source stringlengths 3 92 | c stringlengths 26 2.25M |
|---|---|
raytracer.h | #pragma once
#include "resource.h"
#include <linalg.h>
#include <memory>
#include <omp.h>
#include <random>
#include <time.h>
using namespace linalg::aliases;
namespace cg::renderer
{
struct ray
{
ray(float3 position, float3 direction) : position(position)
{
this->direction = normalize(direction);
}
float3 position;
float3 direction;
};
struct payload
{
float t;
float3 bary;
cg::color color;
};
template<typename VB>
struct triangle
{
triangle(const VB& vertex_a, const VB& vertex_b, const VB& vertex_c);
float3 a;
float3 b;
float3 c;
float3 ba;
float3 ca;
float3 na;
float3 nb;
float3 nc;
float3 ambient;
float3 diffuse;
float3 emissive;
};
template<typename VB>
inline triangle<VB>::triangle(const VB& vertex_a, const VB& vertex_b, const VB& vertex_c)
{
a = float3{ vertex_a.x, vertex_a.y, vertex_a.z };
b = float3{ vertex_b.x, vertex_b.y, vertex_b.z };
c = float3{ vertex_c.x, vertex_c.y, vertex_c.z };
ba = b - a;
ca = c - a;
na = float3{ vertex_a.nx, vertex_a.ny, vertex_a.nz };
nb = float3{ vertex_b.nx, vertex_b.ny, vertex_b.nz };
nc = float3{ vertex_c.nx, vertex_c.ny, vertex_c.nz };
ambient = {
vertex_a.ambient_r,
vertex_a.ambient_g,
vertex_a.ambient_b,
};
diffuse = {
vertex_a.diffuse_r,
vertex_a.diffuse_g,
vertex_a.diffuse_b,
};
emissive = {
vertex_a.emissive_r,
vertex_a.emissive_g,
vertex_a.emissive_b,
};
}
template<typename VB>
class aabb
{
public:
void add_triangle(const triangle<VB> triangle);
const std::vector<triangle<VB>>& get_traingles() const;
bool aabb_test(const ray& ray) const;
protected:
std::vector<triangle<VB>> triangles;
float3 aabb_min;
float3 aabb_max;
};
struct light
{
float3 position;
float3 color;
};
template<typename VB, typename RT>
class raytracer
{
public:
raytracer(){};
~raytracer(){};
void set_render_target(std::shared_ptr<resource<RT>> in_render_target);
void clear_render_target(const RT& in_clear_value);
void set_viewport(size_t in_width, size_t in_height);
void set_per_shape_vertex_buffer(
std::vector<std::shared_ptr<cg::resource<VB>>> in_per_shape_vertex_buffer);
void build_acceleration_structure();
std::vector<aabb<VB>> acceleration_structures;
void ray_generation(float3 position, float3 direction, float3 right, float3 up, float frame_weight);
payload trace_ray(const ray& ray, size_t depth, float max_t = 1000.f, float min_t = 0.001f) const;
payload intersection_shader(const triangle<VB>& triangle, const ray& ray) const;
std::function<payload(const ray& ray)> miss_shader = nullptr;
std::function<payload(const ray& ray, payload& payload, const triangle<VB>& triangle, size_t depth)> closest_hit_shader =
nullptr;
std::function<payload(const ray& ray, payload& payload, const triangle<VB>& triangle)> any_hit_shader =
nullptr;
float get_random(const int thread_num, float range = 0.1f) const;
protected:
std::shared_ptr<cg::resource<RT>> render_target;
std::vector<std::shared_ptr<cg::resource<VB>>> per_shape_vertex_buffer;
size_t width = 1920;
size_t height = 1080;
};
template<typename VB, typename RT>
inline void raytracer<VB, RT>::set_render_target(std::shared_ptr<resource<RT>> in_render_target)
{
render_target = in_render_target;
}
template<typename VB, typename RT>
inline void raytracer<VB, RT>::clear_render_target(const RT& in_clear_value)
{
for (size_t i = 0; i < render_target->get_number_of_elements(); i++)
{
render_target->item(i) = in_clear_value;
}
}
template<typename VB, typename RT>
inline void raytracer<VB, RT>::set_per_shape_vertex_buffer(
std::vector<std::shared_ptr<cg::resource<VB>>> in_per_shape_vertex_buffer)
{
per_shape_vertex_buffer = in_per_shape_vertex_buffer;
}
template<typename VB, typename RT>
inline void raytracer<VB, RT>::build_acceleration_structure()
{
for (auto& vertex_buffer : per_shape_vertex_buffer)
{
size_t vertex_id = 0;
aabb<VB> aabb;
while (vertex_id < vertex_buffer->get_number_of_elements())
{
triangle<VB> triangle(
vertex_buffer->item(vertex_id++), vertex_buffer->item(vertex_id++),
vertex_buffer->item(vertex_id++));
aabb.add_triangle(triangle);
}
acceleration_structures.push_back(aabb);
}
}
template<typename VB, typename RT>
inline void raytracer<VB, RT>::set_viewport(size_t in_width, size_t in_height)
{
width = in_width;
height = in_height;
}
template<typename VB, typename RT>
inline void raytracer<VB, RT>::ray_generation(
float3 position, float3 direction, float3 right, float3 up, float frame_weight = 1)
{
for (int x = 0; x < width;x++)
{
#pragma omp parallel for
for (int y = 0; y < height; y++)
{
float x_jitter = get_random(omp_get_thread_num() + clock());
float y_jitter = get_random(omp_get_thread_num() + clock());
// [0; width - 1]
// [-1; 1]
float u = (2.f * x + x_jitter) / static_cast<float>(width - 1) - 1.f;
u *= static_cast<float>(width) / static_cast<float>(height);
float v = (2.f * y + y_jitter) / static_cast<float>(height - 1) - 1.f;
/*float u_delta = 0.5f / static_cast<float>(width - 1);
u_delta *= static_cast<float>(width) / static_cast<float>(height);
float v_delta = 0.5f / static_cast<float>(height - 1);*/
float3 ray_direction =
direction + (u) * right - (v) * up;
ray ray_0(position, ray_direction);
payload payload_0 = trace_ray(ray_0, 3);
cg::color accumed =
cg::color::from_float3(render_target->item(x, y).to_float3());
cg::color result{
accumed.r * (1.f - frame_weight) + payload_0.color.r * frame_weight,
accumed.g * (1.f - frame_weight) + payload_0.color.g * frame_weight,
accumed.b * (1.f - frame_weight) + payload_0.color.b * frame_weight
};
/*ray ray_1(position, ray_direction + u_delta * right);
payload payload_1 = trace_ray(ray_1, 3);
ray ray_2(position, ray_direction - v_delta * up);
payload payload_2 = trace_ray(ray_2, 3);
ray ray_3(position, ray_direction + u_delta * right - v_delta * up);
payload payload_3 = trace_ray(ray_3, 3);
cg::color accumed_color{
(payload_0.color.r + payload_1.color.r + payload_2.color.r +
payload_3.color.r) /
4.f,
(payload_0.color.g + payload_1.color.g + payload_2.color.g +
payload_3.color.g) /
4.f,
(payload_0.color.b + payload_1.color.b + payload_2.color.b +
payload_3.color.b) /
4.f,
};*/
render_target->item(x, y) = RT::from_color(result);
}
}
}
template<typename VB, typename RT>
inline payload
raytracer<VB, RT>::trace_ray(const ray& ray, size_t depth, float max_t, float min_t) const
{
if (depth == 0)
return miss_shader(ray);
depth--;
payload closest_hit_payload = {};
closest_hit_payload.t = max_t;
const triangle<VB>* closest_triangle = NULL;
for (auto& aabb: acceleration_structures)
{
if (aabb.aabb_test(ray))
{
for (auto& triangle : aabb.get_traingles())
{
payload payload = intersection_shader(triangle, ray);
if (payload.t > min_t && payload.t < closest_hit_payload.t)
{
closest_hit_payload = payload;
closest_triangle = ▵
if (any_hit_shader)
return any_hit_shader(ray, payload, triangle);
}
}
}
}
if (closest_hit_payload.t < max_t)
{
if (closest_hit_shader)
return closest_hit_shader(ray, closest_hit_payload, *closest_triangle, depth);
}
return miss_shader(ray);
}
template<typename VB, typename RT>
inline payload
raytracer<VB, RT>::intersection_shader(const triangle<VB>& triangle, const ray& ray) const
{
payload payload{};
payload.t = -1.f;
float3 pvec = cross(ray.direction, triangle.ca);
float det = dot(triangle.ba, pvec);
if (det > -1e-8 && det < 1e-8)
return payload;
float inv_det = 1.f / det;
float3 tvec = ray.position - triangle.a;
float u = dot(tvec, pvec) * inv_det;
if (u < 0.f || u > 1.f)
return payload;
float3 qvec = cross(tvec, triangle.ba);
float v = dot(ray.direction, qvec) * inv_det;
if (v < 0.f || u + v > 1.f)
return payload;
payload.t = dot(triangle.ca, qvec) * inv_det;
payload.bary = float3{1.f - u - v, u, v};
return payload;
}
template<typename VB, typename RT>
inline float raytracer<VB, RT>::get_random(const int thread_num, const float range) const
{
static std::default_random_engine generator(thread_num);
static std::normal_distribution<float> distribution(0.f, range);
return distribution(generator);
}
template<typename VB>
inline void aabb<VB>::add_triangle(const triangle<VB> triangle)
{
if (triangles.empty())
aabb_max = aabb_min = triangle.a;
triangles.push_back(triangle);
aabb_max = max(triangle.a, aabb_max);
aabb_max = max(triangle.b, aabb_max);
aabb_max = max(triangle.c, aabb_max);
aabb_min = min(triangle.a, aabb_min);
aabb_min = min(triangle.b, aabb_min);
aabb_min = min(triangle.c, aabb_min);
}
template<typename VB>
inline const std::vector<triangle<VB>>& aabb<VB>::get_traingles() const
{
return triangles;
}
template<typename VB>
inline bool aabb<VB>::aabb_test(const ray& ray) const
{
float3 invRaydir = float3(1.f) / ray.direction;
float3 t0 = (aabb_max - ray.position) * invRaydir;
float3 t1 = (aabb_min - ray.position) * invRaydir;
float3 tmin = min(t0, t1);
float3 tmax = max(t0, t1);
return maxelem(tmin) <= minelem(tmax);
}
} // namespace cg::renderer |
ex7.c | #include <stdio.h>
#include <stdlib.h>
#include <omp.h>
#include "timer.h"
int main(int argc, char **argv)
{
const long N = 10000;
const long M = 1000000;
double tempo, fim, inicio;
int i, j, cont, T;
T = atoi(argv[1]);
GET_TIME(inicio);
for (i = 0; i < N; i++)
#pragma omp parallel for num_threads(T) private(i,j,cont)
for(j = 0; j < M; j++)
cont = cont + 1;
GET_TIME(fim);
tempo = fim - inicio;
printf("Tempo: %.8lf\n", tempo);
return 0;
}
|
THTensorConv.c | #ifndef TH_GENERIC_FILE
#define TH_GENERIC_FILE "generic/THTensorConv.c"
#else
/*
2D Input, 2D kernel : convolve given image with the given kernel.
*/
TH_API void THTensor_(validXCorr2Dptr)(real *r_,
real alpha,
real *t_, long ir, long ic,
real *k_, long kr, long kc,
long sr, long sc)
{
long or = (ir - kr) / sr + 1;
long oc = (ic - kc) / sc + 1;
long xx, yy, kx, ky;
if ((sc != 1) || (oc < 4)) {
// regular convolution
for(yy = 0; yy < or; yy++) {
for(xx = 0; xx < oc; xx++) {
/* Dot product in two dimensions... (between input image and the mask) */
real *pi_ = t_ + yy*sr*ic + xx*sc;
real *pw_ = k_;
real sum = 0;
for(ky = 0; ky < kr; ky++) {
for(kx = 0; kx < kc; kx++) {
sum += pi_[kx]*pw_[kx];
}
pi_ += ic; /* next input line */
pw_ += kc; /* next mask line */
}
/* Update output */
*r_++ += alpha*sum;
}
}
} else {
// SSE-based convolution
for(yy = 0; yy < or; yy++) {
real *pi_ = t_ + yy*sr*ic;
real *pw_ = k_;
for (ky = 0; ky < kr; ky++) {
real *pis_ = pi_;
for (kx = 0; kx < kc; kx++) {
THVector_(add)(r_, pis_, alpha*pw_[kx], oc);
pis_++;
}
pi_ += ic; /* next input line */
pw_ += kc; /* next mask line */
}
r_ += oc;
}
}
}
/*
2D Input, 2D kernel : convolve given image with the given kernel.
*/
TH_API void THTensor_(validConv2Dptr)(real *r_,
real alpha,
real *t_, long ir, long ic,
real *k_, long kr, long kc,
long sr, long sc)
{
long or = (ir - kr) / sr + 1;
long oc = (ic - kc) / sc + 1;
long xx, yy, kx, ky;
if ((sc != 1) || (oc < 4)) {
// regular convolution
for(yy = 0; yy < or; yy++) {
for(xx = 0; xx < oc; xx++) {
/* Dot product in two dimensions... (between input image and the mask) */
real *pi_ = t_ + yy*sr*ic + xx*sc;
real *pw_ = k_ + kr*kc - 1;
real sum = 0;
for(ky = 0; ky < kr; ky++) {
for(kx = 0; kx < kc; kx++) {
sum += pi_[kx]*pw_[-kx];
}
pi_ += ic; /* next input line */
pw_ -= kc; /* next mask line */
}
/* Update output */
*r_++ += alpha*sum;
}
}
} else {
// SSE-based convolution
for(yy = 0; yy < or; yy++) {
real *pw_ = k_ + kr*kc - 1;
real *pi_ = t_ + yy*sr*ic;
for (ky = 0; ky < kr; ky++) {
real *pis_ = pi_;
for (kx = 0; kx < kc; kx++) {
THVector_(add)(r_, pis_, alpha*pw_[-kx], oc);
pis_++;
}
pi_ += ic; /* next input line */
pw_ -= kc; /* next mask line */
}
r_ += oc;
}
}
}
/*
2D Input, 2D kernel : convolve given image with the given kernel, full convolution.
*/
TH_API void THTensor_(fullConv2Dptr)(real *r_,
real alpha,
real *t_, long ir, long ic,
real *k_, long kr, long kc,
long sr, long sc)
{
long oc = (ic - 1) * sc + kc;
long xx, yy, kx, ky;
if ((sc != 1) || (ic < 4)) {
// regular convolution
for(yy = 0; yy < ir; yy++) {
for(xx = 0; xx < ic; xx++) {
/* Outer product in two dimensions... (between input image and the mask) */
real *po_ = r_ + yy*sr*oc + xx*sc;
real *pw_ = k_;
for(ky = 0; ky < kr; ky++)
{
real z = *t_ * alpha;
for(kx = 0; kx < kc; kx++) {
po_[kx] += z * pw_[kx];
}
po_ += oc; /* next input line */
pw_ += kc; /* next mask line */
}
t_++;
}
}
} else {
// SSE-based convolution
for(yy = 0; yy < ir; yy++) {
real *po_ = r_ + yy*sr*oc;
real *pw_ = k_;
for (ky = 0; ky < kr; ky++) {
real *pos_ = po_;
for (kx = 0; kx < kc; kx++) {
THVector_(add)(pos_, t_, alpha*pw_[kx], ic);
pos_++;
}
po_ += oc; /* next input line */
pw_ += kc; /* next mask line */
}
t_ += ic;
}
}
}
/*
2D Input, 2D kernel : convolve given image with the given kernel, full convolution.
*/
TH_API void THTensor_(fullXCorr2Dptr)(real *r_,
real alpha,
real *t_, long ir, long ic,
real *k_, long kr, long kc,
long sr, long sc)
{
long oc = (ic - 1) * sc + kc;
long xx, yy, kx, ky;
if ((sc != 1) || (ic < 4)) {
// regular convolution
for(yy = 0; yy < ir; yy++) {
for(xx = 0; xx < ic; xx++) {
/* Outer product in two dimensions... (between input image and the mask) */
real *po_ = r_ + yy*sr*oc + xx*sc;
real *pw_ = k_ + kr*kc -1;
long kx, ky;
for(ky = 0; ky < kr; ky++)
{
real z = *t_ * alpha;
for(kx = 0; kx < kc; kx++) {
po_[kx] += z * pw_[-kx];
}
po_ += oc; /* next input line */
pw_ -= kc; /* next mask line */
}
t_++;
}
}
} else {
// SSE-based convolution
for(yy = 0; yy < ir; yy++) {
real *po_ = r_ + yy*sr*oc;
real *pw_ = k_ + kr*kc -1;
for (ky = 0; ky < kr; ky++) {
real *pos_ = po_;
for (kx = 0; kx < kc; kx++) {
THVector_(add)(pos_, t_, pw_[-kx]*alpha, ic);
pos_++;
}
po_ += oc; /* next input line */
pw_ -= kc; /* next mask line */
}
t_ += ic;
}
}
}
/*
2D Input, 2D kernel : convolve given image with the given kernel, valid convolution.
for sr,sc=1 this is equivalent to validXCorr2Dptr, but otherwise it is useful for
calculating derivatives wrt a kernel that is applied with stride sr,sc != 1
*/
TH_API void THTensor_(validXCorr2DRevptr)(real *r_,
real alpha,
real *t_, long ir, long ic,
real *k_, long kr, long kc,
long sr, long sc)
{
long or = ir - (kr - 1) * sr;
long oc = ic - (kc - 1) * sc;
long xx, yy, kx, ky;
if ((sc != 1) || (kc < 4)) {
// regular convolution
for(yy = 0; yy < kr; yy++) {
for(xx = 0; xx < kc; xx++) {
real *po_ = r_;
real *pi_ = t_ + yy*sr*ic + xx*sc;
real z = *k_++ * alpha;
for(ky = 0; ky < or; ky++) {
for(kx = 0; kx < oc; kx++)
po_[kx] += z * pi_[kx];
pi_ += ic;
po_ += oc;
}
}
}
} else {
// SSE-based convolution
for(yy = 0; yy < kr; yy++) {
for(xx = 0; xx < kc; xx++) {
real *po_ = r_;
real *pi_ = t_ + yy*sr*ic + xx*sc;
real z = *k_++ * alpha;
for(ky = 0; ky < or; ky++) {
THVector_(add)(po_, pi_, z, oc);
pi_ += ic;
po_ += oc;
}
}
}
}
}
/*
3D Input, 3D kernel : convolve given volume with the given kernel.
*/
TH_API void THTensor_(validXCorr3Dptr)(real *r_,
real alpha,
real *t_, long it, long ir, long ic,
real *k_, long kt, long kr, long kc,
long st, long sr, long sc)
{
long ot = (it - kt) / st + 1;
long or = (ir - kr) / sr + 1;
long oc = (ic - kc) / sc + 1;
long zz, xx, yy;
for (zz = 0; zz < ot; zz++)
{
for(yy = 0; yy < or; yy++)
{
for(xx = 0; xx < oc; xx++)
{
/* Dot product in two dimensions... (between input image and the mask) */
real *pi_ = t_ + zz*st*ir*ic + yy*sr*ic + xx*sc;
real *pw_ = k_;
real sum = 0;
long kz, kx, ky;
for(kz = 0; kz < kt; kz++)
{
for(ky = 0; ky < kr; ky++)
{
for(kx = 0; kx < kc; kx++) {
sum += pi_[kx]*pw_[kx];
}
pi_ += ic; /* next input line */
pw_ += kc; /* next mask line */
}
}
/* Update output */
*r_++ += sum*alpha;
}
}
}
}
/*
3D Input, 3D kernel : convolve given volume with the given kernel.
*/
TH_API void THTensor_(validConv3Dptr)(real *r_,
real alpha,
real *t_, long it, long ir, long ic,
real *k_, long kt, long kr, long kc,
long st, long sr, long sc)
{
long ot = (it - kt) / st + 1;
long or = (ir - kr) / sr + 1;
long oc = (ic - kc) / sc + 1;
long zz, xx, yy;
for(zz = 0; zz < ot; zz++)
{
for(yy = 0; yy < or; yy++)
{
for(xx = 0; xx < oc; xx++)
{
/* Dot product in two dimensions... (between input image and the mask) */
real *pi_ = t_ + zz*st*ir*ic + yy*sr*ic + xx*sc;
real *pw_ = k_ + kt*kr*kc - 1;
real sum = 0;
long kz, kx, ky;
for(kz = 0; kz < kt; kz++)
{
for(ky = 0; ky < kr; ky++)
{
for(kx = 0; kx < kc; kx++) {
sum += pi_[kx]*pw_[-kx];
}
pi_ += ic; /* next input line */
pw_ -= kc; /* next mask line */
}
}
/* Update output */
*r_++ += alpha*sum;
}
}
}
}
/*
3D Input, 3D kernel : convolve given volume with the given kernel, full convolution.
*/
TH_API void THTensor_(fullConv3Dptr)(real *r_,
real alpha,
real *t_, long it, long ir, long ic,
real *k_, long kt, long kr, long kc,
long st, long sr, long sc)
{
long or = (ir - 1) * sr + kr;
long oc = (ic - 1) * sc + kc;
long zz, xx, yy;
for(zz = 0; zz < it; zz++)
{
for(yy = 0; yy < ir; yy++)
{
for(xx = 0; xx < ic; xx++)
{
/* Outer product in two dimensions... (between input image and the mask) */
real *po_ = r_ + zz*st*or*oc + yy*sr*oc + xx*sc;
real *pw_ = k_;
long kz, kx, ky;
//printf("Output Plane : %ld,%ld,%ld, input val=%g\n",zz,yy,xx,*t_);
for(kz = 0; kz < kt; kz++)
{
for(ky = 0; ky < kr; ky++)
{
real z = *t_ * alpha;
for(kx = 0; kx < kc; kx++) {
//printf("o=%g,k=%g," , po_[kx],pw_[kx]);
po_[kx] += z * pw_[kx];
//printf("o=%g " , po_[kx]);
}
//printf("\n");
po_ += oc; /* next input line */
pw_ += kc; /* next mask line */
}
//printf("\n");
}
t_++;
}
}
}
}
/*
3D Input, 3D kernel : convolve given volume with the given kernel, full convolution.
*/
TH_API void THTensor_(fullXCorr3Dptr)(real *r_,
real alpha,
real *t_, long it, long ir, long ic,
real *k_, long kt, long kr, long kc,
long st, long sr, long sc)
{
long or = (ir - 1) * sr + kr;
long oc = (ic - 1) * sc + kc;
long zz, xx, yy;
for(zz = 0; zz < it; zz++)
{
for(yy = 0; yy < ir; yy++)
{
for(xx = 0; xx < ic; xx++)
{
/* Outer product in two dimensions... (between input image and the mask) */
real *po_ = r_ + zz*st*or*oc + yy*sr*oc + xx*sc;
real *pw_ = k_ + kt*kr*kc -1;
long kz, kx, ky;
for(kz = 0; kz < kt; kz++)
{
for(ky = 0; ky < kr; ky++)
{
real z = *t_ * alpha;
for(kx = 0; kx < kc; kx++) {
po_[kx] += z * pw_[-kx];
}
po_ += oc; /* next input line */
pw_ -= kc; /* next mask line */
}
}
t_++;
}
}
}
}
/*
3D Input, 3D kernel : convolve given image with the given kernel, valid convolution.
for sr,sc=1 this is equivalent to validXCorr3Dptr, but otherwise it is useful for
calculating derivatives wrt a kernel that is applied with stride sr,sc != 1
*/
TH_API void THTensor_(validXCorr3DRevptr)(real *r_,
real alpha,
real *t_, long it, long ir, long ic,
real *k_, long kt, long kr, long kc,
long st, long sr, long sc)
{
long ot = it - (kt - 1) * st;
long or = ir - (kr - 1) * sr;
long oc = ic - (kc - 1) * sc;
long zz, xx, yy;
for(zz = 0; zz < kt; zz++)
{
for(yy = 0; yy < kr; yy++)
{
for(xx = 0; xx < kc; xx++)
{
real *po_ = r_;
real *pi_ = t_ + zz*st*ir*ic + yy*sr*ic + xx*sc;
real z = *k_++ * alpha;
long kz, kx, ky;
for(kz = 0; kz < ot; kz++)
{
for(ky = 0; ky < or; ky++)
{
for(kx = 0; kx < oc; kx++)
po_[kx] += z * pi_[kx];
pi_ += ic;
po_ += oc;
}
}
}
}
}
}
void THTensor_(conv2d)(real* output_data,
real alpha,
real* ptr_input, long nInputRows, long nInputCols,
real* ptr_weight, long nKernelRows, long nKernelCols,
long srow, long scol,
const char *vf, const char *xc)
{
THArgCheck(*vf == 'V' || *vf == 'F', 7, "type of convolution can be 'V' or 'F'");
THArgCheck(*xc == 'C' || *xc == 'X', 7, "type of convolution can be 'X' or 'C'");
if (*vf == 'F')
if (*xc == 'X')
THTensor_(fullXCorr2Dptr)(output_data,
alpha,
ptr_input, nInputRows, nInputCols,
ptr_weight, nKernelRows, nKernelCols,
srow, scol);
else
THTensor_(fullConv2Dptr)(output_data,
alpha,
ptr_input, nInputRows, nInputCols,
ptr_weight, nKernelRows, nKernelCols,
srow, scol);
else
if (*xc == 'X')
THTensor_(validXCorr2Dptr)(output_data,
alpha,
ptr_input, nInputRows, nInputCols,
ptr_weight, nKernelRows, nKernelCols,
srow, scol);
else
THTensor_(validConv2Dptr)(output_data,
alpha,
ptr_input, nInputRows, nInputCols,
ptr_weight, nKernelRows, nKernelCols,
srow, scol);
}
void THTensor_(conv3d)(real* output_data,
real alpha,
real* ptr_input, long nInputDepth, long nInputRows, long nInputCols,
real* ptr_weight, long nKernelDepth, long nKernelRows, long nKernelCols,
long sdepth, long srow, long scol,
const char *vf, const char *xc)
{
THArgCheck(*vf == 'V' || *vf == 'F', 7, "type of convolution can be 'V' or 'F'");
THArgCheck(*xc == 'C' || *xc == 'X', 7, "type of convolution can be 'X' or 'C'");
if (*vf == 'F')
if (*xc == 'X')
THTensor_(fullXCorr3Dptr)(output_data,
alpha,
ptr_input, nInputDepth, nInputRows, nInputCols,
ptr_weight, nKernelDepth, nKernelRows, nKernelCols,
sdepth, srow, scol);
else
THTensor_(fullConv3Dptr)(output_data,
alpha,
ptr_input, nInputDepth, nInputRows, nInputCols,
ptr_weight, nKernelDepth, nKernelRows, nKernelCols,
sdepth, srow, scol);
else
if (*xc == 'X')
THTensor_(validXCorr3Dptr)(output_data,
alpha,
ptr_input, nInputDepth, nInputRows, nInputCols,
ptr_weight, nKernelDepth, nKernelRows, nKernelCols,
sdepth, srow, scol);
else
THTensor_(validConv3Dptr)(output_data,
alpha,
ptr_input, nInputDepth, nInputRows, nInputCols,
ptr_weight, nKernelDepth, nKernelRows, nKernelCols,
sdepth, srow, scol);
}
long THTensor_(convsize)(long x, long k, long s, const char* vf)
{
THArgCheck(*vf == 'V' || *vf == 'F', 1, "type of convolution can be 'V' or 'F'");
if (*vf == 'V')
return (x-k)/s + 1;
else
return (x-1)*s + k;
}
/*
3D input, 3D kernel, 4D output
like rank1 update
A <- xx' + beta*A
for sr,sc=1 this is equivalent to conv2Dger, but otherwise it is useful for
calculating derivatives wrt a kernel that is applied with stride sr,sc != 1
*/
void THTensor_(conv2DRevger)(THTensor *r_, real beta, real alpha, THTensor *t_, THTensor *k_, long srow, long scol)
{
long nInputPlane, nInputRows, nInputCols;
long nKernelPlane, nKernelRows, nKernelCols;
long nOutputPlane, nOutputRows, nOutputCols;
long istride0, kstride0;
THArgCheck(t_->nDimension == 3 , 3, "input: 3D Tensor expected");
THArgCheck(k_->nDimension == 3 , 4, "kernel: 3D Tensor expected");
THArgCheck(srow >= 1, 5, "Stride should be a positive integer");
THArgCheck(scol >= 1, 6, "Stride should be a positive integer");
THTensor *input = THTensor_(newContiguous)(t_);
THTensor *kernel = THTensor_(newContiguous)(k_);
nInputPlane = input->size[0];
istride0 = input->stride[0];
nInputRows = input->size[1];
nInputCols = input->size[2];
kstride0 = kernel->stride[0];
nKernelPlane = kernel->size[0];
nKernelRows = kernel->size[1];
nKernelCols = kernel->size[2];
nOutputPlane = nInputPlane * kernel->size[0];
THArgCheck(nInputRows >= nKernelRows && nInputCols >= nKernelCols , 2, "covn2DRevger : Input image is smaller than kernel");
nOutputRows = nInputRows - (nKernelRows - 1) * srow;
nOutputCols = nInputCols - (nKernelCols - 1) * scol;
long nelem = THTensor_(nElement)(r_);
THTensor_(resize4d)(r_,nKernelPlane, nInputPlane, nOutputRows, nOutputCols);
real *input_data = THTensor_(data)(input);
real *weight_data = THTensor_(data)(kernel);
real *output_data = THTensor_(data)(r_);
if (nelem == 0 || beta == 0 || nelem != THTensor_(nElement)(r_))
{
/*THTensor_(zero)(r_);*/
long k;
#pragma omp parallel for private(k)
for (k = 0; k < r_->size[0]*r_->size[1]; k++)
{
real* ptr_output = output_data + k*nOutputCols*nOutputRows;
long l;
for (l = 0; l < nOutputRows*nOutputCols; l++)
ptr_output[l] = 0.0;
}
}
else if (beta != 1)
{
/*THTensor_(mul)(r_, beta);*/
long k;
#pragma omp parallel for private(k)
for (k = 0; k < r_->size[0]*r_->size[1]; k++)
{
real* ptr_output = output_data + k*nOutputCols*nOutputRows;
long l;
for (l = 0; l < nOutputRows*nOutputCols; l++)
ptr_output[l] *= beta;
}
}
long k;
#pragma omp parallel for private(k)
for(k = 0; k < nKernelPlane; k++)
{
long i;
/* get kernel */
real *ptr_weight = weight_data+k*kstride0;
for(i = 0; i < nInputPlane; i++)
{
/* get output */
real *ptr_output = output_data + k*nInputPlane*nOutputCols*nOutputRows + i*nOutputCols*nOutputRows;
/* get input */
real *ptr_input = input_data+i*istride0;
/* do image, kernel convolution */
THTensor_(validXCorr2DRevptr)(ptr_output,
alpha,
ptr_input, nInputRows, nInputCols,
ptr_weight, nKernelRows, nKernelCols,
srow, scol);
/* Next output plane */
/* output_data += nOutputCols*nOutputRows; */
}
}
THTensor_(free)(input);
THTensor_(free)(kernel);
}
/*
3D input, 3D kernel, 4D output
like rank1 update
A <- xx' + beta*A
for sr,sc=1 this is equivalent to conv2Dger, but otherwise it is useful for
calculating derivatives wrt a kernel that is applied with stride sr,sc != 1
*/
void THTensor_(conv2DRevgerm)(THTensor *r_, real beta, real alpha, THTensor *t_, THTensor *k_, long srow, long scol)
{
long nbatch, nInputPlane, nInputRows, nInputCols;
long nKernelPlane, nKernelRows, nKernelCols;
long nOutputRows, nOutputCols;
long istride0, kstride0, istride1, kstride1;
THArgCheck(t_->nDimension == 4 , 3, "input: 4D Tensor expected");
THArgCheck(k_->nDimension == 4 , 4, "kernel: 4D Tensor expected");
THArgCheck(srow >= 1, 5, "Stride should be a positive integer");
THArgCheck(scol >= 1, 6, "Stride should be a positive integer");
THTensor *input = THTensor_(newContiguous)(t_);
THTensor *kernel = THTensor_(newContiguous)(k_);
istride0 = input->stride[0];
istride1 = input->stride[1];
nbatch = input->size[0];
nInputPlane = input->size[1];
nInputRows = input->size[2];
nInputCols = input->size[3];
kstride0 = kernel->stride[0];
kstride1 = kernel->stride[1];
nKernelPlane = kernel->size[1];
nKernelRows = kernel->size[2];
nKernelCols = kernel->size[3];
THArgCheck(nInputRows >= nKernelRows && nInputCols >= nKernelCols , 2, "conv2DRevger : Input image is smaller than kernel");
THArgCheck(kernel->size[0] == input->size[0] , 2, "conv2DRevger : Input batch and kernel batch is not same size");
nOutputRows = nInputRows - (nKernelRows - 1) * srow;
nOutputCols = nInputCols - (nKernelCols - 1) * scol;
long nelem = THTensor_(nElement)(r_);
THTensor_(resize4d)(r_,nKernelPlane, nInputPlane, nOutputRows, nOutputCols);
real *input_data = THTensor_(data)(input);
real *weight_data = THTensor_(data)(kernel);
real *output_data = THTensor_(data)(r_);
if (nelem == 0 || beta == 0 || nelem != THTensor_(nElement)(r_))
{
/*THTensor_(zero)(r_);*/
long k;
#pragma omp parallel for private(k)
for (k = 0; k < r_->size[0]*r_->size[1]; k++)
{
real* ptr_output = output_data + k*nOutputCols*nOutputRows;
long l;
for (l = 0; l < nOutputRows*nOutputCols; l++)
ptr_output[l] = 0.0;
}
}
else if (beta != 1)
{
/*THTensor_(mul)(r_, beta);*/
long k;
#pragma omp parallel for private(k)
for (k = 0; k < r_->size[0]*r_->size[1]; k++)
{
real* ptr_output = output_data + k*nOutputCols*nOutputRows;
long l;
for (l = 0; l < nOutputRows*nOutputCols; l++)
ptr_output[l] *= beta;
}
}
long k;
#pragma omp parallel for private(k)
for(k = 0; k < nKernelPlane; k++)
{
long i;
for(i = 0; i < nInputPlane; i++)
{
long p;
for(p = 0; p < nbatch; p++)
{
/* get kernel */
real *ptr_weight = weight_data + p*kstride0 + k*kstride1;
/* get output */
real *ptr_output = output_data + k*nInputPlane*nOutputCols*nOutputRows + i*nOutputCols*nOutputRows;
/* get input */
real *ptr_input = input_data + p*istride0 + i*istride1;
/* do image, kernel convolution */
THTensor_(validXCorr2DRevptr)(ptr_output,
alpha,
ptr_input, nInputRows, nInputCols,
ptr_weight, nKernelRows, nKernelCols,
srow, scol);
/* Next output plane */
/* output_data += nOutputCols*nOutputRows; */
}
}
}
THTensor_(free)(input);
THTensor_(free)(kernel);
}
/*
3D input, 3D kernel, 4D output
like rank1 update
A <- xx' + beta*A
*/
void THTensor_(conv2Dger)(THTensor *r_, real beta, real alpha, THTensor *t_, THTensor *k_, long srow, long scol, const char *vf, const char *xc)
{
long nInputPlane, nInputRows, nInputCols;
long nKernelPlane, nKernelRows, nKernelCols;
long nOutputPlane, nOutputRows, nOutputCols;
long istride0, kstride0;
THArgCheck(t_->nDimension == 3 , 3, "input: 3D Tensor expected");
THArgCheck(k_->nDimension == 3 , 4, "kernel: 3D Tensor expected");
THArgCheck(srow >= 1, 5, "Stride should be a positive integer");
THArgCheck(scol >= 1, 6, "Stride should be a positive integer");
THArgCheck(*vf == 'V' || *vf == 'F', 7, "type of convolution can 'V' or 'F'");
THArgCheck(*xc == 'C' || *xc == 'X', 7, "type of convolution can 'X' or 'C'");
THTensor *input = THTensor_(newContiguous)(t_);
THTensor *kernel = THTensor_(newContiguous)(k_);
nInputPlane = input->size[0];
istride0 = input->stride[0];
nInputRows = input->size[1];
nInputCols = input->size[2];
kstride0 = kernel->stride[0];
nKernelPlane = kernel->size[0];
nKernelRows = kernel->size[1];
nKernelCols = kernel->size[2];
nOutputPlane = nInputPlane * kernel->size[0];
THArgCheck((nInputRows >= nKernelRows && nInputCols >= nKernelCols) || *vf == 'F', 2, "conv2Dger : Input image is smaller than kernel");
if (*vf == 'F') {
nOutputRows = (nInputRows - 1) * srow + nKernelRows;
nOutputCols = (nInputCols - 1) * scol + nKernelCols;
} else { // valid
nOutputRows = (nInputRows - nKernelRows) / srow + 1;
nOutputCols = (nInputCols - nKernelCols) / scol + 1;
}
long nelem = THTensor_(nElement)(r_);
THTensor_(resize4d)(r_, nKernelPlane, nInputPlane, nOutputRows, nOutputCols);
real *input_data = THTensor_(data)(input);
real *weight_data = THTensor_(data)(kernel);
real *output_data = THTensor_(data)(r_);
if (nelem == 0 || beta == 0 || nelem != THTensor_(nElement)(r_))
{
/*THTensor_(zero)(r_);*/
long k;
#pragma omp parallel for private(k)
for (k = 0; k < r_->size[0]*r_->size[1]; k++)
{
real* ptr_output = output_data + k*nOutputCols*nOutputRows;
long l;
for (l = 0; l < nOutputRows*nOutputCols; l++)
ptr_output[l] = 0.0;
}
}
else if (beta != 1)
{
/*THTensor_(mul)(r_, beta);*/
long k;
#pragma omp parallel for private(k)
for (k = 0; k < r_->size[0]*r_->size[1]; k++)
{
real* ptr_output = output_data + k*nOutputCols*nOutputRows;
long l;
for (l = 0; l < nOutputRows*nOutputCols; l++)
ptr_output[l] *= beta;
}
}
long k;
#pragma omp parallel for private(k)
for(k = 0; k < nKernelPlane; k++)
{
long i;
/* get kernel */
real *ptr_weight = weight_data+k*kstride0;
for(i = 0; i < nInputPlane; i++)
{
/* get output */
real *ptr_output = output_data + k*nInputPlane*nOutputCols*nOutputRows + i*nOutputCols*nOutputRows;
/* get input */
real *ptr_input = input_data+i*istride0;
/* do image, kernel convolution */
if (*vf == 'F')
if (*xc == 'X')
THTensor_(fullXCorr2Dptr)(ptr_output,
alpha,
ptr_input, nInputRows, nInputCols,
ptr_weight, nKernelRows, nKernelCols,
srow, scol);
else
THTensor_(fullConv2Dptr)(ptr_output,
alpha,
ptr_input, nInputRows, nInputCols,
ptr_weight, nKernelRows, nKernelCols,
srow, scol);
else
if (*xc == 'X')
THTensor_(validXCorr2Dptr)(ptr_output,
alpha,
ptr_input, nInputRows, nInputCols,
ptr_weight, nKernelRows, nKernelCols,
srow, scol);
else
THTensor_(validConv2Dptr)(ptr_output,
alpha,
ptr_input, nInputRows, nInputCols,
ptr_weight, nKernelRows, nKernelCols,
srow, scol);
/* Next output plane */
/* output_data += nOutputCols*nOutputRows; */
}
}
THTensor_(free)(input);
THTensor_(free)(kernel);
}
/*
3D input, 4D kernel, 3D output
matrix vector product like
y <- Ax + beta*y
*/
void THTensor_(conv2Dmv)(THTensor *r_, real beta, real alpha, THTensor *t_, THTensor *k_, long srow, long scol, const char *vf, const char *xc)
{
long nInputPlane, nInputRows, nInputCols;
long nKernelRows, nKernelCols;
long nOutputPlane, nOutputRows, nOutputCols;
long istride0, kstride0, kstride1;
THArgCheck(t_->nDimension == 3 , 3, "input: 3D Tensor expected");
THArgCheck(k_->nDimension == 4 , 4, "kernel: 4D Tensor expected");
THArgCheck(srow >= 1, 5, "Stride should be a positive integer");
THArgCheck(scol >= 1, 6, "Stride should be a positive integer");
THArgCheck(*vf == 'V' || *vf == 'F', 7, "type of convolution can 'V' or 'F'");
THArgCheck(*xc == 'C' || *xc == 'X', 7, "type of convolution can 'X' or 'C'");
THTensor *input = THTensor_(newContiguous)(t_);
THTensor* kernel;
if (!(k_->stride[3] == 1) || !(k_->stride[2] == k_->size[3])) {
kernel = THTensor_(newContiguous)(k_);
} else {
THTensor_(retain)(k_);
kernel = k_;
}
nInputPlane = input->size[0];
istride0 = input->stride[0];
nInputRows = input->size[1];
nInputCols = input->size[2];
kstride0 = kernel->stride[0];
kstride1 = kernel->stride[1];
nKernelRows = kernel->size[2];
nKernelCols = kernel->size[3];
nOutputPlane = kernel->size[0];
THArgCheck(kernel->size[1] == nInputPlane, 2, "invalid number of input planes");
THArgCheck( (nInputRows >= nKernelRows && nInputCols >= nKernelCols) || *vf == 'F', 2, "conv2Dmv : Input image is smaller than kernel");
if (*vf == 'F') {
nOutputRows = (nInputRows - 1) * srow + nKernelRows;
nOutputCols = (nInputCols - 1) * scol + nKernelCols;
} else { // valid
nOutputRows = (nInputRows - nKernelRows) / srow + 1;
nOutputCols = (nInputCols - nKernelCols) / scol + 1;
}
long nelem = THTensor_(nElement)(r_);
THTensor_(resize3d)(r_, nOutputPlane, nOutputRows, nOutputCols);
real *input_data = THTensor_(data)(input);
real *weight_data = THTensor_(data)(kernel);
real *output_data = THTensor_(data)(r_);
if (nelem == 0 || beta == 0 || nelem != THTensor_(nElement)(r_))
{
/*THTensor_(zero)(r_);*/
long k;
#pragma omp parallel for private(k)
for (k = 0; k < r_->size[0]; k++)
{
real* ptr_output = output_data + k*nOutputCols*nOutputRows;
long l;
for (l = 0; l < nOutputRows*nOutputCols; l++)
ptr_output[l] = 0.0;
}
}
else if (beta != 1)
{
/*THTensor_(mul)(r_, beta);*/
long k;
#pragma omp parallel for private(k)
for (k = 0; k < r_->size[0]; k++)
{
real* ptr_output = output_data + k*nOutputCols*nOutputRows;
long l;
for (l = 0; l < nOutputRows*nOutputCols; l++)
ptr_output[l] *= beta;
}
}
long k;
#pragma omp parallel for private(k)
for(k = 0; k < nOutputPlane; k++)
{
long i;
/* get output */
real *ptr_output = output_data + k*nOutputCols*nOutputRows;
for(i = 0; i < nInputPlane; i++)
{
/* get kernel */
real *ptr_weight = weight_data + k*kstride0 + i*kstride1;
/* get input */
real *ptr_input = input_data + i*istride0;
/* do image, kernel convolution */
if (*vf == 'F')
if (*xc == 'X')
THTensor_(fullXCorr2Dptr)(ptr_output,
alpha,
ptr_input, nInputRows, nInputCols,
ptr_weight, nKernelRows, nKernelCols,
srow, scol);
else
THTensor_(fullConv2Dptr)(ptr_output,
alpha,
ptr_input, nInputRows, nInputCols,
ptr_weight, nKernelRows, nKernelCols,
srow, scol);
else
if (*xc == 'X')
THTensor_(validXCorr2Dptr)(ptr_output,
alpha,
ptr_input, nInputRows, nInputCols,
ptr_weight, nKernelRows, nKernelCols,
srow, scol);
else
THTensor_(validConv2Dptr)(ptr_output,
alpha,
ptr_input, nInputRows, nInputCols,
ptr_weight, nKernelRows, nKernelCols,
srow, scol);
}
/* Next output plane */
/* output_data += nOutputCols*nOutputRows;*/
}
THTensor_(free)(input);
THTensor_(free)(kernel);
}
/*
3D input, 4D kernel, 3D output
matrix vector product like
y <- Ax + beta*y
*/
void THTensor_(conv2Dmm)(THTensor *r_, real beta, real alpha, THTensor *t_, THTensor *k_, long srow, long scol, const char *vf, const char *xc)
{
long nInputPlane, nInputRows, nInputCols;
long nKernelRows, nKernelCols;
long nOutputPlane, nOutputRows, nOutputCols;
long kstride0, kstride1;
THArgCheck(t_->nDimension == 4 , 3, "input: 4D Tensor expected");
THArgCheck(k_->nDimension == 4 , 4, "kernel: 4D Tensor expected");
THArgCheck(srow >= 1, 5, "Stride should be a positive integer");
THArgCheck(scol >= 1, 6, "Stride should be a positive integer");
THArgCheck(*vf == 'V' || *vf == 'F', 7, "type of convolution can 'V' or 'F'");
THArgCheck(*xc == 'C' || *xc == 'X', 7, "type of convolution can 'X' or 'C'");
THTensor *input = THTensor_(newContiguous)(t_);
THTensor* kernel;
if (!(k_->stride[3] == 1) || !(k_->stride[2] == k_->size[3])) {
kernel = THTensor_(newContiguous)(k_);
} else {
THTensor_(retain)(k_);
kernel = k_;
}
long nbatch = input->size[0];
nInputPlane = input->size[1];
nInputRows = input->size[2];
nInputCols = input->size[3];
kstride0 = kernel->stride[0];
kstride1 = kernel->stride[1];
nKernelRows = kernel->size[2];
nKernelCols = kernel->size[3];
nOutputPlane = kernel->size[0];
THArgCheck(kernel->size[1] == nInputPlane, 2, "invalid number of input planes");
THArgCheck( (nInputRows >= nKernelRows && nInputCols >= nKernelCols) || *vf == 'F', 2, "conv2Dmv : Input image is smaller than kernel");
if (*vf == 'F') {
nOutputRows = (nInputRows - 1) * srow + nKernelRows;
nOutputCols = (nInputCols - 1) * scol + nKernelCols;
} else { // valid
nOutputRows = (nInputRows - nKernelRows) / srow + 1;
nOutputCols = (nInputCols - nKernelCols) / scol + 1;
}
long nelem = THTensor_(nElement)(r_);
THTensor_(resize4d)(r_, nbatch, nOutputPlane, nOutputRows, nOutputCols);
real *input_data = THTensor_(data)(input);
real *weight_data = THTensor_(data)(kernel);
real *output_data = THTensor_(data)(r_);
if (nelem == 0 || beta == 0 || nelem != THTensor_(nElement)(r_))
{
/*THTensor_(zero)(r_);*/
long p;
#pragma omp parallel for private(p)
for (p=0; p < r_->size[0]; p++)
{
long k;
for (k = 0; k < r_->size[1]; k++)
{
real* ptr_output = output_data + p*nOutputPlane*nOutputRows*nOutputCols + k*nOutputCols*nOutputRows;
long l;
for (l = 0; l < nOutputRows*nOutputCols; l++)
ptr_output[l] = 0.0;
}
}
}
else if (beta != 1)
{
/*THTensor_(mul)(r_, beta);*/
long p;
#pragma omp parallel for private(p)
for (p=0; p < r_->size[0]; p++)
{
long k;
for (k = 0; k < r_->size[1]; k++)
{
real* ptr_output = output_data + p*nOutputPlane*nOutputRows*nOutputCols + k*nOutputCols*nOutputRows;
long l;
for (l = 0; l < nOutputRows*nOutputCols; l++)
ptr_output[l] *= beta;
}
}
}
long p;
#pragma omp parallel for private(p)
for (p=0; p < nbatch; p++)
{
long k;
for(k = 0; k < nOutputPlane; k++)
{
long i;
/* get output */
real *ptr_output = output_data + p*nOutputPlane*nOutputCols*nOutputRows + k*nOutputCols*nOutputRows;
for(i = 0; i < nInputPlane; i++)
{
/* get kernel */
real *ptr_weight = weight_data + k*kstride0 + i*kstride1;
/* get input */
real *ptr_input = input_data + p*nInputPlane*nInputRows*nInputCols + i*nInputRows*nInputCols;
/* do image, kernel convolution */
if (*vf == 'F')
if (*xc == 'X')
THTensor_(fullXCorr2Dptr)(ptr_output,
alpha,
ptr_input, nInputRows, nInputCols,
ptr_weight, nKernelRows, nKernelCols,
srow, scol);
else
THTensor_(fullConv2Dptr)(ptr_output,
alpha,
ptr_input, nInputRows, nInputCols,
ptr_weight, nKernelRows, nKernelCols,
srow, scol);
else
if (*xc == 'X')
THTensor_(validXCorr2Dptr)(ptr_output,
alpha,
ptr_input, nInputRows, nInputCols,
ptr_weight, nKernelRows, nKernelCols,
srow, scol);
else
THTensor_(validConv2Dptr)(ptr_output,
alpha,
ptr_input, nInputRows, nInputCols,
ptr_weight, nKernelRows, nKernelCols,
srow, scol);
}
/* Next output plane */
/* output_data += nOutputCols*nOutputRows;*/
}
}
THTensor_(free)(input);
THTensor_(free)(kernel);
}
/*
2D input, 2D kernel, 2D output
scalar multiplication like
y <- x*y + beta*y
*/
void THTensor_(conv2Dmul)(THTensor *r_, real beta, real alpha, THTensor *t_, THTensor *k_, long srow, long scol, const char *vf, const char *xc)
{
THArgCheck(t_->nDimension == 2 , 3, "input: 2D Tensor expected");
THArgCheck(k_->nDimension == 2 , 4, "kernel: 2D Tensor expected");
THArgCheck(srow >= 1, 5, "Stride should be a positive integer");
THArgCheck(scol >= 1, 6, "Stride should be a positive integer");
THTensor *input = THTensor_(newContiguous)(t_);
THTensor* kernel = THTensor_(newContiguous)(k_);
long nInputRows = input->size[0];
long nInputCols = input->size[1];
long nKernelRows = kernel->size[0];
long nKernelCols = kernel->size[1];
long nOutputRows, nOutputCols;
THArgCheck((nInputRows >= nKernelRows && nInputCols >= nKernelCols) || *vf == 'F', 2, "conv2Dmul : Input image is smaller than kernel");
nOutputRows = THTensor_(convsize)(nInputRows, nKernelRows, srow, vf);
nOutputCols = THTensor_(convsize)(nInputCols, nKernelCols, scol, vf);
long nelem = THTensor_(nElement)(r_);
THTensor_(resize2d)(r_, nOutputRows, nOutputCols);
if (nelem == 0 || beta == 0 || nelem != THTensor_(nElement)(r_))
THTensor_(zero)(r_);
else if (beta != 1)
THTensor_(mul)(r_, r_, beta);
real *ptr_input = THTensor_(data)(input);
real *ptr_weight = THTensor_(data)(kernel);
real *output_data = THTensor_(data)(r_);
/* do image, kernel convolution */
THTensor_(conv2d)(output_data,
alpha,
ptr_input, nInputRows, nInputCols,
ptr_weight, nKernelRows, nKernelCols,
srow, scol, vf, xc);
THTensor_(free)(input);
THTensor_(free)(kernel);
}
/*
3D input, 3D kernel, 3D output
component wise multiplication like
y <- y.*x + beta*y
*/
void THTensor_(conv2Dcmul)(THTensor *r_, real beta, real alpha, THTensor *t_, THTensor *k_, long srow, long scol, const char *vf, const char *xc)
{
long nInputPlane, nInputRows, nInputCols;
long nKernelRows, nKernelCols;
long nOutputPlane, nOutputRows, nOutputCols;
long istride0, kstride0;
THArgCheck(t_->nDimension == 3 , 3, "input: 3D Tensor expected");
THArgCheck(k_->nDimension == 3 , 4, "kernel: 3D Tensor expected");
THArgCheck(srow >= 1, 5, "Stride should be a positive integer");
THArgCheck(scol >= 1, 6, "Stride should be a positive integer");
THTensor *input = THTensor_(newContiguous)(t_);
THTensor* kernel = THTensor_(newContiguous)(k_);
istride0 = input->stride[0];
nInputPlane = input->size[0];
nInputRows = input->size[1];
nInputCols = input->size[2];
kstride0 = kernel->stride[0];
nOutputPlane = kernel->size[0];
nKernelRows = kernel->size[1];
nKernelCols = kernel->size[2];
THArgCheck(nOutputPlane == nInputPlane, 2, "invalid number of input/kernel planes");
THArgCheck( (nInputRows >= nKernelRows && nInputCols >= nKernelCols) || *vf == 'F', 2, "conv2Dcmul : Input image is smaller than kernel");
nOutputRows = THTensor_(convsize)(nInputRows, nKernelRows, srow, vf);
nOutputCols = THTensor_(convsize)(nInputCols, nKernelCols, scol, vf);
long nelem = THTensor_(nElement)(r_);
THTensor_(resize3d)(r_, nOutputPlane, nOutputRows, nOutputCols);
if (nelem == 0 || beta == 0 || nelem != THTensor_(nElement)(r_))
{
THTensor_(zero)(r_);
}
else if (beta != 1)
THTensor_(mul)(r_, r_, beta);
real *input_data = THTensor_(data)(input);
real *weight_data = THTensor_(data)(kernel);
real *output_data = THTensor_(data)(r_);
long k;
for(k = 0; k < nOutputPlane; k++)
{
/* get kernel */
real *ptr_weight = weight_data + k*kstride0;
/* get input */
real *ptr_input = input_data + k*istride0;
/* do image, kernel convolution */
THTensor_(conv2d)(output_data,
alpha,
ptr_input, nInputRows, nInputCols,
ptr_weight, nKernelRows, nKernelCols,
srow, scol, vf, xc);
/* Next output plane */
output_data += nOutputCols*nOutputRows;
}
THTensor_(free)(input);
THTensor_(free)(kernel);
}
/*
3D input, 3D kernel, 3D output
component wise multiplication like with a permutation map
y <- y.*x + beta*y
*/
void THTensor_(conv2Dmap)(THTensor *r_, real beta, real alpha, THTensor *t_, THTensor *k_, THTensor *map, long srow, long scol, const char *vf, const char *xc)
{
long nInputPlane, nInputRows, nInputCols;
long nKernelRows, nKernelCols;
long nOutputPlane, nOutputRows, nOutputCols;
long istride0, kstride0;
THArgCheck(t_->nDimension == 3 , 3, "input: 3D Tensor expected");
THArgCheck(k_->nDimension == 3 , 4, "kernel: 3D Tensor expected");
THArgCheck(map->nDimension == 2 , 4, "map: 2D Tensor expected");
THArgCheck(srow >= 1, 6, "Stride should be a positive integer");
THArgCheck(scol >= 1, 7, "Stride should be a positive integer");
THTensor *input = THTensor_(newContiguous)(t_);
THTensor* kernel = THTensor_(newContiguous)(k_);
istride0 = input->stride[0];
nInputPlane = input->size[0];
nInputRows = input->size[1];
nInputCols = input->size[2];
kstride0 = kernel->stride[0];
nOutputPlane = kernel->size[0];
nKernelRows = kernel->size[1];
nKernelCols = kernel->size[2];
THArgCheck(nOutputPlane == nInputPlane, 2, "invalid number of input/kernel planes");
THArgCheck( (nInputRows >= nKernelRows && nInputCols >= nKernelCols)
|| *vf == 'F', 2, "conv2Dmap : Input image is smaller than kernel");
nOutputRows = THTensor_(convsize)(nInputRows, nKernelRows, srow, vf);
nOutputCols = THTensor_(convsize)(nInputCols, nKernelCols, scol, vf);
long nelem = THTensor_(nElement)(r_);
THTensor_(resize3d)(r_, nOutputPlane, nOutputRows, nOutputCols);
if (nelem == 0 || beta == 0 || nelem != THTensor_(nElement)(r_))
{
THTensor_(zero)(r_);
}
else if (beta != 1)
THTensor_(mul)(r_, r_, beta);
real *input_data = THTensor_(data)(input);
real *weight_data = THTensor_(data)(kernel);
real *output_data = THTensor_(data)(r_);
long nmaps = map->size[0];
long k;
for(k = 0; k < nmaps; k++)
{
/* get indices */
long from = (long)THTensor_(get2d)(map,k,0)-1;
long to = (long)THTensor_(get2d)(map,k,1)-1;
/* get kernel */
real *ptr_weight = weight_data + k*kstride0;
/* get input */
real *ptr_input = input_data + from*istride0;
/* get output */
real *ptr_output = output_data + to*nOutputRows*nOutputCols;
/* do image, kernel convolution */
THTensor_(conv2d)(ptr_output,
alpha,
ptr_input, nInputRows, nInputCols,
ptr_weight, nKernelRows, nKernelCols,
srow, scol, vf, xc);
}
THTensor_(free)(input);
THTensor_(free)(kernel);
}
/*
4D input, 4D kernel, 5D output
like rank1 update
A <- xx' + beta*A
for sr,sc=1 this is equivalent to xcorr2Dger, but otherwise it is useful for
calculating derivatives wrt a kernel that is applied with stride sr,sc != 1
*/
void THTensor_(conv3DRevger)(THTensor *r_, real beta, real alpha, THTensor *t_, THTensor *k_,
long sdepth, long srow, long scol)
{
long nInputPlane, nInputDepth, nInputRows, nInputCols;
long nKernelPlane, nKernelDepth, nKernelRows, nKernelCols;
long nOutputPlane, nOutputDepth, nOutputRows, nOutputCols;
long istride0, kstride0;
THArgCheck(t_->nDimension == 4 , 3, "input: 4D Tensor expected");
THArgCheck(k_->nDimension == 4 , 4, "kernel: 4D Tensor expected");
THArgCheck(sdepth >= 1, 5, "Stride should be a positive integer");
THArgCheck(srow >= 1, 6, "Stride should be a positive integer");
THArgCheck(scol >= 1, 7, "Stride should be a positive integer");
THTensor *input = THTensor_(newContiguous)(t_);
THTensor *kernel = THTensor_(newContiguous)(k_);
nInputPlane = input->size[0];
istride0 = input->stride[0];
nInputDepth = input->size[1];
nInputRows = input->size[2];
nInputCols = input->size[3];
kstride0 = kernel->stride[0];
nKernelPlane = kernel->size[0];
nKernelDepth= kernel->size[1];
nKernelRows = kernel->size[2];
nKernelCols = kernel->size[3];
nOutputPlane = nInputPlane * kernel->size[0];
THArgCheck(nInputDepth >= nKernelDepth && nInputRows >= nKernelRows && nInputCols >= nKernelCols , 2, "conv3DRevger : Input image is smaller than kernel");
nOutputDepth = nInputDepth - (nKernelDepth - 1) * sdepth;
nOutputRows = nInputRows - (nKernelRows - 1) * srow;
nOutputCols = nInputCols - (nKernelCols - 1) * scol;
long nelem = THTensor_(nElement)(r_);
THTensor_(resize5d)(r_,nKernelPlane, nInputPlane, nOutputDepth, nOutputRows, nOutputCols);
if (nelem == 0 || beta == 0 || nelem != THTensor_(nElement)(r_))
{
THTensor_(zero)(r_);
}
else if (beta != 1)
THTensor_(mul)(r_, r_, beta);
real *input_data = THTensor_(data)(input);
real *weight_data = THTensor_(data)(kernel);
real *output_data = THTensor_(data)(r_);
long k,i;
for(k = 0; k < nKernelPlane; k++)
{
/* get kernel */
real *ptr_weight = weight_data+k*kstride0;
for(i = 0; i < nInputPlane; i++)
{
/* get input */
real *ptr_input = input_data+i*istride0;
/* do image, kernel convolution */
THTensor_(validXCorr3DRevptr)(output_data,
alpha,
ptr_input, nInputDepth, nInputRows, nInputCols,
ptr_weight, nKernelDepth, nKernelRows, nKernelCols,
sdepth, srow, scol);
/* Next output plane */
output_data += nOutputDepth*nOutputCols*nOutputRows;
}
}
THTensor_(free)(input);
THTensor_(free)(kernel);
}
/*
4D input, 4D kernel, 5D output
like rank1 update
A <- xx' + beta*A
*/
void THTensor_(conv3Dger)(THTensor *r_, real beta, real alpha, THTensor *t_, THTensor *k_,
long sdepth, long srow, long scol, const char *vf, const char *xc)
{
long nInputPlane, nInputDepth, nInputRows, nInputCols;
long nKernelPlane, nKernelDepth, nKernelRows, nKernelCols;
long nOutputPlane, nOutputDepth, nOutputRows, nOutputCols;
long istride0, kstride0;
THArgCheck(t_->nDimension == 4 , 3, "input: 4D Tensor expected");
THArgCheck(k_->nDimension == 4 , 4, "kernel: 4D Tensor expected");
THArgCheck(sdepth >= 1, 5, "Stride should be a positive integer");
THArgCheck(srow >= 1, 6, "Stride should be a positive integer");
THArgCheck(scol >= 1, 7, "Stride should be a positive integer");
THArgCheck(*vf == 'V' || *vf == 'F', 8, "type of convolution can 'V' or 'F'");
THArgCheck(*xc == 'C' || *xc == 'X', 8, "type of convolution can 'X' or 'C'");
THTensor *input = THTensor_(newContiguous)(t_);
THTensor *kernel = THTensor_(newContiguous)(k_);
nInputPlane = input->size[0];
istride0 = input->stride[0];
nInputDepth = input->size[1];
nInputRows = input->size[2];
nInputCols = input->size[3];
kstride0 = kernel->stride[0];
nKernelPlane = kernel->size[0];
nKernelDepth = kernel->size[1];
nKernelRows = kernel->size[2];
nKernelCols = kernel->size[3];
nOutputPlane = nInputPlane * kernel->size[0];
THArgCheck((nInputDepth >= nKernelDepth
&& nInputRows >= nKernelRows
&& nInputCols >= nKernelCols)
|| *vf == 'F', 2, "conv3Dger : Input image is smaller than kernel");
nOutputDepth = THTensor_(convsize)(nInputDepth, nKernelDepth, sdepth, vf);
nOutputRows = THTensor_(convsize)(nInputRows, nKernelRows, srow, vf);
nOutputCols = THTensor_(convsize)(nInputCols, nKernelCols, scol, vf);
long nelem = THTensor_(nElement)(r_);
THTensor_(resize5d)(r_,nKernelPlane, nInputPlane, nOutputDepth, nOutputRows, nOutputCols);
if (nelem == 0 || beta == 0 || nelem != THTensor_(nElement)(r_))
{
THTensor_(zero)(r_);
}
else if (beta != 1)
THTensor_(mul)(r_, r_, beta);
real *input_data = THTensor_(data)(input);
real *weight_data = THTensor_(data)(kernel);
real *output_data = THTensor_(data)(r_);
long k,i;
for(k = 0; k < nKernelPlane; k++)
{
/* get kernel */
real *ptr_weight = weight_data+k*kstride0;
for(i = 0; i < nInputPlane; i++)
{
/* get input */
real *ptr_input = input_data+i*istride0;
/* do image, kernel convolution */
THTensor_(conv3d)(output_data,
alpha,
ptr_input, nInputDepth, nInputRows, nInputCols,
ptr_weight, nKernelDepth, nKernelRows, nKernelCols,
sdepth, srow, scol, vf, xc);
/* Next output plane */
output_data += nOutputDepth*nOutputCols*nOutputRows;
}
}
THTensor_(free)(input);
THTensor_(free)(kernel);
}
/*
4D input, 5D kernel, 4D output
matrix vector product like
y <- Ax + beta*y
*/
void THTensor_(conv3Dmv)(THTensor *r_, real beta, real alpha, THTensor *t_, THTensor *k_,
long sdepth, long srow, long scol, const char *vf, const char *xc)
{
long nInputPlane, nInputDepth, nInputRows, nInputCols;
long nKernelDepth, nKernelRows, nKernelCols;
long nOutputPlane, nOutputDepth, nOutputRows, nOutputCols;
long istride0, kstride0, kstride1;
THArgCheck(t_->nDimension == 4 , 3, "input: 4D Tensor expected");
THArgCheck(k_->nDimension == 5 , 4, "kernel: 5D Tensor expected");
THArgCheck(sdepth >= 1, 5, "Stride should be a positive integer");
THArgCheck(srow >= 1, 6, "Stride should be a positive integer");
THArgCheck(scol >= 1, 7, "Stride should be a positive integer");
THArgCheck(*vf == 'V' || *vf == 'F', 8, "type of convolution can 'V' or 'F'");
THArgCheck(*xc == 'C' || *xc == 'X', 8, "type of convolution can 'X' or 'C'");
THTensor *input = THTensor_(newContiguous)(t_);
THTensor* kernel;
if (!(k_->stride[4] == 1) || !(k_->stride[3] == k_->size[4])) {
kernel = THTensor_(newContiguous)(k_);
} else {
THTensor_(retain)(k_);
kernel = k_;
}
nInputPlane = input->size[0];
istride0 = input->stride[0];
nInputDepth = input->size[1];
nInputRows = input->size[2];
nInputCols = input->size[3];
kstride0 = kernel->stride[0];
kstride1 = kernel->stride[1];
nKernelDepth = kernel->size[2];
nKernelRows = kernel->size[3];
nKernelCols = kernel->size[4];
nOutputPlane = kernel->size[0];
THArgCheck(kernel->size[1] == nInputPlane, 2, "invalid number of input planes");
THArgCheck( (nInputDepth >= nKernelDepth && nInputRows >= nKernelRows && nInputCols >= nKernelCols) || *vf == 'F', 2, "conv3Dmv : Input image is smaller than kernel");
nOutputDepth = THTensor_(convsize)(nInputDepth, nKernelDepth, sdepth, vf);
nOutputRows = THTensor_(convsize)(nInputRows, nKernelRows, srow, vf);
nOutputCols = THTensor_(convsize)(nInputCols, nKernelCols, scol, vf);
long nelem = THTensor_(nElement)(r_);
THTensor_(resize4d)(r_, nOutputPlane, nOutputDepth, nOutputRows, nOutputCols);
if (nelem == 0 || beta == 0 || nelem != THTensor_(nElement)(r_))
{
THTensor_(zero)(r_);
}
else if (beta != 1)
THTensor_(mul)(r_, r_, beta);
real *input_data = THTensor_(data)(input);
real *weight_data = THTensor_(data)(kernel);
real *output_data = THTensor_(data)(r_);
long k,i;
for(k = 0; k < nOutputPlane; k++)
{
for(i = 0; i < nInputPlane; i++)
{
/* get kernel */
real *ptr_weight = weight_data + k*kstride0 + i*kstride1;
/* get input */
real *ptr_input = input_data + i*istride0;
/* do image, kernel convolution */
THTensor_(conv3d)(output_data,
alpha,
ptr_input, nInputDepth, nInputRows, nInputCols,
ptr_weight, nKernelDepth, nKernelRows, nKernelCols,
sdepth, srow, scol, vf, xc);
}
/* Next output plane */
output_data += nOutputDepth*nOutputCols*nOutputRows;
}
THTensor_(free)(input);
THTensor_(free)(kernel);
}
/*
3D input, 3D kernel, 3D output
scalar multiplication like
y <- x*y + beta*y
*/
void THTensor_(conv3Dmul)(THTensor *r_, real beta, real alpha, THTensor *t_, THTensor *k_,
long sdepth, long srow, long scol, const char *vf, const char *xc)
{
THArgCheck(t_->nDimension == 3 , 3, "input: 3D Tensor expected");
THArgCheck(k_->nDimension == 3 , 4, "kernel: 3D Tensor expected");
THArgCheck(sdepth >= 1, 5, "Stride should be a positive integer");
THArgCheck(srow >= 1, 6, "Stride should be a positive integer");
THArgCheck(scol >= 1, 7, "Stride should be a positive integer");
THArgCheck(*vf == 'V' || *vf == 'F', 8, "type of convolution can 'V' or 'F'");
THArgCheck(*xc == 'C' || *xc == 'X', 8, "type of convolution can 'X' or 'C'");
THTensor *input = THTensor_(newContiguous)(t_);
THTensor* kernel = THTensor_(newContiguous)(k_);
long nInputDepth = input->size[0];
long nInputRows = input->size[1];
long nInputCols = input->size[2];
long nKernelDepth = kernel->size[0];
long nKernelRows = kernel->size[1];
long nKernelCols = kernel->size[2];
long nOutputDepth, nOutputRows, nOutputCols;
THArgCheck((nInputDepth >= nKernelDepth && nInputRows >= nKernelRows && nInputCols >= nKernelCols) || *vf == 'F', 2, "conv3Dmul : Input image is smaller than kernel");
nOutputDepth = THTensor_(convsize)(nInputDepth, nKernelDepth, sdepth, vf);
nOutputRows = THTensor_(convsize)(nInputRows, nKernelRows, srow, vf);
nOutputCols = THTensor_(convsize)(nInputCols, nKernelCols, scol, vf);
long nelem = THTensor_(nElement)(r_);
THTensor_(resize3d)(r_, nOutputDepth, nOutputRows, nOutputCols);
if (nelem == 0 || beta == 0 || nelem != THTensor_(nElement)(r_))
THTensor_(zero)(r_);
else if (beta != 1)
THTensor_(mul)(r_, r_, beta);
real *ptr_input = THTensor_(data)(input);
real *ptr_weight = THTensor_(data)(kernel);
real *output_data = THTensor_(data)(r_);
/* do image, kernel convolution */
THTensor_(conv3d)(output_data,
alpha,
ptr_input, nInputDepth, nInputRows, nInputCols,
ptr_weight, nKernelDepth, nKernelRows, nKernelCols,
sdepth, srow, scol, vf, xc);
THTensor_(free)(input);
THTensor_(free)(kernel);
}
/*
4D input, 4D kernel, 4D output
component wise multiplication like
y <- y.*x + beta*y
*/
void THTensor_(conv3Dcmul)(THTensor *r_, real beta, real alpha, THTensor *t_, THTensor *k_,
long sdepth, long srow, long scol, const char *vf, const char *xc)
{
long nInputPlane, nInputDepth, nInputRows, nInputCols;
long nKernelDepth, nKernelRows, nKernelCols;
long nOutputPlane, nOutputDepth, nOutputRows, nOutputCols;
long istride0, kstride0;
THArgCheck(t_->nDimension == 4 , 3, "input: 3D Tensor expected");
THArgCheck(k_->nDimension == 4 , 4, "kernel: 3D Tensor expected");
THArgCheck(srow >= 1, 5, "Stride should be a positive integer");
THArgCheck(scol >= 1, 6, "Stride should be a positive integer");
THArgCheck(*vf == 'V' || *vf == 'F', 7, "type of convolution can 'V' or 'F'");
THArgCheck(*xc == 'C' || *xc == 'X', 7, "type of convolution can 'X' or 'C'");
THTensor *input = THTensor_(newContiguous)(t_);
THTensor* kernel = THTensor_(newContiguous)(k_);
istride0 = input->stride[0];
nInputPlane = input->size[0];
nInputDepth = input->size[1];
nInputRows = input->size[2];
nInputCols = input->size[3];
kstride0 = kernel->stride[0];
nOutputPlane = kernel->size[0];
nKernelDepth = kernel->size[1];
nKernelRows = kernel->size[2];
nKernelCols = kernel->size[3];
THArgCheck(nOutputPlane == nInputPlane, 2, "invalid number of input/kernel planes");
THArgCheck( (nInputDepth >= nKernelDepth && nInputRows >= nKernelRows && nInputCols >= nKernelCols) || *vf == 'F', 2, "conv3Dcmul : Input image is smaller than kernel");
nOutputDepth = THTensor_(convsize)(nInputDepth, nKernelDepth, sdepth, vf);
nOutputRows = THTensor_(convsize)(nInputRows, nKernelRows, srow, vf);
nOutputCols = THTensor_(convsize)(nInputCols, nKernelCols, scol, vf);
long nelem = THTensor_(nElement)(r_);
THTensor_(resize4d)(r_, nOutputPlane, nOutputDepth, nOutputRows, nOutputCols);
if (nelem == 0 || beta == 0 || nelem != THTensor_(nElement)(r_))
{
THTensor_(zero)(r_);
}
else if (beta != 1)
THTensor_(mul)(r_, r_, beta);
real *input_data = THTensor_(data)(input);
real *weight_data = THTensor_(data)(kernel);
real *output_data = THTensor_(data)(r_);
long k;
for(k = 0; k < nOutputPlane; k++)
{
/* get kernel */
real *ptr_weight = weight_data + k*kstride0;
/* get input */
real *ptr_input = input_data + k*istride0;
/* do image, kernel convolution */
THTensor_(conv3d)(output_data,
alpha,
ptr_input, nInputDepth, nInputRows, nInputCols,
ptr_weight, nKernelDepth, nKernelRows, nKernelCols,
sdepth, srow, scol, vf, xc);
/* Next output plane */
output_data += nOutputDepth*nOutputCols*nOutputRows;
}
THTensor_(free)(input);
THTensor_(free)(kernel);
}
/*
4D input, 4D kernel, 4D output
component wise multiplication like with a permutation map
y <- y.*x + beta*y
*/
void THTensor_(conv3Dmap)(THTensor *r_, real beta, real alpha, THTensor *t_, THTensor *k_, THTensor *map,
long sdepth, long srow, long scol, const char *vf, const char *xc)
{
long nInputPlane, nInputDepth, nInputRows, nInputCols;
long nKernelDepth, nKernelRows, nKernelCols;
long nOutputPlane, nOutputDepth, nOutputRows, nOutputCols;
long istride0, kstride0;
THArgCheck(t_->nDimension == 4 , 3, "input: 4D Tensor expected");
THArgCheck(k_->nDimension == 4 , 4, "kernel: 4D Tensor expected");
THArgCheck(map->nDimension == 2 , 4, "map: 2D Tensor expected");
THArgCheck(srow >= 1, 6, "Stride should be a positive integer");
THArgCheck(scol >= 1, 7, "Stride should be a positive integer");
THArgCheck(*vf == 'V' || *vf == 'F', 8, "type of convolution can 'V' or 'F'");
THArgCheck(*xc == 'C' || *xc == 'X', 8, "type of convolution can 'X' or 'C'");
THTensor *input = THTensor_(newContiguous)(t_);
THTensor* kernel = THTensor_(newContiguous)(k_);
istride0 = input->stride[0];
nInputPlane = input->size[0];
nInputDepth = input->size[1];
nInputRows = input->size[2];
nInputCols = input->size[3];
kstride0 = kernel->stride[0];
nOutputPlane = kernel->size[0];
nKernelDepth = kernel->size[1];
nKernelRows = kernel->size[2];
nKernelCols = kernel->size[3];
THArgCheck(nOutputPlane == nInputPlane, 2, "invalid number of input/kernel planes");
THArgCheck((nInputDepth >= nKernelDepth
&& nInputRows >= nKernelRows
&& nInputCols >= nKernelCols) || *vf == 'F',
2, "conv3Dmap : Input image is smaller than kernel");
nOutputDepth = THTensor_(convsize)(nInputDepth, nKernelDepth, sdepth, vf);
nOutputRows = THTensor_(convsize)(nInputRows, nKernelRows, srow, vf);
nOutputCols = THTensor_(convsize)(nInputCols, nKernelCols, scol, vf);
long nelem = THTensor_(nElement)(r_);
THTensor_(resize4d)(r_, nOutputPlane, nOutputDepth, nOutputRows, nOutputCols);
if (nelem == 0 || beta == 0 || nelem != THTensor_(nElement)(r_))
{
THTensor_(zero)(r_);
}
else if (beta != 1)
THTensor_(mul)(r_, r_, beta);
real *input_data = THTensor_(data)(input);
real *weight_data = THTensor_(data)(kernel);
real *output_data = THTensor_(data)(r_);
long nmaps = map->size[0];
long k;
for(k = 0; k < nmaps; k++)
{
/* get indices */
long from = (long)THTensor_(get2d)(map,k,0)-1;
long to = (long)THTensor_(get2d)(map,k,1)-1;
/* get kernel */
real *ptr_weight = weight_data + k*kstride0;
/* get input */
real *ptr_input = input_data + from*istride0;
/* get output */
real *ptr_output = output_data + to*nOutputDepth*nOutputRows*nOutputCols;
/* do image, kernel convolution */
THTensor_(conv3d)(ptr_output,
alpha,
ptr_input, nInputDepth, nInputRows, nInputCols,
ptr_weight, nKernelDepth, nKernelRows, nKernelCols,
sdepth, srow, scol, vf, xc);
}
THTensor_(free)(input);
THTensor_(free)(kernel);
}
#endif
|
BKTree.h | // Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
#ifndef _SPTAG_COMMON_BKTREE_H_
#define _SPTAG_COMMON_BKTREE_H_
#include <stack>
#include <string>
#include <vector>
#include <shared_mutex>
#include "../VectorIndex.h"
#include "CommonUtils.h"
#include "QueryResultSet.h"
#include "WorkSpace.h"
#include "Dataset.h"
#include "DistanceUtils.h"
namespace SPTAG
{
namespace COMMON
{
// node type for storing BKT
struct BKTNode
{
SizeType centerid;
SizeType childStart;
SizeType childEnd;
BKTNode(SizeType cid = -1) : centerid(cid), childStart(-1), childEnd(-1) {}
};
template <typename T>
struct KmeansArgs {
int _K;
int _DK;
DimensionType _D;
int _T;
DistCalcMethod _M;
T* centers;
T* newTCenters;
SizeType* counts;
float* newCenters;
SizeType* newCounts;
int* label;
SizeType* clusterIdx;
float* clusterDist;
float* weightedCounts;
float* newWeightedCounts;
float(*fComputeDistance)(const T* pX, const T* pY, DimensionType length);
KmeansArgs(int k, DimensionType dim, SizeType datasize, int threadnum, DistCalcMethod distMethod) : _K(k), _DK(k), _D(dim), _T(threadnum), _M(distMethod) {
centers = (T*)_mm_malloc(sizeof(T) * k * dim, ALIGN_SPTAG);
newTCenters = (T*)_mm_malloc(sizeof(T) * k * dim, ALIGN_SPTAG);
counts = new SizeType[k];
newCenters = new float[threadnum * k * dim];
newCounts = new SizeType[threadnum * k];
label = new int[datasize];
clusterIdx = new SizeType[threadnum * k];
clusterDist = new float[threadnum * k];
weightedCounts = new float[k];
newWeightedCounts = new float[threadnum * k];
fComputeDistance = COMMON::DistanceCalcSelector<T>(distMethod);
}
~KmeansArgs() {
_mm_free(centers);
_mm_free(newTCenters);
delete[] counts;
delete[] newCenters;
delete[] newCounts;
delete[] label;
delete[] clusterIdx;
delete[] clusterDist;
delete[] weightedCounts;
delete[] newWeightedCounts;
}
inline void ClearCounts() {
memset(newCounts, 0, sizeof(SizeType) * _T * _K);
memset(newWeightedCounts, 0, sizeof(float) * _T * _K);
}
inline void ClearCenters() {
memset(newCenters, 0, sizeof(float) * _T * _K * _D);
}
inline void ClearDists(float dist) {
for (int i = 0; i < _T * _K; i++) {
clusterIdx[i] = -1;
clusterDist[i] = dist;
}
}
void Shuffle(std::vector<SizeType>& indices, SizeType first, SizeType last) {
SizeType* pos = new SizeType[_K];
pos[0] = first;
for (int k = 1; k < _K; k++) pos[k] = pos[k - 1] + newCounts[k - 1];
for (int k = 0; k < _K; k++) {
if (newCounts[k] == 0) continue;
SizeType i = pos[k];
while (newCounts[k] > 0) {
SizeType swapid = pos[label[i]] + newCounts[label[i]] - 1;
newCounts[label[i]]--;
std::swap(indices[i], indices[swapid]);
std::swap(label[i], label[swapid]);
}
while (indices[i] != clusterIdx[k]) i++;
std::swap(indices[i], indices[pos[k] + counts[k] - 1]);
}
delete[] pos;
}
};
template <typename T>
float RefineCenters(const Dataset<T>& data, KmeansArgs<T>& args)
{
int maxcluster = -1;
SizeType maxCount = 0;
for (int k = 0; k < args._DK; k++) {
if (args.counts[k] > maxCount && args.newCounts[k] > 0 && DistanceUtils::ComputeDistance((T*)data[args.clusterIdx[k]], args.centers + k * args._D, args._D, DistCalcMethod::L2) > 1e-6)
{
maxcluster = k;
maxCount = args.counts[k];
}
}
if (maxcluster != -1 && (args.clusterIdx[maxcluster] < 0 || args.clusterIdx[maxcluster] >= data.R()))
LOG(Helper::LogLevel::LL_Debug, "maxcluster:%d(%d) Error dist:%f\n", maxcluster, args.newCounts[maxcluster], args.clusterDist[maxcluster]);
float diff = 0;
for (int k = 0; k < args._DK; k++) {
T* TCenter = args.newTCenters + k * args._D;
if (args.counts[k] == 0) {
if (maxcluster != -1) {
//int nextid = Utils::rand_int(last, first);
//while (args.label[nextid] != maxcluster) nextid = Utils::rand_int(last, first);
SizeType nextid = args.clusterIdx[maxcluster];
std::memcpy(TCenter, data[nextid], sizeof(T)*args._D);
}
else {
std::memcpy(TCenter, args.centers + k * args._D, sizeof(T)*args._D);
}
}
else {
float* currCenters = args.newCenters + k * args._D;
for (DimensionType j = 0; j < args._D; j++) currCenters[j] /= args.counts[k];
if (args._M == DistCalcMethod::Cosine) {
COMMON::Utils::Normalize(currCenters, args._D, COMMON::Utils::GetBase<T>());
}
for (DimensionType j = 0; j < args._D; j++) TCenter[j] = (T)(currCenters[j]);
}
diff += args.fComputeDistance(args.centers + k*args._D, TCenter, args._D);
}
return diff;
}
template <typename T>
inline float KmeansAssign(const Dataset<T>& data,
std::vector<SizeType>& indices,
const SizeType first, const SizeType last, KmeansArgs<T>& args,
const bool updateCenters, float lambda) {
float currDist = 0;
SizeType subsize = (last - first - 1) / args._T + 1;
#pragma omp parallel for num_threads(args._T) shared(data, indices) reduction(+:currDist)
for (int tid = 0; tid < args._T; tid++)
{
SizeType istart = first + tid * subsize;
SizeType iend = min(first + (tid + 1) * subsize, last);
SizeType *inewCounts = args.newCounts + tid * args._K;
float *inewCenters = args.newCenters + tid * args._K * args._D;
SizeType * iclusterIdx = args.clusterIdx + tid * args._K;
float * iclusterDist = args.clusterDist + tid * args._K;
float * iweightedCounts = args.newWeightedCounts + tid * args._K;
float idist = 0;
for (SizeType i = istart; i < iend; i++) {
int clusterid = 0;
float smallestDist = MaxDist;
for (int k = 0; k < args._DK; k++) {
float dist = args.fComputeDistance(data[indices[i]], args.centers + k*args._D, args._D) + lambda*args.counts[k];
if (dist > -MaxDist && dist < smallestDist) {
clusterid = k; smallestDist = dist;
}
}
args.label[i] = clusterid;
inewCounts[clusterid]++;
iweightedCounts[clusterid] += smallestDist;
idist += smallestDist;
if (updateCenters) {
const T* v = (const T*)data[indices[i]];
float* center = inewCenters + clusterid*args._D;
for (DimensionType j = 0; j < args._D; j++) center[j] += v[j];
if (smallestDist > iclusterDist[clusterid]) {
iclusterDist[clusterid] = smallestDist;
iclusterIdx[clusterid] = indices[i];
}
}
else {
if (smallestDist <= iclusterDist[clusterid]) {
iclusterDist[clusterid] = smallestDist;
iclusterIdx[clusterid] = indices[i];
}
}
}
currDist += idist;
}
for (int i = 1; i < args._T; i++) {
for (int k = 0; k < args._DK; k++) {
args.newCounts[k] += args.newCounts[i * args._K + k];
args.newWeightedCounts[k] += args.newWeightedCounts[i * args._K + k];
}
}
if (updateCenters) {
for (int i = 1; i < args._T; i++) {
float* currCenter = args.newCenters + i*args._K*args._D;
for (size_t j = 0; j < ((size_t)args._DK) * args._D; j++) args.newCenters[j] += currCenter[j];
for (int k = 0; k < args._DK; k++) {
if (args.clusterIdx[i*args._K + k] != -1 && args.clusterDist[i*args._K + k] > args.clusterDist[k]) {
args.clusterDist[k] = args.clusterDist[i*args._K + k];
args.clusterIdx[k] = args.clusterIdx[i*args._K + k];
}
}
}
}
else {
for (int i = 1; i < args._T; i++) {
for (int k = 0; k < args._DK; k++) {
if (args.clusterIdx[i*args._K + k] != -1 && args.clusterDist[i*args._K + k] <= args.clusterDist[k]) {
args.clusterDist[k] = args.clusterDist[i*args._K + k];
args.clusterIdx[k] = args.clusterIdx[i*args._K + k];
}
}
}
}
return currDist;
}
template <typename T>
inline float InitCenters(const Dataset<T>& data,
std::vector<SizeType>& indices, const SizeType first, const SizeType last,
KmeansArgs<T>& args, int samples, int tryIters) {
SizeType batchEnd = min(first + samples, last);
float lambda, currDist, minClusterDist = MaxDist;
for (int numKmeans = 0; numKmeans < tryIters; numKmeans++) {
for (int k = 0; k < args._DK; k++) {
SizeType randid = COMMON::Utils::rand(last, first);
std::memcpy(args.centers + k*args._D, data[indices[randid]], sizeof(T)*args._D);
}
args.ClearCounts();
args.ClearDists(MaxDist);
currDist = KmeansAssign(data, indices, first, batchEnd, args, false, 0);
if (currDist < minClusterDist) {
minClusterDist = currDist;
memcpy(args.newTCenters, args.centers, sizeof(T)*args._K*args._D);
memcpy(args.counts, args.newCounts, sizeof(SizeType) * args._K);
SizeType maxCluster = 0;
for (int k = 1; k < args._DK; k++) if (args.counts[k] > args.counts[maxCluster]) maxCluster = k;
float avgDist = args.newWeightedCounts[maxCluster] / args.counts[maxCluster];
lambda = (avgDist - args.clusterDist[maxCluster]) / args.counts[maxCluster];
if (lambda < 0) lambda = 0;
}
}
return lambda;
}
template <typename T>
float TryClustering(const Dataset<T>& data,
std::vector<SizeType>& indices, const SizeType first, const SizeType last,
KmeansArgs<T>& args, int samples = 1000, float lambdaFactor = 100.0f, bool debug = false, IAbortOperation* abort = nullptr) {
float adjustedLambda = InitCenters(data, indices, first, last, args, samples, 3);
if (abort && abort->ShouldAbort()) return 0;
SizeType batchEnd = min(first + samples, last);
float currDiff, currDist, minClusterDist = MaxDist;
int noImprovement = 0;
float originalLambda = COMMON::Utils::GetBase<T>() * COMMON::Utils::GetBase<T>() / lambdaFactor / (batchEnd - first);
for (int iter = 0; iter < 100; iter++) {
std::memcpy(args.centers, args.newTCenters, sizeof(T)*args._K*args._D);
std::random_shuffle(indices.begin() + first, indices.begin() + last);
args.ClearCenters();
args.ClearCounts();
args.ClearDists(-MaxDist);
currDist = KmeansAssign(data, indices, first, batchEnd, args, true, min(adjustedLambda, originalLambda));
std::memcpy(args.counts, args.newCounts, sizeof(SizeType) * args._K);
if (currDist < minClusterDist) {
noImprovement = 0;
minClusterDist = currDist;
}
else {
noImprovement++;
}
currDiff = RefineCenters(data, args);
//if (debug) LOG(Helper::LogLevel::LL_Info, "iter %d dist:%f diff:%f\n", iter, currDist, currDiff);
if (abort && abort->ShouldAbort()) return 0;
if (currDiff < 1e-3 || noImprovement >= 5) break;
}
args.ClearCounts();
args.ClearDists(MaxDist);
currDist = KmeansAssign(data, indices, first, last, args, false, 0);
std::memcpy(args.counts, args.newCounts, sizeof(SizeType) * args._K);
SizeType maxCount = 0, minCount = (std::numeric_limits<SizeType>::max)(), availableClusters = 0;
float CountStd = 0.0, CountAvg = (last - first) * 1.0f / args._DK;
for (int i = 0; i < args._DK; i++) {
if (args.counts[i] > maxCount) maxCount = args.counts[i];
if (args.counts[i] < minCount) minCount = args.counts[i];
CountStd += (args.counts[i] - CountAvg) * (args.counts[i] - CountAvg);
if (args.counts[i] > 0) availableClusters++;
}
CountStd = sqrt(CountStd / args._DK) / CountAvg;
if (debug) LOG(Helper::LogLevel::LL_Info, "Lambda:min(%g,%g) Max:%d Min:%d Avg:%f Std/Avg:%f Dist:%f NonZero/Total:%d/%d\n", originalLambda, adjustedLambda, maxCount, minCount, CountAvg, CountStd, currDist, availableClusters, args._DK);
return CountStd;
}
template <typename T>
float DynamicFactorSelect(const Dataset<T> & data,
std::vector<SizeType> & indices, const SizeType first, const SizeType last,
KmeansArgs<T> & args, int samples = 1000) {
float bestLambdaFactor = 100.0f, bestCountStd = (std::numeric_limits<float>::max)();
for (float lambdaFactor = 0.001f; lambdaFactor <= 1000.0f + 1e-3; lambdaFactor *= 10) {
float CountStd = TryClustering(data, indices, first, last, args, samples, lambdaFactor, true);
if (CountStd < bestCountStd) {
bestLambdaFactor = lambdaFactor;
bestCountStd = CountStd;
}
}
/*
std::vector<float> tries(16, 0);
for (int i = 0; i < 8; i++) {
tries[i] = bestLambdaFactor * (i + 2) / 10;
tries[8 + i] = bestLambdaFactor * (i + 2);
}
for (float lambdaFactor : tries) {
float CountStd = TryClustering(data, indices, first, last, args, samples, lambdaFactor, true);
if (CountStd < bestCountStd) {
bestLambdaFactor = lambdaFactor;
bestCountStd = CountStd;
}
}
*/
LOG(Helper::LogLevel::LL_Info, "Best Lambda Factor:%f\n", bestLambdaFactor);
return bestLambdaFactor;
}
template <typename T>
int KmeansClustering(const Dataset<T>& data,
std::vector<SizeType>& indices, const SizeType first, const SizeType last,
KmeansArgs<T>& args, int samples = 1000, float lambdaFactor = 100.0f, bool debug = false, IAbortOperation* abort = nullptr) {
TryClustering(data, indices, first, last, args, samples, lambdaFactor, debug, abort);
if (abort && abort->ShouldAbort()) return 1;
int numClusters = 0;
for (int i = 0; i < args._K; i++) if (args.counts[i] > 0) numClusters++;
if (numClusters <= 1) return numClusters;
args.Shuffle(indices, first, last);
return numClusters;
}
class BKTree
{
public:
BKTree(): m_iTreeNumber(1), m_iBKTKmeansK(32), m_iBKTLeafSize(8), m_iSamples(1000), m_fBalanceFactor(-1.0f), m_lock(new std::shared_timed_mutex) {}
BKTree(const BKTree& other): m_iTreeNumber(other.m_iTreeNumber),
m_iBKTKmeansK(other.m_iBKTKmeansK),
m_iBKTLeafSize(other.m_iBKTLeafSize),
m_iSamples(other.m_iSamples),
m_fBalanceFactor(other.m_fBalanceFactor),
m_lock(new std::shared_timed_mutex) {}
~BKTree() {}
inline const BKTNode& operator[](SizeType index) const { return m_pTreeRoots[index]; }
inline BKTNode& operator[](SizeType index) { return m_pTreeRoots[index]; }
inline SizeType size() const { return (SizeType)m_pTreeRoots.size(); }
inline SizeType sizePerTree() const {
std::shared_lock<std::shared_timed_mutex> lock(*m_lock);
return (SizeType)m_pTreeRoots.size() - m_pTreeStart.back();
}
inline const std::unordered_map<SizeType, SizeType>& GetSampleMap() const { return m_pSampleCenterMap; }
template <typename T>
void Rebuild(const Dataset<T>& data, DistCalcMethod distMethod, IAbortOperation* abort)
{
BKTree newTrees(*this);
newTrees.BuildTrees<T>(data, distMethod, 1, nullptr, nullptr, false, abort);
std::unique_lock<std::shared_timed_mutex> lock(*m_lock);
m_pTreeRoots.swap(newTrees.m_pTreeRoots);
m_pTreeStart.swap(newTrees.m_pTreeStart);
m_pSampleCenterMap.swap(newTrees.m_pSampleCenterMap);
}
template <typename T>
void BuildTrees(const Dataset<T>& data, DistCalcMethod distMethod, int numOfThreads,
std::vector<SizeType>* indices = nullptr, std::vector<SizeType>* reverseIndices = nullptr,
bool dynamicK = false, IAbortOperation* abort = nullptr)
{
struct BKTStackItem {
SizeType index, first, last;
bool debug;
BKTStackItem(SizeType index_, SizeType first_, SizeType last_, bool debug_ = false) : index(index_), first(first_), last(last_), debug(debug_) {}
};
std::stack<BKTStackItem> ss;
std::vector<SizeType> localindices;
if (indices == nullptr) {
localindices.resize(data.R());
for (SizeType i = 0; i < localindices.size(); i++) localindices[i] = i;
}
else {
localindices.assign(indices->begin(), indices->end());
}
KmeansArgs<T> args(m_iBKTKmeansK, data.C(), (SizeType)localindices.size(), numOfThreads, distMethod);
if (m_fBalanceFactor < 0) m_fBalanceFactor = DynamicFactorSelect(data, localindices, 0, (SizeType)localindices.size(), args, m_iSamples);
m_pSampleCenterMap.clear();
for (char i = 0; i < m_iTreeNumber; i++)
{
std::random_shuffle(localindices.begin(), localindices.end());
m_pTreeStart.push_back((SizeType)m_pTreeRoots.size());
m_pTreeRoots.emplace_back((SizeType)localindices.size());
LOG(Helper::LogLevel::LL_Info, "Start to build BKTree %d\n", i + 1);
ss.push(BKTStackItem(m_pTreeStart[i], 0, (SizeType)localindices.size(), true));
while (!ss.empty()) {
if (abort && abort->ShouldAbort()) return;
BKTStackItem item = ss.top(); ss.pop();
SizeType newBKTid = (SizeType)m_pTreeRoots.size();
m_pTreeRoots[item.index].childStart = newBKTid;
if (item.last - item.first <= m_iBKTLeafSize) {
for (SizeType j = item.first; j < item.last; j++) {
SizeType cid = (reverseIndices == nullptr)? localindices[j]: reverseIndices->at(localindices[j]);
m_pTreeRoots.emplace_back(cid);
}
}
else { // clustering the data into BKTKmeansK clusters
if (dynamicK) {
args._DK = std::min<int>((item.last - item.first) / m_iBKTLeafSize + 1, m_iBKTKmeansK);
args._DK = std::max<int>(args._DK, 2);
}
int numClusters = KmeansClustering(data, localindices, item.first, item.last, args, m_iSamples, m_fBalanceFactor, item.debug, abort);
if (numClusters <= 1) {
SizeType end = min(item.last + 1, (SizeType)localindices.size());
std::sort(localindices.begin() + item.first, localindices.begin() + end);
m_pTreeRoots[item.index].centerid = (reverseIndices == nullptr) ? localindices[item.first] : reverseIndices->at(localindices[item.first]);
m_pTreeRoots[item.index].childStart = -m_pTreeRoots[item.index].childStart;
for (SizeType j = item.first + 1; j < end; j++) {
SizeType cid = (reverseIndices == nullptr) ? localindices[j] : reverseIndices->at(localindices[j]);
m_pTreeRoots.emplace_back(cid);
m_pSampleCenterMap[cid] = m_pTreeRoots[item.index].centerid;
}
m_pSampleCenterMap[-1 - m_pTreeRoots[item.index].centerid] = item.index;
}
else {
SizeType maxCount = 0;
for (int k = 0; k < m_iBKTKmeansK; k++) if (args.counts[k] > maxCount) maxCount = args.counts[k];
for (int k = 0; k < m_iBKTKmeansK; k++) {
if (args.counts[k] == 0) continue;
SizeType cid = (reverseIndices == nullptr) ? localindices[item.first + args.counts[k] - 1] : reverseIndices->at(localindices[item.first + args.counts[k] - 1]);
m_pTreeRoots.emplace_back(cid);
if (args.counts[k] > 1) ss.push(BKTStackItem(newBKTid++, item.first, item.first + args.counts[k] - 1, item.debug && (args.counts[k] == maxCount)));
item.first += args.counts[k];
}
}
}
m_pTreeRoots[item.index].childEnd = (SizeType)m_pTreeRoots.size();
}
m_pTreeRoots.emplace_back(-1);
LOG(Helper::LogLevel::LL_Info, "%d BKTree built, %zu %zu\n", i + 1, m_pTreeRoots.size() - m_pTreeStart[i], localindices.size());
}
}
inline std::uint64_t BufferSize() const
{
return sizeof(int) + sizeof(SizeType) * m_iTreeNumber +
sizeof(SizeType) + sizeof(BKTNode) * m_pTreeRoots.size();
}
ErrorCode SaveTrees(std::shared_ptr<Helper::DiskPriorityIO> p_out) const
{
std::shared_lock<std::shared_timed_mutex> lock(*m_lock);
IOBINARY(p_out, WriteBinary, sizeof(m_iTreeNumber), (char*)&m_iTreeNumber);
IOBINARY(p_out, WriteBinary, sizeof(SizeType) * m_iTreeNumber, (char*)m_pTreeStart.data());
SizeType treeNodeSize = (SizeType)m_pTreeRoots.size();
IOBINARY(p_out, WriteBinary, sizeof(treeNodeSize), (char*)&treeNodeSize);
IOBINARY(p_out, WriteBinary, sizeof(BKTNode) * treeNodeSize, (char*)m_pTreeRoots.data());
LOG(Helper::LogLevel::LL_Info, "Save BKT (%d,%d) Finish!\n", m_iTreeNumber, treeNodeSize);
return ErrorCode::Success;
}
ErrorCode SaveTrees(std::string sTreeFileName) const
{
LOG(Helper::LogLevel::LL_Info, "Save BKT to %s\n", sTreeFileName.c_str());
auto ptr = f_createIO();
if (ptr == nullptr || !ptr->Initialize(sTreeFileName.c_str(), std::ios::binary | std::ios::out)) return ErrorCode::FailedCreateFile;
return SaveTrees(ptr);
}
ErrorCode LoadTrees(char* pBKTMemFile)
{
m_iTreeNumber = *((int*)pBKTMemFile);
pBKTMemFile += sizeof(int);
m_pTreeStart.resize(m_iTreeNumber);
memcpy(m_pTreeStart.data(), pBKTMemFile, sizeof(SizeType) * m_iTreeNumber);
pBKTMemFile += sizeof(SizeType)*m_iTreeNumber;
SizeType treeNodeSize = *((SizeType*)pBKTMemFile);
pBKTMemFile += sizeof(SizeType);
m_pTreeRoots.resize(treeNodeSize);
memcpy(m_pTreeRoots.data(), pBKTMemFile, sizeof(BKTNode) * treeNodeSize);
if (m_pTreeRoots.size() > 0 && m_pTreeRoots.back().centerid != -1) m_pTreeRoots.emplace_back(-1);
LOG(Helper::LogLevel::LL_Info, "Load BKT (%d,%d) Finish!\n", m_iTreeNumber, treeNodeSize);
return ErrorCode::Success;
}
ErrorCode LoadTrees(std::shared_ptr<Helper::DiskPriorityIO> p_input)
{
IOBINARY(p_input, ReadBinary, sizeof(m_iTreeNumber), (char*)&m_iTreeNumber);
m_pTreeStart.resize(m_iTreeNumber);
IOBINARY(p_input, ReadBinary, sizeof(SizeType) * m_iTreeNumber, (char*)m_pTreeStart.data());
SizeType treeNodeSize;
IOBINARY(p_input, ReadBinary, sizeof(treeNodeSize), (char*)&treeNodeSize);
m_pTreeRoots.resize(treeNodeSize);
IOBINARY(p_input, ReadBinary, sizeof(BKTNode) * treeNodeSize, (char*)m_pTreeRoots.data());
if (m_pTreeRoots.size() > 0 && m_pTreeRoots.back().centerid != -1) m_pTreeRoots.emplace_back(-1);
LOG(Helper::LogLevel::LL_Info, "Load BKT (%d,%d) Finish!\n", m_iTreeNumber, treeNodeSize);
return ErrorCode::Success;
}
ErrorCode LoadTrees(std::string sTreeFileName)
{
LOG(Helper::LogLevel::LL_Info, "Load BKT From %s\n", sTreeFileName.c_str());
auto ptr = f_createIO();
if (ptr == nullptr || !ptr->Initialize(sTreeFileName.c_str(), std::ios::binary | std::ios::in)) return ErrorCode::FailedOpenFile;
return LoadTrees(ptr);
}
template <typename T>
void InitSearchTrees(const Dataset<T>& data, float(*fComputeDistance)(const T* pX, const T* pY, DimensionType length), COMMON::QueryResultSet<T> &p_query, COMMON::WorkSpace &p_space) const
{
for (char i = 0; i < m_iTreeNumber; i++) {
const BKTNode& node = m_pTreeRoots[m_pTreeStart[i]];
if (node.childStart < 0) {
p_space.m_SPTQueue.insert(NodeDistPair(m_pTreeStart[i], fComputeDistance(p_query.GetQuantizedTarget(), data[node.centerid], data.C())));
}
else {
for (SizeType begin = node.childStart; begin < node.childEnd; begin++) {
SizeType index = m_pTreeRoots[begin].centerid;
p_space.m_SPTQueue.insert(NodeDistPair(begin, fComputeDistance(p_query.GetQuantizedTarget(), data[index], data.C())));
}
}
}
}
template <typename T>
void SearchTrees(const Dataset<T>& data, float(*fComputeDistance)(const T* pX, const T* pY, DimensionType length), COMMON::QueryResultSet<T> &p_query,
COMMON::WorkSpace &p_space, const int p_limits) const
{
while (!p_space.m_SPTQueue.empty())
{
NodeDistPair bcell = p_space.m_SPTQueue.pop();
const BKTNode& tnode = m_pTreeRoots[bcell.node];
if (tnode.childStart < 0) {
if (!p_space.CheckAndSet(tnode.centerid)) {
p_space.m_iNumberOfCheckedLeaves++;
p_space.m_NGQueue.insert(NodeDistPair(tnode.centerid, bcell.distance));
}
if (p_space.m_iNumberOfCheckedLeaves >= p_limits) break;
}
else {
if (!p_space.CheckAndSet(tnode.centerid)) {
p_space.m_NGQueue.insert(NodeDistPair(tnode.centerid, bcell.distance));
}
for (SizeType begin = tnode.childStart; begin < tnode.childEnd; begin++) {
SizeType index = m_pTreeRoots[begin].centerid;
p_space.m_SPTQueue.insert(NodeDistPair(begin, fComputeDistance(p_query.GetQuantizedTarget(), data[index], data.C())));
}
}
}
}
private:
std::vector<SizeType> m_pTreeStart;
std::vector<BKTNode> m_pTreeRoots;
std::unordered_map<SizeType, SizeType> m_pSampleCenterMap;
public:
std::unique_ptr<std::shared_timed_mutex> m_lock;
int m_iTreeNumber, m_iBKTKmeansK, m_iBKTLeafSize, m_iSamples;
float m_fBalanceFactor;
};
}
}
#endif
|
geo_region_growing.h | /*
* Software License Agreement (BSD License)
*
* Point Cloud Library (PCL) - www.pointclouds.org
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
* * Neither the name of the copyright holder(s) 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.
*
* Author : Sergey Ushakov
* Email : mine_all_mine@bk.ru
*
*/
/*
* Modified by Xin Wang
* Email : ericrussell@zju.edu.cn
*/
#pragma once
#include <pcl/pcl_base.h>
#include <pcl/search/search.h>
#include <pcl/point_cloud.h>
#include <pcl/point_types.h>
#include <pcl/search/kdtree.h>
#include <list>
#include <math.h>
#include <time.h>
#include <queue>
#include "omp.h"
/** \brief
* Implements the well known Region Growing algorithm used for segmentation.
* Description can be found in the article
* "Segmentation of point clouds using smoothness constraint"
* by T. Rabbania, F. A. van den Heuvelb, G. Vosselmanc.
* In addition to residual test, the possibility to test curvature is added.
*/
template <typename PointT, typename NormalT>
class GeoRegionGrowing : public pcl::PCLBase<PointT>
{
public:
typedef pcl::search::Search <PointT> KdTree;
typedef typename KdTree::Ptr KdTreePtr;
typedef pcl::PointCloud <NormalT> Normal;
typedef typename Normal::Ptr NormalPtr;
typedef pcl::PointCloud <PointT> PointCloud;
using pcl::PCLBase <PointT>::input_;
using pcl::PCLBase <PointT>::indices_;
using pcl::PCLBase <PointT>::initCompute;
using pcl::PCLBase <PointT>::deinitCompute;
public:
/** \brief Constructor that sets default values for member variables. */
GeoRegionGrowing ();
/** \brief This destructor destroys the cloud, normals and search method used for
* finding KNN. In other words it frees memory.
*/
virtual
~GeoRegionGrowing ();
/** \brief Get the minimum number of points that a cluster needs to contain in order to be considered valid. */
int
getMinClusterSize ();
/** \brief Set the minimum number of points that a cluster needs to contain in order to be considered valid. */
void
setMinClusterSize (int min_cluster_size);
/** \brief Get the maximum number of points that a cluster needs to contain in order to be considered valid. */
int
getMaxClusterSize ();
/** \brief Set the maximum number of points that a cluster needs to contain in order to be considered valid. */
void
setMaxClusterSize (int max_cluster_size);
/** \brief Returns the flag value. This flag signalizes which mode of algorithm will be used.
* If it is set to true than it will work as said in the article. This means that
* it will be testing the angle between normal of the current point and it's neighbours normal.
* Otherwise, it will be testing the angle between normal of the current point
* and normal of the initial point that was chosen for growing new segment.
*/
bool
getSmoothModeFlag () const;
/** \brief This function allows to turn on/off the smoothness constraint.
* \param[in] value new mode value, if set to true then the smooth version will be used.
*/
void
setSmoothModeFlag (bool value);
/** \brief Returns the flag that signalize if the curvature test is turned on/off. */
bool
getCurvatureTestFlag () const;
/** \brief Allows to turn on/off the curvature test. Note that at least one test
* (residual or curvature) must be turned on. If you are turning curvature test off
* then residual test will be turned on automatically.
* \param[in] value new value for curvature test. If set to true then the test will be turned on
*/
virtual void
setCurvatureTestFlag (bool value);
/** \brief Returns the flag that signalize if the residual test is turned on/off. */
bool
getResidualTestFlag () const;
/** \brief
* Allows to turn on/off the residual test. Note that at least one test
* (residual or curvature) must be turned on. If you are turning residual test off
* then curvature test will be turned on automatically.
* \param[in] value new value for residual test. If set to true then the test will be turned on
*/
virtual void
setResidualTestFlag (bool value);
/** \brief Returns smoothness threshold. */
float
getSmoothnessThreshold () const;
/** \brief Allows to set smoothness threshold used for testing the points.
* \param[in] theta new threshold value for the angle between normals
*/
void
setSmoothnessThreshold (float theta);
/** \brief Returns residual threshold. */
float
getResidualThreshold () const;
/** \brief Allows to set residual threshold used for testing the points.
* \param[in] residual new threshold value for residual testing
*/
void
setResidualThreshold (float residual);
/** \brief Returns curvature threshold. */
float
getCurvatureThreshold () const;
/** \brief Allows to set curvature threshold used for testing the points.
* \param[in] curvature new threshold value for curvature testing
*/
void
setCurvatureThreshold (float curvature);
/** \brief Returns the number of nearest neighbours used for KNN. */
unsigned int
getNumberOfNeighbours () const;
/** \brief Allows to set the number of neighbours. For more information check the article.
* \param[in] neighbour_number number of neighbours to use
*/
void
setNumberOfNeighbours (unsigned int neighbour_number);
/** \brief Returns the pointer to the search method that is used for KNN. */
KdTreePtr
getSearchMethod () const;
/** \brief Allows to set search method that will be used for finding KNN.
* \param[in] search search method to use
*/
void
setSearchMethod (const KdTreePtr& tree);
/** \brief Returns normals. */
NormalPtr
getInputNormals () const;
/** \brief This method sets the normals. They are needed for the algorithm, so if
* no normals will be set, the algorithm would not be able to segment the points.
* \param[in] norm normals that will be used in the algorithm
*/
void
setInputNormals (const NormalPtr& norm);
/** \brief This method launches the segmentation algorithm and returns the clusters that were
* obtained during the segmentation.
* \param[out] clusters clusters that were obtained. Each cluster is an array of point indices.
*/
virtual void
extract (std::vector <pcl::PointIndices>& clusters);
/** \brief For a given point this function builds a segment to which it belongs and returns this segment.
* \param[in] index index of the initial point which will be the seed for growing a segment.
* \param[out] cluster cluster to which the point belongs.
*/
virtual void
getSegmentFromPoint (int index, pcl::PointIndices& cluster);
/** \brief If the cloud was successfully segmented, then function
* returns colored cloud. Otherwise it returns an empty pointer.
* Points that belong to the same segment have the same color.
* But this function doesn't guarantee that different segments will have different
* color(it all depends on RNG). Points that were not listed in the indices array will have red color.
*/
pcl::PointCloud<pcl::PointXYZRGB>::Ptr
getColoredCloud ();
/** \brief If the cloud was successfully segmented, then function
* returns colored cloud. Otherwise it returns an empty pointer.
* Points that belong to the same segment have the same color.
* But this function doesn't guarantee that different segments will have different
* color(it all depends on RNG). Points that were not listed in the indices array will have red color.
*/
pcl::PointCloud<pcl::PointXYZRGBA>::Ptr
getColoredCloudRGBA ();
protected:
/** \brief This method simply checks if it is possible to execute the segmentation algorithm with
* the current settings. If it is possible then it returns true.
*/
virtual bool
prepareForSegmentation ();
/** \brief This method finds KNN for each point and saves them to the array
* because the algorithm needs to find KNN a few times.
*/
virtual void
findPointNeighbours ();
/** \brief This function implements the algorithm described in the article
* "Segmentation of point clouds using smoothness constraint"
* by T. Rabbania, F. A. van den Heuvelb, G. Vosselmanc.
*/
void
applySmoothRegionGrowingAlgorithm ();
/** \brief This method grows a segment for the given seed point. And returns the number of its points.
* \param[in] initial_seed index of the point that will serve as the seed point
* \param[in] segment_number indicates which number this segment will have
*/
int
growRegion (int initial_seed, int segment_number);
/** \brief This function is checking if the point with index 'nghbr' belongs to the segment.
* If so, then it returns true. It also checks if this point can serve as the seed.
* \param[in] initial_seed index of the initial point that was passed to the growRegion() function
* \param[in] point index of the current seed point
* \param[in] nghbr index of the point that is neighbour of the current seed
* \param[out] is_a_seed this value is set to true if the point with index 'nghbr' can serve as the seed
*/
virtual bool
validatePoint (int initial_seed, int point, int nghbr, bool& is_a_seed) const;
/** \brief This function simply assembles the regions from list of point labels.
* \param[out] clusters clusters that were obtained during the segmentation process.
* Each cluster is an array of point indices.
*/
void
assembleRegions ();
protected:
/** \brief Stores the minimum number of points that a cluster needs to contain in order to be considered valid. */
int min_pts_per_cluster_;
/** \brief Stores the maximum number of points that a cluster needs to contain in order to be considered valid. */
int max_pts_per_cluster_;
/** \brief Flag that signalizes if the smoothness constraint will be used. */
bool smooth_mode_flag_;
/** \brief If set to true then curvature test will be done during segmentation. */
bool curvature_flag_;
/** \brief If set to true then residual test will be done during segmentation. */
bool residual_flag_;
/** \brief Thershold used for testing the smoothness between points. */
float theta_threshold_;
/** \brief Thershold used in residual test. */
float residual_threshold_;
/** \brief Thershold used in curvature test. */
float curvature_threshold_;
/** \brief Number of neighbours to find. */
unsigned int neighbour_number_;
/** \brief Serch method that will be used for KNN. */
KdTreePtr search_;
/** \brief Contains normals of the points that will be segmented. */
NormalPtr normals_;
/** \brief Contains neighbours of each point. */
std::vector<std::vector<int> > point_neighbours_;
/** \brief Point labels that tells to which segment each point belongs. */
std::vector<int> point_labels_;
/** \brief If set to true then normal/smoothness test will be done during segmentation.
* It is always set to true for the usual region growing algorithm. It is used for turning on/off the test
* for smoothness in the child class RegionGrowingRGB.*/
bool normal_flag_;
/** \brief Tells how much points each segment contains. Used for reserving memory. */
std::vector<int> num_pts_in_segment_;
/** \brief After the segmentation it will contain the segments. */
std::vector <pcl::PointIndices> clusters_;
/** \brief Stores the number of segments. */
int number_of_segments_;
public:
EIGEN_MAKE_ALIGNED_OPERATOR_NEW
};
/** \brief This function is used as a comparator for sorting. */
inline bool
comparePair (std::pair<float, int> i, std::pair<float, int> j)
{
return (i.first < j.first);
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
template <typename PointT, typename NormalT>
GeoRegionGrowing<PointT, NormalT>::GeoRegionGrowing () :
min_pts_per_cluster_ (1),
max_pts_per_cluster_ (std::numeric_limits<int>::max ()),
smooth_mode_flag_ (false),
curvature_flag_ (true),
residual_flag_ (true),
theta_threshold_ (30.0f / 180.0f * static_cast<float> (M_PI)),
residual_threshold_ (0.05f),
curvature_threshold_ (0.05f),
neighbour_number_ (30),
search_ (),
normals_ (),
point_neighbours_ (0),
point_labels_ (0),
normal_flag_ (true),
num_pts_in_segment_ (0),
clusters_ (0),
number_of_segments_ (0)
{
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
template <typename PointT, typename NormalT>
GeoRegionGrowing<PointT, NormalT>::~GeoRegionGrowing ()
{
if (search_ != 0)
search_.reset ();
if (normals_ != 0)
normals_.reset ();
point_neighbours_.clear ();
point_labels_.clear ();
num_pts_in_segment_.clear ();
clusters_.clear ();
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
template <typename PointT, typename NormalT> int
GeoRegionGrowing<PointT, NormalT>::getMinClusterSize ()
{
return (min_pts_per_cluster_);
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
template <typename PointT, typename NormalT> void
GeoRegionGrowing<PointT, NormalT>::setMinClusterSize (int min_cluster_size)
{
min_pts_per_cluster_ = min_cluster_size;
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
template <typename PointT, typename NormalT> int
GeoRegionGrowing<PointT, NormalT>::getMaxClusterSize ()
{
return (max_pts_per_cluster_);
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
template <typename PointT, typename NormalT> void
GeoRegionGrowing<PointT, NormalT>::setMaxClusterSize (int max_cluster_size)
{
max_pts_per_cluster_ = max_cluster_size;
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
template <typename PointT, typename NormalT> bool
GeoRegionGrowing<PointT, NormalT>::getSmoothModeFlag () const
{
return (smooth_mode_flag_);
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
template <typename PointT, typename NormalT> void
GeoRegionGrowing<PointT, NormalT>::setSmoothModeFlag (bool value)
{
smooth_mode_flag_ = value;
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
template <typename PointT, typename NormalT> bool
GeoRegionGrowing<PointT, NormalT>::getCurvatureTestFlag () const
{
return (curvature_flag_);
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
template <typename PointT, typename NormalT> void
GeoRegionGrowing<PointT, NormalT>::setCurvatureTestFlag (bool value)
{
curvature_flag_ = value;
if (curvature_flag_ == false && residual_flag_ == false)
residual_flag_ = true;
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
template <typename PointT, typename NormalT> bool
GeoRegionGrowing<PointT, NormalT>::getResidualTestFlag () const
{
return (residual_flag_);
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
template <typename PointT, typename NormalT> void
GeoRegionGrowing<PointT, NormalT>::setResidualTestFlag (bool value)
{
residual_flag_ = value;
if (curvature_flag_ == false && residual_flag_ == false)
curvature_flag_ = true;
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
template <typename PointT, typename NormalT> float
GeoRegionGrowing<PointT, NormalT>::getSmoothnessThreshold () const
{
return (theta_threshold_);
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
template <typename PointT, typename NormalT> void
GeoRegionGrowing<PointT, NormalT>::setSmoothnessThreshold (float theta)
{
theta_threshold_ = theta;
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
template <typename PointT, typename NormalT> float
GeoRegionGrowing<PointT, NormalT>::getResidualThreshold () const
{
return (residual_threshold_);
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
template <typename PointT, typename NormalT> void
GeoRegionGrowing<PointT, NormalT>::setResidualThreshold (float residual)
{
residual_threshold_ = residual;
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
template <typename PointT, typename NormalT> float
GeoRegionGrowing<PointT, NormalT>::getCurvatureThreshold () const
{
return (curvature_threshold_);
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
template <typename PointT, typename NormalT> void
GeoRegionGrowing<PointT, NormalT>::setCurvatureThreshold (float curvature)
{
curvature_threshold_ = curvature;
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
template <typename PointT, typename NormalT> unsigned int
GeoRegionGrowing<PointT, NormalT>::getNumberOfNeighbours () const
{
return (neighbour_number_);
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
template <typename PointT, typename NormalT> void
GeoRegionGrowing<PointT, NormalT>::setNumberOfNeighbours (unsigned int neighbour_number)
{
neighbour_number_ = neighbour_number;
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
template <typename PointT, typename NormalT> typename GeoRegionGrowing<PointT, NormalT>::KdTreePtr
GeoRegionGrowing<PointT, NormalT>::getSearchMethod () const
{
return (search_);
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
template <typename PointT, typename NormalT> void
GeoRegionGrowing<PointT, NormalT>::setSearchMethod (const KdTreePtr& tree)
{
if (search_ != 0)
search_.reset ();
search_ = tree;
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
template <typename PointT, typename NormalT> typename GeoRegionGrowing<PointT, NormalT>::NormalPtr
GeoRegionGrowing<PointT, NormalT>::getInputNormals () const
{
return (normals_);
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
template <typename PointT, typename NormalT> void
GeoRegionGrowing<PointT, NormalT>::setInputNormals (const NormalPtr& norm)
{
if (normals_ != 0)
normals_.reset ();
normals_ = norm;
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
template <typename PointT, typename NormalT> void
GeoRegionGrowing<PointT, NormalT>::extract (std::vector <pcl::PointIndices>& clusters)
{
clusters_.clear ();
clusters.clear ();
point_neighbours_.clear ();
point_labels_.clear ();
num_pts_in_segment_.clear ();
number_of_segments_ = 0;
bool segmentation_is_possible = initCompute ();
if ( !segmentation_is_possible )
{
deinitCompute ();
return;
}
segmentation_is_possible = prepareForSegmentation ();
if ( !segmentation_is_possible )
{
deinitCompute ();
return;
}
findPointNeighbours ();
applySmoothRegionGrowingAlgorithm ();
assembleRegions ();
clusters.resize (clusters_.size ());
std::vector<pcl::PointIndices>::iterator cluster_iter_input = clusters.begin ();
for (std::vector<pcl::PointIndices>::const_iterator cluster_iter = clusters_.begin (); cluster_iter != clusters_.end (); cluster_iter++)
{
if ((cluster_iter->indices.size () >= min_pts_per_cluster_) &&
(cluster_iter->indices.size () <= max_pts_per_cluster_))
{
*cluster_iter_input = *cluster_iter;
cluster_iter_input++;
}
}
clusters_ = std::vector<pcl::PointIndices> (clusters.begin (), cluster_iter_input);
clusters.resize(clusters_.size());
deinitCompute ();
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
template <typename PointT, typename NormalT> bool
GeoRegionGrowing<PointT, NormalT>::prepareForSegmentation ()
{
// if user forgot to pass point cloud or if it is empty
if ( input_->points.size () == 0 )
return (false);
// if user forgot to pass normals or the sizes of point and normal cloud are different
if ( normals_ == 0 || input_->points.size () != normals_->points.size () )
return (false);
// if residual test is on then we need to check if all needed parameters were correctly initialized
if (residual_flag_)
{
if (residual_threshold_ <= 0.0f)
return (false);
}
// if curvature test is on ...
// if (curvature_flag_)
// {
// in this case we do not need to check anything that related to it
// so we simply commented it
// }
// from here we check those parameters that are always valuable
if (neighbour_number_ == 0)
return (false);
// if user didn't set search method
if (!search_)
search_.reset (new pcl::search::KdTree<PointT>);
if (indices_)
{
if (indices_->empty ())
PCL_ERROR ("[pcl::RegionGrowing::prepareForSegmentation] Empty given indices!\n");
search_->setInputCloud (input_, indices_);
}
else
search_->setInputCloud (input_);
return (true);
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
template <typename PointT, typename NormalT> void
GeoRegionGrowing<PointT, NormalT>::findPointNeighbours ()
{
int point_number = static_cast<int> (indices_->size ());
std::vector<int> temp_neighbours;
point_neighbours_.resize (input_->points.size (), temp_neighbours);
#pragma omp parallel for
for (int i_point = 0; i_point < point_number; i_point++)
{
int point_index = (*indices_)[i_point];
std::vector<int> neighbours;
std::vector<float> distances;
search_->nearestKSearch (i_point, neighbour_number_, neighbours, distances);
point_neighbours_[point_index].swap (neighbours);
}
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
template <typename PointT, typename NormalT> void
GeoRegionGrowing<PointT, NormalT>::applySmoothRegionGrowingAlgorithm ()
{
int num_of_pts = static_cast<int> (indices_->size ());
point_labels_.resize (input_->points.size (), -1);
std::vector< std::pair<float, int> > point_residual;
std::pair<float, int> pair;
point_residual.resize (num_of_pts, pair);
if (normal_flag_ == true)
{
for (int i_point = 0; i_point < num_of_pts; i_point++)
{
int point_index = (*indices_)[i_point];
point_residual[i_point].first = normals_->points[point_index].curvature;
point_residual[i_point].second = point_index;
}
std::sort (point_residual.begin (), point_residual.end (), comparePair);
}
else
{
for (int i_point = 0; i_point < num_of_pts; i_point++)
{
int point_index = (*indices_)[i_point];
point_residual[i_point].first = 0;
point_residual[i_point].second = point_index;
}
}
int seed_counter = 0;
int seed = point_residual[seed_counter].second;
int segmented_pts_num = 0;
int number_of_segments = 0;
while (segmented_pts_num < num_of_pts)
{
int pts_in_segment;
pts_in_segment = growRegion (seed, number_of_segments);
segmented_pts_num += pts_in_segment;
num_pts_in_segment_.push_back (pts_in_segment);
number_of_segments++;
//find next point that is not segmented yet
for (int i_seed = seed_counter + 1; i_seed < num_of_pts; i_seed++)
{
int index = point_residual[i_seed].second;
if (point_labels_[index] == -1)
{
seed = index;
break;
}
}
}
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
template <typename PointT, typename NormalT> int
GeoRegionGrowing<PointT, NormalT>::growRegion (int initial_seed, int segment_number)
{
std::queue<int> seeds;
seeds.push (initial_seed);
point_labels_[initial_seed] = segment_number;
int num_pts_in_segment = 1;
while (!seeds.empty ())
{
int curr_seed;
curr_seed = seeds.front ();
seeds.pop ();
size_t i_nghbr = 0;
while ( i_nghbr < neighbour_number_ && i_nghbr < point_neighbours_[curr_seed].size () )
{
int index = point_neighbours_[curr_seed][i_nghbr];
if (point_labels_[index] != -1)
{
i_nghbr++;
continue;
}
bool is_a_seed = false;
bool belongs_to_segment = validatePoint (initial_seed, curr_seed, index, is_a_seed);
if (belongs_to_segment == false)
{
i_nghbr++;
continue;
}
point_labels_[index] = segment_number;
num_pts_in_segment++;
if (is_a_seed)
{
seeds.push (index);
}
i_nghbr++;
}// next neighbour
}// next seed
return (num_pts_in_segment);
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
template <typename PointT, typename NormalT> bool
GeoRegionGrowing<PointT, NormalT>::validatePoint (int initial_seed, int point, int nghbr, bool& is_a_seed) const
{
is_a_seed = true;
float cosine_threshold = cosf (theta_threshold_);
float cosine_residual_threshold = cosf(residual_threshold_);
float data[4];
data[0] = input_->points[point].data[0];
data[1] = input_->points[point].data[1];
data[2] = input_->points[point].data[2];
data[3] = input_->points[point].data[3];
Eigen::Map<Eigen::Vector3f> initial_point (static_cast<float*> (data));
Eigen::Map<Eigen::Vector3f> initial_normal (static_cast<float*> (normals_->points[point].normal));
//check the angle between normals
Eigen::Map<Eigen::Vector3f> nghbr_normal (static_cast<float*> (normals_->points[nghbr].normal));
float dot_product = fabsf (nghbr_normal.dot (initial_normal));
if (dot_product < cosine_threshold)
{
return (false);
}
if (smooth_mode_flag_ == true)
{
// check the curvature if needed
if (curvature_flag_ && normals_->points[nghbr].curvature > curvature_threshold_)
{
is_a_seed = false;
}
}
else
{
// check the curvature if needed
if (curvature_flag_ && normals_->points[nghbr].curvature > curvature_threshold_)
{
is_a_seed = false;
}
// check the residual if needed
Eigen::Map<Eigen::Vector3f> nghbr_normal (static_cast<float*> (normals_->points[nghbr].normal));
Eigen::Map<Eigen::Vector3f> initial_seed_normal (static_cast<float*> (normals_->points[initial_seed].normal));
float dot_product = fabsf (nghbr_normal.dot (initial_seed_normal));
if (dot_product < cosine_residual_threshold)
{
is_a_seed = false;
}
}
return (true);
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
template <typename PointT, typename NormalT> void
GeoRegionGrowing<PointT, NormalT>::assembleRegions ()
{
int number_of_segments = static_cast<int> (num_pts_in_segment_.size ());
int number_of_points = static_cast<int> (input_->points.size ());
pcl::PointIndices segment;
clusters_.resize (number_of_segments, segment);
for (int i_seg = 0; i_seg < number_of_segments; i_seg++)
{
clusters_[i_seg].indices.resize ( num_pts_in_segment_[i_seg], 0);
}
std::vector<int> counter;
counter.resize (number_of_segments, 0);
for (int i_point = 0; i_point < number_of_points; i_point++)
{
int segment_index = point_labels_[i_point];
if (segment_index != -1)
{
int point_index = counter[segment_index];
clusters_[segment_index].indices[point_index] = i_point;
counter[segment_index] = point_index + 1;
}
}
number_of_segments_ = number_of_segments;
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
template <typename PointT, typename NormalT> void
GeoRegionGrowing<PointT, NormalT>::getSegmentFromPoint (int index, pcl::PointIndices& cluster)
{
cluster.indices.clear ();
bool segmentation_is_possible = initCompute ();
if ( !segmentation_is_possible )
{
deinitCompute ();
return;
}
// first of all we need to find out if this point belongs to cloud
bool point_was_found = false;
int number_of_points = static_cast <int> (indices_->size ());
for (size_t point = 0; point < number_of_points; point++)
if ( (*indices_)[point] == index)
{
point_was_found = true;
break;
}
if (point_was_found)
{
if (clusters_.empty ())
{
point_neighbours_.clear ();
point_labels_.clear ();
num_pts_in_segment_.clear ();
number_of_segments_ = 0;
segmentation_is_possible = prepareForSegmentation ();
if ( !segmentation_is_possible )
{
deinitCompute ();
return;
}
findPointNeighbours ();
applySmoothRegionGrowingAlgorithm ();
assembleRegions ();
}
// if we have already made the segmentation, then find the segment
// to which this point belongs
std::vector <pcl::PointIndices>::iterator i_segment;
for (i_segment = clusters_.begin (); i_segment != clusters_.end (); i_segment++)
{
bool segment_was_found = false;
for (size_t i_point = 0; i_point < i_segment->indices.size (); i_point++)
{
if (i_segment->indices[i_point] == index)
{
segment_was_found = true;
cluster.indices.clear ();
cluster.indices.reserve (i_segment->indices.size ());
std::copy (i_segment->indices.begin (), i_segment->indices.end (), std::back_inserter (cluster.indices));
break;
}
}
if (segment_was_found)
{
break;
}
}// next segment
}// end if point was found
deinitCompute ();
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
template <typename PointT, typename NormalT> pcl::PointCloud<pcl::PointXYZRGB>::Ptr
GeoRegionGrowing<PointT, NormalT>::getColoredCloud ()
{
pcl::PointCloud<pcl::PointXYZRGB>::Ptr colored_cloud;
if (!clusters_.empty ())
{
colored_cloud = (new pcl::PointCloud<pcl::PointXYZRGB>)->makeShared ();
srand (static_cast<unsigned int> (time (0)));
std::vector<unsigned char> colors;
for (size_t i_segment = 0; i_segment < clusters_.size (); i_segment++)
{
colors.push_back (static_cast<unsigned char> (rand () % 256));
colors.push_back (static_cast<unsigned char> (rand () % 256));
colors.push_back (static_cast<unsigned char> (rand () % 256));
}
colored_cloud->width = input_->width;
colored_cloud->height = input_->height;
colored_cloud->is_dense = input_->is_dense;
for (size_t i_point = 0; i_point < input_->points.size (); i_point++)
{
pcl::PointXYZRGB point;
point.x = *(input_->points[i_point].data);
point.y = *(input_->points[i_point].data + 1);
point.z = *(input_->points[i_point].data + 2);
point.r = 255;
point.g = 0;
point.b = 0;
colored_cloud->points.push_back (point);
}
std::vector< pcl::PointIndices >::iterator i_segment;
int next_color = 0;
for (i_segment = clusters_.begin (); i_segment != clusters_.end (); i_segment++)
{
std::vector<int>::iterator i_point;
for (i_point = i_segment->indices.begin (); i_point != i_segment->indices.end (); i_point++)
{
int index;
index = *i_point;
colored_cloud->points[index].r = colors[3 * next_color];
colored_cloud->points[index].g = colors[3 * next_color + 1];
colored_cloud->points[index].b = colors[3 * next_color + 2];
}
next_color++;
}
}
return (colored_cloud);
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
template <typename PointT, typename NormalT> pcl::PointCloud<pcl::PointXYZRGBA>::Ptr
GeoRegionGrowing<PointT, NormalT>::getColoredCloudRGBA ()
{
pcl::PointCloud<pcl::PointXYZRGBA>::Ptr colored_cloud;
if (!clusters_.empty ())
{
colored_cloud = (new pcl::PointCloud<pcl::PointXYZRGBA>)->makeShared ();
srand (static_cast<unsigned int> (time (0)));
std::vector<unsigned char> colors;
for (size_t i_segment = 0; i_segment < clusters_.size (); i_segment++)
{
colors.push_back (static_cast<unsigned char> (rand () % 256));
colors.push_back (static_cast<unsigned char> (rand () % 256));
colors.push_back (static_cast<unsigned char> (rand () % 256));
}
colored_cloud->width = input_->width;
colored_cloud->height = input_->height;
colored_cloud->is_dense = input_->is_dense;
for (size_t i_point = 0; i_point < input_->points.size (); i_point++)
{
pcl::PointXYZRGBA point;
point.x = *(input_->points[i_point].data);
point.y = *(input_->points[i_point].data + 1);
point.z = *(input_->points[i_point].data + 2);
point.r = 255;
point.g = 0;
point.b = 0;
point.a = 0;
colored_cloud->points.push_back (point);
}
std::vector< pcl::PointIndices >::iterator i_segment;
int next_color = 0;
for (i_segment = clusters_.begin (); i_segment != clusters_.end (); i_segment++)
{
std::vector<int>::iterator i_point;
for (i_point = i_segment->indices.begin (); i_point != i_segment->indices.end (); i_point++)
{
int index;
index = *i_point;
colored_cloud->points[index].r = colors[3 * next_color];
colored_cloud->points[index].g = colors[3 * next_color + 1];
colored_cloud->points[index].b = colors[3 * next_color + 2];
}
next_color++;
}
}
return (colored_cloud);
}
|
GB_binop__bxnor_int32.c |
//------------------------------------------------------------------------------
// GB_binop: hard-coded functions for each built-in binary operator
//------------------------------------------------------------------------------
// SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2022, All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
//------------------------------------------------------------------------------
// If this file is in the Generated2/ folder, do not edit it
// (it is auto-generated from Generator/*).
#include "GB.h"
#ifndef GBCOMPACT
#include "GB_emult.h"
#include "GB_control.h"
#include "GB_ek_slice.h"
#include "GB_dense.h"
#include "GB_atomics.h"
#include "GB_bitmap_assign_methods.h"
#include "GB_binop__include.h"
// C=binop(A,B) is defined by the following types and operators:
// A+B function (eWiseAdd): GB (_AaddB__bxnor_int32)
// A.*B function (eWiseMult): GB (_AemultB_08__bxnor_int32)
// A.*B function (eWiseMult): GB (_AemultB_02__bxnor_int32)
// A.*B function (eWiseMult): GB (_AemultB_04__bxnor_int32)
// A.*B function (eWiseMult): GB (_AemultB_bitmap__bxnor_int32)
// A*D function (colscale): GB ((none))
// D*A function (rowscale): GB ((none))
// C+=B function (dense accum): GB (_Cdense_accumB__bxnor_int32)
// C+=b function (dense accum): GB (_Cdense_accumb__bxnor_int32)
// C+=A+B function (dense ewise3): GB ((none))
// C=A+B function (dense ewise3): GB (_Cdense_ewise3_noaccum__bxnor_int32)
// C=scalar+B GB (_bind1st__bxnor_int32)
// C=scalar+B' GB (_bind1st_tran__bxnor_int32)
// C=A+scalar GB (_bind2nd__bxnor_int32)
// C=A'+scalar GB (_bind2nd_tran__bxnor_int32)
// C type: int32_t
// A type: int32_t
// A pattern? 0
// B type: int32_t
// B pattern? 0
// BinaryOp: cij = ~((aij) ^ (bij))
#define GB_ATYPE \
int32_t
#define GB_BTYPE \
int32_t
#define GB_CTYPE \
int32_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) \
int32_t aij = GBX (Ax, pA, A_iso)
// true if values of A are not used
#define GB_A_IS_PATTERN \
0 \
// bij = Bx [pB]
#define GB_GETB(bij,Bx,pB,B_iso) \
int32_t bij = GBX (Bx, pB, B_iso)
// true if values of B are not used
#define GB_B_IS_PATTERN \
0 \
// declare scalar of the same type as C
#define GB_CTYPE_SCALAR(t) \
int32_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_BXNOR || GxB_NO_INT32 || GxB_NO_BXNOR_INT32)
//------------------------------------------------------------------------------
// C += A+B, all 3 matrices dense
//------------------------------------------------------------------------------
#if 0
// The op must be MIN, MAX, PLUS, MINUS, RMINUS, TIMES, DIV, or RDIV.
void GB ((none))
(
GrB_Matrix C,
const GrB_Matrix A,
const GrB_Matrix B,
const int nthreads
)
{
#include "GB_dense_ewise3_accum_template.c"
}
#endif
//------------------------------------------------------------------------------
// C = A+B, all 3 matrices dense
//------------------------------------------------------------------------------
void GB (_Cdense_ewise3_noaccum__bxnor_int32)
(
GrB_Matrix C,
const GrB_Matrix A,
const GrB_Matrix B,
const int nthreads
)
{
#include "GB_dense_ewise3_noaccum_template.c"
}
//------------------------------------------------------------------------------
// C += B, accumulate a sparse matrix into a dense matrix
//------------------------------------------------------------------------------
GrB_Info GB (_Cdense_accumB__bxnor_int32)
(
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__bxnor_int32)
(
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 int32_t
int32_t bwork = (*((int32_t *) p_bwork)) ;
#include "GB_dense_subassign_22_template.c"
return (GrB_SUCCESS) ;
}
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// C = A*D, column scale with diagonal D matrix
//------------------------------------------------------------------------------
#if 0
GrB_Info GB ((none))
(
GrB_Matrix C,
const GrB_Matrix A,
const GrB_Matrix D,
const int64_t *A_ek_slicing, const int A_ntasks, const int A_nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
int32_t *restrict Cx = (int32_t *) C->x ;
#include "GB_AxB_colscale_template.c"
return (GrB_SUCCESS) ;
#endif
}
#endif
//------------------------------------------------------------------------------
// C = D*B, row scale with diagonal D matrix
//------------------------------------------------------------------------------
#if 0
GrB_Info GB ((none))
(
GrB_Matrix C,
const GrB_Matrix D,
const GrB_Matrix B,
int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
int32_t *restrict Cx = (int32_t *) C->x ;
#include "GB_AxB_rowscale_template.c"
return (GrB_SUCCESS) ;
#endif
}
#endif
//------------------------------------------------------------------------------
// eWiseAdd: C=A+B, C<M>=A+B, C<!M>=A+B
//------------------------------------------------------------------------------
GrB_Info GB (_AaddB__bxnor_int32)
(
GrB_Matrix C,
const int C_sparsity,
const GrB_Matrix M,
const bool Mask_struct,
const bool Mask_comp,
const GrB_Matrix A,
const GrB_Matrix B,
const bool is_eWiseUnion,
const GB_void *alpha_scalar_in,
const GB_void *beta_scalar_in,
const bool Ch_is_Mh,
const int64_t *restrict C_to_M,
const int64_t *restrict C_to_A,
const int64_t *restrict C_to_B,
const GB_task_struct *restrict TaskList,
const int C_ntasks,
const int C_nthreads,
GB_Context Context
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
GB_WERK_DECLARE (M_ek_slicing, int64_t) ;
GB_WERK_DECLARE (A_ek_slicing, int64_t) ;
GB_WERK_DECLARE (B_ek_slicing, int64_t) ;
int32_t alpha_scalar ;
int32_t beta_scalar ;
if (is_eWiseUnion)
{
alpha_scalar = (*((int32_t *) alpha_scalar_in)) ;
beta_scalar = (*((int32_t *) beta_scalar_in )) ;
}
#include "GB_add_template.c"
GB_FREE_WORKSPACE ;
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// eWiseMult: C=A.*B, C<M>=A.*B, or C<M!>=A.*B where C is sparse/hyper
//------------------------------------------------------------------------------
GrB_Info GB (_AemultB_08__bxnor_int32)
(
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__bxnor_int32)
(
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__bxnor_int32)
(
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__bxnor_int32)
(
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__bxnor_int32)
(
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
int32_t *Cx = (int32_t *) Cx_output ;
int32_t x = (*((int32_t *) x_input)) ;
int32_t *Bx = (int32_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 ;
int32_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__bxnor_int32)
(
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 ;
int32_t *Cx = (int32_t *) Cx_output ;
int32_t *Ax = (int32_t *) Ax_input ;
int32_t y = (*((int32_t *) y_input)) ;
#pragma omp parallel for num_threads(nthreads) schedule(static)
for (p = 0 ; p < anz ; p++)
{
if (!GBB (Ab, p)) continue ;
int32_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) \
{ \
int32_t aij = GBX (Ax, pA, false) ; \
Cx [pC] = ~((x) ^ (aij)) ; \
}
GrB_Info GB (_bind1st_tran__bxnor_int32)
(
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 \
int32_t
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
int32_t x = (*((const int32_t *) x_input)) ;
#include "GB_unop_transpose.c"
return (GrB_SUCCESS) ;
#endif
#undef GB_ATYPE
#define GB_ATYPE \
int32_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) \
{ \
int32_t aij = GBX (Ax, pA, false) ; \
Cx [pC] = ~((aij) ^ (y)) ; \
}
GrB_Info GB (_bind2nd_tran__bxnor_int32)
(
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
int32_t y = (*((const int32_t *) y_input)) ;
#include "GB_unop_transpose.c"
return (GrB_SUCCESS) ;
#endif
}
#endif
|
3d7pt.lbpar.c | #include <omp.h>
#include <math.h>
#define ceild(n,d) ceil(((double)(n))/((double)(d)))
#define floord(n,d) floor(((double)(n))/((double)(d)))
#define max(x,y) ((x) > (y)? (x) : (y))
#define min(x,y) ((x) < (y)? (x) : (y))
/*
* Order-1, 3D 7 point stencil
* Adapted from PLUTO and Pochoir test bench
*
* Tareq Malas
*/
#include <stdio.h>
#include <stdlib.h>
#include <sys/time.h>
#ifdef LIKWID_PERFMON
#include <likwid.h>
#endif
#include "print_utils.h"
#define TESTS 2
#define MAX(a,b) ((a) > (b) ? a : b)
#define MIN(a,b) ((a) < (b) ? a : b)
/* Subtract the `struct timeval' values X and Y,
* storing the result in RESULT.
*
* Return 1 if the difference is negative, otherwise 0.
*/
int timeval_subtract(struct timeval *result, struct timeval *x, struct timeval *y)
{
/* Perform the carry for the later subtraction by updating y. */
if (x->tv_usec < y->tv_usec)
{
int nsec = (y->tv_usec - x->tv_usec) / 1000000 + 1;
y->tv_usec -= 1000000 * nsec;
y->tv_sec += nsec;
}
if (x->tv_usec - y->tv_usec > 1000000)
{
int nsec = (x->tv_usec - y->tv_usec) / 1000000;
y->tv_usec += 1000000 * nsec;
y->tv_sec -= nsec;
}
/* Compute the time remaining to wait.
* tv_usec is certainly positive.
*/
result->tv_sec = x->tv_sec - y->tv_sec;
result->tv_usec = x->tv_usec - y->tv_usec;
/* Return 1 if result is negative. */
return x->tv_sec < y->tv_sec;
}
int main(int argc, char *argv[])
{
int t, i, j, k, test;
int Nx, Ny, Nz, Nt;
if (argc > 3) {
Nx = atoi(argv[1])+2;
Ny = atoi(argv[2])+2;
Nz = atoi(argv[3])+2;
}
if (argc > 4)
Nt = atoi(argv[4]);
double ****A = (double ****) malloc(sizeof(double***)*2);
A[0] = (double ***) malloc(sizeof(double**)*Nz);
A[1] = (double ***) malloc(sizeof(double**)*Nz);
for(i=0; i<Nz; i++){
A[0][i] = (double**) malloc(sizeof(double*)*Ny);
A[1][i] = (double**) malloc(sizeof(double*)*Ny);
for(j=0;j<Ny;j++){
A[0][i][j] = (double*) malloc(sizeof(double)*Nx);
A[1][i][j] = (double*) malloc(sizeof(double)*Nx);
}
}
// tile size information, including extra element to decide the list length
int *tile_size = (int*) malloc(sizeof(int));
tile_size[0] = -1;
// The list is modified here before source-to-source transformations
tile_size = (int*) realloc((void *)tile_size, sizeof(int)*5);
tile_size[0] = 16;
tile_size[1] = 16;
tile_size[2] = 32;
tile_size[3] = 64;
tile_size[4] = -1;
// for timekeeping
int ts_return = -1;
struct timeval start, end, result;
double tdiff = 0.0, min_tdiff=1.e100;
const int BASE = 1024;
const double alpha = 0.0876;
const double beta = 0.0765;
// initialize variables
//
srand(42);
for (i = 1; i < Nz; i++) {
for (j = 1; j < Ny; j++) {
for (k = 1; k < Nx; k++) {
A[0][i][j][k] = 1.0 * (rand() % BASE);
}
}
}
#ifdef LIKWID_PERFMON
LIKWID_MARKER_INIT;
#pragma omp parallel
{
LIKWID_MARKER_THREADINIT;
#pragma omp barrier
LIKWID_MARKER_START("calc");
}
#endif
int num_threads = 1;
#if defined(_OPENMP)
num_threads = omp_get_max_threads();
#endif
for(test=0; test<TESTS; test++){
gettimeofday(&start, 0);
// serial execution - Addition: 6 && Multiplication: 2
/* Copyright (C) 1991-2014 Free Software Foundation, Inc.
This file is part of the GNU C Library.
The GNU C Library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
The GNU C Library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with the GNU C Library; if not, see
<http://www.gnu.org/licenses/>. */
/* This header is separate from features.h so that the compiler can
include it implicitly at the start of every compilation. It must
not itself include <features.h> or any other header that includes
<features.h> because the implicit include comes before any feature
test macros that may be defined in a source file before it first
explicitly includes a system header. GCC knows the name of this
header in order to preinclude it. */
/* glibc's intent is to support the IEC 559 math functionality, real
and complex. If the GCC (4.9 and later) predefined macros
specifying compiler intent are available, use them to determine
whether the overall intent is to support these features; otherwise,
presume an older compiler has intent to support these features and
define these macros by default. */
/* wchar_t uses ISO/IEC 10646 (2nd ed., published 2011-03-15) /
Unicode 6.0. */
/* We do not support C11 <threads.h>. */
int t1, t2, t3, t4, t5, t6, t7, t8;
int lb, ub, lbp, ubp, lb2, ub2;
register int lbv, ubv;
/* Start of CLooG code */
if ((Nt >= 2) && (Nx >= 3) && (Ny >= 3) && (Nz >= 3)) {
for (t1=-1;t1<=floord(Nt-2,8);t1++) {
lbp=max(ceild(t1,2),ceild(16*t1-Nt+3,16));
ubp=min(floord(Nt+Nz-4,16),floord(8*t1+Nz+5,16));
#pragma omp parallel for private(lbv,ubv,t3,t4,t5,t6,t7,t8)
for (t2=lbp;t2<=ubp;t2++) {
for (t3=max(max(0,ceild(t1-3,4)),ceild(16*t2-Nz-28,32));t3<=min(min(min(floord(Nt+Ny-4,32),floord(8*t1+Ny+13,32)),floord(16*t2+Ny+12,32)),floord(16*t1-16*t2+Nz+Ny+11,32));t3++) {
for (t4=max(max(max(0,ceild(t1-7,8)),ceild(16*t2-Nz-60,64)),ceild(32*t3-Ny-60,64));t4<=min(min(min(min(floord(Nt+Nx-4,64),floord(8*t1+Nx+13,64)),floord(16*t2+Nx+12,64)),floord(32*t3+Nx+28,64)),floord(16*t1-16*t2+Nz+Nx+11,64));t4++) {
for (t5=max(max(max(max(max(0,8*t1),16*t1-16*t2+1),16*t2-Nz+2),32*t3-Ny+2),64*t4-Nx+2);t5<=min(min(min(min(min(Nt-2,8*t1+15),16*t2+14),32*t3+30),64*t4+62),16*t1-16*t2+Nz+13);t5++) {
for (t6=max(max(16*t2,t5+1),-16*t1+16*t2+2*t5-15);t6<=min(min(16*t2+15,-16*t1+16*t2+2*t5),t5+Nz-2);t6++) {
for (t7=max(32*t3,t5+1);t7<=min(32*t3+31,t5+Ny-2);t7++) {
lbv=max(64*t4,t5+1);
ubv=min(64*t4+63,t5+Nx-2);
#pragma ivdep
#pragma vector always
for (t8=lbv;t8<=ubv;t8++) {
A[( t5 + 1) % 2][ (-t5+t6)][ (-t5+t7)][ (-t5+t8)] = ((alpha * A[ t5 % 2][ (-t5+t6)][ (-t5+t7)][ (-t5+t8)]) + (beta * (((((A[ t5 % 2][ (-t5+t6) - 1][ (-t5+t7)][ (-t5+t8)] + A[ t5 % 2][ (-t5+t6)][ (-t5+t7) - 1][ (-t5+t8)]) + A[ t5 % 2][ (-t5+t6)][ (-t5+t7)][ (-t5+t8) - 1]) + A[ t5 % 2][ (-t5+t6) + 1][ (-t5+t7)][ (-t5+t8)]) + A[ t5 % 2][ (-t5+t6)][ (-t5+t7) + 1][ (-t5+t8)]) + A[ t5 % 2][ (-t5+t6)][ (-t5+t7)][ (-t5+t8) + 1])));;
}
}
}
}
}
}
}
}
}
/* End of CLooG code */
gettimeofday(&end, 0);
ts_return = timeval_subtract(&result, &end, &start);
tdiff = (double) (result.tv_sec + result.tv_usec * 1.0e-6);
min_tdiff = min(min_tdiff, tdiff);
printf("Rank 0 TEST# %d time: %f\n", test, tdiff);
}
PRINT_RESULTS(1, "constant")
#ifdef LIKWID_PERFMON
#pragma omp parallel
{
LIKWID_MARKER_STOP("calc");
}
LIKWID_MARKER_CLOSE;
#endif
// Free allocated arrays (Causing performance degradation
/* for(i=0; i<Nz; i++){
for(j=0;j<Ny;j++){
free(A[0][i][j]);
free(A[1][i][j]);
}
free(A[0][i]);
free(A[1][i]);
}
free(A[0]);
free(A[1]);
*/
return 0;
}
|
hello_hybrid.c | #include <stdio.h>
#include "mpi.h"
#include <omp.h>
int main(int argc, char *argv[]) {
int numprocs, rank, namelen;
char processor_name[MPI_MAX_PROCESSOR_NAME];
int iam = 0, np = 1;
MPI_Init(&argc, &argv);
MPI_Comm_size(MPI_COMM_WORLD, &numprocs);
MPI_Comm_rank(MPI_COMM_WORLD, &rank);
MPI_Get_processor_name(processor_name, &namelen);
#pragma omp parallel default(shared) private(iam, np)
{
np = omp_get_num_threads();
iam = omp_get_thread_num();
printf("Hello from thread %d out of %d from process %d out of %d on %s\n",
iam, np, rank, numprocs, processor_name);
}
MPI_Finalize();
}
|
image.c | #ifndef TH_GENERIC_FILE
#define TH_GENERIC_FILE "generic/image.c"
#else
#undef MAX
#define MAX(a,b) ( ((a)>(b)) ? (a) : (b) )
#undef MIN
#define MIN(a,b) ( ((a)<(b)) ? (a) : (b) )
#undef TAPI
#define TAPI __declspec(dllimport)
#ifndef M_PI
#define M_PI 3.14159265358979323846
#endif
static void image_(Main_op_validate)( lua_State *L, THTensor *Tsrc, THTensor *Tdst){
long src_depth = 1;
long dst_depth = 1;
luaL_argcheck(L, Tsrc->nDimension==2 || Tsrc->nDimension==3, 1, "rotate: src not 2 or 3 dimensional");
luaL_argcheck(L, Tdst->nDimension==2 || Tdst->nDimension==3, 2, "rotate: dst not 2 or 3 dimensional");
if(Tdst->nDimension == 3) dst_depth = Tdst->size[0];
if(Tsrc->nDimension == 3) src_depth = Tsrc->size[0];
if( (Tdst->nDimension==3 && ( src_depth!=dst_depth)) ||
(Tdst->nDimension!=Tsrc->nDimension) )
luaL_error(L, "image.scale: src and dst depths do not match");
if( Tdst->nDimension==3 && ( src_depth!=dst_depth) )
luaL_error(L, "image.scale: src and dst depths do not match");
}
static long image_(Main_op_stride)( THTensor *T,int i){
if (T->nDimension == 2) {
if (i == 0) return 0;
else return T->stride[i-1];
}
return T->stride[i];
}
static long image_(Main_op_depth)( THTensor *T){
if(T->nDimension == 3) return T->size[0]; /* rgb or rgba */
return 1; /* greyscale */
}
static void image_(Main_scale_rowcol)(THTensor *Tsrc,
THTensor *Tdst,
long src_start,
long dst_start,
long src_stride,
long dst_stride,
long src_len,
long dst_len ) {
real *src= THTensor_(data)(Tsrc);
real *dst= THTensor_(data)(Tdst);
if ( dst_len > src_len ){
long di;
float si_f;
long si_i;
float scale = (float)(src_len - 1) / (dst_len - 1);
for( di = 0; di < dst_len - 1; di++ ) {
long dst_pos = dst_start + di*dst_stride;
si_f = di * scale; si_i = (long)si_f; si_f -= si_i;
dst[dst_pos] = (1 - si_f) * src[ src_start + si_i * src_stride ] +
si_f * src[ src_start + (si_i + 1) * src_stride ];
}
dst[ dst_start + (dst_len - 1) * dst_stride ] =
src[ src_start + (src_len - 1) * src_stride ];
}
else if ( dst_len < src_len ) {
long di;
long si0_i = 0; float si0_f = 0;
long si1_i; float si1_f;
long si;
float scale = (float)src_len / dst_len;
float acc, n;
for( di = 0; di < dst_len; di++ )
{
si1_f = (di + 1) * scale; si1_i = (long)si1_f; si1_f -= si1_i;
acc = (1 - si0_f) * src[ src_start + si0_i * src_stride ];
n = 1 - si0_f;
for( si = si0_i + 1; si < si1_i; si++ )
{
acc += src[ src_start + si * src_stride ];
n += 1;
}
if( si1_i < src_len )
{
acc += si1_f * src[ src_start + si1_i*src_stride ];
n += si1_f;
}
dst[ dst_start + di*dst_stride ] = acc / n;
si0_i = si1_i; si0_f = si1_f;
}
}
else {
long i;
for( i = 0; i < dst_len; i++ )
dst[ dst_start + i*dst_stride ] = src[ src_start + i*src_stride ];
}
}
static int image_(Main_scaleBilinear)(lua_State *L) {
THTensor *Tsrc = luaT_checkudata(L, 1, torch_Tensor);
THTensor *Tdst = luaT_checkudata(L, 2, torch_Tensor);
THTensor *Ttmp;
long dst_stride0, dst_stride1, dst_stride2, dst_width, dst_height;
long src_stride0, src_stride1, src_stride2, src_width, src_height;
long tmp_stride0, tmp_stride1, tmp_stride2, tmp_width, tmp_height;
long i, j, k;
image_(Main_op_validate)(L, Tsrc,Tdst);
int ndims;
if (Tdst->nDimension == 3) ndims = 3;
else ndims = 2;
Ttmp = THTensor_(newWithSize2d)(Tsrc->size[ndims-2], Tdst->size[ndims-1]);
dst_stride0= image_(Main_op_stride)(Tdst,0);
dst_stride1= image_(Main_op_stride)(Tdst,1);
dst_stride2= image_(Main_op_stride)(Tdst,2);
src_stride0= image_(Main_op_stride)(Tsrc,0);
src_stride1= image_(Main_op_stride)(Tsrc,1);
src_stride2= image_(Main_op_stride)(Tsrc,2);
tmp_stride0= image_(Main_op_stride)(Ttmp,0);
tmp_stride1= image_(Main_op_stride)(Ttmp,1);
tmp_stride2= image_(Main_op_stride)(Ttmp,2);
dst_width= Tdst->size[ndims-1];
dst_height= Tdst->size[ndims-2];
src_width= Tsrc->size[ndims-1];
src_height= Tsrc->size[ndims-2];
tmp_width= Ttmp->size[1];
tmp_height= Ttmp->size[0];
for(k=0;k<image_(Main_op_depth)(Tsrc);k++) {
/* compress/expand rows first */
for(j = 0; j < src_height; j++) {
image_(Main_scale_rowcol)(Tsrc,
Ttmp,
0*src_stride2+j*src_stride1+k*src_stride0,
0*tmp_stride2+j*tmp_stride1+k*tmp_stride0,
src_stride2,
tmp_stride2,
src_width,
tmp_width );
}
/* then columns */
for(i = 0; i < dst_width; i++) {
image_(Main_scale_rowcol)(Ttmp,
Tdst,
i*tmp_stride2+0*tmp_stride1+k*tmp_stride0,
i*dst_stride2+0*dst_stride1+k*dst_stride0,
tmp_stride1,
dst_stride1,
tmp_height,
dst_height );
}
}
THTensor_(free)(Ttmp);
return 0;
}
static int image_(Main_scaleSimple)(lua_State *L)
{
THTensor *Tsrc = luaT_checkudata(L, 1, torch_Tensor);
THTensor *Tdst = luaT_checkudata(L, 2, torch_Tensor);
real *src, *dst;
long dst_stride0, dst_stride1, dst_stride2, dst_width, dst_height, dst_depth;
long src_stride0, src_stride1, src_stride2, src_width, src_height, src_depth;
long i, j, k;
float scx, scy;
luaL_argcheck(L, Tsrc->nDimension==2 || Tsrc->nDimension==3, 1, "image.scale: src not 2 or 3 dimensional");
luaL_argcheck(L, Tdst->nDimension==2 || Tdst->nDimension==3, 2, "image.scale: dst not 2 or 3 dimensional");
src= THTensor_(data)(Tsrc);
dst= THTensor_(data)(Tdst);
dst_stride0 = 0;
dst_stride1 = Tdst->stride[Tdst->nDimension-2];
dst_stride2 = Tdst->stride[Tdst->nDimension-1];
dst_depth = 0;
dst_height = Tdst->size[Tdst->nDimension-2];
dst_width = Tdst->size[Tdst->nDimension-1];
if(Tdst->nDimension == 3) {
dst_stride0 = Tdst->stride[0];
dst_depth = Tdst->size[0];
}
src_stride0 = 0;
src_stride1 = Tsrc->stride[Tsrc->nDimension-2];
src_stride2 = Tsrc->stride[Tsrc->nDimension-1];
src_depth = 0;
src_height = Tsrc->size[Tsrc->nDimension-2];
src_width = Tsrc->size[Tsrc->nDimension-1];
if(Tsrc->nDimension == 3) {
src_stride0 = Tsrc->stride[0];
src_depth = Tsrc->size[0];
}
if( (Tdst->nDimension==3 && ( src_depth!=dst_depth)) ||
(Tdst->nDimension!=Tsrc->nDimension) ) {
printf("image.scale:%d,%d,%ld,%ld\n",Tsrc->nDimension,Tdst->nDimension,src_depth,dst_depth);
luaL_error(L, "image.scale: src and dst depths do not match");
}
if( Tdst->nDimension==3 && ( src_depth!=dst_depth) )
luaL_error(L, "image.scale: src and dst depths do not match");
/* printf("%d,%d -> %d,%d\n",src_width,src_height,dst_width,dst_height); */
scx=((float)src_width)/((float)dst_width);
scy=((float)src_height)/((float)dst_height);
#pragma omp parallel for private(j)
for(j = 0; j < dst_height; j++) {
for(i = 0; i < dst_width; i++) {
float val = 0.0;
long ii=(long) (((float)i)*scx);
long jj=(long) (((float)j)*scy);
if(ii>src_width-1) ii=src_width-1;
if(jj>src_height-1) jj=src_height-1;
if(Tsrc->nDimension==2)
{
val=src[ii*src_stride2+jj*src_stride1];
dst[i*dst_stride2+j*dst_stride1] = val;
}
else
{
for(k=0;k<src_depth;k++)
{
val=src[ii*src_stride2+jj*src_stride1+k*src_stride0];
dst[i*dst_stride2+j*dst_stride1+k*dst_stride0] = val;
}
}
}
}
return 0;
}
static int image_(Main_rotate)(lua_State *L)
{
THTensor *Tsrc = luaT_checkudata(L, 1, torch_Tensor);
THTensor *Tdst = luaT_checkudata(L, 2, torch_Tensor);
float theta = luaL_checknumber(L, 3);
real *src, *dst;
long dst_stride0, dst_stride1, dst_stride2, dst_width, dst_height, dst_depth;
long src_stride0, src_stride1, src_stride2, src_width, src_height, src_depth;
long i, j, k;
float xc, yc;
float id,jd;
long ii,jj;
luaL_argcheck(L, Tsrc->nDimension==2 || Tsrc->nDimension==3, 1, "rotate: src not 2 or 3 dimensional");
luaL_argcheck(L, Tdst->nDimension==2 || Tdst->nDimension==3, 2, "rotate: dst not 2 or 3 dimensional");
src= THTensor_(data)(Tsrc);
dst= THTensor_(data)(Tdst);
dst_stride0 = 0;
dst_stride1 = Tdst->stride[Tdst->nDimension-2];
dst_stride2 = Tdst->stride[Tdst->nDimension-1];
dst_depth = 0;
dst_height = Tdst->size[Tdst->nDimension-2];
dst_width = Tdst->size[Tdst->nDimension-1];
if(Tdst->nDimension == 3) {
dst_stride0 = Tdst->stride[0];
dst_depth = Tdst->size[0];
}
src_stride0 = 0;
src_stride1 = Tsrc->stride[Tsrc->nDimension-2];
src_stride2 = Tsrc->stride[Tsrc->nDimension-1];
src_depth = 0;
src_height = Tsrc->size[Tsrc->nDimension-2];
src_width = Tsrc->size[Tsrc->nDimension-1];
if(Tsrc->nDimension == 3) {
src_stride0 = Tsrc->stride[0];
src_depth = Tsrc->size[0];
}
if( Tsrc->nDimension==3 && Tdst->nDimension==3 && ( src_depth!=dst_depth) )
luaL_error(L, "image.rotate: src and dst depths do not match");
if( (Tsrc->nDimension!=Tdst->nDimension) )
luaL_error(L, "image.rotate: src and dst depths do not match");
xc=src_width/2.0;
yc=src_height/2.0;
for(j = 0; j < dst_height; j++) {
jd=j;
for(i = 0; i < dst_width; i++) {
float val = -1;
id= i;
ii=(long)( cos(theta)*(id-xc)-sin(theta)*(jd-yc) );
jj=(long)( cos(theta)*(jd-yc)+sin(theta)*(id-xc) );
ii+=(long) xc; jj+=(long) yc;
/* rotated corners are blank */
if(ii>src_width-1) val=0;
if(jj>src_height-1) val=0;
if(ii<0) val=0;
if(jj<0) val=0;
if(Tsrc->nDimension==2)
{
if(val==-1)
val=src[ii*src_stride2+jj*src_stride1];
dst[i*dst_stride2+j*dst_stride1] = val;
}
else
{
int do_copy=0; if(val==-1) do_copy=1;
for(k=0;k<src_depth;k++)
{
if(do_copy)
val=src[ii*src_stride2+jj*src_stride1+k*src_stride0];
dst[i*dst_stride2+j*dst_stride1+k*dst_stride0] = val;
}
}
}
}
return 0;
}
static int image_(Main_cropNoScale)(lua_State *L)
{
THTensor *Tsrc = luaT_checkudata(L, 1, torch_Tensor);
THTensor *Tdst = luaT_checkudata(L, 2, torch_Tensor);
long startx = luaL_checklong(L, 3);
long starty = luaL_checklong(L, 4);
real *src, *dst;
long dst_stride0, dst_stride1, dst_stride2, dst_width, dst_height, dst_depth;
long src_stride0, src_stride1, src_stride2, src_width, src_height, src_depth;
long i, j, k;
luaL_argcheck(L, Tsrc->nDimension==2 || Tsrc->nDimension==3, 1, "rotate: src not 2 or 3 dimensional");
luaL_argcheck(L, Tdst->nDimension==2 || Tdst->nDimension==3, 2, "rotate: dst not 2 or 3 dimensional");
src= THTensor_(data)(Tsrc);
dst= THTensor_(data)(Tdst);
dst_stride0 = 0;
dst_stride1 = Tdst->stride[Tdst->nDimension-2];
dst_stride2 = Tdst->stride[Tdst->nDimension-1];
dst_depth = 0;
dst_height = Tdst->size[Tdst->nDimension-2];
dst_width = Tdst->size[Tdst->nDimension-1];
if(Tdst->nDimension == 3) {
dst_stride0 = Tdst->stride[0];
dst_depth = Tdst->size[0];
}
src_stride0 = 0;
src_stride1 = Tsrc->stride[Tsrc->nDimension-2];
src_stride2 = Tsrc->stride[Tsrc->nDimension-1];
src_depth = 0;
src_height = Tsrc->size[Tsrc->nDimension-2];
src_width = Tsrc->size[Tsrc->nDimension-1];
if(Tsrc->nDimension == 3) {
src_stride0 = Tsrc->stride[0];
src_depth = Tsrc->size[0];
}
if( startx<0 || starty<0 || (startx+dst_width>src_width) || (starty+dst_height>src_height))
luaL_error(L, "image.crop: crop goes outside bounds of src");
if( Tdst->nDimension==3 && ( src_depth!=dst_depth) )
luaL_error(L, "image.crop: src and dst depths do not match");
for(j = 0; j < dst_height; j++) {
for(i = 0; i < dst_width; i++) {
float val = 0.0;
long ii=i+startx;
long jj=j+starty;
if(Tsrc->nDimension==2)
{
val=src[ii*src_stride2+jj*src_stride1];
dst[i*dst_stride2+j*dst_stride1] = val;
}
else
{
for(k=0;k<src_depth;k++)
{
val=src[ii*src_stride2+jj*src_stride1+k*src_stride0];
dst[i*dst_stride2+j*dst_stride1+k*dst_stride0] = val;
}
}
}
}
return 0;
}
static int image_(Main_translate)(lua_State *L)
{
THTensor *Tsrc = luaT_checkudata(L, 1, torch_Tensor);
THTensor *Tdst = luaT_checkudata(L, 2, torch_Tensor);
long shiftx = luaL_checklong(L, 3);
long shifty = luaL_checklong(L, 4);
real *src, *dst;
long dst_stride0, dst_stride1, dst_stride2, dst_width, dst_height, dst_depth;
long src_stride0, src_stride1, src_stride2, src_width, src_height, src_depth;
long i, j, k;
luaL_argcheck(L, Tsrc->nDimension==2 || Tsrc->nDimension==3, 1, "rotate: src not 2 or 3 dimensional");
luaL_argcheck(L, Tdst->nDimension==2 || Tdst->nDimension==3, 2, "rotate: dst not 2 or 3 dimensional");
src= THTensor_(data)(Tsrc);
dst= THTensor_(data)(Tdst);
dst_stride0 = 1;
dst_stride1 = Tdst->stride[Tdst->nDimension-2];
dst_stride2 = Tdst->stride[Tdst->nDimension-1];
dst_depth = 1;
dst_height = Tdst->size[Tdst->nDimension-2];
dst_width = Tdst->size[Tdst->nDimension-1];
if(Tdst->nDimension == 3) {
dst_stride0 = Tdst->stride[0];
dst_depth = Tdst->size[0];
}
src_stride0 = 1;
src_stride1 = Tsrc->stride[Tsrc->nDimension-2];
src_stride2 = Tsrc->stride[Tsrc->nDimension-1];
src_depth = 1;
src_height = Tsrc->size[Tsrc->nDimension-2];
src_width = Tsrc->size[Tsrc->nDimension-1];
if(Tsrc->nDimension == 3) {
src_stride0 = Tsrc->stride[0];
src_depth = Tsrc->size[0];
}
if( Tdst->nDimension==3 && ( src_depth!=dst_depth) )
luaL_error(L, "image.translate: src and dst depths do not match");
for(j = 0; j < src_height; j++) {
for(i = 0; i < src_width; i++) {
long ii=i+shiftx;
long jj=j+shifty;
// Check it's within destination bounds, else crop
if(ii<dst_width && jj<dst_height && ii>=0 && jj>=0) {
for(k=0;k<src_depth;k++) {
dst[ii*dst_stride2+jj*dst_stride1+k*dst_stride0] = src[i*src_stride2+j*src_stride1+k*src_stride0];
}
}
}
}
return 0;
}
static int image_(Main_saturate)(lua_State *L) {
THTensor *input = luaT_checkudata(L, 1, torch_Tensor);
THTensor *output = input;
TH_TENSOR_APPLY2(real, output, real, input, \
*output_data = (*input_data < 0) ? 0 : (*input_data > 1) ? 1 : *input_data;)
return 1;
}
/*
* Converts an RGB color value to HSL. Conversion formula
* adapted from http://en.wikipedia.org/wiki/HSL_color_space.
* Assumes r, g, and b are contained in the set [0, 1] and
* returns h, s, and l in the set [0, 1].
*/
int image_(Main_rgb2hsl)(lua_State *L) {
THTensor *rgb = luaT_checkudata(L, 1, torch_Tensor);
THTensor *hsl = luaT_checkudata(L, 2, torch_Tensor);
int y,x;
real r,g,b,h,s,l;
for (y=0; y<rgb->size[1]; y++) {
for (x=0; x<rgb->size[2]; x++) {
// get Rgb
r = THTensor_(get3d)(rgb, 0, y, x);
g = THTensor_(get3d)(rgb, 1, y, x);
b = THTensor_(get3d)(rgb, 2, y, x);
real mx = max(max(r, g), b);
real mn = min(min(r, g), b);
h = (mx + mn) / 2;
s = h;
l = h;
if(mx == mn) {
h = 0; // achromatic
s = 0;
} else {
real d = mx - mn;
s = l > 0.5 ? d / (2 - mx - mn) : d / (mx + mn);
if (mx == r) {
h = (g - b) / d + (g < b ? 6 : 0);
} else if (mx == g) {
h = (b - r) / d + 2;
} else {
h = (r - g) / d + 4;
}
h /= 6;
}
// set hsl
THTensor_(set3d)(hsl, 0, y, x, h);
THTensor_(set3d)(hsl, 1, y, x, s);
THTensor_(set3d)(hsl, 2, y, x, l);
}
}
return 0;
}
// helper
static inline real image_(hue2rgb)(real p, real q, real t) {
if (t < 0.) t += 1;
if (t > 1.) t -= 1;
if (t < 1./6)
return p + (q - p) * 6. * t;
else if (t < 1./2)
return q;
else if (t < 2./3)
return p + (q - p) * (2./3 - t) * 6.;
else
return p;
}
/*
* Converts an HSL color value to RGB. Conversion formula
* adapted from http://en.wikipedia.org/wiki/HSL_color_space.
* Assumes h, s, and l are contained in the set [0, 1] and
* returns r, g, and b in the set [0, 1].
*/
int image_(Main_hsl2rgb)(lua_State *L) {
THTensor *hsl = luaT_checkudata(L, 1, torch_Tensor);
THTensor *rgb = luaT_checkudata(L, 2, torch_Tensor);
int y,x;
real r,g,b,h,s,l;
for (y=0; y<hsl->size[1]; y++) {
for (x=0; x<hsl->size[2]; x++) {
// get hsl
h = THTensor_(get3d)(hsl, 0, y, x);
s = THTensor_(get3d)(hsl, 1, y, x);
l = THTensor_(get3d)(hsl, 2, y, x);
if(s == 0) {
// achromatic
r = l;
g = l;
b = l;
} else {
real q = (l < 0.5) ? (l * (1 + s)) : (l + s - l * s);
real p = 2 * l - q;
real hr = h + 1./3;
real hg = h;
real hb = h - 1./3;
r = image_(hue2rgb)(p, q, hr);
g = image_(hue2rgb)(p, q, hg);
b = image_(hue2rgb)(p, q, hb);
}
// set rgb
THTensor_(set3d)(rgb, 0, y, x, r);
THTensor_(set3d)(rgb, 1, y, x, g);
THTensor_(set3d)(rgb, 2, y, x, b);
}
}
return 0;
}
/*
* Converts an RGB color value to HSV. Conversion formula
* adapted from http://en.wikipedia.org/wiki/HSV_color_space.
* Assumes r, g, and b are contained in the set [0, 1] and
* returns h, s, and v in the set [0, 1].
*/
int image_(Main_rgb2hsv)(lua_State *L) {
THTensor *rgb = luaT_checkudata(L, 1, torch_Tensor);
THTensor *hsv = luaT_checkudata(L, 2, torch_Tensor);
int y,x;
real r,g,b,h,s,v;
for (y=0; y<rgb->size[1]; y++) {
for (x=0; x<rgb->size[2]; x++) {
// get Rgb
r = THTensor_(get3d)(rgb, 0, y, x);
g = THTensor_(get3d)(rgb, 1, y, x);
b = THTensor_(get3d)(rgb, 2, y, x);
real mx = max(max(r, g), b);
real mn = min(min(r, g), b);
h = mx;
v = mx;
real d = mx - mn;
s = (mx==0) ? 0 : d/mx;
if(mx == mn) {
h = 0; // achromatic
} else {
if (mx == r) {
h = (g - b) / d + (g < b ? 6 : 0);
} else if (mx == g) {
h = (b - r) / d + 2;
} else {
h = (r - g) / d + 4;
}
h /= 6;
}
// set hsv
THTensor_(set3d)(hsv, 0, y, x, h);
THTensor_(set3d)(hsv, 1, y, x, s);
THTensor_(set3d)(hsv, 2, y, x, v);
}
}
return 0;
}
/*
* Converts an HSV color value to RGB. Conversion formula
* adapted from http://en.wikipedia.org/wiki/HSV_color_space.
* Assumes h, s, and l are contained in the set [0, 1] and
* returns r, g, and b in the set [0, 1].
*/
int image_(Main_hsv2rgb)(lua_State *L) {
THTensor *hsv = luaT_checkudata(L, 1, torch_Tensor);
THTensor *rgb = luaT_checkudata(L, 2, torch_Tensor);
int y,x;
real r,g,b,h,s,v;
for (y=0; y<hsv->size[1]; y++) {
for (x=0; x<hsv->size[2]; x++) {
// get hsv
h = THTensor_(get3d)(hsv, 0, y, x);
s = THTensor_(get3d)(hsv, 1, y, x);
v = THTensor_(get3d)(hsv, 2, y, x);
int i = floor(h*6.);
real f = h*6-i;
real p = v*(1-s);
real q = v*(1-f*s);
real t = v*(1-(1-f)*s);
switch (i % 6) {
case 0: r = v, g = t, b = p; break;
case 1: r = q, g = v, b = p; break;
case 2: r = p, g = v, b = t; break;
case 3: r = p, g = q, b = v; break;
case 4: r = t, g = p, b = v; break;
case 5: r = v, g = p, b = q; break;
default: r=0; g = 0, b = 0; break;
}
// set rgb
THTensor_(set3d)(rgb, 0, y, x, r);
THTensor_(set3d)(rgb, 1, y, x, g);
THTensor_(set3d)(rgb, 2, y, x, b);
}
}
return 0;
}
/*
* Warps an image, according to an (x,y) flow field. The flow
* field is in the space of the destination image, each vector
* ponts to a source pixel in the original image.
*/
int image_(Main_warp)(lua_State *L) {
THTensor *dst = luaT_checkudata(L, 1, torch_Tensor);
THTensor *src = luaT_checkudata(L, 2, torch_Tensor);
THTensor *flowfield = luaT_checkudata(L, 3, torch_Tensor);
int mode = lua_tointeger(L, 4);
int offset_mode = lua_toboolean(L, 5);
// dims
int width = dst->size[2];
int height = dst->size[1];
int src_width = src->size[2];
int src_height = src->size[1];
int channels = dst->size[0];
long *is = src->stride;
long *os = dst->stride;
long *fs = flowfield->stride;
// get raw pointers
real *dst_data = THTensor_(data)(dst);
real *src_data = THTensor_(data)(src);
real *flow_data = THTensor_(data)(flowfield);
// resample
long k,x,y,jj,v,u,i,j;
for (y=0; y<height; y++) {
for (x=0; x<width; x++) {
// subpixel position:
real flow_y = flow_data[ 0*fs[0] + y*fs[1] + x*fs[2] ];
real flow_x = flow_data[ 1*fs[0] + y*fs[1] + x*fs[2] ];
float iy = offset_mode*y + flow_y;
float ix = offset_mode*x + flow_x;
// borders
ix = MAX(ix,0); ix = MIN(ix,src_width-1);
iy = MAX(iy,0); iy = MIN(iy,src_height-1);
// bilinear?
switch (mode) {
case 1: // Bilinear interpolation
{
// 4 nearest neighbors:
long ix_nw = floor(ix);
long iy_nw = floor(iy);
long ix_ne = ix_nw + 1;
long iy_ne = iy_nw;
long ix_sw = ix_nw;
long iy_sw = iy_nw + 1;
long ix_se = ix_nw + 1;
long iy_se = iy_nw + 1;
// get surfaces to each neighbor:
real nw = ((real)(ix_se-ix))*(iy_se-iy);
real ne = ((real)(ix-ix_sw))*(iy_sw-iy);
real sw = ((real)(ix_ne-ix))*(iy-iy_ne);
real se = ((real)(ix-ix_nw))*(iy-iy_nw);
// weighted sum of neighbors:
for (k=0; k<channels; k++) {
dst_data[ k*os[0] + y*os[1] + x*os[2] ] =
src_data[ k*is[0] + iy_nw*is[1] + ix_nw*is[2] ] * nw
+ src_data[ k*is[0] + iy_ne*is[1] + MIN(ix_ne,src_width-1)*is[2] ] * ne
+ src_data[ k*is[0] + MIN(iy_sw,src_height-1)*is[1] + ix_sw*is[2] ] * sw
+ src_data[ k*is[0] + MIN(iy_se,src_height-1)*is[1] + MIN(ix_se,src_width-1)*is[2] ] * se;
}
}
break;
case 0: // Simple (i.e., nearest neighbor)
{
// 1 nearest neighbor:
long ix_n = floor(ix+0.5);
long iy_n = floor(iy+0.5);
// weighted sum of neighbors:
for (k=0; k<channels; k++) {
dst_data[ k*os[0] + y*os[1] + x*os[2] ] = src_data[ k*is[0] + iy_n*is[1] + ix_n*is[2] ];
}
}
break;
case 2: // Bicubic
{
// Calculate fractional and integer components
long x_pix = floor(ix);
long y_pix = floor(iy);
real dx = ix - (real)x_pix;
real dy = iy - (real)y_pix;
real C[4];
for (k=0; k<channels; k++) {
// Sweep by rows through the samples (to calculate final cubic coefs)
for (jj = 0; jj <= 3; jj++) {
v = y_pix - 1 + jj;
// We need to clamp all uv values to image border: hopefully
// branch prediction and compiler reordering takes care of all
// the conditionals (since the branch probabilities are heavily
// skewed). Alternatively an inline "getPixelSafe" function would
// would be clearer here, but cannot be done with lua?
v = MAX(MIN((long)(src_height-1), v), 0);
long ofst = k * is[0] + v * is[1];
u = x_pix;
u = MAX(MIN((long)(src_width-1), u), 0);
real a0 = src_data[ofst + u * is[2]];
u = x_pix - 1;
u = MAX(MIN((long)(src_width-1), u), 0);
real d0 = src_data[ofst + u * is[2]] - a0;
u = x_pix + 1;
u = MAX(MIN((long)(src_width-1), u), 0);
real d2 = src_data[ofst + u * is[2]] - a0;
u = x_pix + 2;
u = MAX(MIN((long)(src_width-1), u), 0);
real d3 = src_data[ofst + u * is[2]] - a0;
// Note: there are mostly static casts, optimizer will take care of
// of it for us (prevents compiler warnings in new gcc)
real a1 = -(real)1/(real)3*d0 + d2 -(real)1/(real)6*d3;
real a2 = (real)1/(real)2*d0 + (real)1/(real)2*d2;
real a3 = -(real)1/(real)6*d0 - (real)1/(real)2*d2 +
(real)1/(real)6*d3;
C[jj] = a0 + dx * (a1 + dx * (a2 + a3 * dx));
}
real d0 = C[0]-C[1];
real d2 = C[2]-C[1];
real d3 = C[3]-C[1];
real a0 = C[1];
real a1 = -(real)1/(real)3*d0 + d2 - (real)1/(real)6*d3;
real a2 = (real)1/(real)2*d0 + (real)1/(real)2*d2;
real a3 = -(real)1/(real)6*d0 - (real)1/(real)2*d2 +
(real)1/(real)6*d3;
real Cc = a0 + dy * (a1 + dy * (a2 + a3 * dy));
// I assume that since the image is stored as reals we don't have
// to worry about clamping to min and max int (to prevent over or
// underflow)
dst_data[ k*os[0] + y*os[1] + x*os[2] ] = Cc;
}
}
break;
case 3: // Lanczos
{
// Note: Lanczos can be made fast if the resampling period is
// constant... and therefore the Lu, Lv can be cached and reused.
// However, unfortunately warp makes no assumptions about resampling
// and so we need to perform the O(k^2) convolution on each pixel AND
// we have to re-calculate the kernel for every pixel.
// See wikipedia for more info.
// It is however an extremely good approximation to to full sinc
// interpolation (IIR) filter.
// Another note is that the version here has been optimized using
// pretty aggressive code flow and explicit inlining. It might not
// be very readable (contact me, Jonathan Tompson, if it is not)
// Calculate fractional and integer components
long x_pix = floor(ix);
long y_pix = floor(iy);
// Precalculate the L(x) function evaluations in the u and v direction
const long rad = 3; // This is a tunable parameter: 2 to 3 is OK
float Lu[2 * rad]; // L(x) for u direction
float Lv[2 * rad]; // L(x) for v direction
for (u=x_pix-rad+1, i=0; u<=x_pix+rad; u++, i++) {
float du = ix - (float)u; // Lanczos kernel x value
du = du < 0 ? -du : du; // prefer not to used std absf
if (du < 0.000001f) { // TODO: Is there a real eps standard?
Lu[i] = 1;
} else if (du > (float)rad) {
Lu[i] = 0;
} else {
Lu[i] = ((float)rad * sin((float)M_PI * du) *
sin((float)M_PI * du / (float)rad)) /
((float)(M_PI * M_PI) * du * du);
}
}
for (v=y_pix-rad+1, i=0; v<=y_pix+rad; v++, i++) {
float dv = iy - (float)v; // Lanczos kernel x value
dv = dv < 0 ? -dv : dv; // prefer not to used std absf
if (dv < 0.000001f) { // TODO: Is there a real eps standard?
Lv[i] = 1;
} else if (dv > (float)rad) {
Lv[i] = 0;
} else {
Lv[i] = ((float)rad * sin((float)M_PI * dv) *
sin((float)M_PI * dv / (float)rad)) /
((float)(M_PI * M_PI) * dv * dv);
}
}
float sum_weights = 0;
for (u=0; u<2*rad; u++) {
for (v=0; v<2*rad; v++) {
sum_weights += (Lu[u] * Lv[v]);
}
}
for (k=0; k<channels; k++) {
real result = 0;
for (u=x_pix-rad+1, i=0; u<=x_pix+rad; u++, i++) {
long curu = MAX(MIN((long)(src_width-1), u), 0);
for (v=y_pix-rad+1, j=0; v<=y_pix+rad; v++, j++) {
long curv = MAX(MIN((long)(src_height-1), v), 0);
real Suv = src_data[k * is[0] + curv * is[1] + curu * is[2]];
real weight = (real)(Lu[i] * Lv[j]);
result += (Suv * weight);
}
}
// Normalize by the sum of the weights
result = result / (float)sum_weights;
// Again, I assume that since the image is stored as reals we
// don't have to worry about clamping to min and max int (to
// prevent over or underflow)
dst_data[ k*os[0] + y*os[1] + x*os[2] ] = result;
}
}
break;
}
}
}
// done
return 0;
}
int image_(Main_gaussian)(lua_State *L) {
THTensor *dst = luaT_checkudata(L, 1, torch_Tensor);
long width = dst->size[1];
long height = dst->size[0];
long *os = dst->stride;
real *dst_data = THTensor_(data)(dst);
real amplitude = (real)lua_tonumber(L, 2);
int normalize = (int)lua_toboolean(L, 3);
real sigma_u = (real)lua_tonumber(L, 4);
real sigma_v = (real)lua_tonumber(L, 5);
real mean_u = (real)lua_tonumber(L, 6) * (real)width + (real)0.5;
real mean_v = (real)lua_tonumber(L, 7) * (real)height + (real)0.5;
// Precalculate 1/(sigma*size) for speed (for some stupid reason the pragma
// omp declaration prevents gcc from optimizing the inside loop on my macine:
// verified by checking the assembly output)
real over_sigmau = (real)1.0 / (sigma_u * (real)width);
real over_sigmav = (real)1.0 / (sigma_v * (real)height);
long v, u;
real du, dv;
#pragma omp parallel for private(v, u, du, dv)
for (v = 0; v < height; v++) {
for (u = 0; u < width; u++) {
du = ((real)u + 1 - mean_u) * over_sigmau;
dv = ((real)v + 1 - mean_v) * over_sigmav;
dst_data[ v*os[0] + u*os[1] ] = amplitude *
exp(-((du*du*0.5) + (dv*dv*0.5)));
}
}
if (normalize) {
real sum = 0;
// We could parallelize this, but it's more trouble than it's worth
for(v = 0; v < height; v++) {
for(u = 0; u < width; u++) {
sum += dst_data[ v*os[0] + u*os[1] ];
}
}
real one_over_sum = 1.0 / sum;
#pragma omp parallel for private(v, u)
for(v = 0; v < height; v++) {
for(u = 0; u < width; u++) {
dst_data[ v*os[0] + u*os[1] ] *= one_over_sum;
}
}
}
return 0;
}
static const struct luaL_Reg image_(Main__) [] = {
{"scaleSimple", image_(Main_scaleSimple)},
{"scaleBilinear", image_(Main_scaleBilinear)},
{"rotate", image_(Main_rotate)},
{"translate", image_(Main_translate)},
{"cropNoScale", image_(Main_cropNoScale)},
{"warp", image_(Main_warp)},
{"saturate", image_(Main_saturate)},
{"rgb2hsv", image_(Main_rgb2hsv)},
{"rgb2hsl", image_(Main_rgb2hsl)},
{"hsv2rgb", image_(Main_hsv2rgb)},
{"hsl2rgb", image_(Main_hsl2rgb)},
{"gaussian", image_(Main_gaussian)},
{NULL, NULL}
};
void image_(Main_init)(lua_State *L)
{
luaT_pushmetatable(L, torch_Tensor);
luaT_registeratname(L, image_(Main__), "image");
}
#endif
|
expected_output.c | #include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <time.h>
#include <sys/time.h>
//---------------------------------------------------------------------
// program SP
//---------------------------------------------------------------------
//----------
// Class S:
//----------
//----------
// Class W:
//----------
//----------
// Class A:
//----------
//----------
// Class B:
//----------
//----------
// Class C:
//----------
//----------
// Class D:
//----------
//----------
// Class E:
//----------
struct anon_NAS_SP_c_78 {
double real;
double imag;
};
typedef struct anon_NAS_SP_c_78 dcomplex;
/*common /global/*/
int grid_points[3];
int nx2;
int ny2;
int nz2;
/*common /constants/*/
double tx1;
double tx2;
double tx3;
double ty1;
double ty2;
double ty3;
double tz1;
double tz2;
double tz3;
double dx1;
double dx2;
double dx3;
double dx4;
double dx5;
double dy1;
double dy2;
double dy3;
double dy4;
double dy5;
double dz1;
double dz2;
double dz3;
double dz4;
double dz5;
double dssp;
double dt;
double ce[5][13];
double dxmax;
double dymax;
double dzmax;
double xxcon1;
double xxcon2;
double xxcon3;
double xxcon4;
double xxcon5;
double dx1tx1;
double dx2tx1;
double dx3tx1;
double dx4tx1;
double dx5tx1;
double yycon1;
double yycon2;
double yycon3;
double yycon4;
double yycon5;
double dy1ty1;
double dy2ty1;
double dy3ty1;
double dy4ty1;
double dy5ty1;
double zzcon1;
double zzcon2;
double zzcon3;
double zzcon4;
double zzcon5;
double dz1tz1;
double dz2tz1;
double dz3tz1;
double dz4tz1;
double dz5tz1;
double dnxm1;
double dnym1;
double dnzm1;
double c1c2;
double c1c5;
double c3c4;
double c1345;
double conz1;
double c1;
double c2;
double c3;
double c4;
double c5;
double c4dssp;
double c5dssp;
double dtdssp;
double dttx1;
double bt;
double dttx2;
double dtty1;
double dtty2;
double dttz1;
double dttz2;
double c2dttx1;
double c2dtty1;
double c2dttz1;
double comz1;
double comz4;
double comz5;
double comz6;
double c3c4tx3;
double c3c4ty3;
double c3c4tz3;
double c2iv;
double con43;
double con16;
//---------------------------------------------------------------------
// To improve cache performance, grid dimensions padded by 1
// for even number sizes only
//---------------------------------------------------------------------
/*common /fields/*/
double u[36][37][37][5];
double us[36][37][37];
double vs[36][37][37];
double ws[36][37][37];
double qs[36][37][37];
double rho_i[36][37][37];
double speed[36][37][37];
double square[36][37][37];
double rhs[36][37][37][5];
double forcing[36][37][37][5];
//-----------------------------------------------------------------------
// Timer constants
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
void initialize();
void lhsinit(int ni, int nj, double lhs[37][37][5], double lhsp[37][37][5], double lhsm[37][37][5]);
void lhsinitj(int nj, int ni, double lhs[37][37][5], double lhsp[37][37][5], double lhsm[37][37][5]);
void exact_solution(double xi, double eta, double zeta, double dtemp[5]);
void exact_rhs();
void set_constants();
void adi();
void compute_rhs();
void x_solve();
void ninvr();
void y_solve();
void pinvr();
void z_solve();
void tzetar();
void add();
void txinvr();
void error_norm(double rms[5]);
void rhs_norm(double rms[5]);
void verify(int no_time_steps, char *Class, int *verified);
void print_results(char *name, char class, int n1, int n2, int n3, int niter, double t, double mops, char *optype, int verified);
double start[64];
double elapsed[64];
double elapsed_time();
void timer_clear(int n);
void timer_start(int n);
void timer_stop(int n);
double timer_read(int n);
void wtime(double *t);
int main(int argc, char *argv[]) {
int i, niter, step, n3;
double mflops;
double t;
double tmax;
double trecs[16];
int verified;
char Class;
char *t_names[16];
printf("\n\n NAS Parallel Benchmarks (NPB3.3-SER-C) - SP Benchmark\n\n");
niter = 400;
dt = 0.0015;
grid_points[0] = 36;
grid_points[1] = 36;
grid_points[2] = 36;
printf(" Size: %4dx%4dx%4d\n", grid_points[0], grid_points[1], grid_points[2]);
printf(" Iterations: %4d dt: %10.6f\n", niter, dt);
printf("\n");
if((grid_points[0] > 36) || (grid_points[1] > 36) || (grid_points[2] > 36)) {
printf(" %d, %d, %d\n", grid_points[0], grid_points[1], grid_points[2]);
printf(" Problem size too big for compiled array sizes\n");
return 0;
}
nx2 = grid_points[0] - 2;
ny2 = grid_points[1] - 2;
nz2 = grid_points[2] - 2;
set_constants();
/*************** Clava msgError **************
Loop Iteration number is too low
****************************************/
for(i = 1; i <= 15; i++) {
timer_clear(i);
}
exact_rhs();
initialize();
//---------------------------------------------------------------------
// do one time step to touch all code, and reinitialize
//---------------------------------------------------------------------
adi();
initialize();
/*************** Clava msgError **************
Loop Iteration number is too low
****************************************/
for(i = 1; i <= 15; i++) {
timer_clear(i);
}
timer_start(1);
/*************** Clava msgError **************
Variables Access as passed arguments Can not be traced inside of function calls :
printf#267{printf(" Time step %4d\n", step)}
compute_rhs#270{compute_rhs()}
txinvr#271{txinvr()}
x_solve#272{x_solve()}
y_solve#273{y_solve()}
z_solve#274{z_solve()}
add#275{add()}
****************************************/
for(step = 1; step <= niter; step++) {
if((step % 20) == 0 || step == 1) {
printf(" Time step %4d\n", step);
}
adi();
}
timer_stop(1);
tmax = timer_read(1);
verify(niter, &Class, &verified);
if(tmax != 0.0) {
n3 = grid_points[0] * grid_points[1] * grid_points[2];
t = (grid_points[0] + grid_points[1] + grid_points[2]) / 3.0;
mflops = (881.174 * (double) n3 - 4683.91 * (t * t) + 11484.5 * t - 19272.4) * (double) niter / (tmax * 1000000.0);
}
else {
mflops = 0.0;
}
print_results("SP", Class, grid_points[0], grid_points[1], grid_points[2], niter, tmax, mflops, " floating point", verified);
int exitValue = verified ? 0 : 1;
return exitValue;
}
//---------------------------------------------------------------------
// this function computes the norm of the difference between the
// computed solution and the exact solution
//---------------------------------------------------------------------
void error_norm(double rms[5]) {
int i, j, k, m, d;
double xi;
double eta;
double zeta;
double u_exact[5];
double add;
/*************** Clava msgError **************
Loop Iteration number is too low
****************************************/
for(m = 0; m < 5; m++) {
rms[m] = 0.0;
}
#pragma omp parallel for default(shared) private(k, j, i, m, zeta, eta, xi, add) firstprivate(dnzm1, dnym1, dnxm1, grid_points, ce, u, u_exact) reduction(+ : rms[:5])
for(k = 0; k <= grid_points[2] - 1; k++) {
zeta = (double) k * dnzm1;
#pragma omp parallel for default(shared) private(j, i, m, eta, xi, add) firstprivate(dnym1, dnxm1, zeta, k, grid_points, ce, u, u_exact) reduction(+ : rms[:5])
for(j = 0; j <= grid_points[1] - 1; j++) {
eta = (double) j * dnym1;
#pragma omp parallel for default(shared) private(i, m, xi, add) firstprivate(dnxm1, zeta, eta, k, j, grid_points, ce, u, u_exact) reduction(+ : rms[:5])
for(i = 0; i <= grid_points[0] - 1; i++) {
xi = (double) i * dnxm1;
exact_solution(xi, eta, zeta, u_exact);
/*************** Clava msgError **************
Loop Iteration number is too low
****************************************/
for(m = 0; m < 5; m++) {
add = u[k][j][i][m] - u_exact[m];
rms[m] = rms[m] + add * add;
}
}
}
}
/*************** Clava msgError **************
Loop Iteration number is too low
****************************************/
for(m = 0; m < 5; m++) {
/*************** Clava msgError **************
Loop Iteration number is too low
****************************************/
for(d = 0; d < 3; d++) {
rms[m] = rms[m] / (double) (grid_points[d] - 2);
}
rms[m] = sqrt(rms[m]);
}
}
void rhs_norm(double rms[5]) {
int i, j, k, d, m;
double add;
/*************** Clava msgError **************
Loop Iteration number is too low
****************************************/
for(m = 0; m < 5; m++) {
rms[m] = 0.0;
}
#pragma omp parallel for default(shared) private(k, j, i, m, add) firstprivate(nz2, ny2, nx2, rhs) reduction(+ : rms[:5])
for(k = 1; k <= nz2; k++) {
#pragma omp parallel for default(shared) private(j, i, m, add) firstprivate(ny2, nx2, k, rhs) reduction(+ : rms[:5])
for(j = 1; j <= ny2; j++) {
#pragma omp parallel for default(shared) private(i, m, add) firstprivate(nx2, k, j, rhs) reduction(+ : rms[:5])
for(i = 1; i <= nx2; i++) {
/*************** Clava msgError **************
Loop Iteration number is too low
****************************************/
for(m = 0; m < 5; m++) {
add = rhs[k][j][i][m];
rms[m] = rms[m] + add * add;
}
}
}
}
/*************** Clava msgError **************
Loop Iteration number is too low
****************************************/
for(m = 0; m < 5; m++) {
/*************** Clava msgError **************
Loop Iteration number is too low
****************************************/
for(d = 0; d < 3; d++) {
rms[m] = rms[m] / (double) (grid_points[d] - 2);
}
rms[m] = sqrt(rms[m]);
}
}
//---------------------------------------------------------------------
// compute the right hand side based on exact solution
//---------------------------------------------------------------------
void exact_rhs() {
double dtemp[5];
double xi;
double eta;
double zeta;
double dtpp;
int m, i, j, k, ip1, im1, jp1, jm1, km1, kp1;
double ue[36][5];
double buf[36][5];
double q[36];
double cuf[36];
//---------------------------------------------------------------------
// initialize
//---------------------------------------------------------------------
#pragma omp parallel for default(shared) private(k, j, i, m) firstprivate(grid_points)
for(k = 0; k <= grid_points[2] - 1; k++) {
#pragma omp parallel for default(shared) private(j, i, m) firstprivate(k, grid_points)
for(j = 0; j <= grid_points[1] - 1; j++) {
#pragma omp parallel for default(shared) private(i, m) firstprivate(k, j, grid_points)
for(i = 0; i <= grid_points[0] - 1; i++) {
/*************** Clava msgError **************
Loop Iteration number is too low
****************************************/
for(m = 0; m < 5; m++) {
forcing[k][j][i][m] = 0.0;
}
}
}
}
//---------------------------------------------------------------------
// xi-direction flux differences
//---------------------------------------------------------------------
#pragma omp parallel for default(shared) private(k, j, i, m, zeta, eta, xi, dtpp, im1, ip1) firstprivate(dnzm1, dnym1, dnxm1, tx2, dx1tx1, c2, xxcon1, dx2tx1, xxcon2, dx3tx1, dx4tx1, c1, xxcon3, xxcon4, xxcon5, dx5tx1, dssp, grid_points, ce, dtemp, ue, buf, cuf, q)
for(k = 1; k <= grid_points[2] - 2; k++) {
zeta = (double) k * dnzm1;
#pragma omp parallel for default(shared) private(j, i, m, eta, xi, dtpp, im1, ip1) firstprivate(dnym1, dnxm1, zeta, tx2, k, dx1tx1, c2, xxcon1, dx2tx1, xxcon2, dx3tx1, dx4tx1, c1, xxcon3, xxcon4, xxcon5, dx5tx1, dssp, grid_points, ce, dtemp, ue, buf, cuf, q)
for(j = 1; j <= grid_points[1] - 2; j++) {
eta = (double) j * dnym1;
#pragma omp parallel for default(shared) private(i, m, xi, dtpp) firstprivate(dnxm1, zeta, eta, grid_points, ce, dtemp)
for(i = 0; i <= grid_points[0] - 1; i++) {
xi = (double) i * dnxm1;
exact_solution(xi, eta, zeta, dtemp);
/*************** Clava msgError **************
Loop Iteration number is too low
****************************************/
for(m = 0; m < 5; m++) {
ue[i][m] = dtemp[m];
}
dtpp = 1.0 / dtemp[0];
/*************** Clava msgError **************
Loop Iteration number is too low
****************************************/
for(m = 1; m < 5; m++) {
buf[i][m] = dtpp * dtemp[m];
}
cuf[i] = buf[i][1] * buf[i][1];
buf[i][0] = cuf[i] + buf[i][2] * buf[i][2] + buf[i][3] * buf[i][3];
q[i] = 0.5 * (buf[i][1] * ue[i][1] + buf[i][2] * ue[i][2] + buf[i][3] * ue[i][3]);
}
#pragma omp parallel for default(shared) private(i, im1, ip1) firstprivate(tx2, k, j, dx1tx1, c2, xxcon1, dx2tx1, xxcon2, dx3tx1, dx4tx1, c1, xxcon3, xxcon4, xxcon5, dx5tx1, grid_points, ue, q, buf, cuf)
for(i = 1; i <= grid_points[0] - 2; i++) {
im1 = i - 1;
ip1 = i + 1;
forcing[k][j][i][0] = forcing[k][j][i][0] - tx2 * (ue[ip1][1] - ue[im1][1]) + dx1tx1 * (ue[ip1][0] - 2.0 * ue[i][0] + ue[im1][0]);
forcing[k][j][i][1] = forcing[k][j][i][1] - tx2 * ((ue[ip1][1] * buf[ip1][1] + c2 * (ue[ip1][4] - q[ip1])) - (ue[im1][1] * buf[im1][1] + c2 * (ue[im1][4] - q[im1]))) + xxcon1 * (buf[ip1][1] - 2.0 * buf[i][1] + buf[im1][1]) + dx2tx1 * (ue[ip1][1] - 2.0 * ue[i][1] + ue[im1][1]);
forcing[k][j][i][2] = forcing[k][j][i][2] - tx2 * (ue[ip1][2] * buf[ip1][1] - ue[im1][2] * buf[im1][1]) + xxcon2 * (buf[ip1][2] - 2.0 * buf[i][2] + buf[im1][2]) + dx3tx1 * (ue[ip1][2] - 2.0 * ue[i][2] + ue[im1][2]);
forcing[k][j][i][3] = forcing[k][j][i][3] - tx2 * (ue[ip1][3] * buf[ip1][1] - ue[im1][3] * buf[im1][1]) + xxcon2 * (buf[ip1][3] - 2.0 * buf[i][3] + buf[im1][3]) + dx4tx1 * (ue[ip1][3] - 2.0 * ue[i][3] + ue[im1][3]);
forcing[k][j][i][4] = forcing[k][j][i][4] - tx2 * (buf[ip1][1] * (c1 * ue[ip1][4] - c2 * q[ip1]) - buf[im1][1] * (c1 * ue[im1][4] - c2 * q[im1])) + 0.5 * xxcon3 * (buf[ip1][0] - 2.0 * buf[i][0] + buf[im1][0]) + xxcon4 * (cuf[ip1] - 2.0 * cuf[i] + cuf[im1]) + xxcon5 * (buf[ip1][4] - 2.0 * buf[i][4] + buf[im1][4]) + dx5tx1 * (ue[ip1][4] - 2.0 * ue[i][4] + ue[im1][4]);
}
//---------------------------------------------------------------------
// Fourth-order dissipation
//---------------------------------------------------------------------
/*************** Clava msgError **************
Loop Iteration number is too low
****************************************/
for(m = 0; m < 5; m++) {
i = 1;
forcing[k][j][i][m] = forcing[k][j][i][m] - dssp * (5.0 * ue[i][m] - 4.0 * ue[i + 1][m] + ue[i + 2][m]);
i = 2;
forcing[k][j][i][m] = forcing[k][j][i][m] - dssp * (-4.0 * ue[i - 1][m] + 6.0 * ue[i][m] - 4.0 * ue[i + 1][m] + ue[i + 2][m]);
}
#pragma omp parallel for default(shared) private(i, m) firstprivate(dssp, k, j, grid_points, ue)
for(i = 3; i <= grid_points[0] - 4; i++) {
/*************** Clava msgError **************
Loop Iteration number is too low
****************************************/
for(m = 0; m < 5; m++) {
forcing[k][j][i][m] = forcing[k][j][i][m] - dssp * (ue[i - 2][m] - 4.0 * ue[i - 1][m] + 6.0 * ue[i][m] - 4.0 * ue[i + 1][m] + ue[i + 2][m]);
}
}
/*************** Clava msgError **************
Loop Iteration number is too low
****************************************/
for(m = 0; m < 5; m++) {
i = grid_points[0] - 3;
forcing[k][j][i][m] = forcing[k][j][i][m] - dssp * (ue[i - 2][m] - 4.0 * ue[i - 1][m] + 6.0 * ue[i][m] - 4.0 * ue[i + 1][m]);
i = grid_points[0] - 2;
forcing[k][j][i][m] = forcing[k][j][i][m] - dssp * (ue[i - 2][m] - 4.0 * ue[i - 1][m] + 5.0 * ue[i][m]);
}
}
}
//---------------------------------------------------------------------
// eta-direction flux differences
//---------------------------------------------------------------------
#pragma omp parallel for default(shared) private(k, i, j, m, zeta, xi, eta, dtpp, jm1, jp1) firstprivate(dnzm1, dnxm1, dnym1, ty2, dy1ty1, yycon2, dy2ty1, c2, yycon1, dy3ty1, dy4ty1, c1, yycon3, yycon4, yycon5, dy5ty1, dssp, grid_points, ce, dtemp, ue, buf, cuf, q)
for(k = 1; k <= grid_points[2] - 2; k++) {
zeta = (double) k * dnzm1;
#pragma omp parallel for default(shared) private(i, j, m, xi, eta, dtpp, jm1, jp1) firstprivate(dnxm1, dnym1, zeta, ty2, k, dy1ty1, yycon2, dy2ty1, c2, yycon1, dy3ty1, dy4ty1, c1, yycon3, yycon4, yycon5, dy5ty1, dssp, grid_points, ce, dtemp, ue, buf, cuf, q)
for(i = 1; i <= grid_points[0] - 2; i++) {
xi = (double) i * dnxm1;
#pragma omp parallel for default(shared) private(j, m, eta, dtpp) firstprivate(dnym1, zeta, xi, grid_points, ce, dtemp)
for(j = 0; j <= grid_points[1] - 1; j++) {
eta = (double) j * dnym1;
exact_solution(xi, eta, zeta, dtemp);
/*************** Clava msgError **************
Loop Iteration number is too low
****************************************/
for(m = 0; m < 5; m++) {
ue[j][m] = dtemp[m];
}
dtpp = 1.0 / dtemp[0];
/*************** Clava msgError **************
Loop Iteration number is too low
****************************************/
for(m = 1; m < 5; m++) {
buf[j][m] = dtpp * dtemp[m];
}
cuf[j] = buf[j][2] * buf[j][2];
buf[j][0] = cuf[j] + buf[j][1] * buf[j][1] + buf[j][3] * buf[j][3];
q[j] = 0.5 * (buf[j][1] * ue[j][1] + buf[j][2] * ue[j][2] + buf[j][3] * ue[j][3]);
}
#pragma omp parallel for default(shared) private(j, jm1, jp1) firstprivate(ty2, k, i, dy1ty1, yycon2, dy2ty1, c2, yycon1, dy3ty1, dy4ty1, c1, yycon3, yycon4, yycon5, dy5ty1, grid_points, ue, buf, q, cuf)
for(j = 1; j <= grid_points[1] - 2; j++) {
jm1 = j - 1;
jp1 = j + 1;
forcing[k][j][i][0] = forcing[k][j][i][0] - ty2 * (ue[jp1][2] - ue[jm1][2]) + dy1ty1 * (ue[jp1][0] - 2.0 * ue[j][0] + ue[jm1][0]);
forcing[k][j][i][1] = forcing[k][j][i][1] - ty2 * (ue[jp1][1] * buf[jp1][2] - ue[jm1][1] * buf[jm1][2]) + yycon2 * (buf[jp1][1] - 2.0 * buf[j][1] + buf[jm1][1]) + dy2ty1 * (ue[jp1][1] - 2.0 * ue[j][1] + ue[jm1][1]);
forcing[k][j][i][2] = forcing[k][j][i][2] - ty2 * ((ue[jp1][2] * buf[jp1][2] + c2 * (ue[jp1][4] - q[jp1])) - (ue[jm1][2] * buf[jm1][2] + c2 * (ue[jm1][4] - q[jm1]))) + yycon1 * (buf[jp1][2] - 2.0 * buf[j][2] + buf[jm1][2]) + dy3ty1 * (ue[jp1][2] - 2.0 * ue[j][2] + ue[jm1][2]);
forcing[k][j][i][3] = forcing[k][j][i][3] - ty2 * (ue[jp1][3] * buf[jp1][2] - ue[jm1][3] * buf[jm1][2]) + yycon2 * (buf[jp1][3] - 2.0 * buf[j][3] + buf[jm1][3]) + dy4ty1 * (ue[jp1][3] - 2.0 * ue[j][3] + ue[jm1][3]);
forcing[k][j][i][4] = forcing[k][j][i][4] - ty2 * (buf[jp1][2] * (c1 * ue[jp1][4] - c2 * q[jp1]) - buf[jm1][2] * (c1 * ue[jm1][4] - c2 * q[jm1])) + 0.5 * yycon3 * (buf[jp1][0] - 2.0 * buf[j][0] + buf[jm1][0]) + yycon4 * (cuf[jp1] - 2.0 * cuf[j] + cuf[jm1]) + yycon5 * (buf[jp1][4] - 2.0 * buf[j][4] + buf[jm1][4]) + dy5ty1 * (ue[jp1][4] - 2.0 * ue[j][4] + ue[jm1][4]);
}
//---------------------------------------------------------------------
// Fourth-order dissipation
//---------------------------------------------------------------------
/*************** Clava msgError **************
Loop Iteration number is too low
****************************************/
for(m = 0; m < 5; m++) {
j = 1;
forcing[k][j][i][m] = forcing[k][j][i][m] - dssp * (5.0 * ue[j][m] - 4.0 * ue[j + 1][m] + ue[j + 2][m]);
j = 2;
forcing[k][j][i][m] = forcing[k][j][i][m] - dssp * (-4.0 * ue[j - 1][m] + 6.0 * ue[j][m] - 4.0 * ue[j + 1][m] + ue[j + 2][m]);
}
#pragma omp parallel for default(shared) private(j, m) firstprivate(dssp, k, i, grid_points, ue)
for(j = 3; j <= grid_points[1] - 4; j++) {
/*************** Clava msgError **************
Loop Iteration number is too low
****************************************/
for(m = 0; m < 5; m++) {
forcing[k][j][i][m] = forcing[k][j][i][m] - dssp * (ue[j - 2][m] - 4.0 * ue[j - 1][m] + 6.0 * ue[j][m] - 4.0 * ue[j + 1][m] + ue[j + 2][m]);
}
}
/*************** Clava msgError **************
Loop Iteration number is too low
****************************************/
for(m = 0; m < 5; m++) {
j = grid_points[1] - 3;
forcing[k][j][i][m] = forcing[k][j][i][m] - dssp * (ue[j - 2][m] - 4.0 * ue[j - 1][m] + 6.0 * ue[j][m] - 4.0 * ue[j + 1][m]);
j = grid_points[1] - 2;
forcing[k][j][i][m] = forcing[k][j][i][m] - dssp * (ue[j - 2][m] - 4.0 * ue[j - 1][m] + 5.0 * ue[j][m]);
}
}
}
//---------------------------------------------------------------------
// zeta-direction flux differences
//---------------------------------------------------------------------
#pragma omp parallel for default(shared) private(j, i, k, m, eta, xi, zeta, dtpp, km1, kp1) firstprivate(dnym1, dnxm1, dnzm1, tz2, dz1tz1, zzcon2, dz2tz1, dz3tz1, c2, zzcon1, dz4tz1, c1, zzcon3, zzcon4, zzcon5, dz5tz1, dssp, grid_points, ce, dtemp, ue, buf, cuf, q)
for(j = 1; j <= grid_points[1] - 2; j++) {
eta = (double) j * dnym1;
#pragma omp parallel for default(shared) private(i, k, m, xi, zeta, dtpp, km1, kp1) firstprivate(dnxm1, dnzm1, eta, tz2, j, dz1tz1, zzcon2, dz2tz1, dz3tz1, c2, zzcon1, dz4tz1, c1, zzcon3, zzcon4, zzcon5, dz5tz1, dssp, grid_points, ce, dtemp, ue, buf, cuf, q)
for(i = 1; i <= grid_points[0] - 2; i++) {
xi = (double) i * dnxm1;
#pragma omp parallel for default(shared) private(k, m, zeta, dtpp) firstprivate(dnzm1, eta, xi, grid_points, ce, dtemp)
for(k = 0; k <= grid_points[2] - 1; k++) {
zeta = (double) k * dnzm1;
exact_solution(xi, eta, zeta, dtemp);
/*************** Clava msgError **************
Loop Iteration number is too low
****************************************/
for(m = 0; m < 5; m++) {
ue[k][m] = dtemp[m];
}
dtpp = 1.0 / dtemp[0];
/*************** Clava msgError **************
Loop Iteration number is too low
****************************************/
for(m = 1; m < 5; m++) {
buf[k][m] = dtpp * dtemp[m];
}
cuf[k] = buf[k][3] * buf[k][3];
buf[k][0] = cuf[k] + buf[k][1] * buf[k][1] + buf[k][2] * buf[k][2];
q[k] = 0.5 * (buf[k][1] * ue[k][1] + buf[k][2] * ue[k][2] + buf[k][3] * ue[k][3]);
}
#pragma omp parallel for default(shared) private(k, km1, kp1) firstprivate(tz2, j, i, dz1tz1, zzcon2, dz2tz1, dz3tz1, c2, zzcon1, dz4tz1, c1, zzcon3, zzcon4, zzcon5, dz5tz1, grid_points, ue, buf, q, cuf)
for(k = 1; k <= grid_points[2] - 2; k++) {
km1 = k - 1;
kp1 = k + 1;
forcing[k][j][i][0] = forcing[k][j][i][0] - tz2 * (ue[kp1][3] - ue[km1][3]) + dz1tz1 * (ue[kp1][0] - 2.0 * ue[k][0] + ue[km1][0]);
forcing[k][j][i][1] = forcing[k][j][i][1] - tz2 * (ue[kp1][1] * buf[kp1][3] - ue[km1][1] * buf[km1][3]) + zzcon2 * (buf[kp1][1] - 2.0 * buf[k][1] + buf[km1][1]) + dz2tz1 * (ue[kp1][1] - 2.0 * ue[k][1] + ue[km1][1]);
forcing[k][j][i][2] = forcing[k][j][i][2] - tz2 * (ue[kp1][2] * buf[kp1][3] - ue[km1][2] * buf[km1][3]) + zzcon2 * (buf[kp1][2] - 2.0 * buf[k][2] + buf[km1][2]) + dz3tz1 * (ue[kp1][2] - 2.0 * ue[k][2] + ue[km1][2]);
forcing[k][j][i][3] = forcing[k][j][i][3] - tz2 * ((ue[kp1][3] * buf[kp1][3] + c2 * (ue[kp1][4] - q[kp1])) - (ue[km1][3] * buf[km1][3] + c2 * (ue[km1][4] - q[km1]))) + zzcon1 * (buf[kp1][3] - 2.0 * buf[k][3] + buf[km1][3]) + dz4tz1 * (ue[kp1][3] - 2.0 * ue[k][3] + ue[km1][3]);
forcing[k][j][i][4] = forcing[k][j][i][4] - tz2 * (buf[kp1][3] * (c1 * ue[kp1][4] - c2 * q[kp1]) - buf[km1][3] * (c1 * ue[km1][4] - c2 * q[km1])) + 0.5 * zzcon3 * (buf[kp1][0] - 2.0 * buf[k][0] + buf[km1][0]) + zzcon4 * (cuf[kp1] - 2.0 * cuf[k] + cuf[km1]) + zzcon5 * (buf[kp1][4] - 2.0 * buf[k][4] + buf[km1][4]) + dz5tz1 * (ue[kp1][4] - 2.0 * ue[k][4] + ue[km1][4]);
}
//---------------------------------------------------------------------
// Fourth-order dissipation
//---------------------------------------------------------------------
/*************** Clava msgError **************
Loop Iteration number is too low
****************************************/
for(m = 0; m < 5; m++) {
k = 1;
forcing[k][j][i][m] = forcing[k][j][i][m] - dssp * (5.0 * ue[k][m] - 4.0 * ue[k + 1][m] + ue[k + 2][m]);
k = 2;
forcing[k][j][i][m] = forcing[k][j][i][m] - dssp * (-4.0 * ue[k - 1][m] + 6.0 * ue[k][m] - 4.0 * ue[k + 1][m] + ue[k + 2][m]);
}
#pragma omp parallel for default(shared) private(k, m) firstprivate(dssp, j, i, grid_points, ue)
for(k = 3; k <= grid_points[2] - 4; k++) {
/*************** Clava msgError **************
Loop Iteration number is too low
****************************************/
for(m = 0; m < 5; m++) {
forcing[k][j][i][m] = forcing[k][j][i][m] - dssp * (ue[k - 2][m] - 4.0 * ue[k - 1][m] + 6.0 * ue[k][m] - 4.0 * ue[k + 1][m] + ue[k + 2][m]);
}
}
/*************** Clava msgError **************
Loop Iteration number is too low
****************************************/
for(m = 0; m < 5; m++) {
k = grid_points[2] - 3;
forcing[k][j][i][m] = forcing[k][j][i][m] - dssp * (ue[k - 2][m] - 4.0 * ue[k - 1][m] + 6.0 * ue[k][m] - 4.0 * ue[k + 1][m]);
k = grid_points[2] - 2;
forcing[k][j][i][m] = forcing[k][j][i][m] - dssp * (ue[k - 2][m] - 4.0 * ue[k - 1][m] + 5.0 * ue[k][m]);
}
}
}
//---------------------------------------------------------------------
// now change the sign of the forcing function,
//---------------------------------------------------------------------
#pragma omp parallel for default(shared) private(k, j, i, m) firstprivate(grid_points)
for(k = 1; k <= grid_points[2] - 2; k++) {
#pragma omp parallel for default(shared) private(j, i, m) firstprivate(k, grid_points)
for(j = 1; j <= grid_points[1] - 2; j++) {
#pragma omp parallel for default(shared) private(i, m) firstprivate(k, j, grid_points)
for(i = 1; i <= grid_points[0] - 2; i++) {
/*************** Clava msgError **************
Loop Iteration number is too low
****************************************/
for(m = 0; m < 5; m++) {
forcing[k][j][i][m] = -1.0 * forcing[k][j][i][m];
}
}
}
}
}
//---------------------------------------------------------------------
// this function returns the exact solution at point xi, eta, zeta
//---------------------------------------------------------------------
void exact_solution(double xi, double eta, double zeta, double dtemp[5]) {
int m;
/*************** Clava msgError **************
Loop Iteration number is too low
****************************************/
for(m = 0; m < 5; m++) {
dtemp[m] = ce[m][0] + xi * (ce[m][1] + xi * (ce[m][4] + xi * (ce[m][7] + xi * ce[m][10]))) + eta * (ce[m][2] + eta * (ce[m][5] + eta * (ce[m][8] + eta * ce[m][11]))) + zeta * (ce[m][3] + zeta * (ce[m][6] + zeta * (ce[m][9] + zeta * ce[m][12])));
}
}
void adi() {
compute_rhs();
txinvr();
x_solve();
y_solve();
z_solve();
add();
}
//---------------------------------------------------------------------
// addition of update to the vector u
//---------------------------------------------------------------------
void add() {
int i, j, k, m;
#pragma omp parallel for default(shared) private(k, j, i, m) firstprivate(nz2, ny2, nx2, rhs)
for(k = 1; k <= nz2; k++) {
#pragma omp parallel for default(shared) private(j, i, m) firstprivate(ny2, nx2, k, rhs)
for(j = 1; j <= ny2; j++) {
#pragma omp parallel for default(shared) private(i, m) firstprivate(nx2, k, j, rhs)
for(i = 1; i <= nx2; i++) {
/*************** Clava msgError **************
Loop Iteration number is too low
****************************************/
for(m = 0; m < 5; m++) {
u[k][j][i][m] = u[k][j][i][m] + rhs[k][j][i][m];
}
}
}
}
}
//---------------------------------------------------------------------
// This subroutine initializes the field variable u using
// tri-linear transfinite interpolation of the boundary values
//---------------------------------------------------------------------
void initialize() {
int i, j, k, m, ix, iy, iz;
double xi;
double eta;
double zeta;
double Pface[2][3][5];
double Pxi;
double Peta;
double Pzeta;
double temp[5];
//---------------------------------------------------------------------
// Later (in compute_rhs) we compute 1/u for every element. A few of
// the corner elements are not used, but it convenient (and faster)
// to compute the whole thing with a simple loop. Make sure those
// values are nonzero by initializing the whole thing here.
//---------------------------------------------------------------------
#pragma omp parallel for default(shared) private(k, j, i) firstprivate(grid_points)
for(k = 0; k <= grid_points[2] - 1; k++) {
#pragma omp parallel for default(shared) private(j, i) firstprivate(k, grid_points)
for(j = 0; j <= grid_points[1] - 1; j++) {
#pragma omp parallel for default(shared) private(i) firstprivate(k, j, grid_points)
for(i = 0; i <= grid_points[0] - 1; i++) {
u[k][j][i][0] = 1.0;
u[k][j][i][1] = 0.0;
u[k][j][i][2] = 0.0;
u[k][j][i][3] = 0.0;
u[k][j][i][4] = 1.0;
}
}
}
//---------------------------------------------------------------------
// first store the "interpolated" values everywhere on the grid
//---------------------------------------------------------------------
/*************** Clava msgError **************
Variables Access as passed arguments Can not be traced inside of function calls :
exact_solution#787{exact_solution(Pxi, eta, zeta, &Pface[ix][0][0])}
exact_solution#793{exact_solution(xi, Peta, zeta, &Pface[iy][1][0])}
exact_solution#799{exact_solution(xi, eta, Pzeta, &Pface[iz][2][0])}
****************************************/
for(k = 0; k <= grid_points[2] - 1; k++) {
zeta = (double) k * dnzm1;
/*************** Clava msgError **************
Variables Access as passed arguments Can not be traced inside of function calls :
exact_solution#787{exact_solution(Pxi, eta, zeta, &Pface[ix][0][0])}
exact_solution#793{exact_solution(xi, Peta, zeta, &Pface[iy][1][0])}
exact_solution#799{exact_solution(xi, eta, Pzeta, &Pface[iz][2][0])}
****************************************/
for(j = 0; j <= grid_points[1] - 1; j++) {
eta = (double) j * dnym1;
/*************** Clava msgError **************
Variables Access as passed arguments Can not be traced inside of function calls :
exact_solution#787{exact_solution(Pxi, eta, zeta, &Pface[ix][0][0])}
exact_solution#793{exact_solution(xi, Peta, zeta, &Pface[iy][1][0])}
exact_solution#799{exact_solution(xi, eta, Pzeta, &Pface[iz][2][0])}
****************************************/
for(i = 0; i <= grid_points[0] - 1; i++) {
xi = (double) i * dnxm1;
/*************** Clava msgError **************
Loop Iteration number is too low
****************************************/
for(ix = 0; ix < 2; ix++) {
Pxi = (double) ix;
exact_solution(Pxi, eta, zeta, &Pface[ix][0][0]);
}
/*************** Clava msgError **************
Loop Iteration number is too low
****************************************/
for(iy = 0; iy < 2; iy++) {
Peta = (double) iy;
exact_solution(xi, Peta, zeta, &Pface[iy][1][0]);
}
/*************** Clava msgError **************
Loop Iteration number is too low
****************************************/
for(iz = 0; iz < 2; iz++) {
Pzeta = (double) iz;
exact_solution(xi, eta, Pzeta, &Pface[iz][2][0]);
}
/*************** Clava msgError **************
Loop Iteration number is too low
****************************************/
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[k][j][i][m] = Pxi + Peta + Pzeta - Pxi * Peta - Pxi * Pzeta - Peta * Pzeta + Pxi * Peta * Pzeta;
}
}
}
}
//---------------------------------------------------------------------
// now store the exact values on the boundaries
//---------------------------------------------------------------------
//---------------------------------------------------------------------
// west face
//---------------------------------------------------------------------
xi = 0.0;
i = 0;
#pragma omp parallel for default(shared) private(k, j, m, zeta, eta) firstprivate(dnzm1, dnym1, xi, i, grid_points, ce, temp)
for(k = 0; k <= grid_points[2] - 1; k++) {
zeta = (double) k * dnzm1;
#pragma omp parallel for default(shared) private(j, m, eta) firstprivate(dnym1, zeta, xi, k, i, grid_points, ce, temp)
for(j = 0; j <= grid_points[1] - 1; j++) {
eta = (double) j * dnym1;
exact_solution(xi, eta, zeta, temp);
/*************** Clava msgError **************
Loop Iteration number is too low
****************************************/
for(m = 0; m < 5; m++) {
u[k][j][i][m] = temp[m];
}
}
}
//---------------------------------------------------------------------
// east face
//---------------------------------------------------------------------
xi = 1.0;
i = grid_points[0] - 1;
#pragma omp parallel for default(shared) private(k, j, m, zeta, eta) firstprivate(dnzm1, dnym1, xi, i, grid_points, ce, temp)
for(k = 0; k <= grid_points[2] - 1; k++) {
zeta = (double) k * dnzm1;
#pragma omp parallel for default(shared) private(j, m, eta) firstprivate(dnym1, zeta, xi, k, i, grid_points, ce, temp)
for(j = 0; j <= grid_points[1] - 1; j++) {
eta = (double) j * dnym1;
exact_solution(xi, eta, zeta, temp);
/*************** Clava msgError **************
Loop Iteration number is too low
****************************************/
for(m = 0; m < 5; m++) {
u[k][j][i][m] = temp[m];
}
}
}
//---------------------------------------------------------------------
// south face
//---------------------------------------------------------------------
eta = 0.0;
j = 0;
#pragma omp parallel for default(shared) private(k, i, m, zeta, xi) firstprivate(dnzm1, dnxm1, eta, j, grid_points, ce, temp)
for(k = 0; k <= grid_points[2] - 1; k++) {
zeta = (double) k * dnzm1;
#pragma omp parallel for default(shared) private(i, m, xi) firstprivate(dnxm1, zeta, eta, k, j, grid_points, ce, temp)
for(i = 0; i <= grid_points[0] - 1; i++) {
xi = (double) i * dnxm1;
exact_solution(xi, eta, zeta, temp);
/*************** Clava msgError **************
Loop Iteration number is too low
****************************************/
for(m = 0; m < 5; m++) {
u[k][j][i][m] = temp[m];
}
}
}
//---------------------------------------------------------------------
// north face
//---------------------------------------------------------------------
eta = 1.0;
j = grid_points[1] - 1;
#pragma omp parallel for default(shared) private(k, i, m, zeta, xi) firstprivate(dnzm1, dnxm1, eta, j, grid_points, ce, temp)
for(k = 0; k <= grid_points[2] - 1; k++) {
zeta = (double) k * dnzm1;
#pragma omp parallel for default(shared) private(i, m, xi) firstprivate(dnxm1, zeta, eta, k, j, grid_points, ce, temp)
for(i = 0; i <= grid_points[0] - 1; i++) {
xi = (double) i * dnxm1;
exact_solution(xi, eta, zeta, temp);
/*************** Clava msgError **************
Loop Iteration number is too low
****************************************/
for(m = 0; m < 5; m++) {
u[k][j][i][m] = temp[m];
}
}
}
//---------------------------------------------------------------------
// bottom face
//---------------------------------------------------------------------
zeta = 0.0;
k = 0;
#pragma omp parallel for default(shared) private(j, i, m, eta, xi) firstprivate(dnym1, dnxm1, zeta, k, grid_points, ce, temp)
for(j = 0; j <= grid_points[1] - 1; j++) {
eta = (double) j * dnym1;
#pragma omp parallel for default(shared) private(i, m, xi) firstprivate(dnxm1, zeta, eta, k, j, grid_points, ce, temp)
for(i = 0; i <= grid_points[0] - 1; i++) {
xi = (double) i * dnxm1;
exact_solution(xi, eta, zeta, temp);
/*************** Clava msgError **************
Loop Iteration number is too low
****************************************/
for(m = 0; m < 5; m++) {
u[k][j][i][m] = temp[m];
}
}
}
//---------------------------------------------------------------------
// top face
//---------------------------------------------------------------------
zeta = 1.0;
k = grid_points[2] - 1;
#pragma omp parallel for default(shared) private(j, i, m, eta, xi) firstprivate(dnym1, dnxm1, zeta, k, grid_points, ce, temp)
for(j = 0; j <= grid_points[1] - 1; j++) {
eta = (double) j * dnym1;
#pragma omp parallel for default(shared) private(i, m, xi) firstprivate(dnxm1, zeta, eta, k, j, grid_points, ce, temp)
for(i = 0; i <= grid_points[0] - 1; i++) {
xi = (double) i * dnxm1;
exact_solution(xi, eta, zeta, temp);
/*************** Clava msgError **************
Loop Iteration number is too low
****************************************/
for(m = 0; m < 5; m++) {
u[k][j][i][m] = temp[m];
}
}
}
}
void lhsinit(int ni, int nj, double lhs[37][37][5], double lhsp[37][37][5], double lhsm[37][37][5]) {
int j, m;
//---------------------------------------------------------------------
// zap the whole left hand side for starters
// set all diagonal values to 1. This is overkill, but convenient
//---------------------------------------------------------------------
#pragma omp parallel for default(shared) private(j, m) firstprivate(nj, ni)
for(j = 1; j <= nj; j++) {
/*************** Clava msgError **************
Loop Iteration number is too low
****************************************/
for(m = 0; m < 5; m++) {
lhs[j][0][m] = 0.0;
lhsp[j][0][m] = 0.0;
lhsm[j][0][m] = 0.0;
lhs[j][ni][m] = 0.0;
lhsp[j][ni][m] = 0.0;
lhsm[j][ni][m] = 0.0;
}
lhs[j][0][2] = 1.0;
lhsp[j][0][2] = 1.0;
lhsm[j][0][2] = 1.0;
lhs[j][ni][2] = 1.0;
lhsp[j][ni][2] = 1.0;
lhsm[j][ni][2] = 1.0;
}
}
void lhsinitj(int nj, int ni, double lhs[37][37][5], double lhsp[37][37][5], double lhsm[37][37][5]) {
int i, m;
//---------------------------------------------------------------------
// zap the whole left hand side for starters
// set all diagonal values to 1. This is overkill, but convenient
//---------------------------------------------------------------------
#pragma omp parallel for default(shared) private(i, m) firstprivate(ni, nj)
for(i = 1; i <= ni; i++) {
/*************** Clava msgError **************
Loop Iteration number is too low
****************************************/
for(m = 0; m < 5; m++) {
lhs[0][i][m] = 0.0;
lhsp[0][i][m] = 0.0;
lhsm[0][i][m] = 0.0;
lhs[nj][i][m] = 0.0;
lhsp[nj][i][m] = 0.0;
lhsm[nj][i][m] = 0.0;
}
lhs[0][i][2] = 1.0;
lhsp[0][i][2] = 1.0;
lhsm[0][i][2] = 1.0;
lhs[nj][i][2] = 1.0;
lhsp[nj][i][2] = 1.0;
lhsm[nj][i][2] = 1.0;
}
}
//---------------------------------------------------------------------
// block-diagonal matrix-vector multiplication
//---------------------------------------------------------------------
void ninvr() {
int i, j, k;
double r1, r2, r3, r4, r5, t1, t2;
#pragma omp parallel for default(shared) private(k, j, i, r1, r2, r3, r4, r5, t1, t2) firstprivate(nz2, ny2, nx2, bt)
for(k = 1; k <= nz2; k++) {
#pragma omp parallel for default(shared) private(j, i, r1, r2, r3, r4, r5, t1, t2) firstprivate(ny2, nx2, k, bt)
for(j = 1; j <= ny2; j++) {
#pragma omp parallel for default(shared) private(i, r1, r2, r3, r4, r5, t1, t2) firstprivate(nx2, k, j, bt)
for(i = 1; i <= nx2; i++) {
r1 = rhs[k][j][i][0];
r2 = rhs[k][j][i][1];
r3 = rhs[k][j][i][2];
r4 = rhs[k][j][i][3];
r5 = rhs[k][j][i][4];
t1 = bt * r3;
t2 = 0.5 * (r4 + r5);
rhs[k][j][i][0] = -r2;
rhs[k][j][i][1] = r1;
rhs[k][j][i][2] = bt * (r4 - r5);
rhs[k][j][i][3] = -t1 + t2;
rhs[k][j][i][4] = t1 + t2;
}
}
}
}
//---------------------------------------------------------------------
// block-diagonal matrix-vector multiplication
//---------------------------------------------------------------------
void pinvr() {
int i, j, k;
double r1, r2, r3, r4, r5, t1, t2;
#pragma omp parallel for default(shared) private(k, j, i, r1, r2, r3, r4, r5, t1, t2) firstprivate(nz2, ny2, nx2, bt)
for(k = 1; k <= nz2; k++) {
#pragma omp parallel for default(shared) private(j, i, r1, r2, r3, r4, r5, t1, t2) firstprivate(ny2, nx2, k, bt)
for(j = 1; j <= ny2; j++) {
#pragma omp parallel for default(shared) private(i, r1, r2, r3, r4, r5, t1, t2) firstprivate(nx2, k, j, bt)
for(i = 1; i <= nx2; i++) {
r1 = rhs[k][j][i][0];
r2 = rhs[k][j][i][1];
r3 = rhs[k][j][i][2];
r4 = rhs[k][j][i][3];
r5 = rhs[k][j][i][4];
t1 = bt * r1;
t2 = 0.5 * (r4 + r5);
rhs[k][j][i][0] = bt * (r4 - r5);
rhs[k][j][i][1] = -r3;
rhs[k][j][i][2] = r2;
rhs[k][j][i][3] = -t1 + t2;
rhs[k][j][i][4] = t1 + t2;
}
}
}
}
void compute_rhs() {
int i, j, k, m;
double aux, rho_inv, uijk, up1, um1, vijk, vp1, vm1, wijk, wp1, wm1;
//---------------------------------------------------------------------
// compute the reciprocal of density, and the kinetic energy,
// and the speed of sound.
//---------------------------------------------------------------------
#pragma omp parallel for default(shared) private(k, j, i, rho_inv, aux) firstprivate(c1c2, grid_points, u)
for(k = 0; k <= grid_points[2] - 1; k++) {
#pragma omp parallel for default(shared) private(j, i, rho_inv, aux) firstprivate(k, c1c2, grid_points, u)
for(j = 0; j <= grid_points[1] - 1; j++) {
#pragma omp parallel for default(shared) private(i, rho_inv, aux) firstprivate(k, j, c1c2, grid_points, u)
for(i = 0; i <= grid_points[0] - 1; i++) {
rho_inv = 1.0 / u[k][j][i][0];
rho_i[k][j][i] = rho_inv;
us[k][j][i] = u[k][j][i][1] * rho_inv;
vs[k][j][i] = u[k][j][i][2] * rho_inv;
ws[k][j][i] = u[k][j][i][3] * rho_inv;
square[k][j][i] = 0.5 * (u[k][j][i][1] * u[k][j][i][1] + u[k][j][i][2] * u[k][j][i][2] + u[k][j][i][3] * u[k][j][i][3]) * rho_inv;
qs[k][j][i] = square[k][j][i] * rho_inv;
//-------------------------------------------------------------------
// (don't need speed and ainx until the lhs computation)
//-------------------------------------------------------------------
aux = c1c2 * rho_inv * (u[k][j][i][4] - square[k][j][i]);
speed[k][j][i] = sqrt(aux);
}
}
}
//---------------------------------------------------------------------
// copy the exact forcing term to the right hand side; because
// this forcing term is known, we can store it on the whole grid
// including the boundary
//---------------------------------------------------------------------
#pragma omp parallel for default(shared) private(k, j, i, m) firstprivate(grid_points, forcing)
for(k = 0; k <= grid_points[2] - 1; k++) {
#pragma omp parallel for default(shared) private(j, i, m) firstprivate(k, grid_points, forcing)
for(j = 0; j <= grid_points[1] - 1; j++) {
#pragma omp parallel for default(shared) private(i, m) firstprivate(k, j, grid_points, forcing)
for(i = 0; i <= grid_points[0] - 1; i++) {
/*************** Clava msgError **************
Loop Iteration number is too low
****************************************/
for(m = 0; m < 5; m++) {
rhs[k][j][i][m] = forcing[k][j][i][m];
}
}
}
}
//---------------------------------------------------------------------
// compute xi-direction fluxes
//---------------------------------------------------------------------
#pragma omp parallel for default(shared) private(k, j, i, m, uijk, up1, um1) firstprivate(nz2, ny2, nx2, dx1tx1, tx2, c2, dx2tx1, xxcon2, con43, dx3tx1, dx4tx1, c1, dx5tx1, xxcon3, xxcon4, xxcon5, dssp, us, u, square, vs, ws, qs, rho_i)
for(k = 1; k <= nz2; k++) {
#pragma omp parallel for default(shared) private(j, i, uijk, up1, um1) firstprivate(ny2, nx2, k, dx1tx1, tx2, c2, dx2tx1, xxcon2, con43, dx3tx1, dx4tx1, c1, dx5tx1, xxcon3, xxcon4, xxcon5, us, u, square, vs, ws, qs, rho_i)
for(j = 1; j <= ny2; j++) {
#pragma omp parallel for default(shared) private(i, uijk, up1, um1) firstprivate(nx2, k, j, dx1tx1, tx2, c2, dx2tx1, xxcon2, con43, dx3tx1, dx4tx1, c1, dx5tx1, xxcon3, xxcon4, xxcon5, us, u, square, vs, ws, qs, rho_i)
for(i = 1; i <= nx2; i++) {
uijk = us[k][j][i];
up1 = us[k][j][i + 1];
um1 = us[k][j][i - 1];
rhs[k][j][i][0] = rhs[k][j][i][0] + dx1tx1 * (u[k][j][i + 1][0] - 2.0 * u[k][j][i][0] + u[k][j][i - 1][0]) - tx2 * (u[k][j][i + 1][1] - u[k][j][i - 1][1]);
rhs[k][j][i][1] = rhs[k][j][i][1] + dx2tx1 * (u[k][j][i + 1][1] - 2.0 * u[k][j][i][1] + u[k][j][i - 1][1]) + xxcon2 * con43 * (up1 - 2.0 * uijk + um1) - tx2 * (u[k][j][i + 1][1] * up1 - u[k][j][i - 1][1] * um1 + (u[k][j][i + 1][4] - square[k][j][i + 1] - u[k][j][i - 1][4] + square[k][j][i - 1]) * c2);
rhs[k][j][i][2] = rhs[k][j][i][2] + dx3tx1 * (u[k][j][i + 1][2] - 2.0 * u[k][j][i][2] + u[k][j][i - 1][2]) + xxcon2 * (vs[k][j][i + 1] - 2.0 * vs[k][j][i] + vs[k][j][i - 1]) - tx2 * (u[k][j][i + 1][2] * up1 - u[k][j][i - 1][2] * um1);
rhs[k][j][i][3] = rhs[k][j][i][3] + dx4tx1 * (u[k][j][i + 1][3] - 2.0 * u[k][j][i][3] + u[k][j][i - 1][3]) + xxcon2 * (ws[k][j][i + 1] - 2.0 * ws[k][j][i] + ws[k][j][i - 1]) - tx2 * (u[k][j][i + 1][3] * up1 - u[k][j][i - 1][3] * um1);
rhs[k][j][i][4] = rhs[k][j][i][4] + dx5tx1 * (u[k][j][i + 1][4] - 2.0 * u[k][j][i][4] + u[k][j][i - 1][4]) + xxcon3 * (qs[k][j][i + 1] - 2.0 * qs[k][j][i] + qs[k][j][i - 1]) + xxcon4 * (up1 * up1 - 2.0 * uijk * uijk + um1 * um1) + xxcon5 * (u[k][j][i + 1][4] * rho_i[k][j][i + 1] - 2.0 * u[k][j][i][4] * rho_i[k][j][i] + u[k][j][i - 1][4] * rho_i[k][j][i - 1]) - tx2 * ((c1 * u[k][j][i + 1][4] - c2 * square[k][j][i + 1]) * up1 - (c1 * u[k][j][i - 1][4] - c2 * square[k][j][i - 1]) * um1);
}
}
//---------------------------------------------------------------------
// add fourth order xi-direction dissipation
//---------------------------------------------------------------------
#pragma omp parallel for default(shared) private(j, m, i) firstprivate(ny2, k, dssp, u)
for(j = 1; j <= ny2; j++) {
i = 1;
/*************** Clava msgError **************
Loop Iteration number is too low
****************************************/
for(m = 0; m < 5; m++) {
rhs[k][j][i][m] = rhs[k][j][i][m] - dssp * (5.0 * u[k][j][i][m] - 4.0 * u[k][j][i + 1][m] + u[k][j][i + 2][m]);
}
i = 2;
/*************** Clava msgError **************
Loop Iteration number is too low
****************************************/
for(m = 0; m < 5; m++) {
rhs[k][j][i][m] = rhs[k][j][i][m] - dssp * (-4.0 * u[k][j][i - 1][m] + 6.0 * u[k][j][i][m] - 4.0 * u[k][j][i + 1][m] + u[k][j][i + 2][m]);
}
}
#pragma omp parallel for default(shared) private(j, i, m) firstprivate(ny2, nx2, k, dssp, u)
for(j = 1; j <= ny2; j++) {
#pragma omp parallel for default(shared) private(i, m) firstprivate(nx2, k, j, dssp, u)
for(i = 3; i <= nx2 - 2; i++) {
/*************** Clava msgError **************
Loop Iteration number is too low
****************************************/
for(m = 0; m < 5; m++) {
rhs[k][j][i][m] = rhs[k][j][i][m] - dssp * (u[k][j][i - 2][m] - 4.0 * u[k][j][i - 1][m] + 6.0 * u[k][j][i][m] - 4.0 * u[k][j][i + 1][m] + u[k][j][i + 2][m]);
}
}
}
#pragma omp parallel for default(shared) private(j, m, i) firstprivate(ny2, nx2, k, dssp, u)
for(j = 1; j <= ny2; j++) {
i = nx2 - 1;
/*************** Clava msgError **************
Loop Iteration number is too low
****************************************/
for(m = 0; m < 5; m++) {
rhs[k][j][i][m] = rhs[k][j][i][m] - dssp * (u[k][j][i - 2][m] - 4.0 * u[k][j][i - 1][m] + 6.0 * u[k][j][i][m] - 4.0 * u[k][j][i + 1][m]);
}
i = nx2;
/*************** Clava msgError **************
Loop Iteration number is too low
****************************************/
for(m = 0; m < 5; m++) {
rhs[k][j][i][m] = rhs[k][j][i][m] - dssp * (u[k][j][i - 2][m] - 4.0 * u[k][j][i - 1][m] + 5.0 * u[k][j][i][m]);
}
}
}
//---------------------------------------------------------------------
// compute eta-direction fluxes
//---------------------------------------------------------------------
#pragma omp parallel for default(shared) private(k, j, i, m, vijk, vp1, vm1) firstprivate(nz2, ny2, nx2, dy1ty1, ty2, dy2ty1, yycon2, c2, dy3ty1, con43, dy4ty1, c1, dy5ty1, yycon3, yycon4, yycon5, dssp, vs, u, us, square, ws, qs, rho_i)
for(k = 1; k <= nz2; k++) {
#pragma omp parallel for default(shared) private(j, i, vijk, vp1, vm1) firstprivate(ny2, nx2, k, dy1ty1, ty2, dy2ty1, yycon2, c2, dy3ty1, con43, dy4ty1, c1, dy5ty1, yycon3, yycon4, yycon5, vs, u, us, square, ws, qs, rho_i)
for(j = 1; j <= ny2; j++) {
#pragma omp parallel for default(shared) private(i, vijk, vp1, vm1) firstprivate(nx2, k, j, dy1ty1, ty2, dy2ty1, yycon2, c2, dy3ty1, con43, dy4ty1, c1, dy5ty1, yycon3, yycon4, yycon5, vs, u, us, square, ws, qs, rho_i)
for(i = 1; i <= nx2; i++) {
vijk = vs[k][j][i];
vp1 = vs[k][j + 1][i];
vm1 = vs[k][j - 1][i];
rhs[k][j][i][0] = rhs[k][j][i][0] + dy1ty1 * (u[k][j + 1][i][0] - 2.0 * u[k][j][i][0] + u[k][j - 1][i][0]) - ty2 * (u[k][j + 1][i][2] - u[k][j - 1][i][2]);
rhs[k][j][i][1] = rhs[k][j][i][1] + dy2ty1 * (u[k][j + 1][i][1] - 2.0 * u[k][j][i][1] + u[k][j - 1][i][1]) + yycon2 * (us[k][j + 1][i] - 2.0 * us[k][j][i] + us[k][j - 1][i]) - ty2 * (u[k][j + 1][i][1] * vp1 - u[k][j - 1][i][1] * vm1);
rhs[k][j][i][2] = rhs[k][j][i][2] + dy3ty1 * (u[k][j + 1][i][2] - 2.0 * u[k][j][i][2] + u[k][j - 1][i][2]) + yycon2 * con43 * (vp1 - 2.0 * vijk + vm1) - ty2 * (u[k][j + 1][i][2] * vp1 - u[k][j - 1][i][2] * vm1 + (u[k][j + 1][i][4] - square[k][j + 1][i] - u[k][j - 1][i][4] + square[k][j - 1][i]) * c2);
rhs[k][j][i][3] = rhs[k][j][i][3] + dy4ty1 * (u[k][j + 1][i][3] - 2.0 * u[k][j][i][3] + u[k][j - 1][i][3]) + yycon2 * (ws[k][j + 1][i] - 2.0 * ws[k][j][i] + ws[k][j - 1][i]) - ty2 * (u[k][j + 1][i][3] * vp1 - u[k][j - 1][i][3] * vm1);
rhs[k][j][i][4] = rhs[k][j][i][4] + dy5ty1 * (u[k][j + 1][i][4] - 2.0 * u[k][j][i][4] + u[k][j - 1][i][4]) + yycon3 * (qs[k][j + 1][i] - 2.0 * qs[k][j][i] + qs[k][j - 1][i]) + yycon4 * (vp1 * vp1 - 2.0 * vijk * vijk + vm1 * vm1) + yycon5 * (u[k][j + 1][i][4] * rho_i[k][j + 1][i] - 2.0 * u[k][j][i][4] * rho_i[k][j][i] + u[k][j - 1][i][4] * rho_i[k][j - 1][i]) - ty2 * ((c1 * u[k][j + 1][i][4] - c2 * square[k][j + 1][i]) * vp1 - (c1 * u[k][j - 1][i][4] - c2 * square[k][j - 1][i]) * vm1);
}
}
//---------------------------------------------------------------------
// add fourth order eta-direction dissipation
//---------------------------------------------------------------------
j = 1;
#pragma omp parallel for default(shared) private(i, m) firstprivate(nx2, j, k, dssp, u)
for(i = 1; i <= nx2; i++) {
/*************** Clava msgError **************
Loop Iteration number is too low
****************************************/
for(m = 0; m < 5; m++) {
rhs[k][j][i][m] = rhs[k][j][i][m] - dssp * (5.0 * u[k][j][i][m] - 4.0 * u[k][j + 1][i][m] + u[k][j + 2][i][m]);
}
}
j = 2;
#pragma omp parallel for default(shared) private(i, m) firstprivate(nx2, j, k, dssp, u)
for(i = 1; i <= nx2; i++) {
/*************** Clava msgError **************
Loop Iteration number is too low
****************************************/
for(m = 0; m < 5; m++) {
rhs[k][j][i][m] = rhs[k][j][i][m] - dssp * (-4.0 * u[k][j - 1][i][m] + 6.0 * u[k][j][i][m] - 4.0 * u[k][j + 1][i][m] + u[k][j + 2][i][m]);
}
}
#pragma omp parallel for default(shared) private(j, i, m) firstprivate(ny2, nx2, k, dssp, u)
for(j = 3; j <= ny2 - 2; j++) {
#pragma omp parallel for default(shared) private(i, m) firstprivate(nx2, j, k, dssp, u)
for(i = 1; i <= nx2; i++) {
/*************** Clava msgError **************
Loop Iteration number is too low
****************************************/
for(m = 0; m < 5; m++) {
rhs[k][j][i][m] = rhs[k][j][i][m] - dssp * (u[k][j - 2][i][m] - 4.0 * u[k][j - 1][i][m] + 6.0 * u[k][j][i][m] - 4.0 * u[k][j + 1][i][m] + u[k][j + 2][i][m]);
}
}
}
j = ny2 - 1;
#pragma omp parallel for default(shared) private(i, m) firstprivate(nx2, j, k, ny2, dssp, u)
for(i = 1; i <= nx2; i++) {
/*************** Clava msgError **************
Loop Iteration number is too low
****************************************/
for(m = 0; m < 5; m++) {
rhs[k][j][i][m] = rhs[k][j][i][m] - dssp * (u[k][j - 2][i][m] - 4.0 * u[k][j - 1][i][m] + 6.0 * u[k][j][i][m] - 4.0 * u[k][j + 1][i][m]);
}
}
j = ny2;
#pragma omp parallel for default(shared) private(i, m) firstprivate(nx2, j, k, ny2, dssp, u)
for(i = 1; i <= nx2; i++) {
/*************** Clava msgError **************
Loop Iteration number is too low
****************************************/
for(m = 0; m < 5; m++) {
rhs[k][j][i][m] = rhs[k][j][i][m] - dssp * (u[k][j - 2][i][m] - 4.0 * u[k][j - 1][i][m] + 5.0 * u[k][j][i][m]);
}
}
}
//---------------------------------------------------------------------
// compute zeta-direction fluxes
//---------------------------------------------------------------------
#pragma omp parallel for default(shared) private(k, j, i, wijk, wp1, wm1) firstprivate(nz2, ny2, nx2, dz1tz1, tz2, dz2tz1, zzcon2, dz3tz1, c2, dz4tz1, con43, c1, dz5tz1, zzcon3, zzcon4, zzcon5, ws, u, us, vs, square, qs, rho_i)
for(k = 1; k <= nz2; k++) {
#pragma omp parallel for default(shared) private(j, i, wijk, wp1, wm1) firstprivate(ny2, nx2, k, dz1tz1, tz2, dz2tz1, zzcon2, dz3tz1, c2, dz4tz1, con43, c1, dz5tz1, zzcon3, zzcon4, zzcon5, ws, u, us, vs, square, qs, rho_i)
for(j = 1; j <= ny2; j++) {
#pragma omp parallel for default(shared) private(i, wijk, wp1, wm1) firstprivate(nx2, k, j, dz1tz1, tz2, dz2tz1, zzcon2, dz3tz1, c2, dz4tz1, con43, c1, dz5tz1, zzcon3, zzcon4, zzcon5, ws, u, us, vs, square, qs, rho_i)
for(i = 1; i <= nx2; i++) {
wijk = ws[k][j][i];
wp1 = ws[k + 1][j][i];
wm1 = ws[k - 1][j][i];
rhs[k][j][i][0] = rhs[k][j][i][0] + dz1tz1 * (u[k + 1][j][i][0] - 2.0 * u[k][j][i][0] + u[k - 1][j][i][0]) - tz2 * (u[k + 1][j][i][3] - u[k - 1][j][i][3]);
rhs[k][j][i][1] = rhs[k][j][i][1] + dz2tz1 * (u[k + 1][j][i][1] - 2.0 * u[k][j][i][1] + u[k - 1][j][i][1]) + zzcon2 * (us[k + 1][j][i] - 2.0 * us[k][j][i] + us[k - 1][j][i]) - tz2 * (u[k + 1][j][i][1] * wp1 - u[k - 1][j][i][1] * wm1);
rhs[k][j][i][2] = rhs[k][j][i][2] + dz3tz1 * (u[k + 1][j][i][2] - 2.0 * u[k][j][i][2] + u[k - 1][j][i][2]) + zzcon2 * (vs[k + 1][j][i] - 2.0 * vs[k][j][i] + vs[k - 1][j][i]) - tz2 * (u[k + 1][j][i][2] * wp1 - u[k - 1][j][i][2] * wm1);
rhs[k][j][i][3] = rhs[k][j][i][3] + dz4tz1 * (u[k + 1][j][i][3] - 2.0 * u[k][j][i][3] + u[k - 1][j][i][3]) + zzcon2 * con43 * (wp1 - 2.0 * wijk + wm1) - tz2 * (u[k + 1][j][i][3] * wp1 - u[k - 1][j][i][3] * wm1 + (u[k + 1][j][i][4] - square[k + 1][j][i] - u[k - 1][j][i][4] + square[k - 1][j][i]) * c2);
rhs[k][j][i][4] = rhs[k][j][i][4] + dz5tz1 * (u[k + 1][j][i][4] - 2.0 * u[k][j][i][4] + u[k - 1][j][i][4]) + zzcon3 * (qs[k + 1][j][i] - 2.0 * qs[k][j][i] + qs[k - 1][j][i]) + zzcon4 * (wp1 * wp1 - 2.0 * wijk * wijk + wm1 * wm1) + zzcon5 * (u[k + 1][j][i][4] * rho_i[k + 1][j][i] - 2.0 * u[k][j][i][4] * rho_i[k][j][i] + u[k - 1][j][i][4] * rho_i[k - 1][j][i]) - tz2 * ((c1 * u[k + 1][j][i][4] - c2 * square[k + 1][j][i]) * wp1 - (c1 * u[k - 1][j][i][4] - c2 * square[k - 1][j][i]) * wm1);
}
}
}
//---------------------------------------------------------------------
// add fourth order zeta-direction dissipation
//---------------------------------------------------------------------
k = 1;
#pragma omp parallel for default(shared) private(j, i, m) firstprivate(ny2, nx2, k, dssp, u)
for(j = 1; j <= ny2; j++) {
#pragma omp parallel for default(shared) private(i, m) firstprivate(nx2, k, j, dssp, u)
for(i = 1; i <= nx2; i++) {
/*************** Clava msgError **************
Loop Iteration number is too low
****************************************/
for(m = 0; m < 5; m++) {
rhs[k][j][i][m] = rhs[k][j][i][m] - dssp * (5.0 * u[k][j][i][m] - 4.0 * u[k + 1][j][i][m] + u[k + 2][j][i][m]);
}
}
}
k = 2;
#pragma omp parallel for default(shared) private(j, i, m) firstprivate(ny2, nx2, k, dssp, u)
for(j = 1; j <= ny2; j++) {
#pragma omp parallel for default(shared) private(i, m) firstprivate(nx2, k, j, dssp, u)
for(i = 1; i <= nx2; i++) {
/*************** Clava msgError **************
Loop Iteration number is too low
****************************************/
for(m = 0; m < 5; m++) {
rhs[k][j][i][m] = rhs[k][j][i][m] - dssp * (-4.0 * u[k - 1][j][i][m] + 6.0 * u[k][j][i][m] - 4.0 * u[k + 1][j][i][m] + u[k + 2][j][i][m]);
}
}
}
#pragma omp parallel for default(shared) private(k, j, i, m) firstprivate(nz2, ny2, nx2, dssp, u)
for(k = 3; k <= nz2 - 2; k++) {
#pragma omp parallel for default(shared) private(j, i, m) firstprivate(ny2, nx2, k, dssp, u)
for(j = 1; j <= ny2; j++) {
#pragma omp parallel for default(shared) private(i, m) firstprivate(nx2, k, j, dssp, u)
for(i = 1; i <= nx2; i++) {
/*************** Clava msgError **************
Loop Iteration number is too low
****************************************/
for(m = 0; m < 5; m++) {
rhs[k][j][i][m] = rhs[k][j][i][m] - dssp * (u[k - 2][j][i][m] - 4.0 * u[k - 1][j][i][m] + 6.0 * u[k][j][i][m] - 4.0 * u[k + 1][j][i][m] + u[k + 2][j][i][m]);
}
}
}
}
k = nz2 - 1;
#pragma omp parallel for default(shared) private(j, i, m) firstprivate(ny2, nx2, k, dssp, u)
for(j = 1; j <= ny2; j++) {
#pragma omp parallel for default(shared) private(i, m) firstprivate(nx2, k, j, dssp, u)
for(i = 1; i <= nx2; i++) {
/*************** Clava msgError **************
Loop Iteration number is too low
****************************************/
for(m = 0; m < 5; m++) {
rhs[k][j][i][m] = rhs[k][j][i][m] - dssp * (u[k - 2][j][i][m] - 4.0 * u[k - 1][j][i][m] + 6.0 * u[k][j][i][m] - 4.0 * u[k + 1][j][i][m]);
}
}
}
k = nz2;
#pragma omp parallel for default(shared) private(j, i, m) firstprivate(ny2, nx2, k, dssp, u)
for(j = 1; j <= ny2; j++) {
#pragma omp parallel for default(shared) private(i, m) firstprivate(nx2, k, j, dssp, u)
for(i = 1; i <= nx2; i++) {
/*************** Clava msgError **************
Loop Iteration number is too low
****************************************/
for(m = 0; m < 5; m++) {
rhs[k][j][i][m] = rhs[k][j][i][m] - dssp * (u[k - 2][j][i][m] - 4.0 * u[k - 1][j][i][m] + 5.0 * u[k][j][i][m]);
}
}
}
#pragma omp parallel for default(shared) private(k, j, i, m) firstprivate(nz2, ny2, nx2, dt)
for(k = 1; k <= nz2; k++) {
#pragma omp parallel for default(shared) private(j, i, m) firstprivate(ny2, nx2, k, dt)
for(j = 1; j <= ny2; j++) {
#pragma omp parallel for default(shared) private(i, m) firstprivate(nx2, k, j, dt)
for(i = 1; i <= nx2; i++) {
/*************** Clava msgError **************
Loop Iteration number is too low
****************************************/
for(m = 0; m < 5; m++) {
rhs[k][j][i][m] = rhs[k][j][i][m] * dt;
}
}
}
}
}
//---------------------------------------------------------------------
// block-diagonal matrix-vector multiplication
//---------------------------------------------------------------------
void txinvr() {
int i, j, k;
double t1, t2, t3, ac, ru1, uu, vv, ww, r1, r2, r3, r4, r5, ac2inv;
#pragma omp parallel for default(shared) private(k, j, i, ru1, uu, vv, ww, ac, ac2inv, r1, r2, r3, r4, r5, t1, t2, t3) firstprivate(nz2, ny2, nx2, c2, bt, rho_i, us, vs, ws, speed, qs)
for(k = 1; k <= nz2; k++) {
#pragma omp parallel for default(shared) private(j, i, ru1, uu, vv, ww, ac, ac2inv, r1, r2, r3, r4, r5, t1, t2, t3) firstprivate(ny2, nx2, k, c2, bt, rho_i, us, vs, ws, speed, qs)
for(j = 1; j <= ny2; j++) {
#pragma omp parallel for default(shared) private(i, ru1, uu, vv, ww, ac, ac2inv, r1, r2, r3, r4, r5, t1, t2, t3) firstprivate(nx2, k, j, c2, bt, rho_i, us, vs, ws, speed, qs)
for(i = 1; i <= nx2; i++) {
ru1 = rho_i[k][j][i];
uu = us[k][j][i];
vv = vs[k][j][i];
ww = ws[k][j][i];
ac = speed[k][j][i];
ac2inv = ac * ac;
r1 = rhs[k][j][i][0];
r2 = rhs[k][j][i][1];
r3 = rhs[k][j][i][2];
r4 = rhs[k][j][i][3];
r5 = rhs[k][j][i][4];
t1 = c2 / ac2inv * (qs[k][j][i] * r1 - uu * r2 - vv * r3 - ww * r4 + r5);
t2 = bt * ru1 * (uu * r1 - r2);
t3 = (bt * ru1 * ac) * t1;
rhs[k][j][i][0] = r1 - t1;
rhs[k][j][i][1] = -ru1 * (ww * r1 - r4);
rhs[k][j][i][2] = ru1 * (vv * r1 - r3);
rhs[k][j][i][3] = -t2 + t3;
rhs[k][j][i][4] = t2 + t3;
}
}
}
}
//---------------------------------------------------------------------
// block-diagonal matrix-vector multiplication
//---------------------------------------------------------------------
void tzetar() {
int i, j, k;
double t1, t2, t3, ac, xvel, yvel, zvel, r1, r2, r3, r4, r5;
double btuz, ac2u, uzik1;
#pragma omp parallel for default(shared) private(k, j, i, xvel, yvel, zvel, ac, ac2u, r1, r2, r3, r4, r5, uzik1, btuz, t1, t2, t3) firstprivate(nz2, ny2, nx2, bt, c2iv, us, vs, ws, speed, u, qs)
for(k = 1; k <= nz2; k++) {
#pragma omp parallel for default(shared) private(j, i, xvel, yvel, zvel, ac, ac2u, r1, r2, r3, r4, r5, uzik1, btuz, t1, t2, t3) firstprivate(ny2, nx2, k, bt, c2iv, us, vs, ws, speed, u, qs)
for(j = 1; j <= ny2; j++) {
#pragma omp parallel for default(shared) private(i, xvel, yvel, zvel, ac, ac2u, r1, r2, r3, r4, r5, uzik1, btuz, t1, t2, t3) firstprivate(nx2, k, j, bt, c2iv, us, vs, ws, speed, u, qs)
for(i = 1; i <= nx2; i++) {
xvel = us[k][j][i];
yvel = vs[k][j][i];
zvel = ws[k][j][i];
ac = speed[k][j][i];
ac2u = ac * ac;
r1 = rhs[k][j][i][0];
r2 = rhs[k][j][i][1];
r3 = rhs[k][j][i][2];
r4 = rhs[k][j][i][3];
r5 = rhs[k][j][i][4];
uzik1 = u[k][j][i][0];
btuz = bt * uzik1;
t1 = btuz / ac * (r4 + r5);
t2 = r3 + t1;
t3 = btuz * (r4 - r5);
rhs[k][j][i][0] = t2;
rhs[k][j][i][1] = -uzik1 * r2 + xvel * t2;
rhs[k][j][i][2] = uzik1 * r1 + yvel * t2;
rhs[k][j][i][3] = zvel * t2 + t3;
rhs[k][j][i][4] = uzik1 * (-xvel * r2 + yvel * r1) + qs[k][j][i] * t2 + c2iv * ac2u * t1 + zvel * t3;
}
}
}
}
//---------------------------------------------------------------------
// verification routine
//---------------------------------------------------------------------
void verify(int no_time_steps, char *Class, int *verified) {
double xcrref[5];
double xceref[5];
double xcrdif[5];
double xcedif[5];
double epsilon;
double xce[5];
double xcr[5];
double dtref = 0.0;
int m;
//---------------------------------------------------------------------
// tolerance level
//---------------------------------------------------------------------
epsilon = 1.0e-08;
//---------------------------------------------------------------------
// compute the error norm and the residual norm, and exit if not printing
//---------------------------------------------------------------------
error_norm(xce);
compute_rhs();
rhs_norm(xcr);
/*************** Clava msgError **************
Loop Iteration number is too low
****************************************/
for(m = 0; m < 5; m++) {
xcr[m] = xcr[m] / dt;
}
*Class = 'U';
*verified = 1;
/*************** Clava msgError **************
Loop Iteration number is too low
****************************************/
for(m = 0; m < 5; m++) {
xcrref[m] = 1.0;
xceref[m] = 1.0;
}
//---------------------------------------------------------------------
// reference data for 12X12X12 grids after 100 time steps,
// with DT = 1.50e-02
//---------------------------------------------------------------------
if((grid_points[0] == 12) && (grid_points[1] == 12) && (grid_points[2] == 12) && (no_time_steps == 100)) {
*Class = 'S';
dtref = 1.5e-2;
//---------------------------------------------------------------------
// 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;
//---------------------------------------------------------------------
// 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;
//---------------------------------------------------------------------
// reference data for 36X36X36 grids after 400 time steps,
// with DT = 1.5e-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;
//---------------------------------------------------------------------
// 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;
//---------------------------------------------------------------------
// 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;
//---------------------------------------------------------------------
// reference data for 64X64X64 grids after 400 time steps,
// with DT = 1.5e-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;
//---------------------------------------------------------------------
// 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;
//---------------------------------------------------------------------
// 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;
//---------------------------------------------------------------------
// reference data for 102X102X102 grids after 400 time steps,
// with DT = 1.0e-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;
//---------------------------------------------------------------------
// 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;
//---------------------------------------------------------------------
// 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;
//---------------------------------------------------------------------
// reference data for 162X162X162 grids after 400 time steps,
// with DT = 0.67e-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;
//---------------------------------------------------------------------
// 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;
//---------------------------------------------------------------------
// 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;
//---------------------------------------------------------------------
// reference data for 408X408X408 grids after 500 time steps,
// with DT = 0.3e-03
//---------------------------------------------------------------------
}
else if((grid_points[0] == 408) && (grid_points[1] == 408) && (grid_points[2] == 408) && (no_time_steps == 500)) {
*Class = 'D';
dtref = 0.30e-3;
//---------------------------------------------------------------------
// Reference values of RMS-norms of residual.
//---------------------------------------------------------------------
xcrref[0] = 0.1044696216887e+05;
xcrref[1] = 0.3204427762578e+04;
xcrref[2] = 0.4648680733032e+04;
xcrref[3] = 0.4238923283697e+04;
xcrref[4] = 0.7588412036136e+04;
//---------------------------------------------------------------------
// Reference values of RMS-norms of solution error.
//---------------------------------------------------------------------
xceref[0] = 0.5089471423669e+01;
xceref[1] = 0.5323514855894e+00;
xceref[2] = 0.1187051008971e+01;
xceref[3] = 0.1083734951938e+01;
xceref[4] = 0.1164108338568e+02;
//---------------------------------------------------------------------
// reference data for 1020X1020X1020 grids after 500 time steps,
// with DT = 0.1e-03
//---------------------------------------------------------------------
}
else if((grid_points[0] == 1020) && (grid_points[1] == 1020) && (grid_points[2] == 1020) && (no_time_steps == 500)) {
*Class = 'E';
dtref = 0.10e-3;
//---------------------------------------------------------------------
// Reference values of RMS-norms of residual.
//---------------------------------------------------------------------
xcrref[0] = 0.6255387422609e+05;
xcrref[1] = 0.1495317020012e+05;
xcrref[2] = 0.2347595750586e+05;
xcrref[3] = 0.2091099783534e+05;
xcrref[4] = 0.4770412841218e+05;
//---------------------------------------------------------------------
// Reference values of RMS-norms of solution error.
//---------------------------------------------------------------------
xceref[0] = 0.6742735164909e+02;
xceref[1] = 0.5390656036938e+01;
xceref[2] = 0.1680647196477e+02;
xceref[3] = 0.1536963126457e+02;
xceref[4] = 0.1575330146156e+03;
}
else {
*verified = 0;
}
//---------------------------------------------------------------------
// verification test for residuals if gridsize is one of
// the defined grid sizes above (class .ne. 'U')
//---------------------------------------------------------------------
//---------------------------------------------------------------------
// Compute the difference of solution values and the known reference values.
//---------------------------------------------------------------------
/*************** Clava msgError **************
Loop Iteration number is too low
****************************************/
for(m = 0; m < 5; m++) {
xcrdif[m] = fabs((xcr[m] - xcrref[m]) / xcrref[m]);
xcedif[m] = fabs((xce[m] - xceref[m]) / xceref[m]);
}
//---------------------------------------------------------------------
// Output the comparison of computed results to known cases.
//---------------------------------------------------------------------
if(*Class != 'U') {
printf(" Verification being performed for class %c\n", *Class);
printf(" accuracy setting for epsilon = %20.13E\n", epsilon);
*verified = (fabs(dt - dtref) <= epsilon);
if(!(*verified)) {
*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");
}
/*************** Clava msgError **************
Loop Iteration number is too low
****************************************/
for(m = 0; m < 5; m++) {
if(*Class == 'U') {
printf(" %2d%20.13E\n", m + 1, xcr[m]);
}
else if(xcrdif[m] <= epsilon) {
printf(" %2d%20.13E%20.13E%20.13E\n", m + 1, xcr[m], xcrref[m], xcrdif[m]);
}
else {
*verified = 0;
printf(" FAILURE: %2d%20.13E%20.13E%20.13E\n", m + 1, 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");
}
/*************** Clava msgError **************
Loop Iteration number is too low
****************************************/
for(m = 0; m < 5; m++) {
if(*Class == 'U') {
printf(" %2d%20.13E\n", m + 1, xce[m]);
}
else if(xcedif[m] <= epsilon) {
printf(" %2d%20.13E%20.13E%20.13E\n", m + 1, xce[m], xceref[m], xcedif[m]);
}
else {
*verified = 0;
printf(" FAILURE: %2d%20.13E%20.13E%20.13E\n", m + 1, 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");
}
}
//---------------------------------------------------------------------
// this function performs the solution of the approximate factorization
// step in the x-direction for all five matrix components
// simultaneously. The Thomas algorithm is employed to solve the
// systems for the x-lines. Boundary conditions are non-periodic
//---------------------------------------------------------------------
void x_solve() {
int i, j, k, i1, i2, m;
double ru1, fac1, fac2;
double rhon[36];
double cv[36];
double lhs[37][37][5];
double lhsp[37][37][5];
double lhsm[37][37][5];
#pragma omp parallel for default(shared) private(k, j, i, m, ru1, i1, i2, fac1, fac2) firstprivate(nz2, ny2, nx2, c3c4, con43, c1c5, dx2, dx5, dxmax, dx1, dttx2, dttx1, c2dttx1, comz5, comz4, comz1, comz6, grid_points, rho_i, us, speed, lhs, lhsp, lhsm, cv, rhon)
for(k = 1; k <= nz2; k++) {
lhsinit(nx2 + 1, ny2, lhs, lhsp, lhsm);
//---------------------------------------------------------------------
// Computes the left hand side for the three x-factors
//---------------------------------------------------------------------
//---------------------------------------------------------------------
// first fill the lhs for the u-eigenvalue
//---------------------------------------------------------------------
#pragma omp parallel for default(shared) private(j, i, ru1) firstprivate(ny2, c3c4, k, con43, c1c5, dx2, dx5, dxmax, dx1, nx2, dttx2, dttx1, c2dttx1, grid_points, rho_i, us, cv, rhon)
for(j = 1; j <= ny2; j++) {
#pragma omp parallel for default(shared) private(i, ru1) firstprivate(c3c4, k, j, con43, c1c5, dx2, dx5, dxmax, dx1, grid_points, rho_i, us)
for(i = 0; i <= grid_points[0] - 1; i++) {
ru1 = c3c4 * rho_i[k][j][i];
cv[i] = us[k][j][i];
rhon[i] = ((((dx2 + con43 * ru1) > (dx5 + c1c5 * ru1) ? (dx2 + con43 * ru1) : (dx5 + c1c5 * ru1))) > (((dxmax + ru1) > (dx1) ? (dxmax + ru1) : (dx1))) ? (((dx2 + con43 * ru1) > (dx5 + c1c5 * ru1) ? (dx2 + con43 * ru1) : (dx5 + c1c5 * ru1))) : (((dxmax + ru1) > (dx1) ? (dxmax + ru1) : (dx1))));
}
#pragma omp parallel for default(shared) private(i) firstprivate(nx2, j, dttx2, dttx1, c2dttx1, cv, rhon)
for(i = 1; i <= nx2; i++) {
lhs[j][i][0] = 0.0;
lhs[j][i][1] = -dttx2 * cv[i - 1] - dttx1 * rhon[i - 1];
lhs[j][i][2] = 1.0 + c2dttx1 * rhon[i];
lhs[j][i][3] = dttx2 * cv[i + 1] - dttx1 * rhon[i + 1];
lhs[j][i][4] = 0.0;
}
}
//---------------------------------------------------------------------
// add fourth order dissipation
//---------------------------------------------------------------------
#pragma omp parallel for default(shared) private(j, i) firstprivate(ny2, comz5, comz4, comz1, comz6)
for(j = 1; j <= ny2; j++) {
i = 1;
lhs[j][i][2] = lhs[j][i][2] + comz5;
lhs[j][i][3] = lhs[j][i][3] - comz4;
lhs[j][i][4] = lhs[j][i][4] + comz1;
lhs[j][i + 1][1] = lhs[j][i + 1][1] - comz4;
lhs[j][i + 1][2] = lhs[j][i + 1][2] + comz6;
lhs[j][i + 1][3] = lhs[j][i + 1][3] - comz4;
lhs[j][i + 1][4] = lhs[j][i + 1][4] + comz1;
}
#pragma omp parallel for default(shared) private(j, i) firstprivate(ny2, comz1, comz4, comz6, grid_points)
for(j = 1; j <= ny2; j++) {
#pragma omp parallel for default(shared) private(i) firstprivate(j, comz1, comz4, comz6, grid_points)
for(i = 3; i <= grid_points[0] - 4; i++) {
lhs[j][i][0] = lhs[j][i][0] + comz1;
lhs[j][i][1] = lhs[j][i][1] - comz4;
lhs[j][i][2] = lhs[j][i][2] + comz6;
lhs[j][i][3] = lhs[j][i][3] - comz4;
lhs[j][i][4] = lhs[j][i][4] + comz1;
}
}
#pragma omp parallel for default(shared) private(j, i) firstprivate(ny2, comz1, comz4, comz6, comz5, grid_points)
for(j = 1; j <= ny2; j++) {
i = grid_points[0] - 3;
lhs[j][i][0] = lhs[j][i][0] + comz1;
lhs[j][i][1] = lhs[j][i][1] - comz4;
lhs[j][i][2] = lhs[j][i][2] + comz6;
lhs[j][i][3] = lhs[j][i][3] - comz4;
lhs[j][i + 1][0] = lhs[j][i + 1][0] + comz1;
lhs[j][i + 1][1] = lhs[j][i + 1][1] - comz4;
lhs[j][i + 1][2] = lhs[j][i + 1][2] + comz5;
}
//---------------------------------------------------------------------
// subsequently, fill the other factors (u+c), (u-c) by adding to
// the first
//---------------------------------------------------------------------
#pragma omp parallel for default(shared) private(j, i) firstprivate(ny2, nx2, dttx2, k, lhs, speed)
for(j = 1; j <= ny2; j++) {
#pragma omp parallel for default(shared) private(i) firstprivate(nx2, j, dttx2, k, lhs, speed)
for(i = 1; i <= nx2; i++) {
lhsp[j][i][0] = lhs[j][i][0];
lhsp[j][i][1] = lhs[j][i][1] - dttx2 * speed[k][j][i - 1];
lhsp[j][i][2] = lhs[j][i][2];
lhsp[j][i][3] = lhs[j][i][3] + dttx2 * speed[k][j][i + 1];
lhsp[j][i][4] = lhs[j][i][4];
lhsm[j][i][0] = lhs[j][i][0];
lhsm[j][i][1] = lhs[j][i][1] + dttx2 * speed[k][j][i - 1];
lhsm[j][i][2] = lhs[j][i][2];
lhsm[j][i][3] = lhs[j][i][3] - dttx2 * speed[k][j][i + 1];
lhsm[j][i][4] = lhs[j][i][4];
}
}
//---------------------------------------------------------------------
// FORWARD ELIMINATION
//---------------------------------------------------------------------
//---------------------------------------------------------------------
// perform the Thomas algorithm; first, FORWARD ELIMINATION
//---------------------------------------------------------------------
#pragma omp parallel for default(shared) private(j, i, m, i1, i2, fac1) firstprivate(ny2, k, grid_points)
for(j = 1; j <= ny2; j++) {
/*************** Clava msgError **************
unsolved dependency for arrayAccess lhs use : RWR
unsolved dependency for arrayAccess rhs use : RW
****************************************/
for(i = 0; i <= grid_points[0] - 3; i++) {
i1 = i + 1;
i2 = i + 2;
fac1 = 1.0 / lhs[j][i][2];
lhs[j][i][3] = fac1 * lhs[j][i][3];
lhs[j][i][4] = fac1 * lhs[j][i][4];
/*************** Clava msgError **************
Loop Iteration number is too low
****************************************/
for(m = 0; m < 3; m++) {
rhs[k][j][i][m] = fac1 * rhs[k][j][i][m];
}
lhs[j][i1][2] = lhs[j][i1][2] - lhs[j][i1][1] * lhs[j][i][3];
lhs[j][i1][3] = lhs[j][i1][3] - lhs[j][i1][1] * lhs[j][i][4];
/*************** Clava msgError **************
Loop Iteration number is too low
****************************************/
for(m = 0; m < 3; m++) {
rhs[k][j][i1][m] = rhs[k][j][i1][m] - lhs[j][i1][1] * rhs[k][j][i][m];
}
lhs[j][i2][1] = lhs[j][i2][1] - lhs[j][i2][0] * lhs[j][i][3];
lhs[j][i2][2] = lhs[j][i2][2] - lhs[j][i2][0] * lhs[j][i][4];
/*************** Clava msgError **************
Loop Iteration number is too low
****************************************/
for(m = 0; m < 3; m++) {
rhs[k][j][i2][m] = rhs[k][j][i2][m] - lhs[j][i2][0] * rhs[k][j][i][m];
}
}
}
//---------------------------------------------------------------------
// The last two rows in this grid block are a bit different,
// since they for (not have two more rows available for the
// elimination of off-diagonal entries
//---------------------------------------------------------------------
#pragma omp parallel for default(shared) private(j, m, i, i1, fac1, fac2) firstprivate(ny2, k, grid_points)
for(j = 1; j <= ny2; j++) {
i = grid_points[0] - 2;
i1 = grid_points[0] - 1;
fac1 = 1.0 / lhs[j][i][2];
lhs[j][i][3] = fac1 * lhs[j][i][3];
lhs[j][i][4] = fac1 * lhs[j][i][4];
/*************** Clava msgError **************
Loop Iteration number is too low
****************************************/
for(m = 0; m < 3; m++) {
rhs[k][j][i][m] = fac1 * rhs[k][j][i][m];
}
lhs[j][i1][2] = lhs[j][i1][2] - lhs[j][i1][1] * lhs[j][i][3];
lhs[j][i1][3] = lhs[j][i1][3] - lhs[j][i1][1] * lhs[j][i][4];
/*************** Clava msgError **************
Loop Iteration number is too low
****************************************/
for(m = 0; m < 3; m++) {
rhs[k][j][i1][m] = rhs[k][j][i1][m] - lhs[j][i1][1] * rhs[k][j][i][m];
}
//---------------------------------------------------------------------
// scale the last row immediately
//---------------------------------------------------------------------
fac2 = 1.0 / lhs[j][i1][2];
/*************** Clava msgError **************
Loop Iteration number is too low
****************************************/
for(m = 0; m < 3; m++) {
rhs[k][j][i1][m] = fac2 * rhs[k][j][i1][m];
}
}
//---------------------------------------------------------------------
// for (the u+c and the u-c factors
//---------------------------------------------------------------------
#pragma omp parallel for default(shared) private(j, i, i1, i2, m, fac1) firstprivate(ny2, k, grid_points)
for(j = 1; j <= ny2; j++) {
/*************** Clava msgError **************
unsolved dependency for arrayAccess lhsp use : RWR
unsolved dependency for arrayAccess rhs use : RW
unsolved dependency for arrayAccess lhsm use : RWR
****************************************/
for(i = 0; i <= grid_points[0] - 3; i++) {
i1 = i + 1;
i2 = i + 2;
m = 3;
fac1 = 1.0 / lhsp[j][i][2];
lhsp[j][i][3] = fac1 * lhsp[j][i][3];
lhsp[j][i][4] = fac1 * lhsp[j][i][4];
rhs[k][j][i][m] = fac1 * rhs[k][j][i][m];
lhsp[j][i1][2] = lhsp[j][i1][2] - lhsp[j][i1][1] * lhsp[j][i][3];
lhsp[j][i1][3] = lhsp[j][i1][3] - lhsp[j][i1][1] * lhsp[j][i][4];
rhs[k][j][i1][m] = rhs[k][j][i1][m] - lhsp[j][i1][1] * rhs[k][j][i][m];
lhsp[j][i2][1] = lhsp[j][i2][1] - lhsp[j][i2][0] * lhsp[j][i][3];
lhsp[j][i2][2] = lhsp[j][i2][2] - lhsp[j][i2][0] * lhsp[j][i][4];
rhs[k][j][i2][m] = rhs[k][j][i2][m] - lhsp[j][i2][0] * rhs[k][j][i][m];
m = 4;
fac1 = 1.0 / lhsm[j][i][2];
lhsm[j][i][3] = fac1 * lhsm[j][i][3];
lhsm[j][i][4] = fac1 * lhsm[j][i][4];
rhs[k][j][i][m] = fac1 * rhs[k][j][i][m];
lhsm[j][i1][2] = lhsm[j][i1][2] - lhsm[j][i1][1] * lhsm[j][i][3];
lhsm[j][i1][3] = lhsm[j][i1][3] - lhsm[j][i1][1] * lhsm[j][i][4];
rhs[k][j][i1][m] = rhs[k][j][i1][m] - lhsm[j][i1][1] * rhs[k][j][i][m];
lhsm[j][i2][1] = lhsm[j][i2][1] - lhsm[j][i2][0] * lhsm[j][i][3];
lhsm[j][i2][2] = lhsm[j][i2][2] - lhsm[j][i2][0] * lhsm[j][i][4];
rhs[k][j][i2][m] = rhs[k][j][i2][m] - lhsm[j][i2][0] * rhs[k][j][i][m];
}
}
//---------------------------------------------------------------------
// And again the last two rows separately
//---------------------------------------------------------------------
#pragma omp parallel for default(shared) private(j, i, i1, m, fac1) firstprivate(ny2, k, grid_points)
for(j = 1; j <= ny2; j++) {
i = grid_points[0] - 2;
i1 = grid_points[0] - 1;
m = 3;
fac1 = 1.0 / lhsp[j][i][2];
lhsp[j][i][3] = fac1 * lhsp[j][i][3];
lhsp[j][i][4] = fac1 * lhsp[j][i][4];
rhs[k][j][i][m] = fac1 * rhs[k][j][i][m];
lhsp[j][i1][2] = lhsp[j][i1][2] - lhsp[j][i1][1] * lhsp[j][i][3];
lhsp[j][i1][3] = lhsp[j][i1][3] - lhsp[j][i1][1] * lhsp[j][i][4];
rhs[k][j][i1][m] = rhs[k][j][i1][m] - lhsp[j][i1][1] * rhs[k][j][i][m];
m = 4;
fac1 = 1.0 / lhsm[j][i][2];
lhsm[j][i][3] = fac1 * lhsm[j][i][3];
lhsm[j][i][4] = fac1 * lhsm[j][i][4];
rhs[k][j][i][m] = fac1 * rhs[k][j][i][m];
lhsm[j][i1][2] = lhsm[j][i1][2] - lhsm[j][i1][1] * lhsm[j][i][3];
lhsm[j][i1][3] = lhsm[j][i1][3] - lhsm[j][i1][1] * lhsm[j][i][4];
rhs[k][j][i1][m] = rhs[k][j][i1][m] - lhsm[j][i1][1] * rhs[k][j][i][m];
//---------------------------------------------------------------------
// Scale the last row immediately
//---------------------------------------------------------------------
rhs[k][j][i1][3] = rhs[k][j][i1][3] / lhsp[j][i1][2];
rhs[k][j][i1][4] = rhs[k][j][i1][4] / lhsm[j][i1][2];
}
//---------------------------------------------------------------------
// BACKSUBSTITUTION
//---------------------------------------------------------------------
#pragma omp parallel for default(shared) private(j, m, i, i1) firstprivate(ny2, k, grid_points, lhs, lhsp, lhsm)
for(j = 1; j <= ny2; j++) {
i = grid_points[0] - 2;
i1 = grid_points[0] - 1;
/*************** Clava msgError **************
Loop Iteration number is too low
****************************************/
for(m = 0; m < 3; m++) {
rhs[k][j][i][m] = rhs[k][j][i][m] - lhs[j][i][3] * rhs[k][j][i1][m];
}
rhs[k][j][i][3] = rhs[k][j][i][3] - lhsp[j][i][3] * rhs[k][j][i1][3];
rhs[k][j][i][4] = rhs[k][j][i][4] - lhsm[j][i][3] * rhs[k][j][i1][4];
}
//---------------------------------------------------------------------
// The first three factors
//---------------------------------------------------------------------
#pragma omp parallel for default(shared) private(j, i, m, i1, i2) firstprivate(ny2, k, grid_points, lhs, lhsp, lhsm)
for(j = 1; j <= ny2; j++) {
/*************** Clava msgError **************
unsolved dependency for arrayAccess rhs use : RW
****************************************/
for(i = grid_points[0] - 3; i >= 0; i--) {
i1 = i + 1;
i2 = i + 2;
/*************** Clava msgError **************
Loop Iteration number is too low
****************************************/
for(m = 0; m < 3; m++) {
rhs[k][j][i][m] = rhs[k][j][i][m] - lhs[j][i][3] * rhs[k][j][i1][m] - lhs[j][i][4] * rhs[k][j][i2][m];
}
//-------------------------------------------------------------------
// And the remaining two
//-------------------------------------------------------------------
rhs[k][j][i][3] = rhs[k][j][i][3] - lhsp[j][i][3] * rhs[k][j][i1][3] - lhsp[j][i][4] * rhs[k][j][i2][3];
rhs[k][j][i][4] = rhs[k][j][i][4] - lhsm[j][i][3] * rhs[k][j][i1][4] - lhsm[j][i][4] * rhs[k][j][i2][4];
}
}
}
//---------------------------------------------------------------------
// Do the block-diagonal inversion
//---------------------------------------------------------------------
ninvr();
}
//---------------------------------------------------------------------
// this function performs the solution of the approximate factorization
// step in the y-direction for all five matrix components
// simultaneously. The Thomas algorithm is employed to solve the
// systems for the y-lines. Boundary conditions are non-periodic
//---------------------------------------------------------------------
void y_solve() {
int i, j, k, j1, j2, m;
double ru1, fac1, fac2;
double rhoq[36];
double cv[36];
double lhs[37][37][5];
double lhsp[37][37][5];
double lhsm[37][37][5];
#pragma omp parallel for default(shared) private(k, i, j, m, ru1, j1, j2, fac1, fac2) firstprivate(nx2, ny2, c3c4, con43, c1c5, dy3, dy5, dymax, dy1, dtty2, dtty1, c2dtty1, comz5, comz4, comz1, comz6, grid_points, rho_i, vs, speed, lhs, lhsp, lhsm, cv, rhoq)
for(k = 1; k <= grid_points[2] - 2; k++) {
lhsinitj(ny2 + 1, nx2, lhs, lhsp, lhsm);
//---------------------------------------------------------------------
// Computes the left hand side for the three y-factors
//---------------------------------------------------------------------
//---------------------------------------------------------------------
// first fill the lhs for the u-eigenvalue
//---------------------------------------------------------------------
#pragma omp parallel for default(shared) private(i, j, ru1) firstprivate(c3c4, k, con43, c1c5, dy3, dy5, dymax, dy1, dtty2, dtty1, c2dtty1, grid_points, rho_i, vs, cv, rhoq)
for(i = 1; i <= grid_points[0] - 2; i++) {
#pragma omp parallel for default(shared) private(j, ru1) firstprivate(c3c4, k, i, con43, c1c5, dy3, dy5, dymax, dy1, grid_points, rho_i, vs)
for(j = 0; j <= grid_points[1] - 1; j++) {
ru1 = c3c4 * rho_i[k][j][i];
cv[j] = vs[k][j][i];
rhoq[j] = ((((dy3 + con43 * ru1) > (dy5 + c1c5 * ru1) ? (dy3 + con43 * ru1) : (dy5 + c1c5 * ru1))) > (((dymax + ru1) > (dy1) ? (dymax + ru1) : (dy1))) ? (((dy3 + con43 * ru1) > (dy5 + c1c5 * ru1) ? (dy3 + con43 * ru1) : (dy5 + c1c5 * ru1))) : (((dymax + ru1) > (dy1) ? (dymax + ru1) : (dy1))));
}
#pragma omp parallel for default(shared) private(j) firstprivate(i, dtty2, dtty1, c2dtty1, grid_points, cv, rhoq)
for(j = 1; j <= grid_points[1] - 2; j++) {
lhs[j][i][0] = 0.0;
lhs[j][i][1] = -dtty2 * cv[j - 1] - dtty1 * rhoq[j - 1];
lhs[j][i][2] = 1.0 + c2dtty1 * rhoq[j];
lhs[j][i][3] = dtty2 * cv[j + 1] - dtty1 * rhoq[j + 1];
lhs[j][i][4] = 0.0;
}
}
//---------------------------------------------------------------------
// add fourth order dissipation
//---------------------------------------------------------------------
#pragma omp parallel for default(shared) private(i, j) firstprivate(comz5, comz4, comz1, comz6, grid_points)
for(i = 1; i <= grid_points[0] - 2; i++) {
j = 1;
lhs[j][i][2] = lhs[j][i][2] + comz5;
lhs[j][i][3] = lhs[j][i][3] - comz4;
lhs[j][i][4] = lhs[j][i][4] + comz1;
lhs[j + 1][i][1] = lhs[j + 1][i][1] - comz4;
lhs[j + 1][i][2] = lhs[j + 1][i][2] + comz6;
lhs[j + 1][i][3] = lhs[j + 1][i][3] - comz4;
lhs[j + 1][i][4] = lhs[j + 1][i][4] + comz1;
}
#pragma omp parallel for default(shared) private(j, i) firstprivate(comz1, comz4, comz6, grid_points)
for(j = 3; j <= grid_points[1] - 4; j++) {
#pragma omp parallel for default(shared) private(i) firstprivate(j, comz1, comz4, comz6, grid_points)
for(i = 1; i <= grid_points[0] - 2; i++) {
lhs[j][i][0] = lhs[j][i][0] + comz1;
lhs[j][i][1] = lhs[j][i][1] - comz4;
lhs[j][i][2] = lhs[j][i][2] + comz6;
lhs[j][i][3] = lhs[j][i][3] - comz4;
lhs[j][i][4] = lhs[j][i][4] + comz1;
}
}
#pragma omp parallel for default(shared) private(i, j) firstprivate(comz1, comz4, comz6, comz5, grid_points)
for(i = 1; i <= grid_points[0] - 2; i++) {
j = grid_points[1] - 3;
lhs[j][i][0] = lhs[j][i][0] + comz1;
lhs[j][i][1] = lhs[j][i][1] - comz4;
lhs[j][i][2] = lhs[j][i][2] + comz6;
lhs[j][i][3] = lhs[j][i][3] - comz4;
lhs[j + 1][i][0] = lhs[j + 1][i][0] + comz1;
lhs[j + 1][i][1] = lhs[j + 1][i][1] - comz4;
lhs[j + 1][i][2] = lhs[j + 1][i][2] + comz5;
}
//---------------------------------------------------------------------
// subsequently, for (the other two factors
//---------------------------------------------------------------------
#pragma omp parallel for default(shared) private(j, i) firstprivate(dtty2, k, grid_points, lhs, speed)
for(j = 1; j <= grid_points[1] - 2; j++) {
#pragma omp parallel for default(shared) private(i) firstprivate(j, dtty2, k, grid_points, lhs, speed)
for(i = 1; i <= grid_points[0] - 2; i++) {
lhsp[j][i][0] = lhs[j][i][0];
lhsp[j][i][1] = lhs[j][i][1] - dtty2 * speed[k][j - 1][i];
lhsp[j][i][2] = lhs[j][i][2];
lhsp[j][i][3] = lhs[j][i][3] + dtty2 * speed[k][j + 1][i];
lhsp[j][i][4] = lhs[j][i][4];
lhsm[j][i][0] = lhs[j][i][0];
lhsm[j][i][1] = lhs[j][i][1] + dtty2 * speed[k][j - 1][i];
lhsm[j][i][2] = lhs[j][i][2];
lhsm[j][i][3] = lhs[j][i][3] - dtty2 * speed[k][j + 1][i];
lhsm[j][i][4] = lhs[j][i][4];
}
}
//---------------------------------------------------------------------
// FORWARD ELIMINATION
//---------------------------------------------------------------------
/*************** Clava msgError **************
unsolved dependency for arrayAccess lhs use : RWR
unsolved dependency for arrayAccess rhs use : RW
****************************************/
for(j = 0; j <= grid_points[1] - 3; j++) {
j1 = j + 1;
j2 = j + 2;
#pragma omp parallel for default(shared) private(i, m, fac1) firstprivate(j, k, grid_points)
for(i = 1; i <= grid_points[0] - 2; i++) {
fac1 = 1.0 / lhs[j][i][2];
lhs[j][i][3] = fac1 * lhs[j][i][3];
lhs[j][i][4] = fac1 * lhs[j][i][4];
/*************** Clava msgError **************
Loop Iteration number is too low
****************************************/
for(m = 0; m < 3; m++) {
rhs[k][j][i][m] = fac1 * rhs[k][j][i][m];
}
lhs[j1][i][2] = lhs[j1][i][2] - lhs[j1][i][1] * lhs[j][i][3];
lhs[j1][i][3] = lhs[j1][i][3] - lhs[j1][i][1] * lhs[j][i][4];
/*************** Clava msgError **************
Loop Iteration number is too low
****************************************/
for(m = 0; m < 3; m++) {
rhs[k][j1][i][m] = rhs[k][j1][i][m] - lhs[j1][i][1] * rhs[k][j][i][m];
}
lhs[j2][i][1] = lhs[j2][i][1] - lhs[j2][i][0] * lhs[j][i][3];
lhs[j2][i][2] = lhs[j2][i][2] - lhs[j2][i][0] * lhs[j][i][4];
/*************** Clava msgError **************
Loop Iteration number is too low
****************************************/
for(m = 0; m < 3; m++) {
rhs[k][j2][i][m] = rhs[k][j2][i][m] - lhs[j2][i][0] * rhs[k][j][i][m];
}
}
}
//---------------------------------------------------------------------
// The last two rows in this grid block are a bit different,
// since they for (not have two more rows available for the
// elimination of off-diagonal entries
//---------------------------------------------------------------------
j = grid_points[1] - 2;
j1 = grid_points[1] - 1;
#pragma omp parallel for default(shared) private(i, m, fac1, fac2) firstprivate(j, k, j1, grid_points)
for(i = 1; i <= grid_points[0] - 2; i++) {
fac1 = 1.0 / lhs[j][i][2];
lhs[j][i][3] = fac1 * lhs[j][i][3];
lhs[j][i][4] = fac1 * lhs[j][i][4];
/*************** Clava msgError **************
Loop Iteration number is too low
****************************************/
for(m = 0; m < 3; m++) {
rhs[k][j][i][m] = fac1 * rhs[k][j][i][m];
}
lhs[j1][i][2] = lhs[j1][i][2] - lhs[j1][i][1] * lhs[j][i][3];
lhs[j1][i][3] = lhs[j1][i][3] - lhs[j1][i][1] * lhs[j][i][4];
/*************** Clava msgError **************
Loop Iteration number is too low
****************************************/
for(m = 0; m < 3; m++) {
rhs[k][j1][i][m] = rhs[k][j1][i][m] - lhs[j1][i][1] * rhs[k][j][i][m];
}
//---------------------------------------------------------------------
// scale the last row immediately
//---------------------------------------------------------------------
fac2 = 1.0 / lhs[j1][i][2];
/*************** Clava msgError **************
Loop Iteration number is too low
****************************************/
for(m = 0; m < 3; m++) {
rhs[k][j1][i][m] = fac2 * rhs[k][j1][i][m];
}
}
//---------------------------------------------------------------------
// for (the u+c and the u-c factors
//---------------------------------------------------------------------
/*************** Clava msgError **************
unsolved dependency for arrayAccess lhsp use : RWR
unsolved dependency for arrayAccess rhs use : RW
unsolved dependency for arrayAccess lhsm use : RWR
****************************************/
for(j = 0; j <= grid_points[1] - 3; j++) {
j1 = j + 1;
j2 = j + 2;
#pragma omp parallel for default(shared) private(i, m, fac1) firstprivate(j, k, grid_points)
for(i = 1; i <= grid_points[0] - 2; i++) {
m = 3;
fac1 = 1.0 / lhsp[j][i][2];
lhsp[j][i][3] = fac1 * lhsp[j][i][3];
lhsp[j][i][4] = fac1 * lhsp[j][i][4];
rhs[k][j][i][m] = fac1 * rhs[k][j][i][m];
lhsp[j1][i][2] = lhsp[j1][i][2] - lhsp[j1][i][1] * lhsp[j][i][3];
lhsp[j1][i][3] = lhsp[j1][i][3] - lhsp[j1][i][1] * lhsp[j][i][4];
rhs[k][j1][i][m] = rhs[k][j1][i][m] - lhsp[j1][i][1] * rhs[k][j][i][m];
lhsp[j2][i][1] = lhsp[j2][i][1] - lhsp[j2][i][0] * lhsp[j][i][3];
lhsp[j2][i][2] = lhsp[j2][i][2] - lhsp[j2][i][0] * lhsp[j][i][4];
rhs[k][j2][i][m] = rhs[k][j2][i][m] - lhsp[j2][i][0] * rhs[k][j][i][m];
m = 4;
fac1 = 1.0 / lhsm[j][i][2];
lhsm[j][i][3] = fac1 * lhsm[j][i][3];
lhsm[j][i][4] = fac1 * lhsm[j][i][4];
rhs[k][j][i][m] = fac1 * rhs[k][j][i][m];
lhsm[j1][i][2] = lhsm[j1][i][2] - lhsm[j1][i][1] * lhsm[j][i][3];
lhsm[j1][i][3] = lhsm[j1][i][3] - lhsm[j1][i][1] * lhsm[j][i][4];
rhs[k][j1][i][m] = rhs[k][j1][i][m] - lhsm[j1][i][1] * rhs[k][j][i][m];
lhsm[j2][i][1] = lhsm[j2][i][1] - lhsm[j2][i][0] * lhsm[j][i][3];
lhsm[j2][i][2] = lhsm[j2][i][2] - lhsm[j2][i][0] * lhsm[j][i][4];
rhs[k][j2][i][m] = rhs[k][j2][i][m] - lhsm[j2][i][0] * rhs[k][j][i][m];
}
}
//---------------------------------------------------------------------
// And again the last two rows separately
//---------------------------------------------------------------------
j = grid_points[1] - 2;
j1 = grid_points[1] - 1;
#pragma omp parallel for default(shared) private(i, m, fac1) firstprivate(j, k, j1, grid_points)
for(i = 1; i <= grid_points[0] - 2; i++) {
m = 3;
fac1 = 1.0 / lhsp[j][i][2];
lhsp[j][i][3] = fac1 * lhsp[j][i][3];
lhsp[j][i][4] = fac1 * lhsp[j][i][4];
rhs[k][j][i][m] = fac1 * rhs[k][j][i][m];
lhsp[j1][i][2] = lhsp[j1][i][2] - lhsp[j1][i][1] * lhsp[j][i][3];
lhsp[j1][i][3] = lhsp[j1][i][3] - lhsp[j1][i][1] * lhsp[j][i][4];
rhs[k][j1][i][m] = rhs[k][j1][i][m] - lhsp[j1][i][1] * rhs[k][j][i][m];
m = 4;
fac1 = 1.0 / lhsm[j][i][2];
lhsm[j][i][3] = fac1 * lhsm[j][i][3];
lhsm[j][i][4] = fac1 * lhsm[j][i][4];
rhs[k][j][i][m] = fac1 * rhs[k][j][i][m];
lhsm[j1][i][2] = lhsm[j1][i][2] - lhsm[j1][i][1] * lhsm[j][i][3];
lhsm[j1][i][3] = lhsm[j1][i][3] - lhsm[j1][i][1] * lhsm[j][i][4];
rhs[k][j1][i][m] = rhs[k][j1][i][m] - lhsm[j1][i][1] * rhs[k][j][i][m];
//---------------------------------------------------------------------
// Scale the last row immediately
//---------------------------------------------------------------------
rhs[k][j1][i][3] = rhs[k][j1][i][3] / lhsp[j1][i][2];
rhs[k][j1][i][4] = rhs[k][j1][i][4] / lhsm[j1][i][2];
}
//---------------------------------------------------------------------
// BACKSUBSTITUTION
//---------------------------------------------------------------------
j = grid_points[1] - 2;
j1 = grid_points[1] - 1;
#pragma omp parallel for default(shared) private(i, m) firstprivate(j, k, j1, grid_points, lhs, lhsp, lhsm)
for(i = 1; i <= grid_points[0] - 2; i++) {
/*************** Clava msgError **************
Loop Iteration number is too low
****************************************/
for(m = 0; m < 3; m++) {
rhs[k][j][i][m] = rhs[k][j][i][m] - lhs[j][i][3] * rhs[k][j1][i][m];
}
rhs[k][j][i][3] = rhs[k][j][i][3] - lhsp[j][i][3] * rhs[k][j1][i][3];
rhs[k][j][i][4] = rhs[k][j][i][4] - lhsm[j][i][3] * rhs[k][j1][i][4];
}
//---------------------------------------------------------------------
// The first three factors
//---------------------------------------------------------------------
/*************** Clava msgError **************
unsolved dependency for arrayAccess rhs use : RW
****************************************/
for(j = grid_points[1] - 3; j >= 0; j--) {
j1 = j + 1;
j2 = j + 2;
#pragma omp parallel for default(shared) private(i, m) firstprivate(j, k, grid_points, lhs, lhsp, lhsm)
for(i = 1; i <= grid_points[0] - 2; i++) {
/*************** Clava msgError **************
Loop Iteration number is too low
****************************************/
for(m = 0; m < 3; m++) {
rhs[k][j][i][m] = rhs[k][j][i][m] - lhs[j][i][3] * rhs[k][j1][i][m] - lhs[j][i][4] * rhs[k][j2][i][m];
}
//-------------------------------------------------------------------
// And the remaining two
//-------------------------------------------------------------------
rhs[k][j][i][3] = rhs[k][j][i][3] - lhsp[j][i][3] * rhs[k][j1][i][3] - lhsp[j][i][4] * rhs[k][j2][i][3];
rhs[k][j][i][4] = rhs[k][j][i][4] - lhsm[j][i][3] * rhs[k][j1][i][4] - lhsm[j][i][4] * rhs[k][j2][i][4];
}
}
}
pinvr();
}
//---------------------------------------------------------------------
// this function performs the solution of the approximate factorization
// step in the z-direction for all five matrix components
// simultaneously. The Thomas algorithm is employed to solve the
// systems for the z-lines. Boundary conditions are non-periodic
//---------------------------------------------------------------------
void z_solve() {
int i, j, k, k1, k2, m;
double ru1, fac1, fac2;
double rhos[36];
double cv[36];
double lhs[37][37][5];
double lhsp[37][37][5];
double lhsm[37][37][5];
#pragma omp parallel for default(shared) private(j, i, k, m, ru1, k1, k2, fac1, fac2) firstprivate(ny2, nx2, nz2, c3c4, con43, c1c5, dz4, dz5, dzmax, dz1, dttz2, dttz1, c2dttz1, comz5, comz4, comz1, comz6, rho_i, ws, speed, grid_points, lhs, lhsp, lhsm, cv, rhos)
for(j = 1; j <= ny2; j++) {
lhsinitj(nz2 + 1, nx2, lhs, lhsp, lhsm);
//---------------------------------------------------------------------
// Computes the left hand side for the three z-factors
//---------------------------------------------------------------------
//---------------------------------------------------------------------
// first fill the lhs for the u-eigenvalue
//---------------------------------------------------------------------
#pragma omp parallel for default(shared) private(i, k, ru1) firstprivate(nx2, nz2, c3c4, j, con43, c1c5, dz4, dz5, dzmax, dz1, dttz2, dttz1, c2dttz1, rho_i, ws, cv, rhos)
for(i = 1; i <= nx2; i++) {
#pragma omp parallel for default(shared) private(k, ru1) firstprivate(nz2, c3c4, j, i, con43, c1c5, dz4, dz5, dzmax, dz1, rho_i, ws)
for(k = 0; k <= nz2 + 1; k++) {
ru1 = c3c4 * rho_i[k][j][i];
cv[k] = ws[k][j][i];
rhos[k] = ((((dz4 + con43 * ru1) > (dz5 + c1c5 * ru1) ? (dz4 + con43 * ru1) : (dz5 + c1c5 * ru1))) > (((dzmax + ru1) > (dz1) ? (dzmax + ru1) : (dz1))) ? (((dz4 + con43 * ru1) > (dz5 + c1c5 * ru1) ? (dz4 + con43 * ru1) : (dz5 + c1c5 * ru1))) : (((dzmax + ru1) > (dz1) ? (dzmax + ru1) : (dz1))));
}
#pragma omp parallel for default(shared) private(k) firstprivate(nz2, i, dttz2, dttz1, c2dttz1, cv, rhos)
for(k = 1; k <= nz2; k++) {
lhs[k][i][0] = 0.0;
lhs[k][i][1] = -dttz2 * cv[k - 1] - dttz1 * rhos[k - 1];
lhs[k][i][2] = 1.0 + c2dttz1 * rhos[k];
lhs[k][i][3] = dttz2 * cv[k + 1] - dttz1 * rhos[k + 1];
lhs[k][i][4] = 0.0;
}
}
//---------------------------------------------------------------------
// add fourth order dissipation
//---------------------------------------------------------------------
#pragma omp parallel for default(shared) private(i, k) firstprivate(nx2, comz5, comz4, comz1, comz6)
for(i = 1; i <= nx2; i++) {
k = 1;
lhs[k][i][2] = lhs[k][i][2] + comz5;
lhs[k][i][3] = lhs[k][i][3] - comz4;
lhs[k][i][4] = lhs[k][i][4] + comz1;
k = 2;
lhs[k][i][1] = lhs[k][i][1] - comz4;
lhs[k][i][2] = lhs[k][i][2] + comz6;
lhs[k][i][3] = lhs[k][i][3] - comz4;
lhs[k][i][4] = lhs[k][i][4] + comz1;
}
#pragma omp parallel for default(shared) private(k, i) firstprivate(nz2, nx2, comz1, comz4, comz6)
for(k = 3; k <= nz2 - 2; k++) {
#pragma omp parallel for default(shared) private(i) firstprivate(nx2, k, comz1, comz4, comz6)
for(i = 1; i <= nx2; i++) {
lhs[k][i][0] = lhs[k][i][0] + comz1;
lhs[k][i][1] = lhs[k][i][1] - comz4;
lhs[k][i][2] = lhs[k][i][2] + comz6;
lhs[k][i][3] = lhs[k][i][3] - comz4;
lhs[k][i][4] = lhs[k][i][4] + comz1;
}
}
#pragma omp parallel for default(shared) private(i, k) firstprivate(nx2, nz2, comz1, comz4, comz6, comz5)
for(i = 1; i <= nx2; i++) {
k = nz2 - 1;
lhs[k][i][0] = lhs[k][i][0] + comz1;
lhs[k][i][1] = lhs[k][i][1] - comz4;
lhs[k][i][2] = lhs[k][i][2] + comz6;
lhs[k][i][3] = lhs[k][i][3] - comz4;
k = nz2;
lhs[k][i][0] = lhs[k][i][0] + comz1;
lhs[k][i][1] = lhs[k][i][1] - comz4;
lhs[k][i][2] = lhs[k][i][2] + comz5;
}
//---------------------------------------------------------------------
// subsequently, fill the other factors (u+c), (u-c)
//---------------------------------------------------------------------
#pragma omp parallel for default(shared) private(k, i) firstprivate(nz2, nx2, dttz2, j, lhs, speed)
for(k = 1; k <= nz2; k++) {
#pragma omp parallel for default(shared) private(i) firstprivate(nx2, k, dttz2, j, lhs, speed)
for(i = 1; i <= nx2; i++) {
lhsp[k][i][0] = lhs[k][i][0];
lhsp[k][i][1] = lhs[k][i][1] - dttz2 * speed[k - 1][j][i];
lhsp[k][i][2] = lhs[k][i][2];
lhsp[k][i][3] = lhs[k][i][3] + dttz2 * speed[k + 1][j][i];
lhsp[k][i][4] = lhs[k][i][4];
lhsm[k][i][0] = lhs[k][i][0];
lhsm[k][i][1] = lhs[k][i][1] + dttz2 * speed[k - 1][j][i];
lhsm[k][i][2] = lhs[k][i][2];
lhsm[k][i][3] = lhs[k][i][3] - dttz2 * speed[k + 1][j][i];
lhsm[k][i][4] = lhs[k][i][4];
}
}
//---------------------------------------------------------------------
// FORWARD ELIMINATION
//---------------------------------------------------------------------
/*************** Clava msgError **************
unsolved dependency for arrayAccess lhs use : RWR
unsolved dependency for arrayAccess rhs use : RW
****************************************/
for(k = 0; k <= grid_points[2] - 3; k++) {
k1 = k + 1;
k2 = k + 2;
#pragma omp parallel for default(shared) private(i, m, fac1) firstprivate(nx2, k, j)
for(i = 1; i <= nx2; i++) {
fac1 = 1.0 / lhs[k][i][2];
lhs[k][i][3] = fac1 * lhs[k][i][3];
lhs[k][i][4] = fac1 * lhs[k][i][4];
/*************** Clava msgError **************
Loop Iteration number is too low
****************************************/
for(m = 0; m < 3; m++) {
rhs[k][j][i][m] = fac1 * rhs[k][j][i][m];
}
lhs[k1][i][2] = lhs[k1][i][2] - lhs[k1][i][1] * lhs[k][i][3];
lhs[k1][i][3] = lhs[k1][i][3] - lhs[k1][i][1] * lhs[k][i][4];
/*************** Clava msgError **************
Loop Iteration number is too low
****************************************/
for(m = 0; m < 3; m++) {
rhs[k1][j][i][m] = rhs[k1][j][i][m] - lhs[k1][i][1] * rhs[k][j][i][m];
}
lhs[k2][i][1] = lhs[k2][i][1] - lhs[k2][i][0] * lhs[k][i][3];
lhs[k2][i][2] = lhs[k2][i][2] - lhs[k2][i][0] * lhs[k][i][4];
/*************** Clava msgError **************
Loop Iteration number is too low
****************************************/
for(m = 0; m < 3; m++) {
rhs[k2][j][i][m] = rhs[k2][j][i][m] - lhs[k2][i][0] * rhs[k][j][i][m];
}
}
}
//---------------------------------------------------------------------
// The last two rows in this grid block are a bit different,
// since they for (not have two more rows available for the
// elimination of off-diagonal entries
//---------------------------------------------------------------------
k = grid_points[2] - 2;
k1 = grid_points[2] - 1;
#pragma omp parallel for default(shared) private(i, m, fac1, fac2) firstprivate(nx2, k, j, k1)
for(i = 1; i <= nx2; i++) {
fac1 = 1.0 / lhs[k][i][2];
lhs[k][i][3] = fac1 * lhs[k][i][3];
lhs[k][i][4] = fac1 * lhs[k][i][4];
/*************** Clava msgError **************
Loop Iteration number is too low
****************************************/
for(m = 0; m < 3; m++) {
rhs[k][j][i][m] = fac1 * rhs[k][j][i][m];
}
lhs[k1][i][2] = lhs[k1][i][2] - lhs[k1][i][1] * lhs[k][i][3];
lhs[k1][i][3] = lhs[k1][i][3] - lhs[k1][i][1] * lhs[k][i][4];
/*************** Clava msgError **************
Loop Iteration number is too low
****************************************/
for(m = 0; m < 3; m++) {
rhs[k1][j][i][m] = rhs[k1][j][i][m] - lhs[k1][i][1] * rhs[k][j][i][m];
}
//---------------------------------------------------------------------
// scale the last row immediately
//---------------------------------------------------------------------
fac2 = 1.0 / lhs[k1][i][2];
/*************** Clava msgError **************
Loop Iteration number is too low
****************************************/
for(m = 0; m < 3; m++) {
rhs[k1][j][i][m] = fac2 * rhs[k1][j][i][m];
}
}
//---------------------------------------------------------------------
// for (the u+c and the u-c factors
//---------------------------------------------------------------------
/*************** Clava msgError **************
unsolved dependency for arrayAccess lhsp use : RWR
unsolved dependency for arrayAccess rhs use : RW
unsolved dependency for arrayAccess lhsm use : RWR
****************************************/
for(k = 0; k <= grid_points[2] - 3; k++) {
k1 = k + 1;
k2 = k + 2;
#pragma omp parallel for default(shared) private(i, m, fac1) firstprivate(nx2, k, j)
for(i = 1; i <= nx2; i++) {
m = 3;
fac1 = 1.0 / lhsp[k][i][2];
lhsp[k][i][3] = fac1 * lhsp[k][i][3];
lhsp[k][i][4] = fac1 * lhsp[k][i][4];
rhs[k][j][i][m] = fac1 * rhs[k][j][i][m];
lhsp[k1][i][2] = lhsp[k1][i][2] - lhsp[k1][i][1] * lhsp[k][i][3];
lhsp[k1][i][3] = lhsp[k1][i][3] - lhsp[k1][i][1] * lhsp[k][i][4];
rhs[k1][j][i][m] = rhs[k1][j][i][m] - lhsp[k1][i][1] * rhs[k][j][i][m];
lhsp[k2][i][1] = lhsp[k2][i][1] - lhsp[k2][i][0] * lhsp[k][i][3];
lhsp[k2][i][2] = lhsp[k2][i][2] - lhsp[k2][i][0] * lhsp[k][i][4];
rhs[k2][j][i][m] = rhs[k2][j][i][m] - lhsp[k2][i][0] * rhs[k][j][i][m];
m = 4;
fac1 = 1.0 / lhsm[k][i][2];
lhsm[k][i][3] = fac1 * lhsm[k][i][3];
lhsm[k][i][4] = fac1 * lhsm[k][i][4];
rhs[k][j][i][m] = fac1 * rhs[k][j][i][m];
lhsm[k1][i][2] = lhsm[k1][i][2] - lhsm[k1][i][1] * lhsm[k][i][3];
lhsm[k1][i][3] = lhsm[k1][i][3] - lhsm[k1][i][1] * lhsm[k][i][4];
rhs[k1][j][i][m] = rhs[k1][j][i][m] - lhsm[k1][i][1] * rhs[k][j][i][m];
lhsm[k2][i][1] = lhsm[k2][i][1] - lhsm[k2][i][0] * lhsm[k][i][3];
lhsm[k2][i][2] = lhsm[k2][i][2] - lhsm[k2][i][0] * lhsm[k][i][4];
rhs[k2][j][i][m] = rhs[k2][j][i][m] - lhsm[k2][i][0] * rhs[k][j][i][m];
}
}
//---------------------------------------------------------------------
// And again the last two rows separately
//---------------------------------------------------------------------
k = grid_points[2] - 2;
k1 = grid_points[2] - 1;
#pragma omp parallel for default(shared) private(i, m, fac1) firstprivate(nx2, k, j, k1)
for(i = 1; i <= nx2; i++) {
m = 3;
fac1 = 1.0 / lhsp[k][i][2];
lhsp[k][i][3] = fac1 * lhsp[k][i][3];
lhsp[k][i][4] = fac1 * lhsp[k][i][4];
rhs[k][j][i][m] = fac1 * rhs[k][j][i][m];
lhsp[k1][i][2] = lhsp[k1][i][2] - lhsp[k1][i][1] * lhsp[k][i][3];
lhsp[k1][i][3] = lhsp[k1][i][3] - lhsp[k1][i][1] * lhsp[k][i][4];
rhs[k1][j][i][m] = rhs[k1][j][i][m] - lhsp[k1][i][1] * rhs[k][j][i][m];
m = 4;
fac1 = 1.0 / lhsm[k][i][2];
lhsm[k][i][3] = fac1 * lhsm[k][i][3];
lhsm[k][i][4] = fac1 * lhsm[k][i][4];
rhs[k][j][i][m] = fac1 * rhs[k][j][i][m];
lhsm[k1][i][2] = lhsm[k1][i][2] - lhsm[k1][i][1] * lhsm[k][i][3];
lhsm[k1][i][3] = lhsm[k1][i][3] - lhsm[k1][i][1] * lhsm[k][i][4];
rhs[k1][j][i][m] = rhs[k1][j][i][m] - lhsm[k1][i][1] * rhs[k][j][i][m];
//---------------------------------------------------------------------
// Scale the last row immediately (some of this is overkill
// if this is the last cell)
//---------------------------------------------------------------------
rhs[k1][j][i][3] = rhs[k1][j][i][3] / lhsp[k1][i][2];
rhs[k1][j][i][4] = rhs[k1][j][i][4] / lhsm[k1][i][2];
}
//---------------------------------------------------------------------
// BACKSUBSTITUTION
//---------------------------------------------------------------------
k = grid_points[2] - 2;
k1 = grid_points[2] - 1;
#pragma omp parallel for default(shared) private(i, m) firstprivate(nx2, k, k1, j, lhs, lhsp, lhsm)
for(i = 1; i <= nx2; i++) {
/*************** Clava msgError **************
Loop Iteration number is too low
****************************************/
for(m = 0; m < 3; m++) {
rhs[k][j][i][m] = rhs[k][j][i][m] - lhs[k][i][3] * rhs[k1][j][i][m];
}
rhs[k][j][i][3] = rhs[k][j][i][3] - lhsp[k][i][3] * rhs[k1][j][i][3];
rhs[k][j][i][4] = rhs[k][j][i][4] - lhsm[k][i][3] * rhs[k1][j][i][4];
}
//---------------------------------------------------------------------
// Whether or not this is the last processor, we always have
// to complete the back-substitution
//---------------------------------------------------------------------
//---------------------------------------------------------------------
// The first three factors
//---------------------------------------------------------------------
/*************** Clava msgError **************
unsolved dependency for arrayAccess rhs use : RW
****************************************/
for(k = grid_points[2] - 3; k >= 0; k--) {
k1 = k + 1;
k2 = k + 2;
#pragma omp parallel for default(shared) private(i, m) firstprivate(nx2, k, j, lhs, lhsp, lhsm)
for(i = 1; i <= nx2; i++) {
/*************** Clava msgError **************
Loop Iteration number is too low
****************************************/
for(m = 0; m < 3; m++) {
rhs[k][j][i][m] = rhs[k][j][i][m] - lhs[k][i][3] * rhs[k1][j][i][m] - lhs[k][i][4] * rhs[k2][j][i][m];
}
//-------------------------------------------------------------------
// And the remaining two
//-------------------------------------------------------------------
rhs[k][j][i][3] = rhs[k][j][i][3] - lhsp[k][i][3] * rhs[k1][j][i][3] - lhsp[k][i][4] * rhs[k2][j][i][3];
rhs[k][j][i][4] = rhs[k][j][i][4] - lhsm[k][i][3] * rhs[k1][j][i][4] - lhsm[k][i][4] * rhs[k2][j][i][4];
}
}
}
tzetar();
}
void set_constants() {
ce[0][0] = 2.0;
ce[0][1] = 0.0;
ce[0][2] = 0.0;
ce[0][3] = 4.0;
ce[0][4] = 5.0;
ce[0][5] = 3.0;
ce[0][6] = 0.5;
ce[0][7] = 0.02;
ce[0][8] = 0.01;
ce[0][9] = 0.03;
ce[0][10] = 0.5;
ce[0][11] = 0.4;
ce[0][12] = 0.3;
ce[1][0] = 1.0;
ce[1][1] = 0.0;
ce[1][2] = 0.0;
ce[1][3] = 0.0;
ce[1][4] = 1.0;
ce[1][5] = 2.0;
ce[1][6] = 3.0;
ce[1][7] = 0.01;
ce[1][8] = 0.03;
ce[1][9] = 0.02;
ce[1][10] = 0.4;
ce[1][11] = 0.3;
ce[1][12] = 0.5;
ce[2][0] = 2.0;
ce[2][1] = 2.0;
ce[2][2] = 0.0;
ce[2][3] = 0.0;
ce[2][4] = 0.0;
ce[2][5] = 2.0;
ce[2][6] = 3.0;
ce[2][7] = 0.04;
ce[2][8] = 0.03;
ce[2][9] = 0.05;
ce[2][10] = 0.3;
ce[2][11] = 0.5;
ce[2][12] = 0.4;
ce[3][0] = 2.0;
ce[3][1] = 2.0;
ce[3][2] = 0.0;
ce[3][3] = 0.0;
ce[3][4] = 0.0;
ce[3][5] = 2.0;
ce[3][6] = 3.0;
ce[3][7] = 0.03;
ce[3][8] = 0.05;
ce[3][9] = 0.04;
ce[3][10] = 0.2;
ce[3][11] = 0.1;
ce[3][12] = 0.3;
ce[4][0] = 5.0;
ce[4][1] = 4.0;
ce[4][2] = 3.0;
ce[4][3] = 2.0;
ce[4][4] = 0.1;
ce[4][5] = 0.4;
ce[4][6] = 0.3;
ce[4][7] = 0.05;
ce[4][8] = 0.04;
ce[4][9] = 0.03;
ce[4][10] = 0.1;
ce[4][11] = 0.3;
ce[4][12] = 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 = ((dx3) > (dx4) ? (dx3) : (dx4));
dymax = ((dy2) > (dy4) ? (dy2) : (dy4));
dzmax = ((dz2) > (dz3) ? (dz2) : (dz3));
dssp = 0.25 * ((dx1) > (((dy1) > (dz1) ? (dy1) : (dz1))) ? (dx1) : (((dy1) > (dz1) ? (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;
}
void print_results(char *name, char class, int n1, int n2, int n3, int niter, double t, double mops, char *optype, int verified) {
char size[16];
int j;
printf("\n\n %s Benchmark Completed.\n", name);
printf(" Class = %12c\n", class);
// If this is not a grid-based problem (EP, FT, CG), then
// we only print n1, which contains some measure of the
// problem size. In that case, n2 and n3 are both zero.
// Otherwise, we print the grid size n1xn2xn3
if((n2 == 0) && (n3 == 0)) {
if((name[0] == 'E') && (name[1] == 'P')) {
sprintf(size, "%15.0lf", pow(2.0, n1));
j = 14;
if(size[j] == '.') {
size[j] = ' ';
j--;
}
size[j + 1] = '\0';
printf(" Size = %15s\n", size);
}
else {
printf(" Size = %12d\n", n1);
}
}
else {
printf(" Size = %4dx%4dx%4d\n", n1, n2, n3);
}
printf(" Iterations = %12d\n", niter);
printf(" Time in seconds = %12.4lf\n", t);
printf(" Mop/s total = %15.2lf\n", mops);
printf(" Operation type = %24s\n", optype);
if(verified) printf(" Verification = %12s\n", "SUCCESSFUL");
else printf(" Verification = %12s\n", "UNSUCCESSFUL");
}
void wtime(double *t) {
static int sec = -1;
struct timeval tv;
gettimeofday(&tv, (void *) 0);
if(sec < 0) sec = tv.tv_sec;
*t = (tv.tv_sec - sec) + 1.0e-6 * tv.tv_usec;
}
/*****************************************************************/
/****** E L A P S E D _ T I M E ******/
/*****************************************************************/
double elapsed_time() {
double t;
wtime(&t);
return (t);
}
/*****************************************************************/
/****** T I M E R _ C L E A R ******/
/*****************************************************************/
void timer_clear(int n) {
elapsed[n] = 0.0;
}
/*****************************************************************/
/****** T I M E R _ S T A R T ******/
/*****************************************************************/
void timer_start(int n) {
start[n] = elapsed_time();
}
/*****************************************************************/
/****** T I M E R _ S T O P ******/
/*****************************************************************/
void timer_stop(int n) {
double t, now;
now = elapsed_time();
t = now - start[n];
elapsed[n] += t;
}
/*****************************************************************/
/****** T I M E R _ R E A D ******/
/*****************************************************************/
double timer_read(int n) {
return (elapsed[n]);
}
|
feature.c | /*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% FFFFF EEEEE AAA TTTTT U U RRRR EEEEE %
% F E A A T U U R R E %
% FFF EEE AAAAA T U U RRRR EEE %
% F E A A T U U R R E %
% F EEEEE A A T UUU R R EEEEE %
% %
% %
% MagickCore Image Feature Methods %
% %
% Software Design %
% Cristy %
% July 1992 %
% %
% %
% 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/animate.h"
#include "magick/artifact.h"
#include "magick/blob.h"
#include "magick/blob-private.h"
#include "magick/cache.h"
#include "magick/cache-private.h"
#include "magick/cache-view.h"
#include "magick/client.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/compress.h"
#include "magick/constitute.h"
#include "magick/deprecate.h"
#include "magick/display.h"
#include "magick/draw.h"
#include "magick/enhance.h"
#include "magick/exception.h"
#include "magick/exception-private.h"
#include "magick/feature.h"
#include "magick/gem.h"
#include "magick/geometry.h"
#include "magick/list.h"
#include "magick/image-private.h"
#include "magick/magic.h"
#include "magick/magick.h"
#include "magick/matrix.h"
#include "magick/memory_.h"
#include "magick/module.h"
#include "magick/monitor.h"
#include "magick/monitor-private.h"
#include "magick/morphology-private.h"
#include "magick/option.h"
#include "magick/paint.h"
#include "magick/pixel-private.h"
#include "magick/profile.h"
#include "magick/property.h"
#include "magick/quantize.h"
#include "magick/random_.h"
#include "magick/resource_.h"
#include "magick/segment.h"
#include "magick/semaphore.h"
#include "magick/signature-private.h"
#include "magick/string_.h"
#include "magick/thread-private.h"
#include "magick/timer.h"
#include "magick/token.h"
#include "magick/utility.h"
#include "magick/version.h"
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% C a n n y E d g e I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% CannyEdgeImage() uses a multi-stage algorithm to detect a wide range of
% edges in images.
%
% The format of the CannyEdgeImage method is:
%
% Image *CannyEdgeImage(const Image *image,const double radius,
% const double sigma,const double lower_percent,
% const double upper_percent,ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o radius: the radius of the gaussian smoothing filter.
%
% o sigma: the sigma of the gaussian smoothing filter.
%
% o lower_percent: percentage of edge pixels in the lower threshold.
%
% o upper_percent: percentage of edge pixels in the upper threshold.
%
% o exception: return any errors or warnings in this structure.
%
*/
typedef struct _CannyInfo
{
double
magnitude,
intensity;
int
orientation;
ssize_t
x,
y;
} CannyInfo;
static inline MagickBooleanType IsAuthenticPixel(const Image *image,
const ssize_t x,const ssize_t y)
{
if ((x < 0) || (x >= (ssize_t) image->columns))
return(MagickFalse);
if ((y < 0) || (y >= (ssize_t) image->rows))
return(MagickFalse);
return(MagickTrue);
}
static MagickBooleanType TraceEdges(Image *edge_image,CacheView *edge_view,
MatrixInfo *canny_cache,const ssize_t x,const ssize_t y,
const double lower_threshold,ExceptionInfo *exception)
{
CannyInfo
edge,
pixel;
MagickBooleanType
status;
register PixelPacket
*q;
register ssize_t
i;
q=GetCacheViewAuthenticPixels(edge_view,x,y,1,1,exception);
if (q == (PixelPacket *) NULL)
return(MagickFalse);
q->red=QuantumRange;
q->green=QuantumRange;
q->blue=QuantumRange;
status=SyncCacheViewAuthenticPixels(edge_view,exception);
if (status == MagickFalse)
return(MagickFalse);
if (GetMatrixElement(canny_cache,0,0,&edge) == MagickFalse)
return(MagickFalse);
edge.x=x;
edge.y=y;
if (SetMatrixElement(canny_cache,0,0,&edge) == MagickFalse)
return(MagickFalse);
for (i=1; i != 0; )
{
ssize_t
v;
i--;
status=GetMatrixElement(canny_cache,i,0,&edge);
if (status == MagickFalse)
return(MagickFalse);
for (v=(-1); v <= 1; v++)
{
ssize_t
u;
for (u=(-1); u <= 1; u++)
{
if ((u == 0) && (v == 0))
continue;
if (IsAuthenticPixel(edge_image,edge.x+u,edge.y+v) == MagickFalse)
continue;
/*
Not an edge if gradient value is below the lower threshold.
*/
q=GetCacheViewAuthenticPixels(edge_view,edge.x+u,edge.y+v,1,1,
exception);
if (q == (PixelPacket *) NULL)
return(MagickFalse);
status=GetMatrixElement(canny_cache,edge.x+u,edge.y+v,&pixel);
if (status == MagickFalse)
return(MagickFalse);
if ((GetPixelIntensity(edge_image,q) == 0.0) &&
(pixel.intensity >= lower_threshold))
{
q->red=QuantumRange;
q->green=QuantumRange;
q->blue=QuantumRange;
status=SyncCacheViewAuthenticPixels(edge_view,exception);
if (status == MagickFalse)
return(MagickFalse);
edge.x+=u;
edge.y+=v;
status=SetMatrixElement(canny_cache,i,0,&edge);
if (status == MagickFalse)
return(MagickFalse);
i++;
}
}
}
}
return(MagickTrue);
}
MagickExport Image *CannyEdgeImage(const Image *image,const double radius,
const double sigma,const double lower_percent,const double upper_percent,
ExceptionInfo *exception)
{
#define CannyEdgeImageTag "CannyEdge/Image"
CacheView
*edge_view;
CannyInfo
pixel;
char
geometry[MaxTextExtent];
double
lower_threshold,
max,
min,
upper_threshold;
Image
*edge_image;
KernelInfo
*kernel_info;
MagickBooleanType
status;
MagickOffsetType
progress;
MatrixInfo
*canny_cache;
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);
/*
Filter out noise.
*/
(void) FormatLocaleString(geometry,MaxTextExtent,
"blur:%.20gx%.20g;blur:%.20gx%.20g+90",radius,sigma,radius,sigma);
kernel_info=AcquireKernelInfo(geometry);
if (kernel_info == (KernelInfo *) NULL)
ThrowImageException(ResourceLimitError,"MemoryAllocationFailed");
edge_image=MorphologyApply(image,DefaultChannels,ConvolveMorphology,1,
kernel_info,UndefinedCompositeOp,0.0,exception);
kernel_info=DestroyKernelInfo(kernel_info);
if (edge_image == (Image *) NULL)
return((Image *) NULL);
if (SetImageColorspace(edge_image,GRAYColorspace) == MagickFalse)
{
edge_image=DestroyImage(edge_image);
return((Image *) NULL);
}
/*
Find the intensity gradient of the image.
*/
canny_cache=AcquireMatrixInfo(edge_image->columns,edge_image->rows,
sizeof(CannyInfo),exception);
if (canny_cache == (MatrixInfo *) NULL)
{
edge_image=DestroyImage(edge_image);
return((Image *) NULL);
}
status=MagickTrue;
edge_view=AcquireVirtualCacheView(edge_image,exception);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static,4) shared(status) \
magick_threads(edge_image,edge_image,edge_image->rows,1)
#endif
for (y=0; y < (ssize_t) edge_image->rows; y++)
{
register const PixelPacket
*restrict p;
register ssize_t
x;
if (status == MagickFalse)
continue;
p=GetCacheViewVirtualPixels(edge_view,0,y,edge_image->columns+1,2,
exception);
if (p == (const PixelPacket *) NULL)
{
status=MagickFalse;
continue;
}
for (x=0; x < (ssize_t) edge_image->columns; x++)
{
CannyInfo
pixel;
double
dx,
dy;
register const PixelPacket
*restrict kernel_pixels;
ssize_t
v;
static double
Gx[2][2] =
{
{ -1.0, +1.0 },
{ -1.0, +1.0 }
},
Gy[2][2] =
{
{ +1.0, +1.0 },
{ -1.0, -1.0 }
};
(void) ResetMagickMemory(&pixel,0,sizeof(pixel));
dx=0.0;
dy=0.0;
kernel_pixels=p;
for (v=0; v < 2; v++)
{
ssize_t
u;
for (u=0; u < 2; u++)
{
double
intensity;
intensity=GetPixelIntensity(edge_image,kernel_pixels+u);
dx+=0.5*Gx[v][u]*intensity;
dy+=0.5*Gy[v][u]*intensity;
}
kernel_pixels+=edge_image->columns+1;
}
pixel.magnitude=hypot(dx,dy);
pixel.orientation=0;
if (fabs(dx) > MagickEpsilon)
{
double
slope;
slope=dy/dx;
if (slope < 0.0)
{
if (slope < -2.41421356237)
pixel.orientation=0;
else
if (slope < -0.414213562373)
pixel.orientation=1;
else
pixel.orientation=2;
}
else
{
if (slope > 2.41421356237)
pixel.orientation=0;
else
if (slope > 0.414213562373)
pixel.orientation=3;
else
pixel.orientation=2;
}
}
if (SetMatrixElement(canny_cache,x,y,&pixel) == MagickFalse)
continue;
p++;
}
}
edge_view=DestroyCacheView(edge_view);
/*
Non-maxima suppression, remove pixels that are not considered to be part
of an edge.
*/
progress=0;
(void) GetMatrixElement(canny_cache,0,0,&pixel);
max=pixel.intensity;
min=pixel.intensity;
edge_view=AcquireAuthenticCacheView(edge_image,exception);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static,4) shared(status) \
magick_threads(edge_image,edge_image,edge_image->rows,1)
#endif
for (y=0; y < (ssize_t) edge_image->rows; y++)
{
register PixelPacket
*restrict q;
register ssize_t
x;
if (status == MagickFalse)
continue;
q=GetCacheViewAuthenticPixels(edge_view,0,y,edge_image->columns,1,
exception);
if (q == (PixelPacket *) NULL)
{
status=MagickFalse;
continue;
}
for (x=0; x < (ssize_t) edge_image->columns; x++)
{
CannyInfo
alpha_pixel,
beta_pixel,
pixel;
(void) GetMatrixElement(canny_cache,x,y,&pixel);
switch (pixel.orientation)
{
case 0:
default:
{
/*
0 degrees, north and south.
*/
(void) GetMatrixElement(canny_cache,x,y-1,&alpha_pixel);
(void) GetMatrixElement(canny_cache,x,y+1,&beta_pixel);
break;
}
case 1:
{
/*
45 degrees, northwest and southeast.
*/
(void) GetMatrixElement(canny_cache,x-1,y-1,&alpha_pixel);
(void) GetMatrixElement(canny_cache,x+1,y+1,&beta_pixel);
break;
}
case 2:
{
/*
90 degrees, east and west.
*/
(void) GetMatrixElement(canny_cache,x-1,y,&alpha_pixel);
(void) GetMatrixElement(canny_cache,x+1,y,&beta_pixel);
break;
}
case 3:
{
/*
135 degrees, northeast and southwest.
*/
(void) GetMatrixElement(canny_cache,x+1,y-1,&beta_pixel);
(void) GetMatrixElement(canny_cache,x-1,y+1,&alpha_pixel);
break;
}
}
pixel.intensity=pixel.magnitude;
if ((pixel.magnitude < alpha_pixel.magnitude) ||
(pixel.magnitude < beta_pixel.magnitude))
pixel.intensity=0;
(void) SetMatrixElement(canny_cache,x,y,&pixel);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp critical (MagickCore_CannyEdgeImage)
#endif
{
if (pixel.intensity < min)
min=pixel.intensity;
if (pixel.intensity > max)
max=pixel.intensity;
}
q->red=0;
q->green=0;
q->blue=0;
q++;
}
if (SyncCacheViewAuthenticPixels(edge_view,exception) == MagickFalse)
status=MagickFalse;
if (image->progress_monitor != (MagickProgressMonitor) NULL)
{
MagickBooleanType
proceed;
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp critical (MagickCore_CannyEdgeImage)
#endif
proceed=SetImageProgress(image,CannyEdgeImageTag,progress++,
image->rows);
if (proceed == MagickFalse)
status=MagickFalse;
}
}
edge_view=DestroyCacheView(edge_view);
/*
Estimate hysteresis threshold.
*/
lower_threshold=lower_percent*(max-min)+min;
upper_threshold=upper_percent*(max-min)+min;
/*
Hysteresis threshold.
*/
edge_view=AcquireAuthenticCacheView(edge_image,exception);
for (y=0; y < (ssize_t) edge_image->rows; y++)
{
register ssize_t
x;
if (status == MagickFalse)
continue;
for (x=0; x < (ssize_t) edge_image->columns; x++)
{
CannyInfo
pixel;
register const PixelPacket
*restrict p;
/*
Edge if pixel gradient higher than upper threshold.
*/
p=GetCacheViewVirtualPixels(edge_view,x,y,1,1,exception);
if (p == (const PixelPacket *) NULL)
continue;
status=GetMatrixElement(canny_cache,x,y,&pixel);
if (status == MagickFalse)
continue;
if ((GetPixelIntensity(edge_image,p) == 0.0) &&
(pixel.intensity >= upper_threshold))
status=TraceEdges(edge_image,edge_view,canny_cache,x,y,lower_threshold,
exception);
}
}
edge_view=DestroyCacheView(edge_view);
/*
Free resources.
*/
canny_cache=DestroyMatrixInfo(canny_cache);
return(edge_image);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% G e t I m a g e C h a n n e l F e a t u r e s %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% GetImageChannelFeatures() returns features for each channel in the image in
% each of four directions (horizontal, vertical, left and right diagonals)
% for the specified distance. The features include the angular second
% moment, contrast, correlation, sum of squares: variance, inverse difference
% moment, sum average, sum varience, sum entropy, entropy, difference variance,% difference entropy, information measures of correlation 1, information
% measures of correlation 2, and maximum correlation coefficient. You can
% access the red channel contrast, for example, like this:
%
% channel_features=GetImageChannelFeatures(image,1,exception);
% contrast=channel_features[RedChannel].contrast[0];
%
% Use MagickRelinquishMemory() to free the features buffer.
%
% The format of the GetImageChannelFeatures method is:
%
% ChannelFeatures *GetImageChannelFeatures(const Image *image,
% const size_t distance,ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o distance: the distance.
%
% o exception: return any errors or warnings in this structure.
%
*/
static inline ssize_t MagickAbsoluteValue(const ssize_t x)
{
if (x < 0)
return(-x);
return(x);
}
static inline double MagickLog10(const double x)
{
#define Log10Epsilon (1.0e-11)
if (fabs(x) < Log10Epsilon)
return(log10(Log10Epsilon));
return(log10(fabs(x)));
}
MagickExport ChannelFeatures *GetImageChannelFeatures(const Image *image,
const size_t distance,ExceptionInfo *exception)
{
typedef struct _ChannelStatistics
{
DoublePixelPacket
direction[4]; /* horizontal, vertical, left and right diagonals */
} ChannelStatistics;
CacheView
*image_view;
ChannelFeatures
*channel_features;
ChannelStatistics
**cooccurrence,
correlation,
*density_x,
*density_xy,
*density_y,
entropy_x,
entropy_xy,
entropy_xy1,
entropy_xy2,
entropy_y,
mean,
**Q,
*sum,
sum_squares,
variance;
LongPixelPacket
gray,
*grays;
MagickBooleanType
status;
register ssize_t
i;
size_t
length;
ssize_t
y;
unsigned int
number_grays;
assert(image != (Image *) NULL);
assert(image->signature == MagickSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
if ((image->columns < (distance+1)) || (image->rows < (distance+1)))
return((ChannelFeatures *) NULL);
length=CompositeChannels+1UL;
channel_features=(ChannelFeatures *) AcquireQuantumMemory(length,
sizeof(*channel_features));
if (channel_features == (ChannelFeatures *) NULL)
ThrowFatalException(ResourceLimitFatalError,"MemoryAllocationFailed");
(void) ResetMagickMemory(channel_features,0,length*
sizeof(*channel_features));
/*
Form grays.
*/
grays=(LongPixelPacket *) AcquireQuantumMemory(MaxMap+1UL,sizeof(*grays));
if (grays == (LongPixelPacket *) NULL)
{
channel_features=(ChannelFeatures *) RelinquishMagickMemory(
channel_features);
(void) ThrowMagickException(exception,GetMagickModule(),
ResourceLimitError,"MemoryAllocationFailed","`%s'",image->filename);
return(channel_features);
}
for (i=0; i <= (ssize_t) MaxMap; i++)
{
grays[i].red=(~0U);
grays[i].green=(~0U);
grays[i].blue=(~0U);
grays[i].opacity=(~0U);
grays[i].index=(~0U);
}
status=MagickTrue;
image_view=AcquireVirtualCacheView(image,exception);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static,4) shared(status) \
magick_threads(image,image,image->rows,1)
#endif
for (y=0; y < (ssize_t) image->rows; y++)
{
register const IndexPacket
*restrict indexes;
register const PixelPacket
*restrict p;
register ssize_t
x;
if (status == MagickFalse)
continue;
p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1,exception);
if (p == (const PixelPacket *) NULL)
{
status=MagickFalse;
continue;
}
indexes=GetCacheViewVirtualIndexQueue(image_view);
for (x=0; x < (ssize_t) image->columns; x++)
{
grays[ScaleQuantumToMap(GetPixelRed(p))].red=
ScaleQuantumToMap(GetPixelRed(p));
grays[ScaleQuantumToMap(GetPixelGreen(p))].green=
ScaleQuantumToMap(GetPixelGreen(p));
grays[ScaleQuantumToMap(GetPixelBlue(p))].blue=
ScaleQuantumToMap(GetPixelBlue(p));
if (image->colorspace == CMYKColorspace)
grays[ScaleQuantumToMap(GetPixelIndex(indexes+x))].index=
ScaleQuantumToMap(GetPixelIndex(indexes+x));
if (image->matte != MagickFalse)
grays[ScaleQuantumToMap(GetPixelOpacity(p))].opacity=
ScaleQuantumToMap(GetPixelOpacity(p));
p++;
}
}
image_view=DestroyCacheView(image_view);
if (status == MagickFalse)
{
grays=(LongPixelPacket *) RelinquishMagickMemory(grays);
channel_features=(ChannelFeatures *) RelinquishMagickMemory(
channel_features);
return(channel_features);
}
(void) ResetMagickMemory(&gray,0,sizeof(gray));
for (i=0; i <= (ssize_t) MaxMap; i++)
{
if (grays[i].red != ~0U)
grays[(ssize_t) gray.red++].red=grays[i].red;
if (grays[i].green != ~0U)
grays[(ssize_t) gray.green++].green=grays[i].green;
if (grays[i].blue != ~0U)
grays[(ssize_t) gray.blue++].blue=grays[i].blue;
if (image->colorspace == CMYKColorspace)
if (grays[i].index != ~0U)
grays[(ssize_t) gray.index++].index=grays[i].index;
if (image->matte != MagickFalse)
if (grays[i].opacity != ~0U)
grays[(ssize_t) gray.opacity++].opacity=grays[i].opacity;
}
/*
Allocate spatial dependence matrix.
*/
number_grays=gray.red;
if (gray.green > number_grays)
number_grays=gray.green;
if (gray.blue > number_grays)
number_grays=gray.blue;
if (image->colorspace == CMYKColorspace)
if (gray.index > number_grays)
number_grays=gray.index;
if (image->matte != MagickFalse)
if (gray.opacity > number_grays)
number_grays=gray.opacity;
cooccurrence=(ChannelStatistics **) AcquireQuantumMemory(number_grays,
sizeof(*cooccurrence));
density_x=(ChannelStatistics *) AcquireQuantumMemory(2*(number_grays+1),
sizeof(*density_x));
density_xy=(ChannelStatistics *) AcquireQuantumMemory(2*(number_grays+1),
sizeof(*density_xy));
density_y=(ChannelStatistics *) AcquireQuantumMemory(2*(number_grays+1),
sizeof(*density_y));
Q=(ChannelStatistics **) AcquireQuantumMemory(number_grays,sizeof(*Q));
sum=(ChannelStatistics *) AcquireQuantumMemory(number_grays,sizeof(*sum));
if ((cooccurrence == (ChannelStatistics **) NULL) ||
(density_x == (ChannelStatistics *) NULL) ||
(density_xy == (ChannelStatistics *) NULL) ||
(density_y == (ChannelStatistics *) NULL) ||
(Q == (ChannelStatistics **) NULL) ||
(sum == (ChannelStatistics *) NULL))
{
if (Q != (ChannelStatistics **) NULL)
{
for (i=0; i < (ssize_t) number_grays; i++)
Q[i]=(ChannelStatistics *) RelinquishMagickMemory(Q[i]);
Q=(ChannelStatistics **) RelinquishMagickMemory(Q);
}
if (sum != (ChannelStatistics *) NULL)
sum=(ChannelStatistics *) RelinquishMagickMemory(sum);
if (density_y != (ChannelStatistics *) NULL)
density_y=(ChannelStatistics *) RelinquishMagickMemory(density_y);
if (density_xy != (ChannelStatistics *) NULL)
density_xy=(ChannelStatistics *) RelinquishMagickMemory(density_xy);
if (density_x != (ChannelStatistics *) NULL)
density_x=(ChannelStatistics *) RelinquishMagickMemory(density_x);
if (cooccurrence != (ChannelStatistics **) NULL)
{
for (i=0; i < (ssize_t) number_grays; i++)
cooccurrence[i]=(ChannelStatistics *)
RelinquishMagickMemory(cooccurrence[i]);
cooccurrence=(ChannelStatistics **) RelinquishMagickMemory(
cooccurrence);
}
grays=(LongPixelPacket *) RelinquishMagickMemory(grays);
channel_features=(ChannelFeatures *) RelinquishMagickMemory(
channel_features);
(void) ThrowMagickException(exception,GetMagickModule(),
ResourceLimitError,"MemoryAllocationFailed","`%s'",image->filename);
return(channel_features);
}
(void) ResetMagickMemory(&correlation,0,sizeof(correlation));
(void) ResetMagickMemory(density_x,0,2*(number_grays+1)*sizeof(*density_x));
(void) ResetMagickMemory(density_xy,0,2*(number_grays+1)*sizeof(*density_xy));
(void) ResetMagickMemory(density_y,0,2*(number_grays+1)*sizeof(*density_y));
(void) ResetMagickMemory(&mean,0,sizeof(mean));
(void) ResetMagickMemory(sum,0,number_grays*sizeof(*sum));
(void) ResetMagickMemory(&sum_squares,0,sizeof(sum_squares));
(void) ResetMagickMemory(density_xy,0,2*number_grays*sizeof(*density_xy));
(void) ResetMagickMemory(&entropy_x,0,sizeof(entropy_x));
(void) ResetMagickMemory(&entropy_xy,0,sizeof(entropy_xy));
(void) ResetMagickMemory(&entropy_xy1,0,sizeof(entropy_xy1));
(void) ResetMagickMemory(&entropy_xy2,0,sizeof(entropy_xy2));
(void) ResetMagickMemory(&entropy_y,0,sizeof(entropy_y));
(void) ResetMagickMemory(&variance,0,sizeof(variance));
for (i=0; i < (ssize_t) number_grays; i++)
{
cooccurrence[i]=(ChannelStatistics *) AcquireQuantumMemory(number_grays,
sizeof(**cooccurrence));
Q[i]=(ChannelStatistics *) AcquireQuantumMemory(number_grays,sizeof(**Q));
if ((cooccurrence[i] == (ChannelStatistics *) NULL) ||
(Q[i] == (ChannelStatistics *) NULL))
break;
(void) ResetMagickMemory(cooccurrence[i],0,number_grays*
sizeof(**cooccurrence));
(void) ResetMagickMemory(Q[i],0,number_grays*sizeof(**Q));
}
if (i < (ssize_t) number_grays)
{
for (i--; i >= 0; i--)
{
if (Q[i] != (ChannelStatistics *) NULL)
Q[i]=(ChannelStatistics *) RelinquishMagickMemory(Q[i]);
if (cooccurrence[i] != (ChannelStatistics *) NULL)
cooccurrence[i]=(ChannelStatistics *)
RelinquishMagickMemory(cooccurrence[i]);
}
Q=(ChannelStatistics **) RelinquishMagickMemory(Q);
cooccurrence=(ChannelStatistics **) RelinquishMagickMemory(cooccurrence);
sum=(ChannelStatistics *) RelinquishMagickMemory(sum);
density_y=(ChannelStatistics *) RelinquishMagickMemory(density_y);
density_xy=(ChannelStatistics *) RelinquishMagickMemory(density_xy);
density_x=(ChannelStatistics *) RelinquishMagickMemory(density_x);
grays=(LongPixelPacket *) RelinquishMagickMemory(grays);
channel_features=(ChannelFeatures *) RelinquishMagickMemory(
channel_features);
(void) ThrowMagickException(exception,GetMagickModule(),
ResourceLimitError,"MemoryAllocationFailed","`%s'",image->filename);
return(channel_features);
}
/*
Initialize spatial dependence matrix.
*/
status=MagickTrue;
image_view=AcquireVirtualCacheView(image,exception);
for (y=0; y < (ssize_t) image->rows; y++)
{
register const IndexPacket
*restrict indexes;
register const PixelPacket
*restrict p;
register ssize_t
x;
ssize_t
i,
offset,
u,
v;
if (status == MagickFalse)
continue;
p=GetCacheViewVirtualPixels(image_view,-(ssize_t) distance,y,image->columns+
2*distance,distance+2,exception);
if (p == (const PixelPacket *) NULL)
{
status=MagickFalse;
continue;
}
indexes=GetCacheViewVirtualIndexQueue(image_view);
p+=distance;
indexes+=distance;
for (x=0; x < (ssize_t) image->columns; x++)
{
for (i=0; i < 4; i++)
{
switch (i)
{
case 0:
default:
{
/*
Horizontal adjacency.
*/
offset=(ssize_t) distance;
break;
}
case 1:
{
/*
Vertical adjacency.
*/
offset=(ssize_t) (image->columns+2*distance);
break;
}
case 2:
{
/*
Right diagonal adjacency.
*/
offset=(ssize_t) ((image->columns+2*distance)-distance);
break;
}
case 3:
{
/*
Left diagonal adjacency.
*/
offset=(ssize_t) ((image->columns+2*distance)+distance);
break;
}
}
u=0;
v=0;
while (grays[u].red != ScaleQuantumToMap(GetPixelRed(p)))
u++;
while (grays[v].red != ScaleQuantumToMap(GetPixelRed(p+offset)))
v++;
cooccurrence[u][v].direction[i].red++;
cooccurrence[v][u].direction[i].red++;
u=0;
v=0;
while (grays[u].green != ScaleQuantumToMap(GetPixelGreen(p)))
u++;
while (grays[v].green != ScaleQuantumToMap(GetPixelGreen(p+offset)))
v++;
cooccurrence[u][v].direction[i].green++;
cooccurrence[v][u].direction[i].green++;
u=0;
v=0;
while (grays[u].blue != ScaleQuantumToMap(GetPixelBlue(p)))
u++;
while (grays[v].blue != ScaleQuantumToMap((p+offset)->blue))
v++;
cooccurrence[u][v].direction[i].blue++;
cooccurrence[v][u].direction[i].blue++;
if (image->colorspace == CMYKColorspace)
{
u=0;
v=0;
while (grays[u].index != ScaleQuantumToMap(GetPixelIndex(indexes+x)))
u++;
while (grays[v].index != ScaleQuantumToMap(GetPixelIndex(indexes+x+offset)))
v++;
cooccurrence[u][v].direction[i].index++;
cooccurrence[v][u].direction[i].index++;
}
if (image->matte != MagickFalse)
{
u=0;
v=0;
while (grays[u].opacity != ScaleQuantumToMap(GetPixelOpacity(p)))
u++;
while (grays[v].opacity != ScaleQuantumToMap((p+offset)->opacity))
v++;
cooccurrence[u][v].direction[i].opacity++;
cooccurrence[v][u].direction[i].opacity++;
}
}
p++;
}
}
grays=(LongPixelPacket *) RelinquishMagickMemory(grays);
image_view=DestroyCacheView(image_view);
if (status == MagickFalse)
{
for (i=0; i < (ssize_t) number_grays; i++)
cooccurrence[i]=(ChannelStatistics *)
RelinquishMagickMemory(cooccurrence[i]);
cooccurrence=(ChannelStatistics **) RelinquishMagickMemory(cooccurrence);
channel_features=(ChannelFeatures *) RelinquishMagickMemory(
channel_features);
(void) ThrowMagickException(exception,GetMagickModule(),
ResourceLimitError,"MemoryAllocationFailed","`%s'",image->filename);
return(channel_features);
}
/*
Normalize spatial dependence matrix.
*/
for (i=0; i < 4; i++)
{
double
normalize;
register ssize_t
y;
switch (i)
{
case 0:
default:
{
/*
Horizontal adjacency.
*/
normalize=2.0*image->rows*(image->columns-distance);
break;
}
case 1:
{
/*
Vertical adjacency.
*/
normalize=2.0*(image->rows-distance)*image->columns;
break;
}
case 2:
{
/*
Right diagonal adjacency.
*/
normalize=2.0*(image->rows-distance)*(image->columns-distance);
break;
}
case 3:
{
/*
Left diagonal adjacency.
*/
normalize=2.0*(image->rows-distance)*(image->columns-distance);
break;
}
}
normalize=PerceptibleReciprocal(normalize);
for (y=0; y < (ssize_t) number_grays; y++)
{
register ssize_t
x;
for (x=0; x < (ssize_t) number_grays; x++)
{
cooccurrence[x][y].direction[i].red*=normalize;
cooccurrence[x][y].direction[i].green*=normalize;
cooccurrence[x][y].direction[i].blue*=normalize;
if (image->colorspace == CMYKColorspace)
cooccurrence[x][y].direction[i].index*=normalize;
if (image->matte != MagickFalse)
cooccurrence[x][y].direction[i].opacity*=normalize;
}
}
}
/*
Compute texture features.
*/
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static,4) shared(status) \
magick_threads(image,image,number_grays,1)
#endif
for (i=0; i < 4; i++)
{
register ssize_t
y;
for (y=0; y < (ssize_t) number_grays; y++)
{
register ssize_t
x;
for (x=0; x < (ssize_t) number_grays; x++)
{
/*
Angular second moment: measure of homogeneity of the image.
*/
channel_features[RedChannel].angular_second_moment[i]+=
cooccurrence[x][y].direction[i].red*
cooccurrence[x][y].direction[i].red;
channel_features[GreenChannel].angular_second_moment[i]+=
cooccurrence[x][y].direction[i].green*
cooccurrence[x][y].direction[i].green;
channel_features[BlueChannel].angular_second_moment[i]+=
cooccurrence[x][y].direction[i].blue*
cooccurrence[x][y].direction[i].blue;
if (image->colorspace == CMYKColorspace)
channel_features[BlackChannel].angular_second_moment[i]+=
cooccurrence[x][y].direction[i].index*
cooccurrence[x][y].direction[i].index;
if (image->matte != MagickFalse)
channel_features[OpacityChannel].angular_second_moment[i]+=
cooccurrence[x][y].direction[i].opacity*
cooccurrence[x][y].direction[i].opacity;
/*
Correlation: measure of linear-dependencies in the image.
*/
sum[y].direction[i].red+=cooccurrence[x][y].direction[i].red;
sum[y].direction[i].green+=cooccurrence[x][y].direction[i].green;
sum[y].direction[i].blue+=cooccurrence[x][y].direction[i].blue;
if (image->colorspace == CMYKColorspace)
sum[y].direction[i].index+=cooccurrence[x][y].direction[i].index;
if (image->matte != MagickFalse)
sum[y].direction[i].opacity+=cooccurrence[x][y].direction[i].opacity;
correlation.direction[i].red+=x*y*cooccurrence[x][y].direction[i].red;
correlation.direction[i].green+=x*y*
cooccurrence[x][y].direction[i].green;
correlation.direction[i].blue+=x*y*
cooccurrence[x][y].direction[i].blue;
if (image->colorspace == CMYKColorspace)
correlation.direction[i].index+=x*y*
cooccurrence[x][y].direction[i].index;
if (image->matte != MagickFalse)
correlation.direction[i].opacity+=x*y*
cooccurrence[x][y].direction[i].opacity;
/*
Inverse Difference Moment.
*/
channel_features[RedChannel].inverse_difference_moment[i]+=
cooccurrence[x][y].direction[i].red/((y-x)*(y-x)+1);
channel_features[GreenChannel].inverse_difference_moment[i]+=
cooccurrence[x][y].direction[i].green/((y-x)*(y-x)+1);
channel_features[BlueChannel].inverse_difference_moment[i]+=
cooccurrence[x][y].direction[i].blue/((y-x)*(y-x)+1);
if (image->colorspace == CMYKColorspace)
channel_features[IndexChannel].inverse_difference_moment[i]+=
cooccurrence[x][y].direction[i].index/((y-x)*(y-x)+1);
if (image->matte != MagickFalse)
channel_features[OpacityChannel].inverse_difference_moment[i]+=
cooccurrence[x][y].direction[i].opacity/((y-x)*(y-x)+1);
/*
Sum average.
*/
density_xy[y+x+2].direction[i].red+=
cooccurrence[x][y].direction[i].red;
density_xy[y+x+2].direction[i].green+=
cooccurrence[x][y].direction[i].green;
density_xy[y+x+2].direction[i].blue+=
cooccurrence[x][y].direction[i].blue;
if (image->colorspace == CMYKColorspace)
density_xy[y+x+2].direction[i].index+=
cooccurrence[x][y].direction[i].index;
if (image->matte != MagickFalse)
density_xy[y+x+2].direction[i].opacity+=
cooccurrence[x][y].direction[i].opacity;
/*
Entropy.
*/
channel_features[RedChannel].entropy[i]-=
cooccurrence[x][y].direction[i].red*
MagickLog10(cooccurrence[x][y].direction[i].red);
channel_features[GreenChannel].entropy[i]-=
cooccurrence[x][y].direction[i].green*
MagickLog10(cooccurrence[x][y].direction[i].green);
channel_features[BlueChannel].entropy[i]-=
cooccurrence[x][y].direction[i].blue*
MagickLog10(cooccurrence[x][y].direction[i].blue);
if (image->colorspace == CMYKColorspace)
channel_features[IndexChannel].entropy[i]-=
cooccurrence[x][y].direction[i].index*
MagickLog10(cooccurrence[x][y].direction[i].index);
if (image->matte != MagickFalse)
channel_features[OpacityChannel].entropy[i]-=
cooccurrence[x][y].direction[i].opacity*
MagickLog10(cooccurrence[x][y].direction[i].opacity);
/*
Information Measures of Correlation.
*/
density_x[x].direction[i].red+=cooccurrence[x][y].direction[i].red;
density_x[x].direction[i].green+=cooccurrence[x][y].direction[i].green;
density_x[x].direction[i].blue+=cooccurrence[x][y].direction[i].blue;
if (image->colorspace == CMYKColorspace)
density_x[x].direction[i].index+=
cooccurrence[x][y].direction[i].index;
if (image->matte != MagickFalse)
density_x[x].direction[i].opacity+=
cooccurrence[x][y].direction[i].opacity;
density_y[y].direction[i].red+=cooccurrence[x][y].direction[i].red;
density_y[y].direction[i].green+=cooccurrence[x][y].direction[i].green;
density_y[y].direction[i].blue+=cooccurrence[x][y].direction[i].blue;
if (image->colorspace == CMYKColorspace)
density_y[y].direction[i].index+=
cooccurrence[x][y].direction[i].index;
if (image->matte != MagickFalse)
density_y[y].direction[i].opacity+=
cooccurrence[x][y].direction[i].opacity;
}
mean.direction[i].red+=y*sum[y].direction[i].red;
sum_squares.direction[i].red+=y*y*sum[y].direction[i].red;
mean.direction[i].green+=y*sum[y].direction[i].green;
sum_squares.direction[i].green+=y*y*sum[y].direction[i].green;
mean.direction[i].blue+=y*sum[y].direction[i].blue;
sum_squares.direction[i].blue+=y*y*sum[y].direction[i].blue;
if (image->colorspace == CMYKColorspace)
{
mean.direction[i].index+=y*sum[y].direction[i].index;
sum_squares.direction[i].index+=y*y*sum[y].direction[i].index;
}
if (image->matte != MagickFalse)
{
mean.direction[i].opacity+=y*sum[y].direction[i].opacity;
sum_squares.direction[i].opacity+=y*y*sum[y].direction[i].opacity;
}
}
/*
Correlation: measure of linear-dependencies in the image.
*/
channel_features[RedChannel].correlation[i]=
(correlation.direction[i].red-mean.direction[i].red*
mean.direction[i].red)/(sqrt(sum_squares.direction[i].red-
(mean.direction[i].red*mean.direction[i].red))*sqrt(
sum_squares.direction[i].red-(mean.direction[i].red*
mean.direction[i].red)));
channel_features[GreenChannel].correlation[i]=
(correlation.direction[i].green-mean.direction[i].green*
mean.direction[i].green)/(sqrt(sum_squares.direction[i].green-
(mean.direction[i].green*mean.direction[i].green))*sqrt(
sum_squares.direction[i].green-(mean.direction[i].green*
mean.direction[i].green)));
channel_features[BlueChannel].correlation[i]=
(correlation.direction[i].blue-mean.direction[i].blue*
mean.direction[i].blue)/(sqrt(sum_squares.direction[i].blue-
(mean.direction[i].blue*mean.direction[i].blue))*sqrt(
sum_squares.direction[i].blue-(mean.direction[i].blue*
mean.direction[i].blue)));
if (image->colorspace == CMYKColorspace)
channel_features[IndexChannel].correlation[i]=
(correlation.direction[i].index-mean.direction[i].index*
mean.direction[i].index)/(sqrt(sum_squares.direction[i].index-
(mean.direction[i].index*mean.direction[i].index))*sqrt(
sum_squares.direction[i].index-(mean.direction[i].index*
mean.direction[i].index)));
if (image->matte != MagickFalse)
channel_features[OpacityChannel].correlation[i]=
(correlation.direction[i].opacity-mean.direction[i].opacity*
mean.direction[i].opacity)/(sqrt(sum_squares.direction[i].opacity-
(mean.direction[i].opacity*mean.direction[i].opacity))*sqrt(
sum_squares.direction[i].opacity-(mean.direction[i].opacity*
mean.direction[i].opacity)));
}
/*
Compute more texture features.
*/
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static,4) shared(status) \
magick_threads(image,image,number_grays,1)
#endif
for (i=0; i < 4; i++)
{
register ssize_t
x;
for (x=2; x < (ssize_t) (2*number_grays); x++)
{
/*
Sum average.
*/
channel_features[RedChannel].sum_average[i]+=
x*density_xy[x].direction[i].red;
channel_features[GreenChannel].sum_average[i]+=
x*density_xy[x].direction[i].green;
channel_features[BlueChannel].sum_average[i]+=
x*density_xy[x].direction[i].blue;
if (image->colorspace == CMYKColorspace)
channel_features[IndexChannel].sum_average[i]+=
x*density_xy[x].direction[i].index;
if (image->matte != MagickFalse)
channel_features[OpacityChannel].sum_average[i]+=
x*density_xy[x].direction[i].opacity;
/*
Sum entropy.
*/
channel_features[RedChannel].sum_entropy[i]-=
density_xy[x].direction[i].red*
MagickLog10(density_xy[x].direction[i].red);
channel_features[GreenChannel].sum_entropy[i]-=
density_xy[x].direction[i].green*
MagickLog10(density_xy[x].direction[i].green);
channel_features[BlueChannel].sum_entropy[i]-=
density_xy[x].direction[i].blue*
MagickLog10(density_xy[x].direction[i].blue);
if (image->colorspace == CMYKColorspace)
channel_features[IndexChannel].sum_entropy[i]-=
density_xy[x].direction[i].index*
MagickLog10(density_xy[x].direction[i].index);
if (image->matte != MagickFalse)
channel_features[OpacityChannel].sum_entropy[i]-=
density_xy[x].direction[i].opacity*
MagickLog10(density_xy[x].direction[i].opacity);
/*
Sum variance.
*/
channel_features[RedChannel].sum_variance[i]+=
(x-channel_features[RedChannel].sum_entropy[i])*
(x-channel_features[RedChannel].sum_entropy[i])*
density_xy[x].direction[i].red;
channel_features[GreenChannel].sum_variance[i]+=
(x-channel_features[GreenChannel].sum_entropy[i])*
(x-channel_features[GreenChannel].sum_entropy[i])*
density_xy[x].direction[i].green;
channel_features[BlueChannel].sum_variance[i]+=
(x-channel_features[BlueChannel].sum_entropy[i])*
(x-channel_features[BlueChannel].sum_entropy[i])*
density_xy[x].direction[i].blue;
if (image->colorspace == CMYKColorspace)
channel_features[IndexChannel].sum_variance[i]+=
(x-channel_features[IndexChannel].sum_entropy[i])*
(x-channel_features[IndexChannel].sum_entropy[i])*
density_xy[x].direction[i].index;
if (image->matte != MagickFalse)
channel_features[OpacityChannel].sum_variance[i]+=
(x-channel_features[OpacityChannel].sum_entropy[i])*
(x-channel_features[OpacityChannel].sum_entropy[i])*
density_xy[x].direction[i].opacity;
}
}
/*
Compute more texture features.
*/
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static,4) shared(status) \
magick_threads(image,image,number_grays,1)
#endif
for (i=0; i < 4; i++)
{
register ssize_t
y;
for (y=0; y < (ssize_t) number_grays; y++)
{
register ssize_t
x;
for (x=0; x < (ssize_t) number_grays; x++)
{
/*
Sum of Squares: Variance
*/
variance.direction[i].red+=(y-mean.direction[i].red+1)*
(y-mean.direction[i].red+1)*cooccurrence[x][y].direction[i].red;
variance.direction[i].green+=(y-mean.direction[i].green+1)*
(y-mean.direction[i].green+1)*cooccurrence[x][y].direction[i].green;
variance.direction[i].blue+=(y-mean.direction[i].blue+1)*
(y-mean.direction[i].blue+1)*cooccurrence[x][y].direction[i].blue;
if (image->colorspace == CMYKColorspace)
variance.direction[i].index+=(y-mean.direction[i].index+1)*
(y-mean.direction[i].index+1)*cooccurrence[x][y].direction[i].index;
if (image->matte != MagickFalse)
variance.direction[i].opacity+=(y-mean.direction[i].opacity+1)*
(y-mean.direction[i].opacity+1)*
cooccurrence[x][y].direction[i].opacity;
/*
Sum average / Difference Variance.
*/
density_xy[MagickAbsoluteValue(y-x)].direction[i].red+=
cooccurrence[x][y].direction[i].red;
density_xy[MagickAbsoluteValue(y-x)].direction[i].green+=
cooccurrence[x][y].direction[i].green;
density_xy[MagickAbsoluteValue(y-x)].direction[i].blue+=
cooccurrence[x][y].direction[i].blue;
if (image->colorspace == CMYKColorspace)
density_xy[MagickAbsoluteValue(y-x)].direction[i].index+=
cooccurrence[x][y].direction[i].index;
if (image->matte != MagickFalse)
density_xy[MagickAbsoluteValue(y-x)].direction[i].opacity+=
cooccurrence[x][y].direction[i].opacity;
/*
Information Measures of Correlation.
*/
entropy_xy.direction[i].red-=cooccurrence[x][y].direction[i].red*
MagickLog10(cooccurrence[x][y].direction[i].red);
entropy_xy.direction[i].green-=cooccurrence[x][y].direction[i].green*
MagickLog10(cooccurrence[x][y].direction[i].green);
entropy_xy.direction[i].blue-=cooccurrence[x][y].direction[i].blue*
MagickLog10(cooccurrence[x][y].direction[i].blue);
if (image->colorspace == CMYKColorspace)
entropy_xy.direction[i].index-=cooccurrence[x][y].direction[i].index*
MagickLog10(cooccurrence[x][y].direction[i].index);
if (image->matte != MagickFalse)
entropy_xy.direction[i].opacity-=
cooccurrence[x][y].direction[i].opacity*MagickLog10(
cooccurrence[x][y].direction[i].opacity);
entropy_xy1.direction[i].red-=(cooccurrence[x][y].direction[i].red*
MagickLog10(density_x[x].direction[i].red*
density_y[y].direction[i].red));
entropy_xy1.direction[i].green-=(cooccurrence[x][y].direction[i].green*
MagickLog10(density_x[x].direction[i].green*
density_y[y].direction[i].green));
entropy_xy1.direction[i].blue-=(cooccurrence[x][y].direction[i].blue*
MagickLog10(density_x[x].direction[i].blue*
density_y[y].direction[i].blue));
if (image->colorspace == CMYKColorspace)
entropy_xy1.direction[i].index-=(
cooccurrence[x][y].direction[i].index*MagickLog10(
density_x[x].direction[i].index*density_y[y].direction[i].index));
if (image->matte != MagickFalse)
entropy_xy1.direction[i].opacity-=(
cooccurrence[x][y].direction[i].opacity*MagickLog10(
density_x[x].direction[i].opacity*
density_y[y].direction[i].opacity));
entropy_xy2.direction[i].red-=(density_x[x].direction[i].red*
density_y[y].direction[i].red*MagickLog10(
density_x[x].direction[i].red*density_y[y].direction[i].red));
entropy_xy2.direction[i].green-=(density_x[x].direction[i].green*
density_y[y].direction[i].green*MagickLog10(
density_x[x].direction[i].green*density_y[y].direction[i].green));
entropy_xy2.direction[i].blue-=(density_x[x].direction[i].blue*
density_y[y].direction[i].blue*MagickLog10(
density_x[x].direction[i].blue*density_y[y].direction[i].blue));
if (image->colorspace == CMYKColorspace)
entropy_xy2.direction[i].index-=(density_x[x].direction[i].index*
density_y[y].direction[i].index*MagickLog10(
density_x[x].direction[i].index*density_y[y].direction[i].index));
if (image->matte != MagickFalse)
entropy_xy2.direction[i].opacity-=(density_x[x].direction[i].opacity*
density_y[y].direction[i].opacity*MagickLog10(
density_x[x].direction[i].opacity*
density_y[y].direction[i].opacity));
}
}
channel_features[RedChannel].variance_sum_of_squares[i]=
variance.direction[i].red;
channel_features[GreenChannel].variance_sum_of_squares[i]=
variance.direction[i].green;
channel_features[BlueChannel].variance_sum_of_squares[i]=
variance.direction[i].blue;
if (image->colorspace == CMYKColorspace)
channel_features[RedChannel].variance_sum_of_squares[i]=
variance.direction[i].index;
if (image->matte != MagickFalse)
channel_features[RedChannel].variance_sum_of_squares[i]=
variance.direction[i].opacity;
}
/*
Compute more texture features.
*/
(void) ResetMagickMemory(&variance,0,sizeof(variance));
(void) ResetMagickMemory(&sum_squares,0,sizeof(sum_squares));
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static,4) shared(status) \
magick_threads(image,image,number_grays,1)
#endif
for (i=0; i < 4; i++)
{
register ssize_t
x;
for (x=0; x < (ssize_t) number_grays; x++)
{
/*
Difference variance.
*/
variance.direction[i].red+=density_xy[x].direction[i].red;
variance.direction[i].green+=density_xy[x].direction[i].green;
variance.direction[i].blue+=density_xy[x].direction[i].blue;
if (image->colorspace == CMYKColorspace)
variance.direction[i].index+=density_xy[x].direction[i].index;
if (image->matte != MagickFalse)
variance.direction[i].opacity+=density_xy[x].direction[i].opacity;
sum_squares.direction[i].red+=density_xy[x].direction[i].red*
density_xy[x].direction[i].red;
sum_squares.direction[i].green+=density_xy[x].direction[i].green*
density_xy[x].direction[i].green;
sum_squares.direction[i].blue+=density_xy[x].direction[i].blue*
density_xy[x].direction[i].blue;
if (image->colorspace == CMYKColorspace)
sum_squares.direction[i].index+=density_xy[x].direction[i].index*
density_xy[x].direction[i].index;
if (image->matte != MagickFalse)
sum_squares.direction[i].opacity+=density_xy[x].direction[i].opacity*
density_xy[x].direction[i].opacity;
/*
Difference entropy.
*/
channel_features[RedChannel].difference_entropy[i]-=
density_xy[x].direction[i].red*
MagickLog10(density_xy[x].direction[i].red);
channel_features[GreenChannel].difference_entropy[i]-=
density_xy[x].direction[i].green*
MagickLog10(density_xy[x].direction[i].green);
channel_features[BlueChannel].difference_entropy[i]-=
density_xy[x].direction[i].blue*
MagickLog10(density_xy[x].direction[i].blue);
if (image->colorspace == CMYKColorspace)
channel_features[IndexChannel].difference_entropy[i]-=
density_xy[x].direction[i].index*
MagickLog10(density_xy[x].direction[i].index);
if (image->matte != MagickFalse)
channel_features[OpacityChannel].difference_entropy[i]-=
density_xy[x].direction[i].opacity*
MagickLog10(density_xy[x].direction[i].opacity);
/*
Information Measures of Correlation.
*/
entropy_x.direction[i].red-=(density_x[x].direction[i].red*
MagickLog10(density_x[x].direction[i].red));
entropy_x.direction[i].green-=(density_x[x].direction[i].green*
MagickLog10(density_x[x].direction[i].green));
entropy_x.direction[i].blue-=(density_x[x].direction[i].blue*
MagickLog10(density_x[x].direction[i].blue));
if (image->colorspace == CMYKColorspace)
entropy_x.direction[i].index-=(density_x[x].direction[i].index*
MagickLog10(density_x[x].direction[i].index));
if (image->matte != MagickFalse)
entropy_x.direction[i].opacity-=(density_x[x].direction[i].opacity*
MagickLog10(density_x[x].direction[i].opacity));
entropy_y.direction[i].red-=(density_y[x].direction[i].red*
MagickLog10(density_y[x].direction[i].red));
entropy_y.direction[i].green-=(density_y[x].direction[i].green*
MagickLog10(density_y[x].direction[i].green));
entropy_y.direction[i].blue-=(density_y[x].direction[i].blue*
MagickLog10(density_y[x].direction[i].blue));
if (image->colorspace == CMYKColorspace)
entropy_y.direction[i].index-=(density_y[x].direction[i].index*
MagickLog10(density_y[x].direction[i].index));
if (image->matte != MagickFalse)
entropy_y.direction[i].opacity-=(density_y[x].direction[i].opacity*
MagickLog10(density_y[x].direction[i].opacity));
}
/*
Difference variance.
*/
channel_features[RedChannel].difference_variance[i]=
(((double) number_grays*number_grays*sum_squares.direction[i].red)-
(variance.direction[i].red*variance.direction[i].red))/
((double) number_grays*number_grays*number_grays*number_grays);
channel_features[GreenChannel].difference_variance[i]=
(((double) number_grays*number_grays*sum_squares.direction[i].green)-
(variance.direction[i].green*variance.direction[i].green))/
((double) number_grays*number_grays*number_grays*number_grays);
channel_features[BlueChannel].difference_variance[i]=
(((double) number_grays*number_grays*sum_squares.direction[i].blue)-
(variance.direction[i].blue*variance.direction[i].blue))/
((double) number_grays*number_grays*number_grays*number_grays);
if (image->matte != MagickFalse)
channel_features[OpacityChannel].difference_variance[i]=
(((double) number_grays*number_grays*sum_squares.direction[i].opacity)-
(variance.direction[i].opacity*variance.direction[i].opacity))/
((double) number_grays*number_grays*number_grays*number_grays);
if (image->colorspace == CMYKColorspace)
channel_features[IndexChannel].difference_variance[i]=
(((double) number_grays*number_grays*sum_squares.direction[i].index)-
(variance.direction[i].index*variance.direction[i].index))/
((double) number_grays*number_grays*number_grays*number_grays);
/*
Information Measures of Correlation.
*/
channel_features[RedChannel].measure_of_correlation_1[i]=
(entropy_xy.direction[i].red-entropy_xy1.direction[i].red)/
(entropy_x.direction[i].red > entropy_y.direction[i].red ?
entropy_x.direction[i].red : entropy_y.direction[i].red);
channel_features[GreenChannel].measure_of_correlation_1[i]=
(entropy_xy.direction[i].green-entropy_xy1.direction[i].green)/
(entropy_x.direction[i].green > entropy_y.direction[i].green ?
entropy_x.direction[i].green : entropy_y.direction[i].green);
channel_features[BlueChannel].measure_of_correlation_1[i]=
(entropy_xy.direction[i].blue-entropy_xy1.direction[i].blue)/
(entropy_x.direction[i].blue > entropy_y.direction[i].blue ?
entropy_x.direction[i].blue : entropy_y.direction[i].blue);
if (image->colorspace == CMYKColorspace)
channel_features[IndexChannel].measure_of_correlation_1[i]=
(entropy_xy.direction[i].index-entropy_xy1.direction[i].index)/
(entropy_x.direction[i].index > entropy_y.direction[i].index ?
entropy_x.direction[i].index : entropy_y.direction[i].index);
if (image->matte != MagickFalse)
channel_features[OpacityChannel].measure_of_correlation_1[i]=
(entropy_xy.direction[i].opacity-entropy_xy1.direction[i].opacity)/
(entropy_x.direction[i].opacity > entropy_y.direction[i].opacity ?
entropy_x.direction[i].opacity : entropy_y.direction[i].opacity);
channel_features[RedChannel].measure_of_correlation_2[i]=
(sqrt(fabs(1.0-exp(-2.0*(entropy_xy2.direction[i].red-
entropy_xy.direction[i].red)))));
channel_features[GreenChannel].measure_of_correlation_2[i]=
(sqrt(fabs(1.0-exp(-2.0*(entropy_xy2.direction[i].green-
entropy_xy.direction[i].green)))));
channel_features[BlueChannel].measure_of_correlation_2[i]=
(sqrt(fabs(1.0-exp(-2.0*(entropy_xy2.direction[i].blue-
entropy_xy.direction[i].blue)))));
if (image->colorspace == CMYKColorspace)
channel_features[IndexChannel].measure_of_correlation_2[i]=
(sqrt(fabs(1.0-exp(-2.0*(entropy_xy2.direction[i].index-
entropy_xy.direction[i].index)))));
if (image->matte != MagickFalse)
channel_features[OpacityChannel].measure_of_correlation_2[i]=
(sqrt(fabs(1.0-exp(-2.0*(entropy_xy2.direction[i].opacity-
entropy_xy.direction[i].opacity)))));
}
/*
Compute more texture features.
*/
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static,4) shared(status) \
magick_threads(image,image,number_grays,1)
#endif
for (i=0; i < 4; i++)
{
register ssize_t
z;
for (z=0; z < (ssize_t) number_grays; z++)
{
register ssize_t
y;
ChannelStatistics
pixel;
(void) ResetMagickMemory(&pixel,0,sizeof(pixel));
for (y=0; y < (ssize_t) number_grays; y++)
{
register ssize_t
x;
for (x=0; x < (ssize_t) number_grays; x++)
{
/*
Contrast: amount of local variations present in an image.
*/
if (((y-x) == z) || ((x-y) == z))
{
pixel.direction[i].red+=cooccurrence[x][y].direction[i].red;
pixel.direction[i].green+=cooccurrence[x][y].direction[i].green;
pixel.direction[i].blue+=cooccurrence[x][y].direction[i].blue;
if (image->colorspace == CMYKColorspace)
pixel.direction[i].index+=cooccurrence[x][y].direction[i].index;
if (image->matte != MagickFalse)
pixel.direction[i].opacity+=
cooccurrence[x][y].direction[i].opacity;
}
/*
Maximum Correlation Coefficient.
*/
Q[z][y].direction[i].red+=cooccurrence[z][x].direction[i].red*
cooccurrence[y][x].direction[i].red/density_x[z].direction[i].red/
density_y[x].direction[i].red;
Q[z][y].direction[i].green+=cooccurrence[z][x].direction[i].green*
cooccurrence[y][x].direction[i].green/
density_x[z].direction[i].green/density_y[x].direction[i].red;
Q[z][y].direction[i].blue+=cooccurrence[z][x].direction[i].blue*
cooccurrence[y][x].direction[i].blue/density_x[z].direction[i].blue/
density_y[x].direction[i].blue;
if (image->colorspace == CMYKColorspace)
Q[z][y].direction[i].index+=cooccurrence[z][x].direction[i].index*
cooccurrence[y][x].direction[i].index/
density_x[z].direction[i].index/density_y[x].direction[i].index;
if (image->matte != MagickFalse)
Q[z][y].direction[i].opacity+=
cooccurrence[z][x].direction[i].opacity*
cooccurrence[y][x].direction[i].opacity/
density_x[z].direction[i].opacity/
density_y[x].direction[i].opacity;
}
}
channel_features[RedChannel].contrast[i]+=z*z*pixel.direction[i].red;
channel_features[GreenChannel].contrast[i]+=z*z*pixel.direction[i].green;
channel_features[BlueChannel].contrast[i]+=z*z*pixel.direction[i].blue;
if (image->colorspace == CMYKColorspace)
channel_features[BlackChannel].contrast[i]+=z*z*
pixel.direction[i].index;
if (image->matte != MagickFalse)
channel_features[OpacityChannel].contrast[i]+=z*z*
pixel.direction[i].opacity;
}
/*
Maximum Correlation Coefficient.
Future: return second largest eigenvalue of Q.
*/
channel_features[RedChannel].maximum_correlation_coefficient[i]=
sqrt((double) -1.0);
channel_features[GreenChannel].maximum_correlation_coefficient[i]=
sqrt((double) -1.0);
channel_features[BlueChannel].maximum_correlation_coefficient[i]=
sqrt((double) -1.0);
if (image->colorspace == CMYKColorspace)
channel_features[IndexChannel].maximum_correlation_coefficient[i]=
sqrt((double) -1.0);
if (image->matte != MagickFalse)
channel_features[OpacityChannel].maximum_correlation_coefficient[i]=
sqrt((double) -1.0);
}
/*
Relinquish resources.
*/
sum=(ChannelStatistics *) RelinquishMagickMemory(sum);
for (i=0; i < (ssize_t) number_grays; i++)
Q[i]=(ChannelStatistics *) RelinquishMagickMemory(Q[i]);
Q=(ChannelStatistics **) RelinquishMagickMemory(Q);
density_y=(ChannelStatistics *) RelinquishMagickMemory(density_y);
density_xy=(ChannelStatistics *) RelinquishMagickMemory(density_xy);
density_x=(ChannelStatistics *) RelinquishMagickMemory(density_x);
for (i=0; i < (ssize_t) number_grays; i++)
cooccurrence[i]=(ChannelStatistics *)
RelinquishMagickMemory(cooccurrence[i]);
cooccurrence=(ChannelStatistics **) RelinquishMagickMemory(cooccurrence);
return(channel_features);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% H o u g h L i n e I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% Use HoughLineImage() in conjunction with any binary edge extracted image (we
% recommand Canny) to identify lines in the image. The algorithm accumulates
% counts for every white pixel for every possible orientation (for angles from
% 0 to 179 in 1 degree increments) and distance from the center of the image to
% the corner (in 1 px increments) and stores the counts in an accumulator matrix
% of angle vs distance. The size of the accumulator is 180x(diagonal/2). Next
% it searches this space for peaks in counts and converts the locations of the
% peaks to slope and intercept in the normal x,y input image space. Use the
% slope/intercepts to find the endpoints clipped to the bounds of the image. The
% lines are then drawn. The counts are a measure of the length of the lines
%
% The format of the HoughLineImage method is:
%
% Image *HoughLineImage(const Image *image,const size_t width,
% const size_t height,const size_t threshold,ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o width, height: find line pairs as local maxima in this neighborhood.
%
% o threshold: the line count threshold.
%
% o exception: return any errors or warnings in this structure.
%
*/
static inline double MagickRound(double x)
{
/*
Round the fraction to nearest integer.
*/
if ((x-floor(x)) < (ceil(x)-x))
return(floor(x));
return(ceil(x));
}
MagickExport Image *HoughLineImage(const Image *image,const size_t width,
const size_t height,const size_t threshold,ExceptionInfo *exception)
{
#define HoughLineImageTag "HoughLine/Image"
CacheView
*image_view;
char
message[MaxTextExtent],
path[MaxTextExtent];
const char
*artifact;
double
hough_height;
Image
*lines_image = NULL;
ImageInfo
*image_info;
int
file;
MagickBooleanType
status;
MagickOffsetType
progress;
MatrixInfo
*accumulator;
PointInfo
center;
register ssize_t
y;
size_t
accumulator_height,
accumulator_width,
line_count;
/*
Create the accumulator.
*/
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);
accumulator_width=180;
hough_height=((sqrt(2.0)*(double) (image->rows > image->columns ?
image->rows : image->columns))/2.0);
accumulator_height=(size_t) (2.0*hough_height);
accumulator=AcquireMatrixInfo(accumulator_width,accumulator_height,
sizeof(double),exception);
if (accumulator == (MatrixInfo *) NULL)
ThrowImageException(ResourceLimitError,"MemoryAllocationFailed");
if (NullMatrix(accumulator) == MagickFalse)
{
accumulator=DestroyMatrixInfo(accumulator);
ThrowImageException(ResourceLimitError,"MemoryAllocationFailed");
}
/*
Populate the accumulator.
*/
status=MagickTrue;
progress=0;
center.x=(double) image->columns/2.0;
center.y=(double) image->rows/2.0;
image_view=AcquireVirtualCacheView(image,exception);
for (y=0; y < (ssize_t) image->rows; y++)
{
register const PixelPacket
*restrict p;
register ssize_t
x;
if (status == MagickFalse)
continue;
p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1,exception);
if (p == (PixelPacket *) NULL)
{
status=MagickFalse;
continue;
}
for (x=0; x < (ssize_t) image->columns; x++)
{
if (GetPixelIntensity(image,p) > (QuantumRange/2))
{
register ssize_t
i;
for (i=0; i < 180; i++)
{
double
count,
radius;
radius=(((double) x-center.x)*cos(DegreesToRadians((double) i)))+
(((double) y-center.y)*sin(DegreesToRadians((double) i)));
(void) GetMatrixElement(accumulator,i,(ssize_t)
MagickRound(radius+hough_height),&count);
count++;
(void) SetMatrixElement(accumulator,i,(ssize_t)
MagickRound(radius+hough_height),&count);
}
}
p++;
}
if (image->progress_monitor != (MagickProgressMonitor) NULL)
{
MagickBooleanType
proceed;
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp critical (MagickCore_HoughLineImage)
#endif
proceed=SetImageProgress(image,HoughLineImageTag,progress++,
image->rows);
if (proceed == MagickFalse)
status=MagickFalse;
}
}
image_view=DestroyCacheView(image_view);
if (status == MagickFalse)
{
accumulator=DestroyMatrixInfo(accumulator);
return((Image *) NULL);
}
/*
Generate line segments from accumulator.
*/
file=AcquireUniqueFileResource(path);
if (file == -1)
{
accumulator=DestroyMatrixInfo(accumulator);
return((Image *) NULL);
}
(void) FormatLocaleString(message,MaxTextExtent,
"# Hough line transform: %.20gx%.20g%+.20g\n",(double) width,
(double) height,(double) threshold);
if (write(file,message,strlen(message)) != (ssize_t) strlen(message))
status=MagickFalse;
(void) FormatLocaleString(message,MaxTextExtent,"viewbox 0 0 %.20g %.20g\n",
(double) image->columns,(double) image->rows);
if (write(file,message,strlen(message)) != (ssize_t) strlen(message))
status=MagickFalse;
line_count=image->columns > image->rows ? image->columns/4 : image->rows/4;
if (threshold != 0)
line_count=threshold;
for (y=0; y < (ssize_t) accumulator_height; y++)
{
register ssize_t
x;
for (x=0; x < (ssize_t) accumulator_width; x++)
{
double
count;
(void) GetMatrixElement(accumulator,x,y,&count);
if (count >= (double) line_count)
{
double
maxima;
SegmentInfo
line;
ssize_t
v;
/*
Is point a local maxima?
*/
maxima=count;
for (v=(-((ssize_t) height/2)); v <= (((ssize_t) height/2)); v++)
{
ssize_t
u;
for (u=(-((ssize_t) width/2)); u <= (((ssize_t) width/2)); u++)
{
if ((u != 0) || (v !=0))
{
(void) GetMatrixElement(accumulator,x+u,y+v,&count);
if (count > maxima)
{
maxima=count;
break;
}
}
}
if (u < (ssize_t) (width/2))
break;
}
(void) GetMatrixElement(accumulator,x,y,&count);
if (maxima > count)
continue;
if ((x >= 45) && (x <= 135))
{
/*
y = (r-x cos(t))/sin(t)
*/
line.x1=0.0;
line.y1=((double) (y-(accumulator_height/2.0))-((line.x1-
(image->columns/2.0))*cos(DegreesToRadians((double) x))))/
sin(DegreesToRadians((double) x))+(image->rows/2.0);
line.x2=(double) image->columns;
line.y2=((double) (y-(accumulator_height/2.0))-((line.x2-
(image->columns/2.0))*cos(DegreesToRadians((double) x))))/
sin(DegreesToRadians((double) x))+(image->rows/2.0);
}
else
{
/*
x = (r-y cos(t))/sin(t)
*/
line.y1=0.0;
line.x1=((double) (y-(accumulator_height/2.0))-((line.y1-
(image->rows/2.0))*sin(DegreesToRadians((double) x))))/
cos(DegreesToRadians((double) x))+(image->columns/2.0);
line.y2=(double) image->rows;
line.x2=((double) (y-(accumulator_height/2.0))-((line.y2-
(image->rows/2.0))*sin(DegreesToRadians((double) x))))/
cos(DegreesToRadians((double) x))+(image->columns/2.0);
}
(void) FormatLocaleString(message,MaxTextExtent,
"line %g,%g %g,%g # %g\n",line.x1,line.y1,line.x2,line.y2,maxima);
if (write(file,message,strlen(message)) != (ssize_t) strlen(message))
status=MagickFalse;
}
}
}
(void) close(file);
/*
Render lines to image canvas.
*/
image_info=AcquireImageInfo();
image_info->background_color=image->background_color;
(void) FormatLocaleString(image_info->filename,MaxTextExtent,"mvg:%s",path);
artifact=GetImageArtifact(image,"background");
if (artifact != (const char *) NULL)
(void) SetImageOption(image_info,"background",artifact);
artifact=GetImageArtifact(image,"fill");
if (artifact != (const char *) NULL)
(void) SetImageOption(image_info,"fill",artifact);
artifact=GetImageArtifact(image,"stroke");
if (artifact != (const char *) NULL)
(void) SetImageOption(image_info,"stroke",artifact);
artifact=GetImageArtifact(image,"strokewidth");
if (artifact != (const char *) NULL)
(void) SetImageOption(image_info,"strokewidth",artifact);
lines_image=ReadImage(image_info,exception);
artifact=GetImageArtifact(image,"hough-lines:accumulator");
if ((lines_image != (Image *) NULL) &&
(IsMagickTrue(artifact) != MagickFalse))
{
Image
*accumulator_image;
accumulator_image=MatrixToImage(accumulator,exception);
if (accumulator_image != (Image *) NULL)
AppendImageToList(&lines_image,accumulator_image);
}
/*
Free resources.
*/
accumulator=DestroyMatrixInfo(accumulator);
image_info=DestroyImageInfo(image_info);
(void) RelinquishUniqueFileResource(path);
return(GetFirstImageInList(lines_image));
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% M e a n S h i f t I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% MeanShiftImage() delineate arbitrarily shaped clusters in the image. For
% each pixel, it visits all the pixels in the neighborhood specified by
% the window centered at the pixel and excludes those that are outside the
% radius=(window-1)/2 surrounding the pixel. From those pixels, it finds those
% that are within the specified color distance from the current mean, and
% computes a new x,y centroid from those coordinates and a new mean. This new
% x,y centroid is used as the center for a new window. This process iterates
% until it converges and the final mean is replaces the (original window
% center) pixel value. It repeats this process for the next pixel, etc.,
% until it processes all pixels in the image. Results are typically better with
% colorspaces other than sRGB. We recommend YIQ, YUV or YCbCr.
%
% The format of the MeanShiftImage method is:
%
% Image *MeanShiftImage(const Image *image,const size_t width,
% const size_t height,const double color_distance,
% ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o width, height: find pixels in this neighborhood.
%
% o color_distance: the color distance.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport Image *MeanShiftImage(const Image *image,const size_t width,
const size_t height,const double color_distance,ExceptionInfo *exception)
{
#define MaxMeanShiftIterations 100
#define MeanShiftImageTag "MeanShift/Image"
CacheView
*image_view,
*mean_view,
*pixel_view;
Image
*mean_image;
MagickBooleanType
status;
MagickOffsetType
progress;
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);
mean_image=CloneImage(image,image->columns,image->rows,MagickTrue,exception);
if (mean_image == (Image *) NULL)
return((Image *) NULL);
if (SetImageStorageClass(mean_image,DirectClass) == MagickFalse)
{
InheritException(exception,&mean_image->exception);
mean_image=DestroyImage(mean_image);
return((Image *) NULL);
}
status=MagickTrue;
progress=0;
image_view=AcquireVirtualCacheView(image,exception);
pixel_view=AcquireVirtualCacheView(image,exception);
mean_view=AcquireAuthenticCacheView(mean_image,exception);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static,4) shared(status,progress) \
magick_threads(mean_image,mean_image,mean_image->rows,1)
#endif
for (y=0; y < (ssize_t) mean_image->rows; y++)
{
register const IndexPacket
*restrict indexes;
register const PixelPacket
*restrict p;
register PixelPacket
*restrict q;
register ssize_t
x;
if (status == MagickFalse)
continue;
p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1,exception);
q=GetCacheViewAuthenticPixels(mean_view,0,y,mean_image->columns,1,
exception);
if ((p == (const PixelPacket *) NULL) || (q == (PixelPacket *) NULL))
{
status=MagickFalse;
continue;
}
indexes=GetCacheViewVirtualIndexQueue(image_view);
for (x=0; x < (ssize_t) mean_image->columns; x++)
{
MagickPixelPacket
mean_pixel,
previous_pixel;
PointInfo
mean_location,
previous_location;
register ssize_t
i;
GetMagickPixelPacket(image,&mean_pixel);
SetMagickPixelPacket(image,p,indexes+x,&mean_pixel);
mean_location.x=(double) x;
mean_location.y=(double) y;
for (i=0; i < MaxMeanShiftIterations; i++)
{
double
distance,
gamma;
MagickPixelPacket
sum_pixel;
PointInfo
sum_location;
ssize_t
count,
v;
sum_location.x=0.0;
sum_location.y=0.0;
GetMagickPixelPacket(image,&sum_pixel);
previous_location=mean_location;
previous_pixel=mean_pixel;
count=0;
for (v=(-((ssize_t) height/2)); v <= (((ssize_t) height/2)); v++)
{
ssize_t
u;
for (u=(-((ssize_t) width/2)); u <= (((ssize_t) width/2)); u++)
{
if ((v*v+u*u) <= (ssize_t) ((width/2)*(height/2)))
{
PixelPacket
pixel;
status=GetOneCacheViewVirtualPixel(pixel_view,(ssize_t)
MagickRound(mean_location.x+u),(ssize_t) MagickRound(
mean_location.y+v),&pixel,exception);
distance=(mean_pixel.red-pixel.red)*(mean_pixel.red-pixel.red)+
(mean_pixel.green-pixel.green)*(mean_pixel.green-pixel.green)+
(mean_pixel.blue-pixel.blue)*(mean_pixel.blue-pixel.blue);
if (distance <= (color_distance*color_distance))
{
sum_location.x+=mean_location.x+u;
sum_location.y+=mean_location.y+v;
sum_pixel.red+=pixel.red;
sum_pixel.green+=pixel.green;
sum_pixel.blue+=pixel.blue;
sum_pixel.opacity+=pixel.opacity;
count++;
}
}
}
}
gamma=1.0/count;
mean_location.x=gamma*sum_location.x;
mean_location.y=gamma*sum_location.y;
mean_pixel.red=gamma*sum_pixel.red;
mean_pixel.green=gamma*sum_pixel.green;
mean_pixel.blue=gamma*sum_pixel.blue;
mean_pixel.opacity=gamma*sum_pixel.opacity;
distance=(mean_location.x-previous_location.x)*
(mean_location.x-previous_location.x)+
(mean_location.y-previous_location.y)*
(mean_location.y-previous_location.y)+
255.0*QuantumScale*(mean_pixel.red-previous_pixel.red)*
255.0*QuantumScale*(mean_pixel.red-previous_pixel.red)+
255.0*QuantumScale*(mean_pixel.green-previous_pixel.green)*
255.0*QuantumScale*(mean_pixel.green-previous_pixel.green)+
255.0*QuantumScale*(mean_pixel.blue-previous_pixel.blue)*
255.0*QuantumScale*(mean_pixel.blue-previous_pixel.blue);
if (distance <= 3.0)
break;
}
q->red=ClampToQuantum(mean_pixel.red);
q->green=ClampToQuantum(mean_pixel.green);
q->blue=ClampToQuantum(mean_pixel.blue);
q->opacity=ClampToQuantum(mean_pixel.opacity);
p++;
q++;
}
if (SyncCacheViewAuthenticPixels(mean_view,exception) == MagickFalse)
status=MagickFalse;
if (image->progress_monitor != (MagickProgressMonitor) NULL)
{
MagickBooleanType
proceed;
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp critical (MagickCore_MeanShiftImage)
#endif
proceed=SetImageProgress(image,MeanShiftImageTag,progress++,
image->rows);
if (proceed == MagickFalse)
status=MagickFalse;
}
}
mean_view=DestroyCacheView(mean_view);
pixel_view=DestroyCacheView(pixel_view);
image_view=DestroyCacheView(image_view);
return(mean_image);
}
|
visualize.c | /*****************************************************************************
* x264: h264 encoder
*****************************************************************************
* Copyright (C) 2005 Tuukka Toivonen <tuukkat@ee.oulu.fi>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* 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
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02111, USA.
*****************************************************************************/
/*
* Some explanation of the symbols used:
* Red/pink: intra block
* Blue: inter block
* Green: skip block
* Yellow: B-block (not visualized properly yet)
*
* Motion vectors have black dot at their target (ie. at the MB center),
* instead of arrowhead. The black dot is enclosed in filled diamond with radius
* depending on reference frame number (one frame back = zero width, normal case).
*
* The intra blocks have generally lines drawn perpendicular
* to the prediction direction, so for example, if there is a pink block
* with horizontal line at the top of it, it is interpolated by assuming
* luma to be vertically constant.
* DC predicted blocks have both horizontal and vertical lines,
* pink blocks with a diagonal line are predicted using the planar function.
*/
#include "common.h"
#include "visualize.h"
#include "display.h"
#include <omp.h>
typedef struct {
int i_type;
int i_partition;
int i_sub_partition[4];
int i_intra16x16_pred_mode;
int intra4x4_pred_mode[4][4];
int8_t ref[2][4][4]; /* [list][y][x] */
int16_t mv[2][4][4][2]; /* [list][y][x][mvxy] */
} visualize_t;
/* {{{ [fold] char *get_string(const stringlist_t *sl, int entries, int code) */
/* Return string from stringlist corresponding to the given code */
#define GET_STRING(sl, code) get_string((sl), sizeof(sl)/sizeof(*(sl)), code)
typedef struct {
int code;
char *string;
} stringlist_t;
static char *get_string(const stringlist_t *sl, int entries, int code)
{
int i;
for (i=0; i<entries; i++) {
if (sl[i].code==code) break;
}
return (i>=entries) ? "?" : sl[i].string;
}
/* }}} */
/* {{{ [fold] void mv(int x0, int y0, int16_t dmv[2], int ref, int zoom, char *col) */
/* Plot motion vector */
static void mv(int x0, int y0, int16_t dmv[2], int ref, int zoom, char *col)
{
int dx = dmv[0];
int dy = dmv[1];
int i;
dx = (dx * zoom + 2) >> 2; /* Quarter pixel accurate MVs */
dy = (dy * zoom + 2) >> 2;
disp_line(0, x0, y0, x0+dx, y0+dy);
for (i=1; i<ref; i++){
disp_line(0, x0, y0-i, x0+i, y0);
disp_line(0, x0+i, y0, x0, y0+i);
disp_line(0, x0, y0+i, x0-i, y0);
disp_line(0, x0-i, y0, x0, y0-i);
}
disp_setcolor("black");
disp_point(0, x0, y0);
disp_setcolor(col);
}
/* }}} */
/* {{{ [fold] void x264_visualize_init( x264_t *h ) */
void x264_visualize_init( x264_t *h )
{
int mb = h->sps->i_mb_width * h->sps->i_mb_height;
h->visualize = x264_malloc(mb * sizeof(visualize_t));
}
/* }}} */
/* {{{ [fold] void x264_visualize_mb( x264_t *h ) */
void x264_visualize_mb( x264_t *h )
{
visualize_t *v = (visualize_t*)h->visualize + h->mb.i_mb_xy;
int i, l, x, y;
/* Save all data for the MB what we need for drawing the visualization */
v->i_type = h->mb.i_type;
v->i_partition = h->mb.i_partition;
for (i=0; i<4; i++) v->i_sub_partition[i] = h->mb.i_sub_partition[i];
for (y=0; y<4; y++) for (x=0; x<4; x++)
v->intra4x4_pred_mode[y][x] = h->mb.cache.intra4x4_pred_mode[X264_SCAN8_0+y*8+x];
for (l=0; l<2; l++) for (y=0; y<4; y++) for (x=0; x<4; x++) {
for (i=0; i<2; i++) {
v->mv[l][y][x][i] = h->mb.cache.mv[l][X264_SCAN8_0+y*8+x][i];
}
v->ref[l][y][x] = h->mb.cache.ref[l][X264_SCAN8_0+y*8+x];
}
v->i_intra16x16_pred_mode = h->mb.i_intra16x16_pred_mode;
}
/* }}} */
/* {{{ [fold] void x264_visualize_close( x264_t *h ) */
void x264_visualize_close( x264_t *h )
{
x264_free(h->visualize);
}
/* }}} */
/* {{{ [fold] void x264_visualize_show( x264_t *h ) */
/* Display visualization (block types, MVs) of the encoded frame */
/* FIXME: B-type MBs not handled yet properly */
void x264_visualize_show( x264_t *h )
{
int mb_xy;
static const stringlist_t mb_types[] = {
/* Block types marked as NULL will not be drawn */
{ I_4x4 , "red" },
{ I_8x8 , "#ff5640" },
{ I_16x16 , "#ff8060" },
{ I_PCM , "violet" },
{ P_L0 , "SlateBlue" },
{ P_8x8 , "blue" },
{ P_SKIP , "green" },
{ B_DIRECT, "yellow" },
{ B_L0_L0 , "yellow" },
{ B_L0_L1 , "yellow" },
{ B_L0_BI , "yellow" },
{ B_L1_L0 , "yellow" },
{ B_L1_L1 , "yellow" },
{ B_L1_BI , "yellow" },
{ B_BI_L0 , "yellow" },
{ B_BI_L1 , "yellow" },
{ B_BI_BI , "yellow" },
{ B_8x8 , "yellow" },
{ B_SKIP , "yellow" },
};
static const int waitkey = 1; /* Wait for enter after each frame */
static const int drawbox = 1; /* Draw box around each block */
static const int borders = 0; /* Display extrapolated borders outside frame */
static const int zoom = 2; /* Zoom factor */
static const int pad = 32;
uint8_t *const frame = h->fdec->plane[0];
const int width = h->param.i_width;
const int height = h->param.i_height;
const int stride = h->fdec->i_stride[0];
if (borders) {
disp_gray_zoom(0, frame - pad*stride - pad, width+2*pad, height+2*pad, stride, "fdec", zoom);
} else {
disp_gray_zoom(0, frame, width, height, stride, "fdec", zoom);
}
#pragma omp parallel for
for( mb_xy = 0; mb_xy < h->sps->i_mb_width * h->sps->i_mb_height; mb_xy++ )
{
visualize_t *const v = (visualize_t*)h->visualize + mb_xy;
const int mb_y = mb_xy / h->sps->i_mb_width;
const int mb_x = mb_xy % h->sps->i_mb_width;
char *const col = GET_STRING(mb_types, v->i_type);
int x = mb_x*16*zoom;
int y = mb_y*16*zoom;
int l = 0;
unsigned int i, j;
if (col==NULL) continue;
if (borders) {
x += pad*zoom;
y += pad*zoom;
}
disp_setcolor(col);
if (drawbox) disp_rect(0, x, y, x+16*zoom-1, y+16*zoom-1);
if (v->i_type==P_L0 || v->i_type==P_8x8 || v->i_type==P_SKIP) {
/* Predicted (inter) mode, with motion vector */
if (v->i_partition==D_16x16 || v->i_type==P_SKIP) {
mv(x+8*zoom, y+8*zoom, v->mv[l][0][0], v->ref[l][0][0], zoom, col);
}
if (v->i_partition==D_16x8) {
if (drawbox) disp_rect(0, x, y, x+16*zoom, y+8*zoom);
mv(x+8*zoom, y+4*zoom, v->mv[l][0][0], v->ref[l][0][0], zoom, col);
if (drawbox) disp_rect(0, x, y+8*zoom, x+16*zoom, y+16*zoom);
mv(x+8*zoom, y+12*zoom, v->mv[l][2][0], v->ref[l][2][0], zoom, col);
}
if (v->i_partition==D_8x16) {
if (drawbox) disp_rect(0, x, y, x+8*zoom, y+16*zoom);
mv(x+4*zoom, y+8*zoom, v->mv[l][0][0], v->ref[l][0][0], zoom, col);
if (drawbox) disp_rect(0, x+8*zoom, y, x+16*zoom, y+16*zoom);
mv(x+12*zoom, y+8*zoom, v->mv[l][0][2], v->ref[l][0][2], zoom, col);
}
if (v->i_partition==D_8x8) {
for (i=0; i<2; i++) for (j=0; j<2; j++) {
int sp = v->i_sub_partition[i*2+j];
const int x0 = x + j*8*zoom;
const int y0 = y + i*8*zoom;
l = x264_mb_partition_listX_table[0][sp] ? 0 : 1; /* FIXME: not tested if this works */
if (IS_SUB8x8(sp)) {
if (drawbox) disp_rect(0, x0, y0, x0+8*zoom, y0+8*zoom);
mv(x0+4*zoom, y0+4*zoom, v->mv[l][2*i][2*j], v->ref[l][2*i][2*j], zoom, col);
}
if (IS_SUB8x4(sp)) {
if (drawbox) disp_rect(0, x0, y0, x0+8*zoom, y0+4*zoom);
if (drawbox) disp_rect(0, x0, y0+4*zoom, x0+8*zoom, y0+8*zoom);
mv(x0+4*zoom, y0+2*zoom, v->mv[l][2*i][2*j], v->ref[l][2*i][2*j], zoom, col);
mv(x0+4*zoom, y0+6*zoom, v->mv[l][2*i+1][2*j], v->ref[l][2*i+1][2*j], zoom, col);
}
if (IS_SUB4x8(sp)) {
if (drawbox) disp_rect(0, x0, y0, x0+4*zoom, y0+8*zoom);
if (drawbox) disp_rect(0, x0+4*zoom, y0, x0+8*zoom, y0+8*zoom);
mv(x0+2*zoom, y0+4*zoom, v->mv[l][2*i][2*j], v->ref[l][2*i][2*j], zoom, col);
mv(x0+6*zoom, y0+4*zoom, v->mv[l][2*i][2*j+1], v->ref[l][2*i][2*j+1], zoom, col);
}
if (IS_SUB4x4(sp)) {
if (drawbox) disp_rect(0, x0, y0, x0+4*zoom, y0+4*zoom);
if (drawbox) disp_rect(0, x0+4*zoom, y0, x0+8*zoom, y0+4*zoom);
if (drawbox) disp_rect(0, x0, y0+4*zoom, x0+4*zoom, y0+8*zoom);
if (drawbox) disp_rect(0, x0+4*zoom, y0+4*zoom, x0+8*zoom, y0+8*zoom);
mv(x0+2*zoom, y0+2*zoom, v->mv[l][2*i][2*j], v->ref[l][2*i][2*j], zoom, col);
mv(x0+6*zoom, y0+2*zoom, v->mv[l][2*i][2*j+1], v->ref[l][2*i][2*j+1], zoom, col);
mv(x0+2*zoom, y0+6*zoom, v->mv[l][2*i+1][2*j], v->ref[l][2*i+1][2*j], zoom, col);
mv(x0+6*zoom, y0+6*zoom, v->mv[l][2*i+1][2*j+1], v->ref[l][2*i+1][2*j+1], zoom, col);
}
}
}
}
if (IS_INTRA(v->i_type) || v->i_type==I_PCM) {
/* Intra coded */
if (v->i_type==I_16x16) {
switch (v->i_intra16x16_pred_mode) {
case I_PRED_16x16_V:
disp_line(0, x+2*zoom, y+2*zoom, x+14*zoom, y+2*zoom);
break;
case I_PRED_16x16_H:
disp_line(0, x+2*zoom, y+2*zoom, x+2*zoom, y+14*zoom);
break;
case I_PRED_16x16_DC:
case I_PRED_16x16_DC_LEFT:
case I_PRED_16x16_DC_TOP:
case I_PRED_16x16_DC_128:
disp_line(0, x+2*zoom, y+2*zoom, x+14*zoom, y+2*zoom);
disp_line(0, x+2*zoom, y+2*zoom, x+2*zoom, y+14*zoom);
break;
case I_PRED_16x16_P:
disp_line(0, x+2*zoom, y+2*zoom, x+8*zoom, y+8*zoom);
break;
}
}
if (v->i_type==I_4x4 || v->i_type==I_8x8) {
const int di = v->i_type==I_8x8 ? 2 : 1;
const int zoom2 = zoom * di;
for (i=0; i<4; i+=di) for (j=0; j<4; j+=di) {
const int x0 = x + j*4*zoom;
const int y0 = y + i*4*zoom;
if (drawbox) disp_rect(0, x0, y0, x0+4*zoom2, y0+4*zoom2);
switch (v->intra4x4_pred_mode[i][j]) {
case I_PRED_4x4_V: /* Vertical */
disp_line(0, x0+0*zoom2, y0+1*zoom2, x0+4*zoom2, y0+1*zoom2);
break;
case I_PRED_4x4_H: /* Horizontal */
disp_line(0, x0+1*zoom2, y0+0*zoom2, x0+1*zoom2, y0+4*zoom2);
break;
case I_PRED_4x4_DC: /* DC, average from top and left sides */
case I_PRED_4x4_DC_LEFT:
case I_PRED_4x4_DC_TOP:
case I_PRED_4x4_DC_128:
disp_line(0, x0+1*zoom2, y0+1*zoom2, x0+4*zoom2, y0+1*zoom2);
disp_line(0, x0+1*zoom2, y0+1*zoom2, x0+1*zoom2, y0+4*zoom2);
break;
case I_PRED_4x4_DDL: /* Topright-bottomleft */
disp_line(0, x0+0*zoom2, y0+0*zoom2, x0+4*zoom2, y0+4*zoom2);
break;
case I_PRED_4x4_DDR: /* Topleft-bottomright */
disp_line(0, x0+0*zoom2, y0+4*zoom2, x0+4*zoom2, y0+0*zoom2);
break;
case I_PRED_4x4_VR: /* Mix of topleft-bottomright and vertical */
disp_line(0, x0+0*zoom2, y0+2*zoom2, x0+4*zoom2, y0+1*zoom2);
break;
case I_PRED_4x4_HD: /* Mix of topleft-bottomright and horizontal */
disp_line(0, x0+2*zoom2, y0+0*zoom2, x0+1*zoom2, y0+4*zoom2);
break;
case I_PRED_4x4_VL: /* Mix of topright-bottomleft and vertical */
disp_line(0, x0+0*zoom2, y0+1*zoom2, x0+4*zoom2, y0+2*zoom2);
break;
case I_PRED_4x4_HU: /* Mix of topright-bottomleft and horizontal */
disp_line(0, x0+1*zoom2, y0+0*zoom2, x0+2*zoom2, y0+4*zoom2);
break;
}
}
}
}
}
disp_sync();
if (waitkey) getchar();
}
/* }}} */
//EOF
|
resize.c | /*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% RRRR EEEEE SSSSS IIIII ZZZZZ EEEEE %
% R R E SS I ZZ E %
% RRRR EEE SSS I ZZZ EEE %
% R R E SS I ZZ E %
% R R EEEEE SSSSS IIIII ZZZZZ EEEEE %
% %
% %
% MagickCore Image Resize Methods %
% %
% Software Design %
% Cristy %
% July 1992 %
% %
% %
% Copyright 1999-2019 ImageMagick Studio LLC, a non-profit organization %
% dedicated to making software imaging solutions freely available. %
% %
% You may not use this file except in compliance with the License. You may %
% obtain a copy of the License at %
% %
% https://imagemagick.org/script/license.php %
% %
% Unless required by applicable law or agreed to in writing, software %
% distributed under the License is distributed on an "AS IS" BASIS, %
% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. %
% See the License for the specific language governing permissions and %
% limitations under the License. %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
%
*/
/*
Include declarations.
*/
#include "magick/studio.h"
#include "magick/accelerate-private.h"
#include "magick/artifact.h"
#include "magick/blob.h"
#include "magick/cache.h"
#include "magick/cache-view.h"
#include "magick/channel.h"
#include "magick/color.h"
#include "magick/color-private.h"
#include "magick/draw.h"
#include "magick/exception.h"
#include "magick/exception-private.h"
#include "magick/gem.h"
#include "magick/image.h"
#include "magick/image-private.h"
#include "magick/list.h"
#include "magick/memory_.h"
#include "magick/memory-private.h"
#include "magick/magick.h"
#include "magick/pixel-private.h"
#include "magick/property.h"
#include "magick/monitor.h"
#include "magick/monitor-private.h"
#include "magick/nt-base-private.h"
#include "magick/pixel.h"
#include "magick/pixel-private.h"
#include "magick/option.h"
#include "magick/resample.h"
#include "magick/resample-private.h"
#include "magick/resize.h"
#include "magick/resize-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/utility.h"
#include "magick/version.h"
#if defined(MAGICKCORE_LQR_DELEGATE)
#include <lqr.h>
#endif
/*
Typedef declarations.
*/
struct _ResizeFilter
{
MagickRealType
(*filter)(const MagickRealType,const ResizeFilter *),
(*window)(const MagickRealType,const ResizeFilter *),
support, /* filter region of support - the filter support limit */
window_support, /* window support, usally equal to support (expert only) */
scale, /* dimension scaling to fit window support (usally 1.0) */
blur, /* x-scale (blur-sharpen) */
coefficient[7]; /* cubic coefficents for BC-cubic filters */
ResizeWeightingFunctionType
filterWeightingType,
windowWeightingType;
size_t
signature;
};
/*
Forward declaractions.
*/
static MagickRealType
I0(MagickRealType x),
BesselOrderOne(MagickRealType),
Sinc(const MagickRealType, const ResizeFilter *),
SincFast(const MagickRealType, const ResizeFilter *);
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
+ F i l t e r F u n c t i o n s %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% These are the various filter and windowing functions that are provided.
%
% They are internal to this module only. See AcquireResizeFilterInfo() for
% details of the access to these functions, via the GetResizeFilterSupport()
% and GetResizeFilterWeight() API interface.
%
% The individual filter functions have this format...
%
% static MagickRealtype *FilterName(const MagickRealType x,
% const MagickRealType support)
%
% A description of each parameter follows:
%
% o x: the distance from the sampling point generally in the range of 0 to
% support. The GetResizeFilterWeight() ensures this a positive value.
%
% o resize_filter: current filter information. This allows function to
% access support, and possibly other pre-calculated information defining
% the functions.
%
*/
static MagickRealType Blackman(const MagickRealType x,
const ResizeFilter *magick_unused(resize_filter))
{
/*
Blackman: 2nd order cosine windowing function:
0.42 + 0.5 cos(pi x) + 0.08 cos(2pi x)
Refactored by Chantal Racette and Nicolas Robidoux to one trig call and
five flops.
*/
const MagickRealType cosine=cos((double) (MagickPI*x));
magick_unreferenced(resize_filter);
return(0.34+cosine*(0.5+cosine*0.16));
}
static MagickRealType Bohman(const MagickRealType x,
const ResizeFilter *magick_unused(resize_filter))
{
/*
Bohman: 2rd Order cosine windowing function:
(1-x) cos(pi x) + sin(pi x) / pi.
Refactored by Nicolas Robidoux to one trig call, one sqrt call, and 7 flops,
taking advantage of the fact that the support of Bohman is 1.0 (so that we
know that sin(pi x) >= 0).
*/
const double cosine=cos((double) (MagickPI*x));
const double sine=sqrt(1.0-cosine*cosine);
magick_unreferenced(resize_filter);
return((MagickRealType) ((1.0-x)*cosine+(1.0/MagickPI)*sine));
}
static MagickRealType Box(const MagickRealType magick_unused(x),
const ResizeFilter *magick_unused(resize_filter))
{
/*
A Box filter is a equal weighting function (all weights equal).
DO NOT LIMIT results by support or resize point sampling will work
as it requests points beyond its normal 0.0 support size.
*/
magick_unreferenced(x);
magick_unreferenced(resize_filter);
return(1.0);
}
static MagickRealType Cosine(const MagickRealType x,
const ResizeFilter *magick_unused(resize_filter))
{
/*
Cosine window function:
cos((pi/2)*x).
*/
magick_unreferenced(resize_filter);
return((MagickRealType)cos((double) (MagickPI2*x)));
}
static MagickRealType CubicBC(const MagickRealType x,
const ResizeFilter *resize_filter)
{
/*
Cubic Filters using B,C determined values:
Mitchell-Netravali B = 1/3 C = 1/3 "Balanced" cubic spline filter
Catmull-Rom B = 0 C = 1/2 Interpolatory and exact on linears
Spline B = 1 C = 0 B-Spline Gaussian approximation
Hermite B = 0 C = 0 B-Spline interpolator
See paper by Mitchell and Netravali, Reconstruction Filters in Computer
Graphics Computer Graphics, Volume 22, Number 4, August 1988
http://www.cs.utexas.edu/users/fussell/courses/cs384g/lectures/mitchell/
Mitchell.pdf.
Coefficents are determined from B,C values:
P0 = ( 6 - 2*B )/6 = coeff[0]
P1 = 0
P2 = (-18 +12*B + 6*C )/6 = coeff[1]
P3 = ( 12 - 9*B - 6*C )/6 = coeff[2]
Q0 = ( 8*B +24*C )/6 = coeff[3]
Q1 = ( -12*B -48*C )/6 = coeff[4]
Q2 = ( 6*B +30*C )/6 = coeff[5]
Q3 = ( - 1*B - 6*C )/6 = coeff[6]
which are used to define the filter:
P0 + P1*x + P2*x^2 + P3*x^3 0 <= x < 1
Q0 + Q1*x + Q2*x^2 + Q3*x^3 1 <= x < 2
which ensures function is continuous in value and derivative (slope).
*/
if (x < 1.0)
return(resize_filter->coefficient[0]+x*(x*
(resize_filter->coefficient[1]+x*resize_filter->coefficient[2])));
if (x < 2.0)
return(resize_filter->coefficient[3]+x*(resize_filter->coefficient[4]+x*
(resize_filter->coefficient[5]+x*resize_filter->coefficient[6])));
return(0.0);
}
static MagickRealType Gaussian(const MagickRealType x,
const ResizeFilter *resize_filter)
{
/*
Gaussian with a sigma = 1/2 (or as user specified)
Gaussian Formula (1D) ...
exp( -(x^2)/((2.0*sigma^2) ) / (sqrt(2*PI)*sigma^2))
Gaussian Formula (2D) ...
exp( -(x^2+y^2)/(2.0*sigma^2) ) / (PI*sigma^2) )
or for radius
exp( -(r^2)/(2.0*sigma^2) ) / (PI*sigma^2) )
Note that it is only a change from 1-d to radial form is in the
normalization multiplier which is not needed or used when Gaussian is used
as a filter.
The constants are pre-calculated...
coeff[0]=sigma;
coeff[1]=1.0/(2.0*sigma^2);
coeff[2]=1.0/(sqrt(2*PI)*sigma^2);
exp( -coeff[1]*(x^2)) ) * coeff[2];
However the multiplier coeff[1] is need, the others are informative only.
This separates the gaussian 'sigma' value from the 'blur/support'
settings allowing for its use in special 'small sigma' gaussians,
without the filter 'missing' pixels because the support becomes too
small.
*/
return(exp((double)(-resize_filter->coefficient[1]*x*x)));
}
static MagickRealType Hanning(const MagickRealType x,
const ResizeFilter *magick_unused(resize_filter))
{
/*
Cosine window function:
0.5+0.5*cos(pi*x).
*/
const MagickRealType cosine=cos((double) (MagickPI*x));
magick_unreferenced(resize_filter);
return(0.5+0.5*cosine);
}
static MagickRealType Hamming(const MagickRealType x,
const ResizeFilter *magick_unused(resize_filter))
{
/*
Offset cosine window function:
.54 + .46 cos(pi x).
*/
const MagickRealType cosine=cos((double) (MagickPI*x));
magick_unreferenced(resize_filter);
return(0.54+0.46*cosine);
}
static MagickRealType Jinc(const MagickRealType x,
const ResizeFilter *magick_unused(resize_filter))
{
/*
See Pratt "Digital Image Processing" p.97 for Jinc/Bessel functions.
http://mathworld.wolfram.com/JincFunction.html and page 11 of
http://www.ph.ed.ac.uk/%7ewjh/teaching/mo/slides/lens/lens.pdf
The original "zoom" program by Paul Heckbert called this "Bessel". But
really it is more accurately named "Jinc".
*/
magick_unreferenced(resize_filter);
if (x == 0.0)
return((MagickRealType) (0.5*MagickPI));
return(BesselOrderOne((MagickRealType) MagickPI*x)/x);
}
static MagickRealType Kaiser(const MagickRealType x,
const ResizeFilter *resize_filter)
{
/*
Kaiser Windowing Function (bessel windowing)
I0( beta * sqrt( 1-x^2) ) / IO(0)
Beta (coeff[0]) is a free value from 5 to 8 (defaults to 6.5).
However it is typically defined in terms of Alpha*PI
The normalization factor (coeff[1]) is not actually needed,
but without it the filters has a large value at x=0 making it
difficult to compare the function with other windowing functions.
*/
return(resize_filter->coefficient[1]*I0(resize_filter->coefficient[0]*
sqrt((double) (1.0-x*x))));
}
static MagickRealType Lagrange(const MagickRealType x,
const ResizeFilter *resize_filter)
{
MagickRealType
value;
register ssize_t
i;
ssize_t
n,
order;
/*
Lagrange piecewise polynomial fit of sinc: N is the 'order' of the lagrange
function and depends on the overall support window size of the filter. That
is: for a support of 2, it gives a lagrange-4 (piecewise cubic function).
"n" identifies the piece of the piecewise polynomial.
See Survey: Interpolation Methods, IEEE Transactions on Medical Imaging,
Vol 18, No 11, November 1999, p1049-1075, -- Equation 27 on p1064.
*/
if (x > resize_filter->support)
return(0.0);
order=(ssize_t) (2.0*resize_filter->window_support); /* number of pieces */
n=(ssize_t) (resize_filter->window_support+x);
value=1.0f;
for (i=0; i < order; i++)
if (i != n)
value*=(n-i-x)/(n-i);
return(value);
}
static MagickRealType Quadratic(const MagickRealType x,
const ResizeFilter *magick_unused(resize_filter))
{
/*
2rd order (quadratic) B-Spline approximation of Gaussian.
*/
magick_unreferenced(resize_filter);
if (x < 0.5)
return(0.75-x*x);
if (x < 1.5)
return(0.5*(x-1.5)*(x-1.5));
return(0.0);
}
static MagickRealType Sinc(const MagickRealType x,
const ResizeFilter *magick_unused(resize_filter))
{
/*
Scaled sinc(x) function using a trig call:
sinc(x) == sin(pi x)/(pi x).
*/
magick_unreferenced(resize_filter);
if (x != 0.0)
{
const MagickRealType alpha=(MagickRealType) (MagickPI*x);
return(sin((double) alpha)/alpha);
}
return((MagickRealType) 1.0);
}
static MagickRealType SincFast(const MagickRealType x,
const ResizeFilter *magick_unused(resize_filter))
{
/*
Approximations of the sinc function sin(pi x)/(pi x) over the interval
[-4,4] constructed by Nicolas Robidoux and Chantal Racette with funding
from the Natural Sciences and Engineering Research Council of Canada.
Although the approximations are polynomials (for low order of
approximation) and quotients of polynomials (for higher order of
approximation) and consequently are similar in form to Taylor polynomials /
Pade approximants, the approximations are computed with a completely
different technique.
Summary: These approximations are "the best" in terms of bang (accuracy)
for the buck (flops). More specifically: Among the polynomial quotients
that can be computed using a fixed number of flops (with a given "+ - * /
budget"), the chosen polynomial quotient is the one closest to the
approximated function with respect to maximum absolute relative error over
the given interval.
The Remez algorithm, as implemented in the boost library's minimax package,
is the key to the construction: http://www.boost.org/doc/libs/1_36_0/libs/
math/doc/sf_and_dist/html/math_toolkit/backgrounders/remez.html
If outside of the interval of approximation, use the standard trig formula.
*/
magick_unreferenced(resize_filter);
if (x > 4.0)
{
const MagickRealType alpha=(MagickRealType) (MagickPI*x);
return(sin((double) alpha)/alpha);
}
{
/*
The approximations only depend on x^2 (sinc is an even function).
*/
const MagickRealType xx = x*x;
#if MAGICKCORE_QUANTUM_DEPTH <= 8
/*
Maximum absolute relative error 6.3e-6 < 1/2^17.
*/
const double c0 = 0.173610016489197553621906385078711564924e-2L;
const double c1 = -0.384186115075660162081071290162149315834e-3L;
const double c2 = 0.393684603287860108352720146121813443561e-4L;
const double c3 = -0.248947210682259168029030370205389323899e-5L;
const double c4 = 0.107791837839662283066379987646635416692e-6L;
const double c5 = -0.324874073895735800961260474028013982211e-8L;
const double c6 = 0.628155216606695311524920882748052490116e-10L;
const double c7 = -0.586110644039348333520104379959307242711e-12L;
const double p =
c0+xx*(c1+xx*(c2+xx*(c3+xx*(c4+xx*(c5+xx*(c6+xx*c7))))));
return((xx-1.0)*(xx-4.0)*(xx-9.0)*(xx-16.0)*p);
#elif MAGICKCORE_QUANTUM_DEPTH <= 16
/*
Max. abs. rel. error 2.2e-8 < 1/2^25.
*/
const double c0 = 0.173611107357320220183368594093166520811e-2L;
const double c1 = -0.384240921114946632192116762889211361285e-3L;
const double c2 = 0.394201182359318128221229891724947048771e-4L;
const double c3 = -0.250963301609117217660068889165550534856e-5L;
const double c4 = 0.111902032818095784414237782071368805120e-6L;
const double c5 = -0.372895101408779549368465614321137048875e-8L;
const double c6 = 0.957694196677572570319816780188718518330e-10L;
const double c7 = -0.187208577776590710853865174371617338991e-11L;
const double c8 = 0.253524321426864752676094495396308636823e-13L;
const double c9 = -0.177084805010701112639035485248501049364e-15L;
const double p =
c0+xx*(c1+xx*(c2+xx*(c3+xx*(c4+xx*(c5+xx*(c6+xx*(c7+xx*(c8+xx*c9))))))));
return((xx-1.0)*(xx-4.0)*(xx-9.0)*(xx-16.0)*p);
#else
/*
Max. abs. rel. error 1.2e-12 < 1/2^39.
*/
const double c0 = 0.173611111110910715186413700076827593074e-2L;
const double c1 = -0.289105544717893415815859968653611245425e-3L;
const double c2 = 0.206952161241815727624413291940849294025e-4L;
const double c3 = -0.834446180169727178193268528095341741698e-6L;
const double c4 = 0.207010104171026718629622453275917944941e-7L;
const double c5 = -0.319724784938507108101517564300855542655e-9L;
const double c6 = 0.288101675249103266147006509214934493930e-11L;
const double c7 = -0.118218971804934245819960233886876537953e-13L;
const double p =
c0+xx*(c1+xx*(c2+xx*(c3+xx*(c4+xx*(c5+xx*(c6+xx*c7))))));
const double d0 = 1.0L;
const double d1 = 0.547981619622284827495856984100563583948e-1L;
const double d2 = 0.134226268835357312626304688047086921806e-2L;
const double d3 = 0.178994697503371051002463656833597608689e-4L;
const double d4 = 0.114633394140438168641246022557689759090e-6L;
const double q = d0+xx*(d1+xx*(d2+xx*(d3+xx*d4)));
return((MagickRealType) ((xx-1.0)*(xx-4.0)*(xx-9.0)*(xx-16.0)/q*p));
#endif
}
}
static MagickRealType Triangle(const MagickRealType x,
const ResizeFilter *magick_unused(resize_filter))
{
/*
1st order (linear) B-Spline, bilinear interpolation, Tent 1D filter, or
a Bartlett 2D Cone filter. Also used as a Bartlett Windowing function
for Sinc().
*/
magick_unreferenced(resize_filter);
if (x < 1.0)
return(1.0-x);
return(0.0);
}
static MagickRealType Welsh(const MagickRealType x,
const ResizeFilter *magick_unused(resize_filter))
{
/*
Welsh parabolic windowing filter.
*/
magick_unreferenced(resize_filter);
if (x < 1.0)
return(1.0-x*x);
return(0.0);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
+ A c q u i r e R e s i z e F i l t e r %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% AcquireResizeFilter() allocates the ResizeFilter structure. Choose from
% these filters:
%
% FIR (Finite impulse Response) Filters
% Box Triangle Quadratic
% Spline Hermite Catrom
% Mitchell
%
% IIR (Infinite impulse Response) Filters
% Gaussian Sinc Jinc (Bessel)
%
% Windowed Sinc/Jinc Filters
% Blackman Bohman Lanczos
% Hann Hamming Cosine
% Kaiser Welch Parzen
% Bartlett
%
% Special Purpose Filters
% Cubic SincFast LanczosSharp Lanczos2 Lanczos2Sharp
% Robidoux RobidouxSharp
%
% The users "-filter" selection is used to lookup the default 'expert'
% settings for that filter from a internal table. However any provided
% 'expert' settings (see below) may override this selection.
%
% FIR filters are used as is, and are limited to that filters support window
% (unless over-ridden). 'Gaussian' while classed as an IIR filter, is also
% simply clipped by its support size (currently 1.5 or approximately 3*sigma
% as recommended by many references)
%
% The special a 'cylindrical' filter flag will promote the default 4-lobed
% Windowed Sinc filter to a 3-lobed Windowed Jinc equivalent, which is better
% suited to this style of image resampling. This typically happens when using
% such a filter for images distortions.
%
% SPECIFIC FILTERS:
%
% Directly requesting 'Sinc', 'Jinc' function as a filter will force the use
% of function without any windowing, or promotion for cylindrical usage. This
% is not recommended, except by image processing experts, especially as part
% of expert option filter function selection.
%
% Two forms of the 'Sinc' function are available: Sinc and SincFast. Sinc is
% computed using the traditional sin(pi*x)/(pi*x); it is selected if the user
% specifically specifies the use of a Sinc filter. SincFast uses highly
% accurate (and fast) polynomial (low Q) and rational (high Q) approximations,
% and will be used by default in most cases.
%
% The Lanczos filter is a special 3-lobed Sinc-windowed Sinc filter (promoted
% to Jinc-windowed Jinc for cylindrical (Elliptical Weighted Average) use).
% The Sinc version is the most popular windowed filter.
%
% LanczosSharp is a slightly sharpened (blur=0.9812505644269356 < 1) form of
% the Lanczos filter, specifically designed for EWA distortion (as a
% Jinc-Jinc); it can also be used as a slightly sharper orthogonal Lanczos
% (Sinc-Sinc) filter. The chosen blur value comes as close as possible to
% satisfying the following condition without changing the character of the
% corresponding EWA filter:
%
% 'No-Op' Vertical and Horizontal Line Preservation Condition: Images with
% only vertical or horizontal features are preserved when performing 'no-op"
% with EWA distortion.
%
% The Lanczos2 and Lanczos2Sharp filters are 2-lobe versions of the Lanczos
% filters. The 'sharp' version uses a blur factor of 0.9549963639785485,
% again chosen because the resulting EWA filter comes as close as possible to
% satisfying the above condition.
%
% Robidoux is another filter tuned for EWA. It is the Keys cubic filter
% defined by B=(228 - 108 sqrt(2))/199. Robidoux satisfies the "'No-Op'
% Vertical and Horizontal Line Preservation Condition" exactly, and it
% moderately blurs high frequency 'pixel-hash' patterns under no-op. It turns
% out to be close to both Mitchell and Lanczos2Sharp. For example, its first
% crossing is at (36 sqrt(2) + 123)/(72 sqrt(2) + 47), almost the same as the
% first crossing of Mitchell and Lanczos2Sharp.
%
% RodidouxSharp is a slightly sharper version of Rodidoux, some believe it
% is too sharp. It is designed to minimize the maximum possible change in
% a pixel value which is at one of the extremes (e.g., 0 or 255) under no-op
% conditions. Amazingly Mitchell falls roughly between Rodidoux and
% RodidouxSharp, though this seems to have been pure coincidence.
%
% 'EXPERT' OPTIONS:
%
% These artifact "defines" are not recommended for production use without
% expert knowledge of resampling, filtering, and the effects they have on the
% resulting resampled (resized or distorted) image.
%
% They can be used to override any and all filter default, and it is
% recommended you make good use of "filter:verbose" to make sure that the
% overall effect of your selection (before and after) is as expected.
%
% "filter:verbose" controls whether to output the exact results of the
% filter selections made, as well as plotting data for graphing the
% resulting filter over the filters support range.
%
% "filter:filter" select the main function associated with this filter
% name, as the weighting function of the filter. This can be used to
% set a windowing function as a weighting function, for special
% purposes, such as graphing.
%
% If a "filter:window" operation has not been provided, a 'Box'
% windowing function will be set to denote that no windowing function is
% being used.
%
% "filter:window" Select this windowing function for the filter. While any
% filter could be used as a windowing function, using the 'first lobe' of
% that filter over the whole support window, using a non-windowing
% function is not advisible. If no weighting filter function is specified
% a 'SincFast' filter is used.
%
% "filter:lobes" Number of lobes to use for the Sinc/Jinc filter. This a
% simpler method of setting filter support size that will correctly
% handle the Sinc/Jinc switch for an operators filtering requirements.
% Only integers should be given.
%
% "filter:support" Set the support size for filtering to the size given.
% This not recommended for Sinc/Jinc windowed filters (lobes should be
% used instead). This will override any 'filter:lobes' option.
%
% "filter:win-support" Scale windowing function to this size instead. This
% causes the windowing (or self-windowing Lagrange filter) to act is if
% the support window it much much larger than what is actually supplied
% to the calling operator. The filter however is still clipped to the
% real support size given, by the support range supplied to the caller.
% If unset this will equal the normal filter support size.
%
% "filter:blur" Scale the filter and support window by this amount. A value
% of > 1 will generally result in a more blurred image with more ringing
% effects, while a value <1 will sharpen the resulting image with more
% aliasing effects.
%
% "filter:sigma" The sigma value to use for the Gaussian filter only.
% Defaults to '1/2'. Using a different sigma effectively provides a
% method of using the filter as a 'blur' convolution. Particularly when
% using it for Distort.
%
% "filter:b"
% "filter:c" Override the preset B,C values for a Cubic filter.
% If only one of these are given it is assumes to be a 'Keys' type of
% filter such that B+2C=1, where Keys 'alpha' value = C.
%
% Examples:
%
% Set a true un-windowed Sinc filter with 10 lobes (very slow):
% -define filter:filter=Sinc
% -define filter:lobes=8
%
% Set an 8 lobe Lanczos (Sinc or Jinc) filter:
% -filter Lanczos
% -define filter:lobes=8
%
% The format of the AcquireResizeFilter method is:
%
% ResizeFilter *AcquireResizeFilter(const Image *image,
% const FilterTypes filter_type,const MagickBooleanType cylindrical,
% ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o filter: the filter type, defining a preset filter, window and support.
% The artifact settings listed above will override those selections.
%
% o blur: blur the filter by this amount, use 1.0 if unknown. Image
% artifact "filter:blur" will override this API call usage, including any
% internal change (such as for cylindrical usage).
%
% o radial: use a 1D orthogonal filter (Sinc) or 2D cylindrical (radial)
% filter (Jinc).
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport ResizeFilter *AcquireResizeFilter(const Image *image,
const FilterTypes filter,const MagickRealType blur,
const MagickBooleanType cylindrical,ExceptionInfo *exception)
{
const char
*artifact;
FilterTypes
filter_type,
window_type;
MagickRealType
B,
C,
value;
register ResizeFilter
*resize_filter;
/*
Table Mapping given Filter, into Weighting and Windowing functions.
A 'Box' windowing function means its a simble non-windowed filter.
An 'SincFast' filter function could be upgraded to a 'Jinc' filter if a
"cylindrical" is requested, unless a 'Sinc' or 'SincFast' filter was
specifically requested by the user.
WARNING: The order of this table must match the order of the FilterTypes
enumeration specified in "resample.h", or the filter names will not match
the filter being setup.
You can check filter setups with the "filter:verbose" expert setting.
*/
static struct
{
FilterTypes
filter,
window;
} const mapping[SentinelFilter] =
{
{ UndefinedFilter, BoxFilter }, /* Undefined (default to Box) */
{ PointFilter, BoxFilter }, /* SPECIAL: Nearest neighbour */
{ BoxFilter, BoxFilter }, /* Box averaging filter */
{ TriangleFilter, BoxFilter }, /* Linear interpolation filter */
{ HermiteFilter, BoxFilter }, /* Hermite interpolation filter */
{ SincFastFilter, HanningFilter }, /* Hanning -- cosine-sinc */
{ SincFastFilter, HammingFilter }, /* Hamming -- '' variation */
{ SincFastFilter, BlackmanFilter }, /* Blackman -- 2*cosine-sinc */
{ GaussianFilter, BoxFilter }, /* Gaussian blur filter */
{ QuadraticFilter, BoxFilter }, /* Quadratic Gaussian approx */
{ CubicFilter, BoxFilter }, /* General Cubic Filter, Spline */
{ CatromFilter, BoxFilter }, /* Cubic-Keys interpolator */
{ MitchellFilter, BoxFilter }, /* 'Ideal' Cubic-Keys filter */
{ JincFilter, BoxFilter }, /* Raw 3-lobed Jinc function */
{ SincFilter, BoxFilter }, /* Raw 4-lobed Sinc function */
{ SincFastFilter, BoxFilter }, /* Raw fast sinc ("Pade"-type) */
{ SincFastFilter, KaiserFilter }, /* Kaiser -- square root-sinc */
{ LanczosFilter, WelshFilter }, /* Welch -- parabolic (3 lobe) */
{ SincFastFilter, CubicFilter }, /* Parzen -- cubic-sinc */
{ SincFastFilter, BohmanFilter }, /* Bohman -- 2*cosine-sinc */
{ SincFastFilter, TriangleFilter }, /* Bartlett -- triangle-sinc */
{ LagrangeFilter, BoxFilter }, /* Lagrange self-windowing */
{ LanczosFilter, LanczosFilter }, /* Lanczos Sinc-Sinc filters */
{ LanczosSharpFilter, LanczosSharpFilter }, /* | these require */
{ Lanczos2Filter, Lanczos2Filter }, /* | special handling */
{ Lanczos2SharpFilter, Lanczos2SharpFilter },
{ RobidouxFilter, BoxFilter }, /* Cubic Keys tuned for EWA */
{ RobidouxSharpFilter, BoxFilter }, /* Sharper Cubic Keys for EWA */
{ LanczosFilter, CosineFilter }, /* Cosine window (3 lobes) */
{ SplineFilter, BoxFilter }, /* Spline Cubic Filter */
{ LanczosRadiusFilter, LanczosFilter }, /* Lanczos with integer radius */
};
/*
Table mapping the filter/window from the above table to an actual function.
The default support size for that filter as a weighting function, the range
to scale with to use that function as a sinc windowing function, (typ 1.0).
Note that the filter_type -> function is 1 to 1 except for Sinc(),
SincFast(), and CubicBC() functions, which may have multiple filter to
function associations.
See "filter:verbose" handling below for the function -> filter mapping.
*/
static struct
{
MagickRealType
(*function)(const MagickRealType,const ResizeFilter*);
double
support, /* Default lobes/support size of the weighting filter. */
scale, /* Support when function used as a windowing function
Typically equal to the location of the first zero crossing. */
B,C; /* BC-spline coefficients, ignored if not a CubicBC filter. */
ResizeWeightingFunctionType weightingFunctionType;
} const filters[SentinelFilter] =
{
/* .--- support window (if used as a Weighting Function)
| .--- first crossing (if used as a Windowing Function)
| | .--- B value for Cubic Function
| | | .---- C value for Cubic Function
| | | | */
{ Box, 0.5, 0.5, 0.0, 0.0, BoxWeightingFunction }, /* Undefined (default to Box) */
{ Box, 0.0, 0.5, 0.0, 0.0, BoxWeightingFunction }, /* Point (special handling) */
{ Box, 0.5, 0.5, 0.0, 0.0, BoxWeightingFunction }, /* Box */
{ Triangle, 1.0, 1.0, 0.0, 0.0, TriangleWeightingFunction }, /* Triangle */
{ CubicBC, 1.0, 1.0, 0.0, 0.0, CubicBCWeightingFunction }, /* Hermite (cubic B=C=0) */
{ Hanning, 1.0, 1.0, 0.0, 0.0, HanningWeightingFunction }, /* Hann, cosine window */
{ Hamming, 1.0, 1.0, 0.0, 0.0, HammingWeightingFunction }, /* Hamming, '' variation */
{ Blackman, 1.0, 1.0, 0.0, 0.0, BlackmanWeightingFunction }, /* Blackman, 2*cosine window */
{ Gaussian, 2.0, 1.5, 0.0, 0.0, GaussianWeightingFunction }, /* Gaussian */
{ Quadratic, 1.5, 1.5, 0.0, 0.0, QuadraticWeightingFunction },/* Quadratic gaussian */
{ CubicBC, 2.0, 2.0, 1.0, 0.0, CubicBCWeightingFunction }, /* General Cubic Filter */
{ CubicBC, 2.0, 1.0, 0.0, 0.5, CubicBCWeightingFunction }, /* Catmull-Rom (B=0,C=1/2) */
{ CubicBC, 2.0, 8.0/7.0, 1./3., 1./3., CubicBCWeightingFunction }, /* Mitchell (B=C=1/3) */
{ Jinc, 3.0, 1.2196698912665045, 0.0, 0.0, JincWeightingFunction }, /* Raw 3-lobed Jinc */
{ Sinc, 4.0, 1.0, 0.0, 0.0, SincWeightingFunction }, /* Raw 4-lobed Sinc */
{ SincFast, 4.0, 1.0, 0.0, 0.0, SincFastWeightingFunction }, /* Raw fast sinc ("Pade"-type) */
{ Kaiser, 1.0, 1.0, 0.0, 0.0, KaiserWeightingFunction }, /* Kaiser (square root window) */
{ Welsh, 1.0, 1.0, 0.0, 0.0, WelshWeightingFunction }, /* Welsh (parabolic window) */
{ CubicBC, 2.0, 2.0, 1.0, 0.0, CubicBCWeightingFunction }, /* Parzen (B-Spline window) */
{ Bohman, 1.0, 1.0, 0.0, 0.0, BohmanWeightingFunction }, /* Bohman, 2*Cosine window */
{ Triangle, 1.0, 1.0, 0.0, 0.0, TriangleWeightingFunction }, /* Bartlett (triangle window) */
{ Lagrange, 2.0, 1.0, 0.0, 0.0, LagrangeWeightingFunction }, /* Lagrange sinc approximation */
{ SincFast, 3.0, 1.0, 0.0, 0.0, SincFastWeightingFunction }, /* Lanczos, 3-lobed Sinc-Sinc */
{ SincFast, 3.0, 1.0, 0.0, 0.0, SincFastWeightingFunction }, /* Lanczos, Sharpened */
{ SincFast, 2.0, 1.0, 0.0, 0.0, SincFastWeightingFunction }, /* Lanczos, 2-lobed */
{ SincFast, 2.0, 1.0, 0.0, 0.0, SincFastWeightingFunction }, /* Lanczos2, sharpened */
/* Robidoux: Keys cubic close to Lanczos2D sharpened */
{ CubicBC, 2.0, 1.1685777620836932,
0.37821575509399867, 0.31089212245300067, CubicBCWeightingFunction },
/* RobidouxSharp: Sharper version of Robidoux */
{ CubicBC, 2.0, 1.105822933719019,
0.2620145123990142, 0.3689927438004929, CubicBCWeightingFunction },
{ Cosine, 1.0, 1.0, 0.0, 0.0, CosineWeightingFunction }, /* Low level cosine window */
{ CubicBC, 2.0, 2.0, 1.0, 0.0, CubicBCWeightingFunction }, /* Cubic B-Spline (B=1,C=0) */
{ SincFast, 3.0, 1.0, 0.0, 0.0, SincFastWeightingFunction }, /* Lanczos, Interger Radius */
};
/*
The known zero crossings of the Jinc() or more accurately the Jinc(x*PI)
function being used as a filter. It is used by the "filter:lobes" expert
setting and for 'lobes' for Jinc functions in the previous table. This way
users do not have to deal with the highly irrational lobe sizes of the Jinc
filter.
Values taken from
http://cose.math.bas.bg/webMathematica/webComputing/BesselZeros.jsp
using Jv-function with v=1, then dividing by PI.
*/
static double
jinc_zeros[16] =
{
1.2196698912665045,
2.2331305943815286,
3.2383154841662362,
4.2410628637960699,
5.2427643768701817,
6.2439216898644877,
7.2447598687199570,
8.2453949139520427,
9.2458926849494673,
10.246293348754916,
11.246622794877883,
12.246898461138105,
13.247132522181061,
14.247333735806849,
15.247508563037300,
16.247661874700962
};
/*
Allocate resize filter.
*/
assert(image != (const Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
assert(UndefinedFilter < filter && filter < SentinelFilter);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickCoreSignature);
(void) exception;
resize_filter=(ResizeFilter *) AcquireMagickMemory(sizeof(*resize_filter));
if (resize_filter == (ResizeFilter *) NULL)
ThrowFatalException(ResourceLimitFatalError,"MemoryAllocationFailed");
(void) memset(resize_filter,0,sizeof(*resize_filter));
/*
Defaults for the requested filter.
*/
filter_type=mapping[filter].filter;
window_type=mapping[filter].window;
resize_filter->blur = blur; /* function argument blur factor (1.0) */
/* Promote 1D Windowed Sinc Filters to a 2D Windowed Jinc filters */
if ((cylindrical != MagickFalse) && (filter_type == SincFastFilter) &&
(filter != SincFastFilter))
filter_type=JincFilter; /* 1D Windowed Sinc => 2D Windowed Jinc filters */
/* Expert filter setting override */
artifact=GetImageArtifact(image,"filter:filter");
if (artifact != (const char *) NULL)
{
ssize_t
option;
option=ParseCommandOption(MagickFilterOptions,MagickFalse,artifact);
if ((UndefinedFilter < option) && (option < SentinelFilter))
{ /* Raw filter request - no window function. */
filter_type=(FilterTypes) option;
window_type=BoxFilter;
}
/* Filter override with a specific window function. */
artifact=GetImageArtifact(image,"filter:window");
if (artifact != (const char *) NULL)
{
option=ParseCommandOption(MagickFilterOptions,MagickFalse,artifact);
if ((UndefinedFilter < option) && (option < SentinelFilter))
window_type=(FilterTypes) option;
}
}
else
{
/* Window specified, but no filter function? Assume Sinc/Jinc. */
artifact=GetImageArtifact(image,"filter:window");
if (artifact != (const char *) NULL)
{
ssize_t
option;
option=ParseCommandOption(MagickFilterOptions,MagickFalse,artifact);
if ((UndefinedFilter < option) && (option < SentinelFilter))
{
filter_type=cylindrical != MagickFalse ?
JincFilter : SincFastFilter;
window_type=(FilterTypes) option;
}
}
}
/* Assign the real functions to use for the filters selected. */
resize_filter->filter=filters[filter_type].function;
resize_filter->support=filters[filter_type].support;
resize_filter->filterWeightingType=filters[filter_type].weightingFunctionType;
resize_filter->window=filters[window_type].function;
resize_filter->windowWeightingType=filters[window_type].weightingFunctionType;
resize_filter->scale=filters[window_type].scale;
resize_filter->signature=MagickCoreSignature;
/* Filter Modifications for orthogonal/cylindrical usage */
if (cylindrical != MagickFalse)
switch (filter_type)
{
case BoxFilter:
/* Support for Cylindrical Box should be sqrt(2)/2 */
resize_filter->support=(MagickRealType) MagickSQ1_2;
break;
case LanczosFilter:
case LanczosSharpFilter:
case Lanczos2Filter:
case Lanczos2SharpFilter:
case LanczosRadiusFilter:
resize_filter->filter=filters[JincFilter].function;
resize_filter->window=filters[JincFilter].function;
resize_filter->scale=filters[JincFilter].scale;
/* number of lobes (support window size) remain unchanged */
break;
default:
break;
}
/* Global Sharpening (regardless of orthoginal/cylindrical) */
switch (filter_type)
{
case LanczosSharpFilter:
resize_filter->blur *= (MagickRealType) 0.9812505644269356;
break;
case Lanczos2SharpFilter:
resize_filter->blur *= (MagickRealType) 0.9549963639785485;
break;
/* case LanczosRadius: blur adjust is done after lobes */
default:
break;
}
/*
Expert Option Modifications.
*/
/* User Gaussian Sigma Override - no support change */
if ((resize_filter->filter == Gaussian) ||
(resize_filter->window == Gaussian) ) {
value=0.5; /* guassian sigma default, half pixel */
artifact=GetImageArtifact(image,"filter:sigma");
if (artifact != (const char *) NULL)
value=StringToDouble(artifact,(char **) NULL);
/* Define coefficents for Gaussian */
resize_filter->coefficient[0]=value; /* note sigma too */
resize_filter->coefficient[1]=PerceptibleReciprocal(2.0*value*value); /* sigma scaling */
resize_filter->coefficient[2]=PerceptibleReciprocal(Magick2PI*value*value);
/* normalization - not actually needed or used! */
if ( value > 0.5 )
resize_filter->support *= value/0.5; /* increase support */
}
/* User Kaiser Alpha Override - no support change */
if ((resize_filter->filter == Kaiser) ||
(resize_filter->window == Kaiser) ) {
value=6.5; /* default beta value for Kaiser bessel windowing function */
artifact=GetImageArtifact(image,"filter:alpha"); /* FUTURE: depreciate */
if (artifact != (const char *) NULL)
value=StringToDouble(artifact,(char **) NULL);
artifact=GetImageArtifact(image,"filter:kaiser-beta");
if (artifact != (const char *) NULL)
value=StringToDouble(artifact,(char **) NULL);
artifact=GetImageArtifact(image,"filter:kaiser-alpha");
if (artifact != (const char *) NULL)
value=(MagickRealType) (StringToDouble(artifact,(char **) NULL)*MagickPI);
/* Define coefficents for Kaiser Windowing Function */
resize_filter->coefficient[0]=value; /* alpha */
resize_filter->coefficient[1]=PerceptibleReciprocal(I0(value)); /* normalization */
}
/* Support Overrides */
artifact=GetImageArtifact(image,"filter:lobes");
if (artifact != (const char *) NULL)
{
ssize_t
lobes;
lobes=(ssize_t) StringToLong(artifact);
if (lobes < 1)
lobes=1;
resize_filter->support=(MagickRealType) lobes;
}
/* Convert a Jinc function lobes value to a real support value */
if (resize_filter->filter == Jinc)
{
if (resize_filter->support > 16)
resize_filter->support=jinc_zeros[15]; /* largest entry in table */
else
resize_filter->support=jinc_zeros[((long)resize_filter->support)-1];
/* blur this filter so support is a integer value (lobes dependant) */
if (filter_type == LanczosRadiusFilter)
{
resize_filter->blur *= floor(resize_filter->support)/
resize_filter->support;
}
}
/* Expert Blur Override */
artifact=GetImageArtifact(image,"filter:blur");
if (artifact != (const char *) NULL)
resize_filter->blur*=StringToDouble(artifact,(char **) NULL);
if (resize_filter->blur < MagickEpsilon)
resize_filter->blur=(MagickRealType) MagickEpsilon;
/* Expert override of the support setting */
artifact=GetImageArtifact(image,"filter:support");
if (artifact != (const char *) NULL)
resize_filter->support=fabs(StringToDouble(artifact,(char **) NULL));
/*
Scale windowing function separately to the support 'clipping'
window that calling operator is planning to actually use. (Expert
override)
*/
resize_filter->window_support=resize_filter->support; /* default */
artifact=GetImageArtifact(image,"filter:win-support");
if (artifact != (const char *) NULL)
resize_filter->window_support=fabs(StringToDouble(artifact,(char **) NULL));
/*
Adjust window function scaling to match windowing support for
weighting function. This avoids a division on every filter call.
*/
resize_filter->scale/=resize_filter->window_support;
/*
* Set Cubic Spline B,C values, calculate Cubic coefficients.
*/
B=0.0;
C=0.0;
if ((resize_filter->filter == CubicBC) ||
(resize_filter->window == CubicBC) )
{
B=filters[filter_type].B;
C=filters[filter_type].C;
if (filters[window_type].function == CubicBC)
{
B=filters[window_type].B;
C=filters[window_type].C;
}
artifact=GetImageArtifact(image,"filter:b");
if (artifact != (const char *) NULL)
{
B=StringToDouble(artifact,(char **) NULL);
C=(1.0-B)/2.0; /* Calculate C to get a Keys cubic filter. */
artifact=GetImageArtifact(image,"filter:c"); /* user C override */
if (artifact != (const char *) NULL)
C=StringToDouble(artifact,(char **) NULL);
}
else
{
artifact=GetImageArtifact(image,"filter:c");
if (artifact != (const char *) NULL)
{
C=StringToDouble(artifact,(char **) NULL);
B=1.0-2.0*C; /* Calculate B to get a Keys cubic filter. */
}
}
/* Convert B,C values into Cubic Coefficents. See CubicBC(). */
{
const double twoB = B+B;
resize_filter->coefficient[0]=1.0-(1.0/3.0)*B;
resize_filter->coefficient[1]=-3.0+twoB+C;
resize_filter->coefficient[2]=2.0-1.5*B-C;
resize_filter->coefficient[3]=(4.0/3.0)*B+4.0*C;
resize_filter->coefficient[4]=-8.0*C-twoB;
resize_filter->coefficient[5]=B+5.0*C;
resize_filter->coefficient[6]=(-1.0/6.0)*B-C;
}
}
/*
Expert Option Request for verbose details of the resulting filter.
*/
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp master
{
#endif
artifact=GetImageArtifact(image,"filter:verbose");
if (IsMagickTrue(artifact) != MagickFalse)
{
double
support,
x;
/*
Set the weighting function properly when the weighting
function may not exactly match the filter of the same name.
EG: a Point filter is really uses a Box weighting function
with a different support than is typically used.
*/
if (resize_filter->filter == Box) filter_type=BoxFilter;
if (resize_filter->filter == Sinc) filter_type=SincFilter;
if (resize_filter->filter == SincFast) filter_type=SincFastFilter;
if (resize_filter->filter == Jinc) filter_type=JincFilter;
if (resize_filter->filter == CubicBC) filter_type=CubicFilter;
if (resize_filter->window == Box) window_type=BoxFilter;
if (resize_filter->window == Sinc) window_type=SincFilter;
if (resize_filter->window == SincFast) window_type=SincFastFilter;
if (resize_filter->window == Jinc) window_type=JincFilter;
if (resize_filter->window == CubicBC) window_type=CubicFilter;
/*
Report Filter Details.
*/
support=GetResizeFilterSupport(resize_filter); /* practical_support */
(void) FormatLocaleFile(stdout,"# Resampling Filter (for graphing)\n#\n");
(void) FormatLocaleFile(stdout,"# filter = %s\n",
CommandOptionToMnemonic(MagickFilterOptions,filter_type));
(void) FormatLocaleFile(stdout,"# window = %s\n",
CommandOptionToMnemonic(MagickFilterOptions,window_type));
(void) FormatLocaleFile(stdout,"# support = %.*g\n",
GetMagickPrecision(),(double) resize_filter->support);
(void) FormatLocaleFile(stdout,"# window-support = %.*g\n",
GetMagickPrecision(),(double) resize_filter->window_support);
(void) FormatLocaleFile(stdout,"# scale-blur = %.*g\n",
GetMagickPrecision(), (double)resize_filter->blur);
if ( filter_type == GaussianFilter || window_type == GaussianFilter )
(void) FormatLocaleFile(stdout,"# gaussian-sigma = %.*g\n",
GetMagickPrecision(), (double)resize_filter->coefficient[0]);
if ( filter_type == KaiserFilter || window_type == KaiserFilter )
(void) FormatLocaleFile(stdout,"# kaiser-beta = %.*g\n",
GetMagickPrecision(),
(double)resize_filter->coefficient[0]);
(void) FormatLocaleFile(stdout,"# practical-support = %.*g\n",
GetMagickPrecision(), (double)support);
if ( filter_type == CubicFilter || window_type == CubicFilter )
(void) FormatLocaleFile(stdout,"# B,C = %.*g,%.*g\n",
GetMagickPrecision(),(double)B, GetMagickPrecision(),(double)C);
(void) FormatLocaleFile(stdout,"\n");
/*
Output values of resulting filter graph -- for graphing
filter result.
*/
for (x=0.0; x <= support; x+=0.01f)
(void) FormatLocaleFile(stdout,"%5.2lf\t%.*g\n",x,GetMagickPrecision(),
(double) GetResizeFilterWeight(resize_filter,x));
/* A final value so gnuplot can graph the 'stop' properly. */
(void) FormatLocaleFile(stdout,"%5.2lf\t%.*g\n",support,
GetMagickPrecision(),0.0);
}
/* Output the above once only for each image - remove setting */
(void) DeleteImageArtifact((Image *) image,"filter:verbose");
#if defined(MAGICKCORE_OPENMP_SUPPORT)
}
#endif
return(resize_filter);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% A d a p t i v e R e s i z e I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% AdaptiveResizeImage() adaptively resize image with pixel resampling.
%
% This is shortcut function for a fast interpolative resize using mesh
% interpolation. It works well for small resizes of less than +/- 50%
% of the original image size. For larger resizing on images a full
% filtered and slower resize function should be used instead.
%
% The format of the AdaptiveResizeImage method is:
%
% Image *AdaptiveResizeImage(const Image *image,const size_t columns,
% const size_t rows,ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o columns: the number of columns in the resized image.
%
% o rows: the number of rows in the resized image.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport Image *AdaptiveResizeImage(const Image *image,
const size_t columns,const size_t rows,ExceptionInfo *exception)
{
return(InterpolativeResizeImage(image,columns,rows,MeshInterpolatePixel,
exception));
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
+ B e s s e l O r d e r O n e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% BesselOrderOne() computes the Bessel function of x of the first kind of
% order 0. This is used to create the Jinc() filter function below.
%
% Reduce x to |x| since j1(x)= -j1(-x), and for x in (0,8]
%
% j1(x) = x*j1(x);
%
% For x in (8,inf)
%
% j1(x) = sqrt(2/(pi*x))*(p1(x)*cos(x1)-q1(x)*sin(x1))
%
% where x1 = x-3*pi/4. Compute sin(x1) and cos(x1) as follow:
%
% cos(x1) = cos(x)cos(3pi/4)+sin(x)sin(3pi/4)
% = 1/sqrt(2) * (sin(x) - cos(x))
% sin(x1) = sin(x)cos(3pi/4)-cos(x)sin(3pi/4)
% = -1/sqrt(2) * (sin(x) + cos(x))
%
% The format of the BesselOrderOne method is:
%
% MagickRealType BesselOrderOne(MagickRealType x)
%
% A description of each parameter follows:
%
% o x: MagickRealType value.
%
*/
#undef I0
static MagickRealType I0(MagickRealType x)
{
MagickRealType
sum,
t,
y;
register ssize_t
i;
/*
Zeroth order Bessel function of the first kind.
*/
sum=1.0;
y=x*x/4.0;
t=y;
for (i=2; t > MagickEpsilon; i++)
{
sum+=t;
t*=y/((MagickRealType) i*i);
}
return(sum);
}
#undef J1
static MagickRealType J1(MagickRealType x)
{
MagickRealType
p,
q;
register ssize_t
i;
static const double
Pone[] =
{
0.581199354001606143928050809e+21,
-0.6672106568924916298020941484e+20,
0.2316433580634002297931815435e+19,
-0.3588817569910106050743641413e+17,
0.2908795263834775409737601689e+15,
-0.1322983480332126453125473247e+13,
0.3413234182301700539091292655e+10,
-0.4695753530642995859767162166e+7,
0.270112271089232341485679099e+4
},
Qone[] =
{
0.11623987080032122878585294e+22,
0.1185770712190320999837113348e+20,
0.6092061398917521746105196863e+17,
0.2081661221307607351240184229e+15,
0.5243710262167649715406728642e+12,
0.1013863514358673989967045588e+10,
0.1501793594998585505921097578e+7,
0.1606931573481487801970916749e+4,
0.1e+1
};
p=Pone[8];
q=Qone[8];
for (i=7; i >= 0; i--)
{
p=p*x*x+Pone[i];
q=q*x*x+Qone[i];
}
return(p/q);
}
#undef P1
static MagickRealType P1(MagickRealType x)
{
MagickRealType
p,
q;
register ssize_t
i;
static const double
Pone[] =
{
0.352246649133679798341724373e+5,
0.62758845247161281269005675e+5,
0.313539631109159574238669888e+5,
0.49854832060594338434500455e+4,
0.2111529182853962382105718e+3,
0.12571716929145341558495e+1
},
Qone[] =
{
0.352246649133679798068390431e+5,
0.626943469593560511888833731e+5,
0.312404063819041039923015703e+5,
0.4930396490181088979386097e+4,
0.2030775189134759322293574e+3,
0.1e+1
};
p=Pone[5];
q=Qone[5];
for (i=4; i >= 0; i--)
{
p=p*(8.0/x)*(8.0/x)+Pone[i];
q=q*(8.0/x)*(8.0/x)+Qone[i];
}
return(p/q);
}
#undef Q1
static MagickRealType Q1(MagickRealType x)
{
MagickRealType
p,
q;
register ssize_t
i;
static const double
Pone[] =
{
0.3511751914303552822533318e+3,
0.7210391804904475039280863e+3,
0.4259873011654442389886993e+3,
0.831898957673850827325226e+2,
0.45681716295512267064405e+1,
0.3532840052740123642735e-1
},
Qone[] =
{
0.74917374171809127714519505e+4,
0.154141773392650970499848051e+5,
0.91522317015169922705904727e+4,
0.18111867005523513506724158e+4,
0.1038187585462133728776636e+3,
0.1e+1
};
p=Pone[5];
q=Qone[5];
for (i=4; i >= 0; i--)
{
p=p*(8.0/x)*(8.0/x)+Pone[i];
q=q*(8.0/x)*(8.0/x)+Qone[i];
}
return(p/q);
}
static MagickRealType BesselOrderOne(MagickRealType x)
{
MagickRealType
p,
q;
if (x == 0.0)
return(0.0);
p=x;
if (x < 0.0)
x=(-x);
if (x < 8.0)
return(p*J1(x));
q=sqrt((double) (2.0/(MagickPI*x)))*(P1(x)*(1.0/sqrt(2.0)*(sin((double) x)-
cos((double) x)))-8.0/x*Q1(x)*(-1.0/sqrt(2.0)*(sin((double) x)+
cos((double) x))));
if (p < 0.0)
q=(-q);
return(q);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
+ D e s t r o y R e s i z e F i l t e r %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% DestroyResizeFilter() destroy the resize filter.
%
% The format of the DestroyResizeFilter method is:
%
% ResizeFilter *DestroyResizeFilter(ResizeFilter *resize_filter)
%
% A description of each parameter follows:
%
% o resize_filter: the resize filter.
%
*/
MagickExport ResizeFilter *DestroyResizeFilter(ResizeFilter *resize_filter)
{
assert(resize_filter != (ResizeFilter *) NULL);
assert(resize_filter->signature == MagickCoreSignature);
resize_filter->signature=(~MagickCoreSignature);
resize_filter=(ResizeFilter *) RelinquishMagickMemory(resize_filter);
return(resize_filter);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
+ G e t R e s i z e F i l t e r S u p p o r t %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% GetResizeFilterSupport() return the current support window size for this
% filter. Note that this may have been enlarged by filter:blur factor.
%
% The format of the GetResizeFilterSupport method is:
%
% MagickRealType GetResizeFilterSupport(const ResizeFilter *resize_filter)
%
% A description of each parameter follows:
%
% o filter: Image filter to use.
%
*/
MagickExport MagickRealType *GetResizeFilterCoefficient(
const ResizeFilter *resize_filter)
{
assert(resize_filter != (ResizeFilter *) NULL);
assert(resize_filter->signature == MagickCoreSignature);
return((MagickRealType *) resize_filter->coefficient);
}
MagickExport MagickRealType GetResizeFilterBlur(
const ResizeFilter *resize_filter)
{
assert(resize_filter != (ResizeFilter *) NULL);
assert(resize_filter->signature == MagickCoreSignature);
return(resize_filter->blur);
}
MagickExport MagickRealType GetResizeFilterScale(
const ResizeFilter *resize_filter)
{
assert(resize_filter != (ResizeFilter *) NULL);
assert(resize_filter->signature == MagickCoreSignature);
return(resize_filter->scale);
}
MagickExport MagickRealType GetResizeFilterWindowSupport(
const ResizeFilter *resize_filter)
{
assert(resize_filter != (ResizeFilter *) NULL);
assert(resize_filter->signature == MagickCoreSignature);
return(resize_filter->window_support);
}
MagickExport ResizeWeightingFunctionType GetResizeFilterWeightingType(
const ResizeFilter *resize_filter)
{
assert(resize_filter != (ResizeFilter *) NULL);
assert(resize_filter->signature == MagickCoreSignature);
return(resize_filter->filterWeightingType);
}
MagickExport ResizeWeightingFunctionType GetResizeFilterWindowWeightingType(
const ResizeFilter *resize_filter)
{
assert(resize_filter != (ResizeFilter *) NULL);
assert(resize_filter->signature == MagickCoreSignature);
return(resize_filter->windowWeightingType);
}
MagickExport MagickRealType GetResizeFilterSupport(
const ResizeFilter *resize_filter)
{
assert(resize_filter != (ResizeFilter *) NULL);
assert(resize_filter->signature == MagickCoreSignature);
return(resize_filter->support*resize_filter->blur);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
+ G e t R e s i z e F i l t e r W e i g h t %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% GetResizeFilterWeight evaluates the specified resize filter at the point x
% which usally lies between zero and the filters current 'support' and
% returns the weight of the filter function at that point.
%
% The format of the GetResizeFilterWeight method is:
%
% MagickRealType GetResizeFilterWeight(const ResizeFilter *resize_filter,
% const MagickRealType x)
%
% A description of each parameter follows:
%
% o filter: the filter type.
%
% o x: the point.
%
*/
MagickExport MagickRealType GetResizeFilterWeight(
const ResizeFilter *resize_filter,const MagickRealType x)
{
MagickRealType
scale,
weight,
x_blur;
/*
Windowing function - scale the weighting filter by this amount.
*/
assert(resize_filter != (ResizeFilter *) NULL);
assert(resize_filter->signature == MagickCoreSignature);
x_blur=fabs((double) x)/resize_filter->blur; /* X offset with blur scaling */
if ((resize_filter->window_support < MagickEpsilon) ||
(resize_filter->window == Box))
scale=1.0; /* Point or Box Filter -- avoid division by zero */
else
{
scale=resize_filter->scale;
scale=resize_filter->window(x_blur*scale,resize_filter);
}
weight=scale*resize_filter->filter(x_blur,resize_filter);
return(weight);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% I n t e r p o l a t i v e R e s i z e I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% InterpolativeResizeImage() resizes an image using the specified
% interpolation method.
%
% The format of the InterpolativeResizeImage method is:
%
% Image *InterpolativeResizeImage(const Image *image,const size_t columns,
% const size_t rows,const InterpolatePixelMethod method,
% ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o columns: the number of columns in the resized image.
%
% o rows: the number of rows in the resized image.
%
% o method: the pixel interpolation method.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport Image *InterpolativeResizeImage(const Image *image,
const size_t columns,const size_t rows,const InterpolatePixelMethod method,
ExceptionInfo *exception)
{
#define InterpolativeResizeImageTag "Resize/Image"
CacheView
*image_view,
*resize_view;
Image
*resize_image;
MagickBooleanType
status;
MagickOffsetType
progress;
PointInfo
scale;
ssize_t
y;
/*
Interpolatively resize image.
*/
assert(image != (const Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickCoreSignature);
if ((columns == 0) || (rows == 0))
return((Image *) NULL);
if ((columns == image->columns) && (rows == image->rows))
return(CloneImage(image,0,0,MagickTrue,exception));
resize_image=CloneImage(image,columns,rows,MagickTrue,exception);
if (resize_image == (Image *) NULL)
return((Image *) NULL);
if (SetImageStorageClass(resize_image,DirectClass) == MagickFalse)
{
InheritException(exception,&resize_image->exception);
resize_image=DestroyImage(resize_image);
return((Image *) NULL);
}
status=MagickTrue;
progress=0;
image_view=AcquireVirtualCacheView(image,exception);
resize_view=AcquireAuthenticCacheView(resize_image,exception);
scale.x=(double) image->columns/resize_image->columns;
scale.y=(double) image->rows/resize_image->rows;
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static) shared(progress,status) \
magick_number_threads(image,resize_image,resize_image->rows,1)
#endif
for (y=0; y < (ssize_t) resize_image->rows; y++)
{
MagickPixelPacket
pixel;
PointInfo
offset;
register IndexPacket
*magick_restrict resize_indexes;
register PixelPacket
*magick_restrict q;
register ssize_t
x;
if (status == MagickFalse)
continue;
q=QueueCacheViewAuthenticPixels(resize_view,0,y,resize_image->columns,1,
exception);
if (q == (PixelPacket *) NULL)
continue;
resize_indexes=GetCacheViewAuthenticIndexQueue(resize_view);
GetMagickPixelPacket(image,&pixel);
offset.y=((MagickRealType) y+0.5)*scale.y-0.5;
for (x=0; x < (ssize_t) resize_image->columns; x++)
{
offset.x=((MagickRealType) x+0.5)*scale.x-0.5;
status=InterpolateMagickPixelPacket(image,image_view,method,offset.x,
offset.y,&pixel,exception);
if (status == MagickFalse)
break;
SetPixelPacket(resize_image,&pixel,q,resize_indexes+x);
q++;
}
if (SyncCacheViewAuthenticPixels(resize_view,exception) == MagickFalse)
continue;
if (image->progress_monitor != (MagickProgressMonitor) NULL)
{
MagickBooleanType
proceed;
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp atomic
#endif
progress++;
proceed=SetImageProgress(image,InterpolativeResizeImageTag,progress,
image->rows);
if (proceed == MagickFalse)
status=MagickFalse;
}
}
resize_view=DestroyCacheView(resize_view);
image_view=DestroyCacheView(image_view);
if (status == MagickFalse)
resize_image=DestroyImage(resize_image);
return(resize_image);
}
#if defined(MAGICKCORE_LQR_DELEGATE)
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% L i q u i d R e s c a l e I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% LiquidRescaleImage() rescales image with seam carving.
%
% The format of the LiquidRescaleImage method is:
%
% Image *LiquidRescaleImage(const Image *image,
% const size_t columns,const size_t rows,
% const double delta_x,const double rigidity,ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o columns: the number of columns in the rescaled image.
%
% o rows: the number of rows in the rescaled image.
%
% o delta_x: maximum seam transversal step (0 means straight seams).
%
% o rigidity: introduce a bias for non-straight seams (typically 0).
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport Image *LiquidRescaleImage(const Image *image,const size_t columns,
const size_t rows,const double delta_x,const double rigidity,
ExceptionInfo *exception)
{
#define LiquidRescaleImageTag "Rescale/Image"
CacheView
*rescale_view;
const char
*map;
guchar
*packet;
Image
*rescale_image;
int
x,
y;
LqrCarver
*carver;
LqrRetVal
lqr_status;
MagickBooleanType
status;
MagickPixelPacket
pixel;
MemoryInfo
*pixel_info;
unsigned char
*pixels;
/*
Liquid rescale image.
*/
assert(image != (const Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickCoreSignature);
if ((columns == 0) || (rows == 0))
return((Image *) NULL);
if ((columns == image->columns) && (rows == image->rows))
return(CloneImage(image,0,0,MagickTrue,exception));
if ((columns <= 2) || (rows <= 2))
return(ResizeImage(image,columns,rows,image->filter,image->blur,exception));
map="RGB";
if (image->matte != MagickFalse)
map="RGBA";
if (image->colorspace == CMYKColorspace)
{
map="CMYK";
if (image->matte != MagickFalse)
map="CMYKA";
}
pixel_info=AcquireVirtualMemory(image->columns,image->rows*strlen(map)*
sizeof(*pixels));
if (pixel_info == (MemoryInfo *) NULL)
return((Image *) NULL);
pixels=(unsigned char *) GetVirtualMemoryBlob(pixel_info);
status=ExportImagePixels(image,0,0,image->columns,image->rows,map,CharPixel,
pixels,exception);
if (status == MagickFalse)
{
pixel_info=RelinquishVirtualMemory(pixel_info);
ThrowImageException(ResourceLimitError,"MemoryAllocationFailed");
}
carver=lqr_carver_new(pixels,(int) image->columns,(int) image->rows,
(int) strlen(map));
if (carver == (LqrCarver *) NULL)
{
pixel_info=RelinquishVirtualMemory(pixel_info);
ThrowImageException(ResourceLimitError,"MemoryAllocationFailed");
}
lqr_carver_set_preserve_input_image(carver);
lqr_status=lqr_carver_init(carver,(int) delta_x,rigidity);
lqr_status=lqr_carver_resize(carver,(int) columns,(int) rows);
(void) lqr_status;
rescale_image=CloneImage(image,lqr_carver_get_width(carver),
lqr_carver_get_height(carver),MagickTrue,exception);
if (rescale_image == (Image *) NULL)
{
pixel_info=RelinquishVirtualMemory(pixel_info);
return((Image *) NULL);
}
if (SetImageStorageClass(rescale_image,DirectClass) == MagickFalse)
{
InheritException(exception,&rescale_image->exception);
rescale_image=DestroyImage(rescale_image);
return((Image *) NULL);
}
GetMagickPixelPacket(rescale_image,&pixel);
(void) lqr_carver_scan_reset(carver);
rescale_view=AcquireAuthenticCacheView(rescale_image,exception);
while (lqr_carver_scan(carver,&x,&y,&packet) != 0)
{
register IndexPacket
*magick_restrict rescale_indexes;
register PixelPacket
*magick_restrict q;
q=QueueCacheViewAuthenticPixels(rescale_view,x,y,1,1,exception);
if (q == (PixelPacket *) NULL)
break;
rescale_indexes=GetCacheViewAuthenticIndexQueue(rescale_view);
pixel.red=QuantumRange*(packet[0]/255.0);
pixel.green=QuantumRange*(packet[1]/255.0);
pixel.blue=QuantumRange*(packet[2]/255.0);
if (image->colorspace != CMYKColorspace)
{
if (image->matte != MagickFalse)
pixel.opacity=QuantumRange-QuantumRange*(packet[3]/255.0);
}
else
{
pixel.index=QuantumRange*(packet[3]/255.0);
if (image->matte != MagickFalse)
pixel.opacity=QuantumRange-QuantumRange*(packet[4]/255.0);
}
SetPixelPacket(rescale_image,&pixel,q,rescale_indexes);
if (SyncCacheViewAuthenticPixels(rescale_view,exception) == MagickFalse)
break;
}
rescale_view=DestroyCacheView(rescale_view);
/*
Relinquish resources.
*/
pixel_info=RelinquishVirtualMemory(pixel_info);
lqr_carver_destroy(carver);
return(rescale_image);
}
#else
MagickExport Image *LiquidRescaleImage(const Image *image,
const size_t magick_unused(columns),const size_t magick_unused(rows),
const double magick_unused(delta_x),const double magick_unused(rigidity),
ExceptionInfo *exception)
{
assert(image != (const Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickCoreSignature);
(void) ThrowMagickException(exception,GetMagickModule(),MissingDelegateError,
"DelegateLibrarySupportNotBuiltIn","`%s' (LQR)",image->filename);
return((Image *) NULL);
}
#endif
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% M a g n i f y I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% MagnifyImage() doubles the size of the image with a pixel art scaling
% algorithm.
%
% The format of the MagnifyImage method is:
%
% Image *MagnifyImage(const Image *image,ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport Image *MagnifyImage(const Image *image,ExceptionInfo *exception)
{
#define MagnifyImageTag "Magnify/Image"
CacheView
*image_view,
*magnify_view;
Image
*magnify_image;
MagickBooleanType
status;
MagickOffsetType
progress;
ssize_t
y;
/*
Initialize magnified image attributes.
*/
assert(image != (const Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickCoreSignature);
magnify_image=CloneImage(image,2*image->columns,2*image->rows,MagickTrue,
exception);
if (magnify_image == (Image *) NULL)
return((Image *) NULL);
/*
Magnify image.
*/
status=MagickTrue;
progress=0;
image_view=AcquireVirtualCacheView(image,exception);
magnify_view=AcquireAuthenticCacheView(magnify_image,exception);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static) shared(progress,status) \
magick_number_threads(image,magnify_image,image->rows,1)
#endif
for (y=0; y < (ssize_t) image->rows; y++)
{
register IndexPacket
*magick_restrict magnify_indexes;
register PixelPacket
*magick_restrict q;
register ssize_t
x;
if (status == MagickFalse)
continue;
q=QueueCacheViewAuthenticPixels(magnify_view,0,2*y,magnify_image->columns,2,
exception);
if (q == (PixelPacket *) NULL)
{
status=MagickFalse;
continue;
}
magnify_indexes=GetCacheViewAuthenticIndexQueue(magnify_view);
for (x=0; x < (ssize_t) image->columns; x++)
{
MagickRealType
intensity[9];
register const IndexPacket
*magick_restrict indexes;
register const PixelPacket
*magick_restrict p;
register PixelPacket
*magick_restrict r;
register ssize_t
i;
/*
Magnify this row of pixels.
*/
p=GetCacheViewVirtualPixels(image_view,x-1,y-1,3,3,exception);
if (p == (const PixelPacket *) NULL)
{
status=MagickFalse;
continue;
}
indexes=GetCacheViewVirtualIndexQueue(image_view);
for (i=0; i < 9; i++)
intensity[i]=GetPixelIntensity(image,p+i);
r=q;
if ((fabs(intensity[1]-intensity[7]) < MagickEpsilon) ||
(fabs(intensity[3]-intensity[5]) < MagickEpsilon))
{
/*
Clone center pixel.
*/
*r=p[4];
r++;
*r=p[4];
r+=(magnify_image->columns-1);
*r=p[4];
r++;
*r=p[4];
}
else
{
/*
Selectively clone pixel.
*/
if (fabs(intensity[1]-intensity[3]) < MagickEpsilon)
*r=p[3];
else
*r=p[4];
r++;
if (fabs(intensity[1]-intensity[5]) < MagickEpsilon)
*r=p[5];
else
*r=p[4];
r+=(magnify_image->columns-1);
if (fabs(intensity[3]-intensity[7]) < MagickEpsilon)
*r=p[3];
else
*r=p[4];
r++;
if (fabs(intensity[5]-intensity[7]) < MagickEpsilon)
*r=p[5];
else
*r=p[4];
}
if (indexes != (const IndexPacket *) NULL)
{
register IndexPacket
*r;
/*
Magnify the colormap indexes.
*/
r=magnify_indexes;
if ((fabs(intensity[1]-intensity[7]) < MagickEpsilon) ||
(fabs(intensity[3]-intensity[5]) < MagickEpsilon))
{
/*
Clone center pixel.
*/
*r=indexes[4];
r++;
*r=indexes[4];
r+=(magnify_image->columns-1);
*r=indexes[4];
r++;
*r=indexes[4];
}
else
{
/*
Selectively clone pixel.
*/
if (fabs(intensity[1]-intensity[3]) < MagickEpsilon)
*r=indexes[3];
else
*r=indexes[4];
r++;
if (fabs(intensity[1]-intensity[5]) < MagickEpsilon)
*r=indexes[5];
else
*r=indexes[4];
r+=(magnify_image->columns-1);
if (fabs(intensity[3]-intensity[7]) < MagickEpsilon)
*r=indexes[3];
else
*r=indexes[4];
r++;
if (fabs(intensity[5]-intensity[7]) < MagickEpsilon)
*r=indexes[5];
else
*r=indexes[4];
}
magnify_indexes+=2;
}
q+=2;
}
if (SyncCacheViewAuthenticPixels(magnify_view,exception) == MagickFalse)
status=MagickFalse;
if (image->progress_monitor != (MagickProgressMonitor) NULL)
{
MagickBooleanType
proceed;
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp atomic
#endif
progress++;
proceed=SetImageProgress(image,MagnifyImageTag,progress,image->rows);
if (proceed == MagickFalse)
status=MagickFalse;
}
}
magnify_view=DestroyCacheView(magnify_view);
image_view=DestroyCacheView(image_view);
if (status == MagickFalse)
magnify_image=DestroyImage(magnify_image);
return(magnify_image);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% M i n i f y I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% MinifyImage() is a convenience method that scales an image proportionally to
% half its size.
%
% The format of the MinifyImage method is:
%
% Image *MinifyImage(const Image *image,ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport Image *MinifyImage(const Image *image,ExceptionInfo *exception)
{
Image
*minify_image;
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickCoreSignature);
minify_image=ResizeImage(image,image->columns/2,image->rows/2,SplineFilter,
1.0,exception);
return(minify_image);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% R e s a m p l e I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% ResampleImage() resize image in terms of its pixel size, so that when
% displayed at the given resolution it will be the same size in terms of
% real world units as the original image at the original resolution.
%
% The format of the ResampleImage method is:
%
% Image *ResampleImage(Image *image,const double x_resolution,
% const double y_resolution,const FilterTypes filter,const double blur,
% ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image to be resized to fit the given resolution.
%
% o x_resolution: the new image x resolution.
%
% o y_resolution: the new image y resolution.
%
% o filter: Image filter to use.
%
% o blur: the blur factor where > 1 is blurry, < 1 is sharp.
%
*/
MagickExport Image *ResampleImage(const Image *image,const double x_resolution,
const double y_resolution,const FilterTypes filter,const double blur,
ExceptionInfo *exception)
{
#define ResampleImageTag "Resample/Image"
Image
*resample_image;
size_t
height,
width;
/*
Initialize sampled image attributes.
*/
assert(image != (const Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickCoreSignature);
width=(size_t) (x_resolution*image->columns/(image->x_resolution == 0.0 ?
72.0 : image->x_resolution)+0.5);
height=(size_t) (y_resolution*image->rows/(image->y_resolution == 0.0 ?
72.0 : image->y_resolution)+0.5);
resample_image=ResizeImage(image,width,height,filter,blur,exception);
if (resample_image != (Image *) NULL)
{
resample_image->x_resolution=x_resolution;
resample_image->y_resolution=y_resolution;
}
return(resample_image);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% R e s i z e I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% ResizeImage() scales an image to the desired dimensions, using the given
% filter (see AcquireFilterInfo()).
%
% If an undefined filter is given the filter defaults to Mitchell for a
% colormapped image, a image with a matte channel, or if the image is
% enlarged. Otherwise the filter defaults to a Lanczos.
%
% ResizeImage() was inspired by Paul Heckbert's "zoom" program.
%
% The format of the ResizeImage method is:
%
% Image *ResizeImage(Image *image,const size_t columns,
% const size_t rows,const FilterTypes filter,const double blur,
% ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o columns: the number of columns in the scaled image.
%
% o rows: the number of rows in the scaled image.
%
% o filter: Image filter to use.
%
% o blur: the blur factor where > 1 is blurry, < 1 is sharp. Typically set
% this to 1.0.
%
% o exception: return any errors or warnings in this structure.
%
*/
typedef struct _ContributionInfo
{
MagickRealType
weight;
ssize_t
pixel;
} ContributionInfo;
static ContributionInfo **DestroyContributionThreadSet(
ContributionInfo **contribution)
{
register ssize_t
i;
assert(contribution != (ContributionInfo **) NULL);
for (i=0; i < (ssize_t) GetMagickResourceLimit(ThreadResource); i++)
if (contribution[i] != (ContributionInfo *) NULL)
contribution[i]=(ContributionInfo *) RelinquishAlignedMemory(
contribution[i]);
contribution=(ContributionInfo **) RelinquishMagickMemory(contribution);
return(contribution);
}
static ContributionInfo **AcquireContributionThreadSet(const size_t count)
{
register ssize_t
i;
ContributionInfo
**contribution;
size_t
number_threads;
number_threads=(size_t) GetMagickResourceLimit(ThreadResource);
contribution=(ContributionInfo **) AcquireQuantumMemory(number_threads,
sizeof(*contribution));
if (contribution == (ContributionInfo **) NULL)
return((ContributionInfo **) NULL);
(void) memset(contribution,0,number_threads*sizeof(*contribution));
for (i=0; i < (ssize_t) number_threads; i++)
{
contribution[i]=(ContributionInfo *) MagickAssumeAligned(
AcquireAlignedMemory(count,sizeof(**contribution)));
if (contribution[i] == (ContributionInfo *) NULL)
return(DestroyContributionThreadSet(contribution));
}
return(contribution);
}
static MagickBooleanType HorizontalFilter(
const ResizeFilter *magick_restrict resize_filter,
const Image *magick_restrict image,Image *magick_restrict resize_image,
const MagickRealType x_factor,const MagickSizeType span,
MagickOffsetType *magick_restrict offset,ExceptionInfo *exception)
{
#define ResizeImageTag "Resize/Image"
CacheView
*image_view,
*resize_view;
ClassType
storage_class;
ContributionInfo
**magick_restrict contributions;
MagickBooleanType
status;
MagickPixelPacket
zero;
MagickRealType
scale,
support;
ssize_t
x;
/*
Apply filter to resize horizontally from image to resize image.
*/
scale=MagickMax(1.0/x_factor+MagickEpsilon,1.0);
support=scale*GetResizeFilterSupport(resize_filter);
storage_class=support > 0.5 ? DirectClass : image->storage_class;
if (SetImageStorageClass(resize_image,storage_class) == MagickFalse)
{
InheritException(exception,&resize_image->exception);
return(MagickFalse);
}
if (support < 0.5)
{
/*
Support too small even for nearest neighbour: Reduce to point
sampling.
*/
support=(MagickRealType) 0.5;
scale=1.0;
}
contributions=AcquireContributionThreadSet((size_t) (2.0*support+3.0));
if (contributions == (ContributionInfo **) NULL)
{
(void) ThrowMagickException(exception,GetMagickModule(),
ResourceLimitError,"MemoryAllocationFailed","`%s'",image->filename);
return(MagickFalse);
}
status=MagickTrue;
scale=PerceptibleReciprocal(scale);
(void) memset(&zero,0,sizeof(zero));
image_view=AcquireVirtualCacheView(image,exception);
resize_view=AcquireAuthenticCacheView(resize_image,exception);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static) shared(status,offset) \
magick_number_threads(image,resize_image,resize_image->columns,1)
#endif
for (x=0; x < (ssize_t) resize_image->columns; x++)
{
const int
id = GetOpenMPThreadId();
MagickRealType
bisect,
density;
register const IndexPacket
*magick_restrict indexes;
register const PixelPacket
*magick_restrict p;
register ContributionInfo
*magick_restrict contribution;
register IndexPacket
*magick_restrict resize_indexes;
register PixelPacket
*magick_restrict q;
register ssize_t
y;
ssize_t
n,
start,
stop;
if (status == MagickFalse)
continue;
bisect=(MagickRealType) (x+0.5)/x_factor+MagickEpsilon;
start=(ssize_t) MagickMax(bisect-support+0.5,0.0);
stop=(ssize_t) MagickMin(bisect+support+0.5,(double) image->columns);
density=0.0;
contribution=contributions[id];
for (n=0; n < (stop-start); n++)
{
contribution[n].pixel=start+n;
contribution[n].weight=GetResizeFilterWeight(resize_filter,scale*
((MagickRealType) (start+n)-bisect+0.5));
density+=contribution[n].weight;
}
if (n == 0)
continue;
if ((density != 0.0) && (density != 1.0))
{
register ssize_t
i;
/*
Normalize.
*/
density=PerceptibleReciprocal(density);
for (i=0; i < n; i++)
contribution[i].weight*=density;
}
p=GetCacheViewVirtualPixels(image_view,contribution[0].pixel,0,(size_t)
(contribution[n-1].pixel-contribution[0].pixel+1),image->rows,exception);
q=QueueCacheViewAuthenticPixels(resize_view,x,0,1,resize_image->rows,
exception);
if ((p == (const PixelPacket *) NULL) || (q == (PixelPacket *) NULL))
{
status=MagickFalse;
continue;
}
indexes=GetCacheViewVirtualIndexQueue(image_view);
resize_indexes=GetCacheViewAuthenticIndexQueue(resize_view);
for (y=0; y < (ssize_t) resize_image->rows; y++)
{
MagickPixelPacket
pixel;
MagickRealType
alpha;
register ssize_t
i;
ssize_t
j;
pixel=zero;
if (image->matte == MagickFalse)
{
for (i=0; i < n; i++)
{
j=y*(contribution[n-1].pixel-contribution[0].pixel+1)+
(contribution[i].pixel-contribution[0].pixel);
alpha=contribution[i].weight;
pixel.red+=alpha*GetPixelRed(p+j);
pixel.green+=alpha*GetPixelGreen(p+j);
pixel.blue+=alpha*GetPixelBlue(p+j);
pixel.opacity+=alpha*GetPixelOpacity(p+j);
}
SetPixelRed(q,ClampToQuantum(pixel.red));
SetPixelGreen(q,ClampToQuantum(pixel.green));
SetPixelBlue(q,ClampToQuantum(pixel.blue));
SetPixelOpacity(q,ClampToQuantum(pixel.opacity));
if ((image->colorspace == CMYKColorspace) &&
(resize_image->colorspace == CMYKColorspace))
{
for (i=0; i < n; i++)
{
j=y*(contribution[n-1].pixel-contribution[0].pixel+1)+
(contribution[i].pixel-contribution[0].pixel);
alpha=contribution[i].weight;
pixel.index+=alpha*GetPixelIndex(indexes+j);
}
SetPixelIndex(resize_indexes+y,ClampToQuantum(pixel.index));
}
}
else
{
double
gamma;
gamma=0.0;
for (i=0; i < n; i++)
{
j=y*(contribution[n-1].pixel-contribution[0].pixel+1)+
(contribution[i].pixel-contribution[0].pixel);
alpha=contribution[i].weight*QuantumScale*GetPixelAlpha(p+j);
pixel.red+=alpha*GetPixelRed(p+j);
pixel.green+=alpha*GetPixelGreen(p+j);
pixel.blue+=alpha*GetPixelBlue(p+j);
pixel.opacity+=contribution[i].weight*GetPixelOpacity(p+j);
gamma+=alpha;
}
gamma=PerceptibleReciprocal(gamma);
SetPixelRed(q,ClampToQuantum(gamma*pixel.red));
SetPixelGreen(q,ClampToQuantum(gamma*pixel.green));
SetPixelBlue(q,ClampToQuantum(gamma*pixel.blue));
SetPixelOpacity(q,ClampToQuantum(pixel.opacity));
if ((image->colorspace == CMYKColorspace) &&
(resize_image->colorspace == CMYKColorspace))
{
for (i=0; i < n; i++)
{
j=y*(contribution[n-1].pixel-contribution[0].pixel+1)+
(contribution[i].pixel-contribution[0].pixel);
alpha=contribution[i].weight*QuantumScale*GetPixelAlpha(p+j);
pixel.index+=alpha*GetPixelIndex(indexes+j);
}
SetPixelIndex(resize_indexes+y,ClampToQuantum(gamma*pixel.index));
}
}
if ((resize_image->storage_class == PseudoClass) &&
(image->storage_class == PseudoClass))
{
i=(ssize_t) (MagickMin(MagickMax(bisect,(double) start),(double) stop-
1.0)+0.5);
j=y*(contribution[n-1].pixel-contribution[0].pixel+1)+
(contribution[i-start].pixel-contribution[0].pixel);
SetPixelIndex(resize_indexes+y,GetPixelIndex(indexes+j));
}
q++;
}
if (SyncCacheViewAuthenticPixels(resize_view,exception) == MagickFalse)
status=MagickFalse;
if (image->progress_monitor != (MagickProgressMonitor) NULL)
{
MagickBooleanType
proceed;
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp atomic
#endif
(*offset)++;
proceed=SetImageProgress(image,ResizeImageTag,*offset,span);
if (proceed == MagickFalse)
status=MagickFalse;
}
}
resize_view=DestroyCacheView(resize_view);
image_view=DestroyCacheView(image_view);
contributions=DestroyContributionThreadSet(contributions);
return(status);
}
static MagickBooleanType VerticalFilter(
const ResizeFilter *magick_restrict resize_filter,
const Image *magick_restrict image,Image *magick_restrict resize_image,
const MagickRealType y_factor,const MagickSizeType span,
MagickOffsetType *magick_restrict offset,ExceptionInfo *exception)
{
CacheView
*image_view,
*resize_view;
ClassType
storage_class;
ContributionInfo
**magick_restrict contributions;
MagickBooleanType
status;
MagickPixelPacket
zero;
MagickRealType
scale,
support;
ssize_t
y;
/*
Apply filter to resize vertically from image to resize image.
*/
scale=MagickMax(1.0/y_factor+MagickEpsilon,1.0);
support=scale*GetResizeFilterSupport(resize_filter);
storage_class=support > 0.5 ? DirectClass : image->storage_class;
if (SetImageStorageClass(resize_image,storage_class) == MagickFalse)
{
InheritException(exception,&resize_image->exception);
return(MagickFalse);
}
if (support < 0.5)
{
/*
Support too small even for nearest neighbour: Reduce to point
sampling.
*/
support=(MagickRealType) 0.5;
scale=1.0;
}
contributions=AcquireContributionThreadSet((size_t) (2.0*support+3.0));
if (contributions == (ContributionInfo **) NULL)
{
(void) ThrowMagickException(exception,GetMagickModule(),
ResourceLimitError,"MemoryAllocationFailed","`%s'",image->filename);
return(MagickFalse);
}
status=MagickTrue;
scale=PerceptibleReciprocal(scale);
(void) memset(&zero,0,sizeof(zero));
image_view=AcquireVirtualCacheView(image,exception);
resize_view=AcquireAuthenticCacheView(resize_image,exception);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static) shared(status,offset) \
magick_number_threads(image,resize_image,resize_image->rows,1)
#endif
for (y=0; y < (ssize_t) resize_image->rows; y++)
{
const int
id = GetOpenMPThreadId();
MagickRealType
bisect,
density;
register const IndexPacket
*magick_restrict indexes;
register const PixelPacket
*magick_restrict p;
register ContributionInfo
*magick_restrict contribution;
register IndexPacket
*magick_restrict resize_indexes;
register PixelPacket
*magick_restrict q;
register ssize_t
x;
ssize_t
n,
start,
stop;
if (status == MagickFalse)
continue;
bisect=(MagickRealType) (y+0.5)/y_factor+MagickEpsilon;
start=(ssize_t) MagickMax(bisect-support+0.5,0.0);
stop=(ssize_t) MagickMin(bisect+support+0.5,(double) image->rows);
density=0.0;
contribution=contributions[id];
for (n=0; n < (stop-start); n++)
{
contribution[n].pixel=start+n;
contribution[n].weight=GetResizeFilterWeight(resize_filter,scale*
((MagickRealType) (start+n)-bisect+0.5));
density+=contribution[n].weight;
}
if (n == 0)
continue;
if ((density != 0.0) && (density != 1.0))
{
register ssize_t
i;
/*
Normalize.
*/
density=PerceptibleReciprocal(density);
for (i=0; i < n; i++)
contribution[i].weight*=density;
}
p=GetCacheViewVirtualPixels(image_view,0,contribution[0].pixel,
image->columns,(size_t) (contribution[n-1].pixel-contribution[0].pixel+1),
exception);
q=QueueCacheViewAuthenticPixels(resize_view,0,y,resize_image->columns,1,
exception);
if ((p == (const PixelPacket *) NULL) || (q == (PixelPacket *) NULL))
{
status=MagickFalse;
continue;
}
indexes=GetCacheViewVirtualIndexQueue(image_view);
resize_indexes=GetCacheViewAuthenticIndexQueue(resize_view);
for (x=0; x < (ssize_t) resize_image->columns; x++)
{
MagickPixelPacket
pixel;
MagickRealType
alpha;
register ssize_t
i;
ssize_t
j;
pixel=zero;
if (image->matte == MagickFalse)
{
for (i=0; i < n; i++)
{
j=(ssize_t) ((contribution[i].pixel-contribution[0].pixel)*
image->columns+x);
alpha=contribution[i].weight;
pixel.red+=alpha*GetPixelRed(p+j);
pixel.green+=alpha*GetPixelGreen(p+j);
pixel.blue+=alpha*GetPixelBlue(p+j);
pixel.opacity+=alpha*GetPixelOpacity(p+j);
}
SetPixelRed(q,ClampToQuantum(pixel.red));
SetPixelGreen(q,ClampToQuantum(pixel.green));
SetPixelBlue(q,ClampToQuantum(pixel.blue));
SetPixelOpacity(q,ClampToQuantum(pixel.opacity));
if ((image->colorspace == CMYKColorspace) &&
(resize_image->colorspace == CMYKColorspace))
{
for (i=0; i < n; i++)
{
j=(ssize_t) ((contribution[i].pixel-contribution[0].pixel)*
image->columns+x);
alpha=contribution[i].weight;
pixel.index+=alpha*GetPixelIndex(indexes+j);
}
SetPixelIndex(resize_indexes+x,ClampToQuantum(pixel.index));
}
}
else
{
double
gamma;
gamma=0.0;
for (i=0; i < n; i++)
{
j=(ssize_t) ((contribution[i].pixel-contribution[0].pixel)*
image->columns+x);
alpha=contribution[i].weight*QuantumScale*GetPixelAlpha(p+j);
pixel.red+=alpha*GetPixelRed(p+j);
pixel.green+=alpha*GetPixelGreen(p+j);
pixel.blue+=alpha*GetPixelBlue(p+j);
pixel.opacity+=contribution[i].weight*GetPixelOpacity(p+j);
gamma+=alpha;
}
gamma=PerceptibleReciprocal(gamma);
SetPixelRed(q,ClampToQuantum(gamma*pixel.red));
SetPixelGreen(q,ClampToQuantum(gamma*pixel.green));
SetPixelBlue(q,ClampToQuantum(gamma*pixel.blue));
SetPixelOpacity(q,ClampToQuantum(pixel.opacity));
if ((image->colorspace == CMYKColorspace) &&
(resize_image->colorspace == CMYKColorspace))
{
for (i=0; i < n; i++)
{
j=(ssize_t) ((contribution[i].pixel-contribution[0].pixel)*
image->columns+x);
alpha=contribution[i].weight*QuantumScale*GetPixelAlpha(p+j);
pixel.index+=alpha*GetPixelIndex(indexes+j);
}
SetPixelIndex(resize_indexes+x,ClampToQuantum(gamma*pixel.index));
}
}
if ((resize_image->storage_class == PseudoClass) &&
(image->storage_class == PseudoClass))
{
i=(ssize_t) (MagickMin(MagickMax(bisect,(double) start),(double) stop-
1.0)+0.5);
j=(ssize_t) ((contribution[i-start].pixel-contribution[0].pixel)*
image->columns+x);
SetPixelIndex(resize_indexes+x,GetPixelIndex(indexes+j));
}
q++;
}
if (SyncCacheViewAuthenticPixels(resize_view,exception) == MagickFalse)
status=MagickFalse;
if (image->progress_monitor != (MagickProgressMonitor) NULL)
{
MagickBooleanType
proceed;
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp atomic
#endif
(*offset)++;
proceed=SetImageProgress(image,ResizeImageTag,*offset,span);
if (proceed == MagickFalse)
status=MagickFalse;
}
}
resize_view=DestroyCacheView(resize_view);
image_view=DestroyCacheView(image_view);
contributions=DestroyContributionThreadSet(contributions);
return(status);
}
MagickExport Image *ResizeImage(const Image *image,const size_t columns,
const size_t rows,const FilterTypes filter,const double blur,
ExceptionInfo *exception)
{
FilterTypes
filter_type;
Image
*filter_image,
*resize_image;
MagickOffsetType
offset;
MagickRealType
x_factor,
y_factor;
MagickSizeType
span;
MagickStatusType
status;
ResizeFilter
*resize_filter;
/*
Acquire resize image.
*/
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickCoreSignature);
if ((columns == 0) || (rows == 0))
ThrowImageException(ImageError,"NegativeOrZeroImageSize");
if ((columns == image->columns) && (rows == image->rows) &&
(filter == UndefinedFilter) && (blur == 1.0))
return(CloneImage(image,0,0,MagickTrue,exception));
/*
Acquire resize filter.
*/
x_factor=(MagickRealType) columns/(MagickRealType) image->columns;
y_factor=(MagickRealType) rows/(MagickRealType) image->rows;
filter_type=LanczosFilter;
if (filter != UndefinedFilter)
filter_type=filter;
else
if ((x_factor == 1.0) && (y_factor == 1.0))
filter_type=PointFilter;
else
if ((image->storage_class == PseudoClass) ||
(image->matte != MagickFalse) || ((x_factor*y_factor) > 1.0))
filter_type=MitchellFilter;
resize_filter=AcquireResizeFilter(image,filter_type,blur,MagickFalse,
exception);
#if defined(MAGICKCORE_OPENCL_SUPPORT)
resize_image=AccelerateResizeImage(image,columns,rows,resize_filter,
exception);
if (resize_image != NULL)
{
resize_filter=DestroyResizeFilter(resize_filter);
return(resize_image);
}
#endif
resize_image=CloneImage(image,columns,rows,MagickTrue,exception);
if (resize_image == (Image *) NULL)
{
resize_filter=DestroyResizeFilter(resize_filter);
return(resize_image);
}
if (x_factor > y_factor)
filter_image=CloneImage(image,columns,image->rows,MagickTrue,exception);
else
filter_image=CloneImage(image,image->columns,rows,MagickTrue,exception);
if (filter_image == (Image *) NULL)
{
resize_filter=DestroyResizeFilter(resize_filter);
return(DestroyImage(resize_image));
}
/*
Resize image.
*/
offset=0;
if (x_factor > y_factor)
{
span=(MagickSizeType) (filter_image->columns+rows);
status=HorizontalFilter(resize_filter,image,filter_image,x_factor,span,
&offset,exception);
status&=VerticalFilter(resize_filter,filter_image,resize_image,y_factor,
span,&offset,exception);
}
else
{
span=(MagickSizeType) (filter_image->rows+columns);
status=VerticalFilter(resize_filter,image,filter_image,y_factor,span,
&offset,exception);
status&=HorizontalFilter(resize_filter,filter_image,resize_image,x_factor,
span,&offset,exception);
}
/*
Free resources.
*/
filter_image=DestroyImage(filter_image);
resize_filter=DestroyResizeFilter(resize_filter);
if (status == MagickFalse)
{
resize_image=DestroyImage(resize_image);
return((Image *) NULL);
}
resize_image->type=image->type;
return(resize_image);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% S a m p l e I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% SampleImage() scales an image to the desired dimensions with pixel
% sampling. Unlike other scaling methods, this method does not introduce
% any additional color into the scaled image.
%
% The format of the SampleImage method is:
%
% Image *SampleImage(const Image *image,const size_t columns,
% const size_t rows,ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o columns: the number of columns in the sampled image.
%
% o rows: the number of rows in the sampled image.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport Image *SampleImage(const Image *image,const size_t columns,
const size_t rows,ExceptionInfo *exception)
{
#define SampleImageTag "Sample/Image"
CacheView
*image_view,
*sample_view;
Image
*sample_image;
MagickBooleanType
status;
MagickOffsetType
progress;
register ssize_t
x;
ssize_t
*x_offset,
y;
PointInfo
sample_offset;
/*
Initialize sampled image attributes.
*/
assert(image != (const Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickCoreSignature);
if ((columns == 0) || (rows == 0))
ThrowImageException(ImageError,"NegativeOrZeroImageSize");
if ((columns == image->columns) && (rows == image->rows))
return(CloneImage(image,0,0,MagickTrue,exception));
sample_image=CloneImage(image,columns,rows,MagickTrue,exception);
if (sample_image == (Image *) NULL)
return((Image *) NULL);
/*
Check for posible user defined sampling offset Artifact
The default sampling offset is in the mid-point of sample regions.
*/
sample_offset.x=sample_offset.y=0.5-MagickEpsilon;
{
const char
*value;
value=GetImageArtifact(image,"sample:offset");
if (value != (char *) NULL)
{
GeometryInfo
geometry_info;
MagickStatusType
flags;
(void) ParseGeometry(value,&geometry_info);
flags=ParseGeometry(value,&geometry_info);
sample_offset.x=sample_offset.y=geometry_info.rho/100.0-MagickEpsilon;
if ((flags & SigmaValue) != 0)
sample_offset.y=geometry_info.sigma/100.0-MagickEpsilon;
}
}
/*
Allocate scan line buffer and column offset buffers.
*/
x_offset=(ssize_t *) AcquireQuantumMemory((size_t) sample_image->columns,
sizeof(*x_offset));
if (x_offset == (ssize_t *) NULL)
{
sample_image=DestroyImage(sample_image);
ThrowImageException(ResourceLimitError,"MemoryAllocationFailed");
}
for (x=0; x < (ssize_t) sample_image->columns; x++)
x_offset[x]=(ssize_t) ((((double) x+sample_offset.x)*image->columns)/
sample_image->columns);
/*
Sample each row.
*/
status=MagickTrue;
progress=0;
image_view=AcquireVirtualCacheView(image,exception);
sample_view=AcquireAuthenticCacheView(sample_image,exception);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static) shared(status) \
magick_number_threads(image,sample_image,sample_image->rows,1)
#endif
for (y=0; y < (ssize_t) sample_image->rows; y++)
{
register const IndexPacket
*magick_restrict indexes;
register const PixelPacket
*magick_restrict p;
register IndexPacket
*magick_restrict sample_indexes;
register PixelPacket
*magick_restrict q;
register ssize_t
x;
ssize_t
y_offset;
if (status == MagickFalse)
continue;
y_offset=(ssize_t) ((((double) y+sample_offset.y)*image->rows)/
sample_image->rows);
p=GetCacheViewVirtualPixels(image_view,0,y_offset,image->columns,1,
exception);
q=QueueCacheViewAuthenticPixels(sample_view,0,y,sample_image->columns,1,
exception);
if ((p == (const PixelPacket *) NULL) || (q == (PixelPacket *) NULL))
{
status=MagickFalse;
continue;
}
indexes=GetCacheViewAuthenticIndexQueue(image_view);
sample_indexes=GetCacheViewAuthenticIndexQueue(sample_view);
/*
Sample each column.
*/
for (x=0; x < (ssize_t) sample_image->columns; x++)
*q++=p[x_offset[x]];
if ((image->storage_class == PseudoClass) ||
(image->colorspace == CMYKColorspace))
for (x=0; x < (ssize_t) sample_image->columns; x++)
SetPixelIndex(sample_indexes+x,GetPixelIndex(indexes+x_offset[x]));
if (SyncCacheViewAuthenticPixels(sample_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,SampleImageTag,progress,image->rows);
if (proceed == MagickFalse)
status=MagickFalse;
}
}
image_view=DestroyCacheView(image_view);
sample_view=DestroyCacheView(sample_view);
x_offset=(ssize_t *) RelinquishMagickMemory(x_offset);
sample_image->type=image->type;
if (status == MagickFalse)
sample_image=DestroyImage(sample_image);
return(sample_image);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% S c a l e I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% ScaleImage() changes the size of an image to the given dimensions.
%
% The format of the ScaleImage method is:
%
% Image *ScaleImage(const Image *image,const size_t columns,
% const size_t rows,ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o columns: the number of columns in the scaled image.
%
% o rows: the number of rows in the scaled image.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport Image *ScaleImage(const Image *image,const size_t columns,
const size_t rows,ExceptionInfo *exception)
{
#define ScaleImageTag "Scale/Image"
CacheView
*image_view,
*scale_view;
Image
*scale_image;
MagickBooleanType
next_column,
next_row,
proceed,
status;
MagickPixelPacket
pixel,
*scale_scanline,
*scanline,
*x_vector,
*y_vector,
zero;
MagickRealType
alpha;
PointInfo
scale,
span;
register ssize_t
i;
ssize_t
number_rows,
y;
/*
Initialize scaled image attributes.
*/
assert(image != (const Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickCoreSignature);
if ((columns == 0) || (rows == 0))
return((Image *) NULL);
if ((columns == image->columns) && (rows == image->rows))
return(CloneImage(image,0,0,MagickTrue,exception));
scale_image=CloneImage(image,columns,rows,MagickTrue,exception);
if (scale_image == (Image *) NULL)
return((Image *) NULL);
if (SetImageStorageClass(scale_image,DirectClass) == MagickFalse)
{
InheritException(exception,&scale_image->exception);
scale_image=DestroyImage(scale_image);
return((Image *) NULL);
}
/*
Allocate memory.
*/
x_vector=(MagickPixelPacket *) AcquireQuantumMemory((size_t) image->columns,
sizeof(*x_vector));
scanline=x_vector;
if (image->rows != scale_image->rows)
scanline=(MagickPixelPacket *) AcquireQuantumMemory((size_t) image->columns,
sizeof(*scanline));
scale_scanline=(MagickPixelPacket *) AcquireQuantumMemory((size_t)
scale_image->columns,sizeof(*scale_scanline));
y_vector=(MagickPixelPacket *) AcquireQuantumMemory((size_t) image->columns,
sizeof(*y_vector));
if ((scanline == (MagickPixelPacket *) NULL) ||
(scale_scanline == (MagickPixelPacket *) NULL) ||
(x_vector == (MagickPixelPacket *) NULL) ||
(y_vector == (MagickPixelPacket *) NULL))
{
if ((image->rows != scale_image->rows) &&
(scanline != (MagickPixelPacket *) NULL))
scanline=(MagickPixelPacket *) RelinquishMagickMemory(scanline);
if (scale_scanline != (MagickPixelPacket *) NULL)
scale_scanline=(MagickPixelPacket *) RelinquishMagickMemory(
scale_scanline);
if (x_vector != (MagickPixelPacket *) NULL)
x_vector=(MagickPixelPacket *) RelinquishMagickMemory(x_vector);
if (y_vector != (MagickPixelPacket *) NULL)
y_vector=(MagickPixelPacket *) RelinquishMagickMemory(y_vector);
scale_image=DestroyImage(scale_image);
ThrowImageException(ResourceLimitError,"MemoryAllocationFailed");
}
/*
Scale image.
*/
number_rows=0;
next_row=MagickTrue;
span.y=1.0;
scale.y=(double) scale_image->rows/(double) image->rows;
(void) memset(y_vector,0,(size_t) image->columns*
sizeof(*y_vector));
GetMagickPixelPacket(image,&pixel);
(void) memset(&zero,0,sizeof(zero));
i=0;
status=MagickTrue;
image_view=AcquireVirtualCacheView(image,exception);
scale_view=AcquireAuthenticCacheView(scale_image,exception);
for (y=0; y < (ssize_t) scale_image->rows; y++)
{
register const IndexPacket
*magick_restrict indexes;
register const PixelPacket
*magick_restrict p;
register IndexPacket
*magick_restrict scale_indexes;
register MagickPixelPacket
*magick_restrict s,
*magick_restrict t;
register PixelPacket
*magick_restrict q;
register ssize_t
x;
if (status == MagickFalse)
break;
q=QueueCacheViewAuthenticPixels(scale_view,0,y,scale_image->columns,1,
exception);
if (q == (PixelPacket *) NULL)
{
status=MagickFalse;
break;
}
alpha=1.0;
scale_indexes=GetCacheViewAuthenticIndexQueue(scale_view);
if (scale_image->rows == image->rows)
{
/*
Read a new scanline.
*/
p=GetCacheViewVirtualPixels(image_view,0,i++,image->columns,1,
exception);
if (p == (const PixelPacket *) NULL)
{
status=MagickFalse;
break;
}
indexes=GetCacheViewVirtualIndexQueue(image_view);
for (x=0; x < (ssize_t) image->columns; x++)
{
if (image->matte != MagickFalse)
alpha=QuantumScale*GetPixelAlpha(p);
x_vector[x].red=(MagickRealType) (alpha*GetPixelRed(p));
x_vector[x].green=(MagickRealType) (alpha*GetPixelGreen(p));
x_vector[x].blue=(MagickRealType) (alpha*GetPixelBlue(p));
if (image->matte != MagickFalse)
x_vector[x].opacity=(MagickRealType) GetPixelOpacity(p);
if (indexes != (IndexPacket *) NULL)
x_vector[x].index=(MagickRealType) (alpha*GetPixelIndex(indexes+x));
p++;
}
}
else
{
/*
Scale Y direction.
*/
while (scale.y < span.y)
{
if ((next_row != MagickFalse) &&
(number_rows < (ssize_t) image->rows))
{
/*
Read a new scanline.
*/
p=GetCacheViewVirtualPixels(image_view,0,i++,image->columns,1,
exception);
if (p == (const PixelPacket *) NULL)
{
status=MagickFalse;
break;
}
indexes=GetCacheViewVirtualIndexQueue(image_view);
for (x=0; x < (ssize_t) image->columns; x++)
{
if (image->matte != MagickFalse)
alpha=QuantumScale*GetPixelAlpha(p);
x_vector[x].red=(MagickRealType) (alpha*GetPixelRed(p));
x_vector[x].green=(MagickRealType) (alpha*GetPixelGreen(p));
x_vector[x].blue=(MagickRealType) (alpha*GetPixelBlue(p));
if (image->matte != MagickFalse)
x_vector[x].opacity=(MagickRealType) GetPixelOpacity(p);
if (indexes != (IndexPacket *) NULL)
x_vector[x].index=(MagickRealType) (alpha*
GetPixelIndex(indexes+x));
p++;
}
number_rows++;
}
for (x=0; x < (ssize_t) image->columns; x++)
{
y_vector[x].red+=scale.y*x_vector[x].red;
y_vector[x].green+=scale.y*x_vector[x].green;
y_vector[x].blue+=scale.y*x_vector[x].blue;
if (scale_image->matte != MagickFalse)
y_vector[x].opacity+=scale.y*x_vector[x].opacity;
if (scale_indexes != (IndexPacket *) NULL)
y_vector[x].index+=scale.y*x_vector[x].index;
}
span.y-=scale.y;
scale.y=(double) scale_image->rows/(double) image->rows;
next_row=MagickTrue;
}
if ((next_row != MagickFalse) && (number_rows < (ssize_t) image->rows))
{
/*
Read a new scanline.
*/
p=GetCacheViewVirtualPixels(image_view,0,i++,image->columns,1,
exception);
if (p == (const PixelPacket *) NULL)
{
status=MagickFalse;
break;
}
indexes=GetCacheViewVirtualIndexQueue(image_view);
for (x=0; x < (ssize_t) image->columns; x++)
{
if (image->matte != MagickFalse)
alpha=QuantumScale*GetPixelAlpha(p);
x_vector[x].red=(MagickRealType) (alpha*GetPixelRed(p));
x_vector[x].green=(MagickRealType) (alpha*GetPixelGreen(p));
x_vector[x].blue=(MagickRealType) (alpha*GetPixelBlue(p));
if (image->matte != MagickFalse)
x_vector[x].opacity=(MagickRealType) GetPixelOpacity(p);
if (indexes != (IndexPacket *) NULL)
x_vector[x].index=(MagickRealType) (alpha*
GetPixelIndex(indexes+x));
p++;
}
number_rows++;
next_row=MagickFalse;
}
s=scanline;
for (x=0; x < (ssize_t) image->columns; x++)
{
pixel.red=y_vector[x].red+span.y*x_vector[x].red;
pixel.green=y_vector[x].green+span.y*x_vector[x].green;
pixel.blue=y_vector[x].blue+span.y*x_vector[x].blue;
if (image->matte != MagickFalse)
pixel.opacity=y_vector[x].opacity+span.y*x_vector[x].opacity;
if (scale_indexes != (IndexPacket *) NULL)
pixel.index=y_vector[x].index+span.y*x_vector[x].index;
s->red=pixel.red;
s->green=pixel.green;
s->blue=pixel.blue;
if (scale_image->matte != MagickFalse)
s->opacity=pixel.opacity;
if (scale_indexes != (IndexPacket *) NULL)
s->index=pixel.index;
s++;
y_vector[x]=zero;
}
scale.y-=span.y;
if (scale.y <= 0)
{
scale.y=(double) scale_image->rows/(double) image->rows;
next_row=MagickTrue;
}
span.y=1.0;
}
if (scale_image->columns == image->columns)
{
/*
Transfer scanline to scaled image.
*/
s=scanline;
for (x=0; x < (ssize_t) scale_image->columns; x++)
{
if (scale_image->matte != MagickFalse)
alpha=QuantumScale*GetPixelAlpha(s);
alpha=PerceptibleReciprocal(alpha);
SetPixelRed(q,ClampToQuantum(alpha*s->red));
SetPixelGreen(q,ClampToQuantum(alpha*s->green));
SetPixelBlue(q,ClampToQuantum(alpha*s->blue));
if (scale_image->matte != MagickFalse)
SetPixelOpacity(q,ClampToQuantum(s->opacity));
if (scale_indexes != (IndexPacket *) NULL)
SetPixelIndex(scale_indexes+x,ClampToQuantum(alpha*s->index));
q++;
s++;
}
}
else
{
/*
Scale X direction.
*/
pixel=zero;
next_column=MagickFalse;
span.x=1.0;
s=scanline;
t=scale_scanline;
for (x=0; x < (ssize_t) image->columns; x++)
{
scale.x=(double) scale_image->columns/(double) image->columns;
while (scale.x >= span.x)
{
if (next_column != MagickFalse)
{
pixel=zero;
t++;
}
pixel.red+=span.x*s->red;
pixel.green+=span.x*s->green;
pixel.blue+=span.x*s->blue;
if (image->matte != MagickFalse)
pixel.opacity+=span.x*s->opacity;
if (scale_indexes != (IndexPacket *) NULL)
pixel.index+=span.x*s->index;
t->red=pixel.red;
t->green=pixel.green;
t->blue=pixel.blue;
if (scale_image->matte != MagickFalse)
t->opacity=pixel.opacity;
if (scale_indexes != (IndexPacket *) NULL)
t->index=pixel.index;
scale.x-=span.x;
span.x=1.0;
next_column=MagickTrue;
}
if (scale.x > 0)
{
if (next_column != MagickFalse)
{
pixel=zero;
next_column=MagickFalse;
t++;
}
pixel.red+=scale.x*s->red;
pixel.green+=scale.x*s->green;
pixel.blue+=scale.x*s->blue;
if (scale_image->matte != MagickFalse)
pixel.opacity+=scale.x*s->opacity;
if (scale_indexes != (IndexPacket *) NULL)
pixel.index+=scale.x*s->index;
span.x-=scale.x;
}
s++;
}
if (span.x > 0)
{
s--;
pixel.red+=span.x*s->red;
pixel.green+=span.x*s->green;
pixel.blue+=span.x*s->blue;
if (scale_image->matte != MagickFalse)
pixel.opacity+=span.x*s->opacity;
if (scale_indexes != (IndexPacket *) NULL)
pixel.index+=span.x*s->index;
}
if ((next_column == MagickFalse) &&
((ssize_t) (t-scale_scanline) < (ssize_t) scale_image->columns))
{
t->red=pixel.red;
t->green=pixel.green;
t->blue=pixel.blue;
if (scale_image->matte != MagickFalse)
t->opacity=pixel.opacity;
if (scale_indexes != (IndexPacket *) NULL)
t->index=pixel.index;
}
/*
Transfer scanline to scaled image.
*/
t=scale_scanline;
for (x=0; x < (ssize_t) scale_image->columns; x++)
{
if (scale_image->matte != MagickFalse)
alpha=QuantumScale*GetPixelAlpha(t);
alpha=PerceptibleReciprocal(alpha);
SetPixelRed(q,ClampToQuantum(alpha*t->red));
SetPixelGreen(q,ClampToQuantum(alpha*t->green));
SetPixelBlue(q,ClampToQuantum(alpha*t->blue));
if (scale_image->matte != MagickFalse)
SetPixelOpacity(q,ClampToQuantum(t->opacity));
if (scale_indexes != (IndexPacket *) NULL)
SetPixelIndex(scale_indexes+x,ClampToQuantum(alpha*t->index));
t++;
q++;
}
}
if (SyncCacheViewAuthenticPixels(scale_view,exception) == MagickFalse)
{
status=MagickFalse;
break;
}
proceed=SetImageProgress(image,ScaleImageTag,(MagickOffsetType) y,
image->rows);
if (proceed == MagickFalse)
{
status=MagickFalse;
break;
}
}
scale_view=DestroyCacheView(scale_view);
image_view=DestroyCacheView(image_view);
/*
Free allocated memory.
*/
y_vector=(MagickPixelPacket *) RelinquishMagickMemory(y_vector);
scale_scanline=(MagickPixelPacket *) RelinquishMagickMemory(scale_scanline);
if (scale_image->rows != image->rows)
scanline=(MagickPixelPacket *) RelinquishMagickMemory(scanline);
x_vector=(MagickPixelPacket *) RelinquishMagickMemory(x_vector);
scale_image->type=image->type;
if (status == MagickFalse)
scale_image=DestroyImage(scale_image);
return(scale_image);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% T h u m b n a i l I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% ThumbnailImage() changes the size of an image to the given dimensions and
% removes any associated profiles. The goal is to produce small low cost
% thumbnail images suited for display on the Web.
%
% The format of the ThumbnailImage method is:
%
% Image *ThumbnailImage(const Image *image,const size_t columns,
% const size_t rows,ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o columns: the number of columns in the scaled image.
%
% o rows: the number of rows in the scaled image.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport Image *ThumbnailImage(const Image *image,const size_t columns,
const size_t rows,ExceptionInfo *exception)
{
#define SampleFactor 5
char
filename[MaxTextExtent],
value[MaxTextExtent];
const char
*name;
Image
*thumbnail_image;
MagickRealType
x_factor,
y_factor;
struct stat
attributes;
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickCoreSignature);
x_factor=(MagickRealType) columns/(MagickRealType) image->columns;
y_factor=(MagickRealType) rows/(MagickRealType) image->rows;
if ((x_factor*y_factor) > 0.1)
thumbnail_image=ResizeImage(image,columns,rows,image->filter,image->blur,
exception);
else
if (((SampleFactor*columns) < 128) || ((SampleFactor*rows) < 128))
thumbnail_image=ResizeImage(image,columns,rows,image->filter,
image->blur,exception);
else
{
Image
*sample_image;
sample_image=SampleImage(image,SampleFactor*columns,SampleFactor*rows,
exception);
if (sample_image == (Image *) NULL)
return((Image *) NULL);
thumbnail_image=ResizeImage(sample_image,columns,rows,image->filter,
image->blur,exception);
sample_image=DestroyImage(sample_image);
}
if (thumbnail_image == (Image *) NULL)
return(thumbnail_image);
(void) ParseAbsoluteGeometry("0x0+0+0",&thumbnail_image->page);
if (thumbnail_image->matte == MagickFalse)
(void) SetImageAlphaChannel(thumbnail_image,OpaqueAlphaChannel);
thumbnail_image->depth=8;
thumbnail_image->interlace=NoInterlace;
/*
Strip all profiles except color profiles.
*/
ResetImageProfileIterator(thumbnail_image);
for (name=GetNextImageProfile(thumbnail_image); name != (const char *) NULL; )
{
if ((LocaleCompare(name,"icc") != 0) && (LocaleCompare(name,"icm") != 0))
{
(void) DeleteImageProfile(thumbnail_image,name);
ResetImageProfileIterator(thumbnail_image);
}
name=GetNextImageProfile(thumbnail_image);
}
(void) DeleteImageProperty(thumbnail_image,"comment");
(void) CopyMagickString(value,image->magick_filename,MaxTextExtent);
if (strstr(image->magick_filename,"//") == (char *) NULL)
(void) FormatLocaleString(value,MaxTextExtent,"file://%s",
image->magick_filename);
(void) SetImageProperty(thumbnail_image,"Thumb::URI",value);
GetPathComponent(image->magick_filename,TailPath,filename);
(void) CopyMagickString(value,filename,MaxTextExtent);
if (GetPathAttributes(image->filename,&attributes) != MagickFalse)
{
(void) FormatLocaleString(value,MaxTextExtent,"%.20g",(double)
attributes.st_mtime);
(void) SetImageProperty(thumbnail_image,"Thumb::MTime",value);
}
(void) FormatLocaleString(value,MaxTextExtent,"%.20g",(double)
attributes.st_mtime);
(void) FormatMagickSize(GetBlobSize(image),MagickFalse,value);
(void) ConcatenateMagickString(value,"B",MaxTextExtent);
(void) SetImageProperty(thumbnail_image,"Thumb::Size",value);
(void) FormatLocaleString(value,MaxTextExtent,"image/%s",image->magick);
LocaleLower(value);
(void) SetImageProperty(thumbnail_image,"Thumb::Mimetype",value);
(void) SetImageProperty(thumbnail_image,"software",MagickAuthoritativeURL);
(void) FormatLocaleString(value,MaxTextExtent,"%.20g",(double)
image->magick_columns);
(void) SetImageProperty(thumbnail_image,"Thumb::Image::Width",value);
(void) FormatLocaleString(value,MaxTextExtent,"%.20g",(double)
image->magick_rows);
(void) SetImageProperty(thumbnail_image,"Thumb::Image::Height",value);
(void) FormatLocaleString(value,MaxTextExtent,"%.20g",(double)
GetImageListLength(image));
(void) SetImageProperty(thumbnail_image,"Thumb::Document::Pages",value);
return(thumbnail_image);
}
|
gpg_fmt_plug.c | /* GPG cracker patch for JtR. Hacked together during Monsoon of 2012 by
* Dhiru Kholia <dhiru.kholia at gmail.com> .
*
* This software is Copyright (c) 2012, Dhiru Kholia <dhiru.kholia at gmail.com>
* and is based on,
*
* pgpry - PGP private key recovery
* Copyright (C) 2010 Jonas Gehring
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* 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
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>
*
* converted to use 'common' code, Feb29-Mar1 2016, JimF.
*/
#if FMT_EXTERNS_H
extern struct fmt_main fmt_gpg;
#elif FMT_REGISTERS_H
john_register_one(&fmt_gpg);
#else
#include <string.h>
#include <assert.h>
#include <stdint.h>
#ifdef _OPENMP
#include <omp.h>
#ifndef OMP_SCALE
#define OMP_SCALE 64
#endif
#endif
#include "arch.h"
#include "params.h"
#include "common.h"
#include "formats.h"
#include "misc.h"
#include "twofish.h"
#include "md5.h"
#include "rc4.h"
#include "pdfcrack_md5.h"
#include "sha.h"
#include "sha2.h"
#include "gpg_common.h"
#include "memdbg.h"
#define FORMAT_LABEL "gpg"
#define FORMAT_NAME "OpenPGP / GnuPG Secret Key"
#define ALGORITHM_NAME "32/" ARCH_BITS_STR
#define SALT_SIZE sizeof(struct gpg_common_custom_salt*)
#define MIN_KEYS_PER_CRYPT 1
#define MAX_KEYS_PER_CRYPT 1
#if defined (_OPENMP)
static int omp_t = 1;
#endif
static char (*saved_key)[PLAINTEXT_LENGTH + 1];
static int *cracked;
static int any_cracked;
static size_t cracked_size;
static void init(struct fmt_main *self)
{
#if defined (_OPENMP)
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_align(sizeof(*saved_key),
self->params.max_keys_per_crypt, MEM_ALIGN_WORD);
any_cracked = 0;
cracked_size = sizeof(*cracked) * self->params.max_keys_per_crypt;
cracked = mem_calloc_align(sizeof(*cracked), self->params.max_keys_per_crypt, MEM_ALIGN_WORD);
Twofish_initialise();
}
static void done(void)
{
MEM_FREE(cracked);
MEM_FREE(saved_key);
}
static int valid(char *ciphertext, struct fmt_main *self)
{
return gpg_common_valid(ciphertext, self, 1);
}
static void set_salt(void *salt)
{
gpg_common_cur_salt = *(struct gpg_common_custom_salt **)salt;
}
static void gpg_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 int crypt_all(int *pcount, struct db_salt *salt)
{
const int count = *pcount;
int index = 0;
int ks = gpg_common_keySize(gpg_common_cur_salt->cipher_algorithm);
if (any_cracked) {
memset(cracked, 0, cracked_size);
any_cracked = 0;
}
#ifdef _OPENMP
#pragma omp parallel for
for (index = 0; index < count; index++)
#endif
{
int res;
unsigned char keydata[64];
gpg_common_cur_salt->s2kfun(saved_key[index], keydata, ks);
res = gpg_common_check(keydata, ks);
if (res) {
cracked[index] = 1;
#ifdef _OPENMP
#pragma omp atomic
#endif
any_cracked |= 1;
}
}
return count;
}
static int cmp_all(void *binary, int count)
{
return any_cracked;
}
static int cmp_one(void *binary, int index)
{
return cracked[index];
}
static int cmp_exact(char *source, int index)
{
return 1;
}
struct fmt_main fmt_gpg = {
{
FORMAT_LABEL,
FORMAT_NAME,
ALGORITHM_NAME,
BENCHMARK_COMMENT,
BENCHMARK_LENGTH,
0,
PLAINTEXT_LENGTH,
BINARY_SIZE,
BINARY_ALIGN,
SALT_SIZE,
SALT_ALIGN,
MIN_KEYS_PER_CRYPT,
MAX_KEYS_PER_CRYPT,
FMT_CASE | FMT_8_BIT | FMT_OMP | FMT_DYNA_SALT | FMT_HUGE_INPUT,
{
"s2k-count", /* only for gpg --s2k-mode 3, see man gpg, option --s2k-count n */
"hash algorithm [1:MD5 2:SHA1 3:RIPEMD160 8:SHA256 9:SHA384 10:SHA512 11:SHA224]",
"cipher algorithm [1:IDEA 2:3DES 3:CAST5 4:Blowfish 7:AES128 8:AES192 9:AES256 10:Twofish 11:Camellia128 12:Camellia192 13:Camellia256]",
},
{ FORMAT_TAG },
gpg_common_gpg_tests
},
{
init,
done,
fmt_default_reset,
fmt_default_prepare,
valid,
fmt_default_split,
fmt_default_binary,
gpg_common_get_salt,
{
gpg_common_gpg_s2k_count,
gpg_common_gpg_hash_algorithm,
gpg_common_gpg_cipher_algorithm,
},
fmt_default_source,
{
fmt_default_binary_hash
},
fmt_default_salt_hash,
NULL,
set_salt,
gpg_set_key,
get_key,
fmt_default_clear_keys,
crypt_all,
{
fmt_default_get_hash
},
cmp_all,
cmp_one,
cmp_exact
}
};
#endif /* plugin stanza */
|
hecmw_partition.c | /*****************************************************************************
* Copyright (c) 2019 FrontISTR Commons
* This software is released under the MIT License, see LICENSE.txt
*****************************************************************************/
#define INAGAKI_PARTITIONER
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <assert.h>
#include <errno.h>
#include <math.h>
#include "hecmw_util.h"
#include "hecmw_common.h"
#include "hecmw_io.h"
#include "hecmw_part_define.h"
#include "hecmw_part_struct.h"
#include "hecmw_part_log.h"
#include "hecmw_mesh_hash_sort.h"
#include "hecmw_mesh_edge_info.h"
#include "hecmw_part_get_control.h"
#include "hecmw_partition.h"
#include "hecmw_ucd_print.h"
#include "hecmw_graph.h"
#include "hecmw_common_define.h"
#ifdef HECMW_PART_WITH_METIS
#include "metis.h"
#endif
#ifdef _OPENMP
#include <omp.h>
#endif
#define INTERNAL 1
#define EXTERNAL 2
#define BOUNDARY 4
#define OVERLAP 8
#define MASK 16
#define MARK 32
#define MY_DOMAIN 1
#define NEIGHBOR_DOMAIN 2
#define MPC_BLOCK 4
#define CANDIDATE 8
#define EPS (1.0E-12)
#define F_1_2 (0.5)
#define F_6_10 (0.6)
#define QSORT_LOWER 50
#define MASK_BIT(map, bit) ((map) |= (bit))
#define EVAL_BIT(map, bit) ((map) & (bit))
#define INV_BIT(map, bit) ((map) ^= (bit))
#define CLEAR_BIT(map, bit) \
((map) |= (bit)); \
((map) ^= (bit))
#define CLEAR_IEB(map) \
((map) |= (7)); \
((map) ^= (7))
#define CLEAR_MM(map) \
((map) |= (48)); \
((map) ^= (48))
#define DSWAP(a, aa) \
atemp = (a); \
(a) = (aa); \
(aa) = atemp;
#define ISWAP(b, bb) \
btemp = (b); \
(b) = (bb); \
(bb) = btemp;
#define RTC_NORMAL 0
#define RTC_ERROR (-1)
#define RTC_WARN 1
#define MAX_NODE_SIZE 20
struct link_unit {
int id;
struct link_unit *next;
};
struct link_list {
int n;
struct link_unit *list;
struct link_unit *last;
};
/*===== internal/boundary node/element list of each domain =======*/
static int *n_int_nlist = NULL;
static int *n_bnd_nlist = NULL;
static int *n_int_elist = NULL;
static int *n_bnd_elist = NULL;
static int **int_nlist = NULL;
static int **bnd_nlist = NULL;
static int **int_elist = NULL;
static int **bnd_elist = NULL;
static int **ngrp_idx = NULL;
static int **ngrp_item = NULL;
static int **egrp_idx = NULL;
static int **egrp_item = NULL;
/*===== speed up (K. Inagaki )=======*/
static int spdup_clear_MMbnd(char *node_flag, char *elem_flag,
int current_domain) {
int i, node, elem;
for (i = 0; i < n_bnd_nlist[2 * current_domain + 1]; i++) {
node = bnd_nlist[current_domain][i];
CLEAR_MM(node_flag[node - 1]);
}
for (i = 0; i < n_bnd_elist[2 * current_domain + 1]; i++) {
elem = bnd_elist[current_domain][i];
CLEAR_MM(elem_flag[elem - 1]);
}
return RTC_NORMAL;
}
static int spdup_clear_IEB(char *node_flag, char *elem_flag,
int current_domain) {
int i, node, elem;
for (i = 0; i < n_int_nlist[current_domain]; i++) {
node = int_nlist[current_domain][i];
CLEAR_IEB(node_flag[node - 1]);
}
for (i = 0; i < n_bnd_nlist[2 * current_domain + 1]; i++) {
node = bnd_nlist[current_domain][i];
CLEAR_IEB(node_flag[node - 1]);
}
for (i = 0; i < n_int_elist[current_domain]; i++) {
elem = int_elist[current_domain][i];
CLEAR_IEB(elem_flag[elem - 1]);
}
for (i = 0; i < n_bnd_elist[2 * current_domain + 1]; i++) {
elem = bnd_elist[current_domain][i];
CLEAR_IEB(elem_flag[elem - 1]);
}
return RTC_NORMAL;
}
static int spdup_init_list(const struct hecmwST_local_mesh *global_mesh) {
int i, j, k;
int js, je;
int node, n_domain, domain[20], flag;
/*init lists for count (calloc) */
n_int_nlist = (int *)HECMW_calloc(global_mesh->n_subdomain, sizeof(int));
if (n_int_nlist == NULL) {
HECMW_set_error(errno, "");
goto error;
}
n_bnd_nlist = (int *)HECMW_calloc(2 * global_mesh->n_subdomain, sizeof(int));
if (n_bnd_nlist == NULL) {
HECMW_set_error(errno, "");
goto error;
}
n_int_elist = (int *)HECMW_calloc(global_mesh->n_subdomain, sizeof(int));
if (n_int_elist == NULL) {
HECMW_set_error(errno, "");
goto error;
}
n_bnd_elist = (int *)HECMW_calloc(2 * global_mesh->n_subdomain, sizeof(int));
if (n_bnd_elist == NULL) {
HECMW_set_error(errno, "");
goto error;
}
int_nlist = (int **)HECMW_malloc(global_mesh->n_subdomain * sizeof(int *));
if (int_nlist == NULL) {
HECMW_set_error(errno, "");
goto error;
}
bnd_nlist = (int **)HECMW_malloc(global_mesh->n_subdomain * sizeof(int *));
if (bnd_nlist == NULL) {
HECMW_set_error(errno, "");
goto error;
}
int_elist = (int **)HECMW_malloc(global_mesh->n_subdomain * sizeof(int *));
if (int_elist == NULL) {
HECMW_set_error(errno, "");
goto error;
}
bnd_elist = (int **)HECMW_malloc(global_mesh->n_subdomain * sizeof(int *));
if (bnd_elist == NULL) {
HECMW_set_error(errno, "");
goto error;
}
/* count internal node */
for (i = 0; i < global_mesh->n_node; i++) {
n_int_nlist[global_mesh->node_ID[2 * i + 1]]++;
}
/*count internal elem */
for (i = 0; i < global_mesh->n_elem; i++) {
n_int_elist[global_mesh->elem_ID[2 * i + 1]]++;
}
/*count boundary node and elem */
for (i = 0; i < global_mesh->n_elem; i++) {
js = global_mesh->elem_node_index[i];
je = global_mesh->elem_node_index[i + 1];
node = global_mesh->elem_node_item[js];
n_domain = 1;
domain[0] = global_mesh->node_ID[2 * node - 1];
for (j = js + 1; j < je; j++) {
node = global_mesh->elem_node_item[j];
for (flag = 0, k = 0; k < n_domain; k++) {
if (global_mesh->node_ID[2 * node - 1] == domain[k]) {
flag++;
break;
}
}
if (flag == 0) {
domain[n_domain] = global_mesh->node_ID[2 * node - 1];
n_domain++;
}
}
if (n_domain > 1) {
for (j = 0; j < n_domain; j++) {
n_bnd_elist[domain[j]]++;
n_bnd_nlist[domain[j]] += je - js;
}
}
}
/*allocate node/element list of each domain */
for (i = 0; i < global_mesh->n_subdomain; i++) {
int_nlist[i] = (int *)HECMW_calloc(n_int_nlist[i], sizeof(int));
if (int_nlist[i] == NULL) {
HECMW_set_error(errno, "");
goto error;
}
bnd_nlist[i] = (int *)HECMW_calloc(n_bnd_nlist[i], sizeof(int));
if (bnd_nlist[i] == NULL) {
HECMW_set_error(errno, "");
goto error;
}
int_elist[i] = (int *)HECMW_calloc(n_int_elist[i], sizeof(int));
if (int_elist[i] == NULL) {
HECMW_set_error(errno, "");
goto error;
}
bnd_elist[i] = (int *)HECMW_calloc(n_bnd_elist[i], sizeof(int));
if (bnd_elist[i] == NULL) {
HECMW_set_error(errno, "");
goto error;
}
}
return RTC_NORMAL;
error:
return RTC_ERROR;
}
static int int_cmp(const void *v1, const void *v2) {
const int *i1, *i2;
i1 = (const int *)v1;
i2 = (const int *)v2;
if (*i1 < *i2) return -1;
if (*i1 > *i2) return 1;
return 0;
}
static int get_boundary_nodelist(const struct hecmwST_local_mesh *global_mesh,
int domain) {
int i, j, k;
int ks, ke, node, elem, counter;
for (counter = 0, j = 0; j < n_bnd_elist[2 * domain + 1]; j++) {
elem = bnd_elist[domain][j];
ks = global_mesh->elem_node_index[elem - 1];
ke = global_mesh->elem_node_index[elem];
for (k = ks; k < ke; k++) {
node = global_mesh->elem_node_item[k];
bnd_nlist[domain][counter] = node;
counter++;
}
}
qsort(bnd_nlist[domain], counter, sizeof(int), int_cmp);
i = 1;
for (j = 1; j < counter; j++) {
if (bnd_nlist[domain][j - 1] != bnd_nlist[domain][j]) {
bnd_nlist[domain][i] = bnd_nlist[domain][j];
i++;
}
}
n_bnd_nlist[2 * domain + 1] = i;
return RTC_NORMAL;
}
static int sort_and_resize_bndlist(const struct hecmwST_local_mesh *global_mesh,
int domain) {
int i, node, elem;
int *work = NULL;
int bnd_and_int, bnd_not_int;
int n_nlist, n_elist;
/*boundary node list */
n_nlist = n_bnd_nlist[2 * domain + 1];
work = (int *)HECMW_malloc(n_nlist * sizeof(int));
if (work == NULL) {
HECMW_set_error(errno, "");
goto error;
}
/*sort */
bnd_and_int = 0;
bnd_not_int = 0;
for (i = 0; i < n_nlist; i++) {
node = bnd_nlist[domain][i];
if (global_mesh->node_ID[2 * node - 1] == domain) {
work[bnd_and_int] = node;
bnd_and_int++;
}
}
for (i = 0; i < n_nlist; i++) {
node = bnd_nlist[domain][i];
if (global_mesh->node_ID[2 * node - 1] != domain) {
work[bnd_and_int + bnd_not_int] = node;
bnd_not_int++;
}
}
n_bnd_nlist[2 * domain] = bnd_and_int;
n_bnd_nlist[2 * domain + 1] = bnd_and_int + bnd_not_int;
HECMW_assert(n_nlist == n_bnd_nlist[2 * domain + 1]);
/*resize */
HECMW_free(bnd_nlist[domain]);
bnd_nlist[domain] = (int *)HECMW_calloc(n_nlist, sizeof(int));
if (bnd_nlist[domain] == NULL) {
HECMW_set_error(errno, "");
goto error;
}
for (i = 0; i < n_nlist; i++) {
bnd_nlist[domain][i] = work[i];
}
HECMW_free(work);
/*boundary element list */
n_elist = n_bnd_elist[2 * domain + 1];
work = (int *)HECMW_malloc(n_elist * sizeof(int));
if (work == NULL) {
HECMW_set_error(errno, "");
goto error;
}
/*sort */
bnd_and_int = 0;
bnd_not_int = 0;
for (i = 0; i < n_elist; i++) {
elem = bnd_elist[domain][i];
if (global_mesh->elem_ID[2 * elem - 1] == domain) {
work[bnd_and_int] = elem;
bnd_and_int++;
}
}
for (i = 0; i < n_elist; i++) {
elem = bnd_elist[domain][i];
if (global_mesh->elem_ID[2 * elem - 1] != domain) {
work[bnd_and_int + bnd_not_int] = elem;
bnd_not_int++;
}
}
n_bnd_elist[2 * domain] = bnd_and_int;
n_bnd_elist[2 * domain + 1] = bnd_and_int + bnd_not_int;
for (i = 0; i < n_elist; i++) {
bnd_elist[domain][i] = work[i];
}
HECMW_free(work);
HECMW_assert(n_elist == n_bnd_elist[2 * domain + 1]);
return RTC_NORMAL;
error:
return RTC_ERROR;
}
static int spdup_make_list(const struct hecmwST_local_mesh *global_mesh) {
int i, j, k;
int js, je, ks, ke;
int node, elem, n_domain, domain[20], flag;
int current_domain;
int rtc;
/*clear counters */
for (i = 0; i < global_mesh->n_subdomain; i++) {
n_int_nlist[i] = 0;
n_bnd_nlist[2 * i] = 0;
n_bnd_nlist[2 * i + 1] = 0;
n_int_elist[i] = 0;
n_bnd_elist[2 * i] = 0;
n_bnd_elist[2 * i + 1] = 0;
}
/* internal nodelist for each domain */
for (i = 0; i < global_mesh->n_node; i++) {
current_domain = global_mesh->node_ID[2 * i + 1];
int_nlist[current_domain][n_int_nlist[current_domain]] = i + 1;
n_int_nlist[current_domain]++;
}
/* internal elemlist for each domain */
for (i = 0; i < global_mesh->n_elem; i++) {
current_domain = global_mesh->elem_ID[2 * i + 1];
int_elist[current_domain][n_int_elist[current_domain]] = i + 1;
n_int_elist[current_domain]++;
}
/* boundary elemlist for each domain */
for (i = 0; i < global_mesh->n_elem; i++) {
js = global_mesh->elem_node_index[i];
je = global_mesh->elem_node_index[i + 1];
node = global_mesh->elem_node_item[js];
n_domain = 1;
domain[0] = global_mesh->node_ID[2 * node - 1];
for (j = js + 1; j < je; j++) {
node = global_mesh->elem_node_item[j];
for (flag = 0, k = 0; k < n_domain; k++) {
if (global_mesh->node_ID[2 * node - 1] == domain[k]) {
flag++;
break;
}
}
if (flag == 0) {
domain[n_domain] = global_mesh->node_ID[2 * node - 1];
n_domain++;
}
}
if (n_domain > 1) {
for (j = 0; j < n_domain; j++) {
bnd_elist[domain[j]][n_bnd_elist[2 * domain[j] + 1]] = i + 1;
n_bnd_elist[2 * domain[j] + 1]++;
}
}
}
/* boundary nodelist for each domain */
for (i = 0; i < global_mesh->n_subdomain; i++) {
rtc = get_boundary_nodelist(global_mesh, i);
if (rtc != RTC_NORMAL) goto error;
}
for (i = 0; i < global_mesh->n_subdomain; i++) {
rtc = sort_and_resize_bndlist(global_mesh, i);
if (rtc != RTC_NORMAL) goto error;
}
return RTC_NORMAL;
error:
return RTC_ERROR;
}
static int spdup_make_node_grouplist(
const struct hecmwST_local_mesh *global_mesh) {
struct hecmwST_node_grp *node_group_global = global_mesh->node_group;
int i, j, k, node, n_bnd, n_out;
int *n_domain = NULL;
int **domain = NULL;
int current_domain;
int counter[global_mesh->n_subdomain];
/*make list of node to domain(both internal and boundary) */
n_domain = (int *)HECMW_calloc(global_mesh->n_node, sizeof(int));
if (n_domain == NULL) {
HECMW_set_error(errno, "");
goto error;
}
/*count outer node(boundary and not internal) */
for (i = 0; i < global_mesh->n_subdomain; i++) {
n_bnd = n_bnd_nlist[2 * i];
n_out = n_bnd_nlist[2 * i + 1] - n_bnd_nlist[2 * i];
if (n_out == 0) continue;
for (j = 0; j < n_out; j++) {
node = bnd_nlist[i][n_bnd + j];
n_domain[node - 1]++;
}
}
/*make list */
domain = (int **)HECMW_malloc(global_mesh->n_node * sizeof(int *));
if (domain == NULL) {
HECMW_set_error(errno, "");
goto error;
}
for (i = 0; i < global_mesh->n_node; i++) {
domain[i] = (int *)HECMW_malloc((n_domain[i] + 1) *
sizeof(int)); /*+1 means internal node */
if (domain[i] == NULL) {
HECMW_set_error(errno, "");
goto error;
}
domain[i][0] = global_mesh->node_ID[2 * i + 1];
n_domain[i] = 1;
}
for (i = 0; i < global_mesh->n_subdomain; i++) {
n_bnd = n_bnd_nlist[2 * i];
n_out = n_bnd_nlist[2 * i + 1] - n_bnd_nlist[2 * i];
if (n_out == 0) continue;
for (j = 0; j < n_out; j++) {
node = bnd_nlist[i][n_bnd + j];
domain[node - 1][n_domain[node - 1]] = i;
n_domain[node - 1]++;
}
}
/*make ngroup index list */
ngrp_idx = (int **)HECMW_malloc(global_mesh->n_subdomain * sizeof(int *));
if (ngrp_idx == NULL) {
HECMW_set_error(errno, "");
goto error;
}
for (i = 0; i < global_mesh->n_subdomain; i++) {
ngrp_idx[i] =
(int *)HECMW_calloc((node_group_global->n_grp + 1), sizeof(int));
if (ngrp_idx[i] == NULL) {
HECMW_set_error(errno, "");
goto error;
}
}
for (i = 0; i < node_group_global->n_grp; i++) { /*skip group "ALL" */
for (j = 0; j < global_mesh->n_subdomain; j++) {
ngrp_idx[j][i + 1] = ngrp_idx[j][i];
}
if (node_group_global->grp_index[i + 1] - node_group_global->grp_index[i] ==
global_mesh->n_node) {
continue;
}
for (j = node_group_global->grp_index[i];
j < node_group_global->grp_index[i + 1]; j++) {
node = node_group_global->grp_item[j];
for (k = 0; k < n_domain[node - 1]; k++) {
current_domain = domain[node - 1][k];
ngrp_idx[current_domain][i + 1]++;
}
}
}
/*make ngroup item list */
ngrp_item = (int **)HECMW_malloc(global_mesh->n_subdomain * sizeof(int *));
if (ngrp_item == NULL) {
HECMW_set_error(errno, "");
goto error;
}
for (i = 0; i < global_mesh->n_subdomain; i++) {
ngrp_item[i] = (int *)HECMW_malloc(ngrp_idx[i][node_group_global->n_grp] *
sizeof(int));
if (ngrp_item[i] == NULL) {
HECMW_set_error(errno, "");
goto error;
}
counter[i] = 0;
}
for (i = 0; i < node_group_global->n_grp; i++) { /*skip group "ALL" */
if (node_group_global->grp_index[i + 1] - node_group_global->grp_index[i] ==
global_mesh->n_node) {
continue;
}
for (j = node_group_global->grp_index[i];
j < node_group_global->grp_index[i + 1]; j++) {
node = node_group_global->grp_item[j];
for (k = 0; k < n_domain[node - 1]; k++) {
current_domain = domain[node - 1][k];
ngrp_item[current_domain][counter[current_domain]] = node;
counter[current_domain]++;
}
}
}
for (i = 0; i < global_mesh->n_node; i++) {
HECMW_free(domain[i]);
}
HECMW_free(n_domain);
HECMW_free(domain);
return RTC_NORMAL;
error:
return RTC_ERROR;
}
static int spdup_make_element_grouplist(
const struct hecmwST_local_mesh *global_mesh) {
struct hecmwST_elem_grp *elem_group_global = global_mesh->elem_group;
int i, j, k, elem, n_bnd, n_out;
int *n_domain = NULL;
int **domain = NULL;
int current_domain;
int counter[global_mesh->n_subdomain];
/*make list of elem to domain(both internal and boundary) */
n_domain = (int *)HECMW_calloc(global_mesh->n_elem, sizeof(int));
if (n_domain == NULL) {
HECMW_set_error(errno, "");
goto error;
}
/*count outer elem(boundary and not internal) */
for (i = 0; i < global_mesh->n_subdomain; i++) {
n_bnd = n_bnd_elist[2 * i];
n_out = n_bnd_elist[2 * i + 1] - n_bnd_elist[2 * i];
if (n_out == 0) continue;
for (j = 0; j < n_out; j++) {
elem = bnd_elist[i][n_bnd + j];
n_domain[elem - 1]++;
}
}
/*make list */
domain = (int **)HECMW_malloc(global_mesh->n_elem * sizeof(int *));
if (domain == NULL) {
HECMW_set_error(errno, "");
goto error;
}
for (i = 0; i < global_mesh->n_elem; i++) {
domain[i] = (int *)HECMW_malloc((n_domain[i] + 1) *
sizeof(int)); /*+1 means internal elem */
if (domain[i] == NULL) {
HECMW_set_error(errno, "");
goto error;
}
domain[i][0] = global_mesh->elem_ID[2 * i + 1];
n_domain[i] = 1;
}
for (i = 0; i < global_mesh->n_subdomain; i++) {
n_bnd = n_bnd_elist[2 * i];
n_out = n_bnd_elist[2 * i + 1] - n_bnd_elist[2 * i];
if (n_out == 0) continue;
for (j = 0; j < n_out; j++) {
elem = bnd_elist[i][n_bnd + j];
domain[elem - 1][n_domain[elem - 1]] = i;
n_domain[elem - 1]++;
}
}
/*make egroup index list */
egrp_idx = (int **)HECMW_malloc(global_mesh->n_subdomain * sizeof(int *));
if (egrp_idx == NULL) {
HECMW_set_error(errno, "");
goto error;
}
for (i = 0; i < global_mesh->n_subdomain; i++) {
egrp_idx[i] =
(int *)HECMW_calloc((elem_group_global->n_grp + 1), sizeof(int));
if (egrp_idx[i] == NULL) {
HECMW_set_error(errno, "");
goto error;
}
}
for (i = 0; i < elem_group_global->n_grp; i++) { /*skip group "ALL" */
for (j = 0; j < global_mesh->n_subdomain; j++) {
egrp_idx[j][i + 1] = egrp_idx[j][i];
}
if (elem_group_global->grp_index[i + 1] - elem_group_global->grp_index[i] ==
global_mesh->n_elem) {
continue;
}
for (j = elem_group_global->grp_index[i];
j < elem_group_global->grp_index[i + 1]; j++) {
elem = elem_group_global->grp_item[j];
for (k = 0; k < n_domain[elem - 1]; k++) {
current_domain = domain[elem - 1][k];
egrp_idx[current_domain][i + 1]++;
}
}
}
/*make egroup item list */
egrp_item = (int **)HECMW_malloc(global_mesh->n_subdomain * sizeof(int *));
if (egrp_item == NULL) {
HECMW_set_error(errno, "");
goto error;
}
for (i = 0; i < global_mesh->n_subdomain; i++) {
egrp_item[i] = (int *)HECMW_malloc(egrp_idx[i][elem_group_global->n_grp] *
sizeof(int));
if (egrp_item[i] == NULL) {
HECMW_set_error(errno, "");
goto error;
}
counter[i] = 0;
}
for (i = 0; i < elem_group_global->n_grp; i++) { /*skip group "ALL" */
if (elem_group_global->grp_index[i + 1] - elem_group_global->grp_index[i] ==
global_mesh->n_elem) {
continue;
}
for (j = elem_group_global->grp_index[i];
j < elem_group_global->grp_index[i + 1]; j++) {
elem = elem_group_global->grp_item[j];
for (k = 0; k < n_domain[elem - 1]; k++) {
current_domain = domain[elem - 1][k];
egrp_item[current_domain][counter[current_domain]] = elem;
counter[current_domain]++;
}
}
}
for (i = 0; i < global_mesh->n_elem; i++) {
HECMW_free(domain[i]);
}
HECMW_free(n_domain);
HECMW_free(domain);
return RTC_NORMAL;
error:
return RTC_ERROR;
}
static int spdup_makelist_main(const struct hecmwST_local_mesh *global_mesh) {
int rtc;
rtc = spdup_init_list(global_mesh);
if (rtc != RTC_NORMAL) goto error;
rtc = spdup_make_list(global_mesh);
if (rtc != RTC_NORMAL) goto error;
rtc = spdup_make_node_grouplist(global_mesh);
if (rtc != RTC_NORMAL) goto error;
rtc = spdup_make_element_grouplist(global_mesh);
if (rtc != RTC_NORMAL) goto error;
return RTC_NORMAL;
error:
return RTC_ERROR;
}
static void spdup_freelist(const struct hecmwST_local_mesh *global_mesh) {
int i;
HECMW_free(n_int_nlist);
HECMW_free(n_bnd_nlist);
HECMW_free(n_int_elist);
HECMW_free(n_bnd_elist);
for (i = 0; i < global_mesh->n_subdomain; i++) {
HECMW_free(int_nlist[i]);
HECMW_free(bnd_nlist[i]);
HECMW_free(int_elist[i]);
HECMW_free(bnd_elist[i]);
HECMW_free(ngrp_idx[i]);
HECMW_free(ngrp_item[i]);
HECMW_free(egrp_idx[i]);
HECMW_free(egrp_item[i]);
}
HECMW_free(int_nlist);
HECMW_free(bnd_nlist);
HECMW_free(int_elist);
HECMW_free(bnd_elist);
HECMW_free(ngrp_idx);
HECMW_free(ngrp_item);
HECMW_free(egrp_idx);
HECMW_free(egrp_item);
}
static int is_spdup_available(const struct hecmwST_local_mesh *global_mesh) {
return global_mesh->hecmw_flag_parttype == HECMW_FLAG_PARTTYPE_NODEBASED &&
global_mesh->hecmw_flag_partdepth == 1 &&
global_mesh->mpc->n_mpc == 0 && global_mesh->contact_pair->n_pair == 0;
}
/*================================================================================================*/
static char *get_dist_file_name(char *header, int domain, char *fname) {
char s_domain[HECMW_NAME_LEN + 1];
sprintf(s_domain, "%d", domain);
strcpy(fname, header);
strcat(fname, ".");
strcat(fname, s_domain);
return fname;
}
static void free_link_list(struct link_unit *llist) {
struct link_unit *p, *q;
for (p = llist; p; p = q) {
q = p->next;
HECMW_free(p);
}
llist = NULL;
}
/*================================================================================================*/
static int init_struct_global(struct hecmwST_local_mesh *local_mesh) {
if (local_mesh == NULL) {
HECMW_set_error(HECMW_PART_E_INV_ARG, "\'local_mesh\' is NULL");
goto error;
}
memset(local_mesh->gridfile, 0, HECMW_NAME_LEN + 1);
local_mesh->hecmw_n_file = 0;
local_mesh->files = NULL;
memset(local_mesh->header, 0, HECMW_HEADER_LEN + 1);
local_mesh->hecmw_flag_adapt = 0;
local_mesh->hecmw_flag_initcon = 0;
local_mesh->hecmw_flag_parttype = 0;
local_mesh->hecmw_flag_partdepth = 0;
local_mesh->hecmw_flag_version = 0;
local_mesh->hecmw_flag_partcontact = 0;
local_mesh->zero_temp = 0.0;
return RTC_NORMAL;
error:
return RTC_ERROR;
}
static int init_struct_node(struct hecmwST_local_mesh *local_mesh) {
if (local_mesh == NULL) {
HECMW_set_error(HECMW_PART_E_INV_ARG, "\'local_mesh\' is NULL");
goto error;
}
local_mesh->n_node = 0;
local_mesh->n_node_gross = 0;
local_mesh->nn_internal = 0;
local_mesh->node_internal_list = NULL;
local_mesh->node = NULL;
local_mesh->node_ID = NULL;
local_mesh->global_node_ID = NULL;
local_mesh->n_dof = 0;
local_mesh->n_dof_grp = 0;
local_mesh->node_dof_index = NULL;
local_mesh->node_dof_item = NULL;
local_mesh->node_val_index = NULL;
local_mesh->node_val_item = NULL;
local_mesh->node_init_val_index = NULL;
local_mesh->node_init_val_item = NULL;
return RTC_NORMAL;
error:
return RTC_ERROR;
}
static int init_struct_elem(struct hecmwST_local_mesh *local_mesh) {
if (local_mesh == NULL) {
HECMW_set_error(HECMW_PART_E_INV_ARG, "\'local_mesh\' is NULL");
goto error;
}
local_mesh->n_elem = 0;
local_mesh->n_elem_gross = 0;
local_mesh->ne_internal = 0;
local_mesh->elem_internal_list = NULL;
local_mesh->elem_ID = NULL;
local_mesh->global_elem_ID = NULL;
local_mesh->n_elem_type = 0;
local_mesh->elem_type = NULL;
local_mesh->elem_type_index = NULL;
local_mesh->elem_type_item = NULL;
local_mesh->elem_node_index = NULL;
local_mesh->elem_node_item = NULL;
local_mesh->section_ID = NULL;
local_mesh->n_elem_mat_ID = 0;
local_mesh->elem_mat_ID_index = NULL;
local_mesh->elem_mat_ID_item = NULL;
local_mesh->elem_mat_int_index = NULL;
local_mesh->elem_mat_int_val = NULL;
local_mesh->elem_val_index = NULL;
local_mesh->elem_val_item = NULL;
return RTC_NORMAL;
error:
return RTC_ERROR;
}
static int init_struct_comm(struct hecmwST_local_mesh *local_mesh) {
if (local_mesh == NULL) {
HECMW_set_error(HECMW_PART_E_INV_ARG, "\'local_mesh\' is NULL");
goto error;
}
local_mesh->zero = 0;
local_mesh->PETOT = 0;
local_mesh->PEsmpTOT = 0;
local_mesh->my_rank = 0;
local_mesh->errnof = 0;
local_mesh->n_subdomain = 0;
local_mesh->n_neighbor_pe = 0;
local_mesh->neighbor_pe = NULL;
local_mesh->import_index = NULL;
local_mesh->import_item = NULL;
local_mesh->export_index = NULL;
local_mesh->export_item = NULL;
local_mesh->shared_index = NULL;
local_mesh->shared_item = NULL;
return RTC_NORMAL;
error:
return RTC_ERROR;
}
static int init_struct_adapt(struct hecmwST_local_mesh *local_mesh) {
if (local_mesh == NULL) {
HECMW_set_error(HECMW_PART_E_INV_ARG, "\'local_mesh\' is NULL");
goto error;
}
local_mesh->coarse_grid_level = 0;
local_mesh->n_adapt = 0;
local_mesh->when_i_was_refined_node = NULL;
local_mesh->when_i_was_refined_elem = NULL;
local_mesh->adapt_parent_type = NULL;
local_mesh->adapt_type = NULL;
local_mesh->adapt_level = NULL;
local_mesh->adapt_parent = NULL;
local_mesh->adapt_children_index = NULL;
local_mesh->adapt_children_item = NULL;
return RTC_NORMAL;
error:
return RTC_ERROR;
}
static int init_struct_sect(struct hecmwST_local_mesh *local_mesh) {
if (local_mesh == NULL) {
HECMW_set_error(HECMW_PART_E_INV_ARG, "\'local_mesh\' is NULL");
goto error;
}
if (local_mesh->section == NULL) {
HECMW_set_error(HECMW_PART_E_INV_ARG, "\'local_mesh->section\' is NULL");
goto error;
}
local_mesh->section->n_sect = 0;
local_mesh->section->sect_type = NULL;
local_mesh->section->sect_opt = NULL;
local_mesh->section->sect_mat_ID_index = NULL;
local_mesh->section->sect_mat_ID_item = NULL;
local_mesh->section->sect_I_index = NULL;
local_mesh->section->sect_I_item = NULL;
local_mesh->section->sect_R_index = NULL;
local_mesh->section->sect_R_item = NULL;
return RTC_NORMAL;
error:
return RTC_ERROR;
}
static int init_struct_mat(struct hecmwST_local_mesh *local_mesh) {
if (local_mesh == NULL) {
HECMW_set_error(HECMW_PART_E_INV_ARG, "\'local_mesh\' is NULL");
goto error;
}
if (local_mesh->material == NULL) {
HECMW_set_error(HECMW_PART_E_INV_ARG, "\'local_mesh->material\' is NULL");
goto error;
}
local_mesh->material->n_mat = 0;
local_mesh->material->n_mat_item = 0;
local_mesh->material->n_mat_subitem = 0;
local_mesh->material->n_mat_table = 0;
local_mesh->material->mat_name = NULL;
local_mesh->material->mat_item_index = NULL;
local_mesh->material->mat_subitem_index = NULL;
local_mesh->material->mat_table_index = NULL;
local_mesh->material->mat_val = NULL;
local_mesh->material->mat_temp = NULL;
return RTC_NORMAL;
error:
return RTC_ERROR;
}
static int init_struct_mpc(struct hecmwST_local_mesh *local_mesh) {
if (local_mesh == NULL) {
HECMW_set_error(HECMW_PART_E_INV_ARG, "\'local_mesh\' is NULL");
return -1;
}
if (local_mesh->mpc == NULL) {
HECMW_set_error(HECMW_PART_E_INV_ARG, "\'local_mesh->mpc\' is NULL");
goto error;
}
local_mesh->mpc->n_mpc = 0;
local_mesh->mpc->mpc_index = NULL;
local_mesh->mpc->mpc_item = NULL;
local_mesh->mpc->mpc_dof = NULL;
local_mesh->mpc->mpc_val = NULL;
local_mesh->mpc->mpc_const = NULL;
return RTC_NORMAL;
error:
return RTC_ERROR;
}
static int init_struct_amp(struct hecmwST_local_mesh *local_mesh) {
if (local_mesh == NULL) {
HECMW_set_error(HECMW_PART_E_INV_ARG, "\'local_mesh\' is NULL");
goto error;
}
if (local_mesh->amp == NULL) {
HECMW_set_error(HECMW_PART_E_INV_ARG, "\'local_mesh->amp\' is NULL");
goto error;
}
local_mesh->amp->n_amp = 0;
local_mesh->amp->amp_name = NULL;
local_mesh->amp->amp_type_definition = NULL;
local_mesh->amp->amp_type_time = NULL;
local_mesh->amp->amp_type_value = NULL;
local_mesh->amp->amp_index = NULL;
local_mesh->amp->amp_val = NULL;
local_mesh->amp->amp_table = NULL;
return RTC_NORMAL;
error:
return RTC_ERROR;
}
static int init_struct_node_grp(struct hecmwST_local_mesh *local_mesh) {
if (local_mesh == NULL) {
HECMW_set_error(HECMW_PART_E_INV_ARG, "\'local_mesh\' is NULL");
goto error;
}
if (local_mesh->node_group == NULL) {
HECMW_set_error(HECMW_PART_E_INV_ARG, "\'local_mesh->node_group\' is NULL");
goto error;
}
local_mesh->node_group->n_grp = 0;
local_mesh->node_group->grp_name = NULL;
local_mesh->node_group->grp_index = NULL;
local_mesh->node_group->grp_item = NULL;
local_mesh->node_group->n_bc = 0;
local_mesh->node_group->bc_grp_ID = 0;
local_mesh->node_group->bc_grp_type = 0;
local_mesh->node_group->bc_grp_index = 0;
local_mesh->node_group->bc_grp_dof = 0;
local_mesh->node_group->bc_grp_val = 0;
return RTC_NORMAL;
error:
return RTC_ERROR;
}
static int init_struct_elem_grp(struct hecmwST_local_mesh *local_mesh) {
if (local_mesh == NULL) {
HECMW_set_error(HECMW_PART_E_INV_ARG, "\'local_mesh\' is NULL");
goto error;
}
if (local_mesh->elem_group == NULL) {
HECMW_set_error(HECMW_PART_E_INV_ARG, "\'local_mesh->elem_group\' is NULL");
goto error;
}
local_mesh->elem_group->n_grp = 0;
local_mesh->elem_group->grp_name = NULL;
local_mesh->elem_group->grp_index = NULL;
local_mesh->elem_group->grp_item = NULL;
local_mesh->elem_group->n_bc = 0;
local_mesh->elem_group->bc_grp_ID = NULL;
local_mesh->elem_group->bc_grp_type = NULL;
local_mesh->elem_group->bc_grp_index = NULL;
local_mesh->elem_group->bc_grp_val = NULL;
return RTC_NORMAL;
error:
return RTC_ERROR;
}
static int init_struct_surf_grp(struct hecmwST_local_mesh *local_mesh) {
if (local_mesh == NULL) {
HECMW_set_error(HECMW_PART_E_INV_ARG, "\'local_mesh\' is NULL");
goto error;
}
if (local_mesh->surf_group == NULL) {
HECMW_set_error(HECMW_PART_E_INV_ARG, "\'local_mesh->surf_group\' is NULL");
goto error;
}
local_mesh->surf_group->n_grp = 0;
local_mesh->surf_group->grp_name = NULL;
local_mesh->surf_group->grp_index = NULL;
local_mesh->surf_group->grp_item = NULL;
local_mesh->surf_group->n_bc = 0;
local_mesh->surf_group->bc_grp_ID = NULL;
local_mesh->surf_group->bc_grp_type = NULL;
local_mesh->surf_group->bc_grp_index = NULL;
local_mesh->surf_group->bc_grp_val = NULL;
return RTC_NORMAL;
error:
return RTC_ERROR;
}
static int init_struct_contact_pair(struct hecmwST_local_mesh *local_mesh) {
if (local_mesh == NULL) {
HECMW_set_error(HECMW_PART_E_INV_ARG, "\'local_mesh\' is NULL");
goto error;
}
if (local_mesh->contact_pair == NULL) {
HECMW_set_error(HECMW_PART_E_INV_ARG,
"\'local_mesh->contact_pair\' is NULL");
goto error;
}
local_mesh->contact_pair->n_pair = 0;
local_mesh->contact_pair->name = NULL;
local_mesh->contact_pair->type = NULL;
local_mesh->contact_pair->slave_grp_id = NULL;
local_mesh->contact_pair->slave_orisgrp_id = NULL;
local_mesh->contact_pair->master_grp_id = NULL;
return RTC_NORMAL;
error:
return RTC_ERROR;
}
/*================================================================================================*/
static void clean_struct_global(struct hecmwST_local_mesh *local_mesh) {
if (local_mesh == NULL) return;
init_struct_global(local_mesh);
}
static void clean_struct_node(struct hecmwST_local_mesh *local_mesh) {
if (local_mesh == NULL) return;
if (local_mesh->node_internal_list) {
HECMW_free(local_mesh->node_internal_list);
}
if (local_mesh->node) {
HECMW_free(local_mesh->node);
}
if (local_mesh->node_ID) {
HECMW_free(local_mesh->node_ID);
}
if (local_mesh->global_node_ID) {
HECMW_free(local_mesh->global_node_ID);
}
if (local_mesh->node_dof_index) {
HECMW_free(local_mesh->node_dof_index);
}
if (local_mesh->node_init_val_index) {
HECMW_free(local_mesh->node_init_val_index);
}
if (local_mesh->node_init_val_item) {
HECMW_free(local_mesh->node_init_val_item);
}
init_struct_node(local_mesh);
}
static void clean_struct_elem(struct hecmwST_local_mesh *local_mesh) {
if (local_mesh == NULL) return;
if (local_mesh->elem_internal_list) {
HECMW_free(local_mesh->elem_internal_list);
}
if (local_mesh->elem_ID) {
HECMW_free(local_mesh->elem_ID);
}
if (local_mesh->global_elem_ID) {
HECMW_free(local_mesh->global_elem_ID);
}
if (local_mesh->elem_type) {
HECMW_free(local_mesh->elem_type);
}
if (local_mesh->elem_type_index) {
HECMW_free(local_mesh->elem_type_index);
}
if (local_mesh->elem_node_index) {
HECMW_free(local_mesh->elem_node_index);
}
if (local_mesh->elem_node_item) {
HECMW_free(local_mesh->elem_node_item);
}
if (local_mesh->section_ID) {
HECMW_free(local_mesh->section_ID);
}
if (local_mesh->elem_mat_ID_index) {
HECMW_free(local_mesh->elem_mat_ID_index);
}
if (local_mesh->elem_mat_ID_item) {
HECMW_free(local_mesh->elem_mat_ID_item);
}
init_struct_elem(local_mesh);
}
static void clean_struct_comm(struct hecmwST_local_mesh *local_mesh) {
if (local_mesh == NULL) return;
if (local_mesh->neighbor_pe) {
HECMW_free(local_mesh->neighbor_pe);
}
if (local_mesh->import_index) {
HECMW_free(local_mesh->import_index);
}
if (local_mesh->import_item) {
HECMW_free(local_mesh->import_item);
}
if (local_mesh->export_index) {
HECMW_free(local_mesh->export_index);
}
if (local_mesh->export_item) {
HECMW_free(local_mesh->export_item);
}
if (local_mesh->shared_index) {
HECMW_free(local_mesh->shared_index);
}
if (local_mesh->shared_item) {
HECMW_free(local_mesh->shared_item);
}
init_struct_comm(local_mesh);
}
static void clean_struct_adapt(struct hecmwST_local_mesh *local_mesh) {
if (local_mesh == NULL) return;
init_struct_adapt(local_mesh);
}
static void clean_struct_sect(struct hecmwST_local_mesh *local_mesh) {
if (local_mesh == NULL) return;
if (local_mesh->section == NULL) return;
init_struct_sect(local_mesh);
}
static void clean_struct_mat(struct hecmwST_local_mesh *local_mesh) {
if (local_mesh == NULL) return;
if (local_mesh->material == NULL) return;
init_struct_mat(local_mesh);
}
static void clean_struct_mpc(struct hecmwST_local_mesh *local_mesh) {
if (local_mesh == NULL) return;
if (local_mesh->mpc == NULL) return;
HECMW_free(local_mesh->mpc->mpc_index);
HECMW_free(local_mesh->mpc->mpc_item);
HECMW_free(local_mesh->mpc->mpc_dof);
HECMW_free(local_mesh->mpc->mpc_val);
HECMW_free(local_mesh->mpc->mpc_const);
init_struct_mpc(local_mesh);
}
static void clean_struct_amp(struct hecmwST_local_mesh *local_mesh) {
if (local_mesh == NULL) return;
if (local_mesh->amp == NULL) return;
init_struct_amp(local_mesh);
}
static void clean_struct_node_grp(struct hecmwST_local_mesh *local_mesh) {
if (local_mesh == NULL) return;
if (local_mesh->node_group == NULL) return;
if (local_mesh->node_group->grp_index) {
HECMW_free(local_mesh->node_group->grp_index);
}
if (local_mesh->node_group->grp_item) {
HECMW_free(local_mesh->node_group->grp_item);
}
init_struct_node_grp(local_mesh);
}
static void clean_struct_elem_grp(struct hecmwST_local_mesh *local_mesh) {
if (local_mesh == NULL) return;
if (local_mesh->elem_group == NULL) return;
if (local_mesh->elem_group->grp_index) {
HECMW_free(local_mesh->elem_group->grp_index);
}
if (local_mesh->elem_group->grp_item) {
HECMW_free(local_mesh->elem_group->grp_item);
}
init_struct_elem_grp(local_mesh);
}
static void clean_struct_surf_grp(struct hecmwST_local_mesh *local_mesh) {
if (local_mesh == NULL) return;
if (local_mesh->surf_group == NULL) return;
if (local_mesh->surf_group->grp_index) {
HECMW_free(local_mesh->surf_group->grp_index);
}
if (local_mesh->surf_group->grp_item) {
HECMW_free(local_mesh->surf_group->grp_item);
}
init_struct_surf_grp(local_mesh);
}
static void clean_struct_contact_pair(struct hecmwST_local_mesh *local_mesh) {
if (local_mesh == NULL) return;
if (local_mesh->contact_pair == NULL) return;
if (local_mesh->contact_pair->type) {
HECMW_free(local_mesh->contact_pair->type);
}
if (local_mesh->contact_pair->slave_grp_id) {
HECMW_free(local_mesh->contact_pair->slave_grp_id);
}
if (local_mesh->contact_pair->slave_orisgrp_id) {
HECMW_free(local_mesh->contact_pair->slave_orisgrp_id);
}
if (local_mesh->contact_pair->master_grp_id) {
HECMW_free(local_mesh->contact_pair->master_grp_id);
}
init_struct_contact_pair(local_mesh);
}
static void clean_struct_local_mesh(struct hecmwST_local_mesh *local_mesh) {
if (local_mesh == NULL) return;
clean_struct_global(local_mesh);
clean_struct_node(local_mesh);
clean_struct_elem(local_mesh);
clean_struct_comm(local_mesh);
clean_struct_adapt(local_mesh);
clean_struct_sect(local_mesh);
clean_struct_mat(local_mesh);
clean_struct_mpc(local_mesh);
clean_struct_amp(local_mesh);
clean_struct_node_grp(local_mesh);
clean_struct_elem_grp(local_mesh);
clean_struct_surf_grp(local_mesh);
clean_struct_contact_pair(local_mesh);
}
/*- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
* - - - - - - - - - */
static int init_struct_result_data(struct hecmwST_result_data *result_data) {
if (result_data == NULL) {
HECMW_set_error(errno, "\'result_data\' is NULL");
goto error;
}
result_data->nn_dof = NULL;
result_data->node_label = NULL;
result_data->node_val_item = NULL;
result_data->ne_dof = NULL;
result_data->elem_label = NULL;
result_data->elem_val_item = NULL;
return RTC_NORMAL;
error:
return RTC_ERROR;
}
static void free_struct_result_data(struct hecmwST_result_data *result_data) {
int i;
if (result_data == NULL) return;
HECMW_free(result_data->nn_dof);
HECMW_free(result_data->ne_dof);
if (result_data->node_label) {
for (i = 0; i < result_data->nn_component; i++) {
HECMW_free(result_data->node_label[i]);
}
HECMW_free(result_data->node_label);
}
if (result_data->elem_label) {
for (i = 0; i < result_data->ne_component; i++) {
HECMW_free(result_data->elem_label[i]);
}
HECMW_free(result_data->elem_label);
}
HECMW_free(result_data->node_val_item);
HECMW_free(result_data->elem_val_item);
HECMW_free(result_data);
result_data = NULL;
}
/*================================================================================================*/
static int search_eqn_block_idx(const struct hecmwST_local_mesh *mesh) {
int i;
for (i = 0; i < mesh->node_group->n_grp; i++) {
if (!strcmp(mesh->node_group->grp_name[i], HECMW_PART_EQUATION_BLOCK_NAME))
return i;
}
return -1;
}
/*================================================================================================*/
static int quick_sort(int no, int n, double *arr, int *brr, int *istack) {
double a, atemp;
int b, btemp;
int i, ir, j, k, l;
int jstack = 0;
int nstack;
nstack = no;
l = 0;
ir = n - 1;
for (;;) {
if (ir - l < QSORT_LOWER) {
for (j = l + 1; j <= ir; j++) {
a = arr[j];
b = brr[j];
for (i = j - 1; i >= l; i--) {
if (arr[i] <= a) break;
arr[i + 1] = arr[i];
brr[i + 1] = brr[i];
}
arr[i + 1] = a;
brr[i + 1] = b;
}
if (!jstack) return 0;
ir = istack[jstack];
l = istack[jstack - 1];
jstack -= 2;
} else {
k = (l + ir) >> 1;
DSWAP(arr[k], arr[l + 1])
ISWAP(brr[k], brr[l + 1])
if (arr[l] > arr[ir]) {
DSWAP(arr[l], arr[ir])
ISWAP(brr[l], brr[ir])
}
if (arr[l + 1] > arr[ir]) {
DSWAP(arr[l + 1], arr[ir])
ISWAP(brr[l + 1], brr[ir])
}
if (arr[l] > arr[l + 1]) {
DSWAP(arr[l], arr[l + 1])
ISWAP(brr[l], brr[l + 1])
}
i = l + 1;
j = ir;
a = arr[l + 1];
b = brr[l + 1];
for (;;) {
do
i++;
while (arr[i] < a);
do
j--;
while (arr[j] > a);
if (j < i) break;
DSWAP(arr[i], arr[j])
ISWAP(brr[i], brr[j])
}
arr[l + 1] = arr[j];
arr[j] = a;
brr[l + 1] = brr[j];
brr[j] = b;
jstack += 2;
if (jstack > nstack) {
HECMW_set_error(HECMW_PART_E_STACK_OVERFLOW, "");
return -1;
}
if (ir - i + 1 >= j - l) {
istack[jstack] = ir;
istack[jstack - 1] = i;
ir = j - 1;
} else {
istack[jstack] = j - 1;
istack[jstack - 1] = l;
l = i;
}
}
}
}
/*- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
* - - - - - - - - - */
static int rcb_partition(int n, const double *coord, int *wnum,
const struct hecmw_part_cont_data *cont_data) {
double *value;
int *id, *stack;
int rtc;
int counter;
int i, j, k;
id = (int *)HECMW_malloc(sizeof(int) * n);
if (id == NULL) {
HECMW_set_error(errno, "");
goto error;
}
stack = (int *)HECMW_malloc(sizeof(int) * n);
if (stack == NULL) {
HECMW_set_error(errno, "");
goto error;
}
value = (double *)HECMW_malloc(sizeof(double) * n);
if (value == NULL) {
HECMW_set_error(errno, "");
goto error;
}
for (i = 0; i < cont_data->n_rcb_div; i++) {
for (j = 0; j < pow(2, i); j++) {
counter = 0;
switch (cont_data->rcb_axis[i]) {
case HECMW_PART_RCB_X_AXIS: /* X-axis */
for (k = 0; k < n; k++) {
if (wnum[2 * k + 1] == j) {
id[counter] = k;
value[counter] = coord[3 * k];
counter++;
}
}
break;
case HECMW_PART_RCB_Y_AXIS: /* Y-axis */
for (k = 0; k < n; k++) {
if (wnum[2 * k + 1] == j) {
id[counter] = k;
value[counter] = coord[3 * k + 1];
counter++;
}
}
break;
case HECMW_PART_RCB_Z_AXIS: /* Z-axis */
for (k = 0; k < n; k++) {
if (wnum[2 * k + 1] == j) {
id[counter] = k;
value[counter] = coord[3 * k + 2];
counter++;
}
}
break;
default:
HECMW_set_error(HECMW_PART_E_INVALID_RCB_DIR, "");
goto error;
}
/* quick sort */
rtc = quick_sort(n, counter, value, id, stack);
if (rtc != RTC_NORMAL) goto error;
/* belonging domain of node */
for (k = 0; k < counter * F_1_2; k++) {
wnum[2 * id[k] + 1] = j + (int)pow(2, i);
}
}
}
HECMW_free(id);
HECMW_free(stack);
HECMW_free(value);
return RTC_NORMAL;
error:
HECMW_free(id);
HECMW_free(stack);
HECMW_free(value);
return RTC_ERROR;
}
/*------------------------------------------------------------------------------------------------*/
static int calc_gravity(const struct hecmwST_local_mesh *global_mesh,
double *coord) {
double coord_x, coord_y, coord_z;
int node;
int js, je;
int i, j;
for (i = 0; i < global_mesh->n_elem; i++) {
js = global_mesh->elem_node_index[i];
je = global_mesh->elem_node_index[i + 1];
for (coord_x = 0.0, coord_y = 0.0, coord_z = 0.0, j = js; j < je; j++) {
node = global_mesh->elem_node_item[j];
coord_x += global_mesh->node[3 * (node - 1)];
coord_y += global_mesh->node[3 * (node - 1) + 1];
coord_z += global_mesh->node[3 * (node - 1) + 2];
}
coord[3 * i] = coord_x / (je - js);
coord[3 * i + 1] = coord_y / (je - js);
coord[3 * i + 2] = coord_z / (je - js);
}
return RTC_NORMAL;
}
static int rcb_partition_eb(struct hecmwST_local_mesh *global_mesh,
const struct hecmw_part_cont_data *cont_data) {
double *coord = NULL;
int rtc;
coord = (double *)HECMW_malloc(sizeof(double) * global_mesh->n_elem * 3);
if (coord == NULL) {
HECMW_set_error(errno, "");
goto error;
}
rtc = calc_gravity(global_mesh, coord);
if (rtc != RTC_NORMAL) goto error;
rtc = rcb_partition(global_mesh->n_elem, coord, global_mesh->elem_ID,
cont_data);
if (rtc != RTC_NORMAL) goto error;
HECMW_free(coord);
return RTC_NORMAL;
error:
HECMW_free(coord);
return RTC_ERROR;
}
/*================================================================================================*/
static int create_node_graph_link_list(
const struct hecmwST_local_mesh *global_mesh,
const struct hecmw_part_edge_data *edge_data, struct link_list **graph) {
int node1, node2;
long long int i;
for (i = 0; i < edge_data->n_edge; i++) {
node1 = edge_data->edge_node_item[2 * i];
node2 = edge_data->edge_node_item[2 * i + 1];
/* node 1 */
graph[node1 - 1]->last->next =
(struct link_unit *)HECMW_malloc(sizeof(struct link_unit));
if (graph[node1 - 1]->last->next == NULL) {
HECMW_set_error(errno, "");
goto error;
}
graph[node1 - 1]->n += 1;
graph[node1 - 1]->last->next->id = node2;
graph[node1 - 1]->last->next->next = NULL;
graph[node1 - 1]->last = graph[node1 - 1]->last->next;
/* node 2 */
graph[node2 - 1]->last->next =
(struct link_unit *)HECMW_malloc(sizeof(struct link_unit));
if (graph[node2 - 1]->last->next == NULL) {
HECMW_set_error(errno, "");
goto error;
}
graph[node2 - 1]->n += 1;
graph[node2 - 1]->last->next->id = node1;
graph[node2 - 1]->last->next->next = NULL;
graph[node2 - 1]->last = graph[node2 - 1]->last->next;
}
return RTC_NORMAL;
error:
return RTC_ERROR;
}
static int create_node_graph_compress(
const struct hecmwST_local_mesh *global_mesh, struct link_list **graph,
int *node_graph_index, int *node_graph_item) {
int counter;
int i, j;
struct link_unit *p;
for (counter = 0, i = 0; i < global_mesh->n_node; i++) {
node_graph_index[i + 1] = node_graph_index[i] + graph[i]->n;
for (p = graph[i]->list, j = 0; j < graph[i]->n; j++) {
p = p->next;
node_graph_item[counter++] = p->id - 1;
}
}
return RTC_NORMAL;
}
static int create_node_graph(const struct hecmwST_local_mesh *global_mesh,
const struct hecmw_part_edge_data *edge_data,
int *node_graph_index, int *node_graph_item) {
struct link_list **graph = NULL;
int rtc;
int i;
graph = (struct link_list **)HECMW_malloc(sizeof(struct link_list *) *
global_mesh->n_node);
if (graph == NULL) {
HECMW_set_error(errno, "");
goto error;
} else {
for (i = 0; i < global_mesh->n_node; i++) {
graph[i] = NULL;
}
}
for (i = 0; i < global_mesh->n_node; i++) {
graph[i] = (struct link_list *)HECMW_malloc(sizeof(struct link_list));
if (graph[i] == NULL) {
HECMW_set_error(errno, "");
goto error;
} else {
graph[i]->list = NULL;
}
}
for (i = 0; i < global_mesh->n_node; i++) {
graph[i]->list = (struct link_unit *)HECMW_malloc(sizeof(struct link_unit));
if (graph[i]->list == NULL) {
HECMW_set_error(errno, "");
goto error;
} else {
graph[i]->n = 0;
graph[i]->list->next = NULL;
graph[i]->last = graph[i]->list;
}
}
rtc = create_node_graph_link_list(global_mesh, edge_data, graph);
if (rtc != RTC_NORMAL) goto error;
rtc = create_node_graph_compress(global_mesh, graph, node_graph_index,
node_graph_item);
if (rtc != RTC_NORMAL) goto error;
for (i = 0; i < global_mesh->n_node; i++) {
free_link_list(graph[i]->list);
HECMW_free(graph[i]);
}
HECMW_free(graph);
return RTC_NORMAL;
error:
if (graph) {
for (i = 0; i < global_mesh->n_node; i++) {
if (graph[i]) {
free_link_list(graph[i]->list);
HECMW_free(graph[i]);
}
}
HECMW_free(graph);
}
return RTC_ERROR;
}
/*------------------------------------------------------------------------------------------------*/
static int set_node_belong_elem(const struct hecmwST_local_mesh *global_mesh,
struct hecmw_part_node_data *node_data) {
int node, counter;
struct link_list **node_list = NULL;
struct link_unit *p;
int size;
int i, j;
node_data->node_elem_index = NULL;
node_data->node_elem_item = NULL;
node_list = (struct link_list **)HECMW_malloc(sizeof(struct link_list *) *
global_mesh->n_node);
if (node_list == NULL) {
HECMW_set_error(errno, "");
goto error;
} else {
for (i = 0; i < global_mesh->n_node; i++) {
node_list[i] = NULL;
}
}
for (i = 0; i < global_mesh->n_node; i++) {
node_list[i] = (struct link_list *)HECMW_malloc(sizeof(struct link_list));
if (node_list[i] == NULL) {
HECMW_set_error(errno, "");
goto error;
} else {
node_list[i]->list = NULL;
}
}
for (i = 0; i < global_mesh->n_node; i++) {
node_list[i]->list =
(struct link_unit *)HECMW_malloc(sizeof(struct link_unit));
if (node_list[i]->list == NULL) {
HECMW_set_error(errno, "");
goto error;
} else {
node_list[i]->n = 0;
node_list[i]->list->next = NULL;
node_list[i]->last = node_list[i]->list;
}
}
for (i = 0; i < global_mesh->n_elem; i++) {
for (j = global_mesh->elem_node_index[i];
j < global_mesh->elem_node_index[i + 1]; j++) {
node = global_mesh->elem_node_item[j];
size = sizeof(struct link_list);
node_list[node - 1]->last->next = (struct link_unit *)HECMW_malloc(size);
if (node_list[node - 1]->last->next == NULL) {
HECMW_set_error(errno, "");
goto error;
}
node_list[node - 1]->last = node_list[node - 1]->last->next;
node_list[node - 1]->last->id = i + 1;
node_list[node - 1]->last->next = NULL;
node_list[node - 1]->n += 1;
}
}
node_data->node_elem_index =
(int *)HECMW_calloc(global_mesh->n_node + 1, sizeof(int));
if (node_data->node_elem_index == NULL) {
HECMW_set_error(errno, "");
goto error;
}
for (i = 0; i < global_mesh->n_node; i++) {
node_data->node_elem_index[i + 1] =
node_data->node_elem_index[i] + node_list[i]->n;
}
size = sizeof(int) * node_data->node_elem_index[global_mesh->n_node];
node_data->node_elem_item = (int *)HECMW_malloc(size);
if (node_data->node_elem_item == NULL) {
HECMW_set_error(errno, "");
goto error;
}
for (counter = 0, i = 0; i < global_mesh->n_node; i++) {
for (p = node_list[i]->list, j = 0; j < node_list[i]->n; j++) {
p = p->next;
node_data->node_elem_item[counter++] = p->id;
}
HECMW_assert(counter == node_data->node_elem_index[i + 1]);
}
for (i = 0; i < global_mesh->n_node; i++) {
free_link_list(node_list[i]->list);
HECMW_free(node_list[i]);
}
HECMW_free(node_list);
return RTC_NORMAL;
error:
if (node_list) {
for (i = 0; i < global_mesh->n_node; i++) {
if (node_list[i]) {
free_link_list(node_list[i]->list);
HECMW_free(node_list[i]);
}
}
HECMW_free(node_list);
}
HECMW_free(node_data->node_elem_index);
HECMW_free(node_data->node_elem_item);
node_data->node_elem_index = NULL;
node_data->node_elem_item = NULL;
return RTC_ERROR;
}
static int create_elem_graph_link_list(
const struct hecmwST_local_mesh *global_mesh,
const struct hecmw_part_node_data *node_data, struct link_list **graph) {
char *elem_flag = NULL;
int elem, node;
int size;
int counter;
int i, j, k;
elem_flag = (char *)HECMW_malloc(sizeof(char) * global_mesh->n_elem);
if (elem_flag == NULL) {
HECMW_set_error(errno, "");
goto error;
}
for (counter = 0, i = 0; i < global_mesh->n_elem; i++) {
memset(elem_flag, 0, sizeof(char) * global_mesh->n_elem);
MASK_BIT(elem_flag[i], MASK);
for (j = global_mesh->elem_node_index[i];
j < global_mesh->elem_node_index[i + 1]; j++) {
node = global_mesh->elem_node_item[j];
for (k = node_data->node_elem_index[node - 1];
k < node_data->node_elem_index[node]; k++) {
elem = node_data->node_elem_item[k];
if (!EVAL_BIT(elem_flag[elem - 1], MASK)) {
MASK_BIT(elem_flag[elem - 1], MASK);
size = sizeof(struct link_unit);
graph[i]->last->next = (struct link_unit *)HECMW_malloc(size);
if (graph[i]->last->next == NULL) {
HECMW_set_error(errno, "");
goto error;
}
graph[i]->n += 1;
graph[i]->last->next->id = elem;
graph[i]->last->next->next = NULL;
graph[i]->last = graph[i]->last->next;
counter++;
}
}
}
}
HECMW_free(elem_flag);
return counter;
error:
HECMW_free(elem_flag);
return -1;
}
static int create_elem_graph_compress(
const struct hecmwST_local_mesh *global_mesh, struct link_list **graph,
int *elem_graph_index, int *elem_graph_item) {
struct link_unit *p;
int counter;
int i, j;
for (counter = 0, i = 0; i < global_mesh->n_elem; i++) {
elem_graph_index[i + 1] = elem_graph_index[i] + graph[i]->n;
for (p = graph[i]->list, j = 0; j < graph[i]->n; j++) {
p = p->next;
elem_graph_item[counter++] = p->id - 1;
}
}
HECMW_assert(elem_graph_index[global_mesh->n_elem] == counter);
return RTC_NORMAL;
}
static int *create_elem_graph(const struct hecmwST_local_mesh *global_mesh,
int *elem_graph_index) {
struct hecmw_part_node_data *node_data = NULL;
struct link_list **graph = NULL;
int *elem_graph_item = NULL;
int n_graph;
int rtc;
int i;
node_data = (struct hecmw_part_node_data *)HECMW_malloc(
sizeof(struct hecmw_part_node_data));
if (node_data == NULL) {
HECMW_set_error(errno, "");
goto error;
} else {
node_data->node_elem_index = NULL;
node_data->node_elem_item = NULL;
}
rtc = set_node_belong_elem(global_mesh, node_data);
if (rtc != RTC_NORMAL) goto error;
graph = (struct link_list **)HECMW_malloc(sizeof(struct link_list *) *
global_mesh->n_elem);
if (graph == NULL) {
HECMW_set_error(errno, "");
goto error;
} else {
for (i = 0; i < global_mesh->n_elem; i++) {
graph[i] = NULL;
}
}
for (i = 0; i < global_mesh->n_elem; i++) {
graph[i] = (struct link_list *)HECMW_malloc(sizeof(struct link_list));
if (graph[i] == NULL) {
HECMW_set_error(errno, "");
goto error;
} else {
graph[i]->list = NULL;
}
}
for (i = 0; i < global_mesh->n_elem; i++) {
graph[i]->list = (struct link_unit *)HECMW_malloc(sizeof(struct link_unit));
if (graph[i]->list == NULL) {
HECMW_set_error(errno, "");
goto error;
} else {
graph[i]->n = 0;
graph[i]->list->next = NULL;
graph[i]->last = graph[i]->list;
}
}
n_graph = create_elem_graph_link_list(global_mesh, node_data, graph);
if (n_graph < 0) goto error;
elem_graph_item = (int *)HECMW_malloc(sizeof(int) * n_graph);
if (elem_graph_item == NULL) {
HECMW_set_error(errno, "");
goto error;
}
rtc = create_elem_graph_compress(global_mesh, graph, elem_graph_index,
elem_graph_item);
if (rtc != RTC_NORMAL) goto error;
HECMW_free(node_data->node_elem_index);
HECMW_free(node_data->node_elem_item);
HECMW_free(node_data);
for (i = 0; i < global_mesh->n_elem; i++) {
free_link_list(graph[i]->list);
HECMW_free(graph[i]);
}
HECMW_free(graph);
return elem_graph_item;
error:
if (node_data) {
HECMW_free(node_data->node_elem_index);
HECMW_free(node_data->node_elem_item);
HECMW_free(node_data);
}
if (graph) {
for (i = 0; i < global_mesh->n_elem; i++) {
if (graph[i]) {
free_link_list(graph[i]->list);
HECMW_free(graph[i]);
}
}
HECMW_free(graph);
}
HECMW_free(elem_graph_item);
return NULL;
}
/*- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
* - - - - - - - - - */
static int pmetis_interface(const int n_vertex, const int n_domain, int *xadj,
int *adjncy, int *part) {
int edgecut = 0; /* number of edge-cut */
#ifdef HECMW_PART_WITH_METIS
int n = n_vertex; /* number of vertices */
int *vwgt = NULL; /* weight for vertices */
int *adjwgt = NULL; /* weight for edges */
int nparts = n_domain; /* number of sub-domains */
#if defined(METIS_VER_MAJOR) && (METIS_VER_MAJOR == 5)
int ncon = 1; /* number of balancing constraints */
int *vsize = NULL;
real_t *tpwgts = NULL;
real_t *ubvec = NULL;
int *options = NULL;
HECMW_log(HECMW_LOG_DEBUG, "Entering pmetis(v5)...\n");
METIS_PartGraphRecursive(&n, &ncon, xadj, adjncy, vwgt, vsize, adjwgt,
&nparts, tpwgts, ubvec, options, &edgecut, part);
HECMW_log(HECMW_LOG_DEBUG, "Returned from pmetis(v5)\n");
#else
int wgtflag = 0; /* flag of weight for edges */
int numflag = 0; /* flag of stating number of index */
int options[5] = {0, 0, 0, 0, 0}; /* options for pMETIS */
HECMW_log(HECMW_LOG_DEBUG, "Entering pmetis(v4)...\n");
METIS_PartGraphRecursive(&n, xadj, adjncy, vwgt, adjwgt, &wgtflag, &numflag,
&nparts, options, &edgecut, part);
HECMW_log(HECMW_LOG_DEBUG, "Returned from pmetis(v4)\n");
#endif
#endif
return edgecut;
}
static int kmetis_interface(const int n_vertex, const int n_domain, int *xadj,
int *adjncy, int *part) {
int edgecut = 0; /* number of edge-cut */
#ifdef HECMW_PART_WITH_METIS
int n = n_vertex; /* number of vertices */
int *vwgt = NULL; /* weight for vertices */
int *adjwgt = NULL; /* weight for edges */
int nparts = n_domain; /* number of sub-domains */
#if defined(METIS_VER_MAJOR) && (METIS_VER_MAJOR == 5)
int ncon = 1; /* number of balancing constraints */
int *vsize = NULL;
real_t *tpwgts = NULL;
real_t *ubvec = NULL;
int *options = NULL;
HECMW_log(HECMW_LOG_DEBUG, "Entering kmetis(v5)...\n");
METIS_PartGraphKway(&n, &ncon, xadj, adjncy, vwgt, vsize, adjwgt, &nparts,
tpwgts, ubvec, options, &edgecut, part);
HECMW_log(HECMW_LOG_DEBUG, "Returned from kmetis(v5)\n");
#else
int wgtflag = 0; /* flag of weight for edges */
int numflag = 0; /* flag of stating number of index */
int options[5] = {0, 0, 0, 0, 0}; /* options for kMETIS */
HECMW_log(HECMW_LOG_DEBUG, "Entering kmetis(v4)...\n");
METIS_PartGraphKway(&n, xadj, adjncy, vwgt, adjwgt, &wgtflag, &numflag,
&nparts, options, &edgecut, part);
HECMW_log(HECMW_LOG_DEBUG, "Returned from kmetis(v4)\n");
#endif
#endif
return edgecut;
}
static int pmetis_interface_with_weight(int n_vertex, int ncon, int n_domain,
const int *xadj, const int *adjncy,
const int *vwgt, int *part) {
int edgecut = 0; /* number of edge-cut */
#ifdef HECMW_PART_WITH_METIS
int n = n_vertex; /* number of vertices */
int *adjwgt = NULL; /* weight for edges */
int nparts = n_domain; /* number of sub-domains */
#if defined(METIS_VER_MAJOR) && (METIS_VER_MAJOR == 5)
int *vsize = NULL;
real_t *tpwgts = NULL;
real_t *ubvec = NULL;
int *options = NULL;
HECMW_log(HECMW_LOG_DEBUG, "Entering pmetis(v5)...\n");
METIS_PartGraphRecursive(&n, &ncon, (int *)xadj, (int *)adjncy, (int *)vwgt,
vsize, adjwgt, &nparts, tpwgts, ubvec, options,
&edgecut, part);
HECMW_log(HECMW_LOG_DEBUG, "Returned from pmetis(v5)\n");
#else
int wgtflag = 0; /* flag of weight for edges */
int numflag = 0; /* flag of stating number of index */
int options[5] = {0, 0, 0, 0, 0}; /* options for pMETIS */
if (vwgt != NULL) wgtflag = 2;
HECMW_log(HECMW_LOG_DEBUG, "Entering pmetis(v4)...\n");
if (ncon == 1) {
METIS_PartGraphRecursive(&n, (int *)xadj, (int *)adjncy, (int *)vwgt,
adjwgt, &wgtflag, &numflag, &nparts, options,
&edgecut, part);
} else {
METIS_mCPartGraphRecursive(&n, &ncon, (int *)xadj, (int *)adjncy,
(int *)vwgt, adjwgt, &wgtflag, &numflag, &nparts,
options, &edgecut, part);
}
HECMW_log(HECMW_LOG_DEBUG, "Returned from pmetis(v4)\n");
#endif
#endif
return edgecut;
}
static int kmetis_interface_with_weight(int n_vertex, int ncon, int n_domain,
const int *xadj, const int *adjncy,
const int *vwgt, int *part) {
int edgecut = 0; /* number of edge-cut */
#ifdef HECMW_PART_WITH_METIS
int n = n_vertex; /* number of vertices */
int *adjwgt = NULL; /* weight for edges */
int nparts = n_domain; /* number of sub-domains */
#if defined(METIS_VER_MAJOR) && (METIS_VER_MAJOR == 5)
int *vsize = NULL;
real_t *tpwgts = NULL;
real_t *ubvec = NULL;
int *options = NULL;
HECMW_log(HECMW_LOG_DEBUG, "Entering kmetis(v5)...\n");
METIS_PartGraphKway(&n, &ncon, (int *)xadj, (int *)adjncy, (int *)vwgt, vsize,
adjwgt, &nparts, tpwgts, ubvec, options, &edgecut, part);
HECMW_log(HECMW_LOG_DEBUG, "Returned from kmetis(v5)\n");
#else
int wgtflag = 0; /* flag of weight for edges */
int numflag = 0; /* flag of stating number of index */
float *ubvec = NULL;
int options[5] = {0, 0, 0, 0, 0}; /* options for kMETIS */
if (vwgt != NULL) wgtflag = 2;
if (ncon > 1) {
ubvec = (float *)HECMW_malloc(ncon * sizeof(float));
if (ubvec == NULL) {
HECMW_set_error(errno, "");
return -1;
}
}
HECMW_log(HECMW_LOG_DEBUG, "Entering kmetis(v4)...\n");
if (ncon == 1) {
METIS_PartGraphKway(&n, (int *)xadj, (int *)adjncy, (int *)vwgt, adjwgt,
&wgtflag, &numflag, &nparts, options, &edgecut, part);
} else {
METIS_mCPartGraphKway(&n, &ncon, (int *)xadj, (int *)adjncy, (int *)vwgt,
adjwgt, &wgtflag, &numflag, &nparts, ubvec, options,
&edgecut, part);
}
HECMW_log(HECMW_LOG_DEBUG, "Returned from kmetis(v4)\n");
HECMW_free(ubvec);
#endif
#endif
return edgecut;
}
static int contact_agg_mark_node_group(int *mark,
struct hecmwST_local_mesh *global_mesh,
int gid, int agg_id, int *agg_dup) {
struct hecmwST_node_grp *ngrp = global_mesh->node_group;
int istart, iend, i;
HECMW_assert(0 < gid && gid <= ngrp->n_grp);
istart = ngrp->grp_index[gid - 1];
iend = ngrp->grp_index[gid];
for (i = istart; i < iend; i++) {
int nid = ngrp->grp_item[i] - 1;
HECMW_assert(0 <= nid && nid < global_mesh->n_node);
if (0 <= mark[nid] && mark[nid] < agg_id) {
/* the node is included in some other contact pair */
if (*agg_dup == -1) {
*agg_dup = mark[nid];
} else if (mark[nid] != *agg_dup) {
fprintf(stderr,
"ERROR: node included in multiple node groups in different "
"contact pairs,\n"
" which is not supported by CONTACT=AGGREGATE\n");
HECMW_abort(HECMW_comm_get_comm());
}
}
mark[nid] = agg_id;
}
return RTC_NORMAL;
}
static int HECMW_get_num_surf_node(int etype, int sid) {
switch (etype) {
case HECMW_ETYPE_TET1:
case HECMW_ETYPE_PTT1:
return 3;
case HECMW_ETYPE_TET2:
case HECMW_ETYPE_PTT2:
return 6;
case HECMW_ETYPE_HEX1:
case HECMW_ETYPE_PTQ1:
return 4;
case HECMW_ETYPE_HEX2:
case HECMW_ETYPE_PTQ2:
return 8;
case HECMW_ETYPE_PRI1:
if (1 <= sid && sid <= 3) return 4;
if (4 <= sid && sid <= 5) return 3;
case HECMW_ETYPE_PRI2:
if (1 <= sid && sid <= 3) return 8;
if (4 <= sid && sid <= 5) return 6;
default:
fprintf(
stderr,
"ERROR: parallel contact analysis of elem type %d not supported\n",
etype);
return -1;
}
return -1;
}
static const int *HECMW_get_surf_node(int etype, int sid) {
HECMW_assert(0 < sid);
static const int elem_surf_tet1[4][3] = {
{1, 2, 3}, {0, 3, 2}, {0, 1, 3}, {0, 2, 1}};
static const int elem_surf_tet2[4][6] = {{1, 4, 2, 9, 3, 8},
{0, 7, 3, 9, 2, 5},
{0, 6, 1, 8, 3, 7},
{0, 5, 2, 4, 1, 6}};
static const int elem_surf_hex1[6][4] = {{3, 0, 4, 7}, {1, 2, 6, 5},
{0, 1, 5, 4}, {2, 3, 7, 6},
{3, 2, 1, 0}, {4, 5, 6, 7}};
static const int elem_surf_hex2[6][8] = {
{3, 11, 0, 16, 4, 15, 7, 19}, {1, 9, 2, 18, 6, 13, 5, 17},
{0, 8, 1, 17, 5, 12, 4, 16}, {2, 10, 3, 19, 7, 14, 6, 18},
{3, 10, 2, 9, 1, 8, 0, 11}, {4, 12, 5, 13, 6, 14, 7, 15}};
static const int elem_surf_pri1[5][4] = {
{1, 2, 5, 4}, {2, 0, 3, 5}, {0, 1, 4, 3}, {2, 1, 0, -1}, {3, 4, 5, -1}};
static const int elem_surf_pri2[5][8] = {{1, 6, 2, 14, 5, 9, 4, 13},
{2, 7, 0, 12, 3, 10, 5, 14},
{0, 8, 1, 13, 4, 11, 3, 12},
{2, 6, 1, 8, 0, 7, -1, -1},
{3, 11, 4, 9, 5, 10, -1, -1}};
static const int elem_surf_ptt1[3] = {0, 1, 2};
static const int elem_surf_ptt2[6] = {0, 1, 2, 3, 4, 5};
static const int elem_surf_ptq1[4] = {0, 1, 2, 3};
static const int elem_surf_ptq2[8] = {0, 1, 2, 3, 4, 5, 6, 7};
switch (etype) {
case HECMW_ETYPE_TET1:
return elem_surf_tet1[sid - 1];
case HECMW_ETYPE_TET2:
return elem_surf_tet2[sid - 1];
case HECMW_ETYPE_HEX1:
return elem_surf_hex1[sid - 1];
case HECMW_ETYPE_HEX2:
return elem_surf_hex2[sid - 1];
case HECMW_ETYPE_PRI1:
return elem_surf_pri1[sid - 1];
case HECMW_ETYPE_PRI2:
return elem_surf_pri2[sid - 1];
case HECMW_ETYPE_PTT1:
return elem_surf_ptt1;
case HECMW_ETYPE_PTT2:
return elem_surf_ptt2;
case HECMW_ETYPE_PTQ1:
return elem_surf_ptq1;
case HECMW_ETYPE_PTQ2:
return elem_surf_ptq2;
}
fprintf(stderr,
"ERROR: parallel contact analysis of element type %d not supported\n",
etype);
return NULL;
}
static int HECMW_fistr_get_num_surf_node(int etype, int sid) {
switch (etype) {
case HECMW_ETYPE_TET1:
case HECMW_ETYPE_PTT1:
return 3;
case HECMW_ETYPE_TET2:
case HECMW_ETYPE_PTT2:
return 6;
case HECMW_ETYPE_HEX1:
case HECMW_ETYPE_PTQ1:
return 4;
case HECMW_ETYPE_HEX2:
case HECMW_ETYPE_PTQ2:
return 8;
case HECMW_ETYPE_PRI1:
if (1 <= sid && sid <= 2) return 3;
if (3 <= sid && sid <= 5) return 4;
case HECMW_ETYPE_PRI2:
if (1 <= sid && sid <= 2) return 6;
if (3 <= sid && sid <= 5) return 8;
default:
fprintf(
stderr,
"ERROR: parallel contact analysis of elem type %d not supported\n",
etype);
return -1;
}
return -1;
}
static const int *HECMW_fistr_get_surf_node(int etype, int sid) {
HECMW_assert(0 < sid);
static const int elem_surf_tet1[4][3] = {
{0, 1, 2}, {0, 1, 3}, {1, 2, 3}, {2, 0, 3}};
static const int elem_surf_tet2[4][6] = {{0, 6, 1, 4, 2, 5},
{0, 6, 1, 8, 3, 7},
{1, 4, 2, 9, 3, 8},
{2, 5, 0, 9, 3, 7}};
static const int elem_surf_hex1[6][4] = {{0, 1, 2, 3}, {4, 5, 6, 7},
{0, 1, 5, 4}, {1, 2, 6, 5},
{2, 3, 7, 6}, {3, 0, 4, 7}};
static const int elem_surf_hex2[6][8] = {
{0, 8, 1, 9, 2, 10, 3, 11}, {4, 12, 5, 13, 6, 14, 7, 15},
{0, 8, 1, 17, 5, 12, 4, 16}, {1, 9, 2, 18, 6, 13, 5, 17},
{2, 10, 3, 19, 7, 14, 6, 18}, {3, 11, 0, 16, 4, 15, 7, 19}};
static const int elem_surf_pri1[5][4] = {
{0, 1, 2, -1}, {3, 4, 5, -1}, {0, 1, 4, 3}, {1, 2, 5, 4}, {2, 0, 3, 5}};
static const int elem_surf_pri2[5][8] = {{0, 8, 1, 6, 2, 7, -1, -1},
{3, 11, 4, 9, 5, 10, -1, -1},
{0, 8, 1, 13, 4, 11, 3, 12},
{1, 6, 2, 14, 5, 9, 4, 13},
{2, 7, 0, 12, 3, 10, 5, 14}};
static const int elem_surf_ptt1[3] = {0, 1, 2};
static const int elem_surf_ptt2[6] = {0, 1, 2, 3, 4, 5};
static const int elem_surf_ptq1[4] = {0, 1, 2, 3};
static const int elem_surf_ptq2[8] = {0, 1, 2, 3, 4, 5, 6, 7};
switch (etype) {
case HECMW_ETYPE_TET1:
return elem_surf_tet1[sid - 1];
case HECMW_ETYPE_TET2:
return elem_surf_tet2[sid - 1];
case HECMW_ETYPE_HEX1:
return elem_surf_hex1[sid - 1];
case HECMW_ETYPE_HEX2:
return elem_surf_hex2[sid - 1];
case HECMW_ETYPE_PRI1:
return elem_surf_pri1[sid - 1];
case HECMW_ETYPE_PRI2:
return elem_surf_pri2[sid - 1];
case HECMW_ETYPE_PTT1:
return elem_surf_ptt1;
case HECMW_ETYPE_PTT2:
return elem_surf_ptt2;
case HECMW_ETYPE_PTQ1:
return elem_surf_ptq1;
case HECMW_ETYPE_PTQ2:
return elem_surf_ptq2;
}
fprintf(stderr,
"ERROR: parallel contact analysis of element type %d not supported\n",
etype);
return NULL;
}
static int mark_contact_master_nodes(struct hecmwST_local_mesh *global_mesh,
int *mark) {
int i, j, k;
struct hecmwST_contact_pair *cp = global_mesh->contact_pair;
struct hecmwST_surf_grp *sgrp = global_mesh->surf_group;
for (i = 0; i < global_mesh->n_node; i++) {
mark[i] = 0;
}
for (i = 0; i < cp->n_pair; i++) {
int gid = cp->master_grp_id[i];
int jstart = sgrp->grp_index[gid - 1];
int jend = sgrp->grp_index[gid];
for (j = jstart; j < jend; j++) {
int eid = sgrp->grp_item[j * 2] - 1;
int sid = sgrp->grp_item[j * 2 + 1];
int *nop =
global_mesh->elem_node_item + global_mesh->elem_node_index[eid];
int etype = global_mesh->elem_type[eid];
/** IF HEC-MW NUMBERING **/
/* int num_snode = HECMW_get_num_surf_node(etype, sid); */
/* const int *snode = HECMW_get_surf_node(etype, sid); */
/** ELSE IF FrontISTR NUMBERING **/
int num_snode = HECMW_fistr_get_num_surf_node(etype, sid);
const int *snode = HECMW_fistr_get_surf_node(etype, sid);
/** END IF **/
if (num_snode < 0 || snode == NULL) return RTC_ERROR;
for (k = 0; k < num_snode; k++) {
int nid = nop[snode[k]] - 1;
HECMW_assert(0 <= nid && nid < global_mesh->n_node);
mark[nid] = 1;
}
}
}
return RTC_NORMAL;
}
static int contact_agg_mark_surf_group(int *mark,
struct hecmwST_local_mesh *global_mesh,
int gid, int agg_id, int *agg_dup) {
struct hecmwST_surf_grp *sgrp = global_mesh->surf_group;
int istart, iend, i, j;
HECMW_assert(0 < gid && gid <= sgrp->n_grp);
/* get all nodes in the surface and mark them!!! */
istart = sgrp->grp_index[gid - 1];
iend = sgrp->grp_index[gid];
for (i = istart; i < iend; i++) {
int eid = sgrp->grp_item[i * 2] - 1;
int sid = sgrp->grp_item[i * 2 + 1];
int *nop = global_mesh->elem_node_item + global_mesh->elem_node_index[eid];
int etype = global_mesh->elem_type[eid];
/** IF HEC-WM NUMBERING **/
/* int num_snode = HECMW_get_num_surf_node(etype, sid); */
/* const int *snode = HECMW_get_surf_node(etype, sid); */
/** ELSE IF FrontISTR NUMBERING **/
int num_snode = HECMW_fistr_get_num_surf_node(etype, sid);
const int *snode = HECMW_fistr_get_surf_node(etype, sid);
/** END IF **/
if (num_snode < 0 || snode == NULL) return RTC_ERROR;
for (j = 0; j < num_snode; j++) {
int nid = nop[snode[j]] - 1;
HECMW_assert(0 <= nid && nid < global_mesh->n_node);
if (0 <= mark[nid] && mark[nid] < agg_id) {
/* the node is included in some other contact pair */
if (*agg_dup == -1) {
*agg_dup = mark[nid];
} else if (mark[nid] != *agg_dup) {
fprintf(stderr,
"ERROR: node included in multiple surface groups in "
"different contact pairs,\n"
" which is not supported by CONTACT=AGGREGATE\n");
HECMW_abort(HECMW_comm_get_comm());
}
}
mark[nid] = agg_id;
}
}
return RTC_NORMAL;
}
static int metis_partition_nb_contact_agg(
struct hecmwST_local_mesh *global_mesh,
const struct hecmw_part_cont_data *cont_data,
const struct hecmw_part_edge_data *edge_data) {
int n_edgecut;
int *node_graph_index = NULL; /* index for nodal graph */
int *node_graph_item = NULL; /* member of nodal graph */
int *belong_domain = NULL;
int rtc;
int i;
struct hecmwST_contact_pair *cp;
int *mark;
int agg_id, agg_dup, gid;
int n_node2;
const int *node_graph_index2;
const int *node_graph_item2;
int *node_weight2;
struct hecmw_graph graph1, graph2;
const int ncon = 1;
HECMW_assert(global_mesh->hecmw_flag_partcontact ==
HECMW_FLAG_PARTCONTACT_AGGREGATE);
node_graph_index = (int *)HECMW_calloc(global_mesh->n_node + 1, sizeof(int));
if (node_graph_index == NULL) {
HECMW_set_error(errno, "");
goto error;
}
node_graph_item = (int *)HECMW_malloc(sizeof(int) * edge_data->n_edge * 2);
if (node_graph_item == NULL) {
HECMW_set_error(errno, "");
goto error;
}
HECMW_log(HECMW_LOG_DEBUG, "Starting creation of node graph...\n");
rtc = create_node_graph(global_mesh, edge_data, node_graph_index,
node_graph_item);
if (rtc != RTC_NORMAL) goto error;
HECMW_log(HECMW_LOG_DEBUG, "Creation of node graph done\n");
HECMW_log(HECMW_LOG_DEBUG, "Partitioning mode: contact-aggregate\n");
HECMW_log(HECMW_LOG_DEBUG, "Starting aggregation of contact pairs...\n");
/* aggregate contact pair if requested */
cp = global_mesh->contact_pair;
mark = (int *)HECMW_malloc(global_mesh->n_node * sizeof(int));
if (mark == NULL) {
HECMW_set_error(errno, "");
goto error;
}
for (i = 0; i < global_mesh->n_node; i++) {
mark[i] = -1;
}
agg_id = 0;
/* mark contact pairs */
for (i = 0; i < cp->n_pair; i++) {
agg_dup = -1;
/* slave */
if (cp->type[i] == HECMW_CONTACT_TYPE_NODE_SURF) {
gid = cp->slave_grp_id[i];
rtc =
contact_agg_mark_node_group(mark, global_mesh, gid, agg_id, &agg_dup);
if (rtc != RTC_NORMAL) goto error;
} else { /* HECMW_CONTACT_TYPE_SURF_SURF */
gid = cp->slave_grp_id[i];
rtc =
contact_agg_mark_surf_group(mark, global_mesh, gid, agg_id, &agg_dup);
if (rtc != RTC_NORMAL) goto error;
}
/* master */
gid = cp->master_grp_id[i];
rtc = contact_agg_mark_surf_group(mark, global_mesh, gid, agg_id, &agg_dup);
if (rtc != RTC_NORMAL) goto error;
if (agg_dup >= 0) {
for (i = 0; i < global_mesh->n_node; i++) {
if (mark[i] == agg_id) {
mark[i] = agg_dup;
}
}
} else {
agg_id++;
}
}
/* mark other nodes */
for (i = 0; i < global_mesh->n_node; i++) {
if (mark[i] < 0) {
mark[i] = agg_id++;
}
}
n_node2 = agg_id;
/* degenerate node graph */
rtc = HECMW_graph_init_with_arrays(&graph1, global_mesh->n_node,
node_graph_index, node_graph_item);
if (rtc != RTC_NORMAL) goto error;
rtc = HECMW_graph_init(&graph2);
if (rtc != RTC_NORMAL) goto error;
rtc = HECMW_graph_degeneGraph(&graph2, &graph1, n_node2, mark);
if (rtc != RTC_NORMAL) goto error;
HECMW_graph_finalize(&graph1);
node_graph_index2 = HECMW_graph_getEdgeIndex(&graph2);
node_graph_item2 = HECMW_graph_getEdgeItem(&graph2);
node_weight2 = (int *)HECMW_calloc(n_node2, sizeof(int));
if (node_weight2 == NULL) {
HECMW_set_error(errno, "");
goto error;
}
for (i = 0; i < global_mesh->n_node; i++) {
node_weight2[mark[i]] += 1;
}
HECMW_log(HECMW_LOG_DEBUG, "Aggregation of contact pairs done\n");
belong_domain = (int *)HECMW_calloc(n_node2, sizeof(int));
if (belong_domain == NULL) {
HECMW_set_error(errno, "");
goto error;
}
switch (cont_data->method) {
case HECMW_PART_METHOD_PMETIS: /* pMETIS */
n_edgecut = pmetis_interface_with_weight(
n_node2, ncon, global_mesh->n_subdomain, node_graph_index2,
node_graph_item2, node_weight2, belong_domain);
if (n_edgecut < 0) goto error;
break;
case HECMW_PART_METHOD_KMETIS: /* kMETIS */
n_edgecut = kmetis_interface_with_weight(
n_node2, ncon, global_mesh->n_subdomain, node_graph_index2,
node_graph_item2, node_weight2, belong_domain);
if (n_edgecut < 0) goto error;
break;
default:
HECMW_set_error(HECMW_PART_E_INVALID_PMETHOD, "");
goto error;
}
for (i = 0; i < global_mesh->n_node; i++) {
global_mesh->node_ID[2 * i + 1] = belong_domain[mark[i]];
}
HECMW_graph_finalize(&graph2);
HECMW_free(node_graph_index);
HECMW_free(node_graph_item);
HECMW_free(mark);
HECMW_free(node_weight2);
HECMW_free(belong_domain);
return n_edgecut;
error:
HECMW_free(node_graph_index);
HECMW_free(node_graph_item);
HECMW_free(mark);
HECMW_free(node_weight2);
HECMW_free(belong_domain);
return -1;
}
static int metis_partition_nb_contact_dist(
struct hecmwST_local_mesh *global_mesh,
const struct hecmw_part_cont_data *cont_data,
const struct hecmw_part_edge_data *edge_data) {
int n_edgecut;
int *node_graph_index = NULL; /* index for nodal graph */
int *node_graph_item = NULL; /* member of nodal graph */
int *belong_domain = NULL;
int rtc;
int i;
int ncon;
int *node_weight = NULL;
int *mark = NULL;
HECMW_assert(
global_mesh->hecmw_flag_partcontact == HECMW_FLAG_PARTCONTACT_SIMPLE ||
global_mesh->hecmw_flag_partcontact == HECMW_FLAG_PARTCONTACT_DISTRIBUTE);
node_graph_index = (int *)HECMW_calloc(global_mesh->n_node + 1, sizeof(int));
if (node_graph_index == NULL) {
HECMW_set_error(errno, "");
goto error;
}
node_graph_item = (int *)HECMW_malloc(sizeof(int) * edge_data->n_edge * 2);
if (node_graph_item == NULL) {
HECMW_set_error(errno, "");
goto error;
}
HECMW_log(HECMW_LOG_DEBUG, "Starting creation of node graph...\n");
rtc = create_node_graph(global_mesh, edge_data, node_graph_index,
node_graph_item);
if (rtc != RTC_NORMAL) goto error;
HECMW_log(HECMW_LOG_DEBUG, "Creation of node graph done\n");
if (global_mesh->hecmw_flag_partcontact == HECMW_FLAG_PARTCONTACT_SIMPLE) {
HECMW_log(HECMW_LOG_DEBUG, "Partitioning mode: contact-simple\n");
ncon = 1;
node_weight = NULL;
} else /* HECMW_FLAG_PARTCONTACT_DISTRIBUTE */
{
HECMW_log(HECMW_LOG_DEBUG, "Partitioning mode: contact-distribute\n");
ncon = 2;
mark = (int *)HECMW_calloc(global_mesh->n_node, sizeof(int));
if (mark == NULL) {
HECMW_set_error(errno, "");
goto error;
}
rtc = mark_contact_master_nodes(global_mesh, mark);
if (rtc != RTC_NORMAL) goto error;
node_weight = (int *)HECMW_calloc(global_mesh->n_node * ncon, sizeof(int));
if (node_weight == NULL) {
HECMW_set_error(errno, "");
goto error;
}
for (i = 0; i < global_mesh->n_node; i++) {
/* 1st condition: distribute nodes equally */
node_weight[i * ncon] = 1;
/* 2nd condition: distribute master nodes equally */
node_weight[i * ncon + 1] = mark[i];
}
HECMW_free(mark);
}
belong_domain = (int *)HECMW_calloc(global_mesh->n_node, sizeof(int));
if (belong_domain == NULL) {
HECMW_set_error(errno, "");
goto error;
}
switch (cont_data->method) {
case HECMW_PART_METHOD_PMETIS: /* pMETIS */
n_edgecut = pmetis_interface_with_weight(
global_mesh->n_node, ncon, global_mesh->n_subdomain, node_graph_index,
node_graph_item, node_weight, belong_domain);
if (n_edgecut < 0) goto error;
break;
case HECMW_PART_METHOD_KMETIS: /* kMETIS */
n_edgecut = kmetis_interface_with_weight(
global_mesh->n_node, ncon, global_mesh->n_subdomain, node_graph_index,
node_graph_item, node_weight, belong_domain);
if (n_edgecut < 0) goto error;
break;
default:
HECMW_set_error(HECMW_PART_E_INVALID_PMETHOD, "");
goto error;
}
for (i = 0; i < global_mesh->n_node; i++) {
global_mesh->node_ID[2 * i + 1] = belong_domain[i];
}
HECMW_free(node_graph_index);
HECMW_free(node_graph_item);
HECMW_free(belong_domain);
if (node_weight) HECMW_free(node_weight);
return n_edgecut;
error:
HECMW_free(node_graph_index);
HECMW_free(node_graph_item);
HECMW_free(belong_domain);
if (node_weight) HECMW_free(node_weight);
if (mark) HECMW_free(mark);
return -1;
}
static int metis_partition_nb_default(
struct hecmwST_local_mesh *global_mesh,
const struct hecmw_part_cont_data *cont_data,
const struct hecmw_part_edge_data *edge_data) {
int n_edgecut;
int *node_graph_index = NULL; /* index for nodal graph */
int *node_graph_item = NULL; /* member of nodal graph */
int *belong_domain = NULL;
int rtc;
int i;
node_graph_index = (int *)HECMW_calloc(global_mesh->n_node + 1, sizeof(int));
if (node_graph_index == NULL) {
HECMW_set_error(errno, "");
goto error;
}
node_graph_item = (int *)HECMW_malloc(sizeof(int) * edge_data->n_edge * 2);
if (node_graph_item == NULL) {
HECMW_set_error(errno, "");
goto error;
}
HECMW_log(HECMW_LOG_DEBUG, "Starting creation of node graph...\n");
rtc = create_node_graph(global_mesh, edge_data, node_graph_index,
node_graph_item);
if (rtc != RTC_NORMAL) goto error;
HECMW_log(HECMW_LOG_DEBUG, "Creation of node graph done\n");
belong_domain = (int *)HECMW_calloc(global_mesh->n_node, sizeof(int));
if (belong_domain == NULL) {
HECMW_set_error(errno, "");
goto error;
}
HECMW_log(HECMW_LOG_DEBUG, "Partitioning mode: default\n");
switch (cont_data->method) {
case HECMW_PART_METHOD_PMETIS: /* pMETIS */
n_edgecut =
pmetis_interface(global_mesh->n_node, global_mesh->n_subdomain,
node_graph_index, node_graph_item, belong_domain);
if (n_edgecut < 0) goto error;
break;
case HECMW_PART_METHOD_KMETIS: /* kMETIS */
n_edgecut =
kmetis_interface(global_mesh->n_node, global_mesh->n_subdomain,
node_graph_index, node_graph_item, belong_domain);
if (n_edgecut < 0) goto error;
break;
default:
HECMW_set_error(HECMW_PART_E_INVALID_PMETHOD, "");
goto error;
}
for (i = 0; i < global_mesh->n_node; i++) {
global_mesh->node_ID[2 * i + 1] = belong_domain[i];
}
HECMW_free(node_graph_index);
HECMW_free(node_graph_item);
HECMW_free(belong_domain);
return n_edgecut;
error:
HECMW_free(node_graph_index);
HECMW_free(node_graph_item);
HECMW_free(belong_domain);
return -1;
}
static int metis_partition_nb(struct hecmwST_local_mesh *global_mesh,
const struct hecmw_part_cont_data *cont_data,
const struct hecmw_part_edge_data *edge_data) {
if (global_mesh->contact_pair->n_pair > 0) {
switch (global_mesh->hecmw_flag_partcontact) {
case HECMW_FLAG_PARTCONTACT_AGGREGATE:
return metis_partition_nb_contact_agg(global_mesh, cont_data,
edge_data);
case HECMW_FLAG_PARTCONTACT_DISTRIBUTE:
case HECMW_FLAG_PARTCONTACT_SIMPLE:
return metis_partition_nb_contact_dist(global_mesh, cont_data,
edge_data);
default:
return -1;
}
} else {
return metis_partition_nb_default(global_mesh, cont_data, edge_data);
}
}
static int metis_partition_eb(struct hecmwST_local_mesh *global_mesh,
const struct hecmw_part_cont_data *cont_data,
int *elem_graph_index, int *elem_graph_item) {
int n_edgecut;
int *belong_domain = NULL;
int i;
belong_domain = (int *)HECMW_calloc(global_mesh->n_elem, sizeof(int));
if (belong_domain == NULL) {
HECMW_set_error(errno, "");
goto error;
}
switch (cont_data->method) {
case HECMW_PART_METHOD_PMETIS: /* pMETIS */
n_edgecut =
pmetis_interface(global_mesh->n_elem, global_mesh->n_subdomain,
elem_graph_index, elem_graph_item, belong_domain);
if (n_edgecut < 0) goto error;
break;
case HECMW_PART_METHOD_KMETIS: /* kMETIS */
n_edgecut =
kmetis_interface(global_mesh->n_elem, global_mesh->n_subdomain,
elem_graph_index, elem_graph_item, belong_domain);
if (n_edgecut < 0) goto error;
break;
default:
HECMW_set_error(HECMW_PART_E_INVALID_PMETHOD, "");
goto error;
}
for (i = 0; i < global_mesh->n_elem; i++) {
global_mesh->elem_ID[2 * i + 1] = belong_domain[i];
}
HECMW_free(belong_domain);
return n_edgecut;
error:
HECMW_free(belong_domain);
return -1;
}
/*------------------------------------------------------------------------------------------------*/
static int set_node_belong_domain_nb(
struct hecmwST_local_mesh *global_mesh,
const struct hecmw_part_cont_data *cont_data) {
struct hecmw_part_edge_data *edge_data = NULL;
int n_edgecut;
int rtc;
long long int i;
edge_data = (struct hecmw_part_edge_data *)HECMW_malloc(
sizeof(struct hecmw_part_edge_data));
if (edge_data == NULL) {
HECMW_set_error(errno, "");
goto error;
} else {
edge_data->n_edge = 0;
edge_data->edge_node_item = NULL;
}
HECMW_log(HECMW_LOG_DEBUG, "Starting creation of mesh edge info...\n");
rtc = HECMW_mesh_edge_info(global_mesh, edge_data);
if (rtc != 0) goto error;
HECMW_log(HECMW_LOG_DEBUG, "Creation of mesh edge info done\n");
switch (cont_data->method) {
case HECMW_PART_METHOD_RCB: /* RCB */
rtc = rcb_partition(global_mesh->n_node, global_mesh->node,
global_mesh->node_ID, cont_data);
if (rtc != RTC_NORMAL) goto error;
for (n_edgecut = 0, i = 0; i < edge_data->n_edge; i++) {
if (global_mesh
->node_ID[2 * (edge_data->edge_node_item[2 * i] - 1) + 1] !=
global_mesh
->node_ID[2 * (edge_data->edge_node_item[2 * i + 1] - 1) + 1]) {
n_edgecut++;
}
}
break;
case HECMW_PART_METHOD_KMETIS: /* kMETIS */
case HECMW_PART_METHOD_PMETIS: /* pMETIS */
n_edgecut = metis_partition_nb(global_mesh, cont_data, edge_data);
if (n_edgecut < 0) goto error;
break;
default:
HECMW_set_error(HECMW_PART_E_INVALID_PMETHOD, "");
goto error;
}
rtc = HECMW_part_set_log_n_edgecut(edge_data->n_edge, n_edgecut);
if (rtc != RTC_NORMAL) goto error;
/* commented out by K.Goto; begin */
/* rtc = eqn_block( global_mesh ); */
/* if( rtc != RTC_NORMAL ) goto error; */
/* commented out by K.Goto; end */
HECMW_free(edge_data->edge_node_item);
HECMW_free(edge_data);
return RTC_NORMAL;
error:
if (edge_data) {
HECMW_free(edge_data->edge_node_item);
}
HECMW_free(edge_data);
return RTC_ERROR;
}
static int set_node_belong_domain_eb(struct hecmwST_local_mesh *global_mesh) {
int node;
int i, j;
for (i = 0; i < global_mesh->n_node; i++) {
global_mesh->node_ID[2 * i + 1] = global_mesh->n_subdomain;
}
for (i = 0; i < global_mesh->n_elem; i++) {
for (j = global_mesh->elem_node_index[i];
j < global_mesh->elem_node_index[i + 1]; j++) {
node = global_mesh->elem_node_item[j];
if (global_mesh->elem_ID[2 * i + 1] <
global_mesh->node_ID[2 * (node - 1) + 1]) {
global_mesh->node_ID[2 * (node - 1) + 1] =
global_mesh->elem_ID[2 * i + 1];
}
}
}
return RTC_NORMAL;
}
static int set_local_node_id(struct hecmwST_local_mesh *global_mesh) {
int *counter;
int j, domain;
counter = (int *)HECMW_calloc(global_mesh->n_subdomain, sizeof(int));
if (counter == NULL) {
HECMW_set_error(errno, "");
goto error;
}
for (j = 0; j < global_mesh->n_node; j++) {
domain = global_mesh->node_ID[2 * j + 1];
global_mesh->node_ID[2 * j] = ++counter[domain];
}
HECMW_free(counter);
return RTC_NORMAL;
error:
return RTC_ERROR;
}
static int wnumbering_node(struct hecmwST_local_mesh *global_mesh,
const struct hecmw_part_cont_data *cont_data) {
int rtc;
int i;
HECMW_free(global_mesh->node_ID);
global_mesh->node_ID =
(int *)HECMW_malloc(sizeof(int) * global_mesh->n_node * 2);
if (global_mesh->node_ID == NULL) {
HECMW_set_error(errno, "");
goto error;
} else {
for (i = 0; i < global_mesh->n_node; i++) {
global_mesh->node_ID[2 * i] = i + 1;
global_mesh->node_ID[2 * i + 1] = 0;
}
}
if (global_mesh->n_subdomain == 1) return RTC_NORMAL;
switch (global_mesh->hecmw_flag_parttype) {
case HECMW_FLAG_PARTTYPE_NODEBASED: /* for node-based partitioning */
rtc = set_node_belong_domain_nb(global_mesh, cont_data);
if (rtc != RTC_NORMAL) goto error;
break;
case HECMW_FLAG_PARTTYPE_ELEMBASED: /* for element-based partitioning */
rtc = set_node_belong_domain_eb(global_mesh);
if (rtc != RTC_NORMAL) goto error;
break;
default:
HECMW_set_error(HECMW_PART_E_INVALID_PTYPE, "");
goto error;
}
rtc = set_local_node_id(global_mesh);
if (rtc != RTC_NORMAL) goto error;
return RTC_NORMAL;
error:
return RTC_ERROR;
}
/*------------------------------------------------------------------------------------------------*/
static int set_elem_belong_domain_nb(struct hecmwST_local_mesh *global_mesh) {
int node, node_domain, min_domain;
int i, j;
for (i = 0; i < global_mesh->n_elem; i++) {
min_domain = global_mesh->n_subdomain;
for (j = global_mesh->elem_node_index[i];
j < global_mesh->elem_node_index[i + 1]; j++) {
node = global_mesh->elem_node_item[j];
node_domain = global_mesh->node_ID[2 * (node - 1) + 1];
if (node_domain < min_domain) {
min_domain = node_domain;
}
}
global_mesh->elem_ID[2 * i + 1] = min_domain;
}
return RTC_NORMAL;
}
static int count_edge_for_eb(const struct hecmwST_local_mesh *global_mesh,
struct hecmw_part_edge_data *elem_data,
int *elem_graph_index, int *elem_graph_item) {
int rtc;
long long int eid;
int i, j;
rtc = HECMW_mesh_hsort_edge_init(global_mesh->n_node, global_mesh->n_elem);
if (rtc != RTC_NORMAL) goto error;
for (i = 0; i < global_mesh->n_elem; i++) {
for (j = elem_graph_index[i]; j < elem_graph_index[i + 1]; j++) {
eid = HECMW_mesh_hsort_edge(i + 1, elem_graph_item[j] + 1);
if (eid < 0) goto error;
}
}
elem_data->n_edge = HECMW_mesh_hsort_edge_get_n();
if (elem_data->n_edge < 0) goto error;
elem_data->edge_node_item = HECMW_mesh_hsort_edge_get_v();
if (elem_data->edge_node_item == NULL) goto error;
HECMW_mesh_hsort_edge_final();
return RTC_NORMAL;
error:
HECMW_mesh_hsort_edge_final();
return RTC_ERROR;
}
static int set_elem_belong_domain_eb(
struct hecmwST_local_mesh *global_mesh,
const struct hecmw_part_cont_data *cont_data) {
int n_edgecut = 0;
int *elem_graph_index = NULL;
int *elem_graph_item = NULL;
struct hecmw_part_edge_data *elem_data = NULL;
int rtc;
long long int i;
elem_graph_index = (int *)HECMW_calloc(global_mesh->n_elem + 1, sizeof(int));
if (elem_graph_index == NULL) {
HECMW_set_error(errno, "");
goto error;
}
elem_data = (struct hecmw_part_edge_data *)HECMW_malloc(
sizeof(struct hecmw_part_edge_data));
if (elem_data == NULL) {
HECMW_set_error(errno, "");
goto error;
} else {
elem_data->n_edge = 0;
elem_data->edge_node_item = NULL;
}
HECMW_log(HECMW_LOG_DEBUG, "Starting creation of elem graph...\n");
elem_graph_item = create_elem_graph(global_mesh, elem_graph_index);
if (elem_graph_item == NULL) goto error;
HECMW_log(HECMW_LOG_DEBUG, "Creation of elem graph done\n");
rtc = count_edge_for_eb(global_mesh, elem_data, elem_graph_index,
elem_graph_item);
if (rtc != RTC_NORMAL) goto error;
switch (cont_data->method) {
case HECMW_PART_METHOD_RCB: /* RCB */
rtc = rcb_partition_eb(global_mesh, cont_data);
if (rtc != RTC_NORMAL) goto error;
for (n_edgecut = 0, i = 0; i < elem_data->n_edge; i++) {
if (global_mesh
->elem_ID[2 * (elem_data->edge_node_item[2 * i] - 1) + 1] !=
global_mesh
->elem_ID[2 * (elem_data->edge_node_item[2 * i + 1] - 1) + 1]) {
n_edgecut++;
}
}
break;
case HECMW_PART_METHOD_PMETIS: /* pMETIS */
case HECMW_PART_METHOD_KMETIS: /* kMETIS */
n_edgecut = metis_partition_eb(global_mesh, cont_data, elem_graph_index,
elem_graph_item);
if (n_edgecut < 0) goto error;
break;
default:
HECMW_set_error(HECMW_PART_E_INVALID_PMETHOD, "");
goto error;
}
rtc = HECMW_part_set_log_n_edgecut(elem_data->n_edge, n_edgecut);
if (rtc != RTC_NORMAL) goto error;
HECMW_free(elem_graph_index);
HECMW_free(elem_graph_item);
HECMW_free(elem_data->edge_node_item);
HECMW_free(elem_data);
return RTC_NORMAL;
error:
HECMW_free(elem_graph_index);
HECMW_free(elem_graph_item);
if (elem_data) {
HECMW_free(elem_data->edge_node_item);
}
HECMW_free(elem_data);
return RTC_ERROR;
}
static int set_local_elem_id(struct hecmwST_local_mesh *global_mesh) {
int *counter;
int j, domain;
counter = (int *)HECMW_calloc(global_mesh->n_subdomain, sizeof(int));
if (counter == NULL) {
HECMW_set_error(errno, "");
goto error;
}
for (j = 0; j < global_mesh->n_elem; j++) {
domain = global_mesh->elem_ID[2 * j + 1];
global_mesh->elem_ID[2 * j] = ++counter[domain];
}
HECMW_free(counter);
return RTC_NORMAL;
error:
return RTC_ERROR;
}
static int wnumbering_elem(struct hecmwST_local_mesh *global_mesh,
const struct hecmw_part_cont_data *cont_data) {
int rtc;
int i;
HECMW_free(global_mesh->elem_ID);
global_mesh->elem_ID =
(int *)HECMW_malloc(sizeof(int) * global_mesh->n_elem * 2);
if (global_mesh->elem_ID == NULL) {
HECMW_set_error(errno, "");
goto error;
} else {
for (i = 0; i < global_mesh->n_elem; i++) {
global_mesh->elem_ID[2 * i] = i + 1;
global_mesh->elem_ID[2 * i + 1] = 0;
}
}
if (global_mesh->n_subdomain == 1) return RTC_NORMAL;
switch (global_mesh->hecmw_flag_parttype) {
case HECMW_FLAG_PARTTYPE_NODEBASED: /* for node-based partitioning */
rtc = set_elem_belong_domain_nb(global_mesh);
if (rtc != RTC_NORMAL) goto error;
break;
case HECMW_FLAG_PARTTYPE_ELEMBASED: /* for element-based partitioning */
rtc = set_elem_belong_domain_eb(global_mesh, cont_data);
if (rtc != RTC_NORMAL) goto error;
break;
default:
HECMW_set_error(HECMW_PART_E_INVALID_PTYPE, "");
goto error;
}
rtc = set_local_elem_id(global_mesh);
if (rtc != RTC_NORMAL) goto error;
return RTC_NORMAL;
error:
return RTC_ERROR;
}
static int wnumbering(struct hecmwST_local_mesh *global_mesh,
const struct hecmw_part_cont_data *cont_data) {
int rtc;
HECMW_assert(global_mesh);
HECMW_assert(cont_data);
HECMW_log(HECMW_LOG_DEBUG, "Starting double numbering...");
switch (global_mesh->hecmw_flag_parttype) {
case HECMW_FLAG_PARTTYPE_NODEBASED: /* for node-based partitioning */
rtc = wnumbering_node(global_mesh, cont_data);
if (rtc != RTC_NORMAL) goto error;
rtc = wnumbering_elem(global_mesh, cont_data);
if (rtc != RTC_NORMAL) goto error;
break;
case HECMW_FLAG_PARTTYPE_ELEMBASED: /* for element-based partitioning */
rtc = wnumbering_elem(global_mesh, cont_data);
if (rtc != RTC_NORMAL) goto error;
rtc = wnumbering_node(global_mesh, cont_data);
if (rtc != RTC_NORMAL) goto error;
break;
default:
HECMW_set_error(HECMW_PART_E_INVALID_PTYPE, "");
goto error;
}
HECMW_log(HECMW_LOG_DEBUG, "Double numbering done");
return RTC_NORMAL;
error:
return RTC_ERROR;
}
/*==================================================================================================
create neighboring domain & communication information
==================================================================================================*/
/*K. Inagaki */
static int mask_node_by_domain(const struct hecmwST_local_mesh *global_mesh,
char *node_flag, int current_domain) {
int i, node;
for (i = 0; i < n_int_nlist[current_domain]; i++) {
node = int_nlist[current_domain][i];
MASK_BIT(node_flag[node - 1], INTERNAL);
}
return RTC_NORMAL;
}
static int mask_elem_by_domain(const struct hecmwST_local_mesh *global_mesh,
char *elem_flag, int current_domain) {
int i;
for (i = 0; i < global_mesh->n_elem; i++) {
(global_mesh->elem_ID[2 * i + 1] == current_domain)
? MASK_BIT(elem_flag[i], INTERNAL)
: MASK_BIT(elem_flag[i], EXTERNAL);
}
return RTC_NORMAL;
}
/*K. Inagaki */
static int mask_elem_by_domain_mod(char *elem_flag, int current_domain) {
int i, elem;
for (i = 0; i < n_int_elist[current_domain]; i++) {
elem = int_elist[current_domain][i];
MASK_BIT(elem_flag[elem - 1], INTERNAL);
}
return RTC_NORMAL;
}
#if 0
/* For Additional overlap for explicite DOF elimination for MPC */
/* NO LONGER NEEDED because node-migration implemented */
static int mask_slave_node(const struct hecmwST_local_mesh *global_mesh,
char *node_flag, int current_domain) {
int i;
for (i = 0; i < global_mesh->mpc->n_mpc; i++) {
int j0, je, slave, master, j, evalsum;
j0 = global_mesh->mpc->mpc_index[i];
je = global_mesh->mpc->mpc_index[i + 1];
slave = global_mesh->mpc->mpc_item[j0];
/* mask all slave nodes */
MASK_BIT(node_flag[slave - 1], MASK);
/* mark slave nodes that have mpc-link across the boundary */
evalsum = 0;
for (j = j0 + 1; j < je; j++) {
master = global_mesh->mpc->mpc_item[j];
if (EVAL_BIT(node_flag[slave - 1], INTERNAL) ^ /* exclusive or */
EVAL_BIT(node_flag[master - 1], INTERNAL)) {
evalsum++;
}
}
if (evalsum) {
MASK_BIT(node_flag[slave - 1], MARK);
}
}
return RTC_NORMAL;
}
#endif
/*- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
* - - - - - - - - - */
/*K. Inagaki */
static int mask_overlap_elem(char *elem_flag, int domain) {
int i, elem;
for (i = 0; i < n_bnd_elist[2 * domain + 1]; i++) {
elem = bnd_elist[domain][i];
MASK_BIT(elem_flag[elem - 1], OVERLAP);
MASK_BIT(elem_flag[elem - 1], BOUNDARY);
}
return RTC_NORMAL;
}
static int mask_boundary_node(const struct hecmwST_local_mesh *global_mesh,
char *node_flag, const char *elem_flag) {
int node;
int i, j;
for (i = 0; i < global_mesh->n_elem; i++) {
if (EVAL_BIT(elem_flag[i], BOUNDARY)) {
for (j = global_mesh->elem_node_index[i];
j < global_mesh->elem_node_index[i + 1]; j++) {
node = global_mesh->elem_node_item[j];
MASK_BIT(node_flag[node - 1], OVERLAP);
MASK_BIT(node_flag[node - 1], BOUNDARY);
}
}
}
return RTC_NORMAL;
}
/*K. Inagaki */
static int mask_boundary_node_mod(const struct hecmwST_local_mesh *global_mesh,
char *node_flag, char *elem_flag,
int domain) {
int i, node;
for (i = 0; i < n_bnd_nlist[2 * domain + 1]; i++) {
node = bnd_nlist[domain][i];
MASK_BIT(node_flag[node - 1], OVERLAP);
MASK_BIT(node_flag[node - 1], BOUNDARY);
}
return RTC_NORMAL;
}
#if 0
/* For Additional overlap for explicite DOF elimination for MPC */
/* NO LONGER NEEDED because node-migration implemented */
static int mask_boundary_elem_with_slave(
const struct hecmwST_local_mesh *global_mesh, const char *node_flag,
char *elem_flag, int *added) {
int node, evalsum;
int i, j;
*added = 0;
for (i = 0; i < global_mesh->n_elem; i++) {
if (EVAL_BIT(elem_flag[i], BOUNDARY)) continue;
if (HECMW_is_etype_link(global_mesh->elem_type[i]))
continue; /* skip link elements */
evalsum = 0;
for (j = global_mesh->elem_node_index[i];
j < global_mesh->elem_node_index[i + 1]; j++) {
node = global_mesh->elem_node_item[j];
/* check if the node is on boundary and a slave having mpc-link across the
* boundary */
if (EVAL_BIT(node_flag[node - 1], BOUNDARY) &&
EVAL_BIT(node_flag[node - 1], MASK) &&
EVAL_BIT(node_flag[node - 1], MARK)) {
evalsum++;
}
}
if (evalsum) {
MASK_BIT(elem_flag[i], OVERLAP);
MASK_BIT(elem_flag[i], BOUNDARY);
(*added)++;
}
}
return RTC_NORMAL;
}
static int mask_boundary_link_elem_with_slave(
const struct hecmwST_local_mesh *global_mesh, const char *node_flag,
char *elem_flag, int *added) {
int node, evalsum;
int i, j;
*added = 0;
for (i = 0; i < global_mesh->n_elem; i++) {
if (EVAL_BIT(elem_flag[i], BOUNDARY)) continue;
if (!HECMW_is_etype_link(global_mesh->elem_type[i]))
continue; /* check only link elements */
evalsum = 0;
for (j = global_mesh->elem_node_index[i];
j < global_mesh->elem_node_index[i + 1]; j++) {
node = global_mesh->elem_node_item[j];
/* check if the node is on boundary and a slave */
if (EVAL_BIT(node_flag[node - 1], BOUNDARY) &&
EVAL_BIT(node_flag[node - 1], MASK)) {
evalsum++;
}
}
if (evalsum) {
MASK_BIT(elem_flag[i], OVERLAP);
MASK_BIT(elem_flag[i], BOUNDARY);
(*added)++;
}
}
return RTC_NORMAL;
}
#endif
static int mask_additional_overlap_elem(
const struct hecmwST_local_mesh *global_mesh, const char *node_flag,
char *elem_flag) {
int node, evalsum;
int i, j;
for (i = 0; i < global_mesh->n_elem; i++) {
evalsum = 0;
for (j = global_mesh->elem_node_index[i];
j < global_mesh->elem_node_index[i + 1]; j++) {
node = global_mesh->elem_node_item[j];
evalsum += (EVAL_BIT(node_flag[node - 1], BOUNDARY));
}
if (evalsum) {
MASK_BIT(elem_flag[i], OVERLAP);
MASK_BIT(elem_flag[i], BOUNDARY);
}
}
return RTC_NORMAL;
}
static int mask_contact_slave_surf(const struct hecmwST_local_mesh *global_mesh,
char *elem_flag, char *node_flag) {
int i, j, k;
int elem, node, selem;
int evalsum, evalsum2;
int master_gid, slave_gid;
int jstart, jend;
struct hecmwST_contact_pair *cp;
struct hecmwST_surf_grp *sgrp;
struct hecmwST_node_grp *ngrp;
cp = global_mesh->contact_pair;
sgrp = global_mesh->surf_group;
ngrp = global_mesh->node_group;
for (i = 0; i < cp->n_pair; i++) {
switch (cp->type[i]) {
case HECMW_CONTACT_TYPE_NODE_SURF:
/* if any elem of master surf is internal */
evalsum = 0;
master_gid = cp->master_grp_id[i];
jstart = sgrp->grp_index[master_gid - 1];
jend = sgrp->grp_index[master_gid];
for (j = jstart; j < jend; j++) {
elem = sgrp->grp_item[j * 2];
if (EVAL_BIT(elem_flag[elem - 1], INTERNAL)) {
evalsum++;
break;
}
}
if (evalsum) {
/* mask all external slave nodes as BOUNDARY (but not OVERLAP) */
slave_gid = cp->slave_grp_id[i];
jstart = ngrp->grp_index[slave_gid - 1];
jend = ngrp->grp_index[slave_gid];
for (j = jstart; j < jend; j++) {
node = ngrp->grp_item[j];
if (!EVAL_BIT(node_flag[node - 1], INTERNAL)) {
MASK_BIT(node_flag[node - 1], BOUNDARY);
}
}
}
/* if any elem of master surf is external */
evalsum = 0;
master_gid = cp->master_grp_id[i];
jstart = sgrp->grp_index[master_gid - 1];
jend = sgrp->grp_index[master_gid];
for (j = jstart; j < jend; j++) {
elem = sgrp->grp_item[j * 2];
if (!EVAL_BIT(elem_flag[elem - 1], INTERNAL)) {
evalsum++;
break;
}
}
if (evalsum) {
/* mask all internal slave nodes as BOUNDARY (but not OVERLAP) */
slave_gid = cp->slave_grp_id[i];
jstart = ngrp->grp_index[slave_gid - 1];
jend = ngrp->grp_index[slave_gid];
for (j = jstart; j < jend; j++) {
node = ngrp->grp_item[j];
if (EVAL_BIT(node_flag[node - 1], INTERNAL)) {
MASK_BIT(node_flag[node - 1], BOUNDARY);
}
}
}
break;
case HECMW_CONTACT_TYPE_SURF_SURF:
/* if any elem of master surf is internal or boundary */
evalsum = 0;
master_gid = cp->master_grp_id[i];
jstart = sgrp->grp_index[master_gid - 1];
jend = sgrp->grp_index[master_gid];
for (j = jstart; j < jend; j++) {
elem = sgrp->grp_item[j * 2];
if (EVAL_BIT(elem_flag[elem - 1], INTERNAL)
|| EVAL_BIT(elem_flag[elem - 1], BOUNDARY)) {
evalsum++;
break;
}
}
if (evalsum) {
/* mask all external slave elems/nodes as BOUNDARY (but not OVERLAP) */
slave_gid = cp->slave_grp_id[i];
jstart = sgrp->grp_index[slave_gid - 1];
jend = sgrp->grp_index[slave_gid];
for (j = jstart; j < jend; j++) {
selem = sgrp->grp_item[j * 2];
if (!EVAL_BIT(elem_flag[selem - 1], INTERNAL)) {
MASK_BIT(elem_flag[selem - 1], BOUNDARY);
for (k = global_mesh->elem_node_index[selem - 1];
k < global_mesh->elem_node_index[selem]; k++) {
node = global_mesh->elem_node_item[k];
MASK_BIT(node_flag[node - 1], BOUNDARY);
}
}
}
}
/* if any elem of master surf is external or boundary */
evalsum = 0;
master_gid = cp->master_grp_id[i];
jstart = sgrp->grp_index[master_gid - 1];
jend = sgrp->grp_index[master_gid];
for (j = jstart; j < jend; j++) {
elem = sgrp->grp_item[j * 2];
if (!EVAL_BIT(elem_flag[elem - 1], INTERNAL)
|| EVAL_BIT(elem_flag[elem - 1], BOUNDARY)) {
evalsum++;
break;
}
}
if (evalsum) {
/* mask all internal slave nodes as BOUNDARY (but not OVERLAP) */
slave_gid = cp->slave_grp_id[i];
jstart = sgrp->grp_index[slave_gid - 1];
jend = sgrp->grp_index[slave_gid];
for (j = jstart; j < jend; j++) {
evalsum2 = 0;
selem = sgrp->grp_item[j * 2];
for (k = global_mesh->elem_node_index[selem - 1];
k < global_mesh->elem_node_index[selem]; k++) {
node = global_mesh->elem_node_item[k];
if (EVAL_BIT(node_flag[node - 1], INTERNAL)) {
evalsum2++;
break;
}
}
if (evalsum2) {
MASK_BIT(elem_flag[selem - 1], BOUNDARY);
for (k = global_mesh->elem_node_index[selem - 1];
k < global_mesh->elem_node_index[selem]; k++) {
node = global_mesh->elem_node_item[k];
MASK_BIT(node_flag[node - 1], BOUNDARY);
}
}
}
}
break;
default:
return RTC_ERROR;
}
}
return RTC_NORMAL;
}
static int mask_mesh_status_nb(const struct hecmwST_local_mesh *global_mesh,
char *node_flag, char *elem_flag,
int current_domain) {
int rtc;
int i;
rtc = mask_node_by_domain(global_mesh, node_flag, current_domain);
if (rtc != RTC_NORMAL) goto error;
rtc = mask_elem_by_domain_mod(elem_flag, current_domain);
if (rtc != RTC_NORMAL) goto error;
rtc = mask_overlap_elem(elem_flag, current_domain);
if (rtc != RTC_NORMAL) goto error;
rtc =
mask_boundary_node_mod(global_mesh, node_flag, elem_flag, current_domain);
if (rtc != RTC_NORMAL) goto error;
#if 0
/* Additional overlap for explicite DOF elimination for MPC */
/* NO LONGER NEEDED because node-migration implemented */
if (global_mesh->mpc->n_mpc > 0) {
int added = 0;
rtc = mask_slave_node(global_mesh, node_flag, current_domain);
if (rtc != RTC_NORMAL) goto error;
rtc = mask_boundary_elem_with_slave(global_mesh, node_flag, elem_flag,
&added);
if (rtc != RTC_NORMAL) goto error;
if (added > 0) {
rtc = mask_boundary_node(global_mesh, node_flag, elem_flag);
if (rtc != RTC_NORMAL) goto error;
}
added = 0;
rtc = mask_boundary_link_elem_with_slave(global_mesh, node_flag, elem_flag,
&added);
if (rtc != RTC_NORMAL) goto error;
if (added > 0) {
rtc = mask_boundary_node(global_mesh, node_flag, elem_flag);
if (rtc != RTC_NORMAL) goto error;
}
for (i = 0; i < global_mesh->n_node; i++) {
CLEAR_BIT(node_flag[i], MASK);
CLEAR_BIT(node_flag[i], MARK);
}
}
#endif
for (i = 1; i < global_mesh->hecmw_flag_partdepth; i++) {
rtc = mask_additional_overlap_elem(global_mesh, node_flag, elem_flag);
if (rtc != RTC_NORMAL) goto error;
rtc = mask_boundary_node(global_mesh, node_flag, elem_flag);
if (rtc != RTC_NORMAL) goto error;
}
if (global_mesh->contact_pair->n_pair > 0) {
rtc = mask_contact_slave_surf(global_mesh, elem_flag, node_flag);
if (rtc != RTC_NORMAL) goto error;
}
return RTC_NORMAL;
error:
return RTC_ERROR;
}
/*- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
* - - - - - - - - - */
static int mask_overlap_node_mark(const struct hecmwST_local_mesh *global_mesh,
char *node_flag, const char *elem_flag) {
int node;
int i, j;
for (i = 0; i < global_mesh->n_elem; i++) {
if (EVAL_BIT(elem_flag[i], INTERNAL)) {
for (j = global_mesh->elem_node_index[i];
j < global_mesh->elem_node_index[i + 1]; j++) {
node = global_mesh->elem_node_item[j];
MASK_BIT(node_flag[node - 1], MARK);
}
} else {
for (j = global_mesh->elem_node_index[i];
j < global_mesh->elem_node_index[i + 1]; j++) {
node = global_mesh->elem_node_item[j];
MASK_BIT(node_flag[node - 1], MASK);
}
}
}
return RTC_NORMAL;
}
static int mask_overlap_node_inner(const struct hecmwST_local_mesh *global_mesh,
char *node_flag) {
int i;
for (i = 0; i < global_mesh->n_node; i++) {
if (EVAL_BIT(node_flag[i], MARK) && EVAL_BIT(node_flag[i], MASK)) {
MASK_BIT(node_flag[i], OVERLAP);
MASK_BIT(node_flag[i], BOUNDARY);
}
}
return RTC_NORMAL;
}
static int mask_overlap_node(const struct hecmwST_local_mesh *global_mesh,
char *node_flag, const char *elem_flag) {
int rtc;
int i;
rtc = mask_overlap_node_mark(global_mesh, node_flag, elem_flag);
if (rtc != RTC_NORMAL) goto error;
rtc = mask_overlap_node_inner(global_mesh, node_flag);
if (rtc != RTC_NORMAL) goto error;
for (i = 0; i < global_mesh->n_node; i++) {
CLEAR_BIT(node_flag[i], MASK);
CLEAR_BIT(node_flag[i], MARK);
}
return RTC_NORMAL;
error:
return RTC_ERROR;
}
static int mask_boundary_elem(const struct hecmwST_local_mesh *global_mesh,
const char *node_flag, char *elem_flag) {
int node, evalsum;
int i, j;
for (i = 0; i < global_mesh->n_elem; i++) {
evalsum = 0;
for (j = global_mesh->elem_node_index[i];
j < global_mesh->elem_node_index[i + 1]; j++) {
node = global_mesh->elem_node_item[j];
if (EVAL_BIT(node_flag[node - 1], BOUNDARY)) evalsum++;
}
if (evalsum) {
MASK_BIT(elem_flag[i], OVERLAP);
MASK_BIT(elem_flag[i], BOUNDARY);
}
}
return RTC_NORMAL;
}
static int mask_mesh_status_eb(const struct hecmwST_local_mesh *global_mesh,
char *node_flag, char *elem_flag,
int current_domain) {
int rtc;
int i;
for (i = 0; i < global_mesh->n_node; i++) {
CLEAR_BIT(node_flag[i], INTERNAL);
CLEAR_BIT(node_flag[i], EXTERNAL);
CLEAR_BIT(node_flag[i], BOUNDARY);
}
for (i = 0; i < global_mesh->n_elem; i++) {
CLEAR_BIT(elem_flag[i], INTERNAL);
CLEAR_BIT(elem_flag[i], EXTERNAL);
CLEAR_BIT(elem_flag[i], BOUNDARY);
}
rtc = mask_node_by_domain(global_mesh, node_flag, current_domain);
if (rtc != RTC_NORMAL) goto error;
rtc = mask_elem_by_domain(global_mesh, elem_flag, current_domain);
if (rtc != RTC_NORMAL) goto error;
rtc = mask_overlap_node(global_mesh, node_flag, elem_flag);
if (rtc != RTC_NORMAL) goto error;
rtc = mask_boundary_elem(global_mesh, node_flag, elem_flag);
if (rtc != RTC_NORMAL) goto error;
return RTC_NORMAL;
error:
return RTC_ERROR;
}
/*------------------------------------------------------------------------------------------------*/
static int mask_neighbor_domain_nb(const struct hecmwST_local_mesh *global_mesh,
const char *node_flag, char *domain_flag) {
int i;
for (i = 0; i < global_mesh->n_node; i++) {
if (!EVAL_BIT(node_flag[i], INTERNAL) && EVAL_BIT(node_flag[i], BOUNDARY)) {
MASK_BIT(domain_flag[global_mesh->node_ID[2 * i + 1]], MASK);
}
}
return RTC_NORMAL;
}
/*K. Inagaki */
static int mask_neighbor_domain_nb_mod(
const struct hecmwST_local_mesh *global_mesh, const char *node_flag,
char *domain_flag, int domain) {
int i, node;
for (i = n_bnd_nlist[2 * domain]; i < n_bnd_nlist[2 * domain + 1]; i++) {
node = bnd_nlist[domain][i];
MASK_BIT(domain_flag[global_mesh->node_ID[2 * node - 1]], MASK);
}
return RTC_NORMAL;
}
static int mask_neighbor_domain_nb_contact(
const struct hecmwST_local_mesh *global_mesh, const char *node_flag,
const char *elem_flag, char *domain_flag) {
int i, j, k;
int elem, node, selem;
int evalsum;
int master_gid, slave_gid;
int jstart, jend;
struct hecmwST_contact_pair *cp;
struct hecmwST_surf_grp *sgrp;
struct hecmwST_node_grp *ngrp;
cp = global_mesh->contact_pair;
sgrp = global_mesh->surf_group;
ngrp = global_mesh->node_group;
for (i = 0; i < cp->n_pair; i++) {
/* if any slave node is internal */
evalsum = 0;
switch (cp->type[i]) {
case HECMW_CONTACT_TYPE_NODE_SURF:
slave_gid = cp->slave_grp_id[i];
jstart = ngrp->grp_index[slave_gid - 1];
jend = ngrp->grp_index[slave_gid];
for (j = jstart; j < jend; j++) {
node = ngrp->grp_item[j];
if (EVAL_BIT(node_flag[node - 1], INTERNAL)) {
evalsum++;
break;
}
}
break;
case HECMW_CONTACT_TYPE_SURF_SURF:
slave_gid = cp->slave_grp_id[i];
jstart = sgrp->grp_index[slave_gid - 1];
jend = sgrp->grp_index[slave_gid];
for (j = jstart; j < jend; j++) {
selem = sgrp->grp_item[j * 2];
for (k = global_mesh->elem_node_index[selem - 1];
k < global_mesh->elem_node_index[selem]; k++) {
node = global_mesh->elem_node_item[k];
if (EVAL_BIT(node_flag[node - 1], INTERNAL)) {
evalsum++;
break;
}
}
if (evalsum) break;
}
break;
default:
return RTC_ERROR;
}
/* the domain to which elems of the master surf belong is neighbor */
if (evalsum) {
master_gid = cp->master_grp_id[i];
jstart = sgrp->grp_index[master_gid - 1];
jend = sgrp->grp_index[master_gid];
for (j = jstart; j < jend; j++) {
elem = sgrp->grp_item[j * 2];
if (!EVAL_BIT(elem_flag[elem - 1], INTERNAL)) {
MASK_BIT(domain_flag[global_mesh->elem_ID[2 * (elem - 1) + 1]], MASK);
}
}
}
}
return RTC_NORMAL;
}
static int mask_neighbor_domain_eb(const struct hecmwST_local_mesh *global_mesh,
const char *elem_flag, char *domain_flag) {
int i;
for (i = 0; i < global_mesh->n_elem; i++) {
if (EVAL_BIT(elem_flag[i], EXTERNAL) && EVAL_BIT(elem_flag[i], BOUNDARY)) {
MASK_BIT(domain_flag[global_mesh->elem_ID[2 * i + 1]], MASK);
}
}
return RTC_NORMAL;
}
static int count_neighbor_domain(const struct hecmwST_local_mesh *global_mesh,
const char *domain_flag) {
int counter;
int i;
for (counter = 0, i = 0; i < global_mesh->n_subdomain; i++) {
if (EVAL_BIT(domain_flag[i], MASK)) counter++;
}
return counter;
}
static int set_neighbor_domain(const struct hecmwST_local_mesh *global_mesh,
struct hecmwST_local_mesh *local_mesh,
const char *domain_flag) {
int counter;
int i;
for (counter = 0, i = 0; i < global_mesh->n_subdomain; i++) {
if (EVAL_BIT(domain_flag[i], MASK)) {
local_mesh->neighbor_pe[counter++] = i;
}
}
return counter;
}
static int create_neighbor_info(const struct hecmwST_local_mesh *global_mesh,
struct hecmwST_local_mesh *local_mesh,
char *node_flag, char *elem_flag,
int current_domain) {
int rtc;
char *domain_flag = NULL;
HECMW_assert(global_mesh);
HECMW_assert(local_mesh);
HECMW_assert(node_flag);
HECMW_assert(elem_flag);
HECMW_log(HECMW_LOG_DEBUG,
"Starting creation of neighboring domain information...");
local_mesh->n_neighbor_pe = 0;
local_mesh->neighbor_pe = NULL;
domain_flag = (char *)HECMW_calloc(global_mesh->n_subdomain, sizeof(char));
if (domain_flag == NULL) {
HECMW_set_error(errno, "");
goto error;
}
switch (global_mesh->hecmw_flag_parttype) {
case HECMW_FLAG_PARTTYPE_NODEBASED: /* for node-based partitioning */
rtc = mask_mesh_status_nb(global_mesh, node_flag, elem_flag,
current_domain);
if (rtc != RTC_NORMAL) goto error;
if (is_spdup_available(global_mesh)) {
rtc = mask_neighbor_domain_nb_mod(global_mesh, node_flag, domain_flag,
current_domain);
} else {
rtc = mask_neighbor_domain_nb(global_mesh, node_flag, domain_flag);
}
if (rtc != RTC_NORMAL) goto error;
rtc = mask_neighbor_domain_nb_contact(global_mesh, node_flag, elem_flag,
domain_flag);
if (rtc != RTC_NORMAL) goto error;
break;
case HECMW_FLAG_PARTTYPE_ELEMBASED: /* for element-based partitioning */
rtc = mask_mesh_status_eb(global_mesh, node_flag, elem_flag,
current_domain);
if (rtc != RTC_NORMAL) goto error;
rtc = mask_neighbor_domain_eb(global_mesh, elem_flag, domain_flag);
if (rtc != RTC_NORMAL) goto error;
break;
default:
HECMW_set_error(HECMW_PART_E_INVALID_PTYPE, "");
goto error;
}
local_mesh->n_neighbor_pe = count_neighbor_domain(global_mesh, domain_flag);
if (local_mesh->n_neighbor_pe < 0) {
HECMW_set_error(HECMW_PART_E_NNEIGHBORPE_LOWER, "");
goto error;
}
if (local_mesh->n_neighbor_pe == 0) {
local_mesh->neighbor_pe = NULL;
HECMW_free(domain_flag);
return RTC_NORMAL;
}
local_mesh->neighbor_pe =
(int *)HECMW_malloc(sizeof(int) * local_mesh->n_neighbor_pe);
if (local_mesh->neighbor_pe == NULL) {
HECMW_set_error(errno, "");
goto error;
}
rtc = set_neighbor_domain(global_mesh, local_mesh, domain_flag);
HECMW_assert(rtc == local_mesh->n_neighbor_pe);
HECMW_free(domain_flag);
HECMW_log(HECMW_LOG_DEBUG, "Creation of neighboring domain information done");
return RTC_NORMAL;
error:
HECMW_free(domain_flag);
HECMW_free(local_mesh->neighbor_pe);
local_mesh->n_neighbor_pe = 0;
local_mesh->neighbor_pe = NULL;
return RTC_ERROR;
}
/*================================================================================================*/
static int mask_comm_node(const struct hecmwST_local_mesh *global_mesh,
char *node_flag_current, char *node_flag_neighbor) {
int i;
for (i = 0; i < global_mesh->n_node; i++) {
if (EVAL_BIT(node_flag_current[i], BOUNDARY) &&
EVAL_BIT(node_flag_neighbor[i], BOUNDARY)) {
MASK_BIT(node_flag_current[i], MASK);
}
}
return RTC_NORMAL;
}
/*K. Inagaki */
static int mask_comm_node_mod(const struct hecmwST_local_mesh *global_mesh,
char *node_flag_current, char *node_flag_neighbor,
int current_domain) {
int i, node;
for (i = 0; i < n_bnd_nlist[2 * current_domain + 1]; i++) {
node = bnd_nlist[current_domain][i];
if (EVAL_BIT(node_flag_neighbor[node - 1], BOUNDARY)) {
MASK_BIT(node_flag_current[node - 1], MASK);
}
}
return RTC_NORMAL;
}
static int mask_comm_elem(const struct hecmwST_local_mesh *global_mesh,
char *elem_flag_current, char *elem_flag_neighbor) {
int i;
for (i = 0; i < global_mesh->n_elem; i++) {
if (EVAL_BIT(elem_flag_current[i], BOUNDARY) &&
EVAL_BIT(elem_flag_neighbor[i], BOUNDARY)) {
MASK_BIT(elem_flag_current[i], MASK);
}
}
return RTC_NORMAL;
}
/*K. Inagaki */
static int mask_comm_elem_mod(const struct hecmwST_local_mesh *global_mesh,
char *elem_flag_current, char *elem_flag_neighbor,
int current_domain) {
int i, elem;
for (i = 0; i < n_bnd_elist[2 * current_domain + 1]; i++) {
elem = bnd_elist[current_domain][i];
if (EVAL_BIT(elem_flag_neighbor[elem - 1], BOUNDARY)) {
MASK_BIT(elem_flag_current[elem - 1], MASK);
}
}
return RTC_NORMAL;
}
/*K. Inagaki */
static int count_masked_comm_node(const struct hecmwST_local_mesh *global_mesh,
const char *node_flag, int domain) {
int counter;
int i, node;
for (counter = 0, i = 0; i < n_int_nlist[domain]; i++) {
node = int_nlist[domain][i];
if (EVAL_BIT(node_flag[node - 1], MASK)) counter++;
}
return counter;
}
static int count_masked_comm_elem(const struct hecmwST_local_mesh *global_mesh,
const char *elem_flag, int domain) {
int counter;
int i;
for (counter = 0, i = 0; i < global_mesh->n_elem; i++) {
if (EVAL_BIT(elem_flag[i], MASK) &&
global_mesh->elem_ID[2 * i + 1] == domain)
counter++;
}
return counter;
}
static int count_masked_shared_node(
const struct hecmwST_local_mesh *global_mesh, const char *node_flag) {
int counter;
int i;
for (counter = 0, i = 0; i < global_mesh->n_node; i++) {
if (EVAL_BIT(node_flag[i], MASK)) counter++;
}
return counter;
}
static int count_masked_shared_elem(
const struct hecmwST_local_mesh *global_mesh, const char *elem_flag) {
int counter;
int i;
for (counter = 0, i = 0; i < global_mesh->n_elem; i++) {
if (EVAL_BIT(elem_flag[i], MASK)) counter++;
}
return counter;
}
/*K. Inagaki */
static int count_masked_shared_elem_mod(
const struct hecmwST_local_mesh *global_mesh, const char *elem_flag,
int domain) {
int counter;
int i, elem;
for (counter = 0, i = 0; i < n_bnd_elist[2 * domain + 1]; i++) {
elem = bnd_elist[domain][i];
if (EVAL_BIT(elem_flag[elem - 1], MASK)) counter++;
}
return counter;
}
/*K. Inagaki */
static int create_comm_node_pre(const struct hecmwST_local_mesh *global_mesh,
const char *node_flag, int **comm_node,
int neighbor_idx, int domain) {
int counter;
int i, node;
for (counter = 0, i = 0; i < n_int_nlist[domain]; i++) {
node = int_nlist[domain][i];
if (EVAL_BIT(node_flag[node - 1], MASK)) {
comm_node[neighbor_idx][counter++] = node;
}
}
return counter;
}
static int create_comm_elem_pre(const struct hecmwST_local_mesh *global_mesh,
const char *elem_flag, int **comm_elem,
int neighbor_idx, int domain) {
int counter;
int i;
for (counter = 0, i = 0; i < global_mesh->n_elem; i++) {
if (EVAL_BIT(elem_flag[i], MASK) &&
global_mesh->elem_ID[2 * i + 1] == domain) {
comm_elem[neighbor_idx][counter++] = i + 1;
}
}
return counter;
}
static int create_shared_node_pre(const struct hecmwST_local_mesh *global_mesh,
const char *node_flag, int **shared_node,
int neighbor_idx) {
int counter;
int i;
for (counter = 0, i = 0; i < global_mesh->n_node; i++) {
if (EVAL_BIT(node_flag[i], MASK)) {
shared_node[neighbor_idx][counter++] = i + 1;
}
}
return counter;
}
static int create_shared_elem_pre(const struct hecmwST_local_mesh *global_mesh,
const char *elem_flag, int **shared_elem,
int neighbor_idx) {
int counter;
int i;
for (counter = 0, i = 0; i < global_mesh->n_elem; i++) {
if (EVAL_BIT(elem_flag[i], MASK)) {
shared_elem[neighbor_idx][counter++] = i + 1;
}
}
return counter;
}
/*K. Inagaki */
static int create_shared_elem_pre_mod(
const struct hecmwST_local_mesh *global_mesh, const char *elem_flag,
int **shared_elem, int neighbor_idx, int neighbor_domain) {
int counter;
int i, idx1, idx2, elem1, elem2, n_bnd, n_out, maxe;
n_bnd = n_bnd_elist[2 * neighbor_domain];
n_out =
n_bnd_elist[2 * neighbor_domain + 1] - n_bnd_elist[2 * neighbor_domain];
maxe = global_mesh->n_elem + 1;
elem1 = (n_bnd == 0) ? maxe : bnd_elist[neighbor_domain][0];
elem2 = (n_out == 0) ? maxe : bnd_elist[neighbor_domain][n_bnd];
for (counter = 0, idx1 = 0, idx2 = 0, i = 0; i < n_bnd + n_out; i++) {
if (elem1 < elem2) {
if (EVAL_BIT(elem_flag[elem1 - 1], MASK)) {
shared_elem[neighbor_idx][counter++] = elem1;
}
idx1++;
elem1 = (idx1 == n_bnd) ? maxe : bnd_elist[neighbor_domain][idx1];
} else {
if (EVAL_BIT(elem_flag[elem2 - 1], MASK)) {
shared_elem[neighbor_idx][counter++] = elem2;
}
idx2++;
elem2 = (idx2 == n_out) ? maxe : bnd_elist[neighbor_domain][idx2 + n_bnd];
}
}
return counter;
}
static int create_comm_item(int n_neighbor_pe, int **comm_item_pre,
int *comm_index, int *comm_item) {
int i, j, js, je;
for (i = 0; i < n_neighbor_pe; i++) {
js = comm_index[i];
je = comm_index[i + 1];
for (j = 0; j < je - js; j++) {
comm_item[js + j] = comm_item_pre[i][j];
}
}
return RTC_NORMAL;
}
/*------------------------------------------------------------------------------------------------*/
static int create_import_info_nb(const struct hecmwST_local_mesh *global_mesh,
struct hecmwST_local_mesh *local_mesh,
const char *node_flag, int **import_node,
int neighbor_idx, int neighbor_domain) {
int n_import_node, rtc;
n_import_node =
count_masked_comm_node(global_mesh, node_flag, neighbor_domain);
HECMW_assert(n_import_node >= 0);
local_mesh->import_index[neighbor_idx + 1] =
local_mesh->import_index[neighbor_idx] + n_import_node;
import_node[neighbor_idx] = (int *)HECMW_malloc(sizeof(int) * n_import_node);
if (import_node[neighbor_idx] == NULL) {
HECMW_set_error(errno, "");
goto error;
}
rtc = create_comm_node_pre(global_mesh, node_flag, import_node, neighbor_idx,
neighbor_domain);
HECMW_assert(rtc == n_import_node);
return RTC_NORMAL;
error:
return RTC_ERROR;
}
static int create_export_info_nb(const struct hecmwST_local_mesh *global_mesh,
struct hecmwST_local_mesh *local_mesh,
const char *node_flag, int **export_node,
int neighbor_idx, int current_domain,
int neighbor_domain) {
int n_export_node, rtc;
n_export_node =
count_masked_comm_node(global_mesh, node_flag, current_domain);
HECMW_assert(n_export_node >= 0);
local_mesh->export_index[neighbor_idx + 1] =
local_mesh->export_index[neighbor_idx] + n_export_node;
export_node[neighbor_idx] = (int *)HECMW_malloc(sizeof(int) * n_export_node);
if (export_node[neighbor_idx] == NULL) {
HECMW_set_error(errno, "");
goto error;
}
rtc = create_comm_node_pre(global_mesh, node_flag, export_node, neighbor_idx,
current_domain);
HECMW_assert(rtc == n_export_node);
return RTC_NORMAL;
error:
return RTC_ERROR;
}
static int create_shared_info_nb(const struct hecmwST_local_mesh *global_mesh,
struct hecmwST_local_mesh *local_mesh,
const char *elem_flag, int **shared_elem,
int neighbor_idx, int neighbor_domain) {
int n_shared_elem, rtc;
if (is_spdup_available(global_mesh)) {
n_shared_elem =
count_masked_shared_elem_mod(global_mesh, elem_flag, neighbor_domain);
} else {
n_shared_elem = count_masked_shared_elem(global_mesh, elem_flag);
}
HECMW_assert(n_shared_elem >= 0);
local_mesh->shared_index[neighbor_idx + 1] =
local_mesh->shared_index[neighbor_idx] + n_shared_elem;
shared_elem[neighbor_idx] = (int *)HECMW_malloc(sizeof(int) * n_shared_elem);
if (shared_elem[neighbor_idx] == NULL) {
HECMW_set_error(errno, "");
goto error;
}
if (is_spdup_available(global_mesh)) {
rtc = create_shared_elem_pre_mod(global_mesh, elem_flag, shared_elem,
neighbor_idx, neighbor_domain);
} else {
rtc = create_shared_elem_pre(global_mesh, elem_flag, shared_elem,
neighbor_idx);
}
HECMW_assert(rtc == n_shared_elem);
return RTC_NORMAL;
error:
return RTC_ERROR;
}
static int create_comm_info_nb(const struct hecmwST_local_mesh *global_mesh,
struct hecmwST_local_mesh *local_mesh,
char *node_flag, char *elem_flag,
char *node_flag_neighbor,
char *elem_flag_neighbor, int current_domain) {
int **import_node = NULL;
int **export_node = NULL;
int **shared_elem = NULL;
int neighbor_domain;
int size;
int rtc;
int i, j;
local_mesh->import_index = NULL;
local_mesh->export_index = NULL;
local_mesh->shared_index = NULL;
local_mesh->import_item = NULL;
local_mesh->export_item = NULL;
local_mesh->shared_item = NULL;
import_node = (int **)HECMW_malloc(sizeof(int *) * local_mesh->n_neighbor_pe);
if (import_node == NULL) {
HECMW_set_error(errno, "");
goto error;
} else {
for (i = 0; i < local_mesh->n_neighbor_pe; i++) {
import_node[i] = NULL;
}
}
export_node = (int **)HECMW_malloc(sizeof(int *) * local_mesh->n_neighbor_pe);
if (export_node == NULL) {
HECMW_set_error(errno, "");
goto error;
} else {
for (i = 0; i < local_mesh->n_neighbor_pe; i++) {
export_node[i] = NULL;
}
}
shared_elem = (int **)HECMW_malloc(sizeof(int *) * local_mesh->n_neighbor_pe);
if (shared_elem == NULL) {
HECMW_set_error(errno, "");
goto error;
} else {
for (i = 0; i < local_mesh->n_neighbor_pe; i++) {
shared_elem[i] = NULL;
}
}
local_mesh->import_index =
(int *)HECMW_calloc(local_mesh->n_neighbor_pe + 1, sizeof(int));
if (local_mesh->import_index == NULL) {
HECMW_set_error(errno, "");
goto error;
}
local_mesh->export_index =
(int *)HECMW_calloc(local_mesh->n_neighbor_pe + 1, sizeof(int));
if (local_mesh->export_index == NULL) {
HECMW_set_error(errno, "");
goto error;
}
local_mesh->shared_index =
(int *)HECMW_calloc(local_mesh->n_neighbor_pe + 1, sizeof(int));
if (local_mesh->shared_index == NULL) {
HECMW_set_error(errno, "");
goto error;
}
for (i = 0; i < local_mesh->n_neighbor_pe; i++) {
neighbor_domain = local_mesh->neighbor_pe[i];
rtc = mask_mesh_status_nb(global_mesh, node_flag_neighbor,
elem_flag_neighbor, neighbor_domain);
if (rtc != RTC_NORMAL) goto error;
if (is_spdup_available(global_mesh)) {
rtc = mask_comm_node_mod(global_mesh, node_flag, node_flag_neighbor,
current_domain);
} else {
rtc = mask_comm_node(global_mesh, node_flag, node_flag_neighbor);
}
if (rtc != RTC_NORMAL) goto error;
if (is_spdup_available(global_mesh)) {
rtc = mask_comm_elem_mod(global_mesh, elem_flag, elem_flag_neighbor,
current_domain);
} else {
rtc = mask_comm_elem(global_mesh, elem_flag, elem_flag_neighbor);
}
if (rtc != RTC_NORMAL) goto error;
rtc = create_import_info_nb(global_mesh, local_mesh, node_flag, import_node,
i, neighbor_domain);
if (rtc != RTC_NORMAL) goto error;
rtc = create_export_info_nb(global_mesh, local_mesh, node_flag, export_node,
i, current_domain, neighbor_domain);
if (rtc != RTC_NORMAL) goto error;
rtc = create_shared_info_nb(global_mesh, local_mesh, elem_flag, shared_elem,
i, neighbor_domain);
if (rtc != RTC_NORMAL) goto error;
if (is_spdup_available(global_mesh)) {
/*K. Inagaki */
rtc = spdup_clear_IEB(node_flag_neighbor, elem_flag_neighbor,
neighbor_domain);
if (rtc != RTC_NORMAL) goto error;
rtc = spdup_clear_MMbnd(node_flag_neighbor, elem_flag_neighbor,
neighbor_domain);
if (rtc != RTC_NORMAL) goto error;
rtc = spdup_clear_MMbnd(node_flag, elem_flag, current_domain);
if (rtc != RTC_NORMAL) goto error;
} else {
for (j = 0; j < global_mesh->n_node; j++) {
CLEAR_MM(node_flag[j]);
}
for (j = 0; j < global_mesh->n_elem; j++) {
CLEAR_MM(elem_flag[j]);
}
memset(node_flag_neighbor, 0, sizeof(char) * global_mesh->n_node);
memset(elem_flag_neighbor, 0, sizeof(char) * global_mesh->n_elem);
}
}
size = sizeof(int) * local_mesh->import_index[local_mesh->n_neighbor_pe];
local_mesh->import_item = (int *)HECMW_malloc(size);
if (local_mesh->import_item == NULL) {
HECMW_set_error(errno, "");
goto error;
}
rtc = create_comm_item(local_mesh->n_neighbor_pe, import_node,
local_mesh->import_index, local_mesh->import_item);
if (rtc != RTC_NORMAL) goto error;
for (i = 0; i < local_mesh->n_neighbor_pe; i++) {
HECMW_free(import_node[i]);
}
HECMW_free(import_node);
import_node = NULL;
size = sizeof(int) * local_mesh->export_index[local_mesh->n_neighbor_pe];
local_mesh->export_item = (int *)HECMW_malloc(size);
if (local_mesh->export_item == NULL) {
HECMW_set_error(errno, "");
goto error;
}
rtc = create_comm_item(local_mesh->n_neighbor_pe, export_node,
local_mesh->export_index, local_mesh->export_item);
if (rtc != RTC_NORMAL) goto error;
for (i = 0; i < local_mesh->n_neighbor_pe; i++) {
HECMW_free(export_node[i]);
}
HECMW_free(export_node);
export_node = NULL;
size = sizeof(int) * local_mesh->shared_index[local_mesh->n_neighbor_pe];
local_mesh->shared_item = (int *)HECMW_malloc(size);
if (local_mesh->shared_item == NULL) {
HECMW_set_error(errno, "");
goto error;
}
rtc = create_comm_item(local_mesh->n_neighbor_pe, shared_elem,
local_mesh->shared_index, local_mesh->shared_item);
if (rtc != RTC_NORMAL) goto error;
for (i = 0; i < local_mesh->n_neighbor_pe; i++) {
HECMW_free(shared_elem[i]);
}
HECMW_free(shared_elem);
shared_elem = NULL;
return RTC_NORMAL;
error:
if (import_node) {
int i;
for (i = 0; i < local_mesh->n_neighbor_pe; i++) {
HECMW_free(import_node[i]);
}
HECMW_free(import_node);
}
if (export_node) {
int i;
for (i = 0; i < local_mesh->n_neighbor_pe; i++) {
HECMW_free(export_node[i]);
}
HECMW_free(export_node);
}
if (shared_elem) {
int i;
for (i = 0; i < local_mesh->n_neighbor_pe; i++) {
HECMW_free(shared_elem[i]);
}
HECMW_free(shared_elem);
}
HECMW_free(local_mesh->import_index);
HECMW_free(local_mesh->export_index);
HECMW_free(local_mesh->shared_index);
HECMW_free(local_mesh->import_item);
HECMW_free(local_mesh->export_item);
HECMW_free(local_mesh->shared_item);
local_mesh->import_index = NULL;
local_mesh->export_index = NULL;
local_mesh->shared_index = NULL;
local_mesh->import_item = NULL;
local_mesh->export_item = NULL;
local_mesh->shared_item = NULL;
return RTC_ERROR;
}
/*------------------------------------------------------------------------------------------------*/
static int create_import_info_eb(const struct hecmwST_local_mesh *global_mesh,
struct hecmwST_local_mesh *local_mesh,
const char *elem_flag, int **import_elem,
int neighbor_idx, int neighbor_domain) {
int n_import_elem, rtc;
n_import_elem =
count_masked_comm_elem(global_mesh, elem_flag, neighbor_domain);
HECMW_assert(n_import_elem >= 0);
local_mesh->import_index[neighbor_idx + 1] =
local_mesh->import_index[neighbor_idx] + n_import_elem;
import_elem[neighbor_idx] = (int *)HECMW_malloc(sizeof(int) * n_import_elem);
if (import_elem[neighbor_idx] == NULL) {
HECMW_set_error(errno, "");
goto error;
}
rtc = create_comm_elem_pre(global_mesh, elem_flag, import_elem, neighbor_idx,
neighbor_domain);
HECMW_assert(rtc == n_import_elem);
return RTC_NORMAL;
error:
return RTC_ERROR;
}
static int create_export_info_eb(const struct hecmwST_local_mesh *global_mesh,
struct hecmwST_local_mesh *local_mesh,
const char *elem_flag, int **export_elem,
int neighbor_idx, int current_domain,
int neighbor_domain) {
int n_export_elem, rtc;
n_export_elem =
count_masked_comm_elem(global_mesh, elem_flag, current_domain);
HECMW_assert(n_export_elem >= 0);
local_mesh->export_index[neighbor_idx + 1] =
local_mesh->export_index[neighbor_idx] + n_export_elem;
export_elem[neighbor_idx] = (int *)HECMW_malloc(sizeof(int) * n_export_elem);
if (export_elem[neighbor_idx] == NULL) {
HECMW_set_error(errno, "");
goto error;
}
rtc = create_comm_elem_pre(global_mesh, elem_flag, export_elem, neighbor_idx,
current_domain);
HECMW_assert(rtc == n_export_elem);
return RTC_NORMAL;
error:
return RTC_ERROR;
}
static int create_shared_info_eb(const struct hecmwST_local_mesh *global_mesh,
struct hecmwST_local_mesh *local_mesh,
const char *node_flag, int **shared_node,
int neighbor_idx, int neighbor_domain) {
int n_shared_node, rtc;
n_shared_node = count_masked_shared_node(global_mesh, node_flag);
HECMW_assert(n_shared_node >= 0);
local_mesh->shared_index[neighbor_idx + 1] =
local_mesh->shared_index[neighbor_idx] + n_shared_node;
shared_node[neighbor_idx] = (int *)HECMW_malloc(sizeof(int) * n_shared_node);
if (shared_node[neighbor_idx] == NULL) {
HECMW_set_error(errno, "");
goto error;
}
rtc =
create_shared_node_pre(global_mesh, node_flag, shared_node, neighbor_idx);
HECMW_assert(rtc == n_shared_node);
return RTC_NORMAL;
error:
return RTC_ERROR;
}
/*------------------------------------------------------------------------------------------------*/
static int create_comm_info_eb(const struct hecmwST_local_mesh *global_mesh,
struct hecmwST_local_mesh *local_mesh,
char *node_flag, char *elem_flag,
char *node_flag_neighbor,
char *elem_flag_neighbor, int current_domain) {
int **import_elem = NULL;
int **export_elem = NULL;
int **shared_node = NULL;
int neighbor_domain;
int size;
int rtc;
int i, j;
/* allocation */
local_mesh->import_index = NULL;
local_mesh->export_index = NULL;
local_mesh->shared_index = NULL;
local_mesh->import_item = NULL;
local_mesh->export_item = NULL;
local_mesh->shared_item = NULL;
import_elem = (int **)HECMW_malloc(sizeof(int *) * local_mesh->n_neighbor_pe);
if (import_elem == NULL) {
HECMW_set_error(errno, "");
goto error;
} else {
for (i = 0; i < local_mesh->n_neighbor_pe; i++) {
import_elem[i] = NULL;
}
}
export_elem = (int **)HECMW_malloc(sizeof(int *) * local_mesh->n_neighbor_pe);
if (export_elem == NULL) {
HECMW_set_error(errno, "");
goto error;
} else {
for (i = 0; i < local_mesh->n_neighbor_pe; i++) {
export_elem[i] = NULL;
}
}
shared_node = (int **)HECMW_malloc(sizeof(int *) * local_mesh->n_neighbor_pe);
if (shared_node == NULL) {
HECMW_set_error(errno, "");
goto error;
} else {
for (i = 0; i < local_mesh->n_neighbor_pe; i++) {
shared_node[i] = NULL;
}
}
local_mesh->import_index =
(int *)HECMW_calloc(local_mesh->n_neighbor_pe + 1, sizeof(int));
if (local_mesh->import_index == NULL) {
HECMW_set_error(errno, "");
goto error;
}
local_mesh->export_index =
(int *)HECMW_calloc(local_mesh->n_neighbor_pe + 1, sizeof(int));
if (local_mesh->export_index == NULL) {
HECMW_set_error(errno, "");
goto error;
}
local_mesh->shared_index =
(int *)HECMW_calloc(local_mesh->n_neighbor_pe + 1, sizeof(int));
if (local_mesh->shared_index == NULL) {
HECMW_set_error(errno, "");
goto error;
}
/* create communication table */
for (i = 0; i < local_mesh->n_neighbor_pe; i++) {
neighbor_domain = local_mesh->neighbor_pe[i];
for (j = 0; j < global_mesh->n_node; j++) {
CLEAR_BIT(node_flag[j], MASK);
CLEAR_BIT(node_flag[j], MARK);
}
for (j = 0; j < global_mesh->n_elem; j++) {
CLEAR_BIT(elem_flag[j], MASK);
CLEAR_BIT(elem_flag[j], MARK);
}
memset(node_flag_neighbor, 0, sizeof(char) * global_mesh->n_node);
memset(elem_flag_neighbor, 0, sizeof(char) * global_mesh->n_elem);
/* mask boundary node & element */
rtc = mask_mesh_status_eb(global_mesh, node_flag_neighbor,
elem_flag_neighbor, neighbor_domain);
if (rtc != RTC_NORMAL) goto error;
rtc = mask_comm_node(global_mesh, node_flag, node_flag_neighbor);
if (rtc != RTC_NORMAL) goto error;
rtc = mask_comm_elem(global_mesh, elem_flag, elem_flag_neighbor);
if (rtc != RTC_NORMAL) goto error;
/* create import element information (preliminary) */
rtc = create_import_info_eb(global_mesh, local_mesh, elem_flag, import_elem,
i, neighbor_domain);
if (rtc != RTC_NORMAL) goto error;
/* create export element information (preliminary) */
rtc = create_export_info_eb(global_mesh, local_mesh, elem_flag, export_elem,
i, current_domain, neighbor_domain);
if (rtc != RTC_NORMAL) goto error;
/* create shared node information (preliminary) */
rtc = create_shared_info_eb(global_mesh, local_mesh, node_flag, shared_node,
i, neighbor_domain);
if (rtc != RTC_NORMAL) goto error;
}
/* create import element information */
size = sizeof(int) * local_mesh->import_index[local_mesh->n_neighbor_pe];
local_mesh->import_item = (int *)HECMW_malloc(size);
if (local_mesh->import_item == NULL) {
HECMW_set_error(errno, "");
goto error;
}
rtc = create_comm_item(local_mesh->n_neighbor_pe, import_elem,
local_mesh->import_index, local_mesh->import_item);
if (rtc != RTC_NORMAL) goto error;
for (i = 0; i < local_mesh->n_neighbor_pe; i++) {
HECMW_free(import_elem[i]);
}
HECMW_free(import_elem);
import_elem = NULL;
/* create export node information */
size = sizeof(int) * local_mesh->export_index[local_mesh->n_neighbor_pe];
local_mesh->export_item = (int *)HECMW_malloc(size);
if (local_mesh->export_item == NULL) {
HECMW_set_error(errno, "");
goto error;
}
rtc = create_comm_item(local_mesh->n_neighbor_pe, export_elem,
local_mesh->export_index, local_mesh->export_item);
if (rtc != RTC_NORMAL) goto error;
for (i = 0; i < local_mesh->n_neighbor_pe; i++) {
HECMW_free(export_elem[i]);
}
HECMW_free(export_elem);
export_elem = NULL;
/* create shared element information */
size = sizeof(int) * local_mesh->shared_index[local_mesh->n_neighbor_pe];
local_mesh->shared_item = (int *)HECMW_malloc(size);
if (local_mesh->shared_item == NULL) {
HECMW_set_error(errno, "");
goto error;
}
rtc = create_comm_item(local_mesh->n_neighbor_pe, shared_node,
local_mesh->shared_index, local_mesh->shared_item);
if (rtc != RTC_NORMAL) goto error;
for (i = 0; i < local_mesh->n_neighbor_pe; i++) {
HECMW_free(shared_node[i]);
}
HECMW_free(shared_node);
shared_node = NULL;
return RTC_NORMAL;
error:
if (import_elem) {
int i;
for (i = 0; i < local_mesh->n_neighbor_pe; i++) {
HECMW_free(import_elem[i]);
}
HECMW_free(import_elem);
}
if (export_elem) {
int i;
for (i = 0; i < local_mesh->n_neighbor_pe; i++) {
HECMW_free(export_elem[i]);
}
HECMW_free(export_elem);
}
if (shared_node) {
int i;
for (i = 0; i < local_mesh->n_neighbor_pe; i++) {
HECMW_free(shared_node[i]);
}
HECMW_free(shared_node);
}
HECMW_free(local_mesh->import_index);
HECMW_free(local_mesh->export_index);
HECMW_free(local_mesh->shared_index);
HECMW_free(local_mesh->import_item);
HECMW_free(local_mesh->export_item);
HECMW_free(local_mesh->shared_item);
local_mesh->import_index = NULL;
local_mesh->export_index = NULL;
local_mesh->shared_index = NULL;
local_mesh->import_item = NULL;
local_mesh->export_item = NULL;
local_mesh->shared_item = NULL;
return RTC_ERROR;
}
/*================================================================================================*/
static int create_comm_info(const struct hecmwST_local_mesh *global_mesh,
struct hecmwST_local_mesh *local_mesh,
char *node_flag, char *elem_flag,
char *node_flag_neighbor, char *elem_flag_neighbor,
int current_domain) {
int rtc;
HECMW_assert(global_mesh);
HECMW_assert(local_mesh);
HECMW_assert(node_flag);
HECMW_assert(elem_flag);
HECMW_log(HECMW_LOG_DEBUG, "Starting creation of interface table...");
switch (global_mesh->hecmw_flag_parttype) {
case HECMW_FLAG_PARTTYPE_NODEBASED: /* for node-based partitioning */
rtc = create_comm_info_nb(global_mesh, local_mesh, node_flag, elem_flag,
node_flag_neighbor, elem_flag_neighbor,
current_domain);
if (rtc != RTC_NORMAL) goto error;
break;
case HECMW_FLAG_PARTTYPE_ELEMBASED: /* for element-based partitioning */
rtc = create_comm_info_eb(global_mesh, local_mesh, node_flag, elem_flag,
node_flag_neighbor, elem_flag_neighbor,
current_domain);
if (rtc != RTC_NORMAL) goto error;
break;
default:
HECMW_set_error(HECMW_PART_E_INVALID_PTYPE, "");
goto error;
}
HECMW_log(HECMW_LOG_DEBUG, "Creation of interface table done");
return RTC_NORMAL;
error:
return RTC_ERROR;
}
/*==================================================================================================
create distributed mesh information
==================================================================================================*/
/*K. Inagaki */
static int set_node_global2local_internal(
const struct hecmwST_local_mesh *global_mesh,
struct hecmwST_local_mesh *local_mesh, int *node_global2local,
const char *node_flag, int domain) {
int counter;
int i, node;
HECMW_assert(global_mesh);
HECMW_assert(local_mesh);
HECMW_assert(node_global2local);
HECMW_assert(node_flag);
HECMW_assert(global_mesh->n_node > 0);
for (counter = 0, i = 0; i < n_int_nlist[domain]; i++) {
node = int_nlist[domain][i];
node_global2local[node - 1] = ++counter;
}
local_mesh->nn_internal = counter;
return RTC_NORMAL;
}
static int set_node_global2local_external(
const struct hecmwST_local_mesh *global_mesh,
struct hecmwST_local_mesh *local_mesh, int *node_global2local,
const char *node_flag) {
int counter;
int i;
HECMW_assert(global_mesh);
HECMW_assert(local_mesh);
HECMW_assert(node_global2local);
HECMW_assert(node_flag);
HECMW_assert(global_mesh->n_node > 0);
/* ordinary external nodes are marked as BOUNDARY && OVERLAP */
for (counter = local_mesh->nn_internal, i = 0; i < global_mesh->n_node; i++) {
if (!EVAL_BIT(node_flag[i], INTERNAL) && EVAL_BIT(node_flag[i], BOUNDARY) &&
EVAL_BIT(node_flag[i], OVERLAP)) {
node_global2local[i] = ++counter;
}
}
local_mesh->nn_middle = counter;
/* added external contact slave nodes are marked as BOUNDARY but not OVERLAP
*/
for (i = 0; i < global_mesh->n_node; i++) {
if (!EVAL_BIT(node_flag[i], INTERNAL) && EVAL_BIT(node_flag[i], BOUNDARY) &&
!EVAL_BIT(node_flag[i], OVERLAP)) {
node_global2local[i] = ++counter;
}
}
local_mesh->n_node = counter;
local_mesh->n_node_gross = counter;
HECMW_assert(local_mesh->n_node > 0);
return RTC_NORMAL;
}
/*K. Inagaki */
static int set_node_global2local_external_mod(
const struct hecmwST_local_mesh *global_mesh,
struct hecmwST_local_mesh *local_mesh, int *node_global2local,
const char *node_flag, int domain) {
int counter;
int i, node;
HECMW_assert(global_mesh);
HECMW_assert(local_mesh);
HECMW_assert(node_global2local);
HECMW_assert(node_flag);
HECMW_assert(global_mesh->n_node > 0);
for (counter = local_mesh->nn_internal, i = n_bnd_nlist[2 * domain];
i < n_bnd_nlist[2 * domain + 1]; i++) {
node = bnd_nlist[domain][i];
node_global2local[node - 1] = ++counter;
}
local_mesh->n_node = counter;
local_mesh->n_node_gross = counter;
HECMW_assert(local_mesh->n_node > 0);
return RTC_NORMAL;
}
static int set_node_global2local_all(
const struct hecmwST_local_mesh *global_mesh,
struct hecmwST_local_mesh *local_mesh, int *node_global2local,
const char *node_flag) {
int counter;
int i;
HECMW_assert(global_mesh);
HECMW_assert(local_mesh);
HECMW_assert(node_global2local);
HECMW_assert(node_flag);
HECMW_assert(global_mesh->n_node > 0);
for (counter = 0, i = 0; i < global_mesh->n_node; i++) {
if (EVAL_BIT(node_flag[i], INTERNAL) || EVAL_BIT(node_flag[i], BOUNDARY)) {
node_global2local[i] = ++counter;
}
}
local_mesh->n_node = counter;
local_mesh->n_node_gross = counter;
HECMW_assert(local_mesh->n_node > 0);
return RTC_NORMAL;
}
static int const_nn_internal(const struct hecmwST_local_mesh *global_mesh,
struct hecmwST_local_mesh *local_mesh,
const char *node_flag) {
int counter;
int i;
HECMW_assert(global_mesh);
HECMW_assert(local_mesh);
HECMW_assert(node_flag);
HECMW_assert(global_mesh->n_node > 0);
for (counter = 0, i = 0; i < global_mesh->n_node; i++) {
if (EVAL_BIT(node_flag[i], INTERNAL)) counter++;
}
local_mesh->nn_internal = counter;
return 0;
}
static int const_node_internal_list(
const struct hecmwST_local_mesh *global_mesh,
struct hecmwST_local_mesh *local_mesh, int *node_global2local,
const char *node_flag) {
int counter;
int i;
HECMW_assert(global_mesh);
HECMW_assert(local_mesh);
HECMW_assert(node_global2local);
HECMW_assert(node_flag);
HECMW_assert(global_mesh->n_node > 0);
if (local_mesh->nn_internal == 0) {
local_mesh->node_internal_list = NULL;
return RTC_NORMAL;
}
local_mesh->node_internal_list =
(int *)HECMW_malloc(sizeof(int) * local_mesh->nn_internal);
if (local_mesh->node_internal_list == NULL) {
HECMW_set_error(errno, "");
goto error;
}
for (counter = 0, i = 0; i < global_mesh->n_node; i++) {
if (EVAL_BIT(node_flag[i], INTERNAL)) {
local_mesh->node_internal_list[counter++] = node_global2local[i];
}
}
HECMW_assert(counter == local_mesh->nn_internal);
return RTC_NORMAL;
error:
return RTC_ERROR;
}
/*K. Inagaki */
static int set_node_global2local(const struct hecmwST_local_mesh *global_mesh,
struct hecmwST_local_mesh *local_mesh,
int *node_global2local, const char *node_flag,
int current_domain) {
int rtc;
HECMW_assert(global_mesh);
HECMW_assert(local_mesh);
HECMW_assert(node_global2local);
HECMW_assert(node_flag);
switch (global_mesh->hecmw_flag_parttype) {
case HECMW_FLAG_PARTTYPE_NODEBASED:
rtc = set_node_global2local_internal(global_mesh, local_mesh,
node_global2local, node_flag,
current_domain);
if (rtc != RTC_NORMAL) goto error;
if (is_spdup_available(global_mesh)) {
rtc = set_node_global2local_external_mod(global_mesh, local_mesh,
node_global2local, node_flag,
current_domain);
} else {
rtc = set_node_global2local_external(global_mesh, local_mesh,
node_global2local, node_flag);
}
if (rtc != RTC_NORMAL) goto error;
local_mesh->node_internal_list = NULL;
break;
case HECMW_FLAG_PARTTYPE_ELEMBASED:
rtc = const_nn_internal(global_mesh, local_mesh, node_flag);
if (rtc != RTC_NORMAL) goto error;
rtc = set_node_global2local_all(global_mesh, local_mesh,
node_global2local, node_flag);
if (rtc != RTC_NORMAL) goto error;
rtc = const_node_internal_list(global_mesh, local_mesh, node_global2local,
node_flag);
if (rtc != RTC_NORMAL) goto error;
break;
default:
HECMW_set_error(HECMW_PART_E_INVALID_PTYPE, "%d",
global_mesh->hecmw_flag_parttype);
goto error;
}
return RTC_NORMAL;
error:
return RTC_ERROR;
}
/*K. Inagaki */
static int clear_node_global2local(const struct hecmwST_local_mesh *global_mesh,
struct hecmwST_local_mesh *local_mesh,
int *node_global2local, int domain) {
int rtc;
int i, node;
HECMW_assert(global_mesh);
HECMW_assert(local_mesh);
HECMW_assert(node_global2local);
if (is_spdup_available(global_mesh)) {
for (i = 0; i < n_int_nlist[domain]; i++) {
node = int_nlist[domain][i];
node_global2local[node - 1] = 0;
}
for (i = n_bnd_nlist[2 * domain]; i < n_bnd_nlist[2 * domain + 1]; i++) {
node = bnd_nlist[domain][i];
node_global2local[node - 1] = 0;
}
} else {
for (i = 0; i < global_mesh->n_node; i++) {
node_global2local[i] = 0;
}
}
return RTC_NORMAL;
}
/*------------------------------------------------------------------------------------------------*/
static int set_node_local2global(const struct hecmwST_local_mesh *global_mesh,
struct hecmwST_local_mesh *local_mesh,
const int *node_global2local,
int *node_local2global) {
int counter;
int i;
HECMW_assert(global_mesh);
HECMW_assert(local_mesh);
HECMW_assert(node_global2local);
HECMW_assert(node_local2global);
HECMW_assert(global_mesh->n_node > 0);
for (counter = 0, i = 0; i < global_mesh->n_node; i++) {
if (node_global2local[i]) {
node_local2global[node_global2local[i] - 1] = i + 1;
counter++;
}
}
HECMW_assert(counter == local_mesh->n_node);
return RTC_NORMAL;
}
/*K. Inagaki */
static int set_node_local2global_mod(
const struct hecmwST_local_mesh *global_mesh,
struct hecmwST_local_mesh *local_mesh, const int *node_global2local,
int *node_local2global, int domain) {
int counter;
int i, idx1, idx2, node1, node2, n_int, n_bnd, n_out, maxn;
HECMW_assert(global_mesh);
HECMW_assert(local_mesh);
HECMW_assert(node_global2local);
HECMW_assert(node_local2global);
HECMW_assert(global_mesh->n_node > 0);
n_int = n_int_nlist[domain];
n_bnd = n_bnd_nlist[2 * domain];
n_out = n_bnd_nlist[2 * domain + 1] - n_bnd_nlist[2 * domain];
maxn = global_mesh->n_node + 1;
node1 = (n_int == 0) ? maxn : int_nlist[domain][0];
node2 = (n_out == 0) ? maxn : bnd_nlist[domain][n_bnd];
for (counter = 0, idx1 = 0, idx2 = 0, i = 0; i < n_int + n_out; i++) {
if (node1 < node2) {
node_local2global[node_global2local[node1 - 1] - 1] = node1;
idx1++;
node1 = (idx1 == n_int) ? maxn : int_nlist[domain][idx1];
} else {
node_local2global[node_global2local[node2 - 1] - 1] = node2;
idx2++;
node2 = (idx2 == n_out) ? maxn : bnd_nlist[domain][idx2 + n_bnd];
}
counter++;
}
HECMW_assert(counter == local_mesh->n_node);
return RTC_NORMAL;
}
/*------------------------------------------------------------------------------------------------*/
static int set_elem_global2local_internal(
const struct hecmwST_local_mesh *global_mesh,
struct hecmwST_local_mesh *local_mesh, int *elem_global2local,
const char *elem_flag) {
int counter;
int i;
HECMW_assert(global_mesh);
HECMW_assert(local_mesh);
HECMW_assert(elem_global2local);
HECMW_assert(elem_flag);
HECMW_assert(global_mesh->n_elem);
for (counter = 0, i = 0; i < global_mesh->n_elem; i++) {
if (EVAL_BIT(elem_flag[i], INTERNAL)) {
elem_global2local[i] = ++counter;
}
}
local_mesh->ne_internal = counter;
return RTC_NORMAL;
}
static int set_elem_global2local_external(
const struct hecmwST_local_mesh *global_mesh,
struct hecmwST_local_mesh *local_mesh, int *elem_global2local,
const char *elem_flag) {
int counter;
int i;
HECMW_assert(global_mesh);
HECMW_assert(local_mesh);
HECMW_assert(elem_global2local);
HECMW_assert(elem_flag);
HECMW_assert(global_mesh->n_elem);
for (counter = local_mesh->ne_internal, i = 0; i < global_mesh->n_elem; i++) {
if (!EVAL_BIT(elem_flag[i], INTERNAL) && EVAL_BIT(elem_flag[i], BOUNDARY)) {
elem_global2local[i] = ++counter;
}
}
local_mesh->n_elem = counter;
local_mesh->n_elem_gross = counter;
HECMW_assert(local_mesh->n_elem > 0);
return RTC_NORMAL;
}
static int set_elem_global2local_all(
const struct hecmwST_local_mesh *global_mesh,
struct hecmwST_local_mesh *local_mesh, int *elem_global2local,
const char *elem_flag) {
int counter;
int i;
HECMW_assert(global_mesh);
HECMW_assert(local_mesh);
HECMW_assert(elem_global2local);
HECMW_assert(elem_flag);
HECMW_assert(global_mesh->n_elem > 0);
for (counter = 0, i = 0; i < global_mesh->n_elem; i++) {
if (EVAL_BIT(elem_flag[i], INTERNAL) || EVAL_BIT(elem_flag[i], BOUNDARY)) {
elem_global2local[i] = ++counter;
}
}
local_mesh->n_elem = counter;
local_mesh->n_elem_gross = counter;
HECMW_assert(local_mesh->n_elem > 0);
return RTC_NORMAL;
}
/*K. Inagaki */
static int set_elem_global2local_all_mod(
const struct hecmwST_local_mesh *global_mesh,
struct hecmwST_local_mesh *local_mesh, int *elem_global2local,
const char *elem_flag, int domain) {
int counter;
int i, idx1, idx2, elem1, elem2, n_int, n_bnd, n_out, maxe;
HECMW_assert(global_mesh);
HECMW_assert(local_mesh);
HECMW_assert(elem_global2local);
HECMW_assert(elem_flag);
HECMW_assert(global_mesh->n_elem > 0);
n_int = n_int_elist[domain];
n_bnd = n_bnd_elist[2 * domain];
n_out = n_bnd_elist[2 * domain + 1] - n_bnd_elist[2 * domain];
maxe = global_mesh->n_elem + 1;
elem1 = (n_int == 0) ? maxe : int_elist[domain][0];
elem2 = (n_out == 0) ? maxe : bnd_elist[domain][n_bnd];
for (counter = 0, idx1 = 0, idx2 = 0, i = 0; i < n_int + n_out; i++) {
if (elem1 < elem2) {
elem_global2local[elem1 - 1] = ++counter;
idx1++;
elem1 = (idx1 == n_int) ? maxe : int_elist[domain][idx1];
} else {
elem_global2local[elem2 - 1] = ++counter;
idx2++;
elem2 = (idx2 == n_out) ? maxe : bnd_elist[domain][idx2 + n_bnd];
}
}
local_mesh->n_elem = counter;
local_mesh->n_elem_gross = counter;
HECMW_assert(local_mesh->n_elem > 0);
return RTC_NORMAL;
}
static int const_ne_internal(const struct hecmwST_local_mesh *global_mesh,
struct hecmwST_local_mesh *local_mesh,
const char *elem_flag) {
int counter;
int i;
HECMW_assert(global_mesh->n_elem > 0);
for (counter = 0, i = 0; i < global_mesh->n_elem; i++) {
if (EVAL_BIT(elem_flag[i], INTERNAL)) counter++;
}
local_mesh->ne_internal = counter;
return RTC_NORMAL;
}
/*K. Inagaki */
static int const_elem_internal_list(
const struct hecmwST_local_mesh *global_mesh,
struct hecmwST_local_mesh *local_mesh, int *elem_global2local,
const char *elem_flag, int domain) {
int counter;
int i, elem;
HECMW_assert(global_mesh);
HECMW_assert(local_mesh);
HECMW_assert(elem_global2local);
HECMW_assert(elem_flag);
HECMW_assert(global_mesh->n_elem > 0);
if (local_mesh->ne_internal == 0) {
local_mesh->elem_internal_list = NULL;
return RTC_NORMAL;
}
local_mesh->elem_internal_list =
(int *)HECMW_malloc(sizeof(int) * local_mesh->ne_internal);
if (local_mesh->elem_internal_list == NULL) {
HECMW_set_error(errno, "");
goto error;
}
for (counter = 0, i = 0; i < n_int_elist[domain]; i++) {
elem = int_elist[domain][i];
local_mesh->elem_internal_list[counter++] = elem_global2local[elem - 1];
}
HECMW_assert(counter == local_mesh->ne_internal);
return RTC_NORMAL;
error:
return RTC_ERROR;
}
static int set_elem_global2local(const struct hecmwST_local_mesh *global_mesh,
struct hecmwST_local_mesh *local_mesh,
int *elem_global2local, const char *elem_flag,
int current_domain) {
int rtc;
HECMW_assert(global_mesh);
HECMW_assert(local_mesh);
HECMW_assert(elem_global2local);
HECMW_assert(elem_flag);
switch (global_mesh->hecmw_flag_parttype) {
case HECMW_FLAG_PARTTYPE_NODEBASED: /* for node-based partitioning */
local_mesh->ne_internal = n_int_elist[current_domain];
if (is_spdup_available(global_mesh)) {
rtc = set_elem_global2local_all_mod(global_mesh, local_mesh,
elem_global2local, elem_flag,
current_domain);
} else {
rtc = set_elem_global2local_all(global_mesh, local_mesh,
elem_global2local, elem_flag);
}
if (rtc != RTC_NORMAL) goto error;
rtc = const_elem_internal_list(global_mesh, local_mesh, elem_global2local,
elem_flag, current_domain);
if (rtc != RTC_NORMAL) goto error;
break;
case HECMW_FLAG_PARTTYPE_ELEMBASED: /* for element-based partitioning */
rtc = set_elem_global2local_internal(global_mesh, local_mesh,
elem_global2local, elem_flag);
if (rtc != RTC_NORMAL) goto error;
rtc = set_elem_global2local_external(global_mesh, local_mesh,
elem_global2local, elem_flag);
if (rtc != RTC_NORMAL) goto error;
local_mesh->elem_internal_list = NULL;
break;
default:
HECMW_set_error(HECMW_PART_E_INVALID_PTYPE, "%d",
global_mesh->hecmw_flag_parttype);
goto error;
}
return RTC_NORMAL;
error:
return RTC_ERROR;
}
static int clear_elem_global2local(const struct hecmwST_local_mesh *global_mesh,
struct hecmwST_local_mesh *local_mesh,
int *elem_global2local, int domain) {
int rtc;
int i, elem;
HECMW_assert(global_mesh);
HECMW_assert(local_mesh);
HECMW_assert(elem_global2local);
if (is_spdup_available(global_mesh)) {
for (i = 0; i < n_int_elist[domain]; i++) {
elem = int_elist[domain][i];
elem_global2local[elem - 1] = 0;
}
for (i = n_bnd_elist[2 * domain]; i < n_bnd_elist[2 * domain + 1]; i++) {
elem = bnd_elist[domain][i];
elem_global2local[elem - 1] = 0;
}
} else {
for (i = 0; i < global_mesh->n_elem; i++) {
elem_global2local[i] = 0;
}
}
return RTC_NORMAL;
}
/*------------------------------------------------------------------------------------------------*/
static int set_elem_local2global(const struct hecmwST_local_mesh *global_mesh,
struct hecmwST_local_mesh *local_mesh,
const int *elem_global2local,
int *elem_local2global) {
int counter;
int i;
HECMW_assert(global_mesh);
HECMW_assert(local_mesh);
HECMW_assert(elem_global2local);
HECMW_assert(elem_local2global);
HECMW_assert(global_mesh->n_elem > 0);
for (counter = 0, i = 0; i < global_mesh->n_elem; i++) {
if (elem_global2local[i]) {
elem_local2global[elem_global2local[i] - 1] = i + 1;
counter++;
}
}
HECMW_assert(counter == local_mesh->n_elem);
return RTC_NORMAL;
}
/*K. Inagaki */
static int set_elem_local2global_mod(
const struct hecmwST_local_mesh *global_mesh,
struct hecmwST_local_mesh *local_mesh, const int *elem_global2local,
int *elem_local2global, int domain) {
int counter;
int i, idx1, idx2, elem1, elem2, n_int, n_bnd, n_out, maxe;
HECMW_assert(global_mesh);
HECMW_assert(local_mesh);
HECMW_assert(elem_global2local);
HECMW_assert(elem_local2global);
HECMW_assert(global_mesh->n_elem > 0);
n_int = n_int_elist[domain];
n_bnd = n_bnd_elist[2 * domain];
n_out = n_bnd_elist[2 * domain + 1] - n_bnd_elist[2 * domain];
maxe = global_mesh->n_elem + 1;
elem1 = (n_int == 0) ? maxe : int_elist[domain][0];
elem2 = (n_out == 0) ? maxe : bnd_elist[domain][n_bnd];
for (counter = 0, idx1 = 0, idx2 = 0, i = 0; i < n_int + n_out; i++) {
if (elem1 < elem2) {
elem_local2global[elem_global2local[elem1 - 1] - 1] = elem1;
idx1++;
elem1 = (idx1 == n_int) ? maxe : int_elist[domain][idx1];
} else {
elem_local2global[elem_global2local[elem2 - 1] - 1] = elem2;
idx2++;
elem2 = (idx2 == n_out) ? maxe : bnd_elist[domain][idx2 + n_bnd];
}
counter++;
}
HECMW_assert(counter == local_mesh->n_elem);
return RTC_NORMAL;
}
/*================================================================================================*/
static int const_gridfile(const struct hecmwST_local_mesh *global_mesh,
struct hecmwST_local_mesh *local_mesh) {
strcpy(local_mesh->gridfile, global_mesh->gridfile);
return RTC_NORMAL;
}
static int const_hecmw_n_file(const struct hecmwST_local_mesh *global_mesh,
struct hecmwST_local_mesh *local_mesh) {
local_mesh->hecmw_n_file = global_mesh->hecmw_n_file;
return RTC_NORMAL;
}
static int const_files(const struct hecmwST_local_mesh *global_mesh,
struct hecmwST_local_mesh *local_mesh) {
local_mesh->files = global_mesh->files;
return RTC_NORMAL;
}
static int const_header(const struct hecmwST_local_mesh *global_mesh,
struct hecmwST_local_mesh *local_mesh) {
strcpy(local_mesh->header, global_mesh->header);
return RTC_NORMAL;
}
static int const_hecmw_flag_adapt(const struct hecmwST_local_mesh *global_mesh,
struct hecmwST_local_mesh *local_mesh) {
local_mesh->hecmw_flag_adapt = global_mesh->hecmw_flag_adapt;
return RTC_NORMAL;
}
static int const_hecmw_flag_initcon(
const struct hecmwST_local_mesh *global_mesh,
struct hecmwST_local_mesh *local_mesh) {
local_mesh->hecmw_flag_initcon = global_mesh->hecmw_flag_initcon;
return RTC_NORMAL;
}
static int const_hecmw_flag_parttype(
const struct hecmwST_local_mesh *global_mesh,
struct hecmwST_local_mesh *local_mesh) {
local_mesh->hecmw_flag_parttype = global_mesh->hecmw_flag_parttype;
return RTC_NORMAL;
}
static int const_hecmw_flag_partdepth(
const struct hecmwST_local_mesh *global_mesh,
struct hecmwST_local_mesh *local_mesh) {
local_mesh->hecmw_flag_partdepth = global_mesh->hecmw_flag_partdepth;
return RTC_NORMAL;
}
static int const_hecmw_flag_version(
const struct hecmwST_local_mesh *global_mesh,
struct hecmwST_local_mesh *local_mesh) {
local_mesh->hecmw_flag_version = global_mesh->hecmw_flag_version;
return RTC_NORMAL;
}
static int const_hecmw_flag_partcontact(
const struct hecmwST_local_mesh *global_mesh,
struct hecmwST_local_mesh *local_mesh) {
local_mesh->hecmw_flag_partcontact = global_mesh->hecmw_flag_partcontact;
return RTC_NORMAL;
}
static int const_zero_temp(const struct hecmwST_local_mesh *global_mesh,
struct hecmwST_local_mesh *local_mesh) {
local_mesh->zero_temp = global_mesh->zero_temp;
return RTC_NORMAL;
}
static int const_global_info(const struct hecmwST_local_mesh *global_mesh,
struct hecmwST_local_mesh *local_mesh) {
int rtc;
HECMW_assert(global_mesh);
HECMW_assert(local_mesh);
rtc = const_gridfile(global_mesh, local_mesh);
if (rtc != RTC_NORMAL) goto error;
rtc = const_hecmw_n_file(global_mesh, local_mesh);
if (rtc != RTC_NORMAL) goto error;
rtc = const_files(global_mesh, local_mesh);
if (rtc != RTC_NORMAL) goto error;
rtc = const_header(global_mesh, local_mesh);
if (rtc != RTC_NORMAL) goto error;
rtc = const_hecmw_flag_adapt(global_mesh, local_mesh);
if (rtc != RTC_NORMAL) goto error;
rtc = const_hecmw_flag_initcon(global_mesh, local_mesh);
if (rtc != RTC_NORMAL) goto error;
rtc = const_hecmw_flag_parttype(global_mesh, local_mesh);
if (rtc != RTC_NORMAL) goto error;
rtc = const_hecmw_flag_partdepth(global_mesh, local_mesh);
if (rtc != RTC_NORMAL) goto error;
rtc = const_hecmw_flag_version(global_mesh, local_mesh);
if (rtc != RTC_NORMAL) goto error;
rtc = const_hecmw_flag_partcontact(global_mesh, local_mesh);
if (rtc != RTC_NORMAL) goto error;
rtc = const_zero_temp(global_mesh, local_mesh);
if (rtc != RTC_NORMAL) goto error;
return RTC_NORMAL;
error:
return RTC_ERROR;
}
/*- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
* - - - - - - - - - */
static int const_n_dof(const struct hecmwST_local_mesh *global_mesh,
struct hecmwST_local_mesh *local_mesh) {
HECMW_assert(global_mesh->n_dof > 0);
local_mesh->n_dof = global_mesh->n_dof;
HECMW_assert(local_mesh->n_dof > 0);
return RTC_NORMAL;
}
static int const_n_dof_grp(const struct hecmwST_local_mesh *global_mesh,
struct hecmwST_local_mesh *local_mesh) {
HECMW_assert(global_mesh->n_dof_grp);
local_mesh->n_dof_grp = global_mesh->n_dof_grp;
HECMW_assert(global_mesh->n_dof_grp);
return RTC_NORMAL;
}
static int const_node_dof_index(const struct hecmwST_local_mesh *global_mesh,
struct hecmwST_local_mesh *local_mesh,
const char *node_flag) {
int counter;
int i, j;
HECMW_assert(local_mesh->n_dof_grp > 0);
HECMW_assert(global_mesh->node_dof_index);
local_mesh->node_dof_index =
(int *)HECMW_calloc(local_mesh->n_dof_grp + 1, sizeof(int));
if (local_mesh->node_dof_index == NULL) {
HECMW_set_error(errno, "");
goto error;
}
for (counter = 0, i = 0; i < global_mesh->n_dof_grp; i++) {
for (j = global_mesh->node_dof_index[i];
j < global_mesh->node_dof_index[i + 1]; j++) {
if (EVAL_BIT(node_flag[j], INTERNAL)) counter++;
}
local_mesh->node_dof_index[i + 1] = counter;
}
HECMW_assert(local_mesh->node_dof_index[local_mesh->n_dof_grp] ==
local_mesh->nn_internal);
return RTC_NORMAL;
error:
return RTC_ERROR;
}
/*K. Inagaki */
static int const_node_dof_index_mod(
const struct hecmwST_local_mesh *global_mesh,
struct hecmwST_local_mesh *local_mesh, const char *node_flag, int domain) {
int counter;
int i, j, node;
HECMW_assert(local_mesh->n_dof_grp > 0);
HECMW_assert(global_mesh->node_dof_index);
local_mesh->node_dof_index =
(int *)HECMW_calloc(local_mesh->n_dof_grp + 1, sizeof(int));
if (local_mesh->node_dof_index == NULL) {
HECMW_set_error(errno, "");
goto error;
}
for (counter = 0, i = 0; i < global_mesh->n_dof_grp; i++) {
for (j = 0; j < n_int_nlist[domain]; j++) {
node = int_nlist[domain][j];
if (node <= global_mesh->node_dof_index[i]) continue;
if (node > global_mesh->node_dof_index[i + 1]) continue;
counter++;
}
local_mesh->node_dof_index[i + 1] = counter;
}
return RTC_NORMAL;
error:
return RTC_ERROR;
}
static int const_node_dof_item(const struct hecmwST_local_mesh *global_mesh,
struct hecmwST_local_mesh *local_mesh) {
HECMW_assert(global_mesh->node_dof_item);
local_mesh->node_dof_item = global_mesh->node_dof_item;
return 0;
}
static int const_node(const struct hecmwST_local_mesh *global_mesh,
struct hecmwST_local_mesh *local_mesh,
const int *node_local2global) {
int i;
HECMW_assert(local_mesh->n_node > 0);
HECMW_assert(global_mesh->node);
local_mesh->node =
(double *)HECMW_malloc(sizeof(double) * local_mesh->n_node * 3);
if (local_mesh->node == NULL) {
HECMW_set_error(errno, "");
goto error;
}
for (i = 0; i < local_mesh->n_node; i++) {
local_mesh->node[3 * i] = global_mesh->node[3 * (node_local2global[i] - 1)];
local_mesh->node[3 * i + 1] =
global_mesh->node[3 * (node_local2global[i] - 1) + 1];
local_mesh->node[3 * i + 2] =
global_mesh->node[3 * (node_local2global[i] - 1) + 2];
}
return RTC_NORMAL;
error:
return RTC_ERROR;
}
static int const_node_id(const struct hecmwST_local_mesh *global_mesh,
struct hecmwST_local_mesh *local_mesh,
const int *node_local2global) {
int i;
HECMW_assert(local_mesh->n_node > 0);
HECMW_assert(global_mesh->node_ID);
local_mesh->node_ID =
(int *)HECMW_malloc(sizeof(int) * local_mesh->n_node * 2);
if (local_mesh->node_ID == NULL) {
HECMW_set_error(errno, "");
goto error;
}
for (i = 0; i < local_mesh->n_node; i++) {
local_mesh->node_ID[2 * i] =
global_mesh->node_ID[2 * (node_local2global[i] - 1)];
local_mesh->node_ID[2 * i + 1] =
global_mesh->node_ID[2 * (node_local2global[i] - 1) + 1];
}
return RTC_NORMAL;
error:
return RTC_ERROR;
}
static int const_global_node_id(const struct hecmwST_local_mesh *global_mesh,
struct hecmwST_local_mesh *local_mesh,
const int *node_local2global) {
int i;
HECMW_assert(local_mesh->n_node > 0);
HECMW_assert(global_mesh->global_node_ID);
local_mesh->global_node_ID =
(int *)HECMW_malloc(sizeof(int) * local_mesh->n_node);
if (local_mesh->global_node_ID == NULL) {
HECMW_set_error(errno, "");
goto error;
}
for (i = 0; i < local_mesh->n_node; i++) {
local_mesh->global_node_ID[i] =
global_mesh->global_node_ID[node_local2global[i] - 1];
}
return RTC_NORMAL;
error:
return RTC_ERROR;
}
static int const_node_init_val_index(
const struct hecmwST_local_mesh *global_mesh,
struct hecmwST_local_mesh *local_mesh, const int *node_local2global) {
int old_idx;
int i;
HECMW_assert(local_mesh->hecmw_flag_initcon);
HECMW_assert(local_mesh->n_node > 0);
HECMW_assert(global_mesh->node_init_val_index);
local_mesh->node_init_val_index =
(int *)HECMW_calloc(local_mesh->n_node + 1, sizeof(int));
if (local_mesh->node_init_val_index == NULL) {
HECMW_set_error(errno, "");
goto error;
}
for (i = 0; i < local_mesh->n_node; i++) {
old_idx = node_local2global[i] - 1;
local_mesh->node_init_val_index[i + 1] =
local_mesh->node_init_val_index[i] +
global_mesh->node_init_val_index[old_idx + 1] -
global_mesh->node_init_val_index[old_idx];
}
return RTC_NORMAL;
error:
return RTC_ERROR;
}
static int const_node_init_val_item(
const struct hecmwST_local_mesh *global_mesh,
struct hecmwST_local_mesh *local_mesh, const int *node_local2global) {
int size;
int counter;
int i, j, gstart, gend, lstart, lend;
HECMW_assert(local_mesh->hecmw_flag_initcon);
HECMW_assert(local_mesh->n_node > 0);
HECMW_assert(local_mesh->node_init_val_index);
HECMW_assert(global_mesh->node_init_val_item);
if (local_mesh->node_init_val_index[local_mesh->n_node] == 0) {
local_mesh->node_init_val_item = NULL;
return 0;
}
size = sizeof(double) * local_mesh->node_init_val_index[local_mesh->n_node];
local_mesh->node_init_val_item = (double *)HECMW_malloc(size);
if (local_mesh->node_init_val_item == NULL) {
HECMW_set_error(errno, "");
goto error;
}
for (counter = 0, i = 0; i < local_mesh->n_node; i++) {
gstart = global_mesh->node_init_val_index[node_local2global[i] - 1];
gend = global_mesh->node_init_val_index[node_local2global[i]];
lstart = local_mesh->node_init_val_index[i];
lend = local_mesh->node_init_val_index[i + 1];
HECMW_assert(gend - gstart == lend - lstart);
for (j = 0; j < lend - lstart; j++) {
local_mesh->node_init_val_item[lstart + j] =
global_mesh->node_init_val_item[gstart + j];
counter++;
}
HECMW_assert(counter == local_mesh->node_init_val_index[i + 1]);
}
return RTC_NORMAL;
error:
return RTC_ERROR;
}
static int const_node_info(const struct hecmwST_local_mesh *global_mesh,
struct hecmwST_local_mesh *local_mesh,
const int *node_local2global, const char *node_flag,
int current_domain) {
int rtc;
HECMW_assert(global_mesh);
HECMW_assert(local_mesh);
HECMW_assert(node_local2global);
HECMW_assert(node_flag);
rtc = const_n_dof(global_mesh, local_mesh);
if (rtc != RTC_NORMAL) goto error;
rtc = const_n_dof_grp(global_mesh, local_mesh);
if (rtc != RTC_NORMAL) goto error;
switch (global_mesh->hecmw_flag_parttype) {
case HECMW_FLAG_PARTTYPE_NODEBASED:
rtc = const_node_dof_index_mod(global_mesh, local_mesh, node_flag,
current_domain);
break;
case HECMW_FLAG_PARTTYPE_ELEMBASED:
rtc = const_node_dof_index(global_mesh, local_mesh, node_flag);
break;
default:
HECMW_set_error(errno, "");
goto error;
}
if (rtc != RTC_NORMAL) goto error;
rtc = const_node_dof_item(global_mesh, local_mesh);
if (rtc != RTC_NORMAL) goto error;
rtc = const_node(global_mesh, local_mesh, node_local2global);
if (rtc != RTC_NORMAL) goto error;
rtc = const_node_id(global_mesh, local_mesh, node_local2global);
if (rtc != RTC_NORMAL) goto error;
rtc = const_global_node_id(global_mesh, local_mesh, node_local2global);
if (rtc != RTC_NORMAL) goto error;
if (local_mesh->hecmw_flag_initcon) {
rtc = const_node_init_val_index(global_mesh, local_mesh, node_local2global);
if (rtc != RTC_NORMAL) goto error;
rtc = const_node_init_val_item(global_mesh, local_mesh, node_local2global);
if (rtc != RTC_NORMAL) goto error;
}
return RTC_NORMAL;
error:
return RTC_ERROR;
}
/*- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
* - - - - - - - - - */
static int const_n_elem_type(const struct hecmwST_local_mesh *global_mesh,
struct hecmwST_local_mesh *local_mesh) {
HECMW_assert(global_mesh->n_elem_type > 0);
local_mesh->n_elem_type = global_mesh->n_elem_type;
HECMW_assert(local_mesh->n_elem_type > 0);
return RTC_NORMAL;
}
static int const_elem_type(const struct hecmwST_local_mesh *global_mesh,
struct hecmwST_local_mesh *local_mesh,
const int *elem_local2global) {
int i;
HECMW_assert(local_mesh->n_elem > 0);
HECMW_assert(global_mesh->elem_type);
local_mesh->elem_type = (int *)HECMW_malloc(sizeof(int) * local_mesh->n_elem);
if (local_mesh->elem_type == NULL) {
HECMW_set_error(errno, "");
goto error;
}
for (i = 0; i < local_mesh->n_elem; i++) {
local_mesh->elem_type[i] = global_mesh->elem_type[elem_local2global[i] - 1];
}
return RTC_NORMAL;
error:
return RTC_ERROR;
}
static int const_elem_type_index(const struct hecmwST_local_mesh *global_mesh,
struct hecmwST_local_mesh *local_mesh,
const int *elem_global2local) {
int counter;
int i, j;
HECMW_assert(local_mesh->n_elem_type > 0);
HECMW_assert(global_mesh->n_elem_type > 0);
HECMW_assert(global_mesh->elem_type_index);
local_mesh->elem_type_index =
(int *)HECMW_calloc(local_mesh->n_elem_type + 1, sizeof(int));
if (local_mesh->elem_type_index == NULL) {
HECMW_set_error(errno, "");
goto error;
}
for (counter = 0, i = 0; i < global_mesh->n_elem_type; i++) {
for (j = global_mesh->elem_type_index[i];
j < global_mesh->elem_type_index[i + 1]; j++) {
if (elem_global2local[j]) counter++;
}
local_mesh->elem_type_index[i + 1] = counter;
}
HECMW_assert(local_mesh->elem_type_index[local_mesh->n_elem_type] ==
local_mesh->n_elem);
return RTC_NORMAL;
error:
return RTC_ERROR;
}
/*K. Inagaki */
static int const_elem_type_index_mod(
const struct hecmwST_local_mesh *global_mesh,
struct hecmwST_local_mesh *local_mesh, const int *elem_global2local,
int domain) {
int counter;
int i, j, idx1, idx2, elem_tmp, elem1, elem2, n_int, n_bnd, n_out, maxe;
HECMW_assert(local_mesh->n_elem_type > 0);
HECMW_assert(global_mesh->n_elem_type > 0);
HECMW_assert(global_mesh->elem_type_index);
local_mesh->elem_type_index =
(int *)HECMW_calloc(local_mesh->n_elem_type + 1, sizeof(int));
if (local_mesh->elem_type_index == NULL) {
HECMW_set_error(errno, "");
goto error;
}
n_int = n_int_elist[domain];
n_bnd = n_bnd_elist[2 * domain];
n_out = n_bnd_elist[2 * domain + 1] - n_bnd_elist[2 * domain];
maxe = global_mesh->n_elem + 1;
for (counter = 0, i = 0; i < global_mesh->n_elem_type; i++) {
elem1 = (n_int == 0) ? maxe : int_elist[domain][0];
elem2 = (n_out == 0) ? maxe : bnd_elist[domain][n_bnd];
for (idx1 = 0, idx2 = 0, j = 0; j < n_int + n_out; j++) {
if (elem1 < elem2) {
elem_tmp = elem1 - 1;
idx1++;
elem1 = (idx1 == n_int) ? maxe : int_elist[domain][idx1];
} else {
elem_tmp = elem2 - 1;
idx2++;
elem2 = (idx2 == n_out) ? maxe : bnd_elist[domain][idx2 + n_bnd];
}
if (elem_tmp >= global_mesh->elem_type_index[i] &&
elem_tmp < global_mesh->elem_type_index[i + 1]) {
counter++;
}
}
local_mesh->elem_type_index[i + 1] = counter;
}
HECMW_assert(local_mesh->elem_type_index[local_mesh->n_elem_type] ==
local_mesh->n_elem);
return RTC_NORMAL;
error:
return RTC_ERROR;
}
static int const_elem_type_item(const struct hecmwST_local_mesh *global_mesh,
struct hecmwST_local_mesh *local_mesh) {
HECMW_assert(global_mesh->elem_type_item);
local_mesh->elem_type_item = global_mesh->elem_type_item;
return RTC_NORMAL;
}
static int const_elem_node_index(const struct hecmwST_local_mesh *global_mesh,
struct hecmwST_local_mesh *local_mesh,
const int *elem_local2global) {
int old_idx;
int i;
HECMW_assert(local_mesh->n_elem > 0);
HECMW_assert(global_mesh->elem_node_index);
local_mesh->elem_node_index =
(int *)HECMW_calloc(local_mesh->n_elem + 1, sizeof(int));
if (local_mesh->elem_node_index == NULL) {
HECMW_set_error(errno, "");
goto error;
}
for (i = 0; i < local_mesh->n_elem; i++) {
old_idx = elem_local2global[i] - 1;
local_mesh->elem_node_index[i + 1] =
local_mesh->elem_node_index[i] +
global_mesh->elem_node_index[old_idx + 1] -
global_mesh->elem_node_index[old_idx];
}
return RTC_NORMAL;
error:
return RTC_ERROR;
}
static int const_elem_node_item(const struct hecmwST_local_mesh *global_mesh,
struct hecmwST_local_mesh *local_mesh,
const int *node_global2local,
const int *elem_local2global) {
int node;
int size;
int counter;
int i, j, gstart, gend, lstart, lend;
HECMW_assert(local_mesh->n_elem > 0);
HECMW_assert(local_mesh->elem_node_index);
HECMW_assert(local_mesh->elem_node_index[local_mesh->n_elem] > 0);
HECMW_assert(global_mesh->elem_node_item);
size = sizeof(int) * local_mesh->elem_node_index[local_mesh->n_elem];
local_mesh->elem_node_item = (int *)HECMW_malloc(size);
if (local_mesh->elem_node_item == NULL) {
HECMW_set_error(errno, "");
goto error;
}
for (counter = 0, i = 0; i < local_mesh->n_elem; i++) {
gstart = global_mesh->elem_node_index[elem_local2global[i] - 1];
gend = global_mesh->elem_node_index[elem_local2global[i]];
lstart = local_mesh->elem_node_index[i];
lend = local_mesh->elem_node_index[i + 1];
for (j = 0; j < lend - lstart; j++) {
node = global_mesh->elem_node_item[gstart + j];
local_mesh->elem_node_item[lstart + j] = node_global2local[node - 1];
counter++;
}
HECMW_assert(counter == local_mesh->elem_node_index[i + 1]);
}
return RTC_NORMAL;
error:
return RTC_ERROR;
}
static int const_elem_id(const struct hecmwST_local_mesh *global_mesh,
struct hecmwST_local_mesh *local_mesh,
const int *elem_local2global) {
int i;
HECMW_assert(local_mesh->n_elem > 0);
HECMW_assert(global_mesh->elem_ID);
local_mesh->elem_ID =
(int *)HECMW_malloc(sizeof(int) * local_mesh->n_elem * 2);
if (local_mesh->elem_ID == NULL) {
HECMW_set_error(errno, "");
goto error;
}
for (i = 0; i < local_mesh->n_elem; i++) {
local_mesh->elem_ID[2 * i] =
global_mesh->elem_ID[2 * (elem_local2global[i] - 1)];
local_mesh->elem_ID[2 * i + 1] =
global_mesh->elem_ID[2 * (elem_local2global[i] - 1) + 1];
}
return RTC_NORMAL;
error:
return RTC_ERROR;
}
static int const_global_elem_id(const struct hecmwST_local_mesh *global_mesh,
struct hecmwST_local_mesh *local_mesh,
const int *elem_local2global) {
int i;
HECMW_assert(local_mesh->n_elem);
HECMW_assert(global_mesh->global_elem_ID);
local_mesh->global_elem_ID =
(int *)HECMW_malloc(sizeof(int) * local_mesh->n_elem);
if (local_mesh->global_elem_ID == NULL) {
HECMW_set_error(errno, "");
goto error;
}
for (i = 0; i < local_mesh->n_elem; i++) {
local_mesh->global_elem_ID[i] =
global_mesh->global_elem_ID[elem_local2global[i] - 1];
}
return RTC_NORMAL;
error:
return RTC_ERROR;
}
static int const_section_id(const struct hecmwST_local_mesh *global_mesh,
struct hecmwST_local_mesh *local_mesh,
const int *elem_local2global) {
int i;
HECMW_assert(local_mesh->n_elem);
HECMW_assert(global_mesh->section_ID);
local_mesh->section_ID =
(int *)HECMW_malloc(sizeof(int) * local_mesh->n_elem);
if (local_mesh->section_ID == NULL) {
HECMW_set_error(errno, "");
goto error;
}
for (i = 0; i < local_mesh->n_elem; i++) {
local_mesh->section_ID[i] =
global_mesh->section_ID[elem_local2global[i] - 1];
}
return RTC_NORMAL;
error:
return RTC_ERROR;
}
static int const_elem_mat_id_index(const struct hecmwST_local_mesh *global_mesh,
struct hecmwST_local_mesh *local_mesh,
const int *elem_local2global) {
int old_idx;
int i;
HECMW_assert(local_mesh->n_elem > 0);
HECMW_assert(global_mesh->elem_mat_ID_index);
local_mesh->elem_mat_ID_index =
(int *)HECMW_calloc(local_mesh->n_elem + 1, sizeof(int));
if (local_mesh->elem_mat_ID_index == NULL) {
HECMW_set_error(errno, "");
goto error;
}
for (i = 0; i < local_mesh->n_elem; i++) {
old_idx = elem_local2global[i] - 1;
local_mesh->elem_mat_ID_index[i + 1] =
local_mesh->elem_mat_ID_index[i] +
global_mesh->elem_mat_ID_index[old_idx + 1] -
global_mesh->elem_mat_ID_index[old_idx];
}
return RTC_NORMAL;
error:
return RTC_ERROR;
}
static int const_n_elem_mat_id(struct hecmwST_local_mesh *local_mesh) {
HECMW_assert(local_mesh->n_elem > 0);
HECMW_assert(local_mesh->elem_mat_ID_index);
local_mesh->n_elem_mat_ID = local_mesh->elem_mat_ID_index[local_mesh->n_elem];
return RTC_NORMAL;
}
static int const_elem_mat_id_item(const struct hecmwST_local_mesh *global_mesh,
struct hecmwST_local_mesh *local_mesh,
const int *elem_local2global) {
int size;
int counter;
int i, j, gstart, gend, lstart, lend;
HECMW_assert(local_mesh->n_elem > 0);
HECMW_assert(local_mesh->elem_mat_ID_index[local_mesh->n_elem] >= 0);
if (local_mesh->elem_mat_ID_index[local_mesh->n_elem] == 0) {
local_mesh->elem_mat_ID_item = NULL;
return RTC_NORMAL;
}
size = sizeof(int) * local_mesh->elem_mat_ID_index[local_mesh->n_elem];
local_mesh->elem_mat_ID_item = (int *)HECMW_malloc(size);
if (local_mesh->elem_mat_ID_item == NULL) {
HECMW_set_error(errno, "");
goto error;
}
for (counter = 0, i = 0; i < local_mesh->n_elem; i++) {
gstart = global_mesh->elem_mat_ID_index[elem_local2global[i] - 1];
gend = global_mesh->elem_mat_ID_index[elem_local2global[i]];
lstart = local_mesh->elem_mat_ID_index[i];
lend = local_mesh->elem_mat_ID_index[i + 1];
HECMW_assert(lend - lstart == gend - gstart);
for (j = 0; j < lend - lstart; j++) {
local_mesh->elem_mat_ID_item[lstart + j] =
global_mesh->elem_mat_ID_item[gstart + j];
counter++;
}
HECMW_assert(counter == local_mesh->elem_mat_ID_index[i + 1]);
}
HECMW_assert(counter == local_mesh->n_elem_mat_ID);
return RTC_NORMAL;
error:
return RTC_ERROR;
}
static int const_elem_info(const struct hecmwST_local_mesh *global_mesh,
struct hecmwST_local_mesh *local_mesh,
const int *node_global2local,
const int *elem_global2local,
const int *elem_local2global, int current_domain) {
int rtc;
HECMW_assert(global_mesh);
HECMW_assert(local_mesh);
HECMW_assert(node_global2local);
HECMW_assert(elem_global2local);
HECMW_assert(elem_local2global);
rtc = const_n_elem_type(global_mesh, local_mesh);
if (rtc != RTC_NORMAL) goto error;
rtc = const_elem_type(global_mesh, local_mesh, elem_local2global);
if (rtc != RTC_NORMAL) goto error;
if (is_spdup_available(global_mesh)) {
rtc = const_elem_type_index_mod(global_mesh, local_mesh, elem_global2local,
current_domain);
} else {
rtc = const_elem_type_index(global_mesh, local_mesh, elem_global2local);
}
if (rtc != RTC_NORMAL) goto error;
rtc = const_elem_type_item(global_mesh, local_mesh);
if (rtc != RTC_NORMAL) goto error;
rtc = const_elem_node_index(global_mesh, local_mesh, elem_local2global);
if (rtc != RTC_NORMAL) goto error;
rtc = const_elem_node_item(global_mesh, local_mesh, node_global2local,
elem_local2global);
if (rtc != RTC_NORMAL) goto error;
rtc = const_elem_id(global_mesh, local_mesh, elem_local2global);
if (rtc != RTC_NORMAL) goto error;
rtc = const_global_elem_id(global_mesh, local_mesh, elem_local2global);
if (rtc != RTC_NORMAL) goto error;
rtc = const_section_id(global_mesh, local_mesh, elem_local2global);
if (rtc != RTC_NORMAL) goto error;
rtc = const_elem_mat_id_index(global_mesh, local_mesh, elem_local2global);
if (rtc != RTC_NORMAL) goto error;
rtc = const_n_elem_mat_id(local_mesh);
if (rtc != RTC_NORMAL) goto error;
rtc = const_elem_mat_id_item(global_mesh, local_mesh, elem_local2global);
if (rtc != RTC_NORMAL) goto error;
return RTC_NORMAL;
error:
return RTC_ERROR;
}
/*- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
* - - - - - - - - - */
static int const_hecmw_comm(const struct hecmwST_local_mesh *global_mesh,
struct hecmwST_local_mesh *local_mesh) {
local_mesh->HECMW_COMM = global_mesh->HECMW_COMM;
return RTC_NORMAL;
}
static int const_zero(struct hecmwST_local_mesh *local_mesh,
int current_domain) {
local_mesh->zero = (current_domain == 0) ? 1 : 0;
return RTC_NORMAL;
}
static int const_petot(const struct hecmwST_local_mesh *global_mesh,
struct hecmwST_local_mesh *local_mesh) {
local_mesh->PETOT = global_mesh->n_subdomain;
return RTC_NORMAL;
}
static int const_pesmptot(const struct hecmwST_local_mesh *global_mesh,
struct hecmwST_local_mesh *local_mesh) {
local_mesh->PEsmpTOT = global_mesh->PEsmpTOT;
return RTC_NORMAL;
}
static int const_my_rank(struct hecmwST_local_mesh *local_mesh,
int current_domain) {
local_mesh->my_rank = current_domain;
return RTC_NORMAL;
}
static int const_errnof(const struct hecmwST_local_mesh *global_mesh,
struct hecmwST_local_mesh *local_mesh) {
local_mesh->errnof = global_mesh->errnof;
return RTC_NORMAL;
}
static int const_n_subdomain(const struct hecmwST_local_mesh *global_mesh,
struct hecmwST_local_mesh *local_mesh) {
local_mesh->n_subdomain = global_mesh->n_subdomain;
return RTC_NORMAL;
}
static int const_import_item(struct hecmwST_local_mesh *local_mesh,
const int *global2local) {
int new_id;
int i;
if (local_mesh->n_neighbor_pe == 0) {
local_mesh->import_item = NULL;
return RTC_NORMAL;
}
HECMW_assert(local_mesh->n_neighbor_pe > 0);
HECMW_assert(local_mesh->import_index);
HECMW_assert(local_mesh->import_index[local_mesh->n_neighbor_pe] > 0);
HECMW_assert(local_mesh->import_item);
for (i = 0; i < local_mesh->import_index[local_mesh->n_neighbor_pe]; i++) {
new_id = global2local[local_mesh->import_item[i] - 1];
local_mesh->import_item[i] = new_id;
}
return RTC_NORMAL;
}
static int const_export_item(struct hecmwST_local_mesh *local_mesh,
const int *global2local) {
int new_id;
int i;
if (local_mesh->n_neighbor_pe == 0) {
local_mesh->export_item = NULL;
return RTC_NORMAL;
}
HECMW_assert(local_mesh->n_neighbor_pe > 0);
HECMW_assert(local_mesh->export_index);
HECMW_assert(local_mesh->export_index[local_mesh->n_neighbor_pe] > 0);
HECMW_assert(local_mesh->export_item);
for (i = 0; i < local_mesh->export_index[local_mesh->n_neighbor_pe]; i++) {
new_id = global2local[local_mesh->export_item[i] - 1];
local_mesh->export_item[i] = new_id;
}
return RTC_NORMAL;
}
static int const_shared_item(struct hecmwST_local_mesh *local_mesh,
const int *global2local) {
int new_id;
int i;
if (local_mesh->n_neighbor_pe == 0) {
local_mesh->shared_item = NULL;
return RTC_NORMAL;
}
HECMW_assert(local_mesh->n_neighbor_pe > 0);
HECMW_assert(local_mesh->shared_index);
HECMW_assert(local_mesh->shared_index[local_mesh->n_neighbor_pe] > 0);
HECMW_assert(local_mesh->shared_item);
for (i = 0; i < local_mesh->shared_index[local_mesh->n_neighbor_pe]; i++) {
new_id = global2local[local_mesh->shared_item[i] - 1];
local_mesh->shared_item[i] = new_id;
}
return RTC_NORMAL;
}
static int const_comm_info(const struct hecmwST_local_mesh *global_mesh,
struct hecmwST_local_mesh *local_mesh,
const int *node_global2local,
const int *elem_global2local, int current_domain) {
int rtc;
HECMW_assert(global_mesh);
HECMW_assert(local_mesh);
HECMW_assert(node_global2local);
HECMW_assert(elem_global2local);
rtc = const_hecmw_comm(global_mesh, local_mesh);
if (rtc != RTC_NORMAL) goto error;
rtc = const_zero(local_mesh, current_domain);
if (rtc != RTC_NORMAL) goto error;
rtc = const_petot(global_mesh, local_mesh);
if (rtc != RTC_NORMAL) goto error;
rtc = const_pesmptot(global_mesh, local_mesh);
if (rtc != RTC_NORMAL) goto error;
rtc = const_my_rank(local_mesh, current_domain);
if (rtc != RTC_NORMAL) goto error;
rtc = const_errnof(global_mesh, local_mesh);
if (rtc != RTC_NORMAL) goto error;
rtc = const_n_subdomain(global_mesh, local_mesh);
if (rtc != RTC_NORMAL) goto error;
switch (global_mesh->hecmw_flag_parttype) {
case HECMW_FLAG_PARTTYPE_NODEBASED:
rtc = const_import_item(local_mesh, node_global2local);
if (rtc != RTC_NORMAL) goto error;
rtc = const_export_item(local_mesh, node_global2local);
if (rtc != RTC_NORMAL) goto error;
rtc = const_shared_item(local_mesh, elem_global2local);
if (rtc != RTC_NORMAL) goto error;
break;
case HECMW_FLAG_PARTTYPE_ELEMBASED:
rtc = const_import_item(local_mesh, elem_global2local);
if (rtc != RTC_NORMAL) goto error;
rtc = const_export_item(local_mesh, elem_global2local);
if (rtc != RTC_NORMAL) goto error;
rtc = const_shared_item(local_mesh, node_global2local);
if (rtc != RTC_NORMAL) goto error;
break;
default:
HECMW_set_error(HECMW_PART_E_INVALID_PTYPE, "%d",
global_mesh->hecmw_flag_parttype);
goto error;
}
return RTC_NORMAL;
error:
return RTC_ERROR;
}
/*- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
* - - - - - - - - - */
static int const_n_adapt(const struct hecmwST_local_mesh *global_mesh,
struct hecmwST_local_mesh *local_mesh) {
local_mesh->n_adapt = global_mesh->n_adapt;
return RTC_NORMAL;
}
static int const_coarse_grid_level(const struct hecmwST_local_mesh *global_mesh,
struct hecmwST_local_mesh *local_mesh) {
local_mesh->coarse_grid_level = global_mesh->coarse_grid_level;
return RTC_NORMAL;
}
static int const_when_i_was_refined_node(
const struct hecmwST_local_mesh *global_mesh,
struct hecmwST_local_mesh *local_mesh) {
local_mesh->when_i_was_refined_node = global_mesh->when_i_was_refined_node;
return RTC_NORMAL;
}
static int const_when_i_was_refined_elem(
const struct hecmwST_local_mesh *global_mesh,
struct hecmwST_local_mesh *local_mesh) {
local_mesh->when_i_was_refined_elem = global_mesh->when_i_was_refined_elem;
return RTC_NORMAL;
}
static int const_adapt_parent_type(const struct hecmwST_local_mesh *global_mesh,
struct hecmwST_local_mesh *local_mesh) {
local_mesh->adapt_parent_type = global_mesh->adapt_parent_type;
return RTC_NORMAL;
}
static int const_adapt_type(const struct hecmwST_local_mesh *global_mesh,
struct hecmwST_local_mesh *local_mesh) {
local_mesh->adapt_type = global_mesh->adapt_type;
return RTC_NORMAL;
}
static int const_adapt_level(const struct hecmwST_local_mesh *global_mesh,
struct hecmwST_local_mesh *local_mesh) {
local_mesh->adapt_level = global_mesh->adapt_level;
return RTC_NORMAL;
}
static int const_adapt_parent(const struct hecmwST_local_mesh *global_mesh,
struct hecmwST_local_mesh *local_mesh) {
local_mesh->adapt_parent = global_mesh->adapt_parent;
return RTC_NORMAL;
}
static int const_adapt_children_index(
const struct hecmwST_local_mesh *global_mesh,
struct hecmwST_local_mesh *local_mesh) {
local_mesh->adapt_children_index = global_mesh->adapt_children_index;
return RTC_NORMAL;
}
static int const_adapt_children_item(
const struct hecmwST_local_mesh *global_mesh,
struct hecmwST_local_mesh *local_mesh) {
local_mesh->adapt_children_item = global_mesh->adapt_children_item;
return RTC_NORMAL;
}
static int const_adapt_info(const struct hecmwST_local_mesh *global_mesh,
struct hecmwST_local_mesh *local_mesh) {
int rtc;
HECMW_assert(global_mesh);
HECMW_assert(local_mesh);
rtc = const_n_adapt(global_mesh, local_mesh);
if (rtc != RTC_NORMAL) goto error;
rtc = const_coarse_grid_level(global_mesh, local_mesh);
if (rtc != RTC_NORMAL) goto error;
rtc = const_when_i_was_refined_node(global_mesh, local_mesh);
if (rtc != RTC_NORMAL) goto error;
rtc = const_when_i_was_refined_elem(global_mesh, local_mesh);
if (rtc != RTC_NORMAL) goto error;
rtc = const_adapt_parent_type(global_mesh, local_mesh);
if (rtc != RTC_NORMAL) goto error;
rtc = const_adapt_type(global_mesh, local_mesh);
if (rtc != RTC_NORMAL) goto error;
rtc = const_adapt_level(global_mesh, local_mesh);
if (rtc != RTC_NORMAL) goto error;
rtc = const_adapt_parent(global_mesh, local_mesh);
if (rtc != RTC_NORMAL) goto error;
rtc = const_adapt_children_index(global_mesh, local_mesh);
if (rtc != RTC_NORMAL) goto error;
rtc = const_adapt_children_item(global_mesh, local_mesh);
if (rtc != RTC_NORMAL) goto error;
return RTC_NORMAL;
error:
return RTC_ERROR;
}
/*- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
* - - - - - - - - - */
static int const_n_sect(const struct hecmwST_local_mesh *global_mesh,
struct hecmwST_local_mesh *local_mesh) {
local_mesh->section->n_sect = global_mesh->section->n_sect;
return RTC_NORMAL;
}
static int const_sect_type(const struct hecmwST_local_mesh *global_mesh,
struct hecmwST_local_mesh *local_mesh) {
local_mesh->section->sect_type = global_mesh->section->sect_type;
return RTC_NORMAL;
}
static int const_sect_opt(const struct hecmwST_local_mesh *global_mesh,
struct hecmwST_local_mesh *local_mesh) {
local_mesh->section->sect_opt = global_mesh->section->sect_opt;
return RTC_NORMAL;
}
static int const_sect_mat_id_index(const struct hecmwST_local_mesh *global_mesh,
struct hecmwST_local_mesh *local_mesh) {
local_mesh->section->sect_mat_ID_index =
global_mesh->section->sect_mat_ID_index;
return RTC_NORMAL;
}
static int const_sect_mat_id_item(const struct hecmwST_local_mesh *global_mesh,
struct hecmwST_local_mesh *local_mesh) {
local_mesh->section->sect_mat_ID_item =
global_mesh->section->sect_mat_ID_item;
return RTC_NORMAL;
}
static int const_sect_i_index(const struct hecmwST_local_mesh *global_mesh,
struct hecmwST_local_mesh *local_mesh) {
local_mesh->section->sect_I_index = global_mesh->section->sect_I_index;
return RTC_NORMAL;
}
static int const_sect_i_item(const struct hecmwST_local_mesh *global_mesh,
struct hecmwST_local_mesh *local_mesh) {
local_mesh->section->sect_I_item = global_mesh->section->sect_I_item;
return RTC_NORMAL;
}
static int const_sect_r_index(const struct hecmwST_local_mesh *global_mesh,
struct hecmwST_local_mesh *local_mesh) {
local_mesh->section->sect_R_index = global_mesh->section->sect_R_index;
return RTC_NORMAL;
}
static int const_sect_r_item(const struct hecmwST_local_mesh *global_mesh,
struct hecmwST_local_mesh *local_mesh) {
local_mesh->section->sect_R_item = global_mesh->section->sect_R_item;
return RTC_NORMAL;
}
static int const_sect_info(const struct hecmwST_local_mesh *global_mesh,
struct hecmwST_local_mesh *local_mesh) {
int rtc;
HECMW_assert(global_mesh);
HECMW_assert(local_mesh);
HECMW_assert(global_mesh->section);
HECMW_assert(local_mesh->section);
rtc = const_n_sect(global_mesh, local_mesh);
if (rtc != RTC_NORMAL) goto error;
rtc = const_sect_type(global_mesh, local_mesh);
if (rtc != RTC_NORMAL) goto error;
rtc = const_sect_opt(global_mesh, local_mesh);
if (rtc != RTC_NORMAL) goto error;
rtc = const_sect_mat_id_index(global_mesh, local_mesh);
if (rtc != RTC_NORMAL) goto error;
rtc = const_sect_mat_id_item(global_mesh, local_mesh);
if (rtc != RTC_NORMAL) goto error;
rtc = const_sect_i_index(global_mesh, local_mesh);
if (rtc != RTC_NORMAL) goto error;
rtc = const_sect_i_item(global_mesh, local_mesh);
if (rtc != RTC_NORMAL) goto error;
rtc = const_sect_r_index(global_mesh, local_mesh);
if (rtc != RTC_NORMAL) goto error;
rtc = const_sect_r_item(global_mesh, local_mesh);
if (rtc != RTC_NORMAL) goto error;
return RTC_NORMAL;
error:
return RTC_ERROR;
}
/*- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
* - - - - - - - - - */
static int const_n_mat(const struct hecmwST_local_mesh *global_mesh,
struct hecmwST_local_mesh *local_mesh) {
local_mesh->material->n_mat = global_mesh->material->n_mat;
return RTC_NORMAL;
}
static int const_n_mat_item(const struct hecmwST_local_mesh *global_mesh,
struct hecmwST_local_mesh *local_mesh) {
local_mesh->material->n_mat_item = global_mesh->material->n_mat_item;
return RTC_NORMAL;
}
static int const_n_mat_subitem(const struct hecmwST_local_mesh *global_mesh,
struct hecmwST_local_mesh *local_mesh) {
local_mesh->material->n_mat_subitem = global_mesh->material->n_mat_subitem;
return RTC_NORMAL;
}
static int const_n_mat_table(const struct hecmwST_local_mesh *global_mesh,
struct hecmwST_local_mesh *local_mesh) {
local_mesh->material->n_mat_table = global_mesh->material->n_mat_table;
return RTC_NORMAL;
}
static int const_mat_name(const struct hecmwST_local_mesh *global_mesh,
struct hecmwST_local_mesh *local_mesh) {
local_mesh->material->mat_name = global_mesh->material->mat_name;
return RTC_NORMAL;
}
static int const_mat_item_index(const struct hecmwST_local_mesh *global_mesh,
struct hecmwST_local_mesh *local_mesh) {
local_mesh->material->mat_item_index = global_mesh->material->mat_item_index;
return RTC_NORMAL;
}
static int const_mat_subitem_index(const struct hecmwST_local_mesh *global_mesh,
struct hecmwST_local_mesh *local_mesh) {
local_mesh->material->mat_subitem_index =
global_mesh->material->mat_subitem_index;
return RTC_NORMAL;
}
static int const_mat_table_index(const struct hecmwST_local_mesh *global_mesh,
struct hecmwST_local_mesh *local_mesh) {
local_mesh->material->mat_table_index =
global_mesh->material->mat_table_index;
return RTC_NORMAL;
}
static int const_mat_val(const struct hecmwST_local_mesh *global_mesh,
struct hecmwST_local_mesh *local_mesh) {
local_mesh->material->mat_val = global_mesh->material->mat_val;
return RTC_NORMAL;
}
static int const_mat_temp(const struct hecmwST_local_mesh *global_mesh,
struct hecmwST_local_mesh *local_mesh) {
local_mesh->material->mat_temp = global_mesh->material->mat_temp;
return RTC_NORMAL;
}
static int const_mat_info(const struct hecmwST_local_mesh *global_mesh,
struct hecmwST_local_mesh *local_mesh) {
int rtc;
HECMW_assert(global_mesh);
HECMW_assert(global_mesh->material);
HECMW_assert(local_mesh);
HECMW_assert(local_mesh->material);
rtc = const_n_mat(global_mesh, local_mesh);
if (rtc != RTC_NORMAL) goto error;
rtc = const_n_mat_item(global_mesh, local_mesh);
if (rtc != RTC_NORMAL) goto error;
rtc = const_n_mat_subitem(global_mesh, local_mesh);
if (rtc != RTC_NORMAL) goto error;
rtc = const_n_mat_table(global_mesh, local_mesh);
if (rtc != RTC_NORMAL) goto error;
rtc = const_mat_name(global_mesh, local_mesh);
if (rtc != RTC_NORMAL) goto error;
rtc = const_mat_item_index(global_mesh, local_mesh);
if (rtc != RTC_NORMAL) goto error;
rtc = const_mat_subitem_index(global_mesh, local_mesh);
if (rtc != RTC_NORMAL) goto error;
rtc = const_mat_table_index(global_mesh, local_mesh);
if (rtc != RTC_NORMAL) goto error;
rtc = const_mat_val(global_mesh, local_mesh);
if (rtc != RTC_NORMAL) goto error;
rtc = const_mat_temp(global_mesh, local_mesh);
if (rtc != RTC_NORMAL) goto error;
return RTC_NORMAL;
error:
return RTC_ERROR;
}
/*- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
* - - - - - - - - - */
static int const_n_mpc(const struct hecmwST_local_mesh *global_mesh,
struct hecmwST_local_mesh *local_mesh,
const int *node_global2local, char *mpc_flag) {
struct hecmwST_mpc *mpc_global = global_mesh->mpc;
struct hecmwST_mpc *mpc_local = local_mesh->mpc;
int node, diff, evalsum, counter;
int i, j;
for (counter = 0, i = 0; i < mpc_global->n_mpc; i++) {
diff = mpc_global->mpc_index[i + 1] - mpc_global->mpc_index[i];
evalsum = 0;
for (j = mpc_global->mpc_index[i]; j < mpc_global->mpc_index[i + 1]; j++) {
node = mpc_global->mpc_item[j];
if (node_global2local[node - 1] > 0) evalsum++;
}
if (evalsum == diff) {
MASK_BIT(mpc_flag[i], MASK);
counter++;
}
}
mpc_local->n_mpc = counter;
return RTC_NORMAL;
}
static int const_mpc_index(const struct hecmwST_local_mesh *global_mesh,
struct hecmwST_local_mesh *local_mesh,
const char *mpc_flag) {
struct hecmwST_mpc *mpc_global = global_mesh->mpc;
struct hecmwST_mpc *mpc_local = local_mesh->mpc;
int counter;
int i;
mpc_local->mpc_index = (int *)HECMW_calloc(mpc_local->n_mpc + 1, sizeof(int));
if (local_mesh->mpc->mpc_index == NULL) {
HECMW_set_error(errno, "");
goto error;
}
for (counter = 0, i = 0; i < mpc_global->n_mpc; i++) {
if (EVAL_BIT(mpc_flag[i], MASK)) {
mpc_local->mpc_index[counter + 1] = mpc_local->mpc_index[counter] +
mpc_global->mpc_index[i + 1] -
mpc_global->mpc_index[i];
counter++;
}
}
HECMW_assert(counter == mpc_local->n_mpc);
return RTC_NORMAL;
error:
return RTC_ERROR;
}
static int const_mpc_item(const struct hecmwST_local_mesh *global_mesh,
struct hecmwST_local_mesh *local_mesh,
const int *node_global2local, const char *mpc_flag) {
struct hecmwST_mpc *mpc_global = global_mesh->mpc;
struct hecmwST_mpc *mpc_local = local_mesh->mpc;
int mcounter, icounter;
int i, j;
mpc_local->mpc_item =
(int *)HECMW_malloc(sizeof(int) * mpc_local->mpc_index[mpc_local->n_mpc]);
if (mpc_local->mpc_item == NULL) {
HECMW_set_error(errno, "");
goto error;
}
for (mcounter = 0, icounter = 0, i = 0; i < mpc_global->n_mpc; i++) {
if (EVAL_BIT(mpc_flag[i], MASK)) {
for (j = mpc_global->mpc_index[i]; j < mpc_global->mpc_index[i + 1];
j++) {
mpc_local->mpc_item[mcounter++] =
node_global2local[mpc_global->mpc_item[j] - 1];
}
HECMW_assert(mcounter == mpc_local->mpc_index[++icounter]);
}
}
HECMW_assert(icounter == mpc_local->n_mpc);
HECMW_assert(mcounter == mpc_local->mpc_index[mpc_local->n_mpc]);
return RTC_NORMAL;
error:
return RTC_ERROR;
}
static int const_mpc_dof(const struct hecmwST_local_mesh *global_mesh,
struct hecmwST_local_mesh *local_mesh,
const char *mpc_flag) {
struct hecmwST_mpc *mpc_global = global_mesh->mpc;
struct hecmwST_mpc *mpc_local = local_mesh->mpc;
int mcounter, icounter;
int i, j;
mpc_local->mpc_dof =
(int *)HECMW_malloc(sizeof(int) * mpc_local->mpc_index[mpc_local->n_mpc]);
if (local_mesh->mpc->mpc_dof == NULL) {
HECMW_set_error(errno, "");
goto error;
}
for (mcounter = 0, icounter = 0, i = 0; i < mpc_global->n_mpc; i++) {
if (EVAL_BIT(mpc_flag[i], MASK)) {
for (j = mpc_global->mpc_index[i]; j < mpc_global->mpc_index[i + 1];
j++) {
mpc_local->mpc_dof[mcounter++] = mpc_global->mpc_dof[j];
}
HECMW_assert(mcounter == mpc_local->mpc_index[++icounter]);
}
}
HECMW_assert(icounter == mpc_local->n_mpc);
HECMW_assert(mcounter == mpc_local->mpc_index[mpc_local->n_mpc]);
return RTC_NORMAL;
error:
return RTC_ERROR;
}
static int const_mpc_val(const struct hecmwST_local_mesh *global_mesh,
struct hecmwST_local_mesh *local_mesh,
const char *mpc_flag) {
struct hecmwST_mpc *mpc_global = global_mesh->mpc;
struct hecmwST_mpc *mpc_local = local_mesh->mpc;
int size;
int mcounter, icounter;
int i, j;
size = sizeof(double) * mpc_local->mpc_index[mpc_local->n_mpc];
mpc_local->mpc_val = (double *)HECMW_malloc(size);
if (local_mesh->mpc->mpc_val == NULL) {
HECMW_set_error(errno, "");
goto error;
}
for (mcounter = 0, icounter = 0, i = 0; i < mpc_global->n_mpc; i++) {
if (EVAL_BIT(mpc_flag[i], MASK)) {
for (j = mpc_global->mpc_index[i]; j < mpc_global->mpc_index[i + 1];
j++) {
mpc_local->mpc_val[mcounter++] = mpc_global->mpc_val[j];
}
HECMW_assert(mcounter == mpc_local->mpc_index[++icounter]);
}
}
HECMW_assert(icounter == local_mesh->mpc->n_mpc);
HECMW_assert(mcounter == local_mesh->mpc->mpc_index[local_mesh->mpc->n_mpc]);
return RTC_NORMAL;
error:
return RTC_ERROR;
}
static int const_mpc_const(const struct hecmwST_local_mesh *global_mesh,
struct hecmwST_local_mesh *local_mesh,
const char *mpc_flag) {
struct hecmwST_mpc *mpc_global = global_mesh->mpc;
struct hecmwST_mpc *mpc_local = local_mesh->mpc;
int size;
int icounter;
int i;
size = sizeof(double) * mpc_local->n_mpc;
mpc_local->mpc_const = (double *)HECMW_malloc(size);
if (local_mesh->mpc->mpc_const == NULL) {
HECMW_set_error(errno, "");
goto error;
}
for (icounter = 0, i = 0; i < mpc_global->n_mpc; i++) {
if (EVAL_BIT(mpc_flag[i], MASK)) {
mpc_local->mpc_const[icounter] = mpc_global->mpc_const[i];
icounter++;
}
}
HECMW_assert(icounter == local_mesh->mpc->n_mpc);
return RTC_NORMAL;
error:
return RTC_ERROR;
}
static int const_mpc_info(const struct hecmwST_local_mesh *global_mesh,
struct hecmwST_local_mesh *local_mesh,
const int *node_global2local) {
char *mpc_flag = NULL;
int rtc;
HECMW_assert(global_mesh);
HECMW_assert(global_mesh->mpc);
HECMW_assert(local_mesh);
HECMW_assert(local_mesh->mpc);
HECMW_assert(node_global2local);
if (global_mesh->mpc->n_mpc == 0) {
init_struct_mpc(local_mesh);
return RTC_NORMAL;
}
mpc_flag = (char *)HECMW_calloc(global_mesh->mpc->n_mpc, sizeof(char));
if (mpc_flag == NULL) {
HECMW_set_error(errno, "");
goto error;
}
rtc = const_n_mpc(global_mesh, local_mesh, node_global2local, mpc_flag);
if (rtc != RTC_NORMAL) goto error;
if (local_mesh->mpc->n_mpc == 0) {
init_struct_mpc(local_mesh);
HECMW_free(mpc_flag);
return RTC_NORMAL;
}
rtc = const_mpc_index(global_mesh, local_mesh, mpc_flag);
if (rtc != RTC_NORMAL) goto error;
rtc = const_mpc_item(global_mesh, local_mesh, node_global2local, mpc_flag);
if (rtc != RTC_NORMAL) goto error;
rtc = const_mpc_dof(global_mesh, local_mesh, mpc_flag);
if (rtc != RTC_NORMAL) goto error;
rtc = const_mpc_val(global_mesh, local_mesh, mpc_flag);
if (rtc != RTC_NORMAL) goto error;
rtc = const_mpc_const(global_mesh, local_mesh, mpc_flag);
if (rtc != RTC_NORMAL) goto error;
HECMW_free(mpc_flag);
return RTC_NORMAL;
error:
HECMW_free(mpc_flag);
return RTC_ERROR;
}
/*- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
* - - - - - - - - - */
static int const_n_amp(const struct hecmwST_local_mesh *global_mesh,
struct hecmwST_local_mesh *local_mesh) {
local_mesh->amp->n_amp = global_mesh->amp->n_amp;
return RTC_NORMAL;
}
static int const_amp_name(const struct hecmwST_local_mesh *global_mesh,
struct hecmwST_local_mesh *local_mesh) {
local_mesh->amp->amp_name = global_mesh->amp->amp_name;
return RTC_NORMAL;
}
static int const_amp_type_definition(
const struct hecmwST_local_mesh *global_mesh,
struct hecmwST_local_mesh *local_mesh) {
local_mesh->amp->amp_type_definition = global_mesh->amp->amp_type_definition;
return RTC_NORMAL;
}
static int const_amp_type_time(const struct hecmwST_local_mesh *global_mesh,
struct hecmwST_local_mesh *local_mesh) {
local_mesh->amp->amp_type_time = global_mesh->amp->amp_type_time;
return RTC_NORMAL;
}
static int const_amp_type_value(const struct hecmwST_local_mesh *global_mesh,
struct hecmwST_local_mesh *local_mesh) {
local_mesh->amp->amp_type_value = global_mesh->amp->amp_type_value;
return RTC_NORMAL;
}
static int const_amp_index(const struct hecmwST_local_mesh *global_mesh,
struct hecmwST_local_mesh *local_mesh) {
local_mesh->amp->amp_index = global_mesh->amp->amp_index;
return RTC_NORMAL;
}
static int const_amp_val(const struct hecmwST_local_mesh *global_mesh,
struct hecmwST_local_mesh *local_mesh) {
local_mesh->amp->amp_val = global_mesh->amp->amp_val;
return RTC_NORMAL;
}
static int const_amp_table(const struct hecmwST_local_mesh *global_mesh,
struct hecmwST_local_mesh *local_mesh) {
local_mesh->amp->amp_table = global_mesh->amp->amp_table;
return RTC_NORMAL;
}
static int const_amp_info(const struct hecmwST_local_mesh *global_mesh,
struct hecmwST_local_mesh *local_mesh) {
int rtc;
HECMW_assert(global_mesh);
HECMW_assert(global_mesh->amp);
HECMW_assert(local_mesh);
HECMW_assert(local_mesh->amp);
if (global_mesh->amp->n_amp == 0) {
init_struct_amp(local_mesh);
return RTC_NORMAL;
}
rtc = const_n_amp(global_mesh, local_mesh);
if (rtc != RTC_NORMAL) goto error;
rtc = const_amp_name(global_mesh, local_mesh);
if (rtc != RTC_NORMAL) goto error;
rtc = const_amp_type_definition(global_mesh, local_mesh);
if (rtc != RTC_NORMAL) goto error;
rtc = const_amp_type_time(global_mesh, local_mesh);
if (rtc != RTC_NORMAL) goto error;
rtc = const_amp_type_value(global_mesh, local_mesh);
if (rtc != RTC_NORMAL) goto error;
rtc = const_amp_index(global_mesh, local_mesh);
if (rtc != RTC_NORMAL) goto error;
rtc = const_amp_val(global_mesh, local_mesh);
if (rtc != RTC_NORMAL) goto error;
rtc = const_amp_table(global_mesh, local_mesh);
if (rtc != RTC_NORMAL) goto error;
return RTC_NORMAL;
error:
return RTC_ERROR;
}
/*- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
* - - - - - - - - - */
static int *const_node_grp_mask_eqn(
const struct hecmwST_local_mesh *global_mesh,
struct hecmwST_local_mesh *local_mesh, const int *node_global2local,
int eqn_block_idx) {
struct hecmwST_node_grp *node_group_global = global_mesh->node_group;
int *n_eqn_item = NULL;
int diff, evalsum;
int i, j, is, ie, js;
is = node_group_global->grp_index[eqn_block_idx];
ie = node_group_global->grp_index[eqn_block_idx + 1];
n_eqn_item = (int *)HECMW_malloc(sizeof(int) * (ie - is));
if (n_eqn_item == NULL) {
HECMW_set_error(errno, "");
goto error;
}
for (js = 0, i = 0; i < ie - is; i++) {
diff = node_group_global->grp_item[is + i] - js;
for (evalsum = 0, j = js; j < node_group_global->grp_item[is + i]; j++) {
if (node_global2local[j] > 0 &&
node_global2local[j] <= local_mesh->nn_internal)
evalsum++;
}
if (evalsum) {
HECMW_assert(evalsum == diff);
n_eqn_item[i] = diff;
} else {
n_eqn_item[i] = 0;
}
js = node_group_global->grp_item[is + i];
}
return n_eqn_item;
error:
return NULL;
}
static int const_node_n_grp(const struct hecmwST_local_mesh *global_mesh,
struct hecmwST_local_mesh *local_mesh) {
local_mesh->node_group->n_grp = global_mesh->node_group->n_grp;
return RTC_NORMAL;
}
static int const_node_grp_name(const struct hecmwST_local_mesh *global_mesh,
struct hecmwST_local_mesh *local_mesh) {
local_mesh->node_group->grp_name = global_mesh->node_group->grp_name;
return RTC_NORMAL;
}
static int const_node_grp_index(const struct hecmwST_local_mesh *global_mesh,
struct hecmwST_local_mesh *local_mesh,
const int *node_global2local,
const int *n_eqn_item, int eqn_block_idx) {
struct hecmwST_node_grp *node_group_global = global_mesh->node_group;
struct hecmwST_node_grp *node_group_local = local_mesh->node_group;
int node;
int counter, diff;
int i, j;
node_group_local->grp_index =
(int *)HECMW_calloc(node_group_local->n_grp + 1, sizeof(int));
if (node_group_local->grp_index == NULL) {
HECMW_set_error(errno, "");
goto error;
}
for (counter = 0, i = 0; i < node_group_global->n_grp; i++) {
if (i != eqn_block_idx) {
for (j = node_group_global->grp_index[i];
j < node_group_global->grp_index[i + 1]; j++) {
node = node_group_global->grp_item[j];
if (node_global2local[node - 1]) counter++;
}
} else {
diff =
node_group_global->grp_index[i + 1] - node_group_global->grp_index[i];
for (j = 0; j < diff; j++) {
if (n_eqn_item[j] > 0) counter++;
}
}
node_group_local->grp_index[i + 1] = counter;
}
return RTC_NORMAL;
error:
return RTC_ERROR;
}
/*K. Inagaki */
static int const_node_grp_index_mod(
const struct hecmwST_local_mesh *global_mesh,
struct hecmwST_local_mesh *local_mesh, const int *node_global2local,
const int *n_eqn_item, int eqn_block_idx, int domain) {
struct hecmwST_node_grp *node_group_global = global_mesh->node_group;
struct hecmwST_node_grp *node_group_local = local_mesh->node_group;
int node;
int counter, diff;
int i, j;
node_group_local->grp_index =
(int *)HECMW_calloc(node_group_local->n_grp + 1, sizeof(int));
if (node_group_local->grp_index == NULL) {
HECMW_set_error(errno, "");
goto error;
}
for (counter = 0, i = 0; i < node_group_global->n_grp; i++) {
if (i != eqn_block_idx) {
if (node_group_global->grp_index[i + 1] -
node_group_global->grp_index[i] ==
global_mesh->n_node) {
counter += n_int_nlist[domain];
counter += n_bnd_nlist[2 * domain + 1] - n_bnd_nlist[2 * domain];
} else {
counter += ngrp_idx[domain][i + 1] - ngrp_idx[domain][i];
/*
for( j=node_group_global->grp_index[i];
j<node_group_global->grp_index[i+1]; j++ ) {
node = node_group_global->grp_item[j];
if( node_global2local[node-1] ) counter++;
}
*/
}
} else {
diff =
node_group_global->grp_index[i + 1] - node_group_global->grp_index[i];
for (j = 0; j < diff; j++) {
if (n_eqn_item[j] > 0) counter++;
}
}
node_group_local->grp_index[i + 1] = counter;
}
return RTC_NORMAL;
error:
return RTC_ERROR;
}
static int const_node_grp_item(const struct hecmwST_local_mesh *global_mesh,
struct hecmwST_local_mesh *local_mesh,
const int *node_global2local,
const int *n_eqn_item, int eqn_block_idx) {
struct hecmwST_node_grp *node_group_global = global_mesh->node_group;
struct hecmwST_node_grp *node_group_local = local_mesh->node_group;
int node;
int size;
int counter;
int i, j, k, js, je, ks, ls;
size = sizeof(int) * node_group_local->grp_index[node_group_local->n_grp];
node_group_local->grp_item = (int *)HECMW_malloc(size);
if (node_group_local->grp_item == NULL) {
HECMW_set_error(errno, "");
goto error;
}
for (counter = 0, i = 0; i < node_group_global->n_grp; i++) {
if (i != eqn_block_idx) {
for (j = node_group_global->grp_index[i];
j < node_group_global->grp_index[i + 1]; j++) {
node = node_group_global->grp_item[j];
if (node_global2local[node - 1]) {
node_group_local->grp_item[counter++] = node_global2local[node - 1];
}
}
} else {
js = node_group_global->grp_index[i];
je = node_group_global->grp_index[i + 1];
for (ks = 0, ls = 0, j = js; j < je; j++) {
if (n_eqn_item[j - js]) {
HECMW_assert(n_eqn_item[j - js] ==
node_group_global->grp_item[j] - ks);
node_group_local->grp_item[counter] = ls + n_eqn_item[j - js];
for (k = ks; k < node_group_global->grp_item[j]; k++) {
HECMW_assert(ls < node_global2local[k] &&
node_global2local[k] <=
node_group_local->grp_item[counter]);
}
ls = node_group_local->grp_item[counter];
counter++;
}
ks = node_group_global->grp_item[j];
}
}
HECMW_assert(counter == node_group_local->grp_index[i + 1]);
}
return RTC_NORMAL;
error:
return RTC_ERROR;
}
/*K. Inagaki */
static int const_node_grp_item_mod(const struct hecmwST_local_mesh *global_mesh,
struct hecmwST_local_mesh *local_mesh,
const int *node_global2local,
const int *n_eqn_item, int eqn_block_idx,
int domain) {
struct hecmwST_node_grp *node_group_global = global_mesh->node_group;
struct hecmwST_node_grp *node_group_local = local_mesh->node_group;
int node;
int size;
int counter;
int i, j, k, js, je, ks, ls;
int idx1, idx2, node1, node2, n_int, n_bnd, n_out, maxn;
size = sizeof(int) * node_group_local->grp_index[node_group_local->n_grp];
node_group_local->grp_item = (int *)HECMW_malloc(size);
if (node_group_local->grp_item == NULL) {
HECMW_set_error(errno, "");
goto error;
}
n_int = n_int_nlist[domain];
n_bnd = n_bnd_nlist[2 * domain];
n_out = n_bnd_nlist[2 * domain + 1] - n_bnd_nlist[2 * domain];
maxn = global_mesh->n_node + 1;
for (counter = 0, i = 0; i < node_group_global->n_grp; i++) {
if (i != eqn_block_idx) {
if (node_group_global->grp_index[i + 1] -
node_group_global->grp_index[i] ==
global_mesh->n_node) {
idx1 = 0;
idx2 = 0;
node1 = (n_int == 0) ? maxn : int_nlist[domain][0];
node2 = (n_out == 0) ? maxn : bnd_nlist[domain][n_bnd];
for (j = 0; j < n_int + n_out; j++) {
if (node1 < node2) {
node_group_local->grp_item[counter++] =
node_global2local[node1 - 1];
idx1++;
node1 = (idx1 == n_int) ? maxn : int_nlist[domain][idx1];
} else {
node_group_local->grp_item[counter++] =
node_global2local[node2 - 1];
idx2++;
node2 = (idx2 == n_out) ? maxn : bnd_nlist[domain][idx2 + n_bnd];
}
}
} else {
if (ngrp_idx[domain][i + 1] - ngrp_idx[domain][i] == 0) continue;
for (j = ngrp_idx[domain][i]; j < ngrp_idx[domain][i + 1]; j++) {
node = ngrp_item[domain][j];
node_group_local->grp_item[counter++] = node_global2local[node - 1];
}
}
} else {
js = node_group_global->grp_index[i];
je = node_group_global->grp_index[i + 1];
for (ks = 0, ls = 0, j = js; j < je; j++) {
if (n_eqn_item[j - js]) {
HECMW_assert(n_eqn_item[j - js] ==
node_group_global->grp_item[j] - ks);
node_group_local->grp_item[counter] = ls + n_eqn_item[j - js];
for (k = ks; k < node_group_global->grp_item[j]; k++) {
HECMW_assert(ls < node_global2local[k] &&
node_global2local[k] <=
node_group_local->grp_item[counter]);
}
ls = node_group_local->grp_item[counter];
counter++;
}
ks = node_group_global->grp_item[j];
}
}
HECMW_assert(counter == node_group_local->grp_index[i + 1]);
}
return RTC_NORMAL;
error:
return RTC_ERROR;
}
static int const_node_grp_info(const struct hecmwST_local_mesh *global_mesh,
struct hecmwST_local_mesh *local_mesh,
const int *node_global2local,
int current_domain) {
int *n_eqn_item = NULL;
int eqn_block_idx;
int rtc;
HECMW_assert(global_mesh);
HECMW_assert(global_mesh->node_group);
HECMW_assert(local_mesh);
HECMW_assert(local_mesh->node_group);
HECMW_assert(node_global2local);
if (global_mesh->node_group->n_grp == 0) {
init_struct_node_grp(local_mesh);
return RTC_NORMAL;
}
eqn_block_idx = search_eqn_block_idx(global_mesh);
if (eqn_block_idx >= 0) {
n_eqn_item = const_node_grp_mask_eqn(global_mesh, local_mesh,
node_global2local, eqn_block_idx);
if (n_eqn_item == NULL) goto error;
}
rtc = const_node_n_grp(global_mesh, local_mesh);
if (rtc != RTC_NORMAL) goto error;
rtc = const_node_grp_name(global_mesh, local_mesh);
if (rtc != RTC_NORMAL) goto error;
if (is_spdup_available(global_mesh)) {
rtc = const_node_grp_index_mod(global_mesh, local_mesh, node_global2local,
n_eqn_item, eqn_block_idx, current_domain);
if (rtc != RTC_NORMAL) goto error;
rtc = const_node_grp_item_mod(global_mesh, local_mesh, node_global2local,
n_eqn_item, eqn_block_idx, current_domain);
if (rtc != RTC_NORMAL) goto error;
} else {
rtc = const_node_grp_index(global_mesh, local_mesh, node_global2local,
n_eqn_item, eqn_block_idx);
if (rtc != RTC_NORMAL) goto error;
rtc = const_node_grp_item(global_mesh, local_mesh, node_global2local,
n_eqn_item, eqn_block_idx);
if (rtc != RTC_NORMAL) goto error;
}
HECMW_free(n_eqn_item);
return RTC_NORMAL;
error:
HECMW_free(n_eqn_item);
return RTC_ERROR;
}
/*- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
* - - - - - - - - - */
static int const_elem_n_grp(const struct hecmwST_local_mesh *global_mesh,
struct hecmwST_local_mesh *local_mesh) {
local_mesh->elem_group->n_grp = global_mesh->elem_group->n_grp;
return RTC_NORMAL;
}
static int const_elem_grp_name(const struct hecmwST_local_mesh *global_mesh,
struct hecmwST_local_mesh *local_mesh) {
local_mesh->elem_group->grp_name = global_mesh->elem_group->grp_name;
return RTC_NORMAL;
}
static int const_elem_grp_index(const struct hecmwST_local_mesh *global_mesh,
struct hecmwST_local_mesh *local_mesh,
const int *elem_global2local) {
struct hecmwST_elem_grp *elem_group_global = global_mesh->elem_group;
struct hecmwST_elem_grp *elem_group_local = local_mesh->elem_group;
int elem;
int counter;
int i, j;
elem_group_local->grp_index =
(int *)HECMW_calloc(elem_group_local->n_grp + 1, sizeof(int));
if (elem_group_local->grp_index == NULL) {
HECMW_set_error(errno, "");
goto error;
}
for (counter = 0, i = 0; i < elem_group_global->n_grp; i++) {
for (j = elem_group_global->grp_index[i];
j < elem_group_global->grp_index[i + 1]; j++) {
elem = elem_group_global->grp_item[j];
if (elem_global2local[elem - 1]) counter++;
}
elem_group_local->grp_index[i + 1] = counter;
}
return RTC_NORMAL;
error:
return RTC_ERROR;
}
/*K. Inagaki */
static int const_elem_grp_index_mod(
const struct hecmwST_local_mesh *global_mesh,
struct hecmwST_local_mesh *local_mesh, const int *elem_global2local,
int domain) {
struct hecmwST_elem_grp *elem_group_global = global_mesh->elem_group;
struct hecmwST_elem_grp *elem_group_local = local_mesh->elem_group;
int elem;
int counter;
int i, j, idx1, idx2, elem1, elem2;
elem_group_local->grp_index =
(int *)HECMW_calloc(elem_group_local->n_grp + 1, sizeof(int));
if (elem_group_local->grp_index == NULL) {
HECMW_set_error(errno, "");
goto error;
}
for (counter = 0, i = 0; i < elem_group_global->n_grp; i++) {
if (elem_group_global->grp_index[i + 1] - elem_group_global->grp_index[i] ==
global_mesh->n_elem) {
counter += n_int_elist[domain];
counter += n_bnd_elist[2 * domain + 1] - n_bnd_elist[2 * domain];
} else {
counter += egrp_idx[domain][i + 1] - egrp_idx[domain][i];
}
elem_group_local->grp_index[i + 1] = counter;
}
return RTC_NORMAL;
error:
return RTC_ERROR;
}
static int const_elem_grp_item(const struct hecmwST_local_mesh *global_mesh,
struct hecmwST_local_mesh *local_mesh,
const int *elem_global2local) {
struct hecmwST_elem_grp *elem_group_global = global_mesh->elem_group;
struct hecmwST_elem_grp *elem_group_local = local_mesh->elem_group;
int elem;
int size;
int counter;
int i, j;
size = sizeof(int) * elem_group_local->grp_index[elem_group_local->n_grp];
elem_group_local->grp_item = (int *)HECMW_malloc(size);
if (local_mesh->elem_group->grp_item == NULL) {
HECMW_set_error(errno, "");
goto error;
}
for (counter = 0, i = 0; i < elem_group_global->n_grp; i++) {
for (j = elem_group_global->grp_index[i];
j < elem_group_global->grp_index[i + 1]; j++) {
elem = elem_group_global->grp_item[j];
if (elem_global2local[elem - 1]) {
elem_group_local->grp_item[counter++] = elem_global2local[elem - 1];
}
}
HECMW_assert(counter == elem_group_local->grp_index[i + 1]);
}
return RTC_NORMAL;
error:
return RTC_ERROR;
}
/*K. Inagaki */
static int const_elem_grp_item_mod(const struct hecmwST_local_mesh *global_mesh,
struct hecmwST_local_mesh *local_mesh,
const int *elem_global2local, int domain) {
struct hecmwST_elem_grp *elem_group_global = global_mesh->elem_group;
struct hecmwST_elem_grp *elem_group_local = local_mesh->elem_group;
int elem;
int size;
int counter;
int i, j, idx1, idx2, elem1, elem2, n_int, n_bnd, n_out, maxe;
size = sizeof(int) * elem_group_local->grp_index[elem_group_local->n_grp];
elem_group_local->grp_item = (int *)HECMW_malloc(size);
if (local_mesh->elem_group->grp_item == NULL) {
HECMW_set_error(errno, "");
goto error;
}
n_int = n_int_elist[domain];
n_bnd = n_bnd_elist[2 * domain];
n_out = n_bnd_elist[2 * domain + 1] - n_bnd_elist[2 * domain];
maxe = global_mesh->n_elem + 1;
for (counter = 0, i = 0; i < elem_group_global->n_grp; i++) {
if (elem_group_global->grp_index[i + 1] - elem_group_global->grp_index[i] ==
global_mesh->n_elem) {
elem1 = (n_int == 0) ? maxe : int_elist[domain][0];
elem2 = (n_out == 0) ? maxe : bnd_elist[domain][n_bnd];
for (idx1 = 0, idx2 = 0, j = 0; j < n_int + n_out; j++) {
if (elem1 < elem2) {
elem_group_local->grp_item[counter++] = elem_global2local[elem1 - 1];
idx1++;
elem1 = (idx1 == n_int) ? maxe : int_elist[domain][idx1];
} else {
elem_group_local->grp_item[counter++] = elem_global2local[elem2 - 1];
idx2++;
elem2 = (idx2 == n_out) ? maxe : bnd_elist[domain][idx2 + n_bnd];
}
}
} else {
if (egrp_idx[domain][i + 1] - egrp_idx[domain][i] == 0) continue;
for (j = egrp_idx[domain][i]; j < egrp_idx[domain][i + 1]; j++) {
elem = egrp_item[domain][j];
elem_group_local->grp_item[counter++] = elem_global2local[elem - 1];
}
}
HECMW_assert(counter == elem_group_local->grp_index[i + 1]);
}
return RTC_NORMAL;
error:
return RTC_ERROR;
}
static int const_elem_grp_info(const struct hecmwST_local_mesh *global_mesh,
struct hecmwST_local_mesh *local_mesh,
const int *elem_global2local,
int current_domain) {
int rtc;
HECMW_assert(global_mesh);
HECMW_assert(global_mesh->elem_group);
HECMW_assert(local_mesh);
HECMW_assert(local_mesh->elem_group);
HECMW_assert(elem_global2local);
if (global_mesh->elem_group->n_grp == 0) {
init_struct_elem_grp(local_mesh);
return RTC_NORMAL;
}
rtc = const_elem_n_grp(global_mesh, local_mesh);
if (rtc != RTC_NORMAL) goto error;
rtc = const_elem_grp_name(global_mesh, local_mesh);
if (rtc != RTC_NORMAL) goto error;
if (is_spdup_available(global_mesh)) {
rtc = const_elem_grp_index_mod(global_mesh, local_mesh, elem_global2local,
current_domain);
if (rtc != RTC_NORMAL) goto error;
rtc = const_elem_grp_item_mod(global_mesh, local_mesh, elem_global2local,
current_domain);
if (rtc != RTC_NORMAL) goto error;
} else {
rtc = const_elem_grp_index(global_mesh, local_mesh, elem_global2local);
if (rtc != RTC_NORMAL) goto error;
rtc = const_elem_grp_item(global_mesh, local_mesh, elem_global2local);
if (rtc != RTC_NORMAL) goto error;
}
return RTC_NORMAL;
error:
return RTC_ERROR;
}
/*- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
* - - - - - - - - - */
static int const_surf_n_grp(const struct hecmwST_local_mesh *global_mesh,
struct hecmwST_local_mesh *local_mesh) {
local_mesh->surf_group->n_grp = global_mesh->surf_group->n_grp;
return RTC_NORMAL;
}
static int const_surf_grp_name(const struct hecmwST_local_mesh *global_mesh,
struct hecmwST_local_mesh *local_mesh) {
local_mesh->surf_group->grp_name = global_mesh->surf_group->grp_name;
return RTC_NORMAL;
}
static int const_surf_grp_index(const struct hecmwST_local_mesh *global_mesh,
struct hecmwST_local_mesh *local_mesh,
const int *elem_global2local) {
struct hecmwST_surf_grp *surf_group_global = global_mesh->surf_group;
struct hecmwST_surf_grp *surf_group_local = local_mesh->surf_group;
int elem;
int counter;
int i, j;
surf_group_local->grp_index =
(int *)HECMW_calloc(surf_group_local->n_grp + 1, sizeof(int));
if (surf_group_local->grp_index == NULL) {
HECMW_set_error(errno, "");
goto error;
}
for (counter = 0, i = 0; i < surf_group_global->n_grp; i++) {
for (j = surf_group_global->grp_index[i];
j < surf_group_global->grp_index[i + 1]; j++) {
elem = surf_group_global->grp_item[2 * j];
if (elem_global2local[elem - 1]) counter++;
}
surf_group_local->grp_index[i + 1] = counter;
}
return RTC_NORMAL;
error:
return RTC_ERROR;
}
static int const_surf_grp_item(const struct hecmwST_local_mesh *global_mesh,
struct hecmwST_local_mesh *local_mesh,
const int *elem_global2local) {
struct hecmwST_surf_grp *surf_group_global = global_mesh->surf_group;
struct hecmwST_surf_grp *surf_group_local = local_mesh->surf_group;
int elem, surf;
int size;
int counter;
int i, j;
size = sizeof(int) * surf_group_local->grp_index[surf_group_local->n_grp] * 2;
surf_group_local->grp_item = (int *)HECMW_malloc(size);
if (surf_group_local->grp_item == NULL) {
HECMW_set_error(errno, "");
goto error;
}
for (counter = 0, i = 0; i < surf_group_global->n_grp; i++) {
for (j = surf_group_global->grp_index[i];
j < surf_group_global->grp_index[i + 1]; j++) {
elem = surf_group_global->grp_item[2 * j];
surf = surf_group_global->grp_item[2 * j + 1];
if (elem_global2local[elem - 1]) {
surf_group_local->grp_item[2 * counter] = elem_global2local[elem - 1];
surf_group_local->grp_item[2 * counter + 1] = surf;
counter++;
}
}
HECMW_assert(counter == surf_group_local->grp_index[i + 1]);
}
return RTC_NORMAL;
error:
return RTC_ERROR;
}
static int const_surf_grp_info(const struct hecmwST_local_mesh *global_mesh,
struct hecmwST_local_mesh *local_mesh,
const int *elem_global2local) {
int rtc;
HECMW_assert(global_mesh);
HECMW_assert(global_mesh->surf_group);
HECMW_assert(local_mesh);
HECMW_assert(local_mesh->surf_group);
HECMW_assert(elem_global2local);
if (global_mesh->surf_group->n_grp == 0) {
init_struct_surf_grp(local_mesh);
return RTC_NORMAL;
}
rtc = const_surf_n_grp(global_mesh, local_mesh);
if (rtc != RTC_NORMAL) goto error;
rtc = const_surf_grp_name(global_mesh, local_mesh);
if (rtc != RTC_NORMAL) goto error;
rtc = const_surf_grp_index(global_mesh, local_mesh, elem_global2local);
if (rtc != RTC_NORMAL) goto error;
rtc = const_surf_grp_item(global_mesh, local_mesh, elem_global2local);
if (rtc != RTC_NORMAL) goto error;
return RTC_NORMAL;
error:
return RTC_ERROR;
}
/*- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
* - - - - - - - - - */
static int const_contact_pair_n_pair(
const struct hecmwST_local_mesh *global_mesh,
struct hecmwST_local_mesh *local_mesh) {
local_mesh->contact_pair->n_pair = global_mesh->contact_pair->n_pair;
return RTC_NORMAL;
}
static int const_contact_pair_name(const struct hecmwST_local_mesh *global_mesh,
struct hecmwST_local_mesh *local_mesh) {
local_mesh->contact_pair->name = global_mesh->contact_pair->name;
return RTC_NORMAL;
}
static int const_contact_pair_type(const struct hecmwST_local_mesh *global_mesh,
struct hecmwST_local_mesh *local_mesh) {
struct hecmwST_contact_pair *cpair_global = global_mesh->contact_pair;
struct hecmwST_contact_pair *cpair_local = local_mesh->contact_pair;
int i;
cpair_local->type = (int *)HECMW_calloc(cpair_local->n_pair, sizeof(int));
if (cpair_local->type == NULL) {
HECMW_set_error(errno, "");
goto error;
}
for (i = 0; i < cpair_global->n_pair; i++) {
cpair_local->type[i] = cpair_global->type[i];
}
return RTC_NORMAL;
error:
return RTC_ERROR;
}
static int const_contact_pair_slave_grp_id(
const struct hecmwST_local_mesh *global_mesh,
struct hecmwST_local_mesh *local_mesh) {
struct hecmwST_contact_pair *cpair_global = global_mesh->contact_pair;
struct hecmwST_contact_pair *cpair_local = local_mesh->contact_pair;
int i;
cpair_local->slave_grp_id =
(int *)HECMW_calloc(cpair_local->n_pair, sizeof(int));
if (cpair_local->slave_grp_id == NULL) {
HECMW_set_error(errno, "");
goto error;
}
for (i = 0; i < cpair_global->n_pair; i++) {
cpair_local->slave_grp_id[i] = cpair_global->slave_grp_id[i];
}
return RTC_NORMAL;
error:
return RTC_ERROR;
}
static int const_contact_pair_slave_orisgrp_id(
const struct hecmwST_local_mesh *global_mesh,
struct hecmwST_local_mesh *local_mesh) {
struct hecmwST_contact_pair *cpair_global = global_mesh->contact_pair;
struct hecmwST_contact_pair *cpair_local = local_mesh->contact_pair;
int i;
cpair_local->slave_orisgrp_id =
(int *)HECMW_calloc(cpair_local->n_pair, sizeof(int));
if (cpair_local->slave_orisgrp_id == NULL) {
HECMW_set_error(errno, "");
goto error;
}
for (i = 0; i < cpair_global->n_pair; i++) {
cpair_local->slave_orisgrp_id[i] = cpair_global->slave_orisgrp_id[i];
}
return RTC_NORMAL;
error:
return RTC_ERROR;
}
static int const_contact_pair_master_grp_id(
const struct hecmwST_local_mesh *global_mesh,
struct hecmwST_local_mesh *local_mesh) {
struct hecmwST_contact_pair *cpair_global = global_mesh->contact_pair;
struct hecmwST_contact_pair *cpair_local = local_mesh->contact_pair;
int i;
cpair_local->master_grp_id =
(int *)HECMW_calloc(cpair_local->n_pair, sizeof(int));
if (cpair_local->master_grp_id == NULL) {
HECMW_set_error(errno, "");
goto error;
}
for (i = 0; i < cpair_global->n_pair; i++) {
cpair_local->master_grp_id[i] = cpair_global->master_grp_id[i];
}
return RTC_NORMAL;
error:
return RTC_ERROR;
}
static int const_contact_pair_info(const struct hecmwST_local_mesh *global_mesh,
struct hecmwST_local_mesh *local_mesh) {
int rtc;
HECMW_assert(global_mesh);
HECMW_assert(global_mesh->contact_pair);
HECMW_assert(local_mesh);
HECMW_assert(local_mesh->contact_pair);
if (global_mesh->contact_pair->n_pair == 0) {
init_struct_contact_pair(local_mesh);
return RTC_NORMAL;
}
rtc = const_contact_pair_n_pair(global_mesh, local_mesh);
if (rtc != RTC_NORMAL) goto error;
rtc = const_contact_pair_name(global_mesh, local_mesh);
if (rtc != RTC_NORMAL) goto error;
rtc = const_contact_pair_type(global_mesh, local_mesh);
if (rtc != RTC_NORMAL) goto error;
rtc = const_contact_pair_slave_grp_id(global_mesh, local_mesh);
if (rtc != RTC_NORMAL) goto error;
rtc = const_contact_pair_slave_orisgrp_id(global_mesh, local_mesh);
if (rtc != RTC_NORMAL) goto error;
rtc = const_contact_pair_master_grp_id(global_mesh, local_mesh);
if (rtc != RTC_NORMAL) goto error;
return RTC_NORMAL;
error:
return RTC_ERROR;
}
/*- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
* - - - - - - - - - */
static int const_local_data(const struct hecmwST_local_mesh *global_mesh,
struct hecmwST_local_mesh *local_mesh,
const struct hecmw_part_cont_data *cont_data,
const char *node_flag, const char *elem_flag,
int *node_global2local, int *elem_global2local,
int current_domain) {
int *node_local2global = NULL;
int *elem_local2global = NULL;
int rtc, i;
HECMW_log(HECMW_LOG_DEBUG, "Starting creation of local mesh data...\n");
rtc = set_node_global2local(global_mesh, local_mesh, node_global2local,
node_flag, current_domain);
if (rtc != RTC_NORMAL) goto error;
node_local2global = (int *)HECMW_calloc(local_mesh->n_node, sizeof(int));
if (node_local2global == NULL) {
HECMW_set_error(errno, "");
goto error;
}
if (is_spdup_available(global_mesh)) {
rtc = set_node_local2global_mod(global_mesh, local_mesh, node_global2local,
node_local2global, current_domain);
} else {
rtc = set_node_local2global(global_mesh, local_mesh, node_global2local,
node_local2global);
}
if (rtc != RTC_NORMAL) goto error;
rtc = set_elem_global2local(global_mesh, local_mesh, elem_global2local,
elem_flag, current_domain);
if (rtc != RTC_NORMAL) goto error;
elem_local2global = (int *)HECMW_calloc(local_mesh->n_elem, sizeof(int));
if (elem_local2global == NULL) {
HECMW_set_error(errno, "");
goto error;
}
if (is_spdup_available(global_mesh)) {
rtc = set_elem_local2global_mod(global_mesh, local_mesh, elem_global2local,
elem_local2global, current_domain);
} else {
rtc = set_elem_local2global(global_mesh, local_mesh, elem_global2local,
elem_local2global);
}
if (rtc != RTC_NORMAL) goto error;
rtc = const_global_info(global_mesh, local_mesh);
if (rtc != RTC_NORMAL) goto error;
rtc = const_node_info(global_mesh, local_mesh, node_local2global, node_flag,
current_domain);
if (rtc != RTC_NORMAL) goto error;
rtc = const_elem_info(global_mesh, local_mesh, node_global2local,
elem_global2local, elem_local2global, current_domain);
if (rtc != RTC_NORMAL) goto error;
rtc = const_comm_info(global_mesh, local_mesh, node_global2local,
elem_global2local, current_domain);
if (rtc != RTC_NORMAL) goto error;
rtc = const_adapt_info(global_mesh, local_mesh);
if (rtc != RTC_NORMAL) goto error;
rtc = const_sect_info(global_mesh, local_mesh);
if (rtc != RTC_NORMAL) goto error;
rtc = const_mat_info(global_mesh, local_mesh);
if (rtc != RTC_NORMAL) goto error;
rtc = const_mpc_info(global_mesh, local_mesh, node_global2local);
if (rtc != RTC_NORMAL) goto error;
rtc = const_amp_info(global_mesh, local_mesh);
if (rtc != RTC_NORMAL) goto error;
rtc = const_node_grp_info(global_mesh, local_mesh, node_global2local,
current_domain);
if (rtc != RTC_NORMAL) goto error;
rtc = const_elem_grp_info(global_mesh, local_mesh, elem_global2local,
current_domain);
if (rtc != RTC_NORMAL) goto error;
rtc = const_surf_grp_info(global_mesh, local_mesh, elem_global2local);
if (rtc != RTC_NORMAL) goto error;
rtc = const_contact_pair_info(global_mesh, local_mesh);
if (rtc != RTC_NORMAL) goto error;
rtc = clear_node_global2local(global_mesh, local_mesh, node_global2local,
current_domain);
rtc = clear_elem_global2local(global_mesh, local_mesh, elem_global2local,
current_domain);
HECMW_free(node_local2global);
HECMW_free(elem_local2global);
HECMW_log(HECMW_LOG_DEBUG, "Creation of local mesh data done\n");
return RTC_NORMAL;
error:
HECMW_free(node_local2global);
HECMW_free(elem_local2global);
clean_struct_local_mesh(local_mesh);
return RTC_ERROR;
}
/*==================================================================================================
print UCD format data
==================================================================================================*/
static int print_ucd_entire_set_node_data(
const struct hecmwST_local_mesh *global_mesh,
struct hecmwST_result_data *result_data, const char *node_flag) {
int size;
int nn_item;
int i;
result_data->nn_component = 1;
result_data->nn_dof =
(int *)HECMW_malloc(sizeof(int) * result_data->nn_component);
if (result_data->nn_dof == NULL) {
HECMW_set_error(errno, "");
goto error;
}
result_data->nn_dof[0] = 1;
result_data->node_label =
(char **)HECMW_malloc(sizeof(char *) * result_data->nn_component);
if (result_data->node_label == NULL) {
HECMW_set_error(errno, "");
goto error;
} else {
for (i = 0; i < result_data->nn_component; i++) {
result_data->node_label[i] = NULL;
}
}
for (i = 0; i < result_data->nn_component; i++) {
result_data->node_label[i] =
(char *)HECMW_malloc(sizeof(char) * (HECMW_NAME_LEN + 1));
if (result_data->node_label[i] == NULL) {
HECMW_set_error(errno, "");
goto error;
}
}
strcpy(result_data->node_label[0], "rank_of_node");
for (nn_item = 0, i = 0; i < result_data->nn_component; i++) {
nn_item += result_data->nn_dof[i];
}
size = sizeof(double) * nn_item * global_mesh->n_node;
result_data->node_val_item = (double *)HECMW_malloc(size);
if (result_data->node_val_item == NULL) {
HECMW_set_error(errno, "");
goto error;
}
switch (global_mesh->hecmw_flag_parttype) {
case HECMW_FLAG_PARTTYPE_NODEBASED:
for (i = 0; i < global_mesh->n_node; i++) {
result_data->node_val_item[i] = (double)global_mesh->node_ID[2 * i + 1];
}
break;
case HECMW_FLAG_PARTTYPE_ELEMBASED:
for (i = 0; i < global_mesh->n_node; i++) {
if (EVAL_BIT(node_flag[i], OVERLAP)) {
result_data->node_val_item[i] =
(double)global_mesh->n_subdomain + 2.0;
} else {
result_data->node_val_item[i] =
(double)global_mesh->node_ID[2 * i + 1];
}
}
break;
default:
HECMW_set_error(HECMW_PART_E_INVALID_PTYPE, "%d",
global_mesh->hecmw_flag_parttype);
goto error;
}
return RTC_NORMAL;
error:
free_struct_result_data(result_data);
return RTC_ERROR;
}
/*- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
* - - - - - - - - - */
static int print_ucd_entire_set_elem_data(
const struct hecmwST_local_mesh *global_mesh,
struct hecmwST_result_data *result_data, const char *elem_flag) {
int size;
int ne_item;
int i;
result_data->ne_component = 1;
result_data->ne_dof =
(int *)HECMW_malloc(sizeof(int) * result_data->ne_component);
if (result_data->ne_dof == NULL) {
HECMW_set_error(errno, "");
goto error;
}
result_data->ne_dof[0] = 1;
result_data->elem_label =
(char **)HECMW_malloc(sizeof(char *) * result_data->ne_component);
if (result_data->elem_label == NULL) {
HECMW_set_error(errno, "");
goto error;
} else {
for (i = 0; i < result_data->ne_component; i++) {
result_data->elem_label[i] = NULL;
}
}
for (i = 0; i < result_data->ne_component; i++) {
result_data->elem_label[i] =
(char *)HECMW_malloc(sizeof(char) * (HECMW_NAME_LEN + 1));
if (result_data->elem_label[i] == NULL) {
HECMW_set_error(errno, "");
goto error;
}
}
strcpy(result_data->elem_label[0], "partitioning_image");
/* modify element information*/
for (i = 0; i < global_mesh->n_elem; i++) {
switch (global_mesh->elem_type[i]) {
case HECMW_ETYPE_SHT6:
global_mesh->elem_type[i] = HECMW_ETYPE_SHT1;
break;
case HECMW_ETYPE_SHQ8:
global_mesh->elem_type[i] = HECMW_ETYPE_SHQ1;
break;
case HECMW_ETYPE_BEM3:
global_mesh->elem_type[i] = HECMW_ETYPE_ROD1;
break;
case HECMW_ETYPE_ROD31:
global_mesh->elem_type[i] = HECMW_ETYPE_ROD1;
break;
}
}
for (ne_item = 0, i = 0; i < result_data->ne_component; i++) {
ne_item += result_data->ne_dof[i];
}
size = sizeof(double) * ne_item * global_mesh->n_elem;
result_data->elem_val_item = (double *)HECMW_malloc(size);
if (result_data->elem_val_item == NULL) {
HECMW_set_error(errno, "");
goto error;
}
switch (global_mesh->hecmw_flag_parttype) {
case HECMW_FLAG_PARTTYPE_NODEBASED:
for (i = 0; i < global_mesh->n_elem; i++) {
if (EVAL_BIT(elem_flag[i], OVERLAP)) {
result_data->elem_val_item[i] =
(double)global_mesh->n_subdomain + 2.0;
} else {
result_data->elem_val_item[i] =
(double)global_mesh->elem_ID[2 * i + 1];
}
}
break;
case HECMW_FLAG_PARTTYPE_ELEMBASED:
for (i = 0; i < global_mesh->n_elem; i++) {
result_data->elem_val_item[i] = (double)global_mesh->elem_ID[2 * i + 1];
}
break;
default:
HECMW_set_error(HECMW_PART_E_INVALID_PTYPE, "%d",
global_mesh->hecmw_flag_parttype);
goto error;
}
return RTC_NORMAL;
error:
free_struct_result_data(result_data);
return RTC_ERROR;
}
/*- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
static int print_ucd_entire(const struct hecmwST_local_mesh *global_mesh,
const char *node_flag, const char *elem_flag,
const char *ofname) {
struct hecmwST_result_data *result_data;
result_data = (struct hecmwST_result_data *)HECMW_malloc(
sizeof(struct hecmwST_result_data));
if (result_data == NULL) {
HECMW_set_error(errno, "");
goto error;
} else {
init_struct_result_data(result_data);
}
if (print_ucd_entire_set_node_data(global_mesh, result_data, node_flag)) {
goto error;
}
if (print_ucd_entire_set_elem_data(global_mesh, result_data, elem_flag)) {
goto error;
}
if (HECMW_ucd_legacy_print(global_mesh, result_data, ofname)) {
goto error;
}
free_struct_result_data(result_data);
return RTC_NORMAL;
error:
free_struct_result_data(result_data);
return RTC_ERROR;
}
static int init_partition(struct hecmwST_local_mesh *global_mesh,
struct hecmw_part_cont_data *cont_data) {
HECMW_log(HECMW_LOG_DEBUG, "Starting initialization for partitioner...");
/* global_mesh->n_subdomain */
global_mesh->n_subdomain = cont_data->n_domain;
/* global_mesh->hecmw_flag_parttype */
switch (cont_data->type) {
case HECMW_PART_TYPE_NODE_BASED: /* for node-based partitioning */
global_mesh->hecmw_flag_parttype = HECMW_FLAG_PARTTYPE_NODEBASED;
break;
case HECMW_PART_TYPE_ELEMENT_BASED: /* for element-based partitioning */
global_mesh->hecmw_flag_parttype = HECMW_FLAG_PARTTYPE_ELEMBASED;
break;
default:
HECMW_set_error(HECMW_PART_E_INVALID_PTYPE, "%d", cont_data->type);
goto error;
}
/* global_mesh->hecmw_flag_partdepth */
global_mesh->hecmw_flag_partdepth = cont_data->depth;
/* global_mesh->hecmw_flag_partcontact */
if (global_mesh->contact_pair->n_pair > 0) {
switch (cont_data->contact) {
case HECMW_PART_CONTACT_AGGREGATE:
global_mesh->hecmw_flag_partcontact = HECMW_FLAG_PARTCONTACT_AGGREGATE;
break;
case HECMW_PART_CONTACT_DISTRIBUTE:
global_mesh->hecmw_flag_partcontact = HECMW_FLAG_PARTCONTACT_DISTRIBUTE;
break;
case HECMW_PART_CONTACT_SIMPLE:
global_mesh->hecmw_flag_partcontact = HECMW_FLAG_PARTCONTACT_SIMPLE;
break;
case HECMW_PART_CONTACT_DEFAULT:
default:
cont_data->contact = HECMW_PART_CONTACT_SIMPLE;
global_mesh->hecmw_flag_partcontact = HECMW_FLAG_PARTCONTACT_SIMPLE;
break;
}
}
HECMW_log(HECMW_LOG_DEBUG, "Initialization for partitioner done");
return RTC_NORMAL;
error:
return RTC_ERROR;
;
}
/*==================================================================================================
main function
==================================================================================================*/
extern struct hecmwST_local_mesh *HECMW_partition_inner(
struct hecmwST_local_mesh *global_mesh,
struct hecmw_part_cont_data *cont_data) {
struct hecmwST_local_mesh *local_mesh = NULL;
struct hecmw_ctrl_meshfiles *ofheader = NULL;
char *node_flag = NULL;
char *elem_flag = NULL;
char *node_flag_neighbor = NULL;
char *elem_flag_neighbor = NULL;
int *node_global2local = NULL;
int *elem_global2local = NULL;
char ofname[HECMW_FILENAME_LEN + 1];
int *num_elem, *num_node, *num_ielem, *num_inode, *num_nbpe;
int *sum_elem, *sum_node, *sum_ielem, *sum_inode, *sum_nbpe;
int current_domain, nrank, iS, iE;
int rtc;
int i;
int error_in_ompsection = 0;
if (global_mesh == NULL) {
HECMW_set_error(HECMW_PART_E_INV_ARG, "\'global_mesh\' is NULL");
goto error;
}
if (cont_data == NULL) {
HECMW_set_error(HECMW_PART_E_INV_ARG, "\'cont_data\' is NULL");
goto error;
}
rtc = init_partition(global_mesh, cont_data);
if (rtc != RTC_NORMAL) goto error;
rtc = HECMW_part_init_log(global_mesh->n_subdomain);
if (rtc != RTC_NORMAL) goto error;
if (global_mesh->my_rank == 0) {
rtc = HECMW_part_set_log_part_type(cont_data->type);
if (rtc != RTC_NORMAL) goto error;
rtc = HECMW_part_set_log_part_method(cont_data->method);
if (rtc != RTC_NORMAL) goto error;
rtc = HECMW_part_set_log_part_depth(cont_data->depth);
if (rtc != RTC_NORMAL) goto error;
rtc = HECMW_part_set_log_part_contact(cont_data->contact);
if (rtc != RTC_NORMAL) goto error;
rtc = HECMW_part_set_log_n_node_g(global_mesh->n_node);
if (rtc != RTC_NORMAL) goto error;
rtc = HECMW_part_set_log_n_elem_g(global_mesh->n_elem);
if (rtc != RTC_NORMAL) goto error;
}
if (global_mesh->n_subdomain == 1) {
current_domain = 0;
if (global_mesh->my_rank == 0) {
HECMW_log(HECMW_LOG_INFO, "Creating local mesh for domain #%d ...",
current_domain);
ofheader = HECMW_ctrl_get_meshfiles_header_sub(
"part_out", global_mesh->n_subdomain, current_domain);
if (ofheader == NULL) {
HECMW_log(HECMW_LOG_ERROR, "not set output file header");
error_in_ompsection = 1;
goto error;
}
if (ofheader->n_mesh == 0) {
HECMW_log(HECMW_LOG_ERROR, "output file name is not set");
error_in_ompsection = 1;
goto error;
}
get_dist_file_name(ofheader->meshfiles[0].filename, current_domain,
ofname);
HECMW_assert(ofname != NULL);
HECMW_log(HECMW_LOG_DEBUG,
"Starting writing local mesh for domain #%d...",
current_domain);
rtc = HECMW_put_dist_mesh(global_mesh, ofname);
if (rtc != 0) {
HECMW_log(HECMW_LOG_ERROR, "Failed to write local mesh for domain #%d",
current_domain);
goto error;
}
HECMW_log(HECMW_LOG_DEBUG, "Writing local mesh for domain #%d done",
current_domain);
rtc = HECMW_part_set_log_n_elem(0, global_mesh->n_elem);
if (rtc != 0) goto error;
rtc = HECMW_part_set_log_n_node(0, global_mesh->n_node);
if (rtc != 0) goto error;
rtc = HECMW_part_set_log_ne_internal(0, global_mesh->ne_internal);
if (rtc != 0) goto error;
rtc = HECMW_part_set_log_nn_internal(0, global_mesh->nn_internal);
if (rtc != 0) goto error;
rtc = HECMW_part_print_log();
if (rtc) goto error;
}
HECMW_part_finalize_log();
return global_mesh;
}
num_elem = (int *)HECMW_calloc(global_mesh->n_subdomain, sizeof(int));
if (num_elem == NULL) {
HECMW_set_error(errno, "");
goto error;
}
num_node = (int *)HECMW_calloc(global_mesh->n_subdomain, sizeof(int));
if (num_node == NULL) {
HECMW_set_error(errno, "");
goto error;
}
num_ielem = (int *)HECMW_calloc(global_mesh->n_subdomain, sizeof(int));
if (num_ielem == NULL) {
HECMW_set_error(errno, "");
goto error;
}
num_inode = (int *)HECMW_calloc(global_mesh->n_subdomain, sizeof(int));
if (num_inode == NULL) {
HECMW_set_error(errno, "");
goto error;
}
num_nbpe = (int *)HECMW_calloc(global_mesh->n_subdomain, sizeof(int));
if (num_nbpe == NULL) {
HECMW_set_error(errno, "");
goto error;
}
sum_elem = (int *)HECMW_calloc(global_mesh->n_subdomain, sizeof(int));
if (sum_elem == NULL) {
HECMW_set_error(errno, "");
goto error;
}
sum_node = (int *)HECMW_calloc(global_mesh->n_subdomain, sizeof(int));
if (sum_node == NULL) {
HECMW_set_error(errno, "");
goto error;
}
sum_ielem = (int *)HECMW_calloc(global_mesh->n_subdomain, sizeof(int));
if (sum_ielem == NULL) {
HECMW_set_error(errno, "");
goto error;
}
sum_inode = (int *)HECMW_calloc(global_mesh->n_subdomain, sizeof(int));
if (sum_inode == NULL) {
HECMW_set_error(errno, "");
goto error;
}
sum_nbpe = (int *)HECMW_calloc(global_mesh->n_subdomain, sizeof(int));
if (sum_nbpe == NULL) {
HECMW_set_error(errno, "");
goto error;
}
rtc = wnumbering(global_mesh, cont_data);
if (rtc != RTC_NORMAL) goto error;
/*K. Inagaki */
rtc = spdup_makelist_main(global_mesh);
if (rtc != RTC_NORMAL) goto error;
#ifdef _OPENMP
#pragma omp parallel default(none), \
private(node_flag, elem_flag, local_mesh, nrank, iS, iE, i, \
current_domain, rtc, ofheader, ofname), \
private(node_global2local, elem_global2local, \
node_flag_neighbor, elem_flag_neighbor), \
shared(global_mesh, cont_data, num_elem, num_node, \
num_ielem, num_inode, num_nbpe, error_in_ompsection)
{
#endif /* _OPENMP */
node_flag = (char *)HECMW_calloc(global_mesh->n_node, sizeof(char));
if (node_flag == NULL) {
HECMW_set_error(errno, "");
error_in_ompsection = 1;
goto error_omp;
}
elem_flag = (char *)HECMW_calloc(global_mesh->n_elem, sizeof(char));
if (elem_flag == NULL) {
HECMW_set_error(errno, "");
error_in_ompsection = 1;
goto error_omp;
}
/*K. Inagaki */
node_global2local = (int *)HECMW_calloc(global_mesh->n_node, sizeof(int));
if (node_global2local == NULL) {
HECMW_set_error(errno, "");
error_in_ompsection = 1;
goto error_omp;
}
elem_global2local = (int *)HECMW_calloc(global_mesh->n_elem, sizeof(int));
if (elem_global2local == NULL) {
HECMW_set_error(errno, "");
error_in_ompsection = 1;
goto error_omp;
}
node_flag_neighbor =
(char *)HECMW_malloc(sizeof(char) * global_mesh->n_node);
if (node_flag_neighbor == NULL) {
HECMW_set_error(errno, "");
error_in_ompsection = 1;
goto error_omp;
}
elem_flag_neighbor =
(char *)HECMW_malloc(sizeof(char) * global_mesh->n_elem);
if (elem_flag_neighbor == NULL) {
HECMW_set_error(errno, "");
error_in_ompsection = 1;
goto error_omp;
}
memset(node_flag_neighbor, 0, sizeof(char) * global_mesh->n_node);
memset(elem_flag_neighbor, 0, sizeof(char) * global_mesh->n_elem);
local_mesh = HECMW_dist_alloc();
if (local_mesh == NULL) {
error_in_ompsection = 1;
goto error_omp;
}
nrank = global_mesh->n_subdomain / HECMW_comm_get_size();
iS = HECMW_comm_get_rank() * nrank;
iE = iS + nrank;
if (HECMW_comm_get_rank() == HECMW_comm_get_size() - 1)
iE = global_mesh->n_subdomain;
#ifdef _OPENMP
#pragma omp for schedule(dynamic, 1), reduction(+ : error_in_ompsection)
#endif
for (i = iS; i < iE; i++) {
if (error_in_ompsection) continue;
current_domain = i;
HECMW_log(HECMW_LOG_INFO, "Creating local mesh for domain #%d ...",
current_domain);
rtc = create_neighbor_info(global_mesh, local_mesh, node_flag, elem_flag,
current_domain);
if (rtc != RTC_NORMAL) {
error_in_ompsection = 1;
continue;
}
if (global_mesh->n_subdomain > 1) {
rtc = create_comm_info(global_mesh, local_mesh, node_flag, elem_flag,
node_flag_neighbor, elem_flag_neighbor,
current_domain);
if (rtc != RTC_NORMAL) {
error_in_ompsection = 1;
continue;
}
}
rtc = const_local_data(global_mesh, local_mesh, cont_data, node_flag,
elem_flag, node_global2local, elem_global2local,
current_domain);
if (rtc != RTC_NORMAL) {
error_in_ompsection = 1;
continue;
}
num_elem[i] = local_mesh->n_elem;
num_node[i] = local_mesh->n_node;
num_ielem[i] = local_mesh->ne_internal;
num_inode[i] = local_mesh->nn_internal;
num_nbpe[i] = local_mesh->n_neighbor_pe;
ofheader = HECMW_ctrl_get_meshfiles_header_sub(
"part_out", global_mesh->n_subdomain, current_domain);
if (ofheader == NULL) {
HECMW_log(HECMW_LOG_ERROR, "not set output file header");
error_in_ompsection = 1;
continue;
}
if (ofheader->n_mesh == 0) {
HECMW_log(HECMW_LOG_ERROR, "output file name is not set");
error_in_ompsection = 1;
continue;
}
get_dist_file_name(ofheader->meshfiles[0].filename, current_domain,
ofname);
HECMW_assert(ofname != NULL);
HECMW_log(HECMW_LOG_DEBUG,
"Starting writing local mesh for domain #%d...",
current_domain);
rtc = HECMW_put_dist_mesh(local_mesh, ofname);
if (rtc != 0) {
HECMW_log(HECMW_LOG_ERROR, "Failed to write local mesh for domain #%d",
current_domain);
error_in_ompsection = 1;
} else {
HECMW_log(HECMW_LOG_DEBUG, "Writing local mesh for domain #%d done",
current_domain);
}
clean_struct_local_mesh(local_mesh);
HECMW_ctrl_free_meshfiles(ofheader);
ofheader = NULL;
if (is_spdup_available(global_mesh)) {
/*K. Inagaki */
spdup_clear_IEB(node_flag, elem_flag, current_domain);
} else {
int j;
for (j = 0; j < global_mesh->n_node; j++) {
CLEAR_IEB(node_flag[j]);
}
for (j = 0; j < global_mesh->n_elem; j++) {
CLEAR_IEB(elem_flag[j]);
}
}
}
#ifdef _OPENMP
if (error_in_ompsection) goto error_omp;
#pragma omp single
#endif
if (cont_data->is_print_ucd == 1) {
if (global_mesh->my_rank == 0) {
print_ucd_entire(global_mesh, node_flag, elem_flag,
cont_data->ucd_file_name);
}
}
error_omp:
HECMW_dist_free(local_mesh);
HECMW_free(node_flag);
HECMW_free(elem_flag);
/*K. Inagaki */
HECMW_free(node_global2local);
HECMW_free(elem_global2local);
HECMW_free(node_flag_neighbor);
HECMW_free(elem_flag_neighbor);
#ifdef _OPENMP
} /* omp end parallel */
if (error_in_ompsection) goto error;
#endif
rtc = HECMW_Allreduce(num_elem, sum_elem, global_mesh->n_subdomain, HECMW_INT,
HECMW_SUM, HECMW_comm_get_comm());
if (rtc != 0) goto error;
rtc = HECMW_Allreduce(num_node, sum_node, global_mesh->n_subdomain, HECMW_INT,
HECMW_SUM, HECMW_comm_get_comm());
if (rtc != 0) goto error;
rtc = HECMW_Allreduce(num_ielem, sum_ielem, global_mesh->n_subdomain,
HECMW_INT, HECMW_SUM, HECMW_comm_get_comm());
if (rtc != 0) goto error;
rtc = HECMW_Allreduce(num_inode, sum_inode, global_mesh->n_subdomain,
HECMW_INT, HECMW_SUM, HECMW_comm_get_comm());
if (rtc != 0) goto error;
rtc = HECMW_Allreduce(num_nbpe, sum_nbpe, global_mesh->n_subdomain,
HECMW_INT, HECMW_SUM, HECMW_comm_get_comm());
if (rtc != 0) goto error;
if (global_mesh->my_rank == 0) {
for (i = 0; i < global_mesh->n_subdomain; i++) {
rtc = HECMW_part_set_log_n_elem(i, sum_elem[i]);
if (rtc != 0) goto error;
rtc = HECMW_part_set_log_n_node(i, sum_node[i]);
if (rtc != 0) goto error;
rtc = HECMW_part_set_log_ne_internal(i, sum_ielem[i]);
if (rtc != 0) goto error;
rtc = HECMW_part_set_log_nn_internal(i, sum_inode[i]);
if (rtc != 0) goto error;
rtc = HECMW_part_set_log_n_neighbor_pe(i, sum_nbpe[i]);
if (rtc != 0) goto error;
}
rtc = HECMW_part_print_log();
if (rtc) goto error;
}
HECMW_part_finalize_log();
HECMW_free(num_elem);
HECMW_free(num_node);
HECMW_free(num_ielem);
HECMW_free(num_inode);
HECMW_free(num_nbpe);
HECMW_free(sum_elem);
HECMW_free(sum_node);
HECMW_free(sum_ielem);
HECMW_free(sum_inode);
HECMW_free(sum_nbpe);
/*K. Inagaki */
spdup_freelist(global_mesh);
return global_mesh;
error:
HECMW_free(node_flag);
HECMW_free(elem_flag);
HECMW_free(num_elem);
HECMW_free(num_node);
HECMW_free(num_ielem);
HECMW_free(num_inode);
HECMW_free(num_nbpe);
HECMW_free(sum_elem);
HECMW_free(sum_node);
HECMW_free(sum_ielem);
HECMW_free(sum_inode);
HECMW_free(sum_nbpe);
HECMW_dist_free(local_mesh);
if (ofheader) {
HECMW_ctrl_free_meshfiles(ofheader);
}
HECMW_part_finalize_log();
return NULL;
}
extern struct hecmwST_local_mesh *HECMW_partition(
struct hecmwST_local_mesh *global_mesh) {
struct hecmwST_local_mesh *local_mesh;
struct hecmw_part_cont_data *cont_data;
HECMW_log(HECMW_LOG_INFO, "Starting domain decomposition...\n");
if (global_mesh == NULL) {
HECMW_set_error(HECMW_PART_E_INV_ARG, "\'global_mesh\' is NULL");
goto error;
}
cont_data = HECMW_part_get_control(global_mesh);
if (cont_data == NULL) goto error;
local_mesh = HECMW_partition_inner(global_mesh, cont_data);
if (local_mesh == NULL) goto error;
HECMW_part_free_control(cont_data);
HECMW_log(HECMW_LOG_INFO, "Domain decomposition done\n");
return local_mesh;
error:
return NULL;
}
|
GB_binop__land_uint32.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__land_uint32
// A.*B function (eWiseMult): GB_AemultB__land_uint32
// A*D function (colscale): GB_AxD__land_uint32
// D*A function (rowscale): GB_DxB__land_uint32
// C+=B function (dense accum): GB_Cdense_accumB__land_uint32
// C+=b function (dense accum): GB_Cdense_accumb__land_uint32
// C+=A+B function (dense ewise3): (none)
// C=A+B function (dense ewise3): GB_Cdense_ewise3_noaccum__land_uint32
// C=scalar+B GB_bind1st__land_uint32
// C=scalar+B' GB_bind1st_tran__land_uint32
// C=A+scalar GB_bind2nd__land_uint32
// C=A'+scalar GB_bind2nd_tran__land_uint32
// C type: uint32_t
// A type: uint32_t
// B,b type: uint32_t
// BinaryOp: cij = ((aij != 0) && (bij != 0))
#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, i, j) \
z = ((x != 0) && (y != 0)) ;
// op is second
#define GB_OP_IS_SECOND \
0
// op is plus_fp32 or plus_fp64
#define GB_OP_IS_PLUS_REAL \
0
// op is minus_fp32 or minus_fp64
#define GB_OP_IS_MINUS_REAL \
0
// GB_cblas_*axpy gateway routine, if it exists for this operator and type:
#define GB_CBLAS_AXPY \
(none)
// do the numerical phases of GB_add and GB_emult
#define GB_PHASE_2_OF_2
// hard-coded loops can be vectorized
#define GB_PRAGMA_SIMD_VECTORIZE GB_PRAGMA_SIMD
// disable this operator and use the generic case if these conditions hold
#define GB_DISABLE \
(GxB_NO_LAND || GxB_NO_UINT32 || GxB_NO_LAND_UINT32)
//------------------------------------------------------------------------------
// C += A+B, all 3 matrices dense
//------------------------------------------------------------------------------
#if 0
// The op must be MIN, MAX, PLUS, MINUS, RMINUS, TIMES, DIV, or RDIV.
void (none)
(
GrB_Matrix C,
const GrB_Matrix A,
const GrB_Matrix B,
const int nthreads
)
{
#include "GB_dense_ewise3_accum_template.c"
}
#endif
//------------------------------------------------------------------------------
// C = A+B, all 3 matrices dense
//------------------------------------------------------------------------------
GrB_Info GB_Cdense_ewise3_noaccum__land_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__land_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__land_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__land_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__land_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
//------------------------------------------------------------------------------
#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__land_uint32
(
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__land_uint32
(
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__land_uint32
(
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
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++)
{
if (!GBB (Bb, p)) continue ;
uint32_t bij = Bx [p] ;
Cx [p] = ((x != 0) && (bij != 0)) ;
}
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// Cx = op (Ax,y): apply a binary operator to a matrix with scalar bind2nd
//------------------------------------------------------------------------------
GrB_Info GB_bind2nd__land_uint32
(
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 ;
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++)
{
if (!GBB (Ab, p)) continue ;
uint32_t aij = Ax [p] ;
Cx [p] = ((aij != 0) && (y != 0)) ;
}
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// C = op (x, A'): transpose and apply a binary operator
//------------------------------------------------------------------------------
// cij = op (x, aij), no typecasting (in spite of the macro name)
#undef GB_CAST_OP
#define GB_CAST_OP(pC,pA) \
{ \
uint32_t aij = Ax [pA] ; \
Cx [pC] = ((x != 0) && (aij != 0)) ; \
}
GrB_Info GB_bind1st_tran__land_uint32
(
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 \
uint32_t
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
uint32_t x = (*((const uint32_t *) x_input)) ;
#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 typecasting (in spite of the macro name)
#undef GB_CAST_OP
#define GB_CAST_OP(pC,pA) \
{ \
uint32_t aij = Ax [pA] ; \
Cx [pC] = ((aij != 0) && (y != 0)) ; \
}
GrB_Info GB_bind2nd_tran__land_uint32
(
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
uint32_t y = (*((const uint32_t *) y_input)) ;
#include "GB_unop_transpose.c"
return (GrB_SUCCESS) ;
#endif
}
#endif
|
repeat_base.h | // ==========================================================================
// SeqAn - The Library for Sequence Analysis
// ==========================================================================
// Copyright (c) 2006-2013, Knut Reinert, FU Berlin
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of Knut Reinert or the FU Berlin nor the names of
// its contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL KNUT REINERT OR THE FU BERLIN BE LIABLE
// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
// LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
// OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
// DAMAGE.
//
// ==========================================================================
// Author: David Weese <david.weese@fu-berlin.de>
// ==========================================================================
#ifndef SEQAN_HEADER_REPEAT_BASE_H
#define SEQAN_HEADER_REPEAT_BASE_H
#if SEQAN_ENABLE_PARALLELISM
#include <seqan/parallel.h>
#endif // #if SEQAN_ENABLE_PARALLELISM
namespace seqan {
/**
.Class.Repeat
..summary:Store information about a repeat.
..cat:Index
..signature:Repeat<TPos, TPeriod>
..param.TPos:Type to use for storing positions.
...metafunction:Metafunction.Value
..param.TPeriod:Type to use for storing the repeat period.
...default:1
...metafunction:Metafunction.Size
..include:seqan/index.h
..see:Function.findRepeats
.Memvar.Repeat#beginPosition
..summary:The begin position of the repeat of type $TPos$.
..class:Class.Repeat
.Memvar.Repeat#endPosition
..summary:The end position of the repeat of type $TPos$.
..class:Class.Repeat
.Memvar.Repeat#period
..summary:The period of the repeat of type $TSize$.
..class:Class.Repeat
*/
/*!
* @class Repeat
*
* @headerfile seqan/index.h
*
* @brief Store information about a repeat.
*
* @signature Repeat<TPos, TPeriod>
*
* @tparam TPeriod Type to use for storing the repeat period. Default: 1
* @tparam TPos Type to use for storing positions.
*
* @see findRepeats
*
* @var VariableType Repeat::endPosition
*
* @brief The end position of the repeat of type <tt>TPos</tt>.
*
* @var VariableType Repeat::beginPosition
*
* @brief The begin position of the repeat of type <tt>TPos</tt>.
*
* @var VariableType Repeat::period
*
* @brief The period of the repeat of type <tt>TSize</tt>.
*/
template <typename TPos, typename TPeriod>
struct Repeat {
TPos beginPosition;
TPos endPosition;
TPeriod period;
};
template <typename TPos, typename TPeriod>
struct Value< Repeat<TPos, TPeriod> > {
typedef TPos Type;
};
template <typename TPos, typename TPeriod>
struct Size< Repeat<TPos, TPeriod> > {
typedef TPeriod Type;
};
template <typename TSize>
struct RepeatFinderParams {
TSize minRepeatLen;
TSize maxPeriod;
};
// custom TSpec for our customized wotd-Index
struct TRepeatFinder;
template <typename TText>
struct Cargo<Index<TText, IndexWotd<TRepeatFinder> > >
{
typedef Index<TText, IndexWotd<TRepeatFinder> > TIndex;
typedef typename Size<TIndex>::Type TSize;
typedef RepeatFinderParams<TSize> Type;
};
// node predicate
template <typename TText, typename TSpec>
bool nodePredicate(Iter<Index<TText, IndexWotd<TRepeatFinder> >, TSpec> &it)
{
// return countOccurrences(it) * nodeDepth(it) >= cargo(container(it)).minRepeatLen;
return countOccurrences(it) * repLength(it) >= cargo(container(it)).minRepeatLen;
}
// monotonic hull
template <typename TText, typename TSpec>
bool nodeHullPredicate(Iter<Index<TText, IndexWotd<TRepeatFinder> >, TSpec> &it)
{
// return nodeDepth(it) <= cargo(container(it)).maxPeriod;
return repLength(it) <= cargo(container(it)).maxPeriod;
}
template <typename TPos>
struct RepeatLess_ : public ::binary_function<TPos, TPos, bool>
{
// key less
inline bool operator() (TPos const &a, TPos const &b) {
return posLess(a, b);
}
};
template <typename TValue>
inline bool _repeatMaskValue(TValue const &)
{
// TODO(holtgrew): Maybe use unknownValue<TValue>() instead of specializing for all alphabets, especially since we have Rna5 now and might want Rna5Q later.
return false;
}
template <>
inline bool _repeatMaskValue(Dna5 const &val)
{
return val == unknownValue<Dna5>(); // 'N'
}
template <>
inline bool _repeatMaskValue(Dna5Q const &val)
{
return val == unknownValue<Dna5Q>(); // 'N'
}
template <>
inline bool _repeatMaskValue(Iupac const &val)
{
return val == unknownValue<Iupac>(); // 'N'
}
/*
template <>
inline bool _repeatMaskValue(AminoAcid val)
{
return val == 'X';
}
*/
/**
.Function.findRepeats
..summary:Search for repeats in a text.
..cat:Index
..signature:findRepeats(repeatString, text, minRepeatLength[, maxPeriod])
..param.repeatString:A @Class.String@ of @Class.Repeat@ objects.
..param.text:The text to search repeats in.
...type:Class.String
...type:Class.StringSet
..param.minRepeatLength:The minimum length each reported repeat must have.
..param.maxPeriod:Optionally, the maximal period that reported repeats can have.
...default:1
..remarks:Subsequences of undefined values/$N$s will always be reported.
..example.text:The following demonstrates finding repeats of period 1.
..example.code:
String<Repeat<unsigned, unsigned> > repeats;
Dna5String text = "CGATAAAACTNN";
// repeat 0 AAAA
// repeat 1 NN
findRepeats(repeats, text, 3);
// ==> length(repeats) == 2
// ==> repeats[0] == {beginPosition: 4, endPosition: 8, period: 1}
// ==> repeats[1] == {beginPosition: 11, endPosition: 13, period: 1}
..see:Function.unknownValue
..include:seqan/index.h
..see:Class.Repeat
*/
/*!
* @fn findRepeats
*
* @headerfile seqan/index.h
*
* @brief Search for repeats in a text.
*
* @signature findRepeats(repeatString, text, minRepeatLength[, maxPeriod])
*
* @param text The text to search repeats in. Types: @link SequenceConcept @endlink
* @param repeatString A @link String @endlink of @link Repeat @endlink objects.
* @param maxPeriod Optionally, the maximal period that reported repeats can
* have. Default: 1
* @param minRepeatLength The minimum length each reported repeat must have.
*
* @section Remarks
*
* Subsequences of undefined values/<tt>N</tt>s will always be reported.
*
* @section Examples
*
* The following demonstrates finding repeats of period 1.
*
* @code{.cpp}
* String<Repeat<unsigned, unsigned> > repeats;
* Dna5String text = "CGATAAAACTNN";
* // repeat 0 AAAA
* // repeat 1 NN
*
* findRepeats(repeats, text, 3);
* // ==> length(repeats) == 2
* // ==> repeats[0] == {beginPosition: 4, endPosition: 8, period: 1}
* // ==> repeats[1] == {beginPosition: 11, endPosition: 13, period: 1}
* @endcode
* @see unknownValue
* @see Repeat
*/
// TODO(holtgrew): minRepeatLength is 1-off.
// period-1 optimization
template <typename TRepeatStore, typename TString, typename TRepeatSize>
inline void findRepeats(TRepeatStore &repString, TString const &text, TRepeatSize minRepeatLen)
{
typedef typename Value<TRepeatStore>::Type TRepeat;
typedef typename Iterator<TString const>::Type TIterator;
typedef typename Size<TString>::Type TSize;
#if SEQAN_ENABLE_PARALLELISM
typedef typename Value<TString>::Type TValue;
if (length(text) > (TSize)(omp_get_max_threads() * 2 * minRepeatLen)) {
// std::cerr << ">>> PARALLEL WABOOGIE!" << std::endl;
// std::cerr << "omp_get_max_threads() == " << omp_get_max_threads() << std::endl;
// Parallel case.
// NOTE(holtgrew): The minimum text length check above makes it impossible that more than two chunks are
// required to form an otherwise too short repeat.
// TODO(holtgrew): Load balancing? Probably not worth it.
String<TSize> splitters;
String<TRepeatStore> threadLocalStores;
// Each threads finds repeats on its chunk in parallel.
#pragma omp parallel
{
// We have to determine the number of available threads at this point. We will use the number of thread
// local stores to determin the number of available threads later on.
#pragma omp master
{
// std::cerr << "omp_get_num_threads() == " << omp_get_num_threads() << std::endl;
computeSplitters(splitters, length(text), omp_get_num_threads());
resize(threadLocalStores, omp_get_num_threads());
} // end of #pragma omp master
#pragma omp barrier
int const t = omp_get_thread_num();
TRepeatStore & store = threadLocalStores[t];
TRepeat rep;
rep.beginPosition = 0;
rep.endPosition = 0;
rep.period = 1;
// Flags used for force-adding repeats for the chunks that have a left/right neighbour.
bool forceFirst = t > 0;
bool forceLast = (t + 1) < omp_get_num_threads();
// #pragma omp critical
// std::cerr << "omp_get_num_threads() == " << omp_get_num_threads() << std::endl;
TIterator it = iter(text, splitters[t], Standard());
TIterator itEnd = iter(text, splitters[t + 1], Standard());
if (it != itEnd)
{
TValue last = *it;
TSize repLeft = 0;
TSize repRight = 1;
for (++it; it != itEnd; ++it, ++repRight)
{
if (*it != last)
{
// #pragma omp critical
// std::cerr << "t == " << t << ", last == " << last << ", repRight = " << repRight << ", repLeft == " << repLeft << ", minRepeatLen = " << minRepeatLen << ", forceFirst = " << forceFirst << std::endl;
if (_repeatMaskValue(last) || (TRepeatSize)(repRight - repLeft) > minRepeatLen || forceFirst)
{
forceFirst = false;
// insert repeat
rep.beginPosition = splitters[t] + repLeft;
rep.endPosition = splitters[t] + repRight;
// #pragma omp critical
// std::cerr << " t == " << t << ", append" << std::endl;
appendValue(store, rep);
}
repLeft = repRight;
last = *it;
}
}
// #pragma omp critical
// std::cerr << "t == " << t << ", last == " << last << ", repRight = " << repRight << ", repLeft == " << repLeft << ", minRepeatLen = " << minRepeatLen << ", forceLast = " << forceLast << std::endl;
if (_repeatMaskValue(last) || (TRepeatSize)(repRight - repLeft) > minRepeatLen || forceLast)
{
// Insert repeat but only if it is not already in there.
if (empty(store) || (back(store).beginPosition != repLeft && back(store).endPosition != repRight))
{
rep.beginPosition = splitters[t] + repLeft;
rep.endPosition = splitters[t] + repRight;
// #pragma omp critical
// std::cerr << " t == " << t << ", append" << std::endl;
appendValue(store, rep);
}
}
}
} // end of #pragma omp parallel
// std::cerr << ",-- REPEATS BEFORE MENDING\n";
// for (unsigned i = 0; i < length(threadLocalStores); ++i)
// {
// std::cerr << "| i = " << i << std::endl;
// for (unsigned j = 0; j < length(threadLocalStores[i]); ++j)
// std::cerr << "| threadLocalStores[" << i << "][" << j << "] == {" << threadLocalStores[i][j].beginPosition << ", " << threadLocalStores[i][j].endPosition << "}" << std::endl;
// }
// std::cerr << "`--" << std::endl;
// Mend the splice points.
//
// We will copy out infixes described by fromPositions.
String<Pair<TSize> > fromPositions;
resize(fromPositions, length(threadLocalStores));
for (unsigned i = 0; i < length(fromPositions); ++i)
{
fromPositions[i].i1 = 0;
fromPositions[i].i2 = length(threadLocalStores[i]);
}
// First, merge repeats spanning blocks. Do this iteratively until all has been merged.
bool anyChange;
do
{
anyChange = false;
int lastNonEmpty = -1;
for (unsigned i = 0; i < length(threadLocalStores); ++i)
{
if (fromPositions[i].i1 == fromPositions[i].i2)
continue; // Skip empty buckets.
if (lastNonEmpty != -1)
{
bool const adjacent = back(threadLocalStores[lastNonEmpty]).endPosition == front(threadLocalStores[i]).beginPosition;
bool const charsEqual = text[back(threadLocalStores[lastNonEmpty]).beginPosition] == text[front(threadLocalStores[i]).beginPosition];
if (adjacent && charsEqual)
{
anyChange = true;
back(threadLocalStores[lastNonEmpty]).endPosition = front(threadLocalStores[i]).endPosition;
fromPositions[i].i1 += 1;
}
}
if (fromPositions[i].i1 != fromPositions[i].i2)
lastNonEmpty = i;
}
}
while (anyChange);
// Then, remove any repeats in the beginning and end of blocks that are too short.
for (unsigned i = 0; i < length(threadLocalStores); ++i)
{
if (fromPositions[i].i1 == fromPositions[i].i2)
continue;
unsigned j = fromPositions[i].i1;
TRepeatSize len = threadLocalStores[i][j].endPosition - threadLocalStores[i][j].beginPosition;
if (!_repeatMaskValue(text[threadLocalStores[i][j].beginPosition]) && // Never remove mask value.
len <= minRepeatLen)
fromPositions[i].i1 += 1;
if (fromPositions[i].i1 == fromPositions[i].i2)
continue;
j = fromPositions[i].i2 - 1;
len = threadLocalStores[i][j].endPosition - threadLocalStores[i][j].beginPosition;
if (!_repeatMaskValue(text[threadLocalStores[i][j].beginPosition]) && // Never remove mask value.
len <= minRepeatLen)
fromPositions[i].i2 -= 1;
}
// Last, build splitters for output in parallel.
String<unsigned> outSplitters;
appendValue(outSplitters, 0);
for (unsigned i = 0; i < length(threadLocalStores); ++i)
appendValue(outSplitters, back(outSplitters) + fromPositions[i].i2 - fromPositions[i].i1);
// std::cerr << ",-- REPEATS AFTER MENDING\n";
// for (unsigned i = 0; i < length(threadLocalStores); ++i)
// {
// std::cerr << "| i = " << i << std::endl;
// std::cerr << "`--, fromPositions[" << i << "] = (" << fromPositions[i].i1 << ", " << fromPositions[i].i2 << std::endl;
// for (unsigned j = 0; j < length(threadLocalStores[i]); ++j)
// std::cerr << " | threadLocalStores[" << i << "][" << j << "] == {" << threadLocalStores[i][j].beginPosition << ", " << threadLocalStores[i][j].endPosition << "}" << std::endl;
// }
// std::cerr << " `--" << std::endl;
// Allocate memory.
clear(repString);
resize(repString, back(outSplitters));
// Copy back the repeats in parallel.
unsigned nt = length(threadLocalStores);
(void) nt; // Otherwise, GCC 4.6 warns, does not see it used in pragma clause below.
#pragma omp parallel num_threads(nt)
{
int const t = omp_get_thread_num();
arrayCopy(iter(threadLocalStores[t], fromPositions[t].i1, Standard()),
iter(threadLocalStores[t], fromPositions[t].i2, Standard()),
iter(repString, outSplitters[t], Standard()));
} // end of #pragma omp parallel
} else {
#endif // #if SEQAN_ENABLE_PARALLELISM
// Sequential case.
TRepeat rep;
rep.period = 1;
clear(repString);
TIterator it = begin(text, Standard());
TIterator itEnd = end(text, Standard());
if (it == itEnd) return;
TSize repLen = 1;
for (++it; it != itEnd; ++it)
{
if (*it != *(it-1))
{
if (_repeatMaskValue(*(it-1)) || repLen > (TSize)minRepeatLen)
{
// insert repeat
rep.endPosition = it - begin(text, Standard());
rep.beginPosition = rep.endPosition - repLen;
// ::std::cerr<<"left:"<<rep.beginPosition<<" right:"<<rep.endPosition<<" length:"<<posSub(rep.endPosition,rep.beginPosition)<<" period:"<<rep.period<<::std::endl;
appendValue(repString, rep);
}
repLen = 1;
} else
++repLen;
}
if (_repeatMaskValue(*(it-1)) || repLen > (TSize)minRepeatLen)
{
// insert repeat
rep.endPosition = length(text);
rep.beginPosition = rep.endPosition - repLen;
// ::std::cerr<<"left:"<<rep.beginPosition<<" right:"<<rep.endPosition<<" length:"<<posSub(rep.endPosition,rep.beginPosition)<<" period:"<<rep.period<<::std::endl;
appendValue(repString, rep);
}
#if SEQAN_ENABLE_PARALLELISM
}
#endif // #if SEQAN_ENABLE_PARALLELISM
// #pragma omp critical
// {
// std::cerr << "thread #" << omp_get_thread_num() << " REPEATS:";
// for (unsigned i = 0; i < length(repString); ++i) {
// std::cerr << " (" << repString[i].beginPosition << ", " << repString[i].endPosition << ", " << repString[i].period << ")";
// }
// std::cerr << std::endl;
// }
}
// TODO(holtgrew): Why for TString const and StringSet<> const?
template <typename TRepeatStore, typename TString, typename TSpec, typename TRepeatSize>
inline void findRepeats(TRepeatStore &repString, StringSet<TString, TSpec> const &text, TRepeatSize minRepeatLen)
{
typedef typename Value<TRepeatStore>::Type TRepeat;
typedef typename Iterator<TString>::Type TIterator;
typedef typename Value<TString>::Type TValue;
typedef typename Size<TString>::Type TSize;
TRepeat rep;
rep.period = 1;
clear(repString);
for (unsigned i = 0; i < length(text); ++i)
{
TIterator it = begin(text[i], Standard());
TIterator itEnd = end(text[i], Standard());
if (it == itEnd) continue;
TValue last = *it;
TSize repLeft = 0;
TSize repRight = 1;
rep.beginPosition.i1 = i;
rep.endPosition.i1 = i;
for (++it; it != itEnd; ++it, ++repRight)
{
if (last != *it)
{
if (_repeatMaskValue(last) || (TRepeatSize)(repRight - repLeft) > minRepeatLen)
{
// insert repeat
rep.beginPosition.i2 = repLeft;
rep.endPosition.i2 = repRight;
// ::std::cerr<<"left:"<<rep.beginPosition<<" right:"<<rep.endPosition<<" length:"<<posSub(rep.endPosition,rep.beginPosition)<<" period:"<<rep.period<<::std::endl;
appendValue(repString, rep);
}
repLeft = repRight;
last = *it;
}
}
if (_repeatMaskValue(last) || (TRepeatSize)(repRight - repLeft) > minRepeatLen)
{
// insert repeat
rep.beginPosition.i2 = repLeft;
rep.endPosition.i2 = repRight;
// ::std::cerr<<"left:"<<rep.beginPosition<<" right:"<<rep.endPosition<<" length:"<<posSub(rep.endPosition,rep.beginPosition)<<" period:"<<rep.period<<::std::endl;
appendValue(repString, rep);
}
}
}
// main function
template <typename TRepeatStore, typename TText, typename TRepeatSize, typename TPeriodSize>
void findRepeats(TRepeatStore &repString, TText const &text, TRepeatSize minRepeatLen, TPeriodSize maxPeriod)
{
typedef Index<TText, IndexWotd<TRepeatFinder> > TIndex;
typedef typename Size<TIndex>::Type TSize;
typedef typename Iterator<TIndex, TopDown<ParentLinks<> > >::Type TNodeIterator;
typedef typename Fibre<TIndex, FibreSA>::Type const TSA;
typedef typename Infix<TSA>::Type TOccString;
typedef typename Iterator<TOccString>::Type TOccIterator;
typedef typename Value<TRepeatStore>::Type TRepeat;
typedef typename Value<TOccString>::Type TOcc;
typedef ::std::map<TOcc,TRepeat,RepeatLess_<TOcc> > TRepeatList;
if (maxPeriod < 1) return;
if (maxPeriod == 1)
{
findRepeats(repString, text, minRepeatLen);
return;
}
TIndex index(text);
TRepeatList list;
// set repeat finder parameters
cargo(index).minRepeatLen = minRepeatLen;
cargo(index).maxPeriod = maxPeriod;
TNodeIterator nodeIt(index);
TOccIterator itA, itB, itRepBegin, itEnd;
TRepeat rep;
for (; !atEnd(nodeIt); goNext(nodeIt))
{
if (isRoot(nodeIt)) continue;
// get occurrences
TOccString occ = getOccurrences(nodeIt);
itA = begin(occ, Standard());
itEnd = end(occ, Standard());
itRepBegin = itB = itA;
TSize repLen = repLength(nodeIt); // representative length
if ((TSize)minRepeatLen <= repLen) continue;
TSize diff, period = 0; // period of current repeat
TSize repeatLen = 0; // overall length of current repeat
TSize minLen = minRepeatLen - repLen; // minimum repeat length minus length of representative
for (++itB; itB != itEnd; ++itB)
{
diff = posSub(*itB, *itA);
if (diff != period || getSeqNo(*itA) != getSeqNo(*itB))
{
// is the repeat long enough?
if (repeatLen >= minLen)
// is the repeat self overlapping or connected?
if (parentRepLength(nodeIt) < period && period <= repLen)
{
// insert repeat
rep.beginPosition = *itRepBegin;
rep.endPosition = posAdd(*itA, period);
rep.period = period;
// ::std::cerr<<"left:"<<rep.beginPosition<<" right:"<<rep.endPosition<<" length:"<<posSub(rep.endPosition,rep.beginPosition)<<" period:"<<rep.period<<::std::endl;
list.insert(::std::pair<TOcc,TRepeat>(rep.beginPosition, rep));
}
itRepBegin = itA;
period = diff;
repeatLen = 0;
}
repeatLen += period;
itA = itB;
}
// is the last repeat long enough?
if (repeatLen >= minLen)
// is the repeat self overlapping or connected?
if (parentRepLength(nodeIt) < period && period <= repLen)
{
// insert repeat
rep.beginPosition = *itRepBegin;
rep.endPosition = posAdd(*itA, period);
rep.period = period;
// ::std::cerr<<"left:"<<rep.beginPosition<<" right:"<<rep.endPosition<<" length:"<<posSub(rep.endPosition,rep.beginPosition)<<" period:"<<rep.period<<::std::endl;
list.insert(::std::pair<TOcc,TRepeat>(rep.beginPosition, rep));
}
}
// copy low-complex regions to result string
clear(repString);
reserve(repString, list.size(), Exact());
typename TRepeatList::const_iterator lit = list.begin();
typename TRepeatList::const_iterator litEnd = list.end();
for (TSize i = 0; lit != litEnd; ++lit, ++i)
appendValue(repString, (*lit).second);
}
} // namespace seqan
#endif
|
mpy_lowlevel_strided_loops.h | #ifndef __MPY_LOWLEVEL_STRIDED_LOOPS_H
#define __MPY_LOWLEVEL_STRIDED_LOOPS_H
#include <npy_config.h>
/*
* This function pointer is for unary operations that input an
* arbitrarily strided one-dimensional array segment and output
* an arbitrarily strided array segment of the same size.
* It may be a fully general function, or a specialized function
* when the strides or item size have particular known values.
*
* Examples of unary operations are a straight copy, a byte-swap,
* and a casting operation,
*
* The 'transferdata' parameter is slightly special, following a
* generic auxiliary data pattern defined in ndarraytypes.h
* Use NPY_AUXDATA_CLONE and NPY_AUXDATA_FREE to deal with this data.
*
*/
typedef void (PyMicArray_StridedUnaryOp)(void *dst, npy_intp dst_stride,
void *src, npy_intp src_stride,
npy_intp N, npy_intp src_itemsize,
NpyAuxData *transferdata, int device);
/*
* This is for pointers to functions which behave exactly as
* for PyArray_StridedUnaryOp, but with an additional mask controlling
* which values are transformed.
*
* In particular, the 'i'-th element is operated on if and only if
* mask[i*mask_stride] is true.
*/
typedef void (PyMicArray_MaskedStridedUnaryOp)(void *dst, npy_intp dst_stride,
void *src, npy_intp src_stride,
npy_bool *mask, npy_intp mask_stride,
npy_intp N, npy_intp src_itemsize,
NpyAuxData *transferdata, int device);
/*
* Gives back a function pointer to a specialized function for copying
* strided memory. Returns NULL if there is a problem with the inputs.
*
* aligned:
* Should be 1 if the src and dst pointers are always aligned,
* 0 otherwise.
* src_stride:
* Should be the src stride if it will always be the same,
* NPY_MAX_INTP otherwise.
* dst_stride:
* Should be the dst stride if it will always be the same,
* NPY_MAX_INTP otherwise.
* itemsize:
* Should be the item size if it will always be the same, 0 otherwise.
*
*/
NPY_NO_EXPORT PyMicArray_StridedUnaryOp *
PyMicArray_GetStridedCopyFn(int aligned,
npy_intp src_stride, npy_intp dst_stride,
npy_intp itemsize);
/*
* Gives back a function pointer to a specialized function for copying
* and swapping strided memory. This assumes each element is a single
* value to be swapped.
*
* For information on the 'aligned', 'src_stride' and 'dst_stride' parameters
* see above.
*
* Parameters are as for PyArray_GetStridedCopyFn.
*/
NPY_NO_EXPORT PyMicArray_StridedUnaryOp *
PyMicArray_GetStridedCopySwapFn(int aligned,
npy_intp src_stride, npy_intp dst_stride,
npy_intp itemsize);
/*
* Gives back a function pointer to a specialized function for copying
* and swapping strided memory. This assumes each element is a pair
* of values, each of which needs to be swapped.
*
* For information on the 'aligned', 'src_stride' and 'dst_stride' parameters
* see above.
*
* Parameters are as for PyArray_GetStridedCopyFn.
*/
NPY_NO_EXPORT PyMicArray_StridedUnaryOp *
PyMicArray_GetStridedCopySwapPairFn(int aligned,
npy_intp src_stride, npy_intp dst_stride,
npy_intp itemsize);
/*
* Gives back a transfer function and transfer data pair which copies
* the data from source to dest, truncating it if the data doesn't
* fit, and padding with zero bytes if there's too much space.
*
* For information on the 'aligned', 'src_stride' and 'dst_stride' parameters
* see above.
*
* Returns NPY_SUCCEED or NPY_FAIL
*/
/*NPY_NO_EXPORT int
PyMicArray_GetStridedZeroPadCopyFn(int aligned, int unicode_swap,
npy_intp src_stride, npy_intp dst_stride,
npy_intp src_itemsize, npy_intp dst_itemsize,
PyMicArray_StridedUnaryOp **outstransfer,
NpyAuxData **outtransferdata);*/
/*
* For casts between built-in numeric types,
* this produces a function pointer for casting from src_type_num
* to dst_type_num. If a conversion is unsupported, returns NULL
* without setting a Python exception.
*/
NPY_NO_EXPORT PyMicArray_StridedUnaryOp *
PyMicArray_GetStridedNumericCastFn(int aligned,
npy_intp src_stride, npy_intp dst_stride,
int src_type_num, int dst_type_num);
/*
* These two functions copy or convert the data of an n-dimensional array
* to/from a 1-dimensional strided buffer. These functions will only call
* 'stransfer' with the provided dst_stride/src_stride and
* dst_strides[0]/src_strides[0], so the caller can use those values to
* specialize the function.
* Note that even if ndim == 0, everything needs to be set as if ndim == 1.
*
* The return value is the number of elements it couldn't copy. A return value
* of 0 means all elements were copied, a larger value means the end of
* the n-dimensional array was reached before 'count' elements were copied.
*
* ndim:
* The number of dimensions of the n-dimensional array.
* dst/src/mask:
* The destination, source or mask starting pointer.
* dst_stride/src_stride/mask_stride:
* The stride of the 1-dimensional strided buffer
* dst_strides/src_strides:
* The strides of the n-dimensional array.
* dst_strides_inc/src_strides_inc:
* How much to add to the ..._strides pointer to get to the next stride.
* coords:
* The starting coordinates in the n-dimensional array.
* coords_inc:
* How much to add to the coords pointer to get to the next coordinate.
* shape:
* The shape of the n-dimensional array.
* shape_inc:
* How much to add to the shape pointer to get to the next shape entry.
* count:
* How many elements to transfer
* src_itemsize:
* How big each element is. If transferring between elements of different
* sizes, for example a casting operation, the 'stransfer' function
* should be specialized for that, in which case 'stransfer' will use
* this parameter as the source item size.
* stransfer:
* The strided transfer function.
* transferdata:
* An auxiliary data pointer passed to the strided transfer function.
* This follows the conventions of NpyAuxData objects.
*/
NPY_NO_EXPORT npy_intp
PyMicArray_TransferNDimToStrided(npy_intp ndim,
char *dst, npy_intp dst_stride,
char *src, npy_intp *src_strides, npy_intp src_strides_inc,
npy_intp *coords, npy_intp coords_inc,
npy_intp *shape, npy_intp shape_inc,
npy_intp count, npy_intp src_itemsize,
PyMicArray_StridedUnaryOp *stransfer,
NpyAuxData *transferdata, int transferdevice);
NPY_NO_EXPORT npy_intp
PyMicArray_TransferStridedToNDim(npy_intp ndim,
char *dst, npy_intp *dst_strides, npy_intp dst_strides_inc,
char *src, npy_intp src_stride,
npy_intp *coords, npy_intp coords_inc,
npy_intp *shape, npy_intp shape_inc,
npy_intp count, npy_intp src_itemsize,
PyMicArray_StridedUnaryOp *stransfer,
NpyAuxData *transferdata, int transferdevice);
NPY_NO_EXPORT npy_intp
PyMicArray_TransferMaskedStridedToNDim(npy_intp ndim,
char *dst, npy_intp *dst_strides, npy_intp dst_strides_inc,
char *src, npy_intp src_stride,
npy_bool *mask, npy_intp mask_stride,
npy_intp *coords, npy_intp coords_inc,
npy_intp *shape, npy_intp shape_inc,
npy_intp count, npy_intp src_itemsize,
PyMicArray_MaskedStridedUnaryOp *stransfer,
NpyAuxData *transferdata, int transferdevice);
#pragma omp declare target
/*
* Return number of elements that must be peeled from
* the start of 'addr' with 'nvals' elements of size 'esize'
* in order to reach 'alignment'.
* alignment must be a power of two.
* see npy_blocked_end for an example
*/
static NPY_INLINE npy_uintp
mpy_aligned_block_offset(const void * addr, const npy_uintp esize,
const npy_uintp alignment, const npy_uintp nvals)
{
const npy_uintp offset = (npy_uintp)addr & (alignment - 1);
npy_uintp peel = offset ? (alignment - offset) / esize : 0;
peel = nvals < peel ? nvals : peel;
return peel;
}
/*
* Return upper loop bound for an array of 'nvals' elements
* of size 'esize' peeled by 'offset' elements and blocking to
* a vector size of 'vsz' in bytes
*
* example usage:
* npy_intp i;
* double v[101];
* npy_intp esize = sizeof(v[0]);
* npy_intp peel = npy_aligned_block_offset(v, esize, 16, n);
* // peel to alignment 16
* for (i = 0; i < peel; i++)
* <scalar-op>
* // simd vectorized operation
* for (; i < npy_blocked_end(peel, esize, 16, n); i += 16 / esize)
* <blocked-op>
* // handle scalar rest
* for(; i < n; i++)
* <scalar-op>
*/
static NPY_INLINE npy_uintp
mpy_blocked_end(const npy_uintp offset, const npy_uintp esize,
const npy_uintp vsz, const npy_uintp nvals)
{
return nvals - offset - (nvals - offset) % (vsz / esize);
}
/* byte swapping functions */
static NPY_INLINE npy_uint16
mpy_bswap2(npy_uint16 x)
{
return ((x & 0xffu) << 8) | (x >> 8);
}
/*
* treat as int16 and byteswap unaligned memory,
* some cpus don't support unaligned access
*/
static NPY_INLINE void
mpy_bswap2_unaligned(char * x)
{
char a = x[0];
x[0] = x[1];
x[1] = a;
}
static NPY_INLINE npy_uint32
mpy_bswap4(npy_uint32 x)
{
return __builtin_bswap32(x);
}
static NPY_INLINE void
mpy_bswap4_unaligned(char * x)
{
char a = x[0];
x[0] = x[3];
x[3] = a;
a = x[1];
x[1] = x[2];
x[2] = a;
}
static NPY_INLINE npy_uint64
mpy_bswap8(npy_uint64 x)
{
return __builtin_bswap64(x);
}
static NPY_INLINE void
mpy_bswap8_unaligned(char * x)
{
char a = x[0]; x[0] = x[7]; x[7] = a;
a = x[1]; x[1] = x[6]; x[6] = a;
a = x[2]; x[2] = x[5]; x[5] = a;
a = x[3]; x[3] = x[4]; x[4] = a;
}
#pragma omp end declare target
/* Start raw iteration */
#define NPY_RAW_ITER_START(idim, ndim, coord, shape) \
memset((coord), 0, (ndim) * sizeof(coord[0])); \
do {
/* Increment to the next n-dimensional coordinate for one raw array */
#define NPY_RAW_ITER_ONE_NEXT(idim, ndim, coord, shape, data, strides) \
for ((idim) = 1; (idim) < (ndim); ++(idim)) { \
if (++(coord)[idim] == (shape)[idim]) { \
(coord)[idim] = 0; \
(data) -= ((shape)[idim] - 1) * (strides)[idim]; \
} \
else { \
(data) += (strides)[idim]; \
break; \
} \
} \
} while ((idim) < (ndim))
/* Increment to the next n-dimensional coordinate for two raw arrays */
#define NPY_RAW_ITER_TWO_NEXT(idim, ndim, coord, shape, \
dataA, stridesA, dataB, stridesB) \
for ((idim) = 1; (idim) < (ndim); ++(idim)) { \
if (++(coord)[idim] == (shape)[idim]) { \
(coord)[idim] = 0; \
(dataA) -= ((shape)[idim] - 1) * (stridesA)[idim]; \
(dataB) -= ((shape)[idim] - 1) * (stridesB)[idim]; \
} \
else { \
(dataA) += (stridesA)[idim]; \
(dataB) += (stridesB)[idim]; \
break; \
} \
} \
} while ((idim) < (ndim))
/* Increment to the next n-dimensional coordinate for three raw arrays */
#define NPY_RAW_ITER_THREE_NEXT(idim, ndim, coord, shape, \
dataA, stridesA, \
dataB, stridesB, \
dataC, stridesC) \
for ((idim) = 1; (idim) < (ndim); ++(idim)) { \
if (++(coord)[idim] == (shape)[idim]) { \
(coord)[idim] = 0; \
(dataA) -= ((shape)[idim] - 1) * (stridesA)[idim]; \
(dataB) -= ((shape)[idim] - 1) * (stridesB)[idim]; \
(dataC) -= ((shape)[idim] - 1) * (stridesC)[idim]; \
} \
else { \
(dataA) += (stridesA)[idim]; \
(dataB) += (stridesB)[idim]; \
(dataC) += (stridesC)[idim]; \
break; \
} \
} \
} while ((idim) < (ndim))
/* Increment to the next n-dimensional coordinate for four raw arrays */
#define NPY_RAW_ITER_FOUR_NEXT(idim, ndim, coord, shape, \
dataA, stridesA, \
dataB, stridesB, \
dataC, stridesC, \
dataD, stridesD) \
for ((idim) = 1; (idim) < (ndim); ++(idim)) { \
if (++(coord)[idim] == (shape)[idim]) { \
(coord)[idim] = 0; \
(dataA) -= ((shape)[idim] - 1) * (stridesA)[idim]; \
(dataB) -= ((shape)[idim] - 1) * (stridesB)[idim]; \
(dataC) -= ((shape)[idim] - 1) * (stridesC)[idim]; \
(dataD) -= ((shape)[idim] - 1) * (stridesD)[idim]; \
} \
else { \
(dataA) += (stridesA)[idim]; \
(dataB) += (stridesB)[idim]; \
(dataC) += (stridesC)[idim]; \
(dataD) += (stridesD)[idim]; \
break; \
} \
} \
} while ((idim) < (ndim))
#endif |
diagmm_x_coo_u_col.c | #include "alphasparse/kernel.h"
#include "alphasparse/util.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 rowC = mat->rows;
ALPHA_INT colC = columns;
ALPHA_INT num_threads = alpha_get_thread_num();
#ifdef _OPENMP
#pragma omp parallel for num_threads(num_threads)
#endif
for (ALPHA_INT c = 0; c < colC; ++c)
{
for (ALPHA_INT r = 0; r < rowC; ++r)
{
ALPHA_Number t;
alpha_setzero(t);
alpha_mul(t, alpha, x[index2(c, r, ldx)]);
alpha_mul(y[index2(c, r, ldy)], beta, y[index2(c, r, ldy)]);
alpha_add(y[index2(c, r, ldy)], y[index2(c, r, ldy)], t);
}
}
return ALPHA_SPARSE_STATUS_SUCCESS;
}
|
GB_positional_op_ip.c | //------------------------------------------------------------------------------
// GB_positional_op_ip: C = positional_op (A), depending only on i
//------------------------------------------------------------------------------
// SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2021, All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
//------------------------------------------------------------------------------
// A can be jumbled. If A is jumbled, so is C.
{
//--------------------------------------------------------------------------
// Cx = positional_op (A)
//--------------------------------------------------------------------------
int64_t p ;
#pragma omp parallel for num_threads(nthreads) schedule(static)
for (p = 0 ; p < anz ; p++)
{
// GB_POSITION is either i or i+1
int64_t i = GBI (Ai, p, avlen) ;
Cx_int [p] = GB_POSITION ;
}
}
#undef GB_POSITION
|
pooling_layer.h | //Tencent is pleased to support the open source community by making FeatherCNN available.
//Copyright (C) 2018 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.
#pragma once
#include "../feather_simple_generated.h"
#include "../layer.h"
#include <math.h>
#include <limits>
#define MAX(a,b) ((a)>(b))?(a):(b)
#define MIN(a,b) ((a)<(b))?(a):(b)
namespace feather
{
void ave_pool_inner_kernel(float* out, const float* in, const size_t ldin, const size_t kernel_h, const size_t kernel_w)
{
float total = 0.0;
for (size_t m = 0; m != kernel_h; ++m)
{
for (size_t n = 0; n != kernel_w; ++n)
{
size_t pos = m * ldin + n;
total += in[pos];
}
}
*out = total / kernel_h / kernel_w;
}
void max_pool_inner_kernel(float* out, const float* in, const size_t ldin, const size_t kernel_h, const size_t kernel_w)
{
float max = 0.0;
for (size_t m = 0; m != kernel_h; ++m)
{
for (size_t n = 0; n != kernel_w; ++n)
{
size_t pos = m * ldin + n;
max = (in[pos] > max) ? in[pos] : max;
}
}
*out = max;
}
class PoolingLayer : public Layer
{
public:
PoolingLayer(const LayerParameter *layer_param, const RuntimeParameter<float>* rt_param)
: stride_height(1),
stride_width(1),
Layer(layer_param, rt_param)
{
const PoolingParameter *pooling_param = layer_param->pooling_param();
kernel_height = pooling_param->kernel_h();
kernel_width = pooling_param->kernel_w();
pad_height = pooling_param->pad_h();
pad_width = pooling_param->pad_w();
stride_height = pooling_param->stride_h();
stride_width = pooling_param->stride_w();
stride_height = (stride_height <= 0) ? 1 : stride_height;
stride_width = (stride_width <= 0) ? 1 : stride_width;
global_pooling = pooling_param->global_pooling();
this->method = pooling_param->pool();
switch(this->method)
{
case PoolingParameter_::PoolMethod_MAX_:
_pool_inner_kernel = max_pool_inner_kernel;
break;
case PoolingParameter_::PoolMethod_AVE:
_pool_inner_kernel = ave_pool_inner_kernel;
break;
default:
fprintf(stderr, "Unsupported pool method\n");
}
printf("kernel (%ld %ld) pad (%ld %ld) stride (%ld %ld) global_pooling %d\n",
kernel_height, kernel_width, pad_height, pad_width, stride_height, stride_width, global_pooling);
}
int Forward()
{
//fprintf(stderr, "pooling output (%d %d)\n", output_height, output_width);
//printf("input shape %ld %ld %ld kernel shape %ld %ld stride %ld %ld\n", input_channels, input_height, input_width, kernel_height, kernel_width, stride_height, stride_width);
const float *input = _bottom_blobs[_bottom[0]]->data();
float *output = _top_blobs[_top[0]]->data();
float *p = output;
int slot = input_channels*output_height;
#pragma omp parallel for schedule(static) num_threads(num_threads)
// for (int u=0;u<slot;u++)
// {
for (int i=0; i<input_channels; ++i)
{
for (int j=0; j<output_height; j ++)
{
// int i=slot/output_height, j=slot%output_height;
float *p = output + i*output_height*output_width + j*output_width;
for(int l=0; l<output_width; l++) p[l] = (this->method != PoolingParameter_::PoolMethod_MAX_?0:-1*std::numeric_limits<float>::max()) ;
int tmp_pos = j*(int)stride_height - (int)pad_height;
int x_min = MAX(tmp_pos, 0);
int x_max = MIN((int)(tmp_pos+kernel_height), (int) input_height);
for(int x=x_min; x<x_max; ++x)
{
int xpos = i * input_height * input_width + x*input_width;
for (int k = 0; k<output_width; k ++)
{
float total = (this->method != PoolingParameter_::PoolMethod_MAX_?0:-1*std::numeric_limits<float>::max());
int counter=0;
int local_pos = k*(int)stride_width - (int)pad_width;
int y_min = MAX(local_pos, 0);
int y_max = MIN((int)(local_pos + kernel_width), (int) input_width);
for (int y=y_min; y < y_max; ++y)
{
float value = input[xpos + y];
if(this->method != PoolingParameter_::PoolMethod_MAX_) total += value, counter++;
else total = total>value?total:value;
}
if(this->method != PoolingParameter_::PoolMethod_MAX_)
p[k] += total / (counter) / kernel_height;
else p[k] = (p[k]>total) ? p[k]:total;
}
}
}
}
/*
#if 0
f(0)
#else
if(this->method == PoolingParameter_::PoolMethod_MAX_)
#endif
{
float f_minimal = std::numeric_limits<float>::max();
f_minimal = -f_minimal;
//printf("minimal float %f\n", f_minimal);
//Init output
for(int i = 0; i < output_channels * output_height * output_width; ++i)
{
output[i] = f_minimal;
}
const size_t img_size = input_height * input_width;
#pragma omp parallel for num_threads(num_threads) collapse(3)
for (size_t i = 0; i < output_channels; ++i)
{
for (size_t j = 0; j < output_height; ++j)
{
for(size_t u = 0; u < kernel_height; ++u)
{
int row = j * stride_height + u - pad_height;
if(row < 0 || row >= input_height)
continue;
for (size_t k = 0; k < output_width; ++k)
{
float* out_ptr = output + i * output_height * output_width + j * output_width + k;
float max = *out_ptr;
for(size_t v = 0; v < kernel_width; ++v)
{
int col = k * stride_height + v - pad_width;
if(col < 0 || col >= input_width)
continue;
const float* in_ptr = input + i * img_size + row * input_width + col;
float data = *in_ptr;
max = (max > data) ? max : data;
}
*out_ptr = max;
}
}
}
}
}
else
{
for (size_t i = 0; i < output_channels; ++i)
{
for (size_t j = 0; j < output_height; ++j)
{
for (size_t k = 0; k < output_width; ++k)
{
#if 0
float total = 0.0;
for (size_t m = 0; m != kernel_height; ++m)
{
for (size_t n = 0; n != kernel_width; ++n)
{
size_t pos = i * input_height* input_width + (j + m)* input_width + k + n;
total += input[pos];
}
}
*p++ = total / (kernel_height * kernel_width);
#else
size_t border_h = input_height - j * stride_height + pad_height;
size_t border_w = input_width - k * stride_width + pad_width;
size_t kernel_h = (kernel_height < border_h) ? kernel_height : border_h;
size_t kernel_w = (kernel_width < border_w) ? kernel_width : border_w;
//printf("pool shape %ld %ld %ld %ld %ld %ld %d %d\n", kernel_h, kernel_w, output_height, output_width, border_h, border_w, j, k);
int row = j * stride_height - pad_height;
int col = k * stride_width - pad_width;
if(row < 0)
{
kernel_h = kernel_height + row;
row = 0;
}
if(col < 0)
{
kernel_w = kernel_width + col;
col = 0;
}
size_t pos = i * input_height * input_width + row * input_width + col;
_pool_inner_kernel(p, input + pos, input_width, kernel_h, kernel_w);
++p;
#endif
}
}
}
}
*/
return 0;
}
int GenerateTopBlobs()
{
//Only accept a single bottom blob.
const Blob<float> *bottom_blob = _bottom_blobs[_bottom[0]];
input_height = bottom_blob->height();
input_width = bottom_blob->width();
input_channels = bottom_blob->channels();
//printf("layer %s\n", _name.c_str());
//printf("input %lu %lu %lu\n", input_channels, input_height, input_width);
if (global_pooling)
{
kernel_height = input_height;
kernel_width = input_width;
output_height = 1;
output_width = 1;
output_channels = input_channels;
}
else
{
//General pooling.
output_channels = input_channels;
output_height = static_cast<int>(ceil(static_cast<float>(input_height + 2 * pad_height - kernel_height) / stride_height)) + 1;
output_width = static_cast<int>(ceil(static_cast<float>(input_width + 2 * pad_width - kernel_width) / stride_width)) + 1;
}
_top_blobs[_top[0]] = new Blob<float>(1, output_channels, output_height, output_width);
_top_blobs[_top[0]]->Alloc();
//_top_blobs[_top[0]]->PrintBlobInfo();
return 0;
}
private:
size_t input_height;
size_t input_width;
size_t input_channels;
size_t output_height;
size_t output_width;
size_t output_channels;
size_t pad_height;
size_t pad_width;
size_t kernel_height;
size_t kernel_width;
size_t stride_height;
size_t stride_width;
bool global_pooling;
PoolingParameter_::PoolMethod method;
void (*_pool_inner_kernel)(float* out, const float* in, const size_t ldin, const size_t kernel_h, const size_t kernel_w);
};
};
|
distribute-1.c | int s1, s2, s3, s4, s5, s6, s7, s8;
#pragma omp declare target (s1, s2, s3, s4, s5, s6, s7, s8)
void
f1 (void)
{
int i;
#pragma omp distribute
for (i = 0; i < 64; i++)
;
#pragma omp distribute private (i)
for (i = 0; i < 64; i++)
;
#pragma omp distribute
for (int j = 0; j < 64; j++)
;
#pragma omp distribute lastprivate (s1)
for (s1 = 0; s1 < 64; s1 += 2)
;
#pragma omp distribute lastprivate (s2)
for (i = 0; i < 64; i++)
s2 = 2 * i;
#pragma omp distribute simd
for (i = 0; i < 64; i++)
;
#pragma omp distribute simd lastprivate (s3, s4) collapse(2)
for (s3 = 0; s3 < 64; s3++)
for (s4 = 0; s4 < 3; s4++)
;
#pragma omp distribute parallel for
for (i = 0; i < 64; i++)
;
#pragma omp distribute parallel for private (i)
for (i = 0; i < 64; i++)
;
#pragma omp distribute parallel for lastprivate (s5)
for (s5 = 0; s5 < 64; s5++)
;
#pragma omp distribute firstprivate (s7) private (s8)
for (i = 0; i < 64; i++)
s8 = s7++;
}
void
f2 (void)
{
int i;
#pragma omp distribute lastprivate (i) /* { dg-error "lastprivate variable .i. is private in outer context" } */
for (i = 0; i < 64; i++)
;
#pragma omp distribute firstprivate (s6) lastprivate (s6) /* { dg-error "same variable used in .firstprivate. and .lastprivate. clauses on .distribute. construct" } */
for (i = 0; i < 64; i++)
s6 += i;
}
#pragma omp declare target to(f1, f2)
|
parallel_for_sum.c | #include <stdio.h>
int main(void){
int total = 0;
int n_iter = 1000000;
#pragma omp parallel for
for(int i=0; i<n_iter; i++){
total++;
}
printf("Value: %d", total);
return 0;
}
|
blackscholes.c | // Copyright (c) 2007 Intel Corp.
// Black-Scholes
// Analytical method for calculating European Options
//
//
// Reference Source: Options, Futures, and Other Derivatives, 3rd Edition, Prentice
// Hall, John C. Hull,
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <string.h>
#ifdef ENABLE_PARSEC_HOOKS
#include <hooks.h>
#endif
// Multi-threaded pthreads header
#ifdef ENABLE_THREADS
// Add the following line so that icc 9.0 is compatible with pthread lib.
#define __thread __threadp
MAIN_ENV
#undef __thread
#endif
// Multi-threaded OpenMP header
#ifdef ENABLE_OPENMP
#include <omp.h>
#endif
#ifdef ENABLE_TBB
#include "tbb/blocked_range.h"
#include "tbb/parallel_for.h"
#include "tbb/task_scheduler_init.h"
#include "tbb/tick_count.h"
using namespace std;
using namespace tbb;
#endif //ENABLE_TBB
// Multi-threaded header for Windows
#ifdef WIN32
#pragma warning(disable : 4305)
#pragma warning(disable : 4244)
#include <windows.h>
#endif
//Precision to use for calculations
#define fptype float
#define NUM_RUNS 100
typedef struct OptionData_ {
fptype s; // spot price
fptype strike; // strike price
fptype r; // risk-free interest rate
fptype divq; // dividend rate
fptype v; // volatility
fptype t; // time to maturity or option expiration in years
// (1yr = 1.0, 6mos = 0.5, 3mos = 0.25, ..., etc)
char OptionType; // Option type. "P"=PUT, "C"=CALL
fptype divs; // dividend vals (not used in this test)
fptype DGrefval; // DerivaGem Reference Value
} OptionData;
OptionData *data;
fptype *prices;
int numOptions;
int * otype;
fptype * sptprice;
fptype * strike;
fptype * rate;
fptype * volatility;
fptype * otime;
int numErrors = 0;
int nThreads;
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
// Cumulative Normal Distribution Function
// See Hull, Section 11.8, P.243-244
#define inv_sqrt_2xPI 0.39894228040143270286
fptype CNDF ( fptype InputX )
{
int sign;
fptype OutputX;
fptype xInput;
fptype xNPrimeofX;
fptype expValues;
fptype xK2;
fptype xK2_2, xK2_3;
fptype xK2_4, xK2_5;
fptype xLocal, xLocal_1;
fptype xLocal_2, xLocal_3;
// Check for negative value of InputX
if (InputX < 0.0) {
InputX = -InputX;
sign = 1;
} else
sign = 0;
xInput = InputX;
// Compute NPrimeX term common to both four & six decimal accuracy calcs
expValues = exp(-0.5f * InputX * InputX);
xNPrimeofX = expValues;
xNPrimeofX = xNPrimeofX * inv_sqrt_2xPI;
xK2 = 0.2316419 * xInput;
xK2 = 1.0 + xK2;
xK2 = 1.0 / xK2;
xK2_2 = xK2 * xK2;
xK2_3 = xK2_2 * xK2;
xK2_4 = xK2_3 * xK2;
xK2_5 = xK2_4 * xK2;
xLocal_1 = xK2 * 0.319381530;
xLocal_2 = xK2_2 * (-0.356563782);
xLocal_3 = xK2_3 * 1.781477937;
xLocal_2 = xLocal_2 + xLocal_3;
xLocal_3 = xK2_4 * (-1.821255978);
xLocal_2 = xLocal_2 + xLocal_3;
xLocal_3 = xK2_5 * 1.330274429;
xLocal_2 = xLocal_2 + xLocal_3;
xLocal_1 = xLocal_2 + xLocal_1;
xLocal = xLocal_1 * xNPrimeofX;
xLocal = 1.0 - xLocal;
OutputX = xLocal;
if (sign) {
OutputX = 1.0 - OutputX;
}
return OutputX;
}
//////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////
fptype BlkSchlsEqEuroNoDiv( fptype sptprice,
fptype strike, fptype rate, fptype volatility,
fptype time, int otype, float timet )
{
fptype OptionPrice;
// local private working variables for the calculation
fptype xStockPrice;
fptype xStrikePrice;
fptype xRiskFreeRate;
fptype xVolatility;
fptype xTime;
fptype xSqrtTime;
fptype logValues;
fptype xLogTerm;
fptype xD1;
fptype xD2;
fptype xPowerTerm;
fptype xDen;
fptype d1;
fptype d2;
fptype FutureValueX;
fptype NofXd1;
fptype NofXd2;
fptype NegNofXd1;
fptype NegNofXd2;
xStockPrice = sptprice;
xStrikePrice = strike;
xRiskFreeRate = rate;
xVolatility = volatility;
xTime = time;
xSqrtTime = sqrt(xTime);
logValues = log( sptprice / strike );
xLogTerm = logValues;
xPowerTerm = xVolatility * xVolatility;
xPowerTerm = xPowerTerm * 0.5;
xD1 = xRiskFreeRate + xPowerTerm;
xD1 = xD1 * xTime;
xD1 = xD1 + xLogTerm;
xDen = xVolatility * xSqrtTime;
xD1 = xD1 / xDen;
xD2 = xD1 - xDen;
d1 = xD1;
d2 = xD2;
NofXd1 = CNDF( d1 );
NofXd2 = CNDF( d2 );
FutureValueX = strike * ( exp( -(rate)*(time) ) );
if (otype == 0) {
OptionPrice = (sptprice * NofXd1) - (FutureValueX * NofXd2);
} else {
NegNofXd1 = (1.0 - NofXd1);
NegNofXd2 = (1.0 - NofXd2);
OptionPrice = (FutureValueX * NegNofXd2) - (sptprice * NegNofXd1);
}
return OptionPrice;
}
#ifdef ENABLE_TBB
struct mainWork {
mainWork() {}
mainWork(mainWork &w, tbb::split) {}
void operator()(const tbb::blocked_range<int> &range) const {
fptype price;
int begin = range.begin();
int end = range.end();
for (int i=begin; i!=end; i++) {
/* Calling main function to calculate option value based on
* Black & Scholes's equation.
*/
price = BlkSchlsEqEuroNoDiv( sptprice[i], strike[i],
rate[i], volatility[i], otime[i],
otype[i], 0);
prices[i] = price;
#ifdef ERR_CHK
fptype priceDelta = data[i].DGrefval - price;
if( fabs(priceDelta) >= 1e-5 ){
fprintf(stderr,"Error on %d. Computed=%.5f, Ref=%.5f, Delta=%.5f\n",
i, price, data[i].DGrefval, priceDelta);
numError ++;
}
#endif
}
}
};
#endif // ENABLE_TBB
//////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////
#ifdef ENABLE_TBB
int bs_thread(void *tid_ptr) {
int j;
tbb::affinity_partitioner a;
mainWork doall;
for (j=0; j<NUM_RUNS; j++) {
tbb::parallel_for(tbb::blocked_range<int>(0, numOptions), doall, a);
}
return 0;
}
#else // !ENABLE_TBB
#ifdef WIN32
DWORD WINAPI bs_thread(LPVOID tid_ptr){
#else
int bs_thread(void *tid_ptr) {
#endif
int i, j;
fptype price;
fptype priceDelta;
int tid = *(int *)tid_ptr;
int start = tid * (numOptions / nThreads);
int end = start + (numOptions / nThreads);
for (j=0; j<NUM_RUNS; j++) {
#ifdef ENABLE_OPENMP
#pragma omp parallel for private(i, price, priceDelta)
for (i=0; i<numOptions; i++) {
#else //ENABLE_OPENMP
for (i=start; i<end; i++) {
#endif //ENABLE_OPENMP
/* Calling main function to calculate option value based on
* Black & Scholes's equation.
*/
price = BlkSchlsEqEuroNoDiv( sptprice[i], strike[i],
rate[i], volatility[i], otime[i],
otype[i], 0);
prices[i] = price;
#ifdef ERR_CHK
priceDelta = data[i].DGrefval - price;
if( fabs(priceDelta) >= 1e-4 ){
printf("Error on %d. Computed=%.5f, Ref=%.5f, Delta=%.5f\n",
i, price, data[i].DGrefval, priceDelta);
numError ++;
}
#endif
}
}
return 0;
}
#endif //ENABLE_TBB
int main (int argc, char **argv)
{
FILE *file;
int i;
int loopnum;
fptype * buffer;
int * buffer2;
int rv;
#ifdef PARSEC_VERSION
#define __PARSEC_STRING(x) #x
#define __PARSEC_XSTRING(x) __PARSEC_STRING(x)
printf("PARSEC Benchmark Suite Version "__PARSEC_XSTRING(PARSEC_VERSION)"\n");
fflush(NULL);
#else
printf("PARSEC Benchmark Suite\n");
fflush(NULL);
#endif //PARSEC_VERSION
#ifdef ENABLE_PARSEC_HOOKS
__parsec_bench_begin(__parsec_blackscholes);
#endif
if (argc != 4)
{
printf("Usage:\n\t%s <nthreads> <inputFile> <outputFile>\n", argv[0]);
exit(1);
}
nThreads = atoi(argv[1]);
char *inputFile = argv[2];
char *outputFile = argv[3];
//Read input data from file
file = fopen(inputFile, "r");
if(file == NULL) {
printf("ERROR: Unable to open file `%s'.\n", inputFile);
exit(1);
}
rv = fscanf(file, "%i", &numOptions);
if(rv != 1) {
printf("ERROR: Unable to read from file `%s'.\n", inputFile);
fclose(file);
exit(1);
}
if(nThreads > numOptions) {
printf("WARNING: Not enough work, reducing number of threads to match number of options.\n");
nThreads = numOptions;
}
#if !defined(ENABLE_THREADS) && !defined(ENABLE_OPENMP) && !defined(ENABLE_TBB)
if(nThreads != 1) {
printf("Error: <nthreads> must be 1 (serial version)\n");
exit(1);
}
#endif
// alloc spaces for the option data
data = (OptionData*)malloc(numOptions*sizeof(OptionData));
prices = (fptype*)malloc(numOptions*sizeof(fptype));
for ( loopnum = 0; loopnum < numOptions; ++ loopnum )
{
rv = fscanf(file, "%f %f %f %f %f %f %c %f %f", &data[loopnum].s, &data[loopnum].strike, &data[loopnum].r, &data[loopnum].divq, &data[loopnum].v, &data[loopnum].t, &data[loopnum].OptionType, &data[loopnum].divs, &data[loopnum].DGrefval);
if(rv != 9) {
printf("ERROR: Unable to read from file `%s'.\n", inputFile);
fclose(file);
exit(1);
}
}
rv = fclose(file);
if(rv != 0) {
printf("ERROR: Unable to close file `%s'.\n", inputFile);
exit(1);
}
#ifdef ENABLE_THREADS
MAIN_INITENV(,8000000,nThreads);
#endif
printf("Num of Options: %d\n", numOptions);
printf("Num of Runs: %d\n", NUM_RUNS);
#define PAD 256
#define LINESIZE 64
buffer = (fptype *) malloc(5 * numOptions * sizeof(fptype) + PAD);
sptprice = (fptype *) (((unsigned long long)buffer + PAD) & ~(LINESIZE - 1));
strike = sptprice + numOptions;
rate = strike + numOptions;
volatility = rate + numOptions;
otime = volatility + numOptions;
buffer2 = (int *) malloc(numOptions * sizeof(fptype) + PAD);
otype = (int *) (((unsigned long long)buffer2 + PAD) & ~(LINESIZE - 1));
for (i=0; i<numOptions; i++) {
otype[i] = (data[i].OptionType == 'P') ? 1 : 0;
sptprice[i] = data[i].s;
strike[i] = data[i].strike;
rate[i] = data[i].r;
volatility[i] = data[i].v;
otime[i] = data[i].t;
}
printf("Size of data: %d\n", numOptions * (sizeof(OptionData) + sizeof(int)));
#ifdef ENABLE_PARSEC_HOOKS
__parsec_roi_begin();
#endif
#ifdef ENABLE_THREADS
#ifdef WIN32
HANDLE *threads;
int *nums;
threads = (HANDLE *) malloc (nThreads * sizeof(HANDLE));
nums = (int *) malloc (nThreads * sizeof(int));
for(i=0; i<nThreads; i++) {
nums[i] = i;
threads[i] = CreateThread(0, 0, bs_thread, &nums[i], 0, 0);
}
WaitForMultipleObjects(nThreads, threads, TRUE, INFINITE);
free(threads);
free(nums);
#else
int *tids;
tids = (int *) malloc (nThreads * sizeof(int));
for(i=0; i<nThreads; i++) {
tids[i]=i;
CREATE_WITH_ARG(bs_thread, &tids[i]);
}
WAIT_FOR_END(nThreads);
free(tids);
#endif //WIN32
#else //ENABLE_THREADS
#ifdef ENABLE_OPENMP
{
int tid=0;
omp_set_num_threads(nThreads);
bs_thread(&tid);
}
#else //ENABLE_OPENMP
#ifdef ENABLE_TBB
tbb::task_scheduler_init init(nThreads);
int tid=0;
bs_thread(&tid);
#else //ENABLE_TBB
//serial version
int tid=0;
bs_thread(&tid);
#endif //ENABLE_TBB
#endif //ENABLE_OPENMP
#endif //ENABLE_THREADS
#ifdef ENABLE_PARSEC_HOOKS
__parsec_roi_end();
#endif
//Write prices to output file
file = fopen(outputFile, "w");
if(file == NULL) {
printf("ERROR: Unable to open file `%s'.\n", outputFile);
exit(1);
}
rv = fprintf(file, "%i\n", numOptions);
if(rv < 0) {
printf("ERROR: Unable to write to file `%s'.\n", outputFile);
fclose(file);
exit(1);
}
for(i=0; i<numOptions; i++) {
rv = fprintf(file, "%.18f\n", prices[i]);
if(rv < 0) {
printf("ERROR: Unable to write to file `%s'.\n", outputFile);
fclose(file);
exit(1);
}
}
rv = fclose(file);
if(rv != 0) {
printf("ERROR: Unable to close file `%s'.\n", outputFile);
exit(1);
}
#ifdef ERR_CHK
printf("Num Errors: %d\n", numError);
#endif
free(data);
free(prices);
#ifdef ENABLE_PARSEC_HOOKS
__parsec_bench_end();
#endif
return 0;
}
|
GB_unaryop__identity_uint8_uint32.c | //------------------------------------------------------------------------------
// GB_unaryop: hard-coded functions for each built-in unary operator
//------------------------------------------------------------------------------
// SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2019, All Rights Reserved.
// http://suitesparse.com See GraphBLAS/Doc/License.txt for license.
//------------------------------------------------------------------------------
// If this file is in the Generated/ folder, do not edit it (auto-generated).
#include "GB.h"
#ifndef GBCOMPACT
#include "GB_control.h"
#include "GB_iterator.h"
#include "GB_unaryop__include.h"
// C=unop(A) is defined by the following types and operators:
// op(A) function: GB_unop__identity_uint8_uint32
// op(A') function: GB_tran__identity_uint8_uint32
// C type: uint8_t
// A type: uint32_t
// cast: uint8_t cij = (uint8_t) aij
// unaryop: cij = aij
#define GB_ATYPE \
uint32_t
#define GB_CTYPE \
uint8_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_CASTING(z, x) \
uint8_t z = (uint8_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_IDENTITY || GxB_NO_UINT8 || GxB_NO_UINT32)
//------------------------------------------------------------------------------
// Cx = op (cast (Ax)): apply a unary operator
//------------------------------------------------------------------------------
GrB_Info GB_unop__identity_uint8_uint32
(
uint8_t *restrict Cx,
const uint32_t *restrict Ax,
int64_t anz,
int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
#pragma omp parallel for num_threads(nthreads) schedule(static)
for (int64_t p = 0 ; p < anz ; p++)
{
GB_CAST_OP (p, p) ;
}
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// C = op (cast (A')): transpose, typecast, and apply a unary operator
//------------------------------------------------------------------------------
GrB_Info GB_tran__identity_uint8_uint32
(
GrB_Matrix C,
const GrB_Matrix A,
int64_t *restrict *Rowcounts,
GBI_single_iterator Iter,
const int64_t *restrict A_slice,
int naslice
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
#define GB_PHASE_2_OF_2
#include "GB_unaryop_transpose.c"
return (GrB_SUCCESS) ;
#endif
}
#endif
|
3d25pt_var.lbpar.c | #include <omp.h>
#include <math.h>
#define ceild(n,d) ceil(((double)(n))/((double)(d)))
#define floord(n,d) floor(((double)(n))/((double)(d)))
#define max(x,y) ((x) > (y)? (x) : (y))
#define min(x,y) ((x) < (y)? (x) : (y))
/*
* Order-1, 3D 25 point stencil with axis-symmetric ariable coefficients
* Adapted from PLUTO and Pochoir test bench
*
* Tareq Malas
*/
#include <stdio.h>
#include <stdlib.h>
#include <sys/time.h>
#ifdef LIKWID_PERFMON
#include <likwid.h>
#endif
#include "print_utils.h"
#define TESTS 2
#define MAX(a,b) ((a) > (b) ? a : b)
#define MIN(a,b) ((a) < (b) ? a : b)
/* Subtract the `struct timeval' values X and Y,
* storing the result in RESULT.
*
* Return 1 if the difference is negative, otherwise 0.
*/
int timeval_subtract(struct timeval *result, struct timeval *x, struct timeval *y)
{
/* Perform the carry for the later subtraction by updating y. */
if (x->tv_usec < y->tv_usec)
{
int nsec = (y->tv_usec - x->tv_usec) / 1000000 + 1;
y->tv_usec -= 1000000 * nsec;
y->tv_sec += nsec;
}
if (x->tv_usec - y->tv_usec > 1000000)
{
int nsec = (x->tv_usec - y->tv_usec) / 1000000;
y->tv_usec += 1000000 * nsec;
y->tv_sec -= nsec;
}
/* Compute the time remaining to wait.
* tv_usec is certainly positive.
*/
result->tv_sec = x->tv_sec - y->tv_sec;
result->tv_usec = x->tv_usec - y->tv_usec;
/* Return 1 if result is negative. */
return x->tv_sec < y->tv_sec;
}
int main(int argc, char *argv[])
{
int t, i, j, k, m, test;
int Nx, Ny, Nz, Nt;
if (argc > 3) {
Nx = atoi(argv[1])+8;
Ny = atoi(argv[2])+8;
Nz = atoi(argv[3])+8;
}
if (argc > 4)
Nt = atoi(argv[4]);
// allocate the arrays
double ****A = (double ****) malloc(sizeof(double***)*2);
for(m=0; m<2;m++){
A[m] = (double ***) malloc(sizeof(double**)*Nz);
for(i=0; i<Nz; i++){
A[m][i] = (double**) malloc(sizeof(double*)*Ny);
for(j=0;j<Ny;j++){
A[m][i][j] = (double*) malloc(sizeof(double)*Nx);
}
}
}
double ****coef = (double ****) malloc(sizeof(double***)*13);
for(m=0; m<13;m++){
coef[m] = (double ***) malloc(sizeof(double**)*Nz);
for(i=0; i<Nz; i++){
coef[m][i] = (double**) malloc(sizeof(double*)*Ny);
for(j=0;j<Ny;j++){
coef[m][i][j] = (double*) malloc(sizeof(double)*Nx);
}
}
}
// tile size information, including extra element to decide the list length
int *tile_size = (int*) malloc(sizeof(int));
tile_size[0] = -1;
// The list is modified here before source-to-source transformations
tile_size = (int*) realloc((void *)tile_size, sizeof(int)*5);
tile_size[0] = 4;
tile_size[1] = 4;
tile_size[2] = 24;
tile_size[3] = 64;
tile_size[4] = -1;
// for timekeeping
int ts_return = -1;
struct timeval start, end, result;
double tdiff = 0.0, min_tdiff=1.e100;
const int BASE = 1024;
// initialize variables
//
srand(42);
for (i = 1; i < Nz; i++) {
for (j = 1; j < Ny; j++) {
for (k = 1; k < Nx; k++) {
A[0][i][j][k] = 1.0 * (rand() % BASE);
}
}
}
for (m=0; m<13; m++) {
for (i=1; i<Nz; i++) {
for (j=1; j<Ny; j++) {
for (k=1; k<Nx; k++) {
coef[m][i][j][k] = 1.0 * (rand() % BASE);
}
}
}
}
#ifdef LIKWID_PERFMON
LIKWID_MARKER_INIT;
#pragma omp parallel
{
LIKWID_MARKER_THREADINIT;
#pragma omp barrier
LIKWID_MARKER_START("calc");
}
#endif
int num_threads = 1;
#if defined(_OPENMP)
num_threads = omp_get_max_threads();
#endif
for(test=0; test<TESTS; test++){
gettimeofday(&start, 0);
// serial execution - Addition: 6 && Multiplication: 2
/* Copyright (C) 1991-2014 Free Software Foundation, Inc.
This file is part of the GNU C Library.
The GNU C Library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
The GNU C Library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with the GNU C Library; if not, see
<http://www.gnu.org/licenses/>. */
/* This header is separate from features.h so that the compiler can
include it implicitly at the start of every compilation. It must
not itself include <features.h> or any other header that includes
<features.h> because the implicit include comes before any feature
test macros that may be defined in a source file before it first
explicitly includes a system header. GCC knows the name of this
header in order to preinclude it. */
/* glibc's intent is to support the IEC 559 math functionality, real
and complex. If the GCC (4.9 and later) predefined macros
specifying compiler intent are available, use them to determine
whether the overall intent is to support these features; otherwise,
presume an older compiler has intent to support these features and
define these macros by default. */
/* wchar_t uses ISO/IEC 10646 (2nd ed., published 2011-03-15) /
Unicode 6.0. */
/* We do not support C11 <threads.h>. */
int t1, t2, t3, t4, t5, t6, t7, t8;
int lb, ub, lbp, ubp, lb2, ub2;
register int lbv, ubv;
/* Start of CLooG code */
if ((Nt >= 1) && (Nx >= 9) && (Ny >= 9) && (Nz >= 9)) {
for (t1=-1;t1<=2*Nt-2;t1++) {
lbp=ceild(t1+2,2);
ubp=min(floord(4*Nt+Nz-9,4),floord(2*t1+Nz-4,4));
#pragma omp parallel for private(lbv,ubv,t3,t4,t5,t6,t7,t8)
for (t2=lbp;t2<=ubp;t2++) {
for (t3=max(ceild(t1-8,12),ceild(4*t2-Nz-11,24));t3<=min(min(floord(4*Nt+Ny-9,24),floord(2*t1+Ny-3,24)),floord(4*t2+Ny-9,24));t3++) {
for (t4=max(max(ceild(t1-28,32),ceild(4*t2-Nz-51,64)),ceild(24*t3-Ny-51,64));t4<=min(min(min(floord(4*Nt+Nx-9,64),floord(2*t1+Nx-3,64)),floord(4*t2+Nx-9,64)),floord(24*t3+Nx+11,64));t4++) {
for (t5=max(max(max(ceild(t1,2),ceild(4*t2-Nz+5,4)),ceild(24*t3-Ny+5,4)),ceild(64*t4-Nx+5,4));t5<=floord(t1+1,2);t5++) {
for (t6=max(4*t2,-4*t1+4*t2+8*t5-3);t6<=min(min(4*t2+3,-4*t1+4*t2+8*t5),4*t5+Nz-5);t6++) {
for (t7=max(24*t3,4*t5+4);t7<=min(24*t3+23,4*t5+Ny-5);t7++) {
lbv=max(64*t4,4*t5+4);
ubv=min(64*t4+63,4*t5+Nx-5);
#pragma ivdep
#pragma vector always
for (t8=lbv;t8<=ubv;t8++) {
A[( t5 + 1) % 2][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8)] = (((((((((((((coef[0][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8)] * A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8)]) + (coef[1][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8)] * (A[ t5 % 2][ (-4*t5+t6) - 1][ (-4*t5+t7)][ (-4*t5+t8)] + A[ t5 % 2][ (-4*t5+t6) + 1][ (-4*t5+t7)][ (-4*t5+t8)]))) + (coef[2][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8)] * (A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7) - 1][ (-4*t5+t8)] + A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7) + 1][ (-4*t5+t8)]))) + (coef[3][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8)] * (A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8) - 1] + A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8) + 1]))) + (coef[4][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8)] * (A[ t5 % 2][ (-4*t5+t6) - 2][ (-4*t5+t7)][ (-4*t5+t8)] + A[ t5 % 2][ (-4*t5+t6) + 2][ (-4*t5+t7)][ (-4*t5+t8)]))) + (coef[5][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8)] * (A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7) - 2][ (-4*t5+t8)] + A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7) + 2][ (-4*t5+t8)]))) + (coef[6][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8)] * (A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8) - 2] + A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8) + 2]))) + (coef[7][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8)] * (A[ t5 % 2][ (-4*t5+t6) - 3][ (-4*t5+t7)][ (-4*t5+t8)] + A[ t5 % 2][ (-4*t5+t6) + 3][ (-4*t5+t7)][ (-4*t5+t8)]))) + (coef[8][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8)] * (A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7) - 3][ (-4*t5+t8)] + A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7) + 3][ (-4*t5+t8)]))) + (coef[9][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8)] * (A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8) - 3] + A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8) + 3]))) + (coef[10][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8)] * (A[ t5 % 2][ (-4*t5+t6) - 4][ (-4*t5+t7)][ (-4*t5+t8)] + A[ t5 % 2][ (-4*t5+t6) + 4][ (-4*t5+t7)][ (-4*t5+t8)]))) + (coef[11][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8)] * (A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7) - 4][ (-4*t5+t8)] + A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7) + 4][ (-4*t5+t8)]))) + (coef[12][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8)] * (A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8) - 4] + A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8) + 4])));;
}
}
}
}
}
}
}
}
}
/* End of CLooG code */
gettimeofday(&end, 0);
ts_return = timeval_subtract(&result, &end, &start);
tdiff = (double) (result.tv_sec + result.tv_usec * 1.0e-6);
min_tdiff = min(min_tdiff, tdiff);
printf("Rank 0 TEST# %d time: %f\n", test, tdiff);
}
PRINT_RESULTS(4, "variable axis-symmetric")
#ifdef LIKWID_PERFMON
#pragma omp parallel
{
LIKWID_MARKER_STOP("calc");
}
LIKWID_MARKER_CLOSE;
#endif
// Free allocated arrays
for(i=0; i<Nz; i++){
for(j=0;j<Ny;j++){
free(A[0][i][j]);
free(A[1][i][j]);
}
free(A[0][i]);
free(A[1][i]);
}
free(A[0]);
free(A[1]);
for(m=0; m<13;m++){
for(i=0; i<Nz; i++){
for(j=0;j<Ny;j++){
free(coef[m][i][j]);
}
free(coef[m][i]);
}
free(coef[m]);
}
return 0;
}
|
cpd_hicoo.c | /*
This file is part of ParTI!.
ParTI! is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as
published by the Free Software Foundation, either version 3 of
the License, or (at your option) any later version.
ParTI! is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with ParTI!.
If not, see <http://www.gnu.org/licenses/>.
*/
#include <stdio.h>
#include <stdlib.h>
#include <getopt.h>
#include <ParTI.h>
#include "../src/sptensor/sptensor.h"
#include "../src/sptensor/hicoo/hicoo.h"
#include <omp.h>
void print_usage(char ** argv) {
printf("Usage: %s [options] \n", argv[0]);
printf("Options: -i INPUT, --input=INPUT\n");
printf(" -o OUTPUT, --output=OUTPUT\n");
printf(" -b BLOCKSIZE (bits), --blocksize=BLOCKSIZE (bits)\n");
printf(" -k KERNELSIZE (bits), --kernelsize=KERNELSIZE (bits)\n");
printf(" -c CHUNKSIZE (bits), --chunksize=CHUNKSIZE (bits, <=9)\n");
printf(" -e RENUMBER, --renumber=RENUMBER\n");
printf(" -n NITERS_RENUM\n");
printf(" -d CUDA_DEV_ID, --cuda-dev-id=DEV_ID\n");
printf(" -r RANK\n");
printf(" -t TK, --tk=TK\n");
printf(" -a balanced\n");
printf(" --help\n");
printf("\n");
}
int main(int argc, char ** argv) {
printf("CPD HiCOO: \n");
FILE *fi = NULL, *fo = NULL;
sptSparseTensor tsr;
sptSparseTensorHiCOO hitsr;
sptRankKruskalTensor ktensor;
sptElementIndex sb_bits;
sptElementIndex sk_bits;
sptElementIndex sc_bits;
sptIndex R = 16;
int cuda_dev_id = -2;
// int nloops = 1; // 5
sptIndex niters = 5; //5; // 50
double tol = 1e-5;
int renumber = 0;
int niters_renum = 3;
/* renumber:
* = 0 : no renumbering.
* = 1 : renumber with Lexi-order
* = 2 : renumber with BFS-like
* = 3 : randomly renumbering, specify niters_renum.
*/
int tk = 1;
int balanced = 0;
if(argc < 5) { // #Required arguments
print_usage(argv);
exit(1);
}
for(;;) {
static struct option long_options[] = {
{"input", required_argument, 0, 'i'},
{"bs", required_argument, 0, 'b'},
{"ks", required_argument, 0, 'k'},
{"cs", required_argument, 0, 'c'},
{"output", optional_argument, 0, 'o'},
{"impl-num", optional_argument, 0, 'p'},
{"renumber", optional_argument, 0, 'e'},
{"niters-renum", optional_argument, 0, 'n'},
{"cuda-dev-id", optional_argument, 0, 'd'},
{"rank", optional_argument, 0, 'r'},
{"tk", optional_argument, 0, 't'},
{"balanced", optional_argument, 0, 'a'},
{"help", no_argument, 0, 0},
{0, 0, 0, 0}
};
int option_index = 0;
int c = 0;
c = getopt_long(argc, argv, "i:b:k:c:o:e:n:d:r:t:a:", long_options, &option_index);
if(c == -1) {
break;
}
switch(c) {
case 'i':
fi = fopen(optarg, "r");
sptAssert(fi != NULL);
break;
case 'o':
fo = fopen(optarg, "w");
sptAssert(fo != NULL);
break;
case 'b':
sscanf(optarg, "%"PARTI_SCN_ELEMENT_INDEX, &sb_bits);
break;
case 'k':
sscanf(optarg, "%"PARTI_SCN_ELEMENT_INDEX, &sk_bits);
break;
case 'c':
sscanf(optarg, "%"PARTI_SCN_ELEMENT_INDEX, &sc_bits);
break;
case 'e':
sscanf(optarg, "%d", &renumber);
break;
case 'n':
sscanf(optarg, "%d", &niters_renum);
break;
case 'd':
sscanf(optarg, "%d", &cuda_dev_id);
break;
case 'r':
sscanf(optarg, "%"PARTI_SCN_INDEX, &R);
break;
case 't':
sscanf(optarg, "%d", &tk);
break;
case 'a':
sscanf(optarg, "%d", &balanced);
break;
case '?': /* invalid option */
case 'h':
default:
print_usage(argv);
exit(1);
}
}
printf("cuda_dev_id: %d\n", cuda_dev_id);
printf("renumber: %d\n", renumber);
if (renumber == 1)
printf("niters_renum: %d\n\n", niters_renum);
printf("balanced: %d\n", balanced);
/* A sorting included in load tensor */
sptAssert(sptLoadSparseTensor(&tsr, 1, fi) == 0);
fclose(fi);
sptSparseTensorStatus(&tsr, stdout);
// sptAssert(sptDumpSparseTensor(&tsr, 0, stdout) == 0);
/* Renumber the input tensor */
sptIndex ** map_inds;
if (renumber > 0) {
map_inds = (sptIndex **)malloc(tsr.nmodes * sizeof *map_inds);
spt_CheckOSError(!map_inds, "MTTKRP HiCOO");
for(sptIndex m = 0; m < tsr.nmodes; ++m) {
map_inds[m] = (sptIndex *)malloc(tsr.ndims[m] * sizeof (sptIndex));
spt_CheckError(!map_inds[m], "MTTKRP HiCOO", NULL);
for(sptIndex i = 0; i < tsr.ndims[m]; ++i)
map_inds[m][i] = i;
}
sptTimer renumber_timer;
sptNewTimer(&renumber_timer, 0);
sptStartTimer(renumber_timer);
if ( renumber == 1 || renumber == 2) { /* Set the Lexi-order or BFS-like renumbering */
sptIndexRenumber(&tsr, map_inds, renumber, niters_renum, tk);
}
if ( renumber == 3) { /* Set randomly renumbering */
sptGetRandomShuffledIndices(&tsr, map_inds);
}
fflush(stdout);
sptStopTimer(renumber_timer);
sptPrintElapsedTime(renumber_timer, "Renumbering");
sptFreeTimer(renumber_timer);
sptTimer shuffle_timer;
sptNewTimer(&shuffle_timer, 0);
sptStartTimer(shuffle_timer);
sptSparseTensorShuffleIndices(&tsr, map_inds);
sptStopTimer(shuffle_timer);
sptPrintElapsedTime(shuffle_timer, "Shuffling time");
sptFreeTimer(shuffle_timer);
printf("\n");
// sptSparseTensorSortIndex(&tsr, 1); // debug purpose only
// FILE * debug_fp = fopen("new.txt", "w");
// sptAssert(sptDumpSparseTensor(&tsr, 0, debug_fp) == 0);
// fprintf(stdout, "\nmap_inds:\n");
// for(sptIndex m = 0; m < tsr.nmodes; ++m) {
// sptDumpIndexArray(map_inds[m], tsr.ndims[m], stdout);
// }
// fclose(debug_fp);
}
/* Convert to HiCOO tensor */
sptNnzIndex max_nnzb = 0;
sptTimer convert_timer;
sptNewTimer(&convert_timer, 0);
sptStartTimer(convert_timer);
sptAssert(sptSparseTensorToHiCOO(&hitsr, &max_nnzb, &tsr, sb_bits, sk_bits, tk) == 0);
sptStopTimer(convert_timer);
sptPrintElapsedTime(convert_timer, "Convert HiCOO");
sptFreeTimer(convert_timer);
sptSparseTensorStatusHiCOO(&hitsr, stdout);
// sptAssert(sptDumpSparseTensorHiCOO(&hitsr, stdout) == 0);
sptIndex nmodes = hitsr.nmodes;
sptNewRankKruskalTensor(&ktensor, nmodes, tsr.ndims, R);
sptFreeSparseTensor(&tsr);
/* For warm-up caches, timing not included */
if(cuda_dev_id == -2) {
tk = 1;
sptAssert(sptCpdAlsHiCOO(&hitsr, R, niters, tol, &ktensor) == 0);
} else if(cuda_dev_id == -1) {
omp_set_num_threads(tk);
#pragma omp parallel
{
tk = omp_get_num_threads();
}
printf("tk: %d\n", tk);
sptAssert(sptOmpCpdAlsHiCOO(&hitsr, R, niters, tol, tk, balanced, &ktensor) == 0);
}
// for(int it=0; it<nloops; ++it) {
// }
if(fo != NULL) {
// Dump ktensor to files
if (renumber > 0) {
sptRankKruskalTensorInverseShuffleIndices(&ktensor, map_inds);
}
sptAssert( sptDumpRankKruskalTensor(&ktensor, fo) == 0 );
fclose(fo);
}
if (renumber > 0) {
for(sptIndex m = 0; m < tsr.nmodes; ++m) {
free(map_inds[m]);
}
free(map_inds);
}
sptFreeSparseTensorHiCOO(&hitsr);
sptFreeRankKruskalTensor(&ktensor);
return 0;
}
|
Searching.202007281234.only_gather_top_m.h | //
// Created by Zhen Peng on 7/28/2020.
//
#ifndef BATCH_SEARCHING_SEARCHING_H
#define BATCH_SEARCHING_SEARCHING_H
#include <vector>
#include <boost/dynamic_bitset.hpp>
//#include <boost/sort/sort.hpp>
#include <iostream>
#include <fstream>
#include <unordered_map>
#include <immintrin.h>
#include <cstring>
#include <unordered_set>
#include <set>
#include <cfloat>
#include <algorithm>
//#include <omp.h>
#include "../include/definitions.h"
//#include "../include/efanna2e/neighbor.h"
#include "../include/utils.h"
#include "../include/Candidate.h"
#include "../include/parallelization.h"
#include "../include/bitvector.h"
namespace PANNS {
class Searching {
//private:
public:
idi num_v_ = 0;
edgei num_e_ = 0;
idi num_queries_ = 0;
uint64_t dimension_ = 0;
idi width_ = 0; // NSG largest degree
idi ep_ = 0; // Start point
// std::vector<dataf> data_load_;
// std::vector<dataf> queries_load_;
// std::vector< std::vector<dataf> > data_load_;
// std::vector< std::vector<dataf> > queries_load_;
// std::vector<distf> norms_;
dataf *data_load_ = nullptr;
dataf *queries_load_ = nullptr;
// dataf *norms_;
// std::vector< std::vector<idi> > nsg_graph_;
// idi *nsg_graph_indices_;
// idi *nsg_graph_out_edges_;
// std::vector< std::vector<idi> > edge_list_;
char *opt_nsg_graph_ = nullptr;
uint64_t data_bytes_;
uint64_t neighbor_bytes_;
uint64_t vertex_bytes_;
// For multithreads
int num_threads_ = 1;
// int num_real_threads_ = 1;
// int num_threads_intra_query_ = 1;
// int num_threads_inter_query_ = 1;
dataf compute_norm(
const dataf *data) const;
// idi vertex_id);
// const std::vector<PANNS::dataf> &data);
// size_t loc_start,
// idi dimension)
dataf compute_distance_with_norm(
const dataf *v_data,
const dataf *q_data,
// idi vertex_id,
// idi query_id,
// const std::vector<dataf> &d_data,
// const std::vector<dataf> &q_data,
// PANNS::idi d_start,
// PANNS::idi q_start,
const dataf vertex_norm) const;
// idi dimension)
static idi insert_into_queue(
std::vector<Candidate> &c_queue,
idi c_queue_top,
Candidate cand);
static idi add_into_queue(
std::vector<PANNS::Candidate> &queue,
idi &queue_top,
const idi queue_size,
const PANNS::Candidate &cand);
static idi add_into_queue(
std::vector<PANNS::Candidate> &queue,
const idi queue_start,
idi &queue_size,
const idi queue_capacity,
const PANNS::Candidate &cand);
static void add_into_queue_at(
const Candidate &cand,
std::vector<Candidate> &queue,
const idi insert_index, // The insertion location, independent with queue_start
const idi queue_start,
idi &queue_top, // The number of elements in queue, independent with queue_start
const idi queue_size); // The maximum capacity of queue, independent with queue_start.
static void insert_one_element_at(
// const T &cand,
// T *queue_base,
const Candidate &cand,
std::vector<Candidate> &queue_base,
const idi insert_index,
const idi queue_start,
const idi queue_size);
// idi insert_into_queue_nsg(
// std::vector< Candidate > &c_queue,
// idi c_queue_top,
// Candidate cand);
static idi merge_two_queues_into_1st_queue_seq_fixed(
std::vector<Candidate> &queue1,
const idi queue1_start,
const idi queue1_size,
std::vector<Candidate> &queue2,
const idi queue2_start,
const idi queue2_size);
static void merge_two_queues_into_1st_queue_seq_incr(
std::vector<Candidate> &queue1,
const idi queue1_start,
idi &queue1_size, // The number of element in queue1, independent with queue1_start.
const idi queue1_length, // The maximum capacity of queue1, independent with queue1_start.
std::vector<Candidate> &queue2,
const idi queue2_start,
const idi queue2_size);
idi merge_all_queues_para_list(
std::vector< std::vector<Candidate> > &local_queues_list,
std::vector<idi> &local_queues_ends,
std::vector<Candidate> &set_L,
const idi L);
// idi merge_all_queues_para_array(
//// std::vector< std::vector<Candidate> > &local_queues_list,
// std::vector<Candidate> &local_queues_array,
// std::vector<idi> &local_queues_ends,
// const idi local_queue_length,
// std::vector<Candidate> &set_L,
// const idi L);
idi merge_all_queues_para_array(
std::vector<Candidate> &set_L,
// std::vector<Candidate> &local_queues_array,
std::vector<idi> &local_queues_ends,
const idi local_queue_length,
// std::vector<Candidate> &set_L,
const idi L);
idi merge_all_queues_queue_base(
// std::vector< std::vector<Candidate> > &local_queues_list,
std::vector<Candidate> &set_L,
// std::vector<Candidate> &local_queues_array,
std::vector<idi> &local_queues_ends,
const idi queue_base,
const int real_threads,
const idi local_queue_length,
// std::vector<Candidate> &set_L,
const idi L);
void merge_two_consecutive_queues_in_place(
std::vector<Candidate> &two_queues,
const idi base_1,
// const idi &end_1,
const idi base_2,
const idi &length_2);
void merge_in_set_L(
std::vector<Candidate> &set_L,
const idi set_L_length,
const idi num_queues,
const idi local_queue_length);
distf selecting_top_L_seq(
std::vector<Candidate> &set_L,
const idi global_L,
// const idi local_L,
const idi num_queues,
const std::vector<idi> &local_queues_starts,
std::vector<idi> &local_queues_sizes);
void selecting_unchecked_top_M_seq(
const idi query_id,
const idi iter,
std::vector<Candidate> &set_L,
const std::vector<idi> &pointers_starts,
const idi value_M,
const idi num_queues,
const std::vector<idi> &local_queues_starts,
const std::vector<idi> &local_queues_sizes,
std::vector<idi> &local_m_counts);
void gather_unchecked_top_M_seq(
const idi query_id,
const idi iter,
std::vector<Candidate> &set_L,
const std::vector<idi> &pointers_starts,
const idi value_M,
const idi num_queues,
const std::vector<idi> &local_queues_starts,
const std::vector<idi> &local_queues_sizes,
std::vector<idi> &top_m_candidates,
idi &top_m_candidates_size,
std::vector<idi> &bound_subs);
// idi merge_all_queues_all_together_in_sequential(
// std::vector<Candidate> &set_L,
// std::vector<idi> &local_queues_ends,
// const idi local_queue_length,
// const idi L);
// idi min_all_queues_at_heads(
// const std::vector<Candidate> &set_L,
// std::vector<idi> &queue_heads,
// const std::vector<idi> &local_queues_ends,
// const idi local_queue_length,
// const idi L);
public:
// For Profiling
// L3CacheMissRate cache_miss_kernel;
uint64_t count_distance_computation_ = 0;
// uint64_t count_add_to_queue_ = 0;
// uint64_t count_single_query_computation_ = 0;
// distf dist_min_ = 0;
// distf dist_max_ = 0;
// double time_merge_ = 0;
double time_gather_ = 0;
// double time_select_ = 0;
// double time_select_L_ = 0.0;
// double time_select_M_ = 0.0;
// double time_initialization_ = 0;
// double time_sequential_phase_ = 0;
// double time_parallel_phase_ = 0;
// double time_ending_ = 0.0;
// double time_assign_s_ = 0.0;
// double time_expand_ = 0.0;
// double time_pick_top_m_ = 0.0;
// double time_distance_computation_ = 0.0;
// double time_add_to_queue_ = 0.0;
// double time_insert_ = 0;
// double time_compare_minimum_ = 0;
// double time_memmove_ = 0;
// std::vector<double> time_memmove_list_;
// L3CacheMissRate profile_miss_rate;
// uint64_t number_local_elements_ = 0;
// std::vector<idi> L_ids_;
// std::vector<idi> M_ids_;
~Searching()
{
free(data_load_);
data_load_ = nullptr;
// free(queries_load_);
// _mm_free(data_load_);
free(queries_load_);
queries_load_ = nullptr;
// free(norms_);
// free(nsg_graph_indices_);
// free(nsg_graph_out_edges_);
free(opt_nsg_graph_);
opt_nsg_graph_ = nullptr;
}
void load_data_load(char *filename);
void load_queries_load(char *filename);
void load_nsg_graph(char *filename);
// void build_opt_graph();
void prepare_init_ids(
std::vector<unsigned> &init_ids,
const unsigned L) const;
// void prepare_candidate_queue_list(
// const float *query_load,
// std::vector<std::vector<efanna2e::Neighbor> > &retset_list,
// std::vector<boost::dynamic_bitset<> > &is_visited_list,
// const std::vector<unsigned> &init_ids,
// const boost::dynamic_bitset<> &flags,
// unsigned batch_start,
// unsigned batch_size,
// unsigned L);
// void search_in_batch(
//// const float *query_load,
// size_t K,
// size_t L,
// unsigned batch_start,
// unsigned batch_size,
// std::vector< std::vector<Candidate> > &set_L_list,
// std::vector< boost::dynamic_bitset<> > &is_visited_list,
// const std::vector<idi> &init_ids,
// const boost::dynamic_bitset<> &is_visited,
// std::vector<std::vector<idi> > &set_K_list);
void search_in_sequential(
idi query_id,
idi K,
idi L,
std::vector<Candidate> &set_L,
// boost::dynamic_bitset<> &is_visited,
// boost::dynamic_bitset<> is_visited,
// std::vector<idi> &init_ids,
const std::vector<idi> &init_ids,
std::vector<idi> &set_K);
// void search_in_sequential_BitVector(
// const idi query_id,
// const idi K,
// const idi L,
// std::vector<Candidate> &set_L,
// const std::vector<idi> &init_ids,
// std::vector<idi> &set_K);
// idi get_out_degree(idi v_id) const
// {
// if (v_id < num_v_ - 1) {
// return nsg_graph_indices_[v_id + 1] - nsg_graph_indices_[v_id];
// } else {
// return num_e_ - nsg_graph_indices_[v_id];
// }
// }
void search_with_top_m(
idi M,
idi query_id,
idi K,
idi L,
std::vector<Candidate> &set_L,
const std::vector<idi> &init_ids,
std::vector<idi> &set_K);
// std::vector< std::vector<idi> > &top_m_list);
void search_with_top_m_scale_m(
const PANNS::idi value_M_max,
const PANNS::idi query_id,
const PANNS::idi K,
const PANNS::idi L,
std::vector<Candidate> &set_L,
const std::vector<idi> &init_ids,
std::vector<idi> &set_K,
std::vector<idi> &top_m_candidates,
boost::dynamic_bitset<> &is_visited);
// void search_with_top_m_myths_M(
// const PANNS::idi M,
// const PANNS::idi query_id,
// const PANNS::idi K,
// const PANNS::idi L,
// std::vector<Candidate> &set_L,
// const std::vector<idi> &init_ids,
// std::vector<idi> &set_K);
// void search_with_top_m_to_get_distance_range(
// const PANNS::idi M,
// const PANNS::idi query_id,
//// const PANNS::idi K,
// const PANNS::idi L,
// std::vector<Candidate> &set_L,
// const std::vector<idi> &init_ids);
// void search_with_top_m_profile_bit_CAS(
// const PANNS::idi M,
// const PANNS::idi query_id,
// const PANNS::idi K,
// const PANNS::idi L,
// std::vector<Candidate> &set_L,
// const std::vector<idi> &init_ids,
// std::vector<idi> &set_K);
// void search_with_top_m_no_local_arrays(
// const PANNS::idi M,
// const PANNS::idi query_id,
// const PANNS::idi K,
// const PANNS::idi L,
// std::vector<Candidate> &set_L,
// const std::vector<idi> &init_ids,
// std::vector<idi> &set_K,
// boost::dynamic_bitset<> &is_visited);
void search_with_top_m_in_batch(
PANNS::idi M,
PANNS::idi batch_start,
PANNS::idi batch_size,
PANNS::idi K,
PANNS::idi L,
std::vector< std::vector<Candidate> > &set_L_list,
const std::vector<idi> &init_ids,
std::vector< std::vector<idi> > &set_K_list);
// void para_search_with_top_m_critical_area(
// idi M,
// idi query_id,
// idi K,
// idi L,
// std::vector<Candidate> &set_L,
// const std::vector<idi> &init_ids,
// std::vector<idi> &set_K);
// void para_search_with_top_m_critical_area_no_omp(
// idi M,
// idi query_id,
// idi K,
// idi L,
// std::vector<Candidate> &set_L,
// const std::vector<idi> &init_ids,
// std::vector<idi> &set_K);
// void para_search_with_top_m_critical_area_yes_omp(
// idi M,
// idi query_id,
// idi K,
// idi L,
// std::vector<Candidate> &set_L,
// const std::vector<idi> &init_ids,
// std::vector<idi> &set_K);
// void para_search_with_top_m_visited_array(
// const PANNS::idi M,
// const PANNS::idi query_id,
// const PANNS::idi K,
// const PANNS::idi L,
// std::vector<Candidate> &set_L,
// const std::vector<idi> &init_ids,
// std::vector<idi> &set_K,
// std::vector<uint8_t> &is_visited);
// void para_search_with_top_m_merge_queues(
// const idi M,
// const idi query_id,
// const idi K,
// const idi L,
// std::vector<Candidate> &set_L,
// const std::vector<idi> &init_ids,
// std::vector<idi> &set_K);
// void para_search_with_top_m_queues_seq_merge(
// const PANNS::idi M,
// const PANNS::idi query_id,
// const PANNS::idi K,
// const PANNS::idi L,
// std::vector<Candidate> &set_L,
// const std::vector<idi> &init_ids,
// std::vector<idi> &set_K);
// void para_search_with_top_m_merge_queues_no_CAS(
// const idi M,
// const idi query_id,
// const idi K,
// const idi L,
// std::vector<Candidate> &set_L,
// const std::vector<idi> &init_ids,
// std::vector<idi> &set_K,
// const idi local_queue_length,
// std::vector< std::vector<Candidate> > &local_queues_list,
// std::vector<idi> &local_queues_ends,
//// std::vector<uint8_t> &is_visited);
// boost::dynamic_bitset<> &is_visited);
// void para_search_with_top_m_merge_queues_in_array(
// void para_search_with_top_m_merge_queues_new_threshold(
// const idi M,
// const idi query_id,
// const idi K,
// const idi L,
// std::vector<Candidate> &set_L,
// const std::vector<idi> &init_ids,
// std::vector<idi> &set_K,
// const idi local_queue_length, // Maximum size of local queue
//// std::vector< std::vector<Candidate> > &local_queues_list,
// std::vector<Candidate> &local_queues_array,
// std::vector<idi> &local_queues_ends, // Sizes of local queue
// BitVector &is_visited);
// void para_search_with_top_m_merge_queues_by_sort(
// const idi M,
// const idi query_id,
// const idi K,
// const idi L,
// std::vector<Candidate> &set_L,
// const std::vector<idi> &init_ids,
// std::vector<idi> &set_K,
// const idi local_queue_length, // Maximum size of local queue
//// std::vector<Candidate> &local_queues_array,
// std::vector<idi> &local_queues_ends, // Sizes of local queue
// std::vector<idi> &dest_offsets,
// const std::vector<idi> &offsets_load_set_L, // Offsets for store into set_L.
// BitVector &is_visited);
// void para_search_with_top_m_merge_queues_better_merge_v0(
// const idi M,
// const idi query_id,
// const idi K,
// const idi L,
// std::vector<Candidate> &set_L,
// const std::vector<idi> &init_ids,
// std::vector<idi> &set_K,
// const idi local_queue_length, // Maximum size of local queue
// std::vector<idi> &local_queues_ends, // Sizes of local queue
//// std::vector<Candidate> &top_m_candidates,
// std::vector<idi> &top_m_candidates,
//// std::vector<uint8_t> &is_visited);
// boost::dynamic_bitset<> &is_visited);
//// BitVector &is_visited);
// void para_search_with_top_m_merge_queues_better_merge_v2(
// const idi M,
// const idi query_id,
// const idi K,
// const idi L,
// std::vector<Candidate> &set_L,
// const std::vector<idi> &init_ids,
// std::vector<idi> &set_K,
// const idi local_queue_length, // Maximum size of local queue
// std::vector<idi> &local_queues_ends, // Sizes of local queue
//// std::vector<Candidate> &top_m_candidates,
// std::vector<idi> &top_m_candidates,
//// std::vector<uint8_t> &is_visited)
// boost::dynamic_bitset<> &is_visited,
// std::vector<distf> &local_thresholds);
//// BitVector &is_visited)
// void para_search_with_top_m_merge_queues_better_merge_v1(
// const idi M,
// const idi query_id,
// const idi K,
// const idi L,
// std::vector<Candidate> &set_L,
// const std::vector<idi> &init_ids,
// std::vector<idi> &set_K,
// const idi local_queue_length, // Maximum size of local queue
// std::vector<idi> &local_queues_ends, // Sizes of local queue
// std::vector<Candidate> &top_m_candidates,
//// std::vector<idi> &top_m_candidates,
//// std::vector<uint8_t> &is_visited);
// boost::dynamic_bitset<> &is_visited);
//// BitVector &is_visited);
// void para_search_with_top_m_merge_queues_better_merge_v0_0(
// const idi M,
// const idi query_id,
// const idi K,
// const idi L,
// std::vector<Candidate> &set_L,
// const std::vector<idi> &init_ids,
// std::vector<idi> &set_K,
// const idi local_queue_length, // Maximum size of local queue
// std::vector<idi> &local_queues_ends, // Sizes of local queue
//// std::vector<Candidate> &top_m_candidates,
// std::vector<idi> &top_m_candidates,
//// std::vector<uint8_t> &is_visited)
// boost::dynamic_bitset<> &is_visited);
//// BitVector &is_visited)
// void para_search_with_top_m_merge_queues_less_merge(
// const idi M,
// const idi query_id,
// const idi K,
// const idi L,
// std::vector<Candidate> &set_L,
// const std::vector<idi> &init_ids,
// std::vector<idi> &set_K,
// const idi local_queue_length, // Maximum size of local queue
// std::vector<idi> &local_queues_ends, // Sizes of local queue
//// std::vector<Candidate> &top_m_candidates,
// std::vector<idi> &top_m_candidates,
//// std::vector<uint8_t> &is_visited)
// boost::dynamic_bitset<> &is_visited,
// std::vector<distf> &local_thresholds);
//// BitVector &is_visited)
// void para_search_with_top_m_merge_queues_no_merge(
// const idi M,
// const idi query_id,
// const idi K,
// const idi L,
// std::vector<Candidate> &set_L,
// const std::vector<idi> &init_ids,
// std::vector<idi> &set_K,
// const idi local_queue_length, // Maximum size of local queue
// std::vector<idi> &local_queues_ends, // Sizes of local queue
//// std::vector<Candidate> &top_m_candidates,
// std::vector<idi> &top_m_candidates,
//// std::vector<uint8_t> &is_visited)
// boost::dynamic_bitset<> &is_visited,
// std::vector<distf> &local_thresholds,
// const uint64_t computation_threshold);
// void para_search_with_top_m_merge_queues_scale_m_v0(
// const idi value_M_max,
// const idi query_id,
// const idi K,
// const idi L,
// std::vector<Candidate> &set_L,
// const std::vector<idi> &init_ids,
// std::vector<idi> &set_K,
// const idi local_queue_length, // Maximum size of local queue
// std::vector<idi> &local_queues_ends, // Sizes of local queue
//// std::vector<Candidate> &top_m_candidates,
// std::vector<idi> &top_m_candidates,
//// std::vector<uint8_t> &is_visited);
// boost::dynamic_bitset<> &is_visited);
// void para_search_with_top_m_merge_queues_middle_m(
// const idi value_M_middle,
// const idi value_M_max,
// const idi query_id,
// const idi K,
// const idi L,
// std::vector<Candidate> &set_L,
// const std::vector<idi> &init_ids,
// std::vector<idi> &set_K,
// const idi local_queue_length, // Maximum size of local queue
// const idi base_set_L, // base_set_L = (num_threads_ - 1) * local_queue_length;
// std::vector<idi> &local_queues_ends, // Sizes of local queue
//// std::vector<Candidate> &top_m_candidates,
// std::vector<idi> &top_m_candidates,
//// std::vector<uint8_t> &is_visited)
// boost::dynamic_bitset<> &is_visited);
// std::vector<distf> &local_thresholds);
// BitVector &is_visited)
// void para_search_with_top_m_merge_queues_scale_m_v2(
// const idi value_M_min,
// const idi value_M_max,
// const idi query_id,
// const idi K,
// const idi L,
// std::vector<Candidate> &set_L,
// const std::vector<idi> &init_ids,
// std::vector<idi> &set_K,
// const idi local_queue_length, // Maximum size of local queue
// const idi base_set_L, // base_set_L = (num_threads_ - 1) * local_queue_length;
// std::vector<idi> &local_queues_ends, // Sizes of local queue
//// std::vector<Candidate> &top_m_candidates,
// std::vector<idi> &top_m_candidates,
//// std::vector<uint8_t> &is_visited)
// boost::dynamic_bitset<> &is_visited);
// void para_search_with_top_m_merge_queues_scale_m_v3(
// const idi value_M_middle,
// const idi value_M_max,
// const idi query_id,
// const idi K,
// const idi L,
// std::vector<Candidate> &set_L,
// const std::vector<idi> &init_ids,
// std::vector<idi> &set_K,
// const idi local_queue_length, // Maximum size of local queue
// const idi base_set_L, // base_set_L = (num_threads_ - 1) * local_queue_length;
// std::vector<idi> &local_queues_ends, // Sizes of local queue
//// std::vector<Candidate> &top_m_candidates,
// std::vector<idi> &top_m_candidates,
//// std::vector<uint8_t> &is_visited)
// boost::dynamic_bitset<> &is_visited);
void para_search_with_top_m_merge_queues_middle_m_no_merge(
const uint64_t computation_threshold,
const idi value_M_middle,
const idi value_M_max,
const idi query_id,
const idi K,
const idi L,
const idi init_size,
std::vector<Candidate> &set_L,
const std::vector<idi> &init_ids,
std::vector<idi> &set_K,
const idi local_queue_length, // Maximum size of local queue
const idi base_set_L, // base_set_L = (num_threads_ - 1) * local_queue_length;
std::vector<idi> &local_queues_ends, // Sizes of local queue
std::vector<idi> &top_m_candidates,
boost::dynamic_bitset<> &is_visited);
void para_search_with_top_m_merge_queues_sequential_merge(
const idi value_M_middle,
const idi value_M_max,
const idi query_id,
const idi K,
const idi L,
std::vector<Candidate> &set_L,
const std::vector<idi> &init_ids,
std::vector<idi> &set_K,
const idi local_queue_length, // Maximum size of local queue
const idi base_set_L, // base_set_L = (num_threads_ - 1) * local_queue_length;
std::vector<idi> &local_queues_ends, // Sizes of local queue
std::vector<idi> &top_m_candidates,
boost::dynamic_bitset<> &is_visited);
void para_search_with_top_m_nested_para(
const idi batch_start,
const idi batch_size,
const idi value_M_middle,
const idi value_M_max,
const idi K,
const idi L,
std::vector< std::vector<Candidate> > &set_L_list,
const std::vector<idi> &init_ids,
std::vector< std::vector<idi> > &set_K_list,
const idi local_queue_length, // Maximum size of local queue
const idi base_set_L, // base_set_L = (num_threads_ - 1) * local_queue_length;
std::vector< std::vector<idi> > &local_queues_ends_list, // Sizes of local queue
std::vector< std::vector<idi> > &top_m_candidates_list,
std::vector< boost::dynamic_bitset<> > &is_visited_list);
void subsearch_with_top_m(
const idi value_M_max,
const idi query_id,
const idi local_L,
std::vector<Candidate> &set_L,
const idi set_L_start,
idi &set_L_size,
std::vector<idi> &local_top_m_candidates,
boost::dynamic_bitset<> &is_visited,
uint64_t &local_count_distance_computation);
void subsearch_top_m_for_one_iteration(
const idi iter,
idi &k_uc,
const idi value_M,
const idi query_id,
const dataf *query_data,
const idi L,
std::vector<Candidate> &set_L,
const idi set_L_start,
idi &set_L_size,
std::vector<idi> &top_m_candidates,
boost::dynamic_bitset<> &is_visited,
uint64_t &count_distance_computation);
// void subsearch_top_m_for_one_iteration_lth(
// const distf bound_lth,
// const idi iter,
// idi &k_uc,
// const idi value_M,
// const idi query_id,
// const dataf *query_data,
// const idi L,
// std::vector<Candidate> &set_L,
// const idi set_L_start,
// idi &set_L_size,
// std::vector<idi> &top_m_candidates,
// boost::dynamic_bitset<> &is_visited,
// uint64_t &count_distance_computation);
void subsearch_top_m_for_one_iteration_lth_mth(
const distf bound_lth,
// const idi top_m_position,
const idi iter,
idi &k_uc,
const idi local_m_count,
const idi query_id,
const dataf *query_data,
const idi L,
std::vector<Candidate> &set_L,
const idi set_L_start,
idi &set_L_size,
std::vector<idi> &top_m_candidates,
boost::dynamic_bitset<> &is_visited,
uint64_t &count_distance_computation,
double &time_pick_top_m,
uint64_t &count_add_to_queue,
double &time_distance_computation,
double &time_add_to_queue);
// void para_search_with_top_m_subsearch_v3(
// const idi local_M_max,
// const idi local_M_middle,
// const idi query_id,
// const idi K,
// const idi global_L,
// const idi local_L,
//// const idi total_L,
//// const idi init_queue_size,
// std::vector<Candidate> &set_L,
// const std::vector<idi> &init_ids,
// std::vector<idi> &set_K,
// const std::vector<idi> &local_queues_starts,
// std::vector<idi> &local_queues_sizes,
// std::vector<idi> &local_m_counts,
// std::vector< std::vector<idi> > &top_m_candidates_list,
// boost::dynamic_bitset<> &is_visited);
// void para_search_with_top_m_subsearch_v4(
// const idi local_M_max,
// const idi local_M_middle,
// const idi query_id,
// const idi K,
// const idi global_L,
// const idi local_L,
// std::vector<Candidate> &set_L,
// const std::vector<idi> &init_ids,
// std::vector<idi> &set_K,
// const std::vector<idi> &local_queues_starts,
// std::vector<idi> &local_queues_sizes,
// std::vector<idi> &local_m_counts,
// std::vector<idi> &top_m_candidates,
// boost::dynamic_bitset<> &is_visited);
void para_search_with_top_m_subsearch_v5(
const idi local_M_max,
const idi local_M_middle,
const idi query_id,
const idi K,
const idi global_L,
const idi local_L,
// const idi total_L,
// const idi init_queue_size,
std::vector<Candidate> &set_L,
const std::vector<idi> &init_ids,
std::vector<idi> &set_K,
const std::vector<idi> &local_queues_starts,
std::vector<idi> &local_queues_sizes,
// std::vector<idi> &local_m_counts,
std::vector<idi> &top_m_candidates,
// std::vector< std::vector<idi> > &top_m_candidates_list,
boost::dynamic_bitset<> &is_visited);
void subsearch_for_simple_search(
const idi query_id,
const idi local_L,
std::vector<Candidate> &set_L,
const idi base_set_L,
idi &set_L_end,
// std::vector<uint8_t> &is_visited,
boost::dynamic_bitset<> &is_visited,
uint64_t &local_count_distance_computation);
void para_simple_search_subsearch(
const idi query_id,
const idi K,
const idi L,
std::vector<Candidate> &set_L,
const std::vector<idi> &init_ids,
std::vector<idi> &set_K,
// std::vector<uint8_t> &is_visited);
boost::dynamic_bitset<> &is_visited);
// void para_search_with_top_m_merge_queues_global_threshold(
// const idi value_M_middle,
// const idi value_M_max,
// const idi query_id,
// const idi K,
// const idi L,
// std::vector<Candidate> &set_L,
// const std::vector<idi> &init_ids,
// std::vector<idi> &set_K,
// const idi local_queue_length, // Maximum size of local queue
// const idi base_set_L, // base_set_L = (num_threads_ - 1) * local_queue_length;
// std::vector<idi> &local_queues_ends, // Sizes of local queue
// std::vector<idi> &top_m_candidates,
// boost::dynamic_bitset<> &is_visited);
// void para_search_with_top_m_merge_queues_distance_threshold_m(
//// const idi value_M_middle,
//// const idi value_M_max,
// const distf relative_dist_threshold,
// const idi query_id,
// const idi K,
// const idi L,
// std::vector<Candidate> &set_L,
// const std::vector<idi> &init_ids,
// std::vector<idi> &set_K,
// const idi local_queue_length, // Maximum size of local queue
// const idi base_set_L, // base_set_L = (num_threads_ - 1) * local_queue_length;
// std::vector<idi> &local_queues_ends, // Sizes of local queue
//// std::vector<Candidate> &top_m_candidates,
// std::vector<idi> &top_m_candidates,
//// std::vector<uint8_t> &is_visited)
// boost::dynamic_bitset<> &is_visited);
//// std::vector<distf> &local_thresholds)
//// BitVector &is_visited)
// void para_search_with_top_m_merge_queues_distance_threshold_m_middle_iteration(
//// const idi value_M_middle,
//// const idi value_M_max,
// const distf relative_dist_threshold,
// const idi middle_iteration,
// const idi query_id,
// const idi K,
// const idi L,
// std::vector<Candidate> &set_L,
// const std::vector<idi> &init_ids,
// std::vector<idi> &set_K,
// const idi local_queue_length, // Maximum size of local queue
// const idi base_set_L, // base_set_L = (num_threads_ - 1) * local_queue_length;
// std::vector<idi> &local_queues_ends, // Sizes of local queue
//// std::vector<Candidate> &top_m_candidates,
// std::vector<idi> &top_m_candidates,
//// std::vector<uint8_t> &is_visited)
// boost::dynamic_bitset<> &is_visited);
// void para_search_with_top_m_merge_queues_collectors(
// const idi value_M_middle,
// const idi value_M_max,
// const idi query_id,
// const idi K,
// const idi L,
// std::vector<Candidate> &set_L,
// const std::vector<idi> &init_ids,
// std::vector<idi> &set_K,
// const idi local_queue_length, // Maximum size of local queue
// const idi base_set_L, // base_set_L = (num_threads_ - 1) * local_queue_length;
// std::vector<idi> &local_queues_ends, // Sizes of local queue
//// std::vector<Candidate> &top_m_candidates,
// std::vector<idi> &top_m_candidates,
//// std::vector<uint8_t> &is_visited)
// boost::dynamic_bitset<> &is_visited);
// void para_search_with_top_m_merge_queues_selecting(
// const idi value_M_middle,
// const idi value_M_max,
// const idi query_id,
// const idi K,
// const idi L,
// std::vector<Candidate> &set_L,
// const std::vector<idi> &init_ids,
// std::vector<idi> &set_K,
// const idi local_queue_length, // Maximum size of local queue
// const idi base_set_L, // base_set_L = (num_threads_ - 1) * local_queue_length;
// std::vector<idi> &local_queues_ends, // Sizes of local queue
//// std::vector<Candidate> &top_m_candidates,
// std::vector<idi> &top_m_candidates,
//// std::vector<uint8_t> &is_visited)
// boost::dynamic_bitset<> &is_visited);
// void para_search_with_top_m_merge_queues_myths(
// const idi M,
// const idi query_id,
// const idi K,
// const idi L,
// std::vector<Candidate> &set_L,
// const std::vector<idi> &init_ids,
// std::vector<idi> &set_K,
// const idi local_queue_length, // Maximum size of local queue
//// std::vector< std::vector<Candidate> > &local_queues_list,
// std::vector<Candidate> &local_queues_array,
// std::vector<idi> &local_queues_ends, // Sizes of local queue
// BitVector &is_visited);
//// std::vector<uint8_t> &is_visited);
//// boost::dynamic_bitset<> &is_visited);
//// void para_prepare_init_ids(
//// std::vector<unsigned> &init_ids,
//// unsigned L) const;
// void para_search_with_top_m_in_batch_embarassing_para(
// const PANNS::idi M,
// const PANNS::idi batch_start,
// const PANNS::idi batch_size,
// const PANNS::idi K,
// const PANNS::idi L,
// std::vector< std::vector<Candidate> > &set_L_list,
// const std::vector<idi> &init_ids,
// std::vector< std::vector<idi> > &set_K_list,
// std::vector< boost::dynamic_bitset<> > &is_visited_list);
// void test_neighbors_distance_to_father(
// const idi num_selected) const;
// void test_neighbors_normalized_distance_to_father(
// const idi num_selected) const;
void load_true_NN(
const char *filename,
std::vector< std::vector<idi> > &true_nn_list);
void get_recall_for_all_queries(
const std::vector< std::vector<idi> > &true_nn_list,
const std::vector<std::vector<unsigned>> &set_K_list,
std::unordered_map<unsigned, double> &recalls) const;
}; // Class Searching
/**
* Input the data from the file.
* @param filename
*/
inline void Searching::load_data_load(char *filename)
{
auto old_d = dimension_;
DiskIO::load_data(
filename,
data_load_,
num_v_,
dimension_);
if (old_d) {
if (old_d != dimension_) {
std::cerr << "Error: data dimension " << dimension_
<< " is not equal to query dimension " << old_d << "." << std::endl;
exit(EXIT_FAILURE);
}
}
}
/**
* Input queries from the file.
* @param filename
*/
inline void Searching::load_queries_load(char *filename)
{
auto old_d = dimension_;
DiskIO::load_data(
filename,
queries_load_,
num_queries_,
dimension_);
if (old_d) {
if (old_d != dimension_) {
std::cerr << "Error: query dimension " << dimension_
<< " is not equal to data dimension " << old_d << "." << std::endl;
exit(EXIT_FAILURE);
}
}
}
/**
* Input the NSG graph from the file.
* Reference: https://github.com/ZJULearning/nsg/blob/master/src/index_nsg.cpp
* @param filename
*/
inline void Searching::load_nsg_graph(char *filename)
{
std::ifstream fin(filename);
if (!fin.is_open()) {
std::cerr << "Error: cannot read file " << filename << " ." << std::endl;
exit(EXIT_FAILURE);
}
fin.read(reinterpret_cast<char *>(&width_), sizeof(unsigned));
fin.read(reinterpret_cast<char *>(&ep_), sizeof(unsigned));
data_bytes_ = (1 + dimension_) * sizeof(dataf);
neighbor_bytes_ = (1 + width_) * sizeof(idi);
vertex_bytes_ = data_bytes_ + neighbor_bytes_;
opt_nsg_graph_ = (char *) malloc(num_v_ * vertex_bytes_);
if (!opt_nsg_graph_) {
std::cerr << "Error: no enough memory for opt_nsg_graph_." << std::endl;
exit(EXIT_FAILURE);
}
idi v_id = 0;
num_e_ = 0;
char *base_location = opt_nsg_graph_;
while (true) {
idi degree;
fin.read(reinterpret_cast<char *>(°ree), sizeof(unsigned));
if (fin.eof()) {
break;
}
num_e_ += degree;
// std::vector<idi> tmp_ngbrs(degree);
// fin.read(reinterpret_cast<char *>(tmp_ngbrs.data()), degree * sizeof(unsigned));
// Norm and data
distf norm = compute_norm(data_load_ + v_id * dimension_);
// distf norm = compute_norm(v_id);
std::memcpy(base_location, &norm, sizeof(distf)); // Norm
memcpy(base_location + sizeof(distf), data_load_ + v_id * dimension_, dimension_ * sizeof(dataf)); // Data
base_location += data_bytes_;
// Neighbors
memcpy(base_location, °ree, sizeof(idi)); // Number of neighbors
fin.read(base_location + sizeof(idi), degree * sizeof(unsigned)); // Neighbors
// memcpy(location + sizeof(idi), tmp_ngbrs.data(), degree * sizeof(unsigned));
base_location += neighbor_bytes_;
++v_id;
}
if (v_id != num_v_) {
std::cerr << "Error: NSG data has " << v_id
<< " vertices, but origin data has " << num_v_ << " vertices." << std::endl;
exit(EXIT_FAILURE);
}
free(data_load_);
data_load_ = nullptr;
// ////////////////////////
// idi v_id = 0;
// num_e_ = 0;
// while (true) {
// idi degree;
// fin.read(reinterpret_cast<char *>(°ree), sizeof(unsigned));
// if (fin.eof()) {
// break;
// }
// num_e_ += degree;
//
// std::vector<idi> ngbrs(degree);
// fin.read(reinterpret_cast<char *>(ngbrs.data()), degree * sizeof(unsigned));
//// nsg_graph_.push_back(ngbrs);
//// tmp_edge_list.push_back(ngbrs);
// edge_list_.push_back(ngbrs);
// ++v_id;
// }
// if (v_id != num_v_) {
// std::cerr << "Error: NSG data has " << v_id
// << " vertices, but origin data has " << num_v_ << " vertices." << std::endl;
// exit(EXIT_FAILURE);
// }
}
/**
* Load those true top-K neighbors (ground truth) of queries
* @param filename
* @param[out] true_nn_list
*/
inline void Searching::load_true_NN(
const char *filename,
std::vector< std::vector<idi> > &true_nn_list)
// unsigned &t_K)
{
std::ifstream fin(filename);
if (!fin.is_open()) {
fprintf(stderr, "Error: cannot open file %s\n", filename);
exit(EXIT_FAILURE);
}
idi t_query_num;
idi t_K;
// unsigned t_K;
fin.read(reinterpret_cast<char *>(&t_query_num), sizeof(t_query_num));
fin.read(reinterpret_cast<char *>(&t_K), sizeof(t_K));
// if (t_query_num != query_num) {
// fprintf(stderr, "Error: query_num %u is not equal to the record %u in true-NN file %s\n",
// query_num, t_query_num, filename);
// exit(EXIT_FAILURE);
// }
if (t_query_num < num_queries_) {
fprintf(stderr, "Error: t_query_num %u is smaller than num_queries_ %u\n", t_query_num, num_queries_);
exit(EXIT_FAILURE);
}
if (t_K < 100) {
fprintf(stderr, "Error: t_K %u is smaller than 100.\n", t_K);
exit(EXIT_FAILURE);
}
// data = new unsigned[(size_t) t_query_num * (size_t) t_K];
true_nn_list.resize(t_query_num);
for (idi q_i = 0; q_i < t_query_num; ++q_i) {
true_nn_list[q_i].resize(t_K);
}
for (unsigned q_i = 0; q_i < t_query_num; ++q_i) {
// size_t offset = q_i * t_K;
for (unsigned n_i = 0; n_i < t_K; ++n_i) {
unsigned id;
float dist;
fin.read(reinterpret_cast<char *>(&id), sizeof(id));
fin.read(reinterpret_cast<char *>(&dist), sizeof(dist));
// data[offset + n_i] = id;
true_nn_list[q_i][n_i] = id;
}
}
fin.close();
}
inline void Searching::get_recall_for_all_queries(
const std::vector< std::vector<idi> > &true_nn_list,
const std::vector<std::vector<unsigned>> &set_K_list,
std::unordered_map<unsigned, double> &recalls) const
{
// if (t_K < 100) {
// fprintf(stderr, "Error: t_K %u is smaller than 100.\n", t_K);
// exit(EXIT_FAILURE);
// }
if (true_nn_list[0].size() < 100) {
fprintf(stderr, "Error: Number of true nearest neighbors of a query is smaller than 100.\n");
exit(EXIT_FAILURE);
}
recalls[1] = 0.0;
recalls[5] = 0.0;
recalls[10] = 0.0;
recalls[20] = 0.0;
recalls[50] = 0.0;
recalls[100] = 0.0;
for (unsigned q_i = 0; q_i < num_queries_; ++q_i) {
// size_t offset = q_i * t_K;
for (unsigned top_i = 0; top_i < 100; ++top_i) {
unsigned true_id = true_nn_list[q_i][top_i];
for (unsigned n_i = 0; n_i < 100; ++n_i) {
if (set_K_list[q_i][n_i] == true_id) {
if (n_i < 1) recalls[1] += 1;
if (n_i < 5) recalls[5] += 1;
if (n_i < 10) recalls[10] += 1;
if (n_i < 20) recalls[20] += 1;
if (n_i < 50) recalls[50] += 1;
if (n_i < 100) recalls[100] += 1;
}
}
}
}
recalls[1] /= 1.0 * num_queries_;
recalls[5] /= 5.0 * num_queries_;
recalls[10] /= 10.0 * num_queries_;
recalls[20] /= 20.0 * num_queries_;
recalls[50] /= 50.0 * num_queries_;
recalls[100] /= 100.0 * num_queries_;
}
inline void Searching::search_in_sequential(
const idi query_id,
const idi K,
const idi L,
std::vector<Candidate> &set_L,
const std::vector<idi> &init_ids,
std::vector<idi> &set_K)
{
// {//test
// printf("Iteration: Relative_Distance:\n");
//// printf("Iteration: Relative_Distance:\n");
//// printf("----query: %u----\n", query_id);
// }
boost::dynamic_bitset<> is_visited(num_v_);
for (idi v_i = 0; v_i < L; ++v_i) {
is_visited[init_ids[v_i]] = true;
}
const dataf *query_data = queries_load_ + query_id * dimension_;
for (idi v_i = 0; v_i < L; ++v_i) {
idi v_id = init_ids[v_i];
_mm_prefetch(opt_nsg_graph_ + v_id * vertex_bytes_, _MM_HINT_T0);
}
// Get the distances of all candidates, store in the set set_L.
for (unsigned i = 0; i < L; i++) {
unsigned v_id = init_ids[i];
auto *v_data = reinterpret_cast<dataf *>(opt_nsg_graph_ + v_id * vertex_bytes_);
dataf norm = *v_data++;
++count_distance_computation_;
distf dist = compute_distance_with_norm(v_data, query_data, norm);
set_L[i] = Candidate(v_id, dist, false); // False means not checked.
}
std::sort(set_L.begin(), set_L.begin() + L);
idi k = 0; // Index of every queue's first unchecked candidate.
idi tmp_count = 0; // for debug
// {// Print relative distance
//// distf top_dist = set_L[0].distance_;
// for (idi i_l = 0; i_l < L; ++i_l) {
// printf("%u %f\n",
// tmp_count, set_L[i_l].distance_);
//// tmp_count, set_L[i_l].distance_ - top_dist);
// }
// }
while (k < L) {
Candidate &top_cand = set_L[k];
unsigned nk = L;
if (!top_cand.is_checked_) {
++tmp_count;
top_cand.is_checked_ = true;
idi v_id = top_cand.id_; // Vertex ID.
_mm_prefetch(opt_nsg_graph_ + v_id * vertex_bytes_ + data_bytes_, _MM_HINT_T0);
idi *out_edges = (idi *) (opt_nsg_graph_ + v_id * vertex_bytes_ + data_bytes_);
idi out_degree = *out_edges++;
for (idi n_i = 0; n_i < out_degree; ++n_i) {
_mm_prefetch(opt_nsg_graph_ + out_edges[n_i] * vertex_bytes_, _MM_HINT_T0);
}
// Traverse v_id's all neighbors, pushing them into the queue
for (idi e_i = 0; e_i < out_degree; ++e_i) {
idi nb_id = out_edges[e_i];
if (is_visited[nb_id]) {
continue;
}
is_visited[nb_id] = true;
auto *nb_data = reinterpret_cast<dataf *>(opt_nsg_graph_ + nb_id * vertex_bytes_);
dataf norm = *nb_data++;
// Compute the distance
++count_distance_computation_;
distf dist = compute_distance_with_norm(nb_data, query_data, norm);
if (dist > set_L[L-1].distance_) {
continue;
}
// if (dist >= set_L[L-1].distance_) {
// continue;
// }
Candidate cand(nb_id, dist, false);
// Insert into the queue
idi r = insert_into_queue(set_L, L, cand);
if (r < nk) {
nk = r;
}
}
// {// Print relative distance
//// distf top_dist = set_L[0].distance_;
// for (idi i_l = 0; i_l < L; ++i_l) {
// printf("%u %f\n",
// tmp_count, set_L[i_l].distance_);
//// tmp_count, set_L[i_l].distance_ - top_dist);
// }
// }
}
if (nk <= k) {
k = nk;
} else {
++k;
}
}
// cache_miss_kernel.measure_stop();
for (size_t k_i = 0; k_i < K; ++k_i) {
set_K[k_i] = set_L[k_i].id_;
}
// {//test
// if (0 == query_id) {
// exit(1);
// }
// }
}
//inline void Searching::search_in_sequential_BitVector(
// const idi query_id,
// const idi K,
// const idi L,
// std::vector<Candidate> &set_L,
// const std::vector<idi> &init_ids,
// std::vector<idi> &set_K)
//{
//// boost::dynamic_bitset<> is_visited(num_v_);
// BitVector is_visited(num_v_);
//
//#pragma omp parallel for
// for (idi v_i = 0; v_i < L; ++v_i) {
//// is_visited[init_ids[v_i]] = true;
// is_visited.atomic_set_bit(init_ids[v_i]);
// }
//
// const dataf *query_data = queries_load_ + query_id * dimension_;
//
//#pragma omp parallel for
// for (idi v_i = 0; v_i < L; ++v_i) {
// idi v_id = init_ids[v_i];
// _mm_prefetch(opt_nsg_graph_ + v_id * vertex_bytes_, _MM_HINT_T0);
// }
// // Get the distances of all candidates, store in the set set_L.
//#pragma omp parallel for
// for (unsigned i = 0; i < L; i++) {
// unsigned v_id = init_ids[i];
// auto *v_data = reinterpret_cast<dataf *>(opt_nsg_graph_ + v_id * vertex_bytes_);
// dataf norm = *v_data++;
// distf dist = compute_distance_with_norm(v_data, query_data, norm);
// set_L[i] = Candidate(v_id, dist, false); // False means not checked.
// }
// std::sort(set_L.begin(), set_L.begin() + L);
// idi k = 0; // Index of every queue's first unchecked candidate.
// while (k < L) {
// Candidate &top_cand = set_L[k];
// unsigned nk = L;
// if (!top_cand.is_checked_) {
// top_cand.is_checked_ = true;
// idi v_id = top_cand.id_; // Vertex ID.
// _mm_prefetch(opt_nsg_graph_ + v_id * vertex_bytes_ + data_bytes_, _MM_HINT_T0);
// idi *out_edges = (idi *) (opt_nsg_graph_ + v_id * vertex_bytes_ + data_bytes_);
// idi out_degree = *out_edges++;
// for (idi n_i = 0; n_i < out_degree; ++n_i) {
// _mm_prefetch(opt_nsg_graph_ + out_edges[n_i] * vertex_bytes_, _MM_HINT_T0);
// }
// // Traverse v_id's all neighbors, pushing them into the queue
// for (idi e_i = 0; e_i < out_degree; ++e_i) {
// idi nb_id = out_edges[e_i];
//// if (is_visited[nb_id]) {
//// continue;
//// }
//// is_visited[nb_id] = true;
//
// {// Self-defined BitVector
// if (is_visited.atomic_is_bit_set(nb_id)) {
// continue;
// }
// is_visited.atomic_set_bit(nb_id);
// }
//
// auto *nb_data = reinterpret_cast<dataf *>(opt_nsg_graph_ + nb_id * vertex_bytes_);
// dataf norm = *nb_data++;
// // Compute the distance
// distf dist = compute_distance_with_norm(nb_data, query_data, norm);
// if (dist > set_L[L-1].distance_) {
// continue;
// }
//// if (dist >= set_L[L-1].distance_) {
//// continue;
//// }
// Candidate cand(nb_id, dist, false);
// // Insert into the queue
// idi r = insert_into_queue(set_L, L, cand);
// if (r < nk) {
// nk = r;
// }
// }
// }
// if (nk <= k) {
// k = nk;
// } else {
// ++k;
// }
// }
//// cache_miss_kernel.measure_stop();
//#pragma omp parallel for
// for (size_t k_i = 0; k_i < K; ++k_i) {
// set_K[k_i] = set_L[k_i].id_;
// }
//}
/**
* Prepare init_ids and flags, as they are constant for all queries.
* @param[out] init_ids
* @param L
*/
inline void Searching::prepare_init_ids(
std::vector<unsigned int> &init_ids,
const unsigned L) const
{
// idi num_ngbrs = get_out_degree(ep_);
// edgei edge_start = nsg_graph_indices_[ep_];
// // Store ep_'s neighbors as candidates
// idi tmp_l = 0;
// for (; tmp_l < L && tmp_l < num_ngbrs; tmp_l++) {
// init_ids[tmp_l] = nsg_graph_out_edges_[edge_start + tmp_l];
// }
// std::unordered_set<idi> visited_ids;
boost::dynamic_bitset<> is_selected(num_v_);
idi *out_edges = (idi *) (opt_nsg_graph_ + ep_ * vertex_bytes_ + data_bytes_);
idi out_degree = *out_edges++;
idi init_ids_end = 0;
// for (; tmp_l < L && tmp_l < out_degree; tmp_l++) {
for (idi e_i = 0; e_i < out_degree && init_ids_end < L; ++e_i) {
// idi v_id = out_edges[tmp_l];
idi v_id = out_edges[e_i];
if(is_selected[v_id]) {
continue;
}
is_selected[v_id] = true;
// init_ids[tmp_l] = v_id;
init_ids[init_ids_end++] = v_id;
// init_ids[tmp_l] = out_edges[tmp_l];
// visited_ids.insert(init_ids[tmp_l]);
}
// for (idi i = 0; i < tmp_l; ++i) {
// is_visited[init_ids[i]] = true;
// }
// If ep_'s neighbors are not enough, add other random vertices
idi tmp_id = ep_ + 1; // use tmp_id to replace rand().
while (init_ids_end < L) {
tmp_id %= num_v_;
idi v_id = tmp_id++;
if (is_selected[v_id]) {
continue;
}
// if (visited_ids.find(id) != visited_ids.end()) {
// continue;
// }
is_selected[v_id] = true;
// visited_ids.insert(id);
init_ids[init_ids_end++] = v_id;
// tmp_l++;
}
}
// TODO: re-code in AVX-512
inline dataf Searching::compute_norm(
const dataf *data) const
// idi vertex_id)
// const std::vector<PANNS::dataf> &data)
// size_t loc_start,
// idi dimension)
{
// const dataf *a = data.data() + loc_start;
// const dataf *a = data_load_ + vertex_id * dimension_;
// idi size = dimension_;
dataf result = 0;
//#define AVX_L2NORM(addr, dest, tmp) \
// tmp = _mm256_load_ps(addr); \
// tmp = _mm256_mul_ps(tmp, tmp); \
// dest = _mm256_add_ps(dest, tmp);
#define AVX_L2NORM(addr, dest, tmp) \
tmp = _mm256_loadu_ps(addr); \
tmp = _mm256_mul_ps(tmp, tmp); \
dest = _mm256_add_ps(dest, tmp);
__m256 sum;
__m256 l0, l1;
unsigned D = (dimension_ + 7) & ~7U;
unsigned DR = D % 16;
unsigned DD = D - DR;
const float *l = data;
const float *e_l = l + DD;
float unpack[8] __attribute__ ((aligned (32))) = {0, 0, 0, 0, 0, 0, 0, 0};
sum = _mm256_load_ps(unpack);
// sum = _mm256_loadu_ps(unpack);
if (DR) { AVX_L2NORM(e_l, sum, l0); }
for (unsigned i = 0; i < DD; i += 16, l += 16) {
AVX_L2NORM(l, sum, l0);
AVX_L2NORM(l + 8, sum, l1);
}
_mm256_store_ps(unpack, sum);
// _mm256_storeu_ps(unpack, sum);
result = unpack[0] + unpack[1] + unpack[2] + unpack[3] + unpack[4] + unpack[5] + unpack[6] + unpack[7];
return result;
}
inline dataf Searching::compute_distance_with_norm(
const dataf *v_data,
const dataf *q_data,
// idi vertex_id,
// idi query_id,
// const std::vector<PANNS::dataf> &d_data,
// const std::vector<PANNS::dataf> &q_data,
// PANNS::idi d_start,
// PANNS::idi q_start,
const dataf vertex_norm) const
// idi dimension)
{
// idi size = dimension_;
float result = 0;
//#define AVX_DOT(addr1, addr2, dest, tmp1, tmp2) \
// tmp1 = _mm256_load_ps(addr1);\
// tmp2 = _mm256_load_ps(addr2);\
// tmp1 = _mm256_mul_ps(tmp1, tmp2); \
// dest = _mm256_add_ps(dest, tmp1);
#define AVX_DOT(addr1, addr2, dest, tmp1, tmp2) \
tmp1 = _mm256_loadu_ps(addr1);\
tmp2 = _mm256_loadu_ps(addr2);\
tmp1 = _mm256_mul_ps(tmp1, tmp2); \
dest = _mm256_add_ps(dest, tmp1);
__m256 sum;
__m256 l0, l1;
__m256 r0, r1;
unsigned D = (dimension_ + 7) & ~7U;
unsigned DR = D % 16;
unsigned DD = D - DR;
const float *l = v_data;
const float *r = q_data;
// const float *l = (float *) (opt_nsg_graph_ + vertex_id * vertex_bytes_ + sizeof(distf));
// const float *r = queries_load_ + query_id * dimension_;
const float *e_l = l + DD;
const float *e_r = r + DD;
float unpack[8] __attribute__ ((aligned (32))) = {0, 0, 0, 0, 0, 0, 0, 0};
sum = _mm256_load_ps(unpack);
// sum = _mm256_loadu_ps(unpack);
if (DR) { AVX_DOT(e_l, e_r, sum, l0, r0); }
for (unsigned i = 0; i < DD; i += 16, l += 16, r += 16) {
AVX_DOT(l, r, sum, l0, r0);
AVX_DOT(l + 8, r + 8, sum, l1, r1);
}
_mm256_store_ps(unpack, sum);
// _mm256_storeu_ps(unpack, sum);
result = unpack[0] + unpack[1] + unpack[2] + unpack[3] + unpack[4] + unpack[5] + unpack[6] + unpack[7];
result = -2 * result + vertex_norm;
return result;
}
//// DEPRECATED.
// The difference from insert_into_queue is that add_into_queue will increase the queue size by 1.
//inline idi Searching::add_into_queue(
// std::vector<PANNS::Candidate> &queue,
// idi &queue_top,
// const idi queue_size,
// const PANNS::Candidate &cand)
//{
// assert(queue_size > 1);
// if (0 == queue_top) {
// queue[queue_top++] = cand;
// return 0;
// } else if (1 == queue_top) {
// if (queue[0] < cand) {
// queue[queue_top++] = cand;
// return 1;
// } else {
// queue[++queue_top] = queue[0];
// queue[0] = cand;
// return 0;
// }
// }
//
// if (queue[queue_top - 1] < cand) {
// if (queue_top < queue_size) {
// queue[queue_top++] = cand;
// }
// return queue_top;
// }
//
// idi r = insert_into_queue(
// queue,
// queue_top - 1,
// cand);
//// {//test
//// printf("r: %u"
//// "queue_top: %u "
//// "queue_size: %u\n",
//// r,
//// queue_top,
//// queue_size);
//// }
// return r;
//
//// /////////////////////////////////////////////////////////////
//// // Find the insert location
//// auto it_loc = std::lower_bound(queue.begin(), queue.begin() + queue_top, cand);
//// idi insert_loc = it_loc - queue.begin();
//// if (insert_loc == queue_size) {
//// return queue_size;
//// }
////
//// // Insert
////// if (queue_top == queue_size) {
////// // If full already
////// --queue_top;
////// }
//// memmove(reinterpret_cast<char *>(queue.data() + insert_loc + 1),
//// reinterpret_cast<char *>(queue.data() + insert_loc),
//// (queue_top - insert_loc) * sizeof(Candidate));
////// for (idi q_i = queue_top; q_i > insert_loc; --q_i) {
////// queue.at(q_i) = queue.at(q_i - 1);
////// }
//// queue[insert_loc] = cand;
//// ++queue_top;
//// return insert_loc;
//}
// The difference from insert_into_queue is that add_into_queue will increase the queue size by 1.
inline idi Searching::add_into_queue(
std::vector<PANNS::Candidate> &queue,
idi &queue_top,
const idi queue_size,
const PANNS::Candidate &cand)
{
if (0 == queue_top) {
queue[queue_top++] = cand;
return 0;
}
// Find the insert location
auto it_loc = std::lower_bound(queue.begin(), queue.begin() + queue_top, cand);
idi insert_loc = it_loc - queue.begin();
if (insert_loc == queue_size) {
return queue_size;
}
// Insert
if (queue_top == queue_size) {
// If full already
--queue_top;
}
memmove(reinterpret_cast<char *>(queue.data() + insert_loc + 1),
reinterpret_cast<char *>(queue.data() + insert_loc),
(queue_top - insert_loc) * sizeof(Candidate));
// for (idi q_i = queue_top; q_i > insert_loc; --q_i) {
// queue.at(q_i) = queue.at(q_i - 1);
// }
queue[insert_loc] = cand;
++queue_top;
return insert_loc;
}
// The difference from insert_into_queue is that add_into_queue will increase the queue size by 1.
// add_into_queue with a queue_start
inline idi Searching::add_into_queue(
std::vector<PANNS::Candidate> &queue,
const idi queue_start,
idi &queue_size, // The insertion location starting from queue_start
const idi queue_capacity, // The maximum capacity of queue, independent with queue_start.
const PANNS::Candidate &cand)
{
if (0 == queue_size) {
queue[queue_start + queue_size++] = cand;
return 0;
}
idi queue_end = queue_start + queue_size;
// Find the insert location
const auto it_loc = std::lower_bound(queue.begin() + queue_start, queue.begin() + queue_end, cand);
// auto it_loc = std::lower_bound(queue.begin(), queue.begin() + queue_size, cand);
idi insert_loc = it_loc - queue.begin();
if (insert_loc != queue_end) {
if (cand.id_ == it_loc->id_) {
// Duplicate
return queue_capacity;
}
if (queue_size >= queue_capacity) { // Queue is full
--queue_size;
--queue_end;
}
} else { // insert_loc == queue_end, insert at the end?
if (queue_size < queue_capacity) { // Queue is not full
// Insert at the end
queue[insert_loc] = cand;
++queue_size;
return queue_size - 1;
} else { // Queue is full
return queue_capacity;
}
}
// Add into queue
memmove(reinterpret_cast<char *>(queue.data() + insert_loc + 1),
reinterpret_cast<char *>(queue.data() + insert_loc),
(queue_end - insert_loc) * sizeof(Candidate));
queue[insert_loc] = cand;
++queue_size;
return insert_loc - queue_start;
}
inline void Searching::add_into_queue_at(
const Candidate &cand,
std::vector<Candidate> &queue,
const idi insert_index, // The insertion location, independent with queue_start
const idi queue_start,
idi &queue_size, // The number of elements in queue, independent with queue_start
const idi queue_length) // The maximum capacity of queue, independent with queue_start.
{
const idi dest_index = queue_start + insert_index;
if (queue_size == queue_length) {
--queue_size;
}
memmove(reinterpret_cast<char *>(queue.data() + dest_index + 1),
reinterpret_cast<char *>(queue.data() + dest_index),
(queue_size - insert_index) * sizeof(Candidate));
queue[dest_index] = cand;
++queue_size;
}
inline void Searching::insert_one_element_at(
// const T &cand,
// T *queue_base,
const Candidate &cand,
std::vector<Candidate> &queue,
const idi insert_index,
const idi queue_start,
const idi queue_size)
{
const idi dest_index = queue_start + insert_index;
memmove(reinterpret_cast<char *>(queue.data() + dest_index + 1),
reinterpret_cast<char *>(queue.data() + dest_index),
(queue_size - insert_index - 1) * sizeof(Candidate));
queue[dest_index] = cand;
// memmove(reinterpret_cast<char *>(queue_base + dest_index + 1),
// reinterpret_cast<char *>(queue_base + dest_index),
// (queue_size - insert_index - 1) * sizeof(T));
// for (idi q_i = queue_size - 1; q_i > insert_index; --q_i) {
// queue_base.at(q_i + queue_start) = queue_base.at(q_i - 1 + queue_start);
// }
// queue_base[dest_index] = cand;
}
/**
* PANNS version of InsertIntoPool(): binary-search to find the insert place and then move.
* @param[out] c_queue
* @param c_queue_top
* @param cand
* @return
*/
inline idi Searching::insert_into_queue(
std::vector<PANNS::Candidate> &c_queue,
PANNS::idi c_queue_top,
PANNS::Candidate cand)
{
if (c_queue[0].distance_ > cand.distance_) {
// If the first
memmove(reinterpret_cast<char *>(c_queue.data() + 1),
reinterpret_cast<char *>(c_queue.data()),
c_queue_top * sizeof(Candidate));
c_queue[0] = cand;
return 0;
} else if (c_queue[c_queue_top - 1].distance_ == cand.distance_) {
// If the last
if (c_queue[c_queue_top - 1].id_ > cand.id_) {
// Use ID as the second metrics for ordering
c_queue[c_queue_top - 1] = cand;
return c_queue_top - 1;
} else {
return c_queue_top;
}
}
idi left = 0;
idi right = c_queue_top;
while (left < right) {
idi mid = (right - left) / 2 + left;
if (c_queue[mid].distance_ > cand.distance_) {
right = mid;
} else {
left = mid + 1;
}
}
// If the distance is the same
if (0 != left && c_queue[left - 1].distance_ != cand.distance_) {
;
} else {
while (0 != left
&& c_queue[left - 1].distance_ == cand.distance_
&& c_queue[left - 1].id_ > cand.id_) {
// Use ID as the second metrics for ordering
--left;
}
}
// Insert to left
memmove(reinterpret_cast<char *>(c_queue.data() + left + 1),
reinterpret_cast<char *>(c_queue.data() + left),
(c_queue_top - left) * sizeof(Candidate));
c_queue[left] = cand;
return left;
}
//inline void Searching::cand_pushes_ngbrs_into_queue(
// idi cand_id,
// const dataf *query_data,
// idi L,
// idi &new_k,
// boost::dynamic_bitset<> &is_visited,
// std::vector<Candidate> &set_L)
//{
// _mm_prefetch(opt_nsg_graph_ + v_id * vertex_bytes_ + data_bytes_, _MM_HINT_T0);
// idi *out_edges = (idi *) (opt_nsg_graph_ + v_id * vertex_bytes_ + data_bytes_);
// idi out_degree = *out_edges++;
// for (idi n_i = 0; n_i < out_degree; ++n_i) {
// _mm_prefetch(opt_nsg_graph_ + out_edges[n_i] * vertex_bytes_, _MM_HINT_T0);
// }
// for (idi e_i = 0; e_i < out_degree; ++e_i) {
// idi nb_id = out_edges[e_i];
// if (is_visited[nb_id]) {
// continue;
// }
// is_visited[nb_id] = true;
// auto *nb_data = reinterpret_cast<dataf *>(opt_nsg_graph_ + nb_id * vertex_bytes_);
// dataf norm = *nb_data++;
// distf dist = compute_distance_with_norm(nb_data, query_data, norm);
// if (dist >= set_L[L-1].distance_) {
// continue;
// }
// Candidate cand(nb_id, dist, false);
// idi r = insert_into_queue(set_L, L, cand);
// if (r < nk) {
// nk = r;
// }
// }
//}
//inline void Searching::search_in_sequential(
// const idi query_id,
// const idi K,
// const idi L,
// std::vector<Candidate> &set_L,
// const std::vector<idi> &init_ids,
// std::vector<idi> &set_K) const
//{
// boost::dynamic_bitset<> is_visited(num_v_);
//
// for (idi v_i = 0; v_i < L; ++v_i) {
// is_visited[init_ids[v_i]] = true;
// }
// const dataf *query_data = queries_load_ + query_id * dimension_;
//
// for (idi v_i = 0; v_i < L; ++v_i) {
// idi v_id = init_ids[v_i];
// _mm_prefetch(opt_nsg_graph_ + v_id * vertex_bytes_, _MM_HINT_T0);
// }
// // Get the distances of all candidates, store in the set set_L.
// for (unsigned i = 0; i < L; i++) {
// unsigned v_id = init_ids[i];
// auto *v_data = reinterpret_cast<dataf *>(opt_nsg_graph_ + v_id * vertex_bytes_);
// dataf norm = *v_data++;
// distf dist = compute_distance_with_norm(v_data, query_data, norm);
// set_L[i] = Candidate(v_id, dist, false); // False means not checked.
// }
// std::sort(set_L.begin(), set_L.begin() + L);
// idi k = 0; // Index of every queue's first unchecked candidate.
// while (k < L) {
// Candidate &top_cand = set_L[k];
// unsigned nk = L;
// if (!top_cand.is_checked_) {
// top_cand.is_checked_ = true;
// idi v_id = top_cand.id_; // Vertex ID.
// _mm_prefetch(opt_nsg_graph_ + v_id * vertex_bytes_ + data_bytes_, _MM_HINT_T0);
// idi *out_edges = (idi *) (opt_nsg_graph_ + v_id * vertex_bytes_ + data_bytes_);
// idi out_degree = *out_edges++;
// for (idi n_i = 0; n_i < out_degree; ++n_i) {
// _mm_prefetch(opt_nsg_graph_ + out_edges[n_i] * vertex_bytes_, _MM_HINT_T0);
// }
// // Traverse v_id's all neighbors, pushing them into the queue
// for (idi e_i = 0; e_i < out_degree; ++e_i) {
// idi nb_id = out_edges[e_i];
// if (is_visited[nb_id]) {
// continue;
// }
// is_visited[nb_id] = true;
// auto *nb_data = reinterpret_cast<dataf *>(opt_nsg_graph_ + nb_id * vertex_bytes_);
// dataf norm = *nb_data++;
// // Compute the distance
// distf dist = compute_distance_with_norm(nb_data, query_data, norm);
// if (dist > set_L[L-1].distance_) {
// continue;
// }
// Candidate cand(nb_id, dist, false);
// // Insert into the queue
// idi r = insert_into_queue(set_L, L, cand);
// if (r < nk) {
// nk = r;
// }
// }
// }
// if (nk <= k) {
// k = nk;
// } else {
// ++k;
// }
// }
//
// for (size_t k_i = 0; k_i < K; ++k_i) {
// set_K[k_i] = set_L[k_i].id_;
// }
//}
// Deprecated: cannot use std::set, because its element is constant.
//inline void Searching::search_in_sequential(
// const idi query_id,
// const idi K,
// const idi L,
//// std::vector<Candidate> &set_L,
// const std::vector<idi> &init_ids,
// std::vector<idi> &set_K) const
//{
// std::set<Candidate> set_L;
// boost::dynamic_bitset<> is_visited(num_v_);
//
// for (idi v_i = 0; v_i < L; ++v_i) {
// is_visited[init_ids[v_i]] = true;
// }
// const dataf *query_data = queries_load_ + query_id * dimension_;
//
// for (idi v_i = 0; v_i < L; ++v_i) {
// idi v_id = init_ids[v_i];
// _mm_prefetch(opt_nsg_graph_ + v_id * vertex_bytes_, _MM_HINT_T0);
// }
// // Get the distances of all candidates, store in the set set_L.
// for (unsigned i = 0; i < L; i++) {
// unsigned v_id = init_ids[i];
// auto *v_data = reinterpret_cast<dataf *>(opt_nsg_graph_ + v_id * vertex_bytes_);
// dataf norm = *v_data++;
// distf dist = compute_distance_with_norm(v_data, query_data, norm);
//// set_L[i] = Candidate(v_id, dist, false); // False means not checked.
// set_L.emplace(v_id, dist, false);
// }
//// std::sort(set_L.begin(), set_L.begin() + L);
// idi k = 0; // Index of every queue's first unchecked candidate.
// while (k < L) {
//// Candidate &top_cand = set_L[k];
// std::set<Candidate>::iterator top_cand = std::next(set_L.begin(), k);
// unsigned nk = L;
// if (!top_cand->is_checked_) {
// top_cand->is_checked_ = true;
// idi v_id = top_cand.id_; // Vertex ID.
// _mm_prefetch(opt_nsg_graph_ + v_id * vertex_bytes_ + data_bytes_, _MM_HINT_T0);
// idi *out_edges = (idi *) (opt_nsg_graph_ + v_id * vertex_bytes_ + data_bytes_);
// idi out_degree = *out_edges++;
// for (idi n_i = 0; n_i < out_degree; ++n_i) {
// _mm_prefetch(opt_nsg_graph_ + out_edges[n_i] * vertex_bytes_, _MM_HINT_T0);
// }
// // Traverse v_id's all neighbors, pushing them into the queue
// for (idi e_i = 0; e_i < out_degree; ++e_i) {
// idi nb_id = out_edges[e_i];
// if (is_visited[nb_id]) {
// continue;
// }
// is_visited[nb_id] = true;
// auto *nb_data = reinterpret_cast<dataf *>(opt_nsg_graph_ + nb_id * vertex_bytes_);
// dataf norm = *nb_data++;
// // Compute the distance
// distf dist = compute_distance_with_norm(nb_data, query_data, norm);
// if (dist > set_L[L-1].distance_) {
// continue;
// }
// Candidate cand(nb_id, dist, false);
// // Insert into the queue
// idi r = insert_into_queue(set_L, L, cand);
// if (r < nk) {
// nk = r;
// }
// }
// }
// if (nk <= k) {
// k = nk;
// } else {
// ++k;
// }
// }
//
// for (size_t k_i = 0; k_i < K; ++k_i) {
// set_K[k_i] = set_L[k_i].id_;
// }
//}
/* Function:
* queue1_size is fixed.
*/
inline idi Searching::merge_two_queues_into_1st_queue_seq_fixed(
std::vector<Candidate> &queue1,
const idi queue1_start,
const idi queue1_size,
std::vector<Candidate> &queue2,
const idi queue2_start,
const idi queue2_size)
// const idi limit_size)
{
assert(queue1_size && queue2_size);
// Record the lowest insert location.
auto it_loc = std::lower_bound(
queue1.begin() + queue1_start,
queue1.begin() + queue1_start + queue1_size,
queue2[queue2_start]);
idi insert_index = it_loc - (queue1.begin() + queue1_start);
if (insert_index == queue1_size) {
return insert_index;
} else if (insert_index == queue1_size - 1) {
queue1[queue1_start + insert_index] = queue2[queue2_start];
return insert_index;
}
// Insert the 1st of queue2
if (queue2[queue2_start].id_ != it_loc->id_) {
// Not Duplicate
insert_one_element_at(
queue2[queue2_start],
queue1,
insert_index,
queue1_start,
queue1_size);
}
if (queue2_size == 1) {
return insert_index;
}
// Insert
idi q_i_1 = insert_index + 1 + queue1_start;
idi q_i_2 = queue2_start + 1;
const idi q_i_1_bound = queue1_start + queue1_size;
const idi q_i_2_bound = queue2_start + queue2_size;
// const idi insert_i_bound = queue1_start + limit_size;
for (idi insert_i = insert_index + 1; insert_i < queue1_size; ++insert_i) {
if (q_i_1 >= q_i_1_bound || q_i_2 >= q_i_2_bound) {
// queue1 or queue2 finished traverse. Rest o
break;
} else if (queue1[q_i_1] < queue2[q_i_2]) {
++q_i_1;
} else if (queue2[q_i_2] < queue1[q_i_1]) {
// Insert queue2[q_i_2] into queue1
insert_one_element_at(
queue2[q_i_2++],
queue1,
insert_i,
queue1_start,
queue1_size);
++q_i_1;
} else {
// Duplicate
++q_i_2;
++q_i_1;
}
}
return insert_index;
}
/* Function:
* queue1_size should be updated.
* queue1_length should be provided.
*/
inline void Searching::merge_two_queues_into_1st_queue_seq_incr(
std::vector<Candidate> &queue1,
const idi queue1_start,
idi &queue1_size, // The number of element in queue1, independent with queue1_start.
const idi queue1_length, // The maximum capacity of queue1, independent with queue1_start.
std::vector<Candidate> &queue2,
const idi queue2_start,
const idi queue2_size)
// const idi limit_size)
{
assert(queue1_size && queue2_size);
// Record the lowest insert location.
auto it_loc = std::lower_bound(
queue1.begin() + queue1_start,
queue1.begin() + queue1_start + queue1_size,
queue2[queue2_start]);
idi insert_index = it_loc - (queue1.begin() + queue1_start);
if (insert_index == queue1_size) {
idi copy_count = (queue1_size + queue2_size > queue1_length) ?
queue1_length - queue1_size :
queue2_size;
memmove(queue1.data() + queue1_start + queue1_size,
queue2.data() + queue2_start,
copy_count * sizeof(Candidate));
queue1_size += copy_count;
return;
}
if (queue2[queue2_start].id_ != it_loc->id_) {
// Not Duplicate
add_into_queue_at(
queue2[queue2_start],
queue1,
insert_index,
queue1_start,
queue1_size,
queue1_length);
}
if (queue2_size == 1) {
return;
}
// Insert
idi q_i_1 = insert_index + 1 + queue1_start;
idi q_i_2 = queue2_start + 1;
idi q_i_1_bound = queue1_start + queue1_size; // When queue1_size is updated, so should be q_i_1_bound.
const idi q_i_2_bound = queue2_start + queue2_size;
// idi insert_i;
for (idi insert_i = insert_index + 1; insert_i < queue1_length; ++insert_i) {
if (q_i_1 >= q_i_1_bound) {
queue1_size += std::min(queue1_length - insert_i, q_i_2_bound - q_i_2);
for ( ; insert_i < queue1_size; ++insert_i) {
queue1[queue1_start + insert_i] = queue2[q_i_2++];
}
break;
} else if (q_i_2 >= q_i_2_bound) {
break;
} else if (queue1[q_i_1] < queue2[q_i_2]) {
++q_i_1;
} else if (queue2[q_i_2] < queue1[q_i_1]) {
add_into_queue_at(
queue2[q_i_2++],
queue1,
insert_i,
queue1_start,
queue1_size,
queue1_length);
++q_i_1;
q_i_1_bound = queue1_start + queue1_size;
} else {
// Duplicate
++q_i_2;
++q_i_1;
}
}
}
inline idi Searching::merge_all_queues_para_list(
std::vector< std::vector<Candidate> > &local_queues_list,
std::vector<idi> &local_queues_ends,
std::vector<Candidate> &set_L,
const idi L)
{
int size = 1 << (static_cast<idi>(log2(num_threads_)));
idi log2size = static_cast<idi>(log2(size));
for (idi d = 0; d < log2size; ++d) {
uint32_t by = 1 << (d + 1);
#pragma omp parallel for
for (int i = 0; i < size; i += by) {
idi ai = i + (1 << (d + 1)) - 1; // i + 2^(d+1) - 1
idi bi = i + (1 << d) - 1; // i + 2^d - 1
if (0 == local_queues_ends[bi]) {
continue;
}
if (local_queues_ends[ai] == 0) {
local_queues_list[ai].swap(local_queues_list[bi]);
std::swap(local_queues_ends[ai], local_queues_ends[bi]);
continue;
}
// else if (local_queues_ends[ai] < L && local_queues_ends[bi] >= L) {
// local_queues_list[ai].swap(local_queues_list[bi]);
// std::swap(local_queues_ends[ai], local_queues_ends[bi]);
// }
// merge_two_queues_into_1st_queue_seq(
// local_queues_list[ai],
// 0,
// local_queues_ends[ai],
// local_queues_list[bi],
// 0,
// local_queues_ends[bi]);
idi tmp_length = local_queues_ends[ai] + local_queues_ends[bi];
std::vector<Candidate> tmp_queue(tmp_length);
std::merge(
local_queues_list[ai].begin(),
local_queues_list[ai].begin() + local_queues_ends[ai],
local_queues_list[bi].begin(),
local_queues_list[bi].begin() + local_queues_ends[bi],
tmp_queue.begin());
if (tmp_length > L) {
tmp_queue.resize(L);
tmp_length = L;
} else if (tmp_length < L) {
tmp_queue.resize(L);
}
local_queues_list[ai].swap(tmp_queue);
local_queues_ends[ai] = tmp_length;
// {// Print queue a
// printf("d: %u "
// "i: %u "
// "ai: %u "
// "local_queues_ends[%d]: %d\n",
// d,
// i,
// ai,
// ai,
// local_queues_ends[ai]);
// for (idi i_q = 0; i_q < local_queues_ends[ai]; ++i_q) {
// printf("[%u]: "
// "id: %u "
// "dist: %f\n",
// i_q,
// local_queues_list[ai][i_q].id_,
// local_queues_list[ai][i_q].distance_);
// }
// }
}
}
// Remain, prefix-sum-like merge
if (size != num_threads_) {
for (int i = size; i < num_threads_; ++i) {
idi ai = i;
idi bi = i - 1;
if (0 == local_queues_ends[bi]) {
continue;
}
if (local_queues_ends[ai] == 0) {
local_queues_list[ai].swap(local_queues_list[bi]);
std::swap(local_queues_ends[ai], local_queues_ends[bi]);
continue;
}
// else if (local_queues_ends[ai] < L && local_queues_ends[bi] >= L) {
// local_queues_list[ai].swap(local_queues_list[bi]);
// std::swap(local_queues_ends[ai], local_queues_ends[bi]);
// }
// merge_two_queues_into_1st_queue_seq(
// local_queues_list[ai],
// 0,
// local_queues_ends[ai],
// local_queues_list[bi],
// 0,
// local_queues_ends[bi]);
idi tmp_length = local_queues_ends[ai] + local_queues_ends[bi];
std::vector<Candidate> tmp_queue(tmp_length);
std::merge(
local_queues_list[ai].begin(),
local_queues_list[ai].begin() + local_queues_ends[ai],
local_queues_list[bi].begin(),
local_queues_list[bi].begin() + local_queues_ends[bi],
tmp_queue.begin());
if (tmp_length > L) {
tmp_queue.resize(L);
tmp_length = L;
} else if (tmp_length < L) {
tmp_queue.resize(L);
}
local_queues_list[ai].swap(tmp_queue);
local_queues_ends[ai] = tmp_length;
}
}
// Merge into set_L
idi r = L;
if (local_queues_ends[num_threads_ - 1]) {
r = merge_two_queues_into_1st_queue_seq_fixed(
set_L,
0,
L,
local_queues_list[num_threads_ - 1],
0,
local_queues_ends[num_threads_ - 1]);
}
// Reset local_queues_ends
std::fill(local_queues_ends.begin(), local_queues_ends.end(), 0);
return r;
}
/* Function:
* Use large local_queues_array as a concatenation of all queues
*/
inline idi Searching::merge_all_queues_para_array(
std::vector<Candidate> &set_L,
std::vector<idi> &local_queues_ends,
const idi local_queue_length,
const idi L)
{
const int num_queues = num_threads_;
idi nk = L;
int size = 1 << (static_cast<idi>(log2(num_queues)));
idi log2size = static_cast<idi>(log2(size));
for (idi d = 0; d < log2size; ++d) {
uint32_t by = 1 << (d + 1);
#pragma omp parallel for
for (int i = 0; i < size; i += by) {
idi ai = i + (1 << (d + 1)) - 1; // i + 2^(d+1) - 1
idi a_start = ai * local_queue_length;
idi bi = i + (1 << d) - 1; // i + 2^d - 1
idi b_start = bi * local_queue_length;
if (0 == local_queues_ends[bi]) {
continue;
}
if (local_queues_ends[ai] == 0) {
std::copy(set_L.begin() + b_start,
set_L.begin() + b_start + local_queues_ends[bi],
set_L.begin() + a_start); // Copy bi to ai
local_queues_ends[ai] = local_queues_ends[bi];
local_queues_ends[bi] = 0;
continue;
}
if (ai != static_cast<idi>(num_queues - 1)) {
merge_two_queues_into_1st_queue_seq_incr(
set_L,
a_start,
local_queues_ends[ai],
local_queue_length,
set_L,
b_start,
local_queues_ends[bi]);
} else {
idi r = merge_two_queues_into_1st_queue_seq_fixed(
set_L,
a_start,
L,
set_L,
b_start,
local_queues_ends[bi]);
if (r < nk) {
nk = r;
}
}
}
}
// Remain, prefix-sum-like merge
if (size != num_queues) {
for (int i = size; i < num_queues; ++i) {
idi ai = i;
idi a_start = ai * local_queue_length;
idi bi = i - 1;
idi b_start = bi * local_queue_length;
if (0 == local_queues_ends[bi]) {
continue;
}
if (local_queues_ends[ai] == 0) {
std::copy(set_L.begin() + b_start,
set_L.begin() + b_start + local_queues_ends[bi],
set_L.begin() + a_start); // Copy bi to ai
local_queues_ends[ai] = local_queues_ends[bi];
local_queues_ends[bi] = 0;
continue;
}
if (ai != static_cast<idi>(num_queues - 1)) {
merge_two_queues_into_1st_queue_seq_incr(
set_L,
a_start,
local_queues_ends[ai],
local_queue_length,
set_L,
b_start,
local_queues_ends[bi]);
} else {
idi r = merge_two_queues_into_1st_queue_seq_fixed(
set_L,
a_start,
L,
set_L,
b_start,
local_queues_ends[bi]);
if (r < nk) {
nk = r;
}
}
}
}
// Reset local_queues_ends
// Not do this for Collector Idea or Selecting Idea
std::fill(local_queues_ends.begin(), local_queues_ends.end() - 1, 0);
// std::fill(local_queues_ends.begin(), local_queues_ends.end(), 0);
return nk;
// return r;
}
/* Function:
* When merge all queues (in an array, and [num_threads_ - 1] is the global queue),
* the starting local is at [queue_base]
*/
inline idi Searching::merge_all_queues_queue_base(
// std::vector< std::vector<Candidate> > &local_queues_list,
std::vector<Candidate> &set_L,
// std::vector<Candidate> &local_queues_array,
std::vector<idi> &local_queues_ends,
const idi queue_base,
const int real_threads,
const idi local_queue_length,
// std::vector<Candidate> &set_L,
const idi L)
{
idi nk = L;
int size = 1 << (static_cast<idi>(log2(real_threads)));
// int size = 1 << (static_cast<idi>(log2(num_threads_)));
idi log2size = static_cast<idi>(log2(size));
for (idi d = 0; d < log2size; ++d) {
idi by = 1 << (d + 1);
idi i_bound = size + queue_base;
#pragma omp parallel for num_threads(real_threads)
for (idi i = queue_base; i < i_bound; i += by) {
// for (int i = 0; i < size; i += by) {
// idi ai = i + (1 << (d + 1)) - 1 + queue_base; // i + 2^(d+1) - 1
idi ai = i + (1 << (d + 1)) - 1; // i + 2^(d+1) - 1
idi a_start = ai * local_queue_length;
// idi bi = i + (1 << d) - 1 + queue_base; // i + 2^d - 1
idi bi = i + (1 << d) - 1; // i + 2^d - 1
idi b_start = bi * local_queue_length;
if (0 == local_queues_ends[bi]) {
continue;
}
if (local_queues_ends[ai] == 0) {
// local_queues_list[ai].swap(local_queues_list[bi]);
std::copy(set_L.begin() + b_start,
set_L.begin() + b_start + local_queues_ends[bi],
set_L.begin() + a_start); // Copy bi to ai
local_queues_ends[ai] = local_queues_ends[bi];
local_queues_ends[bi] = 0;
continue;
}
if (ai != static_cast<idi>(num_threads_ - 1)) {
merge_two_queues_into_1st_queue_seq_incr(
set_L,
a_start,
local_queues_ends[ai],
local_queue_length,
set_L,
b_start,
local_queues_ends[bi]);
} else {
idi r = merge_two_queues_into_1st_queue_seq_fixed(
set_L,
a_start,
L,
set_L,
b_start,
local_queues_ends[bi]);
if (r < nk) {
nk = r;
}
}
}
}
// Remain, prefix-sum-like merge
if (size != real_threads) {
// if (size != num_threads_) {
for (int i = size + queue_base; i < num_threads_; ++i) {
// for (int i = size; i < num_threads_; ++i) {
idi ai = i;
idi a_start = ai * local_queue_length;
idi bi = i - 1;
idi b_start = bi * local_queue_length;
if (0 == local_queues_ends[bi]) {
continue;
}
if (local_queues_ends[ai] == 0) {
std::copy(set_L.begin() + b_start,
set_L.begin() + b_start + local_queues_ends[bi],
set_L.begin() + a_start); // Copy bi to ai
local_queues_ends[ai] = local_queues_ends[bi];
local_queues_ends[bi] = 0;
continue;
}
if (ai != static_cast<idi>(num_threads_ - 1)) {
merge_two_queues_into_1st_queue_seq_incr(
set_L,
a_start,
local_queues_ends[ai],
local_queue_length,
set_L,
b_start,
local_queues_ends[bi]);
} else {
idi r = merge_two_queues_into_1st_queue_seq_fixed(
set_L,
a_start,
L,
set_L,
b_start,
local_queues_ends[bi]);
if (r < nk) {
nk = r;
}
}
}
}
// Reset local_queues_ends
std::fill(local_queues_ends.begin(), local_queues_ends.end() - 1, 0);
// std::fill(local_queues_ends.begin(), local_queues_ends.end(), 0);
return nk;
// return r;
}
inline void Searching::merge_two_consecutive_queues_in_place(
std::vector<Candidate> &two_queues,
const idi base_1,
// const idi &end_1,
const idi base_2,
const idi &length_2)
{
// idi tid = omp_get_thread_num();
idi index_1 = base_1;
idi index_2 = base_2;
const idi bound_2 = base_2 + length_2;
while (index_1 < index_2
&& index_2 < bound_2) {
Candidate e_1 = two_queues[index_1];
Candidate e_2 = two_queues[index_2];
if (e_1 < e_2) {
++index_1;
} else if (e_2 < e_1) {
// time_memmove_list_[tid] -= WallTimer::get_time_mark();
std::memmove(two_queues.data() + index_1 + 1,
two_queues.data() + index_1,
(index_2 - index_1) * sizeof(Candidate));
// time_memmove_list_[tid] += WallTimer::get_time_mark();
two_queues[index_1] = e_2;
++index_1;
++index_2;
} else { // Duplicate, but have no idea what to do right now
// time_memmove_list_[tid] -= WallTimer::get_time_mark();
std::memmove(two_queues.data() + index_1 + 1,
two_queues.data() + index_1,
(index_2 - index_1) * sizeof(Candidate));
// time_memmove_list_[tid] += WallTimer::get_time_mark();
index_1 += 2;
++index_2;
}
}
}
///* Function:
// * Merge all queues to the global queue, in a two-queue-merge way
// */
//inline idi Searching::merge_all_queues_all_together_in_sequential(
// std::vector<Candidate> &set_L,
// std::vector<idi> &local_queues_ends,
// const idi local_queue_length,
// const idi L)
//{
// const idi num_queues = num_threads_;
// const idi global_queue_base = (num_queues - 1) * local_queue_length;
// std::vector<idi> queue_heads(num_queues, 0);
// idi queue_id_min;
//
//// bool is_finished = false;
// bool is_1st_selected = true;
// idi nk = L; // The highest location of insertion.
// {
// for (idi q_i = 0; q_i < num_queues; ++q_i) {
// if (0 == local_queues_ends[q_i]) {
// continue;
// }
// _mm_prefetch(set_L.data() + q_i * local_queue_length, _MM_HINT_T0);
// }
// }
// while (queue_heads[num_queues - 1] < L) {
//// time_compare_minimum_ -= WallTimer::get_time_mark();
// queue_id_min = min_all_queues_at_heads(
// set_L,
// queue_heads,
// local_queues_ends,
// local_queue_length,
// L);
//// time_compare_minimum_ += WallTimer::get_time_mark();
// if (queue_id_min != num_queues - 1) { // Not in the global queue
//// time_insert_ -= WallTimer::get_time_mark();
// insert_one_element_at(
// set_L[queue_heads[queue_id_min] + queue_id_min * local_queue_length],
// set_L,
// queue_heads[num_queues - 1],
// global_queue_base,
// L);
//// time_insert_ += WallTimer::get_time_mark();
// if (is_1st_selected) { // Get the highest inserting location
// is_1st_selected = false;
// nk = queue_heads[num_queues - 1];
// }
// ++queue_heads[queue_id_min];
// }
// ++queue_heads[num_queues - 1];
// }
//
// // Reset local_queues_ends
// std::fill(local_queues_ends.begin(), local_queues_ends.end() - 1, 0);
// return nk;
//}
///* Function:
// * Find the minimum among queues at their head locations
// */
//inline idi Searching::min_all_queues_at_heads(
// const std::vector<Candidate> &set_L,
// std::vector<idi> &queue_heads,
// const std::vector<idi> &local_queues_ends,
// const idi local_queue_length,
// const idi L)
//{
// const idi num_queues = num_threads_;
// idi min_queue_id = num_queues - 1;
// Candidate min_candidate = set_L[queue_heads[min_queue_id] + min_queue_id * local_queue_length];
//
// for (idi q_i = 0; q_i < num_queues - 1; ++q_i) {
// if (queue_heads[q_i] >= local_queues_ends[q_i]) { // q_i finished
// continue;
// }
// const Candidate &ele = set_L[queue_heads[q_i] + q_i * local_queue_length];
// if (ele < min_candidate) {
// min_candidate = ele;
// min_queue_id = q_i;
// } else if (ele.id_ == min_candidate.id_) { // Redundant element
// ++queue_heads[q_i];
// }
// }
//
// return min_queue_id;
//}
inline void Searching::merge_in_set_L(
std::vector<Candidate> &set_L,
const idi set_L_length,
const idi num_queues,
const idi local_queue_length)
{
idi size = 1 << (static_cast<idi>(log2(num_queues)));
idi log2size = static_cast<idi>(log2(size));
for (idi d = 0; d < log2size; ++d) {
const idi merge_length = (local_queue_length << d);
idi by = 1 << (d + 1);
// Parallel for
#pragma omp parallel for
for (idi i = 0; i < size; i += by) {
// idi a = i + (1 << d) - 1;
// idi b = i + (1 << (d + 1)) - 1;
idi a = i;
idi b = i + (1 << d);
idi base_a = a * local_queue_length;
idi base_b = b * local_queue_length;
if (base_a >= set_L_length || base_b >= set_L_length) {
continue;
}
idi length_b;
if (a + by < size) {
length_b = merge_length;
} else { // The last one
if (size == num_queues) {
length_b = set_L_length - base_b;
} else {
length_b = merge_length;
}
}
// printf("a: %u b: %u "
// "base_a: %u base_b: %u length_b: %u\n",
// a, b,
// base_a, base_b, length_b);
merge_two_consecutive_queues_in_place(
set_L,
base_a,
base_b,
length_b);
}
}
if (size != num_queues) {
for (idi i = size; i < num_queues; ++i) {
idi a = 0;
idi b = i;
idi base_a = a;
idi base_b = b * local_queue_length;
if (base_b >= set_L_length) {
continue;
}
idi length_b;
if (b != num_queues - 1) {
length_b = local_queue_length;
} else {
length_b = set_L_length - base_b;
}
// printf("a: %u b: %u "
// "base_a: %u base_b: %u length_b: %u\n",
// a, b,
// base_a, base_b, length_b);
merge_two_consecutive_queues_in_place(
set_L,
base_a,
base_b,
length_b);
}
}
}
/*
* 7/5/2020-20:27
* Every queue keeps only elements which can be ordered in the top-L globally.
* local_queues_lengths records the end location for all queues
*/
inline distf Searching::selecting_top_L_seq(
std::vector<Candidate> &set_L,
const idi global_L,
const idi num_queues,
const std::vector<idi> &local_queues_starts,
std::vector<idi> &local_queues_sizes)
{
std::vector<idi> pointers(num_queues, 0);
distf bound_lth;
idi rank = 0;
bool is_finished = false;
distf min_dist = FLT_MAX;
idi min_q_i;
idi min_id;
while (rank < global_L) {
is_finished = true;
min_dist = FLT_MAX;
for (idi q_i = 0; q_i < num_queues; ++q_i) {
if (pointers[q_i] >= local_queues_sizes[q_i]) {
// q_i is finished
continue;
}
is_finished = false;
idi sub = pointers[q_i] + local_queues_starts[q_i];
distf tmp_dist = set_L[sub].distance_;
idi tmp_id = set_L[sub].id_;
if (tmp_dist < min_dist) {
min_dist = tmp_dist;
min_id = tmp_id;
min_q_i = q_i;
} else if (tmp_dist == min_dist && tmp_id < min_id) {
min_id = tmp_id;
min_q_i = q_i;
}
}
if (is_finished) {
{//test
printf("Error: selecting_top_L_seq: only found %u elements but global_L is %u.\n",
rank,
global_L);
}
break;
}
bound_lth = min_dist;
++pointers[min_q_i];
++rank;
}
std::copy(pointers.begin(), pointers.end(), local_queues_sizes.begin());
return bound_lth;
}
/*
* 7/24/2020-10:08
* Record for every queue the position that contains the top-M unchecked vertices.
* So the total expanded vertices should still be M, which means the computation should
* be the same with merging idea.
*/
inline void Searching::selecting_unchecked_top_M_seq(
const idi query_id,
const idi iter,
std::vector<Candidate> &set_L,
const std::vector<idi> &pointers_starts,
const idi value_M,
const idi num_queues,
const std::vector<idi> &local_queues_starts,
const std::vector<idi> &local_queues_sizes,
std::vector<idi> &local_m_counts)
{
std::vector<idi> pointers(pointers_starts);
// std::vector<idi> pointers(num_queues, 0);
std::fill(local_m_counts.begin(), local_m_counts.end(), 0);
idi rank = 0;
bool is_finished = true;
distf min_dist = FLT_MAX;
idi min_q_i;
idi min_id;
while (rank < value_M) {
min_dist = FLT_MAX;
for (idi q_i = 0; q_i < num_queues; ++q_i) {
idi &pointer = pointers[q_i];
idi sub = pointer + local_queues_starts[q_i];
// {//test
// if (133 == query_id &&
// 3 == iter &&
// 321341 == set_L[sub].id_) {
// printf("(%u %f)\n",
// set_L[sub].id_, set_L[sub].distance_);
// }
// }
while (pointer < local_queues_sizes[q_i]
&& set_L[sub].is_checked_) {
++pointer;
++sub;
}
if (pointer >= local_queues_sizes[q_i]) {
// q_i is finished
continue;
}
is_finished = false;
distf tmp_dist = set_L[sub].distance_;
idi tmp_id = set_L[sub].id_;
if (tmp_dist < min_dist) {
min_dist = tmp_dist;
min_id = tmp_id;
min_q_i = q_i;
} else if (tmp_dist == min_dist && tmp_id < min_id) {
min_id = tmp_id;
min_q_i = q_i;
}
}
if (!is_finished) {
is_finished = true;
++pointers[min_q_i];
++rank;
++local_m_counts[min_q_i];
} else {
break;
}
}
// std::copy(pointers.begin(), pointers.end(), local_top_m_positions.begin());
}
/*
* 7/27/2020-15:41
* Gather the top-M unchecked vertices from local queues.
*/
inline void Searching::gather_unchecked_top_M_seq(
const idi query_id,
const idi iter,
std::vector<Candidate> &set_L,
const std::vector<idi> &pointers_starts,
const idi value_M,
const idi num_queues,
const std::vector<idi> &local_queues_starts,
const std::vector<idi> &local_queues_sizes,
std::vector<idi> &top_m_candidates,
idi &top_m_candidates_size,
std::vector<idi> &bound_subs)
{
std::vector<idi> pointers(pointers_starts);
// std::vector<idi> pointers(num_queues, 0);
// std::fill(local_m_counts.begin(), local_m_counts.end(), 0);
// idi rank = 0;
bool is_finished = true;
distf min_dist = FLT_MAX;
idi min_q_i;
idi min_id;
while (top_m_candidates_size < value_M) {
min_dist = FLT_MAX;
for (idi q_i = 0; q_i < num_queues; ++q_i) {
idi &pointer = pointers[q_i];
idi sub = pointer + local_queues_starts[q_i];
while (pointer < local_queues_sizes[q_i]
&& set_L[sub].is_checked_) {
++pointer;
++sub;
}
if (pointer >= local_queues_sizes[q_i]) {
// q_i is finished
continue;
}
is_finished = false;
distf tmp_dist = set_L[sub].distance_;
idi tmp_id = set_L[sub].id_;
if (tmp_dist < min_dist) {
min_dist = tmp_dist;
min_id = tmp_id;
min_q_i = q_i;
} else if (tmp_dist == min_dist && tmp_id < min_id) {
min_id = tmp_id;
min_q_i = q_i;
}
}
if (!is_finished) {
is_finished = true;
idi sub = local_queues_starts[min_q_i] + pointers[min_q_i];
top_m_candidates[top_m_candidates_size++] = set_L[sub].id_;
set_L[sub].is_checked_ = true; // Checked
++pointers[min_q_i];
// ++rank;
// ++local_m_counts[min_q_i];
} else {
break;
}
}
// std::copy(pointers.begin(), pointers.end(), local_top_m_positions.begin());
std::copy(pointers.begin(), pointers.end(), bound_subs.begin());
}
inline void Searching::search_with_top_m(
const PANNS::idi M,
const PANNS::idi query_id,
const PANNS::idi K,
const PANNS::idi L,
std::vector<Candidate> &set_L,
const std::vector<idi> &init_ids,
std::vector<idi> &set_K)
{
boost::dynamic_bitset<> is_visited(num_v_);
{
for (idi c_i = 0; c_i < L; ++c_i) {
is_visited[init_ids[c_i]] = true;
}
}
const dataf *query_data = queries_load_ + query_id * dimension_;
for (idi v_i = 0; v_i < L; ++v_i) {
idi v_id = init_ids[v_i];
_mm_prefetch(opt_nsg_graph_ + v_id * vertex_bytes_, _MM_HINT_T0);
}
// Get the distances of all candidates, store in the set set_L.
for (unsigned i = 0; i < L; i++) {
unsigned v_id = init_ids[i];
auto *v_data = reinterpret_cast<dataf *>(opt_nsg_graph_ + v_id * vertex_bytes_);
dataf norm = *v_data++;
++count_distance_computation_;
distf dist = compute_distance_with_norm(v_data, query_data, norm);
set_L[i] = Candidate(v_id, dist, false); // False means not checked.
}
std::sort(set_L.begin(), set_L.begin() + L);
std::vector<idi> top_m_candidates(M);
idi top_m_candidates_end = 0;
idi k = 0; // Index of first unchecked candidate.
idi tmp_count = 0; // for debug
while (k < L) {
++tmp_count;
unsigned nk = L;
// Select M candidates
idi last_k = L;
for (idi c_i = k; c_i < L && top_m_candidates_end < M; ++c_i) {
if (set_L[c_i].is_checked_) {
continue;
}
last_k = c_i; // Record the location of the last candidate selected.
set_L[c_i].is_checked_ = true;
top_m_candidates[top_m_candidates_end++] = set_L[c_i].id_;
}
// Push M candidates' neighbors into the queue.
for (idi c_i = 0; c_i < top_m_candidates_end; ++c_i) {
idi cand_id = top_m_candidates[c_i];
_mm_prefetch(opt_nsg_graph_ + cand_id * vertex_bytes_ + data_bytes_, _MM_HINT_T0);
idi *out_edges = (idi *) (opt_nsg_graph_ + cand_id * vertex_bytes_ + data_bytes_);
idi out_degree = *out_edges++;
for (idi n_i = 0; n_i < out_degree; ++n_i) {
_mm_prefetch(opt_nsg_graph_ + out_edges[n_i] * vertex_bytes_, _MM_HINT_T0);
}
for (idi e_i = 0; e_i < out_degree; ++e_i) {
idi nb_id = out_edges[e_i];
if (is_visited[nb_id]) {
continue;
}
is_visited[nb_id] = true;
auto *nb_data = reinterpret_cast<dataf *>(opt_nsg_graph_ + nb_id * vertex_bytes_);
dataf norm = *nb_data++;
++count_distance_computation_;
distf dist = compute_distance_with_norm(nb_data, query_data, norm);
if (dist > set_L[L-1].distance_) {
continue;
}
Candidate cand(nb_id, dist, false);
idi r = insert_into_queue(set_L, L, cand);
if (r < nk) {
nk = r;
}
}
}
top_m_candidates_end = 0; // Clear top_m_candidates
if (nk <= last_k) {
k = nk;
} else {
k = last_k + 1;
}
}
for (idi k_i = 0; k_i < K; ++k_i) {
set_K[k_i] = set_L[k_i].id_;
}
}
inline void Searching::search_with_top_m_scale_m(
const PANNS::idi value_M_max,
const PANNS::idi query_id,
const PANNS::idi K,
const PANNS::idi L,
std::vector<Candidate> &set_L,
const std::vector<idi> &init_ids,
std::vector<idi> &set_K,
std::vector<idi> &top_m_candidates,
boost::dynamic_bitset<> &is_visited)
{
// boost::dynamic_bitset<> is_visited(num_v_);
{
for (idi c_i = 0; c_i < L; ++c_i) {
is_visited[init_ids[c_i]] = true;
}
}
const dataf *query_data = queries_load_ + query_id * dimension_;
for (idi v_i = 0; v_i < L; ++v_i) {
idi v_id = init_ids[v_i];
_mm_prefetch(opt_nsg_graph_ + v_id * vertex_bytes_, _MM_HINT_T0);
}
// Get the distances of all candidates, store in the set set_L.
for (unsigned i = 0; i < L; i++) {
unsigned v_id = init_ids[i];
auto *v_data = reinterpret_cast<dataf *>(opt_nsg_graph_ + v_id * vertex_bytes_);
dataf norm = *v_data++;
++count_distance_computation_;
distf dist = compute_distance_with_norm(v_data, query_data, norm);
set_L[i] = Candidate(v_id, dist, false); // False means not checked.
}
std::sort(set_L.begin(), set_L.begin() + L);
// std::vector<idi> top_m_candidates(M);
idi top_m_candidates_end = 0;
idi k = 0; // Index of first unchecked candidate.
idi tmp_count = 0; // for debug
idi M = 1;
while (k < L) {
++tmp_count;
unsigned nk = L;
// Select M candidates
idi last_k = L;
for (idi c_i = k; c_i < L && top_m_candidates_end < M; ++c_i) {
if (set_L[c_i].is_checked_) {
continue;
}
last_k = c_i; // Record the location of the last candidate selected.
set_L[c_i].is_checked_ = true;
top_m_candidates[top_m_candidates_end++] = set_L[c_i].id_;
}
// Push M candidates' neighbors into the queue.
for (idi c_i = 0; c_i < top_m_candidates_end; ++c_i) {
idi cand_id = top_m_candidates[c_i];
_mm_prefetch(opt_nsg_graph_ + cand_id * vertex_bytes_ + data_bytes_, _MM_HINT_T0);
idi *out_edges = (idi *) (opt_nsg_graph_ + cand_id * vertex_bytes_ + data_bytes_);
idi out_degree = *out_edges++;
for (idi n_i = 0; n_i < out_degree; ++n_i) {
_mm_prefetch(opt_nsg_graph_ + out_edges[n_i] * vertex_bytes_, _MM_HINT_T0);
}
for (idi e_i = 0; e_i < out_degree; ++e_i) {
idi nb_id = out_edges[e_i];
if (is_visited[nb_id]) {
continue;
}
is_visited[nb_id] = true;
auto *nb_data = reinterpret_cast<dataf *>(opt_nsg_graph_ + nb_id * vertex_bytes_);
dataf norm = *nb_data++;
++count_distance_computation_;
distf dist = compute_distance_with_norm(nb_data, query_data, norm);
if (dist > set_L[L-1].distance_) {
continue;
}
Candidate cand(nb_id, dist, false);
idi r = insert_into_queue(set_L, L, cand);
if (r < nk) {
nk = r;
}
}
}
top_m_candidates_end = 0; // Clear top_m_candidates
if (nk <= last_k) {
k = nk;
} else {
k = last_k + 1;
}
if (M < value_M_max) {
M <<= 1;
}
}
for (idi k_i = 0; k_i < K; ++k_i) {
set_K[k_i] = set_L[k_i].id_;
}
{// Reset
is_visited.reset();
}
}
////void Searching::search_with_top_m(
//inline void Searching::search_with_top_m_to_get_distance_range(
// const PANNS::idi M,
// const PANNS::idi query_id,
//// const PANNS::idi K,
// const PANNS::idi L,
// std::vector<Candidate> &set_L,
// const std::vector<idi> &init_ids)
//// std::vector<idi> &set_K)
//{
// dist_max_ = -FLT_MAX;
// dist_min_ = FLT_MAX;
// boost::dynamic_bitset<> is_visited(num_v_);
//
// {
// for (idi c_i = 0; c_i < L; ++c_i) {
// is_visited[init_ids[c_i]] = true;
// }
// }
//
// const dataf *query_data = queries_load_ + query_id * dimension_;
// for (idi v_i = 0; v_i < L; ++v_i) {
// idi v_id = init_ids[v_i];
// _mm_prefetch(opt_nsg_graph_ + v_id * vertex_bytes_, _MM_HINT_T0);
// }
// // Get the distances of all candidates, store in the set set_L.
// for (unsigned i = 0; i < L; i++) {
// unsigned v_id = init_ids[i];
// auto *v_data = reinterpret_cast<dataf *>(opt_nsg_graph_ + v_id * vertex_bytes_);
// dataf norm = *v_data++;
//// ++count_distance_computation;
// distf dist = compute_distance_with_norm(v_data, query_data, norm);
// set_L[i] = Candidate(v_id, dist, false); // False means not checked.
//// {// For distance range
//// if (dist > dist_max_) {
//// dist_max_ = dist;
//// }
//// if (dist < dist_min_) {
//// dist_min_ = dist;
//// }
//// }
// }
// std::sort(set_L.begin(), set_L.begin() + L);
//
// std::vector<idi> top_m_candidates(M);
// idi top_m_candidates_end = 0;
// idi k = 0; // Index of first unchecked candidate.
// idi tmp_count = 0; // for debug
// while (k < L) {
// ++tmp_count;
//
// unsigned nk = L;
//
// // Select M candidates
// idi last_k = L;
// for (idi c_i = k; c_i < L && top_m_candidates_end < M; ++c_i) {
// if (set_L[c_i].is_checked_) {
// continue;
// }
// last_k = c_i; // Record the location of the last candidate selected.
// set_L[c_i].is_checked_ = true;
// top_m_candidates[top_m_candidates_end++] = set_L[c_i].id_;
// }
//
// // Push M candidates' neighbors into the queue.
// for (idi c_i = 0; c_i < top_m_candidates_end; ++c_i) {
// idi cand_id = top_m_candidates[c_i];
// _mm_prefetch(opt_nsg_graph_ + cand_id * vertex_bytes_ + data_bytes_, _MM_HINT_T0);
// idi *out_edges = (idi *) (opt_nsg_graph_ + cand_id * vertex_bytes_ + data_bytes_);
// idi out_degree = *out_edges++;
// for (idi n_i = 0; n_i < out_degree; ++n_i) {
// _mm_prefetch(opt_nsg_graph_ + out_edges[n_i] * vertex_bytes_, _MM_HINT_T0);
// }
// for (idi e_i = 0; e_i < out_degree; ++e_i) {
// idi nb_id = out_edges[e_i];
// if (is_visited[nb_id]) {
// continue;
// }
// is_visited[nb_id] = true;
// auto *nb_data = reinterpret_cast<dataf *>(opt_nsg_graph_ + nb_id * vertex_bytes_);
// dataf norm = *nb_data++;
//// ++count_distance_computation;
// distf dist = compute_distance_with_norm(nb_data, query_data, norm);
// if (dist > set_L[L-1].distance_) {
// continue;
// }
//// if (dist >= set_L[L-1].distance_) {
//// continue;
//// }
// Candidate cand(nb_id, dist, false);
// idi r = insert_into_queue(set_L, L, cand);
// if (r < nk) {
// nk = r;
// }
//// {// For distance range
//// if (dist > dist_max_) {
//// dist_max_ = dist;
//// }
//// if (dist < dist_min_) {
//// dist_min_ = dist;
//// }
//// }
// }
// }
// top_m_candidates_end = 0; // Clear top_m_candidates
//
// if (nk <= last_k) {
// k = nk;
// } else {
// k = last_k + 1;
// }
// {// For histogram
// for (idi i_l = 0; i_l < L; ++i_l) {
// distf dist = set_L[i_l].distance_;
// {// For distance range
// if (dist > dist_max_) {
// dist_max_ = dist;
// }
// if (dist < dist_min_) {
// dist_min_ = dist;
// }
// }
// }
// }
// }
//
//// for (idi k_i = 0; k_i < K; ++k_i) {
//// set_K[k_i] = set_L[k_i].id_;
//// }
//}
//
////void Searching::search_with_top_m(
//inline void Searching::search_with_top_m_myths_M(
// const PANNS::idi M,
// const PANNS::idi query_id,
// const PANNS::idi K,
// const PANNS::idi L,
// std::vector<Candidate> &set_L,
// const std::vector<idi> &init_ids,
// std::vector<idi> &set_K)
//{
//// {//test
//// printf("query_id: %u\n", query_id);
//// }
// const idi loc_range = L / 3;
//
//
// boost::dynamic_bitset<> is_visited(num_v_);
//
// {
// for (idi c_i = 0; c_i < L; ++c_i) {
// is_visited[init_ids[c_i]] = true;
// }
// }
//
// const dataf *query_data = queries_load_ + query_id * dimension_;
// for (idi v_i = 0; v_i < L; ++v_i) {
// idi v_id = init_ids[v_i];
// _mm_prefetch(opt_nsg_graph_ + v_id * vertex_bytes_, _MM_HINT_T0);
// }
// // Get the distances of all candidates, store in the set set_L.
// for (unsigned i = 0; i < L; i++) {
// unsigned v_id = init_ids[i];
// auto *v_data = reinterpret_cast<dataf *>(opt_nsg_graph_ + v_id * vertex_bytes_);
// dataf norm = *v_data++;
//// ++count_distance_computation;
// distf dist = compute_distance_with_norm(v_data, query_data, norm);
// set_L[i] = Candidate(v_id, dist, false); // False means not checked.
// }
// std::sort(set_L.begin(), set_L.begin() + L);
//
//// {// For histogram
//// const distf dist_range = dist_max_ - dist_min_;
//// printf("iter:%u\n", 0);
//// for (idi i_l = 0; i_l < L; ++i_l) {
//// printf("%f\n", (set_L[i_l].distance_ - dist_min_) / dist_range * 100.0);
//// }
//// }
//
// std::vector<idi> top_m_candidates(M);
// idi top_m_candidates_end = 0;
// idi k = 0; // Index of first unchecked candidate.
// idi tmp_count = 0; // for debug
// while (k < L) {
// std::vector<idi> range_count(3, 0);
// idi zero_inserted_count = 0;
//// {//test
//// printf("tmp_count: %u\n", tmp_count);
//// }
// ++tmp_count;
//
// unsigned nk = L;
//
// // Select M candidates
// idi last_k = L;
// for (idi c_i = k; c_i < L && top_m_candidates_end < M; ++c_i) {
// if (set_L[c_i].is_checked_) {
// continue;
// }
// last_k = c_i; // Record the location of the last candidate selected.
// set_L[c_i].is_checked_ = true;
// top_m_candidates[top_m_candidates_end++] = set_L[c_i].id_;
// }
//// {//test
//// printf("top_m_candidates_ends: %u\n", top_m_candidates_end);
//// }
// {
// if (0 == top_m_candidates_end) {
// break;
// }
// }
//
//
// uint64_t count_neighbors = 0;
// uint64_t count_inserted = 0;
// std::vector<idi> locs_to_count(M);
// // Push M candidates' neighbors into the queue.
// for (idi c_i = 0; c_i < top_m_candidates_end; ++c_i) {
// idi cand_id = top_m_candidates[c_i];
// _mm_prefetch(opt_nsg_graph_ + cand_id * vertex_bytes_ + data_bytes_, _MM_HINT_T0);
// idi *out_edges = (idi *) (opt_nsg_graph_ + cand_id * vertex_bytes_ + data_bytes_);
// idi out_degree = *out_edges++;
// for (idi n_i = 0; n_i < out_degree; ++n_i) {
// _mm_prefetch(opt_nsg_graph_ + out_edges[n_i] * vertex_bytes_, _MM_HINT_T0);
// }
//
// count_neighbors += out_degree;
// idi num_inserted = 0;
//
// for (idi e_i = 0; e_i < out_degree; ++e_i) {
// idi nb_id = out_edges[e_i];
// if (is_visited[nb_id]) {
// continue;
// }
// is_visited[nb_id] = true;
// auto *nb_data = reinterpret_cast<dataf *>(opt_nsg_graph_ + nb_id * vertex_bytes_);
// dataf norm = *nb_data++;
//// ++count_distance_computation;
// distf dist = compute_distance_with_norm(nb_data, query_data, norm);
// if (dist > set_L[L-1].distance_) {
// continue;
// }
//// if (dist >= set_L[L-1].distance_) {
//// continue;
//// }
// ++num_inserted;
// Candidate cand(nb_id, dist, false);
// idi r = insert_into_queue(set_L, L, cand);
//// {
//// printf("c_i: %u "
//// "count: %u "
//// "loc_inserted: %u\n",
//// c_i,
//// num_inserted,
//// r);
//// }
// if (r < nk) {
// nk = r;
// }
// {
// ++range_count[r / loc_range];
// }
// }
// {
// if (0 == num_inserted) {
// ++zero_inserted_count;
// }
// locs_to_count[c_i] = num_inserted;
// count_inserted += num_inserted;
// }
//// {
//// printf("c_i: %u "
//// "num_inserted: %u\n",
//// c_i,
//// num_inserted);
//// }
// }
//// {
//// for (idi c_i = top_m_candidates_end; c_i < M; ++c_i) {
//// locs_to_count[c_i] = 0;
//// }
//// printf("iter:%u\n", tmp_count);
//// for (idi c_i = 0; c_i < M; ++c_i) {
//// printf("%u %u\n", c_i, locs_to_count[c_i]);
//// }
//// }
//// {//test
//// idi sum = 0;
//// for (const idi ct : range_count) sum += ct;
//// printf("tmp_count: %u "
//// "k: %u "
//// "actual_M: %u %.1f%% "
//// "zero_ins: %u %.1f%% "
//// "1/3: %u %.1f%% "
//// "2/3: %u %.1f%% "
//// "3/3: %u %.1f%%\n",
//// tmp_count,
//// k,
//// top_m_candidates_end, 100.0 * top_m_candidates_end / M,
//// zero_inserted_count, 100.0 * zero_inserted_count / top_m_candidates_end,
//// range_count[0], 100.0 * range_count[0] / sum,
//// range_count[1], 100.0 * range_count[1] / sum,
//// range_count[2], 100.0 * range_count[2] / sum);
//// }
// top_m_candidates_end = 0; // Clear top_m_candidates
//
// if (nk <= last_k) {
// k = nk;
// } else {
// k = last_k + 1;
// }
// {
// printf("query:%uiter: %u "
// "#neighbors: %lu "
// "#inserted: %lu "
// "ratio: %.2f%%\n",
// query_id, tmp_count,
// count_neighbors,
// count_inserted,
// 100.0 * count_inserted / count_neighbors);
// }
//// {// For histogram
////// const auto it_min = std::min_element(set_L.begin(), set_L.end());
////// const auto it_max = std::max_element(set_L.begin(), set_L.end());
////// const distf dist_min = it_min->distance_;
////// const distf dist_max = it_max->distance_;
////// const distf dist_min = it_min->distance_ - 1.0;
////// const distf dist_max = it_max->distance_ + 1.0;
//// const distf dist_range = dist_max_ - dist_min_;
////// const distf dist_range = dist_max - dist_min;
////// {
////// printf("it_min->distance_: %f dist_min: %f\n",
////// it_min->distance_, dist_min);
////// }
////// const distf dist_range = it_max->distance_ - it_min->distance_;
//// printf("iter:%u\n", tmp_count);
//// for (idi i_l = 0; i_l < L; ++i_l) {
////// printf("%f\n", set_L[i_l].distance_);
////// printf("%f\n", (set_L[i_l].distance_ - dist_min) / dist_range * 100.0);
//// printf("%f\n", (set_L[i_l].distance_ - dist_min_) / dist_range * 100.0);
////// printf("%.2f\n", (set_L[i_l].distance_ - it_min->distance_) / dist_range * 100.0);
//// }
//// }
// }
//
// for (idi k_i = 0; k_i < K; ++k_i) {
// set_K[k_i] = set_L[k_i].id_;
// }
// if (query_id == 3) {
// exit(1);
// }
//}
//
//// Sequential Top-M algorithm for profiling purpose: byte array, CAS, and OpenMP
////void Searching::search_with_top_m(
//inline void Searching::search_with_top_m_profile_bit_CAS(
// const PANNS::idi M,
// const PANNS::idi query_id,
// const PANNS::idi K,
// const PANNS::idi L,
// std::vector<Candidate> &set_L,
// const std::vector<idi> &init_ids,
// std::vector<idi> &set_K)
//{
//// std::vector<uint8_t> is_visited(num_v_, 0); // Byte array
//// boost::dynamic_bitset<> is_visited(num_v_); // Bit array
// BitVector is_visited(num_v_);
//
// {
//#pragma omp parallel for
// for (idi c_i = 0; c_i < L; ++c_i) {
//// is_visited[init_ids[c_i]] = true;
// is_visited.atomic_set_bit(init_ids[c_i]);
// }
// }
//
// const dataf *query_data = queries_load_ + query_id * dimension_;
//#pragma omp parallel for
// for (idi v_i = 0; v_i < L; ++v_i) {
// idi v_id = init_ids[v_i];
// _mm_prefetch(opt_nsg_graph_ + v_id * vertex_bytes_, _MM_HINT_T0);
// }
// // Get the distances of all candidates, store in the set set_L.
//#pragma omp parallel for
// for (unsigned i = 0; i < L; i++) {
// unsigned v_id = init_ids[i];
// auto *v_data = reinterpret_cast<dataf *>(opt_nsg_graph_ + v_id * vertex_bytes_);
// dataf norm = *v_data++;
//// ++count_distance_computation;
// distf dist = compute_distance_with_norm(v_data, query_data, norm);
// set_L[i] = Candidate(v_id, dist, false); // False means not checked.
// }
// std::sort(set_L.begin(), set_L.begin() + L);
//
// std::vector<idi> top_m_candidates(M);
// idi top_m_candidates_end = 0;
// idi k = 0; // Index of first unchecked candidate.
// idi tmp_count = 0; // for debug
// while (k < L) {
// ++tmp_count;
//
// unsigned nk = L;
//
// // Select M candidates
// idi last_k = L;
// for (idi c_i = k; c_i < L && top_m_candidates_end < M; ++c_i) {
// if (set_L[c_i].is_checked_) {
// continue;
// }
// last_k = c_i; // Record the location of the last candidate selected.
// set_L[c_i].is_checked_ = true;
// top_m_candidates[top_m_candidates_end++] = set_L[c_i].id_;
// }
//
// // Push M candidates' neighbors into the queue.
//#pragma omp parallel for
// for (idi c_i = 0; c_i < top_m_candidates_end; ++c_i) {
// idi cand_id = top_m_candidates[c_i];
// _mm_prefetch(opt_nsg_graph_ + cand_id * vertex_bytes_ + data_bytes_, _MM_HINT_T0);
// idi *out_edges = (idi *) (opt_nsg_graph_ + cand_id * vertex_bytes_ + data_bytes_);
// idi out_degree = *out_edges++;
// for (idi n_i = 0; n_i < out_degree; ++n_i) {
// _mm_prefetch(opt_nsg_graph_ + out_edges[n_i] * vertex_bytes_, _MM_HINT_T0);
// }
// for (idi e_i = 0; e_i < out_degree; ++e_i) {
// idi nb_id = out_edges[e_i];
//// if (is_visited[nb_id]) {
//// continue;
//// }
//// is_visited[nb_id] = true;
//
//// if (!AtomicOps::CAS(is_visited.data() + nb_id,
//// static_cast<uint8_t>(0),
//// static_cast<uint8_t>(1))) {
//// continue;
//// }
// {// Self-defined BitVector
// if (is_visited.atomic_is_bit_set(nb_id)) {
// continue;
// }
// is_visited.atomic_set_bit(nb_id);
// }
//
// auto *nb_data = reinterpret_cast<dataf *>(opt_nsg_graph_ + nb_id * vertex_bytes_);
// dataf norm = *nb_data++;
//// ++count_distance_computation;
// distf dist = compute_distance_with_norm(nb_data, query_data, norm);
// if (dist > set_L[L-1].distance_) {
// continue;
// }
//// if (dist >= set_L[L-1].distance_) {
//// continue;
//// }
// Candidate cand(nb_id, dist, false);
// idi r = insert_into_queue(set_L, L, cand);
// if (r < nk) {
// nk = r;
// }
// }
// }
// top_m_candidates_end = 0; // Clear top_m_candidates
//
// if (nk <= last_k) {
// k = nk;
// } else {
// k = last_k + 1;
// }
// }
//
//#pragma omp parallel for
// for (idi k_i = 0; k_i < K; ++k_i) {
// set_K[k_i] = set_L[k_i].id_;
// }
////
//// {//test
//// for (idi k_i = 0; k_i < K; ++k_i) {
//// printf("%u: %u: %u %f\n",
//// query_id,
//// k_i, set_L[k_i].id_, set_L[k_i].distance_);
//// }
//// exit(1);
//// }
//}
///// Backup
//inline void Searching::search_with_top_m(
// const PANNS::idi M,
// const PANNS::idi query_id,
// const PANNS::idi K,
// const PANNS::idi L,
// std::vector<Candidate> &set_L,
// const std::vector<idi> &init_ids,
// std::vector<idi> &set_K)
//// std::vector< std::vector<idi> > &top_m_list)
//{
// boost::dynamic_bitset<> is_visited(num_v_);
//
// {
// for (idi c_i = 0; c_i < L; ++c_i) {
// is_visited[init_ids[c_i]] = true;
// }
// }
//
// const dataf *query_data = queries_load_ + query_id * dimension_;
// for (idi v_i = 0; v_i < L; ++v_i) {
// idi v_id = init_ids[v_i];
// _mm_prefetch(opt_nsg_graph_ + v_id * vertex_bytes_, _MM_HINT_T0);
// }
// // Get the distances of all candidates, store in the set set_L.
// for (unsigned i = 0; i < L; i++) {
// unsigned v_id = init_ids[i];
// auto *v_data = reinterpret_cast<dataf *>(opt_nsg_graph_ + v_id * vertex_bytes_);
// dataf norm = *v_data++;
//// ++count_distance_computation;
// distf dist = compute_distance_with_norm(v_data, query_data, norm);
// set_L[i] = Candidate(v_id, dist, false); // False means not checked.
// }
// std::sort(set_L.begin(), set_L.begin() + L);
//
// std::vector<idi> top_m_candidates(M);
// idi top_m_candidates_end = 0;
// idi k = 0; // Index of first unchecked candidate.
// idi tmp_count = 0; // for debug
// while (k < L) {
// ++tmp_count;
//
// unsigned nk = L;
//
// // Select M candidates
// idi last_k = L;
// for (idi c_i = k; c_i < L && top_m_candidates_end < M; ++c_i) {
// if (set_L[c_i].is_checked_) {
// continue;
// }
// last_k = c_i; // Record the location of the last candidate selected.
// set_L[c_i].is_checked_ = true;
// top_m_candidates[top_m_candidates_end++] = set_L[c_i].id_;
// }
//
// // Push M candidates' neighbors into the queue.
// for (idi c_i = 0; c_i < top_m_candidates_end; ++c_i) {
// idi cand_id = top_m_candidates[c_i];
// _mm_prefetch(opt_nsg_graph_ + cand_id * vertex_bytes_ + data_bytes_, _MM_HINT_T0);
// idi *out_edges = (idi *) (opt_nsg_graph_ + cand_id * vertex_bytes_ + data_bytes_);
// idi out_degree = *out_edges++;
// for (idi n_i = 0; n_i < out_degree; ++n_i) {
// _mm_prefetch(opt_nsg_graph_ + out_edges[n_i] * vertex_bytes_, _MM_HINT_T0);
// }
// for (idi e_i = 0; e_i < out_degree; ++e_i) {
// idi nb_id = out_edges[e_i];
// if (is_visited[nb_id]) {
// continue;
// }
// is_visited[nb_id] = true;
// auto *nb_data = reinterpret_cast<dataf *>(opt_nsg_graph_ + nb_id * vertex_bytes_);
// dataf norm = *nb_data++;
//// ++count_distance_computation;
// distf dist = compute_distance_with_norm(nb_data, query_data, norm);
// if (dist > set_L[L-1].distance_) {
// continue;
// }
//// if (dist >= set_L[L-1].distance_) {
//// continue;
//// }
// Candidate cand(nb_id, dist, false);
// idi r = insert_into_queue(set_L, L, cand);
// if (r < nk) {
// nk = r;
// }
// }
// }
// top_m_candidates_end = 0; // Clear top_m_candidates
//
// if (nk <= last_k) {
// k = nk;
// } else {
// k = last_k + 1;
// }
// }
//
// for (idi k_i = 0; k_i < K; ++k_i) {
// set_K[k_i] = set_L[k_i].id_;
// }
////
//// {//test
//// for (idi k_i = 0; k_i < K; ++k_i) {
//// printf("%u: %u: %u %f\n",
//// query_id,
//// k_i, set_L[k_i].id_, set_L[k_i].distance_);
//// }
//// exit(1);
//// }
//}
//
////// DEPRECATED: the is_visited array cannot be shared among threads.
//inline void Searching::search_with_top_m_no_local_arrays(
// const PANNS::idi M,
// const PANNS::idi query_id,
// const PANNS::idi K,
// const PANNS::idi L,
// std::vector<Candidate> &set_L,
// const std::vector<idi> &init_ids,
// std::vector<idi> &set_K,
// boost::dynamic_bitset<> &is_visited)
//// std::vector< std::vector<idi> > &top_m_list)
//{
//// boost::dynamic_bitset<> is_visited(num_v_);
//
// {
// for (idi c_i = 0; c_i < L; ++c_i) {
// is_visited[init_ids[c_i]] = true;
// }
// }
//
// const dataf *query_data = queries_load_ + query_id * dimension_;
// for (idi v_i = 0; v_i < L; ++v_i) {
// idi v_id = init_ids[v_i];
// _mm_prefetch(opt_nsg_graph_ + v_id * vertex_bytes_, _MM_HINT_T0);
// }
// // Get the distances of all candidates, store in the set set_L.
// for (unsigned i = 0; i < L; i++) {
// unsigned v_id = init_ids[i];
// auto *v_data = reinterpret_cast<dataf *>(opt_nsg_graph_ + v_id * vertex_bytes_);
// dataf norm = *v_data++;
//// ++count_distance_computation;
// distf dist = compute_distance_with_norm(v_data, query_data, norm);
// set_L[i] = Candidate(v_id, dist, false); // False means not checked.
// }
// std::sort(set_L.begin(), set_L.begin() + L);
//
// std::vector<idi> top_m_candidates(M);
// idi top_m_candidates_end = 0;
// idi k = 0; // Index of first unchecked candidate.
// idi tmp_count = 0; // for debug
// while (k < L) {
// ++tmp_count;
//
// unsigned nk = L;
//
// // Select M candidates
// idi last_k = L;
// for (idi c_i = k; c_i < L && top_m_candidates_end < M; ++c_i) {
// if (set_L[c_i].is_checked_) {
// continue;
// }
// last_k = c_i; // Record the location of the last candidate selected.
// set_L[c_i].is_checked_ = true;
// top_m_candidates[top_m_candidates_end++] = set_L[c_i].id_;
// }
//
// // Push M candidates' neighbors into the queue.
// for (idi c_i = 0; c_i < top_m_candidates_end; ++c_i) {
// idi cand_id = top_m_candidates[c_i];
// _mm_prefetch(opt_nsg_graph_ + cand_id * vertex_bytes_ + data_bytes_, _MM_HINT_T0);
// idi *out_edges = (idi *) (opt_nsg_graph_ + cand_id * vertex_bytes_ + data_bytes_);
// idi out_degree = *out_edges++;
// for (idi n_i = 0; n_i < out_degree; ++n_i) {
// _mm_prefetch(opt_nsg_graph_ + out_edges[n_i] * vertex_bytes_, _MM_HINT_T0);
// }
// for (idi e_i = 0; e_i < out_degree; ++e_i) {
// idi nb_id = out_edges[e_i];
// if (is_visited[nb_id]) {
// continue;
// }
// is_visited[nb_id] = true;
// auto *nb_data = reinterpret_cast<dataf *>(opt_nsg_graph_ + nb_id * vertex_bytes_);
// dataf norm = *nb_data++;
//// ++count_distance_computation;
// distf dist = compute_distance_with_norm(nb_data, query_data, norm);
// if (dist > set_L[L-1].distance_) {
// continue;
// }
//// if (dist >= set_L[L-1].distance_) {
//// continue;
//// }
// Candidate cand(nb_id, dist, false);
// idi r = insert_into_queue(set_L, L, cand);
// if (r < nk) {
// nk = r;
// }
// }
// }
// top_m_candidates_end = 0; // Clear top_m_candidates
//
// if (nk <= last_k) {
// k = nk;
// } else {
// k = last_k + 1;
// }
// }
//
// for (idi k_i = 0; k_i < K; ++k_i) {
// set_K[k_i] = set_L[k_i].id_;
// }
////
//// {//test
//// for (idi k_i = 0; k_i < K; ++k_i) {
//// printf("%u: %u: %u %f\n",
//// query_id,
//// k_i, set_L[k_i].id_, set_L[k_i].distance_);
//// }
//// exit(1);
//// }
//}
inline void Searching::search_with_top_m_in_batch(
const PANNS::idi M,
const PANNS::idi batch_start,
const PANNS::idi batch_size,
const PANNS::idi K,
const PANNS::idi L,
std::vector< std::vector<Candidate> > &set_L_list,
const std::vector<idi> &init_ids,
std::vector< std::vector<idi> > &set_K_list)
{
std::vector< boost::dynamic_bitset<> > is_visited_list(batch_size, boost::dynamic_bitset<> (num_v_));
// Prepare the init_ids
{
//#pragma omp parallel for
for (idi q_i = 0; q_i < batch_size; ++q_i) {
auto &is_visited = is_visited_list[q_i];
for (idi c_i = 0; c_i < L; ++c_i) {
is_visited[init_ids[c_i]] = true;
}
}
}
// Initialize set_L_list
{
//#pragma omp parallel for
for (idi q_i = 0; q_i < batch_size; ++q_i) {
const dataf *query_data = queries_load_ + (q_i + batch_start) * dimension_;
for (idi i = 0; i < L; i++) {
idi v_id = init_ids[i];
auto *v_data = reinterpret_cast<dataf *>(opt_nsg_graph_ + v_id * vertex_bytes_);
dataf norm = *v_data++;
// ++count_distance_computation_;
distf dist = compute_distance_with_norm(v_data, query_data, norm);
set_L_list[q_i][i] = Candidate(v_id, dist, false); // False means not checked.
}
std::sort(set_L_list[q_i].begin(), set_L_list[q_i].begin() + L);
}
}
{
std::vector<idi> joint_queue(M * batch_size); // Joint queue for all shared top-M candidates
idi joint_queue_end = 0;
boost::dynamic_bitset<> is_in_joint_queue(num_v_);
// std::vector< std::vector<idi> > cands_query_ids(num_v_, std::vector<idi>(batch_size)); // If candidate cand_id is selected by query q_i, q_i should be in cands_query_ids[cand_id].
// std::vector<idi> cands_query_ids_ends(num_v_, 0);
std::unordered_map< idi, std::vector<idi> > cands_query_ids(batch_size * M);
std::vector<idi> ks(batch_size, 0); // Indices of every queue's first unchecked candidate.
std::vector<idi> nks(batch_size, L); // Indices of highest candidate inserted
std::vector<idi> last_ks(batch_size, L); // Indices of lowest candidate unchecked
std::vector<idi> queries_not_finished(batch_size);
idi queries_not_finished_end = batch_size;
for (idi q_i = 0; q_i < batch_size; ++q_i) {
queries_not_finished[q_i] = q_i;
}
bool is_finished = false;
idi counter_for_debug = 0;
while (!is_finished) {
++counter_for_debug;
// Build the new joint queue
// Traverse every query's queue
for(idi q_i = 0; q_i < queries_not_finished_end; ++q_i) {
idi q_local_id = queries_not_finished[q_i];
// last_ks[q_local_id] = L;
auto &set_L = set_L_list[q_local_id];
idi top_m_count = 0;
for (idi c_i = ks[q_local_id]; c_i < L && top_m_count < M; ++c_i) {
if (set_L[c_i].is_checked_) {
continue;
}
set_L[c_i].is_checked_ = true;
last_ks[q_local_id] = c_i;
++top_m_count;
idi cand_id = set_L[c_i].id_;
// Record which query selected cand_id
auto tmp_c = cands_query_ids.find(cand_id);
if (tmp_c != cands_query_ids.end()) {
tmp_c->second.push_back(q_local_id);
} else {
cands_query_ids.emplace(cand_id, std::vector<idi>());
cands_query_ids[cand_id].reserve(batch_size);
cands_query_ids[cand_id].push_back(q_local_id);
}
// cands_query_ids[cand_id][cands_query_ids_ends[cand_id]++] = q_local_id;
// Add candidate cand_id into the joint queue
if (is_in_joint_queue[cand_id]) {
continue;
}
is_in_joint_queue[cand_id] = true;
joint_queue[joint_queue_end++] = cand_id;
}
}
queries_not_finished_end = 0; // Clear queries_not_finished
// Traverse every shared candidate
for (idi c_i = 0; c_i < joint_queue_end; ++c_i) {
idi cand_id = joint_queue[c_i];
is_in_joint_queue[cand_id] = false; // Reset is_in_joint_queue
idi *out_edges = (idi *) (opt_nsg_graph_ + cand_id * vertex_bytes_ + data_bytes_);
idi out_degree = *out_edges++;
const auto &query_local_ids = cands_query_ids[cand_id];
// Push neighbors to every queue of the queries that selected cand_id.
// Traverse cand_id's neighbors
// idi &q_i_bound = cands_query_ids_ends[cand_id];
// for (idi q_i = 0; q_i < q_i_bound; ++q_i) {
// idi q_local_id = query_local_ids[q_i];
for (idi q_local_id : query_local_ids) {
dataf *query_data = queries_load_ + (q_local_id + batch_start) * dimension_;
auto &is_visited = is_visited_list[q_local_id];
auto &set_L = set_L_list[q_local_id];
// // Traverse cand_id's neighbors
for (idi e_i = 0; e_i < out_degree; ++e_i) {
idi nb_id = out_edges[e_i];
if (is_visited[nb_id]) {
continue;
}
is_visited[nb_id] = true;
auto *nb_data = reinterpret_cast<dataf *>(opt_nsg_graph_ + nb_id * vertex_bytes_);
dataf norm = *nb_data++;
// ++count_distance_computation_;
distf dist = compute_distance_with_norm(nb_data, query_data, norm);
if (dist > set_L[L-1].distance_) {
continue;
}
// if (dist >= set_L[L-1].distance_) {
// continue;
// }
Candidate new_cand(nb_id, dist, false);
idi insert_loc = insert_into_queue(set_L, L, new_cand);
if (insert_loc < nks[q_local_id]) {
nks[q_local_id] = insert_loc;
}
}
}
cands_query_ids.erase(cand_id);
// q_i_bound = 0; // Clear cands_query_ids[cand_id]
}
joint_queue_end = 0; // Clear joint_queue
for (idi q_local_id = 0; q_local_id < batch_size; ++q_local_id) {
if (nks[q_local_id] <= last_ks[q_local_id]) {
ks[q_local_id] = nks[q_local_id];
} else {
ks[q_local_id] = last_ks[q_local_id] + 1;
}
nks[q_local_id] = L;
last_ks[q_local_id] = L;
if (ks[q_local_id] < L) {
queries_not_finished[queries_not_finished_end++] = q_local_id;
}
}
if (!queries_not_finished_end) {
is_finished = true;
}
}
}
{
for (idi q_i = 0; q_i < batch_size; ++q_i) {
for (idi c_i = 0; c_i < K && c_i < L; ++c_i) {
set_K_list[q_i + batch_start][c_i] = set_L_list[q_i][c_i].id_;
}
}
}
////
// {//test
// for (idi q_i = 0; q_i < batch_size; ++q_i) {
// printf("query: %u\n", q_i + batch_start);
// for (idi c_i = 0; c_i < K; ++c_i) {
// printf("%u: %u %f\n", c_i, set_L_list[q_i][c_i].id_, set_L_list[q_i][c_i].distance_);
// }
// }
// }
}
//inline void Searching::para_search_with_top_m_critical_area(
// const PANNS::idi M,
// const PANNS::idi query_id,
// const PANNS::idi K,
// const PANNS::idi L,
// std::vector<Candidate> &set_L,
// const std::vector<idi> &init_ids,
// std::vector<idi> &set_K)
//// std::vector< std::vector<idi> > &top_m_list)
//{
// std::vector<uint8_t> is_visited(num_v_, 0);
//// boost::dynamic_bitset<> is_visited(num_v_);
//
// {
////#pragma omp parallel for
// for (idi c_i = 0; c_i < L; ++c_i) {
// is_visited[init_ids[c_i]] = 1;
// }
// }
//
// const dataf *query_data = queries_load_ + query_id * dimension_;
// for (idi v_i = 0; v_i < L; ++v_i) {
// idi v_id = init_ids[v_i];
// _mm_prefetch(opt_nsg_graph_ + v_id * vertex_bytes_, _MM_HINT_T0);
// }
// // Get the distances of all candidates, store in the set set_L.
////#pragma omp parallel for
// for (unsigned i = 0; i < L; i++) {
// unsigned v_id = init_ids[i];
// auto *v_data = reinterpret_cast<dataf *>(opt_nsg_graph_ + v_id * vertex_bytes_);
// dataf norm = *v_data++;
// ++count_distance_computation_;
// distf dist = compute_distance_with_norm(v_data, query_data, norm);
// set_L[i] = Candidate(v_id, dist, false); // False means not checked.
// }
// std::sort(set_L.begin(), set_L.begin() + L);
//
// std::vector<idi> top_m_candidates(M);
// idi top_m_candidates_end = 0;
// idi k = 0; // Index of first unchecked candidate.
// idi tmp_count = 0; // for debug
// while (k < L) {
// ++tmp_count;
//
// unsigned nk = L;
//// int nk = L;
//
// // Select M candidates
// idi last_k = L;
// for (idi c_i = k; c_i < L && top_m_candidates_end < M; ++c_i) {
// if (set_L[c_i].is_checked_) {
// continue;
// }
// last_k = c_i; // Record the location of the last candidate selected.
// set_L[c_i].is_checked_ = true;
// top_m_candidates[top_m_candidates_end++] = set_L[c_i].id_;
// }
//
// // Push M candidates' neighbors into the queue.
// // OpenMP reduction(min : nk) has a problem if nk is unsigned. nk might end up with being MAX_UINT.
////#pragma omp parallel for
////#pragma omp parallel for reduction(min : nk)
// for (idi c_i = 0; c_i < top_m_candidates_end; ++c_i) {
// idi cand_id = top_m_candidates[c_i];
// _mm_prefetch(opt_nsg_graph_ + cand_id * vertex_bytes_ + data_bytes_, _MM_HINT_T0);
// idi *out_edges = (idi *) (opt_nsg_graph_ + cand_id * vertex_bytes_ + data_bytes_);
// idi out_degree = *out_edges++;
// for (idi n_i = 0; n_i < out_degree; ++n_i) {
// _mm_prefetch(opt_nsg_graph_ + out_edges[n_i] * vertex_bytes_, _MM_HINT_T0);
// }
// for (idi e_i = 0; e_i < out_degree; ++e_i) {
// idi nb_id = out_edges[e_i];
//// if (is_visited[nb_id]) {
//// continue;
//// }
//// is_visited[nb_id] = 1;
//
// if (!AtomicOps::CAS(is_visited.data() + nb_id,
// static_cast<uint8_t>(0),
// static_cast<uint8_t>(1))) {
// continue;
// }
//
// auto *nb_data = reinterpret_cast<dataf *>(opt_nsg_graph_ + nb_id * vertex_bytes_);
// dataf norm = *nb_data++;
// ++count_distance_computation_;
// distf dist = compute_distance_with_norm(nb_data, query_data, norm);
// if (dist > set_L[L-1].distance_) {
// continue;
// }
//// if (dist >= set_L[L-1].distance_) {
//// continue;
//// }
// Candidate cand(nb_id, dist, false);
// idi r;
////#pragma omp critical
// {
// r = insert_into_queue(set_L, L, cand);
// if (r < nk) {
// nk = r;
// }
// }
// }
// }
// top_m_candidates_end = 0; // Clear top_m_candidates
//
// if (nk <= last_k) {
// k = nk;
// } else {
// k = last_k + 1;
// }
// }
//
////#pragma omp parallel for
// for (idi k_i = 0; k_i < K; ++k_i) {
// set_K[k_i] = set_L[k_i].id_;
// }
//}
//
//inline void Searching::para_search_with_top_m_critical_area_no_omp(
// const PANNS::idi M,
// const PANNS::idi query_id,
// const PANNS::idi K,
// const PANNS::idi L,
// std::vector<Candidate> &set_L,
// const std::vector<idi> &init_ids,
// std::vector<idi> &set_K)
//// std::vector< std::vector<idi> > &top_m_list)
//{
// std::vector<uint8_t> is_visited(num_v_, 0);
//// boost::dynamic_bitset<> is_visited(num_v_);
//
// {
////#pragma omp parallel for
// for (idi c_i = 0; c_i < L; ++c_i) {
// is_visited[init_ids[c_i]] = 1;
// }
// }
//
// const dataf *query_data = queries_load_ + query_id * dimension_;
// for (idi v_i = 0; v_i < L; ++v_i) {
// idi v_id = init_ids[v_i];
// _mm_prefetch(opt_nsg_graph_ + v_id * vertex_bytes_, _MM_HINT_T0);
// }
// // Get the distances of all candidates, store in the set set_L.
////#pragma omp parallel for
// for (unsigned i = 0; i < L; i++) {
// unsigned v_id = init_ids[i];
// auto *v_data = reinterpret_cast<dataf *>(opt_nsg_graph_ + v_id * vertex_bytes_);
// dataf norm = *v_data++;
// ++count_distance_computation_;
// distf dist = compute_distance_with_norm(v_data, query_data, norm);
// set_L[i] = Candidate(v_id, dist, false); // False means not checked.
// }
// std::sort(set_L.begin(), set_L.begin() + L);
//
// std::vector<idi> top_m_candidates(M);
// idi top_m_candidates_end = 0;
// idi k = 0; // Index of first unchecked candidate.
// idi tmp_count = 0; // for debug
// while (k < L) {
// ++tmp_count;
//
// unsigned nk = L;
//// int nk = L;
//
// // Select M candidates
// idi last_k = L;
// for (idi c_i = k; c_i < L && top_m_candidates_end < M; ++c_i) {
// if (set_L[c_i].is_checked_) {
// continue;
// }
// last_k = c_i; // Record the location of the last candidate selected.
// set_L[c_i].is_checked_ = true;
// top_m_candidates[top_m_candidates_end++] = set_L[c_i].id_;
// }
//
// // Push M candidates' neighbors into the queue.
// // OpenMP reduction(min : nk) has a problem if nk is unsigned. nk might end up with being MAX_UINT.
////#pragma omp parallel for
////#pragma omp parallel for reduction(min : nk)
// for (idi c_i = 0; c_i < top_m_candidates_end; ++c_i) {
// idi cand_id = top_m_candidates[c_i];
// _mm_prefetch(opt_nsg_graph_ + cand_id * vertex_bytes_ + data_bytes_, _MM_HINT_T0);
// idi *out_edges = (idi *) (opt_nsg_graph_ + cand_id * vertex_bytes_ + data_bytes_);
// idi out_degree = *out_edges++;
// for (idi n_i = 0; n_i < out_degree; ++n_i) {
// _mm_prefetch(opt_nsg_graph_ + out_edges[n_i] * vertex_bytes_, _MM_HINT_T0);
// }
// for (idi e_i = 0; e_i < out_degree; ++e_i) {
// idi nb_id = out_edges[e_i];
//// if (is_visited[nb_id]) {
//// continue;
//// }
//// is_visited[nb_id] = 1;
//
// if (!AtomicOps::CAS(is_visited.data() + nb_id,
// static_cast<uint8_t>(0),
// static_cast<uint8_t>(1))) {
// continue;
// }
//
// auto *nb_data = reinterpret_cast<dataf *>(opt_nsg_graph_ + nb_id * vertex_bytes_);
// dataf norm = *nb_data++;
// ++count_distance_computation_;
// distf dist = compute_distance_with_norm(nb_data, query_data, norm);
// if (dist > set_L[L-1].distance_) {
// continue;
// }
//// if (dist >= set_L[L-1].distance_) {
//// continue;
//// }
// Candidate cand(nb_id, dist, false);
// idi r;
////#pragma omp critical
// {
// r = insert_into_queue(set_L, L, cand);
// if (r < nk) {
// nk = r;
// }
// }
// }
// }
// top_m_candidates_end = 0; // Clear top_m_candidates
//
// if (nk <= last_k) {
// k = nk;
// } else {
// k = last_k + 1;
// }
// }
//
////#pragma omp parallel for
// for (idi k_i = 0; k_i < K; ++k_i) {
// set_K[k_i] = set_L[k_i].id_;
// }
//}
//
//inline void Searching::para_search_with_top_m_critical_area_yes_omp(
// const PANNS::idi M,
// const PANNS::idi query_id,
// const PANNS::idi K,
// const PANNS::idi L,
// std::vector<Candidate> &set_L,
// const std::vector<idi> &init_ids,
// std::vector<idi> &set_K)
//// std::vector< std::vector<idi> > &top_m_list)
//{
// std::vector<uint8_t> is_visited(num_v_, 0);
//// boost::dynamic_bitset<> is_visited(num_v_);
//
// {
//#pragma omp parallel for
// for (idi c_i = 0; c_i < L; ++c_i) {
// is_visited[init_ids[c_i]] = 1;
// }
// }
//
// const dataf *query_data = queries_load_ + query_id * dimension_;
// for (idi v_i = 0; v_i < L; ++v_i) {
// idi v_id = init_ids[v_i];
// _mm_prefetch(opt_nsg_graph_ + v_id * vertex_bytes_, _MM_HINT_T0);
// }
// // Get the distances of all candidates, store in the set set_L.
////#pragma omp parallel for
// for (unsigned i = 0; i < L; i++) {
// unsigned v_id = init_ids[i];
// auto *v_data = reinterpret_cast<dataf *>(opt_nsg_graph_ + v_id * vertex_bytes_);
// dataf norm = *v_data++;
// ++count_distance_computation_;
// distf dist = compute_distance_with_norm(v_data, query_data, norm);
// set_L[i] = Candidate(v_id, dist, false); // False means not checked.
// }
// std::sort(set_L.begin(), set_L.begin() + L);
//
// std::vector<idi> top_m_candidates(M);
// idi top_m_candidates_end = 0;
// idi k = 0; // Index of first unchecked candidate.
// idi tmp_count = 0; // for debug
// while (k < L) {
// ++tmp_count;
//
// unsigned nk = L;
//// int nk = L;
//
// // Select M candidates
// idi last_k = L;
// for (idi c_i = k; c_i < L && top_m_candidates_end < M; ++c_i) {
// if (set_L[c_i].is_checked_) {
// continue;
// }
// last_k = c_i; // Record the location of the last candidate selected.
// set_L[c_i].is_checked_ = true;
// top_m_candidates[top_m_candidates_end++] = set_L[c_i].id_;
// }
//
// // Push M candidates' neighbors into the queue.
// // OpenMP reduction(min : nk) has a problem if nk is unsigned. nk might end up with being MAX_UINT.
////#pragma omp parallel for
////#pragma omp parallel for reduction(min : nk)
// for (idi c_i = 0; c_i < top_m_candidates_end; ++c_i) {
// idi cand_id = top_m_candidates[c_i];
// _mm_prefetch(opt_nsg_graph_ + cand_id * vertex_bytes_ + data_bytes_, _MM_HINT_T0);
// idi *out_edges = (idi *) (opt_nsg_graph_ + cand_id * vertex_bytes_ + data_bytes_);
// idi out_degree = *out_edges++;
// for (idi n_i = 0; n_i < out_degree; ++n_i) {
// _mm_prefetch(opt_nsg_graph_ + out_edges[n_i] * vertex_bytes_, _MM_HINT_T0);
// }
// for (idi e_i = 0; e_i < out_degree; ++e_i) {
// idi nb_id = out_edges[e_i];
//// if (is_visited[nb_id]) {
//// continue;
//// }
//// is_visited[nb_id] = 1;
//
// if (!AtomicOps::CAS(is_visited.data() + nb_id,
// static_cast<uint8_t>(0),
// static_cast<uint8_t>(1))) {
// continue;
// }
//
// auto *nb_data = reinterpret_cast<dataf *>(opt_nsg_graph_ + nb_id * vertex_bytes_);
// dataf norm = *nb_data++;
// ++count_distance_computation_;
// distf dist = compute_distance_with_norm(nb_data, query_data, norm);
// if (dist > set_L[L-1].distance_) {
// continue;
// }
//// if (dist >= set_L[L-1].distance_) {
//// continue;
//// }
// Candidate cand(nb_id, dist, false);
// idi r;
////#pragma omp critical
// {
// r = insert_into_queue(set_L, L, cand);
// if (r < nk) {
// nk = r;
// }
// }
// }
// }
// top_m_candidates_end = 0; // Clear top_m_candidates
//
// if (nk <= last_k) {
// k = nk;
// } else {
// k = last_k + 1;
// }
// }
//
////#pragma omp parallel for
// for (idi k_i = 0; k_i < K; ++k_i) {
// set_K[k_i] = set_L[k_i].id_;
// }
//}
//
//inline void Searching::para_search_with_top_m_visited_array(
// const PANNS::idi M,
// const PANNS::idi query_id,
// const PANNS::idi K,
// const PANNS::idi L,
// std::vector<Candidate> &set_L,
// const std::vector<idi> &init_ids,
// std::vector<idi> &set_K,
// std::vector<uint8_t> &is_visited)
//// std::vector< std::vector<idi> > &top_m_list)
//{
//// uint64_t count_visited = 0;
//
//// std::vector<uint8_t> is_visited(num_v_, 0);
//// boost::dynamic_bitset<> is_visited(num_v_);
//
// {
////#pragma omp parallel for
// for (idi c_i = 0; c_i < L; ++c_i) {
// is_visited[init_ids[c_i]] = 1;
//// ++count_visited;
// }
// }
//
// const dataf *query_data = queries_load_ + query_id * dimension_;
// for (idi v_i = 0; v_i < L; ++v_i) {
// idi v_id = init_ids[v_i];
// _mm_prefetch(opt_nsg_graph_ + v_id * vertex_bytes_, _MM_HINT_T0);
// }
// // Get the distances of all candidates, store in the set set_L.
////#pragma omp parallel for
// for (unsigned i = 0; i < L; i++) {
// unsigned v_id = init_ids[i];
// auto *v_data = reinterpret_cast<dataf *>(opt_nsg_graph_ + v_id * vertex_bytes_);
// dataf norm = *v_data++;
// ++count_distance_computation_;
// distf dist = compute_distance_with_norm(v_data, query_data, norm);
// set_L[i] = Candidate(v_id, dist, false); // False means not checked.
// }
// std::sort(set_L.begin(), set_L.begin() + L);
//
// std::vector<idi> top_m_candidates(M);
// idi top_m_candidates_end = 0;
// idi k = 0; // Index of first unchecked candidate.
// idi tmp_count = 0; // for debug
// while (k < L) {
// ++tmp_count;
//
// unsigned nk = L;
//// int nk = L;
//
// // Select M candidates
// idi last_k = L;
// for (idi c_i = k; c_i < L && top_m_candidates_end < M; ++c_i) {
// if (set_L[c_i].is_checked_) {
// continue;
// }
// last_k = c_i; // Record the location of the last candidate selected.
// set_L[c_i].is_checked_ = true;
// top_m_candidates[top_m_candidates_end++] = set_L[c_i].id_;
// }
//
// // Push M candidates' neighbors into the queue.
// // OpenMP reduction(min : nk) has a problem if nk is unsigned. nk might end up with being MAX_UINT.
////#pragma omp parallel for
////#pragma omp parallel for reduction(min : nk)
// for (idi c_i = 0; c_i < top_m_candidates_end; ++c_i) {
// idi cand_id = top_m_candidates[c_i];
// _mm_prefetch(opt_nsg_graph_ + cand_id * vertex_bytes_ + data_bytes_, _MM_HINT_T0);
// idi *out_edges = (idi *) (opt_nsg_graph_ + cand_id * vertex_bytes_ + data_bytes_);
// idi out_degree = *out_edges++;
// for (idi n_i = 0; n_i < out_degree; ++n_i) {
// _mm_prefetch(opt_nsg_graph_ + out_edges[n_i] * vertex_bytes_, _MM_HINT_T0);
// }
// for (idi e_i = 0; e_i < out_degree; ++e_i) {
// idi nb_id = out_edges[e_i];
//// if (is_visited[nb_id]) {
//// continue;
//// }
//// is_visited[nb_id] = 1;
//
// if (!AtomicOps::CAS(is_visited.data() + nb_id,
// static_cast<uint8_t>(0),
// static_cast<uint8_t>(1))) {
// continue;
// }
//// ++count_visited;
// auto *nb_data = reinterpret_cast<dataf *>(opt_nsg_graph_ + nb_id * vertex_bytes_);
// dataf norm = *nb_data++;
// ++count_distance_computation_;
// distf dist = compute_distance_with_norm(nb_data, query_data, norm);
// if (dist > set_L[L-1].distance_) {
// continue;
// }
//// if (dist >= set_L[L-1].distance_) {
//// continue;
//// }
// Candidate cand(nb_id, dist, false);
// idi r;
////#pragma omp critical
// {
// r = insert_into_queue(set_L, L, cand);
// if (r < nk) {
// nk = r;
// }
// }
// }
// }
// top_m_candidates_end = 0; // Clear top_m_candidates
//
// if (nk <= last_k) {
// k = nk;
// } else {
// k = last_k + 1;
// }
// }
//
////#pragma omp parallel for
// for (idi k_i = 0; k_i < K; ++k_i) {
// set_K[k_i] = set_L[k_i].id_;
// }
//
//// {
//// printf("query_id: %u "
//// "count_visited: %lu %f%%\n",
//// query_id,
//// count_visited,
//// 100.0 * count_visited / num_v_);
//// }
//}
//
//inline void Searching::para_search_with_top_m_merge_queues(
// const idi M,
// const idi query_id,
// const idi K,
// const idi L,
// std::vector<Candidate> &set_L,
// const std::vector<idi> &init_ids,
// std::vector<idi> &set_K)
//{
//// {//test
//// printf("query_id: %u\n", query_id);
//// }
//// const idi local_queue_length = ((M - 1) / num_threads_ + 1) * width_;
// const idi local_queue_length = L;
// std::vector< std::vector<Candidate> > local_queues_list(num_threads_, std::vector<Candidate>(local_queue_length));
// std::vector<idi> local_queues_ends(num_threads_, 0);
// std::vector<uint8_t> is_visited(num_v_, 0);
//// boost::dynamic_bitset<> is_visited(num_v_);
//
// {
//#pragma omp parallel for
// for (idi c_i = 0; c_i < L; ++c_i) {
// is_visited[init_ids[c_i]] = 1;
// }
// }
//
// const dataf *query_data = queries_load_ + query_id * dimension_;
//#pragma omp parallel for
// for (idi v_i = 0; v_i < L; ++v_i) {
// idi v_id = init_ids[v_i];
// _mm_prefetch(opt_nsg_graph_ + v_id * vertex_bytes_, _MM_HINT_T0);
// }
// // Get the distances of all candidates, store in the set set_L.
//#pragma omp parallel for
// for (unsigned i = 0; i < L; i++) {
// unsigned v_id = init_ids[i];
// auto *v_data = reinterpret_cast<dataf *>(opt_nsg_graph_ + v_id * vertex_bytes_);
// dataf norm = *v_data++;
//// ++count_distance_computation;
// distf dist = compute_distance_with_norm(v_data, query_data, norm);
// set_L[i] = Candidate(v_id, dist, false); // False means not checked.
// }
// std::sort(set_L.begin(), set_L.begin() + L);
//
// std::vector<idi> top_m_candidates(M);
// idi top_m_candidates_end = 0;
// idi k = 0; // Index of first unchecked candidate.
// idi tmp_count = 0; // for debug
// while (k < L) {
// ++tmp_count;
//// {//test
//// printf("tmp_count: %d\n", tmp_count);
//// }
//
// // Select M candidates
// idi last_k = L;
//// Cannot use OpenMP here because this for-loop needs early break by the 2nd condition.
// for (idi c_i = k; c_i < L && top_m_candidates_end < M; ++c_i) {
// if (set_L[c_i].is_checked_) {
// continue;
// }
// last_k = c_i; // Record the location of the last candidate selected.
// set_L[c_i].is_checked_ = true;
// top_m_candidates[top_m_candidates_end++] = set_L[c_i].id_;
// }
//
// // Push M candidates' neighbors into the queue.
//#pragma omp parallel for
// for (idi c_i = 0; c_i < top_m_candidates_end; ++c_i) {
// int tid = omp_get_thread_num();
// idi cand_id = top_m_candidates[c_i];
// _mm_prefetch(opt_nsg_graph_ + cand_id * vertex_bytes_ + data_bytes_, _MM_HINT_T0);
// idi *out_edges = (idi *) (opt_nsg_graph_ + cand_id * vertex_bytes_ + data_bytes_);
// idi out_degree = *out_edges++;
// for (idi n_i = 0; n_i < out_degree; ++n_i) {
// _mm_prefetch(opt_nsg_graph_ + out_edges[n_i] * vertex_bytes_, _MM_HINT_T0);
// }
// for (idi e_i = 0; e_i < out_degree; ++e_i) {
// idi nb_id = out_edges[e_i];
//// if (is_visited[nb_id]) {
//// continue;
//// }
//// is_visited[nb_id] = 1;
//
// if (!AtomicOps::CAS(is_visited.data() + nb_id,
// static_cast<uint8_t>(0),
// static_cast<uint8_t>(1))) {
// continue;
// }
//
// auto *nb_data = reinterpret_cast<dataf *>(opt_nsg_graph_ + nb_id * vertex_bytes_);
// dataf norm = *nb_data++;
//// ++count_distance_computation;
// distf dist = compute_distance_with_norm(nb_data, query_data, norm);
// if (dist > set_L[L-1].distance_) {
// continue;
// }
//// if (dist >= set_L[L-1].distance_) {
//// continue;
//// }
// Candidate cand(nb_id, dist, false);
// // Add to the local queue.
// add_into_queue(local_queues_list[tid], local_queues_ends[tid], local_queue_length, cand);
// }
// }
// top_m_candidates_end = 0; // Clear top_m_candidates
//
// idi nk = L;
//// // Merge. Parallel merging in every two queues.
//// {
//// for (int tid = 0; tid < num_threads_; ++tid) {
//// if (0 == local_queues_ends[tid]) continue;
//// idi r = merge_two_queues_into_1st_queue_para(
//// set_L,
//// 0,
//// L,
//// local_queues_list[tid],
//// 0,
//// local_queues_ends[tid]);
////// idi r = merge_two_queues_into_1st_queue_seq(
////// set_L,
////// 0,
////// L,
////// local_queues_list[tid],
////// 0,
////// local_queues_ends[tid]);
//// local_queues_ends[tid] = 0; // Reset the local queue
//// if (r < nk) {
//// nk = r;
//// }
//// }
//// }
//// {// text
//// if (query_id == 4 &&
//// tmp_count == 5) {
//// // Print local queues
//// for (int t_i = 0; t_i < num_threads_; ++t_i) {
////// idi start_i = t_i * local_queue_length;
//// for (idi q_i = 0; q_i < local_queues_ends[t_i]; ++q_i) {
//// printf("t[%u][%u]: "
//// "id: %u "
//// "dist: %f\n",
//// t_i, q_i,
//// local_queues_list[t_i][q_i].id_,
//// local_queues_list[t_i][q_i].distance_);
//// }
//// }
//// printf("----------\n");
//// for (idi i = 0; i < L; ++i) {
//// printf("set_L[%u]: "
//// "id: %u "
//// "dist: %f\n",
//// i,
//// set_L[i].id_,
//// set_L[i].distance_);
//// }
//// printf("----------\n");
//// }
//// }
// // Merge. Merge all queues in parallel.
// {
// if (num_threads_ > 1) {
// idi r = merge_all_queues_para_list(
// local_queues_list,
// local_queues_ends,
// set_L,
// L);
// if (r < nk) {
// nk = r;
// }
// } else {
// if (local_queues_ends[0]) {
// idi r = merge_two_queues_into_1st_queue_seq_fixed(
// set_L,
// 0,
// L,
// local_queues_list[0],
// 0,
// local_queues_ends[0]);
// local_queues_ends[0] = 0;
// if (r < nk) {
// nk = r;
// }
// }
// }
// }
//// {//test
//// if (query_id == 4) {
//// for (idi i = 0; i < L; ++i) {
//// printf("tmp_count: %u "
//// "set_L[%u]: "
//// "id: %u "
//// "dist: %f\n",
//// tmp_count,
//// i,
//// set_L[i].id_,
//// set_L[i].distance_);
//// }
//// }
////
//// }
//
// if (nk <= last_k) {
// k = nk;
// } else {
// k = last_k + 1;
// }
// }
//
//#pragma omp parallel for
// for (idi k_i = 0; k_i < K; ++k_i) {
// set_K[k_i] = set_L[k_i].id_;
// }
//// {
//// exit(1);
//// }
//// {//test
////
////// if (query_id == 4) {
//// for (idi i = 0; i < L; ++i) {
//// printf("set_L[%u]: "
//// "id: %u "
//// "dist: %f\n",
//// i,
//// set_L[i].id_,
//// set_L[i].distance_);
//// }
////// exit(1);
////// }
//// }
//}
//
////// Using local queue and then sequential merge.
//inline void Searching::para_search_with_top_m_queues_seq_merge(
// const PANNS::idi M,
// const PANNS::idi query_id,
// const PANNS::idi K,
// const PANNS::idi L,
// std::vector<Candidate> &set_L,
// const std::vector<idi> &init_ids,
// std::vector<idi> &set_K)
//// std::vector< std::vector<idi> > &top_m_list)
//{
//// const idi local_queue_length = ((L - 1) / num_threads_ + 1) * width_;
// const idi local_queue_length = L;
// std::vector< std::vector<Candidate> > local_queues_list(num_threads_, std::vector<Candidate>(local_queue_length));
// std::vector<idi> local_queues_ends(num_threads_, 0);
// std::vector<uint8_t> is_visited(num_v_, 0);
//// boost::dynamic_bitset<> is_visited(num_v_);
//
// {
//#pragma omp parallel for
// for (idi c_i = 0; c_i < L; ++c_i) {
// is_visited[init_ids[c_i]] = 1;
// }
// }
//
// const dataf *query_data = queries_load_ + query_id * dimension_;
//// for (idi v_i = 0; v_i < L; ++v_i) {
//// idi v_id = init_ids[v_i];
//// _mm_prefetch(opt_nsg_graph_ + v_id * vertex_bytes_, _MM_HINT_T0);
//// }
// // Get the distances of all candidates, store in the set set_L.
//#pragma omp parallel for
// for (unsigned i = 0; i < L; i++) {
// unsigned v_id = init_ids[i];
// auto *v_data = reinterpret_cast<dataf *>(opt_nsg_graph_ + v_id * vertex_bytes_);
// dataf norm = *v_data++;
//// ++count_distance_computation;
// distf dist = compute_distance_with_norm(v_data, query_data, norm);
// set_L[i] = Candidate(v_id, dist, false); // False means not checked.
// }
// std::sort(set_L.begin(), set_L.begin() + L);
//
// std::vector<idi> top_m_candidates(M);
// idi top_m_candidates_end = 0;
// idi k = 0; // Index of first unchecked candidate.
// idi tmp_count = 0; // for debug
// while (k < L) {
// ++tmp_count;
//// {
//// printf("tmp_count: %u "
//// "k: %u\n",
//// tmp_count,
//// k);
//// }
//
//// unsigned nk = L;
//// int nk = L;
//
// // Select M candidates
// idi last_k = L;
// for (idi c_i = k; c_i < L && top_m_candidates_end < M; ++c_i) {
// if (set_L[c_i].is_checked_) {
// continue;
// }
// last_k = c_i; // Record the location of the last candidate selected.
// set_L[c_i].is_checked_ = true;
// top_m_candidates[top_m_candidates_end++] = set_L[c_i].id_;
// }
//
// // Push M candidates' neighbors into the queue.
//#pragma omp parallel for
// for (idi c_i = 0; c_i < top_m_candidates_end; ++c_i) {
// int tid = omp_get_thread_num();
// idi cand_id = top_m_candidates[c_i];
// _mm_prefetch(opt_nsg_graph_ + cand_id * vertex_bytes_ + data_bytes_, _MM_HINT_T0);
// idi *out_edges = (idi *) (opt_nsg_graph_ + cand_id * vertex_bytes_ + data_bytes_);
// idi out_degree = *out_edges++;
// for (idi n_i = 0; n_i < out_degree; ++n_i) {
// _mm_prefetch(opt_nsg_graph_ + out_edges[n_i] * vertex_bytes_, _MM_HINT_T0);
// }
// for (idi e_i = 0; e_i < out_degree; ++e_i) {
// idi nb_id = out_edges[e_i];
//// if (is_visited[nb_id]) {
//// continue;
//// }
//// is_visited[nb_id] = 1;
//
// if (!AtomicOps::CAS(is_visited.data() + nb_id,
// static_cast<uint8_t>(0),
// static_cast<uint8_t>(1))) {
// continue;
// }
//
// auto *nb_data = reinterpret_cast<dataf *>(opt_nsg_graph_ + nb_id * vertex_bytes_);
// dataf norm = *nb_data++;
//// ++count_distance_computation;
// distf dist = compute_distance_with_norm(nb_data, query_data, norm);
// if (dist > set_L[L-1].distance_) {
// continue;
// }
//// if (dist >= set_L[L-1].distance_) {
//// continue;
//// }
// Candidate cand(nb_id, dist, false);
//// idi r;
////#pragma omp critical
//// {
//// r = insert_into_queue(set_L, L, cand);
//// if (r < nk) {
//// nk = r;
//// }
//// }
// // Add to the local queue.
// add_into_queue(local_queues_list[tid], local_queues_ends[tid], local_queue_length, cand);
// }
// }
// top_m_candidates_end = 0; // Clear top_m_candidates
//
// idi nk = L;
// // Merge
// {
// for (int tid = 0; tid < num_threads_; ++tid) {
// if (0 == local_queues_ends[tid]) continue;
// idi r = merge_two_queues_into_1st_queue_seq_fixed(
// set_L,
// 0,
// L,
// local_queues_list[tid],
// 0,
// local_queues_ends[tid]);
//// L + 1);
// local_queues_ends[tid] = 0; // Reset the local queue
// if (r < nk) {
// nk = r;
// }
// }
// }
//
// if (nk <= last_k) {
// k = nk;
// } else {
// k = last_k + 1;
// }
// }
//
//#pragma omp parallel for
// for (idi k_i = 0; k_i < K; ++k_i) {
// set_K[k_i] = set_L[k_i].id_;
// }
////
//// {//test
//// for (idi k_i = 0; k_i < K; ++k_i) {
//// printf("%u: %u: %u %f\n",
//// query_id,
//// k_i, set_L[k_i].id_, set_L[k_i].distance_);
//// }
//// exit(1);
//// }
//}
//
//inline void Searching::para_search_with_top_m_merge_queues_no_CAS(
// const idi M,
// const idi query_id,
// const idi K,
// const idi L,
// std::vector<Candidate> &set_L,
// const std::vector<idi> &init_ids,
// std::vector<idi> &set_K,
// const idi local_queue_length,
// std::vector< std::vector<Candidate> > &local_queues_list,
// std::vector<idi> &local_queues_ends,
//// std::vector<uint8_t> &is_visited)
// boost::dynamic_bitset<> &is_visited)
//{
////// const idi local_queue_length = ((M - 1) / num_threads_ + 1) * width_;
//// const idi local_queue_length = L;
//// std::vector< std::vector<Candidate> > local_queues_list(num_threads_, std::vector<Candidate>(local_queue_length));
//// std::vector<idi> local_queues_ends(num_threads_, 0);
////// std::vector<uint8_t> is_visited(num_v_, 0);
//// boost::dynamic_bitset<> is_visited(num_v_);
//
// {
//#pragma omp parallel for
// for (idi c_i = 0; c_i < L; ++c_i) {
// is_visited[init_ids[c_i]] = 1;
// }
// }
//
// const dataf *query_data = queries_load_ + query_id * dimension_;
//#pragma omp parallel for
// for (idi v_i = 0; v_i < L; ++v_i) {
// idi v_id = init_ids[v_i];
// _mm_prefetch(opt_nsg_graph_ + v_id * vertex_bytes_, _MM_HINT_T0);
// }
// // Get the distances of all candidates, store in the set set_L.
//#pragma omp parallel for
// for (unsigned i = 0; i < L; i++) {
// unsigned v_id = init_ids[i];
// auto *v_data = reinterpret_cast<dataf *>(opt_nsg_graph_ + v_id * vertex_bytes_);
// dataf norm = *v_data++;
//// ++count_distance_computation;
// distf dist = compute_distance_with_norm(v_data, query_data, norm);
// set_L[i] = Candidate(v_id, dist, false); // False means not checked.
// }
// std::sort(set_L.begin(), set_L.begin() + L);
//
// std::vector<idi> top_m_candidates(M);
// idi top_m_candidates_end = 0;
// idi k = 0; // Index of first unchecked candidate.
// idi tmp_count = 0; // for debug
// while (k < L) {
// ++tmp_count;
//
// // Select M candidates
// idi last_k = L;
//// Cannot use OpenMP here because this for-loop needs early break by the 2nd condition.
// for (idi c_i = k; c_i < L && top_m_candidates_end < M; ++c_i) {
// if (set_L[c_i].is_checked_) {
// continue;
// }
// last_k = c_i; // Record the location of the last candidate selected.
// set_L[c_i].is_checked_ = true;
// top_m_candidates[top_m_candidates_end++] = set_L[c_i].id_;
// }
//
// // Push M candidates' neighbors into the queue.
//#pragma omp parallel for
// for (idi c_i = 0; c_i < top_m_candidates_end; ++c_i) {
// int tid = omp_get_thread_num();
// idi cand_id = top_m_candidates[c_i];
// _mm_prefetch(opt_nsg_graph_ + cand_id * vertex_bytes_ + data_bytes_, _MM_HINT_T0);
// idi *out_edges = (idi *) (opt_nsg_graph_ + cand_id * vertex_bytes_ + data_bytes_);
// idi out_degree = *out_edges++;
// for (idi n_i = 0; n_i < out_degree; ++n_i) {
// _mm_prefetch(opt_nsg_graph_ + out_edges[n_i] * vertex_bytes_, _MM_HINT_T0);
// }
// for (idi e_i = 0; e_i < out_degree; ++e_i) {
// idi nb_id = out_edges[e_i];
// if (is_visited[nb_id]) {
// continue;
// }
// is_visited[nb_id] = 1;
//
//// if (!AtomicOps::CAS(is_visited.data() + nb_id,
//// static_cast<uint8_t>(0),
//// static_cast<uint8_t>(1))) {
//// continue;
//// }
//
// auto *nb_data = reinterpret_cast<dataf *>(opt_nsg_graph_ + nb_id * vertex_bytes_);
// dataf norm = *nb_data++;
//// ++count_distance_computation;
// distf dist = compute_distance_with_norm(nb_data, query_data, norm);
// if (dist > set_L[L-1].distance_) {
// continue;
// }
//// if (dist >= set_L[L-1].distance_) {
//// continue;
//// }
// Candidate cand(nb_id, dist, false);
// // Add to the local queue.
// add_into_queue(local_queues_list[tid], local_queues_ends[tid], local_queue_length, cand);
// }
// }
// top_m_candidates_end = 0; // Clear top_m_candidates
//
// idi nk = L;
//// // Merge. Parallel merging in every two queues.
//// {
//// for (int tid = 0; tid < num_threads_; ++tid) {
//// if (0 == local_queues_ends[tid]) continue;
//// idi r = merge_two_queues_into_1st_queue_para(
//// set_L,
//// 0,
//// L,
//// local_queues_list[tid],
//// 0,
//// local_queues_ends[tid]);
////// idi r = merge_two_queues_into_1st_queue_seq(
////// set_L,
////// 0,
////// L,
////// local_queues_list[tid],
////// 0,
////// local_queues_ends[tid]);
//// local_queues_ends[tid] = 0; // Reset the local queue
//// if (r < nk) {
//// nk = r;
//// }
//// }
//// }
//// // Merge. Merge all queues in parallel.
//// {
//// if (num_threads_ > 1) {
//// idi r = merge_all_queues_para(
//// local_queues_list,
//// local_queues_ends,
//// set_L,
//// L);
//// if (r < nk) {
//// nk = r;
//// }
//// } else {
//// if (local_queues_ends[0]) {
//// idi r = merge_two_queues_into_1st_queue_seq(
//// set_L,
//// 0,
//// L,
//// local_queues_list[0],
//// 0,
//// local_queues_ends[0]);
//// local_queues_ends[0] = 0;
//// if (r < nk) {
//// nk = r;
//// }
//// }
//// }
//// }
// // Merge
// {
// for (int tid = 0; tid < num_threads_; ++tid) {
// if (0 == local_queues_ends[tid]) continue;
// idi r = merge_two_queues_into_1st_queue_seq_fixed(
// set_L,
// 0,
// L,
// local_queues_list[tid],
// 0,
// local_queues_ends[tid]);
//// L + 1);
// local_queues_ends[tid] = 0; // Reset the local queue
// if (r < nk) {
// nk = r;
// }
// }
// }
//
// if (nk <= last_k) {
// k = nk;
// } else {
// k = last_k + 1;
// }
// }
//
//#pragma omp parallel for
// for (idi k_i = 0; k_i < K; ++k_i) {
// set_K[k_i] = set_L[k_i].id_;
// }
//
// {// Reset
// is_visited.reset();
//// std::fill(is_visited.begin(), is_visited.end(), 0);
// std::fill(local_queues_ends.begin(), local_queues_ends.end(), 0);
// }
//}
//inline void Searching::para_search_with_top_m_merge_queues_in_array(
//inline void Searching::para_search_with_top_m_merge_queues_new_threshold(
// const idi M,
// const idi query_id,
// const idi K,
// const idi L,
// std::vector<Candidate> &set_L,
// const std::vector<idi> &init_ids,
// std::vector<idi> &set_K,
// const idi local_queue_length, // Maximum size of local queue
//// std::vector< std::vector<Candidate> > &local_queues_list,
// std::vector<Candidate> &local_queues_array,
// std::vector<idi> &local_queues_ends, // Sizes of local queue
// BitVector &is_visited)
//// std::vector<uint8_t> &is_visited)
//// boost::dynamic_bitset<> &is_visited)
//{
// {
//#pragma omp parallel for
// for (idi c_i = 0; c_i < L; ++c_i) {
//// is_visited[init_ids[c_i]] = 1;
// is_visited.atomic_set_bit(init_ids[c_i]);
// }
// }
//
// const dataf *query_data = queries_load_ + query_id * dimension_;
//#pragma omp parallel for
// for (idi v_i = 0; v_i < L; ++v_i) {
// idi v_id = init_ids[v_i];
// _mm_prefetch(opt_nsg_graph_ + v_id * vertex_bytes_, _MM_HINT_T0);
// }
// // Get the distances of all candidates, store in the set set_L.
//#pragma omp parallel for
// for (unsigned i = 0; i < L; i++) {
// unsigned v_id = init_ids[i];
// auto *v_data = reinterpret_cast<dataf *>(opt_nsg_graph_ + v_id * vertex_bytes_);
// dataf norm = *v_data++;
//// ++count_distance_computation;
// distf dist = compute_distance_with_norm(v_data, query_data, norm);
// set_L[i] = Candidate(v_id, dist, false); // False means not checked.
// }
// std::sort(set_L.begin(), set_L.begin() + L);
//
// idi min_index = L - 1;
// distf min_1st = set_L[min_index].distance_;
//
// std::vector<idi> top_m_candidates(M);
// idi top_m_candidates_end = 0;
// idi k = 0; // Index of first unchecked candidate.
// idi tmp_count = 0; // for debug
// while (k < L) {
// ++tmp_count;
//// {//test
//// printf("tmp_count: %d\n", tmp_count);
//// }
//
// // Select M candidates
// idi last_k = L;
//// Cannot use OpenMP here because this for-loop needs early break by the 2nd condition.
// for (idi c_i = k; c_i < L && top_m_candidates_end < M; ++c_i) {
// if (set_L[c_i].is_checked_) {
// continue;
// }
// last_k = c_i; // Record the location of the last candidate selected.
// set_L[c_i].is_checked_ = true;
// top_m_candidates[top_m_candidates_end++] = set_L[c_i].id_;
// }
//
// // Push M candidates' neighbors into the queue.
//#pragma omp parallel for
// for (idi c_i = 0; c_i < top_m_candidates_end; ++c_i) {
// int tid = omp_get_thread_num();
// const idi local_queue_start = tid * local_queue_length;
// idi cand_id = top_m_candidates[c_i];
// _mm_prefetch(opt_nsg_graph_ + cand_id * vertex_bytes_ + data_bytes_, _MM_HINT_T0);
// idi *out_edges = (idi *) (opt_nsg_graph_ + cand_id * vertex_bytes_ + data_bytes_);
// idi out_degree = *out_edges++;
// for (idi n_i = 0; n_i < out_degree; ++n_i) {
// _mm_prefetch(opt_nsg_graph_ + out_edges[n_i] * vertex_bytes_, _MM_HINT_T0);
// }
// for (idi e_i = 0; e_i < out_degree; ++e_i) {
// idi nb_id = out_edges[e_i];
//// { // Sequential edition
//// if (is_visited[nb_id]) {
//// continue;
//// }
//// is_visited[nb_id] = 1;
//// }
//// { // __ATOMIC_SEQ_CST edition
//// if (!AtomicOps::CAS(is_visited.data() + nb_id,
//// static_cast<uint8_t>(0),
//// static_cast<uint8_t>(1))) {
//// continue;
//// }
//// }
//// {// Acquire and Release edition
//// if (__atomic_load_n(is_visited.data() + nb_id, __ATOMIC_ACQUIRE)) {
//// continue;
//// }
//// __atomic_store_n(is_visited.data() + nb_id, 1, __ATOMIC_RELEASE);
//// }
// {// Self-defined BitVector
// if (is_visited.atomic_is_bit_set(nb_id)) {
// continue;
// }
// is_visited.atomic_set_bit(nb_id);
// }
//
// auto *nb_data = reinterpret_cast<dataf *>(opt_nsg_graph_ + nb_id * vertex_bytes_);
// dataf norm = *nb_data++;
//// ++count_distance_computation;
// distf dist = compute_distance_with_norm(nb_data, query_data, norm);
//
// if (dist > min_1st) {
// continue;
// } else if (min_index > 0) {
// // Inserted, so min_1st needs update
// if (dist > set_L[min_index - 1].distance_) {
// min_1st = dist;
// if (min_index < L - 1) {
// ++min_index;
// }
// } else {
// min_1st = set_L[--min_index].distance_;
// }
//// min_1st = set_L[--min_index].distance_;
// }
//
//// if (dist > set_L[L-1].distance_) {
//// continue;
//// }
//
// Candidate cand(nb_id, dist, false);
// // Add to the local queue.
// add_into_queue(local_queues_array, local_queue_start, local_queues_ends[tid], local_queue_length, cand);
// }
// }
// top_m_candidates_end = 0; // Clear top_m_candidates
//
// idi nk = L;
//// // Merge. Parallel merging in every two queues.
//// {
//// for (int tid = 0; tid < num_threads_; ++tid) {
//// if (0 == local_queues_ends[tid]) continue;
//// idi r = merge_two_queues_into_1st_queue_para(
//// set_L,
//// 0,
//// L,
//// local_queues_list[tid],
//// 0,
//// local_queues_ends[tid]);
////// idi r = merge_two_queues_into_1st_queue_seq(
////// set_L,
////// 0,
////// L,
////// local_queues_list[tid],
////// 0,
////// local_queues_ends[tid]);
//// local_queues_ends[tid] = 0; // Reset the local queue
//// if (r < nk) {
//// nk = r;
//// }
//// }
//// }
// // Merge. Merge all queues in parallel.
// {
// if (num_threads_ > 1) {
// idi r = merge_all_queues_para_array(
//// local_queues_list,
// local_queues_array,
// local_queues_ends,
// local_queue_length,
// set_L,
// L);
// if (r < nk) {
// nk = r;
// }
// } else {
// if (local_queues_ends[0]) {
// idi r = merge_two_queues_into_1st_queue_seq_fixed(
// set_L,
// 0,
// L,
//// local_queues_list[0],
// local_queues_array,
// 0,
// local_queues_ends[0]);
// local_queues_ends[0] = 0;
// if (r < nk) {
// nk = r;
// }
// }
// }
// }
//// // Merge Sequentially
//// {
//// for (int tid = 0; tid < num_threads_; ++tid) {
//// if (0 == local_queues_ends[tid]) continue;
//// idi r = merge_two_queues_into_1st_queue_seq_fixed(
//// set_L,
//// 0,
//// L,
////// local_queues_list[tid],
////// 0,
//// local_queues_array,
//// tid * local_queue_length,
//// local_queues_ends[tid]);
////// L + 1);
//// local_queues_ends[tid] = 0; // Reset the local queue
//// if (r < nk) {
//// nk = r;
//// }
//// }
//// }
//
// if (nk <= last_k) {
// k = nk;
// } else {
// k = last_k + 1;
// }
// }
//
//#pragma omp parallel for
// for (idi k_i = 0; k_i < K; ++k_i) {
// set_K[k_i] = set_L[k_i].id_;
// }
//
// {// Reset
//// is_visited.reset();
//// std::fill(is_visited.begin(), is_visited.end(), 0);
// is_visited.clear_all();
// std::fill(local_queues_ends.begin(), local_queues_ends.end(), 0);
// }
//}
///*
// * 5/7/2020-15:14
// * Use 1 threads to scale M until the value_M_middle.
// * Then use multiple threads.
// */
//inline void Searching::para_search_with_top_m_merge_queues_middle_m(
// const idi value_M_middle,
// const idi value_M_max,
// const idi query_id,
// const idi K,
// const idi L,
// std::vector<Candidate> &set_L,
// const std::vector<idi> &init_ids,
// std::vector<idi> &set_K,
// const idi local_queue_length, // Maximum size of local queue
// const idi base_set_L, // base_set_L = (num_threads_ - 1) * local_queue_length;
// std::vector<idi> &local_queues_ends, // Sizes of local queue
// std::vector<idi> &top_m_candidates,
// boost::dynamic_bitset<> &is_visited)
//{
// time_initialization_ -= WallTimer::get_time_mark();
//// const idi base_set_L = (num_threads_ - 1) * local_queue_length;
////#pragma omp parallel for
// for (idi c_i = 0; c_i < L; ++c_i) {
// is_visited[init_ids[c_i]] = 1;
// }
//
// const dataf *query_data = queries_load_ + query_id * dimension_;
//#pragma omp parallel for
// for (idi v_i = 0; v_i < L; ++v_i) {
// idi v_id = init_ids[v_i];
// _mm_prefetch(opt_nsg_graph_ + v_id * vertex_bytes_, _MM_HINT_T0);
// }
// uint64_t tmp_count_computation = 0;
// // Get the distances of all candidates, store in the set set_L.
////#pragma omp parallel for
//#pragma omp parallel for reduction(+ : tmp_count_computation)
// for (unsigned i = 0; i < L; i++) {
// unsigned v_id = init_ids[i];
// auto *v_data = reinterpret_cast<dataf *>(opt_nsg_graph_ + v_id * vertex_bytes_);
// dataf norm = *v_data++;
// ++tmp_count_computation;
// distf dist = compute_distance_with_norm(v_data, query_data, norm);
// set_L[i + base_set_L] = Candidate(v_id, dist, false); // False means not checked.
// }
// count_distance_computation_ += tmp_count_computation;
// tmp_count_computation = 0;
//// std::sort(set_L.begin(), set_L.begin() + L);
// std::sort(
// set_L.begin() + base_set_L,
// set_L.begin() + base_set_L + L);
// local_queues_ends[num_threads_ - 1] = L;
// time_initialization_ += WallTimer::get_time_mark();
//
// idi top_m_candidates_end = 0;
// idi k = 0; // Index of first unchecked candidate.
// idi tmp_count = 0; // for debug
// idi M = 1;
//
// time_sequential_phase_ -= WallTimer::get_time_mark();
// { // Single thread
// while (k < L && M < value_M_middle) {
// ++tmp_count;
//// {//test
//// printf("tmp_count: %d\n", tmp_count);
//// }
//
// // Select M candidates
// idi last_k = L;
//// Cannot use OpenMP here because this for-loop needs early break by the 2nd condition.
// for (idi c_i = k; c_i < L && top_m_candidates_end < M; ++c_i) {
// idi index_set_L = c_i + base_set_L;
// if (set_L[index_set_L].is_checked_) {
// continue;
// }
// last_k = c_i; // Record the location of the last candidate selected.
// set_L[index_set_L].is_checked_ = true;
// top_m_candidates[top_m_candidates_end++] = set_L[index_set_L].id_;
// }
//
// idi nk = L;
// // Push M candidates' neighbors into the queue.
// for (idi c_i = 0; c_i < top_m_candidates_end; ++c_i) {
// idi cand_id = top_m_candidates[c_i];
// _mm_prefetch(opt_nsg_graph_ + cand_id * vertex_bytes_ + data_bytes_, _MM_HINT_T0);
// idi *out_edges = (idi *) (opt_nsg_graph_ + cand_id * vertex_bytes_ + data_bytes_);
// idi out_degree = *out_edges++;
// for (idi n_i = 0; n_i < out_degree; ++n_i) {
// _mm_prefetch(opt_nsg_graph_ + out_edges[n_i] * vertex_bytes_, _MM_HINT_T0);
// }
// for (idi e_i = 0; e_i < out_degree; ++e_i) {
// idi nb_id = out_edges[e_i];
// { // Sequential edition
// if (is_visited[nb_id]) {
// continue;
// }
// is_visited[nb_id] = 1;
// }
//
// auto *nb_data = reinterpret_cast<dataf *>(opt_nsg_graph_ + nb_id * vertex_bytes_);
// dataf norm = *nb_data++;
// ++tmp_count_computation;
// distf dist = compute_distance_with_norm(nb_data, query_data, norm);
// if (dist > set_L[L - 1 + base_set_L].distance_) {
// continue;
// }
//
// Candidate cand(nb_id, dist, false);
// // Thread 0 maintains the "global" queue
// idi r = add_into_queue(
// set_L,
// base_set_L,
// local_queues_ends[num_threads_ - 1],
// L,
// cand);
// if (r < nk) {
// nk = r;
// }
// }
// }
// top_m_candidates_end = 0; // Clear top_m_candidates
// count_distance_computation_ += tmp_count_computation;
// tmp_count_computation = 0;
//
// if (nk <= last_k) {
// k = nk;
// } else {
// k = last_k + 1;
// }
//
// {// Scale M
// if (M < value_M_max) {
// M <<= 1;
// } else {
// M = value_M_max;
// }
// }
//
// }
// }
// time_sequential_phase_ += WallTimer::get_time_mark();
//
// time_parallel_phase_ -= WallTimer::get_time_mark();
// uint64_t tmp_count_add_to_queue = 0;
// double tmp_time_pick_top_m = 0;
// double tmp_time_distance_computation = 0;
// double tmp_time_add_to_queue = 0.0;
// { // Multiple Threads
// while (k < L) {
// time_expand_ -= WallTimer::get_time_mark();
// ++tmp_count;
//// {//test
//// printf("tmp_count: %d\n", tmp_count);
//// }
// // Select M candidates
// idi last_k = L;
// time_pick_top_m_ -= WallTimer::get_time_mark();
//// Cannot use OpenMP here because this for-loop needs early break by the 2nd condition.
// for (idi c_i = k; c_i < L && top_m_candidates_end < M; ++c_i) {
// idi index_set_L = c_i + base_set_L;
// if (set_L[index_set_L].is_checked_) {
// continue;
// }
// last_k = c_i; // Record the location of the last candidate selected.
// set_L[index_set_L].is_checked_ = true;
// top_m_candidates[top_m_candidates_end++] = set_L[index_set_L].id_;
// }
// time_pick_top_m_ += WallTimer::get_time_mark();
//
//
// idi nk = L;
// // Push M candidates' neighbors into the queue.
//#pragma omp parallel for reduction(+ : tmp_count_computation) \
// reduction(+ : tmp_count_add_to_queue) \
// reduction(+ : tmp_time_pick_top_m) \
// reduction(+ : tmp_time_distance_computation) \
// reduction(+ : tmp_time_add_to_queue)
//// for (int tid = 0; tid < num_threads_; ++tid) {
// for (idi c_i = 0; c_i < top_m_candidates_end; ++c_i) {
// tmp_time_pick_top_m -= WallTimer::get_time_mark();
// int tid = omp_get_thread_num();
// idi cand_id = top_m_candidates[c_i];
//// _mm_prefetch(opt_nsg_graph_ + cand_id * vertex_bytes_ + data_bytes_, _MM_HINT_T0);
// idi *out_edges = (idi *) (opt_nsg_graph_ + cand_id * vertex_bytes_ + data_bytes_);
// idi out_degree = *out_edges++;
//// for (idi n_i = 0; n_i < out_degree; ++n_i) {
//// _mm_prefetch(opt_nsg_graph_ + out_edges[n_i] * vertex_bytes_, _MM_HINT_T0);
//// }
// tmp_time_pick_top_m += WallTimer::get_time_mark();
// for (idi e_i = 0; e_i < out_degree; ++e_i) {
// tmp_time_distance_computation -= WallTimer::get_time_mark();
// idi nb_id = out_edges[e_i];
// { // Sequential edition
// if (is_visited[nb_id]) {
// tmp_time_distance_computation += WallTimer::get_time_mark();
// continue;
// }
// is_visited[nb_id] = 1;
// }
//
// auto *nb_data = reinterpret_cast<dataf *>(opt_nsg_graph_ + nb_id * vertex_bytes_);
// dataf norm = *nb_data++;
// ++tmp_count_computation;
// distf dist = compute_distance_with_norm(nb_data, query_data, norm);
// tmp_time_distance_computation += WallTimer::get_time_mark();
// if (dist > set_L[L - 1 + base_set_L].distance_) {
// continue;
// }
// ++tmp_count_add_to_queue;
// Candidate cand(nb_id, dist, false);
// // Add to the local queue.
//// tmp_time_pick_top_m -= WallTimer::get_time_mark();
// tmp_time_add_to_queue -= WallTimer::get_time_mark();
// if (0 != tid) {
// // Non-Master threads using local queues
// add_into_queue(
// set_L,
// (tid - 1) * local_queue_length,
// local_queues_ends[tid - 1],
// local_queue_length,
// cand);
// } else {
// // Thread 0 maintains the "global" queue
// idi r = add_into_queue(
// set_L,
// base_set_L,
// local_queues_ends[num_threads_ - 1],
// L,
// cand);
// if (r < nk) {
// nk = r;
// }
// }
// tmp_time_add_to_queue += WallTimer::get_time_mark();
//// tmp_time_pick_top_m += WallTimer::get_time_mark();
// }
// }
// time_add_to_queue_ += tmp_time_add_to_queue;
// tmp_time_add_to_queue = 0;
//// }
// time_distance_computation_ += tmp_time_distance_computation;
// tmp_time_distance_computation = 0;
// time_pick_top_m_ += tmp_time_pick_top_m;
// tmp_time_pick_top_m = 0;
// top_m_candidates_end = 0; // Clear top_m_candidates
// count_add_to_queue_ += tmp_count_add_to_queue;
// tmp_count_add_to_queue = 0;
// count_distance_computation_ += tmp_count_computation;
// tmp_count_computation = 0;
// time_expand_ += WallTimer::get_time_mark();
//
//
//// // Merge. Merge all queues in parallel.
// {
// time_merge_ -= WallTimer::get_time_mark();
// if (num_threads_ > 1) {
// idi r = merge_all_queues_para_array(
// set_L,
// local_queues_ends,
// local_queue_length,
// L);
// if (r < nk) {
// nk = r;
// }
// }
// time_merge_ += WallTimer::get_time_mark();
// }
// if (nk <= last_k) {
// k = nk;
// } else {
// k = last_k + 1;
// }
// {// Scale M
// if (M < value_M_max) {
// M <<= 1;
// } else {
// M = value_M_max;
// }
// }
//
// }
// }
// time_parallel_phase_ += WallTimer::get_time_mark();
//
// time_ending_ -= WallTimer::get_time_mark();
//#pragma omp parallel for
// for (idi k_i = 0; k_i < K; ++k_i) {
// set_K[k_i] = set_L[k_i + base_set_L].id_;
//// set_K[k_i] = set_L[k_i].id_;
// }
//
// {// Reset
//// std::fill(is_visited.begin(), is_visited.end(), 0);
// is_visited.reset();
//// is_visited.clear_all();
// std::fill(local_queues_ends.begin(), local_queues_ends.end(), 0);
// }
//
// time_ending_ += WallTimer::get_time_mark();
//// {//test
//// if (3 == query_id) {
//// exit(1);
//// }
//// }
//}
inline void Searching::para_search_with_top_m_merge_queues_middle_m_no_merge(
const uint64_t computation_threshold,
const idi value_M_middle,
const idi value_M_max,
const idi query_id,
const idi K,
const idi L,
const idi init_size,
std::vector<Candidate> &set_L,
const std::vector<idi> &init_ids,
std::vector<idi> &set_K,
const idi local_queue_length, // Maximum size of local queue
const idi base_set_L, // base_set_L = (num_threads_ - 1) * local_queue_length;
std::vector<idi> &local_queues_ends, // Sizes of local queue
std::vector<idi> &top_m_candidates,
boost::dynamic_bitset<> &is_visited)
{
uint64_t count_single_query_computation = 0;
uint64_t count_init_computation = 0;
uint64_t count_seq_computation = 0;
uint64_t count_par_computation = 0;
// {//test
// printf("query_id: %u\n", query_id);
// }
// time_initialization_ -= WallTimer::get_time_mark();
// const idi base_set_L = (num_threads_ - 1) * local_queue_length;
{
#pragma omp parallel for
for (idi c_i = 0; c_i < init_size; ++c_i) {
// for (idi c_i = 0; c_i < L; ++c_i) {
is_visited[init_ids[c_i]] = 1;
// is_visited.atomic_set_bit(init_ids[c_i]);
}
}
const dataf *query_data = queries_load_ + query_id * dimension_;
#pragma omp parallel for
for (idi v_i = 0; v_i < init_size; ++v_i) {
// for (idi v_i = 0; v_i < L; ++v_i) {
idi v_id = init_ids[v_i];
_mm_prefetch(opt_nsg_graph_ + v_id * vertex_bytes_, _MM_HINT_T0);
}
uint64_t tmp_count_computation = 0;
// Get the distances of all candidates, store in the set set_L.
//#pragma omp parallel for
#pragma omp parallel for reduction(+ : tmp_count_computation)
for (unsigned i = 0; i < init_size; i++) {
// for (unsigned i = 0; i < L; i++) {
unsigned v_id = init_ids[i];
auto *v_data = reinterpret_cast<dataf *>(opt_nsg_graph_ + v_id * vertex_bytes_);
dataf norm = *v_data++;
// ++count_distance_computation_;
++tmp_count_computation;
distf dist = compute_distance_with_norm(v_data, query_data, norm);
set_L[i + base_set_L] = Candidate(v_id, dist, false); // False means not checked.
// set_L[i] = Candidate(v_id, dist, false); // False means not checked.
}
count_distance_computation_ += tmp_count_computation;
count_init_computation += tmp_count_computation;
count_single_query_computation += tmp_count_computation;
tmp_count_computation = 0;
// std::sort(set_L.begin(), set_L.begin() + L);
std::sort(
set_L.begin() + base_set_L,
set_L.begin() + base_set_L + init_size);
// set_L.begin() + base_set_L + L);
local_queues_ends[num_threads_ - 1] = init_size;
// local_queues_ends[num_threads_ - 1] = L;
// time_initialization_ += WallTimer::get_time_mark();
// time_sequential_phase_ -= WallTimer::get_time_mark();
// std::vector<idi> top_m_candidates(M);
idi &global_queue_size = local_queues_ends[num_threads_ - 1];
idi top_m_candidates_end = 0;
idi k = 0; // Index of first unchecked candidate.
idi tmp_count = 0; // for debug
idi M = 1;
{ // Single thread
while (k < L && M < value_M_middle && count_single_query_computation <= computation_threshold) {
++tmp_count;
// {//test
// printf("tmp_count: %d\n", tmp_count);
// }
// int real_threads = std::min(static_cast<int>(M), num_threads_);
// idi queue_base = num_threads_ - real_threads;
// Select M candidates
idi last_k = L;
// Cannot use OpenMP here because this for-loop needs early break by the 2nd condition.
for (idi c_i = k; c_i < global_queue_size && top_m_candidates_end < M; ++c_i) {
// for (idi c_i = k; c_i < L && top_m_candidates_end < M; ++c_i) {
idi index_set_L = c_i + base_set_L;
if (set_L[index_set_L].is_checked_) {
continue;
}
last_k = c_i; // Record the location of the last candidate selected.
set_L[index_set_L].is_checked_ = true;
top_m_candidates[top_m_candidates_end++] = set_L[index_set_L].id_;
}
idi nk = L;
// Push M candidates' neighbors into the queue.
for (idi c_i = 0; c_i < top_m_candidates_end; ++c_i) {
idi cand_id = top_m_candidates[c_i];
_mm_prefetch(opt_nsg_graph_ + cand_id * vertex_bytes_ + data_bytes_, _MM_HINT_T0);
idi *out_edges = (idi *) (opt_nsg_graph_ + cand_id * vertex_bytes_ + data_bytes_);
idi out_degree = *out_edges++;
for (idi n_i = 0; n_i < out_degree; ++n_i) {
_mm_prefetch(opt_nsg_graph_ + out_edges[n_i] * vertex_bytes_, _MM_HINT_T0);
}
for (idi e_i = 0; e_i < out_degree; ++e_i) {
idi nb_id = out_edges[e_i];
{ // Sequential edition
if (is_visited[nb_id]) {
continue;
}
is_visited[nb_id] = 1;
}
auto *nb_data = reinterpret_cast<dataf *>(opt_nsg_graph_ + nb_id * vertex_bytes_);
dataf norm = *nb_data++;
// ++count_distance_computation_;
++tmp_count_computation;
distf dist = compute_distance_with_norm(nb_data, query_data, norm);
if (dist > set_L[global_queue_size - 1 + base_set_L].distance_) {
// if (dist > set_L[L - 1 + base_set_L].distance_) {
continue;
}
Candidate cand(nb_id, dist, false);
// Thread 0 maintains the "global" queue
idi r = add_into_queue(
set_L,
base_set_L,
global_queue_size,
// local_queues_ends[num_threads_ - 1],
L,
cand);
if (r < nk) {
nk = r;
}
}
}
top_m_candidates_end = 0; // Clear top_m_candidates
count_distance_computation_ += tmp_count_computation;
count_seq_computation += tmp_count_computation;
count_single_query_computation += tmp_count_computation;
tmp_count_computation = 0;
// {// Local queues' ends
// printf("query%u:iter: %u", query_id, tmp_count);
// for (int i_t = 0; i_t < num_threads_; ++i_t) {
// printf(" [%u]: %u", i_t, local_queues_ends[i_t]);
// }
// printf("\n");
// }
if (nk <= last_k) {
k = nk;
} else {
k = last_k + 1;
}
{// Scale M
if (M < value_M_max) {
M <<= 1;
} else {
M = value_M_max;
}
}
}
}
// time_sequential_phase_ += WallTimer::get_time_mark();
// time_parallel_phase_ -= WallTimer::get_time_mark();
{ // Multiple Threads
while (k < L and count_single_query_computation <= computation_threshold) {
// while (k < L) {
++tmp_count;
// {//test
// printf("tmp_count: %d "
// "k: %u "
// "global_queue_size: %u\n",
// tmp_count,
// k,
// global_queue_size);
// }
// int real_threads = std::min(static_cast<int>(M), num_threads_);
// idi queue_base = num_threads_ - real_threads;
// Select M candidates
idi last_k = L;
// Cannot use OpenMP here because this for-loop needs early break by the 2nd condition.
for (idi c_i = k; c_i < global_queue_size && top_m_candidates_end < M; ++c_i) {
// for (idi c_i = k; c_i < L && top_m_candidates_end < M; ++c_i) {
idi index_set_L = c_i + base_set_L;
if (set_L[index_set_L].is_checked_) {
continue;
}
last_k = c_i; // Record the location of the last candidate selected.
set_L[index_set_L].is_checked_ = true;
top_m_candidates[top_m_candidates_end++] = set_L[index_set_L].id_;
}
idi nk = L;
// Push M candidates' neighbors into the queue.
//#pragma omp parallel for reduction(+ : tmp_count_computation) num_threads(real_threads)
#pragma omp parallel for reduction(+ : tmp_count_computation)
for (idi c_i = 0; c_i < top_m_candidates_end; ++c_i) {
int tid = omp_get_thread_num();
idi cand_id = top_m_candidates[c_i];
_mm_prefetch(opt_nsg_graph_ + cand_id * vertex_bytes_ + data_bytes_, _MM_HINT_T0);
idi *out_edges = (idi *) (opt_nsg_graph_ + cand_id * vertex_bytes_ + data_bytes_);
idi out_degree = *out_edges++;
for (idi n_i = 0; n_i < out_degree; ++n_i) {
_mm_prefetch(opt_nsg_graph_ + out_edges[n_i] * vertex_bytes_, _MM_HINT_T0);
}
for (idi e_i = 0; e_i < out_degree; ++e_i) {
idi nb_id = out_edges[e_i];
{ // Sequential edition
if (is_visited[nb_id]) {
continue;
}
is_visited[nb_id] = 1;
}
auto *nb_data = reinterpret_cast<dataf *>(opt_nsg_graph_ + nb_id * vertex_bytes_);
dataf norm = *nb_data++;
// ++count_distance_computation_;
++tmp_count_computation;
distf dist = compute_distance_with_norm(nb_data, query_data, norm);
if (dist > set_L[global_queue_size - 1 + base_set_L].distance_) {
// if (dist > set_L[L - 1 + base_set_L].distance_) {
continue;
}
Candidate cand(nb_id, dist, false);
// Add to the local queue.
if (0 != tid) {
// Non-Master threads using local queues
add_into_queue(
set_L,
(tid - 1) * local_queue_length,
local_queues_ends[tid - 1],
local_queue_length,
cand);
} else {
// Thread 0 maintains the "global" queue
idi r = add_into_queue(
set_L,
base_set_L,
global_queue_size,
// local_queues_ends[num_threads_ - 1],
L,
cand);
if (r < nk) {
nk = r;
}
}
}
}
top_m_candidates_end = 0; // Clear top_m_candidates
count_distance_computation_ += tmp_count_computation;
count_par_computation += tmp_count_computation;
count_single_query_computation += tmp_count_computation;
tmp_count_computation = 0;
// {// Local queues' ends
// printf("query%u:iter: %u", query_id, tmp_count);
// for (int i_t = 0; i_t < num_threads_; ++i_t) {
// printf(" [%u]: %u", i_t, local_queues_ends[i_t]);
// }
// printf("\n");
// }
// Merge. Merge all queues in parallel.
{
if (num_threads_ > 1) {
// idi r = merge_all_queues_queue_base(
// set_L,
// local_queues_ends,
// queue_base,
// real_threads,
// local_queue_length,
// L);
idi r = merge_all_queues_para_array(
set_L,
local_queues_ends,
local_queue_length,
L);
if (r < nk) {
nk = r;
}
}
}
if (nk <= last_k) {
k = nk;
} else {
k = last_k + 1;
}
{// Scale M
if (M < value_M_max) {
M <<= 1;
} else {
M = value_M_max;
}
}
// {// Print relative distance
//// distf top_dist = set_L[base_set_L].distance_;
// for (idi i_l = 0; i_l < L; ++i_l) {
// printf("%u %f\n",
// tmp_count, set_L[i_l + base_set_L].distance_);
//// tmp_count, set_L[i_l + base_set_L].distance_ - top_dist);
// }
// }
}
}
// time_parallel_phase_ += WallTimer::get_time_mark();
#pragma omp parallel for
for (idi k_i = 0; k_i < K; ++k_i) {
set_K[k_i] = set_L[k_i + base_set_L].id_;
// set_K[k_i] = set_L[k_i].id_;
}
{// Reset
// std::fill(is_visited.begin(), is_visited.end(), 0);
is_visited.reset();
// is_visited.clear_all();
std::fill(local_queues_ends.begin(), local_queues_ends.end(), 0);
}
// {//test
// if (3 == query_id) {
// exit(1);
// }
// }
// {//test
// printf("count_single: %lu "
// "ct_init: %lu "
// "ct_seq: %lu "
// "ct_par: %lu\n",
// count_single_query_computation,
// count_init_computation,
// count_seq_computation,
// count_par_computation);
// }
}
///*
// * 6/15/2020-14:40
// * Queues merging together to the global queue
// */
//inline void Searching::para_search_with_top_m_merge_queues_sequential_merge(
// const idi value_M_middle,
// const idi value_M_max,
// const idi query_id,
// const idi K,
// const idi L,
// std::vector<Candidate> &set_L,
// const std::vector<idi> &init_ids,
// std::vector<idi> &set_K,
// const idi local_queue_length, // Maximum size of local queue
// const idi base_set_L, // base_set_L = (num_threads_ - 1) * local_queue_length;
// std::vector<idi> &local_queues_ends, // Sizes of local queue
// std::vector<idi> &top_m_candidates,
// boost::dynamic_bitset<> &is_visited)
//{
//// const idi base_set_L = (num_threads_ - 1) * local_queue_length;
// {
//#pragma omp parallel for
// for (idi c_i = 0; c_i < L; ++c_i) {
// is_visited[init_ids[c_i]] = 1;
//// is_visited.atomic_set_bit(init_ids[c_i]);
// }
// }
//
// const dataf *query_data = queries_load_ + query_id * dimension_;
//#pragma omp parallel for
// for (idi v_i = 0; v_i < L; ++v_i) {
// idi v_id = init_ids[v_i];
// _mm_prefetch(opt_nsg_graph_ + v_id * vertex_bytes_, _MM_HINT_T0);
// }
// uint64_t tmp_count_computation = 0;
// // Get the distances of all candidates, store in the set set_L.
////#pragma omp parallel for
//#pragma omp parallel for reduction(+ : tmp_count_computation)
// for (unsigned i = 0; i < L; i++) {
// unsigned v_id = init_ids[i];
// auto *v_data = reinterpret_cast<dataf *>(opt_nsg_graph_ + v_id * vertex_bytes_);
// dataf norm = *v_data++;
//// ++count_distance_computation_;
// ++tmp_count_computation;
// distf dist = compute_distance_with_norm(v_data, query_data, norm);
// set_L[i + base_set_L] = Candidate(v_id, dist, false); // False means not checked.
//// set_L[i] = Candidate(v_id, dist, false); // False means not checked.
// }
// count_distance_computation_ += tmp_count_computation;
// tmp_count_computation = 0;
//// std::sort(set_L.begin(), set_L.begin() + L);
// std::sort(
// set_L.begin() + base_set_L,
// set_L.begin() + base_set_L + L);
// local_queues_ends[num_threads_ - 1] = L;
//
//// std::vector<idi> top_m_candidates(M);
// idi top_m_candidates_end = 0;
// idi k = 0; // Index of first unchecked candidate.
// idi tmp_count = 0; // for debug
// idi M = 1;
//
// { // Single thread
// while (k < L && M < value_M_middle) {
// ++tmp_count;
//// {//test
//// printf("tmp_count: %d\n", tmp_count);
//// }
//
// // Select M candidates
// idi last_k = L;
//// Cannot use OpenMP here because this for-loop needs early break by the 2nd condition.
// for (idi c_i = k; c_i < L && top_m_candidates_end < M; ++c_i) {
// idi index_set_L = c_i + base_set_L;
// if (set_L[index_set_L].is_checked_) {
// continue;
// }
// last_k = c_i; // Record the location of the last candidate selected.
// set_L[index_set_L].is_checked_ = true;
// top_m_candidates[top_m_candidates_end++] = set_L[index_set_L].id_;
// }
//
//
// idi nk = L;
// // Push M candidates' neighbors into the queue.
// for (idi c_i = 0; c_i < top_m_candidates_end; ++c_i) {
// idi cand_id = top_m_candidates[c_i];
// _mm_prefetch(opt_nsg_graph_ + cand_id * vertex_bytes_ + data_bytes_, _MM_HINT_T0);
// idi *out_edges = (idi *) (opt_nsg_graph_ + cand_id * vertex_bytes_ + data_bytes_);
// idi out_degree = *out_edges++;
// for (idi n_i = 0; n_i < out_degree; ++n_i) {
// _mm_prefetch(opt_nsg_graph_ + out_edges[n_i] * vertex_bytes_, _MM_HINT_T0);
// }
// for (idi e_i = 0; e_i < out_degree; ++e_i) {
// idi nb_id = out_edges[e_i];
// { // Sequential edition
// if (is_visited[nb_id]) {
// continue;
// }
// is_visited[nb_id] = 1;
// }
//
// auto *nb_data = reinterpret_cast<dataf *>(opt_nsg_graph_ + nb_id * vertex_bytes_);
// dataf norm = *nb_data++;
//// ++count_distance_computation_;
// ++tmp_count_computation;
// distf dist = compute_distance_with_norm(nb_data, query_data, norm);
// if (dist > set_L[L - 1 + base_set_L].distance_) {
// continue;
// }
//
// Candidate cand(nb_id, dist, false);
// // Thread 0 maintains the "global" queue
// idi r = add_into_queue(
// set_L,
// base_set_L,
// local_queues_ends[num_threads_ - 1],
// L,
// cand);
// if (r < nk) {
// nk = r;
// }
// }
// }
// top_m_candidates_end = 0; // Clear top_m_candidates
// count_distance_computation_ += tmp_count_computation;
// tmp_count_computation = 0;
//
// if (nk <= last_k) {
// k = nk;
// } else {
// k = last_k + 1;
// }
//
// {// Scale M
// if (M < value_M_max) {
// M <<= 1;
// } else {
// M = value_M_max;
// }
// }
// }
// }
//
// { // Multiple Threads
// while (k < L) {
// ++tmp_count;
//// {//test
//// if (num_threads_ == 2) {
//// printf("tmp_count: %d "
//// "k: %u\n",
//// tmp_count,
//// k);
//// }
//// }
// // Select M candidates
// idi last_k = L;
//// Cannot use OpenMP here because this for-loop needs early break by the 2nd condition.
// for (idi c_i = k; c_i < L && top_m_candidates_end < M; ++c_i) {
// idi index_set_L = c_i + base_set_L;
// if (set_L[index_set_L].is_checked_) {
// continue;
// }
// last_k = c_i; // Record the location of the last candidate selected.
// set_L[index_set_L].is_checked_ = true;
// top_m_candidates[top_m_candidates_end++] = set_L[index_set_L].id_;
// }
//
//
// idi nk = L;
// // Push M candidates' neighbors into the queue.
////#pragma omp parallel for reduction(+ : tmp_count_computation) num_threads(real_threads)
//#pragma omp parallel for reduction(+ : tmp_count_computation)
// for (idi c_i = 0; c_i < top_m_candidates_end; ++c_i) {
// int tid = omp_get_thread_num();
// idi cand_id = top_m_candidates[c_i];
// _mm_prefetch(opt_nsg_graph_ + cand_id * vertex_bytes_ + data_bytes_, _MM_HINT_T0);
// idi *out_edges = (idi *) (opt_nsg_graph_ + cand_id * vertex_bytes_ + data_bytes_);
// idi out_degree = *out_edges++;
// for (idi n_i = 0; n_i < out_degree; ++n_i) {
// _mm_prefetch(opt_nsg_graph_ + out_edges[n_i] * vertex_bytes_, _MM_HINT_T0);
// }
// for (idi e_i = 0; e_i < out_degree; ++e_i) {
// idi nb_id = out_edges[e_i];
// { // Sequential edition
// if (is_visited[nb_id]) {
// continue;
// }
// is_visited[nb_id] = 1;
// }
//
// auto *nb_data = reinterpret_cast<dataf *>(opt_nsg_graph_ + nb_id * vertex_bytes_);
// dataf norm = *nb_data++;
//// ++count_distance_computation_;
// ++tmp_count_computation;
// distf dist = compute_distance_with_norm(nb_data, query_data, norm);
// if (dist > set_L[L - 1 + base_set_L].distance_) {
// continue;
// }
//
// Candidate cand(nb_id, dist, false);
// // Add to the local queue.
// if (0 != tid) {
// // Non-Master threads using local queues
// add_into_queue(
// set_L,
// (tid - 1) * local_queue_length,
// local_queues_ends[tid - 1],
// local_queue_length,
// cand);
// } else {
// // Thread 0 maintains the "global" queue
// idi r = add_into_queue(
// set_L,
// base_set_L,
// local_queues_ends[num_threads_ - 1],
// L,
// cand);
// if (r < nk) {
// nk = r;
// }
// }
// }
// }
// top_m_candidates_end = 0; // Clear top_m_candidates
// count_distance_computation_ += tmp_count_computation;
// tmp_count_computation = 0;
//
//// // Merge. Merge all queues in parallel.
// {
//// {//test
//// for (idi q_i = 0; q_i < num_threads_; ++q_i) {
//// if (0 == local_queues_ends[q_i]) {
//// continue;
//// }
//// for (idi e_i = 0; e_i < local_queues_ends[q_i]; ++e_i) {
//// printf("tmp_count: %u "
//// "q_i: %u "
//// "[%u]: (%u, %f)\n",
//// tmp_count,
//// q_i,
//// e_i, set_L[q_i * local_queue_length + e_i].id_, set_L[q_i * local_queue_length + e_i].distance_);
//// }
//// }
//// }
//// time_merge_ -= WallTimer::get_time_mark();
// if (num_threads_ > 1) {
// idi r = merge_all_queues_all_together_in_sequential(
// set_L,
// local_queues_ends,
// local_queue_length,
// L);
//// idi r = merge_all_queues_para_array(
//// set_L,
//// local_queues_ends,
//// local_queue_length,
//// L);
// if (r < nk) {
// nk = r;
// }
//// {//test
//// printf("tmp_count: %u "
//// "r: %u "
//// "last_k: %u\n",
//// tmp_count,
//// r,
//// last_k);
//// for (idi l_i = 0; l_i < L; ++l_i) {
//// printf("tmp_count: %u "
//// "[%u]: (%u, %f)\n",
//// tmp_count,
//// l_i, set_L[l_i + base_set_L].id_, set_L[l_i + base_set_L].distance_);
//// }
//// }
// }
//
//// time_merge_ += WallTimer::get_time_mark();
// }
// if (nk <= last_k) {
// k = nk;
// } else {
// k = last_k + 1;
// }
// {// Scale M
// if (M < value_M_max) {
// M <<= 1;
// } else {
// M = value_M_max;
// }
// }
// }
// }
//
//#pragma omp parallel for
// for (idi k_i = 0; k_i < K; ++k_i) {
// set_K[k_i] = set_L[k_i + base_set_L].id_;
//// set_K[k_i] = set_L[k_i].id_;
// }
//
// {// Reset
//// std::fill(is_visited.begin(), is_visited.end(), 0);
// is_visited.reset();
//// is_visited.clear_all();
// std::fill(local_queues_ends.begin(), local_queues_ends.end(), 0);
// }
//
//// {//test
//// if (0 == query_id) {
//// exit(1);
//// }
//// }
//}
///*
// * 6/19/2020:
// * Intra-query + Inter-query
// */
//inline void Searching::para_search_with_top_m_nested_para(
// const idi batch_start,
// const idi batch_size,
// const idi value_M_middle,
// const idi value_M_max,
// const idi K,
// const idi L,
// std::vector< std::vector<Candidate> > &set_L_list,
// const std::vector<idi> &init_ids,
// std::vector< std::vector<idi> > &set_K_list,
// const idi local_queue_length, // Maximum size of local queue
// const idi base_set_L, // base_set_L = (num_threads_intra_query_ - 1) * local_queue_length;
// std::vector< std::vector<idi> > &local_queues_ends_list, // Sizes of local queue
// std::vector< std::vector<idi> > &top_m_candidates_list,
// std::vector< boost::dynamic_bitset<> > &is_visited_list)
//{
// {// Initialize is_visited flag array
//#pragma omp parallel for num_threads(num_threads_inter_query_)
// for (idi q_i = 0; q_i < batch_size; ++q_i) {
// auto &is_visited = is_visited_list[q_i];
//#pragma omp parallel for num_threads(num_threads_intra_query_)
// for (idi c_i = 0; c_i < L; ++c_i) {
// is_visited[init_ids[c_i]] = 1;
// }
// }
// }
//
//#pragma omp parallel for
// for (idi v_i = 0; v_i < L; ++v_i) {
// idi v_id = init_ids[v_i];
// _mm_prefetch(opt_nsg_graph_ + v_id * vertex_bytes_, _MM_HINT_T0);
// }
//
// uint64_t tmp_count_total_computation = 0;
//#pragma omp parallel for num_threads(num_threads_inter_query_) reduction(+ : tmp_count_total_computation)
// for (idi q_i = 0; q_i < batch_size; ++q_i) {
// idi query_id = batch_start + q_i;
// auto &set_L = set_L_list[q_i];
// auto &local_queues_ends = local_queues_ends_list[q_i];
// auto &is_visited = is_visited_list[q_i];
//
// const dataf *query_data = queries_load_ + query_id * dimension_;
////#pragma omp parallel for
//// for (idi v_i = 0; v_i < L; ++v_i) {
//// idi v_id = init_ids[v_i];
//// _mm_prefetch(opt_nsg_graph_ + v_id * vertex_bytes_, _MM_HINT_T0);
//// }
// uint64_t tmp_count_computation = 0;
// // Get the distances of all candidates, store in the set set_L.
////#pragma omp parallel for
//#pragma omp parallel for reduction(+ : tmp_count_computation) num_threads(num_threads_intra_query_)
// for (unsigned i = 0; i < L; i++) {
// unsigned v_id = init_ids[i];
// auto *v_data = reinterpret_cast<dataf *>(opt_nsg_graph_ + v_id * vertex_bytes_);
// dataf norm = *v_data++;
//// ++count_distance_computation_;
// ++tmp_count_computation;
// distf dist = compute_distance_with_norm(v_data, query_data, norm);
// set_L[i + base_set_L] = Candidate(v_id, dist, false); // False means not checked.
//// set_L[i] = Candidate(v_id, dist, false); // False means not checked.
// }
//// count_distance_computation_ += tmp_count_computation;
// tmp_count_total_computation += tmp_count_computation;
// tmp_count_computation = 0;
//// std::sort(set_L.begin(), set_L.begin() + L);
// std::sort(
// set_L.begin() + base_set_L,
// set_L.begin() + base_set_L + L);
// local_queues_ends[num_threads_intra_query_ - 1] = L;
//
//// std::vector<idi> top_m_candidates(M);
// idi top_m_candidates_end = 0;
// idi k = 0; // Index of first unchecked candidate.
// idi tmp_count = 0; // for debug
// idi M = 1;
//
// auto &top_m_candidates = top_m_candidates_list[q_i];
// { // Single thread
// while (k < L && M < value_M_middle) {
// ++tmp_count;
//// {//test
//// printf("tmp_count: %d\n", tmp_count);
//// }
//
// // Select M candidates
// idi last_k = L;
//// Cannot use OpenMP here because this for-loop needs early break by the 2nd condition.
// for (idi c_i = k; c_i < L && top_m_candidates_end < M; ++c_i) {
// idi index_set_L = c_i + base_set_L;
// if (set_L[index_set_L].is_checked_) {
// continue;
// }
// last_k = c_i; // Record the location of the last candidate selected.
// set_L[index_set_L].is_checked_ = true;
// top_m_candidates[top_m_candidates_end++] = set_L[index_set_L].id_;
// }
//
// idi nk = L;
// // Push M candidates' neighbors into the queue.
// for (idi c_i = 0; c_i < top_m_candidates_end; ++c_i) {
// idi cand_id = top_m_candidates[c_i];
// _mm_prefetch(opt_nsg_graph_ + cand_id * vertex_bytes_ + data_bytes_, _MM_HINT_T0);
// idi *out_edges = (idi *) (opt_nsg_graph_ + cand_id * vertex_bytes_ + data_bytes_);
// idi out_degree = *out_edges++;
// for (idi n_i = 0; n_i < out_degree; ++n_i) {
// _mm_prefetch(opt_nsg_graph_ + out_edges[n_i] * vertex_bytes_, _MM_HINT_T0);
// }
// for (idi e_i = 0; e_i < out_degree; ++e_i) {
// idi nb_id = out_edges[e_i];
// { // Sequential edition
// if (is_visited[nb_id]) {
// continue;
// }
// is_visited[nb_id] = 1;
// }
//
// auto *nb_data = reinterpret_cast<dataf *>(opt_nsg_graph_ + nb_id * vertex_bytes_);
// dataf norm = *nb_data++;
//// ++count_distance_computation_;
// ++tmp_count_computation;
// distf dist = compute_distance_with_norm(nb_data, query_data, norm);
//// {//test
//// if (391655 == nb_id) {
//// printf("tmp_count: %u "
//// "nb_id: %u "
//// "distf: %f\n",
//// tmp_count,
//// nb_id,
//// dist);
//// }
//// }
// if (dist > set_L[L - 1 + base_set_L].distance_) {
// continue;
// }
//
// Candidate cand(nb_id, dist, false);
// // Thread 0 maintains the "global" queue
// idi r = add_into_queue(
// set_L,
// base_set_L,
// local_queues_ends[num_threads_intra_query_ - 1],
// L,
// cand);
// if (r < nk) {
// nk = r;
// }
// }
// }
// top_m_candidates_end = 0; // Clear top_m_candidates
//// count_distance_computation_ += tmp_count_computation;
// tmp_count_total_computation += tmp_count_computation;
// tmp_count_computation = 0;
//
// if (nk <= last_k) {
// k = nk;
// } else {
// k = last_k + 1;
// }
//
// {// Scale M
// if (M < value_M_max) {
// M <<= 1;
// } else {
// M = value_M_max;
// }
// }
// }
// }
//
// { // Multiple Threads
// while (k < L) {
// ++tmp_count;
//// {//test
//// printf("tmp_count: %d\n", tmp_count);
//// }
// // Select M candidates
// idi last_k = L;
//// Cannot use OpenMP here because this for-loop needs early break by the 2nd condition.
// for (idi c_i = k; c_i < L && top_m_candidates_end < M; ++c_i) {
// idi index_set_L = c_i + base_set_L;
// if (set_L[index_set_L].is_checked_) {
// continue;
// }
// last_k = c_i; // Record the location of the last candidate selected.
// set_L[index_set_L].is_checked_ = true;
// top_m_candidates[top_m_candidates_end++] = set_L[index_set_L].id_;
// }
//
// idi nk = L;
// // Push M candidates' neighbors into the queue.
//#pragma omp parallel for reduction(+ : tmp_count_computation) num_threads(num_threads_intra_query_)
// for (idi c_i = 0; c_i < top_m_candidates_end; ++c_i) {
// int tid = omp_get_thread_num();
// idi cand_id = top_m_candidates[c_i];
// _mm_prefetch(opt_nsg_graph_ + cand_id * vertex_bytes_ + data_bytes_, _MM_HINT_T0);
// idi *out_edges = (idi *) (opt_nsg_graph_ + cand_id * vertex_bytes_ + data_bytes_);
// idi out_degree = *out_edges++;
// for (idi n_i = 0; n_i < out_degree; ++n_i) {
// _mm_prefetch(opt_nsg_graph_ + out_edges[n_i] * vertex_bytes_, _MM_HINT_T0);
// }
// for (idi e_i = 0; e_i < out_degree; ++e_i) {
// idi nb_id = out_edges[e_i];
// { // Sequential edition
// if (is_visited[nb_id]) {
// continue;
// }
// is_visited[nb_id] = 1;
// }
//
// auto *nb_data = reinterpret_cast<dataf *>(opt_nsg_graph_ + nb_id * vertex_bytes_);
// dataf norm = *nb_data++;
//// ++count_distance_computation_;
// ++tmp_count_computation;
// distf dist = compute_distance_with_norm(nb_data, query_data, norm);
//// {//test
//// if (391655 == nb_id) {
//// printf("tmp_count: %u "
//// "nb_id: %u "
//// "distf: %f\n",
//// tmp_count,
//// nb_id,
//// dist);
//// }
//// }
// if (dist > set_L[L - 1 + base_set_L].distance_) {
// continue;
// }
//
// Candidate cand(nb_id, dist, false);
// // Add to the local queue.
// if (0 != tid) {
// // Non-Master threads using local queues
// add_into_queue(
// set_L,
// (tid - 1) * local_queue_length,
// local_queues_ends[tid - 1],
// local_queue_length,
// cand);
// } else {
// // Thread 0 maintains the "global" queue
// idi r = add_into_queue(
// set_L,
// base_set_L,
// local_queues_ends[num_threads_intra_query_ - 1],
// L,
// cand);
// if (r < nk) {
// nk = r;
// }
// }
// }
// }
// top_m_candidates_end = 0; // Clear top_m_candidates
//// count_distance_computation_ += tmp_count_computation;
// tmp_count_total_computation += tmp_count_computation;
// tmp_count_computation = 0;
//
//// // Merge. Merge all queues in parallel.
// {
//// time_merge_ -= WallTimer::get_time_mark();
// if (num_threads_intra_query_ > 1) {
// idi r = merge_all_queues_para_array(
// set_L,
// local_queues_ends,
// local_queue_length,
// L);
// if (r < nk) {
// nk = r;
// }
// }
//// time_merge_ += WallTimer::get_time_mark();
// }
// if (nk <= last_k) {
// k = nk;
// } else {
// k = last_k + 1;
// }
// {// Scale M
// if (M < value_M_max) {
// M <<= 1;
// } else {
// M = value_M_max;
// }
// }
// }
// }
// count_distance_computation_ += tmp_count_total_computation;
// tmp_count_total_computation = 0;
//
// auto &set_K = set_K_list[query_id];
//
//#pragma omp parallel for num_threads(num_threads_intra_query_)
// for (idi k_i = 0; k_i < K; ++k_i) {
// set_K[k_i] = set_L[k_i + base_set_L].id_;
//// set_K[k_i] = set_L[k_i].id_;
// }
//
// {// Reset
//// std::fill(is_visited.begin(), is_visited.end(), 0);
// is_visited.reset();
//// is_visited.clear_all();
// std::fill(local_queues_ends.begin(), local_queues_ends.end(), 0);
// }
// }
//
//// {//test
//// if (3 == query_id) {
//// exit(1);
//// }
//// }
//// {
//// for (idi k_i = 0; k_i < K; ++k_i) {
//// printf("%u: (%u %f)\n",
//// k_i, set_L_list[0][k_i].id_, set_L_list[0][k_i].distance_);
//// }
//// if (0 == batch_start) {
//// exit(1);
//// }
//// }
//}
/*
* 6/22/2020-21:30
* Do searching on the local_set_L
* local_set_L is already sorted
* is_visited is already set up.
*/
inline void Searching::subsearch_with_top_m(
const idi value_M_max,
const idi query_id,
const idi local_L,
std::vector<Candidate> &set_L,
const idi set_L_start,
idi &set_L_size,
std::vector<idi> &local_top_m_candidates,
boost::dynamic_bitset<> &is_visited,
uint64_t &local_count_distance_computation)
{
const dataf *query_data = queries_load_ + query_id * dimension_;
// idi local_top_m_candidates_end = 0;
idi k = 0; // Index of first unchecked candidate.
idi iter = 0;
idi M = 1; // value of M
while (k < local_L) {
++iter;
subsearch_top_m_for_one_iteration(
iter,
k,
M,
query_id,
query_data,
local_L,
set_L,
set_L_start,
set_L_size,
local_top_m_candidates,
is_visited,
local_count_distance_computation);
{// Scale M
if (M < value_M_max) {
M <<= 1;
} else {
M = value_M_max;
}
}
}
// {//test
// printf("set_L_start: %u "
// "local_count_distance_computation: %lu\n",
// set_L_start,
// local_count_distance_computation);
// }
}
//// Backup
//inline void Searching::subsearch_with_top_m(
// const idi value_M_max,
// const idi query_id,
// const idi local_L,
// std::vector<Candidate> &set_L,
// const idi base_set_L,
// idi &set_L_end,
// std::vector<idi> &local_top_m_candidates,
// boost::dynamic_bitset<> &is_visited,
// uint64_t &local_count_distance_computation)
//{
// const dataf *query_data = queries_load_ + query_id * dimension_;
// idi local_top_m_candidates_end = 0;
// idi k = 0; // Index of first unchecked candidate.
// idi iter = 0;
// idi M = 1; // value of M
//
// while (k < local_L) {
// ++iter;
// // Select M candidates
// idi last_k = local_L;
//// Cannot use OpenMP here because this for-loop needs early break by the 2nd condition.
// for (idi c_i = k; c_i < set_L_end && local_top_m_candidates_end < M; ++c_i) {
// idi index_set_L = c_i + base_set_L;
// if (set_L[index_set_L].is_checked_) {
// continue;
// }
// last_k = c_i; // Record the location of the last candidate selected.
// set_L[index_set_L].is_checked_ = true;
// local_top_m_candidates[local_top_m_candidates_end++] = set_L[index_set_L].id_;
// }
//
// idi nk = local_L;
// // Push M candidates' neighbors into the queue.
// for (idi c_i = 0; c_i < local_top_m_candidates_end; ++c_i) {
// idi cand_id = local_top_m_candidates[c_i];
// _mm_prefetch(opt_nsg_graph_ + cand_id * vertex_bytes_ + data_bytes_, _MM_HINT_T0);
// idi *out_edges = (idi *) (opt_nsg_graph_ + cand_id * vertex_bytes_ + data_bytes_);
// idi out_degree = *out_edges++;
// for (idi n_i = 0; n_i < out_degree; ++n_i) {
// _mm_prefetch(opt_nsg_graph_ + out_edges[n_i] * vertex_bytes_, _MM_HINT_T0);
// }
// for (idi e_i = 0; e_i < out_degree; ++e_i) {
// idi nb_id = out_edges[e_i];
// { // Sequential edition
// if (is_visited[nb_id]) {
// continue;
// }
// is_visited[nb_id] = 1;
// }
//
// auto *nb_data = reinterpret_cast<dataf *>(opt_nsg_graph_ + nb_id * vertex_bytes_);
// dataf norm = *nb_data++;
// ++local_count_distance_computation;
// distf dist = compute_distance_with_norm(nb_data, query_data, norm);
// if (dist > set_L[set_L_end - 1 + base_set_L].distance_) {
// continue;
// }
//
// Candidate cand(nb_id, dist, false);
// // Thread 0 maintains the "global" queue
// idi r = add_into_queue(
// set_L,
// base_set_L,
// set_L_end,
// local_L,
// cand);
// if (r < nk) {
// nk = r;
// }
// }
// }
// local_top_m_candidates_end = 0; // Clear top_m_candidates
//
// if (nk <= last_k) {
// k = nk;
// } else {
// k = last_k + 1;
// }
//
// {// Scale M
// if (M < value_M_max) {
// M <<= 1;
// } else {
// M = value_M_max;
// }
// }
// }
//}
/*
* 7/6/2020-23:17
* Subsearch only 1 iteration using top-m
*/
inline void Searching::subsearch_top_m_for_one_iteration(
const idi iter,
idi &k_uc,
const idi value_M,
const idi query_id,
const dataf *query_data,
const idi L,
std::vector<Candidate> &set_L,
const idi set_L_start,
idi &set_L_size,
std::vector<idi> &top_m_candidates,
boost::dynamic_bitset<> &is_visited,
uint64_t &count_distance_computation)
{
// Select M candidates
idi top_m_candidates_end = 0;
idi last_k = L;
// Cannot use OpenMP here because this for-loop needs early break by the 2nd condition.
for (idi c_i = k_uc; c_i < set_L_size && top_m_candidates_end < value_M; ++c_i) {
idi index_set_L = c_i + set_L_start;
if (set_L[index_set_L].is_checked_) {
continue;
}
last_k = c_i; // Record the location of the last candidate selected.
set_L[index_set_L].is_checked_ = true;
top_m_candidates[top_m_candidates_end++] = set_L[index_set_L].id_;
// {//test
// M_ids_.push_back(set_L[index_set_L].id_);
// }
}
idi nk = L;
// Push M candidates' neighbors into the queue.
for (idi c_i = 0; c_i < top_m_candidates_end; ++c_i) {
idi cand_id = top_m_candidates[c_i];
_mm_prefetch(opt_nsg_graph_ + cand_id * vertex_bytes_ + data_bytes_, _MM_HINT_T0);
idi *out_edges = (idi *) (opt_nsg_graph_ + cand_id * vertex_bytes_ + data_bytes_);
idi out_degree = *out_edges++;
for (idi n_i = 0; n_i < out_degree; ++n_i) {
_mm_prefetch(opt_nsg_graph_ + out_edges[n_i] * vertex_bytes_, _MM_HINT_T0);
}
for (idi e_i = 0; e_i < out_degree; ++e_i) {
idi nb_id = out_edges[e_i];
{ // Sequential edition
if (is_visited[nb_id]) {
continue;
}
is_visited[nb_id] = 1;
}
auto *nb_data = reinterpret_cast<dataf *>(opt_nsg_graph_ + nb_id * vertex_bytes_);
dataf norm = *nb_data++;
++count_distance_computation;
distf dist = compute_distance_with_norm(nb_data, query_data, norm);
if (dist > set_L[set_L_size - 1 + set_L_start].distance_) {
continue;
}
Candidate cand(nb_id, dist, false);
idi r = add_into_queue(
set_L,
set_L_start,
set_L_size,
L,
cand);
if (r < nk) {
nk = r;
}
}
}
// top_m_candidates_end = 0; // Clear top_m_candidates
if (nk <= last_k) {
k_uc = nk;
} else {
k_uc = last_k + 1;
}
// {//test
// for (idi l_i = 0; l_i < set_L_size; ++l_i) {
// L_ids_.push_back(set_L[set_L_start + l_i].id_);
// }
// std::sort(L_ids_.begin(), L_ids_.end());
// std::sort(M_ids_.begin(), M_ids_.end());
// for (idi m_i = 0; m_i < M_ids_.size(); ++m_i) {
// printf("query_id: %u "
// "iter: %u "
// "M[%u]: "
// "%u\n",
// query_id,
// iter,
// m_i,
// M_ids_[m_i]);
// }
// M_ids_.clear();
// for (idi l_i = 0; l_i < L_ids_.size(); ++l_i) {
// printf("query_id: %u "
// "iter: %u "
// "L[%u]: "
// "%u\n",
// query_id,
// iter,
// l_i,
// L_ids_[l_i]);
// }
// L_ids_.clear();
// }
}
///*
// * One more parameter for distance bound
// */
//inline void Searching::subsearch_top_m_for_one_iteration_lth(
// const distf bound_lth,
// const idi iter,
// idi &k_uc,
// const idi value_M,
// const idi query_id,
// const dataf *query_data,
// const idi L,
// std::vector<Candidate> &set_L,
// const idi set_L_start,
// idi &set_L_size,
// std::vector<idi> &top_m_candidates,
// boost::dynamic_bitset<> &is_visited,
// uint64_t &count_distance_computation)
//{
// // Select M candidates
// idi top_m_candidates_end = 0;
// idi last_k = L;
//// Cannot use OpenMP here because this for-loop needs early break by the 2nd condition.
// for (idi c_i = k_uc; c_i < set_L_size && top_m_candidates_end < value_M; ++c_i) {
// idi index_set_L = c_i + set_L_start;
// if (set_L[index_set_L].is_checked_) {
// continue;
// }
// last_k = c_i; // Record the location of the last candidate selected.
// set_L[index_set_L].is_checked_ = true;
// top_m_candidates[top_m_candidates_end++] = set_L[index_set_L].id_;
// }
//
// idi nk = L;
// // Push M candidates' neighbors into the queue.
// for (idi c_i = 0; c_i < top_m_candidates_end; ++c_i) {
// idi cand_id = top_m_candidates[c_i];
// _mm_prefetch(opt_nsg_graph_ + cand_id * vertex_bytes_ + data_bytes_, _MM_HINT_T0);
// idi *out_edges = (idi *) (opt_nsg_graph_ + cand_id * vertex_bytes_ + data_bytes_);
// idi out_degree = *out_edges++;
// for (idi n_i = 0; n_i < out_degree; ++n_i) {
// _mm_prefetch(opt_nsg_graph_ + out_edges[n_i] * vertex_bytes_, _MM_HINT_T0);
// }
// for (idi e_i = 0; e_i < out_degree; ++e_i) {
// idi nb_id = out_edges[e_i];
// { // Sequential edition
// if (is_visited[nb_id]) {
// continue;
// }
// is_visited[nb_id] = 1;
// }
//
// auto *nb_data = reinterpret_cast<dataf *>(opt_nsg_graph_ + nb_id * vertex_bytes_);
// dataf norm = *nb_data++;
// ++count_distance_computation;
// distf dist = compute_distance_with_norm(nb_data, query_data, norm);
// if (dist > bound_lth) {
// continue;
// }
//
// Candidate cand(nb_id, dist, false);
// idi r = add_into_queue(
// set_L,
// set_L_start,
// set_L_size,
// L,
// cand);
// if (r < nk) {
// nk = r;
// }
// }
// }
//
// if (nk <= last_k) {
// k_uc = nk;
// } else {
// k_uc = last_k + 1;
// }
//}
/*
* 7/24/2020-10:53
* Subsearch for one iteration, with the global L-th value as the bound,
* and the top_m_position indicates the bound for local top-M vertices.
*/
inline void Searching::subsearch_top_m_for_one_iteration_lth_mth(
const distf bound_lth,
// const idi top_m_position,
const idi iter,
idi &k_uc,
const idi local_m_count,
const idi query_id,
const dataf *query_data,
const idi L,
std::vector<Candidate> &set_L,
const idi set_L_start,
idi &set_L_size,
std::vector<idi> &top_m_candidates,
boost::dynamic_bitset<> &is_visited,
uint64_t &count_distance_computation,
double &time_pick_top_m,
uint64_t &count_add_to_queue,
double &time_distance_computation,
double &time_add_to_queue)
{
// {//test
// printf("query_id: %u "
// "iter: %u "
// "tid: %u \n",
// query_id,
// iter,
// omp_get_thread_num());
// }
// Select M candidates
idi top_m_candidates_end = 0;
idi last_k = L;
// Cannot use OpenMP here because this for-loop needs early break by the 2nd condition.
// for (idi c_i = k_uc; c_i < top_m_position; ++c_i) {
time_pick_top_m -= WallTimer::get_time_mark();
for (idi c_i = k_uc; c_i < set_L_size && top_m_candidates_end < local_m_count; ++c_i) {
idi index_set_L = c_i + set_L_start;
if (set_L[index_set_L].is_checked_) {
continue;
}
last_k = c_i; // Record the location of the last candidate selected.
set_L[index_set_L].is_checked_ = true;
top_m_candidates[top_m_candidates_end++] = set_L[index_set_L].id_;
// {//test
// M_ids_.push_back(set_L[index_set_L].id_);
// }
}
time_pick_top_m += WallTimer::get_time_mark();
idi nk = L;
// Push M candidates' neighbors into the queue.
for (idi c_i = 0; c_i < top_m_candidates_end; ++c_i) {
time_pick_top_m -= WallTimer::get_time_mark();
idi cand_id = top_m_candidates[c_i];
// _mm_prefetch(opt_nsg_graph_ + cand_id * vertex_bytes_ + data_bytes_, _MM_HINT_T0);
idi *out_edges = (idi *) (opt_nsg_graph_ + cand_id * vertex_bytes_ + data_bytes_);
idi out_degree = *out_edges++;
// for (idi n_i = 0; n_i < out_degree; ++n_i) {
// _mm_prefetch(opt_nsg_graph_ + out_edges[n_i] * vertex_bytes_, _MM_HINT_T0);
// }
time_pick_top_m += WallTimer::get_time_mark();
for (idi e_i = 0; e_i < out_degree; ++e_i) {
time_distance_computation -= WallTimer::get_time_mark();
idi nb_id = out_edges[e_i];
{ // Sequential edition
if (is_visited[nb_id]) {
time_distance_computation += WallTimer::get_time_mark();
continue;
}
is_visited[nb_id] = 1;
}
auto *nb_data = reinterpret_cast<dataf *>(opt_nsg_graph_ + nb_id * vertex_bytes_);
dataf norm = *nb_data++;
++count_distance_computation;
distf dist = compute_distance_with_norm(nb_data, query_data, norm);
time_distance_computation += WallTimer::get_time_mark();
if (dist > set_L[set_L_start + set_L_size - 1].distance_) {
// if (dist > bound_lth) {
continue;
}
++count_add_to_queue;
Candidate cand(nb_id, dist, false);
// time_pick_top_m -= WallTimer::get_time_mark();
time_add_to_queue -= WallTimer::get_time_mark();
idi r = add_into_queue(
set_L,
set_L_start,
set_L_size,
L,
cand);
if (r < nk) {
nk = r;
}
time_add_to_queue += WallTimer::get_time_mark();
// time_pick_top_m += WallTimer::get_time_mark();
}
}
if (nk <= last_k) {
k_uc = nk;
} else {
k_uc = last_k + 1;
}
}
///*
// * 7/26/2020-15:41
// * L-th and M-th Selection.
// * Seq-Par Phases: when M is 1 and 2, do sequential searching;
// * When M is equal and larger than 4, do parallel searching.
// * It's for load-balance issue.
// */
//inline void Searching::para_search_with_top_m_subsearch_v3(
// const idi local_M_max,
// const idi local_M_middle,
// const idi query_id,
// const idi K,
// const idi global_L,
// const idi local_L,
//// const idi total_L,
//// const idi init_queue_size,
// std::vector<Candidate> &set_L,
// const std::vector<idi> &init_ids,
// std::vector<idi> &set_K,
// const std::vector<idi> &local_queues_starts,
// std::vector<idi> &local_queues_sizes,
// std::vector<idi> &local_m_counts,
// std::vector< std::vector<idi> > &top_m_candidates_list,
// boost::dynamic_bitset<> &is_visited)
//{
// time_initialization_ -= WallTimer::get_time_mark();
// uint64_t tmp_count_computation = 0;
// {// Initialization
// // is_visited flag array
////#pragma omp parallel for
//// Cannot use OMP for bit array is_visited!
// for (idi c_i = 0; c_i < global_L; ++c_i) {
// is_visited[init_ids[c_i]] = 1;
// }
//
// const dataf *query_data = queries_load_ + query_id * dimension_;
//#pragma omp parallel for
// for (idi v_i = 0; v_i < global_L; ++v_i) {
// idi v_id = init_ids[v_i];
// _mm_prefetch(opt_nsg_graph_ + v_id * vertex_bytes_, _MM_HINT_T0);
// }
//
// // Get the distances of all candidates, store in the set set_L.
//#pragma omp parallel for reduction(+ : tmp_count_computation)
// for (idi id_i = 0; id_i < global_L; ++id_i) {
// idi v_id = init_ids[id_i];
// auto *v_data = reinterpret_cast<dataf *>(opt_nsg_graph_ + v_id * vertex_bytes_);
// dataf norm = *v_data++;
// ++tmp_count_computation;
// distf dist = compute_distance_with_norm(v_data, query_data, norm);
// set_L[id_i] = Candidate(v_id, dist, false); // False means not checked.
// }
// local_queues_sizes[0] = global_L;
// count_distance_computation_ += tmp_count_computation;
// tmp_count_computation = 0;
// std::sort(set_L.begin(), set_L.begin() + global_L);
// }
// time_initialization_ += WallTimer::get_time_mark();
//
// // Searching
// if (num_threads_ == 1) { // Single threads
//// std::sort(
//// set_L.begin(),
//// set_L.end());
// subsearch_with_top_m(
// local_M_max,
// query_id,
// local_L,
// set_L,
// 0,
// local_queues_sizes[0],
// top_m_candidates_list[0],
// is_visited,
// tmp_count_computation);
// count_distance_computation_ += tmp_count_computation;
// tmp_count_computation = 0;
// } else { // Multiple threads
// const dataf *query_data = queries_load_ + query_id * dimension_;
// const idi num_queues = num_threads_;
// idi local_M = 1;
// idi iter = 0;
// std::vector<idi> ks(num_queues, 0);
//
// time_sequential_phase_ -= WallTimer::get_time_mark();
// {// Sequential Search for M = 1, 2.
// idi &k = ks[0];
// while (k < global_L && local_M < local_M_middle) {
// ++iter;
// subsearch_top_m_for_one_iteration(
// iter,
// k,
// local_M,
// query_id,
// query_data,
// global_L,
// set_L,
// 0,
// local_queues_sizes[0],
// top_m_candidates_list[0],
// is_visited,
// tmp_count_computation);
// count_distance_computation_ += tmp_count_computation;
// tmp_count_computation = 0;
//
// {// Double M
// if (local_M < local_M_max) {
// local_M <<= 1;
// }
// }
// }
// }
// time_sequential_phase_ += WallTimer::get_time_mark();
//
// time_parallel_phase_ -= WallTimer::get_time_mark();
// distf bound_lth = set_L[global_L - 1].distance_;
// {// Parallel Search for M >= 4, or local_M_middle
// time_assign_s_ -=WallTimer::get_time_mark();
// {// Assign elements from Queue[0] to others
// idi dst_i = 1;
// for (idi e_i = 1; e_i < global_L; ++e_i) {
// idi dest_sub = e_i % num_queues;
// if (0 == dest_sub) {
// set_L[dst_i++] = set_L[e_i];
// } else {
// set_L[local_queues_starts[dest_sub] + local_queues_sizes[dest_sub]++] = set_L[e_i];
// }
// }
// local_queues_sizes[0] = dst_i;
// }
// std::fill(ks.begin(), ks.end(), 0);
//
//
// selecting_unchecked_top_M_seq(
// query_id,
// iter,
// set_L,
// ks,
// local_M,
// num_queues,
// local_queues_starts,
// local_queues_sizes,
// local_m_counts);
// time_assign_s_ +=WallTimer::get_time_mark();
//
// double tmp_time_pick_top_m = 0;
// uint64_t tmp_count_add_to_queue = 0;
// uint8_t not_finished = 1;
// double tmp_time_distance_computation = 0;
// double tmp_time_add_to_queue = 0;
// while (true) {
// time_expand_ -= WallTimer::get_time_mark();
// not_finished = 0;
// ++iter;
//#pragma omp parallel for reduction(+ : tmp_count_computation) \
// reduction(+ : tmp_time_pick_top_m) \
// reduction(+ : tmp_count_add_to_queue) \
// reduction(+ : tmp_time_distance_computation) \
// reduction(+ : tmp_time_add_to_queue)
// for (idi q_i = 0; q_i < num_queues; ++q_i) {
// tmp_time_pick_top_m -= WallTimer::get_time_mark();
// idi L_value = q_i == 0 ? global_L : local_L;
// idi &k = ks[q_i];
// idi &local_queue_size = local_queues_sizes[q_i];
// auto &local_top_m_candidates = top_m_candidates_list[q_i];
// idi local_m_count = local_m_counts[q_i];
//// if (local_M < num_queues && !local_m_count) {
//// local_m_count = 1;
//// }
// tmp_time_pick_top_m += WallTimer::get_time_mark();
// if (!local_m_count) {
// continue;
// }
// not_finished = 1;
// const idi local_queue_start = local_queues_starts[q_i];
//
// subsearch_top_m_for_one_iteration_lth_mth(
// bound_lth,
// iter,
// k,
// local_m_count,
// query_id,
// query_data,
// L_value,
// set_L,
// local_queue_start,
// local_queue_size,
// local_top_m_candidates,
// is_visited,
// tmp_count_computation,
// tmp_time_pick_top_m,
// tmp_count_add_to_queue,
// tmp_time_distance_computation,
// tmp_time_add_to_queue);
// }
// time_add_to_queue_ += tmp_time_add_to_queue;
// tmp_time_add_to_queue = 0;
// time_distance_computation_ += tmp_time_distance_computation;
// tmp_time_distance_computation = 0;
// count_add_to_queue_ += tmp_count_add_to_queue;
// tmp_count_add_to_queue = 0;
// time_pick_top_m_ += tmp_time_pick_top_m;
// tmp_time_pick_top_m = 0;
// count_distance_computation_ += tmp_count_computation;
// tmp_count_computation = 0;
// time_expand_ += WallTimer::get_time_mark();
// if (!not_finished) {
// break;
// }
// {// Scale M
// if (local_M < local_M_max) {
// local_M <<= 1;
// }
//// else {
//// local_M = value_M_max;
//// }
// }
// time_select_ -= WallTimer::get_time_mark();
//#pragma omp parallel sections
// {
//#pragma omp section
// {// Setecting and update local_queues_lengths
//// time_select_L_ -= WallTimer::get_time_mark();
// bound_lth = selecting_top_L_seq(
// set_L,
// global_L,
//// local_L,
// num_queues,
// local_queues_starts,
// local_queues_sizes);
//// time_select_L_ += WallTimer::get_time_mark();
// }
//#pragma omp section
// {
//// time_select_M_ -= WallTimer::get_time_mark();
// selecting_unchecked_top_M_seq(
// query_id,
// iter,
// set_L,
// ks,
// local_M,
// num_queues,
// local_queues_starts,
// local_queues_sizes,
// local_m_counts);
//// time_select_M_ += WallTimer::get_time_mark();
// }
// }
// time_select_ += WallTimer::get_time_mark();
//// {//test
//// printf("query_id: %u "
//// "iter: %u",
//// query_id,
//// iter);
//// printf(" local_queues_sizes:");
//// for (idi i = 0; i < num_queues; ++i) {
//// printf(" %u", local_queues_sizes[i]);
//// }
//// printf(" local_m_counts:");
//// for (idi i = 0; i < num_queues; ++i) {
//// printf(" %u", local_m_counts[i]);
//// }
//// printf(" ks:");
//// for (idi i = 0; i < num_queues; ++i) {
//// printf(" %u", ks[i]);
//// }
//// printf("\n");
//// }
// }
// }
// time_parallel_phase_ += WallTimer::get_time_mark();
// }
//
//// time_merge_ -= WallTimer::get_time_mark();
// time_ending_ -= WallTimer::get_time_mark();
// {// Return the results to set_K
// std::vector<idi> pointer(num_threads_, 0);
// // get the first
// distf min_dist = FLT_MAX;
// idi min_q_i;
// idi min_id;
// idi min_sub;
// idi last_id;
// for (int q_i = 0; q_i < num_threads_; ++q_i) {
// if (pointer[q_i] >= local_queues_sizes[q_i]) {
// continue;
// }
// idi sub = pointer[q_i] + local_queues_starts[q_i];
// distf tmp_dist = set_L[sub].distance_;
// idi tmp_id = set_L[sub].id_;
// if (tmp_dist < min_dist) {
// min_dist = tmp_dist;
// min_id = tmp_id;
// min_q_i = q_i;
// min_sub = sub;
// } else if (tmp_dist == min_dist && tmp_id < min_id) {
// min_id = tmp_id;
// min_q_i = q_i;
// min_sub = sub;
// }
// }
// set_K[0] = set_L[min_sub].id_;
//// {//test
//// printf("query_id: %u "
//// "[%u]: "
//// "(%u, %f)\n",
//// query_id,
//// 0,
//// set_L[min_sub].id_, set_L[min_sub].distance_);
//// }
// ++pointer[min_q_i];
// last_id = set_K[0];
//
// bool is_finished = false;
// idi k_i = 1;
// while (k_i < K && !is_finished) {
// is_finished = true;
// min_dist = FLT_MAX;
// for (int q_i = 0; q_i < num_threads_; ++q_i) {
// const idi local_queue_size = local_queues_sizes[q_i];
// idi sub = pointer[q_i] + local_queues_starts[q_i];
//
// while (pointer[q_i] < local_queue_size
// && set_L[sub].id_ == last_id) {
// ++pointer[q_i];
// ++sub;
// }
// if (pointer[q_i] >= local_queue_size) {
// continue;
// }
// is_finished = false;
// distf tmp_dist = set_L[sub].distance_;
// idi tmp_id = set_L[sub].id_;
// if (tmp_dist < min_dist) {
// min_dist = tmp_dist;
// min_id = tmp_id;
// min_q_i = q_i;
// min_sub = sub;
// } else if (tmp_dist == min_dist && tmp_id < min_id) {
// min_id = tmp_id;
// min_q_i = q_i;
// min_sub = sub;
// }
// }
// set_K[k_i] = set_L[min_sub].id_;
//// {//test
//// printf("query_id: %u "
//// "[%u]: "
//// "(%u, %f)\n",
//// query_id,
//// k_i,
//// set_L[min_sub].id_, set_L[min_sub].distance_);
//// }
// ++pointer[min_q_i];
// ++k_i;
// }
// }
//// time_merge_ += WallTimer::get_time_mark();
//
// {// Reset
//// std::fill(is_visited.begin(), is_visited.end(), 0);
// is_visited.reset();
// std::fill(local_queues_sizes.begin() + 1, local_queues_sizes.end(), 0);
// }
//
// time_ending_ += WallTimer::get_time_mark();
//// {//test
//// if (3 == query_id) {
//// exit(1);
//// }
//// }
//}
//
///*
// * 7/27/2020-15:33
// * Same with v3, but gather top-m vertices together
// */
//inline void Searching::para_search_with_top_m_subsearch_v4(
// const idi local_M_max,
// const idi local_M_middle,
// const idi query_id,
// const idi K,
// const idi global_L,
// const idi local_L,
//// const idi total_L,
//// const idi init_queue_size,
// std::vector<Candidate> &set_L,
// const std::vector<idi> &init_ids,
// std::vector<idi> &set_K,
// const std::vector<idi> &local_queues_starts,
// std::vector<idi> &local_queues_sizes,
// std::vector<idi> &local_m_counts,
// std::vector<idi> &top_m_candidates,
//// std::vector< std::vector<idi> > &top_m_candidates_list,
// boost::dynamic_bitset<> &is_visited)
//{
// time_initialization_ -= WallTimer::get_time_mark();
// uint64_t tmp_count_computation = 0;
// {// Initialization
// // is_visited flag array
////#pragma omp parallel for
//// Cannot use OMP for bit array is_visited!
// for (idi c_i = 0; c_i < global_L; ++c_i) {
// is_visited[init_ids[c_i]] = 1;
// }
//
// const dataf *query_data = queries_load_ + query_id * dimension_;
//#pragma omp parallel for
// for (idi v_i = 0; v_i < global_L; ++v_i) {
// idi v_id = init_ids[v_i];
// _mm_prefetch(opt_nsg_graph_ + v_id * vertex_bytes_, _MM_HINT_T0);
// }
//
// // Get the distances of all candidates, store in the set set_L.
//#pragma omp parallel for reduction(+ : tmp_count_computation)
// for (idi id_i = 0; id_i < global_L; ++id_i) {
// idi v_id = init_ids[id_i];
// auto *v_data = reinterpret_cast<dataf *>(opt_nsg_graph_ + v_id * vertex_bytes_);
// dataf norm = *v_data++;
// ++tmp_count_computation;
// distf dist = compute_distance_with_norm(v_data, query_data, norm);
// set_L[id_i] = Candidate(v_id, dist, false); // False means not checked.
// }
// local_queues_sizes[0] = global_L;
// count_distance_computation_ += tmp_count_computation;
// tmp_count_computation = 0;
// std::sort(set_L.begin(), set_L.begin() + global_L);
// }
// time_initialization_ += WallTimer::get_time_mark();
//
// // Searching
// if (num_threads_ == 1) { // Single threads
//// std::sort(
//// set_L.begin(),
//// set_L.end());
// subsearch_with_top_m(
// local_M_max,
// query_id,
// local_L,
// set_L,
// 0,
// local_queues_sizes[0],
// top_m_candidates,
// is_visited,
// tmp_count_computation);
// count_distance_computation_ += tmp_count_computation;
// tmp_count_computation = 0;
// } else { // Multiple threads
// const dataf *query_data = queries_load_ + query_id * dimension_;
// const idi num_queues = num_threads_;
// idi local_M = 1;
// idi iter = 0;
//// std::vector<idi> ks(num_queues, 0);
//
// time_sequential_phase_ -= WallTimer::get_time_mark();
// {// Sequential Search for M = 1, 2.
// idi k = 0;
//// idi &k = ks[0];
// while (k < global_L && local_M < local_M_middle) {
// ++iter;
// subsearch_top_m_for_one_iteration(
// iter,
// k,
// local_M,
// query_id,
// query_data,
// global_L,
// set_L,
// 0,
// local_queues_sizes[0],
// top_m_candidates,
// is_visited,
// tmp_count_computation);
// count_distance_computation_ += tmp_count_computation;
// tmp_count_computation = 0;
//
// {// Double M
// if (local_M < local_M_max) {
// local_M <<= 1;
// }
// }
// }
// }
// time_sequential_phase_ += WallTimer::get_time_mark();
//
// time_parallel_phase_ -= WallTimer::get_time_mark();
// distf bound_lth = set_L[global_L - 1].distance_;
// {// Parallel Search for M >= 4, or local_M_middle
// time_assign_s_ -=WallTimer::get_time_mark();
// {// Assign elements from Queue[0] to others
// idi dst_i = 1;
// for (idi e_i = 1; e_i < global_L; ++e_i) {
// idi dest_sub = e_i % num_queues;
// if (0 == dest_sub) {
// set_L[dst_i++] = set_L[e_i];
// } else {
// set_L[local_queues_starts[dest_sub] + local_queues_sizes[dest_sub]++] = set_L[e_i];
// }
// }
// local_queues_sizes[0] = dst_i;
// }
//// std::fill(ks.begin(), ks.end(), 0);
//
// idi top_m_candidates_size = 0;
//// selecting_unchecked_top_M_seq(
//// query_id,
//// iter,
//// set_L,
//// ks,
//// local_M,
//// num_queues,
//// local_queues_starts,
//// local_queues_sizes,
//// local_m_counts);
// time_assign_s_ +=WallTimer::get_time_mark();
//
// std::vector<idi> ks(num_queues, 0);
// std::vector<idi> nks(num_queues);
// std::vector<idi> bound_ks(num_queues);
// double tmp_time_pick_top_m = 0;
// uint64_t tmp_count_add_to_queue = 0;
// uint8_t not_finished = 1;
// double tmp_time_distance_computation = 0;
// double tmp_time_add_to_queue = 0;
// while (true) {
// time_expand_ -= WallTimer::get_time_mark();
// not_finished = 0;
// ++iter;
//
// // Gather top-M vertices
// time_pick_top_m_ -= WallTimer::get_time_mark();
// gather_unchecked_top_M_seq(
// query_id,
// iter,
// set_L,
// ks,
// local_M,
// num_queues,
// local_queues_starts,
// local_queues_sizes,
// top_m_candidates,
// top_m_candidates_size,
// bound_ks);
// time_pick_top_m_ += WallTimer::get_time_mark();
// if (!top_m_candidates_size) {
// time_expand_ += WallTimer::get_time_mark();
// break;
// }
// std::fill(nks.begin(), nks.end(), global_L);
//
// // Expand top-M vertices
//#pragma omp parallel for schedule(static, 1) \
// reduction(+ : tmp_count_computation) \
// reduction(+ : tmp_count_add_to_queue) \
// reduction(+ : tmp_time_distance_computation) \
// reduction(+ : tmp_time_pick_top_m) \
// reduction(+ : tmp_time_add_to_queue)
// for (idi c_i = 0; c_i < top_m_candidates_size; ++c_i) {
// tmp_time_pick_top_m -= WallTimer::get_time_mark();
// idi tid = omp_get_thread_num();
// const idi set_L_start = local_queues_starts[tid];
// idi &set_L_size = local_queues_sizes[tid];
// idi &nk = nks[tid];
// idi L_value = tid == 0 ? global_L : local_L;
// idi cand_id = top_m_candidates[c_i];
//// _mm_prefetch(opt_nsg_graph_ + cand_id * vertex_bytes_ + data_bytes_, _MM_HINT_T0);
// idi *out_edges = (idi *) (opt_nsg_graph_ + cand_id * vertex_bytes_ + data_bytes_);
// idi out_degree = *out_edges++;
//// for (idi n_i = 0; n_i < out_degree; ++n_i) {
//// _mm_prefetch(opt_nsg_graph_ + out_edges[n_i] * vertex_bytes_, _MM_HINT_T0);
//// }
// tmp_time_pick_top_m += WallTimer::get_time_mark();
// // Expand cand_id's neighbors
// for (idi e_i = 0; e_i < out_degree; ++e_i) {
// tmp_time_distance_computation -= WallTimer::get_time_mark();
// idi nb_id = out_edges[e_i];
// { // Sequential edition
// if (is_visited[nb_id]) {
// tmp_time_distance_computation += WallTimer::get_time_mark();
// continue;
// }
// is_visited[nb_id] = 1;
// }
//
// auto *nb_data = reinterpret_cast<dataf *>(opt_nsg_graph_ + nb_id * vertex_bytes_);
// dataf norm = *nb_data++;
// ++tmp_count_computation;
// distf dist = compute_distance_with_norm(nb_data, query_data, norm);
// tmp_time_distance_computation += WallTimer::get_time_mark();
// if (dist > set_L[set_L_start + set_L_size - 1].distance_) {
//// if (dist > bound_lth) {
// continue;
// }
// ++tmp_count_add_to_queue;
// Candidate cand(nb_id, dist, false);
// tmp_time_add_to_queue -= WallTimer::get_time_mark();
// idi r = add_into_queue(
// set_L,
// set_L_start,
// set_L_size,
// L_value,
// cand);
// if (r < nk) {
// nk = r;
// }
// tmp_time_add_to_queue += WallTimer::get_time_mark();
// }
// }
// top_m_candidates_size = 0;
// time_add_to_queue_ += tmp_time_add_to_queue;
// tmp_time_add_to_queue = 0;
// time_distance_computation_ += tmp_time_distance_computation;
// tmp_time_distance_computation = 0;
// count_add_to_queue_ += tmp_count_add_to_queue;
// tmp_count_add_to_queue = 0;
// time_pick_top_m_ += tmp_time_pick_top_m;
// tmp_time_pick_top_m = 0;
// count_distance_computation_ += tmp_count_computation;
// tmp_count_computation = 0;
// for (idi q_i = 0; q_i < num_queues; ++q_i) {
// if (nks[q_i] < bound_ks[q_i]) {
// ks[q_i] = nks[q_i];
// } else {
// ks[q_i] = bound_ks[q_i];
// }
// }
// time_expand_ += WallTimer::get_time_mark();
//
// time_select_ -= WallTimer::get_time_mark();
// {// Select L-th
// bound_lth = selecting_top_L_seq(
// set_L,
// global_L,
// num_queues,
// local_queues_starts,
// local_queues_sizes);
// }
// time_select_ += WallTimer::get_time_mark();
// {// Scale M
// if (local_M < local_M_max) {
// local_M <<= 1;
// }
// }
//// {//test
//// printf("query_id: %u "
//// "iter: %u",
//// query_id,
//// iter);
//// printf(" local_queues_sizes:");
//// for (idi i = 0; i < num_queues; ++i) {
//// printf(" %u", local_queues_sizes[i]);
//// }
//// printf(" local_m_counts:");
//// for (idi i = 0; i < num_queues; ++i) {
//// printf(" %u", local_m_counts[i]);
//// }
//// printf(" ks:");
//// for (idi i = 0; i < num_queues; ++i) {
//// printf(" %u", ks[i]);
//// }
//// printf("\n");
//// }
// }
// }
// time_parallel_phase_ += WallTimer::get_time_mark();
// }
//
//// time_merge_ -= WallTimer::get_time_mark();
// time_ending_ -= WallTimer::get_time_mark();
// {// Return the results to set_K
// std::vector<idi> pointer(num_threads_, 0);
// // get the first
// distf min_dist = FLT_MAX;
// idi min_q_i;
// idi min_id;
// idi min_sub;
// idi last_id;
// for (int q_i = 0; q_i < num_threads_; ++q_i) {
// if (pointer[q_i] >= local_queues_sizes[q_i]) {
// continue;
// }
// idi sub = pointer[q_i] + local_queues_starts[q_i];
// distf tmp_dist = set_L[sub].distance_;
// idi tmp_id = set_L[sub].id_;
// if (tmp_dist < min_dist) {
// min_dist = tmp_dist;
// min_id = tmp_id;
// min_q_i = q_i;
// min_sub = sub;
// } else if (tmp_dist == min_dist && tmp_id < min_id) {
// min_id = tmp_id;
// min_q_i = q_i;
// min_sub = sub;
// }
// }
// set_K[0] = set_L[min_sub].id_;
//// {//test
//// printf("query_id: %u "
//// "[%u]: "
//// "(%u, %f)\n",
//// query_id,
//// 0,
//// set_L[min_sub].id_, set_L[min_sub].distance_);
//// }
// ++pointer[min_q_i];
// last_id = set_K[0];
//
// bool is_finished = false;
// idi k_i = 1;
// while (k_i < K && !is_finished) {
// is_finished = true;
// min_dist = FLT_MAX;
// for (int q_i = 0; q_i < num_threads_; ++q_i) {
// const idi local_queue_size = local_queues_sizes[q_i];
// idi sub = pointer[q_i] + local_queues_starts[q_i];
//
// while (pointer[q_i] < local_queue_size
// && set_L[sub].id_ == last_id) {
// ++pointer[q_i];
// ++sub;
// }
// if (pointer[q_i] >= local_queue_size) {
// continue;
// }
// is_finished = false;
// distf tmp_dist = set_L[sub].distance_;
// idi tmp_id = set_L[sub].id_;
// if (tmp_dist < min_dist) {
// min_dist = tmp_dist;
// min_id = tmp_id;
// min_q_i = q_i;
// min_sub = sub;
// } else if (tmp_dist == min_dist && tmp_id < min_id) {
// min_id = tmp_id;
// min_q_i = q_i;
// min_sub = sub;
// }
// }
// set_K[k_i] = set_L[min_sub].id_;
//// {//test
//// printf("query_id: %u "
//// "[%u]: "
//// "(%u, %f)\n",
//// query_id,
//// k_i,
//// set_L[min_sub].id_, set_L[min_sub].distance_);
//// }
// ++pointer[min_q_i];
// ++k_i;
// }
// }
//// time_merge_ += WallTimer::get_time_mark();
//
// {// Reset
//// std::fill(is_visited.begin(), is_visited.end(), 0);
// is_visited.reset();
// std::fill(local_queues_sizes.begin() + 1, local_queues_sizes.end(), 0);
// }
//
// time_ending_ += WallTimer::get_time_mark();
//// {//test
//// if (3 == query_id) {
//// exit(1);
//// }
//// }
//}
/*
* 7/28/2020-11:25
* Same with V4, but only gather top-m vertices, but not select top-L.
* Actually this should not be called "subsearch"!
*/
inline void Searching::para_search_with_top_m_subsearch_v5(
const idi local_M_max,
const idi local_M_middle,
const idi query_id,
const idi K,
const idi global_L,
const idi local_L,
// const idi total_L,
// const idi init_queue_size,
std::vector<Candidate> &set_L,
const std::vector<idi> &init_ids,
std::vector<idi> &set_K,
const std::vector<idi> &local_queues_starts,
std::vector<idi> &local_queues_sizes,
// std::vector<idi> &local_m_counts,
std::vector<idi> &top_m_candidates,
// std::vector< std::vector<idi> > &top_m_candidates_list,
boost::dynamic_bitset<> &is_visited)
{
// time_initialization_ -= WallTimer::get_time_mark();
uint64_t tmp_count_computation = 0;
{// Initialization
// is_visited flag array
//#pragma omp parallel for
// Cannot use OMP for bit array is_visited!
for (idi c_i = 0; c_i < global_L; ++c_i) {
is_visited[init_ids[c_i]] = 1;
}
const dataf *query_data = queries_load_ + query_id * dimension_;
#pragma omp parallel for
for (idi v_i = 0; v_i < global_L; ++v_i) {
idi v_id = init_ids[v_i];
_mm_prefetch(opt_nsg_graph_ + v_id * vertex_bytes_, _MM_HINT_T0);
}
// Get the distances of all candidates, store in the set set_L.
#pragma omp parallel for reduction(+ : tmp_count_computation)
for (idi id_i = 0; id_i < global_L; ++id_i) {
idi v_id = init_ids[id_i];
auto *v_data = reinterpret_cast<dataf *>(opt_nsg_graph_ + v_id * vertex_bytes_);
dataf norm = *v_data++;
++tmp_count_computation;
distf dist = compute_distance_with_norm(v_data, query_data, norm);
set_L[id_i] = Candidate(v_id, dist, false); // False means not checked.
}
local_queues_sizes[0] = global_L;
count_distance_computation_ += tmp_count_computation;
tmp_count_computation = 0;
std::sort(set_L.begin(), set_L.begin() + global_L);
}
// time_initialization_ += WallTimer::get_time_mark();
// Searching
if (num_threads_ == 1) { // Single threads
// std::sort(
// set_L.begin(),
// set_L.end());
subsearch_with_top_m(
local_M_max,
query_id,
local_L,
set_L,
0,
local_queues_sizes[0],
top_m_candidates,
is_visited,
tmp_count_computation);
count_distance_computation_ += tmp_count_computation;
tmp_count_computation = 0;
} else { // Multiple threads
const dataf *query_data = queries_load_ + query_id * dimension_;
const idi num_queues = num_threads_;
idi local_M = 1;
idi iter = 0;
// std::vector<idi> ks(num_queues, 0);
// time_sequential_phase_ -= WallTimer::get_time_mark();
{// Sequential Search for M = 1, 2.
idi k = 0;
// idi &k = ks[0];
while (k < global_L && local_M < local_M_middle) {
++iter;
subsearch_top_m_for_one_iteration(
iter,
k,
local_M,
query_id,
query_data,
global_L,
set_L,
0,
local_queues_sizes[0],
top_m_candidates,
is_visited,
tmp_count_computation);
count_distance_computation_ += tmp_count_computation;
tmp_count_computation = 0;
{// Double M
if (local_M < local_M_max) {
local_M <<= 1;
}
}
}
}
// time_sequential_phase_ += WallTimer::get_time_mark();
// time_parallel_phase_ -= WallTimer::get_time_mark();
// distf bound_lth = set_L[global_L - 1].distance_;
{// Parallel Search for M >= 4, or local_M_middle
// time_assign_s_ -=WallTimer::get_time_mark();
{// Assign elements from Queue[0] to others
idi dst_i = 1;
idi e_i_bound = num_queues * local_L;
// for (idi e_i = 1; e_i < global_L; ++e_i) {
for (idi e_i = 1; e_i < e_i_bound; ++e_i) {
idi dest_sub = e_i % num_queues;
if (0 == dest_sub) {
set_L[dst_i++] = set_L[e_i];
// set_L[local_queues_sizes[0]++] = set_L[e_i];
} else {
set_L[local_queues_starts[dest_sub] + local_queues_sizes[dest_sub]++] = set_L[e_i];
}
// if (local_queues_sizes[dest_sub] >= local_L) {
// // Sometimes local_L is very small, even smaller than global_L/T.
// break;
// }
}
local_queues_sizes[0] = dst_i;
}
// std::fill(ks.begin(), ks.end(), 0);
idi top_m_candidates_size = 0;
// time_assign_s_ +=WallTimer::get_time_mark();
std::vector<idi> ks(num_queues, 0);
std::vector<idi> nks(num_queues);
std::vector<idi> bound_ks(num_queues);
// double tmp_time_pick_top_m = 0;
// uint64_t tmp_count_add_to_queue = 0;
// double tmp_time_distance_computation = 0;
// double tmp_time_add_to_queue = 0;
// std::vector<idi> tmp_counts_add_to_queues(num_queues, 0);
while (true) {
// time_expand_ -= WallTimer::get_time_mark();
++iter;
// Gather top-M vertices
time_gather_ -= WallTimer::get_time_mark();
gather_unchecked_top_M_seq(
query_id,
iter,
set_L,
ks,
local_M,
num_queues,
local_queues_starts,
local_queues_sizes,
top_m_candidates,
top_m_candidates_size,
bound_ks);
time_gather_ += WallTimer::get_time_mark();
// {//test
// printf("query_id: %u "
// "iter: %u",
// query_id,
// iter);
// printf(" local_queues_sizes:");
// for (idi i = 0; i < num_queues; ++i) {
// printf(" %u", local_queues_sizes[i]);
// }
// printf(" gathered:");
// for (idi i = 0; i < num_queues; ++i) {
// printf(" %u", bound_ks[i] - ks[i]);
// }
// printf("\n");
// }
if (!top_m_candidates_size) {
// time_expand_ += WallTimer::get_time_mark();
break;
}
std::fill(nks.begin(), nks.end(), global_L);
// Expand top-M vertices
//#pragma omp parallel for reduction(+ : tmp_count_computation)
#pragma omp parallel for schedule(static, 1) reduction(+ : tmp_count_computation)
// reduction(+ : tmp_count_add_to_queue) \
// reduction(+ : tmp_time_distance_computation) \
// reduction(+ : tmp_time_pick_top_m) \
// reduction(+ : tmp_time_add_to_queue)
for (idi c_i = 0; c_i < top_m_candidates_size; ++c_i) {
// tmp_time_pick_top_m -= WallTimer::get_time_mark();
idi tid = omp_get_thread_num();
const idi set_L_start = local_queues_starts[tid];
idi &set_L_size = local_queues_sizes[tid];
idi &nk = nks[tid];
// idi L_value = tid == 0 ? global_L : local_L;
idi L_value = local_L;
idi cand_id = top_m_candidates[c_i];
// _mm_prefetch(opt_nsg_graph_ + cand_id * vertex_bytes_ + data_bytes_, _MM_HINT_T0);
idi *out_edges = (idi *) (opt_nsg_graph_ + cand_id * vertex_bytes_ + data_bytes_);
idi out_degree = *out_edges++;
// for (idi n_i = 0; n_i < out_degree; ++n_i) {
// _mm_prefetch(opt_nsg_graph_ + out_edges[n_i] * vertex_bytes_, _MM_HINT_T0);
// }
// tmp_time_pick_top_m += WallTimer::get_time_mark();
// Expand cand_id's neighbors
for (idi e_i = 0; e_i < out_degree; ++e_i) {
// tmp_time_distance_computation -= WallTimer::get_time_mark();
idi nb_id = out_edges[e_i];
{ // Sequential edition
if (is_visited[nb_id]) {
// tmp_time_distance_computation += WallTimer::get_time_mark();
continue;
}
is_visited[nb_id] = 1;
}
auto *nb_data = reinterpret_cast<dataf *>(opt_nsg_graph_ + nb_id * vertex_bytes_);
dataf norm = *nb_data++;
++tmp_count_computation;
distf dist = compute_distance_with_norm(nb_data, query_data, norm);
// tmp_time_distance_computation += WallTimer::get_time_mark();
// if (dist > set_L[set_L_start + set_L_size - 1].distance_) {
// if (set_L_size < L_value) {
//// ++tmp_count_add_to_queue;
// set_L[set_L_start + set_L_size] = Candidate(nb_id, dist, false);
// if (set_L_size < nk) {
// nk = set_L_size;
// }
// ++set_L_size;
// }
// continue;
// }
if (dist > set_L[set_L_start + set_L_size - 1].distance_) {
// if (dist > bound_lth) {
continue;
}
// ++tmp_counts_add_to_queues[tid];
// ++tmp_count_add_to_queue;
Candidate cand(nb_id, dist, false);
// tmp_time_add_to_queue -= WallTimer::get_time_mark();
idi r = add_into_queue(
set_L,
set_L_start,
set_L_size,
L_value,
cand);
if (r < nk) {
nk = r;
}
// tmp_time_add_to_queue += WallTimer::get_time_mark();
}
}
top_m_candidates_size = 0;
// time_add_to_queue_ += tmp_time_add_to_queue;
// tmp_time_add_to_queue = 0;
// time_distance_computation_ += tmp_time_distance_computation;
// tmp_time_distance_computation = 0;
// count_add_to_queue_ += tmp_count_add_to_queue;
// tmp_count_add_to_queue = 0;
// time_pick_top_m_ += tmp_time_pick_top_m;
// tmp_time_pick_top_m = 0;
count_distance_computation_ += tmp_count_computation;
tmp_count_computation = 0;
for (idi q_i = 0; q_i < num_queues; ++q_i) {
if (nks[q_i] < bound_ks[q_i]) {
ks[q_i] = nks[q_i];
} else {
ks[q_i] = bound_ks[q_i];
}
}
// {//test
// printf("query_id: %u "
// "iter: %u",
// query_id,
// iter);
// printf(" add_to_queues:");
// for (idi i = 0; i < num_queues; ++i) {
// printf(" %u", tmp_counts_add_to_queues[i]);
// tmp_counts_add_to_queues[i] = 0;
// }
// printf("\n");
// }
// time_expand_ += WallTimer::get_time_mark();
// time_select_ -= WallTimer::get_time_mark();
// {// Select L-th
// bound_lth = selecting_top_L_seq(
// set_L,
// global_L,
// num_queues,
// local_queues_starts,
// local_queues_sizes);
// }
// time_select_ += WallTimer::get_time_mark();
{// Scale M
if (local_M < local_M_max) {
local_M <<= 1;
}
}
// {//test
// printf("query_id: %u "
// "iter: %u",
// query_id,
// iter);
// printf(" local_queues_sizes:");
// for (idi i = 0; i < num_queues; ++i) {
// printf(" %u", local_queues_sizes[i]);
// }
//// printf(" local_m_counts:");
//// for (idi i = 0; i < num_queues; ++i) {
//// printf(" %u", local_m_counts[i]);
//// }
//// printf(" ks:");
//// for (idi i = 0; i < num_queues; ++i) {
//// printf(" %u", ks[i]);
//// }
// printf(" bound_ks:");
// for (idi i = 0; i < num_queues; ++i) {
// printf(" %u", bound_ks[i]);
// }
// printf("\n");
// }
}
}
// time_parallel_phase_ += WallTimer::get_time_mark();
}
// time_merge_ -= WallTimer::get_time_mark();
// time_ending_ -= WallTimer::get_time_mark();
{// Return the results to set_K
std::vector<idi> pointer(num_threads_, 0);
// get the first
distf min_dist = FLT_MAX;
idi min_q_i;
idi min_id;
idi min_sub;
idi last_id;
for (int q_i = 0; q_i < num_threads_; ++q_i) {
if (pointer[q_i] >= local_queues_sizes[q_i]) {
continue;
}
idi sub = pointer[q_i] + local_queues_starts[q_i];
distf tmp_dist = set_L[sub].distance_;
idi tmp_id = set_L[sub].id_;
if (tmp_dist < min_dist) {
min_dist = tmp_dist;
min_id = tmp_id;
min_q_i = q_i;
min_sub = sub;
} else if (tmp_dist == min_dist && tmp_id < min_id) {
min_id = tmp_id;
min_q_i = q_i;
min_sub = sub;
}
}
set_K[0] = set_L[min_sub].id_;
// {//test
// printf("query_id: %u "
// "[%u]: "
// "(%u, %f)\n",
// query_id,
// 0,
// set_L[min_sub].id_, set_L[min_sub].distance_);
// }
++pointer[min_q_i];
last_id = set_K[0];
bool is_finished = false;
idi k_i = 1;
while (k_i < K && !is_finished) {
is_finished = true;
min_dist = FLT_MAX;
for (int q_i = 0; q_i < num_threads_; ++q_i) {
const idi local_queue_size = local_queues_sizes[q_i];
idi sub = pointer[q_i] + local_queues_starts[q_i];
while (pointer[q_i] < local_queue_size
&& set_L[sub].id_ == last_id) {
++pointer[q_i];
++sub;
}
if (pointer[q_i] >= local_queue_size) {
continue;
}
is_finished = false;
distf tmp_dist = set_L[sub].distance_;
idi tmp_id = set_L[sub].id_;
if (tmp_dist < min_dist) {
min_dist = tmp_dist;
min_id = tmp_id;
min_q_i = q_i;
min_sub = sub;
} else if (tmp_dist == min_dist && tmp_id < min_id) {
min_id = tmp_id;
min_q_i = q_i;
min_sub = sub;
}
}
set_K[k_i] = set_L[min_sub].id_;
// {//test
// printf("query_id: %u "
// "[%u]: "
// "(%u, %f)\n",
// query_id,
// k_i,
// set_L[min_sub].id_, set_L[min_sub].distance_);
// }
++pointer[min_q_i];
++k_i;
}
}
// time_merge_ += WallTimer::get_time_mark();
{// Reset
// std::fill(is_visited.begin(), is_visited.end(), 0);
is_visited.reset();
std::fill(local_queues_sizes.begin() + 1, local_queues_sizes.end(), 0);
}
// time_ending_ += WallTimer::get_time_mark();
// {//test
// if (3 == query_id) {
// exit(1);
// }
// }
}
/*
* 6/27/2020-12:33
* Do searching on the local_set_L
* local_set_L is already sorted
* is_visited is already set up.
*/
inline void Searching::subsearch_for_simple_search(
const idi query_id,
const idi local_L,
std::vector<Candidate> &set_L,
const idi base_set_L,
idi &set_L_end,
// std::vector<uint8_t> &is_visited,
boost::dynamic_bitset<> &is_visited,
uint64_t &local_count_distance_computation)
{
const dataf *query_data = queries_load_ + query_id * dimension_;
// idi local_top_m_candidates_end = 0;
idi k = 0; // Index of first unchecked candidate.
idi iter = 0;
// idi M = 1; // value of M
while (k < local_L) {
++iter;
// {//test
// printf("query_id: %u "
// "iter: %u\n",
// query_id,
// iter);
// }
// Select the top-1 unchecked candidate
idi top_1;
idi last_k = local_L;
// Cannot use OpenMP here because this for-loop needs early break by the 2nd condition.
for (idi c_i = k; c_i < set_L_end; ++c_i) {
idi index_set_L = c_i + base_set_L;
if (set_L[index_set_L].is_checked_) {
continue;
}
top_1 = set_L[index_set_L].id_;
last_k = c_i; // Record the location of the last candidate selected.
set_L[index_set_L].is_checked_ = true;
// local_top_m_candidates[local_top_m_candidates_end++] = set_L[index_set_L].id_;
break;
}
if (last_k == local_L) {
break;
}
idi nk = local_L;
// Push top-1' neighbors into the queue.
idi cand_id = top_1;
_mm_prefetch(opt_nsg_graph_ + cand_id * vertex_bytes_ + data_bytes_, _MM_HINT_T0);
idi *out_edges = (idi *) (opt_nsg_graph_ + cand_id * vertex_bytes_ + data_bytes_);
idi out_degree = *out_edges++;
for (idi n_i = 0; n_i < out_degree; ++n_i) {
_mm_prefetch(opt_nsg_graph_ + out_edges[n_i] * vertex_bytes_, _MM_HINT_T0);
}
for (idi e_i = 0; e_i < out_degree; ++e_i) {
idi nb_id = out_edges[e_i];
{ // Sequential edition
if (is_visited[nb_id]) {
continue;
}
is_visited[nb_id] = 1;
}
// {// Critical edition
// if (!AtomicOps::CAS(is_visited.data() + nb_id,
// static_cast<uint8_t>(0),
// static_cast<uint8_t>(1))) {
// continue;
// }
// }
auto *nb_data = reinterpret_cast<dataf *>(opt_nsg_graph_ + nb_id * vertex_bytes_);
dataf norm = *nb_data++;
++local_count_distance_computation;
distf dist = compute_distance_with_norm(nb_data, query_data, norm);
// {
// if (0 == query_id
// && (785802 == nb_id
// || 180955 == nb_id
// || 240996 == nb_id
// || 813701 == nb_id
// || 708177 == nb_id
// || 87578 == nb_id
// || 561813 == nb_id
// || 701258 == nb_id
// || 872728 == nb_id)) {
//// && 180955 == nb_id) {
// printf("parent: %u "
// "nb_id: %u "
// "dist: %f "
// "base_set_L: %u "
// "set_L_end: %u\n",
// cand_id,
// nb_id,
// dist,
// base_set_L,
// set_L_end);
// }
// }
if (dist > set_L[set_L_end - 1 + base_set_L].distance_) {
continue;
}
Candidate cand(nb_id, dist, false);
// Thread 0 maintains the "global" queue
idi r = add_into_queue(
set_L,
base_set_L,
set_L_end,
local_L,
cand);
if (r < nk) {
nk = r;
}
}
if (nk <= last_k) {
k = nk;
} else {
k = last_k + 1;
}
}
}
/*
* 6/27/2020-12:26
* Is is good to use subsearch by every thread it self?
*/
inline void Searching::para_simple_search_subsearch(
const idi query_id,
const idi K,
const idi L,
std::vector<Candidate> &set_L,
const std::vector<idi> &init_ids,
std::vector<idi> &set_K,
// std::vector<uint8_t> &is_visited)
boost::dynamic_bitset<> &is_visited)
{
uint64_t tmp_count_computation = 0;
{// Initialization
// is_visited flag array
//#pragma omp parallel for
// Cannot use OMP for bit array is_visited!
for (idi c_i = 0; c_i < L; ++c_i) {
is_visited[init_ids[c_i]] = 1;
}
const dataf *query_data = queries_load_ + query_id * dimension_;
#pragma omp parallel for
for (idi v_i = 0; v_i < L; ++v_i) {
idi v_id = init_ids[v_i];
_mm_prefetch(opt_nsg_graph_ + v_id * vertex_bytes_, _MM_HINT_T0);
}
// Get the distances of all candidates, store in the set set_L.
//#pragma omp parallel for
#pragma omp parallel for reduction(+ : tmp_count_computation)
for (unsigned i = 0; i < L; i++) {
unsigned v_id = init_ids[i];
auto *v_data = reinterpret_cast<dataf *>(opt_nsg_graph_ + v_id * vertex_bytes_);
dataf norm = *v_data++;
++tmp_count_computation;
distf dist = compute_distance_with_norm(v_data, query_data, norm);
set_L[i] = Candidate(v_id, dist, false); // False means not checked.
}
count_distance_computation_ += tmp_count_computation;
tmp_count_computation = 0;
// std::sort(
// set_L.begin(),
// set_L.begin() + L);
}
idi queue_end = L;
// Searching
if (num_threads_ == 1) { // Single threads
std::sort(
set_L.begin(),
set_L.end());
subsearch_for_simple_search(
query_id,
L,
set_L,
0,
queue_end,
is_visited,
tmp_count_computation);
count_distance_computation_ += tmp_count_computation;
// {
//// {//test
//// for (idi i = 0; i < queue_end; ++i) {
//// printf("start: "
//// "query_id: %u "
//// "set_L[%u]: "
//// "(%u %f)\n",
//// query_id,
//// i,
//// set_L[i].id_, set_L[i].distance_);
//// }
//// }
//
// idi half_length = queue_end / 2;
// std::sort(
// set_L.begin(),
// set_L.begin() + half_length);
//// {//test
//// for (idi i = 0; i < half_length; ++i) {
//// printf("sorted: "
//// "query_id: %u "
//// "set_L[%u]: "
//// "(%u %f)\n",
//// query_id,
//// i,
//// set_L[i].id_, set_L[i].distance_);
//// }
//// }
//
// subsearch_for_simple_search(
// query_id,
// half_length, // local_L
// set_L,
// 0, // base_set_L
// half_length, // set_L_end
// is_visited,
// tmp_count_computation);
//
//// {//test
//// for (idi i = 0; i < half_length; ++i) {
//// printf("subsearched: "
//// "query_id: %u "
//// "set_L[%u]: "
//// "(%u %f)\n",
//// query_id,
//// i,
//// set_L[i].id_, set_L[i].distance_);
//// }
//// }
//
// std::sort(
// set_L.begin() + half_length,
// set_L.end());
//
//// {//test
//// for (idi i = half_length; i < queue_end; ++i) {
//// printf("sorted: "
//// "query_id: %u "
//// "set_L[%u]: "
//// "(%u %f)\n",
//// query_id,
//// i,
//// set_L[i].id_, set_L[i].distance_);
//// }
//// }
//
// subsearch_for_simple_search(
// query_id,
// half_length, // local_L
// set_L,
// half_length, // base_set_L
// half_length, // set_L_end
// is_visited,
// tmp_count_computation);
//// {//test
//// for (idi i = half_length; i < queue_end; ++i) {
//// printf("subsearched: "
//// "query_id: %u "
//// "set_L[%u]: "
//// "(%u %f)\n",
//// query_id,
//// i,
//// set_L[i].id_, set_L[i].distance_);
//// }
//// }
//// {//test
//// for (idi i = 0; i < queue_end; ++i) {
//// printf("explored: "
//// "query_id: %u "
//// "set_L[%u]: "
//// "(%u %f)\n",
//// query_id,
//// i,
//// set_L[i].id_, set_L[i].distance_);
//// }
//// }
// count_distance_computation_ += tmp_count_computation;
//
// std::vector <Candidate> tmp_set_L(L);
// std::merge(set_L.begin(), set_L.begin() + half_length,
// set_L.begin() + half_length, set_L.end(),
// tmp_set_L.begin());
// std::copy(tmp_set_L.begin(), tmp_set_L.end(), set_L.begin());
//// {//test
//// for (idi i = 0; i < queue_end; ++i) {
//// printf("merged: "
//// "query_id: %u "
//// "set_L[%u]: "
//// "(%u %f)\n",
//// query_id,
//// i,
//// set_L[i].id_, set_L[i].distance_);
//// }
//// }
// }
} else { // Multiple threads
const idi num_queues = num_threads_;
const idi local_queue_length = (L - 1) / num_queues + 1;
// Parallel for
#pragma omp parallel for reduction(+ : tmp_count_computation)
for (idi q_i = 0; q_i < num_queues; ++q_i) {
idi local_queue_base = q_i * local_queue_length;
if (local_queue_base >= L) {
continue;
}
idi local_queue_end = local_queue_length;
if (local_queue_base + local_queue_end > L) {
local_queue_end = L - local_queue_base;
}
std::sort(
set_L.begin() + local_queue_base,
set_L.begin() + local_queue_base + local_queue_end);
subsearch_for_simple_search(
query_id,
local_queue_end, // local_L
set_L,
local_queue_base, // base_set_L
local_queue_end, // set_L_end
is_visited,
tmp_count_computation);
}
count_distance_computation_ += tmp_count_computation;
// Merge
// time_merge_ -= WallTimer::get_time_mark();
merge_in_set_L(
set_L,
L,
num_queues,
local_queue_length);
// time_merge_ += WallTimer::get_time_mark();
}
{// Return the results to set_K
// How to deal with duplicate?
idi last_id = set_L[0].id_;
set_K[0] = last_id;
idi k_i = 1;
idi l_i = 1;
while (k_i < K && l_i < L) {
if (last_id == set_L[l_i].id_) {
++l_i;
continue;
}
last_id = set_L[l_i++].id_;
set_K[k_i++] = last_id;
}
//#pragma omp parallel for
// for (idi k_i = 0; k_i < K; ++k_i) {
// set_K[k_i] = set_L[k_i].id_;
//// set_K[k_i] = set_L[k_i].id_;
// }
}
{// Reset
// std::fill(is_visited.begin(), is_visited.end(), 0);
is_visited.reset();
// is_visited.clear_all();
}
// {//test
// if (0 == query_id) {
// exit(1);
// }
// }
}
///*
// * 6/22/2020-09:38
// * A synchronized last element as the sentinel
// */
//inline void Searching::para_search_with_top_m_merge_queues_global_threshold(
// const idi value_M_middle,
// const idi value_M_max,
// const idi query_id,
// const idi K,
// const idi L,
// std::vector<Candidate> &set_L,
// const std::vector<idi> &init_ids,
// std::vector<idi> &set_K,
// const idi local_queue_length, // Maximum size of local queue
// const idi base_set_L, // base_set_L = (num_threads_ - 1) * local_queue_length;
// std::vector<idi> &local_queues_ends, // Sizes of local queue
// std::vector<idi> &top_m_candidates,
// boost::dynamic_bitset<> &is_visited)
//{
//// const idi base_set_L = (num_threads_ - 1) * local_queue_length;
// {
//#pragma omp parallel for
// for (idi c_i = 0; c_i < L; ++c_i) {
// is_visited[init_ids[c_i]] = 1;
// }
// }
//
// const dataf *query_data = queries_load_ + query_id * dimension_;
//#pragma omp parallel for
// for (idi v_i = 0; v_i < L; ++v_i) {
// idi v_id = init_ids[v_i];
// _mm_prefetch(opt_nsg_graph_ + v_id * vertex_bytes_, _MM_HINT_T0);
// }
// uint64_t tmp_count_computation = 0;
// // Get the distances of all candidates, store in the set set_L.
////#pragma omp parallel for
//#pragma omp parallel for reduction(+ : tmp_count_computation)
// for (unsigned i = 0; i < L; i++) {
// unsigned v_id = init_ids[i];
// auto *v_data = reinterpret_cast<dataf *>(opt_nsg_graph_ + v_id * vertex_bytes_);
// dataf norm = *v_data++;
// ++tmp_count_computation;
// distf dist = compute_distance_with_norm(v_data, query_data, norm);
// set_L[i + base_set_L] = Candidate(v_id, dist, false); // False means not checked.
// }
// count_distance_computation_ += tmp_count_computation;
// tmp_count_computation = 0;
//// std::sort(set_L.begin(), set_L.begin() + L);
// std::sort(
// set_L.begin() + base_set_L,
// set_L.begin() + base_set_L + L);
// local_queues_ends[num_threads_ - 1] = L;
//
// idi top_m_candidates_end = 0;
// idi k = 0; // Index of first unchecked candidate.
// idi tmp_count = 0; // for debug
// idi M = 1;
//
// { // Single thread
// while (k < L && M < value_M_middle) {
// ++tmp_count;
//// {//test
//// printf("tmp_count: %d\n", tmp_count);
//// }
//
// // Select M candidates
// idi last_k = L;
//// Cannot use OpenMP here because this for-loop needs early break by the 2nd condition.
// for (idi c_i = k; c_i < L && top_m_candidates_end < M; ++c_i) {
// idi index_set_L = c_i + base_set_L;
// if (set_L[index_set_L].is_checked_) {
// continue;
// }
// last_k = c_i; // Record the location of the last candidate selected.
// set_L[index_set_L].is_checked_ = true;
// top_m_candidates[top_m_candidates_end++] = set_L[index_set_L].id_;
// }
//
// idi nk = L;
// // Push M candidates' neighbors into the queue.
// for (idi c_i = 0; c_i < top_m_candidates_end; ++c_i) {
// idi cand_id = top_m_candidates[c_i];
// _mm_prefetch(opt_nsg_graph_ + cand_id * vertex_bytes_ + data_bytes_, _MM_HINT_T0);
// idi *out_edges = (idi *) (opt_nsg_graph_ + cand_id * vertex_bytes_ + data_bytes_);
// idi out_degree = *out_edges++;
// for (idi n_i = 0; n_i < out_degree; ++n_i) {
// _mm_prefetch(opt_nsg_graph_ + out_edges[n_i] * vertex_bytes_, _MM_HINT_T0);
// }
// for (idi e_i = 0; e_i < out_degree; ++e_i) {
// idi nb_id = out_edges[e_i];
// { // Sequential edition
// if (is_visited[nb_id]) {
// continue;
// }
// is_visited[nb_id] = 1;
// }
//
// auto *nb_data = reinterpret_cast<dataf *>(opt_nsg_graph_ + nb_id * vertex_bytes_);
// dataf norm = *nb_data++;
// ++tmp_count_computation;
// distf dist = compute_distance_with_norm(nb_data, query_data, norm);
// if (dist > set_L[L - 1 + base_set_L].distance_) {
// continue;
// }
//
// Candidate cand(nb_id, dist, false);
// // Thread 0 maintains the "global" queue
// idi r = add_into_queue(
// set_L,
// base_set_L,
// local_queues_ends[num_threads_ - 1],
// L,
// cand);
// if (r < nk) {
// nk = r;
// }
// }
// }
// top_m_candidates_end = 0; // Clear top_m_candidates
// count_distance_computation_ += tmp_count_computation;
// tmp_count_computation = 0;
//
// if (nk <= last_k) {
// k = nk;
// } else {
// k = last_k + 1;
// }
//
// {// Scale M
// if (M < value_M_max) {
// M <<= 1;
// } else {
// M = value_M_max;
// }
// }
//
// }
// }
//
// { // Multiple Threads
// while (k < L) {
// ++tmp_count;
//// {//test
//// printf("tmp_count: %d\n", tmp_count);
//// }
// // Select M candidates
// idi last_k = L;
//// Cannot use OpenMP here because this for-loop needs early break by the 2nd condition.
// for (idi c_i = k; c_i < L && top_m_candidates_end < M; ++c_i) {
// idi index_set_L = c_i + base_set_L;
// if (set_L[index_set_L].is_checked_) {
// continue;
// }
// last_k = c_i; // Record the location of the last candidate selected.
// set_L[index_set_L].is_checked_ = true;
// top_m_candidates[top_m_candidates_end++] = set_L[index_set_L].id_;
// }
//
//
// idi nk = L;
// // Push M candidates' neighbors into the queue.
////#pragma omp parallel for reduction(+ : tmp_count_computation) num_threads(real_threads)
//#pragma omp parallel for reduction(+ : tmp_count_computation)
// for (idi c_i = 0; c_i < top_m_candidates_end; ++c_i) {
// int tid = omp_get_thread_num();
// idi cand_id = top_m_candidates[c_i];
// _mm_prefetch(opt_nsg_graph_ + cand_id * vertex_bytes_ + data_bytes_, _MM_HINT_T0);
// idi *out_edges = (idi *) (opt_nsg_graph_ + cand_id * vertex_bytes_ + data_bytes_);
// idi out_degree = *out_edges++;
// for (idi n_i = 0; n_i < out_degree; ++n_i) {
// _mm_prefetch(opt_nsg_graph_ + out_edges[n_i] * vertex_bytes_, _MM_HINT_T0);
// }
// for (idi e_i = 0; e_i < out_degree; ++e_i) {
// idi nb_id = out_edges[e_i];
// { // Sequential edition
// if (is_visited[nb_id]) {
// continue;
// }
// is_visited[nb_id] = 1;
// }
//
// auto *nb_data = reinterpret_cast<dataf *>(opt_nsg_graph_ + nb_id * vertex_bytes_);
// dataf norm = *nb_data++;
// ++tmp_count_computation;
// distf dist = compute_distance_with_norm(nb_data, query_data, norm);
// if (dist > set_L[L - 1 + base_set_L].distance_) {
// continue;
// }
//
// Candidate cand(nb_id, dist, false);
// // Add to the local queue.
// if (0 != tid) {
// // Non-Master threads using local queues
// add_into_queue(
// set_L,
// (tid - 1) * local_queue_length,
// local_queues_ends[tid - 1],
// local_queue_length,
// cand);
// } else {
// // Thread 0 maintains the "global" queue
// idi r = add_into_queue(
// set_L,
// base_set_L,
// local_queues_ends[num_threads_ - 1],
// L,
// cand);
// if (r < nk) {
// nk = r;
// }
// }
// }
// }
// top_m_candidates_end = 0; // Clear top_m_candidates
// count_distance_computation_ += tmp_count_computation;
// tmp_count_computation = 0;
//
// {// Local queues' ends
//// printf("query%u:iter: %u", query_id, tmp_count);
// idi total_elements = 0;
// for (int i_t = 0; i_t < num_threads_ - 1; ++i_t) {
// total_elements += local_queues_ends[i_t];
// }
// number_local_elements_ += total_elements;
//// printf(" total_elements: %u+%u\n", total_elements - local_queues_ends[num_threads_ - 1], local_queues_ends[num_threads_ - 1]);
//// for (int i_t = 0; i_t < num_threads_; ++i_t) {
//// printf(" [%u]: %u", i_t, local_queues_ends[i_t]);
//// }
//// printf("\n");
// }
//
//// // Merge. Merge all queues in parallel.
// {
// time_merge_ -= WallTimer::get_time_mark();
// if (num_threads_ > 1) {
// idi r = merge_all_queues_para_array(
// set_L,
// local_queues_ends,
// local_queue_length,
// L);
// if (r < nk) {
// nk = r;
// }
// }
// time_merge_ += WallTimer::get_time_mark();
// }
// if (nk <= last_k) {
// k = nk;
// } else {
// k = last_k + 1;
// }
// {// Scale M
// if (M < value_M_max) {
// M <<= 1;
// } else {
// M = value_M_max;
// }
// }
//
// }
// }
//
//
//#pragma omp parallel for
// for (idi k_i = 0; k_i < K; ++k_i) {
// set_K[k_i] = set_L[k_i + base_set_L].id_;
//// set_K[k_i] = set_L[k_i].id_;
// }
//
// {// Reset
//// std::fill(is_visited.begin(), is_visited.end(), 0);
// is_visited.reset();
//// is_visited.clear_all();
// std::fill(local_queues_ends.begin(), local_queues_ends.end(), 0);
// }
//
//// {//test
//// if (0 == query_id) {
//// exit(1);
//// }
//// }
//}
///*
// * 6/7/2020-16:55
// * Use 1 threads to scale M until the value_M_middle.
// * Then use multiple threads.
// * Except for Thread 0, other threads are collectors. They collect, but do not merge.
// * Only merge once after Thread 0 stops.
// */
//inline void Searching::para_search_with_top_m_merge_queues_collectors(
// const idi value_M_middle,
// const idi value_M_max,
// const idi query_id,
// const idi K,
// const idi L,
// std::vector<Candidate> &set_L,
// const std::vector<idi> &init_ids,
// std::vector<idi> &set_K,
// const idi local_queue_length, // Maximum size of local queue
// const idi base_set_L, // base_set_L = (num_threads_ - 1) * local_queue_length;
// std::vector<idi> &local_queues_ends, // Sizes of local queue
//// std::vector<Candidate> &top_m_candidates,
// std::vector<idi> &top_m_candidates,
//// std::vector<uint8_t> &is_visited)
// boost::dynamic_bitset<> &is_visited)
//// std::vector<distf> &local_thresholds)
//// BitVector &is_visited)
//{
// {
//#pragma omp parallel for
// for (idi c_i = 0; c_i < L; ++c_i) {
// is_visited[init_ids[c_i]] = 1;
//// is_visited.atomic_set_bit(init_ids[c_i]);
// }
// }
//
// const dataf *query_data = queries_load_ + query_id * dimension_;
//#pragma omp parallel for
// for (idi v_i = 0; v_i < L; ++v_i) {
// idi v_id = init_ids[v_i];
// _mm_prefetch(opt_nsg_graph_ + v_id * vertex_bytes_, _MM_HINT_T0);
// }
// uint64_t tmp_count_computation = 0;
// // Get the distances of all candidates, store in the set set_L.
////#pragma omp parallel for
//#pragma omp parallel for reduction(+ : tmp_count_computation)
// for (unsigned i = 0; i < L; i++) {
// unsigned v_id = init_ids[i];
// auto *v_data = reinterpret_cast<dataf *>(opt_nsg_graph_ + v_id * vertex_bytes_);
// dataf norm = *v_data++;
//// ++count_distance_computation_;
// ++tmp_count_computation;
// distf dist = compute_distance_with_norm(v_data, query_data, norm);
// set_L[i + base_set_L] = Candidate(v_id, dist, false); // False means not checked.
//// set_L[i] = Candidate(v_id, dist, false); // False means not checked.
// }
// count_distance_computation_ += tmp_count_computation;
// tmp_count_computation = 0;
//// std::sort(set_L.begin(), set_L.begin() + L);
// std::sort(
// set_L.begin() + base_set_L,
// set_L.begin() + base_set_L + L);
//// boost::sort::block_indirect_sort(
//// set_L.begin() + base_set_L,
//// set_L.begin() + base_set_L + L,
//// num_threads_);
// local_queues_ends[num_threads_ - 1] = L;
//
//// std::vector<idi> top_m_candidates(M);
// idi top_m_candidates_end = 0;
// idi k = 0; // Index of first unchecked candidate.
// idi tmp_count = 0; // for debug
// idi M = 1;
//
// // Single thread
// {
// while (k < L && M < value_M_middle) {
// ++tmp_count;
//// {//test
//// printf("tmp_count: %d\n", tmp_count);
//// }
//
//// int real_threads = std::min(static_cast<int>(M), num_threads_);
//// idi queue_base = num_threads_ - real_threads;
// // Select M candidates
// idi last_k = L;
//// Cannot use OpenMP here because this for-loop needs early break by the 2nd condition.
// for (idi c_i = k; c_i < L && top_m_candidates_end < M; ++c_i) {
// idi index_set_L = c_i + base_set_L;
// if (set_L[index_set_L].is_checked_) {
// continue;
// }
// last_k = c_i; // Record the location of the last candidate selected.
// set_L[index_set_L].is_checked_ = true;
// top_m_candidates[top_m_candidates_end++] = set_L[index_set_L].id_;
// }
//
// idi nk = L;
// // Push M candidates' neighbors into the queue.
// for (idi c_i = 0; c_i < top_m_candidates_end; ++c_i) {
// idi cand_id = top_m_candidates[c_i];
// _mm_prefetch(opt_nsg_graph_ + cand_id * vertex_bytes_ + data_bytes_, _MM_HINT_T0);
// idi *out_edges = (idi *) (opt_nsg_graph_ + cand_id * vertex_bytes_ + data_bytes_);
// idi out_degree = *out_edges++;
// for (idi n_i = 0; n_i < out_degree; ++n_i) {
// _mm_prefetch(opt_nsg_graph_ + out_edges[n_i] * vertex_bytes_, _MM_HINT_T0);
// }
// for (idi e_i = 0; e_i < out_degree; ++e_i) {
// idi nb_id = out_edges[e_i];
// { // Sequential edition
// if (is_visited[nb_id]) {
// continue;
// }
// is_visited[nb_id] = 1;
// }
//
// auto *nb_data = reinterpret_cast<dataf *>(opt_nsg_graph_ + nb_id * vertex_bytes_);
// dataf norm = *nb_data++;
//// ++count_distance_computation_;
// ++tmp_count_computation;
// distf dist = compute_distance_with_norm(nb_data, query_data, norm);
// if (dist > set_L[L - 1 + base_set_L].distance_) {
// continue;
// }
//
// Candidate cand(nb_id, dist, false);
// // Thread 0 maintains the "global" queue
// idi r = add_into_queue(
// set_L,
// base_set_L,
// local_queues_ends[num_threads_ - 1],
// L,
// cand);
// if (r < nk) {
// nk = r;
// }
// }
// }
// top_m_candidates_end = 0; // Clear top_m_candidates
// count_distance_computation_ += tmp_count_computation;
// tmp_count_computation = 0;
//
// if (nk <= last_k) {
// k = nk;
// } else {
// k = last_k + 1;
// }
//
// {// Scale M
// if (M < value_M_max) {
// M <<= 1;
// } else {
// M = value_M_max;
// }
// }
// }
// }
//
// // Multiple Threads
// {
//// while (k < L/num_threads_/2) {
// while (k < L) {
// ++tmp_count;
//// {//test
//// printf("tmp_count: %d\n", tmp_count);
//// }
//// int real_threads = std::min(static_cast<int>(M), num_threads_);
//// idi queue_base = num_threads_ - real_threads;
// // Select M candidates
// idi last_k = L;
//// Cannot use OpenMP here because this for-loop needs early break by the 2nd condition.
// for (idi c_i = k; c_i < L && top_m_candidates_end < M; ++c_i) {
// idi index_set_L = c_i + base_set_L;
// if (set_L[index_set_L].is_checked_) {
// continue;
// }
// last_k = c_i; // Record the location of the last candidate selected.
// set_L[index_set_L].is_checked_ = true;
// top_m_candidates[top_m_candidates_end++] = set_L[index_set_L].id_;
// }
//
// idi chunk_size;
// if (num_threads_ <= top_m_candidates_end) {
// chunk_size = (top_m_candidates_end - 1) / num_threads_ + 1;
// } else {
// chunk_size = 1;
// }
// idi nk = L;
// // Push M candidates' neighbors into the queue.
////#pragma omp parallel for reduction(+ : tmp_count_computation) num_threads(real_threads)
////#pragma omp parallel for reduction(+ : tmp_count_computation)
//#pragma omp parallel for reduction(+ : tmp_count_computation) schedule(static, chunk_size)
// for (idi c_i = 0; c_i < top_m_candidates_end; ++c_i) {
// int tid = omp_get_thread_num();
//// {
//// if (c_i < chunk_size && tid != 0) {
//// printf("query_id: %u "
//// "tmp_count: %u "
//// "chunk_size: %u "
//// "c_i: %u "
//// "tid: %u\n",
//// query_id,
//// tmp_count,
//// chunk_size,
//// c_i,
//// tid);
//// }
//// }
// idi cand_id = top_m_candidates[c_i];
// _mm_prefetch(opt_nsg_graph_ + cand_id * vertex_bytes_ + data_bytes_, _MM_HINT_T0);
// idi *out_edges = (idi *) (opt_nsg_graph_ + cand_id * vertex_bytes_ + data_bytes_);
// idi out_degree = *out_edges++;
// for (idi n_i = 0; n_i < out_degree; ++n_i) {
// _mm_prefetch(opt_nsg_graph_ + out_edges[n_i] * vertex_bytes_, _MM_HINT_T0);
// }
// for (idi e_i = 0; e_i < out_degree; ++e_i) {
// idi nb_id = out_edges[e_i];
// { // Sequential edition
// if (is_visited[nb_id]) {
// continue;
// }
// is_visited[nb_id] = 1;
// }
//
// auto *nb_data = reinterpret_cast<dataf *>(opt_nsg_graph_ + nb_id * vertex_bytes_);
// dataf norm = *nb_data++;
//// ++count_distance_computation_;
// ++tmp_count_computation;
// distf dist = compute_distance_with_norm(nb_data, query_data, norm);
// if (dist > set_L[L - 1 + base_set_L].distance_) {
// continue;
// }
//
// Candidate cand(nb_id, dist, false);
// // Add to the local queue.
// if (0 != tid) {
// // Non-Master threads using local queues
// add_into_queue(
// set_L,
// (tid - 1) * local_queue_length,
// local_queues_ends[tid - 1],
// local_queue_length,
// cand);
// } else {
// // Thread 0 maintains the "global" queue
// idi r = add_into_queue(
// set_L,
// base_set_L,
// local_queues_ends[num_threads_ - 1],
// L,
// cand);
// if (r < nk) {
// nk = r;
// }
// }
// }
// }
// top_m_candidates_end = 0; // Clear top_m_candidates
// count_distance_computation_ += tmp_count_computation;
// tmp_count_computation = 0;
//
////// // Merge. Merge all queues in parallel.
//// {
//// time_merge_ -= WallTimer::get_time_mark();
//// if (num_threads_ > 1) {
////// idi r = merge_all_queues_queue_base(
////// set_L,
////// local_queues_ends,
////// queue_base,
////// real_threads,
////// local_queue_length,
////// L);
//// idi r = merge_all_queues_para_array(
//// set_L,
//// local_queues_ends,
//// local_queue_length,
//// L);
//// if (r < nk) {
//// nk = r;
//// }
//// }
//// time_merge_ += WallTimer::get_time_mark();
//// }
// if (nk <= last_k) {
// k = nk;
// } else {
// k = last_k + 1;
// }
// {// Scale M
// if (M < value_M_max) {
// M <<= 1;
// } else {
// M = value_M_max;
// }
// }
// }
//
//// // Merge only once after Master Thread stops.
//// {
//// time_merge_ -= WallTimer::get_time_mark();
//// if (num_threads_ > 1) {
////// idi r = merge_all_queues_queue_base(
////// set_L,
////// local_queues_ends,
////// queue_base,
////// real_threads,
////// local_queue_length,
////// L);
//// merge_all_queues_para_array(
//// set_L,
//// local_queues_ends,
//// local_queue_length,
//// L);
//// }
//// time_merge_ += WallTimer::get_time_mark();
//// }
// }
//
//
//#pragma omp parallel for
// for (idi k_i = 0; k_i < K; ++k_i) {
// set_K[k_i] = set_L[k_i + base_set_L].id_;
//// set_K[k_i] = set_L[k_i].id_;
// }
//
// {// Reset
//// std::fill(is_visited.begin(), is_visited.end(), 0);
// is_visited.reset();
//// is_visited.clear_all();
// std::fill(local_queues_ends.begin(), local_queues_ends.end(), 0);
// }
//
//// {//test
//// printf("tmp_count: %u\n", tmp_count);
//// if (3 == query_id) {
//// exit(1);
//// }
//// }
//}
///*
// * 6/8/2020-16:39
// * Selecting rather than merging
// */
//inline void Searching::para_search_with_top_m_merge_queues_selecting(
// const idi value_M_middle,
// const idi value_M_max,
// const idi query_id,
// const idi K,
// const idi L,
// std::vector<Candidate> &set_L,
// const std::vector<idi> &init_ids,
// std::vector<idi> &set_K,
// const idi local_queue_length, // Maximum size of local queue
// const idi base_set_L, // base_set_L = (num_threads_ - 1) * local_queue_length;
// std::vector<idi> &local_queues_ends, // Sizes of local queue
//// std::vector<Candidate> &top_m_candidates,
// std::vector<idi> &top_m_candidates,
//// std::vector<uint8_t> &is_visited)
// boost::dynamic_bitset<> &is_visited)
//{
// {
//#pragma omp parallel for
// for (idi c_i = 0; c_i < L; ++c_i) {
// is_visited[init_ids[c_i]] = 1;
//// is_visited.atomic_set_bit(init_ids[c_i]);
// }
// }
//
// const dataf *query_data = queries_load_ + query_id * dimension_;
//#pragma omp parallel for
// for (idi v_i = 0; v_i < L; ++v_i) {
// idi v_id = init_ids[v_i];
// _mm_prefetch(opt_nsg_graph_ + v_id * vertex_bytes_, _MM_HINT_T0);
// }
// uint64_t tmp_count_computation = 0;
// // Get the distances of all candidates, store in the set set_L.
////#pragma omp parallel for
//#pragma omp parallel for reduction(+ : tmp_count_computation)
// for (unsigned i = 0; i < L; i++) {
// unsigned v_id = init_ids[i];
// auto *v_data = reinterpret_cast<dataf *>(opt_nsg_graph_ + v_id * vertex_bytes_);
// dataf norm = *v_data++;
//// ++count_distance_computation_;
// ++tmp_count_computation;
// distf dist = compute_distance_with_norm(v_data, query_data, norm);
// set_L[i + base_set_L] = Candidate(v_id, dist, false); // False means not checked.
//// set_L[i] = Candidate(v_id, dist, false); // False means not checked.
// }
// count_distance_computation_ += tmp_count_computation;
// tmp_count_computation = 0;
//// std::sort(set_L.begin(), set_L.begin() + L);
// std::sort(
// set_L.begin() + base_set_L,
// set_L.begin() + base_set_L + L);
//// boost::sort::block_indirect_sort(
//// set_L.begin() + base_set_L,
//// set_L.begin() + base_set_L + L,
//// num_threads_);
// local_queues_ends[num_threads_ - 1] = L;
//
//// std::vector<idi> top_m_candidates(M);
// idi top_m_candidates_end = 0;
// idi k = 0; // Index of first unchecked candidate.
// idi tmp_count = 0; // for debug
// idi M = 1;
//
// // Single thread
// {
// while (k < L && M < value_M_middle) {
// ++tmp_count;
//// {//test
//// printf("tmp_count: %d\n", tmp_count);
//// }
//
//// int real_threads = std::min(static_cast<int>(M), num_threads_);
//// idi queue_base = num_threads_ - real_threads;
// // Select M candidates
// idi last_k = L;
//// Cannot use OpenMP here because this for-loop needs early break by the 2nd condition.
// for (idi c_i = k; c_i < L && top_m_candidates_end < M; ++c_i) {
// idi index_set_L = c_i + base_set_L;
// if (set_L[index_set_L].is_checked_) {
// continue;
// }
// last_k = c_i; // Record the location of the last candidate selected.
// set_L[index_set_L].is_checked_ = true;
// top_m_candidates[top_m_candidates_end++] = set_L[index_set_L].id_;
// }
//
// idi nk = L;
// // Push M candidates' neighbors into the queue.
// for (idi c_i = 0; c_i < top_m_candidates_end; ++c_i) {
// idi cand_id = top_m_candidates[c_i];
// _mm_prefetch(opt_nsg_graph_ + cand_id * vertex_bytes_ + data_bytes_, _MM_HINT_T0);
// idi *out_edges = (idi *) (opt_nsg_graph_ + cand_id * vertex_bytes_ + data_bytes_);
// idi out_degree = *out_edges++;
// for (idi n_i = 0; n_i < out_degree; ++n_i) {
// _mm_prefetch(opt_nsg_graph_ + out_edges[n_i] * vertex_bytes_, _MM_HINT_T0);
// }
// for (idi e_i = 0; e_i < out_degree; ++e_i) {
// idi nb_id = out_edges[e_i];
// { // Sequential edition
// if (is_visited[nb_id]) {
// continue;
// }
// is_visited[nb_id] = 1;
// }
//
// auto *nb_data = reinterpret_cast<dataf *>(opt_nsg_graph_ + nb_id * vertex_bytes_);
// dataf norm = *nb_data++;
//// ++count_distance_computation_;
// ++tmp_count_computation;
// distf dist = compute_distance_with_norm(nb_data, query_data, norm);
// if (dist > set_L[L - 1 + base_set_L].distance_) {
// continue;
// }
//
// Candidate cand(nb_id, dist, false);
// // Thread 0 maintains the "global" queue
// idi r = add_into_queue(
// set_L,
// base_set_L,
// local_queues_ends[num_threads_ - 1],
// L,
// cand);
// if (r < nk) {
// nk = r;
// }
// }
// }
// top_m_candidates_end = 0; // Clear top_m_candidates
// count_distance_computation_ += tmp_count_computation;
// tmp_count_computation = 0;
//
// if (nk <= last_k) {
// k = nk;
// } else {
// k = last_k + 1;
// }
//
// {// Scale M
// if (M < value_M_max) {
// M <<= 1;
// } else {
// M = value_M_max;
// }
// }
// }
// }
//
// // Multiple Threads
// {
//// while (k < L/num_threads_/2) {
//// while (k < L) {
// while (true) {
// ++tmp_count;
//// {//test
//// printf("tmp_count: %d\n", tmp_count);
//// }
//// // Select M candidates
//// idi last_k = L;
////// Cannot use OpenMP here because this for-loop needs early break by the 2nd condition.
//// for (idi c_i = k; c_i < L && top_m_candidates_end < M; ++c_i) {
//// idi index_set_L = c_i + base_set_L;
//// if (set_L[index_set_L].is_checked_) {
//// continue;
//// }
//// last_k = c_i; // Record the location of the last candidate selected.
//// set_L[index_set_L].is_checked_ = true;
//// top_m_candidates[top_m_candidates_end++] = set_L[index_set_L].id_;
//// }
//
// // Select M candidates
// {
// idi traverse_count = 0;
// idi bound_sub = L; // This is not always true!
// for (idi sub = 0; sub < bound_sub && top_m_candidates_end < M && traverse_count < L; ++sub) {
// for (int tid = 0; tid < num_threads_ && top_m_candidates_end < M && traverse_count < L; ++tid) {
// if (sub >= local_queues_ends[tid]) {
// continue;
// }
// idi index_set_L = tid * local_queue_length + sub;
// if (set_L[index_set_L].is_checked_) {
// continue;
// }
// set_L[index_set_L].is_checked_ = true;
// top_m_candidates[top_m_candidates_end++] = set_L[index_set_L].id_;
// }
// }
//
// if (0 == top_m_candidates_end) {
// break;
// }
// }
//
//// idi nk = L;
// // Push M candidates' neighbors into the queue.
////#pragma omp parallel for reduction(+ : tmp_count_computation) num_threads(real_threads)
//#pragma omp parallel for reduction(+ : tmp_count_computation)
// for (idi c_i = 0; c_i < top_m_candidates_end; ++c_i) {
// int tid = omp_get_thread_num();
// idi cand_id = top_m_candidates[c_i];
// _mm_prefetch(opt_nsg_graph_ + cand_id * vertex_bytes_ + data_bytes_, _MM_HINT_T0);
// idi *out_edges = (idi *) (opt_nsg_graph_ + cand_id * vertex_bytes_ + data_bytes_);
// idi out_degree = *out_edges++;
// for (idi n_i = 0; n_i < out_degree; ++n_i) {
// _mm_prefetch(opt_nsg_graph_ + out_edges[n_i] * vertex_bytes_, _MM_HINT_T0);
// }
// for (idi e_i = 0; e_i < out_degree; ++e_i) {
// idi nb_id = out_edges[e_i];
// { // Sequential edition
// if (is_visited[nb_id]) {
// continue;
// }
// is_visited[nb_id] = 1;
// }
//
// auto *nb_data = reinterpret_cast<dataf *>(opt_nsg_graph_ + nb_id * vertex_bytes_);
// dataf norm = *nb_data++;
//// ++count_distance_computation_;
// ++tmp_count_computation;
// distf dist = compute_distance_with_norm(nb_data, query_data, norm);
// if (dist > set_L[L - 1 + base_set_L].distance_) {
// continue;
// }
//
// Candidate cand(nb_id, dist, false);
// // Add to the local queue.
// if (0 != tid) {
// // Non-Master threads using local queues
// add_into_queue(
// set_L,
// (tid - 1) * local_queue_length,
// local_queues_ends[tid - 1],
// local_queue_length,
// cand);
// } else {
// // Thread 0 maintains the "global" queue
//// idi r =
// add_into_queue(
// set_L,
// base_set_L,
// local_queues_ends[num_threads_ - 1],
// L,
// cand);
//// if (r < nk) {
//// nk = r;
//// }
// }
// }
// }
// top_m_candidates_end = 0; // Clear top_m_candidates
// count_distance_computation_ += tmp_count_computation;
// tmp_count_computation = 0;
//
//// // Merge. Merge all queues in parallel.
// {
// time_merge_ -= WallTimer::get_time_mark();
// if (num_threads_ > 1) {
//// idi r = merge_all_queues_queue_base(
//// set_L,
//// local_queues_ends,
//// queue_base,
//// real_threads,
//// local_queue_length,
//// L);
//// idi r =
// merge_all_queues_para_array(
// set_L,
// local_queues_ends,
// local_queue_length,
// L);
//// if (r < nk) {
//// nk = r;
//// }
// }
// time_merge_ += WallTimer::get_time_mark();
// }
//// if (nk <= last_k) {
//// k = nk;
//// } else {
//// k = last_k + 1;
//// }
// {// Scale M
// if (M < value_M_max) {
// M <<= 1;
// } else {
// M = value_M_max;
// }
// }
// }
// }
//
//
////#pragma omp parallel for
//// for (idi k_i = 0; k_i < K; ++k_i) {
//// set_K[k_i] = set_L[k_i + base_set_L].id_;
////// set_K[k_i] = set_L[k_i].id_;
//// }
//
// {
// idi k_i = 0;
// idi bound_sub = K / num_threads_;
// for (idi sub = 0; sub < bound_sub; ++sub) {
// for (int tid = 0; tid < num_threads_; ++tid) {
// idi index_set_L = tid * local_queue_length + sub;
// set_K[k_i++] = set_L[index_set_L].id_;
// }
// }
// idi remain = K - k_i;
// if (remain) {
// for (int tid = 0; tid < remain; ++tid) {
// idi index_set_L = tid * local_queue_length + bound_sub;
// set_K[k_i++] = set_L[index_set_L].id_;
// }
// }
// }
//
// {// Reset
//// std::fill(is_visited.begin(), is_visited.end(), 0);
// is_visited.reset();
//// is_visited.clear_all();
// std::fill(local_queues_ends.begin(), local_queues_ends.end(), 0);
// }
//
//// {//test
//// printf("tmp_count: %u\n", tmp_count);
//// if (3 == query_id) {
//// exit(1);
//// }
//// }
//}
} // namespace PANNS
#endif //BATCH_SEARCHING_SEARCHING_H
|
Example_tasking.7.c | /*
* @@name: tasking.7c
* @@type: C
* @@compilable: yes
* @@linkable: no
* @@expect: success
* @@version: omp_3.0
*/
int tp;
#pragma omp threadprivate(tp)
int var;
void work()
{
#pragma omp task
{
/* do work here */
#pragma omp task
{
tp = 1;
/* do work here */
#pragma omp task
{
/* no modification of tp */
}
var = tp; //value of tp can be 1 or 2
}
tp = 2;
}
}
|
3d7pt_var.lbpar.c | #include <omp.h>
#include <math.h>
#define ceild(n,d) ceil(((double)(n))/((double)(d)))
#define floord(n,d) floor(((double)(n))/((double)(d)))
#define max(x,y) ((x) > (y)? (x) : (y))
#define min(x,y) ((x) < (y)? (x) : (y))
/*
* Order-1, 3D 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] = 16;
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
/* Copyright (C) 1991-2014 Free Software Foundation, Inc.
This file is part of the GNU C Library.
The GNU C Library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
The GNU C Library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with the GNU C Library; if not, see
<http://www.gnu.org/licenses/>. */
/* This header is separate from features.h so that the compiler can
include it implicitly at the start of every compilation. It must
not itself include <features.h> or any other header that includes
<features.h> because the implicit include comes before any feature
test macros that may be defined in a source file before it first
explicitly includes a system header. GCC knows the name of this
header in order to preinclude it. */
/* glibc's intent is to support the IEC 559 math functionality, real
and complex. If the GCC (4.9 and later) predefined macros
specifying compiler intent are available, use them to determine
whether the overall intent is to support these features; otherwise,
presume an older compiler has intent to support these features and
define these macros by default. */
/* wchar_t uses ISO/IEC 10646 (2nd ed., published 2011-03-15) /
Unicode 6.0. */
/* We do not support C11 <threads.h>. */
int t1, t2, t3, t4, t5, t6, t7, t8;
int lb, ub, lbp, ubp, lb2, ub2;
register int lbv, ubv;
/* Start of CLooG code */
if ((Nt >= 2) && (Nx >= 3) && (Ny >= 3) && (Nz >= 3)) {
for (t1=-1;t1<=floord(Nt-2,12);t1++) {
lbp=max(ceild(t1,2),ceild(24*t1-Nt+3,24));
ubp=min(floord(Nt+Nz-4,24),floord(12*t1+Nz+9,24));
#pragma omp parallel for private(lbv,ubv,t3,t4,t5,t6,t7,t8)
for (t2=lbp;t2<=ubp;t2++) {
for (t3=max(max(0,ceild(3*t1-3,4)),ceild(24*t2-Nz-12,16));t3<=min(min(min(floord(Nt+Ny-4,16),floord(12*t1+Ny+21,16)),floord(24*t2+Ny+20,16)),floord(24*t1-24*t2+Nz+Ny+19,16));t3++) {
for (t4=max(max(max(0,ceild(3*t1-255,256)),ceild(24*t2-Nz-1020,1024)),ceild(16*t3-Ny-1020,1024));t4<=min(min(min(min(floord(Nt+Nx-4,1024),floord(12*t1+Nx+21,1024)),floord(24*t2+Nx+20,1024)),floord(16*t3+Nx+12,1024)),floord(24*t1-24*t2+Nz+Nx+19,1024));t4++) {
for (t5=max(max(max(max(max(0,12*t1),24*t1-24*t2+1),24*t2-Nz+2),16*t3-Ny+2),1024*t4-Nx+2);t5<=min(min(min(min(min(Nt-2,12*t1+23),24*t2+22),16*t3+14),1024*t4+1022),24*t1-24*t2+Nz+21);t5++) {
for (t6=max(max(24*t2,t5+1),-24*t1+24*t2+2*t5-23);t6<=min(min(24*t2+23,-24*t1+24*t2+2*t5),t5+Nz-2);t6++) {
for (t7=max(16*t3,t5+1);t7<=min(16*t3+15,t5+Ny-2);t7++) {
lbv=max(1024*t4,t5+1);
ubv=min(1024*t4+1023,t5+Nx-2);
#pragma ivdep
#pragma vector always
for (t8=lbv;t8<=ubv;t8++) {
A[( t5 + 1) % 2][ (-t5+t6)][ (-t5+t7)][ (-t5+t8)] = (((((((coef[0][ (-t5+t6)][ (-t5+t7)][ (-t5+t8)] * A[ t5 % 2][ (-t5+t6)][ (-t5+t7)][ (-t5+t8)]) + (coef[1][ (-t5+t6)][ (-t5+t7)][ (-t5+t8)] * A[ t5 % 2][ (-t5+t6) - 1][ (-t5+t7)][ (-t5+t8)])) + (coef[2][ (-t5+t6)][ (-t5+t7)][ (-t5+t8)] * A[ t5 % 2][ (-t5+t6)][ (-t5+t7) - 1][ (-t5+t8)])) + (coef[3][ (-t5+t6)][ (-t5+t7)][ (-t5+t8)] * A[ t5 % 2][ (-t5+t6)][ (-t5+t7)][ (-t5+t8) - 1])) + (coef[4][ (-t5+t6)][ (-t5+t7)][ (-t5+t8)] * A[ t5 % 2][ (-t5+t6) + 1][ (-t5+t7)][ (-t5+t8)])) + (coef[5][ (-t5+t6)][ (-t5+t7)][ (-t5+t8)] * A[ t5 % 2][ (-t5+t6)][ (-t5+t7) + 1][ (-t5+t8)])) + (coef[6][ (-t5+t6)][ (-t5+t7)][ (-t5+t8)] * A[ t5 % 2][ (-t5+t6)][ (-t5+t7)][ (-t5+t8) + 1]));;
}
}
}
}
}
}
}
}
}
/* End of CLooG code */
gettimeofday(&end, 0);
ts_return = timeval_subtract(&result, &end, &start);
tdiff = (double) (result.tv_sec + result.tv_usec * 1.0e-6);
min_tdiff = min(min_tdiff, tdiff);
printf("Rank 0 TEST# %d time: %f\n", test, tdiff);
}
PRINT_RESULTS(1, "variable no-symmetry")
#ifdef LIKWID_PERFMON
#pragma omp parallel
{
LIKWID_MARKER_STOP("calc");
}
LIKWID_MARKER_CLOSE;
#endif
// Free allocated arrays
for(i=0; i<Nz; i++){
for(j=0;j<Ny;j++){
free(A[0][i][j]);
free(A[1][i][j]);
}
free(A[0][i]);
free(A[1][i]);
}
free(A[0]);
free(A[1]);
for(m=0; m<7;m++){
for(i=0; i<Nz; i++){
for(j=0;j<Ny;j++){
free(coef[m][i][j]);
}
free(coef[m][i]);
}
free(coef[m]);
}
return 0;
}
|
GB_unaryop__abs_uint64_uint64.c | //------------------------------------------------------------------------------
// GB_unaryop: hard-coded functions for each built-in unary operator
//------------------------------------------------------------------------------
// SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2019, All Rights Reserved.
// http://suitesparse.com See GraphBLAS/Doc/License.txt for license.
//------------------------------------------------------------------------------
// If this file is in the Generated/ folder, do not edit it (auto-generated).
#include "GB.h"
#ifndef GBCOMPACT
#include "GB_control.h"
#include "GB_iterator.h"
#include "GB_unaryop__include.h"
// C=unop(A) is defined by the following types and operators:
// op(A) function: GB_unop__abs_uint64_uint64
// op(A') function: GB_tran__abs_uint64_uint64
// C type: uint64_t
// A type: uint64_t
// cast: uint64_t cij = (uint64_t) aij
// unaryop: cij = aij
#define GB_ATYPE \
uint64_t
#define GB_CTYPE \
uint64_t
// aij = Ax [pA]
#define GB_GETA(aij,Ax,pA) \
uint64_t aij = Ax [pA]
#define GB_CX(p) Cx [p]
// unary operator
#define GB_OP(z, x) \
z = x ;
// casting
#define GB_CASTING(z, x) \
uint64_t z = (uint64_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_UINT64)
//------------------------------------------------------------------------------
// Cx = op (cast (Ax)): apply a unary operator
//------------------------------------------------------------------------------
GrB_Info GB_unop__abs_uint64_uint64
(
uint64_t *restrict Cx,
const uint64_t *restrict Ax,
int64_t anz,
int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
#pragma omp parallel for num_threads(nthreads) schedule(static)
for (int64_t p = 0 ; p < anz ; p++)
{
GB_CAST_OP (p, p) ;
}
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// C = op (cast (A')): transpose, typecast, and apply a unary operator
//------------------------------------------------------------------------------
GrB_Info GB_tran__abs_uint64_uint64
(
GrB_Matrix C,
const GrB_Matrix A,
int64_t **Rowcounts,
GBI_single_iterator Iter,
const int64_t *restrict A_slice,
int naslice
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
#define GB_PHASE_2_OF_2
#include "GB_unaryop_transpose.c"
return (GrB_SUCCESS) ;
#endif
}
#endif
|
convolution_sgemm_packn_fp16s.h | // Tencent is pleased to support the open source community by making ncnn available.
//
// Copyright (C) 2021 THL A29 Limited, a Tencent company. All rights reserved.
//
// Licensed under the BSD 3-Clause License (the "License"); you may not use this file except
// in compliance with the License. You may obtain a copy of the License at
//
// https://opensource.org/licenses/BSD-3-Clause
//
// Unless required by applicable law or agreed to in writing, software distributed
// under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
// CONDITIONS OF ANY KIND, either express or implied. See the License for the
// specific language governing permissions and limitations under the License.
static void im2col_sgemm_packn_fp16sa_rvv(const Mat& bottom_im2col, Mat& top_blob, const Mat& kernel, const Mat& _bias, const Option& opt)
{
const int packn = csrr_vlenb() / 2;
const word_type vl = vsetvl_e16m1(packn);
// Mat bottom_im2col(size, maxk, inch, 2u * packn, packn, opt.workspace_allocator);
const int size = bottom_im2col.w;
const int maxk = bottom_im2col.h;
const int inch = bottom_im2col.c;
const int outch = top_blob.c;
const __fp16* bias = _bias;
// permute
Mat tmp;
if (size >= 8)
tmp.create(8 * maxk, inch, size / 8 + (size % 8) / 4 + (size % 4) / 2 + size % 2, 2u * packn, packn, opt.workspace_allocator);
else if (size >= 4)
tmp.create(4 * maxk, inch, size / 4 + (size % 4) / 2 + size % 2, 2u * packn, packn, opt.workspace_allocator);
else if (size >= 2)
tmp.create(2 * maxk, inch, size / 2 + size % 2, 2u * packn, packn, opt.workspace_allocator);
else
tmp.create(maxk, inch, size, 2u * packn, packn, opt.workspace_allocator);
{
int remain_size_start = 0;
int nn_size = size >> 3;
#pragma omp parallel for num_threads(opt.num_threads)
for (int ii = 0; ii < nn_size; ii++)
{
int i = remain_size_start + ii * 8;
__fp16* tmpptr = tmp.channel(i / 8);
for (int q = 0; q < inch; q++)
{
const __fp16* img0 = (const __fp16*)bottom_im2col.channel(q) + i * packn;
for (int k = 0; k < maxk; k++)
{
#if RVV_SPEC_0_7
asm volatile(
"mv t3, %[LEN] \n\t"
"mv t1, %[SRC] \n\t"
"mv t2, %[TMP] \n\t"
"slli t3, t3, 1 \n\t"
"vle.v v0, (t1) \n\t"
"add t1, t1, t3 \n\t"
"vle.v v1, (t1) \n\t"
"add t1, t1, t3 \n\t"
"vle.v v2, (t1) \n\t"
"add t1, t1, t3 \n\t"
"vle.v v3, (t1) \n\t"
"add t1, t1, t3 \n\t"
"vle.v v4, (t1) \n\t"
"add t1, t1, t3 \n\t"
"vle.v v5, (t1) \n\t"
"add t1, t1, t3 \n\t"
"vle.v v6, (t1) \n\t"
"add t1, t1, t3 \n\t"
"vle.v v7, (t1) \n\t"
"add t1, t1, t3 \n\t"
"vsseg8e.v v0, (t2) \n\t"
:
: [LEN] "r"(packn), [SRC] "r"(img0), [TMP] "r"(tmpptr)
: "cc", "memory", "v0", "v1", "v2", "v3", "v4", "v5", "v6", "v7", "t1", "t2", "t3");
img0 += size * packn;
tmpptr += packn * 8;
#else
vfloat16m1_t _val0 = vle16_v_f16m1(img0, vl);
vfloat16m1_t _val1 = vle16_v_f16m1(img0 + packn, vl);
vfloat16m1_t _val2 = vle16_v_f16m1(img0 + packn * 2, vl);
vfloat16m1_t _val3 = vle16_v_f16m1(img0 + packn * 3, vl);
vfloat16m1_t _val4 = vle16_v_f16m1(img0 + packn * 4, vl);
vfloat16m1_t _val5 = vle16_v_f16m1(img0 + packn * 5, vl);
vfloat16m1_t _val6 = vle16_v_f16m1(img0 + packn * 6, vl);
vfloat16m1_t _val7 = vle16_v_f16m1(img0 + packn * 7, vl);
vsseg8e16_v_f16m1x8(tmpptr, vcreate_f16m1x8(_val0, _val1, _val2, _val3, _val4, _val5, _val6, _val7), vl);
img0 += size * packn;
tmpptr += packn * 8;
#endif
}
}
}
remain_size_start += nn_size << 3;
nn_size = (size - remain_size_start) >> 2;
#pragma omp parallel for num_threads(opt.num_threads)
for (int ii = 0; ii < nn_size; ii++)
{
int i = remain_size_start + ii * 4;
__fp16* tmpptr = tmp.channel(i / 8 + (i % 8) / 4);
for (int q = 0; q < inch; q++)
{
const __fp16* img0 = (const __fp16*)bottom_im2col.channel(q) + i * packn;
for (int k = 0; k < maxk; k++)
{
#if RVV_SPEC_0_7
asm volatile(
"mv t3, %[LEN] \n\t"
"mv t1, %[SRC] \n\t"
"mv t2, %[TMP] \n\t"
"slli t3, t3, 1 \n\t"
"vle.v v0, (t1) \n\t"
"add t1, t1, t3 \n\t"
"vle.v v1, (t1) \n\t"
"add t1, t1, t3 \n\t"
"vle.v v2, (t1) \n\t"
"add t1, t1, t3 \n\t"
"vle.v v3, (t1) \n\t"
"vsseg4e.v v0, (t2) \n\t"
:
: [LEN] "r"(packn), [SRC] "r"(img0), [TMP] "r"(tmpptr)
: "cc", "memory", "v0", "v1", "v2", "v3", "t1", "t2", "t3");
img0 += size * packn;
tmpptr += packn * 4;
#else
vfloat16m1_t _val0 = vle16_v_f16m1(img0, vl);
vfloat16m1_t _val1 = vle16_v_f16m1(img0 + packn, vl);
vfloat16m1_t _val2 = vle16_v_f16m1(img0 + packn * 2, vl);
vfloat16m1_t _val3 = vle16_v_f16m1(img0 + packn * 3, vl);
vsseg4e16_v_f16m1x4(tmpptr, vcreate_f16m1x4(_val0, _val1, _val2, _val3), vl);
img0 += size * packn;
tmpptr += packn * 4;
#endif
}
}
}
remain_size_start += nn_size << 2;
nn_size = (size - remain_size_start) >> 1;
#pragma omp parallel for num_threads(opt.num_threads)
for (int ii = 0; ii < nn_size; ii++)
{
int i = remain_size_start + ii * 2;
__fp16* tmpptr = tmp.channel(i / 8 + (i % 8) / 4 + (i % 4) / 2);
for (int q = 0; q < inch; q++)
{
const __fp16* img0 = (const __fp16*)bottom_im2col.channel(q) + i * packn;
for (int k = 0; k < maxk; k++)
{
#if RVV_SPEC_0_7
asm volatile(
"mv t3, %[LEN] \n\t"
"mv t1, %[SRC] \n\t"
"mv t2, %[TMP] \n\t"
"slli t3, t3, 1 \n\t"
"vle.v v0, (t1) \n\t"
"add t1, t1, t3 \n\t"
"vle.v v1, (t1) \n\t"
"add t1, t1, t3 \n\t"
:
: [LEN] "r"(packn), [SRC] "r"(img0), [TMP] "r"(tmpptr)
: "cc", "memory", "v0", "v1", "t1", "t2", "t3");
img0 += size * packn;
tmpptr += packn * 2;
#else
vfloat16m1_t _val0 = vle16_v_f16m1(img0, vl);
vfloat16m1_t _val1 = vle16_v_f16m1(img0 + packn, vl);
vsseg2e16_v_f16m1x2(tmpptr, vcreate_f16m1x2(_val0, _val1), vl);
img0 += size * packn;
tmpptr += packn * 2;
#endif
}
}
}
remain_size_start += nn_size << 1;
#pragma omp parallel for num_threads(opt.num_threads)
for (int i = remain_size_start; i < size; i++)
{
__fp16* tmpptr = tmp.channel(i / 8 + (i % 8) / 4 + (i % 4) / 2 + i % 2);
for (int q = 0; q < inch; q++)
{
const __fp16* img0 = (const __fp16*)bottom_im2col.channel(q) + i * packn;
for (int k = 0; k < maxk; k++)
{
vfloat16m1_t _val = vle16_v_f16m1(img0, vl);
vse16_v_f16m1(tmpptr, _val, vl);
img0 += size * packn;
tmpptr += packn;
}
}
}
}
#pragma omp parallel for num_threads(opt.num_threads)
for (int p = 0; p < outch; p++)
{
__fp16* outptr0 = top_blob.channel(p);
int i = 0;
for (; i + 7 < size; i += 8)
{
const __fp16* tmpptr = tmp.channel(i / 8);
const __fp16* kptr0 = kernel.channel(p);
int nn = inch * maxk * packn; // inch always > 0
vfloat16m1_t _sum0 = vfmv_v_f_f16m1(0.f, vl);
vfloat16m1_t _sum1 = vfmv_v_f_f16m1(0.f, vl);
vfloat16m1_t _sum2 = vfmv_v_f_f16m1(0.f, vl);
vfloat16m1_t _sum3 = vfmv_v_f_f16m1(0.f, vl);
vfloat16m1_t _sum4 = vfmv_v_f_f16m1(0.f, vl);
vfloat16m1_t _sum5 = vfmv_v_f_f16m1(0.f, vl);
vfloat16m1_t _sum6 = vfmv_v_f_f16m1(0.f, vl);
vfloat16m1_t _sum7 = vfmv_v_f_f16m1(0.f, vl);
if (bias)
{
_sum0 = vle16_v_f16m1(bias + p * packn, vl);
_sum1 = vle16_v_f16m1(bias + p * packn, vl);
_sum2 = vle16_v_f16m1(bias + p * packn, vl);
_sum3 = vle16_v_f16m1(bias + p * packn, vl);
_sum4 = vle16_v_f16m1(bias + p * packn, vl);
_sum5 = vle16_v_f16m1(bias + p * packn, vl);
_sum6 = vle16_v_f16m1(bias + p * packn, vl);
_sum7 = vle16_v_f16m1(bias + p * packn, vl);
}
for (int j = 0; j < nn; j++)
{
__fp16 val0 = *tmpptr++;
__fp16 val1 = *tmpptr++;
__fp16 val2 = *tmpptr++;
__fp16 val3 = *tmpptr++;
__fp16 val4 = *tmpptr++;
__fp16 val5 = *tmpptr++;
__fp16 val6 = *tmpptr++;
__fp16 val7 = *tmpptr++;
vfloat16m1_t _w0 = vle16_v_f16m1(kptr0, vl);
_sum0 = vfmacc_vf_f16m1(_sum0, val0, _w0, vl);
_sum1 = vfmacc_vf_f16m1(_sum1, val1, _w0, vl);
_sum2 = vfmacc_vf_f16m1(_sum2, val2, _w0, vl);
_sum3 = vfmacc_vf_f16m1(_sum3, val3, _w0, vl);
_sum4 = vfmacc_vf_f16m1(_sum4, val4, _w0, vl);
_sum5 = vfmacc_vf_f16m1(_sum5, val5, _w0, vl);
_sum6 = vfmacc_vf_f16m1(_sum6, val6, _w0, vl);
_sum7 = vfmacc_vf_f16m1(_sum7, val7, _w0, vl);
kptr0 += packn;
}
vse16_v_f16m1(outptr0, _sum0, vl);
vse16_v_f16m1(outptr0 + packn, _sum1, vl);
vse16_v_f16m1(outptr0 + packn * 2, _sum2, vl);
vse16_v_f16m1(outptr0 + packn * 3, _sum3, vl);
vse16_v_f16m1(outptr0 + packn * 4, _sum4, vl);
vse16_v_f16m1(outptr0 + packn * 5, _sum5, vl);
vse16_v_f16m1(outptr0 + packn * 6, _sum6, vl);
vse16_v_f16m1(outptr0 + packn * 7, _sum7, vl);
outptr0 += packn * 8;
}
for (; i + 3 < size; i += 4)
{
const __fp16* tmpptr = tmp.channel(i / 8 + (i % 8) / 4);
const __fp16* kptr0 = kernel.channel(p);
int nn = inch * maxk * packn; // inch always > 0
vfloat16m1_t _sum0 = vfmv_v_f_f16m1(0.f, vl);
vfloat16m1_t _sum1 = vfmv_v_f_f16m1(0.f, vl);
vfloat16m1_t _sum2 = vfmv_v_f_f16m1(0.f, vl);
vfloat16m1_t _sum3 = vfmv_v_f_f16m1(0.f, vl);
if (bias)
{
_sum0 = vle16_v_f16m1(bias + p * packn, vl);
_sum1 = vle16_v_f16m1(bias + p * packn, vl);
_sum2 = vle16_v_f16m1(bias + p * packn, vl);
_sum3 = vle16_v_f16m1(bias + p * packn, vl);
}
for (int j = 0; j < nn; j++)
{
__fp16 val0 = *tmpptr++;
__fp16 val1 = *tmpptr++;
__fp16 val2 = *tmpptr++;
__fp16 val3 = *tmpptr++;
vfloat16m1_t _w0 = vle16_v_f16m1(kptr0, vl);
_sum0 = vfmacc_vf_f16m1(_sum0, val0, _w0, vl);
_sum1 = vfmacc_vf_f16m1(_sum1, val1, _w0, vl);
_sum2 = vfmacc_vf_f16m1(_sum2, val2, _w0, vl);
_sum3 = vfmacc_vf_f16m1(_sum3, val3, _w0, vl);
kptr0 += packn;
}
vse16_v_f16m1(outptr0, _sum0, vl);
vse16_v_f16m1(outptr0 + packn, _sum1, vl);
vse16_v_f16m1(outptr0 + packn * 2, _sum2, vl);
vse16_v_f16m1(outptr0 + packn * 3, _sum3, vl);
outptr0 += packn * 4;
}
for (; i + 1 < size; i += 2)
{
const __fp16* tmpptr = tmp.channel(i / 8 + (i % 8) / 4 + (i % 4) / 2);
const __fp16* kptr0 = kernel.channel(p);
int nn = inch * maxk * packn; // inch always > 0
vfloat16m1_t _sum0 = vfmv_v_f_f16m1(0.f, vl);
vfloat16m1_t _sum1 = vfmv_v_f_f16m1(0.f, vl);
if (bias)
{
_sum0 = vle16_v_f16m1(bias + p * packn, vl);
_sum1 = vle16_v_f16m1(bias + p * packn, vl);
}
for (int j = 0; j < nn; j++)
{
__fp16 val0 = *tmpptr++;
__fp16 val1 = *tmpptr++;
vfloat16m1_t _w0 = vle16_v_f16m1(kptr0, vl);
_sum0 = vfmacc_vf_f16m1(_sum0, val0, _w0, vl);
_sum1 = vfmacc_vf_f16m1(_sum1, val1, _w0, vl);
kptr0 += packn;
}
vse16_v_f16m1(outptr0, _sum0, vl);
vse16_v_f16m1(outptr0 + packn, _sum1, vl);
outptr0 += packn * 2;
}
for (; i < size; i++)
{
const __fp16* tmpptr = tmp.channel(i / 8 + (i % 8) / 4 + (i % 4) / 2 + i % 2);
const __fp16* kptr0 = kernel.channel(p);
int nn = inch * maxk * packn; // inch always > 0
vfloat16m1_t _sum = vfmv_v_f_f16m1(0.f, vl);
if (bias)
{
_sum = vle16_v_f16m1(bias + p * packn, vl);
}
for (int j = 0; j < nn; j++)
{
__fp16 val = *tmpptr++;
vfloat16m1_t _w0 = vle16_v_f16m1(kptr0, vl);
_sum = vfmacc_vf_f16m1(_sum, val, _w0, vl);
kptr0 += packn;
}
vse16_v_f16m1(outptr0, _sum, vl);
outptr0 += packn;
}
}
}
static void convolution_im2col_sgemm_packn_fp16sa_rvv(const Mat& bottom_blob, Mat& top_blob, const Mat& kernel, const Mat& _bias, int kernel_w, int kernel_h, int dilation_w, int dilation_h, int stride_w, int stride_h, const Option& opt)
{
const int packn = csrr_vlenb() / 2;
const word_type vl = vsetvl_e16m1(packn);
int w = bottom_blob.w;
int inch = bottom_blob.c;
int outw = top_blob.w;
int outh = top_blob.h;
const int size = outw * outh;
const int maxk = kernel_w * kernel_h;
// im2col
Mat bottom_im2col(size, maxk, inch, 2u * packn, packn, opt.workspace_allocator);
{
const int gap = (w * stride_h - outw * stride_w) * packn;
#pragma omp parallel for num_threads(opt.num_threads)
for (int p = 0; p < inch; p++)
{
const Mat img = bottom_blob.channel(p);
__fp16* ptr = bottom_im2col.channel(p);
for (int u = 0; u < kernel_h; u++)
{
for (int v = 0; v < kernel_w; v++)
{
const __fp16* sptr = img.row<const __fp16>(dilation_h * u) + dilation_w * v * packn;
for (int i = 0; i < outh; i++)
{
int j = 0;
for (; j < outw; j++)
{
vfloat16m1_t _val = vle16_v_f16m1(sptr, vl);
vse16_v_f16m1(ptr, _val, vl);
sptr += stride_w * packn;
ptr += packn;
}
sptr += gap;
}
}
}
}
}
im2col_sgemm_packn_fp16sa_rvv(bottom_im2col, top_blob, kernel, _bias, opt);
}
|
DRB084-threadprivatemissing-orig-yes.c | /*
Copyright (c) 2017, Lawrence Livermore National Security, LLC.
Produced at the Lawrence Livermore National Laboratory
Written by Chunhua Liao, Pei-Hung Lin, Joshua Asplund,
Markus Schordan, and Ian Karlin
(email: liao6@llnl.gov, lin32@llnl.gov, asplund1@llnl.gov,
schordan1@llnl.gov, karlin1@llnl.gov)
LLNL-CODE-732144
All rights reserved.
This file is part of DataRaceBench. For details, see
https://github.com/LLNL/dataracebench. Please also see the LICENSE file
for our additional BSD notice.
Redistribution and use in source and binary forms, with
or without modification, are permitted provided that the following
conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the disclaimer below.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the disclaimer (as noted below)
in the documentation and/or other materials provided with the
distribution.
* Neither the name of the LLNS/LLNL nor the names of its contributors
may be used to endorse or promote products derived from this
software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL LAWRENCE LIVERMORE NATIONAL
SECURITY, LLC, THE U.S. DEPARTMENT OF ENERGY OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
THE POSSIBILITY OF SUCH DAMAGE.
*/
/*
A file-scope variable used within a function called by a parallel region.
No threadprivate is used to avoid data races.
Data race pairs sum0@61:3 vs. sum0@61:8
sum0@61:3 vs. sum0@61:3
*/
#include <stdio.h>
#include <assert.h>
int sum0=0, sum1=0;
//#pragma omp threadprivate(sum0)
void foo (int i)
{
sum0=sum0+i;
}
int main()
{
int i, sum=0;
#pragma omp parallel
{
#pragma omp for
for (i=1;i<=1000;i++)
{
foo (i);
}
#pragma omp critical
{
sum= sum+sum0;
}
}
/* reference calculation */
for (i=1;i<=1000;i++)
{
sum1=sum1+i;
}
printf("sum=%d; sum1=%d\n",sum,sum1);
// assert(sum==sum1);
return 0;
}
|
GB_binop__bor_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 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__bor_uint8)
// A.*B function (eWiseMult): GB (_AemultB_08__bor_uint8)
// A.*B function (eWiseMult): GB (_AemultB_02__bor_uint8)
// A.*B function (eWiseMult): GB (_AemultB_04__bor_uint8)
// A.*B function (eWiseMult): GB (_AemultB_bitmap__bor_uint8)
// A*D function (colscale): GB (_AxD__bor_uint8)
// D*A function (rowscale): GB (_DxB__bor_uint8)
// C+=B function (dense accum): GB (_Cdense_accumB__bor_uint8)
// C+=b function (dense accum): GB (_Cdense_accumb__bor_uint8)
// C+=A+B function (dense ewise3): GB ((none))
// C=A+B function (dense ewise3): GB (_Cdense_ewise3_noaccum__bor_uint8)
// C=scalar+B GB (_bind1st__bor_uint8)
// C=scalar+B' GB (_bind1st_tran__bor_uint8)
// C=A+scalar GB (_bind2nd__bor_uint8)
// C=A'+scalar GB (_bind2nd_tran__bor_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,A_iso) \
uint8_t aij = GBX (Ax, pA, A_iso)
// bij = Bx [pB]
#define GB_GETB(bij,Bx,pB,B_iso) \
uint8_t bij = GBX (Bx, pB, B_iso)
// 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,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_BOR || GxB_NO_UINT8 || GxB_NO_BOR_UINT8)
//------------------------------------------------------------------------------
// C += A+B, all 3 matrices dense
//------------------------------------------------------------------------------
#if 0
// The op must be MIN, MAX, PLUS, MINUS, RMINUS, TIMES, DIV, or RDIV.
void GB ((none))
(
GrB_Matrix C,
const GrB_Matrix A,
const GrB_Matrix B,
const int nthreads
)
{
#include "GB_dense_ewise3_accum_template.c"
}
#endif
//------------------------------------------------------------------------------
// C = A+B, all 3 matrices dense
//------------------------------------------------------------------------------
GrB_Info GB (_Cdense_ewise3_noaccum__bor_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__bor_uint8)
(
GrB_Matrix C,
const GrB_Matrix B,
const int64_t *B_ek_slicing, const int B_ntasks, const int B_nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
{
#include "GB_dense_subassign_23_template.c"
}
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// C += b, accumulate a scalar into a dense matrix
//------------------------------------------------------------------------------
GrB_Info GB (_Cdense_accumb__bor_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__bor_uint8)
(
GrB_Matrix C,
const GrB_Matrix A, bool A_is_pattern,
const GrB_Matrix D, bool D_is_pattern,
const int64_t *A_ek_slicing, const int A_ntasks, const int A_nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
uint8_t *restrict Cx = (uint8_t *) C->x ;
#include "GB_AxB_colscale_template.c"
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// C = D*B, row scale with diagonal D matrix
//------------------------------------------------------------------------------
GrB_Info GB (_DxB__bor_uint8)
(
GrB_Matrix C,
const GrB_Matrix D, bool D_is_pattern,
const GrB_Matrix B, bool B_is_pattern,
int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
uint8_t *restrict Cx = (uint8_t *) C->x ;
#include "GB_AxB_rowscale_template.c"
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// eWiseAdd: C=A+B, C<M>=A+B, C<!M>=A+B
//------------------------------------------------------------------------------
GrB_Info GB (_AaddB__bor_uint8)
(
GrB_Matrix C,
const int C_sparsity,
const GrB_Matrix M,
const bool Mask_struct,
const bool Mask_comp,
const GrB_Matrix A,
const GrB_Matrix B,
const bool Ch_is_Mh,
const int64_t *restrict C_to_M,
const int64_t *restrict C_to_A,
const int64_t *restrict C_to_B,
const GB_task_struct *restrict TaskList,
const int C_ntasks,
const int C_nthreads,
GB_Context Context
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
GB_WERK_DECLARE (M_ek_slicing, int64_t) ;
GB_WERK_DECLARE (A_ek_slicing, int64_t) ;
GB_WERK_DECLARE (B_ek_slicing, int64_t) ;
#include "GB_add_template.c"
GB_FREE_WORK ;
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// eWiseMult: C=A.*B, C<M>=A.*B, or C<M!>=A.*B where C is sparse/hyper
//------------------------------------------------------------------------------
GrB_Info GB (_AemultB_08__bor_uint8)
(
GrB_Matrix C,
const int C_sparsity,
const int ewise_method,
const GrB_Matrix M,
const bool Mask_struct,
const bool Mask_comp,
const GrB_Matrix A,
const GrB_Matrix B,
const int64_t *restrict C_to_M,
const int64_t *restrict C_to_A,
const int64_t *restrict C_to_B,
const GB_task_struct *restrict TaskList,
const int C_ntasks,
const int C_nthreads,
GB_Context Context
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
#include "GB_emult_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__bor_uint8)
(
GrB_Matrix C,
const GrB_Matrix M,
const bool Mask_struct,
const bool Mask_comp,
const GrB_Matrix A,
const GrB_Matrix B,
const bool flipxy,
const int64_t *restrict Cp_kfirst,
const int64_t *A_ek_slicing, const int A_ntasks, const int A_nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
#if GB_BINOP_FLIP
// The operator is not commutative, and does not have a flipped
// variant. For example z=atan2(y,x).
if (flipxy)
{
// use fmult(y,x)
#undef GB_FLIPPED
#define GB_FLIPPED 1
#include "GB_emult_02_template.c"
}
else
{
// use fmult(x,y)
#undef GB_FLIPPED
#define GB_FLIPPED 0
#include "GB_emult_02_template.c"
}
#else
// No need to handle the flip: the operator is either commutative, or
// has been handled by changing z=div(y,x) to z=rdiv(x,y) for example.
#undef GB_FLIPPED
#define GB_FLIPPED 0
#include "GB_emult_02_template.c"
#endif
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// eWiseMult: C<M> = A.*B, M sparse/hyper, A and B bitmap/full
//------------------------------------------------------------------------------
GrB_Info GB (_AemultB_04__bor_uint8)
(
GrB_Matrix C,
const GrB_Matrix M,
const bool Mask_struct,
const GrB_Matrix A,
const GrB_Matrix B,
const int64_t *restrict Cp_kfirst,
const int64_t *M_ek_slicing, const int M_ntasks, const int M_nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
#include "GB_emult_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__bor_uint8)
(
GrB_Matrix C,
const int ewise_method,
const GrB_Matrix M,
const bool Mask_struct,
const bool Mask_comp,
const GrB_Matrix A,
const GrB_Matrix B,
const int64_t *M_ek_slicing, const int M_ntasks, const int M_nthreads,
const int C_nthreads,
GB_Context Context
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
#include "GB_bitmap_emult_template.c"
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// Cx = op (x,Bx): apply a binary operator to a matrix with scalar bind1st
//------------------------------------------------------------------------------
GrB_Info GB (_bind1st__bor_uint8)
(
GB_void *Cx_output, // Cx and Bx may be aliased
const GB_void *x_input,
const GB_void *Bx_input,
const int8_t *restrict Bb,
int64_t bnz,
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 < bnz ; p++)
{
if (!GBB (Bb, p)) continue ;
uint8_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__bor_uint8)
(
GB_void *Cx_output, // Cx and Ax may be aliased
const GB_void *Ax_input,
const GB_void *y_input,
const int8_t *restrict Ab,
int64_t anz,
int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
int64_t p ;
uint8_t *Cx = (uint8_t *) Cx_output ;
uint8_t *Ax = (uint8_t *) Ax_input ;
uint8_t y = (*((uint8_t *) y_input)) ;
#pragma omp parallel for num_threads(nthreads) schedule(static)
for (p = 0 ; p < anz ; p++)
{
if (!GBB (Ab, p)) continue ;
uint8_t aij = 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) \
{ \
uint8_t aij = GBX (Ax, pA, false) ; \
Cx [pC] = (x) | (aij) ; \
}
GrB_Info GB (_bind1st_tran__bor_uint8)
(
GrB_Matrix C,
const GB_void *x_input,
const GrB_Matrix A,
int64_t *restrict *Workspaces,
const int64_t *restrict A_slice,
int nworkspaces,
int nthreads
)
{
// GB_unop_transpose.c uses GB_ATYPE, but A is
// the 2nd input to binary operator z=f(x,y).
#undef GB_ATYPE
#define GB_ATYPE \
uint8_t
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
uint8_t x = (*((const uint8_t *) x_input)) ;
#include "GB_unop_transpose.c"
return (GrB_SUCCESS) ;
#endif
#undef GB_ATYPE
#define GB_ATYPE \
uint8_t
}
//------------------------------------------------------------------------------
// C = op (A', y): transpose and apply a binary operator
//------------------------------------------------------------------------------
// cij = op (aij, y), no typecasting (in spite of the macro name)
#undef GB_CAST_OP
#define GB_CAST_OP(pC,pA) \
{ \
uint8_t aij = GBX (Ax, pA, false) ; \
Cx [pC] = (aij) | (y) ; \
}
GrB_Info GB (_bind2nd_tran__bor_uint8)
(
GrB_Matrix C,
const GrB_Matrix A,
const GB_void *y_input,
int64_t *restrict *Workspaces,
const int64_t *restrict A_slice,
int nworkspaces,
int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
uint8_t y = (*((const uint8_t *) y_input)) ;
#include "GB_unop_transpose.c"
return (GrB_SUCCESS) ;
#endif
}
#endif
|
rt_dlauum.c | #include "runtime.h"
void RT_CORE_dlauum(Quark *quark, Quark_Task_Flags *task_flags,
PLASMA_enum uplo, int n, int nb,
double *A, int lda)
{
plasma_context_t *plasma;
plasma = plasma_context_self();
if (plasma->runtime == PLASMA_QUARK) {
QUARK_CORE_dlauum(quark, task_flags,
uplo, n, nb, A, lda);
} else if (plasma->runtime == PLASMA_OMPSS) {
#pragma omp target device (smp) copy_deps
#pragma omp task inout([lda*n]A) label(dlauum)
CORE_dlauum_rt(uplo, n, A, lda);
}
}
void CORE_dlauum_rt(PLASMA_enum uplo, int n, double *A, int lda)
{
LAPACKE_dlauum_work(LAPACK_COL_MAJOR, lapack_const(uplo), n, A, lda);
}
|
fx.c | /*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% FFFFF X X %
% F X X %
% FFF X %
% F X X %
% F X X %
% %
% %
% MagickCore Image Special Effects Methods %
% %
% Software Design %
% Cristy %
% October 1996 %
% %
% %
% %
% Copyright 1999-2019 ImageMagick Studio LLC, a non-profit organization %
% dedicated to making software imaging solutions freely available. %
% %
% You may not use this file except in compliance with the License. You may %
% obtain a copy of the License at %
% %
% https://imagemagick.org/script/license.php %
% %
% Unless required by applicable law or agreed to in writing, software %
% distributed under the License is distributed on an "AS IS" BASIS, %
% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. %
% See the License for the specific language governing permissions and %
% limitations under the License. %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
%
%
*/
/*
Include declarations.
*/
#include "MagickCore/studio.h"
#include "MagickCore/accelerate-private.h"
#include "MagickCore/annotate.h"
#include "MagickCore/artifact.h"
#include "MagickCore/attribute.h"
#include "MagickCore/cache.h"
#include "MagickCore/cache-view.h"
#include "MagickCore/channel.h"
#include "MagickCore/color.h"
#include "MagickCore/color-private.h"
#include "MagickCore/colorspace-private.h"
#include "MagickCore/composite.h"
#include "MagickCore/decorate.h"
#include "MagickCore/distort.h"
#include "MagickCore/draw.h"
#include "MagickCore/effect.h"
#include "MagickCore/enhance.h"
#include "MagickCore/exception.h"
#include "MagickCore/exception-private.h"
#include "MagickCore/fx.h"
#include "MagickCore/fx-private.h"
#include "MagickCore/gem.h"
#include "MagickCore/gem-private.h"
#include "MagickCore/geometry.h"
#include "MagickCore/layer.h"
#include "MagickCore/list.h"
#include "MagickCore/log.h"
#include "MagickCore/image.h"
#include "MagickCore/image-private.h"
#include "MagickCore/magick.h"
#include "MagickCore/memory_.h"
#include "MagickCore/memory-private.h"
#include "MagickCore/monitor.h"
#include "MagickCore/monitor-private.h"
#include "MagickCore/option.h"
#include "MagickCore/pixel.h"
#include "MagickCore/pixel-accessor.h"
#include "MagickCore/property.h"
#include "MagickCore/quantum.h"
#include "MagickCore/quantum-private.h"
#include "MagickCore/random_.h"
#include "MagickCore/random-private.h"
#include "MagickCore/resample.h"
#include "MagickCore/resample-private.h"
#include "MagickCore/resize.h"
#include "MagickCore/resource_.h"
#include "MagickCore/splay-tree.h"
#include "MagickCore/statistic.h"
#include "MagickCore/string_.h"
#include "MagickCore/string-private.h"
#include "MagickCore/thread-private.h"
#include "MagickCore/threshold.h"
#include "MagickCore/transform.h"
#include "MagickCore/transform-private.h"
#include "MagickCore/utility.h"
/*
Define declarations.
*/
#define LeftShiftOperator 0xf5U
#define RightShiftOperator 0xf6U
#define LessThanEqualOperator 0xf7U
#define GreaterThanEqualOperator 0xf8U
#define EqualOperator 0xf9U
#define NotEqualOperator 0xfaU
#define LogicalAndOperator 0xfbU
#define LogicalOrOperator 0xfcU
#define ExponentialNotation 0xfdU
struct _FxInfo
{
const Image
*images;
char
*expression;
FILE
*file;
SplayTreeInfo
*colors,
*symbols;
CacheView
**view;
RandomInfo
*random_info;
ExceptionInfo
*exception;
};
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
+ A c q u i r e F x I n f o %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% AcquireFxInfo() allocates the FxInfo structure.
%
% The format of the AcquireFxInfo method is:
%
% FxInfo *AcquireFxInfo(Image *images,const char *expression,
% ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o images: the image sequence.
%
% o expression: the expression.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickPrivate FxInfo *AcquireFxInfo(const Image *images,const char *expression,
ExceptionInfo *exception)
{
char
fx_op[2];
const Image
*next;
FxInfo
*fx_info;
register ssize_t
i;
fx_info=(FxInfo *) AcquireCriticalMemory(sizeof(*fx_info));
(void) memset(fx_info,0,sizeof(*fx_info));
fx_info->exception=AcquireExceptionInfo();
fx_info->images=images;
fx_info->colors=NewSplayTree(CompareSplayTreeString,RelinquishMagickMemory,
RelinquishMagickMemory);
fx_info->symbols=NewSplayTree(CompareSplayTreeString,RelinquishMagickMemory,
RelinquishMagickMemory);
fx_info->view=(CacheView **) AcquireQuantumMemory(GetImageListLength(
fx_info->images),sizeof(*fx_info->view));
if (fx_info->view == (CacheView **) NULL)
ThrowFatalException(ResourceLimitFatalError,"MemoryAllocationFailed");
i=0;
next=GetFirstImageInList(fx_info->images);
for ( ; next != (Image *) NULL; next=next->next)
{
fx_info->view[i]=AcquireVirtualCacheView(next,exception);
i++;
}
fx_info->random_info=AcquireRandomInfo();
fx_info->expression=ConstantString(expression);
fx_info->file=stderr;
(void) SubstituteString(&fx_info->expression," ",""); /* compact string */
/*
Force right-to-left associativity for unary negation.
*/
(void) SubstituteString(&fx_info->expression,"-","-1.0*");
(void) SubstituteString(&fx_info->expression,"^-1.0*","^-");
(void) SubstituteString(&fx_info->expression,"E-1.0*","E-");
(void) SubstituteString(&fx_info->expression,"e-1.0*","e-");
/*
Convert compound to simple operators.
*/
fx_op[1]='\0';
*fx_op=(char) LeftShiftOperator;
(void) SubstituteString(&fx_info->expression,"<<",fx_op);
*fx_op=(char) RightShiftOperator;
(void) SubstituteString(&fx_info->expression,">>",fx_op);
*fx_op=(char) LessThanEqualOperator;
(void) SubstituteString(&fx_info->expression,"<=",fx_op);
*fx_op=(char) GreaterThanEqualOperator;
(void) SubstituteString(&fx_info->expression,">=",fx_op);
*fx_op=(char) EqualOperator;
(void) SubstituteString(&fx_info->expression,"==",fx_op);
*fx_op=(char) NotEqualOperator;
(void) SubstituteString(&fx_info->expression,"!=",fx_op);
*fx_op=(char) LogicalAndOperator;
(void) SubstituteString(&fx_info->expression,"&&",fx_op);
*fx_op=(char) LogicalOrOperator;
(void) SubstituteString(&fx_info->expression,"||",fx_op);
*fx_op=(char) ExponentialNotation;
(void) SubstituteString(&fx_info->expression,"**",fx_op);
return(fx_info);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% A d d N o i s e I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% AddNoiseImage() adds random noise to the image.
%
% The format of the AddNoiseImage method is:
%
% Image *AddNoiseImage(const Image *image,const NoiseType noise_type,
% const double attenuate,ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o channel: the channel type.
%
% o noise_type: The type of noise: Uniform, Gaussian, Multiplicative,
% Impulse, Laplacian, or Poisson.
%
% o attenuate: attenuate the random distribution.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport Image *AddNoiseImage(const Image *image,const NoiseType noise_type,
const double attenuate,ExceptionInfo *exception)
{
#define AddNoiseImageTag "AddNoise/Image"
CacheView
*image_view,
*noise_view;
Image
*noise_image;
MagickBooleanType
status;
MagickOffsetType
progress;
RandomInfo
**magick_restrict random_info;
ssize_t
y;
#if defined(MAGICKCORE_OPENMP_SUPPORT)
unsigned long
key;
#endif
/*
Initialize noise image attributes.
*/
assert(image != (const Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickCoreSignature);
#if defined(MAGICKCORE_OPENCL_SUPPORT)
noise_image=AccelerateAddNoiseImage(image,noise_type,attenuate,exception);
if (noise_image != (Image *) NULL)
return(noise_image);
#endif
noise_image=CloneImage(image,0,0,MagickTrue,exception);
if (noise_image == (Image *) NULL)
return((Image *) NULL);
if (SetImageStorageClass(noise_image,DirectClass,exception) == MagickFalse)
{
noise_image=DestroyImage(noise_image);
return((Image *) NULL);
}
/*
Add noise in each row.
*/
status=MagickTrue;
progress=0;
random_info=AcquireRandomInfoThreadSet();
image_view=AcquireVirtualCacheView(image,exception);
noise_view=AcquireAuthenticCacheView(noise_image,exception);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
key=GetRandomSecretKey(random_info[0]);
#pragma omp parallel for schedule(static) shared(progress,status) \
magick_number_threads(image,noise_image,image->rows,key == ~0UL)
#endif
for (y=0; y < (ssize_t) image->rows; y++)
{
const int
id = GetOpenMPThreadId();
MagickBooleanType
sync;
register const Quantum
*magick_restrict p;
register ssize_t
x;
register Quantum
*magick_restrict q;
if (status == MagickFalse)
continue;
p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1,exception);
q=QueueCacheViewAuthenticPixels(noise_view,0,y,noise_image->columns,1,
exception);
if ((p == (const Quantum *) NULL) || (q == (Quantum *) NULL))
{
status=MagickFalse;
continue;
}
for (x=0; x < (ssize_t) image->columns; x++)
{
register ssize_t
i;
for (i=0; i < (ssize_t) GetPixelChannels(image); i++)
{
PixelChannel channel = GetPixelChannelChannel(image,i);
PixelTrait traits = GetPixelChannelTraits(image,channel);
PixelTrait noise_traits=GetPixelChannelTraits(noise_image,channel);
if ((traits == UndefinedPixelTrait) ||
(noise_traits == UndefinedPixelTrait))
continue;
if ((noise_traits & CopyPixelTrait) != 0)
{
SetPixelChannel(noise_image,channel,p[i],q);
continue;
}
SetPixelChannel(noise_image,channel,ClampToQuantum(
GenerateDifferentialNoise(random_info[id],p[i],noise_type,attenuate)),
q);
}
p+=GetPixelChannels(image);
q+=GetPixelChannels(noise_image);
}
sync=SyncCacheViewAuthenticPixels(noise_view,exception);
if (sync == MagickFalse)
status=MagickFalse;
if (image->progress_monitor != (MagickProgressMonitor) NULL)
{
MagickBooleanType
proceed;
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp atomic
#endif
progress++;
proceed=SetImageProgress(image,AddNoiseImageTag,progress,image->rows);
if (proceed == MagickFalse)
status=MagickFalse;
}
}
noise_view=DestroyCacheView(noise_view);
image_view=DestroyCacheView(image_view);
random_info=DestroyRandomInfoThreadSet(random_info);
if (status == MagickFalse)
noise_image=DestroyImage(noise_image);
return(noise_image);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% B l u e S h i f t I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% BlueShiftImage() mutes the colors of the image to simulate a scene at
% nighttime in the moonlight.
%
% The format of the BlueShiftImage method is:
%
% Image *BlueShiftImage(const Image *image,const double factor,
% ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o factor: the shift factor.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport Image *BlueShiftImage(const Image *image,const double factor,
ExceptionInfo *exception)
{
#define BlueShiftImageTag "BlueShift/Image"
CacheView
*image_view,
*shift_view;
Image
*shift_image;
MagickBooleanType
status;
MagickOffsetType
progress;
ssize_t
y;
/*
Allocate blue shift image.
*/
assert(image != (const Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickCoreSignature);
shift_image=CloneImage(image,0,0,MagickTrue,exception);
if (shift_image == (Image *) NULL)
return((Image *) NULL);
if (SetImageStorageClass(shift_image,DirectClass,exception) == MagickFalse)
{
shift_image=DestroyImage(shift_image);
return((Image *) NULL);
}
/*
Blue-shift DirectClass image.
*/
status=MagickTrue;
progress=0;
image_view=AcquireVirtualCacheView(image,exception);
shift_view=AcquireAuthenticCacheView(shift_image,exception);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static) shared(progress,status) \
magick_number_threads(image,shift_image,image->rows,1)
#endif
for (y=0; y < (ssize_t) image->rows; y++)
{
MagickBooleanType
sync;
PixelInfo
pixel;
Quantum
quantum;
register const Quantum
*magick_restrict p;
register ssize_t
x;
register Quantum
*magick_restrict q;
if (status == MagickFalse)
continue;
p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1,exception);
q=QueueCacheViewAuthenticPixels(shift_view,0,y,shift_image->columns,1,
exception);
if ((p == (const Quantum *) NULL) || (q == (Quantum *) NULL))
{
status=MagickFalse;
continue;
}
for (x=0; x < (ssize_t) image->columns; x++)
{
quantum=GetPixelRed(image,p);
if (GetPixelGreen(image,p) < quantum)
quantum=GetPixelGreen(image,p);
if (GetPixelBlue(image,p) < quantum)
quantum=GetPixelBlue(image,p);
pixel.red=0.5*(GetPixelRed(image,p)+factor*quantum);
pixel.green=0.5*(GetPixelGreen(image,p)+factor*quantum);
pixel.blue=0.5*(GetPixelBlue(image,p)+factor*quantum);
quantum=GetPixelRed(image,p);
if (GetPixelGreen(image,p) > quantum)
quantum=GetPixelGreen(image,p);
if (GetPixelBlue(image,p) > quantum)
quantum=GetPixelBlue(image,p);
pixel.red=0.5*(pixel.red+factor*quantum);
pixel.green=0.5*(pixel.green+factor*quantum);
pixel.blue=0.5*(pixel.blue+factor*quantum);
SetPixelRed(shift_image,ClampToQuantum(pixel.red),q);
SetPixelGreen(shift_image,ClampToQuantum(pixel.green),q);
SetPixelBlue(shift_image,ClampToQuantum(pixel.blue),q);
p+=GetPixelChannels(image);
q+=GetPixelChannels(shift_image);
}
sync=SyncCacheViewAuthenticPixels(shift_view,exception);
if (sync == MagickFalse)
status=MagickFalse;
if (image->progress_monitor != (MagickProgressMonitor) NULL)
{
MagickBooleanType
proceed;
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp atomic
#endif
progress++;
proceed=SetImageProgress(image,BlueShiftImageTag,progress,image->rows);
if (proceed == MagickFalse)
status=MagickFalse;
}
}
image_view=DestroyCacheView(image_view);
shift_view=DestroyCacheView(shift_view);
if (status == MagickFalse)
shift_image=DestroyImage(shift_image);
return(shift_image);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% C h a r c o a l I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% CharcoalImage() creates a new image that is a copy of an existing one with
% the edge highlighted. It allocates the memory necessary for the new Image
% structure and returns a pointer to the new image.
%
% The format of the CharcoalImage method is:
%
% Image *CharcoalImage(const Image *image,const double radius,
% const double sigma,ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o radius: the radius of the pixel neighborhood.
%
% o sigma: the standard deviation of the Gaussian, in pixels.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport Image *CharcoalImage(const Image *image,const double radius,
const double sigma,ExceptionInfo *exception)
{
Image
*charcoal_image,
*edge_image;
MagickBooleanType
status;
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickCoreSignature);
edge_image=EdgeImage(image,radius,exception);
if (edge_image == (Image *) NULL)
return((Image *) NULL);
charcoal_image=(Image *) NULL;
status=ClampImage(edge_image,exception);
if (status != MagickFalse)
charcoal_image=BlurImage(edge_image,radius,sigma,exception);
edge_image=DestroyImage(edge_image);
if (charcoal_image == (Image *) NULL)
return((Image *) NULL);
status=NormalizeImage(charcoal_image,exception);
if (status != MagickFalse)
status=NegateImage(charcoal_image,MagickFalse,exception);
if (status != MagickFalse)
status=GrayscaleImage(charcoal_image,image->intensity,exception);
if (status == MagickFalse)
charcoal_image=DestroyImage(charcoal_image);
return(charcoal_image);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% C o l o r i z e I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% ColorizeImage() blends the fill color with each pixel in the image.
% A percentage blend is specified with opacity. Control the application
% of different color components by specifying a different percentage for
% each component (e.g. 90/100/10 is 90% red, 100% green, and 10% blue).
%
% The format of the ColorizeImage method is:
%
% Image *ColorizeImage(const Image *image,const char *blend,
% const PixelInfo *colorize,ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o blend: A character string indicating the level of blending as a
% percentage.
%
% o colorize: A color value.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport Image *ColorizeImage(const Image *image,const char *blend,
const PixelInfo *colorize,ExceptionInfo *exception)
{
#define ColorizeImageTag "Colorize/Image"
#define Colorize(pixel,blend_percentage,colorize) \
(((pixel)*(100.0-(blend_percentage))+(colorize)*(blend_percentage))/100.0)
CacheView
*image_view;
GeometryInfo
geometry_info;
Image
*colorize_image;
MagickBooleanType
status;
MagickOffsetType
progress;
MagickStatusType
flags;
PixelInfo
blend_percentage;
ssize_t
y;
/*
Allocate colorized image.
*/
assert(image != (const Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickCoreSignature);
colorize_image=CloneImage(image,0,0,MagickTrue,exception);
if (colorize_image == (Image *) NULL)
return((Image *) NULL);
if (SetImageStorageClass(colorize_image,DirectClass,exception) == MagickFalse)
{
colorize_image=DestroyImage(colorize_image);
return((Image *) NULL);
}
if ((IsGrayColorspace(colorize_image->colorspace) != MagickFalse) ||
(IsPixelInfoGray(colorize) != MagickFalse))
(void) SetImageColorspace(colorize_image,sRGBColorspace,exception);
if ((colorize_image->alpha_trait == UndefinedPixelTrait) &&
(colorize->alpha_trait != UndefinedPixelTrait))
(void) SetImageAlpha(colorize_image,OpaqueAlpha,exception);
if (blend == (const char *) NULL)
return(colorize_image);
GetPixelInfo(colorize_image,&blend_percentage);
flags=ParseGeometry(blend,&geometry_info);
blend_percentage.red=geometry_info.rho;
blend_percentage.green=geometry_info.rho;
blend_percentage.blue=geometry_info.rho;
blend_percentage.black=geometry_info.rho;
blend_percentage.alpha=(MagickRealType) TransparentAlpha;
if ((flags & SigmaValue) != 0)
blend_percentage.green=geometry_info.sigma;
if ((flags & XiValue) != 0)
blend_percentage.blue=geometry_info.xi;
if ((flags & PsiValue) != 0)
blend_percentage.alpha=geometry_info.psi;
if (blend_percentage.colorspace == CMYKColorspace)
{
if ((flags & PsiValue) != 0)
blend_percentage.black=geometry_info.psi;
if ((flags & ChiValue) != 0)
blend_percentage.alpha=geometry_info.chi;
}
/*
Colorize DirectClass image.
*/
status=MagickTrue;
progress=0;
image_view=AcquireVirtualCacheView(colorize_image,exception);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static) shared(progress,status) \
magick_number_threads(colorize_image,colorize_image,colorize_image->rows,1)
#endif
for (y=0; y < (ssize_t) colorize_image->rows; y++)
{
MagickBooleanType
sync;
register Quantum
*magick_restrict q;
register ssize_t
x;
if (status == MagickFalse)
continue;
q=GetCacheViewAuthenticPixels(image_view,0,y,colorize_image->columns,1,
exception);
if (q == (Quantum *) NULL)
{
status=MagickFalse;
continue;
}
for (x=0; x < (ssize_t) colorize_image->columns; x++)
{
register ssize_t
i;
for (i=0; i < (ssize_t) GetPixelChannels(colorize_image); i++)
{
PixelTrait traits = GetPixelChannelTraits(colorize_image,
(PixelChannel) i);
if (traits == UndefinedPixelTrait)
continue;
if ((traits & CopyPixelTrait) != 0)
continue;
SetPixelChannel(colorize_image,(PixelChannel) i,ClampToQuantum(
Colorize(q[i],GetPixelInfoChannel(&blend_percentage,(PixelChannel) i),
GetPixelInfoChannel(colorize,(PixelChannel) i))),q);
}
q+=GetPixelChannels(colorize_image);
}
sync=SyncCacheViewAuthenticPixels(image_view,exception);
if (sync == MagickFalse)
status=MagickFalse;
if (image->progress_monitor != (MagickProgressMonitor) NULL)
{
MagickBooleanType
proceed;
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp atomic
#endif
progress++;
proceed=SetImageProgress(image,ColorizeImageTag,progress,
colorize_image->rows);
if (proceed == MagickFalse)
status=MagickFalse;
}
}
image_view=DestroyCacheView(image_view);
if (status == MagickFalse)
colorize_image=DestroyImage(colorize_image);
return(colorize_image);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% C o l o r M a t r i x I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% ColorMatrixImage() applies color transformation to an image. This method
% permits saturation changes, hue rotation, luminance to alpha, and various
% other effects. Although variable-sized transformation matrices can be used,
% typically one uses a 5x5 matrix for an RGBA image and a 6x6 for CMYKA
% (or RGBA with offsets). The matrix is similar to those used by Adobe Flash
% except offsets are in column 6 rather than 5 (in support of CMYKA images)
% and offsets are normalized (divide Flash offset by 255).
%
% The format of the ColorMatrixImage method is:
%
% Image *ColorMatrixImage(const Image *image,
% const KernelInfo *color_matrix,ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o color_matrix: the color matrix.
%
% o exception: return any errors or warnings in this structure.
%
*/
/* FUTURE: modify to make use of a MagickMatrix Mutliply function
That should be provided in "matrix.c"
(ASIDE: actually distorts should do this too but currently doesn't)
*/
MagickExport Image *ColorMatrixImage(const Image *image,
const KernelInfo *color_matrix,ExceptionInfo *exception)
{
#define ColorMatrixImageTag "ColorMatrix/Image"
CacheView
*color_view,
*image_view;
double
ColorMatrix[6][6] =
{
{ 1.0, 0.0, 0.0, 0.0, 0.0, 0.0 },
{ 0.0, 1.0, 0.0, 0.0, 0.0, 0.0 },
{ 0.0, 0.0, 1.0, 0.0, 0.0, 0.0 },
{ 0.0, 0.0, 0.0, 1.0, 0.0, 0.0 },
{ 0.0, 0.0, 0.0, 0.0, 1.0, 0.0 },
{ 0.0, 0.0, 0.0, 0.0, 0.0, 1.0 }
};
Image
*color_image;
MagickBooleanType
status;
MagickOffsetType
progress;
register ssize_t
i;
ssize_t
u,
v,
y;
/*
Map given color_matrix, into a 6x6 matrix RGBKA and a constant
*/
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickCoreSignature);
i=0;
for (v=0; v < (ssize_t) color_matrix->height; v++)
for (u=0; u < (ssize_t) color_matrix->width; u++)
{
if ((v < 6) && (u < 6))
ColorMatrix[v][u]=color_matrix->values[i];
i++;
}
/*
Initialize color image.
*/
color_image=CloneImage(image,0,0,MagickTrue,exception);
if (color_image == (Image *) NULL)
return((Image *) NULL);
if (SetImageStorageClass(color_image,DirectClass,exception) == MagickFalse)
{
color_image=DestroyImage(color_image);
return((Image *) NULL);
}
if (image->debug != MagickFalse)
{
char
format[MagickPathExtent],
*message;
(void) LogMagickEvent(TransformEvent,GetMagickModule(),
" ColorMatrix image with color matrix:");
message=AcquireString("");
for (v=0; v < 6; v++)
{
*message='\0';
(void) FormatLocaleString(format,MagickPathExtent,"%.20g: ",(double) v);
(void) ConcatenateString(&message,format);
for (u=0; u < 6; u++)
{
(void) FormatLocaleString(format,MagickPathExtent,"%+f ",
ColorMatrix[v][u]);
(void) ConcatenateString(&message,format);
}
(void) LogMagickEvent(TransformEvent,GetMagickModule(),"%s",message);
}
message=DestroyString(message);
}
/*
Apply the ColorMatrix to image.
*/
status=MagickTrue;
progress=0;
image_view=AcquireVirtualCacheView(image,exception);
color_view=AcquireAuthenticCacheView(color_image,exception);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static) shared(progress,status) \
magick_number_threads(image,color_image,image->rows,1)
#endif
for (y=0; y < (ssize_t) image->rows; y++)
{
PixelInfo
pixel;
register const Quantum
*magick_restrict p;
register Quantum
*magick_restrict q;
register ssize_t
x;
if (status == MagickFalse)
continue;
p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1,exception);
q=GetCacheViewAuthenticPixels(color_view,0,y,color_image->columns,1,
exception);
if ((p == (const Quantum *) NULL) || (q == (Quantum *) NULL))
{
status=MagickFalse;
continue;
}
GetPixelInfo(image,&pixel);
for (x=0; x < (ssize_t) image->columns; x++)
{
register ssize_t
v;
size_t
height;
GetPixelInfoPixel(image,p,&pixel);
height=color_matrix->height > 6 ? 6UL : color_matrix->height;
for (v=0; v < (ssize_t) height; v++)
{
double
sum;
sum=ColorMatrix[v][0]*GetPixelRed(image,p)+ColorMatrix[v][1]*
GetPixelGreen(image,p)+ColorMatrix[v][2]*GetPixelBlue(image,p);
if (image->colorspace == CMYKColorspace)
sum+=ColorMatrix[v][3]*GetPixelBlack(image,p);
if (image->alpha_trait != UndefinedPixelTrait)
sum+=ColorMatrix[v][4]*GetPixelAlpha(image,p);
sum+=QuantumRange*ColorMatrix[v][5];
switch (v)
{
case 0: pixel.red=sum; break;
case 1: pixel.green=sum; break;
case 2: pixel.blue=sum; break;
case 3: pixel.black=sum; break;
case 4: pixel.alpha=sum; break;
default: break;
}
}
SetPixelViaPixelInfo(color_image,&pixel,q);
p+=GetPixelChannels(image);
q+=GetPixelChannels(color_image);
}
if (SyncCacheViewAuthenticPixels(color_view,exception) == MagickFalse)
status=MagickFalse;
if (image->progress_monitor != (MagickProgressMonitor) NULL)
{
MagickBooleanType
proceed;
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp atomic
#endif
progress++;
proceed=SetImageProgress(image,ColorMatrixImageTag,progress,
image->rows);
if (proceed == MagickFalse)
status=MagickFalse;
}
}
color_view=DestroyCacheView(color_view);
image_view=DestroyCacheView(image_view);
if (status == MagickFalse)
color_image=DestroyImage(color_image);
return(color_image);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
+ D e s t r o y F x I n f o %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% DestroyFxInfo() deallocates memory associated with an FxInfo structure.
%
% The format of the DestroyFxInfo method is:
%
% ImageInfo *DestroyFxInfo(ImageInfo *fx_info)
%
% A description of each parameter follows:
%
% o fx_info: the fx info.
%
*/
MagickPrivate FxInfo *DestroyFxInfo(FxInfo *fx_info)
{
register ssize_t
i;
fx_info->exception=DestroyExceptionInfo(fx_info->exception);
fx_info->expression=DestroyString(fx_info->expression);
fx_info->symbols=DestroySplayTree(fx_info->symbols);
fx_info->colors=DestroySplayTree(fx_info->colors);
for (i=(ssize_t) GetImageListLength(fx_info->images)-1; i >= 0; i--)
fx_info->view[i]=DestroyCacheView(fx_info->view[i]);
fx_info->view=(CacheView **) RelinquishMagickMemory(fx_info->view);
fx_info->random_info=DestroyRandomInfo(fx_info->random_info);
fx_info=(FxInfo *) RelinquishMagickMemory(fx_info);
return(fx_info);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
+ F x E v a l u a t e C h a n n e l E x p r e s s i o n %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% FxEvaluateChannelExpression() evaluates an expression and returns the
% results.
%
% The format of the FxEvaluateExpression method is:
%
% double FxEvaluateChannelExpression(FxInfo *fx_info,
% const PixelChannel channel,const ssize_t x,const ssize_t y,
% double *alpha,Exceptioninfo *exception)
% double FxEvaluateExpression(FxInfo *fx_info,
% double *alpha,Exceptioninfo *exception)
%
% A description of each parameter follows:
%
% o fx_info: the fx info.
%
% o channel: the channel.
%
% o x,y: the pixel position.
%
% o alpha: the result.
%
% o exception: return any errors or warnings in this structure.
%
*/
static double FxChannelStatistics(FxInfo *fx_info,Image *image,
PixelChannel channel,const char *symbol,ExceptionInfo *exception)
{
ChannelType
channel_mask;
char
key[MagickPathExtent],
statistic[MagickPathExtent];
const char
*value;
register const char
*p;
channel_mask=UndefinedChannel;
for (p=symbol; (*p != '.') && (*p != '\0'); p++) ;
if (*p == '.')
{
ssize_t
option;
option=ParseCommandOption(MagickPixelChannelOptions,MagickTrue,p+1);
if (option >= 0)
{
channel=(PixelChannel) option;
channel_mask=SetPixelChannelMask(image,(ChannelType)
(1UL << channel));
}
}
(void) FormatLocaleString(key,MagickPathExtent,"%p.%.20g.%s",(void *) image,
(double) channel,symbol);
value=(const char *) GetValueFromSplayTree(fx_info->symbols,key);
if (value != (const char *) NULL)
{
if (channel_mask != UndefinedChannel)
(void) SetPixelChannelMask(image,channel_mask);
return(QuantumScale*StringToDouble(value,(char **) NULL));
}
(void) DeleteNodeFromSplayTree(fx_info->symbols,key);
if (LocaleNCompare(symbol,"depth",5) == 0)
{
size_t
depth;
depth=GetImageDepth(image,exception);
(void) FormatLocaleString(statistic,MagickPathExtent,"%.20g",(double)
depth);
}
if (LocaleNCompare(symbol,"kurtosis",8) == 0)
{
double
kurtosis,
skewness;
(void) GetImageKurtosis(image,&kurtosis,&skewness,exception);
(void) FormatLocaleString(statistic,MagickPathExtent,"%.20g",kurtosis);
}
if (LocaleNCompare(symbol,"maxima",6) == 0)
{
double
maxima,
minima;
(void) GetImageRange(image,&minima,&maxima,exception);
(void) FormatLocaleString(statistic,MagickPathExtent,"%.20g",maxima);
}
if (LocaleNCompare(symbol,"mean",4) == 0)
{
double
mean,
standard_deviation;
(void) GetImageMean(image,&mean,&standard_deviation,exception);
(void) FormatLocaleString(statistic,MagickPathExtent,"%.20g",mean);
}
if (LocaleNCompare(symbol,"minima",6) == 0)
{
double
maxima,
minima;
(void) GetImageRange(image,&minima,&maxima,exception);
(void) FormatLocaleString(statistic,MagickPathExtent,"%.20g",minima);
}
if (LocaleNCompare(symbol,"skewness",8) == 0)
{
double
kurtosis,
skewness;
(void) GetImageKurtosis(image,&kurtosis,&skewness,exception);
(void) FormatLocaleString(statistic,MagickPathExtent,"%.20g",skewness);
}
if (LocaleNCompare(symbol,"standard_deviation",18) == 0)
{
double
mean,
standard_deviation;
(void) GetImageMean(image,&mean,&standard_deviation,exception);
(void) FormatLocaleString(statistic,MagickPathExtent,"%.20g",
standard_deviation);
}
if (channel_mask != UndefinedChannel)
(void) SetPixelChannelMask(image,channel_mask);
(void) AddValueToSplayTree(fx_info->symbols,ConstantString(key),
ConstantString(statistic));
return(QuantumScale*StringToDouble(statistic,(char **) NULL));
}
static double
FxEvaluateSubexpression(FxInfo *,const PixelChannel,const ssize_t,
const ssize_t,const char *,const size_t,double *,ExceptionInfo *);
static inline MagickBooleanType IsFxFunction(const char *expression,
const char *name,const size_t length)
{
int
c;
c=name[length];
if ((LocaleNCompare(expression,name,length) == 0) &&
((isspace(c) == 0) || (c == '(')))
return(MagickTrue);
return(MagickFalse);
}
static MagickOffsetType FxGCD(MagickOffsetType alpha,MagickOffsetType beta)
{
if (beta != 0)
return(FxGCD(beta,alpha % beta));
return(alpha);
}
static inline const char *FxSubexpression(const char *expression,
ExceptionInfo *exception)
{
const char
*subexpression;
register ssize_t
level;
level=0;
subexpression=expression;
while ((*subexpression != '\0') &&
((level != 1) || (strchr(")",(int) *subexpression) == (char *) NULL)))
{
if (strchr("(",(int) *subexpression) != (char *) NULL)
level++;
else
if (strchr(")",(int) *subexpression) != (char *) NULL)
level--;
subexpression++;
}
if (*subexpression == '\0')
(void) ThrowMagickException(exception,GetMagickModule(),OptionError,
"UnbalancedParenthesis","`%s'",expression);
return(subexpression);
}
static double FxGetSymbol(FxInfo *fx_info,const PixelChannel channel,
const ssize_t x,const ssize_t y,const char *expression,const size_t depth,
ExceptionInfo *exception)
{
char
*q,
symbol[MagickPathExtent];
const char
*p,
*value;
Image
*image;
MagickBooleanType
status;
PixelInfo
pixel;
double
alpha,
beta;
PointInfo
point;
register ssize_t
i;
size_t
level;
p=expression;
i=GetImageIndexInList(fx_info->images);
level=0;
point.x=(double) x;
point.y=(double) y;
if (isalpha((int) ((unsigned char) *(p+1))) == 0)
{
char
*subexpression;
subexpression=AcquireString(expression);
if (strchr("suv",(int) *p) != (char *) NULL)
{
switch (*p)
{
case 's':
default:
{
i=GetImageIndexInList(fx_info->images);
break;
}
case 'u': i=0; break;
case 'v': i=1; break;
}
p++;
if (*p == '[')
{
level++;
q=subexpression;
for (p++; *p != '\0'; )
{
if (*p == '[')
level++;
else
if (*p == ']')
{
level--;
if (level == 0)
break;
}
*q++=(*p++);
}
*q='\0';
alpha=FxEvaluateSubexpression(fx_info,channel,x,y,subexpression,
depth,&beta,exception);
i=(ssize_t) alpha;
if (*p != '\0')
p++;
}
if (*p == '.')
p++;
}
if ((*p == 'p') && (isalpha((int) ((unsigned char) *(p+1))) == 0))
{
p++;
if (*p == '{')
{
level++;
q=subexpression;
for (p++; *p != '\0'; )
{
if (*p == '{')
level++;
else
if (*p == '}')
{
level--;
if (level == 0)
break;
}
*q++=(*p++);
}
*q='\0';
alpha=FxEvaluateSubexpression(fx_info,channel,x,y,subexpression,
depth,&beta,exception);
point.x=alpha;
point.y=beta;
if (*p != '\0')
p++;
}
else
if (*p == '[')
{
level++;
q=subexpression;
for (p++; *p != '\0'; )
{
if (*p == '[')
level++;
else
if (*p == ']')
{
level--;
if (level == 0)
break;
}
*q++=(*p++);
}
*q='\0';
alpha=FxEvaluateSubexpression(fx_info,channel,x,y,subexpression,
depth,&beta,exception);
point.x+=alpha;
point.y+=beta;
if (*p != '\0')
p++;
}
if (*p == '.')
p++;
}
subexpression=DestroyString(subexpression);
}
image=GetImageFromList(fx_info->images,i);
if (image == (Image *) NULL)
{
(void) ThrowMagickException(exception,GetMagickModule(),OptionError,
"NoSuchImage","`%s'",expression);
return(0.0);
}
i=GetImageIndexInList(image);
GetPixelInfo(image,&pixel);
status=InterpolatePixelInfo(image,fx_info->view[i],image->interpolate,
point.x,point.y,&pixel,exception);
(void) status;
if ((strlen(p) > 2) && (LocaleCompare(p,"intensity") != 0) &&
(LocaleCompare(p,"luma") != 0) && (LocaleCompare(p,"luminance") != 0) &&
(LocaleCompare(p,"hue") != 0) && (LocaleCompare(p,"saturation") != 0) &&
(LocaleCompare(p,"lightness") != 0))
{
char
name[MagickPathExtent];
(void) CopyMagickString(name,p,MagickPathExtent);
for (q=name+(strlen(name)-1); q > name; q--)
{
if (*q == ')')
break;
if (*q == '.')
{
*q='\0';
break;
}
}
if ((strlen(name) > 2) &&
(GetValueFromSplayTree(fx_info->symbols,name) == (const char *) NULL))
{
PixelInfo
*color;
color=(PixelInfo *) GetValueFromSplayTree(fx_info->colors,name);
if (color != (PixelInfo *) NULL)
{
pixel=(*color);
p+=strlen(name);
}
else
{
MagickBooleanType
status;
status=QueryColorCompliance(name,AllCompliance,&pixel,
fx_info->exception);
if (status != MagickFalse)
{
(void) AddValueToSplayTree(fx_info->colors,ConstantString(
name),ClonePixelInfo(&pixel));
p+=strlen(name);
}
}
}
}
(void) CopyMagickString(symbol,p,MagickPathExtent);
StripString(symbol);
if (*symbol == '\0')
{
switch (channel)
{
case RedPixelChannel: return(QuantumScale*pixel.red);
case GreenPixelChannel: return(QuantumScale*pixel.green);
case BluePixelChannel: return(QuantumScale*pixel.blue);
case BlackPixelChannel:
{
if (image->colorspace != CMYKColorspace)
{
(void) ThrowMagickException(exception,GetMagickModule(),
ImageError,"ColorSeparatedImageRequired","`%s'",
image->filename);
return(0.0);
}
return(QuantumScale*pixel.black);
}
case AlphaPixelChannel:
{
if (pixel.alpha_trait == UndefinedPixelTrait)
return(1.0);
alpha=(double) (QuantumScale*pixel.alpha);
return(alpha);
}
case CompositePixelChannel:
{
Quantum
quantum_pixel[MaxPixelChannels];
SetPixelViaPixelInfo(image,&pixel,quantum_pixel);
return(QuantumScale*GetPixelIntensity(image,quantum_pixel));
}
case IndexPixelChannel:
return(0.0);
default:
break;
}
(void) ThrowMagickException(exception,GetMagickModule(),OptionError,
"UnableToParseExpression","`%s'",p);
return(0.0);
}
switch (*symbol)
{
case 'A':
case 'a':
{
if (LocaleCompare(symbol,"a") == 0)
return((QuantumScale*pixel.alpha));
break;
}
case 'B':
case 'b':
{
if (LocaleCompare(symbol,"b") == 0)
return(QuantumScale*pixel.blue);
break;
}
case 'C':
case 'c':
{
if (IsFxFunction(symbol,"channel",7) != MagickFalse)
{
GeometryInfo
channel_info;
MagickStatusType
flags;
flags=ParseGeometry(symbol+7,&channel_info);
if (image->colorspace == CMYKColorspace)
switch (channel)
{
case CyanPixelChannel:
{
if ((flags & RhoValue) == 0)
return(0.0);
return(channel_info.rho);
}
case MagentaPixelChannel:
{
if ((flags & SigmaValue) == 0)
return(0.0);
return(channel_info.sigma);
}
case YellowPixelChannel:
{
if ((flags & XiValue) == 0)
return(0.0);
return(channel_info.xi);
}
case BlackPixelChannel:
{
if ((flags & PsiValue) == 0)
return(0.0);
return(channel_info.psi);
}
case AlphaPixelChannel:
{
if ((flags & ChiValue) == 0)
return(0.0);
return(channel_info.chi);
}
default:
return(0.0);
}
switch (channel)
{
case RedPixelChannel:
{
if ((flags & RhoValue) == 0)
return(0.0);
return(channel_info.rho);
}
case GreenPixelChannel:
{
if ((flags & SigmaValue) == 0)
return(0.0);
return(channel_info.sigma);
}
case BluePixelChannel:
{
if ((flags & XiValue) == 0)
return(0.0);
return(channel_info.xi);
}
case BlackPixelChannel:
{
if ((flags & ChiValue) == 0)
return(0.0);
return(channel_info.chi);
}
case AlphaPixelChannel:
{
if ((flags & PsiValue) == 0)
return(0.0);
return(channel_info.psi);
}
default:
return(0.0);
}
}
if (LocaleCompare(symbol,"c") == 0)
return(QuantumScale*pixel.red);
break;
}
case 'D':
case 'd':
{
if (LocaleNCompare(symbol,"depth",5) == 0)
return(FxChannelStatistics(fx_info,image,channel,symbol,exception));
break;
}
case 'E':
case 'e':
{
if (LocaleCompare(symbol,"extent") == 0)
{
if (image->extent != 0)
return((double) image->extent);
return((double) GetBlobSize(image));
}
break;
}
case 'G':
case 'g':
{
if (LocaleCompare(symbol,"g") == 0)
return(QuantumScale*pixel.green);
break;
}
case 'K':
case 'k':
{
if (LocaleNCompare(symbol,"kurtosis",8) == 0)
return(FxChannelStatistics(fx_info,image,channel,symbol,exception));
if (LocaleCompare(symbol,"k") == 0)
{
if (image->colorspace != CMYKColorspace)
{
(void) ThrowMagickException(exception,GetMagickModule(),
OptionError,"ColorSeparatedImageRequired","`%s'",
image->filename);
return(0.0);
}
return(QuantumScale*pixel.black);
}
break;
}
case 'H':
case 'h':
{
if (LocaleCompare(symbol,"h") == 0)
return((double) image->rows);
if (LocaleCompare(symbol,"hue") == 0)
{
double
hue,
lightness,
saturation;
ConvertRGBToHSL(pixel.red,pixel.green,pixel.blue,&hue,&saturation,
&lightness);
return(hue);
}
break;
}
case 'I':
case 'i':
{
if ((LocaleCompare(symbol,"image.depth") == 0) ||
(LocaleCompare(symbol,"image.minima") == 0) ||
(LocaleCompare(symbol,"image.maxima") == 0) ||
(LocaleCompare(symbol,"image.mean") == 0) ||
(LocaleCompare(symbol,"image.kurtosis") == 0) ||
(LocaleCompare(symbol,"image.skewness") == 0) ||
(LocaleCompare(symbol,"image.standard_deviation") == 0))
return(FxChannelStatistics(fx_info,image,channel,symbol+6,exception));
if (LocaleCompare(symbol,"image.resolution.x") == 0)
return(image->resolution.x);
if (LocaleCompare(symbol,"image.resolution.y") == 0)
return(image->resolution.y);
if (LocaleCompare(symbol,"intensity") == 0)
{
Quantum
quantum_pixel[MaxPixelChannels];
SetPixelViaPixelInfo(image,&pixel,quantum_pixel);
return(QuantumScale*GetPixelIntensity(image,quantum_pixel));
}
if (LocaleCompare(symbol,"i") == 0)
return((double) x);
break;
}
case 'J':
case 'j':
{
if (LocaleCompare(symbol,"j") == 0)
return((double) y);
break;
}
case 'L':
case 'l':
{
if (LocaleCompare(symbol,"lightness") == 0)
{
double
hue,
lightness,
saturation;
ConvertRGBToHSL(pixel.red,pixel.green,pixel.blue,&hue,&saturation,
&lightness);
return(lightness);
}
if (LocaleCompare(symbol,"luma") == 0)
{
double
luma;
luma=0.212656*pixel.red+0.715158*pixel.green+0.072186*pixel.blue;
return(QuantumScale*luma);
}
if (LocaleCompare(symbol,"luminance") == 0)
{
double
luminence;
luminence=0.212656*pixel.red+0.715158*pixel.green+0.072186*pixel.blue;
return(QuantumScale*luminence);
}
break;
}
case 'M':
case 'm':
{
if (LocaleNCompare(symbol,"maxima",6) == 0)
return(FxChannelStatistics(fx_info,image,channel,symbol,exception));
if (LocaleNCompare(symbol,"mean",4) == 0)
return(FxChannelStatistics(fx_info,image,channel,symbol,exception));
if (LocaleNCompare(symbol,"minima",6) == 0)
return(FxChannelStatistics(fx_info,image,channel,symbol,exception));
if (LocaleCompare(symbol,"m") == 0)
return(QuantumScale*pixel.green);
break;
}
case 'N':
case 'n':
{
if (LocaleCompare(symbol,"n") == 0)
return((double) GetImageListLength(fx_info->images));
break;
}
case 'O':
case 'o':
{
if (LocaleCompare(symbol,"o") == 0)
return(QuantumScale*pixel.alpha);
break;
}
case 'P':
case 'p':
{
if (LocaleCompare(symbol,"page.height") == 0)
return((double) image->page.height);
if (LocaleCompare(symbol,"page.width") == 0)
return((double) image->page.width);
if (LocaleCompare(symbol,"page.x") == 0)
return((double) image->page.x);
if (LocaleCompare(symbol,"page.y") == 0)
return((double) image->page.y);
if (LocaleCompare(symbol,"printsize.x") == 0)
return(PerceptibleReciprocal(image->resolution.x)*image->columns);
if (LocaleCompare(symbol,"printsize.y") == 0)
return(PerceptibleReciprocal(image->resolution.y)*image->rows);
break;
}
case 'Q':
case 'q':
{
if (LocaleCompare(symbol,"quality") == 0)
return((double) image->quality);
break;
}
case 'R':
case 'r':
{
if (LocaleCompare(symbol,"resolution.x") == 0)
return(image->resolution.x);
if (LocaleCompare(symbol,"resolution.y") == 0)
return(image->resolution.y);
if (LocaleCompare(symbol,"r") == 0)
return(QuantumScale*pixel.red);
break;
}
case 'S':
case 's':
{
if (LocaleCompare(symbol,"saturation") == 0)
{
double
hue,
lightness,
saturation;
ConvertRGBToHSL(pixel.red,pixel.green,pixel.blue,&hue,&saturation,
&lightness);
return(saturation);
}
if (LocaleNCompare(symbol,"skewness",8) == 0)
return(FxChannelStatistics(fx_info,image,channel,symbol,exception));
if (LocaleNCompare(symbol,"standard_deviation",18) == 0)
return(FxChannelStatistics(fx_info,image,channel,symbol,exception));
break;
}
case 'T':
case 't':
{
if (LocaleCompare(symbol,"t") == 0)
return((double) GetImageIndexInList(fx_info->images));
break;
}
case 'W':
case 'w':
{
if (LocaleCompare(symbol,"w") == 0)
return((double) image->columns);
break;
}
case 'Y':
case 'y':
{
if (LocaleCompare(symbol,"y") == 0)
return(QuantumScale*pixel.blue);
break;
}
case 'Z':
case 'z':
{
if (LocaleCompare(symbol,"z") == 0)
return((double) GetImageDepth(image,fx_info->exception));
break;
}
default:
break;
}
value=(const char *) GetValueFromSplayTree(fx_info->symbols,symbol);
if (value != (const char *) NULL)
return(StringToDouble(value,(char **) NULL));
(void) ThrowMagickException(exception,GetMagickModule(),OptionError,
"UnableToParseExpression","`%s'",symbol);
return(0.0);
}
static const char *FxOperatorPrecedence(const char *expression,
ExceptionInfo *exception)
{
typedef enum
{
UndefinedPrecedence,
NullPrecedence,
BitwiseComplementPrecedence,
ExponentPrecedence,
ExponentialNotationPrecedence,
MultiplyPrecedence,
AdditionPrecedence,
ShiftPrecedence,
RelationalPrecedence,
EquivalencyPrecedence,
BitwiseAndPrecedence,
BitwiseOrPrecedence,
LogicalAndPrecedence,
LogicalOrPrecedence,
TernaryPrecedence,
AssignmentPrecedence,
CommaPrecedence,
SeparatorPrecedence
} FxPrecedence;
FxPrecedence
precedence,
target;
register const char
*subexpression;
register int
c;
size_t
level;
c=(-1);
level=0;
subexpression=(const char *) NULL;
target=NullPrecedence;
while ((c != '\0') && (*expression != '\0'))
{
precedence=UndefinedPrecedence;
if ((isspace((int) ((unsigned char) *expression)) != 0) || (c == (int) '@'))
{
expression++;
continue;
}
switch (*expression)
{
case 'A':
case 'a':
{
#if defined(MAGICKCORE_HAVE_ACOSH)
if (IsFxFunction(expression,"acosh",5) != MagickFalse)
{
expression+=5;
break;
}
#endif
#if defined(MAGICKCORE_HAVE_ASINH)
if (IsFxFunction(expression,"asinh",5) != MagickFalse)
{
expression+=5;
break;
}
#endif
#if defined(MAGICKCORE_HAVE_ATANH)
if (IsFxFunction(expression,"atanh",5) != MagickFalse)
{
expression+=5;
break;
}
#endif
if (IsFxFunction(expression,"atan2",5) != MagickFalse)
{
expression+=5;
break;
}
break;
}
case 'E':
case 'e':
{
if ((isdigit(c) != 0) &&
((LocaleNCompare(expression,"E+",2) == 0) ||
(LocaleNCompare(expression,"E-",2) == 0)))
{
expression+=2; /* scientific notation */
break;
}
}
case 'J':
case 'j':
{
if ((IsFxFunction(expression,"j0",2) != MagickFalse) ||
(IsFxFunction(expression,"j1",2) != MagickFalse))
{
expression+=2;
break;
}
break;
}
case '#':
{
while (isxdigit((int) ((unsigned char) *(expression+1))) != 0)
expression++;
break;
}
default:
break;
}
if ((c == (int) '{') || (c == (int) '['))
level++;
else
if ((c == (int) '}') || (c == (int) ']'))
level--;
if (level == 0)
switch ((unsigned char) *expression)
{
case '~':
case '!':
{
precedence=BitwiseComplementPrecedence;
break;
}
case '^':
case '@':
{
precedence=ExponentPrecedence;
break;
}
default:
{
if (((c != 0) && ((isdigit(c) != 0) ||
(strchr(")",c) != (char *) NULL))) &&
(((islower((int) ((unsigned char) *expression)) != 0) ||
(strchr("(",(int) ((unsigned char) *expression)) != (char *) NULL)) ||
((isdigit(c) == 0) &&
(isdigit((int) ((unsigned char) *expression)) != 0))) &&
(strchr("xy",(int) ((unsigned char) *expression)) == (char *) NULL))
precedence=MultiplyPrecedence;
break;
}
case '*':
case '/':
case '%':
{
precedence=MultiplyPrecedence;
break;
}
case '+':
case '-':
{
if ((strchr("(+-/*%:&^|<>~,",c) == (char *) NULL) ||
(isalpha(c) != 0))
precedence=AdditionPrecedence;
break;
}
case LeftShiftOperator:
case RightShiftOperator:
{
precedence=ShiftPrecedence;
break;
}
case '<':
case LessThanEqualOperator:
case GreaterThanEqualOperator:
case '>':
{
precedence=RelationalPrecedence;
break;
}
case EqualOperator:
case NotEqualOperator:
{
precedence=EquivalencyPrecedence;
break;
}
case '&':
{
precedence=BitwiseAndPrecedence;
break;
}
case '|':
{
precedence=BitwiseOrPrecedence;
break;
}
case LogicalAndOperator:
{
precedence=LogicalAndPrecedence;
break;
}
case LogicalOrOperator:
{
precedence=LogicalOrPrecedence;
break;
}
case ExponentialNotation:
{
precedence=ExponentialNotationPrecedence;
break;
}
case ':':
case '?':
{
precedence=TernaryPrecedence;
break;
}
case '=':
{
precedence=AssignmentPrecedence;
break;
}
case ',':
{
precedence=CommaPrecedence;
break;
}
case ';':
{
precedence=SeparatorPrecedence;
break;
}
}
if ((precedence == BitwiseComplementPrecedence) ||
(precedence == TernaryPrecedence) ||
(precedence == AssignmentPrecedence))
{
if (precedence > target)
{
/*
Right-to-left associativity.
*/
target=precedence;
subexpression=expression;
}
}
else
if (precedence >= target)
{
/*
Left-to-right associativity.
*/
target=precedence;
subexpression=expression;
}
if (strchr("(",(int) *expression) != (char *) NULL)
expression=FxSubexpression(expression,exception);
c=(int) (*expression++);
}
return(subexpression);
}
static double FxEvaluateSubexpression(FxInfo *fx_info,
const PixelChannel channel,const ssize_t x,const ssize_t y,
const char *expression,const size_t depth,double *beta,
ExceptionInfo *exception)
{
#define FxMaxParenthesisDepth 58
#define FxMaxSubexpressionDepth 200
#define FxReturn(value) \
{ \
subexpression=DestroyString(subexpression); \
return(value); \
}
char
*q,
*subexpression;
double
alpha,
gamma;
register const char
*p;
*beta=0.0;
subexpression=AcquireString(expression);
*subexpression='\0';
if (depth > FxMaxSubexpressionDepth)
{
(void) ThrowMagickException(exception,GetMagickModule(),OptionError,
"UnableToParseExpression","`%s'",expression);
FxReturn(0.0);
}
if (exception->severity >= ErrorException)
FxReturn(0.0);
while (isspace((int) ((unsigned char) *expression)) != 0)
expression++;
if (*expression == '\0')
FxReturn(0.0);
p=FxOperatorPrecedence(expression,exception);
if (p != (const char *) NULL)
{
(void) CopyMagickString(subexpression,expression,(size_t)
(p-expression+1));
alpha=FxEvaluateSubexpression(fx_info,channel,x,y,subexpression,depth+1,
beta,exception);
switch ((unsigned char) *p)
{
case '~':
{
*beta=FxEvaluateSubexpression(fx_info,channel,x,y,++p,depth+1,beta,
exception);
*beta=(double) (~(size_t) *beta);
FxReturn(*beta);
}
case '!':
{
*beta=FxEvaluateSubexpression(fx_info,channel,x,y,++p,depth+1,beta,
exception);
FxReturn(*beta == 0.0 ? 1.0 : 0.0);
}
case '^':
{
*beta=pow(alpha,FxEvaluateSubexpression(fx_info,channel,x,y,++p,
depth+1,beta,exception));
FxReturn(*beta);
}
case '*':
case ExponentialNotation:
{
*beta=FxEvaluateSubexpression(fx_info,channel,x,y,++p,depth+1,beta,
exception);
FxReturn(alpha*(*beta));
}
case '/':
{
*beta=FxEvaluateSubexpression(fx_info,channel,x,y,++p,depth+1,beta,
exception);
FxReturn(PerceptibleReciprocal(*beta)*alpha);
}
case '%':
{
*beta=FxEvaluateSubexpression(fx_info,channel,x,y,++p,depth+1,beta,
exception);
*beta=fabs(floor((*beta)+0.5));
FxReturn(fmod(alpha,*beta));
}
case '+':
{
*beta=FxEvaluateSubexpression(fx_info,channel,x,y,++p,depth+1,beta,
exception);
FxReturn(alpha+(*beta));
}
case '-':
{
*beta=FxEvaluateSubexpression(fx_info,channel,x,y,++p,depth+1,beta,
exception);
FxReturn(alpha-(*beta));
}
case LeftShiftOperator:
{
gamma=FxEvaluateSubexpression(fx_info,channel,x,y,++p,depth+1,beta,
exception);
if ((size_t) (gamma+0.5) >= (8*sizeof(size_t)))
{
(void) ThrowMagickException(exception,GetMagickModule(),
OptionError,"ShiftCountOverflow","`%s'",subexpression);
FxReturn(0.0);
}
*beta=(double) ((size_t) (alpha+0.5) << (size_t) (gamma+0.5));
FxReturn(*beta);
}
case RightShiftOperator:
{
gamma=FxEvaluateSubexpression(fx_info,channel,x,y,++p,depth+1,beta,
exception);
if ((size_t) (gamma+0.5) >= (8*sizeof(size_t)))
{
(void) ThrowMagickException(exception,GetMagickModule(),
OptionError,"ShiftCountOverflow","`%s'",subexpression);
FxReturn(0.0);
}
*beta=(double) ((size_t) (alpha+0.5) >> (size_t) (gamma+0.5));
FxReturn(*beta);
}
case '<':
{
*beta=FxEvaluateSubexpression(fx_info,channel,x,y,++p,depth+1,beta,
exception);
FxReturn(alpha < *beta ? 1.0 : 0.0);
}
case LessThanEqualOperator:
{
*beta=FxEvaluateSubexpression(fx_info,channel,x,y,++p,depth+1,beta,
exception);
FxReturn(alpha <= *beta ? 1.0 : 0.0);
}
case '>':
{
*beta=FxEvaluateSubexpression(fx_info,channel,x,y,++p,depth+1,beta,
exception);
FxReturn(alpha > *beta ? 1.0 : 0.0);
}
case GreaterThanEqualOperator:
{
*beta=FxEvaluateSubexpression(fx_info,channel,x,y,++p,depth+1,beta,
exception);
FxReturn(alpha >= *beta ? 1.0 : 0.0);
}
case EqualOperator:
{
*beta=FxEvaluateSubexpression(fx_info,channel,x,y,++p,depth+1,beta,
exception);
FxReturn(fabs(alpha-(*beta)) < MagickEpsilon ? 1.0 : 0.0);
}
case NotEqualOperator:
{
*beta=FxEvaluateSubexpression(fx_info,channel,x,y,++p,depth+1,beta,
exception);
FxReturn(fabs(alpha-(*beta)) >= MagickEpsilon ? 1.0 : 0.0);
}
case '&':
{
gamma=FxEvaluateSubexpression(fx_info,channel,x,y,++p,depth+1,beta,
exception);
*beta=(double) ((size_t) (alpha+0.5) & (size_t) (gamma+0.5));
FxReturn(*beta);
}
case '|':
{
gamma=FxEvaluateSubexpression(fx_info,channel,x,y,++p,depth+1,beta,
exception);
*beta=(double) ((size_t) (alpha+0.5) | (size_t) (gamma+0.5));
FxReturn(*beta);
}
case LogicalAndOperator:
{
p++;
if (alpha <= 0.0)
{
*beta=0.0;
FxReturn(*beta);
}
gamma=FxEvaluateSubexpression(fx_info,channel,x,y,p,depth+1,beta,
exception);
*beta=(gamma > 0.0) ? 1.0 : 0.0;
FxReturn(*beta);
}
case LogicalOrOperator:
{
p++;
if (alpha > 0.0)
{
*beta=1.0;
FxReturn(*beta);
}
gamma=FxEvaluateSubexpression(fx_info,channel,x,y,p,depth+1,beta,
exception);
*beta=(gamma > 0.0) ? 1.0 : 0.0;
FxReturn(*beta);
}
case '?':
{
(void) CopyMagickString(subexpression,++p,MagickPathExtent);
q=subexpression;
p=StringToken(":",&q);
if (q == (char *) NULL)
{
(void) ThrowMagickException(exception,GetMagickModule(),
OptionError,"UnableToParseExpression","`%s'",subexpression);
FxReturn(0.0);
}
if (fabs(alpha) >= MagickEpsilon)
gamma=FxEvaluateSubexpression(fx_info,channel,x,y,p,depth+1,beta,
exception);
else
gamma=FxEvaluateSubexpression(fx_info,channel,x,y,q,depth+1,beta,
exception);
FxReturn(gamma);
}
case '=':
{
char
numeric[MagickPathExtent];
q=subexpression;
while (isalpha((int) ((unsigned char) *q)) != 0)
q++;
if (*q != '\0')
{
(void) ThrowMagickException(exception,GetMagickModule(),
OptionError,"UnableToParseExpression","`%s'",subexpression);
FxReturn(0.0);
}
ClearMagickException(exception);
*beta=FxEvaluateSubexpression(fx_info,channel,x,y,++p,depth+1,beta,
exception);
(void) FormatLocaleString(numeric,MagickPathExtent,"%.20g",*beta);
(void) DeleteNodeFromSplayTree(fx_info->symbols,subexpression);
(void) AddValueToSplayTree(fx_info->symbols,ConstantString(
subexpression),ConstantString(numeric));
FxReturn(*beta);
}
case ',':
{
*beta=FxEvaluateSubexpression(fx_info,channel,x,y,++p,depth+1,beta,
exception);
FxReturn(alpha);
}
case ';':
{
*beta=FxEvaluateSubexpression(fx_info,channel,x,y,++p,depth+1,beta,
exception);
FxReturn(*beta);
}
default:
{
gamma=alpha*FxEvaluateSubexpression(fx_info,channel,x,y,++p,depth+1,
beta,exception);
FxReturn(gamma);
}
}
}
if (strchr("(",(int) *expression) != (char *) NULL)
{
if (depth >= FxMaxParenthesisDepth)
(void) ThrowMagickException(exception,GetMagickModule(),OptionError,
"ParenthesisNestedTooDeeply","`%s'",expression);
(void) CopyMagickString(subexpression,expression+1,MagickPathExtent);
if (strlen(subexpression) != 0)
subexpression[strlen(subexpression)-1]='\0';
gamma=FxEvaluateSubexpression(fx_info,channel,x,y,subexpression,depth+1,
beta,exception);
FxReturn(gamma);
}
switch (*expression)
{
case '+':
{
gamma=FxEvaluateSubexpression(fx_info,channel,x,y,expression+1,depth+1,
beta,exception);
FxReturn(1.0*gamma);
}
case '-':
{
gamma=FxEvaluateSubexpression(fx_info,channel,x,y,expression+1,depth+1,
beta,exception);
FxReturn(-1.0*gamma);
}
case '~':
{
gamma=FxEvaluateSubexpression(fx_info,channel,x,y,expression+1,depth+1,
beta,exception);
FxReturn((double) (~(size_t) (gamma+0.5)));
}
case 'A':
case 'a':
{
if (IsFxFunction(expression,"abs",3) != MagickFalse)
{
alpha=FxEvaluateSubexpression(fx_info,channel,x,y,expression+3,
depth+1,beta,exception);
FxReturn(fabs(alpha));
}
#if defined(MAGICKCORE_HAVE_ACOSH)
if (IsFxFunction(expression,"acosh",5) != MagickFalse)
{
alpha=FxEvaluateSubexpression(fx_info,channel,x,y,expression+5,
depth+1,beta,exception);
FxReturn(acosh(alpha));
}
#endif
if (IsFxFunction(expression,"acos",4) != MagickFalse)
{
alpha=FxEvaluateSubexpression(fx_info,channel,x,y,expression+4,
depth+1,beta,exception);
FxReturn(acos(alpha));
}
#if defined(MAGICKCORE_HAVE_J1)
if (IsFxFunction(expression,"airy",4) != MagickFalse)
{
alpha=FxEvaluateSubexpression(fx_info,channel,x,y,expression+4,
depth+1,beta,exception);
if (alpha == 0.0)
FxReturn(1.0);
gamma=2.0*j1((MagickPI*alpha))/(MagickPI*alpha);
FxReturn(gamma*gamma);
}
#endif
#if defined(MAGICKCORE_HAVE_ASINH)
if (IsFxFunction(expression,"asinh",5) != MagickFalse)
{
alpha=FxEvaluateSubexpression(fx_info,channel,x,y,expression+5,
depth+1,beta,exception);
FxReturn(asinh(alpha));
}
#endif
if (IsFxFunction(expression,"asin",4) != MagickFalse)
{
alpha=FxEvaluateSubexpression(fx_info,channel,x,y,expression+4,
depth+1,beta,exception);
FxReturn(asin(alpha));
}
if (IsFxFunction(expression,"alt",3) != MagickFalse)
{
alpha=FxEvaluateSubexpression(fx_info,channel,x,y,expression+3,
depth+1,beta,exception);
FxReturn(((ssize_t) alpha) & 0x01 ? -1.0 : 1.0);
}
if (IsFxFunction(expression,"atan2",5) != MagickFalse)
{
alpha=FxEvaluateSubexpression(fx_info,channel,x,y,expression+5,
depth+1,beta,exception);
FxReturn(atan2(alpha,*beta));
}
#if defined(MAGICKCORE_HAVE_ATANH)
if (IsFxFunction(expression,"atanh",5) != MagickFalse)
{
alpha=FxEvaluateSubexpression(fx_info,channel,x,y,expression+5,
depth+1,beta,exception);
FxReturn(atanh(alpha));
}
#endif
if (IsFxFunction(expression,"atan",4) != MagickFalse)
{
alpha=FxEvaluateSubexpression(fx_info,channel,x,y,expression+4,
depth+1,beta,exception);
FxReturn(atan(alpha));
}
if (LocaleCompare(expression,"a") == 0)
FxReturn(FxGetSymbol(fx_info,channel,x,y,expression,depth+1,exception));
break;
}
case 'B':
case 'b':
{
if (LocaleCompare(expression,"b") == 0)
FxReturn(FxGetSymbol(fx_info,channel,x,y,expression,depth+1,exception));
break;
}
case 'C':
case 'c':
{
if (IsFxFunction(expression,"ceil",4) != MagickFalse)
{
alpha=FxEvaluateSubexpression(fx_info,channel,x,y,expression+4,
depth+1,beta,exception);
FxReturn(ceil(alpha));
}
if (IsFxFunction(expression,"clamp",5) != MagickFalse)
{
alpha=FxEvaluateSubexpression(fx_info,channel,x,y,expression+5,
depth+1,beta,exception);
if (alpha < 0.0)
FxReturn(0.0);
if (alpha > 1.0)
FxReturn(1.0);
FxReturn(alpha);
}
if (IsFxFunction(expression,"cosh",4) != MagickFalse)
{
alpha=FxEvaluateSubexpression(fx_info,channel,x,y,expression+4,
depth+1,beta,exception);
FxReturn(cosh(alpha));
}
if (IsFxFunction(expression,"cos",3) != MagickFalse)
{
alpha=FxEvaluateSubexpression(fx_info,channel,x,y,expression+3,
depth+1,beta,exception);
FxReturn(cos(alpha));
}
if (LocaleCompare(expression,"c") == 0)
FxReturn(FxGetSymbol(fx_info,channel,x,y,expression,depth+1,exception));
break;
}
case 'D':
case 'd':
{
if (IsFxFunction(expression,"debug",5) != MagickFalse)
{
const char
*type;
alpha=FxEvaluateSubexpression(fx_info,channel,x,y,expression+5,
depth+1,beta,exception);
if (fx_info->images->colorspace == CMYKColorspace)
switch (channel)
{
case CyanPixelChannel: type="cyan"; break;
case MagentaPixelChannel: type="magenta"; break;
case YellowPixelChannel: type="yellow"; break;
case AlphaPixelChannel: type="opacity"; break;
case BlackPixelChannel: type="black"; break;
default: type="unknown"; break;
}
else
switch (channel)
{
case RedPixelChannel: type="red"; break;
case GreenPixelChannel: type="green"; break;
case BluePixelChannel: type="blue"; break;
case AlphaPixelChannel: type="opacity"; break;
default: type="unknown"; break;
}
*subexpression='\0';
if (strlen(expression) > 6)
(void) CopyMagickString(subexpression,expression+6,
MagickPathExtent);
if (strlen(subexpression) > 1)
subexpression[strlen(subexpression)-1]='\0';
if (fx_info->file != (FILE *) NULL)
(void) FormatLocaleFile(fx_info->file,"%s[%.20g,%.20g].%s: "
"%s=%.*g\n",fx_info->images->filename,(double) x,(double) y,type,
subexpression,GetMagickPrecision(),alpha);
FxReturn(0.0);
}
if (IsFxFunction(expression,"drc",3) != MagickFalse)
{
alpha=FxEvaluateSubexpression(fx_info,channel,x,y,expression+3,
depth+1,beta,exception);
FxReturn((alpha/(*beta*(alpha-1.0)+1.0)));
}
break;
}
case 'E':
case 'e':
{
if (LocaleCompare(expression,"epsilon") == 0)
FxReturn(MagickEpsilon);
#if defined(MAGICKCORE_HAVE_ERF)
if (IsFxFunction(expression,"erf",3) != MagickFalse)
{
alpha=FxEvaluateSubexpression(fx_info,channel,x,y,expression+3,
depth+1,beta,exception);
FxReturn(erf(alpha));
}
#endif
if (IsFxFunction(expression,"exp",3) != MagickFalse)
{
alpha=FxEvaluateSubexpression(fx_info,channel,x,y,expression+3,
depth+1,beta,exception);
FxReturn(exp(alpha));
}
if (LocaleCompare(expression,"e") == 0)
FxReturn(2.7182818284590452354);
break;
}
case 'F':
case 'f':
{
if (IsFxFunction(expression,"floor",5) != MagickFalse)
{
alpha=FxEvaluateSubexpression(fx_info,channel,x,y,expression+5,
depth+1,beta,exception);
FxReturn(floor(alpha));
}
break;
}
case 'G':
case 'g':
{
if (IsFxFunction(expression,"gauss",5) != MagickFalse)
{
alpha=FxEvaluateSubexpression(fx_info,channel,x,y,expression+5,
depth+1,beta,exception);
gamma=exp((-alpha*alpha/2.0))/sqrt(2.0*MagickPI);
FxReturn(gamma);
}
if (IsFxFunction(expression,"gcd",3) != MagickFalse)
{
MagickOffsetType
gcd;
alpha=FxEvaluateSubexpression(fx_info,channel,x,y,expression+3,
depth+1,beta,exception);
gcd=FxGCD((MagickOffsetType) (alpha+0.5),(MagickOffsetType) (*beta+
0.5));
FxReturn((double) gcd);
}
if (LocaleCompare(expression,"g") == 0)
FxReturn(FxGetSymbol(fx_info,channel,x,y,expression,depth+1,exception));
break;
}
case 'H':
case 'h':
{
if (LocaleCompare(expression,"h") == 0)
FxReturn(FxGetSymbol(fx_info,channel,x,y,expression,depth+1,exception));
if (LocaleCompare(expression,"hue") == 0)
FxReturn(FxGetSymbol(fx_info,channel,x,y,expression,depth+1,exception));
if (IsFxFunction(expression,"hypot",5) != MagickFalse)
{
alpha=FxEvaluateSubexpression(fx_info,channel,x,y,expression+5,
depth+1,beta,exception);
FxReturn(hypot(alpha,*beta));
}
break;
}
case 'K':
case 'k':
{
if (LocaleCompare(expression,"k") == 0)
FxReturn(FxGetSymbol(fx_info,channel,x,y,expression,depth+1,exception));
break;
}
case 'I':
case 'i':
{
if (LocaleCompare(expression,"intensity") == 0)
FxReturn(FxGetSymbol(fx_info,channel,x,y,expression,depth+1,exception));
if (IsFxFunction(expression,"int",3) != MagickFalse)
{
alpha=FxEvaluateSubexpression(fx_info,channel,x,y,expression+3,
depth+1,beta,exception);
FxReturn(floor(alpha));
}
if (IsFxFunction(expression,"isnan",5) != MagickFalse)
{
alpha=FxEvaluateSubexpression(fx_info,channel,x,y,expression+5,
depth+1,beta,exception);
FxReturn((double) !!IsNaN(alpha));
}
if (LocaleCompare(expression,"i") == 0)
FxReturn(FxGetSymbol(fx_info,channel,x,y,expression,depth+1,exception));
break;
}
case 'J':
case 'j':
{
if (LocaleCompare(expression,"j") == 0)
FxReturn(FxGetSymbol(fx_info,channel,x,y,expression,depth+1,exception));
#if defined(MAGICKCORE_HAVE_J0)
if (IsFxFunction(expression,"j0",2) != MagickFalse)
{
alpha=FxEvaluateSubexpression(fx_info,channel,x,y,expression+2,
depth+1,beta,exception);
FxReturn(j0(alpha));
}
#endif
#if defined(MAGICKCORE_HAVE_J1)
if (IsFxFunction(expression,"j1",2) != MagickFalse)
{
alpha=FxEvaluateSubexpression(fx_info,channel,x,y,expression+2,
depth+1,beta,exception);
FxReturn(j1(alpha));
}
#endif
#if defined(MAGICKCORE_HAVE_J1)
if (IsFxFunction(expression,"jinc",4) != MagickFalse)
{
alpha=FxEvaluateSubexpression(fx_info,channel,x,y,expression+4,
depth+1,beta,exception);
if (alpha == 0.0)
FxReturn(1.0);
gamma=(2.0*j1((MagickPI*alpha))/(MagickPI*alpha));
FxReturn(gamma);
}
#endif
break;
}
case 'L':
case 'l':
{
if (IsFxFunction(expression,"ln",2) != MagickFalse)
{
alpha=FxEvaluateSubexpression(fx_info,channel,x,y,expression+2,
depth+1,beta,exception);
FxReturn(log(alpha));
}
if (IsFxFunction(expression,"logtwo",6) != MagickFalse)
{
alpha=FxEvaluateSubexpression(fx_info,channel,x,y,expression+6,
depth+1,beta,exception);
FxReturn(log10(alpha)/log10(2.0));
}
if (IsFxFunction(expression,"log",3) != MagickFalse)
{
alpha=FxEvaluateSubexpression(fx_info,channel,x,y,expression+3,
depth+1,beta,exception);
FxReturn(log10(alpha));
}
if (LocaleCompare(expression,"lightness") == 0)
FxReturn(FxGetSymbol(fx_info,channel,x,y,expression,depth+1,exception));
break;
}
case 'M':
case 'm':
{
if (LocaleCompare(expression,"MaxRGB") == 0)
FxReturn(QuantumRange);
if (LocaleNCompare(expression,"maxima",6) == 0)
break;
if (IsFxFunction(expression,"max",3) != MagickFalse)
{
alpha=FxEvaluateSubexpression(fx_info,channel,x,y,expression+3,
depth+1,beta,exception);
FxReturn(alpha > *beta ? alpha : *beta);
}
if (LocaleNCompare(expression,"minima",6) == 0)
break;
if (IsFxFunction(expression,"min",3) != MagickFalse)
{
alpha=FxEvaluateSubexpression(fx_info,channel,x,y,expression+3,
depth+1,beta,exception);
FxReturn(alpha < *beta ? alpha : *beta);
}
if (IsFxFunction(expression,"mod",3) != MagickFalse)
{
alpha=FxEvaluateSubexpression(fx_info,channel,x,y,expression+3,
depth+1,beta,exception);
gamma=alpha-floor((alpha*PerceptibleReciprocal(*beta)))*(*beta);
FxReturn(gamma);
}
if (LocaleCompare(expression,"m") == 0)
FxReturn(FxGetSymbol(fx_info,channel,x,y,expression,depth+1,exception));
break;
}
case 'N':
case 'n':
{
if (IsFxFunction(expression,"not",3) != MagickFalse)
{
alpha=FxEvaluateSubexpression(fx_info,channel,x,y,expression+3,
depth+1,beta,exception);
FxReturn((double) (alpha < MagickEpsilon));
}
if (LocaleCompare(expression,"n") == 0)
FxReturn(FxGetSymbol(fx_info,channel,x,y,expression,depth+1,exception));
break;
}
case 'O':
case 'o':
{
if (LocaleCompare(expression,"Opaque") == 0)
FxReturn(1.0);
if (LocaleCompare(expression,"o") == 0)
FxReturn(FxGetSymbol(fx_info,channel,x,y,expression,depth+1,exception));
break;
}
case 'P':
case 'p':
{
if (LocaleCompare(expression,"phi") == 0)
FxReturn(MagickPHI);
if (LocaleCompare(expression,"pi") == 0)
FxReturn(MagickPI);
if (IsFxFunction(expression,"pow",3) != MagickFalse)
{
alpha=FxEvaluateSubexpression(fx_info,channel,x,y,expression+3,
depth+1,beta,exception);
FxReturn(pow(alpha,*beta));
}
if (LocaleCompare(expression,"p") == 0)
FxReturn(FxGetSymbol(fx_info,channel,x,y,expression,depth+1,exception));
break;
}
case 'Q':
case 'q':
{
if (LocaleCompare(expression,"QuantumRange") == 0)
FxReturn(QuantumRange);
if (LocaleCompare(expression,"QuantumScale") == 0)
FxReturn(QuantumScale);
break;
}
case 'R':
case 'r':
{
if (IsFxFunction(expression,"rand",4) != MagickFalse)
{
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp critical (MagickCore_FxEvaluateSubexpression)
#endif
alpha=GetPseudoRandomValue(fx_info->random_info);
FxReturn(alpha);
}
if (IsFxFunction(expression,"round",5) != MagickFalse)
{
alpha=FxEvaluateSubexpression(fx_info,channel,x,y,expression+5,
depth+1,beta,exception);
FxReturn(floor(alpha+0.5));
}
if (LocaleCompare(expression,"r") == 0)
FxReturn(FxGetSymbol(fx_info,channel,x,y,expression,depth+1,exception));
break;
}
case 'S':
case 's':
{
if (LocaleCompare(expression,"saturation") == 0)
FxReturn(FxGetSymbol(fx_info,channel,x,y,expression,depth+1,exception));
if (IsFxFunction(expression,"sign",4) != MagickFalse)
{
alpha=FxEvaluateSubexpression(fx_info,channel,x,y,expression+4,
depth+1,beta,exception);
FxReturn(alpha < 0.0 ? -1.0 : 1.0);
}
if (IsFxFunction(expression,"sinc",4) != MagickFalse)
{
alpha=FxEvaluateSubexpression(fx_info,channel,x,y,expression+4,
depth+1,beta,exception);
if (alpha == 0)
FxReturn(1.0);
gamma=sin((MagickPI*alpha))/(MagickPI*alpha);
FxReturn(gamma);
}
if (IsFxFunction(expression,"sinh",4) != MagickFalse)
{
alpha=FxEvaluateSubexpression(fx_info,channel,x,y,expression+4,
depth+1,beta,exception);
FxReturn(sinh(alpha));
}
if (IsFxFunction(expression,"sin",3) != MagickFalse)
{
alpha=FxEvaluateSubexpression(fx_info,channel,x,y,expression+3,
depth+1,beta,exception);
FxReturn(sin(alpha));
}
if (IsFxFunction(expression,"sqrt",4) != MagickFalse)
{
alpha=FxEvaluateSubexpression(fx_info,channel,x,y,expression+4,
depth+1,beta,exception);
FxReturn(sqrt(alpha));
}
if (IsFxFunction(expression,"squish",6) != MagickFalse)
{
alpha=FxEvaluateSubexpression(fx_info,channel,x,y,expression+6,
depth+1,beta,exception);
FxReturn((1.0/(1.0+exp(-alpha))));
}
if (LocaleCompare(expression,"s") == 0)
FxReturn(FxGetSymbol(fx_info,channel,x,y,expression,depth+1,exception));
break;
}
case 'T':
case 't':
{
if (IsFxFunction(expression,"tanh",4) != MagickFalse)
{
alpha=FxEvaluateSubexpression(fx_info,channel,x,y,expression+4,
depth+1,beta,exception);
FxReturn(tanh(alpha));
}
if (IsFxFunction(expression,"tan",3) != MagickFalse)
{
alpha=FxEvaluateSubexpression(fx_info,channel,x,y,expression+3,
depth+1,beta,exception);
FxReturn(tan(alpha));
}
if (LocaleCompare(expression,"Transparent") == 0)
FxReturn(0.0);
if (IsFxFunction(expression,"trunc",5) != MagickFalse)
{
alpha=FxEvaluateSubexpression(fx_info,channel,x,y,expression+5,
depth+1,beta,exception);
if (alpha >= 0.0)
FxReturn(floor(alpha));
FxReturn(ceil(alpha));
}
if (LocaleCompare(expression,"t") == 0)
FxReturn(FxGetSymbol(fx_info,channel,x,y,expression,depth+1,exception));
break;
}
case 'U':
case 'u':
{
if (LocaleCompare(expression,"u") == 0)
FxReturn(FxGetSymbol(fx_info,channel,x,y,expression,depth+1,exception));
break;
}
case 'V':
case 'v':
{
if (LocaleCompare(expression,"v") == 0)
FxReturn(FxGetSymbol(fx_info,channel,x,y,expression,depth+1,exception));
break;
}
case 'W':
case 'w':
{
if (IsFxFunction(expression,"while",5) != MagickFalse)
{
/*
Parse while(condition,expression).
*/
(void) CopyMagickString(subexpression,expression+5,MagickPathExtent);
q=subexpression;
p=StringToken(",",&q);
if ((p == (char *) NULL) || (strlen(p) < 1) || (q == (char *) NULL))
{
(void) ThrowMagickException(exception,GetMagickModule(),
OptionError,"UnableToParseExpression","`%s'",expression);
FxReturn(0.0);
}
for ( ; ; )
{
double sans = 0.0;
alpha=FxEvaluateSubexpression(fx_info,channel,x,y,p+1,depth+1,&sans,
exception);
if (fabs(alpha) < MagickEpsilon)
FxReturn(*beta);
alpha=FxEvaluateSubexpression(fx_info,channel,x,y,q,depth+1,beta,
exception);
}
}
if (LocaleCompare(expression,"w") == 0)
FxReturn(FxGetSymbol(fx_info,channel,x,y,expression,depth+1,exception));
break;
}
case 'Y':
case 'y':
{
if (LocaleCompare(expression,"y") == 0)
FxReturn(FxGetSymbol(fx_info,channel,x,y,expression,depth+1,exception));
break;
}
case 'Z':
case 'z':
{
if (LocaleCompare(expression,"z") == 0)
FxReturn(FxGetSymbol(fx_info,channel,x,y,expression,depth+1,exception));
break;
}
default:
break;
}
subexpression=DestroyString(subexpression);
q=(char *) expression;
alpha=InterpretSiPrefixValue(expression,&q);
if (q == expression)
FxReturn(FxGetSymbol(fx_info,channel,x,y,expression,depth+1,exception));
FxReturn(alpha);
}
MagickPrivate MagickBooleanType FxEvaluateExpression(FxInfo *fx_info,
double *alpha,ExceptionInfo *exception)
{
MagickBooleanType
status;
status=FxEvaluateChannelExpression(fx_info,GrayPixelChannel,0,0,alpha,
exception);
return(status);
}
MagickExport MagickBooleanType FxPreprocessExpression(FxInfo *fx_info,
double *alpha,ExceptionInfo *exception)
{
FILE
*file;
MagickBooleanType
status;
file=fx_info->file;
fx_info->file=(FILE *) NULL;
status=FxEvaluateChannelExpression(fx_info,GrayPixelChannel,0,0,alpha,
exception);
fx_info->file=file;
return(status);
}
MagickPrivate MagickBooleanType FxEvaluateChannelExpression(FxInfo *fx_info,
const PixelChannel channel,const ssize_t x,const ssize_t y,
double *alpha,ExceptionInfo *exception)
{
double
beta;
beta=0.0;
*alpha=FxEvaluateSubexpression(fx_info,channel,x,y,fx_info->expression,0,
&beta,exception);
return(exception->severity == OptionError ? MagickFalse : MagickTrue);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% F x I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% FxImage() applies a mathematical expression to the specified image.
%
% The format of the FxImage method is:
%
% Image *FxImage(const Image *image,const char *expression,
% ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o expression: A mathematical expression.
%
% o exception: return any errors or warnings in this structure.
%
*/
static FxInfo **DestroyFxThreadSet(FxInfo **fx_info)
{
register ssize_t
i;
assert(fx_info != (FxInfo **) NULL);
for (i=0; i < (ssize_t) GetMagickResourceLimit(ThreadResource); i++)
if (fx_info[i] != (FxInfo *) NULL)
fx_info[i]=DestroyFxInfo(fx_info[i]);
fx_info=(FxInfo **) RelinquishMagickMemory(fx_info);
return(fx_info);
}
static FxInfo **AcquireFxThreadSet(const Image *image,const char *expression,
ExceptionInfo *exception)
{
char
*fx_expression;
FxInfo
**fx_info;
double
alpha;
register ssize_t
i;
size_t
number_threads;
number_threads=(size_t) GetMagickResourceLimit(ThreadResource);
fx_info=(FxInfo **) AcquireQuantumMemory(number_threads,sizeof(*fx_info));
if (fx_info == (FxInfo **) NULL)
{
(void) ThrowMagickException(exception,GetMagickModule(),
ResourceLimitError,"MemoryAllocationFailed","`%s'",image->filename);
return((FxInfo **) NULL);
}
(void) memset(fx_info,0,number_threads*sizeof(*fx_info));
if (*expression != '@')
fx_expression=ConstantString(expression);
else
fx_expression=FileToString(expression+1,~0UL,exception);
for (i=0; i < (ssize_t) number_threads; i++)
{
MagickBooleanType
status;
fx_info[i]=AcquireFxInfo(image,fx_expression,exception);
if (fx_info[i] == (FxInfo *) NULL)
break;
status=FxPreprocessExpression(fx_info[i],&alpha,exception);
if (status == MagickFalse)
break;
}
fx_expression=DestroyString(fx_expression);
if (i < (ssize_t) number_threads)
fx_info=DestroyFxThreadSet(fx_info);
return(fx_info);
}
MagickExport Image *FxImage(const Image *image,const char *expression,
ExceptionInfo *exception)
{
#define FxImageTag "Fx/Image"
CacheView
*fx_view,
*image_view;
FxInfo
**magick_restrict fx_info;
Image
*fx_image;
MagickBooleanType
status;
MagickOffsetType
progress;
ssize_t
y;
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
if (expression == (const char *) NULL)
return(CloneImage(image,0,0,MagickTrue,exception));
fx_info=AcquireFxThreadSet(image,expression,exception);
if (fx_info == (FxInfo **) NULL)
return((Image *) NULL);
fx_image=CloneImage(image,0,0,MagickTrue,exception);
if (fx_image == (Image *) NULL)
{
fx_info=DestroyFxThreadSet(fx_info);
return((Image *) NULL);
}
if (SetImageStorageClass(fx_image,DirectClass,exception) == MagickFalse)
{
fx_info=DestroyFxThreadSet(fx_info);
fx_image=DestroyImage(fx_image);
return((Image *) NULL);
}
/*
Fx image.
*/
status=MagickTrue;
progress=0;
image_view=AcquireVirtualCacheView(image,exception);
fx_view=AcquireAuthenticCacheView(fx_image,exception);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static) shared(progress,status) \
magick_number_threads(image,fx_image,fx_image->rows,1)
#endif
for (y=0; y < (ssize_t) fx_image->rows; y++)
{
const int
id = GetOpenMPThreadId();
register const Quantum
*magick_restrict p;
register Quantum
*magick_restrict q;
register ssize_t
x;
if (status == MagickFalse)
continue;
p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1,exception);
q=QueueCacheViewAuthenticPixels(fx_view,0,y,fx_image->columns,1,exception);
if ((p == (const Quantum *) NULL) || (q == (Quantum *) NULL))
{
status=MagickFalse;
continue;
}
for (x=0; x < (ssize_t) fx_image->columns; x++)
{
register ssize_t
i;
for (i=0; i < (ssize_t) GetPixelChannels(image); i++)
{
double
alpha;
PixelChannel channel = GetPixelChannelChannel(image,i);
PixelTrait traits = GetPixelChannelTraits(image,channel);
PixelTrait fx_traits=GetPixelChannelTraits(fx_image,channel);
if ((traits == UndefinedPixelTrait) ||
(fx_traits == UndefinedPixelTrait))
continue;
if ((fx_traits & CopyPixelTrait) != 0)
{
SetPixelChannel(fx_image,channel,p[i],q);
continue;
}
alpha=0.0;
(void) FxEvaluateChannelExpression(fx_info[id],channel,x,y,&alpha,
exception);
q[i]=ClampToQuantum(QuantumRange*alpha);
}
p+=GetPixelChannels(image);
q+=GetPixelChannels(fx_image);
}
if (SyncCacheViewAuthenticPixels(fx_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,FxImageTag,progress,image->rows);
if (proceed == MagickFalse)
status=MagickFalse;
}
}
fx_view=DestroyCacheView(fx_view);
image_view=DestroyCacheView(image_view);
fx_info=DestroyFxThreadSet(fx_info);
if (status == MagickFalse)
fx_image=DestroyImage(fx_image);
return(fx_image);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% I m p l o d e I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% ImplodeImage() creates a new image that is a copy of an existing
% one with the image pixels "implode" by the specified percentage. It
% allocates the memory necessary for the new Image structure and returns a
% pointer to the new image.
%
% The format of the ImplodeImage method is:
%
% Image *ImplodeImage(const Image *image,const double amount,
% const PixelInterpolateMethod method,ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o implode_image: Method ImplodeImage returns a pointer to the image
% after it is implode. A null image is returned if there is a memory
% shortage.
%
% o image: the image.
%
% o amount: Define the extent of the implosion.
%
% o method: the pixel interpolation method.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport Image *ImplodeImage(const Image *image,const double amount,
const PixelInterpolateMethod method,ExceptionInfo *exception)
{
#define ImplodeImageTag "Implode/Image"
CacheView
*canvas_view,
*implode_view,
*interpolate_view;
double
radius;
Image
*canvas_image,
*implode_image;
MagickBooleanType
status;
MagickOffsetType
progress;
PointInfo
center,
scale;
ssize_t
y;
/*
Initialize implode image attributes.
*/
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickCoreSignature);
canvas_image=CloneImage(image,0,0,MagickTrue,exception);
if (canvas_image == (Image *) NULL)
return((Image *) NULL);
if ((canvas_image->alpha_trait == UndefinedPixelTrait) &&
(canvas_image->background_color.alpha != OpaqueAlpha))
(void) SetImageAlphaChannel(canvas_image,OpaqueAlphaChannel,exception);
implode_image=CloneImage(canvas_image,0,0,MagickTrue,exception);
if (implode_image == (Image *) NULL)
{
canvas_image=DestroyImage(canvas_image);
return((Image *) NULL);
}
if (SetImageStorageClass(implode_image,DirectClass,exception) == MagickFalse)
{
canvas_image=DestroyImage(canvas_image);
implode_image=DestroyImage(implode_image);
return((Image *) NULL);
}
/*
Compute scaling factor.
*/
scale.x=1.0;
scale.y=1.0;
center.x=0.5*canvas_image->columns;
center.y=0.5*canvas_image->rows;
radius=center.x;
if (canvas_image->columns > canvas_image->rows)
scale.y=(double) canvas_image->columns/(double) canvas_image->rows;
else
if (canvas_image->columns < canvas_image->rows)
{
scale.x=(double) canvas_image->rows/(double) canvas_image->columns;
radius=center.y;
}
/*
Implode image.
*/
status=MagickTrue;
progress=0;
canvas_view=AcquireVirtualCacheView(canvas_image,exception);
interpolate_view=AcquireVirtualCacheView(canvas_image,exception);
implode_view=AcquireAuthenticCacheView(implode_image,exception);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static) shared(progress,status) \
magick_number_threads(canvas_image,implode_image,canvas_image->rows,1)
#endif
for (y=0; y < (ssize_t) canvas_image->rows; y++)
{
double
distance;
PointInfo
delta;
register const Quantum
*magick_restrict p;
register ssize_t
x;
register Quantum
*magick_restrict q;
if (status == MagickFalse)
continue;
p=GetCacheViewVirtualPixels(canvas_view,0,y,canvas_image->columns,1,
exception);
q=QueueCacheViewAuthenticPixels(implode_view,0,y,implode_image->columns,1,
exception);
if ((p == (const Quantum *) NULL) || (q == (Quantum *) NULL))
{
status=MagickFalse;
continue;
}
delta.y=scale.y*(double) (y-center.y);
for (x=0; x < (ssize_t) canvas_image->columns; x++)
{
register ssize_t
i;
/*
Determine if the pixel is within an ellipse.
*/
delta.x=scale.x*(double) (x-center.x);
distance=delta.x*delta.x+delta.y*delta.y;
if (distance >= (radius*radius))
for (i=0; i < (ssize_t) GetPixelChannels(canvas_image); i++)
{
PixelChannel channel = GetPixelChannelChannel(canvas_image,i);
PixelTrait traits = GetPixelChannelTraits(canvas_image,channel);
PixelTrait implode_traits = GetPixelChannelTraits(implode_image,
channel);
if ((traits == UndefinedPixelTrait) ||
(implode_traits == UndefinedPixelTrait))
continue;
SetPixelChannel(implode_image,channel,p[i],q);
}
else
{
double
factor;
/*
Implode the pixel.
*/
factor=1.0;
if (distance > 0.0)
factor=pow(sin(MagickPI*sqrt((double) distance)/radius/2),-amount);
status=InterpolatePixelChannels(canvas_image,interpolate_view,
implode_image,method,(double) (factor*delta.x/scale.x+center.x),
(double) (factor*delta.y/scale.y+center.y),q,exception);
if (status == MagickFalse)
break;
}
p+=GetPixelChannels(canvas_image);
q+=GetPixelChannels(implode_image);
}
if (SyncCacheViewAuthenticPixels(implode_view,exception) == MagickFalse)
status=MagickFalse;
if (canvas_image->progress_monitor != (MagickProgressMonitor) NULL)
{
MagickBooleanType
proceed;
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp atomic
#endif
progress++;
proceed=SetImageProgress(canvas_image,ImplodeImageTag,progress,
canvas_image->rows);
if (proceed == MagickFalse)
status=MagickFalse;
}
}
implode_view=DestroyCacheView(implode_view);
interpolate_view=DestroyCacheView(interpolate_view);
canvas_view=DestroyCacheView(canvas_view);
canvas_image=DestroyImage(canvas_image);
if (status == MagickFalse)
implode_image=DestroyImage(implode_image);
return(implode_image);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% M o r p h I m a g e s %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% The MorphImages() method requires a minimum of two images. The first
% image is transformed into the second by a number of intervening images
% as specified by frames.
%
% The format of the MorphImage method is:
%
% Image *MorphImages(const Image *image,const size_t number_frames,
% ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o number_frames: Define the number of in-between image to generate.
% The more in-between frames, the smoother the morph.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport Image *MorphImages(const Image *image,const size_t number_frames,
ExceptionInfo *exception)
{
#define MorphImageTag "Morph/Image"
double
alpha,
beta;
Image
*morph_image,
*morph_images;
MagickBooleanType
status;
MagickOffsetType
scene;
register const Image
*next;
register ssize_t
n;
ssize_t
y;
/*
Clone first frame in sequence.
*/
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickCoreSignature);
morph_images=CloneImage(image,0,0,MagickTrue,exception);
if (morph_images == (Image *) NULL)
return((Image *) NULL);
if (GetNextImageInList(image) == (Image *) NULL)
{
/*
Morph single image.
*/
for (n=1; n < (ssize_t) number_frames; n++)
{
morph_image=CloneImage(image,0,0,MagickTrue,exception);
if (morph_image == (Image *) NULL)
{
morph_images=DestroyImageList(morph_images);
return((Image *) NULL);
}
AppendImageToList(&morph_images,morph_image);
if (image->progress_monitor != (MagickProgressMonitor) NULL)
{
MagickBooleanType
proceed;
proceed=SetImageProgress(image,MorphImageTag,(MagickOffsetType) n,
number_frames);
if (proceed == MagickFalse)
status=MagickFalse;
}
}
return(GetFirstImageInList(morph_images));
}
/*
Morph image sequence.
*/
status=MagickTrue;
scene=0;
next=image;
for ( ; GetNextImageInList(next) != (Image *) NULL; next=GetNextImageInList(next))
{
for (n=0; n < (ssize_t) number_frames; n++)
{
CacheView
*image_view,
*morph_view;
beta=(double) (n+1.0)/(double) (number_frames+1.0);
alpha=1.0-beta;
morph_image=ResizeImage(next,(size_t) (alpha*next->columns+beta*
GetNextImageInList(next)->columns+0.5),(size_t) (alpha*next->rows+beta*
GetNextImageInList(next)->rows+0.5),next->filter,exception);
if (morph_image == (Image *) NULL)
{
morph_images=DestroyImageList(morph_images);
return((Image *) NULL);
}
status=SetImageStorageClass(morph_image,DirectClass,exception);
if (status == MagickFalse)
{
morph_image=DestroyImage(morph_image);
return((Image *) NULL);
}
AppendImageToList(&morph_images,morph_image);
morph_images=GetLastImageInList(morph_images);
morph_image=ResizeImage(GetNextImageInList(next),morph_images->columns,
morph_images->rows,GetNextImageInList(next)->filter,exception);
if (morph_image == (Image *) NULL)
{
morph_images=DestroyImageList(morph_images);
return((Image *) NULL);
}
image_view=AcquireVirtualCacheView(morph_image,exception);
morph_view=AcquireAuthenticCacheView(morph_images,exception);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static) shared(status) \
magick_number_threads(morph_image,morph_image,morph_image->rows,1)
#endif
for (y=0; y < (ssize_t) morph_images->rows; y++)
{
MagickBooleanType
sync;
register const Quantum
*magick_restrict p;
register ssize_t
x;
register Quantum
*magick_restrict q;
if (status == MagickFalse)
continue;
p=GetCacheViewVirtualPixels(image_view,0,y,morph_image->columns,1,
exception);
q=GetCacheViewAuthenticPixels(morph_view,0,y,morph_images->columns,1,
exception);
if ((p == (const Quantum *) NULL) || (q == (Quantum *) NULL))
{
status=MagickFalse;
continue;
}
for (x=0; x < (ssize_t) morph_images->columns; x++)
{
register ssize_t
i;
for (i=0; i < (ssize_t) GetPixelChannels(morph_image); i++)
{
PixelChannel channel = GetPixelChannelChannel(morph_image,i);
PixelTrait traits = GetPixelChannelTraits(morph_image,channel);
PixelTrait morph_traits=GetPixelChannelTraits(morph_images,channel);
if ((traits == UndefinedPixelTrait) ||
(morph_traits == UndefinedPixelTrait))
continue;
if ((morph_traits & CopyPixelTrait) != 0)
{
SetPixelChannel(morph_image,channel,p[i],q);
continue;
}
SetPixelChannel(morph_image,channel,ClampToQuantum(alpha*
GetPixelChannel(morph_images,channel,q)+beta*p[i]),q);
}
p+=GetPixelChannels(morph_image);
q+=GetPixelChannels(morph_images);
}
sync=SyncCacheViewAuthenticPixels(morph_view,exception);
if (sync == MagickFalse)
status=MagickFalse;
}
morph_view=DestroyCacheView(morph_view);
image_view=DestroyCacheView(image_view);
morph_image=DestroyImage(morph_image);
}
if (n < (ssize_t) number_frames)
break;
/*
Clone last frame in sequence.
*/
morph_image=CloneImage(GetNextImageInList(next),0,0,MagickTrue,exception);
if (morph_image == (Image *) NULL)
{
morph_images=DestroyImageList(morph_images);
return((Image *) NULL);
}
AppendImageToList(&morph_images,morph_image);
morph_images=GetLastImageInList(morph_images);
if (image->progress_monitor != (MagickProgressMonitor) NULL)
{
MagickBooleanType
proceed;
proceed=SetImageProgress(image,MorphImageTag,scene,
GetImageListLength(image));
if (proceed == MagickFalse)
status=MagickFalse;
}
scene++;
}
if (GetNextImageInList(next) != (Image *) NULL)
{
morph_images=DestroyImageList(morph_images);
return((Image *) NULL);
}
return(GetFirstImageInList(morph_images));
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% P l a s m a I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% PlasmaImage() initializes an image with plasma fractal values. The image
% must be initialized with a base color and the random number generator
% seeded before this method is called.
%
% The format of the PlasmaImage method is:
%
% MagickBooleanType PlasmaImage(Image *image,const SegmentInfo *segment,
% size_t attenuate,size_t depth,ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o segment: Define the region to apply plasma fractals values.
%
% o attenuate: Define the plasma attenuation factor.
%
% o depth: Limit the plasma recursion depth.
%
% o exception: return any errors or warnings in this structure.
%
*/
static inline Quantum PlasmaPixel(RandomInfo *random_info,
const double pixel,const double noise)
{
Quantum
plasma;
plasma=ClampToQuantum(pixel+noise*GetPseudoRandomValue(random_info)-
noise/2.0);
if (plasma <= 0)
return((Quantum) 0);
if (plasma >= QuantumRange)
return(QuantumRange);
return(plasma);
}
static MagickBooleanType PlasmaImageProxy(Image *image,CacheView *image_view,
CacheView *u_view,CacheView *v_view,RandomInfo *random_info,
const SegmentInfo *segment,size_t attenuate,size_t depth,
ExceptionInfo *exception)
{
double
plasma;
register const Quantum
*magick_restrict u,
*magick_restrict v;
register Quantum
*magick_restrict q;
register ssize_t
i;
ssize_t
x,
x_mid,
y,
y_mid;
if ((fabs(segment->x2-segment->x1) <= MagickEpsilon) &&
(fabs(segment->y2-segment->y1) <= MagickEpsilon))
return(MagickTrue);
if (depth != 0)
{
MagickBooleanType
status;
SegmentInfo
local_info;
/*
Divide the area into quadrants and recurse.
*/
depth--;
attenuate++;
x_mid=(ssize_t) ceil((segment->x1+segment->x2)/2-0.5);
y_mid=(ssize_t) ceil((segment->y1+segment->y2)/2-0.5);
local_info=(*segment);
local_info.x2=(double) x_mid;
local_info.y2=(double) y_mid;
(void) PlasmaImageProxy(image,image_view,u_view,v_view,random_info,
&local_info,attenuate,depth,exception);
local_info=(*segment);
local_info.y1=(double) y_mid;
local_info.x2=(double) x_mid;
(void) PlasmaImageProxy(image,image_view,u_view,v_view,random_info,
&local_info,attenuate,depth,exception);
local_info=(*segment);
local_info.x1=(double) x_mid;
local_info.y2=(double) y_mid;
(void) PlasmaImageProxy(image,image_view,u_view,v_view,random_info,
&local_info,attenuate,depth,exception);
local_info=(*segment);
local_info.x1=(double) x_mid;
local_info.y1=(double) y_mid;
status=PlasmaImageProxy(image,image_view,u_view,v_view,random_info,
&local_info,attenuate,depth,exception);
return(status);
}
x_mid=(ssize_t) ceil((segment->x1+segment->x2)/2-0.5);
y_mid=(ssize_t) ceil((segment->y1+segment->y2)/2-0.5);
if ((fabs(segment->x1-x_mid) < MagickEpsilon) &&
(fabs(segment->x2-x_mid) < MagickEpsilon) &&
(fabs(segment->y1-y_mid) < MagickEpsilon) &&
(fabs(segment->y2-y_mid) < MagickEpsilon))
return(MagickFalse);
/*
Average pixels and apply plasma.
*/
plasma=(double) QuantumRange/(2.0*attenuate);
if ((fabs(segment->x1-x_mid) > MagickEpsilon) ||
(fabs(segment->x2-x_mid) > MagickEpsilon))
{
/*
Left pixel.
*/
x=(ssize_t) ceil(segment->x1-0.5);
u=GetCacheViewVirtualPixels(u_view,x,(ssize_t) ceil(segment->y1-0.5),1,1,
exception);
v=GetCacheViewVirtualPixels(v_view,x,(ssize_t) ceil(segment->y2-0.5),1,1,
exception);
q=QueueCacheViewAuthenticPixels(image_view,x,y_mid,1,1,exception);
if ((u == (const Quantum *) NULL) || (v == (const Quantum *) NULL) ||
(q == (Quantum *) NULL))
return(MagickTrue);
for (i=0; i < (ssize_t) GetPixelChannels(image); i++)
{
PixelChannel channel = GetPixelChannelChannel(image,i);
PixelTrait traits = GetPixelChannelTraits(image,channel);
if (traits == UndefinedPixelTrait)
continue;
q[i]=PlasmaPixel(random_info,(u[i]+v[i])/2.0,plasma);
}
(void) SyncCacheViewAuthenticPixels(image_view,exception);
if (fabs(segment->x1-segment->x2) > MagickEpsilon)
{
/*
Right pixel.
*/
x=(ssize_t) ceil(segment->x2-0.5);
u=GetCacheViewVirtualPixels(u_view,x,(ssize_t) ceil(segment->y1-0.5),
1,1,exception);
v=GetCacheViewVirtualPixels(v_view,x,(ssize_t) ceil(segment->y2-0.5),
1,1,exception);
q=QueueCacheViewAuthenticPixels(image_view,x,y_mid,1,1,exception);
if ((u == (const Quantum *) NULL) || (v == (const Quantum *) NULL) ||
(q == (Quantum *) NULL))
return(MagickTrue);
for (i=0; i < (ssize_t) GetPixelChannels(image); i++)
{
PixelChannel channel = GetPixelChannelChannel(image,i);
PixelTrait traits = GetPixelChannelTraits(image,channel);
if (traits == UndefinedPixelTrait)
continue;
q[i]=PlasmaPixel(random_info,(u[i]+v[i])/2.0,plasma);
}
(void) SyncCacheViewAuthenticPixels(image_view,exception);
}
}
if ((fabs(segment->y1-y_mid) > MagickEpsilon) ||
(fabs(segment->y2-y_mid) > MagickEpsilon))
{
if ((fabs(segment->x1-x_mid) > MagickEpsilon) ||
(fabs(segment->y2-y_mid) > MagickEpsilon))
{
/*
Bottom pixel.
*/
y=(ssize_t) ceil(segment->y2-0.5);
u=GetCacheViewVirtualPixels(u_view,(ssize_t) ceil(segment->x1-0.5),y,
1,1,exception);
v=GetCacheViewVirtualPixels(v_view,(ssize_t) ceil(segment->x2-0.5),y,
1,1,exception);
q=QueueCacheViewAuthenticPixels(image_view,x_mid,y,1,1,exception);
if ((u == (const Quantum *) NULL) || (v == (const Quantum *) NULL) ||
(q == (Quantum *) NULL))
return(MagickTrue);
for (i=0; i < (ssize_t) GetPixelChannels(image); i++)
{
PixelChannel channel = GetPixelChannelChannel(image,i);
PixelTrait traits = GetPixelChannelTraits(image,channel);
if (traits == UndefinedPixelTrait)
continue;
q[i]=PlasmaPixel(random_info,(u[i]+v[i])/2.0,plasma);
}
(void) SyncCacheViewAuthenticPixels(image_view,exception);
}
if (fabs(segment->y1-segment->y2) > MagickEpsilon)
{
/*
Top pixel.
*/
y=(ssize_t) ceil(segment->y1-0.5);
u=GetCacheViewVirtualPixels(u_view,(ssize_t) ceil(segment->x1-0.5),y,
1,1,exception);
v=GetCacheViewVirtualPixels(v_view,(ssize_t) ceil(segment->x2-0.5),y,
1,1,exception);
q=QueueCacheViewAuthenticPixels(image_view,x_mid,y,1,1,exception);
if ((u == (const Quantum *) NULL) || (v == (const Quantum *) NULL) ||
(q == (Quantum *) NULL))
return(MagickTrue);
for (i=0; i < (ssize_t) GetPixelChannels(image); i++)
{
PixelChannel channel = GetPixelChannelChannel(image,i);
PixelTrait traits = GetPixelChannelTraits(image,channel);
if (traits == UndefinedPixelTrait)
continue;
q[i]=PlasmaPixel(random_info,(u[i]+v[i])/2.0,plasma);
}
(void) SyncCacheViewAuthenticPixels(image_view,exception);
}
}
if ((fabs(segment->x1-segment->x2) > MagickEpsilon) ||
(fabs(segment->y1-segment->y2) > MagickEpsilon))
{
/*
Middle pixel.
*/
x=(ssize_t) ceil(segment->x1-0.5);
y=(ssize_t) ceil(segment->y1-0.5);
u=GetCacheViewVirtualPixels(u_view,x,y,1,1,exception);
x=(ssize_t) ceil(segment->x2-0.5);
y=(ssize_t) ceil(segment->y2-0.5);
v=GetCacheViewVirtualPixels(v_view,x,y,1,1,exception);
q=QueueCacheViewAuthenticPixels(image_view,x_mid,y_mid,1,1,exception);
if ((u == (const Quantum *) NULL) || (v == (const Quantum *) NULL) ||
(q == (Quantum *) NULL))
return(MagickTrue);
for (i=0; i < (ssize_t) GetPixelChannels(image); i++)
{
PixelChannel channel = GetPixelChannelChannel(image,i);
PixelTrait traits = GetPixelChannelTraits(image,channel);
if (traits == UndefinedPixelTrait)
continue;
q[i]=PlasmaPixel(random_info,(u[i]+v[i])/2.0,plasma);
}
(void) SyncCacheViewAuthenticPixels(image_view,exception);
}
if ((fabs(segment->x2-segment->x1) < 3.0) &&
(fabs(segment->y2-segment->y1) < 3.0))
return(MagickTrue);
return(MagickFalse);
}
MagickExport MagickBooleanType PlasmaImage(Image *image,
const SegmentInfo *segment,size_t attenuate,size_t depth,
ExceptionInfo *exception)
{
CacheView
*image_view,
*u_view,
*v_view;
MagickBooleanType
status;
RandomInfo
*random_info;
assert(image != (Image *) NULL);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"...");
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"...");
if (SetImageStorageClass(image,DirectClass,exception) == MagickFalse)
return(MagickFalse);
image_view=AcquireAuthenticCacheView(image,exception);
u_view=AcquireVirtualCacheView(image,exception);
v_view=AcquireVirtualCacheView(image,exception);
random_info=AcquireRandomInfo();
status=PlasmaImageProxy(image,image_view,u_view,v_view,random_info,segment,
attenuate,depth,exception);
random_info=DestroyRandomInfo(random_info);
v_view=DestroyCacheView(v_view);
u_view=DestroyCacheView(u_view);
image_view=DestroyCacheView(image_view);
return(status);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% P o l a r o i d I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% PolaroidImage() simulates a Polaroid picture.
%
% The format of the PolaroidImage method is:
%
% Image *PolaroidImage(const Image *image,const DrawInfo *draw_info,
% const char *caption,const double angle,
% const PixelInterpolateMethod method,ExceptionInfo exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o draw_info: the draw info.
%
% o caption: the Polaroid caption.
%
% o angle: Apply the effect along this angle.
%
% o method: the pixel interpolation method.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport Image *PolaroidImage(const Image *image,const DrawInfo *draw_info,
const char *caption,const double angle,const PixelInterpolateMethod method,
ExceptionInfo *exception)
{
Image
*bend_image,
*caption_image,
*flop_image,
*picture_image,
*polaroid_image,
*rotate_image,
*trim_image;
size_t
height;
ssize_t
quantum;
/*
Simulate a Polaroid picture.
*/
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickCoreSignature);
quantum=(ssize_t) MagickMax(MagickMax((double) image->columns,(double)
image->rows)/25.0,10.0);
height=image->rows+2*quantum;
caption_image=(Image *) NULL;
if (caption != (const char *) NULL)
{
char
*text;
/*
Generate caption image.
*/
caption_image=CloneImage(image,image->columns,1,MagickTrue,exception);
if (caption_image == (Image *) NULL)
return((Image *) NULL);
text=InterpretImageProperties((ImageInfo *) NULL,(Image *) image,caption,
exception);
if (text != (char *) NULL)
{
char
geometry[MagickPathExtent];
DrawInfo
*annotate_info;
MagickBooleanType
status;
ssize_t
count;
TypeMetric
metrics;
annotate_info=CloneDrawInfo((const ImageInfo *) NULL,draw_info);
(void) CloneString(&annotate_info->text,text);
count=FormatMagickCaption(caption_image,annotate_info,MagickTrue,
&metrics,&text,exception);
status=SetImageExtent(caption_image,image->columns,(size_t)
((count+1)*(metrics.ascent-metrics.descent)+0.5),exception);
if (status == MagickFalse)
caption_image=DestroyImage(caption_image);
else
{
caption_image->background_color=image->border_color;
(void) SetImageBackgroundColor(caption_image,exception);
(void) CloneString(&annotate_info->text,text);
(void) FormatLocaleString(geometry,MagickPathExtent,"+0+%.20g",
metrics.ascent);
if (annotate_info->gravity == UndefinedGravity)
(void) CloneString(&annotate_info->geometry,AcquireString(
geometry));
(void) AnnotateImage(caption_image,annotate_info,exception);
height+=caption_image->rows;
}
annotate_info=DestroyDrawInfo(annotate_info);
text=DestroyString(text);
}
}
picture_image=CloneImage(image,image->columns+2*quantum,height,MagickTrue,
exception);
if (picture_image == (Image *) NULL)
{
if (caption_image != (Image *) NULL)
caption_image=DestroyImage(caption_image);
return((Image *) NULL);
}
picture_image->background_color=image->border_color;
(void) SetImageBackgroundColor(picture_image,exception);
(void) CompositeImage(picture_image,image,OverCompositeOp,MagickTrue,quantum,
quantum,exception);
if (caption_image != (Image *) NULL)
{
(void) CompositeImage(picture_image,caption_image,OverCompositeOp,
MagickTrue,quantum,(ssize_t) (image->rows+3*quantum/2),exception);
caption_image=DestroyImage(caption_image);
}
(void) QueryColorCompliance("none",AllCompliance,
&picture_image->background_color,exception);
(void) SetImageAlphaChannel(picture_image,OpaqueAlphaChannel,exception);
rotate_image=RotateImage(picture_image,90.0,exception);
picture_image=DestroyImage(picture_image);
if (rotate_image == (Image *) NULL)
return((Image *) NULL);
picture_image=rotate_image;
bend_image=WaveImage(picture_image,0.01*picture_image->rows,2.0*
picture_image->columns,method,exception);
picture_image=DestroyImage(picture_image);
if (bend_image == (Image *) NULL)
return((Image *) NULL);
picture_image=bend_image;
rotate_image=RotateImage(picture_image,-90.0,exception);
picture_image=DestroyImage(picture_image);
if (rotate_image == (Image *) NULL)
return((Image *) NULL);
picture_image=rotate_image;
picture_image->background_color=image->background_color;
polaroid_image=ShadowImage(picture_image,80.0,2.0,quantum/3,quantum/3,
exception);
if (polaroid_image == (Image *) NULL)
{
picture_image=DestroyImage(picture_image);
return(picture_image);
}
flop_image=FlopImage(polaroid_image,exception);
polaroid_image=DestroyImage(polaroid_image);
if (flop_image == (Image *) NULL)
{
picture_image=DestroyImage(picture_image);
return(picture_image);
}
polaroid_image=flop_image;
(void) CompositeImage(polaroid_image,picture_image,OverCompositeOp,
MagickTrue,(ssize_t) (-0.01*picture_image->columns/2.0),0L,exception);
picture_image=DestroyImage(picture_image);
(void) QueryColorCompliance("none",AllCompliance,
&polaroid_image->background_color,exception);
rotate_image=RotateImage(polaroid_image,angle,exception);
polaroid_image=DestroyImage(polaroid_image);
if (rotate_image == (Image *) NULL)
return((Image *) NULL);
polaroid_image=rotate_image;
trim_image=TrimImage(polaroid_image,exception);
polaroid_image=DestroyImage(polaroid_image);
if (trim_image == (Image *) NULL)
return((Image *) NULL);
polaroid_image=trim_image;
return(polaroid_image);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% S e p i a T o n e I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% MagickSepiaToneImage() applies a special effect to the image, similar to the
% effect achieved in a photo darkroom by sepia toning. Threshold ranges from
% 0 to QuantumRange and is a measure of the extent of the sepia toning. A
% threshold of 80% is a good starting point for a reasonable tone.
%
% The format of the SepiaToneImage method is:
%
% Image *SepiaToneImage(const Image *image,const double threshold,
% ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o threshold: the tone threshold.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport Image *SepiaToneImage(const Image *image,const double threshold,
ExceptionInfo *exception)
{
#define SepiaToneImageTag "SepiaTone/Image"
CacheView
*image_view,
*sepia_view;
Image
*sepia_image;
MagickBooleanType
status;
MagickOffsetType
progress;
ssize_t
y;
/*
Initialize sepia-toned image attributes.
*/
assert(image != (const Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickCoreSignature);
sepia_image=CloneImage(image,0,0,MagickTrue,exception);
if (sepia_image == (Image *) NULL)
return((Image *) NULL);
if (SetImageStorageClass(sepia_image,DirectClass,exception) == MagickFalse)
{
sepia_image=DestroyImage(sepia_image);
return((Image *) NULL);
}
/*
Tone each row of the image.
*/
status=MagickTrue;
progress=0;
image_view=AcquireVirtualCacheView(image,exception);
sepia_view=AcquireAuthenticCacheView(sepia_image,exception);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static) shared(progress,status) \
magick_number_threads(image,sepia_image,image->rows,1)
#endif
for (y=0; y < (ssize_t) image->rows; y++)
{
register const Quantum
*magick_restrict p;
register ssize_t
x;
register Quantum
*magick_restrict q;
if (status == MagickFalse)
continue;
p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1,exception);
q=GetCacheViewAuthenticPixels(sepia_view,0,y,sepia_image->columns,1,
exception);
if ((p == (const Quantum *) NULL) || (q == (Quantum *) NULL))
{
status=MagickFalse;
continue;
}
for (x=0; x < (ssize_t) image->columns; x++)
{
double
intensity,
tone;
intensity=GetPixelIntensity(image,p);
tone=intensity > threshold ? (double) QuantumRange : intensity+
(double) QuantumRange-threshold;
SetPixelRed(sepia_image,ClampToQuantum(tone),q);
tone=intensity > (7.0*threshold/6.0) ? (double) QuantumRange :
intensity+(double) QuantumRange-7.0*threshold/6.0;
SetPixelGreen(sepia_image,ClampToQuantum(tone),q);
tone=intensity < (threshold/6.0) ? 0 : intensity-threshold/6.0;
SetPixelBlue(sepia_image,ClampToQuantum(tone),q);
tone=threshold/7.0;
if ((double) GetPixelGreen(image,q) < tone)
SetPixelGreen(sepia_image,ClampToQuantum(tone),q);
if ((double) GetPixelBlue(image,q) < tone)
SetPixelBlue(sepia_image,ClampToQuantum(tone),q);
SetPixelAlpha(sepia_image,GetPixelAlpha(image,p),q);
p+=GetPixelChannels(image);
q+=GetPixelChannels(sepia_image);
}
if (SyncCacheViewAuthenticPixels(sepia_view,exception) == MagickFalse)
status=MagickFalse;
if (image->progress_monitor != (MagickProgressMonitor) NULL)
{
MagickBooleanType
proceed;
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp atomic
#endif
progress++;
proceed=SetImageProgress(image,SepiaToneImageTag,progress,image->rows);
if (proceed == MagickFalse)
status=MagickFalse;
}
}
sepia_view=DestroyCacheView(sepia_view);
image_view=DestroyCacheView(image_view);
(void) NormalizeImage(sepia_image,exception);
(void) ContrastImage(sepia_image,MagickTrue,exception);
if (status == MagickFalse)
sepia_image=DestroyImage(sepia_image);
return(sepia_image);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% S h a d o w I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% ShadowImage() simulates a shadow from the specified image and returns it.
%
% The format of the ShadowImage method is:
%
% Image *ShadowImage(const Image *image,const double alpha,
% const double sigma,const ssize_t x_offset,const ssize_t y_offset,
% ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o alpha: percentage transparency.
%
% o sigma: the standard deviation of the Gaussian, in pixels.
%
% o x_offset: the shadow x-offset.
%
% o y_offset: the shadow y-offset.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport Image *ShadowImage(const Image *image,const double alpha,
const double sigma,const ssize_t x_offset,const ssize_t y_offset,
ExceptionInfo *exception)
{
#define ShadowImageTag "Shadow/Image"
CacheView
*image_view;
ChannelType
channel_mask;
Image
*border_image,
*clone_image,
*shadow_image;
MagickBooleanType
status;
PixelInfo
background_color;
RectangleInfo
border_info;
ssize_t
y;
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickCoreSignature);
clone_image=CloneImage(image,0,0,MagickTrue,exception);
if (clone_image == (Image *) NULL)
return((Image *) NULL);
if (IsGrayColorspace(image->colorspace) != MagickFalse)
(void) SetImageColorspace(clone_image,sRGBColorspace,exception);
(void) SetImageVirtualPixelMethod(clone_image,EdgeVirtualPixelMethod,
exception);
border_info.width=(size_t) floor(2.0*sigma+0.5);
border_info.height=(size_t) floor(2.0*sigma+0.5);
border_info.x=0;
border_info.y=0;
(void) QueryColorCompliance("none",AllCompliance,&clone_image->border_color,
exception);
clone_image->alpha_trait=BlendPixelTrait;
border_image=BorderImage(clone_image,&border_info,OverCompositeOp,exception);
clone_image=DestroyImage(clone_image);
if (border_image == (Image *) NULL)
return((Image *) NULL);
if (border_image->alpha_trait == UndefinedPixelTrait)
(void) SetImageAlphaChannel(border_image,OpaqueAlphaChannel,exception);
/*
Shadow image.
*/
status=MagickTrue;
background_color=border_image->background_color;
background_color.alpha_trait=BlendPixelTrait;
image_view=AcquireAuthenticCacheView(border_image,exception);
for (y=0; y < (ssize_t) border_image->rows; y++)
{
register Quantum
*magick_restrict q;
register ssize_t
x;
if (status == MagickFalse)
continue;
q=QueueCacheViewAuthenticPixels(image_view,0,y,border_image->columns,1,
exception);
if (q == (Quantum *) NULL)
{
status=MagickFalse;
continue;
}
for (x=0; x < (ssize_t) border_image->columns; x++)
{
if (border_image->alpha_trait != UndefinedPixelTrait)
background_color.alpha=GetPixelAlpha(border_image,q)*alpha/100.0;
SetPixelViaPixelInfo(border_image,&background_color,q);
q+=GetPixelChannels(border_image);
}
if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
status=MagickFalse;
}
image_view=DestroyCacheView(image_view);
if (status == MagickFalse)
{
border_image=DestroyImage(border_image);
return((Image *) NULL);
}
channel_mask=SetImageChannelMask(border_image,AlphaChannel);
shadow_image=BlurImage(border_image,0.0,sigma,exception);
border_image=DestroyImage(border_image);
if (shadow_image == (Image *) NULL)
return((Image *) NULL);
(void) SetPixelChannelMask(shadow_image,channel_mask);
if (shadow_image->page.width == 0)
shadow_image->page.width=shadow_image->columns;
if (shadow_image->page.height == 0)
shadow_image->page.height=shadow_image->rows;
shadow_image->page.width+=x_offset-(ssize_t) border_info.width;
shadow_image->page.height+=y_offset-(ssize_t) border_info.height;
shadow_image->page.x+=x_offset-(ssize_t) border_info.width;
shadow_image->page.y+=y_offset-(ssize_t) border_info.height;
return(shadow_image);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% S k e t c h I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% SketchImage() simulates a pencil sketch. We convolve the image with a
% Gaussian operator of the given radius and standard deviation (sigma). For
% reasonable results, radius should be larger than sigma. Use a radius of 0
% and SketchImage() selects a suitable radius for you. Angle gives the angle
% of the sketch.
%
% The format of the SketchImage method is:
%
% Image *SketchImage(const Image *image,const double radius,
% const double sigma,const double angle,ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o radius: the radius of the Gaussian, in pixels, not counting the
% center pixel.
%
% o sigma: the standard deviation of the Gaussian, in pixels.
%
% o angle: apply the effect along this angle.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport Image *SketchImage(const Image *image,const double radius,
const double sigma,const double angle,ExceptionInfo *exception)
{
CacheView
*random_view;
Image
*blend_image,
*blur_image,
*dodge_image,
*random_image,
*sketch_image;
MagickBooleanType
status;
RandomInfo
**magick_restrict random_info;
ssize_t
y;
#if defined(MAGICKCORE_OPENMP_SUPPORT)
unsigned long
key;
#endif
/*
Sketch image.
*/
random_image=CloneImage(image,image->columns << 1,image->rows << 1,
MagickTrue,exception);
if (random_image == (Image *) NULL)
return((Image *) NULL);
status=MagickTrue;
random_info=AcquireRandomInfoThreadSet();
random_view=AcquireAuthenticCacheView(random_image,exception);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
key=GetRandomSecretKey(random_info[0]);
#pragma omp parallel for schedule(static) shared(status) \
magick_number_threads(random_image,random_image,random_image->rows,key == ~0UL)
#endif
for (y=0; y < (ssize_t) random_image->rows; y++)
{
const int
id = GetOpenMPThreadId();
register Quantum
*magick_restrict q;
register ssize_t
x;
if (status == MagickFalse)
continue;
q=QueueCacheViewAuthenticPixels(random_view,0,y,random_image->columns,1,
exception);
if (q == (Quantum *) NULL)
{
status=MagickFalse;
continue;
}
for (x=0; x < (ssize_t) random_image->columns; x++)
{
double
value;
register ssize_t
i;
value=GetPseudoRandomValue(random_info[id]);
for (i=0; i < (ssize_t) GetPixelChannels(random_image); i++)
{
PixelChannel channel = GetPixelChannelChannel(image,i);
PixelTrait traits = GetPixelChannelTraits(image,channel);
if (traits == UndefinedPixelTrait)
continue;
q[i]=ClampToQuantum(QuantumRange*value);
}
q+=GetPixelChannels(random_image);
}
if (SyncCacheViewAuthenticPixels(random_view,exception) == MagickFalse)
status=MagickFalse;
}
random_view=DestroyCacheView(random_view);
random_info=DestroyRandomInfoThreadSet(random_info);
if (status == MagickFalse)
{
random_image=DestroyImage(random_image);
return(random_image);
}
blur_image=MotionBlurImage(random_image,radius,sigma,angle,exception);
random_image=DestroyImage(random_image);
if (blur_image == (Image *) NULL)
return((Image *) NULL);
dodge_image=EdgeImage(blur_image,radius,exception);
blur_image=DestroyImage(blur_image);
if (dodge_image == (Image *) NULL)
return((Image *) NULL);
status=ClampImage(dodge_image,exception);
if (status != MagickFalse)
status=NormalizeImage(dodge_image,exception);
if (status != MagickFalse)
status=NegateImage(dodge_image,MagickFalse,exception);
if (status != MagickFalse)
status=TransformImage(&dodge_image,(char *) NULL,"50%",exception);
sketch_image=CloneImage(image,0,0,MagickTrue,exception);
if (sketch_image == (Image *) NULL)
{
dodge_image=DestroyImage(dodge_image);
return((Image *) NULL);
}
(void) CompositeImage(sketch_image,dodge_image,ColorDodgeCompositeOp,
MagickTrue,0,0,exception);
dodge_image=DestroyImage(dodge_image);
blend_image=CloneImage(image,0,0,MagickTrue,exception);
if (blend_image == (Image *) NULL)
{
sketch_image=DestroyImage(sketch_image);
return((Image *) NULL);
}
if (blend_image->alpha_trait != BlendPixelTrait)
(void) SetImageAlpha(blend_image,TransparentAlpha,exception);
(void) SetImageArtifact(blend_image,"compose:args","20x80");
(void) CompositeImage(sketch_image,blend_image,BlendCompositeOp,MagickTrue,
0,0,exception);
blend_image=DestroyImage(blend_image);
return(sketch_image);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% S o l a r i z e I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% SolarizeImage() applies a special effect to the image, similar to the effect
% achieved in a photo darkroom by selectively exposing areas of photo
% sensitive paper to light. Threshold ranges from 0 to QuantumRange and is a
% measure of the extent of the solarization.
%
% The format of the SolarizeImage method is:
%
% MagickBooleanType SolarizeImage(Image *image,const double threshold,
% ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o threshold: Define the extent of the solarization.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport MagickBooleanType SolarizeImage(Image *image,
const double threshold,ExceptionInfo *exception)
{
#define SolarizeImageTag "Solarize/Image"
CacheView
*image_view;
MagickBooleanType
status;
MagickOffsetType
progress;
ssize_t
y;
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
if (IsGrayColorspace(image->colorspace) != MagickFalse)
(void) SetImageColorspace(image,sRGBColorspace,exception);
if (image->storage_class == PseudoClass)
{
register ssize_t
i;
/*
Solarize colormap.
*/
for (i=0; i < (ssize_t) image->colors; i++)
{
if ((double) image->colormap[i].red > threshold)
image->colormap[i].red=QuantumRange-image->colormap[i].red;
if ((double) image->colormap[i].green > threshold)
image->colormap[i].green=QuantumRange-image->colormap[i].green;
if ((double) image->colormap[i].blue > threshold)
image->colormap[i].blue=QuantumRange-image->colormap[i].blue;
}
}
/*
Solarize image.
*/
status=MagickTrue;
progress=0;
image_view=AcquireAuthenticCacheView(image,exception);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static) shared(progress,status) \
magick_number_threads(image,image,image->rows,1)
#endif
for (y=0; y < (ssize_t) image->rows; y++)
{
register ssize_t
x;
register Quantum
*magick_restrict q;
if (status == MagickFalse)
continue;
q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception);
if (q == (Quantum *) NULL)
{
status=MagickFalse;
continue;
}
for (x=0; x < (ssize_t) image->columns; x++)
{
register ssize_t
i;
for (i=0; i < (ssize_t) GetPixelChannels(image); i++)
{
PixelChannel channel = GetPixelChannelChannel(image,i);
PixelTrait traits = GetPixelChannelTraits(image,channel);
if ((traits & UpdatePixelTrait) == 0)
continue;
if ((double) q[i] > threshold)
q[i]=QuantumRange-q[i];
}
q+=GetPixelChannels(image);
}
if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
status=MagickFalse;
if (image->progress_monitor != (MagickProgressMonitor) NULL)
{
MagickBooleanType
proceed;
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp atomic
#endif
progress++;
proceed=SetImageProgress(image,SolarizeImageTag,progress,image->rows);
if (proceed == MagickFalse)
status=MagickFalse;
}
}
image_view=DestroyCacheView(image_view);
return(status);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% S t e g a n o I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% SteganoImage() hides a digital watermark within the image. Recover
% the hidden watermark later to prove that the authenticity of an image.
% Offset defines the start position within the image to hide the watermark.
%
% The format of the SteganoImage method is:
%
% Image *SteganoImage(const Image *image,Image *watermark,
% ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o watermark: the watermark image.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport Image *SteganoImage(const Image *image,const Image *watermark,
ExceptionInfo *exception)
{
#define GetBit(alpha,i) ((((size_t) (alpha) >> (size_t) (i)) & 0x01) != 0)
#define SetBit(alpha,i,set) (Quantum) ((set) != 0 ? (size_t) (alpha) \
| (one << (size_t) (i)) : (size_t) (alpha) & ~(one << (size_t) (i)))
#define SteganoImageTag "Stegano/Image"
CacheView
*stegano_view,
*watermark_view;
Image
*stegano_image;
int
c;
MagickBooleanType
status;
PixelInfo
pixel;
register Quantum
*q;
register ssize_t
x;
size_t
depth,
one;
ssize_t
i,
j,
k,
y;
/*
Initialize steganographic image attributes.
*/
assert(image != (const Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
assert(watermark != (const Image *) NULL);
assert(watermark->signature == MagickCoreSignature);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickCoreSignature);
one=1UL;
stegano_image=CloneImage(image,0,0,MagickTrue,exception);
if (stegano_image == (Image *) NULL)
return((Image *) NULL);
stegano_image->depth=MAGICKCORE_QUANTUM_DEPTH;
if (SetImageStorageClass(stegano_image,DirectClass,exception) == MagickFalse)
{
stegano_image=DestroyImage(stegano_image);
return((Image *) NULL);
}
/*
Hide watermark in low-order bits of image.
*/
c=0;
i=0;
j=0;
depth=stegano_image->depth;
k=stegano_image->offset;
status=MagickTrue;
watermark_view=AcquireVirtualCacheView(watermark,exception);
stegano_view=AcquireAuthenticCacheView(stegano_image,exception);
for (i=(ssize_t) depth-1; (i >= 0) && (j < (ssize_t) depth); i--)
{
for (y=0; (y < (ssize_t) watermark->rows) && (j < (ssize_t) depth); y++)
{
for (x=0; (x < (ssize_t) watermark->columns) && (j < (ssize_t) depth); x++)
{
ssize_t
offset;
(void) GetOneCacheViewVirtualPixelInfo(watermark_view,x,y,&pixel,
exception);
offset=k/(ssize_t) stegano_image->columns;
if (offset >= (ssize_t) stegano_image->rows)
break;
q=GetCacheViewAuthenticPixels(stegano_view,k % (ssize_t)
stegano_image->columns,k/(ssize_t) stegano_image->columns,1,1,
exception);
if (q == (Quantum *) NULL)
break;
switch (c)
{
case 0:
{
SetPixelRed(stegano_image,SetBit(GetPixelRed(stegano_image,q),j,
GetBit(GetPixelInfoIntensity(stegano_image,&pixel),i)),q);
break;
}
case 1:
{
SetPixelGreen(stegano_image,SetBit(GetPixelGreen(stegano_image,q),j,
GetBit(GetPixelInfoIntensity(stegano_image,&pixel),i)),q);
break;
}
case 2:
{
SetPixelBlue(stegano_image,SetBit(GetPixelBlue(stegano_image,q),j,
GetBit(GetPixelInfoIntensity(stegano_image,&pixel),i)),q);
break;
}
}
if (SyncCacheViewAuthenticPixels(stegano_view,exception) == MagickFalse)
break;
c++;
if (c == 3)
c=0;
k++;
if (k == (ssize_t) (stegano_image->columns*stegano_image->columns))
k=0;
if (k == stegano_image->offset)
j++;
}
}
if (image->progress_monitor != (MagickProgressMonitor) NULL)
{
MagickBooleanType
proceed;
proceed=SetImageProgress(image,SteganoImageTag,(MagickOffsetType)
(depth-i),depth);
if (proceed == MagickFalse)
status=MagickFalse;
}
}
stegano_view=DestroyCacheView(stegano_view);
watermark_view=DestroyCacheView(watermark_view);
if (status == MagickFalse)
stegano_image=DestroyImage(stegano_image);
return(stegano_image);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% S t e r e o A n a g l y p h I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% StereoAnaglyphImage() combines two images and produces a single image that
% is the composite of a left and right image of a stereo pair. Special
% red-green stereo glasses are required to view this effect.
%
% The format of the StereoAnaglyphImage method is:
%
% Image *StereoImage(const Image *left_image,const Image *right_image,
% ExceptionInfo *exception)
% Image *StereoAnaglyphImage(const Image *left_image,
% const Image *right_image,const ssize_t x_offset,const ssize_t y_offset,
% ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o left_image: the left image.
%
% o right_image: the right image.
%
% o exception: return any errors or warnings in this structure.
%
% o x_offset: amount, in pixels, by which the left image is offset to the
% right of the right image.
%
% o y_offset: amount, in pixels, by which the left image is offset to the
% bottom of the right image.
%
%
*/
MagickExport Image *StereoImage(const Image *left_image,
const Image *right_image,ExceptionInfo *exception)
{
return(StereoAnaglyphImage(left_image,right_image,0,0,exception));
}
MagickExport Image *StereoAnaglyphImage(const Image *left_image,
const Image *right_image,const ssize_t x_offset,const ssize_t y_offset,
ExceptionInfo *exception)
{
#define StereoImageTag "Stereo/Image"
const Image
*image;
Image
*stereo_image;
MagickBooleanType
status;
ssize_t
y;
assert(left_image != (const Image *) NULL);
assert(left_image->signature == MagickCoreSignature);
if (left_image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",
left_image->filename);
assert(right_image != (const Image *) NULL);
assert(right_image->signature == MagickCoreSignature);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickCoreSignature);
image=left_image;
if ((left_image->columns != right_image->columns) ||
(left_image->rows != right_image->rows))
ThrowImageException(ImageError,"LeftAndRightImageSizesDiffer");
/*
Initialize stereo image attributes.
*/
stereo_image=CloneImage(left_image,left_image->columns,left_image->rows,
MagickTrue,exception);
if (stereo_image == (Image *) NULL)
return((Image *) NULL);
if (SetImageStorageClass(stereo_image,DirectClass,exception) == MagickFalse)
{
stereo_image=DestroyImage(stereo_image);
return((Image *) NULL);
}
(void) SetImageColorspace(stereo_image,sRGBColorspace,exception);
/*
Copy left image to red channel and right image to blue channel.
*/
status=MagickTrue;
for (y=0; y < (ssize_t) stereo_image->rows; y++)
{
register const Quantum
*magick_restrict p,
*magick_restrict q;
register ssize_t
x;
register Quantum
*magick_restrict r;
p=GetVirtualPixels(left_image,-x_offset,y-y_offset,image->columns,1,
exception);
q=GetVirtualPixels(right_image,0,y,right_image->columns,1,exception);
r=QueueAuthenticPixels(stereo_image,0,y,stereo_image->columns,1,exception);
if ((p == (const Quantum *) NULL) || (q == (Quantum *) NULL) ||
(r == (Quantum *) NULL))
break;
for (x=0; x < (ssize_t) stereo_image->columns; x++)
{
SetPixelRed(stereo_image,GetPixelRed(left_image,p),r);
SetPixelGreen(stereo_image,GetPixelGreen(right_image,q),r);
SetPixelBlue(stereo_image,GetPixelBlue(right_image,q),r);
if ((GetPixelAlphaTraits(stereo_image) & CopyPixelTrait) != 0)
SetPixelAlpha(stereo_image,(GetPixelAlpha(left_image,p)+
GetPixelAlpha(right_image,q))/2,r);
p+=GetPixelChannels(left_image);
q+=GetPixelChannels(right_image);
r+=GetPixelChannels(stereo_image);
}
if (SyncAuthenticPixels(stereo_image,exception) == MagickFalse)
break;
if (image->progress_monitor != (MagickProgressMonitor) NULL)
{
MagickBooleanType
proceed;
proceed=SetImageProgress(image,StereoImageTag,(MagickOffsetType) y,
stereo_image->rows);
if (proceed == MagickFalse)
status=MagickFalse;
}
}
if (status == MagickFalse)
stereo_image=DestroyImage(stereo_image);
return(stereo_image);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% S w i r l I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% SwirlImage() swirls the pixels about the center of the image, where
% degrees indicates the sweep of the arc through which each pixel is moved.
% You get a more dramatic effect as the degrees move from 1 to 360.
%
% The format of the SwirlImage method is:
%
% Image *SwirlImage(const Image *image,double degrees,
% const PixelInterpolateMethod method,ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o degrees: Define the tightness of the swirling effect.
%
% o method: the pixel interpolation method.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport Image *SwirlImage(const Image *image,double degrees,
const PixelInterpolateMethod method,ExceptionInfo *exception)
{
#define SwirlImageTag "Swirl/Image"
CacheView
*canvas_view,
*interpolate_view,
*swirl_view;
double
radius;
Image
*canvas_image,
*swirl_image;
MagickBooleanType
status;
MagickOffsetType
progress;
PointInfo
center,
scale;
ssize_t
y;
/*
Initialize swirl image attributes.
*/
assert(image != (const Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickCoreSignature);
canvas_image=CloneImage(image,0,0,MagickTrue,exception);
if (canvas_image == (Image *) NULL)
return((Image *) NULL);
swirl_image=CloneImage(canvas_image,0,0,MagickTrue,exception);
if (swirl_image == (Image *) NULL)
{
canvas_image=DestroyImage(canvas_image);
return((Image *) NULL);
}
if (SetImageStorageClass(swirl_image,DirectClass,exception) == MagickFalse)
{
canvas_image=DestroyImage(canvas_image);
swirl_image=DestroyImage(swirl_image);
return((Image *) NULL);
}
if (swirl_image->background_color.alpha_trait != UndefinedPixelTrait)
(void) SetImageAlphaChannel(swirl_image,OnAlphaChannel,exception);
/*
Compute scaling factor.
*/
center.x=(double) canvas_image->columns/2.0;
center.y=(double) canvas_image->rows/2.0;
radius=MagickMax(center.x,center.y);
scale.x=1.0;
scale.y=1.0;
if (canvas_image->columns > canvas_image->rows)
scale.y=(double) canvas_image->columns/(double) canvas_image->rows;
else
if (canvas_image->columns < canvas_image->rows)
scale.x=(double) canvas_image->rows/(double) canvas_image->columns;
degrees=(double) DegreesToRadians(degrees);
/*
Swirl image.
*/
status=MagickTrue;
progress=0;
canvas_view=AcquireVirtualCacheView(canvas_image,exception);
interpolate_view=AcquireVirtualCacheView(image,exception);
swirl_view=AcquireAuthenticCacheView(swirl_image,exception);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static) shared(progress,status) \
magick_number_threads(canvas_image,swirl_image,canvas_image->rows,1)
#endif
for (y=0; y < (ssize_t) canvas_image->rows; y++)
{
double
distance;
PointInfo
delta;
register const Quantum
*magick_restrict p;
register ssize_t
x;
register Quantum
*magick_restrict q;
if (status == MagickFalse)
continue;
p=GetCacheViewVirtualPixels(canvas_view,0,y,canvas_image->columns,1,
exception);
q=QueueCacheViewAuthenticPixels(swirl_view,0,y,swirl_image->columns,1,
exception);
if ((p == (const Quantum *) NULL) || (q == (Quantum *) NULL))
{
status=MagickFalse;
continue;
}
delta.y=scale.y*(double) (y-center.y);
for (x=0; x < (ssize_t) canvas_image->columns; x++)
{
/*
Determine if the pixel is within an ellipse.
*/
delta.x=scale.x*(double) (x-center.x);
distance=delta.x*delta.x+delta.y*delta.y;
if (distance >= (radius*radius))
{
register ssize_t
i;
for (i=0; i < (ssize_t) GetPixelChannels(canvas_image); i++)
{
PixelChannel channel = GetPixelChannelChannel(canvas_image,i);
PixelTrait traits = GetPixelChannelTraits(canvas_image,channel);
PixelTrait swirl_traits = GetPixelChannelTraits(swirl_image,
channel);
if ((traits == UndefinedPixelTrait) ||
(swirl_traits == UndefinedPixelTrait))
continue;
SetPixelChannel(swirl_image,channel,p[i],q);
}
}
else
{
double
cosine,
factor,
sine;
/*
Swirl the pixel.
*/
factor=1.0-sqrt((double) distance)/radius;
sine=sin((double) (degrees*factor*factor));
cosine=cos((double) (degrees*factor*factor));
status=InterpolatePixelChannels(canvas_image,interpolate_view,
swirl_image,method,((cosine*delta.x-sine*delta.y)/scale.x+center.x),
(double) ((sine*delta.x+cosine*delta.y)/scale.y+center.y),q,
exception);
if (status == MagickFalse)
break;
}
p+=GetPixelChannels(canvas_image);
q+=GetPixelChannels(swirl_image);
}
if (SyncCacheViewAuthenticPixels(swirl_view,exception) == MagickFalse)
status=MagickFalse;
if (canvas_image->progress_monitor != (MagickProgressMonitor) NULL)
{
MagickBooleanType
proceed;
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp atomic
#endif
progress++;
proceed=SetImageProgress(canvas_image,SwirlImageTag,progress,
canvas_image->rows);
if (proceed == MagickFalse)
status=MagickFalse;
}
}
swirl_view=DestroyCacheView(swirl_view);
interpolate_view=DestroyCacheView(interpolate_view);
canvas_view=DestroyCacheView(canvas_view);
canvas_image=DestroyImage(canvas_image);
if (status == MagickFalse)
swirl_image=DestroyImage(swirl_image);
return(swirl_image);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% T i n t I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% TintImage() applies a color vector to each pixel in the image. The length
% of the vector is 0 for black and white and at its maximum for the midtones.
% The vector weighting function is f(x)=(1-(4.0*((x-0.5)*(x-0.5))))
%
% The format of the TintImage method is:
%
% Image *TintImage(const Image *image,const char *blend,
% const PixelInfo *tint,ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o blend: A color value used for tinting.
%
% o tint: A color value used for tinting.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport Image *TintImage(const Image *image,const char *blend,
const PixelInfo *tint,ExceptionInfo *exception)
{
#define TintImageTag "Tint/Image"
CacheView
*image_view,
*tint_view;
double
intensity;
GeometryInfo
geometry_info;
Image
*tint_image;
MagickBooleanType
status;
MagickOffsetType
progress;
PixelInfo
color_vector;
MagickStatusType
flags;
ssize_t
y;
/*
Allocate tint image.
*/
assert(image != (const Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickCoreSignature);
tint_image=CloneImage(image,0,0,MagickTrue,exception);
if (tint_image == (Image *) NULL)
return((Image *) NULL);
if (SetImageStorageClass(tint_image,DirectClass,exception) == MagickFalse)
{
tint_image=DestroyImage(tint_image);
return((Image *) NULL);
}
if ((IsGrayColorspace(image->colorspace) != MagickFalse) &&
(IsPixelInfoGray(tint) == MagickFalse))
(void) SetImageColorspace(tint_image,sRGBColorspace,exception);
if (blend == (const char *) NULL)
return(tint_image);
/*
Determine RGB values of the color.
*/
GetPixelInfo(image,&color_vector);
flags=ParseGeometry(blend,&geometry_info);
color_vector.red=geometry_info.rho;
color_vector.green=geometry_info.rho;
color_vector.blue=geometry_info.rho;
color_vector.alpha=(MagickRealType) OpaqueAlpha;
if ((flags & SigmaValue) != 0)
color_vector.green=geometry_info.sigma;
if ((flags & XiValue) != 0)
color_vector.blue=geometry_info.xi;
if ((flags & PsiValue) != 0)
color_vector.alpha=geometry_info.psi;
if (image->colorspace == CMYKColorspace)
{
color_vector.black=geometry_info.rho;
if ((flags & PsiValue) != 0)
color_vector.black=geometry_info.psi;
if ((flags & ChiValue) != 0)
color_vector.alpha=geometry_info.chi;
}
intensity=(double) GetPixelInfoIntensity((const Image *) NULL,tint);
color_vector.red=(double) (color_vector.red*tint->red/100.0-intensity);
color_vector.green=(double) (color_vector.green*tint->green/100.0-intensity);
color_vector.blue=(double) (color_vector.blue*tint->blue/100.0-intensity);
color_vector.black=(double) (color_vector.black*tint->black/100.0-intensity);
color_vector.alpha=(double) (color_vector.alpha*tint->alpha/100.0-intensity);
/*
Tint image.
*/
status=MagickTrue;
progress=0;
image_view=AcquireVirtualCacheView(image,exception);
tint_view=AcquireAuthenticCacheView(tint_image,exception);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static) shared(progress,status) \
magick_number_threads(image,tint_image,image->rows,1)
#endif
for (y=0; y < (ssize_t) image->rows; y++)
{
register const Quantum
*magick_restrict p;
register Quantum
*magick_restrict q;
register ssize_t
x;
if (status == MagickFalse)
continue;
p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1,exception);
q=QueueCacheViewAuthenticPixels(tint_view,0,y,tint_image->columns,1,
exception);
if ((p == (const Quantum *) NULL) || (q == (Quantum *) NULL))
{
status=MagickFalse;
continue;
}
for (x=0; x < (ssize_t) image->columns; x++)
{
PixelInfo
pixel;
double
weight;
GetPixelInfo(image,&pixel);
weight=QuantumScale*GetPixelRed(image,p)-0.5;
pixel.red=(MagickRealType) GetPixelRed(image,p)+color_vector.red*
(1.0-(4.0*(weight*weight)));
weight=QuantumScale*GetPixelGreen(image,p)-0.5;
pixel.green=(MagickRealType) GetPixelGreen(image,p)+color_vector.green*
(1.0-(4.0*(weight*weight)));
weight=QuantumScale*GetPixelBlue(image,p)-0.5;
pixel.blue=(MagickRealType) GetPixelBlue(image,p)+color_vector.blue*
(1.0-(4.0*(weight*weight)));
weight=QuantumScale*GetPixelBlack(image,p)-0.5;
pixel.black=(MagickRealType) GetPixelBlack(image,p)+color_vector.black*
(1.0-(4.0*(weight*weight)));
pixel.alpha=(MagickRealType) GetPixelAlpha(image,p);
SetPixelViaPixelInfo(tint_image,&pixel,q);
p+=GetPixelChannels(image);
q+=GetPixelChannels(tint_image);
}
if (SyncCacheViewAuthenticPixels(tint_view,exception) == MagickFalse)
status=MagickFalse;
if (image->progress_monitor != (MagickProgressMonitor) NULL)
{
MagickBooleanType
proceed;
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp atomic
#endif
progress++;
proceed=SetImageProgress(image,TintImageTag,progress,image->rows);
if (proceed == MagickFalse)
status=MagickFalse;
}
}
tint_view=DestroyCacheView(tint_view);
image_view=DestroyCacheView(image_view);
if (status == MagickFalse)
tint_image=DestroyImage(tint_image);
return(tint_image);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% V i g n e t t e I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% VignetteImage() softens the edges of the image in vignette style.
%
% The format of the VignetteImage method is:
%
% Image *VignetteImage(const Image *image,const double radius,
% const double sigma,const ssize_t x,const ssize_t y,
% ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o radius: the radius of the pixel neighborhood.
%
% o sigma: the standard deviation of the Gaussian, in pixels.
%
% o x, y: Define the x and y ellipse offset.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport Image *VignetteImage(const Image *image,const double radius,
const double sigma,const ssize_t x,const ssize_t y,ExceptionInfo *exception)
{
char
ellipse[MagickPathExtent];
DrawInfo
*draw_info;
Image
*canvas,
*blur_image,
*oval_image,
*vignette_image;
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickCoreSignature);
canvas=CloneImage(image,0,0,MagickTrue,exception);
if (canvas == (Image *) NULL)
return((Image *) NULL);
if (SetImageStorageClass(canvas,DirectClass,exception) == MagickFalse)
{
canvas=DestroyImage(canvas);
return((Image *) NULL);
}
canvas->alpha_trait=BlendPixelTrait;
oval_image=CloneImage(canvas,canvas->columns,canvas->rows,MagickTrue,
exception);
if (oval_image == (Image *) NULL)
{
canvas=DestroyImage(canvas);
return((Image *) NULL);
}
(void) QueryColorCompliance("#000000",AllCompliance,
&oval_image->background_color,exception);
(void) SetImageBackgroundColor(oval_image,exception);
draw_info=CloneDrawInfo((const ImageInfo *) NULL,(const DrawInfo *) NULL);
(void) QueryColorCompliance("#ffffff",AllCompliance,&draw_info->fill,
exception);
(void) QueryColorCompliance("#ffffff",AllCompliance,&draw_info->stroke,
exception);
(void) FormatLocaleString(ellipse,MagickPathExtent,"ellipse %g,%g,%g,%g,"
"0.0,360.0",image->columns/2.0,image->rows/2.0,image->columns/2.0-x,
image->rows/2.0-y);
draw_info->primitive=AcquireString(ellipse);
(void) DrawImage(oval_image,draw_info,exception);
draw_info=DestroyDrawInfo(draw_info);
blur_image=BlurImage(oval_image,radius,sigma,exception);
oval_image=DestroyImage(oval_image);
if (blur_image == (Image *) NULL)
{
canvas=DestroyImage(canvas);
return((Image *) NULL);
}
blur_image->alpha_trait=UndefinedPixelTrait;
(void) CompositeImage(canvas,blur_image,IntensityCompositeOp,MagickTrue,
0,0,exception);
blur_image=DestroyImage(blur_image);
vignette_image=MergeImageLayers(canvas,FlattenLayer,exception);
canvas=DestroyImage(canvas);
if (vignette_image != (Image *) NULL)
(void) TransformImageColorspace(vignette_image,image->colorspace,exception);
return(vignette_image);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% W a v e I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% WaveImage() creates a "ripple" effect in the image by shifting the pixels
% vertically along a sine wave whose amplitude and wavelength is specified
% by the given parameters.
%
% The format of the WaveImage method is:
%
% Image *WaveImage(const Image *image,const double amplitude,
% const double wave_length,const PixelInterpolateMethod method,
% ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o amplitude, wave_length: Define the amplitude and wave length of the
% sine wave.
%
% o interpolate: the pixel interpolation method.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport Image *WaveImage(const Image *image,const double amplitude,
const double wave_length,const PixelInterpolateMethod method,
ExceptionInfo *exception)
{
#define WaveImageTag "Wave/Image"
CacheView
*canvas_image_view,
*wave_view;
float
*sine_map;
Image
*canvas_image,
*wave_image;
MagickBooleanType
status;
MagickOffsetType
progress;
register ssize_t
i;
ssize_t
y;
/*
Initialize wave image attributes.
*/
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickCoreSignature);
canvas_image=CloneImage(image,0,0,MagickTrue,exception);
if (canvas_image == (Image *) NULL)
return((Image *) NULL);
if ((canvas_image->alpha_trait == UndefinedPixelTrait) &&
(canvas_image->background_color.alpha != OpaqueAlpha))
(void) SetImageAlpha(canvas_image,OpaqueAlpha,exception);
wave_image=CloneImage(canvas_image,canvas_image->columns,(size_t)
(canvas_image->rows+2.0*fabs(amplitude)),MagickTrue,exception);
if (wave_image == (Image *) NULL)
{
canvas_image=DestroyImage(canvas_image);
return((Image *) NULL);
}
if (SetImageStorageClass(wave_image,DirectClass,exception) == MagickFalse)
{
canvas_image=DestroyImage(canvas_image);
wave_image=DestroyImage(wave_image);
return((Image *) NULL);
}
/*
Allocate sine map.
*/
sine_map=(float *) AcquireQuantumMemory((size_t) wave_image->columns,
sizeof(*sine_map));
if (sine_map == (float *) NULL)
{
canvas_image=DestroyImage(canvas_image);
wave_image=DestroyImage(wave_image);
ThrowImageException(ResourceLimitError,"MemoryAllocationFailed");
}
for (i=0; i < (ssize_t) wave_image->columns; i++)
sine_map[i]=(float) fabs(amplitude)+amplitude*sin((double)
((2.0*MagickPI*i)/wave_length));
/*
Wave image.
*/
status=MagickTrue;
progress=0;
canvas_image_view=AcquireVirtualCacheView(canvas_image,exception);
wave_view=AcquireAuthenticCacheView(wave_image,exception);
(void) SetCacheViewVirtualPixelMethod(canvas_image_view,
BackgroundVirtualPixelMethod);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static) shared(progress,status) \
magick_number_threads(canvas_image,wave_image,wave_image->rows,1)
#endif
for (y=0; y < (ssize_t) wave_image->rows; y++)
{
register const Quantum
*magick_restrict p;
register Quantum
*magick_restrict q;
register ssize_t
x;
if (status == MagickFalse)
continue;
p=GetCacheViewVirtualPixels(canvas_image_view,0,y,canvas_image->columns,1,
exception);
q=QueueCacheViewAuthenticPixels(wave_view,0,y,wave_image->columns,1,
exception);
if ((p == (const Quantum *) NULL) || (q == (Quantum *) NULL))
{
status=MagickFalse;
continue;
}
for (x=0; x < (ssize_t) wave_image->columns; x++)
{
status=InterpolatePixelChannels(canvas_image,canvas_image_view,
wave_image,method,(double) x,(double) (y-sine_map[x]),q,exception);
if (status == MagickFalse)
break;
p+=GetPixelChannels(canvas_image);
q+=GetPixelChannels(wave_image);
}
if (SyncCacheViewAuthenticPixels(wave_view,exception) == MagickFalse)
status=MagickFalse;
if (image->progress_monitor != (MagickProgressMonitor) NULL)
{
MagickBooleanType
proceed;
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp atomic
#endif
progress++;
proceed=SetImageProgress(canvas_image,WaveImageTag,progress,
canvas_image->rows);
if (proceed == MagickFalse)
status=MagickFalse;
}
}
wave_view=DestroyCacheView(wave_view);
canvas_image_view=DestroyCacheView(canvas_image_view);
canvas_image=DestroyImage(canvas_image);
sine_map=(float *) RelinquishMagickMemory(sine_map);
if (status == MagickFalse)
wave_image=DestroyImage(wave_image);
return(wave_image);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% W a v e l e t D e n o i s e I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% WaveletDenoiseImage() removes noise from the image using a wavelet
% transform. The wavelet transform is a fast hierarchical scheme for
% processing an image using a set of consecutive lowpass and high_pass filters,
% followed by a decimation. This results in a decomposition into different
% scales which can be regarded as different “frequency bands”, determined by
% the mother wavelet. Adapted from dcraw.c by David Coffin.
%
% The format of the WaveletDenoiseImage method is:
%
% Image *WaveletDenoiseImage(const Image *image,const double threshold,
% const double softness,ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o threshold: set the threshold for smoothing.
%
% o softness: attenuate the smoothing threshold.
%
% o exception: return any errors or warnings in this structure.
%
*/
static inline void HatTransform(const float *magick_restrict pixels,
const size_t stride,const size_t extent,const size_t scale,float *kernel)
{
const float
*magick_restrict p,
*magick_restrict q,
*magick_restrict r;
register ssize_t
i;
p=pixels;
q=pixels+scale*stride;
r=pixels+scale*stride;
for (i=0; i < (ssize_t) scale; i++)
{
kernel[i]=0.25f*(*p+(*p)+(*q)+(*r));
p+=stride;
q-=stride;
r+=stride;
}
for ( ; i < (ssize_t) (extent-scale); i++)
{
kernel[i]=0.25f*(2.0f*(*p)+*(p-scale*stride)+*(p+scale*stride));
p+=stride;
}
q=p-scale*stride;
r=pixels+stride*(extent-2);
for ( ; i < (ssize_t) extent; i++)
{
kernel[i]=0.25f*(*p+(*p)+(*q)+(*r));
p+=stride;
q+=stride;
r-=stride;
}
}
MagickExport Image *WaveletDenoiseImage(const Image *image,
const double threshold,const double softness,ExceptionInfo *exception)
{
CacheView
*image_view,
*noise_view;
float
*kernel,
*pixels;
Image
*noise_image;
MagickBooleanType
status;
MagickSizeType
number_pixels;
MemoryInfo
*pixels_info;
ssize_t
channel;
static const float
noise_levels[] = { 0.8002f, 0.2735f, 0.1202f, 0.0585f, 0.0291f, 0.0152f,
0.0080f, 0.0044f };
/*
Initialize noise image attributes.
*/
assert(image != (const Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickCoreSignature);
#if defined(MAGICKCORE_OPENCL_SUPPORT)
noise_image=AccelerateWaveletDenoiseImage(image,threshold,exception);
if (noise_image != (Image *) NULL)
return(noise_image);
#endif
noise_image=CloneImage(image,0,0,MagickTrue,exception);
if (noise_image == (Image *) NULL)
return((Image *) NULL);
if (SetImageStorageClass(noise_image,DirectClass,exception) == MagickFalse)
{
noise_image=DestroyImage(noise_image);
return((Image *) NULL);
}
if (AcquireMagickResource(WidthResource,4*image->columns) == MagickFalse)
ThrowImageException(ResourceLimitError,"MemoryAllocationFailed");
pixels_info=AcquireVirtualMemory(3*image->columns,image->rows*
sizeof(*pixels));
kernel=(float *) AcquireQuantumMemory(MagickMax(image->rows,image->columns)+1,
GetOpenMPMaximumThreads()*sizeof(*kernel));
if ((pixels_info == (MemoryInfo *) NULL) || (kernel == (float *) NULL))
{
if (kernel != (float *) NULL)
kernel=(float *) RelinquishMagickMemory(kernel);
if (pixels_info != (MemoryInfo *) NULL)
pixels_info=RelinquishVirtualMemory(pixels_info);
ThrowImageException(ResourceLimitError,"MemoryAllocationFailed");
}
pixels=(float *) GetVirtualMemoryBlob(pixels_info);
status=MagickTrue;
number_pixels=(MagickSizeType) image->columns*image->rows;
image_view=AcquireAuthenticCacheView(image,exception);
noise_view=AcquireAuthenticCacheView(noise_image,exception);
for (channel=0; channel < (ssize_t) GetPixelChannels(image); channel++)
{
register ssize_t
i;
size_t
high_pass,
low_pass;
ssize_t
level,
y;
PixelChannel
pixel_channel;
PixelTrait
traits;
if (status == MagickFalse)
continue;
traits=GetPixelChannelTraits(image,(PixelChannel) channel);
if (traits == UndefinedPixelTrait)
continue;
pixel_channel=GetPixelChannelChannel(image,channel);
if ((pixel_channel != RedPixelChannel) &&
(pixel_channel != GreenPixelChannel) &&
(pixel_channel != BluePixelChannel))
continue;
/*
Copy channel from image to wavelet pixel array.
*/
i=0;
for (y=0; y < (ssize_t) image->rows; y++)
{
register const Quantum
*magick_restrict p;
ssize_t
x;
p=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception);
if (p == (const Quantum *) NULL)
{
status=MagickFalse;
break;
}
for (x=0; x < (ssize_t) image->columns; x++)
{
pixels[i++]=(float) p[channel];
p+=GetPixelChannels(image);
}
}
/*
Low pass filter outputs are called approximation kernel & high pass
filters are referred to as detail kernel. The detail kernel
have high values in the noisy parts of the signal.
*/
high_pass=0;
for (level=0; level < 5; level++)
{
double
magnitude;
ssize_t
x,
y;
low_pass=(size_t) (number_pixels*((level & 0x01)+1));
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static,1) \
magick_number_threads(image,image,image->rows,1)
#endif
for (y=0; y < (ssize_t) image->rows; y++)
{
const int
id = GetOpenMPThreadId();
register float
*magick_restrict p,
*magick_restrict q;
register ssize_t
x;
p=kernel+id*image->columns;
q=pixels+y*image->columns;
HatTransform(q+high_pass,1,image->columns,(size_t) (1UL << level),p);
q+=low_pass;
for (x=0; x < (ssize_t) image->columns; x++)
*q++=(*p++);
}
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static,1) \
magick_number_threads(image,image,image->columns,1)
#endif
for (x=0; x < (ssize_t) image->columns; x++)
{
const int
id = GetOpenMPThreadId();
register float
*magick_restrict p,
*magick_restrict q;
register ssize_t
y;
p=kernel+id*image->rows;
q=pixels+x+low_pass;
HatTransform(q,image->columns,image->rows,(size_t) (1UL << level),p);
for (y=0; y < (ssize_t) image->rows; y++)
{
*q=(*p++);
q+=image->columns;
}
}
/*
To threshold, each coefficient is compared to a threshold value and
attenuated / shrunk by some factor.
*/
magnitude=threshold*noise_levels[level];
for (i=0; i < (ssize_t) number_pixels; ++i)
{
pixels[high_pass+i]-=pixels[low_pass+i];
if (pixels[high_pass+i] < -magnitude)
pixels[high_pass+i]+=magnitude-softness*magnitude;
else
if (pixels[high_pass+i] > magnitude)
pixels[high_pass+i]-=magnitude-softness*magnitude;
else
pixels[high_pass+i]*=softness;
if (high_pass != 0)
pixels[i]+=pixels[high_pass+i];
}
high_pass=low_pass;
}
/*
Reconstruct image from the thresholded wavelet kernel.
*/
i=0;
for (y=0; y < (ssize_t) image->rows; y++)
{
MagickBooleanType
sync;
register Quantum
*magick_restrict q;
register ssize_t
x;
ssize_t
offset;
q=GetCacheViewAuthenticPixels(noise_view,0,y,noise_image->columns,1,
exception);
if (q == (Quantum *) NULL)
{
status=MagickFalse;
break;
}
offset=GetPixelChannelOffset(noise_image,pixel_channel);
for (x=0; x < (ssize_t) image->columns; x++)
{
MagickRealType
pixel;
pixel=(MagickRealType) pixels[i]+pixels[low_pass+i];
q[offset]=ClampToQuantum(pixel);
i++;
q+=GetPixelChannels(noise_image);
}
sync=SyncCacheViewAuthenticPixels(noise_view,exception);
if (sync == MagickFalse)
status=MagickFalse;
}
if (image->progress_monitor != (MagickProgressMonitor) NULL)
{
MagickBooleanType
proceed;
proceed=SetImageProgress(image,AddNoiseImageTag,(MagickOffsetType)
channel,GetPixelChannels(image));
if (proceed == MagickFalse)
status=MagickFalse;
}
}
noise_view=DestroyCacheView(noise_view);
image_view=DestroyCacheView(image_view);
kernel=(float *) RelinquishMagickMemory(kernel);
pixels_info=RelinquishVirtualMemory(pixels_info);
if (status == MagickFalse)
noise_image=DestroyImage(noise_image);
return(noise_image);
}
|
GB_unaryop__ainv_int32_uint32.c | //------------------------------------------------------------------------------
// GB_unaryop: hard-coded functions for each built-in unary operator
//------------------------------------------------------------------------------
// SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2019, All Rights Reserved.
// http://suitesparse.com See GraphBLAS/Doc/License.txt for license.
//------------------------------------------------------------------------------
// If this file is in the Generated/ folder, do not edit it (auto-generated).
#include "GB.h"
#ifndef GBCOMPACT
#include "GB_control.h"
#include "GB_iterator.h"
#include "GB_unaryop__include.h"
// C=unop(A) is defined by the following types and operators:
// op(A) function: GB_unop__ainv_int32_uint32
// op(A') function: GB_tran__ainv_int32_uint32
// C type: int32_t
// A type: uint32_t
// cast: int32_t cij = (int32_t) aij
// unaryop: cij = -aij
#define GB_ATYPE \
uint32_t
#define GB_CTYPE \
int32_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_CASTING(z, x) \
int32_t z = (int32_t) x ;
// cij = op (cast (aij))
#define GB_CAST_OP(pC,pA) \
{ \
/* aij = Ax [pA] */ \
GB_GETA (aij, Ax, pA) ; \
/* Cx [pC] = op (cast (aij)) */ \
GB_CASTING (x, aij) ; \
GB_OP (GB_CX (pC), x) ; \
}
// disable this operator and use the generic case if these conditions hold
#define GB_DISABLE \
(GxB_NO_AINV || GxB_NO_INT32 || GxB_NO_UINT32)
//------------------------------------------------------------------------------
// Cx = op (cast (Ax)): apply a unary operator
//------------------------------------------------------------------------------
GrB_Info GB_unop__ainv_int32_uint32
(
int32_t *restrict Cx,
const uint32_t *restrict Ax,
int64_t anz,
int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
#pragma omp parallel for num_threads(nthreads) schedule(static)
for (int64_t p = 0 ; p < anz ; p++)
{
GB_CAST_OP (p, p) ;
}
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// C = op (cast (A')): transpose, typecast, and apply a unary operator
//------------------------------------------------------------------------------
GrB_Info GB_tran__ainv_int32_uint32
(
GrB_Matrix C,
const GrB_Matrix A,
int64_t **Rowcounts,
GBI_single_iterator Iter,
const int64_t *restrict A_slice,
int naslice
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
#define GB_PHASE_2_OF_2
#include "GB_unaryop_transpose.c"
return (GrB_SUCCESS) ;
#endif
}
#endif
|
tool_available.c | // The OpenMP standard defines 3 ways of providing ompt_start_tool:
// 1. "statically-linking the tool’s definition of ompt_start_tool into an OpenMP application"
// RUN: %libomp-compile -DCODE -DTOOL && %libomp-run | FileCheck %s
// Note: We should compile the tool without -fopenmp as other tools developer
// would do. Otherwise this test may pass for the wrong reasons on Darwin.
// RUN: %clang %flags -DTOOL -shared -fPIC %s -o %T/tool.so
// 2. "introducing a dynamically-linked library that includes the tool’s definition of ompt_start_tool into the application’s address space"
// 2.1 Link with tool during compilation
// RUN: %libomp-compile -DCODE %no-as-needed-flag %T/tool.so && %libomp-run | FileCheck %s
// 2.2 Link with tool during compilation, but AFTER the runtime
// RUN: %libomp-compile -DCODE -lomp %no-as-needed-flag %T/tool.so && %libomp-run | FileCheck %s
// 2.3 Inject tool via the dynamic loader
// RUN: %libomp-compile -DCODE && %preload-tool %libomp-run | FileCheck %s
// 3. "providing the name of a dynamically-linked library appropriate for the architecture and operating system used by the application in the tool-libraries-var ICV"
// RUN: %libomp-compile -DCODE && env OMP_TOOL_LIBRARIES=%T/tool.so %libomp-run | FileCheck %s
// REQUIRES: ompt
/*
* This file contains code for an OMPT shared library tool to be
* loaded and the code for the OpenMP executable.
* -DTOOL enables the code for the tool during compilation
* -DCODE enables the code for the executable during compilation
*/
#ifdef CODE
#include "omp.h"
int main()
{
#pragma omp parallel num_threads(2)
{
}
// Check if libomp supports the callbacks for this test.
// CHECK-NOT: {{^}}0: Could not register callback
// CHECK: {{^}}0: NULL_POINTER=[[NULL:.*$]]
// CHECK: {{^}}0: ompt_event_runtime_shutdown
return 0;
}
#endif /* CODE */
#ifdef TOOL
#include <stdio.h>
#include <omp-tools.h>
int ompt_initialize(
ompt_function_lookup_t lookup,
ompt_data_t* tool_data)
{
printf("0: NULL_POINTER=%p\n", (void*)NULL);
return 1; //success
}
void ompt_finalize(ompt_data_t* tool_data)
{
printf("0: ompt_event_runtime_shutdown\n");
}
ompt_start_tool_result_t* ompt_start_tool(
unsigned int omp_version,
const char *runtime_version)
{
static ompt_start_tool_result_t ompt_start_tool_result = {&ompt_initialize,&ompt_finalize, 0};
return &ompt_start_tool_result;
}
#endif /* TOOL */
|
dgelqf.c | /**
*
* @file
*
* PLASMA is a software package provided by:
* University of Tennessee, US,
* University of Manchester, UK.
*
* @generated from /home/luszczek/workspace/plasma/bitbucket/plasma/compute/zgelqf.c, normal z -> d, Fri Sep 28 17:38:01 2018
*
**/
#include "plasma.h"
#include "plasma_async.h"
#include "plasma_context.h"
#include "plasma_descriptor.h"
#include "plasma_internal.h"
#include "plasma_tuning.h"
#include "plasma_types.h"
#include "plasma_workspace.h"
/***************************************************************************//**
*
* @ingroup plasma_gelqf
*
* Computes tile LQ factorization of a complex m-by-n matrix A.
* The factorization has the form
* \f[ A = L \times Q \f],
* where L is a lower trapezoidal with positive diagonal and Q is a matrix with
* orthonormal rows.
*
*******************************************************************************
*
* @param[in] m
* The number of rows of the matrix A. m >= 0.
*
* @param[in] n
* The number of columns of the matrix A. n >= 0.
*
* @param[in,out] pA
* On entry, pointer to the m-by-n matrix A.
* On exit, the elements on and below the diagonal of the array
* contain the m-by-min(m,n) lower trapezoidal matrix L (L is lower
* triangular if M <= N); the elements above the diagonal represent
* the orthogonal matrix Q as a product of elementary reflectors, stored
* by tiles.
*
* @param[in] lda
* The leading dimension of the array A. lda >= max(1,m).
*
* @param[out] T
* On exit, auxiliary factorization data, required by plasma_dgelqs
* to solve the system of equations.
* Matrix of T is allocated inside this function and needs to be
* destroyed by plasma_desc_destroy.
*
*******************************************************************************
*
* @retval PlasmaSuccess successful exit
* @retval < 0 if -i, the i-th argument had an illegal value
*
*******************************************************************************
*
* @sa plasma_omp_dgelqf
* @sa plasma_cgelqf
* @sa plasma_dgelqf
* @sa plasma_sgelqf
* @sa plasma_dgelqs
*
******************************************************************************/
int plasma_dgelqf(int m, int n,
double *pA, int lda,
plasma_desc_t *T)
{
// Get PLASMA context.
plasma_context_t *plasma = plasma_context_self();
if (plasma == NULL) {
plasma_fatal_error("PLASMA not initialized");
return PlasmaErrorNotInitialized;
}
// Check input arguments.
if (m < 0) {
plasma_error("illegal value of m");
return -1;
}
if (n < 0) {
plasma_error("illegal value of n");
return -2;
}
if (lda < imax(1, m)) {
plasma_error("illegal value of lda");
return -4;
}
// quick return
if (imin(m, n) == 0)
return PlasmaSuccess;
// Tune parameters.
if (plasma->tuning)
plasma_tune_gelqf(plasma, PlasmaRealDouble, m, n);
// Set tiling parameters.
int ib = plasma->ib;
int nb = plasma->nb;
plasma_enum_t householder_mode = plasma->householder_mode;
// Create tile matrix.
plasma_desc_t A;
int retval;
retval = plasma_desc_general_create(PlasmaRealDouble, nb, nb,
m, n, 0, 0, m, n, &A);
if (retval != PlasmaSuccess) {
plasma_error("plasma_desc_general_create() failed");
return retval;
}
// Prepare descriptor T.
retval = plasma_descT_create(A, ib, householder_mode, T);
if (retval != PlasmaSuccess) {
plasma_error("plasma_descT_create() failed");
return retval;
}
// Allocate workspace.
plasma_workspace_t work;
size_t lwork = nb + ib*nb; // gelqt: tau + work
retval = plasma_workspace_create(&work, lwork, PlasmaRealDouble);
if (retval != PlasmaSuccess) {
plasma_error("plasma_workspace_create() failed");
return retval;
}
// Initialize sequence.
plasma_sequence_t sequence;
retval = plasma_sequence_init(&sequence);
// Initialize request.
plasma_request_t request;
retval = plasma_request_init(&request);
// asynchronous block
#pragma omp parallel
#pragma omp master
{
// Translate to tile layout.
plasma_omp_dge2desc(pA, lda, A, &sequence, &request);
// Call the tile async function.
plasma_omp_dgelqf(A, *T, work, &sequence, &request);
// Translate back to LAPACK layout.
plasma_omp_ddesc2ge(A, pA, lda, &sequence, &request);
}
// implicit synchronization
plasma_workspace_destroy(&work);
// Free matrix A in tile layout.
plasma_desc_destroy(&A);
// Return status.
int status = sequence.status;
return status;
}
/***************************************************************************//**
*
* @ingroup plasma_gelqf
*
* Computes the tile LQ factorization of a matrix.
* Non-blocking tile version of plasma_dgelqf().
* May return before the computation is finished.
* Allows for pipelining of operations at runtime.
*
*******************************************************************************
*
* @param[in,out] A
* Descriptor of matrix A.
* A is stored in the tile layout.
*
* @param[out] T
* Descriptor of matrix T.
* On exit, auxiliary factorization data, required by plasma_dgelqs to
* solve the system of equations.
*
* @param[in] work
* Workspace for the auxiliary arrays needed by some coreblas kernels.
* For LQ factorization, contains preallocated space for tau and work
* arrays. Allocated by the plasma_workspace_create function.
*
* @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_dgelqf
* @sa plasma_omp_cgelqf
* @sa plasma_omp_dgelqf
* @sa plasma_omp_sgelqf
* @sa plasma_omp_dgelqs
*
******************************************************************************/
void plasma_omp_dgelqf(plasma_desc_t A, plasma_desc_t T,
plasma_workspace_t work,
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 (plasma_desc_check(A) != PlasmaSuccess) {
plasma_error("invalid A");
plasma_request_fail(sequence, request, PlasmaErrorIllegalValue);
return;
}
if (plasma_desc_check(T) != PlasmaSuccess) {
plasma_error("invalid T");
plasma_request_fail(sequence, request, PlasmaErrorIllegalValue);
return;
}
if (sequence == NULL) {
plasma_fatal_error("NULL sequence");
plasma_request_fail(sequence, request, PlasmaErrorIllegalValue);
return;
}
if (request == NULL) {
plasma_fatal_error("NULL request");
plasma_request_fail(sequence, request, PlasmaErrorIllegalValue);
return;
}
// quick return
if (imin(A.m, A.n) == 0)
return;
// Call the parallel function.
if (plasma->householder_mode == PlasmaTreeHouseholder) {
plasma_pdgelqf_tree(A, T, work, sequence, request);
}
else {
plasma_pdgelqf(A, T, work, sequence, request);
}
}
|
generator.h | // Copyright (c) 2015, The Regents of the University of California (Regents)
// See LICENSE.txt for license details
#ifndef GENERATOR_H_
#define GENERATOR_H_
#include <algorithm>
#include <cinttypes>
#include <random>
#include <iostream>
#include "graph.h"
#include "pvector.h"
#include "util.h"
#include <boost/random/uniform_real_distribution.hpp>
/*
GAP Benchmark Suite
Class: Generator
Author: Scott Beamer
Given scale and degree, generates edgelist for synthetic graph
- Intended to be called from Builder
- GenerateEL(uniform) generates and returns the edgelist
- Can generate uniform random (uniform=true) or R-MAT graph according
to Graph500 parameters (uniform=false)
- Can also randomize weights within a weighted edgelist (InsertWeights)
- Blocking/reseeding is for parallelism with deterministic output edgelist
*/
template <typename NodeID_, typename DestID_ = NodeID_,
typename WeightT_ = NodeID_>
class Generator {
typedef EdgePair<NodeID_, DestID_> Edge;
typedef EdgePair<NodeID_, NodeWeight<NodeID_, WeightT_>> WEdge;
typedef pvector<Edge> EdgeList;
public:
Generator(int scale, int degree) {
scale_ = scale;
num_nodes_ = 1l << scale;
num_edges_ = num_nodes_ * degree;
if (num_nodes_ > std::numeric_limits<NodeID_>::max()) {
std::cout << "NodeID type (max: " << std::numeric_limits<NodeID_>::max();
std::cout << ") too small to hold " << num_nodes_ << std::endl;
std::cout << "Recommend changing NodeID (typedef'd in src/benchmark.h)";
std::cout << " to a wider type and recompiling" << std::endl;
std::exit(-31);
}
}
void PermuteIDs(EdgeList &el) {
pvector<NodeID_> permutation(num_nodes_);
std::mt19937 rng(kRandSeed);
#pragma omp parallel for
for (NodeID_ n=0; n < num_nodes_; n++)
permutation[n] = n;
shuffle(permutation.begin(), permutation.end(), rng);
#pragma omp parallel for
for (int64_t e=0; e < num_edges_; e++)
el[e] = Edge(permutation[el[e].u], permutation[el[e].v]);
}
EdgeList MakeUniformEL() {
EdgeList el(num_edges_);
#pragma omp parallel
{
std::mt19937 rng;
std::uniform_int_distribution<NodeID_> udist(0, num_nodes_-1);
#pragma omp for
for (int64_t block=0; block < num_edges_; block+=block_size) {
rng.seed(kRandSeed + block/block_size);
for (int64_t e=block; e < std::min(block+block_size, num_edges_); e++) {
el[e] = Edge(udist(rng), udist(rng));
}
}
}
return el;
}
EdgeList MakeRMatEL() {
const float A = 0.57f, B = 0.19f, C = 0.19f;
EdgeList el(num_edges_);
#pragma omp parallel
{
static std::mt19937 rng;
static boost::random::uniform_real_distribution<> udist(0, 1.0f);
#pragma omp threadprivate(rng , udist)
#pragma omp for
for (int64_t block=0; block < num_edges_; block+=block_size) {
// std::mt19937 rng;
// boost::random::uniform_real_distribution<float> udist(0, 1.0f);
rng.seed(kRandSeed + block/block_size);
for (int64_t e=block; e < std::min(block+block_size, num_edges_); e++) {
NodeID_ src = 0, dst = 0;
for (int depth=0; depth < scale_; depth++) {
float rand_point = udist(rng);
src = src << 1;
dst = dst << 1;
if (rand_point < A+B) {
if (rand_point > A)
dst++;
} else {
src++;
if (rand_point > A+B+C)
dst++;
}
}
el[e] = Edge(src, dst);
}
}
}
PermuteIDs(el);
// TIME_PRINT("Shuffle", std::shuffle(el.begin(), el.end(),
// std::mt19937()));
return el;
}
EdgeList GenerateEL(bool uniform) {
EdgeList el;
Timer t;
t.Start();
if (uniform)
el = MakeUniformEL();
else
el = MakeRMatEL();
t.Stop();
PrintTime("Generate Time", t.Seconds());
return el;
}
static void InsertWeights(pvector<EdgePair<NodeID_, NodeID_>> &el) {}
// Overwrites existing weights with random from [1,255]
static void InsertWeights(pvector<WEdge> &el) {
#pragma omp parallel
{
std::mt19937 rng;
std::uniform_int_distribution<int> udist(1, 255);
int64_t el_size = el.size();
#pragma omp for
for (int64_t block=0; block < el_size; block+=block_size) {
rng.seed(kRandSeed + block/block_size);
for (int64_t e=block; e < std::min(block+block_size, el_size); e++) {
el[e].v.w = static_cast<WeightT_>(udist(rng));
}
}
}
}
private:
int scale_;
int64_t num_nodes_;
int64_t num_edges_;
static const int64_t block_size = 1<<18;
};
#endif // GENERATOR_H_
|
task_codegen.c | // RUN: %clang_cc1 -verify -triple x86_64-apple-darwin10 -fopenmp -x c -emit-llvm %s -o - | FileCheck %s
// RUN: %clang_cc1 -fopenmp -x c -triple x86_64-apple-darwin10 -emit-pch -o %t %s
// RUN: %clang_cc1 -fopenmp -x c -triple x86_64-apple-darwin10 -include-pch %t -verify %s -emit-llvm -o - | FileCheck %s
// expected-no-diagnostics
#ifndef HEADER
#define HEADER
void foo();
// CHECK-LABEL: @main
int main() {
// CHECK: call i32 @__kmpc_global_thread_num(
// CHECK: call i8* @__kmpc_omp_task_alloc(
// CHECK: call i32 @__kmpc_omp_task(
#pragma omp task
{
#pragma omp taskgroup
{
#pragma omp task
foo();
}
}
// CHECK: ret i32 0
return 0;
}
// CHECK: call void @__kmpc_taskgroup(
// CHECK: call i8* @__kmpc_omp_task_alloc(
// CHECK: call i32 @__kmpc_omp_task(
// CHECK: call void @__kmpc_end_taskgroup(
#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] = 32;
tile_size[1] = 32;
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;
}
|
convert_csc_x_coo.c | #include "alphasparse/format.h"
#include <stdlib.h>
#include <alphasparse/opt.h>
#include <alphasparse/util.h>
#include <memory.h>
static int col_first_cmp(const ALPHA_Point *a, const ALPHA_Point *b)
{
if (a->y != b->y)
return a->y - b->y;
return a->x - b->x;
}
alphasparse_status_t ONAME(const ALPHA_SPMAT_COO *source, ALPHA_SPMAT_CSC **dest)
{
ALPHA_SPMAT_CSC *mat = alpha_malloc(sizeof(ALPHA_SPMAT_CSC));
*dest = mat;
ALPHA_INT m = source->rows;
ALPHA_INT n = source->cols;
ALPHA_INT nnz = source->nnz;
//sort by (col,row)
ALPHA_Point *points = alpha_malloc(sizeof(ALPHA_Point) * nnz);
for (ALPHA_INT i = 0; i < nnz; i++)
{
points[i].x = source->row_indx[i];
points[i].y = source->col_indx[i];
points[i].v = source->values[i];
}
qsort(points, nnz, sizeof(ALPHA_Point), (__compar_fn_t)col_first_cmp);
mat->rows = m;
mat->cols = n;
ALPHA_INT *cols_offset = alpha_memalign((n + 1) * sizeof(ALPHA_INT), DEFAULT_ALIGNMENT);
mat->row_indx = alpha_memalign(nnz * sizeof(ALPHA_INT), DEFAULT_ALIGNMENT);
mat->values = alpha_memalign(nnz * sizeof(ALPHA_Number), DEFAULT_ALIGNMENT);
mat->cols_start = cols_offset;
mat->cols_end = cols_offset + 1;
mat->cols_start[0] = 0;
ALPHA_INT index = 0;
ALPHA_INT count = 0;
for (ALPHA_INT i = 0; i < nnz; i++)
{
while (index < points[i].y)
{
mat->cols_end[index] = count;
index += 1;
}
if (index == points[i].y)
{
count += 1;
}
}
while (index < n - 1)
{
mat->cols_end[index] = count;
index += 1;
}
mat->cols_end[n - 1] = count;
ALPHA_INT num_threads = alpha_get_thread_num();
ALPHA_INT* partition = alpha_malloc(sizeof(ALPHA_INT)*(num_threads+1));
balanced_partition_row_by_nnz(mat->cols_end, mat->cols, num_threads, partition);
#ifdef _OPENMP
#pragma omp parallel num_threads(num_threads)
#endif
{
ALPHA_INT tid = alpha_get_thread_id();
ALPHA_INT lcs = partition[tid];
ALPHA_INT lch = partition[tid + 1];
for (ALPHA_INT ac = lcs; ac < lch; ac++)
{
for (ALPHA_INT ai = mat->cols_start[ac]; ai < mat->cols_end[ac]; ++ai)
{
mat->row_indx[ai] = points[ai].x;
mat->values[ai] = points[ai].v;
}
}
}
alpha_free(points);
alpha_free(partition);
return ALPHA_SPARSE_STATUS_SUCCESS;
} |
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] = 4;
tile_size[1] = 4;
tile_size[2] = 16;
tile_size[3] = 32;
tile_size[4] = -1;
// for timekeeping
int ts_return = -1;
struct timeval start, end, result;
double tdiff = 0.0, min_tdiff=1.e100;
const int BASE = 1024;
// initialize variables
//
srand(42);
for (i = 1; i < Nz; i++) {
for (j = 1; j < Ny; j++) {
for (k = 1; k < Nx; k++) {
A[0][i][j][k] = 1.0 * (rand() % BASE);
}
}
}
for (m=0; m<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_unop__identity_int16_bool.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_int16_bool)
// op(A') function: GB (_unop_tran__identity_int16_bool)
// C type: int16_t
// A type: bool
// cast: int16_t cij = (int16_t) aij
// unaryop: cij = aij
#define GB_ATYPE \
bool
#define GB_CTYPE \
int16_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) \
int16_t z = (int16_t) aij ;
// cij = op (aij)
#define GB_CAST_OP(pC,pA) \
{ \
/* aij = Ax [pA] */ \
bool aij = Ax [pA] ; \
/* Cx [pC] = op (cast (aij)) */ \
int16_t z = (int16_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_INT16 || GxB_NO_BOOL)
//------------------------------------------------------------------------------
// Cx = op (cast (Ax)): apply a unary operator
//------------------------------------------------------------------------------
GrB_Info GB (_unop_apply__identity_int16_bool)
(
int16_t *Cx, // Cx and Ax may be aliased
const bool *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++)
{
bool aij = Ax [p] ;
int16_t z = (int16_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 ;
bool aij = Ax [p] ;
int16_t z = (int16_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_int16_bool)
(
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
|
CostEvaluatorFull.h | /**********************************************************************************************************************
This file is part of the Control Toolbox (https://adrlab.bitbucket.io/ct), copyright by ETH Zurich, Google Inc.
Authors: Michael Neunert, Markus Giftthaler, Markus Stäuble, Diego Pardo, Farbod Farshidian
Licensed under Apache2 license (see LICENSE file in main directory)
**********************************************************************************************************************/
#pragma once
//#include <omp.h>
#include <math.h>
#include <cmath>
#include <functional>
#include <ct/optcon/costfunction/CostFunctionQuadratic.hpp>
#include <ct/optcon/dms/dms_core/OptVectorDms.h>
#include <ct/optcon/dms/dms_core/ShotContainer.h>
#include <ct/optcon/nlp/DiscreteCostEvaluatorBase.h>
namespace ct {
namespace optcon {
/**
* @ingroup DMS
*
* @brief Performs the full cost integration over the shots
*
* @tparam STATE_DIM The state dimension
* @tparam CONTROL_DIM The input dimension
*/
template <size_t STATE_DIM, size_t CONTROL_DIM, typename SCALAR = double>
class CostEvaluatorFull : public tpl::DiscreteCostEvaluatorBase<SCALAR>
{
public:
EIGEN_MAKE_ALIGNED_OPERATOR_NEW
typedef DmsDimensions<STATE_DIM, CONTROL_DIM, SCALAR> DIMENSIONS;
typedef typename DIMENSIONS::state_vector_t state_vector_t;
typedef typename DIMENSIONS::control_vector_t control_vector_t;
typedef typename DIMENSIONS::state_vector_array_t state_vector_array_t;
typedef typename DIMENSIONS::control_vector_array_t control_vector_array_t;
typedef typename DIMENSIONS::time_array_t time_array_t;
CostEvaluatorFull() = delete;
/**
* @brief Custom constructor
*
* @param[in] costFct The cost function
* @param[in] w The optimization vector
* @param[in] controlSpliner The control spliner
* @param[in] shotInt The shot number
* @param[in] settings The dms settings
*/
CostEvaluatorFull(std::shared_ptr<ct::optcon::CostFunctionQuadratic<STATE_DIM, CONTROL_DIM, SCALAR>> costFct,
std::shared_ptr<OptVectorDms<STATE_DIM, CONTROL_DIM, SCALAR>> w,
std::shared_ptr<SplinerBase<control_vector_t, SCALAR>> controlSpliner,
std::vector<std::shared_ptr<ShotContainer<STATE_DIM, CONTROL_DIM, SCALAR>>> shotInt,
DmsSettings settings)
: costFct_(costFct), w_(w), controlSpliner_(controlSpliner), shotContainers_(shotInt), settings_(settings)
{
}
/**
* @brief The destructor.
*/
virtual ~CostEvaluatorFull() {}
virtual SCALAR eval() override
{
SCALAR cost = SCALAR(0.0);
#pragma omp parallel for num_threads(settings_.nThreads_)
for (auto shotContainer = shotContainers_.begin(); shotContainer < shotContainers_.end(); ++shotContainer)
{
(*shotContainer)->integrateCost();
}
for (auto shotContainer : shotContainers_)
cost += shotContainer->getCostIntegrated();
costFct_->setCurrentStateAndControl(w_->getOptimizedState(settings_.N_), control_vector_t::Zero());
cost += costFct_->evaluateTerminal();
return cost;
}
virtual void evalGradient(size_t grad_length, Eigen::Map<Eigen::Matrix<SCALAR, Eigen::Dynamic, 1>>& grad) override
{
grad.setZero();
assert(shotContainers_.size() == settings_.N_);
// go through all shots, integrate the state trajectories and evaluate cost accordingly
// intermediate costs
#pragma omp parallel for num_threads(settings_.nThreads_)
for (auto shotContainer = shotContainers_.begin(); shotContainer < shotContainers_.end(); ++shotContainer)
{
(*shotContainer)->integrateCostSensitivities();
}
for (size_t shotNr = 0; shotNr < shotContainers_.size(); ++shotNr)
{
switch (settings_.splineType_)
{
case DmsSettings::ZERO_ORDER_HOLD:
{
grad.segment(w_->getStateIndex(shotNr), STATE_DIM) += shotContainers_[shotNr]->getdLdSiIntegrated();
grad.segment(w_->getControlIndex(shotNr), CONTROL_DIM) +=
shotContainers_[shotNr]->getdLdQiIntegrated();
break;
}
case DmsSettings::PIECEWISE_LINEAR:
{
grad.segment(w_->getStateIndex(shotNr), STATE_DIM) += shotContainers_[shotNr]->getdLdSiIntegrated();
grad.segment(w_->getControlIndex(shotNr), CONTROL_DIM) +=
shotContainers_[shotNr]->getdLdQiIntegrated();
grad.segment(w_->getControlIndex(shotNr + 1), CONTROL_DIM) +=
shotContainers_[shotNr]->getdLdQip1Integrated();
break;
}
default:
throw(std::runtime_error(
" cost gradient not yet implemented for this type of interpolation. Exiting"));
}
// H-part.
// if(settings_.objectiveType_ == DmsSettings::OPTIMIZE_GRID)
// {
// costFct_->setCurrentStateAndControl(shotContainers_[shotNr]->getStateIntegrated(),
// controlSpliner_->evalSpline(shotContainers_[shotNr]->getIntegrationTimeFinal(), shotNr));
// grad(w_->getTimeSegmentIndex(shotNr)) = costFct_->evaluateIntermediate() + shotContainers_[shotNr]->getdLdHiIntegrated();
// }
}
/* gradient of terminal cost */
costFct_->setCurrentStateAndControl(w_->getOptimizedState(settings_.N_), control_vector_t::Zero());
grad.segment(w_->getStateIndex(settings_.N_), STATE_DIM) +=
costFct_->stateDerivativeTerminal(); // * dXdSi.back();
}
private:
std::shared_ptr<ct::optcon::CostFunctionQuadratic<STATE_DIM, CONTROL_DIM, SCALAR>> costFct_;
std::shared_ptr<OptVectorDms<STATE_DIM, CONTROL_DIM, SCALAR>> w_;
std::shared_ptr<SplinerBase<control_vector_t, SCALAR>> controlSpliner_;
std::vector<std::shared_ptr<ShotContainer<STATE_DIM, CONTROL_DIM, SCALAR>>> shotContainers_;
const DmsSettings settings_;
};
} // namespace optcon
} // namespace ct
|
shared_update.c | // RUN: %libomptarget-compile-run-and-check-generic
// REQUIRES: unified_shared_memory
// amdgcn does not have printf definition
// XFAIL: amdgcn-amd-amdhsa
#include <stdio.h>
#include <omp.h>
// ---------------------------------------------------------------------------
// Various definitions copied from OpenMP RTL
extern void __tgt_register_requires(int64_t);
// End of definitions copied from OpenMP RTL.
// ---------------------------------------------------------------------------
#pragma omp requires unified_shared_memory
#define N 1024
int main(int argc, char *argv[]) {
int fails;
void *host_alloc, *device_alloc;
void *host_data, *device_data;
int *alloc = (int *)malloc(N * sizeof(int));
int data[N];
// Manual registration of requires flags for Clang versions
// that do not support requires.
__tgt_register_requires(8);
for (int i = 0; i < N; ++i) {
alloc[i] = 10;
data[i] = 1;
}
host_data = &data[0];
host_alloc = &alloc[0];
// implicit mapping of data
#pragma omp target map(tofrom : device_data, device_alloc)
{
device_data = &data[0];
device_alloc = &alloc[0];
for (int i = 0; i < N; i++) {
alloc[i] += 1;
data[i] += 1;
}
}
// CHECK: Address of alloc on device matches host address.
if (device_alloc == host_alloc)
printf("Address of alloc on device matches host address.\n");
// CHECK: Address of data on device matches host address.
if (device_data == host_data)
printf("Address of data on device matches host address.\n");
// On the host, check that the arrays have been updated.
// CHECK: Alloc device values updated: Succeeded
fails = 0;
for (int i = 0; i < N; i++) {
if (alloc[i] != 11)
fails++;
}
printf("Alloc device values updated: %s\n",
(fails == 0) ? "Succeeded" : "Failed");
// CHECK: Data device values updated: Succeeded
fails = 0;
for (int i = 0; i < N; i++) {
if (data[i] != 2)
fails++;
}
printf("Data device values updated: %s\n",
(fails == 0) ? "Succeeded" : "Failed");
//
// Test that updates on the host snd on the device are both visible.
//
// Update on the host.
for (int i = 0; i < N; ++i) {
alloc[i] += 1;
data[i] += 1;
}
#pragma omp target
{
// CHECK: Alloc host values updated: Succeeded
fails = 0;
for (int i = 0; i < N; i++) {
if (alloc[i] != 12)
fails++;
}
printf("Alloc host values updated: %s\n",
(fails == 0) ? "Succeeded" : "Failed");
// CHECK: Data host values updated: Succeeded
fails = 0;
for (int i = 0; i < N; i++) {
if (data[i] != 3)
fails++;
}
printf("Data host values updated: %s\n",
(fails == 0) ? "Succeeded" : "Failed");
}
free(alloc);
printf("Done!\n");
return 0;
}
|
o5logon_fmt_plug.c | /* Cracker for Oracle's O5LOGON protocol hashes. Hacked together during
* September of 2012 by Dhiru Kholia <dhiru.kholia at gmail.com>.
*
* O5LOGON is used since version 11g. CVE-2012-3137 applies to Oracle 11.1
* and 11.2 databases. Oracle has "fixed" the problem in version 11.2.0.3.
*
* This software is Copyright (c) 2012, Dhiru Kholia <dhiru.kholia at gmail.com>,
* and it is hereby released to the general public under the following terms:
* Redistribution and use in source and binary forms, with or without modification,
* are permitted. */
/*
* Modifications (c) 2014 Harrison Neal, released under the same terms
* as the original.
*/
#if FMT_EXTERNS_H
extern struct fmt_main fmt_o5logon;
#elif FMT_REGISTERS_H
john_register_one(&fmt_o5logon);
#else
#include <string.h>
#include <assert.h>
#include <errno.h>
#include "arch.h"
#include "sha.h"
#include "misc.h"
#include "common.h"
#include "formats.h"
#include "params.h"
#include "options.h"
#include "aes/aes.h"
#ifdef _OPENMP
static int omp_t = 1;
#include <omp.h>
#define OMP_SCALE 512 // tuned on core i7
#endif
#include "memdbg.h"
#define FORMAT_LABEL "o5logon"
#define FORMAT_NAME "Oracle O5LOGON protocol"
#define ALGORITHM_NAME "SHA1 AES 32/" ARCH_BITS_STR
#define BENCHMARK_COMMENT ""
#define BENCHMARK_LENGTH -1
#define PLAINTEXT_LENGTH 32
#define CIPHERTEXT_LENGTH 48
#define SALT_LENGTH 10
#define BINARY_SIZE 0
#define BINARY_ALIGN 1
#define SALT_ALIGN 1
#define SALT_SIZE sizeof(struct custom_salt)
#define MIN_KEYS_PER_CRYPT 1
#define MAX_KEYS_PER_CRYPT 1
static struct fmt_tests o5logon_tests[] = {
{"$o5logon$566499330E8896301A1D2711EFB59E756D41AF7A550488D82FE7C8A418E5BE08B4052C0DC404A805C1D7D43FE3350873*4F739806EBC1D7742BC6", "password"},
{"$o5logon$3BB71A77E1DBB5FFCCC8FC8C4537F16584CB5113E4CCE3BAFF7B66D527E32D29DF5A69FA747C4E2C18C1837F750E5BA6*4F739806EBC1D7742BC6", "password"},
{"$o5logon$ED91B97A04000F326F17430A65DACB30CD1EF788E6EC310742B811E32112C0C9CC39554C9C01A090CB95E95C94140C28*7FD52BC80AA5836695D4", "test1"},
{"$o5logon$B7711CC7E805520CEAE8C1AC459F745639E6C9338F192F92204A9518B226ED39851C154CB384E4A58C444A6DF26146E4*3D14D54520BC9E6511F4", "openwall"},
{"$o5logon$76F9BBAEEA9CF70F2A660A909F85F374F16F0A4B1BE1126A062AE9F0D3268821EF361BF08EBEF392F782F2D6D0192FD6*3D14D54520BC9E6511F4", "openwall"},
{"$o5logon$C35A36EA7FF7293EF828B2BD5A2830CA28A57BF621EAE14B605D41A88FC2CF7EFE7C73495FB22F06D6D98317D63DDA71*406813CBAEED2FD4AD23", "MDDATA"},
{"$o5logon$B9AC30E3CD7E1D7C95FA17E1C62D061289C36FD5A6C45C098FF7572AB9AD2B684FB7E131E03CE1543A5A99A30D68DD13*447BED5BE70F7067D646", "sys"},
// the following hash (from HITCON 2014 CTF) revealed multiple bugs in this format (false positives)!
// m3odbe
// m3o3rt
{"$o5logon$A10D52C1A432B61834F4B0D9592F55BD0DA2B440AEEE1858515A646683240D24A61F0C9366C63E93D629292B7891F44A*878C0B92D61A594F2680", "m3ow00"},
{NULL}
};
static char (*saved_key)[PLAINTEXT_LENGTH + 1];
static int *cracked, any_cracked;
static struct custom_salt {
char unsigned salt[SALT_LENGTH]; /* AUTH_VFR_DATA */
char unsigned ct[CIPHERTEXT_LENGTH]; /* AUTH_SESSKEY */
} *cur_salt;
static aes_fptr_cbc aesFunc;
static void init(struct fmt_main *self)
{
char *Buf;
#ifdef _OPENMP
omp_t = omp_get_max_threads();
self->params.min_keys_per_crypt *= omp_t;
omp_t *= OMP_SCALE;
self->params.max_keys_per_crypt *= omp_t;
#endif
saved_key = mem_calloc_tiny(sizeof(*saved_key) *
self->params.max_keys_per_crypt, MEM_ALIGN_WORD);
cracked = mem_calloc_tiny(sizeof(*cracked) *
self->params.max_keys_per_crypt, MEM_ALIGN_WORD);
aesFunc = get_AES_dec192_CBC();
Buf = mem_alloc_tiny(128, 1);
sprintf(Buf, "%s %s", self->params.algorithm_name, get_AES_type_string());
self->params.algorithm_name=Buf;
}
static int ishex(char *q)
{
while (atoi16[ARCH_INDEX(*q)] != 0x7F)
q++;
return !*q;
}
static int valid(char *ciphertext, struct fmt_main *self)
{
char *ctcopy;
char *keeptr;
char *p;
if (strncmp(ciphertext, "$o5logon$", 9))
return 0;
ctcopy = strdup(ciphertext);
keeptr = ctcopy;
ctcopy += 9;
p = strtok(ctcopy, "*"); /* ciphertext */
if(!p)
goto err;
if(strlen(p) != CIPHERTEXT_LENGTH * 2)
goto err;
if (!ishex(p))
goto err;
if ((p = strtok(NULL, "*")) == NULL) /* salt */
goto err;
if(strlen(p) != SALT_LENGTH * 2)
goto err;
if (!ishex(p))
goto err;
MEM_FREE(keeptr);
return 1;
err:
MEM_FREE(keeptr);
return 0;
}
static void *get_salt(char *ciphertext)
{
char *ctcopy = strdup(ciphertext);
char *keeptr = ctcopy;
char *p;
int i;
static struct custom_salt cs;
ctcopy += 9; /* skip over "$o5logon$" */
p = strtok(ctcopy, "*");
for (i = 0; i < CIPHERTEXT_LENGTH; i++)
cs.ct[i] = atoi16[ARCH_INDEX(p[i * 2])] * 16
+ atoi16[ARCH_INDEX(p[i * 2 + 1])];
p = strtok(NULL, "*");
for (i = 0; i < SALT_LENGTH; i++)
cs.salt[i] = atoi16[ARCH_INDEX(p[i * 2])] * 16
+ atoi16[ARCH_INDEX(p[i * 2 + 1])];
MEM_FREE(keeptr);
return (void *)&cs;
}
static void set_salt(void *salt)
{
cur_salt = (struct custom_salt *)salt;
}
static int crypt_all(int *pcount, struct db_salt *salt)
{
int count = *pcount;
int index = 0;
if (any_cracked) {
memset(cracked, 0, sizeof(*cracked) * count);
any_cracked = 0;
}
#ifdef _OPENMP
#pragma omp parallel for
for (index = 0; index < count; index++)
#endif
{
unsigned char key[24];
unsigned char pt[16];
unsigned char iv[16];
// No longer using AES key here.
SHA_CTX ctx;
memset(&key[20], 0, 4);
SHA1_Init(&ctx);
SHA1_Update(&ctx, saved_key[index], strlen(saved_key[index]));
SHA1_Update(&ctx, cur_salt->salt, 10);
SHA1_Final(key, &ctx);
memcpy(iv, cur_salt->ct + 16, 16);
// Using AES function:
// in (cipher), out (plain), key, block count, iv
aesFunc(cur_salt->ct + 32, pt, key, 1, iv);
if (!memcmp(pt + 8, "\x08\x08\x08\x08\x08\x08\x08\x08", 8)) {
cracked[index] = 1;
#ifdef _OPENMP
#pragma omp atomic
#endif
any_cracked |= 1;
}
}
return count;
}
static int cmp_all(void *binary, int count)
{
return any_cracked;
}
static int cmp_one(void *binary, int index)
{
return cracked[index];
}
static int cmp_exact(char *source, int index)
{
return 1;
}
static void o5logon_set_key(char *key, int index)
{
int saved_key_length = strlen(key);
if (saved_key_length > PLAINTEXT_LENGTH)
saved_key_length = PLAINTEXT_LENGTH;
memcpy(saved_key[index], key, saved_key_length);
saved_key[index][saved_key_length] = 0;
}
static char *get_key(int index)
{
return saved_key[index];
}
struct fmt_main fmt_o5logon = {
{
FORMAT_LABEL,
FORMAT_NAME,
ALGORITHM_NAME,
BENCHMARK_COMMENT,
BENCHMARK_LENGTH,
PLAINTEXT_LENGTH,
BINARY_SIZE,
BINARY_ALIGN,
SALT_SIZE,
SALT_ALIGN,
MIN_KEYS_PER_CRYPT,
MAX_KEYS_PER_CRYPT,
FMT_CASE | FMT_8_BIT | FMT_OMP,
#if FMT_MAIN_VERSION > 11
{ NULL },
#endif
o5logon_tests
}, {
init,
fmt_default_done,
fmt_default_reset,
fmt_default_prepare,
valid,
fmt_default_split,
fmt_default_binary,
get_salt,
#if FMT_MAIN_VERSION > 11
{ NULL },
#endif
fmt_default_source,
{
fmt_default_binary_hash
},
fmt_default_salt_hash,
set_salt,
o5logon_set_key,
get_key,
fmt_default_clear_keys,
crypt_all,
{
fmt_default_get_hash
},
cmp_all,
cmp_one,
cmp_exact
}
};
#endif /* plugin stanza */
|
DRACC_OMP_042_Wrong_ordered_clause_Inter_yes.c | /*
Data race between the values in countervar leading to changing results, by utilising the ordered construct the execution will be sequentially consistent.
*/
#include <stdio.h>
#include <stdbool.h>
#include <stdlib.h>
#define N 42000
int countervar[N];
int init(){
for(int i=0; i<N; i++){
countervar[i]=0;
}
return 0;
}
int count(){
#pragma omp target map(tofrom:countervar[0:N]) device(0)
#pragma omp teams distribute
for (int i=1; i<N; i++){
countervar[i]=countervar[i-1]+1;
}
return 0;
}
int check(){
bool test = false;
for(int i=0; i<N; i++){
if(countervar[i]!=i){
test = true;
}
}
printf("Memory Access Issue visible: %s\n",test ? "true" : "false");
return 0;
}
int main(){
init();
count();
check();
return 0;
} |
core_zlantr.c | /**
*
* @file
*
* PLASMA is a software package provided by:
* University of Tennessee, US,
* University of Manchester, UK.
*
* @precisions normal z -> c d s
*
**/
#include "core_blas.h"
#include "plasma_types.h"
#include "plasma_internal.h"
#include "core_lapack.h"
#include <math.h>
/******************************************************************************/
void core_zlantr(plasma_enum_t norm, plasma_enum_t uplo, plasma_enum_t diag,
int m, int n,
const plasma_complex64_t *A, int lda,
double *work, double *value)
{
// Due to a bug in LAPACKE < 3.6.1, this function always returns zero.
// *value = LAPACKE_zlantr_work(LAPACK_COL_MAJOR,
// lapack_const(norm), lapack_const(uplo),
// lapack_const(diag),
// m, n, A, lda, work);
// Calling LAPACK directly instead.
char nrm = lapack_const(norm);
char upl = lapack_const(uplo);
char dia = lapack_const(diag);
*value = LAPACK_zlantr(&nrm, &upl, &dia, &m, &n, A, &lda, work);
}
/******************************************************************************/
void core_omp_zlantr(plasma_enum_t norm, plasma_enum_t uplo, plasma_enum_t diag,
int m, int n,
const plasma_complex64_t *A, int lda,
double *work, double *value,
plasma_sequence_t *sequence, plasma_request_t *request)
{
#pragma omp task depend(in:A[0:lda*n]) \
depend(out:value[0:1])
{
if (sequence->status == PlasmaSuccess)
core_zlantr(norm, uplo, diag, m, n, A, lda, work, value);
}
}
/******************************************************************************/
void core_omp_zlantr_aux(plasma_enum_t norm, plasma_enum_t uplo,
plasma_enum_t diag,
int m, int n,
const plasma_complex64_t *A, int lda,
double *value,
plasma_sequence_t *sequence, plasma_request_t *request)
{
switch (norm) {
case PlasmaOneNorm:
#pragma omp task depend(in:A[0:lda*n]) \
depend(out:value[0:n])
{
if (sequence->status == PlasmaSuccess) {
if (uplo == PlasmaUpper) {
if (diag == PlasmaNonUnit) {
for (int j = 0; j < n; j++) {
value[j] = cabs(A[lda*j]);
for (int i = 1; i < imin(j+1, m); i++) {
value[j] += cabs(A[lda*j+i]);
}
}
}
else { // PlasmaUnit
int j;
for (j = 0; j < imin(n, m); j++) {
value[j] = 1.0;
for (int i = 0; i < j; i++) {
value[j] += cabs(A[lda*j+i]);
}
}
for (; j < n; j++) {
value[j] = cabs(A[lda*j]);
for (int i = 1; i < m; i++) {
value[j] += cabs(A[lda*j+i]);
}
}
}
}
else { // PlasmaLower
if (diag == PlasmaNonUnit) {
int j;
for (j = 0; j < imin(n, m); j++) {
value[j] = cabs(A[lda*j+j]);
for (int i = j+1; i < m; i++) {
value[j] += cabs(A[lda*j+i]);
}
}
for (; j < n; j++)
value[j] = 0.0;
}
else { // PlasmaUnit
int j;
for (j = 0; j < imin(n, m); j++) {
value[j] = 1.0;
for (int i = j+1; i < m; i++) {
value[j] += cabs(A[lda*j+i]);
}
}
for (; j < n; j++)
value[j] = 0.0;
}
}
}
}
break;
case PlasmaInfNorm:
#pragma omp task depend(in:A[0:lda*n]) \
depend(out:value[0:m])
{
if (sequence->status == PlasmaSuccess) {
if (uplo == PlasmaUpper) {
if (diag == PlasmaNonUnit) {
for (int i = 0; i < m; i++)
value[i] = 0.0;
for (int j = 0; j < n; j++) {
for (int i = 0; i < imin(j+1, m); i++) {
value[i] += cabs(A[lda*j+i]);
}
}
}
else { // PlasmaUnit
int i;
for (i = 0; i < imin(m, n); i++)
value[i] = 1.0;
for (; i < m; i++)
value[i] = 0.0;
int j;
for (j = 0; j < imin(n, m); j++) {
for (i = 0; i < j; i++) {
value[i] += cabs(A[lda*j+i]);
}
}
for (; j < n; j++) {
for (i = 0; i < m; i++) {
value[i] += cabs(A[lda*j+i]);
}
}
}
}
else { // PlasmaLower
if (diag == PlasmaNonUnit) {
for (int i = 0; i < m; i++)
value[i] = 0.0;
for (int j = 0; j < imin(n, m); j++) {
for (int i = j; i < m; i++) {
value[i] += cabs(A[lda*j+i]);
}
}
}
else { // PlasmaUnit
int i;
for (i = 0; i < imin(m, n); i++)
value[i] = 1.0;
for (; i < m; i++)
value[i] = 0.0;
for (int j = 0; j < imin(n, m); j++) {
for (i = j+1; i < m; i++) {
value[i] += cabs(A[lda*j+i]);
}
}
}
}
}
}
break;
}
}
|
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] = 256;
tile_size[4] = -1;
// for timekeeping
int ts_return = -1;
struct timeval start, end, result;
double tdiff = 0.0, min_tdiff=1.e100;
const int BASE = 1024;
// initialize variables
//
srand(42);
for (i = 1; i < Nz; i++) {
for (j = 1; j < Ny; j++) {
for (k = 1; k < Nx; k++) {
A[0][i][j][k] = 1.0 * (rand() % BASE);
}
}
}
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;
}
|
pt_mat.h | // -*- mode:c++;c-basic-offset:4 -*-
#ifndef INCLUDED_PT_MAT_H__
#define INCLUDED_PT_MAT_H__
#include <config.h>
/*! \file
\brief Generic parallel transport.
*/
#include <util/gjp.h>
#include <comms/scu.h>
#include <util/omp_wrapper.h>
#include <vector>
#include <cstddef>
CPS_START_NAMESPACE
// namespace pt_generic: contains a single useful routine pt() for
// generic parallel transport. Roughly this is a rewrite of pt_mat()
// (you can find equivalent code in
// src/util/parallel_transport/pt_base/noarch/pt.C) but use threaded
// calculation and parallel communication.
//
// pt() does the following:
// 1. For forward direction (dir = 0, 2, 4, 6 correspond to +X, +Y, +Z, +T),
// out(x) = U_\mu(x) in(x+\mu) or out(x-\mu) = U_\mu(x-\mu) in(x)
//
// 2. For backward direction (dir = 1, 3, 5, 7 correspond to -X, -Y, -Z, -T),
// out(x) = U_\mu(x-\mu)^\dag in(x-\mu) or out(x+\mu) = U_\mu(x)^\dag in(x)
namespace pt_generic {
enum { NUM_DIR = 8 };
static inline int idx_4d(const int x[4], const int lx[4]) {
int ret = 0;
for(int i = 3; i >= 0; --i) {
ret = ret * lx[i] + x[i];
}
return ret;
}
static inline int idx_4d_surf(const int x[4], const int lx[4], int mu) {
int ret = 0;
for(int i = 3; i >= 0; --i) {
if(i == mu) continue;
ret = ret * lx[i] + x[i];
}
return ret;
}
// Compute all size and offset data need for this batch of parallel transport.
// Everything is measured in # of elements of the Site object.
static void compute_comm(std::vector<int> &comm_size,
std::vector<int> &comm_off,
int total[],
int N, const int dir[])
{
int lcl[4] = { GJP.XnodeSites(), GJP.YnodeSites(), GJP.ZnodeSites(), GJP.TnodeSites() };
int vol4d = GJP.VolNodeSites();
int surf[4] = {vol4d / lcl[0], vol4d / lcl[1], vol4d / lcl[2], vol4d / lcl[3] };
for(int i = 0; i < NUM_DIR; ++i) total[i] = 0;
comm_size.resize(N);
comm_off.resize(N);
for(int i = 0; i < N; ++i) {
int mu = dir[i];
comm_size[i] = surf[mu / 2];
comm_off[i] = total[mu];
total[mu] += comm_size[i];
}
}
static void thread_work_partial(int nwork, int me, int nthreads,
int &mywork, int &myoff)
{
int basework = nwork / nthreads;
int backfill = nthreads - (nwork % nthreads);
mywork = (nwork + me) / nthreads;
myoff = basework * me;
if ( me > backfill )
myoff += (me-backfill);
}
// collect surface data
template<typename Link, typename Site>
void collect(Site buf[], Link gauge[], Site vol[], int mu, bool do_send)
{
int lcl[4] = { GJP.XnodeSites(), GJP.YnodeSites(), GJP.ZnodeSites(), GJP.TnodeSites() };
int low[4] = { 0, 0, 0, 0 };
int high[4] = { lcl[0], lcl[1], lcl[2], lcl[3] };
bool backwards = mu % 2 ? true : false;
mu /= 2;
low[mu] = do_send == backwards ? lcl[mu] - 1 : 0;
high[mu] = low[mu] + 1;
const int hl[4] = {high[0] - low[0],
high[1] - low[1],
high[2] - low[2],
high[3] - low[3] };
const int hl_sites = hl[0] * hl[1] * hl[2] * hl[3];
int me = omp_get_thread_num();
int nthreads = omp_get_num_threads();
int mywork, myoff;
thread_work_partial(hl_sites, me, nthreads, mywork, myoff);
for(int i = 0; i < mywork; ++i) {
int x[4];
int tmp = i + myoff;
x[0] = tmp % hl[0] + low[0]; tmp /= hl[0];
x[1] = tmp % hl[1] + low[1]; tmp /= hl[1];
x[2] = tmp % hl[2] + low[2]; tmp /= hl[2];
x[3] = tmp % hl[3] + low[3];
int off_4d = idx_4d(x, lcl);
int off_3d = idx_4d_surf(x, lcl, mu);
if(do_send) {
if(backwards) {
Link tmp;
tmp.Dagger(gauge[mu + 4 * off_4d]);
buf[off_3d] = tmp * vol[off_4d];
} else {
buf[off_3d] = vol[off_4d];
}
} else {
if(backwards) {
vol[off_4d] = buf[off_3d];
} else {
vol[off_4d] = gauge[mu + 4 * off_4d] * buf[off_3d];
}
}
}
}
template<typename Link, typename Site>
void compute_internal(Site out[], Link gauge[], Site in[], int mu, int nthreads)
{
int lcl[4] = { GJP.XnodeSites(), GJP.YnodeSites(), GJP.ZnodeSites(), GJP.TnodeSites() };
int low[4] = { 0, 0, 0, 0 };
int high[4] = { lcl[0], lcl[1], lcl[2], lcl[3] };
bool backwards = mu % 2 ? true : false;
mu /= 2;
low[mu] = backwards ? 0 : 1;
high[mu] = low[mu] + lcl[mu] - 1;
const int hl[4] = {high[0] - low[0],
high[1] - low[1],
high[2] - low[2],
high[3] - low[3] };
const int hl_sites = hl[0] * hl[1] * hl[2] * hl[3];
int me = omp_get_thread_num();
int mywork, myoff;
thread_work_partial(hl_sites, me, nthreads, mywork, myoff);
for(int i = 0; i < mywork; ++i) {
int x[4];
int tmp = i + myoff;
x[0] = tmp % hl[0] + low[0]; tmp /= hl[0];
x[1] = tmp % hl[1] + low[1]; tmp /= hl[1];
x[2] = tmp % hl[2] + low[2]; tmp /= hl[2];
x[3] = tmp % hl[3] + low[3];
int y[4] = {x[0], x[1], x[2], x[3]};
y[mu] = backwards ? x[mu] + 1 : x[mu] - 1;
int off_x = idx_4d(x, lcl);
int off_y = idx_4d(y, lcl);
if(backwards) {
Link tmp;
tmp.Dagger(gauge[4 * off_x + mu]);
out[off_y] = tmp * in[off_x];
} else {
out[off_y] = gauge[4 * off_y + mu] * in[off_x];
}
}
}
template<typename Link, typename Site>
void pt(int N, Site *out[], Link *gauge[], Site *in[], const int dir[])
{
// 1. compute comm space requirement and pointer shift
std::vector<int> comm_size;
std::vector<int> comm_off;
int total[NUM_DIR];
compute_comm(comm_size, comm_off, total, N, dir);
// 2. allocate comm space
Site *sndbuf[NUM_DIR];
Site *rcvbuf[NUM_DIR];
for(int i = 0; i < NUM_DIR; ++i) {
if(total[i] == 0) { // no communication in this direction
sndbuf[i] = rcvbuf[i] = NULL;
} else {
sndbuf[i] = new Site[total[i]];
rcvbuf[i] = new Site[total[i]];
}
}
// 3. compute/collect surface sites for communication
#pragma omp parallel
{
for(int d = 0; d < N; ++d) {
collect(sndbuf[dir[d]] + comm_off[d], gauge[d], in[d], dir[d], true);
}
}
// 4. single threaded comm
// If you fix the multi thread MPI problem on BG/Q you can do multithreaded comm here.
for(int mu = 0; mu < 4; ++mu) {
// forwards
if(total[2 * mu]) {
getPlusData((Float *)rcvbuf[2 * mu], (Float *)sndbuf[2 * mu],
sizeof(Site) * total[2 * mu] / sizeof(Float), mu);
}
// backwards
if(total[2 * mu + 1]) {
getMinusData((Float *)rcvbuf[2 * mu + 1], (Float *)sndbuf[2 * mu + 1],
sizeof(Site) * total[2 * mu + 1] / sizeof(Float), mu);
}
}
#pragma omp parallel
{
int nthreads = omp_get_num_threads();
// int me = omp_get_thread_num();
// 5. compute internal parallel transport
for(int d = 0; d < N; ++d) {
compute_internal(out[d], gauge[d], in[d], dir[d], nthreads);
}
//#pragma omp barrier
// 6. compute/collect surface sites
for(int d = 0; d < N; ++d) {
collect(rcvbuf[dir[d]] + comm_off[d], gauge[d], out[d], dir[d], false);
}
}
for(int i = 0; i < NUM_DIR; ++i) {
delete[] sndbuf[i];
delete[] rcvbuf[i];
}
}
}
CPS_END_NAMESPACE
#endif
|
transpose.h | // This code is part of the Problem Based Benchmark Suite (PBBS)
// Copyright (c) 2011-2016 Guy Blelloch and the PBBS team
//
// 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 "get_time.h"
#include "sequence_ops.h"
#include "utilities.h"
namespace pbbs {
constexpr const size_t TRANS_THRESHHOLD = PAR_GRANULARITY / 4;
inline size_t split(size_t n) {
return n / 2;
// return ((((size_t) 1) << log2_up(n) != n) ? n/2 : (7*(n+1))/16);
}
template <class E> struct transpose {
E *A, *B;
transpose(E *AA, E *BB) : A(AA), B(BB) {}
void transR(size_t rStart, size_t rCount, size_t rLength, size_t cStart,
size_t cCount, size_t cLength) {
if (cCount * rCount < TRANS_THRESHHOLD) {
for (size_t i = rStart; i < rStart + rCount; i++)
for (size_t j = cStart; j < cStart + cCount; j++)
B[j * cLength + i] = A[i * rLength + j];
} else if (cCount > rCount) {
size_t l1 = split(cCount);
size_t l2 = cCount - l1;
auto left = [&]() {
transR(rStart, rCount, rLength, cStart, l1, cLength);
};
auto right = [&]() {
transR(rStart, rCount, rLength, cStart + l1, l2, cLength);
};
par_do(left, right);
} else {
size_t l1 = split(cCount);
size_t l2 = rCount - l1;
auto left = [&]() {
transR(rStart, l1, rLength, cStart, cCount, cLength);
};
auto right = [&]() {
transR(rStart + l1, l2, rLength, cStart, cCount, cLength);
};
par_do(left, right);
}
}
void trans(size_t rCount, size_t cCount) {
#if defined(OPENMP)
#pragma omp parallel
#pragma omp single
#endif
transR(0, rCount, cCount, 0, cCount, rCount);
}
};
template <class E, class int_t> struct blockTrans {
E *A, *B;
int_t *OA, *OB;
blockTrans(E *AA, E *BB, int_t *OOA, int_t *OOB)
: A(AA), B(BB), OA(OOA), OB(OOB) {}
void transR(size_t rStart, size_t rCount, size_t rLength, size_t cStart,
size_t cCount, size_t cLength) {
if (cCount * rCount < TRANS_THRESHHOLD * 16) {
parallel_for(rStart, rStart + rCount, [&](size_t i) {
for (size_t j = cStart; j < cStart + cCount; j++) {
size_t sa = OA[i * rLength + j];
size_t sb = OB[j * cLength + i];
size_t l = OA[i * rLength + j + 1] - sa;
for (size_t k = 0; k < l; k++)
move_uninitialized(B[k + sb], A[k + sa]);
}
});
} else if (cCount > rCount) {
size_t l1 = split(cCount);
size_t l2 = cCount - l1;
auto left = [&]() {
transR(rStart, rCount, rLength, cStart, l1, cLength);
};
auto right = [&]() {
transR(rStart, rCount, rLength, cStart + l1, l2, cLength);
};
par_do(left, right);
} else {
size_t l1 = split(cCount);
size_t l2 = rCount - l1;
auto left = [&]() {
transR(rStart, l1, rLength, cStart, cCount, cLength);
};
auto right = [&]() {
transR(rStart + l1, l2, rLength, cStart, cCount, cLength);
};
par_do(left, right);
}
}
void trans(size_t rCount, size_t cCount) {
#if defined(OPENMP)
#pragma omp parallel
#pragma omp single
#endif
transR(0, rCount, cCount, 0, cCount, rCount);
}
};
// Moves values from blocks to buckets
// From is sorted by key within each block, in block major
// counts is the # of keys in each bucket for each block, in block major
// From and To are of lenght n
// counts is of length num_blocks * num_buckets
// Data is memcpy'd into To avoiding initializers and overloaded =
template <typename E, typename s_size_t>
size_t *transpose_buckets(E *From, E *To, s_size_t *counts, size_t n,
size_t block_size, size_t num_blocks,
size_t num_buckets) {
timer t("transpose", false);
size_t m = num_buckets * num_blocks;
sequence<s_size_t> dest_offsets; //(m);
auto add = addm<s_size_t>();
// std::cout << "ss 8" << std::endl;
// for smaller input do non-cache oblivious version
if (n < (1 << 22) || num_buckets <= 512 || num_blocks <= 512) {
size_t block_bits = log2_up(num_blocks);
size_t block_mask = num_blocks - 1;
if ((size_t)1 << block_bits != num_blocks) {
std::cout << "in transpose_buckets: num_blocks must be a power or 2"
<< std::endl;
abort();
}
// determine the destination offsets
auto get = [&](size_t i) {
return counts[(i >> block_bits) + num_buckets * (i & block_mask)];
};
// slow down?
dest_offsets = sequence<s_size_t>(m, get);
size_t sum = scan_inplace(dest_offsets.slice(), add);
if (sum != n)
abort();
t.next("seq and scan");
// send each key to correct location within its bucket
auto f = [&](size_t i) {
size_t s_offset = i * block_size;
for (size_t j = 0; j < num_buckets; j++) {
size_t d_offset = dest_offsets[i + num_blocks * j];
size_t len = counts[i * num_buckets + j];
for (size_t k = 0; k < len; k++)
move_uninitialized(To[d_offset++], From[s_offset++]);
}
};
parallel_for(0, num_blocks, f, 1);
t.next("trans");
free_array(counts);
} else { // for larger input do cache efficient transpose
sequence<s_size_t> source_offsets(counts, m);
dest_offsets = sequence<s_size_t>(m);
size_t total;
transpose<s_size_t>(counts, dest_offsets.begin())
.trans(num_blocks, num_buckets);
t.next("trans 1");
// std::cout << "ss 9" << std::endl;
// do both scans inplace
total = scan_inplace(dest_offsets.slice(), add);
if (total != n)
abort();
total = scan_inplace(source_offsets.slice(), add);
if (total != n)
abort();
source_offsets[m] = n;
t.next("scans");
blockTrans<E, s_size_t>(From, To, source_offsets.begin(),
dest_offsets.begin())
.trans(num_blocks, num_buckets);
t.next("trans 2");
// std::cout << "ss 10" << std::endl;
}
size_t *bucket_offsets = new_array_no_init<size_t>(num_buckets + 1);
for (s_size_t i = 0; i < num_buckets; i++)
bucket_offsets[i] = dest_offsets[i * num_blocks];
// last element is the total size n
bucket_offsets[num_buckets] = n;
return bucket_offsets;
}
} // namespace pbbs
|
lsh_index.h | /***********************************************************************
* Software License Agreement (BSD License)
*
* Copyright 2008-2009 Marius Muja (mariusm@cs.ubc.ca). All rights reserved.
* Copyright 2008-2009 David G. Lowe (lowe@cs.ubc.ca). All rights reserved.
*
* THE BSD LICENSE
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*************************************************************************/
/***********************************************************************
* Author: Vincent Rabaud
*************************************************************************/
#ifndef RTABMAP_FLANN_LSH_INDEX_H_
#define RTABMAP_FLANN_LSH_INDEX_H_
#include <algorithm>
#include <cassert>
#include <cstring>
#include <map>
#include <vector>
#include "rtflann/general.h"
#include "rtflann/algorithms/nn_index.h"
#include "rtflann/util/matrix.h"
#include "rtflann/util/result_set.h"
#include "rtflann/util/heap.h"
#include "rtflann/util/lsh_table.h"
#include "rtflann/util/allocator.h"
#include "rtflann/util/random.h"
#include "rtflann/util/saving.h"
namespace rtflann
{
struct LshIndexParams : public IndexParams
{
LshIndexParams(unsigned int table_number = 12, unsigned int key_size = 20, unsigned int multi_probe_level = 2)
{
(* this)["algorithm"] = FLANN_INDEX_LSH;
// The number of hash tables to use
(*this)["table_number"] = table_number;
// The length of the key in the hash tables
(*this)["key_size"] = key_size;
// Number of levels to use in multi-probe (0 for standard LSH)
(*this)["multi_probe_level"] = multi_probe_level;
}
};
/**
* Randomized kd-tree index
*
* Contains the k-d trees and other information for indexing a set of points
* for nearest-neighbor matching.
*/
template<typename Distance>
class LshIndex : public NNIndex<Distance>
{
public:
typedef typename Distance::ElementType ElementType;
typedef typename Distance::ResultType DistanceType;
typedef NNIndex<Distance> BaseClass;
/** Constructor
* @param params parameters passed to the LSH algorithm
* @param d the distance used
*/
LshIndex(const IndexParams& params = LshIndexParams(), Distance d = Distance()) :
BaseClass(params, d)
{
table_number_ = get_param<unsigned int>(index_params_,"table_number",12);
key_size_ = get_param<unsigned int>(index_params_,"key_size",20);
multi_probe_level_ = get_param<unsigned int>(index_params_,"multi_probe_level",2);
fill_xor_mask(0, key_size_, multi_probe_level_, xor_masks_);
}
/** Constructor
* @param input_data dataset with the input features
* @param params parameters passed to the LSH algorithm
* @param d the distance used
*/
LshIndex(const Matrix<ElementType>& input_data, const IndexParams& params = LshIndexParams(), Distance d = Distance()) :
BaseClass(params, d)
{
table_number_ = get_param<unsigned int>(index_params_,"table_number",12);
key_size_ = get_param<unsigned int>(index_params_,"key_size",20);
multi_probe_level_ = get_param<unsigned int>(index_params_,"multi_probe_level",2);
fill_xor_mask(0, key_size_, multi_probe_level_, xor_masks_);
setDataset(input_data);
}
LshIndex(const LshIndex& other) : BaseClass(other),
tables_(other.tables_),
table_number_(other.table_number_),
key_size_(other.key_size_),
multi_probe_level_(other.multi_probe_level_),
xor_masks_(other.xor_masks_)
{
}
LshIndex& operator=(LshIndex other)
{
this->swap(other);
return *this;
}
virtual ~LshIndex()
{
freeIndex();
}
BaseClass* clone() const
{
return new LshIndex(*this);
}
using BaseClass::buildIndex;
void addPoints(const Matrix<ElementType>& points, float rebuild_threshold = 2)
{
assert(points.cols==veclen_);
size_t old_size = size_;
extendDataset(points);
if (rebuild_threshold>1 && size_at_build_*rebuild_threshold<size_) {
buildIndex();
}
else {
for (unsigned int i = 0; i < table_number_; ++i) {
lsh::LshTable<ElementType>& table = tables_[i];
for (size_t i=old_size;i<size_;++i) {
table.add(i, points_[i]);
}
}
}
}
flann_algorithm_t getType() const
{
return FLANN_INDEX_LSH;
}
template<typename Archive>
void serialize(Archive& ar)
{
ar.setObject(this);
ar & *static_cast<NNIndex<Distance>*>(this);
ar & table_number_;
ar & key_size_;
ar & multi_probe_level_;
ar & xor_masks_;
ar & tables_;
if (Archive::is_loading::value) {
index_params_["algorithm"] = getType();
index_params_["table_number"] = table_number_;
index_params_["key_size"] = key_size_;
index_params_["multi_probe_level"] = multi_probe_level_;
}
}
void saveIndex(FILE* stream)
{
serialization::SaveArchive sa(stream);
sa & *this;
}
void loadIndex(FILE* stream)
{
serialization::LoadArchive la(stream);
la & *this;
}
/**
* Computes the index memory usage
* Returns: memory used by the index
*/
int usedMemory() const
{
return size_ * sizeof(int);
}
/**
* \brief Perform k-nearest neighbor search
* \param[in] queries The query points for which to find the nearest neighbors
* \param[out] indices The indices of the nearest neighbors found
* \param[out] dists Distances to the nearest neighbors found
* \param[in] knn Number of nearest neighbors to return
* \param[in] params Search parameters
*/
int knnSearch(const Matrix<ElementType>& queries,
Matrix<size_t>& indices,
Matrix<DistanceType>& dists,
size_t knn,
const SearchParams& params) const
{
assert(queries.cols == veclen_);
assert(indices.rows >= queries.rows);
assert(dists.rows >= queries.rows);
assert(indices.cols >= knn);
assert(dists.cols >= knn);
int count = 0;
if (params.use_heap==FLANN_True) {
#pragma omp parallel num_threads(params.cores)
{
KNNUniqueResultSet<DistanceType> resultSet(knn);
#pragma omp for schedule(static) reduction(+:count)
for (int i = 0; i < (int)queries.rows; i++) {
resultSet.clear();
findNeighbors(resultSet, queries[i], params);
size_t n = std::min(resultSet.size(), knn);
resultSet.copy(indices[i], dists[i], n, params.sorted);
indices_to_ids(indices[i], indices[i], n);
count += n;
}
}
}
else {
#pragma omp parallel num_threads(params.cores)
{
KNNResultSet<DistanceType> resultSet(knn);
#pragma omp for schedule(static) reduction(+:count)
for (int i = 0; i < (int)queries.rows; i++) {
resultSet.clear();
findNeighbors(resultSet, queries[i], params);
size_t n = std::min(resultSet.size(), knn);
resultSet.copy(indices[i], dists[i], n, params.sorted);
indices_to_ids(indices[i], indices[i], n);
count += n;
}
}
}
return count;
}
/**
* \brief Perform k-nearest neighbor search
* \param[in] queries The query points for which to find the nearest neighbors
* \param[out] indices The indices of the nearest neighbors found
* \param[out] dists Distances to the nearest neighbors found
* \param[in] knn Number of nearest neighbors to return
* \param[in] params Search parameters
*/
int knnSearch(const Matrix<ElementType>& queries,
std::vector< std::vector<size_t> >& indices,
std::vector<std::vector<DistanceType> >& dists,
size_t knn,
const SearchParams& params) const
{
assert(queries.cols == veclen_);
if (indices.size() < queries.rows ) indices.resize(queries.rows);
if (dists.size() < queries.rows ) dists.resize(queries.rows);
int count = 0;
if (params.use_heap==FLANN_True) {
#pragma omp parallel num_threads(params.cores)
{
KNNUniqueResultSet<DistanceType> resultSet(knn);
#pragma omp for schedule(static) reduction(+:count)
for (int i = 0; i < (int)queries.rows; i++) {
resultSet.clear();
findNeighbors(resultSet, queries[i], params);
size_t n = std::min(resultSet.size(), knn);
indices[i].resize(n);
dists[i].resize(n);
if (n > 0) {
resultSet.copy(&indices[i][0], &dists[i][0], n, params.sorted);
indices_to_ids(&indices[i][0], &indices[i][0], n);
}
count += n;
}
}
}
else {
#pragma omp parallel num_threads(params.cores)
{
KNNResultSet<DistanceType> resultSet(knn);
#pragma omp for schedule(static) reduction(+:count)
for (int i = 0; i < (int)queries.rows; i++) {
resultSet.clear();
findNeighbors(resultSet, queries[i], params);
size_t n = std::min(resultSet.size(), knn);
indices[i].resize(n);
dists[i].resize(n);
if (n > 0) {
resultSet.copy(&indices[i][0], &dists[i][0], n, params.sorted);
indices_to_ids(&indices[i][0], &indices[i][0], n);
}
count += n;
}
}
}
return count;
}
/**
* Find set of nearest neighbors to vec. Their indices are stored inside
* the result object.
*
* Params:
* result = the result object in which the indices of the nearest-neighbors are stored
* vec = the vector for which to search the nearest neighbors
* maxCheck = the maximum number of restarts (in a best-bin-first manner)
*/
void findNeighbors(ResultSet<DistanceType>& result, const ElementType* vec, const SearchParams& /*searchParams*/) const
{
getNeighbors(vec, result);
}
protected:
/**
* Builds the index
*/
void buildIndexImpl()
{
tables_.resize(table_number_);
std::vector<std::pair<size_t,ElementType*> > features;
features.reserve(points_.size());
for (size_t i=0;i<points_.size();++i) {
features.push_back(std::make_pair(i, points_[i]));
}
for (unsigned int i = 0; i < table_number_; ++i) {
lsh::LshTable<ElementType>& table = tables_[i];
table = lsh::LshTable<ElementType>(veclen_, key_size_);
// Add the features to the table
table.add(features);
}
}
void freeIndex()
{
/* nothing to do here */
}
private:
/** Defines the comparator on score and index
*/
typedef std::pair<float, unsigned int> ScoreIndexPair;
struct SortScoreIndexPairOnSecond
{
bool operator()(const ScoreIndexPair& left, const ScoreIndexPair& right) const
{
return left.second < right.second;
}
};
/** Fills the different xor masks to use when getting the neighbors in multi-probe LSH
* @param key the key we build neighbors from
* @param lowest_index the lowest index of the bit set
* @param level the multi-probe level we are at
* @param xor_masks all the xor mask
*/
void fill_xor_mask(lsh::BucketKey key, int lowest_index, unsigned int level,
std::vector<lsh::BucketKey>& xor_masks)
{
xor_masks.push_back(key);
if (level == 0) return;
for (int index = lowest_index - 1; index >= 0; --index) {
// Create a new key
lsh::BucketKey new_key = key | (lsh::BucketKey(1) << index);
fill_xor_mask(new_key, index, level - 1, xor_masks);
}
}
/** Performs the approximate nearest-neighbor search.
* @param vec the feature to analyze
* @param do_radius flag indicating if we check the radius too
* @param radius the radius if it is a radius search
* @param do_k flag indicating if we limit the number of nn
* @param k_nn the number of nearest neighbors
* @param checked_average used for debugging
*/
void getNeighbors(const ElementType* vec, bool do_radius, float radius, bool do_k, unsigned int k_nn,
float& checked_average)
{
static std::vector<ScoreIndexPair> score_index_heap;
if (do_k) {
unsigned int worst_score = std::numeric_limits<unsigned int>::max();
typename std::vector<lsh::LshTable<ElementType> >::const_iterator table = tables_.begin();
typename std::vector<lsh::LshTable<ElementType> >::const_iterator table_end = tables_.end();
for (; table != table_end; ++table) {
size_t key = table->getKey(vec);
std::vector<lsh::BucketKey>::const_iterator xor_mask = xor_masks_.begin();
std::vector<lsh::BucketKey>::const_iterator xor_mask_end = xor_masks_.end();
for (; xor_mask != xor_mask_end; ++xor_mask) {
size_t sub_key = key ^ (*xor_mask);
const lsh::Bucket* bucket = table->getBucketFromKey(sub_key);
if (bucket == 0) continue;
// Go over each descriptor index
std::vector<lsh::FeatureIndex>::const_iterator training_index = bucket->begin();
std::vector<lsh::FeatureIndex>::const_iterator last_training_index = bucket->end();
DistanceType hamming_distance;
// Process the rest of the candidates
for (; training_index < last_training_index; ++training_index) {
if (removed_ && removed_points_.test(*training_index)) continue;
hamming_distance = distance_(vec, points_[*training_index].point, veclen_);
if (hamming_distance < worst_score) {
// Insert the new element
score_index_heap.push_back(ScoreIndexPair(hamming_distance, training_index));
std::push_heap(score_index_heap.begin(), score_index_heap.end());
if (score_index_heap.size() > (unsigned int)k_nn) {
// Remove the highest distance value as we have too many elements
std::pop_heap(score_index_heap.begin(), score_index_heap.end());
score_index_heap.pop_back();
// Keep track of the worst score
worst_score = score_index_heap.front().first;
}
}
}
}
}
}
else {
typename std::vector<lsh::LshTable<ElementType> >::const_iterator table = tables_.begin();
typename std::vector<lsh::LshTable<ElementType> >::const_iterator table_end = tables_.end();
for (; table != table_end; ++table) {
size_t key = table->getKey(vec);
std::vector<lsh::BucketKey>::const_iterator xor_mask = xor_masks_.begin();
std::vector<lsh::BucketKey>::const_iterator xor_mask_end = xor_masks_.end();
for (; xor_mask != xor_mask_end; ++xor_mask) {
size_t sub_key = key ^ (*xor_mask);
const lsh::Bucket* bucket = table->getBucketFromKey(sub_key);
if (bucket == 0) continue;
// Go over each descriptor index
std::vector<lsh::FeatureIndex>::const_iterator training_index = bucket->begin();
std::vector<lsh::FeatureIndex>::const_iterator last_training_index = bucket->end();
DistanceType hamming_distance;
// Process the rest of the candidates
for (; training_index < last_training_index; ++training_index) {
if (removed_ && removed_points_.test(*training_index)) continue;
// Compute the Hamming distance
hamming_distance = distance_(vec, points_[*training_index].point, veclen_);
if (hamming_distance < radius) score_index_heap.push_back(ScoreIndexPair(hamming_distance, training_index));
}
}
}
}
}
/** Performs the approximate nearest-neighbor search.
* This is a slower version than the above as it uses the ResultSet
* @param vec the feature to analyze
*/
void getNeighbors(const ElementType* vec, ResultSet<DistanceType>& result) const
{
typename std::vector<lsh::LshTable<ElementType> >::const_iterator table = tables_.begin();
typename std::vector<lsh::LshTable<ElementType> >::const_iterator table_end = tables_.end();
for (; table != table_end; ++table) {
size_t key = table->getKey(vec);
std::vector<lsh::BucketKey>::const_iterator xor_mask = xor_masks_.begin();
std::vector<lsh::BucketKey>::const_iterator xor_mask_end = xor_masks_.end();
for (; xor_mask != xor_mask_end; ++xor_mask) {
size_t sub_key = key ^ (*xor_mask);
const lsh::Bucket* bucket = table->getBucketFromKey(sub_key);
if (bucket == 0) continue;
// Go over each descriptor index
std::vector<lsh::FeatureIndex>::const_iterator training_index = bucket->begin();
std::vector<lsh::FeatureIndex>::const_iterator last_training_index = bucket->end();
DistanceType hamming_distance;
// Process the rest of the candidates
for (; training_index < last_training_index; ++training_index) {
if (removed_ && removed_points_.test(*training_index)) continue;
// Compute the Hamming distance
hamming_distance = distance_(vec, points_[*training_index], veclen_);
result.addPoint(hamming_distance, *training_index);
}
}
}
}
void swap(LshIndex& other)
{
BaseClass::swap(other);
std::swap(tables_, other.tables_);
std::swap(size_at_build_, other.size_at_build_);
std::swap(table_number_, other.table_number_);
std::swap(key_size_, other.key_size_);
std::swap(multi_probe_level_, other.multi_probe_level_);
std::swap(xor_masks_, other.xor_masks_);
}
/** The different hash tables */
std::vector<lsh::LshTable<ElementType> > tables_;
/** table number */
unsigned int table_number_;
/** key size */
unsigned int key_size_;
/** How far should we look for neighbors in multi-probe LSH */
unsigned int multi_probe_level_;
/** The XOR masks to apply to a key to get the neighboring buckets */
std::vector<lsh::BucketKey> xor_masks_;
USING_BASECLASS_SYMBOLS
};
}
#endif //FLANN_LSH_INDEX_H_
|
GB_binop__bor_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 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__bor_uint8)
// A.*B function (eWiseMult): GB (_AemultB_08__bor_uint8)
// A.*B function (eWiseMult): GB (_AemultB_02__bor_uint8)
// A.*B function (eWiseMult): GB (_AemultB_04__bor_uint8)
// A.*B function (eWiseMult): GB (_AemultB_bitmap__bor_uint8)
// A*D function (colscale): GB (_AxD__bor_uint8)
// D*A function (rowscale): GB (_DxB__bor_uint8)
// C+=B function (dense accum): GB (_Cdense_accumB__bor_uint8)
// C+=b function (dense accum): GB (_Cdense_accumb__bor_uint8)
// C+=A+B function (dense ewise3): GB ((none))
// C=A+B function (dense ewise3): GB (_Cdense_ewise3_noaccum__bor_uint8)
// C=scalar+B GB (_bind1st__bor_uint8)
// C=scalar+B' GB (_bind1st_tran__bor_uint8)
// C=A+scalar GB (_bind2nd__bor_uint8)
// C=A'+scalar GB (_bind2nd_tran__bor_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,A_iso) \
uint8_t aij = GBX (Ax, pA, A_iso)
// bij = Bx [pB]
#define GB_GETB(bij,Bx,pB,B_iso) \
uint8_t bij = GBX (Bx, pB, B_iso)
// 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,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_BOR || GxB_NO_UINT8 || GxB_NO_BOR_UINT8)
//------------------------------------------------------------------------------
// C += A+B, all 3 matrices dense
//------------------------------------------------------------------------------
#if 0
// The op must be MIN, MAX, PLUS, MINUS, RMINUS, TIMES, DIV, or RDIV.
void GB ((none))
(
GrB_Matrix C,
const GrB_Matrix A,
const GrB_Matrix B,
const int nthreads
)
{
#include "GB_dense_ewise3_accum_template.c"
}
#endif
//------------------------------------------------------------------------------
// C = A+B, all 3 matrices dense
//------------------------------------------------------------------------------
GrB_Info GB (_Cdense_ewise3_noaccum__bor_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__bor_uint8)
(
GrB_Matrix C,
const GrB_Matrix B,
const int64_t *B_ek_slicing, const int B_ntasks, const int B_nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
{
#include "GB_dense_subassign_23_template.c"
}
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// C += b, accumulate a scalar into a dense matrix
//------------------------------------------------------------------------------
GrB_Info GB (_Cdense_accumb__bor_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__bor_uint8)
(
GrB_Matrix C,
const GrB_Matrix A, bool A_is_pattern,
const GrB_Matrix D, bool D_is_pattern,
const int64_t *A_ek_slicing, const int A_ntasks, const int A_nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
uint8_t *restrict Cx = (uint8_t *) C->x ;
#include "GB_AxB_colscale_template.c"
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// C = D*B, row scale with diagonal D matrix
//------------------------------------------------------------------------------
GrB_Info GB (_DxB__bor_uint8)
(
GrB_Matrix C,
const GrB_Matrix D, bool D_is_pattern,
const GrB_Matrix B, bool B_is_pattern,
int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
uint8_t *restrict Cx = (uint8_t *) C->x ;
#include "GB_AxB_rowscale_template.c"
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// eWiseAdd: C=A+B, C<M>=A+B, C<!M>=A+B
//------------------------------------------------------------------------------
GrB_Info GB (_AaddB__bor_uint8)
(
GrB_Matrix C,
const int C_sparsity,
const GrB_Matrix M,
const bool Mask_struct,
const bool Mask_comp,
const GrB_Matrix A,
const GrB_Matrix B,
const bool Ch_is_Mh,
const int64_t *restrict C_to_M,
const int64_t *restrict C_to_A,
const int64_t *restrict C_to_B,
const GB_task_struct *restrict TaskList,
const int C_ntasks,
const int C_nthreads,
GB_Context Context
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
GB_WERK_DECLARE (M_ek_slicing, int64_t) ;
GB_WERK_DECLARE (A_ek_slicing, int64_t) ;
GB_WERK_DECLARE (B_ek_slicing, int64_t) ;
#include "GB_add_template.c"
GB_FREE_WORK ;
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// eWiseMult: C=A.*B, C<M>=A.*B, or C<M!>=A.*B where C is sparse/hyper
//------------------------------------------------------------------------------
GrB_Info GB (_AemultB_08__bor_uint8)
(
GrB_Matrix C,
const int C_sparsity,
const int ewise_method,
const GrB_Matrix M,
const bool Mask_struct,
const bool Mask_comp,
const GrB_Matrix A,
const GrB_Matrix B,
const int64_t *restrict C_to_M,
const int64_t *restrict C_to_A,
const int64_t *restrict C_to_B,
const GB_task_struct *restrict TaskList,
const int C_ntasks,
const int C_nthreads,
GB_Context Context
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
#include "GB_emult_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__bor_uint8)
(
GrB_Matrix C,
const GrB_Matrix M,
const bool Mask_struct,
const bool Mask_comp,
const GrB_Matrix A,
const GrB_Matrix B,
const bool flipxy,
const int64_t *restrict Cp_kfirst,
const int64_t *A_ek_slicing, const int A_ntasks, const int A_nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
#if GB_BINOP_FLIP
// The operator is not commutative, and does not have a flipped
// variant. For example z=atan2(y,x).
if (flipxy)
{
// use fmult(y,x)
#undef GB_FLIPPED
#define GB_FLIPPED 1
#include "GB_emult_02_template.c"
}
else
{
// use fmult(x,y)
#undef GB_FLIPPED
#define GB_FLIPPED 0
#include "GB_emult_02_template.c"
}
#else
// No need to handle the flip: the operator is either commutative, or
// has been handled by changing z=div(y,x) to z=rdiv(x,y) for example.
#undef GB_FLIPPED
#define GB_FLIPPED 0
#include "GB_emult_02_template.c"
#endif
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// eWiseMult: C<M> = A.*B, M sparse/hyper, A and B bitmap/full
//------------------------------------------------------------------------------
GrB_Info GB (_AemultB_04__bor_uint8)
(
GrB_Matrix C,
const GrB_Matrix M,
const bool Mask_struct,
const GrB_Matrix A,
const GrB_Matrix B,
const int64_t *restrict Cp_kfirst,
const int64_t *M_ek_slicing, const int M_ntasks, const int M_nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
#include "GB_emult_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__bor_uint8)
(
GrB_Matrix C,
const int ewise_method,
const GrB_Matrix M,
const bool Mask_struct,
const bool Mask_comp,
const GrB_Matrix A,
const GrB_Matrix B,
const int64_t *M_ek_slicing, const int M_ntasks, const int M_nthreads,
const int C_nthreads,
GB_Context Context
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
#include "GB_bitmap_emult_template.c"
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// Cx = op (x,Bx): apply a binary operator to a matrix with scalar bind1st
//------------------------------------------------------------------------------
GrB_Info GB (_bind1st__bor_uint8)
(
GB_void *Cx_output, // Cx and Bx may be aliased
const GB_void *x_input,
const GB_void *Bx_input,
const int8_t *restrict Bb,
int64_t bnz,
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 < bnz ; p++)
{
if (!GBB (Bb, p)) continue ;
uint8_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__bor_uint8)
(
GB_void *Cx_output, // Cx and Ax may be aliased
const GB_void *Ax_input,
const GB_void *y_input,
const int8_t *restrict Ab,
int64_t anz,
int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
int64_t p ;
uint8_t *Cx = (uint8_t *) Cx_output ;
uint8_t *Ax = (uint8_t *) Ax_input ;
uint8_t y = (*((uint8_t *) y_input)) ;
#pragma omp parallel for num_threads(nthreads) schedule(static)
for (p = 0 ; p < anz ; p++)
{
if (!GBB (Ab, p)) continue ;
uint8_t aij = 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) \
{ \
uint8_t aij = GBX (Ax, pA, false) ; \
Cx [pC] = (x) | (aij) ; \
}
GrB_Info GB (_bind1st_tran__bor_uint8)
(
GrB_Matrix C,
const GB_void *x_input,
const GrB_Matrix A,
int64_t *restrict *Workspaces,
const int64_t *restrict A_slice,
int nworkspaces,
int nthreads
)
{
// GB_unop_transpose.c uses GB_ATYPE, but A is
// the 2nd input to binary operator z=f(x,y).
#undef GB_ATYPE
#define GB_ATYPE \
uint8_t
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
uint8_t x = (*((const uint8_t *) x_input)) ;
#include "GB_unop_transpose.c"
return (GrB_SUCCESS) ;
#endif
#undef GB_ATYPE
#define GB_ATYPE \
uint8_t
}
//------------------------------------------------------------------------------
// C = op (A', y): transpose and apply a binary operator
//------------------------------------------------------------------------------
// cij = op (aij, y), no typecasting (in spite of the macro name)
#undef GB_CAST_OP
#define GB_CAST_OP(pC,pA) \
{ \
uint8_t aij = GBX (Ax, pA, false) ; \
Cx [pC] = (aij) | (y) ; \
}
GrB_Info GB (_bind2nd_tran__bor_uint8)
(
GrB_Matrix C,
const GrB_Matrix A,
const GB_void *y_input,
int64_t *restrict *Workspaces,
const int64_t *restrict A_slice,
int nworkspaces,
int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
uint8_t y = (*((const uint8_t *) y_input)) ;
#include "GB_unop_transpose.c"
return (GrB_SUCCESS) ;
#endif
}
#endif
|
HeatStencil.c | #include <errno.h>
#include <math.h>
#include <omp.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define RESOLUTION_WIDTH 50
#define RESOLUTION_HEIGHT 50
#define HEAT_SOURCE_TEMP 333.00f // 273 + 60 K
#define DELTA_TIME 0.02f
#define PERROR fprintf(stderr, "%s:%d: error: %s\n", __FILE__, __LINE__, strerror(errno))
#define PERROR_GOTO(label) \
do { \
PERROR; \
goto label; \
} while (0)
// -- vector utilities --
#define IND(y, x) ((y) * (N) + (x))
#define SWAP(x, y) \
do { \
__typeof__(x) _x = x; \
__typeof__(y) _y = y; \
x = _y; \
y = _x; \
} while (0)
#define FLOAT_EQUALS(x, y) fabs(x - y) < 0.01
void printTemperature(double *m, int N, int M);
// -- simulation code ---
int main(int argc, char **argv) {
// 'parsing' optional input parameter = problem size
int N = 200;
if (argc > 1) {
N = atoi(argv[1]);
}
int T = N * 10;
printf("Computing heat-distribution for room size %dX%d for T=%d timesteps\n", N, N, T);
// ---------- setup ----------
// create a buffer for storing temperature fields
double *A = malloc(sizeof(double) * N * N);
if (!A)
PERROR_GOTO(error_a);
// create a second buffer for the computation
double *B = malloc(sizeof(double) * N * N);
if (!B)
PERROR_GOTO(error_b);
// set up initial conditions in A
#pragma omp parallel for collapse(2)
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) {
A[IND(i, j)] = 273; // temperature is 0° C everywhere (273 K)
B[IND(i, j)] = 273;
}
}
// and there is a heat source
int source_x = N / 4;
int source_y = N / 4;
A[IND(source_x, source_y)] = HEAT_SOURCE_TEMP;
B[IND(source_x, source_y)] = HEAT_SOURCE_TEMP;
printf("Initial:");
printTemperature(A, N, N);
printf("\n");
// ---------- compute ----------
// for each time step ..
for (int t = 0; t < T; t++) {
// Heat propagation, will use own heat on corner (1 to N-1)
#pragma omp parallel for collapse(2)
for (int i = 1; i < N - 1; i++) {
for (int j = 1; j < N - 1; j++) {
double l, r, u, d;
// don't change the value if heat source
if (IND(source_x, source_y) != IND(i, j)) {
l = A[IND(i - 1, j)];
r = A[IND(i + 1, j)];
u = A[IND(i, j - 1)];
d = A[IND(i, j + 1)];
B[IND(i, j)] = ((l + r + u + d) / 4 - A[IND(i, j)]) * DELTA_TIME + A[IND(i, j)];
}
}
}
// todo make sure the heat source stays the same
if (!FLOAT_EQUALS(B[IND(source_x, source_y)], HEAT_SOURCE_TEMP)) {
fprintf(stderr, "Error: Heat source changed! Source heat = %.2fF\n", B[IND(source_x, source_y)]);
errno = ECANCELED;
PERROR_GOTO(error_b);
}
SWAP(A, B);
// every 1000 steps show intermediate step
if (!(t % 1000)) {
printf("Step t=%d\n", t);
printTemperature(A, N, N);
printf("\n");
}
}
// ---------- check ----------
printf("Final:");
printTemperature(A, N, N);
printf("\n");
// simple verification if nowhere the heat is more then the heat source
int success = 1;
for (long long i = 0; i < N; i++) {
for (long long j = 0; j < N; j++) {
double temp = A[IND(i, j)];
if (273 <= temp && temp <= 273 + 60)
continue;
success = 0;
break;
}
}
printf("Verification: %s\n", (success) ? "OK" : "FAILED");
// ---------- cleanup ----------
error_b:
free(B);
error_a:
free(A);
return (success) ? EXIT_SUCCESS : EXIT_FAILURE;
}
void printTemperature(double *m, int N, int M) {
const char *colors = " .-:=+*^X#%@";
const int numColors = 12;
// boundaries for temperature (for simplicity hard-coded)
const double max = 273 + 30;
const double min = 273 + 0;
// set the 'render' resolution
int W = RESOLUTION_WIDTH;
int H = RESOLUTION_HEIGHT;
// step size in each dimension
int sW = N / W;
int sH = M / H;
// upper wall
printf("\t");
for (int u = 0; u < W + 2; u++) {
printf("X");
}
printf("\n");
// room
for (int i = 0; i < H; i++) {
// left wall
printf("\tX");
// actual room
for (int j = 0; j < W; j++) {
// get max temperature in this tile
double max_t = 0;
for (int x = sH * i; x < sH * i + sH; x++) {
for (int y = sW * j; y < sW * j + sW; y++) {
max_t = (max_t < m[IND(x, y)]) ? m[IND(x, y)] : max_t;
}
}
double temp = max_t;
// pick the 'color'
int c = ((temp - min) / (max - min)) * numColors;
c = (c >= numColors) ? numColors - 1 : ((c < 0) ? 0 : c);
// print the average temperature
printf("%c", colors[c]);
}
// right wall
printf("X\n");
}
// lower wall
printf("\t");
for (int l = 0; l < W + 2; l++) {
printf("X");
}
printf("\n");
}
|
master.c | // OpenMP Master Example
#include <omp.h>
#include <stdio.h>
#include <stdlib.h>
int main( int argc, char** argv ) {
int num_threads = 0; // Number of Threads
int thread_id = 0; // ID Number of Running Thread
#pragma omp parallel private( num_threads, thread_id )
{
// Get the Thread Number
thread_id = omp_get_thread_num( );
printf( "Hello World from Thread %d\n", thread_id );
// Have Master Print Total Number of Threads Used
#pragma omp master
{
num_threads = omp_get_num_threads( );
printf( "Number of Threads = %d\n", num_threads );
}
}
return 0;
}
// End master.c - EWG SDG
|
mclib.c | #include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <stdbool.h>
#include <glob.h>
#include <unistd.h>
#include <dirent.h>
#include "hdf5.h"
#include <math.h>
#include <time.h>
#include <gsl/gsl_math.h>
#include <gsl/gsl_rng.h>
#include <gsl/gsl_randist.h>
#include <gsl/gsl_blas.h>
#include <gsl/gsl_vector.h>
#include <gsl/gsl_matrix.h>
#include <gsl/gsl_sf_bessel.h>
#include <gsl/gsl_permutation.h>
#include <gsl/gsl_sort.h>
#include <gsl/gsl_sort_vector.h>
#include "mclib_3d.h"
#include <omp.h>
#include "mpi.h"
#define PROP_DIM1 1
#define PROP_DIM2 8
#define PROP_DIM3 8
#define COORD_DIM1 2
#define R_DIM_2D 9120
#define THETA_DIM_2D 2000
//define constants
const double A_RAD=7.56e-15, C_LIGHT=2.99792458e10, PL_CONST=6.6260755e-27;
const double K_B=1.380658e-16, M_P=1.6726231e-24, THOMP_X_SECT=6.65246e-25, M_EL=9.1093879e-28 ;
int getOrigNumProcesses(int *counted_cont_procs, int **proc_array, char dir[200], int angle_rank, int angle_procs, int last_frame, int dim_switch, int riken_switch)
{
int i=0, j=0, val=0, original_num_procs=-1, rand_num=0;
int frame2=0, framestart=0, scatt_framestart=0, ph_num=0;
double time=0;
char mc_chkpt_files[200]="", restrt=""; //define new variable that wont write over the restrt variable in the main part of the code, when its put into the readCheckpoint function
struct photon *phPtr=NULL; //pointer to array of photons
//DIR * dirp;
//struct dirent * entry;
//struct stat st = {0};
glob_t files;
//if (angle_rank==0)
{
//find number of mc_checkpt files there are
//loop through them and find out which prior processes didnt finish and keep track of which ones didnt
snprintf(mc_chkpt_files, sizeof(mc_chkpt_files), "%s%s", dir,"mc_chkpt_*" );
val=glob(mc_chkpt_files, 0, NULL,&files );
printf("TEST: %s\n", mc_chkpt_files);
//look @ a file by choosing rand int between 0 and files.gl_pathc and if the file exists open and read it to get the actual value for the old number of angle_procs
srand(angle_rank);
//printf("NUM_FILES: %d\n",files.gl_pathc);
rand_num=rand() % files.gl_pathc;
snprintf(mc_chkpt_files, sizeof(mc_chkpt_files), "%s%s%d%s", dir,"mc_chkpt_", rand_num,".dat" );
printf("TEST: %s\n", mc_chkpt_files);
if ( access( mc_chkpt_files, F_OK ) == -1 )
{
while(( access( mc_chkpt_files, F_OK ) == -1 ) )
{
rand_num=rand() % files.gl_pathc;
snprintf(mc_chkpt_files, sizeof(mc_chkpt_files), "%s%s%d%s", dir,"mc_chkpt_", rand_num,".dat" );
//printf("TEST: %s\n", mc_chkpt_files);
}
}
readCheckpoint(dir, &phPtr, &frame2, &framestart, &scatt_framestart, &ph_num, &restrt, &time, rand_num, &original_num_procs, dim_switch, riken_switch);
//original_num_procs= 70;
}
int count_procs[original_num_procs], count=0;
int cont_procs[original_num_procs];
//create array of files including any checkpoint file which may not have been created yet b/c old process was still in 1st frame of scattering
for (j=0;j<original_num_procs;j++)
{
count_procs[j]=j;
cont_procs[j]=-1; //set to impossible value for previous mpi process rank that needs to be con't
}
int limit= (angle_rank != angle_procs-1) ? (angle_rank+1)*original_num_procs/angle_procs : original_num_procs;
//char mc_chkpt_files[200]="";
printf("Angle ID: %d, start_num: %d, limit: %d\n", angle_rank, (angle_rank*original_num_procs/angle_procs), limit);
count=0;
for (j=floor(angle_rank*original_num_procs/angle_procs);j<limit;j++)
{
snprintf(mc_chkpt_files, sizeof(mc_chkpt_files), "%s%s%d%s", dir,"mc_chkpt_", j,".dat" );
//printf("TEST: %s\n", mc_chkpt_files);
if ( access( mc_chkpt_files, F_OK ) != -1 )
{
readCheckpoint(dir, &phPtr, &frame2, &framestart, &scatt_framestart, &ph_num, &restrt, &time, count_procs[j], &i, dim_switch, riken_switch);
free(phPtr);
phPtr=NULL;
if ((framestart<=frame2) && (scatt_framestart<=last_frame)) //add another condition here
{
cont_procs[count]=j;
printf("ACCEPTED: %s\n", mc_chkpt_files);
count++;
}
}
else
{
cont_procs[count]=j;
printf("ACCEPTED: %s\n", mc_chkpt_files);
count++;
}
}
(*proc_array)=malloc (count * sizeof (int )); //allocate space to pointer to hold the old process angle_id's
count=0;
for (i=0;i<original_num_procs;i++)
{
if (cont_procs[i]!=-1)
{
(*proc_array)[count]=cont_procs[i];
count++;
}
}
//save number of old processes this process counted need to be restarted
*counted_cont_procs=count;
globfree(& files);
return original_num_procs;
}
void printPhotons(struct photon *ph, int num_ph, int frame,int frame_inj, char dir[200], int angle_rank )
{
//function to save the photons' positions and 4 momentum
int i=0;
char mc_file_p0[200]="", mc_file_p1[200]="",mc_file_p2[200]="", mc_file_p3[200]="";
char mc_file_r0[200]="", mc_file_r1[200]="", mc_file_r2[200]="", mc_file_ns[200]="", mc_file_pw[200]="";
FILE *fPtr=NULL, *fPtr1=NULL,*fPtr2=NULL,*fPtr3=NULL,*fPtr4=NULL,*fPtr5=NULL,*fPtr6=NULL,*fPtr7=NULL,*fPtr8=NULL;
//make strings for proper files
snprintf(mc_file_p0,sizeof(mc_file_p0),"%s%s%d%s%d%s",dir,"mcdata_", frame,"_P0_", angle_rank, ".dat" );
snprintf(mc_file_p1,sizeof(mc_file_p0),"%s%s%d%s%d%s",dir,"mcdata_", frame,"_P1_", angle_rank, ".dat" );
snprintf(mc_file_p2,sizeof(mc_file_p0),"%s%s%d%s%d%s",dir,"mcdata_", frame,"_P2_", angle_rank, ".dat" );
snprintf(mc_file_p3,sizeof(mc_file_p0),"%s%s%d%s%d%s",dir,"mcdata_", frame,"_P3_", angle_rank, ".dat" );
snprintf(mc_file_r0,sizeof(mc_file_p0),"%s%s%d%s%d%s",dir,"mcdata_", frame,"_R0_", angle_rank, ".dat" );
snprintf(mc_file_r1,sizeof(mc_file_p0),"%s%s%d%s%d%s",dir,"mcdata_", frame,"_R1_", angle_rank, ".dat" );
snprintf(mc_file_r2,sizeof(mc_file_p0),"%s%s%d%s%d%s",dir,"mcdata_", frame,"_R2_", angle_rank, ".dat" );
snprintf(mc_file_ns,sizeof(mc_file_p0),"%s%s%d%s%d%s",dir,"mcdata_", frame,"_NS_", angle_rank, ".dat" ); //for number of scatterings each photon went through
if (frame==frame_inj) //if the frame is the same one that the photons were injected in, save the photon weights
{
snprintf(mc_file_pw,sizeof(mc_file_p0),"%s%s%d%s",dir,"mcdata_PW_", angle_rank, ".dat" );
}
//save the energy
fPtr=fopen(mc_file_p0, "a");
fPtr1=fopen(mc_file_p1, "a");
fPtr2=fopen(mc_file_p2, "a");
fPtr3=fopen(mc_file_p3, "a");
fPtr4=fopen(mc_file_r0, "a");
fPtr5=fopen(mc_file_r1, "a");
fPtr6=fopen(mc_file_r2, "a");
fPtr7=fopen(mc_file_ns, "a");
if (frame==frame_inj)
{
fPtr8=fopen(mc_file_pw, "a");
}
//printf("Writing P0\n");
for (i=0;i<num_ph;i++)
{
fprintf(fPtr,"%0.13e\t", (ph+i)->p0);
//printf("%d: %0.13e \n", i, (ph+i)->p0);
fprintf(fPtr1,"%0.13e\t", (ph+i)->p1);
//printf("%d: %0.13e \n", i, (ph+i)->p1);
fprintf(fPtr2,"%0.13e\t", (ph+i)->p2);
//printf("%d: %0.13e \n", i, (ph+i)->p2);
fprintf(fPtr3,"%0.13e\t", (ph+i)->p3);
//printf("%d: %0.13e \n", i, (ph+i)->p3);
fprintf(fPtr4,"%0.13e\t", (ph+i)->r0);
//printf("%d: %0.13e \n", i, (ph+i)->r0);
fprintf(fPtr5,"%0.13e\t", (ph+i)->r1);
//printf("%d: %0.13e \n", i, (ph+i)->r1);
fprintf(fPtr6,"%0.13e\t", (ph+i)->r2);
//printf("%d: %0.13e \n", i, (ph+i)->r2);
//fprintf(fPtr7,"%0.13e\t", *(ph_num_scatt+i));
fprintf(fPtr7,"%e\t", (ph+i)->num_scatt);
//printf("%d: %0.13e \n", i, (ph+i)->num_scatt);
if (frame==frame_inj)
{
fprintf(fPtr8,"%e\t", (ph+i)->weight);
}
}
fclose(fPtr);
fclose(fPtr1);
fclose(fPtr2);
fclose(fPtr3);
fclose(fPtr4);
fclose(fPtr5);
fclose(fPtr6);
fclose(fPtr7);
if (frame==frame_inj)
{
fclose(fPtr8);
}
//printf("%s\n%s\n%s\n", mc_file_p0, mc_file_r0, mc_file_ns);
}
void saveCheckpoint(char dir[200], int frame, int frame2, int scatt_frame, int ph_num,double time_now, struct photon *ph, int last_frame, int angle_rank,int angle_size )
{
//function to save data necessary to restart simulation if it ends
//need to save all photon data
FILE *fPtr=NULL;
char checkptfile[200]="";
char command[200]="";
char restart;
int i=0;
//for openMPI have some type of problem with saving the checkpoint file for the frame in which photons have been injected and scattered in, can try to delete old mc_checkpoint file
//and creating a new one in that case?
snprintf(checkptfile,sizeof(checkptfile),"%s%s%d%s",dir,"mc_chkpt_", angle_rank,".dat" );
if ((scatt_frame!=last_frame) && (scatt_frame != frame))
{
fPtr=fopen(checkptfile, "wb");
//printf("%s\n", checkptfile);
if (fPtr==NULL)
{
printf("Cannot open %s to save checkpoint\n", checkptfile);
}
fwrite(&angle_size, sizeof(int), 1, fPtr);
restart='c';
fwrite(&restart, sizeof(char), 1, fPtr);
//printf("Rank: %d wrote restart %c\n", angle_rank, restart);
fflush(stdout);
fwrite(&frame, sizeof(int), 1, fPtr);
//printf("Rank: %d wrote frame\n", angle_rank);
fflush(stdout);
fwrite(&frame2, sizeof(int), 1, fPtr);
//printf("Rank: %d wrote frame2\n", angle_rank);
fflush(stdout);
fwrite(&scatt_frame, sizeof(int), 1, fPtr);
//printf("Rank: %d wrote scatt_frame\n", angle_rank);
fflush(stdout);
fwrite(&time_now, sizeof(double), 1, fPtr);
//printf("Rank: %d wrote time_now\n", angle_rank);
fflush(stdout);
fwrite(&ph_num, sizeof(int), 1, fPtr);
//printf("Rank: %d wrote ph_num\n", angle_rank);
fflush(stdout);
for(i=0;i<ph_num;i++)
{
fwrite((ph+i), sizeof(struct photon ), 1, fPtr);
//fwrite((ph), sizeof(struct photon )*ph_num, ph_num, fPtr);
}
//printf("Rank: %d wrote photons\n", angle_rank);
fflush(stdout);
}
else if (scatt_frame == frame)
{
snprintf(command, sizeof(command), "%s%s","exec rm ",checkptfile);
system(command);
fPtr=fopen(checkptfile, "wb");
//printf("%s\n", checkptfile);
fflush(stdout);
if (fPtr==NULL)
{
printf("Cannot open %s to save checkpoint\n", checkptfile);
}
fwrite(&angle_size, sizeof(int), 1, fPtr);
restart='c';
fwrite(&restart, sizeof(char), 1, fPtr);
//printf("Rank: %d wrote restart %c\n", angle_rank, restart);
fflush(stdout);
fwrite(&frame, sizeof(int), 1, fPtr);
//printf("Rank: %d wrote frame\n", angle_rank);
fflush(stdout);
fwrite(&frame2, sizeof(int), 1, fPtr);
//printf("Rank: %d wrote frame2\n", angle_rank);
fflush(stdout);
fwrite(&scatt_frame, sizeof(int), 1, fPtr);
//printf("Rank: %d wrote scatt_frame\n", angle_rank);
fflush(stdout);
fwrite(&time_now, sizeof(double), 1, fPtr);
//printf("Rank: %d wrote time_now\n", angle_rank);
fflush(stdout);
fwrite(&ph_num, sizeof(int), 1, fPtr);
//printf("Rank: %d wrote ph_num\n", angle_rank);
fflush(stdout);
for(i=0;i<ph_num;i++)
{
//fwrite((ph), sizeof(struct photon )*ph_num, ph_num, fPtr);
fwrite((ph+i), sizeof(struct photon ), 1, fPtr);
}
//printf("Rank: %d wrote photons\n", angle_rank);
fflush(stdout);
}
else
{
fPtr=fopen(checkptfile, "wb");
//printf("%s\n", checkptfile);
if (fPtr==NULL)
{
printf("Cannot open %s to save checkpoint\n", checkptfile);
}
//just finished last iteration of scatt_frame
fwrite(&angle_size, sizeof(int), 1, fPtr);
restart='r';
fwrite(&restart, sizeof(char), 1, fPtr);
fwrite(&frame, sizeof(int), 1, fPtr);
fwrite(&frame2, sizeof(int), 1, fPtr);
}
fclose(fPtr);
}
void readCheckpoint(char dir[200], struct photon **ph, int *frame2, int *framestart, int *scatt_framestart, int *ph_num, char *restart, double *time, int angle_rank, int *angle_size , int dim_switch, int riken_switch )
{
//function to read in data from checkpoint file
FILE *fPtr=NULL;
char checkptfile[200]="";
int i=0;
//int frame, scatt_frame, ph_num, i=0;
struct photon *phHolder=NULL; //pointer to struct to hold data read in from checkpoint file
snprintf(checkptfile,sizeof(checkptfile),"%s%s%d%s",dir,"mc_chkpt_", angle_rank,".dat" );
printf("Checkpoint file: %s\n", checkptfile);
if (access( checkptfile, F_OK ) != -1) //if you can access the file, open and read it
{
fPtr=fopen(checkptfile, "rb");
{
fread(angle_size, sizeof(int), 1, fPtr); //uncomment once I run MCRAT for the sims that didnt save this originally
}
fread(restart, sizeof(char), 1, fPtr);
//printf("%c\n", *restart);
fread(framestart, sizeof(int), 1, fPtr);
//printf("%d\n", *framestart);
fread(frame2, sizeof(int), 1, fPtr);
if((*restart)=='c')
{
fread(scatt_framestart, sizeof(int), 1, fPtr);
if ((riken_switch==1) && (dim_switch==1) && ((*scatt_framestart)>=3000))
{
*scatt_framestart+=10; //when the frame ==3000 for RIKEN 3D hydro files, increment file numbers by 10 instead of by 1
}
else
{
*scatt_framestart+=1; //add one to start at the next frame after the simulation was interrrupted
}
//printf("%d\n", *scatt_framestart);
fread(time, sizeof(double), 1, fPtr);
//printf("%e\n", *time);
fread(ph_num, sizeof(int), 1, fPtr);
//printf("%d\n", *ph_num);
phHolder=malloc(sizeof(struct photon));
(*ph)=malloc(sizeof(struct photon)*(*ph_num)); //allocate memory to hold photon data
for (i=0;i<(*ph_num);i++)
{
fread(phHolder, sizeof(struct photon), 1, fPtr);
//printf("%e,%e,%e, %e,%e,%e, %e, %e\n",(ph)->p0, (ph)->p1, (ph)->p2, ph->p3, (ph)->r0, (ph)->r1, (ph)->r2, ph->num_scatt );
(*ph)[i].p0=phHolder->p0;
(*ph)[i].p1=phHolder->p1;
(*ph)[i].p2=phHolder->p2;
(*ph)[i].p3=phHolder->p3;
(*ph)[i].r0= phHolder->r0;
(*ph)[i].r1=phHolder->r1 ;
(*ph)[i].r2=phHolder->r2;
(*ph)[i].num_scatt=phHolder->num_scatt;
(*ph)[i].weight=phHolder->weight;
(*ph)[i].nearest_block_index= phHolder->nearest_block_index;
}
free(phHolder);
}
else
{
if ((riken_switch==1) && (dim_switch==1) && ((*framestart)>=3000))
{
*framestart+=10; //when the frame ==3000 for RIKEN 3D hydro files, increment file numbers by 10 instead of by 1
}
else
{
*framestart+=1; //if the checkpoint file saved and the program was inturrupted before the frame variable had just increased and before the scatt_frame iteration was saved, add one to the frame start
}
*scatt_framestart=(*framestart);
}
fclose(fPtr);
}
else //if not use default
{
//*framestart=(*framestart);
*scatt_framestart=(*framestart);
*restart='r';
}
}
void readMcPar(char file[200], double *fluid_domain_x, double *fluid_domain_y, double *fps, double *theta_jmin, double *theta_j, double *d_theta_j, double *inj_radius_small, double *inj_radius_large, int *frm0_small, int *frm0_large, int *last_frm, int *frm2_small,int *frm2_large , double *ph_weight_small,double *ph_weight_large,int *min_photons, int *max_photons, char *spect, char *restart, int *num_threads, int *dim_switch)
{
//function to read mc.par file
FILE *fptr=NULL;
char buf[100]="";
double theta_deg;
//open file
fptr=fopen(file,"r");
//read in frames per sec and other variables outlined in main()
fscanf(fptr, "%lf",fluid_domain_x);
//printf("%lf\n", *fluid_domain_x );
fgets(buf, 100,fptr);
fscanf(fptr, "%lf",fluid_domain_y);
//printf("%lf\n", *fluid_domain_y );
fgets(buf, 100,fptr);
fscanf(fptr, "%lf",fps);
//printf("%f\n", *fps );
fgets(buf, 100,fptr);
fscanf(fptr, "%d",frm0_small);
//printf("%d\n", *frm0_small );
fgets(buf, 100,fptr);
fscanf(fptr, "%d",frm0_large);
//printf("%d\n", *frm0_large );
fgets(buf, 100,fptr);
fscanf(fptr, "%d",last_frm);
//printf("%d\n", *last_frm );
fgets(buf, 100,fptr);
fscanf(fptr, "%d",frm2_small);
*frm2_small+=*frm0_small; //frame to go to is what is given in the file plus the starting frame
//printf("%d\n", *frm2_small );
fgets(buf, 100,fptr);
//fscanf(fptr, "%d",photon_num); remove photon num because we dont need this
//printf("%d\n", *photon_num );
fscanf(fptr, "%d",frm2_large);
*frm2_large+=*frm0_large; //frame to go to is what is given in the file plus the starting frame
//printf("%d\n", *frm2_large );
fgets(buf, 100,fptr);
//fgets(buf, 100,fptr);
fscanf(fptr, "%lf",inj_radius_small);
//printf("%lf\n", *inj_radius_small );
fgets(buf, 100,fptr);
fscanf(fptr, "%lf",inj_radius_large);
//printf("%lf\n", *inj_radius_large );
fgets(buf, 100,fptr);
//theta jmin
fscanf(fptr, "%lf",&theta_deg);
*theta_jmin=theta_deg;//*M_PI/180; leave as degrees to manipulate processes
//printf("%f\n", *theta_jmin );
fgets(buf, 100,fptr);
fscanf(fptr, "%lf",&theta_deg);
*theta_j=theta_deg;//*M_PI/180;
//printf("%f\n", *theta_j );
fgets(buf, 100,fptr);
fscanf(fptr, "%lf",d_theta_j);
//*theta_j=theta_deg;//*M_PI/180;
//printf("%f\n", *theta_j );
fgets(buf, 100,fptr);
fscanf(fptr, "%lf",ph_weight_small);
//printf("%f\n", *ph_weight_small );
fgets(buf, 100,fptr);
fscanf(fptr, "%lf",ph_weight_large);
fgets(buf, 100,fptr);
fscanf(fptr, "%d",min_photons);
fgets(buf, 100,fptr);
fscanf(fptr, "%d",max_photons);
fgets(buf, 100,fptr);
*spect=getc(fptr);
fgets(buf, 100,fptr);
//printf("%c\n",*spect);
*restart=getc(fptr);
fgets(buf, 100,fptr);
fscanf(fptr, "%d",num_threads);
//printf("%d\n",*num_threads);
fgets(buf, 100,fptr);
fscanf(fptr, "%d",dim_switch);
//printf("%d\n",*dim_switch);
//close file
fclose(fptr);
}
void readAndDecimate(char flash_file[200], double r_inj, double fps, double **x, double **y, double **szx, double **szy, double **r,\
double **theta, double **velx, double **vely, double **dens, double **pres, double **gamma, double **dens_lab, double **temp, int *number, int ph_inj_switch, double min_r, double max_r, double min_theta, double max_theta, FILE *fPtr)
{
//function to read in data from FLASH file
hid_t file,dset, space;
herr_t status;
hsize_t dims[2]={0,0}; //hold dimension size for coordinate data set (mostly interested in dims[0])
double **vel_x_buffer=NULL, **vel_y_buffer=NULL, **dens_buffer=NULL, **pres_buffer=NULL, **coord_buffer=NULL, **block_sz_buffer=NULL;
double *velx_unprc=NULL, *vely_unprc=NULL, *dens_unprc=NULL, *pres_unprc=NULL, *x_unprc=NULL, *y_unprc=NULL, *r_unprc=NULL, *szx_unprc=NULL, *szy_unprc=NULL;
int i,j,count,x1_count, y1_count, r_count, **node_buffer=NULL, num_nodes=0, elem_factor=0;
double x1[8]={-7.0/16,-5.0/16,-3.0/16,-1.0/16,1.0/16,3.0/16,5.0/16,7.0/16};
double ph_rmin=0, ph_rmax=0, ph_thetamin=0, ph_thetamax=0, r_grid_innercorner=0, r_grid_outercorner=0, theta_grid_innercorner=0, theta_grid_outercorner=0;
if (ph_inj_switch==0)
{
ph_rmin=min_r;
ph_rmax=max_r;
ph_thetamin=min_theta-2*0.017453292519943295; //min_theta - 2*Pi/180 (2 degrees)
ph_thetamax=max_theta+2*0.017453292519943295; //max_theta + 2*Pi/180 (2 degrees)
}
file = H5Fopen (flash_file, H5F_ACC_RDONLY, H5P_DEFAULT);
//ret=H5Pclose(acc_tpl1);
fprintf(fPtr, ">> mc.py: Reading positional, density, pressure, and velocity information...\n");
fflush(fPtr);
//printf("Reading coord\n");
dset = H5Dopen (file, "coordinates", H5P_DEFAULT);
//get dimensions of array and save it
space = H5Dget_space (dset);
H5Sget_simple_extent_dims(space, dims, NULL); //save dimesnions in dims
/*
* Allocate array of pointers to rows. OPTIMIZE HERE: INITALIZE ALL THE BUFFERS AT ONCE IN 1 FOR LOOP
*/
coord_buffer = (double **) malloc (dims[0] * sizeof (double *));
coord_buffer[0] = (double *) malloc (dims[0] * dims[1] * sizeof (double));
block_sz_buffer= (double **) malloc (dims[0] * sizeof (double *));
block_sz_buffer[0] = (double *) malloc (dims[0] * COORD_DIM1 * sizeof (double));
node_buffer= (int **) malloc (dims[0] * sizeof (int *));
node_buffer[0] = (int *) malloc (dims[0] * sizeof (int));
vel_x_buffer= (double **) malloc (dims[0] * sizeof (double *));
vel_x_buffer[0]= (double *) malloc (dims[0] * PROP_DIM1 *PROP_DIM2*PROP_DIM3* sizeof (double));
vel_y_buffer= (double **) malloc (dims[0] * sizeof (double *));
vel_y_buffer[0]= (double *) malloc (dims[0] * PROP_DIM1 *PROP_DIM2*PROP_DIM3* sizeof (double));
dens_buffer= (double **) malloc (dims[0] * sizeof (double *));
dens_buffer[0]= (double *) malloc (dims[0] * PROP_DIM1 *PROP_DIM2*PROP_DIM3* sizeof (double));
pres_buffer= (double **) malloc (dims[0] * sizeof (double *));
pres_buffer[0]= (double *) malloc (dims[0] * PROP_DIM1 *PROP_DIM2*PROP_DIM3* sizeof (double));
/*
* Set the rest of the pointers to rows to the correct addresses.
*/
for (i=1; i<dims[0]; i++)
{
coord_buffer[i] = coord_buffer[0] + i * dims[1];
block_sz_buffer[i] = block_sz_buffer[0] + i * COORD_DIM1;
node_buffer[i] = node_buffer[0] + i ;
vel_x_buffer[i] = vel_x_buffer[0] + i * PROP_DIM1*PROP_DIM2*PROP_DIM3;
vel_y_buffer[i] = vel_y_buffer[0] + i * PROP_DIM1*PROP_DIM2*PROP_DIM3;
dens_buffer[i] = dens_buffer[0] + i * PROP_DIM1*PROP_DIM2*PROP_DIM3;
pres_buffer[i] = pres_buffer[0] + i * PROP_DIM1*PROP_DIM2*PROP_DIM3;
}
//read data such that first column is x and second column is y
//printf("Reading Dataset\n");
status = H5Dread (dset, H5T_NATIVE_DOUBLE, H5S_ALL, H5S_ALL, H5P_DEFAULT,coord_buffer[0]);
//close dataset
status = H5Sclose (space);
status = H5Dclose (dset);
//printf("Reading block size\n");
dset = H5Dopen (file, "block size", H5P_DEFAULT);
//printf("Reading Dataset\n");
status = H5Dread (dset, H5T_NATIVE_DOUBLE, H5S_ALL, H5S_ALL, H5P_DEFAULT,block_sz_buffer[0]);
// first column of buffer is x and second column is y
status = H5Dclose (dset);
//printf("Reading node type\n");
dset = H5Dopen (file, "node type", H5P_DEFAULT);
//printf("Reading Dataset\n");
status = H5Dread (dset, H5T_NATIVE_INT, H5S_ALL, H5S_ALL, H5P_DEFAULT,node_buffer[0]);
status = H5Dclose (dset);
//printf("Reading velx\n");
dset = H5Dopen (file, "velx", H5P_DEFAULT);
//printf("Reading Dataset\n");
status = H5Dread (dset, H5T_NATIVE_DOUBLE, H5S_ALL, H5S_ALL, H5P_DEFAULT,vel_x_buffer[0]);
status = H5Dclose (dset);
//printf("Reading vely\n");
dset = H5Dopen (file, "vely", H5P_DEFAULT);
//printf("Reading Dataset\n");
status = H5Dread (dset, H5T_NATIVE_DOUBLE, H5S_ALL, H5S_ALL, H5P_DEFAULT,vel_y_buffer[0]);
status = H5Dclose (dset);
//printf("Reading dens\n");
dset = H5Dopen (file, "dens", H5P_DEFAULT);
//printf("Reading Dataset\n");
status = H5Dread (dset, H5T_NATIVE_DOUBLE, H5S_ALL, H5S_ALL, H5P_DEFAULT,dens_buffer[0]);
status = H5Dclose (dset);
//printf("Reading pres\n");
dset = H5Dopen (file, "pres", H5P_DEFAULT);
//printf("Reading Dataset\n");
status = H5Dread (dset, H5T_NATIVE_DOUBLE, H5S_ALL, H5S_ALL, H5P_DEFAULT,pres_buffer[0]);
status = H5Dclose (dset);
//H5Pclose(xfer_plist);
status = H5Fclose (file);
fprintf(fPtr,">> Selecting good node types (=1)\n");
//find out how many good nodes there are
for (i=0;i<dims[0];i++)
{
if (node_buffer[i][0]==1 ){
num_nodes++;
}
}
//allocate memory for arrays to hold unprocessed data
pres_unprc=malloc (num_nodes* PROP_DIM1 *PROP_DIM2*PROP_DIM3 * sizeof (double ));
dens_unprc=malloc (num_nodes* PROP_DIM1 *PROP_DIM2*PROP_DIM3 * sizeof (double ));
velx_unprc=malloc (num_nodes* PROP_DIM1 *PROP_DIM2*PROP_DIM3 * sizeof (double ));
vely_unprc=malloc (num_nodes* PROP_DIM1 *PROP_DIM2*PROP_DIM3 * sizeof (double ));
x_unprc=malloc (num_nodes* PROP_DIM1 *PROP_DIM2*PROP_DIM3 * sizeof (double ));
y_unprc=malloc (num_nodes* PROP_DIM1 *PROP_DIM2*PROP_DIM3 * sizeof (double ));
r_unprc=malloc (num_nodes* PROP_DIM1 *PROP_DIM2*PROP_DIM3 * sizeof (double ));
szx_unprc=malloc (num_nodes* PROP_DIM1 *PROP_DIM2*PROP_DIM3 * sizeof (double ));
szy_unprc=malloc (num_nodes* PROP_DIM1 *PROP_DIM2*PROP_DIM3 * sizeof (double ));
//find where the good values corresponding to the good gones (=1) and save them to the previously allocated pointers which are 1D arrays
//also create proper x and y arrays and block size arrays
//and then free up the buffer memory space
fprintf(fPtr,">> Creating and reshaping arrays\n");
count=0;
for (i=0;i<dims[0];i++)
{
if (node_buffer[i][0]==1 )
{
x1_count=0;
y1_count=0;
for (j=0;j<(PROP_DIM1*PROP_DIM2*PROP_DIM3);j++)
{
*(pres_unprc+count)=pres_buffer[i][j];
*(dens_unprc+count)=dens_buffer[i][j];
*(velx_unprc+count)=vel_x_buffer[i][j];
*(vely_unprc+count)=vel_y_buffer[i][j];
*(szx_unprc+count)=((block_sz_buffer[i][0])/8)*1e9; //divide by 8 for resolution, multiply by 1e9 to scale properly?
*(szy_unprc+count)=((block_sz_buffer[i][1])/8)*1e9;
if (j%8==0)
{
x1_count=0;
}
if ((j%8==0) && (j!=0))
{
y1_count++;
}
*(x_unprc+count)=(coord_buffer[i][0]+block_sz_buffer[i][0]*x1[x1_count])*1e9;
*(y_unprc+count)=(coord_buffer[i][1]+block_sz_buffer[i][1]*x1[y1_count])*1e9;
//printf("%d,%d,%d,%d\n",count,j,x1_count,y1_count);
x1_count++;
count++;
}
}
}
free (pres_buffer[0]); free (dens_buffer[0]);free (vel_x_buffer[0]);free (vel_y_buffer[0]); free(coord_buffer[0]);free(block_sz_buffer[0]);free(node_buffer[0]);
free (pres_buffer);free(dens_buffer);free(vel_x_buffer);free(vel_y_buffer);free(coord_buffer);free(block_sz_buffer);free(node_buffer);
//fill in radius array and find in how many places r > injection radius
elem_factor=1;
r_count=0;
while (r_count==0)
{
r_count=0;
elem_factor++;
for (i=0;i<count;i++)
{
*(r_unprc+i)=pow((pow(*(x_unprc+i),2)+pow(*(y_unprc+i),2)),0.5);
if (ph_inj_switch==0)
{
r_grid_innercorner = pow((*(x_unprc+i) - *(szx_unprc+i)/2.0) * ((*(x_unprc+i) - *(szx_unprc+i)/2.0))+(*(y_unprc+i) - *(szx_unprc+i)/2.0) * (*(y_unprc+i) - *(szx_unprc+i)/2.0),0.5);
r_grid_outercorner = pow((*(x_unprc+i) + *(szx_unprc+i)/2.0) * ((*(x_unprc+i) + *(szx_unprc+i)/2.0))+(*(y_unprc+i) + *(szx_unprc+i)/2.0) * (*(y_unprc+i) + *(szx_unprc+i)/2.0),0.5);
theta_grid_innercorner = acos( (*(y_unprc+i) - *(szx_unprc+i)/2.0) /r_grid_innercorner); //arccos of y/r for the bottom left corner
theta_grid_outercorner = acos( (*(y_unprc+i) + *(szx_unprc+i)/2.0) /r_grid_outercorner);
if (((ph_rmin - elem_factor*C_LIGHT/fps) <= r_grid_outercorner) && (r_grid_innercorner <= (ph_rmax + elem_factor*C_LIGHT/fps) ) && (theta_grid_outercorner >= ph_thetamin) && (theta_grid_innercorner <= ph_thetamax) )
{
r_count++;
}
}
else
{
if (*(r_unprc+i)> (0.95*r_inj) )
{
r_count++;
}
}
}
//fprintf(fPtr, "r_count: %d count: %d\n", r_count, count);
}
fprintf(fPtr, "Elem factor: %d Ph_rmin: %e rmax: %e Chosen FLASH min_r: %e max_r: %e min_theta: %e degrees max_theta: %e degrees\n", elem_factor, ph_rmin, ph_rmax, ph_rmin - (elem_factor*C_LIGHT/fps), ph_rmax + (elem_factor*C_LIGHT/fps), ph_thetamin*180/M_PI, ph_thetamax*180/M_PI);
fflush(fPtr);
//allocate memory to hold processed data
(*pres)=malloc (r_count * sizeof (double ));
(*velx)=malloc (r_count * sizeof (double ));
(*vely)=malloc (r_count * sizeof (double ));
(*dens)=malloc (r_count * sizeof (double ));
(*x)=malloc (r_count * sizeof (double ));
(*y)=malloc (r_count * sizeof (double ));
(*r)=malloc (r_count * sizeof (double ));
(*theta)=malloc (r_count * sizeof (double ));
(*gamma)=malloc (r_count * sizeof (double ));
(*dens_lab)=malloc (r_count * sizeof (double ));
(*szx)=malloc (r_count * sizeof (double ));
(*szy)=malloc (r_count * sizeof (double ));
(*temp)=malloc (r_count * sizeof (double ));
//assign values based on r> 0.95*r_inj
j=0;
for (i=0;i<count;i++)
{
if (ph_inj_switch==0)
{
r_grid_innercorner = pow((*(x_unprc+i) - *(szx_unprc+i)/2.0) * ((*(x_unprc+i) - *(szx_unprc+i)/2.0))+(*(y_unprc+i) - *(szx_unprc+i)/2.0) * (*(y_unprc+i) - *(szx_unprc+i)/2.0),0.5);
r_grid_outercorner = pow((*(x_unprc+i) + *(szx_unprc+i)/2.0) * ((*(x_unprc+i) + *(szx_unprc+i)/2.0))+(*(y_unprc+i) + *(szx_unprc+i)/2.0) * (*(y_unprc+i) + *(szx_unprc+i)/2.0),0.5);
theta_grid_innercorner = acos( (*(y_unprc+i) - *(szx_unprc+i)/2.0) /r_grid_innercorner); //arccos of y/r for the bottom left corner
theta_grid_outercorner = acos( (*(y_unprc+i) + *(szx_unprc+i)/2.0) /r_grid_outercorner);
if (((ph_rmin - elem_factor*C_LIGHT/fps) <= r_grid_outercorner) && (r_grid_innercorner <= (ph_rmax + elem_factor*C_LIGHT/fps) ) && (theta_grid_outercorner >= ph_thetamin) && (theta_grid_innercorner <= ph_thetamax))
{
(*pres)[j]=*(pres_unprc+i);
(*velx)[j]=*(velx_unprc+i);
(*vely)[j]=*(vely_unprc+i);
(*dens)[j]=*(dens_unprc+i);
(*x)[j]=*(x_unprc+i);
(*y)[j]=*(y_unprc+i);
(*r)[j]=*(r_unprc+i);
(*szx)[j]=*(szx_unprc+i);
(*szy)[j]=*(szy_unprc+i);
(*theta)[j]=atan2( *(x_unprc+i) , *(y_unprc+i) );//theta in radians in relation to jet axis
(*gamma)[j]=pow(pow(1.0-(pow(*(velx_unprc+i),2)+pow(*(vely_unprc+i),2)),0.5),-1); //v is in units of c
(*dens_lab)[j]= (*(dens_unprc+i)) * (pow(pow(1.0-(pow(*(velx_unprc+i),2)+pow(*(vely_unprc+i),2)),0.5),-1));
(*temp)[j]=pow(3*(*(pres_unprc+i))*pow(C_LIGHT,2.0)/(A_RAD) ,1.0/4.0);
j++;
}
}
else
{
if (*(r_unprc+i)> (0.95*r_inj) )
{
(*pres)[j]=*(pres_unprc+i);
(*velx)[j]=*(velx_unprc+i);
(*vely)[j]=*(vely_unprc+i);
(*dens)[j]=*(dens_unprc+i);
(*x)[j]=*(x_unprc+i);
(*y)[j]=*(y_unprc+i);
(*r)[j]=*(r_unprc+i);
(*szx)[j]=*(szx_unprc+i);
(*szy)[j]=*(szy_unprc+i);
(*theta)[j]=atan2( *(x_unprc+i) , *(y_unprc+i) );//theta in radians in relation to jet axis
(*gamma)[j]=pow(pow(1.0-(pow(*(velx_unprc+i),2)+pow(*(vely_unprc+i),2)),0.5),-1); //v is in units of c
(*dens_lab)[j]= (*(dens_unprc+i)) * (pow(pow(1.0-(pow(*(velx_unprc+i),2)+pow(*(vely_unprc+i),2)),0.5),-1));
(*temp)[j]=pow(3*(*(pres_unprc+i))*pow(C_LIGHT,2.0)/(A_RAD) ,1.0/4.0);
j++;
}
}
}
*number=j;
//fprintf(fPtr, "number: %d\n", j);
free(pres_unprc); free(velx_unprc);free(vely_unprc);free(dens_unprc);free(x_unprc); free(y_unprc);free(r_unprc);free(szx_unprc);free(szy_unprc);
}
void photonInjection( struct photon **ph, int *ph_num, double r_inj, double ph_weight, int min_photons, int max_photons, char spect, int array_length, double fps, double theta_min, double theta_max,\
double *x, double *y, double *szx, double *szy, double *r, double *theta, double *temps, double *vx, double *vy, gsl_rng * rand, int riken_switch, FILE *fPtr)
{
int i=0, block_cnt=0, *ph_dens=NULL, ph_tot=0, j=0,k=0;
double ph_dens_calc=0.0, fr_dum=0.0, y_dum=0.0, yfr_dum=0.0, fr_max=0, bb_norm=0, position_phi, ph_weight_adjusted, rmin, rmax;
double com_v_phi, com_v_theta, *p_comv=NULL, *boost=NULL; //comoving phi, theta, comoving 4 momentum for a photon, and boost for photon(to go to lab frame)
double *l_boost=NULL; //pointer to hold array of lorentz boost, to lab frame, values
float num_dens_coeff;
if (spect=='w') //from MCRAT paper, w for wien spectrum
{
num_dens_coeff=8.44;
//printf("in wien spectrum\n");
}
else
{
num_dens_coeff=20.29; //this is for black body spectrum
//printf("in BB spectrum");
}
//find how many blocks are near the injection radius within the angles defined in mc.par, get temperatures and calculate number of photons to allocate memory for
//and then rcord which blocks have to have "x" amount of photons injected there
rmin=r_inj - 0.5*C_LIGHT/fps;
rmax=r_inj + 0.5*C_LIGHT/fps;
for(i=0;i<array_length;i++)
{
//look at all boxes in width delta r=c/fps and within angles we are interested in NEED TO IMPLEMENT
if ((*(r+i) >= rmin) && (*(r+i) < rmax ) && (*(theta+i)< theta_max) && (*(theta+i) >=theta_min) )
{
block_cnt++;
}
}
//printf("Blocks: %d\n", block_cnt);
ph_dens=malloc(block_cnt * sizeof(int));
//calculate the photon density for each block and save it to the array
j=0;
ph_tot=0;
ph_weight_adjusted=ph_weight;
//printf("%d %d\n", max_photons, min_photons);
while ((ph_tot>max_photons) || (ph_tot<min_photons) )
{
j=0;
ph_tot=0;
//allocate memory to record density of photons for each block
//ph_dens=malloc(block_cnt * sizeof(int));
for (i=0;i<array_length;i++)
{
//printf("%d\n",i);
//printf("%e, %e, %e, %e, %e, %e\n", *(r+i),(r_inj - C_LIGHT/fps), (r_inj + C_LIGHT/fps), *(theta+i) , theta_max, theta_min);
if ((*(r+i) >= rmin) && (*(r+i) < rmax ) && (*(theta+i)< theta_max) && (*(theta+i) >=theta_min) )
{
if (riken_switch==0)
{
//using FLASH
ph_dens_calc=(num_dens_coeff*2.0*M_PI*(*(x+i))*pow(*(temps+i),3.0)*pow(*(szx+i),2.0) /(ph_weight_adjusted))*pow(pow(1.0-(pow(*(vx+i),2)+pow(*(vy+i),2)),0.5),-1) ; //a*T^3/(weight) dV, dV=2*PI*x*dx^2,
}
else
{
ph_dens_calc=(num_dens_coeff*2.0*M_PI*pow(*(r+i),2)*sin(*(theta+i))*pow(*(temps+i),3.0)*(*(szx+i))*(*(szy+i)) /(ph_weight_adjusted))*pow(pow(1.0-(pow(*(vx+i),2)+pow(*(vy+i),2)),0.5),-1); //dV=2 *pi* r^2 Sin(theta) dr dtheta
}
(*(ph_dens+j))=gsl_ran_poisson(rand,ph_dens_calc) ; //choose from poission distribution with mean of ph_dens_calc
//printf("%d, %lf \n",*(ph_dens+j), ph_dens_calc);
//sum up all the densities to get total number of photons
ph_tot+=(*(ph_dens+j));
j++;
}
}
if (ph_tot>max_photons)
{
//if the number of photons is too big make ph_weight larger
ph_weight_adjusted*=10;
//free(ph_dens);
}
else if (ph_tot<min_photons)
{
ph_weight_adjusted*=0.5;
//free(ph_dens);
}
//printf("dens: %d, photons: %d\n", *(ph_dens+(j-1)), ph_tot);
}
//printf("%d\n", ph_tot);
//allocate memory for that many photons and also allocate memory to hold comoving 4 momentum of each photon and the velocity of the fluid
(*ph)=malloc (ph_tot * sizeof (struct photon ));
p_comv=malloc(4*sizeof(double));
boost=malloc(3*sizeof(double));
l_boost=malloc(4*sizeof(double));
//go through blocks and assign random energies/locations to proper number of photons
ph_tot=0;
k=0;
for (i=0;i<array_length;i++)
{
if ((*(r+i) >= rmin) && (*(r+i) < rmax ) && (*(theta+i)< theta_max) && (*(theta+i) >= theta_min) )
{
//*(temps+i)=0.76*(*(temps+i));
for(j=0;j<( *(ph_dens+k) ); j++ )
{
//have to get random frequency for the photon comoving frequency
y_dum=1; //initalize loop
yfr_dum=0;
while (y_dum>yfr_dum)
{
fr_dum=gsl_rng_uniform_pos(rand)*6.3e11*(*(temps+i)); //in Hz
//printf("%lf, %lf ",gsl_rng_uniform_pos(rand), (*(temps+i)));
y_dum=gsl_rng_uniform_pos(rand);
//printf("%lf ",fr_dum);
if (spect=='w')
{
yfr_dum=(1.0/(1.29e31))*pow((fr_dum/(*(temps+i))),3.0)/(exp((PL_CONST*fr_dum)/(K_B*(*(temps+i)) ))-1); //curve is normalized to maximum
}
else
{
fr_max=(5.88e10)*(*(temps+i));//(C_LIGHT*(*(temps+i)))/(0.29); //max frequency of bb
bb_norm=(PL_CONST*fr_max * pow((fr_max/C_LIGHT),2.0))/(exp(PL_CONST*fr_max/(K_B*(*(temps+i))))-1); //find value of bb at fr_max
yfr_dum=((1.0/bb_norm)*PL_CONST*fr_dum * pow((fr_dum/C_LIGHT),2.0))/(exp(PL_CONST*fr_dum/(K_B*(*(temps+i))))-1); //curve is normalized to vaue of bb @ max frequency
}
//printf("%lf, %lf,%lf,%e \n",(*(temps+i)),fr_dum, y_dum, yfr_dum);
}
//printf("%lf\n ",fr_dum);
position_phi=gsl_rng_uniform(rand)*2*M_PI;
com_v_phi=gsl_rng_uniform(rand)*2*M_PI;
com_v_theta=acos((gsl_rng_uniform(rand)*2)-1);
//printf("%lf, %lf, %lf\n", position_phi, com_v_phi, com_v_theta);
//populate 4 momentum comoving array
*(p_comv+0)=PL_CONST*fr_dum/C_LIGHT;
*(p_comv+1)=(PL_CONST*fr_dum/C_LIGHT)*sin(com_v_theta)*cos(com_v_phi);
*(p_comv+2)=(PL_CONST*fr_dum/C_LIGHT)*sin(com_v_theta)*sin(com_v_phi);
*(p_comv+3)=(PL_CONST*fr_dum/C_LIGHT)*cos(com_v_theta);
//populate boost matrix, not sure why multiplying by -1, seems to give correct answer in old python code...
*(boost+0)=-1*(*(vx+i))*cos(position_phi);
*(boost+1)=-1*(*(vx+i))*sin(position_phi);
*(boost+2)=-1*(*(vy+i));
//printf("%lf, %lf, %lf\n", *(boost+0), *(boost+1), *(boost+2));
//boost to lab frame
lorentzBoost(boost, p_comv, l_boost, 'p', fPtr);
//printf("Assignemnt: %e, %e, %e, %e\n", *(l_boost+0), *(l_boost+1), *(l_boost+2),*(l_boost+3));
(*ph)[ph_tot].p0=(*(l_boost+0));
(*ph)[ph_tot].p1=(*(l_boost+1));
(*ph)[ph_tot].p2=(*(l_boost+2));
(*ph)[ph_tot].p3=(*(l_boost+3));
(*ph)[ph_tot].r0= (*(x+i))*cos(position_phi); //put photons @ center of box that they are supposed to be in with random phi
(*ph)[ph_tot].r1=(*(x+i))*sin(position_phi) ;
(*ph)[ph_tot].r2=(*(y+i)); //y coordinate in flash becomes z coordinate in MCRaT
(*ph)[ph_tot].num_scatt=0;
(*ph)[ph_tot].weight=ph_weight_adjusted;
(*ph)[ph_tot].nearest_block_index=0;
//printf("%d\n",ph_tot);
ph_tot++;
}
k++;
}
}
*ph_num=ph_tot; //save number of photons
//printf(" %d: %d\n", *(ph_dens+(k-1)), *ph_num);
free(ph_dens); free(p_comv);free(boost); free(l_boost);
}
void lorentzBoost(double *boost, double *p_ph, double *result, char object, FILE *fPtr)
{
//function to perform lorentz boost
//if doing boost for an electron last argument is 'e' and there wont be a check for zero norm
//if doing boost for a photon last argument is 'p' and there will be a check for zero norm
double beta=0, gamma=0, *boosted_p=NULL;
gsl_vector_view b=gsl_vector_view_array(boost, 3); //make boost pointer into vector
gsl_vector_view p=gsl_vector_view_array(p_ph, 4); //make boost pointer into vector
gsl_matrix *lambda1= gsl_matrix_calloc (4, 4); //create matrix thats 4x4 to do lorentz boost
gsl_vector *p_ph_prime =gsl_vector_calloc(4); //create vestor to hold lorentz boosted vector
/*
fprintf(fPtr,"Boost: %e, %e, %e, %e\n",gsl_blas_dnrm2(&b.vector), *(boost+0), *(boost+1), *(boost+2));
fflush(fPtr);
fprintf(fPtr,"4 Momentum to Boost: %e, %e, %e, %e\n",*(p_ph+0), *(p_ph+1), *(p_ph+2), *(p_ph+3));
fflush(fPtr);
*/
//if magnitude of fluid velocity is != 0 do lorentz boost otherwise dont need to do a boost
if (gsl_blas_dnrm2(&b.vector) > 0)
{
//fprintf(fPtr,"in If\n");
//fflush(fPtr);
beta=gsl_blas_dnrm2(&b.vector);
gamma=1.0/sqrt(1-pow(beta, 2.0));
//fprintf(fPtr,"Beta: %e\tGamma: %e\n",beta,gamma );
//fflush(fPtr);
//initalize matrix values
gsl_matrix_set(lambda1, 0,0, gamma);
gsl_matrix_set(lambda1, 0,1, -1*gsl_vector_get(&b.vector,0)*gamma);
gsl_matrix_set(lambda1, 0,2, -1*gsl_vector_get(&b.vector,1)*gamma);
gsl_matrix_set(lambda1, 0,3, -1*gsl_vector_get(&b.vector,2)*gamma);
gsl_matrix_set(lambda1, 1,1, 1+((gamma-1)*pow(gsl_vector_get(&b.vector,0),2.0)/pow(beta,2.0) ) );
gsl_matrix_set(lambda1, 1,2, ((gamma-1)*(gsl_vector_get(&b.vector,0)* gsl_vector_get(&b.vector,1)/pow(beta,2.0) ) ));
gsl_matrix_set(lambda1, 1,3, ((gamma-1)*(gsl_vector_get(&b.vector,0)* gsl_vector_get(&b.vector,2)/pow(beta,2.0) ) ));
gsl_matrix_set(lambda1, 2,2, 1+((gamma-1)*pow(gsl_vector_get(&b.vector,1),2.0)/pow(beta,2.0) ) );
gsl_matrix_set(lambda1, 2,3, ((gamma-1)*(gsl_vector_get(&b.vector,1)* gsl_vector_get(&b.vector,2)/pow(beta,2.0)) ) );
gsl_matrix_set(lambda1, 3,3, 1+((gamma-1)*pow(gsl_vector_get(&b.vector,2),2.0)/pow(beta,2.0) ) );
gsl_matrix_set(lambda1, 1,0, gsl_matrix_get(lambda1,0,1));
gsl_matrix_set(lambda1, 2,0, gsl_matrix_get(lambda1,0,2));
gsl_matrix_set(lambda1, 3,0, gsl_matrix_get(lambda1,0,3));
gsl_matrix_set(lambda1, 2,1, gsl_matrix_get(lambda1,1,2));
gsl_matrix_set(lambda1, 3,1, gsl_matrix_get(lambda1,1,3));
gsl_matrix_set(lambda1, 3,2, gsl_matrix_get(lambda1,2,3));
gsl_blas_dgemv(CblasNoTrans, 1, lambda1, &p.vector, 0, p_ph_prime );
/*
fprintf(fPtr,"Lorentz Boost Matrix 0: %e,%e, %e, %e\n", gsl_matrix_get(lambda1, 0,0), gsl_matrix_get(lambda1, 0,1), gsl_matrix_get(lambda1, 0,2), gsl_matrix_get(lambda1, 0,3));
fflush(fPtr);
fprintf(fPtr,"Lorentz Boost Matrix 1: %e,%e, %e, %e\n", gsl_matrix_get(lambda1, 1,0), gsl_matrix_get(lambda1, 1,1), gsl_matrix_get(lambda1, 1,2), gsl_matrix_get(lambda1, 1,3));
fflush(fPtr);
fprintf(fPtr,"Lorentz Boost Matrix 2: %e,%e, %e, %e\n", gsl_matrix_get(lambda1, 2,0), gsl_matrix_get(lambda1, 2,1), gsl_matrix_get(lambda1, 2,2), gsl_matrix_get(lambda1, 2,3));
fflush(fPtr);
fprintf(fPtr,"Lorentz Boost Matrix 3: %e,%e, %e, %e\n", gsl_matrix_get(lambda1, 3,0), gsl_matrix_get(lambda1, 3,1), gsl_matrix_get(lambda1, 3,2), gsl_matrix_get(lambda1, 3,3));
fflush(fPtr);
fprintf(fPtr,"Before Check: %e %e %e %e\n ",gsl_vector_get(p_ph_prime, 0), gsl_vector_get(p_ph_prime, 1), gsl_vector_get(p_ph_prime, 2), gsl_vector_get(p_ph_prime, 3));
fflush(fPtr);
*/
//double check vector for 0 norm condition if photon
if (object == 'p')
{
//fprintf(fPtr,"In if\n");
boosted_p=zeroNorm(gsl_vector_ptr(p_ph_prime, 0));
}
else
{
boosted_p=gsl_vector_ptr(p_ph_prime, 0);
}
/*
fprintf(fPtr,"After Check: %e %e %e %e\n ", *(boosted_p+0),*(boosted_p+1),*(boosted_p+2),*(boosted_p+3) );
fflush(fPtr);
* */
}
else
{
/*
fprintf(fPtr,"in else");
fflush(fPtr);
* */
//double check vector for 0 norm condition
if (object=='p')
{
boosted_p=zeroNorm(p_ph);
}
else
{
//if 4 momentum isnt for photon and there is no boost to be done, we dont care about normality and just want back what was passed to lorentz boost
boosted_p=gsl_vector_ptr(&p.vector, 0);
}
}
//assign values to result
*(result+0)=*(boosted_p+0);
*(result+1)=*(boosted_p+1);
*(result+2)=*(boosted_p+2);
*(result+3)=*(boosted_p+3);
//free up memory
//free(boosted_p);
gsl_matrix_free (lambda1); gsl_vector_free(p_ph_prime);
}
double *zeroNorm(double *p_ph)
{
//ensures zero norm condition of photon 4 monetum is held
int i=0;
double normalizing_factor=0;
gsl_vector_view p=gsl_vector_view_array((p_ph+1), 3); //make last 3 elements of p_ph pointer into vector
if (*(p_ph+0) != gsl_blas_dnrm2(&p.vector ) )
{
normalizing_factor=(gsl_blas_dnrm2(&p.vector ));
//fprintf(fPtr,"in zero norm if\n");
//fflush(fPtr);
//go through and correct 4 momentum assuming the energy is correct
*(p_ph+1)= ((*(p_ph+1))/(normalizing_factor))*(*(p_ph+0));
*(p_ph+2)= ((*(p_ph+2))/(normalizing_factor))*(*(p_ph+0));
*(p_ph+3)= ((*(p_ph+3))/(normalizing_factor))*(*(p_ph+0));
}
/*
if (pow((*(p_ph+0)),2) != ( pow((*(p_ph+1)),2)+pow((*(p_ph+2)),2)+pow((*(p_ph+3)),2) ) )
{
printf("This isnt normalized in the function\nThe difference is: %e\n", pow((*(p_ph+0)),2) - ( pow((*(p_ph+1)),2)+pow((*(p_ph+2)),2)+pow((*(p_ph+3)),2) ) );
}
*/ //normalized within a factor of 10^-53
return p_ph;
}
int findNearestBlock(int array_num, double ph_x, double ph_y, double ph_z, double *x, double *y, double *z, int dim_switch_3d)
{
double dist=0, dist_min=1e15, block_dist=0;
int min_index=0, j=0;
dist_min=1e15;//set dist to impossible value to make sure at least first distance calulated is saved
block_dist=3e9;
while (dist_min==1e15) //if this is true, then the algorithm hasnt found blocks within the acceptable range given by block_dist
{
for(j=0;j<array_num;j++)
{
//if the distance between them is within 3e9, to restrict number of possible calculations, calulate the total distance between the box and photon
if ((dim_switch_3d==0) && (fabs(ph_x- (*(x+j)))<block_dist) && (fabs(ph_y- (*(y+j)))<block_dist))
{
dist= pow(pow(ph_x- (*(x+j)), 2.0) + pow(ph_y- (*(y+j)) , 2.0),0.5);
//fprintf(fPtr,"Dist calculated as: %e, index: %d\n", dist, j);
//printf("In outer if statement, OLD: %e, %d\n", dist_min, min_index);
if((dist<dist_min))
{
//fprintf(fPtr,"In innermost if statement, OLD: %e, %d\n", dist_min, min_index);
dist_min=dist; //save new minimum distance
min_index=j; //save index
//printf("New Min dist: %e, New min Index: %d, Array_Num: %d\n", dist_min, min_index, array_num);
}
}
else if ((dim_switch_3d==1) &&(fabs(ph_x- (*(x+j)))<block_dist) && (fabs(ph_y- (*(y+j)))<block_dist) && (fabs(ph_z- (*(z+j)))<block_dist))
{
dist= pow(pow(ph_x- (*(x+j)), 2.0) + pow(ph_y- (*(y+j)),2.0 ) + pow(ph_z- (*(z+j)) , 2.0),0.5);
if((dist<dist_min))
{
//printf("In innermost if statement, OLD: %e, %d\n", dist_min, min_index);
dist_min=dist; //save new minimum distance
min_index=j; //save index
//fprintf(fPtr,"New Min dist: %e, New min Index: %d, Array_Num: %e\n", dist_min, min_index, array_num);
}
}
}
block_dist*=10; //increase size of accepted distances for gris points, if dist_min==1e12 then the next time the acceptance range wil be larger
}
return min_index;
}
int findContainingBlock(int array_num, double ph_x, double ph_y, double ph_z, double *x, double *y, double *z, double *szx, double *szy, int dim_switch_3d, int riken_switch, FILE *fPtr)
{
int i=0, within_block_index=0;
bool is_in_block=0; //boolean to determine if the photon is outside of a grid
for (i=0;i<array_num;i++)
{
is_in_block=checkInBlock(i, ph_x, ph_y, ph_z, x, y, z, szx, szy, dim_switch_3d, riken_switch);
if (is_in_block)
{
within_block_index=i;
//change for loop index once the block is found so the code doesnt search the rest of the grids to see if the photon is within those grids
i=array_num;
}
}
if (is_in_block==0)
{
fprintf(fPtr, "Couldn't find a block that the photon is in\n");
}
return within_block_index;
}
int checkInBlock(int block_index, double ph_x, double ph_y, double ph_z, double *x, double *y, double *z, double *szx, double *szy, int dim_switch_3d, int riken_switch)
{
bool is_in_block=0; //boolean to determine if the photon is outside of its previously noted block
double x0=0, x1=0, x2=0, sz_x0=0, sz_x1=0, sz_x2=0; //coordinate and sizes of grid block, in cartesian its x,y,z in spherical its r,theta,phi
int return_val=0;
if (dim_switch_3d==0)
{
if (riken_switch==1)
{
x0=pow(pow((*(x+block_index)),2.0)+pow((*(y+block_index)),2.0), 0.5);
x1=atan2((*(x+block_index)), (*(y+block_index)));
sz_x0=(*(szx+block_index));
sz_x1=(*(szy+block_index));
//pow(pow( ph_x, 2.0) + pow(ph_y, 2.0),0.5) atan2(ph_x, ph_y)
is_in_block= (fabs(pow(pow( ph_x, 2.0) + pow(ph_y, 2.0),0.5) - x0) <= sz_x0/2.0) && (fabs(atan2(ph_x, ph_y) - x1 ) <= sz_x1/2.0);
}
else
{
x0=(*(x+block_index));
x1=(*(y+block_index));
sz_x0=(*(szx+block_index));
sz_x1=(*(szy+block_index));
is_in_block= (fabs(ph_x-x0) <= sz_x0/2.0) && (fabs(ph_y-x1) <= sz_x1/2.0);
}
}
else
{
if (riken_switch==1)
{
x0=pow(pow((*(x+block_index)), 2.0) + pow((*(y+block_index)),2.0 ) + pow((*(z+block_index)) , 2.0),0.5);
x1=acos((*(z+block_index))/pow(pow((*(x+block_index)), 2.0) + pow((*(y+block_index)),2.0 ) + pow((*(z+block_index)) , 2.0),0.5));
x2=atan2((*(y+block_index)), (*(x+block_index)));
sz_x0=(*(szy+block_index));
sz_x1=(*(szx+block_index));
sz_x2=(*(szx+block_index));
is_in_block= (fabs(pow(pow( ph_x, 2.0) + pow(ph_y, 2.0)+pow(ph_z, 2.0),0.5) - x0) <= sz_x0/2.0) && (fabs(acos(ph_z/pow(pow(ph_x, 2.0) + pow(ph_y,2.0 ) + pow(ph_z , 2.0),0.5)) - x1 ) <= sz_x1/2.0) && (fabs(atan2(ph_y, ph_x) - x2 ) <= sz_x2/2.0);
}
}
if (is_in_block)
{
return_val=1;
}
else
{
return_val=0;
}
return return_val;
}
int findNearestPropertiesAndMinMFP( struct photon *ph, int num_ph, int array_num, double hydro_domain_x, double hydro_domain_y, double *time_step, double *x, double *y, double *z, double *szx, double *szy, double *velx, double *vely, double *velz, double *dens_lab,\
double *temp, double *n_dens_lab, double *n_vx, double *n_vy, double *n_vz, double *n_temp, gsl_rng * rand, int dim_switch_3d, int find_nearest_block_switch, int riken_switch, FILE *fPtr)
{
int i=0, min_index=0, ph_block_index=0;
double ph_x=0, ph_y=0, ph_phi=0, ph_z=0, ph_r=0;
double fl_v_x=0, fl_v_y=0, fl_v_z=0; //to hold the fluid velocity in MCRaT coordinates
double ph_v_norm=0, fl_v_norm=0;
double n_cosangle=0, n_dens_lab_tmp=0,n_vx_tmp=0, n_vy_tmp=0, n_vz_tmp=0, n_temp_tmp=0 ;
double rnd_tracker=0, n_dens_lab_min=0, n_vx_min=0, n_vy_min=0, n_vz_min=0, n_temp_min=0;
int num_thread=omp_get_num_threads();
bool is_in_block=0; //boolean to determine if the photon is outside of its previously noted block
int index=0;
double mfp=0,min_mfp=0, beta=0;
double *all_time_steps=NULL;
gsl_permutation *perm = gsl_permutation_alloc(num_ph); //to hold sorted indexes of smallest to largest time_steps
gsl_vector_view all_time_steps_vector;
//initialize gsl random number generator fo each thread
const gsl_rng_type *rng_t;
gsl_rng **rng;
gsl_rng_env_setup();
rng_t = gsl_rng_ranlxs0;
rng = (gsl_rng **) malloc((num_thread ) * sizeof(gsl_rng *));
rng[0]=rand;
//#pragma omp parallel for num_threads(nt)
for(i=1;i<num_thread;i++)
{
rng[i] = gsl_rng_alloc (rng_t);
gsl_rng_set(rng[i],gsl_rng_get(rand));
}
//go through each photon and find the blocks around it and then get the distances to all of those blocks and choose the one thats the shortest distance away
//can optimize here, exchange the for loops and change condition to compare to each of the photons is the radius of the block is .95 (or 1.05) times the min (max) photon radius
//or just parallelize this part here
all_time_steps=malloc(num_ph*sizeof(double));
min_mfp=1e12;
#pragma omp parallel for num_threads(num_thread) firstprivate( is_in_block, ph_block_index, ph_r, ph_x, ph_y, ph_z, ph_phi, min_index, n_dens_lab_tmp,n_vx_tmp, n_vy_tmp, n_vz_tmp, n_temp_tmp, fl_v_x, fl_v_y, fl_v_z, fl_v_norm, ph_v_norm, n_cosangle, mfp, beta, rnd_tracker) private(i) shared(min_mfp )
for (i=0;i<num_ph; i++)
{
//printf("%d, %e,%e\n", i, ((ph+i)->r0), ((ph+i)->r1));
if (find_nearest_block_switch==0)
{
ph_block_index=(ph+i)->nearest_block_index; //if starting a new frame the number of indexes can change and cause a seg fault
}
else
{
ph_block_index=0; //if starting a new frame set index=0 to avoid this issue
}
if (dim_switch_3d==0)
{
ph_x=pow(pow(((ph+i)->r0),2.0)+pow(((ph+i)->r1),2.0), 0.5); //convert back to FLASH x coordinate
ph_y=((ph+i)->r2);
ph_phi=atan2(((ph+i)->r1), ((ph+i)->r0));
ph_r=pow(ph_x*ph_x + ph_y*ph_y, 0.5);
}
else
{
ph_x=((ph+i)->r0);
ph_y=((ph+i)->r1);
ph_z=((ph+i)->r2);
ph_r=pow(ph_x*ph_x + ph_y*ph_y+ph_z*ph_z, 0.5);
}
//if the location of the photon is less than the domain of the hydro simulation then do all of this, otherwise assing huge mfp value so no scattering occurs and the next frame is loaded
if ((ph_y<hydro_domain_y) && (ph_x<hydro_domain_x))
{
//printf("ph_x:%e, ph_y:%e\n", ph_x, ph_y);
is_in_block=checkInBlock(ph_block_index, ph_x, ph_y, ph_z, x, y, z, szx, szy, dim_switch_3d, riken_switch);
if (find_nearest_block_switch==0 && is_in_block)
{
//keep the saved grid index
min_index=ph_block_index;
}
else
{
//find the new index of the block closest to the photon
//min_index=findNearestBlock(array_num, ph_x, ph_y, ph_z, x, y, z, dim_switch_3d); //stop doing this one b/c nearest grid could be one that the photon isnt actually in due to adaptive mesh
//find the new index of the block that the photon is actually in
min_index=findContainingBlock(array_num, ph_x, ph_y, ph_z, x, y, z, szx, szy, dim_switch_3d, riken_switch, fPtr);
(ph+i)->nearest_block_index=min_index; //save the index
}
//fprintf(fPtr,"Outside\n");
//save values
(n_dens_lab_tmp)= (*(dens_lab+min_index));
(n_vx_tmp)= (*(velx+min_index));
(n_vy_tmp)= (*(vely+min_index));
(n_temp_tmp)= (*(temp+min_index));
if (dim_switch_3d==1)
{
(n_vz_tmp)= (*(velz+min_index));
}
if (dim_switch_3d==0)
{
fl_v_x=(*(velx+min_index))*cos(ph_phi);
fl_v_y=(*(velx+min_index))*sin(ph_phi);
fl_v_z=(*(vely+min_index));
}
else
{
fl_v_x=(*(velx+min_index));
fl_v_y=(*(vely+min_index));
fl_v_z=(*(velz+min_index));
}
fl_v_norm=pow(pow(fl_v_x, 2.0)+pow(fl_v_y, 2.0)+pow(fl_v_z, 2.0), 0.5);
ph_v_norm=pow(pow(((ph+i)->p1), 2.0)+pow(((ph+i)->p2), 2.0)+pow(((ph+i)->p3), 2.0), 0.5);
//(*(n_cosangle+i))=((fl_v_x* ((ph+i)->p1))+(fl_v_y* ((ph+i)->p2))+(fl_v_z* ((ph+i)->p3)))/(fl_v_norm*ph_v_norm ); //find cosine of the angle between the photon and the fluid velocities via a dot product
(n_cosangle)=((fl_v_x* ((ph+i)->p1))+(fl_v_y* ((ph+i)->p2))+(fl_v_z* ((ph+i)->p3)))/(fl_v_norm*ph_v_norm ); //make 1 for cylindrical otherwise its undefined
if (dim_switch_3d==0)
{
beta=pow((pow((n_vx_tmp),2)+pow((n_vy_tmp),2)),0.5);
}
else
{
beta=pow((pow((n_vx_tmp),2)+pow((n_vy_tmp),2)+pow((n_vz_tmp),2)),0.5);
}
//put this in to double check that random number is between 0 and 1 (exclusive) because there was a problem with this for parallel case
rnd_tracker=0;
rnd_tracker=gsl_rng_uniform_pos(rng[omp_get_thread_num()]);
//printf("Rnd_tracker: %e Thread number %d \n",rnd_tracker, omp_get_thread_num() );
mfp=(-1)*(M_P/((n_dens_lab_tmp))/THOMP_X_SECT/(1.0-beta*((n_cosangle))))*log(rnd_tracker) ; //calulate the mfp and then multiply it by the ln of a random number to simulate distribution of mean free paths
}
else
{
mfp=min_mfp;
//printf("In ELSE\n");
}
*(all_time_steps+i)=mfp/C_LIGHT;
}
//free rand number generator
for (i=1;i<num_thread;i++)
{
gsl_rng_free(rng[i]);
}
free(rng);
//save variables I need
all_time_steps_vector=gsl_vector_view_array(all_time_steps, num_ph); //makes a vector to use the time steps in another gsl function
gsl_sort_vector_index (perm, &all_time_steps_vector.vector); //sorts timesteps from smallest to largest and saves the indexes fo the smallest to largest elements in perm, the all_time_steps vector stays in the same order as before (ordered by photons)
//for (i=0;i<num_ph;i++)
//{
// *(sorted_indexes+i)= (int) perm->data[i]; //save sorted indexes to array to use outside of function
//}
(*time_step)=*(all_time_steps+( (int) perm->data[0] ));
index= (int) perm->data[0] ;//first element of sorted array, index of photon
min_index=(ph+index)->nearest_block_index; //index of FLASH element closest to photon that will scatter
*(n_dens_lab)= (*(dens_lab+min_index));
*(n_vx)= (*(velx+min_index));
*(n_vy)= (*(vely+min_index));
*(n_temp)= (*(temp+min_index));
if (dim_switch_3d==1)
{
*(n_vz)= (*(velz+min_index));
}
free (all_time_steps);
gsl_permutation_free(perm);
all_time_steps=NULL;
return index;
}
int interpolatePropertiesAndMinMFP( struct photon *ph, int num_ph, int array_num, double *time_step, double *x, double *y, double *z, double *szx, double *szy, double *velx, double *vely, double *velz, double *dens_lab,\
double *temp, double *n_dens_lab, double *n_vx, double *n_vy, double *n_vz, double *n_temp, gsl_rng * rand, int dim_switch_3d, int find_nearest_block_switch, int riken_switch, FILE *fPtr)
{
/*
* THIS FUNCTION IS WRITTEN JUST FOR 2D SIMS AS OF NOW
*/
int i=0, j=0, min_index=0, ph_block_index=0;
int left_block_index=0, right_block_index=0, bottom_block_index=0, top_block_index=0, all_adjacent_block_indexes[4];
double ph_x=0, ph_y=0, ph_phi=0, ph_z=0, dist=0, left_dist_min=0, right_dist_min=0, top_dist_min=0, bottom_dist_min=0, dv=0, v=0;
double fl_v_x=0, fl_v_y=0, fl_v_z=0; //to hold the fluid velocity in MCRaT coordinates
double r=0, theta=0;
double ph_v_norm=0, fl_v_norm=0;
double n_cosangle=0, n_dens_lab_tmp=0,n_vx_tmp=0, n_vy_tmp=0, n_vz_tmp=0, n_temp_tmp=0;
double rnd_tracker=0, n_dens_lab_min=0, n_vx_min=0, n_vy_min=0, n_vz_min=0, n_temp_min=0;
int num_thread=2;//omp_get_max_threads();
bool is_in_block=0; //boolean to determine if the photon is outside of its previously noted block
int index=0;
double mfp=0,min_mfp=0, beta=0;
//initialize gsl random number generator fo each thread
const gsl_rng_type *rng_t;
gsl_rng **rng;
gsl_rng_env_setup();
rng_t = gsl_rng_ranlxs0;
rng = (gsl_rng **) malloc((num_thread ) * sizeof(gsl_rng *));
rng[0]=rand;
//#pragma omp parallel for num_threads(nt)
for(i=1;i<num_thread;i++)
{
rng[i] = gsl_rng_alloc (rng_t);
gsl_rng_set(rng[i],gsl_rng_get(rand));
}
//go through each photon and find the blocks around it and then get the distances to all of those blocks and choose the one thats the shortest distance away
//can optimize here, exchange the for loops and change condition to compare to each of the photons is the radius of the block is .95 (or 1.05) times the min (max) photon radius
//or just parallelize this part here
min_mfp=1e12;
#pragma omp parallel for num_threads(num_thread) firstprivate( r, theta,dv, v, all_adjacent_block_indexes, j, left_block_index, right_block_index, top_block_index, bottom_block_index, is_in_block, ph_block_index, ph_x, ph_y, ph_z, ph_phi, min_index, n_dens_lab_tmp,n_vx_tmp, n_vy_tmp, n_vz_tmp, n_temp_tmp, fl_v_x, fl_v_y, fl_v_z, fl_v_norm, ph_v_norm, n_cosangle, mfp, beta, rnd_tracker) private(i) shared(min_mfp )
for (i=0;i<num_ph; i++)
{
//printf("%d, %e,%e\n", i, ((ph+i)->r0), ((ph+i)->r1));
if (find_nearest_block_switch==0)
{
ph_block_index=(ph+i)->nearest_block_index; //if starting a new frame the number of indexes can change and cause a seg fault
}
else
{
ph_block_index=0; //if starting a new frame set index=0 to avoid this issue
}
if (dim_switch_3d==0)
{
ph_x=pow(pow(((ph+i)->r0),2.0)+pow(((ph+i)->r1),2.0), 0.5); //convert back to FLASH x coordinate
ph_y=((ph+i)->r2);
ph_phi=atan2(((ph+i)->r1), ((ph+i)->r0));
}
else
{
ph_x=((ph+i)->r0);
ph_y=((ph+i)->r1);
ph_z=((ph+i)->r2);
}
//printf("ph_x:%e, ph_y:%e\n", ph_x, ph_y);
is_in_block=checkInBlock(ph_block_index, ph_x, ph_y, ph_z, x, y, z, szx, szy, dim_switch_3d, riken_switch);
if (find_nearest_block_switch==0 && is_in_block)
{
//keep the saved grid index
min_index=ph_block_index;
}
else
{
//find the new index of the block closest to the photon
//min_index=findNearestBlock(array_num, ph_x, ph_y, ph_z, x, y, z, dim_switch_3d); //stop doing this one b/c nearest grid could be one that the photon isnt actually in due to adaptive mesh
//find the new index of the block that the photon is actually in
min_index=findContainingBlock(array_num, ph_x, ph_y, ph_z, x, y, z, szx, szy, dim_switch_3d, riken_switch, fPtr);
(ph+i)->nearest_block_index=min_index; //save the index
}
//look for the blocks surounding the block of interest and order them by the
left_dist_min=1e15;//set dist to impossible value to make sure at least first distance calulated is saved
right_dist_min=1e15;
top_dist_min=1e15;
bottom_dist_min=1e15;
for (j=0;j<array_num;j++)
{
if ((dim_switch_3d==0))
{
dist= pow(pow((*(x+min_index))- (*(x+j)), 2.0) + pow((*(y+min_index))- (*(y+j)) , 2.0),0.5);
}
else
{
dist= pow(pow((*(x+min_index))- (*(x+j)), 2.0) + pow((*(y+min_index))- (*(y+j)),2.0 ) + pow((*(z+min_index))- (*(z+j)) , 2.0),0.5);
}
if ((*(x+j))<(*(x+min_index)) && (dist < left_dist_min) )
{
left_block_index=j;
left_dist_min=dist;
}
else if ((*(x+j))>(*(x+min_index)) && (dist < right_dist_min))
{
right_block_index=j;
right_dist_min=dist;
}
if ((*(y+j))<(*(y+min_index)) && (dist < bottom_dist_min) )
{
bottom_block_index=j;
bottom_dist_min=dist;
}
else if ((*(y+j))>(*(y+min_index)) && (dist < top_dist_min) )
{
top_block_index=j;
top_dist_min=dist;
}
}
all_adjacent_block_indexes[0]=left_block_index;
all_adjacent_block_indexes[1]=right_block_index;
all_adjacent_block_indexes[2]=bottom_block_index;
all_adjacent_block_indexes[3]=top_block_index;
//do a weighted average of the 4 nearest grids based on volume
v=0;
(n_dens_lab_tmp)=0;
(n_vx_tmp)= 0;
(n_vy_tmp)= 0;
(n_temp_tmp)= 0;
(n_vz_tmp)= 0;
for (j=0;j<4;j++)
{
if (riken_switch==0)
{
//using FLASH
dv=2.0*M_PI*(*(x+all_adjacent_block_indexes[j]))*pow(*(szx+all_adjacent_block_indexes[j]),2.0) ;
}
else
{
r=pow(pow((*(x+all_adjacent_block_indexes[j])),2.0)+pow((*(y+all_adjacent_block_indexes[j])),2.0), 0.5);
theta=atan2((*(x+all_adjacent_block_indexes[j])), (*(y+all_adjacent_block_indexes[j])));
dv=2.0*M_PI*pow(r,2)*sin(theta)*(*(szx+all_adjacent_block_indexes[j]))*(*(szy+all_adjacent_block_indexes[j])) ;
}
v+=dv;
//save values
(n_dens_lab_tmp)+= (*(dens_lab+all_adjacent_block_indexes[j]))*dv;
(n_vx_tmp)+= (*(velx+all_adjacent_block_indexes[j]))*dv;
(n_vy_tmp)+= (*(vely+all_adjacent_block_indexes[j]))*dv;
(n_temp_tmp)+= (*(temp+all_adjacent_block_indexes[j]))*dv;
if (dim_switch_3d==1)
{
(n_vz_tmp)+= (*(velz+all_adjacent_block_indexes[j]))*dv;
}
}
//fprintf(fPtr,"Outside\n");
//save values
(n_dens_lab_tmp)/= v;
(n_vx_tmp)/= v;
(n_vy_tmp)/= v;
(n_temp_tmp)/= v;
if (dim_switch_3d==1)
{
(n_vz_tmp)/= v;
}
if (dim_switch_3d==0)
{
fl_v_x=n_vx_tmp*cos(ph_phi);
fl_v_y=n_vx_tmp*sin(ph_phi);
fl_v_z=n_vy_tmp;
}
else
{
fl_v_x=n_vx_tmp;
fl_v_y=n_vy_tmp;
fl_v_z=n_vz_tmp;
}
fl_v_norm=pow(pow(fl_v_x, 2.0)+pow(fl_v_y, 2.0)+pow(fl_v_z, 2.0), 0.5);
ph_v_norm=pow(pow(((ph+i)->p1), 2.0)+pow(((ph+i)->p2), 2.0)+pow(((ph+i)->p3), 2.0), 0.5);
//(*(n_cosangle+i))=((fl_v_x* ((ph+i)->p1))+(fl_v_y* ((ph+i)->p2))+(fl_v_z* ((ph+i)->p3)))/(fl_v_norm*ph_v_norm ); //find cosine of the angle between the photon and the fluid velocities via a dot product
(n_cosangle)=((fl_v_x* ((ph+i)->p1))+(fl_v_y* ((ph+i)->p2))+(fl_v_z* ((ph+i)->p3)))/(fl_v_norm*ph_v_norm ); //make 1 for cylindrical otherwise its undefined
if (dim_switch_3d==0)
{
beta=pow((pow((n_vx_tmp),2)+pow((n_vy_tmp),2)),0.5);
}
else
{
beta=pow((pow((n_vx_tmp),2)+pow((n_vy_tmp),2)+pow((n_vz_tmp),2)),0.5);
}
//put this in to double check that random number is between 0 and 1 (exclusive) because there was a problem with this for parallel case
rnd_tracker=0;
rnd_tracker=gsl_rng_uniform_pos(rng[omp_get_thread_num()]);
mfp=(-1)*(M_P/((n_dens_lab_tmp))/THOMP_X_SECT/(1.0-beta*((n_cosangle))))*log(rnd_tracker) ; //calulate the mfp and then multiply it by the ln of a random number to simulate distribution of mean free paths
#pragma omp critical
if ( mfp<min_mfp)
{
min_mfp=mfp;
n_dens_lab_min= n_dens_lab_tmp;
n_vx_min= n_vx_tmp;
n_vy_min= n_vy_tmp;
if (dim_switch_3d==1)
{
n_vz_min= n_vz_tmp;
}
n_temp_min= n_temp_tmp;
index=i;
//fprintf(fPtr, "Thread is %d. new min: %e for photon %d with block properties: %e, %e, %e Located at: %e, %e, Dist: %e\n", omp_get_thread_num(), mfp, index, n_vx_tmp, n_vy_tmp, n_temp_tmp, *(x+min_index), *(y+min_index), dist_min);
//fflush(fPtr);
#pragma omp flush(min_mfp)
}
}
//free rand number generator
for (i=1;i<num_thread;i++)
{
gsl_rng_free(rng[i]);
}
free(rng);
*(n_dens_lab)= n_dens_lab_min;
*(n_vx)= n_vx_min;
*(n_vy)= n_vy_min;
if (dim_switch_3d==1)
{
*(n_vz)= n_vz_min;
}
*(n_temp)= n_temp_min;
(*time_step)=min_mfp/C_LIGHT;
return index;
}
void updatePhotonPosition(struct photon *ph, int num_ph, double t, FILE *fPtr)
{
//move photons by speed of light
int i=0, num_thread=omp_get_num_threads();
double old_position=0, new_position=0, divide_p0=0;
#pragma omp parallel for num_threads(num_thread) firstprivate(old_position, new_position, divide_p0)
for (i=0;i<num_ph;i++)
{
old_position= pow( pow(ph->r0,2)+pow(ph->r1,2)+pow(ph->r2,2), 0.5 );
divide_p0=1.0/((ph+i)->p0);
((ph+i)->r0)+=((ph+i)->p1)*divide_p0*C_LIGHT*t; //update x position
((ph+i)->r1)+=((ph+i)->p2)*divide_p0*C_LIGHT*t;//update y
((ph+i)->r2)+=((ph+i)->p3)*divide_p0*C_LIGHT*t;//update z
new_position= pow( pow(ph->r0,2)+pow(ph->r1,2)+pow(ph->r2,2), 0.5 );
if ((new_position-old_position)/t > C_LIGHT)
{
fprintf(fPtr, "PHOTON NUMBER %d IS SUPERLUMINAL. ITS SPEED IS %e c.\n", i, ((new_position-old_position)/t)/C_LIGHT);
}
//printf("In update function: %e, %e, %e, %e, %e, %e, %e\n",((ph+i)->r0), ((ph+i)->r1), ((ph+i)->r2), t, ((ph+i)->p1)/((ph+i)->p0), ((ph+i)->p2)/((ph+i)->p0), ((ph+i)->p3)/((ph+i)->p0) );
}
//printf("In update function: %e, %e, %e, %e\n",t, ((ph)->p1)/((ph)->p0), ((ph)->p2)/((ph)->p0), ((ph)->p3)/((ph)->p0) );
}
void photonScatter(struct photon *ph, double flash_vx, double flash_vy, double flash_vz, double fluid_temp, gsl_rng * rand,int dim_switch_3d, FILE *fPtr)
{
//function to perform single photon scattering
double ph_phi=0;
double *ph_p=malloc(4*sizeof(double)); //pointer to hold only photon 4 momentum @ start
double *el_p_comov=malloc(4*sizeof(double));//pointer to hold the electron 4 momenta in comoving frame
double *ph_p_comov=malloc(4*sizeof(double));//pointer to hold the comoving photon 4 momenta
double *fluid_beta=malloc(3*sizeof(double));//pointer to hold fluid velocity vector
double *negative_fluid_beta=malloc(3*sizeof(double));//pointer to hold negative fluid velocity vector
ph_phi=atan2((ph->r1), ((ph->r0)));
/*
fprintf(fPtr,"ph_phi=%e\n", ph_phi);
fflush(fPtr);
*/
//convert flash coordinated into MCRaT coordinates
//printf("Getting fluid_beta\n");
if (dim_switch_3d==0)
{
(*(fluid_beta+0))=flash_vx*cos(ph_phi);
(*(fluid_beta+1))=flash_vx*sin(ph_phi);
(*(fluid_beta+2))=flash_vy;
}
else
{
(*(fluid_beta+0))=flash_vx;
(*(fluid_beta+1))=flash_vy;
(*(fluid_beta+2))=flash_vz;
}
/*
fprintf(fPtr,"FLASH v: %e, %e\n", flash_vx,flash_vy);
fflush(fPtr);
*/
//fill in photon 4 momentum
//printf("filling in 4 momentum in photonScatter\n");
*(ph_p+0)=(ph->p0);
*(ph_p+1)=(ph->p1);
*(ph_p+2)=(ph->p2);
*(ph_p+3)=(ph->p3);
/*
fprintf(fPtr,"Unscattered Photon in Lab frame: %e, %e, %e,%e, %e, %e, %e\n", *(ph_p+0), *(ph_p+1), *(ph_p+2), *(ph_p+3), (ph->r0), (ph->r1), (ph->r2));
fflush(fPtr);
fprintf(fPtr,"Fluid Beta: %e, %e, %e\n", *(fluid_beta+0),*(fluid_beta+1), *(fluid_beta+2));
fflush(fPtr);
*/
//first we bring the photon to the fluid's comoving frame
lorentzBoost(fluid_beta, ph_p, ph_p_comov, 'p', fPtr);
/*
fprintf(fPtr,"Old: %e, %e, %e,%e\n", ph->p0, ph->p1, ph->p2, ph->p3);
fflush(fPtr);
fprintf(fPtr, "Before Scattering, In Comov_frame:\n");
fflush(fPtr);
fprintf(fPtr, "ph_comov: %e, %e, %e,%e\n", *(ph_p_comov+0), *(ph_p_comov+1), *(ph_p_comov+2), *(ph_p_comov+3));
fflush(fPtr);
*/
//second we generate a thermal electron at the correct temperature
singleElectron(el_p_comov, fluid_temp, ph_p_comov, rand, fPtr);
//fprintf(fPtr,"el_comov: %e, %e, %e,%e\n", *(el_p_comov+0), *(el_p_comov+1), *(el_p_comov+2), *(el_p_comov+3));
//fflush(fPtr);
//third we perform the scattering and save scattered photon 4 monetum in ph_p_comov @ end of function
singleComptonScatter(el_p_comov, ph_p_comov, rand, fPtr);
//fprintf(fPtr,"After Scattering, After Lorentz Boost to Comov frame: %e, %e, %e,%e\n", *(ph_p_comov+0), *(ph_p_comov+1), *(ph_p_comov+2), *(ph_p_comov+3));
//fflush(fPtr);
//fourth we bring the photon back to the lab frame
*(negative_fluid_beta+0)=-1*( *(fluid_beta+0));
*(negative_fluid_beta+1)=-1*( *(fluid_beta+1));
*(negative_fluid_beta+2)=-1*( *(fluid_beta+2));
lorentzBoost(negative_fluid_beta, ph_p_comov, ph_p, 'p', fPtr);
//fprintf(fPtr,"Scattered Photon in Lab frame: %e, %e, %e,%e\n", *(ph_p+0), *(ph_p+1), *(ph_p+2), *(ph_p+3));
fflush(fPtr);
if (((*(ph_p+0))*C_LIGHT/1.6e-9) > 1e4)
{
fprintf(fPtr,"Extremely High Photon Energy!!!!!!!!\n");
fflush(fPtr);
}
//fprintf(fPtr,"Old: %e, %e, %e,%e\n", ph->p0, ph->p1, ph->p2, ph->p3);
//fprintf(fPtr, "Old: %e, %e, %e,%e\n", *(ph_p_comov+0), *(ph_p_comov+1), *(ph_p_comov+2), *(ph_p_comov+3));
//assign the photon its new lab 4 momentum
(ph->p0)=(*(ph_p+0));
(ph->p1)=(*(ph_p+1));
(ph->p2)=(*(ph_p+2));
(ph->p3)=(*(ph_p+3));
//printf("Done assigning values to original struct\n");
free(el_p_comov);
free(ph_p_comov);
free(fluid_beta);
free(negative_fluid_beta);
free(ph_p);
ph_p=NULL;negative_fluid_beta=NULL;ph_p_comov=NULL; el_p_comov=NULL;
}
void singleElectron(double *el_p, double temp, double *ph_p, gsl_rng * rand, FILE *fPtr)
{
//generates an electron with random energy
double factor=0, gamma=0;
double y_dum=0, f_x_dum=0, x_dum=0, beta_x_dum=0, beta=0, phi=0, theta=0, ph_theta=0, ph_phi=0;
gsl_matrix *rot= gsl_matrix_calloc (3, 3); //create matrix thats 3x3 to do rotation
gsl_vector_view el_p_prime ; //create vector to hold rotated electron 4 momentum
gsl_vector *result=gsl_vector_alloc (3);
//fprintf(fPtr, "Temp in singleElectron: %e\n", temp);
if (temp>= 1e7)
{
//printf("In if\n");
factor=K_B*temp/(M_EL*pow(C_LIGHT,2.0));
y_dum=1; //initalize loop to get a random gamma from the distribution of electron velocities
f_x_dum=0;
while ((isnan(f_x_dum) !=0) || (y_dum>f_x_dum) )
{
x_dum=gsl_rng_uniform_pos(rand)*(1+100*factor);
beta_x_dum=pow(1-(pow(x_dum, -2.0)) ,0.5);
y_dum=gsl_rng_uniform(rand)/2.0;
f_x_dum=pow(x_dum,2)*(beta_x_dum/gsl_sf_bessel_Kn (2, 1.0/factor))*exp(-1*x_dum/factor); //not sure if this is right is giving small values of gamma -> beta=nan
//fprintf(fPtr,"Choosing a Gamma: xdum: %e, f_x_dum: %e, y_dum: %e\n", x_dum, f_x_dum, y_dum);
}
gamma=x_dum;
}
else
{
//printf("In else\n");
factor=pow(K_B*temp/M_EL,0.5);
//calculate a random gamma from 3 random velocities drawn from a gaussian distribution with std deviation of "factor"
gamma=pow( 1- (pow(gsl_ran_gaussian(rand, factor)/C_LIGHT, 2)+ pow(gsl_ran_gaussian(rand, factor)/C_LIGHT, 2)+pow(gsl_ran_gaussian(rand, factor)/C_LIGHT, 2) ) ,-0.5);
}
//fprintf(fPtr,"Chosen Gamma: %e\n",gamma);
beta=pow( 1- (1/pow( gamma,2.0 )) ,0.5);
//printf("Beta is: %e in singleElectron\n", beta);
phi=gsl_rng_uniform(rand)*2*M_PI;
y_dum=1; //initalize loop to get a random theta
f_x_dum=0;
while (y_dum>f_x_dum)
{
y_dum=gsl_rng_uniform(rand)*1.3;
x_dum=gsl_rng_uniform(rand)*M_PI;
f_x_dum=sin(x_dum)*(1-(beta*cos(x_dum)));
}
theta=x_dum;
//fprintf(fPtr,"Beta: %e\tPhi: %e\tTheta: %e\n",beta,phi, theta);
//fill in electron 4 momentum NOT SURE WHY THE ORDER IS AS SUCH SEEMS TO BE E/c, pz,py,px!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
*(el_p+0)=gamma*(M_EL)*(C_LIGHT);
*(el_p+1)=gamma*(M_EL)*(C_LIGHT)*beta*cos(theta);
*(el_p+2)=gamma*(M_EL)*(C_LIGHT)*beta*sin(theta)*sin(phi);
*(el_p+3)=gamma*(M_EL)*(C_LIGHT)*beta*sin(theta)*cos(phi);
//printf("Old: %e, %e, %e,%e\n", *(el_p+0), *(el_p+1), *(el_p+2), *(el_p+3));
el_p_prime=gsl_vector_view_array((el_p+1), 3);
//find angles of photon NOT SURE WHY WERE CHANGING REFERENCE FRAMES HERE???!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
ph_phi=atan2(*(ph_p+2), *(ph_p+3)); //Double Check
ph_theta=atan2(pow( pow(*(ph_p+2),2)+ pow(*(ph_p+3),2) , 0.5) , (*(ph_p+1)) );
//printf("Calculated Photon phi and theta in singleElectron:%e, %e\n", ph_phi, ph_theta);
//fill in rotation matrix to rotate around x axis to get rid of phi angle
gsl_matrix_set(rot, 1,1,1);
gsl_matrix_set(rot, 2,2,cos(ph_theta));
gsl_matrix_set(rot, 0,0,cos(ph_theta));
gsl_matrix_set(rot, 0,2,-sin(ph_theta));
gsl_matrix_set(rot, 2,0,sin(ph_theta));
gsl_blas_dgemv(CblasNoTrans, 1, rot, &el_p_prime.vector, 0, result);
/*
printf("Rotation Matrix 0: %e,%e, %e\n", gsl_matrix_get(rot, 0,0), gsl_matrix_get(rot, 0,1), gsl_matrix_get(rot, 0,2));
printf("Rotation Matrix 1: %e,%e, %e\n", gsl_matrix_get(rot, 1,0), gsl_matrix_get(rot, 1,1), gsl_matrix_get(rot, 1,2));
printf("Rotation Matrix 2: %e,%e, %e\n", gsl_matrix_get(rot, 2,0), gsl_matrix_get(rot, 2,1), gsl_matrix_get(rot, 2,2));
printf("Middle: %e, %e, %e,%e\n", *(el_p+0), gsl_vector_get(result,0), gsl_vector_get(result,1), gsl_vector_get(result,2));
*/
gsl_matrix_set_all(rot,0);
gsl_matrix_set(rot, 0,0,1);
gsl_matrix_set(rot, 1,1,cos(-ph_phi));
gsl_matrix_set(rot, 2,2,cos(-ph_phi));
gsl_matrix_set(rot, 1,2,-sin(-ph_phi));
gsl_matrix_set(rot, 2,1,sin(-ph_phi));
gsl_blas_dgemv(CblasNoTrans, 1, rot, result, 0, &el_p_prime.vector);
/*
printf("Rotation Matrix 0: %e,%e, %e\n", gsl_matrix_get(rot, 0,0), gsl_matrix_get(rot, 0,1), gsl_matrix_get(rot, 0,2));
printf("Rotation Matrix 1: %e,%e, %e\n", gsl_matrix_get(rot, 1,0), gsl_matrix_get(rot, 1,1), gsl_matrix_get(rot, 1,2));
printf("Rotation Matrix 2: %e,%e, %e\n", gsl_matrix_get(rot, 2,0), gsl_matrix_get(rot, 2,1), gsl_matrix_get(rot, 2,2));
printf("Final EL_P_vec: %e, %e, %e,%e\n", *(el_p+0), gsl_vector_get(&el_p_prime.vector,0), gsl_vector_get(&el_p_prime.vector,1), gsl_vector_get(&el_p_prime.vector,2));
*/
gsl_matrix_free (rot);gsl_vector_free(result);
}
void singleComptonScatter(double *el_comov, double *ph_comov, gsl_rng * rand, FILE *fPtr)
{
//This routine performs a Compton scattering between a photon and a moving electron.
int i=0;
double *el_v=malloc(3*sizeof(double));
double *negative_el_v=malloc(3*sizeof(double));
double *ph_p_prime=malloc(4*sizeof(double));//use this to keep track of how the ph 4 momentum changes with each rotation
double *el_p_prime=malloc(4*sizeof(double));
double phi0=0, phi1=0, phi=0, theta=0;
double y_dum, f_x_dum, x_dum;
gsl_matrix *rot0= gsl_matrix_calloc (3, 3); //create matricies thats 3x3 to do rotations
gsl_matrix *rot1= gsl_matrix_calloc (3, 3);
gsl_vector *result0=gsl_vector_alloc (3); //vectors to hold results of rotations
gsl_vector *result1=gsl_vector_alloc (3);
gsl_vector *result=gsl_vector_alloc (4);
gsl_vector *whole_ph_p=gsl_vector_alloc (4);
gsl_vector_view ph_p ; //create vector to hold comoving photon and electron 4 momentum
gsl_vector_view el_p ;
//fill in electron velocity array and photon 4 momentum
*(el_v+0)=(*(el_comov+1))/(*(el_comov+0));
*(el_v+1)=(*(el_comov+2))/(*(el_comov+0));
*(el_v+2)=(*(el_comov+3))/(*(el_comov+0));
//printf("el_v: %e, %e, %e\n", *(el_v+0), *(el_v+1), *(el_v+2));
//lorentz boost into frame where the electron is stationary
lorentzBoost(el_v, el_comov, el_p_prime, 'e', fPtr);
lorentzBoost(el_v, ph_comov, ph_p_prime, 'p', fPtr);
//printf("New ph_p in electron rest frame: %e, %e, %e,%e\n", *(ph_p_prime+0), *(ph_p_prime+1), *(ph_p_prime+2), *(ph_p_prime+3));
ph_p=gsl_vector_view_array((ph_p_prime+1), 3);
el_p=gsl_vector_view_array(el_p_prime,4);
phi0=atan2(*(ph_p_prime+2), *(ph_p_prime+1) );
//printf("Photon Phi: %e\n", phi0);
//rotate the axes so that the photon incomes along the x-axis
gsl_matrix_set(rot0, 2,2,1);
gsl_matrix_set(rot0, 0,0,cos(-phi0));
gsl_matrix_set(rot0, 1,1,cos(-phi0));
gsl_matrix_set(rot0, 0,1,-sin(-phi0));
gsl_matrix_set(rot0, 1,0,sin(-phi0));
gsl_blas_dgemv(CblasNoTrans, 1, rot0, &ph_p.vector, 0, result0);
/*
printf("Rotation Matrix 0: %e,%e, %e\n", gsl_matrix_get(rot0, 0,0), gsl_matrix_get(rot0, 0,1), gsl_matrix_get(rot0, 0,2));
printf("Rotation Matrix 1: %e,%e, %e\n", gsl_matrix_get(rot0, 1,0), gsl_matrix_get(rot0, 1,1), gsl_matrix_get(rot0, 1,2));
printf("Rotation Matrix 2: %e,%e, %e\n", gsl_matrix_get(rot0, 2,0), gsl_matrix_get(rot0, 2,1), gsl_matrix_get(rot0, 2,2));
*/
//set values of ph_p_prime equal to the result and get new phi from result
*(ph_p_prime+1)=gsl_vector_get(result0,0);
*(ph_p_prime+2)=0;//gsl_vector_get(result,1); //just directly setting it to 0 now?
*(ph_p_prime+3)=gsl_vector_get(result0,2);
phi1=atan2(gsl_vector_get(result0,2), gsl_vector_get(result0,0));
/*
printf("rotation 1: %e, %e, %e\n", *(ph_p_prime+1), *(ph_p_prime+2), *(ph_p_prime+3));
printf("Photon Phi: %e\n", phi1);
printf("make sure the vector view is good: %e, %e, %e,%e\n", *(ph_p_prime+0), gsl_vector_get(&ph_p.vector,0), gsl_vector_get(&ph_p.vector,1), gsl_vector_get(&ph_p.vector,2));
*/
//rotate around y to bring it all along x
gsl_matrix_set(rot1, 1,1,1);
gsl_matrix_set(rot1, 0,0,cos(-phi1));
gsl_matrix_set(rot1, 2,2,cos(-phi1));
gsl_matrix_set(rot1, 0,2,-sin(-phi1));
gsl_matrix_set(rot1, 2,0,sin(-phi1));
gsl_blas_dgemv(CblasNoTrans, 1, rot1, &ph_p.vector, 0, result1);
/*
printf("Rotation Matrix 0: %e,%e, %e\n", gsl_matrix_get(rot1, 0,0), gsl_matrix_get(rot1, 0,1), gsl_matrix_get(rot1, 0,2));
printf("Rotation Matrix 1: %e,%e, %e\n", gsl_matrix_get(rot1, 1,0), gsl_matrix_get(rot1, 1,1), gsl_matrix_get(rot1, 1,2));
printf("Rotation Matrix 2: %e,%e, %e\n", gsl_matrix_get(rot1, 2,0), gsl_matrix_get(rot1, 2,1), gsl_matrix_get(rot1, 2,2));
*/
//set values of ph_p_prime equal to the result and get new phi from result
*(ph_p_prime+1)=*(ph_p_prime+0);//why setting it to the energy?
*(ph_p_prime+2)=gsl_vector_get(result1,1);
*(ph_p_prime+3)=0; //just directly setting it to 0 now?
//printf("rotation 2: %e, %e, %e, %e\n", *(ph_p_prime+0), *(ph_p_prime+1), *(ph_p_prime+2), *(ph_p_prime+3));
//generate random theta and phi angles for scattering
phi=gsl_rng_uniform(rand)*2*M_PI;
//printf("Phi: %e\n", phi);
y_dum=1; //initalize loop to get a random theta
f_x_dum=0;
while (y_dum>f_x_dum)
{
y_dum=gsl_rng_uniform(rand)*1.09;
x_dum=gsl_rng_uniform(rand)*M_PI;
f_x_dum=sin(x_dum)*(1+pow(cos(x_dum),2));
}
theta=x_dum;
//printf("Theta: %e\n", theta);
//perform scattering and compute new 4-momenta of electron and photon
//scattered photon 4 momentum
gsl_vector_set(result, 0, (*(ph_p_prime+0))/(1+ (( (*(ph_p_prime+0))*(1-cos(theta)) )/(M_EL*C_LIGHT )) ) ); //DOUBLE CHECK HERE!!!!
gsl_vector_set(result, 1, gsl_vector_get(result,0)*cos(theta) );
gsl_vector_set(result, 2, gsl_vector_get(result,0)*sin(theta)*sin(phi) );
gsl_vector_set(result, 3, gsl_vector_get(result,0)*sin(theta)*cos(phi) );
//printf("%e\n", gsl_vector_get(result,0));
//calculate electron 4 momentum OPTIMIZE HERE: DONT USE A FOR LOOP HERE!!!! Done
//prescattered photon 4 momentum
gsl_vector_set(whole_ph_p, 0, (*(ph_p_prime+0)));
gsl_vector_set(whole_ph_p, 1, (*(ph_p_prime+1)));
gsl_vector_set(whole_ph_p, 2, (*(ph_p_prime+2)));
gsl_vector_set(whole_ph_p, 3, (*(ph_p_prime+3)));
/*
for (i=0;i<4;i++)
{
gsl_vector_set(whole_ph_p, i, (*(ph_p_prime+i)));
}
*/
gsl_vector_sub(whole_ph_p,result); //resut is saved into ph_p vector, unscattered-scattered 4 mometum of photon
gsl_vector_add(&el_p.vector ,whole_ph_p);
/*
printf("After scattering:\n");
printf("el_p: %e, %e, %e,%e\n", gsl_vector_get(&el_p.vector,0), gsl_vector_get(&el_p.vector,1), gsl_vector_get(&el_p.vector,2), gsl_vector_get(&el_p.vector,3));
printf("ph_p: %e, %e, %e,%e\n", gsl_vector_get(result,0), gsl_vector_get(result,1), gsl_vector_get(result,2), gsl_vector_get(result,3));
*/
//rotate back to comoving frame
*(ph_p_prime+0)=gsl_vector_get(result,0);
*(ph_p_prime+1)=gsl_vector_get(result,1); //set values of photon prime momentum from doing the scattering to use the vector view of it in dot product
*(ph_p_prime+2)=gsl_vector_get(result,2);
*(ph_p_prime+3)=gsl_vector_get(result,3);
gsl_matrix_set_all(rot1,0);
gsl_matrix_set(rot1, 1,1,1);
gsl_matrix_set(rot1, 0,0,cos(-phi1));
gsl_matrix_set(rot1, 2,2,cos(-phi1));
gsl_matrix_set(rot1, 0,2,sin(-phi1));
gsl_matrix_set(rot1, 2,0,-sin(-phi1));
gsl_blas_dgemv(CblasNoTrans, 1, rot1, &ph_p.vector, 0, result1);
/*
printf("Photon Phi: %e\n", phi1);
printf("Rotation Matrix 0: %e,%e, %e\n", gsl_matrix_get(rot1, 0,0), gsl_matrix_get(rot1, 0,1), gsl_matrix_get(rot1, 0,2));
printf("Rotation Matrix 1: %e,%e, %e\n", gsl_matrix_get(rot1, 1,0), gsl_matrix_get(rot1, 1,1), gsl_matrix_get(rot1, 1,2));
printf("Rotation Matrix 2: %e,%e, %e\n", gsl_matrix_get(rot1, 2,0), gsl_matrix_get(rot1, 2,1), gsl_matrix_get(rot1, 2,2));
*/
//set values of ph_p_prime to result1 from undoing 2nd rotation
*(ph_p_prime+1)=gsl_vector_get(result1,0);
*(ph_p_prime+2)=gsl_vector_get(result1,1);
*(ph_p_prime+3)=gsl_vector_get(result1,2);
//printf("Undo rotation 2: %e, %e, %e, %e\n", *(ph_p_prime+0), *(ph_p_prime+1), *(ph_p_prime+2), *(ph_p_prime+3));
//ignore the electron, dont care about it, undo the first rotation
gsl_matrix_set_all(rot0,0);
gsl_matrix_set(rot0, 2,2,1);
gsl_matrix_set(rot0, 0,0,cos(-phi0));
gsl_matrix_set(rot0, 1,1,cos(-phi0));
gsl_matrix_set(rot0, 0,1,sin(-phi0));
gsl_matrix_set(rot0, 1,0,-sin(-phi0));
gsl_blas_dgemv(CblasNoTrans, 1, rot0, &ph_p.vector, 0, result0);
/*
printf("Photon Phi: %e\n", phi0);
printf("Rotation Matrix 0: %e,%e, %e\n", gsl_matrix_get(rot0, 0,0), gsl_matrix_get(rot0, 0,1), gsl_matrix_get(rot0, 0,2));
printf("Rotation Matrix 1: %e,%e, %e\n", gsl_matrix_get(rot0, 1,0), gsl_matrix_get(rot0, 1,1), gsl_matrix_get(rot0, 1,2));
printf("Rotation Matrix 2: %e,%e, %e\n", gsl_matrix_get(rot0, 2,0), gsl_matrix_get(rot0, 2,1), gsl_matrix_get(rot0, 2,2));
*/
*(ph_p_prime+1)=gsl_vector_get(result0,0);
*(ph_p_prime+2)=gsl_vector_get(result0,1);
*(ph_p_prime+3)=gsl_vector_get(result0,2);
//printf("Undo rotation 1: %e, %e, %e, %e\n", *(ph_p_prime+0), *(ph_p_prime+1), *(ph_p_prime+2), *(ph_p_prime+3));
//deboost photon to lab frame
*(negative_el_v+0)=(-1*(*(el_v+0)));
*(negative_el_v+1)=(-1*(*(el_v+1)));
*(negative_el_v+2)=(-1*(*(el_v+2)));
lorentzBoost(negative_el_v, ph_p_prime, ph_comov, 'p', fPtr);
//printf("Undo boost 1: %e, %e, %e, %e\n", *(ph_comov+0), *(ph_comov+1), *(ph_comov+2), *(ph_comov+3));
gsl_matrix_free(rot0); gsl_matrix_free(rot1);gsl_vector_free(result0);gsl_vector_free(result1);gsl_vector_free(result);
//gsl_rng_free (rand);
gsl_vector_free(whole_ph_p);free(ph_p_prime);free(el_p_prime);free(el_v); free(negative_el_v);
}
double averagePhotonEnergy(struct photon *ph, int num_ph)
{
//to calculate weighted photon energy
int i=0;
double e_sum=0, w_sum=0;
for (i=0;i<num_ph;i++)
{
e_sum+=(((ph+i)->p0)*((ph+i)->weight));
w_sum+=((ph+i)->weight);
}
return (e_sum*C_LIGHT)/w_sum;
}
void phScattStats(struct photon *ph, int ph_num, int *max, int *min, double *avg, double *r_avg )
{
int temp_max=0, temp_min=-1, i=0;
double sum=0, avg_r_sum=0;
for (i=0;i<ph_num;i++)
{
sum+=((ph+i)->num_scatt);
avg_r_sum+=pow(((ph+i)->r0)*((ph+i)->r0) + ((ph+i)->r1)*((ph+i)->r1) + ((ph+i)->r2)*((ph+i)->r2), 0.5);
if (((ph+i)->num_scatt) > temp_max )
{
temp_max=((ph+i)->num_scatt);
//printf("The new max is: %d\n", temp_max);
}
if ((i==0) || (((ph+i)->num_scatt)<temp_min))
{
temp_min=((ph+i)->num_scatt);
//printf("The new min is: %d\n", temp_min);
}
}
*avg=sum/ph_num;
*r_avg=avg_r_sum/ph_num;
*max=temp_max;
*min=temp_min;
}
void cylindricalPrep(double *gamma, double *vx, double *vy, double *dens, double *dens_lab, double *pres, double *temp, int num_array)
{
double gamma_infinity=100, t_comov=1*pow(10, 5), ddensity=3e-7;// the comoving temperature in Kelvin, and the comoving density in g/cm^2
int i=0;
double vel=pow(1-pow(gamma_infinity, -2.0) ,0.5), lab_dens=gamma_infinity*ddensity;
for (i=0; i<num_array;i++)
{
*(gamma+i)=gamma_infinity;
*(vx+i)=0;
*(vy+i)=vel;
*(dens+i)=ddensity;
*(dens_lab+i)=lab_dens;
*(pres+i)=(A_RAD*pow(t_comov, 4.0))/(3*pow(C_LIGHT, 2.0));
*(temp+i)=pow(3*(*(pres+i))*pow(C_LIGHT,2.0)/(A_RAD) ,1.0/4.0); //just assign t_comov
}
}
void sphericalPrep(double *r, double *x, double *y, double *gamma, double *vx, double *vy, double *dens, double *dens_lab, double *pres, double *temp, int num_array, FILE *fPtr)
{
double gamma_infinity=100, lumi=1e52, r00=1e8;
double vel=0;
int i=0;
for (i=0;i<num_array;i++)
{
if ((*(r+i)) >= (r00*gamma_infinity))
{
*(gamma+i)=gamma_infinity;
*(pres+i)=(lumi*pow(r00, 2.0/3.0)*pow(*(r+i), -8.0/3.0) )/(12.0*M_PI*C_LIGHT*pow(gamma_infinity, 4.0/3.0)*pow(C_LIGHT, 2.0));
}
else
{
*(gamma+i)=(*(r+i))/r00;
*(pres+i)=(lumi*pow(r00, 2.0))/(12.0*M_PI*C_LIGHT*pow(C_LIGHT, 2.0)*pow(*(r+i), 4.0) );
}
vel=pow(1-(pow(*(gamma+i), -2.0)) ,0.5);
*(vx+i)=(vel*(*(x+i)))/pow(pow(*(x+i), 2)+ pow(*(y+i), 2) ,0.5);
*(vy+i)=(vel*(*(y+i)))/pow(pow(*(x+i), 2)+ pow(*(y+i), 2) ,0.5);
*(dens+i)=lumi/(4*M_PI*pow(*(r+i), 2.0)*pow(C_LIGHT, 3.0)*gamma_infinity*(*(gamma+i)));
*(dens_lab+i)=(*(dens+i))*(*(gamma+i));
*(temp+i)=pow(3*(*(pres+i))*pow(C_LIGHT,2.0)/(A_RAD) ,1.0/4.0);
//fprintf(fPtr,"Gamma: %lf\nR: %lf\nPres: %e\nvel %lf\nX: %lf\nY %lf\nVx: %lf\nVy: %lf\nDens: %e\nLab_Dens: %e\nTemp: %lf\n", *(gamma+i), *(r+i), *(pres+i), vel, *(x+i), *(y+i), *(vx+i), *(vy+i), *(dens+i), *(dens_lab+i), *(temp+i));
}
}
void dirFileMerge(char dir[200], int start_frame, int last_frame, int numprocs, int angle_id, int dim_switch, int riken_switch, FILE *fPtr )
{
//function to merge files in mcdir produced by various threads
int i=0, j=0, k=0, num_files=8, num_thread=8; //omp_get_max_threads() number of files is number of types of mcdata files there are
int increment=1;
char filename_k[2000]="", file_no_thread_num[2000]="", cmd[2000]="", mcdata_type[200]="";
//printf("Merging files in %s\n", dir);
//#pragma omp parallel for num_threads(num_thread) firstprivate( filename_k, file_no_thread_num, cmd,mcdata_type,num_files, increment ) private(i,j,k)
// i < last frame because calculation before this function gives last_frame as the first frame of the next process set of frames to merge files for
for (i=start_frame;i<last_frame;i=i+increment)
{
fprintf(fPtr, "Merging files for frame: %d\n", i);
fflush(fPtr);
if ((riken_switch==1) && (dim_switch==1) && (i>=3000))
{
increment=10; //when the frame ==3000 for RIKEN 3D hydro files, increment file numbers by 10 instead of by 1
}
for (j=0;j<num_files;j=j+1)
{
switch (j)
{
case 0: snprintf(mcdata_type,sizeof(mcdata_type), "%s", "P0"); break;
case 1: snprintf(mcdata_type,sizeof(mcdata_type), "%s", "P1");break;
case 2: snprintf(mcdata_type,sizeof(mcdata_type), "%s", "P2"); break;
case 3: snprintf(mcdata_type,sizeof(mcdata_type), "%s", "P3"); break;
case 4: snprintf(mcdata_type,sizeof(mcdata_type), "%s", "R0"); break;
case 5: snprintf(mcdata_type,sizeof(mcdata_type), "%s", "R1"); break;
case 6: snprintf(mcdata_type,sizeof(mcdata_type), "%s", "R2"); break;
case 7: snprintf(mcdata_type,sizeof(mcdata_type), "%s", "NS"); break;
}
for (k=0;k<numprocs;k++)
{
snprintf(file_no_thread_num,sizeof(file_no_thread_num),"%s%s%d%s%s%s", dir,"mcdata_",i,"_", mcdata_type,".dat");
snprintf(filename_k,sizeof(filename_k),"%s%s%d%s%s%s%d%s", dir,"mcdata_",i,"_", mcdata_type ,"_",k, ".dat");
//check if both the file exists
if (( access( filename_k, F_OK ) != -1 ) )
{
//if they both do make command to cat the together always in the same order
//fprintf(fPtr, "Merging: %s\n", filename_k);
snprintf(cmd, sizeof(cmd), "%s%s %s%s", "cat ", filename_k, " >> ", file_no_thread_num);
system(cmd);
}
//remove file
snprintf(cmd, sizeof(cmd), "%s%s", "rm ", filename_k);
system(cmd);
}
}
}
if (angle_id==0)
{
//merge photon weight files
for (k=0;k<numprocs;k++)
{
snprintf(file_no_thread_num,sizeof(file_no_thread_num),"%s%s", dir,"mcdata_PW.dat");
snprintf(filename_k,sizeof(filename_k),"%s%s%d%s", dir,"mcdata_PW_",k,".dat");
if (( access( filename_k, F_OK ) != -1 ) )
{
//if they both do make command to cat the together always in the same order
snprintf(cmd, sizeof(cmd), "%s%s %s%s", "cat ", filename_k, " >> ", file_no_thread_num);
system(cmd);
}
//remove files
snprintf(cmd, sizeof(cmd), "%s%s", "rm ", filename_k);
system(cmd);
}
}
}
void modifyFlashName(char flash_file[200], char prefix[200], int frame, int dim_switch)
{
int lim1=0, lim2=0, lim3=0;
if (dim_switch==0)
{
//2D case
lim1=10;
lim2=100;
lim3=1000;
}
else
{
//3d case
lim1=100;
lim2=1000;
lim3=10000;
}
if (frame<lim1)
{
snprintf(flash_file,200, "%s%.3d%d",prefix,000,frame);
}
else if (frame<lim2)
{
snprintf(flash_file,200, "%s%.2d%d",prefix,00,frame);
}
else if (frame<lim3)
{
snprintf(flash_file,200, "%s%d%d",prefix,0,frame);
}
else
{
snprintf(flash_file,200, "%s%d",prefix,frame);
}
}
void readHydro2D(char hydro_prefix[200], int frame, double r_inj, double fps, double **x, double **y, double **szx, double **szy, double **r, double **theta, double **velx, double **vely, double **dens, double **pres, double **gamma, double **dens_lab, double **temp, int *number, int ph_inj_switch, double min_r, double max_r, FILE *fPtr)
{
FILE *hydroPtr=NULL;
char hydrofile[200]="", file_num[200]="", full_file[200]="", file_end[200]="" ;
char buf[10]="";
int i=0, j=0, k=0, elem=0, elem_factor=0;
int all_index_buffer=0, r_min_index=0, r_max_index=0, theta_min_index=0, theta_max_index=0; //all_index_buffer contains phi_min, phi_max, theta_min, theta_max, r_min, r_max indexes to get from grid files
int r_index=0, theta_index=0;
float buffer=0;
float *dens_unprc=NULL,*vel_r_unprc=NULL, *vel_theta_unprc=NULL,*pres_unprc=NULL;
double ph_rmin=0, ph_rmax=0;
double r_in=1e10;
//double *r_edge=malloc(sizeof(double)*(R_DIM_2D+1));
//double *dr=malloc(sizeof(double)*(R_DIM_2D));
double *r_unprc=malloc(sizeof(double)*R_DIM_2D);
double *theta_unprc=malloc(sizeof(double)*THETA_DIM_2D);
if (ph_inj_switch==0)
{
ph_rmin=min_r;
ph_rmax=max_r;
}
snprintf(file_end,sizeof(file_end),"%s","small.data" );
//density
snprintf(hydrofile,sizeof(hydrofile),"%s%s%d%s",hydro_prefix,"u0", 1,"-" );
modifyFlashName(file_num, hydrofile, frame,0);
fprintf(fPtr,">> Opening file %s\n", file_num);
fflush(fPtr);
snprintf(full_file, sizeof(full_file), "%s%s", file_num, file_end);
hydroPtr=fopen(full_file, "rb");
fread(&buffer, sizeof(float), 1,hydroPtr); //random stuff about the file from fortran
fread(&all_index_buffer, sizeof(int)*1, 1,hydroPtr); //min and max indexes for the grid
fread(&all_index_buffer, sizeof(int)*1, 1,hydroPtr);
fread(&theta_min_index, sizeof(int)*1, 1,hydroPtr);
fread(&theta_max_index, sizeof(int)*1, 1,hydroPtr);
fread(&r_min_index, sizeof(int)*1, 1,hydroPtr);
fread(&r_max_index, sizeof(int)*1, 1,hydroPtr);
fclose(hydroPtr);
//fortran indexing starts @ 1, but C starts @ 0
r_min_index--;//=r_min_index-1;
r_max_index--;//=r_max_index-1;
theta_min_index--;//=theta_min_index-1;
theta_max_index--;//=theta_max_index-1;
elem=(r_max_index+1-r_min_index)*(theta_max_index+1-theta_min_index); //max index is max number of elements minus 1, there add one to get total number of elements
fprintf(fPtr,"Elem %d\n", elem);
fprintf(fPtr,"Limits %d, %d, %d, %d, %d, %d\n", all_index_buffer, all_index_buffer, theta_min_index, theta_max_index, r_min_index, r_max_index);
fflush(fPtr);
//now with number of elements allocate data
dens_unprc=malloc(elem*sizeof(float));
vel_r_unprc=malloc(elem*sizeof(float));
vel_theta_unprc=malloc(elem*sizeof(float));
pres_unprc=malloc(elem*sizeof(float));
hydroPtr=fopen(full_file, "rb");
fread(&buffer, sizeof(float), 1,hydroPtr); //random stuff about the file from fortran
fread(&all_index_buffer, sizeof(int)*1, 1,hydroPtr); //min and max indexes for the grid
fread(&all_index_buffer, sizeof(int)*1, 1,hydroPtr);
fread(&all_index_buffer, sizeof(int)*1, 1,hydroPtr); //min and max indexes for the grid
fread(&all_index_buffer, sizeof(int)*1, 1,hydroPtr);
fread(&all_index_buffer, sizeof(int)*1, 1,hydroPtr);
fread(&all_index_buffer, sizeof(int)*1, 1,hydroPtr);
fread(&buffer, sizeof(float), 1,hydroPtr); //random stuff about the file from fortran
fread(&buffer, sizeof(float), 1,hydroPtr); //random stuff about the file from fortran
/*
for (i=0;i<elem;i++)
{
fread((dens_unprc+i), sizeof(float),1, hydroPtr); //read data
}
*/
fread(dens_unprc, sizeof(float),elem, hydroPtr);
fclose(hydroPtr);
//V_r
snprintf(hydrofile,sizeof(hydrofile),"%s%s%d%s",hydro_prefix,"u0", 2,"-" );
modifyFlashName(file_num, hydrofile, frame,0);
snprintf(full_file, sizeof(full_file), "%s%s", file_num, file_end);
hydroPtr=fopen(full_file, "rb");
fread(&buffer, sizeof(float), 1,hydroPtr); //random stuff about the file from fortran
fread(&all_index_buffer, sizeof(int)*1, 1,hydroPtr); //min and max indexes for the grid
fread(&all_index_buffer, sizeof(int)*1, 1,hydroPtr);
fread(&all_index_buffer, sizeof(int)*1, 1,hydroPtr); //min and max indexes for the grid
fread(&all_index_buffer, sizeof(int)*1, 1,hydroPtr);
fread(&all_index_buffer, sizeof(int)*1, 1,hydroPtr);
fread(&all_index_buffer, sizeof(int)*1, 1,hydroPtr);
fread(&buffer, sizeof(float), 1,hydroPtr); //random stuff about the file from fortran
fread(&buffer, sizeof(float), 1,hydroPtr); //random stuff about the file from fortran
fread(vel_r_unprc, sizeof(float),elem, hydroPtr); //data
fclose(hydroPtr);
//V_theta
snprintf(hydrofile,sizeof(hydrofile),"%s%s%d%s",hydro_prefix,"u0", 3,"-" );
modifyFlashName(file_num, hydrofile, frame,0);
snprintf(full_file, sizeof(full_file), "%s%s", file_num, file_end);
hydroPtr=fopen(full_file, "rb");
fread(&buffer, sizeof(float), 1,hydroPtr); //random stuff about the file from fortran
fread(&all_index_buffer, sizeof(int)*1, 1,hydroPtr); //min and max indexes for the grid
fread(&all_index_buffer, sizeof(int)*1, 1,hydroPtr);
fread(&all_index_buffer, sizeof(int)*1, 1,hydroPtr); //min and max indexes for the grid
fread(&all_index_buffer, sizeof(int)*1, 1,hydroPtr);
fread(&all_index_buffer, sizeof(int)*1, 1,hydroPtr);
fread(&all_index_buffer, sizeof(int)*1, 1,hydroPtr);
fread(&buffer, sizeof(float), 1,hydroPtr); //random stuff about the file from fortran
fread(&buffer, sizeof(float), 1,hydroPtr); //random stuff about the file from fortran
fread(vel_theta_unprc, sizeof(float), elem, hydroPtr); //data
fclose(hydroPtr);
//u04 is phi component but is all 0
//pres
snprintf(hydrofile,sizeof(hydrofile),"%s%s%d%s",hydro_prefix,"u0", 8,"-" );
modifyFlashName(file_num, hydrofile, frame,0);
snprintf(full_file, sizeof(full_file), "%s%s", file_num, file_end);
//fprintf(fPtr,">> Opening file %s\n", full_file);
//fflush(fPtr);
hydroPtr=fopen(full_file, "rb");
fread(&buffer, sizeof(float), 1,hydroPtr); //random stuff about the file from fortran
fread(&all_index_buffer, sizeof(int)*1, 1,hydroPtr); //min and max indexes for the grid
fread(&all_index_buffer, sizeof(int)*1, 1,hydroPtr);
fread(&all_index_buffer, sizeof(int)*1, 1,hydroPtr); //min and max indexes for the grid
fread(&all_index_buffer, sizeof(int)*1, 1,hydroPtr);
fread(&all_index_buffer, sizeof(int)*1, 1,hydroPtr);
fread(&all_index_buffer, sizeof(int)*1, 1,hydroPtr);
fread(&buffer, sizeof(float), 1,hydroPtr); //random stuff about the file from fortran
fread(&buffer, sizeof(float), 1,hydroPtr); //random stuff about the file from fortran
//elem=(r_max_index-r_min_index)*(theta_max_index-theta_min_index);
//fprintf(fPtr,"Elem %d\n", elem);
//fprintf(fPtr,"Limits %d, %d, %d, %d, %d, %d\n", all_index_buffer, all_index_buffer, theta_min_index, theta_max_index, r_min_index, r_max_index);
//fflush(fPtr);
fread(pres_unprc, sizeof(float),elem, hydroPtr); //data
fclose(hydroPtr);
/*
for (j=0 ;j<(theta_max_index+1-theta_min_index); j++)
{
for (k=0; k<(r_max_index+1-r_min_index); k++)
{
fprintf(fPtr,"Pres %d: %e\n", ( j*(r_max_index+1-r_min_index)+k ), *(pres_unprc+( j*(r_max_index+1-r_min_index)+k )));
//fprintf(fPtr,"Pres %d: %e\n", ( j*(r_max_index)+k ), *(pres_unprc+( j*(r_max_index)+k )));
fflush(fPtr);
}
}
exit(0);
*/
//R
snprintf(hydrofile,sizeof(hydrofile),"%s%s",hydro_prefix,"grid-x1.data" );
hydroPtr=fopen(hydrofile, "r");
//fprintf(fPtr,">> Opening file %s\n", hydrofile);
//fflush(fPtr);
i=0;
while (i<R_DIM_2D)
{
fscanf(hydroPtr, "%lf", (r_unprc+i)); //read value
fgets(buf, 3,hydroPtr); //read comma
/*
if (i<5)
{
//printf("Here\n");
fprintf(fPtr,"R %d: %e\n", i, *(r_unprc+i));
fflush(fPtr);
}
*/
i++;
}
fclose(hydroPtr);
//theta from y axis
snprintf(hydrofile,sizeof(hydrofile),"%s%s",hydro_prefix,"grid-x2.data" );
hydroPtr=fopen(hydrofile, "r");
//fprintf(fPtr,">> Opening file %s\n", hydrofile);
//fflush(fPtr);
i=0;
while (i<THETA_DIM_2D)
{
fscanf(hydroPtr, "%lf", (theta_unprc+i)); //read value
fgets(buf, 3,hydroPtr); //read comma
/*
if (i<5)
{
fprintf(fPtr,"Theta %d: %e\n", i, *(theta_unprc+i));
fflush(fPtr);
}
*/
i++;
}
fclose(hydroPtr);
//limit number of array elements
//fill in radius array and find in how many places r > injection radius
elem_factor=0;
elem=0;
while (elem==0)
{
elem_factor++;
elem=0;
for (j=0 ;j<(theta_max_index+1-theta_min_index); j++)
{
for (k=0; k<(r_max_index+1-r_min_index); k++)
{
i=r_min_index+k; //look at indexes of r that are included in small hydro file
//if I have photons do selection differently than if injecting photons
if (ph_inj_switch==0)
{
//if calling this function when propagating photons, choose blocks based on where the photons are
if (((ph_rmin - elem_factor*C_LIGHT/fps)<(*(r_unprc+i))) && (*(r_unprc+i) < (ph_rmax + elem_factor*C_LIGHT/fps) ))
{
// *(pres_unprc+(i*R_DIM*THETA_DIM + j*R_DIM + k )
elem++;
}
}
else
{
//if calling this function to inject photons choose blocks based on injection parameters, r_inj, which is sufficient
if (((r_inj - C_LIGHT/fps)<(*(r_unprc+i))) && (*(r_unprc+i) < (r_inj + C_LIGHT/fps) ))
{
// *(pres_unprc+(i*R_DIM*THETA_DIM + j*R_DIM + k )
elem++;
}
}
}
}
}
fprintf(fPtr, "Number of post restricted Elems: %d %e\n", elem, r_inj);
fflush(fPtr);
(*pres)=malloc (elem * sizeof (double ));
(*velx)=malloc (elem * sizeof (double ));
(*vely)=malloc (elem * sizeof (double ));
(*dens)=malloc (elem * sizeof (double ));
(*x)=malloc (elem * sizeof (double ));
(*y)=malloc (elem * sizeof (double ));
(*r)=malloc (elem * sizeof (double ));
(*theta)=malloc (elem * sizeof (double ));
(*gamma)=malloc (elem * sizeof (double ));
(*dens_lab)=malloc (elem * sizeof (double ));
//szx becomes delta r szy becomes delta theta
(*szx)=malloc (elem * sizeof (double ));
(*szy)=malloc (elem * sizeof (double ));
(*temp)=malloc (elem * sizeof (double ));
elem=0;
for (j=0 ;j<(theta_max_index+1-theta_min_index); j++)
{
for (k=0; k<(r_max_index+1-r_min_index); k++)
{
r_index=r_min_index+k; //look at indexes of r that are included in small hydro file
theta_index=theta_min_index+j;
if (ph_inj_switch==0)
{
if (((ph_rmin - elem_factor*C_LIGHT/fps)<(*(r_unprc+r_index))) && (*(r_unprc+r_index) < (ph_rmax + elem_factor*C_LIGHT/fps) ))
{
(*pres)[elem]=*(pres_unprc+( j*(r_max_index+1-r_min_index)+k ));
(*velx)[elem]=(*(vel_r_unprc+( j*(r_max_index+1-r_min_index)+k )))*sin(*(theta_unprc+theta_index))+(*(vel_theta_unprc+( j*(r_max_index+1-r_min_index)+k )))*cos(*(theta_unprc+theta_index));
(*vely)[elem]=(*(vel_r_unprc+( j*(r_max_index+1-r_min_index)+k )))*cos(*(theta_unprc+theta_index))-(*(vel_theta_unprc+( j*(r_max_index+1-r_min_index)+k )))*sin(*(theta_unprc+theta_index));
(*dens)[elem]=*(dens_unprc+( j*(r_max_index+1-r_min_index)+k ));
(*x)[elem]=(*(r_unprc+r_index))*sin(*(theta_unprc+theta_index));
(*y)[elem]=(*(r_unprc+r_index))*cos(*(theta_unprc+theta_index));
(*r)[elem]=*(r_unprc+r_index);
(*szx)[elem]=(*(r_unprc+r_index))*((M_PI/2)/2000);
(*szy)[elem]=(M_PI/2)/2000;
(*theta)[elem]=*(theta_unprc+theta_index);//theta in radians in relation to jet axis
(*gamma)[elem]=pow(pow(1.0-(pow(*(vel_r_unprc+( j*(r_max_index+1-r_min_index)+k )),2)+pow(*(vel_theta_unprc+( j*(r_max_index+1-r_min_index)+k )),2)),0.5),-1); //v is in units of c
(*dens_lab)[elem]= (*(dens_unprc+( j*(r_max_index+1-r_min_index)+k ))) * pow(pow(1.0-(pow(*(vel_r_unprc+( j*(r_max_index+1-r_min_index)+k )),2)+pow(*(vel_theta_unprc+( j*(r_max_index+1-r_min_index)+k )),2)),0.5),-1);
(*temp)[elem]=pow(3*(*(pres_unprc+( j*(r_max_index+1-r_min_index)+k )))*pow(C_LIGHT,2.0)/(A_RAD) ,1.0/4.0);
elem++;
}
}
else
{
if (((r_inj - C_LIGHT/fps)<(*(r_unprc+r_index))) && (*(r_unprc+r_index) < (r_inj + C_LIGHT/fps) ))
{
(*pres)[elem]=*(pres_unprc+( j*(r_max_index+1-r_min_index)+k ));
(*velx)[elem]=(*(vel_r_unprc+( j*(r_max_index+1-r_min_index)+k )))*sin(*(theta_unprc+theta_index))+(*(vel_theta_unprc+( j*(r_max_index+1-r_min_index)+k )))*cos(*(theta_unprc+theta_index));
(*vely)[elem]=(*(vel_r_unprc+( j*(r_max_index+1-r_min_index)+k )))*cos(*(theta_unprc+theta_index))-(*(vel_theta_unprc+( j*(r_max_index+1-r_min_index)+k )))*sin(*(theta_unprc+theta_index));
(*dens)[elem]=*(dens_unprc+( j*(r_max_index+1-r_min_index)+k ));
(*x)[elem]=(*(r_unprc+r_index))*sin(*(theta_unprc+theta_index));
(*y)[elem]=(*(r_unprc+r_index))*cos(*(theta_unprc+theta_index));
(*r)[elem]=*(r_unprc+r_index);
(*szx)[elem]=(*(r_unprc+r_index))*((M_PI/2)/2000);
(*szy)[elem]=(M_PI/2)/2000;
(*theta)[elem]=*(theta_unprc+theta_index);//theta in radians in relation to jet axis
(*gamma)[elem]=pow(pow(1.0-(pow(*(vel_r_unprc+( j*(r_max_index+1-r_min_index)+k )),2)+pow(*(vel_theta_unprc+( j*(r_max_index+1-r_min_index)+k )),2)),0.5),-1); //v is in units of c
(*dens_lab)[elem]= (*(dens_unprc+( j*(r_max_index+1-r_min_index)+k ))) * pow(pow(1.0-(pow(*(vel_r_unprc+( j*(r_max_index+1-r_min_index)+k )),2)+pow(*(vel_theta_unprc+( j*(r_max_index+1-r_min_index)+k )),2)),0.5),-1);
(*temp)[elem]=pow(3*(*(pres_unprc+( j*(r_max_index+1-r_min_index)+k )))*pow(C_LIGHT,2.0)/(A_RAD) ,1.0/4.0);
elem++;
}
}
}
}
(*number)=elem;
//fprintf(fPtr, "Number of post restricted Elems: %d %e\n", elem, r_inj);
//fflush(fPtr);
free(pres_unprc); //works when not being freed?
//fprintf(fPtr, "pres Done\n\n");
//fflush(fPtr);
free(vel_r_unprc);
//fprintf(fPtr, "vel_r Done\n\n");
//fflush(fPtr);
free(vel_theta_unprc);
//fprintf(fPtr, "vel_theta Done\n\n");
//fflush(fPtr);
free(dens_unprc);
//fprintf(fPtr, "dens Done\n\n");
//fflush(fPtr);
free(r_unprc);
//fprintf(fPtr, "r Done\n\n");
//fflush(fPtr);
free(theta_unprc);
//fprintf(fPtr, "theta Done\n\n");
//fflush(fPtr);
pres_unprc=NULL;
vel_r_unprc=NULL;
vel_theta_unprc=NULL;
dens_unprc=NULL;
r_unprc=NULL;
theta_unprc=NULL;
//fprintf(fPtr, "ALL Done\n\n");
//fflush(fPtr);
}
|
axpy_ompacc.c | // Experimental test input for Accelerator directives
// simplest scalar*vector operations
// Liao 1/15/2013
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <string.h>
/* change this to do saxpy or daxpy : single precision or double precision*/
#define REAL double
#define VEC_LEN 1024000 //use a fixed number for now
/* zero out the entire vector */
void zero(REAL *A, int n)
{
int i;
for (i = 0; i < n; i++) {
A[i] = 0.0;
}
}
/* initialize a vector with random floating point numbers */
void init(REAL *A, int n)
{
int i;
for (i = 0; i < n; i++) {
A[i] = (double)drand48();
}
}
/*serial version */
void axpy(REAL* x, REAL* y, long n, REAL a) {
int i;
for (i = 0; i < n; ++i)
{
y[i] += a * x[i];
}
}
/* compare two arrays and return percentage of difference */
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;
}
void axpy_ompacc(REAL* x, REAL* y, int n, REAL a) {
int i;
/* this one defines both the target device name and data environment to map to,
I think here we need mechanism to tell the compiler the device type (could be multiple) so that compiler can generate the codes of different versions;
we also need to let the runtime know what the target device is so the runtime will chose the right function to call if the code are generated
#pragma omp target device (gpu0) map(x, y)
*/
#pragma omp target device (0) map(tofrom: y[0:n]) map(to: x[0:n],a,n)
#pragma omp parallel for shared(x, y, n, a) private(i)
for (i = 0; i < n; ++i)
y[i] += a * x[i];
}
int main(int argc, char *argv[])
{
int n;
REAL *y_ompacc, *y, *x;
REAL a = 123.456;
n = VEC_LEN;
y_ompacc = (REAL *) malloc(n * sizeof(REAL));
y = (REAL *) malloc(n * sizeof(REAL));
x = (REAL *) malloc(n * sizeof(REAL));
srand48(1<<12);
init(x, n);
init(y_ompacc, n);
memcpy(y, y_ompacc, n*sizeof(REAL));
axpy(x, y, n, a);
/* openmp acc version */
axpy_ompacc(x, y_ompacc, n, a);
REAL checkresult = check(y_ompacc, y, n);
printf("axpy(%d): checksum: %g\n", n, checkresult);
assert (checkresult < 1.0e-10);
free(y_ompacc);
free(y);
free(x);
return 0;
}
|
nodes.c | #include "nodes.h"
#include "../../../comms.h"
#include "../../../profiler.h"
#include "../../nodes_data.h"
#include "../../nodes_interface.h"
#include <assert.h>
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
// Solve the unstructured diffusion problem
void solve_unstructured_diffusion_2d(
const int nx, const int ny, const int pad, Mesh* mesh,
NodesMesh* nmesh, const int max_inners, const double dt,
const double heat_capacity, const double conductivity, double* temperature,
double* b, double* r, double* p, double* rho, double* Ap, int* end_niters,
double* end_error, double* reduce_array) {
// Store initial residual
calculate_rhs(
nx, ny, pad, heat_capacity, conductivity, dt, nmesh->volume,
rho, temperature, b, nmesh->edge_vertex0,
nmesh->edge_vertex1, nmesh->cell_centroids_x,
nmesh->cell_centroids_y, nmesh->vertices_x,
nmesh->vertices_y, nmesh->cells_edges,
nmesh->edges_cells);
double local_old_r2 = initialise_cg(
nx, ny, pad, dt, conductivity, heat_capacity, p, r, temperature,
nmesh->volume, b, rho, nmesh->cells_edges,
nmesh->edge_vertex0, nmesh->edge_vertex1,
nmesh->vertices_x, nmesh->vertices_y,
nmesh->cell_centroids_x, nmesh->cell_centroids_y,
nmesh->edges_cells);
double global_old_r2 = reduce_all_sum(local_old_r2);
handle_boundary_2d(nx, ny, mesh, p, NO_INVERT, PACK);
handle_boundary_2d(nx, ny, mesh, temperature, NO_INVERT, PACK);
// TODO: Can one of the allreduces be removed with kernel fusion?
int ii = 0;
for (ii = 0; ii < max_inners; ++ii) {
const double local_pAp = calculate_pAp(
nx, ny, pad, p, Ap, dt, conductivity, heat_capacity, temperature,
nmesh->volume, rho, nmesh->cells_edges,
nmesh->edge_vertex0, nmesh->edge_vertex1,
nmesh->vertices_x, nmesh->vertices_y,
nmesh->cell_centroids_x,
nmesh->cell_centroids_y, nmesh->edges_cells);
const double global_pAp = reduce_all_sum(local_pAp);
const double alpha = global_old_r2 / global_pAp;
const double local_new_r2 =
calculate_new_r2(nx, ny, pad, alpha, temperature, p, r, Ap);
const double global_new_r2 = reduce_all_sum(local_new_r2);
const double beta = global_new_r2 / global_old_r2;
handle_boundary_2d(nx, ny, mesh, temperature, NO_INVERT, PACK);
// Check if the solution has converged
if (fabs(global_new_r2) < EPS) {
global_old_r2 = global_new_r2;
break;
}
update_conjugate(nx, ny, pad, beta, r, p);
handle_boundary_2d(nx, ny, mesh, p, NO_INVERT, PACK);
// Store the old squared residual
global_old_r2 = global_new_r2;
}
*end_niters = ii;
*end_error = global_old_r2;
}
// Calculate the RHS including the unstructured correction term
void calculate_rhs(const int nx, const int ny, const int pad,
const double heat_capacity, const double conductivity,
const double dt, const double* volume, const double* rho,
const double* temperature, double* b,
const int* edge_vertex0, const int* edge_vertex1,
const double* cell_centroids_x,
const double* cell_centroids_y, const double* vertices_x,
const double* vertices_y, const int* cells_edges,
const int* edges_cells) {
/*
Note here that the temperature is the guessed temperature.
*/
// Find the RHS that includes the unstructured mesh correction
#pragma omp parallel for
for (int ii = pad; ii < ny - pad; ++ii) {
#pragma omp simd
for (int jj = pad; jj < nx - pad; ++jj) {
// Fetch the cell centered values
const int cell_index = (ii)*nx + (jj);
const double density = rho[(cell_index)];
const double V = volume[(cell_index)];
// Calculate the cell centroids
const double cell_centroid_x = cell_centroids_x[(cell_index)];
const double cell_centroid_y = cell_centroids_y[(cell_index)];
/*
* Performing least squares approximation to get unknown d
* d = [ dphi/dx, dphi/dy ]
* M = [ (dx0, dx1 ..., dx_ff) (dy0, dy1, ..., dy_ff) ]
* del(phi) = [ phi1-phi0, phi2-phi0, ..., phi_ff-phi0 ]
* d = (M^T.M)^(-1).(M^T).del(phi)
*/
// Calculate the coefficents to matrix M
double MTM[3] = {0.0}; // Describes the three unique quantities in (M^T.M)
double MT_del_phi[2] = {0.0};
double coeff[2] = {0.0};
// Calculate the coefficients for all edges
for (int ee = 0; ee < NEDGES; ++ee) {
const int edge_index = cells_edges[(ee)*nx * ny + (cell_index)];
const int neighbour_index =
(edges_cells[edge_index * NCELLS_PER_EDGE] == cell_index)
? edges_cells[edge_index * NCELLS_PER_EDGE + 1]
: edges_cells[edge_index * NCELLS_PER_EDGE];
// Calculate the vector pointing between the cell centroids
double es_x = (cell_centroids_x[(neighbour_index)] - cell_centroid_x);
double es_y = (cell_centroids_y[(neighbour_index)] - cell_centroid_y);
const double centroid_distance = sqrt(es_x * es_x + es_y * es_y);
es_x /= centroid_distance;
es_y /= centroid_distance;
// Calculate the edge differentials
const int vertex0 = edge_vertex0[(edge_index)];
const int vertex1 = edge_vertex1[(edge_index)];
// Calculate the area vector, even though vertices aren't ordered well
double A_x = (vertices_y[vertex1] - vertices_y[vertex0]);
double A_y = -(vertices_x[vertex1] - vertices_x[vertex0]);
if ((A_x * es_x + A_y * es_y) < 0.0) {
A_x = -A_x;
A_y = -A_y;
}
// Calculate the gradient matrix
const double phi0 = temperature[(cell_index)];
const double phi_ff = temperature[(neighbour_index)];
MTM[0] += es_x * es_x;
MTM[1] += es_x * es_y;
MTM[2] += es_y * es_y;
MT_del_phi[0] += es_x * (phi_ff - phi0);
MT_del_phi[1] += es_y * (phi_ff - phi0);
// Calculate the coefficients of transformed shape
const double density1 = rho[(neighbour_index)];
const double edge_density =
(2.0 * density * density1) / (density + density1);
const double diffusion_coeff =
conductivity / (edge_density * heat_capacity);
const double gam = (A_x * A_x + A_y * A_y) / (A_x * es_x + A_y * es_y);
coeff[0] += diffusion_coeff * (A_x - es_x * gam);
coeff[1] += diffusion_coeff * (A_y - es_y * gam);
}
// Solve the equation for the temperature gradients
const double MTM_det = (1.0 / (MTM[0] * MTM[2] - MTM[1] * MTM[1]));
const double temp_grad_cell_x =
MTM_det * (MT_del_phi[0] * MTM[2] - MT_del_phi[1] * MTM[1]);
const double temp_grad_cell_y =
MTM_det * (MT_del_phi[1] * MTM[0] - MT_del_phi[0] * MTM[1]);
// TODO: SHOULD THERE BE A COEFFICIENT FOR TAU?
const double tau =
temp_grad_cell_x * coeff[0] + temp_grad_cell_y * coeff[1];
b[(cell_index)] = temperature[(cell_index)] + (dt / (density * V)) * tau;
}
}
}
// Initialises the CG solver
double initialise_cg(const int nx, const int ny, const int pad, const double dt,
const double conductivity, const double heat_capacity,
double* p, double* r, const double* temperature,
const double* volume, const double* b, const double* rho,
const int* cells_edges, const int* edge_vertex0,
const int* edge_vertex1, const double* vertices_x,
const double* vertices_y, const double* cell_centroids_x,
const double* cell_centroids_y, const int* edges_cells) {
START_PROFILING(&compute_profile);
// Going to initialise the coefficients here. This ensures that if the
// density or mesh were changed by another package, that the coefficients
// are updated accordingly, making performance evaluation fairer.
double initial_r2 = 0.0;
#pragma omp parallel for reduction(+ : initial_r2)
for (int ii = pad; ii < ny - pad; ++ii) {
#pragma omp simd
for (int jj = pad; jj < nx - pad; ++jj) {
const int cell_index = (ii)*nx + (jj);
const double density = rho[(cell_index)];
const double V = volume[(cell_index)];
// Calculate the cell centroids
const double cell_centroid_x = cell_centroids_x[(cell_index)];
const double cell_centroid_y = cell_centroids_y[(cell_index)];
double neighbour_coeff_total = 0.0;
double neighbour_contribution = 0.0;
for (int ee = 0; ee < NEDGES; ++ee) {
const int edge_index = cells_edges[(ee)*nx * ny + (cell_index)];
const int neighbour_index =
(edges_cells[edge_index * NCELLS_PER_EDGE] == cell_index)
? edges_cells[edge_index * NCELLS_PER_EDGE + 1]
: edges_cells[edge_index * NCELLS_PER_EDGE];
// Calculate the unit vector pointing between the cell centroids
double es_x = (cell_centroids_x[(neighbour_index)] - cell_centroid_x);
double es_y = (cell_centroids_y[(neighbour_index)] - cell_centroid_y);
const double centroid_distance = sqrt(es_x * es_x + es_y * es_y);
es_x /= centroid_distance;
es_y /= centroid_distance;
// Calculate the edge differentials
const int vertex0 = edge_vertex0[(edge_index)];
const int vertex1 = edge_vertex1[(edge_index)];
// Calculate the area vector, even though vertices aren't ordered well
double A_x = (vertices_y[vertex1] - vertices_y[vertex0]);
double A_y = -(vertices_x[vertex1] - vertices_x[vertex0]);
if ((A_x * es_x + A_y * es_y) < 0.0) {
A_x = -A_x;
A_y = -A_y;
}
// Calculate the diffusion coefficient
const double edge_density = (2.0 * density * rho[(neighbour_index)]) /
(density + rho[(neighbour_index)]);
const double diffusion_coeff =
conductivity / (edge_density * heat_capacity);
const double neighbour_coeff =
(dt * diffusion_coeff * (A_x * A_x + A_y * A_y)) /
(V * centroid_distance * (A_x * es_x + A_y * es_y));
neighbour_contribution +=
temperature[(neighbour_index)] * neighbour_coeff;
neighbour_coeff_total += neighbour_coeff;
}
r[(cell_index)] = b[(cell_index)] - ((neighbour_coeff_total + 1.0) *
temperature[(cell_index)] -
neighbour_contribution);
p[(cell_index)] = r[(cell_index)];
initial_r2 += r[(cell_index)] * r[(cell_index)];
}
}
STOP_PROFILING(&compute_profile, "initialise cg");
return initial_r2;
}
// Calculates a value for alpha
double calculate_pAp(const int nx, const int ny, const int pad, double* p,
double* Ap, const double dt, const double conductivity,
const double heat_capacity, const double* temperature,
const double* volume, const double* rho,
const int* cells_edges, const int* edge_vertex0,
const int* edge_vertex1, const double* vertices_x,
const double* vertices_y, const double* cell_centroids_x,
const double* cell_centroids_y, const int* edges_cells) {
START_PROFILING(&compute_profile);
double pAp = 0.0;
#pragma omp parallel for reduction(+ : pAp)
for (int ii = pad; ii < ny - pad; ++ii) {
#pragma omp simd
for (int jj = pad; jj < nx - pad; ++jj) {
const int cell_index = (ii)*nx + (jj);
const double density = rho[(cell_index)];
const double V = volume[(cell_index)];
// Calculate the cell centroids
const double cell_centroid_x = cell_centroids_x[(cell_index)];
const double cell_centroid_y = cell_centroids_y[(cell_index)];
double neighbour_coeff_total = 0.0;
double neighbour_contribution = 0.0;
for (int ee = 0; ee < NEDGES; ++ee) {
const int edge_index = cells_edges[(ee)*nx * ny + (cell_index)];
const int neighbour_index =
(edges_cells[edge_index * NCELLS_PER_EDGE] == cell_index)
? edges_cells[edge_index * NCELLS_PER_EDGE + 1]
: edges_cells[edge_index * NCELLS_PER_EDGE];
// Calculate the unit vector pointing between the cell centroids
double es_x = (cell_centroids_x[(neighbour_index)] - cell_centroid_x);
double es_y = (cell_centroids_y[(neighbour_index)] - cell_centroid_y);
const double centroid_distance = sqrt(es_x * es_x + es_y * es_y);
es_x /= centroid_distance;
es_y /= centroid_distance;
// Calculate the edge differentials
const int vertex0 = edge_vertex0[(edge_index)];
const int vertex1 = edge_vertex1[(edge_index)];
// Calculate the area vector, even though vertices aren't ordered well
double A_x = (vertices_y[vertex1] - vertices_y[vertex0]);
double A_y = -(vertices_x[vertex1] - vertices_x[vertex0]);
if ((A_x * es_x + A_y * es_y) < 0.0) {
A_x = -A_x;
A_y = -A_y;
}
// Calculate the diffusion coefficient
const double edge_density = (2.0 * density * rho[(neighbour_index)]) /
(density + rho[(neighbour_index)]);
const double diffusion_coeff =
conductivity / (edge_density * heat_capacity);
const double neighbour_coeff =
(dt * diffusion_coeff * (A_x * A_x + A_y * A_y)) /
(V * centroid_distance * (A_x * es_x + A_y * es_y));
neighbour_contribution += p[(neighbour_index)] * neighbour_coeff;
neighbour_coeff_total += neighbour_coeff;
}
Ap[(cell_index)] = ((neighbour_coeff_total + 1.0) * p[(cell_index)] -
neighbour_contribution);
pAp += p[(cell_index)] * Ap[(cell_index)];
}
}
STOP_PROFILING(&compute_profile, "calculate alpha");
return pAp;
}
// Updates the current guess using the calculated alpha
double calculate_new_r2(const int nx, const int ny, const int pad, double alpha,
double* temperature, double* p, double* r, double* Ap) {
START_PROFILING(&compute_profile);
double new_r2 = 0.0;
for (int ii = pad; ii < ny - pad; ++ii) {
for (int jj = pad; jj < nx - pad; ++jj) {
temperature[(ii)*nx + (jj)] += alpha * p[(ii)*nx + (jj)];
r[(ii)*nx + (jj)] -= alpha * Ap[(ii)*nx + (jj)];
new_r2 += r[(ii)*nx + (jj)] * r[(ii)*nx + (jj)];
}
}
STOP_PROFILING(&compute_profile, "calculate new r2");
return new_r2;
}
// Updates the conjugate from the calculated beta and residual
void update_conjugate(const int nx, const int ny, const int pad,
const double beta, const double* r, double* p) {
START_PROFILING(&compute_profile);
for (int ii = pad; ii < ny - pad; ++ii) {
for (int jj = pad; jj < nx - pad; ++jj) {
p[(ii)*nx + (jj)] = r[(ii)*nx + (jj)] + beta * p[(ii)*nx + (jj)];
}
}
STOP_PROFILING(&compute_profile, "update conjugate");
}
|
pmmomp.c | #include <stdio.h>
#include <stdlib.h>
#ifdef _OPENMP
#include <omp.h>
#endif
#include <string.h>
void printMatriz (int n, int **m) {
int i, j;
for (i=0; i<n; i++) {
for (j=0; j<n; j++)
printf("%d ", m[i][j]);
printf("\n");
}
}
int main(int argc, char const *argv[]) {
if (argc < 2) {
fprintf(stderr, "ERROR: falta numero de filas y columnas\n");
exit(1);
}
unsigned n, i, j, k;
n = strtol(argv[1], NULL, 10);
int **a, **b, **c;
a = (int **) malloc(n*sizeof(int*));
b = (int **) malloc(n*sizeof(int*));
c = (int **) malloc(n*sizeof(int*));
for (i=0; i<n; i++) {
a[i] = (int *) malloc(n*sizeof(int));
b[i] = (int *) malloc(n*sizeof(int));
c[i] = (int *) malloc(n*sizeof(int));
}
// Inicializacion
#pragma omp parallel for private(j)
for (i=0; i<n; i++) {
for (j=0; j<n; j++) {
a[i][j] = 0;
b[i][j] = /*i+1*/1;
c[i][j] = /*j+1*/2;
}
}
// Multiplicacion
double start, end, tiempo;
start = omp_get_wtime();
#pragma omp parallel for private(k,j)
for (i=0; i<n; i++)
for (j=0; j<n; j++)
for (k=0; k<n; k++)
a[i][j] += b[i][k] * c[k][j];
end = omp_get_wtime();
tiempo = end - start;
if (n < 15) {
printf("M1:\n");
printMatriz(n, b);
printf("M2:\n");
printMatriz(n, c);
printf("Sol:\n");
printMatriz(n, a);
}
else
printf("Tiempo = %11.9f\t Primera = %d\t Ultima=%d\n",tiempo,a[0][0],a[n-1][n-1]);
return 0;
}
|
distributed_sort.c | #include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <math.h>
#define AROW 3
#define ACOL 10000
#define MAX_VALUE 10
int compare_ints (const void *a, const void *b) {
const int *da = (const int *) a;
const int *db = (const int *) b;
return (*da > *db) - (*da < *db);
}
int* sort(int* row) {
qsort(row, ACOL, sizeof(int), compare_ints);
return row;
}
void merge(int m, int n, int k, int A[], int B[], int C[]) {
int i = 0, j = 0, p;
while (i < m && j < n) {
if (A[i] <= B[j]) {
C[k] = A[i];
i++;
} else {
C[k] = B[j];
j++;
}
k++;
}
if (i < m) {
for (p = i; p < m; p++) {
C[k] = A[p];
k++;
}
} else {
for (p = j; p < n; p++) {
C[k] = B[p];
k++;
}
}
}
int* sort_full(int** a) {
int* C = (int*) malloc(sizeof(int) * AROW * ACOL);
int N = AROW * ACOL;
int i;
for (i = 0; i < AROW; i++) {
merge(i * ACOL, ACOL, i * ACOL, C, a[i], C);
}
return C;
}
int main(int argc, char *argv[]) {
int a[AROW][ACOL];
int i, j;
struct timeval start, end;
srand(time(NULL));
for (i = 0; i < AROW; i++) {
for (j = 0; j < ACOL; j++) {
a[i][j] = rand() % MAX_VALUE;
}
}
gettimeofday(&start, NULL);
#pragma omp parallel for
for (i = 0; i < AROW; i++) {
sort(a[i]);
}
//sort_full(a);
gettimeofday(&end, NULL);
//for (i = 0; i < AROW; i++) {
// for (j = 0; j < ACOL; j++) {
// printf("%3d ", a[i][j]);
// }
// printf("\n");
//}
printf("\n");
long duration_ms = ((end.tv_sec - start.tv_sec) * 1000 + (end.tv_usec - start.tv_usec) / 1000.0);
printf("Time: %ld ms\n", duration_ms);
return 0;
}
|
GB_cast_array.c | //------------------------------------------------------------------------------
// GB_cast_array: typecast an array
//------------------------------------------------------------------------------
// SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2022, All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
//------------------------------------------------------------------------------
// Casts an input array Ax to an output array Cx with a different type. The
// two types are always different, so this does not need to handle user-defined
// types. The iso case is not handled; Ax and Cx must be the same size and no
// iso expansion is done.
#include "GB.h"
#ifndef GBCUDA_DEV
#include "GB_unop__include.h"
#endif
GB_PUBLIC
void GB_cast_array // typecast an array
(
GB_void *Cx, // output array
const GB_Type_code code1, // type code for Cx
GB_void *Ax, // input array
const GB_Type_code code2, // type code for Ax
const int8_t *restrict Ab, // bitmap for Ax
const int64_t anz, // number of entries in Cx and Ax
const int nthreads // number of threads to use
)
{
//--------------------------------------------------------------------------
// check inputs
//--------------------------------------------------------------------------
if (anz == 0 || Cx == Ax)
{
// if anz is zero: no work to do, and the Ax and Cx pointer may be NULL
// as well. If Cx and Ax are aliased, then no copy is needed.
return ;
}
ASSERT (Cx != NULL) ;
ASSERT (Ax != NULL) ;
ASSERT (anz > 0) ;
ASSERT (GB_code_compatible (code1, code2)) ;
ASSERT (code1 != code2) ;
ASSERT (code1 != GB_UDT_code) ;
//--------------------------------------------------------------------------
// typecast the array
//--------------------------------------------------------------------------
#ifndef GBCUDA_DEV
//----------------------------------------------------------------------
// define the worker for the switch factory
//----------------------------------------------------------------------
#define GB_unop_apply(zname,xname) \
GB (_unop_apply__identity ## zname ## xname)
#define GB_WORKER(ignore1,zname,ztype,xname,xtype) \
{ \
GrB_Info info = GB_unop_apply (zname,xname) \
((ztype *) Cx, (xtype *) Ax, Ab, anz, nthreads) ; \
if (info == GrB_SUCCESS) return ; \
} \
break ;
//----------------------------------------------------------------------
// launch the switch factory
//----------------------------------------------------------------------
#define GB_EXCLUDE_SAME_TYPES
#include "GB_2type_factory.c"
#endif
//--------------------------------------------------------------------------
// generic worker: only used for GBCUDA_DEV case
//--------------------------------------------------------------------------
int64_t csize = GB_code_size (code1, 0) ;
int64_t asize = GB_code_size (code2, 0) ;
GB_cast_function cast_A_to_C = GB_cast_factory (code1, code2) ;
int64_t p ;
#pragma omp parallel for num_threads(nthreads) schedule(static)
for (p = 0 ; p < anz ; p++)
{
if (!GBB (Ab, p)) continue ;
// Cx [p] = Ax [p]
cast_A_to_C (Cx +(p*csize), Ax +(p*asize), asize) ;
}
}
|
ft.c | /*--------------------------------------------------------------------
NAS Parallel Benchmarks 3.0 structured OpenMP C versions - FT
This benchmark is an OpenMP C version of the NPB FT 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/
--------------------------------------------------------------------*/
/*--------------------------------------------------------------------
Authors: D. Bailey
W. Saphir
OpenMP C version: S. Satoh
3.0 structure translation: M. Popov
--------------------------------------------------------------------*/
#include "../common/npb-C.h"
/* global variables */
#include "global.h"
/* function declarations */
static void evolve(dcomplex u0[NZ][NY][NX], dcomplex u1[NZ][NY][NX],
int t, int indexmap[NZ][NY][NX], int d[3]);
static void compute_initial_conditions(dcomplex u0[NZ][NY][NX], int d[3]);
static void ipow46(double a, int exponent, double *result);
static void setup(void);
static void compute_indexmap(int indexmap[NZ][NY][NX], int d[3]);
static void print_timers(void);
static void fft(int dir, dcomplex x1[NZ][NY][NX], dcomplex x2[NZ][NY][NX]);
static void cffts1(int is, int d[3], dcomplex x[NZ][NY][NX],
dcomplex xout[NZ][NY][NX],
dcomplex y0[NX][FFTBLOCKPAD],
dcomplex y1[NX][FFTBLOCKPAD]);
static void cffts2(int is, int d[3], dcomplex x[NZ][NY][NX],
dcomplex xout[NZ][NY][NX],
dcomplex y0[NX][FFTBLOCKPAD],
dcomplex y1[NX][FFTBLOCKPAD]);
static void cffts3(int is, int d[3], dcomplex x[NZ][NY][NX],
dcomplex xout[NZ][NY][NX],
dcomplex y0[NX][FFTBLOCKPAD],
dcomplex y1[NX][FFTBLOCKPAD]);
static void fft_init (int n);
static void cfftz (int is, int m, int n, dcomplex x[NX][FFTBLOCKPAD],
dcomplex y[NX][FFTBLOCKPAD]);
static void fftz2 (int is, int l, int m, int n, int ny, int ny1,
dcomplex u[NX], dcomplex x[NX][FFTBLOCKPAD],
dcomplex y[NX][FFTBLOCKPAD]);
static int ilog2(int n);
static void checksum(int i, dcomplex u1[NZ][NY][NX], int d[3]);
static void verify (int d1, int d2, int d3, int nt,
boolean *verified, char *class);
/*--------------------------------------------------------------------
c FT benchmark
c-------------------------------------------------------------------*/
int main(int argc, char **argv) {
/*c-------------------------------------------------------------------
c-------------------------------------------------------------------*/
int i, ierr;
/*------------------------------------------------------------------
c u0, u1, u2 are the main arrays in the problem.
c Depending on the decomposition, these arrays will have different
c dimensions. To accomodate all possibilities, we allocate them as
c one-dimensional arrays and pass them to subroutines for different
c views
c - u0 contains the initial (transformed) initial condition
c - u1 and u2 are working arrays
c - indexmap maps i,j,k of u0 to the correct i^2+j^2+k^2 for the
c time evolution operator.
c-----------------------------------------------------------------*/
/*--------------------------------------------------------------------
c Large arrays are in common so that they are allocated on the
c heap rather than the stack. This common block is not
c referenced directly anywhere else. Padding is to avoid accidental
c cache problems, since all array sizes are powers of two.
c-------------------------------------------------------------------*/
static dcomplex u0[NZ][NY][NX];
static dcomplex pad1[3];
static dcomplex u1[NZ][NY][NX];
static dcomplex pad2[3];
static dcomplex u2[NZ][NY][NX];
static dcomplex pad3[3];
static int indexmap[NZ][NY][NX];
int iter;
int nthreads = 1;
double total_time, mflops;
boolean verified;
char class;
/*--------------------------------------------------------------------
c Run the entire problem once to make sure all data is touched.
c This reduces variable startup costs, which is important for such a
c short benchmark. The other NPB 2 implementations are similar.
c-------------------------------------------------------------------*/
for (i = 0; i < T_MAX; i++) {
timer_clear(i);
}
setup();
compute_indexmap(indexmap, dims[2]);
compute_initial_conditions(u1, dims[0]);
fft_init (dims[0][0]);
fft(1, u1, u0);
/*--------------------------------------------------------------------
c Start over from the beginning. Note that all operations must
c be timed, in contrast to other benchmarks.
c-------------------------------------------------------------------*/
for (i = 0; i < T_MAX; i++) {
timer_clear(i);
}
timer_start(T_TOTAL);
if (TIMERS_ENABLED == TRUE) timer_start(T_SETUP);
compute_indexmap(indexmap, dims[2]);
compute_initial_conditions(u1, dims[0]);
fft_init (dims[0][0]);
if (TIMERS_ENABLED == TRUE) {
timer_stop(T_SETUP);
}
if (TIMERS_ENABLED == TRUE) {
timer_start(T_FFT);
}
fft(1, u1, u0);
if (TIMERS_ENABLED == TRUE) {
timer_stop(T_FFT);
}
for (iter = 1; iter <= niter; iter++) {
if (TIMERS_ENABLED == TRUE) {
timer_start(T_EVOLVE);
}
evolve(u0, u1, iter, indexmap, dims[0]);
if (TIMERS_ENABLED == TRUE) {
timer_stop(T_EVOLVE);
}
if (TIMERS_ENABLED == TRUE) {
timer_start(T_FFT);
}
fft(-1, u1, u2);
if (TIMERS_ENABLED == TRUE) {
timer_stop(T_FFT);
}
if (TIMERS_ENABLED == TRUE) {
timer_start(T_CHECKSUM);
}
checksum(iter, u2, dims[0]);
if (TIMERS_ENABLED == TRUE) {
timer_stop(T_CHECKSUM);
}
}
verify(NX, NY, NZ, niter, &verified, &class);
{
#if defined(_OPENMP)
nthreads = omp_get_num_threads();
#endif /* _OPENMP */
} /* end parallel */
timer_stop(T_TOTAL);
total_time = timer_read(T_TOTAL);
if( total_time != 0.0) {
mflops = 1.0e-6*(double)(NTOTAL) *
(14.8157+7.19641*log((double)(NTOTAL))
+ (5.23518+7.21113*log((double)(NTOTAL)))*niter)
/total_time;
} else {
mflops = 0.0;
}
c_print_results("FT", class, NX, NY, NZ, niter, nthreads,
total_time, mflops, " floating point", verified,
NPBVERSION, COMPILETIME,
CS1, CS2, CS3, CS4, CS5, CS6, CS7);
if (TIMERS_ENABLED == TRUE) print_timers();
}
/*--------------------------------------------------------------------
c-------------------------------------------------------------------*/
static void evolve(dcomplex u0[NZ][NY][NX], dcomplex u1[NZ][NY][NX],
int t, int indexmap[NZ][NY][NX], int d[3]) {
/*--------------------------------------------------------------------
c-------------------------------------------------------------------*/
/*--------------------------------------------------------------------
c evolve u0 -> u1 (t time steps) in fourier space
c-------------------------------------------------------------------*/
int i, j, k;
#pragma omp parallel for private(i ,j ,k )
for (k = 0; k < d[2]; k++) {
for (j = 0; j < d[1]; j++) {
for (i = 0; i < d[0]; i++) {
crmul(u1[k][j][i], u0[k][j][i], ex[t*indexmap[k][j][i]]);
}
}
}
}
/*--------------------------------------------------------------------
c-------------------------------------------------------------------*/
static void compute_initial_conditions(dcomplex u0[NZ][NY][NX], int d[3]) {
/*--------------------------------------------------------------------
c-------------------------------------------------------------------*/
/*--------------------------------------------------------------------
c Fill in array u0 with initial conditions from
c random number generator
c-------------------------------------------------------------------*/
int k;
double x0, start, an, dummy;
static double tmp[NX*2*MAXDIM+1];
int i,j,t;
start = SEED;
/*--------------------------------------------------------------------
c Jump to the starting element for our first plane.
c-------------------------------------------------------------------*/
ipow46(A, (zstart[0]-1)*2*NX*NY + (ystart[0]-1)*2*NX, &an);
dummy = randlc(&start, an);
ipow46(A, 2*NX*NY, &an);
/*--------------------------------------------------------------------
c Go through by z planes filling in one square at a time.
c-------------------------------------------------------------------*/
for (k = 0; k < dims[0][2]; k++) {
x0 = start;
vranlc(2*NX*dims[0][1], &x0, A, tmp);
t = 1;
for (j = 0; j < dims[0][1]; j++)
for (i = 0; i < NX; i++) {
u0[k][j][i].real = tmp[t++];
u0[k][j][i].imag = tmp[t++];
}
if (k != dims[0][2]) dummy = randlc(&start, an);
}
}
/*--------------------------------------------------------------------
c-------------------------------------------------------------------*/
static void ipow46(double a, int exponent, double *result) {
/*--------------------------------------------------------------------
c-------------------------------------------------------------------*/
/*--------------------------------------------------------------------
c compute a^exponent mod 2^46
c-------------------------------------------------------------------*/
double dummy, q, r;
int n, n2;
/*--------------------------------------------------------------------
c Use
c a^n = a^(n/2)*a^(n/2) if n even else
c a^n = a*a^(n-1) if n odd
c-------------------------------------------------------------------*/
*result = 1;
if (exponent == 0) return;
q = a;
r = 1;
n = exponent;
while (n > 1) {
n2 = n/2;
if (n2 * 2 == n) {
dummy = randlc(&q, q);
n = n2;
} else {
dummy = randlc(&r, q);
n = n-1;
}
}
dummy = randlc(&r, q);
*result = r;
}
/*--------------------------------------------------------------------
c-------------------------------------------------------------------*/
static void setup(void) {
/*--------------------------------------------------------------------
c-------------------------------------------------------------------*/
int ierr, i, j, fstatus;
printf("\n\n NAS Parallel Benchmarks 3.0 structured OpenMP C version"
" - FT Benchmark\n\n");
niter = NITER_DEFAULT;
printf(" Size : %3dx%3dx%3d\n", NX, NY, NZ);
printf(" Iterations : %7d\n", niter);
/* 1004 format(' Number of processes : ', i7)
1005 format(' Processor array : ', i3, 'x', i3)
1006 format(' WARNING: compiled for ', i5, ' processes. ',
> ' Will not verify. ')*/
#pragma omp parallel for firstprivate(i )
for (i = 0;i < 3 ; i++) {
dims[i][0] = NX;
dims[i][1] = NY;
dims[i][2] = NZ;
}
#pragma omp parallel for firstprivate(i )
for (i = 0; i < 3; i++) {
xstart[i] = 1;
xend[i] = NX;
ystart[i] = 1;
yend[i] = NY;
zstart[i] = 1;
zend[i] = NZ;
}
/*--------------------------------------------------------------------
c Set up info for blocking of ffts and transposes. This improves
c performance on cache-based systems. Blocking involves
c working on a chunk of the problem at a time, taking chunks
c along the first, second, or third dimension.
c
c - In cffts1 blocking is on 2nd dimension (with fft on 1st dim)
c - In cffts2/3 blocking is on 1st dimension (with fft on 2nd and 3rd dims)
c Since 1st dim is always in processor, we'll assume it's long enough
c (default blocking factor is 16 so min size for 1st dim is 16)
c The only case we have to worry about is cffts1 in a 2d decomposition.
c so the blocking factor should not be larger than the 2nd dimension.
c-------------------------------------------------------------------*/
fftblock = FFTBLOCK_DEFAULT;
fftblockpad = FFTBLOCKPAD_DEFAULT;
if (fftblock != FFTBLOCK_DEFAULT) fftblockpad = fftblock+3;
}
/*--------------------------------------------------------------------
c-------------------------------------------------------------------*/
static void compute_indexmap(int indexmap[NZ][NY][NX], int d[3]) {
/*--------------------------------------------------------------------
c-------------------------------------------------------------------*/
/*--------------------------------------------------------------------
c compute function from local (i,j,k) to ibar^2+jbar^2+kbar^2
c for time evolution exponent.
c-------------------------------------------------------------------*/
int i, j, k, ii, ii2, jj, ij2, kk;
double ap;
/*--------------------------------------------------------------------
c basically we want to convert the fortran indices
c 1 2 3 4 5 6 7 8
c to
c 0 1 2 3 -4 -3 -2 -1
c The following magic formula does the trick:
c mod(i-1+n/2, n) - n/2
c-------------------------------------------------------------------*/
#pragma omp parallel for private(i ,j ,k ,ii ,ii2 ,jj ,ij2 ,kk )
for (i = 0; i < dims[2][0]; i++) {
ii = (i+1+xstart[2]-2+NX/2)%NX - NX/2;
ii2 = ii*ii;
#pragma omp parallel for firstprivate(k ,j ,ii ,ii2 ,jj ,ij2 ,kk ,indexmap ,i )
for (j = 0; j < dims[2][1]; j++) {
jj = (j+1+ystart[2]-2+NY/2)%NY - NY/2;
ij2 = jj*jj+ii2;
#pragma omp parallel for firstprivate(k ,j ,ii ,ii2 ,jj ,ij2 ,kk ,indexmap ,i )
for (k = 0; k < dims[2][2]; k++) {
kk = (k+1+zstart[2]-2+NZ/2)%NZ - NZ/2;
indexmap[k][j][i] = kk*kk+ij2;
}
}
}
/*--------------------------------------------------------------------
c compute array of exponentials for time evolution.
c-------------------------------------------------------------------*/
ap = - 4.0 * ALPHA * PI * PI;
ex[0] = 1.0;
ex[1] = exp(ap);
for (i = 2; i <= EXPMAX; i++) {
ex[i] = ex[i-1]*ex[1];
}
}
/*--------------------------------------------------------------------
c-------------------------------------------------------------------*/
static void print_timers(void) {
/*--------------------------------------------------------------------
c-------------------------------------------------------------------*/
int i;
char *tstrings[] = { " total ",
" setup ",
" fft ",
" evolve ",
" checksum ",
" fftlow ",
" fftcopy " };
for (i = 0; i < T_MAX; i++) {
if (timer_read(i) != 0.0) {
printf("timer %2d(%16s( :%10.6f\n", i, tstrings[i], timer_read(i));
}
}
}
/*--------------------------------------------------------------------
c-------------------------------------------------------------------*/
static void fft(int dir, dcomplex x1[NZ][NY][NX], dcomplex x2[NZ][NY][NX]) {
/*--------------------------------------------------------------------
c-------------------------------------------------------------------*/
dcomplex y0[NX][FFTBLOCKPAD];
dcomplex y1[NX][FFTBLOCKPAD];
/*--------------------------------------------------------------------
c note: args x1, x2 must be different arrays
c note: args for cfftsx are (direction, layout, xin, xout, scratch)
c xin/xout may be the same and it can be somewhat faster
c if they are
c-------------------------------------------------------------------*/
if (dir == 1) {
cffts1(1, dims[0], x1, x1, y0, y1); /* x1 -> x1 */
cffts2(1, dims[1], x1, x1, y0, y1); /* x1 -> x1 */
cffts3(1, dims[2], x1, x2, y0, y1); /* x1 -> x2 */
} else {
cffts3(-1, dims[2], x1, x1, y0, y1); /* x1 -> x1 */
cffts2(-1, dims[1], x1, x1, y0, y1); /* x1 -> x1 */
cffts1(-1, dims[0], x1, x2, y0, y1); /* x1 -> x2 */
}
}
/*--------------------------------------------------------------------
c-------------------------------------------------------------------*/
static void cffts1(int is, int d[3], dcomplex x[NZ][NY][NX],
dcomplex xout[NZ][NY][NX],
dcomplex y0[NX][FFTBLOCKPAD],
dcomplex y1[NX][FFTBLOCKPAD]) {
/*--------------------------------------------------------------------
c-------------------------------------------------------------------*/
int logd[3];
int i, j, k, jj;
#pragma omp parallel for firstprivate(d ,i )
for (i = 0; i < 3; i++) {
logd[i] = ilog2(d[i]);
}
{
dcomplex y0[NX][FFTBLOCKPAD];
dcomplex y1[NX][FFTBLOCKPAD];
#pragma omp parallel for private(i ,j ,k ,jj )
for (k = 0; k < d[2]; k++) {
for (jj = 0; jj <= d[1] - fftblock; jj+=fftblock) {
/* if (TIMERS_ENABLED == TRUE) timer_start(T_FFTCOPY); */
#pragma omp parallel for firstprivate(fftblock ,i ,jj ,x ,j ,k )
for (j = 0; j < fftblock; j++) {
#pragma omp parallel for firstprivate(fftblock ,i ,jj ,x ,j ,k )
for (i = 0; i < d[0]; i++) {
y0[i][j].real = x[k][j+jj][i].real;
y0[i][j].imag = x[k][j+jj][i].imag;
}
}
/* if (TIMERS_ENABLED == TRUE) timer_stop(T_FFTCOPY); */
/* if (TIMERS_ENABLED == TRUE) timer_start(T_FFTLOW); */
cfftz (is, logd[0],
d[0], y0, y1);
/* if (TIMERS_ENABLED == TRUE) timer_stop(T_FFTLOW); */
/* if (TIMERS_ENABLED == TRUE) timer_start(T_FFTCOPY); */
#pragma omp parallel for firstprivate(fftblock ,i ,jj ,x ,j ,k )
for (j = 0; j < fftblock; j++) {
for (i = 0; i < d[0]; i++) {
xout[k][j+jj][i].real = y0[i][j].real;
xout[k][j+jj][i].imag = y0[i][j].imag;
}
}
/* if (TIMERS_ENABLED == TRUE) timer_stop(T_FFTCOPY); */
}
}
}
}
/*--------------------------------------------------------------------
c-------------------------------------------------------------------*/
static void cffts2(int is, int d[3], dcomplex x[NZ][NY][NX],
dcomplex xout[NZ][NY][NX],
dcomplex y0[NX][FFTBLOCKPAD],
dcomplex y1[NX][FFTBLOCKPAD]) {
/*--------------------------------------------------------------------
c-------------------------------------------------------------------*/
int logd[3];
int i, j, k, ii;
#pragma omp parallel for firstprivate(d ,i )
for (i = 0; i < 3; i++) {
logd[i] = ilog2(d[i]);
}
{
dcomplex y0[NX][FFTBLOCKPAD];
dcomplex y1[NX][FFTBLOCKPAD];
#pragma omp parallel for private(i ,j ,k ,ii )
for (k = 0; k < d[2]; k++) {
for (ii = 0; ii <= d[0] - fftblock; ii+=fftblock) {
/* if (TIMERS_ENABLED == TRUE) timer_start(T_FFTCOPY); */
#pragma omp parallel for firstprivate(i ,ii ,x ,fftblock ,j ,k )
for (j = 0; j < d[1]; j++) {
#pragma omp parallel for firstprivate(i ,ii ,x ,fftblock ,j ,k )
for (i = 0; i < fftblock; i++) {
y0[j][i].real = x[k][j][i+ii].real;
y0[j][i].imag = x[k][j][i+ii].imag;
}
}
/* if (TIMERS_ENABLED == TRUE) timer_stop(T_FFTCOPY); */
/* if (TIMERS_ENABLED == TRUE) timer_start(T_FFTLOW); */
cfftz (is, logd[1],
d[1], y0, y1);
/* if (TIMERS_ENABLED == TRUE) timer_stop(T_FFTLOW); */
/* if (TIMERS_ENABLED == TRUE) timer_start(T_FFTCOPY); */
#pragma omp parallel for firstprivate(i ,ii ,x ,fftblock ,j ,k )
for (j = 0; j < d[1]; j++) {
for (i = 0; i < fftblock; i++) {
xout[k][j][i+ii].real = y0[j][i].real;
xout[k][j][i+ii].imag = y0[j][i].imag;
}
}
/* if (TIMERS_ENABLED == TRUE) timer_stop(T_FFTCOPY); */
}
}
}
}
/*--------------------------------------------------------------------
c-------------------------------------------------------------------*/
static void cffts3(int is, int d[3], dcomplex x[NZ][NY][NX],
dcomplex xout[NZ][NY][NX],
dcomplex y0[NX][FFTBLOCKPAD],
dcomplex y1[NX][FFTBLOCKPAD]) {
/*--------------------------------------------------------------------
c-------------------------------------------------------------------*/
int logd[3];
int i, j, k, ii;
#pragma omp parallel for firstprivate(d ,i )
for (i = 0;i < 3; i++) {
logd[i] = ilog2(d[i]);
}
{
dcomplex y0[NX][FFTBLOCKPAD];
dcomplex y1[NX][FFTBLOCKPAD];
#pragma omp parallel for private(i ,j ,k ,ii )
for (j = 0; j < d[1]; j++) {
for (ii = 0; ii <= d[0] - fftblock; ii+=fftblock) {
/* if (TIMERS_ENABLED == TRUE) timer_start(T_FFTCOPY); */
#pragma omp parallel for firstprivate(i ,ii ,x ,fftblock ,k ,j )
for (k = 0; k < d[2]; k++) {
#pragma omp parallel for firstprivate(i ,ii ,x ,fftblock ,k ,j )
for (i = 0; i < fftblock; i++) {
y0[k][i].real = x[k][j][i+ii].real;
y0[k][i].imag = x[k][j][i+ii].imag;
}
}
/* if (TIMERS_ENABLED == TRUE) timer_stop(T_FFTCOPY); */
/* if (TIMERS_ENABLED == TRUE) timer_start(T_FFTLOW); */
cfftz (is, logd[2],
d[2], y0, y1);
/* if (TIMERS_ENABLED == TRUE) timer_stop(T_FFTLOW); */
/* if (TIMERS_ENABLED == TRUE) timer_start(T_FFTCOPY); */
#pragma omp parallel for firstprivate(i ,ii ,x ,fftblock ,k ,j )
for (k = 0; k < d[2]; k++) {
for (i = 0; i < fftblock; i++) {
xout[k][j][i+ii].real = y0[k][i].real;
xout[k][j][i+ii].imag = y0[k][i].imag;
}
}
/* if (TIMERS_ENABLED == TRUE) timer_stop(T_FFTCOPY); */
}
}
}
}
/*--------------------------------------------------------------------
c-------------------------------------------------------------------*/
static void fft_init (int n) {
/*--------------------------------------------------------------------
c-------------------------------------------------------------------*/
/*--------------------------------------------------------------------
c compute the roots-of-unity array that will be used for subsequent FFTs.
c-------------------------------------------------------------------*/
int m,nu,ku,i,j,ln;
double t, ti;
/*--------------------------------------------------------------------
c Initialize the U array with sines and cosines in a manner that permits
c stride one access at each FFT iteration.
c-------------------------------------------------------------------*/
nu = n;
m = ilog2(n);
u[0].real = (double)m;
u[0].imag = 0.0;
ku = 1;
ln = 1;
for (j = 1; j <= m; j++) {
t = PI / ln;
for (i = 0; i <= ln - 1; i++) {
ti = i * t;
u[i+ku].real = cos(ti);
u[i+ku].imag = sin(ti);
}
ku = ku + ln;
ln = 2 * ln;
}
}
/*--------------------------------------------------------------------
c-------------------------------------------------------------------*/
static void cfftz (int is, int m, int n, dcomplex x[NX][FFTBLOCKPAD],
dcomplex y[NX][FFTBLOCKPAD]) {
/*--------------------------------------------------------------------
c-------------------------------------------------------------------*/
/*--------------------------------------------------------------------
c Computes NY N-point complex-to-complex FFTs of X using an algorithm due
c to Swarztrauber. X is both the input and the output array, while Y is a
c scratch array. It is assumed that N = 2^M. Before calling CFFTZ to
c perform FFTs, the array U must be initialized by calling CFFTZ with IS
c set to 0 and M set to MX, where MX is the maximum value of M for any
c subsequent call.
c-------------------------------------------------------------------*/
int i,j,l,mx;
/*--------------------------------------------------------------------
c Check if input parameters are invalid.
c-------------------------------------------------------------------*/
mx = (int)(u[0].real);
if ((is != 1 && is != -1) || m < 1 || m > mx) {
printf("CFFTZ: Either U has not been initialized, or else\n"
"one of the input parameters is invalid%5d%5d%5d\n",
is, m, mx);
exit(1);
}
/*--------------------------------------------------------------------
c Perform one variant of the Stockham FFT.
c-------------------------------------------------------------------*/
for (l = 1; l <= m; l+=2) {
fftz2 (is, l, m, n, fftblock, fftblockpad, u, x, y);
if (l == m) break;
fftz2 (is, l + 1, m, n, fftblock, fftblockpad, u, y, x);
}
/*--------------------------------------------------------------------
c Copy Y to X.
c-------------------------------------------------------------------*/
if (m % 2 == 1) {
for (j = 0; j < n; j++) {
#pragma omp parallel for firstprivate(fftblock ,y ,x ,i ,j )
for (i = 0; i < fftblock; i++) {
x[j][i].real = y[j][i].real;
x[j][i].imag = y[j][i].imag;
}
}
}
}
/*--------------------------------------------------------------------
c-------------------------------------------------------------------*/
static void fftz2 (int is, int l, int m, int n, int ny, int ny1,
dcomplex u[NX], dcomplex x[NX][FFTBLOCKPAD],
dcomplex y[NX][FFTBLOCKPAD]) {
/*--------------------------------------------------------------------
c-------------------------------------------------------------------*/
/*--------------------------------------------------------------------
c Performs the L-th iteration of the second variant of the Stockham FFT.
c-------------------------------------------------------------------*/
int k,n1,li,lj,lk,ku,i,j,i11,i12,i21,i22;
dcomplex u1,x11,x21;
/*--------------------------------------------------------------------
c Set initial parameters.
c-------------------------------------------------------------------*/
n1 = n / 2;
if (l-1 == 0) {
lk = 1;
} else {
lk = 2 << ((l - 1)-1);
}
if (m-l == 0) {
li = 1;
} else {
li = 2 << ((m - l)-1);
}
lj = 2 * lk;
ku = li;
for (i = 0; i < li; i++) {
i11 = i * lk;
i12 = i11 + n1;
i21 = i * lj;
i22 = i21 + lk;
if (is >= 1) {
u1.real = u[ku+i].real;
u1.imag = u[ku+i].imag;
} else {
u1.real = u[ku+i].real;
u1.imag = -u[ku+i].imag;
}
/*--------------------------------------------------------------------
c This loop is vectorizable.
c-------------------------------------------------------------------*/
for (k = 0; k < lk; k++) {
for (j = 0; j < ny; j++) {
double x11real, x11imag;
double x21real, x21imag;
x11real = x[i11+k][j].real;
x11imag = x[i11+k][j].imag;
x21real = x[i12+k][j].real;
x21imag = x[i12+k][j].imag;
y[i21+k][j].real = x11real + x21real;
y[i21+k][j].imag = x11imag + x21imag;
y[i22+k][j].real = u1.real * (x11real - x21real)
- u1.imag * (x11imag - x21imag);
y[i22+k][j].imag = u1.real * (x11imag - x21imag)
+ u1.imag * (x11real - x21real);
}
}
}
}
/*--------------------------------------------------------------------
c-------------------------------------------------------------------*/
static int ilog2(int n) {
/*--------------------------------------------------------------------
c-------------------------------------------------------------------*/
int nn, lg;
if (n == 1) {
return 0;
}
lg = 1;
nn = 2;
while (nn < n) {
nn = nn << 1;
lg++;
}
return lg;
}
/*--------------------------------------------------------------------
c-------------------------------------------------------------------*/
static void checksum(int i, dcomplex u1[NZ][NY][NX], int d[3]) {
{
/*--------------------------------------------------------------------
c-------------------------------------------------------------------*/
int j, q,r,s, ierr;
dcomplex chk,allchk;
chk.real = 0.0;
chk.imag = 0.0;
#pragma omp parallel for
for (j = 1; j <= 1024; j++) {
q = j%NX+1;
if (q >= xstart[0] && q <= xend[0]) {
r = (3*j)%NY+1;
if (r >= ystart[0] && r <= yend[0]) {
s = (5*j)%NZ+1;
if (s >= zstart[0] && s <= zend[0]) {
cadd(chk,chk,u1[s-zstart[0]][r-ystart[0]][q-xstart[0]]);
}
}
}
}
{
sums[i].real += chk.real;
sums[i].imag += chk.imag;
}
{
/* complex % real */
sums[i].real = sums[i].real/(double)(NTOTAL);
sums[i].imag = sums[i].imag/(double)(NTOTAL);
printf("T = %5d Checksum = %22.12e %22.12e\n",
i, sums[i].real, sums[i].imag);
}
}
}
/*--------------------------------------------------------------------
c-------------------------------------------------------------------*/
static void verify (int d1, int d2, int d3, int nt,
boolean *verified, char *class) {
/*--------------------------------------------------------------------
c-------------------------------------------------------------------*/
int ierr, size, i;
double err, epsilon;
/*--------------------------------------------------------------------
c Sample size reference checksums
c-------------------------------------------------------------------*/
/*--------------------------------------------------------------------
c Class S size reference checksums
c-------------------------------------------------------------------*/
double vdata_real_s[6+1] = { 0.0,
5.546087004964e+02,
5.546385409189e+02,
5.546148406171e+02,
5.545423607415e+02,
5.544255039624e+02,
5.542683411902e+02 };
double vdata_imag_s[6+1] = { 0.0,
4.845363331978e+02,
4.865304269511e+02,
4.883910722336e+02,
4.901273169046e+02,
4.917475857993e+02,
4.932597244941e+02 };
/*--------------------------------------------------------------------
c Class W size reference checksums
c-------------------------------------------------------------------*/
double vdata_real_w[6+1] = { 0.0,
5.673612178944e+02,
5.631436885271e+02,
5.594024089970e+02,
5.560698047020e+02,
5.530898991250e+02,
5.504159734538e+02 };
double vdata_imag_w[6+1] = { 0.0,
5.293246849175e+02,
5.282149986629e+02,
5.270996558037e+02,
5.260027904925e+02,
5.249400845633e+02,
5.239212247086e+02 };
/*--------------------------------------------------------------------
c Class A size reference checksums
c-------------------------------------------------------------------*/
double vdata_real_a[6+1] = { 0.0,
5.046735008193e+02,
5.059412319734e+02,
5.069376896287e+02,
5.077892868474e+02,
5.085233095391e+02,
5.091487099959e+02 };
double vdata_imag_a[6+1] = { 0.0,
5.114047905510e+02,
5.098809666433e+02,
5.098144042213e+02,
5.101336130759e+02,
5.104914655194e+02,
5.107917842803e+02 };
/*--------------------------------------------------------------------
c Class B size reference checksums
c-------------------------------------------------------------------*/
double vdata_real_b[20+1] = { 0.0,
5.177643571579e+02,
5.154521291263e+02,
5.146409228649e+02,
5.142378756213e+02,
5.139626667737e+02,
5.137423460082e+02,
5.135547056878e+02,
5.133910925466e+02,
5.132470705390e+02,
5.131197729984e+02,
5.130070319283e+02,
5.129070537032e+02,
5.128182883502e+02,
5.127393733383e+02,
5.126691062020e+02,
5.126064276004e+02,
5.125504076570e+02,
5.125002331720e+02,
5.124551951846e+02,
5.124146770029e+02 };
double vdata_imag_b[20+1] = { 0.0,
5.077803458597e+02,
5.088249431599e+02,
5.096208912659e+02,
5.101023387619e+02,
5.103976610617e+02,
5.105948019802e+02,
5.107404165783e+02,
5.108576573661e+02,
5.109577278523e+02,
5.110460304483e+02,
5.111252433800e+02,
5.111968077718e+02,
5.112616233064e+02,
5.113203605551e+02,
5.113735928093e+02,
5.114218460548e+02,
5.114656139760e+02,
5.115053595966e+02,
5.115415130407e+02,
5.115744692211e+02 };
/*--------------------------------------------------------------------
c Class C size reference checksums
c-------------------------------------------------------------------*/
double vdata_real_c[20+1] = { 0.0,
5.195078707457e+02,
5.155422171134e+02,
5.144678022222e+02,
5.140150594328e+02,
5.137550426810e+02,
5.135811056728e+02,
5.134569343165e+02,
5.133651975661e+02,
5.132955192805e+02,
5.132410471738e+02,
5.131971141679e+02,
5.131605205716e+02,
5.131290734194e+02,
5.131012720314e+02,
5.130760908195e+02,
5.130528295923e+02,
5.130310107773e+02,
5.130103090133e+02,
5.129905029333e+02,
5.129714421109e+02 };
double vdata_imag_c[20+1] = { 0.0,
5.149019699238e+02,
5.127578201997e+02,
5.122251847514e+02,
5.121090289018e+02,
5.121143685824e+02,
5.121496764568e+02,
5.121870921893e+02,
5.122193250322e+02,
5.122454735794e+02,
5.122663649603e+02,
5.122830879827e+02,
5.122965869718e+02,
5.123075927445e+02,
5.123166486553e+02,
5.123241541685e+02,
5.123304037599e+02,
5.123356167976e+02,
5.123399592211e+02,
5.123435588985e+02,
5.123465164008e+02 };
epsilon = 1.0e-12;
*verified = TRUE;
*class = 'U';
if (d1 == 64 &&
d2 == 64 &&
d3 == 64 &&
nt == 6) {
*class = 'S';
for (i = 1; i <= nt; i++) {
err = (get_real(sums[i]) - vdata_real_s[i]) / vdata_real_s[i];
if (fabs(err) > epsilon) {
*verified = FALSE;
break;
}
err = (get_imag(sums[i]) - vdata_imag_s[i]) / vdata_imag_s[i];
if (fabs(err) > epsilon) {
*verified = FALSE;
break;
}
}
} else if (d1 == 128 &&
d2 == 128 &&
d3 == 32 &&
nt == 6) {
*class = 'W';
for (i = 1; i <= nt; i++) {
err = (get_real(sums[i]) - vdata_real_w[i]) / vdata_real_w[i];
if (fabs(err) > epsilon) {
*verified = FALSE;
break;
}
err = (get_imag(sums[i]) - vdata_imag_w[i]) / vdata_imag_w[i];
if (fabs(err) > epsilon) {
*verified = FALSE;
break;
}
}
} else if (d1 == 256 &&
d2 == 256 &&
d3 == 128 &&
nt == 6) {
*class = 'A';
for (i = 1; i <= nt; i++) {
err = (get_real(sums[i]) - vdata_real_a[i]) / vdata_real_a[i];
if (fabs(err) > epsilon) {
*verified = FALSE;
break;
}
err = (get_imag(sums[i]) - vdata_imag_a[i]) / vdata_imag_a[i];
if (fabs(err) > epsilon) {
*verified = FALSE;
break;
}
}
} else if (d1 == 512 &&
d2 == 256 &&
d3 == 256 &&
nt == 20) {
*class = 'B';
for (i = 1; i <= nt; i++) {
err = (get_real(sums[i]) - vdata_real_b[i]) / vdata_real_b[i];
if (fabs(err) > epsilon) {
*verified = FALSE;
break;
}
err = (get_imag(sums[i]) - vdata_imag_b[i]) / vdata_imag_b[i];
if (fabs(err) > epsilon) {
*verified = FALSE;
break;
}
}
} else if (d1 == 512 &&
d2 == 512 &&
d3 == 512 &&
nt == 20) {
*class = 'C';
for (i = 1; i <= nt; i++) {
err = (get_real(sums[i]) - vdata_real_c[i]) / vdata_real_c[i];
if (fabs(err) > epsilon) {
*verified = FALSE;
break;
}
err = (get_imag(sums[i]) - vdata_imag_c[i]) / vdata_imag_c[i];
if (fabs(err) > epsilon) {
*verified = FALSE;
break;
}
}
}
if (*class != 'U') {
printf("Result verification successful\n");
} else {
printf("Result verification failed\n");
}
printf("class = %1c\n", *class);
}
|
trilinos_residual_criteria.h | // KRATOS _____ _ _ _
// |_ _| __(_) (_)_ __ ___ ___
// | || '__| | | | '_ \ / _ \/ __|
// | || | | | | | | | | (_) \__
// |_||_| |_|_|_|_| |_|\___/|___/ APPLICATION
//
// License: BSD License
// Kratos default license: kratos/license.txt
//
// Main authors: Jordi Cotela
//
#if !defined(KRATOS_TRILINOS_RESIDUAL_CRITERIA_H_INCLUDED)
#define KRATOS_TRILINOS_RESIDUAL_CRITERIA_H_INCLUDED
// System includes
// External includes
// Project includes
#include "includes/define.h"
#include "solving_strategies/convergencecriterias/residual_criteria.h"
namespace Kratos
{
///@addtogroup TrilinosApplication
///@{
///@name Kratos Classes
///@{
/// MPI version of the ResidualCriteria.
/** Implements a convergence criteria based on the norm of the (free rows of) the RHS vector.
* @see ResidualCriteria
*/
template< class TSparseSpace, class TDenseSpace >
class TrilinosResidualCriteria : public ResidualCriteria< TSparseSpace, TDenseSpace >
{
public:
///@name Type Definitions
///@{
/// Pointer definition of TrilinosResidualCriteria
KRATOS_CLASS_POINTER_DEFINITION(TrilinosResidualCriteria);
typedef ResidualCriteria< TSparseSpace, TDenseSpace > BaseType;
typedef typename BaseType::TDataType TDataType;
///@}
///@name Life Cycle
///@{
/// Constructor
explicit TrilinosResidualCriteria(TDataType NewRatioTolerance,TDataType AlwaysConvergedNorm):
ResidualCriteria<TSparseSpace,TDenseSpace>(NewRatioTolerance, AlwaysConvergedNorm)
{}
/// Copy constructor
explicit TrilinosResidualCriteria(const TrilinosResidualCriteria& rOther):
ResidualCriteria<TSparseSpace,TDenseSpace>(rOther)
{}
/// Destructor.
~TrilinosResidualCriteria() override {}
///@}
///@name Operators
///@{
/// Deleted assignment operator.
TrilinosResidualCriteria& operator=(TrilinosResidualCriteria const& rOther) = delete;
///@}
protected:
///@name Protected Operations
///@{
/**
* @brief This method computes the norm of the residual
* @details It checks if the dof is fixed
* @param rModelPart Reference to the ModelPart containing the problem.
* @param rResidualSolutionNorm The norm of the residual
* @param rDofNum The number of DoFs
* @param rDofSet Reference to the container of the problem's degrees of freedom (stored by the BuilderAndSolver)
* @param b RHS vector (residual + reactions)
*/
void CalculateResidualNorm(
ModelPart& rModelPart,
TDataType& rResidualSolutionNorm,
typename BaseType::SizeType& rDofNum,
typename BaseType::DofsArrayType& rDofSet,
const typename BaseType::TSystemVectorType& rB) override
{
// Initialize
TDataType residual_solution_norm = TDataType();
long int local_dof_num = 0;
const int rank = rB.Comm().MyPID();
// Loop over Dofs
#pragma omp parallel for reduction(+:residual_solution_norm,local_dof_num)
for (int i = 0; i < static_cast<int>(rDofSet.size()); i++) {
auto it_dof = rDofSet.begin() + i;
typename BaseType::IndexType dof_id;
TDataType residual_dof_value;
if (it_dof->IsFree() && (it_dof->GetSolutionStepValue(PARTITION_INDEX) == rank)) {
dof_id = it_dof->EquationId();
residual_dof_value = TSparseSpace::GetValue(rB,dof_id);
residual_solution_norm += residual_dof_value * residual_dof_value;
local_dof_num++;
}
}
// Combine local contributions
// Note that I'm not merging the two calls because one adds doubles and the other ints (JC)
rB.Comm().SumAll(&residual_solution_norm,&rResidualSolutionNorm,1);
// SizeType is long unsigned int in linux, but EpetraComm does not support unsigned types
long int global_dof_num = 0;
rB.Comm().SumAll(&local_dof_num,&global_dof_num,1);
rDofNum = static_cast<typename BaseType::SizeType>(global_dof_num);
rResidualSolutionNorm = std::sqrt(rResidualSolutionNorm);
}
///@}
private:
///@name Member Variables
///@{
///@}
///@name Private Operations
///@{
///@}
}; // Class TrilinosResidualCriteria
///@}
///@} addtogroup block
} // namespace Kratos.
#endif // KRATOS_TRILINOS_RESIDUAL_CRITERIA_H_INCLUDED defined
|
SimplexNoiseKernel.h | /****************************************************************************
** Copyright 2019 The Open Group
** Copyright 2019 Bluware, Inc.
**
** 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.
****************************************************************************/
#include <OpenVDS/Vector.h>
#include <OpenVDS/ValueConversion.h>
#include <OpenVDS/VolumeIndexer.h>
#define NOISE_OCTAVES (5)
#define NOISE_SCALE (0.06f * 0.1f)
namespace OpenVDS
{
template<int dimensionality, int octaves>
float SimplexNoise(float *position, unsigned int randomSeed)
{
int integerPosition[4];
int index[4];
float distance[4];
float sortedDistance[4];
int dimension;
float skew = (sqrtf((float)dimensionality + 1) - 1.f) / (float)dimensionality;
float unskew = (dimensionality + 1 - sqrtf((float)dimensionality + 1)) / ((float)dimensionality * (dimensionality + 1));
float noise = 0.f;
float scale = 1.f;
float amplitude = 1.f;
float amplitudeSum = 0.f;
for(int octave = 0; octave < octaves; octave++)
{
float positionSum = position[0] * scale;
for(dimension = 1; dimension < dimensionality; dimension++)
{
positionSum += position[dimension] * scale;
}
integerPosition[0] = (int)floorf(position[0] * scale + positionSum * skew);
int integerPositionSum = integerPosition[0];
for(dimension = 1; dimension < dimensionality; dimension++)
{
integerPosition[dimension] = (int)floorf(position[dimension] * scale + positionSum * skew);
integerPositionSum += integerPosition[dimension];
}
for(dimension = 0; dimension < dimensionality; dimension++)
{
distance[dimension] = position[dimension] * scale - (integerPosition[dimension] - integerPositionSum * unskew);
sortedDistance[dimension] = distance[dimension];
index[dimension] = dimension;
}
for(dimension = 0; dimension < dimensionality - 1; dimension++)
{
if(sortedDistance[dimension] < sortedDistance[dimension + 1])
{
float rTemp = sortedDistance[dimension];
int iTemp = index[dimension];
sortedDistance[dimension] = sortedDistance[dimension + 1];
index[dimension] = index[dimension + 1];
sortedDistance[dimension + 1] = rTemp;
index[dimension + 1] = iTemp;
if(dimension > 0) dimension-=2;
}
}
for(int vertex = 0; true; vertex++)
{
unsigned int
random = randomSeed,
u0 = 79555561 + octave * 322147;
for(dimension = 0; dimension < dimensionality; dimension++)
{
random += integerPosition[dimension] * random;
u0 += random;
random ^= u0 + 8953453 * random;
}
float weight = 0.6f - distance[0] * distance[0]; // This vertex contributes relative to the distance of the point from this vertex
for(dimension = 1; dimension < dimensionality; dimension++)
{
weight -= distance[dimension] * distance[dimension];
}
if(weight > 0.f)
{
weight *= weight;
weight *= weight;
// We use a gradient vector which is the midpoint of some edge of an N-dimensional cube centered on origo
// To get this, we chose a vertex of the N-dimensional cube, and then chose one of it's coordinates to be 0
// This gives us two ways of making every edge, but that is completely unproblematic
int iNull = random % dimensionality;
random /= dimensionality;
// We loop through each component to form the dot product between the gradient vector and the distance vector
float dot = 0.f;
for(dimension = 0; dimension < dimensionality; dimension++)
{
if(dimension != iNull)
{
dot += distance[dimension] * ((int)(random & 2) - 1);
}
random >>= 1;
}
noise += dot * weight * amplitude;
}
if(vertex >= dimensionality) break;
for(dimension = 0; dimension < dimensionality; dimension++)
{
distance[dimension] += unskew;
}
distance[index[vertex]] -= 1.f;
integerPosition[index[vertex]]++;
}
amplitude *= 0.35f;
amplitudeSum += amplitude;
scale *= 3.5f;
}
return 0.5f + noise * 5.0f / amplitudeSum;
}
template<int dimension, typename T, bool useNoValue>
struct NoiseKernel
{
static void Do(void * outputVoid, VolumeIndexerBase<dimension> const &outputIndexer, Vector<float, dimension> const &frequency, float threshold, float noValue, unsigned int random)
{
assert(false);
//didnt find the specialisation
}
};
template<int dimension, bool useNoValue, typename ... Args>
inline void GenericDispatcher_1(VolumeDataChannelDescriptor::Format format, Args ... args)
{
switch(format)
{
case VolumeDataChannelDescriptor::Format_1Bit:NoiseKernel<dimension, bool, useNoValue>::Do(args...); break;
case VolumeDataChannelDescriptor::Format_U8: NoiseKernel<dimension, uint8_t, useNoValue>::Do(args...); break;
case VolumeDataChannelDescriptor::Format_U16: NoiseKernel<dimension, uint16_t, useNoValue>::Do(args...); break;
case VolumeDataChannelDescriptor::Format_R32: NoiseKernel<dimension, float, useNoValue>::Do(args...); break;
case VolumeDataChannelDescriptor::Format_U32: NoiseKernel<dimension, uint32_t, useNoValue>::Do(args...); break;
case VolumeDataChannelDescriptor::Format_R64: NoiseKernel<dimension, double, useNoValue>::Do(args...); break;
case VolumeDataChannelDescriptor::Format_U64: NoiseKernel<dimension, uint64_t, useNoValue>::Do(args...); break;
case VolumeDataChannelDescriptor::Format_Any: break;
}
}
template<int dimension, typename ... Args>
inline void GenericDispatcher(bool useNoValue, VolumeDataChannelDescriptor::Format format, Args ... args)
{
if (useNoValue)
GenericDispatcher_1<dimension, true, Args...>(format, args...);
else
GenericDispatcher_1<dimension, false, Args...>(format, args...);
}
template <typename T, bool useNoValue>
struct NoiseKernel<2, T, useNoValue>
{
static void Do(void * outputVoid, VolumeIndexer2D const &outputIndexer2D, FloatVector2 const &frequency, float threshold, float noValue, unsigned int random)
{
T *output = static_cast<T *>(outputVoid);
IntVector<2> numSamples;
IntVector<2> localOutIndex;
for (int i=0; i<2; i++)
{
numSamples[i] = outputIndexer2D.GetDataBlockNumSamples(i);
}
float
valueRangeScale = outputIndexer2D.valueRangeMax - outputIndexer2D.valueRangeMin;
QuantizingValueConverterWithNoValue<T, float, useNoValue> converter(outputIndexer2D.valueRangeMin, outputIndexer2D.valueRangeMax, 1.0f, 0.0f, noValue, noValue);
#pragma omp parallel for firstprivate(converter) schedule(static)
for (int iDim1 = 0; iDim1 < numSamples[1]; iDim1++)
for (int iDim0 = 0; iDim0 < numSamples[0]; iDim0++)
{
IntVector<2>
localOutIndex(iDim0, iDim1);
IntVector<2>
voxelIndex = outputIndexer2D.LocalIndexToVoxelIndex(localOutIndex);
float
pos[2] = { voxelIndex[0] * frequency[0] * NOISE_SCALE,
voxelIndex[1] * frequency[1] * NOISE_SCALE };
float
value = SimplexNoise<2, NOISE_OCTAVES>(pos, random);
output[outputIndexer2D.LocalIndexToDataIndex(localOutIndex)] = converter.ConvertValue(value < threshold ? noValue : (value * valueRangeScale + outputIndexer2D.valueRangeMin));
}
}
};
inline void CalculateNoise2D(void* output, VolumeDataChannelDescriptor::Format format, VolumeIndexer2D *outputIndexer, FloatVector2 frequency, float threshold, float noValue, bool useNoValue, unsigned int random)
{
GenericDispatcher<2>(useNoValue, format, output, *outputIndexer, frequency, threshold, noValue, random);
}
template <typename T, bool useNoValue>
struct NoiseKernel<3, T, useNoValue>
{
static void Do(void* outputVoid, VolumeIndexer3D const &outputIndexer3D, FloatVector3 const &frequency, float threshold, float noValue, unsigned int random)
{
T *output = static_cast<T*>(outputVoid);
IntVector<3> numSamples;
IntVector<3> localOutIndex;
for (int i=0; i<3; i++)
{
numSamples[i] = outputIndexer3D.GetDataBlockNumSamples(i);
}
float
valueRangeScale = outputIndexer3D.valueRangeMax - outputIndexer3D.valueRangeMin;
QuantizingValueConverterWithNoValue<T, float, useNoValue> converter(outputIndexer3D.valueRangeMin, outputIndexer3D.valueRangeMax, valueRangeScale, outputIndexer3D.valueRangeMin, noValue, noValue);
#pragma omp parallel for if(numSamples[2] > 1) firstprivate(converter) schedule(static)
for (int iDim2 = 0; iDim2 < numSamples[2]; iDim2++)
#pragma omp parallel for if(numSamples[2] == 1) firstprivate(converter) schedule(static)
for (int iDim1 = 0; iDim1 < numSamples[1]; iDim1++)
for (int iDim0 = 0; iDim0 < numSamples[0]; iDim0++)
{
IntVector<3>
localOutIndex(iDim0, iDim1, iDim2);
IntVector<3>
voxelIndex = outputIndexer3D.LocalIndexToVoxelIndex(localOutIndex);
float
pos[3] = { voxelIndex[0] * frequency[0] * NOISE_SCALE,
voxelIndex[1] * frequency[1] * NOISE_SCALE,
voxelIndex[2] * frequency[2] * NOISE_SCALE };
float
value = SimplexNoise<3, NOISE_OCTAVES>(pos, random);
output[outputIndexer3D.LocalIndexToDataIndex(localOutIndex)] = converter.ConvertValue(value < threshold ? noValue : value * valueRangeScale + outputIndexer3D.valueRangeMin);
}
}
};
inline void CalculateNoise3D(void* output, VolumeDataChannelDescriptor::Format format, VolumeIndexer3D *outputIndexer, FloatVector3 frequency, float threshold, float noValue, bool useNoValue, unsigned int random)
{
GenericDispatcher<3>(useNoValue, format, output, *outputIndexer, frequency, threshold, noValue, random);
}
template <typename T, bool useNoValue>
struct NoiseKernel<4,T,useNoValue>
{
static void Do(void* outputVoid, VolumeIndexer4D const &outputIndexer4D, FloatVector4 const &frequency, float threshold, float noValue, unsigned int random)
{
T *output = static_cast<T *>(outputVoid);
IntVector<4> numSamples;
for (int i=0; i<4; i++)
{
numSamples[i] = outputIndexer4D.GetDataBlockNumSamples(i);
}
float
valueRangeScale = outputIndexer4D.valueRangeMax - outputIndexer4D.valueRangeMin;
QuantizingValueConverterWithNoValue<T, float, useNoValue> converter(outputIndexer4D.valueRangeMin, outputIndexer4D.valueRangeMax, 1.0f, 0.0f, noValue, noValue);
#pragma omp parallel for if(numSamples[2] > 1) firstprivate(converter) schedule(static)
for (int iDim2 = 0; iDim2 < numSamples[2]; iDim2++)
#pragma omp parallel for if(numSamples[2] == 1) firstprivate(converter) schedule(static)
for (int iDim1 = 0; iDim1 < numSamples[1]; iDim1++)
for (int iDim0 = 0; iDim0 < numSamples[0]; iDim0++)
{
IntVector<4>
localOutIndex(iDim0, iDim1, iDim2, 0);
IntVector<4>
voxelIndex = outputIndexer4D.LocalIndexToVoxelIndex(localOutIndex);
float
pos[4] = { voxelIndex[0] * frequency[0] * NOISE_SCALE,
voxelIndex[1] * frequency[1] * NOISE_SCALE,
voxelIndex[2] * frequency[2] * NOISE_SCALE,
voxelIndex[3] * frequency[3] * NOISE_SCALE };
float
value = SimplexNoise<4, NOISE_OCTAVES>(pos, random);
output[outputIndexer4D.LocalIndexToDataIndex(localOutIndex)] = converter.ConvertValue(value < threshold ? noValue : (value * valueRangeScale + outputIndexer4D.valueRangeMin));
}
}
};
inline void CalculateNoise4D(void* output, VolumeDataChannelDescriptor::Format format, VolumeIndexer4D *outputIndexer, FloatVector4 frequency, float threshold, float noValue, bool useNoValue, unsigned int random)
{
GenericDispatcher<4>(useNoValue, format, output, *outputIndexer, frequency, threshold, noValue, random);
}
}
|
energy.h | #pragma once
#include "space.h"
#include <Eigen/Dense>
#ifdef ENABLE_POWERSASA
#include <power_sasa.h>
#endif
namespace Faunus {
namespace ReactionCoordinate {
struct ReactionCoordinateBase;
}
namespace Energy {
class Energybase {
public:
enum keys { OLD, NEW, NONE };
keys key = NONE;
std::string name;
std::string cite;
TimeRelativeOfTotal<std::chrono::microseconds> timer;
virtual double energy(Change &) = 0; //!< energy due to change
virtual void to_json(json &j) const; //!< json output
virtual void sync(Energybase *, Change &);
virtual void init(); //!< reset and initialize
virtual inline void force(std::vector<Point> &){}; // update forces on all particles
inline virtual ~Energybase(){};
};
void to_json(json &j, const Energybase &base); //!< Converts any energy class to json object
/**
* @brief Check for overlap between atoms and the simulation container
*
* If found infinite energy is returned. Not needed for cuboidal geometry
* as there's nover any overlap due to PBC.
*/
struct ContainerOverlap : public Energybase {
const Tspace &spc;
ContainerOverlap(const Tspace &spc) : spc(spc) { name = "ContainerOverlap"; }
double energy(Change &change) override;
};
/**
* This holds Ewald setup and must *not* depend on particle type, nor depend on Space
*/
struct EwaldData {
typedef std::complex<double> Tcomplex;
Eigen::Matrix3Xd kVectors; // k-vectors, 3xK
Eigen::VectorXd Aks; // 1xK, to minimize computational effort (Eq.24,DOI:10.1063/1.481216)
Eigen::VectorXcd Qion, Qdip; // 1xK
double alpha, rc, kc, check_k2_zero, lB;
double const_inf, eps_surf;
bool spherical_sum = true;
bool ipbc = false;
int kVectorsInUse = 0;
Point L; //!< Box dimensions
void update(const Point &box);
};
void from_json(const json &j, EwaldData &d);
void to_json(json &j, const EwaldData &d);
#ifdef DOCTEST_LIBRARY_INCLUDED
TEST_CASE("[Faunus] Ewald - EwaldData") {
using doctest::Approx;
EwaldData data = R"({
"ipbc": false, "epsr": 1.0, "alpha": 0.894427190999916, "epss": 1.0,
"kcutoff": 11.0, "spherical_sum": true, "cutoff": 5.0})"_json;
data.update(Point(10, 10, 10));
CHECK(data.ipbc == false);
CHECK(data.const_inf == 1);
CHECK(data.alpha == 0.894427190999916);
CHECK(data.kVectors.cols() == 2975);
CHECK(data.Qion.size() == data.kVectors.cols());
data.ipbc = true;
data.update(Point(10, 10, 10));
CHECK(data.kVectors.cols() == 846);
CHECK(data.Qion.size() == data.kVectors.cols());
}
#endif
/** @brief recipe or policies for ion-ion ewald */
template <bool eigenopt = false /** use Eigen matrix ops where possible */> struct PolicyIonIon {
typedef typename Tspace::Tpvec::iterator iter;
Tspace *spc;
Tspace *old = nullptr; // set only if key==NEW at first call to `sync()`
PolicyIonIon(Tspace &spc) : spc(&spc) {}
void updateComplex(EwaldData &data) const {
auto active = spc->activeParticles();
if (eigenopt)
if (data.ipbc == false) {
auto pos = asEigenMatrix(active.begin().base(), active.end().base(), &Tspace::Tparticle::pos); // Nx3
auto charge =
asEigenVector(active.begin().base(), active.end().base(), &Tspace::Tparticle::charge); // Nx1
Eigen::MatrixXd kr = pos.matrix() * data.kVectors; // Nx3 * 3xK = NxK
data.Qion.real() = (kr.array().cos().colwise() * charge).colwise().sum();
data.Qion.imag() = kr.array().sin().colwise().sum();
return;
}
for (int k = 0; k < data.kVectors.cols(); k++) {
const Point &kv = data.kVectors.col(k);
EwaldData::Tcomplex Q(0, 0);
if (data.ipbc)
for (auto &i : active)
Q += kv.cwiseProduct(i.pos).array().cos().prod() * i.charge;
else
for (auto &i : active) {
double dot = kv.dot(i.pos);
Q += i.charge * EwaldData::Tcomplex(std::cos(dot), std::sin(dot));
}
data.Qion[k] = Q;
}
} //!< Update all k vectors
void updateComplex(EwaldData &data, Change &change) const {
assert(old != nullptr);
assert(spc->p.size() == old->p.size());
for (int k = 0; k < data.kVectors.cols(); k++) {
auto &Q = data.Qion[k];
Point q = data.kVectors.col(k);
if (data.ipbc)
for (auto cg : change.groups) {
auto g_new = spc->groups.at(cg.index);
auto g_old = old->groups.at(cg.index);
for (auto i : cg.atoms) {
if (i < g_new.size())
Q += q.cwiseProduct((g_new.begin() + i)->pos).array().cos().prod() *
(g_new.begin() + i)->charge;
if (i < g_old.size())
Q -= q.cwiseProduct((g_old.begin() + i)->pos).array().cos().prod() *
(g_old.begin() + i)->charge;
}
}
else
for (auto cg : change.groups) {
auto g_new = spc->groups.at(cg.index);
auto g_old = old->groups.at(cg.index);
for (auto i : cg.atoms) {
if (i < g_new.size()) {
double _new = q.dot((g_new.begin() + i)->pos);
Q += (g_new.begin() + i)->charge * EwaldData::Tcomplex(std::cos(_new), std::sin(_new));
}
if (i < g_old.size()) {
double _old = q.dot((g_old.begin() + i)->pos);
Q -= (g_old.begin() + i)->charge * EwaldData::Tcomplex(std::cos(_old), std::sin(_old));
}
}
}
}
} //!< Optimized update of k subset. Require access to old positions through `old` pointer
double selfEnergy(const EwaldData &d, Change &change) {
double Eq = 0;
if (change.dN)
for (auto cg : change.groups) {
auto g = spc->groups.at(cg.index);
for (auto i : cg.atoms)
if (i < g.size())
Eq += std::pow((g.begin() + i)->charge, 2);
}
else if (change.all and not change.dV)
for (auto g : spc->groups)
for (auto i : g)
Eq += i.charge * i.charge;
return -d.alpha * Eq / std::sqrt(pc::pi) * d.lB;
}
double surfaceEnergy(const EwaldData &d, Change &change) {
if (d.const_inf < 0.5)
return 0;
Point qr(0, 0, 0);
if (change.all or change.dV)
for (auto g : spc->groups)
for (auto i : g)
qr += i.charge * i.pos;
else if (change.groups.size() > 0)
for (auto cg : change.groups) {
auto g = spc->groups.at(cg.index);
for (auto i : cg.atoms)
if (i < g.size())
qr += (g.begin() + i)->charge * (g.begin() + i)->pos;
}
return d.const_inf * 2 * pc::pi / ((2 * d.eps_surf + 1) * spc->geo.getVolume()) * qr.dot(qr) * d.lB;
}
double reciprocalEnergy(const EwaldData &d) {
double E = 0;
if (eigenopt) // known at compile time
E = d.Aks.cwiseProduct(d.Qion.cwiseAbs2()).sum();
else
for (int k = 0; k < d.Qion.size(); k++)
E += d.Aks[k] * std::norm(d.Qion[k]);
return 2 * pc::pi / spc->geo.getVolume() * E * d.lB;
}
};
#ifdef DOCTEST_LIBRARY_INCLUDED
TEST_CASE("[Faunus] Ewald - IonIonPolicy") {
using doctest::Approx;
Tspace spc;
spc.p.resize(2);
spc.geo = R"( {"type": "cuboid", "length": 10} )"_json;
spc.p[0] = R"( {"pos": [0,0,0], "q": 1.0} )"_json;
spc.p[1] = R"( {"pos": [1,0,0], "q": -1.0} )"_json;
Group<Particle> g(spc.p.begin(), spc.p.end());
spc.groups.push_back(g);
PolicyIonIon<> ionion(spc);
EwaldData data = R"({
"epsr": 1.0, "alpha": 0.894427190999916, "epss": 1.0,
"kcutoff": 11.0, "spherical_sum": true, "cutoff": 5.0})"_json;
Change c;
c.all = true;
data.ipbc = false; // PBC Ewald (http://dx.doi.org/10.1063/1.481216)
data.update(spc.geo.getLength());
ionion.updateComplex(data);
CHECK(ionion.selfEnergy(data, c) == Approx(-1.0092530088080642 * data.lB));
CHECK(ionion.surfaceEnergy(data, c) == Approx(0.0020943951023931952 * data.lB));
CHECK(ionion.reciprocalEnergy(data) == Approx(0.21303063979675319 * data.lB));
data.ipbc = true; // IPBC Ewald
data.update(spc.geo.getLength());
ionion.updateComplex(data);
CHECK(ionion.selfEnergy(data, c) == Approx(-1.0092530088080642 * data.lB));
CHECK(ionion.surfaceEnergy(data, c) == Approx(0.0020943951023931952 * data.lB));
CHECK(ionion.reciprocalEnergy(data) == Approx(0.0865107467 * data.lB));
}
#endif
/** @brief Ewald summation reciprocal energy */
template <class Policy = PolicyIonIon<>> class Ewald : public Energybase {
private:
EwaldData data;
Policy policy;
Tspace &spc;
public:
Ewald(const json &j, Tspace &spc) : policy(spc), spc(spc) {
name = "ewald";
data = j;
init();
}
void init() override {
data.update(spc.geo.getLength());
policy.updateComplex(data); // brute force. todo: be selective
}
double energy(Change &change) override {
double u = 0;
if (change) {
// If the state is NEW (trial state), then update all k-vectors
if (key == NEW) {
if (change.all || change.dV) { // everything changes
data.update(spc.geo.getLength());
policy.updateComplex(data); // update all (expensive!)
} else {
if (change.groups.size() > 0)
policy.updateComplex(data, change);
}
}
u = policy.surfaceEnergy(data, change) + policy.reciprocalEnergy(data) + policy.selfEnergy(data, change);
}
return u;
}
void sync(Energybase *basePtr, Change &) override {
auto other = dynamic_cast<decltype(this)>(basePtr);
assert(other);
if (other->key == OLD)
policy.old = &(other->spc); // give NEW access to OLD space for optimized updates
data = other->data; // copy everything!
} //!< Called after a move is rejected/accepted as well as before simulation
void to_json(json &j) const override { j = data; }
};
/** @brief Self-energy term of electrostatic potentials */
class SelfEnergy : public Energybase {
private:
std::string type;
double selfenergy_prefactor, epsr, lB, rc;
Tspace &spc;
public:
SelfEnergy(const json &j, Tspace &spc);
double energy(Change &change) override;
};
class Isobaric : public Energybase {
private:
Tspace &spc;
double P; // P/kT
public:
Isobaric(const json &j, Tspace &spc);
double energy(Change &change) override;
void to_json(json &j) const override;
};
/**
* @brief Constrain system using reaction coordinates
*
* If outside specified `range`, infinity energy is returned, causing rejection.
*/
class Constrain : public Energybase {
private:
std::string type;
std::shared_ptr<ReactionCoordinate::ReactionCoordinateBase> rc = nullptr;
public:
Constrain(const json &j, Tspace &spc);
double energy(Change &change) override;
void to_json(json &j) const override;
};
/*
* The keys of the `intra` map are group index and the values
* is a vector of `BondData`. For bonds between groups, fill
* in `inter` which is evaluated for every update of call to
* `energy`.
*
* @todo Optimize.
*/
class Bonded : public Energybase {
private:
Tspace &spc;
typedef typename Tspace::Tpvec Tpvec;
typedef std::vector<std::shared_ptr<Potential::BondData>> BondVector;
BondVector inter; // inter-molecular bonds
std::map<int, BondVector> intra; // intra-molecular bonds
private:
void update_intra(); // finds and adds all intra-molecular bonds of active molecules
double sum_energy(const BondVector &bonds) const; // sum energy in vector of BondData
double sum_energy(const BondVector &bonds, const std::vector<int> &particles_ndx)
const; // sum energy in vector of BondData for matching particle indices
public:
Bonded(const json &j, Tspace &spc);
void to_json(json &j) const override;
double energy(Change &change) override; // brute force -- refine this!
};
/**
* @brief Nonbonded energy using a pair-potential
*/
template <typename Tpairpot> class Nonbonded : public Energybase {
private:
double g2gcnt = 0, g2gskip = 0;
PairMatrix<double> cutoff2; // matrix w. group-to-group cutoff
protected:
typedef typename Tspace::Tpvec Tpvec;
typedef typename Tspace::Tgroup Tgroup;
double Rc2_g2g = pc::infty;
// control of when OpenMP should be used
bool omp_enable = false;
bool omp_i2all = false;
bool omp_g2g = false;
bool omp_p2p = false;
void to_json(json &j) const override {
j["pairpot"] = pairpot;
if (omp_enable) {
json _a = json::array();
if (omp_p2p)
_a.push_back("p2p");
if (omp_g2g)
_a.push_back("g2g");
if (omp_i2all)
_a.push_back("i2all");
j["openmp"] = _a;
}
j["cutoff_g2g"] = json::object();
auto &_j = j["cutoff_g2g"];
for (auto &a : Faunus::molecules)
for (auto &b : Faunus::molecules)
if (a.id() >= b.id())
_j[a.name + " " + b.name] = sqrt(cutoff2(a.id(), b.id()));
}
template <typename T> inline bool cut(const T &g1, const T &g2) {
g2gcnt++;
if (g1.atomic || g2.atomic)
return false;
if (spc.geo.sqdist(g1.cm, g2.cm) < cutoff2(g1.id, g2.id))
return false;
g2gskip++;
return true;
} //!< true if group<->group interaction can be skipped
template <typename T> inline double i2i(const T &a, const T &b) {
assert(&a != &b && "a and b cannot be the same particle");
return pairpot(a, b, spc.geo.vdist(a.pos, b.pos));
}
/*
* Internal energy in group, calculating all with all or, if `index`
* is given, only a subset. Index specifies the internal index (starting
* from zero) of changed particles within the group.
*/
double g_internal(const Tgroup &g, const std::vector<int> &index = std::vector<int>()) {
using namespace ranges;
double u = 0;
if (index.empty() and not molecules.at(g.id).rigid) // assume that all atoms have changed
for (auto i = g.begin(); i != g.end(); ++i)
for (auto j = i; ++j != g.end();)
u += i2i(*i, *j);
else { // only a subset has changed
auto fixed = view::ints(0, int(g.size())) |
view::remove_if([&index](int i) { return std::binary_search(index.begin(), index.end(), i); });
for (int i : index) { // moved<->static
for (int j : fixed) {
u += i2i(*(g.begin() + i), *(g.begin() + j));
}
}
for (int i : index) // moved<->moved
for (int j : index)
if (j > i)
u += i2i(*(g.begin() + i), *(g.begin() + j));
}
return u;
}
/*
* Calculates the interaction energy of a particle, `i`,
* and checks (1) if it is already part of Space, or (2)
* external to space.
*/
double i2all(const typename Tspace::Tparticle &i) {
double u = 0;
auto it = spc.findGroupContaining(i); // iterator to group
if (it != spc.groups.end()) { // check if i belongs to group in space
#pragma omp parallel for reduction(+ : u) if (omp_enable and omp_i2all)
for (size_t ig = 0; ig < spc.groups.size(); ig++) {
auto &g = spc.groups[ig];
if (&g != &(*it)) // avoid self-interaction
if (not cut(g, *it)) // check g2g cut-off
for (auto &j : g) // loop over particles in other group
u += i2i(i, j);
}
for (auto &j : *it) // i with all particles in own group
if (&j != &i)
u += i2i(i, j);
} else // particle does not belong to any group
for (auto &g : spc.groups) // i with all other *active* particles
for (auto &j : g) // (this will include only active particles)
u += i2i(i, j);
return u;
}
/*
* Group-to-group energy. A subset of `g1` can be given with `index` which refers
* to the internal index (starting at zero) of the first group, `g1
* NOTE: the interpretation of this function is extended to also consider the mutual interactions
* of a subset of each group and in such case returns sub1 <-> 2 and !sub1<->sub2,
* hence excluding !sub1 <-> !sub2 in comparision to calling onconstrained g2g. In absence
* of sub1 any sub2 is ignored.
*/
virtual double g2g(const Tgroup &g1, const Tgroup &g2, const std::vector<int> &index = std::vector<int>(),
const std::vector<int> &jndex = std::vector<int>()) {
using namespace ranges;
double u = 0;
if (not cut(g1, g2)) {
if (index.empty() && jndex.empty()) // if index is empty, assume all in g1 have changed
#pragma omp parallel for reduction(+ : u) schedule(dynamic) if (omp_enable and omp_p2p)
for (size_t i = 0; i < g1.size(); i++)
for (size_t j = 0; j < g2.size(); j++)
u += i2i(*(g1.begin() + i), *(g2.begin() + j));
else { // only a subset of g1
for (auto i : index)
for (auto j = g2.begin(); j != g2.end(); ++j)
u += i2i(*(g1.begin() + i), *j);
if (not jndex.empty()) {
auto fixed = view::ints(0, int(g1.size())) | view::remove_if([&index](int i) {
return std::binary_search(index.begin(), index.end(), i);
});
for (auto i : jndex) // moved2 <-|
for (auto j : fixed) // static1 <-|
u += i2i(*(g2.begin() + i), *(g1.begin() + j));
}
}
}
return u;
}
public:
Tspace &spc; //!< Space to operate on
Tpairpot pairpot; //!< Pair potential
Nonbonded(const json &j, Tspace &spc) : spc(spc) {
name = "nonbonded";
pairpot = j;
// controls for OpenMP
auto it = j.find("openmp");
if (it != j.end())
if (it->is_array())
if (it->size() > 0) {
omp_enable = true;
for (const std::string &k : *it)
if (k == "g2g")
omp_g2g = true;
else if (k == "p2p")
omp_p2p = true;
else if (k == "i2all")
omp_i2all = true;
#ifndef _OPENMP
std::cerr << "warning: nonbonded requests unavailable OpenMP." << endl;
#endif
}
// disable all group-to-group cutoffs by setting infinity
for (auto &i : Faunus::molecules)
for (auto &j : Faunus::molecules)
cutoff2.set(i.id(), j.id(), pc::infty);
it = j.find("cutoff_g2g");
if (it != j.end()) {
// old style input w. only a single cutoff
if (it->is_number()) {
Rc2_g2g = std::pow(it->get<double>(), 2);
for (auto &i : Faunus::molecules)
for (auto &j : Faunus::molecules)
cutoff2.set(i.id(), j.id(), Rc2_g2g);
}
// new style input w. multiple cutoffs between molecules
else if (it->is_object()) {
// ensure that there is a default, fallback cutoff
Rc2_g2g = std::pow(it->at("default").get<double>(), 2);
for (auto &i : Faunus::molecules)
for (auto &j : Faunus::molecules)
cutoff2.set(i.id(), j.id(), Rc2_g2g);
// loop for space separated molecule pairs in keys
for (auto &i : it->items()) {
auto v = words2vec<std::string>(i.key());
if (v.size() == 2) {
int id1 = (*findName(Faunus::molecules, v[0])).id();
int id2 = (*findName(Faunus::molecules, v[1])).id();
cutoff2.set(id1, id2, std::pow(i.value().get<double>(), 2));
}
}
}
}
}
void force(std::vector<Point> &forces) override {
auto &p = spc.p; // alias to particle vector (reference)
assert(forces.size() == p.size() && "the forces size must match the particle size");
for (size_t i = 0; i < p.size() - 1; i++)
for (size_t j = i + 1; j < p.size(); j++) {
// Point r = spc.geo.vdist(p[i].pos, p[j].pos); // minimum distance vector
Point f; //= pairpot.force( p[i], p[j], r.squaredNorm(), r );
forces[i] += f;
forces[j] -= f;
}
}
double energy(Change &change) override {
using namespace ranges;
double u = 0;
if (change) {
if (change.dV) {
#pragma omp parallel for reduction(+ : u) schedule(dynamic) if (omp_enable and omp_g2g)
for (auto i = spc.groups.begin(); i < spc.groups.end(); ++i) {
for (auto j = i; ++j != spc.groups.end();)
u += g2g(*i, *j);
if (i->atomic)
u += g_internal(*i);
}
return u;
}
// did everything change?
if (change.all) {
#pragma omp parallel for reduction(+ : u) schedule(dynamic) if (omp_enable and omp_g2g)
for (auto i = spc.groups.begin(); i < spc.groups.end(); ++i) {
for (auto j = i; ++j != spc.groups.end();)
u += g2g(*i, *j);
u += g_internal(*i);
}
// more todo here...
return u;
}
// if exactly ONE molecule is changed
if (change.groups.size() == 1 && not change.dN) {
auto &d = change.groups[0];
auto gindex = spc.groups.at(d.index).to_index(spc.p.begin()).first;
// exactly one atom has move
if (d.atoms.size() == 1)
return i2all(spc.p.at(gindex + d.atoms[0]));
// more atoms moved
auto &g1 = spc.groups.at(d.index);
// for (auto &g2 : spc.groups)
#pragma omp parallel for reduction(+ : u) schedule(dynamic) if (omp_enable and omp_g2g)
for (size_t i = 0; i < spc.groups.size(); i++) {
auto &g2 = spc.groups[i];
if (&g1 != &g2)
u += g2g(g1, g2, d.atoms);
}
if (d.internal)
u += g_internal(g1, d.atoms);
return u;
}
auto moved = change.touchedGroupIndex(); // index of moved groups
auto fixed = view::ints(0, int(spc.groups.size())) | view::remove_if([&moved](int i) {
return std::binary_search(moved.begin(), moved.end(), i);
}); // index of static groups
if (change.dN) {
/*auto moved = change.touchedGroupIndex(); // index of moved groups
std::vector<int> Moved;
for (auto i: moved) {
Moved.push_back(i);
}
std::sort( Moved.begin(), Moved.end() );
auto fixed = view::ints( 0, int(spc.groups.size()) )
| view::remove_if(
[&Moved](int i){return std::binary_search(Moved.begin(), Moved.end(), i);}
); // index of static groups*/
for (auto cg1 = change.groups.begin(); cg1 < change.groups.end();
++cg1) { // Loop over all changed groups
std::vector<int> ifiltered, jfiltered; // Active atoms
auto g1 = &spc.groups.at(cg1->index);
for (auto i : cg1->atoms) {
if (i < g1->size())
ifiltered.push_back(i);
}
// Skip if the group is empty
if (not ifiltered.empty())
for (auto j : fixed)
u += g2g(*g1, spc.groups[j], ifiltered, jfiltered);
for (auto cg2 = cg1; ++cg2 != change.groups.end();) {
for (auto i : cg2->atoms)
if (i < spc.groups.at(cg2->index).size())
jfiltered.push_back(i);
// Skip if both groups are empty
if (not(ifiltered.empty() && jfiltered.empty()))
u += g2g(*g1, spc.groups.at(cg2->index), ifiltered, jfiltered);
jfiltered.clear();
}
if (not ifiltered.empty() and not molecules.at(g1->id).rigid) {
if (cg1->all) {
u += g_internal(*g1);
} else
u += g_internal(*g1, ifiltered);
}
}
return u;
}
// moved<->moved
if (change.moved2moved) {
for (auto i = moved.begin(); i != moved.end(); ++i)
for (auto j = i; ++j != moved.end();)
u += g2g(spc.groups[*i], spc.groups[*j]);
}
// moved<->static
if (omp_enable and omp_g2g) {
std::vector<std::pair<int, int>> pairs(size(moved) * size(fixed));
size_t cnt = 0;
for (auto i : moved)
for (auto j : fixed)
pairs[cnt++] = {i, j};
#pragma omp parallel for reduction(+ : u) schedule(dynamic) if (omp_enable and omp_g2g)
for (size_t i = 0; i < pairs.size(); i++)
u += g2g(spc.groups[pairs[i].first], spc.groups[pairs[i].second]);
} else
for (auto i : moved)
for (auto j : fixed)
u += g2g(spc.groups[i], spc.groups[j]);
// more todo!
}
return u;
}
}; //!< Nonbonded, pair-wise additive energy term
template <typename Tpairpot> class NonbondedCached : public Nonbonded<Tpairpot> {
private:
typedef Nonbonded<Tpairpot> base;
typedef typename Tspace::Tgroup Tgroup;
Eigen::MatrixXf cache;
Tspace &spc;
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wunused-parameter"
double g2g(const Tgroup &g1, const Tgroup &g2, const std::vector<int> &index = std::vector<int>(),
const std::vector<int> &jndex = std::vector<int>()) override {
#pragma GCC diagnostic pop
int i = &g1 - &base::spc.groups.front();
int j = &g2 - &base::spc.groups.front();
if (j < i)
std::swap(i, j);
if (base::key == Energybase::NEW) { // if this is from the trial system,
double u = 0;
if (not base::cut(g1, g2)) {
for (auto &i : g1)
for (auto &j : g2)
u += base::i2i(i, j);
}
cache(i, j) = u;
}
return cache(i, j); // return (cached) value
}
public:
NonbondedCached(const json &j, Tspace &spc) : base(j, spc), spc(spc) {
base::name += "EM";
init();
}
void init() override {
cache.resize(spc.groups.size(), spc.groups.size());
cache.setZero();
for (auto i = base::spc.groups.begin(); i < base::spc.groups.end(); ++i) {
for (auto j = i; ++j != base::spc.groups.end();) {
int k = &(*i) - &base::spc.groups.front();
int l = &(*j) - &base::spc.groups.front();
if (l < k)
std::swap(k, l);
double u = 0;
if (!base::cut(*i, *j)) {
for (auto &k : *i)
for (auto &l : *j)
u += base::i2i(k, l);
}
cache(k, l) = u;
}
}
} //!< Cache pair interactions in matrix
double energy(Change &change) override {
using namespace ranges;
double u = 0;
if (change) {
if (change.all || change.dV) {
#pragma omp parallel for reduction(+ : u) schedule(dynamic) if (this->omp_enable)
for (auto i = base::spc.groups.begin(); i < base::spc.groups.end(); ++i) {
for (auto j = i; ++j != base::spc.groups.end();)
u += g2g(*i, *j);
}
return u;
}
// if exactly ONE molecule is changed
if (change.groups.size() == 1) {
auto &d = change.groups[0];
auto &g1 = base::spc.groups.at(d.index);
#pragma omp parallel for reduction(+ : u) schedule(dynamic) if (this->omp_enable and this->omp_g2g)
for (size_t i = 0; i < spc.groups.size(); i++) {
auto &g2 = spc.groups[i];
if (&g1 != &g2)
u += g2g(g1, g2, d.atoms);
}
return u;
}
auto moved = change.touchedGroupIndex(); // index of moved groups
auto fixed = view::ints(0, int(base::spc.groups.size())) | view::remove_if([&moved](int i) {
return std::binary_search(moved.begin(), moved.end(), i);
}); // index of static groups
// moved<->moved
if (change.moved2moved)
for (auto i = moved.begin(); i != moved.end(); ++i)
for (auto j = i; ++j != moved.end();)
u += g2g(base::spc.groups[*i], base::spc.groups[*j]);
// moved<->static
if (this->omp_enable and this->omp_g2g) {
std::vector<std::pair<int, int>> pairs(size(moved) * size(fixed));
size_t cnt = 0;
for (auto i : moved)
for (auto j : fixed)
pairs[cnt++] = {i, j};
#pragma omp parallel for reduction(+ : u) schedule(dynamic) if (this->omp_enable and this->omp_g2g)
for (size_t i = 0; i < pairs.size(); i++)
u += g2g(spc.groups[pairs[i].first], spc.groups[pairs[i].second]);
} else
for (auto i : moved)
for (auto j : fixed)
u += g2g(base::spc.groups[i], base::spc.groups[j]);
// more todo!
}
return u;
}
void sync(Energybase *basePtr, Change &change) override {
auto other = dynamic_cast<decltype(this)>(basePtr);
assert(other);
if (change.all || change.dV)
cache.triangularView<Eigen::StrictlyUpper>() =
(other->cache).template triangularView<Eigen::StrictlyUpper>();
else
for (auto &d : change.groups) {
for (int i = 0; i < d.index; i++)
cache(i, d.index) = other->cache(i, d.index);
for (size_t i = d.index + 1; i < base::spc.groups.size(); i++)
cache(d.index, i) = other->cache(d.index, i);
}
} //!< Copy energy matrix from other
}; //!< Nonbonded with cached energies (Energy Matrix)
#ifdef ENABLE_POWERSASA
/*
* @todo:
* - can only a subset of sasa be calculated? Note that it's the
* `update_coord()` function that takes up most time.
* - delegate to GPU? In the PowerSasa paper this is mentioned
*/
class SASAEnergy : public Energybase {
public:
std::vector<float> sasa, radii;
private:
typedef typename Tspace::Tpvec Tpvec;
Tspace &spc;
double probe; // sasa probe radius (angstrom)
double conc = 0; // co-solute concentration (mol/l)
Average<double> avgArea; // average surface area
std::shared_ptr<POWERSASA::PowerSasa<float, Point>> ps = nullptr;
void updateSASA(const Tpvec &p);
void to_json(json &j) const override;
/*
* @note
* This is not enough as the PowerSasa object contains data
* that also need syncing. It works due to the `update` (expensive!)
* call in `energy`.
*/
void sync(Energybase *basePtr, Change &c) override;
public:
SASAEnergy(const json &j, Tspace &spc);
void init() override;
double energy(Change &) override;
}; //!< SASA energy from transfer free energies
#endif
struct Example2D : public Energybase {
Point &i; // reference to 1st particle in the system
Example2D(const json &, Tspace &spc);
double energy(Change &change) override;
};
class Hamiltonian : public Energybase, public BasePointerVector<Energybase> {
protected:
double maxenergy = pc::infty; //!< Maximum allowed energy change
void to_json(json &j) const override;
void addEwald(const json &j, Tspace &spc); //!< Adds an instance of reciprocal space Ewald energies (if appropriate)
void
addSelfEnergy(const json &j,
Tspace &spc); //!< Adds an instance of the self term of the electrostatic potential (if appropriate)
public:
Hamiltonian(Tspace &spc, const json &j);
double energy(Change &change) override; //!< Energy due to changes
void init() override;
void sync(Energybase *basePtr, Change &change) override;
}; //!< Aggregates and sum energy terms
} // namespace Energy
} // namespace Faunus
|
GB_unaryop__identity_bool_int8.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_bool_int8
// op(A') function: GB_tran__identity_bool_int8
// C type: bool
// A type: int8_t
// cast: bool cij = (bool) aij
// unaryop: cij = aij
#define GB_ATYPE \
int8_t
#define GB_CTYPE \
bool
// 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_CASTING(z, aij) \
bool z = (bool) aij ;
// cij = op (cast (aij))
#define GB_CAST_OP(pC,pA) \
{ \
/* aij = Ax [pA] */ \
GB_GETA (aij, Ax, pA) ; \
/* Cx [pC] = op (cast (aij)) */ \
GB_CASTING (z, aij) ; \
GB_OP (GB_CX (pC), z) ; \
}
// disable this operator and use the generic case if these conditions hold
#define GB_DISABLE \
(GxB_NO_IDENTITY || GxB_NO_BOOL || GxB_NO_INT8)
//------------------------------------------------------------------------------
// Cx = op (cast (Ax)): apply a unary operator
//------------------------------------------------------------------------------
GrB_Info GB_unop__identity_bool_int8
(
bool *Cx, // Cx and Ax may be aliased
int8_t *Ax,
int64_t anz,
int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
int64_t p ;
#pragma omp parallel for num_threads(nthreads) schedule(static)
for (p = 0 ; p < anz ; p++)
{
GB_CAST_OP (p, p) ;
}
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// C = op (cast (A')): transpose, typecast, and apply a unary operator
//------------------------------------------------------------------------------
GrB_Info GB_tran__identity_bool_int8
(
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
|
GB_binop__iseq_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__iseq_uint16)
// A.*B function (eWiseMult): GB (_AemultB)
// A.*B function (eWiseMult): GB (_AemultB_02__iseq_uint16)
// A.*B function (eWiseMult): GB (_AemultB_03__iseq_uint16)
// A.*B function (eWiseMult): GB (_AemultB_bitmap__iseq_uint16)
// A*D function (colscale): GB (_AxD__iseq_uint16)
// D*A function (rowscale): GB (_DxB__iseq_uint16)
// C+=B function (dense accum): GB (_Cdense_accumB__iseq_uint16)
// C+=b function (dense accum): GB (_Cdense_accumb__iseq_uint16)
// C+=A+B function (dense ewise3): GB ((none))
// C=A+B function (dense ewise3): GB (_Cdense_ewise3_noaccum__iseq_uint16)
// C=scalar+B GB (_bind1st__iseq_uint16)
// C=scalar+B' GB (_bind1st_tran__iseq_uint16)
// C=A+scalar GB (_bind2nd__iseq_uint16)
// C=A'+scalar GB (_bind2nd_tran__iseq_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, i, j) \
z = (x == y) ;
// true if the binop must be flipped
#define GB_BINOP_FLIP \
0
// op is second
#define GB_OP_IS_SECOND \
0
// do the numerical phases of GB_add and GB_emult
#define GB_PHASE_2_OF_2
// hard-coded loops can be vectorized
#define GB_PRAGMA_SIMD_VECTORIZE GB_PRAGMA_SIMD
// disable this operator and use the generic case if these conditions hold
#define GB_DISABLE \
(GxB_NO_ISEQ || GxB_NO_UINT16 || GxB_NO_ISEQ_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__iseq_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__iseq_uint16)
(
GrB_Matrix C,
const GrB_Matrix B,
const int64_t *B_ek_slicing, const int B_ntasks, const int B_nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
{
#include "GB_dense_subassign_23_template.c"
}
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// C += b, accumulate a scalar into a dense matrix
//------------------------------------------------------------------------------
GrB_Info GB (_Cdense_accumb__iseq_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__iseq_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
uint16_t *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__iseq_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 *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__iseq_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__iseq_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__iseq_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__iseq_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__iseq_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__iseq_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
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++)
{
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__iseq_uint16)
(
GB_void *Cx_output, // Cx and Ax may be aliased
const GB_void *Ax_input,
const GB_void *y_input,
const int8_t *restrict Ab,
int64_t anz,
int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
int64_t p ;
uint16_t *Cx = (uint16_t *) Cx_output ;
uint16_t *Ax = (uint16_t *) Ax_input ;
uint16_t y = (*((uint16_t *) y_input)) ;
#pragma omp parallel for num_threads(nthreads) schedule(static)
for (p = 0 ; p < anz ; p++)
{
if (!GBB (Ab, p)) continue ;
uint16_t aij = 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__iseq_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__iseq_uint16)
(
GrB_Matrix C,
const GrB_Matrix A,
const GB_void *y_input,
int64_t *restrict *Workspaces,
const int64_t *restrict A_slice,
int nworkspaces,
int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
uint16_t y = (*((const uint16_t *) y_input)) ;
#include "GB_unop_transpose.c"
return (GrB_SUCCESS) ;
#endif
}
#endif
|
GB_subassign_04.c | //------------------------------------------------------------------------------
// GB_subassign_04: C(I,J) += A ; using S
//------------------------------------------------------------------------------
// SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2020, All Rights Reserved.
// http://suitesparse.com See GraphBLAS/Doc/License.txt for license.
//------------------------------------------------------------------------------
// Method 04: C(I,J) += A ; using S
// M: NULL
// Mask_comp: false
// C_replace: false
// accum: present
// A: matrix
// S: constructed
#define GB_FREE_WORK GB_FREE_TWO_SLICE
#include "GB_subassign_methods.h"
GrB_Info GB_subassign_04
(
GrB_Matrix C,
// input:
const GrB_Index *I,
const int64_t nI,
const int Ikind,
const int64_t Icolon [3],
const GrB_Index *J,
const int64_t nJ,
const int Jkind,
const int64_t Jcolon [3],
const GrB_BinaryOp accum,
const GrB_Matrix A,
const GrB_Matrix S,
GB_Context Context
)
{
//--------------------------------------------------------------------------
// get inputs
//--------------------------------------------------------------------------
GB_GET_C ;
GB_GET_A ;
GB_GET_S ;
GB_GET_ACCUM ;
//--------------------------------------------------------------------------
// Method 04: C(I,J) += A ; using S
//--------------------------------------------------------------------------
// Time: Close to Optimal. Every entry in A must be visited, and the
// corresponding entry in S must then be found. Time for this phase is
// Omega(nnz(A)), but S has already been constructed, in Omega(nnz(S))
// time. This method simply traverses all of A+S (like GB_add for
// computing A+S), the same as Method 02. Time taken is O(nnz(A)+nnz(S)).
// The only difference is that the traversal of A+S can terminate if A is
// exhausted. Entries in S but not A do not actually require any work
// (unlike Method 02, which must visit all entries in A+S).
// Method 02 and Method 04 are somewhat similar. They differ on how C is
// modified when the entry is present in S but not A.
// Compare with Method 16, which computes C(I,J)<!M> += A, using S.
//--------------------------------------------------------------------------
// Parallel: Z=A+S (Methods 02, 04, 09, 10, 11, 12, 14, 16, 18, 20)
//--------------------------------------------------------------------------
GB_SUBASSIGN_TWO_SLICE (A, S) ;
//--------------------------------------------------------------------------
// phase 1: create zombies, update entries, and count pending tuples
//--------------------------------------------------------------------------
int taskid ;
#pragma omp parallel for num_threads(nthreads) schedule(dynamic,1) \
reduction(+:nzombies)
for (taskid = 0 ; taskid < ntasks ; taskid++)
{
//----------------------------------------------------------------------
// get the task descriptor
//----------------------------------------------------------------------
GB_GET_TASK_DESCRIPTOR_PHASE1 ;
//----------------------------------------------------------------------
// compute all vectors in this task
//----------------------------------------------------------------------
for (int64_t k = kfirst ; k <= klast ; k++)
{
//------------------------------------------------------------------
// get A(:,j) and S(:,j)
//------------------------------------------------------------------
int64_t j = (Zh == NULL) ? k : Zh [k] ;
GB_GET_MAPPED_VECTOR (pA, pA_end, pA, pA_end, Ap, j, k, Z_to_X) ;
GB_GET_MAPPED_VECTOR (pS, pS_end, pB, pB_end, Sp, j, k, Z_to_S) ;
//------------------------------------------------------------------
// do a 2-way merge of S(:,j) and A(:,j)
//------------------------------------------------------------------
// jC = J [j] ; or J is a colon expression
// int64_t jC = GB_ijlist (J, j, Jkind, Jcolon) ;
// while both list S (:,j) and A (:,j) have entries
while (pS < pS_end && pA < pA_end)
{
int64_t iS = Si [pS] ;
int64_t iA = Ai [pA] ;
if (iS < iA)
{
// ----[C . 1] or [X . 1]-----------------------------------
// S (i,j) is present but A (i,j) is not
// [C . 1]: action: ( C ): no change, with accum
// [X . 1]: action: ( X ): still a zombie
GB_NEXT (S) ;
}
else if (iA < iS)
{
// ----[. A 1]----------------------------------------------
// S (i,j) is not present, A (i,j) is present
// [. A 1]: action: ( insert )
task_pending++ ;
GB_NEXT (A) ;
}
else
{
// ----[C A 1] or [X A 1]-----------------------------------
// both S (i,j) and A (i,j) present
// [C A 1]: action: ( =C+A ): apply accum
// [X A 1]: action: ( undelete ): zombie lives
GB_C_S_LOOKUP ;
GB_withaccum_C_A_1_matrix ;
GB_NEXT (S) ;
GB_NEXT (A) ;
}
}
// ignore the remainder of S (:,j)
// List A (:,j) has entries. List S (:,j) exhausted.
task_pending += (pA_end - pA) ;
}
GB_PHASE1_TASK_WRAPUP ;
}
//--------------------------------------------------------------------------
// phase 2: insert pending tuples
//--------------------------------------------------------------------------
GB_PENDING_CUMSUM ;
#pragma omp parallel for num_threads(nthreads) schedule(dynamic,1) \
reduction(&&:pending_sorted)
for (taskid = 0 ; taskid < ntasks ; taskid++)
{
//----------------------------------------------------------------------
// get the task descriptor
//----------------------------------------------------------------------
GB_GET_TASK_DESCRIPTOR_PHASE2 ;
//----------------------------------------------------------------------
// compute all vectors in this task
//----------------------------------------------------------------------
for (int64_t k = kfirst ; k <= klast ; k++)
{
//------------------------------------------------------------------
// get A(:,j) and S(:,j)
//------------------------------------------------------------------
int64_t j = (Zh == NULL) ? k : Zh [k] ;
GB_GET_MAPPED_VECTOR (pA, pA_end, pA, pA_end, Ap, j, k, Z_to_X) ;
GB_GET_MAPPED_VECTOR (pS, pS_end, pB, pB_end, Sp, j, k, Z_to_S) ;
//------------------------------------------------------------------
// do a 2-way merge of S(:,j) and A(:,j)
//------------------------------------------------------------------
// jC = J [j] ; or J is a colon expression
int64_t jC = GB_ijlist (J, j, Jkind, Jcolon) ;
// while both list S (:,j) and A (:,j) have entries
while (pS < pS_end && pA < pA_end)
{
int64_t iS = Si [pS] ;
int64_t iA = Ai [pA] ;
if (iS < iA)
{
GB_NEXT (S) ;
}
else if (iA < iS)
{
// ----[. A 1]----------------------------------------------
// S (i,j) is not present, A (i,j) is present
// [. A 1]: action: ( insert )
int64_t iC = GB_ijlist (I, iA, Ikind, Icolon) ;
GB_PENDING_INSERT (Ax +(pA*asize)) ;
GB_NEXT (A) ;
}
else
{
GB_NEXT (S) ;
GB_NEXT (A) ;
}
}
// ignore the remainder of S (:,j)
// while list A (:,j) has entries. List S (:,j) exhausted.
while (pA < pA_end)
{
// ----[. A 1]--------------------------------------------------
// S (i,j) is not present, A (i,j) is present
// [. A 1]: action: ( insert )
int64_t iA = Ai [pA] ;
int64_t iC = GB_ijlist (I, iA, Ikind, Icolon) ;
GB_PENDING_INSERT (Ax +(pA*asize)) ;
GB_NEXT (A) ;
}
}
GB_PHASE2_TASK_WRAPUP ;
}
//--------------------------------------------------------------------------
// finalize the matrix and return result
//--------------------------------------------------------------------------
GB_SUBASSIGN_WRAPUP ;
}
|
dds.c | /*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% DDDD DDDD SSSSS %
% D D D D SS %
% D D D D SSS %
% D D D D SS %
% DDDD DDDD SSSSS %
% %
% %
% Read/Write Microsoft Direct Draw Surface Image Format %
% %
% Software Design %
% Bianca van Schaik %
% March 2008 %
% Dirk Lemstra %
% September 2013 %
% %
% %
% 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://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/attribute.h"
#include "magick/blob.h"
#include "magick/blob-private.h"
#include "magick/cache.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/list.h"
#include "magick/log.h"
#include "magick/magick.h"
#include "magick/memory_.h"
#include "magick/monitor.h"
#include "magick/monitor-private.h"
#include "magick/option.h"
#include "magick/pixel-accessor.h"
#include "magick/profile.h"
#include "magick/quantum.h"
#include "magick/quantum-private.h"
#include "magick/resource_.h"
#include "magick/static.h"
#include "magick/string_.h"
#include "magick/string-private.h"
#include "magick/module.h"
#include "magick/transform.h"
/*
Definitions
*/
#define DDSD_CAPS 0x00000001
#define DDSD_HEIGHT 0x00000002
#define DDSD_WIDTH 0x00000004
#define DDSD_PITCH 0x00000008
#define DDSD_PIXELFORMAT 0x00001000
#define DDSD_MIPMAPCOUNT 0x00020000
#define DDSD_LINEARSIZE 0x00080000
#define DDSD_DEPTH 0x00800000
#define DDPF_ALPHAPIXELS 0x00000001
#define DDPF_FOURCC 0x00000004
#define DDPF_RGB 0x00000040
#define DDPF_LUMINANCE 0x00020000
#define FOURCC_DXT1 0x31545844
#define FOURCC_DXT3 0x33545844
#define FOURCC_DXT5 0x35545844
#define DDSCAPS_COMPLEX 0x00000008
#define DDSCAPS_TEXTURE 0x00001000
#define DDSCAPS_MIPMAP 0x00400000
#define DDSCAPS2_CUBEMAP 0x00000200
#define DDSCAPS2_CUBEMAP_POSITIVEX 0x00000400
#define DDSCAPS2_CUBEMAP_NEGATIVEX 0x00000800
#define DDSCAPS2_CUBEMAP_POSITIVEY 0x00001000
#define DDSCAPS2_CUBEMAP_NEGATIVEY 0x00002000
#define DDSCAPS2_CUBEMAP_POSITIVEZ 0x00004000
#define DDSCAPS2_CUBEMAP_NEGATIVEZ 0x00008000
#define DDSCAPS2_VOLUME 0x00200000
#ifndef SIZE_MAX
#define SIZE_MAX ((size_t) -1)
#endif
/*
Structure declarations.
*/
typedef struct _DDSPixelFormat
{
size_t
flags,
fourcc,
rgb_bitcount,
r_bitmask,
g_bitmask,
b_bitmask,
alpha_bitmask;
} DDSPixelFormat;
typedef struct _DDSInfo
{
size_t
flags,
height,
width,
pitchOrLinearSize,
depth,
mipmapcount,
ddscaps1,
ddscaps2;
DDSPixelFormat
pixelformat;
} DDSInfo;
typedef struct _DDSColors
{
unsigned char
r[4],
g[4],
b[4],
a[4];
} DDSColors;
typedef struct _DDSVector4
{
float
x,
y,
z,
w;
} DDSVector4;
typedef struct _DDSVector3
{
float
x,
y,
z;
} DDSVector3;
typedef struct _DDSSourceBlock
{
unsigned char
start,
end,
error;
} DDSSourceBlock;
typedef struct _DDSSingleColourLookup
{
DDSSourceBlock sources[2];
} DDSSingleColourLookup;
typedef MagickBooleanType
DDSDecoder(Image *, DDSInfo *, ExceptionInfo *);
static const DDSSingleColourLookup DDSLookup_5_4[] =
{
{ { { 0, 0, 0 }, { 0, 0, 0 } } },
{ { { 0, 0, 1 }, { 0, 1, 1 } } },
{ { { 0, 0, 2 }, { 0, 1, 0 } } },
{ { { 0, 0, 3 }, { 0, 1, 1 } } },
{ { { 0, 0, 4 }, { 0, 2, 1 } } },
{ { { 1, 0, 3 }, { 0, 2, 0 } } },
{ { { 1, 0, 2 }, { 0, 2, 1 } } },
{ { { 1, 0, 1 }, { 0, 3, 1 } } },
{ { { 1, 0, 0 }, { 0, 3, 0 } } },
{ { { 1, 0, 1 }, { 1, 2, 1 } } },
{ { { 1, 0, 2 }, { 1, 2, 0 } } },
{ { { 1, 0, 3 }, { 0, 4, 0 } } },
{ { { 1, 0, 4 }, { 0, 5, 1 } } },
{ { { 2, 0, 3 }, { 0, 5, 0 } } },
{ { { 2, 0, 2 }, { 0, 5, 1 } } },
{ { { 2, 0, 1 }, { 0, 6, 1 } } },
{ { { 2, 0, 0 }, { 0, 6, 0 } } },
{ { { 2, 0, 1 }, { 2, 3, 1 } } },
{ { { 2, 0, 2 }, { 2, 3, 0 } } },
{ { { 2, 0, 3 }, { 0, 7, 0 } } },
{ { { 2, 0, 4 }, { 1, 6, 1 } } },
{ { { 3, 0, 3 }, { 1, 6, 0 } } },
{ { { 3, 0, 2 }, { 0, 8, 0 } } },
{ { { 3, 0, 1 }, { 0, 9, 1 } } },
{ { { 3, 0, 0 }, { 0, 9, 0 } } },
{ { { 3, 0, 1 }, { 0, 9, 1 } } },
{ { { 3, 0, 2 }, { 0, 10, 1 } } },
{ { { 3, 0, 3 }, { 0, 10, 0 } } },
{ { { 3, 0, 4 }, { 2, 7, 1 } } },
{ { { 4, 0, 4 }, { 2, 7, 0 } } },
{ { { 4, 0, 3 }, { 0, 11, 0 } } },
{ { { 4, 0, 2 }, { 1, 10, 1 } } },
{ { { 4, 0, 1 }, { 1, 10, 0 } } },
{ { { 4, 0, 0 }, { 0, 12, 0 } } },
{ { { 4, 0, 1 }, { 0, 13, 1 } } },
{ { { 4, 0, 2 }, { 0, 13, 0 } } },
{ { { 4, 0, 3 }, { 0, 13, 1 } } },
{ { { 4, 0, 4 }, { 0, 14, 1 } } },
{ { { 5, 0, 3 }, { 0, 14, 0 } } },
{ { { 5, 0, 2 }, { 2, 11, 1 } } },
{ { { 5, 0, 1 }, { 2, 11, 0 } } },
{ { { 5, 0, 0 }, { 0, 15, 0 } } },
{ { { 5, 0, 1 }, { 1, 14, 1 } } },
{ { { 5, 0, 2 }, { 1, 14, 0 } } },
{ { { 5, 0, 3 }, { 0, 16, 0 } } },
{ { { 5, 0, 4 }, { 0, 17, 1 } } },
{ { { 6, 0, 3 }, { 0, 17, 0 } } },
{ { { 6, 0, 2 }, { 0, 17, 1 } } },
{ { { 6, 0, 1 }, { 0, 18, 1 } } },
{ { { 6, 0, 0 }, { 0, 18, 0 } } },
{ { { 6, 0, 1 }, { 2, 15, 1 } } },
{ { { 6, 0, 2 }, { 2, 15, 0 } } },
{ { { 6, 0, 3 }, { 0, 19, 0 } } },
{ { { 6, 0, 4 }, { 1, 18, 1 } } },
{ { { 7, 0, 3 }, { 1, 18, 0 } } },
{ { { 7, 0, 2 }, { 0, 20, 0 } } },
{ { { 7, 0, 1 }, { 0, 21, 1 } } },
{ { { 7, 0, 0 }, { 0, 21, 0 } } },
{ { { 7, 0, 1 }, { 0, 21, 1 } } },
{ { { 7, 0, 2 }, { 0, 22, 1 } } },
{ { { 7, 0, 3 }, { 0, 22, 0 } } },
{ { { 7, 0, 4 }, { 2, 19, 1 } } },
{ { { 8, 0, 4 }, { 2, 19, 0 } } },
{ { { 8, 0, 3 }, { 0, 23, 0 } } },
{ { { 8, 0, 2 }, { 1, 22, 1 } } },
{ { { 8, 0, 1 }, { 1, 22, 0 } } },
{ { { 8, 0, 0 }, { 0, 24, 0 } } },
{ { { 8, 0, 1 }, { 0, 25, 1 } } },
{ { { 8, 0, 2 }, { 0, 25, 0 } } },
{ { { 8, 0, 3 }, { 0, 25, 1 } } },
{ { { 8, 0, 4 }, { 0, 26, 1 } } },
{ { { 9, 0, 3 }, { 0, 26, 0 } } },
{ { { 9, 0, 2 }, { 2, 23, 1 } } },
{ { { 9, 0, 1 }, { 2, 23, 0 } } },
{ { { 9, 0, 0 }, { 0, 27, 0 } } },
{ { { 9, 0, 1 }, { 1, 26, 1 } } },
{ { { 9, 0, 2 }, { 1, 26, 0 } } },
{ { { 9, 0, 3 }, { 0, 28, 0 } } },
{ { { 9, 0, 4 }, { 0, 29, 1 } } },
{ { { 10, 0, 3 }, { 0, 29, 0 } } },
{ { { 10, 0, 2 }, { 0, 29, 1 } } },
{ { { 10, 0, 1 }, { 0, 30, 1 } } },
{ { { 10, 0, 0 }, { 0, 30, 0 } } },
{ { { 10, 0, 1 }, { 2, 27, 1 } } },
{ { { 10, 0, 2 }, { 2, 27, 0 } } },
{ { { 10, 0, 3 }, { 0, 31, 0 } } },
{ { { 10, 0, 4 }, { 1, 30, 1 } } },
{ { { 11, 0, 3 }, { 1, 30, 0 } } },
{ { { 11, 0, 2 }, { 4, 24, 0 } } },
{ { { 11, 0, 1 }, { 1, 31, 1 } } },
{ { { 11, 0, 0 }, { 1, 31, 0 } } },
{ { { 11, 0, 1 }, { 1, 31, 1 } } },
{ { { 11, 0, 2 }, { 2, 30, 1 } } },
{ { { 11, 0, 3 }, { 2, 30, 0 } } },
{ { { 11, 0, 4 }, { 2, 31, 1 } } },
{ { { 12, 0, 4 }, { 2, 31, 0 } } },
{ { { 12, 0, 3 }, { 4, 27, 0 } } },
{ { { 12, 0, 2 }, { 3, 30, 1 } } },
{ { { 12, 0, 1 }, { 3, 30, 0 } } },
{ { { 12, 0, 0 }, { 4, 28, 0 } } },
{ { { 12, 0, 1 }, { 3, 31, 1 } } },
{ { { 12, 0, 2 }, { 3, 31, 0 } } },
{ { { 12, 0, 3 }, { 3, 31, 1 } } },
{ { { 12, 0, 4 }, { 4, 30, 1 } } },
{ { { 13, 0, 3 }, { 4, 30, 0 } } },
{ { { 13, 0, 2 }, { 6, 27, 1 } } },
{ { { 13, 0, 1 }, { 6, 27, 0 } } },
{ { { 13, 0, 0 }, { 4, 31, 0 } } },
{ { { 13, 0, 1 }, { 5, 30, 1 } } },
{ { { 13, 0, 2 }, { 5, 30, 0 } } },
{ { { 13, 0, 3 }, { 8, 24, 0 } } },
{ { { 13, 0, 4 }, { 5, 31, 1 } } },
{ { { 14, 0, 3 }, { 5, 31, 0 } } },
{ { { 14, 0, 2 }, { 5, 31, 1 } } },
{ { { 14, 0, 1 }, { 6, 30, 1 } } },
{ { { 14, 0, 0 }, { 6, 30, 0 } } },
{ { { 14, 0, 1 }, { 6, 31, 1 } } },
{ { { 14, 0, 2 }, { 6, 31, 0 } } },
{ { { 14, 0, 3 }, { 8, 27, 0 } } },
{ { { 14, 0, 4 }, { 7, 30, 1 } } },
{ { { 15, 0, 3 }, { 7, 30, 0 } } },
{ { { 15, 0, 2 }, { 8, 28, 0 } } },
{ { { 15, 0, 1 }, { 7, 31, 1 } } },
{ { { 15, 0, 0 }, { 7, 31, 0 } } },
{ { { 15, 0, 1 }, { 7, 31, 1 } } },
{ { { 15, 0, 2 }, { 8, 30, 1 } } },
{ { { 15, 0, 3 }, { 8, 30, 0 } } },
{ { { 15, 0, 4 }, { 10, 27, 1 } } },
{ { { 16, 0, 4 }, { 10, 27, 0 } } },
{ { { 16, 0, 3 }, { 8, 31, 0 } } },
{ { { 16, 0, 2 }, { 9, 30, 1 } } },
{ { { 16, 0, 1 }, { 9, 30, 0 } } },
{ { { 16, 0, 0 }, { 12, 24, 0 } } },
{ { { 16, 0, 1 }, { 9, 31, 1 } } },
{ { { 16, 0, 2 }, { 9, 31, 0 } } },
{ { { 16, 0, 3 }, { 9, 31, 1 } } },
{ { { 16, 0, 4 }, { 10, 30, 1 } } },
{ { { 17, 0, 3 }, { 10, 30, 0 } } },
{ { { 17, 0, 2 }, { 10, 31, 1 } } },
{ { { 17, 0, 1 }, { 10, 31, 0 } } },
{ { { 17, 0, 0 }, { 12, 27, 0 } } },
{ { { 17, 0, 1 }, { 11, 30, 1 } } },
{ { { 17, 0, 2 }, { 11, 30, 0 } } },
{ { { 17, 0, 3 }, { 12, 28, 0 } } },
{ { { 17, 0, 4 }, { 11, 31, 1 } } },
{ { { 18, 0, 3 }, { 11, 31, 0 } } },
{ { { 18, 0, 2 }, { 11, 31, 1 } } },
{ { { 18, 0, 1 }, { 12, 30, 1 } } },
{ { { 18, 0, 0 }, { 12, 30, 0 } } },
{ { { 18, 0, 1 }, { 14, 27, 1 } } },
{ { { 18, 0, 2 }, { 14, 27, 0 } } },
{ { { 18, 0, 3 }, { 12, 31, 0 } } },
{ { { 18, 0, 4 }, { 13, 30, 1 } } },
{ { { 19, 0, 3 }, { 13, 30, 0 } } },
{ { { 19, 0, 2 }, { 16, 24, 0 } } },
{ { { 19, 0, 1 }, { 13, 31, 1 } } },
{ { { 19, 0, 0 }, { 13, 31, 0 } } },
{ { { 19, 0, 1 }, { 13, 31, 1 } } },
{ { { 19, 0, 2 }, { 14, 30, 1 } } },
{ { { 19, 0, 3 }, { 14, 30, 0 } } },
{ { { 19, 0, 4 }, { 14, 31, 1 } } },
{ { { 20, 0, 4 }, { 14, 31, 0 } } },
{ { { 20, 0, 3 }, { 16, 27, 0 } } },
{ { { 20, 0, 2 }, { 15, 30, 1 } } },
{ { { 20, 0, 1 }, { 15, 30, 0 } } },
{ { { 20, 0, 0 }, { 16, 28, 0 } } },
{ { { 20, 0, 1 }, { 15, 31, 1 } } },
{ { { 20, 0, 2 }, { 15, 31, 0 } } },
{ { { 20, 0, 3 }, { 15, 31, 1 } } },
{ { { 20, 0, 4 }, { 16, 30, 1 } } },
{ { { 21, 0, 3 }, { 16, 30, 0 } } },
{ { { 21, 0, 2 }, { 18, 27, 1 } } },
{ { { 21, 0, 1 }, { 18, 27, 0 } } },
{ { { 21, 0, 0 }, { 16, 31, 0 } } },
{ { { 21, 0, 1 }, { 17, 30, 1 } } },
{ { { 21, 0, 2 }, { 17, 30, 0 } } },
{ { { 21, 0, 3 }, { 20, 24, 0 } } },
{ { { 21, 0, 4 }, { 17, 31, 1 } } },
{ { { 22, 0, 3 }, { 17, 31, 0 } } },
{ { { 22, 0, 2 }, { 17, 31, 1 } } },
{ { { 22, 0, 1 }, { 18, 30, 1 } } },
{ { { 22, 0, 0 }, { 18, 30, 0 } } },
{ { { 22, 0, 1 }, { 18, 31, 1 } } },
{ { { 22, 0, 2 }, { 18, 31, 0 } } },
{ { { 22, 0, 3 }, { 20, 27, 0 } } },
{ { { 22, 0, 4 }, { 19, 30, 1 } } },
{ { { 23, 0, 3 }, { 19, 30, 0 } } },
{ { { 23, 0, 2 }, { 20, 28, 0 } } },
{ { { 23, 0, 1 }, { 19, 31, 1 } } },
{ { { 23, 0, 0 }, { 19, 31, 0 } } },
{ { { 23, 0, 1 }, { 19, 31, 1 } } },
{ { { 23, 0, 2 }, { 20, 30, 1 } } },
{ { { 23, 0, 3 }, { 20, 30, 0 } } },
{ { { 23, 0, 4 }, { 22, 27, 1 } } },
{ { { 24, 0, 4 }, { 22, 27, 0 } } },
{ { { 24, 0, 3 }, { 20, 31, 0 } } },
{ { { 24, 0, 2 }, { 21, 30, 1 } } },
{ { { 24, 0, 1 }, { 21, 30, 0 } } },
{ { { 24, 0, 0 }, { 24, 24, 0 } } },
{ { { 24, 0, 1 }, { 21, 31, 1 } } },
{ { { 24, 0, 2 }, { 21, 31, 0 } } },
{ { { 24, 0, 3 }, { 21, 31, 1 } } },
{ { { 24, 0, 4 }, { 22, 30, 1 } } },
{ { { 25, 0, 3 }, { 22, 30, 0 } } },
{ { { 25, 0, 2 }, { 22, 31, 1 } } },
{ { { 25, 0, 1 }, { 22, 31, 0 } } },
{ { { 25, 0, 0 }, { 24, 27, 0 } } },
{ { { 25, 0, 1 }, { 23, 30, 1 } } },
{ { { 25, 0, 2 }, { 23, 30, 0 } } },
{ { { 25, 0, 3 }, { 24, 28, 0 } } },
{ { { 25, 0, 4 }, { 23, 31, 1 } } },
{ { { 26, 0, 3 }, { 23, 31, 0 } } },
{ { { 26, 0, 2 }, { 23, 31, 1 } } },
{ { { 26, 0, 1 }, { 24, 30, 1 } } },
{ { { 26, 0, 0 }, { 24, 30, 0 } } },
{ { { 26, 0, 1 }, { 26, 27, 1 } } },
{ { { 26, 0, 2 }, { 26, 27, 0 } } },
{ { { 26, 0, 3 }, { 24, 31, 0 } } },
{ { { 26, 0, 4 }, { 25, 30, 1 } } },
{ { { 27, 0, 3 }, { 25, 30, 0 } } },
{ { { 27, 0, 2 }, { 28, 24, 0 } } },
{ { { 27, 0, 1 }, { 25, 31, 1 } } },
{ { { 27, 0, 0 }, { 25, 31, 0 } } },
{ { { 27, 0, 1 }, { 25, 31, 1 } } },
{ { { 27, 0, 2 }, { 26, 30, 1 } } },
{ { { 27, 0, 3 }, { 26, 30, 0 } } },
{ { { 27, 0, 4 }, { 26, 31, 1 } } },
{ { { 28, 0, 4 }, { 26, 31, 0 } } },
{ { { 28, 0, 3 }, { 28, 27, 0 } } },
{ { { 28, 0, 2 }, { 27, 30, 1 } } },
{ { { 28, 0, 1 }, { 27, 30, 0 } } },
{ { { 28, 0, 0 }, { 28, 28, 0 } } },
{ { { 28, 0, 1 }, { 27, 31, 1 } } },
{ { { 28, 0, 2 }, { 27, 31, 0 } } },
{ { { 28, 0, 3 }, { 27, 31, 1 } } },
{ { { 28, 0, 4 }, { 28, 30, 1 } } },
{ { { 29, 0, 3 }, { 28, 30, 0 } } },
{ { { 29, 0, 2 }, { 30, 27, 1 } } },
{ { { 29, 0, 1 }, { 30, 27, 0 } } },
{ { { 29, 0, 0 }, { 28, 31, 0 } } },
{ { { 29, 0, 1 }, { 29, 30, 1 } } },
{ { { 29, 0, 2 }, { 29, 30, 0 } } },
{ { { 29, 0, 3 }, { 29, 30, 1 } } },
{ { { 29, 0, 4 }, { 29, 31, 1 } } },
{ { { 30, 0, 3 }, { 29, 31, 0 } } },
{ { { 30, 0, 2 }, { 29, 31, 1 } } },
{ { { 30, 0, 1 }, { 30, 30, 1 } } },
{ { { 30, 0, 0 }, { 30, 30, 0 } } },
{ { { 30, 0, 1 }, { 30, 31, 1 } } },
{ { { 30, 0, 2 }, { 30, 31, 0 } } },
{ { { 30, 0, 3 }, { 30, 31, 1 } } },
{ { { 30, 0, 4 }, { 31, 30, 1 } } },
{ { { 31, 0, 3 }, { 31, 30, 0 } } },
{ { { 31, 0, 2 }, { 31, 30, 1 } } },
{ { { 31, 0, 1 }, { 31, 31, 1 } } },
{ { { 31, 0, 0 }, { 31, 31, 0 } } }
};
static const DDSSingleColourLookup DDSLookup_6_4[] =
{
{ { { 0, 0, 0 }, { 0, 0, 0 } } },
{ { { 0, 0, 1 }, { 0, 1, 0 } } },
{ { { 0, 0, 2 }, { 0, 2, 0 } } },
{ { { 1, 0, 1 }, { 0, 3, 1 } } },
{ { { 1, 0, 0 }, { 0, 3, 0 } } },
{ { { 1, 0, 1 }, { 0, 4, 0 } } },
{ { { 1, 0, 2 }, { 0, 5, 0 } } },
{ { { 2, 0, 1 }, { 0, 6, 1 } } },
{ { { 2, 0, 0 }, { 0, 6, 0 } } },
{ { { 2, 0, 1 }, { 0, 7, 0 } } },
{ { { 2, 0, 2 }, { 0, 8, 0 } } },
{ { { 3, 0, 1 }, { 0, 9, 1 } } },
{ { { 3, 0, 0 }, { 0, 9, 0 } } },
{ { { 3, 0, 1 }, { 0, 10, 0 } } },
{ { { 3, 0, 2 }, { 0, 11, 0 } } },
{ { { 4, 0, 1 }, { 0, 12, 1 } } },
{ { { 4, 0, 0 }, { 0, 12, 0 } } },
{ { { 4, 0, 1 }, { 0, 13, 0 } } },
{ { { 4, 0, 2 }, { 0, 14, 0 } } },
{ { { 5, 0, 1 }, { 0, 15, 1 } } },
{ { { 5, 0, 0 }, { 0, 15, 0 } } },
{ { { 5, 0, 1 }, { 0, 16, 0 } } },
{ { { 5, 0, 2 }, { 1, 15, 0 } } },
{ { { 6, 0, 1 }, { 0, 17, 0 } } },
{ { { 6, 0, 0 }, { 0, 18, 0 } } },
{ { { 6, 0, 1 }, { 0, 19, 0 } } },
{ { { 6, 0, 2 }, { 3, 14, 0 } } },
{ { { 7, 0, 1 }, { 0, 20, 0 } } },
{ { { 7, 0, 0 }, { 0, 21, 0 } } },
{ { { 7, 0, 1 }, { 0, 22, 0 } } },
{ { { 7, 0, 2 }, { 4, 15, 0 } } },
{ { { 8, 0, 1 }, { 0, 23, 0 } } },
{ { { 8, 0, 0 }, { 0, 24, 0 } } },
{ { { 8, 0, 1 }, { 0, 25, 0 } } },
{ { { 8, 0, 2 }, { 6, 14, 0 } } },
{ { { 9, 0, 1 }, { 0, 26, 0 } } },
{ { { 9, 0, 0 }, { 0, 27, 0 } } },
{ { { 9, 0, 1 }, { 0, 28, 0 } } },
{ { { 9, 0, 2 }, { 7, 15, 0 } } },
{ { { 10, 0, 1 }, { 0, 29, 0 } } },
{ { { 10, 0, 0 }, { 0, 30, 0 } } },
{ { { 10, 0, 1 }, { 0, 31, 0 } } },
{ { { 10, 0, 2 }, { 9, 14, 0 } } },
{ { { 11, 0, 1 }, { 0, 32, 0 } } },
{ { { 11, 0, 0 }, { 0, 33, 0 } } },
{ { { 11, 0, 1 }, { 2, 30, 0 } } },
{ { { 11, 0, 2 }, { 0, 34, 0 } } },
{ { { 12, 0, 1 }, { 0, 35, 0 } } },
{ { { 12, 0, 0 }, { 0, 36, 0 } } },
{ { { 12, 0, 1 }, { 3, 31, 0 } } },
{ { { 12, 0, 2 }, { 0, 37, 0 } } },
{ { { 13, 0, 1 }, { 0, 38, 0 } } },
{ { { 13, 0, 0 }, { 0, 39, 0 } } },
{ { { 13, 0, 1 }, { 5, 30, 0 } } },
{ { { 13, 0, 2 }, { 0, 40, 0 } } },
{ { { 14, 0, 1 }, { 0, 41, 0 } } },
{ { { 14, 0, 0 }, { 0, 42, 0 } } },
{ { { 14, 0, 1 }, { 6, 31, 0 } } },
{ { { 14, 0, 2 }, { 0, 43, 0 } } },
{ { { 15, 0, 1 }, { 0, 44, 0 } } },
{ { { 15, 0, 0 }, { 0, 45, 0 } } },
{ { { 15, 0, 1 }, { 8, 30, 0 } } },
{ { { 15, 0, 2 }, { 0, 46, 0 } } },
{ { { 16, 0, 2 }, { 0, 47, 0 } } },
{ { { 16, 0, 1 }, { 1, 46, 0 } } },
{ { { 16, 0, 0 }, { 0, 48, 0 } } },
{ { { 16, 0, 1 }, { 0, 49, 0 } } },
{ { { 16, 0, 2 }, { 0, 50, 0 } } },
{ { { 17, 0, 1 }, { 2, 47, 0 } } },
{ { { 17, 0, 0 }, { 0, 51, 0 } } },
{ { { 17, 0, 1 }, { 0, 52, 0 } } },
{ { { 17, 0, 2 }, { 0, 53, 0 } } },
{ { { 18, 0, 1 }, { 4, 46, 0 } } },
{ { { 18, 0, 0 }, { 0, 54, 0 } } },
{ { { 18, 0, 1 }, { 0, 55, 0 } } },
{ { { 18, 0, 2 }, { 0, 56, 0 } } },
{ { { 19, 0, 1 }, { 5, 47, 0 } } },
{ { { 19, 0, 0 }, { 0, 57, 0 } } },
{ { { 19, 0, 1 }, { 0, 58, 0 } } },
{ { { 19, 0, 2 }, { 0, 59, 0 } } },
{ { { 20, 0, 1 }, { 7, 46, 0 } } },
{ { { 20, 0, 0 }, { 0, 60, 0 } } },
{ { { 20, 0, 1 }, { 0, 61, 0 } } },
{ { { 20, 0, 2 }, { 0, 62, 0 } } },
{ { { 21, 0, 1 }, { 8, 47, 0 } } },
{ { { 21, 0, 0 }, { 0, 63, 0 } } },
{ { { 21, 0, 1 }, { 1, 62, 0 } } },
{ { { 21, 0, 2 }, { 1, 63, 0 } } },
{ { { 22, 0, 1 }, { 10, 46, 0 } } },
{ { { 22, 0, 0 }, { 2, 62, 0 } } },
{ { { 22, 0, 1 }, { 2, 63, 0 } } },
{ { { 22, 0, 2 }, { 3, 62, 0 } } },
{ { { 23, 0, 1 }, { 11, 47, 0 } } },
{ { { 23, 0, 0 }, { 3, 63, 0 } } },
{ { { 23, 0, 1 }, { 4, 62, 0 } } },
{ { { 23, 0, 2 }, { 4, 63, 0 } } },
{ { { 24, 0, 1 }, { 13, 46, 0 } } },
{ { { 24, 0, 0 }, { 5, 62, 0 } } },
{ { { 24, 0, 1 }, { 5, 63, 0 } } },
{ { { 24, 0, 2 }, { 6, 62, 0 } } },
{ { { 25, 0, 1 }, { 14, 47, 0 } } },
{ { { 25, 0, 0 }, { 6, 63, 0 } } },
{ { { 25, 0, 1 }, { 7, 62, 0 } } },
{ { { 25, 0, 2 }, { 7, 63, 0 } } },
{ { { 26, 0, 1 }, { 16, 45, 0 } } },
{ { { 26, 0, 0 }, { 8, 62, 0 } } },
{ { { 26, 0, 1 }, { 8, 63, 0 } } },
{ { { 26, 0, 2 }, { 9, 62, 0 } } },
{ { { 27, 0, 1 }, { 16, 48, 0 } } },
{ { { 27, 0, 0 }, { 9, 63, 0 } } },
{ { { 27, 0, 1 }, { 10, 62, 0 } } },
{ { { 27, 0, 2 }, { 10, 63, 0 } } },
{ { { 28, 0, 1 }, { 16, 51, 0 } } },
{ { { 28, 0, 0 }, { 11, 62, 0 } } },
{ { { 28, 0, 1 }, { 11, 63, 0 } } },
{ { { 28, 0, 2 }, { 12, 62, 0 } } },
{ { { 29, 0, 1 }, { 16, 54, 0 } } },
{ { { 29, 0, 0 }, { 12, 63, 0 } } },
{ { { 29, 0, 1 }, { 13, 62, 0 } } },
{ { { 29, 0, 2 }, { 13, 63, 0 } } },
{ { { 30, 0, 1 }, { 16, 57, 0 } } },
{ { { 30, 0, 0 }, { 14, 62, 0 } } },
{ { { 30, 0, 1 }, { 14, 63, 0 } } },
{ { { 30, 0, 2 }, { 15, 62, 0 } } },
{ { { 31, 0, 1 }, { 16, 60, 0 } } },
{ { { 31, 0, 0 }, { 15, 63, 0 } } },
{ { { 31, 0, 1 }, { 24, 46, 0 } } },
{ { { 31, 0, 2 }, { 16, 62, 0 } } },
{ { { 32, 0, 2 }, { 16, 63, 0 } } },
{ { { 32, 0, 1 }, { 17, 62, 0 } } },
{ { { 32, 0, 0 }, { 25, 47, 0 } } },
{ { { 32, 0, 1 }, { 17, 63, 0 } } },
{ { { 32, 0, 2 }, { 18, 62, 0 } } },
{ { { 33, 0, 1 }, { 18, 63, 0 } } },
{ { { 33, 0, 0 }, { 27, 46, 0 } } },
{ { { 33, 0, 1 }, { 19, 62, 0 } } },
{ { { 33, 0, 2 }, { 19, 63, 0 } } },
{ { { 34, 0, 1 }, { 20, 62, 0 } } },
{ { { 34, 0, 0 }, { 28, 47, 0 } } },
{ { { 34, 0, 1 }, { 20, 63, 0 } } },
{ { { 34, 0, 2 }, { 21, 62, 0 } } },
{ { { 35, 0, 1 }, { 21, 63, 0 } } },
{ { { 35, 0, 0 }, { 30, 46, 0 } } },
{ { { 35, 0, 1 }, { 22, 62, 0 } } },
{ { { 35, 0, 2 }, { 22, 63, 0 } } },
{ { { 36, 0, 1 }, { 23, 62, 0 } } },
{ { { 36, 0, 0 }, { 31, 47, 0 } } },
{ { { 36, 0, 1 }, { 23, 63, 0 } } },
{ { { 36, 0, 2 }, { 24, 62, 0 } } },
{ { { 37, 0, 1 }, { 24, 63, 0 } } },
{ { { 37, 0, 0 }, { 32, 47, 0 } } },
{ { { 37, 0, 1 }, { 25, 62, 0 } } },
{ { { 37, 0, 2 }, { 25, 63, 0 } } },
{ { { 38, 0, 1 }, { 26, 62, 0 } } },
{ { { 38, 0, 0 }, { 32, 50, 0 } } },
{ { { 38, 0, 1 }, { 26, 63, 0 } } },
{ { { 38, 0, 2 }, { 27, 62, 0 } } },
{ { { 39, 0, 1 }, { 27, 63, 0 } } },
{ { { 39, 0, 0 }, { 32, 53, 0 } } },
{ { { 39, 0, 1 }, { 28, 62, 0 } } },
{ { { 39, 0, 2 }, { 28, 63, 0 } } },
{ { { 40, 0, 1 }, { 29, 62, 0 } } },
{ { { 40, 0, 0 }, { 32, 56, 0 } } },
{ { { 40, 0, 1 }, { 29, 63, 0 } } },
{ { { 40, 0, 2 }, { 30, 62, 0 } } },
{ { { 41, 0, 1 }, { 30, 63, 0 } } },
{ { { 41, 0, 0 }, { 32, 59, 0 } } },
{ { { 41, 0, 1 }, { 31, 62, 0 } } },
{ { { 41, 0, 2 }, { 31, 63, 0 } } },
{ { { 42, 0, 1 }, { 32, 61, 0 } } },
{ { { 42, 0, 0 }, { 32, 62, 0 } } },
{ { { 42, 0, 1 }, { 32, 63, 0 } } },
{ { { 42, 0, 2 }, { 41, 46, 0 } } },
{ { { 43, 0, 1 }, { 33, 62, 0 } } },
{ { { 43, 0, 0 }, { 33, 63, 0 } } },
{ { { 43, 0, 1 }, { 34, 62, 0 } } },
{ { { 43, 0, 2 }, { 42, 47, 0 } } },
{ { { 44, 0, 1 }, { 34, 63, 0 } } },
{ { { 44, 0, 0 }, { 35, 62, 0 } } },
{ { { 44, 0, 1 }, { 35, 63, 0 } } },
{ { { 44, 0, 2 }, { 44, 46, 0 } } },
{ { { 45, 0, 1 }, { 36, 62, 0 } } },
{ { { 45, 0, 0 }, { 36, 63, 0 } } },
{ { { 45, 0, 1 }, { 37, 62, 0 } } },
{ { { 45, 0, 2 }, { 45, 47, 0 } } },
{ { { 46, 0, 1 }, { 37, 63, 0 } } },
{ { { 46, 0, 0 }, { 38, 62, 0 } } },
{ { { 46, 0, 1 }, { 38, 63, 0 } } },
{ { { 46, 0, 2 }, { 47, 46, 0 } } },
{ { { 47, 0, 1 }, { 39, 62, 0 } } },
{ { { 47, 0, 0 }, { 39, 63, 0 } } },
{ { { 47, 0, 1 }, { 40, 62, 0 } } },
{ { { 47, 0, 2 }, { 48, 46, 0 } } },
{ { { 48, 0, 2 }, { 40, 63, 0 } } },
{ { { 48, 0, 1 }, { 41, 62, 0 } } },
{ { { 48, 0, 0 }, { 41, 63, 0 } } },
{ { { 48, 0, 1 }, { 48, 49, 0 } } },
{ { { 48, 0, 2 }, { 42, 62, 0 } } },
{ { { 49, 0, 1 }, { 42, 63, 0 } } },
{ { { 49, 0, 0 }, { 43, 62, 0 } } },
{ { { 49, 0, 1 }, { 48, 52, 0 } } },
{ { { 49, 0, 2 }, { 43, 63, 0 } } },
{ { { 50, 0, 1 }, { 44, 62, 0 } } },
{ { { 50, 0, 0 }, { 44, 63, 0 } } },
{ { { 50, 0, 1 }, { 48, 55, 0 } } },
{ { { 50, 0, 2 }, { 45, 62, 0 } } },
{ { { 51, 0, 1 }, { 45, 63, 0 } } },
{ { { 51, 0, 0 }, { 46, 62, 0 } } },
{ { { 51, 0, 1 }, { 48, 58, 0 } } },
{ { { 51, 0, 2 }, { 46, 63, 0 } } },
{ { { 52, 0, 1 }, { 47, 62, 0 } } },
{ { { 52, 0, 0 }, { 47, 63, 0 } } },
{ { { 52, 0, 1 }, { 48, 61, 0 } } },
{ { { 52, 0, 2 }, { 48, 62, 0 } } },
{ { { 53, 0, 1 }, { 56, 47, 0 } } },
{ { { 53, 0, 0 }, { 48, 63, 0 } } },
{ { { 53, 0, 1 }, { 49, 62, 0 } } },
{ { { 53, 0, 2 }, { 49, 63, 0 } } },
{ { { 54, 0, 1 }, { 58, 46, 0 } } },
{ { { 54, 0, 0 }, { 50, 62, 0 } } },
{ { { 54, 0, 1 }, { 50, 63, 0 } } },
{ { { 54, 0, 2 }, { 51, 62, 0 } } },
{ { { 55, 0, 1 }, { 59, 47, 0 } } },
{ { { 55, 0, 0 }, { 51, 63, 0 } } },
{ { { 55, 0, 1 }, { 52, 62, 0 } } },
{ { { 55, 0, 2 }, { 52, 63, 0 } } },
{ { { 56, 0, 1 }, { 61, 46, 0 } } },
{ { { 56, 0, 0 }, { 53, 62, 0 } } },
{ { { 56, 0, 1 }, { 53, 63, 0 } } },
{ { { 56, 0, 2 }, { 54, 62, 0 } } },
{ { { 57, 0, 1 }, { 62, 47, 0 } } },
{ { { 57, 0, 0 }, { 54, 63, 0 } } },
{ { { 57, 0, 1 }, { 55, 62, 0 } } },
{ { { 57, 0, 2 }, { 55, 63, 0 } } },
{ { { 58, 0, 1 }, { 56, 62, 1 } } },
{ { { 58, 0, 0 }, { 56, 62, 0 } } },
{ { { 58, 0, 1 }, { 56, 63, 0 } } },
{ { { 58, 0, 2 }, { 57, 62, 0 } } },
{ { { 59, 0, 1 }, { 57, 63, 1 } } },
{ { { 59, 0, 0 }, { 57, 63, 0 } } },
{ { { 59, 0, 1 }, { 58, 62, 0 } } },
{ { { 59, 0, 2 }, { 58, 63, 0 } } },
{ { { 60, 0, 1 }, { 59, 62, 1 } } },
{ { { 60, 0, 0 }, { 59, 62, 0 } } },
{ { { 60, 0, 1 }, { 59, 63, 0 } } },
{ { { 60, 0, 2 }, { 60, 62, 0 } } },
{ { { 61, 0, 1 }, { 60, 63, 1 } } },
{ { { 61, 0, 0 }, { 60, 63, 0 } } },
{ { { 61, 0, 1 }, { 61, 62, 0 } } },
{ { { 61, 0, 2 }, { 61, 63, 0 } } },
{ { { 62, 0, 1 }, { 62, 62, 1 } } },
{ { { 62, 0, 0 }, { 62, 62, 0 } } },
{ { { 62, 0, 1 }, { 62, 63, 0 } } },
{ { { 62, 0, 2 }, { 63, 62, 0 } } },
{ { { 63, 0, 1 }, { 63, 63, 1 } } },
{ { { 63, 0, 0 }, { 63, 63, 0 } } }
};
static const DDSSingleColourLookup*
DDS_LOOKUP[] =
{
DDSLookup_5_4,
DDSLookup_6_4,
DDSLookup_5_4
};
/*
Macros
*/
#define C565_r(x) (((x) & 0xF800) >> 11)
#define C565_g(x) (((x) & 0x07E0) >> 5)
#define C565_b(x) ((x) & 0x001F)
#define C565_red(x) ( (C565_r(x) << 3 | C565_r(x) >> 2))
#define C565_green(x) ( (C565_g(x) << 2 | C565_g(x) >> 4))
#define C565_blue(x) ( (C565_b(x) << 3 | C565_b(x) >> 2))
#define DIV2(x) ((x) > 1 ? ((x) >> 1) : 1)
#define FixRange(min, max, steps) \
if (min > max) \
min = max; \
if ((ssize_t) max - min < steps) \
max = MagickMin(min + steps, 255); \
if ((ssize_t) max - min < steps) \
min = MagickMax(0, (ssize_t) max - steps)
#define Dot(left, right) (left.x*right.x) + (left.y*right.y) + (left.z*right.z)
#define VectorInit(vector, value) vector.x = vector.y = vector.z = vector.w \
= value
#define VectorInit3(vector, value) vector.x = vector.y = vector.z = value
#define IsBitMask(mask, r, g, b, a) (mask.r_bitmask == r && mask.g_bitmask == \
g && mask.b_bitmask == b && mask.alpha_bitmask == a)
/*
Forward declarations
*/
static MagickBooleanType
ConstructOrdering(const size_t,const DDSVector4 *,const DDSVector3,
DDSVector4 *,DDSVector4 *,unsigned char *,size_t),
ReadDDSInfo(Image *,DDSInfo *),
ReadDXT1(Image *,DDSInfo *,ExceptionInfo *),
ReadDXT3(Image *,DDSInfo *,ExceptionInfo *),
ReadDXT5(Image *,DDSInfo *,ExceptionInfo *),
ReadUncompressedRGB(Image *,DDSInfo *,ExceptionInfo *),
ReadUncompressedRGBA(Image *,DDSInfo *,ExceptionInfo *),
SkipDXTMipmaps(Image *,DDSInfo *,int,ExceptionInfo *),
SkipRGBMipmaps(Image *,DDSInfo *,int,ExceptionInfo *),
WriteDDSImage(const ImageInfo *,Image *),
WriteMipmaps(Image *,const size_t,const size_t,const size_t,
const MagickBooleanType,const MagickBooleanType,ExceptionInfo *);
static void
RemapIndices(const ssize_t *,const unsigned char *,unsigned char *),
WriteDDSInfo(Image *,const size_t,const size_t,const size_t),
WriteFourCC(Image *,const size_t,const MagickBooleanType,
const MagickBooleanType,ExceptionInfo *),
WriteImageData(Image *,const size_t,const size_t,const MagickBooleanType,
const MagickBooleanType,ExceptionInfo *),
WriteIndices(Image *,const DDSVector3,const DDSVector3, unsigned char *),
WriteSingleColorFit(Image *,const DDSVector4 *,const ssize_t *),
WriteUncompressed(Image *,ExceptionInfo *);
static inline void VectorAdd(const DDSVector4 left, const DDSVector4 right,
DDSVector4 *destination)
{
destination->x = left.x + right.x;
destination->y = left.y + right.y;
destination->z = left.z + right.z;
destination->w = left.w + right.w;
}
static inline void VectorClamp(DDSVector4 *value)
{
value->x = MagickMin(1.0f,MagickMax(0.0f,value->x));
value->y = MagickMin(1.0f,MagickMax(0.0f,value->y));
value->z = MagickMin(1.0f,MagickMax(0.0f,value->z));
value->w = MagickMin(1.0f,MagickMax(0.0f,value->w));
}
static inline void VectorClamp3(DDSVector3 *value)
{
value->x = MagickMin(1.0f,MagickMax(0.0f,value->x));
value->y = MagickMin(1.0f,MagickMax(0.0f,value->y));
value->z = MagickMin(1.0f,MagickMax(0.0f,value->z));
}
static inline void VectorCopy43(const DDSVector4 source,
DDSVector3 *destination)
{
destination->x = source.x;
destination->y = source.y;
destination->z = source.z;
}
static inline void VectorCopy44(const DDSVector4 source,
DDSVector4 *destination)
{
destination->x = source.x;
destination->y = source.y;
destination->z = source.z;
destination->w = source.w;
}
static inline void VectorNegativeMultiplySubtract(const DDSVector4 a,
const DDSVector4 b, const DDSVector4 c, DDSVector4 *destination)
{
destination->x = c.x - (a.x * b.x);
destination->y = c.y - (a.y * b.y);
destination->z = c.z - (a.z * b.z);
destination->w = c.w - (a.w * b.w);
}
static inline void VectorMultiply(const DDSVector4 left,
const DDSVector4 right, DDSVector4 *destination)
{
destination->x = left.x * right.x;
destination->y = left.y * right.y;
destination->z = left.z * right.z;
destination->w = left.w * right.w;
}
static inline void VectorMultiply3(const DDSVector3 left,
const DDSVector3 right, DDSVector3 *destination)
{
destination->x = left.x * right.x;
destination->y = left.y * right.y;
destination->z = left.z * right.z;
}
static inline void VectorMultiplyAdd(const DDSVector4 a, const DDSVector4 b,
const DDSVector4 c, DDSVector4 *destination)
{
destination->x = (a.x * b.x) + c.x;
destination->y = (a.y * b.y) + c.y;
destination->z = (a.z * b.z) + c.z;
destination->w = (a.w * b.w) + c.w;
}
static inline void VectorMultiplyAdd3(const DDSVector3 a, const DDSVector3 b,
const DDSVector3 c, DDSVector3 *destination)
{
destination->x = (a.x * b.x) + c.x;
destination->y = (a.y * b.y) + c.y;
destination->z = (a.z * b.z) + c.z;
}
static inline void VectorReciprocal(const DDSVector4 value,
DDSVector4 *destination)
{
destination->x = 1.0f / value.x;
destination->y = 1.0f / value.y;
destination->z = 1.0f / value.z;
destination->w = 1.0f / value.w;
}
static inline void VectorSubtract(const DDSVector4 left,
const DDSVector4 right, DDSVector4 *destination)
{
destination->x = left.x - right.x;
destination->y = left.y - right.y;
destination->z = left.z - right.z;
destination->w = left.w - right.w;
}
static inline void VectorSubtract3(const DDSVector3 left,
const DDSVector3 right, DDSVector3 *destination)
{
destination->x = left.x - right.x;
destination->y = left.y - right.y;
destination->z = left.z - right.z;
}
static inline void VectorTruncate(DDSVector4 *value)
{
value->x = value->x > 0.0f ? floor(value->x) : ceil(value->x);
value->y = value->y > 0.0f ? floor(value->y) : ceil(value->y);
value->z = value->z > 0.0f ? floor(value->z) : ceil(value->z);
value->w = value->w > 0.0f ? floor(value->w) : ceil(value->w);
}
static inline void VectorTruncate3(DDSVector3 *value)
{
value->x = value->x > 0.0f ? floor(value->x) : ceil(value->x);
value->y = value->y > 0.0f ? floor(value->y) : ceil(value->y);
value->z = value->z > 0.0f ? floor(value->z) : ceil(value->z);
}
static void CalculateColors(unsigned short c0, unsigned short c1,
DDSColors *c, MagickBooleanType ignoreAlpha)
{
c->a[0] = c->a[1] = c->a[2] = c->a[3] = 0;
c->r[0] = (unsigned char) C565_red(c0);
c->g[0] = (unsigned char) C565_green(c0);
c->b[0] = (unsigned char) C565_blue(c0);
c->r[1] = (unsigned char) C565_red(c1);
c->g[1] = (unsigned char) C565_green(c1);
c->b[1] = (unsigned char) C565_blue(c1);
if (ignoreAlpha != MagickFalse || c0 > c1)
{
c->r[2] = (unsigned char) ((2 * c->r[0] + c->r[1]) / 3);
c->g[2] = (unsigned char) ((2 * c->g[0] + c->g[1]) / 3);
c->b[2] = (unsigned char) ((2 * c->b[0] + c->b[1]) / 3);
c->r[3] = (unsigned char) ((c->r[0] + 2 * c->r[1]) / 3);
c->g[3] = (unsigned char) ((c->g[0] + 2 * c->g[1]) / 3);
c->b[3] = (unsigned char) ((c->b[0] + 2 * c->b[1]) / 3);
}
else
{
c->r[2] = (unsigned char) ((c->r[0] + c->r[1]) / 2);
c->g[2] = (unsigned char) ((c->g[0] + c->g[1]) / 2);
c->b[2] = (unsigned char) ((c->b[0] + c->b[1]) / 2);
c->r[3] = c->g[3] = c->b[3] = 0;
c->a[3] = 255;
}
}
static size_t CompressAlpha(const size_t min, const size_t max,
const size_t steps, const ssize_t *alphas, unsigned char* indices)
{
unsigned char
codes[8];
register ssize_t
i;
size_t
error,
index,
j,
least,
value;
codes[0] = (unsigned char) min;
codes[1] = (unsigned char) max;
codes[6] = 0;
codes[7] = 255;
for (i=1; i < (ssize_t) steps; i++)
codes[i+1] = (unsigned char) (((steps-i)*min + i*max) / steps);
error = 0;
for (i=0; i<16; i++)
{
if (alphas[i] == -1)
{
indices[i] = 0;
continue;
}
value = alphas[i];
least = SIZE_MAX;
index = 0;
for (j=0; j<8; j++)
{
size_t
dist;
dist = value - (size_t)codes[j];
dist *= dist;
if (dist < least)
{
least = dist;
index = j;
}
}
indices[i] = (unsigned char)index;
error += least;
}
return error;
}
static void CompressClusterFit(const size_t count,
const DDSVector4 *points, const ssize_t *map, const DDSVector3 principle,
const DDSVector4 metric, DDSVector3 *start, DDSVector3 *end,
unsigned char *indices)
{
DDSVector3
axis;
DDSVector4
grid,
gridrcp,
half,
onethird_onethird2,
pointsWeights[16],
two,
twonineths,
twothirds_twothirds2,
xSumwSum;
float
bestError = 1e+37f;
size_t
bestIteration = 0,
besti = 0,
bestj = 0,
bestk = 0,
iterationIndex;
ssize_t
i;
unsigned char
*o,
order[128],
unordered[16];
VectorInit(half,0.5f);
VectorInit(two,2.0f);
VectorInit(onethird_onethird2,1.0f/3.0f);
onethird_onethird2.w = 1.0f/9.0f;
VectorInit(twothirds_twothirds2,2.0f/3.0f);
twothirds_twothirds2.w = 4.0f/9.0f;
VectorInit(twonineths,2.0f/9.0f);
grid.x = 31.0f;
grid.y = 63.0f;
grid.z = 31.0f;
grid.w = 0.0f;
gridrcp.x = 1.0f/31.0f;
gridrcp.y = 1.0f/63.0f;
gridrcp.z = 1.0f/31.0f;
gridrcp.w = 0.0f;
xSumwSum.x = 0.0f;
xSumwSum.y = 0.0f;
xSumwSum.z = 0.0f;
xSumwSum.w = 0.0f;
ConstructOrdering(count,points,principle,pointsWeights,&xSumwSum,order,0);
for (iterationIndex = 0;;)
{
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(dynamic,1) \
num_threads(GetMagickResourceLimit(ThreadResource))
#endif
for (i=0; i < (ssize_t) count; i++)
{
DDSVector4
part0,
part1,
part2;
size_t
ii,
j,
k,
kmin;
VectorInit(part0,0.0f);
for(ii=0; ii < (size_t) i; ii++)
VectorAdd(pointsWeights[ii],part0,&part0);
VectorInit(part1,0.0f);
for (j=(size_t) i;;)
{
if (j == 0)
{
VectorCopy44(pointsWeights[0],&part2);
kmin = 1;
}
else
{
VectorInit(part2,0.0f);
kmin = j;
}
for (k=kmin;;)
{
DDSVector4
a,
alpha2_sum,
alphax_sum,
alphabeta_sum,
b,
beta2_sum,
betax_sum,
e1,
e2,
factor,
part3;
float
error;
VectorSubtract(xSumwSum,part2,&part3);
VectorSubtract(part3,part1,&part3);
VectorSubtract(part3,part0,&part3);
VectorMultiplyAdd(part1,twothirds_twothirds2,part0,&alphax_sum);
VectorMultiplyAdd(part2,onethird_onethird2,alphax_sum,&alphax_sum);
VectorInit(alpha2_sum,alphax_sum.w);
VectorMultiplyAdd(part2,twothirds_twothirds2,part3,&betax_sum);
VectorMultiplyAdd(part1,onethird_onethird2,betax_sum,&betax_sum);
VectorInit(beta2_sum,betax_sum.w);
VectorAdd(part1,part2,&alphabeta_sum);
VectorInit(alphabeta_sum,alphabeta_sum.w);
VectorMultiply(twonineths,alphabeta_sum,&alphabeta_sum);
VectorMultiply(alpha2_sum,beta2_sum,&factor);
VectorNegativeMultiplySubtract(alphabeta_sum,alphabeta_sum,factor,
&factor);
VectorReciprocal(factor,&factor);
VectorMultiply(alphax_sum,beta2_sum,&a);
VectorNegativeMultiplySubtract(betax_sum,alphabeta_sum,a,&a);
VectorMultiply(a,factor,&a);
VectorMultiply(betax_sum,alpha2_sum,&b);
VectorNegativeMultiplySubtract(alphax_sum,alphabeta_sum,b,&b);
VectorMultiply(b,factor,&b);
VectorClamp(&a);
VectorMultiplyAdd(grid,a,half,&a);
VectorTruncate(&a);
VectorMultiply(a,gridrcp,&a);
VectorClamp(&b);
VectorMultiplyAdd(grid,b,half,&b);
VectorTruncate(&b);
VectorMultiply(b,gridrcp,&b);
VectorMultiply(b,b,&e1);
VectorMultiply(e1,beta2_sum,&e1);
VectorMultiply(a,a,&e2);
VectorMultiplyAdd(e2,alpha2_sum,e1,&e1);
VectorMultiply(a,b,&e2);
VectorMultiply(e2,alphabeta_sum,&e2);
VectorNegativeMultiplySubtract(a,alphax_sum,e2,&e2);
VectorNegativeMultiplySubtract(b,betax_sum,e2,&e2);
VectorMultiplyAdd(two,e2,e1,&e2);
VectorMultiply(e2,metric,&e2);
error = e2.x + e2.y + e2.z;
if (error < bestError)
{
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp critical (DDS_CompressClusterFit)
#endif
{
if (error < bestError)
{
VectorCopy43(a,start);
VectorCopy43(b,end);
bestError = error;
besti = i;
bestj = j;
bestk = k;
bestIteration = iterationIndex;
}
}
}
if (k == count)
break;
VectorAdd(pointsWeights[k],part2,&part2);
k++;
}
if (j == count)
break;
VectorAdd(pointsWeights[j],part1,&part1);
j++;
}
}
if (bestIteration != iterationIndex)
break;
iterationIndex++;
if (iterationIndex == 8)
break;
VectorSubtract3(*end,*start,&axis);
if (ConstructOrdering(count,points,axis,pointsWeights,&xSumwSum,order,
iterationIndex) == MagickFalse)
break;
}
o = order + (16*bestIteration);
for (i=0; i < (ssize_t) besti; i++)
unordered[o[i]] = 0;
for (i=besti; i < (ssize_t) bestj; i++)
unordered[o[i]] = 2;
for (i=bestj; i < (ssize_t) bestk; i++)
unordered[o[i]] = 3;
for (i=bestk; i < (ssize_t) count; i++)
unordered[o[i]] = 1;
RemapIndices(map,unordered,indices);
}
static void CompressRangeFit(const size_t count,
const DDSVector4 *points, const ssize_t *map, const DDSVector3 principle,
const DDSVector4 metric, DDSVector3 *start, DDSVector3 *end,
unsigned char *indices)
{
float
d,
bestDist,
max,
min,
val;
DDSVector3
codes[4],
grid,
gridrcp,
half,
dist;
register ssize_t
i;
size_t
bestj,
j;
unsigned char
closest[16];
VectorInit3(half,0.5f);
grid.x = 31.0f;
grid.y = 63.0f;
grid.z = 31.0f;
gridrcp.x = 1.0f/31.0f;
gridrcp.y = 1.0f/63.0f;
gridrcp.z = 1.0f/31.0f;
if (count > 0)
{
VectorCopy43(points[0],start);
VectorCopy43(points[0],end);
min = max = Dot(points[0],principle);
for (i=1; i < (ssize_t) count; i++)
{
val = Dot(points[i],principle);
if (val < min)
{
VectorCopy43(points[i],start);
min = val;
}
else if (val > max)
{
VectorCopy43(points[i],end);
max = val;
}
}
}
VectorClamp3(start);
VectorMultiplyAdd3(grid,*start,half,start);
VectorTruncate3(start);
VectorMultiply3(*start,gridrcp,start);
VectorClamp3(end);
VectorMultiplyAdd3(grid,*end,half,end);
VectorTruncate3(end);
VectorMultiply3(*end,gridrcp,end);
codes[0] = *start;
codes[1] = *end;
codes[2].x = (start->x * (2.0f/3.0f)) + (end->x * (1.0f/3.0f));
codes[2].y = (start->y * (2.0f/3.0f)) + (end->y * (1.0f/3.0f));
codes[2].z = (start->z * (2.0f/3.0f)) + (end->z * (1.0f/3.0f));
codes[3].x = (start->x * (1.0f/3.0f)) + (end->x * (2.0f/3.0f));
codes[3].y = (start->y * (1.0f/3.0f)) + (end->y * (2.0f/3.0f));
codes[3].z = (start->z * (1.0f/3.0f)) + (end->z * (2.0f/3.0f));
for (i=0; i < (ssize_t) count; i++)
{
bestDist = 1e+37f;
bestj = 0;
for (j=0; j < 4; j++)
{
dist.x = (points[i].x - codes[j].x) * metric.x;
dist.y = (points[i].y - codes[j].y) * metric.y;
dist.z = (points[i].z - codes[j].z) * metric.z;
d = Dot(dist,dist);
if (d < bestDist)
{
bestDist = d;
bestj = j;
}
}
closest[i] = (unsigned char) bestj;
}
RemapIndices(map, closest, indices);
}
static void ComputeEndPoints(const DDSSingleColourLookup *lookup[],
const unsigned char *color, DDSVector3 *start, DDSVector3 *end,
unsigned char *index)
{
register ssize_t
i;
size_t
c,
maxError = SIZE_MAX;
for (i=0; i < 2; i++)
{
const DDSSourceBlock*
sources[3];
size_t
error = 0;
for (c=0; c < 3; c++)
{
sources[c] = &lookup[c][color[c]].sources[i];
error += ((size_t) sources[c]->error) * ((size_t) sources[c]->error);
}
if (error > maxError)
continue;
start->x = (float) sources[0]->start / 31.0f;
start->y = (float) sources[1]->start / 63.0f;
start->z = (float) sources[2]->start / 31.0f;
end->x = (float) sources[0]->end / 31.0f;
end->y = (float) sources[1]->end / 63.0f;
end->z = (float) sources[2]->end / 31.0f;
*index = (unsigned char) (2*i);
maxError = error;
}
}
static void ComputePrincipleComponent(const float *covariance,
DDSVector3 *principle)
{
DDSVector4
row0,
row1,
row2,
v;
register ssize_t
i;
row0.x = covariance[0];
row0.y = covariance[1];
row0.z = covariance[2];
row0.w = 0.0f;
row1.x = covariance[1];
row1.y = covariance[3];
row1.z = covariance[4];
row1.w = 0.0f;
row2.x = covariance[2];
row2.y = covariance[4];
row2.z = covariance[5];
row2.w = 0.0f;
VectorInit(v,1.0f);
for (i=0; i < 8; i++)
{
DDSVector4
w;
float
a;
w.x = row0.x * v.x;
w.y = row0.y * v.x;
w.z = row0.z * v.x;
w.w = row0.w * v.x;
w.x = (row1.x * v.y) + w.x;
w.y = (row1.y * v.y) + w.y;
w.z = (row1.z * v.y) + w.z;
w.w = (row1.w * v.y) + w.w;
w.x = (row2.x * v.z) + w.x;
w.y = (row2.y * v.z) + w.y;
w.z = (row2.z * v.z) + w.z;
w.w = (row2.w * v.z) + w.w;
a = (float) PerceptibleReciprocal(MagickMax(w.x,MagickMax(w.y,w.z)));
v.x = w.x * a;
v.y = w.y * a;
v.z = w.z * a;
v.w = w.w * a;
}
VectorCopy43(v,principle);
}
static void ComputeWeightedCovariance(const size_t count,
const DDSVector4 *points, float *covariance)
{
DDSVector3
centroid;
float
total;
size_t
i;
total = 0.0f;
VectorInit3(centroid,0.0f);
for (i=0; i < count; i++)
{
total += points[i].w;
centroid.x += (points[i].x * points[i].w);
centroid.y += (points[i].y * points[i].w);
centroid.z += (points[i].z * points[i].w);
}
if( total > 1.192092896e-07F)
{
centroid.x /= total;
centroid.y /= total;
centroid.z /= total;
}
for (i=0; i < 6; i++)
covariance[i] = 0.0f;
for (i = 0; i < count; i++)
{
DDSVector3
a,
b;
a.x = points[i].x - centroid.x;
a.y = points[i].y - centroid.y;
a.z = points[i].z - centroid.z;
b.x = points[i].w * a.x;
b.y = points[i].w * a.y;
b.z = points[i].w * a.z;
covariance[0] += a.x*b.x;
covariance[1] += a.x*b.y;
covariance[2] += a.x*b.z;
covariance[3] += a.y*b.y;
covariance[4] += a.y*b.z;
covariance[5] += a.z*b.z;
}
}
static MagickBooleanType ConstructOrdering(const size_t count,
const DDSVector4 *points, const DDSVector3 axis, DDSVector4 *pointsWeights,
DDSVector4 *xSumwSum, unsigned char *order, size_t iteration)
{
float
dps[16],
f;
register ssize_t
i;
size_t
j;
unsigned char
c,
*o,
*p;
o = order + (16*iteration);
for (i=0; i < (ssize_t) count; i++)
{
dps[i] = Dot(points[i],axis);
o[i] = (unsigned char)i;
}
for (i=0; i < (ssize_t) count; i++)
{
for (j=i; j > 0 && dps[j] < dps[j - 1]; j--)
{
f = dps[j];
dps[j] = dps[j - 1];
dps[j - 1] = f;
c = o[j];
o[j] = o[j - 1];
o[j - 1] = c;
}
}
for (i=0; i < (ssize_t) iteration; i++)
{
MagickBooleanType
same;
p = order + (16*i);
same = MagickTrue;
for (j=0; j < count; j++)
{
if (o[j] != p[j])
{
same = MagickFalse;
break;
}
}
if (same != MagickFalse)
return MagickFalse;
}
xSumwSum->x = 0;
xSumwSum->y = 0;
xSumwSum->z = 0;
xSumwSum->w = 0;
for (i=0; i < (ssize_t) count; i++)
{
DDSVector4
v;
j = (size_t) o[i];
v.x = points[j].w * points[j].x;
v.y = points[j].w * points[j].y;
v.z = points[j].w * points[j].z;
v.w = points[j].w * 1.0f;
VectorCopy44(v,&pointsWeights[i]);
VectorAdd(*xSumwSum,v,xSumwSum);
}
return MagickTrue;
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% I s D D S %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% IsDDS() returns MagickTrue if the image format type, identified by the
% magick string, is DDS.
%
% The format of the IsDDS method is:
%
% MagickBooleanType IsDDS(const unsigned char *magick,const size_t length)
%
% A description of each parameter follows:
%
% o magick: compare image format pattern against these bytes.
%
% o length: Specifies the length of the magick string.
%
*/
static MagickBooleanType IsDDS(const unsigned char *magick, const size_t length)
{
if (length < 4)
return(MagickFalse);
if (LocaleNCompare((char *) magick,"DDS ", 4) == 0)
return(MagickTrue);
return(MagickFalse);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% R e a d D D S I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% ReadDDSImage() reads a DirectDraw Surface image file and returns it. It
% allocates the memory necessary for the new Image structure and returns a
% pointer to the new image.
%
% The format of the ReadDDSImage method is:
%
% Image *ReadDDSImage(const ImageInfo *image_info,ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image_info: The image info.
%
% o exception: return any errors or warnings in this structure.
%
*/
static Image *ReadDDSImage(const ImageInfo *image_info,ExceptionInfo *exception)
{
Image
*image;
MagickBooleanType
status,
cubemap = MagickFalse,
volume = MagickFalse,
matte;
CompressionType
compression;
DDSInfo
dds_info;
DDSDecoder
*decoder;
size_t
n,
num_images;
/*
Open image file.
*/
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickCoreSignature);
if (image_info->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",
image_info->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickCoreSignature);
image=AcquireImage(image_info);
status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);
if (status == MagickFalse)
{
image=DestroyImageList(image);
return((Image *) NULL);
}
/*
Initialize image structure.
*/
if (ReadDDSInfo(image, &dds_info) != MagickTrue)
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
if (dds_info.ddscaps2 & DDSCAPS2_CUBEMAP)
cubemap = MagickTrue;
if (dds_info.ddscaps2 & DDSCAPS2_VOLUME && dds_info.depth > 0)
volume = MagickTrue;
(void) SeekBlob(image, 128, SEEK_SET);
/*
Determine pixel format
*/
if (dds_info.pixelformat.flags & DDPF_RGB)
{
compression = NoCompression;
if (dds_info.pixelformat.flags & DDPF_ALPHAPIXELS)
{
matte = MagickTrue;
decoder = ReadUncompressedRGBA;
}
else
{
matte = MagickTrue;
decoder = ReadUncompressedRGB;
}
}
else if (dds_info.pixelformat.flags & DDPF_LUMINANCE)
{
compression = NoCompression;
if (dds_info.pixelformat.flags & DDPF_ALPHAPIXELS)
{
/* Not sure how to handle this */
ThrowReaderException(CorruptImageError, "ImageTypeNotSupported");
}
else
{
matte = MagickFalse;
decoder = ReadUncompressedRGB;
}
}
else if (dds_info.pixelformat.flags & DDPF_FOURCC)
{
switch (dds_info.pixelformat.fourcc)
{
case FOURCC_DXT1:
{
matte = MagickFalse;
compression = DXT1Compression;
decoder = ReadDXT1;
break;
}
case FOURCC_DXT3:
{
matte = MagickTrue;
compression = DXT3Compression;
decoder = ReadDXT3;
break;
}
case FOURCC_DXT5:
{
matte = MagickTrue;
compression = DXT5Compression;
decoder = ReadDXT5;
break;
}
default:
{
/* Unknown FOURCC */
ThrowReaderException(CorruptImageError, "ImageTypeNotSupported");
}
}
}
else
{
/* Neither compressed nor uncompressed... thus unsupported */
ThrowReaderException(CorruptImageError, "ImageTypeNotSupported");
}
num_images = 1;
if (cubemap)
{
/*
Determine number of faces defined in the cubemap
*/
num_images = 0;
if (dds_info.ddscaps2 & DDSCAPS2_CUBEMAP_POSITIVEX) num_images++;
if (dds_info.ddscaps2 & DDSCAPS2_CUBEMAP_NEGATIVEX) num_images++;
if (dds_info.ddscaps2 & DDSCAPS2_CUBEMAP_POSITIVEY) num_images++;
if (dds_info.ddscaps2 & DDSCAPS2_CUBEMAP_NEGATIVEY) num_images++;
if (dds_info.ddscaps2 & DDSCAPS2_CUBEMAP_POSITIVEZ) num_images++;
if (dds_info.ddscaps2 & DDSCAPS2_CUBEMAP_NEGATIVEZ) num_images++;
}
if (volume)
num_images = dds_info.depth;
if ((num_images == 0) || (num_images > GetBlobSize(image)))
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
if (AcquireMagickResource(ListLengthResource,num_images) == MagickFalse)
ThrowReaderException(ResourceLimitError,"ListLengthExceedsLimit");
for (n = 0; n < num_images; n++)
{
if (n != 0)
{
if (EOFBlob(image) != MagickFalse)
ThrowReaderException(CorruptImageError,"UnexpectedEndOfFile");
/* Start a new image */
AcquireNextImage(image_info,image);
if (GetNextImageInList(image) == (Image *) NULL)
return(DestroyImageList(image));
image=SyncNextImageInList(image);
}
image->matte = matte;
image->compression = compression;
image->columns = dds_info.width;
image->rows = dds_info.height;
image->storage_class = DirectClass;
image->endian = LSBEndian;
image->depth = 8;
if (image_info->ping != MagickFalse)
{
(void) CloseBlob(image);
return(GetFirstImageInList(image));
}
status=SetImageExtent(image,image->columns,image->rows);
if (status == MagickFalse)
{
InheritException(exception,&image->exception);
return(DestroyImageList(image));
}
(void) SetImageBackgroundColor(image);
if ((decoder)(image, &dds_info, exception) != MagickTrue)
{
(void) CloseBlob(image);
return(GetFirstImageInList(image));
}
}
(void) CloseBlob(image);
return(GetFirstImageInList(image));
}
static MagickBooleanType ReadDDSInfo(Image *image, DDSInfo *dds_info)
{
size_t
hdr_size,
required;
/* Seek to start of header */
(void) SeekBlob(image, 4, SEEK_SET);
/* Check header field */
hdr_size = ReadBlobLSBLong(image);
if (hdr_size != 124)
return MagickFalse;
/* Fill in DDS info struct */
dds_info->flags = ReadBlobLSBLong(image);
/* Check required flags */
required=(size_t) (DDSD_WIDTH | DDSD_HEIGHT | DDSD_PIXELFORMAT);
if ((dds_info->flags & required) != required)
return MagickFalse;
dds_info->height = ReadBlobLSBLong(image);
dds_info->width = ReadBlobLSBLong(image);
dds_info->pitchOrLinearSize = ReadBlobLSBLong(image);
dds_info->depth = ReadBlobLSBLong(image);
dds_info->mipmapcount = ReadBlobLSBLong(image);
(void) SeekBlob(image, 44, SEEK_CUR); /* reserved region of 11 DWORDs */
/* Read pixel format structure */
hdr_size = ReadBlobLSBLong(image);
if (hdr_size != 32)
return MagickFalse;
dds_info->pixelformat.flags = ReadBlobLSBLong(image);
dds_info->pixelformat.fourcc = ReadBlobLSBLong(image);
dds_info->pixelformat.rgb_bitcount = ReadBlobLSBLong(image);
dds_info->pixelformat.r_bitmask = ReadBlobLSBLong(image);
dds_info->pixelformat.g_bitmask = ReadBlobLSBLong(image);
dds_info->pixelformat.b_bitmask = ReadBlobLSBLong(image);
dds_info->pixelformat.alpha_bitmask = ReadBlobLSBLong(image);
dds_info->ddscaps1 = ReadBlobLSBLong(image);
dds_info->ddscaps2 = ReadBlobLSBLong(image);
(void) SeekBlob(image, 12, SEEK_CUR); /* 3 reserved DWORDs */
return MagickTrue;
}
static MagickBooleanType ReadDXT1(Image *image,DDSInfo *dds_info,
ExceptionInfo *exception)
{
DDSColors
colors;
PixelPacket
*q;
register ssize_t
i,
x;
size_t
bits;
ssize_t
j,
y;
unsigned char
code;
unsigned short
c0,
c1;
for (y = 0; y < (ssize_t) image->rows; y += 4)
{
for (x = 0; x < (ssize_t) image->columns; x += 4)
{
/* Get 4x4 patch of pixels to write on */
q=QueueAuthenticPixels(image,x,y,MagickMin(4,image->columns-x),
MagickMin(4,image->rows-y),exception);
if (q == (PixelPacket *) NULL)
return MagickFalse;
/* Read 8 bytes of data from the image */
c0 = ReadBlobLSBShort(image);
c1 = ReadBlobLSBShort(image);
bits = ReadBlobLSBLong(image);
CalculateColors(c0, c1, &colors, MagickFalse);
if (EOFBlob(image) != MagickFalse)
break;
/* Write the pixels */
for (j = 0; j < 4; j++)
{
for (i = 0; i < 4; i++)
{
if (((x + i) < (ssize_t) image->columns) &&
((y + j) < (ssize_t) image->rows))
{
code=(unsigned char) ((bits >> ((j*4+i)*2)) & 0x3);
SetPixelRed(q,ScaleCharToQuantum(colors.r[code]));
SetPixelGreen(q,ScaleCharToQuantum(colors.g[code]));
SetPixelBlue(q,ScaleCharToQuantum(colors.b[code]));
SetPixelOpacity(q,ScaleCharToQuantum(colors.a[code]));
if ((colors.a[code] != 0) && (image->matte == MagickFalse))
image->matte=MagickTrue; /* Correct matte */
q++;
}
}
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
return MagickFalse;
}
if (EOFBlob(image) != MagickFalse)
break;
}
return(SkipDXTMipmaps(image,dds_info,8,exception));
}
static MagickBooleanType ReadDXT3(Image *image, DDSInfo *dds_info,
ExceptionInfo *exception)
{
DDSColors
colors;
ssize_t
j,
y;
PixelPacket
*q;
register ssize_t
i,
x;
unsigned char
alpha;
size_t
a0,
a1,
bits,
code;
unsigned short
c0,
c1;
for (y = 0; y < (ssize_t) dds_info->height; y += 4)
{
for (x = 0; x < (ssize_t) dds_info->width; x += 4)
{
/* Get 4x4 patch of pixels to write on */
q = QueueAuthenticPixels(image, x, y, MagickMin(4, dds_info->width - x),
MagickMin(4, dds_info->height - y),exception);
if (q == (PixelPacket *) NULL)
return MagickFalse;
/* Read alpha values (8 bytes) */
a0 = ReadBlobLSBLong(image);
a1 = ReadBlobLSBLong(image);
/* Read 8 bytes of data from the image */
c0 = ReadBlobLSBShort(image);
c1 = ReadBlobLSBShort(image);
bits = ReadBlobLSBLong(image);
CalculateColors(c0, c1, &colors, MagickTrue);
if (EOFBlob(image) != MagickFalse)
break;
/* Write the pixels */
for (j = 0; j < 4; j++)
{
for (i = 0; i < 4; i++)
{
if ((x + i) < (ssize_t) dds_info->width && (y + j) < (ssize_t) dds_info->height)
{
code = (bits >> ((4*j+i)*2)) & 0x3;
SetPixelRed(q,ScaleCharToQuantum(colors.r[code]));
SetPixelGreen(q,ScaleCharToQuantum(colors.g[code]));
SetPixelBlue(q,ScaleCharToQuantum(colors.b[code]));
/*
Extract alpha value: multiply 0..15 by 17 to get range 0..255
*/
if (j < 2)
alpha = 17U * (unsigned char) ((a0 >> (4*(4*j+i))) & 0xf);
else
alpha = 17U * (unsigned char) ((a1 >> (4*(4*(j-2)+i))) & 0xf);
SetPixelAlpha(q,ScaleCharToQuantum((unsigned char)
alpha));
q++;
}
}
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
return MagickFalse;
}
if (EOFBlob(image) != MagickFalse)
break;
}
return(SkipDXTMipmaps(image,dds_info,16,exception));
}
static MagickBooleanType ReadDXT5(Image *image, DDSInfo *dds_info,
ExceptionInfo *exception)
{
DDSColors
colors;
ssize_t
j,
y;
MagickSizeType
alpha_bits;
PixelPacket
*q;
register ssize_t
i,
x;
unsigned char
a0,
a1;
size_t
alpha,
bits,
code,
alpha_code;
unsigned short
c0,
c1;
for (y = 0; y < (ssize_t) dds_info->height; y += 4)
{
for (x = 0; x < (ssize_t) dds_info->width; x += 4)
{
/* Get 4x4 patch of pixels to write on */
q = QueueAuthenticPixels(image, x, y, MagickMin(4, dds_info->width - x),
MagickMin(4, dds_info->height - y),exception);
if (q == (PixelPacket *) NULL)
return MagickFalse;
/* Read alpha values (8 bytes) */
a0 = (unsigned char) ReadBlobByte(image);
a1 = (unsigned char) ReadBlobByte(image);
alpha_bits = (MagickSizeType)ReadBlobLSBLong(image);
alpha_bits = alpha_bits | ((MagickSizeType)ReadBlobLSBShort(image) << 32);
/* Read 8 bytes of data from the image */
c0 = ReadBlobLSBShort(image);
c1 = ReadBlobLSBShort(image);
bits = ReadBlobLSBLong(image);
CalculateColors(c0, c1, &colors, MagickTrue);
if (EOFBlob(image) != MagickFalse)
break;
/* Write the pixels */
for (j = 0; j < 4; j++)
{
for (i = 0; i < 4; i++)
{
if ((x + i) < (ssize_t) dds_info->width && (y + j) < (ssize_t) dds_info->height)
{
code = (bits >> ((4*j+i)*2)) & 0x3;
SetPixelRed(q,ScaleCharToQuantum(colors.r[code]));
SetPixelGreen(q,ScaleCharToQuantum(colors.g[code]));
SetPixelBlue(q,ScaleCharToQuantum(colors.b[code]));
/* Extract alpha value */
alpha_code = (size_t) (alpha_bits >> (3*(4*j+i))) & 0x7;
if (alpha_code == 0)
alpha = a0;
else if (alpha_code == 1)
alpha = a1;
else if (a0 > a1)
alpha = ((8-alpha_code) * a0 + (alpha_code-1) * a1) / 7;
else if (alpha_code == 6)
alpha = 0;
else if (alpha_code == 7)
alpha = 255;
else
alpha = (((6-alpha_code) * a0 + (alpha_code-1) * a1) / 5);
SetPixelAlpha(q,ScaleCharToQuantum((unsigned char)
alpha));
q++;
}
}
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
return MagickFalse;
}
if (EOFBlob(image) != MagickFalse)
break;
}
return(SkipDXTMipmaps(image,dds_info,16,exception));
}
static MagickBooleanType ReadUncompressedRGB(Image *image, DDSInfo *dds_info,
ExceptionInfo *exception)
{
PixelPacket
*q;
ssize_t
x, y;
unsigned short
color;
if (dds_info->pixelformat.rgb_bitcount == 8)
(void) SetImageType(image,GrayscaleType);
else if (dds_info->pixelformat.rgb_bitcount == 16 && !IsBitMask(
dds_info->pixelformat,0xf800,0x07e0,0x001f,0x0000))
ThrowBinaryException(CorruptImageError,"ImageTypeNotSupported",
image->filename);
for (y = 0; y < (ssize_t) dds_info->height; y++)
{
q = QueueAuthenticPixels(image, 0, y, dds_info->width, 1,exception);
if (q == (PixelPacket *) NULL)
return MagickFalse;
for (x = 0; x < (ssize_t) dds_info->width; x++)
{
if (dds_info->pixelformat.rgb_bitcount == 8)
SetPixelGray(q,ScaleCharToQuantum(ReadBlobByte(image)));
else if (dds_info->pixelformat.rgb_bitcount == 16)
{
color=ReadBlobShort(image);
SetPixelRed(q,ScaleCharToQuantum((unsigned char)
(((color >> 11)/31.0)*255)));
SetPixelGreen(q,ScaleCharToQuantum((unsigned char)
((((unsigned short)(color << 5) >> 10)/63.0)*255)));
SetPixelBlue(q,ScaleCharToQuantum((unsigned char)
((((unsigned short)(color << 11) >> 11)/31.0)*255)));
}
else
{
SetPixelBlue(q,ScaleCharToQuantum((unsigned char)
ReadBlobByte(image)));
SetPixelGreen(q,ScaleCharToQuantum((unsigned char)
ReadBlobByte(image)));
SetPixelRed(q,ScaleCharToQuantum((unsigned char)
ReadBlobByte(image)));
if (dds_info->pixelformat.rgb_bitcount == 32)
(void) ReadBlobByte(image);
}
SetPixelAlpha(q,QuantumRange);
q++;
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
return MagickFalse;
}
return(SkipRGBMipmaps(image,dds_info,3,exception));
}
static MagickBooleanType ReadUncompressedRGBA(Image *image, DDSInfo *dds_info,
ExceptionInfo *exception)
{
PixelPacket
*q;
ssize_t
alphaBits,
x,
y;
unsigned short
color;
alphaBits=0;
if (dds_info->pixelformat.rgb_bitcount == 16)
{
if (IsBitMask(dds_info->pixelformat,0x7c00,0x03e0,0x001f,0x8000))
alphaBits=1;
else if (IsBitMask(dds_info->pixelformat,0x00ff,0x00ff,0x00ff,0xff00))
{
alphaBits=2;
(void) SetImageType(image,GrayscaleMatteType);
}
else if (IsBitMask(dds_info->pixelformat,0x0f00,0x00f0,0x000f,0xf000))
alphaBits=4;
else
ThrowBinaryException(CorruptImageError,"ImageTypeNotSupported",
image->filename);
}
for (y = 0; y < (ssize_t) dds_info->height; y++)
{
q = QueueAuthenticPixels(image, 0, y, dds_info->width, 1,exception);
if (q == (PixelPacket *) NULL)
return MagickFalse;
for (x = 0; x < (ssize_t) dds_info->width; x++)
{
if (dds_info->pixelformat.rgb_bitcount == 16)
{
color=ReadBlobShort(image);
if (alphaBits == 1)
{
SetPixelAlpha(q,(color & (1 << 15)) ? QuantumRange : 0);
SetPixelRed(q,ScaleCharToQuantum((unsigned char)
((((unsigned short)(color << 1) >> 11)/31.0)*255)));
SetPixelGreen(q,ScaleCharToQuantum((unsigned char)
((((unsigned short)(color << 6) >> 11)/31.0)*255)));
SetPixelBlue(q,ScaleCharToQuantum((unsigned char)
((((unsigned short)(color << 11) >> 11)/31.0)*255)));
}
else if (alphaBits == 2)
{
SetPixelAlpha(q,ScaleCharToQuantum((unsigned char)
(color >> 8)));
SetPixelGray(q,ScaleCharToQuantum((unsigned char)color));
}
else
{
SetPixelAlpha(q,ScaleCharToQuantum((unsigned char)
(((color >> 12)/15.0)*255)));
SetPixelRed(q,ScaleCharToQuantum((unsigned char)
((((unsigned short)(color << 4) >> 12)/15.0)*255)));
SetPixelGreen(q,ScaleCharToQuantum((unsigned char)
((((unsigned short)(color << 8) >> 12)/15.0)*255)));
SetPixelBlue(q,ScaleCharToQuantum((unsigned char)
((((unsigned short)(color << 12) >> 12)/15.0)*255)));
}
}
else
{
SetPixelBlue(q,ScaleCharToQuantum((unsigned char)
ReadBlobByte(image)));
SetPixelGreen(q,ScaleCharToQuantum((unsigned char)
ReadBlobByte(image)));
SetPixelRed(q,ScaleCharToQuantum((unsigned char)
ReadBlobByte(image)));
SetPixelAlpha(q,ScaleCharToQuantum((unsigned char)
ReadBlobByte(image)));
}
q++;
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
return MagickFalse;
}
return(SkipRGBMipmaps(image,dds_info,4,exception));
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% R e g i s t e r D D S I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% RegisterDDSImage() adds attributes for the DDS image format to
% the list of supported formats. The attributes include the image format
% tag, a method to read and/or write the format, whether the format
% supports the saving of more than one frame to the same file or blob,
% whether the format supports native in-memory I/O, and a brief
% description of the format.
%
% The format of the RegisterDDSImage method is:
%
% RegisterDDSImage(void)
%
*/
ModuleExport size_t RegisterDDSImage(void)
{
MagickInfo
*entry;
entry = SetMagickInfo("DDS");
entry->decoder = (DecodeImageHandler *) ReadDDSImage;
entry->encoder = (EncodeImageHandler *) WriteDDSImage;
entry->magick = (IsImageFormatHandler *) IsDDS;
entry->seekable_stream=MagickTrue;
entry->description = ConstantString("Microsoft DirectDraw Surface");
entry->module = ConstantString("DDS");
(void) RegisterMagickInfo(entry);
entry = SetMagickInfo("DXT1");
entry->decoder = (DecodeImageHandler *) ReadDDSImage;
entry->encoder = (EncodeImageHandler *) WriteDDSImage;
entry->magick = (IsImageFormatHandler *) IsDDS;
entry->seekable_stream=MagickTrue;
entry->description = ConstantString("Microsoft DirectDraw Surface");
entry->module = ConstantString("DDS");
(void) RegisterMagickInfo(entry);
entry = SetMagickInfo("DXT5");
entry->decoder = (DecodeImageHandler *) ReadDDSImage;
entry->encoder = (EncodeImageHandler *) WriteDDSImage;
entry->magick = (IsImageFormatHandler *) IsDDS;
entry->seekable_stream=MagickTrue;
entry->description = ConstantString("Microsoft DirectDraw Surface");
entry->module = ConstantString("DDS");
(void) RegisterMagickInfo(entry);
return(MagickImageCoderSignature);
}
static void RemapIndices(const ssize_t *map, const unsigned char *source,
unsigned char *target)
{
register ssize_t
i;
for (i = 0; i < 16; i++)
{
if (map[i] == -1)
target[i] = 3;
else
target[i] = source[map[i]];
}
}
/*
Skip the mipmap images for compressed (DXTn) dds files
*/
static MagickBooleanType SkipDXTMipmaps(Image *image,DDSInfo *dds_info,
int texel_size,ExceptionInfo *exception)
{
register ssize_t
i;
MagickOffsetType
offset;
size_t
h,
w;
/*
Only skip mipmaps for textures and cube maps
*/
if (EOFBlob(image) != MagickFalse)
{
ThrowFileException(exception,CorruptImageWarning,"UnexpectedEndOfFile",
image->filename);
return(MagickFalse);
}
if (dds_info->ddscaps1 & DDSCAPS_MIPMAP
&& (dds_info->ddscaps1 & DDSCAPS_TEXTURE
|| dds_info->ddscaps2 & DDSCAPS2_CUBEMAP))
{
w = DIV2(dds_info->width);
h = DIV2(dds_info->height);
/*
Mipmapcount includes the main image, so start from one
*/
for (i = 1; (i < (ssize_t) dds_info->mipmapcount) && w && h; i++)
{
offset = (MagickOffsetType) ((w + 3) / 4) * ((h + 3) / 4) * texel_size;
if (SeekBlob(image,offset,SEEK_CUR) < 0)
break;
if ((w == 1) && (h == 1))
break;
w = DIV2(w);
h = DIV2(h);
}
}
return(MagickTrue);
}
/*
Skip the mipmap images for uncompressed (RGB or RGBA) dds files
*/
static MagickBooleanType SkipRGBMipmaps(Image *image,DDSInfo *dds_info,
int pixel_size,ExceptionInfo *exception)
{
MagickOffsetType
offset;
register ssize_t
i;
size_t
h,
w;
/*
Only skip mipmaps for textures and cube maps
*/
if (EOFBlob(image) != MagickFalse)
{
ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile",
image->filename);
return(MagickFalse);
}
if (dds_info->ddscaps1 & DDSCAPS_MIPMAP
&& (dds_info->ddscaps1 & DDSCAPS_TEXTURE
|| dds_info->ddscaps2 & DDSCAPS2_CUBEMAP))
{
w = DIV2(dds_info->width);
h = DIV2(dds_info->height);
/*
Mipmapcount includes the main image, so start from one
*/
for (i=1; (i < (ssize_t) dds_info->mipmapcount) && w && h; i++)
{
offset = (MagickOffsetType) w * h * pixel_size;
if (SeekBlob(image,offset,SEEK_CUR) < 0)
break;
w = DIV2(w);
h = DIV2(h);
if ((w == 1) && (h == 1))
break;
}
}
return(MagickTrue);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% U n r e g i s t e r D D S I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% UnregisterDDSImage() removes format registrations made by the
% DDS module from the list of supported formats.
%
% The format of the UnregisterDDSImage method is:
%
% UnregisterDDSImage(void)
%
*/
ModuleExport void UnregisterDDSImage(void)
{
(void) UnregisterMagickInfo("DDS");
(void) UnregisterMagickInfo("DXT1");
(void) UnregisterMagickInfo("DXT5");
}
static void WriteAlphas(Image *image, const ssize_t* alphas, size_t min5,
size_t max5, size_t min7, size_t max7)
{
register ssize_t
i;
size_t
err5,
err7,
j;
unsigned char
indices5[16],
indices7[16];
FixRange(min5,max5,5);
err5 = CompressAlpha(min5,max5,5,alphas,indices5);
FixRange(min7,max7,7);
err7 = CompressAlpha(min7,max7,7,alphas,indices7);
if (err7 < err5)
{
for (i=0; i < 16; i++)
{
unsigned char
index;
index = indices7[i];
if( index == 0 )
indices5[i] = 1;
else if (index == 1)
indices5[i] = 0;
else
indices5[i] = 9 - index;
}
min5 = max7;
max5 = min7;
}
(void) WriteBlobByte(image,(unsigned char) min5);
(void) WriteBlobByte(image,(unsigned char) max5);
for(i=0; i < 2; i++)
{
size_t
value = 0;
for (j=0; j < 8; j++)
{
size_t index = (size_t) indices5[j + i*8];
value |= ( index << 3*j );
}
for (j=0; j < 3; j++)
{
size_t byte = (value >> 8*j) & 0xff;
(void) WriteBlobByte(image,(unsigned char) byte);
}
}
}
static void WriteCompressed(Image *image, const size_t count,
DDSVector4* points, const ssize_t* map, const MagickBooleanType clusterFit)
{
float
covariance[16];
DDSVector3
end,
principle,
start;
DDSVector4
metric;
unsigned char
indices[16];
VectorInit(metric,1.0f);
VectorInit3(start,0.0f);
VectorInit3(end,0.0f);
ComputeWeightedCovariance(count,points,covariance);
ComputePrincipleComponent(covariance,&principle);
if (clusterFit == MagickFalse || count == 0)
CompressRangeFit(count,points,map,principle,metric,&start,&end,indices);
else
CompressClusterFit(count,points,map,principle,metric,&start,&end,indices);
WriteIndices(image,start,end,indices);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% W r i t e D D S I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% WriteDDSImage() writes a DirectDraw Surface image file in the DXT5 format.
%
% The format of the WriteBMPImage method is:
%
% MagickBooleanType WriteDDSImage(const ImageInfo *image_info,Image *image)
%
% A description of each parameter follows.
%
% o image_info: the image info.
%
% o image: The image.
%
*/
static MagickBooleanType WriteDDSImage(const ImageInfo *image_info,
Image *image)
{
const char
*option;
size_t
compression,
columns,
maxMipmaps,
mipmaps,
pixelFormat,
rows;
MagickBooleanType
clusterFit,
status,
weightByAlpha;
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickCoreSignature);
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
status=OpenBlob(image_info,image,WriteBinaryBlobMode,&image->exception);
if (status == MagickFalse)
return(status);
(void) TransformImageColorspace(image,sRGBColorspace);
pixelFormat=DDPF_FOURCC;
compression=FOURCC_DXT5;
if (!image->matte)
compression=FOURCC_DXT1;
if (LocaleCompare(image_info->magick,"dxt1") == 0)
compression=FOURCC_DXT1;
option=GetImageOption(image_info,"dds:compression");
if (option != (char *) NULL)
{
if (LocaleCompare(option,"dxt1") == 0)
compression=FOURCC_DXT1;
if (LocaleCompare(option,"none") == 0)
pixelFormat=DDPF_RGB;
}
clusterFit=MagickFalse;
weightByAlpha=MagickFalse;
if (pixelFormat == DDPF_FOURCC)
{
option=GetImageOption(image_info,"dds:cluster-fit");
if (IsStringTrue(option) != MagickFalse)
{
clusterFit=MagickTrue;
if (compression != FOURCC_DXT1)
{
option=GetImageOption(image_info,"dds:weight-by-alpha");
if (IsStringTrue(option) != MagickFalse)
weightByAlpha=MagickTrue;
}
}
}
maxMipmaps=SIZE_MAX;
mipmaps=0;
if ((image->columns & (image->columns - 1)) == 0 &&
(image->rows & (image->rows - 1)) == 0)
{
option=GetImageOption(image_info,"dds:mipmaps");
if (option != (char *) NULL)
maxMipmaps=StringToUnsignedLong(option);
if (maxMipmaps != 0)
{
columns=image->columns;
rows=image->rows;
while ((columns != 1 || rows != 1) && mipmaps != maxMipmaps)
{
columns=DIV2(columns);
rows=DIV2(rows);
mipmaps++;
}
}
}
WriteDDSInfo(image,pixelFormat,compression,mipmaps);
WriteImageData(image,pixelFormat,compression,clusterFit,weightByAlpha,
&image->exception);
if (mipmaps > 0 && WriteMipmaps(image,pixelFormat,compression,mipmaps,
clusterFit,weightByAlpha,&image->exception) == MagickFalse)
return(MagickFalse);
(void) CloseBlob(image);
return(MagickTrue);
}
static void WriteDDSInfo(Image *image, const size_t pixelFormat,
const size_t compression, const size_t mipmaps)
{
char
software[MaxTextExtent];
register ssize_t
i;
unsigned int
format,
caps,
flags;
flags=(unsigned int) (DDSD_CAPS | DDSD_WIDTH | DDSD_HEIGHT |
DDSD_PIXELFORMAT);
caps=(unsigned int) DDSCAPS_TEXTURE;
format=(unsigned int) pixelFormat;
if (format == DDPF_FOURCC)
flags=flags | DDSD_LINEARSIZE;
else
flags=flags | DDSD_PITCH;
if (mipmaps > 0)
{
flags=flags | (unsigned int) DDSD_MIPMAPCOUNT;
caps=caps | (unsigned int) (DDSCAPS_MIPMAP | DDSCAPS_COMPLEX);
}
if (format != DDPF_FOURCC && image->matte)
format=format | DDPF_ALPHAPIXELS;
(void) WriteBlob(image,4,(unsigned char *) "DDS ");
(void) WriteBlobLSBLong(image,124);
(void) WriteBlobLSBLong(image,flags);
(void) WriteBlobLSBLong(image,(unsigned int) image->rows);
(void) WriteBlobLSBLong(image,(unsigned int) image->columns);
if (pixelFormat == DDPF_FOURCC)
{
/* Compressed DDS requires linear compressed size of first image */
if (compression == FOURCC_DXT1)
(void) WriteBlobLSBLong(image,(unsigned int) (MagickMax(1,
(image->columns+3)/4)*MagickMax(1,(image->rows+3)/4)*8));
else /* DXT5 */
(void) WriteBlobLSBLong(image,(unsigned int) (MagickMax(1,
(image->columns+3)/4)*MagickMax(1,(image->rows+3)/4)*16));
}
else
{
/* Uncompressed DDS requires byte pitch of first image */
if (image->matte != MagickFalse)
(void) WriteBlobLSBLong(image,(unsigned int) (image->columns * 4));
else
(void) WriteBlobLSBLong(image,(unsigned int) (image->columns * 3));
}
(void) WriteBlobLSBLong(image,0x00);
(void) WriteBlobLSBLong(image,(unsigned int) mipmaps+1);
(void) memset(software,0,sizeof(software));
(void) CopyMagickString(software,"IMAGEMAGICK",MaxTextExtent);
(void) WriteBlob(image,44,(unsigned char *) software);
(void) WriteBlobLSBLong(image,32);
(void) WriteBlobLSBLong(image,format);
if (pixelFormat == DDPF_FOURCC)
{
(void) WriteBlobLSBLong(image,(unsigned int) compression);
for(i=0;i < 5;i++) /* bitcount / masks */
(void) WriteBlobLSBLong(image,0x00);
}
else
{
(void) WriteBlobLSBLong(image,0x00);
if (image->matte != MagickFalse)
{
(void) WriteBlobLSBLong(image,32);
(void) WriteBlobLSBLong(image,0xff0000);
(void) WriteBlobLSBLong(image,0xff00);
(void) WriteBlobLSBLong(image,0xff);
(void) WriteBlobLSBLong(image,0xff000000);
}
else
{
(void) WriteBlobLSBLong(image,24);
(void) WriteBlobLSBLong(image,0xff0000);
(void) WriteBlobLSBLong(image,0xff00);
(void) WriteBlobLSBLong(image,0xff);
(void) WriteBlobLSBLong(image,0x00);
}
}
(void) WriteBlobLSBLong(image,caps);
for(i=0;i < 4;i++) /* ddscaps2 + reserved region */
(void) WriteBlobLSBLong(image,0x00);
}
static void WriteFourCC(Image *image, const size_t compression,
const MagickBooleanType clusterFit, const MagickBooleanType weightByAlpha,
ExceptionInfo *exception)
{
register const PixelPacket
*p;
register ssize_t
x;
ssize_t
i,
y,
bx,
by;
for (y=0; y < (ssize_t) image->rows; y+=4)
{
for (x=0; x < (ssize_t) image->columns; x+=4)
{
MagickBooleanType
match;
DDSVector4
point,
points[16];
size_t
count = 0,
max5 = 0,
max7 = 0,
min5 = 255,
min7 = 255,
columns = 4,
rows = 4;
ssize_t
alphas[16],
map[16];
unsigned char
alpha;
if (x + columns >= image->columns)
columns = image->columns - x;
if (y + rows >= image->rows)
rows = image->rows - y;
p=GetVirtualPixels(image,x,y,columns,rows,exception);
if (p == (const PixelPacket *) NULL)
break;
for (i=0; i<16; i++)
{
map[i] = -1;
alphas[i] = -1;
}
for (by=0; by < (ssize_t) rows; by++)
{
for (bx=0; bx < (ssize_t) columns; bx++)
{
if (compression == FOURCC_DXT5)
alpha = ScaleQuantumToChar(GetPixelAlpha(p));
else
alpha = 255;
if (compression == FOURCC_DXT5)
{
if (alpha < min7)
min7 = alpha;
if (alpha > max7)
max7 = alpha;
if (alpha != 0 && alpha < min5)
min5 = alpha;
if (alpha != 255 && alpha > max5)
max5 = alpha;
}
alphas[4*by + bx] = (size_t)alpha;
point.x = (float)ScaleQuantumToChar(GetPixelRed(p)) / 255.0f;
point.y = (float)ScaleQuantumToChar(GetPixelGreen(p)) / 255.0f;
point.z = (float)ScaleQuantumToChar(GetPixelBlue(p)) / 255.0f;
point.w = weightByAlpha ? (float)(alpha + 1) / 256.0f : 1.0f;
p++;
match = MagickFalse;
for (i=0; i < (ssize_t) count; i++)
{
if ((points[i].x == point.x) &&
(points[i].y == point.y) &&
(points[i].z == point.z) &&
(alpha >= 128 || compression == FOURCC_DXT5))
{
points[i].w += point.w;
map[4*by + bx] = i;
match = MagickTrue;
break;
}
}
if (match != MagickFalse)
continue;
points[count].x = point.x;
points[count].y = point.y;
points[count].z = point.z;
points[count].w = point.w;
map[4*by + bx] = count;
count++;
}
}
for (i=0; i < (ssize_t) count; i++)
points[i].w = sqrt(points[i].w);
if (compression == FOURCC_DXT5)
WriteAlphas(image,alphas,min5,max5,min7,max7);
if (count == 1)
WriteSingleColorFit(image,points,map);
else
WriteCompressed(image,count,points,map,clusterFit);
}
}
}
static void WriteImageData(Image *image, const size_t pixelFormat,
const size_t compression, const MagickBooleanType clusterFit,
const MagickBooleanType weightByAlpha, ExceptionInfo *exception)
{
if (pixelFormat == DDPF_FOURCC)
WriteFourCC(image,compression,clusterFit,weightByAlpha,exception);
else
WriteUncompressed(image,exception);
}
static inline size_t ClampToLimit(const float value,
const size_t limit)
{
size_t
result = (int) (value + 0.5f);
if (result < 0.0f)
return(0);
if (result > limit)
return(limit);
return result;
}
static inline size_t ColorTo565(const DDSVector3 point)
{
size_t r = ClampToLimit(31.0f*point.x,31);
size_t g = ClampToLimit(63.0f*point.y,63);
size_t b = ClampToLimit(31.0f*point.z,31);
return (r << 11) | (g << 5) | b;
}
static void WriteIndices(Image *image, const DDSVector3 start,
const DDSVector3 end, unsigned char* indices)
{
register ssize_t
i;
size_t
a,
b;
unsigned char
remapped[16];
const unsigned char
*ind;
a = ColorTo565(start);
b = ColorTo565(end);
for (i=0; i<16; i++)
{
if( a < b )
remapped[i] = (indices[i] ^ 0x1) & 0x3;
else if( a == b )
remapped[i] = 0;
else
remapped[i] = indices[i];
}
if( a < b )
Swap(a,b);
(void) WriteBlobByte(image,(unsigned char) (a & 0xff));
(void) WriteBlobByte(image,(unsigned char) (a >> 8));
(void) WriteBlobByte(image,(unsigned char) (b & 0xff));
(void) WriteBlobByte(image,(unsigned char) (b >> 8));
for (i=0; i<4; i++)
{
ind = remapped + 4*i;
(void) WriteBlobByte(image,ind[0] | (ind[1] << 2) | (ind[2] << 4) |
(ind[3] << 6));
}
}
static MagickBooleanType WriteMipmaps(Image *image, const size_t pixelFormat,
const size_t compression, const size_t mipmaps,
const MagickBooleanType clusterFit, const MagickBooleanType weightByAlpha,
ExceptionInfo *exception)
{
Image*
resize_image;
register ssize_t
i;
size_t
columns,
rows;
columns = image->columns;
rows = image->rows;
for (i=0; i< (ssize_t) mipmaps; i++)
{
resize_image = ResizeImage(image,DIV2(columns),DIV2(rows),TriangleFilter,1.0,
exception);
if (resize_image == (Image *) NULL)
return(MagickFalse);
DestroyBlob(resize_image);
resize_image->blob=ReferenceBlob(image->blob);
WriteImageData(resize_image,pixelFormat,compression,weightByAlpha,
clusterFit,exception);
resize_image=DestroyImage(resize_image);
columns = DIV2(columns);
rows = DIV2(rows);
}
return(MagickTrue);
}
static void WriteSingleColorFit(Image *image, const DDSVector4* points,
const ssize_t* map)
{
DDSVector3
start,
end;
register ssize_t
i;
unsigned char
color[3],
index,
indexes[16],
indices[16];
color[0] = (unsigned char) ClampToLimit(255.0f*points->x,255);
color[1] = (unsigned char) ClampToLimit(255.0f*points->y,255);
color[2] = (unsigned char) ClampToLimit(255.0f*points->z,255);
index=0;
ComputeEndPoints(DDS_LOOKUP,color,&start,&end,&index);
for (i=0; i< 16; i++)
indexes[i]=index;
RemapIndices(map,indexes,indices);
WriteIndices(image,start,end,indices);
}
static void WriteUncompressed(Image *image, ExceptionInfo *exception)
{
register const PixelPacket
*p;
register ssize_t
x;
ssize_t
y;
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++)
{
(void) WriteBlobByte(image,ScaleQuantumToChar(GetPixelBlue(p)));
(void) WriteBlobByte(image,ScaleQuantumToChar(GetPixelGreen(p)));
(void) WriteBlobByte(image,ScaleQuantumToChar(GetPixelRed(p)));
if (image->matte)
(void) WriteBlobByte(image,ScaleQuantumToChar(GetPixelAlpha(p)));
p++;
}
}
}
|
GB_emult_04_template.c | //------------------------------------------------------------------------------
// GB_emult_04_template: C<M>= A.*B, M sparse/hyper, A and B bitmap/full
//------------------------------------------------------------------------------
// SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2021, All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
//------------------------------------------------------------------------------
// C is sparse, with the same sparsity structure as M.
// A and B are both bitmap/full.
{
//--------------------------------------------------------------------------
// get M, A, B, and C
//--------------------------------------------------------------------------
const int8_t *restrict Ab = A->b ;
const int8_t *restrict Bb = B->b ;
const bool A_iso = A->iso ;
const bool B_iso = B->iso ;
#ifdef GB_ISO_EMULT
ASSERT (C->iso) ;
#else
ASSERT (!C->iso) ;
ASSERT (!(A_iso && B_iso)) ; // one of A or B can be iso, but not both
const GB_ATYPE *restrict Ax = (GB_ATYPE *) A->x ;
const GB_BTYPE *restrict Bx = (GB_BTYPE *) B->x ;
GB_CTYPE *restrict Cx = (GB_CTYPE *) C->x ;
#endif
const int64_t *restrict Mp = M->p ;
const int64_t *restrict Mh = M->h ;
const int64_t *restrict Mi = M->i ;
const GB_void *restrict Mx = (GB_void *) ((Mask_struct) ? NULL : M->x) ;
const int64_t vlen = M->vlen ;
const size_t msize = M->type->size ;
const int64_t *restrict Cp = C->p ;
int64_t *restrict Ci = C->i ;
const int64_t *restrict kfirst_Mslice = M_ek_slicing ;
const int64_t *restrict klast_Mslice = M_ek_slicing + M_ntasks ;
const int64_t *restrict pstart_Mslice = M_ek_slicing + M_ntasks * 2 ;
//--------------------------------------------------------------------------
// Method4: C<M>=A.*B where M is sparse/hyper, A and B are bitmap/full
//--------------------------------------------------------------------------
int tid ;
#pragma omp parallel for num_threads(M_nthreads) schedule(dynamic,1)
for (tid = 0 ; tid < M_ntasks ; tid++)
{
int64_t kfirst = kfirst_Mslice [tid] ;
int64_t klast = klast_Mslice [tid] ;
for (int64_t k = kfirst ; k <= klast ; k++)
{
int64_t j = GBH (Mh, k) ;
int64_t pstart = j * vlen ;
int64_t pM, pM_end, pC ;
GB_get_pA_and_pC (&pM, &pM_end, &pC, tid, k, kfirst, klast,
pstart_Mslice, Cp_kfirst, Cp, vlen, Mp, vlen) ;
for ( ; pM < pM_end ; pM++)
{
int64_t i = Mi [pM] ;
if (GB_mcast (Mx, pM, msize) &&
(GBB (Ab, pstart + i)
&& // TODO: for GB_add, use || instead
GBB (Bb, pstart + i)))
{
int64_t p = pstart + i ;
// C (i,j) = A (i,j) .* B (i,j)
Ci [pC] = i ;
#ifndef GB_ISO_EMULT
GB_GETA (aij, Ax, p, A_iso) ;
GB_GETB (bij, Bx, p, B_iso) ;
GB_BINOP (GB_CX (pC), aij, bij, i, j) ;
#endif
pC++ ;
}
}
}
}
}
|
GB_binop__band_uint64.c |
//------------------------------------------------------------------------------
// GB_binop: hard-coded functions for each built-in binary operator
//------------------------------------------------------------------------------
// SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2022, All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
//------------------------------------------------------------------------------
// If this file is in the Generated2/ folder, do not edit it
// (it is auto-generated from Generator/*).
#include "GB.h"
#ifndef GBCOMPACT
#include "GB_emult.h"
#include "GB_control.h"
#include "GB_ek_slice.h"
#include "GB_dense.h"
#include "GB_atomics.h"
#include "GB_bitmap_assign_methods.h"
#include "GB_binop__include.h"
// C=binop(A,B) is defined by the following types and operators:
// A+B function (eWiseAdd): GB (_AaddB__band_uint64)
// A.*B function (eWiseMult): GB (_AemultB_08__band_uint64)
// A.*B function (eWiseMult): GB (_AemultB_02__band_uint64)
// A.*B function (eWiseMult): GB (_AemultB_04__band_uint64)
// A.*B function (eWiseMult): GB (_AemultB_bitmap__band_uint64)
// A*D function (colscale): GB (_AxD__band_uint64)
// D*A function (rowscale): GB (_DxB__band_uint64)
// C+=B function (dense accum): GB (_Cdense_accumB__band_uint64)
// C+=b function (dense accum): GB (_Cdense_accumb__band_uint64)
// C+=A+B function (dense ewise3): GB ((none))
// C=A+B function (dense ewise3): GB (_Cdense_ewise3_noaccum__band_uint64)
// C=scalar+B GB (_bind1st__band_uint64)
// C=scalar+B' GB (_bind1st_tran__band_uint64)
// C=A+scalar GB (_bind2nd__band_uint64)
// C=A'+scalar GB (_bind2nd_tran__band_uint64)
// C type: uint64_t
// A type: uint64_t
// A pattern? 0
// B type: uint64_t
// B pattern? 0
// 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)
// true if values of A are not used
#define GB_A_IS_PATTERN \
0 \
// bij = Bx [pB]
#define GB_GETB(bij,Bx,pB,B_iso) \
uint64_t bij = GBX (Bx, pB, B_iso)
// true if values of B are not used
#define GB_B_IS_PATTERN \
0 \
// declare scalar of the same type as C
#define GB_CTYPE_SCALAR(t) \
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_BAND || GxB_NO_UINT64 || GxB_NO_BAND_UINT64)
//------------------------------------------------------------------------------
// C += A+B, all 3 matrices dense
//------------------------------------------------------------------------------
#if 0
// The op must be MIN, MAX, PLUS, MINUS, RMINUS, TIMES, DIV, or RDIV.
void GB ((none))
(
GrB_Matrix C,
const GrB_Matrix A,
const GrB_Matrix B,
const int nthreads
)
{
#include "GB_dense_ewise3_accum_template.c"
}
#endif
//------------------------------------------------------------------------------
// C = A+B, all 3 matrices dense
//------------------------------------------------------------------------------
void GB (_Cdense_ewise3_noaccum__band_uint64)
(
GrB_Matrix C,
const GrB_Matrix A,
const GrB_Matrix B,
const int nthreads
)
{
#include "GB_dense_ewise3_noaccum_template.c"
}
//------------------------------------------------------------------------------
// C += B, accumulate a sparse matrix into a dense matrix
//------------------------------------------------------------------------------
GrB_Info GB (_Cdense_accumB__band_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__band_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__band_uint64)
(
GrB_Matrix C,
const GrB_Matrix A,
const GrB_Matrix D,
const int64_t *A_ek_slicing, const int A_ntasks, const int A_nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
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__band_uint64)
(
GrB_Matrix C,
const GrB_Matrix D,
const GrB_Matrix B,
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, C<M>=A+B, C<!M>=A+B
//------------------------------------------------------------------------------
GrB_Info GB (_AaddB__band_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 is_eWiseUnion,
const GB_void *alpha_scalar_in,
const GB_void *beta_scalar_in,
const bool Ch_is_Mh,
const int64_t *restrict C_to_M,
const int64_t *restrict C_to_A,
const int64_t *restrict C_to_B,
const GB_task_struct *restrict TaskList,
const int C_ntasks,
const int C_nthreads,
GB_Context Context
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
GB_WERK_DECLARE (M_ek_slicing, int64_t) ;
GB_WERK_DECLARE (A_ek_slicing, int64_t) ;
GB_WERK_DECLARE (B_ek_slicing, int64_t) ;
uint64_t alpha_scalar ;
uint64_t beta_scalar ;
if (is_eWiseUnion)
{
alpha_scalar = (*((uint64_t *) alpha_scalar_in)) ;
beta_scalar = (*((uint64_t *) beta_scalar_in )) ;
}
#include "GB_add_template.c"
GB_FREE_WORKSPACE ;
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// eWiseMult: C=A.*B, C<M>=A.*B, or C<M!>=A.*B where C is sparse/hyper
//------------------------------------------------------------------------------
GrB_Info GB (_AemultB_08__band_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_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__band_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_04__band_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_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__band_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__band_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__band_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__band_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__band_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
|
GB_extractTuples.c | //------------------------------------------------------------------------------
// GB_extractTuples: extract all the tuples from a matrix
//------------------------------------------------------------------------------
// SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2021, All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
//------------------------------------------------------------------------------
// Extracts all tuples from a matrix, like [I,J,X] = find (A). If any
// parameter I, J and/or X is NULL, then that component is not extracted. The
// size of the I, J, and X arrays (those that are not NULL) is given by nvals,
// which must be at least as large as GrB_nvals (&nvals, A). The values in the
// matrix are typecasted to the type of X, as needed.
// This function does the work for the user-callable GrB_*_extractTuples
// functions, and helps build the tuples for GB_concat_hyper.
// Tf A is iso and X is not NULL, the iso scalar Ax [0] is expanded into X.
#include "GB.h"
#define GB_FREE_ALL \
{ \
GB_FREE_WERK (&Ap, Ap_size) ; \
GB_FREE_WERK (&X_bitmap, X_bitmap_size) ; \
}
GrB_Info GB_extractTuples // extract all tuples from a matrix
(
GrB_Index *I_out, // array for returning row indices of tuples
GrB_Index *J_out, // array for returning col indices of tuples
void *X, // array for returning values of tuples
GrB_Index *p_nvals, // I,J,X size on input; # tuples on output
const GB_Type_code xcode, // type of array X
const GrB_Matrix A, // matrix to extract tuples from
GB_Context Context
)
{
//--------------------------------------------------------------------------
// check inputs
//--------------------------------------------------------------------------
GrB_Info info ;
GB_void *restrict X_bitmap = NULL ; size_t X_bitmap_size = 0 ;
int64_t *restrict Ap = NULL ; size_t Ap_size = 0 ;
ASSERT_MATRIX_OK (A, "A to extract", GB0) ;
ASSERT (p_nvals != NULL) ;
// delete any lingering zombies and assemble any pending tuples;
// allow A to remain jumbled
GB_MATRIX_WAIT_IF_PENDING_OR_ZOMBIES (A) ;
GB_BURBLE_DENSE (A, "(A %s) ") ;
ASSERT (xcode <= GB_UDT_code) ;
const GB_Type_code acode = A->type->code ;
const size_t asize = A->type->size ;
// xcode and A must be compatible
if (!GB_code_compatible (xcode, acode))
{
return (GrB_DOMAIN_MISMATCH) ;
}
const int64_t anz = GB_nnz (A) ;
if (anz == 0)
{
// no work to do
(*p_nvals) = 0 ;
return (GrB_SUCCESS) ;
}
int64_t nvals = *p_nvals ; // size of I,J,X on input
if (nvals < anz && (I_out != NULL || J_out != NULL || X != NULL))
{
// output arrays are not big enough
return (GrB_INSUFFICIENT_SPACE) ;
}
//-------------------------------------------------------------------------
// determine the number of threads to use
//-------------------------------------------------------------------------
GB_GET_NTHREADS_MAX (nthreads_max, chunk, Context) ;
int nthreads = GB_nthreads (anz + A->nvec, chunk, nthreads_max) ;
//-------------------------------------------------------------------------
// handle the CSR/CSC format
//--------------------------------------------------------------------------
GrB_Index *I, *J ;
if (A->is_csc)
{
I = I_out ;
J = J_out ;
}
else
{
I = J_out ;
J = I_out ;
}
//--------------------------------------------------------------------------
// bitmap case
//--------------------------------------------------------------------------
if (GB_IS_BITMAP (A))
{
//----------------------------------------------------------------------
// allocate workspace
//----------------------------------------------------------------------
bool need_typecast = (X != NULL) && (xcode != acode) ;
if (need_typecast)
{
// X must be typecasted
int64_t anzmax = GB_IMAX (anz, 1) ;
X_bitmap = GB_MALLOC_WERK (anzmax*asize, GB_void, &X_bitmap_size) ;
}
Ap = GB_MALLOC_WERK (A->vdim+1, int64_t, &Ap_size) ;
if (Ap == NULL || (need_typecast && X_bitmap == NULL))
{
// out of memory
GB_FREE_ALL ;
return (GrB_OUT_OF_MEMORY) ;
}
//----------------------------------------------------------------------
// extract the tuples
//----------------------------------------------------------------------
// TODO: pass xcode to GB_convert_bitmap_worker and let it do the
// typecasting. This works for now, however.
// if A is iso, GB_convert_bitmap_worker expands the iso scalar
// into its result, X or X_bitmap
GB_OK (GB_convert_bitmap_worker (Ap, (int64_t *) I, (int64_t *) J,
(GB_void *) (need_typecast ? X_bitmap : X), NULL, A, Context)) ;
//----------------------------------------------------------------------
// typecast X if needed
//----------------------------------------------------------------------
if (need_typecast)
{
// typecast the values from X_bitmap into X
ASSERT (X != NULL) ;
ASSERT (xcode != acode) ;
GB_cast_array ((GB_void *) X, xcode, X_bitmap, acode, NULL, anz,
nthreads) ;
}
}
else
{
//----------------------------------------------------------------------
// sparse, hypersparse, or full case
//----------------------------------------------------------------------
//----------------------------------------------------------------------
// extract the row indices
//----------------------------------------------------------------------
if (I != NULL)
{
if (A->i == NULL)
{
// A is full; construct the row indices
int64_t avlen = A->vlen ;
int64_t p ;
#pragma omp parallel for num_threads(nthreads) schedule(static)
for (p = 0 ; p < anz ; p++)
{
I [p] = (p % avlen) ;
}
}
else
{
GB_memcpy (I, A->i, anz * sizeof (int64_t), nthreads) ;
}
}
//----------------------------------------------------------------------
// extract the column indices
//----------------------------------------------------------------------
if (J != NULL)
{
GB_OK (GB_extract_vector_list ((int64_t *) J, A, Context)) ;
}
//----------------------------------------------------------------------
// extract the values
//----------------------------------------------------------------------
if (X != NULL)
{
if (A->iso)
{
// typecast the scalar and expand it into X
size_t xsize = GB_code_size (xcode, asize) ;
GB_void scalar [GB_VLA(xsize)] ;
GB_cast_scalar (scalar, xcode, A->x, acode, asize) ;
GB_iso_expand (X, anz, scalar, xsize, Context) ;
}
else if (xcode == acode)
{
// copy the values from A into X, no typecast
GB_memcpy (X, A->x, anz * asize, nthreads) ;
}
else
{
// typecast the values from A into X
ASSERT (X != NULL) ;
GB_cast_array ((GB_void *) X, xcode, (GB_void *) A->x, acode,
NULL, anz, nthreads) ;
}
}
}
//--------------------------------------------------------------------------
// free workspace and return result
//--------------------------------------------------------------------------
*p_nvals = anz ; // number of tuples extracted
GB_FREE_ALL ;
return (GrB_SUCCESS) ;
}
|
softmax.h | // Copyright 2018 Xiaomi, Inc. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#ifndef MACE_KERNELS_SOFTMAX_H_
#define MACE_KERNELS_SOFTMAX_H_
#include <algorithm>
#include <functional>
#include <memory>
#include <vector>
#include <limits>
#include "mace/core/future.h"
#include "mace/core/tensor.h"
#include "mace/public/mace.h"
#include "mace/utils/utils.h"
#ifdef MACE_ENABLE_OPENCL
#include "mace/core/runtime/opencl/cl2_header.h"
#endif // MACE_ENABLE_OPENCL
namespace mace {
namespace kernels {
template<DeviceType D, typename T>
struct SoftmaxFunctor;
template<>
struct SoftmaxFunctor<DeviceType::CPU, float> {
MaceStatus operator()(const Tensor *input,
Tensor *output,
StatsFuture *future) {
MACE_UNUSED(future);
Tensor::MappingGuard input_guard(input);
Tensor::MappingGuard output_guard(output);
const float *input_data = input->data<float>();
float *output_data = output->mutable_data<float>();
// softmax for nchw image
if (input->dim_size() == 4) {
const index_t batch = input->dim(0);
const index_t class_count = input->dim(1);
const index_t class_size = input->dim(2) * input->dim(3);
const index_t batch_size = class_count * class_size;
for (index_t b = 0; b < batch; ++b) {
#pragma omp parallel for
for (index_t k = 0; k < class_size; ++k) {
const float *input_ptr = input_data + b * batch_size + k;
float *output_ptr = output_data + b * batch_size + k;
float max_val = std::numeric_limits<float>::lowest();
index_t channel_offset = 0;
for (index_t c = 0; c < class_count; ++c) {
float data = input_ptr[channel_offset];
if (data > max_val) {
max_val = data;
}
channel_offset += class_size;
}
channel_offset = 0;
float sum = 0;
for (index_t c = 0; c < class_count; ++c) {
float exp_value = ::exp(input_ptr[channel_offset] - max_val);
sum += exp_value;
output_ptr[channel_offset] = exp_value;
channel_offset += class_size;
}
sum = std::max(sum, std::numeric_limits<float>::min());
channel_offset = 0;
for (index_t c = 0; c < class_count; ++c) {
output_ptr[channel_offset] /= sum;
channel_offset += class_size;
}
} // k
} // b
} else if (input->dim_size() == 2) { // normal 2d softmax
const index_t class_size = input->dim(0);
const index_t class_count = input->dim(1);
#pragma omp parallel for
for (index_t k = 0; k < class_size; ++k) {
const float *input_ptr = input_data + k * class_count;
float *output_ptr = output_data + k * class_count;
float max_val = std::numeric_limits<float>::lowest();
for (index_t c = 0; c < class_count; ++c) {
max_val = std::max(max_val, input_ptr[c]);
}
float sum = 0;
for (index_t c = 0; c < class_count; ++c) {
float exp_value = ::exp(input_ptr[c] - max_val);
sum += exp_value;
output_ptr[c] = exp_value;
}
sum = std::max(sum, std::numeric_limits<float>::min());
for (index_t c = 0; c < class_count; ++c) {
output_ptr[c] /= sum;
}
}
} else {
MACE_NOT_IMPLEMENTED;
}
return MACE_SUCCESS;
}
};
#ifdef MACE_ENABLE_OPENCL
template<typename T>
struct SoftmaxFunctor<DeviceType::GPU, T> {
MaceStatus operator()(const Tensor *logits,
Tensor *output,
StatsFuture *future);
cl::Kernel kernel_;
uint32_t kwg_size_;
std::unique_ptr<BufferBase> kernel_error_;
std::vector<index_t> input_shape_;
};
#endif // MACE_ENABLE_OPENCL
} // namespace kernels
} // namespace mace
#endif // MACE_KERNELS_SOFTMAX_H_
|
lis_precon_iluk.c | /* Copyright (C) 2002-2012 The SSI Project. 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 project 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 SCALABLE SOFTWARE INFRASTRUCTURE PROJECT
``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 SCALABLE SOFTWARE INFRASTRUCTURE
PROJECT BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
/*
* This subroutine is made based on ITSOL.
*
* http://www-users.cs.umn.edu/~saad/software/ITSOL/
*
*/
#ifdef HAVE_CONFIG_H
#include "lis_config.h"
#else
#ifdef HAVE_CONFIG_WIN32_H
#include "lis_config_win32.h"
#endif
#endif
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <memory.h>
#ifdef _OPENMP
#include <omp.h>
#endif
#ifdef USE_MPI
#include <mpi.h>
#endif
#include "lislib.h"
LIS_INT lis_symbolic_fact_crs(LIS_SOLVER solver, LIS_PRECON precon);
LIS_INT lis_numerical_fact_crs(LIS_SOLVER solver, LIS_PRECON precon);
LIS_INT lis_symbolic_fact_bsr(LIS_SOLVER solver, LIS_PRECON precon);
LIS_INT lis_numerical_fact_bsr(LIS_SOLVER solver, LIS_PRECON precon);
LIS_INT lis_symbolic_fact_vbr(LIS_SOLVER solver, LIS_PRECON precon);
LIS_INT lis_numerical_fact_vbr(LIS_SOLVER solver, LIS_PRECON precon);
#undef __FUNC__
#define __FUNC__ "lis_precon_create_iluk"
LIS_INT lis_precon_create_iluk(LIS_SOLVER solver, LIS_PRECON precon)
{
LIS_INT storage,block,err;
LIS_MATRIX A,B;
LIS_DEBUG_FUNC_IN;
storage = solver->options[LIS_OPTIONS_STORAGE];
block = solver->options[LIS_OPTIONS_STORAGE_BLOCK];
if( storage==LIS_MATRIX_BSR || storage==LIS_MATRIX_VBR )
{
if( solver->A->matrix_type!=storage )
{
err = lis_matrix_convert_self(solver);
if( err ) return err;
}
}
switch( solver->A->matrix_type )
{
case LIS_MATRIX_CRS:
err = lis_symbolic_fact_crs(solver,precon);
if( err ) return err;
err = lis_numerical_fact_crs(solver,precon);
if( err ) return err;
lis_psolve_xxx[LIS_PRECON_TYPE_ILU] = lis_psolve_iluk_crs;
lis_psolvet_xxx[LIS_PRECON_TYPE_ILU] = lis_psolvet_iluk_crs;
precon->is_copy = LIS_TRUE;
break;
case LIS_MATRIX_BSR:
err = lis_symbolic_fact_bsr(solver,precon);
if( err ) return err;
err = lis_numerical_fact_bsr(solver,precon);
if( err ) return err;
lis_psolve_xxx[LIS_PRECON_TYPE_ILU] = lis_psolve_iluk_bsr;
lis_psolvet_xxx[LIS_PRECON_TYPE_ILU] = lis_psolvet_iluk_bsr;
break;
case LIS_MATRIX_VBR:
err = lis_symbolic_fact_vbr(solver,precon);
if( err ) return err;
err = lis_numerical_fact_vbr(solver,precon);
if( err ) return err;
lis_psolve_xxx[LIS_PRECON_TYPE_ILU] = lis_psolve_iluk_vbr;
/* lis_psolvet_xxx[LIS_PRECON_TYPE_ILU] = lis_psolvet_iluk_vbr;*/
break;
default:
A = solver->A;
err = lis_matrix_duplicate(A,&B);
if( err ) return err;
lis_matrix_set_type(B,LIS_MATRIX_CRS);
err = lis_matrix_convert(A,B);
if( err ) return err;
solver->A = B;
err = lis_symbolic_fact_crs(solver,precon);
if( err ) return err;
err = lis_numerical_fact_crs(solver,precon);
if( err ) return err;
lis_psolve_xxx[LIS_PRECON_TYPE_ILU] = lis_psolve_iluk_crs;
lis_psolvet_xxx[LIS_PRECON_TYPE_ILU] = lis_psolvet_iluk_crs;
lis_matrix_destroy(B);
solver->A = A;
precon->is_copy = LIS_TRUE;
break;
}
LIS_DEBUG_FUNC_OUT;
return LIS_SUCCESS;
}
#undef __FUNC__
#define __FUNC__ "lis_symbolic_fact_crs"
LIS_INT lis_symbolic_fact_crs(LIS_SOLVER solver, LIS_PRECON precon)
{
#ifdef _OPENMP
LIS_INT err;
LIS_INT i,j,k;
LIS_INT n,levfill;
LIS_INT col,ip,it,jpiv,incl,incu,jmin,kmin;
LIS_INT *levls,*jbuf,*iw,**ulvl;
LIS_INT is,ie,my_rank,nprocs;
LIS_MATRIX A;
LIS_MATRIX_ILU L,U;
LIS_VECTOR D;
LIS_DEBUG_FUNC_IN;
A = solver->A;
n = A->n;
levfill = solver->options[LIS_OPTIONS_FILL];
nprocs = omp_get_max_threads();
L = NULL;
U = NULL;
err = lis_matrix_ilu_create(n,1,&L);
if( err ) return err;
err = lis_matrix_ilu_create(n,1,&U);
if( err ) return err;
err = lis_matrix_ilu_setCR(L);
if( err ) return err;
err = lis_matrix_ilu_setCR(U);
if( err ) return err;
err = lis_vector_duplicate(A,&D);
if( err )
{
return err;
}
ulvl = (LIS_INT **)lis_malloc(n*sizeof(LIS_INT *),"lis_symbolic_fact_crs::ulvl");
if( ulvl==NULL )
{
LIS_SETERR_MEM(n*sizeof(LIS_INT));
return LIS_OUT_OF_MEMORY;
}
levls = (LIS_INT *)lis_malloc(nprocs*n*sizeof(LIS_INT),"lis_symbolic_fact_crs::levls");
if( levls==NULL )
{
LIS_SETERR_MEM(n*sizeof(LIS_INT));
return LIS_OUT_OF_MEMORY;
}
jbuf = (LIS_INT *)lis_malloc(nprocs*n*sizeof(LIS_INT),"lis_symbolic_fact_crs::jbuf");
if( jbuf==NULL )
{
LIS_SETERR_MEM(n*sizeof(LIS_INT));
return LIS_OUT_OF_MEMORY;
}
iw = (LIS_INT *)lis_malloc(n*sizeof(LIS_INT),"lis_symbolic_fact_crs::iw");
if( iw==NULL )
{
LIS_SETERR_MEM(n*sizeof(LIS_INT));
return LIS_OUT_OF_MEMORY;
}
#pragma omp parallel private(i,j,k,is,ie,my_rank,incl,incu,col,jpiv,it,ip,kmin,jmin)
{
my_rank = omp_get_thread_num();
LIS_GET_ISIE(my_rank,nprocs,n,is,ie);
for(i=is;i<ie;i++) iw[i]=-1;
for(i=is;i<ie;i++)
{
incl = 0;
incu = i;
for(j=A->ptr[i];j<A->ptr[i+1];j++)
{
col = A->index[j];
#ifdef USE_MPI
if( col>=n ) continue;
#endif
if( col>=is && col<ie )
{
if( col < i )
{
jbuf[my_rank*n+incl] = col;
levls[my_rank*n+incl] = 0;
iw[col] = incl++;
}
else if( col > i )
{
jbuf[my_rank*n+incu] = col;
levls[my_rank*n+incu] = 0;
iw[col] = incu++;
}
}
}
jpiv = -1;
while( ++jpiv < incl )
{
k = jbuf[my_rank*n+jpiv];
kmin = k;
jmin = jpiv;
for(j=jpiv+1;j<incl;j++)
{
if( jbuf[my_rank*n+j]<kmin )
{
kmin = jbuf[my_rank*n+j];
jmin = j;
}
}
if( jmin!=jpiv )
{
jbuf[my_rank*n+jpiv] = kmin;
jbuf[my_rank*n+jmin] = k;
iw[kmin] = jpiv;
iw[k] = jmin;
j = levls[my_rank*n+jpiv];
levls[my_rank*n+jpiv] = levls[my_rank*n+jmin];
levls[my_rank*n+jmin] = j;
k = kmin;
}
for(j=0;j<U->nnz[k];j++)
{
col = U->index[k][j];
it = ulvl[k][j] + levls[my_rank*n+jpiv]+1;
if( it > levfill ) continue;
ip = iw[col];
if( ip==-1 )
{
if( col < i )
{
jbuf[my_rank*n+incl] = col;
levls[my_rank*n+incl] = it;
iw[col] = incl++;
}
else if( col > i )
{
jbuf[my_rank*n+incu] = col;
levls[my_rank*n+incu] = it;
iw[col] = incu++;
}
}
else
{
levls[my_rank*n+ip] = _min(levls[my_rank*n+ip],it);
}
}
}
for(j=0;j<incl;j++) iw[jbuf[my_rank*n+j]] = -1;
for(j=i;j<incu;j++) iw[jbuf[my_rank*n+j]] = -1;
L->nnz[i] = incl;
if( incl > 0 )
{
L->index[i] = (LIS_INT *)malloc(incl*sizeof(LIS_INT));
L->value[i] = (LIS_SCALAR *)malloc(incl*sizeof(LIS_SCALAR));
memcpy(L->index[i],&jbuf[my_rank*n],incl*sizeof(LIS_INT));
}
k = incu-i;
U->nnz[i] = k;
if( k > 0 )
{
U->index[i] = (LIS_INT *)malloc(k*sizeof(LIS_INT));
U->value[i] = (LIS_SCALAR *)malloc(k*sizeof(LIS_SCALAR));
ulvl[i] = (LIS_INT *)malloc(k*sizeof(LIS_INT));
memcpy(U->index[i],&jbuf[my_rank*n+i],k*sizeof(LIS_INT));
memcpy(ulvl[i],&levls[my_rank*n+i],k*sizeof(LIS_INT));
}
}
}
precon->L = L;
precon->U = U;
precon->D = D;
lis_free2(3,levls,jbuf,iw);
for(i=0;i<n-1;i++)
{
if(U->nnz[i]) free(ulvl[i]);
}
lis_free(ulvl);
LIS_DEBUG_FUNC_OUT;
return LIS_SUCCESS;
#else
LIS_INT err;
LIS_INT i,j,k;
LIS_INT n,levfill;
LIS_INT col,ip,it,jpiv,incl,incu,jmin,kmin;
LIS_INT *levls,*jbuf,*iw,**ulvl;
LIS_MATRIX A;
LIS_MATRIX_ILU L,U;
LIS_VECTOR D;
LIS_DEBUG_FUNC_IN;
A = solver->A;
n = A->n;
levfill = solver->options[LIS_OPTIONS_FILL];
L = NULL;
U = NULL;
D = NULL;
err = lis_matrix_ilu_create(n,1,&L);
if( err ) return err;
err = lis_matrix_ilu_create(n,1,&U);
if( err ) return err;
err = lis_matrix_ilu_setCR(L);
if( err ) return err;
err = lis_matrix_ilu_setCR(U);
if( err ) return err;
err = lis_vector_duplicate(A,&D);
if( err )
{
return err;
}
ulvl = (LIS_INT **)lis_malloc(n*sizeof(LIS_INT *),"lis_symbolic_fact_crs::ulvl");
if( ulvl==NULL )
{
LIS_SETERR_MEM(n*sizeof(LIS_INT));
return LIS_OUT_OF_MEMORY;
}
levls = (LIS_INT *)lis_malloc(n*sizeof(LIS_INT),"lis_symbolic_fact_crs::levls");
if( levls==NULL )
{
LIS_SETERR_MEM(n*sizeof(LIS_INT));
return LIS_OUT_OF_MEMORY;
}
jbuf = (LIS_INT *)lis_malloc(n*sizeof(LIS_INT),"lis_symbolic_fact_crs::jbuf");
if( jbuf==NULL )
{
LIS_SETERR_MEM(n*sizeof(LIS_INT));
return LIS_OUT_OF_MEMORY;
}
iw = (LIS_INT *)lis_malloc(n*sizeof(LIS_INT),"lis_symbolic_fact_crs::iw");
if( iw==NULL )
{
LIS_SETERR_MEM(n*sizeof(LIS_INT));
return LIS_OUT_OF_MEMORY;
}
for(i=0;i<n;i++) iw[i]=-1;
for(i=0;i<n;i++)
{
incl = 0;
incu = i;
for(j=A->ptr[i];j<A->ptr[i+1];j++)
{
col = A->index[j];
#ifdef USE_MPI
if( col>=n ) continue;
#endif
if( col < i )
{
jbuf[incl] = col;
levls[incl] = 0;
iw[col] = incl++;
}
else if( col > i )
{
jbuf[incu] = col;
levls[incu] = 0;
iw[col] = incu++;
}
}
jpiv = -1;
while( ++jpiv < incl )
{
k = jbuf[jpiv];
kmin = k;
jmin = jpiv;
for(j=jpiv+1;j<incl;j++)
{
if( jbuf[j]<kmin )
{
kmin = jbuf[j];
jmin = j;
}
}
if( jmin!=jpiv )
{
jbuf[jpiv] = kmin;
jbuf[jmin] = k;
iw[kmin] = jpiv;
iw[k] = jmin;
j = levls[jpiv];
levls[jpiv] = levls[jmin];
levls[jmin] = j;
k = kmin;
}
for(j=0;j<U->nnz[k];j++)
{
col = U->index[k][j];
it = ulvl[k][j] + levls[jpiv]+1;
if( it > levfill ) continue;
ip = iw[col];
if( ip==-1 )
{
if( col < i )
{
jbuf[incl] = col;
levls[incl] = it;
iw[col] = incl++;
}
else if( col > i )
{
jbuf[incu] = col;
levls[incu] = it;
iw[col] = incu++;
}
}
else
{
levls[ip] = _min(levls[ip],it);
}
}
}
for(j=0;j<incl;j++) iw[jbuf[j]] = -1;
for(j=i;j<incu;j++) iw[jbuf[j]] = -1;
L->nnz[i] = incl;
if( incl > 0 )
{
L->index[i] = (LIS_INT *)malloc(incl*sizeof(LIS_INT));
L->value[i] = (LIS_SCALAR *)malloc(incl*sizeof(LIS_SCALAR));
memcpy(L->index[i],jbuf,incl*sizeof(LIS_INT));
}
k = incu-i;
U->nnz[i] = k;
if( k > 0 )
{
U->index[i] = (LIS_INT *)malloc(k*sizeof(LIS_INT));
U->value[i] = (LIS_SCALAR *)malloc(k*sizeof(LIS_SCALAR));
ulvl[i] = (LIS_INT *)malloc(k*sizeof(LIS_INT));
memcpy(U->index[i],jbuf+i,k*sizeof(LIS_INT));
memcpy(ulvl[i],levls+i,k*sizeof(LIS_INT));
}
}
precon->L = L;
precon->U = U;
precon->D = D;
lis_free2(3,levls,jbuf,iw);
for(i=0;i<n-1;i++)
{
if(U->nnz[i]) free(ulvl[i]);
}
lis_free(ulvl);
LIS_DEBUG_FUNC_OUT;
return LIS_SUCCESS;
#endif
}
#undef __FUNC__
#define __FUNC__ "lis_numerical_fact_crs"
LIS_INT lis_numerical_fact_crs(LIS_SOLVER solver, LIS_PRECON precon)
{
#ifdef _OPENMP
LIS_INT err;
LIS_INT i,j,k;
LIS_INT n;
LIS_INT col,jpos,jrow;
LIS_INT *jw;
LIS_INT is,ie,my_rank,nprocs;
LIS_MATRIX A;
LIS_MATRIX_ILU L,U;
LIS_VECTOR D;
LIS_DEBUG_FUNC_IN;
A = solver->A;
n = A->n;
nprocs = omp_get_max_threads();
L = precon->L;
U = precon->U;
D = precon->D;
jw = (LIS_INT *)lis_malloc(n*sizeof(LIS_INT),"lis_numerical_fact_crs::jw");
if( jw==NULL )
{
LIS_SETERR_MEM(n*sizeof(LIS_INT));
return LIS_OUT_OF_MEMORY;
}
#pragma omp parallel private(i,j,k,is,ie,my_rank,col,jpos,jrow)
{
my_rank = omp_get_thread_num();
LIS_GET_ISIE(my_rank,nprocs,n,is,ie);
for(i=is;i<ie;i++) jw[i] = -1;
for(i=is;i<ie;i++)
{
for(j=0;j<L->nnz[i];j++)
{
col = L->index[i][j];
jw[col] = j;
L->value[i][j] = 0;
}
jw[i] = i;
D->value[i] = 0;
for(j=0;j<U->nnz[i];j++)
{
col = U->index[i][j];
jw[col] = j;
U->value[i][j] = 0;
}
for(j=A->ptr[i];j<A->ptr[i+1];j++)
{
col = A->index[j];
#ifdef USE_MPI
if( col>=n ) continue;
#endif
if( col>=is && col<ie )
{
jpos = jw[col];
if( col<i )
{
L->value[i][jpos] = A->value[j];
}
else if( col==i )
{
D->value[i] = A->value[j];
}
else
{
U->value[i][jpos] = A->value[j];
}
}
}
for(j=0;j<L->nnz[i];j++)
{
jrow = L->index[i][j];
L->value[i][j] *= D->value[jrow];
for(k=0;k<U->nnz[jrow];k++)
{
col = U->index[jrow][k];
jpos = jw[col];
if( jpos==-1 ) continue;
if( col<i )
{
L->value[i][jpos] -= L->value[i][j] * U->value[jrow][k];
}
else if( col==i )
{
D->value[i] -= L->value[i][j] * U->value[jrow][k];
}
else
{
U->value[i][jpos] -= L->value[i][j] * U->value[jrow][k];
}
}
}
for(j=0;j<L->nnz[i];j++)
{
col = L->index[i][j];
jw[col] = -1;
}
jw[i] = -1;
for(j=0;j<U->nnz[i];j++)
{
col = U->index[i][j];
jw[col] = -1;
}
D->value[i] = 1.0 / D->value[i];
}
}
lis_free(jw);
LIS_DEBUG_FUNC_OUT;
return LIS_SUCCESS;
#else
LIS_INT i,j,k;
LIS_INT n;
LIS_INT col,jpos,jrow;
LIS_INT *jw;
LIS_MATRIX A;
LIS_MATRIX_ILU L,U;
LIS_VECTOR D;
LIS_DEBUG_FUNC_IN;
A = solver->A;
n = A->n;
L = precon->L;
U = precon->U;
D = precon->D;
jw = (LIS_INT *)lis_malloc(n*sizeof(LIS_INT),"lis_numerical_fact_crs::jw");
if( jw==NULL )
{
LIS_SETERR_MEM(n*sizeof(LIS_INT));
return LIS_OUT_OF_MEMORY;
}
for(i=0;i<n;i++) jw[i] = -1;
for(i=0;i<n;i++)
{
for(j=0;j<L->nnz[i];j++)
{
col = L->index[i][j];
jw[col] = j;
L->value[i][j] = 0;
}
jw[i] = i;
D->value[i] = 0;
for(j=0;j<U->nnz[i];j++)
{
col = U->index[i][j];
jw[col] = j;
U->value[i][j] = 0;
}
for(j=A->ptr[i];j<A->ptr[i+1];j++)
{
col = A->index[j];
#ifdef USE_MPI
if( col>=n ) continue;
#endif
jpos = jw[col];
if( col<i )
{
L->value[i][jpos] = A->value[j];
}
else if( col==i )
{
D->value[i] = A->value[j];
}
else
{
U->value[i][jpos] = A->value[j];
}
}
for(j=0;j<L->nnz[i];j++)
{
jrow = L->index[i][j];
L->value[i][j] *= D->value[jrow];
for(k=0;k<U->nnz[jrow];k++)
{
col = U->index[jrow][k];
jpos = jw[col];
if( jpos==-1 ) continue;
if( col<i )
{
L->value[i][jpos] -= L->value[i][j] * U->value[jrow][k];
}
else if( col==i )
{
D->value[i] -= L->value[i][j] * U->value[jrow][k];
}
else
{
U->value[i][jpos] -= L->value[i][j] * U->value[jrow][k];
}
}
}
for(j=0;j<L->nnz[i];j++)
{
col = L->index[i][j];
jw[col] = -1;
}
jw[i] = -1;
for(j=0;j<U->nnz[i];j++)
{
col = U->index[i][j];
jw[col] = -1;
}
D->value[i] = 1.0 / D->value[i];
}
lis_free(jw);
LIS_DEBUG_FUNC_OUT;
return LIS_SUCCESS;
#endif
}
#undef __FUNC__
#define __FUNC__ "lis_psolve_iluk_crs"
LIS_INT lis_psolve_iluk_crs(LIS_SOLVER solver, LIS_VECTOR B, LIS_VECTOR X)
{
#ifdef _OPENMP
LIS_INT i,j,jj,n;
LIS_INT is,ie,my_rank,nprocs;
LIS_SCALAR *b,*x;
LIS_MATRIX_ILU L,U;
LIS_VECTOR D;
LIS_PRECON precon;
LIS_QUAD_DECLAR;
#ifdef USE_QUAD_PRECISION
LIS_SCALAR *xl;
#endif
LIS_DEBUG_FUNC_IN;
precon = solver->precon;
L = precon->L;
U = precon->U;
D = precon->D;
b = B->value;
x = X->value;
#ifdef USE_QUAD_PRECISION
xl = X->value_lo;
#endif
n = solver->A->n;
nprocs = omp_get_max_threads();
#ifdef USE_QUAD_PRECISION
if( B->precision==LIS_PRECISION_DEFAULT )
{
#endif
lis_vector_copy(B,X);
#pragma omp parallel private(i,j,jj,is,ie,my_rank)
{
my_rank = omp_get_thread_num();
LIS_GET_ISIE(my_rank,nprocs,n,is,ie);
for(i=is;i<ie;i++)
{
for(j=0;j<L->nnz[i];j++)
{
jj = L->index[i][j];
x[i] -= L->value[i][j] * x[jj];
}
}
for(i=ie-1;i>=is;i--)
{
for(j=0;j<U->nnz[i];j++)
{
jj = U->index[i][j];
x[i] -= U->value[i][j] * x[jj];
}
x[i] = D->value[i]*x[i];
}
}
#ifdef USE_QUAD_PRECISION
}
else
{
lis_vector_copyex_mm(B,X);
nprocs = omp_get_max_threads();
#ifndef USE_SSE2
#pragma omp parallel private(i,j,jj,is,ie,my_rank,p1,p2,tq,bhi,blo,chi,clo,sh,sl,th,tl,eh,el)
#else
#pragma omp parallel private(i,j,jj,is,ie,my_rank,bh,ch,sh,wh,th,bl,cl,sl,wl,tl,p1,p2,t0,t1,t2,eh)
#endif
{
my_rank = omp_get_thread_num();
LIS_GET_ISIE(my_rank,nprocs,n,is,ie);
for(i=is;i<ie;i++)
{
for(j=0;j<L->nnz[i];j++)
{
jj = L->index[i][j];
#ifndef USE_SSE2
LIS_QUAD_FMAD(x[i],xl[i],x[i],xl[i],x[jj],xl[jj],-L->value[i][j]);
#else
LIS_QUAD_FMAD_SSE2(x[i],xl[i],x[i],xl[i],x[jj],xl[jj],-L->value[i][j]);
#endif
/* x[i] -= L->value[i][j] * x[jj];*/
}
}
for(i=ie-1;i>=is;i--)
{
for(j=0;j<U->nnz[i];j++)
{
jj = U->index[i][j];
#ifndef USE_SSE2
LIS_QUAD_FMAD(x[i],xl[i],x[i],xl[i],x[jj],xl[jj],-U->value[i][j]);
#else
LIS_QUAD_FMAD_SSE2(x[i],xl[i],x[i],xl[i],x[jj],xl[jj],-U->value[i][j]);
#endif
/* x[i] -= U->value[i][j] * x[jj];*/
}
#ifndef USE_SSE2
LIS_QUAD_MULD(x[i],xl[i],x[i],xl[i],D->value[i]);
#else
LIS_QUAD_MULD_SSE2(x[i],xl[i],x[i],xl[i],D->value[i]);
#endif
/* x[i] = D->value[i]*x[i];*/
}
}
}
#endif
LIS_DEBUG_FUNC_OUT;
return LIS_SUCCESS;
#else
LIS_INT i,j,jj,n;
LIS_SCALAR *b,*x;
LIS_MATRIX_ILU L,U;
LIS_VECTOR D;
LIS_PRECON precon;
LIS_QUAD_DECLAR;
#ifdef USE_QUAD_PRECISION
LIS_SCALAR *xl;
#endif
/*
* LUx = b
* LU = (D + L*A) * (I + D^-1 * U*A)
*/
LIS_DEBUG_FUNC_IN;
precon = solver->precon;
L = precon->L;
U = precon->U;
D = precon->D;
b = B->value;
x = X->value;
#ifdef USE_QUAD_PRECISION
xl = X->value_lo;
#endif
n = solver->A->n;
#ifdef USE_QUAD_PRECISION
if( B->precision==LIS_PRECISION_DEFAULT )
{
#endif
lis_vector_copy(B,X);
for(i=0; i<n; i++)
{
for(j=0;j<L->nnz[i];j++)
{
jj = L->index[i][j];
x[i] -= L->value[i][j] * x[jj];
}
}
for(i=n-1; i>=0; i--)
{
for(j=0;j<U->nnz[i];j++)
{
jj = U->index[i][j];
x[i] -= U->value[i][j] * x[jj];
}
x[i] = D->value[i]*x[i];
}
#ifdef USE_QUAD_PRECISION
}
else
{
lis_vector_copy(B,X);
for(i=0; i<n; i++)
{
for(j=0;j<L->nnz[i];j++)
{
jj = L->index[i][j];
#ifndef USE_SSE2
LIS_QUAD_FMAD(x[i],xl[i],x[i],xl[i],x[jj],xl[jj],-L->value[i][j]);
#else
LIS_QUAD_FMAD_SSE2(x[i],xl[i],x[i],xl[i],x[jj],xl[jj],-L->value[i][j]);
#endif
/* x[i] -= L->value[i][j] * x[jj];*/
}
}
for(i=n-1; i>=0; i--)
{
for(j=0;j<U->nnz[i];j++)
{
jj = U->index[i][j];
#ifndef USE_SSE2
LIS_QUAD_FMAD(x[i],xl[i],x[i],xl[i],x[jj],xl[jj],-U->value[i][j]);
#else
LIS_QUAD_FMAD_SSE2(x[i],xl[i],x[i],xl[i],x[jj],xl[jj],-U->value[i][j]);
#endif
/* x[i] -= U->value[i][j] * x[jj];*/
}
#ifndef USE_SSE2
LIS_QUAD_MULD(x[i],xl[i],x[i],xl[i],D->value[i]);
#else
LIS_QUAD_MULD_SSE2(x[i],xl[i],x[i],xl[i],D->value[i]);
#endif
/* x[i] = D->value[i]*x[i];*/
}
}
#endif
LIS_DEBUG_FUNC_OUT;
return LIS_SUCCESS;
#endif
}
#undef __FUNC__
#define __FUNC__ "lis_psolvet_iluk_crs"
LIS_INT lis_psolvet_iluk_crs(LIS_SOLVER solver, LIS_VECTOR B, LIS_VECTOR X)
{
#ifdef _OPENMP
LIS_INT i,j,jj,n;
LIS_INT is,ie,my_rank,nprocs;
LIS_SCALAR *b,*x;
LIS_MATRIX_ILU L,U;
LIS_VECTOR D;
LIS_PRECON precon;
LIS_QUAD_DECLAR;
#ifdef USE_QUAD_PRECISION
LIS_SCALAR *xl;
#endif
LIS_DEBUG_FUNC_IN;
precon = solver->precon;
L = precon->L;
U = precon->U;
D = precon->D;
b = B->value;
x = X->value;
#ifdef USE_QUAD_PRECISION
xl = X->value_lo;
#endif
n = solver->A->n;
nprocs = omp_get_max_threads();
#ifdef USE_QUAD_PRECISION
if( B->precision==LIS_PRECISION_DEFAULT )
{
#endif
lis_vector_copy(B,X);
#pragma omp parallel private(i,j,jj,is,ie,my_rank)
{
my_rank = omp_get_thread_num();
LIS_GET_ISIE(my_rank,nprocs,n,is,ie);
for(i=is;i<ie;i++)
{
x[i] = D->value[i]*x[i];
for(j=0;j<U->nnz[i];j++)
{
jj = U->index[i][j];
x[jj] -= U->value[i][j] * x[i];
}
}
for(i=ie-1;i>=is;i--)
{
for(j=0;j<L->nnz[i];j++)
{
jj = L->index[i][j];
x[jj] -= L->value[i][j] * x[i];
}
}
}
#ifdef USE_QUAD_PRECISION
}
else
{
lis_vector_copyex_mm(B,X);
nprocs = omp_get_max_threads();
#ifndef USE_SSE2
#pragma omp parallel private(i,j,jj,is,ie,my_rank,p1,p2,tq,bhi,blo,chi,clo,sh,sl,th,tl,eh,el)
#else
#pragma omp parallel private(i,j,jj,is,ie,my_rank,bh,ch,sh,wh,th,bl,cl,sl,wl,tl,p1,p2,t0,t1,t2,eh)
#endif
{
my_rank = omp_get_thread_num();
LIS_GET_ISIE(my_rank,nprocs,n,is,ie);
for(i=is;i<ie;i++)
{
#ifndef USE_SSE2
LIS_QUAD_MULD(x[i],xl[i],x[i],xl[i],D->value[i]);
#else
LIS_QUAD_MULD_SSE2(x[i],xl[i],x[i],xl[i],D->value[i]);
#endif
/* x[i] = D->value[i]*x[i];*/
for(j=0;j<U->nnz[i];j++)
{
jj = U->index[i][j];
#ifndef USE_SSE2
LIS_QUAD_FMAD(x[jj],xl[jj],x[jj],xl[jj],x[i],xl[i],-U->value[i][j]);
#else
LIS_QUAD_FMAD_SSE2(x[jj],xl[jj],x[jj],xl[jj],x[i],xl[i],-U->value[i][j]);
#endif
/* x[jj] -= U->value[i][j] * x[i];*/
}
}
for(i=ie-1;i>=is;i--)
{
for(j=0;j<L->nnz[i];j++)
{
jj = L->index[i][j];
#ifndef USE_SSE2
LIS_QUAD_FMAD(x[jj],xl[jj],x[jj],xl[jj],x[i],xl[i],-L->value[i][j]);
#else
LIS_QUAD_FMAD_SSE2(x[jj],xl[jj],x[jj],xl[jj],x[i],xl[i],-L->value[i][j]);
#endif
/* x[jj] -= L->value[i][j] * x[i];*/
}
}
}
}
#endif
LIS_DEBUG_FUNC_OUT;
return LIS_SUCCESS;
#else
LIS_INT i,j,jj,n;
LIS_SCALAR *b,*x;
LIS_MATRIX_ILU L,U;
LIS_VECTOR D;
LIS_PRECON precon;
LIS_QUAD_DECLAR;
#ifdef USE_QUAD_PRECISION
LIS_SCALAR *xl;
#endif
LIS_DEBUG_FUNC_IN;
precon = solver->precon;
L = precon->L;
U = precon->U;
D = precon->D;
b = B->value;
x = X->value;
#ifdef USE_QUAD_PRECISION
xl = X->value_lo;
#endif
n = solver->A->n;
#ifdef USE_QUAD_PRECISION
if( B->precision==LIS_PRECISION_DEFAULT )
{
#endif
lis_vector_copy(B,X);
for(i=0; i<n; i++)
{
x[i] = D->value[i]*x[i];
for(j=0;j<U->nnz[i];j++)
{
jj = U->index[i][j];
x[jj] -= U->value[i][j] * x[i];
}
}
for(i=n-1; i>=0; i--)
{
for(j=0;j<L->nnz[i];j++)
{
jj = L->index[i][j];
x[jj] -= L->value[i][j] * x[i];
}
}
#ifdef USE_QUAD_PRECISION
}
else
{
lis_vector_copy(B,X);
for(i=0; i<n; i++)
{
#ifndef USE_SSE2
LIS_QUAD_MULD(x[i],xl[i],x[i],xl[i],D->value[i]);
#else
LIS_QUAD_MULD_SSE2(x[i],xl[i],x[i],xl[i],D->value[i]);
#endif
/* x[i] = D->value[i]*x[i];*/
for(j=0;j<U->nnz[i];j++)
{
jj = U->index[i][j];
#ifndef USE_SSE2
LIS_QUAD_FMAD(x[jj],xl[jj],x[jj],xl[jj],x[i],xl[i],-U->value[i][j]);
#else
LIS_QUAD_FMAD_SSE2(x[jj],xl[jj],x[jj],xl[jj],x[i],xl[i],-U->value[i][j]);
#endif
/* x[jj] -= U->value[i][j] * x[i];*/
}
}
for(i=n-1; i>=0; i--)
{
for(j=0;j<L->nnz[i];j++)
{
jj = L->index[i][j];
#ifndef USE_SSE2
LIS_QUAD_FMAD(x[jj],xl[jj],x[jj],xl[jj],x[i],xl[i],-L->value[i][j]);
#else
LIS_QUAD_FMAD_SSE2(x[jj],xl[jj],x[jj],xl[jj],x[i],xl[i],-L->value[i][j]);
#endif
/* x[jj] -= L->value[i][j] * x[i];*/
}
}
}
#endif
LIS_DEBUG_FUNC_OUT;
return LIS_SUCCESS;
#endif
}
#undef __FUNC__
#define __FUNC__ "lis_symbolic_fact_bsr"
LIS_INT lis_symbolic_fact_bsr(LIS_SOLVER solver, LIS_PRECON precon)
{
#ifdef _OPENMP
LIS_INT err;
LIS_INT i,j,k,bnr,bs;
LIS_INT n,nr,levfill;
LIS_INT col,ip,it,jpiv,incl,incu,jmin,kmin;
LIS_INT *levls,*jbuf,*iw,**ulvl;
LIS_INT is,ie,my_rank,nprocs;
LIS_MATRIX A;
LIS_MATRIX_ILU L,U;
LIS_MATRIX_DIAG D;
LIS_DEBUG_FUNC_IN;
A = solver->A;
n = A->n;
nr = A->nr;
bnr = A->bnr;
bs = bnr*bnr;
levfill = solver->options[LIS_OPTIONS_FILL];
nprocs = omp_get_max_threads();
L = NULL;
U = NULL;
err = lis_matrix_ilu_create(nr,bnr,&L);
if( err ) return err;
err = lis_matrix_ilu_create(nr,bnr,&U);
if( err ) return err;
err = lis_matrix_ilu_setCR(L);
if( err ) return err;
err = lis_matrix_ilu_setCR(U);
if( err ) return err;
err = lis_matrix_diag_duplicateM(A,&D);
if( err )
{
return err;
}
ulvl = (LIS_INT **)lis_malloc(nr*sizeof(LIS_INT *),"lis_symbolic_fact_bsr::ulvl");
if( ulvl==NULL )
{
LIS_SETERR_MEM(n*sizeof(LIS_INT));
return LIS_OUT_OF_MEMORY;
}
levls = (LIS_INT *)lis_malloc(nprocs*nr*sizeof(LIS_INT),"lis_symbolic_fact_bsr::levls");
if( levls==NULL )
{
LIS_SETERR_MEM(n*sizeof(LIS_INT));
return LIS_OUT_OF_MEMORY;
}
jbuf = (LIS_INT *)lis_malloc(nprocs*nr*sizeof(LIS_INT),"lis_symbolic_fact_bsr::jbuf");
if( jbuf==NULL )
{
LIS_SETERR_MEM(n*sizeof(LIS_INT));
return LIS_OUT_OF_MEMORY;
}
iw = (LIS_INT *)lis_malloc(nr*sizeof(LIS_INT),"lis_symbolic_fact_bsr::iw");
if( iw==NULL )
{
LIS_SETERR_MEM(n*sizeof(LIS_INT));
return LIS_OUT_OF_MEMORY;
}
#pragma omp parallel private(i,j,k,is,ie,my_rank,incl,incu,col,jpiv,it,ip,kmin,jmin)
{
my_rank = omp_get_thread_num();
LIS_GET_ISIE(my_rank,nprocs,nr,is,ie);
for(i=is;i<ie;i++) iw[i]=-1;
for(i=is;i<ie;i++)
{
incl = 0;
incu = i;
for(j=A->bptr[i];j<A->bptr[i+1];j++)
{
col = A->bindex[j];
#ifdef USE_MPI
if( col>=nr ) continue;
#endif
if( col>=is && col<ie )
{
if( col < i )
{
jbuf[my_rank*nr+incl] = col;
levls[my_rank*nr+incl] = 0;
iw[col] = incl++;
}
else if( col > i )
{
jbuf[my_rank*nr+incu] = col;
levls[my_rank*nr+incu] = 0;
iw[col] = incu++;
}
}
}
jpiv = -1;
while( ++jpiv < incl )
{
k = jbuf[my_rank*nr+jpiv];
kmin = k;
jmin = jpiv;
for(j=jpiv+1;j<incl;j++)
{
if( jbuf[my_rank*nr+j]<kmin )
{
kmin = jbuf[my_rank*nr+j];
jmin = j;
}
}
if( jmin!=jpiv )
{
jbuf[my_rank*nr+jpiv] = kmin;
jbuf[my_rank*nr+jmin] = k;
iw[kmin] = jpiv;
iw[k] = jmin;
j = levls[my_rank*nr+jpiv];
levls[my_rank*nr+jpiv] = levls[my_rank*nr+jmin];
levls[my_rank*nr+jmin] = j;
k = kmin;
}
for(j=0;j<U->nnz[k];j++)
{
col = U->index[k][j];
it = ulvl[k][j] + levls[my_rank*nr+jpiv]+1;
if( it > levfill ) continue;
ip = iw[col];
if( ip==-1 )
{
if( col < i )
{
jbuf[my_rank*nr+incl] = col;
levls[my_rank*nr+incl] = it;
iw[col] = incl++;
}
else if( col > i )
{
jbuf[my_rank*nr+incu] = col;
levls[my_rank*nr+incu] = it;
iw[col] = incu++;
}
}
else
{
levls[my_rank*nr+ip] = _min(levls[my_rank*nr+ip],it);
}
}
}
for(j=0;j<incl;j++) iw[jbuf[my_rank*nr+j]] = -1;
for(j=i;j<incu;j++) iw[jbuf[my_rank*nr+j]] = -1;
L->nnz[i] = incl;
if( incl > 0 )
{
L->index[i] = (LIS_INT *)malloc(incl*sizeof(LIS_INT));
L->value[i] = (LIS_SCALAR *)malloc(bs*incl*sizeof(LIS_SCALAR));
memcpy(L->index[i],&jbuf[my_rank*nr],incl*sizeof(LIS_INT));
}
k = incu-i;
U->nnz[i] = k;
if( k > 0 )
{
U->index[i] = (LIS_INT *)malloc(k*sizeof(LIS_INT));
U->value[i] = (LIS_SCALAR *)malloc(bs*k*sizeof(LIS_SCALAR));
ulvl[i] = (LIS_INT *)malloc(k*sizeof(LIS_INT));
memcpy(U->index[i],&jbuf[my_rank*nr+i],k*sizeof(LIS_INT));
memcpy(ulvl[i],&levls[my_rank*nr+i],k*sizeof(LIS_INT));
}
}
}
precon->L = L;
precon->U = U;
precon->WD = D;
lis_free2(3,levls,jbuf,iw);
for(i=0;i<nr-1;i++)
{
if(U->nnz[i]) free(ulvl[i]);
}
lis_free(ulvl);
LIS_DEBUG_FUNC_OUT;
return LIS_SUCCESS;
#else
LIS_INT err;
LIS_INT i,j,k,bnr,bs;
LIS_INT n,nr,levfill;
LIS_INT col,ip,it,jpiv,incl,incu,jmin,kmin;
LIS_INT *levls,*jbuf,*iw,**ulvl;
LIS_MATRIX A;
LIS_MATRIX_ILU L,U;
LIS_MATRIX_DIAG D;
LIS_DEBUG_FUNC_IN;
A = solver->A;
n = A->n;
nr = A->nr;
bnr = A->bnr;
bs = bnr*bnr;
levfill = solver->options[LIS_OPTIONS_FILL];
L = NULL;
U = NULL;
err = lis_matrix_ilu_create(nr,bnr,&L);
if( err ) return err;
err = lis_matrix_ilu_create(nr,bnr,&U);
if( err ) return err;
err = lis_matrix_ilu_setCR(L);
if( err ) return err;
err = lis_matrix_ilu_setCR(U);
if( err ) return err;
err = lis_matrix_diag_duplicateM(A,&D);
if( err )
{
return err;
}
ulvl = (LIS_INT **)lis_malloc(nr*sizeof(LIS_INT *),"lis_symbolic_fact_bsr::ulvl");
if( ulvl==NULL )
{
LIS_SETERR_MEM(n*sizeof(LIS_INT));
return LIS_OUT_OF_MEMORY;
}
levls = (LIS_INT *)lis_malloc(nr*sizeof(LIS_INT),"lis_symbolic_fact_bsr::levls");
if( levls==NULL )
{
LIS_SETERR_MEM(n*sizeof(LIS_INT));
return LIS_OUT_OF_MEMORY;
}
jbuf = (LIS_INT *)lis_malloc(nr*sizeof(LIS_INT),"lis_symbolic_fact_bsr::jbuf");
if( jbuf==NULL )
{
LIS_SETERR_MEM(n*sizeof(LIS_INT));
return LIS_OUT_OF_MEMORY;
}
iw = (LIS_INT *)lis_malloc(nr*sizeof(LIS_INT),"lis_symbolic_fact_bsr::iw");
if( iw==NULL )
{
LIS_SETERR_MEM(n*sizeof(LIS_INT));
return LIS_OUT_OF_MEMORY;
}
for(i=0;i<nr;i++) iw[i]=-1;
for(i=0;i<nr;i++)
{
incl = 0;
incu = i;
for(j=A->bptr[i];j<A->bptr[i+1];j++)
{
col = A->bindex[j];
#ifdef USE_MPI
if( col>=nr ) continue;
#endif
if( col < i )
{
jbuf[incl] = col;
levls[incl] = 0;
iw[col] = incl++;
}
else if( col > i )
{
jbuf[incu] = col;
levls[incu] = 0;
iw[col] = incu++;
}
}
jpiv = -1;
while( ++jpiv < incl )
{
k = jbuf[jpiv];
kmin = k;
jmin = jpiv;
for(j=jpiv+1;j<incl;j++)
{
if( jbuf[j]<kmin )
{
kmin = jbuf[j];
jmin = j;
}
}
if( jmin!=jpiv )
{
jbuf[jpiv] = kmin;
jbuf[jmin] = k;
iw[kmin] = jpiv;
iw[k] = jmin;
j = levls[jpiv];
levls[jpiv] = levls[jmin];
levls[jmin] = j;
k = kmin;
}
for(j=0;j<U->nnz[k];j++)
{
col = U->index[k][j];
it = ulvl[k][j] + levls[jpiv]+1;
if( it > levfill ) continue;
ip = iw[col];
if( ip==-1 )
{
if( col < i )
{
jbuf[incl] = col;
levls[incl] = it;
iw[col] = incl++;
}
else if( col > i )
{
jbuf[incu] = col;
levls[incu] = it;
iw[col] = incu++;
}
}
else
{
levls[ip] = _min(levls[ip],it);
}
}
}
for(j=0;j<incl;j++) iw[jbuf[j]] = -1;
for(j=i;j<incu;j++) iw[jbuf[j]] = -1;
L->nnz[i] = incl;
if( incl > 0 )
{
L->index[i] = (LIS_INT *)malloc(incl*sizeof(LIS_INT));
L->value[i] = (LIS_SCALAR *)malloc(bs*incl*sizeof(LIS_SCALAR));
memcpy(L->index[i],jbuf,incl*sizeof(LIS_INT));
}
k = incu-i;
U->nnz[i] = k;
if( k > 0 )
{
U->index[i] = (LIS_INT *)malloc(k*sizeof(LIS_INT));
U->value[i] = (LIS_SCALAR *)malloc(bs*k*sizeof(LIS_SCALAR));
ulvl[i] = (LIS_INT *)malloc(k*sizeof(LIS_INT));
memcpy(U->index[i],jbuf+i,k*sizeof(LIS_INT));
memcpy(ulvl[i],levls+i,k*sizeof(LIS_INT));
}
}
precon->L = L;
precon->U = U;
precon->WD = D;
lis_free2(3,levls,jbuf,iw);
for(i=0;i<nr-1;i++)
{
if(U->nnz[i]) free(ulvl[i]);
}
lis_free(ulvl);
LIS_DEBUG_FUNC_OUT;
return LIS_SUCCESS;
#endif
}
#undef __FUNC__
#define __FUNC__ "lis_numerical_fact_bsr"
LIS_INT lis_numerical_fact_bsr(LIS_SOLVER solver, LIS_PRECON precon)
{
#ifdef _OPENMP
LIS_INT err;
LIS_INT i,j,k,bnr,bs;
LIS_INT n,nr;
LIS_INT col,jpos,jrow;
LIS_INT *jw;
LIS_INT is,ie,my_rank,nprocs;
LIS_SCALAR buf[16];
LIS_MATRIX A;
LIS_MATRIX_ILU L,U;
LIS_MATRIX_DIAG D;
LIS_DEBUG_FUNC_IN;
A = solver->A;
n = A->n;
nr = A->nr;
bnr = A->bnr;
bs = bnr*bnr;
nprocs = omp_get_max_threads();
L = precon->L;
U = precon->U;
D = precon->WD;
jw = (LIS_INT *)lis_malloc(nr*sizeof(LIS_INT),"lis_numerical_fact_bsr::jw");
if( jw==NULL )
{
LIS_SETERR_MEM(n*sizeof(LIS_INT));
return LIS_OUT_OF_MEMORY;
}
#pragma omp parallel private(i,j,k,is,ie,my_rank,col,jpos,jrow,buf)
{
my_rank = omp_get_thread_num();
LIS_GET_ISIE(my_rank,nprocs,nr,is,ie);
for(i=is;i<ie;i++) jw[i] = -1;
for(i=is;i<ie;i++)
{
for(j=0;j<L->nnz[i];j++)
{
col = L->index[i][j];
jw[col] = j;
memset(&L->value[i][bs*j],0,bs*sizeof(LIS_SCALAR));
}
jw[i] = i;
memset(&D->value[bs*i],0,bs*sizeof(LIS_SCALAR));
for(j=0;j<U->nnz[i];j++)
{
col = U->index[i][j];
jw[col] = j;
memset(&U->value[i][bs*j],0,bs*sizeof(LIS_SCALAR));
}
for(j=A->bptr[i];j<A->bptr[i+1];j++)
{
col = A->bindex[j];
#ifdef USE_MPI
if( col>=nr ) continue;
#endif
if( col>=is && col<ie )
{
jpos = jw[col];
if( col<i )
{
memcpy(&L->value[i][bs*jpos],&A->value[bs*j],bs*sizeof(LIS_SCALAR));
}
else if( col==i )
{
memcpy(&D->value[bs*i],&A->value[bs*j],bs*sizeof(LIS_SCALAR));
}
else
{
memcpy(&U->value[i][bs*jpos],&A->value[bs*j],bs*sizeof(LIS_SCALAR));
}
}
}
for(j=0;j<L->nnz[i];j++)
{
jrow = L->index[i][j];
lis_array_matmat(bnr,&L->value[i][bs*j],&D->value[bs*jrow],buf,LIS_INS_VALUE);
memcpy(&L->value[i][bs*j],buf,bs*sizeof(LIS_SCALAR));
for(k=0;k<U->nnz[jrow];k++)
{
col = U->index[jrow][k];
jpos = jw[col];
if( jpos==-1 ) continue;
if( col<i )
{
lis_array_matmat(bnr,&L->value[i][bs*j],&U->value[jrow][bs*k],&L->value[i][bs*jpos],LIS_SUB_VALUE);
}
else if( col==i )
{
lis_array_matmat(bnr,&L->value[i][bs*j],&U->value[jrow][bs*k],&D->value[bs*i],LIS_SUB_VALUE);
}
else
{
lis_array_matmat(bnr,&L->value[i][bs*j],&U->value[jrow][bs*k],&U->value[i][bs*jpos],LIS_SUB_VALUE);
}
}
}
for(j=0;j<L->nnz[i];j++)
{
col = L->index[i][j];
jw[col] = -1;
}
jw[i] = -1;
for(j=0;j<U->nnz[i];j++)
{
col = U->index[i][j];
jw[col] = -1;
}
if( i==nr-1 )
{
switch(bnr)
{
case 2:
if( n%2!=0 )
{
D->value[4*(nr-1)+3] = 1.0;
}
break;
case 3:
if( n%3==1 )
{
D->value[9*(nr-1)+4] = 1.0;
D->value[9*(nr-1)+8] = 1.0;
}
else if( n%3==2 )
{
D->value[9*(nr-1)+8] = 1.0;
}
break;
}
}
lis_array_invGauss(bnr,&D->value[bs*i]);
}
}
lis_free(jw);
LIS_DEBUG_FUNC_OUT;
return LIS_SUCCESS;
#else
LIS_INT i,j,k,bnr,bs;
LIS_INT n,nr;
LIS_INT col,jpos,jrow;
LIS_INT *jw;
LIS_SCALAR buf[16];
LIS_MATRIX A;
LIS_MATRIX_ILU L,U;
LIS_MATRIX_DIAG D;
LIS_DEBUG_FUNC_IN;
A = solver->A;
n = A->n;
nr = A->nr;
bnr = A->bnr;
bs = bnr*bnr;
L = precon->L;
U = precon->U;
D = precon->WD;
jw = (LIS_INT *)lis_malloc(nr*sizeof(LIS_INT),"lis_numerical_fact_bsr::jw");
if( jw==NULL )
{
LIS_SETERR_MEM(n*sizeof(LIS_INT));
return LIS_OUT_OF_MEMORY;
}
for(i=0;i<nr;i++) jw[i] = -1;
for(i=0;i<nr;i++)
{
for(j=0;j<L->nnz[i];j++)
{
col = L->index[i][j];
jw[col] = j;
memset(&L->value[i][bs*j],0,bs*sizeof(LIS_SCALAR));
}
jw[i] = i;
memset(&D->value[bs*i],0,bs*sizeof(LIS_SCALAR));
for(j=0;j<U->nnz[i];j++)
{
col = U->index[i][j];
jw[col] = j;
memset(&U->value[i][bs*j],0,bs*sizeof(LIS_SCALAR));
}
for(j=A->bptr[i];j<A->bptr[i+1];j++)
{
col = A->bindex[j];
#ifdef USE_MPI
if( col>=nr ) continue;
#endif
jpos = jw[col];
if( col<i )
{
memcpy(&L->value[i][bs*jpos],&A->value[bs*j],bs*sizeof(LIS_SCALAR));
}
else if( col==i )
{
memcpy(&D->value[bs*i],&A->value[bs*j],bs*sizeof(LIS_SCALAR));
}
else
{
memcpy(&U->value[i][bs*jpos],&A->value[bs*j],bs*sizeof(LIS_SCALAR));
}
}
for(j=0;j<L->nnz[i];j++)
{
jrow = L->index[i][j];
lis_array_matmat(bnr,&L->value[i][bs*j],&D->value[bs*jrow],buf,LIS_INS_VALUE);
memcpy(&L->value[i][bs*j],buf,bs*sizeof(LIS_SCALAR));
for(k=0;k<U->nnz[jrow];k++)
{
col = U->index[jrow][k];
jpos = jw[col];
if( jpos==-1 ) continue;
if( col<i )
{
lis_array_matmat(bnr,&L->value[i][bs*j],&U->value[jrow][bs*k],&L->value[i][bs*jpos],LIS_SUB_VALUE);
}
else if( col==i )
{
lis_array_matmat(bnr,&L->value[i][bs*j],&U->value[jrow][bs*k],&D->value[bs*i],LIS_SUB_VALUE);
}
else
{
lis_array_matmat(bnr,&L->value[i][bs*j],&U->value[jrow][bs*k],&U->value[i][bs*jpos],LIS_SUB_VALUE);
}
}
}
for(j=0;j<L->nnz[i];j++)
{
col = L->index[i][j];
jw[col] = -1;
}
jw[i] = -1;
for(j=0;j<U->nnz[i];j++)
{
col = U->index[i][j];
jw[col] = -1;
}
if( i==nr-1 )
{
switch(bnr)
{
case 2:
if( n%2!=0 )
{
D->value[4*(nr-1)+3] = 1.0;
}
break;
case 3:
if( n%3==1 )
{
D->value[9*(nr-1)+4] = 1.0;
D->value[9*(nr-1)+8] = 1.0;
}
else if( n%3==2 )
{
D->value[9*(nr-1)+8] = 1.0;
}
break;
}
}
lis_array_invGauss(bnr,&D->value[bs*i]);
}
lis_free(jw);
LIS_DEBUG_FUNC_OUT;
return LIS_SUCCESS;
#endif
}
#undef __FUNC__
#define __FUNC__ "lis_psolve_iluk_bsr"
LIS_INT lis_psolve_iluk_bsr(LIS_SOLVER solver, LIS_VECTOR B, LIS_VECTOR X)
{
#ifdef _OPENMP
LIS_INT i,j,jj,nr,bnr,ii,bs;
LIS_INT is,ie,my_rank,nprocs;
LIS_SCALAR w[3],t;
LIS_SCALAR *b,*x;
LIS_MATRIX_ILU L,U;
LIS_MATRIX_DIAG D;
LIS_PRECON precon;
/*
* LUx = b
* LU = (D + L*A) * (I + D^-1 * U*A)
*/
LIS_DEBUG_FUNC_IN;
precon = solver->precon;
L = precon->L;
U = precon->U;
D = precon->WD;
b = B->value;
x = X->value;
nr = solver->A->nr;
bnr = solver->A->bnr;
bs = bnr*bnr;
nprocs = omp_get_max_threads();
lis_vector_copy(B,X);
#pragma omp parallel private(i,j,jj,is,ie,my_rank,w)
{
my_rank = omp_get_thread_num();
LIS_GET_ISIE(my_rank,nprocs,nr,is,ie);
for(i=is;i<ie;i++)
{
for(j=0;j<L->nnz[i];j++)
{
jj = L->index[i][j];
lis_array_matvec(bnr,&L->value[i][bs*j],&x[bnr*jj],&x[bnr*i],LIS_SUB_VALUE);
/* x[bnr*i+0] -= L->value[i][bs*j+0]*x[bnr*jj+0] + L->value[i][bs*j+3]*x[bnr*jj+1] + L->value[i][bs*j+6]*x[bnr*jj+2];
x[bnr*i+1] -= L->value[i][bs*j+1]*x[bnr*jj+0] + L->value[i][bs*j+4]*x[bnr*jj+1] + L->value[i][bs*j+7]*x[bnr*jj+2];
x[bnr*i+2] -= L->value[i][bs*j+2]*x[bnr*jj+0] + L->value[i][bs*j+5]*x[bnr*jj+1] + L->value[i][bs*j+8]*x[bnr*jj+2];*/
}
}
for(i=ie-1;i>=is;i--)
{
for(j=0;j<U->nnz[i];j++)
{
jj = U->index[i][j];
lis_array_matvec(bnr,&U->value[i][bs*j],&x[bnr*jj],&x[bnr*i],LIS_SUB_VALUE);
/* x[bnr*i+0] -= U->value[i][bs*j+0]*x[bnr*jj+0] + U->value[i][bs*j+3]*x[bnr*jj+1] + U->value[i][bs*j+6]*x[bnr*jj+2];
x[bnr*i+1] -= U->value[i][bs*j+1]*x[bnr*jj+0] + U->value[i][bs*j+4]*x[bnr*jj+1] + U->value[i][bs*j+7]*x[bnr*jj+2];
x[bnr*i+2] -= U->value[i][bs*j+2]*x[bnr*jj+0] + U->value[i][bs*j+5]*x[bnr*jj+1] + U->value[i][bs*j+8]*x[bnr*jj+2];*/
}
/* luinv(bnr,&D->value[bs*i],&x[bnr*i],w);
memcpy(&x[bnr*i],w,bnr*sizeof(LIS_SCALAR));
w[0] = D->value[bs*i+0]*x[bnr*i+0] + D->value[bs*i+3]*x[bnr*i+1] + D->value[bs*i+6]*x[bnr*i+2];
w[1] = D->value[bs*i+1]*x[bnr*i+0] + D->value[bs*i+4]*x[bnr*i+1] + D->value[bs*i+7]*x[bnr*i+2];
w[2] = D->value[bs*i+2]*x[bnr*i+0] + D->value[bs*i+5]*x[bnr*i+1] + D->value[bs*i+8]*x[bnr*i+2];
x[bnr*i+0] = w[0];
x[bnr*i+1] = w[1];
x[bnr*i+2] = w[2];*/
lis_array_matvec(bnr,&D->value[bs*i],&x[bnr*i],w,LIS_INS_VALUE);
memcpy(&x[bnr*i],w,bnr*sizeof(LIS_SCALAR));
}
}
LIS_DEBUG_FUNC_OUT;
return LIS_SUCCESS;
#else
LIS_INT i,j,jj,nr,bnr,bs;
LIS_SCALAR w[9];
LIS_SCALAR *b,*x;
LIS_MATRIX_ILU L,U;
LIS_MATRIX_DIAG D;
LIS_PRECON precon;
/*
* LUx = b
* LU = (D + L*A) * (I + D^-1 * U*A)
*/
LIS_DEBUG_FUNC_IN;
precon = solver->precon;
L = precon->L;
U = precon->U;
D = precon->WD;
b = B->value;
x = X->value;
nr = solver->A->nr;
bnr = solver->A->bnr;
bs = bnr*bnr;
lis_vector_copy(B,X);
for(i=0; i<nr; i++)
{
for(j=0;j<L->nnz[i];j++)
{
jj = L->index[i][j];
lis_array_matvec(bnr,&L->value[i][bs*j],&x[bnr*jj],&x[bnr*i],LIS_SUB_VALUE);
}
}
for(i=nr-1; i>=0; i--)
{
for(j=0;j<U->nnz[i];j++)
{
jj = U->index[i][j];
lis_array_matvec(bnr,&U->value[i][bs*j],&x[bnr*jj],&x[bnr*i],LIS_SUB_VALUE);
}
/* luinv(bnr,&D->value[bs*i],&x[bnr*i],w);
memcpy(&x[bnr*i],w,bnr*sizeof(LIS_SCALAR));*/
lis_array_matvec(bnr,&D->value[bs*i],&x[bnr*i],w,LIS_INS_VALUE);
memcpy(&x[bnr*i],w,bnr*sizeof(LIS_SCALAR));
}
LIS_DEBUG_FUNC_OUT;
return LIS_SUCCESS;
#endif
}
#undef __FUNC__
#define __FUNC__ "lis_psolvet_iluk_bsr"
LIS_INT lis_psolvet_iluk_bsr(LIS_SOLVER solver, LIS_VECTOR B, LIS_VECTOR X)
{
#ifdef _OPENMP
LIS_INT i,j,jj,nr,bnr,ii,bs;
LIS_INT is,ie,my_rank,nprocs;
LIS_SCALAR w[3],t;
LIS_SCALAR *b,*x;
LIS_MATRIX_ILU L,U;
LIS_MATRIX_DIAG D;
LIS_PRECON precon;
/*
* LUx = b
* LU = (D + L*A) * (I + D^-1 * U*A)
*/
LIS_DEBUG_FUNC_IN;
precon = solver->precon;
L = precon->L;
U = precon->U;
D = precon->WD;
b = B->value;
x = X->value;
nr = solver->A->nr;
bnr = solver->A->bnr;
bs = bnr*bnr;
nprocs = omp_get_max_threads();
lis_vector_copy(B,X);
#pragma omp parallel private(i,j,jj,is,ie,my_rank,w)
{
my_rank = omp_get_thread_num();
LIS_GET_ISIE(my_rank,nprocs,nr,is,ie);
for(i=is;i<ie;i++)
{
for(j=0;j<L->nnz[i];j++)
{
jj = L->index[i][j];
lis_array_matvec(bnr,&L->value[i][bs*j],&x[bnr*jj],&x[bnr*i],LIS_SUB_VALUE);
/* x[bnr*i+0] -= L->value[i][bs*j+0]*x[bnr*jj+0] + L->value[i][bs*j+3]*x[bnr*jj+1] + L->value[i][bs*j+6]*x[bnr*jj+2];
x[bnr*i+1] -= L->value[i][bs*j+1]*x[bnr*jj+0] + L->value[i][bs*j+4]*x[bnr*jj+1] + L->value[i][bs*j+7]*x[bnr*jj+2];
x[bnr*i+2] -= L->value[i][bs*j+2]*x[bnr*jj+0] + L->value[i][bs*j+5]*x[bnr*jj+1] + L->value[i][bs*j+8]*x[bnr*jj+2];*/
}
}
for(i=ie-1;i>=is;i--)
{
for(j=0;j<U->nnz[i];j++)
{
jj = U->index[i][j];
lis_array_matvec(bnr,&U->value[i][bs*j],&x[bnr*jj],&x[bnr*i],LIS_SUB_VALUE);
/* x[bnr*i+0] -= U->value[i][bs*j+0]*x[bnr*jj+0] + U->value[i][bs*j+3]*x[bnr*jj+1] + U->value[i][bs*j+6]*x[bnr*jj+2];
x[bnr*i+1] -= U->value[i][bs*j+1]*x[bnr*jj+0] + U->value[i][bs*j+4]*x[bnr*jj+1] + U->value[i][bs*j+7]*x[bnr*jj+2];
x[bnr*i+2] -= U->value[i][bs*j+2]*x[bnr*jj+0] + U->value[i][bs*j+5]*x[bnr*jj+1] + U->value[i][bs*j+8]*x[bnr*jj+2];*/
}
/* luinv(bnr,&D->value[bs*i],&x[bnr*i],w);
memcpy(&x[bnr*i],w,bnr*sizeof(LIS_SCALAR));
w[0] = D->value[bs*i+0]*x[bnr*i+0] + D->value[bs*i+3]*x[bnr*i+1] + D->value[bs*i+6]*x[bnr*i+2];
w[1] = D->value[bs*i+1]*x[bnr*i+0] + D->value[bs*i+4]*x[bnr*i+1] + D->value[bs*i+7]*x[bnr*i+2];
w[2] = D->value[bs*i+2]*x[bnr*i+0] + D->value[bs*i+5]*x[bnr*i+1] + D->value[bs*i+8]*x[bnr*i+2];
x[bnr*i+0] = w[0];
x[bnr*i+1] = w[1];
x[bnr*i+2] = w[2];*/
lis_array_matvec(bnr,&D->value[bs*i],&x[bnr*i],w,LIS_INS_VALUE);
memcpy(&x[bnr*i],w,bnr*sizeof(LIS_SCALAR));
}
}
LIS_DEBUG_FUNC_OUT;
return LIS_SUCCESS;
#else
LIS_INT i,j,jj,nr,bnr,bs;
LIS_SCALAR w[9];
LIS_SCALAR *b,*x;
LIS_MATRIX_ILU L,U;
LIS_MATRIX_DIAG D;
LIS_PRECON precon;
/*
* LUx = b
* LU = (D + L*A) * (I + D^-1 * U*A)
*/
LIS_DEBUG_FUNC_IN;
precon = solver->precon;
L = precon->L;
U = precon->U;
D = precon->WD;
b = B->value;
x = X->value;
nr = solver->A->nr;
bnr = solver->A->bnr;
bs = bnr*bnr;
lis_vector_copy(B,X);
for(i=0; i<nr; i++)
{
lis_array_matvect(bnr,&D->value[bs*i],&x[bnr*i],w,LIS_INS_VALUE);
memcpy(&x[bnr*i],w,bnr*sizeof(LIS_SCALAR));
for(j=0;j<U->nnz[i];j++)
{
jj = U->index[i][j];
lis_array_matvect(bnr,&U->value[i][bs*j],&x[bnr*i],&x[bnr*jj],LIS_SUB_VALUE);
}
}
for(i=nr-1; i>=0; i--)
{
for(j=0;j<L->nnz[i];j++)
{
jj = L->index[i][j];
lis_array_matvect(bnr,&L->value[i][bs*j],&x[bnr*i],&x[bnr*jj],LIS_SUB_VALUE);
}
/* luinv(bnr,&D->value[bs*i],&x[bnr*i],w);
memcpy(&x[bnr*i],w,bnr*sizeof(LIS_SCALAR));*/
}
LIS_DEBUG_FUNC_OUT;
return LIS_SUCCESS;
#endif
}
#undef __FUNC__
#define __FUNC__ "lis_symbolic_fact_vbr"
LIS_INT lis_symbolic_fact_vbr(LIS_SOLVER solver, LIS_PRECON precon)
{
#ifdef _OPENMP
LIS_INT err;
LIS_INT i,j,k,kk,t,bnr,bs;
LIS_INT n,nr,levfill;
LIS_INT col,ip,it,jpiv,incl,incu,jmin,kmin;
LIS_INT *levls,*jbuf,*iw,**ulvl;
LIS_INT is,ie,my_rank,nprocs;
LIS_MATRIX A;
LIS_MATRIX_ILU L,U;
LIS_MATRIX_DIAG D;
LIS_DEBUG_FUNC_IN;
A = solver->A;
n = A->n;
nr = A->nr;
bnr = A->bnr;
bs = bnr*bnr;
levfill = solver->options[LIS_OPTIONS_FILL];
nprocs = omp_get_max_threads();
L = NULL;
U = NULL;
err = lis_matrix_ilu_create(nr,bnr,&L);
if( err ) return err;
err = lis_matrix_ilu_create(nr,bnr,&U);
if( err ) return err;
err = lis_matrix_ilu_setVR(L);
if( err ) return err;
err = lis_matrix_ilu_setVR(U);
if( err ) return err;
memcpy(L->bsz,A->row,(nr+1)*sizeof(LIS_INT));
memcpy(U->bsz,A->row,(nr+1)*sizeof(LIS_INT));
err = lis_matrix_diag_duplicateM(A,&D);
if( err )
{
return err;
}
ulvl = (LIS_INT **)lis_malloc(nr*sizeof(LIS_INT *),"lis_symbolic_fact_bsr::ulvl");
if( ulvl==NULL )
{
LIS_SETERR_MEM(n*sizeof(LIS_INT));
return LIS_OUT_OF_MEMORY;
}
levls = (LIS_INT *)lis_malloc(nr*sizeof(LIS_INT),"lis_symbolic_fact_bsr::levls");
if( levls==NULL )
{
LIS_SETERR_MEM(n*sizeof(LIS_INT));
return LIS_OUT_OF_MEMORY;
}
jbuf = (LIS_INT *)lis_malloc(nr*sizeof(LIS_INT),"lis_symbolic_fact_bsr::jbuf");
if( jbuf==NULL )
{
LIS_SETERR_MEM(n*sizeof(LIS_INT));
return LIS_OUT_OF_MEMORY;
}
iw = (LIS_INT *)lis_malloc(nr*sizeof(LIS_INT),"lis_symbolic_fact_bsr::iw");
if( iw==NULL )
{
LIS_SETERR_MEM(n*sizeof(LIS_INT));
return LIS_OUT_OF_MEMORY;
}
for(i=0;i<nr;i++) iw[i]=-1;
#pragma omp parallel private(i,j,k,is,ie,my_rank,incl,incu,col,jpiv,it,ip,kmin,jmin)
{
my_rank = omp_get_thread_num();
LIS_GET_ISIE(my_rank,nprocs,nr,is,ie);
for(i=0;i<nr;i++)
{
incl = 0;
incu = i;
for(j=A->bptr[i];j<A->bptr[i+1];j++)
{
col = A->bindex[j];
#ifdef USE_MPI
if( col>=nr ) continue;
#endif
if( col < i )
{
jbuf[incl] = col;
levls[incl] = 0;
iw[col] = incl++;
}
else if( col > i )
{
jbuf[incu] = col;
levls[incu] = 0;
iw[col] = incu++;
}
}
jpiv = -1;
while( ++jpiv < incl )
{
k = jbuf[jpiv];
kmin = k;
jmin = jpiv;
for(j=jpiv+1;j<incl;j++)
{
if( jbuf[j]<kmin )
{
kmin = jbuf[j];
jmin = j;
}
}
if( jmin!=jpiv )
{
jbuf[jpiv] = kmin;
jbuf[jmin] = k;
iw[kmin] = jpiv;
iw[k] = jmin;
j = levls[jpiv];
levls[jpiv] = levls[jmin];
levls[jmin] = j;
k = kmin;
}
for(j=0;j<U->nnz[k];j++)
{
col = U->index[k][j];
it = ulvl[k][j] + levls[jpiv]+1;
if( it > levfill ) continue;
ip = iw[col];
if( ip==-1 )
{
if( col < i )
{
jbuf[incl] = col;
levls[incl] = it;
iw[col] = incl++;
}
else if( col > i )
{
jbuf[incu] = col;
levls[incu] = it;
iw[col] = incu++;
}
}
else
{
levls[ip] = _min(levls[ip],it);
}
}
}
for(j=0;j<incl;j++) iw[jbuf[j]] = -1;
for(j=i;j<incu;j++) iw[jbuf[j]] = -1;
L->nnz[i] = incl;
if( incl > 0 )
{
L->index[i] = (LIS_INT *)malloc(incl*sizeof(LIS_INT));
L->values[i] = (LIS_SCALAR **)malloc(incl*sizeof(LIS_SCALAR *));
memcpy(L->index[i],jbuf,incl*sizeof(LIS_INT));
/*
printf("i=%d L_nnz=%d\n",i,incl);
for(j=0;j<incl;j++)
{
printf("(%d,%d) ",j,jbuf[j]);
}
printf("\n");
*/
}
k = incu-i;
U->nnz[i] = k;
if( k > 0 )
{
U->index[i] = (LIS_INT *)malloc(k*sizeof(LIS_INT));
U->values[i] = (LIS_SCALAR **)malloc(k*sizeof(LIS_SCALAR *));
ulvl[i] = (LIS_INT *)malloc(k*sizeof(LIS_INT));
memcpy(U->index[i],jbuf+i,k*sizeof(LIS_INT));
memcpy(ulvl[i],levls+i,k*sizeof(LIS_INT));
/*
printf("i=%d U_nnz=%d\n",i,k);
for(j=i;j<incu;j++)
{
printf("(%d,%d) ",j,jbuf[j]);
}
printf("\n");
*/
}
}
}
precon->L = L;
precon->U = U;
precon->WD = D;
lis_free2(3,levls,jbuf,iw);
for(i=0;i<nr-1;i++)
{
if(U->nnz[i]) free(ulvl[i]);
}
lis_free(ulvl);
LIS_DEBUG_FUNC_OUT;
return LIS_SUCCESS;
#else
LIS_INT err;
LIS_INT i,j,k,bnr,bs;
LIS_INT n,nr,levfill;
LIS_INT col,ip,it,jpiv,incl,incu,jmin,kmin;
LIS_INT *levls,*jbuf,*iw,**ulvl;
LIS_MATRIX A;
LIS_MATRIX_ILU L,U;
LIS_MATRIX_DIAG D;
LIS_DEBUG_FUNC_IN;
A = solver->A;
n = A->n;
nr = A->nr;
bnr = A->bnr;
bs = bnr*bnr;
levfill = solver->options[LIS_OPTIONS_FILL];
L = NULL;
U = NULL;
err = lis_matrix_ilu_create(nr,bnr,&L);
if( err ) return err;
err = lis_matrix_ilu_create(nr,bnr,&U);
if( err ) return err;
err = lis_matrix_ilu_setVR(L);
if( err ) return err;
err = lis_matrix_ilu_setVR(U);
if( err ) return err;
memcpy(L->bsz,A->row,(nr+1)*sizeof(LIS_INT));
memcpy(U->bsz,A->row,(nr+1)*sizeof(LIS_INT));
err = lis_matrix_diag_duplicateM(A,&D);
if( err )
{
return err;
}
ulvl = (LIS_INT **)lis_malloc(nr*sizeof(LIS_INT *),"lis_symbolic_fact_bsr::ulvl");
if( ulvl==NULL )
{
LIS_SETERR_MEM(n*sizeof(LIS_INT));
return LIS_OUT_OF_MEMORY;
}
levls = (LIS_INT *)lis_malloc(nr*sizeof(LIS_INT),"lis_symbolic_fact_bsr::levls");
if( levls==NULL )
{
LIS_SETERR_MEM(n*sizeof(LIS_INT));
return LIS_OUT_OF_MEMORY;
}
jbuf = (LIS_INT *)lis_malloc(nr*sizeof(LIS_INT),"lis_symbolic_fact_bsr::jbuf");
if( jbuf==NULL )
{
LIS_SETERR_MEM(n*sizeof(LIS_INT));
return LIS_OUT_OF_MEMORY;
}
iw = (LIS_INT *)lis_malloc(nr*sizeof(LIS_INT),"lis_symbolic_fact_bsr::iw");
if( iw==NULL )
{
LIS_SETERR_MEM(n*sizeof(LIS_INT));
return LIS_OUT_OF_MEMORY;
}
for(i=0;i<nr;i++) iw[i]=-1;
for(i=0;i<nr;i++)
{
incl = 0;
incu = i;
for(j=A->bptr[i];j<A->bptr[i+1];j++)
{
col = A->bindex[j];
#ifdef USE_MPI
if( col>=nr ) continue;
#endif
if( col < i )
{
jbuf[incl] = col;
levls[incl] = 0;
iw[col] = incl++;
}
else if( col > i )
{
jbuf[incu] = col;
levls[incu] = 0;
iw[col] = incu++;
}
}
jpiv = -1;
while( ++jpiv < incl )
{
k = jbuf[jpiv];
kmin = k;
jmin = jpiv;
for(j=jpiv+1;j<incl;j++)
{
if( jbuf[j]<kmin )
{
kmin = jbuf[j];
jmin = j;
}
}
if( jmin!=jpiv )
{
jbuf[jpiv] = kmin;
jbuf[jmin] = k;
iw[kmin] = jpiv;
iw[k] = jmin;
j = levls[jpiv];
levls[jpiv] = levls[jmin];
levls[jmin] = j;
k = kmin;
}
for(j=0;j<U->nnz[k];j++)
{
col = U->index[k][j];
it = ulvl[k][j] + levls[jpiv]+1;
if( it > levfill ) continue;
ip = iw[col];
if( ip==-1 )
{
if( col < i )
{
jbuf[incl] = col;
levls[incl] = it;
iw[col] = incl++;
}
else if( col > i )
{
jbuf[incu] = col;
levls[incu] = it;
iw[col] = incu++;
}
}
else
{
levls[ip] = _min(levls[ip],it);
}
}
}
for(j=0;j<incl;j++) iw[jbuf[j]] = -1;
for(j=i;j<incu;j++) iw[jbuf[j]] = -1;
L->nnz[i] = incl;
if( incl > 0 )
{
L->index[i] = (LIS_INT *)malloc(incl*sizeof(LIS_INT));
L->values[i] = (LIS_SCALAR **)malloc(incl*sizeof(LIS_SCALAR *));
memcpy(L->index[i],jbuf,incl*sizeof(LIS_INT));
/*
printf("i=%d L_nnz=%d\n",i,incl);
for(j=0;j<incl;j++)
{
printf("(%d,%d) ",j,jbuf[j]);
}
printf("\n");
*/
}
k = incu-i;
U->nnz[i] = k;
if( k > 0 )
{
U->index[i] = (LIS_INT *)malloc(k*sizeof(LIS_INT));
U->values[i] = (LIS_SCALAR **)malloc(k*sizeof(LIS_SCALAR *));
ulvl[i] = (LIS_INT *)malloc(k*sizeof(LIS_INT));
memcpy(U->index[i],jbuf+i,k*sizeof(LIS_INT));
memcpy(ulvl[i],levls+i,k*sizeof(LIS_INT));
/*
printf("i=%d U_nnz=%d\n",i,k);
for(j=i;j<incu;j++)
{
printf("(%d,%d) ",j,jbuf[j]);
}
printf("\n");
*/
}
}
precon->L = L;
precon->U = U;
precon->WD = D;
lis_free2(3,levls,jbuf,iw);
for(i=0;i<nr-1;i++)
{
if(U->nnz[i]) free(ulvl[i]);
}
lis_free(ulvl);
LIS_DEBUG_FUNC_OUT;
return LIS_SUCCESS;
#endif
}
#define _DIM(bs,i) (bs[i+1]-bs[i])
#undef __FUNC__
#define __FUNC__ "lis_numerical_fact_vbr"
LIS_INT lis_numerical_fact_vbr(LIS_SOLVER solver, LIS_PRECON precon)
{
#ifdef _OPENMP
LIS_INT err;
LIS_INT i,j,k,dim,sz,mm,nn,kk;
LIS_INT n,nr;
LIS_INT col,jpos,jrow;
LIS_INT *jw,*bsz;
LIS_INT is,ie,my_rank,nprocs;
LIS_SCALAR buf[1024];
LIS_MATRIX A;
LIS_MATRIX_ILU L,U;
LIS_MATRIX_DIAG D;
LIS_DEBUG_FUNC_IN;
A = solver->A;
n = A->n;
nr = A->nr;
nprocs = omp_get_max_threads();
L = precon->L;
U = precon->U;
D = precon->WD;
bsz = A->row;
jw = (LIS_INT *)lis_malloc(nr*sizeof(LIS_INT),"lis_numerical_fact_bsr::jw");
if( jw==NULL )
{
LIS_SETERR_MEM(n*sizeof(LIS_INT));
return LIS_OUT_OF_MEMORY;
}
#pragma omp parallel private(i,j,k,is,ie,my_rank,col,jpos,jrow,buf)
{
my_rank = omp_get_thread_num();
LIS_GET_ISIE(my_rank,nprocs,nr,is,ie);
for(i=0;i<nr;i++) jw[i] = -1;
for(i=0;i<nr;i++)
{
dim = _DIM(bsz,i);
for(j=0;j<L->nnz[i];j++)
{
col = L->index[i][j];
sz = dim*_DIM(bsz,col);
jw[col] = j;
L->values[i][j] = (LIS_SCALAR *)malloc(sz*sizeof(LIS_SCALAR));
memset(L->values[i][j],0,sz*sizeof(LIS_SCALAR));
}
jw[i] = i;
memset(D->v_value[i],0,dim*dim*sizeof(LIS_SCALAR));
for(j=0;j<U->nnz[i];j++)
{
col = U->index[i][j];
sz = dim*_DIM(bsz,col);
jw[col] = j;
U->values[i][j] = (LIS_SCALAR *)malloc(sz*sizeof(LIS_SCALAR));
memset(U->values[i][j],0,sz*sizeof(LIS_SCALAR));
}
for(j=A->bptr[i];j<A->bptr[i+1];j++)
{
col = A->bindex[j];
#ifdef USE_MPI
if( col>=nr ) continue;
#endif
sz = _DIM(bsz,col);
jpos = jw[col];
if( col<i )
{
memcpy(L->values[i][jpos],&A->value[A->ptr[j]],dim*sz*sizeof(LIS_SCALAR));
}
else if( col==i )
{
memcpy(D->v_value[i],&A->value[A->ptr[j]],dim*sz*sizeof(LIS_SCALAR));
}
else
{
memcpy(U->values[i][jpos],&A->value[A->ptr[j]],dim*sz*sizeof(LIS_SCALAR));
}
}
for(j=0;j<L->nnz[i];j++)
{
jrow = L->index[i][j];
mm = dim;
nn = _DIM(bsz,jrow);
lis_array_matmat2(mm,nn,nn,L->values[i][j],mm,D->v_value[jrow],nn,buf,mm,LIS_INS_VALUE);
memcpy(L->values[i][j],buf,mm*nn*sizeof(LIS_SCALAR));
for(k=0;k<U->nnz[jrow];k++)
{
col = U->index[jrow][k];
jpos = jw[col];
if( jpos==-1 ) continue;
if( col<i )
{
kk = _DIM(bsz,col);
lis_array_matmat2(mm,kk,nn,L->values[i][j],mm,U->values[jrow][k],nn,L->values[i][jpos],mm,LIS_SUB_VALUE);
}
else if( col==i )
{
lis_array_matmat2(mm,mm,nn,L->values[i][j],mm,U->values[jrow][k],nn,D->v_value[i],mm,LIS_SUB_VALUE);
}
else
{
kk = _DIM(bsz,col);
lis_array_matmat2(mm,kk,nn,L->values[i][j],mm,U->values[jrow][k],nn,U->values[i][jpos],mm,LIS_SUB_VALUE);
}
}
}
for(j=0;j<L->nnz[i];j++)
{
col = L->index[i][j];
jw[col] = -1;
}
jw[i] = -1;
for(j=0;j<U->nnz[i];j++)
{
col = U->index[i][j];
jw[col] = -1;
}
lis_array_invGauss(dim,D->v_value[i]);
}
}
lis_free(jw);
LIS_DEBUG_FUNC_OUT;
return LIS_SUCCESS;
#else
LIS_INT i,j,k,dim,sz,mm,nn,kk;
LIS_INT n,nr;
LIS_INT col,jpos,jrow;
LIS_INT *jw,*bsz;
LIS_SCALAR buf[1024];
LIS_MATRIX A;
LIS_MATRIX_ILU L,U;
LIS_MATRIX_DIAG D;
LIS_DEBUG_FUNC_IN;
A = solver->A;
n = A->n;
nr = A->nr;
L = precon->L;
U = precon->U;
D = precon->WD;
bsz = A->row;
jw = (LIS_INT *)lis_malloc(nr*sizeof(LIS_INT),"lis_numerical_fact_bsr::jw");
if( jw==NULL )
{
LIS_SETERR_MEM(n*sizeof(LIS_INT));
return LIS_OUT_OF_MEMORY;
}
for(i=0;i<nr;i++) jw[i] = -1;
for(i=0;i<nr;i++)
{
dim = _DIM(bsz,i);
for(j=0;j<L->nnz[i];j++)
{
col = L->index[i][j];
sz = dim*_DIM(bsz,col);
jw[col] = j;
L->values[i][j] = (LIS_SCALAR *)malloc(sz*sizeof(LIS_SCALAR));
memset(L->values[i][j],0,sz*sizeof(LIS_SCALAR));
}
jw[i] = i;
memset(D->v_value[i],0,dim*dim*sizeof(LIS_SCALAR));
for(j=0;j<U->nnz[i];j++)
{
col = U->index[i][j];
sz = dim*_DIM(bsz,col);
jw[col] = j;
U->values[i][j] = (LIS_SCALAR *)malloc(sz*sizeof(LIS_SCALAR));
memset(U->values[i][j],0,sz*sizeof(LIS_SCALAR));
}
for(j=A->bptr[i];j<A->bptr[i+1];j++)
{
col = A->bindex[j];
#ifdef USE_MPI
if( col>=nr ) continue;
#endif
sz = _DIM(bsz,col);
jpos = jw[col];
if( col<i )
{
memcpy(L->values[i][jpos],&A->value[A->ptr[j]],dim*sz*sizeof(LIS_SCALAR));
}
else if( col==i )
{
memcpy(D->v_value[i],&A->value[A->ptr[j]],dim*sz*sizeof(LIS_SCALAR));
}
else
{
memcpy(U->values[i][jpos],&A->value[A->ptr[j]],dim*sz*sizeof(LIS_SCALAR));
}
}
for(j=0;j<L->nnz[i];j++)
{
jrow = L->index[i][j];
mm = dim;
nn = _DIM(bsz,jrow);
/* printf("i=%d j=%d jrow=%d mm=%d nn=%d matmat\n",i,j,jrow,mm,nn);*/
lis_array_matmat2(mm,nn,nn,L->values[i][j],mm,D->v_value[jrow],nn,buf,mm,LIS_INS_VALUE);
memcpy(L->values[i][j],buf,mm*nn*sizeof(LIS_SCALAR));
for(k=0;k<U->nnz[jrow];k++)
{
col = U->index[jrow][k];
jpos = jw[col];
if( jpos==-1 ) continue;
if( col<i )
{
kk = _DIM(bsz,col);
lis_array_matmat2(mm,kk,nn,L->values[i][j],mm,U->values[jrow][k],nn,L->values[i][jpos],mm,LIS_SUB_VALUE);
}
else if( col==i )
{
lis_array_matmat2(mm,mm,nn,L->values[i][j],mm,U->values[jrow][k],nn,D->v_value[i],mm,LIS_SUB_VALUE);
}
else
{
kk = _DIM(bsz,col);
lis_array_matmat2(mm,kk,nn,L->values[i][j],mm,U->values[jrow][k],nn,U->values[i][jpos],mm,LIS_SUB_VALUE);
}
}
}
for(j=0;j<L->nnz[i];j++)
{
col = L->index[i][j];
jw[col] = -1;
}
jw[i] = -1;
for(j=0;j<U->nnz[i];j++)
{
col = U->index[i][j];
jw[col] = -1;
}
lis_array_invGauss(dim,D->v_value[i]);
}
lis_free(jw);
LIS_DEBUG_FUNC_OUT;
return LIS_SUCCESS;
#endif
}
#undef __FUNC__
#define __FUNC__ "lis_psolve_iluk_vbr"
LIS_INT lis_psolve_iluk_vbr(LIS_SOLVER solver, LIS_VECTOR B, LIS_VECTOR X)
{
#ifdef _OPENMP
LIS_INT i,j,jj,nr,bnr,dim,sz,*bsz;
LIS_INT is,ie,my_rank,nprocs;
LIS_SCALAR w[1024],t;
LIS_SCALAR *b,*x;
LIS_MATRIX_ILU L,U;
LIS_MATRIX_DIAG D;
LIS_PRECON precon;
/*
* LUx = b
* LU = (D + L*A) * (I + D^-1 * U*A)
*/
LIS_DEBUG_FUNC_IN;
precon = solver->precon;
L = precon->L;
U = precon->U;
D = precon->WD;
b = B->value;
x = X->value;
nr = solver->A->nr;
bsz = L->bsz;
nprocs = omp_get_max_threads();
lis_vector_copy(B,X);
#pragma omp parallel private(i,j,jj,is,ie,my_rank,w)
{
my_rank = omp_get_thread_num();
LIS_GET_ISIE(my_rank,nprocs,nr,is,ie);
for(i=0; i<nr; i++)
{
dim = _DIM(bsz,i);
bnr = bsz[i];
for(j=0;j<L->nnz[i];j++)
{
jj = L->index[i][j];
sz = _DIM(bsz,jj);
lis_array_matvec2(dim,sz,L->values[i][j],dim,&x[bsz[jj]],&x[bnr],LIS_SUB_VALUE);
}
}
for(i=nr-1; i>=0; i--)
{
dim = _DIM(bsz,i);
bnr = bsz[i];
for(j=0;j<U->nnz[i];j++)
{
jj = U->index[i][j];
sz = _DIM(bsz,jj);
lis_array_matvec2(dim,sz,U->values[i][j],dim,&x[bsz[jj]],&x[bnr],LIS_SUB_VALUE);
}
lis_array_matvec2(dim,dim,D->v_value[i],dim,&x[bnr],w,LIS_INS_VALUE);
memcpy(&x[bnr],w,dim*sizeof(LIS_SCALAR));
}
}
LIS_DEBUG_FUNC_OUT;
return LIS_SUCCESS;
#else
LIS_INT i,j,jj,nr,bnr,dim,sz,*bsz;
LIS_SCALAR w[1024];
LIS_SCALAR *b,*x;
LIS_MATRIX_ILU L,U;
LIS_MATRIX_DIAG D;
LIS_PRECON precon;
/*
* LUx = b
* LU = (D + L*A) * (I + D^-1 * U*A)
*/
LIS_DEBUG_FUNC_IN;
precon = solver->precon;
L = precon->L;
U = precon->U;
D = precon->WD;
b = B->value;
x = X->value;
nr = solver->A->nr;
bsz = L->bsz;
lis_vector_copy(B,X);
for(i=0; i<nr; i++)
{
dim = _DIM(bsz,i);
bnr = bsz[i];
for(j=0;j<L->nnz[i];j++)
{
jj = L->index[i][j];
sz = _DIM(bsz,jj);
lis_array_matvec2(dim,sz,L->values[i][j],dim,&x[bsz[jj]],&x[bnr],LIS_SUB_VALUE);
}
}
for(i=nr-1; i>=0; i--)
{
dim = _DIM(bsz,i);
bnr = bsz[i];
for(j=0;j<U->nnz[i];j++)
{
jj = U->index[i][j];
sz = _DIM(bsz,jj);
lis_array_matvec2(dim,sz,U->values[i][j],dim,&x[bsz[jj]],&x[bnr],LIS_SUB_VALUE);
}
lis_array_matvec2(dim,dim,D->v_value[i],dim,&x[bnr],w,LIS_INS_VALUE);
memcpy(&x[bnr],w,dim*sizeof(LIS_SCALAR));
}
LIS_DEBUG_FUNC_OUT;
return LIS_SUCCESS;
#endif
}
|
constr_dens.c | // for license information, see the accompanying LICENSE file
#include "vars_nuclear.h"
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <complex.h>
#include <assert.h>
#include <mpi.h>
extern double pi ;
double minr( double , double ) ;
void grid3( double * , double * , double * , const int , const int , const int , double * , double * , double * ) ;
void i2xyz( const int , int * , int * , int * , const int , const int ) ;
void divide_work( const int , const int , const int , int * , int * ) ;
void gradient( double complex * , const int , double complex * , double complex * , double complex * , const int , const int , const MPI_Comm , double complex * , double complex * , double complex * , const int , const int , const int , const int ) ;
void gradient_ud( double complex * f , const int n , double complex * g_x , double complex * g_y , double complex * g_z , double complex * g_xd , double complex * g_yd , double complex * g_zd , const int nstart , const int nstop , const MPI_Comm comm , double complex * d1_x , double complex * d1_y , double complex * d1_z , const int nx , const int ny , const int nz ) ;
void diverg( double * , double * , double * , double * , const int , const int , const int , const MPI_Comm , double complex * , double complex * , double complex * , const int , const int , const int ) ;
double factor_ec( const double , const double, int icub) ;
void shift_coords( double complex * vec , const int n , FFtransf_vars * fftransf_vars , Lattice_arrays * latt_coords , const double xcm , const double ycm , const double zcm ) ;
void laplacean( double * f , const int n , double * lapf , const int nstart , const int nstop , const MPI_Comm comm , double * k1d_x , double * k1d_y , double * k1d_z , const int nx , const int ny , const int nz , const int ired );
void laplacean_complex( double complex * f , const int n , double complex * lapf , const int nstart , const int nstop , const MPI_Comm comm , double * k1d_x , double * k1d_y , double * k1d_z , const int nx , const int ny , const int nz , const int ired ) ;
void allocate_dens( Densities * dens , const int ip , const int np , const int nxyz )
{
int iwork ;
int i ;
divide_work( nxyz , ip , np , &( dens->nstart ) , &( dens->nstop) ) ;
iwork = dens->nstop - dens->nstart ;
if( iwork > 0 )
{
assert( dens->tau = malloc( iwork * sizeof( double ) ) ) ;
assert( dens->nu = malloc( iwork * sizeof( double complex ) ) ) ;
assert( dens->divjj = malloc( iwork * sizeof( double ) ) ) ;
assert( dens->jjx = malloc( iwork * sizeof( double ) ) ) ;
assert( dens->jjy = malloc( iwork * sizeof( double ) ) ) ;
assert( dens->jjz = malloc( iwork * sizeof( double ) ) ) ;
for( i = 0 ; i < iwork ; i++ )
{
dens->tau[ i ] = 0. ;
dens->divjj[ i ] = 0. ;
dens->nu[ i ] = 0. + 0. * I ;
}
}
assert( dens->rho = malloc( nxyz * sizeof( double ) ) ) ;
#pragma omp parallel for default(shared) private(i)
for( i = 0 ; i < nxyz ; i++ )
dens->rho[ i ] = 0. ;
}
void mem_share( Densities * dens , double * ex_array , const int nxyz , const int idim )
{
int i ;
for( i = 0 ; i < idim ; i++ )
*( ex_array + i ) = 0. ;
dens->rho = ex_array ;
if( idim > nxyz ) {
dens->divjj = ex_array + nxyz ;
dens->tau = ex_array + ( nxyz + dens->nstop - dens->nstart ) ;
}
}
/* function to generate the 1D kinetic energy */
void generate_ke_1d( double * ke , const int n , const double a , const int iopt_der )
{
int i , j ;
double pi2 , angle , xn2 , constant , isign , xn ;
pi2 = pow( pi / a , 2 ) ;
xn = ( double ) n ;
xn2 = xn * xn ;
constant = 2.0 * pi2 / xn2 ;
if( iopt_der == 0 )
* ke = pi2 * ( 1.0 - 1.0 / xn2 ) / 3.0 ; /* Baye */
else
* ke = pi2 * ( 1.0 + 2.0 / xn2 ) / 3.0 ;
isign = - 1.0 ;
for ( i = 1 ; i < n ; i++ )
{
angle = ( double ) i * pi / xn ;
ke [ i ] = isign * constant / ( pow( sin( angle ) , 2.0 ) ) ;
if( iopt_der == 0 )
ke [ i ] = ke[ i ] * cos( angle ) ; /* Baye */
isign = - isign ;
}
}
/* Generate the 1D derivative */
void generate_der_1d( double complex * der , const int n , const double a , const int iopt_der )
{
int i , n1 ;
double angle , xn , c , isign ;
double c1 = 0. ; /* remove the highest component for c1=0 */
xn = (double) n ;
n1 = n - 1 ;
c = pi / xn ;
/* Note: the order in the derivative array is: -( N - 1 ) cooresponding to der[0],
-(N-1) + 1 corresponds to der[1] , and so forth */
if ( iopt_der == 0 )
* ( der + n1 ) = 0.0 ;
else
* ( der + n1 ) = - c * c1 * I / a ;
isign = -1.0 / a ;
for ( i = 1 ; i < n ; i++ )
{
angle = i * c ;
if ( iopt_der == 0 )
*( der + n1 + i ) = isign * c / sin( angle ) ;
else
*( der + n1 + i ) = isign * c * ( 1.0 / tan( angle ) - c1 * I ) ;
isign = - isign ;
*( der + n1 - i ) = - conj( *( der + n1 + i ) ) ;
}
}
void make_coordinates( const int nxyz , const int nx , const int ny , const int nz , const double dx , const double dy , const double dz , Lattice_arrays * lattice_vars )
{
double * xx , * yy , * zz ;
double xn ;
int i ;
assert( lattice_vars-> wx = malloc( nxyz * sizeof( int ) ) ) ;
assert( lattice_vars-> wy = malloc( nxyz * sizeof( int ) ) ) ;
assert( lattice_vars-> wz = malloc( nxyz * sizeof( int ) ) ) ;
assert( lattice_vars-> xa = malloc( nxyz * sizeof( double ) ) ) ;
assert( lattice_vars-> ya = malloc( nxyz * sizeof( double ) ) ) ;
assert( lattice_vars-> za = malloc( nxyz * sizeof( double ) ) ) ;
assert( lattice_vars-> kx = malloc( nxyz * sizeof( double ) ) ) ;
assert( lattice_vars-> ky = malloc( nxyz * sizeof( double ) ) ) ;
assert( lattice_vars-> kz = malloc( nxyz * sizeof( double ) ) ) ;
assert( lattice_vars-> kin = malloc( nxyz * sizeof( double ) ) ) ;
assert( xx = malloc( nx * sizeof( double ) ) ) ;
assert( yy = malloc( ny * sizeof( double ) ) ) ;
assert( zz = malloc( nz * sizeof( double ) ) ) ;
for(i=0;i<nx;i++)
xx[i]=1.;
xx[nx/2]=0.;
for(i=0;i<ny;i++)
yy[i]=1.;
yy[ny/2]=0.;
for(i=0;i<nz;i++)
zz[i]=1.;
zz[nz/2]=0.;
grid3( xx , yy , zz , nx , ny , nz , lattice_vars->xa , lattice_vars->ya , lattice_vars->za ) ;
for(i=0;i<nxyz;i++){
lattice_vars->wx[i]=(int) lattice_vars->xa[i];
lattice_vars->wy[i]=(int) lattice_vars->ya[i];
lattice_vars->wz[i]=(int) lattice_vars->za[i];
}
xn = ( ( double ) nx ) / 2.0 ;
for( i = 0 ; i < nx ; i++ )
xx[ i ] = ( ( double) i - xn ) * dx ;
xn = ( ( double ) ny ) / 2.0 ;
for( i = 0 ; i < ny ; i++ )
yy[ i ] = ( ( double ) i - xn ) * dy ;
xn = ( ( double ) nz ) / 2.0 ;
for( i = 0 ; i < nz ; i++ )
zz[ i ] = ( ( double ) i - xn ) * dz ;
grid3( xx , yy , zz , nx , ny , nz , lattice_vars->xa , lattice_vars->ya , lattice_vars->za ) ;
/* set also the momentum space */
xn = pi / ( ( double ) nx * dx ) ;
for( i = 0 ; i < nx / 2 ; i++ )
{
*( xx + i ) = ( double) ( 2 * i ) * xn ;
*( xx + i + nx / 2 ) = ( double ) ( 2 * i - nx ) * xn ;
}
xn = pi / ( ( double ) ny * dy ) ;
for( i = 0 ; i < ny / 2 ; i++ )
{
*( yy + i ) = ( double) ( 2 * i ) * xn ;
*( yy + i + ny / 2 ) = ( double ) ( 2 * i - ny ) * xn ;
}
xn = pi / ( ( double ) nz * dz ) ;
for( i = 0 ; i < nz / 2 ; i++ )
{
*( zz + i ) = ( double) ( 2 * i ) * xn ;
*( zz + i + nz / 2 ) = ( double ) ( 2 * i - nz ) * xn ;
}
grid3( xx , yy , zz , nx , ny , nz , lattice_vars->kx , lattice_vars->ky , lattice_vars->kz ) ;
for( i = 0 ; i < nxyz ; i++ )
{
lattice_vars->kin[ i ] = pow( lattice_vars->kx[ i ] , 2. ) + pow( lattice_vars->ky[ i ] , 2. ) + pow( lattice_vars->kz[ i ] , 2. ) ;
}
free( xx ) ;
free( yy ) ;
free( zz ) ;
}
void compute_densities( double * lam , double complex * z , const int nxyz , const int ip , const MPI_Comm comm , Densities * dens , const int m_ip , const int n_iq , const int i_p , const int i_q , const int mb , const int nb , const int p_proc , const int q_proc , const int nx , const int ny , const int nz , double complex * d1_x , double complex * d1_y , double complex * d1_z , double * k1d_x, double * k1d_y, double * k1d_z, const double e_max , int * nwf , double * occ , FFtransf_vars * fftransf_vars , Lattice_arrays * latt_coords , int icub)
{
/*
Computes the particle, anomalous and current densities from the eigenvectors z
*/
int n , nhalf , iwork ;
int i , j , li , lj , ii , jj , iu , id , kk1 , nn ;
int nstart , nstop ;
double complex * vec , * vec1 , * vec2 , * vec3 ;
double complex * dx_d , * dy_d , * dz_d , * dx_u , * dy_u , * dz_u ;
double num_part , num_part_sum , jxy , jxz , jyz , jzy , jyx , jzx , f1 ;
double complex * vvx, * vvy, * vvz;
double complex * lapl_d, * lapl_u; // laplacean of up and down components
double * rho , * occ1 ;
int * indx , i_tot ;
nstart = dens->nstart ;
nstop = dens->nstop ;
iwork = nstop - nstart ;
n = 4 * nxyz ;
nn = 3 * nxyz ;
nhalf = 2 * nxyz ;
assert( lapl_u = malloc( nxyz * sizeof( double complex ) ) ) ; // Asserting the laplacean elements.
assert( lapl_d = malloc( nxyz * sizeof( double complex ) ) ) ;
if( iwork > 0 ) {
assert( dx_d = malloc( iwork * sizeof( double complex ) ) ) ;
assert( dy_d = malloc( iwork * sizeof( double complex ) ) ) ;
assert( dz_d = malloc( iwork * sizeof( double complex ) ) ) ;
assert( dx_u = malloc( iwork * sizeof( double complex ) ) ) ;
assert( dy_u = malloc( iwork * sizeof( double complex ) ) ) ;
assert( dz_u = malloc( iwork * sizeof( double complex ) ) ) ;
}
assert( occ1 = malloc( nhalf * sizeof( double ) ) ) ;
assert( vec = malloc( nn * sizeof( double complex ) ) ) ;
assert( vec1 = malloc( n * sizeof( double complex ) ) ) ;
assert( rho = malloc( nxyz * sizeof( double ) ) ) ;
for( i = 0 ; i < nxyz ; i++ )
*( rho + i ) = 0. ;
for( i = 0 ; i < iwork ; i++ )
{
*( dens->tau + i ) = 0. ;
*( dens->divjj + i ) = 0. ;
*( dens->nu + i ) = 0. + I * 0. ;
}
* nwf = 0 ;
for( jj = 0 ; jj < nhalf ; jj++ ) {
occ1[ jj ] = 0. ;
}
f1 = 1.0 ;
for( jj = nhalf ; jj < n ; jj++ )
/* construct one vector at a time for positive eigenvalues */
{
f1 = sqrt( factor_ec( *( lam + jj ) , e_max ,icub) ) ;
if( f1 < 1.e-6 )
break ;
for( i = 0 ; i < n ; i++ )
*( vec1 + i ) = 0. + 0. * I ;
#pragma omp parallel for default(shared) private(li,ii,lj,j)
for( lj = 0 ; lj < n_iq ; lj++ )
{
j = i_q * nb + ( lj / nb ) * q_proc * nb + lj % nb ;
if( j == jj )
for( li = 0 ; li < m_ip ; li++ )
{
ii = i_p * mb + ( li / mb ) * p_proc * mb + li % mb ;
vec1[ ii ] = z[ lj * m_ip + li ] * f1 ;
}
}
MPI_Allreduce( vec1 + nxyz , vec , nn , MPI_DOUBLE_COMPLEX , MPI_SUM , comm ) ;
gradient_ud( vec + nxyz , nxyz , dx_u , dy_u , dz_u , dx_d , dy_d , dz_d , nstart , nstop , comm , d1_x , d1_y , d1_z , nx , ny , nz ) ;
// Calculating Laplacians.
laplacean_complex( vec + nxyz, nxyz, lapl_u, nstart, nstop, comm, k1d_x, k1d_y, k1d_z, nx, ny, nz, 0) ;
laplacean_complex( vec + 2*nxyz, nxyz, lapl_d, nstart, nstop, comm, k1d_x, k1d_y, k1d_z, nx, ny, nz, 0) ;
#pragma omp parallel for default(shared) private(i,iu,id,ii)
for( i = nstart ; i < nstop ; i++ )
{
ii = i - nstart ;
iu = i + nxyz ;
id = iu + nxyz ;
occ1[ *nwf ] += ( pow( cabs( vec[ iu ] ) , 2. ) + pow( cabs( vec[ id ] ) , 2. ) ) ;
*( rho + i ) += ( pow( cabs( vec[ iu ] ) , 2. ) + pow( cabs( vec[ id ] ) , 2. ) ) ;
*( dens->tau + ii ) -= creal(conj(vec[iu])*lapl_u[i] + conj(vec[id])*lapl_d[i]);
*( dens->nu + ii ) -= ( conj( vec[ i ] ) * vec[ iu ] ) ;
*( dens->divjj + ii ) -= ( cimag( dy_u[ ii ] * conj( dx_u[ ii ] ) - dy_d[ ii ] * conj( dx_d[ ii ] ) + dz_u[ ii ] * conj( dy_d[ ii ] ) - dy_u[ ii ] * conj( dz_d[ ii ] ) ) + creal( dx_d[ ii ] * conj( dz_u[ ii ] ) - dx_u[ ii ] * conj( dz_d[ ii ] ) ) ) ;
}
(*nwf)++ ;
}
free( vec ) ; free( vec1 ) ;
if( iwork > 0 ) { free( dx_d ) ; free( dy_d ) ; free( dz_d ) ; free( dx_u ) ; free( dy_u ) ; free( dz_u ) ; }
MPI_Allreduce( occ1 , occ , nhalf , MPI_DOUBLE , MPI_SUM , comm ) ;
MPI_Allreduce( rho , dens->rho , nxyz , MPI_DOUBLE , MPI_SUM , comm ) ;
free( lapl_u ) ; free( lapl_d );
free( occ1 ) ;
laplacean( dens->rho, nxyz, rho, 0, nxyz, comm, k1d_x, k1d_y, k1d_z, nx, ny, nz, 0 ); // Now buffer rho contains lap rho.
for( i = 0 ; i < nstop - nstart ; i++)
{
dens->tau[i]+=.5*rho[i+nstart] ;
dens->divjj[ i ] *= 2. ;
}
free( rho ) ;
}
void compute_densities_finitetemp( double * lam , double complex * z , const int nxyz , const int ip , const MPI_Comm comm , Densities * dens , const int m_ip , const int n_iq , const int i_p , const int i_q , const int mb , const int nb , const int p_proc , const int q_proc , const int nx , const int ny , const int nz , double complex * d1_x , double complex * d1_y , double complex * d1_z , const double e_max , const double temp, int * nwf , double * occ , FFtransf_vars * fftransf_vars , Lattice_arrays * latt_coords ,int icub)
{
/*
Computes the particle, anomalous and current densities from the eigenvectors z in
finite temperature case
*/
int n , nhalf , iwork ;
int i , j , li , lj , ii , jj , iu , id , kk1 , nn ;
int nstart , nstop ;
double complex * vec , * vec1 , * vec2 , * vec3 ;
double complex * dx_d , * dy_d , * dz_d , * dx_u , * dy_u , * dz_u ;
double num_part , num_part_sum , jxy , jxz , jyz , jzy , jyx , jzx , f1 , ft;
double complex * vvx, * vvy, * vvz;
double * rho , * occ1 ;
int * indx , i_tot ;
nstart = dens->nstart ;
nstop = dens->nstop ;
iwork = nstop - nstart ;
n = 4 * nxyz ;
nn = 3 * nxyz ;
nhalf = 2 * nxyz ;
if( iwork > 0 ) {
assert( dx_d = malloc( iwork * sizeof( double complex ) ) ) ;
assert( dy_d = malloc( iwork * sizeof( double complex ) ) ) ;
assert( dz_d = malloc( iwork * sizeof( double complex ) ) ) ;
assert( dx_u = malloc( iwork * sizeof( double complex ) ) ) ;
assert( dy_u = malloc( iwork * sizeof( double complex ) ) ) ;
assert( dz_u = malloc( iwork * sizeof( double complex ) ) ) ;
}
assert( occ1 = malloc( nhalf * sizeof( double ) ) ) ;
assert( vec = malloc( nn * sizeof( double complex ) ) ) ;
assert( vec1 = malloc( n * sizeof( double complex ) ) ) ;
assert( rho = malloc( nxyz * sizeof( double ) ) ) ;
for( i = 0 ; i < nxyz ; i++ )
*( rho + i ) = 0. ;
for( i = 0 ; i < iwork ; i++ )
{
*( dens->tau + i ) = 0. ;
*( dens->divjj + i ) = 0. ;
*( dens->nu + i ) = 0. + I * 0. ;
}
* nwf = 0 ;
for( jj = 0 ; jj < nhalf ; jj++ ) {
occ1[ jj ] = 0. ;
}
f1 = 1.0 ;
for( jj = nhalf ; jj < n ; jj++ )
/* construct one vector at a time for positive eigenvalues */
{
f1 = sqrt( factor_ec( *( lam + jj ) , e_max ,icub) ) ;
if( f1 < 1.e-6 )
break ;
ft = 1.0 / (1.0 + exp(-1.0 * *(lam + jj) / temp) );
for( i = 0 ; i < n ; i++ )
*( vec1 + i ) = 0. + 0. * I ;
#pragma omp parallel for default(shared) private(li,ii,lj,j)
for( lj = 0 ; lj < n_iq ; lj++ )
{
j = i_q * nb + ( lj / nb ) * q_proc * nb + lj % nb ;
if( j == jj )
for( li = 0 ; li < m_ip ; li++ )
{
ii = i_p * mb + ( li / mb ) * p_proc * mb + li % mb ;
vec1[ ii ] = z[ lj * m_ip + li ] * f1 ;
}
}
// finite temperature part. I
MPI_Allreduce( vec1 + nxyz , vec , nn , MPI_DOUBLE_COMPLEX , MPI_SUM , comm ) ;
gradient_ud( vec + nxyz , nxyz , dx_u , dy_u , dz_u , dx_d , dy_d , dz_d , nstart , nstop , comm , d1_x , d1_y , d1_z , nx , ny , nz ) ;
#pragma omp parallel for default(shared) private(i,iu,id,ii)
for( i = nstart ; i < nstop ; i++ )
{
ii = i - nstart ;
iu = i + nxyz ; // v - up component
id = iu + nxyz ; // v - down component
occ1[ *nwf ] += ( pow( cabs( vec[ iu ] ) , 2. ) + pow( cabs( vec[ id ] ) , 2. ) )*ft ;
*( rho + i ) += ( pow( cabs( vec[ iu ] ) , 2. ) + pow( cabs( vec[ id ] ) , 2. ) )*ft ;
*( dens->tau + ii ) += ( pow( cabs( dx_d[ ii ] ) , 2. ) + pow ( cabs( dy_d[ ii ] ) , 2. ) + pow( cabs( dz_d[ ii ] ) , 2. ) + pow( cabs( dx_u[ ii ] ) , 2. ) + pow ( cabs( dy_u[ ii ] ) , 2. ) + pow( cabs( dz_u[ ii ] ) , 2. ) )*ft ;
*( dens->nu + ii ) -= ( conj( vec[ i ] ) * vec[ iu ] ) * (2*ft-1) ;
*( dens->divjj + ii ) -= ( cimag( dy_u[ ii ] * conj( dx_u[ ii ] ) - dy_d[ ii ] * conj( dx_d[ ii ] ) + dz_u[ ii ] * conj( dy_d[ ii ] ) - dy_u[ ii ] * conj( dz_d[ ii ] ) ) + creal( dx_d[ ii ] * conj( dz_u[ ii ] ) - dx_u[ ii ] * conj( dz_d[ ii ] ) ) )*ft ;
}
// finite temperature part. II
MPI_Allreduce( vec1, vec , nn , MPI_DOUBLE_COMPLEX , MPI_SUM , comm ) ;
gradient_ud( vec , nxyz , dx_u , dy_u , dz_u , dx_d , dy_d , dz_d , nstart , nstop , comm , d1_x , d1_y , d1_z , nx , ny , nz ) ;
#pragma omp parallel for default(shared) private(i,iu,id,ii)
for( i = nstart ; i < nstop ; i++ )
{
ii = i - nstart ;
iu = i; // u - up component
id = iu + nxyz ; // u - down component
occ1[ *nwf ] += ( pow( cabs( vec[ iu ] ) , 2. ) + pow( cabs( vec[ id ] ) , 2. ) )*(1-ft) ;
*( rho + i ) += ( pow( cabs( vec[ iu ] ) , 2. ) + pow( cabs( vec[ id ] ) , 2. ) )*(1-ft) ;
*( dens->tau + ii ) += ( pow( cabs( dx_d[ ii ] ) , 2. ) + pow ( cabs( dy_d[ ii ] ) , 2. ) + pow( cabs( dz_d[ ii ] ) , 2. ) + pow( cabs( dx_u[ ii ] ) , 2. ) + pow ( cabs( dy_u[ ii ] ) , 2. ) + pow( cabs( dz_u[ ii ] ) , 2. ) )*(1-ft) ;
*( dens->divjj + ii ) -= ( cimag( dy_u[ ii ] * conj( dx_u[ ii ] ) - dy_d[ ii ] * conj( dx_d[ ii ] ) + dz_u[ ii ] * conj( dy_d[ ii ] ) - dy_u[ ii ] * conj( dz_d[ ii ] ) ) + creal( dx_d[ ii ] * conj( dz_u[ ii ] ) - dx_u[ ii ] * conj( dz_d[ ii ] ) ) )*(1-ft) ;
}
(*nwf)++ ;
}
free( vec ) ; free( vec1 ) ;
if( iwork > 0 ) { free( dx_d ) ; free( dy_d ) ; free( dz_d ) ; free( dx_u ) ; free( dy_u ) ; free( dz_u ) ; }
MPI_Allreduce( occ1 , occ , nhalf , MPI_DOUBLE , MPI_SUM , comm ) ;
MPI_Allreduce( rho , dens->rho , nxyz , MPI_DOUBLE , MPI_SUM , comm ) ;
free( rho ) ; free( occ1 ) ;
for( i = 0 ; i < nstop - nstart ; i++)
dens->divjj[ i ] *= 2. ;
}
double factor_ec( const double e , const double e_cut, int icub)
{
double e1 ;
double fact ;
e1 = ( e - e_cut )/ 0.25 ;
if( e1 > 40.0 )
fact = 0. ;
if( e1 < -40.0 )
fact = 1. ;
else
fact = 1. / ( 1. + exp( e1 ) ) ;
if(icub == 0) // Spherical cutoff.
if(e > e_cut)
fact = 0.;
else
fact = 1.;
else if (icub == 1)
fact = 1.0; // for cubic-cutoff
return( fact ) ;
}
void shift_coords( double complex * vec , const int n , FFtransf_vars * fftransf_vars , Lattice_arrays * latt_coords , const double xcm , const double ycm , const double zcm )
{
int i ;
double xarg ;
for( i = 0 ; i < n ; i++ )
* ( fftransf_vars->buff + i ) = vec[ i ] ;
fftw_execute( fftransf_vars->plan_f ) ;
for( i = 0 ; i < n ; i++ )
{
xarg = latt_coords->kx[ i ] * xcm + latt_coords->ky[ i ] * ycm + latt_coords->kz[ i ] * zcm ;
*( fftransf_vars->buff + i ) *= ( cos( xarg ) + I * sin( xarg ) ) ;
}
fftw_execute( fftransf_vars->plan_b ) ;
xarg = 1. / ( ( double ) n ) ;
for( i = 0 ; i < n ; i++ )
vec[ i ] = fftransf_vars->buff[ i ] * xarg ;
}
double rescale_dens( Densities * dens , const int nxyz , const double npart , const double dxyz , const int iscale )
{
int i ;
double xpart = 0. ;
for( i = 0 ; i < nxyz ; i++ )
xpart += *( dens->rho + i ) ;
xpart = xpart * dxyz / npart ;
if( iscale == 0 )
return( xpart ) ;
for( i = 0 ; i < nxyz ; i++ )
{
*( dens->rho + i ) = *( dens->rho + i ) / xpart ;
}
return( xpart ) ;
}
void exch_nucl_dens( const MPI_Comm commw , const int ip , const int gr_ip , const int gr_np , const int idim , double * ex_array_p , double * ex_array_n )
{
MPI_Status istats ;
int tag1 = 100 , tag2 = 300 ;
if( ip == gr_ip )
MPI_Send( ex_array_p , idim , MPI_DOUBLE , gr_ip + gr_np , tag1 , commw ) ;
if( ip == gr_ip + gr_np )
MPI_Recv( ex_array_p , idim , MPI_DOUBLE , gr_ip , tag1 , commw , &istats ) ;
if( ip == gr_ip + gr_np )
MPI_Send( ex_array_n , idim , MPI_DOUBLE , gr_ip , tag2 , commw ) ;
if( ip == gr_ip )
MPI_Recv( ex_array_n , idim , MPI_DOUBLE , gr_ip + gr_np , tag2 , commw , &istats ) ;
}
void grid3( double * xx , double * yy , double * zz , const int nx , const int ny , const int nz , double * X , double * Y , double * Z )
{
int ix , iy , iz , ixyz ;
for( ix = 0 ; ix < nx ; ix++)
for( iy = 0 ; iy < ny ; iy++ )
for ( iz = 0 ; iz < nz ; iz++ )
{
ixyz = iz + nz * ( iy + ny * ix ) ;
X[ ixyz ] = xx[ ix ] ;
Y[ ixyz ] = yy[ iy ] ;
Z[ ixyz ] = zz[ iz ] ;
}
}
void divide_work( const int n , const int ip , const int np , int * nstart , int * nstop )
{
int nav , nspill , i , n0 ;
nav = n / np ;
n0 = 0 ;
nspill = n - np * nav ;
* nstop = 0 ;
for( i = 0 ; i <= ip ; i++ )
{
* nstart = * nstop ;
* nstop = * nstart + nav ;
if( i < nspill )
* nstop = * nstop + 1 ;
}
}
void array_rescale( double * a , const int n , const double alpha )
{
int i ;
for( i = 0 ; i < n ; i++ )
a[ i ] = alpha * a[ i ] ;
}
void cm_initial( double * lam , double complex * z , const int m_ip , const int n_iq , const int i_p , const int i_q , const int mb , const int nb , const int p_proc , const int q_proc , const int nx , const int ny , const int nz , const double e_max , Lattice_arrays * latt_coords , double * xcm , double * ycm , double * zcm , const MPI_Comm comm , int icub)
{
int n ;
int nxyz = nx * ny * nz ;
int nhalf , jj , j , i ;
int li , lj ;
double f1 , xpart , xcm1 , ycm1 , zcm1 ;
double wf ;
xcm1 = 0. ;
ycm1 = 0. ;
zcm1 = 0. ;
xpart = 0. ;
n = 4 * nxyz ;
nhalf = 2 * nxyz ;
for( jj = nhalf ; jj < n ; jj++ )
/* construgct one vector at a time for positive eigenvalues */
{
f1 = sqrt( factor_ec( *( lam + jj ) , e_max ,icub) ) ;
if( f1 < 1.e-6 )
break ;
for( lj = 0 ; lj < n_iq ; lj++ )
{
j = i_q * nb + ( lj / nb ) * q_proc * nb + lj % nb ;
if( j == jj )
for( li = 0 ; li < m_ip ; li++ )
{
wf = pow( cabs( z[ lj * m_ip + li ] ) * f1 , 2. ) ;
i = ( i_p * mb + ( li / mb ) * p_proc * mb + li % mb ) ;
if( i > nhalf - 1 )
{
i = i % nxyz ;
xcm1 += ( latt_coords->xa[ i ] * wf ) ;
ycm1 += ( latt_coords->ya[ i ] * wf ) ;
zcm1 += ( latt_coords->za[ i ] * wf ) ;
xpart += wf ;
}
}
}
}
MPI_Allreduce( &xpart , xcm , 1 , MPI_DOUBLE , MPI_SUM , comm ) ;
xpart = * xcm ;
MPI_Allreduce( &xcm1 , xcm , 1 , MPI_DOUBLE , MPI_SUM , comm ) ;
MPI_Allreduce( &ycm1 , ycm , 1 , MPI_DOUBLE , MPI_SUM , comm ) ;
MPI_Allreduce( &zcm1 , zcm , 1 , MPI_DOUBLE , MPI_SUM , comm ) ;
* xcm /= xpart ;
* ycm /= xpart ;
* zcm /= xpart ;
}
void change_mu_eq_sp( double * amu , double * lam , double * occ , const int nwf , const double npart )
{
double * e_eq , * del2 , e_qp ;
int i , k ;
double xpart , dndmu ;
assert( e_eq = malloc( nwf * sizeof( double ) ) ) ;
assert( del2 = malloc( nwf * sizeof( double ) ) ) ;
for( i = 0 ; i < nwf ; ++i )
{
e_eq[ i ] = lam[ i ] * ( 1. - 2. * occ[ i ] ) + * amu ;
del2[ i ] = pow( lam[ i ] , 2. ) - pow( e_eq[ i ] - * amu , 2. ) ;
}
for( k = 0 ; k < 51 ; ++k )
{
xpart = ( double ) nwf ;
dndmu = 0. ;
for( i = 0 ; i < nwf ; ++i )
{
e_qp = sqrt( pow( e_eq[ i ] - * amu , 2. ) + del2[ i ] ) ;
xpart -= ( e_eq[ i ] - * amu ) / e_qp ;
dndmu += del2[ i ] / pow( e_qp , 3. ) ;
}
xpart = xpart / 2. ;
if( fabs( xpart - npart ) < 1.e-12 )
{
*amu -= 6. * ( xpart - npart ) / npart ;
break ;
}
dndmu = 1.0 / dndmu ;
dndmu = minr( 0.8 * dndmu , 3. ) ;
*amu += dndmu * ( npart - xpart ) ;
}
free( del2 ) ; free( e_eq ) ;
}
double minr( double x , double y )
{
if( x < y )
return( x ) ;
else
return( y ) ;
}
double distMass( double * rho_p, double * rho_n, double n, double z0 , double * za,int *wz ,double dxyz){
double sum1=0., sum2=0., sum1_=0., sum2_=0.;
double rho;
int i;
for(i=0;i<n;i++){
rho=rho_p[i]+rho_n[i];
if( za[i] < z0 ){
sum1_ += rho;
sum1 += (z0-za[i]*wz[i])*rho;
}
if( za[i] > z0 ){
sum2_ += rho;
sum2 += (za[i]*wz[i]-z0)*rho;
}
if( za[i]==z0 ){
sum1_ += .5*rho;
sum2_ += .5*rho;
}
}
printf("Mass1=%f Mass2=%f\n",sum1_*dxyz,sum2_*dxyz);
return( sum2/sum2_+sum1/sum1_ );
}
|
Sema.h | //===--- Sema.h - Semantic Analysis & AST Building --------------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file defines the Sema class, which performs semantic analysis and
// builds ASTs.
//
//===----------------------------------------------------------------------===//
#ifndef LLVM_CLANG_SEMA_SEMA_H
#define LLVM_CLANG_SEMA_SEMA_H
#include "clang/AST/Attr.h"
#include "clang/AST/DeclarationName.h"
#include "clang/AST/Expr.h"
#include "clang/AST/ExprObjC.h"
#include "clang/AST/ExternalASTSource.h"
#include "clang/AST/MangleNumberingContext.h"
#include "clang/AST/NSAPI.h"
#include "clang/AST/PrettyPrinter.h"
#include "clang/AST/TypeLoc.h"
#include "clang/Basic/ExpressionTraits.h"
#include "clang/Basic/LangOptions.h"
#include "clang/Basic/Module.h"
#include "clang/Basic/OpenMPKinds.h"
#include "clang/Basic/Specifiers.h"
#include "clang/Basic/TemplateKinds.h"
#include "clang/Basic/TypeTraits.h"
#include "clang/Sema/AnalysisBasedWarnings.h"
#include "clang/Sema/DeclSpec.h"
#include "clang/Sema/ExternalSemaSource.h"
#include "clang/Sema/IdentifierResolver.h"
#include "clang/Sema/LocInfoType.h"
#include "clang/Sema/ObjCMethodList.h"
#include "clang/Sema/Ownership.h"
#include "clang/Sema/Scope.h"
#include "clang/Sema/ScopeInfo.h"
#include "clang/Sema/TypoCorrection.h"
#include "clang/Sema/Weak.h"
#include "llvm/ADT/ArrayRef.h"
#include "llvm/ADT/Optional.h"
#include "llvm/ADT/SetVector.h"
#include "llvm/ADT/SmallPtrSet.h"
#include "llvm/ADT/SmallVector.h"
#include "llvm/ADT/TinyPtrVector.h"
#include <deque>
#include <memory>
#include <string>
#include <vector>
namespace llvm {
class APSInt;
template <typename ValueT> struct DenseMapInfo;
template <typename ValueT, typename ValueInfoT> class DenseSet;
class SmallBitVector;
class InlineAsmIdentifierInfo;
}
namespace clang {
class ADLResult;
class ASTConsumer;
class ASTContext;
class ASTMutationListener;
class ASTReader;
class ASTWriter;
class ArrayType;
class AttributeList;
class BlockDecl;
class CapturedDecl;
class CXXBasePath;
class CXXBasePaths;
class CXXBindTemporaryExpr;
typedef SmallVector<CXXBaseSpecifier*, 4> CXXCastPath;
class CXXConstructorDecl;
class CXXConversionDecl;
class CXXDeleteExpr;
class CXXDestructorDecl;
class CXXFieldCollector;
class CXXMemberCallExpr;
class CXXMethodDecl;
class CXXScopeSpec;
class CXXTemporary;
class CXXTryStmt;
class CallExpr;
class ClassTemplateDecl;
class ClassTemplatePartialSpecializationDecl;
class ClassTemplateSpecializationDecl;
class VarTemplatePartialSpecializationDecl;
class CodeCompleteConsumer;
class CodeCompletionAllocator;
class CodeCompletionTUInfo;
class CodeCompletionResult;
class Decl;
class DeclAccessPair;
class DeclContext;
class DeclRefExpr;
class DeclaratorDecl;
class DeducedTemplateArgument;
class DependentDiagnostic;
class DesignatedInitExpr;
class Designation;
class EnableIfAttr;
class EnumConstantDecl;
class Expr;
class ExtVectorType;
class ExternalSemaSource;
class FormatAttr;
class FriendDecl;
class FunctionDecl;
class FunctionProtoType;
class FunctionTemplateDecl;
class ImplicitConversionSequence;
class InitListExpr;
class InitializationKind;
class InitializationSequence;
class InitializedEntity;
class IntegerLiteral;
class LabelStmt;
class LambdaExpr;
class LangOptions;
class LocalInstantiationScope;
class LookupResult;
class MacroInfo;
typedef ArrayRef<std::pair<IdentifierInfo *, SourceLocation>> ModuleIdPath;
class ModuleLoader;
class MultiLevelTemplateArgumentList;
class NamedDecl;
class ObjCCategoryDecl;
class ObjCCategoryImplDecl;
class ObjCCompatibleAliasDecl;
class ObjCContainerDecl;
class ObjCImplDecl;
class ObjCImplementationDecl;
class ObjCInterfaceDecl;
class ObjCIvarDecl;
template <class T> class ObjCList;
class ObjCMessageExpr;
class ObjCMethodDecl;
class ObjCPropertyDecl;
class ObjCProtocolDecl;
class OMPThreadPrivateDecl;
class OMPClause;
class OverloadCandidateSet;
class OverloadExpr;
class ParenListExpr;
class ParmVarDecl;
class Preprocessor;
class PseudoDestructorTypeStorage;
class PseudoObjectExpr;
class QualType;
class StandardConversionSequence;
class Stmt;
class StringLiteral;
class SwitchStmt;
class TemplateArgument;
class TemplateArgumentList;
class TemplateArgumentLoc;
class TemplateDecl;
class TemplateParameterList;
class TemplatePartialOrderingContext;
class TemplateTemplateParmDecl;
class Token;
class TypeAliasDecl;
class TypedefDecl;
class TypedefNameDecl;
class TypeLoc;
class TypoCorrectionConsumer;
class UnqualifiedId;
class UnresolvedLookupExpr;
class UnresolvedMemberExpr;
class UnresolvedSetImpl;
class UnresolvedSetIterator;
class UsingDecl;
class UsingShadowDecl;
class ValueDecl;
class VarDecl;
class VarTemplateSpecializationDecl;
class VisibilityAttr;
class VisibleDeclConsumer;
class IndirectFieldDecl;
struct DeductionFailureInfo;
class TemplateSpecCandidateSet;
namespace sema {
class AccessedEntity;
class BlockScopeInfo;
class CapturedRegionScopeInfo;
class CapturingScopeInfo;
class CompoundScopeInfo;
class DelayedDiagnostic;
class DelayedDiagnosticPool;
class FunctionScopeInfo;
class LambdaScopeInfo;
class PossiblyUnreachableDiag;
class TemplateDeductionInfo;
}
namespace threadSafety {
class BeforeSet;
void threadSafetyCleanup(BeforeSet* Cache);
}
// FIXME: No way to easily map from TemplateTypeParmTypes to
// TemplateTypeParmDecls, so we have this horrible PointerUnion.
typedef std::pair<llvm::PointerUnion<const TemplateTypeParmType*, NamedDecl*>,
SourceLocation> UnexpandedParameterPack;
/// Describes whether we've seen any nullability information for the given
/// file.
struct FileNullability {
/// The first pointer declarator (of any pointer kind) in the file that does
/// not have a corresponding nullability annotation.
SourceLocation PointerLoc;
/// Which kind of pointer declarator we saw.
uint8_t PointerKind;
/// Whether we saw any type nullability annotations in the given file.
bool SawTypeNullability = false;
};
/// A mapping from file IDs to a record of whether we've seen nullability
/// information in that file.
class FileNullabilityMap {
/// A mapping from file IDs to the nullability information for each file ID.
llvm::DenseMap<FileID, FileNullability> Map;
/// A single-element cache based on the file ID.
struct {
FileID File;
FileNullability Nullability;
} Cache;
public:
FileNullability &operator[](FileID file) {
// Check the single-element cache.
if (file == Cache.File)
return Cache.Nullability;
// It's not in the single-element cache; flush the cache if we have one.
if (!Cache.File.isInvalid()) {
Map[Cache.File] = Cache.Nullability;
}
// Pull this entry into the cache.
Cache.File = file;
Cache.Nullability = Map[file];
return Cache.Nullability;
}
};
/// Sema - This implements semantic analysis and AST building for C.
class Sema {
Sema(const Sema &) = delete;
void operator=(const Sema &) = delete;
///\brief Source of additional semantic information.
ExternalSemaSource *ExternalSource;
///\brief Whether Sema has generated a multiplexer and has to delete it.
bool isMultiplexExternalSource;
static bool mightHaveNonExternalLinkage(const DeclaratorDecl *FD);
bool isVisibleSlow(const NamedDecl *D);
bool shouldLinkPossiblyHiddenDecl(const NamedDecl *Old,
const NamedDecl *New) {
// We are about to link these. It is now safe to compute the linkage of
// the new decl. If the new decl has external linkage, we will
// link it with the hidden decl (which also has external linkage) and
// it will keep having external linkage. If it has internal linkage, we
// will not link it. Since it has no previous decls, it will remain
// with internal linkage.
if (getLangOpts().ModulesHideInternalLinkage)
return isVisible(Old) || New->isExternallyVisible();
return true;
}
public:
typedef OpaquePtr<DeclGroupRef> DeclGroupPtrTy;
typedef OpaquePtr<TemplateName> TemplateTy;
typedef OpaquePtr<QualType> TypeTy;
OpenCLOptions OpenCLFeatures;
FPOptions FPFeatures;
const LangOptions &LangOpts;
Preprocessor &PP;
ASTContext &Context;
ASTConsumer &Consumer;
DiagnosticsEngine &Diags;
SourceManager &SourceMgr;
/// \brief Flag indicating whether or not to collect detailed statistics.
bool CollectStats;
/// \brief Code-completion consumer.
CodeCompleteConsumer *CodeCompleter;
/// CurContext - This is the current declaration context of parsing.
DeclContext *CurContext;
/// \brief Generally null except when we temporarily switch decl contexts,
/// like in \see ActOnObjCTemporaryExitContainerContext.
DeclContext *OriginalLexicalContext;
/// VAListTagName - The declaration name corresponding to __va_list_tag.
/// This is used as part of a hack to omit that class from ADL results.
DeclarationName VAListTagName;
/// PackContext - Manages the stack for \#pragma pack. An alignment
/// of 0 indicates default alignment.
void *PackContext; // Really a "PragmaPackStack*"
bool MSStructPragmaOn; // True when \#pragma ms_struct on
/// \brief Controls member pointer representation format under the MS ABI.
LangOptions::PragmaMSPointersToMembersKind
MSPointerToMemberRepresentationMethod;
enum PragmaVtorDispKind {
PVDK_Push, ///< #pragma vtordisp(push, mode)
PVDK_Set, ///< #pragma vtordisp(mode)
PVDK_Pop, ///< #pragma vtordisp(pop)
PVDK_Reset ///< #pragma vtordisp()
};
enum PragmaMsStackAction {
PSK_Reset, // #pragma ()
PSK_Set, // #pragma ("name")
PSK_Push, // #pragma (push[, id])
PSK_Push_Set, // #pragma (push[, id], "name")
PSK_Pop, // #pragma (pop[, id])
PSK_Pop_Set, // #pragma (pop[, id], "name")
};
/// \brief Whether to insert vtordisps prior to virtual bases in the Microsoft
/// C++ ABI. Possible values are 0, 1, and 2, which mean:
///
/// 0: Suppress all vtordisps
/// 1: Insert vtordisps in the presence of vbase overrides and non-trivial
/// structors
/// 2: Always insert vtordisps to support RTTI on partially constructed
/// objects
///
/// The stack always has at least one element in it.
SmallVector<MSVtorDispAttr::Mode, 2> VtorDispModeStack;
/// Stack of active SEH __finally scopes. Can be empty.
SmallVector<Scope*, 2> CurrentSEHFinally;
/// \brief Source location for newly created implicit MSInheritanceAttrs
SourceLocation ImplicitMSInheritanceAttrLoc;
template<typename ValueType>
struct PragmaStack {
struct Slot {
llvm::StringRef StackSlotLabel;
ValueType Value;
SourceLocation PragmaLocation;
Slot(llvm::StringRef StackSlotLabel,
ValueType Value,
SourceLocation PragmaLocation)
: StackSlotLabel(StackSlotLabel), Value(Value),
PragmaLocation(PragmaLocation) {}
};
void Act(SourceLocation PragmaLocation,
PragmaMsStackAction Action,
llvm::StringRef StackSlotLabel,
ValueType Value);
explicit PragmaStack(const ValueType &Value)
: CurrentValue(Value) {}
SmallVector<Slot, 2> Stack;
ValueType CurrentValue;
SourceLocation CurrentPragmaLocation;
};
// FIXME: We should serialize / deserialize these if they occur in a PCH (but
// we shouldn't do so if they're in a module).
PragmaStack<StringLiteral *> DataSegStack;
PragmaStack<StringLiteral *> BSSSegStack;
PragmaStack<StringLiteral *> ConstSegStack;
PragmaStack<StringLiteral *> CodeSegStack;
/// A mapping that describes the nullability we've seen in each header file.
FileNullabilityMap NullabilityMap;
/// Last section used with #pragma init_seg.
StringLiteral *CurInitSeg;
SourceLocation CurInitSegLoc;
/// VisContext - Manages the stack for \#pragma GCC visibility.
void *VisContext; // Really a "PragmaVisStack*"
/// \brief This represents the last location of a "#pragma clang optimize off"
/// directive if such a directive has not been closed by an "on" yet. If
/// optimizations are currently "on", this is set to an invalid location.
SourceLocation OptimizeOffPragmaLocation;
/// \brief Flag indicating if Sema is building a recovery call expression.
///
/// This flag is used to avoid building recovery call expressions
/// if Sema is already doing so, which would cause infinite recursions.
bool IsBuildingRecoveryCallExpr;
/// ExprNeedsCleanups - True if the current evaluation context
/// requires cleanups to be run at its conclusion.
bool ExprNeedsCleanups;
/// ExprCleanupObjects - This is the stack of objects requiring
/// cleanup that are created by the current full expression. The
/// element type here is ExprWithCleanups::Object.
SmallVector<BlockDecl*, 8> ExprCleanupObjects;
/// \brief Store a list of either DeclRefExprs or MemberExprs
/// that contain a reference to a variable (constant) that may or may not
/// be odr-used in this Expr, and we won't know until all lvalue-to-rvalue
/// and discarded value conversions have been applied to all subexpressions
/// of the enclosing full expression. This is cleared at the end of each
/// full expression.
llvm::SmallPtrSet<Expr*, 2> MaybeODRUseExprs;
/// \brief Stack containing information about each of the nested
/// function, block, and method scopes that are currently active.
///
/// This array is never empty. Clients should ignore the first
/// element, which is used to cache a single FunctionScopeInfo
/// that's used to parse every top-level function.
SmallVector<sema::FunctionScopeInfo *, 4> FunctionScopes;
typedef LazyVector<TypedefNameDecl *, ExternalSemaSource,
&ExternalSemaSource::ReadExtVectorDecls, 2, 2>
ExtVectorDeclsType;
/// ExtVectorDecls - This is a list all the extended vector types. This allows
/// us to associate a raw vector type with one of the ext_vector type names.
/// This is only necessary for issuing pretty diagnostics.
ExtVectorDeclsType ExtVectorDecls;
/// FieldCollector - Collects CXXFieldDecls during parsing of C++ classes.
std::unique_ptr<CXXFieldCollector> FieldCollector;
typedef llvm::SmallSetVector<const NamedDecl*, 16> NamedDeclSetType;
/// \brief Set containing all declared private fields that are not used.
NamedDeclSetType UnusedPrivateFields;
/// \brief Set containing all typedefs that are likely unused.
llvm::SmallSetVector<const TypedefNameDecl *, 4>
UnusedLocalTypedefNameCandidates;
/// \brief Delete-expressions to be analyzed at the end of translation unit
///
/// This list contains class members, and locations of delete-expressions
/// that could not be proven as to whether they mismatch with new-expression
/// used in initializer of the field.
typedef std::pair<SourceLocation, bool> DeleteExprLoc;
typedef llvm::SmallVector<DeleteExprLoc, 4> DeleteLocs;
llvm::MapVector<FieldDecl *, DeleteLocs> DeleteExprs;
typedef llvm::SmallPtrSet<const CXXRecordDecl*, 8> RecordDeclSetTy;
/// PureVirtualClassDiagSet - a set of class declarations which we have
/// emitted a list of pure virtual functions. Used to prevent emitting the
/// same list more than once.
std::unique_ptr<RecordDeclSetTy> PureVirtualClassDiagSet;
/// ParsingInitForAutoVars - a set of declarations with auto types for which
/// we are currently parsing the initializer.
llvm::SmallPtrSet<const Decl*, 4> ParsingInitForAutoVars;
/// \brief Look for a locally scoped extern "C" declaration by the given name.
NamedDecl *findLocallyScopedExternCDecl(DeclarationName Name);
typedef LazyVector<VarDecl *, ExternalSemaSource,
&ExternalSemaSource::ReadTentativeDefinitions, 2, 2>
TentativeDefinitionsType;
/// \brief All the tentative definitions encountered in the TU.
TentativeDefinitionsType TentativeDefinitions;
typedef LazyVector<const DeclaratorDecl *, ExternalSemaSource,
&ExternalSemaSource::ReadUnusedFileScopedDecls, 2, 2>
UnusedFileScopedDeclsType;
/// \brief The set of file scoped decls seen so far that have not been used
/// and must warn if not used. Only contains the first declaration.
UnusedFileScopedDeclsType UnusedFileScopedDecls;
typedef LazyVector<CXXConstructorDecl *, ExternalSemaSource,
&ExternalSemaSource::ReadDelegatingConstructors, 2, 2>
DelegatingCtorDeclsType;
/// \brief All the delegating constructors seen so far in the file, used for
/// cycle detection at the end of the TU.
DelegatingCtorDeclsType DelegatingCtorDecls;
/// \brief All the overriding functions seen during a class definition
/// that had their exception spec checks delayed, plus the overridden
/// function.
SmallVector<std::pair<const CXXMethodDecl*, const CXXMethodDecl*>, 2>
DelayedExceptionSpecChecks;
/// \brief All the members seen during a class definition which were both
/// explicitly defaulted and had explicitly-specified exception
/// specifications, along with the function type containing their
/// user-specified exception specification. Those exception specifications
/// were overridden with the default specifications, but we still need to
/// check whether they are compatible with the default specification, and
/// we can't do that until the nesting set of class definitions is complete.
SmallVector<std::pair<CXXMethodDecl*, const FunctionProtoType*>, 2>
DelayedDefaultedMemberExceptionSpecs;
typedef llvm::MapVector<const FunctionDecl *, LateParsedTemplate *>
LateParsedTemplateMapT;
LateParsedTemplateMapT LateParsedTemplateMap;
/// \brief Callback to the parser to parse templated functions when needed.
typedef void LateTemplateParserCB(void *P, LateParsedTemplate &LPT);
typedef void LateTemplateParserCleanupCB(void *P);
LateTemplateParserCB *LateTemplateParser;
LateTemplateParserCleanupCB *LateTemplateParserCleanup;
void *OpaqueParser;
void SetLateTemplateParser(LateTemplateParserCB *LTP,
LateTemplateParserCleanupCB *LTPCleanup,
void *P) {
LateTemplateParser = LTP;
LateTemplateParserCleanup = LTPCleanup;
OpaqueParser = P;
}
class DelayedDiagnostics;
class DelayedDiagnosticsState {
sema::DelayedDiagnosticPool *SavedPool;
friend class Sema::DelayedDiagnostics;
};
typedef DelayedDiagnosticsState ParsingDeclState;
typedef DelayedDiagnosticsState ProcessingContextState;
/// A class which encapsulates the logic for delaying diagnostics
/// during parsing and other processing.
class DelayedDiagnostics {
/// \brief The current pool of diagnostics into which delayed
/// diagnostics should go.
sema::DelayedDiagnosticPool *CurPool;
public:
DelayedDiagnostics() : CurPool(nullptr) {}
/// Adds a delayed diagnostic.
void add(const sema::DelayedDiagnostic &diag); // in DelayedDiagnostic.h
/// Determines whether diagnostics should be delayed.
bool shouldDelayDiagnostics() { return CurPool != nullptr; }
/// Returns the current delayed-diagnostics pool.
sema::DelayedDiagnosticPool *getCurrentPool() const {
return CurPool;
}
/// Enter a new scope. Access and deprecation diagnostics will be
/// collected in this pool.
DelayedDiagnosticsState push(sema::DelayedDiagnosticPool &pool) {
DelayedDiagnosticsState state;
state.SavedPool = CurPool;
CurPool = &pool;
return state;
}
/// Leave a delayed-diagnostic state that was previously pushed.
/// Do not emit any of the diagnostics. This is performed as part
/// of the bookkeeping of popping a pool "properly".
void popWithoutEmitting(DelayedDiagnosticsState state) {
CurPool = state.SavedPool;
}
/// Enter a new scope where access and deprecation diagnostics are
/// not delayed.
DelayedDiagnosticsState pushUndelayed() {
DelayedDiagnosticsState state;
state.SavedPool = CurPool;
CurPool = nullptr;
return state;
}
/// Undo a previous pushUndelayed().
void popUndelayed(DelayedDiagnosticsState state) {
assert(CurPool == nullptr);
CurPool = state.SavedPool;
}
} DelayedDiagnostics;
/// A RAII object to temporarily push a declaration context.
class ContextRAII {
private:
Sema &S;
DeclContext *SavedContext;
ProcessingContextState SavedContextState;
QualType SavedCXXThisTypeOverride;
public:
ContextRAII(Sema &S, DeclContext *ContextToPush, bool NewThisContext = true)
: S(S), SavedContext(S.CurContext),
SavedContextState(S.DelayedDiagnostics.pushUndelayed()),
SavedCXXThisTypeOverride(S.CXXThisTypeOverride)
{
assert(ContextToPush && "pushing null context");
S.CurContext = ContextToPush;
if (NewThisContext)
S.CXXThisTypeOverride = QualType();
}
void pop() {
if (!SavedContext) return;
S.CurContext = SavedContext;
S.DelayedDiagnostics.popUndelayed(SavedContextState);
S.CXXThisTypeOverride = SavedCXXThisTypeOverride;
SavedContext = nullptr;
}
~ContextRAII() {
pop();
}
};
/// \brief RAII object to handle the state changes required to synthesize
/// a function body.
class SynthesizedFunctionScope {
Sema &S;
Sema::ContextRAII SavedContext;
public:
SynthesizedFunctionScope(Sema &S, DeclContext *DC)
: S(S), SavedContext(S, DC)
{
S.PushFunctionScope();
S.PushExpressionEvaluationContext(Sema::PotentiallyEvaluated);
}
~SynthesizedFunctionScope() {
S.PopExpressionEvaluationContext();
S.PopFunctionScopeInfo();
}
};
/// WeakUndeclaredIdentifiers - Identifiers contained in
/// \#pragma weak before declared. rare. may alias another
/// identifier, declared or undeclared
llvm::MapVector<IdentifierInfo *, WeakInfo> WeakUndeclaredIdentifiers;
/// ExtnameUndeclaredIdentifiers - Identifiers contained in
/// \#pragma redefine_extname before declared. Used in Solaris system headers
/// to define functions that occur in multiple standards to call the version
/// in the currently selected standard.
llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*> ExtnameUndeclaredIdentifiers;
/// \brief Load weak undeclared identifiers from the external source.
void LoadExternalWeakUndeclaredIdentifiers();
/// WeakTopLevelDecl - Translation-unit scoped declarations generated by
/// \#pragma weak during processing of other Decls.
/// I couldn't figure out a clean way to generate these in-line, so
/// we store them here and handle separately -- which is a hack.
/// It would be best to refactor this.
SmallVector<Decl*,2> WeakTopLevelDecl;
IdentifierResolver IdResolver;
/// Translation Unit Scope - useful to Objective-C actions that need
/// to lookup file scope declarations in the "ordinary" C decl namespace.
/// For example, user-defined classes, built-in "id" type, etc.
Scope *TUScope;
/// \brief The C++ "std" namespace, where the standard library resides.
LazyDeclPtr StdNamespace;
/// \brief The C++ "std::bad_alloc" class, which is defined by the C++
/// standard library.
LazyDeclPtr StdBadAlloc;
/// \brief The C++ "std::initializer_list" template, which is defined in
/// \<initializer_list>.
ClassTemplateDecl *StdInitializerList;
/// \brief The C++ "type_info" declaration, which is defined in \<typeinfo>.
RecordDecl *CXXTypeInfoDecl;
/// \brief The MSVC "_GUID" struct, which is defined in MSVC header files.
RecordDecl *MSVCGuidDecl;
/// \brief Caches identifiers/selectors for NSFoundation APIs.
std::unique_ptr<NSAPI> NSAPIObj;
/// \brief The declaration of the Objective-C NSNumber class.
ObjCInterfaceDecl *NSNumberDecl;
/// \brief The declaration of the Objective-C NSValue class.
ObjCInterfaceDecl *NSValueDecl;
/// \brief Pointer to NSNumber type (NSNumber *).
QualType NSNumberPointer;
/// \brief Pointer to NSValue type (NSValue *).
QualType NSValuePointer;
/// \brief The Objective-C NSNumber methods used to create NSNumber literals.
ObjCMethodDecl *NSNumberLiteralMethods[NSAPI::NumNSNumberLiteralMethods];
/// \brief The declaration of the Objective-C NSString class.
ObjCInterfaceDecl *NSStringDecl;
/// \brief Pointer to NSString type (NSString *).
QualType NSStringPointer;
/// \brief The declaration of the stringWithUTF8String: method.
ObjCMethodDecl *StringWithUTF8StringMethod;
/// \brief The declaration of the valueWithBytes:objCType: method.
ObjCMethodDecl *ValueWithBytesObjCTypeMethod;
/// \brief The declaration of the Objective-C NSArray class.
ObjCInterfaceDecl *NSArrayDecl;
/// \brief Pointer to NSMutableArray type (NSMutableArray *).
QualType NSMutableArrayPointer;
/// \brief The declaration of the arrayWithObjects:count: method.
ObjCMethodDecl *ArrayWithObjectsMethod;
/// \brief The declaration of the Objective-C NSDictionary class.
ObjCInterfaceDecl *NSDictionaryDecl;
/// \brief Pointer to NSMutableDictionary type (NSMutableDictionary *).
QualType NSMutableDictionaryPointer;
/// \brief Pointer to NSMutableSet type (NSMutableSet *).
QualType NSMutableSetPointer;
/// \brief Pointer to NSCountedSet type (NSCountedSet *).
QualType NSCountedSetPointer;
/// \brief Pointer to NSMutableOrderedSet type (NSMutableOrderedSet *).
QualType NSMutableOrderedSetPointer;
/// \brief The declaration of the dictionaryWithObjects:forKeys:count: method.
ObjCMethodDecl *DictionaryWithObjectsMethod;
/// \brief id<NSCopying> type.
QualType QIDNSCopying;
/// \brief will hold 'respondsToSelector:'
Selector RespondsToSelectorSel;
/// \brief counter for internal MS Asm label names.
unsigned MSAsmLabelNameCounter;
/// A flag to remember whether the implicit forms of operator new and delete
/// have been declared.
bool GlobalNewDeleteDeclared;
/// A flag to indicate that we're in a context that permits abstract
/// references to fields. This is really a
bool AllowAbstractFieldReference;
/// \brief Describes how the expressions currently being parsed are
/// evaluated at run-time, if at all.
enum ExpressionEvaluationContext {
/// \brief The current expression and its subexpressions occur within an
/// unevaluated operand (C++11 [expr]p7), such as the subexpression of
/// \c sizeof, where the type of the expression may be significant but
/// no code will be generated to evaluate the value of the expression at
/// run time.
Unevaluated,
/// \brief The current expression occurs within an unevaluated
/// operand that unconditionally permits abstract references to
/// fields, such as a SIZE operator in MS-style inline assembly.
UnevaluatedAbstract,
/// \brief The current context is "potentially evaluated" in C++11 terms,
/// but the expression is evaluated at compile-time (like the values of
/// cases in a switch statement).
ConstantEvaluated,
/// \brief The current expression is potentially evaluated at run time,
/// which means that code may be generated to evaluate the value of the
/// expression at run time.
PotentiallyEvaluated,
/// \brief The current expression is potentially evaluated, but any
/// declarations referenced inside that expression are only used if
/// in fact the current expression is used.
///
/// This value is used when parsing default function arguments, for which
/// we would like to provide diagnostics (e.g., passing non-POD arguments
/// through varargs) but do not want to mark declarations as "referenced"
/// until the default argument is used.
PotentiallyEvaluatedIfUsed
};
/// \brief Data structure used to record current or nested
/// expression evaluation contexts.
struct ExpressionEvaluationContextRecord {
/// \brief The expression evaluation context.
ExpressionEvaluationContext Context;
/// \brief Whether the enclosing context needed a cleanup.
bool ParentNeedsCleanups;
/// \brief Whether we are in a decltype expression.
bool IsDecltype;
/// \brief The number of active cleanup objects when we entered
/// this expression evaluation context.
unsigned NumCleanupObjects;
/// \brief The number of typos encountered during this expression evaluation
/// context (i.e. the number of TypoExprs created).
unsigned NumTypos;
llvm::SmallPtrSet<Expr*, 2> SavedMaybeODRUseExprs;
/// \brief The lambdas that are present within this context, if it
/// is indeed an unevaluated context.
SmallVector<LambdaExpr *, 2> Lambdas;
/// \brief The declaration that provides context for lambda expressions
/// and block literals if the normal declaration context does not
/// suffice, e.g., in a default function argument.
Decl *ManglingContextDecl;
/// \brief The context information used to mangle lambda expressions
/// and block literals within this context.
///
/// This mangling information is allocated lazily, since most contexts
/// do not have lambda expressions or block literals.
IntrusiveRefCntPtr<MangleNumberingContext> MangleNumbering;
/// \brief If we are processing a decltype type, a set of call expressions
/// for which we have deferred checking the completeness of the return type.
SmallVector<CallExpr *, 8> DelayedDecltypeCalls;
/// \brief If we are processing a decltype type, a set of temporary binding
/// expressions for which we have deferred checking the destructor.
SmallVector<CXXBindTemporaryExpr *, 8> DelayedDecltypeBinds;
ExpressionEvaluationContextRecord(ExpressionEvaluationContext Context,
unsigned NumCleanupObjects,
bool ParentNeedsCleanups,
Decl *ManglingContextDecl,
bool IsDecltype)
: Context(Context), ParentNeedsCleanups(ParentNeedsCleanups),
IsDecltype(IsDecltype), NumCleanupObjects(NumCleanupObjects),
NumTypos(0),
ManglingContextDecl(ManglingContextDecl), MangleNumbering() { }
/// \brief Retrieve the mangling numbering context, used to consistently
/// number constructs like lambdas for mangling.
MangleNumberingContext &getMangleNumberingContext(ASTContext &Ctx);
bool isUnevaluated() const {
return Context == Unevaluated || Context == UnevaluatedAbstract;
}
};
/// A stack of expression evaluation contexts.
SmallVector<ExpressionEvaluationContextRecord, 8> ExprEvalContexts;
/// \brief Compute the mangling number context for a lambda expression or
/// block literal.
///
/// \param DC - The DeclContext containing the lambda expression or
/// block literal.
/// \param[out] ManglingContextDecl - Returns the ManglingContextDecl
/// associated with the context, if relevant.
MangleNumberingContext *getCurrentMangleNumberContext(
const DeclContext *DC,
Decl *&ManglingContextDecl);
/// SpecialMemberOverloadResult - The overloading result for a special member
/// function.
///
/// This is basically a wrapper around PointerIntPair. The lowest bits of the
/// integer are used to determine whether overload resolution succeeded.
class SpecialMemberOverloadResult : public llvm::FastFoldingSetNode {
public:
enum Kind {
NoMemberOrDeleted,
Ambiguous,
Success
};
private:
llvm::PointerIntPair<CXXMethodDecl*, 2> Pair;
public:
SpecialMemberOverloadResult(const llvm::FoldingSetNodeID &ID)
: FastFoldingSetNode(ID)
{}
CXXMethodDecl *getMethod() const { return Pair.getPointer(); }
void setMethod(CXXMethodDecl *MD) { Pair.setPointer(MD); }
Kind getKind() const { return static_cast<Kind>(Pair.getInt()); }
void setKind(Kind K) { Pair.setInt(K); }
};
/// \brief A cache of special member function overload resolution results
/// for C++ records.
llvm::FoldingSet<SpecialMemberOverloadResult> SpecialMemberCache;
/// \brief The kind of translation unit we are processing.
///
/// When we're processing a complete translation unit, Sema will perform
/// end-of-translation-unit semantic tasks (such as creating
/// initializers for tentative definitions in C) once parsing has
/// completed. Modules and precompiled headers perform different kinds of
/// checks.
TranslationUnitKind TUKind;
llvm::BumpPtrAllocator BumpAlloc;
/// \brief The number of SFINAE diagnostics that have been trapped.
unsigned NumSFINAEErrors;
typedef llvm::DenseMap<ParmVarDecl *, llvm::TinyPtrVector<ParmVarDecl *>>
UnparsedDefaultArgInstantiationsMap;
/// \brief A mapping from parameters with unparsed default arguments to the
/// set of instantiations of each parameter.
///
/// This mapping is a temporary data structure used when parsing
/// nested class templates or nested classes of class templates,
/// where we might end up instantiating an inner class before the
/// default arguments of its methods have been parsed.
UnparsedDefaultArgInstantiationsMap UnparsedDefaultArgInstantiations;
// Contains the locations of the beginning of unparsed default
// argument locations.
llvm::DenseMap<ParmVarDecl *, SourceLocation> UnparsedDefaultArgLocs;
/// UndefinedInternals - all the used, undefined objects which require a
/// definition in this translation unit.
llvm::DenseMap<NamedDecl *, SourceLocation> UndefinedButUsed;
/// Obtain a sorted list of functions that are undefined but ODR-used.
void getUndefinedButUsed(
SmallVectorImpl<std::pair<NamedDecl *, SourceLocation> > &Undefined);
/// Retrieves list of suspicious delete-expressions that will be checked at
/// the end of translation unit.
const llvm::MapVector<FieldDecl *, DeleteLocs> &
getMismatchingDeleteExpressions() const;
typedef std::pair<ObjCMethodList, ObjCMethodList> GlobalMethods;
typedef llvm::DenseMap<Selector, GlobalMethods> GlobalMethodPool;
/// Method Pool - allows efficient lookup when typechecking messages to "id".
/// We need to maintain a list, since selectors can have differing signatures
/// across classes. In Cocoa, this happens to be extremely uncommon (only 1%
/// of selectors are "overloaded").
/// At the head of the list it is recorded whether there were 0, 1, or >= 2
/// methods inside categories with a particular selector.
GlobalMethodPool MethodPool;
/// Method selectors used in a \@selector expression. Used for implementation
/// of -Wselector.
llvm::MapVector<Selector, SourceLocation> ReferencedSelectors;
/// Kinds of C++ special members.
enum CXXSpecialMember {
CXXDefaultConstructor,
CXXCopyConstructor,
CXXMoveConstructor,
CXXCopyAssignment,
CXXMoveAssignment,
CXXDestructor,
CXXInvalid
};
typedef std::pair<CXXRecordDecl*, CXXSpecialMember> SpecialMemberDecl;
/// The C++ special members which we are currently in the process of
/// declaring. If this process recursively triggers the declaration of the
/// same special member, we should act as if it is not yet declared.
llvm::SmallSet<SpecialMemberDecl, 4> SpecialMembersBeingDeclared;
void ReadMethodPool(Selector Sel);
/// Private Helper predicate to check for 'self'.
bool isSelfExpr(Expr *RExpr);
bool isSelfExpr(Expr *RExpr, const ObjCMethodDecl *Method);
/// \brief Cause the active diagnostic on the DiagosticsEngine to be
/// emitted. This is closely coupled to the SemaDiagnosticBuilder class and
/// should not be used elsewhere.
void EmitCurrentDiagnostic(unsigned DiagID);
/// Records and restores the FP_CONTRACT state on entry/exit of compound
/// statements.
class FPContractStateRAII {
public:
FPContractStateRAII(Sema& S)
: S(S), OldFPContractState(S.FPFeatures.fp_contract) {}
~FPContractStateRAII() {
S.FPFeatures.fp_contract = OldFPContractState;
}
private:
Sema& S;
bool OldFPContractState : 1;
};
void addImplicitTypedef(StringRef Name, QualType T);
public:
Sema(Preprocessor &pp, ASTContext &ctxt, ASTConsumer &consumer,
TranslationUnitKind TUKind = TU_Complete,
CodeCompleteConsumer *CompletionConsumer = nullptr);
~Sema();
/// \brief Perform initialization that occurs after the parser has been
/// initialized but before it parses anything.
void Initialize();
const LangOptions &getLangOpts() const { return LangOpts; }
OpenCLOptions &getOpenCLOptions() { return OpenCLFeatures; }
FPOptions &getFPOptions() { return FPFeatures; }
DiagnosticsEngine &getDiagnostics() const { return Diags; }
SourceManager &getSourceManager() const { return SourceMgr; }
Preprocessor &getPreprocessor() const { return PP; }
ASTContext &getASTContext() const { return Context; }
ASTConsumer &getASTConsumer() const { return Consumer; }
ASTMutationListener *getASTMutationListener() const;
ExternalSemaSource* getExternalSource() const { return ExternalSource; }
///\brief Registers an external source. If an external source already exists,
/// creates a multiplex external source and appends to it.
///
///\param[in] E - A non-null external sema source.
///
void addExternalSource(ExternalSemaSource *E);
void PrintStats() const;
/// \brief Helper class that creates diagnostics with optional
/// template instantiation stacks.
///
/// This class provides a wrapper around the basic DiagnosticBuilder
/// class that emits diagnostics. SemaDiagnosticBuilder is
/// responsible for emitting the diagnostic (as DiagnosticBuilder
/// does) and, if the diagnostic comes from inside a template
/// instantiation, printing the template instantiation stack as
/// well.
class SemaDiagnosticBuilder : public DiagnosticBuilder {
Sema &SemaRef;
unsigned DiagID;
public:
SemaDiagnosticBuilder(DiagnosticBuilder &DB, Sema &SemaRef, unsigned DiagID)
: DiagnosticBuilder(DB), SemaRef(SemaRef), DiagID(DiagID) { }
~SemaDiagnosticBuilder() {
// If we aren't active, there is nothing to do.
if (!isActive()) return;
// Otherwise, we need to emit the diagnostic. First flush the underlying
// DiagnosticBuilder data, and clear the diagnostic builder itself so it
// won't emit the diagnostic in its own destructor.
//
// This seems wasteful, in that as written the DiagnosticBuilder dtor will
// do its own needless checks to see if the diagnostic needs to be
// emitted. However, because we take care to ensure that the builder
// objects never escape, a sufficiently smart compiler will be able to
// eliminate that code.
FlushCounts();
Clear();
// Dispatch to Sema to emit the diagnostic.
SemaRef.EmitCurrentDiagnostic(DiagID);
}
/// Teach operator<< to produce an object of the correct type.
template<typename T>
friend const SemaDiagnosticBuilder &operator<<(
const SemaDiagnosticBuilder &Diag, const T &Value) {
const DiagnosticBuilder &BaseDiag = Diag;
BaseDiag << Value;
return Diag;
}
};
/// \brief Emit a diagnostic.
SemaDiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID) {
DiagnosticBuilder DB = Diags.Report(Loc, DiagID);
return SemaDiagnosticBuilder(DB, *this, DiagID);
}
/// \brief Emit a partial diagnostic.
SemaDiagnosticBuilder Diag(SourceLocation Loc, const PartialDiagnostic& PD);
/// \brief Build a partial diagnostic.
PartialDiagnostic PDiag(unsigned DiagID = 0); // in SemaInternal.h
bool findMacroSpelling(SourceLocation &loc, StringRef name);
/// \brief Get a string to suggest for zero-initialization of a type.
std::string
getFixItZeroInitializerForType(QualType T, SourceLocation Loc) const;
std::string getFixItZeroLiteralForType(QualType T, SourceLocation Loc) const;
/// \brief Calls \c Lexer::getLocForEndOfToken()
SourceLocation getLocForEndOfToken(SourceLocation Loc, unsigned Offset = 0);
/// \brief Retrieve the module loader associated with the preprocessor.
ModuleLoader &getModuleLoader() const;
void emitAndClearUnusedLocalTypedefWarnings();
void ActOnEndOfTranslationUnit();
void CheckDelegatingCtorCycles();
Scope *getScopeForContext(DeclContext *Ctx);
void PushFunctionScope();
void PushBlockScope(Scope *BlockScope, BlockDecl *Block);
sema::LambdaScopeInfo *PushLambdaScope();
/// \brief This is used to inform Sema what the current TemplateParameterDepth
/// is during Parsing. Currently it is used to pass on the depth
/// when parsing generic lambda 'auto' parameters.
void RecordParsingTemplateParameterDepth(unsigned Depth);
void PushCapturedRegionScope(Scope *RegionScope, CapturedDecl *CD,
RecordDecl *RD,
CapturedRegionKind K);
void
PopFunctionScopeInfo(const sema::AnalysisBasedWarnings::Policy *WP = nullptr,
const Decl *D = nullptr,
const BlockExpr *blkExpr = nullptr);
sema::FunctionScopeInfo *getCurFunction() const {
return FunctionScopes.back();
}
sema::FunctionScopeInfo *getEnclosingFunction() const {
if (FunctionScopes.empty())
return nullptr;
for (int e = FunctionScopes.size()-1; e >= 0; --e) {
if (isa<sema::BlockScopeInfo>(FunctionScopes[e]))
continue;
return FunctionScopes[e];
}
return nullptr;
}
template <typename ExprT>
void recordUseOfEvaluatedWeak(const ExprT *E, bool IsRead=true) {
if (!isUnevaluatedContext())
getCurFunction()->recordUseOfWeak(E, IsRead);
}
void PushCompoundScope();
void PopCompoundScope();
sema::CompoundScopeInfo &getCurCompoundScope() const;
bool hasAnyUnrecoverableErrorsInThisFunction() const;
/// \brief Retrieve the current block, if any.
sema::BlockScopeInfo *getCurBlock();
/// \brief Retrieve the current lambda scope info, if any.
sema::LambdaScopeInfo *getCurLambda();
/// \brief Retrieve the current generic lambda info, if any.
sema::LambdaScopeInfo *getCurGenericLambda();
/// \brief Retrieve the current captured region, if any.
sema::CapturedRegionScopeInfo *getCurCapturedRegion();
/// WeakTopLevelDeclDecls - access to \#pragma weak-generated Decls
SmallVectorImpl<Decl *> &WeakTopLevelDecls() { return WeakTopLevelDecl; }
void ActOnComment(SourceRange Comment);
//===--------------------------------------------------------------------===//
// Type Analysis / Processing: SemaType.cpp.
//
QualType BuildQualifiedType(QualType T, SourceLocation Loc, Qualifiers Qs,
const DeclSpec *DS = nullptr);
QualType BuildQualifiedType(QualType T, SourceLocation Loc, unsigned CVRA,
const DeclSpec *DS = nullptr);
QualType BuildPointerType(QualType T,
SourceLocation Loc, DeclarationName Entity);
QualType BuildReferenceType(QualType T, bool LValueRef,
SourceLocation Loc, DeclarationName Entity);
QualType BuildArrayType(QualType T, ArrayType::ArraySizeModifier ASM,
Expr *ArraySize, unsigned Quals,
SourceRange Brackets, DeclarationName Entity);
QualType BuildExtVectorType(QualType T, Expr *ArraySize,
SourceLocation AttrLoc);
bool CheckFunctionReturnType(QualType T, SourceLocation Loc);
unsigned deduceWeakPropertyFromType(QualType T) {
if ((getLangOpts().getGC() != LangOptions::NonGC &&
T.isObjCGCWeak()) ||
(getLangOpts().ObjCAutoRefCount &&
T.getObjCLifetime() == Qualifiers::OCL_Weak))
return ObjCDeclSpec::DQ_PR_weak;
return 0;
}
/// \brief Build a function type.
///
/// This routine checks the function type according to C++ rules and
/// under the assumption that the result type and parameter types have
/// just been instantiated from a template. It therefore duplicates
/// some of the behavior of GetTypeForDeclarator, but in a much
/// simpler form that is only suitable for this narrow use case.
///
/// \param T The return type of the function.
///
/// \param ParamTypes The parameter types of the function. This array
/// will be modified to account for adjustments to the types of the
/// function parameters.
///
/// \param Loc The location of the entity whose type involves this
/// function type or, if there is no such entity, the location of the
/// type that will have function type.
///
/// \param Entity The name of the entity that involves the function
/// type, if known.
///
/// \param EPI Extra information about the function type. Usually this will
/// be taken from an existing function with the same prototype.
///
/// \returns A suitable function type, if there are no errors. The
/// unqualified type will always be a FunctionProtoType.
/// Otherwise, returns a NULL type.
QualType BuildFunctionType(QualType T,
MutableArrayRef<QualType> ParamTypes,
SourceLocation Loc, DeclarationName Entity,
const FunctionProtoType::ExtProtoInfo &EPI);
QualType BuildMemberPointerType(QualType T, QualType Class,
SourceLocation Loc,
DeclarationName Entity);
QualType BuildBlockPointerType(QualType T,
SourceLocation Loc, DeclarationName Entity);
QualType BuildParenType(QualType T);
QualType BuildAtomicType(QualType T, SourceLocation Loc);
TypeSourceInfo *GetTypeForDeclarator(Declarator &D, Scope *S);
TypeSourceInfo *GetTypeForDeclaratorCast(Declarator &D, QualType FromTy);
TypeSourceInfo *GetTypeSourceInfoForDeclarator(Declarator &D, QualType T,
TypeSourceInfo *ReturnTypeInfo);
/// \brief Package the given type and TSI into a ParsedType.
ParsedType CreateParsedType(QualType T, TypeSourceInfo *TInfo);
DeclarationNameInfo GetNameForDeclarator(Declarator &D);
DeclarationNameInfo GetNameFromUnqualifiedId(const UnqualifiedId &Name);
static QualType GetTypeFromParser(ParsedType Ty,
TypeSourceInfo **TInfo = nullptr);
CanThrowResult canThrow(const Expr *E);
const FunctionProtoType *ResolveExceptionSpec(SourceLocation Loc,
const FunctionProtoType *FPT);
void UpdateExceptionSpec(FunctionDecl *FD,
const FunctionProtoType::ExceptionSpecInfo &ESI);
bool CheckSpecifiedExceptionType(QualType &T, const SourceRange &Range);
bool CheckDistantExceptionSpec(QualType T);
bool CheckEquivalentExceptionSpec(FunctionDecl *Old, FunctionDecl *New);
bool CheckEquivalentExceptionSpec(
const FunctionProtoType *Old, SourceLocation OldLoc,
const FunctionProtoType *New, SourceLocation NewLoc);
bool CheckEquivalentExceptionSpec(
const PartialDiagnostic &DiagID, const PartialDiagnostic & NoteID,
const FunctionProtoType *Old, SourceLocation OldLoc,
const FunctionProtoType *New, SourceLocation NewLoc,
bool *MissingExceptionSpecification = nullptr,
bool *MissingEmptyExceptionSpecification = nullptr,
bool AllowNoexceptAllMatchWithNoSpec = false,
bool IsOperatorNew = false);
bool CheckExceptionSpecSubset(
const PartialDiagnostic &DiagID, const PartialDiagnostic & NoteID,
const FunctionProtoType *Superset, SourceLocation SuperLoc,
const FunctionProtoType *Subset, SourceLocation SubLoc);
bool CheckParamExceptionSpec(const PartialDiagnostic & NoteID,
const FunctionProtoType *Target, SourceLocation TargetLoc,
const FunctionProtoType *Source, SourceLocation SourceLoc);
TypeResult ActOnTypeName(Scope *S, Declarator &D);
/// \brief The parser has parsed the context-sensitive type 'instancetype'
/// in an Objective-C message declaration. Return the appropriate type.
ParsedType ActOnObjCInstanceType(SourceLocation Loc);
/// \brief Abstract class used to diagnose incomplete types.
struct TypeDiagnoser {
bool Suppressed;
TypeDiagnoser(bool Suppressed = false) : Suppressed(Suppressed) { }
virtual void diagnose(Sema &S, SourceLocation Loc, QualType T) = 0;
virtual ~TypeDiagnoser() {}
};
static int getPrintable(int I) { return I; }
static unsigned getPrintable(unsigned I) { return I; }
static bool getPrintable(bool B) { return B; }
static const char * getPrintable(const char *S) { return S; }
static StringRef getPrintable(StringRef S) { return S; }
static const std::string &getPrintable(const std::string &S) { return S; }
static const IdentifierInfo *getPrintable(const IdentifierInfo *II) {
return II;
}
static DeclarationName getPrintable(DeclarationName N) { return N; }
static QualType getPrintable(QualType T) { return T; }
static SourceRange getPrintable(SourceRange R) { return R; }
static SourceRange getPrintable(SourceLocation L) { return L; }
static SourceRange getPrintable(const Expr *E) { return E->getSourceRange(); }
static SourceRange getPrintable(TypeLoc TL) { return TL.getSourceRange();}
template <typename... Ts> class BoundTypeDiagnoser : public TypeDiagnoser {
unsigned DiagID;
std::tuple<const Ts &...> Args;
template <std::size_t... Is>
void emit(const SemaDiagnosticBuilder &DB,
llvm::index_sequence<Is...>) const {
// Apply all tuple elements to the builder in order.
bool Dummy[] = {(DB << getPrintable(std::get<Is>(Args)))...};
(void)Dummy;
}
public:
BoundTypeDiagnoser(unsigned DiagID, const Ts &...Args)
: TypeDiagnoser(DiagID == 0), DiagID(DiagID), Args(Args...) {}
void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
if (Suppressed)
return;
const SemaDiagnosticBuilder &DB = S.Diag(Loc, DiagID);
emit(DB, llvm::index_sequence_for<Ts...>());
DB << T;
}
};
private:
bool RequireCompleteTypeImpl(SourceLocation Loc, QualType T,
TypeDiagnoser &Diagnoser);
VisibleModuleSet VisibleModules;
llvm::SmallVector<VisibleModuleSet, 16> VisibleModulesStack;
Module *CachedFakeTopLevelModule;
public:
/// \brief Get the module owning an entity.
Module *getOwningModule(Decl *Entity);
/// \brief Make a merged definition of an existing hidden definition \p ND
/// visible at the specified location.
void makeMergedDefinitionVisible(NamedDecl *ND, SourceLocation Loc);
bool isModuleVisible(Module *M) { return VisibleModules.isVisible(M); }
/// Determine whether a declaration is visible to name lookup.
bool isVisible(const NamedDecl *D) {
return !D->isHidden() || isVisibleSlow(D);
}
bool hasVisibleMergedDefinition(NamedDecl *Def);
/// Determine if \p D has a visible definition. If not, suggest a declaration
/// that should be made visible to expose the definition.
bool hasVisibleDefinition(NamedDecl *D, NamedDecl **Suggested,
bool OnlyNeedComplete = false);
bool hasVisibleDefinition(const NamedDecl *D) {
NamedDecl *Hidden;
return hasVisibleDefinition(const_cast<NamedDecl*>(D), &Hidden);
}
/// Determine if the template parameter \p D has a visible default argument.
bool
hasVisibleDefaultArgument(const NamedDecl *D,
llvm::SmallVectorImpl<Module *> *Modules = nullptr);
bool RequireCompleteType(SourceLocation Loc, QualType T,
TypeDiagnoser &Diagnoser);
bool RequireCompleteType(SourceLocation Loc, QualType T,
unsigned DiagID);
template <typename... Ts>
bool RequireCompleteType(SourceLocation Loc, QualType T, unsigned DiagID,
const Ts &...Args) {
BoundTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...);
return RequireCompleteType(Loc, T, Diagnoser);
}
bool RequireCompleteExprType(Expr *E, TypeDiagnoser &Diagnoser);
bool RequireCompleteExprType(Expr *E, unsigned DiagID);
template <typename... Ts>
bool RequireCompleteExprType(Expr *E, unsigned DiagID, const Ts &...Args) {
BoundTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...);
return RequireCompleteExprType(E, Diagnoser);
}
bool RequireLiteralType(SourceLocation Loc, QualType T,
TypeDiagnoser &Diagnoser);
bool RequireLiteralType(SourceLocation Loc, QualType T, unsigned DiagID);
template <typename... Ts>
bool RequireLiteralType(SourceLocation Loc, QualType T, unsigned DiagID,
const Ts &...Args) {
BoundTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...);
return RequireLiteralType(Loc, T, Diagnoser);
}
QualType getElaboratedType(ElaboratedTypeKeyword Keyword,
const CXXScopeSpec &SS, QualType T);
QualType BuildTypeofExprType(Expr *E, SourceLocation Loc);
/// If AsUnevaluated is false, E is treated as though it were an evaluated
/// context, such as when building a type for decltype(auto).
QualType BuildDecltypeType(Expr *E, SourceLocation Loc,
bool AsUnevaluated = true);
QualType BuildUnaryTransformType(QualType BaseType,
UnaryTransformType::UTTKind UKind,
SourceLocation Loc);
//===--------------------------------------------------------------------===//
// Symbol table / Decl tracking callbacks: SemaDecl.cpp.
//
/// List of decls defined in a function prototype. This contains EnumConstants
/// that incorrectly end up in translation unit scope because there is no
/// function to pin them on. ActOnFunctionDeclarator reads this list and patches
/// them into the FunctionDecl.
std::vector<NamedDecl*> DeclsInPrototypeScope;
DeclGroupPtrTy ConvertDeclToDeclGroup(Decl *Ptr, Decl *OwnedType = nullptr);
void DiagnoseUseOfUnimplementedSelectors();
bool isSimpleTypeSpecifier(tok::TokenKind Kind) const;
ParsedType getTypeName(const IdentifierInfo &II, SourceLocation NameLoc,
Scope *S, CXXScopeSpec *SS = nullptr,
bool isClassName = false,
bool HasTrailingDot = false,
ParsedType ObjectType = ParsedType(),
bool IsCtorOrDtorName = false,
bool WantNontrivialTypeSourceInfo = false,
IdentifierInfo **CorrectedII = nullptr);
TypeSpecifierType isTagName(IdentifierInfo &II, Scope *S);
bool isMicrosoftMissingTypename(const CXXScopeSpec *SS, Scope *S);
void DiagnoseUnknownTypeName(IdentifierInfo *&II,
SourceLocation IILoc,
Scope *S,
CXXScopeSpec *SS,
ParsedType &SuggestedType,
bool AllowClassTemplates = false);
/// \brief For compatibility with MSVC, we delay parsing of some default
/// template type arguments until instantiation time. Emits a warning and
/// returns a synthesized DependentNameType that isn't really dependent on any
/// other template arguments.
ParsedType ActOnDelayedDefaultTemplateArg(const IdentifierInfo &II,
SourceLocation NameLoc);
/// \brief Describes the result of the name lookup and resolution performed
/// by \c ClassifyName().
enum NameClassificationKind {
NC_Unknown,
NC_Error,
NC_Keyword,
NC_Type,
NC_Expression,
NC_NestedNameSpecifier,
NC_TypeTemplate,
NC_VarTemplate,
NC_FunctionTemplate
};
class NameClassification {
NameClassificationKind Kind;
ExprResult Expr;
TemplateName Template;
ParsedType Type;
const IdentifierInfo *Keyword;
explicit NameClassification(NameClassificationKind Kind) : Kind(Kind) {}
public:
NameClassification(ExprResult Expr) : Kind(NC_Expression), Expr(Expr) {}
NameClassification(ParsedType Type) : Kind(NC_Type), Type(Type) {}
NameClassification(const IdentifierInfo *Keyword)
: Kind(NC_Keyword), Keyword(Keyword) { }
static NameClassification Error() {
return NameClassification(NC_Error);
}
static NameClassification Unknown() {
return NameClassification(NC_Unknown);
}
static NameClassification NestedNameSpecifier() {
return NameClassification(NC_NestedNameSpecifier);
}
static NameClassification TypeTemplate(TemplateName Name) {
NameClassification Result(NC_TypeTemplate);
Result.Template = Name;
return Result;
}
static NameClassification VarTemplate(TemplateName Name) {
NameClassification Result(NC_VarTemplate);
Result.Template = Name;
return Result;
}
static NameClassification FunctionTemplate(TemplateName Name) {
NameClassification Result(NC_FunctionTemplate);
Result.Template = Name;
return Result;
}
NameClassificationKind getKind() const { return Kind; }
ParsedType getType() const {
assert(Kind == NC_Type);
return Type;
}
ExprResult getExpression() const {
assert(Kind == NC_Expression);
return Expr;
}
TemplateName getTemplateName() const {
assert(Kind == NC_TypeTemplate || Kind == NC_FunctionTemplate ||
Kind == NC_VarTemplate);
return Template;
}
TemplateNameKind getTemplateNameKind() const {
switch (Kind) {
case NC_TypeTemplate:
return TNK_Type_template;
case NC_FunctionTemplate:
return TNK_Function_template;
case NC_VarTemplate:
return TNK_Var_template;
default:
llvm_unreachable("unsupported name classification.");
}
}
};
/// \brief Perform name lookup on the given name, classifying it based on
/// the results of name lookup and the following token.
///
/// This routine is used by the parser to resolve identifiers and help direct
/// parsing. When the identifier cannot be found, this routine will attempt
/// to correct the typo and classify based on the resulting name.
///
/// \param S The scope in which we're performing name lookup.
///
/// \param SS The nested-name-specifier that precedes the name.
///
/// \param Name The identifier. If typo correction finds an alternative name,
/// this pointer parameter will be updated accordingly.
///
/// \param NameLoc The location of the identifier.
///
/// \param NextToken The token following the identifier. Used to help
/// disambiguate the name.
///
/// \param IsAddressOfOperand True if this name is the operand of a unary
/// address of ('&') expression, assuming it is classified as an
/// expression.
///
/// \param CCC The correction callback, if typo correction is desired.
NameClassification
ClassifyName(Scope *S, CXXScopeSpec &SS, IdentifierInfo *&Name,
SourceLocation NameLoc, const Token &NextToken,
bool IsAddressOfOperand,
std::unique_ptr<CorrectionCandidateCallback> CCC = nullptr);
Decl *ActOnDeclarator(Scope *S, Declarator &D);
NamedDecl *HandleDeclarator(Scope *S, Declarator &D,
MultiTemplateParamsArg TemplateParameterLists);
void RegisterLocallyScopedExternCDecl(NamedDecl *ND, Scope *S);
bool DiagnoseClassNameShadow(DeclContext *DC, DeclarationNameInfo Info);
bool diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC,
DeclarationName Name,
SourceLocation Loc);
void
diagnoseIgnoredQualifiers(unsigned DiagID, unsigned Quals,
SourceLocation FallbackLoc,
SourceLocation ConstQualLoc = SourceLocation(),
SourceLocation VolatileQualLoc = SourceLocation(),
SourceLocation RestrictQualLoc = SourceLocation(),
SourceLocation AtomicQualLoc = SourceLocation());
static bool adjustContextForLocalExternDecl(DeclContext *&DC);
void DiagnoseFunctionSpecifiers(const DeclSpec &DS);
void CheckShadow(Scope *S, VarDecl *D, const LookupResult& R);
void CheckShadow(Scope *S, VarDecl *D);
void CheckCastAlign(Expr *Op, QualType T, SourceRange TRange);
void handleTagNumbering(const TagDecl *Tag, Scope *TagScope);
void setTagNameForLinkagePurposes(TagDecl *TagFromDeclSpec,
TypedefNameDecl *NewTD);
void CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *D);
NamedDecl* ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC,
TypeSourceInfo *TInfo,
LookupResult &Previous);
NamedDecl* ActOnTypedefNameDecl(Scope* S, DeclContext* DC, TypedefNameDecl *D,
LookupResult &Previous, bool &Redeclaration);
NamedDecl *ActOnVariableDeclarator(Scope *S, Declarator &D, DeclContext *DC,
TypeSourceInfo *TInfo,
LookupResult &Previous,
MultiTemplateParamsArg TemplateParamLists,
bool &AddToScope);
// Returns true if the variable declaration is a redeclaration
bool CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous);
void CheckVariableDeclarationType(VarDecl *NewVD);
void CheckCompleteVariableDeclaration(VarDecl *var);
void MaybeSuggestAddingStaticToDecl(const FunctionDecl *D);
NamedDecl* ActOnFunctionDeclarator(Scope* S, Declarator& D, DeclContext* DC,
TypeSourceInfo *TInfo,
LookupResult &Previous,
MultiTemplateParamsArg TemplateParamLists,
bool &AddToScope);
bool AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD);
bool CheckConstexprFunctionDecl(const FunctionDecl *FD);
bool CheckConstexprFunctionBody(const FunctionDecl *FD, Stmt *Body);
void DiagnoseHiddenVirtualMethods(CXXMethodDecl *MD);
void FindHiddenVirtualMethods(CXXMethodDecl *MD,
SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods);
void NoteHiddenVirtualMethods(CXXMethodDecl *MD,
SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods);
// Returns true if the function declaration is a redeclaration
bool CheckFunctionDeclaration(Scope *S,
FunctionDecl *NewFD, LookupResult &Previous,
bool IsExplicitSpecialization);
void CheckMain(FunctionDecl *FD, const DeclSpec &D);
void CheckMSVCRTEntryPoint(FunctionDecl *FD);
Decl *ActOnParamDeclarator(Scope *S, Declarator &D);
ParmVarDecl *BuildParmVarDeclForTypedef(DeclContext *DC,
SourceLocation Loc,
QualType T);
ParmVarDecl *CheckParameter(DeclContext *DC, SourceLocation StartLoc,
SourceLocation NameLoc, IdentifierInfo *Name,
QualType T, TypeSourceInfo *TSInfo,
StorageClass SC);
void ActOnParamDefaultArgument(Decl *param,
SourceLocation EqualLoc,
Expr *defarg);
void ActOnParamUnparsedDefaultArgument(Decl *param,
SourceLocation EqualLoc,
SourceLocation ArgLoc);
void ActOnParamDefaultArgumentError(Decl *param, SourceLocation EqualLoc);
bool SetParamDefaultArgument(ParmVarDecl *Param, Expr *DefaultArg,
SourceLocation EqualLoc);
void AddInitializerToDecl(Decl *dcl, Expr *init, bool DirectInit,
bool TypeMayContainAuto);
void ActOnUninitializedDecl(Decl *dcl, bool TypeMayContainAuto);
void ActOnInitializerError(Decl *Dcl);
void ActOnPureSpecifier(Decl *D, SourceLocation PureSpecLoc);
void ActOnCXXForRangeDecl(Decl *D);
StmtResult ActOnCXXForRangeIdentifier(Scope *S, SourceLocation IdentLoc,
IdentifierInfo *Ident,
ParsedAttributes &Attrs,
SourceLocation AttrEnd);
void SetDeclDeleted(Decl *dcl, SourceLocation DelLoc);
void SetDeclDefaulted(Decl *dcl, SourceLocation DefaultLoc);
void FinalizeDeclaration(Decl *D);
DeclGroupPtrTy FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS,
ArrayRef<Decl *> Group);
DeclGroupPtrTy BuildDeclaratorGroup(MutableArrayRef<Decl *> Group,
bool TypeMayContainAuto = true);
/// Should be called on all declarations that might have attached
/// documentation comments.
void ActOnDocumentableDecl(Decl *D);
void ActOnDocumentableDecls(ArrayRef<Decl *> Group);
void ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D,
SourceLocation LocAfterDecls);
void CheckForFunctionRedefinition(FunctionDecl *FD,
const FunctionDecl *EffectiveDefinition =
nullptr);
Decl *ActOnStartOfFunctionDef(Scope *S, Declarator &D);
Decl *ActOnStartOfFunctionDef(Scope *S, Decl *D);
void ActOnStartOfObjCMethodDef(Scope *S, Decl *D);
bool isObjCMethodDecl(Decl *D) {
return D && isa<ObjCMethodDecl>(D);
}
/// \brief Determine whether we can delay parsing the body of a function or
/// function template until it is used, assuming we don't care about emitting
/// code for that function.
///
/// This will be \c false if we may need the body of the function in the
/// middle of parsing an expression (where it's impractical to switch to
/// parsing a different function), for instance, if it's constexpr in C++11
/// or has an 'auto' return type in C++14. These cases are essentially bugs.
bool canDelayFunctionBody(const Declarator &D);
/// \brief Determine whether we can skip parsing the body of a function
/// definition, assuming we don't care about analyzing its body or emitting
/// code for that function.
///
/// This will be \c false only if we may need the body of the function in
/// order to parse the rest of the program (for instance, if it is
/// \c constexpr in C++11 or has an 'auto' return type in C++14).
bool canSkipFunctionBody(Decl *D);
void computeNRVO(Stmt *Body, sema::FunctionScopeInfo *Scope);
Decl *ActOnFinishFunctionBody(Decl *Decl, Stmt *Body);
Decl *ActOnFinishFunctionBody(Decl *Decl, Stmt *Body, bool IsInstantiation);
Decl *ActOnSkippedFunctionBody(Decl *Decl);
void ActOnFinishInlineMethodDef(CXXMethodDecl *D);
/// ActOnFinishDelayedAttribute - Invoked when we have finished parsing an
/// attribute for which parsing is delayed.
void ActOnFinishDelayedAttribute(Scope *S, Decl *D, ParsedAttributes &Attrs);
/// \brief Diagnose any unused parameters in the given sequence of
/// ParmVarDecl pointers.
void DiagnoseUnusedParameters(ParmVarDecl * const *Begin,
ParmVarDecl * const *End);
/// \brief Diagnose whether the size of parameters or return value of a
/// function or obj-c method definition is pass-by-value and larger than a
/// specified threshold.
void DiagnoseSizeOfParametersAndReturnValue(ParmVarDecl * const *Begin,
ParmVarDecl * const *End,
QualType ReturnTy,
NamedDecl *D);
void DiagnoseInvalidJumps(Stmt *Body);
Decl *ActOnFileScopeAsmDecl(Expr *expr,
SourceLocation AsmLoc,
SourceLocation RParenLoc);
/// \brief Handle a C++11 empty-declaration and attribute-declaration.
Decl *ActOnEmptyDeclaration(Scope *S,
AttributeList *AttrList,
SourceLocation SemiLoc);
/// \brief The parser has processed a module import declaration.
///
/// \param AtLoc The location of the '@' symbol, if any.
///
/// \param ImportLoc The location of the 'import' keyword.
///
/// \param Path The module access path.
DeclResult ActOnModuleImport(SourceLocation AtLoc, SourceLocation ImportLoc,
ModuleIdPath Path);
/// \brief The parser has processed a module import translated from a
/// #include or similar preprocessing directive.
void ActOnModuleInclude(SourceLocation DirectiveLoc, Module *Mod);
/// \brief The parsed has entered a submodule.
void ActOnModuleBegin(SourceLocation DirectiveLoc, Module *Mod);
/// \brief The parser has left a submodule.
void ActOnModuleEnd(SourceLocation DirectiveLoc, Module *Mod);
/// \brief Create an implicit import of the given module at the given
/// source location, for error recovery, if possible.
///
/// This routine is typically used when an entity found by name lookup
/// is actually hidden within a module that we know about but the user
/// has forgotten to import.
void createImplicitModuleImportForErrorRecovery(SourceLocation Loc,
Module *Mod);
/// Kinds of missing import. Note, the values of these enumerators correspond
/// to %select values in diagnostics.
enum class MissingImportKind {
Declaration,
Definition,
DefaultArgument
};
/// \brief Diagnose that the specified declaration needs to be visible but
/// isn't, and suggest a module import that would resolve the problem.
void diagnoseMissingImport(SourceLocation Loc, NamedDecl *Decl,
bool NeedDefinition, bool Recover = true);
void diagnoseMissingImport(SourceLocation Loc, NamedDecl *Decl,
SourceLocation DeclLoc, ArrayRef<Module *> Modules,
MissingImportKind MIK, bool Recover);
/// \brief Retrieve a suitable printing policy.
PrintingPolicy getPrintingPolicy() const {
return getPrintingPolicy(Context, PP);
}
/// \brief Retrieve a suitable printing policy.
static PrintingPolicy getPrintingPolicy(const ASTContext &Ctx,
const Preprocessor &PP);
/// Scope actions.
void ActOnPopScope(SourceLocation Loc, Scope *S);
void ActOnTranslationUnitScope(Scope *S);
Decl *ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS,
DeclSpec &DS);
Decl *ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS,
DeclSpec &DS,
MultiTemplateParamsArg TemplateParams,
bool IsExplicitInstantiation = false);
Decl *BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS,
AccessSpecifier AS,
RecordDecl *Record,
const PrintingPolicy &Policy);
Decl *BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS,
RecordDecl *Record);
bool isAcceptableTagRedeclaration(const TagDecl *Previous,
TagTypeKind NewTag, bool isDefinition,
SourceLocation NewTagLoc,
const IdentifierInfo *Name);
enum TagUseKind {
TUK_Reference, // Reference to a tag: 'struct foo *X;'
TUK_Declaration, // Fwd decl of a tag: 'struct foo;'
TUK_Definition, // Definition of a tag: 'struct foo { int X; } Y;'
TUK_Friend // Friend declaration: 'friend struct foo;'
};
struct SkipBodyInfo {
SkipBodyInfo() : ShouldSkip(false), Previous(nullptr) {}
bool ShouldSkip;
NamedDecl *Previous;
};
Decl *ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
SourceLocation KWLoc, CXXScopeSpec &SS,
IdentifierInfo *Name, SourceLocation NameLoc,
AttributeList *Attr, AccessSpecifier AS,
SourceLocation ModulePrivateLoc,
MultiTemplateParamsArg TemplateParameterLists,
bool &OwnedDecl, bool &IsDependent,
SourceLocation ScopedEnumKWLoc,
bool ScopedEnumUsesClassTag, TypeResult UnderlyingType,
bool IsTypeSpecifier, SkipBodyInfo *SkipBody = nullptr);
Decl *ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc,
unsigned TagSpec, SourceLocation TagLoc,
CXXScopeSpec &SS,
IdentifierInfo *Name, SourceLocation NameLoc,
AttributeList *Attr,
MultiTemplateParamsArg TempParamLists);
TypeResult ActOnDependentTag(Scope *S,
unsigned TagSpec,
TagUseKind TUK,
const CXXScopeSpec &SS,
IdentifierInfo *Name,
SourceLocation TagLoc,
SourceLocation NameLoc);
void ActOnDefs(Scope *S, Decl *TagD, SourceLocation DeclStart,
IdentifierInfo *ClassName,
SmallVectorImpl<Decl *> &Decls);
Decl *ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart,
Declarator &D, Expr *BitfieldWidth);
FieldDecl *HandleField(Scope *S, RecordDecl *TagD, SourceLocation DeclStart,
Declarator &D, Expr *BitfieldWidth,
InClassInitStyle InitStyle,
AccessSpecifier AS);
MSPropertyDecl *HandleMSProperty(Scope *S, RecordDecl *TagD,
SourceLocation DeclStart,
Declarator &D, Expr *BitfieldWidth,
InClassInitStyle InitStyle,
AccessSpecifier AS,
AttributeList *MSPropertyAttr);
FieldDecl *CheckFieldDecl(DeclarationName Name, QualType T,
TypeSourceInfo *TInfo,
RecordDecl *Record, SourceLocation Loc,
bool Mutable, Expr *BitfieldWidth,
InClassInitStyle InitStyle,
SourceLocation TSSL,
AccessSpecifier AS, NamedDecl *PrevDecl,
Declarator *D = nullptr);
bool CheckNontrivialField(FieldDecl *FD);
void DiagnoseNontrivial(const CXXRecordDecl *Record, CXXSpecialMember CSM);
bool SpecialMemberIsTrivial(CXXMethodDecl *MD, CXXSpecialMember CSM,
bool Diagnose = false);
CXXSpecialMember getSpecialMember(const CXXMethodDecl *MD);
void ActOnLastBitfield(SourceLocation DeclStart,
SmallVectorImpl<Decl *> &AllIvarDecls);
Decl *ActOnIvar(Scope *S, SourceLocation DeclStart,
Declarator &D, Expr *BitfieldWidth,
tok::ObjCKeywordKind visibility);
// This is used for both record definitions and ObjC interface declarations.
void ActOnFields(Scope* S, SourceLocation RecLoc, Decl *TagDecl,
ArrayRef<Decl *> Fields,
SourceLocation LBrac, SourceLocation RBrac,
AttributeList *AttrList);
/// ActOnTagStartDefinition - Invoked when we have entered the
/// scope of a tag's definition (e.g., for an enumeration, class,
/// struct, or union).
void ActOnTagStartDefinition(Scope *S, Decl *TagDecl);
typedef void *SkippedDefinitionContext;
/// \brief Invoked when we enter a tag definition that we're skipping.
SkippedDefinitionContext ActOnTagStartSkippedDefinition(Scope *S, Decl *TD);
Decl *ActOnObjCContainerStartDefinition(Decl *IDecl);
/// ActOnStartCXXMemberDeclarations - Invoked when we have parsed a
/// C++ record definition's base-specifiers clause and are starting its
/// member declarations.
void ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagDecl,
SourceLocation FinalLoc,
bool IsFinalSpelledSealed,
SourceLocation LBraceLoc);
/// ActOnTagFinishDefinition - Invoked once we have finished parsing
/// the definition of a tag (enumeration, class, struct, or union).
void ActOnTagFinishDefinition(Scope *S, Decl *TagDecl,
SourceLocation RBraceLoc);
void ActOnTagFinishSkippedDefinition(SkippedDefinitionContext Context);
void ActOnObjCContainerFinishDefinition();
/// \brief Invoked when we must temporarily exit the objective-c container
/// scope for parsing/looking-up C constructs.
///
/// Must be followed by a call to \see ActOnObjCReenterContainerContext
void ActOnObjCTemporaryExitContainerContext(DeclContext *DC);
void ActOnObjCReenterContainerContext(DeclContext *DC);
/// ActOnTagDefinitionError - Invoked when there was an unrecoverable
/// error parsing the definition of a tag.
void ActOnTagDefinitionError(Scope *S, Decl *TagDecl);
EnumConstantDecl *CheckEnumConstant(EnumDecl *Enum,
EnumConstantDecl *LastEnumConst,
SourceLocation IdLoc,
IdentifierInfo *Id,
Expr *val);
bool CheckEnumUnderlyingType(TypeSourceInfo *TI);
bool CheckEnumRedeclaration(SourceLocation EnumLoc, bool IsScoped,
QualType EnumUnderlyingTy, const EnumDecl *Prev);
/// Determine whether the body of an anonymous enumeration should be skipped.
/// \param II The name of the first enumerator.
SkipBodyInfo shouldSkipAnonEnumBody(Scope *S, IdentifierInfo *II,
SourceLocation IILoc);
Decl *ActOnEnumConstant(Scope *S, Decl *EnumDecl, Decl *LastEnumConstant,
SourceLocation IdLoc, IdentifierInfo *Id,
AttributeList *Attrs,
SourceLocation EqualLoc, Expr *Val);
void ActOnEnumBody(SourceLocation EnumLoc, SourceLocation LBraceLoc,
SourceLocation RBraceLoc, Decl *EnumDecl,
ArrayRef<Decl *> Elements,
Scope *S, AttributeList *Attr);
DeclContext *getContainingDC(DeclContext *DC);
/// Set the current declaration context until it gets popped.
void PushDeclContext(Scope *S, DeclContext *DC);
void PopDeclContext();
/// EnterDeclaratorContext - Used when we must lookup names in the context
/// of a declarator's nested name specifier.
void EnterDeclaratorContext(Scope *S, DeclContext *DC);
void ExitDeclaratorContext(Scope *S);
/// Push the parameters of D, which must be a function, into scope.
void ActOnReenterFunctionContext(Scope* S, Decl* D);
void ActOnExitFunctionContext();
DeclContext *getFunctionLevelDeclContext();
/// getCurFunctionDecl - If inside of a function body, this returns a pointer
/// to the function decl for the function being parsed. If we're currently
/// in a 'block', this returns the containing context.
FunctionDecl *getCurFunctionDecl();
/// getCurMethodDecl - If inside of a method body, this returns a pointer to
/// the method decl for the method being parsed. If we're currently
/// in a 'block', this returns the containing context.
ObjCMethodDecl *getCurMethodDecl();
/// getCurFunctionOrMethodDecl - Return the Decl for the current ObjC method
/// or C function we're in, otherwise return null. If we're currently
/// in a 'block', this returns the containing context.
NamedDecl *getCurFunctionOrMethodDecl();
/// Add this decl to the scope shadowed decl chains.
void PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext = true);
/// \brief Make the given externally-produced declaration visible at the
/// top level scope.
///
/// \param D The externally-produced declaration to push.
///
/// \param Name The name of the externally-produced declaration.
void pushExternalDeclIntoScope(NamedDecl *D, DeclarationName Name);
/// isDeclInScope - If 'Ctx' is a function/method, isDeclInScope returns true
/// if 'D' is in Scope 'S', otherwise 'S' is ignored and isDeclInScope returns
/// true if 'D' belongs to the given declaration context.
///
/// \param AllowInlineNamespace If \c true, allow the declaration to be in the
/// enclosing namespace set of the context, rather than contained
/// directly within it.
bool isDeclInScope(NamedDecl *D, DeclContext *Ctx, Scope *S = nullptr,
bool AllowInlineNamespace = false);
/// Finds the scope corresponding to the given decl context, if it
/// happens to be an enclosing scope. Otherwise return NULL.
static Scope *getScopeForDeclContext(Scope *S, DeclContext *DC);
/// Subroutines of ActOnDeclarator().
TypedefDecl *ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
TypeSourceInfo *TInfo);
bool isIncompatibleTypedef(TypeDecl *Old, TypedefNameDecl *New);
/// Attribute merging methods. Return true if a new attribute was added.
AvailabilityAttr *mergeAvailabilityAttr(NamedDecl *D, SourceRange Range,
IdentifierInfo *Platform,
VersionTuple Introduced,
VersionTuple Deprecated,
VersionTuple Obsoleted,
bool IsUnavailable,
StringRef Message,
bool Override,
unsigned AttrSpellingListIndex);
TypeVisibilityAttr *mergeTypeVisibilityAttr(Decl *D, SourceRange Range,
TypeVisibilityAttr::VisibilityType Vis,
unsigned AttrSpellingListIndex);
VisibilityAttr *mergeVisibilityAttr(Decl *D, SourceRange Range,
VisibilityAttr::VisibilityType Vis,
unsigned AttrSpellingListIndex);
DLLImportAttr *mergeDLLImportAttr(Decl *D, SourceRange Range,
unsigned AttrSpellingListIndex);
DLLExportAttr *mergeDLLExportAttr(Decl *D, SourceRange Range,
unsigned AttrSpellingListIndex);
MSInheritanceAttr *
mergeMSInheritanceAttr(Decl *D, SourceRange Range, bool BestCase,
unsigned AttrSpellingListIndex,
MSInheritanceAttr::Spelling SemanticSpelling);
FormatAttr *mergeFormatAttr(Decl *D, SourceRange Range,
IdentifierInfo *Format, int FormatIdx,
int FirstArg, unsigned AttrSpellingListIndex);
SectionAttr *mergeSectionAttr(Decl *D, SourceRange Range, StringRef Name,
unsigned AttrSpellingListIndex);
AlwaysInlineAttr *mergeAlwaysInlineAttr(Decl *D, SourceRange Range,
IdentifierInfo *Ident,
unsigned AttrSpellingListIndex);
MinSizeAttr *mergeMinSizeAttr(Decl *D, SourceRange Range,
unsigned AttrSpellingListIndex);
OptimizeNoneAttr *mergeOptimizeNoneAttr(Decl *D, SourceRange Range,
unsigned AttrSpellingListIndex);
/// \brief Describes the kind of merge to perform for availability
/// attributes (including "deprecated", "unavailable", and "availability").
enum AvailabilityMergeKind {
/// \brief Don't merge availability attributes at all.
AMK_None,
/// \brief Merge availability attributes for a redeclaration, which requires
/// an exact match.
AMK_Redeclaration,
/// \brief Merge availability attributes for an override, which requires
/// an exact match or a weakening of constraints.
AMK_Override
};
void mergeDeclAttributes(NamedDecl *New, Decl *Old,
AvailabilityMergeKind AMK = AMK_Redeclaration);
void MergeTypedefNameDecl(TypedefNameDecl *New, LookupResult &OldDecls);
bool MergeFunctionDecl(FunctionDecl *New, NamedDecl *&Old, Scope *S,
bool MergeTypeWithOld);
bool MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old,
Scope *S, bool MergeTypeWithOld);
void mergeObjCMethodDecls(ObjCMethodDecl *New, ObjCMethodDecl *Old);
void MergeVarDecl(VarDecl *New, LookupResult &Previous);
void MergeVarDeclTypes(VarDecl *New, VarDecl *Old, bool MergeTypeWithOld);
void MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old);
bool MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old, Scope *S);
// AssignmentAction - This is used by all the assignment diagnostic functions
// to represent what is actually causing the operation
enum AssignmentAction {
AA_Assigning,
AA_Passing,
AA_Returning,
AA_Converting,
AA_Initializing,
AA_Sending,
AA_Casting,
AA_Passing_CFAudited
};
/// C++ Overloading.
enum OverloadKind {
/// This is a legitimate overload: the existing declarations are
/// functions or function templates with different signatures.
Ovl_Overload,
/// This is not an overload because the signature exactly matches
/// an existing declaration.
Ovl_Match,
/// This is not an overload because the lookup results contain a
/// non-function.
Ovl_NonFunction
};
OverloadKind CheckOverload(Scope *S,
FunctionDecl *New,
const LookupResult &OldDecls,
NamedDecl *&OldDecl,
bool IsForUsingDecl);
bool IsOverload(FunctionDecl *New, FunctionDecl *Old, bool IsForUsingDecl);
/// \brief Checks availability of the function depending on the current
/// function context.Inside an unavailable function,unavailability is ignored.
///
/// \returns true if \p FD is unavailable and current context is inside
/// an available function, false otherwise.
bool isFunctionConsideredUnavailable(FunctionDecl *FD);
ImplicitConversionSequence
TryImplicitConversion(Expr *From, QualType ToType,
bool SuppressUserConversions,
bool AllowExplicit,
bool InOverloadResolution,
bool CStyle,
bool AllowObjCWritebackConversion);
bool IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType);
bool IsFloatingPointPromotion(QualType FromType, QualType ToType);
bool IsComplexPromotion(QualType FromType, QualType ToType);
bool IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
bool InOverloadResolution,
QualType& ConvertedType, bool &IncompatibleObjC);
bool isObjCPointerConversion(QualType FromType, QualType ToType,
QualType& ConvertedType, bool &IncompatibleObjC);
bool isObjCWritebackConversion(QualType FromType, QualType ToType,
QualType &ConvertedType);
bool IsBlockPointerConversion(QualType FromType, QualType ToType,
QualType& ConvertedType);
bool FunctionParamTypesAreEqual(const FunctionProtoType *OldType,
const FunctionProtoType *NewType,
unsigned *ArgPos = nullptr);
void HandleFunctionTypeMismatch(PartialDiagnostic &PDiag,
QualType FromType, QualType ToType);
void maybeExtendBlockObject(ExprResult &E);
CastKind PrepareCastToObjCObjectPointer(ExprResult &E);
bool CheckPointerConversion(Expr *From, QualType ToType,
CastKind &Kind,
CXXCastPath& BasePath,
bool IgnoreBaseAccess);
bool IsMemberPointerConversion(Expr *From, QualType FromType, QualType ToType,
bool InOverloadResolution,
QualType &ConvertedType);
bool CheckMemberPointerConversion(Expr *From, QualType ToType,
CastKind &Kind,
CXXCastPath &BasePath,
bool IgnoreBaseAccess);
bool IsQualificationConversion(QualType FromType, QualType ToType,
bool CStyle, bool &ObjCLifetimeConversion);
bool IsNoReturnConversion(QualType FromType, QualType ToType,
QualType &ResultTy);
bool DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType);
bool isSameOrCompatibleFunctionType(CanQualType Param, CanQualType Arg);
ExprResult PerformMoveOrCopyInitialization(const InitializedEntity &Entity,
const VarDecl *NRVOCandidate,
QualType ResultType,
Expr *Value,
bool AllowNRVO = true);
bool CanPerformCopyInitialization(const InitializedEntity &Entity,
ExprResult Init);
ExprResult PerformCopyInitialization(const InitializedEntity &Entity,
SourceLocation EqualLoc,
ExprResult Init,
bool TopLevelOfInitList = false,
bool AllowExplicit = false);
ExprResult PerformObjectArgumentInitialization(Expr *From,
NestedNameSpecifier *Qualifier,
NamedDecl *FoundDecl,
CXXMethodDecl *Method);
ExprResult PerformContextuallyConvertToBool(Expr *From);
ExprResult PerformContextuallyConvertToObjCPointer(Expr *From);
/// Contexts in which a converted constant expression is required.
enum CCEKind {
CCEK_CaseValue, ///< Expression in a case label.
CCEK_Enumerator, ///< Enumerator value with fixed underlying type.
CCEK_TemplateArg, ///< Value of a non-type template parameter.
CCEK_NewExpr ///< Constant expression in a noptr-new-declarator.
};
ExprResult CheckConvertedConstantExpression(Expr *From, QualType T,
llvm::APSInt &Value, CCEKind CCE);
ExprResult CheckConvertedConstantExpression(Expr *From, QualType T,
APValue &Value, CCEKind CCE);
/// \brief Abstract base class used to perform a contextual implicit
/// conversion from an expression to any type passing a filter.
class ContextualImplicitConverter {
public:
bool Suppress;
bool SuppressConversion;
ContextualImplicitConverter(bool Suppress = false,
bool SuppressConversion = false)
: Suppress(Suppress), SuppressConversion(SuppressConversion) {}
/// \brief Determine whether the specified type is a valid destination type
/// for this conversion.
virtual bool match(QualType T) = 0;
/// \brief Emits a diagnostic complaining that the expression does not have
/// integral or enumeration type.
virtual SemaDiagnosticBuilder
diagnoseNoMatch(Sema &S, SourceLocation Loc, QualType T) = 0;
/// \brief Emits a diagnostic when the expression has incomplete class type.
virtual SemaDiagnosticBuilder
diagnoseIncomplete(Sema &S, SourceLocation Loc, QualType T) = 0;
/// \brief Emits a diagnostic when the only matching conversion function
/// is explicit.
virtual SemaDiagnosticBuilder diagnoseExplicitConv(
Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) = 0;
/// \brief Emits a note for the explicit conversion function.
virtual SemaDiagnosticBuilder
noteExplicitConv(Sema &S, CXXConversionDecl *Conv, QualType ConvTy) = 0;
/// \brief Emits a diagnostic when there are multiple possible conversion
/// functions.
virtual SemaDiagnosticBuilder
diagnoseAmbiguous(Sema &S, SourceLocation Loc, QualType T) = 0;
/// \brief Emits a note for one of the candidate conversions.
virtual SemaDiagnosticBuilder
noteAmbiguous(Sema &S, CXXConversionDecl *Conv, QualType ConvTy) = 0;
/// \brief Emits a diagnostic when we picked a conversion function
/// (for cases when we are not allowed to pick a conversion function).
virtual SemaDiagnosticBuilder diagnoseConversion(
Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) = 0;
virtual ~ContextualImplicitConverter() {}
};
class ICEConvertDiagnoser : public ContextualImplicitConverter {
bool AllowScopedEnumerations;
public:
ICEConvertDiagnoser(bool AllowScopedEnumerations,
bool Suppress, bool SuppressConversion)
: ContextualImplicitConverter(Suppress, SuppressConversion),
AllowScopedEnumerations(AllowScopedEnumerations) {}
/// Match an integral or (possibly scoped) enumeration type.
bool match(QualType T) override;
SemaDiagnosticBuilder
diagnoseNoMatch(Sema &S, SourceLocation Loc, QualType T) override {
return diagnoseNotInt(S, Loc, T);
}
/// \brief Emits a diagnostic complaining that the expression does not have
/// integral or enumeration type.
virtual SemaDiagnosticBuilder
diagnoseNotInt(Sema &S, SourceLocation Loc, QualType T) = 0;
};
/// Perform a contextual implicit conversion.
ExprResult PerformContextualImplicitConversion(
SourceLocation Loc, Expr *FromE, ContextualImplicitConverter &Converter);
enum ObjCSubscriptKind {
OS_Array,
OS_Dictionary,
OS_Error
};
ObjCSubscriptKind CheckSubscriptingKind(Expr *FromE);
// Note that LK_String is intentionally after the other literals, as
// this is used for diagnostics logic.
enum ObjCLiteralKind {
LK_Array,
LK_Dictionary,
LK_Numeric,
LK_Boxed,
LK_String,
LK_Block,
LK_None
};
ObjCLiteralKind CheckLiteralKind(Expr *FromE);
ExprResult PerformObjectMemberConversion(Expr *From,
NestedNameSpecifier *Qualifier,
NamedDecl *FoundDecl,
NamedDecl *Member);
// Members have to be NamespaceDecl* or TranslationUnitDecl*.
// TODO: make this is a typesafe union.
typedef llvm::SmallPtrSet<DeclContext *, 16> AssociatedNamespaceSet;
typedef llvm::SmallPtrSet<CXXRecordDecl *, 16> AssociatedClassSet;
void AddOverloadCandidate(FunctionDecl *Function,
DeclAccessPair FoundDecl,
ArrayRef<Expr *> Args,
OverloadCandidateSet& CandidateSet,
bool SuppressUserConversions = false,
bool PartialOverloading = false,
bool AllowExplicit = false);
void AddFunctionCandidates(const UnresolvedSetImpl &Functions,
ArrayRef<Expr *> Args,
OverloadCandidateSet &CandidateSet,
TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr,
bool SuppressUserConversions = false,
bool PartialOverloading = false);
void AddMethodCandidate(DeclAccessPair FoundDecl,
QualType ObjectType,
Expr::Classification ObjectClassification,
ArrayRef<Expr *> Args,
OverloadCandidateSet& CandidateSet,
bool SuppressUserConversion = false);
void AddMethodCandidate(CXXMethodDecl *Method,
DeclAccessPair FoundDecl,
CXXRecordDecl *ActingContext, QualType ObjectType,
Expr::Classification ObjectClassification,
ArrayRef<Expr *> Args,
OverloadCandidateSet& CandidateSet,
bool SuppressUserConversions = false,
bool PartialOverloading = false);
void AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl,
DeclAccessPair FoundDecl,
CXXRecordDecl *ActingContext,
TemplateArgumentListInfo *ExplicitTemplateArgs,
QualType ObjectType,
Expr::Classification ObjectClassification,
ArrayRef<Expr *> Args,
OverloadCandidateSet& CandidateSet,
bool SuppressUserConversions = false,
bool PartialOverloading = false);
void AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate,
DeclAccessPair FoundDecl,
TemplateArgumentListInfo *ExplicitTemplateArgs,
ArrayRef<Expr *> Args,
OverloadCandidateSet& CandidateSet,
bool SuppressUserConversions = false,
bool PartialOverloading = false);
void AddConversionCandidate(CXXConversionDecl *Conversion,
DeclAccessPair FoundDecl,
CXXRecordDecl *ActingContext,
Expr *From, QualType ToType,
OverloadCandidateSet& CandidateSet,
bool AllowObjCConversionOnExplicit);
void AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate,
DeclAccessPair FoundDecl,
CXXRecordDecl *ActingContext,
Expr *From, QualType ToType,
OverloadCandidateSet &CandidateSet,
bool AllowObjCConversionOnExplicit);
void AddSurrogateCandidate(CXXConversionDecl *Conversion,
DeclAccessPair FoundDecl,
CXXRecordDecl *ActingContext,
const FunctionProtoType *Proto,
Expr *Object, ArrayRef<Expr *> Args,
OverloadCandidateSet& CandidateSet);
void AddMemberOperatorCandidates(OverloadedOperatorKind Op,
SourceLocation OpLoc, ArrayRef<Expr *> Args,
OverloadCandidateSet& CandidateSet,
SourceRange OpRange = SourceRange());
void AddBuiltinCandidate(QualType ResultTy, QualType *ParamTys,
ArrayRef<Expr *> Args,
OverloadCandidateSet& CandidateSet,
bool IsAssignmentOperator = false,
unsigned NumContextualBoolArguments = 0);
void AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
SourceLocation OpLoc, ArrayRef<Expr *> Args,
OverloadCandidateSet& CandidateSet);
void AddArgumentDependentLookupCandidates(DeclarationName Name,
SourceLocation Loc,
ArrayRef<Expr *> Args,
TemplateArgumentListInfo *ExplicitTemplateArgs,
OverloadCandidateSet& CandidateSet,
bool PartialOverloading = false);
// Emit as a 'note' the specific overload candidate
void NoteOverloadCandidate(FunctionDecl *Fn, QualType DestType = QualType());
// Emit as a series of 'note's all template and non-templates
// identified by the expression Expr
void NoteAllOverloadCandidates(Expr* E, QualType DestType = QualType());
/// Check the enable_if expressions on the given function. Returns the first
/// failing attribute, or NULL if they were all successful.
EnableIfAttr *CheckEnableIf(FunctionDecl *Function, ArrayRef<Expr *> Args,
bool MissingImplicitThis = false);
// [PossiblyAFunctionType] --> [Return]
// NonFunctionType --> NonFunctionType
// R (A) --> R(A)
// R (*)(A) --> R (A)
// R (&)(A) --> R (A)
// R (S::*)(A) --> R (A)
QualType ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType);
FunctionDecl *
ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr,
QualType TargetType,
bool Complain,
DeclAccessPair &Found,
bool *pHadMultipleCandidates = nullptr);
FunctionDecl *
ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl,
bool Complain = false,
DeclAccessPair *Found = nullptr);
bool ResolveAndFixSingleFunctionTemplateSpecialization(
ExprResult &SrcExpr,
bool DoFunctionPointerConverion = false,
bool Complain = false,
const SourceRange& OpRangeForComplaining = SourceRange(),
QualType DestTypeForComplaining = QualType(),
unsigned DiagIDForComplaining = 0);
Expr *FixOverloadedFunctionReference(Expr *E,
DeclAccessPair FoundDecl,
FunctionDecl *Fn);
ExprResult FixOverloadedFunctionReference(ExprResult,
DeclAccessPair FoundDecl,
FunctionDecl *Fn);
void AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE,
ArrayRef<Expr *> Args,
OverloadCandidateSet &CandidateSet,
bool PartialOverloading = false);
// An enum used to represent the different possible results of building a
// range-based for loop.
enum ForRangeStatus {
FRS_Success,
FRS_NoViableFunction,
FRS_DiagnosticIssued
};
// An enum to represent whether something is dealing with a call to begin()
// or a call to end() in a range-based for loop.
enum BeginEndFunction {
BEF_begin,
BEF_end
};
ForRangeStatus BuildForRangeBeginEndCall(Scope *S, SourceLocation Loc,
SourceLocation RangeLoc,
VarDecl *Decl,
BeginEndFunction BEF,
const DeclarationNameInfo &NameInfo,
LookupResult &MemberLookup,
OverloadCandidateSet *CandidateSet,
Expr *Range, ExprResult *CallExpr);
ExprResult BuildOverloadedCallExpr(Scope *S, Expr *Fn,
UnresolvedLookupExpr *ULE,
SourceLocation LParenLoc,
MultiExprArg Args,
SourceLocation RParenLoc,
Expr *ExecConfig,
bool AllowTypoCorrection=true);
bool buildOverloadedCallSet(Scope *S, Expr *Fn, UnresolvedLookupExpr *ULE,
MultiExprArg Args, SourceLocation RParenLoc,
OverloadCandidateSet *CandidateSet,
ExprResult *Result);
ExprResult CreateOverloadedUnaryOp(SourceLocation OpLoc,
unsigned Opc,
const UnresolvedSetImpl &Fns,
Expr *input);
ExprResult CreateOverloadedBinOp(SourceLocation OpLoc,
unsigned Opc,
const UnresolvedSetImpl &Fns,
Expr *LHS, Expr *RHS);
ExprResult CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
SourceLocation RLoc,
Expr *Base,Expr *Idx);
ExprResult
BuildCallToMemberFunction(Scope *S, Expr *MemExpr,
SourceLocation LParenLoc,
MultiExprArg Args,
SourceLocation RParenLoc);
ExprResult
BuildCallToObjectOfClassType(Scope *S, Expr *Object, SourceLocation LParenLoc,
MultiExprArg Args,
SourceLocation RParenLoc);
ExprResult BuildOverloadedArrowExpr(Scope *S, Expr *Base,
SourceLocation OpLoc,
bool *NoArrowOperatorFound = nullptr);
/// CheckCallReturnType - Checks that a call expression's return type is
/// complete. Returns true on failure. The location passed in is the location
/// that best represents the call.
bool CheckCallReturnType(QualType ReturnType, SourceLocation Loc,
CallExpr *CE, FunctionDecl *FD);
/// Helpers for dealing with blocks and functions.
bool CheckParmsForFunctionDef(ParmVarDecl *const *Param,
ParmVarDecl *const *ParamEnd,
bool CheckParameterNames);
void CheckCXXDefaultArguments(FunctionDecl *FD);
void CheckExtraCXXDefaultArguments(Declarator &D);
Scope *getNonFieldDeclScope(Scope *S);
/// \name Name lookup
///
/// These routines provide name lookup that is used during semantic
/// analysis to resolve the various kinds of names (identifiers,
/// overloaded operator names, constructor names, etc.) into zero or
/// more declarations within a particular scope. The major entry
/// points are LookupName, which performs unqualified name lookup,
/// and LookupQualifiedName, which performs qualified name lookup.
///
/// All name lookup is performed based on some specific criteria,
/// which specify what names will be visible to name lookup and how
/// far name lookup should work. These criteria are important both
/// for capturing language semantics (certain lookups will ignore
/// certain names, for example) and for performance, since name
/// lookup is often a bottleneck in the compilation of C++. Name
/// lookup criteria is specified via the LookupCriteria enumeration.
///
/// The results of name lookup can vary based on the kind of name
/// lookup performed, the current language, and the translation
/// unit. In C, for example, name lookup will either return nothing
/// (no entity found) or a single declaration. In C++, name lookup
/// can additionally refer to a set of overloaded functions or
/// result in an ambiguity. All of the possible results of name
/// lookup are captured by the LookupResult class, which provides
/// the ability to distinguish among them.
//@{
/// @brief Describes the kind of name lookup to perform.
enum LookupNameKind {
/// Ordinary name lookup, which finds ordinary names (functions,
/// variables, typedefs, etc.) in C and most kinds of names
/// (functions, variables, members, types, etc.) in C++.
LookupOrdinaryName = 0,
/// Tag name lookup, which finds the names of enums, classes,
/// structs, and unions.
LookupTagName,
/// Label name lookup.
LookupLabel,
/// Member name lookup, which finds the names of
/// class/struct/union members.
LookupMemberName,
/// Look up of an operator name (e.g., operator+) for use with
/// operator overloading. This lookup is similar to ordinary name
/// lookup, but will ignore any declarations that are class members.
LookupOperatorName,
/// Look up of a name that precedes the '::' scope resolution
/// operator in C++. This lookup completely ignores operator, object,
/// function, and enumerator names (C++ [basic.lookup.qual]p1).
LookupNestedNameSpecifierName,
/// Look up a namespace name within a C++ using directive or
/// namespace alias definition, ignoring non-namespace names (C++
/// [basic.lookup.udir]p1).
LookupNamespaceName,
/// Look up all declarations in a scope with the given name,
/// including resolved using declarations. This is appropriate
/// for checking redeclarations for a using declaration.
LookupUsingDeclName,
/// Look up an ordinary name that is going to be redeclared as a
/// name with linkage. This lookup ignores any declarations that
/// are outside of the current scope unless they have linkage. See
/// C99 6.2.2p4-5 and C++ [basic.link]p6.
LookupRedeclarationWithLinkage,
/// Look up a friend of a local class. This lookup does not look
/// outside the innermost non-class scope. See C++11 [class.friend]p11.
LookupLocalFriendName,
/// Look up the name of an Objective-C protocol.
LookupObjCProtocolName,
/// Look up implicit 'self' parameter of an objective-c method.
LookupObjCImplicitSelfParam,
/// \brief Look up any declaration with any name.
LookupAnyName
};
/// \brief Specifies whether (or how) name lookup is being performed for a
/// redeclaration (vs. a reference).
enum RedeclarationKind {
/// \brief The lookup is a reference to this name that is not for the
/// purpose of redeclaring the name.
NotForRedeclaration = 0,
/// \brief The lookup results will be used for redeclaration of a name,
/// if an entity by that name already exists.
ForRedeclaration
};
/// \brief The possible outcomes of name lookup for a literal operator.
enum LiteralOperatorLookupResult {
/// \brief The lookup resulted in an error.
LOLR_Error,
/// \brief The lookup found a single 'cooked' literal operator, which
/// expects a normal literal to be built and passed to it.
LOLR_Cooked,
/// \brief The lookup found a single 'raw' literal operator, which expects
/// a string literal containing the spelling of the literal token.
LOLR_Raw,
/// \brief The lookup found an overload set of literal operator templates,
/// which expect the characters of the spelling of the literal token to be
/// passed as a non-type template argument pack.
LOLR_Template,
/// \brief The lookup found an overload set of literal operator templates,
/// which expect the character type and characters of the spelling of the
/// string literal token to be passed as template arguments.
LOLR_StringTemplate
};
SpecialMemberOverloadResult *LookupSpecialMember(CXXRecordDecl *D,
CXXSpecialMember SM,
bool ConstArg,
bool VolatileArg,
bool RValueThis,
bool ConstThis,
bool VolatileThis);
typedef std::function<void(const TypoCorrection &)> TypoDiagnosticGenerator;
typedef std::function<ExprResult(Sema &, TypoExpr *, TypoCorrection)>
TypoRecoveryCallback;
private:
bool CppLookupName(LookupResult &R, Scope *S);
struct TypoExprState {
std::unique_ptr<TypoCorrectionConsumer> Consumer;
TypoDiagnosticGenerator DiagHandler;
TypoRecoveryCallback RecoveryHandler;
TypoExprState();
TypoExprState(TypoExprState&& other) LLVM_NOEXCEPT;
TypoExprState& operator=(TypoExprState&& other) LLVM_NOEXCEPT;
};
/// \brief The set of unhandled TypoExprs and their associated state.
llvm::MapVector<TypoExpr *, TypoExprState> DelayedTypos;
/// \brief Creates a new TypoExpr AST node.
TypoExpr *createDelayedTypo(std::unique_ptr<TypoCorrectionConsumer> TCC,
TypoDiagnosticGenerator TDG,
TypoRecoveryCallback TRC);
// \brief The set of known/encountered (unique, canonicalized) NamespaceDecls.
//
// The boolean value will be true to indicate that the namespace was loaded
// from an AST/PCH file, or false otherwise.
llvm::MapVector<NamespaceDecl*, bool> KnownNamespaces;
/// \brief Whether we have already loaded known namespaces from an extenal
/// source.
bool LoadedExternalKnownNamespaces;
/// \brief Helper for CorrectTypo and CorrectTypoDelayed used to create and
/// populate a new TypoCorrectionConsumer. Returns nullptr if typo correction
/// should be skipped entirely.
std::unique_ptr<TypoCorrectionConsumer>
makeTypoCorrectionConsumer(const DeclarationNameInfo &Typo,
Sema::LookupNameKind LookupKind, Scope *S,
CXXScopeSpec *SS,
std::unique_ptr<CorrectionCandidateCallback> CCC,
DeclContext *MemberContext, bool EnteringContext,
const ObjCObjectPointerType *OPT,
bool ErrorRecovery);
public:
const TypoExprState &getTypoExprState(TypoExpr *TE) const;
/// \brief Clears the state of the given TypoExpr.
void clearDelayedTypo(TypoExpr *TE);
/// \brief Look up a name, looking for a single declaration. Return
/// null if the results were absent, ambiguous, or overloaded.
///
/// It is preferable to use the elaborated form and explicitly handle
/// ambiguity and overloaded.
NamedDecl *LookupSingleName(Scope *S, DeclarationName Name,
SourceLocation Loc,
LookupNameKind NameKind,
RedeclarationKind Redecl
= NotForRedeclaration);
bool LookupName(LookupResult &R, Scope *S,
bool AllowBuiltinCreation = false);
bool LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx,
bool InUnqualifiedLookup = false);
bool LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx,
CXXScopeSpec &SS);
bool LookupParsedName(LookupResult &R, Scope *S, CXXScopeSpec *SS,
bool AllowBuiltinCreation = false,
bool EnteringContext = false);
ObjCProtocolDecl *LookupProtocol(IdentifierInfo *II, SourceLocation IdLoc,
RedeclarationKind Redecl
= NotForRedeclaration);
bool LookupInSuper(LookupResult &R, CXXRecordDecl *Class);
void LookupOverloadedOperatorName(OverloadedOperatorKind Op, Scope *S,
QualType T1, QualType T2,
UnresolvedSetImpl &Functions);
void addOverloadedOperatorToUnresolvedSet(UnresolvedSetImpl &Functions,
DeclAccessPair Operator,
QualType T1, QualType T2);
LabelDecl *LookupOrCreateLabel(IdentifierInfo *II, SourceLocation IdentLoc,
SourceLocation GnuLabelLoc = SourceLocation());
DeclContextLookupResult LookupConstructors(CXXRecordDecl *Class);
CXXConstructorDecl *LookupDefaultConstructor(CXXRecordDecl *Class);
CXXConstructorDecl *LookupCopyingConstructor(CXXRecordDecl *Class,
unsigned Quals);
CXXMethodDecl *LookupCopyingAssignment(CXXRecordDecl *Class, unsigned Quals,
bool RValueThis, unsigned ThisQuals);
CXXConstructorDecl *LookupMovingConstructor(CXXRecordDecl *Class,
unsigned Quals);
CXXMethodDecl *LookupMovingAssignment(CXXRecordDecl *Class, unsigned Quals,
bool RValueThis, unsigned ThisQuals);
CXXDestructorDecl *LookupDestructor(CXXRecordDecl *Class);
bool checkLiteralOperatorId(const CXXScopeSpec &SS, const UnqualifiedId &Id);
LiteralOperatorLookupResult LookupLiteralOperator(Scope *S, LookupResult &R,
ArrayRef<QualType> ArgTys,
bool AllowRaw,
bool AllowTemplate,
bool AllowStringTemplate);
bool isKnownName(StringRef name);
void ArgumentDependentLookup(DeclarationName Name, SourceLocation Loc,
ArrayRef<Expr *> Args, ADLResult &Functions);
void LookupVisibleDecls(Scope *S, LookupNameKind Kind,
VisibleDeclConsumer &Consumer,
bool IncludeGlobalScope = true);
void LookupVisibleDecls(DeclContext *Ctx, LookupNameKind Kind,
VisibleDeclConsumer &Consumer,
bool IncludeGlobalScope = true);
enum CorrectTypoKind {
CTK_NonError, // CorrectTypo used in a non error recovery situation.
CTK_ErrorRecovery // CorrectTypo used in normal error recovery.
};
TypoCorrection CorrectTypo(const DeclarationNameInfo &Typo,
Sema::LookupNameKind LookupKind,
Scope *S, CXXScopeSpec *SS,
std::unique_ptr<CorrectionCandidateCallback> CCC,
CorrectTypoKind Mode,
DeclContext *MemberContext = nullptr,
bool EnteringContext = false,
const ObjCObjectPointerType *OPT = nullptr,
bool RecordFailure = true);
TypoExpr *CorrectTypoDelayed(const DeclarationNameInfo &Typo,
Sema::LookupNameKind LookupKind, Scope *S,
CXXScopeSpec *SS,
std::unique_ptr<CorrectionCandidateCallback> CCC,
TypoDiagnosticGenerator TDG,
TypoRecoveryCallback TRC, CorrectTypoKind Mode,
DeclContext *MemberContext = nullptr,
bool EnteringContext = false,
const ObjCObjectPointerType *OPT = nullptr);
/// \brief Process any TypoExprs in the given Expr and its children,
/// generating diagnostics as appropriate and returning a new Expr if there
/// were typos that were all successfully corrected and ExprError if one or
/// more typos could not be corrected.
///
/// \param E The Expr to check for TypoExprs.
///
/// \param InitDecl A VarDecl to avoid because the Expr being corrected is its
/// initializer.
///
/// \param Filter A function applied to a newly rebuilt Expr to determine if
/// it is an acceptable/usable result from a single combination of typo
/// corrections. As long as the filter returns ExprError, different
/// combinations of corrections will be tried until all are exhausted.
ExprResult
CorrectDelayedTyposInExpr(Expr *E, VarDecl *InitDecl = nullptr,
llvm::function_ref<ExprResult(Expr *)> Filter =
[](Expr *E) -> ExprResult { return E; });
ExprResult
CorrectDelayedTyposInExpr(Expr *E,
llvm::function_ref<ExprResult(Expr *)> Filter) {
return CorrectDelayedTyposInExpr(E, nullptr, Filter);
}
ExprResult
CorrectDelayedTyposInExpr(ExprResult ER, VarDecl *InitDecl = nullptr,
llvm::function_ref<ExprResult(Expr *)> Filter =
[](Expr *E) -> ExprResult { return E; }) {
return ER.isInvalid() ? ER : CorrectDelayedTyposInExpr(ER.get(), Filter);
}
ExprResult
CorrectDelayedTyposInExpr(ExprResult ER,
llvm::function_ref<ExprResult(Expr *)> Filter) {
return CorrectDelayedTyposInExpr(ER, nullptr, Filter);
}
void diagnoseTypo(const TypoCorrection &Correction,
const PartialDiagnostic &TypoDiag,
bool ErrorRecovery = true);
void diagnoseTypo(const TypoCorrection &Correction,
const PartialDiagnostic &TypoDiag,
const PartialDiagnostic &PrevNote,
bool ErrorRecovery = true);
void FindAssociatedClassesAndNamespaces(SourceLocation InstantiationLoc,
ArrayRef<Expr *> Args,
AssociatedNamespaceSet &AssociatedNamespaces,
AssociatedClassSet &AssociatedClasses);
void FilterLookupForScope(LookupResult &R, DeclContext *Ctx, Scope *S,
bool ConsiderLinkage, bool AllowInlineNamespace);
void DiagnoseAmbiguousLookup(LookupResult &Result);
//@}
ObjCInterfaceDecl *getObjCInterfaceDecl(IdentifierInfo *&Id,
SourceLocation IdLoc,
bool TypoCorrection = false);
NamedDecl *LazilyCreateBuiltin(IdentifierInfo *II, unsigned ID,
Scope *S, bool ForRedeclaration,
SourceLocation Loc);
NamedDecl *ImplicitlyDefineFunction(SourceLocation Loc, IdentifierInfo &II,
Scope *S);
void AddKnownFunctionAttributes(FunctionDecl *FD);
// More parsing and symbol table subroutines.
void ProcessPragmaWeak(Scope *S, Decl *D);
// Decl attributes - this routine is the top level dispatcher.
void ProcessDeclAttributes(Scope *S, Decl *D, const Declarator &PD);
void ProcessDeclAttributeList(Scope *S, Decl *D, const AttributeList *AL,
bool IncludeCXX11Attributes = true);
bool ProcessAccessDeclAttributeList(AccessSpecDecl *ASDecl,
const AttributeList *AttrList);
void checkUnusedDeclAttributes(Declarator &D);
/// Determine if type T is a valid subject for a nonnull and similar
/// attributes. By default, we look through references (the behavior used by
/// nonnull), but if the second parameter is true, then we treat a reference
/// type as valid.
bool isValidPointerAttrType(QualType T, bool RefOkay = false);
bool CheckRegparmAttr(const AttributeList &attr, unsigned &value);
bool CheckCallingConvAttr(const AttributeList &attr, CallingConv &CC,
const FunctionDecl *FD = nullptr);
bool CheckNoReturnAttr(const AttributeList &attr);
bool checkStringLiteralArgumentAttr(const AttributeList &Attr,
unsigned ArgNum, StringRef &Str,
SourceLocation *ArgLocation = nullptr);
bool checkSectionName(SourceLocation LiteralLoc, StringRef Str);
void checkTargetAttr(SourceLocation LiteralLoc, StringRef Str);
bool checkMSInheritanceAttrOnDefinition(
CXXRecordDecl *RD, SourceRange Range, bool BestCase,
MSInheritanceAttr::Spelling SemanticSpelling);
void CheckAlignasUnderalignment(Decl *D);
/// Adjust the calling convention of a method to be the ABI default if it
/// wasn't specified explicitly. This handles method types formed from
/// function type typedefs and typename template arguments.
void adjustMemberFunctionCC(QualType &T, bool IsStatic);
// Check if there is an explicit attribute, but only look through parens.
// The intent is to look for an attribute on the current declarator, but not
// one that came from a typedef.
bool hasExplicitCallingConv(QualType &T);
/// Get the outermost AttributedType node that sets a calling convention.
/// Valid types should not have multiple attributes with different CCs.
const AttributedType *getCallingConvAttributedType(QualType T) const;
/// Check whether a nullability type specifier can be added to the given
/// type.
///
/// \param type The type to which the nullability specifier will be
/// added. On success, this type will be updated appropriately.
///
/// \param nullability The nullability specifier to add.
///
/// \param nullabilityLoc The location of the nullability specifier.
///
/// \param isContextSensitive Whether this nullability specifier was
/// written as a context-sensitive keyword (in an Objective-C
/// method) or an Objective-C property attribute, rather than as an
/// underscored type specifier.
///
/// \returns true if nullability cannot be applied, false otherwise.
bool checkNullabilityTypeSpecifier(QualType &type, NullabilityKind nullability,
SourceLocation nullabilityLoc,
bool isContextSensitive);
/// \brief Stmt attributes - this routine is the top level dispatcher.
StmtResult ProcessStmtAttributes(Stmt *Stmt, AttributeList *Attrs,
SourceRange Range);
void WarnConflictingTypedMethods(ObjCMethodDecl *Method,
ObjCMethodDecl *MethodDecl,
bool IsProtocolMethodDecl);
void CheckConflictingOverridingMethod(ObjCMethodDecl *Method,
ObjCMethodDecl *Overridden,
bool IsProtocolMethodDecl);
/// WarnExactTypedMethods - This routine issues a warning if method
/// implementation declaration matches exactly that of its declaration.
void WarnExactTypedMethods(ObjCMethodDecl *Method,
ObjCMethodDecl *MethodDecl,
bool IsProtocolMethodDecl);
typedef llvm::SmallPtrSet<Selector, 8> SelectorSet;
typedef llvm::DenseMap<Selector, ObjCMethodDecl*> ProtocolsMethodsMap;
/// CheckImplementationIvars - This routine checks if the instance variables
/// listed in the implelementation match those listed in the interface.
void CheckImplementationIvars(ObjCImplementationDecl *ImpDecl,
ObjCIvarDecl **Fields, unsigned nIvars,
SourceLocation Loc);
/// ImplMethodsVsClassMethods - This is main routine to warn if any method
/// remains unimplemented in the class or category \@implementation.
void ImplMethodsVsClassMethods(Scope *S, ObjCImplDecl* IMPDecl,
ObjCContainerDecl* IDecl,
bool IncompleteImpl = false);
/// DiagnoseUnimplementedProperties - This routine warns on those properties
/// which must be implemented by this implementation.
void DiagnoseUnimplementedProperties(Scope *S, ObjCImplDecl* IMPDecl,
ObjCContainerDecl *CDecl,
bool SynthesizeProperties);
/// Diagnose any null-resettable synthesized setters.
void diagnoseNullResettableSynthesizedSetters(const ObjCImplDecl *impDecl);
/// DefaultSynthesizeProperties - This routine default synthesizes all
/// properties which must be synthesized in the class's \@implementation.
void DefaultSynthesizeProperties (Scope *S, ObjCImplDecl* IMPDecl,
ObjCInterfaceDecl *IDecl);
void DefaultSynthesizeProperties(Scope *S, Decl *D);
/// IvarBacksCurrentMethodAccessor - This routine returns 'true' if 'IV' is
/// an ivar synthesized for 'Method' and 'Method' is a property accessor
/// declared in class 'IFace'.
bool IvarBacksCurrentMethodAccessor(ObjCInterfaceDecl *IFace,
ObjCMethodDecl *Method, ObjCIvarDecl *IV);
/// DiagnoseUnusedBackingIvarInAccessor - Issue an 'unused' warning if ivar which
/// backs the property is not used in the property's accessor.
void DiagnoseUnusedBackingIvarInAccessor(Scope *S,
const ObjCImplementationDecl *ImplD);
/// GetIvarBackingPropertyAccessor - If method is a property setter/getter and
/// it property has a backing ivar, returns this ivar; otherwise, returns NULL.
/// It also returns ivar's property on success.
ObjCIvarDecl *GetIvarBackingPropertyAccessor(const ObjCMethodDecl *Method,
const ObjCPropertyDecl *&PDecl) const;
/// Called by ActOnProperty to handle \@property declarations in
/// class extensions.
ObjCPropertyDecl *HandlePropertyInClassExtension(Scope *S,
SourceLocation AtLoc,
SourceLocation LParenLoc,
FieldDeclarator &FD,
Selector GetterSel,
Selector SetterSel,
const bool isAssign,
const bool isReadWrite,
const unsigned Attributes,
const unsigned AttributesAsWritten,
bool *isOverridingProperty,
QualType T,
TypeSourceInfo *TSI,
tok::ObjCKeywordKind MethodImplKind);
/// Called by ActOnProperty and HandlePropertyInClassExtension to
/// handle creating the ObjcPropertyDecl for a category or \@interface.
ObjCPropertyDecl *CreatePropertyDecl(Scope *S,
ObjCContainerDecl *CDecl,
SourceLocation AtLoc,
SourceLocation LParenLoc,
FieldDeclarator &FD,
Selector GetterSel,
Selector SetterSel,
const bool isAssign,
const bool isReadWrite,
const unsigned Attributes,
const unsigned AttributesAsWritten,
QualType T,
TypeSourceInfo *TSI,
tok::ObjCKeywordKind MethodImplKind,
DeclContext *lexicalDC = nullptr);
/// AtomicPropertySetterGetterRules - This routine enforces the rule (via
/// warning) when atomic property has one but not the other user-declared
/// setter or getter.
void AtomicPropertySetterGetterRules(ObjCImplDecl* IMPDecl,
ObjCContainerDecl* IDecl);
void DiagnoseOwningPropertyGetterSynthesis(const ObjCImplementationDecl *D);
void DiagnoseMissingDesignatedInitOverrides(
const ObjCImplementationDecl *ImplD,
const ObjCInterfaceDecl *IFD);
void DiagnoseDuplicateIvars(ObjCInterfaceDecl *ID, ObjCInterfaceDecl *SID);
enum MethodMatchStrategy {
MMS_loose,
MMS_strict
};
/// MatchTwoMethodDeclarations - Checks if two methods' type match and returns
/// true, or false, accordingly.
bool MatchTwoMethodDeclarations(const ObjCMethodDecl *Method,
const ObjCMethodDecl *PrevMethod,
MethodMatchStrategy strategy = MMS_strict);
/// MatchAllMethodDeclarations - Check methods declaraed in interface or
/// or protocol against those declared in their implementations.
void MatchAllMethodDeclarations(const SelectorSet &InsMap,
const SelectorSet &ClsMap,
SelectorSet &InsMapSeen,
SelectorSet &ClsMapSeen,
ObjCImplDecl* IMPDecl,
ObjCContainerDecl* IDecl,
bool &IncompleteImpl,
bool ImmediateClass,
bool WarnCategoryMethodImpl=false);
/// CheckCategoryVsClassMethodMatches - Checks that methods implemented in
/// category matches with those implemented in its primary class and
/// warns each time an exact match is found.
void CheckCategoryVsClassMethodMatches(ObjCCategoryImplDecl *CatIMP);
/// \brief Add the given method to the list of globally-known methods.
void addMethodToGlobalList(ObjCMethodList *List, ObjCMethodDecl *Method);
private:
/// AddMethodToGlobalPool - Add an instance or factory method to the global
/// pool. See descriptoin of AddInstanceMethodToGlobalPool.
void AddMethodToGlobalPool(ObjCMethodDecl *Method, bool impl, bool instance);
/// LookupMethodInGlobalPool - Returns the instance or factory method and
/// optionally warns if there are multiple signatures.
ObjCMethodDecl *LookupMethodInGlobalPool(Selector Sel, SourceRange R,
bool receiverIdOrClass,
bool instance);
public:
/// \brief - Returns instance or factory methods in global method pool for
/// given selector. If no such method or only one method found, function returns
/// false; otherwise, it returns true
bool CollectMultipleMethodsInGlobalPool(Selector Sel,
SmallVectorImpl<ObjCMethodDecl*>& Methods,
bool instance);
bool AreMultipleMethodsInGlobalPool(Selector Sel, ObjCMethodDecl *BestMethod,
SourceRange R,
bool receiverIdOrClass);
void DiagnoseMultipleMethodInGlobalPool(SmallVectorImpl<ObjCMethodDecl*> &Methods,
Selector Sel, SourceRange R,
bool receiverIdOrClass);
private:
/// \brief - Returns a selector which best matches given argument list or
/// nullptr if none could be found
ObjCMethodDecl *SelectBestMethod(Selector Sel, MultiExprArg Args,
bool IsInstance);
/// \brief Record the typo correction failure and return an empty correction.
TypoCorrection FailedCorrection(IdentifierInfo *Typo, SourceLocation TypoLoc,
bool RecordFailure = true) {
if (RecordFailure)
TypoCorrectionFailures[Typo].insert(TypoLoc);
return TypoCorrection();
}
public:
/// AddInstanceMethodToGlobalPool - All instance methods in a translation
/// unit are added to a global pool. This allows us to efficiently associate
/// a selector with a method declaraation for purposes of typechecking
/// messages sent to "id" (where the class of the object is unknown).
void AddInstanceMethodToGlobalPool(ObjCMethodDecl *Method, bool impl=false) {
AddMethodToGlobalPool(Method, impl, /*instance*/true);
}
/// AddFactoryMethodToGlobalPool - Same as above, but for factory methods.
void AddFactoryMethodToGlobalPool(ObjCMethodDecl *Method, bool impl=false) {
AddMethodToGlobalPool(Method, impl, /*instance*/false);
}
/// AddAnyMethodToGlobalPool - Add any method, instance or factory to global
/// pool.
void AddAnyMethodToGlobalPool(Decl *D);
/// LookupInstanceMethodInGlobalPool - Returns the method and warns if
/// there are multiple signatures.
ObjCMethodDecl *LookupInstanceMethodInGlobalPool(Selector Sel, SourceRange R,
bool receiverIdOrClass=false) {
return LookupMethodInGlobalPool(Sel, R, receiverIdOrClass,
/*instance*/true);
}
/// LookupFactoryMethodInGlobalPool - Returns the method and warns if
/// there are multiple signatures.
ObjCMethodDecl *LookupFactoryMethodInGlobalPool(Selector Sel, SourceRange R,
bool receiverIdOrClass=false) {
return LookupMethodInGlobalPool(Sel, R, receiverIdOrClass,
/*instance*/false);
}
const ObjCMethodDecl *SelectorsForTypoCorrection(Selector Sel,
QualType ObjectType=QualType());
/// LookupImplementedMethodInGlobalPool - Returns the method which has an
/// implementation.
ObjCMethodDecl *LookupImplementedMethodInGlobalPool(Selector Sel);
/// CollectIvarsToConstructOrDestruct - Collect those ivars which require
/// initialization.
void CollectIvarsToConstructOrDestruct(ObjCInterfaceDecl *OI,
SmallVectorImpl<ObjCIvarDecl*> &Ivars);
//===--------------------------------------------------------------------===//
// Statement Parsing Callbacks: SemaStmt.cpp.
public:
class FullExprArg {
public:
FullExprArg(Sema &actions) : E(nullptr) { }
ExprResult release() {
return E;
}
Expr *get() const { return E; }
Expr *operator->() {
return E;
}
private:
// FIXME: No need to make the entire Sema class a friend when it's just
// Sema::MakeFullExpr that needs access to the constructor below.
friend class Sema;
explicit FullExprArg(Expr *expr) : E(expr) {}
Expr *E;
};
FullExprArg MakeFullExpr(Expr *Arg) {
return MakeFullExpr(Arg, Arg ? Arg->getExprLoc() : SourceLocation());
}
FullExprArg MakeFullExpr(Expr *Arg, SourceLocation CC) {
return FullExprArg(ActOnFinishFullExpr(Arg, CC).get());
}
FullExprArg MakeFullDiscardedValueExpr(Expr *Arg) {
ExprResult FE =
ActOnFinishFullExpr(Arg, Arg ? Arg->getExprLoc() : SourceLocation(),
/*DiscardedValue*/ true);
return FullExprArg(FE.get());
}
StmtResult ActOnExprStmt(ExprResult Arg);
StmtResult ActOnExprStmtError();
StmtResult ActOnNullStmt(SourceLocation SemiLoc,
bool HasLeadingEmptyMacro = false);
void ActOnStartOfCompoundStmt();
void ActOnFinishOfCompoundStmt();
StmtResult ActOnCompoundStmt(SourceLocation L, SourceLocation R,
ArrayRef<Stmt *> Elts, bool isStmtExpr);
/// \brief A RAII object to enter scope of a compound statement.
class CompoundScopeRAII {
public:
CompoundScopeRAII(Sema &S): S(S) {
S.ActOnStartOfCompoundStmt();
}
~CompoundScopeRAII() {
S.ActOnFinishOfCompoundStmt();
}
private:
Sema &S;
};
/// An RAII helper that pops function a function scope on exit.
struct FunctionScopeRAII {
Sema &S;
bool Active;
FunctionScopeRAII(Sema &S) : S(S), Active(true) {}
~FunctionScopeRAII() {
if (Active)
S.PopFunctionScopeInfo();
}
void disable() { Active = false; }
};
StmtResult ActOnDeclStmt(DeclGroupPtrTy Decl,
SourceLocation StartLoc,
SourceLocation EndLoc);
void ActOnForEachDeclStmt(DeclGroupPtrTy Decl);
StmtResult ActOnForEachLValueExpr(Expr *E);
StmtResult ActOnCaseStmt(SourceLocation CaseLoc, Expr *LHSVal,
SourceLocation DotDotDotLoc, Expr *RHSVal,
SourceLocation ColonLoc);
void ActOnCaseStmtBody(Stmt *CaseStmt, Stmt *SubStmt);
StmtResult ActOnDefaultStmt(SourceLocation DefaultLoc,
SourceLocation ColonLoc,
Stmt *SubStmt, Scope *CurScope);
StmtResult ActOnLabelStmt(SourceLocation IdentLoc, LabelDecl *TheDecl,
SourceLocation ColonLoc, Stmt *SubStmt);
StmtResult ActOnAttributedStmt(SourceLocation AttrLoc,
ArrayRef<const Attr*> Attrs,
Stmt *SubStmt);
StmtResult ActOnIfStmt(SourceLocation IfLoc,
FullExprArg CondVal, Decl *CondVar,
Stmt *ThenVal,
SourceLocation ElseLoc, Stmt *ElseVal);
StmtResult ActOnStartOfSwitchStmt(SourceLocation SwitchLoc,
Expr *Cond,
Decl *CondVar);
StmtResult ActOnFinishSwitchStmt(SourceLocation SwitchLoc,
Stmt *Switch, Stmt *Body);
StmtResult ActOnWhileStmt(SourceLocation WhileLoc,
FullExprArg Cond,
Decl *CondVar, Stmt *Body);
StmtResult ActOnDoStmt(SourceLocation DoLoc, Stmt *Body,
SourceLocation WhileLoc,
SourceLocation CondLParen, Expr *Cond,
SourceLocation CondRParen);
StmtResult ActOnForStmt(SourceLocation ForLoc,
SourceLocation LParenLoc,
Stmt *First, FullExprArg Second,
Decl *SecondVar,
FullExprArg Third,
SourceLocation RParenLoc,
Stmt *Body);
ExprResult CheckObjCForCollectionOperand(SourceLocation forLoc,
Expr *collection);
StmtResult ActOnObjCForCollectionStmt(SourceLocation ForColLoc,
Stmt *First, Expr *collection,
SourceLocation RParenLoc);
StmtResult FinishObjCForCollectionStmt(Stmt *ForCollection, Stmt *Body);
enum BuildForRangeKind {
/// Initial building of a for-range statement.
BFRK_Build,
/// Instantiation or recovery rebuild of a for-range statement. Don't
/// attempt any typo-correction.
BFRK_Rebuild,
/// Determining whether a for-range statement could be built. Avoid any
/// unnecessary or irreversible actions.
BFRK_Check
};
StmtResult ActOnCXXForRangeStmt(SourceLocation ForLoc, Stmt *LoopVar,
SourceLocation ColonLoc, Expr *Collection,
SourceLocation RParenLoc,
BuildForRangeKind Kind);
StmtResult BuildCXXForRangeStmt(SourceLocation ForLoc,
SourceLocation ColonLoc,
Stmt *RangeDecl, Stmt *BeginEndDecl,
Expr *Cond, Expr *Inc,
Stmt *LoopVarDecl,
SourceLocation RParenLoc,
BuildForRangeKind Kind);
StmtResult FinishCXXForRangeStmt(Stmt *ForRange, Stmt *Body);
StmtResult ActOnGotoStmt(SourceLocation GotoLoc,
SourceLocation LabelLoc,
LabelDecl *TheDecl);
StmtResult ActOnIndirectGotoStmt(SourceLocation GotoLoc,
SourceLocation StarLoc,
Expr *DestExp);
StmtResult ActOnContinueStmt(SourceLocation ContinueLoc, Scope *CurScope);
StmtResult ActOnBreakStmt(SourceLocation BreakLoc, Scope *CurScope);
void ActOnCapturedRegionStart(SourceLocation Loc, Scope *CurScope,
CapturedRegionKind Kind, unsigned NumParams);
typedef std::pair<StringRef, QualType> CapturedParamNameType;
void ActOnCapturedRegionStart(SourceLocation Loc, Scope *CurScope,
CapturedRegionKind Kind,
ArrayRef<CapturedParamNameType> Params);
StmtResult ActOnCapturedRegionEnd(Stmt *S);
void ActOnCapturedRegionError();
RecordDecl *CreateCapturedStmtRecordDecl(CapturedDecl *&CD,
SourceLocation Loc,
unsigned NumParams);
VarDecl *getCopyElisionCandidate(QualType ReturnType, Expr *E,
bool AllowFunctionParameters);
bool isCopyElisionCandidate(QualType ReturnType, const VarDecl *VD,
bool AllowFunctionParameters);
StmtResult ActOnReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp,
Scope *CurScope);
StmtResult BuildReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp);
StmtResult ActOnCapScopeReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp);
StmtResult ActOnGCCAsmStmt(SourceLocation AsmLoc, bool IsSimple,
bool IsVolatile, unsigned NumOutputs,
unsigned NumInputs, IdentifierInfo **Names,
MultiExprArg Constraints, MultiExprArg Exprs,
Expr *AsmString, MultiExprArg Clobbers,
SourceLocation RParenLoc);
ExprResult LookupInlineAsmIdentifier(CXXScopeSpec &SS,
SourceLocation TemplateKWLoc,
UnqualifiedId &Id,
llvm::InlineAsmIdentifierInfo &Info,
bool IsUnevaluatedContext);
bool LookupInlineAsmField(StringRef Base, StringRef Member,
unsigned &Offset, SourceLocation AsmLoc);
StmtResult ActOnMSAsmStmt(SourceLocation AsmLoc, SourceLocation LBraceLoc,
ArrayRef<Token> AsmToks,
StringRef AsmString,
unsigned NumOutputs, unsigned NumInputs,
ArrayRef<StringRef> Constraints,
ArrayRef<StringRef> Clobbers,
ArrayRef<Expr*> Exprs,
SourceLocation EndLoc);
LabelDecl *GetOrCreateMSAsmLabel(StringRef ExternalLabelName,
SourceLocation Location,
bool AlwaysCreate);
VarDecl *BuildObjCExceptionDecl(TypeSourceInfo *TInfo, QualType ExceptionType,
SourceLocation StartLoc,
SourceLocation IdLoc, IdentifierInfo *Id,
bool Invalid = false);
Decl *ActOnObjCExceptionDecl(Scope *S, Declarator &D);
StmtResult ActOnObjCAtCatchStmt(SourceLocation AtLoc, SourceLocation RParen,
Decl *Parm, Stmt *Body);
StmtResult ActOnObjCAtFinallyStmt(SourceLocation AtLoc, Stmt *Body);
StmtResult ActOnObjCAtTryStmt(SourceLocation AtLoc, Stmt *Try,
MultiStmtArg Catch, Stmt *Finally);
StmtResult BuildObjCAtThrowStmt(SourceLocation AtLoc, Expr *Throw);
StmtResult ActOnObjCAtThrowStmt(SourceLocation AtLoc, Expr *Throw,
Scope *CurScope);
ExprResult ActOnObjCAtSynchronizedOperand(SourceLocation atLoc,
Expr *operand);
StmtResult ActOnObjCAtSynchronizedStmt(SourceLocation AtLoc,
Expr *SynchExpr,
Stmt *SynchBody);
StmtResult ActOnObjCAutoreleasePoolStmt(SourceLocation AtLoc, Stmt *Body);
VarDecl *BuildExceptionDeclaration(Scope *S, TypeSourceInfo *TInfo,
SourceLocation StartLoc,
SourceLocation IdLoc,
IdentifierInfo *Id);
Decl *ActOnExceptionDeclarator(Scope *S, Declarator &D);
StmtResult ActOnCXXCatchBlock(SourceLocation CatchLoc,
Decl *ExDecl, Stmt *HandlerBlock);
StmtResult ActOnCXXTryBlock(SourceLocation TryLoc, Stmt *TryBlock,
ArrayRef<Stmt *> Handlers);
StmtResult ActOnSEHTryBlock(bool IsCXXTry, // try (true) or __try (false) ?
SourceLocation TryLoc, Stmt *TryBlock,
Stmt *Handler);
StmtResult ActOnSEHExceptBlock(SourceLocation Loc,
Expr *FilterExpr,
Stmt *Block);
void ActOnStartSEHFinallyBlock();
void ActOnAbortSEHFinallyBlock();
StmtResult ActOnFinishSEHFinallyBlock(SourceLocation Loc, Stmt *Block);
StmtResult ActOnSEHLeaveStmt(SourceLocation Loc, Scope *CurScope);
void DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock);
bool ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const;
/// \brief If it's a file scoped decl that must warn if not used, keep track
/// of it.
void MarkUnusedFileScopedDecl(const DeclaratorDecl *D);
/// DiagnoseUnusedExprResult - If the statement passed in is an expression
/// whose result is unused, warn.
void DiagnoseUnusedExprResult(const Stmt *S);
void DiagnoseUnusedNestedTypedefs(const RecordDecl *D);
void DiagnoseUnusedDecl(const NamedDecl *ND);
/// Emit \p DiagID if statement located on \p StmtLoc has a suspicious null
/// statement as a \p Body, and it is located on the same line.
///
/// This helps prevent bugs due to typos, such as:
/// if (condition);
/// do_stuff();
void DiagnoseEmptyStmtBody(SourceLocation StmtLoc,
const Stmt *Body,
unsigned DiagID);
/// Warn if a for/while loop statement \p S, which is followed by
/// \p PossibleBody, has a suspicious null statement as a body.
void DiagnoseEmptyLoopBody(const Stmt *S,
const Stmt *PossibleBody);
/// Warn if a value is moved to itself.
void DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr,
SourceLocation OpLoc);
ParsingDeclState PushParsingDeclaration(sema::DelayedDiagnosticPool &pool) {
return DelayedDiagnostics.push(pool);
}
void PopParsingDeclaration(ParsingDeclState state, Decl *decl);
typedef ProcessingContextState ParsingClassState;
ParsingClassState PushParsingClass() {
return DelayedDiagnostics.pushUndelayed();
}
void PopParsingClass(ParsingClassState state) {
DelayedDiagnostics.popUndelayed(state);
}
void redelayDiagnostics(sema::DelayedDiagnosticPool &pool);
enum AvailabilityDiagnostic { AD_Deprecation, AD_Unavailable, AD_Partial };
void EmitAvailabilityWarning(AvailabilityDiagnostic AD,
NamedDecl *D, StringRef Message,
SourceLocation Loc,
const ObjCInterfaceDecl *UnknownObjCClass,
const ObjCPropertyDecl *ObjCProperty,
bool ObjCPropertyAccess);
bool makeUnavailableInSystemHeader(SourceLocation loc,
StringRef message);
//===--------------------------------------------------------------------===//
// Expression Parsing Callbacks: SemaExpr.cpp.
bool CanUseDecl(NamedDecl *D);
bool DiagnoseUseOfDecl(NamedDecl *D, SourceLocation Loc,
const ObjCInterfaceDecl *UnknownObjCClass=nullptr,
bool ObjCPropertyAccess=false);
void NoteDeletedFunction(FunctionDecl *FD);
std::string getDeletedOrUnavailableSuffix(const FunctionDecl *FD);
bool DiagnosePropertyAccessorMismatch(ObjCPropertyDecl *PD,
ObjCMethodDecl *Getter,
SourceLocation Loc);
void DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc,
ArrayRef<Expr *> Args);
void PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext,
Decl *LambdaContextDecl = nullptr,
bool IsDecltype = false);
enum ReuseLambdaContextDecl_t { ReuseLambdaContextDecl };
void PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext,
ReuseLambdaContextDecl_t,
bool IsDecltype = false);
void PopExpressionEvaluationContext();
void DiscardCleanupsInEvaluationContext();
ExprResult TransformToPotentiallyEvaluated(Expr *E);
ExprResult HandleExprEvaluationContextForTypeof(Expr *E);
ExprResult ActOnConstantExpression(ExprResult Res);
// Functions for marking a declaration referenced. These functions also
// contain the relevant logic for marking if a reference to a function or
// variable is an odr-use (in the C++11 sense). There are separate variants
// for expressions referring to a decl; these exist because odr-use marking
// needs to be delayed for some constant variables when we build one of the
// named expressions.
void MarkAnyDeclReferenced(SourceLocation Loc, Decl *D, bool OdrUse);
void MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func,
bool OdrUse = true);
void MarkVariableReferenced(SourceLocation Loc, VarDecl *Var);
void MarkDeclRefReferenced(DeclRefExpr *E);
void MarkMemberReferenced(MemberExpr *E);
void UpdateMarkingForLValueToRValue(Expr *E);
void CleanupVarDeclMarking();
enum TryCaptureKind {
TryCapture_Implicit, TryCapture_ExplicitByVal, TryCapture_ExplicitByRef
};
/// \brief Try to capture the given variable.
///
/// \param Var The variable to capture.
///
/// \param Loc The location at which the capture occurs.
///
/// \param Kind The kind of capture, which may be implicit (for either a
/// block or a lambda), or explicit by-value or by-reference (for a lambda).
///
/// \param EllipsisLoc The location of the ellipsis, if one is provided in
/// an explicit lambda capture.
///
/// \param BuildAndDiagnose Whether we are actually supposed to add the
/// captures or diagnose errors. If false, this routine merely check whether
/// the capture can occur without performing the capture itself or complaining
/// if the variable cannot be captured.
///
/// \param CaptureType Will be set to the type of the field used to capture
/// this variable in the innermost block or lambda. Only valid when the
/// variable can be captured.
///
/// \param DeclRefType Will be set to the type of a reference to the capture
/// from within the current scope. Only valid when the variable can be
/// captured.
///
/// \param FunctionScopeIndexToStopAt If non-null, it points to the index
/// of the FunctionScopeInfo stack beyond which we do not attempt to capture.
/// This is useful when enclosing lambdas must speculatively capture
/// variables that may or may not be used in certain specializations of
/// a nested generic lambda.
///
/// \returns true if an error occurred (i.e., the variable cannot be
/// captured) and false if the capture succeeded.
bool tryCaptureVariable(VarDecl *Var, SourceLocation Loc, TryCaptureKind Kind,
SourceLocation EllipsisLoc, bool BuildAndDiagnose,
QualType &CaptureType,
QualType &DeclRefType,
const unsigned *const FunctionScopeIndexToStopAt);
/// \brief Try to capture the given variable.
bool tryCaptureVariable(VarDecl *Var, SourceLocation Loc,
TryCaptureKind Kind = TryCapture_Implicit,
SourceLocation EllipsisLoc = SourceLocation());
/// \brief Checks if the variable must be captured.
bool NeedToCaptureVariable(VarDecl *Var, SourceLocation Loc);
/// \brief Given a variable, determine the type that a reference to that
/// variable will have in the given scope.
QualType getCapturedDeclRefType(VarDecl *Var, SourceLocation Loc);
void MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T);
void MarkDeclarationsReferencedInExpr(Expr *E,
bool SkipLocalVariables = false);
/// \brief Try to recover by turning the given expression into a
/// call. Returns true if recovery was attempted or an error was
/// emitted; this may also leave the ExprResult invalid.
bool tryToRecoverWithCall(ExprResult &E, const PartialDiagnostic &PD,
bool ForceComplain = false,
bool (*IsPlausibleResult)(QualType) = nullptr);
/// \brief Figure out if an expression could be turned into a call.
bool tryExprAsCall(Expr &E, QualType &ZeroArgCallReturnTy,
UnresolvedSetImpl &NonTemplateOverloads);
/// \brief Conditionally issue a diagnostic based on the current
/// evaluation context.
///
/// \param Statement If Statement is non-null, delay reporting the
/// diagnostic until the function body is parsed, and then do a basic
/// reachability analysis to determine if the statement is reachable.
/// If it is unreachable, the diagnostic will not be emitted.
bool DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement,
const PartialDiagnostic &PD);
// Primary Expressions.
SourceRange getExprRange(Expr *E) const;
ExprResult ActOnIdExpression(
Scope *S, CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
UnqualifiedId &Id, bool HasTrailingLParen, bool IsAddressOfOperand,
std::unique_ptr<CorrectionCandidateCallback> CCC = nullptr,
bool IsInlineAsmIdentifier = false, Token *KeywordReplacement = nullptr);
void DecomposeUnqualifiedId(const UnqualifiedId &Id,
TemplateArgumentListInfo &Buffer,
DeclarationNameInfo &NameInfo,
const TemplateArgumentListInfo *&TemplateArgs);
bool
DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R,
std::unique_ptr<CorrectionCandidateCallback> CCC,
TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr,
ArrayRef<Expr *> Args = None, TypoExpr **Out = nullptr);
ExprResult LookupInObjCMethod(LookupResult &LookUp, Scope *S,
IdentifierInfo *II,
bool AllowBuiltinCreation=false);
ExprResult ActOnDependentIdExpression(const CXXScopeSpec &SS,
SourceLocation TemplateKWLoc,
const DeclarationNameInfo &NameInfo,
bool isAddressOfOperand,
const TemplateArgumentListInfo *TemplateArgs);
ExprResult BuildDeclRefExpr(ValueDecl *D, QualType Ty,
ExprValueKind VK,
SourceLocation Loc,
const CXXScopeSpec *SS = nullptr);
ExprResult
BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
const DeclarationNameInfo &NameInfo,
const CXXScopeSpec *SS = nullptr,
NamedDecl *FoundD = nullptr,
const TemplateArgumentListInfo *TemplateArgs = nullptr);
ExprResult
BuildAnonymousStructUnionMemberReference(
const CXXScopeSpec &SS,
SourceLocation nameLoc,
IndirectFieldDecl *indirectField,
DeclAccessPair FoundDecl = DeclAccessPair::make(nullptr, AS_none),
Expr *baseObjectExpr = nullptr,
SourceLocation opLoc = SourceLocation());
ExprResult BuildPossibleImplicitMemberExpr(const CXXScopeSpec &SS,
SourceLocation TemplateKWLoc,
LookupResult &R,
const TemplateArgumentListInfo *TemplateArgs);
ExprResult BuildImplicitMemberExpr(const CXXScopeSpec &SS,
SourceLocation TemplateKWLoc,
LookupResult &R,
const TemplateArgumentListInfo *TemplateArgs,
bool IsDefiniteInstance);
bool UseArgumentDependentLookup(const CXXScopeSpec &SS,
const LookupResult &R,
bool HasTrailingLParen);
ExprResult BuildQualifiedDeclarationNameExpr(
CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo,
bool IsAddressOfOperand, TypeSourceInfo **RecoveryTSI = nullptr);
ExprResult BuildDependentDeclRefExpr(const CXXScopeSpec &SS,
SourceLocation TemplateKWLoc,
const DeclarationNameInfo &NameInfo,
const TemplateArgumentListInfo *TemplateArgs);
ExprResult BuildDeclarationNameExpr(const CXXScopeSpec &SS,
LookupResult &R,
bool NeedsADL,
bool AcceptInvalidDecl = false);
ExprResult BuildDeclarationNameExpr(
const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, NamedDecl *D,
NamedDecl *FoundD = nullptr,
const TemplateArgumentListInfo *TemplateArgs = nullptr,
bool AcceptInvalidDecl = false);
ExprResult BuildLiteralOperatorCall(LookupResult &R,
DeclarationNameInfo &SuffixInfo,
ArrayRef<Expr *> Args,
SourceLocation LitEndLoc,
TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr);
ExprResult BuildPredefinedExpr(SourceLocation Loc,
PredefinedExpr::IdentType IT);
ExprResult ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind);
ExprResult ActOnIntegerConstant(SourceLocation Loc, uint64_t Val);
bool CheckLoopHintExpr(Expr *E, SourceLocation Loc);
ExprResult ActOnNumericConstant(const Token &Tok, Scope *UDLScope = nullptr);
ExprResult ActOnCharacterConstant(const Token &Tok,
Scope *UDLScope = nullptr);
ExprResult ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E);
ExprResult ActOnParenListExpr(SourceLocation L,
SourceLocation R,
MultiExprArg Val);
/// ActOnStringLiteral - The specified tokens were lexed as pasted string
/// fragments (e.g. "foo" "bar" L"baz").
ExprResult ActOnStringLiteral(ArrayRef<Token> StringToks,
Scope *UDLScope = nullptr);
ExprResult ActOnGenericSelectionExpr(SourceLocation KeyLoc,
SourceLocation DefaultLoc,
SourceLocation RParenLoc,
Expr *ControllingExpr,
ArrayRef<ParsedType> ArgTypes,
ArrayRef<Expr *> ArgExprs);
ExprResult CreateGenericSelectionExpr(SourceLocation KeyLoc,
SourceLocation DefaultLoc,
SourceLocation RParenLoc,
Expr *ControllingExpr,
ArrayRef<TypeSourceInfo *> Types,
ArrayRef<Expr *> Exprs);
// Binary/Unary Operators. 'Tok' is the token for the operator.
ExprResult CreateBuiltinUnaryOp(SourceLocation OpLoc, UnaryOperatorKind Opc,
Expr *InputExpr);
ExprResult BuildUnaryOp(Scope *S, SourceLocation OpLoc,
UnaryOperatorKind Opc, Expr *Input);
ExprResult ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
tok::TokenKind Op, Expr *Input);
QualType CheckAddressOfOperand(ExprResult &Operand, SourceLocation OpLoc);
ExprResult CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo,
SourceLocation OpLoc,
UnaryExprOrTypeTrait ExprKind,
SourceRange R);
ExprResult CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc,
UnaryExprOrTypeTrait ExprKind);
ExprResult
ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc,
UnaryExprOrTypeTrait ExprKind,
bool IsType, void *TyOrEx,
const SourceRange &ArgRange);
ExprResult CheckPlaceholderExpr(Expr *E);
bool CheckVecStepExpr(Expr *E);
bool CheckUnaryExprOrTypeTraitOperand(Expr *E, UnaryExprOrTypeTrait ExprKind);
bool CheckUnaryExprOrTypeTraitOperand(QualType ExprType, SourceLocation OpLoc,
SourceRange ExprRange,
UnaryExprOrTypeTrait ExprKind);
ExprResult ActOnSizeofParameterPackExpr(Scope *S,
SourceLocation OpLoc,
IdentifierInfo &Name,
SourceLocation NameLoc,
SourceLocation RParenLoc);
ExprResult ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
tok::TokenKind Kind, Expr *Input);
ExprResult ActOnArraySubscriptExpr(Scope *S, Expr *Base, SourceLocation LLoc,
Expr *Idx, SourceLocation RLoc);
ExprResult CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc,
Expr *Idx, SourceLocation RLoc);
// This struct is for use by ActOnMemberAccess to allow
// BuildMemberReferenceExpr to be able to reinvoke ActOnMemberAccess after
// changing the access operator from a '.' to a '->' (to see if that is the
// change needed to fix an error about an unknown member, e.g. when the class
// defines a custom operator->).
struct ActOnMemberAccessExtraArgs {
Scope *S;
UnqualifiedId &Id;
Decl *ObjCImpDecl;
};
ExprResult BuildMemberReferenceExpr(
Expr *Base, QualType BaseType, SourceLocation OpLoc, bool IsArrow,
CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
NamedDecl *FirstQualifierInScope, const DeclarationNameInfo &NameInfo,
const TemplateArgumentListInfo *TemplateArgs,
ActOnMemberAccessExtraArgs *ExtraArgs = nullptr);
ExprResult
BuildMemberReferenceExpr(Expr *Base, QualType BaseType, SourceLocation OpLoc,
bool IsArrow, const CXXScopeSpec &SS,
SourceLocation TemplateKWLoc,
NamedDecl *FirstQualifierInScope, LookupResult &R,
const TemplateArgumentListInfo *TemplateArgs,
bool SuppressQualifierCheck = false,
ActOnMemberAccessExtraArgs *ExtraArgs = nullptr);
ExprResult PerformMemberExprBaseConversion(Expr *Base, bool IsArrow);
bool CheckQualifiedMemberReference(Expr *BaseExpr, QualType BaseType,
const CXXScopeSpec &SS,
const LookupResult &R);
ExprResult ActOnDependentMemberExpr(Expr *Base, QualType BaseType,
bool IsArrow, SourceLocation OpLoc,
const CXXScopeSpec &SS,
SourceLocation TemplateKWLoc,
NamedDecl *FirstQualifierInScope,
const DeclarationNameInfo &NameInfo,
const TemplateArgumentListInfo *TemplateArgs);
ExprResult ActOnMemberAccessExpr(Scope *S, Expr *Base,
SourceLocation OpLoc,
tok::TokenKind OpKind,
CXXScopeSpec &SS,
SourceLocation TemplateKWLoc,
UnqualifiedId &Member,
Decl *ObjCImpDecl);
void ActOnDefaultCtorInitializers(Decl *CDtorDecl);
bool ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
FunctionDecl *FDecl,
const FunctionProtoType *Proto,
ArrayRef<Expr *> Args,
SourceLocation RParenLoc,
bool ExecConfig = false);
void CheckStaticArrayArgument(SourceLocation CallLoc,
ParmVarDecl *Param,
const Expr *ArgExpr);
/// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
/// This provides the location of the left/right parens and a list of comma
/// locations.
ExprResult ActOnCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc,
MultiExprArg ArgExprs, SourceLocation RParenLoc,
Expr *ExecConfig = nullptr,
bool IsExecConfig = false);
ExprResult BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl,
SourceLocation LParenLoc,
ArrayRef<Expr *> Arg,
SourceLocation RParenLoc,
Expr *Config = nullptr,
bool IsExecConfig = false);
ExprResult ActOnCUDAExecConfigExpr(Scope *S, SourceLocation LLLLoc,
MultiExprArg ExecConfig,
SourceLocation GGGLoc);
ExprResult ActOnCastExpr(Scope *S, SourceLocation LParenLoc,
Declarator &D, ParsedType &Ty,
SourceLocation RParenLoc, Expr *CastExpr);
ExprResult BuildCStyleCastExpr(SourceLocation LParenLoc,
TypeSourceInfo *Ty,
SourceLocation RParenLoc,
Expr *Op);
CastKind PrepareScalarCast(ExprResult &src, QualType destType);
/// \brief Build an altivec or OpenCL literal.
ExprResult BuildVectorLiteral(SourceLocation LParenLoc,
SourceLocation RParenLoc, Expr *E,
TypeSourceInfo *TInfo);
ExprResult MaybeConvertParenListExprToParenExpr(Scope *S, Expr *ME);
ExprResult ActOnCompoundLiteral(SourceLocation LParenLoc,
ParsedType Ty,
SourceLocation RParenLoc,
Expr *InitExpr);
ExprResult BuildCompoundLiteralExpr(SourceLocation LParenLoc,
TypeSourceInfo *TInfo,
SourceLocation RParenLoc,
Expr *LiteralExpr);
ExprResult ActOnInitList(SourceLocation LBraceLoc,
MultiExprArg InitArgList,
SourceLocation RBraceLoc);
ExprResult ActOnDesignatedInitializer(Designation &Desig,
SourceLocation Loc,
bool GNUSyntax,
ExprResult Init);
private:
static BinaryOperatorKind ConvertTokenKindToBinaryOpcode(tok::TokenKind Kind);
public:
ExprResult ActOnBinOp(Scope *S, SourceLocation TokLoc,
tok::TokenKind Kind, Expr *LHSExpr, Expr *RHSExpr);
ExprResult BuildBinOp(Scope *S, SourceLocation OpLoc,
BinaryOperatorKind Opc, Expr *LHSExpr, Expr *RHSExpr);
ExprResult CreateBuiltinBinOp(SourceLocation OpLoc, BinaryOperatorKind Opc,
Expr *LHSExpr, Expr *RHSExpr);
/// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
/// in the case of a the GNU conditional expr extension.
ExprResult ActOnConditionalOp(SourceLocation QuestionLoc,
SourceLocation ColonLoc,
Expr *CondExpr, Expr *LHSExpr, Expr *RHSExpr);
/// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
ExprResult ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc,
LabelDecl *TheDecl);
void ActOnStartStmtExpr();
ExprResult ActOnStmtExpr(SourceLocation LPLoc, Stmt *SubStmt,
SourceLocation RPLoc); // "({..})"
void ActOnStmtExprError();
// __builtin_offsetof(type, identifier(.identifier|[expr])*)
struct OffsetOfComponent {
SourceLocation LocStart, LocEnd;
bool isBrackets; // true if [expr], false if .ident
union {
IdentifierInfo *IdentInfo;
Expr *E;
} U;
};
/// __builtin_offsetof(type, a.b[123][456].c)
ExprResult BuildBuiltinOffsetOf(SourceLocation BuiltinLoc,
TypeSourceInfo *TInfo,
OffsetOfComponent *CompPtr,
unsigned NumComponents,
SourceLocation RParenLoc);
ExprResult ActOnBuiltinOffsetOf(Scope *S,
SourceLocation BuiltinLoc,
SourceLocation TypeLoc,
ParsedType ParsedArgTy,
OffsetOfComponent *CompPtr,
unsigned NumComponents,
SourceLocation RParenLoc);
// __builtin_choose_expr(constExpr, expr1, expr2)
ExprResult ActOnChooseExpr(SourceLocation BuiltinLoc,
Expr *CondExpr, Expr *LHSExpr,
Expr *RHSExpr, SourceLocation RPLoc);
// __builtin_va_arg(expr, type)
ExprResult ActOnVAArg(SourceLocation BuiltinLoc, Expr *E, ParsedType Ty,
SourceLocation RPLoc);
ExprResult BuildVAArgExpr(SourceLocation BuiltinLoc, Expr *E,
TypeSourceInfo *TInfo, SourceLocation RPLoc);
// __null
ExprResult ActOnGNUNullExpr(SourceLocation TokenLoc);
bool CheckCaseExpression(Expr *E);
/// \brief Describes the result of an "if-exists" condition check.
enum IfExistsResult {
/// \brief The symbol exists.
IER_Exists,
/// \brief The symbol does not exist.
IER_DoesNotExist,
/// \brief The name is a dependent name, so the results will differ
/// from one instantiation to the next.
IER_Dependent,
/// \brief An error occurred.
IER_Error
};
IfExistsResult
CheckMicrosoftIfExistsSymbol(Scope *S, CXXScopeSpec &SS,
const DeclarationNameInfo &TargetNameInfo);
IfExistsResult
CheckMicrosoftIfExistsSymbol(Scope *S, SourceLocation KeywordLoc,
bool IsIfExists, CXXScopeSpec &SS,
UnqualifiedId &Name);
StmtResult BuildMSDependentExistsStmt(SourceLocation KeywordLoc,
bool IsIfExists,
NestedNameSpecifierLoc QualifierLoc,
DeclarationNameInfo NameInfo,
Stmt *Nested);
StmtResult ActOnMSDependentExistsStmt(SourceLocation KeywordLoc,
bool IsIfExists,
CXXScopeSpec &SS, UnqualifiedId &Name,
Stmt *Nested);
//===------------------------- "Block" Extension ------------------------===//
/// ActOnBlockStart - This callback is invoked when a block literal is
/// started.
void ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope);
/// ActOnBlockArguments - This callback allows processing of block arguments.
/// If there are no arguments, this is still invoked.
void ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo,
Scope *CurScope);
/// ActOnBlockError - If there is an error parsing a block, this callback
/// is invoked to pop the information about the block from the action impl.
void ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope);
/// ActOnBlockStmtExpr - This is called when the body of a block statement
/// literal was successfully completed. ^(int x){...}
ExprResult ActOnBlockStmtExpr(SourceLocation CaretLoc, Stmt *Body,
Scope *CurScope);
//===---------------------------- Clang Extensions ----------------------===//
/// __builtin_convertvector(...)
ExprResult ActOnConvertVectorExpr(Expr *E, ParsedType ParsedDestTy,
SourceLocation BuiltinLoc,
SourceLocation RParenLoc);
//===---------------------------- OpenCL Features -----------------------===//
/// __builtin_astype(...)
ExprResult ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy,
SourceLocation BuiltinLoc,
SourceLocation RParenLoc);
//===---------------------------- C++ Features --------------------------===//
// Act on C++ namespaces
Decl *ActOnStartNamespaceDef(Scope *S, SourceLocation InlineLoc,
SourceLocation NamespaceLoc,
SourceLocation IdentLoc,
IdentifierInfo *Ident,
SourceLocation LBrace,
AttributeList *AttrList);
void ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace);
NamespaceDecl *getStdNamespace() const;
NamespaceDecl *getOrCreateStdNamespace();
CXXRecordDecl *getStdBadAlloc() const;
/// \brief Tests whether Ty is an instance of std::initializer_list and, if
/// it is and Element is not NULL, assigns the element type to Element.
bool isStdInitializerList(QualType Ty, QualType *Element);
/// \brief Looks for the std::initializer_list template and instantiates it
/// with Element, or emits an error if it's not found.
///
/// \returns The instantiated template, or null on error.
QualType BuildStdInitializerList(QualType Element, SourceLocation Loc);
/// \brief Determine whether Ctor is an initializer-list constructor, as
/// defined in [dcl.init.list]p2.
bool isInitListConstructor(const CXXConstructorDecl *Ctor);
Decl *ActOnUsingDirective(Scope *CurScope,
SourceLocation UsingLoc,
SourceLocation NamespcLoc,
CXXScopeSpec &SS,
SourceLocation IdentLoc,
IdentifierInfo *NamespcName,
AttributeList *AttrList);
void PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir);
Decl *ActOnNamespaceAliasDef(Scope *CurScope,
SourceLocation NamespaceLoc,
SourceLocation AliasLoc,
IdentifierInfo *Alias,
CXXScopeSpec &SS,
SourceLocation IdentLoc,
IdentifierInfo *Ident);
void HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow);
bool CheckUsingShadowDecl(UsingDecl *UD, NamedDecl *Target,
const LookupResult &PreviousDecls,
UsingShadowDecl *&PrevShadow);
UsingShadowDecl *BuildUsingShadowDecl(Scope *S, UsingDecl *UD,
NamedDecl *Target,
UsingShadowDecl *PrevDecl);
bool CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
bool HasTypenameKeyword,
const CXXScopeSpec &SS,
SourceLocation NameLoc,
const LookupResult &Previous);
bool CheckUsingDeclQualifier(SourceLocation UsingLoc,
const CXXScopeSpec &SS,
const DeclarationNameInfo &NameInfo,
SourceLocation NameLoc);
NamedDecl *BuildUsingDeclaration(Scope *S, AccessSpecifier AS,
SourceLocation UsingLoc,
CXXScopeSpec &SS,
DeclarationNameInfo NameInfo,
AttributeList *AttrList,
bool IsInstantiation,
bool HasTypenameKeyword,
SourceLocation TypenameLoc);
bool CheckInheritingConstructorUsingDecl(UsingDecl *UD);
Decl *ActOnUsingDeclaration(Scope *CurScope,
AccessSpecifier AS,
bool HasUsingKeyword,
SourceLocation UsingLoc,
CXXScopeSpec &SS,
UnqualifiedId &Name,
AttributeList *AttrList,
bool HasTypenameKeyword,
SourceLocation TypenameLoc);
Decl *ActOnAliasDeclaration(Scope *CurScope,
AccessSpecifier AS,
MultiTemplateParamsArg TemplateParams,
SourceLocation UsingLoc,
UnqualifiedId &Name,
AttributeList *AttrList,
TypeResult Type,
Decl *DeclFromDeclSpec);
/// BuildCXXConstructExpr - Creates a complete call to a constructor,
/// including handling of its default argument expressions.
///
/// \param ConstructKind - a CXXConstructExpr::ConstructionKind
ExprResult
BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
CXXConstructorDecl *Constructor, MultiExprArg Exprs,
bool HadMultipleCandidates, bool IsListInitialization,
bool IsStdInitListInitialization,
bool RequiresZeroInit, unsigned ConstructKind,
SourceRange ParenRange);
// FIXME: Can we remove this and have the above BuildCXXConstructExpr check if
// the constructor can be elidable?
ExprResult
BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
CXXConstructorDecl *Constructor, bool Elidable,
MultiExprArg Exprs, bool HadMultipleCandidates,
bool IsListInitialization,
bool IsStdInitListInitialization, bool RequiresZeroInit,
unsigned ConstructKind, SourceRange ParenRange);
ExprResult BuildCXXDefaultInitExpr(SourceLocation Loc, FieldDecl *Field);
/// BuildCXXDefaultArgExpr - Creates a CXXDefaultArgExpr, instantiating
/// the default expr if needed.
ExprResult BuildCXXDefaultArgExpr(SourceLocation CallLoc,
FunctionDecl *FD,
ParmVarDecl *Param);
/// FinalizeVarWithDestructor - Prepare for calling destructor on the
/// constructed variable.
void FinalizeVarWithDestructor(VarDecl *VD, const RecordType *DeclInitType);
/// \brief Helper class that collects exception specifications for
/// implicitly-declared special member functions.
class ImplicitExceptionSpecification {
// Pointer to allow copying
Sema *Self;
// We order exception specifications thus:
// noexcept is the most restrictive, but is only used in C++11.
// throw() comes next.
// Then a throw(collected exceptions)
// Finally no specification, which is expressed as noexcept(false).
// throw(...) is used instead if any called function uses it.
ExceptionSpecificationType ComputedEST;
llvm::SmallPtrSet<CanQualType, 4> ExceptionsSeen;
SmallVector<QualType, 4> Exceptions;
void ClearExceptions() {
ExceptionsSeen.clear();
Exceptions.clear();
}
public:
explicit ImplicitExceptionSpecification(Sema &Self)
: Self(&Self), ComputedEST(EST_BasicNoexcept) {
if (!Self.getLangOpts().CPlusPlus11)
ComputedEST = EST_DynamicNone;
}
/// \brief Get the computed exception specification type.
ExceptionSpecificationType getExceptionSpecType() const {
assert(ComputedEST != EST_ComputedNoexcept &&
"noexcept(expr) should not be a possible result");
return ComputedEST;
}
/// \brief The number of exceptions in the exception specification.
unsigned size() const { return Exceptions.size(); }
/// \brief The set of exceptions in the exception specification.
const QualType *data() const { return Exceptions.data(); }
/// \brief Integrate another called method into the collected data.
void CalledDecl(SourceLocation CallLoc, const CXXMethodDecl *Method);
/// \brief Integrate an invoked expression into the collected data.
void CalledExpr(Expr *E);
/// \brief Overwrite an EPI's exception specification with this
/// computed exception specification.
FunctionProtoType::ExceptionSpecInfo getExceptionSpec() const {
FunctionProtoType::ExceptionSpecInfo ESI;
ESI.Type = getExceptionSpecType();
if (ESI.Type == EST_Dynamic) {
ESI.Exceptions = Exceptions;
} else if (ESI.Type == EST_None) {
/// C++11 [except.spec]p14:
/// The exception-specification is noexcept(false) if the set of
/// potential exceptions of the special member function contains "any"
ESI.Type = EST_ComputedNoexcept;
ESI.NoexceptExpr = Self->ActOnCXXBoolLiteral(SourceLocation(),
tok::kw_false).get();
}
return ESI;
}
};
/// \brief Determine what sort of exception specification a defaulted
/// copy constructor of a class will have.
ImplicitExceptionSpecification
ComputeDefaultedDefaultCtorExceptionSpec(SourceLocation Loc,
CXXMethodDecl *MD);
/// \brief Determine what sort of exception specification a defaulted
/// default constructor of a class will have, and whether the parameter
/// will be const.
ImplicitExceptionSpecification
ComputeDefaultedCopyCtorExceptionSpec(CXXMethodDecl *MD);
/// \brief Determine what sort of exception specification a defautled
/// copy assignment operator of a class will have, and whether the
/// parameter will be const.
ImplicitExceptionSpecification
ComputeDefaultedCopyAssignmentExceptionSpec(CXXMethodDecl *MD);
/// \brief Determine what sort of exception specification a defaulted move
/// constructor of a class will have.
ImplicitExceptionSpecification
ComputeDefaultedMoveCtorExceptionSpec(CXXMethodDecl *MD);
/// \brief Determine what sort of exception specification a defaulted move
/// assignment operator of a class will have.
ImplicitExceptionSpecification
ComputeDefaultedMoveAssignmentExceptionSpec(CXXMethodDecl *MD);
/// \brief Determine what sort of exception specification a defaulted
/// destructor of a class will have.
ImplicitExceptionSpecification
ComputeDefaultedDtorExceptionSpec(CXXMethodDecl *MD);
/// \brief Determine what sort of exception specification an inheriting
/// constructor of a class will have.
ImplicitExceptionSpecification
ComputeInheritingCtorExceptionSpec(CXXConstructorDecl *CD);
/// \brief Evaluate the implicit exception specification for a defaulted
/// special member function.
void EvaluateImplicitExceptionSpec(SourceLocation Loc, CXXMethodDecl *MD);
/// \brief Check the given exception-specification and update the
/// exception specification information with the results.
void checkExceptionSpecification(bool IsTopLevel,
ExceptionSpecificationType EST,
ArrayRef<ParsedType> DynamicExceptions,
ArrayRef<SourceRange> DynamicExceptionRanges,
Expr *NoexceptExpr,
SmallVectorImpl<QualType> &Exceptions,
FunctionProtoType::ExceptionSpecInfo &ESI);
/// \brief Determine if we're in a case where we need to (incorrectly) eagerly
/// parse an exception specification to work around a libstdc++ bug.
bool isLibstdcxxEagerExceptionSpecHack(const Declarator &D);
/// \brief Add an exception-specification to the given member function
/// (or member function template). The exception-specification was parsed
/// after the method itself was declared.
void actOnDelayedExceptionSpecification(Decl *Method,
ExceptionSpecificationType EST,
SourceRange SpecificationRange,
ArrayRef<ParsedType> DynamicExceptions,
ArrayRef<SourceRange> DynamicExceptionRanges,
Expr *NoexceptExpr);
/// \brief Determine if a special member function should have a deleted
/// definition when it is defaulted.
bool ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM,
bool Diagnose = false);
/// \brief Declare the implicit default constructor for the given class.
///
/// \param ClassDecl The class declaration into which the implicit
/// default constructor will be added.
///
/// \returns The implicitly-declared default constructor.
CXXConstructorDecl *DeclareImplicitDefaultConstructor(
CXXRecordDecl *ClassDecl);
/// DefineImplicitDefaultConstructor - Checks for feasibility of
/// defining this constructor as the default constructor.
void DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
CXXConstructorDecl *Constructor);
/// \brief Declare the implicit destructor for the given class.
///
/// \param ClassDecl The class declaration into which the implicit
/// destructor will be added.
///
/// \returns The implicitly-declared destructor.
CXXDestructorDecl *DeclareImplicitDestructor(CXXRecordDecl *ClassDecl);
/// DefineImplicitDestructor - Checks for feasibility of
/// defining this destructor as the default destructor.
void DefineImplicitDestructor(SourceLocation CurrentLocation,
CXXDestructorDecl *Destructor);
/// \brief Build an exception spec for destructors that don't have one.
///
/// C++11 says that user-defined destructors with no exception spec get one
/// that looks as if the destructor was implicitly declared.
void AdjustDestructorExceptionSpec(CXXRecordDecl *ClassDecl,
CXXDestructorDecl *Destructor);
/// \brief Declare all inheriting constructors for the given class.
///
/// \param ClassDecl The class declaration into which the inheriting
/// constructors will be added.
void DeclareInheritingConstructors(CXXRecordDecl *ClassDecl);
/// \brief Define the specified inheriting constructor.
void DefineInheritingConstructor(SourceLocation UseLoc,
CXXConstructorDecl *Constructor);
/// \brief Declare the implicit copy constructor for the given class.
///
/// \param ClassDecl The class declaration into which the implicit
/// copy constructor will be added.
///
/// \returns The implicitly-declared copy constructor.
CXXConstructorDecl *DeclareImplicitCopyConstructor(CXXRecordDecl *ClassDecl);
/// DefineImplicitCopyConstructor - Checks for feasibility of
/// defining this constructor as the copy constructor.
void DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
CXXConstructorDecl *Constructor);
/// \brief Declare the implicit move constructor for the given class.
///
/// \param ClassDecl The Class declaration into which the implicit
/// move constructor will be added.
///
/// \returns The implicitly-declared move constructor, or NULL if it wasn't
/// declared.
CXXConstructorDecl *DeclareImplicitMoveConstructor(CXXRecordDecl *ClassDecl);
/// DefineImplicitMoveConstructor - Checks for feasibility of
/// defining this constructor as the move constructor.
void DefineImplicitMoveConstructor(SourceLocation CurrentLocation,
CXXConstructorDecl *Constructor);
/// \brief Declare the implicit copy assignment operator for the given class.
///
/// \param ClassDecl The class declaration into which the implicit
/// copy assignment operator will be added.
///
/// \returns The implicitly-declared copy assignment operator.
CXXMethodDecl *DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl);
/// \brief Defines an implicitly-declared copy assignment operator.
void DefineImplicitCopyAssignment(SourceLocation CurrentLocation,
CXXMethodDecl *MethodDecl);
/// \brief Declare the implicit move assignment operator for the given class.
///
/// \param ClassDecl The Class declaration into which the implicit
/// move assignment operator will be added.
///
/// \returns The implicitly-declared move assignment operator, or NULL if it
/// wasn't declared.
CXXMethodDecl *DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl);
/// \brief Defines an implicitly-declared move assignment operator.
void DefineImplicitMoveAssignment(SourceLocation CurrentLocation,
CXXMethodDecl *MethodDecl);
/// \brief Force the declaration of any implicitly-declared members of this
/// class.
void ForceDeclarationOfImplicitMembers(CXXRecordDecl *Class);
/// \brief Determine whether the given function is an implicitly-deleted
/// special member function.
bool isImplicitlyDeleted(FunctionDecl *FD);
/// \brief Check whether 'this' shows up in the type of a static member
/// function after the (naturally empty) cv-qualifier-seq would be.
///
/// \returns true if an error occurred.
bool checkThisInStaticMemberFunctionType(CXXMethodDecl *Method);
/// \brief Whether this' shows up in the exception specification of a static
/// member function.
bool checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method);
/// \brief Check whether 'this' shows up in the attributes of the given
/// static member function.
///
/// \returns true if an error occurred.
bool checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method);
/// MaybeBindToTemporary - If the passed in expression has a record type with
/// a non-trivial destructor, this will return CXXBindTemporaryExpr. Otherwise
/// it simply returns the passed in expression.
ExprResult MaybeBindToTemporary(Expr *E);
bool CompleteConstructorCall(CXXConstructorDecl *Constructor,
MultiExprArg ArgsPtr,
SourceLocation Loc,
SmallVectorImpl<Expr*> &ConvertedArgs,
bool AllowExplicit = false,
bool IsListInitialization = false);
ParsedType getInheritingConstructorName(CXXScopeSpec &SS,
SourceLocation NameLoc,
IdentifierInfo &Name);
ParsedType getDestructorName(SourceLocation TildeLoc,
IdentifierInfo &II, SourceLocation NameLoc,
Scope *S, CXXScopeSpec &SS,
ParsedType ObjectType,
bool EnteringContext);
ParsedType getDestructorType(const DeclSpec& DS, ParsedType ObjectType);
// Checks that reinterpret casts don't have undefined behavior.
void CheckCompatibleReinterpretCast(QualType SrcType, QualType DestType,
bool IsDereference, SourceRange Range);
/// ActOnCXXNamedCast - Parse {dynamic,static,reinterpret,const}_cast's.
ExprResult ActOnCXXNamedCast(SourceLocation OpLoc,
tok::TokenKind Kind,
SourceLocation LAngleBracketLoc,
Declarator &D,
SourceLocation RAngleBracketLoc,
SourceLocation LParenLoc,
Expr *E,
SourceLocation RParenLoc);
ExprResult BuildCXXNamedCast(SourceLocation OpLoc,
tok::TokenKind Kind,
TypeSourceInfo *Ty,
Expr *E,
SourceRange AngleBrackets,
SourceRange Parens);
ExprResult BuildCXXTypeId(QualType TypeInfoType,
SourceLocation TypeidLoc,
TypeSourceInfo *Operand,
SourceLocation RParenLoc);
ExprResult BuildCXXTypeId(QualType TypeInfoType,
SourceLocation TypeidLoc,
Expr *Operand,
SourceLocation RParenLoc);
/// ActOnCXXTypeid - Parse typeid( something ).
ExprResult ActOnCXXTypeid(SourceLocation OpLoc,
SourceLocation LParenLoc, bool isType,
void *TyOrExpr,
SourceLocation RParenLoc);
ExprResult BuildCXXUuidof(QualType TypeInfoType,
SourceLocation TypeidLoc,
TypeSourceInfo *Operand,
SourceLocation RParenLoc);
ExprResult BuildCXXUuidof(QualType TypeInfoType,
SourceLocation TypeidLoc,
Expr *Operand,
SourceLocation RParenLoc);
/// ActOnCXXUuidof - Parse __uuidof( something ).
ExprResult ActOnCXXUuidof(SourceLocation OpLoc,
SourceLocation LParenLoc, bool isType,
void *TyOrExpr,
SourceLocation RParenLoc);
/// \brief Handle a C++1z fold-expression: ( expr op ... op expr ).
ExprResult ActOnCXXFoldExpr(SourceLocation LParenLoc, Expr *LHS,
tok::TokenKind Operator,
SourceLocation EllipsisLoc, Expr *RHS,
SourceLocation RParenLoc);
ExprResult BuildCXXFoldExpr(SourceLocation LParenLoc, Expr *LHS,
BinaryOperatorKind Operator,
SourceLocation EllipsisLoc, Expr *RHS,
SourceLocation RParenLoc);
ExprResult BuildEmptyCXXFoldExpr(SourceLocation EllipsisLoc,
BinaryOperatorKind Operator);
//// ActOnCXXThis - Parse 'this' pointer.
ExprResult ActOnCXXThis(SourceLocation loc);
/// \brief Try to retrieve the type of the 'this' pointer.
///
/// \returns The type of 'this', if possible. Otherwise, returns a NULL type.
QualType getCurrentThisType();
/// \brief When non-NULL, the C++ 'this' expression is allowed despite the
/// current context not being a non-static member function. In such cases,
/// this provides the type used for 'this'.
QualType CXXThisTypeOverride;
/// \brief RAII object used to temporarily allow the C++ 'this' expression
/// to be used, with the given qualifiers on the current class type.
class CXXThisScopeRAII {
Sema &S;
QualType OldCXXThisTypeOverride;
bool Enabled;
public:
/// \brief Introduce a new scope where 'this' may be allowed (when enabled),
/// using the given declaration (which is either a class template or a
/// class) along with the given qualifiers.
/// along with the qualifiers placed on '*this'.
CXXThisScopeRAII(Sema &S, Decl *ContextDecl, unsigned CXXThisTypeQuals,
bool Enabled = true);
~CXXThisScopeRAII();
};
/// \brief Make sure the value of 'this' is actually available in the current
/// context, if it is a potentially evaluated context.
///
/// \param Loc The location at which the capture of 'this' occurs.
///
/// \param Explicit Whether 'this' is explicitly captured in a lambda
/// capture list.
///
/// \param FunctionScopeIndexToStopAt If non-null, it points to the index
/// of the FunctionScopeInfo stack beyond which we do not attempt to capture.
/// This is useful when enclosing lambdas must speculatively capture
/// 'this' that may or may not be used in certain specializations of
/// a nested generic lambda (depending on whether the name resolves to
/// a non-static member function or a static function).
/// \return returns 'true' if failed, 'false' if success.
bool CheckCXXThisCapture(SourceLocation Loc, bool Explicit = false,
bool BuildAndDiagnose = true,
const unsigned *const FunctionScopeIndexToStopAt = nullptr);
/// \brief Determine whether the given type is the type of *this that is used
/// outside of the body of a member function for a type that is currently
/// being defined.
bool isThisOutsideMemberFunctionBody(QualType BaseType);
/// ActOnCXXBoolLiteral - Parse {true,false} literals.
ExprResult ActOnCXXBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind);
/// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals.
ExprResult ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind);
/// ActOnCXXNullPtrLiteral - Parse 'nullptr'.
ExprResult ActOnCXXNullPtrLiteral(SourceLocation Loc);
//// ActOnCXXThrow - Parse throw expressions.
ExprResult ActOnCXXThrow(Scope *S, SourceLocation OpLoc, Expr *expr);
ExprResult BuildCXXThrow(SourceLocation OpLoc, Expr *Ex,
bool IsThrownVarInScope);
bool CheckCXXThrowOperand(SourceLocation ThrowLoc, QualType ThrowTy, Expr *E);
/// ActOnCXXTypeConstructExpr - Parse construction of a specified type.
/// Can be interpreted either as function-style casting ("int(x)")
/// or class type construction ("ClassType(x,y,z)")
/// or creation of a value-initialized type ("int()").
ExprResult ActOnCXXTypeConstructExpr(ParsedType TypeRep,
SourceLocation LParenLoc,
MultiExprArg Exprs,
SourceLocation RParenLoc);
ExprResult BuildCXXTypeConstructExpr(TypeSourceInfo *Type,
SourceLocation LParenLoc,
MultiExprArg Exprs,
SourceLocation RParenLoc);
/// ActOnCXXNew - Parsed a C++ 'new' expression.
ExprResult ActOnCXXNew(SourceLocation StartLoc, bool UseGlobal,
SourceLocation PlacementLParen,
MultiExprArg PlacementArgs,
SourceLocation PlacementRParen,
SourceRange TypeIdParens, Declarator &D,
Expr *Initializer);
ExprResult BuildCXXNew(SourceRange Range, bool UseGlobal,
SourceLocation PlacementLParen,
MultiExprArg PlacementArgs,
SourceLocation PlacementRParen,
SourceRange TypeIdParens,
QualType AllocType,
TypeSourceInfo *AllocTypeInfo,
Expr *ArraySize,
SourceRange DirectInitRange,
Expr *Initializer,
bool TypeMayContainAuto = true);
bool CheckAllocatedType(QualType AllocType, SourceLocation Loc,
SourceRange R);
bool FindAllocationFunctions(SourceLocation StartLoc, SourceRange Range,
bool UseGlobal, QualType AllocType, bool IsArray,
MultiExprArg PlaceArgs,
FunctionDecl *&OperatorNew,
FunctionDecl *&OperatorDelete);
bool FindAllocationOverload(SourceLocation StartLoc, SourceRange Range,
DeclarationName Name, MultiExprArg Args,
DeclContext *Ctx,
bool AllowMissing, FunctionDecl *&Operator,
bool Diagnose = true);
void DeclareGlobalNewDelete();
void DeclareGlobalAllocationFunction(DeclarationName Name, QualType Return,
QualType Param1,
QualType Param2 = QualType(),
bool addRestrictAttr = false);
bool FindDeallocationFunction(SourceLocation StartLoc, CXXRecordDecl *RD,
DeclarationName Name, FunctionDecl* &Operator,
bool Diagnose = true);
FunctionDecl *FindUsualDeallocationFunction(SourceLocation StartLoc,
bool CanProvideSize,
DeclarationName Name);
/// ActOnCXXDelete - Parsed a C++ 'delete' expression
ExprResult ActOnCXXDelete(SourceLocation StartLoc,
bool UseGlobal, bool ArrayForm,
Expr *Operand);
DeclResult ActOnCXXConditionDeclaration(Scope *S, Declarator &D);
ExprResult CheckConditionVariable(VarDecl *ConditionVar,
SourceLocation StmtLoc,
bool ConvertToBoolean);
ExprResult ActOnNoexceptExpr(SourceLocation KeyLoc, SourceLocation LParen,
Expr *Operand, SourceLocation RParen);
ExprResult BuildCXXNoexceptExpr(SourceLocation KeyLoc, Expr *Operand,
SourceLocation RParen);
/// \brief Parsed one of the type trait support pseudo-functions.
ExprResult ActOnTypeTrait(TypeTrait Kind, SourceLocation KWLoc,
ArrayRef<ParsedType> Args,
SourceLocation RParenLoc);
ExprResult BuildTypeTrait(TypeTrait Kind, SourceLocation KWLoc,
ArrayRef<TypeSourceInfo *> Args,
SourceLocation RParenLoc);
/// ActOnArrayTypeTrait - Parsed one of the bianry type trait support
/// pseudo-functions.
ExprResult ActOnArrayTypeTrait(ArrayTypeTrait ATT,
SourceLocation KWLoc,
ParsedType LhsTy,
Expr *DimExpr,
SourceLocation RParen);
ExprResult BuildArrayTypeTrait(ArrayTypeTrait ATT,
SourceLocation KWLoc,
TypeSourceInfo *TSInfo,
Expr *DimExpr,
SourceLocation RParen);
/// ActOnExpressionTrait - Parsed one of the unary type trait support
/// pseudo-functions.
ExprResult ActOnExpressionTrait(ExpressionTrait OET,
SourceLocation KWLoc,
Expr *Queried,
SourceLocation RParen);
ExprResult BuildExpressionTrait(ExpressionTrait OET,
SourceLocation KWLoc,
Expr *Queried,
SourceLocation RParen);
ExprResult ActOnStartCXXMemberReference(Scope *S,
Expr *Base,
SourceLocation OpLoc,
tok::TokenKind OpKind,
ParsedType &ObjectType,
bool &MayBePseudoDestructor);
ExprResult BuildPseudoDestructorExpr(Expr *Base,
SourceLocation OpLoc,
tok::TokenKind OpKind,
const CXXScopeSpec &SS,
TypeSourceInfo *ScopeType,
SourceLocation CCLoc,
SourceLocation TildeLoc,
PseudoDestructorTypeStorage DestroyedType);
ExprResult ActOnPseudoDestructorExpr(Scope *S, Expr *Base,
SourceLocation OpLoc,
tok::TokenKind OpKind,
CXXScopeSpec &SS,
UnqualifiedId &FirstTypeName,
SourceLocation CCLoc,
SourceLocation TildeLoc,
UnqualifiedId &SecondTypeName);
ExprResult ActOnPseudoDestructorExpr(Scope *S, Expr *Base,
SourceLocation OpLoc,
tok::TokenKind OpKind,
SourceLocation TildeLoc,
const DeclSpec& DS);
/// MaybeCreateExprWithCleanups - If the current full-expression
/// requires any cleanups, surround it with a ExprWithCleanups node.
/// Otherwise, just returns the passed-in expression.
Expr *MaybeCreateExprWithCleanups(Expr *SubExpr);
Stmt *MaybeCreateStmtWithCleanups(Stmt *SubStmt);
ExprResult MaybeCreateExprWithCleanups(ExprResult SubExpr);
ExprResult ActOnFinishFullExpr(Expr *Expr) {
return ActOnFinishFullExpr(Expr, Expr ? Expr->getExprLoc()
: SourceLocation());
}
ExprResult ActOnFinishFullExpr(Expr *Expr, SourceLocation CC,
bool DiscardedValue = false,
bool IsConstexpr = false,
bool IsLambdaInitCaptureInitializer = false);
StmtResult ActOnFinishFullStmt(Stmt *Stmt);
// Marks SS invalid if it represents an incomplete type.
bool RequireCompleteDeclContext(CXXScopeSpec &SS, DeclContext *DC);
DeclContext *computeDeclContext(QualType T);
DeclContext *computeDeclContext(const CXXScopeSpec &SS,
bool EnteringContext = false);
bool isDependentScopeSpecifier(const CXXScopeSpec &SS);
CXXRecordDecl *getCurrentInstantiationOf(NestedNameSpecifier *NNS);
/// \brief The parser has parsed a global nested-name-specifier '::'.
///
/// \param CCLoc The location of the '::'.
///
/// \param SS The nested-name-specifier, which will be updated in-place
/// to reflect the parsed nested-name-specifier.
///
/// \returns true if an error occurred, false otherwise.
bool ActOnCXXGlobalScopeSpecifier(SourceLocation CCLoc, CXXScopeSpec &SS);
/// \brief The parser has parsed a '__super' nested-name-specifier.
///
/// \param SuperLoc The location of the '__super' keyword.
///
/// \param ColonColonLoc The location of the '::'.
///
/// \param SS The nested-name-specifier, which will be updated in-place
/// to reflect the parsed nested-name-specifier.
///
/// \returns true if an error occurred, false otherwise.
bool ActOnSuperScopeSpecifier(SourceLocation SuperLoc,
SourceLocation ColonColonLoc, CXXScopeSpec &SS);
bool isAcceptableNestedNameSpecifier(const NamedDecl *SD,
bool *CanCorrect = nullptr);
NamedDecl *FindFirstQualifierInScope(Scope *S, NestedNameSpecifier *NNS);
bool isNonTypeNestedNameSpecifier(Scope *S, CXXScopeSpec &SS,
SourceLocation IdLoc,
IdentifierInfo &II,
ParsedType ObjectType);
bool BuildCXXNestedNameSpecifier(Scope *S,
IdentifierInfo &Identifier,
SourceLocation IdentifierLoc,
SourceLocation CCLoc,
QualType ObjectType,
bool EnteringContext,
CXXScopeSpec &SS,
NamedDecl *ScopeLookupResult,
bool ErrorRecoveryLookup,
bool *IsCorrectedToColon = nullptr);
/// \brief The parser has parsed a nested-name-specifier 'identifier::'.
///
/// \param S The scope in which this nested-name-specifier occurs.
///
/// \param Identifier The identifier preceding the '::'.
///
/// \param IdentifierLoc The location of the identifier.
///
/// \param CCLoc The location of the '::'.
///
/// \param ObjectType The type of the object, if we're parsing
/// nested-name-specifier in a member access expression.
///
/// \param EnteringContext Whether we're entering the context nominated by
/// this nested-name-specifier.
///
/// \param SS The nested-name-specifier, which is both an input
/// parameter (the nested-name-specifier before this type) and an
/// output parameter (containing the full nested-name-specifier,
/// including this new type).
///
/// \param ErrorRecoveryLookup If true, then this method is called to improve
/// error recovery. In this case do not emit error message.
///
/// \param IsCorrectedToColon If not null, suggestions to replace '::' -> ':'
/// are allowed. The bool value pointed by this parameter is set to 'true'
/// if the identifier is treated as if it was followed by ':', not '::'.
///
/// \returns true if an error occurred, false otherwise.
bool ActOnCXXNestedNameSpecifier(Scope *S,
IdentifierInfo &Identifier,
SourceLocation IdentifierLoc,
SourceLocation CCLoc,
ParsedType ObjectType,
bool EnteringContext,
CXXScopeSpec &SS,
bool ErrorRecoveryLookup = false,
bool *IsCorrectedToColon = nullptr);
ExprResult ActOnDecltypeExpression(Expr *E);
bool ActOnCXXNestedNameSpecifierDecltype(CXXScopeSpec &SS,
const DeclSpec &DS,
SourceLocation ColonColonLoc);
bool IsInvalidUnlessNestedName(Scope *S, CXXScopeSpec &SS,
IdentifierInfo &Identifier,
SourceLocation IdentifierLoc,
SourceLocation ColonLoc,
ParsedType ObjectType,
bool EnteringContext);
/// \brief The parser has parsed a nested-name-specifier
/// 'template[opt] template-name < template-args >::'.
///
/// \param S The scope in which this nested-name-specifier occurs.
///
/// \param SS The nested-name-specifier, which is both an input
/// parameter (the nested-name-specifier before this type) and an
/// output parameter (containing the full nested-name-specifier,
/// including this new type).
///
/// \param TemplateKWLoc the location of the 'template' keyword, if any.
/// \param TemplateName the template name.
/// \param TemplateNameLoc The location of the template name.
/// \param LAngleLoc The location of the opening angle bracket ('<').
/// \param TemplateArgs The template arguments.
/// \param RAngleLoc The location of the closing angle bracket ('>').
/// \param CCLoc The location of the '::'.
///
/// \param EnteringContext Whether we're entering the context of the
/// nested-name-specifier.
///
///
/// \returns true if an error occurred, false otherwise.
bool ActOnCXXNestedNameSpecifier(Scope *S,
CXXScopeSpec &SS,
SourceLocation TemplateKWLoc,
TemplateTy TemplateName,
SourceLocation TemplateNameLoc,
SourceLocation LAngleLoc,
ASTTemplateArgsPtr TemplateArgs,
SourceLocation RAngleLoc,
SourceLocation CCLoc,
bool EnteringContext);
/// \brief Given a C++ nested-name-specifier, produce an annotation value
/// that the parser can use later to reconstruct the given
/// nested-name-specifier.
///
/// \param SS A nested-name-specifier.
///
/// \returns A pointer containing all of the information in the
/// nested-name-specifier \p SS.
void *SaveNestedNameSpecifierAnnotation(CXXScopeSpec &SS);
/// \brief Given an annotation pointer for a nested-name-specifier, restore
/// the nested-name-specifier structure.
///
/// \param Annotation The annotation pointer, produced by
/// \c SaveNestedNameSpecifierAnnotation().
///
/// \param AnnotationRange The source range corresponding to the annotation.
///
/// \param SS The nested-name-specifier that will be updated with the contents
/// of the annotation pointer.
void RestoreNestedNameSpecifierAnnotation(void *Annotation,
SourceRange AnnotationRange,
CXXScopeSpec &SS);
bool ShouldEnterDeclaratorScope(Scope *S, const CXXScopeSpec &SS);
/// ActOnCXXEnterDeclaratorScope - Called when a C++ scope specifier (global
/// scope or nested-name-specifier) is parsed, part of a declarator-id.
/// After this method is called, according to [C++ 3.4.3p3], names should be
/// looked up in the declarator-id's scope, until the declarator is parsed and
/// ActOnCXXExitDeclaratorScope is called.
/// The 'SS' should be a non-empty valid CXXScopeSpec.
bool ActOnCXXEnterDeclaratorScope(Scope *S, CXXScopeSpec &SS);
/// ActOnCXXExitDeclaratorScope - Called when a declarator that previously
/// invoked ActOnCXXEnterDeclaratorScope(), is finished. 'SS' is the same
/// CXXScopeSpec that was passed to ActOnCXXEnterDeclaratorScope as well.
/// Used to indicate that names should revert to being looked up in the
/// defining scope.
void ActOnCXXExitDeclaratorScope(Scope *S, const CXXScopeSpec &SS);
/// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse an
/// initializer for the declaration 'Dcl'.
/// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
/// static data member of class X, names should be looked up in the scope of
/// class X.
void ActOnCXXEnterDeclInitializer(Scope *S, Decl *Dcl);
/// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an
/// initializer for the declaration 'Dcl'.
void ActOnCXXExitDeclInitializer(Scope *S, Decl *Dcl);
/// \brief Create a new lambda closure type.
CXXRecordDecl *createLambdaClosureType(SourceRange IntroducerRange,
TypeSourceInfo *Info,
bool KnownDependent,
LambdaCaptureDefault CaptureDefault);
/// \brief Start the definition of a lambda expression.
CXXMethodDecl *startLambdaDefinition(CXXRecordDecl *Class,
SourceRange IntroducerRange,
TypeSourceInfo *MethodType,
SourceLocation EndLoc,
ArrayRef<ParmVarDecl *> Params);
/// \brief Endow the lambda scope info with the relevant properties.
void buildLambdaScope(sema::LambdaScopeInfo *LSI,
CXXMethodDecl *CallOperator,
SourceRange IntroducerRange,
LambdaCaptureDefault CaptureDefault,
SourceLocation CaptureDefaultLoc,
bool ExplicitParams,
bool ExplicitResultType,
bool Mutable);
/// \brief Perform initialization analysis of the init-capture and perform
/// any implicit conversions such as an lvalue-to-rvalue conversion if
/// not being used to initialize a reference.
QualType performLambdaInitCaptureInitialization(SourceLocation Loc,
bool ByRef, IdentifierInfo *Id, Expr *&Init);
/// \brief Create a dummy variable within the declcontext of the lambda's
/// call operator, for name lookup purposes for a lambda init capture.
///
/// CodeGen handles emission of lambda captures, ignoring these dummy
/// variables appropriately.
VarDecl *createLambdaInitCaptureVarDecl(SourceLocation Loc,
QualType InitCaptureType, IdentifierInfo *Id, Expr *Init);
/// \brief Build the implicit field for an init-capture.
FieldDecl *buildInitCaptureField(sema::LambdaScopeInfo *LSI, VarDecl *Var);
/// \brief Note that we have finished the explicit captures for the
/// given lambda.
void finishLambdaExplicitCaptures(sema::LambdaScopeInfo *LSI);
/// \brief Introduce the lambda parameters into scope.
void addLambdaParameters(CXXMethodDecl *CallOperator, Scope *CurScope);
/// \brief Deduce a block or lambda's return type based on the return
/// statements present in the body.
void deduceClosureReturnType(sema::CapturingScopeInfo &CSI);
/// ActOnStartOfLambdaDefinition - This is called just before we start
/// parsing the body of a lambda; it analyzes the explicit captures and
/// arguments, and sets up various data-structures for the body of the
/// lambda.
void ActOnStartOfLambdaDefinition(LambdaIntroducer &Intro,
Declarator &ParamInfo, Scope *CurScope);
/// ActOnLambdaError - If there is an error parsing a lambda, this callback
/// is invoked to pop the information about the lambda.
void ActOnLambdaError(SourceLocation StartLoc, Scope *CurScope,
bool IsInstantiation = false);
/// ActOnLambdaExpr - This is called when the body of a lambda expression
/// was successfully completed.
ExprResult ActOnLambdaExpr(SourceLocation StartLoc, Stmt *Body,
Scope *CurScope);
/// \brief Complete a lambda-expression having processed and attached the
/// lambda body.
ExprResult BuildLambdaExpr(SourceLocation StartLoc, SourceLocation EndLoc,
sema::LambdaScopeInfo *LSI);
/// \brief Define the "body" of the conversion from a lambda object to a
/// function pointer.
///
/// This routine doesn't actually define a sensible body; rather, it fills
/// in the initialization expression needed to copy the lambda object into
/// the block, and IR generation actually generates the real body of the
/// block pointer conversion.
void DefineImplicitLambdaToFunctionPointerConversion(
SourceLocation CurrentLoc, CXXConversionDecl *Conv);
/// \brief Define the "body" of the conversion from a lambda object to a
/// block pointer.
///
/// This routine doesn't actually define a sensible body; rather, it fills
/// in the initialization expression needed to copy the lambda object into
/// the block, and IR generation actually generates the real body of the
/// block pointer conversion.
void DefineImplicitLambdaToBlockPointerConversion(SourceLocation CurrentLoc,
CXXConversionDecl *Conv);
ExprResult BuildBlockForLambdaConversion(SourceLocation CurrentLocation,
SourceLocation ConvLocation,
CXXConversionDecl *Conv,
Expr *Src);
// ParseObjCStringLiteral - Parse Objective-C string literals.
ExprResult ParseObjCStringLiteral(SourceLocation *AtLocs,
Expr **Strings,
unsigned NumStrings);
ExprResult BuildObjCStringLiteral(SourceLocation AtLoc, StringLiteral *S);
/// BuildObjCNumericLiteral - builds an ObjCBoxedExpr AST node for the
/// numeric literal expression. Type of the expression will be "NSNumber *"
/// or "id" if NSNumber is unavailable.
ExprResult BuildObjCNumericLiteral(SourceLocation AtLoc, Expr *Number);
ExprResult ActOnObjCBoolLiteral(SourceLocation AtLoc, SourceLocation ValueLoc,
bool Value);
ExprResult BuildObjCArrayLiteral(SourceRange SR, MultiExprArg Elements);
/// BuildObjCBoxedExpr - builds an ObjCBoxedExpr AST node for the
/// '@' prefixed parenthesized expression. The type of the expression will
/// either be "NSNumber *", "NSString *" or "NSValue *" depending on the type
/// of ValueType, which is allowed to be a built-in numeric type, "char *",
/// "const char *" or C structure with attribute 'objc_boxable'.
ExprResult BuildObjCBoxedExpr(SourceRange SR, Expr *ValueExpr);
ExprResult BuildObjCSubscriptExpression(SourceLocation RB, Expr *BaseExpr,
Expr *IndexExpr,
ObjCMethodDecl *getterMethod,
ObjCMethodDecl *setterMethod);
ExprResult BuildObjCDictionaryLiteral(SourceRange SR,
ObjCDictionaryElement *Elements,
unsigned NumElements);
ExprResult BuildObjCEncodeExpression(SourceLocation AtLoc,
TypeSourceInfo *EncodedTypeInfo,
SourceLocation RParenLoc);
ExprResult BuildCXXMemberCallExpr(Expr *Exp, NamedDecl *FoundDecl,
CXXConversionDecl *Method,
bool HadMultipleCandidates);
ExprResult ParseObjCEncodeExpression(SourceLocation AtLoc,
SourceLocation EncodeLoc,
SourceLocation LParenLoc,
ParsedType Ty,
SourceLocation RParenLoc);
/// ParseObjCSelectorExpression - Build selector expression for \@selector
ExprResult ParseObjCSelectorExpression(Selector Sel,
SourceLocation AtLoc,
SourceLocation SelLoc,
SourceLocation LParenLoc,
SourceLocation RParenLoc,
bool WarnMultipleSelectors);
/// ParseObjCProtocolExpression - Build protocol expression for \@protocol
ExprResult ParseObjCProtocolExpression(IdentifierInfo * ProtocolName,
SourceLocation AtLoc,
SourceLocation ProtoLoc,
SourceLocation LParenLoc,
SourceLocation ProtoIdLoc,
SourceLocation RParenLoc);
//===--------------------------------------------------------------------===//
// C++ Declarations
//
Decl *ActOnStartLinkageSpecification(Scope *S,
SourceLocation ExternLoc,
Expr *LangStr,
SourceLocation LBraceLoc);
Decl *ActOnFinishLinkageSpecification(Scope *S,
Decl *LinkageSpec,
SourceLocation RBraceLoc);
//===--------------------------------------------------------------------===//
// C++ Classes
//
bool isCurrentClassName(const IdentifierInfo &II, Scope *S,
const CXXScopeSpec *SS = nullptr);
bool isCurrentClassNameTypo(IdentifierInfo *&II, const CXXScopeSpec *SS);
bool ActOnAccessSpecifier(AccessSpecifier Access,
SourceLocation ASLoc,
SourceLocation ColonLoc,
AttributeList *Attrs = nullptr);
NamedDecl *ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS,
Declarator &D,
MultiTemplateParamsArg TemplateParameterLists,
Expr *BitfieldWidth, const VirtSpecifiers &VS,
InClassInitStyle InitStyle);
void ActOnStartCXXInClassMemberInitializer();
void ActOnFinishCXXInClassMemberInitializer(Decl *VarDecl,
SourceLocation EqualLoc,
Expr *Init);
MemInitResult ActOnMemInitializer(Decl *ConstructorD,
Scope *S,
CXXScopeSpec &SS,
IdentifierInfo *MemberOrBase,
ParsedType TemplateTypeTy,
const DeclSpec &DS,
SourceLocation IdLoc,
SourceLocation LParenLoc,
ArrayRef<Expr *> Args,
SourceLocation RParenLoc,
SourceLocation EllipsisLoc);
MemInitResult ActOnMemInitializer(Decl *ConstructorD,
Scope *S,
CXXScopeSpec &SS,
IdentifierInfo *MemberOrBase,
ParsedType TemplateTypeTy,
const DeclSpec &DS,
SourceLocation IdLoc,
Expr *InitList,
SourceLocation EllipsisLoc);
MemInitResult BuildMemInitializer(Decl *ConstructorD,
Scope *S,
CXXScopeSpec &SS,
IdentifierInfo *MemberOrBase,
ParsedType TemplateTypeTy,
const DeclSpec &DS,
SourceLocation IdLoc,
Expr *Init,
SourceLocation EllipsisLoc);
MemInitResult BuildMemberInitializer(ValueDecl *Member,
Expr *Init,
SourceLocation IdLoc);
MemInitResult BuildBaseInitializer(QualType BaseType,
TypeSourceInfo *BaseTInfo,
Expr *Init,
CXXRecordDecl *ClassDecl,
SourceLocation EllipsisLoc);
MemInitResult BuildDelegatingInitializer(TypeSourceInfo *TInfo,
Expr *Init,
CXXRecordDecl *ClassDecl);
bool SetDelegatingInitializer(CXXConstructorDecl *Constructor,
CXXCtorInitializer *Initializer);
bool SetCtorInitializers(CXXConstructorDecl *Constructor, bool AnyErrors,
ArrayRef<CXXCtorInitializer *> Initializers = None);
void SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation);
/// MarkBaseAndMemberDestructorsReferenced - Given a record decl,
/// mark all the non-trivial destructors of its members and bases as
/// referenced.
void MarkBaseAndMemberDestructorsReferenced(SourceLocation Loc,
CXXRecordDecl *Record);
/// \brief The list of classes whose vtables have been used within
/// this translation unit, and the source locations at which the
/// first use occurred.
typedef std::pair<CXXRecordDecl*, SourceLocation> VTableUse;
/// \brief The list of vtables that are required but have not yet been
/// materialized.
SmallVector<VTableUse, 16> VTableUses;
/// \brief The set of classes whose vtables have been used within
/// this translation unit, and a bit that will be true if the vtable is
/// required to be emitted (otherwise, it should be emitted only if needed
/// by code generation).
llvm::DenseMap<CXXRecordDecl *, bool> VTablesUsed;
/// \brief Load any externally-stored vtable uses.
void LoadExternalVTableUses();
/// \brief Note that the vtable for the given class was used at the
/// given location.
void MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class,
bool DefinitionRequired = false);
/// \brief Mark the exception specifications of all virtual member functions
/// in the given class as needed.
void MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc,
const CXXRecordDecl *RD);
/// MarkVirtualMembersReferenced - Will mark all members of the given
/// CXXRecordDecl referenced.
void MarkVirtualMembersReferenced(SourceLocation Loc,
const CXXRecordDecl *RD);
/// \brief Define all of the vtables that have been used in this
/// translation unit and reference any virtual members used by those
/// vtables.
///
/// \returns true if any work was done, false otherwise.
bool DefineUsedVTables();
void AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl);
void ActOnMemInitializers(Decl *ConstructorDecl,
SourceLocation ColonLoc,
ArrayRef<CXXCtorInitializer*> MemInits,
bool AnyErrors);
void checkClassLevelDLLAttribute(CXXRecordDecl *Class);
void propagateDLLAttrToBaseClassTemplate(
CXXRecordDecl *Class, Attr *ClassAttr,
ClassTemplateSpecializationDecl *BaseTemplateSpec,
SourceLocation BaseLoc);
void CheckCompletedCXXClass(CXXRecordDecl *Record);
void ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc,
Decl *TagDecl,
SourceLocation LBrac,
SourceLocation RBrac,
AttributeList *AttrList);
void ActOnFinishCXXMemberDecls();
void ActOnFinishCXXMemberDefaultArgs(Decl *D);
void ActOnReenterCXXMethodParameter(Scope *S, ParmVarDecl *Param);
unsigned ActOnReenterTemplateScope(Scope *S, Decl *Template);
void ActOnStartDelayedMemberDeclarations(Scope *S, Decl *Record);
void ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *Method);
void ActOnDelayedCXXMethodParameter(Scope *S, Decl *Param);
void ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *Record);
void ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *Method);
void ActOnFinishDelayedMemberInitializers(Decl *Record);
void MarkAsLateParsedTemplate(FunctionDecl *FD, Decl *FnD,
CachedTokens &Toks);
void UnmarkAsLateParsedTemplate(FunctionDecl *FD);
bool IsInsideALocalClassWithinATemplateFunction();
Decl *ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc,
Expr *AssertExpr,
Expr *AssertMessageExpr,
SourceLocation RParenLoc);
Decl *BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc,
Expr *AssertExpr,
StringLiteral *AssertMessageExpr,
SourceLocation RParenLoc,
bool Failed);
FriendDecl *CheckFriendTypeDecl(SourceLocation LocStart,
SourceLocation FriendLoc,
TypeSourceInfo *TSInfo);
Decl *ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
MultiTemplateParamsArg TemplateParams);
NamedDecl *ActOnFriendFunctionDecl(Scope *S, Declarator &D,
MultiTemplateParamsArg TemplateParams);
QualType CheckConstructorDeclarator(Declarator &D, QualType R,
StorageClass& SC);
void CheckConstructor(CXXConstructorDecl *Constructor);
QualType CheckDestructorDeclarator(Declarator &D, QualType R,
StorageClass& SC);
bool CheckDestructor(CXXDestructorDecl *Destructor);
void CheckConversionDeclarator(Declarator &D, QualType &R,
StorageClass& SC);
Decl *ActOnConversionDeclarator(CXXConversionDecl *Conversion);
void CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD);
void CheckExplicitlyDefaultedMemberExceptionSpec(CXXMethodDecl *MD,
const FunctionProtoType *T);
void CheckDelayedMemberExceptionSpecs();
//===--------------------------------------------------------------------===//
// C++ Derived Classes
//
/// ActOnBaseSpecifier - Parsed a base specifier
CXXBaseSpecifier *CheckBaseSpecifier(CXXRecordDecl *Class,
SourceRange SpecifierRange,
bool Virtual, AccessSpecifier Access,
TypeSourceInfo *TInfo,
SourceLocation EllipsisLoc);
BaseResult ActOnBaseSpecifier(Decl *classdecl,
SourceRange SpecifierRange,
ParsedAttributes &Attrs,
bool Virtual, AccessSpecifier Access,
ParsedType basetype,
SourceLocation BaseLoc,
SourceLocation EllipsisLoc);
bool AttachBaseSpecifiers(CXXRecordDecl *Class, CXXBaseSpecifier **Bases,
unsigned NumBases);
void ActOnBaseSpecifiers(Decl *ClassDecl, CXXBaseSpecifier **Bases,
unsigned NumBases);
bool IsDerivedFrom(QualType Derived, QualType Base);
bool IsDerivedFrom(QualType Derived, QualType Base, CXXBasePaths &Paths);
// FIXME: I don't like this name.
void BuildBasePathArray(const CXXBasePaths &Paths, CXXCastPath &BasePath);
bool CheckDerivedToBaseConversion(QualType Derived, QualType Base,
SourceLocation Loc, SourceRange Range,
CXXCastPath *BasePath = nullptr,
bool IgnoreAccess = false);
bool CheckDerivedToBaseConversion(QualType Derived, QualType Base,
unsigned InaccessibleBaseID,
unsigned AmbigiousBaseConvID,
SourceLocation Loc, SourceRange Range,
DeclarationName Name,
CXXCastPath *BasePath);
std::string getAmbiguousPathsDisplayString(CXXBasePaths &Paths);
bool CheckOverridingFunctionAttributes(const CXXMethodDecl *New,
const CXXMethodDecl *Old);
/// CheckOverridingFunctionReturnType - Checks whether the return types are
/// covariant, according to C++ [class.virtual]p5.
bool CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
const CXXMethodDecl *Old);
/// CheckOverridingFunctionExceptionSpec - Checks whether the exception
/// spec is a subset of base spec.
bool CheckOverridingFunctionExceptionSpec(const CXXMethodDecl *New,
const CXXMethodDecl *Old);
bool CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange);
/// CheckOverrideControl - Check C++11 override control semantics.
void CheckOverrideControl(NamedDecl *D);
/// DiagnoseAbsenceOfOverrideControl - Diagnose if 'override' keyword was
/// not used in the declaration of an overriding method.
void DiagnoseAbsenceOfOverrideControl(NamedDecl *D);
/// CheckForFunctionMarkedFinal - Checks whether a virtual member function
/// overrides a virtual member function marked 'final', according to
/// C++11 [class.virtual]p4.
bool CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New,
const CXXMethodDecl *Old);
//===--------------------------------------------------------------------===//
// C++ Access Control
//
enum AccessResult {
AR_accessible,
AR_inaccessible,
AR_dependent,
AR_delayed
};
bool SetMemberAccessSpecifier(NamedDecl *MemberDecl,
NamedDecl *PrevMemberDecl,
AccessSpecifier LexicalAS);
AccessResult CheckUnresolvedMemberAccess(UnresolvedMemberExpr *E,
DeclAccessPair FoundDecl);
AccessResult CheckUnresolvedLookupAccess(UnresolvedLookupExpr *E,
DeclAccessPair FoundDecl);
AccessResult CheckAllocationAccess(SourceLocation OperatorLoc,
SourceRange PlacementRange,
CXXRecordDecl *NamingClass,
DeclAccessPair FoundDecl,
bool Diagnose = true);
AccessResult CheckConstructorAccess(SourceLocation Loc,
CXXConstructorDecl *D,
const InitializedEntity &Entity,
AccessSpecifier Access,
bool IsCopyBindingRefToTemp = false);
AccessResult CheckConstructorAccess(SourceLocation Loc,
CXXConstructorDecl *D,
const InitializedEntity &Entity,
AccessSpecifier Access,
const PartialDiagnostic &PDiag);
AccessResult CheckDestructorAccess(SourceLocation Loc,
CXXDestructorDecl *Dtor,
const PartialDiagnostic &PDiag,
QualType objectType = QualType());
AccessResult CheckFriendAccess(NamedDecl *D);
AccessResult CheckMemberAccess(SourceLocation UseLoc,
CXXRecordDecl *NamingClass,
DeclAccessPair Found);
AccessResult CheckMemberOperatorAccess(SourceLocation Loc,
Expr *ObjectExpr,
Expr *ArgExpr,
DeclAccessPair FoundDecl);
AccessResult CheckAddressOfMemberAccess(Expr *OvlExpr,
DeclAccessPair FoundDecl);
AccessResult CheckBaseClassAccess(SourceLocation AccessLoc,
QualType Base, QualType Derived,
const CXXBasePath &Path,
unsigned DiagID,
bool ForceCheck = false,
bool ForceUnprivileged = false);
void CheckLookupAccess(const LookupResult &R);
bool IsSimplyAccessible(NamedDecl *decl, DeclContext *Ctx);
bool isSpecialMemberAccessibleForDeletion(CXXMethodDecl *decl,
AccessSpecifier access,
QualType objectType);
void HandleDependentAccessCheck(const DependentDiagnostic &DD,
const MultiLevelTemplateArgumentList &TemplateArgs);
void PerformDependentDiagnostics(const DeclContext *Pattern,
const MultiLevelTemplateArgumentList &TemplateArgs);
void HandleDelayedAccessCheck(sema::DelayedDiagnostic &DD, Decl *Ctx);
/// \brief When true, access checking violations are treated as SFINAE
/// failures rather than hard errors.
bool AccessCheckingSFINAE;
enum AbstractDiagSelID {
AbstractNone = -1,
AbstractReturnType,
AbstractParamType,
AbstractVariableType,
AbstractFieldType,
AbstractIvarType,
AbstractSynthesizedIvarType,
AbstractArrayType
};
bool RequireNonAbstractType(SourceLocation Loc, QualType T,
TypeDiagnoser &Diagnoser);
template <typename... Ts>
bool RequireNonAbstractType(SourceLocation Loc, QualType T, unsigned DiagID,
const Ts &...Args) {
BoundTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...);
return RequireNonAbstractType(Loc, T, Diagnoser);
}
void DiagnoseAbstractType(const CXXRecordDecl *RD);
bool RequireNonAbstractType(SourceLocation Loc, QualType T, unsigned DiagID,
AbstractDiagSelID SelID = AbstractNone);
//===--------------------------------------------------------------------===//
// C++ Overloaded Operators [C++ 13.5]
//
bool CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl);
bool CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl);
//===--------------------------------------------------------------------===//
// C++ Templates [C++ 14]
//
void FilterAcceptableTemplateNames(LookupResult &R,
bool AllowFunctionTemplates = true);
bool hasAnyAcceptableTemplateNames(LookupResult &R,
bool AllowFunctionTemplates = true);
void LookupTemplateName(LookupResult &R, Scope *S, CXXScopeSpec &SS,
QualType ObjectType, bool EnteringContext,
bool &MemberOfUnknownSpecialization);
TemplateNameKind isTemplateName(Scope *S,
CXXScopeSpec &SS,
bool hasTemplateKeyword,
UnqualifiedId &Name,
ParsedType ObjectType,
bool EnteringContext,
TemplateTy &Template,
bool &MemberOfUnknownSpecialization);
bool DiagnoseUnknownTemplateName(const IdentifierInfo &II,
SourceLocation IILoc,
Scope *S,
const CXXScopeSpec *SS,
TemplateTy &SuggestedTemplate,
TemplateNameKind &SuggestedKind);
void DiagnoseTemplateParameterShadow(SourceLocation Loc, Decl *PrevDecl);
TemplateDecl *AdjustDeclIfTemplate(Decl *&Decl);
Decl *ActOnTypeParameter(Scope *S, bool Typename,
SourceLocation EllipsisLoc,
SourceLocation KeyLoc,
IdentifierInfo *ParamName,
SourceLocation ParamNameLoc,
unsigned Depth, unsigned Position,
SourceLocation EqualLoc,
ParsedType DefaultArg);
QualType CheckNonTypeTemplateParameterType(QualType T, SourceLocation Loc);
Decl *ActOnNonTypeTemplateParameter(Scope *S, Declarator &D,
unsigned Depth,
unsigned Position,
SourceLocation EqualLoc,
Expr *DefaultArg);
Decl *ActOnTemplateTemplateParameter(Scope *S,
SourceLocation TmpLoc,
TemplateParameterList *Params,
SourceLocation EllipsisLoc,
IdentifierInfo *ParamName,
SourceLocation ParamNameLoc,
unsigned Depth,
unsigned Position,
SourceLocation EqualLoc,
ParsedTemplateArgument DefaultArg);
TemplateParameterList *
ActOnTemplateParameterList(unsigned Depth,
SourceLocation ExportLoc,
SourceLocation TemplateLoc,
SourceLocation LAngleLoc,
Decl **Params, unsigned NumParams,
SourceLocation RAngleLoc);
/// \brief The context in which we are checking a template parameter list.
enum TemplateParamListContext {
TPC_ClassTemplate,
TPC_VarTemplate,
TPC_FunctionTemplate,
TPC_ClassTemplateMember,
TPC_FriendClassTemplate,
TPC_FriendFunctionTemplate,
TPC_FriendFunctionTemplateDefinition,
TPC_TypeAliasTemplate
};
bool CheckTemplateParameterList(TemplateParameterList *NewParams,
TemplateParameterList *OldParams,
TemplateParamListContext TPC);
TemplateParameterList *MatchTemplateParametersToScopeSpecifier(
SourceLocation DeclStartLoc, SourceLocation DeclLoc,
const CXXScopeSpec &SS, TemplateIdAnnotation *TemplateId,
ArrayRef<TemplateParameterList *> ParamLists,
bool IsFriend, bool &IsExplicitSpecialization, bool &Invalid);
DeclResult CheckClassTemplate(Scope *S, unsigned TagSpec, TagUseKind TUK,
SourceLocation KWLoc, CXXScopeSpec &SS,
IdentifierInfo *Name, SourceLocation NameLoc,
AttributeList *Attr,
TemplateParameterList *TemplateParams,
AccessSpecifier AS,
SourceLocation ModulePrivateLoc,
SourceLocation FriendLoc,
unsigned NumOuterTemplateParamLists,
TemplateParameterList **OuterTemplateParamLists,
SkipBodyInfo *SkipBody = nullptr);
void translateTemplateArguments(const ASTTemplateArgsPtr &In,
TemplateArgumentListInfo &Out);
void NoteAllFoundTemplates(TemplateName Name);
QualType CheckTemplateIdType(TemplateName Template,
SourceLocation TemplateLoc,
TemplateArgumentListInfo &TemplateArgs);
TypeResult
ActOnTemplateIdType(CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
TemplateTy Template, SourceLocation TemplateLoc,
SourceLocation LAngleLoc,
ASTTemplateArgsPtr TemplateArgs,
SourceLocation RAngleLoc,
bool IsCtorOrDtorName = false);
/// \brief Parsed an elaborated-type-specifier that refers to a template-id,
/// such as \c class T::template apply<U>.
TypeResult ActOnTagTemplateIdType(TagUseKind TUK,
TypeSpecifierType TagSpec,
SourceLocation TagLoc,
CXXScopeSpec &SS,
SourceLocation TemplateKWLoc,
TemplateTy TemplateD,
SourceLocation TemplateLoc,
SourceLocation LAngleLoc,
ASTTemplateArgsPtr TemplateArgsIn,
SourceLocation RAngleLoc);
DeclResult ActOnVarTemplateSpecialization(
Scope *S, Declarator &D, TypeSourceInfo *DI,
SourceLocation TemplateKWLoc, TemplateParameterList *TemplateParams,
StorageClass SC, bool IsPartialSpecialization);
DeclResult CheckVarTemplateId(VarTemplateDecl *Template,
SourceLocation TemplateLoc,
SourceLocation TemplateNameLoc,
const TemplateArgumentListInfo &TemplateArgs);
ExprResult CheckVarTemplateId(const CXXScopeSpec &SS,
const DeclarationNameInfo &NameInfo,
VarTemplateDecl *Template,
SourceLocation TemplateLoc,
const TemplateArgumentListInfo *TemplateArgs);
ExprResult BuildTemplateIdExpr(const CXXScopeSpec &SS,
SourceLocation TemplateKWLoc,
LookupResult &R,
bool RequiresADL,
const TemplateArgumentListInfo *TemplateArgs);
ExprResult BuildQualifiedTemplateIdExpr(CXXScopeSpec &SS,
SourceLocation TemplateKWLoc,
const DeclarationNameInfo &NameInfo,
const TemplateArgumentListInfo *TemplateArgs);
TemplateNameKind ActOnDependentTemplateName(Scope *S,
CXXScopeSpec &SS,
SourceLocation TemplateKWLoc,
UnqualifiedId &Name,
ParsedType ObjectType,
bool EnteringContext,
TemplateTy &Template);
DeclResult
ActOnClassTemplateSpecialization(Scope *S, unsigned TagSpec, TagUseKind TUK,
SourceLocation KWLoc,
SourceLocation ModulePrivateLoc,
TemplateIdAnnotation &TemplateId,
AttributeList *Attr,
MultiTemplateParamsArg TemplateParameterLists,
SkipBodyInfo *SkipBody = nullptr);
Decl *ActOnTemplateDeclarator(Scope *S,
MultiTemplateParamsArg TemplateParameterLists,
Declarator &D);
Decl *ActOnStartOfFunctionTemplateDef(Scope *FnBodyScope,
MultiTemplateParamsArg TemplateParameterLists,
Declarator &D);
bool
CheckSpecializationInstantiationRedecl(SourceLocation NewLoc,
TemplateSpecializationKind NewTSK,
NamedDecl *PrevDecl,
TemplateSpecializationKind PrevTSK,
SourceLocation PrevPtOfInstantiation,
bool &SuppressNew);
bool CheckDependentFunctionTemplateSpecialization(FunctionDecl *FD,
const TemplateArgumentListInfo &ExplicitTemplateArgs,
LookupResult &Previous);
bool CheckFunctionTemplateSpecialization(FunctionDecl *FD,
TemplateArgumentListInfo *ExplicitTemplateArgs,
LookupResult &Previous);
bool CheckMemberSpecialization(NamedDecl *Member, LookupResult &Previous);
DeclResult
ActOnExplicitInstantiation(Scope *S,
SourceLocation ExternLoc,
SourceLocation TemplateLoc,
unsigned TagSpec,
SourceLocation KWLoc,
const CXXScopeSpec &SS,
TemplateTy Template,
SourceLocation TemplateNameLoc,
SourceLocation LAngleLoc,
ASTTemplateArgsPtr TemplateArgs,
SourceLocation RAngleLoc,
AttributeList *Attr);
DeclResult
ActOnExplicitInstantiation(Scope *S,
SourceLocation ExternLoc,
SourceLocation TemplateLoc,
unsigned TagSpec,
SourceLocation KWLoc,
CXXScopeSpec &SS,
IdentifierInfo *Name,
SourceLocation NameLoc,
AttributeList *Attr);
DeclResult ActOnExplicitInstantiation(Scope *S,
SourceLocation ExternLoc,
SourceLocation TemplateLoc,
Declarator &D);
TemplateArgumentLoc
SubstDefaultTemplateArgumentIfAvailable(TemplateDecl *Template,
SourceLocation TemplateLoc,
SourceLocation RAngleLoc,
Decl *Param,
SmallVectorImpl<TemplateArgument>
&Converted,
bool &HasDefaultArg);
/// \brief Specifies the context in which a particular template
/// argument is being checked.
enum CheckTemplateArgumentKind {
/// \brief The template argument was specified in the code or was
/// instantiated with some deduced template arguments.
CTAK_Specified,
/// \brief The template argument was deduced via template argument
/// deduction.
CTAK_Deduced,
/// \brief The template argument was deduced from an array bound
/// via template argument deduction.
CTAK_DeducedFromArrayBound
};
bool CheckTemplateArgument(NamedDecl *Param,
TemplateArgumentLoc &Arg,
NamedDecl *Template,
SourceLocation TemplateLoc,
SourceLocation RAngleLoc,
unsigned ArgumentPackIndex,
SmallVectorImpl<TemplateArgument> &Converted,
CheckTemplateArgumentKind CTAK = CTAK_Specified);
/// \brief Check that the given template arguments can be be provided to
/// the given template, converting the arguments along the way.
///
/// \param Template The template to which the template arguments are being
/// provided.
///
/// \param TemplateLoc The location of the template name in the source.
///
/// \param TemplateArgs The list of template arguments. If the template is
/// a template template parameter, this function may extend the set of
/// template arguments to also include substituted, defaulted template
/// arguments.
///
/// \param PartialTemplateArgs True if the list of template arguments is
/// intentionally partial, e.g., because we're checking just the initial
/// set of template arguments.
///
/// \param Converted Will receive the converted, canonicalized template
/// arguments.
///
/// \returns true if an error occurred, false otherwise.
bool CheckTemplateArgumentList(TemplateDecl *Template,
SourceLocation TemplateLoc,
TemplateArgumentListInfo &TemplateArgs,
bool PartialTemplateArgs,
SmallVectorImpl<TemplateArgument> &Converted);
bool CheckTemplateTypeArgument(TemplateTypeParmDecl *Param,
TemplateArgumentLoc &Arg,
SmallVectorImpl<TemplateArgument> &Converted);
bool CheckTemplateArgument(TemplateTypeParmDecl *Param,
TypeSourceInfo *Arg);
ExprResult CheckTemplateArgument(NonTypeTemplateParmDecl *Param,
QualType InstantiatedParamType, Expr *Arg,
TemplateArgument &Converted,
CheckTemplateArgumentKind CTAK = CTAK_Specified);
bool CheckTemplateArgument(TemplateTemplateParmDecl *Param,
TemplateArgumentLoc &Arg,
unsigned ArgumentPackIndex);
ExprResult
BuildExpressionFromDeclTemplateArgument(const TemplateArgument &Arg,
QualType ParamType,
SourceLocation Loc);
ExprResult
BuildExpressionFromIntegralTemplateArgument(const TemplateArgument &Arg,
SourceLocation Loc);
/// \brief Enumeration describing how template parameter lists are compared
/// for equality.
enum TemplateParameterListEqualKind {
/// \brief We are matching the template parameter lists of two templates
/// that might be redeclarations.
///
/// \code
/// template<typename T> struct X;
/// template<typename T> struct X;
/// \endcode
TPL_TemplateMatch,
/// \brief We are matching the template parameter lists of two template
/// template parameters as part of matching the template parameter lists
/// of two templates that might be redeclarations.
///
/// \code
/// template<template<int I> class TT> struct X;
/// template<template<int Value> class Other> struct X;
/// \endcode
TPL_TemplateTemplateParmMatch,
/// \brief We are matching the template parameter lists of a template
/// template argument against the template parameter lists of a template
/// template parameter.
///
/// \code
/// template<template<int Value> class Metafun> struct X;
/// template<int Value> struct integer_c;
/// X<integer_c> xic;
/// \endcode
TPL_TemplateTemplateArgumentMatch
};
bool TemplateParameterListsAreEqual(TemplateParameterList *New,
TemplateParameterList *Old,
bool Complain,
TemplateParameterListEqualKind Kind,
SourceLocation TemplateArgLoc
= SourceLocation());
bool CheckTemplateDeclScope(Scope *S, TemplateParameterList *TemplateParams);
/// \brief Called when the parser has parsed a C++ typename
/// specifier, e.g., "typename T::type".
///
/// \param S The scope in which this typename type occurs.
/// \param TypenameLoc the location of the 'typename' keyword
/// \param SS the nested-name-specifier following the typename (e.g., 'T::').
/// \param II the identifier we're retrieving (e.g., 'type' in the example).
/// \param IdLoc the location of the identifier.
TypeResult
ActOnTypenameType(Scope *S, SourceLocation TypenameLoc,
const CXXScopeSpec &SS, const IdentifierInfo &II,
SourceLocation IdLoc);
/// \brief Called when the parser has parsed a C++ typename
/// specifier that ends in a template-id, e.g.,
/// "typename MetaFun::template apply<T1, T2>".
///
/// \param S The scope in which this typename type occurs.
/// \param TypenameLoc the location of the 'typename' keyword
/// \param SS the nested-name-specifier following the typename (e.g., 'T::').
/// \param TemplateLoc the location of the 'template' keyword, if any.
/// \param TemplateName The template name.
/// \param TemplateNameLoc The location of the template name.
/// \param LAngleLoc The location of the opening angle bracket ('<').
/// \param TemplateArgs The template arguments.
/// \param RAngleLoc The location of the closing angle bracket ('>').
TypeResult
ActOnTypenameType(Scope *S, SourceLocation TypenameLoc,
const CXXScopeSpec &SS,
SourceLocation TemplateLoc,
TemplateTy TemplateName,
SourceLocation TemplateNameLoc,
SourceLocation LAngleLoc,
ASTTemplateArgsPtr TemplateArgs,
SourceLocation RAngleLoc);
QualType CheckTypenameType(ElaboratedTypeKeyword Keyword,
SourceLocation KeywordLoc,
NestedNameSpecifierLoc QualifierLoc,
const IdentifierInfo &II,
SourceLocation IILoc);
TypeSourceInfo *RebuildTypeInCurrentInstantiation(TypeSourceInfo *T,
SourceLocation Loc,
DeclarationName Name);
bool RebuildNestedNameSpecifierInCurrentInstantiation(CXXScopeSpec &SS);
ExprResult RebuildExprInCurrentInstantiation(Expr *E);
bool RebuildTemplateParamsInCurrentInstantiation(
TemplateParameterList *Params);
std::string
getTemplateArgumentBindingsText(const TemplateParameterList *Params,
const TemplateArgumentList &Args);
std::string
getTemplateArgumentBindingsText(const TemplateParameterList *Params,
const TemplateArgument *Args,
unsigned NumArgs);
//===--------------------------------------------------------------------===//
// C++ Variadic Templates (C++0x [temp.variadic])
//===--------------------------------------------------------------------===//
/// Determine whether an unexpanded parameter pack might be permitted in this
/// location. Useful for error recovery.
bool isUnexpandedParameterPackPermitted();
/// \brief The context in which an unexpanded parameter pack is
/// being diagnosed.
///
/// Note that the values of this enumeration line up with the first
/// argument to the \c err_unexpanded_parameter_pack diagnostic.
enum UnexpandedParameterPackContext {
/// \brief An arbitrary expression.
UPPC_Expression = 0,
/// \brief The base type of a class type.
UPPC_BaseType,
/// \brief The type of an arbitrary declaration.
UPPC_DeclarationType,
/// \brief The type of a data member.
UPPC_DataMemberType,
/// \brief The size of a bit-field.
UPPC_BitFieldWidth,
/// \brief The expression in a static assertion.
UPPC_StaticAssertExpression,
/// \brief The fixed underlying type of an enumeration.
UPPC_FixedUnderlyingType,
/// \brief The enumerator value.
UPPC_EnumeratorValue,
/// \brief A using declaration.
UPPC_UsingDeclaration,
/// \brief A friend declaration.
UPPC_FriendDeclaration,
/// \brief A declaration qualifier.
UPPC_DeclarationQualifier,
/// \brief An initializer.
UPPC_Initializer,
/// \brief A default argument.
UPPC_DefaultArgument,
/// \brief The type of a non-type template parameter.
UPPC_NonTypeTemplateParameterType,
/// \brief The type of an exception.
UPPC_ExceptionType,
/// \brief Partial specialization.
UPPC_PartialSpecialization,
/// \brief Microsoft __if_exists.
UPPC_IfExists,
/// \brief Microsoft __if_not_exists.
UPPC_IfNotExists,
/// \brief Lambda expression.
UPPC_Lambda,
/// \brief Block expression,
UPPC_Block
};
/// \brief Diagnose unexpanded parameter packs.
///
/// \param Loc The location at which we should emit the diagnostic.
///
/// \param UPPC The context in which we are diagnosing unexpanded
/// parameter packs.
///
/// \param Unexpanded the set of unexpanded parameter packs.
///
/// \returns true if an error occurred, false otherwise.
bool DiagnoseUnexpandedParameterPacks(SourceLocation Loc,
UnexpandedParameterPackContext UPPC,
ArrayRef<UnexpandedParameterPack> Unexpanded);
/// \brief If the given type contains an unexpanded parameter pack,
/// diagnose the error.
///
/// \param Loc The source location where a diagnostc should be emitted.
///
/// \param T The type that is being checked for unexpanded parameter
/// packs.
///
/// \returns true if an error occurred, false otherwise.
bool DiagnoseUnexpandedParameterPack(SourceLocation Loc, TypeSourceInfo *T,
UnexpandedParameterPackContext UPPC);
/// \brief If the given expression contains an unexpanded parameter
/// pack, diagnose the error.
///
/// \param E The expression that is being checked for unexpanded
/// parameter packs.
///
/// \returns true if an error occurred, false otherwise.
bool DiagnoseUnexpandedParameterPack(Expr *E,
UnexpandedParameterPackContext UPPC = UPPC_Expression);
/// \brief If the given nested-name-specifier contains an unexpanded
/// parameter pack, diagnose the error.
///
/// \param SS The nested-name-specifier that is being checked for
/// unexpanded parameter packs.
///
/// \returns true if an error occurred, false otherwise.
bool DiagnoseUnexpandedParameterPack(const CXXScopeSpec &SS,
UnexpandedParameterPackContext UPPC);
/// \brief If the given name contains an unexpanded parameter pack,
/// diagnose the error.
///
/// \param NameInfo The name (with source location information) that
/// is being checked for unexpanded parameter packs.
///
/// \returns true if an error occurred, false otherwise.
bool DiagnoseUnexpandedParameterPack(const DeclarationNameInfo &NameInfo,
UnexpandedParameterPackContext UPPC);
/// \brief If the given template name contains an unexpanded parameter pack,
/// diagnose the error.
///
/// \param Loc The location of the template name.
///
/// \param Template The template name that is being checked for unexpanded
/// parameter packs.
///
/// \returns true if an error occurred, false otherwise.
bool DiagnoseUnexpandedParameterPack(SourceLocation Loc,
TemplateName Template,
UnexpandedParameterPackContext UPPC);
/// \brief If the given template argument contains an unexpanded parameter
/// pack, diagnose the error.
///
/// \param Arg The template argument that is being checked for unexpanded
/// parameter packs.
///
/// \returns true if an error occurred, false otherwise.
bool DiagnoseUnexpandedParameterPack(TemplateArgumentLoc Arg,
UnexpandedParameterPackContext UPPC);
/// \brief Collect the set of unexpanded parameter packs within the given
/// template argument.
///
/// \param Arg The template argument that will be traversed to find
/// unexpanded parameter packs.
void collectUnexpandedParameterPacks(TemplateArgument Arg,
SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
/// \brief Collect the set of unexpanded parameter packs within the given
/// template argument.
///
/// \param Arg The template argument that will be traversed to find
/// unexpanded parameter packs.
void collectUnexpandedParameterPacks(TemplateArgumentLoc Arg,
SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
/// \brief Collect the set of unexpanded parameter packs within the given
/// type.
///
/// \param T The type that will be traversed to find
/// unexpanded parameter packs.
void collectUnexpandedParameterPacks(QualType T,
SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
/// \brief Collect the set of unexpanded parameter packs within the given
/// type.
///
/// \param TL The type that will be traversed to find
/// unexpanded parameter packs.
void collectUnexpandedParameterPacks(TypeLoc TL,
SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
/// \brief Collect the set of unexpanded parameter packs within the given
/// nested-name-specifier.
///
/// \param SS The nested-name-specifier that will be traversed to find
/// unexpanded parameter packs.
void collectUnexpandedParameterPacks(CXXScopeSpec &SS,
SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
/// \brief Collect the set of unexpanded parameter packs within the given
/// name.
///
/// \param NameInfo The name that will be traversed to find
/// unexpanded parameter packs.
void collectUnexpandedParameterPacks(const DeclarationNameInfo &NameInfo,
SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
/// \brief Invoked when parsing a template argument followed by an
/// ellipsis, which creates a pack expansion.
///
/// \param Arg The template argument preceding the ellipsis, which
/// may already be invalid.
///
/// \param EllipsisLoc The location of the ellipsis.
ParsedTemplateArgument ActOnPackExpansion(const ParsedTemplateArgument &Arg,
SourceLocation EllipsisLoc);
/// \brief Invoked when parsing a type followed by an ellipsis, which
/// creates a pack expansion.
///
/// \param Type The type preceding the ellipsis, which will become
/// the pattern of the pack expansion.
///
/// \param EllipsisLoc The location of the ellipsis.
TypeResult ActOnPackExpansion(ParsedType Type, SourceLocation EllipsisLoc);
/// \brief Construct a pack expansion type from the pattern of the pack
/// expansion.
TypeSourceInfo *CheckPackExpansion(TypeSourceInfo *Pattern,
SourceLocation EllipsisLoc,
Optional<unsigned> NumExpansions);
/// \brief Construct a pack expansion type from the pattern of the pack
/// expansion.
QualType CheckPackExpansion(QualType Pattern,
SourceRange PatternRange,
SourceLocation EllipsisLoc,
Optional<unsigned> NumExpansions);
/// \brief Invoked when parsing an expression followed by an ellipsis, which
/// creates a pack expansion.
///
/// \param Pattern The expression preceding the ellipsis, which will become
/// the pattern of the pack expansion.
///
/// \param EllipsisLoc The location of the ellipsis.
ExprResult ActOnPackExpansion(Expr *Pattern, SourceLocation EllipsisLoc);
/// \brief Invoked when parsing an expression followed by an ellipsis, which
/// creates a pack expansion.
///
/// \param Pattern The expression preceding the ellipsis, which will become
/// the pattern of the pack expansion.
///
/// \param EllipsisLoc The location of the ellipsis.
ExprResult CheckPackExpansion(Expr *Pattern, SourceLocation EllipsisLoc,
Optional<unsigned> NumExpansions);
/// \brief Determine whether we could expand a pack expansion with the
/// given set of parameter packs into separate arguments by repeatedly
/// transforming the pattern.
///
/// \param EllipsisLoc The location of the ellipsis that identifies the
/// pack expansion.
///
/// \param PatternRange The source range that covers the entire pattern of
/// the pack expansion.
///
/// \param Unexpanded The set of unexpanded parameter packs within the
/// pattern.
///
/// \param ShouldExpand Will be set to \c true if the transformer should
/// expand the corresponding pack expansions into separate arguments. When
/// set, \c NumExpansions must also be set.
///
/// \param RetainExpansion Whether the caller should add an unexpanded
/// pack expansion after all of the expanded arguments. This is used
/// when extending explicitly-specified template argument packs per
/// C++0x [temp.arg.explicit]p9.
///
/// \param NumExpansions The number of separate arguments that will be in
/// the expanded form of the corresponding pack expansion. This is both an
/// input and an output parameter, which can be set by the caller if the
/// number of expansions is known a priori (e.g., due to a prior substitution)
/// and will be set by the callee when the number of expansions is known.
/// The callee must set this value when \c ShouldExpand is \c true; it may
/// set this value in other cases.
///
/// \returns true if an error occurred (e.g., because the parameter packs
/// are to be instantiated with arguments of different lengths), false
/// otherwise. If false, \c ShouldExpand (and possibly \c NumExpansions)
/// must be set.
bool CheckParameterPacksForExpansion(SourceLocation EllipsisLoc,
SourceRange PatternRange,
ArrayRef<UnexpandedParameterPack> Unexpanded,
const MultiLevelTemplateArgumentList &TemplateArgs,
bool &ShouldExpand,
bool &RetainExpansion,
Optional<unsigned> &NumExpansions);
/// \brief Determine the number of arguments in the given pack expansion
/// type.
///
/// This routine assumes that the number of arguments in the expansion is
/// consistent across all of the unexpanded parameter packs in its pattern.
///
/// Returns an empty Optional if the type can't be expanded.
Optional<unsigned> getNumArgumentsInExpansion(QualType T,
const MultiLevelTemplateArgumentList &TemplateArgs);
/// \brief Determine whether the given declarator contains any unexpanded
/// parameter packs.
///
/// This routine is used by the parser to disambiguate function declarators
/// with an ellipsis prior to the ')', e.g.,
///
/// \code
/// void f(T...);
/// \endcode
///
/// To determine whether we have an (unnamed) function parameter pack or
/// a variadic function.
///
/// \returns true if the declarator contains any unexpanded parameter packs,
/// false otherwise.
bool containsUnexpandedParameterPacks(Declarator &D);
/// \brief Returns the pattern of the pack expansion for a template argument.
///
/// \param OrigLoc The template argument to expand.
///
/// \param Ellipsis Will be set to the location of the ellipsis.
///
/// \param NumExpansions Will be set to the number of expansions that will
/// be generated from this pack expansion, if known a priori.
TemplateArgumentLoc getTemplateArgumentPackExpansionPattern(
TemplateArgumentLoc OrigLoc,
SourceLocation &Ellipsis,
Optional<unsigned> &NumExpansions) const;
//===--------------------------------------------------------------------===//
// C++ Template Argument Deduction (C++ [temp.deduct])
//===--------------------------------------------------------------------===//
QualType adjustCCAndNoReturn(QualType ArgFunctionType, QualType FunctionType);
/// \brief Describes the result of template argument deduction.
///
/// The TemplateDeductionResult enumeration describes the result of
/// template argument deduction, as returned from
/// DeduceTemplateArguments(). The separate TemplateDeductionInfo
/// structure provides additional information about the results of
/// template argument deduction, e.g., the deduced template argument
/// list (if successful) or the specific template parameters or
/// deduced arguments that were involved in the failure.
enum TemplateDeductionResult {
/// \brief Template argument deduction was successful.
TDK_Success = 0,
/// \brief The declaration was invalid; do nothing.
TDK_Invalid,
/// \brief Template argument deduction exceeded the maximum template
/// instantiation depth (which has already been diagnosed).
TDK_InstantiationDepth,
/// \brief Template argument deduction did not deduce a value
/// for every template parameter.
TDK_Incomplete,
/// \brief Template argument deduction produced inconsistent
/// deduced values for the given template parameter.
TDK_Inconsistent,
/// \brief Template argument deduction failed due to inconsistent
/// cv-qualifiers on a template parameter type that would
/// otherwise be deduced, e.g., we tried to deduce T in "const T"
/// but were given a non-const "X".
TDK_Underqualified,
/// \brief Substitution of the deduced template argument values
/// resulted in an error.
TDK_SubstitutionFailure,
/// \brief A non-depnedent component of the parameter did not match the
/// corresponding component of the argument.
TDK_NonDeducedMismatch,
/// \brief When performing template argument deduction for a function
/// template, there were too many call arguments.
TDK_TooManyArguments,
/// \brief When performing template argument deduction for a function
/// template, there were too few call arguments.
TDK_TooFewArguments,
/// \brief The explicitly-specified template arguments were not valid
/// template arguments for the given template.
TDK_InvalidExplicitArguments,
/// \brief The arguments included an overloaded function name that could
/// not be resolved to a suitable function.
TDK_FailedOverloadResolution,
/// \brief Deduction failed; that's all we know.
TDK_MiscellaneousDeductionFailure
};
TemplateDeductionResult
DeduceTemplateArguments(ClassTemplatePartialSpecializationDecl *Partial,
const TemplateArgumentList &TemplateArgs,
sema::TemplateDeductionInfo &Info);
TemplateDeductionResult
DeduceTemplateArguments(VarTemplatePartialSpecializationDecl *Partial,
const TemplateArgumentList &TemplateArgs,
sema::TemplateDeductionInfo &Info);
TemplateDeductionResult SubstituteExplicitTemplateArguments(
FunctionTemplateDecl *FunctionTemplate,
TemplateArgumentListInfo &ExplicitTemplateArgs,
SmallVectorImpl<DeducedTemplateArgument> &Deduced,
SmallVectorImpl<QualType> &ParamTypes, QualType *FunctionType,
sema::TemplateDeductionInfo &Info);
/// brief A function argument from which we performed template argument
// deduction for a call.
struct OriginalCallArg {
OriginalCallArg(QualType OriginalParamType,
unsigned ArgIdx,
QualType OriginalArgType)
: OriginalParamType(OriginalParamType), ArgIdx(ArgIdx),
OriginalArgType(OriginalArgType) { }
QualType OriginalParamType;
unsigned ArgIdx;
QualType OriginalArgType;
};
TemplateDeductionResult
FinishTemplateArgumentDeduction(FunctionTemplateDecl *FunctionTemplate,
SmallVectorImpl<DeducedTemplateArgument> &Deduced,
unsigned NumExplicitlySpecified,
FunctionDecl *&Specialization,
sema::TemplateDeductionInfo &Info,
SmallVectorImpl<OriginalCallArg> const *OriginalCallArgs = nullptr,
bool PartialOverloading = false);
TemplateDeductionResult
DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate,
TemplateArgumentListInfo *ExplicitTemplateArgs,
ArrayRef<Expr *> Args,
FunctionDecl *&Specialization,
sema::TemplateDeductionInfo &Info,
bool PartialOverloading = false);
TemplateDeductionResult
DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate,
TemplateArgumentListInfo *ExplicitTemplateArgs,
QualType ArgFunctionType,
FunctionDecl *&Specialization,
sema::TemplateDeductionInfo &Info,
bool InOverloadResolution = false);
TemplateDeductionResult
DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate,
QualType ToType,
CXXConversionDecl *&Specialization,
sema::TemplateDeductionInfo &Info);
TemplateDeductionResult
DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate,
TemplateArgumentListInfo *ExplicitTemplateArgs,
FunctionDecl *&Specialization,
sema::TemplateDeductionInfo &Info,
bool InOverloadResolution = false);
/// \brief Substitute Replacement for \p auto in \p TypeWithAuto
QualType SubstAutoType(QualType TypeWithAuto, QualType Replacement);
/// \brief Substitute Replacement for auto in TypeWithAuto
TypeSourceInfo* SubstAutoTypeSourceInfo(TypeSourceInfo *TypeWithAuto,
QualType Replacement);
/// \brief Result type of DeduceAutoType.
enum DeduceAutoResult {
DAR_Succeeded,
DAR_Failed,
DAR_FailedAlreadyDiagnosed
};
DeduceAutoResult DeduceAutoType(TypeSourceInfo *AutoType, Expr *&Initializer,
QualType &Result);
DeduceAutoResult DeduceAutoType(TypeLoc AutoTypeLoc, Expr *&Initializer,
QualType &Result);
void DiagnoseAutoDeductionFailure(VarDecl *VDecl, Expr *Init);
bool DeduceReturnType(FunctionDecl *FD, SourceLocation Loc,
bool Diagnose = true);
TypeLoc getReturnTypeLoc(FunctionDecl *FD) const;
bool DeduceFunctionTypeFromReturnExpr(FunctionDecl *FD,
SourceLocation ReturnLoc,
Expr *&RetExpr, AutoType *AT);
FunctionTemplateDecl *getMoreSpecializedTemplate(FunctionTemplateDecl *FT1,
FunctionTemplateDecl *FT2,
SourceLocation Loc,
TemplatePartialOrderingContext TPOC,
unsigned NumCallArguments1,
unsigned NumCallArguments2);
UnresolvedSetIterator
getMostSpecialized(UnresolvedSetIterator SBegin, UnresolvedSetIterator SEnd,
TemplateSpecCandidateSet &FailedCandidates,
SourceLocation Loc,
const PartialDiagnostic &NoneDiag,
const PartialDiagnostic &AmbigDiag,
const PartialDiagnostic &CandidateDiag,
bool Complain = true, QualType TargetType = QualType());
ClassTemplatePartialSpecializationDecl *
getMoreSpecializedPartialSpecialization(
ClassTemplatePartialSpecializationDecl *PS1,
ClassTemplatePartialSpecializationDecl *PS2,
SourceLocation Loc);
VarTemplatePartialSpecializationDecl *getMoreSpecializedPartialSpecialization(
VarTemplatePartialSpecializationDecl *PS1,
VarTemplatePartialSpecializationDecl *PS2, SourceLocation Loc);
void MarkUsedTemplateParameters(const TemplateArgumentList &TemplateArgs,
bool OnlyDeduced,
unsigned Depth,
llvm::SmallBitVector &Used);
void MarkDeducedTemplateParameters(
const FunctionTemplateDecl *FunctionTemplate,
llvm::SmallBitVector &Deduced) {
return MarkDeducedTemplateParameters(Context, FunctionTemplate, Deduced);
}
static void MarkDeducedTemplateParameters(ASTContext &Ctx,
const FunctionTemplateDecl *FunctionTemplate,
llvm::SmallBitVector &Deduced);
//===--------------------------------------------------------------------===//
// C++ Template Instantiation
//
MultiLevelTemplateArgumentList
getTemplateInstantiationArgs(NamedDecl *D,
const TemplateArgumentList *Innermost = nullptr,
bool RelativeToPrimary = false,
const FunctionDecl *Pattern = nullptr);
/// \brief A template instantiation that is currently in progress.
struct ActiveTemplateInstantiation {
/// \brief The kind of template instantiation we are performing
enum InstantiationKind {
/// We are instantiating a template declaration. The entity is
/// the declaration we're instantiating (e.g., a CXXRecordDecl).
TemplateInstantiation,
/// We are instantiating a default argument for a template
/// parameter. The Entity is the template, and
/// TemplateArgs/NumTemplateArguments provides the template
/// arguments as specified.
/// FIXME: Use a TemplateArgumentList
DefaultTemplateArgumentInstantiation,
/// We are instantiating a default argument for a function.
/// The Entity is the ParmVarDecl, and TemplateArgs/NumTemplateArgs
/// provides the template arguments as specified.
DefaultFunctionArgumentInstantiation,
/// We are substituting explicit template arguments provided for
/// a function template. The entity is a FunctionTemplateDecl.
ExplicitTemplateArgumentSubstitution,
/// We are substituting template argument determined as part of
/// template argument deduction for either a class template
/// partial specialization or a function template. The
/// Entity is either a ClassTemplatePartialSpecializationDecl or
/// a FunctionTemplateDecl.
DeducedTemplateArgumentSubstitution,
/// We are substituting prior template arguments into a new
/// template parameter. The template parameter itself is either a
/// NonTypeTemplateParmDecl or a TemplateTemplateParmDecl.
PriorTemplateArgumentSubstitution,
/// We are checking the validity of a default template argument that
/// has been used when naming a template-id.
DefaultTemplateArgumentChecking,
/// We are instantiating the exception specification for a function
/// template which was deferred until it was needed.
ExceptionSpecInstantiation
} Kind;
/// \brief The point of instantiation within the source code.
SourceLocation PointOfInstantiation;
/// \brief The template (or partial specialization) in which we are
/// performing the instantiation, for substitutions of prior template
/// arguments.
NamedDecl *Template;
/// \brief The entity that is being instantiated.
Decl *Entity;
/// \brief The list of template arguments we are substituting, if they
/// are not part of the entity.
const TemplateArgument *TemplateArgs;
/// \brief The number of template arguments in TemplateArgs.
unsigned NumTemplateArgs;
/// \brief The template deduction info object associated with the
/// substitution or checking of explicit or deduced template arguments.
sema::TemplateDeductionInfo *DeductionInfo;
/// \brief The source range that covers the construct that cause
/// the instantiation, e.g., the template-id that causes a class
/// template instantiation.
SourceRange InstantiationRange;
ActiveTemplateInstantiation()
: Kind(TemplateInstantiation), Template(nullptr), Entity(nullptr),
TemplateArgs(nullptr), NumTemplateArgs(0), DeductionInfo(nullptr) {}
/// \brief Determines whether this template is an actual instantiation
/// that should be counted toward the maximum instantiation depth.
bool isInstantiationRecord() const;
friend bool operator==(const ActiveTemplateInstantiation &X,
const ActiveTemplateInstantiation &Y) {
if (X.Kind != Y.Kind)
return false;
if (X.Entity != Y.Entity)
return false;
switch (X.Kind) {
case TemplateInstantiation:
case ExceptionSpecInstantiation:
return true;
case PriorTemplateArgumentSubstitution:
case DefaultTemplateArgumentChecking:
return X.Template == Y.Template && X.TemplateArgs == Y.TemplateArgs;
case DefaultTemplateArgumentInstantiation:
case ExplicitTemplateArgumentSubstitution:
case DeducedTemplateArgumentSubstitution:
case DefaultFunctionArgumentInstantiation:
return X.TemplateArgs == Y.TemplateArgs;
}
llvm_unreachable("Invalid InstantiationKind!");
}
friend bool operator!=(const ActiveTemplateInstantiation &X,
const ActiveTemplateInstantiation &Y) {
return !(X == Y);
}
};
/// \brief List of active template instantiations.
///
/// This vector is treated as a stack. As one template instantiation
/// requires another template instantiation, additional
/// instantiations are pushed onto the stack up to a
/// user-configurable limit LangOptions::InstantiationDepth.
SmallVector<ActiveTemplateInstantiation, 16>
ActiveTemplateInstantiations;
/// \brief Extra modules inspected when performing a lookup during a template
/// instantiation. Computed lazily.
SmallVector<Module*, 16> ActiveTemplateInstantiationLookupModules;
/// \brief Cache of additional modules that should be used for name lookup
/// within the current template instantiation. Computed lazily; use
/// getLookupModules() to get a complete set.
llvm::DenseSet<Module*> LookupModulesCache;
/// \brief Get the set of additional modules that should be checked during
/// name lookup. A module and its imports become visible when instanting a
/// template defined within it.
llvm::DenseSet<Module*> &getLookupModules();
/// \brief Whether we are in a SFINAE context that is not associated with
/// template instantiation.
///
/// This is used when setting up a SFINAE trap (\c see SFINAETrap) outside
/// of a template instantiation or template argument deduction.
bool InNonInstantiationSFINAEContext;
/// \brief The number of ActiveTemplateInstantiation entries in
/// \c ActiveTemplateInstantiations that are not actual instantiations and,
/// therefore, should not be counted as part of the instantiation depth.
unsigned NonInstantiationEntries;
/// \brief The last template from which a template instantiation
/// error or warning was produced.
///
/// This value is used to suppress printing of redundant template
/// instantiation backtraces when there are multiple errors in the
/// same instantiation. FIXME: Does this belong in Sema? It's tough
/// to implement it anywhere else.
ActiveTemplateInstantiation LastTemplateInstantiationErrorContext;
/// \brief The current index into pack expansion arguments that will be
/// used for substitution of parameter packs.
///
/// The pack expansion index will be -1 to indicate that parameter packs
/// should be instantiated as themselves. Otherwise, the index specifies
/// which argument within the parameter pack will be used for substitution.
int ArgumentPackSubstitutionIndex;
/// \brief RAII object used to change the argument pack substitution index
/// within a \c Sema object.
///
/// See \c ArgumentPackSubstitutionIndex for more information.
class ArgumentPackSubstitutionIndexRAII {
Sema &Self;
int OldSubstitutionIndex;
public:
ArgumentPackSubstitutionIndexRAII(Sema &Self, int NewSubstitutionIndex)
: Self(Self), OldSubstitutionIndex(Self.ArgumentPackSubstitutionIndex) {
Self.ArgumentPackSubstitutionIndex = NewSubstitutionIndex;
}
~ArgumentPackSubstitutionIndexRAII() {
Self.ArgumentPackSubstitutionIndex = OldSubstitutionIndex;
}
};
friend class ArgumentPackSubstitutionRAII;
/// \brief The stack of calls expression undergoing template instantiation.
///
/// The top of this stack is used by a fixit instantiating unresolved
/// function calls to fix the AST to match the textual change it prints.
SmallVector<CallExpr *, 8> CallsUndergoingInstantiation;
/// \brief For each declaration that involved template argument deduction, the
/// set of diagnostics that were suppressed during that template argument
/// deduction.
///
/// FIXME: Serialize this structure to the AST file.
typedef llvm::DenseMap<Decl *, SmallVector<PartialDiagnosticAt, 1> >
SuppressedDiagnosticsMap;
SuppressedDiagnosticsMap SuppressedDiagnostics;
/// \brief A stack object to be created when performing template
/// instantiation.
///
/// Construction of an object of type \c InstantiatingTemplate
/// pushes the current instantiation onto the stack of active
/// instantiations. If the size of this stack exceeds the maximum
/// number of recursive template instantiations, construction
/// produces an error and evaluates true.
///
/// Destruction of this object will pop the named instantiation off
/// the stack.
struct InstantiatingTemplate {
/// \brief Note that we are instantiating a class template,
/// function template, or a member thereof.
InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
Decl *Entity,
SourceRange InstantiationRange = SourceRange());
struct ExceptionSpecification {};
/// \brief Note that we are instantiating an exception specification
/// of a function template.
InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
FunctionDecl *Entity, ExceptionSpecification,
SourceRange InstantiationRange = SourceRange());
/// \brief Note that we are instantiating a default argument in a
/// template-id.
InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
TemplateDecl *Template,
ArrayRef<TemplateArgument> TemplateArgs,
SourceRange InstantiationRange = SourceRange());
/// \brief Note that we are instantiating a default argument in a
/// template-id.
InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
FunctionTemplateDecl *FunctionTemplate,
ArrayRef<TemplateArgument> TemplateArgs,
ActiveTemplateInstantiation::InstantiationKind Kind,
sema::TemplateDeductionInfo &DeductionInfo,
SourceRange InstantiationRange = SourceRange());
/// \brief Note that we are instantiating as part of template
/// argument deduction for a class template partial
/// specialization.
InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
ClassTemplatePartialSpecializationDecl *PartialSpec,
ArrayRef<TemplateArgument> TemplateArgs,
sema::TemplateDeductionInfo &DeductionInfo,
SourceRange InstantiationRange = SourceRange());
/// \brief Note that we are instantiating as part of template
/// argument deduction for a variable template partial
/// specialization.
InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
VarTemplatePartialSpecializationDecl *PartialSpec,
ArrayRef<TemplateArgument> TemplateArgs,
sema::TemplateDeductionInfo &DeductionInfo,
SourceRange InstantiationRange = SourceRange());
InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
ParmVarDecl *Param,
ArrayRef<TemplateArgument> TemplateArgs,
SourceRange InstantiationRange = SourceRange());
/// \brief Note that we are substituting prior template arguments into a
/// non-type parameter.
InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
NamedDecl *Template,
NonTypeTemplateParmDecl *Param,
ArrayRef<TemplateArgument> TemplateArgs,
SourceRange InstantiationRange);
/// \brief Note that we are substituting prior template arguments into a
/// template template parameter.
InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
NamedDecl *Template,
TemplateTemplateParmDecl *Param,
ArrayRef<TemplateArgument> TemplateArgs,
SourceRange InstantiationRange);
/// \brief Note that we are checking the default template argument
/// against the template parameter for a given template-id.
InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
TemplateDecl *Template,
NamedDecl *Param,
ArrayRef<TemplateArgument> TemplateArgs,
SourceRange InstantiationRange);
/// \brief Note that we have finished instantiating this template.
void Clear();
~InstantiatingTemplate() { Clear(); }
/// \brief Determines whether we have exceeded the maximum
/// recursive template instantiations.
bool isInvalid() const { return Invalid; }
private:
Sema &SemaRef;
bool Invalid;
bool SavedInNonInstantiationSFINAEContext;
bool CheckInstantiationDepth(SourceLocation PointOfInstantiation,
SourceRange InstantiationRange);
InstantiatingTemplate(
Sema &SemaRef, ActiveTemplateInstantiation::InstantiationKind Kind,
SourceLocation PointOfInstantiation, SourceRange InstantiationRange,
Decl *Entity, NamedDecl *Template = nullptr,
ArrayRef<TemplateArgument> TemplateArgs = ArrayRef<TemplateArgument>(),
sema::TemplateDeductionInfo *DeductionInfo = nullptr);
InstantiatingTemplate(const InstantiatingTemplate&) = delete;
InstantiatingTemplate&
operator=(const InstantiatingTemplate&) = delete;
};
void PrintInstantiationStack();
/// \brief Determines whether we are currently in a context where
/// template argument substitution failures are not considered
/// errors.
///
/// \returns An empty \c Optional if we're not in a SFINAE context.
/// Otherwise, contains a pointer that, if non-NULL, contains the nearest
/// template-deduction context object, which can be used to capture
/// diagnostics that will be suppressed.
Optional<sema::TemplateDeductionInfo *> isSFINAEContext() const;
/// \brief Determines whether we are currently in a context that
/// is not evaluated as per C++ [expr] p5.
bool isUnevaluatedContext() const {
assert(!ExprEvalContexts.empty() &&
"Must be in an expression evaluation context");
return ExprEvalContexts.back().isUnevaluated();
}
/// \brief RAII class used to determine whether SFINAE has
/// trapped any errors that occur during template argument
/// deduction.
class SFINAETrap {
Sema &SemaRef;
unsigned PrevSFINAEErrors;
bool PrevInNonInstantiationSFINAEContext;
bool PrevAccessCheckingSFINAE;
public:
explicit SFINAETrap(Sema &SemaRef, bool AccessCheckingSFINAE = false)
: SemaRef(SemaRef), PrevSFINAEErrors(SemaRef.NumSFINAEErrors),
PrevInNonInstantiationSFINAEContext(
SemaRef.InNonInstantiationSFINAEContext),
PrevAccessCheckingSFINAE(SemaRef.AccessCheckingSFINAE)
{
if (!SemaRef.isSFINAEContext())
SemaRef.InNonInstantiationSFINAEContext = true;
SemaRef.AccessCheckingSFINAE = AccessCheckingSFINAE;
}
~SFINAETrap() {
SemaRef.NumSFINAEErrors = PrevSFINAEErrors;
SemaRef.InNonInstantiationSFINAEContext
= PrevInNonInstantiationSFINAEContext;
SemaRef.AccessCheckingSFINAE = PrevAccessCheckingSFINAE;
}
/// \brief Determine whether any SFINAE errors have been trapped.
bool hasErrorOccurred() const {
return SemaRef.NumSFINAEErrors > PrevSFINAEErrors;
}
};
/// \brief RAII class used to indicate that we are performing provisional
/// semantic analysis to determine the validity of a construct, so
/// typo-correction and diagnostics in the immediate context (not within
/// implicitly-instantiated templates) should be suppressed.
class TentativeAnalysisScope {
Sema &SemaRef;
// FIXME: Using a SFINAETrap for this is a hack.
SFINAETrap Trap;
bool PrevDisableTypoCorrection;
public:
explicit TentativeAnalysisScope(Sema &SemaRef)
: SemaRef(SemaRef), Trap(SemaRef, true),
PrevDisableTypoCorrection(SemaRef.DisableTypoCorrection) {
SemaRef.DisableTypoCorrection = true;
}
~TentativeAnalysisScope() {
SemaRef.DisableTypoCorrection = PrevDisableTypoCorrection;
}
};
/// \brief The current instantiation scope used to store local
/// variables.
LocalInstantiationScope *CurrentInstantiationScope;
/// \brief Tracks whether we are in a context where typo correction is
/// disabled.
bool DisableTypoCorrection;
/// \brief The number of typos corrected by CorrectTypo.
unsigned TyposCorrected;
typedef llvm::SmallSet<SourceLocation, 2> SrcLocSet;
typedef llvm::DenseMap<IdentifierInfo *, SrcLocSet> IdentifierSourceLocations;
/// \brief A cache containing identifiers for which typo correction failed and
/// their locations, so that repeated attempts to correct an identifier in a
/// given location are ignored if typo correction already failed for it.
IdentifierSourceLocations TypoCorrectionFailures;
/// \brief Worker object for performing CFG-based warnings.
sema::AnalysisBasedWarnings AnalysisWarnings;
threadSafety::BeforeSet *ThreadSafetyDeclCache;
/// \brief An entity for which implicit template instantiation is required.
///
/// The source location associated with the declaration is the first place in
/// the source code where the declaration was "used". It is not necessarily
/// the point of instantiation (which will be either before or after the
/// namespace-scope declaration that triggered this implicit instantiation),
/// However, it is the location that diagnostics should generally refer to,
/// because users will need to know what code triggered the instantiation.
typedef std::pair<ValueDecl *, SourceLocation> PendingImplicitInstantiation;
/// \brief The queue of implicit template instantiations that are required
/// but have not yet been performed.
std::deque<PendingImplicitInstantiation> PendingInstantiations;
class SavePendingInstantiationsAndVTableUsesRAII {
public:
SavePendingInstantiationsAndVTableUsesRAII(Sema &S, bool Enabled)
: S(S), Enabled(Enabled) {
if (!Enabled) return;
SavedPendingInstantiations.swap(S.PendingInstantiations);
SavedVTableUses.swap(S.VTableUses);
}
~SavePendingInstantiationsAndVTableUsesRAII() {
if (!Enabled) return;
// Restore the set of pending vtables.
assert(S.VTableUses.empty() &&
"VTableUses should be empty before it is discarded.");
S.VTableUses.swap(SavedVTableUses);
// Restore the set of pending implicit instantiations.
assert(S.PendingInstantiations.empty() &&
"PendingInstantiations should be empty before it is discarded.");
S.PendingInstantiations.swap(SavedPendingInstantiations);
}
private:
Sema &S;
SmallVector<VTableUse, 16> SavedVTableUses;
std::deque<PendingImplicitInstantiation> SavedPendingInstantiations;
bool Enabled;
};
/// \brief The queue of implicit template instantiations that are required
/// and must be performed within the current local scope.
///
/// This queue is only used for member functions of local classes in
/// templates, which must be instantiated in the same scope as their
/// enclosing function, so that they can reference function-local
/// types, static variables, enumerators, etc.
std::deque<PendingImplicitInstantiation> PendingLocalImplicitInstantiations;
class SavePendingLocalImplicitInstantiationsRAII {
public:
SavePendingLocalImplicitInstantiationsRAII(Sema &S): S(S) {
SavedPendingLocalImplicitInstantiations.swap(
S.PendingLocalImplicitInstantiations);
}
~SavePendingLocalImplicitInstantiationsRAII() {
assert(S.PendingLocalImplicitInstantiations.empty() &&
"there shouldn't be any pending local implicit instantiations");
SavedPendingLocalImplicitInstantiations.swap(
S.PendingLocalImplicitInstantiations);
}
private:
Sema &S;
std::deque<PendingImplicitInstantiation>
SavedPendingLocalImplicitInstantiations;
};
void PerformPendingInstantiations(bool LocalOnly = false);
TypeSourceInfo *SubstType(TypeSourceInfo *T,
const MultiLevelTemplateArgumentList &TemplateArgs,
SourceLocation Loc, DeclarationName Entity);
QualType SubstType(QualType T,
const MultiLevelTemplateArgumentList &TemplateArgs,
SourceLocation Loc, DeclarationName Entity);
TypeSourceInfo *SubstType(TypeLoc TL,
const MultiLevelTemplateArgumentList &TemplateArgs,
SourceLocation Loc, DeclarationName Entity);
TypeSourceInfo *SubstFunctionDeclType(TypeSourceInfo *T,
const MultiLevelTemplateArgumentList &TemplateArgs,
SourceLocation Loc,
DeclarationName Entity,
CXXRecordDecl *ThisContext,
unsigned ThisTypeQuals);
void SubstExceptionSpec(FunctionDecl *New, const FunctionProtoType *Proto,
const MultiLevelTemplateArgumentList &Args);
ParmVarDecl *SubstParmVarDecl(ParmVarDecl *D,
const MultiLevelTemplateArgumentList &TemplateArgs,
int indexAdjustment,
Optional<unsigned> NumExpansions,
bool ExpectParameterPack);
bool SubstParmTypes(SourceLocation Loc,
ParmVarDecl **Params, unsigned NumParams,
const MultiLevelTemplateArgumentList &TemplateArgs,
SmallVectorImpl<QualType> &ParamTypes,
SmallVectorImpl<ParmVarDecl *> *OutParams = nullptr);
ExprResult SubstExpr(Expr *E,
const MultiLevelTemplateArgumentList &TemplateArgs);
/// \brief Substitute the given template arguments into a list of
/// expressions, expanding pack expansions if required.
///
/// \param Exprs The list of expressions to substitute into.
///
/// \param NumExprs The number of expressions in \p Exprs.
///
/// \param IsCall Whether this is some form of call, in which case
/// default arguments will be dropped.
///
/// \param TemplateArgs The set of template arguments to substitute.
///
/// \param Outputs Will receive all of the substituted arguments.
///
/// \returns true if an error occurred, false otherwise.
bool SubstExprs(Expr **Exprs, unsigned NumExprs, bool IsCall,
const MultiLevelTemplateArgumentList &TemplateArgs,
SmallVectorImpl<Expr *> &Outputs);
StmtResult SubstStmt(Stmt *S,
const MultiLevelTemplateArgumentList &TemplateArgs);
Decl *SubstDecl(Decl *D, DeclContext *Owner,
const MultiLevelTemplateArgumentList &TemplateArgs);
ExprResult SubstInitializer(Expr *E,
const MultiLevelTemplateArgumentList &TemplateArgs,
bool CXXDirectInit);
bool
SubstBaseSpecifiers(CXXRecordDecl *Instantiation,
CXXRecordDecl *Pattern,
const MultiLevelTemplateArgumentList &TemplateArgs);
bool
InstantiateClass(SourceLocation PointOfInstantiation,
CXXRecordDecl *Instantiation, CXXRecordDecl *Pattern,
const MultiLevelTemplateArgumentList &TemplateArgs,
TemplateSpecializationKind TSK,
bool Complain = true);
bool InstantiateEnum(SourceLocation PointOfInstantiation,
EnumDecl *Instantiation, EnumDecl *Pattern,
const MultiLevelTemplateArgumentList &TemplateArgs,
TemplateSpecializationKind TSK);
bool InstantiateInClassInitializer(
SourceLocation PointOfInstantiation, FieldDecl *Instantiation,
FieldDecl *Pattern, const MultiLevelTemplateArgumentList &TemplateArgs);
struct LateInstantiatedAttribute {
const Attr *TmplAttr;
LocalInstantiationScope *Scope;
Decl *NewDecl;
LateInstantiatedAttribute(const Attr *A, LocalInstantiationScope *S,
Decl *D)
: TmplAttr(A), Scope(S), NewDecl(D)
{ }
};
typedef SmallVector<LateInstantiatedAttribute, 16> LateInstantiatedAttrVec;
void InstantiateAttrs(const MultiLevelTemplateArgumentList &TemplateArgs,
const Decl *Pattern, Decl *Inst,
LateInstantiatedAttrVec *LateAttrs = nullptr,
LocalInstantiationScope *OuterMostScope = nullptr);
bool
InstantiateClassTemplateSpecialization(SourceLocation PointOfInstantiation,
ClassTemplateSpecializationDecl *ClassTemplateSpec,
TemplateSpecializationKind TSK,
bool Complain = true);
void InstantiateClassMembers(SourceLocation PointOfInstantiation,
CXXRecordDecl *Instantiation,
const MultiLevelTemplateArgumentList &TemplateArgs,
TemplateSpecializationKind TSK);
void InstantiateClassTemplateSpecializationMembers(
SourceLocation PointOfInstantiation,
ClassTemplateSpecializationDecl *ClassTemplateSpec,
TemplateSpecializationKind TSK);
NestedNameSpecifierLoc
SubstNestedNameSpecifierLoc(NestedNameSpecifierLoc NNS,
const MultiLevelTemplateArgumentList &TemplateArgs);
DeclarationNameInfo
SubstDeclarationNameInfo(const DeclarationNameInfo &NameInfo,
const MultiLevelTemplateArgumentList &TemplateArgs);
TemplateName
SubstTemplateName(NestedNameSpecifierLoc QualifierLoc, TemplateName Name,
SourceLocation Loc,
const MultiLevelTemplateArgumentList &TemplateArgs);
bool Subst(const TemplateArgumentLoc *Args, unsigned NumArgs,
TemplateArgumentListInfo &Result,
const MultiLevelTemplateArgumentList &TemplateArgs);
void InstantiateExceptionSpec(SourceLocation PointOfInstantiation,
FunctionDecl *Function);
void InstantiateFunctionDefinition(SourceLocation PointOfInstantiation,
FunctionDecl *Function,
bool Recursive = false,
bool DefinitionRequired = false);
VarTemplateSpecializationDecl *BuildVarTemplateInstantiation(
VarTemplateDecl *VarTemplate, VarDecl *FromVar,
const TemplateArgumentList &TemplateArgList,
const TemplateArgumentListInfo &TemplateArgsInfo,
SmallVectorImpl<TemplateArgument> &Converted,
SourceLocation PointOfInstantiation, void *InsertPos,
LateInstantiatedAttrVec *LateAttrs = nullptr,
LocalInstantiationScope *StartingScope = nullptr);
VarTemplateSpecializationDecl *CompleteVarTemplateSpecializationDecl(
VarTemplateSpecializationDecl *VarSpec, VarDecl *PatternDecl,
const MultiLevelTemplateArgumentList &TemplateArgs);
void
BuildVariableInstantiation(VarDecl *NewVar, VarDecl *OldVar,
const MultiLevelTemplateArgumentList &TemplateArgs,
LateInstantiatedAttrVec *LateAttrs,
DeclContext *Owner,
LocalInstantiationScope *StartingScope,
bool InstantiatingVarTemplate = false);
void InstantiateVariableInitializer(
VarDecl *Var, VarDecl *OldVar,
const MultiLevelTemplateArgumentList &TemplateArgs);
void InstantiateVariableDefinition(SourceLocation PointOfInstantiation,
VarDecl *Var, bool Recursive = false,
bool DefinitionRequired = false);
void InstantiateStaticDataMemberDefinition(
SourceLocation PointOfInstantiation,
VarDecl *Var,
bool Recursive = false,
bool DefinitionRequired = false);
void InstantiateMemInitializers(CXXConstructorDecl *New,
const CXXConstructorDecl *Tmpl,
const MultiLevelTemplateArgumentList &TemplateArgs);
NamedDecl *FindInstantiatedDecl(SourceLocation Loc, NamedDecl *D,
const MultiLevelTemplateArgumentList &TemplateArgs);
DeclContext *FindInstantiatedContext(SourceLocation Loc, DeclContext *DC,
const MultiLevelTemplateArgumentList &TemplateArgs);
// Objective-C declarations.
enum ObjCContainerKind {
OCK_None = -1,
OCK_Interface = 0,
OCK_Protocol,
OCK_Category,
OCK_ClassExtension,
OCK_Implementation,
OCK_CategoryImplementation
};
ObjCContainerKind getObjCContainerKind() const;
DeclResult actOnObjCTypeParam(Scope *S,
ObjCTypeParamVariance variance,
SourceLocation varianceLoc,
unsigned index,
IdentifierInfo *paramName,
SourceLocation paramLoc,
SourceLocation colonLoc,
ParsedType typeBound);
ObjCTypeParamList *actOnObjCTypeParamList(Scope *S, SourceLocation lAngleLoc,
ArrayRef<Decl *> typeParams,
SourceLocation rAngleLoc);
void popObjCTypeParamList(Scope *S, ObjCTypeParamList *typeParamList);
Decl *ActOnStartClassInterface(Scope *S,
SourceLocation AtInterfaceLoc,
IdentifierInfo *ClassName,
SourceLocation ClassLoc,
ObjCTypeParamList *typeParamList,
IdentifierInfo *SuperName,
SourceLocation SuperLoc,
ArrayRef<ParsedType> SuperTypeArgs,
SourceRange SuperTypeArgsRange,
Decl * const *ProtoRefs,
unsigned NumProtoRefs,
const SourceLocation *ProtoLocs,
SourceLocation EndProtoLoc,
AttributeList *AttrList);
void ActOnSuperClassOfClassInterface(Scope *S,
SourceLocation AtInterfaceLoc,
ObjCInterfaceDecl *IDecl,
IdentifierInfo *ClassName,
SourceLocation ClassLoc,
IdentifierInfo *SuperName,
SourceLocation SuperLoc,
ArrayRef<ParsedType> SuperTypeArgs,
SourceRange SuperTypeArgsRange);
void ActOnTypedefedProtocols(SmallVectorImpl<Decl *> &ProtocolRefs,
IdentifierInfo *SuperName,
SourceLocation SuperLoc);
Decl *ActOnCompatibilityAlias(
SourceLocation AtCompatibilityAliasLoc,
IdentifierInfo *AliasName, SourceLocation AliasLocation,
IdentifierInfo *ClassName, SourceLocation ClassLocation);
bool CheckForwardProtocolDeclarationForCircularDependency(
IdentifierInfo *PName,
SourceLocation &PLoc, SourceLocation PrevLoc,
const ObjCList<ObjCProtocolDecl> &PList);
Decl *ActOnStartProtocolInterface(
SourceLocation AtProtoInterfaceLoc,
IdentifierInfo *ProtocolName, SourceLocation ProtocolLoc,
Decl * const *ProtoRefNames, unsigned NumProtoRefs,
const SourceLocation *ProtoLocs,
SourceLocation EndProtoLoc,
AttributeList *AttrList);
Decl *ActOnStartCategoryInterface(SourceLocation AtInterfaceLoc,
IdentifierInfo *ClassName,
SourceLocation ClassLoc,
ObjCTypeParamList *typeParamList,
IdentifierInfo *CategoryName,
SourceLocation CategoryLoc,
Decl * const *ProtoRefs,
unsigned NumProtoRefs,
const SourceLocation *ProtoLocs,
SourceLocation EndProtoLoc);
Decl *ActOnStartClassImplementation(
SourceLocation AtClassImplLoc,
IdentifierInfo *ClassName, SourceLocation ClassLoc,
IdentifierInfo *SuperClassname,
SourceLocation SuperClassLoc);
Decl *ActOnStartCategoryImplementation(SourceLocation AtCatImplLoc,
IdentifierInfo *ClassName,
SourceLocation ClassLoc,
IdentifierInfo *CatName,
SourceLocation CatLoc);
DeclGroupPtrTy ActOnFinishObjCImplementation(Decl *ObjCImpDecl,
ArrayRef<Decl *> Decls);
DeclGroupPtrTy ActOnForwardClassDeclaration(SourceLocation Loc,
IdentifierInfo **IdentList,
SourceLocation *IdentLocs,
ArrayRef<ObjCTypeParamList *> TypeParamLists,
unsigned NumElts);
DeclGroupPtrTy ActOnForwardProtocolDeclaration(SourceLocation AtProtoclLoc,
const IdentifierLocPair *IdentList,
unsigned NumElts,
AttributeList *attrList);
void FindProtocolDeclaration(bool WarnOnDeclarations, bool ForObjCContainer,
const IdentifierLocPair *ProtocolId,
unsigned NumProtocols,
SmallVectorImpl<Decl *> &Protocols);
/// Given a list of identifiers (and their locations), resolve the
/// names to either Objective-C protocol qualifiers or type
/// arguments, as appropriate.
void actOnObjCTypeArgsOrProtocolQualifiers(
Scope *S,
ParsedType baseType,
SourceLocation lAngleLoc,
ArrayRef<IdentifierInfo *> identifiers,
ArrayRef<SourceLocation> identifierLocs,
SourceLocation rAngleLoc,
SourceLocation &typeArgsLAngleLoc,
SmallVectorImpl<ParsedType> &typeArgs,
SourceLocation &typeArgsRAngleLoc,
SourceLocation &protocolLAngleLoc,
SmallVectorImpl<Decl *> &protocols,
SourceLocation &protocolRAngleLoc,
bool warnOnIncompleteProtocols);
/// Build a an Objective-C protocol-qualified 'id' type where no
/// base type was specified.
TypeResult actOnObjCProtocolQualifierType(
SourceLocation lAngleLoc,
ArrayRef<Decl *> protocols,
ArrayRef<SourceLocation> protocolLocs,
SourceLocation rAngleLoc);
/// Build a specialized and/or protocol-qualified Objective-C type.
TypeResult actOnObjCTypeArgsAndProtocolQualifiers(
Scope *S,
SourceLocation Loc,
ParsedType BaseType,
SourceLocation TypeArgsLAngleLoc,
ArrayRef<ParsedType> TypeArgs,
SourceLocation TypeArgsRAngleLoc,
SourceLocation ProtocolLAngleLoc,
ArrayRef<Decl *> Protocols,
ArrayRef<SourceLocation> ProtocolLocs,
SourceLocation ProtocolRAngleLoc);
/// Build an Objective-C object pointer type.
QualType BuildObjCObjectType(QualType BaseType,
SourceLocation Loc,
SourceLocation TypeArgsLAngleLoc,
ArrayRef<TypeSourceInfo *> TypeArgs,
SourceLocation TypeArgsRAngleLoc,
SourceLocation ProtocolLAngleLoc,
ArrayRef<ObjCProtocolDecl *> Protocols,
ArrayRef<SourceLocation> ProtocolLocs,
SourceLocation ProtocolRAngleLoc,
bool FailOnError = false);
/// Check the application of the Objective-C '__kindof' qualifier to
/// the given type.
bool checkObjCKindOfType(QualType &type, SourceLocation loc);
/// Ensure attributes are consistent with type.
/// \param [in, out] Attributes The attributes to check; they will
/// be modified to be consistent with \p PropertyTy.
void CheckObjCPropertyAttributes(Decl *PropertyPtrTy,
SourceLocation Loc,
unsigned &Attributes,
bool propertyInPrimaryClass);
/// Process the specified property declaration and create decls for the
/// setters and getters as needed.
/// \param property The property declaration being processed
/// \param CD The semantic container for the property
/// \param redeclaredProperty Declaration for property if redeclared
/// in class extension.
/// \param lexicalDC Container for redeclaredProperty.
void ProcessPropertyDecl(ObjCPropertyDecl *property,
ObjCContainerDecl *CD,
ObjCPropertyDecl *redeclaredProperty = nullptr,
ObjCContainerDecl *lexicalDC = nullptr);
void DiagnosePropertyMismatch(ObjCPropertyDecl *Property,
ObjCPropertyDecl *SuperProperty,
const IdentifierInfo *Name,
bool OverridingProtocolProperty);
void DiagnoseClassExtensionDupMethods(ObjCCategoryDecl *CAT,
ObjCInterfaceDecl *ID);
Decl *ActOnAtEnd(Scope *S, SourceRange AtEnd,
ArrayRef<Decl *> allMethods = None,
ArrayRef<DeclGroupPtrTy> allTUVars = None);
Decl *ActOnProperty(Scope *S, SourceLocation AtLoc,
SourceLocation LParenLoc,
FieldDeclarator &FD, ObjCDeclSpec &ODS,
Selector GetterSel, Selector SetterSel,
bool *OverridingProperty,
tok::ObjCKeywordKind MethodImplKind,
DeclContext *lexicalDC = nullptr);
Decl *ActOnPropertyImplDecl(Scope *S,
SourceLocation AtLoc,
SourceLocation PropertyLoc,
bool ImplKind,
IdentifierInfo *PropertyId,
IdentifierInfo *PropertyIvar,
SourceLocation PropertyIvarLoc);
enum ObjCSpecialMethodKind {
OSMK_None,
OSMK_Alloc,
OSMK_New,
OSMK_Copy,
OSMK_RetainingInit,
OSMK_NonRetainingInit
};
struct ObjCArgInfo {
IdentifierInfo *Name;
SourceLocation NameLoc;
// The Type is null if no type was specified, and the DeclSpec is invalid
// in this case.
ParsedType Type;
ObjCDeclSpec DeclSpec;
/// ArgAttrs - Attribute list for this argument.
AttributeList *ArgAttrs;
};
Decl *ActOnMethodDeclaration(
Scope *S,
SourceLocation BeginLoc, // location of the + or -.
SourceLocation EndLoc, // location of the ; or {.
tok::TokenKind MethodType,
ObjCDeclSpec &ReturnQT, ParsedType ReturnType,
ArrayRef<SourceLocation> SelectorLocs, Selector Sel,
// optional arguments. The number of types/arguments is obtained
// from the Sel.getNumArgs().
ObjCArgInfo *ArgInfo,
DeclaratorChunk::ParamInfo *CParamInfo, unsigned CNumArgs, // c-style args
AttributeList *AttrList, tok::ObjCKeywordKind MethodImplKind,
bool isVariadic, bool MethodDefinition);
ObjCMethodDecl *LookupMethodInQualifiedType(Selector Sel,
const ObjCObjectPointerType *OPT,
bool IsInstance);
ObjCMethodDecl *LookupMethodInObjectType(Selector Sel, QualType Ty,
bool IsInstance);
bool CheckARCMethodDecl(ObjCMethodDecl *method);
bool inferObjCARCLifetime(ValueDecl *decl);
ExprResult
HandleExprPropertyRefExpr(const ObjCObjectPointerType *OPT,
Expr *BaseExpr,
SourceLocation OpLoc,
DeclarationName MemberName,
SourceLocation MemberLoc,
SourceLocation SuperLoc, QualType SuperType,
bool Super);
ExprResult
ActOnClassPropertyRefExpr(IdentifierInfo &receiverName,
IdentifierInfo &propertyName,
SourceLocation receiverNameLoc,
SourceLocation propertyNameLoc);
ObjCMethodDecl *tryCaptureObjCSelf(SourceLocation Loc);
/// \brief Describes the kind of message expression indicated by a message
/// send that starts with an identifier.
enum ObjCMessageKind {
/// \brief The message is sent to 'super'.
ObjCSuperMessage,
/// \brief The message is an instance message.
ObjCInstanceMessage,
/// \brief The message is a class message, and the identifier is a type
/// name.
ObjCClassMessage
};
ObjCMessageKind getObjCMessageKind(Scope *S,
IdentifierInfo *Name,
SourceLocation NameLoc,
bool IsSuper,
bool HasTrailingDot,
ParsedType &ReceiverType);
ExprResult ActOnSuperMessage(Scope *S, SourceLocation SuperLoc,
Selector Sel,
SourceLocation LBracLoc,
ArrayRef<SourceLocation> SelectorLocs,
SourceLocation RBracLoc,
MultiExprArg Args);
ExprResult BuildClassMessage(TypeSourceInfo *ReceiverTypeInfo,
QualType ReceiverType,
SourceLocation SuperLoc,
Selector Sel,
ObjCMethodDecl *Method,
SourceLocation LBracLoc,
ArrayRef<SourceLocation> SelectorLocs,
SourceLocation RBracLoc,
MultiExprArg Args,
bool isImplicit = false);
ExprResult BuildClassMessageImplicit(QualType ReceiverType,
bool isSuperReceiver,
SourceLocation Loc,
Selector Sel,
ObjCMethodDecl *Method,
MultiExprArg Args);
ExprResult ActOnClassMessage(Scope *S,
ParsedType Receiver,
Selector Sel,
SourceLocation LBracLoc,
ArrayRef<SourceLocation> SelectorLocs,
SourceLocation RBracLoc,
MultiExprArg Args);
ExprResult BuildInstanceMessage(Expr *Receiver,
QualType ReceiverType,
SourceLocation SuperLoc,
Selector Sel,
ObjCMethodDecl *Method,
SourceLocation LBracLoc,
ArrayRef<SourceLocation> SelectorLocs,
SourceLocation RBracLoc,
MultiExprArg Args,
bool isImplicit = false);
ExprResult BuildInstanceMessageImplicit(Expr *Receiver,
QualType ReceiverType,
SourceLocation Loc,
Selector Sel,
ObjCMethodDecl *Method,
MultiExprArg Args);
ExprResult ActOnInstanceMessage(Scope *S,
Expr *Receiver,
Selector Sel,
SourceLocation LBracLoc,
ArrayRef<SourceLocation> SelectorLocs,
SourceLocation RBracLoc,
MultiExprArg Args);
ExprResult BuildObjCBridgedCast(SourceLocation LParenLoc,
ObjCBridgeCastKind Kind,
SourceLocation BridgeKeywordLoc,
TypeSourceInfo *TSInfo,
Expr *SubExpr);
ExprResult ActOnObjCBridgedCast(Scope *S,
SourceLocation LParenLoc,
ObjCBridgeCastKind Kind,
SourceLocation BridgeKeywordLoc,
ParsedType Type,
SourceLocation RParenLoc,
Expr *SubExpr);
void CheckTollFreeBridgeCast(QualType castType, Expr *castExpr);
void CheckObjCBridgeRelatedCast(QualType castType, Expr *castExpr);
bool CheckTollFreeBridgeStaticCast(QualType castType, Expr *castExpr,
CastKind &Kind);
bool checkObjCBridgeRelatedComponents(SourceLocation Loc,
QualType DestType, QualType SrcType,
ObjCInterfaceDecl *&RelatedClass,
ObjCMethodDecl *&ClassMethod,
ObjCMethodDecl *&InstanceMethod,
TypedefNameDecl *&TDNDecl,
bool CfToNs);
bool CheckObjCBridgeRelatedConversions(SourceLocation Loc,
QualType DestType, QualType SrcType,
Expr *&SrcExpr);
bool ConversionToObjCStringLiteralCheck(QualType DstType, Expr *&SrcExpr);
bool checkInitMethod(ObjCMethodDecl *method, QualType receiverTypeIfCall);
/// \brief Check whether the given new method is a valid override of the
/// given overridden method, and set any properties that should be inherited.
void CheckObjCMethodOverride(ObjCMethodDecl *NewMethod,
const ObjCMethodDecl *Overridden);
/// \brief Describes the compatibility of a result type with its method.
enum ResultTypeCompatibilityKind {
RTC_Compatible,
RTC_Incompatible,
RTC_Unknown
};
void CheckObjCMethodOverrides(ObjCMethodDecl *ObjCMethod,
ObjCInterfaceDecl *CurrentClass,
ResultTypeCompatibilityKind RTC);
enum PragmaOptionsAlignKind {
POAK_Native, // #pragma options align=native
POAK_Natural, // #pragma options align=natural
POAK_Packed, // #pragma options align=packed
POAK_Power, // #pragma options align=power
POAK_Mac68k, // #pragma options align=mac68k
POAK_Reset // #pragma options align=reset
};
/// ActOnPragmaOptionsAlign - Called on well formed \#pragma options align.
void ActOnPragmaOptionsAlign(PragmaOptionsAlignKind Kind,
SourceLocation PragmaLoc);
enum PragmaPackKind {
PPK_Default, // #pragma pack([n])
PPK_Show, // #pragma pack(show), only supported by MSVC.
PPK_Push, // #pragma pack(push, [identifier], [n])
PPK_Pop // #pragma pack(pop, [identifier], [n])
};
enum PragmaMSStructKind {
PMSST_OFF, // #pragms ms_struct off
PMSST_ON // #pragms ms_struct on
};
enum PragmaMSCommentKind {
PCK_Unknown,
PCK_Linker, // #pragma comment(linker, ...)
PCK_Lib, // #pragma comment(lib, ...)
PCK_Compiler, // #pragma comment(compiler, ...)
PCK_ExeStr, // #pragma comment(exestr, ...)
PCK_User // #pragma comment(user, ...)
};
/// ActOnPragmaPack - Called on well formed \#pragma pack(...).
void ActOnPragmaPack(PragmaPackKind Kind,
IdentifierInfo *Name,
Expr *Alignment,
SourceLocation PragmaLoc,
SourceLocation LParenLoc,
SourceLocation RParenLoc);
/// ActOnPragmaMSStruct - Called on well formed \#pragma ms_struct [on|off].
void ActOnPragmaMSStruct(PragmaMSStructKind Kind);
/// ActOnPragmaMSComment - Called on well formed
/// \#pragma comment(kind, "arg").
void ActOnPragmaMSComment(PragmaMSCommentKind Kind, StringRef Arg);
/// ActOnPragmaMSPointersToMembers - called on well formed \#pragma
/// pointers_to_members(representation method[, general purpose
/// representation]).
void ActOnPragmaMSPointersToMembers(
LangOptions::PragmaMSPointersToMembersKind Kind,
SourceLocation PragmaLoc);
/// \brief Called on well formed \#pragma vtordisp().
void ActOnPragmaMSVtorDisp(PragmaVtorDispKind Kind, SourceLocation PragmaLoc,
MSVtorDispAttr::Mode Value);
enum PragmaSectionKind {
PSK_DataSeg,
PSK_BSSSeg,
PSK_ConstSeg,
PSK_CodeSeg,
};
bool UnifySection(StringRef SectionName,
int SectionFlags,
DeclaratorDecl *TheDecl);
bool UnifySection(StringRef SectionName,
int SectionFlags,
SourceLocation PragmaSectionLocation);
/// \brief Called on well formed \#pragma bss_seg/data_seg/const_seg/code_seg.
void ActOnPragmaMSSeg(SourceLocation PragmaLocation,
PragmaMsStackAction Action,
llvm::StringRef StackSlotLabel,
StringLiteral *SegmentName,
llvm::StringRef PragmaName);
/// \brief Called on well formed \#pragma section().
void ActOnPragmaMSSection(SourceLocation PragmaLocation,
int SectionFlags, StringLiteral *SegmentName);
/// \brief Called on well-formed \#pragma init_seg().
void ActOnPragmaMSInitSeg(SourceLocation PragmaLocation,
StringLiteral *SegmentName);
/// ActOnPragmaDetectMismatch - Call on well-formed \#pragma detect_mismatch
void ActOnPragmaDetectMismatch(StringRef Name, StringRef Value);
/// ActOnPragmaUnused - Called on well-formed '\#pragma unused'.
void ActOnPragmaUnused(const Token &Identifier,
Scope *curScope,
SourceLocation PragmaLoc);
/// ActOnPragmaVisibility - Called on well formed \#pragma GCC visibility... .
void ActOnPragmaVisibility(const IdentifierInfo* VisType,
SourceLocation PragmaLoc);
NamedDecl *DeclClonePragmaWeak(NamedDecl *ND, IdentifierInfo *II,
SourceLocation Loc);
void DeclApplyPragmaWeak(Scope *S, NamedDecl *ND, WeakInfo &W);
/// ActOnPragmaWeakID - Called on well formed \#pragma weak ident.
void ActOnPragmaWeakID(IdentifierInfo* WeakName,
SourceLocation PragmaLoc,
SourceLocation WeakNameLoc);
/// ActOnPragmaRedefineExtname - Called on well formed
/// \#pragma redefine_extname oldname newname.
void ActOnPragmaRedefineExtname(IdentifierInfo* WeakName,
IdentifierInfo* AliasName,
SourceLocation PragmaLoc,
SourceLocation WeakNameLoc,
SourceLocation AliasNameLoc);
/// ActOnPragmaWeakAlias - Called on well formed \#pragma weak ident = ident.
void ActOnPragmaWeakAlias(IdentifierInfo* WeakName,
IdentifierInfo* AliasName,
SourceLocation PragmaLoc,
SourceLocation WeakNameLoc,
SourceLocation AliasNameLoc);
/// ActOnPragmaFPContract - Called on well formed
/// \#pragma {STDC,OPENCL} FP_CONTRACT
void ActOnPragmaFPContract(tok::OnOffSwitch OOS);
/// AddAlignmentAttributesForRecord - Adds any needed alignment attributes to
/// a the record decl, to handle '\#pragma pack' and '\#pragma options align'.
void AddAlignmentAttributesForRecord(RecordDecl *RD);
/// AddMsStructLayoutForRecord - Adds ms_struct layout attribute to record.
void AddMsStructLayoutForRecord(RecordDecl *RD);
/// FreePackedContext - Deallocate and null out PackContext.
void FreePackedContext();
/// PushNamespaceVisibilityAttr - Note that we've entered a
/// namespace with a visibility attribute.
void PushNamespaceVisibilityAttr(const VisibilityAttr *Attr,
SourceLocation Loc);
/// AddPushedVisibilityAttribute - If '\#pragma GCC visibility' was used,
/// add an appropriate visibility attribute.
void AddPushedVisibilityAttribute(Decl *RD);
/// PopPragmaVisibility - Pop the top element of the visibility stack; used
/// for '\#pragma GCC visibility' and visibility attributes on namespaces.
void PopPragmaVisibility(bool IsNamespaceEnd, SourceLocation EndLoc);
/// FreeVisContext - Deallocate and null out VisContext.
void FreeVisContext();
/// AddCFAuditedAttribute - Check whether we're currently within
/// '\#pragma clang arc_cf_code_audited' and, if so, consider adding
/// the appropriate attribute.
void AddCFAuditedAttribute(Decl *D);
/// \brief Called on well formed \#pragma clang optimize.
void ActOnPragmaOptimize(bool On, SourceLocation PragmaLoc);
/// \brief Get the location for the currently active "\#pragma clang optimize
/// off". If this location is invalid, then the state of the pragma is "on".
SourceLocation getOptimizeOffPragmaLocation() const {
return OptimizeOffPragmaLocation;
}
/// \brief Only called on function definitions; if there is a pragma in scope
/// with the effect of a range-based optnone, consider marking the function
/// with attribute optnone.
void AddRangeBasedOptnone(FunctionDecl *FD);
/// \brief Adds the 'optnone' attribute to the function declaration if there
/// are no conflicts; Loc represents the location causing the 'optnone'
/// attribute to be added (usually because of a pragma).
void AddOptnoneAttributeIfNoConflicts(FunctionDecl *FD, SourceLocation Loc);
/// AddAlignedAttr - Adds an aligned attribute to a particular declaration.
void AddAlignedAttr(SourceRange AttrRange, Decl *D, Expr *E,
unsigned SpellingListIndex, bool IsPackExpansion);
void AddAlignedAttr(SourceRange AttrRange, Decl *D, TypeSourceInfo *T,
unsigned SpellingListIndex, bool IsPackExpansion);
/// AddAssumeAlignedAttr - Adds an assume_aligned attribute to a particular
/// declaration.
void AddAssumeAlignedAttr(SourceRange AttrRange, Decl *D, Expr *E, Expr *OE,
unsigned SpellingListIndex);
/// AddAlignValueAttr - Adds an align_value attribute to a particular
/// declaration.
void AddAlignValueAttr(SourceRange AttrRange, Decl *D, Expr *E,
unsigned SpellingListIndex);
/// AddLaunchBoundsAttr - Adds a launch_bounds attribute to a particular
/// declaration.
void AddLaunchBoundsAttr(SourceRange AttrRange, Decl *D, Expr *MaxThreads,
Expr *MinBlocks, unsigned SpellingListIndex);
// OpenMP directives and clauses.
private:
void *VarDataSharingAttributesStack;
/// \brief Initialization of data-sharing attributes stack.
void InitDataSharingAttributesStack();
void DestroyDataSharingAttributesStack();
ExprResult VerifyPositiveIntegerConstantInClause(Expr *Op,
OpenMPClauseKind CKind);
public:
/// \brief Check if the specified variable is used in a private clause in
/// Checks if the specified variable is used in one of the private
/// clauses in OpenMP constructs.
bool IsOpenMPCapturedVar(VarDecl *VD);
/// OpenMP constructs.
/// \param Level Relative level of nested OpenMP construct for that the check
/// is performed.
bool isOpenMPPrivateVar(VarDecl *VD, unsigned Level);
ExprResult PerformOpenMPImplicitIntegerConversion(SourceLocation OpLoc,
Expr *Op);
/// \brief Called on start of new data sharing attribute block.
void StartOpenMPDSABlock(OpenMPDirectiveKind K,
const DeclarationNameInfo &DirName, Scope *CurScope,
SourceLocation Loc);
/// \brief Start analysis of clauses.
void StartOpenMPClause(OpenMPClauseKind K);
/// \brief End analysis of clauses.
void EndOpenMPClause();
/// \brief Called on end of data sharing attribute block.
void EndOpenMPDSABlock(Stmt *CurDirective);
/// \brief Check if the current region is an OpenMP loop region and if it is,
/// mark loop control variable, used in \p Init for loop initialization, as
/// private by default.
/// \param Init First part of the for loop.
void ActOnOpenMPLoopInitialization(SourceLocation ForLoc, Stmt *Init);
// OpenMP directives and clauses.
/// \brief Called on correct id-expression from the '#pragma omp
/// threadprivate'.
ExprResult ActOnOpenMPIdExpression(Scope *CurScope,
CXXScopeSpec &ScopeSpec,
const DeclarationNameInfo &Id);
/// \brief Called on well-formed '#pragma omp threadprivate'.
DeclGroupPtrTy ActOnOpenMPThreadprivateDirective(
SourceLocation Loc,
ArrayRef<Expr *> VarList);
/// \brief Builds a new OpenMPThreadPrivateDecl and checks its correctness.
OMPThreadPrivateDecl *CheckOMPThreadPrivateDecl(
SourceLocation Loc,
ArrayRef<Expr *> VarList);
/// \brief Initialization of captured region for OpenMP region.
void ActOnOpenMPRegionStart(OpenMPDirectiveKind DKind, Scope *CurScope);
/// \brief End of OpenMP region.
///
/// \param S Statement associated with the current OpenMP region.
/// \param Clauses List of clauses for the current OpenMP region.
///
/// \returns Statement for finished OpenMP region.
StmtResult ActOnOpenMPRegionEnd(StmtResult S, ArrayRef<OMPClause *> Clauses);
StmtResult ActOnOpenMPExecutableDirective(
OpenMPDirectiveKind Kind, const DeclarationNameInfo &DirName,
OpenMPDirectiveKind CancelRegion, ArrayRef<OMPClause *> Clauses,
Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc);
/// \brief Called on well-formed '\#pragma omp parallel' after parsing
/// of the associated statement.
StmtResult ActOnOpenMPParallelDirective(ArrayRef<OMPClause *> Clauses,
Stmt *AStmt,
SourceLocation StartLoc,
SourceLocation EndLoc);
/// \brief Called on well-formed '\#pragma omp simd' after parsing
/// of the associated statement.
StmtResult ActOnOpenMPSimdDirective(
ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
SourceLocation EndLoc,
llvm::DenseMap<VarDecl *, Expr *> &VarsWithImplicitDSA);
/// \brief Called on well-formed '\#pragma omp for' after parsing
/// of the associated statement.
StmtResult ActOnOpenMPForDirective(
ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
SourceLocation EndLoc,
llvm::DenseMap<VarDecl *, Expr *> &VarsWithImplicitDSA);
/// \brief Called on well-formed '\#pragma omp for simd' after parsing
/// of the associated statement.
StmtResult ActOnOpenMPForSimdDirective(
ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
SourceLocation EndLoc,
llvm::DenseMap<VarDecl *, Expr *> &VarsWithImplicitDSA);
/// \brief Called on well-formed '\#pragma omp sections' after parsing
/// of the associated statement.
StmtResult ActOnOpenMPSectionsDirective(ArrayRef<OMPClause *> Clauses,
Stmt *AStmt, SourceLocation StartLoc,
SourceLocation EndLoc);
/// \brief Called on well-formed '\#pragma omp section' after parsing of the
/// associated statement.
StmtResult ActOnOpenMPSectionDirective(Stmt *AStmt, SourceLocation StartLoc,
SourceLocation EndLoc);
/// \brief Called on well-formed '\#pragma omp single' after parsing of the
/// associated statement.
StmtResult ActOnOpenMPSingleDirective(ArrayRef<OMPClause *> Clauses,
Stmt *AStmt, SourceLocation StartLoc,
SourceLocation EndLoc);
/// \brief Called on well-formed '\#pragma omp master' after parsing of the
/// associated statement.
StmtResult ActOnOpenMPMasterDirective(Stmt *AStmt, SourceLocation StartLoc,
SourceLocation EndLoc);
/// \brief Called on well-formed '\#pragma omp critical' after parsing of the
/// associated statement.
StmtResult ActOnOpenMPCriticalDirective(const DeclarationNameInfo &DirName,
Stmt *AStmt, SourceLocation StartLoc,
SourceLocation EndLoc);
/// \brief Called on well-formed '\#pragma omp parallel for' after parsing
/// of the associated statement.
StmtResult ActOnOpenMPParallelForDirective(
ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
SourceLocation EndLoc,
llvm::DenseMap<VarDecl *, Expr *> &VarsWithImplicitDSA);
/// \brief Called on well-formed '\#pragma omp parallel for simd' after
/// parsing of the associated statement.
StmtResult ActOnOpenMPParallelForSimdDirective(
ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
SourceLocation EndLoc,
llvm::DenseMap<VarDecl *, Expr *> &VarsWithImplicitDSA);
/// \brief Called on well-formed '\#pragma omp parallel sections' after
/// parsing of the associated statement.
StmtResult ActOnOpenMPParallelSectionsDirective(ArrayRef<OMPClause *> Clauses,
Stmt *AStmt,
SourceLocation StartLoc,
SourceLocation EndLoc);
/// \brief Called on well-formed '\#pragma omp task' after parsing of the
/// associated statement.
StmtResult ActOnOpenMPTaskDirective(ArrayRef<OMPClause *> Clauses,
Stmt *AStmt, SourceLocation StartLoc,
SourceLocation EndLoc);
/// \brief Called on well-formed '\#pragma omp taskyield'.
StmtResult ActOnOpenMPTaskyieldDirective(SourceLocation StartLoc,
SourceLocation EndLoc);
/// \brief Called on well-formed '\#pragma omp barrier'.
StmtResult ActOnOpenMPBarrierDirective(SourceLocation StartLoc,
SourceLocation EndLoc);
/// \brief Called on well-formed '\#pragma omp taskwait'.
StmtResult ActOnOpenMPTaskwaitDirective(SourceLocation StartLoc,
SourceLocation EndLoc);
/// \brief Called on well-formed '\#pragma omp taskgroup'.
StmtResult ActOnOpenMPTaskgroupDirective(Stmt *AStmt, SourceLocation StartLoc,
SourceLocation EndLoc);
/// \brief Called on well-formed '\#pragma omp flush'.
StmtResult ActOnOpenMPFlushDirective(ArrayRef<OMPClause *> Clauses,
SourceLocation StartLoc,
SourceLocation EndLoc);
/// \brief Called on well-formed '\#pragma omp ordered' after parsing of the
/// associated statement.
StmtResult ActOnOpenMPOrderedDirective(Stmt *AStmt, SourceLocation StartLoc,
SourceLocation EndLoc);
/// \brief Called on well-formed '\#pragma omp atomic' after parsing of the
/// associated statement.
StmtResult ActOnOpenMPAtomicDirective(ArrayRef<OMPClause *> Clauses,
Stmt *AStmt, SourceLocation StartLoc,
SourceLocation EndLoc);
/// \brief Called on well-formed '\#pragma omp target' after parsing of the
/// associated statement.
StmtResult ActOnOpenMPTargetDirective(ArrayRef<OMPClause *> Clauses,
Stmt *AStmt, SourceLocation StartLoc,
SourceLocation EndLoc);
/// \brief Called on well-formed '\#pragma omp teams' after parsing of the
/// associated statement.
StmtResult ActOnOpenMPTeamsDirective(ArrayRef<OMPClause *> Clauses,
Stmt *AStmt, SourceLocation StartLoc,
SourceLocation EndLoc);
/// \brief Called on well-formed '\#pragma omp cancellation point'.
StmtResult
ActOnOpenMPCancellationPointDirective(SourceLocation StartLoc,
SourceLocation EndLoc,
OpenMPDirectiveKind CancelRegion);
/// \brief Called on well-formed '\#pragma omp cancel'.
StmtResult ActOnOpenMPCancelDirective(SourceLocation StartLoc,
SourceLocation EndLoc,
OpenMPDirectiveKind CancelRegion);
OMPClause *ActOnOpenMPSingleExprClause(OpenMPClauseKind Kind,
Expr *Expr,
SourceLocation StartLoc,
SourceLocation LParenLoc,
SourceLocation EndLoc);
/// \brief Called on well-formed 'if' clause.
OMPClause *ActOnOpenMPIfClause(Expr *Condition, SourceLocation StartLoc,
SourceLocation LParenLoc,
SourceLocation EndLoc);
/// \brief Called on well-formed 'final' clause.
OMPClause *ActOnOpenMPFinalClause(Expr *Condition, SourceLocation StartLoc,
SourceLocation LParenLoc,
SourceLocation EndLoc);
/// \brief Called on well-formed 'num_threads' clause.
OMPClause *ActOnOpenMPNumThreadsClause(Expr *NumThreads,
SourceLocation StartLoc,
SourceLocation LParenLoc,
SourceLocation EndLoc);
/// \brief Called on well-formed 'safelen' clause.
OMPClause *ActOnOpenMPSafelenClause(Expr *Length,
SourceLocation StartLoc,
SourceLocation LParenLoc,
SourceLocation EndLoc);
/// \brief Called on well-formed 'collapse' clause.
OMPClause *ActOnOpenMPCollapseClause(Expr *NumForLoops,
SourceLocation StartLoc,
SourceLocation LParenLoc,
SourceLocation EndLoc);
OMPClause *ActOnOpenMPSimpleClause(OpenMPClauseKind Kind,
unsigned Argument,
SourceLocation ArgumentLoc,
SourceLocation StartLoc,
SourceLocation LParenLoc,
SourceLocation EndLoc);
/// \brief Called on well-formed 'default' clause.
OMPClause *ActOnOpenMPDefaultClause(OpenMPDefaultClauseKind Kind,
SourceLocation KindLoc,
SourceLocation StartLoc,
SourceLocation LParenLoc,
SourceLocation EndLoc);
/// \brief Called on well-formed 'proc_bind' clause.
OMPClause *ActOnOpenMPProcBindClause(OpenMPProcBindClauseKind Kind,
SourceLocation KindLoc,
SourceLocation StartLoc,
SourceLocation LParenLoc,
SourceLocation EndLoc);
OMPClause *ActOnOpenMPSingleExprWithArgClause(OpenMPClauseKind Kind,
unsigned Argument, Expr *Expr,
SourceLocation StartLoc,
SourceLocation LParenLoc,
SourceLocation ArgumentLoc,
SourceLocation CommaLoc,
SourceLocation EndLoc);
/// \brief Called on well-formed 'schedule' clause.
OMPClause *ActOnOpenMPScheduleClause(OpenMPScheduleClauseKind Kind,
Expr *ChunkSize, SourceLocation StartLoc,
SourceLocation LParenLoc,
SourceLocation KindLoc,
SourceLocation CommaLoc,
SourceLocation EndLoc);
OMPClause *ActOnOpenMPClause(OpenMPClauseKind Kind, SourceLocation StartLoc,
SourceLocation EndLoc);
/// \brief Called on well-formed 'ordered' clause.
OMPClause *ActOnOpenMPOrderedClause(SourceLocation StartLoc,
SourceLocation EndLoc);
/// \brief Called on well-formed 'nowait' clause.
OMPClause *ActOnOpenMPNowaitClause(SourceLocation StartLoc,
SourceLocation EndLoc);
/// \brief Called on well-formed 'untied' clause.
OMPClause *ActOnOpenMPUntiedClause(SourceLocation StartLoc,
SourceLocation EndLoc);
/// \brief Called on well-formed 'mergeable' clause.
OMPClause *ActOnOpenMPMergeableClause(SourceLocation StartLoc,
SourceLocation EndLoc);
/// \brief Called on well-formed 'read' clause.
OMPClause *ActOnOpenMPReadClause(SourceLocation StartLoc,
SourceLocation EndLoc);
/// \brief Called on well-formed 'write' clause.
OMPClause *ActOnOpenMPWriteClause(SourceLocation StartLoc,
SourceLocation EndLoc);
/// \brief Called on well-formed 'update' clause.
OMPClause *ActOnOpenMPUpdateClause(SourceLocation StartLoc,
SourceLocation EndLoc);
/// \brief Called on well-formed 'capture' clause.
OMPClause *ActOnOpenMPCaptureClause(SourceLocation StartLoc,
SourceLocation EndLoc);
/// \brief Called on well-formed 'seq_cst' clause.
OMPClause *ActOnOpenMPSeqCstClause(SourceLocation StartLoc,
SourceLocation EndLoc);
OMPClause *ActOnOpenMPVarListClause(
OpenMPClauseKind Kind, ArrayRef<Expr *> Vars, Expr *TailExpr,
SourceLocation StartLoc, SourceLocation LParenLoc,
SourceLocation ColonLoc, SourceLocation EndLoc,
CXXScopeSpec &ReductionIdScopeSpec,
const DeclarationNameInfo &ReductionId, OpenMPDependClauseKind DepKind,
SourceLocation DepLoc);
/// \brief Called on well-formed 'private' clause.
OMPClause *ActOnOpenMPPrivateClause(ArrayRef<Expr *> VarList,
SourceLocation StartLoc,
SourceLocation LParenLoc,
SourceLocation EndLoc);
/// \brief Called on well-formed 'firstprivate' clause.
OMPClause *ActOnOpenMPFirstprivateClause(ArrayRef<Expr *> VarList,
SourceLocation StartLoc,
SourceLocation LParenLoc,
SourceLocation EndLoc);
/// \brief Called on well-formed 'lastprivate' clause.
OMPClause *ActOnOpenMPLastprivateClause(ArrayRef<Expr *> VarList,
SourceLocation StartLoc,
SourceLocation LParenLoc,
SourceLocation EndLoc);
/// \brief Called on well-formed 'shared' clause.
OMPClause *ActOnOpenMPSharedClause(ArrayRef<Expr *> VarList,
SourceLocation StartLoc,
SourceLocation LParenLoc,
SourceLocation EndLoc);
/// \brief Called on well-formed 'reduction' clause.
OMPClause *
ActOnOpenMPReductionClause(ArrayRef<Expr *> VarList, SourceLocation StartLoc,
SourceLocation LParenLoc, SourceLocation ColonLoc,
SourceLocation EndLoc,
CXXScopeSpec &ReductionIdScopeSpec,
const DeclarationNameInfo &ReductionId);
/// \brief Called on well-formed 'linear' clause.
OMPClause *ActOnOpenMPLinearClause(ArrayRef<Expr *> VarList,
Expr *Step,
SourceLocation StartLoc,
SourceLocation LParenLoc,
SourceLocation ColonLoc,
SourceLocation EndLoc);
/// \brief Called on well-formed 'aligned' clause.
OMPClause *ActOnOpenMPAlignedClause(ArrayRef<Expr *> VarList,
Expr *Alignment,
SourceLocation StartLoc,
SourceLocation LParenLoc,
SourceLocation ColonLoc,
SourceLocation EndLoc);
/// \brief Called on well-formed 'copyin' clause.
OMPClause *ActOnOpenMPCopyinClause(ArrayRef<Expr *> VarList,
SourceLocation StartLoc,
SourceLocation LParenLoc,
SourceLocation EndLoc);
/// \brief Called on well-formed 'copyprivate' clause.
OMPClause *ActOnOpenMPCopyprivateClause(ArrayRef<Expr *> VarList,
SourceLocation StartLoc,
SourceLocation LParenLoc,
SourceLocation EndLoc);
/// \brief Called on well-formed 'flush' pseudo clause.
OMPClause *ActOnOpenMPFlushClause(ArrayRef<Expr *> VarList,
SourceLocation StartLoc,
SourceLocation LParenLoc,
SourceLocation EndLoc);
/// \brief Called on well-formed 'depend' clause.
OMPClause *
ActOnOpenMPDependClause(OpenMPDependClauseKind DepKind, SourceLocation DepLoc,
SourceLocation ColonLoc, ArrayRef<Expr *> VarList,
SourceLocation StartLoc, SourceLocation LParenLoc,
SourceLocation EndLoc);
/// \brief The kind of conversion being performed.
enum CheckedConversionKind {
/// \brief An implicit conversion.
CCK_ImplicitConversion,
/// \brief A C-style cast.
CCK_CStyleCast,
/// \brief A functional-style cast.
CCK_FunctionalCast,
/// \brief A cast other than a C-style cast.
CCK_OtherCast
};
/// ImpCastExprToType - If Expr is not of type 'Type', insert an implicit
/// cast. If there is already an implicit cast, merge into the existing one.
/// If isLvalue, the result of the cast is an lvalue.
ExprResult ImpCastExprToType(Expr *E, QualType Type, CastKind CK,
ExprValueKind VK = VK_RValue,
const CXXCastPath *BasePath = nullptr,
CheckedConversionKind CCK
= CCK_ImplicitConversion);
/// ScalarTypeToBooleanCastKind - Returns the cast kind corresponding
/// to the conversion from scalar type ScalarTy to the Boolean type.
static CastKind ScalarTypeToBooleanCastKind(QualType ScalarTy);
/// IgnoredValueConversions - Given that an expression's result is
/// syntactically ignored, perform any conversions that are
/// required.
ExprResult IgnoredValueConversions(Expr *E);
// UsualUnaryConversions - promotes integers (C99 6.3.1.1p2) and converts
// functions and arrays to their respective pointers (C99 6.3.2.1).
ExprResult UsualUnaryConversions(Expr *E);
/// CallExprUnaryConversions - a special case of an unary conversion
/// performed on a function designator of a call expression.
ExprResult CallExprUnaryConversions(Expr *E);
// DefaultFunctionArrayConversion - converts functions and arrays
// to their respective pointers (C99 6.3.2.1).
ExprResult DefaultFunctionArrayConversion(Expr *E);
// DefaultFunctionArrayLvalueConversion - converts functions and
// arrays to their respective pointers and performs the
// lvalue-to-rvalue conversion.
ExprResult DefaultFunctionArrayLvalueConversion(Expr *E);
// DefaultLvalueConversion - performs lvalue-to-rvalue conversion on
// the operand. This is DefaultFunctionArrayLvalueConversion,
// except that it assumes the operand isn't of function or array
// type.
ExprResult DefaultLvalueConversion(Expr *E);
// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
// do not have a prototype. Integer promotions are performed on each
// argument, and arguments that have type float are promoted to double.
ExprResult DefaultArgumentPromotion(Expr *E);
// Used for emitting the right warning by DefaultVariadicArgumentPromotion
enum VariadicCallType {
VariadicFunction,
VariadicBlock,
VariadicMethod,
VariadicConstructor,
VariadicDoesNotApply
};
VariadicCallType getVariadicCallType(FunctionDecl *FDecl,
const FunctionProtoType *Proto,
Expr *Fn);
// Used for determining in which context a type is allowed to be passed to a
// vararg function.
enum VarArgKind {
VAK_Valid,
VAK_ValidInCXX11,
VAK_Undefined,
VAK_MSVCUndefined,
VAK_Invalid
};
// Determines which VarArgKind fits an expression.
VarArgKind isValidVarArgType(const QualType &Ty);
/// Check to see if the given expression is a valid argument to a variadic
/// function, issuing a diagnostic if not.
void checkVariadicArgument(const Expr *E, VariadicCallType CT);
/// Check to see if a given expression could have '.c_str()' called on it.
bool hasCStrMethod(const Expr *E);
/// GatherArgumentsForCall - Collector argument expressions for various
/// form of call prototypes.
bool GatherArgumentsForCall(SourceLocation CallLoc, FunctionDecl *FDecl,
const FunctionProtoType *Proto,
unsigned FirstParam, ArrayRef<Expr *> Args,
SmallVectorImpl<Expr *> &AllArgs,
VariadicCallType CallType = VariadicDoesNotApply,
bool AllowExplicit = false,
bool IsListInitialization = false);
// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
// will create a runtime trap if the resulting type is not a POD type.
ExprResult DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT,
FunctionDecl *FDecl);
// UsualArithmeticConversions - performs the UsualUnaryConversions on it's
// operands and then handles various conversions that are common to binary
// operators (C99 6.3.1.8). If both operands aren't arithmetic, this
// routine returns the first non-arithmetic type found. The client is
// responsible for emitting appropriate error diagnostics.
QualType UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS,
bool IsCompAssign = false);
/// AssignConvertType - All of the 'assignment' semantic checks return this
/// enum to indicate whether the assignment was allowed. These checks are
/// done for simple assignments, as well as initialization, return from
/// function, argument passing, etc. The query is phrased in terms of a
/// source and destination type.
enum AssignConvertType {
/// Compatible - the types are compatible according to the standard.
Compatible,
/// PointerToInt - The assignment converts a pointer to an int, which we
/// accept as an extension.
PointerToInt,
/// IntToPointer - The assignment converts an int to a pointer, which we
/// accept as an extension.
IntToPointer,
/// FunctionVoidPointer - The assignment is between a function pointer and
/// void*, which the standard doesn't allow, but we accept as an extension.
FunctionVoidPointer,
/// IncompatiblePointer - The assignment is between two pointers types that
/// are not compatible, but we accept them as an extension.
IncompatiblePointer,
/// IncompatiblePointer - The assignment is between two pointers types which
/// point to integers which have a different sign, but are otherwise
/// identical. This is a subset of the above, but broken out because it's by
/// far the most common case of incompatible pointers.
IncompatiblePointerSign,
/// CompatiblePointerDiscardsQualifiers - The assignment discards
/// c/v/r qualifiers, which we accept as an extension.
CompatiblePointerDiscardsQualifiers,
/// IncompatiblePointerDiscardsQualifiers - The assignment
/// discards qualifiers that we don't permit to be discarded,
/// like address spaces.
IncompatiblePointerDiscardsQualifiers,
/// IncompatibleNestedPointerQualifiers - The assignment is between two
/// nested pointer types, and the qualifiers other than the first two
/// levels differ e.g. char ** -> const char **, but we accept them as an
/// extension.
IncompatibleNestedPointerQualifiers,
/// IncompatibleVectors - The assignment is between two vector types that
/// have the same size, which we accept as an extension.
IncompatibleVectors,
/// IntToBlockPointer - The assignment converts an int to a block
/// pointer. We disallow this.
IntToBlockPointer,
/// IncompatibleBlockPointer - The assignment is between two block
/// pointers types that are not compatible.
IncompatibleBlockPointer,
/// IncompatibleObjCQualifiedId - The assignment is between a qualified
/// id type and something else (that is incompatible with it). For example,
/// "id <XXX>" = "Foo *", where "Foo *" doesn't implement the XXX protocol.
IncompatibleObjCQualifiedId,
/// IncompatibleObjCWeakRef - Assigning a weak-unavailable object to an
/// object with __weak qualifier.
IncompatibleObjCWeakRef,
/// Incompatible - We reject this conversion outright, it is invalid to
/// represent it in the AST.
Incompatible
};
/// DiagnoseAssignmentResult - Emit a diagnostic, if required, for the
/// assignment conversion type specified by ConvTy. This returns true if the
/// conversion was invalid or false if the conversion was accepted.
bool DiagnoseAssignmentResult(AssignConvertType ConvTy,
SourceLocation Loc,
QualType DstType, QualType SrcType,
Expr *SrcExpr, AssignmentAction Action,
bool *Complained = nullptr);
/// IsValueInFlagEnum - Determine if a value is allowed as part of a flag
/// enum. If AllowMask is true, then we also allow the complement of a valid
/// value, to be used as a mask.
bool IsValueInFlagEnum(const EnumDecl *ED, const llvm::APInt &Val,
bool AllowMask) const;
/// DiagnoseAssignmentEnum - Warn if assignment to enum is a constant
/// integer not in the range of enum values.
void DiagnoseAssignmentEnum(QualType DstType, QualType SrcType,
Expr *SrcExpr);
/// CheckAssignmentConstraints - Perform type checking for assignment,
/// argument passing, variable initialization, and function return values.
/// C99 6.5.16.
AssignConvertType CheckAssignmentConstraints(SourceLocation Loc,
QualType LHSType,
QualType RHSType);
/// Check assignment constraints and prepare for a conversion of the
/// RHS to the LHS type.
AssignConvertType CheckAssignmentConstraints(QualType LHSType,
ExprResult &RHS,
CastKind &Kind);
// CheckSingleAssignmentConstraints - Currently used by
// CheckAssignmentOperands, and ActOnReturnStmt. Prior to type checking,
// this routine performs the default function/array converions.
AssignConvertType CheckSingleAssignmentConstraints(QualType LHSType,
ExprResult &RHS,
bool Diagnose = true,
bool DiagnoseCFAudited = false);
// \brief If the lhs type is a transparent union, check whether we
// can initialize the transparent union with the given expression.
AssignConvertType CheckTransparentUnionArgumentConstraints(QualType ArgType,
ExprResult &RHS);
bool IsStringLiteralToNonConstPointerConversion(Expr *From, QualType ToType);
bool CheckExceptionSpecCompatibility(Expr *From, QualType ToType);
ExprResult PerformImplicitConversion(Expr *From, QualType ToType,
AssignmentAction Action,
bool AllowExplicit = false);
ExprResult PerformImplicitConversion(Expr *From, QualType ToType,
AssignmentAction Action,
bool AllowExplicit,
ImplicitConversionSequence& ICS);
ExprResult PerformImplicitConversion(Expr *From, QualType ToType,
const ImplicitConversionSequence& ICS,
AssignmentAction Action,
CheckedConversionKind CCK
= CCK_ImplicitConversion);
ExprResult PerformImplicitConversion(Expr *From, QualType ToType,
const StandardConversionSequence& SCS,
AssignmentAction Action,
CheckedConversionKind CCK);
/// the following "Check" methods will return a valid/converted QualType
/// or a null QualType (indicating an error diagnostic was issued).
/// type checking binary operators (subroutines of CreateBuiltinBinOp).
QualType InvalidOperands(SourceLocation Loc, ExprResult &LHS,
ExprResult &RHS);
QualType CheckPointerToMemberOperands( // C++ 5.5
ExprResult &LHS, ExprResult &RHS, ExprValueKind &VK,
SourceLocation OpLoc, bool isIndirect);
QualType CheckMultiplyDivideOperands( // C99 6.5.5
ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign,
bool IsDivide);
QualType CheckRemainderOperands( // C99 6.5.5
ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
bool IsCompAssign = false);
QualType CheckAdditionOperands( // C99 6.5.6
ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, unsigned Opc,
QualType* CompLHSTy = nullptr);
QualType CheckSubtractionOperands( // C99 6.5.6
ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
QualType* CompLHSTy = nullptr);
QualType CheckShiftOperands( // C99 6.5.7
ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, unsigned Opc,
bool IsCompAssign = false);
QualType CheckCompareOperands( // C99 6.5.8/9
ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, unsigned OpaqueOpc,
bool isRelational);
QualType CheckBitwiseOperands( // C99 6.5.[10...12]
ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
bool IsCompAssign = false);
QualType CheckLogicalOperands( // C99 6.5.[13,14]
ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, unsigned Opc);
// CheckAssignmentOperands is used for both simple and compound assignment.
// For simple assignment, pass both expressions and a null converted type.
// For compound assignment, pass both expressions and the converted type.
QualType CheckAssignmentOperands( // C99 6.5.16.[1,2]
Expr *LHSExpr, ExprResult &RHS, SourceLocation Loc, QualType CompoundType);
ExprResult checkPseudoObjectIncDec(Scope *S, SourceLocation OpLoc,
UnaryOperatorKind Opcode, Expr *Op);
ExprResult checkPseudoObjectAssignment(Scope *S, SourceLocation OpLoc,
BinaryOperatorKind Opcode,
Expr *LHS, Expr *RHS);
ExprResult checkPseudoObjectRValue(Expr *E);
Expr *recreateSyntacticForm(PseudoObjectExpr *E);
QualType CheckConditionalOperands( // C99 6.5.15
ExprResult &Cond, ExprResult &LHS, ExprResult &RHS,
ExprValueKind &VK, ExprObjectKind &OK, SourceLocation QuestionLoc);
QualType CXXCheckConditionalOperands( // C++ 5.16
ExprResult &cond, ExprResult &lhs, ExprResult &rhs,
ExprValueKind &VK, ExprObjectKind &OK, SourceLocation questionLoc);
QualType FindCompositePointerType(SourceLocation Loc, Expr *&E1, Expr *&E2,
bool *NonStandardCompositeType = nullptr);
QualType FindCompositePointerType(SourceLocation Loc,
ExprResult &E1, ExprResult &E2,
bool *NonStandardCompositeType = nullptr) {
Expr *E1Tmp = E1.get(), *E2Tmp = E2.get();
QualType Composite = FindCompositePointerType(Loc, E1Tmp, E2Tmp,
NonStandardCompositeType);
E1 = E1Tmp;
E2 = E2Tmp;
return Composite;
}
QualType FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS,
SourceLocation QuestionLoc);
bool DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr,
SourceLocation QuestionLoc);
void DiagnoseAlwaysNonNullPointer(Expr *E,
Expr::NullPointerConstantKind NullType,
bool IsEqual, SourceRange Range);
/// type checking for vector binary operators.
QualType CheckVectorOperands(ExprResult &LHS, ExprResult &RHS,
SourceLocation Loc, bool IsCompAssign);
QualType GetSignedVectorType(QualType V);
QualType CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS,
SourceLocation Loc, bool isRelational);
QualType CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS,
SourceLocation Loc);
bool isLaxVectorConversion(QualType srcType, QualType destType);
/// type checking declaration initializers (C99 6.7.8)
bool CheckForConstantInitializer(Expr *e, QualType t);
// type checking C++ declaration initializers (C++ [dcl.init]).
/// ReferenceCompareResult - Expresses the result of comparing two
/// types (cv1 T1 and cv2 T2) to determine their compatibility for the
/// purposes of initialization by reference (C++ [dcl.init.ref]p4).
enum ReferenceCompareResult {
/// Ref_Incompatible - The two types are incompatible, so direct
/// reference binding is not possible.
Ref_Incompatible = 0,
/// Ref_Related - The two types are reference-related, which means
/// that their unqualified forms (T1 and T2) are either the same
/// or T1 is a base class of T2.
Ref_Related,
/// Ref_Compatible_With_Added_Qualification - The two types are
/// reference-compatible with added qualification, meaning that
/// they are reference-compatible and the qualifiers on T1 (cv1)
/// are greater than the qualifiers on T2 (cv2).
Ref_Compatible_With_Added_Qualification,
/// Ref_Compatible - The two types are reference-compatible and
/// have equivalent qualifiers (cv1 == cv2).
Ref_Compatible
};
ReferenceCompareResult CompareReferenceRelationship(SourceLocation Loc,
QualType T1, QualType T2,
bool &DerivedToBase,
bool &ObjCConversion,
bool &ObjCLifetimeConversion);
ExprResult checkUnknownAnyCast(SourceRange TypeRange, QualType CastType,
Expr *CastExpr, CastKind &CastKind,
ExprValueKind &VK, CXXCastPath &Path);
/// \brief Force an expression with unknown-type to an expression of the
/// given type.
ExprResult forceUnknownAnyToType(Expr *E, QualType ToType);
/// \brief Type-check an expression that's being passed to an
/// __unknown_anytype parameter.
ExprResult checkUnknownAnyArg(SourceLocation callLoc,
Expr *result, QualType ¶mType);
// CheckVectorCast - check type constraints for vectors.
// Since vectors are an extension, there are no C standard reference for this.
// We allow casting between vectors and integer datatypes of the same size.
// returns true if the cast is invalid
bool CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty,
CastKind &Kind);
// CheckExtVectorCast - check type constraints for extended vectors.
// Since vectors are an extension, there are no C standard reference for this.
// We allow casting between vectors and integer datatypes of the same size,
// or vectors and the element type of that vector.
// returns the cast expr
ExprResult CheckExtVectorCast(SourceRange R, QualType DestTy, Expr *CastExpr,
CastKind &Kind);
ExprResult BuildCXXFunctionalCastExpr(TypeSourceInfo *TInfo,
SourceLocation LParenLoc,
Expr *CastExpr,
SourceLocation RParenLoc);
enum ARCConversionResult { ACR_okay, ACR_unbridged };
/// \brief Checks for invalid conversions and casts between
/// retainable pointers and other pointer kinds.
ARCConversionResult CheckObjCARCConversion(SourceRange castRange,
QualType castType, Expr *&op,
CheckedConversionKind CCK,
bool DiagnoseCFAudited = false,
BinaryOperatorKind Opc = BO_PtrMemD
);
Expr *stripARCUnbridgedCast(Expr *e);
void diagnoseARCUnbridgedCast(Expr *e);
bool CheckObjCARCUnavailableWeakConversion(QualType castType,
QualType ExprType);
/// checkRetainCycles - Check whether an Objective-C message send
/// might create an obvious retain cycle.
void checkRetainCycles(ObjCMessageExpr *msg);
void checkRetainCycles(Expr *receiver, Expr *argument);
void checkRetainCycles(VarDecl *Var, Expr *Init);
/// checkUnsafeAssigns - Check whether +1 expr is being assigned
/// to weak/__unsafe_unretained type.
bool checkUnsafeAssigns(SourceLocation Loc, QualType LHS, Expr *RHS);
/// checkUnsafeExprAssigns - Check whether +1 expr is being assigned
/// to weak/__unsafe_unretained expression.
void checkUnsafeExprAssigns(SourceLocation Loc, Expr *LHS, Expr *RHS);
/// CheckMessageArgumentTypes - Check types in an Obj-C message send.
/// \param Method - May be null.
/// \param [out] ReturnType - The return type of the send.
/// \return true iff there were any incompatible types.
bool CheckMessageArgumentTypes(QualType ReceiverType,
MultiExprArg Args, Selector Sel,
ArrayRef<SourceLocation> SelectorLocs,
ObjCMethodDecl *Method, bool isClassMessage,
bool isSuperMessage,
SourceLocation lbrac, SourceLocation rbrac,
SourceRange RecRange,
QualType &ReturnType, ExprValueKind &VK);
/// \brief Determine the result of a message send expression based on
/// the type of the receiver, the method expected to receive the message,
/// and the form of the message send.
QualType getMessageSendResultType(QualType ReceiverType,
ObjCMethodDecl *Method,
bool isClassMessage, bool isSuperMessage);
/// \brief If the given expression involves a message send to a method
/// with a related result type, emit a note describing what happened.
void EmitRelatedResultTypeNote(const Expr *E);
/// \brief Given that we had incompatible pointer types in a return
/// statement, check whether we're in a method with a related result
/// type, and if so, emit a note describing what happened.
void EmitRelatedResultTypeNoteForReturn(QualType destType);
/// CheckBooleanCondition - Diagnose problems involving the use of
/// the given expression as a boolean condition (e.g. in an if
/// statement). Also performs the standard function and array
/// decays, possibly changing the input variable.
///
/// \param Loc - A location associated with the condition, e.g. the
/// 'if' keyword.
/// \return true iff there were any errors
ExprResult CheckBooleanCondition(Expr *E, SourceLocation Loc);
ExprResult ActOnBooleanCondition(Scope *S, SourceLocation Loc,
Expr *SubExpr);
/// DiagnoseAssignmentAsCondition - Given that an expression is
/// being used as a boolean condition, warn if it's an assignment.
void DiagnoseAssignmentAsCondition(Expr *E);
/// \brief Redundant parentheses over an equality comparison can indicate
/// that the user intended an assignment used as condition.
void DiagnoseEqualityWithExtraParens(ParenExpr *ParenE);
/// CheckCXXBooleanCondition - Returns true if conversion to bool is invalid.
ExprResult CheckCXXBooleanCondition(Expr *CondExpr);
/// ConvertIntegerToTypeWarnOnOverflow - Convert the specified APInt to have
/// the specified width and sign. If an overflow occurs, detect it and emit
/// the specified diagnostic.
void ConvertIntegerToTypeWarnOnOverflow(llvm::APSInt &OldVal,
unsigned NewWidth, bool NewSign,
SourceLocation Loc, unsigned DiagID);
/// Checks that the Objective-C declaration is declared in the global scope.
/// Emits an error and marks the declaration as invalid if it's not declared
/// in the global scope.
bool CheckObjCDeclScope(Decl *D);
/// \brief Abstract base class used for diagnosing integer constant
/// expression violations.
class VerifyICEDiagnoser {
public:
bool Suppress;
VerifyICEDiagnoser(bool Suppress = false) : Suppress(Suppress) { }
virtual void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) =0;
virtual void diagnoseFold(Sema &S, SourceLocation Loc, SourceRange SR);
virtual ~VerifyICEDiagnoser() { }
};
/// VerifyIntegerConstantExpression - Verifies that an expression is an ICE,
/// and reports the appropriate diagnostics. Returns false on success.
/// Can optionally return the value of the expression.
ExprResult VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result,
VerifyICEDiagnoser &Diagnoser,
bool AllowFold = true);
ExprResult VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result,
unsigned DiagID,
bool AllowFold = true);
ExprResult VerifyIntegerConstantExpression(Expr *E,
llvm::APSInt *Result = nullptr);
/// VerifyBitField - verifies that a bit field expression is an ICE and has
/// the correct width, and that the field type is valid.
/// Returns false on success.
/// Can optionally return whether the bit-field is of width 0
ExprResult VerifyBitField(SourceLocation FieldLoc, IdentifierInfo *FieldName,
QualType FieldTy, bool IsMsStruct,
Expr *BitWidth, bool *ZeroWidth = nullptr);
enum CUDAFunctionTarget {
CFT_Device,
CFT_Global,
CFT_Host,
CFT_HostDevice,
CFT_InvalidTarget
};
CUDAFunctionTarget IdentifyCUDATarget(const FunctionDecl *D);
bool CheckCUDATarget(const FunctionDecl *Caller, const FunctionDecl *Callee);
/// Given a implicit special member, infer its CUDA target from the
/// calls it needs to make to underlying base/field special members.
/// \param ClassDecl the class for which the member is being created.
/// \param CSM the kind of special member.
/// \param MemberDecl the special member itself.
/// \param ConstRHS true if this is a copy operation with a const object on
/// its RHS.
/// \param Diagnose true if this call should emit diagnostics.
/// \return true if there was an error inferring.
/// The result of this call is implicit CUDA target attribute(s) attached to
/// the member declaration.
bool inferCUDATargetForImplicitSpecialMember(CXXRecordDecl *ClassDecl,
CXXSpecialMember CSM,
CXXMethodDecl *MemberDecl,
bool ConstRHS,
bool Diagnose);
/// \name Code completion
//@{
/// \brief Describes the context in which code completion occurs.
enum ParserCompletionContext {
/// \brief Code completion occurs at top-level or namespace context.
PCC_Namespace,
/// \brief Code completion occurs within a class, struct, or union.
PCC_Class,
/// \brief Code completion occurs within an Objective-C interface, protocol,
/// or category.
PCC_ObjCInterface,
/// \brief Code completion occurs within an Objective-C implementation or
/// category implementation
PCC_ObjCImplementation,
/// \brief Code completion occurs within the list of instance variables
/// in an Objective-C interface, protocol, category, or implementation.
PCC_ObjCInstanceVariableList,
/// \brief Code completion occurs following one or more template
/// headers.
PCC_Template,
/// \brief Code completion occurs following one or more template
/// headers within a class.
PCC_MemberTemplate,
/// \brief Code completion occurs within an expression.
PCC_Expression,
/// \brief Code completion occurs within a statement, which may
/// also be an expression or a declaration.
PCC_Statement,
/// \brief Code completion occurs at the beginning of the
/// initialization statement (or expression) in a for loop.
PCC_ForInit,
/// \brief Code completion occurs within the condition of an if,
/// while, switch, or for statement.
PCC_Condition,
/// \brief Code completion occurs within the body of a function on a
/// recovery path, where we do not have a specific handle on our position
/// in the grammar.
PCC_RecoveryInFunction,
/// \brief Code completion occurs where only a type is permitted.
PCC_Type,
/// \brief Code completion occurs in a parenthesized expression, which
/// might also be a type cast.
PCC_ParenthesizedExpression,
/// \brief Code completion occurs within a sequence of declaration
/// specifiers within a function, method, or block.
PCC_LocalDeclarationSpecifiers
};
void CodeCompleteModuleImport(SourceLocation ImportLoc, ModuleIdPath Path);
void CodeCompleteOrdinaryName(Scope *S,
ParserCompletionContext CompletionContext);
void CodeCompleteDeclSpec(Scope *S, DeclSpec &DS,
bool AllowNonIdentifiers,
bool AllowNestedNameSpecifiers);
struct CodeCompleteExpressionData;
void CodeCompleteExpression(Scope *S,
const CodeCompleteExpressionData &Data);
void CodeCompleteMemberReferenceExpr(Scope *S, Expr *Base,
SourceLocation OpLoc,
bool IsArrow);
void CodeCompletePostfixExpression(Scope *S, ExprResult LHS);
void CodeCompleteTag(Scope *S, unsigned TagSpec);
void CodeCompleteTypeQualifiers(DeclSpec &DS);
void CodeCompleteCase(Scope *S);
void CodeCompleteCall(Scope *S, Expr *Fn, ArrayRef<Expr *> Args);
void CodeCompleteConstructor(Scope *S, QualType Type, SourceLocation Loc,
ArrayRef<Expr *> Args);
void CodeCompleteInitializer(Scope *S, Decl *D);
void CodeCompleteReturn(Scope *S);
void CodeCompleteAfterIf(Scope *S);
void CodeCompleteAssignmentRHS(Scope *S, Expr *LHS);
void CodeCompleteQualifiedId(Scope *S, CXXScopeSpec &SS,
bool EnteringContext);
void CodeCompleteUsing(Scope *S);
void CodeCompleteUsingDirective(Scope *S);
void CodeCompleteNamespaceDecl(Scope *S);
void CodeCompleteNamespaceAliasDecl(Scope *S);
void CodeCompleteOperatorName(Scope *S);
void CodeCompleteConstructorInitializer(
Decl *Constructor,
ArrayRef<CXXCtorInitializer *> Initializers);
void CodeCompleteLambdaIntroducer(Scope *S, LambdaIntroducer &Intro,
bool AfterAmpersand);
void CodeCompleteObjCAtDirective(Scope *S);
void CodeCompleteObjCAtVisibility(Scope *S);
void CodeCompleteObjCAtStatement(Scope *S);
void CodeCompleteObjCAtExpression(Scope *S);
void CodeCompleteObjCPropertyFlags(Scope *S, ObjCDeclSpec &ODS);
void CodeCompleteObjCPropertyGetter(Scope *S);
void CodeCompleteObjCPropertySetter(Scope *S);
void CodeCompleteObjCPassingType(Scope *S, ObjCDeclSpec &DS,
bool IsParameter);
void CodeCompleteObjCMessageReceiver(Scope *S);
void CodeCompleteObjCSuperMessage(Scope *S, SourceLocation SuperLoc,
ArrayRef<IdentifierInfo *> SelIdents,
bool AtArgumentExpression);
void CodeCompleteObjCClassMessage(Scope *S, ParsedType Receiver,
ArrayRef<IdentifierInfo *> SelIdents,
bool AtArgumentExpression,
bool IsSuper = false);
void CodeCompleteObjCInstanceMessage(Scope *S, Expr *Receiver,
ArrayRef<IdentifierInfo *> SelIdents,
bool AtArgumentExpression,
ObjCInterfaceDecl *Super = nullptr);
void CodeCompleteObjCForCollection(Scope *S,
DeclGroupPtrTy IterationVar);
void CodeCompleteObjCSelector(Scope *S,
ArrayRef<IdentifierInfo *> SelIdents);
void CodeCompleteObjCProtocolReferences(IdentifierLocPair *Protocols,
unsigned NumProtocols);
void CodeCompleteObjCProtocolDecl(Scope *S);
void CodeCompleteObjCInterfaceDecl(Scope *S);
void CodeCompleteObjCSuperclass(Scope *S,
IdentifierInfo *ClassName,
SourceLocation ClassNameLoc);
void CodeCompleteObjCImplementationDecl(Scope *S);
void CodeCompleteObjCInterfaceCategory(Scope *S,
IdentifierInfo *ClassName,
SourceLocation ClassNameLoc);
void CodeCompleteObjCImplementationCategory(Scope *S,
IdentifierInfo *ClassName,
SourceLocation ClassNameLoc);
void CodeCompleteObjCPropertyDefinition(Scope *S);
void CodeCompleteObjCPropertySynthesizeIvar(Scope *S,
IdentifierInfo *PropertyName);
void CodeCompleteObjCMethodDecl(Scope *S,
bool IsInstanceMethod,
ParsedType ReturnType);
void CodeCompleteObjCMethodDeclSelector(Scope *S,
bool IsInstanceMethod,
bool AtParameterName,
ParsedType ReturnType,
ArrayRef<IdentifierInfo *> SelIdents);
void CodeCompletePreprocessorDirective(bool InConditional);
void CodeCompleteInPreprocessorConditionalExclusion(Scope *S);
void CodeCompletePreprocessorMacroName(bool IsDefinition);
void CodeCompletePreprocessorExpression();
void CodeCompletePreprocessorMacroArgument(Scope *S,
IdentifierInfo *Macro,
MacroInfo *MacroInfo,
unsigned Argument);
void CodeCompleteNaturalLanguage();
void GatherGlobalCodeCompletions(CodeCompletionAllocator &Allocator,
CodeCompletionTUInfo &CCTUInfo,
SmallVectorImpl<CodeCompletionResult> &Results);
//@}
//===--------------------------------------------------------------------===//
// Extra semantic analysis beyond the C type system
public:
SourceLocation getLocationOfStringLiteralByte(const StringLiteral *SL,
unsigned ByteNo) const;
private:
void CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
const ArraySubscriptExpr *ASE=nullptr,
bool AllowOnePastEnd=true, bool IndexNegated=false);
void CheckArrayAccess(const Expr *E);
// Used to grab the relevant information from a FormatAttr and a
// FunctionDeclaration.
struct FormatStringInfo {
unsigned FormatIdx;
unsigned FirstDataArg;
bool HasVAListArg;
};
bool getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember,
FormatStringInfo *FSI);
bool CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall,
const FunctionProtoType *Proto);
bool CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation loc,
ArrayRef<const Expr *> Args);
bool CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall,
const FunctionProtoType *Proto);
bool CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto);
void CheckConstructorCall(FunctionDecl *FDecl,
ArrayRef<const Expr *> Args,
const FunctionProtoType *Proto,
SourceLocation Loc);
void checkCall(NamedDecl *FDecl, const FunctionProtoType *Proto,
ArrayRef<const Expr *> Args, bool IsMemberFunction,
SourceLocation Loc, SourceRange Range,
VariadicCallType CallType);
bool CheckObjCString(Expr *Arg);
ExprResult CheckBuiltinFunctionCall(FunctionDecl *FDecl,
unsigned BuiltinID, CallExpr *TheCall);
bool CheckARMBuiltinExclusiveCall(unsigned BuiltinID, CallExpr *TheCall,
unsigned MaxWidth);
bool CheckNeonBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
bool CheckARMBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
bool CheckAArch64BuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
bool CheckMipsBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
bool CheckSystemZBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
bool CheckX86BuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
bool CheckPPCBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
bool SemaBuiltinVAStart(CallExpr *TheCall);
bool SemaBuiltinVAStartARM(CallExpr *Call);
bool SemaBuiltinUnorderedCompare(CallExpr *TheCall);
bool SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs);
public:
// Used by C++ template instantiation.
ExprResult SemaBuiltinShuffleVector(CallExpr *TheCall);
ExprResult SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo,
SourceLocation BuiltinLoc,
SourceLocation RParenLoc);
private:
bool SemaBuiltinPrefetch(CallExpr *TheCall);
bool SemaBuiltinAssume(CallExpr *TheCall);
bool SemaBuiltinAssumeAligned(CallExpr *TheCall);
bool SemaBuiltinLongjmp(CallExpr *TheCall);
bool SemaBuiltinSetjmp(CallExpr *TheCall);
ExprResult SemaBuiltinAtomicOverloaded(ExprResult TheCallResult);
ExprResult SemaAtomicOpsOverloaded(ExprResult TheCallResult,
AtomicExpr::AtomicOp Op);
bool SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum,
llvm::APSInt &Result);
bool SemaBuiltinConstantArgRange(CallExpr *TheCall, int ArgNum,
int Low, int High);
bool SemaBuiltinARMSpecialReg(unsigned BuiltinID, CallExpr *TheCall,
int ArgNum, unsigned ExpectedFieldNum,
bool AllowName);
bool SemaBuiltinCpuSupports(CallExpr *TheCall);
public:
enum FormatStringType {
FST_Scanf,
FST_Printf,
FST_NSString,
FST_Strftime,
FST_Strfmon,
FST_Kprintf,
FST_FreeBSDKPrintf,
FST_OSTrace,
FST_Unknown
};
static FormatStringType GetFormatStringType(const FormatAttr *Format);
void CheckFormatString(const StringLiteral *FExpr, const Expr *OrigFormatExpr,
ArrayRef<const Expr *> Args, bool HasVAListArg,
unsigned format_idx, unsigned firstDataArg,
FormatStringType Type, bool inFunctionCall,
VariadicCallType CallType,
llvm::SmallBitVector &CheckedVarArgs);
bool FormatStringHasSArg(const StringLiteral *FExpr);
bool GetFormatNSStringIdx(const FormatAttr *Format, unsigned &Idx);
private:
bool CheckFormatArguments(const FormatAttr *Format,
ArrayRef<const Expr *> Args,
bool IsCXXMember,
VariadicCallType CallType,
SourceLocation Loc, SourceRange Range,
llvm::SmallBitVector &CheckedVarArgs);
bool CheckFormatArguments(ArrayRef<const Expr *> Args,
bool HasVAListArg, unsigned format_idx,
unsigned firstDataArg, FormatStringType Type,
VariadicCallType CallType,
SourceLocation Loc, SourceRange range,
llvm::SmallBitVector &CheckedVarArgs);
void CheckAbsoluteValueFunction(const CallExpr *Call,
const FunctionDecl *FDecl,
IdentifierInfo *FnInfo);
void CheckMemaccessArguments(const CallExpr *Call,
unsigned BId,
IdentifierInfo *FnName);
void CheckStrlcpycatArguments(const CallExpr *Call,
IdentifierInfo *FnName);
void CheckStrncatArguments(const CallExpr *Call,
IdentifierInfo *FnName);
void CheckReturnValExpr(Expr *RetValExp, QualType lhsType,
SourceLocation ReturnLoc,
bool isObjCMethod = false,
const AttrVec *Attrs = nullptr,
const FunctionDecl *FD = nullptr);
void CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr* RHS);
void CheckImplicitConversions(Expr *E, SourceLocation CC = SourceLocation());
void CheckBoolLikeConversion(Expr *E, SourceLocation CC);
void CheckForIntOverflow(Expr *E);
void CheckUnsequencedOperations(Expr *E);
/// \brief Perform semantic checks on a completed expression. This will either
/// be a full-expression or a default argument expression.
void CheckCompletedExpr(Expr *E, SourceLocation CheckLoc = SourceLocation(),
bool IsConstexpr = false);
void CheckBitFieldInitialization(SourceLocation InitLoc, FieldDecl *Field,
Expr *Init);
/// \brief Check if the given expression contains 'break' or 'continue'
/// statement that produces control flow different from GCC.
void CheckBreakContinueBinding(Expr *E);
/// \brief Check whether receiver is mutable ObjC container which
/// attempts to add itself into the container
void CheckObjCCircularContainer(ObjCMessageExpr *Message);
void AnalyzeDeleteExprMismatch(const CXXDeleteExpr *DE);
void AnalyzeDeleteExprMismatch(FieldDecl *Field, SourceLocation DeleteLoc,
bool DeleteWasArrayForm);
public:
/// \brief Register a magic integral constant to be used as a type tag.
void RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind,
uint64_t MagicValue, QualType Type,
bool LayoutCompatible, bool MustBeNull);
struct TypeTagData {
TypeTagData() {}
TypeTagData(QualType Type, bool LayoutCompatible, bool MustBeNull) :
Type(Type), LayoutCompatible(LayoutCompatible),
MustBeNull(MustBeNull)
{}
QualType Type;
/// If true, \c Type should be compared with other expression's types for
/// layout-compatibility.
unsigned LayoutCompatible : 1;
unsigned MustBeNull : 1;
};
/// A pair of ArgumentKind identifier and magic value. This uniquely
/// identifies the magic value.
typedef std::pair<const IdentifierInfo *, uint64_t> TypeTagMagicValue;
private:
/// \brief A map from magic value to type information.
std::unique_ptr<llvm::DenseMap<TypeTagMagicValue, TypeTagData>>
TypeTagForDatatypeMagicValues;
/// \brief Peform checks on a call of a function with argument_with_type_tag
/// or pointer_with_type_tag attributes.
void CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr,
const Expr * const *ExprArgs);
/// \brief The parser's current scope.
///
/// The parser maintains this state here.
Scope *CurScope;
mutable IdentifierInfo *Ident_super;
mutable IdentifierInfo *Ident___float128;
/// Nullability type specifiers.
IdentifierInfo *Ident__Nonnull = nullptr;
IdentifierInfo *Ident__Nullable = nullptr;
IdentifierInfo *Ident__Null_unspecified = nullptr;
IdentifierInfo *Ident_NSError = nullptr;
protected:
friend class Parser;
friend class InitializationSequence;
friend class ASTReader;
friend class ASTDeclReader;
friend class ASTWriter;
public:
/// Retrieve the keyword associated
IdentifierInfo *getNullabilityKeyword(NullabilityKind nullability);
/// The struct behind the CFErrorRef pointer.
RecordDecl *CFError = nullptr;
/// Retrieve the identifier "NSError".
IdentifierInfo *getNSErrorIdent();
/// \brief Retrieve the parser's current scope.
///
/// This routine must only be used when it is certain that semantic analysis
/// and the parser are in precisely the same context, which is not the case
/// when, e.g., we are performing any kind of template instantiation.
/// Therefore, the only safe places to use this scope are in the parser
/// itself and in routines directly invoked from the parser and *never* from
/// template substitution or instantiation.
Scope *getCurScope() const { return CurScope; }
void incrementMSManglingNumber() const {
return CurScope->incrementMSManglingNumber();
}
IdentifierInfo *getSuperIdentifier() const;
IdentifierInfo *getFloat128Identifier() const;
Decl *getObjCDeclContext() const;
DeclContext *getCurLexicalContext() const {
return OriginalLexicalContext ? OriginalLexicalContext : CurContext;
}
AvailabilityResult getCurContextAvailability() const;
const DeclContext *getCurObjCLexicalContext() const {
const DeclContext *DC = getCurLexicalContext();
// A category implicitly has the attribute of the interface.
if (const ObjCCategoryDecl *CatD = dyn_cast<ObjCCategoryDecl>(DC))
DC = CatD->getClassInterface();
return DC;
}
/// \brief To be used for checking whether the arguments being passed to
/// function exceeds the number of parameters expected for it.
static bool TooManyArguments(size_t NumParams, size_t NumArgs,
bool PartialOverloading = false) {
// We check whether we're just after a comma in code-completion.
if (NumArgs > 0 && PartialOverloading)
return NumArgs + 1 > NumParams; // If so, we view as an extra argument.
return NumArgs > NumParams;
}
};
/// \brief RAII object that enters a new expression evaluation context.
class EnterExpressionEvaluationContext {
Sema &Actions;
public:
EnterExpressionEvaluationContext(Sema &Actions,
Sema::ExpressionEvaluationContext NewContext,
Decl *LambdaContextDecl = nullptr,
bool IsDecltype = false)
: Actions(Actions) {
Actions.PushExpressionEvaluationContext(NewContext, LambdaContextDecl,
IsDecltype);
}
EnterExpressionEvaluationContext(Sema &Actions,
Sema::ExpressionEvaluationContext NewContext,
Sema::ReuseLambdaContextDecl_t,
bool IsDecltype = false)
: Actions(Actions) {
Actions.PushExpressionEvaluationContext(NewContext,
Sema::ReuseLambdaContextDecl,
IsDecltype);
}
~EnterExpressionEvaluationContext() {
Actions.PopExpressionEvaluationContext();
}
};
DeductionFailureInfo
MakeDeductionFailureInfo(ASTContext &Context, Sema::TemplateDeductionResult TDK,
sema::TemplateDeductionInfo &Info);
/// \brief Contains a late templated function.
/// Will be parsed at the end of the translation unit, used by Sema & Parser.
struct LateParsedTemplate {
CachedTokens Toks;
/// \brief The template function declaration to be late parsed.
Decl *D;
};
} // end namespace clang
#endif
|
pr68640.c | /* { dg-do compile } */
/* { dg-options "-O2 -fopenmp -fdump-tree-ealias-all" } */
#define N 1024
int
foo (int *__restrict__ ap)
{
int *bp = ap;
#pragma omp parallel for
for (unsigned int idx = 0; idx < N; idx++)
ap[idx] = bp[idx];
}
/* { dg-final { scan-tree-dump-times "clique 1 base 1" 2 "ealias" } } */
/* { dg-final { scan-tree-dump-times "(?n)clique 1 base 0" 2 "ealias" } } */
|
single3.c | /*
*/
#include <stdio.h>
#include <omp.h>
#include<assert.h>
int a;
int b;
int main(void)
{
#pragma omp parallel
{
#pragma omp single
{
int num_threads = 2;
}
#pragma omp single nowait copyprivate(a,b)
{
int num_threads = 3;
}
}
return 0;
}
|
trilinos_residual_criteria.h | // KRATOS _____ _ _ _
// |_ _| __(_) (_)_ __ ___ ___
// | || '__| | | | '_ \ / _ \/ __|
// | || | | | | | | | | (_) \__
// |_||_| |_|_|_|_| |_|\___/|___/ APPLICATION
//
// License: BSD License
// Kratos default license: kratos/license.txt
//
// Main authors: Jordi Cotela
//
#if !defined(KRATOS_TRILINOS_RESIDUAL_CRITERIA_H_INCLUDED)
#define KRATOS_TRILINOS_RESIDUAL_CRITERIA_H_INCLUDED
// System includes
// External includes
// Project includes
#include "includes/define.h"
#include "solving_strategies/convergencecriterias/residual_criteria.h"
namespace Kratos
{
///@addtogroup TrilinosApplication
///@{
///@name Kratos Classes
///@{
/// MPI version of the ResidualCriteria.
/** Implements a convergence criteria based on the norm of the (free rows of) the RHS vector.
* @see ResidualCriteria
*/
template< class TSparseSpace, class TDenseSpace >
class TrilinosResidualCriteria : public ResidualCriteria< TSparseSpace, TDenseSpace >
{
public:
///@name Type Definitions
///@{
/// Pointer definition of TrilinosResidualCriteria
KRATOS_CLASS_POINTER_DEFINITION(TrilinosResidualCriteria);
typedef ResidualCriteria< TSparseSpace, TDenseSpace > BaseType;
typedef typename BaseType::TDataType TDataType;
///@}
///@name Life Cycle
///@{
/// Constructor
explicit TrilinosResidualCriteria(TDataType NewRatioTolerance,TDataType AlwaysConvergedNorm):
ResidualCriteria<TSparseSpace,TDenseSpace>(NewRatioTolerance, AlwaysConvergedNorm)
{}
/// Copy constructor
explicit TrilinosResidualCriteria(const TrilinosResidualCriteria& rOther):
ResidualCriteria<TSparseSpace,TDenseSpace>(rOther)
{}
/// Destructor.
~TrilinosResidualCriteria() override {}
///@}
///@name Operators
///@{
/// Deleted assignment operator.
TrilinosResidualCriteria& operator=(TrilinosResidualCriteria const& rOther) = delete;
///@}
protected:
///@name Protected Operations
///@{
/**
* @brief This method computes the norm of the residual
* @details It checks if the dof is fixed
* @param rModelPart Reference to the ModelPart containing the problem.
* @param rResidualSolutionNorm The norm of the residual
* @param rDofNum The number of DoFs
* @param rDofSet Reference to the container of the problem's degrees of freedom (stored by the BuilderAndSolver)
* @param b RHS vector (residual + reactions)
*/
void CalculateResidualNorm(
ModelPart& rModelPart,
TDataType& rResidualSolutionNorm,
typename BaseType::SizeType& rDofNum,
typename BaseType::DofsArrayType& rDofSet,
const typename BaseType::TSystemVectorType& rB) override
{
// Initialize
TDataType residual_solution_norm = TDataType();
long int local_dof_num = 0;
const int rank = rB.Comm().MyPID();
// Loop over Dofs
#pragma omp parallel for reduction(+:residual_solution_norm,local_dof_num)
for (int i = 0; i < static_cast<int>(rDofSet.size()); i++) {
auto it_dof = rDofSet.begin() + i;
typename BaseType::IndexType dof_id;
TDataType residual_dof_value;
if (it_dof->IsFree() && (it_dof->GetSolutionStepValue(PARTITION_INDEX) == rank)) {
dof_id = it_dof->EquationId();
residual_dof_value = TSparseSpace::GetValue(rB,dof_id);
residual_solution_norm += residual_dof_value * residual_dof_value;
local_dof_num++;
}
}
// Combine local contributions
// Note that I'm not merging the two calls because one adds doubles and the other ints (JC)
rB.Comm().SumAll(&residual_solution_norm,&rResidualSolutionNorm,1);
// SizeType is long unsigned int in linux, but EpetraComm does not support unsigned types
long int global_dof_num = 0;
rB.Comm().SumAll(&local_dof_num,&global_dof_num,1);
rDofNum = static_cast<typename BaseType::SizeType>(global_dof_num);
rResidualSolutionNorm = std::sqrt(rResidualSolutionNorm);
}
///@}
private:
///@name Member Variables
///@{
///@}
///@name Private Operations
///@{
///@}
}; // Class TrilinosResidualCriteria
///@}
///@} addtogroup block
} // namespace Kratos.
#endif // KRATOS_TRILINOS_RESIDUAL_CRITERIA_H_INCLUDED defined
|
cg.c | #include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include "globals.h"
#include "randdp.h"
#include "timers.h"
//---------------------------------------------------------------------
/* common / main_int_mem / */
static int colidx[NZ];
static int rowstr[NA+1];
static int iv[NA];
static int arow[NA];
static int acol[NAZ];
/* common / main_flt_mem / */
static double aelt[NAZ];
static double a[NZ];
static double x[NA+2];
static double z[NA+2];
static double p[NA+2];
static double q[NA+2];
static double r[NA+2];
/* common / partit_size / */
static int naa;
static int nzz;
static int firstrow;
static int lastrow;
static int firstcol;
static int lastcol;
/* common /urando/ */
static double amult;
static double tran;
/* common /timers/ */
static logical timeron;
//---------------------------------------------------------------------
//---------------------------------------------------------------------
static void conj_grad(int colidx[],
int rowstr[],
double x[],
double z[],
double a[],
double p[],
double q[],
double r[],
double *rnorm);
static void makea(int n,
int nz,
double a[],
int colidx[],
int rowstr[],
int firstrow,
int lastrow,
int firstcol,
int lastcol,
int arow[],
int acol[][NONZER+1],
double aelt[][NONZER+1],
int iv[]);
static void sparse(double a[],
int colidx[],
int rowstr[],
int n,
int nz,
int nozer,
int arow[],
int acol[][NONZER+1],
double aelt[][NONZER+1],
int firstrow,
int lastrow,
int nzloc[],
double rcond,
double shift);
static void sprnvc(int n, int nz, int nn1, double v[], int iv[]);
static int icnvrt(double x, int ipwr2);
static void vecset(int n, double v[], int iv[], int *nzv, int i, double val);
//---------------------------------------------------------------------
int main(int argc, char *argv[])
{
int i, j, k, it;
double zeta;
double rnorm;
double norm_temp1, norm_temp2;
double t, mflops, tmax;
//char Class;
logical verified;
double zeta_verify_value, epsilon, err;
char *t_names[T_last];
for (i = 0; i < T_last; i++) {
timer_clear(i);
}
timer_start(T_init);
firstrow = 0;
lastrow = NA-1;
firstcol = 0;
lastcol = NA-1;
zeta_verify_value = VALID_RESULT;
printf("\nCG start...\n\n");
printf(" Size: %11d\n", NA);
printf(" Iterations: %5d\n", NITER);
printf("\n");
naa = NA;
nzz = NZ;
//---------------------------------------------------------------------
// Inialize random number generator
//---------------------------------------------------------------------
tran = 314159265.0;
amult = 1220703125.0;
zeta = randlc(&tran, amult);
//---------------------------------------------------------------------
//
//---------------------------------------------------------------------
makea(naa, nzz, a, colidx, rowstr,
firstrow, lastrow, firstcol, lastcol,
arow,
(int (*)[NONZER+1])(void*)acol,
(double (*)[NONZER+1])(void*)aelt,
iv);
//---------------------------------------------------------------------
// Note: as a result of the above call to makea:
// values of j used in indexing rowstr go from 0 --> lastrow-firstrow
// values of colidx which are col indexes go from firstcol --> lastcol
// So:
// Shift the col index vals from actual (firstcol --> lastcol )
// to local, i.e., (0 --> lastcol-firstcol)
//---------------------------------------------------------------------
for (j = 0; j < lastrow - firstrow + 1; j++) {
for (k = rowstr[j]; k < rowstr[j+1]; k++) {
colidx[k] = colidx[k] - firstcol;
}
}
//---------------------------------------------------------------------
// set starting vector to (1, 1, .... 1)
//---------------------------------------------------------------------
for (i = 0; i < NA+1; i++) {
x[i] = 1.0;
}
for (j = 0; j < lastcol - firstcol + 1; j++) {
q[j] = 0.0;
z[j] = 0.0;
r[j] = 0.0;
p[j] = 0.0;
}
zeta = 0.0;
//---------------------------------------------------------------------
//---->
// Do one iteration untimed to init all code and data page tables
//----> (then reinit, start timing, to niter its)
//---------------------------------------------------------------------
for (it = 1; it <= 1; it++) {
//---------------------------------------------------------------------
// The call to the conjugate gradient routine:
//---------------------------------------------------------------------
conj_grad(colidx, rowstr, x, z, a, p, q, r, &rnorm);
//---------------------------------------------------------------------
// zeta = shift + 1/(x.z)
// So, first: (x.z)
// Also, find norm of z
// So, first: (z.z)
//---------------------------------------------------------------------
norm_temp1 = 0.0;
norm_temp2 = 0.0;
#pragma omp parallel for schedule(auto) private(j) reduction(+:norm_temp1,norm_temp2)
for (j = 0; j < lastcol - firstcol + 1; j++) {
norm_temp1 = norm_temp1 + x[j] * z[j];
norm_temp2 = norm_temp2 + z[j] * z[j];
}
norm_temp2 = 1.0 / sqrt(norm_temp2);
//---------------------------------------------------------------------
// Normalize z to obtain x
//---------------------------------------------------------------------
#pragma omp parallel for schedule(auto) private(j)
for (j = 0; j < lastcol - firstcol + 1; j++) {
x[j] = norm_temp2 * z[j];
}
} // end of do one iteration untimed
//---------------------------------------------------------------------
// set starting vector to (1, 1, .... 1)
//---------------------------------------------------------------------
//#pragma omp parallel for schedule(auto) private(i)
for (i = 0; i < NA+1; i++) {
x[i] = 1.0;
}
zeta = 0.0;
timer_stop(T_init);
printf(" Initialization time = %15.3f seconds\n", timer_read(T_init));
timer_start(T_bench);
//---------------------------------------------------------------------
//---->
// Main Iteration for inverse power method
//---->
//---------------------------------------------------------------------
for (it = 1; it <= NITER; it++) {
//---------------------------------------------------------------------
// The call to the conjugate gradient routine:
//---------------------------------------------------------------------
if (timeron) timer_start(T_conj_grad);
conj_grad(colidx, rowstr, x, z, a, p, q, r, &rnorm);
if (timeron) timer_stop(T_conj_grad);
//---------------------------------------------------------------------
// zeta = shift + 1/(x.z)
// So, first: (x.z)
// Also, find norm of z
// So, first: (z.z)
//---------------------------------------------------------------------
norm_temp1 = 0.0;
norm_temp2 = 0.0;
// know no why can't parallel
//#pragma omp parallel for schedule(auto) private(j) reduction(+:norm_temp1,norm_temp2)
for (j = 0; j < lastcol - firstcol + 1; j++) {
norm_temp1 += x[j]*z[j];
norm_temp2 += z[j]*z[j];
}
norm_temp2 = 1.0 / sqrt(norm_temp2);
zeta = SHIFT + 1.0 / norm_temp1;
if (it == 1)
printf("\n iteration ||r|| zeta\n");
printf(" %5d %20.14E%20.13f\n", it, rnorm, zeta);
//---------------------------------------------------------------------
// Normalize z to obtain x
//---------------------------------------------------------------------
#pragma omp parallel for schedule(auto) private(j)
for (j = 0; j < lastcol - firstcol + 1; j++) {
x[j] = norm_temp2 * z[j];
}
} // end of main iter inv pow meth
timer_stop(T_bench);
//---------------------------------------------------------------------
// End of timed section
//---------------------------------------------------------------------
t = timer_read(T_bench);
printf("\nComplete...\n");
epsilon = 1.0e-10;
err = fabs(zeta - zeta_verify_value) / zeta_verify_value;
if (err <= epsilon) {
verified = true;
printf(" VERIFICATION SUCCESSFUL\n");
printf(" Zeta is %20.13E\n", zeta);
printf(" Error is %20.13E\n", err);
} else {
verified = false;
printf(" VERIFICATION FAILED\n");
printf(" Zeta %20.13E\n", zeta);
printf(" The correct zeta is %20.13E\n", zeta_verify_value);
}
printf("\n\nExecution time : %lf seconds\n\n", t);
return 0;
}
//---------------------------------------------------------------------
// Floaging point arrays here are named as in spec discussion of
// CG algorithm
//---------------------------------------------------------------------
static void conj_grad(int colidx[],
int rowstr[],
double x[],
double z[],
double a[],
double p[],
double q[],
double r[],
double *rnorm)
{
int j, k;
int cgit, cgitmax = 25;
double d, sum, rho, rho0, alpha, beta;
rho = 0.0;
//---------------------------------------------------------------------
// Initialize the CG algorithm:
//---------------------------------------------------------------------
#pragma omp parallel for schedule(auto) private(j)
for (j = 0; j < naa+1; j++) {
q[j] = 0.0;
z[j] = 0.0;
r[j] = x[j];
p[j] = r[j];
}
//---------------------------------------------------------------------
// rho = r.r
// Now, obtain the norm of r: First, sum squares of r elements locally...
//---------------------------------------------------------------------
#pragma omp parallel for schedule(auto) reduction(+:rho)
for (j = 0; j < lastcol - firstcol + 1; j++) {
rho = rho + r[j]*r[j];
}
//---------------------------------------------------------------------
//---->
// The conj grad iteration loop
//---->
//---------------------------------------------------------------------
for (cgit = 1; cgit <= cgitmax; cgit++) {
//---------------------------------------------------------------------
// q = A.p
// The partition submatrix-vector multiply: use workspace w
//---------------------------------------------------------------------
//
// NOTE: this version of the multiply is actually (slightly: maybe %5)
// faster on the sp2 on 16 nodes than is the unrolled-by-2 version
// below. On the Cray t3d, the reverse is true, i.e., the
// unrolled-by-two version is some 10% faster.
// The unrolled-by-8 version below is significantly faster
// on the Cray t3d - overall speed of code is 1.5 times faster.
#pragma omp parallel for private(j,k,sum)
for (j = 0; j < lastrow - firstrow + 1; j++) {
sum = 0.0;
for (k = rowstr[j]; k < rowstr[j+1]; k++) {
sum = sum + a[k]*p[colidx[k]];
}
q[j] = sum;
}
//---------------------------------------------------------------------
// Obtain p.q
//---------------------------------------------------------------------
d = 0.0;
#pragma omp parallel for reduction(+:d) private(j)
for (j = 0; j < lastcol - firstcol + 1; j++) {
d += p[j]*q[j];
}
//---------------------------------------------------------------------
// Obtain alpha = rho / (p.q)
//---------------------------------------------------------------------
alpha = rho / d;
//---------------------------------------------------------------------
// Save a temporary of rho
//---------------------------------------------------------------------
rho0 = rho;
//---------------------------------------------------------------------
// Obtain z = z + alpha*p
// and r = r - alpha*q
//---------------------------------------------------------------------
rho = 0.0;
#pragma omp parallel for schedule(auto)
for (j = 0; j < lastcol - firstcol + 1; j++) {
z[j] += alpha*p[j];
r[j] -= alpha*q[j];
}
//---------------------------------------------------------------------
// rho = r.r
// Now, obtain the norm of r: First, sum squares of r elements locally...
//---------------------------------------------------------------------
#pragma omp parallel for schedule(auto) reduction(+:rho)
for (j = 0; j < lastcol - firstcol + 1; j++) {
rho += r[j]*r[j];
}
//---------------------------------------------------------------------
// Obtain beta:
//---------------------------------------------------------------------
beta = rho / rho0;
//---------------------------------------------------------------------
// p = r + beta*p
//---------------------------------------------------------------------
#pragma omp parallel for schedule(auto)
for (j = 0; j < lastcol - firstcol + 1; j++) {
p[j] = r[j] + beta*p[j];
}
} // end of do cgit=1,cgitmax
//---------------------------------------------------------------------
// Compute residual norm explicitly: ||r|| = ||x - A.z||
// First, form A.z
// The partition submatrix-vector multiply
//---------------------------------------------------------------------
sum = 0.0;
#pragma omp parallel for schedule(auto) private(d,j,k)
for (j = 0; j < lastrow - firstrow + 1; j++) {
d = 0.0;
for (k = rowstr[j]; k < rowstr[j+1]; k++) {
d = d + a[k]*z[colidx[k]];
}
r[j] = d;
}
//---------------------------------------------------------------------
// At this point, r contains A.z
//---------------------------------------------------------------------
#pragma omp parallel for schedule(auto) reduction(+:sum)
for (j = 0; j < lastcol-firstcol+1; j++) {
d = x[j] - r[j];
sum += d*d;
}
*rnorm = sqrt(sum);
}
//---------------------------------------------------------------------
// generate the test problem for benchmark 6
// makea generates a sparse matrix with a
// prescribed sparsity distribution
//
// parameter type usage
//
// input
//
// n i number of cols/rows of matrix
// nz i nonzeros as declared array size
// rcond r*8 condition number
// shift r*8 main diagonal shift
//
// output
//
// a r*8 array for nonzeros
// colidx i col indices
// rowstr i row pointers
//
// workspace
//
// iv, arow, acol i
// aelt r*8
//---------------------------------------------------------------------
static void makea(int n,
int nz,
double a[],
int colidx[],
int rowstr[],
int firstrow,
int lastrow,
int firstcol,
int lastcol,
int arow[],
int acol[][NONZER+1],
double aelt[][NONZER+1],
int iv[])
{
int iouter, ivelt, nzv, nn1;
int ivc[NONZER+1];
double vc[NONZER+1];
//---------------------------------------------------------------------
// nonzer is approximately (int(sqrt(nnza /n)));
//---------------------------------------------------------------------
//---------------------------------------------------------------------
// nn1 is the smallest power of two not less than n
//---------------------------------------------------------------------
nn1 = 1;
do {
nn1 = 2 * nn1;
} while (nn1 < n);
//---------------------------------------------------------------------
// Generate nonzero positions and save for the use in sparse.
//---------------------------------------------------------------------
for (iouter = 0; iouter < n; iouter++) {
nzv = NONZER;
sprnvc(n, nzv, nn1, vc, ivc);
vecset(n, vc, ivc, &nzv, iouter+1, 0.5);
arow[iouter] = nzv;
for (ivelt = 0; ivelt < nzv; ivelt++) {
acol[iouter][ivelt] = ivc[ivelt] - 1;
aelt[iouter][ivelt] = vc[ivelt];
}
}
//---------------------------------------------------------------------
// ... make the sparse matrix from list of elements with duplicates
// (iv is used as workspace)
//---------------------------------------------------------------------
sparse(a, colidx, rowstr, n, nz, NONZER, arow, acol,
aelt, firstrow, lastrow,
iv, RCOND, SHIFT);
}
//---------------------------------------------------------------------
// rows range from firstrow to lastrow
// the rowstr pointers are defined for nrows = lastrow-firstrow+1 values
//---------------------------------------------------------------------
static void sparse(double a[],
int colidx[],
int rowstr[],
int n,
int nz,
int nozer,
int arow[],
int acol[][NONZER+1],
double aelt[][NONZER+1],
int firstrow,
int lastrow,
int nzloc[],
double rcond,
double shift)
{
int nrows;
//---------------------------------------------------
// generate a sparse matrix from a list of
// [col, row, element] tri
//---------------------------------------------------
int i, j, j1, j2, nza, k, kk, nzrow, jcol;
double size, scale, ratio, va;
logical cont40;
//---------------------------------------------------------------------
// how many rows of result
//---------------------------------------------------------------------
nrows = lastrow - firstrow + 1;
//---------------------------------------------------------------------
// ...count the number of triples in each row
//---------------------------------------------------------------------
#pragma omp parallel for
for (j = 0; j < nrows+1; j++) {
rowstr[j] = 0;
}
for (i = 0; i < n; i++) {
for (nza = 0; nza < arow[i]; nza++) {
j = acol[i][nza] + 1;
rowstr[j] = rowstr[j] + arow[i];
}
}
rowstr[0] = 0;
for (j = 1; j < nrows+1; j++) {
rowstr[j] = rowstr[j] + rowstr[j-1];
}
nza = rowstr[nrows] - 1;
//---------------------------------------------------------------------
// ... rowstr(j) now is the location of the first nonzero
// of row j of a
//---------------------------------------------------------------------
if (nza > nz) {
printf("Space for matrix elements exceeded in sparse\n");
printf("nza, nzmax = %d, %d\n", nza, nz);
exit(EXIT_FAILURE);
}
//---------------------------------------------------------------------
// ... preload data pages
//---------------------------------------------------------------------
for (j = 0; j < nrows; j++) {
for (k = rowstr[j]; k < rowstr[j+1]; k++) {
a[k] = 0.0;
colidx[k] = -1;
}
nzloc[j] = 0;
}
//---------------------------------------------------------------------
// ... generate actual values by summing duplicates
//---------------------------------------------------------------------
size = 1.0;
ratio = pow(rcond, (1.0 / (double)(n)));
for (i = 0; i < n; i++) {
for (nza = 0; nza < arow[i]; nza++) {
j = acol[i][nza];
scale = size * aelt[i][nza];
for (nzrow = 0; nzrow < arow[i]; nzrow++) {
jcol = acol[i][nzrow];
va = aelt[i][nzrow] * scale;
//--------------------------------------------------------------------
// ... add the identity * rcond to the generated matrix to bound
// the smallest eigenvalue from below by rcond
//--------------------------------------------------------------------
if (jcol == j && j == i) {
va = va + rcond - shift;
}
cont40 = false;
for (k = rowstr[j]; k < rowstr[j+1]; k++) {
if (colidx[k] > jcol) {
//----------------------------------------------------------------
// ... insert colidx here orderly
//----------------------------------------------------------------
for (kk = rowstr[j+1]-2; kk >= k; kk--) {
if (colidx[kk] > -1) {
a[kk+1] = a[kk];
colidx[kk+1] = colidx[kk];
}
}
colidx[k] = jcol;
a[k] = 0.0;
cont40 = true;
break;
} else if (colidx[k] == -1) {
colidx[k] = jcol;
cont40 = true;
break;
} else if (colidx[k] == jcol) {
//--------------------------------------------------------------
// ... mark the duplicated entry
//--------------------------------------------------------------
nzloc[j] = nzloc[j] + 1;
cont40 = true;
break;
}
}
if (cont40 == false) {
printf("internal error in sparse: i=%d\n", i);
exit(EXIT_FAILURE);
}
a[k] = a[k] + va;
}
}
size = size * ratio;
}
//---------------------------------------------------------------------
// ... remove empty entries and generate final results
//---------------------------------------------------------------------
for (j = 1; j < nrows; j++) {
nzloc[j] = nzloc[j] + nzloc[j-1];
}
for (j = 0; j < nrows; ++j) {
if (j > 0) {
j1 = rowstr[j] - nzloc[j-1];
} else {
j1 = 0;
}
j2 = rowstr[j+1] - nzloc[j];
nza = rowstr[j];
for (k = j1; k < j2; ++k) {
a[k] = a[nza];
colidx[k] = colidx[nza];
++nza;
}
}
#pragma omp parallel for schedule(auto)
for (j = 1; j < nrows+1; j++) {
rowstr[j] = rowstr[j] - nzloc[j-1];
}
nza = rowstr[nrows] - 1;
}
//---------------------------------------------------------------------
// generate a sparse n-vector (v, iv)
// having nzv nonzeros
//
// mark(i) is set to 1 if position i is nonzero.
// mark is all zero on entry and is reset to all zero before exit
// this corrects a performance bug found by John G. Lewis, caused by
// reinitialization of mark on every one of the n calls to sprnvc
//---------------------------------------------------------------------
static void sprnvc(int n, int nz, int nn1, double v[], int iv[])
{
int nzv, ii, i;
double vecelt, vecloc;
nzv = 0;
while (nzv < nz) {
vecelt = randlc(&tran, amult);
//---------------------------------------------------------------------
// generate an integer between 1 and n in a portable manner
//---------------------------------------------------------------------
vecloc = randlc(&tran, amult);
i = icnvrt(vecloc, nn1) + 1;
if (i > n) continue;
//---------------------------------------------------------------------
// was this integer generated already?
//---------------------------------------------------------------------
logical was_gen = false;
for (ii = 0; ii < nzv; ii++) {
if (iv[ii] == i) {
was_gen = true;
break;
}
}
if (was_gen) continue;
v[nzv] = vecelt;
iv[nzv] = i;
nzv = nzv + 1;
}
}
//---------------------------------------------------------------------
// scale a double precision number x in (0,1) by a power of 2 and chop it
//---------------------------------------------------------------------
static int icnvrt(double x, int ipwr2)
{
return (int)(ipwr2 * x);
}
//---------------------------------------------------------------------
// set ith element of sparse vector (v, iv) with
// nzv nonzeros to val
//---------------------------------------------------------------------
static void vecset(int n, double v[], int iv[], int *nzv, int i, double val)
{
int k;
logical set;
set = false;
#pragma omp parallel for
for (k = 0; k < *nzv; k++) {
if (iv[k] == i) {
v[k] = val;
set = true;
}
}
if (set == false) {
v[*nzv] = val;
iv[*nzv] = i;
*nzv = *nzv + 1;
}
}
|
matrix.c | /*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% M M AAA TTTTT RRRR IIIII X X %
% MM MM A A T R R I X X %
% M M M AAAAA T RRRR I X %
% M M A A T R R I X X %
% M M A A T R R IIIII X X %
% %
% %
% MagickCore Matrix Methods %
% %
% Software Design %
% Cristy %
% August 2007 %
% %
% %
% Copyright 1999-2019 ImageMagick Studio LLC, a non-profit organization %
% dedicated to making software imaging solutions freely available. %
% %
% You may not use this file except in compliance with the License. You may %
% obtain a copy of the License at %
% %
% https://imagemagick.org/script/license.php %
% %
% Unless required by applicable law or agreed to in writing, software %
% distributed under the License is distributed on an "AS IS" BASIS, %
% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. %
% See the License for the specific language governing permissions and %
% limitations under the License. %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
%
*/
/*
Include declarations.
*/
#include "MagickCore/studio.h"
#include "MagickCore/blob.h"
#include "MagickCore/blob-private.h"
#include "MagickCore/cache.h"
#include "MagickCore/exception.h"
#include "MagickCore/exception-private.h"
#include "MagickCore/image-private.h"
#include "MagickCore/matrix.h"
#include "MagickCore/matrix-private.h"
#include "MagickCore/memory_.h"
#include "MagickCore/pixel-accessor.h"
#include "MagickCore/pixel-private.h"
#include "MagickCore/resource_.h"
#include "MagickCore/semaphore.h"
#include "MagickCore/thread-private.h"
#include "MagickCore/utility.h"
/*
Typedef declaration.
*/
struct _MatrixInfo
{
CacheType
type;
size_t
columns,
rows,
stride;
MagickSizeType
length;
MagickBooleanType
mapped,
synchronize;
char
path[MagickPathExtent];
int
file;
void
*elements;
SemaphoreInfo
*semaphore;
size_t
signature;
};
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% A c q u i r e M a t r i x I n f o %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% AcquireMatrixInfo() allocates the ImageInfo structure.
%
% The format of the AcquireMatrixInfo method is:
%
% MatrixInfo *AcquireMatrixInfo(const size_t columns,const size_t rows,
% const size_t stride,ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o columns: the matrix columns.
%
% o rows: the matrix rows.
%
% o stride: the matrix stride.
%
% o exception: return any errors or warnings in this structure.
%
*/
#if defined(SIGBUS)
static void MatrixSignalHandler(int status)
{
ThrowFatalException(CacheFatalError,"UnableToExtendMatrixCache");
}
#endif
static inline MagickOffsetType WriteMatrixElements(
const MatrixInfo *magick_restrict matrix_info,const MagickOffsetType offset,
const MagickSizeType length,const unsigned char *magick_restrict buffer)
{
register MagickOffsetType
i;
ssize_t
count;
#if !defined(MAGICKCORE_HAVE_PWRITE)
LockSemaphoreInfo(matrix_info->semaphore);
if (lseek(matrix_info->file,offset,SEEK_SET) < 0)
{
UnlockSemaphoreInfo(matrix_info->semaphore);
return((MagickOffsetType) -1);
}
#endif
count=0;
for (i=0; i < (MagickOffsetType) length; i+=count)
{
#if !defined(MAGICKCORE_HAVE_PWRITE)
count=write(matrix_info->file,buffer+i,(size_t) MagickMin(length-i,
(MagickSizeType) SSIZE_MAX));
#else
count=pwrite(matrix_info->file,buffer+i,(size_t) MagickMin(length-i,
(MagickSizeType) SSIZE_MAX),(off_t) (offset+i));
#endif
if (count <= 0)
{
count=0;
if (errno != EINTR)
break;
}
}
#if !defined(MAGICKCORE_HAVE_PWRITE)
UnlockSemaphoreInfo(matrix_info->semaphore);
#endif
return(i);
}
static MagickBooleanType SetMatrixExtent(
MatrixInfo *magick_restrict matrix_info,MagickSizeType length)
{
MagickOffsetType
count,
extent,
offset;
if (length != (MagickSizeType) ((MagickOffsetType) length))
return(MagickFalse);
offset=(MagickOffsetType) lseek(matrix_info->file,0,SEEK_END);
if (offset < 0)
return(MagickFalse);
if ((MagickSizeType) offset >= length)
return(MagickTrue);
extent=(MagickOffsetType) length-1;
count=WriteMatrixElements(matrix_info,extent,1,(const unsigned char *) "");
#if defined(MAGICKCORE_HAVE_POSIX_FALLOCATE)
if (matrix_info->synchronize != MagickFalse)
(void) posix_fallocate(matrix_info->file,offset+1,extent-offset);
#endif
#if defined(SIGBUS)
(void) signal(SIGBUS,MatrixSignalHandler);
#endif
return(count != (MagickOffsetType) 1 ? MagickFalse : MagickTrue);
}
MagickExport MatrixInfo *AcquireMatrixInfo(const size_t columns,
const size_t rows,const size_t stride,ExceptionInfo *exception)
{
char
*synchronize;
MagickBooleanType
status;
MatrixInfo
*matrix_info;
matrix_info=(MatrixInfo *) AcquireMagickMemory(sizeof(*matrix_info));
if (matrix_info == (MatrixInfo *) NULL)
return((MatrixInfo *) NULL);
(void) memset(matrix_info,0,sizeof(*matrix_info));
matrix_info->signature=MagickCoreSignature;
matrix_info->columns=columns;
matrix_info->rows=rows;
matrix_info->stride=stride;
matrix_info->semaphore=AcquireSemaphoreInfo();
synchronize=GetEnvironmentValue("MAGICK_SYNCHRONIZE");
if (synchronize != (const char *) NULL)
{
matrix_info->synchronize=IsStringTrue(synchronize);
synchronize=DestroyString(synchronize);
}
matrix_info->length=(MagickSizeType) columns*rows*stride;
if (matrix_info->columns != (size_t) (matrix_info->length/rows/stride))
{
(void) ThrowMagickException(exception,GetMagickModule(),CacheError,
"CacheResourcesExhausted","`%s'","matrix cache");
return(DestroyMatrixInfo(matrix_info));
}
matrix_info->type=MemoryCache;
status=AcquireMagickResource(AreaResource,matrix_info->length);
if ((status != MagickFalse) &&
(matrix_info->length == (MagickSizeType) ((size_t) matrix_info->length)))
{
status=AcquireMagickResource(MemoryResource,matrix_info->length);
if (status != MagickFalse)
{
matrix_info->mapped=MagickFalse;
matrix_info->elements=AcquireMagickMemory((size_t)
matrix_info->length);
if (matrix_info->elements == NULL)
{
matrix_info->mapped=MagickTrue;
matrix_info->elements=MapBlob(-1,IOMode,0,(size_t)
matrix_info->length);
}
if (matrix_info->elements == (unsigned short *) NULL)
RelinquishMagickResource(MemoryResource,matrix_info->length);
}
}
matrix_info->file=(-1);
if (matrix_info->elements == (unsigned short *) NULL)
{
status=AcquireMagickResource(DiskResource,matrix_info->length);
if (status == MagickFalse)
{
(void) ThrowMagickException(exception,GetMagickModule(),CacheError,
"CacheResourcesExhausted","`%s'","matrix cache");
return(DestroyMatrixInfo(matrix_info));
}
matrix_info->type=DiskCache;
matrix_info->file=AcquireUniqueFileResource(matrix_info->path);
if (matrix_info->file == -1)
return(DestroyMatrixInfo(matrix_info));
status=AcquireMagickResource(MapResource,matrix_info->length);
if (status != MagickFalse)
{
status=SetMatrixExtent(matrix_info,matrix_info->length);
if (status != MagickFalse)
matrix_info->elements=(void *) MapBlob(matrix_info->file,IOMode,0,
(size_t) matrix_info->length);
if (matrix_info->elements != NULL)
matrix_info->type=MapCache;
else
RelinquishMagickResource(MapResource,matrix_info->length);
}
}
return(matrix_info);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% A c q u i r e M a g i c k M a t r i x %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% AcquireMagickMatrix() allocates and returns a matrix in the form of an
% array of pointers to an array of doubles, with all values pre-set to zero.
%
% This used to generate the two dimensional matrix, and vectors required
% for the GaussJordanElimination() method below, solving some system of
% simultanious equations.
%
% The format of the AcquireMagickMatrix method is:
%
% double **AcquireMagickMatrix(const size_t number_rows,
% const size_t size)
%
% A description of each parameter follows:
%
% o number_rows: the number pointers for the array of pointers
% (first dimension).
%
% o size: the size of the array of doubles each pointer points to
% (second dimension).
%
*/
MagickExport double **AcquireMagickMatrix(const size_t number_rows,
const size_t size)
{
double
**matrix;
register ssize_t
i,
j;
matrix=(double **) AcquireQuantumMemory(number_rows,sizeof(*matrix));
if (matrix == (double **) NULL)
return((double **) NULL);
for (i=0; i < (ssize_t) number_rows; i++)
{
matrix[i]=(double *) AcquireQuantumMemory(size,sizeof(*matrix[i]));
if (matrix[i] == (double *) NULL)
{
for (j=0; j < i; j++)
matrix[j]=(double *) RelinquishMagickMemory(matrix[j]);
matrix=(double **) RelinquishMagickMemory(matrix);
return((double **) NULL);
}
for (j=0; j < (ssize_t) size; j++)
matrix[i][j]=0.0;
}
return(matrix);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% D e s t r o y M a t r i x I n f o %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% DestroyMatrixInfo() dereferences a matrix, deallocating memory associated
% with the matrix.
%
% The format of the DestroyImage method is:
%
% MatrixInfo *DestroyMatrixInfo(MatrixInfo *matrix_info)
%
% A description of each parameter follows:
%
% o matrix_info: the matrix.
%
*/
MagickExport MatrixInfo *DestroyMatrixInfo(MatrixInfo *matrix_info)
{
assert(matrix_info != (MatrixInfo *) NULL);
assert(matrix_info->signature == MagickCoreSignature);
LockSemaphoreInfo(matrix_info->semaphore);
switch (matrix_info->type)
{
case MemoryCache:
{
if (matrix_info->mapped == MagickFalse)
matrix_info->elements=RelinquishMagickMemory(matrix_info->elements);
else
{
(void) UnmapBlob(matrix_info->elements,(size_t) matrix_info->length);
matrix_info->elements=(unsigned short *) NULL;
}
RelinquishMagickResource(MemoryResource,matrix_info->length);
break;
}
case MapCache:
{
(void) UnmapBlob(matrix_info->elements,(size_t) matrix_info->length);
matrix_info->elements=NULL;
RelinquishMagickResource(MapResource,matrix_info->length);
}
case DiskCache:
{
if (matrix_info->file != -1)
(void) close(matrix_info->file);
(void) RelinquishUniqueFileResource(matrix_info->path);
RelinquishMagickResource(DiskResource,matrix_info->length);
break;
}
default:
break;
}
UnlockSemaphoreInfo(matrix_info->semaphore);
RelinquishSemaphoreInfo(&matrix_info->semaphore);
return((MatrixInfo *) RelinquishMagickMemory(matrix_info));
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
+ G a u s s J o r d a n E l i m i n a t i o n %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% GaussJordanElimination() returns a matrix in reduced row echelon form,
% while simultaneously reducing and thus solving the augumented results
% matrix.
%
% See also http://en.wikipedia.org/wiki/Gauss-Jordan_elimination
%
% The format of the GaussJordanElimination method is:
%
% MagickBooleanType GaussJordanElimination(double **matrix,
% double **vectors,const size_t rank,const size_t number_vectors)
%
% A description of each parameter follows:
%
% o matrix: the matrix to be reduced, as an 'array of row pointers'.
%
% o vectors: the additional matrix argumenting the matrix for row reduction.
% Producing an 'array of column vectors'.
%
% o rank: The size of the matrix (both rows and columns).
% Also represents the number terms that need to be solved.
%
% o number_vectors: Number of vectors columns, argumenting the above matrix.
% Usally 1, but can be more for more complex equation solving.
%
% Note that the 'matrix' is given as a 'array of row pointers' of rank size.
% That is values can be assigned as matrix[row][column] where 'row' is
% typically the equation, and 'column' is the term of the equation.
% That is the matrix is in the form of a 'row first array'.
%
% However 'vectors' is a 'array of column pointers' which can have any number
% of columns, with each column array the same 'rank' size as 'matrix'.
%
% This allows for simpler handling of the results, especially is only one
% column 'vector' is all that is required to produce the desired solution.
%
% For example, the 'vectors' can consist of a pointer to a simple array of
% doubles. when only one set of simultanious equations is to be solved from
% the given set of coefficient weighted terms.
%
% double **matrix = AcquireMagickMatrix(8UL,8UL);
% double coefficents[8];
% ...
% GaussJordanElimination(matrix, &coefficents, 8UL, 1UL);
%
% However by specifing more 'columns' (as an 'array of vector columns',
% you can use this function to solve a set of 'separable' equations.
%
% For example a distortion function where u = U(x,y) v = V(x,y)
% And the functions U() and V() have separate coefficents, but are being
% generated from a common x,y->u,v data set.
%
% Another example is generation of a color gradient from a set of colors at
% specific coordients, such as a list x,y -> r,g,b,a.
%
% You can also use the 'vectors' to generate an inverse of the given 'matrix'
% though as a 'column first array' rather than a 'row first array'. For
% details see http://en.wikipedia.org/wiki/Gauss-Jordan_elimination
%
*/
MagickPrivate MagickBooleanType GaussJordanElimination(double **matrix,
double **vectors,const size_t rank,const size_t number_vectors)
{
#define GaussJordanSwap(x,y) \
{ \
if ((x) != (y)) \
{ \
(x)+=(y); \
(y)=(x)-(y); \
(x)=(x)-(y); \
} \
}
double
max,
scale;
register ssize_t
i,
j,
k;
ssize_t
column,
*columns,
*pivots,
row,
*rows;
columns=(ssize_t *) AcquireQuantumMemory(rank,sizeof(*columns));
rows=(ssize_t *) AcquireQuantumMemory(rank,sizeof(*rows));
pivots=(ssize_t *) AcquireQuantumMemory(rank,sizeof(*pivots));
if ((rows == (ssize_t *) NULL) || (columns == (ssize_t *) NULL) ||
(pivots == (ssize_t *) NULL))
{
if (pivots != (ssize_t *) NULL)
pivots=(ssize_t *) RelinquishMagickMemory(pivots);
if (columns != (ssize_t *) NULL)
columns=(ssize_t *) RelinquishMagickMemory(columns);
if (rows != (ssize_t *) NULL)
rows=(ssize_t *) RelinquishMagickMemory(rows);
return(MagickFalse);
}
(void) memset(columns,0,rank*sizeof(*columns));
(void) memset(rows,0,rank*sizeof(*rows));
(void) memset(pivots,0,rank*sizeof(*pivots));
column=0;
row=0;
for (i=0; i < (ssize_t) rank; i++)
{
max=0.0;
for (j=0; j < (ssize_t) rank; j++)
if (pivots[j] != 1)
{
for (k=0; k < (ssize_t) rank; k++)
if (pivots[k] != 0)
{
if (pivots[k] > 1)
return(MagickFalse);
}
else
if (fabs(matrix[j][k]) >= max)
{
max=fabs(matrix[j][k]);
row=j;
column=k;
}
}
pivots[column]++;
if (row != column)
{
for (k=0; k < (ssize_t) rank; k++)
GaussJordanSwap(matrix[row][k],matrix[column][k]);
for (k=0; k < (ssize_t) number_vectors; k++)
GaussJordanSwap(vectors[k][row],vectors[k][column]);
}
rows[i]=row;
columns[i]=column;
if (matrix[column][column] == 0.0)
return(MagickFalse); /* sigularity */
scale=PerceptibleReciprocal(matrix[column][column]);
matrix[column][column]=1.0;
for (j=0; j < (ssize_t) rank; j++)
matrix[column][j]*=scale;
for (j=0; j < (ssize_t) number_vectors; j++)
vectors[j][column]*=scale;
for (j=0; j < (ssize_t) rank; j++)
if (j != column)
{
scale=matrix[j][column];
matrix[j][column]=0.0;
for (k=0; k < (ssize_t) rank; k++)
matrix[j][k]-=scale*matrix[column][k];
for (k=0; k < (ssize_t) number_vectors; k++)
vectors[k][j]-=scale*vectors[k][column];
}
}
for (j=(ssize_t) rank-1; j >= 0; j--)
if (columns[j] != rows[j])
for (i=0; i < (ssize_t) rank; i++)
GaussJordanSwap(matrix[i][rows[j]],matrix[i][columns[j]]);
pivots=(ssize_t *) RelinquishMagickMemory(pivots);
rows=(ssize_t *) RelinquishMagickMemory(rows);
columns=(ssize_t *) RelinquishMagickMemory(columns);
return(MagickTrue);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% G e t M a t r i x C o l u m n s %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% GetMatrixColumns() returns the number of columns in the matrix.
%
% The format of the GetMatrixColumns method is:
%
% size_t GetMatrixColumns(const MatrixInfo *matrix_info)
%
% A description of each parameter follows:
%
% o matrix_info: the matrix.
%
*/
MagickExport size_t GetMatrixColumns(const MatrixInfo *matrix_info)
{
assert(matrix_info != (MatrixInfo *) NULL);
assert(matrix_info->signature == MagickCoreSignature);
return(matrix_info->columns);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% G e t M a t r i x E l e m e n t %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% GetMatrixElement() returns the specifed element in the matrix.
%
% The format of the GetMatrixElement method is:
%
% MagickBooleanType GetMatrixElement(const MatrixInfo *matrix_info,
% const ssize_t x,const ssize_t y,void *value)
%
% A description of each parameter follows:
%
% o matrix_info: the matrix columns.
%
% o x: the matrix x-offset.
%
% o y: the matrix y-offset.
%
% o value: return the matrix element in this buffer.
%
*/
static inline ssize_t EdgeX(const ssize_t x,const size_t columns)
{
if (x < 0L)
return(0L);
if (x >= (ssize_t) columns)
return((ssize_t) (columns-1));
return(x);
}
static inline ssize_t EdgeY(const ssize_t y,const size_t rows)
{
if (y < 0L)
return(0L);
if (y >= (ssize_t) rows)
return((ssize_t) (rows-1));
return(y);
}
static inline MagickOffsetType ReadMatrixElements(
const MatrixInfo *magick_restrict matrix_info,const MagickOffsetType offset,
const MagickSizeType length,unsigned char *magick_restrict buffer)
{
register MagickOffsetType
i;
ssize_t
count;
#if !defined(MAGICKCORE_HAVE_PREAD)
LockSemaphoreInfo(matrix_info->semaphore);
if (lseek(matrix_info->file,offset,SEEK_SET) < 0)
{
UnlockSemaphoreInfo(matrix_info->semaphore);
return((MagickOffsetType) -1);
}
#endif
count=0;
for (i=0; i < (MagickOffsetType) length; i+=count)
{
#if !defined(MAGICKCORE_HAVE_PREAD)
count=read(matrix_info->file,buffer+i,(size_t) MagickMin(length-i,
(MagickSizeType) SSIZE_MAX));
#else
count=pread(matrix_info->file,buffer+i,(size_t) MagickMin(length-i,
(MagickSizeType) SSIZE_MAX),(off_t) (offset+i));
#endif
if (count <= 0)
{
count=0;
if (errno != EINTR)
break;
}
}
#if !defined(MAGICKCORE_HAVE_PREAD)
UnlockSemaphoreInfo(matrix_info->semaphore);
#endif
return(i);
}
MagickExport MagickBooleanType GetMatrixElement(const MatrixInfo *matrix_info,
const ssize_t x,const ssize_t y,void *value)
{
MagickOffsetType
count,
i;
assert(matrix_info != (const MatrixInfo *) NULL);
assert(matrix_info->signature == MagickCoreSignature);
i=(MagickOffsetType) EdgeY(y,matrix_info->rows)*matrix_info->columns+
EdgeX(x,matrix_info->columns);
if (matrix_info->type != DiskCache)
{
(void) memcpy(value,(unsigned char *) matrix_info->elements+i*
matrix_info->stride,matrix_info->stride);
return(MagickTrue);
}
count=ReadMatrixElements(matrix_info,i*matrix_info->stride,
matrix_info->stride,(unsigned char *) value);
if (count != (MagickOffsetType) matrix_info->stride)
return(MagickFalse);
return(MagickTrue);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% G e t M a t r i x R o w s %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% GetMatrixRows() returns the number of rows in the matrix.
%
% The format of the GetMatrixRows method is:
%
% size_t GetMatrixRows(const MatrixInfo *matrix_info)
%
% A description of each parameter follows:
%
% o matrix_info: the matrix.
%
*/
MagickExport size_t GetMatrixRows(const MatrixInfo *matrix_info)
{
assert(matrix_info != (const MatrixInfo *) NULL);
assert(matrix_info->signature == MagickCoreSignature);
return(matrix_info->rows);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
+ L e a s t S q u a r e s A d d T e r m s %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% LeastSquaresAddTerms() adds one set of terms and associate results to the
% given matrix and vectors for solving using least-squares function fitting.
%
% The format of the AcquireMagickMatrix method is:
%
% void LeastSquaresAddTerms(double **matrix,double **vectors,
% const double *terms,const double *results,const size_t rank,
% const size_t number_vectors);
%
% A description of each parameter follows:
%
% o matrix: the square matrix to add given terms/results to.
%
% o vectors: the result vectors to add terms/results to.
%
% o terms: the pre-calculated terms (without the unknown coefficent
% weights) that forms the equation being added.
%
% o results: the result(s) that should be generated from the given terms
% weighted by the yet-to-be-solved coefficents.
%
% o rank: the rank or size of the dimensions of the square matrix.
% Also the length of vectors, and number of terms being added.
%
% o number_vectors: Number of result vectors, and number or results being
% added. Also represents the number of separable systems of equations
% that is being solved.
%
% Example of use...
%
% 2 dimensional Affine Equations (which are separable)
% c0*x + c2*y + c4*1 => u
% c1*x + c3*y + c5*1 => v
%
% double **matrix = AcquireMagickMatrix(3UL,3UL);
% double **vectors = AcquireMagickMatrix(2UL,3UL);
% double terms[3], results[2];
% ...
% for each given x,y -> u,v
% terms[0] = x;
% terms[1] = y;
% terms[2] = 1;
% results[0] = u;
% results[1] = v;
% LeastSquaresAddTerms(matrix,vectors,terms,results,3UL,2UL);
% ...
% if ( GaussJordanElimination(matrix,vectors,3UL,2UL) ) {
% c0 = vectors[0][0];
% c2 = vectors[0][1];
% c4 = vectors[0][2];
% c1 = vectors[1][0];
% c3 = vectors[1][1];
% c5 = vectors[1][2];
% }
% else
% printf("Matrix unsolvable\n);
% RelinquishMagickMatrix(matrix,3UL);
% RelinquishMagickMatrix(vectors,2UL);
%
*/
MagickPrivate void LeastSquaresAddTerms(double **matrix,double **vectors,
const double *terms,const double *results,const size_t rank,
const size_t number_vectors)
{
register ssize_t
i,
j;
for (j=0; j < (ssize_t) rank; j++)
{
for (i=0; i < (ssize_t) rank; i++)
matrix[i][j]+=terms[i]*terms[j];
for (i=0; i < (ssize_t) number_vectors; i++)
vectors[i][j]+=results[i]*terms[j];
}
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% M a t r i x T o I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% MatrixToImage() returns a matrix as an image. The matrix elements must be
% of type double otherwise nonsense is returned.
%
% The format of the MatrixToImage method is:
%
% Image *MatrixToImage(const MatrixInfo *matrix_info,
% ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o matrix_info: the matrix.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport Image *MatrixToImage(const MatrixInfo *matrix_info,
ExceptionInfo *exception)
{
CacheView
*image_view;
double
max_value,
min_value,
scale_factor;
Image
*image;
MagickBooleanType
status;
ssize_t
y;
assert(matrix_info != (const MatrixInfo *) NULL);
assert(matrix_info->signature == MagickCoreSignature);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickCoreSignature);
if (matrix_info->stride < sizeof(double))
return((Image *) NULL);
/*
Determine range of matrix.
*/
(void) GetMatrixElement(matrix_info,0,0,&min_value);
max_value=min_value;
for (y=0; y < (ssize_t) matrix_info->rows; y++)
{
register ssize_t
x;
for (x=0; x < (ssize_t) matrix_info->columns; x++)
{
double
value;
if (GetMatrixElement(matrix_info,x,y,&value) == MagickFalse)
continue;
if (value < min_value)
min_value=value;
else
if (value > max_value)
max_value=value;
}
}
if ((min_value == 0.0) && (max_value == 0.0))
scale_factor=0;
else
if (min_value == max_value)
{
scale_factor=(double) QuantumRange/min_value;
min_value=0;
}
else
scale_factor=(double) QuantumRange/(max_value-min_value);
/*
Convert matrix to image.
*/
image=AcquireImage((ImageInfo *) NULL,exception);
image->columns=matrix_info->columns;
image->rows=matrix_info->rows;
image->colorspace=GRAYColorspace;
status=MagickTrue;
image_view=AcquireAuthenticCacheView(image,exception);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static) shared(status) \
magick_number_threads(image,image,image->rows,1)
#endif
for (y=0; y < (ssize_t) image->rows; y++)
{
double
value;
register Quantum
*q;
register ssize_t
x;
if (status == MagickFalse)
continue;
q=QueueCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception);
if (q == (Quantum *) NULL)
{
status=MagickFalse;
continue;
}
for (x=0; x < (ssize_t) image->columns; x++)
{
if (GetMatrixElement(matrix_info,x,y,&value) == MagickFalse)
continue;
value=scale_factor*(value-min_value);
*q=ClampToQuantum(value);
q+=GetPixelChannels(image);
}
if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
status=MagickFalse;
}
image_view=DestroyCacheView(image_view);
if (status == MagickFalse)
image=DestroyImage(image);
return(image);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% N u l l M a t r i x %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% NullMatrix() sets all elements of the matrix to zero.
%
% The format of the memset method is:
%
% MagickBooleanType *NullMatrix(MatrixInfo *matrix_info)
%
% A description of each parameter follows:
%
% o matrix_info: the matrix.
%
*/
MagickExport MagickBooleanType NullMatrix(MatrixInfo *matrix_info)
{
register ssize_t
x;
ssize_t
count,
y;
unsigned char
value;
assert(matrix_info != (const MatrixInfo *) NULL);
assert(matrix_info->signature == MagickCoreSignature);
if (matrix_info->type != DiskCache)
{
(void) memset(matrix_info->elements,0,(size_t)
matrix_info->length);
return(MagickTrue);
}
value=0;
(void) lseek(matrix_info->file,0,SEEK_SET);
for (y=0; y < (ssize_t) matrix_info->rows; y++)
{
for (x=0; x < (ssize_t) matrix_info->length; x++)
{
count=write(matrix_info->file,&value,sizeof(value));
if (count != (ssize_t) sizeof(value))
break;
}
if (x < (ssize_t) matrix_info->length)
break;
}
return(y < (ssize_t) matrix_info->rows ? MagickFalse : MagickTrue);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% R e l i n q u i s h M a g i c k M a t r i x %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% RelinquishMagickMatrix() frees the previously acquired matrix (array of
% pointers to arrays of doubles).
%
% The format of the RelinquishMagickMatrix method is:
%
% double **RelinquishMagickMatrix(double **matrix,
% const size_t number_rows)
%
% A description of each parameter follows:
%
% o matrix: the matrix to relinquish
%
% o number_rows: the first dimension of the acquired matrix (number of
% pointers)
%
*/
MagickExport double **RelinquishMagickMatrix(double **matrix,
const size_t number_rows)
{
register ssize_t
i;
if (matrix == (double **) NULL )
return(matrix);
for (i=0; i < (ssize_t) number_rows; i++)
matrix[i]=(double *) RelinquishMagickMemory(matrix[i]);
matrix=(double **) RelinquishMagickMemory(matrix);
return(matrix);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% S e t M a t r i x E l e m e n t %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% SetMatrixElement() sets the specifed element in the matrix.
%
% The format of the SetMatrixElement method is:
%
% MagickBooleanType SetMatrixElement(const MatrixInfo *matrix_info,
% const ssize_t x,const ssize_t y,void *value)
%
% A description of each parameter follows:
%
% o matrix_info: the matrix columns.
%
% o x: the matrix x-offset.
%
% o y: the matrix y-offset.
%
% o value: set the matrix element to this value.
%
*/
MagickExport MagickBooleanType SetMatrixElement(const MatrixInfo *matrix_info,
const ssize_t x,const ssize_t y,const void *value)
{
MagickOffsetType
count,
i;
assert(matrix_info != (const MatrixInfo *) NULL);
assert(matrix_info->signature == MagickCoreSignature);
i=(MagickOffsetType) y*matrix_info->columns+x;
if ((i < 0) ||
((MagickSizeType) (i*matrix_info->stride) >= matrix_info->length))
return(MagickFalse);
if (matrix_info->type != DiskCache)
{
(void) memcpy((unsigned char *) matrix_info->elements+i*
matrix_info->stride,value,matrix_info->stride);
return(MagickTrue);
}
count=WriteMatrixElements(matrix_info,i*matrix_info->stride,
matrix_info->stride,(unsigned char *) value);
if (count != (MagickOffsetType) matrix_info->stride)
return(MagickFalse);
return(MagickTrue);
}
|
feature_group.h | /*!
* Copyright (c) 2017 Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See LICENSE file in the project root for license information.
*/
#ifndef LIGHTGBM_FEATURE_GROUP_H_
#define LIGHTGBM_FEATURE_GROUP_H_
#include <cstdio>
#include <memory>
#include <vector>
#include <LightGBM/bin.h>
#include <LightGBM/meta.h>
#include <LightGBM/utils/random.h>
namespace LightGBM {
class Dataset;
class DatasetLoader;
/*! \brief Using to store data and providing some operations on one feature group*/
class FeatureGroup {
public:
friend Dataset;
friend DatasetLoader;
/*!
* \brief Constructor
* \param num_feature number of features of this group
* \param bin_mappers Bin mapper for features
* \param num_data Total number of data
* \param is_enable_sparse True if enable sparse feature
*/
FeatureGroup(int num_feature, bool is_multi_val,
std::vector<std::unique_ptr<BinMapper>>* bin_mappers,
data_size_t num_data) : num_feature_(num_feature), is_multi_val_(is_multi_val), is_sparse_(false) {
CHECK_EQ(static_cast<int>(bin_mappers->size()), num_feature);
// use bin at zero to store most_freq_bin
num_total_bin_ = 1;
bin_offsets_.emplace_back(num_total_bin_);
auto& ref_bin_mappers = *bin_mappers;
for (int i = 0; i < num_feature_; ++i) {
bin_mappers_.emplace_back(ref_bin_mappers[i].release());
auto num_bin = bin_mappers_[i]->num_bin();
if (bin_mappers_[i]->GetMostFreqBin() == 0) {
num_bin -= 1;
}
num_total_bin_ += num_bin;
bin_offsets_.emplace_back(num_total_bin_);
}
CreateBinData(num_data, is_multi_val_, true, false);
}
FeatureGroup(const FeatureGroup& other, int num_data) {
num_feature_ = other.num_feature_;
is_multi_val_ = other.is_multi_val_;
is_sparse_ = other.is_sparse_;
num_total_bin_ = other.num_total_bin_;
bin_offsets_ = other.bin_offsets_;
bin_mappers_.reserve(other.bin_mappers_.size());
for (auto& bin_mapper : other.bin_mappers_) {
bin_mappers_.emplace_back(new BinMapper(*bin_mapper));
}
CreateBinData(num_data, is_multi_val_, !is_sparse_, is_sparse_);
}
FeatureGroup(std::vector<std::unique_ptr<BinMapper>>* bin_mappers,
data_size_t num_data) : num_feature_(1), is_multi_val_(false) {
CHECK_EQ(static_cast<int>(bin_mappers->size()), 1);
// use bin at zero to store default_bin
num_total_bin_ = 1;
bin_offsets_.emplace_back(num_total_bin_);
auto& ref_bin_mappers = *bin_mappers;
for (int i = 0; i < num_feature_; ++i) {
bin_mappers_.emplace_back(ref_bin_mappers[i].release());
auto num_bin = bin_mappers_[i]->num_bin();
if (bin_mappers_[i]->GetMostFreqBin() == 0) {
num_bin -= 1;
}
num_total_bin_ += num_bin;
bin_offsets_.emplace_back(num_total_bin_);
}
CreateBinData(num_data, false, false, false);
}
/*!
* \brief Constructor from memory
* \param memory Pointer of memory
* \param num_all_data Number of global data
* \param local_used_indices Local used indices, empty means using all data
*/
FeatureGroup(const void* memory, data_size_t num_all_data,
const std::vector<data_size_t>& local_used_indices) {
const char* memory_ptr = reinterpret_cast<const char*>(memory);
// get is_sparse
is_multi_val_ = *(reinterpret_cast<const bool*>(memory_ptr));
memory_ptr += sizeof(is_multi_val_);
is_sparse_ = *(reinterpret_cast<const bool*>(memory_ptr));
memory_ptr += sizeof(is_sparse_);
num_feature_ = *(reinterpret_cast<const int*>(memory_ptr));
memory_ptr += sizeof(num_feature_);
// get bin mapper
bin_mappers_.clear();
bin_offsets_.clear();
// start from 1, due to need to store zero bin in this slot
num_total_bin_ = 1;
bin_offsets_.emplace_back(num_total_bin_);
for (int i = 0; i < num_feature_; ++i) {
bin_mappers_.emplace_back(new BinMapper(memory_ptr));
auto num_bin = bin_mappers_[i]->num_bin();
if (bin_mappers_[i]->GetMostFreqBin() == 0) {
num_bin -= 1;
}
num_total_bin_ += num_bin;
bin_offsets_.emplace_back(num_total_bin_);
memory_ptr += bin_mappers_[i]->SizesInByte();
}
data_size_t num_data = num_all_data;
if (!local_used_indices.empty()) {
num_data = static_cast<data_size_t>(local_used_indices.size());
}
if (is_multi_val_) {
for (int i = 0; i < num_feature_; ++i) {
int addi = bin_mappers_[i]->GetMostFreqBin() == 0 ? 0 : 1;
if (bin_mappers_[i]->sparse_rate() >= kSparseThreshold) {
multi_bin_data_.emplace_back(Bin::CreateSparseBin(num_data, bin_mappers_[i]->num_bin() + addi));
} else {
multi_bin_data_.emplace_back(Bin::CreateDenseBin(num_data, bin_mappers_[i]->num_bin() + addi));
}
multi_bin_data_.back()->LoadFromMemory(memory_ptr, local_used_indices);
memory_ptr += multi_bin_data_.back()->SizesInByte();
}
} else {
if (is_sparse_) {
bin_data_.reset(Bin::CreateSparseBin(num_data, num_total_bin_));
} else {
bin_data_.reset(Bin::CreateDenseBin(num_data, num_total_bin_));
}
// get bin data
bin_data_->LoadFromMemory(memory_ptr, local_used_indices);
}
}
/*! \brief Destructor */
~FeatureGroup() {
}
/*!
* \brief Push one record, will auto convert to bin and push to bin data
* \param tid Thread id
* \param idx Index of record
* \param value feature value of record
*/
inline void PushData(int tid, int sub_feature_idx, data_size_t line_idx, double value) {
uint32_t bin = bin_mappers_[sub_feature_idx]->ValueToBin(value);
if (bin == bin_mappers_[sub_feature_idx]->GetMostFreqBin()) { return; }
if (bin_mappers_[sub_feature_idx]->GetMostFreqBin() == 0) {
bin -= 1;
}
if (is_multi_val_) {
multi_bin_data_[sub_feature_idx]->Push(tid, line_idx, bin + 1);
} else {
bin += bin_offsets_[sub_feature_idx];
bin_data_->Push(tid, line_idx, bin);
}
}
void ReSize(int num_data) {
if (!is_multi_val_) {
bin_data_->ReSize(num_data);
} else {
for (int i = 0; i < num_feature_; ++i) {
multi_bin_data_[i]->ReSize(num_data);
}
}
}
inline void CopySubrow(const FeatureGroup* full_feature, const data_size_t* used_indices, data_size_t num_used_indices) {
if (!is_multi_val_) {
bin_data_->CopySubrow(full_feature->bin_data_.get(), used_indices, num_used_indices);
} else {
for (int i = 0; i < num_feature_; ++i) {
multi_bin_data_[i]->CopySubrow(full_feature->multi_bin_data_[i].get(), used_indices, num_used_indices);
}
}
}
inline BinIterator* SubFeatureIterator(int sub_feature) {
uint32_t most_freq_bin = bin_mappers_[sub_feature]->GetMostFreqBin();
if (!is_multi_val_) {
uint32_t min_bin = bin_offsets_[sub_feature];
uint32_t max_bin = bin_offsets_[sub_feature + 1] - 1;
return bin_data_->GetIterator(min_bin, max_bin, most_freq_bin);
} else {
int addi = bin_mappers_[sub_feature]->GetMostFreqBin() == 0 ? 0 : 1;
uint32_t min_bin = 1;
uint32_t max_bin = bin_mappers_[sub_feature]->num_bin() - 1 + addi;
return multi_bin_data_[sub_feature]->GetIterator(min_bin, max_bin, most_freq_bin);
}
}
inline void FinishLoad() {
if (is_multi_val_) {
OMP_INIT_EX();
#pragma omp parallel for schedule(guided)
for (int i = 0; i < num_feature_; ++i) {
OMP_LOOP_EX_BEGIN();
multi_bin_data_[i]->FinishLoad();
OMP_LOOP_EX_END();
}
OMP_THROW_EX();
} else {
bin_data_->FinishLoad();
}
}
/*!
* \brief Returns a BinIterator that can access the entire feature group's raw data.
* The RawGet() function of the iterator should be called for best efficiency.
* \return A pointer to the BinIterator object
*/
inline BinIterator* FeatureGroupIterator() {
if (is_multi_val_) {
return nullptr;
}
uint32_t min_bin = bin_offsets_[0];
uint32_t max_bin = bin_offsets_.back() - 1;
uint32_t most_freq_bin = 0;
return bin_data_->GetIterator(min_bin, max_bin, most_freq_bin);
}
inline data_size_t Split(int sub_feature, const uint32_t* threshold,
int num_threshold, bool default_left,
const data_size_t* data_indices, data_size_t cnt,
data_size_t* lte_indices,
data_size_t* gt_indices) const {
uint32_t default_bin = bin_mappers_[sub_feature]->GetDefaultBin();
uint32_t most_freq_bin = bin_mappers_[sub_feature]->GetMostFreqBin();
if (!is_multi_val_) {
uint32_t min_bin = bin_offsets_[sub_feature];
uint32_t max_bin = bin_offsets_[sub_feature + 1] - 1;
if (bin_mappers_[sub_feature]->bin_type() == BinType::NumericalBin) {
auto missing_type = bin_mappers_[sub_feature]->missing_type();
if (num_feature_ == 1) {
return bin_data_->Split(max_bin, default_bin, most_freq_bin,
missing_type, default_left, *threshold,
data_indices, cnt, lte_indices, gt_indices);
} else {
return bin_data_->Split(min_bin, max_bin, default_bin, most_freq_bin,
missing_type, default_left, *threshold,
data_indices, cnt, lte_indices, gt_indices);
}
} else {
if (num_feature_ == 1) {
return bin_data_->SplitCategorical(max_bin, most_freq_bin, threshold,
num_threshold, data_indices, cnt,
lte_indices, gt_indices);
} else {
return bin_data_->SplitCategorical(
min_bin, max_bin, most_freq_bin, threshold, num_threshold,
data_indices, cnt, lte_indices, gt_indices);
}
}
} else {
int addi = bin_mappers_[sub_feature]->GetMostFreqBin() == 0 ? 0 : 1;
uint32_t max_bin = bin_mappers_[sub_feature]->num_bin() - 1 + addi;
if (bin_mappers_[sub_feature]->bin_type() == BinType::NumericalBin) {
auto missing_type = bin_mappers_[sub_feature]->missing_type();
return multi_bin_data_[sub_feature]->Split(
max_bin, default_bin, most_freq_bin, missing_type, default_left,
*threshold, data_indices, cnt, lte_indices, gt_indices);
} else {
return multi_bin_data_[sub_feature]->SplitCategorical(
max_bin, most_freq_bin, threshold, num_threshold, data_indices, cnt,
lte_indices, gt_indices);
}
}
}
/*!
* \brief From bin to feature value
* \param bin
* \return FeatureGroup value of this bin
*/
inline double BinToValue(int sub_feature_idx, uint32_t bin) const {
return bin_mappers_[sub_feature_idx]->BinToValue(bin);
}
/*!
* \brief Save binary data to file
* \param file File want to write
*/
void SaveBinaryToFile(const VirtualFileWriter* writer) const {
writer->Write(&is_multi_val_, sizeof(is_multi_val_));
writer->Write(&is_sparse_, sizeof(is_sparse_));
writer->Write(&num_feature_, sizeof(num_feature_));
for (int i = 0; i < num_feature_; ++i) {
bin_mappers_[i]->SaveBinaryToFile(writer);
}
if (is_multi_val_) {
for (int i = 0; i < num_feature_; ++i) {
multi_bin_data_[i]->SaveBinaryToFile(writer);
}
} else {
bin_data_->SaveBinaryToFile(writer);
}
}
/*!
* \brief Get sizes in byte of this object
*/
size_t SizesInByte() const {
size_t ret = sizeof(is_multi_val_) + sizeof(is_sparse_) + sizeof(num_feature_);
for (int i = 0; i < num_feature_; ++i) {
ret += bin_mappers_[i]->SizesInByte();
}
if (!is_multi_val_) {
ret += bin_data_->SizesInByte();
} else {
for (int i = 0; i < num_feature_; ++i) {
ret += multi_bin_data_[i]->SizesInByte();
}
}
return ret;
}
/*! \brief Disable copy */
FeatureGroup& operator=(const FeatureGroup&) = delete;
/*! \brief Deep copy */
FeatureGroup(const FeatureGroup& other) {
num_feature_ = other.num_feature_;
is_multi_val_ = other.is_multi_val_;
is_sparse_ = other.is_sparse_;
num_total_bin_ = other.num_total_bin_;
bin_offsets_ = other.bin_offsets_;
bin_mappers_.reserve(other.bin_mappers_.size());
for (auto& bin_mapper : other.bin_mappers_) {
bin_mappers_.emplace_back(new BinMapper(*bin_mapper));
}
if (!is_multi_val_) {
bin_data_.reset(other.bin_data_->Clone());
} else {
multi_bin_data_.clear();
for (int i = 0; i < num_feature_; ++i) {
multi_bin_data_.emplace_back(other.multi_bin_data_[i]->Clone());
}
}
}
private:
void CreateBinData(int num_data, bool is_multi_val, bool force_dense, bool force_sparse) {
if (is_multi_val) {
multi_bin_data_.clear();
for (int i = 0; i < num_feature_; ++i) {
int addi = bin_mappers_[i]->GetMostFreqBin() == 0 ? 0 : 1;
if (bin_mappers_[i]->sparse_rate() >= kSparseThreshold) {
multi_bin_data_.emplace_back(Bin::CreateSparseBin(
num_data, bin_mappers_[i]->num_bin() + addi));
} else {
multi_bin_data_.emplace_back(
Bin::CreateDenseBin(num_data, bin_mappers_[i]->num_bin() + addi));
}
}
is_multi_val_ = true;
} else {
if (force_sparse || (!force_dense && num_feature_ == 1 &&
bin_mappers_[0]->sparse_rate() >= kSparseThreshold)) {
is_sparse_ = true;
bin_data_.reset(Bin::CreateSparseBin(num_data, num_total_bin_));
} else {
is_sparse_ = false;
bin_data_.reset(Bin::CreateDenseBin(num_data, num_total_bin_));
}
is_multi_val_ = false;
}
}
/*! \brief Number of features */
int num_feature_;
/*! \brief Bin mapper for sub features */
std::vector<std::unique_ptr<BinMapper>> bin_mappers_;
/*! \brief Bin offsets for sub features */
std::vector<uint32_t> bin_offsets_;
/*! \brief Bin data of this feature */
std::unique_ptr<Bin> bin_data_;
std::vector<std::unique_ptr<Bin>> multi_bin_data_;
/*! \brief True if this feature is sparse */
bool is_multi_val_;
bool is_sparse_;
int num_total_bin_;
};
} // namespace LightGBM
#endif // LIGHTGBM_FEATURE_GROUP_H_
|
main.c | #include <omp.h>
#include <stdio.h>
#include <stdlib.h>
int main(int argc, const char *argv[])
{
int i;
double x;
double pi;
long steps = 1000000000;
if (argc > 1)
{
steps = atoi(argv[1]);
}
else {
printf("Use: %s [puntos]\n", argv[0]);
}
double step = 1.0 / (double)steps;
double sum = 0.0;
double start = omp_get_wtime();
#pragma omp parallel for reduction(+ : sum) private(x, i)
for (i = 0; i < steps; i++)
{
x = (i + 0.5) * step;
sum += 4.0 / (1.0 + x * x);
}
pi = step * sum;
double delta = omp_get_wtime() - start;
printf("PI = %.16g calculado en %.4g segundos con %ld puntos\n", pi, delta, steps);
} |
distort.c | /*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% DDDD IIIII SSSSS TTTTT OOO RRRR TTTTT %
% D D I SS T O O R R T %
% D D I SSS T O O RRRR T %
% D D I SS T O O R R T %
% DDDD IIIII SSSSS T OOO R R T %
% %
% %
% MagickCore Image Distortion Methods %
% %
% Software Design %
% Cristy %
% Anthony Thyssen %
% June 2007 %
% %
% %
% Copyright 1999-2021 ImageMagick Studio LLC, a non-profit organization %
% dedicated to making software imaging solutions freely available. %
% %
% You may not use this file except in compliance with the License. You may %
% obtain a copy of the License at %
% %
% https://imagemagick.org/script/license.php %
% %
% Unless required by applicable law or agreed to in writing, software %
% distributed under the License is distributed on an "AS IS" BASIS, %
% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. %
% See the License for the specific language governing permissions and %
% limitations under the License. %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
%
*/
/*
Include declarations.
*/
#include "MagickCore/studio.h"
#include "MagickCore/artifact.h"
#include "MagickCore/cache.h"
#include "MagickCore/cache-view.h"
#include "MagickCore/channel.h"
#include "MagickCore/colorspace-private.h"
#include "MagickCore/composite-private.h"
#include "MagickCore/distort.h"
#include "MagickCore/exception.h"
#include "MagickCore/exception-private.h"
#include "MagickCore/gem.h"
#include "MagickCore/image.h"
#include "MagickCore/linked-list.h"
#include "MagickCore/list.h"
#include "MagickCore/matrix.h"
#include "MagickCore/matrix-private.h"
#include "MagickCore/memory_.h"
#include "MagickCore/monitor-private.h"
#include "MagickCore/option.h"
#include "MagickCore/pixel.h"
#include "MagickCore/pixel-accessor.h"
#include "MagickCore/pixel-private.h"
#include "MagickCore/resample.h"
#include "MagickCore/resample-private.h"
#include "MagickCore/registry.h"
#include "MagickCore/resource_.h"
#include "MagickCore/semaphore.h"
#include "MagickCore/shear.h"
#include "MagickCore/string_.h"
#include "MagickCore/string-private.h"
#include "MagickCore/thread-private.h"
#include "MagickCore/token.h"
#include "MagickCore/transform.h"
/*
Numerous internal routines for image distortions.
*/
static inline void AffineArgsToCoefficients(double *affine)
{
/* map external sx,ry,rx,sy,tx,ty to internal c0,c2,c4,c1,c3,c5 */
double tmp[4]; /* note indexes 0 and 5 remain unchanged */
tmp[0]=affine[1]; tmp[1]=affine[2]; tmp[2]=affine[3]; tmp[3]=affine[4];
affine[3]=tmp[0]; affine[1]=tmp[1]; affine[4]=tmp[2]; affine[2]=tmp[3];
}
static inline void CoefficientsToAffineArgs(double *coeff)
{
/* map internal c0,c1,c2,c3,c4,c5 to external sx,ry,rx,sy,tx,ty */
double tmp[4]; /* note indexes 0 and 5 remain unchanged */
tmp[0]=coeff[3]; tmp[1]=coeff[1]; tmp[2]=coeff[4]; tmp[3]=coeff[2];
coeff[1]=tmp[0]; coeff[2]=tmp[1]; coeff[3]=tmp[2]; coeff[4]=tmp[3];
}
static void InvertAffineCoefficients(const double *coeff,double *inverse)
{
/* From "Digital Image Warping" by George Wolberg, page 50 */
double determinant;
determinant=PerceptibleReciprocal(coeff[0]*coeff[4]-coeff[1]*coeff[3]);
inverse[0]=determinant*coeff[4];
inverse[1]=determinant*(-coeff[1]);
inverse[2]=determinant*(coeff[1]*coeff[5]-coeff[2]*coeff[4]);
inverse[3]=determinant*(-coeff[3]);
inverse[4]=determinant*coeff[0];
inverse[5]=determinant*(coeff[2]*coeff[3]-coeff[0]*coeff[5]);
}
static void InvertPerspectiveCoefficients(const double *coeff,
double *inverse)
{
/* From "Digital Image Warping" by George Wolberg, page 53 */
double determinant;
determinant=PerceptibleReciprocal(coeff[0]*coeff[4]-coeff[3]*coeff[1]);
inverse[0]=determinant*(coeff[4]-coeff[7]*coeff[5]);
inverse[1]=determinant*(coeff[7]*coeff[2]-coeff[1]);
inverse[2]=determinant*(coeff[1]*coeff[5]-coeff[4]*coeff[2]);
inverse[3]=determinant*(coeff[6]*coeff[5]-coeff[3]);
inverse[4]=determinant*(coeff[0]-coeff[6]*coeff[2]);
inverse[5]=determinant*(coeff[3]*coeff[2]-coeff[0]*coeff[5]);
inverse[6]=determinant*(coeff[3]*coeff[7]-coeff[6]*coeff[4]);
inverse[7]=determinant*(coeff[6]*coeff[1]-coeff[0]*coeff[7]);
}
/*
* Polynomial Term Defining Functions
*
* Order must either be an integer, or 1.5 to produce
* the 2 number_valuesal polynomial function...
* affine 1 (3) u = c0 + c1*x + c2*y
* bilinear 1.5 (4) u = '' + c3*x*y
* quadratic 2 (6) u = '' + c4*x*x + c5*y*y
* cubic 3 (10) u = '' + c6*x^3 + c7*x*x*y + c8*x*y*y + c9*y^3
* quartic 4 (15) u = '' + c10*x^4 + ... + c14*y^4
* quintic 5 (21) u = '' + c15*x^5 + ... + c20*y^5
* number in parenthesis minimum number of points needed.
* Anything beyond quintic, has not been implemented until
* a more automated way of determining terms is found.
* Note the slight re-ordering of the terms for a quadratic polynomial
* which is to allow the use of a bi-linear (order=1.5) polynomial.
* All the later polynomials are ordered simply from x^N to y^N
*/
static size_t poly_number_terms(double order)
{
/* Return the number of terms for a 2d polynomial */
if ( order < 1 || order > 5 ||
( order != floor(order) && (order-1.5) > MagickEpsilon) )
return 0; /* invalid polynomial order */
return((size_t) floor((order+1)*(order+2)/2));
}
static double poly_basis_fn(ssize_t n, double x, double y)
{
/* Return the result for this polynomial term */
switch(n) {
case 0: return( 1.0 ); /* constant */
case 1: return( x );
case 2: return( y ); /* affine order = 1 terms = 3 */
case 3: return( x*y ); /* bilinear order = 1.5 terms = 4 */
case 4: return( x*x );
case 5: return( y*y ); /* quadratic order = 2 terms = 6 */
case 6: return( x*x*x );
case 7: return( x*x*y );
case 8: return( x*y*y );
case 9: return( y*y*y ); /* cubic order = 3 terms = 10 */
case 10: return( x*x*x*x );
case 11: return( x*x*x*y );
case 12: return( x*x*y*y );
case 13: return( x*y*y*y );
case 14: return( y*y*y*y ); /* quartic order = 4 terms = 15 */
case 15: return( x*x*x*x*x );
case 16: return( x*x*x*x*y );
case 17: return( x*x*x*y*y );
case 18: return( x*x*y*y*y );
case 19: return( x*y*y*y*y );
case 20: return( y*y*y*y*y ); /* quintic order = 5 terms = 21 */
}
return( 0 ); /* should never happen */
}
static const char *poly_basis_str(ssize_t n)
{
/* return the result for this polynomial term */
switch(n) {
case 0: return(""); /* constant */
case 1: return("*ii");
case 2: return("*jj"); /* affine order = 1 terms = 3 */
case 3: return("*ii*jj"); /* bilinear order = 1.5 terms = 4 */
case 4: return("*ii*ii");
case 5: return("*jj*jj"); /* quadratic order = 2 terms = 6 */
case 6: return("*ii*ii*ii");
case 7: return("*ii*ii*jj");
case 8: return("*ii*jj*jj");
case 9: return("*jj*jj*jj"); /* cubic order = 3 terms = 10 */
case 10: return("*ii*ii*ii*ii");
case 11: return("*ii*ii*ii*jj");
case 12: return("*ii*ii*jj*jj");
case 13: return("*ii*jj*jj*jj");
case 14: return("*jj*jj*jj*jj"); /* quartic order = 4 terms = 15 */
case 15: return("*ii*ii*ii*ii*ii");
case 16: return("*ii*ii*ii*ii*jj");
case 17: return("*ii*ii*ii*jj*jj");
case 18: return("*ii*ii*jj*jj*jj");
case 19: return("*ii*jj*jj*jj*jj");
case 20: return("*jj*jj*jj*jj*jj"); /* quintic order = 5 terms = 21 */
}
return( "UNKNOWN" ); /* should never happen */
}
static double poly_basis_dx(ssize_t n, double x, double y)
{
/* polynomial term for x derivative */
switch(n) {
case 0: return( 0.0 ); /* constant */
case 1: return( 1.0 );
case 2: return( 0.0 ); /* affine order = 1 terms = 3 */
case 3: return( y ); /* bilinear order = 1.5 terms = 4 */
case 4: return( x );
case 5: return( 0.0 ); /* quadratic order = 2 terms = 6 */
case 6: return( x*x );
case 7: return( x*y );
case 8: return( y*y );
case 9: return( 0.0 ); /* cubic order = 3 terms = 10 */
case 10: return( x*x*x );
case 11: return( x*x*y );
case 12: return( x*y*y );
case 13: return( y*y*y );
case 14: return( 0.0 ); /* quartic order = 4 terms = 15 */
case 15: return( x*x*x*x );
case 16: return( x*x*x*y );
case 17: return( x*x*y*y );
case 18: return( x*y*y*y );
case 19: return( y*y*y*y );
case 20: return( 0.0 ); /* quintic order = 5 terms = 21 */
}
return( 0.0 ); /* should never happen */
}
static double poly_basis_dy(ssize_t n, double x, double y)
{
/* polynomial term for y derivative */
switch(n) {
case 0: return( 0.0 ); /* constant */
case 1: return( 0.0 );
case 2: return( 1.0 ); /* affine order = 1 terms = 3 */
case 3: return( x ); /* bilinear order = 1.5 terms = 4 */
case 4: return( 0.0 );
case 5: return( y ); /* quadratic order = 2 terms = 6 */
default: return( poly_basis_dx(n-1,x,y) ); /* weird but true */
}
/* NOTE: the only reason that last is not true for 'quadratic'
is due to the re-arrangement of terms to allow for 'bilinear'
*/
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% A f f i n e T r a n s f o r m I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% AffineTransformImage() transforms an image as dictated by the affine matrix.
% It allocates the memory necessary for the new Image structure and returns
% a pointer to the new image.
%
% The format of the AffineTransformImage method is:
%
% Image *AffineTransformImage(const Image *image,
% AffineMatrix *affine_matrix,ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o affine_matrix: the affine matrix.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport Image *AffineTransformImage(const Image *image,
const AffineMatrix *affine_matrix,ExceptionInfo *exception)
{
double
distort[6];
Image
*deskew_image;
/*
Affine transform image.
*/
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
assert(affine_matrix != (AffineMatrix *) NULL);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickCoreSignature);
distort[0]=affine_matrix->sx;
distort[1]=affine_matrix->rx;
distort[2]=affine_matrix->ry;
distort[3]=affine_matrix->sy;
distort[4]=affine_matrix->tx;
distort[5]=affine_matrix->ty;
deskew_image=DistortImage(image,AffineProjectionDistortion,6,distort,
MagickTrue,exception);
return(deskew_image);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
+ G e n e r a t e C o e f f i c i e n t s %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% GenerateCoefficients() takes user provided input arguments and generates
% the coefficients, needed to apply the specific distortion for either
% distorting images (generally using control points) or generating a color
% gradient from sparsely separated color points.
%
% The format of the GenerateCoefficients() method is:
%
% Image *GenerateCoefficients(const Image *image,DistortMethod method,
% const size_t number_arguments,const double *arguments,
% size_t number_values, ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image to be distorted.
%
% o method: the method of image distortion/ sparse gradient
%
% o number_arguments: the number of arguments given.
%
% o arguments: the arguments for this distortion method.
%
% o number_values: the style and format of given control points, (caller type)
% 0: 2 dimensional mapping of control points (Distort)
% Format: u,v,x,y where u,v is the 'source' of the
% the color to be plotted, for DistortImage()
% N: Interpolation of control points with N values (usally r,g,b)
% Format: x,y,r,g,b mapping x,y to color values r,g,b
% IN future, variable number of values may be given (1 to N)
%
% o exception: return any errors or warnings in this structure
%
% Note that the returned array of double values must be freed by the
% calling method using RelinquishMagickMemory(). This however may change in
% the future to require a more 'method' specific method.
%
% Because of this this method should not be classed as stable or used
% outside other MagickCore library methods.
*/
static inline double MagickRound(double x)
{
/*
Round the fraction to nearest integer.
*/
if ((x-floor(x)) < (ceil(x)-x))
return(floor(x));
return(ceil(x));
}
static double *GenerateCoefficients(const Image *image,
DistortMethod *method,const size_t number_arguments,const double *arguments,
size_t number_values,ExceptionInfo *exception)
{
double
*coeff;
size_t
i;
size_t
number_coefficients, /* number of coefficients to return (array size) */
cp_size, /* number floating point numbers per control point */
cp_x,cp_y, /* the x,y indexes for control point */
cp_values; /* index of values for this control point */
/* number_values Number of values given per control point */
if ( number_values == 0 ) {
/* Image distortion using control points (or other distortion)
That is generate a mapping so that x,y->u,v given u,v,x,y
*/
number_values = 2; /* special case: two values of u,v */
cp_values = 0; /* the values i,j are BEFORE the destination CP x,y */
cp_x = 2; /* location of x,y in input control values */
cp_y = 3;
/* NOTE: cp_values, also used for later 'reverse map distort' tests */
}
else {
cp_x = 0; /* location of x,y in input control values */
cp_y = 1;
cp_values = 2; /* and the other values are after x,y */
/* Typically in this case the values are R,G,B color values */
}
cp_size = number_values+2; /* each CP defintion involves this many numbers */
/* If not enough control point pairs are found for specific distortions
fall back to Affine distortion (allowing 0 to 3 point pairs)
*/
if ( number_arguments < 4*cp_size &&
( *method == BilinearForwardDistortion
|| *method == BilinearReverseDistortion
|| *method == PerspectiveDistortion
) )
*method = AffineDistortion;
number_coefficients=0;
switch (*method) {
case AffineDistortion:
case RigidAffineDistortion:
/* also BarycentricColorInterpolate: */
number_coefficients=3*number_values;
break;
case PolynomialDistortion:
/* number of coefficents depend on the given polynomal 'order' */
i = poly_number_terms(arguments[0]);
number_coefficients = 2 + i*number_values;
if ( i == 0 ) {
(void) ThrowMagickException(exception,GetMagickModule(),OptionError,
"InvalidArgument","%s : '%s'","Polynomial",
"Invalid order, should be interger 1 to 5, or 1.5");
return((double *) NULL);
}
if ( number_arguments < 1+i*cp_size ) {
(void) ThrowMagickException(exception,GetMagickModule(),OptionError,
"InvalidArgument", "%s : 'require at least %.20g CPs'",
"Polynomial", (double) i);
return((double *) NULL);
}
break;
case BilinearReverseDistortion:
number_coefficients=4*number_values;
break;
/*
The rest are constants as they are only used for image distorts
*/
case BilinearForwardDistortion:
number_coefficients=10; /* 2*4 coeff plus 2 constants */
cp_x = 0; /* Reverse src/dest coords for forward mapping */
cp_y = 1;
cp_values = 2;
break;
#if 0
case QuadraterialDistortion:
number_coefficients=19; /* BilinearForward + BilinearReverse */
#endif
break;
case ShepardsDistortion:
number_coefficients=1; /* The power factor to use */
break;
case ArcDistortion:
number_coefficients=5;
break;
case ScaleRotateTranslateDistortion:
case AffineProjectionDistortion:
case Plane2CylinderDistortion:
case Cylinder2PlaneDistortion:
number_coefficients=6;
break;
case PolarDistortion:
case DePolarDistortion:
number_coefficients=8;
break;
case PerspectiveDistortion:
case PerspectiveProjectionDistortion:
number_coefficients=9;
break;
case BarrelDistortion:
case BarrelInverseDistortion:
number_coefficients=10;
break;
default:
perror("unknown method given"); /* just fail assertion */
}
/* allocate the array of coefficients needed */
coeff=(double *) AcquireQuantumMemory(number_coefficients,sizeof(*coeff));
if (coeff == (double *) NULL)
{
(void) ThrowMagickException(exception,GetMagickModule(),
ResourceLimitError,"MemoryAllocationFailed","%s",
"GenerateCoefficients");
return((double *) NULL);
}
/* zero out coefficients array */
for (i=0; i < number_coefficients; i++)
coeff[i] = 0.0;
switch (*method)
{
case AffineDistortion:
{
/* Affine Distortion
v = c0*x + c1*y + c2
for each 'value' given
Input Arguments are sets of control points...
For Distort Images u,v, x,y ...
For Sparse Gradients x,y, r,g,b ...
*/
if ( number_arguments%cp_size != 0 ||
number_arguments < cp_size ) {
(void) ThrowMagickException(exception,GetMagickModule(),OptionError,
"InvalidArgument", "%s : 'require at least %.20g CPs'",
"Affine", 1.0);
coeff=(double *) RelinquishMagickMemory(coeff);
return((double *) NULL);
}
/* handle special cases of not enough arguments */
if ( number_arguments == cp_size ) {
/* Only 1 CP Set Given */
if ( cp_values == 0 ) {
/* image distortion - translate the image */
coeff[0] = 1.0;
coeff[2] = arguments[0] - arguments[2];
coeff[4] = 1.0;
coeff[5] = arguments[1] - arguments[3];
}
else {
/* sparse gradient - use the values directly */
for (i=0; i<number_values; i++)
coeff[i*3+2] = arguments[cp_values+i];
}
}
else {
/* 2 or more points (usally 3) given.
Solve a least squares simultaneous equation for coefficients.
*/
double
**matrix,
**vectors,
terms[3];
MagickBooleanType
status;
/* create matrix, and a fake vectors matrix */
matrix=AcquireMagickMatrix(3UL,3UL);
vectors=(double **) AcquireQuantumMemory(number_values,
sizeof(*vectors));
if (matrix == (double **) NULL || vectors == (double **) NULL)
{
matrix = RelinquishMagickMatrix(matrix, 3UL);
vectors = (double **) RelinquishMagickMemory(vectors);
coeff = (double *) RelinquishMagickMemory(coeff);
(void) ThrowMagickException(exception,GetMagickModule(),
ResourceLimitError,"MemoryAllocationFailed",
"%s", "DistortCoefficients");
return((double *) NULL);
}
/* fake a number_values x3 vectors matrix from coefficients array */
for (i=0; i < number_values; i++)
vectors[i] = &(coeff[i*3]);
/* Add given control point pairs for least squares solving */
for (i=0; i < number_arguments; i+=cp_size) {
terms[0] = arguments[i+cp_x]; /* x */
terms[1] = arguments[i+cp_y]; /* y */
terms[2] = 1; /* 1 */
LeastSquaresAddTerms(matrix,vectors,terms,
&(arguments[i+cp_values]),3UL,number_values);
}
if ( number_arguments == 2*cp_size ) {
/* Only two pairs were given, but we need 3 to solve the affine.
Fake extra coordinates by rotating p1 around p0 by 90 degrees.
x2 = x0 - (y1-y0) y2 = y0 + (x1-x0)
*/
terms[0] = arguments[cp_x]
- ( arguments[cp_size+cp_y] - arguments[cp_y] ); /* x2 */
terms[1] = arguments[cp_y] +
+ ( arguments[cp_size+cp_x] - arguments[cp_x] ); /* y2 */
terms[2] = 1; /* 1 */
if ( cp_values == 0 ) {
/* Image Distortion - rotate the u,v coordients too */
double
uv2[2];
uv2[0] = arguments[0] - arguments[5] + arguments[1]; /* u2 */
uv2[1] = arguments[1] + arguments[4] - arguments[0]; /* v2 */
LeastSquaresAddTerms(matrix,vectors,terms,uv2,3UL,2UL);
}
else {
/* Sparse Gradient - use values of p0 for linear gradient */
LeastSquaresAddTerms(matrix,vectors,terms,
&(arguments[cp_values]),3UL,number_values);
}
}
/* Solve for LeastSquares Coefficients */
status=GaussJordanElimination(matrix,vectors,3UL,number_values);
matrix = RelinquishMagickMatrix(matrix, 3UL);
vectors = (double **) RelinquishMagickMemory(vectors);
if ( status == MagickFalse ) {
coeff = (double *) RelinquishMagickMemory(coeff);
(void) ThrowMagickException(exception,GetMagickModule(),OptionError,
"InvalidArgument","%s : 'Unsolvable Matrix'",
CommandOptionToMnemonic(MagickDistortOptions, *method) );
return((double *) NULL);
}
}
return(coeff);
}
case RigidAffineDistortion:
{
double
inverse[6],
**matrix,
terms[5],
*vectors[1];
MagickBooleanType
status;
/*
Rigid affine (also known as a Euclidean transform), restricts affine
coefficients to 4 (S, R, Tx, Ty) with Sy=Sx and Ry = -Rx so that one has
only scale, rotation and translation. No skew.
*/
if (((number_arguments % cp_size) != 0) || (number_arguments < cp_size))
{
(void) ThrowMagickException(exception,GetMagickModule(),OptionError,
"InvalidArgument", "%s : 'require at least %.20g CPs'",
CommandOptionToMnemonic(MagickDistortOptions,*method),2.0);
coeff=(double *) RelinquishMagickMemory(coeff);
return((double *) NULL);
}
/*
Rigid affine requires a 4x4 least-squares matrix (zeroed).
*/
matrix=AcquireMagickMatrix(4UL,4UL);
if (matrix == (double **) NULL)
{
coeff=(double *) RelinquishMagickMemory(coeff);
(void) ThrowMagickException(exception,GetMagickModule(),
ResourceLimitError,"MemoryAllocationFailed","%s",
CommandOptionToMnemonic(MagickDistortOptions,*method));
return((double *) NULL);
}
/*
Add control points for least squares solving.
*/
vectors[0]=(&(coeff[0]));
for (i=0; i < number_arguments; i+=4)
{
terms[0]=arguments[i+0];
terms[1]=(-arguments[i+1]);
terms[2]=1.0;
terms[3]=0.0;
LeastSquaresAddTerms(matrix,vectors,terms,&(arguments[i+2]),4UL,1UL);
terms[0]=arguments[i+1];
terms[1]=arguments[i+0];
terms[2]=0.0;
terms[3]=1.0;
LeastSquaresAddTerms(matrix,vectors,terms,&(arguments[i+3]),4UL,1UL);
}
/*
Solve for least-squares coefficients.
*/
status=GaussJordanElimination(matrix,vectors,4UL,1UL);
matrix=RelinquishMagickMatrix(matrix,4UL);
if (status == MagickFalse)
{
coeff=(double *) RelinquishMagickMemory(coeff);
(void) ThrowMagickException(exception,GetMagickModule(),OptionError,
"InvalidArgument","%s : 'Unsolvable Matrix'",
CommandOptionToMnemonic(MagickDistortOptions,*method));
return((double *) NULL);
}
/*
Convert (S, R, Tx, Ty) to an affine projection.
*/
inverse[0]=coeff[0];
inverse[1]=coeff[1];
inverse[2]=(-coeff[1]);
inverse[3]=coeff[0];
inverse[4]=coeff[2];
inverse[5]=coeff[3];
AffineArgsToCoefficients(inverse);
InvertAffineCoefficients(inverse,coeff);
*method=AffineDistortion;
return(coeff);
}
case AffineProjectionDistortion:
{
/*
Arguments: Affine Matrix (forward mapping)
Arguments sx, rx, ry, sy, tx, ty
Where u = sx*x + ry*y + tx
v = rx*x + sy*y + ty
Returns coefficients (in there inverse form) ordered as...
sx ry tx rx sy ty
AffineProjection Distortion Notes...
+ Will only work with a 2 number_values for Image Distortion
+ Can not be used for generating a sparse gradient (interpolation)
*/
double inverse[8];
if (number_arguments != 6) {
coeff = (double *) RelinquishMagickMemory(coeff);
(void) ThrowMagickException(exception,GetMagickModule(),OptionError,
"InvalidArgument","%s : 'Needs 6 coeff values'",
CommandOptionToMnemonic(MagickDistortOptions, *method) );
return((double *) NULL);
}
/* FUTURE: trap test for sx*sy-rx*ry == 0 (determinant = 0, no inverse) */
for(i=0; i<6UL; i++ )
inverse[i] = arguments[i];
AffineArgsToCoefficients(inverse); /* map into coefficents */
InvertAffineCoefficients(inverse, coeff); /* invert */
*method = AffineDistortion;
return(coeff);
}
case ScaleRotateTranslateDistortion:
{
/* Scale, Rotate and Translate Distortion
An alternative Affine Distortion
Argument options, by number of arguments given:
7: x,y, sx,sy, a, nx,ny
6: x,y, s, a, nx,ny
5: x,y, sx,sy, a
4: x,y, s, a
3: x,y, a
2: s, a
1: a
Where actions are (in order of application)
x,y 'center' of transforms (default = image center)
sx,sy scale image by this amount (default = 1)
a angle of rotation (argument required)
nx,ny move 'center' here (default = x,y or no movement)
And convert to affine mapping coefficients
ScaleRotateTranslate Distortion Notes...
+ Does not use a set of CPs in any normal way
+ Will only work with a 2 number_valuesal Image Distortion
+ Cannot be used for generating a sparse gradient (interpolation)
*/
double
cosine, sine,
x,y,sx,sy,a,nx,ny;
/* set default center, and default scale */
x = nx = (double)(image->columns)/2.0 + (double)image->page.x;
y = ny = (double)(image->rows)/2.0 + (double)image->page.y;
sx = sy = 1.0;
switch ( number_arguments ) {
case 0:
coeff = (double *) RelinquishMagickMemory(coeff);
(void) ThrowMagickException(exception,GetMagickModule(),OptionError,
"InvalidArgument","%s : 'Needs at least 1 argument'",
CommandOptionToMnemonic(MagickDistortOptions, *method) );
return((double *) NULL);
case 1:
a = arguments[0];
break;
case 2:
sx = sy = arguments[0];
a = arguments[1];
break;
default:
x = nx = arguments[0];
y = ny = arguments[1];
switch ( number_arguments ) {
case 3:
a = arguments[2];
break;
case 4:
sx = sy = arguments[2];
a = arguments[3];
break;
case 5:
sx = arguments[2];
sy = arguments[3];
a = arguments[4];
break;
case 6:
sx = sy = arguments[2];
a = arguments[3];
nx = arguments[4];
ny = arguments[5];
break;
case 7:
sx = arguments[2];
sy = arguments[3];
a = arguments[4];
nx = arguments[5];
ny = arguments[6];
break;
default:
coeff = (double *) RelinquishMagickMemory(coeff);
(void) ThrowMagickException(exception,GetMagickModule(),OptionError,
"InvalidArgument","%s : 'Too Many Arguments (7 or less)'",
CommandOptionToMnemonic(MagickDistortOptions, *method) );
return((double *) NULL);
}
break;
}
/* Trap if sx or sy == 0 -- image is scaled out of existance! */
if ( fabs(sx) < MagickEpsilon || fabs(sy) < MagickEpsilon ) {
coeff = (double *) RelinquishMagickMemory(coeff);
(void) ThrowMagickException(exception,GetMagickModule(),OptionError,
"InvalidArgument","%s : 'Zero Scale Given'",
CommandOptionToMnemonic(MagickDistortOptions, *method) );
return((double *) NULL);
}
/* Save the given arguments as an affine distortion */
a=DegreesToRadians(a); cosine=cos(a); sine=sin(a);
*method = AffineDistortion;
coeff[0]=cosine/sx;
coeff[1]=sine/sx;
coeff[2]=x-nx*coeff[0]-ny*coeff[1];
coeff[3]=(-sine)/sy;
coeff[4]=cosine/sy;
coeff[5]=y-nx*coeff[3]-ny*coeff[4];
return(coeff);
}
case PerspectiveDistortion:
{ /*
Perspective Distortion (a ratio of affine distortions)
p(x,y) c0*x + c1*y + c2
u = ------ = ------------------
r(x,y) c6*x + c7*y + 1
q(x,y) c3*x + c4*y + c5
v = ------ = ------------------
r(x,y) c6*x + c7*y + 1
c8 = Sign of 'r', or the denominator affine, for the actual image.
This determines what part of the distorted image is 'ground'
side of the horizon, the other part is 'sky' or invalid.
Valid values are +1.0 or -1.0 only.
Input Arguments are sets of control points...
For Distort Images u,v, x,y ...
For Sparse Gradients x,y, r,g,b ...
Perspective Distortion Notes...
+ Can be thought of as ratio of 3 affine transformations
+ Not separatable: r() or c6 and c7 are used by both equations
+ All 8 coefficients must be determined simultaniously
+ Will only work with a 2 number_valuesal Image Distortion
+ Can not be used for generating a sparse gradient (interpolation)
+ It is not linear, but is simple to generate an inverse
+ All lines within an image remain lines.
+ but distances between points may vary.
*/
double
**matrix,
*vectors[1],
terms[8];
size_t
cp_u = cp_values,
cp_v = cp_values+1;
MagickBooleanType
status;
if ( number_arguments%cp_size != 0 ||
number_arguments < cp_size*4 ) {
(void) ThrowMagickException(exception,GetMagickModule(),OptionError,
"InvalidArgument", "%s : 'require at least %.20g CPs'",
CommandOptionToMnemonic(MagickDistortOptions, *method), 4.0);
coeff=(double *) RelinquishMagickMemory(coeff);
return((double *) NULL);
}
/* fake 1x8 vectors matrix directly using the coefficients array */
vectors[0] = &(coeff[0]);
/* 8x8 least-squares matrix (zeroed) */
matrix = AcquireMagickMatrix(8UL,8UL);
if (matrix == (double **) NULL) {
coeff=(double *) RelinquishMagickMemory(coeff);
(void) ThrowMagickException(exception,GetMagickModule(),
ResourceLimitError,"MemoryAllocationFailed",
"%s", "DistortCoefficients");
return((double *) NULL);
}
/* Add control points for least squares solving */
for (i=0; i < number_arguments; i+=4) {
terms[0]=arguments[i+cp_x]; /* c0*x */
terms[1]=arguments[i+cp_y]; /* c1*y */
terms[2]=1.0; /* c2*1 */
terms[3]=0.0;
terms[4]=0.0;
terms[5]=0.0;
terms[6]=-terms[0]*arguments[i+cp_u]; /* 1/(c6*x) */
terms[7]=-terms[1]*arguments[i+cp_u]; /* 1/(c7*y) */
LeastSquaresAddTerms(matrix,vectors,terms,&(arguments[i+cp_u]),
8UL,1UL);
terms[0]=0.0;
terms[1]=0.0;
terms[2]=0.0;
terms[3]=arguments[i+cp_x]; /* c3*x */
terms[4]=arguments[i+cp_y]; /* c4*y */
terms[5]=1.0; /* c5*1 */
terms[6]=-terms[3]*arguments[i+cp_v]; /* 1/(c6*x) */
terms[7]=-terms[4]*arguments[i+cp_v]; /* 1/(c7*y) */
LeastSquaresAddTerms(matrix,vectors,terms,&(arguments[i+cp_v]),
8UL,1UL);
}
/* Solve for LeastSquares Coefficients */
status=GaussJordanElimination(matrix,vectors,8UL,1UL);
matrix = RelinquishMagickMatrix(matrix, 8UL);
if ( status == MagickFalse ) {
coeff = (double *) RelinquishMagickMemory(coeff);
(void) ThrowMagickException(exception,GetMagickModule(),OptionError,
"InvalidArgument","%s : 'Unsolvable Matrix'",
CommandOptionToMnemonic(MagickDistortOptions, *method) );
return((double *) NULL);
}
/*
Calculate 9'th coefficient! The ground-sky determination.
What is sign of the 'ground' in r() denominator affine function?
Just use any valid image coordinate (first control point) in
destination for determination of what part of view is 'ground'.
*/
coeff[8] = coeff[6]*arguments[cp_x]
+ coeff[7]*arguments[cp_y] + 1.0;
coeff[8] = (coeff[8] < 0.0) ? -1.0 : +1.0;
return(coeff);
}
case PerspectiveProjectionDistortion:
{
/*
Arguments: Perspective Coefficents (forward mapping)
*/
if (number_arguments != 8) {
coeff = (double *) RelinquishMagickMemory(coeff);
(void) ThrowMagickException(exception,GetMagickModule(),OptionError,
"InvalidArgument", "%s : 'Needs 8 coefficient values'",
CommandOptionToMnemonic(MagickDistortOptions, *method));
return((double *) NULL);
}
/* FUTURE: trap test c0*c4-c3*c1 == 0 (determinate = 0, no inverse) */
InvertPerspectiveCoefficients(arguments, coeff);
/*
Calculate 9'th coefficient! The ground-sky determination.
What is sign of the 'ground' in r() denominator affine function?
Just use any valid image cocodinate in destination for determination.
For a forward mapped perspective the images 0,0 coord will map to
c2,c5 in the distorted image, so set the sign of denominator of that.
*/
coeff[8] = coeff[6]*arguments[2]
+ coeff[7]*arguments[5] + 1.0;
coeff[8] = (coeff[8] < 0.0) ? -1.0 : +1.0;
*method = PerspectiveDistortion;
return(coeff);
}
case BilinearForwardDistortion:
case BilinearReverseDistortion:
{
/* Bilinear Distortion (Forward mapping)
v = c0*x + c1*y + c2*x*y + c3;
for each 'value' given
This is actually a simple polynomial Distortion! The difference
however is when we need to reverse the above equation to generate a
BilinearForwardDistortion (see below).
Input Arguments are sets of control points...
For Distort Images u,v, x,y ...
For Sparse Gradients x,y, r,g,b ...
*/
double
**matrix,
**vectors,
terms[4];
MagickBooleanType
status;
/* check the number of arguments */
if ( number_arguments%cp_size != 0 ||
number_arguments < cp_size*4 ) {
(void) ThrowMagickException(exception,GetMagickModule(),OptionError,
"InvalidArgument", "%s : 'require at least %.20g CPs'",
CommandOptionToMnemonic(MagickDistortOptions, *method), 4.0);
coeff=(double *) RelinquishMagickMemory(coeff);
return((double *) NULL);
}
/* create matrix, and a fake vectors matrix */
matrix=AcquireMagickMatrix(4UL,4UL);
vectors=(double **) AcquireQuantumMemory(number_values,sizeof(*vectors));
if (matrix == (double **) NULL || vectors == (double **) NULL)
{
matrix = RelinquishMagickMatrix(matrix, 4UL);
vectors = (double **) RelinquishMagickMemory(vectors);
coeff = (double *) RelinquishMagickMemory(coeff);
(void) ThrowMagickException(exception,GetMagickModule(),
ResourceLimitError,"MemoryAllocationFailed",
"%s", "DistortCoefficients");
return((double *) NULL);
}
/* fake a number_values x4 vectors matrix from coefficients array */
for (i=0; i < number_values; i++)
vectors[i] = &(coeff[i*4]);
/* Add given control point pairs for least squares solving */
for (i=0; i < number_arguments; i+=cp_size) {
terms[0] = arguments[i+cp_x]; /* x */
terms[1] = arguments[i+cp_y]; /* y */
terms[2] = terms[0]*terms[1]; /* x*y */
terms[3] = 1; /* 1 */
LeastSquaresAddTerms(matrix,vectors,terms,
&(arguments[i+cp_values]),4UL,number_values);
}
/* Solve for LeastSquares Coefficients */
status=GaussJordanElimination(matrix,vectors,4UL,number_values);
matrix = RelinquishMagickMatrix(matrix, 4UL);
vectors = (double **) RelinquishMagickMemory(vectors);
if ( status == MagickFalse ) {
coeff = (double *) RelinquishMagickMemory(coeff);
(void) ThrowMagickException(exception,GetMagickModule(),OptionError,
"InvalidArgument","%s : 'Unsolvable Matrix'",
CommandOptionToMnemonic(MagickDistortOptions, *method) );
return((double *) NULL);
}
if ( *method == BilinearForwardDistortion ) {
/* Bilinear Forward Mapped Distortion
The above least-squares solved for coefficents but in the forward
direction, due to changes to indexing constants.
i = c0*x + c1*y + c2*x*y + c3;
j = c4*x + c5*y + c6*x*y + c7;
where i,j are in the destination image, NOT the source.
Reverse Pixel mapping however needs to use reverse of these
functions. It required a full page of algbra to work out the
reversed mapping formula, but resolves down to the following...
c8 = c0*c5-c1*c4;
c9 = 2*(c2*c5-c1*c6); // '2*a' in the quadratic formula
i = i - c3; j = j - c7;
b = c6*i - c2*j + c8; // So that a*y^2 + b*y + c == 0
c = c4*i - c0*j; // y = ( -b +- sqrt(bb - 4ac) ) / (2*a)
r = b*b - c9*(c+c);
if ( c9 != 0 )
y = ( -b + sqrt(r) ) / c9;
else
y = -c/b;
x = ( i - c1*y) / ( c1 - c2*y );
NB: if 'r' is negative there is no solution!
NB: the sign of the sqrt() should be negative if image becomes
flipped or flopped, or crosses over itself.
NB: techniqually coefficient c5 is not needed, anymore,
but kept for completness.
See Anthony Thyssen <A.Thyssen@griffith.edu.au>
or Fred Weinhaus <fmw@alink.net> for more details.
*/
coeff[8] = coeff[0]*coeff[5] - coeff[1]*coeff[4];
coeff[9] = 2*(coeff[2]*coeff[5] - coeff[1]*coeff[6]);
}
return(coeff);
}
#if 0
case QuadrilateralDistortion:
{
/* Map a Quadrilateral to a unit square using BilinearReverse
Then map that unit square back to the final Quadrilateral
using BilinearForward.
Input Arguments are sets of control points...
For Distort Images u,v, x,y ...
For Sparse Gradients x,y, r,g,b ...
*/
/* UNDER CONSTRUCTION */
return(coeff);
}
#endif
case PolynomialDistortion:
{
/* Polynomial Distortion
First two coefficents are used to hole global polynomal information
c0 = Order of the polynimial being created
c1 = number_of_terms in one polynomial equation
Rest of the coefficients map to the equations....
v = c0 + c1*x + c2*y + c3*x*y + c4*x^2 + c5*y^2 + c6*x^3 + ...
for each 'value' (number_values of them) given.
As such total coefficients = 2 + number_terms * number_values
Input Arguments are sets of control points...
For Distort Images order [u,v, x,y] ...
For Sparse Gradients order [x,y, r,g,b] ...
Polynomial Distortion Notes...
+ UNDER DEVELOPMENT -- Do not expect this to remain as is.
+ Currently polynomial is a reversed mapped distortion.
+ Order 1.5 is fudged to map into a bilinear distortion.
though it is not the same order as that distortion.
*/
double
**matrix,
**vectors,
*terms;
size_t
nterms; /* number of polynomial terms per number_values */
ssize_t
j;
MagickBooleanType
status;
/* first two coefficients hold polynomial order information */
coeff[0] = arguments[0];
coeff[1] = (double) poly_number_terms(arguments[0]);
nterms = (size_t) coeff[1];
/* create matrix, a fake vectors matrix, and least sqs terms */
matrix=AcquireMagickMatrix(nterms,nterms);
vectors=(double **) AcquireQuantumMemory(number_values,
sizeof(*vectors));
terms=(double *) AcquireQuantumMemory(nterms,sizeof(*terms));
if ((matrix == (double **) NULL) || (vectors == (double **) NULL) ||
(terms == (double *) NULL))
{
matrix = RelinquishMagickMatrix(matrix, nterms);
vectors = (double **) RelinquishMagickMemory(vectors);
terms = (double *) RelinquishMagickMemory(terms);
coeff = (double *) RelinquishMagickMemory(coeff);
(void) ThrowMagickException(exception,GetMagickModule(),
ResourceLimitError,"MemoryAllocationFailed",
"%s", "DistortCoefficients");
return((double *) NULL);
}
/* fake a number_values x3 vectors matrix from coefficients array */
for (i=0; i < number_values; i++)
vectors[i] = &(coeff[2+i*nterms]);
/* Add given control point pairs for least squares solving */
for (i=1; i < number_arguments; i+=cp_size) { /* NB: start = 1 not 0 */
for (j=0; j < (ssize_t) nterms; j++)
terms[j] = poly_basis_fn(j,arguments[i+cp_x],arguments[i+cp_y]);
LeastSquaresAddTerms(matrix,vectors,terms,
&(arguments[i+cp_values]),nterms,number_values);
}
terms = (double *) RelinquishMagickMemory(terms);
/* Solve for LeastSquares Coefficients */
status=GaussJordanElimination(matrix,vectors,nterms,number_values);
matrix = RelinquishMagickMatrix(matrix, nterms);
vectors = (double **) RelinquishMagickMemory(vectors);
if ( status == MagickFalse ) {
coeff = (double *) RelinquishMagickMemory(coeff);
(void) ThrowMagickException(exception,GetMagickModule(),OptionError,
"InvalidArgument","%s : 'Unsolvable Matrix'",
CommandOptionToMnemonic(MagickDistortOptions, *method) );
return((double *) NULL);
}
return(coeff);
}
case ArcDistortion:
{
/* Arc Distortion
Args: arc_width rotate top_edge_radius bottom_edge_radius
All but first argument are optional
arc_width The angle over which to arc the image side-to-side
rotate Angle to rotate image from vertical center
top_radius Set top edge of source image at this radius
bottom_radius Set bootom edge to this radius (radial scaling)
By default, if the radii arguments are nor provided the image radius
is calculated so the horizontal center-line is fits the given arc
without scaling.
The output image size is ALWAYS adjusted to contain the whole image,
and an offset is given to position image relative to the 0,0 point of
the origin, allowing users to use relative positioning onto larger
background (via -flatten).
The arguments are converted to these coefficients
c0: angle for center of source image
c1: angle scale for mapping to source image
c2: radius for top of source image
c3: radius scale for mapping source image
c4: centerline of arc within source image
Note the coefficients use a center angle, so asymptotic join is
furthest from both sides of the source image. This also means that
for arc angles greater than 360 the sides of the image will be
trimmed equally.
Arc Distortion Notes...
+ Does not use a set of CPs
+ Will only work with Image Distortion
+ Can not be used for generating a sparse gradient (interpolation)
*/
if ( number_arguments >= 1 && arguments[0] < MagickEpsilon ) {
coeff = (double *) RelinquishMagickMemory(coeff);
(void) ThrowMagickException(exception,GetMagickModule(),OptionError,
"InvalidArgument","%s : 'Arc Angle Too Small'",
CommandOptionToMnemonic(MagickDistortOptions, *method) );
return((double *) NULL);
}
if ( number_arguments >= 3 && arguments[2] < MagickEpsilon ) {
coeff = (double *) RelinquishMagickMemory(coeff);
(void) ThrowMagickException(exception,GetMagickModule(),OptionError,
"InvalidArgument","%s : 'Outer Radius Too Small'",
CommandOptionToMnemonic(MagickDistortOptions, *method) );
return((double *) NULL);
}
coeff[0] = -MagickPI2; /* -90, place at top! */
if ( number_arguments >= 1 )
coeff[1] = DegreesToRadians(arguments[0]);
else
coeff[1] = MagickPI2; /* zero arguments - center is at top */
if ( number_arguments >= 2 )
coeff[0] += DegreesToRadians(arguments[1]);
coeff[0] /= Magick2PI; /* normalize radians */
coeff[0] -= MagickRound(coeff[0]);
coeff[0] *= Magick2PI; /* de-normalize back to radians */
coeff[3] = (double)image->rows-1;
coeff[2] = (double)image->columns/coeff[1] + coeff[3]/2.0;
if ( number_arguments >= 3 ) {
if ( number_arguments >= 4 )
coeff[3] = arguments[2] - arguments[3];
else
coeff[3] *= arguments[2]/coeff[2];
coeff[2] = arguments[2];
}
coeff[4] = ((double)image->columns-1.0)/2.0;
return(coeff);
}
case PolarDistortion:
case DePolarDistortion:
{
/* (De)Polar Distortion (same set of arguments)
Args: Rmax, Rmin, Xcenter,Ycenter, Afrom,Ato
DePolar can also have the extra arguments of Width, Height
Coefficients 0 to 5 is the sanatized version first 6 input args
Coefficient 6 is the angle to coord ratio and visa-versa
Coefficient 7 is the radius to coord ratio and visa-versa
WARNING: It is possible for Radius max<min and/or Angle from>to
*/
if ( number_arguments == 3
|| ( number_arguments > 6 && *method == PolarDistortion )
|| number_arguments > 8 ) {
(void) ThrowMagickException(exception,GetMagickModule(),
OptionError,"InvalidArgument", "%s : number of arguments",
CommandOptionToMnemonic(MagickDistortOptions, *method) );
coeff=(double *) RelinquishMagickMemory(coeff);
return((double *) NULL);
}
/* Rmax - if 0 calculate appropriate value */
if ( number_arguments >= 1 )
coeff[0] = arguments[0];
else
coeff[0] = 0.0;
/* Rmin - usally 0 */
coeff[1] = number_arguments >= 2 ? arguments[1] : 0.0;
/* Center X,Y */
if ( number_arguments >= 4 ) {
coeff[2] = arguments[2];
coeff[3] = arguments[3];
}
else { /* center of actual image */
coeff[2] = (double)(image->columns)/2.0+image->page.x;
coeff[3] = (double)(image->rows)/2.0+image->page.y;
}
/* Angle from,to - about polar center 0 is downward */
coeff[4] = -MagickPI;
if ( number_arguments >= 5 )
coeff[4] = DegreesToRadians(arguments[4]);
coeff[5] = coeff[4];
if ( number_arguments >= 6 )
coeff[5] = DegreesToRadians(arguments[5]);
if ( fabs(coeff[4]-coeff[5]) < MagickEpsilon )
coeff[5] += Magick2PI; /* same angle is a full circle */
/* if radius 0 or negative, its a special value... */
if ( coeff[0] < MagickEpsilon ) {
/* Use closest edge if radius == 0 */
if ( fabs(coeff[0]) < MagickEpsilon ) {
coeff[0]=MagickMin(fabs(coeff[2]-image->page.x),
fabs(coeff[3]-image->page.y));
coeff[0]=MagickMin(coeff[0],
fabs(coeff[2]-image->page.x-image->columns));
coeff[0]=MagickMin(coeff[0],
fabs(coeff[3]-image->page.y-image->rows));
}
/* furthest diagonal if radius == -1 */
if ( fabs(-1.0-coeff[0]) < MagickEpsilon ) {
double rx,ry;
rx = coeff[2]-image->page.x;
ry = coeff[3]-image->page.y;
coeff[0] = rx*rx+ry*ry;
ry = coeff[3]-image->page.y-image->rows;
coeff[0] = MagickMax(coeff[0],rx*rx+ry*ry);
rx = coeff[2]-image->page.x-image->columns;
coeff[0] = MagickMax(coeff[0],rx*rx+ry*ry);
ry = coeff[3]-image->page.y;
coeff[0] = MagickMax(coeff[0],rx*rx+ry*ry);
coeff[0] = sqrt(coeff[0]);
}
}
/* IF Rmax <= 0 or Rmin < 0 OR Rmax < Rmin, THEN error */
if ( coeff[0] < MagickEpsilon || coeff[1] < -MagickEpsilon
|| (coeff[0]-coeff[1]) < MagickEpsilon ) {
(void) ThrowMagickException(exception,GetMagickModule(),OptionError,
"InvalidArgument", "%s : Invalid Radius",
CommandOptionToMnemonic(MagickDistortOptions, *method) );
coeff=(double *) RelinquishMagickMemory(coeff);
return((double *) NULL);
}
/* converstion ratios */
if ( *method == PolarDistortion ) {
coeff[6]=(double) image->columns/(coeff[5]-coeff[4]);
coeff[7]=(double) image->rows/(coeff[0]-coeff[1]);
}
else { /* *method == DePolarDistortion */
coeff[6]=(coeff[5]-coeff[4])/image->columns;
coeff[7]=(coeff[0]-coeff[1])/image->rows;
}
return(coeff);
}
case Cylinder2PlaneDistortion:
case Plane2CylinderDistortion:
{
/* 3D Cylinder to/from a Tangential Plane
Projection between a clinder and flat plain from a point on the
center line of the cylinder.
The two surfaces coincide in 3D space at the given centers of
distortion (perpendicular to projection point) on both images.
Args: FOV_arc_width
Coefficents: FOV(radians), Radius, center_x,y, dest_center_x,y
FOV (Field Of View) the angular field of view of the distortion,
across the width of the image, in degrees. The centers are the
points of least distortion in the input and resulting images.
These centers are however determined later.
Coeff 0 is the FOV angle of view of image width in radians
Coeff 1 is calculated radius of cylinder.
Coeff 2,3 center of distortion of input image
Coefficents 4,5 Center of Distortion of dest (determined later)
*/
if ( arguments[0] < MagickEpsilon || arguments[0] > 160.0 ) {
(void) ThrowMagickException(exception,GetMagickModule(),OptionError,
"InvalidArgument", "%s : Invalid FOV Angle",
CommandOptionToMnemonic(MagickDistortOptions, *method) );
coeff=(double *) RelinquishMagickMemory(coeff);
return((double *) NULL);
}
coeff[0] = DegreesToRadians(arguments[0]);
if ( *method == Cylinder2PlaneDistortion )
/* image is curved around cylinder, so FOV angle (in radians)
* scales directly to image X coordinate, according to its radius.
*/
coeff[1] = (double) image->columns/coeff[0];
else
/* radius is distance away from an image with this angular FOV */
coeff[1] = (double) image->columns / ( 2 * tan(coeff[0]/2) );
coeff[2] = (double)(image->columns)/2.0+image->page.x;
coeff[3] = (double)(image->rows)/2.0+image->page.y;
coeff[4] = coeff[2];
coeff[5] = coeff[3]; /* assuming image size is the same */
return(coeff);
}
case BarrelDistortion:
case BarrelInverseDistortion:
{
/* Barrel Distortion
Rs=(A*Rd^3 + B*Rd^2 + C*Rd + D)*Rd
BarrelInv Distortion
Rs=Rd/(A*Rd^3 + B*Rd^2 + C*Rd + D)
Where Rd is the normalized radius from corner to middle of image
Input Arguments are one of the following forms (number of arguments)...
3: A,B,C
4: A,B,C,D
5: A,B,C X,Y
6: A,B,C,D X,Y
8: Ax,Bx,Cx,Dx Ay,By,Cy,Dy
10: Ax,Bx,Cx,Dx Ay,By,Cy,Dy X,Y
Returns 10 coefficent values, which are de-normalized (pixel scale)
Ax, Bx, Cx, Dx, Ay, By, Cy, Dy, Xc, Yc
*/
/* Radius de-normalization scaling factor */
double
rscale = 2.0/MagickMin((double) image->columns,(double) image->rows);
/* sanity check number of args must = 3,4,5,6,8,10 or error */
if ( (number_arguments < 3) || (number_arguments == 7) ||
(number_arguments == 9) || (number_arguments > 10) )
{
coeff=(double *) RelinquishMagickMemory(coeff);
(void) ThrowMagickException(exception,GetMagickModule(),
OptionError,"InvalidArgument", "%s : number of arguments",
CommandOptionToMnemonic(MagickDistortOptions, *method) );
return((double *) NULL);
}
/* A,B,C,D coefficients */
coeff[0] = arguments[0];
coeff[1] = arguments[1];
coeff[2] = arguments[2];
if ((number_arguments == 3) || (number_arguments == 5) )
coeff[3] = 1.0 - coeff[0] - coeff[1] - coeff[2];
else
coeff[3] = arguments[3];
/* de-normalize the coefficients */
coeff[0] *= pow(rscale,3.0);
coeff[1] *= rscale*rscale;
coeff[2] *= rscale;
/* Y coefficients: as given OR same as X coefficients */
if ( number_arguments >= 8 ) {
coeff[4] = arguments[4] * pow(rscale,3.0);
coeff[5] = arguments[5] * rscale*rscale;
coeff[6] = arguments[6] * rscale;
coeff[7] = arguments[7];
}
else {
coeff[4] = coeff[0];
coeff[5] = coeff[1];
coeff[6] = coeff[2];
coeff[7] = coeff[3];
}
/* X,Y Center of Distortion (image coodinates) */
if ( number_arguments == 5 ) {
coeff[8] = arguments[3];
coeff[9] = arguments[4];
}
else if ( number_arguments == 6 ) {
coeff[8] = arguments[4];
coeff[9] = arguments[5];
}
else if ( number_arguments == 10 ) {
coeff[8] = arguments[8];
coeff[9] = arguments[9];
}
else {
/* center of the image provided (image coodinates) */
coeff[8] = (double)image->columns/2.0 + image->page.x;
coeff[9] = (double)image->rows/2.0 + image->page.y;
}
return(coeff);
}
case ShepardsDistortion:
{
/* Shepards Distortion input arguments are the coefficents!
Just check the number of arguments is valid!
Args: u1,v1, x1,y1, ...
OR : u1,v1, r1,g1,c1, ...
*/
if ( number_arguments%cp_size != 0 ||
number_arguments < cp_size ) {
(void) ThrowMagickException(exception,GetMagickModule(),OptionError,
"InvalidArgument", "%s : 'requires CP's (4 numbers each)'",
CommandOptionToMnemonic(MagickDistortOptions, *method));
coeff=(double *) RelinquishMagickMemory(coeff);
return((double *) NULL);
}
/* User defined weighting power for Shepard's Method */
{ const char *artifact=GetImageArtifact(image,"shepards:power");
if ( artifact != (const char *) NULL ) {
coeff[0]=StringToDouble(artifact,(char **) NULL) / 2.0;
if ( coeff[0] < MagickEpsilon ) {
(void) ThrowMagickException(exception,GetMagickModule(),
OptionError,"InvalidArgument","%s", "-define shepards:power" );
coeff=(double *) RelinquishMagickMemory(coeff);
return((double *) NULL);
}
}
else
coeff[0]=1.0; /* Default power of 2 (Inverse Squared) */
}
return(coeff);
}
default:
break;
}
/* you should never reach this point */
perror("no method handler"); /* just fail assertion */
return((double *) NULL);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
+ D i s t o r t R e s i z e I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% DistortResizeImage() resize image using the equivalent but slower image
% distortion operator. The filter is applied using a EWA cylindrical
% resampling. But like resize the final image size is limited to whole pixels
% with no effects by virtual-pixels on the result.
%
% Note that images containing a transparency channel will be twice as slow to
% resize as images one without transparency.
%
% The format of the DistortResizeImage method is:
%
% Image *DistortResizeImage(const Image *image,const size_t columns,
% const size_t rows,ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o columns: the number of columns in the resized image.
%
% o rows: the number of rows in the resized image.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport Image *DistortResizeImage(const Image *image,const size_t columns,
const size_t rows,ExceptionInfo *exception)
{
#define DistortResizeImageTag "Distort/Image"
Image
*resize_image,
*tmp_image;
RectangleInfo
crop_area;
double
distort_args[12];
VirtualPixelMethod
vp_save;
/*
Distort resize image.
*/
assert(image != (const Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickCoreSignature);
if ((columns == 0) || (rows == 0))
return((Image *) NULL);
/* Do not short-circuit this resize if final image size is unchanged */
(void) memset(distort_args,0,sizeof(distort_args));
distort_args[4]=(double) image->columns;
distort_args[6]=(double) columns;
distort_args[9]=(double) image->rows;
distort_args[11]=(double) rows;
vp_save=GetImageVirtualPixelMethod(image);
tmp_image=CloneImage(image,0,0,MagickTrue,exception);
if (tmp_image == (Image *) NULL)
return((Image *) NULL);
(void) SetImageVirtualPixelMethod(tmp_image,TransparentVirtualPixelMethod,
exception);
if (image->alpha_trait == UndefinedPixelTrait)
{
/*
Image has no alpha channel, so we are free to use it.
*/
(void) SetImageAlphaChannel(tmp_image,SetAlphaChannel,exception);
resize_image=DistortImage(tmp_image,AffineDistortion,12,distort_args,
MagickTrue,exception),
tmp_image=DestroyImage(tmp_image);
if (resize_image == (Image *) NULL)
return((Image *) NULL);
(void) SetImageAlphaChannel(resize_image,OffAlphaChannel,exception);
}
else
{
/*
Image has transparency so handle colors and alpha separatly.
Basically we need to separate Virtual-Pixel alpha in the resized
image, so only the actual original images alpha channel is used.
distort alpha channel separately
*/
Image
*resize_alpha;
(void) SetImageAlphaChannel(tmp_image,ExtractAlphaChannel,exception);
(void) SetImageAlphaChannel(tmp_image,OpaqueAlphaChannel,exception);
resize_alpha=DistortImage(tmp_image,AffineDistortion,12,distort_args,
MagickTrue,exception),
tmp_image=DestroyImage(tmp_image);
if (resize_alpha == (Image *) NULL)
return((Image *) NULL);
/* distort the actual image containing alpha + VP alpha */
tmp_image=CloneImage(image,0,0,MagickTrue,exception);
if (tmp_image == (Image *) NULL)
return((Image *) NULL);
(void) SetImageVirtualPixelMethod(tmp_image,
TransparentVirtualPixelMethod,exception);
resize_image=DistortImage(tmp_image,AffineDistortion,12,distort_args,
MagickTrue,exception),
tmp_image=DestroyImage(tmp_image);
if (resize_image == (Image *) NULL)
{
resize_alpha=DestroyImage(resize_alpha);
return((Image *) NULL);
}
/* replace resize images alpha with the separally distorted alpha */
(void) SetImageAlphaChannel(resize_image,OffAlphaChannel,exception);
(void) SetImageAlphaChannel(resize_alpha,OffAlphaChannel,exception);
(void) CompositeImage(resize_image,resize_alpha,CopyAlphaCompositeOp,
MagickTrue,0,0,exception);
resize_alpha=DestroyImage(resize_alpha);
resize_image->alpha_trait=image->alpha_trait;
resize_image->compose=image->compose;
}
(void) SetImageVirtualPixelMethod(resize_image,vp_save,exception);
/*
Clean up the results of the Distortion
*/
crop_area.width=columns;
crop_area.height=rows;
crop_area.x=0;
crop_area.y=0;
tmp_image=resize_image;
resize_image=CropImage(tmp_image,&crop_area,exception);
tmp_image=DestroyImage(tmp_image);
if (resize_image != (Image *) NULL)
{
resize_image->page.width=0;
resize_image->page.height=0;
}
return(resize_image);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% D i s t o r t I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% DistortImage() distorts an image using various distortion methods, by
% mapping color lookups of the source image to a new destination image
% usally of the same size as the source image, unless 'bestfit' is set to
% true.
%
% If 'bestfit' is enabled, and distortion allows it, the destination image is
% adjusted to ensure the whole source 'image' will just fit within the final
% destination image, which will be sized and offset accordingly. Also in
% many cases the virtual offset of the source image will be taken into
% account in the mapping.
%
% If the '-verbose' control option has been set print to standard error the
% equicelent '-fx' formula with coefficients for the function, if practical.
%
% The format of the DistortImage() method is:
%
% Image *DistortImage(const Image *image,const DistortMethod method,
% const size_t number_arguments,const double *arguments,
% MagickBooleanType bestfit, ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image to be distorted.
%
% o method: the method of image distortion.
%
% ArcDistortion always ignores source image offset, and always
% 'bestfit' the destination image with the top left corner offset
% relative to the polar mapping center.
%
% Affine, Perspective, and Bilinear, do least squares fitting of the
% distrotion when more than the minimum number of control point pairs
% are provided.
%
% Perspective, and Bilinear, fall back to a Affine distortion when less
% than 4 control point pairs are provided. While Affine distortions
% let you use any number of control point pairs, that is Zero pairs is
% a No-Op (viewport only) distortion, one pair is a translation and
% two pairs of control points do a scale-rotate-translate, without any
% shearing.
%
% o number_arguments: the number of arguments given.
%
% o arguments: an array of floating point arguments for this method.
%
% o bestfit: Attempt to 'bestfit' the size of the resulting image.
% This also forces the resulting image to be a 'layered' virtual
% canvas image. Can be overridden using 'distort:viewport' setting.
%
% o exception: return any errors or warnings in this structure
%
% Extra Controls from Image meta-data (artifacts)...
%
% o "verbose"
% Output to stderr alternatives, internal coefficents, and FX
% equivalents for the distortion operation (if feasible).
% This forms an extra check of the distortion method, and allows users
% access to the internal constants IM calculates for the distortion.
%
% o "distort:viewport"
% Directly set the output image canvas area and offest to use for the
% resulting image, rather than use the original images canvas, or a
% calculated 'bestfit' canvas.
%
% o "distort:scale"
% Scale the size of the output canvas by this amount to provide a
% method of Zooming, and for super-sampling the results.
%
% Other settings that can effect results include
%
% o 'interpolate' For source image lookups (scale enlargements)
%
% o 'filter' Set filter to use for area-resampling (scale shrinking).
% Set to 'point' to turn off and use 'interpolate' lookup
% instead
%
*/
MagickExport Image *DistortImage(const Image *image, DistortMethod method,
const size_t number_arguments,const double *arguments,
MagickBooleanType bestfit,ExceptionInfo *exception)
{
#define DistortImageTag "Distort/Image"
double
*coeff,
output_scaling;
Image
*distort_image;
RectangleInfo
geometry; /* geometry of the distorted space viewport */
MagickBooleanType
viewport_given;
PixelInfo
invalid; /* the color to assign when distort result is invalid */
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickCoreSignature);
/*
Handle Special Compound Distortions
*/
if ( method == ResizeDistortion )
{
if ( number_arguments != 2 )
{
(void) ThrowMagickException(exception,GetMagickModule(),OptionError,
"InvalidArgument","%s : '%s'","Resize",
"Invalid number of args: 2 only");
return((Image *) NULL);
}
distort_image=DistortResizeImage(image,(size_t)arguments[0],
(size_t)arguments[1], exception);
return(distort_image);
}
/*
Convert input arguments (usually as control points for reverse mapping)
into mapping coefficients to apply the distortion.
Note that some distortions are mapped to other distortions,
and as such do not require specific code after this point.
*/
coeff = GenerateCoefficients(image, &method, number_arguments,
arguments, 0, exception);
if ( coeff == (double *) NULL )
return((Image *) NULL);
/*
Determine the size and offset for a 'bestfit' destination.
Usally the four corners of the source image is enough.
*/
/* default output image bounds, when no 'bestfit' is requested */
geometry.width=image->columns;
geometry.height=image->rows;
geometry.x=0;
geometry.y=0;
if ( method == ArcDistortion ) {
bestfit = MagickTrue; /* always calculate a 'best fit' viewport */
}
/* Work out the 'best fit', (required for ArcDistortion) */
if ( bestfit ) {
PointInfo
s,d,min,max; /* source, dest coords --mapping--> min, max coords */
MagickBooleanType
fix_bounds = MagickTrue; /* enlarge bounds for VP handling */
s.x=s.y=min.x=max.x=min.y=max.y=0.0; /* keep compiler happy */
/* defines to figure out the bounds of the distorted image */
#define InitalBounds(p) \
{ \
/* printf("%lg,%lg -> %lg,%lg\n", s.x,s.y, d.x,d.y); */ \
min.x = max.x = p.x; \
min.y = max.y = p.y; \
}
#define ExpandBounds(p) \
{ \
/* printf("%lg,%lg -> %lg,%lg\n", s.x,s.y, d.x,d.y); */ \
min.x = MagickMin(min.x,p.x); \
max.x = MagickMax(max.x,p.x); \
min.y = MagickMin(min.y,p.y); \
max.y = MagickMax(max.y,p.y); \
}
switch (method)
{
case AffineDistortion:
case RigidAffineDistortion:
{ double inverse[6];
InvertAffineCoefficients(coeff, inverse);
s.x = (double) image->page.x;
s.y = (double) image->page.y;
d.x = inverse[0]*s.x+inverse[1]*s.y+inverse[2];
d.y = inverse[3]*s.x+inverse[4]*s.y+inverse[5];
InitalBounds(d);
s.x = (double) image->page.x+image->columns;
s.y = (double) image->page.y;
d.x = inverse[0]*s.x+inverse[1]*s.y+inverse[2];
d.y = inverse[3]*s.x+inverse[4]*s.y+inverse[5];
ExpandBounds(d);
s.x = (double) image->page.x;
s.y = (double) image->page.y+image->rows;
d.x = inverse[0]*s.x+inverse[1]*s.y+inverse[2];
d.y = inverse[3]*s.x+inverse[4]*s.y+inverse[5];
ExpandBounds(d);
s.x = (double) image->page.x+image->columns;
s.y = (double) image->page.y+image->rows;
d.x = inverse[0]*s.x+inverse[1]*s.y+inverse[2];
d.y = inverse[3]*s.x+inverse[4]*s.y+inverse[5];
ExpandBounds(d);
break;
}
case PerspectiveDistortion:
{ double inverse[8], scale;
InvertPerspectiveCoefficients(coeff, inverse);
s.x = (double) image->page.x;
s.y = (double) image->page.y;
scale=inverse[6]*s.x+inverse[7]*s.y+1.0;
scale=PerceptibleReciprocal(scale);
d.x = scale*(inverse[0]*s.x+inverse[1]*s.y+inverse[2]);
d.y = scale*(inverse[3]*s.x+inverse[4]*s.y+inverse[5]);
InitalBounds(d);
s.x = (double) image->page.x+image->columns;
s.y = (double) image->page.y;
scale=inverse[6]*s.x+inverse[7]*s.y+1.0;
scale=PerceptibleReciprocal(scale);
d.x = scale*(inverse[0]*s.x+inverse[1]*s.y+inverse[2]);
d.y = scale*(inverse[3]*s.x+inverse[4]*s.y+inverse[5]);
ExpandBounds(d);
s.x = (double) image->page.x;
s.y = (double) image->page.y+image->rows;
scale=inverse[6]*s.x+inverse[7]*s.y+1.0;
scale=PerceptibleReciprocal(scale);
d.x = scale*(inverse[0]*s.x+inverse[1]*s.y+inverse[2]);
d.y = scale*(inverse[3]*s.x+inverse[4]*s.y+inverse[5]);
ExpandBounds(d);
s.x = (double) image->page.x+image->columns;
s.y = (double) image->page.y+image->rows;
scale=inverse[6]*s.x+inverse[7]*s.y+1.0;
scale=PerceptibleReciprocal(scale);
d.x = scale*(inverse[0]*s.x+inverse[1]*s.y+inverse[2]);
d.y = scale*(inverse[3]*s.x+inverse[4]*s.y+inverse[5]);
ExpandBounds(d);
break;
}
case ArcDistortion:
{ double a, ca, sa;
/* Forward Map Corners */
a = coeff[0]-coeff[1]/2; ca = cos(a); sa = sin(a);
d.x = coeff[2]*ca;
d.y = coeff[2]*sa;
InitalBounds(d);
d.x = (coeff[2]-coeff[3])*ca;
d.y = (coeff[2]-coeff[3])*sa;
ExpandBounds(d);
a = coeff[0]+coeff[1]/2; ca = cos(a); sa = sin(a);
d.x = coeff[2]*ca;
d.y = coeff[2]*sa;
ExpandBounds(d);
d.x = (coeff[2]-coeff[3])*ca;
d.y = (coeff[2]-coeff[3])*sa;
ExpandBounds(d);
/* Orthogonal points along top of arc */
for( a=(double) (ceil((double) ((coeff[0]-coeff[1]/2.0)/MagickPI2))*MagickPI2);
a<(coeff[0]+coeff[1]/2.0); a+=MagickPI2 ) {
ca = cos(a); sa = sin(a);
d.x = coeff[2]*ca;
d.y = coeff[2]*sa;
ExpandBounds(d);
}
/*
Convert the angle_to_width and radius_to_height
to appropriate scaling factors, to allow faster processing
in the mapping function.
*/
coeff[1] = (double) (Magick2PI*image->columns/coeff[1]);
coeff[3] = (double)image->rows/coeff[3];
break;
}
case PolarDistortion:
{
if (number_arguments < 2)
coeff[2] = coeff[3] = 0.0;
min.x = coeff[2]-coeff[0];
max.x = coeff[2]+coeff[0];
min.y = coeff[3]-coeff[0];
max.y = coeff[3]+coeff[0];
/* should be about 1.0 if Rmin = 0 */
coeff[7]=(double) geometry.height/(coeff[0]-coeff[1]);
break;
}
case DePolarDistortion:
{
/* direct calculation as it needs to tile correctly
* for reversibility in a DePolar-Polar cycle */
fix_bounds = MagickFalse;
geometry.x = geometry.y = 0;
geometry.height = (size_t) ceil(coeff[0]-coeff[1]);
geometry.width = (size_t) ceil((coeff[0]-coeff[1])*
(coeff[5]-coeff[4])*0.5);
/* correct scaling factors relative to new size */
coeff[6]=(coeff[5]-coeff[4])*PerceptibleReciprocal(geometry.width); /* changed width */
coeff[7]=(coeff[0]-coeff[1])*PerceptibleReciprocal(geometry.height); /* should be about 1.0 */
break;
}
case Cylinder2PlaneDistortion:
{
/* direct calculation so center of distortion is either a pixel
* center, or pixel edge. This allows for reversibility of the
* distortion */
geometry.x = geometry.y = 0;
geometry.width = (size_t) ceil( 2.0*coeff[1]*tan(coeff[0]/2.0) );
geometry.height = (size_t) ceil( 2.0*coeff[3]/cos(coeff[0]/2.0) );
/* correct center of distortion relative to new size */
coeff[4] = (double) geometry.width/2.0;
coeff[5] = (double) geometry.height/2.0;
fix_bounds = MagickFalse;
break;
}
case Plane2CylinderDistortion:
{
/* direct calculation center is either pixel center, or pixel edge
* so as to allow reversibility of the image distortion */
geometry.x = geometry.y = 0;
geometry.width = (size_t) ceil(coeff[0]*coeff[1]); /* FOV * radius */
geometry.height = (size_t) (2*coeff[3]); /* input image height */
/* correct center of distortion relative to new size */
coeff[4] = (double) geometry.width/2.0;
coeff[5] = (double) geometry.height/2.0;
fix_bounds = MagickFalse;
break;
}
case ShepardsDistortion:
case BilinearForwardDistortion:
case BilinearReverseDistortion:
#if 0
case QuadrilateralDistortion:
#endif
case PolynomialDistortion:
case BarrelDistortion:
case BarrelInverseDistortion:
default:
/* no calculated bestfit available for these distortions */
bestfit = MagickFalse;
fix_bounds = MagickFalse;
break;
}
/* Set the output image geometry to calculated 'bestfit'.
Yes this tends to 'over do' the file image size, ON PURPOSE!
Do not do this for DePolar which needs to be exact for virtual tiling.
*/
if ( fix_bounds ) {
geometry.x = (ssize_t) floor(min.x-0.5);
geometry.y = (ssize_t) floor(min.y-0.5);
geometry.width=(size_t) ceil(max.x-geometry.x+0.5);
geometry.height=(size_t) ceil(max.y-geometry.y+0.5);
}
} /* end bestfit destination image calculations */
/* The user provided a 'viewport' expert option which may
overrides some parts of the current output image geometry.
This also overrides its default 'bestfit' setting.
*/
{ const char *artifact=GetImageArtifact(image,"distort:viewport");
viewport_given = MagickFalse;
if ( artifact != (const char *) NULL ) {
MagickStatusType flags=ParseAbsoluteGeometry(artifact,&geometry);
if (flags==NoValue)
(void) ThrowMagickException(exception,GetMagickModule(),
OptionWarning,"InvalidSetting","'%s' '%s'",
"distort:viewport",artifact);
else
viewport_given = MagickTrue;
}
}
/* Verbose output */
if (IsStringTrue(GetImageArtifact(image,"verbose")) != MagickFalse) {
ssize_t
i;
char image_gen[MagickPathExtent];
const char *lookup;
/* Set destination image size and virtual offset */
if ( bestfit || viewport_given ) {
(void) FormatLocaleString(image_gen,MagickPathExtent,
" -size %.20gx%.20g -page %+.20g%+.20g xc: +insert \\\n",
(double) geometry.width,(double) geometry.height,(double) geometry.x,
(double) geometry.y);
lookup="v.p{xx-v.page.x-0.5,yy-v.page.y-0.5}";
}
else {
image_gen[0] = '\0'; /* no destination to generate */
lookup = "p{xx-page.x-0.5,yy-page.y-0.5}"; /* simplify lookup */
}
switch (method)
{
case AffineDistortion:
case RigidAffineDistortion:
{
double
*inverse;
inverse=(double *) AcquireQuantumMemory(6,sizeof(*inverse));
if (inverse == (double *) NULL)
{
coeff=(double *) RelinquishMagickMemory(coeff);
(void) ThrowMagickException(exception,GetMagickModule(),
ResourceLimitError,"MemoryAllocationFailed","%s","DistortImages");
return((Image *) NULL);
}
InvertAffineCoefficients(coeff, inverse);
CoefficientsToAffineArgs(inverse);
(void) FormatLocaleFile(stderr, "Affine projection:\n");
(void) FormatLocaleFile(stderr,
" -distort AffineProjection \\\n '");
for (i=0; i < 5; i++)
(void) FormatLocaleFile(stderr, "%.*g,",GetMagickPrecision(),
inverse[i]);
(void) FormatLocaleFile(stderr, "%.*g'\n",GetMagickPrecision(),
inverse[5]);
(void) FormatLocaleFile(stderr,
"Equivalent scale, rotation(deg), translation:\n");
(void) FormatLocaleFile(stderr," %.*g,%.*g,%.*g,%.*g\n",
GetMagickPrecision(),sqrt(inverse[0]*inverse[0]+
inverse[1]*inverse[1]),GetMagickPrecision(),
RadiansToDegrees(atan2(inverse[1],inverse[0])),
GetMagickPrecision(),inverse[4],GetMagickPrecision(),inverse[5]);
inverse=(double *) RelinquishMagickMemory(inverse);
(void) FormatLocaleFile(stderr,"Affine distort, FX equivalent:\n");
(void) FormatLocaleFile(stderr, "%s", image_gen);
(void) FormatLocaleFile(stderr,
" -fx 'ii=i+page.x+0.5; jj=j+page.y+0.5;\n");
(void) FormatLocaleFile(stderr," xx=%+.*g*ii %+.*g*jj %+.*g;\n",
GetMagickPrecision(),coeff[0],GetMagickPrecision(),coeff[1],
GetMagickPrecision(),coeff[2]);
(void) FormatLocaleFile(stderr," yy=%+.*g*ii %+.*g*jj %+.*g;\n",
GetMagickPrecision(),coeff[3],GetMagickPrecision(),coeff[4],
GetMagickPrecision(),coeff[5]);
(void) FormatLocaleFile(stderr," %s' \\\n",lookup);
break;
}
case PerspectiveDistortion:
{
double
*inverse;
inverse=(double *) AcquireQuantumMemory(8,sizeof(*inverse));
if (inverse == (double *) NULL)
{
coeff=(double *) RelinquishMagickMemory(coeff);
(void) ThrowMagickException(exception,GetMagickModule(),
ResourceLimitError,"MemoryAllocationFailed","%s",
"DistortCoefficients");
return((Image *) NULL);
}
InvertPerspectiveCoefficients(coeff, inverse);
(void) FormatLocaleFile(stderr,"Perspective Projection:\n");
(void) FormatLocaleFile(stderr,
" -distort PerspectiveProjection \\\n '");
for (i=0; i < 4; i++)
(void) FormatLocaleFile(stderr, "%.*g, ",GetMagickPrecision(),
inverse[i]);
(void) FormatLocaleFile(stderr, "\n ");
for ( ; i < 7; i++)
(void) FormatLocaleFile(stderr, "%.*g, ",GetMagickPrecision(),
inverse[i]);
(void) FormatLocaleFile(stderr, "%.*g'\n",GetMagickPrecision(),
inverse[7]);
inverse=(double *) RelinquishMagickMemory(inverse);
(void) FormatLocaleFile(stderr,"Perspective Distort, FX Equivelent:\n");
(void) FormatLocaleFile(stderr,"%.1024s",image_gen);
(void) FormatLocaleFile(stderr,
" -fx 'ii=i+page.x+0.5; jj=j+page.y+0.5;\n");
(void) FormatLocaleFile(stderr," rr=%+.*g*ii %+.*g*jj + 1;\n",
GetMagickPrecision(),coeff[6],GetMagickPrecision(),coeff[7]);
(void) FormatLocaleFile(stderr,
" xx=(%+.*g*ii %+.*g*jj %+.*g)/rr;\n",
GetMagickPrecision(),coeff[0],GetMagickPrecision(),coeff[1],
GetMagickPrecision(),coeff[2]);
(void) FormatLocaleFile(stderr,
" yy=(%+.*g*ii %+.*g*jj %+.*g)/rr;\n",
GetMagickPrecision(),coeff[3],GetMagickPrecision(),coeff[4],
GetMagickPrecision(),coeff[5]);
(void) FormatLocaleFile(stderr," rr%s0 ? %s : blue' \\\n",
coeff[8] < 0.0 ? "<" : ">", lookup);
break;
}
case BilinearForwardDistortion:
{
(void) FormatLocaleFile(stderr,"BilinearForward Mapping Equations:\n");
(void) FormatLocaleFile(stderr,"%s", image_gen);
(void) FormatLocaleFile(stderr," i = %+lf*x %+lf*y %+lf*x*y %+lf;\n",
coeff[0],coeff[1],coeff[2],coeff[3]);
(void) FormatLocaleFile(stderr," j = %+lf*x %+lf*y %+lf*x*y %+lf;\n",
coeff[4],coeff[5],coeff[6],coeff[7]);
#if 0
/* for debugging */
(void) FormatLocaleFile(stderr, " c8 = %+lf c9 = 2*a = %+lf;\n",
coeff[8], coeff[9]);
#endif
(void) FormatLocaleFile(stderr,
"BilinearForward Distort, FX Equivelent:\n");
(void) FormatLocaleFile(stderr,"%s", image_gen);
(void) FormatLocaleFile(stderr,
" -fx 'ii=i+page.x%+lf; jj=j+page.y%+lf;\n",0.5-coeff[3],0.5-
coeff[7]);
(void) FormatLocaleFile(stderr," bb=%lf*ii %+lf*jj %+lf;\n",
coeff[6], -coeff[2], coeff[8]);
/* Handle Special degenerate (non-quadratic) or trapezoidal case */
if (coeff[9] != 0)
{
(void) FormatLocaleFile(stderr,
" rt=bb*bb %+lf*(%lf*ii%+lf*jj);\n",-2*coeff[9],coeff[4],
-coeff[0]);
(void) FormatLocaleFile(stderr,
" yy=( -bb + sqrt(rt) ) / %lf;\n",coeff[9]);
}
else
(void) FormatLocaleFile(stderr," yy=(%lf*ii%+lf*jj)/bb;\n",
-coeff[4],coeff[0]);
(void) FormatLocaleFile(stderr,
" xx=(ii %+lf*yy)/(%lf %+lf*yy);\n",-coeff[1],coeff[0],
coeff[2]);
if ( coeff[9] != 0 )
(void) FormatLocaleFile(stderr," (rt < 0 ) ? red : %s'\n",
lookup);
else
(void) FormatLocaleFile(stderr," %s' \\\n", lookup);
break;
}
case BilinearReverseDistortion:
{
#if 0
(void) FormatLocaleFile(stderr, "Polynomial Projection Distort:\n");
(void) FormatLocaleFile(stderr, " -distort PolynomialProjection \\\n");
(void) FormatLocaleFile(stderr, " '1.5, %lf, %lf, %lf, %lf,\n",
coeff[3], coeff[0], coeff[1], coeff[2]);
(void) FormatLocaleFile(stderr, " %lf, %lf, %lf, %lf'\n",
coeff[7], coeff[4], coeff[5], coeff[6]);
#endif
(void) FormatLocaleFile(stderr,
"BilinearReverse Distort, FX Equivelent:\n");
(void) FormatLocaleFile(stderr,"%s", image_gen);
(void) FormatLocaleFile(stderr,
" -fx 'ii=i+page.x+0.5; jj=j+page.y+0.5;\n");
(void) FormatLocaleFile(stderr,
" xx=%+lf*ii %+lf*jj %+lf*ii*jj %+lf;\n",coeff[0],coeff[1],
coeff[2], coeff[3]);
(void) FormatLocaleFile(stderr,
" yy=%+lf*ii %+lf*jj %+lf*ii*jj %+lf;\n",coeff[4],coeff[5],
coeff[6], coeff[7]);
(void) FormatLocaleFile(stderr," %s' \\\n", lookup);
break;
}
case PolynomialDistortion:
{
size_t nterms = (size_t) coeff[1];
(void) FormatLocaleFile(stderr,
"Polynomial (order %lg, terms %lu), FX Equivelent\n",coeff[0],
(unsigned long) nterms);
(void) FormatLocaleFile(stderr,"%s", image_gen);
(void) FormatLocaleFile(stderr,
" -fx 'ii=i+page.x+0.5; jj=j+page.y+0.5;\n");
(void) FormatLocaleFile(stderr, " xx =");
for (i=0; i < (ssize_t) nterms; i++)
{
if ((i != 0) && (i%4 == 0))
(void) FormatLocaleFile(stderr, "\n ");
(void) FormatLocaleFile(stderr," %+lf%s",coeff[2+i],
poly_basis_str(i));
}
(void) FormatLocaleFile(stderr,";\n yy =");
for (i=0; i < (ssize_t) nterms; i++)
{
if ((i != 0) && (i%4 == 0))
(void) FormatLocaleFile(stderr,"\n ");
(void) FormatLocaleFile(stderr," %+lf%s",coeff[2+i+nterms],
poly_basis_str(i));
}
(void) FormatLocaleFile(stderr,";\n %s' \\\n", lookup);
break;
}
case ArcDistortion:
{
(void) FormatLocaleFile(stderr,"Arc Distort, Internal Coefficients:\n");
for (i=0; i < 5; i++)
(void) FormatLocaleFile(stderr,
" c%.20g = %+lf\n",(double) i,coeff[i]);
(void) FormatLocaleFile(stderr,"Arc Distort, FX Equivelent:\n");
(void) FormatLocaleFile(stderr,"%s", image_gen);
(void) FormatLocaleFile(stderr," -fx 'ii=i+page.x; jj=j+page.y;\n");
(void) FormatLocaleFile(stderr," xx=(atan2(jj,ii)%+lf)/(2*pi);\n",
-coeff[0]);
(void) FormatLocaleFile(stderr," xx=xx-round(xx);\n");
(void) FormatLocaleFile(stderr," xx=xx*%lf %+lf;\n",coeff[1],
coeff[4]);
(void) FormatLocaleFile(stderr,
" yy=(%lf - hypot(ii,jj)) * %lf;\n",coeff[2],coeff[3]);
(void) FormatLocaleFile(stderr," v.p{xx-.5,yy-.5}' \\\n");
break;
}
case PolarDistortion:
{
(void) FormatLocaleFile(stderr,"Polar Distort, Internal Coefficents\n");
for (i=0; i < 8; i++)
(void) FormatLocaleFile(stderr," c%.20g = %+lf\n",(double) i,
coeff[i]);
(void) FormatLocaleFile(stderr,"Polar Distort, FX Equivelent:\n");
(void) FormatLocaleFile(stderr,"%s", image_gen);
(void) FormatLocaleFile(stderr,
" -fx 'ii=i+page.x%+lf; jj=j+page.y%+lf;\n",-coeff[2],-coeff[3]);
(void) FormatLocaleFile(stderr," xx=(atan2(ii,jj)%+lf)/(2*pi);\n",
-(coeff[4]+coeff[5])/2 );
(void) FormatLocaleFile(stderr," xx=xx-round(xx);\n");
(void) FormatLocaleFile(stderr," xx=xx*2*pi*%lf + v.w/2;\n",
coeff[6] );
(void) FormatLocaleFile(stderr," yy=(hypot(ii,jj)%+lf)*%lf;\n",
-coeff[1],coeff[7] );
(void) FormatLocaleFile(stderr," v.p{xx-.5,yy-.5}' \\\n");
break;
}
case DePolarDistortion:
{
(void) FormatLocaleFile(stderr,
"DePolar Distort, Internal Coefficents\n");
for (i=0; i < 8; i++)
(void) FormatLocaleFile(stderr," c%.20g = %+lf\n",(double) i,
coeff[i]);
(void) FormatLocaleFile(stderr,"DePolar Distort, FX Equivelent:\n");
(void) FormatLocaleFile(stderr,"%s", image_gen);
(void) FormatLocaleFile(stderr," -fx 'aa=(i+.5)*%lf %+lf;\n",
coeff[6],+coeff[4]);
(void) FormatLocaleFile(stderr," rr=(j+.5)*%lf %+lf;\n",
coeff[7],+coeff[1]);
(void) FormatLocaleFile(stderr," xx=rr*sin(aa) %+lf;\n",
coeff[2]);
(void) FormatLocaleFile(stderr," yy=rr*cos(aa) %+lf;\n",
coeff[3]);
(void) FormatLocaleFile(stderr," v.p{xx-.5,yy-.5}' \\\n");
break;
}
case Cylinder2PlaneDistortion:
{
(void) FormatLocaleFile(stderr,
"Cylinder to Plane Distort, Internal Coefficents\n");
(void) FormatLocaleFile(stderr," cylinder_radius = %+lf\n",coeff[1]);
(void) FormatLocaleFile(stderr,
"Cylinder to Plane Distort, FX Equivelent:\n");
(void) FormatLocaleFile(stderr, "%s", image_gen);
(void) FormatLocaleFile(stderr,
" -fx 'ii=i+page.x%+lf+0.5; jj=j+page.y%+lf+0.5;\n",-coeff[4],
-coeff[5]);
(void) FormatLocaleFile(stderr," aa=atan(ii/%+lf);\n",coeff[1]);
(void) FormatLocaleFile(stderr," xx=%lf*aa%+lf;\n",
coeff[1],coeff[2]);
(void) FormatLocaleFile(stderr," yy=jj*cos(aa)%+lf;\n",coeff[3]);
(void) FormatLocaleFile(stderr," %s' \\\n", lookup);
break;
}
case Plane2CylinderDistortion:
{
(void) FormatLocaleFile(stderr,
"Plane to Cylinder Distort, Internal Coefficents\n");
(void) FormatLocaleFile(stderr," cylinder_radius = %+lf\n",coeff[1]);
(void) FormatLocaleFile(stderr,
"Plane to Cylinder Distort, FX Equivelent:\n");
(void) FormatLocaleFile(stderr,"%s", image_gen);
(void) FormatLocaleFile(stderr,
" -fx 'ii=i+page.x%+lf+0.5; jj=j+page.y%+lf+0.5;\n",-coeff[4],
-coeff[5]);
(void) FormatLocaleFile(stderr," ii=ii/%+lf;\n",coeff[1]);
(void) FormatLocaleFile(stderr," xx=%lf*tan(ii)%+lf;\n",coeff[1],
coeff[2] );
(void) FormatLocaleFile(stderr," yy=jj/cos(ii)%+lf;\n",coeff[3]);
(void) FormatLocaleFile(stderr," %s' \\\n", lookup);
break;
}
case BarrelDistortion:
case BarrelInverseDistortion:
{
double
xc,
yc;
/*
NOTE: This does the barrel roll in pixel coords not image coords
The internal distortion must do it in image coordinates,
so that is what the center coeff (8,9) is given in.
*/
xc=((double)image->columns-1.0)/2.0+image->page.x;
yc=((double)image->rows-1.0)/2.0+image->page.y;
(void) FormatLocaleFile(stderr, "Barrel%s Distort, FX Equivelent:\n",
method == BarrelDistortion ? "" : "Inv");
(void) FormatLocaleFile(stderr, "%s", image_gen);
if ( fabs(coeff[8]-xc-0.5) < 0.1 && fabs(coeff[9]-yc-0.5) < 0.1 )
(void) FormatLocaleFile(stderr," -fx 'xc=(w-1)/2; yc=(h-1)/2;\n");
else
(void) FormatLocaleFile(stderr," -fx 'xc=%lf; yc=%lf;\n",coeff[8]-
0.5,coeff[9]-0.5);
(void) FormatLocaleFile(stderr,
" ii=i-xc; jj=j-yc; rr=hypot(ii,jj);\n");
(void) FormatLocaleFile(stderr,
" ii=ii%s(%lf*rr*rr*rr %+lf*rr*rr %+lf*rr %+lf);\n",
method == BarrelDistortion ? "*" : "/",coeff[0],coeff[1],coeff[2],
coeff[3]);
(void) FormatLocaleFile(stderr,
" jj=jj%s(%lf*rr*rr*rr %+lf*rr*rr %+lf*rr %+lf);\n",
method == BarrelDistortion ? "*" : "/",coeff[4],coeff[5],coeff[6],
coeff[7]);
(void) FormatLocaleFile(stderr," v.p{fx*ii+xc,fy*jj+yc}' \\\n");
}
default:
break;
}
}
/*
The user provided a 'scale' expert option will scale the output image size,
by the factor given allowing for super-sampling of the distorted image
space. Any scaling factors must naturally be halved as a result.
*/
{ const char *artifact;
artifact=GetImageArtifact(image,"distort:scale");
output_scaling = 1.0;
if (artifact != (const char *) NULL) {
output_scaling = fabs(StringToDouble(artifact,(char **) NULL));
geometry.width=(size_t) (output_scaling*geometry.width+0.5);
geometry.height=(size_t) (output_scaling*geometry.height+0.5);
geometry.x=(ssize_t) (output_scaling*geometry.x+0.5);
geometry.y=(ssize_t) (output_scaling*geometry.y+0.5);
if ( output_scaling < 0.1 ) {
coeff = (double *) RelinquishMagickMemory(coeff);
(void) ThrowMagickException(exception,GetMagickModule(),OptionError,
"InvalidArgument","%s", "-set option:distort:scale" );
return((Image *) NULL);
}
output_scaling = 1/output_scaling;
}
}
#define ScaleFilter(F,A,B,C,D) \
ScaleResampleFilter( (F), \
output_scaling*(A), output_scaling*(B), \
output_scaling*(C), output_scaling*(D) )
/*
Initialize the distort image attributes.
*/
distort_image=CloneImage(image,geometry.width,geometry.height,MagickTrue,
exception);
if (distort_image == (Image *) NULL)
{
coeff=(double *) RelinquishMagickMemory(coeff);
return((Image *) NULL);
}
/* if image is ColorMapped - change it to DirectClass */
if (SetImageStorageClass(distort_image,DirectClass,exception) == MagickFalse)
{
coeff=(double *) RelinquishMagickMemory(coeff);
distort_image=DestroyImage(distort_image);
return((Image *) NULL);
}
if ((IsPixelInfoGray(&distort_image->background_color) == MagickFalse) &&
(IsGrayColorspace(distort_image->colorspace) != MagickFalse))
(void) SetImageColorspace(distort_image,sRGBColorspace,exception);
if (distort_image->background_color.alpha_trait != UndefinedPixelTrait)
distort_image->alpha_trait=BlendPixelTrait;
distort_image->page.x=geometry.x;
distort_image->page.y=geometry.y;
ConformPixelInfo(distort_image,&distort_image->matte_color,&invalid,
exception);
{ /* ----- MAIN CODE -----
Sample the source image to each pixel in the distort image.
*/
CacheView
*distort_view;
MagickBooleanType
status;
MagickOffsetType
progress;
PixelInfo
zero;
ResampleFilter
**magick_restrict resample_filter;
ssize_t
j;
status=MagickTrue;
progress=0;
GetPixelInfo(distort_image,&zero);
resample_filter=AcquireResampleFilterThreadSet(image,
UndefinedVirtualPixelMethod,MagickFalse,exception);
distort_view=AcquireAuthenticCacheView(distort_image,exception);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static) shared(progress,status) \
magick_number_threads(image,distort_image,distort_image->rows,1)
#endif
for (j=0; j < (ssize_t) distort_image->rows; j++)
{
const int
id = GetOpenMPThreadId();
double
validity; /* how mathematically valid is this the mapping */
MagickBooleanType
sync;
PixelInfo
pixel; /* pixel color to assign to distorted image */
PointInfo
d,
s; /* transform destination image x,y to source image x,y */
ssize_t
i;
Quantum
*magick_restrict q;
q=QueueCacheViewAuthenticPixels(distort_view,0,j,distort_image->columns,1,
exception);
if (q == (Quantum *) NULL)
{
status=MagickFalse;
continue;
}
pixel=zero;
/* Define constant scaling vectors for Affine Distortions
Other methods are either variable, or use interpolated lookup
*/
switch (method)
{
case AffineDistortion:
case RigidAffineDistortion:
ScaleFilter( resample_filter[id],
coeff[0], coeff[1],
coeff[3], coeff[4] );
break;
default:
break;
}
/* Initialize default pixel validity
* negative: pixel is invalid output 'matte_color'
* 0.0 to 1.0: antialiased, mix with resample output
* 1.0 or greater: use resampled output.
*/
validity = 1.0;
for (i=0; i < (ssize_t) distort_image->columns; i++)
{
/* map pixel coordinate to distortion space coordinate */
d.x = (double) (geometry.x+i+0.5)*output_scaling;
d.y = (double) (geometry.y+j+0.5)*output_scaling;
s = d; /* default is a no-op mapping */
switch (method)
{
case AffineDistortion:
case RigidAffineDistortion:
{
s.x=coeff[0]*d.x+coeff[1]*d.y+coeff[2];
s.y=coeff[3]*d.x+coeff[4]*d.y+coeff[5];
/* Affine partial derivitives are constant -- set above */
break;
}
case PerspectiveDistortion:
{
double
p,n,r,abs_r,abs_c6,abs_c7,scale;
/* perspective is a ratio of affines */
p=coeff[0]*d.x+coeff[1]*d.y+coeff[2];
n=coeff[3]*d.x+coeff[4]*d.y+coeff[5];
r=coeff[6]*d.x+coeff[7]*d.y+1.0;
/* Pixel Validity -- is it a 'sky' or 'ground' pixel */
validity = (r*coeff[8] < 0.0) ? 0.0 : 1.0;
/* Determine horizon anti-alias blending */
abs_r = fabs(r)*2;
abs_c6 = fabs(coeff[6]);
abs_c7 = fabs(coeff[7]);
if ( abs_c6 > abs_c7 ) {
if ( abs_r < abs_c6*output_scaling )
validity = 0.5 - coeff[8]*r/(coeff[6]*output_scaling);
}
else if ( abs_r < abs_c7*output_scaling )
validity = 0.5 - coeff[8]*r/(coeff[7]*output_scaling);
/* Perspective Sampling Point (if valid) */
if ( validity > 0.0 ) {
/* divide by r affine, for perspective scaling */
scale = 1.0/r;
s.x = p*scale;
s.y = n*scale;
/* Perspective Partial Derivatives or Scaling Vectors */
scale *= scale;
ScaleFilter( resample_filter[id],
(r*coeff[0] - p*coeff[6])*scale,
(r*coeff[1] - p*coeff[7])*scale,
(r*coeff[3] - n*coeff[6])*scale,
(r*coeff[4] - n*coeff[7])*scale );
}
break;
}
case BilinearReverseDistortion:
{
/* Reversed Mapped is just a simple polynomial */
s.x=coeff[0]*d.x+coeff[1]*d.y+coeff[2]*d.x*d.y+coeff[3];
s.y=coeff[4]*d.x+coeff[5]*d.y
+coeff[6]*d.x*d.y+coeff[7];
/* Bilinear partial derivitives of scaling vectors */
ScaleFilter( resample_filter[id],
coeff[0] + coeff[2]*d.y,
coeff[1] + coeff[2]*d.x,
coeff[4] + coeff[6]*d.y,
coeff[5] + coeff[6]*d.x );
break;
}
case BilinearForwardDistortion:
{
/* Forward mapped needs reversed polynomial equations
* which unfortunatally requires a square root! */
double b,c;
d.x -= coeff[3]; d.y -= coeff[7];
b = coeff[6]*d.x - coeff[2]*d.y + coeff[8];
c = coeff[4]*d.x - coeff[0]*d.y;
validity = 1.0;
/* Handle Special degenerate (non-quadratic) case
* Currently without horizon anti-alising */
if ( fabs(coeff[9]) < MagickEpsilon )
s.y = -c/b;
else {
c = b*b - 2*coeff[9]*c;
if ( c < 0.0 )
validity = 0.0;
else
s.y = ( -b + sqrt(c) )/coeff[9];
}
if ( validity > 0.0 )
s.x = ( d.x - coeff[1]*s.y) / ( coeff[0] + coeff[2]*s.y );
/* NOTE: the sign of the square root should be -ve for parts
where the source image becomes 'flipped' or 'mirrored'.
FUTURE: Horizon handling
FUTURE: Scaling factors or Deritives (how?)
*/
break;
}
#if 0
case BilinearDistortion:
/* Bilinear mapping of any Quadrilateral to any Quadrilateral */
/* UNDER DEVELOPMENT */
break;
#endif
case PolynomialDistortion:
{
/* multi-ordered polynomial */
ssize_t
k;
ssize_t
nterms=(ssize_t)coeff[1];
PointInfo
du,dv; /* the du,dv vectors from unit dx,dy -- derivatives */
s.x=s.y=du.x=du.y=dv.x=dv.y=0.0;
for(k=0; k < nterms; k++) {
s.x += poly_basis_fn(k,d.x,d.y)*coeff[2+k];
du.x += poly_basis_dx(k,d.x,d.y)*coeff[2+k];
du.y += poly_basis_dy(k,d.x,d.y)*coeff[2+k];
s.y += poly_basis_fn(k,d.x,d.y)*coeff[2+k+nterms];
dv.x += poly_basis_dx(k,d.x,d.y)*coeff[2+k+nterms];
dv.y += poly_basis_dy(k,d.x,d.y)*coeff[2+k+nterms];
}
ScaleFilter( resample_filter[id], du.x,du.y,dv.x,dv.y );
break;
}
case ArcDistortion:
{
/* what is the angle and radius in the destination image */
s.x = (double) ((atan2(d.y,d.x) - coeff[0])/Magick2PI);
s.x -= MagickRound(s.x); /* angle */
s.y = hypot(d.x,d.y); /* radius */
/* Arc Distortion Partial Scaling Vectors
Are derived by mapping the perpendicular unit vectors
dR and dA*R*2PI rather than trying to map dx and dy
The results is a very simple orthogonal aligned ellipse.
*/
if ( s.y > MagickEpsilon )
ScaleFilter( resample_filter[id],
(double) (coeff[1]/(Magick2PI*s.y)), 0, 0, coeff[3] );
else
ScaleFilter( resample_filter[id],
distort_image->columns*2, 0, 0, coeff[3] );
/* now scale the angle and radius for source image lookup point */
s.x = s.x*coeff[1] + coeff[4] + image->page.x +0.5;
s.y = (coeff[2] - s.y) * coeff[3] + image->page.y;
break;
}
case PolarDistortion:
{ /* 2D Cartesain to Polar View */
d.x -= coeff[2];
d.y -= coeff[3];
s.x = atan2(d.x,d.y) - (coeff[4]+coeff[5])/2;
s.x /= Magick2PI;
s.x -= MagickRound(s.x);
s.x *= Magick2PI; /* angle - relative to centerline */
s.y = hypot(d.x,d.y); /* radius */
/* Polar Scaling vectors are based on mapping dR and dA vectors
This results in very simple orthogonal scaling vectors
*/
if ( s.y > MagickEpsilon )
ScaleFilter( resample_filter[id],
(double) (coeff[6]/(Magick2PI*s.y)), 0, 0, coeff[7] );
else
ScaleFilter( resample_filter[id],
distort_image->columns*2, 0, 0, coeff[7] );
/* now finish mapping radius/angle to source x,y coords */
s.x = s.x*coeff[6] + (double)image->columns/2.0 + image->page.x;
s.y = (s.y-coeff[1])*coeff[7] + image->page.y;
break;
}
case DePolarDistortion:
{ /* @D Polar to Carteasain */
/* ignore all destination virtual offsets */
d.x = ((double)i+0.5)*output_scaling*coeff[6]+coeff[4];
d.y = ((double)j+0.5)*output_scaling*coeff[7]+coeff[1];
s.x = d.y*sin(d.x) + coeff[2];
s.y = d.y*cos(d.x) + coeff[3];
/* derivatives are usless - better to use SuperSampling */
break;
}
case Cylinder2PlaneDistortion:
{ /* 3D Cylinder to Tangential Plane */
double ax, cx;
/* relative to center of distortion */
d.x -= coeff[4]; d.y -= coeff[5];
d.x /= coeff[1]; /* x' = x/r */
ax=atan(d.x); /* aa = atan(x/r) = u/r */
cx=cos(ax); /* cx = cos(atan(x/r)) = 1/sqrt(x^2+u^2) */
s.x = coeff[1]*ax; /* u = r*atan(x/r) */
s.y = d.y*cx; /* v = y*cos(u/r) */
/* derivatives... (see personnal notes) */
ScaleFilter( resample_filter[id],
1.0/(1.0+d.x*d.x), 0.0, -d.x*s.y*cx*cx/coeff[1], s.y/d.y );
#if 0
if ( i == 0 && j == 0 ) {
fprintf(stderr, "x=%lf y=%lf u=%lf v=%lf\n", d.x*coeff[1], d.y, s.x, s.y);
fprintf(stderr, "phi = %lf\n", (double)(ax * 180.0/MagickPI) );
fprintf(stderr, "du/dx=%lf du/dx=%lf dv/dx=%lf dv/dy=%lf\n",
1.0/(1.0+d.x*d.x), 0.0, -d.x*s.y*cx*cx/coeff[1], s.y/d.y );
fflush(stderr); }
#endif
/* add center of distortion in source */
s.x += coeff[2]; s.y += coeff[3];
break;
}
case Plane2CylinderDistortion:
{ /* 3D Cylinder to Tangential Plane */
/* relative to center of distortion */
d.x -= coeff[4]; d.y -= coeff[5];
/* is pixel valid - horizon of a infinite Virtual-Pixel Plane
* (see Anthony Thyssen's personal note) */
validity = (double) (coeff[1]*MagickPI2 - fabs(d.x))/output_scaling + 0.5;
if ( validity > 0.0 ) {
double cx,tx;
d.x /= coeff[1]; /* x'= x/r */
cx = 1/cos(d.x); /* cx = 1/cos(x/r) */
tx = tan(d.x); /* tx = tan(x/r) */
s.x = coeff[1]*tx; /* u = r * tan(x/r) */
s.y = d.y*cx; /* v = y / cos(x/r) */
/* derivatives... (see Anthony Thyssen's personal notes) */
ScaleFilter( resample_filter[id],
cx*cx, 0.0, s.y*cx/coeff[1], cx );
#if 0
/*if ( i == 0 && j == 0 )*/
if ( d.x == 0.5 && d.y == 0.5 ) {
fprintf(stderr, "x=%lf y=%lf u=%lf v=%lf\n", d.x*coeff[1], d.y, s.x, s.y);
fprintf(stderr, "radius = %lf phi = %lf validity = %lf\n",
coeff[1], (double)(d.x * 180.0/MagickPI), validity );
fprintf(stderr, "du/dx=%lf du/dx=%lf dv/dx=%lf dv/dy=%lf\n",
cx*cx, 0.0, s.y*cx/coeff[1], cx);
fflush(stderr); }
#endif
}
/* add center of distortion in source */
s.x += coeff[2]; s.y += coeff[3];
break;
}
case BarrelDistortion:
case BarrelInverseDistortion:
{ /* Lens Barrel Distionion Correction */
double r,fx,fy,gx,gy;
/* Radial Polynomial Distortion (de-normalized) */
d.x -= coeff[8];
d.y -= coeff[9];
r = sqrt(d.x*d.x+d.y*d.y);
if ( r > MagickEpsilon ) {
fx = ((coeff[0]*r + coeff[1])*r + coeff[2])*r + coeff[3];
fy = ((coeff[4]*r + coeff[5])*r + coeff[6])*r + coeff[7];
gx = ((3*coeff[0]*r + 2*coeff[1])*r + coeff[2])/r;
gy = ((3*coeff[4]*r + 2*coeff[5])*r + coeff[6])/r;
/* adjust functions and scaling for 'inverse' form */
if ( method == BarrelInverseDistortion ) {
fx = 1/fx; fy = 1/fy;
gx *= -fx*fx; gy *= -fy*fy;
}
/* Set the source pixel to lookup and EWA derivative vectors */
s.x = d.x*fx + coeff[8];
s.y = d.y*fy + coeff[9];
ScaleFilter( resample_filter[id],
gx*d.x*d.x + fx, gx*d.x*d.y,
gy*d.x*d.y, gy*d.y*d.y + fy );
}
else {
/* Special handling to avoid divide by zero when r==0
**
** The source and destination pixels match in this case
** which was set at the top of the loop using s = d;
** otherwise... s.x=coeff[8]; s.y=coeff[9];
*/
if ( method == BarrelDistortion )
ScaleFilter( resample_filter[id],
coeff[3], 0, 0, coeff[7] );
else /* method == BarrelInverseDistortion */
/* FUTURE, trap for D==0 causing division by zero */
ScaleFilter( resample_filter[id],
1.0/coeff[3], 0, 0, 1.0/coeff[7] );
}
break;
}
case ShepardsDistortion:
{ /* Shepards Method, or Inverse Weighted Distance for
displacement around the destination image control points
The input arguments are the coefficents to the function.
This is more of a 'displacement' function rather than an
absolute distortion function.
Note: We can not determine derivatives using shepards method
so only a point sample interpolatation can be used.
*/
double
denominator;
size_t
k;
denominator = s.x = s.y = 0;
for(k=0; k<number_arguments; k+=4) {
double weight =
((double)d.x-arguments[k+2])*((double)d.x-arguments[k+2])
+ ((double)d.y-arguments[k+3])*((double)d.y-arguments[k+3]);
weight = pow(weight,coeff[0]); /* shepards power factor */
weight = ( weight < 1.0 ) ? 1.0 : 1.0/weight;
s.x += (arguments[ k ]-arguments[k+2])*weight;
s.y += (arguments[k+1]-arguments[k+3])*weight;
denominator += weight;
}
s.x /= denominator;
s.y /= denominator;
s.x += d.x; /* make it as relative displacement */
s.y += d.y;
break;
}
default:
break; /* use the default no-op given above */
}
/* map virtual canvas location back to real image coordinate */
if ( bestfit && method != ArcDistortion ) {
s.x -= image->page.x;
s.y -= image->page.y;
}
s.x -= 0.5;
s.y -= 0.5;
if ( validity <= 0.0 ) {
/* result of distortion is an invalid pixel - don't resample */
SetPixelViaPixelInfo(distort_image,&invalid,q);
}
else {
/* resample the source image to find its correct color */
(void) ResamplePixelColor(resample_filter[id],s.x,s.y,&pixel,
exception);
/* if validity between 0.0 and 1.0 mix result with invalid pixel */
if ( validity < 1.0 ) {
/* Do a blend of sample color and invalid pixel */
/* should this be a 'Blend', or an 'Over' compose */
CompositePixelInfoBlend(&pixel,validity,&invalid,(1.0-validity),
&pixel);
}
SetPixelViaPixelInfo(distort_image,&pixel,q);
}
q+=GetPixelChannels(distort_image);
}
sync=SyncCacheViewAuthenticPixels(distort_view,exception);
if (sync == MagickFalse)
status=MagickFalse;
if (image->progress_monitor != (MagickProgressMonitor) NULL)
{
MagickBooleanType
proceed;
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp atomic
#endif
progress++;
proceed=SetImageProgress(image,DistortImageTag,progress,image->rows);
if (proceed == MagickFalse)
status=MagickFalse;
}
}
distort_view=DestroyCacheView(distort_view);
resample_filter=DestroyResampleFilterThreadSet(resample_filter);
if (status == MagickFalse)
distort_image=DestroyImage(distort_image);
}
/* Arc does not return an offset unless 'bestfit' is in effect
And the user has not provided an overriding 'viewport'.
*/
if ( method == ArcDistortion && !bestfit && !viewport_given ) {
distort_image->page.x = 0;
distort_image->page.y = 0;
}
coeff=(double *) RelinquishMagickMemory(coeff);
return(distort_image);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% R o t a t e I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% RotateImage() creates a new image that is a rotated copy of an existing
% one. Positive angles rotate counter-clockwise (right-hand rule), while
% negative angles rotate clockwise. Rotated images are usually larger than
% the originals and have 'empty' triangular corners. X axis. Empty
% triangles left over from shearing the image are filled with the background
% color defined by member 'background_color' of the image. RotateImage
% allocates the memory necessary for the new Image structure and returns a
% pointer to the new image.
%
% The format of the RotateImage method is:
%
% Image *RotateImage(const Image *image,const double degrees,
% ExceptionInfo *exception)
%
% A description of each parameter follows.
%
% o image: the image.
%
% o degrees: Specifies the number of degrees to rotate the image.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport Image *RotateImage(const Image *image,const double degrees,
ExceptionInfo *exception)
{
Image
*distort_image,
*rotate_image;
double
angle;
PointInfo
shear;
size_t
rotations;
/*
Adjust rotation angle.
*/
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickCoreSignature);
angle=fmod(degrees,360.0);
while (angle < -45.0)
angle+=360.0;
for (rotations=0; angle > 45.0; rotations++)
angle-=90.0;
rotations%=4;
shear.x=(-tan((double) DegreesToRadians(angle)/2.0));
shear.y=sin((double) DegreesToRadians(angle));
if ((fabs(shear.x) < MagickEpsilon) && (fabs(shear.y) < MagickEpsilon))
return(IntegralRotateImage(image,rotations,exception));
distort_image=CloneImage(image,0,0,MagickTrue,exception);
if (distort_image == (Image *) NULL)
return((Image *) NULL);
(void) SetImageVirtualPixelMethod(distort_image,BackgroundVirtualPixelMethod,
exception);
rotate_image=DistortImage(distort_image,ScaleRotateTranslateDistortion,1,
°rees,MagickTrue,exception);
distort_image=DestroyImage(distort_image);
return(rotate_image);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% S p a r s e C o l o r I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% SparseColorImage(), given a set of coordinates, interpolates the colors
% found at those coordinates, across the whole image, using various methods.
%
% The format of the SparseColorImage() method is:
%
% Image *SparseColorImage(const Image *image,
% const SparseColorMethod method,const size_t number_arguments,
% const double *arguments,ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image to be filled in.
%
% o method: the method to fill in the gradient between the control points.
%
% The methods used for SparseColor() are often simular to methods
% used for DistortImage(), and even share the same code for determination
% of the function coefficents, though with more dimensions (or resulting
% values).
%
% o number_arguments: the number of arguments given.
%
% o arguments: array of floating point arguments for this method--
% x,y,color_values-- with color_values given as normalized values.
%
% o exception: return any errors or warnings in this structure
%
*/
MagickExport Image *SparseColorImage(const Image *image,
const SparseColorMethod method,const size_t number_arguments,
const double *arguments,ExceptionInfo *exception)
{
#define SparseColorTag "Distort/SparseColor"
SparseColorMethod
sparse_method;
double
*coeff;
Image
*sparse_image;
size_t
number_colors;
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickCoreSignature);
/* Determine number of color values needed per control point */
number_colors=0;
if ((GetPixelRedTraits(image) & UpdatePixelTrait) != 0)
number_colors++;
if ((GetPixelGreenTraits(image) & UpdatePixelTrait) != 0)
number_colors++;
if ((GetPixelBlueTraits(image) & UpdatePixelTrait) != 0)
number_colors++;
if (((GetPixelBlackTraits(image) & UpdatePixelTrait) != 0) &&
(image->colorspace == CMYKColorspace))
number_colors++;
if (((GetPixelAlphaTraits(image) & UpdatePixelTrait) != 0) &&
(image->alpha_trait != UndefinedPixelTrait))
number_colors++;
/*
Convert input arguments into mapping coefficients, this this case
we are mapping (distorting) colors, rather than coordinates.
*/
{ DistortMethod
distort_method;
distort_method=(DistortMethod) method;
if ( distort_method >= SentinelDistortion )
distort_method = ShepardsDistortion; /* Pretend to be Shepards */
coeff = GenerateCoefficients(image, &distort_method, number_arguments,
arguments, number_colors, exception);
if ( coeff == (double *) NULL )
return((Image *) NULL);
/*
Note some Distort Methods may fall back to other simpler methods,
Currently the only fallback of concern is Bilinear to Affine
(Barycentric), which is alaso sparse_colr method. This also ensures
correct two and one color Barycentric handling.
*/
sparse_method = (SparseColorMethod) distort_method;
if ( distort_method == ShepardsDistortion )
sparse_method = method; /* return non-distort methods to normal */
if ( sparse_method == InverseColorInterpolate )
coeff[0]=0.5; /* sqrt() the squared distance for inverse */
}
/* Verbose output */
if (IsStringTrue(GetImageArtifact(image,"verbose")) != MagickFalse) {
switch (sparse_method) {
case BarycentricColorInterpolate:
{
ssize_t x=0;
(void) FormatLocaleFile(stderr, "Barycentric Sparse Color:\n");
if ((GetPixelRedTraits(image) & UpdatePixelTrait) != 0)
(void) FormatLocaleFile(stderr, " -channel R -fx '%+lf*i %+lf*j %+lf' \\\n",
coeff[x], coeff[x+1], coeff[x+2]),x+=3;
if ((GetPixelGreenTraits(image) & UpdatePixelTrait) != 0)
(void) FormatLocaleFile(stderr, " -channel G -fx '%+lf*i %+lf*j %+lf' \\\n",
coeff[x], coeff[x+1], coeff[x+2]),x+=3;
if ((GetPixelBlueTraits(image) & UpdatePixelTrait) != 0)
(void) FormatLocaleFile(stderr, " -channel B -fx '%+lf*i %+lf*j %+lf' \\\n",
coeff[x], coeff[x+1], coeff[x+2]),x+=3;
if (((GetPixelBlackTraits(image) & UpdatePixelTrait) != 0) &&
(image->colorspace == CMYKColorspace))
(void) FormatLocaleFile(stderr, " -channel K -fx '%+lf*i %+lf*j %+lf' \\\n",
coeff[x], coeff[x+1], coeff[x+2]),x+=3;
if (((GetPixelAlphaTraits(image) & UpdatePixelTrait) != 0) &&
(image->alpha_trait != UndefinedPixelTrait))
(void) FormatLocaleFile(stderr, " -channel A -fx '%+lf*i %+lf*j %+lf' \\\n",
coeff[x], coeff[x+1], coeff[x+2]),x+=3;
break;
}
case BilinearColorInterpolate:
{
ssize_t x=0;
(void) FormatLocaleFile(stderr, "Bilinear Sparse Color\n");
if ((GetPixelRedTraits(image) & UpdatePixelTrait) != 0)
(void) FormatLocaleFile(stderr, " -channel R -fx '%+lf*i %+lf*j %+lf*i*j %+lf;\n",
coeff[ x ], coeff[x+1],
coeff[x+2], coeff[x+3]),x+=4;
if ((GetPixelGreenTraits(image) & UpdatePixelTrait) != 0)
(void) FormatLocaleFile(stderr, " -channel G -fx '%+lf*i %+lf*j %+lf*i*j %+lf;\n",
coeff[ x ], coeff[x+1],
coeff[x+2], coeff[x+3]),x+=4;
if ((GetPixelBlueTraits(image) & UpdatePixelTrait) != 0)
(void) FormatLocaleFile(stderr, " -channel B -fx '%+lf*i %+lf*j %+lf*i*j %+lf;\n",
coeff[ x ], coeff[x+1],
coeff[x+2], coeff[x+3]),x+=4;
if (((GetPixelBlackTraits(image) & UpdatePixelTrait) != 0) &&
(image->colorspace == CMYKColorspace))
(void) FormatLocaleFile(stderr, " -channel K -fx '%+lf*i %+lf*j %+lf*i*j %+lf;\n",
coeff[ x ], coeff[x+1],
coeff[x+2], coeff[x+3]),x+=4;
if (((GetPixelAlphaTraits(image) & UpdatePixelTrait) != 0) &&
(image->alpha_trait != UndefinedPixelTrait))
(void) FormatLocaleFile(stderr, " -channel A -fx '%+lf*i %+lf*j %+lf*i*j %+lf;\n",
coeff[ x ], coeff[x+1],
coeff[x+2], coeff[x+3]),x+=4;
break;
}
default:
/* sparse color method is too complex for FX emulation */
break;
}
}
/* Generate new image for generated interpolated gradient.
* ASIDE: Actually we could have just replaced the colors of the original
* image, but IM Core policy, is if storage class could change then clone
* the image.
*/
sparse_image=CloneImage(image,0,0,MagickTrue,exception);
if (sparse_image == (Image *) NULL)
return((Image *) NULL);
if (SetImageStorageClass(sparse_image,DirectClass,exception) == MagickFalse)
{ /* if image is ColorMapped - change it to DirectClass */
sparse_image=DestroyImage(sparse_image);
return((Image *) NULL);
}
{ /* ----- MAIN CODE ----- */
CacheView
*sparse_view;
MagickBooleanType
status;
MagickOffsetType
progress;
ssize_t
j;
status=MagickTrue;
progress=0;
sparse_view=AcquireAuthenticCacheView(sparse_image,exception);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static) shared(progress,status) \
magick_number_threads(image,sparse_image,sparse_image->rows,1)
#endif
for (j=0; j < (ssize_t) sparse_image->rows; j++)
{
MagickBooleanType
sync;
PixelInfo
pixel; /* pixel to assign to distorted image */
ssize_t
i;
Quantum
*magick_restrict q;
q=GetCacheViewAuthenticPixels(sparse_view,0,j,sparse_image->columns,
1,exception);
if (q == (Quantum *) NULL)
{
status=MagickFalse;
continue;
}
GetPixelInfo(sparse_image,&pixel);
for (i=0; i < (ssize_t) image->columns; i++)
{
GetPixelInfoPixel(image,q,&pixel);
switch (sparse_method)
{
case BarycentricColorInterpolate:
{
ssize_t x=0;
if ((GetPixelRedTraits(image) & UpdatePixelTrait) != 0)
pixel.red = coeff[x]*i +coeff[x+1]*j
+coeff[x+2], x+=3;
if ((GetPixelGreenTraits(image) & UpdatePixelTrait) != 0)
pixel.green = coeff[x]*i +coeff[x+1]*j
+coeff[x+2], x+=3;
if ((GetPixelBlueTraits(image) & UpdatePixelTrait) != 0)
pixel.blue = coeff[x]*i +coeff[x+1]*j
+coeff[x+2], x+=3;
if (((GetPixelBlackTraits(image) & UpdatePixelTrait) != 0) &&
(image->colorspace == CMYKColorspace))
pixel.black = coeff[x]*i +coeff[x+1]*j
+coeff[x+2], x+=3;
if (((GetPixelAlphaTraits(image) & UpdatePixelTrait) != 0) &&
(image->alpha_trait != UndefinedPixelTrait))
pixel.alpha = coeff[x]*i +coeff[x+1]*j
+coeff[x+2], x+=3;
break;
}
case BilinearColorInterpolate:
{
ssize_t x=0;
if ((GetPixelRedTraits(image) & UpdatePixelTrait) != 0)
pixel.red = coeff[x]*i + coeff[x+1]*j +
coeff[x+2]*i*j + coeff[x+3], x+=4;
if ((GetPixelGreenTraits(image) & UpdatePixelTrait) != 0)
pixel.green = coeff[x]*i + coeff[x+1]*j +
coeff[x+2]*i*j + coeff[x+3], x+=4;
if ((GetPixelBlueTraits(image) & UpdatePixelTrait) != 0)
pixel.blue = coeff[x]*i + coeff[x+1]*j +
coeff[x+2]*i*j + coeff[x+3], x+=4;
if (((GetPixelBlackTraits(image) & UpdatePixelTrait) != 0) &&
(image->colorspace == CMYKColorspace))
pixel.black = coeff[x]*i + coeff[x+1]*j +
coeff[x+2]*i*j + coeff[x+3], x+=4;
if (((GetPixelAlphaTraits(image) & UpdatePixelTrait) != 0) &&
(image->alpha_trait != UndefinedPixelTrait))
pixel.alpha = coeff[x]*i + coeff[x+1]*j +
coeff[x+2]*i*j + coeff[x+3], x+=4;
break;
}
case InverseColorInterpolate:
case ShepardsColorInterpolate:
{ /* Inverse (Squared) Distance weights average (IDW) */
size_t
k;
double
denominator;
if ((GetPixelRedTraits(image) & UpdatePixelTrait) != 0)
pixel.red=0.0;
if ((GetPixelGreenTraits(image) & UpdatePixelTrait) != 0)
pixel.green=0.0;
if ((GetPixelBlueTraits(image) & UpdatePixelTrait) != 0)
pixel.blue=0.0;
if (((GetPixelBlackTraits(image) & UpdatePixelTrait) != 0) &&
(image->colorspace == CMYKColorspace))
pixel.black=0.0;
if (((GetPixelAlphaTraits(image) & UpdatePixelTrait) != 0) &&
(image->alpha_trait != UndefinedPixelTrait))
pixel.alpha=0.0;
denominator = 0.0;
for(k=0; k<number_arguments; k+=2+number_colors) {
ssize_t x=(ssize_t) k+2;
double weight =
((double)i-arguments[ k ])*((double)i-arguments[ k ])
+ ((double)j-arguments[k+1])*((double)j-arguments[k+1]);
weight = pow(weight,coeff[0]); /* inverse of power factor */
weight = ( weight < 1.0 ) ? 1.0 : 1.0/weight;
if ((GetPixelRedTraits(image) & UpdatePixelTrait) != 0)
pixel.red += arguments[x++]*weight;
if ((GetPixelGreenTraits(image) & UpdatePixelTrait) != 0)
pixel.green += arguments[x++]*weight;
if ((GetPixelBlueTraits(image) & UpdatePixelTrait) != 0)
pixel.blue += arguments[x++]*weight;
if (((GetPixelBlackTraits(image) & UpdatePixelTrait) != 0) &&
(image->colorspace == CMYKColorspace))
pixel.black += arguments[x++]*weight;
if (((GetPixelAlphaTraits(image) & UpdatePixelTrait) != 0) &&
(image->alpha_trait != UndefinedPixelTrait))
pixel.alpha += arguments[x++]*weight;
denominator += weight;
}
if ((GetPixelRedTraits(image) & UpdatePixelTrait) != 0)
pixel.red/=denominator;
if ((GetPixelGreenTraits(image) & UpdatePixelTrait) != 0)
pixel.green/=denominator;
if ((GetPixelBlueTraits(image) & UpdatePixelTrait) != 0)
pixel.blue/=denominator;
if (((GetPixelBlackTraits(image) & UpdatePixelTrait) != 0) &&
(image->colorspace == CMYKColorspace))
pixel.black/=denominator;
if (((GetPixelAlphaTraits(image) & UpdatePixelTrait) != 0) &&
(image->alpha_trait != UndefinedPixelTrait))
pixel.alpha/=denominator;
break;
}
case ManhattanColorInterpolate:
{
size_t
k;
double
minimum = MagickMaximumValue;
/*
Just use the closest control point you can find!
*/
for(k=0; k<number_arguments; k+=2+number_colors) {
double distance =
fabs((double)i-arguments[ k ])
+ fabs((double)j-arguments[k+1]);
if ( distance < minimum ) {
ssize_t x=(ssize_t) k+2;
if ((GetPixelRedTraits(image) & UpdatePixelTrait) != 0)
pixel.red=arguments[x++];
if ((GetPixelGreenTraits(image) & UpdatePixelTrait) != 0)
pixel.green=arguments[x++];
if ((GetPixelBlueTraits(image) & UpdatePixelTrait) != 0)
pixel.blue=arguments[x++];
if (((GetPixelBlackTraits(image) & UpdatePixelTrait) != 0) &&
(image->colorspace == CMYKColorspace))
pixel.black=arguments[x++];
if (((GetPixelAlphaTraits(image) & UpdatePixelTrait) != 0) &&
(image->alpha_trait != UndefinedPixelTrait))
pixel.alpha=arguments[x++];
minimum = distance;
}
}
break;
}
case VoronoiColorInterpolate:
default:
{
size_t
k;
double
minimum = MagickMaximumValue;
/*
Just use the closest control point you can find!
*/
for (k=0; k<number_arguments; k+=2+number_colors) {
double distance =
((double)i-arguments[ k ])*((double)i-arguments[ k ])
+ ((double)j-arguments[k+1])*((double)j-arguments[k+1]);
if ( distance < minimum ) {
ssize_t x=(ssize_t) k+2;
if ((GetPixelRedTraits(image) & UpdatePixelTrait) != 0)
pixel.red=arguments[x++];
if ((GetPixelGreenTraits(image) & UpdatePixelTrait) != 0)
pixel.green=arguments[x++];
if ((GetPixelBlueTraits(image) & UpdatePixelTrait) != 0)
pixel.blue=arguments[x++];
if (((GetPixelBlackTraits(image) & UpdatePixelTrait) != 0) &&
(image->colorspace == CMYKColorspace))
pixel.black=arguments[x++];
if (((GetPixelAlphaTraits(image) & UpdatePixelTrait) != 0) &&
(image->alpha_trait != UndefinedPixelTrait))
pixel.alpha=arguments[x++];
minimum = distance;
}
}
break;
}
}
/* set the color directly back into the source image */
if ((GetPixelRedTraits(image) & UpdatePixelTrait) != 0)
pixel.red=(MagickRealType) ClampPixel(QuantumRange*pixel.red);
if ((GetPixelGreenTraits(image) & UpdatePixelTrait) != 0)
pixel.green=(MagickRealType) ClampPixel(QuantumRange*pixel.green);
if ((GetPixelBlueTraits(image) & UpdatePixelTrait) != 0)
pixel.blue=(MagickRealType) ClampPixel(QuantumRange*pixel.blue);
if (((GetPixelBlackTraits(image) & UpdatePixelTrait) != 0) &&
(image->colorspace == CMYKColorspace))
pixel.black=(MagickRealType) ClampPixel(QuantumRange*pixel.black);
if (((GetPixelAlphaTraits(image) & UpdatePixelTrait) != 0) &&
(image->alpha_trait != UndefinedPixelTrait))
pixel.alpha=(MagickRealType) ClampPixel(QuantumRange*pixel.alpha);
SetPixelViaPixelInfo(sparse_image,&pixel,q);
q+=GetPixelChannels(sparse_image);
}
sync=SyncCacheViewAuthenticPixels(sparse_view,exception);
if (sync == MagickFalse)
status=MagickFalse;
if (image->progress_monitor != (MagickProgressMonitor) NULL)
{
MagickBooleanType
proceed;
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp atomic
#endif
progress++;
proceed=SetImageProgress(image,SparseColorTag,progress,image->rows);
if (proceed == MagickFalse)
status=MagickFalse;
}
}
sparse_view=DestroyCacheView(sparse_view);
if (status == MagickFalse)
sparse_image=DestroyImage(sparse_image);
}
coeff = (double *) RelinquishMagickMemory(coeff);
return(sparse_image);
}
|
LAGraph_pagerankx4.c | //------------------------------------------------------------------------------
// LAGraph_pagerankx4: pagerank using a real semiring
//------------------------------------------------------------------------------
/*
LAGraph: graph algorithms based on GraphBLAS
Copyright 2020 LAGraph Contributors.
(see Contributors.txt for a full list of Contributors; see
ContributionInstructions.txt for information on how you can Contribute to
this project).
All Rights Reserved.
NO WARRANTY. THIS MATERIAL IS FURNISHED ON AN "AS-IS" BASIS. THE LAGRAPH
CONTRIBUTORS MAKE NO WARRANTIES OF ANY KIND, EITHER EXPRESSED OR IMPLIED,
AS TO ANY MATTER INCLUDING, BUT NOT LIMITED TO, WARRANTY OF FITNESS FOR
PURPOSE OR MERCHANTABILITY, EXCLUSIVITY, OR RESULTS OBTAINED FROM USE OF
THE MATERIAL. THE CONTRIBUTORS DO NOT MAKE ANY WARRANTY OF ANY KIND WITH
RESPECT TO FREEDOM FROM PATENT, TRADEMARK, OR COPYRIGHT INFRINGEMENT.
Released under a BSD license, please see the LICENSE file distributed with
this Software or contact permission@sei.cmu.edu for full terms.
Created, in part, with funding and support from the United States
Government. (see Acknowledgments.txt file).
This program includes and/or can make use of certain third party source
code, object code, documentation and other files ("Third Party Software").
See LICENSE file for more details.
*/
//------------------------------------------------------------------------------
// LAGraph_pagerankx4: GAP-style PageRank, with import/export
// Tim Davis and Mohsen Aznaveh.
// See also LAGraph_pagerank3f, for the same computation without import/export.
// This version is just slightly faster than LAGraph_pagerank3f (perhaps 10%
// at most, sometimes the difference is smaller).
// This algorithm follows the specification given in the GAP Benchmark Suite:
// https://arxiv.org/abs/1508.03619 which assumes that both A and A' are
// already available, as are the row and column degrees.
// The GAP Benchmark algorithm assumes the graph has no nodes with no out-going
// edges (otherwise, a divide-by-zero occurs when dividing by d_out [i] below).
// In terms of the adjacency matrix, it assumes there are no rows in A that
// have no entries.
// For fastest results, the input matrix should stored in GxB_BY_COL format.
// TODO: or use AT by row, since the GAP assumes both A and A' are available.
#include "LAGraph.h"
#define LAGRAPH_FREE_WORK \
{ \
LAGRAPH_FREE (vi) ; \
LAGRAPH_FREE (vx) ; \
LAGRAPH_FREE (wi) ; \
LAGRAPH_FREE (wx) ; \
LAGRAPH_FREE (prior) ; \
GrB_free (&v) ; \
GrB_free (&w) ; \
}
#define LAGRAPH_FREE_ALL \
{ \
LAGRAPH_FREE_WORK ; \
GrB_free (result) ; \
}
GrB_Info LAGraph_pagerankx4 // PageRank definition
(
GrB_Vector *result, // output: array of LAGraph_PageRank structs
GrB_Matrix A, // binary input graph, not modified
const float *LA_RESTRICT d_out, // out degree of each node (GrB_FP32, size n)
float damping, // damping factor (typically 0.85)
int itermax, // maximum number of iterations
int *iters // output: number of iterations taken
)
{
//--------------------------------------------------------------------------
// initializations
//--------------------------------------------------------------------------
GrB_Info info ;
GrB_Index n ;
GrB_Vector v = NULL, w = NULL ;
GrB_Index *vi = NULL, *wi = NULL ;
float *LA_RESTRICT vx = NULL ;
float *LA_RESTRICT wx = NULL ;
float *LA_RESTRICT prior = NULL ;
GrB_Type type = GrB_FP32 ;
(*result) = NULL ;
LAGr_Matrix_nrows (&n, A) ;
#if defined ( GxB_SUITESPARSE_GRAPHBLAS ) \
&& ( GxB_IMPLEMENTATION >= GxB_VERSION (3,2,0) )
GrB_Descriptor desc_t0 = GrB_DESC_T0 ;
#else
GrB_Descriptor desc_t0 = LAGraph_desc_tooo ;
#endif
const float teleport = (1 - damping) / n ;
const float tol = 1e-4 ;
float rdiff = 1 ; // first iteration is always done
int nthreads = LAGraph_get_nthreads ( ) ;
nthreads = LAGRAPH_MIN (n, nthreads) ;
nthreads = LAGRAPH_MAX (nthreads, 1) ;
// allocate workspace
vx = LAGraph_malloc (n, sizeof (float)) ;
vi = LAGraph_malloc (n, sizeof (GrB_Index)) ;
wx = LAGraph_malloc (n, sizeof (float)) ;
wi = LAGraph_malloc (n, sizeof (GrB_Index)) ;
prior = LAGraph_malloc (n, sizeof (float)) ;
if (vx == NULL || vi == NULL || prior == NULL || wx == NULL || wi == NULL)
{
LAGRAPH_ERROR ("out of memory", GrB_OUT_OF_MEMORY) ;
}
// v = 1/n
#pragma omp parallel for num_threads(nthreads) schedule(static)
for (int64_t k = 0 ; k < n ; k++)
{
vi [k] = k ;
vx [k] = 1.0 / n ;
wi [k] = k ;
}
//--------------------------------------------------------------------------
// pagerank iterations
//--------------------------------------------------------------------------
for ((*iters) = 0 ; (*iters) < itermax && rdiff > tol ; (*iters)++)
{
// prior = v ;
// v = damping * v ./ dout ;
// w (:) = teleport
#pragma omp parallel for num_threads(nthreads) schedule(static)
for (int64_t i = 0 ; i < n ; i++)
{
prior [i] = vx [i] ;
vx [i] = damping * vx [i] / d_out [i] ;
wx [i] = teleport ;
}
// import wx and wi into w
LAGr_Vector_import (&w, type, n, n, &wi, (void **) (&wx), NULL) ;
// import vx and vi into v
LAGr_Vector_import (&v, type, n, n, &vi, (void **) (&vx), NULL) ;
// w += A'*v
LAGr_mxv (w, NULL, GrB_PLUS_FP32, GxB_PLUS_SECOND_FP32, A, v, desc_t0) ;
// export w to vx and vi (the new score; note the swap)
LAGr_Vector_export (&w, &type, &n, &n, &vi, (void **) (&vx), NULL) ;
// export v to wx and wi (workspace for next iteration)
LAGr_Vector_export (&v, &type, &n, &n, &wi, (void **) (&wx), NULL) ;
// check for convergence
rdiff = 0 ;
#pragma omp parallel for num_threads(nthreads) schedule(static) \
reduction(+:rdiff)
for (int64_t i = 0 ; i < n ; i++)
{
rdiff += fabsf (prior [i] - vx [i]) ;
}
}
//--------------------------------------------------------------------------
// free workspace and return result
//--------------------------------------------------------------------------
LAGr_Vector_import (result, type, n, n, &vi, (void **) (&vx), NULL) ;
LAGRAPH_FREE_WORK ;
return (GrB_SUCCESS) ;
}
|
bml_allocate_ellpack_typed.c | #include "../../macros.h"
#include "../../typed.h"
#include "../bml_allocate.h"
#include "../bml_types.h"
#include "bml_allocate_ellpack.h"
#include "bml_types_ellpack.h"
#include <complex.h>
#include <math.h>
#include <stdlib.h>
#include <string.h>
#include <assert.h>
#ifdef _OPENMP
#include <omp.h>
#endif
/** Clear a matrix.
*
* Numbers of non-zeroes, indeces, and values are set to zero.
*
* \ingroup allocate_group
*
* \param A The matrix.
*/
void TYPED_FUNC(
bml_clear_ellpack) (
bml_matrix_ellpack_t * A)
{
REAL_T *A_value = A->value;
#if defined (USE_OMP_OFFLOAD)
int *A_index = A->index;
int *A_nnz = A->nnz;
int N = A->N;
int M = A->M;
#pragma omp target teams distribute parallel for
for (int i = 0; i < N; i++)
{
A_nnz[i] = 0;
}
#pragma omp target teams distribute parallel for collapse(2) schedule (static, 1)
for (int i = 0; i < N; i++)
{
for (int j = 0; j < M; j++)
{
A_index[ROWMAJOR(i, j, N, M)] = 0;
A_value[ROWMAJOR(i, j, N, M)] = 0.0;
}
}
#else // conditional for offload
#ifdef INTEL_OPT
#pragma omp parallel for simd
#pragma vector aligned
for (int i = 0; i < (A->N * A->M); i++)
{
__assume_aligned(A->index, MALLOC_ALIGNMENT);
__assume_aligned(A_value, MALLOC_ALIGNMENT);
A->index[i] = 0;
A_value[i] = 0.0;
}
#pragma omp parallel for simd
#pragma vector aligned
for (int i = 0; i < A->N; i++)
{
__assume_aligned(A->nnz, MALLOC_ALIGNMENT);
A->nnz[i] = 0;
}
#else
memset(A->nnz, 0, A->N * sizeof(int));
memset(A->index, 0, A->N * A->M * sizeof(int));
memset(A->value, 0.0, A->N * A->M * sizeof(REAL_T));
#endif
#endif // conditional for offload
}
/** Allocate a matrix with uninitialized values.
*
* Note that the matrix \f$ a \f$ will be newly allocated. If it is
* already allocated then the matrix will be deallocated in the
* process.
*
* \ingroup allocate_group
*
* \param matrix_precision The precision of the matrix. The default
* is double precision.
* \param matrix_dimension The matrix size.
* \param distrib_mode The distribution mode.
* \return The matrix.
*/
bml_matrix_ellpack_t
* TYPED_FUNC(bml_noinit_matrix_ellpack) (bml_matrix_dimension_t
matrix_dimension,
bml_distribution_mode_t
distrib_mode)
{
bml_matrix_ellpack_t *A =
bml_noinit_allocate_memory(sizeof(bml_matrix_ellpack_t));
A->matrix_type = ellpack;
A->matrix_precision = MATRIX_PRECISION;
A->N = matrix_dimension.N_rows;
A->M = matrix_dimension.N_nz_max;
A->distribution_mode = distrib_mode;
A->index = bml_noinit_allocate_memory(sizeof(int) * A->N * A->M);
A->nnz = bml_allocate_memory(sizeof(int) * A->N);
A->value = bml_noinit_allocate_memory(sizeof(REAL_T) * A->N * A->M);
A->domain = bml_default_domain(A->N, A->M, distrib_mode);
A->domain2 = bml_default_domain(A->N, A->M, distrib_mode);
#if defined(USE_OMP_OFFLOAD)
int N = A->N;
int M = A->M;
int *A_index = A->index;
int *A_nnz = A->nnz;
REAL_T *A_value = A->value;
#pragma omp target enter data map(alloc:A_value[:N*M], A_index[:N*M], A_nnz[:N])
#pragma omp target update to(A_value[:N*M], A_index[:N*M], A_nnz[:N])
#endif
return A;
}
/** Allocate the zero matrix.
*
* Note that the matrix \f$ a \f$ will be newly allocated. If it is
* already allocated then the matrix will be deallocated in the
* process.
*
* \ingroup allocate_group
*
* \param matrix_precision The precision of the matrix. The default
* is double precision.
* \param N The matrix size.
* \param M The number of non-zeroes per row.
* \param distrib_mode The distribution mode.
* \return The matrix.
*/
bml_matrix_ellpack_t *TYPED_FUNC(
bml_zero_matrix_ellpack) (
int N,
int M,
bml_distribution_mode_t distrib_mode)
{
assert(M > 0);
bml_matrix_ellpack_t *A =
bml_allocate_memory(sizeof(bml_matrix_ellpack_t));
A->matrix_type = ellpack;
A->matrix_precision = MATRIX_PRECISION;
A->N = N;
A->M = M;
A->distribution_mode = distrib_mode;
// need to keep these allocates for host copy
A->index = bml_allocate_memory(sizeof(int) * N * M);
A->nnz = bml_allocate_memory(sizeof(int) * N);
A->value = bml_allocate_memory(sizeof(REAL_T) * N * M);
REAL_T *A_value = A->value;
A->domain = bml_default_domain(N, M, distrib_mode);
A->domain2 = bml_default_domain(N, M, distrib_mode);
#if defined(USE_OMP_OFFLOAD)
int *A_nnz = A->nnz;
int *A_index = A->index;
int NM = N * M;
#pragma omp target enter data map(alloc:A_value[:N*M], A_index[:N*M], A_nnz[:N])
#pragma omp target teams distribute parallel for schedule (static, 1)
for (int i = 0; i < N; i++)
{
A_nnz[i] = 0;
}
#pragma omp target teams distribute parallel for collapse(2) schedule (static, 1)
for (int i = 0; i < N; i++)
{
for (int j = 0; j < M; j++)
{
A_index[ROWMAJOR(i, j, N, M)] = 0;
A_value[ROWMAJOR(i, j, N, M)] = 0.0;
}
}
#endif
return A;
}
/** Allocate a banded random matrix.
*
* Note that the matrix \f$ a \f$ will be newly allocated. If it is
* already allocated then the matrix will be deallocated in the
* process.
*
* \ingroup allocate_group
*
* \param matrix_precision The precision of the matrix. The default
* is double precision.
* \param N The matrix size.
* \param M The number of non-zeroes per row.
* \param distrib_mode The distribution mode.
* \return The matrix.
*/
bml_matrix_ellpack_t *TYPED_FUNC(
bml_banded_matrix_ellpack) (
int N,
int M,
bml_distribution_mode_t distrib_mode)
{
bml_matrix_ellpack_t *A =
TYPED_FUNC(bml_zero_matrix_ellpack) (N, M, distrib_mode);
REAL_T *A_value = A->value;
int *A_index = A->index;
int *A_nnz = A->nnz;
const REAL_T INV_RAND_MAX = 1.0 / (REAL_T) RAND_MAX;
#pragma omp parallel for shared(A_value, A_index, A_nnz)
for (int i = 0; i < N; i++)
{
int jind = 0;
for (int j = (i - M / 2 >= 0 ? i - M / 2 : 0);
j < (i - M / 2 + M <= N ? i - M / 2 + M : N); j++)
{
A_value[ROWMAJOR(i, jind, N, M)] = rand() * INV_RAND_MAX;
A_index[ROWMAJOR(i, jind, N, M)] = j;
jind++;
}
A_nnz[i] = jind;
}
#if defined(USE_OMP_OFFLOAD)
#pragma omp target update to(A_value[:N*M], A_index[:N*M], A_nnz[:N])
#endif
return A;
}
/** Allocate a random matrix.
*
* Note that the matrix \f$ a \f$ will be newly allocated. If it is
* already allocated then the matrix will be deallocated in the
* process.
*
* \ingroup allocate_group
*
* \param matrix_precision The precision of the matrix. The default
* is double precision.
* \param N The matrix size.
* \param M The number of non-zeroes per row.
* \param distrib_mode The distribution mode.
* \return The matrix.
*
* Note: Do not use OpenMP when setting values for a random matrix,
* this makes the operation non-repeatable.
*/
bml_matrix_ellpack_t *TYPED_FUNC(
bml_random_matrix_ellpack) (
int N,
int M,
bml_distribution_mode_t distrib_mode)
{
bml_matrix_ellpack_t *A =
TYPED_FUNC(bml_zero_matrix_ellpack) (N, M, distrib_mode);
REAL_T *A_value = A->value;
int *A_index = A->index;
int *A_nnz = A->nnz;
const REAL_T INV_RAND_MAX = 1.0 / (REAL_T) RAND_MAX;
for (int i = 0; i < N; i++)
{
int jind = 0;
for (int j = 0; j < M; j++)
{
A_value[ROWMAJOR(i, jind, N, M)] = rand() * INV_RAND_MAX;
A_index[ROWMAJOR(i, jind, N, M)] = j;
jind++;
}
A_nnz[i] = jind;
}
#if defined(USE_OMP_OFFLOAD)
#pragma omp target update to(A_value[:N*M], A_index[:N*M], A_nnz[:N])
#endif
return A;
}
/** Allocate the identity matrix.
*
* Note that the matrix \f$ a \f$ will be newly allocated. If it is
* already allocated then the matrix will be deallocated in the
* process.
*
* \ingroup allocate_group
*
* \param matrix_precision The precision of the matrix. The default
* is double precision.
* \param N The matrix size.
* \param M The number of non-zeroes per row.
* \param distrib_mode The distribution mode.
* \return The matrix.
*/
bml_matrix_ellpack_t *TYPED_FUNC(
bml_identity_matrix_ellpack) (
int N,
int M,
bml_distribution_mode_t distrib_mode)
{
bml_matrix_ellpack_t *A =
TYPED_FUNC(bml_zero_matrix_ellpack) (N, M, distrib_mode);
REAL_T *A_value = A->value;
int *A_index = A->index;
int *A_nnz = A->nnz;
#pragma omp parallel for shared(A_value, A_index, A_nnz)
for (int i = 0; i < N; i++)
{
#ifdef INTEL_OPT
__assume_aligned(A_value, MALLOC_ALIGNMENT);
__assume_aligned(A_index, MALLOC_ALIGNMENT);
__assume_aligned(A_nnz, MALLOC_ALIGNMENT);
#endif
A_value[ROWMAJOR(i, 0, N, M)] = (REAL_T) 1.0;
A_index[ROWMAJOR(i, 0, N, M)] = i;
A_nnz[i] = 1;
}
#if defined(USE_OMP_OFFLOAD)
#pragma omp target update to(A_value[:N*M], A_index[:N*M], A_nnz[:N])
#endif
return A;
}
|
trmv_c_csr_u_lo_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_lo_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)
{
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_lo_conj_omp(alpha, A, x, beta, y);
}
|
mysql_netauth_fmt_plug.c | /* Cracker for MySQL network authentication hashes. Hacked together
* during May of 2012 by Dhiru Kholia <dhiru.kholia at gmail.com>.
*
* This software is Copyright (c) 2012, Dhiru Kholia <dhiru.kholia at gmail.com>,
* and it is hereby released to the general public under the following terms:
* Redistribution and use in source and binary forms, with or without modification,
* are permitted. */
#if FMT_EXTERNS_H
extern struct fmt_main fmt_mysqlna;
#elif FMT_REGISTERS_H
john_register_one(&fmt_mysqlna);
#else
#include "sha.h"
#include <string.h>
#include <assert.h>
#include <errno.h>
#include "arch.h"
#include "misc.h"
#include "common.h"
#include "formats.h"
#include "params.h"
#include "options.h"
#ifdef _OPENMP
static int omp_t = 1;
#include <omp.h>
#ifndef OMP_SCALE
#define OMP_SCALE 1024// tuned K8-dual HT
#endif
#endif
#include "memdbg.h"
#define FORMAT_LABEL "mysqlna"
#define FORMAT_NAME "MySQL Network Authentication"
#define ALGORITHM_NAME "SHA1 32/" ARCH_BITS_STR
#define BENCHMARK_COMMENT ""
#define BENCHMARK_LENGTH -1
#define PLAINTEXT_LENGTH 32
#define HEX_LENGTH 40
#define CIPHERTEXT_LENGTH 90
#define BINARY_SIZE 20
#define BINARY_ALIGN MEM_ALIGN_WORD
#define SALT_SIZE sizeof(struct custom_salt)
#define SALT_ALIGN MEM_ALIGN_NONE
#define MIN_KEYS_PER_CRYPT 1
#define MAX_KEYS_PER_CRYPT 1
static struct fmt_tests mysqlna_tests[] = {
{"$mysqlna$2D52396369653E4626293B2F75244D3871507A39*7D63098BEE381A51AA6DF11E307E46BD4F8B6E0C", "openwall"},
{"$mysqlna$615c2b5e79656f7d4931594e5b5d416c7b483365*c3a70da2874db890eb2f0a5e3ea80b2ed17da0d0", "openwall"},
{"$mysqlna$295a687c59275452214b366b39776d3f31757b2e*7343f45c94cccd646a1b29bbfad064a9ee5c0380", "overlord magnum"},
{NULL}
};
static char (*saved_key)[PLAINTEXT_LENGTH + 1];
static ARCH_WORD_32 (*crypt_out)[BINARY_SIZE / sizeof(ARCH_WORD_32)];
static struct custom_salt {
char unsigned scramble[20];
} *cur_salt;
static void init(struct fmt_main *self)
{
#ifdef _OPENMP
omp_t = omp_get_max_threads();
self->params.min_keys_per_crypt *= omp_t;
omp_t *= OMP_SCALE;
self->params.max_keys_per_crypt *= omp_t;
#endif
saved_key = mem_calloc(self->params.max_keys_per_crypt,
sizeof(*saved_key));
crypt_out = mem_calloc(self->params.max_keys_per_crypt,
sizeof(*crypt_out));
}
static void done(void)
{
MEM_FREE(crypt_out);
MEM_FREE(saved_key);
}
static int valid(char *ciphertext, struct fmt_main *self)
{
char *p, *q;
if (strncmp(ciphertext, "$mysqlna$", 9))
return 0;
p = ciphertext + 9;
q = strstr(ciphertext, "*");
if(!q)
return 0;
if (q - p != HEX_LENGTH)
return 0;
while (atoi16[ARCH_INDEX(*p)] != 0x7F && p < q)
p++;
if (q - p != 0)
return 0;
if(strlen(p) < HEX_LENGTH)
return 0;
q = p + 1;
while (atoi16[ARCH_INDEX(*q)] != 0x7F)
q++;
return !*q && q - p - 1 == HEX_LENGTH;
}
static char* split(char *ciphertext, int index, struct fmt_main *self)
{
static char out[CIPHERTEXT_LENGTH + 1];
strncpy(out, ciphertext, sizeof(out));
strlwr(out);
return out;
}
static void *get_salt(char *ciphertext)
{
char *ctcopy = strdup(ciphertext);
char *keeptr = ctcopy;
char *p;
int i;
static struct custom_salt cs;
ctcopy += 9; /* skip over "$mysqlna$" */
p = strtokm(ctcopy, "*");
for (i = 0; i < 20; i++)
cs.scramble[i] = atoi16[ARCH_INDEX(p[i * 2])] * 16
+ atoi16[ARCH_INDEX(p[i * 2 + 1])];
MEM_FREE(keeptr);
return (void *)&cs;
}
static void *get_binary(char *ciphertext)
{
static union {
unsigned char c[BINARY_SIZE];
ARCH_WORD dummy;
} buf;
unsigned char *out = buf.c;
char *p;
int i;
p = strrchr(ciphertext, '*') + 1;
for (i = 0; i < BINARY_SIZE; i++) {
out[i] =
(atoi16[ARCH_INDEX(*p)] << 4) |
atoi16[ARCH_INDEX(p[1])];
p += 2;
}
return out;
}
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
{
unsigned char stage1_hash[20];
unsigned char inner_hash[20];
unsigned char token[20];
SHA_CTX ctx;
int i;
unsigned char *p = (unsigned char*)crypt_out[index];
SHA1_Init(&ctx);
SHA1_Update(&ctx, saved_key[index], strlen(saved_key[index]));
SHA1_Final(stage1_hash, &ctx);
SHA1_Init(&ctx);
SHA1_Update(&ctx, stage1_hash, 20);
SHA1_Final(inner_hash, &ctx);
SHA1_Init(&ctx);
SHA1_Update(&ctx, cur_salt->scramble, 20);
SHA1_Update(&ctx, inner_hash, 20);
SHA1_Final(token, &ctx);
for(i = 0; i < 20; i++) {
p[i] = token[i] ^ stage1_hash[i];
}
}
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 mysqlna_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];
}
struct fmt_main fmt_mysqlna = {
{
FORMAT_LABEL,
FORMAT_NAME,
ALGORITHM_NAME,
BENCHMARK_COMMENT,
BENCHMARK_LENGTH,
0,
PLAINTEXT_LENGTH,
BINARY_SIZE,
BINARY_ALIGN,
SALT_SIZE,
SALT_ALIGN,
MIN_KEYS_PER_CRYPT,
MAX_KEYS_PER_CRYPT,
FMT_CASE | FMT_8_BIT | FMT_OMP | FMT_SPLIT_UNIFIES_CASE,
{ NULL },
mysqlna_tests
}, {
init,
done,
fmt_default_reset,
fmt_default_prepare,
valid,
split,
get_binary,
get_salt,
{ NULL },
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,
mysqlna_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 */
|
mandelbrot-4.c | /* The Computer Language Benchmarks Game
* http://benchmarksgame.alioth.debian.org/
contributed by Paolo Bonzini
further optimized by Jason Garrett-Glaser
pthreads added by Eckehard Berns
further optimized by Ryan Henszey
modified by Samy Al Bahra (use GCC atomic builtins)
modified by Kenneth Jonsson
*/
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
typedef double v2df __attribute__ ((vector_size(16))); /* vector of two doubles */
typedef int v4si __attribute__ ((vector_size(16))); /* vector of four ints */
const v2df zero = { 0.0, 0.0 };
const v2df four = { 4.0, 4.0 };
/*
* Constant throughout the program, value depends on N
*/
int bytes_per_row;
double inverse_w;
double inverse_h;
/*
* Program argument: height and width of the image
*/
int N;
/*
* Lookup table for initial real-axis value
*/
v2df *Crvs;
/*
* Mandelbrot bitmap
*/
uint8_t *bitmap;
static void calc_row(int y) {
uint8_t *row_bitmap = bitmap + (bytes_per_row * y);
int x;
const v2df Civ_init = { y*inverse_h-1.0, y*inverse_h-1.0 };
for (x=0; x<N; x+=2)
{
v2df Crv = Crvs[x >> 1];
v2df Civ = Civ_init;
v2df Zrv = zero;
v2df Ziv = zero;
v2df Trv = zero;
v2df Tiv = zero;
int i = 50;
int two_pixels;
v2df is_still_bounded;
do {
Ziv = (Zrv*Ziv) + (Zrv*Ziv) + Civ;
Zrv = Trv - Tiv + Crv;
Trv = Zrv * Zrv;
Tiv = Ziv * Ziv;
/*
* All bits will be set to 1 if 'Trv + Tiv' is less than 4
* and all bits will be set to 0 otherwise. Two elements
* are calculated in parallel here.
*/
is_still_bounded = __builtin_ia32_cmplepd(Trv + Tiv, four);
/*
* Move the sign-bit of the low element to bit 0, move the
* sign-bit of the high element to bit 1. The result is
* that the pixel will be set if the calculation was
* bounded.
*/
two_pixels = __builtin_ia32_movmskpd(is_still_bounded);
} while (--i > 0 && two_pixels);
/*
* The pixel bits must be in the most and second most
* significant position
*/
two_pixels <<= 6;
/*
* Add the two pixels to the bitmap, all bits are
* initially zero since the area was allocated with
* calloc()
*/
row_bitmap[x >> 3] |= (uint8_t) (two_pixels >> (x & 7));
}
}
int main (int argc, char **argv)
{
int i;
N = atoi(argv[1]);
bytes_per_row = (N + 7) >> 3;
inverse_w = 2.0 / (bytes_per_row << 3);
inverse_h = 2.0 / N;
/*
* Crvs must be 16-bytes aligned on some CPU:s.
*/
if (posix_memalign((void**)&Crvs, sizeof(v2df), sizeof(v2df) * N / 2))
return EXIT_FAILURE;
#pragma omp parallel for
for (i = 0; i < N; i+=2) {
v2df Crv = { (i+1.0)*inverse_w-1.5, (i)*inverse_w-1.5 };
Crvs[i >> 1] = Crv;
}
bitmap = calloc(bytes_per_row, N);
if (bitmap == NULL)
return EXIT_FAILURE;
#pragma omp parallel for schedule(static,1)
for (i = 0; i < N; i++)
calc_row(i);
printf("P4\n%d %d\n", N, N);
fwrite(bitmap, bytes_per_row, N, stdout);
free(bitmap);
free(Crvs);
return EXIT_SUCCESS;
}
|
wre.c | #include "wre.h"
#include "wmm.h"
#include "wor.h"
void wdre
(const size_t n, wide K2[static restrict 1], wide RE[static restrict 1], wide OU[static restrict 1], wide OV[static restrict 1],
const double A11[static restrict 1], const double A21[static restrict 1], const double A12[static restrict 1], const double A22[static restrict 1],
const double U11[static restrict 1], const double U21[static restrict 1], const double U12[static restrict 1], const double U22[static restrict 1],
const double V11[static restrict 1], const double V21[static restrict 1], const double V12[static restrict 1], const double V22[static restrict 1],
const double S1[static restrict 1], const double S2[static restrict 1], const double *const S)
{
if (S) {
#ifdef _OPENMP
#pragma omp parallel for default(none) shared(n,K2,RE,OU,OV,A11,A21,A12,A22,U11,U21,U12,U22,V11,V21,V12,V22,S1,S2,S)
#endif /* _OPENMP */
for (size_t i = (size_t)0u; i < n; ++i) {
RE[i] = wdmm
(A11[i], A21[i], A12[i], A22[i], U11[i], U21[i], U12[i], U22[i], V11[i], V21[i], V12[i], V22[i], S1[i], S2[i], S[i], (K2 + i));
OU[i] = wdor(U11[i], U21[i], U12[i], U22[i]);
OV[i] = wdor(V11[i], V21[i], V12[i], V22[i]);
}
}
else {
#ifdef _OPENMP
#pragma omp parallel for default(none) shared(n,K2,RE,OU,OV,A11,A21,A12,A22,U11,U21,U12,U22,V11,V21,V12,V22,S1,S2)
#endif /* _OPENMP */
for (size_t i = (size_t)0u; i < n; ++i) {
RE[i] = wdmm
(A11[i], A21[i], A12[i], A22[i], U11[i], U21[i], U12[i], U22[i], V11[i], V21[i], V12[i], V22[i], S1[i], S2[i], +0.0, (K2 + i));
OU[i] = wdor(U11[i], U21[i], U12[i], U22[i]);
OV[i] = wdor(V11[i], V21[i], V12[i], V22[i]);
}
}
}
void wzre
(const size_t n, wide K2[static restrict 1], wide RE[static restrict 1], wide OU[static restrict 1], wide OV[static restrict 1],
const double A11r[static restrict 1], const double A11i[static restrict 1], const double A21r[static restrict 1], const double A21i[static restrict 1],
const double A12r[static restrict 1], const double A12i[static restrict 1], const double A22r[static restrict 1], const double A22i[static restrict 1],
const double U11r[static restrict 1], const double U11i[static restrict 1], const double U21r[static restrict 1], const double U21i[static restrict 1],
const double U12r[static restrict 1], const double U12i[static restrict 1], const double U22r[static restrict 1], const double U22i[static restrict 1],
const double V11r[static restrict 1], const double V11i[static restrict 1], const double V21r[static restrict 1], const double V21i[static restrict 1],
const double V12r[static restrict 1], const double V12i[static restrict 1], const double V22r[static restrict 1], const double V22i[static restrict 1],
const double S1[static restrict 1], const double S2[static restrict 1], const double *const S)
{
if (S) {
#ifdef _OPENMP
#pragma omp parallel for default(none) shared(n,K2,RE,OU,OV,A11r,A11i,A21r,A21i,A12r,A12i,A22r,A22i,U11r,U11i,U21r,U21i,U12r,U12i,U22r,U22i,V11r,V11i,V21r,V21i,V12r,V12i,V22r,V22i,S1,S2,S)
#endif /* _OPENMP */
for (size_t i = (size_t)0u; i < n; ++i) {
RE[i] = wzmm
(A11r[i], A11i[i], A21r[i], A21i[i], A12r[i], A12i[i], A22r[i], A22i[i],
U11r[i], U11i[i], U21r[i], U21i[i], U12r[i], U12i[i], U22r[i], U22i[i],
V11r[i], V11i[i], V21r[i], V21i[i], V12r[i], V12i[i], V22r[i], V22i[i],
S1[i], S2[i], S[i], (K2 + i));
OU[i] = wzor(U11r[i], U11i[i], U21r[i], U21i[i], U12r[i], U12i[i], U22r[i], U22i[i]);
OV[i] = wzor(V11r[i], V11i[i], V21r[i], V21i[i], V12r[i], V12i[i], V22r[i], V22i[i]);
}
}
else {
#ifdef _OPENMP
#pragma omp parallel for default(none) shared(n,K2,RE,OU,OV,A11r,A11i,A21r,A21i,A12r,A12i,A22r,A22i,U11r,U11i,U21r,U21i,U12r,U12i,U22r,U22i,V11r,V11i,V21r,V21i,V12r,V12i,V22r,V22i,S1,S2)
#endif /* _OPENMP */
for (size_t i = (size_t)0u; i < n; ++i) {
RE[i] = wzmm
(A11r[i], A11i[i], A21r[i], A21i[i], A12r[i], A12i[i], A22r[i], A22i[i],
U11r[i], U11i[i], U21r[i], U21i[i], U12r[i], U12i[i], U22r[i], U22i[i],
V11r[i], V11i[i], V21r[i], V21i[i], V12r[i], V12i[i], V22r[i], V22i[i],
S1[i], S2[i], +0.0, (K2 + i));
OU[i] = wzor(U11r[i], U11i[i], U21r[i], U21i[i], U12r[i], U12i[i], U22r[i], U22i[i]);
OV[i] = wzor(V11r[i], V11i[i], V21r[i], V21i[i], V12r[i], V12i[i], V22r[i], V22i[i]);
}
}
}
int Pwre(FILE f[static 1], const size_t n, const wide K2[static restrict 1], const wide RE[static restrict 1], const wide OU[static restrict 1], const wide OV[static restrict 1])
{
int ret = fprintf(f, "\n\"N\",\"K2\",\"RE\",\"OU\",\"OV\"\n");
if (25 != ret)
return -1;
char s[31];
for (size_t i = (size_t)0u; i < n; ++i) {
ret += fprintf(f, "%zu,%s,", i, xtoa(s, (long double)(K2[i])));
ret += fprintf(f, "%s,", xtoa(s, (long double)(RE[i])));
ret += fprintf(f, "%s,", xtoa(s, (long double)(OU[i])));
ret += fprintf(f, "%s\n", xtoa(s, (long double)(OV[i])));
}
return (fflush(f) ? -2 : ret);
}
int Bwre(FILE f[static 1], const size_t i, const double t, const wide k2, const wide re, const wide ou, const wide ov, const double *const avg)
{
char s[31];
int ret = fprintf(f, "%8zu,", i);
ret += fprintf(f, "%# 13.6f,", t);
ret += fprintf(f, "%s,", xtoa(s, (long double)k2));
ret += fprintf(f, "%s,", xtoa(s, (long double)re));
ret += fprintf(f, "%s,", xtoa(s, (long double)ou));
ret += fprintf(f, "%s", xtoa(s, (long double)ov));
ret += (avg ? fprintf(f, ",%#13.11f\n", *avg) : fprintf(f, "\n"));
return (fflush(f) ? -1 : ret);
}
|
GB_unaryop__ainv_bool_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__ainv_bool_uint16
// op(A') function: GB_tran__ainv_bool_uint16
// C type: bool
// A type: uint16_t
// cast: bool cij = (bool) aij
// unaryop: cij = aij
#define GB_ATYPE \
uint16_t
#define GB_CTYPE \
bool
// 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 ;
// casting
#define GB_CASTING(z, aij) \
bool z = (bool) aij ;
// cij = op (cast (aij))
#define GB_CAST_OP(pC,pA) \
{ \
/* aij = Ax [pA] */ \
GB_GETA (aij, Ax, pA) ; \
/* Cx [pC] = op (cast (aij)) */ \
GB_CASTING (z, aij) ; \
GB_OP (GB_CX (pC), z) ; \
}
// disable this operator and use the generic case if these conditions hold
#define GB_DISABLE \
(GxB_NO_AINV || GxB_NO_BOOL || GxB_NO_UINT16)
//------------------------------------------------------------------------------
// Cx = op (cast (Ax)): apply a unary operator
//------------------------------------------------------------------------------
GrB_Info GB_unop__ainv_bool_uint16
(
bool *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__ainv_bool_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
|
CGOpenMPRuntime.h | //===----- CGOpenMPRuntime.h - Interface to OpenMP Runtimes -----*- 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 provides a class for OpenMP runtime code generation.
//
//===----------------------------------------------------------------------===//
#ifndef LLVM_CLANG_LIB_CODEGEN_CGOPENMPRUNTIME_H
#define LLVM_CLANG_LIB_CODEGEN_CGOPENMPRUNTIME_H
#include "CGValue.h"
#include "clang/AST/DeclOpenMP.h"
#include "clang/AST/GlobalDecl.h"
#include "clang/AST/Type.h"
#include "clang/Basic/OpenMPKinds.h"
#include "clang/Basic/SourceLocation.h"
#include "llvm/ADT/DenseMap.h"
#include "llvm/ADT/PointerIntPair.h"
#include "llvm/ADT/SmallPtrSet.h"
#include "llvm/ADT/StringMap.h"
#include "llvm/ADT/StringSet.h"
#include "llvm/Frontend/OpenMP/OMPConstants.h"
#include "llvm/Frontend/OpenMP/OMPIRBuilder.h"
#include "llvm/IR/Function.h"
#include "llvm/IR/ValueHandle.h"
#include "llvm/Support/AtomicOrdering.h"
namespace llvm {
class ArrayType;
class Constant;
class FunctionType;
class GlobalVariable;
class StructType;
class Type;
class Value;
class OpenMPIRBuilder;
} // namespace llvm
namespace clang {
class Expr;
class OMPDependClause;
class OMPExecutableDirective;
class OMPLoopDirective;
class VarDecl;
class OMPDeclareReductionDecl;
class IdentifierInfo;
namespace CodeGen {
class Address;
class CodeGenFunction;
class CodeGenModule;
/// A basic class for pre|post-action for advanced codegen sequence for OpenMP
/// region.
class PrePostActionTy {
public:
explicit PrePostActionTy() {}
virtual void Enter(CodeGenFunction &CGF) {}
virtual void Exit(CodeGenFunction &CGF) {}
virtual ~PrePostActionTy() {}
};
/// Class provides a way to call simple version of codegen for OpenMP region, or
/// an advanced with possible pre|post-actions in codegen.
class RegionCodeGenTy final {
intptr_t CodeGen;
typedef void (*CodeGenTy)(intptr_t, CodeGenFunction &, PrePostActionTy &);
CodeGenTy Callback;
mutable PrePostActionTy *PrePostAction;
RegionCodeGenTy() = delete;
RegionCodeGenTy &operator=(const RegionCodeGenTy &) = delete;
template <typename Callable>
static void CallbackFn(intptr_t CodeGen, CodeGenFunction &CGF,
PrePostActionTy &Action) {
return (*reinterpret_cast<Callable *>(CodeGen))(CGF, Action);
}
public:
template <typename Callable>
RegionCodeGenTy(
Callable &&CodeGen,
std::enable_if_t<!std::is_same<std::remove_reference_t<Callable>,
RegionCodeGenTy>::value> * = nullptr)
: CodeGen(reinterpret_cast<intptr_t>(&CodeGen)),
Callback(CallbackFn<std::remove_reference_t<Callable>>),
PrePostAction(nullptr) {}
void setAction(PrePostActionTy &Action) const { PrePostAction = &Action; }
void operator()(CodeGenFunction &CGF) const;
};
struct OMPTaskDataTy final {
SmallVector<const Expr *, 4> PrivateVars;
SmallVector<const Expr *, 4> PrivateCopies;
SmallVector<const Expr *, 4> FirstprivateVars;
SmallVector<const Expr *, 4> FirstprivateCopies;
SmallVector<const Expr *, 4> FirstprivateInits;
SmallVector<const Expr *, 4> LastprivateVars;
SmallVector<const Expr *, 4> LastprivateCopies;
SmallVector<const Expr *, 4> ReductionVars;
SmallVector<const Expr *, 4> ReductionOrigs;
SmallVector<const Expr *, 4> ReductionCopies;
SmallVector<const Expr *, 4> ReductionOps;
struct DependData {
OpenMPDependClauseKind DepKind = OMPC_DEPEND_unknown;
const Expr *IteratorExpr = nullptr;
SmallVector<const Expr *, 4> DepExprs;
explicit DependData() = default;
DependData(OpenMPDependClauseKind DepKind, const Expr *IteratorExpr)
: DepKind(DepKind), IteratorExpr(IteratorExpr) {}
};
SmallVector<DependData, 4> Dependences;
llvm::PointerIntPair<llvm::Value *, 1, bool> Final;
llvm::PointerIntPair<llvm::Value *, 1, bool> Schedule;
llvm::PointerIntPair<llvm::Value *, 1, bool> Priority;
llvm::Value *Reductions = nullptr;
unsigned NumberOfParts = 0;
bool Tied = true;
bool Nogroup = false;
bool IsReductionWithTaskMod = false;
bool IsWorksharingReduction = false;
};
/// Class intended to support codegen of all kind of the reduction clauses.
class ReductionCodeGen {
private:
/// Data required for codegen of reduction clauses.
struct ReductionData {
/// Reference to the item shared between tasks to reduce into.
const Expr *Shared = nullptr;
/// Reference to the original item.
const Expr *Ref = nullptr;
/// Helper expression for generation of private copy.
const Expr *Private = nullptr;
/// Helper expression for generation reduction operation.
const Expr *ReductionOp = nullptr;
ReductionData(const Expr *Shared, const Expr *Ref, const Expr *Private,
const Expr *ReductionOp)
: Shared(Shared), Ref(Ref), Private(Private), ReductionOp(ReductionOp) {
}
};
/// List of reduction-based clauses.
SmallVector<ReductionData, 4> ClausesData;
/// List of addresses of shared variables/expressions.
SmallVector<std::pair<LValue, LValue>, 4> SharedAddresses;
/// List of addresses of original variables/expressions.
SmallVector<std::pair<LValue, LValue>, 4> OrigAddresses;
/// Sizes of the reduction items in chars.
SmallVector<std::pair<llvm::Value *, llvm::Value *>, 4> Sizes;
/// Base declarations for the reduction items.
SmallVector<const VarDecl *, 4> BaseDecls;
/// Emits lvalue for shared expression.
LValue emitSharedLValue(CodeGenFunction &CGF, const Expr *E);
/// Emits upper bound for shared expression (if array section).
LValue emitSharedLValueUB(CodeGenFunction &CGF, const Expr *E);
/// Performs aggregate initialization.
/// \param N Number of reduction item in the common list.
/// \param PrivateAddr Address of the corresponding private item.
/// \param SharedLVal Address of the original shared variable.
/// \param DRD Declare reduction construct used for reduction item.
void emitAggregateInitialization(CodeGenFunction &CGF, unsigned N,
Address PrivateAddr, LValue SharedLVal,
const OMPDeclareReductionDecl *DRD);
public:
ReductionCodeGen(ArrayRef<const Expr *> Shareds, ArrayRef<const Expr *> Origs,
ArrayRef<const Expr *> Privates,
ArrayRef<const Expr *> ReductionOps);
/// Emits lvalue for the shared and original reduction item.
/// \param N Number of the reduction item.
void emitSharedOrigLValue(CodeGenFunction &CGF, unsigned N);
/// Emits the code for the variable-modified type, if required.
/// \param N Number of the reduction item.
void emitAggregateType(CodeGenFunction &CGF, unsigned N);
/// Emits the code for the variable-modified type, if required.
/// \param N Number of the reduction item.
/// \param Size Size of the type in chars.
void emitAggregateType(CodeGenFunction &CGF, unsigned N, llvm::Value *Size);
/// Performs initialization of the private copy for the reduction item.
/// \param N Number of the reduction item.
/// \param PrivateAddr Address of the corresponding private item.
/// \param DefaultInit Default initialization sequence that should be
/// performed if no reduction specific initialization is found.
/// \param SharedLVal Address of the original shared variable.
void
emitInitialization(CodeGenFunction &CGF, unsigned N, Address PrivateAddr,
LValue SharedLVal,
llvm::function_ref<bool(CodeGenFunction &)> DefaultInit);
/// Returns true if the private copy requires cleanups.
bool needCleanups(unsigned N);
/// Emits cleanup code for the reduction item.
/// \param N Number of the reduction item.
/// \param PrivateAddr Address of the corresponding private item.
void emitCleanups(CodeGenFunction &CGF, unsigned N, Address PrivateAddr);
/// Adjusts \p PrivatedAddr for using instead of the original variable
/// address in normal operations.
/// \param N Number of the reduction item.
/// \param PrivateAddr Address of the corresponding private item.
Address adjustPrivateAddress(CodeGenFunction &CGF, unsigned N,
Address PrivateAddr);
/// Returns LValue for the reduction item.
LValue getSharedLValue(unsigned N) const { return SharedAddresses[N].first; }
/// Returns LValue for the original reduction item.
LValue getOrigLValue(unsigned N) const { return OrigAddresses[N].first; }
/// Returns the size of the reduction item (in chars and total number of
/// elements in the item), or nullptr, if the size is a constant.
std::pair<llvm::Value *, llvm::Value *> getSizes(unsigned N) const {
return Sizes[N];
}
/// Returns the base declaration of the reduction item.
const VarDecl *getBaseDecl(unsigned N) const { return BaseDecls[N]; }
/// Returns the base declaration of the reduction item.
const Expr *getRefExpr(unsigned N) const { return ClausesData[N].Ref; }
/// Returns true if the initialization of the reduction item uses initializer
/// from declare reduction construct.
bool usesReductionInitializer(unsigned N) const;
};
class CGOpenMPRuntime {
public:
/// Allows to disable automatic handling of functions used in target regions
/// as those marked as `omp declare target`.
class DisableAutoDeclareTargetRAII {
CodeGenModule &CGM;
bool SavedShouldMarkAsGlobal;
public:
DisableAutoDeclareTargetRAII(CodeGenModule &CGM);
~DisableAutoDeclareTargetRAII();
};
/// Manages list of nontemporal decls for the specified directive.
class NontemporalDeclsRAII {
CodeGenModule &CGM;
const bool NeedToPush;
public:
NontemporalDeclsRAII(CodeGenModule &CGM, const OMPLoopDirective &S);
~NontemporalDeclsRAII();
};
/// Maps the expression for the lastprivate variable to the global copy used
/// to store new value because original variables are not mapped in inner
/// parallel regions. Only private copies are captured but we need also to
/// store private copy in shared address.
/// Also, stores the expression for the private loop counter and it
/// threaprivate name.
struct LastprivateConditionalData {
llvm::MapVector<CanonicalDeclPtr<const Decl>, SmallString<16>>
DeclToUniqueName;
LValue IVLVal;
llvm::Function *Fn = nullptr;
bool Disabled = false;
};
/// Manages list of lastprivate conditional decls for the specified directive.
class LastprivateConditionalRAII {
enum class ActionToDo {
DoNotPush,
PushAsLastprivateConditional,
DisableLastprivateConditional,
};
CodeGenModule &CGM;
ActionToDo Action = ActionToDo::DoNotPush;
/// Check and try to disable analysis of inner regions for changes in
/// lastprivate conditional.
void tryToDisableInnerAnalysis(const OMPExecutableDirective &S,
llvm::DenseSet<CanonicalDeclPtr<const Decl>>
&NeedToAddForLPCsAsDisabled) const;
LastprivateConditionalRAII(CodeGenFunction &CGF,
const OMPExecutableDirective &S);
public:
explicit LastprivateConditionalRAII(CodeGenFunction &CGF,
const OMPExecutableDirective &S,
LValue IVLVal);
static LastprivateConditionalRAII disable(CodeGenFunction &CGF,
const OMPExecutableDirective &S);
~LastprivateConditionalRAII();
};
llvm::OpenMPIRBuilder &getOMPBuilder() { return OMPBuilder; }
protected:
CodeGenModule &CGM;
StringRef FirstSeparator, Separator;
/// Constructor allowing to redefine the name separator for the variables.
explicit CGOpenMPRuntime(CodeGenModule &CGM, StringRef FirstSeparator,
StringRef Separator);
/// Creates offloading entry for the provided entry ID \a ID,
/// address \a Addr, size \a Size, and flags \a Flags.
virtual void createOffloadEntry(llvm::Constant *ID, llvm::Constant *Addr,
uint64_t Size, int32_t Flags,
llvm::GlobalValue::LinkageTypes Linkage);
/// Helper to emit outlined function for 'target' directive.
/// \param D Directive to emit.
/// \param ParentName Name of the function that encloses the target region.
/// \param OutlinedFn Outlined function value to be defined by this call.
/// \param OutlinedFnID Outlined function ID value to be defined by this call.
/// \param IsOffloadEntry True if the outlined function is an offload entry.
/// \param CodeGen Lambda codegen specific to an accelerator device.
/// An outlined function may not be an entry if, e.g. the if clause always
/// evaluates to false.
virtual void emitTargetOutlinedFunctionHelper(const OMPExecutableDirective &D,
StringRef ParentName,
llvm::Function *&OutlinedFn,
llvm::Constant *&OutlinedFnID,
bool IsOffloadEntry,
const RegionCodeGenTy &CodeGen);
/// Emits object of ident_t type with info for source location.
/// \param Flags Flags for OpenMP location.
///
llvm::Value *emitUpdateLocation(CodeGenFunction &CGF, SourceLocation Loc,
unsigned Flags = 0);
/// Returns pointer to ident_t type.
llvm::Type *getIdentTyPointerTy();
/// Gets thread id value for the current thread.
///
llvm::Value *getThreadID(CodeGenFunction &CGF, SourceLocation Loc);
/// Get the function name of an outlined region.
// The name can be customized depending on the target.
//
virtual StringRef getOutlinedHelperName() const { return ".omp_outlined."; }
/// Emits \p Callee function call with arguments \p Args with location \p Loc.
void emitCall(CodeGenFunction &CGF, SourceLocation Loc,
llvm::FunctionCallee Callee,
ArrayRef<llvm::Value *> Args = llvm::None) const;
/// Emits address of the word in a memory where current thread id is
/// stored.
virtual Address emitThreadIDAddress(CodeGenFunction &CGF, SourceLocation Loc);
void setLocThreadIdInsertPt(CodeGenFunction &CGF,
bool AtCurrentPoint = false);
void clearLocThreadIdInsertPt(CodeGenFunction &CGF);
/// Check if the default location must be constant.
/// Default is false to support OMPT/OMPD.
virtual bool isDefaultLocationConstant() const { return false; }
/// Returns additional flags that can be stored in reserved_2 field of the
/// default location.
virtual unsigned getDefaultLocationReserved2Flags() const { return 0; }
/// Returns default flags for the barriers depending on the directive, for
/// which this barier is going to be emitted.
static unsigned getDefaultFlagsForBarriers(OpenMPDirectiveKind Kind);
/// Get the LLVM type for the critical name.
llvm::ArrayType *getKmpCriticalNameTy() const {return KmpCriticalNameTy;}
/// Returns corresponding lock object for the specified critical region
/// name. If the lock object does not exist it is created, otherwise the
/// reference to the existing copy is returned.
/// \param CriticalName Name of the critical region.
///
llvm::Value *getCriticalRegionLock(StringRef CriticalName);
private:
/// An OpenMP-IR-Builder instance.
llvm::OpenMPIRBuilder OMPBuilder;
/// Default const ident_t object used for initialization of all other
/// ident_t objects.
llvm::Constant *DefaultOpenMPPSource = nullptr;
using FlagsTy = std::pair<unsigned, unsigned>;
/// Map of flags and corresponding default locations.
using OpenMPDefaultLocMapTy = llvm::DenseMap<FlagsTy, llvm::Value *>;
OpenMPDefaultLocMapTy OpenMPDefaultLocMap;
Address getOrCreateDefaultLocation(unsigned Flags);
QualType IdentQTy;
llvm::StructType *IdentTy = nullptr;
/// Map for SourceLocation and OpenMP runtime library debug locations.
typedef llvm::DenseMap<unsigned, llvm::Value *> OpenMPDebugLocMapTy;
OpenMPDebugLocMapTy OpenMPDebugLocMap;
/// The type for a microtask which gets passed to __kmpc_fork_call().
/// Original representation is:
/// typedef void (kmpc_micro)(kmp_int32 global_tid, kmp_int32 bound_tid,...);
llvm::FunctionType *Kmpc_MicroTy = nullptr;
/// Stores debug location and ThreadID for the function.
struct DebugLocThreadIdTy {
llvm::Value *DebugLoc;
llvm::Value *ThreadID;
/// Insert point for the service instructions.
llvm::AssertingVH<llvm::Instruction> ServiceInsertPt = nullptr;
};
/// Map of local debug location, ThreadId and functions.
typedef llvm::DenseMap<llvm::Function *, DebugLocThreadIdTy>
OpenMPLocThreadIDMapTy;
OpenMPLocThreadIDMapTy OpenMPLocThreadIDMap;
/// Map of UDRs and corresponding combiner/initializer.
typedef llvm::DenseMap<const OMPDeclareReductionDecl *,
std::pair<llvm::Function *, llvm::Function *>>
UDRMapTy;
UDRMapTy UDRMap;
/// Map of functions and locally defined UDRs.
typedef llvm::DenseMap<llvm::Function *,
SmallVector<const OMPDeclareReductionDecl *, 4>>
FunctionUDRMapTy;
FunctionUDRMapTy FunctionUDRMap;
/// Map from the user-defined mapper declaration to its corresponding
/// functions.
llvm::DenseMap<const OMPDeclareMapperDecl *, llvm::Function *> UDMMap;
/// Map of functions and their local user-defined mappers.
using FunctionUDMMapTy =
llvm::DenseMap<llvm::Function *,
SmallVector<const OMPDeclareMapperDecl *, 4>>;
FunctionUDMMapTy FunctionUDMMap;
/// Maps local variables marked as lastprivate conditional to their internal
/// types.
llvm::DenseMap<llvm::Function *,
llvm::DenseMap<CanonicalDeclPtr<const Decl>,
std::tuple<QualType, const FieldDecl *,
const FieldDecl *, LValue>>>
LastprivateConditionalToTypes;
/// Type kmp_critical_name, originally defined as typedef kmp_int32
/// kmp_critical_name[8];
llvm::ArrayType *KmpCriticalNameTy;
/// An ordered map of auto-generated variables to their unique names.
/// It stores variables with the following names: 1) ".gomp_critical_user_" +
/// <critical_section_name> + ".var" for "omp critical" directives; 2)
/// <mangled_name_for_global_var> + ".cache." for cache for threadprivate
/// variables.
llvm::StringMap<llvm::AssertingVH<llvm::Constant>, llvm::BumpPtrAllocator>
InternalVars;
/// Type typedef kmp_int32 (* kmp_routine_entry_t)(kmp_int32, void *);
llvm::Type *KmpRoutineEntryPtrTy = nullptr;
QualType KmpRoutineEntryPtrQTy;
/// Type typedef struct kmp_task {
/// void * shareds; /**< pointer to block of pointers to
/// shared vars */
/// kmp_routine_entry_t routine; /**< pointer to routine to call for
/// executing task */
/// kmp_int32 part_id; /**< part id for the task */
/// kmp_routine_entry_t destructors; /* pointer to function to invoke
/// deconstructors of firstprivate C++ objects */
/// } kmp_task_t;
QualType KmpTaskTQTy;
/// Saved kmp_task_t for task directive.
QualType SavedKmpTaskTQTy;
/// Saved kmp_task_t for taskloop-based directive.
QualType SavedKmpTaskloopTQTy;
/// Type typedef struct kmp_depend_info {
/// kmp_intptr_t base_addr;
/// size_t len;
/// struct {
/// bool in:1;
/// bool out:1;
/// } flags;
/// } kmp_depend_info_t;
QualType KmpDependInfoTy;
/// Type typedef struct kmp_task_affinity_info {
/// kmp_intptr_t base_addr;
/// size_t len;
/// struct {
/// bool flag1 : 1;
/// bool flag2 : 1;
/// kmp_int32 reserved : 30;
/// } flags;
/// } kmp_task_affinity_info_t;
QualType KmpTaskAffinityInfoTy;
/// struct kmp_dim { // loop bounds info casted to kmp_int64
/// kmp_int64 lo; // lower
/// kmp_int64 up; // upper
/// kmp_int64 st; // stride
/// };
QualType KmpDimTy;
/// Type struct __tgt_offload_entry{
/// void *addr; // Pointer to the offload entry info.
/// // (function or global)
/// char *name; // Name of the function or global.
/// size_t size; // Size of the entry info (0 if it a function).
/// int32_t flags;
/// int32_t reserved;
/// };
QualType TgtOffloadEntryQTy;
/// Entity that registers the offloading constants that were emitted so
/// far.
class OffloadEntriesInfoManagerTy {
CodeGenModule &CGM;
/// Number of entries registered so far.
unsigned OffloadingEntriesNum = 0;
public:
/// Base class of the entries info.
class OffloadEntryInfo {
public:
/// Kind of a given entry.
enum OffloadingEntryInfoKinds : unsigned {
/// Entry is a target region.
OffloadingEntryInfoTargetRegion = 0,
/// Entry is a declare target variable.
OffloadingEntryInfoDeviceGlobalVar = 1,
/// Invalid entry info.
OffloadingEntryInfoInvalid = ~0u
};
protected:
OffloadEntryInfo() = delete;
explicit OffloadEntryInfo(OffloadingEntryInfoKinds Kind) : Kind(Kind) {}
explicit OffloadEntryInfo(OffloadingEntryInfoKinds Kind, unsigned Order,
uint32_t Flags)
: Flags(Flags), Order(Order), Kind(Kind) {}
~OffloadEntryInfo() = default;
public:
bool isValid() const { return Order != ~0u; }
unsigned getOrder() const { return Order; }
OffloadingEntryInfoKinds getKind() const { return Kind; }
uint32_t getFlags() const { return Flags; }
void setFlags(uint32_t NewFlags) { Flags = NewFlags; }
llvm::Constant *getAddress() const {
return cast_or_null<llvm::Constant>(Addr);
}
void setAddress(llvm::Constant *V) {
assert(!Addr.pointsToAliveValue() && "Address has been set before!");
Addr = V;
}
static bool classof(const OffloadEntryInfo *Info) { return true; }
private:
/// Address of the entity that has to be mapped for offloading.
llvm::WeakTrackingVH Addr;
/// Flags associated with the device global.
uint32_t Flags = 0u;
/// Order this entry was emitted.
unsigned Order = ~0u;
OffloadingEntryInfoKinds Kind = OffloadingEntryInfoInvalid;
};
/// Return true if a there are no entries defined.
bool empty() const;
/// Return number of entries defined so far.
unsigned size() const { return OffloadingEntriesNum; }
OffloadEntriesInfoManagerTy(CodeGenModule &CGM) : CGM(CGM) {}
//
// Target region entries related.
//
/// Kind of the target registry entry.
enum OMPTargetRegionEntryKind : uint32_t {
/// Mark the entry as target region.
OMPTargetRegionEntryTargetRegion = 0x0,
/// Mark the entry as a global constructor.
OMPTargetRegionEntryCtor = 0x02,
/// Mark the entry as a global destructor.
OMPTargetRegionEntryDtor = 0x04,
};
/// Target region entries info.
class OffloadEntryInfoTargetRegion final : public OffloadEntryInfo {
/// Address that can be used as the ID of the entry.
llvm::Constant *ID = nullptr;
public:
OffloadEntryInfoTargetRegion()
: OffloadEntryInfo(OffloadingEntryInfoTargetRegion) {}
explicit OffloadEntryInfoTargetRegion(unsigned Order,
llvm::Constant *Addr,
llvm::Constant *ID,
OMPTargetRegionEntryKind Flags)
: OffloadEntryInfo(OffloadingEntryInfoTargetRegion, Order, Flags),
ID(ID) {
setAddress(Addr);
}
llvm::Constant *getID() const { return ID; }
void setID(llvm::Constant *V) {
assert(!ID && "ID has been set before!");
ID = V;
}
static bool classof(const OffloadEntryInfo *Info) {
return Info->getKind() == OffloadingEntryInfoTargetRegion;
}
};
/// Initialize target region entry.
void initializeTargetRegionEntryInfo(unsigned DeviceID, unsigned FileID,
StringRef ParentName, unsigned LineNum,
unsigned Order);
/// Register target region entry.
void registerTargetRegionEntryInfo(unsigned DeviceID, unsigned FileID,
StringRef ParentName, unsigned LineNum,
llvm::Constant *Addr, llvm::Constant *ID,
OMPTargetRegionEntryKind Flags);
/// Return true if a target region entry with the provided information
/// exists.
bool hasTargetRegionEntryInfo(unsigned DeviceID, unsigned FileID,
StringRef ParentName, unsigned LineNum) const;
/// brief Applies action \a Action on all registered entries.
typedef llvm::function_ref<void(unsigned, unsigned, StringRef, unsigned,
const OffloadEntryInfoTargetRegion &)>
OffloadTargetRegionEntryInfoActTy;
void actOnTargetRegionEntriesInfo(
const OffloadTargetRegionEntryInfoActTy &Action);
//
// Device global variable entries related.
//
/// Kind of the global variable entry..
enum OMPTargetGlobalVarEntryKind : uint32_t {
/// Mark the entry as a to declare target.
OMPTargetGlobalVarEntryTo = 0x0,
/// Mark the entry as a to declare target link.
OMPTargetGlobalVarEntryLink = 0x1,
};
/// Device global variable entries info.
class OffloadEntryInfoDeviceGlobalVar final : public OffloadEntryInfo {
/// Type of the global variable.
CharUnits VarSize;
llvm::GlobalValue::LinkageTypes Linkage;
public:
OffloadEntryInfoDeviceGlobalVar()
: OffloadEntryInfo(OffloadingEntryInfoDeviceGlobalVar) {}
explicit OffloadEntryInfoDeviceGlobalVar(unsigned Order,
OMPTargetGlobalVarEntryKind Flags)
: OffloadEntryInfo(OffloadingEntryInfoDeviceGlobalVar, Order, Flags) {}
explicit OffloadEntryInfoDeviceGlobalVar(
unsigned Order, llvm::Constant *Addr, CharUnits VarSize,
OMPTargetGlobalVarEntryKind Flags,
llvm::GlobalValue::LinkageTypes Linkage)
: OffloadEntryInfo(OffloadingEntryInfoDeviceGlobalVar, Order, Flags),
VarSize(VarSize), Linkage(Linkage) {
setAddress(Addr);
}
CharUnits getVarSize() const { return VarSize; }
void setVarSize(CharUnits Size) { VarSize = Size; }
llvm::GlobalValue::LinkageTypes getLinkage() const { return Linkage; }
void setLinkage(llvm::GlobalValue::LinkageTypes LT) { Linkage = LT; }
static bool classof(const OffloadEntryInfo *Info) {
return Info->getKind() == OffloadingEntryInfoDeviceGlobalVar;
}
};
/// Initialize device global variable entry.
void initializeDeviceGlobalVarEntryInfo(StringRef Name,
OMPTargetGlobalVarEntryKind Flags,
unsigned Order);
/// Register device global variable entry.
void
registerDeviceGlobalVarEntryInfo(StringRef VarName, llvm::Constant *Addr,
CharUnits VarSize,
OMPTargetGlobalVarEntryKind Flags,
llvm::GlobalValue::LinkageTypes Linkage);
/// Checks if the variable with the given name has been registered already.
bool hasDeviceGlobalVarEntryInfo(StringRef VarName) const {
return OffloadEntriesDeviceGlobalVar.count(VarName) > 0;
}
/// Applies action \a Action on all registered entries.
typedef llvm::function_ref<void(StringRef,
const OffloadEntryInfoDeviceGlobalVar &)>
OffloadDeviceGlobalVarEntryInfoActTy;
void actOnDeviceGlobalVarEntriesInfo(
const OffloadDeviceGlobalVarEntryInfoActTy &Action);
private:
// Storage for target region entries kind. The storage is to be indexed by
// file ID, device ID, parent function name and line number.
typedef llvm::DenseMap<unsigned, OffloadEntryInfoTargetRegion>
OffloadEntriesTargetRegionPerLine;
typedef llvm::StringMap<OffloadEntriesTargetRegionPerLine>
OffloadEntriesTargetRegionPerParentName;
typedef llvm::DenseMap<unsigned, OffloadEntriesTargetRegionPerParentName>
OffloadEntriesTargetRegionPerFile;
typedef llvm::DenseMap<unsigned, OffloadEntriesTargetRegionPerFile>
OffloadEntriesTargetRegionPerDevice;
typedef OffloadEntriesTargetRegionPerDevice OffloadEntriesTargetRegionTy;
OffloadEntriesTargetRegionTy OffloadEntriesTargetRegion;
/// Storage for device global variable entries kind. The storage is to be
/// indexed by mangled name.
typedef llvm::StringMap<OffloadEntryInfoDeviceGlobalVar>
OffloadEntriesDeviceGlobalVarTy;
OffloadEntriesDeviceGlobalVarTy OffloadEntriesDeviceGlobalVar;
};
OffloadEntriesInfoManagerTy OffloadEntriesInfoManager;
bool ShouldMarkAsGlobal = true;
/// List of the emitted declarations.
llvm::DenseSet<CanonicalDeclPtr<const Decl>> AlreadyEmittedTargetDecls;
/// List of the global variables with their addresses that should not be
/// emitted for the target.
llvm::StringMap<llvm::WeakTrackingVH> EmittedNonTargetVariables;
/// List of variables that can become declare target implicitly and, thus,
/// must be emitted.
llvm::SmallDenseSet<const VarDecl *> DeferredGlobalVariables;
using NontemporalDeclsSet = llvm::SmallDenseSet<CanonicalDeclPtr<const Decl>>;
/// Stack for list of declarations in current context marked as nontemporal.
/// The set is the union of all current stack elements.
llvm::SmallVector<NontemporalDeclsSet, 4> NontemporalDeclsStack;
/// Stack for list of addresses of declarations in current context marked as
/// lastprivate conditional. The set is the union of all current stack
/// elements.
llvm::SmallVector<LastprivateConditionalData, 4> LastprivateConditionalStack;
/// Flag for keeping track of weather a requires unified_shared_memory
/// directive is present.
bool HasRequiresUnifiedSharedMemory = false;
/// Atomic ordering from the omp requires directive.
llvm::AtomicOrdering RequiresAtomicOrdering = llvm::AtomicOrdering::Monotonic;
/// Flag for keeping track of weather a target region has been emitted.
bool HasEmittedTargetRegion = false;
/// Flag for keeping track of weather a device routine has been emitted.
/// Device routines are specific to the
bool HasEmittedDeclareTargetRegion = false;
/// Loads all the offload entries information from the host IR
/// metadata.
void loadOffloadInfoMetadata();
/// Returns __tgt_offload_entry type.
QualType getTgtOffloadEntryQTy();
/// Start scanning from statement \a S and and emit all target regions
/// found along the way.
/// \param S Starting statement.
/// \param ParentName Name of the function declaration that is being scanned.
void scanForTargetRegionsFunctions(const Stmt *S, StringRef ParentName);
/// Build type kmp_routine_entry_t (if not built yet).
void emitKmpRoutineEntryT(QualType KmpInt32Ty);
/// Returns pointer to kmpc_micro type.
llvm::Type *getKmpc_MicroPointerTy();
/// Returns __kmpc_for_static_init_* runtime function for the specified
/// size \a IVSize and sign \a IVSigned.
llvm::FunctionCallee createForStaticInitFunction(unsigned IVSize,
bool IVSigned);
/// Returns __kmpc_dispatch_init_* runtime function for the specified
/// size \a IVSize and sign \a IVSigned.
llvm::FunctionCallee createDispatchInitFunction(unsigned IVSize,
bool IVSigned);
/// Returns __kmpc_dispatch_next_* runtime function for the specified
/// size \a IVSize and sign \a IVSigned.
llvm::FunctionCallee createDispatchNextFunction(unsigned IVSize,
bool IVSigned);
/// Returns __kmpc_dispatch_fini_* runtime function for the specified
/// size \a IVSize and sign \a IVSigned.
llvm::FunctionCallee createDispatchFiniFunction(unsigned IVSize,
bool IVSigned);
/// If the specified mangled name is not in the module, create and
/// return threadprivate cache object. This object is a pointer's worth of
/// storage that's reserved for use by the OpenMP runtime.
/// \param VD Threadprivate variable.
/// \return Cache variable for the specified threadprivate.
llvm::Constant *getOrCreateThreadPrivateCache(const VarDecl *VD);
/// Gets (if variable with the given name already exist) or creates
/// internal global variable with the specified Name. The created variable has
/// linkage CommonLinkage by default and is initialized by null value.
/// \param Ty Type of the global variable. If it is exist already the type
/// must be the same.
/// \param Name Name of the variable.
llvm::Constant *getOrCreateInternalVariable(llvm::Type *Ty,
const llvm::Twine &Name,
unsigned AddressSpace = 0);
/// Set of threadprivate variables with the generated initializer.
llvm::StringSet<> ThreadPrivateWithDefinition;
/// Set of declare target variables with the generated initializer.
llvm::StringSet<> DeclareTargetWithDefinition;
/// Emits initialization code for the threadprivate variables.
/// \param VDAddr Address of the global variable \a VD.
/// \param Ctor Pointer to a global init function for \a VD.
/// \param CopyCtor Pointer to a global copy function for \a VD.
/// \param Dtor Pointer to a global destructor function for \a VD.
/// \param Loc Location of threadprivate declaration.
void emitThreadPrivateVarInit(CodeGenFunction &CGF, Address VDAddr,
llvm::Value *Ctor, llvm::Value *CopyCtor,
llvm::Value *Dtor, SourceLocation Loc);
/// Emit the array initialization or deletion portion for user-defined mapper
/// code generation.
void emitUDMapperArrayInitOrDel(CodeGenFunction &MapperCGF,
llvm::Value *Handle, llvm::Value *BasePtr,
llvm::Value *Ptr, llvm::Value *Size,
llvm::Value *MapType, CharUnits ElementSize,
llvm::BasicBlock *ExitBB, bool IsInit);
struct TaskResultTy {
llvm::Value *NewTask = nullptr;
llvm::Function *TaskEntry = nullptr;
llvm::Value *NewTaskNewTaskTTy = nullptr;
LValue TDBase;
const RecordDecl *KmpTaskTQTyRD = nullptr;
llvm::Value *TaskDupFn = nullptr;
};
/// Emit task region for the task directive. The task region is emitted in
/// several steps:
/// 1. Emit a call to kmp_task_t *__kmpc_omp_task_alloc(ident_t *, kmp_int32
/// gtid, kmp_int32 flags, size_t sizeof_kmp_task_t, size_t sizeof_shareds,
/// kmp_routine_entry_t *task_entry). Here task_entry is a pointer to the
/// function:
/// kmp_int32 .omp_task_entry.(kmp_int32 gtid, kmp_task_t *tt) {
/// TaskFunction(gtid, tt->part_id, tt->shareds);
/// return 0;
/// }
/// 2. Copy a list of shared variables to field shareds of the resulting
/// structure kmp_task_t returned by the previous call (if any).
/// 3. Copy a pointer to destructions function to field destructions of the
/// resulting structure kmp_task_t.
/// \param D Current task directive.
/// \param TaskFunction An LLVM function with type void (*)(i32 /*gtid*/, i32
/// /*part_id*/, captured_struct */*__context*/);
/// \param SharedsTy A type which contains references the shared variables.
/// \param Shareds Context with the list of shared variables from the \p
/// TaskFunction.
/// \param Data Additional data for task generation like tiednsee, final
/// state, list of privates etc.
TaskResultTy emitTaskInit(CodeGenFunction &CGF, SourceLocation Loc,
const OMPExecutableDirective &D,
llvm::Function *TaskFunction, QualType SharedsTy,
Address Shareds, const OMPTaskDataTy &Data);
/// Returns default address space for the constant firstprivates, 0 by
/// default.
virtual unsigned getDefaultFirstprivateAddressSpace() const { return 0; }
/// Emit code that pushes the trip count of loops associated with constructs
/// 'target teams distribute' and 'teams distribute parallel for'.
/// \param SizeEmitter Emits the int64 value for the number of iterations of
/// the associated loop.
void emitTargetNumIterationsCall(
CodeGenFunction &CGF, const OMPExecutableDirective &D,
llvm::Value *DeviceID,
llvm::function_ref<llvm::Value *(CodeGenFunction &CGF,
const OMPLoopDirective &D)>
SizeEmitter);
/// Emit update for lastprivate conditional data.
void emitLastprivateConditionalUpdate(CodeGenFunction &CGF, LValue IVLVal,
StringRef UniqueDeclName, LValue LVal,
SourceLocation Loc);
/// Returns the number of the elements and the address of the depobj
/// dependency array.
/// \return Number of elements in depobj array and the pointer to the array of
/// dependencies.
std::pair<llvm::Value *, LValue> getDepobjElements(CodeGenFunction &CGF,
LValue DepobjLVal,
SourceLocation Loc);
public:
explicit CGOpenMPRuntime(CodeGenModule &CGM)
: CGOpenMPRuntime(CGM, ".", ".") {}
virtual ~CGOpenMPRuntime() {}
virtual void clear();
/// Emits code for OpenMP 'if' clause using specified \a CodeGen
/// function. Here is the logic:
/// if (Cond) {
/// ThenGen();
/// } else {
/// ElseGen();
/// }
void emitIfClause(CodeGenFunction &CGF, const Expr *Cond,
const RegionCodeGenTy &ThenGen,
const RegionCodeGenTy &ElseGen);
/// Checks if the \p Body is the \a CompoundStmt and returns its child
/// statement iff there is only one that is not evaluatable at the compile
/// time.
static const Stmt *getSingleCompoundChild(ASTContext &Ctx, const Stmt *Body);
/// Get the platform-specific name separator.
std::string getName(ArrayRef<StringRef> Parts) const;
/// Emit code for the specified user defined reduction construct.
virtual void emitUserDefinedReduction(CodeGenFunction *CGF,
const OMPDeclareReductionDecl *D);
/// Get combiner/initializer for the specified user-defined reduction, if any.
virtual std::pair<llvm::Function *, llvm::Function *>
getUserDefinedReduction(const OMPDeclareReductionDecl *D);
/// Emit the function for the user defined mapper construct.
void emitUserDefinedMapper(const OMPDeclareMapperDecl *D,
CodeGenFunction *CGF = nullptr);
/// Get the function for the specified user-defined mapper. If it does not
/// exist, create one.
llvm::Function *
getOrCreateUserDefinedMapperFunc(const OMPDeclareMapperDecl *D);
/// Emits outlined function for the specified OpenMP parallel directive
/// \a D. This outlined function has type void(*)(kmp_int32 *ThreadID,
/// kmp_int32 BoundID, struct context_vars*).
/// \param D OpenMP directive.
/// \param ThreadIDVar Variable for thread id in the current OpenMP region.
/// \param InnermostKind Kind of innermost directive (for simple directives it
/// is a directive itself, for combined - its innermost directive).
/// \param CodeGen Code generation sequence for the \a D directive.
virtual llvm::Function *emitParallelOutlinedFunction(
const OMPExecutableDirective &D, const VarDecl *ThreadIDVar,
OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen);
/// Emits outlined function for the specified OpenMP teams directive
/// \a D. This outlined function has type void(*)(kmp_int32 *ThreadID,
/// kmp_int32 BoundID, struct context_vars*).
/// \param D OpenMP directive.
/// \param ThreadIDVar Variable for thread id in the current OpenMP region.
/// \param InnermostKind Kind of innermost directive (for simple directives it
/// is a directive itself, for combined - its innermost directive).
/// \param CodeGen Code generation sequence for the \a D directive.
virtual llvm::Function *emitTeamsOutlinedFunction(
const OMPExecutableDirective &D, const VarDecl *ThreadIDVar,
OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen);
/// Emits outlined function for the OpenMP task directive \a D. This
/// outlined function has type void(*)(kmp_int32 ThreadID, struct task_t*
/// TaskT).
/// \param D OpenMP directive.
/// \param ThreadIDVar Variable for thread id in the current OpenMP region.
/// \param PartIDVar Variable for partition id in the current OpenMP untied
/// task region.
/// \param TaskTVar Variable for task_t argument.
/// \param InnermostKind Kind of innermost directive (for simple directives it
/// is a directive itself, for combined - its innermost directive).
/// \param CodeGen Code generation sequence for the \a D directive.
/// \param Tied true if task is generated for tied task, false otherwise.
/// \param NumberOfParts Number of parts in untied task. Ignored for tied
/// tasks.
///
virtual llvm::Function *emitTaskOutlinedFunction(
const OMPExecutableDirective &D, const VarDecl *ThreadIDVar,
const VarDecl *PartIDVar, const VarDecl *TaskTVar,
OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen,
bool Tied, unsigned &NumberOfParts);
/// Cleans up references to the objects in finished function.
///
virtual void functionFinished(CodeGenFunction &CGF);
/// Emits code for parallel or serial call of the \a OutlinedFn with
/// variables captured in a record which address is stored in \a
/// CapturedStruct.
/// \param OutlinedFn Outlined function to be run in parallel threads. Type of
/// this function is void(*)(kmp_int32 *, kmp_int32, struct context_vars*).
/// \param CapturedVars A pointer to the record with the references to
/// variables used in \a OutlinedFn function.
/// \param IfCond Condition in the associated 'if' clause, if it was
/// specified, nullptr otherwise.
///
virtual void emitParallelCall(CodeGenFunction &CGF, SourceLocation Loc,
llvm::Function *OutlinedFn,
ArrayRef<llvm::Value *> CapturedVars,
const Expr *IfCond);
/// Emits a critical region.
/// \param CriticalName Name of the critical region.
/// \param CriticalOpGen Generator for the statement associated with the given
/// critical region.
/// \param Hint Value of the 'hint' clause (optional).
virtual void emitCriticalRegion(CodeGenFunction &CGF, StringRef CriticalName,
const RegionCodeGenTy &CriticalOpGen,
SourceLocation Loc,
const Expr *Hint = nullptr);
/// Emits a master region.
/// \param MasterOpGen Generator for the statement associated with the given
/// master region.
virtual void emitMasterRegion(CodeGenFunction &CGF,
const RegionCodeGenTy &MasterOpGen,
SourceLocation Loc);
/// Emits code for a taskyield directive.
virtual void emitTaskyieldCall(CodeGenFunction &CGF, SourceLocation Loc);
/// Emit a taskgroup region.
/// \param TaskgroupOpGen Generator for the statement associated with the
/// given taskgroup region.
virtual void emitTaskgroupRegion(CodeGenFunction &CGF,
const RegionCodeGenTy &TaskgroupOpGen,
SourceLocation Loc);
/// Emits a single region.
/// \param SingleOpGen Generator for the statement associated with the given
/// single region.
virtual void emitSingleRegion(CodeGenFunction &CGF,
const RegionCodeGenTy &SingleOpGen,
SourceLocation Loc,
ArrayRef<const Expr *> CopyprivateVars,
ArrayRef<const Expr *> DestExprs,
ArrayRef<const Expr *> SrcExprs,
ArrayRef<const Expr *> AssignmentOps);
/// Emit an ordered region.
/// \param OrderedOpGen Generator for the statement associated with the given
/// ordered region.
virtual void emitOrderedRegion(CodeGenFunction &CGF,
const RegionCodeGenTy &OrderedOpGen,
SourceLocation Loc, bool IsThreads);
/// Emit an implicit/explicit barrier for OpenMP threads.
/// \param Kind Directive for which this implicit barrier call must be
/// generated. Must be OMPD_barrier for explicit barrier generation.
/// \param EmitChecks true if need to emit checks for cancellation barriers.
/// \param ForceSimpleCall true simple barrier call must be emitted, false if
/// runtime class decides which one to emit (simple or with cancellation
/// checks).
///
virtual void emitBarrierCall(CodeGenFunction &CGF, SourceLocation Loc,
OpenMPDirectiveKind Kind,
bool EmitChecks = true,
bool ForceSimpleCall = false);
/// Check if the specified \a ScheduleKind is static non-chunked.
/// This kind of worksharing directive is emitted without outer loop.
/// \param ScheduleKind Schedule kind specified in the 'schedule' clause.
/// \param Chunked True if chunk is specified in the clause.
///
virtual bool isStaticNonchunked(OpenMPScheduleClauseKind ScheduleKind,
bool Chunked) const;
/// Check if the specified \a ScheduleKind is static non-chunked.
/// This kind of distribute directive is emitted without outer loop.
/// \param ScheduleKind Schedule kind specified in the 'dist_schedule' clause.
/// \param Chunked True if chunk is specified in the clause.
///
virtual bool isStaticNonchunked(OpenMPDistScheduleClauseKind ScheduleKind,
bool Chunked) const;
/// Check if the specified \a ScheduleKind is static chunked.
/// \param ScheduleKind Schedule kind specified in the 'schedule' clause.
/// \param Chunked True if chunk is specified in the clause.
///
virtual bool isStaticChunked(OpenMPScheduleClauseKind ScheduleKind,
bool Chunked) const;
/// Check if the specified \a ScheduleKind is static non-chunked.
/// \param ScheduleKind Schedule kind specified in the 'dist_schedule' clause.
/// \param Chunked True if chunk is specified in the clause.
///
virtual bool isStaticChunked(OpenMPDistScheduleClauseKind ScheduleKind,
bool Chunked) const;
/// Check if the specified \a ScheduleKind is dynamic.
/// This kind of worksharing directive is emitted without outer loop.
/// \param ScheduleKind Schedule Kind specified in the 'schedule' clause.
///
virtual bool isDynamic(OpenMPScheduleClauseKind ScheduleKind) const;
/// struct with the values to be passed to the dispatch runtime function
struct DispatchRTInput {
/// Loop lower bound
llvm::Value *LB = nullptr;
/// Loop upper bound
llvm::Value *UB = nullptr;
/// Chunk size specified using 'schedule' clause (nullptr if chunk
/// was not specified)
llvm::Value *Chunk = nullptr;
DispatchRTInput() = default;
DispatchRTInput(llvm::Value *LB, llvm::Value *UB, llvm::Value *Chunk)
: LB(LB), UB(UB), Chunk(Chunk) {}
};
/// Call the appropriate runtime routine to initialize it before start
/// of loop.
/// This is used for non static scheduled types and when the ordered
/// clause is present on the loop construct.
/// Depending on the loop schedule, it is necessary to call some runtime
/// routine before start of the OpenMP loop to get the loop upper / lower
/// bounds \a LB and \a UB and stride \a ST.
///
/// \param CGF Reference to current CodeGenFunction.
/// \param Loc Clang source location.
/// \param ScheduleKind Schedule kind, specified by the 'schedule' clause.
/// \param IVSize Size of the iteration variable in bits.
/// \param IVSigned Sign of the iteration variable.
/// \param Ordered true if loop is ordered, false otherwise.
/// \param DispatchValues struct containing llvm values for lower bound, upper
/// bound, and chunk expression.
/// For the default (nullptr) value, the chunk 1 will be used.
///
virtual void emitForDispatchInit(CodeGenFunction &CGF, SourceLocation Loc,
const OpenMPScheduleTy &ScheduleKind,
unsigned IVSize, bool IVSigned, bool Ordered,
const DispatchRTInput &DispatchValues);
/// Struct with the values to be passed to the static runtime function
struct StaticRTInput {
/// Size of the iteration variable in bits.
unsigned IVSize = 0;
/// Sign of the iteration variable.
bool IVSigned = false;
/// true if loop is ordered, false otherwise.
bool Ordered = false;
/// Address of the output variable in which the flag of the last iteration
/// is returned.
Address IL = Address::invalid();
/// Address of the output variable in which the lower iteration number is
/// returned.
Address LB = Address::invalid();
/// Address of the output variable in which the upper iteration number is
/// returned.
Address UB = Address::invalid();
/// Address of the output variable in which the stride value is returned
/// necessary to generated the static_chunked scheduled loop.
Address ST = Address::invalid();
/// Value of the chunk for the static_chunked scheduled loop. For the
/// default (nullptr) value, the chunk 1 will be used.
llvm::Value *Chunk = nullptr;
StaticRTInput(unsigned IVSize, bool IVSigned, bool Ordered, Address IL,
Address LB, Address UB, Address ST,
llvm::Value *Chunk = nullptr)
: IVSize(IVSize), IVSigned(IVSigned), Ordered(Ordered), IL(IL), LB(LB),
UB(UB), ST(ST), Chunk(Chunk) {}
};
/// Call the appropriate runtime routine to initialize it before start
/// of loop.
///
/// This is used only in case of static schedule, when the user did not
/// specify a ordered clause on the loop construct.
/// Depending on the loop schedule, it is necessary to call some runtime
/// routine before start of the OpenMP loop to get the loop upper / lower
/// bounds LB and UB and stride ST.
///
/// \param CGF Reference to current CodeGenFunction.
/// \param Loc Clang source location.
/// \param DKind Kind of the directive.
/// \param ScheduleKind Schedule kind, specified by the 'schedule' clause.
/// \param Values Input arguments for the construct.
///
virtual void emitForStaticInit(CodeGenFunction &CGF, SourceLocation Loc,
OpenMPDirectiveKind DKind,
const OpenMPScheduleTy &ScheduleKind,
const StaticRTInput &Values);
///
/// \param CGF Reference to current CodeGenFunction.
/// \param Loc Clang source location.
/// \param SchedKind Schedule kind, specified by the 'dist_schedule' clause.
/// \param Values Input arguments for the construct.
///
virtual void emitDistributeStaticInit(CodeGenFunction &CGF,
SourceLocation Loc,
OpenMPDistScheduleClauseKind SchedKind,
const StaticRTInput &Values);
/// Call the appropriate runtime routine to notify that we finished
/// iteration of the ordered loop with the dynamic scheduling.
///
/// \param CGF Reference to current CodeGenFunction.
/// \param Loc Clang source location.
/// \param IVSize Size of the iteration variable in bits.
/// \param IVSigned Sign of the iteration variable.
///
virtual void emitForOrderedIterationEnd(CodeGenFunction &CGF,
SourceLocation Loc, unsigned IVSize,
bool IVSigned);
/// Call the appropriate runtime routine to notify that we finished
/// all the work with current loop.
///
/// \param CGF Reference to current CodeGenFunction.
/// \param Loc Clang source location.
/// \param DKind Kind of the directive for which the static finish is emitted.
///
virtual void emitForStaticFinish(CodeGenFunction &CGF, SourceLocation Loc,
OpenMPDirectiveKind DKind);
/// Call __kmpc_dispatch_next(
/// ident_t *loc, kmp_int32 tid, kmp_int32 *p_lastiter,
/// kmp_int[32|64] *p_lower, kmp_int[32|64] *p_upper,
/// kmp_int[32|64] *p_stride);
/// \param IVSize Size of the iteration variable in bits.
/// \param IVSigned Sign of the iteration variable.
/// \param IL Address of the output variable in which the flag of the
/// last iteration is returned.
/// \param LB Address of the output variable in which the lower iteration
/// number is returned.
/// \param UB Address of the output variable in which the upper iteration
/// number is returned.
/// \param ST Address of the output variable in which the stride value is
/// returned.
virtual llvm::Value *emitForNext(CodeGenFunction &CGF, SourceLocation Loc,
unsigned IVSize, bool IVSigned,
Address IL, Address LB,
Address UB, Address ST);
/// Emits call to void __kmpc_push_num_threads(ident_t *loc, kmp_int32
/// global_tid, kmp_int32 num_threads) to generate code for 'num_threads'
/// clause.
/// \param NumThreads An integer value of threads.
virtual void emitNumThreadsClause(CodeGenFunction &CGF,
llvm::Value *NumThreads,
SourceLocation Loc);
/// Emit call to void __kmpc_push_proc_bind(ident_t *loc, kmp_int32
/// global_tid, int proc_bind) to generate code for 'proc_bind' clause.
virtual void emitProcBindClause(CodeGenFunction &CGF,
llvm::omp::ProcBindKind ProcBind,
SourceLocation Loc);
/// Returns address of the threadprivate variable for the current
/// thread.
/// \param VD Threadprivate variable.
/// \param VDAddr Address of the global variable \a VD.
/// \param Loc Location of the reference to threadprivate var.
/// \return Address of the threadprivate variable for the current thread.
virtual Address getAddrOfThreadPrivate(CodeGenFunction &CGF,
const VarDecl *VD,
Address VDAddr,
SourceLocation Loc);
/// Returns the address of the variable marked as declare target with link
/// clause OR as declare target with to clause and unified memory.
virtual Address getAddrOfDeclareTargetVar(const VarDecl *VD);
/// Emit a code for initialization of threadprivate variable. It emits
/// a call to runtime library which adds initial value to the newly created
/// threadprivate variable (if it is not constant) and registers destructor
/// for the variable (if any).
/// \param VD Threadprivate variable.
/// \param VDAddr Address of the global variable \a VD.
/// \param Loc Location of threadprivate declaration.
/// \param PerformInit true if initialization expression is not constant.
virtual llvm::Function *
emitThreadPrivateVarDefinition(const VarDecl *VD, Address VDAddr,
SourceLocation Loc, bool PerformInit,
CodeGenFunction *CGF = nullptr);
/// Emit a code for initialization of declare target variable.
/// \param VD Declare target variable.
/// \param Addr Address of the global variable \a VD.
/// \param PerformInit true if initialization expression is not constant.
virtual bool emitDeclareTargetVarDefinition(const VarDecl *VD,
llvm::GlobalVariable *Addr,
bool PerformInit);
/// Creates artificial threadprivate variable with name \p Name and type \p
/// VarType.
/// \param VarType Type of the artificial threadprivate variable.
/// \param Name Name of the artificial threadprivate variable.
virtual Address getAddrOfArtificialThreadPrivate(CodeGenFunction &CGF,
QualType VarType,
StringRef Name);
/// Emit flush of the variables specified in 'omp flush' directive.
/// \param Vars List of variables to flush.
virtual void emitFlush(CodeGenFunction &CGF, ArrayRef<const Expr *> Vars,
SourceLocation Loc, llvm::AtomicOrdering AO);
/// Emit task region for the task directive. The task region is
/// emitted in several steps:
/// 1. Emit a call to kmp_task_t *__kmpc_omp_task_alloc(ident_t *, kmp_int32
/// gtid, kmp_int32 flags, size_t sizeof_kmp_task_t, size_t sizeof_shareds,
/// kmp_routine_entry_t *task_entry). Here task_entry is a pointer to the
/// function:
/// kmp_int32 .omp_task_entry.(kmp_int32 gtid, kmp_task_t *tt) {
/// TaskFunction(gtid, tt->part_id, tt->shareds);
/// return 0;
/// }
/// 2. Copy a list of shared variables to field shareds of the resulting
/// structure kmp_task_t returned by the previous call (if any).
/// 3. Copy a pointer to destructions function to field destructions of the
/// resulting structure kmp_task_t.
/// 4. Emit a call to kmp_int32 __kmpc_omp_task(ident_t *, kmp_int32 gtid,
/// kmp_task_t *new_task), where new_task is a resulting structure from
/// previous items.
/// \param D Current task directive.
/// \param TaskFunction An LLVM function with type void (*)(i32 /*gtid*/, i32
/// /*part_id*/, captured_struct */*__context*/);
/// \param SharedsTy A type which contains references the shared variables.
/// \param Shareds Context with the list of shared variables from the \p
/// TaskFunction.
/// \param IfCond Not a nullptr if 'if' clause was specified, nullptr
/// otherwise.
/// \param Data Additional data for task generation like tiednsee, final
/// state, list of privates etc.
virtual void emitTaskCall(CodeGenFunction &CGF, SourceLocation Loc,
const OMPExecutableDirective &D,
llvm::Function *TaskFunction, QualType SharedsTy,
Address Shareds, const Expr *IfCond,
const OMPTaskDataTy &Data);
/// Emit task region for the taskloop directive. The taskloop region is
/// emitted in several steps:
/// 1. Emit a call to kmp_task_t *__kmpc_omp_task_alloc(ident_t *, kmp_int32
/// gtid, kmp_int32 flags, size_t sizeof_kmp_task_t, size_t sizeof_shareds,
/// kmp_routine_entry_t *task_entry). Here task_entry is a pointer to the
/// function:
/// kmp_int32 .omp_task_entry.(kmp_int32 gtid, kmp_task_t *tt) {
/// TaskFunction(gtid, tt->part_id, tt->shareds);
/// return 0;
/// }
/// 2. Copy a list of shared variables to field shareds of the resulting
/// structure kmp_task_t returned by the previous call (if any).
/// 3. Copy a pointer to destructions function to field destructions of the
/// resulting structure kmp_task_t.
/// 4. Emit a call to void __kmpc_taskloop(ident_t *loc, int gtid, kmp_task_t
/// *task, int if_val, kmp_uint64 *lb, kmp_uint64 *ub, kmp_int64 st, int
/// nogroup, int sched, kmp_uint64 grainsize, void *task_dup ), where new_task
/// is a resulting structure from
/// previous items.
/// \param D Current task directive.
/// \param TaskFunction An LLVM function with type void (*)(i32 /*gtid*/, i32
/// /*part_id*/, captured_struct */*__context*/);
/// \param SharedsTy A type which contains references the shared variables.
/// \param Shareds Context with the list of shared variables from the \p
/// TaskFunction.
/// \param IfCond Not a nullptr if 'if' clause was specified, nullptr
/// otherwise.
/// \param Data Additional data for task generation like tiednsee, final
/// state, list of privates etc.
virtual void emitTaskLoopCall(CodeGenFunction &CGF, SourceLocation Loc,
const OMPLoopDirective &D,
llvm::Function *TaskFunction,
QualType SharedsTy, Address Shareds,
const Expr *IfCond, const OMPTaskDataTy &Data);
/// Emit code for the directive that does not require outlining.
///
/// \param InnermostKind Kind of innermost directive (for simple directives it
/// is a directive itself, for combined - its innermost directive).
/// \param CodeGen Code generation sequence for the \a D directive.
/// \param HasCancel true if region has inner cancel directive, false
/// otherwise.
virtual void emitInlinedDirective(CodeGenFunction &CGF,
OpenMPDirectiveKind InnermostKind,
const RegionCodeGenTy &CodeGen,
bool HasCancel = false);
/// Emits reduction function.
/// \param ArgsType Array type containing pointers to reduction variables.
/// \param Privates List of private copies for original reduction arguments.
/// \param LHSExprs List of LHS in \a ReductionOps reduction operations.
/// \param RHSExprs List of RHS in \a ReductionOps reduction operations.
/// \param ReductionOps List of reduction operations in form 'LHS binop RHS'
/// or 'operator binop(LHS, RHS)'.
llvm::Function *emitReductionFunction(SourceLocation Loc,
llvm::Type *ArgsType,
ArrayRef<const Expr *> Privates,
ArrayRef<const Expr *> LHSExprs,
ArrayRef<const Expr *> RHSExprs,
ArrayRef<const Expr *> ReductionOps);
/// Emits single reduction combiner
void emitSingleReductionCombiner(CodeGenFunction &CGF,
const Expr *ReductionOp,
const Expr *PrivateRef,
const DeclRefExpr *LHS,
const DeclRefExpr *RHS);
struct ReductionOptionsTy {
bool WithNowait;
bool SimpleReduction;
OpenMPDirectiveKind ReductionKind;
};
/// Emit a code for reduction clause. Next code should be emitted for
/// reduction:
/// \code
///
/// static kmp_critical_name lock = { 0 };
///
/// void reduce_func(void *lhs[<n>], void *rhs[<n>]) {
/// ...
/// *(Type<i>*)lhs[i] = RedOp<i>(*(Type<i>*)lhs[i], *(Type<i>*)rhs[i]);
/// ...
/// }
///
/// ...
/// void *RedList[<n>] = {&<RHSExprs>[0], ..., &<RHSExprs>[<n>-1]};
/// switch (__kmpc_reduce{_nowait}(<loc>, <gtid>, <n>, sizeof(RedList),
/// RedList, reduce_func, &<lock>)) {
/// case 1:
/// ...
/// <LHSExprs>[i] = RedOp<i>(*<LHSExprs>[i], *<RHSExprs>[i]);
/// ...
/// __kmpc_end_reduce{_nowait}(<loc>, <gtid>, &<lock>);
/// break;
/// case 2:
/// ...
/// Atomic(<LHSExprs>[i] = RedOp<i>(*<LHSExprs>[i], *<RHSExprs>[i]));
/// ...
/// break;
/// default:;
/// }
/// \endcode
///
/// \param Privates List of private copies for original reduction arguments.
/// \param LHSExprs List of LHS in \a ReductionOps reduction operations.
/// \param RHSExprs List of RHS in \a ReductionOps reduction operations.
/// \param ReductionOps List of reduction operations in form 'LHS binop RHS'
/// or 'operator binop(LHS, RHS)'.
/// \param Options List of options for reduction codegen:
/// WithNowait true if parent directive has also nowait clause, false
/// otherwise.
/// SimpleReduction Emit reduction operation only. Used for omp simd
/// directive on the host.
/// ReductionKind The kind of reduction to perform.
virtual void emitReduction(CodeGenFunction &CGF, SourceLocation Loc,
ArrayRef<const Expr *> Privates,
ArrayRef<const Expr *> LHSExprs,
ArrayRef<const Expr *> RHSExprs,
ArrayRef<const Expr *> ReductionOps,
ReductionOptionsTy Options);
/// Emit a code for initialization of task reduction clause. Next code
/// should be emitted for reduction:
/// \code
///
/// _taskred_item_t red_data[n];
/// ...
/// red_data[i].shar = &shareds[i];
/// red_data[i].orig = &origs[i];
/// red_data[i].size = sizeof(origs[i]);
/// red_data[i].f_init = (void*)RedInit<i>;
/// red_data[i].f_fini = (void*)RedDest<i>;
/// red_data[i].f_comb = (void*)RedOp<i>;
/// red_data[i].flags = <Flag_i>;
/// ...
/// void* tg1 = __kmpc_taskred_init(gtid, n, red_data);
/// \endcode
/// For reduction clause with task modifier it emits the next call:
/// \code
///
/// _taskred_item_t red_data[n];
/// ...
/// red_data[i].shar = &shareds[i];
/// red_data[i].orig = &origs[i];
/// red_data[i].size = sizeof(origs[i]);
/// red_data[i].f_init = (void*)RedInit<i>;
/// red_data[i].f_fini = (void*)RedDest<i>;
/// red_data[i].f_comb = (void*)RedOp<i>;
/// red_data[i].flags = <Flag_i>;
/// ...
/// void* tg1 = __kmpc_taskred_modifier_init(loc, gtid, is_worksharing, n,
/// red_data);
/// \endcode
/// \param LHSExprs List of LHS in \a Data.ReductionOps reduction operations.
/// \param RHSExprs List of RHS in \a Data.ReductionOps reduction operations.
/// \param Data Additional data for task generation like tiedness, final
/// state, list of privates, reductions etc.
virtual llvm::Value *emitTaskReductionInit(CodeGenFunction &CGF,
SourceLocation Loc,
ArrayRef<const Expr *> LHSExprs,
ArrayRef<const Expr *> RHSExprs,
const OMPTaskDataTy &Data);
/// Emits the following code for reduction clause with task modifier:
/// \code
/// __kmpc_task_reduction_modifier_fini(loc, gtid, is_worksharing);
/// \endcode
virtual void emitTaskReductionFini(CodeGenFunction &CGF, SourceLocation Loc,
bool IsWorksharingReduction);
/// Required to resolve existing problems in the runtime. Emits threadprivate
/// variables to store the size of the VLAs/array sections for
/// initializer/combiner/finalizer functions.
/// \param RCG Allows to reuse an existing data for the reductions.
/// \param N Reduction item for which fixups must be emitted.
virtual void emitTaskReductionFixups(CodeGenFunction &CGF, SourceLocation Loc,
ReductionCodeGen &RCG, unsigned N);
/// Get the address of `void *` type of the privatue copy of the reduction
/// item specified by the \p SharedLVal.
/// \param ReductionsPtr Pointer to the reduction data returned by the
/// emitTaskReductionInit function.
/// \param SharedLVal Address of the original reduction item.
virtual Address getTaskReductionItem(CodeGenFunction &CGF, SourceLocation Loc,
llvm::Value *ReductionsPtr,
LValue SharedLVal);
/// Emit code for 'taskwait' directive.
virtual void emitTaskwaitCall(CodeGenFunction &CGF, SourceLocation Loc);
/// Emit code for 'cancellation point' construct.
/// \param CancelRegion Region kind for which the cancellation point must be
/// emitted.
///
virtual void emitCancellationPointCall(CodeGenFunction &CGF,
SourceLocation Loc,
OpenMPDirectiveKind CancelRegion);
/// Emit code for 'cancel' construct.
/// \param IfCond Condition in the associated 'if' clause, if it was
/// specified, nullptr otherwise.
/// \param CancelRegion Region kind for which the cancel must be emitted.
///
virtual void emitCancelCall(CodeGenFunction &CGF, SourceLocation Loc,
const Expr *IfCond,
OpenMPDirectiveKind CancelRegion);
/// Emit outilined function for 'target' directive.
/// \param D Directive to emit.
/// \param ParentName Name of the function that encloses the target region.
/// \param OutlinedFn Outlined function value to be defined by this call.
/// \param OutlinedFnID Outlined function ID value to be defined by this call.
/// \param IsOffloadEntry True if the outlined function is an offload entry.
/// \param CodeGen Code generation sequence for the \a D directive.
/// An outlined function may not be an entry if, e.g. the if clause always
/// evaluates to false.
virtual void emitTargetOutlinedFunction(const OMPExecutableDirective &D,
StringRef ParentName,
llvm::Function *&OutlinedFn,
llvm::Constant *&OutlinedFnID,
bool IsOffloadEntry,
const RegionCodeGenTy &CodeGen);
/// Emit the target offloading code associated with \a D. The emitted
/// code attempts offloading the execution to the device, an the event of
/// a failure it executes the host version outlined in \a OutlinedFn.
/// \param D Directive to emit.
/// \param OutlinedFn Host version of the code to be offloaded.
/// \param OutlinedFnID ID of host version of the code to be offloaded.
/// \param IfCond Expression evaluated in if clause associated with the target
/// directive, or null if no if clause is used.
/// \param Device Expression evaluated in device clause associated with the
/// target directive, or null if no device clause is used and device modifier.
/// \param SizeEmitter Callback to emit number of iterations for loop-based
/// directives.
virtual void emitTargetCall(
CodeGenFunction &CGF, const OMPExecutableDirective &D,
llvm::Function *OutlinedFn, llvm::Value *OutlinedFnID, const Expr *IfCond,
llvm::PointerIntPair<const Expr *, 2, OpenMPDeviceClauseModifier> Device,
llvm::function_ref<llvm::Value *(CodeGenFunction &CGF,
const OMPLoopDirective &D)>
SizeEmitter);
/// Emit the target regions enclosed in \a GD function definition or
/// the function itself in case it is a valid device function. Returns true if
/// \a GD was dealt with successfully.
/// \param GD Function to scan.
virtual bool emitTargetFunctions(GlobalDecl GD);
/// Emit the global variable if it is a valid device global variable.
/// Returns true if \a GD was dealt with successfully.
/// \param GD Variable declaration to emit.
virtual bool emitTargetGlobalVariable(GlobalDecl GD);
/// Checks if the provided global decl \a GD is a declare target variable and
/// registers it when emitting code for the host.
virtual void registerTargetGlobalVariable(const VarDecl *VD,
llvm::Constant *Addr);
/// Registers provided target firstprivate variable as global on the
/// target.
llvm::Constant *registerTargetFirstprivateCopy(CodeGenFunction &CGF,
const VarDecl *VD);
/// Emit the global \a GD if it is meaningful for the target. Returns
/// if it was emitted successfully.
/// \param GD Global to scan.
virtual bool emitTargetGlobal(GlobalDecl GD);
/// Creates and returns a registration function for when at least one
/// requires directives was used in the current module.
llvm::Function *emitRequiresDirectiveRegFun();
/// Creates all the offload entries in the current compilation unit
/// along with the associated metadata.
void createOffloadEntriesAndInfoMetadata();
/// Emits code for teams call of the \a OutlinedFn with
/// variables captured in a record which address is stored in \a
/// CapturedStruct.
/// \param OutlinedFn Outlined function to be run by team masters. Type of
/// this function is void(*)(kmp_int32 *, kmp_int32, struct context_vars*).
/// \param CapturedVars A pointer to the record with the references to
/// variables used in \a OutlinedFn function.
///
virtual void emitTeamsCall(CodeGenFunction &CGF,
const OMPExecutableDirective &D,
SourceLocation Loc, llvm::Function *OutlinedFn,
ArrayRef<llvm::Value *> CapturedVars);
/// Emits call to void __kmpc_push_num_teams(ident_t *loc, kmp_int32
/// global_tid, kmp_int32 num_teams, kmp_int32 thread_limit) to generate code
/// for num_teams clause.
/// \param NumTeams An integer expression of teams.
/// \param ThreadLimit An integer expression of threads.
virtual void emitNumTeamsClause(CodeGenFunction &CGF, const Expr *NumTeams,
const Expr *ThreadLimit, SourceLocation Loc);
/// Struct that keeps all the relevant information that should be kept
/// throughout a 'target data' region.
class TargetDataInfo {
/// Set to true if device pointer information have to be obtained.
bool RequiresDevicePointerInfo = false;
/// Set to true if Clang emits separate runtime calls for the beginning and
/// end of the region. These calls might have separate map type arrays.
bool SeparateBeginEndCalls = false;
public:
/// The array of base pointer passed to the runtime library.
llvm::Value *BasePointersArray = nullptr;
/// The array of section pointers passed to the runtime library.
llvm::Value *PointersArray = nullptr;
/// The array of sizes passed to the runtime library.
llvm::Value *SizesArray = nullptr;
/// The array of map types passed to the runtime library for the beginning
/// of the region or for the entire region if there are no separate map
/// types for the region end.
llvm::Value *MapTypesArray = nullptr;
/// The array of map types passed to the runtime library for the end of the
/// region, or nullptr if there are no separate map types for the region
/// end.
llvm::Value *MapTypesArrayEnd = nullptr;
/// The array of user-defined mappers passed to the runtime library.
llvm::Value *MappersArray = nullptr;
/// Indicate whether any user-defined mapper exists.
bool HasMapper = false;
/// The total number of pointers passed to the runtime library.
unsigned NumberOfPtrs = 0u;
/// Map between the a declaration of a capture and the corresponding base
/// pointer address where the runtime returns the device pointers.
llvm::DenseMap<const ValueDecl *, Address> CaptureDeviceAddrMap;
explicit TargetDataInfo() {}
explicit TargetDataInfo(bool RequiresDevicePointerInfo,
bool SeparateBeginEndCalls)
: RequiresDevicePointerInfo(RequiresDevicePointerInfo),
SeparateBeginEndCalls(SeparateBeginEndCalls) {}
/// Clear information about the data arrays.
void clearArrayInfo() {
BasePointersArray = nullptr;
PointersArray = nullptr;
SizesArray = nullptr;
MapTypesArray = nullptr;
MapTypesArrayEnd = nullptr;
MappersArray = nullptr;
HasMapper = false;
NumberOfPtrs = 0u;
}
/// Return true if the current target data information has valid arrays.
bool isValid() {
return BasePointersArray && PointersArray && SizesArray &&
MapTypesArray && (!HasMapper || MappersArray) && NumberOfPtrs;
}
bool requiresDevicePointerInfo() { return RequiresDevicePointerInfo; }
bool separateBeginEndCalls() { return SeparateBeginEndCalls; }
};
/// Emit the target data mapping code associated with \a D.
/// \param D Directive to emit.
/// \param IfCond Expression evaluated in if clause associated with the
/// target directive, or null if no device clause is used.
/// \param Device Expression evaluated in device clause associated with the
/// target directive, or null if no device clause is used.
/// \param Info A record used to store information that needs to be preserved
/// until the region is closed.
virtual void emitTargetDataCalls(CodeGenFunction &CGF,
const OMPExecutableDirective &D,
const Expr *IfCond, const Expr *Device,
const RegionCodeGenTy &CodeGen,
TargetDataInfo &Info);
/// Emit the data mapping/movement code associated with the directive
/// \a D that should be of the form 'target [{enter|exit} data | update]'.
/// \param D Directive to emit.
/// \param IfCond Expression evaluated in if clause associated with the target
/// directive, or null if no if clause is used.
/// \param Device Expression evaluated in device clause associated with the
/// target directive, or null if no device clause is used.
virtual void emitTargetDataStandAloneCall(CodeGenFunction &CGF,
const OMPExecutableDirective &D,
const Expr *IfCond,
const Expr *Device);
/// Marks function \a Fn with properly mangled versions of vector functions.
/// \param FD Function marked as 'declare simd'.
/// \param Fn LLVM function that must be marked with 'declare simd'
/// attributes.
virtual void emitDeclareSimdFunction(const FunctionDecl *FD,
llvm::Function *Fn);
/// Emit initialization for doacross loop nesting support.
/// \param D Loop-based construct used in doacross nesting construct.
virtual void emitDoacrossInit(CodeGenFunction &CGF, const OMPLoopDirective &D,
ArrayRef<Expr *> NumIterations);
/// Emit code for doacross ordered directive with 'depend' clause.
/// \param C 'depend' clause with 'sink|source' dependency kind.
virtual void emitDoacrossOrdered(CodeGenFunction &CGF,
const OMPDependClause *C);
/// Translates the native parameter of outlined function if this is required
/// for target.
/// \param FD Field decl from captured record for the parameter.
/// \param NativeParam Parameter itself.
virtual const VarDecl *translateParameter(const FieldDecl *FD,
const VarDecl *NativeParam) const {
return NativeParam;
}
/// Gets the address of the native argument basing on the address of the
/// target-specific parameter.
/// \param NativeParam Parameter itself.
/// \param TargetParam Corresponding target-specific parameter.
virtual Address getParameterAddress(CodeGenFunction &CGF,
const VarDecl *NativeParam,
const VarDecl *TargetParam) const;
/// Choose default schedule type and chunk value for the
/// dist_schedule clause.
virtual void getDefaultDistScheduleAndChunk(CodeGenFunction &CGF,
const OMPLoopDirective &S, OpenMPDistScheduleClauseKind &ScheduleKind,
llvm::Value *&Chunk) const {}
/// Choose default schedule type and chunk value for the
/// schedule clause.
virtual void getDefaultScheduleAndChunk(CodeGenFunction &CGF,
const OMPLoopDirective &S, OpenMPScheduleClauseKind &ScheduleKind,
const Expr *&ChunkExpr) const;
/// Emits call of the outlined function with the provided arguments,
/// translating these arguments to correct target-specific arguments.
virtual void
emitOutlinedFunctionCall(CodeGenFunction &CGF, SourceLocation Loc,
llvm::FunctionCallee OutlinedFn,
ArrayRef<llvm::Value *> Args = llvm::None) const;
/// Emits OpenMP-specific function prolog.
/// Required for device constructs.
virtual void emitFunctionProlog(CodeGenFunction &CGF, const Decl *D);
/// Gets the OpenMP-specific address of the local variable.
virtual Address getAddressOfLocalVariable(CodeGenFunction &CGF,
const VarDecl *VD);
/// Marks the declaration as already emitted for the device code and returns
/// true, if it was marked already, and false, otherwise.
bool markAsGlobalTarget(GlobalDecl GD);
/// Emit deferred declare target variables marked for deferred emission.
void emitDeferredTargetDecls() const;
/// Adjust some parameters for the target-based directives, like addresses of
/// the variables captured by reference in lambdas.
virtual void
adjustTargetSpecificDataForLambdas(CodeGenFunction &CGF,
const OMPExecutableDirective &D) const;
/// Perform check on requires decl to ensure that target architecture
/// supports unified addressing
virtual void processRequiresDirective(const OMPRequiresDecl *D);
/// Gets default memory ordering as specified in requires directive.
llvm::AtomicOrdering getDefaultMemoryOrdering() const;
/// Checks if the variable has associated OMPAllocateDeclAttr attribute with
/// the predefined allocator and translates it into the corresponding address
/// space.
virtual bool hasAllocateAttributeForGlobalVar(const VarDecl *VD, LangAS &AS);
/// Return whether the unified_shared_memory has been specified.
bool hasRequiresUnifiedSharedMemory() const;
/// Checks if the \p VD variable is marked as nontemporal declaration in
/// current context.
bool isNontemporalDecl(const ValueDecl *VD) const;
/// Create specialized alloca to handle lastprivate conditionals.
Address emitLastprivateConditionalInit(CodeGenFunction &CGF,
const VarDecl *VD);
/// Checks if the provided \p LVal is lastprivate conditional and emits the
/// code to update the value of the original variable.
/// \code
/// lastprivate(conditional: a)
/// ...
/// <type> a;
/// lp_a = ...;
/// #pragma omp critical(a)
/// if (last_iv_a <= iv) {
/// last_iv_a = iv;
/// global_a = lp_a;
/// }
/// \endcode
virtual void checkAndEmitLastprivateConditional(CodeGenFunction &CGF,
const Expr *LHS);
/// Checks if the lastprivate conditional was updated in inner region and
/// writes the value.
/// \code
/// lastprivate(conditional: a)
/// ...
/// <type> a;bool Fired = false;
/// #pragma omp ... shared(a)
/// {
/// lp_a = ...;
/// Fired = true;
/// }
/// if (Fired) {
/// #pragma omp critical(a)
/// if (last_iv_a <= iv) {
/// last_iv_a = iv;
/// global_a = lp_a;
/// }
/// Fired = false;
/// }
/// \endcode
virtual void checkAndEmitSharedLastprivateConditional(
CodeGenFunction &CGF, const OMPExecutableDirective &D,
const llvm::DenseSet<CanonicalDeclPtr<const VarDecl>> &IgnoredDecls);
/// Gets the address of the global copy used for lastprivate conditional
/// update, if any.
/// \param PrivLVal LValue for the private copy.
/// \param VD Original lastprivate declaration.
virtual void emitLastprivateConditionalFinalUpdate(CodeGenFunction &CGF,
LValue PrivLVal,
const VarDecl *VD,
SourceLocation Loc);
/// Emits list of dependecies based on the provided data (array of
/// dependence/expression pairs).
/// \returns Pointer to the first element of the array casted to VoidPtr type.
std::pair<llvm::Value *, Address>
emitDependClause(CodeGenFunction &CGF,
ArrayRef<OMPTaskDataTy::DependData> Dependencies,
SourceLocation Loc);
/// Emits list of dependecies based on the provided data (array of
/// dependence/expression pairs) for depobj construct. In this case, the
/// variable is allocated in dynamically. \returns Pointer to the first
/// element of the array casted to VoidPtr type.
Address emitDepobjDependClause(CodeGenFunction &CGF,
const OMPTaskDataTy::DependData &Dependencies,
SourceLocation Loc);
/// Emits the code to destroy the dependency object provided in depobj
/// directive.
void emitDestroyClause(CodeGenFunction &CGF, LValue DepobjLVal,
SourceLocation Loc);
/// Updates the dependency kind in the specified depobj object.
/// \param DepobjLVal LValue for the main depobj object.
/// \param NewDepKind New dependency kind.
void emitUpdateClause(CodeGenFunction &CGF, LValue DepobjLVal,
OpenMPDependClauseKind NewDepKind, SourceLocation Loc);
/// Initializes user defined allocators specified in the uses_allocators
/// clauses.
void emitUsesAllocatorsInit(CodeGenFunction &CGF, const Expr *Allocator,
const Expr *AllocatorTraits);
/// Destroys user defined allocators specified in the uses_allocators clause.
void emitUsesAllocatorsFini(CodeGenFunction &CGF, const Expr *Allocator);
};
/// Class supports emissionof SIMD-only code.
class CGOpenMPSIMDRuntime final : public CGOpenMPRuntime {
public:
explicit CGOpenMPSIMDRuntime(CodeGenModule &CGM) : CGOpenMPRuntime(CGM) {}
~CGOpenMPSIMDRuntime() override {}
/// Emits outlined function for the specified OpenMP parallel directive
/// \a D. This outlined function has type void(*)(kmp_int32 *ThreadID,
/// kmp_int32 BoundID, struct context_vars*).
/// \param D OpenMP directive.
/// \param ThreadIDVar Variable for thread id in the current OpenMP region.
/// \param InnermostKind Kind of innermost directive (for simple directives it
/// is a directive itself, for combined - its innermost directive).
/// \param CodeGen Code generation sequence for the \a D directive.
llvm::Function *
emitParallelOutlinedFunction(const OMPExecutableDirective &D,
const VarDecl *ThreadIDVar,
OpenMPDirectiveKind InnermostKind,
const RegionCodeGenTy &CodeGen) override;
/// Emits outlined function for the specified OpenMP teams directive
/// \a D. This outlined function has type void(*)(kmp_int32 *ThreadID,
/// kmp_int32 BoundID, struct context_vars*).
/// \param D OpenMP directive.
/// \param ThreadIDVar Variable for thread id in the current OpenMP region.
/// \param InnermostKind Kind of innermost directive (for simple directives it
/// is a directive itself, for combined - its innermost directive).
/// \param CodeGen Code generation sequence for the \a D directive.
llvm::Function *
emitTeamsOutlinedFunction(const OMPExecutableDirective &D,
const VarDecl *ThreadIDVar,
OpenMPDirectiveKind InnermostKind,
const RegionCodeGenTy &CodeGen) override;
/// Emits outlined function for the OpenMP task directive \a D. This
/// outlined function has type void(*)(kmp_int32 ThreadID, struct task_t*
/// TaskT).
/// \param D OpenMP directive.
/// \param ThreadIDVar Variable for thread id in the current OpenMP region.
/// \param PartIDVar Variable for partition id in the current OpenMP untied
/// task region.
/// \param TaskTVar Variable for task_t argument.
/// \param InnermostKind Kind of innermost directive (for simple directives it
/// is a directive itself, for combined - its innermost directive).
/// \param CodeGen Code generation sequence for the \a D directive.
/// \param Tied true if task is generated for tied task, false otherwise.
/// \param NumberOfParts Number of parts in untied task. Ignored for tied
/// tasks.
///
llvm::Function *emitTaskOutlinedFunction(
const OMPExecutableDirective &D, const VarDecl *ThreadIDVar,
const VarDecl *PartIDVar, const VarDecl *TaskTVar,
OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen,
bool Tied, unsigned &NumberOfParts) override;
/// Emits code for parallel or serial call of the \a OutlinedFn with
/// variables captured in a record which address is stored in \a
/// CapturedStruct.
/// \param OutlinedFn Outlined function to be run in parallel threads. Type of
/// this function is void(*)(kmp_int32 *, kmp_int32, struct context_vars*).
/// \param CapturedVars A pointer to the record with the references to
/// variables used in \a OutlinedFn function.
/// \param IfCond Condition in the associated 'if' clause, if it was
/// specified, nullptr otherwise.
///
void emitParallelCall(CodeGenFunction &CGF, SourceLocation Loc,
llvm::Function *OutlinedFn,
ArrayRef<llvm::Value *> CapturedVars,
const Expr *IfCond) override;
/// Emits a critical region.
/// \param CriticalName Name of the critical region.
/// \param CriticalOpGen Generator for the statement associated with the given
/// critical region.
/// \param Hint Value of the 'hint' clause (optional).
void emitCriticalRegion(CodeGenFunction &CGF, StringRef CriticalName,
const RegionCodeGenTy &CriticalOpGen,
SourceLocation Loc,
const Expr *Hint = nullptr) override;
/// Emits a master region.
/// \param MasterOpGen Generator for the statement associated with the given
/// master region.
void emitMasterRegion(CodeGenFunction &CGF,
const RegionCodeGenTy &MasterOpGen,
SourceLocation Loc) override;
/// Emits code for a taskyield directive.
void emitTaskyieldCall(CodeGenFunction &CGF, SourceLocation Loc) override;
/// Emit a taskgroup region.
/// \param TaskgroupOpGen Generator for the statement associated with the
/// given taskgroup region.
void emitTaskgroupRegion(CodeGenFunction &CGF,
const RegionCodeGenTy &TaskgroupOpGen,
SourceLocation Loc) override;
/// Emits a single region.
/// \param SingleOpGen Generator for the statement associated with the given
/// single region.
void emitSingleRegion(CodeGenFunction &CGF,
const RegionCodeGenTy &SingleOpGen, SourceLocation Loc,
ArrayRef<const Expr *> CopyprivateVars,
ArrayRef<const Expr *> DestExprs,
ArrayRef<const Expr *> SrcExprs,
ArrayRef<const Expr *> AssignmentOps) override;
/// Emit an ordered region.
/// \param OrderedOpGen Generator for the statement associated with the given
/// ordered region.
void emitOrderedRegion(CodeGenFunction &CGF,
const RegionCodeGenTy &OrderedOpGen,
SourceLocation Loc, bool IsThreads) override;
/// Emit an implicit/explicit barrier for OpenMP threads.
/// \param Kind Directive for which this implicit barrier call must be
/// generated. Must be OMPD_barrier for explicit barrier generation.
/// \param EmitChecks true if need to emit checks for cancellation barriers.
/// \param ForceSimpleCall true simple barrier call must be emitted, false if
/// runtime class decides which one to emit (simple or with cancellation
/// checks).
///
void emitBarrierCall(CodeGenFunction &CGF, SourceLocation Loc,
OpenMPDirectiveKind Kind, bool EmitChecks = true,
bool ForceSimpleCall = false) override;
/// This is used for non static scheduled types and when the ordered
/// clause is present on the loop construct.
/// Depending on the loop schedule, it is necessary to call some runtime
/// routine before start of the OpenMP loop to get the loop upper / lower
/// bounds \a LB and \a UB and stride \a ST.
///
/// \param CGF Reference to current CodeGenFunction.
/// \param Loc Clang source location.
/// \param ScheduleKind Schedule kind, specified by the 'schedule' clause.
/// \param IVSize Size of the iteration variable in bits.
/// \param IVSigned Sign of the iteration variable.
/// \param Ordered true if loop is ordered, false otherwise.
/// \param DispatchValues struct containing llvm values for lower bound, upper
/// bound, and chunk expression.
/// For the default (nullptr) value, the chunk 1 will be used.
///
void emitForDispatchInit(CodeGenFunction &CGF, SourceLocation Loc,
const OpenMPScheduleTy &ScheduleKind,
unsigned IVSize, bool IVSigned, bool Ordered,
const DispatchRTInput &DispatchValues) override;
/// Call the appropriate runtime routine to initialize it before start
/// of loop.
///
/// This is used only in case of static schedule, when the user did not
/// specify a ordered clause on the loop construct.
/// Depending on the loop schedule, it is necessary to call some runtime
/// routine before start of the OpenMP loop to get the loop upper / lower
/// bounds LB and UB and stride ST.
///
/// \param CGF Reference to current CodeGenFunction.
/// \param Loc Clang source location.
/// \param DKind Kind of the directive.
/// \param ScheduleKind Schedule kind, specified by the 'schedule' clause.
/// \param Values Input arguments for the construct.
///
void emitForStaticInit(CodeGenFunction &CGF, SourceLocation Loc,
OpenMPDirectiveKind DKind,
const OpenMPScheduleTy &ScheduleKind,
const StaticRTInput &Values) override;
///
/// \param CGF Reference to current CodeGenFunction.
/// \param Loc Clang source location.
/// \param SchedKind Schedule kind, specified by the 'dist_schedule' clause.
/// \param Values Input arguments for the construct.
///
void emitDistributeStaticInit(CodeGenFunction &CGF, SourceLocation Loc,
OpenMPDistScheduleClauseKind SchedKind,
const StaticRTInput &Values) override;
/// Call the appropriate runtime routine to notify that we finished
/// iteration of the ordered loop with the dynamic scheduling.
///
/// \param CGF Reference to current CodeGenFunction.
/// \param Loc Clang source location.
/// \param IVSize Size of the iteration variable in bits.
/// \param IVSigned Sign of the iteration variable.
///
void emitForOrderedIterationEnd(CodeGenFunction &CGF, SourceLocation Loc,
unsigned IVSize, bool IVSigned) override;
/// Call the appropriate runtime routine to notify that we finished
/// all the work with current loop.
///
/// \param CGF Reference to current CodeGenFunction.
/// \param Loc Clang source location.
/// \param DKind Kind of the directive for which the static finish is emitted.
///
void emitForStaticFinish(CodeGenFunction &CGF, SourceLocation Loc,
OpenMPDirectiveKind DKind) override;
/// Call __kmpc_dispatch_next(
/// ident_t *loc, kmp_int32 tid, kmp_int32 *p_lastiter,
/// kmp_int[32|64] *p_lower, kmp_int[32|64] *p_upper,
/// kmp_int[32|64] *p_stride);
/// \param IVSize Size of the iteration variable in bits.
/// \param IVSigned Sign of the iteration variable.
/// \param IL Address of the output variable in which the flag of the
/// last iteration is returned.
/// \param LB Address of the output variable in which the lower iteration
/// number is returned.
/// \param UB Address of the output variable in which the upper iteration
/// number is returned.
/// \param ST Address of the output variable in which the stride value is
/// returned.
llvm::Value *emitForNext(CodeGenFunction &CGF, SourceLocation Loc,
unsigned IVSize, bool IVSigned, Address IL,
Address LB, Address UB, Address ST) override;
/// Emits call to void __kmpc_push_num_threads(ident_t *loc, kmp_int32
/// global_tid, kmp_int32 num_threads) to generate code for 'num_threads'
/// clause.
/// \param NumThreads An integer value of threads.
void emitNumThreadsClause(CodeGenFunction &CGF, llvm::Value *NumThreads,
SourceLocation Loc) override;
/// Emit call to void __kmpc_push_proc_bind(ident_t *loc, kmp_int32
/// global_tid, int proc_bind) to generate code for 'proc_bind' clause.
void emitProcBindClause(CodeGenFunction &CGF,
llvm::omp::ProcBindKind ProcBind,
SourceLocation Loc) override;
/// Returns address of the threadprivate variable for the current
/// thread.
/// \param VD Threadprivate variable.
/// \param VDAddr Address of the global variable \a VD.
/// \param Loc Location of the reference to threadprivate var.
/// \return Address of the threadprivate variable for the current thread.
Address getAddrOfThreadPrivate(CodeGenFunction &CGF, const VarDecl *VD,
Address VDAddr, SourceLocation Loc) override;
/// Emit a code for initialization of threadprivate variable. It emits
/// a call to runtime library which adds initial value to the newly created
/// threadprivate variable (if it is not constant) and registers destructor
/// for the variable (if any).
/// \param VD Threadprivate variable.
/// \param VDAddr Address of the global variable \a VD.
/// \param Loc Location of threadprivate declaration.
/// \param PerformInit true if initialization expression is not constant.
llvm::Function *
emitThreadPrivateVarDefinition(const VarDecl *VD, Address VDAddr,
SourceLocation Loc, bool PerformInit,
CodeGenFunction *CGF = nullptr) override;
/// Creates artificial threadprivate variable with name \p Name and type \p
/// VarType.
/// \param VarType Type of the artificial threadprivate variable.
/// \param Name Name of the artificial threadprivate variable.
Address getAddrOfArtificialThreadPrivate(CodeGenFunction &CGF,
QualType VarType,
StringRef Name) override;
/// Emit flush of the variables specified in 'omp flush' directive.
/// \param Vars List of variables to flush.
void emitFlush(CodeGenFunction &CGF, ArrayRef<const Expr *> Vars,
SourceLocation Loc, llvm::AtomicOrdering AO) override;
/// Emit task region for the task directive. The task region is
/// emitted in several steps:
/// 1. Emit a call to kmp_task_t *__kmpc_omp_task_alloc(ident_t *, kmp_int32
/// gtid, kmp_int32 flags, size_t sizeof_kmp_task_t, size_t sizeof_shareds,
/// kmp_routine_entry_t *task_entry). Here task_entry is a pointer to the
/// function:
/// kmp_int32 .omp_task_entry.(kmp_int32 gtid, kmp_task_t *tt) {
/// TaskFunction(gtid, tt->part_id, tt->shareds);
/// return 0;
/// }
/// 2. Copy a list of shared variables to field shareds of the resulting
/// structure kmp_task_t returned by the previous call (if any).
/// 3. Copy a pointer to destructions function to field destructions of the
/// resulting structure kmp_task_t.
/// 4. Emit a call to kmp_int32 __kmpc_omp_task(ident_t *, kmp_int32 gtid,
/// kmp_task_t *new_task), where new_task is a resulting structure from
/// previous items.
/// \param D Current task directive.
/// \param TaskFunction An LLVM function with type void (*)(i32 /*gtid*/, i32
/// /*part_id*/, captured_struct */*__context*/);
/// \param SharedsTy A type which contains references the shared variables.
/// \param Shareds Context with the list of shared variables from the \p
/// TaskFunction.
/// \param IfCond Not a nullptr if 'if' clause was specified, nullptr
/// otherwise.
/// \param Data Additional data for task generation like tiednsee, final
/// state, list of privates etc.
void emitTaskCall(CodeGenFunction &CGF, SourceLocation Loc,
const OMPExecutableDirective &D,
llvm::Function *TaskFunction, QualType SharedsTy,
Address Shareds, const Expr *IfCond,
const OMPTaskDataTy &Data) override;
/// Emit task region for the taskloop directive. The taskloop region is
/// emitted in several steps:
/// 1. Emit a call to kmp_task_t *__kmpc_omp_task_alloc(ident_t *, kmp_int32
/// gtid, kmp_int32 flags, size_t sizeof_kmp_task_t, size_t sizeof_shareds,
/// kmp_routine_entry_t *task_entry). Here task_entry is a pointer to the
/// function:
/// kmp_int32 .omp_task_entry.(kmp_int32 gtid, kmp_task_t *tt) {
/// TaskFunction(gtid, tt->part_id, tt->shareds);
/// return 0;
/// }
/// 2. Copy a list of shared variables to field shareds of the resulting
/// structure kmp_task_t returned by the previous call (if any).
/// 3. Copy a pointer to destructions function to field destructions of the
/// resulting structure kmp_task_t.
/// 4. Emit a call to void __kmpc_taskloop(ident_t *loc, int gtid, kmp_task_t
/// *task, int if_val, kmp_uint64 *lb, kmp_uint64 *ub, kmp_int64 st, int
/// nogroup, int sched, kmp_uint64 grainsize, void *task_dup ), where new_task
/// is a resulting structure from
/// previous items.
/// \param D Current task directive.
/// \param TaskFunction An LLVM function with type void (*)(i32 /*gtid*/, i32
/// /*part_id*/, captured_struct */*__context*/);
/// \param SharedsTy A type which contains references the shared variables.
/// \param Shareds Context with the list of shared variables from the \p
/// TaskFunction.
/// \param IfCond Not a nullptr if 'if' clause was specified, nullptr
/// otherwise.
/// \param Data Additional data for task generation like tiednsee, final
/// state, list of privates etc.
void emitTaskLoopCall(CodeGenFunction &CGF, SourceLocation Loc,
const OMPLoopDirective &D, llvm::Function *TaskFunction,
QualType SharedsTy, Address Shareds, const Expr *IfCond,
const OMPTaskDataTy &Data) override;
/// Emit a code for reduction clause. Next code should be emitted for
/// reduction:
/// \code
///
/// static kmp_critical_name lock = { 0 };
///
/// void reduce_func(void *lhs[<n>], void *rhs[<n>]) {
/// ...
/// *(Type<i>*)lhs[i] = RedOp<i>(*(Type<i>*)lhs[i], *(Type<i>*)rhs[i]);
/// ...
/// }
///
/// ...
/// void *RedList[<n>] = {&<RHSExprs>[0], ..., &<RHSExprs>[<n>-1]};
/// switch (__kmpc_reduce{_nowait}(<loc>, <gtid>, <n>, sizeof(RedList),
/// RedList, reduce_func, &<lock>)) {
/// case 1:
/// ...
/// <LHSExprs>[i] = RedOp<i>(*<LHSExprs>[i], *<RHSExprs>[i]);
/// ...
/// __kmpc_end_reduce{_nowait}(<loc>, <gtid>, &<lock>);
/// break;
/// case 2:
/// ...
/// Atomic(<LHSExprs>[i] = RedOp<i>(*<LHSExprs>[i], *<RHSExprs>[i]));
/// ...
/// break;
/// default:;
/// }
/// \endcode
///
/// \param Privates List of private copies for original reduction arguments.
/// \param LHSExprs List of LHS in \a ReductionOps reduction operations.
/// \param RHSExprs List of RHS in \a ReductionOps reduction operations.
/// \param ReductionOps List of reduction operations in form 'LHS binop RHS'
/// or 'operator binop(LHS, RHS)'.
/// \param Options List of options for reduction codegen:
/// WithNowait true if parent directive has also nowait clause, false
/// otherwise.
/// SimpleReduction Emit reduction operation only. Used for omp simd
/// directive on the host.
/// ReductionKind The kind of reduction to perform.
void emitReduction(CodeGenFunction &CGF, SourceLocation Loc,
ArrayRef<const Expr *> Privates,
ArrayRef<const Expr *> LHSExprs,
ArrayRef<const Expr *> RHSExprs,
ArrayRef<const Expr *> ReductionOps,
ReductionOptionsTy Options) override;
/// Emit a code for initialization of task reduction clause. Next code
/// should be emitted for reduction:
/// \code
///
/// _taskred_item_t red_data[n];
/// ...
/// red_data[i].shar = &shareds[i];
/// red_data[i].orig = &origs[i];
/// red_data[i].size = sizeof(origs[i]);
/// red_data[i].f_init = (void*)RedInit<i>;
/// red_data[i].f_fini = (void*)RedDest<i>;
/// red_data[i].f_comb = (void*)RedOp<i>;
/// red_data[i].flags = <Flag_i>;
/// ...
/// void* tg1 = __kmpc_taskred_init(gtid, n, red_data);
/// \endcode
/// For reduction clause with task modifier it emits the next call:
/// \code
///
/// _taskred_item_t red_data[n];
/// ...
/// red_data[i].shar = &shareds[i];
/// red_data[i].orig = &origs[i];
/// red_data[i].size = sizeof(origs[i]);
/// red_data[i].f_init = (void*)RedInit<i>;
/// red_data[i].f_fini = (void*)RedDest<i>;
/// red_data[i].f_comb = (void*)RedOp<i>;
/// red_data[i].flags = <Flag_i>;
/// ...
/// void* tg1 = __kmpc_taskred_modifier_init(loc, gtid, is_worksharing, n,
/// red_data);
/// \endcode
/// \param LHSExprs List of LHS in \a Data.ReductionOps reduction operations.
/// \param RHSExprs List of RHS in \a Data.ReductionOps reduction operations.
/// \param Data Additional data for task generation like tiedness, final
/// state, list of privates, reductions etc.
llvm::Value *emitTaskReductionInit(CodeGenFunction &CGF, SourceLocation Loc,
ArrayRef<const Expr *> LHSExprs,
ArrayRef<const Expr *> RHSExprs,
const OMPTaskDataTy &Data) override;
/// Emits the following code for reduction clause with task modifier:
/// \code
/// __kmpc_task_reduction_modifier_fini(loc, gtid, is_worksharing);
/// \endcode
void emitTaskReductionFini(CodeGenFunction &CGF, SourceLocation Loc,
bool IsWorksharingReduction) override;
/// Required to resolve existing problems in the runtime. Emits threadprivate
/// variables to store the size of the VLAs/array sections for
/// initializer/combiner/finalizer functions + emits threadprivate variable to
/// store the pointer to the original reduction item for the custom
/// initializer defined by declare reduction construct.
/// \param RCG Allows to reuse an existing data for the reductions.
/// \param N Reduction item for which fixups must be emitted.
void emitTaskReductionFixups(CodeGenFunction &CGF, SourceLocation Loc,
ReductionCodeGen &RCG, unsigned N) override;
/// Get the address of `void *` type of the privatue copy of the reduction
/// item specified by the \p SharedLVal.
/// \param ReductionsPtr Pointer to the reduction data returned by the
/// emitTaskReductionInit function.
/// \param SharedLVal Address of the original reduction item.
Address getTaskReductionItem(CodeGenFunction &CGF, SourceLocation Loc,
llvm::Value *ReductionsPtr,
LValue SharedLVal) override;
/// Emit code for 'taskwait' directive.
void emitTaskwaitCall(CodeGenFunction &CGF, SourceLocation Loc) override;
/// Emit code for 'cancellation point' construct.
/// \param CancelRegion Region kind for which the cancellation point must be
/// emitted.
///
void emitCancellationPointCall(CodeGenFunction &CGF, SourceLocation Loc,
OpenMPDirectiveKind CancelRegion) override;
/// Emit code for 'cancel' construct.
/// \param IfCond Condition in the associated 'if' clause, if it was
/// specified, nullptr otherwise.
/// \param CancelRegion Region kind for which the cancel must be emitted.
///
void emitCancelCall(CodeGenFunction &CGF, SourceLocation Loc,
const Expr *IfCond,
OpenMPDirectiveKind CancelRegion) override;
/// Emit outilined function for 'target' directive.
/// \param D Directive to emit.
/// \param ParentName Name of the function that encloses the target region.
/// \param OutlinedFn Outlined function value to be defined by this call.
/// \param OutlinedFnID Outlined function ID value to be defined by this call.
/// \param IsOffloadEntry True if the outlined function is an offload entry.
/// \param CodeGen Code generation sequence for the \a D directive.
/// An outlined function may not be an entry if, e.g. the if clause always
/// evaluates to false.
void emitTargetOutlinedFunction(const OMPExecutableDirective &D,
StringRef ParentName,
llvm::Function *&OutlinedFn,
llvm::Constant *&OutlinedFnID,
bool IsOffloadEntry,
const RegionCodeGenTy &CodeGen) override;
/// Emit the target offloading code associated with \a D. The emitted
/// code attempts offloading the execution to the device, an the event of
/// a failure it executes the host version outlined in \a OutlinedFn.
/// \param D Directive to emit.
/// \param OutlinedFn Host version of the code to be offloaded.
/// \param OutlinedFnID ID of host version of the code to be offloaded.
/// \param IfCond Expression evaluated in if clause associated with the target
/// directive, or null if no if clause is used.
/// \param Device Expression evaluated in device clause associated with the
/// target directive, or null if no device clause is used and device modifier.
void emitTargetCall(
CodeGenFunction &CGF, const OMPExecutableDirective &D,
llvm::Function *OutlinedFn, llvm::Value *OutlinedFnID, const Expr *IfCond,
llvm::PointerIntPair<const Expr *, 2, OpenMPDeviceClauseModifier> Device,
llvm::function_ref<llvm::Value *(CodeGenFunction &CGF,
const OMPLoopDirective &D)>
SizeEmitter) override;
/// Emit the target regions enclosed in \a GD function definition or
/// the function itself in case it is a valid device function. Returns true if
/// \a GD was dealt with successfully.
/// \param GD Function to scan.
bool emitTargetFunctions(GlobalDecl GD) override;
/// Emit the global variable if it is a valid device global variable.
/// Returns true if \a GD was dealt with successfully.
/// \param GD Variable declaration to emit.
bool emitTargetGlobalVariable(GlobalDecl GD) override;
/// Emit the global \a GD if it is meaningful for the target. Returns
/// if it was emitted successfully.
/// \param GD Global to scan.
bool emitTargetGlobal(GlobalDecl GD) override;
/// Emits code for teams call of the \a OutlinedFn with
/// variables captured in a record which address is stored in \a
/// CapturedStruct.
/// \param OutlinedFn Outlined function to be run by team masters. Type of
/// this function is void(*)(kmp_int32 *, kmp_int32, struct context_vars*).
/// \param CapturedVars A pointer to the record with the references to
/// variables used in \a OutlinedFn function.
///
void emitTeamsCall(CodeGenFunction &CGF, const OMPExecutableDirective &D,
SourceLocation Loc, llvm::Function *OutlinedFn,
ArrayRef<llvm::Value *> CapturedVars) override;
/// Emits call to void __kmpc_push_num_teams(ident_t *loc, kmp_int32
/// global_tid, kmp_int32 num_teams, kmp_int32 thread_limit) to generate code
/// for num_teams clause.
/// \param NumTeams An integer expression of teams.
/// \param ThreadLimit An integer expression of threads.
void emitNumTeamsClause(CodeGenFunction &CGF, const Expr *NumTeams,
const Expr *ThreadLimit, SourceLocation Loc) override;
/// Emit the target data mapping code associated with \a D.
/// \param D Directive to emit.
/// \param IfCond Expression evaluated in if clause associated with the
/// target directive, or null if no device clause is used.
/// \param Device Expression evaluated in device clause associated with the
/// target directive, or null if no device clause is used.
/// \param Info A record used to store information that needs to be preserved
/// until the region is closed.
void emitTargetDataCalls(CodeGenFunction &CGF,
const OMPExecutableDirective &D, const Expr *IfCond,
const Expr *Device, const RegionCodeGenTy &CodeGen,
TargetDataInfo &Info) override;
/// Emit the data mapping/movement code associated with the directive
/// \a D that should be of the form 'target [{enter|exit} data | update]'.
/// \param D Directive to emit.
/// \param IfCond Expression evaluated in if clause associated with the target
/// directive, or null if no if clause is used.
/// \param Device Expression evaluated in device clause associated with the
/// target directive, or null if no device clause is used.
void emitTargetDataStandAloneCall(CodeGenFunction &CGF,
const OMPExecutableDirective &D,
const Expr *IfCond,
const Expr *Device) override;
/// Emit initialization for doacross loop nesting support.
/// \param D Loop-based construct used in doacross nesting construct.
void emitDoacrossInit(CodeGenFunction &CGF, const OMPLoopDirective &D,
ArrayRef<Expr *> NumIterations) override;
/// Emit code for doacross ordered directive with 'depend' clause.
/// \param C 'depend' clause with 'sink|source' dependency kind.
void emitDoacrossOrdered(CodeGenFunction &CGF,
const OMPDependClause *C) override;
/// Translates the native parameter of outlined function if this is required
/// for target.
/// \param FD Field decl from captured record for the parameter.
/// \param NativeParam Parameter itself.
const VarDecl *translateParameter(const FieldDecl *FD,
const VarDecl *NativeParam) const override;
/// Gets the address of the native argument basing on the address of the
/// target-specific parameter.
/// \param NativeParam Parameter itself.
/// \param TargetParam Corresponding target-specific parameter.
Address getParameterAddress(CodeGenFunction &CGF, const VarDecl *NativeParam,
const VarDecl *TargetParam) const override;
/// Gets the OpenMP-specific address of the local variable.
Address getAddressOfLocalVariable(CodeGenFunction &CGF,
const VarDecl *VD) override {
return Address::invalid();
}
};
} // namespace CodeGen
} // namespace clang
#endif
|
Example_target_mapper.1.c | /*
* @@name: target_mapper_map.1c
* @@type: C
* @@compilable: yes
* @@linkable: no
* @@expect: success
* @@version: omp_5.0
*/
#include <stdlib.h>
#include <stdio.h>
#define N 100
typedef struct myvec{
size_t len;
double *data;
} myvec_t;
#pragma omp declare mapper(myvec_t v) \
map(v, v.data[0:v.len])
void init(myvec_t *s);
int main(){
myvec_t s;
s.data = (double *)calloc(N,sizeof(double));
s.len = N;
#pragma omp target
init(&s);
printf("s.data[%d]=%lf\n",N-1,s.data[N-1]); //s.data[99]=99.000000
}
void init(myvec_t *s)
{ for(int i=0; i<s->len; i++) s->data[i]=i; }
|
convolution_1x1.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 conv1x1s1_sse(const Mat& bottom_blob, Mat& top_blob, const Mat& _kernel, const Mat& _bias, const Option& opt)
{
int inch = bottom_blob.c;
int outw = top_blob.w;
int outh = top_blob.h;
int outch = top_blob.c;
const 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;
int size = outw * outh;
int remain = size;
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++;
r1++;
r2++;
r3++;
outptr++;
}
}
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;
int size = outw * outh;
int remain = size;
for (; remain > 0; remain--)
{
float sum = *r0 * k0;
*outptr += sum;
r0++;
outptr++;
}
}
}
}
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;
}
}
}
}
|
pdf_fmt.c | /**
* Copyright (C) 2006 Henning Norén
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* 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
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301,
* USA.
*
* Re-factored for JtR by Dhiru Kholia during June, 2011 for GSoC.
*
* References:
*
* http://www.adobe.com/devnet/pdf/pdf_reference.html
* http://www.cs.cmu.edu/~dst/Adobe/Gallery/anon21jul01-pdf-encryption.txt
* http://www.novapdf.com/kb/pdf-example-files-created-with-with-novapdf-138.html
*
* TODO: add support for detecting AESV2 and AESV3 encrypted documents
* lacking "trailer dictionary" to pdfparser.c */
#undef MEM_FREE
#include <string.h>
#include "arch.h"
#include "params.h"
#include "common.h"
#include "formats.h"
#include "misc.h"
#ifdef _OPENMP
#include <omp.h>
#define OMP_SCALE 64
#endif
#include "pdfcrack.h"
#include "pdfparser.h"
#define FORMAT_LABEL "PDF"
#define FORMAT_NAME ""
#define ALGORITHM_NAME "MD5 RC4 32/" ARCH_BITS_STR
#define BENCHMARK_COMMENT ""
#define BENCHMARK_LENGTH -1000
#define PLAINTEXT_LENGTH 32
#define BINARY_SIZE 0
#define SALT_SIZE sizeof(struct custom_salt)
#define MIN_KEYS_PER_CRYPT 1
#define MAX_KEYS_PER_CRYPT 1
#if defined (_OPENMP)
static int omp_t = 1;
#endif
static struct custom_salt *cur_salt;
static char (*saved_key)[PLAINTEXT_LENGTH + 1];
static int *cracked;
static int any_cracked;
static size_t cracked_size;
static struct fmt_tests pdf_tests[] = {
{"$pdf$Standard*badad1e86442699427116d3e5d5271bc80a27814fc5e80f815efeef839354c5f*289ece9b5ce451a5d7064693dab3badf101112131415161718191a1b1c1d1e1f*16*34b1b6e593787af681a9b63fa8bf563b*1*1*0*1*4*128*-4*3*2", "test"},
{"$pdf$Standard*d83a8ab680f144dfb2ff2334c206a6060779e007701ab881767f961aecda7984*a5ed4de7e078cb75dfdcd63e8da7a25800000000000000000000000000000000*16*06a7f710cf8dfafbd394540d40984ae2*1*1*0*1*4*128*-1028*3*2", "July2099"},
{"$pdf$Standard*2446dd5ed2e18b3ce1ac9b56733226018e3f5c2639051eb1c9b2b215b30bc820*fa3af175d761963c8449ee7015b7770800000000000000000000000000000000*16*12a4da1abe6b7a1ceb84610bad87236d*1*1*0*1*4*128*-1028*3*2", "WHATwhatWHERE?"},
{"$pdf$Standard*6a80a547b8b8b7636fcc5b322f1c63ce4b670c9b01f2aace09e48d85e1f19f83*e64eb62fc46be66e33571d50a29b464100000000000000000000000000000000*16*14a8c53ffa4a79b3ed9421ef15618420*1*1*0*1*4*128*-1028*3*2", "38r285a9"},
{NULL}
};
static void init(struct fmt_main *self)
{
#if defined (_OPENMP)
omp_t = omp_get_max_threads();
self->params.min_keys_per_crypt *= omp_t;
omp_t *= OMP_SCALE;
self->params.max_keys_per_crypt *= omp_t;
#endif
saved_key = mem_calloc_tiny(sizeof(*saved_key) *
self->params.max_keys_per_crypt, MEM_ALIGN_WORD);
any_cracked = 0;
cracked_size = sizeof(*cracked) * self->params.max_keys_per_crypt;
cracked = mem_calloc_tiny(cracked_size, MEM_ALIGN_WORD);
}
static int ishex(char *q)
{
while (atoi16[ARCH_INDEX(*q)] != 0x7F)
q++;
return !*q;
}
static int valid(char *ciphertext, struct fmt_main *self)
{
char *ctcopy, *ptr, *keeptr;
int res;
if (strncmp(ciphertext, "$pdf$Standard*", 14))
return 0;
if (!(ctcopy = strdup(ciphertext)))
return 0;
keeptr = ctcopy;
ctcopy += 14;
if (!(ptr = strtok(ctcopy, "*"))) /* o_string */
goto error;
if (!ishex(ptr))
goto error;
if (!(ptr = strtok(NULL, "*"))) /* u_string */
goto error;
if (!ishex(ptr))
goto error;
if (!(ptr = strtok(NULL, "*"))) /* fileIDLen */
goto error;
if (strncmp(ptr, "16", 2))
goto error;
if (!(ptr = strtok(NULL, "*"))) /* fileID */
goto error;
if (!ishex(ptr))
goto error;
if (!(ptr = strtok(NULL, "*"))) /* encryptMetaData */
goto error;
res = atoi(ptr);
if (res != 0 && res != 1)
goto error;
if (!(ptr = strtok(NULL, "*"))) /* work_with_user */
goto error;
res = atoi(ptr);
if (res != 0 && res != 1)
goto error;
if (!(ptr = strtok(NULL, "*"))) /* have_userpassword */
goto error;
res = atoi(ptr);
if (res != 0 && res != 1)
goto error;
if (!(ptr = strtok(NULL, "*"))) /* version_major */
goto error;
if (!(ptr = strtok(NULL, "*"))) /* version_minor */
goto error;
if (!(ptr = strtok(NULL, "*"))) /* length */
goto error;
if (!(ptr = strtok(NULL, "*"))) /* permissions */
goto error;
if (!(ptr = strtok(NULL, "*"))) /* revision */
goto error;
if (!(ptr = strtok(NULL, "*"))) /* version */
goto error;
MEM_FREE(keeptr);
return 1;
error:
MEM_FREE(keeptr);
return 0;
}
static void *get_salt(char *ciphertext)
{
char *ctcopy = strdup(ciphertext);
char *keeptr = ctcopy;
int i;
char *p;
static struct custom_salt cs;
ctcopy += 5; /* skip over "$pdf$" marker */
memset(cs.encKeyWorkSpace, 0, 128);
/* restore serialized data */
strncpy(cs.e.s_handler, strtok(ctcopy, "*"), 32);
p = strtok(NULL, "*");
for (i = 0; i < 32; i++)
cs.e.o_string[i] =
atoi16[ARCH_INDEX(p[i * 2])] * 16 +
atoi16[ARCH_INDEX(p[i * 2 + 1])];
p = strtok(NULL, "*");
for (i = 0; i < 32; i++)
cs.e.u_string[i] =
atoi16[ARCH_INDEX(p[i * 2])] * 16 +
atoi16[ARCH_INDEX(p[i * 2 + 1])];
p = strtok(NULL, "*");
cs.e.fileIDLen = atoi(p);
p = strtok(NULL, "*");
for (i = 0; i < cs.e.fileIDLen; i++)
cs.e.fileID[i] =
atoi16[ARCH_INDEX(p[i * 2])] * 16 +
atoi16[ARCH_INDEX(p[i * 2 + 1])];
p = strtok(NULL, "*");
cs.e.encryptMetaData = atoi(p);
p = strtok(NULL, "*");
cs.e.work_with_user = atoi(p);
p = strtok(NULL, "*");
cs.e.have_userpassword = atoi(p);
p = strtok(NULL, "*");
cs.e.version_major = atoi(p);
p = strtok(NULL, "*");
cs.e.version_minor = atoi(p);
p = strtok(NULL, "*");
cs.e.length = atoi(p);
p = strtok(NULL, "*");
cs.e.permissions = atoi(p);
p = strtok(NULL, "*");
cs.e.revision = atoi(p);
p = strtok(NULL, "*");
cs.e.version = atoi(p);
if (cs.e.have_userpassword)
cs.userpassword = (unsigned char *)strtok(NULL, "*");
else
cs.userpassword = NULL;
cs.knownPassword = false;
MEM_FREE(keeptr);
/* try to initialize the cracking-engine */
if (!initPDFCrack(&cs)) {
fprintf(stderr, "Wrong userpassword, '%s'\n", cs.userpassword);
exit(-1);
}
return (void *)&cs;
}
static void set_salt(void *salt)
{
cur_salt = (struct custom_salt *)salt;
loadPDFCrack(cur_salt);
}
static void pdf_set_key(char *key, int index)
{
int saved_key_length = strlen(key);
if (saved_key_length > PLAINTEXT_LENGTH)
saved_key_length = PLAINTEXT_LENGTH;
memcpy(saved_key[index], key, saved_key_length);
saved_key[index][saved_key_length] = 0;
}
static char *get_key(int index)
{
return saved_key[index];
}
static void crypt_all(int count)
{
int index = 0;
if (any_cracked) {
memset(cracked, 0, cracked_size);
any_cracked = 0;
}
#ifdef _OPENMP
#pragma omp parallel for
for (index = 0; index < count; index++)
#endif
{
/* do the actual crunching */
cracked[index] = runCrack(saved_key[index], cur_salt);
if(cracked[index] == 1)
#ifdef _OPENMP
#pragma omp critical
#endif
any_cracked = 1;
}
}
static int cmp_all(void *binary, int count)
{
return any_cracked;
}
static int cmp_one(void *binary, int index)
{
return cracked[index];
}
static int cmp_exact(char *source, int index)
{
return cracked[index];
}
struct fmt_main fmt_pdf = {
{
FORMAT_LABEL,
FORMAT_NAME,
ALGORITHM_NAME,
BENCHMARK_COMMENT,
BENCHMARK_LENGTH,
PLAINTEXT_LENGTH,
BINARY_SIZE,
DEFAULT_ALIGN,
SALT_SIZE,
DEFAULT_ALIGN,
MIN_KEYS_PER_CRYPT,
MAX_KEYS_PER_CRYPT,
FMT_CASE | FMT_8_BIT | FMT_OMP,
pdf_tests
},
{
init,
fmt_default_prepare,
valid,
fmt_default_split,
fmt_default_binary,
get_salt,
fmt_default_source,
{
fmt_default_binary_hash
},
fmt_default_salt_hash,
set_salt,
pdf_set_key,
get_key,
fmt_default_clear_keys,
crypt_all,
{
fmt_default_get_hash
},
cmp_all,
cmp_one,
cmp_exact
}
};
|
transpose.c | /*
Copyright (c) 2013, 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: transpose
PURPOSE: This program tests the efficiency with which a square matrix
can be transposed and stored in another matrix. The matrices
are distributed identically.
USAGE: Program inputs are the matrix order, the number of times to
repeat the operation, and the communication mode
transpose <#threads> <# iterations> <matrix size> [tile size]
An optional parameter specifies the tile size used to divide the
individual matrix blocks for improved cache and TLB performance.
The output consists of diagnostics to make sure the
transpose worked and timing statistics.
FUNCTIONS CALLED:
Other than MPI or standard C functions, the following
functions are used in this program:
wtime() Portable wall-timer interface.
bail_out() Determine global error and exit if nonzero.
HISTORY: Written by Tim Mattson, April 1999.
Updated by Rob Van der Wijngaart, December 2005.
Updated by Rob Van der Wijngaart, October 2006.
Updated by Rob Van der Wijngaart, November 2014::
- made variable names more consistent
- put timing around entire iterative loop of transposes
- fixed incorrect matrix block access; no separate function
for local transpose of matrix block
- reordered initialization and verification loops to
produce unit stride
- changed initialization values, such that the input matrix
elements are: A(i,j) = i+order*j
*******************************************************************/
/******************************************************************
Layout nomenclature
-------------------
o Each rank owns one block of columns (Colblock) of the overall
matrix to be transposed, as well as of the transposed matrix.
o Colblock is stored contiguously in the memory of the rank.
The stored format is column major, which means that matrix
elements (i,j) and (i+1,j) are adjacent, and (i,j) and (i,j+1)
are "order" words apart
o Colblock is logically composed of #ranks Blocks, but a Block is
not stored contiguously in memory. Conceptually, the Block is
the unit of data that gets communicated between ranks. Block i of
rank j is locally transposed and gathered into a buffer called Work,
which is sent to rank i, where it is scattered into Block j of the
transposed matrix.
o When tiling is applied to reduce TLB misses, each block gets
accessed by tiles.
o The original and transposed matrices are called A and B
-----------------------------------------------------------------
| | | | |
| Colblock | | | |
| | | | |
| | | | |
| | | | |
| ------------------------------- |
| | | | |
| | Block | | |
| | | | |
| | | | |
| | | | |
| ------------------------------- |
| |Tile| | | |
| | | | | Overall Matrix |
| |---- | | |
| | | | |
| | | | |
| ------------------------------- |
| | | | |
| | | | |
| | | | |
| | | | |
| | | | |
-----------------------------------------------------------------*/
#include <par-res-kern_general.h>
#include <par-res-kern_mpiomp.h>
#define A(i,j) A_p[(i+istart)+order*(j)]
#define B(i,j) B_p[(i+istart)+order*(j)]
#define Work_in(i,j) Work_in_p[i+Block_order*(j)]
#define Work_out(i,j) Work_out_p[i+Block_order*(j)]
int main(int argc, char ** argv)
{
int Block_order; /* number of columns owned by rank */
int Block_size; /* size of a single block */
int Colblock_size; /* size of column block */
int Tile_order=32; /* default Tile order */
int tiling; /* boolean: true if tiling is used */
int Num_procs; /* number of ranks */
int order; /* order of overall matrix */
int send_to, recv_from; /* ranks with which to communicate */
MPI_Status status;
#ifndef SYNCHRONOUS
MPI_Request send_req;
MPI_Request recv_req;
#endif
long bytes; /* combined size of matrices */
int my_ID; /* rank */
int root=0; /* ID of root rank */
int iterations; /* number of times to do the transpose */
int i, j, it, jt, istart;/* dummies */
int iter; /* index of iteration */
int phase; /* phase inside staged communication */
int colstart; /* starting column for owning rank */
int nthread_input, /* thread parameters */
nthread;
int error; /* error flag */
double *A_p; /* original matrix column block */
double *B_p; /* transposed matrix column block */
double *Work_in_p; /* workspace for the transpose function */
double *Work_out_p; /* workspace for the transpose function */
double abserr, /* absolute error */
abserr_tot; /* aggregate absolute error */
double epsilon = 1.e-8; /* error tolerance */
double local_trans_time, /* timing parameters */
trans_time,
avgtime;
/*********************************************************************
** Initialize the MPI environment
*********************************************************************/
MPI_Init(&argc,&argv);
MPI_Comm_rank(MPI_COMM_WORLD, &my_ID);
MPI_Comm_size(MPI_COMM_WORLD, &Num_procs);
/*********************************************************************
** process, test and broadcast input parameters
*********************************************************************/
error = 0;
if (my_ID == root) {
if (argc != 4 && argc != 5){
printf("Usage: %s <#threads><#iterations> <matrix order> [Tile size]\n",
*argv);
error = 1; goto ENDOFTESTS;
}
/* Take number of threads to request from command line */
nthread_input = atoi(*++argv);
if ((nthread_input < 1) || (nthread_input > MAX_THREADS)) {
printf("ERROR: Invalid number of threads: %d\n", nthread_input);
error = 1;
goto ENDOFTESTS;
}
iterations = atoi(*++argv);
if(iterations < 1){
printf("ERROR: iterations must be >= 1 : %d \n",iterations);
error = 1; goto ENDOFTESTS;
}
order = atoi(*++argv);
if (order < Num_procs) {
printf("ERROR: matrix order %d should at least # procs %d\n",
order, Num_procs);
error = 1; goto ENDOFTESTS;
}
if (order%Num_procs) {
printf("ERROR: matrix order %d should be divisible by # procs %d\n",
order, Num_procs);
error = 1; goto ENDOFTESTS;
}
if (argc == 5) Tile_order = atoi(*++argv);
ENDOFTESTS:;
}
bail_out(error);
/* Broadcast input data to all ranks */
MPI_Bcast(&order, 1, MPI_INT, root, MPI_COMM_WORLD);
MPI_Bcast(&iterations, 1, MPI_INT, root, MPI_COMM_WORLD);
MPI_Bcast(&Tile_order, 1, MPI_INT, root, MPI_COMM_WORLD);
MPI_Bcast(&nthread_input, 1, MPI_INT, root, MPI_COMM_WORLD);
omp_set_num_threads(nthread_input);
/* a non-positive tile size means no tiling of the local transpose */
tiling = (Tile_order > 0) && (Tile_order < order);
if (my_ID == root) {
printf("MPI+OpenMP matrix transpose: B = A^T\n");
printf("Number of ranks = %d\n", Num_procs);
printf("Number of threads = %d\n", omp_get_max_threads());
printf("Matrix order = %d\n", order);
printf("Number of iterations = %d\n", iterations);
if (tiling) {
printf("Tile size = %d\n", Tile_order);
#ifdef COLLAPSE
printf("Using loop collapse\n");
}
#endif
else printf("Untiled\n");
#ifndef SYNCHRONOUS
printf("Non-");
#endif
printf("Blocking messages\n");
}
bytes = 2.0 * sizeof(double) * order * order;
/*********************************************************************
** The matrix is broken up into column blocks that are mapped one to a
** rank. Each column block is made up of Num_procs smaller square
** blocks of order block_order.
*********************************************************************/
Block_order = order/Num_procs;
colstart = Block_order * my_ID;
Colblock_size = order * Block_order;
Block_size = Block_order * Block_order;
/*********************************************************************
** Create the column block of the test matrix, the row block of the
** transposed matrix, and workspace (workspace only if #procs>1)
*********************************************************************/
A_p = (double *)malloc(Colblock_size*sizeof(double));
if (A_p == NULL){
printf(" Error allocating space for original matrix on node %d\n",my_ID);
error = 1;
}
bail_out(error);
B_p = (double *)malloc(Colblock_size*sizeof(double));
if (B_p == NULL){
printf(" Error allocating space for transpose matrix on node %d\n",my_ID);
error = 1;
}
bail_out(error);
if (Num_procs>1) {
Work_in_p = (double *)malloc(2*Block_size*sizeof(double));
if (Work_in_p == NULL){
printf(" Error allocating space for work on node %d\n",my_ID);
error = 1;
}
bail_out(error);
Work_out_p = Work_in_p + Block_size;
}
/* Fill the original column matrix */
istart = 0;
if (tiling) {
#ifdef COLLAPSE
#pragma omp parallel for private (i,it,jt) collapse(2)
#else
#pragma omp parallel for private (i,it,jt)
#endif
for (j=0; j<Block_order; j+=Tile_order)
for (i=0; i<order; i+=Tile_order)
for (jt=j; jt<MIN(Block_order,j+Tile_order);jt++)
for (it=i; it<MIN(order,i+Tile_order); it++) {
A(it,jt) = (double) (order*(jt+colstart) + it);
B(it,jt) = -1.0;
}
}
else {
#pragma omp parallel for private (i)
for (j=0;j<Block_order;j++)
for (i=0;i<order; i++) {
A(i,j) = (double) (order*(j+colstart) + i);
B(i,j) = -1.0;
}
}
for (iter = 0; iter<=iterations; iter++){
/* start timer after a warmup iteration */
if (iter == 1) {
MPI_Barrier(MPI_COMM_WORLD);
local_trans_time = wtime();
}
/* do the local transpose */
istart = colstart;
if (!tiling) {
#pragma omp parallel for private (j)
for (i=0; i<Block_order; i++)
for (j=0; j<Block_order; j++) {
B(j,i) = A(i,j);
}
}
else {
#ifdef COLLAPSE
#pragma omp parallel for private (j,it,jt) collapse(2)
#else
#pragma omp parallel for private (j,it,jt)
#endif
for (i=0; i<Block_order; i+=Tile_order)
for (j=0; j<Block_order; j+=Tile_order)
for (it=i; it<MIN(Block_order,i+Tile_order); it++)
for (jt=j; jt<MIN(Block_order,j+Tile_order);jt++) {
B(jt,it) = A(it,jt);
}
}
for (phase=1; phase<Num_procs; phase++){
recv_from = (my_ID + phase )%Num_procs;
send_to = (my_ID - phase + Num_procs)%Num_procs;
#ifndef SYNCHRONOUS
MPI_Irecv(Work_in_p, Block_size, MPI_DOUBLE,
recv_from, phase, MPI_COMM_WORLD, &recv_req);
#endif
istart = send_to*Block_order;
if (!tiling) {
#pragma omp parallel for private (j)
for (i=0; i<Block_order; i++)
for (j=0; j<Block_order; j++){
Work_out(j,i) = A(i,j);
}
}
else {
#ifdef COLLAPSE
#pragma omp parallel for private (j,it,jt) collapse(2)
#else
#pragma omp parallel for private (j,it,jt)
#endif
for (i=0; i<Block_order; i+=Tile_order)
for (j=0; j<Block_order; j+=Tile_order)
for (it=i; it<MIN(Block_order,i+Tile_order); it++)
for (jt=j; jt<MIN(Block_order,j+Tile_order);jt++) {
Work_out(jt,it) = A(it,jt);
}
}
#ifndef SYNCHRONOUS
MPI_Isend(Work_out_p, Block_size, MPI_DOUBLE, send_to,
phase, MPI_COMM_WORLD, &send_req);
MPI_Wait(&recv_req, &status);
MPI_Wait(&send_req, &status);
#else
MPI_Sendrecv(Work_out_p, Block_size, MPI_DOUBLE, send_to, phase,
Work_in_p, Block_size, MPI_DOUBLE,
recv_from, phase, MPI_COMM_WORLD, &status);
#endif
istart = recv_from*Block_order;
/* scatter received block to transposed matrix; no need to tile */
#pragma omp parallel for private (i)
for (j=0; j<Block_order; j++)
for (i=0; i<Block_order; i++) {
B(i,j) = Work_in(i,j);
}
} /* end of phase loop */
} /* end of iterations */
local_trans_time = wtime() - local_trans_time;
MPI_Reduce(&local_trans_time, &trans_time, 1, MPI_DOUBLE, MPI_MAX, root,
MPI_COMM_WORLD);
abserr = 0.0;
istart = 0;
#pragma omp parallel for private (i)
for (j=0;j<Block_order;j++) for (i=0;i<order; i++) {
abserr += ABS(B(i,j) - (double)(order*i + j+colstart));
}
MPI_Reduce(&abserr, &abserr_tot, 1, MPI_DOUBLE, MPI_SUM, root, MPI_COMM_WORLD);
if (my_ID == root) {
if (abserr_tot < epsilon) {
printf("Solution validates\n");
avgtime = trans_time/(double)iterations;
printf("Rate (MB/s): %lf Avg time (s): %lf\n",1.0E-06*bytes/avgtime, avgtime);
#ifdef VERBOSE
printf("Summed errors: %f \n", abserr);
#endif
}
else {
printf("ERROR: Aggregate squared error %lf exceeds threshold %e\n", abserr_tot, epsilon);
error = 1;
}
}
bail_out(error);
MPI_Finalize();
exit(EXIT_SUCCESS);
} /* end of main */
|
_hypre_utilities.h |
/*** DO NOT EDIT THIS FILE DIRECTLY (use 'headers' to generate) ***/
#ifndef hypre_UTILITIES_HEADER
#define hypre_UTILITIES_HEADER
#include "HYPRE_utilities.h"
#ifdef HYPRE_USING_OPENMP
#include <omp.h>
#endif
#ifdef __cplusplus
extern "C" {
#endif
/******************************************************************************
* Copyright 1998-2019 Lawrence Livermore National Security, LLC and other
* HYPRE Project Developers. See the top-level COPYRIGHT file for details.
*
* SPDX-License-Identifier: (Apache-2.0 OR MIT)
******************************************************************************/
/******************************************************************************
*
* General structures and values
*
*****************************************************************************/
#ifndef hypre_GENERAL_HEADER
#define hypre_GENERAL_HEADER
/* This allows us to consistently avoid 'int' throughout hypre */
typedef int hypre_int;
typedef long int hypre_longint;
typedef unsigned int hypre_uint;
typedef unsigned long int hypre_ulongint;
typedef unsigned long long int hypre_ulonglongint;
/* This allows us to consistently avoid 'double' throughout hypre */
typedef double hypre_double;
/*--------------------------------------------------------------------------
* Define various functions
*--------------------------------------------------------------------------*/
#ifndef hypre_max
#define hypre_max(a,b) (((a)<(b)) ? (b) : (a))
#endif
#ifndef hypre_min
#define hypre_min(a,b) (((a)<(b)) ? (a) : (b))
#endif
#ifndef hypre_abs
#define hypre_abs(a) (((a)>0) ? (a) : -(a))
#endif
#ifndef hypre_round
#define hypre_round(x) ( ((x) < 0.0) ? ((HYPRE_Int)(x - 0.5)) : ((HYPRE_Int)(x + 0.5)) )
#endif
#ifndef hypre_pow2
#define hypre_pow2(i) ( 1 << (i) )
#endif
#endif /* hypre_GENERAL_HEADER */
/******************************************************************************
* Copyright 1998-2019 Lawrence Livermore National Security, LLC and other
* HYPRE Project Developers. See the top-level COPYRIGHT file for details.
*
* SPDX-License-Identifier: (Apache-2.0 OR MIT)
******************************************************************************/
#ifndef hypre_PRINTF_HEADER
#define hypre_PRINTF_HEADER
#include <stdio.h>
/* printf.c */
// #ifdef HYPRE_BIGINT
HYPRE_Int hypre_ndigits( HYPRE_BigInt number );
HYPRE_Int hypre_printf( const char *format , ... );
HYPRE_Int hypre_fprintf( FILE *stream , const char *format, ... );
HYPRE_Int hypre_sprintf( char *s , const char *format, ... );
HYPRE_Int hypre_scanf( const char *format , ... );
HYPRE_Int hypre_fscanf( FILE *stream , const char *format, ... );
HYPRE_Int hypre_sscanf( char *s , const char *format, ... );
// #else
// #define hypre_printf printf
// #define hypre_fprintf fprintf
// #define hypre_sprintf sprintf
// #define hypre_scanf scanf
// #define hypre_fscanf fscanf
// #define hypre_sscanf sscanf
// #endif
#endif
/******************************************************************************
* Copyright 1998-2019 Lawrence Livermore National Security, LLC and other
* HYPRE Project Developers. See the top-level COPYRIGHT file for details.
*
* SPDX-License-Identifier: (Apache-2.0 OR MIT)
******************************************************************************/
#ifndef hypre_ERROR_HEADER
#define hypre_ERROR_HEADER
#include <assert.h>
/*--------------------------------------------------------------------------
* Global variable used in hypre error checking
*--------------------------------------------------------------------------*/
extern HYPRE_Int hypre__global_error;
#define hypre_error_flag hypre__global_error
/*--------------------------------------------------------------------------
* HYPRE error macros
*--------------------------------------------------------------------------*/
void hypre_error_handler(const char *filename, HYPRE_Int line, HYPRE_Int ierr, const char *msg);
#define hypre_error(IERR) hypre_error_handler(__FILE__, __LINE__, IERR, NULL)
#define hypre_error_w_msg(IERR, msg) hypre_error_handler(__FILE__, __LINE__, IERR, msg)
#define hypre_error_in_arg(IARG) hypre_error(HYPRE_ERROR_ARG | IARG<<3)
#if defined(HYPRE_DEBUG)
/* host assert */
#define hypre_assert(EX) do { if (!(EX)) { hypre_fprintf(stderr, "[%s, %d] hypre_assert failed: %s\n", __FILE__, __LINE__, #EX); hypre_error(1); assert(0); } } while (0)
/* device assert */
#if defined(HYPRE_USING_CUDA)
#define hypre_device_assert(EX) assert(EX)
#elif defined(HYPRE_USING_HIP)
/* FIXME: Currently, asserts in device kernels in HIP do not behave well */
#define hypre_device_assert(EX)
#endif
#else /* #ifdef HYPRE_DEBUG */
/* this is to silence compiler's unused variable warnings */
#ifdef __cplusplus
#define hypre_assert(EX) do { if (0) { static_cast<void> (EX); } } while (0)
#else
#define hypre_assert(EX) do { if (0) { (void) (EX); } } while (0)
#endif
#define hypre_device_assert(EX)
#endif
#endif /* hypre_ERROR_HEADER */
/******************************************************************************
* Copyright 1998-2019 Lawrence Livermore National Security, LLC and other
* HYPRE Project Developers. See the top-level COPYRIGHT file for details.
*
* SPDX-License-Identifier: (Apache-2.0 OR MIT)
******************************************************************************/
/******************************************************************************
*
* Fake mpi stubs to generate serial codes without mpi
*
*****************************************************************************/
#ifndef hypre_MPISTUBS
#define hypre_MPISTUBS
#ifdef __cplusplus
extern "C" {
#endif
#ifdef HYPRE_SEQUENTIAL
/******************************************************************************
* MPI stubs to generate serial codes without mpi
*****************************************************************************/
/*--------------------------------------------------------------------------
* Change all MPI names to hypre_MPI names to avoid link conflicts.
*
* NOTE: MPI_Comm is the only MPI symbol in the HYPRE user interface,
* and is defined in `HYPRE_utilities.h'.
*--------------------------------------------------------------------------*/
#define MPI_Comm hypre_MPI_Comm
#define MPI_Group hypre_MPI_Group
#define MPI_Request hypre_MPI_Request
#define MPI_Datatype hypre_MPI_Datatype
#define MPI_Status hypre_MPI_Status
#define MPI_Op hypre_MPI_Op
#define MPI_Aint hypre_MPI_Aint
#define MPI_Info hypre_MPI_Info
#define MPI_COMM_WORLD hypre_MPI_COMM_WORLD
#define MPI_COMM_NULL hypre_MPI_COMM_NULL
#define MPI_COMM_SELF hypre_MPI_COMM_SELF
#define MPI_COMM_TYPE_SHARED hypre_MPI_COMM_TYPE_SHARED
#define MPI_BOTTOM hypre_MPI_BOTTOM
#define MPI_FLOAT hypre_MPI_FLOAT
#define MPI_DOUBLE hypre_MPI_DOUBLE
#define MPI_LONG_DOUBLE hypre_MPI_LONG_DOUBLE
#define MPI_INT hypre_MPI_INT
#define MPI_LONG_LONG_INT hypre_MPI_INT
#define MPI_CHAR hypre_MPI_CHAR
#define MPI_LONG hypre_MPI_LONG
#define MPI_BYTE hypre_MPI_BYTE
#define MPI_C_DOUBLE_COMPLEX hypre_MPI_COMPLEX
#define MPI_SUM hypre_MPI_SUM
#define MPI_MIN hypre_MPI_MIN
#define MPI_MAX hypre_MPI_MAX
#define MPI_LOR hypre_MPI_LOR
#define MPI_LAND hypre_MPI_LAND
#define MPI_SUCCESS hypre_MPI_SUCCESS
#define MPI_STATUSES_IGNORE hypre_MPI_STATUSES_IGNORE
#define MPI_UNDEFINED hypre_MPI_UNDEFINED
#define MPI_REQUEST_NULL hypre_MPI_REQUEST_NULL
#define MPI_INFO_NULL hypre_MPI_INFO_NULL
#define MPI_ANY_SOURCE hypre_MPI_ANY_SOURCE
#define MPI_ANY_TAG hypre_MPI_ANY_TAG
#define MPI_SOURCE hypre_MPI_SOURCE
#define MPI_TAG hypre_MPI_TAG
#define MPI_Init hypre_MPI_Init
#define MPI_Finalize hypre_MPI_Finalize
#define MPI_Abort hypre_MPI_Abort
#define MPI_Wtime hypre_MPI_Wtime
#define MPI_Wtick hypre_MPI_Wtick
#define MPI_Barrier hypre_MPI_Barrier
#define MPI_Comm_create hypre_MPI_Comm_create
#define MPI_Comm_dup hypre_MPI_Comm_dup
#define MPI_Comm_f2c hypre_MPI_Comm_f2c
#define MPI_Comm_group hypre_MPI_Comm_group
#define MPI_Comm_size hypre_MPI_Comm_size
#define MPI_Comm_rank hypre_MPI_Comm_rank
#define MPI_Comm_free hypre_MPI_Comm_free
#define MPI_Comm_split hypre_MPI_Comm_split
#define MPI_Comm_split_type hypre_MPI_Comm_split_type
#define MPI_Group_incl hypre_MPI_Group_incl
#define MPI_Group_free hypre_MPI_Group_free
#define MPI_Address hypre_MPI_Address
#define MPI_Get_count hypre_MPI_Get_count
#define MPI_Alltoall hypre_MPI_Alltoall
#define MPI_Allgather hypre_MPI_Allgather
#define MPI_Allgatherv hypre_MPI_Allgatherv
#define MPI_Gather hypre_MPI_Gather
#define MPI_Gatherv hypre_MPI_Gatherv
#define MPI_Scatter hypre_MPI_Scatter
#define MPI_Scatterv hypre_MPI_Scatterv
#define MPI_Bcast hypre_MPI_Bcast
#define MPI_Send hypre_MPI_Send
#define MPI_Recv hypre_MPI_Recv
#define MPI_Isend hypre_MPI_Isend
#define MPI_Irecv hypre_MPI_Irecv
#define MPI_Send_init hypre_MPI_Send_init
#define MPI_Recv_init hypre_MPI_Recv_init
#define MPI_Irsend hypre_MPI_Irsend
#define MPI_Startall hypre_MPI_Startall
#define MPI_Probe hypre_MPI_Probe
#define MPI_Iprobe hypre_MPI_Iprobe
#define MPI_Test hypre_MPI_Test
#define MPI_Testall hypre_MPI_Testall
#define MPI_Wait hypre_MPI_Wait
#define MPI_Waitall hypre_MPI_Waitall
#define MPI_Waitany hypre_MPI_Waitany
#define MPI_Allreduce hypre_MPI_Allreduce
#define MPI_Reduce hypre_MPI_Reduce
#define MPI_Scan hypre_MPI_Scan
#define MPI_Request_free hypre_MPI_Request_free
#define MPI_Type_contiguous hypre_MPI_Type_contiguous
#define MPI_Type_vector hypre_MPI_Type_vector
#define MPI_Type_hvector hypre_MPI_Type_hvector
#define MPI_Type_struct hypre_MPI_Type_struct
#define MPI_Type_commit hypre_MPI_Type_commit
#define MPI_Type_free hypre_MPI_Type_free
#define MPI_Op_free hypre_MPI_Op_free
#define MPI_Op_create hypre_MPI_Op_create
#define MPI_User_function hypre_MPI_User_function
#define MPI_Info_create hypre_MPI_Info_create
/*--------------------------------------------------------------------------
* Types, etc.
*--------------------------------------------------------------------------*/
/* These types have associated creation and destruction routines */
typedef HYPRE_Int hypre_MPI_Comm;
typedef HYPRE_Int hypre_MPI_Group;
typedef HYPRE_Int hypre_MPI_Request;
typedef HYPRE_Int hypre_MPI_Datatype;
typedef void (hypre_MPI_User_function) ();
typedef struct
{
HYPRE_Int hypre_MPI_SOURCE;
HYPRE_Int hypre_MPI_TAG;
} hypre_MPI_Status;
typedef HYPRE_Int hypre_MPI_Op;
typedef HYPRE_Int hypre_MPI_Aint;
typedef HYPRE_Int hypre_MPI_Info;
#define hypre_MPI_COMM_SELF 1
#define hypre_MPI_COMM_WORLD 0
#define hypre_MPI_COMM_NULL -1
#define hypre_MPI_COMM_TYPE_SHARED 0
#define hypre_MPI_BOTTOM 0x0
#define hypre_MPI_FLOAT 0
#define hypre_MPI_DOUBLE 1
#define hypre_MPI_LONG_DOUBLE 2
#define hypre_MPI_INT 3
#define hypre_MPI_CHAR 4
#define hypre_MPI_LONG 5
#define hypre_MPI_BYTE 6
#define hypre_MPI_REAL 7
#define hypre_MPI_COMPLEX 8
#define hypre_MPI_SUM 0
#define hypre_MPI_MIN 1
#define hypre_MPI_MAX 2
#define hypre_MPI_LOR 3
#define hypre_MPI_LAND 4
#define hypre_MPI_SUCCESS 0
#define hypre_MPI_STATUSES_IGNORE 0
#define hypre_MPI_UNDEFINED -9999
#define hypre_MPI_REQUEST_NULL 0
#define hypre_MPI_INFO_NULL 0
#define hypre_MPI_ANY_SOURCE 1
#define hypre_MPI_ANY_TAG 1
#else
/******************************************************************************
* MPI stubs to do casting of HYPRE_Int and hypre_int correctly
*****************************************************************************/
typedef MPI_Comm hypre_MPI_Comm;
typedef MPI_Group hypre_MPI_Group;
typedef MPI_Request hypre_MPI_Request;
typedef MPI_Datatype hypre_MPI_Datatype;
typedef MPI_Status hypre_MPI_Status;
typedef MPI_Op hypre_MPI_Op;
typedef MPI_Aint hypre_MPI_Aint;
typedef MPI_Info hypre_MPI_Info;
typedef MPI_User_function hypre_MPI_User_function;
#define hypre_MPI_COMM_WORLD MPI_COMM_WORLD
#define hypre_MPI_COMM_NULL MPI_COMM_NULL
#define hypre_MPI_BOTTOM MPI_BOTTOM
#define hypre_MPI_COMM_SELF MPI_COMM_SELF
#define hypre_MPI_COMM_TYPE_SHARED MPI_COMM_TYPE_SHARED
#define hypre_MPI_FLOAT MPI_FLOAT
#define hypre_MPI_DOUBLE MPI_DOUBLE
#define hypre_MPI_LONG_DOUBLE MPI_LONG_DOUBLE
/* HYPRE_MPI_INT is defined in HYPRE_utilities.h */
#define hypre_MPI_INT HYPRE_MPI_INT
#define hypre_MPI_CHAR MPI_CHAR
#define hypre_MPI_LONG MPI_LONG
#define hypre_MPI_BYTE MPI_BYTE
/* HYPRE_MPI_REAL is defined in HYPRE_utilities.h */
#define hypre_MPI_REAL HYPRE_MPI_REAL
/* HYPRE_MPI_COMPLEX is defined in HYPRE_utilities.h */
#define hypre_MPI_COMPLEX HYPRE_MPI_COMPLEX
#define hypre_MPI_SUM MPI_SUM
#define hypre_MPI_MIN MPI_MIN
#define hypre_MPI_MAX MPI_MAX
#define hypre_MPI_LOR MPI_LOR
#define hypre_MPI_SUCCESS MPI_SUCCESS
#define hypre_MPI_STATUSES_IGNORE MPI_STATUSES_IGNORE
#define hypre_MPI_UNDEFINED MPI_UNDEFINED
#define hypre_MPI_REQUEST_NULL MPI_REQUEST_NULL
#define hypre_MPI_INFO_NULL MPI_INFO_NULL
#define hypre_MPI_ANY_SOURCE MPI_ANY_SOURCE
#define hypre_MPI_ANY_TAG MPI_ANY_TAG
#define hypre_MPI_SOURCE MPI_SOURCE
#define hypre_MPI_TAG MPI_TAG
#define hypre_MPI_LAND MPI_LAND
#endif
/******************************************************************************
* Everything below this applies to both ifdef cases above
*****************************************************************************/
/*--------------------------------------------------------------------------
* Prototypes
*--------------------------------------------------------------------------*/
/* mpistubs.c */
HYPRE_Int hypre_MPI_Init( hypre_int *argc , char ***argv );
HYPRE_Int hypre_MPI_Finalize( void );
HYPRE_Int hypre_MPI_Abort( hypre_MPI_Comm comm , HYPRE_Int errorcode );
HYPRE_Real hypre_MPI_Wtime( void );
HYPRE_Real hypre_MPI_Wtick( void );
HYPRE_Int hypre_MPI_Barrier( hypre_MPI_Comm comm );
HYPRE_Int hypre_MPI_Comm_create( hypre_MPI_Comm comm , hypre_MPI_Group group , hypre_MPI_Comm *newcomm );
HYPRE_Int hypre_MPI_Comm_dup( hypre_MPI_Comm comm , hypre_MPI_Comm *newcomm );
hypre_MPI_Comm hypre_MPI_Comm_f2c( hypre_int comm );
HYPRE_Int hypre_MPI_Comm_size( hypre_MPI_Comm comm , HYPRE_Int *size );
HYPRE_Int hypre_MPI_Comm_rank( hypre_MPI_Comm comm , HYPRE_Int *rank );
HYPRE_Int hypre_MPI_Comm_free( hypre_MPI_Comm *comm );
HYPRE_Int hypre_MPI_Comm_group( hypre_MPI_Comm comm , hypre_MPI_Group *group );
HYPRE_Int hypre_MPI_Comm_split( hypre_MPI_Comm comm, HYPRE_Int n, HYPRE_Int m, hypre_MPI_Comm * comms );
HYPRE_Int hypre_MPI_Group_incl( hypre_MPI_Group group , HYPRE_Int n , HYPRE_Int *ranks , hypre_MPI_Group *newgroup );
HYPRE_Int hypre_MPI_Group_free( hypre_MPI_Group *group );
HYPRE_Int hypre_MPI_Address( void *location , hypre_MPI_Aint *address );
HYPRE_Int hypre_MPI_Get_count( hypre_MPI_Status *status , hypre_MPI_Datatype datatype , HYPRE_Int *count );
HYPRE_Int hypre_MPI_Alltoall( void *sendbuf , HYPRE_Int sendcount , hypre_MPI_Datatype sendtype , void *recvbuf , HYPRE_Int recvcount , hypre_MPI_Datatype recvtype , hypre_MPI_Comm comm );
HYPRE_Int hypre_MPI_Allgather( void *sendbuf , HYPRE_Int sendcount , hypre_MPI_Datatype sendtype , void *recvbuf , HYPRE_Int recvcount , hypre_MPI_Datatype recvtype , hypre_MPI_Comm comm );
HYPRE_Int hypre_MPI_Allgatherv( void *sendbuf , HYPRE_Int sendcount , hypre_MPI_Datatype sendtype , void *recvbuf , HYPRE_Int *recvcounts , HYPRE_Int *displs , hypre_MPI_Datatype recvtype , hypre_MPI_Comm comm );
HYPRE_Int hypre_MPI_Gather( void *sendbuf , HYPRE_Int sendcount , hypre_MPI_Datatype sendtype , void *recvbuf , HYPRE_Int recvcount , hypre_MPI_Datatype recvtype , HYPRE_Int root , hypre_MPI_Comm comm );
HYPRE_Int hypre_MPI_Gatherv( void *sendbuf , HYPRE_Int sendcount , hypre_MPI_Datatype sendtype , void *recvbuf , HYPRE_Int *recvcounts , HYPRE_Int *displs , hypre_MPI_Datatype recvtype , HYPRE_Int root , hypre_MPI_Comm comm );
HYPRE_Int hypre_MPI_Scatter( void *sendbuf , HYPRE_Int sendcount , hypre_MPI_Datatype sendtype , void *recvbuf , HYPRE_Int recvcount , hypre_MPI_Datatype recvtype , HYPRE_Int root , hypre_MPI_Comm comm );
HYPRE_Int hypre_MPI_Scatterv( void *sendbuf , HYPRE_Int *sendcounts , HYPRE_Int *displs, hypre_MPI_Datatype sendtype , void *recvbuf , HYPRE_Int recvcount , hypre_MPI_Datatype recvtype , HYPRE_Int root , hypre_MPI_Comm comm );
HYPRE_Int hypre_MPI_Bcast( void *buffer , HYPRE_Int count , hypre_MPI_Datatype datatype , HYPRE_Int root , hypre_MPI_Comm comm );
HYPRE_Int hypre_MPI_Send( void *buf , HYPRE_Int count , hypre_MPI_Datatype datatype , HYPRE_Int dest , HYPRE_Int tag , hypre_MPI_Comm comm );
HYPRE_Int hypre_MPI_Recv( void *buf , HYPRE_Int count , hypre_MPI_Datatype datatype , HYPRE_Int source , HYPRE_Int tag , hypre_MPI_Comm comm , hypre_MPI_Status *status );
HYPRE_Int hypre_MPI_Isend( void *buf , HYPRE_Int count , hypre_MPI_Datatype datatype , HYPRE_Int dest , HYPRE_Int tag , hypre_MPI_Comm comm , hypre_MPI_Request *request );
HYPRE_Int hypre_MPI_Irecv( void *buf , HYPRE_Int count , hypre_MPI_Datatype datatype , HYPRE_Int source , HYPRE_Int tag , hypre_MPI_Comm comm , hypre_MPI_Request *request );
HYPRE_Int hypre_MPI_Send_init( void *buf , HYPRE_Int count , hypre_MPI_Datatype datatype , HYPRE_Int dest , HYPRE_Int tag , hypre_MPI_Comm comm , hypre_MPI_Request *request );
HYPRE_Int hypre_MPI_Recv_init( void *buf , HYPRE_Int count , hypre_MPI_Datatype datatype , HYPRE_Int dest , HYPRE_Int tag , hypre_MPI_Comm comm , hypre_MPI_Request *request );
HYPRE_Int hypre_MPI_Irsend( void *buf , HYPRE_Int count , hypre_MPI_Datatype datatype , HYPRE_Int dest , HYPRE_Int tag , hypre_MPI_Comm comm , hypre_MPI_Request *request );
HYPRE_Int hypre_MPI_Startall( HYPRE_Int count , hypre_MPI_Request *array_of_requests );
HYPRE_Int hypre_MPI_Probe( HYPRE_Int source , HYPRE_Int tag , hypre_MPI_Comm comm , hypre_MPI_Status *status );
HYPRE_Int hypre_MPI_Iprobe( HYPRE_Int source , HYPRE_Int tag , hypre_MPI_Comm comm , HYPRE_Int *flag , hypre_MPI_Status *status );
HYPRE_Int hypre_MPI_Test( hypre_MPI_Request *request , HYPRE_Int *flag , hypre_MPI_Status *status );
HYPRE_Int hypre_MPI_Testall( HYPRE_Int count , hypre_MPI_Request *array_of_requests , HYPRE_Int *flag , hypre_MPI_Status *array_of_statuses );
HYPRE_Int hypre_MPI_Wait( hypre_MPI_Request *request , hypre_MPI_Status *status );
HYPRE_Int hypre_MPI_Waitall( HYPRE_Int count , hypre_MPI_Request *array_of_requests , hypre_MPI_Status *array_of_statuses );
HYPRE_Int hypre_MPI_Waitany( HYPRE_Int count , hypre_MPI_Request *array_of_requests , HYPRE_Int *index , hypre_MPI_Status *status );
HYPRE_Int hypre_MPI_Allreduce( void *sendbuf , void *recvbuf , HYPRE_Int count , hypre_MPI_Datatype datatype , hypre_MPI_Op op , hypre_MPI_Comm comm );
HYPRE_Int hypre_MPI_Reduce( void *sendbuf , void *recvbuf , HYPRE_Int count , hypre_MPI_Datatype datatype , hypre_MPI_Op op , HYPRE_Int root , hypre_MPI_Comm comm );
HYPRE_Int hypre_MPI_Scan( void *sendbuf , void *recvbuf , HYPRE_Int count , hypre_MPI_Datatype datatype , hypre_MPI_Op op , hypre_MPI_Comm comm );
HYPRE_Int hypre_MPI_Request_free( hypre_MPI_Request *request );
HYPRE_Int hypre_MPI_Type_contiguous( HYPRE_Int count , hypre_MPI_Datatype oldtype , hypre_MPI_Datatype *newtype );
HYPRE_Int hypre_MPI_Type_vector( HYPRE_Int count , HYPRE_Int blocklength , HYPRE_Int stride , hypre_MPI_Datatype oldtype , hypre_MPI_Datatype *newtype );
HYPRE_Int hypre_MPI_Type_hvector( HYPRE_Int count , HYPRE_Int blocklength , hypre_MPI_Aint stride , hypre_MPI_Datatype oldtype , hypre_MPI_Datatype *newtype );
HYPRE_Int hypre_MPI_Type_struct( HYPRE_Int count , HYPRE_Int *array_of_blocklengths , hypre_MPI_Aint *array_of_displacements , hypre_MPI_Datatype *array_of_types , hypre_MPI_Datatype *newtype );
HYPRE_Int hypre_MPI_Type_commit( hypre_MPI_Datatype *datatype );
HYPRE_Int hypre_MPI_Type_free( hypre_MPI_Datatype *datatype );
HYPRE_Int hypre_MPI_Op_free( hypre_MPI_Op *op );
HYPRE_Int hypre_MPI_Op_create( hypre_MPI_User_function *function , hypre_int commute , hypre_MPI_Op *op );
#if defined(HYPRE_USING_GPU)
HYPRE_Int hypre_MPI_Comm_split_type(hypre_MPI_Comm comm, HYPRE_Int split_type, HYPRE_Int key, hypre_MPI_Info info, hypre_MPI_Comm *newcomm);
HYPRE_Int hypre_MPI_Info_create(hypre_MPI_Info *info);
HYPRE_Int hypre_MPI_Info_free( hypre_MPI_Info *info );
#endif
#ifdef __cplusplus
}
#endif
#endif
/******************************************************************************
* Copyright 1998-2019 Lawrence Livermore National Security, LLC and other
* HYPRE Project Developers. See the top-level COPYRIGHT file for details.
*
* SPDX-License-Identifier: (Apache-2.0 OR MIT)
******************************************************************************/
#ifndef HYPRE_SMP_HEADER
#define HYPRE_SMP_HEADER
#endif
#define HYPRE_SMP_SCHEDULE schedule(static)
/******************************************************************************
* Copyright 1998-2019 Lawrence Livermore National Security, LLC and other
* HYPRE Project Developers. See the top-level COPYRIGHT file for details.
*
* SPDX-License-Identifier: (Apache-2.0 OR MIT)
******************************************************************************/
/******************************************************************************
*
* Header file for memory management utilities
*
* The abstract memory model has a Host (think CPU) and a Device (think GPU) and
* three basic types of memory management utilities:
*
* 1. Malloc(..., location)
* location=LOCATION_DEVICE - malloc memory on the device
* location=LOCATION_HOST - malloc memory on the host
* 2. MemCopy(..., method)
* method=HOST_TO_DEVICE - copy from host to device
* method=DEVICE_TO_HOST - copy from device to host
* method=DEVICE_TO_DEVICE - copy from device to device
* 3. SetExecutionMode
* location=LOCATION_DEVICE - execute on the device
* location=LOCATION_HOST - execute on the host
*
* Although the abstract model does not explicitly reflect a managed memory
* model (i.e., unified memory), it can support it. Here is a summary of how
* the abstract model would be mapped to specific hardware scenarios:
*
* Not using a device, not using managed memory
* Malloc(..., location)
* location=LOCATION_DEVICE - host malloc e.g., malloc
* location=LOCATION_HOST - host malloc e.g., malloc
* MemoryCopy(..., locTo,locFrom)
* locTo=LOCATION_HOST, locFrom=LOCATION_DEVICE - copy from host to host e.g., memcpy
* locTo=LOCATION_DEVICE, locFrom=LOCATION_HOST - copy from host to host e.g., memcpy
* locTo=LOCATION_DEVICE, locFrom=LOCATION_DEVICE - copy from host to host e.g., memcpy
* SetExecutionMode
* location=LOCATION_DEVICE - execute on the host
* location=LOCATION_HOST - execute on the host
*
* Using a device, not using managed memory
* Malloc(..., location)
* location=LOCATION_DEVICE - device malloc e.g., cudaMalloc
* location=LOCATION_HOST - host malloc e.g., malloc
* MemoryCopy(..., locTo,locFrom)
* locTo=LOCATION_HOST, locFrom=LOCATION_DEVICE - copy from device to host e.g., cudaMemcpy
* locTo=LOCATION_DEVICE, locFrom=LOCATION_HOST - copy from host to device e.g., cudaMemcpy
* locTo=LOCATION_DEVICE, locFrom=LOCATION_DEVICE - copy from device to device e.g., cudaMemcpy
* SetExecutionMode
* location=LOCATION_DEVICE - execute on the device
* location=LOCATION_HOST - execute on the host
*
* Using a device, using managed memory
* Malloc(..., location)
* location=LOCATION_DEVICE - managed malloc e.g., cudaMallocManaged
* location=LOCATION_HOST - host malloc e.g., malloc
* MemoryCopy(..., locTo,locFrom)
* locTo=LOCATION_HOST, locFrom=LOCATION_DEVICE - copy from device to host e.g., cudaMallocManaged
* locTo=LOCATION_DEVICE, locFrom=LOCATION_HOST - copy from host to device e.g., cudaMallocManaged
* locTo=LOCATION_DEVICE, locFrom=LOCATION_DEVICE - copy from device to device e.g., cudaMallocManaged
* SetExecutionMode
* location=LOCATION_DEVICE - execute on the device
* location=LOCATION_HOST - execute on the host
*
*****************************************************************************/
#ifndef hypre_MEMORY_HEADER
#define hypre_MEMORY_HEADER
#include <stdio.h>
#include <stdlib.h>
#if defined(HYPRE_USING_UMPIRE)
#include "umpire/interface/umpire.h"
#define HYPRE_UMPIRE_POOL_NAME_MAX_LEN 1024
#endif
/* stringification:
* _Pragma(string-literal), so we need to cast argument to a string
* The three dots as last argument of the macro tells compiler that this is a variadic macro.
* I.e. this is a macro that receives variable number of arguments.
*/
#define HYPRE_STR(...) #__VA_ARGS__
#define HYPRE_XSTR(...) HYPRE_STR(__VA_ARGS__)
#ifdef __cplusplus
extern "C" {
#endif
typedef enum _hypre_MemoryLocation
{
hypre_MEMORY_UNDEFINED = -1,
hypre_MEMORY_HOST ,
hypre_MEMORY_HOST_PINNED ,
hypre_MEMORY_DEVICE ,
hypre_MEMORY_UNIFIED
} hypre_MemoryLocation;
/*-------------------------------------------------------
* hypre_GetActualMemLocation
* return actual location based on the selected memory model
*-------------------------------------------------------*/
static inline hypre_MemoryLocation
hypre_GetActualMemLocation(HYPRE_MemoryLocation location)
{
if (location == HYPRE_MEMORY_HOST)
{
return hypre_MEMORY_HOST;
}
if (location == HYPRE_MEMORY_DEVICE)
{
#if defined(HYPRE_USING_HOST_MEMORY)
return hypre_MEMORY_HOST;
#elif defined(HYPRE_USING_DEVICE_MEMORY)
return hypre_MEMORY_DEVICE;
#elif defined(HYPRE_USING_UNIFIED_MEMORY)
return hypre_MEMORY_UNIFIED;
#else
#error Wrong HYPRE memory setting.
#endif
}
return hypre_MEMORY_UNDEFINED;
}
#ifdef HYPRE_USING_MEMORY_TRACKER
typedef struct
{
char _action[16];
void *_ptr;
size_t _nbytes;
hypre_MemoryLocation _memory_location;
char _filename[256];
char _function[256];
HYPRE_Int _line;
size_t _pair;
} hypre_MemoryTrackerEntry;
typedef struct
{
size_t actual_size;
size_t alloced_size;
size_t prev_end;
hypre_MemoryTrackerEntry *data;
} hypre_MemoryTracker;
/* These Allocs are with memory tracker, for debug */
#define hypre_TAlloc(type, count, location) \
( \
{ \
void *ptr = hypre_MAlloc((size_t)(sizeof(type) * (count)), location); \
hypre_MemoryTrackerInsert("malloc", ptr, sizeof(type)*(count), hypre_GetActualMemLocation(location), __FILE__, __func__, __LINE__);\
(type *) ptr; \
} \
)
#define _hypre_TAlloc(type, count, location) \
( \
{ \
void *ptr = _hypre_MAlloc((size_t)(sizeof(type) * (count)), location); \
hypre_MemoryTrackerInsert("malloc", ptr, sizeof(type)*(count), location, __FILE__, __func__, __LINE__); \
(type *) ptr; \
} \
)
#define hypre_CTAlloc(type, count, location) \
( \
{ \
void *ptr = hypre_CAlloc((size_t)(count), (size_t)sizeof(type), location); \
hypre_MemoryTrackerInsert("calloc", ptr, sizeof(type)*(count), hypre_GetActualMemLocation(location), __FILE__, __func__, __LINE__);\
(type *) ptr; \
} \
)
#define hypre_TReAlloc(ptr, type, count, location) \
( \
{ \
hypre_MemoryTrackerInsert("rfree", ptr, (size_t) -1, hypre_GetActualMemLocation(location), __FILE__, __func__, __LINE__); \
void *new_ptr = hypre_ReAlloc((char *)ptr, (size_t)(sizeof(type) * (count)), location); \
hypre_MemoryTrackerInsert("rmalloc", new_ptr, sizeof(type)*(count), hypre_GetActualMemLocation(location), __FILE__, __func__, __LINE__);\
(type *) new_ptr; \
} \
)
#define hypre_TReAlloc_v2(ptr, old_type, old_count, new_type, new_count, location) \
( \
{ \
hypre_MemoryTrackerInsert("rfree", ptr, sizeof(old_type)*(old_count), hypre_GetActualMemLocation(location), __FILE__, __func__, __LINE__); \
void *new_ptr = hypre_ReAlloc_v2((char *)ptr, (size_t)(sizeof(old_type)*(old_count)), (size_t)(sizeof(new_type)*(new_count)), location); \
hypre_MemoryTrackerInsert("rmalloc", new_ptr, sizeof(new_type)*(new_count), hypre_GetActualMemLocation(location), __FILE__, __func__, __LINE__);\
(new_type *) new_ptr; \
} \
)
#define hypre_TMemcpy(dst, src, type, count, locdst, locsrc) \
( \
{ \
hypre_Memcpy((void *)(dst), (void *)(src), (size_t)(sizeof(type) * (count)), locdst, locsrc); \
} \
)
#define hypre_TFree(ptr, location) \
( \
{ \
hypre_MemoryTrackerInsert("free", ptr, (size_t) -1, hypre_GetActualMemLocation(location), __FILE__, __func__, __LINE__); \
hypre_Free((void *)ptr, location); \
ptr = NULL; \
} \
)
#define _hypre_TFree(ptr, location) \
( \
{ \
hypre_MemoryTrackerInsert("free", ptr, (size_t) -1, location, __FILE__, __func__, __LINE__); \
_hypre_Free((void *)ptr, location); \
ptr = NULL; \
} \
)
#else /* #ifdef HYPRE_USING_MEMORY_TRACKER */
#define hypre_TAlloc(type, count, location) \
( (type *) hypre_MAlloc((size_t)(sizeof(type) * (count)), location) )
#define _hypre_TAlloc(type, count, location) \
( (type *) _hypre_MAlloc((size_t)(sizeof(type) * (count)), location) )
#define hypre_CTAlloc(type, count, location) \
( (type *) hypre_CAlloc((size_t)(count), (size_t)sizeof(type), location) )
#define hypre_TReAlloc(ptr, type, count, location) \
( (type *) hypre_ReAlloc((char *)ptr, (size_t)(sizeof(type) * (count)), location) )
#define hypre_TReAlloc_v2(ptr, old_type, old_count, new_type, new_count, location) \
( (new_type *) hypre_ReAlloc_v2((char *)ptr, (size_t)(sizeof(old_type)*(old_count)), (size_t)(sizeof(new_type)*(new_count)), location) )
#define hypre_TMemcpy(dst, src, type, count, locdst, locsrc) \
(hypre_Memcpy((void *)(dst), (void *)(src), (size_t)(sizeof(type) * (count)), locdst, locsrc))
#define hypre_TFree(ptr, location) \
( hypre_Free((void *)ptr, location), ptr = NULL )
#define _hypre_TFree(ptr, location) \
( _hypre_Free((void *)ptr, location), ptr = NULL )
#endif /* #ifdef HYPRE_USING_MEMORY_TRACKER */
/*--------------------------------------------------------------------------
* Prototypes
*--------------------------------------------------------------------------*/
/* memory.c */
void * hypre_Memset(void *ptr, HYPRE_Int value, size_t num, HYPRE_MemoryLocation location);
void hypre_MemPrefetch(void *ptr, size_t size, HYPRE_MemoryLocation location);
void * hypre_MAlloc(size_t size, HYPRE_MemoryLocation location);
void * hypre_CAlloc( size_t count, size_t elt_size, HYPRE_MemoryLocation location);
void hypre_Free(void *ptr, HYPRE_MemoryLocation location);
void hypre_Memcpy(void *dst, void *src, size_t size, HYPRE_MemoryLocation loc_dst, HYPRE_MemoryLocation loc_src);
void * hypre_ReAlloc(void *ptr, size_t size, HYPRE_MemoryLocation location);
void * hypre_ReAlloc_v2(void *ptr, size_t old_size, size_t new_size, HYPRE_MemoryLocation location);
void * _hypre_MAlloc(size_t size, hypre_MemoryLocation location);
void _hypre_Free(void *ptr, hypre_MemoryLocation location);
HYPRE_ExecutionPolicy hypre_GetExecPolicy1(HYPRE_MemoryLocation location);
HYPRE_ExecutionPolicy hypre_GetExecPolicy2(HYPRE_MemoryLocation location1, HYPRE_MemoryLocation location2);
HYPRE_Int hypre_GetPointerLocation(const void *ptr, hypre_MemoryLocation *memory_location);
HYPRE_Int hypre_PrintMemoryTracker();
HYPRE_Int hypre_SetCubMemPoolSize( hypre_uint bin_growth, hypre_uint min_bin, hypre_uint max_bin, size_t max_cached_bytes );
HYPRE_Int hypre_umpire_host_pooled_allocate(void **ptr, size_t nbytes);
HYPRE_Int hypre_umpire_host_pooled_free(void *ptr);
void *hypre_umpire_host_pooled_realloc(void *ptr, size_t size);
HYPRE_Int hypre_umpire_device_pooled_allocate(void **ptr, size_t nbytes);
HYPRE_Int hypre_umpire_device_pooled_free(void *ptr);
HYPRE_Int hypre_umpire_um_pooled_allocate(void **ptr, size_t nbytes);
HYPRE_Int hypre_umpire_um_pooled_free(void *ptr);
HYPRE_Int hypre_umpire_pinned_pooled_allocate(void **ptr, size_t nbytes);
HYPRE_Int hypre_umpire_pinned_pooled_free(void *ptr);
#ifdef HYPRE_USING_MEMORY_TRACKER
hypre_MemoryTracker * hypre_MemoryTrackerCreate();
void hypre_MemoryTrackerDestroy(hypre_MemoryTracker *tracker);
void hypre_MemoryTrackerInsert(const char *action, void *ptr, size_t nbytes, hypre_MemoryLocation memory_location, const char *filename, const char *function, HYPRE_Int line);
HYPRE_Int hypre_PrintMemoryTracker();
#endif
/* memory_dmalloc.c */
HYPRE_Int hypre_InitMemoryDebugDML( HYPRE_Int id );
HYPRE_Int hypre_FinalizeMemoryDebugDML( void );
char *hypre_MAllocDML( HYPRE_Int size , char *file , HYPRE_Int line );
char *hypre_CAllocDML( HYPRE_Int count , HYPRE_Int elt_size , char *file , HYPRE_Int line );
char *hypre_ReAllocDML( char *ptr , HYPRE_Int size , char *file , HYPRE_Int line );
void hypre_FreeDML( char *ptr , char *file , HYPRE_Int line );
#ifdef __cplusplus
}
#endif
#endif
/******************************************************************************
* Copyright 1998-2019 Lawrence Livermore National Security, LLC and other
* HYPRE Project Developers. See the top-level COPYRIGHT file for details.
*
* SPDX-License-Identifier: (Apache-2.0 OR MIT)
******************************************************************************/
#ifndef HYPRE_OMP_DEVICE_H
#define HYPRE_OMP_DEVICE_H
#if defined(HYPRE_USING_DEVICE_OPENMP)
#include "omp.h"
/* OpenMP 4.5 device memory management */
extern HYPRE_Int hypre__global_offload;
extern HYPRE_Int hypre__offload_device_num;
extern HYPRE_Int hypre__offload_host_num;
/* stats */
extern size_t hypre__target_allc_count;
extern size_t hypre__target_free_count;
extern size_t hypre__target_allc_bytes;
extern size_t hypre__target_free_bytes;
extern size_t hypre__target_htod_count;
extern size_t hypre__target_dtoh_count;
extern size_t hypre__target_htod_bytes;
extern size_t hypre__target_dtoh_bytes;
/* CHECK MODE: check if offloading has effect (turned on when configured with --enable-debug)
* if we ``enter'' an address, it should not exist in device [o.w NO EFFECT]
* if we ``exit'' or ''update'' an address, it should exist in device [o.w ERROR]
* hypre__offload_flag: 0 == OK; 1 == WRONG
*/
#ifdef HYPRE_DEVICE_OPENMP_CHECK
#define HYPRE_OFFLOAD_FLAG(devnum, hptr, type) HYPRE_Int hypre__offload_flag = (type[1] == 'n') == omp_target_is_present(hptr, devnum);
#else
#define HYPRE_OFFLOAD_FLAG(...) HYPRE_Int hypre__offload_flag = 0; /* non-debug mode, always OK */
#endif
/* OMP 4.5 offloading macro */
#define hypre_omp_device_offload(devnum, hptr, datatype, offset, count, type1, type2) \
{\
/* devnum: device number \
* hptr: host poiter \
* datatype \
* type1: ``e(n)ter'', ''e(x)it'', or ``u(p)date'' \
* type2: ``(a)lloc'', ``(t)o'', ``(d)elete'', ''(f)rom'' \
*/ \
datatype *hypre__offload_hptr = (datatype *) hptr; \
/* if hypre__global_offload == 0, or
* hptr (host pointer) == NULL,
* this offload will be IGNORED */ \
if (hypre__global_offload && hypre__offload_hptr != NULL) { \
/* offloading offset and size (in datatype) */ \
size_t hypre__offload_offset = offset, hypre__offload_size = count; \
/* in the CHECK mode, we test if this offload has effect */ \
HYPRE_OFFLOAD_FLAG(devnum, hypre__offload_hptr, type1) \
if (hypre__offload_flag) { \
printf("[!NO Effect! %s %d] device %d target: %6s %6s, data %p, [%ld:%ld]\n", __FILE__, __LINE__, devnum, type1, type2, (void *)hypre__offload_hptr, hypre__offload_offset, hypre__offload_size); exit(0); \
} else { \
size_t offload_bytes = count * sizeof(datatype); \
/* printf("[ %s %d] device %d target: %6s %6s, data %p, [%d:%d]\n", __FILE__, __LINE__, devnum, type1, type2, (void *)hypre__offload_hptr, hypre__offload_offset, hypre__offload_size); */ \
if (type1[1] == 'n' && type2[0] == 't') { \
/* enter to */\
hypre__target_allc_count ++; \
hypre__target_allc_bytes += offload_bytes; \
hypre__target_htod_count ++; \
hypre__target_htod_bytes += offload_bytes; \
_Pragma (HYPRE_XSTR(omp target enter data map(to:hypre__offload_hptr[hypre__offload_offset:hypre__offload_size]))) \
} else if (type1[1] == 'n' && type2[0] == 'a') { \
/* enter alloc */ \
hypre__target_allc_count ++; \
hypre__target_allc_bytes += offload_bytes; \
_Pragma (HYPRE_XSTR(omp target enter data map(alloc:hypre__offload_hptr[hypre__offload_offset:hypre__offload_size]))) \
} else if (type1[1] == 'x' && type2[0] == 'd') { \
/* exit delete */\
hypre__target_free_count ++; \
hypre__target_free_bytes += offload_bytes; \
_Pragma (HYPRE_XSTR(omp target exit data map(delete:hypre__offload_hptr[hypre__offload_offset:hypre__offload_size]))) \
} else if (type1[1] == 'x' && type2[0] == 'f') {\
/* exit from */ \
hypre__target_free_count ++; \
hypre__target_free_bytes += offload_bytes; \
hypre__target_dtoh_count ++; \
hypre__target_dtoh_bytes += offload_bytes; \
_Pragma (HYPRE_XSTR(omp target exit data map(from:hypre__offload_hptr[hypre__offload_offset:hypre__offload_size]))) \
} else if (type1[1] == 'p' && type2[0] == 't') { \
/* update to */ \
hypre__target_htod_count ++; \
hypre__target_htod_bytes += offload_bytes; \
_Pragma (HYPRE_XSTR(omp target update to(hypre__offload_hptr[hypre__offload_offset:hypre__offload_size]))) \
} else if (type1[1] == 'p' && type2[0] == 'f') {\
/* update from */ \
hypre__target_dtoh_count ++; \
hypre__target_dtoh_bytes += offload_bytes; \
_Pragma (HYPRE_XSTR(omp target update from(hypre__offload_hptr[hypre__offload_offset:hypre__offload_size]))) \
} else {\
printf("error: unrecognized offloading type combination!\n"); exit(-1); \
} \
} \
} \
}
HYPRE_Int HYPRE_OMPOffload(HYPRE_Int device, void *ptr, size_t num, const char *type1, const char *type2);
HYPRE_Int HYPRE_OMPPtrIsMapped(void *p, HYPRE_Int device_num);
HYPRE_Int HYPRE_OMPOffloadOn();
HYPRE_Int HYPRE_OMPOffloadOff();
HYPRE_Int HYPRE_OMPOffloadStatPrint();
#endif /* HYPRE_USING_DEVICE_OPENMP */
#endif /* HYPRE_OMP_DEVICE_H */
/******************************************************************************
* Copyright 1998-2019 Lawrence Livermore National Security, LLC and other
* HYPRE Project Developers. See the top-level COPYRIGHT file for details.
*
* SPDX-License-Identifier: (Apache-2.0 OR MIT)
******************************************************************************/
#ifndef hypre_THREADING_HEADER
#define hypre_THREADING_HEADER
#ifdef HYPRE_USING_OPENMP
HYPRE_Int hypre_NumThreads( void );
HYPRE_Int hypre_NumActiveThreads( void );
HYPRE_Int hypre_GetThreadNum( void );
void hypre_SetNumThreads(HYPRE_Int nt);
#else
#define hypre_NumThreads() 1
#define hypre_NumActiveThreads() 1
#define hypre_GetThreadNum() 0
#define hypre_SetNumThreads(x)
#endif
void hypre_GetSimpleThreadPartition( HYPRE_Int *begin, HYPRE_Int *end, HYPRE_Int n );
#endif
/******************************************************************************
* Copyright 1998-2019 Lawrence Livermore National Security, LLC and other
* HYPRE Project Developers. See the top-level COPYRIGHT file for details.
*
* SPDX-License-Identifier: (Apache-2.0 OR MIT)
******************************************************************************/
/******************************************************************************
*
* Header file for doing timing
*
*****************************************************************************/
#ifndef HYPRE_TIMING_HEADER
#define HYPRE_TIMING_HEADER
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#ifdef __cplusplus
extern "C" {
#endif
/*--------------------------------------------------------------------------
* Prototypes for low-level timing routines
*--------------------------------------------------------------------------*/
/* timer.c */
HYPRE_Real time_getWallclockSeconds( void );
HYPRE_Real time_getCPUSeconds( void );
HYPRE_Real time_get_wallclock_seconds_( void );
HYPRE_Real time_get_cpu_seconds_( void );
/*--------------------------------------------------------------------------
* With timing off
*--------------------------------------------------------------------------*/
#ifndef HYPRE_TIMING
#define hypre_InitializeTiming(name) 0
#define hypre_FinalizeTiming(index)
#define hypre_IncFLOPCount(inc)
#define hypre_BeginTiming(i)
#define hypre_EndTiming(i)
#define hypre_PrintTiming(heading, comm)
#define hypre_ClearTiming()
/*--------------------------------------------------------------------------
* With timing on
*--------------------------------------------------------------------------*/
#else
/*-------------------------------------------------------
* Global timing structure
*-------------------------------------------------------*/
typedef struct
{
HYPRE_Real *wall_time;
HYPRE_Real *cpu_time;
HYPRE_Real *flops;
char **name;
HYPRE_Int *state; /* boolean flag to allow for recursive timing */
HYPRE_Int *num_regs; /* count of how many times a name is registered */
HYPRE_Int num_names;
HYPRE_Int size;
HYPRE_Real wall_count;
HYPRE_Real CPU_count;
HYPRE_Real FLOP_count;
} hypre_TimingType;
#ifdef HYPRE_TIMING_GLOBALS
hypre_TimingType *hypre_global_timing = NULL;
#else
extern hypre_TimingType *hypre_global_timing;
#endif
/*-------------------------------------------------------
* Accessor functions
*-------------------------------------------------------*/
#define hypre_TimingWallTime(i) (hypre_global_timing -> wall_time[(i)])
#define hypre_TimingCPUTime(i) (hypre_global_timing -> cpu_time[(i)])
#define hypre_TimingFLOPS(i) (hypre_global_timing -> flops[(i)])
#define hypre_TimingName(i) (hypre_global_timing -> name[(i)])
#define hypre_TimingState(i) (hypre_global_timing -> state[(i)])
#define hypre_TimingNumRegs(i) (hypre_global_timing -> num_regs[(i)])
#define hypre_TimingWallCount (hypre_global_timing -> wall_count)
#define hypre_TimingCPUCount (hypre_global_timing -> CPU_count)
#define hypre_TimingFLOPCount (hypre_global_timing -> FLOP_count)
/*-------------------------------------------------------
* Prototypes
*-------------------------------------------------------*/
/* timing.c */
HYPRE_Int hypre_InitializeTiming( const char *name );
HYPRE_Int hypre_FinalizeTiming( HYPRE_Int time_index );
HYPRE_Int hypre_IncFLOPCount( HYPRE_BigInt inc );
HYPRE_Int hypre_BeginTiming( HYPRE_Int time_index );
HYPRE_Int hypre_EndTiming( HYPRE_Int time_index );
HYPRE_Int hypre_ClearTiming( void );
HYPRE_Int hypre_PrintTiming( const char *heading , MPI_Comm comm );
#endif
#ifdef __cplusplus
}
#endif
#endif
/******************************************************************************
* Copyright 1998-2019 Lawrence Livermore National Security, LLC and other
* HYPRE Project Developers. See the top-level COPYRIGHT file for details.
*
* SPDX-License-Identifier: (Apache-2.0 OR MIT)
******************************************************************************/
/******************************************************************************
*
* Header file link lists
*
*****************************************************************************/
#ifndef HYPRE_LINKLIST_HEADER
#define HYPRE_LINKLIST_HEADER
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#ifdef __cplusplus
extern "C" {
#endif
struct double_linked_list
{
HYPRE_Int data;
struct double_linked_list *next_elt;
struct double_linked_list *prev_elt;
HYPRE_Int head;
HYPRE_Int tail;
};
typedef struct double_linked_list hypre_ListElement;
typedef hypre_ListElement *hypre_LinkList;
#ifdef __cplusplus
}
#endif
#endif
/******************************************************************************
* Copyright 1998-2019 Lawrence Livermore National Security, LLC and other
* HYPRE Project Developers. See the top-level COPYRIGHT file for details.
*
* SPDX-License-Identifier: (Apache-2.0 OR MIT)
******************************************************************************/
#ifndef hypre_EXCHANGE_DATA_HEADER
#define hypre_EXCHANGE_DATA_HEADER
#define hypre_BinaryTreeParentId(tree) (tree->parent_id)
#define hypre_BinaryTreeNumChild(tree) (tree->num_child)
#define hypre_BinaryTreeChildIds(tree) (tree->child_id)
#define hypre_BinaryTreeChildId(tree, i) (tree->child_id[i])
typedef struct
{
HYPRE_Int parent_id;
HYPRE_Int num_child;
HYPRE_Int *child_id;
} hypre_BinaryTree;
/* In the fill_response() function the user needs to set the recv__buf
and the response_message_size. Memory of size send_response_storage has been
alllocated for the send_buf (in exchange_data) - if more is needed, then
realloc and adjust
the send_response_storage. The realloc amount should be storage+overhead.
If the response is an empty "confirmation" message, then set
response_message_size =0 (and do not modify the send_buf) */
typedef struct
{
HYPRE_Int (*fill_response)(void* recv_buf, HYPRE_Int contact_size,
HYPRE_Int contact_proc, void* response_obj,
MPI_Comm comm, void** response_buf,
HYPRE_Int* response_message_size);
HYPRE_Int send_response_overhead; /*set by exchange data */
HYPRE_Int send_response_storage; /*storage allocated for send_response_buf*/
void *data1; /*data fields user may want to access in fill_response */
void *data2;
} hypre_DataExchangeResponse;
HYPRE_Int hypre_CreateBinaryTree(HYPRE_Int, HYPRE_Int, hypre_BinaryTree*);
HYPRE_Int hypre_DestroyBinaryTree(hypre_BinaryTree*);
HYPRE_Int hypre_DataExchangeList(HYPRE_Int num_contacts, HYPRE_Int *contact_proc_list, void *contact_send_buf, HYPRE_Int *contact_send_buf_starts, HYPRE_Int contact_obj_size, HYPRE_Int response_obj_size, hypre_DataExchangeResponse *response_obj, HYPRE_Int max_response_size, HYPRE_Int rnum, MPI_Comm comm, void **p_response_recv_buf, HYPRE_Int **p_response_recv_buf_starts);
#endif /* end of header */
/******************************************************************************
* Copyright 1998-2019 Lawrence Livermore National Security, LLC and other
* HYPRE Project Developers. See the top-level COPYRIGHT file for details.
*
* SPDX-License-Identifier: (Apache-2.0 OR MIT)
******************************************************************************/
/******************************************************************************
*
* Header file for Caliper instrumentation macros
*
*****************************************************************************/
#ifndef CALIPER_INSTRUMENTATION_HEADER
#define CALIPER_INSTRUMENTATION_HEADER
#include "HYPRE_config.h"
#ifdef HYPRE_USING_CALIPER
#ifdef __cplusplus
extern "C++" {
#endif
#include <caliper/cali.h>
#ifdef __cplusplus
}
#endif
static char hypre__levelname[16];
#define HYPRE_ANNOTATE_FUNC_BEGIN CALI_MARK_FUNCTION_BEGIN
#define HYPRE_ANNOTATE_FUNC_END CALI_MARK_FUNCTION_END
#define HYPRE_ANNOTATE_LOOP_BEGIN(id, str) CALI_MARK_LOOP_BEGIN(id, str)
#define HYPRE_ANNOTATE_LOOP_END(id) CALI_MARK_LOOP_END(id)
#define HYPRE_ANNOTATE_ITER_BEGIN(id, it) CALI_MARK_ITERATION_BEGIN(id, it)
#define HYPRE_ANNOTATE_ITER_END(id) CALI_MARK_ITERATION_END(id)
#define HYPRE_ANNOTATE_MGLEVEL_BEGIN(lvl)\
{\
hypre_sprintf(hypre__levelname, "MG level %d", lvl);\
CALI_MARK_BEGIN(hypre__levelname);\
}
#define HYPRE_ANNOTATE_MGLEVEL_END(lvl)\
{\
hypre_sprintf(hypre__levelname, "MG level %d", lvl);\
CALI_MARK_END(hypre__levelname);\
}
#else
#define HYPRE_ANNOTATE_FUNC_BEGIN
#define HYPRE_ANNOTATE_FUNC_END
#define HYPRE_ANNOTATE_LOOP_BEGIN(id, str)
#define HYPRE_ANNOTATE_LOOP_END(id)
#define HYPRE_ANNOTATE_ITER_BEGIN(id, it)
#define HYPRE_ANNOTATE_ITER_END(id)
#define HYPRE_ANNOTATE_MGLEVEL_BEGIN(lvl)
#define HYPRE_ANNOTATE_MGLEVEL_END(lvl)
#endif
#endif /* CALIPER_INSTRUMENTATION_HEADER */
/******************************************************************************
* Copyright 1998-2019 Lawrence Livermore National Security, LLC and other
* HYPRE Project Developers. See the top-level COPYRIGHT file for details.
*
* SPDX-License-Identifier: (Apache-2.0 OR MIT)
******************************************************************************/
/******************************************************************************
*
* General structures and values
*
*****************************************************************************/
#ifndef HYPRE_HANDLE_H
#define HYPRE_HANDLE_H
struct hypre_CudaData;
typedef struct hypre_CudaData hypre_CudaData;
typedef struct
{
HYPRE_Int hypre_error;
HYPRE_MemoryLocation memory_location;
HYPRE_ExecutionPolicy default_exec_policy;
HYPRE_ExecutionPolicy struct_exec_policy;
#if defined(HYPRE_USING_GPU)
hypre_CudaData *cuda_data;
/* device G-S options */
HYPRE_Int device_gs_method;
#endif
#if defined(HYPRE_USING_UMPIRE)
char umpire_device_pool_name[HYPRE_UMPIRE_POOL_NAME_MAX_LEN];
char umpire_um_pool_name[HYPRE_UMPIRE_POOL_NAME_MAX_LEN];
char umpire_host_pool_name[HYPRE_UMPIRE_POOL_NAME_MAX_LEN];
char umpire_pinned_pool_name[HYPRE_UMPIRE_POOL_NAME_MAX_LEN];
size_t umpire_device_pool_size;
size_t umpire_um_pool_size;
size_t umpire_host_pool_size;
size_t umpire_pinned_pool_size;
size_t umpire_block_size;
HYPRE_Int own_umpire_device_pool;
HYPRE_Int own_umpire_um_pool;
HYPRE_Int own_umpire_host_pool;
HYPRE_Int own_umpire_pinned_pool;
umpire_resourcemanager umpire_rm;
#endif
} hypre_Handle;
/* accessor macros to hypre_Handle */
#define hypre_HandleMemoryLocation(hypre_handle) ((hypre_handle) -> memory_location)
#define hypre_HandleDefaultExecPolicy(hypre_handle) ((hypre_handle) -> default_exec_policy)
#define hypre_HandleStructExecPolicy(hypre_handle) ((hypre_handle) -> struct_exec_policy)
#define hypre_HandleCudaData(hypre_handle) ((hypre_handle) -> cuda_data)
#define hypre_HandleDeviceGSMethod(hypre_handle) ((hypre_handle) -> device_gs_method)
#define hypre_HandleCurandGenerator(hypre_handle) hypre_CudaDataCurandGenerator(hypre_HandleCudaData(hypre_handle))
#define hypre_HandleCublasHandle(hypre_handle) hypre_CudaDataCublasHandle(hypre_HandleCudaData(hypre_handle))
#define hypre_HandleCusparseHandle(hypre_handle) hypre_CudaDataCusparseHandle(hypre_HandleCudaData(hypre_handle))
#define hypre_HandleCudaComputeStream(hypre_handle) hypre_CudaDataCudaComputeStream(hypre_HandleCudaData(hypre_handle))
#define hypre_HandleCubBinGrowth(hypre_handle) hypre_CudaDataCubBinGrowth(hypre_HandleCudaData(hypre_handle))
#define hypre_HandleCubMinBin(hypre_handle) hypre_CudaDataCubMinBin(hypre_HandleCudaData(hypre_handle))
#define hypre_HandleCubMaxBin(hypre_handle) hypre_CudaDataCubMaxBin(hypre_HandleCudaData(hypre_handle))
#define hypre_HandleCubMaxCachedBytes(hypre_handle) hypre_CudaDataCubMaxCachedBytes(hypre_HandleCudaData(hypre_handle))
#define hypre_HandleCubDevAllocator(hypre_handle) hypre_CudaDataCubDevAllocator(hypre_HandleCudaData(hypre_handle))
#define hypre_HandleCubUvmAllocator(hypre_handle) hypre_CudaDataCubUvmAllocator(hypre_HandleCudaData(hypre_handle))
#define hypre_HandleCudaDevice(hypre_handle) hypre_CudaDataCudaDevice(hypre_HandleCudaData(hypre_handle))
#define hypre_HandleCudaComputeStreamNum(hypre_handle) hypre_CudaDataCudaComputeStreamNum(hypre_HandleCudaData(hypre_handle))
#define hypre_HandleCudaReduceBuffer(hypre_handle) hypre_CudaDataCudaReduceBuffer(hypre_HandleCudaData(hypre_handle))
#define hypre_HandleStructCommRecvBuffer(hypre_handle) hypre_CudaDataStructCommRecvBuffer(hypre_HandleCudaData(hypre_handle))
#define hypre_HandleStructCommSendBuffer(hypre_handle) hypre_CudaDataStructCommSendBuffer(hypre_HandleCudaData(hypre_handle))
#define hypre_HandleStructCommRecvBufferSize(hypre_handle) hypre_CudaDataStructCommRecvBufferSize(hypre_HandleCudaData(hypre_handle))
#define hypre_HandleStructCommSendBufferSize(hypre_handle) hypre_CudaDataStructCommSendBufferSize(hypre_HandleCudaData(hypre_handle))
#define hypre_HandleSpgemmUseCusparse(hypre_handle) hypre_CudaDataSpgemmUseCusparse(hypre_HandleCudaData(hypre_handle))
#define hypre_HandleSpgemmNumPasses(hypre_handle) hypre_CudaDataSpgemmNumPasses(hypre_HandleCudaData(hypre_handle))
#define hypre_HandleSpgemmRownnzEstimateMethod(hypre_handle) hypre_CudaDataSpgemmRownnzEstimateMethod(hypre_HandleCudaData(hypre_handle))
#define hypre_HandleSpgemmRownnzEstimateNsamples(hypre_handle) hypre_CudaDataSpgemmRownnzEstimateNsamples(hypre_HandleCudaData(hypre_handle))
#define hypre_HandleSpgemmRownnzEstimateMultFactor(hypre_handle) hypre_CudaDataSpgemmRownnzEstimateMultFactor(hypre_HandleCudaData(hypre_handle))
#define hypre_HandleSpgemmHashType(hypre_handle) hypre_CudaDataSpgemmHashType(hypre_HandleCudaData(hypre_handle))
#define hypre_HandleUmpireDeviceAllocator(hypre_handle) hypre_CudaDataUmpireDeviceAllocator(hypre_HandleCudaData(hypre_handle))
#define hypre_HandleUseGpuRand(hypre_handle) hypre_CudaDataUseGpuRand(hypre_HandleCudaData(hypre_handle))
#define hypre_HandleUmpireResourceMan(hypre_handle) ((hypre_handle) -> umpire_rm)
#define hypre_HandleUmpireDevicePoolSize(hypre_handle) ((hypre_handle) -> umpire_device_pool_size)
#define hypre_HandleUmpireUMPoolSize(hypre_handle) ((hypre_handle) -> umpire_um_pool_size)
#define hypre_HandleUmpireHostPoolSize(hypre_handle) ((hypre_handle) -> umpire_host_pool_size)
#define hypre_HandleUmpirePinnedPoolSize(hypre_handle) ((hypre_handle) -> umpire_pinned_pool_size)
#define hypre_HandleUmpireBlockSize(hypre_handle) ((hypre_handle) -> umpire_block_size)
#define hypre_HandleUmpireDevicePoolName(hypre_handle) ((hypre_handle) -> umpire_device_pool_name)
#define hypre_HandleUmpireUMPoolName(hypre_handle) ((hypre_handle) -> umpire_um_pool_name)
#define hypre_HandleUmpireHostPoolName(hypre_handle) ((hypre_handle) -> umpire_host_pool_name)
#define hypre_HandleUmpirePinnedPoolName(hypre_handle) ((hypre_handle) -> umpire_pinned_pool_name)
#define hypre_HandleOwnUmpireDevicePool(hypre_handle) ((hypre_handle) -> own_umpire_device_pool)
#define hypre_HandleOwnUmpireUMPool(hypre_handle) ((hypre_handle) -> own_umpire_um_pool)
#define hypre_HandleOwnUmpireHostPool(hypre_handle) ((hypre_handle) -> own_umpire_host_pool)
#define hypre_HandleOwnUmpirePinnedPool(hypre_handle) ((hypre_handle) -> own_umpire_pinned_pool)
#endif
/******************************************************************************
* Copyright 1998-2019 Lawrence Livermore National Security, LLC and other
* HYPRE Project Developers. See the top-level COPYRIGHT file for details.
*
* SPDX-License-Identifier: (Apache-2.0 OR MIT)
******************************************************************************/
#ifndef HYPRE_GSELIM_H
#define HYPRE_GSELIM_H
#define hypre_gselim(A,x,n,error) \
{ \
HYPRE_Int j,k,m; \
HYPRE_Real factor; \
HYPRE_Real divA; \
error = 0; \
if (n == 1) /* A is 1x1 */ \
{ \
if (A[0] != 0.0) \
{ \
x[0] = x[0]/A[0]; \
} \
else \
{ \
error++; \
} \
} \
else/* A is nxn. Forward elimination */ \
{ \
for (k = 0; k < n-1; k++) \
{ \
if (A[k*n+k] != 0.0) \
{ \
divA = 1.0/A[k*n+k]; \
for (j = k+1; j < n; j++) \
{ \
if (A[j*n+k] != 0.0) \
{ \
factor = A[j*n+k]*divA; \
for (m = k+1; m < n; m++) \
{ \
A[j*n+m] -= factor * A[k*n+m]; \
} \
x[j] -= factor * x[k]; \
} \
} \
} \
} \
/* Back Substitution */ \
for (k = n-1; k > 0; --k) \
{ \
if (A[k*n+k] != 0.0) \
{ \
x[k] /= A[k*n+k]; \
for (j = 0; j < k; j++) \
{ \
if (A[j*n+k] != 0.0) \
{ \
x[j] -= x[k] * A[j*n+k]; \
} \
} \
} \
} \
if (A[0] != 0.0) x[0] /= A[0]; \
} \
}
#endif /* #ifndef HYPRE_GSELIM_H */
/******************************************************************************
* Copyright 1998-2019 Lawrence Livermore National Security, LLC and other
* HYPRE Project Developers. See the top-level COPYRIGHT file for details.
*
* SPDX-License-Identifier: (Apache-2.0 OR MIT)
******************************************************************************/
/* amg_linklist.c */
void hypre_dispose_elt ( hypre_LinkList element_ptr );
void hypre_remove_point ( hypre_LinkList *LoL_head_ptr , hypre_LinkList *LoL_tail_ptr , HYPRE_Int measure , HYPRE_Int index , HYPRE_Int *lists , HYPRE_Int *where );
hypre_LinkList hypre_create_elt ( HYPRE_Int Item );
void hypre_enter_on_lists ( hypre_LinkList *LoL_head_ptr , hypre_LinkList *LoL_tail_ptr , HYPRE_Int measure , HYPRE_Int index , HYPRE_Int *lists , HYPRE_Int *where );
/* binsearch.c */
HYPRE_Int hypre_BinarySearch ( HYPRE_Int *list , HYPRE_Int value , HYPRE_Int list_length );
HYPRE_Int hypre_BigBinarySearch ( HYPRE_BigInt *list , HYPRE_BigInt value , HYPRE_Int list_length );
HYPRE_Int hypre_BinarySearch2 ( HYPRE_Int *list , HYPRE_Int value , HYPRE_Int low , HYPRE_Int high , HYPRE_Int *spot );
HYPRE_Int *hypre_LowerBound( HYPRE_Int *first, HYPRE_Int *last, HYPRE_Int value );
HYPRE_BigInt *hypre_BigLowerBound( HYPRE_BigInt *first, HYPRE_BigInt *last, HYPRE_BigInt value );
/* complex.c */
#ifdef HYPRE_COMPLEX
HYPRE_Complex hypre_conj( HYPRE_Complex value );
HYPRE_Real hypre_cabs( HYPRE_Complex value );
HYPRE_Real hypre_creal( HYPRE_Complex value );
HYPRE_Real hypre_cimag( HYPRE_Complex value );
#else
#define hypre_conj(value) value
#define hypre_cabs(value) fabs(value)
#define hypre_creal(value) value
#define hypre_cimag(value) 0.0
#endif
/* general.c */
#ifdef HYPRE_USING_MEMORY_TRACKER
hypre_MemoryTracker* hypre_memory_tracker();
#endif
hypre_Handle* hypre_handle();
hypre_Handle* hypre_HandleCreate();
HYPRE_Int hypre_HandleDestroy(hypre_Handle *hypre_handle_);
HYPRE_Int hypre_SetDevice(hypre_int device_id, hypre_Handle *hypre_handle_);
HYPRE_Int hypre_GetDevice(hypre_int *device_id);
HYPRE_Int hypre_GetDeviceCount(hypre_int *device_count);
HYPRE_Int hypre_GetDeviceLastError();
HYPRE_Int hypre_UmpireInit(hypre_Handle *hypre_handle_);
HYPRE_Int hypre_UmpireFinalize(hypre_Handle *hypre_handle_);
/* qsort.c */
void hypre_swap ( HYPRE_Int *v , HYPRE_Int i , HYPRE_Int j );
void hypre_swap_c ( HYPRE_Complex *v , HYPRE_Int i , HYPRE_Int j );
void hypre_swap2 ( HYPRE_Int *v , HYPRE_Real *w , HYPRE_Int i , HYPRE_Int j );
void hypre_BigSwap2 ( HYPRE_BigInt *v , HYPRE_Real *w , HYPRE_Int i , HYPRE_Int j );
void hypre_swap2i ( HYPRE_Int *v , HYPRE_Int *w , HYPRE_Int i , HYPRE_Int j );
void hypre_BigSwap2i ( HYPRE_BigInt *v , HYPRE_Int *w , HYPRE_Int i , HYPRE_Int j );
void hypre_swap3i ( HYPRE_Int *v , HYPRE_Int *w , HYPRE_Int *z , HYPRE_Int i , HYPRE_Int j );
void hypre_swap3_d ( HYPRE_Real *v , HYPRE_Int *w , HYPRE_Int *z , HYPRE_Int i , HYPRE_Int j );
void hypre_swap3_d_perm(HYPRE_Int *v, HYPRE_Real *w, HYPRE_Int *z, HYPRE_Int i, HYPRE_Int j );
void hypre_BigSwap4_d ( HYPRE_Real *v , HYPRE_BigInt *w , HYPRE_Int *z , HYPRE_Int *y , HYPRE_Int i , HYPRE_Int j );
void hypre_swap_d ( HYPRE_Real *v , HYPRE_Int i , HYPRE_Int j );
void hypre_qsort0 ( HYPRE_Int *v , HYPRE_Int left , HYPRE_Int right );
void hypre_qsort1 ( HYPRE_Int *v , HYPRE_Real *w , HYPRE_Int left , HYPRE_Int right );
void hypre_BigQsort1 ( HYPRE_BigInt *v , HYPRE_Real *w , HYPRE_Int left , HYPRE_Int right );
void hypre_qsort2i ( HYPRE_Int *v , HYPRE_Int *w , HYPRE_Int left , HYPRE_Int right );
void hypre_BigQsort2i( HYPRE_BigInt *v, HYPRE_Int *w, HYPRE_Int left, HYPRE_Int right );
void hypre_qsort2 ( HYPRE_Int *v , HYPRE_Real *w , HYPRE_Int left , HYPRE_Int right );
void hypre_qsort2_abs ( HYPRE_Int *v , HYPRE_Real *w , HYPRE_Int left , HYPRE_Int right );
void hypre_qsort3i ( HYPRE_Int *v , HYPRE_Int *w , HYPRE_Int *z , HYPRE_Int left , HYPRE_Int right );
void hypre_qsort3ir ( HYPRE_Int *v , HYPRE_Real *w , HYPRE_Int *z , HYPRE_Int left , HYPRE_Int right );
void hypre_qsort3( HYPRE_Real *v, HYPRE_Int *w, HYPRE_Int *z, HYPRE_Int left, HYPRE_Int right );
void hypre_qsort3_abs ( HYPRE_Real *v , HYPRE_Int *w , HYPRE_Int *z , HYPRE_Int left , HYPRE_Int right );
void hypre_BigQsort4_abs ( HYPRE_Real *v , HYPRE_BigInt *w , HYPRE_Int *z , HYPRE_Int *y , HYPRE_Int left , HYPRE_Int right );
void hypre_qsort_abs ( HYPRE_Real *w , HYPRE_Int left , HYPRE_Int right );
void hypre_BigSwapbi(HYPRE_BigInt *v, HYPRE_Int *w, HYPRE_Int i, HYPRE_Int j );
void hypre_BigQsortbi( HYPRE_BigInt *v, HYPRE_Int *w, HYPRE_Int left, HYPRE_Int right );
void hypre_BigSwapLoc(HYPRE_BigInt *v, HYPRE_Int *w, HYPRE_Int i, HYPRE_Int j );
void hypre_BigQsortbLoc( HYPRE_BigInt *v, HYPRE_Int *w, HYPRE_Int left, HYPRE_Int right );
void hypre_BigSwapb2i(HYPRE_BigInt *v, HYPRE_Int *w, HYPRE_Int *z, HYPRE_Int i, HYPRE_Int j );
void hypre_BigQsortb2i( HYPRE_BigInt *v, HYPRE_Int *w, HYPRE_Int *z, HYPRE_Int left, HYPRE_Int right );
void hypre_BigSwap( HYPRE_BigInt *v, HYPRE_Int i, HYPRE_Int j );
void hypre_BigQsort0( HYPRE_BigInt *v, HYPRE_Int left, HYPRE_Int right );
void hypre_topo_sort(const HYPRE_Int *row_ptr, const HYPRE_Int *col_inds, const HYPRE_Complex *data, HYPRE_Int *ordering, HYPRE_Int n);
void hypre_dense_topo_sort(const HYPRE_Complex *L, HYPRE_Int *ordering, HYPRE_Int n, HYPRE_Int is_col_major);
/* qsplit.c */
HYPRE_Int hypre_DoubleQuickSplit ( HYPRE_Real *values , HYPRE_Int *indices , HYPRE_Int list_length , HYPRE_Int NumberKept );
/* random.c */
/* HYPRE_CUDA_GLOBAL */ void hypre_SeedRand ( HYPRE_Int seed );
/* HYPRE_CUDA_GLOBAL */ HYPRE_Int hypre_RandI ( void );
/* HYPRE_CUDA_GLOBAL */ HYPRE_Real hypre_Rand ( void );
/* prefix_sum.c */
/**
* Assumed to be called within an omp region.
* Let x_i be the input of ith thread.
* The output of ith thread y_i = x_0 + x_1 + ... + x_{i-1}
* Additionally, sum = x_0 + x_1 + ... + x_{nthreads - 1}
* Note that always y_0 = 0
*
* @param workspace at least with length (nthreads+1)
* workspace[tid] will contain result for tid
* workspace[nthreads] will contain sum
*/
void hypre_prefix_sum(HYPRE_Int *in_out, HYPRE_Int *sum, HYPRE_Int *workspace);
/**
* This version does prefix sum in pair.
* Useful when we prefix sum of diag and offd in tandem.
*
* @param worksapce at least with length 2*(nthreads+1)
* workspace[2*tid] and workspace[2*tid+1] will contain results for tid
* workspace[3*nthreads] and workspace[3*nthreads + 1] will contain sums
*/
void hypre_prefix_sum_pair(HYPRE_Int *in_out1, HYPRE_Int *sum1, HYPRE_Int *in_out2, HYPRE_Int *sum2, HYPRE_Int *workspace);
/**
* @param workspace at least with length 3*(nthreads+1)
* workspace[3*tid:3*tid+3) will contain results for tid
*/
void hypre_prefix_sum_triple(HYPRE_Int *in_out1, HYPRE_Int *sum1, HYPRE_Int *in_out2, HYPRE_Int *sum2, HYPRE_Int *in_out3, HYPRE_Int *sum3, HYPRE_Int *workspace);
/**
* n prefix-sums together.
* workspace[n*tid:n*(tid+1)) will contain results for tid
* workspace[nthreads*tid:nthreads*(tid+1)) will contain sums
*
* @param workspace at least with length n*(nthreads+1)
*/
void hypre_prefix_sum_multiple(HYPRE_Int *in_out, HYPRE_Int *sum, HYPRE_Int n, HYPRE_Int *workspace);
/* hopscotch_hash.c */
#ifdef HYPRE_USING_OPENMP
/* Check if atomic operations are available to use concurrent hopscotch hash table */
#if defined(__GNUC__) && defined(__GNUC_MINOR__) && defined(__GNUC_PATCHLEVEL__) && (__GNUC__ * 10000 + __GNUC_MINOR__ * 100 + __GNUC_PATCHLEVEL__) > 40100
#define HYPRE_USING_ATOMIC
//#elif defined _MSC_VER // JSP: haven't tested, so comment out for now
//#define HYPRE_USING_ATOMIC
//#elif defined(__STDC_VERSION__) && __STDC_VERSION__ >= 201112L && !defined(__STDC_NO_ATOMICS__)
// JSP: not many compilers have implemented this, so comment out for now
//#define HYPRE_USING_ATOMIC
//#include <stdatomic.h>
#endif
#endif // HYPRE_USING_OPENMP
#ifdef HYPRE_HOPSCOTCH
#ifdef HYPRE_USING_ATOMIC
// concurrent hopscotch hashing is possible only with atomic supports
#define HYPRE_CONCURRENT_HOPSCOTCH
#endif
#endif
#ifdef HYPRE_CONCURRENT_HOPSCOTCH
typedef struct
{
HYPRE_Int volatile timestamp;
omp_lock_t lock;
} hypre_HopscotchSegment;
#endif
/**
* The current typical use case of unordered set is putting input sequence
* with lots of duplication (putting all colidx received from other ranks),
* followed by one sweep of enumeration.
* Since the capacity is set to the number of inputs, which is much larger
* than the number of unique elements, we optimize for initialization and
* enumeration whose time is proportional to the capacity.
* For initialization and enumeration, structure of array (SoA) is better
* for vectorization, cache line utilization, and so on.
*/
typedef struct
{
HYPRE_Int volatile segmentMask;
HYPRE_Int volatile bucketMask;
#ifdef HYPRE_CONCURRENT_HOPSCOTCH
hypre_HopscotchSegment* volatile segments;
#endif
HYPRE_Int *volatile key;
hypre_uint *volatile hopInfo;
HYPRE_Int *volatile hash;
} hypre_UnorderedIntSet;
typedef struct
{
HYPRE_Int volatile segmentMask;
HYPRE_Int volatile bucketMask;
#ifdef HYPRE_CONCURRENT_HOPSCOTCH
hypre_HopscotchSegment* volatile segments;
#endif
HYPRE_BigInt *volatile key;
hypre_uint *volatile hopInfo;
HYPRE_BigInt *volatile hash;
} hypre_UnorderedBigIntSet;
typedef struct
{
hypre_uint volatile hopInfo;
HYPRE_Int volatile hash;
HYPRE_Int volatile key;
HYPRE_Int volatile data;
} hypre_HopscotchBucket;
typedef struct
{
hypre_uint volatile hopInfo;
HYPRE_BigInt volatile hash;
HYPRE_BigInt volatile key;
HYPRE_Int volatile data;
} hypre_BigHopscotchBucket;
/**
* The current typical use case of unoredered map is putting input sequence
* with no duplication (inverse map of a bijective mapping) followed by
* lots of lookups.
* For lookup, array of structure (AoS) gives better cache line utilization.
*/
typedef struct
{
HYPRE_Int volatile segmentMask;
HYPRE_Int volatile bucketMask;
#ifdef HYPRE_CONCURRENT_HOPSCOTCH
hypre_HopscotchSegment* volatile segments;
#endif
hypre_HopscotchBucket* volatile table;
} hypre_UnorderedIntMap;
typedef struct
{
HYPRE_Int volatile segmentMask;
HYPRE_Int volatile bucketMask;
#ifdef HYPRE_CONCURRENT_HOPSCOTCH
hypre_HopscotchSegment* volatile segments;
#endif
hypre_BigHopscotchBucket* volatile table;
} hypre_UnorderedBigIntMap;
/* merge_sort.c */
/**
* Why merge sort?
* 1) Merge sort can take advantage of eliminating duplicates.
* 2) Merge sort is more efficiently parallelizable than qsort
*/
HYPRE_Int hypre_MergeOrderedArrays( HYPRE_Int size1 , HYPRE_Int *array1 , HYPRE_Int size2 , HYPRE_Int *array2 , HYPRE_Int *size3_ptr , HYPRE_Int **array3_ptr);
void hypre_union2(HYPRE_Int n1, HYPRE_BigInt *arr1, HYPRE_Int n2, HYPRE_BigInt *arr2, HYPRE_Int *n3, HYPRE_BigInt *arr3, HYPRE_Int *map1, HYPRE_Int *map2);
void hypre_merge_sort(HYPRE_Int *in, HYPRE_Int *temp, HYPRE_Int len, HYPRE_Int **sorted);
void hypre_big_merge_sort(HYPRE_BigInt *in, HYPRE_BigInt *temp, HYPRE_Int len, HYPRE_BigInt **sorted);
void hypre_sort_and_create_inverse_map(HYPRE_Int *in, HYPRE_Int len, HYPRE_Int **out, hypre_UnorderedIntMap *inverse_map);
void hypre_big_sort_and_create_inverse_map(HYPRE_BigInt *in, HYPRE_Int len, HYPRE_BigInt **out, hypre_UnorderedBigIntMap *inverse_map);
#if defined(HYPRE_USING_GPU)
HYPRE_Int hypre_SyncCudaComputeStream(hypre_Handle *hypre_handle);
HYPRE_Int hypre_SyncCudaDevice(hypre_Handle *hypre_handle);
HYPRE_Int hypreDevice_DiagScaleVector(HYPRE_Int n, HYPRE_Int *A_i, HYPRE_Complex *A_data, HYPRE_Complex *x, HYPRE_Complex beta, HYPRE_Complex *y);
HYPRE_Int hypreDevice_DiagScaleVector2(HYPRE_Int n, HYPRE_Int *A_i, HYPRE_Complex *A_data, HYPRE_Complex *x, HYPRE_Complex beta, HYPRE_Complex *y, HYPRE_Complex *z);
HYPRE_Int hypreDevice_IVAXPY(HYPRE_Int n, HYPRE_Complex *a, HYPRE_Complex *x, HYPRE_Complex *y);
HYPRE_Int hypreDevice_MaskedIVAXPY(HYPRE_Int n, HYPRE_Complex *a, HYPRE_Complex *x, HYPRE_Complex *y, HYPRE_Int *mask);
HYPRE_Int hypreDevice_BigIntFilln(HYPRE_BigInt *d_x, size_t n, HYPRE_BigInt v);
HYPRE_Int hypreDevice_Filln(HYPRE_Complex *d_x, size_t n, HYPRE_Complex v);
#endif
HYPRE_Int hypre_CurandUniform( HYPRE_Int n, HYPRE_Real *urand, HYPRE_Int set_seed, hypre_ulonglongint seed, HYPRE_Int set_offset, hypre_ulonglongint offset);
HYPRE_Int hypre_CurandUniformSingle( HYPRE_Int n, float *urand, HYPRE_Int set_seed, hypre_ulonglongint seed, HYPRE_Int set_offset, hypre_ulonglongint offset);
HYPRE_Int hypre_bind_device(HYPRE_Int myid, HYPRE_Int nproc, MPI_Comm comm);
/* nvtx.c */
void hypre_GpuProfilingPushRangeColor(const char *name, HYPRE_Int cid);
void hypre_GpuProfilingPushRange(const char *name);
void hypre_GpuProfilingPopRange();
/* utilities.c */
HYPRE_Int hypre_multmod(HYPRE_Int a, HYPRE_Int b, HYPRE_Int mod);
void hypre_partition1D(HYPRE_Int n, HYPRE_Int p, HYPRE_Int j, HYPRE_Int *s, HYPRE_Int *e);
char *hypre_strcpy(char *destination, const char *source);
HYPRE_Int hypre_SetSyncCudaCompute(HYPRE_Int action);
HYPRE_Int hypre_RestoreSyncCudaCompute();
HYPRE_Int hypre_GetSyncCudaCompute(HYPRE_Int *cuda_compute_stream_sync_ptr);
HYPRE_Int hypre_SyncCudaComputeStream(hypre_Handle *hypre_handle);
/* handle.c */
HYPRE_Int hypre_SetSpGemmUseCusparse( HYPRE_Int use_cusparse );
HYPRE_Int hypre_SetUseGpuRand( HYPRE_Int use_gpurand );
HYPRE_Int hypre_SetGaussSeidelMethod( HYPRE_Int gs_method );
/******************************************************************************
* Copyright 1998-2019 Lawrence Livermore National Security, LLC and other
* HYPRE Project Developers. See the top-level COPYRIGHT file for details.
*
* SPDX-License-Identifier: (Apache-2.0 OR MIT)
******************************************************************************/
/**
* Hopscotch hash is modified from the code downloaded from
* https://sites.google.com/site/cconcurrencypackage/hopscotch-hashing
* with the following terms of usage
*/
////////////////////////////////////////////////////////////////////////////////
//TERMS OF USAGE
//------------------------------------------------------------------------------
//
// Permission to use, copy, modify and distribute this software and
// its documentation for any purpose is hereby granted without fee,
// provided that due acknowledgments to the authors are provided and
// this permission notice appears in all copies of the software.
// The software is provided "as is". There is no warranty of any kind.
//
//Authors:
// Maurice Herlihy
// Brown University
// and
// Nir Shavit
// Tel-Aviv University
// and
// Moran Tzafrir
// Tel-Aviv University
//
// Date: July 15, 2008.
//
////////////////////////////////////////////////////////////////////////////////
// Programmer : Moran Tzafrir (MoranTza@gmail.com)
// Modified : Jongsoo Park (jongsoo.park@intel.com)
// Oct 1, 2015.
//
////////////////////////////////////////////////////////////////////////////////
#ifndef hypre_HOPSCOTCH_HASH_HEADER
#define hypre_HOPSCOTCH_HASH_HEADER
//#include <strings.h>
#include <string.h>
#include <stdio.h>
#include <limits.h>
#include <math.h>
#ifdef HYPRE_USING_OPENMP
#include <omp.h>
#endif
#include "_hypre_utilities.h"
// Potentially architecture specific features used here:
// __sync_val_compare_and_swap
#ifdef __cplusplus
extern "C" {
#endif
/******************************************************************************
* This next section of code is here instead of in _hypre_utilities.h to get
* around some portability issues with Visual Studio. By putting it here, we
* can explicitly include this '.h' file in a few files in hypre and compile
* them with C++ instead of C (VS does not support C99 'inline').
******************************************************************************/
#ifdef HYPRE_USING_ATOMIC
static inline HYPRE_Int
hypre_compare_and_swap( HYPRE_Int *ptr, HYPRE_Int oldval, HYPRE_Int newval )
{
#if defined(__GNUC__) && defined(__GNUC_MINOR__) && defined(__GNUC_PATCHLEVEL__) && (__GNUC__ * 10000 + __GNUC_MINOR__ * 100 + __GNUC_PATCHLEVEL__) > 40100
return __sync_val_compare_and_swap(ptr, oldval, newval);
//#elif defind _MSC_VER
//return _InterlockedCompareExchange((long *)ptr, newval, oldval);
//#elif defined(__STDC_VERSION__) && __STDC_VERSION__ >= 201112L && !defined(__STDC_NO_ATOMICS__)
// JSP: not many compilers have implemented this, so comment out for now
//_Atomic HYPRE_Int *atomic_ptr = ptr;
//atomic_compare_exchange_strong(atomic_ptr, &oldval, newval);
//return oldval;
#endif
}
static inline HYPRE_Int
hypre_fetch_and_add( HYPRE_Int *ptr, HYPRE_Int value )
{
#if defined(__GNUC__) && defined(__GNUC_MINOR__) && defined(__GNUC_PATCHLEVEL__) && (__GNUC__ * 10000 + __GNUC_MINOR__ * 100 + __GNUC_PATCHLEVEL__) > 40100
return __sync_fetch_and_add(ptr, value);
//#elif defined _MSC_VER
//return _InterlockedExchangeAdd((long *)ptr, value);
//#elif defined(__STDC_VERSION__) && __STDC_VERSION__ >= 201112L && !defined(__STDC_NO_ATOMICS__)
// JSP: not many compilers have implemented this, so comment out for now
//_Atomic HYPRE_Int *atomic_ptr = ptr;
//return atomic_fetch_add(atomic_ptr, value);
#endif
}
#else // !HYPRE_USING_ATOMIC
static inline HYPRE_Int
hypre_compare_and_swap( HYPRE_Int *ptr, HYPRE_Int oldval, HYPRE_Int newval )
{
if (*ptr == oldval)
{
*ptr = newval;
return oldval;
}
else return *ptr;
}
static inline HYPRE_Int
hypre_fetch_and_add( HYPRE_Int *ptr, HYPRE_Int value )
{
HYPRE_Int oldval = *ptr;
*ptr += value;
return oldval;
}
#endif // !HYPRE_USING_ATOMIC
/******************************************************************************/
// Constants ................................................................
#define HYPRE_HOPSCOTCH_HASH_HOP_RANGE (32)
#define HYPRE_HOPSCOTCH_HASH_INSERT_RANGE (4*1024)
#define HYPRE_HOPSCOTCH_HASH_EMPTY (0)
#define HYPRE_HOPSCOTCH_HASH_BUSY (1)
// Small Utilities ..........................................................
static inline HYPRE_Int
first_lsb_bit_indx( hypre_uint x )
{
HYPRE_Int pos;
#if defined(_MSC_VER)
if (x == 0)
{
pos = 0;
}
else
{
for (pos = 1; !(x & 1); ++pos)
{
x >>= 1;
}
}
#else
pos = ffs(x);
#endif
return (pos - 1);
}
/**
* hypre_Hash is adapted from xxHash with the following license.
*/
/*
xxHash - Extremely Fast Hash algorithm
Header File
Copyright (C) 2012-2015, Yann Collet.
BSD 2-Clause License (http://www.opensource.org/licenses/bsd-license.php)
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.
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.
You can contact the author at :
- xxHash source repository : https://github.com/Cyan4973/xxHash
*/
/***************************************
* Constants
***************************************/
#define HYPRE_XXH_PRIME32_1 2654435761U
#define HYPRE_XXH_PRIME32_2 2246822519U
#define HYPRE_XXH_PRIME32_3 3266489917U
#define HYPRE_XXH_PRIME32_4 668265263U
#define HYPRE_XXH_PRIME32_5 374761393U
#define HYPRE_XXH_PRIME64_1 11400714785074694791ULL
#define HYPRE_XXH_PRIME64_2 14029467366897019727ULL
#define HYPRE_XXH_PRIME64_3 1609587929392839161ULL
#define HYPRE_XXH_PRIME64_4 9650029242287828579ULL
#define HYPRE_XXH_PRIME64_5 2870177450012600261ULL
#define HYPRE_XXH_rotl32(x,r) ((x << r) | (x >> (32 - r)))
#define HYPRE_XXH_rotl64(x,r) ((x << r) | (x >> (64 - r)))
#if defined(HYPRE_MIXEDINT) || defined(HYPRE_BIGINT)
static inline HYPRE_BigInt
hypre_BigHash( HYPRE_BigInt input )
{
hypre_ulongint h64 = HYPRE_XXH_PRIME64_5 + sizeof(input);
hypre_ulongint k1 = input;
k1 *= HYPRE_XXH_PRIME64_2;
k1 = HYPRE_XXH_rotl64(k1, 31);
k1 *= HYPRE_XXH_PRIME64_1;
h64 ^= k1;
h64 = HYPRE_XXH_rotl64(h64, 27)*HYPRE_XXH_PRIME64_1 + HYPRE_XXH_PRIME64_4;
h64 ^= h64 >> 33;
h64 *= HYPRE_XXH_PRIME64_2;
h64 ^= h64 >> 29;
h64 *= HYPRE_XXH_PRIME64_3;
h64 ^= h64 >> 32;
#ifndef NDEBUG
if (HYPRE_HOPSCOTCH_HASH_EMPTY == h64) {
hypre_printf("hash(%lld) = %d\n", h64, HYPRE_HOPSCOTCH_HASH_EMPTY);
hypre_assert(HYPRE_HOPSCOTCH_HASH_EMPTY != h64);
}
#endif
return h64;
}
#else
static inline HYPRE_Int
hypre_BigHash(HYPRE_Int input)
{
hypre_uint h32 = HYPRE_XXH_PRIME32_5 + sizeof(input);
// 1665863975 is added to input so that
// only -1073741824 gives HYPRE_HOPSCOTCH_HASH_EMPTY.
// Hence, we're fine as long as key is non-negative.
h32 += (input + 1665863975)*HYPRE_XXH_PRIME32_3;
h32 = HYPRE_XXH_rotl32(h32, 17)*HYPRE_XXH_PRIME32_4;
h32 ^= h32 >> 15;
h32 *= HYPRE_XXH_PRIME32_2;
h32 ^= h32 >> 13;
h32 *= HYPRE_XXH_PRIME32_3;
h32 ^= h32 >> 16;
//hypre_assert(HYPRE_HOPSCOTCH_HASH_EMPTY != h32);
return h32;
}
#endif
#ifdef HYPRE_BIGINT
static inline HYPRE_Int
hypre_Hash(HYPRE_Int input)
{
hypre_ulongint h64 = HYPRE_XXH_PRIME64_5 + sizeof(input);
hypre_ulongint k1 = input;
k1 *= HYPRE_XXH_PRIME64_2;
k1 = HYPRE_XXH_rotl64(k1, 31);
k1 *= HYPRE_XXH_PRIME64_1;
h64 ^= k1;
h64 = HYPRE_XXH_rotl64(h64, 27)*HYPRE_XXH_PRIME64_1 + HYPRE_XXH_PRIME64_4;
h64 ^= h64 >> 33;
h64 *= HYPRE_XXH_PRIME64_2;
h64 ^= h64 >> 29;
h64 *= HYPRE_XXH_PRIME64_3;
h64 ^= h64 >> 32;
#ifndef NDEBUG
if (HYPRE_HOPSCOTCH_HASH_EMPTY == h64) {
hypre_printf("hash(%lld) = %d\n", h64, HYPRE_HOPSCOTCH_HASH_EMPTY);
hypre_assert(HYPRE_HOPSCOTCH_HASH_EMPTY != h64);
}
#endif
return h64;
}
#else
static inline HYPRE_Int
hypre_Hash(HYPRE_Int input)
{
hypre_uint h32 = HYPRE_XXH_PRIME32_5 + sizeof(input);
// 1665863975 is added to input so that
// only -1073741824 gives HYPRE_HOPSCOTCH_HASH_EMPTY.
// Hence, we're fine as long as key is non-negative.
h32 += (input + 1665863975)*HYPRE_XXH_PRIME32_3;
h32 = HYPRE_XXH_rotl32(h32, 17)*HYPRE_XXH_PRIME32_4;
h32 ^= h32 >> 15;
h32 *= HYPRE_XXH_PRIME32_2;
h32 ^= h32 >> 13;
h32 *= HYPRE_XXH_PRIME32_3;
h32 ^= h32 >> 16;
//hypre_assert(HYPRE_HOPSCOTCH_HASH_EMPTY != h32);
return h32;
}
#endif
static inline void
hypre_UnorderedIntSetFindCloserFreeBucket( hypre_UnorderedIntSet *s,
#ifdef HYPRE_CONCURRENT_HOPSCOTCH
hypre_HopscotchSegment *start_seg,
#endif
HYPRE_Int *free_bucket,
HYPRE_Int *free_dist )
{
HYPRE_Int move_bucket = *free_bucket - (HYPRE_HOPSCOTCH_HASH_HOP_RANGE - 1);
HYPRE_Int move_free_dist;
for (move_free_dist = HYPRE_HOPSCOTCH_HASH_HOP_RANGE - 1; move_free_dist > 0; --move_free_dist)
{
hypre_uint start_hop_info = s->hopInfo[move_bucket];
HYPRE_Int move_new_free_dist = -1;
hypre_uint mask = 1;
HYPRE_Int i;
for (i = 0; i < move_free_dist; ++i, mask <<= 1)
{
if (mask & start_hop_info)
{
move_new_free_dist = i;
break;
}
}
if (-1 != move_new_free_dist)
{
#ifdef HYPRE_CONCURRENT_HOPSCOTCH
hypre_HopscotchSegment* move_segment = &(s->segments[move_bucket & s->segmentMask]);
if(start_seg != move_segment)
omp_set_lock(&move_segment->lock);
#endif
if (start_hop_info == s->hopInfo[move_bucket])
{
// new_free_bucket -> free_bucket and empty new_free_bucket
HYPRE_Int new_free_bucket = move_bucket + move_new_free_dist;
s->key[*free_bucket] = s->key[new_free_bucket];
s->hash[*free_bucket] = s->hash[new_free_bucket];
#ifdef HYPRE_CONCURRENT_HOPSCOTCH
++move_segment->timestamp;
#pragma omp flush
#endif
s->hopInfo[move_bucket] |= (1U << move_free_dist);
s->hopInfo[move_bucket] &= ~(1U << move_new_free_dist);
*free_bucket = new_free_bucket;
*free_dist -= move_free_dist - move_new_free_dist;
#ifdef HYPRE_CONCURRENT_HOPSCOTCH
if(start_seg != move_segment)
omp_unset_lock(&move_segment->lock);
#endif
return;
}
#ifdef HYPRE_CONCURRENT_HOPSCOTCH
if(start_seg != move_segment)
omp_unset_lock(&move_segment->lock);
#endif
}
++move_bucket;
}
*free_bucket = -1;
*free_dist = 0;
}
static inline void
hypre_UnorderedBigIntSetFindCloserFreeBucket( hypre_UnorderedBigIntSet *s,
#ifdef HYPRE_CONCURRENT_HOPSCOTCH
hypre_HopscotchSegment *start_seg,
#endif
HYPRE_Int *free_bucket,
HYPRE_Int *free_dist )
{
HYPRE_Int move_bucket = *free_bucket - (HYPRE_HOPSCOTCH_HASH_HOP_RANGE - 1);
HYPRE_Int move_free_dist;
for (move_free_dist = HYPRE_HOPSCOTCH_HASH_HOP_RANGE - 1; move_free_dist > 0; --move_free_dist)
{
hypre_uint start_hop_info = s->hopInfo[move_bucket];
HYPRE_Int move_new_free_dist = -1;
hypre_uint mask = 1;
HYPRE_Int i;
for (i = 0; i < move_free_dist; ++i, mask <<= 1)
{
if (mask & start_hop_info)
{
move_new_free_dist = i;
break;
}
}
if (-1 != move_new_free_dist)
{
#ifdef HYPRE_CONCURRENT_HOPSCOTCH
hypre_HopscotchSegment* move_segment = &(s->segments[move_bucket & s->segmentMask]);
if(start_seg != move_segment)
omp_set_lock(&move_segment->lock);
#endif
if (start_hop_info == s->hopInfo[move_bucket])
{
// new_free_bucket -> free_bucket and empty new_free_bucket
HYPRE_Int new_free_bucket = move_bucket + move_new_free_dist;
s->key[*free_bucket] = s->key[new_free_bucket];
s->hash[*free_bucket] = s->hash[new_free_bucket];
#ifdef HYPRE_CONCURRENT_HOPSCOTCH
++move_segment->timestamp;
#pragma omp flush
#endif
s->hopInfo[move_bucket] |= (1U << move_free_dist);
s->hopInfo[move_bucket] &= ~(1U << move_new_free_dist);
*free_bucket = new_free_bucket;
*free_dist -= move_free_dist - move_new_free_dist;
#ifdef HYPRE_CONCURRENT_HOPSCOTCH
if(start_seg != move_segment)
omp_unset_lock(&move_segment->lock);
#endif
return;
}
#ifdef HYPRE_CONCURRENT_HOPSCOTCH
if(start_seg != move_segment)
omp_unset_lock(&move_segment->lock);
#endif
}
++move_bucket;
}
*free_bucket = -1;
*free_dist = 0;
}
static inline void
hypre_UnorderedIntMapFindCloserFreeBucket( hypre_UnorderedIntMap *m,
#ifdef HYPRE_CONCURRENT_HOPSCOTCH
hypre_HopscotchSegment *start_seg,
#endif
hypre_HopscotchBucket **free_bucket,
HYPRE_Int *free_dist)
{
hypre_HopscotchBucket* move_bucket = *free_bucket - (HYPRE_HOPSCOTCH_HASH_HOP_RANGE - 1);
HYPRE_Int move_free_dist;
for (move_free_dist = HYPRE_HOPSCOTCH_HASH_HOP_RANGE - 1; move_free_dist > 0; --move_free_dist)
{
hypre_uint start_hop_info = move_bucket->hopInfo;
HYPRE_Int move_new_free_dist = -1;
hypre_uint mask = 1;
HYPRE_Int i;
for (i = 0; i < move_free_dist; ++i, mask <<= 1)
{
if (mask & start_hop_info)
{
move_new_free_dist = i;
break;
}
}
if (-1 != move_new_free_dist)
{
#ifdef HYPRE_CONCURRENT_HOPSCOTCH
hypre_HopscotchSegment* move_segment = &(m->segments[(move_bucket - m->table) & m->segmentMask]);
if (start_seg != move_segment)
omp_set_lock(&move_segment->lock);
#endif
if (start_hop_info == move_bucket->hopInfo)
{
// new_free_bucket -> free_bucket and empty new_free_bucket
hypre_HopscotchBucket* new_free_bucket = move_bucket + move_new_free_dist;
(*free_bucket)->data = new_free_bucket->data;
(*free_bucket)->key = new_free_bucket->key;
(*free_bucket)->hash = new_free_bucket->hash;
#ifdef HYPRE_CONCURRENT_HOPSCOTCH
++move_segment->timestamp;
#pragma omp flush
#endif
move_bucket->hopInfo |= (1U << move_free_dist);
move_bucket->hopInfo &= ~(1U << move_new_free_dist);
*free_bucket = new_free_bucket;
*free_dist -= move_free_dist - move_new_free_dist;
#ifdef HYPRE_CONCURRENT_HOPSCOTCH
if(start_seg != move_segment)
omp_unset_lock(&move_segment->lock);
#endif
return;
}
#ifdef HYPRE_CONCURRENT_HOPSCOTCH
if(start_seg != move_segment)
omp_unset_lock(&move_segment->lock);
#endif
}
++move_bucket;
}
*free_bucket = NULL;
*free_dist = 0;
}
static inline void
hypre_UnorderedBigIntMapFindCloserFreeBucket( hypre_UnorderedBigIntMap *m,
#ifdef HYPRE_CONCURRENT_HOPSCOTCH
hypre_HopscotchSegment *start_seg,
#endif
hypre_BigHopscotchBucket **free_bucket,
HYPRE_Int *free_dist)
{
hypre_BigHopscotchBucket* move_bucket = *free_bucket - (HYPRE_HOPSCOTCH_HASH_HOP_RANGE - 1);
HYPRE_Int move_free_dist;
for (move_free_dist = HYPRE_HOPSCOTCH_HASH_HOP_RANGE - 1; move_free_dist > 0; --move_free_dist)
{
hypre_uint start_hop_info = move_bucket->hopInfo;
HYPRE_Int move_new_free_dist = -1;
hypre_uint mask = 1;
HYPRE_Int i;
for (i = 0; i < move_free_dist; ++i, mask <<= 1)
{
if (mask & start_hop_info)
{
move_new_free_dist = i;
break;
}
}
if (-1 != move_new_free_dist)
{
#ifdef HYPRE_CONCURRENT_HOPSCOTCH
hypre_HopscotchSegment* move_segment = &(m->segments[(move_bucket - m->table) & m->segmentMask]);
if (start_seg != move_segment)
omp_set_lock(&move_segment->lock);
#endif
if (start_hop_info == move_bucket->hopInfo)
{
// new_free_bucket -> free_bucket and empty new_free_bucket
hypre_BigHopscotchBucket* new_free_bucket = move_bucket + move_new_free_dist;
(*free_bucket)->data = new_free_bucket->data;
(*free_bucket)->key = new_free_bucket->key;
(*free_bucket)->hash = new_free_bucket->hash;
#ifdef HYPRE_CONCURRENT_HOPSCOTCH
++move_segment->timestamp;
#pragma omp flush
#endif
move_bucket->hopInfo |= (1U << move_free_dist);
move_bucket->hopInfo &= ~(1U << move_new_free_dist);
*free_bucket = new_free_bucket;
*free_dist -= move_free_dist - move_new_free_dist;
#ifdef HYPRE_CONCURRENT_HOPSCOTCH
if(start_seg != move_segment)
omp_unset_lock(&move_segment->lock);
#endif
return;
}
#ifdef HYPRE_CONCURRENT_HOPSCOTCH
if(start_seg != move_segment)
omp_unset_lock(&move_segment->lock);
#endif
}
++move_bucket;
}
*free_bucket = NULL;
*free_dist = 0;
}
void hypre_UnorderedIntSetCreate( hypre_UnorderedIntSet *s,
HYPRE_Int inCapacity,
HYPRE_Int concurrencyLevel);
void hypre_UnorderedBigIntSetCreate( hypre_UnorderedBigIntSet *s,
HYPRE_Int inCapacity,
HYPRE_Int concurrencyLevel);
void hypre_UnorderedIntMapCreate( hypre_UnorderedIntMap *m,
HYPRE_Int inCapacity,
HYPRE_Int concurrencyLevel);
void hypre_UnorderedBigIntMapCreate( hypre_UnorderedBigIntMap *m,
HYPRE_Int inCapacity,
HYPRE_Int concurrencyLevel);
void hypre_UnorderedIntSetDestroy( hypre_UnorderedIntSet *s );
void hypre_UnorderedBigIntSetDestroy( hypre_UnorderedBigIntSet *s );
void hypre_UnorderedIntMapDestroy( hypre_UnorderedIntMap *m );
void hypre_UnorderedBigIntMapDestroy( hypre_UnorderedBigIntMap *m );
// Query Operations .........................................................
static inline HYPRE_Int
hypre_UnorderedIntSetContains( hypre_UnorderedIntSet *s,
HYPRE_Int key )
{
//CALCULATE HASH ..........................
#ifdef HYPRE_BIGINT
HYPRE_Int hash = hypre_BigHash(key);
#else
HYPRE_Int hash = hypre_Hash(key);
#endif
//CHECK IF ALREADY CONTAIN ................
#ifdef HYPRE_CONCURRENT_HOPSCOTCH
hypre_HopscotchSegment *segment = &s->segments[hash & s->segmentMask];
#endif
HYPRE_Int bucket = hash & s->bucketMask;
hypre_uint hopInfo = s->hopInfo[bucket];
if (0 == hopInfo)
return 0;
else if (1 == hopInfo )
{
if (hash == s->hash[bucket] && key == s->key[bucket])
return 1;
else return 0;
}
#ifdef HYPRE_CONCURRENT_HOPSCOTCH
HYPRE_Int startTimestamp = segment->timestamp;
#endif
while (0 != hopInfo)
{
HYPRE_Int i = first_lsb_bit_indx(hopInfo);
HYPRE_Int currElm = bucket + i;
if (hash == s->hash[currElm] && key == s->key[currElm])
return 1;
hopInfo &= ~(1U << i);
}
#ifdef HYPRE_CONCURRENT_HOPSCOTCH
if (segment->timestamp == startTimestamp)
return 0;
#endif
HYPRE_Int i;
for (i = 0; i< HYPRE_HOPSCOTCH_HASH_HOP_RANGE; ++i)
{
if (hash == s->hash[bucket + i] && key == s->key[bucket + i])
return 1;
}
return 0;
}
static inline HYPRE_Int
hypre_UnorderedBigIntSetContains( hypre_UnorderedBigIntSet *s,
HYPRE_BigInt key )
{
//CALCULATE HASH ..........................
#if defined(HYPRE_BIGINT) || defined(HYPRE_MIXEDINT)
HYPRE_BigInt hash = hypre_BigHash(key);
#else
HYPRE_BigInt hash = hypre_Hash(key);
#endif
//CHECK IF ALREADY CONTAIN ................
#ifdef HYPRE_CONCURRENT_HOPSCOTCH
hypre_HopscotchSegment *segment = &s->segments[(HYPRE_Int)(hash & s->segmentMask)];
#endif
HYPRE_Int bucket = (HYPRE_Int)(hash & s->bucketMask);
hypre_uint hopInfo = s->hopInfo[bucket];
if (0 == hopInfo)
return 0;
else if (1 == hopInfo )
{
if (hash == s->hash[bucket] && key == s->key[bucket])
return 1;
else return 0;
}
#ifdef HYPRE_CONCURRENT_HOPSCOTCH
HYPRE_Int startTimestamp = segment->timestamp;
#endif
while (0 != hopInfo)
{
HYPRE_Int i = first_lsb_bit_indx(hopInfo);
HYPRE_Int currElm = bucket + i;
if (hash == s->hash[currElm] && key == s->key[currElm])
return 1;
hopInfo &= ~(1U << i);
}
#ifdef HYPRE_CONCURRENT_HOPSCOTCH
if (segment->timestamp == startTimestamp)
return 0;
#endif
HYPRE_Int i;
for (i = 0; i< HYPRE_HOPSCOTCH_HASH_HOP_RANGE; ++i)
{
if (hash == s->hash[bucket + i] && key == s->key[bucket + i])
return 1;
}
return 0;
}
/**
* @ret -1 if key doesn't exist
*/
static inline HYPRE_Int
hypre_UnorderedIntMapGet( hypre_UnorderedIntMap *m,
HYPRE_Int key )
{
//CALCULATE HASH ..........................
#ifdef HYPRE_BIGINT
HYPRE_Int hash = hypre_BigHash(key);
#else
HYPRE_Int hash = hypre_Hash(key);
#endif
//CHECK IF ALREADY CONTAIN ................
#ifdef HYPRE_CONCURRENT_HOPSCOTCH
hypre_HopscotchSegment *segment = &m->segments[hash & m->segmentMask];
#endif
hypre_HopscotchBucket *elmAry = &(m->table[hash & m->bucketMask]);
hypre_uint hopInfo = elmAry->hopInfo;
if (0 == hopInfo)
return -1;
else if (1 == hopInfo )
{
if (hash == elmAry->hash && key == elmAry->key)
return elmAry->data;
else return -1;
}
#ifdef HYPRE_CONCURRENT_HOPSCOTCH
HYPRE_Int startTimestamp = segment->timestamp;
#endif
while (0 != hopInfo)
{
HYPRE_Int i = first_lsb_bit_indx(hopInfo);
hypre_HopscotchBucket* currElm = elmAry + i;
if (hash == currElm->hash && key == currElm->key)
return currElm->data;
hopInfo &= ~(1U << i);
}
#ifdef HYPRE_CONCURRENT_HOPSCOTCH
if (segment->timestamp == startTimestamp)
return -1;
#endif
hypre_HopscotchBucket *currBucket = &(m->table[hash & m->bucketMask]);
HYPRE_Int i;
for (i = 0; i< HYPRE_HOPSCOTCH_HASH_HOP_RANGE; ++i, ++currBucket)
{
if (hash == currBucket->hash && key == currBucket->key)
return currBucket->data;
}
return -1;
}
static inline
HYPRE_Int hypre_UnorderedBigIntMapGet( hypre_UnorderedBigIntMap *m,
HYPRE_BigInt key )
{
//CALCULATE HASH ..........................
#if defined(HYPRE_BIGINT) || defined(HYPRE_MIXEDINT)
HYPRE_BigInt hash = hypre_BigHash(key);
#else
HYPRE_BigInt hash = hypre_Hash(key);
#endif
//CHECK IF ALREADY CONTAIN ................
#ifdef HYPRE_CONCURRENT_HOPSCOTCH
hypre_HopscotchSegment *segment = &m->segments[(HYPRE_Int)(hash & m->segmentMask)];
#endif
hypre_BigHopscotchBucket *elmAry = &(m->table[(HYPRE_Int)(hash & m->bucketMask)]);
hypre_uint hopInfo = elmAry->hopInfo;
if (0 == hopInfo)
return -1;
else if (1 == hopInfo )
{
if (hash == elmAry->hash && key == elmAry->key)
return elmAry->data;
else return -1;
}
#ifdef HYPRE_CONCURRENT_HOPSCOTCH
HYPRE_Int startTimestamp = segment->timestamp;
#endif
while (0 != hopInfo)
{
HYPRE_Int i = first_lsb_bit_indx(hopInfo);
hypre_BigHopscotchBucket* currElm = elmAry + i;
if (hash == currElm->hash && key == currElm->key)
return currElm->data;
hopInfo &= ~(1U << i);
}
#ifdef HYPRE_CONCURRENT_HOPSCOTCH
if (segment->timestamp == startTimestamp)
return -1;
#endif
hypre_BigHopscotchBucket *currBucket = &(m->table[hash & m->bucketMask]);
HYPRE_Int i;
for (i = 0; i< HYPRE_HOPSCOTCH_HASH_HOP_RANGE; ++i, ++currBucket)
{
if (hash == currBucket->hash && key == currBucket->key)
return currBucket->data;
}
return -1;
}
//status Operations .........................................................
static inline
HYPRE_Int hypre_UnorderedIntSetSize( hypre_UnorderedIntSet *s )
{
HYPRE_Int counter = 0;
HYPRE_Int n = s->bucketMask + HYPRE_HOPSCOTCH_HASH_INSERT_RANGE;
HYPRE_Int i;
for (i = 0; i < n; ++i)
{
if (HYPRE_HOPSCOTCH_HASH_EMPTY != s->hash[i])
{
++counter;
}
}
return counter;
}
static inline
HYPRE_Int hypre_UnorderedBigIntSetSize( hypre_UnorderedBigIntSet *s )
{
HYPRE_Int counter = 0;
HYPRE_BigInt n = s->bucketMask + HYPRE_HOPSCOTCH_HASH_INSERT_RANGE;
HYPRE_Int i;
for (i = 0; i < n; ++i)
{
if (HYPRE_HOPSCOTCH_HASH_EMPTY != s->hash[i])
{
++counter;
}
}
return counter;
}
static inline HYPRE_Int
hypre_UnorderedIntMapSize( hypre_UnorderedIntMap *m )
{
HYPRE_Int counter = 0;
HYPRE_Int n = m->bucketMask + HYPRE_HOPSCOTCH_HASH_INSERT_RANGE;
HYPRE_Int i;
for (i = 0; i < n; ++i)
{
if( HYPRE_HOPSCOTCH_HASH_EMPTY != m->table[i].hash )
{
++counter;
}
}
return counter;
}
static inline HYPRE_Int
hypre_UnorderedBigIntMapSize( hypre_UnorderedBigIntMap *m )
{
HYPRE_Int counter = 0;
HYPRE_Int n = m->bucketMask + HYPRE_HOPSCOTCH_HASH_INSERT_RANGE;
HYPRE_Int i;
for (i = 0; i < n; ++i)
{
if( HYPRE_HOPSCOTCH_HASH_EMPTY != m->table[i].hash )
{
++counter;
}
}
return counter;
}
HYPRE_Int *hypre_UnorderedIntSetCopyToArray( hypre_UnorderedIntSet *s, HYPRE_Int *len );
HYPRE_BigInt *hypre_UnorderedBigIntSetCopyToArray( hypre_UnorderedBigIntSet *s, HYPRE_Int *len );
//modification Operations ...................................................
static inline void
hypre_UnorderedIntSetPut( hypre_UnorderedIntSet *s,
HYPRE_Int key )
{
//CALCULATE HASH ..........................
#ifdef HYPRE_BIGINT
HYPRE_Int hash = hypre_BigHash(key);
#else
HYPRE_Int hash = hypre_Hash(key);
#endif
//LOCK KEY HASH ENTERY ....................
#ifdef HYPRE_CONCURRENT_HOPSCOTCH
hypre_HopscotchSegment *segment = &s->segments[hash & s->segmentMask];
omp_set_lock(&segment->lock);
#endif
HYPRE_Int bucket = hash&s->bucketMask;
//CHECK IF ALREADY CONTAIN ................
hypre_uint hopInfo = s->hopInfo[bucket];
while (0 != hopInfo)
{
HYPRE_Int i = first_lsb_bit_indx(hopInfo);
HYPRE_Int currElm = bucket + i;
if(hash == s->hash[currElm] && key == s->key[currElm])
{
#ifdef HYPRE_CONCURRENT_HOPSCOTCH
omp_unset_lock(&segment->lock);
#endif
return;
}
hopInfo &= ~(1U << i);
}
//LOOK FOR FREE BUCKET ....................
HYPRE_Int free_bucket = bucket;
HYPRE_Int free_dist = 0;
for ( ; free_dist < HYPRE_HOPSCOTCH_HASH_INSERT_RANGE; ++free_dist, ++free_bucket)
{
if( (HYPRE_HOPSCOTCH_HASH_EMPTY == s->hash[free_bucket]) &&
(HYPRE_HOPSCOTCH_HASH_EMPTY ==
hypre_compare_and_swap((HYPRE_Int *)&s->hash[free_bucket],
(HYPRE_Int)HYPRE_HOPSCOTCH_HASH_EMPTY,
(HYPRE_Int)HYPRE_HOPSCOTCH_HASH_BUSY)) )
break;
}
//PLACE THE NEW KEY .......................
if (free_dist < HYPRE_HOPSCOTCH_HASH_INSERT_RANGE)
{
do
{
if (free_dist < HYPRE_HOPSCOTCH_HASH_HOP_RANGE)
{
s->key[free_bucket] = key;
s->hash[free_bucket] = hash;
s->hopInfo[bucket] |= 1U << free_dist;
#ifdef HYPRE_CONCURRENT_HOPSCOTCH
omp_unset_lock(&segment->lock);
#endif
return;
}
hypre_UnorderedIntSetFindCloserFreeBucket(s,
#ifdef HYPRE_CONCURRENT_HOPSCOTCH
segment,
#endif
&free_bucket, &free_dist);
} while (-1 != free_bucket);
}
//NEED TO RESIZE ..........................
hypre_error_w_msg(HYPRE_ERROR_GENERIC,"ERROR - RESIZE is not implemented\n");
/*fprintf(stderr, "ERROR - RESIZE is not implemented\n");*/
exit(1);
return;
}
static inline void
hypre_UnorderedBigIntSetPut( hypre_UnorderedBigIntSet *s,
HYPRE_BigInt key )
{
//CALCULATE HASH ..........................
#if defined(HYPRE_BIGINT) || defined(HYPRE_MIXEDINT)
HYPRE_BigInt hash = hypre_BigHash(key);
#else
HYPRE_BigInt hash = hypre_Hash(key);
#endif
//LOCK KEY HASH ENTERY ....................
#ifdef HYPRE_CONCURRENT_HOPSCOTCH
hypre_HopscotchSegment *segment = &s->segments[hash & s->segmentMask];
omp_set_lock(&segment->lock);
#endif
HYPRE_Int bucket = (HYPRE_Int)(hash&s->bucketMask);
//CHECK IF ALREADY CONTAIN ................
hypre_uint hopInfo = s->hopInfo[bucket];
while (0 != hopInfo)
{
HYPRE_Int i = first_lsb_bit_indx(hopInfo);
HYPRE_Int currElm = bucket + i;
if(hash == s->hash[currElm] && key == s->key[currElm])
{
#ifdef HYPRE_CONCURRENT_HOPSCOTCH
omp_unset_lock(&segment->lock);
#endif
return;
}
hopInfo &= ~(1U << i);
}
//LOOK FOR FREE BUCKET ....................
HYPRE_Int free_bucket = bucket;
HYPRE_Int free_dist = 0;
for ( ; free_dist < HYPRE_HOPSCOTCH_HASH_INSERT_RANGE; ++free_dist, ++free_bucket)
{
if( (HYPRE_HOPSCOTCH_HASH_EMPTY == s->hash[free_bucket]) &&
(HYPRE_HOPSCOTCH_HASH_EMPTY ==
hypre_compare_and_swap((HYPRE_Int *)&s->hash[free_bucket],
(HYPRE_Int)HYPRE_HOPSCOTCH_HASH_EMPTY,
(HYPRE_Int)HYPRE_HOPSCOTCH_HASH_BUSY)) )
break;
}
//PLACE THE NEW KEY .......................
if (free_dist < HYPRE_HOPSCOTCH_HASH_INSERT_RANGE)
{
do
{
if (free_dist < HYPRE_HOPSCOTCH_HASH_HOP_RANGE)
{
s->key[free_bucket] = key;
s->hash[free_bucket] = hash;
s->hopInfo[bucket] |= 1U << free_dist;
#ifdef HYPRE_CONCURRENT_HOPSCOTCH
omp_unset_lock(&segment->lock);
#endif
return;
}
hypre_UnorderedBigIntSetFindCloserFreeBucket(s,
#ifdef HYPRE_CONCURRENT_HOPSCOTCH
segment,
#endif
&free_bucket, &free_dist);
} while (-1 != free_bucket);
}
//NEED TO RESIZE ..........................
hypre_error_w_msg(HYPRE_ERROR_GENERIC,"ERROR - RESIZE is not implemented\n");
/*fprintf(stderr, "ERROR - RESIZE is not implemented\n");*/
exit(1);
return;
}
static inline HYPRE_Int
hypre_UnorderedIntMapPutIfAbsent( hypre_UnorderedIntMap *m,
HYPRE_Int key, HYPRE_Int data )
{
//CALCULATE HASH ..........................
#ifdef HYPRE_BIGINT
HYPRE_Int hash = hypre_BigHash(key);
#else
HYPRE_Int hash = hypre_Hash(key);
#endif
//LOCK KEY HASH ENTERY ....................
#ifdef HYPRE_CONCURRENT_HOPSCOTCH
hypre_HopscotchSegment *segment = &m->segments[hash & m->segmentMask];
omp_set_lock(&segment->lock);
#endif
hypre_HopscotchBucket* startBucket = &(m->table[hash & m->bucketMask]);
//CHECK IF ALREADY CONTAIN ................
hypre_uint hopInfo = startBucket->hopInfo;
while (0 != hopInfo)
{
HYPRE_Int i = first_lsb_bit_indx(hopInfo);
hypre_HopscotchBucket* currElm = startBucket + i;
if (hash == currElm->hash && key == currElm->key)
{
HYPRE_Int rc = currElm->data;
#ifdef HYPRE_CONCURRENT_HOPSCOTCH
omp_unset_lock(&segment->lock);
#endif
return rc;
}
hopInfo &= ~(1U << i);
}
//LOOK FOR FREE BUCKET ....................
hypre_HopscotchBucket* free_bucket = startBucket;
HYPRE_Int free_dist = 0;
for ( ; free_dist < HYPRE_HOPSCOTCH_HASH_INSERT_RANGE; ++free_dist, ++free_bucket)
{
if( (HYPRE_HOPSCOTCH_HASH_EMPTY == free_bucket->hash) &&
(HYPRE_HOPSCOTCH_HASH_EMPTY ==
hypre_compare_and_swap((HYPRE_Int *)&free_bucket->hash,
(HYPRE_Int)HYPRE_HOPSCOTCH_HASH_EMPTY,
(HYPRE_Int)HYPRE_HOPSCOTCH_HASH_BUSY)) )
break;
}
//PLACE THE NEW KEY .......................
if (free_dist < HYPRE_HOPSCOTCH_HASH_INSERT_RANGE)
{
do
{
if (free_dist < HYPRE_HOPSCOTCH_HASH_HOP_RANGE)
{
free_bucket->data = data;
free_bucket->key = key;
free_bucket->hash = hash;
startBucket->hopInfo |= 1U << free_dist;
#ifdef HYPRE_CONCURRENT_HOPSCOTCH
omp_unset_lock(&segment->lock);
#endif
return HYPRE_HOPSCOTCH_HASH_EMPTY;
}
hypre_UnorderedIntMapFindCloserFreeBucket(m,
#ifdef HYPRE_CONCURRENT_HOPSCOTCH
segment,
#endif
&free_bucket, &free_dist);
} while (NULL != free_bucket);
}
//NEED TO RESIZE ..........................
hypre_error_w_msg(HYPRE_ERROR_GENERIC,"ERROR - RESIZE is not implemented\n");
/*fprintf(stderr, "ERROR - RESIZE is not implemented\n");*/
exit(1);
return HYPRE_HOPSCOTCH_HASH_EMPTY;
}
static inline HYPRE_Int
hypre_UnorderedBigIntMapPutIfAbsent( hypre_UnorderedBigIntMap *m,
HYPRE_BigInt key, HYPRE_Int data)
{
//CALCULATE HASH ..........................
#if defined(HYPRE_BIGINT) || defined(HYPRE_MIXEDINT)
HYPRE_BigInt hash = hypre_BigHash(key);
#else
HYPRE_BigInt hash = hypre_Hash(key);
#endif
//LOCK KEY HASH ENTERY ....................
#ifdef HYPRE_CONCURRENT_HOPSCOTCH
hypre_HopscotchSegment *segment = &m->segments[hash & m->segmentMask];
omp_set_lock(&segment->lock);
#endif
hypre_BigHopscotchBucket* startBucket = &(m->table[hash & m->bucketMask]);
//CHECK IF ALREADY CONTAIN ................
hypre_uint hopInfo = startBucket->hopInfo;
while (0 != hopInfo)
{
HYPRE_Int i = first_lsb_bit_indx(hopInfo);
hypre_BigHopscotchBucket* currElm = startBucket + i;
if (hash == currElm->hash && key == currElm->key)
{
HYPRE_Int rc = currElm->data;
#ifdef HYPRE_CONCURRENT_HOPSCOTCH
omp_unset_lock(&segment->lock);
#endif
return rc;
}
hopInfo &= ~(1U << i);
}
//LOOK FOR FREE BUCKET ....................
hypre_BigHopscotchBucket* free_bucket = startBucket;
HYPRE_Int free_dist = 0;
for ( ; free_dist < HYPRE_HOPSCOTCH_HASH_INSERT_RANGE; ++free_dist, ++free_bucket)
{
if( (HYPRE_HOPSCOTCH_HASH_EMPTY == free_bucket->hash) &&
(HYPRE_HOPSCOTCH_HASH_EMPTY ==
hypre_compare_and_swap((HYPRE_Int *)&free_bucket->hash,
(HYPRE_Int)HYPRE_HOPSCOTCH_HASH_EMPTY,
(HYPRE_Int)HYPRE_HOPSCOTCH_HASH_BUSY)) )
break;
}
//PLACE THE NEW KEY .......................
if (free_dist < HYPRE_HOPSCOTCH_HASH_INSERT_RANGE)
{
do
{
if (free_dist < HYPRE_HOPSCOTCH_HASH_HOP_RANGE)
{
free_bucket->data = data;
free_bucket->key = key;
free_bucket->hash = hash;
startBucket->hopInfo |= 1U << free_dist;
#ifdef HYPRE_CONCURRENT_HOPSCOTCH
omp_unset_lock(&segment->lock);
#endif
return HYPRE_HOPSCOTCH_HASH_EMPTY;
}
hypre_UnorderedBigIntMapFindCloserFreeBucket(m,
#ifdef HYPRE_CONCURRENT_HOPSCOTCH
segment,
#endif
&free_bucket, &free_dist);
} while (NULL != free_bucket);
}
//NEED TO RESIZE ..........................
hypre_error_w_msg(HYPRE_ERROR_GENERIC,"ERROR - RESIZE is not implemented\n");
/*fprintf(stderr, "ERROR - RESIZE is not implemented\n");*/
exit(1);
return HYPRE_HOPSCOTCH_HASH_EMPTY;
}
#ifdef __cplusplus
} // extern "C"
#endif
#endif // hypre_HOPSCOTCH_HASH_HEADER
#ifdef __cplusplus
}
#endif
#endif
|
GB_binop__minus_uint32.c |
//------------------------------------------------------------------------------
// GB_binop: hard-coded functions for each built-in binary operator
//------------------------------------------------------------------------------
// SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2022, All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
//------------------------------------------------------------------------------
// If this file is in the Generated2/ folder, do not edit it
// (it is auto-generated from Generator/*).
#include "GB.h"
#ifndef GBCOMPACT
#include "GB_emult.h"
#include "GB_control.h"
#include "GB_ek_slice.h"
#include "GB_dense.h"
#include "GB_atomics.h"
#include "GB_bitmap_assign_methods.h"
#include "GB_binop__include.h"
// C=binop(A,B) is defined by the following types and operators:
// A+B function (eWiseAdd): GB (_AaddB__minus_uint32)
// A.*B function (eWiseMult): GB (_AemultB_08__minus_uint32)
// A.*B function (eWiseMult): GB (_AemultB_02__minus_uint32)
// A.*B function (eWiseMult): GB (_AemultB_04__minus_uint32)
// A.*B function (eWiseMult): GB (_AemultB_bitmap__minus_uint32)
// A*D function (colscale): GB (_AxD__minus_uint32)
// D*A function (rowscale): GB (_DxB__minus_uint32)
// C+=B function (dense accum): GB (_Cdense_accumB__minus_uint32)
// C+=b function (dense accum): GB (_Cdense_accumb__minus_uint32)
// C+=A+B function (dense ewise3): GB (_Cdense_ewise3_accum__minus_uint32)
// C=A+B function (dense ewise3): GB (_Cdense_ewise3_noaccum__minus_uint32)
// C=scalar+B GB (_bind1st__minus_uint32)
// C=scalar+B' GB (_bind1st_tran__minus_uint32)
// C=A+scalar GB (_bind2nd__minus_uint32)
// C=A'+scalar GB (_bind2nd_tran__minus_uint32)
// C type: uint32_t
// A type: uint32_t
// A pattern? 0
// B type: uint32_t
// B pattern? 0
// BinaryOp: cij = (aij - bij)
#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,A_iso) \
uint32_t aij = GBX (Ax, pA, A_iso)
// true if values of A are not used
#define GB_A_IS_PATTERN \
0 \
// bij = Bx [pB]
#define GB_GETB(bij,Bx,pB,B_iso) \
uint32_t bij = GBX (Bx, pB, B_iso)
// true if values of B are not used
#define GB_B_IS_PATTERN \
0 \
// declare scalar of the same type as C
#define GB_CTYPE_SCALAR(t) \
uint32_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_UINT32 || GxB_NO_MINUS_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__minus_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
//------------------------------------------------------------------------------
void GB (_Cdense_ewise3_noaccum__minus_uint32)
(
GrB_Matrix C,
const GrB_Matrix A,
const GrB_Matrix B,
const int nthreads
)
{
#include "GB_dense_ewise3_noaccum_template.c"
}
//------------------------------------------------------------------------------
// C += B, accumulate a sparse matrix into a dense matrix
//------------------------------------------------------------------------------
GrB_Info GB (_Cdense_accumB__minus_uint32)
(
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_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__minus_uint32)
(
GrB_Matrix C,
const GrB_Matrix A,
const GrB_Matrix D,
const int64_t *A_ek_slicing, const int A_ntasks, const int A_nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
uint32_t *restrict Cx = (uint32_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_uint32)
(
GrB_Matrix C,
const GrB_Matrix D,
const GrB_Matrix B,
int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
uint32_t *restrict Cx = (uint32_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__minus_uint32)
(
GrB_Matrix C,
const int C_sparsity,
const GrB_Matrix M,
const bool Mask_struct,
const bool Mask_comp,
const GrB_Matrix A,
const GrB_Matrix B,
const bool is_eWiseUnion,
const GB_void *alpha_scalar_in,
const GB_void *beta_scalar_in,
const bool Ch_is_Mh,
const int64_t *restrict C_to_M,
const int64_t *restrict C_to_A,
const int64_t *restrict C_to_B,
const GB_task_struct *restrict TaskList,
const int C_ntasks,
const int C_nthreads,
GB_Context Context
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
GB_WERK_DECLARE (M_ek_slicing, int64_t) ;
GB_WERK_DECLARE (A_ek_slicing, int64_t) ;
GB_WERK_DECLARE (B_ek_slicing, int64_t) ;
uint32_t alpha_scalar ;
uint32_t beta_scalar ;
if (is_eWiseUnion)
{
alpha_scalar = (*((uint32_t *) alpha_scalar_in)) ;
beta_scalar = (*((uint32_t *) beta_scalar_in )) ;
}
#include "GB_add_template.c"
GB_FREE_WORKSPACE ;
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// eWiseMult: C=A.*B, C<M>=A.*B, or C<M!>=A.*B where C is sparse/hyper
//------------------------------------------------------------------------------
GrB_Info GB (_AemultB_08__minus_uint32)
(
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__minus_uint32)
(
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__minus_uint32)
(
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__minus_uint32)
(
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_uint32)
(
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
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 < bnz ; p++)
{
if (!GBB (Bb, p)) continue ;
uint32_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_uint32)
(
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 ;
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++)
{
if (!GBB (Ab, p)) continue ;
uint32_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) \
{ \
uint32_t aij = GBX (Ax, pA, false) ; \
Cx [pC] = (x - aij) ; \
}
GrB_Info GB (_bind1st_tran__minus_uint32)
(
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 \
uint32_t
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
uint32_t x = (*((const uint32_t *) x_input)) ;
#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 typecasting (in spite of the macro name)
#undef GB_CAST_OP
#define GB_CAST_OP(pC,pA) \
{ \
uint32_t aij = GBX (Ax, pA, false) ; \
Cx [pC] = (aij - y) ; \
}
GrB_Info GB (_bind2nd_tran__minus_uint32)
(
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
uint32_t y = (*((const uint32_t *) y_input)) ;
#include "GB_unop_transpose.c"
return (GrB_SUCCESS) ;
#endif
}
#endif
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.