source stringlengths 3 92 | c stringlengths 26 2.25M |
|---|---|
dropout-inl.h | /*!
* Copyright (c) 2015 by Contributors
* \file dropout-inl.h
* \brief
* \author Bing Xu
*/
#ifndef MXNET_OPERATOR_DROPOUT_INL_H_
#define MXNET_OPERATOR_DROPOUT_INL_H_
#include <dmlc/logging.h>
#include <dmlc/parameter.h>
#include <mxnet/operator.h>
#include <map>
#include <vector>
#include <string>
#include <utility>
#include <algorithm>
#include "./operator_common.h"
#include "./mshadow_op.h"
#if defined(USE_MKL) && defined(_OPENMP)
#include <omp.h>
#include <mkl_vml_functions.h>
#include <mkl_vsl.h>
#endif // USE_MKL && _OPENMP
namespace dropout {
enum DropoutOpInputs {kData};
enum DropoutOpOutputs {kOut, kMask};
enum DropoutOpForwardResource {kRandom};
} // namespace dropout
namespace mxnet {
namespace op {
#if defined(USE_MKL) && defined(_OPENMP)
static void bernoulli_generate(int n, double p, int* r) {
int seed = 17 + rand() % 4096; // NOLINT(runtime/threadsafe_fn)
int nthr = omp_get_max_threads();
# pragma omp parallel num_threads(nthr)
{
const int ithr = omp_get_thread_num();
const int avg_amount = (n + nthr - 1) / nthr;
const int my_offset = ithr * avg_amount;
const int my_amount = std::min(my_offset + avg_amount, n) - my_offset;
if (my_amount > 0) {
VSLStreamStatePtr stream;
vslNewStream(&stream, VSL_BRNG_MCG31, seed);
vslSkipAheadStream(stream, my_offset);
viRngBernoulli(VSL_RNG_METHOD_BERNOULLI_ICDF, stream, my_amount,
r + my_offset, p);
vslDeleteStream(&stream);
}
}
}
#endif // USE_MKL && _OPENMP
struct DropoutParam : public dmlc::Parameter<DropoutParam> {
float p;
DMLC_DECLARE_PARAMETER(DropoutParam) {
DMLC_DECLARE_FIELD(p).set_default(0.5)
.set_range(0, 1)
.describe("Fraction of the input that gets dropped out during training time.");
}
}; // struct DropoutParam
template<typename xpu, typename DType>
class DropoutOp : public Operator {
public:
explicit DropoutOp(DropoutParam param) {
this->pkeep_ = 1.0f - param.p;
}
virtual void Forward(const OpContext &ctx,
const std::vector<TBlob> &in_data,
const std::vector<OpReqType> &req,
const std::vector<TBlob> &out_data,
const std::vector<TBlob> &aux_states) {
using namespace mshadow;
using namespace mshadow::expr;
CHECK_EQ(in_data.size(), 1U);
if (ctx.is_train) {
CHECK_EQ(out_data.size(), 2U);
}
Stream<xpu> *s = ctx.get_stream<xpu>();
Tensor<xpu, 2, DType> data = in_data[dropout::kData].FlatTo2D<xpu, DType>(s);
Tensor<xpu, 2, DType> out = out_data[dropout::kOut].FlatTo2D<xpu, DType>(s);
if (ctx.is_train) {
Tensor<xpu, 2, DType> mask = out_data[dropout::kMask].FlatTo2D<xpu, DType>(s);
#if !defined(__CUDACC__) && defined(USE_MKL) && defined(_OPENMP)
DType* outptr = out.dptr_;
DType* dataptr = data.dptr_;
int* maskptr = reinterpret_cast<int*>(mask.dptr_);
int count = mask.shape_[0]*mask.shape_[1];
bernoulli_generate(count, this->pkeep_, maskptr);
#pragma omp parallel for
for (int i = 0; i < count; ++i) {
outptr[i] = dataptr[i] * maskptr[i];
}
#else
Random<xpu> *prnd = ctx.requested[dropout::kRandom].get_random<xpu, real_t>(s);
mask = tcast<DType>(F<mshadow_op::threshold>(
prnd->uniform(mask.shape_), pkeep_) * (1.0f / pkeep_));
Assign(out, req[dropout::kOut], data * mask);
#endif // USE_MKL && _OPENMP
} else {
Assign(out, req[dropout::kOut], F<mshadow_op::identity>(data));
}
}
virtual void Backward(const OpContext &ctx,
const std::vector<TBlob> &out_grad,
const std::vector<TBlob> &in_data,
const std::vector<TBlob> &out_data,
const std::vector<OpReqType> &req,
const std::vector<TBlob> &in_grad,
const std::vector<TBlob> &aux_states) {
using namespace mshadow;
using namespace mshadow::expr;
CHECK_EQ(out_grad.size(), 1U);
CHECK_EQ(in_grad.size(), 1U);
Stream<xpu> *s = ctx.get_stream<xpu>();
Tensor<xpu, 2, DType> grad = out_grad[dropout::kOut].FlatTo2D<xpu, DType>(s);
Tensor<xpu, 2, DType> mask = out_data[dropout::kMask].FlatTo2D<xpu, DType>(s);
Tensor<xpu, 2, DType> gdata = in_grad[dropout::kData].FlatTo2D<xpu, DType>(s);
#if !defined(__CUDACC__) && defined(USE_MKL) && defined(_OPENMP)
DType* ingradptr = gdata.dptr_;
DType* outgradptr = grad.dptr_;
int* maskptr = reinterpret_cast<int*>(mask.dptr_);
int count = mask.shape_[0]*mask.shape_[1];
#pragma omp parallel for
for (int i = 0; i < count; ++i) {
ingradptr[i] = outgradptr[i] * maskptr[i];
}
#else // USE_MKL && _OPENMP
Assign(gdata, req[dropout::kData], grad * mask);
#endif // USE_MKL && _OPENMP
}
private:
real_t pkeep_;
}; // class DropoutOp
template<typename xpu>
Operator *CreateOp(DropoutParam param, int dtype);
#if DMLC_USE_CXX11
class DropoutProp : public OperatorProperty {
public:
void Init(const std::vector<std::pair<std::string, std::string> >& kwargs) override {
param_.Init(kwargs);
}
std::map<std::string, std::string> GetParams() const override {
return param_.__DICT__();
}
bool InferShape(std::vector<TShape> *in_shape,
std::vector<TShape> *out_shape,
std::vector<TShape> *aux_shape) const override {
using namespace mshadow;
CHECK_EQ(in_shape->size(), 1U);
const TShape &dshape = in_shape->at(0);
if (dshape.ndim() == 0) return false;
out_shape->clear();
out_shape->push_back(dshape);
out_shape->push_back(dshape);
return true;
}
bool InferType(std::vector<int> *in_type,
std::vector<int> *out_type,
std::vector<int> *aux_type) const override {
CHECK_EQ(in_type->size(), 1U);
int dtype = in_type->at(0);
if (dtype == -1) {
LOG(FATAL) << "input type to dropout is not specified.";
return false;
}
size_t nout = this->ListOutputs().size();
out_type->clear();
for (size_t i = 0; i < nout; ++i) out_type->push_back(dtype);
return true;
}
OperatorProperty* Copy() const override {
auto ptr = new DropoutProp();
ptr->param_ = param_;
return ptr;
}
std::string TypeString() const override {
return "Dropout";
}
std::vector<int> DeclareBackwardDependency(
const std::vector<int> &out_grad,
const std::vector<int> &in_data,
const std::vector<int> &out_data) const override {
return {out_grad[dropout::kOut], out_data[dropout::kMask]};
}
std::vector<std::pair<int, void*> > BackwardInplaceOption(
const std::vector<int> &out_grad,
const std::vector<int> &in_data,
const std::vector<int> &out_data,
const std::vector<void*> &in_grad) const override {
return {{out_grad[dropout::kOut], in_grad[dropout::kData]}};
}
std::vector<std::pair<int, void*> > ForwardInplaceOption(
const std::vector<int> &in_data,
const std::vector<void*> &out_data) const override {
return {{in_data[dropout::kData], out_data[dropout::kOut]}};
}
std::vector<ResourceRequest> ForwardResource(
const std::vector<TShape> &in_shape) const override {
return {ResourceRequest::kRandom};
}
int NumVisibleOutputs() const override {
return 1;
}
int NumOutputs() const override {
return 2;
}
std::vector<std::string> ListOutputs() const override {
return {"output", "mask"};
}
Operator* CreateOperator(Context ctx) const override {
LOG(FATAL) << "Not Implemented";
return NULL;
}
Operator* CreateOperatorEx(Context ctx, std::vector<TShape> *in_shape,
std::vector<int> *in_type) const override;
private:
DropoutParam param_;
}; // class DropoutProp
#endif // DMLC_USE_CXX11
} // namespace op
} // namespace mxnet
#endif // MXNET_OPERATOR_DROPOUT_INL_H_
|
simde-diagnostic.h | /* SPDX-License-Identifier: MIT
*
* Permission is hereby granted, free of charge, to any person
* obtaining a copy of this software and associated documentation
* files (the "Software"), to deal in the Software without
* restriction, including without limitation the rights to use, copy,
* modify, merge, publish, distribute, sublicense, and/or sell copies
* of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
* BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
* ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*
* Copyright:
* 2017-2020 Evan Nemerson <evan@nemerson.com>
*/
/* SIMDe targets a very wide range of standards and compilers, and our
* goal is to compile cleanly even with extremely aggressive warnings
* (i.e., -Weverything in clang, -Wextra in GCC, /W4 for MSVC, etc.)
* treated as errors.
*
* While our preference is to resolve the underlying issue a given
* diagnostic is warning us about, sometimes that's not possible.
* Fixing a warning in one compiler may cause problems in another.
* Sometimes a warning doesn't really apply to us (false positives),
* and sometimes adhering to a warning would mean dropping a feature
* we *know* the compiler supports since we have tested specifically
* for the compiler or feature.
*
* When practical, warnings are only disabled for specific code. For
* a list of warnings which are enabled by default in all SIMDe code,
* see SIMDE_DISABLE_UNWANTED_DIAGNOSTICS. Note that we restore the
* warning stack when SIMDe is done parsing, so code which includes
* SIMDe is not deprived of these warnings.
*/
#if !defined(SIMDE_DIAGNOSTIC_H)
#include "hedley.h"
/* This is only to help us implement functions like _mm_undefined_ps. */
#if defined(SIMDE_DIAGNOSTIC_DISABLE_UNINITIALIZED_)
#undef SIMDE_DIAGNOSTIC_DISABLE_UNINITIALIZED_
#endif
#if HEDLEY_HAS_WARNING("-Wuninitialized")
#define SIMDE_DIAGNOSTIC_DISABLE_UNINITIALIZED_ _Pragma("clang diagnostic ignored \"-Wuninitialized\"")
#elif HEDLEY_GCC_VERSION_CHECK(4,2,0)
#define SIMDE_DIAGNOSTIC_DISABLE_UNINITIALIZED_ _Pragma("GCC diagnostic ignored \"-Wuninitialized\"")
#elif HEDLEY_PGI_VERSION_CHECK(19,10,0)
#define SIMDE_DIAGNOSTIC_DISABLE_UNINITIALIZED_ _Pragma("diag_suppress 549")
#elif HEDLEY_SUNPRO_VERSION_CHECK(5,14,0) && defined(__cplusplus)
#define SIMDE_DIAGNOSTIC_DISABLE_UNINITIALIZED_ _Pragma("error_messages(off,SEC_UNINITIALIZED_MEM_READ,SEC_UNDEFINED_RETURN_VALUE,unassigned)")
#elif HEDLEY_SUNPRO_VERSION_CHECK(5,14,0)
#define SIMDE_DIAGNOSTIC_DISABLE_UNINITIALIZED_ _Pragma("error_messages(off,SEC_UNINITIALIZED_MEM_READ,SEC_UNDEFINED_RETURN_VALUE)")
#elif HEDLEY_SUNPRO_VERSION_CHECK(5,12,0) && defined(__cplusplus)
#define SIMDE_DIAGNOSTIC_DISABLE_UNINITIALIZED_ _Pragma("error_messages(off,unassigned)")
#elif \
HEDLEY_TI_VERSION_CHECK(16,9,9) || \
HEDLEY_TI_CL6X_VERSION_CHECK(8,0,0) || \
HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \
HEDLEY_TI_CLPRU_VERSION_CHECK(2,3,2)
#define SIMDE_DIAGNOSTIC_DISABLE_UNINITIALIZED_ _Pragma("diag_suppress 551")
#elif HEDLEY_INTEL_VERSION_CHECK(13,0,0)
#define SIMDE_DIAGNOSTIC_DISABLE_UNINITIALIZED_ _Pragma("warning(disable:592)")
#elif HEDLEY_MSVC_VERSION_CHECK(19,0,0) && !defined(__MSVC_RUNTIME_CHECKS)
#define SIMDE_DIAGNOSTIC_DISABLE_UNINITIALIZED_ __pragma(warning(disable:4700))
#endif
/* GCC emits a lot of "notes" about the ABI being different for things
* in newer versions of GCC. We don't really care because all our
* functions are inlined and don't generate ABI. */
#if HEDLEY_GCC_VERSION_CHECK(7,0,0)
#define SIMDE_DIAGNOSTIC_DISABLE_PSABI_ _Pragma("GCC diagnostic ignored \"-Wpsabi\"")
#else
#define SIMDE_DIAGNOSTIC_DISABLE_PSABI_
#endif
/* Since MMX uses x87 FP registers, you're supposed to call _mm_empty()
* after each MMX function before any floating point instructions.
* Some compilers warn about functions which use MMX functions but
* don't call _mm_empty(). However, since SIMDe is implementyng the
* MMX API we shouldn't be calling _mm_empty(); we leave it to the
* caller to invoke simde_mm_empty(). */
#if HEDLEY_INTEL_VERSION_CHECK(19,0,0)
#define SIMDE_DIAGNOSTIC_DISABLE_NO_EMMS_INSTRUCTION_ _Pragma("warning(disable:13200 13203)")
#elif defined(HEDLEY_MSVC_VERSION)
#define SIMDE_DIAGNOSTIC_DISABLE_NO_EMMS_INSTRUCTION_ __pragma(warning(disable:4799))
#else
#define SIMDE_DIAGNOSTIC_DISABLE_NO_EMMS_INSTRUCTION_
#endif
/* Intel is pushing people to use OpenMP SIMD instead of Cilk+, so they
* emit a diagnostic if you use #pragma simd instead of
* #pragma omp simd. SIMDe supports OpenMP SIMD, you just need to
* compile with -qopenmp or -qopenmp-simd and define
* SIMDE_ENABLE_OPENMP. Cilk+ is just a fallback. */
#if HEDLEY_INTEL_VERSION_CHECK(18,0,0)
#define SIMDE_DIAGNOSTIC_DISABLE_SIMD_PRAGMA_DEPRECATED_ _Pragma("warning(disable:3948)")
#else
#define SIMDE_DIAGNOSTIC_DISABLE_SIMD_PRAGMA_DEPRECATED_
#endif
#if \
defined(HEDLEY_MSVC_VERSION)
#define SIMDE_DIAGNOSTIC_DISABLE_NON_CONSTANT_AGGREGATE_INITIALIZER_ __pragma(warning(disable:4204))
#else
#define SIMDE_DIAGNOSTIC_DISABLE_NON_CONSTANT_AGGREGATE_INITIALIZER_
#endif
/* This warning needs a lot of work. It is triggered if all you do is
* pass the value to memcpy/__builtin_memcpy, or if you initialize a
* member of the union, even if that member takes up the entire union.
* Last tested with clang-10, hopefully things will improve in the
* future; if clang fixes this I'd love to enable it. */
#if \
HEDLEY_HAS_WARNING("-Wconditional-uninitialized")
#define SIMDE_DIAGNOSTIC_DISABLE_CONDITIONAL_UNINITIALIZED_ _Pragma("clang diagnostic ignored \"-Wconditional-uninitialized\"")
#else
#define SIMDE_DIAGNOSTIC_DISABLE_CONDITIONAL_UNINITIALIZED_
#endif
/* This warning is meant to catch things like `0.3 + 0.4 == 0.7`, which
* will is false. However, SIMDe uses these operations exclusively
* for things like _mm_cmpeq_ps, for which we really do want to check
* for equality (or inequality).
*
* If someone wants to put together a SIMDE_FLOAT_EQUAL(a, op, b) macro
* which just wraps a check in some code do disable this diagnostic I'd
* be happy to accept it. */
#if \
HEDLEY_HAS_WARNING("-Wfloat-equal") || \
HEDLEY_GCC_VERSION_CHECK(3,0,0)
#define SIMDE_DIAGNOSTIC_DISABLE_FLOAT_EQUAL_ _Pragma("GCC diagnostic ignored \"-Wfloat-equal\"")
#else
#define SIMDE_DIAGNOSTIC_DISABLE_FLOAT_EQUAL_
#endif
/* This is because we use HEDLEY_STATIC_ASSERT for static assertions.
* If Hedley can't find an implementation it will preprocess to
* nothing, which means there will be a trailing semi-colon. */
#if HEDLEY_HAS_WARNING("-Wextra-semi")
#define SIMDE_DIAGNOSTIC_DISABLE_EXTRA_SEMI_ _Pragma("clang diagnostic ignored \"-Wextra-semi\"")
#elif HEDLEY_GCC_VERSION_CHECK(8,1,0) && defined(__cplusplus)
#define SIMDE_DIAGNOSTIC_DISABLE_EXTRA_SEMI_ _Pragma("GCC diagnostic ignored \"-Wextra-semi\"")
#else
#define SIMDE_DIAGNOSTIC_DISABLE_EXTRA_SEMI_
#endif
/* We do use a few variadic macros, which technically aren't available
* until C99 and C++11, but every compiler I'm aware of has supported
* them for much longer. That said, usage is isolated to the test
* suite and compilers known to support them. */
#if HEDLEY_HAS_WARNING("-Wvariadic-macros") || HEDLEY_GCC_VERSION_CHECK(4,0,0)
#if HEDLEY_HAS_WARNING("-Wc++98-compat-pedantic")
#define SIMDE_DIAGNOSTIC_DISABLE_VARIADIC_MACROS_ \
_Pragma("clang diagnostic ignored \"-Wvariadic-macros\"") \
_Pragma("clang diagnostic ignored \"-Wc++98-compat-pedantic\"")
#else
#define SIMDE_DIAGNOSTIC_DISABLE_VARIADIC_MACROS_ _Pragma("GCC diagnostic ignored \"-Wvariadic-macros\"")
#endif
#else
#define SIMDE_DIAGNOSTIC_DISABLE_VARIADIC_MACROS_
#endif
/* Triggered when assigning a float to a double implicitly. We use
* explicit casts in SIMDe, this is only used in the test suite. */
#if HEDLEY_HAS_WARNING("-Wdouble-promotion")
#define SIMDE_DIAGNOSTIC_DISABLE_DOUBLE_PROMOTION_ _Pragma("clang diagnostic ignored \"-Wdouble-promotion\"")
#else
#define SIMDE_DIAGNOSTIC_DISABLE_DOUBLE_PROMOTION_
#endif
/* Several compilers treat conformant array parameters as VLAs. We
* test to make sure we're in C mode (C++ doesn't support CAPs), and
* that the version of the standard supports CAPs. We also blacklist
* some buggy compilers like MSVC (the logic is in Hedley if you want
* to take a look), but with certain warnings enabled some compilers
* still like to emit a diagnostic. */
#if HEDLEY_HAS_WARNING("-Wvla")
#define SIMDE_DIAGNOSTIC_DISABLE_VLA_ _Pragma("clang diagnostic ignored \"-Wvla\"")
#elif HEDLEY_GCC_VERSION_CHECK(4,3,0)
#define SIMDE_DIAGNOSTIC_DISABLE_VLA_ _Pragma("GCC diagnostic ignored \"-Wvla\"")
#else
#define SIMDE_DIAGNOSTIC_DISABLE_VLA_
#endif
#if HEDLEY_HAS_WARNING("-Wused-but-marked-unused")
#define SIMDE_DIAGNOSTIC_DISABLE_USED_BUT_MARKED_UNUSED_ _Pragma("clang diagnostic ignored \"-Wused-but-marked-unused\"")
#else
#define SIMDE_DIAGNOSTIC_DISABLE_USED_BUT_MARKED_UNUSED_
#endif
#if HEDLEY_HAS_WARNING("-Wunused-function")
#define SIMDE_DIAGNOSTIC_DISABLE_UNUSED_FUNCTION_ _Pragma("clang diagnostic ignored \"-Wunused-function\"")
#elif HEDLEY_GCC_VERSION_CHECK(3,4,0)
#define SIMDE_DIAGNOSTIC_DISABLE_UNUSED_FUNCTION_ _Pragma("GCC diagnostic ignored \"-Wunused-function\"")
#else
#define SIMDE_DIAGNOSTIC_DISABLE_UNUSED_FUNCTION_
#endif
#if HEDLEY_HAS_WARNING("-Wpass-failed")
#define SIMDE_DIAGNOSTIC_DISABLE_PASS_FAILED_ _Pragma("clang diagnostic ignored \"-Wpass-failed\"")
#else
#define SIMDE_DIAGNOSTIC_DISABLE_PASS_FAILED_
#endif
/* https://github.com/nemequ/simde/issues/277 */
#if defined(HEDLEY_GCC_VERSION) && HEDLEY_GCC_VERSION_CHECK(4,6,0) && !HEDLEY_GCC_VERSION_CHECK(6,0,0) && defined(__cplusplus)
#define SIMDE_DIAGNOSTIC_DISABLE_BUGGY_UNUSED_BUT_SET_VARIBALE _Pragma("GCC diagnostic ignored \"-Wunused-but-set-variable\"")
#else
#define SIMDE_DIAGNOSTIC_DISABLE_BUGGY_UNUSED_BUT_SET_VARIBALE
#endif
/* Some compilers, such as clang, may use `long long` for 64-bit
* integers, but `long long` triggers a diagnostic with
* -Wc++98-compat-pedantic which says 'long long' is incompatible with
* C++98. */
#if HEDLEY_HAS_WARNING("-Wc++98-compat-pedantic")
#define SIMDE_DIAGNOSTIC_DISABLE_CPP98_COMPAT_PEDANTIC _Pragma("clang diagnostic ignored \"-Wc++98-compat-pedantic\"")
#else
#define SIMDE_DIAGNOSTIC_DISABLE_CPP98_COMPAT_PEDANTIC
#endif
#define SIMDE_DISABLE_UNWANTED_DIAGNOSTICS \
SIMDE_DIAGNOSTIC_DISABLE_PSABI_ \
SIMDE_DIAGNOSTIC_DISABLE_NO_EMMS_INSTRUCTION_ \
SIMDE_DIAGNOSTIC_DISABLE_SIMD_PRAGMA_DEPRECATED_ \
SIMDE_DIAGNOSTIC_DISABLE_CONDITIONAL_UNINITIALIZED_ \
SIMDE_DIAGNOSTIC_DISABLE_FLOAT_EQUAL_ \
SIMDE_DIAGNOSTIC_DISABLE_NON_CONSTANT_AGGREGATE_INITIALIZER_ \
SIMDE_DIAGNOSTIC_DISABLE_EXTRA_SEMI_ \
SIMDE_DIAGNOSTIC_DISABLE_VLA_ \
SIMDE_DIAGNOSTIC_DISABLE_USED_BUT_MARKED_UNUSED_ \
SIMDE_DIAGNOSTIC_DISABLE_UNUSED_FUNCTION_ \
SIMDE_DIAGNOSTIC_DISABLE_PASS_FAILED_ \
SIMDE_DIAGNOSTIC_DISABLE_CPP98_COMPAT_PEDANTIC \
SIMDE_DIAGNOSTIC_DISABLE_BUGGY_UNUSED_BUT_SET_VARIBALE
#endif
|
GB_unop__identity_int64_int64.c | //------------------------------------------------------------------------------
// GB_unop: hard-coded functions for each built-in unary operator
//------------------------------------------------------------------------------
// SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2022, All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
//------------------------------------------------------------------------------
// If this file is in the Generated2/ folder, do not edit it
// (it is auto-generated from Generator/*).
#include "GB.h"
#ifndef GBCOMPACT
#include "GB_control.h"
#include "GB_atomics.h"
#include "GB_unop__include.h"
// C=unop(A) is defined by the following types and operators:
// op(A) function: GB (_unop_apply__(none))
// op(A') function: GB (_unop_tran__identity_int64_int64)
// C type: int64_t
// A type: int64_t
// cast: int64_t cij = aij
// unaryop: cij = aij
#define GB_ATYPE \
int64_t
#define GB_CTYPE \
int64_t
// aij = Ax [pA]
#define GB_GETA(aij,Ax,pA) \
int64_t aij = Ax [pA]
#define GB_CX(p) Cx [p]
// unary operator
#define GB_OP(z, x) \
z = x ;
// casting
#define GB_CAST(z, aij) \
int64_t z = aij ;
// cij = op (aij)
#define GB_CAST_OP(pC,pA) \
{ \
/* aij = Ax [pA] */ \
int64_t aij = Ax [pA] ; \
/* Cx [pC] = op (cast (aij)) */ \
int64_t z = aij ; \
Cx [pC] = z ; \
}
// disable this operator and use the generic case if these conditions hold
#define GB_DISABLE \
(GxB_NO_IDENTITY || GxB_NO_INT64)
//------------------------------------------------------------------------------
// Cx = op (cast (Ax)): apply a unary operator
//------------------------------------------------------------------------------
#if 0
GrB_Info GB (_unop_apply__(none))
(
int64_t *Cx, // Cx and Ax may be aliased
const int64_t *Ax,
const int8_t *restrict Ab, // A->b if A is bitmap
int64_t anz,
int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
int64_t p ;
if (Ab == NULL)
{
#pragma omp parallel for num_threads(nthreads) schedule(static)
for (p = 0 ; p < anz ; p++)
{
int64_t aij = Ax [p] ;
int64_t z = aij ;
Cx [p] = z ;
}
}
else
{
// bitmap case, no transpose; A->b already memcpy'd into C->b
#pragma omp parallel for num_threads(nthreads) schedule(static)
for (p = 0 ; p < anz ; p++)
{
if (!Ab [p]) continue ;
int64_t aij = Ax [p] ;
int64_t z = aij ;
Cx [p] = z ;
}
}
return (GrB_SUCCESS) ;
#endif
}
#endif
//------------------------------------------------------------------------------
// C = op (cast (A')): transpose, typecast, and apply a unary operator
//------------------------------------------------------------------------------
GrB_Info GB (_unop_tran__identity_int64_int64)
(
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
|
RNAdos.c | /*
* Compute the density of states
*
* c Gregor Entzian, Ronny Lorenz
* Vienna RNA package
*/
#include <stdlib.h>
#include "ViennaRNA/utils/basic.h"
#include "ViennaRNA/utils/structures.h"
#include "ViennaRNA/params/io.h"
#include "ViennaRNA/datastructures/basic.h"
#include "ViennaRNA/fold_vars.h"
#include "ViennaRNA/params/basic.h"
#include "ViennaRNA/loops/all.h"
#include "ViennaRNA/alphabet.h"
#include "ViennaRNA/mfe.h"
#include "ViennaRNA/file_utils.h"
#include "ViennaRNA/io/file_formats.h"
#include "ViennaRNA/datastructures/hash_tables.h"
#ifdef _OPENMP
#include <omp.h>
#endif
#include "RNAdos_cmdl.h"
typedef struct key_value_ {
int key;
int value;
} key_value;
static unsigned
hash_function_dos(void *hash_entry,
unsigned long hashtable_size)
{
key_value *hem = ((key_value *)hash_entry);
unsigned long c = (unsigned long)hem->key;
return c % hashtable_size;
}
/***
* 0 is equal, 1 is different!
*/
static int
hash_comparison_dos(void *x,
void *y)
{
key_value *hem_x = ((key_value *)x);
key_value *hem_y = ((key_value *)y);
if ((x == NULL) ^ (y == NULL))
return 1;
return !(hem_x->key == hem_y->key);
}
static int
free_hash_entry_dos(void *hash_entry)
{
/*
* if (hash_entry != NULL) {
* key_value *hem_x = ((key_value *) hash_entry);
* free (hem_x);
* }
*/
return 0;
}
static vrna_hash_table_t
create_hashtable(int hashbits)
{
vrna_callback_ht_free_entry *my_free = free_hash_entry_dos;
vrna_callback_ht_compare_entries *my_comparison = hash_comparison_dos;
vrna_callback_ht_hash_function *my_hash_function = hash_function_dos;
vrna_hash_table_t ht = vrna_ht_init(hashbits,
my_comparison,
my_hash_function,
my_free);
return ht;
}
typedef struct energy_count_ {
int energy;
double count;
} energy_count;
typedef struct hashtable_list_ {
unsigned long length;
unsigned long allocated_size;
energy_count *list_energy_count_pairs;
key_value **list_key_value_pairs;
vrna_hash_table_t ht_energy_index; // lookup table;
} hashtable_list;
struct dp_counts_per_energy {
hashtable_list *n_ij_e;
hashtable_list *n_ij_A_e;
hashtable_list *n_ij_M_e;
hashtable_list *n_ij_M1_e;
};
static hashtable_list
create_hashtable_list(int hashbits)
{
hashtable_list ht_list;
ht_list.allocated_size = 10;
ht_list.length = 0;
ht_list.list_energy_count_pairs = vrna_alloc(sizeof(energy_count) * ht_list.allocated_size);
ht_list.list_key_value_pairs = vrna_alloc(sizeof(key_value *) * ht_list.allocated_size);
ht_list.ht_energy_index = create_hashtable(hashbits);
return ht_list;
}
static
void
free_hashtable_list(hashtable_list *ht_list)
{
vrna_ht_free(ht_list->ht_energy_index);
free(ht_list->list_energy_count_pairs);
int i = 0;
for (; i < ht_list->length; i++)
free(ht_list->list_key_value_pairs[i]);
free(ht_list->list_key_value_pairs);
}
static
void
hashtable_list_add_count(hashtable_list *htl,
int energy,
double count)
{
if (htl->ht_energy_index != NULL) {
key_value to_check;
to_check.key = energy;
//to_check.value = count;
key_value *lookup_result = NULL;
lookup_result = vrna_ht_get(htl->ht_energy_index, (void *)&to_check);
if (lookup_result == NULL) {
//value is not in list.
if (htl->length >= htl->allocated_size) {
htl->allocated_size += 10;
htl->list_energy_count_pairs =
vrna_realloc(htl->list_energy_count_pairs, sizeof(energy_count) * htl->allocated_size);
htl->list_key_value_pairs = vrna_realloc(htl->list_key_value_pairs,
sizeof(key_value *) * htl->allocated_size);
}
energy_count ec;
ec.count = count;
ec.energy = energy;
int list_index = htl->length;
htl->list_energy_count_pairs[list_index] = ec;
to_check.value = list_index;
key_value *to_store = vrna_alloc(sizeof(key_value));
*to_store = to_check;
htl->list_key_value_pairs[list_index] = to_store;
htl->length++;
key_value *to_insert = htl->list_key_value_pairs[list_index];
int res = vrna_ht_insert(htl->ht_energy_index, (void *)to_insert);
if (res != 0)
fprintf(stderr, "dos.c: hash table insert failed!");
} else {
// the energy-index pair is already in the list.
int list_index = lookup_result->value;
htl->list_energy_count_pairs[list_index].count += count;
}
}
}
static
double
lookup_count_from_energy(hashtable_list *htl,
int energy)
{
key_value to_check;
to_check.key = energy;
key_value *lookup_result;
lookup_result = vrna_ht_get(htl->ht_energy_index, (void *)&to_check);
if (lookup_result == NULL) {
//value is not in list.
return 0;
} else {
int index = lookup_result->value;
return htl->list_energy_count_pairs[index].count;
}
}
static
double
lookup_count_from_index(hashtable_list *htl,
int index)
{
if (index < 0)
return 0;
return htl->list_energy_count_pairs[index].count;
}
int
lookup_energy_from_index(hashtable_list *htl,
int index)
{
if (index < 0)
return 1000000;
return htl->list_energy_count_pairs[index].energy;
}
PRIVATE INLINE int
decompose_pair(vrna_fold_compound_t *fc,
int i,
int j,
int min_energy,
int max_e,
struct dp_counts_per_energy *dp_count_matrix_pt)
{
hashtable_list *source_table;
hashtable_list *source_table_2;
hashtable_list *result_table;
int turn = fc->params->model_details.min_loop_size;
int ij = fc->jindx[j] + i;
int *rtype = &(fc->params->model_details.rtype[0]);
short *S1 = fc->sequence_encoding;
int type = fc->ptype[fc->jindx[j] + i];
int no_close =
(((type == 3) || (type == 4)) && fc->params->model_details.noGUclosure);
/* do we evaluate this pair? */
if (type) {
/* check for hairpin loop */
int energy_hp = E_Hairpin(j - i - 1,
type,
S1[i + 1],
S1[j - 1],
fc->sequence + i - 1,
fc->params);
if (energy_hp <= max_e) {
result_table = &dp_count_matrix_pt->n_ij_e[ij];
hashtable_list_add_count(result_table, energy_hp, 1);
}
/* check for interior loops */
int maxp = MIN2(j - 2 - turn, i + MAXLOOP + 1);
int p, q, type_2, pq;
int energy;
for (p = i + 1; p <= maxp; p++) {
unsigned int minq = p + turn + 1;
for (q = minq; q < j; q++) {
pq = fc->jindx[q] + p;
/* set distance to reference structure... */
type_2 = fc->ptype[fc->jindx[q] + p];
if (type_2 == 0)
continue;
type_2 = rtype[type_2];
if (no_closingGU)
if (no_close || (type_2 == 3) || (type_2 == 4))
if ((p > i + 1) || (q < j - 1))
continue;
/* continue unless stack */
energy = E_IntLoop(p - i - 1,
j - q - 1,
type,
type_2,
S1[i + 1],
S1[j - 1],
S1[p - 1],
S1[q + 1],
fc->params);
source_table = &dp_count_matrix_pt->n_ij_e[pq];
if (source_table->length > 0) {
result_table = &dp_count_matrix_pt->n_ij_e[ij];
for (int ei = 0; ei < source_table->length; ei++) {
int pq_energy = lookup_energy_from_index(source_table, ei);
double pq_count = lookup_count_from_index(source_table, ei);
int sum_energy = pq_energy + energy;
if ((sum_energy >= min_energy) && (sum_energy <= max_e))
hashtable_list_add_count(result_table, sum_energy, pq_count);
}
}
} /* end q-loop */
} /* end p-loop */
//new_c = MIN2(new_c, min_int);
/* check for multibranch loops */
if (!no_close) {
/* dangle energies for multiloop closing stem */
int tt = rtype[type];
int temp2 = fc->params->MLclosing;
if (dangles == 2)
temp2 += E_MLstem(tt, S1[j - 1], S1[i + 1], fc->params);
else
temp2 += E_MLstem(tt, -1, -1, fc->params);
int u;
for (u = i + turn + 2; u < j - turn - 2; u++) {
int i1u = fc->jindx[u] + (i + 1);
int u1j1 = fc->jindx[j - 1] + (u + 1);
source_table = &dp_count_matrix_pt->n_ij_M_e[i1u];
source_table_2 = &dp_count_matrix_pt->n_ij_M1_e[u1j1];
if (source_table->length > 0 && source_table_2->length > 0) {
result_table = &dp_count_matrix_pt->n_ij_e[ij];
for (int ei_1 = 0; ei_1 < source_table->length; ei_1++) {
int m_energy = lookup_energy_from_index(source_table, ei_1);
double m_count = lookup_count_from_index(source_table, ei_1);
for (int ei_2 = 0; ei_2 < source_table_2->length; ei_2++) {
int m1_energy = lookup_energy_from_index(source_table_2, ei_2);
double m1_count = lookup_count_from_index(source_table_2, ei_2);
int sum_energy = m_energy + m1_energy + temp2;
if ((sum_energy >= min_energy) && (sum_energy <= max_e)) {
double c_count = m_count * m1_count;
hashtable_list_add_count(result_table, sum_energy, c_count);
}
}
}
}
}
}
} /* end >> if (pair) << */
return 0;
}
int
print_array_energy_counts(hashtable_list *matrix,
int length_col,
int min_energy,
int max_energy)
{
int j = length_col;
if (matrix[j].length > 0) {
for (int e = min_energy; e <= max_energy; e++) {
double count = lookup_count_from_energy(&matrix[j], e);
if (count > 0)
printf("%6.2f\t%10.4g\n", e / 100., count);
}
}
printf("\n");
return 0;
}
/* fill DP matrices */
PRIVATE void
compute_density_of_states(vrna_fold_compound_t *fc,
int max_energy_input,
int hashbits,
int verbose)
{
int i, j, ij, length, turn, *indx;
vrna_param_t *P;
length = (int)fc->length;
indx = fc->jindx;
P = fc->params;
turn = P->model_details.min_loop_size;
int dangles = P->model_details.dangles;
short *S1 = fc->sequence_encoding;
hashtable_list *source_table;
hashtable_list *source_table_2;
hashtable_list *result_table;
hashtable_list *n_ij_e =
(hashtable_list *)vrna_alloc(sizeof(hashtable_list) * ((length + 1) * (length + 1)));
hashtable_list *n_ij_A_e =
(hashtable_list *)vrna_alloc(sizeof(hashtable_list) * (length + 1));
hashtable_list *n_ij_M_e =
(hashtable_list *)vrna_alloc(sizeof(hashtable_list) * ((length + 1) * (length + 1)));
hashtable_list *n_ij_M1_e =
(hashtable_list *)vrna_alloc(sizeof(hashtable_list) * ((length + 1) * (length + 1)));
struct dp_counts_per_energy count_matrix_pt;
count_matrix_pt.n_ij_e = n_ij_e;
count_matrix_pt.n_ij_A_e = n_ij_A_e;
count_matrix_pt.n_ij_M_e = n_ij_M_e;
count_matrix_pt.n_ij_M1_e = n_ij_M1_e;
/* compute mfe and search the matrices for the minimal energy contribution */
int min_energy = (int)round(vrna_mfe(fc, NULL) * 100.0);
if (verbose)
printf("min_energy (global): %d \n", min_energy);
/* search through DP matrices for minimal entry */
for (int i = 1; i < length; i++)
for (int j = i + 1; j <= length; j++) {
ij = indx[j] + i;
int e = fc->matrices->c[ij];
if (e < min_energy)
min_energy = e;
e = fc->matrices->fML[ij];
if (e < min_energy)
min_energy = e;
}
for (int i = 1; i <= length; i++) {
int e = fc->matrices->f5[i];
if (e < min_energy)
min_energy = e;
}
// clean mfe fold matrices (we need only counts)
vrna_mx_mfe_free(fc);
int max_energy = max_energy_input;
/* compute max_energy */
if (min_energy < 0)
/* increase internal energy threshold in order to count
* structures at the border correctly.
*/
max_energy = max_energy - 2 * min_energy;
int step_energy = 1; // 1 decakal. (smallest unit of energy computations)
int range = max_energy - min_energy;
int energy_length = range + 1; // ceil (range / (float) step_energy) + 1;
if (verbose) {
printf("min_energy: %d \n", min_energy);
printf("max_energy: %d %d\n", max_energy, min_energy + (step_energy * (energy_length - 1)));
printf("range: %d, energy_length: %d\n", range, energy_length);
}
/* start recursion */
if (length <= turn)
/* only the open chain is possible */
return;
//for (i = length - turn - 1; i >= 1; i--) {
// for (j = i + turn + 1; j <= length; j++) {
int d;
for (d = turn + 2; d <= length; d++) {
/* i,j in [1..length] */
#ifdef _OPENMP
#pragma omp parallel for private(j, i, ij, source_table, source_table_2, result_table)
#endif
for (j = d; j <= length; j++) {
i = j - d + 1;
ij = indx[j] + i;
int type = fc->ptype[fc->jindx[j] + i];
//prepare matrices (add third dimension)
count_matrix_pt.n_ij_e[ij] = create_hashtable_list(hashbits);
count_matrix_pt.n_ij_M_e[ij] = create_hashtable_list(hashbits);
count_matrix_pt.n_ij_M1_e[ij] = create_hashtable_list(hashbits);
/* decompose subsegment [i, j] with pair (i, j) */
decompose_pair(fc, i, j, min_energy, max_energy, &count_matrix_pt);
/* decompose subsegment [i, j] that is multibranch loop part with at least one branch */
int temp2 = 0;
if (dangles == 2)
temp2 += E_MLstem(type, (i == 1) ? S1[length] : S1[i - 1], S1[j + 1], P);
else
temp2 += E_MLstem(type, -1, -1, P);
/*
* now to the actual computations...
* 1st E_M[ij] = E_M1[ij] = E_C[ij] + b
*/
source_table = &count_matrix_pt.n_ij_e[ij];
if (source_table->length > 0) {
result_table = &count_matrix_pt.n_ij_M1_e[ij];
hashtable_list *result_table_2 = &count_matrix_pt.n_ij_M_e[ij];
for (int ei = 0; ei < source_table->length; ei++) {
int c_energy = lookup_energy_from_index(source_table, ei);
double c_count = lookup_count_from_index(source_table, ei);
int sum_energy = c_energy + temp2;
if ((sum_energy >= min_energy) && (sum_energy <= max_energy)) {
hashtable_list_add_count(result_table, sum_energy, c_count);
hashtable_list_add_count(result_table_2, sum_energy, c_count);
}
}
}
/* 2rd E_M[ij] = MIN(E_M[ij], E_M[i,j-1] + c) */
source_table = &count_matrix_pt.n_ij_M_e[fc->jindx[j - 1] + i];
if (source_table->length > 0) {
result_table = &count_matrix_pt.n_ij_M_e[ij];
for (int ei = 0; ei < source_table->length; ei++) {
int m_energy = lookup_energy_from_index(source_table, ei);
double m_count = lookup_count_from_index(source_table, ei);
int sum_energy = m_energy + P->MLbase;
if ((sum_energy >= min_energy) && (sum_energy <= max_energy))
hashtable_list_add_count(result_table, sum_energy, m_count);
}
}
/* 3th E_M1[ij] = MIN(E_M1[ij], E_M1[i,j-1] + c) */
source_table = &count_matrix_pt.n_ij_M1_e[fc->jindx[j - 1] + i];
if (source_table->length > 0) {
result_table = &count_matrix_pt.n_ij_M1_e[ij];
for (int ei = 0; ei < source_table->length; ei++) {
int m1_energy = lookup_energy_from_index(source_table, ei);
double m1_count = lookup_count_from_index(source_table, ei);
int sum_energy = m1_energy + P->MLbase;
if ((sum_energy >= min_energy) && (sum_energy <= max_energy))
hashtable_list_add_count(result_table, sum_energy, m1_count);
}
}
if (j > turn + 2) {
int u;
int temp3;
for (u = i; u < j; u++) {
int u1j = fc->jindx[j] + u + 1;
int iu = fc->jindx[u] + i;
source_table = &count_matrix_pt.n_ij_e[u1j];
if (source_table->length > 0) {
type = fc->ptype[u1j];
/* [i..u] is unpaired */
if (dangles == 2)
temp2 = E_MLstem(type, S1[u], S1[j + 1], P);
else
temp2 = E_MLstem(type, -1, -1, P);
temp3 = temp2 + (u - i + 1) * P->MLbase;
result_table = &count_matrix_pt.n_ij_M_e[ij];
for (int ei = 0; ei < source_table->length; ei++) {
int c_energy = lookup_energy_from_index(source_table, ei);
double c_count = lookup_count_from_index(source_table, ei);
int sum_energy = c_energy + temp3;
if ((sum_energy >= min_energy) && (sum_energy <= max_energy))
hashtable_list_add_count(result_table, sum_energy, c_count);
}
/* [i...u] has at least one stem */
source_table_2 = &count_matrix_pt.n_ij_M_e[iu];
if (source_table_2->length > 0) {
source_table = &count_matrix_pt.n_ij_e[u1j];
result_table = &count_matrix_pt.n_ij_M_e[ij];
for (int ei_1 = 0; ei_1 < source_table->length; ei_1++) {
int c_energy = lookup_energy_from_index(source_table, ei_1);
double c_count = lookup_count_from_index(source_table, ei_1);
for (int ei_2 = 0; ei_2 < source_table_2->length; ei_2++) {
int m_energy = lookup_energy_from_index(source_table_2, ei_2);
double m_count = lookup_count_from_index(source_table_2, ei_2);
int sum_energy = c_energy + m_energy + temp2;
if ((sum_energy >= min_energy) && (sum_energy <= max_energy)) {
double product_count = c_count * m_count;
hashtable_list_add_count(result_table, sum_energy, product_count);
}
}
}
}
}
}
}
} /* end of j-loop */
} /* end of i-loop */
/* calculate energies of 5' fragments */
int x;
#ifdef _OPENMP
#pragma omp parallel for private(x)
#endif
for (x = 0; x <= length; x++)
count_matrix_pt.n_ij_A_e[x] = create_hashtable_list(hashbits);
int cnt1;
#ifdef _OPENMP
#pragma omp parallel for private(cnt1)
#endif
for (cnt1 = 1; cnt1 <= turn + 1; cnt1++) {
int c_energy = 0;
double c_count = 1;
result_table = &count_matrix_pt.n_ij_A_e[cnt1];
hashtable_list_add_count(result_table, c_energy, c_count);
}
for (j = turn + 2; j <= length; j++) {
/* j-1 is unpaired ... */
source_table = &count_matrix_pt.n_ij_A_e[j - 1];
result_table = &count_matrix_pt.n_ij_A_e[j];
int ei;
for (ei = 0; ei < source_table->length; ei++) {
int c_energy = lookup_energy_from_index(source_table, ei);
double c_count = lookup_count_from_index(source_table, ei);
hashtable_list_add_count(result_table, c_energy, c_count);
}
/* j pairs with 1 */
ij = fc->jindx[j] + 1;
int type = fc->ptype[ij];
int additional_en = 0;
if (type) {
if (dangles == 2)
additional_en += E_ExtLoop(type, -1, j < length ? S1[j + 1] : -1, P);
else
additional_en += E_ExtLoop(type, -1, -1, P);
}
source_table = &count_matrix_pt.n_ij_e[ij];
if (source_table->length > 0) {
result_table = &count_matrix_pt.n_ij_A_e[j];
int ei;
for (ei = 0; ei < source_table->length; ei++) {
int c_energy = lookup_energy_from_index(source_table, ei);
double c_count = lookup_count_from_index(source_table, ei);
int sum_energy = c_energy + additional_en;
if ((sum_energy >= min_energy) && (sum_energy <= max_energy))
hashtable_list_add_count(result_table, sum_energy, c_count);
}
}
/* j pairs with some other nucleotide -> see below */
for (i = j - turn - 1; i > 1; i--) {
ij = fc->jindx[j] + i;
type = fc->ptype[ij];
if (type) {
if (dangles == 2)
additional_en = E_ExtLoop(type, S1[i - 1], j < length ? S1[j + 1] : -1, P);
else
additional_en = E_ExtLoop(type, -1, -1, P);
source_table = &count_matrix_pt.n_ij_e[ij];
source_table_2 = &count_matrix_pt.n_ij_A_e[i - 1];
if (source_table->length > 0 && source_table_2->length > 0) {
result_table = &count_matrix_pt.n_ij_A_e[j];
int ei_1;
for (ei_1 = 0; ei_1 < source_table->length; ei_1++) {
int c_energy = lookup_energy_from_index(source_table, ei_1);
double c_count = lookup_count_from_index(source_table, ei_1);
int ei_2;
for (ei_2 = 0; ei_2 < source_table_2->length; ei_2++) {
int f5_energy = lookup_energy_from_index(source_table_2, ei_2);
double f5_count = lookup_count_from_index(source_table_2, ei_2);
int sum_energy = c_energy + f5_energy + additional_en;
if ((sum_energy >= min_energy) && (sum_energy <= max_energy)) {
double product_count = c_count * f5_count;
hashtable_list_add_count(result_table, sum_energy, product_count);
}
}
}
}
}
}
}
printf("Energy bands with counted structures:\n");
print_array_energy_counts(count_matrix_pt.n_ij_A_e, length, min_energy, max_energy_input);
for (i = length - turn - 1; i >= 1; i--) {
#ifdef _OPENMP
#pragma omp parallel for private(j, ij)
#endif
for (j = i + turn + 1; j <= length; j++) {
ij = indx[j] + i;
if (count_matrix_pt.n_ij_e[ij].allocated_size > 0)
free_hashtable_list(&count_matrix_pt.n_ij_e[ij]);
if (count_matrix_pt.n_ij_M_e[ij].allocated_size > 0)
free_hashtable_list(&count_matrix_pt.n_ij_M_e[ij]);
if (count_matrix_pt.n_ij_M1_e[ij].allocated_size > 0)
free_hashtable_list(&count_matrix_pt.n_ij_M1_e[ij]);
}
}
#ifdef _OPENMP
#pragma omp parallel for private(i)
#endif
for (i = 0; i <= length; i++)
free_hashtable_list(&count_matrix_pt.n_ij_A_e[i]);
free(count_matrix_pt.n_ij_e);
free(count_matrix_pt.n_ij_A_e);
free(count_matrix_pt.n_ij_M_e);
free(count_matrix_pt.n_ij_M1_e);
}
char *
read_sequence_from_stdin()
{
char *rec_sequence, *rec_id, **rec_rest;
unsigned int rec_type;
unsigned int read_opt = 0;
rec_id = NULL;
rec_rest = NULL;
rec_type = vrna_file_fasta_read_record(&rec_id,
&rec_sequence,
&rec_rest,
stdin,
read_opt);
if (rec_type & (VRNA_INPUT_ERROR | VRNA_INPUT_QUIT))
return "";
char *result_sequence = NULL;
if (rec_type & VRNA_INPUT_SEQUENCE)
result_sequence = rec_sequence;
return result_sequence;
}
int
main(int argc,
char *argv[])
{
struct RNAdos_args_info args_info;
vrna_md_t md;
set_model_details(&md);
md.uniq_ML = 1;
md.noLP = 0;
md.circ = 0;
md.dangles = 2;
int verbose = 0;
int max_energy = 0;
int hash_bits = 20;
char *ParamFile = NULL;
/*
#############################################
# check the command line prameters
#############################################
*/
if (RNAdos_cmdline_parser(argc, argv, &args_info) != 0)
exit(1);
char *rnaSequence = NULL;
if (!args_info.sequence_given) {
rnaSequence = read_sequence_from_stdin();
if (rnaSequence == NULL) {
fprintf(stderr, "No RNA sequence given!");
exit(1);
}
} else {
rnaSequence = args_info.sequence_arg;
}
/* temperature */
if (args_info.temp_given)
md.temperature = temperature = args_info.temp_arg;
/* dangle options */
if (args_info.dangles_given) {
if ((args_info.dangles_arg != 0) && (args_info.dangles_arg != 2))
vrna_message_warning(
"required dangle model not implemented, falling back to default dangles=2");
else
md.dangles = dangles = args_info.dangles_arg;
}
if (args_info.verbose_given)
verbose = 1;
if (args_info.max_energy_given)
max_energy = args_info.max_energy_arg;
if (args_info.hashtable_bits_given)
hash_bits = args_info.hashtable_bits_arg;
/* set number of threads for parallel computation */
if (args_info.numThreads_given) {
#ifdef _OPENMP
omp_set_num_threads(args_info.numThreads_arg);
omp_set_dynamic(0);
#endif
}
/* get energy parameter file name */
if (args_info.paramFile_given)
ParamFile = strdup(args_info.paramFile_arg);
/* free allocated memory of command line data structure */
RNAdos_cmdline_parser_free(&args_info);
if (ParamFile != NULL) {
if (!strcmp(ParamFile, "DNA"))
vrna_params_load_DNA_Mathews2004();
else
vrna_params_load(ParamFile, VRNA_PARAMETER_FORMAT_DEFAULT);
}
if (verbose)
printf("%s\n", rnaSequence);
vrna_fold_compound_t *fc = vrna_fold_compound(rnaSequence,
&md,
VRNA_OPTION_DEFAULT);
if (!vrna_fold_compound_prepare(fc, VRNA_OPTION_MFE))
vrna_message_warning("vrna_mfe@mfe.c: Failed to prepare vrna_fold_compound");
int max_energy_dcal = max_energy * 100;
compute_density_of_states(fc, max_energy_dcal, hash_bits, verbose);
free(rnaSequence);
vrna_fold_compound_free(fc);
return EXIT_SUCCESS;
}
|
CG.h | /**
* This file contains (modified) code from the Eigen library.
* Eigen License:
*
* Copyright (C) 2008 Gael Guennebaud <gael.guennebaud@inria.fr>
* Copyright (C) 2007-2011 Benoit Jacob <jacob.benoit.1@gmail.com>
*
* This Source Code Form is subject to the terms of the Mozilla
* Public License v. 2.0. If a copy of the MPL was not distributed
* with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
*
*
* ======================
*
* The modifications are part of the Eigen Recursive Matrix Extension (ERME).
* ERME License:
*
* Copyright (c) 2019 Darius Rückert
* Licensed under the MIT License.
*/
#pragma once
#include "../Core.h"
#include "../Core/ParallelHelper.h"
#include "Cholesky.h"
namespace Eigen::Recursive
{
template <typename _Scalar>
class RecursiveDiagonalPreconditioner
{
typedef _Scalar Scalar;
typedef Eigen::Matrix<Scalar, Eigen::Dynamic, 1> Vector;
public:
typedef typename Vector::StorageIndex StorageIndex;
enum
{
ColsAtCompileTime = Eigen::Dynamic,
MaxColsAtCompileTime = Eigen::Dynamic
};
RecursiveDiagonalPreconditioner() : m_isInitialized(false) {}
void resize(int N) { m_invdiag.resize(N); }
template <typename MatType>
explicit RecursiveDiagonalPreconditioner(const MatType& mat) : m_invdiag(mat.cols())
{
compute(mat);
}
Eigen::Index rows() const { return m_invdiag.size(); }
Eigen::Index cols() const { return m_invdiag.size(); }
template <typename MatType>
RecursiveDiagonalPreconditioner& analyzePattern(const MatType&)
{
return *this;
}
// Sparse Matrix Initialization
template <typename Scalar, int options>
// RecursiveDiagonalPreconditioner& factorize(const MatType& mat)
RecursiveDiagonalPreconditioner& factorize(const SparseMatrix<Scalar, options>& mat)
{
using MatType = SparseMatrix<Scalar, options>;
m_invdiag.resize(mat.cols());
for (int j = 0; j < mat.outerSize(); ++j)
{
typename MatType::InnerIterator it(mat, j);
while (it && it.index() != j) ++it;
if (it && it.index() == j)
// m_invdiag(j) = Scalar(1)/it.value();
removeMatrixScalar(m_invdiag(j)) = removeMatrixScalar(inverseCholesky(it.value()));
else
// m_invdiag(j) = Scalar(1);
removeMatrixScalar(m_invdiag(j)) = removeMatrixScalar(MultiplicativeNeutral<Scalar>::get());
}
m_isInitialized = true;
return *this;
}
// Dense Matrix Initialization
template <typename MatType>
RecursiveDiagonalPreconditioner& factorize(const MatType& mat)
{
m_invdiag.resize(mat.cols());
for (int j = 0; j < mat.outerSize(); ++j)
{
removeMatrixScalar(m_invdiag(j)) = removeMatrixScalar(inverseCholesky(mat(j, j)));
}
m_isInitialized = true;
return *this;
}
template <typename T>
RecursiveDiagonalPreconditioner& factorize(const Eigen::DiagonalMatrix<T, -1>& mat)
{
auto N = mat.rows();
if (m_invdiag.rows() != N)
{
std::terminate();
m_invdiag.resize(N);
}
#pragma omp for
for (int j = 0; j < N; ++j)
{
m_invdiag(j) = inverseCholesky(mat.diagonal()(j));
}
m_isInitialized = true;
return *this;
}
template <typename MatType>
RecursiveDiagonalPreconditioner& compute(const MatType& mat)
{
return factorize(mat);
}
/** \internal */
template <typename Rhs, typename Dest>
void _solve_impl(const Rhs& b, Dest& x) const
{
// x = m_invdiag.array() * b.array();
#pragma omp for
for (int i = 0; i < b.rows(); ++i)
{
x(i) = m_invdiag(i) * b(i);
}
}
template <typename Rhs>
inline const Eigen::Solve<RecursiveDiagonalPreconditioner, Rhs> solve(const Eigen::MatrixBase<Rhs>& b) const
{
eigen_assert(m_isInitialized && "DiagonalPreconditioner is not initialized.");
eigen_assert(m_invdiag.size() == b.rows() &&
"DiagonalPreconditioner::solve(): invalid number of rows of the right hand side matrix b");
return Eigen::Solve<RecursiveDiagonalPreconditioner, Rhs>(*this, b.derived());
}
Eigen::ComputationInfo info() { return Eigen::Success; }
const auto& getDiagElement(int i) const { return m_invdiag(i); }
Vector m_invdiag;
protected:
bool m_isInitialized;
};
//#define RM_CG_DEBUG_OUTPUT
/**
* A conjugate gradient solver, which works for recursives matrices.
* Solve:
* A * x = b for x
*
* The matrix A is given as function (for example a lambda function).
* This way we can implement an implicit cg solver, which does not construct the full matrix A.
*
* Example call:
*
* // Build preconditioner
* RecursiveDiagonalPreconditioner<MatrixScalar<Block>> P;
* Eigen::Index iters = 50;
* Scalar tol = 1e-50;
* P.compute(S);
*
* // Solve with explicit matrix S
* DAType tmp(n);
* recursive_conjugate_gradient(
* [&](const DAType& v) {
* tmp = S * v;
* return tmp;
* },
* ej, da, P, iters, tol);
*
*/
template <typename MultFunction, typename Rhs, typename Dest, typename Preconditioner, typename SuperScalar>
EIGEN_DONT_INLINE void recursive_conjugate_gradient(const MultFunction& applyA, const Rhs& rhs, Dest& x,
const Preconditioner& precond, Eigen::Index& iters,
SuperScalar& tol_error)
{
// Typedefs
using namespace Eigen;
using std::abs;
using std::sqrt;
typedef SuperScalar RealScalar;
typedef SuperScalar Scalar;
typedef Rhs VectorType;
// Temp Vector variables
Index n = rhs.rows();
#ifdef RM_CG_DEBUG_OUTPUT
std::cout << "Starting recursive CG" << std::endl;
std::cout << "Iterations: " << iters << std::endl;
std::cout << "Tolerance: " << tol_error << std::endl;
std::cout << "N: " << n << std::endl;
#endif
#if 0
// Create them locally
VectorType z(n);
VectorType p(n);
#else
// Use static variables so a repeated call with the same size doesn't allocate memory
static thread_local VectorType z;
static thread_local VectorType p;
static thread_local VectorType residual;
z.resize(n);
p.resize(n);
residual.resize(n);
#endif
RealScalar tol = tol_error;
Index maxIters = iters;
applyA(x, residual);
residual = rhs - residual;
RealScalar rhsNorm2 = squaredNorm(rhs);
if (rhsNorm2 == 0)
{
x.setZero();
iters = 0;
tol_error = 0;
return;
}
RealScalar threshold = tol * tol * rhsNorm2;
RealScalar residualNorm2 = squaredNorm(residual);
#ifdef RM_CG_DEBUG_OUTPUT
std::cout << "Initial residual: " << residualNorm2 << std::endl;
#endif
if (residualNorm2 < threshold)
{
iters = 0;
tol_error = sqrt(residualNorm2 / rhsNorm2);
return;
}
p = precond.solve(residual); // initial search direction
// the square of the absolute value of r scaled by invM
RealScalar absNew = dot(residual, p);
#ifdef RM_CG_DEBUG_OUTPUT
std::cout << "dot(r,p): " << absNew << std::endl;
#endif
Index i = 0;
while (i < maxIters)
{
// std::cout << "CG Residual " << i << ": " << residualNorm2 << std::endl;
applyA(p, z);
// the amount we travel on dir
Scalar alpha = absNew / dot(p, z);
// update solution
x += scalarMult(p, alpha);
// update residual
residual -= scalarMult(z, alpha);
residualNorm2 = squaredNorm(residual);
#ifdef RM_CG_DEBUG_OUTPUT
std::cout << "Iteration: " << i << " Residual: " << residualNorm2 << " Alpha: " << alpha << std::endl;
#endif
if (residualNorm2 < threshold) break;
z = precond.solve(residual); // approximately solve for "A z = residual"
// std::cout << expand(p).transpose() << std::endl;
RealScalar absOld = absNew;
absNew = dot(residual, z); // update the absolute value of r
RealScalar beta = absNew / absOld; // calculate the Gram-Schmidt value used to create the new search direction
// std::cout << "absnew " << absNew << " beta " << beta << std::endl;
p = z + scalarMult(p, beta); // update search direction
i++;
}
tol_error = sqrt(residualNorm2 / rhsNorm2);
iters = i;
}
#if defined(_OPENMP)
template <typename T>
struct alignas(64) CacheAlignedValues
{
T data;
};
template <typename T>
inline double accumulate(const T& v)
{
double d = 0;
for (auto& v : v)
{
d += v.data;
}
return d;
}
// Multi threaded implementation
template <typename MultFunction, typename Rhs, typename Dest, typename Preconditioner, typename SuperScalar>
EIGEN_DONT_INLINE void recursive_conjugate_gradient_OMP(const MultFunction& applyA, const Rhs& rhs, Dest& x,
const Preconditioner& precond, Eigen::Index& iters,
SuperScalar& tol_error)
{
// Typedefs
using namespace Eigen;
using std::abs;
using std::sqrt;
typedef SuperScalar RealScalar;
typedef SuperScalar Scalar;
typedef Rhs VectorType;
// Temp Vector variables
Index n = rhs.rows();
// Use static variables so a repeated call with the same size doesn't allocate memory
static VectorType z;
static VectorType p;
static VectorType residual;
static std::vector<CacheAlignedValues<Scalar>> tmpResults1, tmpResults;
# pragma omp single
{
z.resize(n);
p.resize(n);
residual.resize(n);
tmpResults1.resize(omp_get_num_threads());
tmpResults.resize(omp_get_num_threads());
}
int tid = omp_get_thread_num();
RealScalar tol = tol_error;
Index maxIters = iters;
applyA(x, residual);
# pragma omp for
for (int i = 0; i < n; ++i)
{
residual(i) = rhs(i) - residual(i);
}
// tmpResults[tid] = squaredNorm_omp(rhs);
squaredNorm_omp_local(rhs, tmpResults[tid].data);
RealScalar rhsNorm2 = accumulate(tmpResults);
if (rhsNorm2 == 0)
{
// x.setZero();
# pragma omp for
for (int i = 0; i < n; ++i)
{
x(i).get().setZero();
}
iters = 0;
tol_error = 0;
maxIters = 0;
}
RealScalar threshold = tol * tol * rhsNorm2;
squaredNorm_omp_local(residual, tmpResults1[tid].data);
RealScalar residualNorm2 = accumulate(tmpResults1);
// RealScalar residualNorm2 = squaredNorm(residual);
if (residualNorm2 < threshold)
{
iters = 0;
tol_error = sqrt(residualNorm2 / rhsNorm2);
maxIters = 0;
}
p = precond.solve(residual); // initial search direction
dot_omp_local(residual, p, tmpResults[tid].data);
RealScalar absNew = accumulate(tmpResults);
Index i = 0;
while (i < maxIters)
{
// std::cout << "CG Residual " << i << ": " << residualNorm2 << std::endl;
applyA(p, z);
dot_omp_local(p, z, tmpResults1[tid].data);
Scalar dotpz = accumulate(tmpResults1);
Scalar alpha = absNew / dotpz;
# pragma omp for
for (int i = 0; i < n; ++i)
{
// the amount we travel on dir
// update solution
x(i) += p(i) * alpha;
// update residual
residual(i) -= z(i) * alpha;
}
squaredNorm_omp_local(residual, tmpResults[tid].data);
residualNorm2 = accumulate(tmpResults);
if (residualNorm2 < threshold) break;
z = precond.solve(residual); // approximately solve for "A z = residual"
RealScalar absOld = absNew;
dot_omp_local(residual, z, tmpResults[tid].data);
absNew = accumulate(tmpResults);
RealScalar beta = absNew / absOld; // calculate the Gram-Schmidt value used to create the new search direction
// std::cout << "absnew " << absNew << " beta " << beta << std::endl;
# pragma omp for
for (int i = 0; i < n; ++i)
{
p(i) = z(i) + p(i) * beta; // update search direction
}
i++;
}
tol_error = sqrt(residualNorm2 / rhsNorm2);
iters = i;
}
#endif
} // namespace Eigen::Recursive
|
ast-dump-openmp-cancel.c | // RUN: %clang_cc1 -triple x86_64-unknown-unknown -fopenmp -ast-dump %s | FileCheck --match-full-lines -implicit-check-not=openmp_structured_block %s
void test() {
#pragma omp parallel
{
#pragma omp cancel parallel
}
}
// CHECK: TranslationUnitDecl {{.*}} <<invalid sloc>> <invalid sloc>
// CHECK: `-FunctionDecl {{.*}} <{{.*}}ast-dump-openmp-cancel.c:3:1, line:8:1> line:3:6 test 'void ()'
// CHECK-NEXT: `-CompoundStmt {{.*}} <col:13, line:8:1>
// CHECK-NEXT: `-OMPParallelDirective {{.*}} <line:4:1, col:21>
// CHECK-NEXT: `-CapturedStmt {{.*}} <line:5:3, line:7:3>
// CHECK-NEXT: `-CapturedDecl {{.*}} <<invalid sloc>> <invalid sloc> nothrow
// CHECK-NEXT: |-CompoundStmt {{.*}} <line:5:3, line:7:3> openmp_structured_block
// CHECK-NEXT: | `-OMPCancelDirective {{.*}} <line:6:1, col:28> openmp_standalone_directive
// CHECK-NEXT: |-ImplicitParamDecl {{.*}} <line:4:1> col:1 implicit .global_tid. 'const int *const restrict'
// CHECK-NEXT: |-ImplicitParamDecl {{.*}} <col:1> col:1 implicit .bound_tid. 'const int *const restrict'
// CHECK-NEXT: `-ImplicitParamDecl {{.*}} <col:1> col:1 implicit __context 'struct (anonymous at {{.*}}ast-dump-openmp-cancel.c:4:1) *const restrict'
|
draw.c | /*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% DDDD RRRR AAA W W %
% D D R R A A W W %
% D D RRRR AAAAA W W W %
% D D R RN A A WW WW %
% DDDD R R A A W W %
% %
% %
% MagickCore Image Drawing Methods %
% %
% %
% Software Design %
% John Cristy %
% July 1998 %
% %
% %
% Copyright 1999-2011 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. %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% Bill Radcliffe of Corbis (www.corbis.com) contributed the polygon
% rendering code based on Paul Heckbert's "Concave Polygon Scan Conversion",
% Graphics Gems, 1990. Leonard Rosenthal and David Harr of Appligent
% (www.appligent.com) contributed the dash pattern, linecap stroking
% algorithm, and minor rendering improvements.
%
*/
/*
Include declarations.
*/
#include "magick/studio.h"
#include "magick/annotate.h"
#include "magick/artifact.h"
#include "magick/blob.h"
#include "magick/cache.h"
#include "magick/cache-view.h"
#include "magick/color.h"
#include "magick/composite.h"
#include "magick/composite-private.h"
#include "magick/constitute.h"
#include "magick/draw.h"
#include "magick/draw-private.h"
#include "magick/enhance.h"
#include "magick/exception.h"
#include "magick/exception-private.h"
#include "magick/gem.h"
#include "magick/geometry.h"
#include "magick/image-private.h"
#include "magick/list.h"
#include "magick/log.h"
#include "magick/monitor.h"
#include "magick/monitor-private.h"
#include "magick/option.h"
#include "magick/paint.h"
#include "magick/pixel-private.h"
#include "magick/property.h"
#include "magick/resample.h"
#include "magick/resample-private.h"
#include "magick/string_.h"
#include "magick/string-private.h"
#include "magick/thread-private.h"
#include "magick/token.h"
#include "magick/transform.h"
#include "magick/utility.h"
/*
Define declarations.
*/
#define BezierQuantum 200
/*
Typedef declarations.
*/
typedef struct _EdgeInfo
{
SegmentInfo
bounds;
MagickRealType
scanline;
PointInfo
*points;
size_t
number_points;
ssize_t
direction;
MagickBooleanType
ghostline;
size_t
highwater;
} EdgeInfo;
typedef struct _ElementInfo
{
MagickRealType
cx,
cy,
major,
minor,
angle;
} ElementInfo;
typedef struct _PolygonInfo
{
EdgeInfo
*edges;
size_t
number_edges;
} PolygonInfo;
typedef enum
{
MoveToCode,
OpenCode,
GhostlineCode,
LineToCode,
EndCode
} PathInfoCode;
typedef struct _PathInfo
{
PointInfo
point;
PathInfoCode
code;
} PathInfo;
/*
Forward declarations.
*/
static MagickBooleanType
DrawStrokePolygon(Image *,const DrawInfo *,const PrimitiveInfo *);
static PrimitiveInfo
*TraceStrokePolygon(const DrawInfo *,const PrimitiveInfo *);
static size_t
TracePath(PrimitiveInfo *,const char *);
static void
TraceArc(PrimitiveInfo *,const PointInfo,const PointInfo,const PointInfo),
TraceArcPath(PrimitiveInfo *,const PointInfo,const PointInfo,const PointInfo,
const MagickRealType,const MagickBooleanType,const MagickBooleanType),
TraceBezier(PrimitiveInfo *,const size_t),
TraceCircle(PrimitiveInfo *,const PointInfo,const PointInfo),
TraceEllipse(PrimitiveInfo *,const PointInfo,const PointInfo,const PointInfo),
TraceLine(PrimitiveInfo *,const PointInfo,const PointInfo),
TraceRectangle(PrimitiveInfo *,const PointInfo,const PointInfo),
TraceRoundRectangle(PrimitiveInfo *,const PointInfo,const PointInfo,
PointInfo),
TraceSquareLinecap(PrimitiveInfo *,const size_t,const MagickRealType);
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% A c q u i r e D r a w I n f o %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% AcquireDrawInfo() returns a DrawInfo structure properly initialized.
%
% The format of the AcquireDrawInfo method is:
%
% DrawInfo *AcquireDrawInfo(void)
%
*/
MagickExport DrawInfo *AcquireDrawInfo(void)
{
DrawInfo
*draw_info;
draw_info=(DrawInfo *) AcquireMagickMemory(sizeof(*draw_info));
if (draw_info == (DrawInfo *) NULL)
ThrowFatalException(ResourceLimitFatalError,"MemoryAllocationFailed");
GetDrawInfo((ImageInfo *) NULL,draw_info);
return(draw_info);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% C l o n e D r a w I n f o %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% CloneDrawInfo() makes a copy of the given draw info structure. If NULL
% is specified, a new image info structure is created initialized to
% default values.
%
% The format of the CloneDrawInfo method is:
%
% DrawInfo *CloneDrawInfo(const ImageInfo *image_info,
% const DrawInfo *draw_info)
%
% A description of each parameter follows:
%
% o image_info: the image info.
%
% o draw_info: the draw info.
%
*/
MagickExport DrawInfo *CloneDrawInfo(const ImageInfo *image_info,
const DrawInfo *draw_info)
{
DrawInfo
*clone_info;
clone_info=(DrawInfo *) AcquireMagickMemory(sizeof(*clone_info));
if (clone_info == (DrawInfo *) NULL)
ThrowFatalException(ResourceLimitFatalError,"MemoryAllocationFailed");
GetDrawInfo(image_info,clone_info);
if (draw_info == (DrawInfo *) NULL)
return(clone_info);
if (clone_info->primitive != (char *) NULL)
(void) CloneString(&clone_info->primitive,draw_info->primitive);
if (draw_info->geometry != (char *) NULL)
(void) CloneString(&clone_info->geometry,draw_info->geometry);
clone_info->viewbox=draw_info->viewbox;
clone_info->affine=draw_info->affine;
clone_info->gravity=draw_info->gravity;
clone_info->fill=draw_info->fill;
clone_info->stroke=draw_info->stroke;
clone_info->stroke_width=draw_info->stroke_width;
if (draw_info->fill_pattern != (Image *) NULL)
clone_info->fill_pattern=CloneImage(draw_info->fill_pattern,0,0,MagickTrue,
&draw_info->fill_pattern->exception);
else
if (draw_info->tile != (Image *) NULL)
clone_info->fill_pattern=CloneImage(draw_info->tile,0,0,MagickTrue,
&draw_info->tile->exception);
clone_info->tile=NewImageList(); /* tile is deprecated */
if (draw_info->stroke_pattern != (Image *) NULL)
clone_info->stroke_pattern=CloneImage(draw_info->stroke_pattern,0,0,
MagickTrue,&draw_info->stroke_pattern->exception);
clone_info->stroke_antialias=draw_info->stroke_antialias;
clone_info->text_antialias=draw_info->text_antialias;
clone_info->fill_rule=draw_info->fill_rule;
clone_info->linecap=draw_info->linecap;
clone_info->linejoin=draw_info->linejoin;
clone_info->miterlimit=draw_info->miterlimit;
clone_info->dash_offset=draw_info->dash_offset;
clone_info->decorate=draw_info->decorate;
clone_info->compose=draw_info->compose;
if (draw_info->text != (char *) NULL)
(void) CloneString(&clone_info->text,draw_info->text);
if (draw_info->font != (char *) NULL)
(void) CloneString(&clone_info->font,draw_info->font);
if (draw_info->metrics != (char *) NULL)
(void) CloneString(&clone_info->metrics,draw_info->metrics);
if (draw_info->family != (char *) NULL)
(void) CloneString(&clone_info->family,draw_info->family);
clone_info->style=draw_info->style;
clone_info->stretch=draw_info->stretch;
clone_info->weight=draw_info->weight;
if (draw_info->encoding != (char *) NULL)
(void) CloneString(&clone_info->encoding,draw_info->encoding);
clone_info->pointsize=draw_info->pointsize;
clone_info->kerning=draw_info->kerning;
clone_info->interline_spacing=draw_info->interline_spacing;
clone_info->interword_spacing=draw_info->interword_spacing;
clone_info->direction=draw_info->direction;
if (draw_info->density != (char *) NULL)
(void) CloneString(&clone_info->density,draw_info->density);
clone_info->align=draw_info->align;
clone_info->undercolor=draw_info->undercolor;
clone_info->border_color=draw_info->border_color;
if (draw_info->server_name != (char *) NULL)
(void) CloneString(&clone_info->server_name,draw_info->server_name);
if (draw_info->dash_pattern != (double *) NULL)
{
register ssize_t
x;
for (x=0; draw_info->dash_pattern[x] != 0.0; x++) ;
clone_info->dash_pattern=(double *) AcquireQuantumMemory((size_t) x+1UL,
sizeof(*clone_info->dash_pattern));
if (clone_info->dash_pattern == (double *) NULL)
ThrowFatalException(ResourceLimitFatalError,
"UnableToAllocateDashPattern");
(void) CopyMagickMemory(clone_info->dash_pattern,draw_info->dash_pattern,
(size_t) (x+1)*sizeof(*clone_info->dash_pattern));
}
clone_info->gradient=draw_info->gradient;
if (draw_info->gradient.stops != (StopInfo *) NULL)
{
size_t
number_stops;
number_stops=clone_info->gradient.number_stops;
clone_info->gradient.stops=(StopInfo *) AcquireQuantumMemory((size_t)
number_stops,sizeof(*clone_info->gradient.stops));
if (clone_info->gradient.stops == (StopInfo *) NULL)
ThrowFatalException(ResourceLimitFatalError,
"UnableToAllocateDashPattern");
(void) CopyMagickMemory(clone_info->gradient.stops,
draw_info->gradient.stops,(size_t) number_stops*
sizeof(*clone_info->gradient.stops));
}
if (draw_info->clip_mask != (char *) NULL)
(void) CloneString(&clone_info->clip_mask,draw_info->clip_mask);
clone_info->bounds=draw_info->bounds;
clone_info->clip_units=draw_info->clip_units;
clone_info->render=draw_info->render;
clone_info->opacity=draw_info->opacity;
clone_info->element_reference=draw_info->element_reference;
clone_info->debug=IsEventLogging();
return(clone_info);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
+ C o n v e r t P a t h T o P o l y g o n %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% ConvertPathToPolygon() converts a path to the more efficient sorted
% rendering form.
%
% The format of the ConvertPathToPolygon method is:
%
% PolygonInfo *ConvertPathToPolygon(const DrawInfo *draw_info,
% const PathInfo *path_info)
%
% A description of each parameter follows:
%
% o Method ConvertPathToPolygon returns the path in a more efficient sorted
% rendering form of type PolygonInfo.
%
% o draw_info: Specifies a pointer to an DrawInfo structure.
%
% o path_info: Specifies a pointer to an PathInfo structure.
%
%
*/
#if defined(__cplusplus) || defined(c_plusplus)
extern "C" {
#endif
static int CompareEdges(const void *x,const void *y)
{
register const EdgeInfo
*p,
*q;
/*
Compare two edges.
*/
p=(const EdgeInfo *) x;
q=(const EdgeInfo *) y;
if ((p->points[0].y-MagickEpsilon) > q->points[0].y)
return(1);
if ((p->points[0].y+MagickEpsilon) < q->points[0].y)
return(-1);
if ((p->points[0].x-MagickEpsilon) > q->points[0].x)
return(1);
if ((p->points[0].x+MagickEpsilon) < q->points[0].x)
return(-1);
if (((p->points[1].x-p->points[0].x)*(q->points[1].y-q->points[0].y)-
(p->points[1].y-p->points[0].y)*(q->points[1].x-q->points[0].x)) > 0.0)
return(1);
return(-1);
}
#if defined(__cplusplus) || defined(c_plusplus)
}
#endif
static void LogPolygonInfo(const PolygonInfo *polygon_info)
{
register EdgeInfo
*p;
register ssize_t
i,
j;
(void) LogMagickEvent(DrawEvent,GetMagickModule()," begin active-edge");
p=polygon_info->edges;
for (i=0; i < (ssize_t) polygon_info->number_edges; i++)
{
(void) LogMagickEvent(DrawEvent,GetMagickModule()," edge %.20g:",
(double) i);
(void) LogMagickEvent(DrawEvent,GetMagickModule()," direction: %s",
p->direction != MagickFalse ? "down" : "up");
(void) LogMagickEvent(DrawEvent,GetMagickModule()," ghostline: %s",
p->ghostline != MagickFalse ? "transparent" : "opaque");
(void) LogMagickEvent(DrawEvent,GetMagickModule(),
" bounds: %g,%g - %g,%g",p->bounds.x1,p->bounds.y1,
p->bounds.x2,p->bounds.y2);
for (j=0; j < (ssize_t) p->number_points; j++)
(void) LogMagickEvent(DrawEvent,GetMagickModule()," %g,%g",
p->points[j].x,p->points[j].y);
p++;
}
(void) LogMagickEvent(DrawEvent,GetMagickModule()," end active-edge");
}
static void ReversePoints(PointInfo *points,const size_t number_points)
{
PointInfo
point;
register ssize_t
i;
for (i=0; i < (ssize_t) (number_points >> 1); i++)
{
point=points[i];
points[i]=points[number_points-(i+1)];
points[number_points-(i+1)]=point;
}
}
static PolygonInfo *ConvertPathToPolygon(
const DrawInfo *magick_unused(draw_info),const PathInfo *path_info)
{
long
direction,
next_direction;
PointInfo
point,
*points;
PolygonInfo
*polygon_info;
SegmentInfo
bounds;
register ssize_t
i,
n;
MagickBooleanType
ghostline;
size_t
edge,
number_edges,
number_points;
/*
Convert a path to the more efficient sorted rendering form.
*/
polygon_info=(PolygonInfo *) AcquireMagickMemory(sizeof(*polygon_info));
if (polygon_info == (PolygonInfo *) NULL)
return((PolygonInfo *) NULL);
number_edges=16;
polygon_info->edges=(EdgeInfo *) AcquireQuantumMemory((size_t) number_edges,
sizeof(*polygon_info->edges));
if (polygon_info->edges == (EdgeInfo *) NULL)
return((PolygonInfo *) NULL);
direction=0;
edge=0;
ghostline=MagickFalse;
n=0;
number_points=0;
points=(PointInfo *) NULL;
(void) ResetMagickMemory(&point,0,sizeof(point));
(void) ResetMagickMemory(&bounds,0,sizeof(bounds));
for (i=0; path_info[i].code != EndCode; i++)
{
if ((path_info[i].code == MoveToCode) || (path_info[i].code == OpenCode) ||
(path_info[i].code == GhostlineCode))
{
/*
Move to.
*/
if ((points != (PointInfo *) NULL) && (n >= 2))
{
if (edge == number_edges)
{
number_edges<<=1;
polygon_info->edges=(EdgeInfo *) ResizeQuantumMemory(
polygon_info->edges,(size_t) number_edges,
sizeof(*polygon_info->edges));
if (polygon_info->edges == (EdgeInfo *) NULL)
return((PolygonInfo *) NULL);
}
polygon_info->edges[edge].number_points=(size_t) n;
polygon_info->edges[edge].scanline=(-1.0);
polygon_info->edges[edge].highwater=0;
polygon_info->edges[edge].ghostline=ghostline;
polygon_info->edges[edge].direction=(ssize_t) (direction > 0);
if (direction < 0)
ReversePoints(points,(size_t) n);
polygon_info->edges[edge].points=points;
polygon_info->edges[edge].bounds=bounds;
polygon_info->edges[edge].bounds.y1=points[0].y;
polygon_info->edges[edge].bounds.y2=points[n-1].y;
points=(PointInfo *) NULL;
ghostline=MagickFalse;
edge++;
}
if (points == (PointInfo *) NULL)
{
number_points=16;
points=(PointInfo *) AcquireQuantumMemory((size_t) number_points,
sizeof(*points));
if (points == (PointInfo *) NULL)
return((PolygonInfo *) NULL);
}
ghostline=path_info[i].code == GhostlineCode ? MagickTrue : MagickFalse;
point=path_info[i].point;
points[0]=point;
bounds.x1=point.x;
bounds.x2=point.x;
direction=0;
n=1;
continue;
}
/*
Line to.
*/
next_direction=((path_info[i].point.y > point.y) ||
((path_info[i].point.y == point.y) &&
(path_info[i].point.x > point.x))) ? 1 : -1;
if ((direction != 0) && (direction != next_direction))
{
/*
New edge.
*/
point=points[n-1];
if (edge == number_edges)
{
number_edges<<=1;
polygon_info->edges=(EdgeInfo *) ResizeQuantumMemory(
polygon_info->edges,(size_t) number_edges,
sizeof(*polygon_info->edges));
if (polygon_info->edges == (EdgeInfo *) NULL)
return((PolygonInfo *) NULL);
}
polygon_info->edges[edge].number_points=(size_t) n;
polygon_info->edges[edge].scanline=(-1.0);
polygon_info->edges[edge].highwater=0;
polygon_info->edges[edge].ghostline=ghostline;
polygon_info->edges[edge].direction=(ssize_t) (direction > 0);
if (direction < 0)
ReversePoints(points,(size_t) n);
polygon_info->edges[edge].points=points;
polygon_info->edges[edge].bounds=bounds;
polygon_info->edges[edge].bounds.y1=points[0].y;
polygon_info->edges[edge].bounds.y2=points[n-1].y;
number_points=16;
points=(PointInfo *) AcquireQuantumMemory((size_t) number_points,
sizeof(*points));
if (points == (PointInfo *) NULL)
return((PolygonInfo *) NULL);
n=1;
ghostline=MagickFalse;
points[0]=point;
bounds.x1=point.x;
bounds.x2=point.x;
edge++;
}
direction=next_direction;
if (points == (PointInfo *) NULL)
continue;
if (n == (ssize_t) number_points)
{
number_points<<=1;
points=(PointInfo *) ResizeQuantumMemory(points,(size_t) number_points,
sizeof(*points));
if (points == (PointInfo *) NULL)
return((PolygonInfo *) NULL);
}
point=path_info[i].point;
points[n]=point;
if (point.x < bounds.x1)
bounds.x1=point.x;
if (point.x > bounds.x2)
bounds.x2=point.x;
n++;
}
if (points != (PointInfo *) NULL)
{
if (n < 2)
points=(PointInfo *) RelinquishMagickMemory(points);
else
{
if (edge == number_edges)
{
number_edges<<=1;
polygon_info->edges=(EdgeInfo *) ResizeQuantumMemory(
polygon_info->edges,(size_t) number_edges,
sizeof(*polygon_info->edges));
if (polygon_info->edges == (EdgeInfo *) NULL)
return((PolygonInfo *) NULL);
}
polygon_info->edges[edge].number_points=(size_t) n;
polygon_info->edges[edge].scanline=(-1.0);
polygon_info->edges[edge].highwater=0;
polygon_info->edges[edge].ghostline=ghostline;
polygon_info->edges[edge].direction=(ssize_t) (direction > 0);
if (direction < 0)
ReversePoints(points,(size_t) n);
polygon_info->edges[edge].points=points;
polygon_info->edges[edge].bounds=bounds;
polygon_info->edges[edge].bounds.y1=points[0].y;
polygon_info->edges[edge].bounds.y2=points[n-1].y;
ghostline=MagickFalse;
edge++;
}
}
polygon_info->number_edges=edge;
qsort(polygon_info->edges,(size_t) polygon_info->number_edges,
sizeof(*polygon_info->edges),CompareEdges);
if (IsEventLogging() != MagickFalse)
LogPolygonInfo(polygon_info);
return(polygon_info);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
+ C o n v e r t P r i m i t i v e T o P a t h %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% ConvertPrimitiveToPath() converts a PrimitiveInfo structure into a vector
% path structure.
%
% The format of the ConvertPrimitiveToPath method is:
%
% PathInfo *ConvertPrimitiveToPath(const DrawInfo *draw_info,
% const PrimitiveInfo *primitive_info)
%
% A description of each parameter follows:
%
% o Method ConvertPrimitiveToPath returns a vector path structure of type
% PathInfo.
%
% o draw_info: a structure of type DrawInfo.
%
% o primitive_info: Specifies a pointer to an PrimitiveInfo structure.
%
%
*/
static void LogPathInfo(const PathInfo *path_info)
{
register const PathInfo
*p;
(void) LogMagickEvent(DrawEvent,GetMagickModule()," begin vector-path");
for (p=path_info; p->code != EndCode; p++)
(void) LogMagickEvent(DrawEvent,GetMagickModule(),
" %g,%g %s",p->point.x,p->point.y,p->code == GhostlineCode ?
"moveto ghostline" : p->code == OpenCode ? "moveto open" :
p->code == MoveToCode ? "moveto" : p->code == LineToCode ? "lineto" :
"?");
(void) LogMagickEvent(DrawEvent,GetMagickModule()," end vector-path");
}
static PathInfo *ConvertPrimitiveToPath(
const DrawInfo *magick_unused(draw_info),const PrimitiveInfo *primitive_info)
{
PathInfo
*path_info;
PathInfoCode
code;
PointInfo
p,
q;
register ssize_t
i,
n;
ssize_t
coordinates,
start;
/*
Converts a PrimitiveInfo structure into a vector path structure.
*/
switch (primitive_info->primitive)
{
case PointPrimitive:
case ColorPrimitive:
case MattePrimitive:
case TextPrimitive:
case ImagePrimitive:
return((PathInfo *) NULL);
default:
break;
}
for (i=0; primitive_info[i].primitive != UndefinedPrimitive; i++) ;
path_info=(PathInfo *) AcquireQuantumMemory((size_t) (2UL*i+3UL),
sizeof(*path_info));
if (path_info == (PathInfo *) NULL)
return((PathInfo *) NULL);
coordinates=0;
n=0;
p.x=(-1.0);
p.y=(-1.0);
q.x=(-1.0);
q.y=(-1.0);
start=0;
for (i=0; primitive_info[i].primitive != UndefinedPrimitive; i++)
{
code=LineToCode;
if (coordinates <= 0)
{
coordinates=(ssize_t) primitive_info[i].coordinates;
p=primitive_info[i].point;
start=n;
code=MoveToCode;
}
coordinates--;
/*
Eliminate duplicate points.
*/
if ((i == 0) || (fabs(q.x-primitive_info[i].point.x) > MagickEpsilon) ||
(fabs(q.y-primitive_info[i].point.y) > MagickEpsilon))
{
path_info[n].code=code;
path_info[n].point=primitive_info[i].point;
q=primitive_info[i].point;
n++;
}
if (coordinates > 0)
continue;
if ((fabs(p.x-primitive_info[i].point.x) <= MagickEpsilon) &&
(fabs(p.y-primitive_info[i].point.y) <= MagickEpsilon))
continue;
/*
Mark the p point as open if it does not match the q.
*/
path_info[start].code=OpenCode;
path_info[n].code=GhostlineCode;
path_info[n].point=primitive_info[i].point;
n++;
path_info[n].code=LineToCode;
path_info[n].point=p;
n++;
}
path_info[n].code=EndCode;
path_info[n].point.x=0.0;
path_info[n].point.y=0.0;
if (IsEventLogging() != MagickFalse)
LogPathInfo(path_info);
return(path_info);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% D e s t r o y D r a w I n f o %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% DestroyDrawInfo() deallocates memory associated with an DrawInfo
% structure.
%
% The format of the DestroyDrawInfo method is:
%
% DrawInfo *DestroyDrawInfo(DrawInfo *draw_info)
%
% A description of each parameter follows:
%
% o draw_info: the draw info.
%
*/
MagickExport DrawInfo *DestroyDrawInfo(DrawInfo *draw_info)
{
if (draw_info->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"...");
assert(draw_info != (DrawInfo *) NULL);
assert(draw_info->signature == MagickSignature);
if (draw_info->primitive != (char *) NULL)
draw_info->primitive=DestroyString(draw_info->primitive);
if (draw_info->text != (char *) NULL)
draw_info->text=DestroyString(draw_info->text);
if (draw_info->geometry != (char *) NULL)
draw_info->geometry=DestroyString(draw_info->geometry);
if (draw_info->tile != (Image *) NULL)
draw_info->tile=DestroyImage(draw_info->tile);
if (draw_info->fill_pattern != (Image *) NULL)
draw_info->fill_pattern=DestroyImage(draw_info->fill_pattern);
if (draw_info->stroke_pattern != (Image *) NULL)
draw_info->stroke_pattern=DestroyImage(draw_info->stroke_pattern);
if (draw_info->font != (char *) NULL)
draw_info->font=DestroyString(draw_info->font);
if (draw_info->metrics != (char *) NULL)
draw_info->metrics=DestroyString(draw_info->metrics);
if (draw_info->family != (char *) NULL)
draw_info->family=DestroyString(draw_info->family);
if (draw_info->encoding != (char *) NULL)
draw_info->encoding=DestroyString(draw_info->encoding);
if (draw_info->density != (char *) NULL)
draw_info->density=DestroyString(draw_info->density);
if (draw_info->server_name != (char *) NULL)
draw_info->server_name=(char *)
RelinquishMagickMemory(draw_info->server_name);
if (draw_info->dash_pattern != (double *) NULL)
draw_info->dash_pattern=(double *) RelinquishMagickMemory(
draw_info->dash_pattern);
if (draw_info->gradient.stops != (StopInfo *) NULL)
draw_info->gradient.stops=(StopInfo *) RelinquishMagickMemory(
draw_info->gradient.stops);
if (draw_info->clip_mask != (char *) NULL)
draw_info->clip_mask=DestroyString(draw_info->clip_mask);
draw_info->signature=(~MagickSignature);
draw_info=(DrawInfo *) RelinquishMagickMemory(draw_info);
return(draw_info);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
+ D e s t r o y E d g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% DestroyEdge() destroys the specified polygon edge.
%
% The format of the DestroyEdge method is:
%
% ssize_t DestroyEdge(PolygonInfo *polygon_info,const int edge)
%
% A description of each parameter follows:
%
% o polygon_info: Specifies a pointer to an PolygonInfo structure.
%
% o edge: the polygon edge number to destroy.
%
*/
static size_t DestroyEdge(PolygonInfo *polygon_info,
const size_t edge)
{
assert(edge < polygon_info->number_edges);
polygon_info->edges[edge].points=(PointInfo *) RelinquishMagickMemory(
polygon_info->edges[edge].points);
polygon_info->number_edges--;
if (edge < polygon_info->number_edges)
(void) CopyMagickMemory(polygon_info->edges+edge,polygon_info->edges+edge+1,
(size_t) (polygon_info->number_edges-edge)*sizeof(*polygon_info->edges));
return(polygon_info->number_edges);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
+ D e s t r o y P o l y g o n I n f o %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% DestroyPolygonInfo() destroys the PolygonInfo data structure.
%
% The format of the DestroyPolygonInfo method is:
%
% PolygonInfo *DestroyPolygonInfo(PolygonInfo *polygon_info)
%
% A description of each parameter follows:
%
% o polygon_info: Specifies a pointer to an PolygonInfo structure.
%
*/
static PolygonInfo *DestroyPolygonInfo(PolygonInfo *polygon_info)
{
register ssize_t
i;
for (i=0; i < (ssize_t) polygon_info->number_edges; i++)
polygon_info->edges[i].points=(PointInfo *)
RelinquishMagickMemory(polygon_info->edges[i].points);
polygon_info->edges=(EdgeInfo *) RelinquishMagickMemory(polygon_info->edges);
return((PolygonInfo *) RelinquishMagickMemory(polygon_info));
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% D r a w A f f i n e I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% DrawAffineImage() composites the source over the destination image as
% dictated by the affine transform.
%
% The format of the DrawAffineImage method is:
%
% MagickBooleanType DrawAffineImage(Image *image,const Image *source,
% const AffineMatrix *affine)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o source: the source image.
%
% o affine: the affine transform.
%
*/
static SegmentInfo AffineEdge(const Image *image,const AffineMatrix *affine,
const double y,const SegmentInfo *edge)
{
double
intercept,
z;
register double
x;
SegmentInfo
inverse_edge;
/*
Determine left and right edges.
*/
inverse_edge.x1=edge->x1;
inverse_edge.y1=edge->y1;
inverse_edge.x2=edge->x2;
inverse_edge.y2=edge->y2;
z=affine->ry*y+affine->tx;
if (affine->sx > MagickEpsilon)
{
intercept=(-z/affine->sx);
x=intercept+MagickEpsilon;
if (x > inverse_edge.x1)
inverse_edge.x1=x;
intercept=(-z+(double) image->columns)/affine->sx;
x=intercept-MagickEpsilon;
if (x < inverse_edge.x2)
inverse_edge.x2=x;
}
else
if (affine->sx < -MagickEpsilon)
{
intercept=(-z+(double) image->columns)/affine->sx;
x=intercept+MagickEpsilon;
if (x > inverse_edge.x1)
inverse_edge.x1=x;
intercept=(-z/affine->sx);
x=intercept-MagickEpsilon;
if (x < inverse_edge.x2)
inverse_edge.x2=x;
}
else
if ((z < 0.0) || ((size_t) floor(z+0.5) >= image->columns))
{
inverse_edge.x2=edge->x1;
return(inverse_edge);
}
/*
Determine top and bottom edges.
*/
z=affine->sy*y+affine->ty;
if (affine->rx > MagickEpsilon)
{
intercept=(-z/affine->rx);
x=intercept+MagickEpsilon;
if (x > inverse_edge.x1)
inverse_edge.x1=x;
intercept=(-z+(double) image->rows)/affine->rx;
x=intercept-MagickEpsilon;
if (x < inverse_edge.x2)
inverse_edge.x2=x;
}
else
if (affine->rx < -MagickEpsilon)
{
intercept=(-z+(double) image->rows)/affine->rx;
x=intercept+MagickEpsilon;
if (x > inverse_edge.x1)
inverse_edge.x1=x;
intercept=(-z/affine->rx);
x=intercept-MagickEpsilon;
if (x < inverse_edge.x2)
inverse_edge.x2=x;
}
else
if ((z < 0.0) || ((size_t) floor(z+0.5) >= image->rows))
{
inverse_edge.x2=edge->x2;
return(inverse_edge);
}
return(inverse_edge);
}
static AffineMatrix InverseAffineMatrix(const AffineMatrix *affine)
{
AffineMatrix
inverse_affine;
double
determinant;
determinant=1.0/(affine->sx*affine->sy-affine->rx*affine->ry);
inverse_affine.sx=determinant*affine->sy;
inverse_affine.rx=determinant*(-affine->rx);
inverse_affine.ry=determinant*(-affine->ry);
inverse_affine.sy=determinant*affine->sx;
inverse_affine.tx=(-affine->tx)*inverse_affine.sx-affine->ty*
inverse_affine.ry;
inverse_affine.ty=(-affine->tx)*inverse_affine.rx-affine->ty*
inverse_affine.sy;
return(inverse_affine);
}
static inline ssize_t MagickAbsoluteValue(const ssize_t x)
{
if (x < 0)
return(-x);
return(x);
}
static inline double MagickMax(const double x,const double y)
{
if (x > y)
return(x);
return(y);
}
static inline double MagickMin(const double x,const double y)
{
if (x < y)
return(x);
return(y);
}
MagickExport MagickBooleanType DrawAffineImage(Image *image,
const Image *source,const AffineMatrix *affine)
{
AffineMatrix
inverse_affine;
CacheView
*image_view,
*source_view;
ExceptionInfo
*exception;
MagickBooleanType
status;
MagickPixelPacket
zero;
PointInfo
extent[4],
min,
max,
point;
register ssize_t
i;
SegmentInfo
edge;
ssize_t
y;
/*
Determine bounding box.
*/
assert(image != (Image *) NULL);
assert(image->signature == MagickSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
assert(source != (const Image *) NULL);
assert(source->signature == MagickSignature);
assert(affine != (AffineMatrix *) NULL);
extent[0].x=0.0;
extent[0].y=0.0;
extent[1].x=(double) source->columns-1.0;
extent[1].y=0.0;
extent[2].x=(double) source->columns-1.0;
extent[2].y=(double) source->rows-1.0;
extent[3].x=0.0;
extent[3].y=(double) source->rows-1.0;
for (i=0; i < 4; i++)
{
point=extent[i];
extent[i].x=point.x*affine->sx+point.y*affine->ry+affine->tx;
extent[i].y=point.x*affine->rx+point.y*affine->sy+affine->ty;
}
min=extent[0];
max=extent[0];
for (i=1; i < 4; i++)
{
if (min.x > extent[i].x)
min.x=extent[i].x;
if (min.y > extent[i].y)
min.y=extent[i].y;
if (max.x < extent[i].x)
max.x=extent[i].x;
if (max.y < extent[i].y)
max.y=extent[i].y;
}
/*
Affine transform image.
*/
if (SetImageStorageClass(image,DirectClass) == MagickFalse)
return(MagickFalse);
status=MagickTrue;
edge.x1=MagickMax(min.x,0.0);
edge.y1=MagickMax(min.y,0.0);
edge.x2=MagickMin(max.x,(double) image->columns-1.0);
edge.y2=MagickMin(max.y,(double) image->rows-1.0);
inverse_affine=InverseAffineMatrix(affine);
GetMagickPixelPacket(image,&zero);
exception=(&image->exception);
image_view=AcquireCacheView(image);
source_view=AcquireCacheView(source);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(dynamic,4) shared(status)
#endif
for (y=(ssize_t) ceil(edge.y1-0.5); y <= (ssize_t) floor(edge.y2+0.5); y++)
{
MagickPixelPacket
composite,
pixel;
PointInfo
point;
register IndexPacket
*restrict indexes;
register ssize_t
x;
register PixelPacket
*restrict q;
SegmentInfo
inverse_edge;
ssize_t
x_offset;
inverse_edge=AffineEdge(source,&inverse_affine,(double) y,&edge);
if (inverse_edge.x2 < inverse_edge.x1)
continue;
q=GetCacheViewAuthenticPixels(image_view,(ssize_t) ceil(inverse_edge.x1-
0.5),y,(size_t) ((ssize_t) floor(inverse_edge.x2+0.5)-(ssize_t) floor(
inverse_edge.x1+0.5)+1),1,exception);
if (q == (PixelPacket *) NULL)
continue;
indexes=GetCacheViewAuthenticIndexQueue(image_view);
pixel=zero;
composite=zero;
x_offset=0;
for (x=(ssize_t) ceil(inverse_edge.x1-0.5); x <= (ssize_t) floor(inverse_edge.x2+0.5); x++)
{
point.x=(double) x*inverse_affine.sx+y*inverse_affine.ry+
inverse_affine.tx;
point.y=(double) x*inverse_affine.rx+y*inverse_affine.sy+
inverse_affine.ty;
(void) InterpolateMagickPixelPacket(image,image_view,
UndefinedInterpolatePixel,point.x,point.y,&pixel,exception);
SetMagickPixelPacket(image,q,indexes+x_offset,&composite);
MagickPixelCompositeOver(&pixel,pixel.opacity,&composite,
composite.opacity,&composite);
SetPixelPacket(image,&composite,q,indexes+x_offset);
x_offset++;
q++;
}
if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
status=MagickFalse;
}
source_view=DestroyCacheView(source_view);
image_view=DestroyCacheView(image_view);
return(status);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
+ D r a w B o u n d i n g R e c t a n g l e s %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% DrawBoundingRectangles() draws the bounding rectangles on the image. This
% is only useful for developers debugging the rendering algorithm.
%
% The format of the DrawBoundingRectangles method is:
%
% void DrawBoundingRectangles(Image *image,const DrawInfo *draw_info,
% PolygonInfo *polygon_info)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o draw_info: the draw info.
%
% o polygon_info: Specifies a pointer to a PolygonInfo structure.
%
*/
static void DrawBoundingRectangles(Image *image,const DrawInfo *draw_info,
const PolygonInfo *polygon_info)
{
DrawInfo
*clone_info;
MagickRealType
mid;
PointInfo
end,
resolution,
start;
PrimitiveInfo
primitive_info[6];
register ssize_t
i;
SegmentInfo
bounds;
ssize_t
coordinates;
clone_info=CloneDrawInfo((ImageInfo *) NULL,draw_info);
(void) QueryColorDatabase("#0000",&clone_info->fill,&image->exception);
resolution.x=DefaultResolution;
resolution.y=DefaultResolution;
if (clone_info->density != (char *) NULL)
{
GeometryInfo
geometry_info;
MagickStatusType
flags;
flags=ParseGeometry(clone_info->density,&geometry_info);
resolution.x=geometry_info.rho;
resolution.y=geometry_info.sigma;
if ((flags & SigmaValue) == MagickFalse)
resolution.y=resolution.x;
}
mid=(resolution.x/72.0)*ExpandAffine(&clone_info->affine)*
clone_info->stroke_width/2.0;
bounds.x1=0.0;
bounds.y1=0.0;
bounds.x2=0.0;
bounds.y2=0.0;
if (polygon_info != (PolygonInfo *) NULL)
{
bounds=polygon_info->edges[0].bounds;
for (i=1; i < (ssize_t) polygon_info->number_edges; i++)
{
if (polygon_info->edges[i].bounds.x1 < (double) bounds.x1)
bounds.x1=polygon_info->edges[i].bounds.x1;
if (polygon_info->edges[i].bounds.y1 < (double) bounds.y1)
bounds.y1=polygon_info->edges[i].bounds.y1;
if (polygon_info->edges[i].bounds.x2 > (double) bounds.x2)
bounds.x2=polygon_info->edges[i].bounds.x2;
if (polygon_info->edges[i].bounds.y2 > (double) bounds.y2)
bounds.y2=polygon_info->edges[i].bounds.y2;
}
bounds.x1-=mid;
bounds.x1=bounds.x1 < 0.0 ? 0.0 : bounds.x1 >= (double)
image->columns ? (double) image->columns-1 : bounds.x1;
bounds.y1-=mid;
bounds.y1=bounds.y1 < 0.0 ? 0.0 : bounds.y1 >= (double)
image->rows ? (double) image->rows-1 : bounds.y1;
bounds.x2+=mid;
bounds.x2=bounds.x2 < 0.0 ? 0.0 : bounds.x2 >= (double)
image->columns ? (double) image->columns-1 : bounds.x2;
bounds.y2+=mid;
bounds.y2=bounds.y2 < 0.0 ? 0.0 : bounds.y2 >= (double)
image->rows ? (double) image->rows-1 : bounds.y2;
for (i=0; i < (ssize_t) polygon_info->number_edges; i++)
{
if (polygon_info->edges[i].direction != 0)
(void) QueryColorDatabase("red",&clone_info->stroke,
&image->exception);
else
(void) QueryColorDatabase("green",&clone_info->stroke,
&image->exception);
start.x=(double) (polygon_info->edges[i].bounds.x1-mid);
start.y=(double) (polygon_info->edges[i].bounds.y1-mid);
end.x=(double) (polygon_info->edges[i].bounds.x2+mid);
end.y=(double) (polygon_info->edges[i].bounds.y2+mid);
primitive_info[0].primitive=RectanglePrimitive;
TraceRectangle(primitive_info,start,end);
primitive_info[0].method=ReplaceMethod;
coordinates=(ssize_t) primitive_info[0].coordinates;
primitive_info[coordinates].primitive=UndefinedPrimitive;
(void) DrawPrimitive(image,clone_info,primitive_info);
}
}
(void) QueryColorDatabase("blue",&clone_info->stroke,&image->exception);
start.x=(double) (bounds.x1-mid);
start.y=(double) (bounds.y1-mid);
end.x=(double) (bounds.x2+mid);
end.y=(double) (bounds.y2+mid);
primitive_info[0].primitive=RectanglePrimitive;
TraceRectangle(primitive_info,start,end);
primitive_info[0].method=ReplaceMethod;
coordinates=(ssize_t) primitive_info[0].coordinates;
primitive_info[coordinates].primitive=UndefinedPrimitive;
(void) DrawPrimitive(image,clone_info,primitive_info);
clone_info=DestroyDrawInfo(clone_info);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% D r a w C l i p P a t h %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% DrawClipPath() draws the clip path on the image mask.
%
% The format of the DrawClipPath method is:
%
% MagickBooleanType DrawClipPath(Image *image,const DrawInfo *draw_info,
% const char *name)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o draw_info: the draw info.
%
% o name: the name of the clip path.
%
*/
MagickExport MagickBooleanType DrawClipPath(Image *image,
const DrawInfo *draw_info,const char *name)
{
char
clip_mask[MaxTextExtent];
const char
*value;
DrawInfo
*clone_info;
MagickStatusType
status;
assert(image != (Image *) NULL);
assert(image->signature == MagickSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
assert(draw_info != (const DrawInfo *) NULL);
(void) FormatMagickString(clip_mask,MaxTextExtent,"%s",name);
value=GetImageArtifact(image,clip_mask);
if (value == (const char *) NULL)
return(MagickFalse);
if (image->clip_mask == (Image *) NULL)
{
Image
*clip_mask;
clip_mask=CloneImage(image,image->columns,image->rows,MagickTrue,
&image->exception);
if (clip_mask == (Image *) NULL)
return(MagickFalse);
(void) SetImageClipMask(image,clip_mask);
clip_mask=DestroyImage(clip_mask);
}
(void) QueryColorDatabase("#00000000",&image->clip_mask->background_color,
&image->exception);
image->clip_mask->background_color.opacity=(Quantum) TransparentOpacity;
(void) SetImageBackgroundColor(image->clip_mask);
if (image->debug != MagickFalse)
(void) LogMagickEvent(DrawEvent,GetMagickModule(),"\nbegin clip-path %s",
draw_info->clip_mask);
clone_info=CloneDrawInfo((ImageInfo *) NULL,draw_info);
(void) CloneString(&clone_info->primitive,value);
(void) QueryColorDatabase("#ffffff",&clone_info->fill,&image->exception);
clone_info->clip_mask=(char *) NULL;
status=DrawImage(image->clip_mask,clone_info);
status|=NegateImage(image->clip_mask,MagickFalse);
clone_info=DestroyDrawInfo(clone_info);
if (image->debug != MagickFalse)
(void) LogMagickEvent(DrawEvent,GetMagickModule(),"end clip-path");
return(status != 0 ? MagickTrue : MagickFalse);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
+ D r a w D a s h P o l y g o n %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% DrawDashPolygon() draws a dashed polygon (line, rectangle, ellipse) on the
% image while respecting the dash offset and dash pattern attributes.
%
% The format of the DrawDashPolygon method is:
%
% MagickBooleanType DrawDashPolygon(const DrawInfo *draw_info,
% const PrimitiveInfo *primitive_info,Image *image)
%
% A description of each parameter follows:
%
% o draw_info: the draw info.
%
% o primitive_info: Specifies a pointer to a PrimitiveInfo structure.
%
% o image: the image.
%
%
*/
static MagickBooleanType DrawDashPolygon(const DrawInfo *draw_info,
const PrimitiveInfo *primitive_info,Image *image)
{
DrawInfo
*clone_info;
MagickRealType
length,
maximum_length,
offset,
scale,
total_length;
MagickStatusType
status;
PrimitiveInfo
*dash_polygon;
register ssize_t
i;
register MagickRealType
dx,
dy;
size_t
number_vertices;
ssize_t
j,
n;
assert(draw_info != (const DrawInfo *) NULL);
if (image->debug != MagickFalse)
(void) LogMagickEvent(DrawEvent,GetMagickModule()," begin draw-dash");
clone_info=CloneDrawInfo((ImageInfo *) NULL,draw_info);
clone_info->miterlimit=0;
for (i=0; primitive_info[i].primitive != UndefinedPrimitive; i++) ;
number_vertices=(size_t) i;
dash_polygon=(PrimitiveInfo *) AcquireQuantumMemory((size_t)
(2UL*number_vertices+1UL),sizeof(*dash_polygon));
if (dash_polygon == (PrimitiveInfo *) NULL)
return(MagickFalse);
dash_polygon[0]=primitive_info[0];
scale=ExpandAffine(&draw_info->affine);
length=scale*(draw_info->dash_pattern[0]-0.5);
offset=draw_info->dash_offset != 0.0 ? scale*draw_info->dash_offset : 0.0;
j=1;
for (n=0; offset > 0.0; j=0)
{
if (draw_info->dash_pattern[n] <= 0.0)
break;
length=scale*(draw_info->dash_pattern[n]+(n == 0 ? -0.5 : 0.5));
if (offset > length)
{
offset-=length;
n++;
length=scale*(draw_info->dash_pattern[n]+(n == 0 ? -0.5 : 0.5));
continue;
}
if (offset < length)
{
length-=offset;
offset=0.0;
break;
}
offset=0.0;
n++;
}
status=MagickTrue;
maximum_length=0.0;
total_length=0.0;
for (i=1; i < (ssize_t) number_vertices; i++)
{
dx=primitive_info[i].point.x-primitive_info[i-1].point.x;
dy=primitive_info[i].point.y-primitive_info[i-1].point.y;
maximum_length=hypot((double) dx,dy);
if (length == 0.0)
{
n++;
if (draw_info->dash_pattern[n] == 0.0)
n=0;
length=scale*(draw_info->dash_pattern[n]+(n == 0 ? -0.5 : 0.5));
}
for (total_length=0.0; (total_length+length) < maximum_length; )
{
total_length+=length;
if ((n & 0x01) != 0)
{
dash_polygon[0]=primitive_info[0];
dash_polygon[0].point.x=(double) (primitive_info[i-1].point.x+dx*
total_length/maximum_length);
dash_polygon[0].point.y=(double) (primitive_info[i-1].point.y+dy*
total_length/maximum_length);
j=1;
}
else
{
if ((j+1) > (ssize_t) (2*number_vertices))
break;
dash_polygon[j]=primitive_info[i-1];
dash_polygon[j].point.x=(double) (primitive_info[i-1].point.x+dx*
total_length/maximum_length);
dash_polygon[j].point.y=(double) (primitive_info[i-1].point.y+dy*
total_length/maximum_length);
dash_polygon[j].coordinates=1;
j++;
dash_polygon[0].coordinates=(size_t) j;
dash_polygon[j].primitive=UndefinedPrimitive;
status|=DrawStrokePolygon(image,clone_info,dash_polygon);
}
n++;
if (draw_info->dash_pattern[n] == 0.0)
n=0;
length=scale*(draw_info->dash_pattern[n]+(n == 0 ? -0.5 : 0.5));
}
length-=(maximum_length-total_length);
if ((n & 0x01) != 0)
continue;
dash_polygon[j]=primitive_info[i];
dash_polygon[j].coordinates=1;
j++;
}
if ((total_length < maximum_length) && ((n & 0x01) == 0) && (j > 1))
{
dash_polygon[j]=primitive_info[i-1];
dash_polygon[j].point.x+=MagickEpsilon;
dash_polygon[j].point.y+=MagickEpsilon;
dash_polygon[j].coordinates=1;
j++;
dash_polygon[0].coordinates=(size_t) j;
dash_polygon[j].primitive=UndefinedPrimitive;
status|=DrawStrokePolygon(image,clone_info,dash_polygon);
}
dash_polygon=(PrimitiveInfo *) RelinquishMagickMemory(dash_polygon);
clone_info=DestroyDrawInfo(clone_info);
if (image->debug != MagickFalse)
(void) LogMagickEvent(DrawEvent,GetMagickModule()," end draw-dash");
return(status != 0 ? MagickTrue : MagickFalse);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% D r a w I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% DrawImage() draws a graphic primitive on your image. The primitive
% may be represented as a string or filename. Precede the filename with an
% "at" sign (@) and the contents of the file are drawn on the image. You
% can affect how text is drawn by setting one or more members of the draw
% info structure.
%
% The format of the DrawImage method is:
%
% MagickBooleanType DrawImage(Image *image,const DrawInfo *draw_info)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o draw_info: the draw info.
%
*/
static inline MagickBooleanType IsPoint(const char *point)
{
char
*p;
double
value;
value=strtod(point,&p);
return((value == 0.0) && (p == point) ? MagickFalse : MagickTrue);
}
static inline void TracePoint(PrimitiveInfo *primitive_info,
const PointInfo point)
{
primitive_info->coordinates=1;
primitive_info->point=point;
}
MagickExport MagickBooleanType DrawImage(Image *image,const DrawInfo *draw_info)
{
#define RenderImageTag "Render/Image"
AffineMatrix
affine,
current;
char
key[2*MaxTextExtent],
keyword[MaxTextExtent],
geometry[MaxTextExtent],
name[MaxTextExtent],
pattern[MaxTextExtent],
*primitive,
*token;
const char
*q;
DrawInfo
**graphic_context;
MagickBooleanType
proceed,
status;
MagickRealType
angle,
factor,
primitive_extent;
PointInfo
point;
PixelPacket
start_color;
PrimitiveInfo
*primitive_info;
PrimitiveType
primitive_type;
register const char
*p;
register ssize_t
i,
x;
SegmentInfo
bounds;
size_t
length,
number_points;
ssize_t
j,
k,
n;
/*
Ensure the annotation info is valid.
*/
assert(image != (Image *) NULL);
assert(image->signature == MagickSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
assert(draw_info != (DrawInfo *) NULL);
assert(draw_info->signature == MagickSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"...");
if ((draw_info->primitive == (char *) NULL) ||
(*draw_info->primitive == '\0'))
return(MagickFalse);
if (image->debug != MagickFalse)
(void) LogMagickEvent(DrawEvent,GetMagickModule(),"begin draw-image");
if (*draw_info->primitive != '@')
primitive=AcquireString(draw_info->primitive);
else
primitive=FileToString(draw_info->primitive+1,~0,&image->exception);
if (primitive == (char *) NULL)
return(MagickFalse);
primitive_extent=(MagickRealType) strlen(primitive);
(void) SetImageArtifact(image,"MVG",primitive);
n=0;
/*
Allocate primitive info memory.
*/
graphic_context=(DrawInfo **) AcquireMagickMemory(
sizeof(*graphic_context));
if (graphic_context == (DrawInfo **) NULL)
{
primitive=DestroyString(primitive);
ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
image->filename);
}
number_points=2047;
primitive_info=(PrimitiveInfo *) AcquireQuantumMemory((size_t) number_points,
sizeof(*primitive_info));
if (primitive_info == (PrimitiveInfo *) NULL)
{
primitive=DestroyString(primitive);
for ( ; n >= 0; n--)
graphic_context[n]=DestroyDrawInfo(graphic_context[n]);
graphic_context=(DrawInfo **) RelinquishMagickMemory(graphic_context);
ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
image->filename);
}
graphic_context[n]=CloneDrawInfo((ImageInfo *) NULL,draw_info);
graphic_context[n]->viewbox=image->page;
if ((image->page.width == 0) || (image->page.height == 0))
{
graphic_context[n]->viewbox.width=image->columns;
graphic_context[n]->viewbox.height=image->rows;
}
token=AcquireString(primitive);
(void) QueryColorDatabase("#000000",&start_color,&image->exception);
if (SetImageStorageClass(image,DirectClass) == MagickFalse)
return(MagickFalse);
status=MagickTrue;
for (q=primitive; *q != '\0'; )
{
/*
Interpret graphic primitive.
*/
GetMagickToken(q,&q,keyword);
if (*keyword == '\0')
break;
if (*keyword == '#')
{
/*
Comment.
*/
while ((*q != '\n') && (*q != '\0'))
q++;
continue;
}
p=q-strlen(keyword)-1;
primitive_type=UndefinedPrimitive;
current=graphic_context[n]->affine;
GetAffineMatrix(&affine);
switch (*keyword)
{
case ';':
break;
case 'a':
case 'A':
{
if (LocaleCompare("affine",keyword) == 0)
{
GetMagickToken(q,&q,token);
affine.sx=StringToDouble(token);
GetMagickToken(q,&q,token);
if (*token == ',')
GetMagickToken(q,&q,token);
affine.rx=StringToDouble(token);
GetMagickToken(q,&q,token);
if (*token == ',')
GetMagickToken(q,&q,token);
affine.ry=StringToDouble(token);
GetMagickToken(q,&q,token);
if (*token == ',')
GetMagickToken(q,&q,token);
affine.sy=StringToDouble(token);
GetMagickToken(q,&q,token);
if (*token == ',')
GetMagickToken(q,&q,token);
affine.tx=StringToDouble(token);
GetMagickToken(q,&q,token);
if (*token == ',')
GetMagickToken(q,&q,token);
affine.ty=StringToDouble(token);
break;
}
if (LocaleCompare("arc",keyword) == 0)
{
primitive_type=ArcPrimitive;
break;
}
status=MagickFalse;
break;
}
case 'b':
case 'B':
{
if (LocaleCompare("bezier",keyword) == 0)
{
primitive_type=BezierPrimitive;
break;
}
if (LocaleCompare("border-color",keyword) == 0)
{
GetMagickToken(q,&q,token);
(void) QueryColorDatabase(token,&graphic_context[n]->border_color,
&image->exception);
break;
}
status=MagickFalse;
break;
}
case 'c':
case 'C':
{
if (LocaleCompare("clip-path",keyword) == 0)
{
/*
Create clip mask.
*/
GetMagickToken(q,&q,token);
(void) CloneString(&graphic_context[n]->clip_mask,token);
(void) DrawClipPath(image,graphic_context[n],
graphic_context[n]->clip_mask);
break;
}
if (LocaleCompare("clip-rule",keyword) == 0)
{
ssize_t
fill_rule;
GetMagickToken(q,&q,token);
fill_rule=ParseMagickOption(MagickFillRuleOptions,MagickFalse,
token);
if (fill_rule == -1)
{
status=MagickFalse;
break;
}
graphic_context[n]->fill_rule=(FillRule) fill_rule;
break;
}
if (LocaleCompare("clip-units",keyword) == 0)
{
ssize_t
clip_units;
GetMagickToken(q,&q,token);
clip_units=ParseMagickOption(MagickClipPathOptions,MagickFalse,
token);
if (clip_units == -1)
{
status=MagickFalse;
break;
}
graphic_context[n]->clip_units=(ClipPathUnits) clip_units;
if (clip_units == ObjectBoundingBox)
{
GetAffineMatrix(¤t);
affine.sx=draw_info->bounds.x2;
affine.sy=draw_info->bounds.y2;
affine.tx=draw_info->bounds.x1;
affine.ty=draw_info->bounds.y1;
break;
}
break;
}
if (LocaleCompare("circle",keyword) == 0)
{
primitive_type=CirclePrimitive;
break;
}
if (LocaleCompare("color",keyword) == 0)
{
primitive_type=ColorPrimitive;
break;
}
status=MagickFalse;
break;
}
case 'd':
case 'D':
{
if (LocaleCompare("decorate",keyword) == 0)
{
ssize_t
decorate;
GetMagickToken(q,&q,token);
decorate=ParseMagickOption(MagickDecorateOptions,MagickFalse,
token);
if (decorate == -1)
{
status=MagickFalse;
break;
}
graphic_context[n]->decorate=(DecorationType) decorate;
break;
}
status=MagickFalse;
break;
}
case 'e':
case 'E':
{
if (LocaleCompare("ellipse",keyword) == 0)
{
primitive_type=EllipsePrimitive;
break;
}
if (LocaleCompare("encoding",keyword) == 0)
{
GetMagickToken(q,&q,token);
(void) CloneString(&graphic_context[n]->encoding,token);
break;
}
status=MagickFalse;
break;
}
case 'f':
case 'F':
{
if (LocaleCompare("fill",keyword) == 0)
{
GetMagickToken(q,&q,token);
(void) FormatMagickString(pattern,MaxTextExtent,"%s",token);
if (GetImageArtifact(image,pattern) != (const char *) NULL)
(void) DrawPatternPath(image,draw_info,token,
&graphic_context[n]->fill_pattern);
else
{
status=QueryColorDatabase(token,&graphic_context[n]->fill,
&image->exception);
if (status == MagickFalse)
{
ImageInfo
*pattern_info;
pattern_info=AcquireImageInfo();
(void) CopyMagickString(pattern_info->filename,token,
MaxTextExtent);
graphic_context[n]->fill_pattern=
ReadImage(pattern_info,&image->exception);
CatchException(&image->exception);
pattern_info=DestroyImageInfo(pattern_info);
}
}
break;
}
if (LocaleCompare("fill-opacity",keyword) == 0)
{
GetMagickToken(q,&q,token);
factor=strchr(token,'%') != (char *) NULL ? 0.01 : 1.0;
graphic_context[n]->fill.opacity=ClampToQuantum((MagickRealType)
QuantumRange*(1.0-factor*StringToDouble(token)));
break;
}
if (LocaleCompare("fill-rule",keyword) == 0)
{
ssize_t
fill_rule;
GetMagickToken(q,&q,token);
fill_rule=ParseMagickOption(MagickFillRuleOptions,MagickFalse,
token);
if (fill_rule == -1)
{
status=MagickFalse;
break;
}
graphic_context[n]->fill_rule=(FillRule) fill_rule;
break;
}
if (LocaleCompare("font",keyword) == 0)
{
GetMagickToken(q,&q,token);
(void) CloneString(&graphic_context[n]->font,token);
if (LocaleCompare("none",token) == 0)
graphic_context[n]->font=(char *)
RelinquishMagickMemory(graphic_context[n]->font);
break;
}
if (LocaleCompare("font-family",keyword) == 0)
{
GetMagickToken(q,&q,token);
(void) CloneString(&graphic_context[n]->family,token);
break;
}
if (LocaleCompare("font-size",keyword) == 0)
{
GetMagickToken(q,&q,token);
graphic_context[n]->pointsize=StringToDouble(token);
break;
}
if (LocaleCompare("font-stretch",keyword) == 0)
{
ssize_t
stretch;
GetMagickToken(q,&q,token);
stretch=ParseMagickOption(MagickStretchOptions,MagickFalse,token);
if (stretch == -1)
{
status=MagickFalse;
break;
}
graphic_context[n]->stretch=(StretchType) stretch;
break;
}
if (LocaleCompare("font-style",keyword) == 0)
{
ssize_t
style;
GetMagickToken(q,&q,token);
style=ParseMagickOption(MagickStyleOptions,MagickFalse,token);
if (style == -1)
{
status=MagickFalse;
break;
}
graphic_context[n]->style=(StyleType) style;
break;
}
if (LocaleCompare("font-weight",keyword) == 0)
{
GetMagickToken(q,&q,token);
graphic_context[n]->weight=StringToUnsignedLong(token);
if (LocaleCompare(token,"all") == 0)
graphic_context[n]->weight=0;
if (LocaleCompare(token,"bold") == 0)
graphic_context[n]->weight=700;
if (LocaleCompare(token,"bolder") == 0)
if (graphic_context[n]->weight <= 800)
graphic_context[n]->weight+=100;
if (LocaleCompare(token,"lighter") == 0)
if (graphic_context[n]->weight >= 100)
graphic_context[n]->weight-=100;
if (LocaleCompare(token,"normal") == 0)
graphic_context[n]->weight=400;
break;
}
status=MagickFalse;
break;
}
case 'g':
case 'G':
{
if (LocaleCompare("gradient-units",keyword) == 0)
{
GetMagickToken(q,&q,token);
break;
}
if (LocaleCompare("gravity",keyword) == 0)
{
ssize_t
gravity;
GetMagickToken(q,&q,token);
gravity=ParseMagickOption(MagickGravityOptions,MagickFalse,token);
if (gravity == -1)
{
status=MagickFalse;
break;
}
graphic_context[n]->gravity=(GravityType) gravity;
break;
}
status=MagickFalse;
break;
}
case 'i':
case 'I':
{
if (LocaleCompare("image",keyword) == 0)
{
ssize_t
compose;
primitive_type=ImagePrimitive;
GetMagickToken(q,&q,token);
compose=ParseMagickOption(MagickComposeOptions,MagickFalse,token);
if (compose == -1)
{
status=MagickFalse;
break;
}
graphic_context[n]->compose=(CompositeOperator) compose;
break;
}
if (LocaleCompare("interline-spacing",keyword) == 0)
{
GetMagickToken(q,&q,token);
graphic_context[n]->interline_spacing=StringToDouble(token);
break;
}
if (LocaleCompare("interword-spacing",keyword) == 0)
{
GetMagickToken(q,&q,token);
graphic_context[n]->interword_spacing=StringToDouble(token);
break;
}
status=MagickFalse;
break;
}
case 'k':
case 'K':
{
if (LocaleCompare("kerning",keyword) == 0)
{
GetMagickToken(q,&q,token);
graphic_context[n]->kerning=StringToDouble(token);
break;
}
status=MagickFalse;
break;
}
case 'l':
case 'L':
{
if (LocaleCompare("line",keyword) == 0)
{
primitive_type=LinePrimitive;
break;
}
status=MagickFalse;
break;
}
case 'm':
case 'M':
{
if (LocaleCompare("matte",keyword) == 0)
{
primitive_type=MattePrimitive;
break;
}
status=MagickFalse;
break;
}
case 'o':
case 'O':
{
if (LocaleCompare("offset",keyword) == 0)
{
GetMagickToken(q,&q,token);
break;
}
if (LocaleCompare("opacity",keyword) == 0)
{
GetMagickToken(q,&q,token);
factor=strchr(token,'%') != (char *) NULL ? 0.01 : 1.0;
graphic_context[n]->opacity=ClampToQuantum((MagickRealType)
QuantumRange*(1.0-((1.0-QuantumScale*graphic_context[n]->opacity)*
factor*StringToDouble(token))));
graphic_context[n]->fill.opacity=graphic_context[n]->opacity;
graphic_context[n]->stroke.opacity=graphic_context[n]->opacity;
break;
}
status=MagickFalse;
break;
}
case 'p':
case 'P':
{
if (LocaleCompare("path",keyword) == 0)
{
primitive_type=PathPrimitive;
break;
}
if (LocaleCompare("point",keyword) == 0)
{
primitive_type=PointPrimitive;
break;
}
if (LocaleCompare("polyline",keyword) == 0)
{
primitive_type=PolylinePrimitive;
break;
}
if (LocaleCompare("polygon",keyword) == 0)
{
primitive_type=PolygonPrimitive;
break;
}
if (LocaleCompare("pop",keyword) == 0)
{
GetMagickToken(q,&q,token);
if (LocaleCompare("clip-path",token) == 0)
break;
if (LocaleCompare("defs",token) == 0)
break;
if (LocaleCompare("gradient",token) == 0)
break;
if (LocaleCompare("graphic-context",token) == 0)
{
if (n <= 0)
{
(void) ThrowMagickException(&image->exception,
GetMagickModule(),DrawError,
"UnbalancedGraphicContextPushPop","`%s'",token);
n=0;
break;
}
if (graphic_context[n]->clip_mask != (char *) NULL)
if (LocaleCompare(graphic_context[n]->clip_mask,
graphic_context[n-1]->clip_mask) != 0)
(void) SetImageClipMask(image,(Image *) NULL);
graphic_context[n]=DestroyDrawInfo(graphic_context[n]);
n--;
break;
}
if (LocaleCompare("pattern",token) == 0)
break;
status=MagickFalse;
break;
}
if (LocaleCompare("push",keyword) == 0)
{
GetMagickToken(q,&q,token);
if (LocaleCompare("clip-path",token) == 0)
{
char
name[MaxTextExtent];
GetMagickToken(q,&q,token);
(void) FormatMagickString(name,MaxTextExtent,"%s",token);
for (p=q; *q != '\0'; )
{
GetMagickToken(q,&q,token);
if (LocaleCompare(token,"pop") != 0)
continue;
GetMagickToken(q,(const char **) NULL,token);
if (LocaleCompare(token,"clip-path") != 0)
continue;
break;
}
(void) CopyMagickString(token,p,(size_t) (q-p-4+1));
(void) SetImageArtifact(image,name,token);
GetMagickToken(q,&q,token);
break;
}
if (LocaleCompare("gradient",token) == 0)
{
char
key[2*MaxTextExtent],
name[MaxTextExtent],
type[MaxTextExtent];
SegmentInfo
segment;
GetMagickToken(q,&q,token);
(void) CopyMagickString(name,token,MaxTextExtent);
GetMagickToken(q,&q,token);
(void) CopyMagickString(type,token,MaxTextExtent);
GetMagickToken(q,&q,token);
segment.x1=StringToDouble(token);
GetMagickToken(q,&q,token);
if (*token == ',')
GetMagickToken(q,&q,token);
segment.y1=StringToDouble(token);
GetMagickToken(q,&q,token);
if (*token == ',')
GetMagickToken(q,&q,token);
segment.x2=StringToDouble(token);
GetMagickToken(q,&q,token);
if (*token == ',')
GetMagickToken(q,&q,token);
segment.y2=StringToDouble(token);
if (LocaleCompare(type,"radial") == 0)
{
GetMagickToken(q,&q,token);
if (*token == ',')
GetMagickToken(q,&q,token);
}
for (p=q; *q != '\0'; )
{
GetMagickToken(q,&q,token);
if (LocaleCompare(token,"pop") != 0)
continue;
GetMagickToken(q,(const char **) NULL,token);
if (LocaleCompare(token,"gradient") != 0)
continue;
break;
}
(void) CopyMagickString(token,p,(size_t) (q-p-4+1));
bounds.x1=graphic_context[n]->affine.sx*segment.x1+
graphic_context[n]->affine.ry*segment.y1+
graphic_context[n]->affine.tx;
bounds.y1=graphic_context[n]->affine.rx*segment.x1+
graphic_context[n]->affine.sy*segment.y1+
graphic_context[n]->affine.ty;
bounds.x2=graphic_context[n]->affine.sx*segment.x2+
graphic_context[n]->affine.ry*segment.y2+
graphic_context[n]->affine.tx;
bounds.y2=graphic_context[n]->affine.rx*segment.x2+
graphic_context[n]->affine.sy*segment.y2+
graphic_context[n]->affine.ty;
(void) FormatMagickString(key,MaxTextExtent,"%s",name);
(void) SetImageArtifact(image,key,token);
(void) FormatMagickString(key,MaxTextExtent,"%s-geometry",name);
(void) FormatMagickString(geometry,MaxTextExtent,
"%gx%g%+.15g%+.15g",
MagickMax(fabs(bounds.x2-bounds.x1+1.0),1.0),
MagickMax(fabs(bounds.y2-bounds.y1+1.0),1.0),
bounds.x1,bounds.y1);
(void) SetImageArtifact(image,key,geometry);
GetMagickToken(q,&q,token);
break;
}
if (LocaleCompare("pattern",token) == 0)
{
RectangleInfo
bounds;
GetMagickToken(q,&q,token);
(void) CopyMagickString(name,token,MaxTextExtent);
GetMagickToken(q,&q,token);
bounds.x=(ssize_t) ceil(StringToDouble(token)-0.5);
GetMagickToken(q,&q,token);
if (*token == ',')
GetMagickToken(q,&q,token);
bounds.y=(ssize_t) ceil(StringToDouble(token)-0.5);
GetMagickToken(q,&q,token);
if (*token == ',')
GetMagickToken(q,&q,token);
bounds.width=(size_t) floor(StringToDouble(token)+0.5);
GetMagickToken(q,&q,token);
if (*token == ',')
GetMagickToken(q,&q,token);
bounds.height=(size_t) floor(StringToDouble(token)+0.5);
for (p=q; *q != '\0'; )
{
GetMagickToken(q,&q,token);
if (LocaleCompare(token,"pop") != 0)
continue;
GetMagickToken(q,(const char **) NULL,token);
if (LocaleCompare(token,"pattern") != 0)
continue;
break;
}
(void) CopyMagickString(token,p,(size_t) (q-p-4+1));
(void) FormatMagickString(key,MaxTextExtent,"%s",name);
(void) SetImageArtifact(image,key,token);
(void) FormatMagickString(key,MaxTextExtent,"%s-geometry",name);
(void) FormatMagickString(geometry,MaxTextExtent,
"%.20gx%.20g%+.20g%+.20g",(double) bounds.width,(double)
bounds.height,(double) bounds.x,(double) bounds.y);
(void) SetImageArtifact(image,key,geometry);
GetMagickToken(q,&q,token);
break;
}
if (LocaleCompare("graphic-context",token) == 0)
{
n++;
graphic_context=(DrawInfo **) ResizeQuantumMemory(
graphic_context,(size_t) (n+1),sizeof(*graphic_context));
if (graphic_context == (DrawInfo **) NULL)
{
(void) ThrowMagickException(&image->exception,
GetMagickModule(),ResourceLimitError,
"MemoryAllocationFailed","`%s'",image->filename);
break;
}
graphic_context[n]=CloneDrawInfo((ImageInfo *) NULL,
graphic_context[n-1]);
break;
}
if (LocaleCompare("defs",token) == 0)
break;
status=MagickFalse;
break;
}
status=MagickFalse;
break;
}
case 'r':
case 'R':
{
if (LocaleCompare("rectangle",keyword) == 0)
{
primitive_type=RectanglePrimitive;
break;
}
if (LocaleCompare("rotate",keyword) == 0)
{
GetMagickToken(q,&q,token);
angle=StringToDouble(token);
affine.sx=cos(DegreesToRadians(fmod((double) angle,360.0)));
affine.rx=sin(DegreesToRadians(fmod((double) angle,360.0)));
affine.ry=(-sin(DegreesToRadians(fmod((double) angle,360.0))));
affine.sy=cos(DegreesToRadians(fmod((double) angle,360.0)));
break;
}
if (LocaleCompare("roundRectangle",keyword) == 0)
{
primitive_type=RoundRectanglePrimitive;
break;
}
status=MagickFalse;
break;
}
case 's':
case 'S':
{
if (LocaleCompare("scale",keyword) == 0)
{
GetMagickToken(q,&q,token);
affine.sx=StringToDouble(token);
GetMagickToken(q,&q,token);
if (*token == ',')
GetMagickToken(q,&q,token);
affine.sy=StringToDouble(token);
break;
}
if (LocaleCompare("skewX",keyword) == 0)
{
GetMagickToken(q,&q,token);
angle=StringToDouble(token);
affine.ry=sin(DegreesToRadians(angle));
break;
}
if (LocaleCompare("skewY",keyword) == 0)
{
GetMagickToken(q,&q,token);
angle=StringToDouble(token);
affine.rx=(-tan(DegreesToRadians(angle)/2.0));
break;
}
if (LocaleCompare("stop-color",keyword) == 0)
{
PixelPacket
stop_color;
GetMagickToken(q,&q,token);
(void) QueryColorDatabase(token,&stop_color,&image->exception);
(void) GradientImage(image,LinearGradient,ReflectSpread,
&start_color,&stop_color);
start_color=stop_color;
GetMagickToken(q,&q,token);
break;
}
if (LocaleCompare("stroke",keyword) == 0)
{
GetMagickToken(q,&q,token);
(void) FormatMagickString(pattern,MaxTextExtent,"%s",token);
if (GetImageArtifact(image,pattern) != (const char *) NULL)
(void) DrawPatternPath(image,draw_info,token,
&graphic_context[n]->stroke_pattern);
else
{
status=QueryColorDatabase(token,&graphic_context[n]->stroke,
&image->exception);
if (status == MagickFalse)
{
ImageInfo
*pattern_info;
pattern_info=AcquireImageInfo();
(void) CopyMagickString(pattern_info->filename,token,
MaxTextExtent);
graphic_context[n]->stroke_pattern=
ReadImage(pattern_info,&image->exception);
CatchException(&image->exception);
pattern_info=DestroyImageInfo(pattern_info);
}
}
break;
}
if (LocaleCompare("stroke-antialias",keyword) == 0)
{
GetMagickToken(q,&q,token);
graphic_context[n]->stroke_antialias=
StringToLong(token) != 0 ? MagickTrue : MagickFalse;
break;
}
if (LocaleCompare("stroke-dasharray",keyword) == 0)
{
if (graphic_context[n]->dash_pattern != (double *) NULL)
graphic_context[n]->dash_pattern=(double *)
RelinquishMagickMemory(graphic_context[n]->dash_pattern);
if (IsPoint(q) != MagickFalse)
{
const char
*p;
p=q;
GetMagickToken(p,&p,token);
if (*token == ',')
GetMagickToken(p,&p,token);
for (x=0; IsPoint(token) != MagickFalse; x++)
{
GetMagickToken(p,&p,token);
if (*token == ',')
GetMagickToken(p,&p,token);
}
graphic_context[n]->dash_pattern=(double *)
AcquireQuantumMemory((size_t) (2UL*x+1UL),
sizeof(*graphic_context[n]->dash_pattern));
if (graphic_context[n]->dash_pattern == (double *) NULL)
{
(void) ThrowMagickException(&image->exception,
GetMagickModule(),ResourceLimitError,
"MemoryAllocationFailed","`%s'",image->filename);
break;
}
for (j=0; j < x; j++)
{
GetMagickToken(q,&q,token);
if (*token == ',')
GetMagickToken(q,&q,token);
graphic_context[n]->dash_pattern[j]=StringToDouble(token);
}
if ((x & 0x01) != 0)
for ( ; j < (2*x); j++)
graphic_context[n]->dash_pattern[j]=
graphic_context[n]->dash_pattern[j-x];
graphic_context[n]->dash_pattern[j]=0.0;
break;
}
GetMagickToken(q,&q,token);
break;
}
if (LocaleCompare("stroke-dashoffset",keyword) == 0)
{
GetMagickToken(q,&q,token);
graphic_context[n]->dash_offset=StringToDouble(token);
break;
}
if (LocaleCompare("stroke-linecap",keyword) == 0)
{
ssize_t
linecap;
GetMagickToken(q,&q,token);
linecap=ParseMagickOption(MagickLineCapOptions,MagickFalse,token);
if (linecap == -1)
{
status=MagickFalse;
break;
}
graphic_context[n]->linecap=(LineCap) linecap;
break;
}
if (LocaleCompare("stroke-linejoin",keyword) == 0)
{
ssize_t
linejoin;
GetMagickToken(q,&q,token);
linejoin=ParseMagickOption(MagickLineJoinOptions,MagickFalse,token);
if (linejoin == -1)
{
status=MagickFalse;
break;
}
graphic_context[n]->linejoin=(LineJoin) linejoin;
break;
}
if (LocaleCompare("stroke-miterlimit",keyword) == 0)
{
GetMagickToken(q,&q,token);
graphic_context[n]->miterlimit=StringToUnsignedLong(token);
break;
}
if (LocaleCompare("stroke-opacity",keyword) == 0)
{
GetMagickToken(q,&q,token);
factor=strchr(token,'%') != (char *) NULL ? 0.01 : 1.0;
graphic_context[n]->stroke.opacity=ClampToQuantum((MagickRealType)
QuantumRange*(1.0-factor*StringToDouble(token)));
break;
}
if (LocaleCompare("stroke-width",keyword) == 0)
{
GetMagickToken(q,&q,token);
graphic_context[n]->stroke_width=StringToDouble(token);
break;
}
status=MagickFalse;
break;
}
case 't':
case 'T':
{
if (LocaleCompare("text",keyword) == 0)
{
primitive_type=TextPrimitive;
break;
}
if (LocaleCompare("text-align",keyword) == 0)
{
ssize_t
align;
GetMagickToken(q,&q,token);
align=ParseMagickOption(MagickAlignOptions,MagickFalse,token);
if (align == -1)
{
status=MagickFalse;
break;
}
graphic_context[n]->align=(AlignType) align;
break;
}
if (LocaleCompare("text-anchor",keyword) == 0)
{
ssize_t
align;
GetMagickToken(q,&q,token);
align=ParseMagickOption(MagickAlignOptions,MagickFalse,token);
if (align == -1)
{
status=MagickFalse;
break;
}
graphic_context[n]->align=(AlignType) align;
break;
}
if (LocaleCompare("text-antialias",keyword) == 0)
{
GetMagickToken(q,&q,token);
graphic_context[n]->text_antialias=
StringToLong(token) != 0 ? MagickTrue : MagickFalse;
break;
}
if (LocaleCompare("text-undercolor",keyword) == 0)
{
GetMagickToken(q,&q,token);
(void) QueryColorDatabase(token,&graphic_context[n]->undercolor,
&image->exception);
break;
}
if (LocaleCompare("translate",keyword) == 0)
{
GetMagickToken(q,&q,token);
affine.tx=StringToDouble(token);
GetMagickToken(q,&q,token);
if (*token == ',')
GetMagickToken(q,&q,token);
affine.ty=StringToDouble(token);
break;
}
status=MagickFalse;
break;
}
case 'v':
case 'V':
{
if (LocaleCompare("viewbox",keyword) == 0)
{
GetMagickToken(q,&q,token);
graphic_context[n]->viewbox.x=(ssize_t) ceil(StringToDouble(token)-
0.5);
GetMagickToken(q,&q,token);
if (*token == ',')
GetMagickToken(q,&q,token);
graphic_context[n]->viewbox.y=(ssize_t) ceil(StringToDouble(token)-
0.5);
GetMagickToken(q,&q,token);
if (*token == ',')
GetMagickToken(q,&q,token);
graphic_context[n]->viewbox.width=(size_t) floor(
StringToDouble(token)+0.5);
GetMagickToken(q,&q,token);
if (*token == ',')
GetMagickToken(q,&q,token);
graphic_context[n]->viewbox.height=(size_t) floor(
StringToDouble(token)+0.5);
break;
}
status=MagickFalse;
break;
}
default:
{
status=MagickFalse;
break;
}
}
if (status == MagickFalse)
break;
if ((affine.sx != 1.0) || (affine.rx != 0.0) || (affine.ry != 0.0) ||
(affine.sy != 1.0) || (affine.tx != 0.0) || (affine.ty != 0.0))
{
graphic_context[n]->affine.sx=current.sx*affine.sx+current.ry*affine.rx;
graphic_context[n]->affine.rx=current.rx*affine.sx+current.sy*affine.rx;
graphic_context[n]->affine.ry=current.sx*affine.ry+current.ry*affine.sy;
graphic_context[n]->affine.sy=current.rx*affine.ry+current.sy*affine.sy;
graphic_context[n]->affine.tx=current.sx*affine.tx+current.ry*affine.ty+
current.tx;
graphic_context[n]->affine.ty=current.rx*affine.tx+current.sy*affine.ty+
current.ty;
}
if (primitive_type == UndefinedPrimitive)
{
if (image->debug != MagickFalse)
(void) LogMagickEvent(DrawEvent,GetMagickModule()," %.*s",
(int) (q-p),p);
continue;
}
/*
Parse the primitive attributes.
*/
i=0;
j=0;
primitive_info[0].point.x=0.0;
primitive_info[0].point.y=0.0;
for (x=0; *q != '\0'; x++)
{
/*
Define points.
*/
if (IsPoint(q) == MagickFalse)
break;
GetMagickToken(q,&q,token);
point.x=StringToDouble(token);
GetMagickToken(q,&q,token);
if (*token == ',')
GetMagickToken(q,&q,token);
point.y=StringToDouble(token);
GetMagickToken(q,(const char **) NULL,token);
if (*token == ',')
GetMagickToken(q,&q,token);
primitive_info[i].primitive=primitive_type;
primitive_info[i].point=point;
primitive_info[i].coordinates=0;
primitive_info[i].method=FloodfillMethod;
i++;
if (i < (ssize_t) number_points)
continue;
number_points<<=1;
primitive_info=(PrimitiveInfo *) ResizeQuantumMemory(primitive_info,
(size_t) number_points,sizeof(*primitive_info));
if (primitive_info == (PrimitiveInfo *) NULL)
{
(void) ThrowMagickException(&image->exception,GetMagickModule(),
ResourceLimitError,"MemoryAllocationFailed","`%s'",image->filename);
break;
}
}
primitive_info[j].primitive=primitive_type;
primitive_info[j].coordinates=(size_t) x;
primitive_info[j].method=FloodfillMethod;
primitive_info[j].text=(char *) NULL;
/*
Circumscribe primitive within a circle.
*/
bounds.x1=primitive_info[j].point.x;
bounds.y1=primitive_info[j].point.y;
bounds.x2=primitive_info[j].point.x;
bounds.y2=primitive_info[j].point.y;
for (k=1; k < (ssize_t) primitive_info[j].coordinates; k++)
{
point=primitive_info[j+k].point;
if (point.x < bounds.x1)
bounds.x1=point.x;
if (point.y < bounds.y1)
bounds.y1=point.y;
if (point.x > bounds.x2)
bounds.x2=point.x;
if (point.y > bounds.y2)
bounds.y2=point.y;
}
/*
Speculate how many points our primitive might consume.
*/
length=primitive_info[j].coordinates;
switch (primitive_type)
{
case RectanglePrimitive:
{
length*=5;
break;
}
case RoundRectanglePrimitive:
{
length*=5+8*BezierQuantum;
break;
}
case BezierPrimitive:
{
if (primitive_info[j].coordinates > 107)
(void) ThrowMagickException(&image->exception,GetMagickModule(),
DrawError,"TooManyBezierCoordinates","`%s'",token);
length=BezierQuantum*primitive_info[j].coordinates;
break;
}
case PathPrimitive:
{
char
*s,
*t;
GetMagickToken(q,&q,token);
length=1;
t=token;
for (s=token; *s != '\0'; s=t)
{
double
value;
value=strtod(s,&t);
(void) value;
if (s == t)
{
t++;
continue;
}
length+=BezierQuantum;
}
break;
}
case CirclePrimitive:
case ArcPrimitive:
case EllipsePrimitive:
{
MagickRealType
alpha,
beta,
radius;
alpha=bounds.x2-bounds.x1;
beta=bounds.y2-bounds.y1;
radius=hypot((double) alpha,(double) beta);
length=2*((size_t) (MagickPI*radius))+6*BezierQuantum+360+1;
break;
}
default:
break;
}
if ((size_t) (i+length) >= number_points)
{
/*
Resize based on speculative points required by primitive.
*/
number_points+=length+1;
primitive_info=(PrimitiveInfo *) ResizeQuantumMemory(primitive_info,
(size_t) number_points,sizeof(*primitive_info));
if (primitive_info == (PrimitiveInfo *) NULL)
{
(void) ThrowMagickException(&image->exception,GetMagickModule(),
ResourceLimitError,"MemoryAllocationFailed","`%s'",
image->filename);
break;
}
}
switch (primitive_type)
{
case PointPrimitive:
default:
{
if (primitive_info[j].coordinates != 1)
{
status=MagickFalse;
break;
}
TracePoint(primitive_info+j,primitive_info[j].point);
i=(ssize_t) (j+primitive_info[j].coordinates);
break;
}
case LinePrimitive:
{
if (primitive_info[j].coordinates != 2)
{
status=MagickFalse;
break;
}
TraceLine(primitive_info+j,primitive_info[j].point,
primitive_info[j+1].point);
i=(ssize_t) (j+primitive_info[j].coordinates);
break;
}
case RectanglePrimitive:
{
if (primitive_info[j].coordinates != 2)
{
status=MagickFalse;
break;
}
TraceRectangle(primitive_info+j,primitive_info[j].point,
primitive_info[j+1].point);
i=(ssize_t) (j+primitive_info[j].coordinates);
break;
}
case RoundRectanglePrimitive:
{
if (primitive_info[j].coordinates != 3)
{
status=MagickFalse;
break;
}
TraceRoundRectangle(primitive_info+j,primitive_info[j].point,
primitive_info[j+1].point,primitive_info[j+2].point);
i=(ssize_t) (j+primitive_info[j].coordinates);
break;
}
case ArcPrimitive:
{
if (primitive_info[j].coordinates != 3)
{
primitive_type=UndefinedPrimitive;
break;
}
TraceArc(primitive_info+j,primitive_info[j].point,
primitive_info[j+1].point,primitive_info[j+2].point);
i=(ssize_t) (j+primitive_info[j].coordinates);
break;
}
case EllipsePrimitive:
{
if (primitive_info[j].coordinates != 3)
{
status=MagickFalse;
break;
}
TraceEllipse(primitive_info+j,primitive_info[j].point,
primitive_info[j+1].point,primitive_info[j+2].point);
i=(ssize_t) (j+primitive_info[j].coordinates);
break;
}
case CirclePrimitive:
{
if (primitive_info[j].coordinates != 2)
{
status=MagickFalse;
break;
}
TraceCircle(primitive_info+j,primitive_info[j].point,
primitive_info[j+1].point);
i=(ssize_t) (j+primitive_info[j].coordinates);
break;
}
case PolylinePrimitive:
break;
case PolygonPrimitive:
{
primitive_info[i]=primitive_info[j];
primitive_info[i].coordinates=0;
primitive_info[j].coordinates++;
i++;
break;
}
case BezierPrimitive:
{
if (primitive_info[j].coordinates < 3)
{
status=MagickFalse;
break;
}
TraceBezier(primitive_info+j,primitive_info[j].coordinates);
i=(ssize_t) (j+primitive_info[j].coordinates);
break;
}
case PathPrimitive:
{
i=(ssize_t) (j+TracePath(primitive_info+j,token));
break;
}
case ColorPrimitive:
case MattePrimitive:
{
ssize_t
method;
if (primitive_info[j].coordinates != 1)
{
status=MagickFalse;
break;
}
GetMagickToken(q,&q,token);
method=ParseMagickOption(MagickMethodOptions,MagickFalse,token);
if (method == -1)
{
status=MagickFalse;
break;
}
primitive_info[j].method=(PaintMethod) method;
break;
}
case TextPrimitive:
{
if (primitive_info[j].coordinates != 1)
{
status=MagickFalse;
break;
}
if (*token != ',')
GetMagickToken(q,&q,token);
primitive_info[j].text=AcquireString(token);
break;
}
case ImagePrimitive:
{
if (primitive_info[j].coordinates != 2)
{
status=MagickFalse;
break;
}
GetMagickToken(q,&q,token);
primitive_info[j].text=AcquireString(token);
break;
}
}
if (primitive_info == (PrimitiveInfo *) NULL)
break;
if (image->debug != MagickFalse)
(void) LogMagickEvent(DrawEvent,GetMagickModule()," %.*s",(int) (q-p),p);
if (status == MagickFalse)
break;
primitive_info[i].primitive=UndefinedPrimitive;
if (i == 0)
continue;
/*
Transform points.
*/
for (i=0; primitive_info[i].primitive != UndefinedPrimitive; i++)
{
point=primitive_info[i].point;
primitive_info[i].point.x=graphic_context[n]->affine.sx*point.x+
graphic_context[n]->affine.ry*point.y+graphic_context[n]->affine.tx;
primitive_info[i].point.y=graphic_context[n]->affine.rx*point.x+
graphic_context[n]->affine.sy*point.y+graphic_context[n]->affine.ty;
point=primitive_info[i].point;
if (point.x < graphic_context[n]->bounds.x1)
graphic_context[n]->bounds.x1=point.x;
if (point.y < graphic_context[n]->bounds.y1)
graphic_context[n]->bounds.y1=point.y;
if (point.x > graphic_context[n]->bounds.x2)
graphic_context[n]->bounds.x2=point.x;
if (point.y > graphic_context[n]->bounds.y2)
graphic_context[n]->bounds.y2=point.y;
if (primitive_info[i].primitive == ImagePrimitive)
break;
if (i >= (ssize_t) number_points)
ThrowFatalException(ResourceLimitFatalError,"MemoryAllocationFailed");
}
if (graphic_context[n]->render != MagickFalse)
{
if ((n != 0) && (graphic_context[n]->clip_mask != (char *) NULL) &&
(LocaleCompare(graphic_context[n]->clip_mask,
graphic_context[n-1]->clip_mask) != 0))
(void) DrawClipPath(image,graphic_context[n],
graphic_context[n]->clip_mask);
(void) DrawPrimitive(image,graphic_context[n],primitive_info);
}
if (primitive_info->text != (char *) NULL)
primitive_info->text=(char *) RelinquishMagickMemory(
primitive_info->text);
proceed=SetImageProgress(image,RenderImageTag,q-primitive,(MagickSizeType)
primitive_extent);
if (proceed == MagickFalse)
break;
}
if (image->debug != MagickFalse)
(void) LogMagickEvent(DrawEvent,GetMagickModule(),"end draw-image");
/*
Relinquish resources.
*/
token=DestroyString(token);
if (primitive_info != (PrimitiveInfo *) NULL)
primitive_info=(PrimitiveInfo *) RelinquishMagickMemory(primitive_info);
primitive=DestroyString(primitive);
for ( ; n >= 0; n--)
graphic_context[n]=DestroyDrawInfo(graphic_context[n]);
graphic_context=(DrawInfo **) RelinquishMagickMemory(graphic_context);
if (status == MagickFalse)
ThrowBinaryException(DrawError,"NonconformingDrawingPrimitiveDefinition",
keyword);
return(status);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% D r a w G r a d i e n t I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% DrawGradientImage() draws a linear gradient on the image.
%
% The format of the DrawGradientImage method is:
%
% MagickBooleanType DrawGradientImage(Image *image,
% const DrawInfo *draw_info)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o _info: the draw info.
%
*/
static inline MagickRealType GetStopColorOffset(const GradientInfo *gradient,
const ssize_t x,const ssize_t y)
{
switch (gradient->type)
{
case UndefinedGradient:
case LinearGradient:
{
MagickRealType
gamma,
length,
offset,
scale;
PointInfo
p,
q;
const SegmentInfo
*gradient_vector;
gradient_vector=(&gradient->gradient_vector);
p.x=gradient_vector->x2-gradient_vector->x1;
p.y=gradient_vector->y2-gradient_vector->y1;
q.x=(double) x-gradient_vector->x1;
q.y=(double) y-gradient_vector->y1;
length=sqrt(q.x*q.x+q.y*q.y);
gamma=sqrt(p.x*p.x+p.y*p.y)*length;
gamma=1.0/(gamma <= MagickEpsilon ? 1.0 : gamma);
scale=p.x*q.x+p.y*q.y;
offset=gamma*scale*length;
return(offset);
}
case RadialGradient:
{
MagickRealType
length,
offset;
PointInfo
v;
v.x=(double) x-gradient->center.x;
v.y=(double) y-gradient->center.y;
length=sqrt(v.x*v.x+v.y*v.y);
if (gradient->spread == RepeatSpread)
return(length);
offset=length/gradient->radius;
return(offset);
}
}
return(0.0);
}
MagickExport MagickBooleanType DrawGradientImage(Image *image,
const DrawInfo *draw_info)
{
CacheView
*image_view;
const GradientInfo
*gradient;
const SegmentInfo
*gradient_vector;
ExceptionInfo
*exception;
MagickBooleanType
status;
MagickPixelPacket
zero;
MagickRealType
length;
PointInfo
point;
RectangleInfo
bounding_box;
ssize_t
y;
/*
Draw linear or radial gradient on image.
*/
assert(image != (Image *) NULL);
assert(image->signature == MagickSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
assert(draw_info != (const DrawInfo *) NULL);
gradient=(&draw_info->gradient);
gradient_vector=(&gradient->gradient_vector);
point.x=gradient_vector->x2-gradient_vector->x1;
point.y=gradient_vector->y2-gradient_vector->y1;
length=sqrt(point.x*point.x+point.y*point.y);
bounding_box=gradient->bounding_box;
status=MagickTrue;
exception=(&image->exception);
GetMagickPixelPacket(image,&zero);
image_view=AcquireCacheView(image);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(dynamic,4) shared(status)
#endif
for (y=bounding_box.y; y < (ssize_t) bounding_box.height; y++)
{
MagickPixelPacket
composite,
pixel;
MagickRealType
alpha,
offset;
register IndexPacket
*restrict indexes;
register ssize_t
i,
x;
register PixelPacket
*restrict q;
ssize_t
j;
if (status == MagickFalse)
continue;
q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception);
if (q == (PixelPacket *) NULL)
{
status=MagickFalse;
continue;
}
indexes=GetCacheViewAuthenticIndexQueue(image_view);
pixel=zero;
composite=zero;
offset=GetStopColorOffset(gradient,0,y);
if (gradient->type != RadialGradient)
offset/=length;
for (x=bounding_box.x; x < (ssize_t) bounding_box.width; x++)
{
SetMagickPixelPacket(image,q,indexes+x,&pixel);
switch (gradient->spread)
{
case UndefinedSpread:
case PadSpread:
{
if ((x != (ssize_t) ceil(gradient_vector->x1-0.5)) ||
(y != (ssize_t) ceil(gradient_vector->y1-0.5)))
{
offset=GetStopColorOffset(gradient,x,y);
if (gradient->type != RadialGradient)
offset/=length;
}
for (i=0; i < (ssize_t) gradient->number_stops; i++)
if (offset < gradient->stops[i].offset)
break;
if ((offset < 0.0) || (i == 0))
composite=gradient->stops[0].color;
else
if ((offset > 1.0) || (i == (ssize_t) gradient->number_stops))
composite=gradient->stops[gradient->number_stops-1].color;
else
{
j=i;
i--;
alpha=(offset-gradient->stops[i].offset)/
(gradient->stops[j].offset-gradient->stops[i].offset);
MagickPixelCompositeBlend(&gradient->stops[i].color,1.0-alpha,
&gradient->stops[j].color,alpha,&composite);
}
break;
}
case ReflectSpread:
{
if ((x != (ssize_t) ceil(gradient_vector->x1-0.5)) ||
(y != (ssize_t) ceil(gradient_vector->y1-0.5)))
{
offset=GetStopColorOffset(gradient,x,y);
if (gradient->type != RadialGradient)
offset/=length;
}
if (offset < 0.0)
offset=(-offset);
if ((ssize_t) fmod(offset,2.0) == 0)
offset=fmod(offset,1.0);
else
offset=1.0-fmod(offset,1.0);
for (i=0; i < (ssize_t) gradient->number_stops; i++)
if (offset < gradient->stops[i].offset)
break;
if (i == 0)
composite=gradient->stops[0].color;
else
if (i == (ssize_t) gradient->number_stops)
composite=gradient->stops[gradient->number_stops-1].color;
else
{
j=i;
i--;
alpha=(offset-gradient->stops[i].offset)/
(gradient->stops[j].offset-gradient->stops[i].offset);
MagickPixelCompositeBlend(&gradient->stops[i].color,1.0-alpha,
&gradient->stops[j].color,alpha,&composite);
}
break;
}
case RepeatSpread:
{
MagickBooleanType
antialias;
MagickRealType
repeat;
antialias=MagickFalse;
repeat=0.0;
if ((x != (ssize_t) ceil(gradient_vector->x1-0.5)) ||
(y != (ssize_t) ceil(gradient_vector->y1-0.5)))
{
offset=GetStopColorOffset(gradient,x,y);
if (gradient->type == LinearGradient)
{
repeat=fmod(offset,length);
if (repeat < 0.0)
repeat=length-fmod(-repeat,length);
else
repeat=fmod(offset,length);
antialias=(repeat < length) && ((repeat+1.0) > length) ?
MagickTrue : MagickFalse;
offset=repeat/length;
}
else
{
repeat=fmod(offset,gradient->radius);
if (repeat < 0.0)
repeat=gradient->radius-fmod(-repeat,gradient->radius);
else
repeat=fmod(offset,gradient->radius);
antialias=repeat+1.0 > gradient->radius ?
MagickTrue : MagickFalse;
offset=repeat/gradient->radius;
}
}
for (i=0; i < (ssize_t) gradient->number_stops; i++)
if (offset < gradient->stops[i].offset)
break;
if (i == 0)
composite=gradient->stops[0].color;
else
if (i == (ssize_t) gradient->number_stops)
composite=gradient->stops[gradient->number_stops-1].color;
else
{
j=i;
i--;
alpha=(offset-gradient->stops[i].offset)/
(gradient->stops[j].offset-gradient->stops[i].offset);
if (antialias != MagickFalse)
{
if (gradient->type == LinearGradient)
alpha=length-repeat;
else
alpha=gradient->radius-repeat;
i=0;
j=(ssize_t) gradient->number_stops-1L;
}
MagickPixelCompositeBlend(&gradient->stops[i].color,1.0-alpha,
&gradient->stops[j].color,alpha,&composite);
}
break;
}
}
MagickPixelCompositeOver(&composite,composite.opacity,&pixel,
pixel.opacity,&pixel);
SetPixelPacket(image,&pixel,q,indexes+x);
q++;
}
if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
status=MagickFalse;
}
image_view=DestroyCacheView(image_view);
return(status);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% D r a w P a t t e r n P a t h %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% DrawPatternPath() draws a pattern.
%
% The format of the DrawPatternPath method is:
%
% MagickBooleanType DrawPatternPath(Image *image,const DrawInfo *draw_info,
% const char *name,Image **pattern)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o draw_info: the draw info.
%
% o name: the pattern name.
%
% o image: the image.
%
*/
MagickExport MagickBooleanType DrawPatternPath(Image *image,
const DrawInfo *draw_info,const char *name,Image **pattern)
{
char
property[MaxTextExtent];
const char
*geometry,
*path;
DrawInfo
*clone_info;
ImageInfo
*image_info;
MagickBooleanType
status;
assert(image != (Image *) NULL);
assert(image->signature == MagickSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
assert(draw_info != (const DrawInfo *) NULL);
assert(name != (const char *) NULL);
(void) FormatMagickString(property,MaxTextExtent,"%s",name);
path=GetImageArtifact(image,property);
if (path == (const char *) NULL)
return(MagickFalse);
(void) FormatMagickString(property,MaxTextExtent,"%s-geometry",name);
geometry=GetImageArtifact(image,property);
if (geometry == (const char *) NULL)
return(MagickFalse);
if ((*pattern) != (Image *) NULL)
*pattern=DestroyImage(*pattern);
image_info=AcquireImageInfo();
image_info->size=AcquireString(geometry);
*pattern=AcquireImage(image_info);
image_info=DestroyImageInfo(image_info);
(void) QueryColorDatabase("#00000000",&(*pattern)->background_color,
&image->exception);
(void) SetImageBackgroundColor(*pattern);
if (image->debug != MagickFalse)
(void) LogMagickEvent(DrawEvent,GetMagickModule(),
"begin pattern-path %s %s",name,geometry);
clone_info=CloneDrawInfo((ImageInfo *) NULL,draw_info);
clone_info->fill_pattern=NewImageList();
clone_info->stroke_pattern=NewImageList();
(void) CloneString(&clone_info->primitive,path);
status=DrawImage(*pattern,clone_info);
clone_info=DestroyDrawInfo(clone_info);
if (image->debug != MagickFalse)
(void) LogMagickEvent(DrawEvent,GetMagickModule(),"end pattern-path");
return(status);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
+ D r a w P o l y g o n P r i m i t i v e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% DrawPolygonPrimitive() draws a polygon on the image.
%
% The format of the DrawPolygonPrimitive method is:
%
% MagickBooleanType DrawPolygonPrimitive(Image *image,
% const DrawInfo *draw_info,const PrimitiveInfo *primitive_info)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o draw_info: the draw info.
%
% o primitive_info: Specifies a pointer to a PrimitiveInfo structure.
%
*/
static PolygonInfo **DestroyPolygonThreadSet(PolygonInfo **polygon_info)
{
register ssize_t
i;
assert(polygon_info != (PolygonInfo **) NULL);
for (i=0; i < (ssize_t) GetOpenMPMaximumThreads(); i++)
if (polygon_info[i] != (PolygonInfo *) NULL)
polygon_info[i]=DestroyPolygonInfo(polygon_info[i]);
polygon_info=(PolygonInfo **) RelinquishMagickMemory(polygon_info);
return(polygon_info);
}
static PolygonInfo **AcquirePolygonThreadSet(const DrawInfo *draw_info,
const PrimitiveInfo *primitive_info)
{
PathInfo
*restrict path_info;
PolygonInfo
**polygon_info;
register ssize_t
i;
size_t
number_threads;
number_threads=GetOpenMPMaximumThreads();
polygon_info=(PolygonInfo **) AcquireQuantumMemory(number_threads,
sizeof(*polygon_info));
if (polygon_info == (PolygonInfo **) NULL)
return((PolygonInfo **) NULL);
(void) ResetMagickMemory(polygon_info,0,GetOpenMPMaximumThreads()*
sizeof(*polygon_info));
path_info=ConvertPrimitiveToPath(draw_info,primitive_info);
if (path_info == (PathInfo *) NULL)
return(DestroyPolygonThreadSet(polygon_info));
for (i=0; i < (ssize_t) number_threads; i++)
{
polygon_info[i]=ConvertPathToPolygon(draw_info,path_info);
if (polygon_info[i] == (PolygonInfo *) NULL)
return(DestroyPolygonThreadSet(polygon_info));
}
path_info=(PathInfo *) RelinquishMagickMemory(path_info);
return(polygon_info);
}
static MagickRealType GetPixelOpacity(PolygonInfo *polygon_info,
const MagickRealType mid,const MagickBooleanType fill,
const FillRule fill_rule,const double x,const double y,
MagickRealType *stroke_opacity)
{
MagickRealType
alpha,
beta,
distance,
subpath_opacity;
PointInfo
delta;
register EdgeInfo
*p;
register const PointInfo
*q;
register ssize_t
i;
ssize_t
j,
winding_number;
/*
Compute fill & stroke opacity for this (x,y) point.
*/
*stroke_opacity=0.0;
subpath_opacity=0.0;
p=polygon_info->edges;
for (j=0; j < (ssize_t) polygon_info->number_edges; j++, p++)
{
if (y <= (p->bounds.y1-mid-0.5))
break;
if (y > (p->bounds.y2+mid+0.5))
{
(void) DestroyEdge(polygon_info,(size_t) j);
continue;
}
if ((x <= (p->bounds.x1-mid-0.5)) || (x > (p->bounds.x2+mid+0.5)))
continue;
i=(ssize_t) MagickMax((double) p->highwater,1.0);
for ( ; i < (ssize_t) p->number_points; i++)
{
if (y <= (p->points[i-1].y-mid-0.5))
break;
if (y > (p->points[i].y+mid+0.5))
continue;
if (p->scanline != y)
{
p->scanline=y;
p->highwater=(size_t) i;
}
/*
Compute distance between a point and an edge.
*/
q=p->points+i-1;
delta.x=(q+1)->x-q->x;
delta.y=(q+1)->y-q->y;
beta=delta.x*(x-q->x)+delta.y*(y-q->y);
if (beta < 0.0)
{
delta.x=x-q->x;
delta.y=y-q->y;
distance=delta.x*delta.x+delta.y*delta.y;
}
else
{
alpha=delta.x*delta.x+delta.y*delta.y;
if (beta > alpha)
{
delta.x=x-(q+1)->x;
delta.y=y-(q+1)->y;
distance=delta.x*delta.x+delta.y*delta.y;
}
else
{
alpha=1.0/alpha;
beta=delta.x*(y-q->y)-delta.y*(x-q->x);
distance=alpha*beta*beta;
}
}
/*
Compute stroke & subpath opacity.
*/
beta=0.0;
if (p->ghostline == MagickFalse)
{
alpha=mid+0.5;
if ((*stroke_opacity < 1.0) &&
(distance <= ((alpha+0.25)*(alpha+0.25))))
{
alpha=mid-0.5;
if (distance <= ((alpha+0.25)*(alpha+0.25)))
*stroke_opacity=1.0;
else
{
beta=1.0;
if (distance != 1.0)
beta=sqrt((double) distance);
alpha=beta-mid-0.5;
if (*stroke_opacity < ((alpha-0.25)*(alpha-0.25)))
*stroke_opacity=(alpha-0.25)*(alpha-0.25);
}
}
}
if ((fill == MagickFalse) || (distance > 1.0) || (subpath_opacity >= 1.0))
continue;
if (distance <= 0.0)
{
subpath_opacity=1.0;
continue;
}
if (distance > 1.0)
continue;
if (beta == 0.0)
{
beta=1.0;
if (distance != 1.0)
beta=sqrt(distance);
}
alpha=beta-1.0;
if (subpath_opacity < (alpha*alpha))
subpath_opacity=alpha*alpha;
}
}
/*
Compute fill opacity.
*/
if (fill == MagickFalse)
return(0.0);
if (subpath_opacity >= 1.0)
return(1.0);
/*
Determine winding number.
*/
winding_number=0;
p=polygon_info->edges;
for (j=0; j < (ssize_t) polygon_info->number_edges; j++, p++)
{
if (y <= p->bounds.y1)
break;
if ((y > p->bounds.y2) || (x <= p->bounds.x1))
continue;
if (x > p->bounds.x2)
{
winding_number+=p->direction ? 1 : -1;
continue;
}
i=(ssize_t) MagickMax((double) p->highwater,1.0);
for ( ; i < (ssize_t) p->number_points; i++)
if (y <= p->points[i].y)
break;
q=p->points+i-1;
if ((((q+1)->x-q->x)*(y-q->y)) <= (((q+1)->y-q->y)*(x-q->x)))
winding_number+=p->direction ? 1 : -1;
}
if (fill_rule != NonZeroRule)
{
if ((MagickAbsoluteValue(winding_number) & 0x01) != 0)
return(1.0);
}
else
if (MagickAbsoluteValue(winding_number) != 0)
return(1.0);
return(subpath_opacity);
}
static MagickBooleanType DrawPolygonPrimitive(Image *image,
const DrawInfo *draw_info,const PrimitiveInfo *primitive_info)
{
CacheView
*image_view;
ExceptionInfo
*exception;
MagickBooleanType
fill,
status;
MagickRealType
mid;
PolygonInfo
**restrict polygon_info;
register EdgeInfo
*p;
register ssize_t
i;
SegmentInfo
bounds;
ssize_t
start,
stop,
y;
/*
Compute bounding box.
*/
assert(image != (Image *) NULL);
assert(image->signature == MagickSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
assert(draw_info != (DrawInfo *) NULL);
assert(draw_info->signature == MagickSignature);
assert(primitive_info != (PrimitiveInfo *) NULL);
if (primitive_info->coordinates == 0)
return(MagickTrue);
polygon_info=AcquirePolygonThreadSet(draw_info,primitive_info);
if (polygon_info == (PolygonInfo **) NULL)
return(MagickFalse);
if (0)
DrawBoundingRectangles(image,draw_info,polygon_info[0]);
if (image->debug != MagickFalse)
(void) LogMagickEvent(DrawEvent,GetMagickModule()," begin draw-polygon");
fill=(primitive_info->method == FillToBorderMethod) ||
(primitive_info->method == FloodfillMethod) ? MagickTrue : MagickFalse;
mid=ExpandAffine(&draw_info->affine)*draw_info->stroke_width/2.0;
bounds=polygon_info[0]->edges[0].bounds;
for (i=1; i < (ssize_t) polygon_info[0]->number_edges; i++)
{
p=polygon_info[0]->edges+i;
if (p->bounds.x1 < bounds.x1)
bounds.x1=p->bounds.x1;
if (p->bounds.y1 < bounds.y1)
bounds.y1=p->bounds.y1;
if (p->bounds.x2 > bounds.x2)
bounds.x2=p->bounds.x2;
if (p->bounds.y2 > bounds.y2)
bounds.y2=p->bounds.y2;
}
bounds.x1-=(mid+1.0);
bounds.x1=bounds.x1 < 0.0 ? 0.0 : (size_t) ceil(bounds.x1-0.5) >=
image->columns ? (double) image->columns-1.0 : bounds.x1;
bounds.y1-=(mid+1.0);
bounds.y1=bounds.y1 < 0.0 ? 0.0 : (size_t) ceil(bounds.y1-0.5) >=
image->rows ? (double) image->rows-1.0 : bounds.y1;
bounds.x2+=(mid+1.0);
bounds.x2=bounds.x2 < 0.0 ? 0.0 : (size_t) floor(bounds.x2+0.5) >=
image->columns ? (double) image->columns-1.0 : bounds.x2;
bounds.y2+=(mid+1.0);
bounds.y2=bounds.y2 < 0.0 ? 0.0 : (size_t) floor(bounds.y2+0.5) >=
image->rows ? (double) image->rows-1.0 : bounds.y2;
status=MagickTrue;
exception=(&image->exception);
start=(ssize_t) ceil(bounds.x1-0.5);
stop=(ssize_t) floor(bounds.x2+0.5);
image_view=AcquireCacheView(image);
if (primitive_info->coordinates == 1)
{
/*
Draw point.
*/
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(dynamic,4) shared(status)
#endif
for (y=(ssize_t) ceil(bounds.y1-0.5); y <= (ssize_t) floor(bounds.y2+0.5); y++)
{
MagickBooleanType
sync;
register ssize_t
x;
register PixelPacket
*restrict q;
if (status == MagickFalse)
continue;
x=start;
q=GetCacheViewAuthenticPixels(image_view,x,y,(size_t) (stop-x+1),
1,exception);
if (q == (PixelPacket *) NULL)
{
status=MagickFalse;
continue;
}
for ( ; x <= stop; x++)
{
if ((x == (ssize_t) ceil(primitive_info->point.x-0.5)) &&
(y == (ssize_t) ceil(primitive_info->point.y-0.5)))
(void) GetStrokeColor(draw_info,x,y,q);
q++;
}
sync=SyncCacheViewAuthenticPixels(image_view,exception);
if (sync == MagickFalse)
status=MagickFalse;
}
image_view=DestroyCacheView(image_view);
polygon_info=DestroyPolygonThreadSet(polygon_info);
if (image->debug != MagickFalse)
(void) LogMagickEvent(DrawEvent,GetMagickModule(),
" end draw-polygon");
return(status);
}
/*
Draw polygon or line.
*/
if (image->matte == MagickFalse)
(void) SetImageAlphaChannel(image,OpaqueAlphaChannel);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(dynamic,4) shared(status)
#endif
for (y=(ssize_t) ceil(bounds.y1-0.5); y <= (ssize_t) floor(bounds.y2+0.5); y++)
{
const int
id = GetOpenMPThreadId();
MagickRealType
fill_opacity,
stroke_opacity;
PixelPacket
fill_color,
stroke_color;
register PixelPacket
*restrict q;
register ssize_t
x;
if (status == MagickFalse)
continue;
q=GetCacheViewAuthenticPixels(image_view,start,y,(size_t) (stop-
start+1),1,exception);
if (q == (PixelPacket *) NULL)
{
status=MagickFalse;
continue;
}
for (x=start; x <= stop; x++)
{
/*
Fill and/or stroke.
*/
fill_opacity=GetPixelOpacity(polygon_info[id],mid,fill,
draw_info->fill_rule,(double) x,(double) y,&stroke_opacity);
if (draw_info->stroke_antialias == MagickFalse)
{
fill_opacity=fill_opacity > 0.25 ? 1.0 : 0.0;
stroke_opacity=stroke_opacity > 0.25 ? 1.0 : 0.0;
}
(void) GetFillColor(draw_info,x,y,&fill_color);
fill_opacity=(MagickRealType) (QuantumRange-fill_opacity*(QuantumRange-
fill_color.opacity));
MagickCompositeOver(&fill_color,fill_opacity,q,(MagickRealType)
q->opacity,q);
(void) GetStrokeColor(draw_info,x,y,&stroke_color);
stroke_opacity=(MagickRealType) (QuantumRange-stroke_opacity*
(QuantumRange-stroke_color.opacity));
MagickCompositeOver(&stroke_color,stroke_opacity,q,(MagickRealType)
q->opacity,q);
q++;
}
if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
status=MagickFalse;
}
image_view=DestroyCacheView(image_view);
polygon_info=DestroyPolygonThreadSet(polygon_info);
if (image->debug != MagickFalse)
(void) LogMagickEvent(DrawEvent,GetMagickModule()," end draw-polygon");
return(status);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% D r a w P r i m i t i v e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% DrawPrimitive() draws a primitive (line, rectangle, ellipse) on the image.
%
% The format of the DrawPrimitive method is:
%
% MagickBooleanType DrawPrimitive(Image *image,const DrawInfo *draw_info,
% PrimitiveInfo *primitive_info)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o draw_info: the draw info.
%
% o primitive_info: Specifies a pointer to a PrimitiveInfo structure.
%
*/
static void LogPrimitiveInfo(const PrimitiveInfo *primitive_info)
{
const char
*methods[] =
{
"point",
"replace",
"floodfill",
"filltoborder",
"reset",
"?"
};
PointInfo
p,
q,
point;
register ssize_t
i,
x;
ssize_t
coordinates,
y;
x=(ssize_t) ceil(primitive_info->point.x-0.5);
y=(ssize_t) ceil(primitive_info->point.y-0.5);
switch (primitive_info->primitive)
{
case PointPrimitive:
{
(void) LogMagickEvent(DrawEvent,GetMagickModule(),
"PointPrimitive %.20g,%.20g %s",(double) x,(double) y,
methods[primitive_info->method]);
return;
}
case ColorPrimitive:
{
(void) LogMagickEvent(DrawEvent,GetMagickModule(),
"ColorPrimitive %.20g,%.20g %s",(double) x,(double) y,
methods[primitive_info->method]);
return;
}
case MattePrimitive:
{
(void) LogMagickEvent(DrawEvent,GetMagickModule(),
"MattePrimitive %.20g,%.20g %s",(double) x,(double) y,
methods[primitive_info->method]);
return;
}
case TextPrimitive:
{
(void) LogMagickEvent(DrawEvent,GetMagickModule(),
"TextPrimitive %.20g,%.20g",(double) x,(double) y);
return;
}
case ImagePrimitive:
{
(void) LogMagickEvent(DrawEvent,GetMagickModule(),
"ImagePrimitive %.20g,%.20g",(double) x,(double) y);
return;
}
default:
break;
}
coordinates=0;
p=primitive_info[0].point;
q.x=(-1.0);
q.y=(-1.0);
for (i=0; primitive_info[i].primitive != UndefinedPrimitive; i++)
{
point=primitive_info[i].point;
if (coordinates <= 0)
{
coordinates=(ssize_t) primitive_info[i].coordinates;
(void) LogMagickEvent(DrawEvent,GetMagickModule(),
" begin open (%.20g)",(double) coordinates);
p=point;
}
point=primitive_info[i].point;
if ((fabs(q.x-point.x) > MagickEpsilon) ||
(fabs(q.y-point.y) > MagickEpsilon))
(void) LogMagickEvent(DrawEvent,GetMagickModule(),
" %.20g: %.18g,%.18g",(double) coordinates,point.x,point.y);
else
(void) LogMagickEvent(DrawEvent,GetMagickModule(),
" %.20g: %g,%g (duplicate)",(double) coordinates,point.x,point.y);
q=point;
coordinates--;
if (coordinates > 0)
continue;
if ((fabs(p.x-point.x) > MagickEpsilon) ||
(fabs(p.y-point.y) > MagickEpsilon))
(void) LogMagickEvent(DrawEvent,GetMagickModule()," end last (%.20g)",
(double) coordinates);
else
(void) LogMagickEvent(DrawEvent,GetMagickModule()," end open (%.20g)",
(double) coordinates);
}
}
MagickExport MagickBooleanType DrawPrimitive(Image *image,
const DrawInfo *draw_info,const PrimitiveInfo *primitive_info)
{
CacheView
*image_view;
ExceptionInfo
*exception;
MagickStatusType
status;
register ssize_t
i,
x;
ssize_t
y;
if (image->debug != MagickFalse)
{
(void) LogMagickEvent(DrawEvent,GetMagickModule(),
" begin draw-primitive");
(void) LogMagickEvent(DrawEvent,GetMagickModule(),
" affine: %g,%g,%g,%g,%g,%g",draw_info->affine.sx,
draw_info->affine.rx,draw_info->affine.ry,draw_info->affine.sy,
draw_info->affine.tx,draw_info->affine.ty);
}
status=MagickTrue;
exception=(&image->exception);
x=(ssize_t) ceil(primitive_info->point.x-0.5);
y=(ssize_t) ceil(primitive_info->point.y-0.5);
image_view=AcquireCacheView(image);
switch (primitive_info->primitive)
{
case PointPrimitive:
{
PixelPacket
fill_color;
PixelPacket
*q;
if ((y < 0) || (y >= (ssize_t) image->rows))
break;
if ((x < 0) || (x >= (ssize_t) image->columns))
break;
q=GetCacheViewAuthenticPixels(image_view,x,y,1,1,exception);
if (q == (PixelPacket *) NULL)
break;
(void) GetFillColor(draw_info,x,y,&fill_color);
MagickCompositeOver(&fill_color,(MagickRealType) fill_color.opacity,q,
(MagickRealType) q->opacity,q);
(void) SyncCacheViewAuthenticPixels(image_view,exception);
break;
}
case ColorPrimitive:
{
switch (primitive_info->method)
{
case PointMethod:
default:
{
PixelPacket
*q;
q=GetCacheViewAuthenticPixels(image_view,x,y,1,1,exception);
if (q == (PixelPacket *) NULL)
break;
(void) GetFillColor(draw_info,x,y,q);
(void) SyncCacheViewAuthenticPixels(image_view,exception);
break;
}
case ReplaceMethod:
{
MagickBooleanType
sync;
PixelPacket
target;
(void) GetOneCacheViewVirtualPixel(image_view,x,y,&target,exception);
for (y=0; y < (ssize_t) image->rows; y++)
{
register PixelPacket
*restrict q;
q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,
exception);
if (q == (PixelPacket *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
if (IsColorSimilar(image,q,&target) == MagickFalse)
{
q++;
continue;
}
(void) GetFillColor(draw_info,x,y,q);
q++;
}
sync=SyncCacheViewAuthenticPixels(image_view,exception);
if (sync == MagickFalse)
break;
}
break;
}
case FloodfillMethod:
case FillToBorderMethod:
{
MagickPixelPacket
target;
(void) GetOneVirtualMagickPixel(image,x,y,&target,exception);
if (primitive_info->method == FillToBorderMethod)
{
target.red=(MagickRealType) draw_info->border_color.red;
target.green=(MagickRealType) draw_info->border_color.green;
target.blue=(MagickRealType) draw_info->border_color.blue;
}
(void) FloodfillPaintImage(image,DefaultChannels,draw_info,&target,x,
y,primitive_info->method == FloodfillMethod ? MagickFalse :
MagickTrue);
break;
}
case ResetMethod:
{
MagickBooleanType
sync;
for (y=0; y < (ssize_t) image->rows; y++)
{
register PixelPacket
*restrict q;
register ssize_t
x;
q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,
exception);
if (q == (PixelPacket *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
(void) GetFillColor(draw_info,x,y,q);
q++;
}
sync=SyncCacheViewAuthenticPixels(image_view,exception);
if (sync == MagickFalse)
break;
}
break;
}
}
break;
}
case MattePrimitive:
{
if (image->matte == MagickFalse)
(void) SetImageAlphaChannel(image,OpaqueAlphaChannel);
switch (primitive_info->method)
{
case PointMethod:
default:
{
PixelPacket
pixel;
PixelPacket
*q;
q=GetCacheViewAuthenticPixels(image_view,x,y,1,1,exception);
if (q == (PixelPacket *) NULL)
break;
(void) GetFillColor(draw_info,x,y,&pixel);
q->opacity=pixel.opacity;
(void) SyncCacheViewAuthenticPixels(image_view,exception);
break;
}
case ReplaceMethod:
{
MagickBooleanType
sync;
PixelPacket
pixel,
target;
(void) GetOneCacheViewVirtualPixel(image_view,x,y,&target,exception);
for (y=0; y < (ssize_t) image->rows; y++)
{
register PixelPacket
*restrict q;
register ssize_t
x;
q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,
exception);
if (q == (PixelPacket *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
if (IsColorSimilar(image,q,&target) == MagickFalse)
{
q++;
continue;
}
(void) GetFillColor(draw_info,x,y,&pixel);
q->opacity=pixel.opacity;
q++;
}
sync=SyncCacheViewAuthenticPixels(image_view,exception);
if (sync == MagickFalse)
break;
}
break;
}
case FloodfillMethod:
case FillToBorderMethod:
{
MagickPixelPacket
target;
(void) GetOneVirtualMagickPixel(image,x,y,&target,exception);
if (primitive_info->method == FillToBorderMethod)
{
target.red=(MagickRealType) draw_info->border_color.red;
target.green=(MagickRealType) draw_info->border_color.green;
target.blue=(MagickRealType) draw_info->border_color.blue;
}
(void) FloodfillPaintImage(image,OpacityChannel,draw_info,&target,x,y,
primitive_info->method == FloodfillMethod ? MagickFalse :
MagickTrue);
break;
}
case ResetMethod:
{
MagickBooleanType
sync;
PixelPacket
pixel;
for (y=0; y < (ssize_t) image->rows; y++)
{
register PixelPacket
*restrict q;
register ssize_t
x;
q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,
exception);
if (q == (PixelPacket *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
(void) GetFillColor(draw_info,x,y,&pixel);
q->opacity=pixel.opacity;
q++;
}
sync=SyncCacheViewAuthenticPixels(image_view,exception);
if (sync == MagickFalse)
break;
}
break;
}
}
break;
}
case TextPrimitive:
{
char
geometry[MaxTextExtent];
DrawInfo
*clone_info;
if (primitive_info->text == (char *) NULL)
break;
clone_info=CloneDrawInfo((ImageInfo *) NULL,draw_info);
(void) CloneString(&clone_info->text,primitive_info->text);
(void) FormatMagickString(geometry,MaxTextExtent,"%+f%+f",
primitive_info->point.x,primitive_info->point.y);
(void) CloneString(&clone_info->geometry,geometry);
status=AnnotateImage(image,clone_info);
clone_info=DestroyDrawInfo(clone_info);
break;
}
case ImagePrimitive:
{
AffineMatrix
affine;
char
composite_geometry[MaxTextExtent];
Image
*composite_image;
ImageInfo
*clone_info;
RectangleInfo
geometry;
ssize_t
x1,
y1;
if (primitive_info->text == (char *) NULL)
break;
clone_info=AcquireImageInfo();
if (LocaleNCompare(primitive_info->text,"data:",5) == 0)
composite_image=ReadInlineImage(clone_info,primitive_info->text,
&image->exception);
else
{
(void) CopyMagickString(clone_info->filename,primitive_info->text,
MaxTextExtent);
composite_image=ReadImage(clone_info,&image->exception);
}
clone_info=DestroyImageInfo(clone_info);
if (composite_image == (Image *) NULL)
break;
(void) SetImageProgressMonitor(composite_image,(MagickProgressMonitor)
NULL,(void *) NULL);
x1=(ssize_t) ceil(primitive_info[1].point.x-0.5);
y1=(ssize_t) ceil(primitive_info[1].point.y-0.5);
if (((x1 != 0L) && (x1 != (ssize_t) composite_image->columns)) ||
((y1 != 0L) && (y1 != (ssize_t) composite_image->rows)))
{
char
geometry[MaxTextExtent];
/*
Resize image.
*/
(void) FormatMagickString(geometry,MaxTextExtent,"%gx%g!",
primitive_info[1].point.x,primitive_info[1].point.y);
composite_image->filter=image->filter;
(void) TransformImage(&composite_image,(char *) NULL,geometry);
}
if (composite_image->matte == MagickFalse)
(void) SetImageAlphaChannel(composite_image,OpaqueAlphaChannel);
if (draw_info->opacity != OpaqueOpacity)
(void) SetImageOpacity(composite_image,draw_info->opacity);
SetGeometry(image,&geometry);
image->gravity=draw_info->gravity;
geometry.x=x;
geometry.y=y;
(void) FormatMagickString(composite_geometry,MaxTextExtent,
"%.20gx%.20g%+.20g%+.20g",(double) composite_image->columns,(double)
composite_image->rows,(double) geometry.x,(double) geometry.y);
(void) ParseGravityGeometry(image,composite_geometry,&geometry,
&image->exception);
affine=draw_info->affine;
affine.tx=(double) geometry.x;
affine.ty=(double) geometry.y;
composite_image->interpolate=image->interpolate;
if (draw_info->compose == OverCompositeOp)
(void) DrawAffineImage(image,composite_image,&affine);
else
(void) CompositeImage(image,draw_info->compose,composite_image,
geometry.x,geometry.y);
composite_image=DestroyImage(composite_image);
break;
}
default:
{
MagickRealType
mid,
scale;
DrawInfo
*clone_info;
if (IsEventLogging() != MagickFalse)
LogPrimitiveInfo(primitive_info);
scale=ExpandAffine(&draw_info->affine);
if ((draw_info->dash_pattern != (double *) NULL) &&
(draw_info->dash_pattern[0] != 0.0) &&
((scale*draw_info->stroke_width) > MagickEpsilon) &&
(draw_info->stroke.opacity != (Quantum) TransparentOpacity))
{
/*
Draw dash polygon.
*/
clone_info=CloneDrawInfo((ImageInfo *) NULL,draw_info);
clone_info->stroke_width=0.0;
clone_info->stroke.opacity=(Quantum) TransparentOpacity;
status=DrawPolygonPrimitive(image,clone_info,primitive_info);
clone_info=DestroyDrawInfo(clone_info);
(void) DrawDashPolygon(draw_info,primitive_info,image);
break;
}
mid=ExpandAffine(&draw_info->affine)*draw_info->stroke_width/2.0;
if ((mid > 1.0) &&
(draw_info->stroke.opacity != (Quantum) TransparentOpacity))
{
MagickBooleanType
closed_path;
/*
Draw strokes while respecting line cap/join attributes.
*/
for (i=0; primitive_info[i].primitive != UndefinedPrimitive; i++) ;
closed_path=
(primitive_info[i-1].point.x == primitive_info[0].point.x) &&
(primitive_info[i-1].point.y == primitive_info[0].point.y) ?
MagickTrue : MagickFalse;
i=(ssize_t) primitive_info[0].coordinates;
if ((((draw_info->linecap == RoundCap) ||
(closed_path != MagickFalse)) &&
(draw_info->linejoin == RoundJoin)) ||
(primitive_info[i].primitive != UndefinedPrimitive))
{
(void) DrawPolygonPrimitive(image,draw_info,primitive_info);
break;
}
clone_info=CloneDrawInfo((ImageInfo *) NULL,draw_info);
clone_info->stroke_width=0.0;
clone_info->stroke.opacity=(Quantum) TransparentOpacity;
status=DrawPolygonPrimitive(image,clone_info,primitive_info);
clone_info=DestroyDrawInfo(clone_info);
status|=DrawStrokePolygon(image,draw_info,primitive_info);
break;
}
status=DrawPolygonPrimitive(image,draw_info,primitive_info);
break;
}
}
image_view=DestroyCacheView(image_view);
if (image->debug != MagickFalse)
(void) LogMagickEvent(DrawEvent,GetMagickModule()," end draw-primitive");
return(status != 0 ? MagickTrue : MagickFalse);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
+ D r a w S t r o k e P o l y g o n %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% DrawStrokePolygon() draws a stroked polygon (line, rectangle, ellipse) on
% the image while respecting the line cap and join attributes.
%
% The format of the DrawStrokePolygon method is:
%
% MagickBooleanType DrawStrokePolygon(Image *image,
% const DrawInfo *draw_info,const PrimitiveInfo *primitive_info)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o draw_info: the draw info.
%
% o primitive_info: Specifies a pointer to a PrimitiveInfo structure.
%
%
*/
static void DrawRoundLinecap(Image *image,const DrawInfo *draw_info,
const PrimitiveInfo *primitive_info)
{
PrimitiveInfo
linecap[5];
register ssize_t
i;
for (i=0; i < 4; i++)
linecap[i]=(*primitive_info);
linecap[0].coordinates=4;
linecap[1].point.x+=(double) (10.0*MagickEpsilon);
linecap[2].point.x+=(double) (10.0*MagickEpsilon);
linecap[2].point.y+=(double) (10.0*MagickEpsilon);
linecap[3].point.y+=(double) (10.0*MagickEpsilon);
linecap[4].primitive=UndefinedPrimitive;
(void) DrawPolygonPrimitive(image,draw_info,linecap);
}
static MagickBooleanType DrawStrokePolygon(Image *image,
const DrawInfo *draw_info,const PrimitiveInfo *primitive_info)
{
DrawInfo
*clone_info;
MagickBooleanType
closed_path,
status;
PrimitiveInfo
*stroke_polygon;
register const PrimitiveInfo
*p,
*q;
/*
Draw stroked polygon.
*/
if (image->debug != MagickFalse)
(void) LogMagickEvent(DrawEvent,GetMagickModule(),
" begin draw-stroke-polygon");
clone_info=CloneDrawInfo((ImageInfo *) NULL,draw_info);
clone_info->fill=draw_info->stroke;
clone_info->stroke.opacity=(Quantum) TransparentOpacity;
clone_info->stroke_width=0.0;
clone_info->fill_rule=NonZeroRule;
status=MagickTrue;
for (p=primitive_info; p->primitive != UndefinedPrimitive; p+=p->coordinates)
{
stroke_polygon=TraceStrokePolygon(draw_info,p);
status=DrawPolygonPrimitive(image,clone_info,stroke_polygon);
stroke_polygon=(PrimitiveInfo *) RelinquishMagickMemory(stroke_polygon);
q=p+p->coordinates-1;
closed_path=(q->point.x == p->point.x) && (q->point.y == p->point.y) ?
MagickTrue : MagickFalse;
if ((draw_info->linecap == RoundCap) && (closed_path == MagickFalse))
{
DrawRoundLinecap(image,draw_info,p);
DrawRoundLinecap(image,draw_info,q);
}
}
clone_info=DestroyDrawInfo(clone_info);
if (image->debug != MagickFalse)
(void) LogMagickEvent(DrawEvent,GetMagickModule(),
" end draw-stroke-polygon");
return(status);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% G e t A f f i n e M a t r i x %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% GetAffineMatrix() returns an AffineMatrix initialized to the identity
% matrix.
%
% The format of the GetAffineMatrix method is:
%
% void GetAffineMatrix(AffineMatrix *affine_matrix)
%
% A description of each parameter follows:
%
% o affine_matrix: the affine matrix.
%
*/
MagickExport void GetAffineMatrix(AffineMatrix *affine_matrix)
{
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"...");
assert(affine_matrix != (AffineMatrix *) NULL);
(void) ResetMagickMemory(affine_matrix,0,sizeof(*affine_matrix));
affine_matrix->sx=1.0;
affine_matrix->sy=1.0;
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
+ G e t D r a w I n f o %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% GetDrawInfo() initializes draw_info to default values.
%
% The format of the GetDrawInfo method is:
%
% void GetDrawInfo(const ImageInfo *image_info,DrawInfo *draw_info)
%
% A description of each parameter follows:
%
% o image_info: the image info..
%
% o draw_info: the draw info.
%
*/
MagickExport void GetDrawInfo(const ImageInfo *image_info,DrawInfo *draw_info)
{
const char
*option;
ExceptionInfo
*exception;
ImageInfo
*clone_info;
/*
Initialize draw attributes.
*/
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"...");
assert(draw_info != (DrawInfo *) NULL);
(void) ResetMagickMemory(draw_info,0,sizeof(*draw_info));
clone_info=CloneImageInfo(image_info);
GetAffineMatrix(&draw_info->affine);
exception=AcquireExceptionInfo();
(void) QueryColorDatabase("#000F",&draw_info->fill,exception);
(void) QueryColorDatabase("#FFF0",&draw_info->stroke,exception);
draw_info->stroke_antialias=clone_info->antialias;
draw_info->stroke_width=1.0;
draw_info->opacity=OpaqueOpacity;
draw_info->fill_rule=EvenOddRule;
draw_info->linecap=ButtCap;
draw_info->linejoin=MiterJoin;
draw_info->miterlimit=10;
draw_info->decorate=NoDecoration;
if (clone_info->font != (char *) NULL)
draw_info->font=AcquireString(clone_info->font);
if (clone_info->density != (char *) NULL)
draw_info->density=AcquireString(clone_info->density);
draw_info->text_antialias=clone_info->antialias;
draw_info->pointsize=12.0;
if (clone_info->pointsize != 0.0)
draw_info->pointsize=clone_info->pointsize;
draw_info->undercolor.opacity=(Quantum) TransparentOpacity;
draw_info->border_color=clone_info->border_color;
draw_info->compose=OverCompositeOp;
if (clone_info->server_name != (char *) NULL)
draw_info->server_name=AcquireString(clone_info->server_name);
draw_info->render=MagickTrue;
draw_info->debug=IsEventLogging();
option=GetImageOption(clone_info,"encoding");
if (option != (const char *) NULL)
(void) CloneString(&draw_info->encoding,option);
option=GetImageOption(clone_info,"kerning");
if (option != (const char *) NULL)
draw_info->kerning=StringToDouble(option);
option=GetImageOption(clone_info,"interline-spacing");
if (option != (const char *) NULL)
draw_info->interline_spacing=StringToDouble(option);
draw_info->direction=UndefinedDirection;
option=GetImageOption(clone_info,"interword-spacing");
if (option != (const char *) NULL)
draw_info->interword_spacing=StringToDouble(option);
option=GetImageOption(clone_info,"direction");
if (option != (const char *) NULL)
draw_info->direction=(DirectionType) ParseMagickOption(
MagickDirectionOptions,MagickFalse,option);
option=GetImageOption(clone_info,"fill");
if (option != (const char *) NULL)
(void) QueryColorDatabase(option,&draw_info->fill,exception);
option=GetImageOption(clone_info,"stroke");
if (option != (const char *) NULL)
(void) QueryColorDatabase(option,&draw_info->stroke,exception);
option=GetImageOption(clone_info,"strokewidth");
if (option != (const char *) NULL)
draw_info->stroke_width=StringToDouble(option);
option=GetImageOption(clone_info,"undercolor");
if (option != (const char *) NULL)
(void) QueryColorDatabase(option,&draw_info->undercolor,exception);
option=GetImageOption(clone_info,"gravity");
if (option != (const char *) NULL)
draw_info->gravity=(GravityType) ParseMagickOption(MagickGravityOptions,
MagickFalse,option);
exception=DestroyExceptionInfo(exception);
draw_info->signature=MagickSignature;
clone_info=DestroyImageInfo(clone_info);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
+ P e r m u t a t e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% Permutate() returns the permuation of the (n,k).
%
% The format of the Permutate method is:
%
% void Permutate(ssize_t n,ssize_t k)
%
% A description of each parameter follows:
%
% o n:
%
% o k:
%
%
*/
static inline MagickRealType Permutate(const ssize_t n,const ssize_t k)
{
MagickRealType
r;
register ssize_t
i;
r=1.0;
for (i=k+1; i <= n; i++)
r*=i;
for (i=1; i <= (n-k); i++)
r/=i;
return(r);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
+ T r a c e P r i m i t i v e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% TracePrimitive is a collection of methods for generating graphic
% primitives such as arcs, ellipses, paths, etc.
%
*/
static void TraceArc(PrimitiveInfo *primitive_info,const PointInfo start,
const PointInfo end,const PointInfo degrees)
{
PointInfo
center,
radii;
center.x=0.5*(end.x+start.x);
center.y=0.5*(end.y+start.y);
radii.x=fabs(center.x-start.x);
radii.y=fabs(center.y-start.y);
TraceEllipse(primitive_info,center,radii,degrees);
}
static void TraceArcPath(PrimitiveInfo *primitive_info,const PointInfo start,
const PointInfo end,const PointInfo arc,const MagickRealType angle,
const MagickBooleanType large_arc,const MagickBooleanType sweep)
{
MagickRealType
alpha,
beta,
delta,
factor,
gamma,
theta;
PointInfo
center,
points[3],
radii;
register MagickRealType
cosine,
sine;
register PrimitiveInfo
*p;
register ssize_t
i;
size_t
arc_segments;
if ((start.x == end.x) && (start.y == end.y))
{
TracePoint(primitive_info,end);
return;
}
radii.x=fabs(arc.x);
radii.y=fabs(arc.y);
if ((radii.x == 0.0) || (radii.y == 0.0))
{
TraceLine(primitive_info,start,end);
return;
}
cosine=cos(DegreesToRadians(fmod((double) angle,360.0)));
sine=sin(DegreesToRadians(fmod((double) angle,360.0)));
center.x=(double) (cosine*(end.x-start.x)/2+sine*(end.y-start.y)/2);
center.y=(double) (cosine*(end.y-start.y)/2-sine*(end.x-start.x)/2);
delta=(center.x*center.x)/(radii.x*radii.x)+(center.y*center.y)/
(radii.y*radii.y);
if (delta < MagickEpsilon)
{
TraceLine(primitive_info,start,end);
return;
}
if (delta > 1.0)
{
radii.x*=sqrt((double) delta);
radii.y*=sqrt((double) delta);
}
points[0].x=(double) (cosine*start.x/radii.x+sine*start.y/radii.x);
points[0].y=(double) (cosine*start.y/radii.y-sine*start.x/radii.y);
points[1].x=(double) (cosine*end.x/radii.x+sine*end.y/radii.x);
points[1].y=(double) (cosine*end.y/radii.y-sine*end.x/radii.y);
alpha=points[1].x-points[0].x;
beta=points[1].y-points[0].y;
factor=1.0/(alpha*alpha+beta*beta)-0.25;
if (factor <= 0.0)
factor=0.0;
else
{
factor=sqrt((double) factor);
if (sweep == large_arc)
factor=(-factor);
}
center.x=(double) ((points[0].x+points[1].x)/2-factor*beta);
center.y=(double) ((points[0].y+points[1].y)/2+factor*alpha);
alpha=atan2(points[0].y-center.y,points[0].x-center.x);
theta=atan2(points[1].y-center.y,points[1].x-center.x)-alpha;
if ((theta < 0.0) && (sweep != MagickFalse))
theta+=(MagickRealType) (2.0*MagickPI);
else
if ((theta > 0.0) && (sweep == MagickFalse))
theta-=(MagickRealType) (2.0*MagickPI);
arc_segments=(size_t) ceil(fabs((double) (theta/(0.5*MagickPI+
MagickEpsilon))));
p=primitive_info;
for (i=0; i < (ssize_t) arc_segments; i++)
{
beta=0.5*((alpha+(i+1)*theta/arc_segments)-(alpha+i*theta/arc_segments));
gamma=(8.0/3.0)*sin(fmod((double) (0.5*beta),DegreesToRadians(360.0)))*
sin(fmod((double) (0.5*beta),DegreesToRadians(360.0)))/
sin(fmod((double) beta,DegreesToRadians(360.0)));
points[0].x=(double) (center.x+cos(fmod((double) (alpha+(double) i*theta/
arc_segments),DegreesToRadians(360.0)))-gamma*sin(fmod((double) (alpha+
(double) i*theta/arc_segments),DegreesToRadians(360.0))));
points[0].y=(double) (center.y+sin(fmod((double) (alpha+(double) i*theta/
arc_segments),DegreesToRadians(360.0)))+gamma*cos(fmod((double) (alpha+
(double) i*theta/arc_segments),DegreesToRadians(360.0))));
points[2].x=(double) (center.x+cos(fmod((double) (alpha+(double) (i+1)*
theta/arc_segments),DegreesToRadians(360.0))));
points[2].y=(double) (center.y+sin(fmod((double) (alpha+(double) (i+1)*
theta/arc_segments),DegreesToRadians(360.0))));
points[1].x=(double) (points[2].x+gamma*sin(fmod((double) (alpha+(double)
(i+1)*theta/arc_segments),DegreesToRadians(360.0))));
points[1].y=(double) (points[2].y-gamma*cos(fmod((double) (alpha+(double)
(i+1)*theta/arc_segments),DegreesToRadians(360.0))));
p->point.x=(p == primitive_info) ? start.x : (p-1)->point.x;
p->point.y=(p == primitive_info) ? start.y : (p-1)->point.y;
(p+1)->point.x=(double) (cosine*radii.x*points[0].x-sine*radii.y*
points[0].y);
(p+1)->point.y=(double) (sine*radii.x*points[0].x+cosine*radii.y*
points[0].y);
(p+2)->point.x=(double) (cosine*radii.x*points[1].x-sine*radii.y*
points[1].y);
(p+2)->point.y=(double) (sine*radii.x*points[1].x+cosine*radii.y*
points[1].y);
(p+3)->point.x=(double) (cosine*radii.x*points[2].x-sine*radii.y*
points[2].y);
(p+3)->point.y=(double) (sine*radii.x*points[2].x+cosine*radii.y*
points[2].y);
if (i == (ssize_t) (arc_segments-1))
(p+3)->point=end;
TraceBezier(p,4);
p+=p->coordinates;
}
primitive_info->coordinates=(size_t) (p-primitive_info);
for (i=0; i < (ssize_t) primitive_info->coordinates; i++)
{
p->primitive=primitive_info->primitive;
p--;
}
}
static void TraceBezier(PrimitiveInfo *primitive_info,
const size_t number_coordinates)
{
MagickRealType
alpha,
*coefficients,
weight;
PointInfo
end,
point,
*points;
register PrimitiveInfo
*p;
register ssize_t
i,
j;
size_t
control_points,
quantum;
/*
Allocate coeficients.
*/
quantum=number_coordinates;
for (i=0; i < (ssize_t) number_coordinates; i++)
{
for (j=i+1; j < (ssize_t) number_coordinates; j++)
{
alpha=fabs(primitive_info[j].point.x-primitive_info[i].point.x);
if (alpha > (MagickRealType) quantum)
quantum=(size_t) alpha;
alpha=fabs(primitive_info[j].point.y-primitive_info[i].point.y);
if (alpha > (MagickRealType) quantum)
quantum=(size_t) alpha;
}
}
quantum=(size_t) MagickMin((double) quantum/number_coordinates,
(double) BezierQuantum);
control_points=quantum*number_coordinates;
coefficients=(MagickRealType *) AcquireQuantumMemory((size_t)
number_coordinates,sizeof(*coefficients));
points=(PointInfo *) AcquireQuantumMemory((size_t) control_points,
sizeof(*points));
if ((coefficients == (MagickRealType *) NULL) ||
(points == (PointInfo *) NULL))
ThrowFatalException(ResourceLimitFatalError,"MemoryAllocationFailed");
/*
Compute bezier points.
*/
end=primitive_info[number_coordinates-1].point;
for (i=0; i < (ssize_t) number_coordinates; i++)
coefficients[i]=Permutate((ssize_t) number_coordinates-1,i);
weight=0.0;
for (i=0; i < (ssize_t) control_points; i++)
{
p=primitive_info;
point.x=0.0;
point.y=0.0;
alpha=pow((double) (1.0-weight),(double) number_coordinates-1.0);
for (j=0; j < (ssize_t) number_coordinates; j++)
{
point.x+=alpha*coefficients[j]*p->point.x;
point.y+=alpha*coefficients[j]*p->point.y;
alpha*=weight/(1.0-weight);
p++;
}
points[i]=point;
weight+=1.0/control_points;
}
/*
Bezier curves are just short segmented polys.
*/
p=primitive_info;
for (i=0; i < (ssize_t) control_points; i++)
{
TracePoint(p,points[i]);
p+=p->coordinates;
}
TracePoint(p,end);
p+=p->coordinates;
primitive_info->coordinates=(size_t) (p-primitive_info);
for (i=0; i < (ssize_t) primitive_info->coordinates; i++)
{
p->primitive=primitive_info->primitive;
p--;
}
points=(PointInfo *) RelinquishMagickMemory(points);
coefficients=(MagickRealType *) RelinquishMagickMemory(coefficients);
}
static void TraceCircle(PrimitiveInfo *primitive_info,const PointInfo start,
const PointInfo end)
{
MagickRealType
alpha,
beta,
radius;
PointInfo
offset,
degrees;
alpha=end.x-start.x;
beta=end.y-start.y;
radius=hypot((double) alpha,(double) beta);
offset.x=(double) radius;
offset.y=(double) radius;
degrees.x=0.0;
degrees.y=360.0;
TraceEllipse(primitive_info,start,offset,degrees);
}
static void TraceEllipse(PrimitiveInfo *primitive_info,const PointInfo start,
const PointInfo stop,const PointInfo degrees)
{
MagickRealType
delta,
step,
y;
PointInfo
angle,
point;
register PrimitiveInfo
*p;
register ssize_t
i;
/*
Ellipses are just short segmented polys.
*/
if ((stop.x == 0.0) && (stop.y == 0.0))
{
TracePoint(primitive_info,start);
return;
}
delta=2.0/MagickMax(stop.x,stop.y);
step=(MagickRealType) (MagickPI/8.0);
if ((delta >= 0.0) && (delta < (MagickRealType) (MagickPI/8.0)))
step=(MagickRealType) (MagickPI/(4*(MagickPI/delta/2+0.5)));
angle.x=DegreesToRadians(degrees.x);
y=degrees.y;
while (y < degrees.x)
y+=360.0;
angle.y=(double) (DegreesToRadians(y)-MagickEpsilon);
for (p=primitive_info; angle.x < angle.y; angle.x+=step)
{
point.x=cos(fmod(angle.x,DegreesToRadians(360.0)))*stop.x+start.x;
point.y=sin(fmod(angle.x,DegreesToRadians(360.0)))*stop.y+start.y;
TracePoint(p,point);
p+=p->coordinates;
}
point.x=cos(fmod(angle.y,DegreesToRadians(360.0)))*stop.x+start.x;
point.y=sin(fmod(angle.y,DegreesToRadians(360.0)))*stop.y+start.y;
TracePoint(p,point);
p+=p->coordinates;
primitive_info->coordinates=(size_t) (p-primitive_info);
for (i=0; i < (ssize_t) primitive_info->coordinates; i++)
{
p->primitive=primitive_info->primitive;
p--;
}
}
static void TraceLine(PrimitiveInfo *primitive_info,const PointInfo start,
const PointInfo end)
{
TracePoint(primitive_info,start);
if ((fabs(start.x-end.x) <= MagickEpsilon) &&
(fabs(start.y-end.y) <= MagickEpsilon))
{
primitive_info->primitive=PointPrimitive;
primitive_info->coordinates=1;
return;
}
TracePoint(primitive_info+1,end);
(primitive_info+1)->primitive=primitive_info->primitive;
primitive_info->coordinates=2;
}
static size_t TracePath(PrimitiveInfo *primitive_info,const char *path)
{
char
token[MaxTextExtent];
const char
*p;
int
attribute,
last_attribute;
MagickRealType
x,
y;
PointInfo
end,
points[4],
point,
start;
PrimitiveType
primitive_type;
register PrimitiveInfo
*q;
register ssize_t
i;
size_t
number_coordinates,
z_count;
attribute=0;
point.x=0.0;
point.y=0.0;
start.x=0.0;
start.y=0.0;
number_coordinates=0;
z_count=0;
primitive_type=primitive_info->primitive;
q=primitive_info;
for (p=path; *p != '\0'; )
{
while (isspace((int) ((unsigned char) *p)) != 0)
p++;
if (*p == '\0')
break;
last_attribute=attribute;
attribute=(int) (*p++);
switch (attribute)
{
case 'a':
case 'A':
{
MagickBooleanType
large_arc,
sweep;
MagickRealType
angle;
PointInfo
arc;
/*
Compute arc points.
*/
do
{
GetMagickToken(p,&p,token);
if (*token == ',')
GetMagickToken(p,&p,token);
arc.x=StringToDouble(token);
GetMagickToken(p,&p,token);
if (*token == ',')
GetMagickToken(p,&p,token);
arc.y=StringToDouble(token);
GetMagickToken(p,&p,token);
if (*token == ',')
GetMagickToken(p,&p,token);
angle=StringToDouble(token);
GetMagickToken(p,&p,token);
if (*token == ',')
GetMagickToken(p,&p,token);
large_arc=StringToLong(token) != 0 ? MagickTrue : MagickFalse;
GetMagickToken(p,&p,token);
if (*token == ',')
GetMagickToken(p,&p,token);
sweep=StringToLong(token) != 0 ? MagickTrue : MagickFalse;
GetMagickToken(p,&p,token);
if (*token == ',')
GetMagickToken(p,&p,token);
x=StringToDouble(token);
GetMagickToken(p,&p,token);
if (*token == ',')
GetMagickToken(p,&p,token);
y=StringToDouble(token);
end.x=(double) (attribute == (int) 'A' ? x : point.x+x);
end.y=(double) (attribute == (int) 'A' ? y : point.y+y);
TraceArcPath(q,point,end,arc,angle,large_arc,sweep);
q+=q->coordinates;
point=end;
} while (IsPoint(p) != MagickFalse);
break;
}
case 'c':
case 'C':
{
/*
Compute bezier points.
*/
do
{
points[0]=point;
for (i=1; i < 4; i++)
{
GetMagickToken(p,&p,token);
if (*token == ',')
GetMagickToken(p,&p,token);
x=StringToDouble(token);
GetMagickToken(p,&p,token);
if (*token == ',')
GetMagickToken(p,&p,token);
y=StringToDouble(token);
end.x=(double) (attribute == (int) 'C' ? x : point.x+x);
end.y=(double) (attribute == (int) 'C' ? y : point.y+y);
points[i]=end;
}
for (i=0; i < 4; i++)
(q+i)->point=points[i];
TraceBezier(q,4);
q+=q->coordinates;
point=end;
} while (IsPoint(p) != MagickFalse);
break;
}
case 'H':
case 'h':
{
do
{
GetMagickToken(p,&p,token);
if (*token == ',')
GetMagickToken(p,&p,token);
x=StringToDouble(token);
point.x=(double) (attribute == (int) 'H' ? x: point.x+x);
TracePoint(q,point);
q+=q->coordinates;
} while (IsPoint(p) != MagickFalse);
break;
}
case 'l':
case 'L':
{
do
{
GetMagickToken(p,&p,token);
if (*token == ',')
GetMagickToken(p,&p,token);
x=StringToDouble(token);
GetMagickToken(p,&p,token);
if (*token == ',')
GetMagickToken(p,&p,token);
y=StringToDouble(token);
point.x=(double) (attribute == (int) 'L' ? x : point.x+x);
point.y=(double) (attribute == (int) 'L' ? y : point.y+y);
TracePoint(q,point);
q+=q->coordinates;
} while (IsPoint(p) != MagickFalse);
break;
}
case 'M':
case 'm':
{
if (q != primitive_info)
{
primitive_info->coordinates=(size_t) (q-primitive_info);
number_coordinates+=primitive_info->coordinates;
primitive_info=q;
}
i=0;
do
{
GetMagickToken(p,&p,token);
if (*token == ',')
GetMagickToken(p,&p,token);
x=StringToDouble(token);
GetMagickToken(p,&p,token);
if (*token == ',')
GetMagickToken(p,&p,token);
y=StringToDouble(token);
point.x=(double) (attribute == (int) 'M' ? x : point.x+x);
point.y=(double) (attribute == (int) 'M' ? y : point.y+y);
if (i == 0)
start=point;
i++;
TracePoint(q,point);
q+=q->coordinates;
if ((i != 0) && (attribute == (int) 'M'))
{
TracePoint(q,point);
q+=q->coordinates;
}
} while (IsPoint(p) != MagickFalse);
break;
}
case 'q':
case 'Q':
{
/*
Compute bezier points.
*/
do
{
points[0]=point;
for (i=1; i < 3; i++)
{
GetMagickToken(p,&p,token);
if (*token == ',')
GetMagickToken(p,&p,token);
x=StringToDouble(token);
GetMagickToken(p,&p,token);
if (*token == ',')
GetMagickToken(p,&p,token);
y=StringToDouble(token);
if (*p == ',')
p++;
end.x=(double) (attribute == (int) 'Q' ? x : point.x+x);
end.y=(double) (attribute == (int) 'Q' ? y : point.y+y);
points[i]=end;
}
for (i=0; i < 3; i++)
(q+i)->point=points[i];
TraceBezier(q,3);
q+=q->coordinates;
point=end;
} while (IsPoint(p) != MagickFalse);
break;
}
case 's':
case 'S':
{
/*
Compute bezier points.
*/
do
{
points[0]=points[3];
points[1].x=2.0*points[3].x-points[2].x;
points[1].y=2.0*points[3].y-points[2].y;
for (i=2; i < 4; i++)
{
GetMagickToken(p,&p,token);
if (*token == ',')
GetMagickToken(p,&p,token);
x=StringToDouble(token);
GetMagickToken(p,&p,token);
if (*token == ',')
GetMagickToken(p,&p,token);
y=StringToDouble(token);
if (*p == ',')
p++;
end.x=(double) (attribute == (int) 'S' ? x : point.x+x);
end.y=(double) (attribute == (int) 'S' ? y : point.y+y);
points[i]=end;
}
if (strchr("CcSs",last_attribute) == (char *) NULL)
{
points[0]=points[2];
points[1]=points[3];
}
for (i=0; i < 4; i++)
(q+i)->point=points[i];
TraceBezier(q,4);
q+=q->coordinates;
point=end;
} while (IsPoint(p) != MagickFalse);
break;
}
case 't':
case 'T':
{
/*
Compute bezier points.
*/
do
{
points[0]=points[2];
points[1].x=2.0*points[2].x-points[1].x;
points[1].y=2.0*points[2].y-points[1].y;
for (i=2; i < 3; i++)
{
GetMagickToken(p,&p,token);
if (*token == ',')
GetMagickToken(p,&p,token);
x=StringToDouble(token);
GetMagickToken(p,&p,token);
if (*token == ',')
GetMagickToken(p,&p,token);
y=StringToDouble(token);
end.x=(double) (attribute == (int) 'T' ? x : point.x+x);
end.y=(double) (attribute == (int) 'T' ? y : point.y+y);
points[i]=end;
}
if (strchr("QqTt",last_attribute) == (char *) NULL)
{
points[0]=points[2];
points[1]=points[3];
}
for (i=0; i < 3; i++)
(q+i)->point=points[i];
TraceBezier(q,3);
q+=q->coordinates;
point=end;
} while (IsPoint(p) != MagickFalse);
break;
}
case 'v':
case 'V':
{
do
{
GetMagickToken(p,&p,token);
if (*token == ',')
GetMagickToken(p,&p,token);
y=StringToDouble(token);
point.y=(double) (attribute == (int) 'V' ? y : point.y+y);
TracePoint(q,point);
q+=q->coordinates;
} while (IsPoint(p) != MagickFalse);
break;
}
case 'z':
case 'Z':
{
point=start;
TracePoint(q,point);
q+=q->coordinates;
primitive_info->coordinates=(size_t) (q-primitive_info);
number_coordinates+=primitive_info->coordinates;
primitive_info=q;
z_count++;
break;
}
default:
{
if (isalpha((int) ((unsigned char) attribute)) != 0)
(void) fprintf(stderr,"attribute not recognized: %c\n",attribute);
break;
}
}
}
primitive_info->coordinates=(size_t) (q-primitive_info);
number_coordinates+=primitive_info->coordinates;
for (i=0; i < (ssize_t) number_coordinates; i++)
{
q--;
q->primitive=primitive_type;
if (z_count > 1)
q->method=FillToBorderMethod;
}
q=primitive_info;
return(number_coordinates);
}
static void TraceRectangle(PrimitiveInfo *primitive_info,const PointInfo start,
const PointInfo end)
{
PointInfo
point;
register PrimitiveInfo
*p;
register ssize_t
i;
p=primitive_info;
TracePoint(p,start);
p+=p->coordinates;
point.x=start.x;
point.y=end.y;
TracePoint(p,point);
p+=p->coordinates;
TracePoint(p,end);
p+=p->coordinates;
point.x=end.x;
point.y=start.y;
TracePoint(p,point);
p+=p->coordinates;
TracePoint(p,start);
p+=p->coordinates;
primitive_info->coordinates=(size_t) (p-primitive_info);
for (i=0; i < (ssize_t) primitive_info->coordinates; i++)
{
p->primitive=primitive_info->primitive;
p--;
}
}
static void TraceRoundRectangle(PrimitiveInfo *primitive_info,
const PointInfo start,const PointInfo end,PointInfo arc)
{
PointInfo
degrees,
offset,
point;
register PrimitiveInfo
*p;
register ssize_t
i;
p=primitive_info;
offset.x=fabs(end.x-start.x);
offset.y=fabs(end.y-start.y);
if (arc.x > (0.5*offset.x))
arc.x=0.5*offset.x;
if (arc.y > (0.5*offset.y))
arc.y=0.5*offset.y;
point.x=start.x+offset.x-arc.x;
point.y=start.y+arc.y;
degrees.x=270.0;
degrees.y=360.0;
TraceEllipse(p,point,arc,degrees);
p+=p->coordinates;
point.x=start.x+offset.x-arc.x;
point.y=start.y+offset.y-arc.y;
degrees.x=0.0;
degrees.y=90.0;
TraceEllipse(p,point,arc,degrees);
p+=p->coordinates;
point.x=start.x+arc.x;
point.y=start.y+offset.y-arc.y;
degrees.x=90.0;
degrees.y=180.0;
TraceEllipse(p,point,arc,degrees);
p+=p->coordinates;
point.x=start.x+arc.x;
point.y=start.y+arc.y;
degrees.x=180.0;
degrees.y=270.0;
TraceEllipse(p,point,arc,degrees);
p+=p->coordinates;
TracePoint(p,primitive_info->point);
p+=p->coordinates;
primitive_info->coordinates=(size_t) (p-primitive_info);
for (i=0; i < (ssize_t) primitive_info->coordinates; i++)
{
p->primitive=primitive_info->primitive;
p--;
}
}
static void TraceSquareLinecap(PrimitiveInfo *primitive_info,
const size_t number_vertices,const MagickRealType offset)
{
MagickRealType
distance;
register MagickRealType
dx,
dy;
register ssize_t
i;
ssize_t
j;
dx=0.0;
dy=0.0;
for (i=1; i < (ssize_t) number_vertices; i++)
{
dx=primitive_info[0].point.x-primitive_info[i].point.x;
dy=primitive_info[0].point.y-primitive_info[i].point.y;
if ((fabs((double) dx) >= MagickEpsilon) ||
(fabs((double) dy) >= MagickEpsilon))
break;
}
if (i == (ssize_t) number_vertices)
i=(ssize_t) number_vertices-1L;
distance=hypot((double) dx,(double) dy);
primitive_info[0].point.x=(double) (primitive_info[i].point.x+
dx*(distance+offset)/distance);
primitive_info[0].point.y=(double) (primitive_info[i].point.y+
dy*(distance+offset)/distance);
for (j=(ssize_t) number_vertices-2; j >= 0; j--)
{
dx=primitive_info[number_vertices-1].point.x-primitive_info[j].point.x;
dy=primitive_info[number_vertices-1].point.y-primitive_info[j].point.y;
if ((fabs((double) dx) >= MagickEpsilon) ||
(fabs((double) dy) >= MagickEpsilon))
break;
}
distance=hypot((double) dx,(double) dy);
primitive_info[number_vertices-1].point.x=(double) (primitive_info[j].point.x+
dx*(distance+offset)/distance);
primitive_info[number_vertices-1].point.y=(double) (primitive_info[j].point.y+
dy*(distance+offset)/distance);
}
static PrimitiveInfo *TraceStrokePolygon(const DrawInfo *draw_info,
const PrimitiveInfo *primitive_info)
{
typedef struct _LineSegment
{
double
p,
q;
} LineSegment;
LineSegment
dx,
dy,
inverse_slope,
slope,
theta;
MagickBooleanType
closed_path;
MagickRealType
delta_theta,
dot_product,
mid,
miterlimit;
PointInfo
box_p[5],
box_q[5],
center,
offset,
*path_p,
*path_q;
PrimitiveInfo
*polygon_primitive,
*stroke_polygon;
register ssize_t
i;
size_t
arc_segments,
max_strokes,
number_vertices;
ssize_t
j,
n,
p,
q;
/*
Allocate paths.
*/
number_vertices=primitive_info->coordinates;
max_strokes=2*number_vertices+6*BezierQuantum+360;
path_p=(PointInfo *) AcquireQuantumMemory((size_t) max_strokes,
sizeof(*path_p));
path_q=(PointInfo *) AcquireQuantumMemory((size_t) max_strokes,
sizeof(*path_q));
polygon_primitive=(PrimitiveInfo *) AcquireQuantumMemory((size_t)
number_vertices+2UL,sizeof(*polygon_primitive));
if ((path_p == (PointInfo *) NULL) || (path_q == (PointInfo *) NULL) ||
(polygon_primitive == (PrimitiveInfo *) NULL))
return((PrimitiveInfo *) NULL);
(void) CopyMagickMemory(polygon_primitive,primitive_info,(size_t)
number_vertices*sizeof(*polygon_primitive));
closed_path=
(primitive_info[number_vertices-1].point.x == primitive_info[0].point.x) &&
(primitive_info[number_vertices-1].point.y == primitive_info[0].point.y) ?
MagickTrue : MagickFalse;
if ((draw_info->linejoin == RoundJoin) ||
((draw_info->linejoin == MiterJoin) && (closed_path != MagickFalse)))
{
polygon_primitive[number_vertices]=primitive_info[1];
number_vertices++;
}
polygon_primitive[number_vertices].primitive=UndefinedPrimitive;
/*
Compute the slope for the first line segment, p.
*/
dx.p=0.0;
dy.p=0.0;
for (n=1; n < (ssize_t) number_vertices; n++)
{
dx.p=polygon_primitive[n].point.x-polygon_primitive[0].point.x;
dy.p=polygon_primitive[n].point.y-polygon_primitive[0].point.y;
if ((fabs(dx.p) >= MagickEpsilon) || (fabs(dy.p) >= MagickEpsilon))
break;
}
if (n == (ssize_t) number_vertices)
n=(ssize_t) number_vertices-1L;
slope.p=0.0;
inverse_slope.p=0.0;
if (fabs(dx.p) <= MagickEpsilon)
{
if (dx.p >= 0.0)
slope.p=dy.p < 0.0 ? -1.0/MagickEpsilon : 1.0/MagickEpsilon;
else
slope.p=dy.p < 0.0 ? 1.0/MagickEpsilon : -1.0/MagickEpsilon;
}
else
if (fabs(dy.p) <= MagickEpsilon)
{
if (dy.p >= 0.0)
inverse_slope.p=dx.p < 0.0 ? -1.0/MagickEpsilon : 1.0/MagickEpsilon;
else
inverse_slope.p=dx.p < 0.0 ? 1.0/MagickEpsilon : -1.0/MagickEpsilon;
}
else
{
slope.p=dy.p/dx.p;
inverse_slope.p=(-1.0/slope.p);
}
mid=ExpandAffine(&draw_info->affine)*draw_info->stroke_width/2.0;
miterlimit=(MagickRealType) (draw_info->miterlimit*draw_info->miterlimit*
mid*mid);
if ((draw_info->linecap == SquareCap) && (closed_path == MagickFalse))
TraceSquareLinecap(polygon_primitive,number_vertices,mid);
offset.x=sqrt((double) (mid*mid/(inverse_slope.p*inverse_slope.p+1.0)));
offset.y=(double) (offset.x*inverse_slope.p);
if ((dy.p*offset.x-dx.p*offset.y) > 0.0)
{
box_p[0].x=polygon_primitive[0].point.x-offset.x;
box_p[0].y=polygon_primitive[0].point.y-offset.x*inverse_slope.p;
box_p[1].x=polygon_primitive[n].point.x-offset.x;
box_p[1].y=polygon_primitive[n].point.y-offset.x*inverse_slope.p;
box_q[0].x=polygon_primitive[0].point.x+offset.x;
box_q[0].y=polygon_primitive[0].point.y+offset.x*inverse_slope.p;
box_q[1].x=polygon_primitive[n].point.x+offset.x;
box_q[1].y=polygon_primitive[n].point.y+offset.x*inverse_slope.p;
}
else
{
box_p[0].x=polygon_primitive[0].point.x+offset.x;
box_p[0].y=polygon_primitive[0].point.y+offset.y;
box_p[1].x=polygon_primitive[n].point.x+offset.x;
box_p[1].y=polygon_primitive[n].point.y+offset.y;
box_q[0].x=polygon_primitive[0].point.x-offset.x;
box_q[0].y=polygon_primitive[0].point.y-offset.y;
box_q[1].x=polygon_primitive[n].point.x-offset.x;
box_q[1].y=polygon_primitive[n].point.y-offset.y;
}
/*
Create strokes for the line join attribute: bevel, miter, round.
*/
p=0;
q=0;
path_q[p++]=box_q[0];
path_p[q++]=box_p[0];
for (i=(ssize_t) n+1; i < (ssize_t) number_vertices; i++)
{
/*
Compute the slope for this line segment, q.
*/
dx.q=polygon_primitive[i].point.x-polygon_primitive[n].point.x;
dy.q=polygon_primitive[i].point.y-polygon_primitive[n].point.y;
dot_product=dx.q*dx.q+dy.q*dy.q;
if (dot_product < 0.25)
continue;
slope.q=0.0;
inverse_slope.q=0.0;
if (fabs(dx.q) < MagickEpsilon)
{
if (dx.q >= 0.0)
slope.q=dy.q < 0.0 ? -1.0/MagickEpsilon : 1.0/MagickEpsilon;
else
slope.q=dy.q < 0.0 ? 1.0/MagickEpsilon : -1.0/MagickEpsilon;
}
else
if (fabs(dy.q) <= MagickEpsilon)
{
if (dy.q >= 0.0)
inverse_slope.q=dx.q < 0.0 ? -1.0/MagickEpsilon : 1.0/MagickEpsilon;
else
inverse_slope.q=dx.q < 0.0 ? 1.0/MagickEpsilon : -1.0/MagickEpsilon;
}
else
{
slope.q=dy.q/dx.q;
inverse_slope.q=(-1.0/slope.q);
}
offset.x=sqrt((double) (mid*mid/(inverse_slope.q*inverse_slope.q+1.0)));
offset.y=(double) (offset.x*inverse_slope.q);
dot_product=dy.q*offset.x-dx.q*offset.y;
if (dot_product > 0.0)
{
box_p[2].x=polygon_primitive[n].point.x-offset.x;
box_p[2].y=polygon_primitive[n].point.y-offset.y;
box_p[3].x=polygon_primitive[i].point.x-offset.x;
box_p[3].y=polygon_primitive[i].point.y-offset.y;
box_q[2].x=polygon_primitive[n].point.x+offset.x;
box_q[2].y=polygon_primitive[n].point.y+offset.y;
box_q[3].x=polygon_primitive[i].point.x+offset.x;
box_q[3].y=polygon_primitive[i].point.y+offset.y;
}
else
{
box_p[2].x=polygon_primitive[n].point.x+offset.x;
box_p[2].y=polygon_primitive[n].point.y+offset.y;
box_p[3].x=polygon_primitive[i].point.x+offset.x;
box_p[3].y=polygon_primitive[i].point.y+offset.y;
box_q[2].x=polygon_primitive[n].point.x-offset.x;
box_q[2].y=polygon_primitive[n].point.y-offset.y;
box_q[3].x=polygon_primitive[i].point.x-offset.x;
box_q[3].y=polygon_primitive[i].point.y-offset.y;
}
if (fabs((double) (slope.p-slope.q)) <= MagickEpsilon)
{
box_p[4]=box_p[1];
box_q[4]=box_q[1];
}
else
{
box_p[4].x=(double) ((slope.p*box_p[0].x-box_p[0].y-slope.q*box_p[3].x+
box_p[3].y)/(slope.p-slope.q));
box_p[4].y=(double) (slope.p*(box_p[4].x-box_p[0].x)+box_p[0].y);
box_q[4].x=(double) ((slope.p*box_q[0].x-box_q[0].y-slope.q*box_q[3].x+
box_q[3].y)/(slope.p-slope.q));
box_q[4].y=(double) (slope.p*(box_q[4].x-box_q[0].x)+box_q[0].y);
}
if (q >= (ssize_t) (max_strokes-6*BezierQuantum-360))
{
max_strokes+=6*BezierQuantum+360;
path_p=(PointInfo *) ResizeQuantumMemory(path_p,(size_t) max_strokes,
sizeof(*path_p));
path_q=(PointInfo *) ResizeQuantumMemory(path_q,(size_t) max_strokes,
sizeof(*path_q));
if ((path_p == (PointInfo *) NULL) || (path_q == (PointInfo *) NULL))
{
polygon_primitive=(PrimitiveInfo *)
RelinquishMagickMemory(polygon_primitive);
return((PrimitiveInfo *) NULL);
}
}
dot_product=dx.q*dy.p-dx.p*dy.q;
if (dot_product <= 0.0)
switch (draw_info->linejoin)
{
case BevelJoin:
{
path_q[q++]=box_q[1];
path_q[q++]=box_q[2];
dot_product=(box_q[4].x-box_p[4].x)*(box_q[4].x-box_p[4].x)+
(box_q[4].y-box_p[4].y)*(box_q[4].y-box_p[4].y);
if (dot_product <= miterlimit)
path_p[p++]=box_p[4];
else
{
path_p[p++]=box_p[1];
path_p[p++]=box_p[2];
}
break;
}
case MiterJoin:
{
dot_product=(box_q[4].x-box_p[4].x)*(box_q[4].x-box_p[4].x)+
(box_q[4].y-box_p[4].y)*(box_q[4].y-box_p[4].y);
if (dot_product <= miterlimit)
{
path_q[q++]=box_q[4];
path_p[p++]=box_p[4];
}
else
{
path_q[q++]=box_q[1];
path_q[q++]=box_q[2];
path_p[p++]=box_p[1];
path_p[p++]=box_p[2];
}
break;
}
case RoundJoin:
{
dot_product=(box_q[4].x-box_p[4].x)*(box_q[4].x-box_p[4].x)+
(box_q[4].y-box_p[4].y)*(box_q[4].y-box_p[4].y);
if (dot_product <= miterlimit)
path_p[p++]=box_p[4];
else
{
path_p[p++]=box_p[1];
path_p[p++]=box_p[2];
}
center=polygon_primitive[n].point;
theta.p=atan2(box_q[1].y-center.y,box_q[1].x-center.x);
theta.q=atan2(box_q[2].y-center.y,box_q[2].x-center.x);
if (theta.q < theta.p)
theta.q+=(MagickRealType) (2.0*MagickPI);
arc_segments=(size_t) ceil((double) ((theta.q-theta.p)/
(2.0*sqrt((double) (1.0/mid)))));
path_q[q].x=box_q[1].x;
path_q[q].y=box_q[1].y;
q++;
for (j=1; j < (ssize_t) arc_segments; j++)
{
delta_theta=(MagickRealType) (j*(theta.q-theta.p)/arc_segments);
path_q[q].x=(double) (center.x+mid*cos(fmod((double)
(theta.p+delta_theta),DegreesToRadians(360.0))));
path_q[q].y=(double) (center.y+mid*sin(fmod((double)
(theta.p+delta_theta),DegreesToRadians(360.0))));
q++;
}
path_q[q++]=box_q[2];
break;
}
default:
break;
}
else
switch (draw_info->linejoin)
{
case BevelJoin:
{
path_p[p++]=box_p[1];
path_p[p++]=box_p[2];
dot_product=(box_q[4].x-box_p[4].x)*(box_q[4].x-box_p[4].x)+
(box_q[4].y-box_p[4].y)*(box_q[4].y-box_p[4].y);
if (dot_product <= miterlimit)
path_q[q++]=box_q[4];
else
{
path_q[q++]=box_q[1];
path_q[q++]=box_q[2];
}
break;
}
case MiterJoin:
{
dot_product=(box_q[4].x-box_p[4].x)*(box_q[4].x-box_p[4].x)+
(box_q[4].y-box_p[4].y)*(box_q[4].y-box_p[4].y);
if (dot_product <= miterlimit)
{
path_q[q++]=box_q[4];
path_p[p++]=box_p[4];
}
else
{
path_q[q++]=box_q[1];
path_q[q++]=box_q[2];
path_p[p++]=box_p[1];
path_p[p++]=box_p[2];
}
break;
}
case RoundJoin:
{
dot_product=(box_q[4].x-box_p[4].x)*(box_q[4].x-box_p[4].x)+
(box_q[4].y-box_p[4].y)*(box_q[4].y-box_p[4].y);
if (dot_product <= miterlimit)
path_q[q++]=box_q[4];
else
{
path_q[q++]=box_q[1];
path_q[q++]=box_q[2];
}
center=polygon_primitive[n].point;
theta.p=atan2(box_p[1].y-center.y,box_p[1].x-center.x);
theta.q=atan2(box_p[2].y-center.y,box_p[2].x-center.x);
if (theta.p < theta.q)
theta.p+=(MagickRealType) (2.0*MagickPI);
arc_segments=(size_t) ceil((double) ((theta.p-theta.q)/
(2.0*sqrt((double) (1.0/mid)))));
path_p[p++]=box_p[1];
for (j=1; j < (ssize_t) arc_segments; j++)
{
delta_theta=(MagickRealType) (j*(theta.q-theta.p)/arc_segments);
path_p[p].x=(double) (center.x+mid*cos(fmod((double)
(theta.p+delta_theta),DegreesToRadians(360.0))));
path_p[p].y=(double) (center.y+mid*sin(fmod((double)
(theta.p+delta_theta),DegreesToRadians(360.0))));
p++;
}
path_p[p++]=box_p[2];
break;
}
default:
break;
}
slope.p=slope.q;
inverse_slope.p=inverse_slope.q;
box_p[0]=box_p[2];
box_p[1]=box_p[3];
box_q[0]=box_q[2];
box_q[1]=box_q[3];
dx.p=dx.q;
dy.p=dy.q;
n=i;
}
path_p[p++]=box_p[1];
path_q[q++]=box_q[1];
/*
Trace stroked polygon.
*/
stroke_polygon=(PrimitiveInfo *) AcquireQuantumMemory((size_t)
(p+q+2UL*closed_path+2UL),sizeof(*stroke_polygon));
if (stroke_polygon != (PrimitiveInfo *) NULL)
{
for (i=0; i < (ssize_t) p; i++)
{
stroke_polygon[i]=polygon_primitive[0];
stroke_polygon[i].point=path_p[i];
}
if (closed_path != MagickFalse)
{
stroke_polygon[i]=polygon_primitive[0];
stroke_polygon[i].point=stroke_polygon[0].point;
i++;
}
for ( ; i < (ssize_t) (p+q+closed_path); i++)
{
stroke_polygon[i]=polygon_primitive[0];
stroke_polygon[i].point=path_q[p+q+closed_path-(i+1)];
}
if (closed_path != MagickFalse)
{
stroke_polygon[i]=polygon_primitive[0];
stroke_polygon[i].point=stroke_polygon[p+closed_path].point;
i++;
}
stroke_polygon[i]=polygon_primitive[0];
stroke_polygon[i].point=stroke_polygon[0].point;
i++;
stroke_polygon[i].primitive=UndefinedPrimitive;
stroke_polygon[0].coordinates=(size_t) (p+q+2*closed_path+1);
}
path_p=(PointInfo *) RelinquishMagickMemory(path_p);
path_q=(PointInfo *) RelinquishMagickMemory(path_q);
polygon_primitive=(PrimitiveInfo *) RelinquishMagickMemory(polygon_primitive);
return(stroke_polygon);
}
|
GB_binop__ne_fc32.c | //------------------------------------------------------------------------------
// GB_binop: hard-coded functions for each built-in binary operator
//------------------------------------------------------------------------------
// SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2021, All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
//------------------------------------------------------------------------------
// If this file is in the 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__ne_fc32
// A.*B function (eWiseMult): GB_AemultB__ne_fc32
// A*D function (colscale): (none)
// D*A function (rowscale): (node)
// C+=B function (dense accum): GB_Cdense_accumB__ne_fc32
// C+=b function (dense accum): GB_Cdense_accumb__ne_fc32
// C+=A+B function (dense ewise3): (none)
// C=A+B function (dense ewise3): GB_Cdense_ewise3_noaccum__ne_fc32
// C=scalar+B GB_bind1st__ne_fc32
// C=scalar+B' GB_bind1st_tran__ne_fc32
// C=A+scalar GB_bind2nd__ne_fc32
// C=A'+scalar GB_bind2nd_tran__ne_fc32
// C type: bool
// A type: GxB_FC32_t
// B,b type: GxB_FC32_t
// BinaryOp: cij = GB_FC32_ne (aij, bij)
#define GB_ATYPE \
GxB_FC32_t
#define GB_BTYPE \
GxB_FC32_t
#define GB_CTYPE \
bool
// true if the types of A and B are identical
#define GB_ATYPE_IS_BTYPE \
1
// true if the types of C and A are identical
#define GB_CTYPE_IS_ATYPE \
0
// true if the types of C and B are identical
#define GB_CTYPE_IS_BTYPE \
0
// aij = Ax [pA]
#define GB_GETA(aij,Ax,pA) \
GxB_FC32_t aij = Ax [pA]
// bij = Bx [pB]
#define GB_GETB(bij,Bx,pB) \
GxB_FC32_t bij = Bx [pB]
// declare scalar of the same type as C
#define GB_CTYPE_SCALAR(t) \
bool t
// cij = Ax [pA]
#define GB_COPY_A_TO_C(cij,Ax,pA) \
cij = (crealf (Ax [pA]) != 0) || (cimagf (Ax [pA]) != 0)
// cij = Bx [pB]
#define GB_COPY_B_TO_C(cij,Bx,pB) \
cij = (crealf (Bx [pB]) != 0) || (cimagf (Bx [pB]) != 0)
#define GB_CX(p) Cx [p]
// binary operator
#define GB_BINOP(z, x, y, i, j) \
z = GB_FC32_ne (x, y) ;
// op is second
#define GB_OP_IS_SECOND \
0
// op is plus_fp32 or plus_fp64
#define GB_OP_IS_PLUS_REAL \
0
// op is minus_fp32 or minus_fp64
#define GB_OP_IS_MINUS_REAL \
0
// GB_cblas_*axpy gateway routine, if it exists for this operator and type:
#define GB_CBLAS_AXPY \
(none)
// do the numerical phases of GB_add and GB_emult
#define GB_PHASE_2_OF_2
// hard-coded loops can be vectorized
#define GB_PRAGMA_SIMD_VECTORIZE GB_PRAGMA_SIMD
// disable this operator and use the generic case if these conditions hold
#define GB_DISABLE \
(GxB_NO_NE || GxB_NO_FC32 || GxB_NO_NE_FC32)
//------------------------------------------------------------------------------
// 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__ne_fc32
(
GrB_Matrix C,
const GrB_Matrix A,
const GrB_Matrix B,
const int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
#include "GB_dense_ewise3_noaccum_template.c"
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// C += B, accumulate a sparse matrix into a dense matrix
//------------------------------------------------------------------------------
GrB_Info GB_Cdense_accumB__ne_fc32
(
GrB_Matrix C,
const GrB_Matrix B,
const int64_t *GB_RESTRICT kfirst_slice,
const int64_t *GB_RESTRICT klast_slice,
const int64_t *GB_RESTRICT pstart_slice,
const int ntasks,
const int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
#if 0
{
#include "GB_dense_subassign_23_template.c"
}
#endif
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// C += b, accumulate a scalar into a dense matrix
//------------------------------------------------------------------------------
GrB_Info GB_Cdense_accumb__ne_fc32
(
GrB_Matrix C,
const GB_void *p_bwork,
const int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
#if 0
{
// get the scalar b for C += b, of type GxB_FC32_t
GxB_FC32_t bwork = (*((GxB_FC32_t *) p_bwork)) ;
#include "GB_dense_subassign_22_template.c"
return (GrB_SUCCESS) ;
}
#endif
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// C = A*D, column scale with diagonal D matrix
//------------------------------------------------------------------------------
#if 0
GrB_Info (none)
(
GrB_Matrix C,
const GrB_Matrix A, bool A_is_pattern,
const GrB_Matrix D, bool D_is_pattern,
const int64_t *GB_RESTRICT kfirst_slice,
const int64_t *GB_RESTRICT klast_slice,
const int64_t *GB_RESTRICT pstart_slice,
const int ntasks,
const int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
bool *GB_RESTRICT Cx = (bool *) C->x ;
#include "GB_AxB_colscale_meta.c"
return (GrB_SUCCESS) ;
#endif
}
#endif
//------------------------------------------------------------------------------
// C = D*B, row scale with diagonal D matrix
//------------------------------------------------------------------------------
#if 0
GrB_Info (node)
(
GrB_Matrix C,
const GrB_Matrix D, bool D_is_pattern,
const GrB_Matrix B, bool B_is_pattern,
int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
bool *GB_RESTRICT Cx = (bool *) C->x ;
#include "GB_AxB_rowscale_meta.c"
return (GrB_SUCCESS) ;
#endif
}
#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__ne_fc32
(
GrB_Matrix C,
const int C_sparsity,
const GrB_Matrix M,
const bool Mask_struct,
const bool Mask_comp,
const GrB_Matrix A,
const GrB_Matrix B,
const bool Ch_is_Mh,
const int64_t *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__ne_fc32
(
GrB_Matrix C,
const int C_sparsity,
const GrB_Matrix M,
const bool Mask_struct,
const bool Mask_comp,
const GrB_Matrix A,
const GrB_Matrix B,
const 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__ne_fc32
(
GB_void *Cx_output, // Cx and Bx may be aliased
const GB_void *x_input,
const GB_void *Bx_input,
const int8_t *GB_RESTRICT Bb,
int64_t anz,
int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
bool *Cx = (bool *) Cx_output ;
GxB_FC32_t x = (*((GxB_FC32_t *) x_input)) ;
GxB_FC32_t *Bx = (GxB_FC32_t *) Bx_input ;
int64_t p ;
#pragma omp parallel for num_threads(nthreads) schedule(static)
for (p = 0 ; p < anz ; p++)
{
if (!GBB (Bb, p)) continue ;
GxB_FC32_t bij = Bx [p] ;
Cx [p] = GB_FC32_ne (x, bij) ;
}
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// Cx = op (Ax,y): apply a binary operator to a matrix with scalar bind2nd
//------------------------------------------------------------------------------
GrB_Info GB_bind2nd__ne_fc32
(
GB_void *Cx_output, // Cx and Ax may be aliased
const GB_void *Ax_input,
const GB_void *y_input,
const int8_t *GB_RESTRICT Ab,
int64_t anz,
int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
int64_t p ;
bool *Cx = (bool *) Cx_output ;
GxB_FC32_t *Ax = (GxB_FC32_t *) Ax_input ;
GxB_FC32_t y = (*((GxB_FC32_t *) y_input)) ;
#pragma omp parallel for num_threads(nthreads) schedule(static)
for (p = 0 ; p < anz ; p++)
{
if (!GBB (Ab, p)) continue ;
GxB_FC32_t aij = Ax [p] ;
Cx [p] = GB_FC32_ne (aij, y) ;
}
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// C = op (x, A'): transpose and apply a binary operator
//------------------------------------------------------------------------------
// cij = op (x, aij), no typecasting (in spite of the macro name)
#undef GB_CAST_OP
#define GB_CAST_OP(pC,pA) \
{ \
GxB_FC32_t aij = Ax [pA] ; \
Cx [pC] = GB_FC32_ne (x, aij) ; \
}
GrB_Info GB_bind1st_tran__ne_fc32
(
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 \
GxB_FC32_t
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
GxB_FC32_t x = (*((const GxB_FC32_t *) x_input)) ;
#include "GB_unop_transpose.c"
return (GrB_SUCCESS) ;
#endif
#undef GB_ATYPE
#define GB_ATYPE \
GxB_FC32_t
}
//------------------------------------------------------------------------------
// C = op (A', y): transpose and apply a binary operator
//------------------------------------------------------------------------------
// cij = op (aij, y), no typecasting (in spite of the macro name)
#undef GB_CAST_OP
#define GB_CAST_OP(pC,pA) \
{ \
GxB_FC32_t aij = Ax [pA] ; \
Cx [pC] = GB_FC32_ne (aij, y) ; \
}
GrB_Info GB_bind2nd_tran__ne_fc32
(
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
GxB_FC32_t y = (*((const GxB_FC32_t *) y_input)) ;
#include "GB_unop_transpose.c"
return (GrB_SUCCESS) ;
#endif
}
#endif
|
Parallelizer.h | // This file is part of Eigen, a lightweight C++ template library
// for linear algebra.
//
// Copyright (C) 2010 Gael Guennebaud <gael.guennebaud@inria.fr>
//
// This Source Code Form is subject to the terms of the Mozilla
// Public License v. 2.0. If a copy of the MPL was not distributed
// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
#ifndef EIGEN_PARALLELIZER_H
#define EIGEN_PARALLELIZER_H
namespace Eigen {
namespace internal {
/** \internal */
inline void manage_multi_threading(Action action, int* v)
{
static EIGEN_UNUSED int m_maxThreads = -1;
if(action==SetAction)
{
eigen_internal_assert(v!=0);
m_maxThreads = *v;
}
else if(action==GetAction)
{
eigen_internal_assert(v!=0);
#ifdef EIGEN_HAS_OPENMP
if(m_maxThreads>0)
*v = m_maxThreads;
else
*v = omp_get_max_threads();
#else
*v = 1;
#endif
}
else
{
eigen_internal_assert(false);
}
}
}
/** Must be call first when calling Eigen from multiple threads */
inline void initParallel()
{
int nbt;
internal::manage_multi_threading(GetAction, &nbt);
std::ptrdiff_t l1, l2, l3;
internal::manage_caching_sizes(GetAction, &l1, &l2, &l3);
}
/** \returns the max number of threads reserved for Eigen
* \sa setNbThreads */
inline int nbThreads()
{
int ret;
internal::manage_multi_threading(GetAction, &ret);
return ret;
}
/** Sets the max number of threads reserved for Eigen
* \sa nbThreads */
inline void setNbThreads(int v)
{
internal::manage_multi_threading(SetAction, &v);
}
namespace internal {
template<typename Index> struct GemmParallelInfo
{
GemmParallelInfo() : sync(-1), users(0), lhs_start(0), lhs_length(0) {}
int volatile sync;
int volatile users;
Index lhs_start;
Index lhs_length;
};
template<bool Condition, typename Functor, typename Index>
void parallelize_gemm(const Functor& func, Index rows, Index cols, bool transpose)
{
// TODO when EIGEN_USE_BLAS is defined,
// we should still enable OMP for other scalar types
#if !(defined (EIGEN_HAS_OPENMP)) || defined (EIGEN_USE_BLAS)
// FIXME the transpose variable is only needed to properly split
// the matrix product when multithreading is enabled. This is a temporary
// fix to support row-major destination matrices. This whole
// parallelizer mechanism has to be redisigned anyway.
EIGEN_UNUSED_VARIABLE(transpose);
func(0,rows, 0,cols);
#else
// Dynamically check whether we should enable or disable OpenMP.
// The conditions are:
// - the max number of threads we can create is greater than 1
// - we are not already in a parallel code
// - the sizes are large enough
// compute the maximal number of threads from the size of the product:
// FIXME this has to be fine tuned
Index size = transpose ? rows : cols;
Index pb_max_threads = std::max<Index>(1,size / 32);
// compute the number of threads we are going to use
Index threads = std::min<Index>(nbThreads(), pb_max_threads);
// if multi-threading is explicitely disabled, not useful, or if we already are in a parallel session,
// then abort multi-threading
// FIXME omp_get_num_threads()>1 only works for openmp, what if the user does not use openmp?
if((!Condition) || (threads==1) || (omp_get_num_threads()>1))
return func(0,rows, 0,cols);
Eigen::initParallel();
func.initParallelSession(threads);
if(transpose)
std::swap(rows,cols);
ei_declare_aligned_stack_constructed_variable(GemmParallelInfo<Index>,info,threads,0);
#pragma omp parallel num_threads(threads)
{
Index i = omp_get_thread_num();
// Note that the actual number of threads might be lower than the number of request ones.
Index actual_threads = omp_get_num_threads();
Index blockCols = (cols / actual_threads) & ~Index(0x3);
Index blockRows = (rows / actual_threads);
blockRows = (blockRows/Functor::Traits::mr)*Functor::Traits::mr;
Index r0 = i*blockRows;
Index actualBlockRows = (i+1==actual_threads) ? rows-r0 : blockRows;
Index c0 = i*blockCols;
Index actualBlockCols = (i+1==actual_threads) ? cols-c0 : blockCols;
info[i].lhs_start = r0;
info[i].lhs_length = actualBlockRows;
if(transpose) func(c0, actualBlockCols, 0, rows, info);
else func(0, rows, c0, actualBlockCols, info);
}
#endif
}
} // end namespace internal
} // end namespace Eigen
#endif // EIGEN_PARALLELIZER_H
|
pchetrf_aasen.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/pzhetrf_aasen.c, normal z -> c, Fri Sep 28 17:38:12 2018
*
**/
#include <math.h>
#include "plasma_async.h"
#include "plasma_context.h"
#include "plasma_descriptor.h"
#include "plasma_internal.h"
#include "plasma_types.h"
#include "plasma_workspace.h"
#include <plasma_core_blas.h>
#define A(m, n) ((plasma_complex32_t*)plasma_tile_addr(A, (m), (n)))
#define L(m, n) ((plasma_complex32_t*)plasma_tile_addr(A, (m), (n)-1))
#define U(m, n) ((plasma_complex32_t*)plasma_tile_addr(A, (m)-1, (n)))
#define T(m, n) ((plasma_complex32_t*)(W4((m)+((m)-(n))*A.mt)))
#define Tgb(m, n) ((plasma_complex32_t*)plasma_tile_addr(T, (m), (n)))
// W(m): nb*nb used to compute T(k,k)
#define W(m) ((plasma_complex32_t*)plasma_tile_addr(W, (m), 0))
// W2(m): mt*(nb*nb) to store H
#define W2(m) ((plasma_complex32_t*)plasma_tile_addr(W2, (m), 0))
// W3(m): mt*(nb*nb) used to form T(k,k)
#define W3(m) ((plasma_complex32_t*)plasma_tile_addr(W3, (m), 0))
// W4(m): mt*(nb*nb) used to store off-diagonal T
#define W4(m) ((plasma_complex32_t*)plasma_tile_addr(W4, (m), 0))
// W5(m): wmt used to update L(:,k)
#define W5(m) ((plasma_complex32_t*)plasma_tile_addr(W5, (m), 0))
#define H(m, n) (uplo == PlasmaLower ? W2((m)) : W2((n)))
#define IPIV(i) (ipiv + (i)*(A.mb))
/***************************************************************************//**
* Parallel tile LDLt factorization.
* @see plasma_omp_chetrf_aasen
******************************************************************************/
void plasma_pchetrf_aasen(plasma_enum_t uplo,
plasma_desc_t A, int *ipiv,
plasma_desc_t T,
plasma_desc_t W,
plasma_sequence_t *sequence,
plasma_request_t *request)
{
// Return if failed sequence.
if (sequence->status != PlasmaSuccess)
return;
// Read parameters from the context.
plasma_context_t *plasma = plasma_context_self();
int ib = plasma->ib;
int wmt = W.mt-(1+4*A.mt);
// Creaet views for the workspaces
plasma_desc_t W2
= plasma_desc_view(W, A.mb, 0, A.mt*A.mb, A.nb);
plasma_desc_t W3
= plasma_desc_view(W, (1+1*A.mt)*A.mb, 0, A.mt*A.mb, A.nb);
plasma_desc_t W4
= plasma_desc_view(W, (1+2*A.mt)*A.mb, 0, 2*A.mt*A.mb, A.nb);
plasma_desc_t W5
= plasma_desc_view(W, (1+4*A.mt)*A.mb, 0, wmt*A.mb, A.nb);
//==============
// PlasmaLower
//==============
// NOTE: In old PLASMA, we used priority.
if (uplo == PlasmaLower) {
for (int k = 0; k < A.mt; k++) {
int nvak = plasma_tile_nview(A, k);
int mvak = plasma_tile_mview(A, k);
int ldak = plasma_tile_mmain(A, k);
int ldtk = plasma_tile_mmain(W4, k);
// -- computing offdiagonals H(1:k-1, k) -- //
for (int m=1; m < k; m++) {
int mvam = plasma_tile_mview(A, m);
int ldtm = plasma_tile_mmain(W4, m);
plasma_core_omp_cgemm(
PlasmaNoTrans, PlasmaConjTrans,
mvam, mvak, mvam,
1.0, T(m, m), ldtm,
L(k, m), ldak,
0.0, H(m, k), A.mb,
sequence, request);
if (m > 1) {
plasma_core_omp_cgemm(
PlasmaNoTrans, PlasmaConjTrans,
mvam, mvak, A.mb,
1.0, T(m, m-1), ldtm,
L(k, m-1), ldak,
1.0, H(m, k), A.mb,
sequence, request);
}
int mvamp1 = plasma_tile_mview(A, m+1);
int ldtmp1 = plasma_tile_mmain(W4, m+1);
plasma_core_omp_cgemm(
PlasmaConjTrans, PlasmaConjTrans,
mvam, mvak, mvamp1,
1.0, T(m+1, m), ldtmp1,
L(k, m+1), ldak,
1.0, H(m, k), A.mb,
sequence, request);
}
// ---- end of computing H(1:(k-1),k) -- //
// -- computing diagonal T(k, k) -- //
plasma_complex32_t beta;
if (k > 1) {
int num = k-1;
for (int m = 1; m < k; m++) {
int mvam = plasma_tile_mview(A, m);
int id = (m-1) % num;
if (m < num+1)
beta = 0.0;
else
beta = 1.0;
plasma_core_omp_cgemm(
PlasmaNoTrans, PlasmaNoTrans,
mvak, mvak, mvam,
-1.0, L(k, m), ldak,
H(m, k), A.mb,
beta, W3(id), A.mb,
sequence, request);
}
// all-reduce W3 using a binary tree //
// NOTE: Old PLASMA had an option to reduce in a set of tiles //
// num_players: number of players
int num_players = num;
// num_rounds : height of tournament
int num_rounds = ceil( log10((float)num_players)/log10(2.0) );
// base: intervals between brackets
int base = 2;
for (int round = 1; round <= num_rounds; round++) {
int num_brackets = num_players / 2; // number of brackets
for (int bracket = 0; bracket < num_brackets; bracket++) {
// first contender
int m1 = base*bracket;
// second contender
int m2 = m1+base/2;
plasma_core_omp_cgeadd(
PlasmaNoTrans, mvak, mvak,
1.0, W3(m2), A.mb,
1.0, W3(m1), A.mb,
sequence, request);
}
num_players = ceil( ((float)num_players)/2.0 );
base = 2*base;
}
plasma_core_omp_clacpy(
PlasmaLower, PlasmaNoTrans,
mvak, mvak,
A(k, k), ldak,
T(k, k), ldtk,
sequence, request);
plasma_core_omp_cgeadd(
PlasmaNoTrans, mvak, mvak,
1.0, W3(0), A.mb,
1.0, T(k, k), ldtk,
sequence, request);
}
else { // k == 0 or 1
plasma_core_omp_clacpy(
PlasmaLower, PlasmaNoTrans,
mvak, mvak,
A(k, k), ldak,
T(k, k), ldtk,
sequence, request);
// expanding to full matrix
plasma_core_omp_clacpy(
PlasmaLower, PlasmaConjTrans,
mvak, mvak,
T(k, k), ldtk,
T(k, k), ldtk,
sequence, request);
}
if (k > 0) {
if (k > 1) {
plasma_core_omp_cgemm(
PlasmaNoTrans, PlasmaNoTrans,
mvak, A.mb, mvak,
1.0, L(k, k), ldak,
T(k, k-1), ldtk,
0.0, W(0), A.mb,
sequence, request);
plasma_core_omp_cgemm(
PlasmaNoTrans, PlasmaConjTrans,
mvak, mvak, A.mb,
-1.0, W(0), A.mb,
L(k, k-1), ldak,
1.0, T(k, k), ldtk,
sequence, request);
}
// - symmetrically solve with L(k,k) //
plasma_core_omp_chegst(
1, PlasmaLower, mvak,
T(k, k), ldtk,
L(k, k), ldak,
sequence, request);
// expand to full matrix
plasma_core_omp_clacpy(
PlasmaLower, PlasmaConjTrans,
mvak, mvak,
T(k, k), ldtk,
T(k, k), ldtk,
sequence, request);
}
// computing H(k, k) //
beta = 0.0;
if (k > 1) {
plasma_core_omp_cgemm(
PlasmaNoTrans, PlasmaConjTrans,
mvak, mvak, A.nb,
1.0, T(k, k-1), ldtk,
L(k, k-1), ldak,
0.0, H(k, k), A.mb,
sequence, request);
beta = 1.0;
}
// computing the (k+1)-th column of L //
if (k+1 < A.nt) {
int ldakp1 = plasma_tile_mmain(A, k+1);
if (k > 0) {
// finish computing H(k, k) //
plasma_core_omp_cgemm(
PlasmaNoTrans, PlasmaConjTrans,
mvak, mvak, mvak,
1.0, T(k, k), ldtk,
L(k, k), ldak,
beta, H(k, k), A.mb,
sequence, request);
// computing the (k+1)-th column of L //
// - update with the previous column
if (A.mt-k < plasma->max_threads && k > 0) {
int num = imin(k, wmt/(A.mt-k-1)); // workspace per row
for (int n = 1; n <= k; n++) {
// update A(k+1:mt-1, k) using L(:,n) //
plasma_complex32_t *a1, *a2, *b, *c;
int ma1 = (A.mt-k)*A.mb;
int ma2 = plasma_tile_mmain(A, A.mt-1);
int mc = (A.mt-(k+1))*A.mb;
int na = plasma_tile_nmain(A, k);
a1 = L(k, n); // we need only L(k+1:mt-1, n)
a2 = L(k, A.mt-1); // left-over tile
b = H(n, k);
c = W5(((n-1)%num)*(A.mt-k-1));
int mvan = plasma_tile_mview(A, n);
#pragma omp task depend(in:a1[0:ma1*na]) \
depend(in:a2[0:ma2*na]) \
depend(in:b[0:A.mb*mvak]) \
depend(inout:c[0:mc*A.mb])
{
for (int m = k+1; m < A.mt; m++) {
int mvam = plasma_tile_mview(A, m);
int ldam = plasma_tile_mmain(A, m);
int id = (m-k-1)+((n-1)%num)*(A.mt-k-1);
if (n < num+1)
beta = 0.0;
else
beta = 1.0;
#pragma omp task
{
plasma_core_cgemm(
PlasmaNoTrans, PlasmaNoTrans,
mvam, mvak, mvan,
-1.0, L(m, n), ldam,
H(n, k), A.mb,
beta, W5(id), A.mb);
}
}
#pragma omp taskwait
}
}
// accumerate within workspace using a binary tree
// num_players: number of players
int num_players = num;
// num_rounds: height of tournament
int num_rounds = ceil( log10((float)num_players)/log10(2.0) );
// base: intervals between brackets
int base = 2;
for (int round = 1; round <= num_rounds; round++) {
int num_brackets = num_players / 2; // number of brackets
for (int bracket = 0; bracket < num_brackets; bracket++) {
// first contender
int m1 = base*bracket;
// second contender
int m2 = m1+base/2;
plasma_complex32_t *c1, *c2;
int mc = (A.mt-(k+1))*A.mb;
c1 = W5(m1*(A.mt-k-1));
c2 = W5(m2*(A.mt-k-1));
#pragma omp task depend(in:c2[0:mc*A.mb]) \
depend(inout:c1[0:mc*A.mb])
{
for (int m = k+1; m < A.mt; m++) {
int mvam = plasma_tile_mview(A, m);
#pragma omp task
{
plasma_core_cgeadd(
PlasmaNoTrans, mvam, mvak,
1.0, W5((m-k-1)+m2*(A.mt-k-1)), A.mb,
1.0, W5((m-k-1)+m1*(A.mt-k-1)), A.mb);
}
}
#pragma omp taskwait
}
}
num_players = ceil( ((float)num_players)/2.0 );
base = 2*base;
}
// accumelate into A(k+1:mt-1, k)
{
plasma_complex32_t *c1;
plasma_complex32_t *c2_in;
plasma_complex32_t *c3_in;
plasma_complex32_t *c2_out;
int mc = (A.mt-(k+1))*A.mb;
int mc2_in = (A.mt-k)*A.mb;
int mc3_in = plasma_tile_mmain(A, A.mt-1);
int mc2_out = (A.mt-(k+1))*A.mb;
int nc2 = plasma_tile_nmain(A, k);
c1 = W5(0);
c2_in = A(k, k); // we write only A(k+1,k), but dependency from sym-swap
c3_in = A(A.mt-1, k); // left-over tile
c2_out = A(k+1, k);
#pragma omp task depend(in:c1[0:mc*A.mb]) \
depend(in:c2_in[0:mc2_in*nc2]) \
depend(in:c3_in[0:mc3_in*nc2]) \
depend(out:c2_out[0:mc2_out*nc2])
{
for (int m = k+1; m < A.mt; m++) {
int mvam = plasma_tile_mview(A, m);
int ldam = plasma_tile_mmain(A, m);
#pragma omp task
{
plasma_core_cgeadd(
PlasmaNoTrans, mvam, mvak,
1.0, W5(m-k-1), A.mb,
1.0, A(m, k), ldam);
}
}
#pragma omp taskwait
}
}
}
else {
for (int n = 1; n <= k; n++) {
// update L(:,k+1) using L(:,n) //
plasma_complex32_t *a1, *a2;
plasma_complex32_t *b;
plasma_complex32_t *c1_in, *c2_in;
plasma_complex32_t *c_out;
int ma1 = (A.mt-k)*A.mb;
int ma2 = plasma_tile_mmain(A, A.mt-1);
int mc1_in = (A.mt-k)*A.mb;
int mc2_in = plasma_tile_mmain(A, A.mt-1);
int mc_out = (A.mt-(k+1))*A.mb;
int na = plasma_tile_nmain(A, k);
int nc = plasma_tile_nmain(A, k);
a1 = L(k, n); // we read only L(k+1:mt-1, n), dependency from row-swap
a2 = L(A.mt-1, n); // left-over tile
b = H(n, k);
c1_in = A(k, k); // we write only A(k+1,k), but dependency from sym-swap
c2_in = A(A.mt-1, k); // left-over tile
c_out = A(k+1, k);
int mvan = plasma_tile_mview(A, n);
#pragma omp task depend(in:a1[0:ma1*na]) \
depend(in:a2[0:ma2*na]) \
depend(in:b[0:A.mb*mvak]) \
depend(in:c1_in[0:mc1_in*nc]) \
depend(in:c2_in[0:mc2_in*nc]) \
depend(out:c_out[0:mc_out*nc])
{
for (int m = k+1; m < A.mt; m++) {
int mvam = plasma_tile_mview(A, m);
int ldam = plasma_tile_mmain(A, m);
#pragma omp task
{
plasma_core_cgemm(
PlasmaNoTrans, PlasmaNoTrans,
mvam, mvak, mvan,
-1.0, L(m, n), ldam,
H(n, k), A.mb,
1.0, A(m, k), ldam);
}
}
#pragma omp taskwait
}
}
}
} // end of if (k > 0)
// ============================= //
// == PLASMA LU panel == //
// ============================= //
// -- compute LU of the panel -- //
plasma_complex32_t *a1, *a2;
a1 = L(k+1, k+1);
a2 = L(A.mt-1, k+1);
int mlkk = A.m - (k+1)*A.mb; // dimension
int ma1 = (A.mt-(k+1)-1)*A.mb;
int ma2 = plasma_tile_mmain(A, A.mt-1);
int na = plasma_tile_nmain(A, k);
int k1 = 1+(k+1)*A.nb;
int k2 = imin(mlkk, mvak)+(k+1)*A.nb;
int num_panel_threads = imin(plasma->max_panel_threads,
A.mt-(k+1));
#pragma omp task depend(inout:a1[0:ma1*na]) \
depend(inout:a2[0:ma2*na]) \
depend(out:ipiv[k1-1:k2])
{
volatile int *max_idx =
(int*)malloc(num_panel_threads*sizeof(int));
if (max_idx == NULL)
plasma_request_fail(sequence, request,
PlasmaErrorOutOfMemory);
volatile plasma_complex32_t *max_val =
(plasma_complex32_t*)malloc(num_panel_threads*sizeof(
plasma_complex32_t));
if (max_val == NULL)
plasma_request_fail(sequence, request,
PlasmaErrorOutOfMemory);
volatile int info = 0;
plasma_barrier_t barrier;
plasma_barrier_init(&barrier);
if (sequence->status == PlasmaSuccess) {
for (int rank = 0; rank < num_panel_threads; rank++) {
#pragma omp task shared(barrier)
{
plasma_desc_t view =
plasma_desc_view(A,
(k+1)*A.mb, k*A.nb,
mlkk, mvak);
plasma_core_cgetrf(view, IPIV(k+1), ib,
rank, num_panel_threads,
max_idx, max_val, &info,
&barrier);
if (info != 0)
plasma_request_fail(sequence, request,
(k+1)*A.mb+info);
}
}
}
#pragma omp taskwait
free((void*)max_idx);
free((void*)max_val);
{
for (int i = 0; i < imin(mlkk, mvak); i++) {
IPIV(k+1)[i] += (k+1)*A.mb;
}
}
}
// ============================== //
// == end of PLASMA LU panel == //
// ============================== //
// -- apply pivoting to previous columns of L -- //
for (int n = 1; n < k+1; n++) {
ma1 = (A.mt-k-1)*A.mb;
ma2 = plasma_tile_mmain(A, A.mt-1);
na = plasma_tile_nmain(A, n-1);
a1 = L(k+1, n);
a2 = L(A.mt-1, n);
#pragma omp task depend(in:ipiv[(k1-1):k2]) \
depend(inout:a1[0:ma1*na]) \
depend(inout:a2[0:ma2*na])
{
if (sequence->status == PlasmaSuccess) {
plasma_desc_t view =
plasma_desc_view(A, 0, (n-1)*A.nb, A.m, na);
plasma_core_cgeswp(PlasmaRowwise, view, k1, k2, ipiv, 1);
}
}
}
// computing T(k+1, k) //
int mvakp1 = plasma_tile_mview(A, k+1);
int ldak_n = plasma_tile_nmain(A, k);
int ldtkp1 = plasma_tile_mmain(W4, k+1);
// copy upper-triangular part of L(k+1,k+1) to T(k+1,k)
// and then zero it out
plasma_core_omp_clacpy(
PlasmaUpper, PlasmaNoTrans,
mvakp1, mvak,
L(k+1, k+1), ldakp1,
T(k+1, k ), ldtkp1,
sequence, request);
plasma_core_omp_claset(
PlasmaUpper,
ldakp1, ldak_n, 0, 0,
mvakp1, mvak,
0.0, 1.0,
L(k+1, k+1));
if (k > 0) {
plasma_core_omp_ctrsm(
PlasmaRight, PlasmaLower,
PlasmaConjTrans, PlasmaUnit,
mvakp1, mvak,
1.0, L(k, k), ldak,
T(k+1, k), ldtkp1,
sequence, request);
}
// -- symmetrically apply pivoting to trailing A -- //
{
int mnt1, mnt2;
mnt2 = A.mt-1-(k+1);
ma2 = plasma_tile_mmain(A, A.mt-1);
mnt1 = (mnt2*(mnt2+1))/2; // # of remaining tiles in a1
mnt1 *= A.mb*A.mb;
mnt2 *= A.mb*ma2; // a2
mnt2 += ma2*ma2; // last diagonal
a1 = A(k+1, k+1);
a2 = A(A.mt-1, k+1);
int num_swap_threads = imin(plasma->max_panel_threads,
A.mt-(k+1));
#pragma omp task depend(in:ipiv[(k1-1):k2]) \
depend(inout:a1[0:mnt1]) \
depend(inout:a2[0:mnt2])
{
plasma_barrier_t barrier;
plasma_barrier_init(&barrier);
for (int rank = 0; rank < num_swap_threads; rank++) {
#pragma omp task shared(barrier)
{
plasma_core_cheswp(rank, num_swap_threads, PlasmaLower, A, k1, k2, ipiv, 1, &barrier);
}
}
#pragma omp taskwait
}
}
}
// copy T(k+1, k) to T(k, k+1) for cgbtrf,
// forcing T(k, k) and T(k+1, k) tiles are ready
plasma_complex32_t *Tin10 = NULL;
plasma_complex32_t *Tin11 = NULL;
plasma_complex32_t *Tin21 = NULL;
plasma_complex32_t *Tout01 = NULL;
plasma_complex32_t *Tout11 = NULL;
plasma_complex32_t *Tout21 = NULL;
plasma_complex32_t *Tout = NULL;
int km1 = imax(0, k-1);
int kp1 = imin(k+1, A.mt-1);
int ldtkm1 = plasma_tile_mmain(W4, km1);
int ldtkp1 = plasma_tile_mmain(W4, kp1);
int nvakp1 = plasma_tile_nview(A, kp1);
Tin10 = T(k, km1);
Tin11 = T(k, k);
Tin21 = T(kp1, k);
Tout01 = Tgb(km1, k);
Tout11 = Tgb(k, k);
Tout21 = Tgb(kp1, k);
Tout = Tgb(imax(0, k-T.kut+1), k);
#pragma omp task depend(in:Tin10[0:A.mb*ldtk]) \
depend(in:Tin11[0:nvak*ldtk]) \
depend(in:Tin21[0:nvakp1*ldtkp1]) \
depend(out:Tout01[0:nvak*ldtkm1]) \
depend(out:Tout11[0:nvak*ldtk]) \
depend(out:Tout21[0:nvak*ldtkp1]) \
depend(out:Tout[0:nvak*ldtkp1])
{
plasma_core_clacpy(
PlasmaGeneral, PlasmaNoTrans,
mvak, mvak,
T(k, k), ldtk,
Tgb(k, k), ldtk);
if (k+1 < T.nt) {
int mvakp1 = plasma_tile_mview(A, k+1);
plasma_core_clacpy(
PlasmaGeneral, PlasmaNoTrans,
mvakp1, mvak,
T(kp1, k), ldtkp1,
Tgb(kp1, k), ldtkp1);
}
if (k > 0) {
int nvakm1 = plasma_tile_nview(A, k-1);
plasma_core_clacpy(
PlasmaGeneral, PlasmaConjTrans,
mvak, nvakm1,
T(k, km1), ldtk,
Tgb(km1, k), ldtkm1);
}
}
}
}
//==============
// PlasmaUpper
//==============
else {
// TODO: Upper
}
}
|
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] = 4;
tile_size[1] = 4;
tile_size[2] = 24;
tile_size[3] = 512;
tile_size[4] = -1;
// for timekeeping
int ts_return = -1;
struct timeval start, end, result;
double tdiff = 0.0, min_tdiff=1.e100;
const int BASE = 1024;
// 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,2);t1++) {
lbp=max(ceild(t1,2),ceild(4*t1-Nt+3,4));
ubp=min(floord(Nt+Nz-4,4),floord(2*t1+Nz-1,4));
#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-11,12)),ceild(4*t2-Nz-20,24));t3<=min(min(min(floord(4*t2+Ny,24),floord(Nt+Ny-4,24)),floord(2*t1+Ny+1,24)),floord(4*t1-4*t2+Nz+Ny-1,24));t3++) {
for (t4=max(max(max(0,ceild(t1-255,256)),ceild(4*t2-Nz-508,512)),ceild(24*t3-Ny-508,512));t4<=min(min(min(min(floord(4*t2+Nx,512),floord(Nt+Nx-4,512)),floord(2*t1+Nx+1,512)),floord(24*t3+Nx+20,512)),floord(4*t1-4*t2+Nz+Nx-1,512));t4++) {
for (t5=max(max(max(max(max(0,2*t1),4*t1-4*t2+1),4*t2-Nz+2),24*t3-Ny+2),512*t4-Nx+2);t5<=min(min(min(min(min(Nt-2,2*t1+3),4*t2+2),24*t3+22),512*t4+510),4*t1-4*t2+Nz+1);t5++) {
for (t6=max(max(4*t2,t5+1),-4*t1+4*t2+2*t5-3);t6<=min(min(4*t2+3,-4*t1+4*t2+2*t5),t5+Nz-2);t6++) {
for (t7=max(24*t3,t5+1);t7<=min(24*t3+23,t5+Ny-2);t7++) {
lbv=max(512*t4,t5+1);
ubv=min(512*t4+511,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;
}
|
GeneralMatrixMatrix.h | // This file is part of Eigen, a lightweight C++ template library
// for linear algebra.
//
// Copyright (C) 2008-2009 Gael Guennebaud <gael.guennebaud@inria.fr>
//
// This Source Code Form is subject to the terms of the Mozilla
// Public License v. 2.0. If a copy of the MPL was not distributed
// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
#ifndef EIGEN_GENERAL_MATRIX_MATRIX_H
#define EIGEN_GENERAL_MATRIX_MATRIX_H
namespace Eigen {
namespace internal {
template<typename _LhsScalar, typename _RhsScalar> class level3_blocking;
/* Specialization for a row-major destination matrix => simple transposition of the product */
template<
typename Index,
typename LhsScalar, int LhsStorageOrder, bool ConjugateLhs,
typename RhsScalar, int RhsStorageOrder, bool ConjugateRhs>
struct general_matrix_matrix_product<Index,LhsScalar,LhsStorageOrder,ConjugateLhs,RhsScalar,RhsStorageOrder,ConjugateRhs,RowMajor>
{
typedef gebp_traits<RhsScalar,LhsScalar> Traits;
typedef typename ScalarBinaryOpTraits<LhsScalar, RhsScalar>::ReturnType ResScalar;
static EIGEN_STRONG_INLINE void run(
Index rows, Index cols, Index depth,
const LhsScalar* lhs, Index lhsStride,
const RhsScalar* rhs, Index rhsStride,
ResScalar* res, Index resStride,
ResScalar alpha,
level3_blocking<RhsScalar,LhsScalar>& blocking,
GemmParallelInfo<Index>* info = 0)
{
// transpose the product such that the result is column major
general_matrix_matrix_product<Index,
RhsScalar, RhsStorageOrder==RowMajor ? ColMajor : RowMajor, ConjugateRhs,
LhsScalar, LhsStorageOrder==RowMajor ? ColMajor : RowMajor, ConjugateLhs,
ColMajor>
::run(cols,rows,depth,rhs,rhsStride,lhs,lhsStride,res,resStride,alpha,blocking,info);
}
};
/* Specialization for a col-major destination matrix
* => Blocking algorithm following Goto's paper */
template<
typename Index,
typename LhsScalar, int LhsStorageOrder, bool ConjugateLhs,
typename RhsScalar, int RhsStorageOrder, bool ConjugateRhs>
struct general_matrix_matrix_product<Index,LhsScalar,LhsStorageOrder,ConjugateLhs,RhsScalar,RhsStorageOrder,ConjugateRhs,ColMajor>
{
typedef gebp_traits<LhsScalar,RhsScalar> Traits;
typedef typename ScalarBinaryOpTraits<LhsScalar, RhsScalar>::ReturnType ResScalar;
static void run(Index rows, Index cols, Index depth,
const LhsScalar* _lhs, Index lhsStride,
const RhsScalar* _rhs, Index rhsStride,
ResScalar* _res, Index resStride,
ResScalar alpha,
level3_blocking<LhsScalar,RhsScalar>& blocking,
GemmParallelInfo<Index>* info = 0)
{
typedef const_blas_data_mapper<LhsScalar, Index, LhsStorageOrder> LhsMapper;
typedef const_blas_data_mapper<RhsScalar, Index, RhsStorageOrder> RhsMapper;
typedef blas_data_mapper<typename Traits::ResScalar, Index, ColMajor> ResMapper;
LhsMapper lhs(_lhs,lhsStride);
RhsMapper rhs(_rhs,rhsStride);
ResMapper res(_res, resStride);
Index kc = blocking.kc(); // cache block size along the K direction
Index mc = (std::min)(rows,blocking.mc()); // cache block size along the M direction
Index nc = (std::min)(cols,blocking.nc()); // cache block size along the N direction
gemm_pack_lhs<LhsScalar, Index, LhsMapper, Traits::mr, Traits::LhsProgress, LhsStorageOrder> pack_lhs;
gemm_pack_rhs<RhsScalar, Index, RhsMapper, Traits::nr, RhsStorageOrder> pack_rhs;
gebp_kernel<LhsScalar, RhsScalar, Index, ResMapper, Traits::mr, Traits::nr, ConjugateLhs, ConjugateRhs> gebp;
#ifdef EIGEN_HAS_OPENMP
if(info)
{
// this is the parallel version!
int tid = omp_get_thread_num();
int threads = omp_get_num_threads();
LhsScalar* blockA = blocking.blockA();
eigen_internal_assert(blockA!=0);
std::size_t sizeB = kc*nc;
ei_declare_aligned_stack_constructed_variable(RhsScalar, blockB, sizeB, 0);
// For each horizontal panel of the rhs, and corresponding vertical panel of the lhs...
for(Index k=0; k<depth; k+=kc)
{
const Index actual_kc = (std::min)(k+kc,depth)-k; // => rows of B', and cols of the A'
// In order to reduce the chance that a thread has to wait for the other,
// let's start by packing B'.
pack_rhs(blockB, rhs.getSubMapper(k,0), actual_kc, nc);
// Pack A_k to A' in a parallel fashion:
// each thread packs the sub block A_k,i to A'_i where i is the thread id.
// However, before copying to A'_i, we have to make sure that no other thread is still using it,
// i.e., we test that info[tid].users equals 0.
// Then, we set info[tid].users to the number of threads to mark that all other threads are going to use it.
while(info[tid].users!=0) {}
info[tid].users += threads;
pack_lhs(blockA+info[tid].lhs_start*actual_kc, lhs.getSubMapper(info[tid].lhs_start,k), actual_kc, info[tid].lhs_length);
// Notify the other threads that the part A'_i is ready to go.
info[tid].sync = k;
// Computes C_i += A' * B' per A'_i
for(int shift=0; shift<threads; ++shift)
{
int i = (tid+shift)%threads;
// At this point we have to make sure that A'_i has been updated by the thread i,
// we use testAndSetOrdered to mimic a volatile access.
// However, no need to wait for the B' part which has been updated by the current thread!
if (shift>0) {
while(info[i].sync!=k) {
}
}
gebp(res.getSubMapper(info[i].lhs_start, 0), blockA+info[i].lhs_start*actual_kc, blockB, info[i].lhs_length, actual_kc, nc, alpha);
}
// Then keep going as usual with the remaining B'
for(Index j=nc; j<cols; j+=nc)
{
const Index actual_nc = (std::min)(j+nc,cols)-j;
// pack B_k,j to B'
pack_rhs(blockB, rhs.getSubMapper(k,j), actual_kc, actual_nc);
// C_j += A' * B'
gebp(res.getSubMapper(0, j), blockA, blockB, rows, actual_kc, actual_nc, alpha);
}
// Release all the sub blocks A'_i of A' for the current thread,
// i.e., we simply decrement the number of users by 1
for(Index i=0; i<threads; ++i)
#pragma omp atomic
info[i].users -= 1;
}
}
else
#endif // EIGEN_HAS_OPENMP
{
EIGEN_UNUSED_VARIABLE(info);
// this is the sequential version!
std::size_t sizeA = kc*mc;
std::size_t sizeB = kc*nc;
ei_declare_aligned_stack_constructed_variable(LhsScalar, blockA, sizeA, blocking.blockA());
ei_declare_aligned_stack_constructed_variable(RhsScalar, blockB, sizeB, blocking.blockB());
const bool pack_rhs_once = mc!=rows && kc==depth && nc==cols;
// For each horizontal panel of the rhs, and corresponding panel of the lhs...
for(Index i2=0; i2<rows; i2+=mc)
{
const Index actual_mc = (std::min)(i2+mc,rows)-i2;
for(Index k2=0; k2<depth; k2+=kc)
{
const Index actual_kc = (std::min)(k2+kc,depth)-k2;
// OK, here we have selected one horizontal panel of rhs and one vertical panel of lhs.
// => Pack lhs's panel into a sequential chunk of memory (L2/L3 caching)
// Note that this panel will be read as many times as the number of blocks in the rhs's
// horizontal panel which is, in practice, a very low number.
pack_lhs(blockA, lhs.getSubMapper(i2,k2), actual_kc, actual_mc);
// For each kc x nc block of the rhs's horizontal panel...
for(Index j2=0; j2<cols; j2+=nc)
{
const Index actual_nc = (std::min)(j2+nc,cols)-j2;
// We pack the rhs's block into a sequential chunk of memory (L2 caching)
// Note that this block will be read a very high number of times, which is equal to the number of
// micro horizontal panel of the large rhs's panel (e.g., rows/12 times).
if((!pack_rhs_once) || i2==0)
pack_rhs(blockB, rhs.getSubMapper(k2,j2), actual_kc, actual_nc);
// Everything is packed, we can now call the panel * block kernel:
gebp(res.getSubMapper(i2, j2), blockA, blockB, actual_mc, actual_kc, actual_nc, alpha);
}
}
}
}
}
};
/*********************************************************************************
* Specialization of generic_product_impl for "large" GEMM, i.e.,
* implementation of the high level wrapper to general_matrix_matrix_product
**********************************************************************************/
template<typename Scalar, typename Index, typename Gemm, typename Lhs, typename Rhs, typename Dest, typename BlockingType>
struct gemm_functor
{
gemm_functor(const Lhs& lhs, const Rhs& rhs, Dest& dest, const Scalar& actualAlpha, BlockingType& blocking)
: m_lhs(lhs), m_rhs(rhs), m_dest(dest), m_actualAlpha(actualAlpha), m_blocking(blocking)
{}
void initParallelSession(Index num_threads) const
{
m_blocking.initParallel(m_lhs.rows(), m_rhs.cols(), m_lhs.cols(), num_threads);
m_blocking.allocateA();
}
void operator() (Index row, Index rows, Index col=0, Index cols=-1, GemmParallelInfo<Index>* info=0) const
{
if(cols==-1)
cols = m_rhs.cols();
Gemm::run(rows, cols, m_lhs.cols(),
&m_lhs.coeffRef(row,0), m_lhs.outerStride(),
&m_rhs.coeffRef(0,col), m_rhs.outerStride(),
(Scalar*)&(m_dest.coeffRef(row,col)), m_dest.outerStride(),
m_actualAlpha, m_blocking, info);
}
typedef typename Gemm::Traits Traits;
protected:
const Lhs& m_lhs;
const Rhs& m_rhs;
Dest& m_dest;
Scalar m_actualAlpha;
BlockingType& m_blocking;
};
template<int StorageOrder, typename LhsScalar, typename RhsScalar, int MaxRows, int MaxCols, int MaxDepth, int KcFactor=1,
bool FiniteAtCompileTime = MaxRows!=Dynamic && MaxCols!=Dynamic && MaxDepth != Dynamic> class gemm_blocking_space;
template<typename _LhsScalar, typename _RhsScalar>
class level3_blocking
{
typedef _LhsScalar LhsScalar;
typedef _RhsScalar RhsScalar;
protected:
LhsScalar* m_blockA;
RhsScalar* m_blockB;
Index m_mc;
Index m_nc;
Index m_kc;
public:
level3_blocking()
: m_blockA(0), m_blockB(0), m_mc(0), m_nc(0), m_kc(0)
{}
inline Index mc() const { return m_mc; }
inline Index nc() const { return m_nc; }
inline Index kc() const { return m_kc; }
inline LhsScalar* blockA() { return m_blockA; }
inline RhsScalar* blockB() { return m_blockB; }
};
template<int StorageOrder, typename _LhsScalar, typename _RhsScalar, int MaxRows, int MaxCols, int MaxDepth, int KcFactor>
class gemm_blocking_space<StorageOrder,_LhsScalar,_RhsScalar,MaxRows, MaxCols, MaxDepth, KcFactor, true /* == FiniteAtCompileTime */>
: public level3_blocking<
typename conditional<StorageOrder==RowMajor,_RhsScalar,_LhsScalar>::type,
typename conditional<StorageOrder==RowMajor,_LhsScalar,_RhsScalar>::type>
{
enum {
Transpose = StorageOrder==RowMajor,
ActualRows = Transpose ? MaxCols : MaxRows,
ActualCols = Transpose ? MaxRows : MaxCols
};
typedef typename conditional<Transpose,_RhsScalar,_LhsScalar>::type LhsScalar;
typedef typename conditional<Transpose,_LhsScalar,_RhsScalar>::type RhsScalar;
typedef gebp_traits<LhsScalar,RhsScalar> Traits;
enum {
SizeA = ActualRows * MaxDepth,
SizeB = ActualCols * MaxDepth
};
#if EIGEN_MAX_STATIC_ALIGN_BYTES >= EIGEN_DEFAULT_ALIGN_BYTES
EIGEN_ALIGN_MAX LhsScalar m_staticA[SizeA];
EIGEN_ALIGN_MAX RhsScalar m_staticB[SizeB];
#else
EIGEN_ALIGN_MAX char m_staticA[SizeA * sizeof(LhsScalar) + EIGEN_DEFAULT_ALIGN_BYTES-1];
EIGEN_ALIGN_MAX char m_staticB[SizeB * sizeof(RhsScalar) + EIGEN_DEFAULT_ALIGN_BYTES-1];
#endif
public:
gemm_blocking_space(Index /*rows*/, Index /*cols*/, Index /*depth*/, Index /*num_threads*/, bool /*full_rows = false*/)
{
this->m_mc = ActualRows;
this->m_nc = ActualCols;
this->m_kc = MaxDepth;
#if EIGEN_MAX_STATIC_ALIGN_BYTES >= EIGEN_DEFAULT_ALIGN_BYTES
this->m_blockA = m_staticA;
this->m_blockB = m_staticB;
#else
this->m_blockA = reinterpret_cast<LhsScalar*>((internal::UIntPtr(m_staticA) + (EIGEN_DEFAULT_ALIGN_BYTES-1)) & ~std::size_t(EIGEN_DEFAULT_ALIGN_BYTES-1));
this->m_blockB = reinterpret_cast<RhsScalar*>((internal::UIntPtr(m_staticB) + (EIGEN_DEFAULT_ALIGN_BYTES-1)) & ~std::size_t(EIGEN_DEFAULT_ALIGN_BYTES-1));
#endif
}
void initParallel(Index, Index, Index, Index)
{}
inline void allocateA() {}
inline void allocateB() {}
inline void allocateAll() {}
};
template<int StorageOrder, typename _LhsScalar, typename _RhsScalar, int MaxRows, int MaxCols, int MaxDepth, int KcFactor>
class gemm_blocking_space<StorageOrder,_LhsScalar,_RhsScalar,MaxRows, MaxCols, MaxDepth, KcFactor, false>
: public level3_blocking<
typename conditional<StorageOrder==RowMajor,_RhsScalar,_LhsScalar>::type,
typename conditional<StorageOrder==RowMajor,_LhsScalar,_RhsScalar>::type>
{
enum {
Transpose = StorageOrder==RowMajor
};
typedef typename conditional<Transpose,_RhsScalar,_LhsScalar>::type LhsScalar;
typedef typename conditional<Transpose,_LhsScalar,_RhsScalar>::type RhsScalar;
typedef gebp_traits<LhsScalar,RhsScalar> Traits;
Index m_sizeA;
Index m_sizeB;
public:
gemm_blocking_space(Index rows, Index cols, Index depth, Index num_threads, bool l3_blocking)
{
this->m_mc = Transpose ? cols : rows;
this->m_nc = Transpose ? rows : cols;
this->m_kc = depth;
if(l3_blocking)
{
computeProductBlockingSizes<LhsScalar,RhsScalar,KcFactor>(this->m_kc, this->m_mc, this->m_nc, num_threads);
}
else // no l3 blocking
{
Index n = this->m_nc;
computeProductBlockingSizes<LhsScalar,RhsScalar,KcFactor>(this->m_kc, this->m_mc, n, num_threads);
}
m_sizeA = this->m_mc * this->m_kc;
m_sizeB = this->m_kc * this->m_nc;
}
void initParallel(Index rows, Index cols, Index depth, Index num_threads)
{
this->m_mc = Transpose ? cols : rows;
this->m_nc = Transpose ? rows : cols;
this->m_kc = depth;
eigen_internal_assert(this->m_blockA==0 && this->m_blockB==0);
Index m = this->m_mc;
computeProductBlockingSizes<LhsScalar,RhsScalar,KcFactor>(this->m_kc, m, this->m_nc, num_threads);
m_sizeA = this->m_mc * this->m_kc;
m_sizeB = this->m_kc * this->m_nc;
}
void allocateA()
{
if(this->m_blockA==0)
this->m_blockA = aligned_new<LhsScalar>(m_sizeA);
}
void allocateB()
{
if(this->m_blockB==0)
this->m_blockB = aligned_new<RhsScalar>(m_sizeB);
}
void allocateAll()
{
allocateA();
allocateB();
}
~gemm_blocking_space()
{
aligned_delete(this->m_blockA, m_sizeA);
aligned_delete(this->m_blockB, m_sizeB);
}
};
} // end namespace internal
namespace internal {
template<typename Lhs, typename Rhs>
struct generic_product_impl<Lhs,Rhs,DenseShape,DenseShape,GemmProduct>
: generic_product_impl_base<Lhs,Rhs,generic_product_impl<Lhs,Rhs,DenseShape,DenseShape,GemmProduct> >
{
typedef typename Product<Lhs,Rhs>::Scalar Scalar;
typedef typename Lhs::Scalar LhsScalar;
typedef typename Rhs::Scalar RhsScalar;
typedef internal::blas_traits<Lhs> LhsBlasTraits;
typedef typename LhsBlasTraits::DirectLinearAccessType ActualLhsType;
typedef typename internal::remove_all<ActualLhsType>::type ActualLhsTypeCleaned;
typedef internal::blas_traits<Rhs> RhsBlasTraits;
typedef typename RhsBlasTraits::DirectLinearAccessType ActualRhsType;
typedef typename internal::remove_all<ActualRhsType>::type ActualRhsTypeCleaned;
enum {
MaxDepthAtCompileTime = EIGEN_SIZE_MIN_PREFER_FIXED(Lhs::MaxColsAtCompileTime,Rhs::MaxRowsAtCompileTime)
};
typedef generic_product_impl<Lhs,Rhs,DenseShape,DenseShape,CoeffBasedProductMode> lazyproduct;
template<typename Dst>
static void evalTo(Dst& dst, const Lhs& lhs, const Rhs& rhs)
{
// See http://eigen.tuxfamily.org/bz/show_bug.cgi?id=404 for a discussion and helper program
// to determine the following heuristic.
// EIGEN_GEMM_TO_COEFFBASED_THRESHOLD is typically defined to 20 in GeneralProduct.h,
// unless it has been specialized by the user or for a given architecture.
// Note that the condition rhs.rows()>0 was required because lazy produc is (was?) not happy with empty inputs.
// I'm not sure it is still required.
if((rhs.rows()+dst.rows()+dst.cols())<EIGEN_GEMM_TO_COEFFBASED_THRESHOLD && rhs.rows()>0)
lazyproduct::evalTo(dst, lhs, rhs);
else
{
dst.setZero();
scaleAndAddTo(dst, lhs, rhs, Scalar(1));
}
}
template<typename Dst>
static void addTo(Dst& dst, const Lhs& lhs, const Rhs& rhs)
{
if((rhs.rows()+dst.rows()+dst.cols())<EIGEN_GEMM_TO_COEFFBASED_THRESHOLD && rhs.rows()>0)
lazyproduct::addTo(dst, lhs, rhs);
else
scaleAndAddTo(dst,lhs, rhs, Scalar(1));
}
template<typename Dst>
static void subTo(Dst& dst, const Lhs& lhs, const Rhs& rhs)
{
if((rhs.rows()+dst.rows()+dst.cols())<EIGEN_GEMM_TO_COEFFBASED_THRESHOLD && rhs.rows()>0)
lazyproduct::subTo(dst, lhs, rhs);
else
scaleAndAddTo(dst, lhs, rhs, Scalar(-1));
}
template<typename Dest>
static void scaleAndAddTo(Dest& dst, const Lhs& a_lhs, const Rhs& a_rhs, const Scalar& alpha)
{
eigen_assert(dst.rows()==a_lhs.rows() && dst.cols()==a_rhs.cols());
if(a_lhs.cols()==0 || a_lhs.rows()==0 || a_rhs.cols()==0)
return;
typename internal::add_const_on_value_type<ActualLhsType>::type lhs = LhsBlasTraits::extract(a_lhs);
typename internal::add_const_on_value_type<ActualRhsType>::type rhs = RhsBlasTraits::extract(a_rhs);
Scalar actualAlpha = alpha * LhsBlasTraits::extractScalarFactor(a_lhs)
* RhsBlasTraits::extractScalarFactor(a_rhs);
typedef internal::gemm_blocking_space<(Dest::Flags&RowMajorBit) ? RowMajor : ColMajor,LhsScalar,RhsScalar,
Dest::MaxRowsAtCompileTime,Dest::MaxColsAtCompileTime,MaxDepthAtCompileTime> BlockingType;
typedef internal::gemm_functor<
Scalar, Index,
internal::general_matrix_matrix_product<
Index,
LhsScalar, (ActualLhsTypeCleaned::Flags&RowMajorBit) ? RowMajor : ColMajor, bool(LhsBlasTraits::NeedToConjugate),
RhsScalar, (ActualRhsTypeCleaned::Flags&RowMajorBit) ? RowMajor : ColMajor, bool(RhsBlasTraits::NeedToConjugate),
(Dest::Flags&RowMajorBit) ? RowMajor : ColMajor>,
ActualLhsTypeCleaned, ActualRhsTypeCleaned, Dest, BlockingType> GemmFunctor;
BlockingType blocking(dst.rows(), dst.cols(), lhs.cols(), 1, true);
internal::parallelize_gemm<(Dest::MaxRowsAtCompileTime>32 || Dest::MaxRowsAtCompileTime==Dynamic)>
(GemmFunctor(lhs, rhs, dst, actualAlpha, blocking), a_lhs.rows(), a_rhs.cols(), a_lhs.cols(), Dest::Flags&RowMajorBit);
}
};
} // end namespace internal
} // end namespace Eigen
#endif // EIGEN_GENERAL_MATRIX_MATRIX_H
|
AuxiliaryUtilities.h | #pragma once
// Author: Miguel Angel Celigueta maceli@cimne.upc.edu
#include <pybind11/pybind11.h>
#include "includes/define.h"
#include "includes/model_part.h"
#include "pre_utilities.h"
namespace Kratos {
class AuxiliaryUtilities {
public:
typedef ModelPart::ElementsContainerType ElementsArrayType;
typedef ModelPart::NodesContainerType::ContainerType NodesContainerType;
typedef GlobalPointersVector<Element> ParticleWeakVectorType;
typedef GlobalPointersVector<Element>::iterator ParticleWeakIteratorType;
KRATOS_CLASS_POINTER_DEFINITION(AuxiliaryUtilities);
AuxiliaryUtilities() {};
virtual ~AuxiliaryUtilities() {};
double ComputeAverageZStressFor2D(ModelPart& rSpheresModelPart) {
ElementsArrayType& pElements = rSpheresModelPart.GetCommunicator().LocalMesh().Elements();
double sub_total = 0.0;
double average_value = 0.0;
#pragma omp parallel for
for (int k = 0; k < (int)pElements.size(); k++) {
ElementsArrayType::iterator it = pElements.ptr_begin() + k;
Element* p_element = &(*it);
SphericContinuumParticle* p_sphere = dynamic_cast<SphericContinuumParticle*>(p_element);
double z_tensor_value = (*p_sphere->mSymmStressTensor)(2,2);
sub_total += z_tensor_value;
}
average_value = sub_total/(int)pElements.size();
return average_value;
}
};
}
|
GB_binop__bset_uint8.c | //------------------------------------------------------------------------------
// GB_binop: hard-coded functions for each built-in binary operator
//------------------------------------------------------------------------------
// SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2021, All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
//------------------------------------------------------------------------------
// If this file is in the Generated/ folder, do not edit it (auto-generated).
#include "GB.h"
#ifndef GBCOMPACT
#include "GB_emult.h"
#include "GB_control.h"
#include "GB_ek_slice.h"
#include "GB_dense.h"
#include "GB_atomics.h"
#include "GB_bitmap_assign_methods.h"
#include "GB_binop__include.h"
// C=binop(A,B) is defined by the following types and operators:
// A+B function (eWiseAdd): GB (_AaddB__bset_uint8)
// A.*B function (eWiseMult): GB (_AemultB)
// A.*B function (eWiseMult): GB (_AemultB_02__bset_uint8)
// A.*B function (eWiseMult): GB (_AemultB_03__bset_uint8)
// A.*B function (eWiseMult): GB (_AemultB_bitmap__bset_uint8)
// A*D function (colscale): GB ((none))
// D*A function (rowscale): GB ((node))
// C+=B function (dense accum): GB (_Cdense_accumB__bset_uint8)
// C+=b function (dense accum): GB (_Cdense_accumb__bset_uint8)
// C+=A+B function (dense ewise3): GB ((none))
// C=A+B function (dense ewise3): GB (_Cdense_ewise3_noaccum__bset_uint8)
// C=scalar+B GB (_bind1st__bset_uint8)
// C=scalar+B' GB (_bind1st_tran__bset_uint8)
// C=A+scalar GB (_bind2nd__bset_uint8)
// C=A'+scalar GB (_bind2nd_tran__bset_uint8)
// C type: uint8_t
// A type: uint8_t
// B,b type: uint8_t
// BinaryOp: cij = GB_BITSET (aij, bij, uint8_t, 8)
#define GB_ATYPE \
uint8_t
#define GB_BTYPE \
uint8_t
#define GB_CTYPE \
uint8_t
// true if the types of A and B are identical
#define GB_ATYPE_IS_BTYPE \
1
// true if the types of C and A are identical
#define GB_CTYPE_IS_ATYPE \
1
// true if the types of C and B are identical
#define GB_CTYPE_IS_BTYPE \
1
// aij = Ax [pA]
#define GB_GETA(aij,Ax,pA) \
uint8_t aij = Ax [pA]
// bij = Bx [pB]
#define GB_GETB(bij,Bx,pB) \
uint8_t bij = Bx [pB]
// declare scalar of the same type as C
#define GB_CTYPE_SCALAR(t) \
uint8_t t
// cij = Ax [pA]
#define GB_COPY_A_TO_C(cij,Ax,pA) \
cij = Ax [pA]
// cij = Bx [pB]
#define GB_COPY_B_TO_C(cij,Bx,pB) \
cij = Bx [pB]
#define GB_CX(p) Cx [p]
// binary operator
#define GB_BINOP(z, x, y, i, j) \
z = GB_BITSET (x, y, uint8_t, 8) ;
// true if the binop must be flipped
#define GB_BINOP_FLIP \
1
// op is second
#define GB_OP_IS_SECOND \
0
// do the numerical phases of GB_add and GB_emult
#define GB_PHASE_2_OF_2
// hard-coded loops can be vectorized
#define GB_PRAGMA_SIMD_VECTORIZE GB_PRAGMA_SIMD
// disable this operator and use the generic case if these conditions hold
#define GB_DISABLE \
(GxB_NO_BSET || GxB_NO_UINT8 || GxB_NO_BSET_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__bset_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__bset_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__bset_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
//------------------------------------------------------------------------------
#if 0
GrB_Info GB ((none))
(
GrB_Matrix C,
const GrB_Matrix A, bool A_is_pattern,
const GrB_Matrix D, bool D_is_pattern,
const int64_t *A_ek_slicing, const int A_ntasks, const int A_nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
uint8_t *restrict Cx = (uint8_t *) C->x ;
#include "GB_AxB_colscale_meta.c"
return (GrB_SUCCESS) ;
#endif
}
#endif
//------------------------------------------------------------------------------
// C = D*B, row scale with diagonal D matrix
//------------------------------------------------------------------------------
#if 0
GrB_Info GB ((node))
(
GrB_Matrix C,
const GrB_Matrix D, bool D_is_pattern,
const GrB_Matrix B, bool B_is_pattern,
int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
uint8_t *restrict Cx = (uint8_t *) C->x ;
#include "GB_AxB_rowscale_meta.c"
return (GrB_SUCCESS) ;
#endif
}
#endif
//------------------------------------------------------------------------------
// eWiseAdd: C = A+B or C<M> = A+B
//------------------------------------------------------------------------------
GrB_Info GB (_AaddB__bset_uint8)
(
GrB_Matrix C,
const int C_sparsity,
const GrB_Matrix M,
const bool Mask_struct,
const bool Mask_comp,
const GrB_Matrix A,
const GrB_Matrix B,
const bool Ch_is_Mh,
const int64_t *restrict C_to_M,
const int64_t *restrict C_to_A,
const int64_t *restrict C_to_B,
const GB_task_struct *restrict TaskList,
const int C_ntasks,
const int C_nthreads,
GB_Context Context
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
GB_WERK_DECLARE (M_ek_slicing, int64_t) ;
GB_WERK_DECLARE (A_ek_slicing, int64_t) ;
GB_WERK_DECLARE (B_ek_slicing, int64_t) ;
#include "GB_add_template.c"
GB_FREE_WORK ;
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// eWiseMult: C = A.*B or C<M> = A.*B
//------------------------------------------------------------------------------
GrB_Info GB (_AemultB_01__bset_uint8)
(
GrB_Matrix C,
const int C_sparsity,
const int ewise_method,
const GrB_Matrix M,
const bool Mask_struct,
const bool Mask_comp,
const GrB_Matrix A,
const GrB_Matrix B,
const int64_t *restrict C_to_M,
const int64_t *restrict C_to_A,
const int64_t *restrict C_to_B,
const GB_task_struct *restrict TaskList,
const int C_ntasks,
const int C_nthreads,
GB_Context Context
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
#include "GB_emult_01_meta.c"
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// eWiseMult: C<#> = A.*B when A is sparse/hyper and B is bitmap/full
//------------------------------------------------------------------------------
GrB_Info GB (_AemultB_02__bset_uint8)
(
GrB_Matrix C,
const GrB_Matrix M,
const bool Mask_struct,
const bool Mask_comp,
const GrB_Matrix A,
const GrB_Matrix B,
const bool flipxy,
const int64_t *restrict Cp_kfirst,
const int64_t *A_ek_slicing, const int A_ntasks, const int A_nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
#if GB_BINOP_FLIP
// The operator is not commutative, and does not have a flipped
// variant. For example z=atan2(y,x).
if (flipxy)
{
// use fmult(y,x)
#undef GB_FLIPPED
#define GB_FLIPPED 1
#include "GB_emult_02_template.c"
}
else
{
// use fmult(x,y)
#undef GB_FLIPPED
#define GB_FLIPPED 0
#include "GB_emult_02_template.c"
}
#else
// No need to handle the flip: the operator is either commutative, or
// has been handled by changing z=div(y,x) to z=rdiv(x,y) for example.
#undef GB_FLIPPED
#define GB_FLIPPED 0
#include "GB_emult_02_template.c"
#endif
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// eWiseMult: C<M> = A.*B, M sparse/hyper, A and B bitmap/full
//------------------------------------------------------------------------------
GrB_Info GB (_AemultB_03__bset_uint8)
(
GrB_Matrix C,
const GrB_Matrix M,
const bool Mask_struct,
const GrB_Matrix A,
const GrB_Matrix B,
const int64_t *restrict Cp_kfirst,
const int64_t *M_ek_slicing, const int M_ntasks, const int M_nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
#include "GB_emult_03_template.c"
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// eWiseMult: C=A.*B, C<M>=A.*B, C<!M>=A.*B where C is bitmap
//------------------------------------------------------------------------------
GrB_Info GB (_AemultB_bitmap__bset_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__bset_uint8)
(
GB_void *Cx_output, // Cx and Bx may be aliased
const GB_void *x_input,
const GB_void *Bx_input,
const int8_t *restrict Bb,
int64_t anz,
int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
uint8_t *Cx = (uint8_t *) Cx_output ;
uint8_t x = (*((uint8_t *) x_input)) ;
uint8_t *Bx = (uint8_t *) Bx_input ;
int64_t p ;
#pragma omp parallel for num_threads(nthreads) schedule(static)
for (p = 0 ; p < anz ; p++)
{
if (!GBB (Bb, p)) continue ;
uint8_t bij = Bx [p] ;
Cx [p] = GB_BITSET (x, bij, uint8_t, 8) ;
}
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// Cx = op (Ax,y): apply a binary operator to a matrix with scalar bind2nd
//------------------------------------------------------------------------------
GrB_Info GB (_bind2nd__bset_uint8)
(
GB_void *Cx_output, // Cx and Ax may be aliased
const GB_void *Ax_input,
const GB_void *y_input,
const int8_t *restrict Ab,
int64_t anz,
int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
int64_t p ;
uint8_t *Cx = (uint8_t *) Cx_output ;
uint8_t *Ax = (uint8_t *) Ax_input ;
uint8_t y = (*((uint8_t *) y_input)) ;
#pragma omp parallel for num_threads(nthreads) schedule(static)
for (p = 0 ; p < anz ; p++)
{
if (!GBB (Ab, p)) continue ;
uint8_t aij = Ax [p] ;
Cx [p] = GB_BITSET (aij, y, uint8_t, 8) ;
}
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// C = op (x, A'): transpose and apply a binary operator
//------------------------------------------------------------------------------
// cij = op (x, aij), no typecasting (in spite of the macro name)
#undef GB_CAST_OP
#define GB_CAST_OP(pC,pA) \
{ \
uint8_t aij = Ax [pA] ; \
Cx [pC] = GB_BITSET (x, aij, uint8_t, 8) ; \
}
GrB_Info GB (_bind1st_tran__bset_uint8)
(
GrB_Matrix C,
const GB_void *x_input,
const GrB_Matrix A,
int64_t *restrict *Workspaces,
const int64_t *restrict A_slice,
int nworkspaces,
int nthreads
)
{
// GB_unop_transpose.c uses GB_ATYPE, but A is
// the 2nd input to binary operator z=f(x,y).
#undef GB_ATYPE
#define GB_ATYPE \
uint8_t
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
uint8_t x = (*((const uint8_t *) x_input)) ;
#include "GB_unop_transpose.c"
return (GrB_SUCCESS) ;
#endif
#undef GB_ATYPE
#define GB_ATYPE \
uint8_t
}
//------------------------------------------------------------------------------
// C = op (A', y): transpose and apply a binary operator
//------------------------------------------------------------------------------
// cij = op (aij, y), no typecasting (in spite of the macro name)
#undef GB_CAST_OP
#define GB_CAST_OP(pC,pA) \
{ \
uint8_t aij = Ax [pA] ; \
Cx [pC] = GB_BITSET (aij, y, uint8_t, 8) ; \
}
GrB_Info GB (_bind2nd_tran__bset_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
|
GB_binop__rdiv_int16.c |
//------------------------------------------------------------------------------
// GB_binop: hard-coded functions for each built-in binary operator
//------------------------------------------------------------------------------
// SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2021, All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
//------------------------------------------------------------------------------
// If this file is in the Generated2/ folder, do not edit it
// (it is auto-generated from Generator/*).
#include "GB.h"
#ifndef GBCOMPACT
#include "GB_emult.h"
#include "GB_control.h"
#include "GB_ek_slice.h"
#include "GB_dense.h"
#include "GB_atomics.h"
#include "GB_bitmap_assign_methods.h"
#include "GB_binop__include.h"
// C=binop(A,B) is defined by the following types and operators:
// A+B function (eWiseAdd): GB (_AaddB__rdiv_int16)
// A.*B function (eWiseMult): GB (_AemultB_08__rdiv_int16)
// A.*B function (eWiseMult): GB (_AemultB_02__rdiv_int16)
// A.*B function (eWiseMult): GB (_AemultB_04__rdiv_int16)
// A.*B function (eWiseMult): GB (_AemultB_bitmap__rdiv_int16)
// A*D function (colscale): GB (_AxD__rdiv_int16)
// D*A function (rowscale): GB (_DxB__rdiv_int16)
// C+=B function (dense accum): GB (_Cdense_accumB__rdiv_int16)
// C+=b function (dense accum): GB (_Cdense_accumb__rdiv_int16)
// C+=A+B function (dense ewise3): GB (_Cdense_ewise3_accum__rdiv_int16)
// C=A+B function (dense ewise3): GB (_Cdense_ewise3_noaccum__rdiv_int16)
// C=scalar+B GB (_bind1st__rdiv_int16)
// C=scalar+B' GB (_bind1st_tran__rdiv_int16)
// C=A+scalar GB (_bind2nd__rdiv_int16)
// C=A'+scalar GB (_bind2nd_tran__rdiv_int16)
// C type: int16_t
// A type: int16_t
// A pattern? 0
// B type: int16_t
// B pattern? 0
// BinaryOp: cij = GB_IDIV_SIGNED (bij, aij, 16)
#define GB_ATYPE \
int16_t
#define GB_BTYPE \
int16_t
#define GB_CTYPE \
int16_t
// true if the types of A and B are identical
#define GB_ATYPE_IS_BTYPE \
1
// true if the types of C and A are identical
#define GB_CTYPE_IS_ATYPE \
1
// true if the types of C and B are identical
#define GB_CTYPE_IS_BTYPE \
1
// aij = Ax [pA]
#define GB_GETA(aij,Ax,pA,A_iso) \
int16_t aij = GBX (Ax, pA, A_iso)
// true if values of A are not used
#define GB_A_IS_PATTERN \
0 \
// bij = Bx [pB]
#define GB_GETB(bij,Bx,pB,B_iso) \
int16_t bij = GBX (Bx, pB, B_iso)
// true if values of B are not used
#define GB_B_IS_PATTERN \
0 \
// declare scalar of the same type as C
#define GB_CTYPE_SCALAR(t) \
int16_t t
// cij = Ax [pA]
#define GB_COPY_A_TO_C(cij,Ax,pA,A_iso) \
cij = GBX (Ax, pA, A_iso)
// cij = Bx [pB]
#define GB_COPY_B_TO_C(cij,Bx,pB,B_iso) \
cij = GBX (Bx, pB, B_iso)
#define GB_CX(p) Cx [p]
// binary operator
#define GB_BINOP(z,x,y,i,j) \
z = GB_IDIV_SIGNED (y, x, 16) ;
// 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_RDIV || GxB_NO_INT16 || GxB_NO_RDIV_INT16)
//------------------------------------------------------------------------------
// C += A+B, all 3 matrices dense
//------------------------------------------------------------------------------
// The op must be MIN, MAX, PLUS, MINUS, RMINUS, TIMES, DIV, or RDIV.
void GB (_Cdense_ewise3_accum__rdiv_int16)
(
GrB_Matrix C,
const GrB_Matrix A,
const GrB_Matrix B,
const int nthreads
)
{
#include "GB_dense_ewise3_accum_template.c"
}
//------------------------------------------------------------------------------
// C = A+B, all 3 matrices dense
//------------------------------------------------------------------------------
void GB (_Cdense_ewise3_noaccum__rdiv_int16)
(
GrB_Matrix C,
const GrB_Matrix A,
const GrB_Matrix B,
const int nthreads
)
{
#include "GB_dense_ewise3_noaccum_template.c"
}
//------------------------------------------------------------------------------
// C += B, accumulate a sparse matrix into a dense matrix
//------------------------------------------------------------------------------
GrB_Info GB (_Cdense_accumB__rdiv_int16)
(
GrB_Matrix C,
const GrB_Matrix B,
const int64_t *B_ek_slicing, const int B_ntasks, const int B_nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
{
#include "GB_dense_subassign_23_template.c"
}
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// C += b, accumulate a scalar into a dense matrix
//------------------------------------------------------------------------------
GrB_Info GB (_Cdense_accumb__rdiv_int16)
(
GrB_Matrix C,
const GB_void *p_bwork,
const int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
{
// get the scalar b for C += b, of type int16_t
int16_t bwork = (*((int16_t *) p_bwork)) ;
#include "GB_dense_subassign_22_template.c"
return (GrB_SUCCESS) ;
}
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// C = A*D, column scale with diagonal D matrix
//------------------------------------------------------------------------------
GrB_Info GB (_AxD__rdiv_int16)
(
GrB_Matrix C,
const GrB_Matrix A,
const GrB_Matrix D,
const int64_t *A_ek_slicing, const int A_ntasks, const int A_nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
int16_t *restrict Cx = (int16_t *) C->x ;
#include "GB_AxB_colscale_template.c"
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// C = D*B, row scale with diagonal D matrix
//------------------------------------------------------------------------------
GrB_Info GB (_DxB__rdiv_int16)
(
GrB_Matrix C,
const GrB_Matrix D,
const GrB_Matrix B,
int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
int16_t *restrict Cx = (int16_t *) C->x ;
#include "GB_AxB_rowscale_template.c"
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// eWiseAdd: C=A+B, C<M>=A+B, C<!M>=A+B
//------------------------------------------------------------------------------
GrB_Info GB (_AaddB__rdiv_int16)
(
GrB_Matrix C,
const int C_sparsity,
const GrB_Matrix M,
const bool Mask_struct,
const bool Mask_comp,
const GrB_Matrix A,
const GrB_Matrix B,
const bool is_eWiseUnion,
const GB_void *alpha_scalar_in,
const GB_void *beta_scalar_in,
const bool Ch_is_Mh,
const int64_t *restrict C_to_M,
const int64_t *restrict C_to_A,
const int64_t *restrict C_to_B,
const GB_task_struct *restrict TaskList,
const int C_ntasks,
const int C_nthreads,
GB_Context Context
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
GB_WERK_DECLARE (M_ek_slicing, int64_t) ;
GB_WERK_DECLARE (A_ek_slicing, int64_t) ;
GB_WERK_DECLARE (B_ek_slicing, int64_t) ;
int16_t alpha_scalar ;
int16_t beta_scalar ;
if (is_eWiseUnion)
{
alpha_scalar = (*((int16_t *) alpha_scalar_in)) ;
beta_scalar = (*((int16_t *) beta_scalar_in )) ;
}
#include "GB_add_template.c"
GB_FREE_WORKSPACE ;
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// eWiseMult: C=A.*B, C<M>=A.*B, or C<M!>=A.*B where C is sparse/hyper
//------------------------------------------------------------------------------
GrB_Info GB (_AemultB_08__rdiv_int16)
(
GrB_Matrix C,
const int C_sparsity,
const int ewise_method,
const GrB_Matrix M,
const bool Mask_struct,
const bool Mask_comp,
const GrB_Matrix A,
const GrB_Matrix B,
const int64_t *restrict C_to_M,
const int64_t *restrict C_to_A,
const int64_t *restrict C_to_B,
const GB_task_struct *restrict TaskList,
const int C_ntasks,
const int C_nthreads,
GB_Context Context
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
#include "GB_emult_08_meta.c"
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// eWiseMult: C<#> = A.*B when A is sparse/hyper and B is bitmap/full
//------------------------------------------------------------------------------
GrB_Info GB (_AemultB_02__rdiv_int16)
(
GrB_Matrix C,
const GrB_Matrix M,
const bool Mask_struct,
const bool Mask_comp,
const GrB_Matrix A,
const GrB_Matrix B,
const bool flipxy,
const int64_t *restrict Cp_kfirst,
const int64_t *A_ek_slicing, const int A_ntasks, const int A_nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
#if GB_BINOP_FLIP
// The operator is not commutative, and does not have a flipped
// variant. For example z=atan2(y,x).
if (flipxy)
{
// use fmult(y,x)
#undef GB_FLIPPED
#define GB_FLIPPED 1
#include "GB_emult_02_template.c"
}
else
{
// use fmult(x,y)
#undef GB_FLIPPED
#define GB_FLIPPED 0
#include "GB_emult_02_template.c"
}
#else
// No need to handle the flip: the operator is either commutative, or
// has been handled by changing z=div(y,x) to z=rdiv(x,y) for example.
#undef GB_FLIPPED
#define GB_FLIPPED 0
#include "GB_emult_02_template.c"
#endif
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// eWiseMult: C<M> = A.*B, M sparse/hyper, A and B bitmap/full
//------------------------------------------------------------------------------
GrB_Info GB (_AemultB_04__rdiv_int16)
(
GrB_Matrix C,
const GrB_Matrix M,
const bool Mask_struct,
const GrB_Matrix A,
const GrB_Matrix B,
const int64_t *restrict Cp_kfirst,
const int64_t *M_ek_slicing, const int M_ntasks, const int M_nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
#include "GB_emult_04_template.c"
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// eWiseMult: C=A.*B, C<M>=A.*B, C<!M>=A.*B where C is bitmap
//------------------------------------------------------------------------------
GrB_Info GB (_AemultB_bitmap__rdiv_int16)
(
GrB_Matrix C,
const int ewise_method,
const GrB_Matrix M,
const bool Mask_struct,
const bool Mask_comp,
const GrB_Matrix A,
const GrB_Matrix B,
const int64_t *M_ek_slicing, const int M_ntasks, const int M_nthreads,
const int C_nthreads,
GB_Context Context
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
#include "GB_bitmap_emult_template.c"
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// Cx = op (x,Bx): apply a binary operator to a matrix with scalar bind1st
//------------------------------------------------------------------------------
GrB_Info GB (_bind1st__rdiv_int16)
(
GB_void *Cx_output, // Cx and Bx may be aliased
const GB_void *x_input,
const GB_void *Bx_input,
const int8_t *restrict Bb,
int64_t bnz,
int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
int16_t *Cx = (int16_t *) Cx_output ;
int16_t x = (*((int16_t *) x_input)) ;
int16_t *Bx = (int16_t *) Bx_input ;
int64_t p ;
#pragma omp parallel for num_threads(nthreads) schedule(static)
for (p = 0 ; p < bnz ; p++)
{
if (!GBB (Bb, p)) continue ;
int16_t bij = GBX (Bx, p, false) ;
Cx [p] = GB_IDIV_SIGNED (bij, x, 16) ;
}
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// Cx = op (Ax,y): apply a binary operator to a matrix with scalar bind2nd
//------------------------------------------------------------------------------
GrB_Info GB (_bind2nd__rdiv_int16)
(
GB_void *Cx_output, // Cx and Ax may be aliased
const GB_void *Ax_input,
const GB_void *y_input,
const int8_t *restrict Ab,
int64_t anz,
int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
int64_t p ;
int16_t *Cx = (int16_t *) Cx_output ;
int16_t *Ax = (int16_t *) Ax_input ;
int16_t y = (*((int16_t *) y_input)) ;
#pragma omp parallel for num_threads(nthreads) schedule(static)
for (p = 0 ; p < anz ; p++)
{
if (!GBB (Ab, p)) continue ;
int16_t aij = GBX (Ax, p, false) ;
Cx [p] = GB_IDIV_SIGNED (y, aij, 16) ;
}
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// C = op (x, A'): transpose and apply a binary operator
//------------------------------------------------------------------------------
// cij = op (x, aij), no typecasting (in spite of the macro name)
#undef GB_CAST_OP
#define GB_CAST_OP(pC,pA) \
{ \
int16_t aij = GBX (Ax, pA, false) ; \
Cx [pC] = GB_IDIV_SIGNED (aij, x, 16) ; \
}
GrB_Info GB (_bind1st_tran__rdiv_int16)
(
GrB_Matrix C,
const GB_void *x_input,
const GrB_Matrix A,
int64_t *restrict *Workspaces,
const int64_t *restrict A_slice,
int nworkspaces,
int nthreads
)
{
// GB_unop_transpose.c uses GB_ATYPE, but A is
// the 2nd input to binary operator z=f(x,y).
#undef GB_ATYPE
#define GB_ATYPE \
int16_t
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
int16_t x = (*((const int16_t *) x_input)) ;
#include "GB_unop_transpose.c"
return (GrB_SUCCESS) ;
#endif
#undef GB_ATYPE
#define GB_ATYPE \
int16_t
}
//------------------------------------------------------------------------------
// C = op (A', y): transpose and apply a binary operator
//------------------------------------------------------------------------------
// cij = op (aij, y), no typecasting (in spite of the macro name)
#undef GB_CAST_OP
#define GB_CAST_OP(pC,pA) \
{ \
int16_t aij = GBX (Ax, pA, false) ; \
Cx [pC] = GB_IDIV_SIGNED (y, aij, 16) ; \
}
GrB_Info GB (_bind2nd_tran__rdiv_int16)
(
GrB_Matrix C,
const GrB_Matrix A,
const GB_void *y_input,
int64_t *restrict *Workspaces,
const int64_t *restrict A_slice,
int nworkspaces,
int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
int16_t y = (*((const int16_t *) y_input)) ;
#include "GB_unop_transpose.c"
return (GrB_SUCCESS) ;
#endif
}
#endif
|
organismsbuffer.h | #pragma once
#include "organism.h"
#include "rng.h"
#include <assert.h>
namespace NEAT {
template<typename TOrganism = Organism>
class OrganismsBuffer {
size_t _n;
std::vector<TOrganism> _a;
std::vector<TOrganism> _b;
std::vector<TOrganism> *_curr;
std::vector<TOrganism> *_prev;
public:
OrganismsBuffer(rng_t rng,
std::vector<std::unique_ptr<Genome>> &seeds,
size_t n,
size_t population_index = 0)
: _n(n) {
_a.reserve(n);
_b.reserve(n);
_curr = &_a;
_prev = &_b;
for(size_t i = 0; i < n; i++) {
_a.emplace_back(*seeds[i + population_index]);
size_t ipop = i + population_index;
_a[i].population_index = ipop;
_a[i].net->population_index = ipop;
_a[i].genome->genome_id = ipop;
_a[i].genome->rng.seed(rng.integer());
}
for(size_t i = 0; i < n; i++) {
_b.emplace_back(*seeds[i + population_index]);
size_t ipop = i + population_index;
_b[i].population_index = ipop;
_b[i].net->population_index = ipop;
_b[i].genome->genome_id = ipop;
_b[i].genome->rng.seed(rng.integer());
}
}
void init_phenotypes() {
#pragma omp parallel for
for(size_t i = 0; i < _n; i++) {
Organism &org = curr()[i];
org.genome->init_phenotype(*org.net);
}
}
size_t size(){
return _n;
}
std::vector<TOrganism> &curr() {
return *_curr;
}
std::vector<TOrganism> &prev() {
return *_prev;
}
void next_generation(int generation) {
if(_curr == &_a) {
_curr = &_b;
_prev = &_a;
} else {
_curr = &_a;
_prev = &_b;
}
assert( _curr->size() == _n );
for(TOrganism &org: curr())
org.init(generation);
}
};
}
|
update_ops_named_X.c |
#include "constant.h"
#include "update_ops.h"
#include "utility.h"
#ifdef _OPENMP
#include <omp.h>
#endif
#ifdef _USE_SIMD
#ifdef _MSC_VER
#include <intrin.h>
#else
#include <x86intrin.h>
#endif
#endif
//void X_gate_old(UINT target_qubit_index, CTYPE *state, ITYPE dim);
//void X_gate_single(UINT target_qubit_index, CTYPE *state, ITYPE dim);
//void X_gate_parallel(UINT target_qubit_index, CTYPE *state, ITYPE dim);
void X_gate(UINT target_qubit_index, CTYPE *state, ITYPE dim) {
//UINT threshold = 13;
//X_gate_old(target_qubit_index, state, dim);
//X_gate_single(target_qubit_index, state, dim);
//X_gate_single_simd(target_qubit_index, state, dim);
//X_gate_single_unroll(target_qubit_index, state, dim);
//X_gate_parallel(target_qubit_index, state, dim);
//return;
#ifdef _USE_SIMD
#ifdef _OPENMP
UINT threshold = 13;
if (dim < (((ITYPE)1) << threshold)) {
X_gate_single_simd(target_qubit_index, state, dim);
}
else {
X_gate_parallel_simd(target_qubit_index, state, dim);
}
#else
X_gate_single_simd(target_qubit_index, state, dim);
#endif
#else
#ifdef _OPENMP
UINT threshold = 13;
if (dim < (((ITYPE)1) << threshold)) {
X_gate_single_unroll(target_qubit_index, state, dim);
}
else {
X_gate_parallel_unroll(target_qubit_index, state, dim);
}
#else
X_gate_single_unroll(target_qubit_index, state, dim);
#endif
#endif
}
void X_gate_single_unroll(UINT target_qubit_index, CTYPE *state, ITYPE dim) {
const ITYPE loop_dim = dim / 2;
const ITYPE mask = (1ULL << target_qubit_index);
const ITYPE mask_low = mask - 1;
const ITYPE mask_high = ~mask_low;
ITYPE state_index = 0;
if (target_qubit_index == 0) {
ITYPE basis_index = 0;
for (basis_index = 0; basis_index < dim; basis_index += 2) {
CTYPE temp = state[basis_index];
state[basis_index] = state[basis_index + 1];
state[basis_index + 1] = temp;
}
}
else {
for (state_index = 0; state_index < loop_dim; state_index += 2) {
ITYPE basis_index_0 = (state_index&mask_low) + ((state_index&mask_high) << 1);
ITYPE basis_index_1 = basis_index_0 + mask;
CTYPE temp0 = state[basis_index_0];
CTYPE temp1 = state[basis_index_0+1];
state[basis_index_0] = state[basis_index_1];
state[basis_index_0+1] = state[basis_index_1+1];
state[basis_index_1] = temp0;
state[basis_index_1+1] = temp1;
}
}
}
#ifdef _OPENMP
void X_gate_parallel_unroll(UINT target_qubit_index, CTYPE *state, ITYPE dim) {
const ITYPE loop_dim = dim / 2;
const ITYPE mask = (1ULL << target_qubit_index);
const ITYPE mask_low = mask - 1;
const ITYPE mask_high = ~mask_low;
ITYPE state_index = 0;
if (target_qubit_index == 0) {
ITYPE basis_index = 0;
#pragma omp parallel for
for (basis_index = 0; basis_index < dim; basis_index += 2) {
CTYPE temp = state[basis_index];
state[basis_index] = state[basis_index + 1];
state[basis_index + 1] = temp;
}
}
else {
#pragma omp parallel for
for (state_index = 0; state_index < loop_dim; state_index += 2) {
ITYPE basis_index_0 = (state_index&mask_low) + ((state_index&mask_high) << 1);
ITYPE basis_index_1 = basis_index_0 + mask;
CTYPE temp0 = state[basis_index_0];
CTYPE temp1 = state[basis_index_0 + 1];
state[basis_index_0] = state[basis_index_1];
state[basis_index_0 + 1] = state[basis_index_1 + 1];
state[basis_index_1] = temp0;
state[basis_index_1 + 1] = temp1;
}
}
}
#endif
#ifdef _USE_SIMD
void X_gate_single_simd(UINT target_qubit_index, CTYPE *state, ITYPE dim) {
const ITYPE loop_dim = dim / 2;
const ITYPE mask = (1ULL << target_qubit_index);
const ITYPE mask_low = mask - 1;
const ITYPE mask_high = ~mask_low;
ITYPE state_index = 0;
//double* cast_state = (double*)state;
if (target_qubit_index == 0) {
ITYPE basis_index = 0;
for (basis_index = 0; basis_index < dim; basis_index += 2) {
double* ptr = (double*)(state + basis_index);
__m256d data = _mm256_loadu_pd(ptr);
data = _mm256_permute4x64_pd(data, 78); // (3210) -> (1032) : 1*2 + 4*3 + 16*0 + 64*1 = 2+12+64=78
_mm256_storeu_pd(ptr, data);
}
}
else {
for (state_index = 0; state_index < loop_dim; state_index += 2) {
ITYPE basis_index_0 = (state_index&mask_low) + ((state_index&mask_high) << 1);
ITYPE basis_index_1 = basis_index_0 + mask;
double* ptr0 = (double*)(state + basis_index_0);
double* ptr1 = (double*)(state + basis_index_1);
__m256d data0 = _mm256_loadu_pd(ptr0);
__m256d data1 = _mm256_loadu_pd(ptr1);
_mm256_storeu_pd(ptr1, data0);
_mm256_storeu_pd(ptr0, data1);
}
}
}
#ifdef _OPENMP
void X_gate_parallel_simd(UINT target_qubit_index, CTYPE *state, ITYPE dim) {
const ITYPE loop_dim = dim / 2;
const ITYPE mask = (1ULL << target_qubit_index);
const ITYPE mask_low = mask - 1;
const ITYPE mask_high = ~mask_low;
ITYPE state_index = 0;
//double* cast_state = (double*)state;
if (target_qubit_index == 0) {
ITYPE basis_index = 0;
#pragma omp parallel for
for (basis_index = 0; basis_index < dim; basis_index += 2) {
double* ptr = (double*)(state + basis_index);
__m256d data = _mm256_loadu_pd(ptr);
data = _mm256_permute4x64_pd(data, 78); // (3210) -> (1032) : 1*2 + 4*3 + 16*0 + 64*1 = 2+12+64=78
_mm256_storeu_pd(ptr, data);
}
}
else {
#pragma omp parallel for
for (state_index = 0; state_index < loop_dim; state_index += 2) {
ITYPE basis_index_0 = (state_index&mask_low) + ((state_index&mask_high) << 1);
ITYPE basis_index_1 = basis_index_0 + mask;
double* ptr0 = (double*)(state + basis_index_0);
double* ptr1 = (double*)(state + basis_index_1);
__m256d data0 = _mm256_loadu_pd(ptr0);
__m256d data1 = _mm256_loadu_pd(ptr1);
_mm256_storeu_pd(ptr1, data0);
_mm256_storeu_pd(ptr0, data1);
}
}
}
#endif
#endif
/*
void X_gate_old(UINT target_qubit_index, CTYPE *state, ITYPE dim) {
const ITYPE loop_dim = dim / 2;
const ITYPE mask = (1ULL << target_qubit_index);
ITYPE state_index;
#ifdef _OPENMP
//#pragma omp parallel for
#endif
for (state_index = 0; state_index < loop_dim; ++state_index) {
ITYPE basis_index_0 = insert_zero_to_basis_index(state_index, mask, target_qubit_index);
ITYPE basis_index_1 = basis_index_0 ^ mask;
swap_amplitude(state, basis_index_0, basis_index_1);
}
}
void X_gate_single(UINT target_qubit_index, CTYPE *state, ITYPE dim) {
const ITYPE loop_dim = dim / 2;
const ITYPE mask = (1ULL << target_qubit_index);
const ITYPE mask_low = mask - 1;
const ITYPE mask_high = ~mask_low;
ITYPE state_index = 0;
for (state_index = 0; state_index < loop_dim; ++state_index) {
ITYPE basis_index_0 = (state_index&mask_low) + ((state_index&mask_high) << 1);
ITYPE basis_index_1 = basis_index_0 + mask;
CTYPE temp = state[basis_index_0];
state[basis_index_0] = state[basis_index_1];
state[basis_index_1] = temp;
}
}
#ifdef _OPENMP
void X_gate_parallel(UINT target_qubit_index, CTYPE *state, ITYPE dim) {
const ITYPE loop_dim = dim / 2;
const ITYPE mask = (1ULL << target_qubit_index);
const ITYPE mask_low = mask - 1;
const ITYPE mask_high = ~mask_low;
ITYPE state_index = 0;
#pragma omp parallel for
for (state_index = 0; state_index < loop_dim; ++state_index) {
ITYPE basis_index_0 = (state_index&mask_low) + ((state_index&mask_high) << 1);
ITYPE basis_index_1 = basis_index_0 + mask;
CTYPE temp = state[basis_index_0];
state[basis_index_0] = state[basis_index_1];
state[basis_index_1] = temp;
}
}
#endif
*/
|
Searching.202008061153.less_sync.h | //
// Created by Zhen Peng on 8/6/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;
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);
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 idi 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_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_queues_of_four(
std::vector<Candidate> &set_L,
const std::vector<idi> &local_queues_starts,
std::vector<idi> &local_queues_sizes,
const idi group_id,
const idi local_queue_capacity,
const idi master_queue_capacity);
idi merge_all_queues_to_master(
std::vector<Candidate> &set_L,
const std::vector<idi> &local_queues_starts,
std::vector<idi> &local_queues_sizes,
const idi local_queue_capacity,
const idi local_master_queue_capacity,
const idi master_queue_capacity,
const idi group_size);
idi master_top_m_to_groups(
std::vector<Candidate> &set_L,
const std::vector<idi> &local_queues_starts,
std::vector<idi> &local_queues_sizes,
std::vector<idi> &top_m_candidates,
const std::vector<idi> &top_m_candidates_starts,
std::vector<idi> &top_m_candidates_sizes,
const idi k_uc,
idi &last_k,
const idi M,
const idi num_groups);
// const idi group_size);
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 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 seq_search_with_top_m_double_m(
const idi M_max,
const idi query_id,
const idi K,
const idi global_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);
idi expand_one_candidate(
idi cand_id,
const dataf *query_data,
const distf &dist_bound,
std::vector<Candidate> &set_L,
const idi local_queue_start,
idi &local_queue_size,
const idi &local_queue_capacity,
boost::dynamic_bitset<> &is_visited,
uint64_t &local_count_computation);
void para_search_with_top_m_hierarchy_merge_v0(
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_capacity, // Maximum size of local queue
const idi local_master_queue_capacity,
const std::vector<idi> &local_queues_starts,
std::vector<idi> &local_queues_sizes, // Sizes of local queue
// std::vector< std::vector<idi> > &top_m_candidates_list, // every group has one top-M queue
std::vector<idi> &top_m_candidate,
const std::vector<idi> &top_m_candidates_starts,
std::vector<idi> &top_m_candidates_sizes,
boost::dynamic_bitset<> &is_visited,
const idi group_size, // Should be 4
const idi full_merge_freq);
void para_search_with_top_m_less_sync_v0(
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_capacity, // Maximum size of local queue
const std::vector<idi> &local_queues_starts,
std::vector<idi> &local_queues_sizes, // Sizes of local queue
std::vector<idi> &top_m_candidates,
boost::dynamic_bitset<> &is_visited,
const idi full_merge_freq,
const idi local_iter_bound);
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_;
}
/**
* 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;
}
//
// 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;
}
/* 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 idi 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 insert_index;
}
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_index;
}
// 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;
}
}
return insert_index;
}
/* 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: merge 4 queues into the last queue
*/
inline idi Searching::merge_queues_of_four(
std::vector<Candidate> &set_L,
const std::vector<idi> &local_queues_starts,
std::vector<idi> &local_queues_sizes,
const idi group_id,
const idi local_queue_capacity,
const idi master_queue_capacity)
{
// const int num_queues = 4;
const idi group_start = group_id * 4;
idi nk = master_queue_capacity;
#pragma omp parallel for num_threads(2)
for (int i = 0; i < 2; ++i) {
const idi bi = 2 * i + group_start;
const idi ai = bi + 1;
if (!local_queues_sizes[bi]) {
continue;
}
if (!local_queues_sizes[ai]) {
std::copy(
set_L.begin() + local_queues_starts[bi],
set_L.begin() + local_queues_starts[bi] + local_queues_sizes[bi],
set_L.begin() + local_queues_starts[ai]);
local_queues_sizes[ai] = local_queues_sizes[bi];
local_queues_sizes[bi] = 0;
continue;
}
if (ai != 3 + group_start) {
merge_two_queues_into_1st_queue_seq_incr(
set_L,
local_queues_starts[ai],
local_queues_sizes[ai],
local_queue_capacity,
set_L,
local_queues_starts[bi],
local_queues_sizes[bi]);
} else {
idi r = merge_two_queues_into_1st_queue_seq_incr(
set_L,
local_queues_starts[ai],
local_queues_sizes[ai],
master_queue_capacity,
set_L,
local_queues_starts[bi],
local_queues_sizes[bi]);
if (r < nk) {
nk = r;
}
}
local_queues_sizes[bi] = 0;
}
{
const idi bi = 1 + group_start;
const idi ai = 3 + group_start;
if (!local_queues_sizes[bi]) {
return nk;
}
if (!local_queues_sizes[ai]) {
std::copy(
set_L.begin() + local_queues_starts[bi],
set_L.begin() + local_queues_starts[bi] + local_queues_sizes[bi],
set_L.begin() + local_queues_starts[ai]);
local_queues_sizes[ai] = local_queues_sizes[bi];
local_queues_sizes[bi] = 0;
return 0;
}
idi r = merge_two_queues_into_1st_queue_seq_incr(
set_L,
local_queues_starts[ai],
local_queues_sizes[ai],
master_queue_capacity,
set_L,
local_queues_starts[bi],
local_queues_sizes[bi]);
if (r < nk) {
nk = r;
}
local_queues_sizes[bi] = 0;
}
return nk;
}
/*
* Function: used by hierarchical merging idea.
* Merge all queues into the last queue.
* Difference with merge_all_queues_para_array: here the last queue might not have L elements in the beginning,
* so use merge_two_queues_into_1st_queue_seq_incr(), not merge_two_queues_into_1st_queue_seq_fixed().
*/
inline idi Searching::merge_all_queues_to_master(
std::vector<Candidate> &set_L,
const std::vector<idi> &local_queues_starts,
std::vector<idi> &local_queues_sizes,
const idi local_queue_capacity,
const idi local_master_queue_capacity,
const idi master_queue_capacity,
const idi group_size)
{
const idi num_queues = num_threads_;
idi nk = master_queue_capacity;
int size = num_queues;
// 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_capacity;
idi a_start = local_queues_starts[ai];
idi bi = i + (1 << d) - 1; // i + 2^d - 1
// idi b_start = bi * local_queue_capacity;
idi b_start = local_queues_starts[bi];
if (0 == local_queues_sizes[bi]) {
continue;
}
if (local_queues_sizes[ai] == 0) {
std::copy(set_L.begin() + b_start,
set_L.begin() + b_start + local_queues_sizes[bi],
set_L.begin() + a_start); // Copy bi to ai
local_queues_sizes[ai] = local_queues_sizes[bi];
local_queues_sizes[bi] = 0;
continue;
}
if ((group_size - 1) != ai % 4) {
merge_two_queues_into_1st_queue_seq_incr(
set_L,
a_start,
local_queues_sizes[ai],
local_queue_capacity,
set_L,
b_start,
local_queues_sizes[bi]);
} else if (num_queues - 1 != ai) {
merge_two_queues_into_1st_queue_seq_incr(
set_L,
a_start,
local_queues_sizes[ai],
local_master_queue_capacity,
set_L,
b_start,
local_queues_sizes[bi]);
} else {
idi r = merge_two_queues_into_1st_queue_seq_incr(
set_L,
a_start,
local_queues_sizes[ai],
master_queue_capacity,
set_L,
b_start,
local_queues_sizes[bi]);
if (ai == num_queues - 1 && r < nk) {
nk = r;
}
}
// if ((group_size - 1) == ai % 4) {
// idi r = merge_two_queues_into_1st_queue_seq_incr(
// set_L,
// a_start,
// local_queues_sizes[ai],
// master_queue_capacity,
// set_L,
// b_start,
// local_queues_sizes[bi]);
// if (ai == num_queues - 1 && r < nk) {
// nk = r;
// }
// } else {
// merge_two_queues_into_1st_queue_seq_incr(
// set_L,
// a_start,
// local_queues_sizes[ai],
// local_queue_capacity,
// set_L,
// b_start,
// local_queues_sizes[bi]);
// }
// if (ai != num_queues - 1) {
// merge_two_queues_into_1st_queue_seq_incr(
// set_L,
// a_start,
// local_queues_sizes[ai],
// local_queue_capacity,
// set_L,
// b_start,
// local_queues_sizes[bi]);
// } else {
// idi r = merge_two_queues_into_1st_queue_seq_incr(
// set_L,
// a_start,
// local_queues_sizes[ai],
// master_queue_capacity,
// set_L,
// b_start,
// local_queues_sizes[bi]);
// if (r < nk) {
// nk = r;
// }
// }
local_queues_sizes[bi] = 0;
}
}
// Reset local_queues_sizes
// Not do this for Collector Idea or Selecting Idea
// std::fill(local_queues_sizes.begin(), local_queues_sizes.end() - 1, 0);
// std::fill(local_queues_sizes.begin(), local_queues_sizes.end(), 0);
return nk;
}
/*
* Function: distribute master queue's top-M unchecked elements to top_m_candidates.
* Used by hierarchical merging idea.
*/
inline idi Searching::master_top_m_to_groups(
std::vector<Candidate> &set_L,
const std::vector<idi> &local_queues_starts,
std::vector<idi> &local_queues_sizes,
std::vector<idi> &top_m_candidates,
const std::vector<idi> &top_m_candidates_starts,
std::vector<idi> &top_m_candidates_sizes,
const idi k_uc,
idi &last_k,
const idi M,
const idi num_groups)
// const idi group_size)
{
const idi last_queue_start = local_queues_starts[num_threads_ - 1];
idi c_i_start = k_uc + last_queue_start;
idi c_i_bound = last_queue_start + local_queues_sizes[num_threads_ - 1];
idi top_m_count = 0;
for (idi c_i = c_i_start; c_i < c_i_bound && top_m_count < M; ++c_i) {
if (set_L[c_i].is_checked_) {
continue;
}
last_k = c_i - last_queue_start;
set_L[c_i].is_checked_ = true;
idi g_i = top_m_count % num_groups;
++top_m_count;
top_m_candidates[top_m_candidates_starts[g_i] + top_m_candidates_sizes[g_i]++] = set_L[c_i].id_;
}
return top_m_count;
// idi m_i = 0;
// const idi master_start = local_queues_starts[num_threads_ - 1];
// const idi e_i_bound = local_queues_sizes[num_threads_ - 1];
// for (idi e_i = 0; e_i < e_i_bound; ++e_i) {
// idi group_id = e_i % num_groups;
// if (num_groups - 1 == group_id) {
// set_L[master_start + m_i++] = set_L[master_start + e_i];
// } else {
// idi q_id = group_id * group_size + group_size - 1;
// set_L[local_queues_starts[q_id] + local_queues_sizes[q_id]++] = set_L[master_start + e_i];
// }
// }
// local_queues_sizes[num_threads_ - 1] = m_i;
}
/*
* 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);
// }
}
/*
* 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_;
}
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;
}
}
/*
* 7/31/2020-12:48
* Use for profile. Sequential Double-M.
*/
inline void Searching::seq_search_with_top_m_double_m(
const idi M_max,
const idi query_id,
const idi K,
const idi global_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)
{
// time_initialization_ -= WallTimer::get_time_mark();
std::vector<idi> top_m_candidates(M_max);
boost::dynamic_bitset<> is_visited(num_v_);
uint64_t tmp_count_computation = 0;
idi set_L_size;
{// 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.
}
set_L_size = 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
subsearch_with_top_m(
M_max,
query_id,
global_L,
set_L,
0,
set_L_size,
top_m_candidates,
is_visited,
tmp_count_computation);
count_distance_computation_ += tmp_count_computation;
tmp_count_computation = 0;
// time_merge_ -= WallTimer::get_time_mark();
// time_ending_ -= WallTimer::get_time_mark();
// time_merge_ += WallTimer::get_time_mark();
{
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();
// }
// time_ending_ += WallTimer::get_time_mark();
// {//test
// if (3 == query_id) {
// exit(1);
// }
// }
}
/*
* 7/29/2020-17:26
* The same procedure with Middle-M, but do hierarchical merging to reduce merging frequency.
* Right now there are only 3 levels (1 middle level). And 4 workers form a group.
*/
inline void Searching::para_search_with_top_m_hierarchy_merge_v0(
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_capacity, // Maximum size of local queue
const idi local_master_queue_capacity, // Maximum size of local master queue
// const idi base_set_L, // base_set_L = (num_threads_ - 1) * local_queue_length;
const std::vector<idi> &local_queues_starts,
std::vector<idi> &local_queues_sizes, // Sizes of local queue
// std::vector< std::vector<idi> > &top_m_candidates_list, // every group has one top-M queue
std::vector<idi> &top_m_candidates,
const std::vector<idi> &top_m_candidates_starts,
std::vector<idi> &top_m_candidates_sizes,
// std::vector<idi> &top_m_candidates,
boost::dynamic_bitset<> &is_visited,
const idi group_size, // Should be 4
const idi full_merge_freq)
{
// time_initialization_ -= WallTimer::get_time_mark();
// const idi base_set_L = (num_threads_ - 1) * local_queue_length;
const idi master_queue_start = local_queues_starts[num_threads_ - 1];
const idi num_groups = (num_threads_ - 1) / group_size + 1; // 4 workers per group.
const dataf *query_data = queries_load_ + query_id * dimension_;
// Initialization Phase
{
//#pragma omp parallel for
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);
// }
// Get the distances of all candidates, store in the set set_L.
uint64_t tmp_count_computation = 0;
#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 + master_queue_start] = Candidate(v_id, dist, false); // False means not checked.
}
count_distance_computation_ += tmp_count_computation;
// tmp_count_computation = 0;
std::sort(
set_L.begin() + master_queue_start,
set_L.begin() + master_queue_start + L);
local_queues_sizes[num_threads_ - 1] = L;
} // Initialization Phase
// time_initialization_ += WallTimer::get_time_mark();
// idi top_m_candidates_end = 0;
idi iter = 0; // for debug
idi M = 1;
idi k = 0; // Index of first unchecked candidate.
// Sequential Phase
{
uint64_t tmp_count_computation = 0;
while (k < L && M < value_M_middle) {
++iter;
subsearch_top_m_for_one_iteration(
iter,
k,
M,
query_id,
query_data,
L,
set_L,
master_queue_start,
local_queues_sizes[num_threads_ - 1],
top_m_candidates,
is_visited,
tmp_count_computation);
count_distance_computation_ += tmp_count_computation;
tmp_count_computation = 0;
{// Double M
if (M < value_M_max) {
M <<= 1U;
}
}
}
} // Sequential Phase
// if (M < static_cast<idi>(num_threads_)) {
// M = num_threads_;
// }
// Parallel Phase
idi para_iter = 0;
if (num_threads_ <= 4) {
idi top_m_candidates_size = 0;
idi last_k;
idi nk;
uint64_t tmp_count_computation = 0;
while (true) {
// while (k < L) {
++iter;
last_k = L;
// Pick top-M
for (idi c_i = k; c_i < L && top_m_candidates_size < M; ++c_i) {
idi index_set_L = c_i + master_queue_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_size++] = set_L[index_set_L].id_;
}
if (!top_m_candidates_size) {
break;
}
// time_pick_top_m_ += WallTimer::get_time_mark();
nk = L;
// Push M candidates' neighbors into the queue.
#pragma omp parallel for reduction(+ : tmp_count_computation)
for (idi c_i = 0; c_i < top_m_candidates_size; ++c_i) {
int tid = omp_get_thread_num();
idi local_queue_start = local_queues_starts[tid];
idi &local_queue_size = local_queues_sizes[tid];
idi cand_id = top_m_candidates[c_i];
if (num_threads_ - 1 != tid) {
expand_one_candidate(
cand_id,
query_data,
set_L[master_queue_start + L - 1].distance_,
set_L,
local_queue_start,
local_queue_size,
local_queue_capacity,
is_visited,
tmp_count_computation);
} else {
idi r = expand_one_candidate(
cand_id,
query_data,
set_L[master_queue_start + L - 1].distance_,
set_L,
local_queue_start,
local_queue_size,
L,
is_visited,
tmp_count_computation);
if (r < nk) {
nk = r;
}
}
}
top_m_candidates_size = 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_para_array(
set_L,
local_queues_sizes,
local_queue_capacity,
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 <<= 1U;
}
}
}
} else { // 8 threads
bool is_finished = false;
bool is_full_merged = true;
idi M_group;
std::vector<idi> ks(num_groups, 0);
ks[num_groups - 1] = k;
std::vector<idi> nks(num_groups);
std::vector<idi> last_ks(num_groups);
uint64_t tmp_count_distance_computation = 0;
// bool is_finished = false;
while (!is_finished) {
++para_iter;
++iter;
M_group = M / num_groups;
is_finished = true;
if (1 == para_iter || (para_iter - 1) % full_merge_freq) {
// Initialize every group's top-M candidates from the global Master queue
master_top_m_to_groups(
set_L,
local_queues_starts,
local_queues_sizes,
top_m_candidates,
top_m_candidates_starts,
top_m_candidates_sizes,
ks[num_groups - 1],
last_ks[num_groups - 1],
M,
num_groups);
}
#pragma omp parallel for num_threads(num_groups) \
reduction(+ : tmp_count_distance_computation)
for (idi g_i = 0; g_i < num_groups; ++g_i) {
const idi local_master_queue_id = g_i * group_size + group_size - 1;
const idi local_master_queue_start = local_queues_starts[local_master_queue_id];
idi &local_master_queue_size = local_queues_sizes[local_master_queue_id];
idi &k_uc = ks[g_i];
const idi top_m_candidates_start = top_m_candidates_starts[g_i];
idi &top_m_candidates_size = top_m_candidates_sizes[g_i];
idi &last_k = last_ks[g_i];
// Pick top-M
if (1 != para_iter && 0 == (para_iter - 1) % full_merge_freq) {
// if ((para_iter - 1) % full_merge_freq) {
last_k = L;
for (idi c_i = k_uc; c_i < local_master_queue_size && top_m_candidates_size < M_group; ++c_i) {
idi index_set_L = c_i + local_master_queue_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_start + top_m_candidates_size++] = set_L[index_set_L].id_;
}
}
if (!top_m_candidates_size) {
continue;
}
is_finished = false;
idi &nk = nks[g_i];
nk = L;
idi c_i_start = top_m_candidates_starts[g_i];
idi c_i_bound = c_i_start + top_m_candidates_size;
uint64_t tmp_count_distance_computation_ig = 0;
// Expand top-M
#pragma omp parallel for num_threads(group_size) \
reduction(+ : tmp_count_distance_computation_ig)
for (idi c_i = c_i_start; c_i < c_i_bound; ++c_i) {
idi tid_ig = omp_get_thread_num();
idi q_id = g_i * group_size + tid_ig;
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_distance_computation_ig;
distf dist = compute_distance_with_norm(nb_data, query_data, norm);
if (local_master_queue_size == local_master_queue_capacity
&& dist > set_L[local_master_queue_size - 1 + local_master_queue_start].distance_) {
continue;
}
Candidate cand(nb_id, dist, false);
// Add to the local queue.
if (0 != tid_ig) {
// Non-Master threads using local queues
add_into_queue(
set_L,
local_queues_starts[q_id - 1],
local_queues_sizes[q_id - 1],
local_queue_capacity,
cand);
} else if (num_groups - 1 != g_i) {
// Thread 0 but not the last group maintains the local master queue
idi r = add_into_queue(
set_L,
local_master_queue_start,
local_master_queue_size,
local_master_queue_capacity,
cand);
if (r < nk) {
nk = r;
}
} else {
// Thread 0 and the last group maintains the master queue
idi r = add_into_queue(
set_L,
local_master_queue_start,
local_master_queue_size,
L,
cand);
if (r < nk) {
nk = r;
}
}
}
} // Expand in a group
tmp_count_distance_computation += tmp_count_distance_computation_ig;
top_m_candidates_size = 0;
// Merge in a group
if (0 == (para_iter % full_merge_freq)) {
idi r;
if (num_groups - 1 != g_i) {
// Normal group
r = merge_queues_of_four(
set_L,
local_queues_starts,
local_queues_sizes,
g_i,
local_queue_capacity,
local_master_queue_capacity);
} else {
// The group contains the master queue
r = merge_queues_of_four(
set_L,
local_queues_starts,
local_queues_sizes,
g_i,
local_queue_capacity,
L);
}
if (r < nk) {
nk = r;
}
if (nk <= last_k) {
k_uc = nk;
} else {
k_uc = last_k + 1;
}
}
} // Middle Level Parallelism
count_distance_computation_ += tmp_count_distance_computation;
tmp_count_distance_computation = 0;
// Do full merge and distribute
if (!is_finished && para_iter % full_merge_freq) {
// Full merge
idi r = merge_all_queues_to_master(
set_L,
local_queues_starts,
local_queues_sizes,
local_queue_capacity,
local_master_queue_capacity,
L,
group_size);
is_full_merged = true;
idi &nk = nks[num_groups - 1];
idi &k_uc = ks[num_groups - 1];
idi &last_k = last_ks[num_groups - 1];
if (r < nk) {
nk = r;
}
if (nk <= last_k) {
k_uc = nk;
} else {
k_uc = last_k + 1;
}
} else {
is_full_merged = false;
}
{// Scale M
if (M < value_M_max) {
M <<= 1U;
}
}
} // Iteration
if (!is_full_merged) {
merge_all_queues_to_master(
set_L,
local_queues_sizes,
local_queues_sizes,
local_queue_capacity,
local_master_queue_capacity,
L,
group_size);
}
}
#pragma omp parallel for
for (idi k_i = 0; k_i < K; ++k_i) {
set_K[k_i] = set_L[k_i + master_queue_start].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_sizes.begin(), local_queues_sizes.end(), 0);
}
// {//test
// if (14 == query_id) {
// exit(1);
// }
// }
}
/*
* Function: expand a candidate, visiting its neighbors.
* Return the lowest adding location.
*/
inline idi Searching::expand_one_candidate(
idi cand_id,
const dataf *query_data,
const distf &dist_bound,
std::vector<Candidate> &set_L,
const idi local_queue_start,
idi &local_queue_size,
const idi &local_queue_capacity,
boost::dynamic_bitset<> &is_visited,
// const idi nk_init,
uint64_t &local_count_computation)
{
// _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();
idi nk = local_queue_capacity;
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_computation;
distf dist = compute_distance_with_norm(nb_data, query_data, norm);
if (dist > dist_bound) {
// if (dist > set_L[L - 1 + master_queue_start].distance_) {
continue;
}
Candidate cand(nb_id, dist, false);
// Add to the local queue.
idi r = add_into_queue(
set_L,
local_queue_start,
local_queue_size,
local_queue_capacity,
cand);
if (r < nk) {
nk = r;
}
}
return nk;
}
/*
* 8/6/2020-11:58
* Based on Middle-4, but reduce full merge frequency.
* Actually, this is local Searching, not Less Synchronization.
*/
inline void Searching::para_search_with_top_m_less_sync_v0(
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_capacity, // Maximum size of local queue
const std::vector<idi> &local_queues_starts,
std::vector<idi> &local_queues_sizes, // Sizes of local queue
std::vector<idi> &top_m_candidates,
boost::dynamic_bitset<> &is_visited,
const idi full_merge_freq,
const idi local_iter_bound)
{
const idi master_queue_start = local_queues_starts[num_threads_ - 1];
const dataf *query_data = queries_load_ + query_id * dimension_;
// Initialization Phase
{
//#pragma omp parallel for
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);
// }
// Get the distances of all candidates, store in the set set_L.
uint64_t tmp_count_computation = 0;
#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 + master_queue_start] = Candidate(v_id, dist, false); // False means not checked.
}
count_distance_computation_ += tmp_count_computation;
// tmp_count_computation = 0;
std::sort(
set_L.begin() + master_queue_start,
set_L.begin() + master_queue_start + L);
local_queues_sizes[num_threads_ - 1] = L;
} // Initialization Phase
idi iter = 0; // for debug
idi M = 1;
idi k = 0; // Index of first unchecked candidate.
// Sequential Phase
{
uint64_t tmp_count_computation = 0;
while (k < L && M < value_M_middle) {
++iter;
subsearch_top_m_for_one_iteration(
iter,
k,
M,
query_id,
query_data,
L,
set_L,
master_queue_start,
local_queues_sizes[num_threads_ - 1],
top_m_candidates,
is_visited,
tmp_count_computation);
count_distance_computation_ += tmp_count_computation;
tmp_count_computation = 0;
{// Double M
if (M < value_M_max) {
M <<= 1U;
}
}
}
} // Sequential Phase
// if (M < static_cast<idi>(num_threads_)) {
// M = num_threads_;
// }
// Parallel Phase
idi para_iter = 0;
idi top_m_candidates_size = 0;
idi last_k;
idi nk;
uint64_t tmp_count_computation = 0;
while (true) {
// while (k < L) {
++para_iter;
++iter;
last_k = L;
// Pick top-M
for (idi c_i = k; c_i < L && top_m_candidates_size < M; ++c_i) {
idi index_set_L = c_i + master_queue_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_size++] = set_L[index_set_L].id_;
}
if (!top_m_candidates_size) {
break;
}
nk = L;
// Expand
//#pragma omp parallel for reduction(+ : tmp_count_computation)
#pragma omp parallel reduction(+ : tmp_count_computation)
{
#pragma omp for nowait
for (idi c_i = 0; c_i < top_m_candidates_size; ++c_i) {
int tid = omp_get_thread_num();
idi local_queue_start = local_queues_starts[tid];
idi &local_queue_size = local_queues_sizes[tid];
idi cand_id = top_m_candidates[c_i];
if (num_threads_ - 1 != tid) {
expand_one_candidate(
cand_id,
query_data,
set_L[master_queue_start + L - 1].distance_,
set_L,
local_queue_start,
local_queue_size,
local_queue_capacity,
is_visited,
tmp_count_computation);
} else {
idi r = expand_one_candidate(
cand_id,
query_data,
set_L[master_queue_start + L - 1].distance_,
set_L,
local_queue_start,
local_queue_size,
L,
is_visited,
tmp_count_computation);
if (r < nk) {
nk = r;
}
}
} // Expand
if (0 == (para_iter % full_merge_freq)) {
// Local search iterations
int q_i = omp_get_thread_num();
idi local_queue_start = local_queues_starts[q_i];
idi &local_queue_size = local_queues_sizes[q_i];
const idi queue_capacity = (num_threads_ - 1 != q_i) ? local_queue_capacity : L;
idi tmp_k;
if (num_threads_ - 1 != q_i) {
tmp_k = 0;
} else {
if (nk <= last_k) {
tmp_k = nk;
} else {
tmp_k = last_k + 1;
}
}
// if (tmp_k >= local_queue_size) {
// continue;
// }
idi i_t = 0;
idi cand_id;
while (tmp_k < local_queue_size) {
idi r;
if (!set_L[local_queue_start + tmp_k].is_checked_) {
set_L[local_queue_start + tmp_k].is_checked_ = true;
cand_id = set_L[local_queue_start + tmp_k].id_;
// Expand
r = expand_one_candidate(
cand_id,
query_data,
set_L[master_queue_start + L - 1].distance_,
set_L,
local_queue_start,
local_queue_size,
queue_capacity,
is_visited,
tmp_count_computation);
if (++i_t == local_iter_bound) {
break;
}
} else {
r = queue_capacity;
}
if (r <= tmp_k) {
tmp_k = r;
} else {
++tmp_k;
}
}
} // Local Search
} // OMP Parallel Construct
top_m_candidates_size = 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_para_array(
set_L,
local_queues_sizes,
local_queue_capacity,
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 <<= 1U;
}
}
}
#pragma omp parallel for
for (idi k_i = 0; k_i < K; ++k_i) {
set_K[k_i] = set_L[k_i + master_queue_start].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_sizes.begin(), local_queues_sizes.end(), 0);
}
// {//test
// if (14 == query_id) {
// exit(1);
// }
// }
}
} // namespace PANNS
#endif //BATCH_SEARCHING_SEARCHING_H
|
mlp_example_bf16_amx_numa.c | /******************************************************************************
* Copyright (c) Intel Corporation - All rights reserved. *
* This file is part of the LIBXSMM library. *
* *
* For information on the license, see the LICENSE file. *
* Further information: https://github.com/hfp/libxsmm/ *
* SPDX-License-Identifier: BSD-3-Clause *
******************************************************************************/
/* Evangelos Georganas, Alexander Heinecke (Intel Corp.)
******************************************************************************/
#include <libxsmm.h>
#include <libxsmm_sync.h>
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <math.h>
#if defined(_OPENMP)
# include <omp.h>
#endif
#include <numa.h>
/* include c-based dnn library */
#include "../common/dnn_common.h"
#define CHECK_L1
#define OVERWRITE_DOUTPUT_BWDUPD
#define _mm512_load_fil(A) _mm512_castsi512_ps(_mm512_slli_epi32(_mm512_cvtepi16_epi32(_mm256_loadu_si256((__m256i*)(A))),16))
#define _mm512_store_fil(A,B) _mm256_storeu_si256((__m256i*)(A), (__m256i)_mm512_cvtneps_pbh((B)))
LIBXSMM_INLINE void my_init_buf(float* buf, size_t size, int initPos, int initOne)
{
int i;
zero_buf(buf, size);
for (i = 0; i < (int)size; ++i) {
buf[i] = (float)((initOne != 0) ? 1.0 : ((initPos != 0) ? libxsmm_rng_f64() : (0.05 - libxsmm_rng_f64()/10.0)));
}
}
LIBXSMM_INLINE void my_init_buf_bf16(libxsmm_bfloat16* buf, size_t size, int initPos, int initOne)
{
int i;
zero_buf_bf16(buf, size);
for (i = 0; i < (int)size; ++i) {
libxsmm_bfloat16_hp tmp;
tmp.f = (float)((initOne != 0) ? 1.0 : ((initPos != 0) ? libxsmm_rng_f64() : (0.05 - libxsmm_rng_f64()/10.0)));
buf[i] = tmp.i[1];
}
}
#if 0
LIBXSMM_INLINE void my_matrix_copy_KCCK_to_KCCK_vnni(float *src, float *dst, int C, int K, int bc, int bk)
{
int k1, k2, c1, c2;
int kBlocks = K/bk;
int cBlocks = C/bc;
LIBXSMM_VLA_DECL(4, float, real_src, src, cBlocks, bc, bk);
LIBXSMM_VLA_DECL(5, float, real_dst, dst, cBlocks, bc/2, bk, 2);
for (k1 = 0; k1 < kBlocks; k1++) {
for (c1 = 0; c1 < cBlocks; c1++) {
for (c2 = 0; c2 < bc; c2++) {
for (k2 = 0; k2 < bk; k2++) {
LIBXSMM_VLA_ACCESS(5, real_dst, k1, c1, c2/2, k2, c2%2, cBlocks, bc/2, bk, 2) = LIBXSMM_VLA_ACCESS(4, real_src, k1, c1, c2, k2, cBlocks, bc, bk);
}
}
}
}
}
#endif
typedef enum my_eltwise_fuse {
MY_ELTWISE_FUSE_NONE = 0,
MY_ELTWISE_FUSE_BIAS = 1,
MY_ELTWISE_FUSE_RELU = 2,
MY_ELTWISE_FUSE_BIAS_RELU = MY_ELTWISE_FUSE_BIAS | MY_ELTWISE_FUSE_RELU
} my_eltwise_fuse;
typedef enum my_pass {
MY_PASS_FWD = 1,
MY_PASS_BWD_D = 2,
MY_PASS_BWD_W = 4,
MY_PASS_BWD = 6
} my_pass;
typedef struct my_opt_config {
libxsmm_blasint C;
libxsmm_blasint K;
libxsmm_blasint bc;
libxsmm_blasint bk;
libxsmm_blasint threads;
float lr;
size_t scratch_size;
libxsmm_barrier* barrier;
} my_opt_config;
typedef struct my_smax_fwd_config {
libxsmm_blasint N;
libxsmm_blasint C;
libxsmm_blasint bn;
libxsmm_blasint bc;
libxsmm_blasint threads;
size_t scratch_size;
libxsmm_barrier* barrier;
} my_smax_fwd_config;
typedef struct my_smax_bwd_config {
libxsmm_blasint N;
libxsmm_blasint C;
libxsmm_blasint bn;
libxsmm_blasint bc;
libxsmm_blasint threads;
size_t scratch_size;
float loss_weight;
libxsmm_barrier* barrier;
} my_smax_bwd_config;
typedef struct my_fc_fwd_config {
libxsmm_blasint N;
libxsmm_blasint C;
libxsmm_blasint K;
libxsmm_blasint bn;
libxsmm_blasint bc;
libxsmm_blasint bk;
libxsmm_blasint threads;
my_eltwise_fuse fuse_type;
libxsmm_blasint fwd_bf;
libxsmm_blasint fwd_2d_blocking;
libxsmm_blasint fwd_col_teams;
libxsmm_blasint fwd_row_teams;
size_t scratch_size;
libxsmm_barrier* barrier;
libxsmm_bsmmfunction fwd_config_kernel;
libxsmm_bsmmfunction tilerelease_kernel;
libxsmm_bsmmfunction_reducebatch_strd gemm_fwd;
libxsmm_bsmmfunction_reducebatch_strd gemm_fwd2;
libxsmm_bmmfunction_reducebatch_strd gemm_fwd3;
libxsmm_bmmfunction_reducebatch_strd_meltwfused gemm_fwd4;
libxsmm_bmmfunction_reducebatch_strd_meltwfused gemm_fwd5;
libxsmm_bmmfunction_reducebatch_strd_meltwfused gemm_fwd6;
libxsmm_bmmfunction_reducebatch_strd_meltwfused gemm_fwd7;
libxsmm_bmmfunction_reducebatch_strd_meltwfused gemm_fwd8;
libxsmm_meltwfunction_cvtfp32bf16 fwd_cvtfp32bf16_kernel;
libxsmm_meltwfunction_cvtfp32bf16_act fwd_cvtfp32bf16_relu_kernel;
libxsmm_meltwfunction_act_cvtfp32bf16 fwd_sigmoid_cvtfp32bf16_kernel;
libxsmm_meltwfunction_copy fwd_zero_kernel;
libxsmm_meltwfunction_copy fwd_copy_bf16fp32_kernel;
libxsmm_meltwfunction_copy fwd_colbcast_bf16fp32_copy_kernel;
} my_fc_fwd_config;
typedef struct my_fc_bwd_config {
libxsmm_blasint N;
libxsmm_blasint C;
libxsmm_blasint K;
libxsmm_blasint bn;
libxsmm_blasint bc;
libxsmm_blasint bk;
libxsmm_blasint threads;
my_eltwise_fuse fuse_type;
libxsmm_blasint bwd_bf;
libxsmm_blasint bwd_2d_blocking;
libxsmm_blasint bwd_col_teams;
libxsmm_blasint bwd_row_teams;
libxsmm_blasint upd_bf;
libxsmm_blasint upd_2d_blocking;
libxsmm_blasint upd_col_teams;
libxsmm_blasint upd_row_teams;
libxsmm_blasint ifm_subtasks;
libxsmm_blasint ofm_subtasks;
size_t scratch_size;
size_t doutput_scratch_mark;
libxsmm_barrier* barrier;
libxsmm_bsmmfunction bwd_config_kernel;
libxsmm_bsmmfunction upd_config_kernel;
libxsmm_bsmmfunction tilerelease_kernel;
libxsmm_bsmmfunction_reducebatch_strd gemm_bwd;
libxsmm_bsmmfunction_reducebatch_strd gemm_bwd2;
libxsmm_bmmfunction_reducebatch_strd gemm_bwd3;
libxsmm_bsmmfunction_reducebatch_strd gemm_upd;
libxsmm_bsmmfunction_reducebatch_strd gemm_upd2;
libxsmm_bmmfunction_reducebatch_strd gemm_upd3;
libxsmm_meltwfunction_cvtfp32bf16 bwd_cvtfp32bf16_kernel;
libxsmm_meltwfunction_cvtfp32bf16 upd_cvtfp32bf16_kernel;
libxsmm_meltwfunction_relu bwd_relu_kernel;
libxsmm_meltwfunction_copy bwd_zero_kernel;
libxsmm_meltwfunction_copy upd_zero_kernel;
libxsmm_meltwfunction_reduce delbias_reduce_kernel;
libxsmm_meltwfunction_transform vnni_to_vnniT_kernel;
libxsmm_meltwfunction_transform norm_to_normT_kernel;
libxsmm_meltwfunction_transform norm_to_vnni_kernel;
} my_fc_bwd_config;
typedef struct my_numa_thr_cfg {
int thr_s;
int thr_e;
int *blocksOFm_s;
int *blocksOFm_e;
int *blocksIFm_s;
int *blocksIFm_e;
libxsmm_bfloat16 **scratch;
size_t *layer_size;
libxsmm_bfloat16 **bwd_d_scratch;
size_t *bwd_d_layer_size;
libxsmm_bfloat16 **bwd_w_scratch;
size_t *bwd_w_layer_size;
} my_numa_thr_cfg;
my_fc_fwd_config setup_my_fc_fwd(libxsmm_blasint N, libxsmm_blasint C, libxsmm_blasint K, libxsmm_blasint bn,
libxsmm_blasint bc, libxsmm_blasint bk, libxsmm_blasint threads, my_eltwise_fuse fuse_type) {
my_fc_fwd_config res;
libxsmm_blasint lda = bk;
libxsmm_blasint ldb = bc;
libxsmm_blasint ldc = bk;
libxsmm_blasint ld_zero = bk*bn;
libxsmm_blasint ld_upconvert = K;
float alpha = 1.0f;
float beta = 1.0f;
float zerobeta = 0.0f;
libxsmm_meltw_flags fusion_flags;
int l_flags, l_tc_flags;
int l_tr_flags = LIBXSMM_GEMM_FLAG_NO_SETUP_TILECONFIG | ( LIBXSMM_GEMM_VNNI_FLAGS('N', 'N', 'V', 'N') );
libxsmm_blasint unroll_hint;
/* setting up some handle values */
res.N = N;
res.C = C;
res.K = K;
res.bn = bn;
res.bc = bc;
res.bk = bk;
res.threads = threads;
res.fuse_type = fuse_type;
/* setup parallelization strategy */
if (threads == 16) {
res.fwd_bf = 1;
res.fwd_2d_blocking = 1;
res.fwd_col_teams = 2;
res.fwd_row_teams = 8;
} else {
res.fwd_bf = 1;
res.fwd_2d_blocking = 0;
res.fwd_col_teams = 1;
res.fwd_row_teams = 1;
}
#if 0
res.fwd_bf = atoi(getenv("FWD_BF"));
res.fwd_2d_blocking = atoi(getenv("FWD_2D_BLOCKING"));
res.fwd_col_teams = atoi(getenv("FWD_COL_TEAMS"));
res.fwd_row_teams = atoi(getenv("FWD_ROW_TEAMS"));
#endif
/* setting up the barrier */
res.barrier = libxsmm_barrier_create(threads, 1);
/* TPP creation */
l_flags = ( LIBXSMM_GEMM_VNNI_FLAGS('N', 'N', 'V', 'N') ) | LIBXSMM_GEMM_FLAG_NO_RESET_TILECONFIG | LIBXSMM_GEMM_FLAG_NO_SETUP_TILECONFIG;
l_tc_flags = LIBXSMM_GEMM_FLAG_NO_RESET_TILECONFIG | ( LIBXSMM_GEMM_VNNI_FLAGS('N', 'N', 'V', 'N') );
unroll_hint = (res.C/res.bc)/res.fwd_bf;
res.fwd_config_kernel = libxsmm_bsmmdispatch(res.bk, res.bn, res.bc, &lda, &ldb, &ldc, NULL, &beta, &l_tc_flags, NULL);
if ( res.fwd_config_kernel == NULL ) {
fprintf( stderr, "JIT for BRGEMM TPP fwd_config_kernel failed. Bailing...!\n");
exit(-1);
}
res.gemm_fwd = libxsmm_bsmmdispatch_reducebatch_strd_unroll(res.bk, res.bn, res.bc, res.bk*res.bc*sizeof(libxsmm_bfloat16), res.bc*res.bn*sizeof(libxsmm_bfloat16), unroll_hint, &lda, &ldb, &ldc, &alpha, &beta, &l_flags, NULL);
if ( res.gemm_fwd == NULL ) {
fprintf( stderr, "JIT for BRGEMM TPP gemm_fwd failed. Bailing...!\n");
exit(-1);
}
res.gemm_fwd2 = libxsmm_bsmmdispatch_reducebatch_strd_unroll(res.bk, res.bn, res.bc, res.bk*res.bc*sizeof(libxsmm_bfloat16), res.bc*res.bn*sizeof(libxsmm_bfloat16), unroll_hint, &lda, &ldb, &ldc, &alpha, &zerobeta, &l_flags, NULL);
if ( res.gemm_fwd2 == NULL ) {
fprintf( stderr, "JIT for BRGEMM TPP gemm_fwd2 failed. Bailing...!\n");
exit(-1);
}
res.gemm_fwd3 = libxsmm_bmmdispatch_reducebatch_strd_unroll(res.bk, res.bn, res.bc, res.bk*res.bc*sizeof(libxsmm_bfloat16), res.bc*res.bn*sizeof(libxsmm_bfloat16), unroll_hint, &lda, &ldb, &ldc, &alpha, &zerobeta, &l_flags, NULL);
if ( res.gemm_fwd3 == NULL ) {
fprintf( stderr, "JIT for BRGEMM TPP gemm_fwd3 failed. Bailing...!\n");
exit(-1);
}
fusion_flags = LIBXSMM_MELTW_FLAG_COLBIAS_OVERWRITE_C;
res.gemm_fwd4 = libxsmm_bmmdispatch_reducebatch_strd_meltwfused_unroll(res.bk, res.bn, res.bc, res.bk*res.bc*sizeof(libxsmm_bfloat16), res.bc*res.bn*sizeof(libxsmm_bfloat16), unroll_hint, &lda, &ldb, &ldc, &alpha, &zerobeta, &l_flags, NULL, LIBXSMM_MELTW_OPERATION_COLBIAS_ACT, LIBXSMM_DATATYPE_F32, fusion_flags, 0, 0, 0, 0);
if ( res.gemm_fwd4 == NULL ) {
fprintf( stderr, "JIT for BRGEMM TPP gemm_fwd4 failed. Bailing...!\n");
exit(-1);
}
fusion_flags = LIBXSMM_MELTW_FLAG_ACT_RELU_OVERWRITE_C;
res.gemm_fwd5 = libxsmm_bmmdispatch_reducebatch_strd_meltwfused_unroll(res.bk, res.bn, res.bc, res.bk*res.bc*sizeof(libxsmm_bfloat16), res.bc*res.bn*sizeof(libxsmm_bfloat16), unroll_hint, &lda, &ldb, &ldc, &alpha, &zerobeta, &l_flags, NULL, LIBXSMM_MELTW_OPERATION_COLBIAS_ACT, LIBXSMM_DATATYPE_F32, fusion_flags, 0, 0, 0, 0);
if ( res.gemm_fwd5 == NULL ) {
fprintf( stderr, "JIT for BRGEMM TPP gemm_fwd5 failed. Bailing...!\n");
exit(-1);
}
fusion_flags = LIBXSMM_MELTW_FLAG_ACT_SIGM_OVERWRITE_C;
res.gemm_fwd6 = libxsmm_bmmdispatch_reducebatch_strd_meltwfused_unroll(res.bk, res.bn, res.bc, res.bk*res.bc*sizeof(libxsmm_bfloat16), res.bc*res.bn*sizeof(libxsmm_bfloat16), unroll_hint, &lda, &ldb, &ldc, &alpha, &zerobeta, &l_flags, NULL, LIBXSMM_MELTW_OPERATION_COLBIAS_ACT, LIBXSMM_DATATYPE_F32, fusion_flags, 0, 0, 0, 0);
if ( res.gemm_fwd6 == NULL ) {
fprintf( stderr, "JIT for BRGEMM TPP gemm_fwd6 failed. Bailing...!\n");
exit(-1);
}
fusion_flags = LIBXSMM_MELTW_FLAG_COLBIAS_ACT_RELU_OVERWRITE_C;
res.gemm_fwd7 = libxsmm_bmmdispatch_reducebatch_strd_meltwfused_unroll(res.bk, res.bn, res.bc, res.bk*res.bc*sizeof(libxsmm_bfloat16), res.bc*res.bn*sizeof(libxsmm_bfloat16), unroll_hint, &lda, &ldb, &ldc, &alpha, &zerobeta, &l_flags, NULL, LIBXSMM_MELTW_OPERATION_COLBIAS_ACT, LIBXSMM_DATATYPE_F32, fusion_flags, 0, 0, 0, 0);
if ( res.gemm_fwd7 == NULL ) {
fprintf( stderr, "JIT for BRGEMM TPP gemm_fwd7 failed. Bailing...!\n");
exit(-1);
}
fusion_flags = LIBXSMM_MELTW_FLAG_COLBIAS_ACT_SIGM_OVERWRITE_C;
res.gemm_fwd8 = libxsmm_bmmdispatch_reducebatch_strd_meltwfused_unroll(res.bk, res.bn, res.bc, res.bk*res.bc*sizeof(libxsmm_bfloat16), res.bc*res.bn*sizeof(libxsmm_bfloat16), unroll_hint, &lda, &ldb, &ldc, &alpha, &zerobeta, &l_flags, NULL, LIBXSMM_MELTW_OPERATION_COLBIAS_ACT, LIBXSMM_DATATYPE_F32, fusion_flags, 0, 0, 0, 0);
if ( res.gemm_fwd8 == NULL ) {
fprintf( stderr, "JIT for BRGEMM TPP gemm_fwd8 failed. Bailing...!\n");
exit(-1);
}
/* Also JIT eltwise TPPs... */
res.fwd_cvtfp32bf16_kernel = libxsmm_dispatch_meltw_cvtfp32bf16(res.bk, res.bn, &ldc, &ldc, LIBXSMM_DATATYPE_F32, LIBXSMM_DATATYPE_BF16, LIBXSMM_MELTW_FLAG_CVT_NONE);
if ( res.fwd_cvtfp32bf16_kernel == NULL ) {
fprintf( stderr, "JIT for TPP fwd_cvtfp32bf16_kernel failed. Bailing...!\n");
exit(-1);
}
res.fwd_cvtfp32bf16_relu_kernel = libxsmm_dispatch_meltw_cvtfp32bf16_act(res.bk, res.bn, &ldc, &ldc, LIBXSMM_DATATYPE_F32, LIBXSMM_DATATYPE_BF16, LIBXSMM_MELTW_FLAG_CVTA_FUSE_RELU, 0);
if ( res.fwd_cvtfp32bf16_relu_kernel == NULL ) {
fprintf( stderr, "JIT for TPP fwd_cvtfp32bf16_relu_kernel failed. Bailing...!\n");
exit(-1);
}
res.fwd_sigmoid_cvtfp32bf16_kernel = libxsmm_dispatch_meltw_act_cvtfp32bf16(res.bk, res.bn, &ldc, &ldc, LIBXSMM_DATATYPE_F32, LIBXSMM_DATATYPE_BF16, LIBXSMM_MELTW_FLAG_ACVT_FUSE_SIGM, 0);
if ( res.fwd_sigmoid_cvtfp32bf16_kernel == NULL ) {
fprintf( stderr, "JIT for TPP fwd_sigmoid_cvtfp32bf16_kernel failed. Bailing...!\n");
exit(-1);
}
res.tilerelease_kernel = libxsmm_bsmmdispatch(res.bk, res.bk, res.bk, NULL, NULL, NULL, NULL, NULL, &l_tr_flags, NULL);
if ( res.tilerelease_kernel == NULL ) {
fprintf( stderr, "JIT for TPP tilerelease_kernel failed. Bailing...!\n");
exit(-1);
}
res.fwd_zero_kernel = libxsmm_dispatch_meltw_copy(bn*bk, 1, &ld_zero, &ld_zero, LIBXSMM_DATATYPE_F32, LIBXSMM_DATATYPE_F32, LIBXSMM_MELTW_FLAG_COPY_ZERO);
if ( res.fwd_zero_kernel == NULL ) {
fprintf( stderr, "JIT for TPP fwd_zero_kernel failed. Bailing...!\n");
exit(-1);
}
res.fwd_colbcast_bf16fp32_copy_kernel = libxsmm_dispatch_meltw_copy(bk, bn, &ldc, &ldc, LIBXSMM_DATATYPE_BF16, LIBXSMM_DATATYPE_F32, LIBXSMM_MELTW_FLAG_COPY_COLBCAST);
if ( res.fwd_colbcast_bf16fp32_copy_kernel == NULL ) {
fprintf( stderr, "JIT for TPP fwd_colbcast_bf16fp32_copy_kernel failed. Bailing...!\n");
exit(-1);
}
res.fwd_copy_bf16fp32_kernel = libxsmm_dispatch_meltw_copy(K, 1, &ld_upconvert, &ld_upconvert, LIBXSMM_DATATYPE_BF16, LIBXSMM_DATATYPE_F32, LIBXSMM_MELTW_FLAG_COPY_NONE);
if ( res.fwd_copy_bf16fp32_kernel == NULL ) {
fprintf( stderr, "JIT for TPP fwd_copy_bf16fp32_kernel failed. Bailing...!\n");
exit(-1);
}
/* init scratch */
res.scratch_size = sizeof(float) * LIBXSMM_MAX(res.K * res.N, res.threads * LIBXSMM_MAX(res.bk * res.bn, res.K));
return res;
}
my_fc_bwd_config setup_my_fc_bwd(libxsmm_blasint N, libxsmm_blasint C, libxsmm_blasint K, libxsmm_blasint bn,
libxsmm_blasint bc, libxsmm_blasint bk, libxsmm_blasint threads, my_eltwise_fuse fuse_type) {
my_fc_bwd_config res;
libxsmm_blasint lda = bk;
libxsmm_blasint ldb = bc;
libxsmm_blasint ldc = bk;
libxsmm_blasint ld_zero_bwd = bc*bn;
libxsmm_blasint ld_zero_upd = bk;
libxsmm_blasint delbias_K = K;
libxsmm_blasint delbias_N = N;
float alpha = 1.0f;
float beta = 1.0f;
float zerobeta = 0.0f;
libxsmm_blasint updM;
libxsmm_blasint updN;
int l_flags, l_tc_flags;
int l_tr_flags = LIBXSMM_GEMM_FLAG_NO_SETUP_TILECONFIG | ( LIBXSMM_GEMM_VNNI_FLAGS('N', 'N', 'V', 'N') );
libxsmm_blasint unroll_hint;
size_t size_bwd_scratch;
size_t size_upd_scratch;
libxsmm_blasint bbk;
libxsmm_blasint bbc;
libxsmm_meltw_transform_flags trans_flags;
libxsmm_blasint ldaT = bc;
libxsmm_blasint ldb_orig= bc;
/* setting up some handle values */
res.N = N;
res.C = C;
res.K = K;
res.bn = bn;
res.bc = bc;
res.bk = bk;
res.threads = threads;
res.fuse_type = fuse_type;
/* setup parallelization strategy */
if (threads == 16) {
res.bwd_bf = 1;
res.bwd_2d_blocking = 1;
res.bwd_col_teams = 2;
res.bwd_row_teams = 8;
res.upd_bf = 1;
res.upd_2d_blocking = 0;
res.upd_col_teams = 1;
res.upd_row_teams = 1;
res.ifm_subtasks = 1;
res.ofm_subtasks = 1;
} else {
res.bwd_bf = 1;
res.bwd_2d_blocking = 0;
res.bwd_col_teams = 1;
res.bwd_row_teams = 1;
res.upd_bf = 1;
res.upd_2d_blocking = 0;
res.upd_col_teams = 1;
res.upd_row_teams = 1;
res.ifm_subtasks = 1;
res.ofm_subtasks = 1;
}
bbk = (res.upd_2d_blocking == 1) ? bk : bk/res.ofm_subtasks;
bbc = (res.upd_2d_blocking == 1) ? bc : bc/res.ifm_subtasks;
#if 0
res.bwd_bf = atoi(getenv("BWD_BF"));
res.bwd_2d_blocking = atoi(getenv("BWD_2D_BLOCKING"));
res.bwd_col_teams = atoi(getenv("BWD_COL_TEAMS"));
res.bwd_row_teams = atoi(getenv("BWD_ROW_TEAMS"));
res.upd_bf = atoi(getenv("UPD_BF"));
res.upd_2d_blocking = atoi(getenv("UPD_2D_BLOCKING"));
res.upd_col_teams = atoi(getenv("UPD_COL_TEAMS"));
res.upd_row_teams = atoi(getenv("UPD_ROW_TEAMS"));
res.ifm_subtasks = atoi(getenv("IFM_SUBTASKS"));
res.ofm_subtasks = atoi(getenv("OFM_SUBTASKS"));
#endif
/* setting up the barrier */
res.barrier = libxsmm_barrier_create(threads, 1);
/* TPP creation */
/* BWD GEMM */
l_flags = ( LIBXSMM_GEMM_VNNI_FLAGS('N', 'N', 'V', 'N') ) | LIBXSMM_GEMM_FLAG_NO_RESET_TILECONFIG | LIBXSMM_GEMM_FLAG_NO_SETUP_TILECONFIG;
l_tc_flags = LIBXSMM_GEMM_FLAG_NO_RESET_TILECONFIG | ( LIBXSMM_GEMM_VNNI_FLAGS('N', 'N', 'V', 'N') );
unroll_hint = (res.K/res.bk)/res.bwd_bf;
res.gemm_bwd = libxsmm_bsmmdispatch_reducebatch_strd_unroll(res.bc, res.bn, res.bk, res.bk*res.bc*sizeof(libxsmm_bfloat16), res.bk*res.bn*sizeof(libxsmm_bfloat16), unroll_hint, &ldb, &lda, &ldb, &alpha, &beta, &l_flags, NULL);
if ( res.gemm_bwd == NULL ) {
fprintf( stderr, "JIT for BRGEMM TPP gemm_bwd failed. Bailing...!\n");
exit(-1);
}
res.gemm_bwd2 = libxsmm_bsmmdispatch_reducebatch_strd_unroll(res.bc, res.bn, res.bk, res.bk*res.bc*sizeof(libxsmm_bfloat16), res.bk*res.bn*sizeof(libxsmm_bfloat16), unroll_hint, &ldb, &lda, &ldb, &alpha, &zerobeta, &l_flags, NULL);
if ( res.gemm_bwd2 == NULL ) {
fprintf( stderr, "JIT for BRGEMM TPP gemm_bwd2 failed. Bailing...!\n");
exit(-1);
}
res.gemm_bwd3 = libxsmm_bmmdispatch_reducebatch_strd_unroll(res.bc, res.bn, res.bk, res.bk*res.bc*sizeof(libxsmm_bfloat16), res.bk*res.bn*sizeof(libxsmm_bfloat16), unroll_hint, &ldb, &lda, &ldb, &alpha, &zerobeta, &l_flags, NULL);
if ( res.gemm_bwd3 == NULL ) {
fprintf( stderr, "JIT for BRGEMM TPP gemm_bwd3 failed. Bailing...!\n");
exit(-1);
}
res.bwd_config_kernel = libxsmm_bsmmdispatch(res.bc, res.bn, res.bk, &ldb, &lda, &ldb, NULL, &beta, &l_tc_flags, NULL);
if ( res.bwd_config_kernel == NULL ) {
fprintf( stderr, "JIT for BRGEMM TPP bwd_config_kernel failed. Bailing...!\n");
exit(-1);
}
/* Also JIT eltwise TPPs... */
res.bwd_cvtfp32bf16_kernel = libxsmm_dispatch_meltw_cvtfp32bf16(res.bc, res.bn, &ldb, &ldb, LIBXSMM_DATATYPE_F32, LIBXSMM_DATATYPE_BF16, LIBXSMM_MELTW_FLAG_CVT_NONE);
if ( res.bwd_cvtfp32bf16_kernel == NULL ) {
fprintf( stderr, "JIT for TPP bwd_cvtfp32bf16_kernel failed. Bailing...!\n");
exit(-1);
}
res.bwd_relu_kernel = libxsmm_dispatch_meltw_relu(res.bc, res.bn, &ldb, &ldb, LIBXSMM_DATATYPE_BF16, LIBXSMM_DATATYPE_BF16, LIBXSMM_MELTW_FLAG_RELU_BWD, 0);
if ( res.bwd_relu_kernel == NULL ) {
fprintf( stderr, "JIT for TPP bwd_relu_kernel failed. Bailing...!\n");
exit(-1);
}
res.bwd_zero_kernel = libxsmm_dispatch_meltw_copy(bn*bc, 1, &ld_zero_bwd, &ld_zero_bwd, LIBXSMM_DATATYPE_F32, LIBXSMM_DATATYPE_F32, LIBXSMM_MELTW_FLAG_COPY_ZERO);
if ( res.bwd_zero_kernel == NULL ) {
fprintf( stderr, "JIT for TPP bwd_zero_kernel failed. Bailing...!\n");
exit(-1);
}
/* JITing the tranpose kernel */
trans_flags = LIBXSMM_MELTW_FLAG_TRANSFORM_VNNI_TO_VNNIT;
res.vnni_to_vnniT_kernel = libxsmm_dispatch_meltw_transform(bk, bc, &lda, &ldaT, LIBXSMM_DATATYPE_BF16, LIBXSMM_DATATYPE_BF16, trans_flags);
if ( res.vnni_to_vnniT_kernel == NULL ) {
fprintf( stderr, "JIT for TPP vnni_to_vnniT_kernel failed. Bailing...!\n");
exit(-1);
}
/* UPD GEMM */
lda = res.bk;
ldb = res.bn;
ldc = res.bk;
updM = res.bk/res.ofm_subtasks;
updN = res.bc/res.ifm_subtasks;
l_flags = ( LIBXSMM_GEMM_VNNI_FLAGS('N', 'N', 'V', 'N') ) | LIBXSMM_GEMM_FLAG_NO_RESET_TILECONFIG | LIBXSMM_GEMM_FLAG_NO_SETUP_TILECONFIG;
l_tc_flags = LIBXSMM_GEMM_FLAG_NO_RESET_TILECONFIG | ( LIBXSMM_GEMM_VNNI_FLAGS('N', 'N', 'V', 'N') );
unroll_hint = (res.N/res.bn)/res.upd_bf;
res.gemm_upd = libxsmm_bsmmdispatch_reducebatch_strd_unroll(updM, updN, res.bn, res.bk*res.bn*sizeof(libxsmm_bfloat16), res.bc*res.bn*sizeof(libxsmm_bfloat16), unroll_hint, &lda, &ldb, &ldc, &alpha, &beta, &l_flags, NULL);
if ( res.gemm_upd == NULL ) {
fprintf( stderr, "JIT for BRGEMM TPP gemm_upd failed. Bailing...!\n");
exit(-1);
}
res.gemm_upd2 = libxsmm_bsmmdispatch_reducebatch_strd_unroll(updM, updN, res.bn, res.bk*res.bn*sizeof(libxsmm_bfloat16), res.bc*res.bn*sizeof(libxsmm_bfloat16), unroll_hint, &lda, &ldb, &ldc, &alpha, &zerobeta, &l_flags, NULL);
if ( res.gemm_upd2 == NULL ) {
fprintf( stderr, "JIT for BRGEMM TPP gemm_upd2 failed. Bailing...!\n");
exit(-1);
}
l_flags = l_flags | LIBXSMM_GEMM_FLAG_VNNI_C;
res.gemm_upd3 = libxsmm_bmmdispatch_reducebatch_strd_unroll(updM, updN, res.bn, res.bk*res.bn*sizeof(libxsmm_bfloat16), res.bc*res.bn*sizeof(libxsmm_bfloat16), unroll_hint, &lda, &ldb, &ldc, &alpha, &zerobeta, &l_flags, NULL);
if ( res.gemm_upd3 == NULL ) {
fprintf( stderr, "JIT for BRGEMM TPP gemm_upd3 failed. Bailing...!\n");
exit(-1);
}
res.upd_config_kernel = libxsmm_bsmmdispatch(updM, updN, res.bn, &lda, &ldb, &ldc, NULL, &beta, &l_tc_flags, NULL);
if ( res.upd_config_kernel == NULL ) {
fprintf( stderr, "JIT for BRGEMM TPP upd_config_kernel failed. Bailing...!\n");
exit(-1);
}
res.tilerelease_kernel = libxsmm_bsmmdispatch(res.bk, res.bk, res.bk, NULL, NULL, NULL, NULL, NULL, &l_tr_flags, NULL);
if ( res.tilerelease_kernel == NULL ) {
fprintf( stderr, "JIT for TPP tilerelease_kernel failed. Bailing...!\n");
exit(-1);
}
/* Also JIT eltwise TPPs... */
res.upd_cvtfp32bf16_kernel = libxsmm_dispatch_meltw_cvtfp32bf16(bbk, bbc, &ldc, &ldc, LIBXSMM_DATATYPE_F32, LIBXSMM_DATATYPE_BF16, LIBXSMM_MELTW_FLAG_CVT_VNNI_FORMAT);
if ( res.upd_cvtfp32bf16_kernel == NULL ) {
fprintf( stderr, "JIT for TPP upd_cvtfp32bf16_kernel failed. Bailing...!\n");
exit(-1);
}
res.upd_zero_kernel = libxsmm_dispatch_meltw_copy(bbk, bbc, &ld_zero_upd, &ld_zero_upd, LIBXSMM_DATATYPE_F32, LIBXSMM_DATATYPE_F32, LIBXSMM_MELTW_FLAG_COPY_ZERO);
if ( res.upd_zero_kernel == NULL ) {
fprintf( stderr, "JIT for TPP upd_zero_kernel failed. Bailing...!\n");
exit(-1);
}
res.delbias_reduce_kernel = libxsmm_dispatch_meltw_reduce(bk, bn, &delbias_K, &delbias_N, LIBXSMM_DATATYPE_BF16, LIBXSMM_DATATYPE_BF16, LIBXSMM_MELTW_FLAG_REDUCE_OP_ADD | LIBXSMM_MELTW_FLAG_REDUCE_COLS | LIBXSMM_MELTW_FLAG_REDUCE_ELTS | LIBXSMM_MELTW_FLAG_REDUCE_NCNC_FORMAT, 0);
if ( res.delbias_reduce_kernel == NULL ) {
fprintf( stderr, "JIT for TPP delbias_reduce_kernel failed. Bailing...!\n");
exit(-1);
}
/* JITing the tranpose kernels */
trans_flags = LIBXSMM_MELTW_FLAG_TRANSFORM_NORM_TO_VNNI;
res.norm_to_vnni_kernel = libxsmm_dispatch_meltw_transform(bk, bn, &lda, &lda, LIBXSMM_DATATYPE_BF16, LIBXSMM_DATATYPE_BF16, trans_flags);
if ( res.norm_to_vnni_kernel == NULL ) {
fprintf( stderr, "JIT for TPP norm_to_vnni_kernel failed. Bailing...!\n");
exit(-1);
}
trans_flags = LIBXSMM_MELTW_FLAG_TRANSFORM_NORM_TO_NORMT;
res.norm_to_normT_kernel = libxsmm_dispatch_meltw_transform(bc, bn, &ldb, &ldb_orig, LIBXSMM_DATATYPE_BF16, LIBXSMM_DATATYPE_BF16, trans_flags);
if ( res.norm_to_normT_kernel == NULL ) {
fprintf( stderr, "JIT for TPP norm_to_normT_kernel failed. Bailing...!\n");
exit(-1);
}
/* init scratch */
size_bwd_scratch = sizeof(float) * LIBXSMM_MAX(res.C * res.N, res.threads * res.bc * res.bn) + sizeof(libxsmm_bfloat16) * res.C * res.K;
size_upd_scratch = sizeof(float) * LIBXSMM_MAX(res.C * res.K, res.threads * res.bc * res.bk) + sizeof(libxsmm_bfloat16) * res.threads * res.bk * res.bc + sizeof(libxsmm_bfloat16) * (res.N * (res.C + res.K));
#ifdef OVERWRITE_DOUTPUT_BWDUPD
res.scratch_size = LIBXSMM_MAX(size_bwd_scratch, size_upd_scratch) + sizeof(libxsmm_bfloat16) * res.N * res.K;
#else
res.scratch_size = LIBXSMM_MAX(size_bwd_scratch, size_upd_scratch) + 2 * sizeof(libxsmm_bfloat16) * res.N * res.K;
#endif
res.doutput_scratch_mark = LIBXSMM_MAX(size_bwd_scratch, size_upd_scratch) ;
return res;
}
my_opt_config setup_my_opt(libxsmm_blasint C, libxsmm_blasint K, libxsmm_blasint bc, libxsmm_blasint bk,
libxsmm_blasint threads, float lr) {
my_opt_config res;
/* setting up some handle values */
res.C = C;
res.K = K;
res.bc = bc;
res.bk = bk;
res.threads = threads;
res.lr = lr;
/* setting up the barrier */
res.barrier = libxsmm_barrier_create(threads, 1);
/* init scratch */
res.scratch_size = 0;
return res;
}
my_smax_fwd_config setup_my_smax_fwd(libxsmm_blasint N, libxsmm_blasint C, libxsmm_blasint bn, libxsmm_blasint bc,
libxsmm_blasint threads) {
my_smax_fwd_config res;
/* setting up some handle values */
res.C = C;
res.N = N;
res.bc = bc;
res.bn = bn;
res.threads = threads;
/* setting up the barrier */
res.barrier = libxsmm_barrier_create(threads, 1);
/* init scratch */
res.scratch_size = (sizeof(float)*res.C*res.N*2);;
return res;
}
my_smax_bwd_config setup_my_smax_bwd(libxsmm_blasint N, libxsmm_blasint C, libxsmm_blasint bn, libxsmm_blasint bc,
libxsmm_blasint threads, float loss_weight) {
my_smax_bwd_config res;
/* setting up some handle values */
res.C = C;
res.N = N;
res.bc = bc;
res.bn = bn;
res.threads = threads;
res.loss_weight = loss_weight;
/* setting up the barrier */
res.barrier = libxsmm_barrier_create(threads, 1);
/* init scratch */
res.scratch_size = (sizeof(float)*res.C*res.N*2);;
return res;
}
void my_fc_fwd_exec( my_fc_fwd_config cfg, const libxsmm_bfloat16* wt_ptr, const libxsmm_bfloat16* in_act_ptr, libxsmm_bfloat16* out_act_ptr,
const libxsmm_bfloat16* bias_ptr, unsigned char* relu_ptr, int start_tid, int my_tid, void* scratch, my_numa_thr_cfg *numa_thr_cfg, int layer ) {
const libxsmm_blasint nBlocksIFm = cfg.C / cfg.bc;
const libxsmm_blasint nBlocksOFm = cfg.K / cfg.bk;
const libxsmm_blasint nBlocksMB = cfg.N / cfg.bn;
const libxsmm_blasint bn = cfg.bn;
const libxsmm_blasint bk = cfg.bk;
const libxsmm_blasint lpb = 2;
const libxsmm_blasint bc_lp = cfg.bc/lpb;
/* const libxsmm_blasint bc = cfg.bc;*/
libxsmm_blasint use_2d_blocking = cfg.fwd_2d_blocking;
/* computing first logical thread */
const libxsmm_blasint ltid = my_tid - start_tid;
/* number of tasks that could be run in parallel */
const libxsmm_blasint work = nBlocksOFm * nBlocksMB;
/* compute chunk size */
const libxsmm_blasint chunksize = (work % cfg.threads == 0) ? (work / cfg.threads) : ((work / cfg.threads) + 1);
/* compute thr_begin and thr_end */
const libxsmm_blasint thr_begin = (ltid * chunksize < work) ? (ltid * chunksize) : work;
const libxsmm_blasint thr_end = ((ltid + 1) * chunksize < work) ? ((ltid + 1) * chunksize) : work;
/* loop variables */
libxsmm_blasint mb1ofm1 = 0, mb1 = 0, ofm1 = 0, ifm1 = 0;
libxsmm_blasint N_tasks_per_thread = 0, M_tasks_per_thread = 0, my_M_start = 0, my_M_end = 0, my_N_start = 0, my_N_end = 0, my_col_id = 0, my_row_id = 0, col_teams = 0, row_teams = 0;
LIBXSMM_VLA_DECL(4, libxsmm_bfloat16, output, out_act_ptr, nBlocksOFm, cfg.bn, cfg.bk);
LIBXSMM_VLA_DECL(4, const libxsmm_bfloat16, input, in_act_ptr, nBlocksIFm, cfg.bn, cfg.bc);
LIBXSMM_VLA_DECL(5, const libxsmm_bfloat16, filter, wt_ptr, nBlocksIFm, bc_lp, cfg.bk, lpb);
LIBXSMM_VLA_DECL(4, float, output_f32, (float*)scratch, nBlocksOFm, bn, bk);
libxsmm_meltw_gemm_param gemm_eltwise_params;
float* fp32_bias_scratch = ((cfg.fuse_type & MY_ELTWISE_FUSE_BIAS) == MY_ELTWISE_FUSE_BIAS) ? (float*)scratch + ltid * cfg.K : NULL;
LIBXSMM_VLA_DECL(2, const libxsmm_bfloat16, bias, ((cfg.fuse_type & MY_ELTWISE_FUSE_BIAS) == MY_ELTWISE_FUSE_BIAS) ? (libxsmm_bfloat16*) bias_ptr : NULL, cfg.bk);
LIBXSMM_VLA_DECL(4, __mmask32, relubitmask, ((cfg.fuse_type & MY_ELTWISE_FUSE_RELU) == MY_ELTWISE_FUSE_RELU) ? (__mmask32*)relu_ptr : NULL, nBlocksOFm, cfg.bn, cfg.bk/32);
libxsmm_meltwfunction_cvtfp32bf16_act eltwise_kernel_act = cfg.fwd_cvtfp32bf16_relu_kernel;
libxsmm_meltw_cvtfp32bf16_act_param eltwise_params_act;
libxsmm_meltwfunction_cvtfp32bf16 eltwise_kernel = cfg.fwd_cvtfp32bf16_kernel;
libxsmm_meltw_cvtfp32bf16_param eltwise_params;
libxsmm_bmmfunction_reducebatch_strd_meltwfused bf16_batchreduce_kernel_zerobeta_fused_eltwise;
libxsmm_meltw_copy_param copy_params;
unsigned long long blocks = nBlocksIFm;
libxsmm_blasint CB_BLOCKS = nBlocksIFm, BF = 1;
if (((cfg.fuse_type & MY_ELTWISE_FUSE_BIAS) == MY_ELTWISE_FUSE_BIAS) && ((cfg.fuse_type & MY_ELTWISE_FUSE_RELU) == MY_ELTWISE_FUSE_RELU )) {
bf16_batchreduce_kernel_zerobeta_fused_eltwise = cfg.gemm_fwd7;
} else if ((cfg.fuse_type & MY_ELTWISE_FUSE_BIAS) == MY_ELTWISE_FUSE_BIAS) {
bf16_batchreduce_kernel_zerobeta_fused_eltwise = cfg.gemm_fwd4;
} else if ((cfg.fuse_type & MY_ELTWISE_FUSE_RELU) == MY_ELTWISE_FUSE_RELU) {
bf16_batchreduce_kernel_zerobeta_fused_eltwise = cfg.gemm_fwd5;
} else {
bf16_batchreduce_kernel_zerobeta_fused_eltwise = NULL;
}
BF = cfg.fwd_bf;
CB_BLOCKS = nBlocksIFm/BF;
blocks = CB_BLOCKS;
if (use_2d_blocking == 1) {
col_teams = cfg.fwd_col_teams;
row_teams = cfg.fwd_row_teams;
my_row_id = ltid % row_teams;
my_col_id = ltid / row_teams;
N_tasks_per_thread = (nBlocksMB + col_teams-1)/col_teams;
M_tasks_per_thread = (nBlocksOFm + row_teams-1)/row_teams;
my_N_start = LIBXSMM_MIN( my_col_id * N_tasks_per_thread, nBlocksMB);
my_N_end = LIBXSMM_MIN( (my_col_id+1) * N_tasks_per_thread, nBlocksMB);
my_M_start = LIBXSMM_MIN( my_row_id * M_tasks_per_thread, nBlocksOFm);
my_M_end = LIBXSMM_MIN( (my_row_id+1) * M_tasks_per_thread, nBlocksOFm);
}
const libxsmm_blasint ofm_start = numa_thr_cfg->blocksOFm_s[layer];
/* lazy barrier init */
libxsmm_barrier_init(cfg.barrier, ltid);
cfg.fwd_config_kernel(NULL, NULL, NULL);
if (use_2d_blocking == 1) {
if (BF > 1) {
for ( ifm1 = 0; ifm1 < BF; ++ifm1 ) {
for (ofm1 = my_M_start; ofm1 < my_M_end; ++ofm1) {
for (mb1 = my_N_start; mb1 < my_N_end; ++mb1) {
if ( ifm1 == 0 ) {
if ( (cfg.fuse_type & MY_ELTWISE_FUSE_BIAS) == MY_ELTWISE_FUSE_BIAS ) {
copy_params.in_ptr = &LIBXSMM_VLA_ACCESS(2, bias, ofm1, 0,cfg.bk);
copy_params.out_ptr = &LIBXSMM_VLA_ACCESS(4, output_f32, mb1, ofm1, 0, 0, nBlocksOFm,cfg.bn,cfg.bk);
cfg.fwd_colbcast_bf16fp32_copy_kernel(©_params);
} else {
copy_params.out_ptr = &LIBXSMM_VLA_ACCESS(4, output_f32, mb1, ofm1, 0, 0, nBlocksOFm, cfg.bn, cfg.bk);
cfg.fwd_zero_kernel(©_params);
}
}
cfg.gemm_fwd( &LIBXSMM_VLA_ACCESS(5, filter, ofm1, ifm1*CB_BLOCKS, 0, 0, 0, nBlocksIFm, bc_lp, cfg.bk, lpb),
&LIBXSMM_VLA_ACCESS(4, input, mb1, ifm1*CB_BLOCKS, 0, 0, nBlocksIFm, cfg.bn, cfg.bc),
&LIBXSMM_VLA_ACCESS(4, output_f32, mb1, ofm1, 0, 0, nBlocksOFm, cfg.bn, cfg.bk), &blocks);
if ( ifm1 == BF-1 ) {
if ( (cfg.fuse_type & MY_ELTWISE_FUSE_RELU) == MY_ELTWISE_FUSE_RELU ) {
eltwise_params_act.in_ptr = &LIBXSMM_VLA_ACCESS(4, output_f32, mb1, ofm1, 0, 0, nBlocksOFm, cfg.bn, cfg.bk);
eltwise_params_act.out_ptr = &LIBXSMM_VLA_ACCESS(4, output, mb1, ofm1, 0, 0, nBlocksOFm, cfg.bn, cfg.bk);
eltwise_params_act.actstore_ptr = &LIBXSMM_VLA_ACCESS(4, relubitmask, mb1, ofm1, 0, 0, nBlocksOFm, cfg.bn, cfg.bk/32);
eltwise_kernel_act(&eltwise_params_act);
} else {
eltwise_params.in_ptr = &LIBXSMM_VLA_ACCESS(4, output_f32, mb1, ofm1, 0, 0, nBlocksOFm, cfg.bn, cfg.bk);
eltwise_params.out_ptr = &LIBXSMM_VLA_ACCESS(4, output, mb1, ofm1, 0, 0, nBlocksOFm, cfg.bn, cfg.bk);
eltwise_kernel(&eltwise_params);
}
}
}
}
}
} else {
if ( (cfg.fuse_type & MY_ELTWISE_FUSE_BIAS) == MY_ELTWISE_FUSE_BIAS ) {
copy_params.in_ptr = &LIBXSMM_VLA_ACCESS(2, bias, 0, 0,cfg.bk);
copy_params.out_ptr = fp32_bias_scratch;
cfg.fwd_copy_bf16fp32_kernel(©_params);
}
for (ofm1 = my_M_start; ofm1 < my_M_end; ++ofm1) {
for (mb1 = my_N_start; mb1 < my_N_end; ++mb1) {
if ( ((cfg.fuse_type & MY_ELTWISE_FUSE_BIAS) == MY_ELTWISE_FUSE_BIAS) || ((cfg.fuse_type & MY_ELTWISE_FUSE_RELU) == MY_ELTWISE_FUSE_RELU )) {
if ((cfg.fuse_type & MY_ELTWISE_FUSE_BIAS) == MY_ELTWISE_FUSE_BIAS) {
gemm_eltwise_params.bias_ptr = (float*) fp32_bias_scratch + ofm1 * cfg.bk;
}
if ((cfg.fuse_type & MY_ELTWISE_FUSE_RELU) == MY_ELTWISE_FUSE_RELU) {
gemm_eltwise_params.out_ptr = &LIBXSMM_VLA_ACCESS(4, relubitmask, mb1, ofm1, 0, 0, nBlocksOFm, cfg.bn, cfg.bk/32);
}
bf16_batchreduce_kernel_zerobeta_fused_eltwise( &LIBXSMM_VLA_ACCESS(5, filter, ofm1-ofm_start, 0, 0, 0, 0, nBlocksIFm, bc_lp, cfg.bk, lpb),
&LIBXSMM_VLA_ACCESS(4, input, mb1, 0, 0, 0, nBlocksIFm, cfg.bn, cfg.bc),
&LIBXSMM_VLA_ACCESS(4, output, mb1, ofm1, 0, 0, nBlocksOFm, bn, bk), &blocks, &gemm_eltwise_params);
} else {
cfg.gemm_fwd3( &LIBXSMM_VLA_ACCESS(5, filter, ofm1-ofm_start, 0, 0, 0, 0, nBlocksIFm, bc_lp, cfg.bk, lpb),
&LIBXSMM_VLA_ACCESS(4, input, mb1, 0, 0, 0, nBlocksIFm, cfg.bn, cfg.bc),
&LIBXSMM_VLA_ACCESS(4, output, mb1, ofm1, 0, 0, nBlocksOFm, bn, bk), &blocks);
}
}
}
}
} else {
if (BF > 1) {
for ( ifm1 = 0; ifm1 < BF; ++ifm1 ) {
for ( mb1ofm1 = thr_begin; mb1ofm1 < thr_end; ++mb1ofm1 ) {
mb1 = mb1ofm1%nBlocksMB;
ofm1 = mb1ofm1/nBlocksMB;
/* Initialize libxsmm_blasintermediate f32 tensor */
if ( ifm1 == 0 ) {
if ( (cfg.fuse_type & MY_ELTWISE_FUSE_BIAS) == MY_ELTWISE_FUSE_BIAS ) {
copy_params.in_ptr = &LIBXSMM_VLA_ACCESS(2, bias, ofm1, 0,cfg.bk);
copy_params.out_ptr = &LIBXSMM_VLA_ACCESS(4, output_f32, mb1, ofm1, 0, 0, nBlocksOFm,cfg.bn,cfg.bk);
cfg.fwd_colbcast_bf16fp32_copy_kernel(©_params);
} else {
copy_params.out_ptr = &LIBXSMM_VLA_ACCESS(4, output_f32, mb1, ofm1, 0, 0, nBlocksOFm, cfg.bn, cfg.bk);
cfg.fwd_zero_kernel(©_params);
}
}
cfg.gemm_fwd( &LIBXSMM_VLA_ACCESS(5, filter, ofm1, ifm1*CB_BLOCKS, 0, 0, 0, nBlocksIFm, bc_lp, cfg.bk, lpb),
&LIBXSMM_VLA_ACCESS(4, input, mb1, ifm1*CB_BLOCKS, 0, 0, nBlocksIFm, cfg.bn, cfg.bc),
&LIBXSMM_VLA_ACCESS(4, output_f32, mb1, ofm1, 0, 0, nBlocksOFm, cfg.bn, cfg.bk), &blocks);
if ( ifm1 == BF-1 ) {
if ( (cfg.fuse_type & MY_ELTWISE_FUSE_RELU) == MY_ELTWISE_FUSE_RELU ) {
eltwise_params_act.in_ptr = &LIBXSMM_VLA_ACCESS(4, output_f32, mb1, ofm1, 0, 0, nBlocksOFm, cfg.bn, cfg.bk);
eltwise_params_act.out_ptr = &LIBXSMM_VLA_ACCESS(4, output, mb1, ofm1, 0, 0, nBlocksOFm, cfg.bn, cfg.bk);
eltwise_params_act.actstore_ptr = &LIBXSMM_VLA_ACCESS(4, relubitmask, mb1, ofm1, 0, 0, nBlocksOFm, cfg.bn, cfg.bk/32);
eltwise_kernel_act(&eltwise_params_act);
} else {
eltwise_params.in_ptr = &LIBXSMM_VLA_ACCESS(4, output_f32, mb1, ofm1, 0, 0, nBlocksOFm, cfg.bn, cfg.bk);
eltwise_params.out_ptr = &LIBXSMM_VLA_ACCESS(4, output, mb1, ofm1, 0, 0, nBlocksOFm, cfg.bn, cfg.bk);
eltwise_kernel(&eltwise_params);
}
}
}
}
} else {
if ( (cfg.fuse_type & MY_ELTWISE_FUSE_BIAS) == MY_ELTWISE_FUSE_BIAS ) {
copy_params.in_ptr = &LIBXSMM_VLA_ACCESS(2, bias, 0, 0,cfg.bk);
copy_params.out_ptr = fp32_bias_scratch;
cfg.fwd_copy_bf16fp32_kernel(©_params);
}
for ( mb1ofm1 = thr_begin; mb1ofm1 < thr_end; ++mb1ofm1 ) {
mb1 = mb1ofm1%nBlocksMB;
ofm1 = mb1ofm1/nBlocksMB;
if ( ((cfg.fuse_type & MY_ELTWISE_FUSE_BIAS) == MY_ELTWISE_FUSE_BIAS) || ((cfg.fuse_type & MY_ELTWISE_FUSE_RELU) == MY_ELTWISE_FUSE_RELU )) {
if ((cfg.fuse_type & MY_ELTWISE_FUSE_BIAS) == MY_ELTWISE_FUSE_BIAS) {
gemm_eltwise_params.bias_ptr = (float*) fp32_bias_scratch + ofm1 * cfg.bk;
}
if ((cfg.fuse_type & MY_ELTWISE_FUSE_RELU) == MY_ELTWISE_FUSE_RELU) {
gemm_eltwise_params.out_ptr = &LIBXSMM_VLA_ACCESS(4, relubitmask, mb1, ofm1, 0, 0, nBlocksOFm, cfg.bn, cfg.bk/32);
}
bf16_batchreduce_kernel_zerobeta_fused_eltwise( &LIBXSMM_VLA_ACCESS(5, filter, ofm1-ofm_start, 0, 0, 0, 0, nBlocksIFm, bc_lp, cfg.bk, lpb),
&LIBXSMM_VLA_ACCESS(4, input, mb1, 0, 0, 0, nBlocksIFm, cfg.bn, cfg.bc),
&LIBXSMM_VLA_ACCESS(4, output, mb1, ofm1, 0, 0, nBlocksOFm, bn, bk), &blocks, &gemm_eltwise_params);
} else {
cfg.gemm_fwd3( &LIBXSMM_VLA_ACCESS(5, filter, ofm1-ofm_start, 0, 0, 0, 0, nBlocksIFm, bc_lp, cfg.bk, lpb),
&LIBXSMM_VLA_ACCESS(4, input, mb1, 0, 0, 0, nBlocksIFm, cfg.bn, cfg.bc),
&LIBXSMM_VLA_ACCESS(4, output, mb1, ofm1, 0, 0, nBlocksOFm, bn, bk), &blocks);
}
}
}
}
cfg.tilerelease_kernel(NULL, NULL, NULL);
libxsmm_barrier_wait(cfg.barrier, ltid);
}
void my_fc_bwd_exec( my_fc_bwd_config cfg, const libxsmm_bfloat16* wt_ptr, libxsmm_bfloat16* din_act_ptr,
const libxsmm_bfloat16* dout_act_ptr, libxsmm_bfloat16* dwt_ptr, const libxsmm_bfloat16* in_act_ptr,
libxsmm_bfloat16* dbias_ptr, const unsigned char* relu_ptr, my_pass pass, int start_tid, int my_tid, void* scratch ) {
/* size variables, all const */
/* here we assume that input and output blocking is similar */
const libxsmm_blasint bn = cfg.bn;
const libxsmm_blasint bk = cfg.bk;
const libxsmm_blasint bc = cfg.bc;
libxsmm_blasint lpb = 2;
const libxsmm_blasint bc_lp = bc/lpb;
const libxsmm_blasint bk_lp = bk/lpb;
const libxsmm_blasint bn_lp = bn/lpb;
const libxsmm_blasint nBlocksIFm = cfg.C / cfg.bc;
const libxsmm_blasint nBlocksOFm = cfg.K / cfg.bk;
const libxsmm_blasint nBlocksMB = cfg.N / cfg.bn;
libxsmm_blasint mb1ofm1 = 0, mb1 = 0, ofm1 = 0, ofm2 = 0;
libxsmm_blasint performed_doutput_transpose = 0;
libxsmm_meltw_transform_param trans_param;
/* computing first logical thread */
const libxsmm_blasint ltid = my_tid - start_tid;
/* number of tasks for transpose that could be run in parallel */
const libxsmm_blasint eltwise_work = nBlocksOFm * nBlocksMB;
/* compute chunk size */
const libxsmm_blasint eltwise_chunksize = (eltwise_work % cfg.threads == 0) ? (eltwise_work / cfg.threads) : ((eltwise_work / cfg.threads) + 1);
/* compute thr_begin and thr_end */
const libxsmm_blasint eltwise_thr_begin = (ltid * eltwise_chunksize < eltwise_work) ? (ltid * eltwise_chunksize) : eltwise_work;
const libxsmm_blasint eltwise_thr_end = ((ltid + 1) * eltwise_chunksize < eltwise_work) ? ((ltid + 1) * eltwise_chunksize) : eltwise_work;
/* number of tasks for transpose that could be run in parallel */
const libxsmm_blasint dbias_work = nBlocksOFm;
/* compute chunk size */
const libxsmm_blasint dbias_chunksize = (dbias_work % cfg.threads == 0) ? (dbias_work / cfg.threads) : ((dbias_work / cfg.threads) + 1);
/* compute thr_begin and thr_end */
const libxsmm_blasint dbias_thr_begin = (ltid * dbias_chunksize < dbias_work) ? (ltid * dbias_chunksize) : dbias_work;
const libxsmm_blasint dbias_thr_end = ((ltid + 1) * dbias_chunksize < dbias_work) ? ((ltid + 1) * dbias_chunksize) : dbias_work;
LIBXSMM_VLA_DECL(2, libxsmm_bfloat16, dbias, ((cfg.fuse_type & MY_ELTWISE_FUSE_BIAS) == MY_ELTWISE_FUSE_BIAS) ? (libxsmm_bfloat16*) dbias_ptr : NULL, cfg.bk);
LIBXSMM_VLA_DECL(4, __mmask32, relubitmask, ((cfg.fuse_type & MY_ELTWISE_FUSE_RELU) == MY_ELTWISE_FUSE_RELU) ? (__mmask32*)relu_ptr : NULL, nBlocksOFm, cfg.bn, cfg.bk/32);
#ifdef OVERWRITE_DOUTPUT_BWDUPD
libxsmm_bfloat16 *grad_output_ptr = (libxsmm_bfloat16*)dout_act_ptr;
libxsmm_bfloat16 *tr_doutput_ptr = (((cfg.fuse_type & MY_ELTWISE_FUSE_RELU) == MY_ELTWISE_FUSE_RELU)) ? (libxsmm_bfloat16*)((char*)scratch + cfg.doutput_scratch_mark) : (libxsmm_bfloat16*)scratch;
#else
libxsmm_bfloat16 *grad_output_ptr = (((cfg.fuse_type & MY_ELTWISE_FUSE_RELU) == MY_ELTWISE_FUSE_RELU)) ? (libxsmm_bfloat16*)((char*)scratch + cfg.doutput_scratch_mark) : (libxsmm_bfloat16*)dout_act_ptr;
libxsmm_bfloat16 *tr_doutput_ptr = (((cfg.fuse_type & MY_ELTWISE_FUSE_RELU) == MY_ELTWISE_FUSE_RELU)) ? (libxsmm_bfloat16*)grad_output_ptr + cfg.N * cfg.K : (libxsmm_bfloat16*)scratch;
#endif
LIBXSMM_VLA_DECL(4, const libxsmm_bfloat16, doutput_orig, (libxsmm_bfloat16*)dout_act_ptr, nBlocksOFm, bn, bk);
libxsmm_meltw_relu_param relu_params;
libxsmm_meltwfunction_relu relu_kernel = cfg.bwd_relu_kernel;
LIBXSMM_VLA_DECL(4, libxsmm_bfloat16, doutput, grad_output_ptr, nBlocksOFm, bn, bk);
LIBXSMM_VLA_DECL(5, libxsmm_bfloat16, doutput_tr, tr_doutput_ptr, nBlocksMB, bn_lp, bk, lpb);
libxsmm_meltwfunction_cvtfp32bf16 eltwise_kernel = cfg.bwd_cvtfp32bf16_kernel;
libxsmm_meltwfunction_cvtfp32bf16 eltwise_kernel2 = cfg.upd_cvtfp32bf16_kernel;
libxsmm_meltw_cvtfp32bf16_param eltwise_params;
libxsmm_meltw_copy_param copy_params;
libxsmm_meltw_reduce_param delbias_params;
/* lazy barrier init */
libxsmm_barrier_init(cfg.barrier, ltid);
cfg.bwd_config_kernel(NULL, NULL, NULL);
/* Apply to doutput potential fusions */
if (((cfg.fuse_type & MY_ELTWISE_FUSE_RELU) == MY_ELTWISE_FUSE_RELU)) {
for ( mb1ofm1 = eltwise_thr_begin; mb1ofm1 < eltwise_thr_end; ++mb1ofm1 ) {
mb1 = mb1ofm1/nBlocksOFm;
ofm1 = mb1ofm1%nBlocksOFm;
relu_params.in_ptr = &LIBXSMM_VLA_ACCESS(4, doutput_orig, mb1, ofm1, 0, 0, nBlocksOFm, cfg.bn, cfg.bk);
relu_params.out_ptr = &LIBXSMM_VLA_ACCESS(4, doutput, mb1, ofm1, 0, 0, nBlocksOFm, cfg.bn, cfg.bk);
relu_params.mask_ptr = &LIBXSMM_VLA_ACCESS(4, relubitmask, mb1, ofm1, 0, 0, nBlocksOFm, cfg.bn, cfg.bk/32);
relu_kernel(&relu_params);
/* If in UPD pass, also perform transpose of doutput */
if ( (pass & MY_PASS_BWD_W) == MY_PASS_BWD_W ) {
trans_param.in_ptr = &LIBXSMM_VLA_ACCESS(4, doutput, mb1, ofm1, 0, 0, nBlocksOFm, bn, bk);
trans_param.out_ptr = &LIBXSMM_VLA_ACCESS(5, doutput_tr, ofm1, mb1, 0, 0, 0, nBlocksMB, bn_lp, bk, lpb);
cfg.norm_to_vnni_kernel(&trans_param);
}
}
if ( (pass & MY_PASS_BWD_W) == MY_PASS_BWD_W ) {
performed_doutput_transpose = 1;
}
libxsmm_barrier_wait(cfg.barrier, ltid);
}
/* Accumulation of bias happens in f32 */
if (((cfg.fuse_type & MY_ELTWISE_FUSE_BIAS) == MY_ELTWISE_FUSE_BIAS)) {
for ( ofm1 = dbias_thr_begin; ofm1 < dbias_thr_end; ++ofm1 ) {
delbias_params.in_ptr = &LIBXSMM_VLA_ACCESS(4, doutput, 0, ofm1, 0, 0, nBlocksOFm, cfg.bn, cfg.bk);
delbias_params.out_ptr_0 = &LIBXSMM_VLA_ACCESS(2, dbias, ofm1, 0, cfg.bk);
cfg.delbias_reduce_kernel(&delbias_params);
}
/* wait for eltwise to finish */
libxsmm_barrier_wait(cfg.barrier, ltid);
}
if ( (pass & MY_PASS_BWD_D) == MY_PASS_BWD_D ){
libxsmm_blasint use_2d_blocking = cfg.bwd_2d_blocking;
/* number of tasks that could be run in parallel */
const libxsmm_blasint work = nBlocksIFm * nBlocksMB;
/* compute chunk size */
const libxsmm_blasint chunksize = (work % cfg.threads == 0) ? (work / cfg.threads) : ((work / cfg.threads) + 1);
/* compute thr_begin and thr_end */
const libxsmm_blasint thr_begin = (ltid * chunksize < work) ? (ltid * chunksize) : work;
const libxsmm_blasint thr_end = ((ltid + 1) * chunksize < work) ? ((ltid + 1) * chunksize) : work;
/* number of tasks for transpose that could be run in parallel */
const libxsmm_blasint transpose_work = nBlocksIFm * nBlocksOFm;
/* compute chunk size */
const libxsmm_blasint transpose_chunksize = (transpose_work % cfg.threads == 0) ? (transpose_work / cfg.threads) : ((transpose_work / cfg.threads) + 1);
/* compute thr_begin and thr_end */
const libxsmm_blasint transpose_thr_begin = (ltid * transpose_chunksize < transpose_work) ? (ltid * transpose_chunksize) : transpose_work;
const libxsmm_blasint transpose_thr_end = ((ltid + 1) * transpose_chunksize < transpose_work) ? ((ltid + 1) * transpose_chunksize) : transpose_work;
/* loop variables */
libxsmm_blasint ifm1 = 0, ifm1ofm1 = 0, mb1ifm1 = 0;
libxsmm_blasint N_tasks_per_thread = 0, M_tasks_per_thread = 0, my_M_start = 0, my_M_end = 0, my_N_start = 0, my_N_end = 0, my_col_id = 0, my_row_id = 0, col_teams = 0, row_teams = 0;
LIBXSMM_VLA_DECL(5, const libxsmm_bfloat16, filter, (libxsmm_bfloat16*)wt_ptr, nBlocksIFm, bc_lp, bk, lpb);
LIBXSMM_VLA_DECL(4, libxsmm_bfloat16, dinput, (libxsmm_bfloat16* )din_act_ptr, nBlocksIFm, bn, bc);
LIBXSMM_VLA_DECL(5, libxsmm_bfloat16, filter_tr, (libxsmm_bfloat16*)scratch, nBlocksOFm, bk_lp, bc, lpb);
float* temp_output = (float*)scratch + (cfg.C * cfg.K)/2;
LIBXSMM_VLA_DECL(4, float, dinput_f32, (float*) temp_output, nBlocksIFm, bn, bc);
unsigned long long blocks = nBlocksOFm;
libxsmm_blasint KB_BLOCKS = nBlocksOFm, BF = 1;
BF = cfg.bwd_bf;
KB_BLOCKS = nBlocksOFm/BF;
blocks = KB_BLOCKS;
if (use_2d_blocking == 1) {
col_teams = cfg.bwd_col_teams;
row_teams = cfg.bwd_row_teams;
my_row_id = ltid % row_teams;
my_col_id = ltid / row_teams;
N_tasks_per_thread = (nBlocksMB + col_teams-1)/col_teams;
M_tasks_per_thread = (nBlocksIFm + row_teams-1)/row_teams;
my_N_start = LIBXSMM_MIN( my_col_id * N_tasks_per_thread, nBlocksMB);
my_N_end = LIBXSMM_MIN( (my_col_id+1) * N_tasks_per_thread, nBlocksMB);
my_M_start = LIBXSMM_MIN( my_row_id * M_tasks_per_thread, nBlocksIFm);
my_M_end = LIBXSMM_MIN( (my_row_id+1) * M_tasks_per_thread, nBlocksIFm);
}
/* transpose weight */
for (ifm1ofm1 = transpose_thr_begin; ifm1ofm1 < transpose_thr_end; ++ifm1ofm1) {
ofm1 = ifm1ofm1 / nBlocksIFm;
ifm1 = ifm1ofm1 % nBlocksIFm;
trans_param.in_ptr = &LIBXSMM_VLA_ACCESS(5, filter, ofm1, ifm1, 0, 0, 0, nBlocksIFm, bc_lp, bk, lpb);
trans_param.out_ptr = &LIBXSMM_VLA_ACCESS(5, filter_tr, ifm1, ofm1, 0, 0, 0, nBlocksOFm, bk_lp, bc, lpb);
cfg.vnni_to_vnniT_kernel(&trans_param);
}
/* wait for transpose to finish */
libxsmm_barrier_wait(cfg.barrier, ltid);
if (use_2d_blocking == 1) {
if (BF > 1) {
for ( ofm1 = 0; ofm1 < BF; ++ofm1 ) {
for (ifm1 = my_M_start; ifm1 < my_M_end; ++ifm1) {
for (mb1 = my_N_start; mb1 < my_N_end; ++mb1) {
/* Initialize libxsmm_blasintermediate f32 tensor */
if ( ofm1 == 0 ) {
copy_params.out_ptr = &LIBXSMM_VLA_ACCESS(4, dinput_f32, mb1, ifm1, 0, 0, nBlocksIFm, bn, bc);
cfg.bwd_zero_kernel(©_params);
}
cfg.gemm_bwd( &LIBXSMM_VLA_ACCESS(5, filter_tr, ifm1, ofm1*KB_BLOCKS, 0, 0, 0, nBlocksOFm, bk_lp, bc, lpb),
&LIBXSMM_VLA_ACCESS(4, doutput, mb1, ofm1*KB_BLOCKS, 0, 0, nBlocksOFm, bn, bk),
&LIBXSMM_VLA_ACCESS(4, dinput_f32, mb1, ifm1, 0, 0, nBlocksIFm, bn, bc), &blocks);
/* downconvert libxsmm_blasintermediate f32 tensor to bf 16 and store to final C */
if ( ofm1 == BF-1 ) {
eltwise_params.in_ptr = &LIBXSMM_VLA_ACCESS(4, dinput_f32, mb1, ifm1, 0, 0, nBlocksIFm, bn, bc);
eltwise_params.out_ptr = &LIBXSMM_VLA_ACCESS(4, dinput, mb1, ifm1, 0, 0, nBlocksIFm, bn, bc);
eltwise_kernel(&eltwise_params);
}
}
}
}
} else {
for (ifm1 = my_M_start; ifm1 < my_M_end; ++ifm1) {
for (mb1 = my_N_start; mb1 < my_N_end; ++mb1) {
cfg.gemm_bwd3( &LIBXSMM_VLA_ACCESS(5, filter_tr, ifm1, 0, 0, 0, 0, nBlocksOFm, bk_lp, bc, lpb),
&LIBXSMM_VLA_ACCESS(4, doutput, mb1, 0, 0, 0, nBlocksOFm, bn, bk),
&LIBXSMM_VLA_ACCESS(4, dinput, mb1, ifm1, 0, 0, nBlocksIFm, bn, bc), &blocks);
}
}
}
} else {
if (BF > 1) {
for ( ofm1 = 0; ofm1 < BF; ++ofm1 ) {
for ( mb1ifm1 = thr_begin; mb1ifm1 < thr_end; ++mb1ifm1 ) {
mb1 = mb1ifm1%nBlocksMB;
ifm1 = mb1ifm1/nBlocksMB;
/* Initialize libxsmm_blasintermediate f32 tensor */
if ( ofm1 == 0 ) {
copy_params.out_ptr = &LIBXSMM_VLA_ACCESS(4, dinput_f32, mb1, ifm1, 0, 0, nBlocksIFm, bn, bc);
cfg.bwd_zero_kernel(©_params);
}
cfg.gemm_bwd( &LIBXSMM_VLA_ACCESS(5, filter_tr, ifm1, ofm1*KB_BLOCKS, 0, 0, 0, nBlocksOFm, bk_lp, bc, lpb),
&LIBXSMM_VLA_ACCESS(4, doutput, mb1, ofm1*KB_BLOCKS, 0, 0, nBlocksOFm, bn, bk),
&LIBXSMM_VLA_ACCESS(4, dinput_f32, mb1, ifm1, 0, 0, nBlocksIFm, bn, bc), &blocks);
/* downconvert libxsmm_blasintermediate f32 tensor to bf 16 and store to final C */
if ( ofm1 == BF-1 ) {
eltwise_params.in_ptr = &LIBXSMM_VLA_ACCESS(4, dinput_f32, mb1, ifm1, 0, 0, nBlocksIFm, bn, bc);
eltwise_params.out_ptr = &LIBXSMM_VLA_ACCESS(4, dinput, mb1, ifm1, 0, 0, nBlocksIFm, bn, bc);
eltwise_kernel(&eltwise_params);
}
}
}
} else {
for ( mb1ifm1 = thr_begin; mb1ifm1 < thr_end; ++mb1ifm1 ) {
mb1 = mb1ifm1%nBlocksMB;
ifm1 = mb1ifm1/nBlocksMB;
cfg.gemm_bwd3( &LIBXSMM_VLA_ACCESS(5, filter_tr, ifm1, 0, 0, 0, 0, nBlocksOFm, bk_lp, bc, lpb),
&LIBXSMM_VLA_ACCESS(4, doutput, mb1, 0, 0, 0, nBlocksOFm, bn, bk),
&LIBXSMM_VLA_ACCESS(4, dinput, mb1, ifm1, 0, 0, nBlocksIFm, bn, bc), &blocks);
}
}
}
libxsmm_barrier_wait(cfg.barrier, ltid);
}
if ( (pass & MY_PASS_BWD_W) == MY_PASS_BWD_W ) {
/* number of tasks that could be run in parallel */
const libxsmm_blasint ofm_subtasks = (cfg.upd_2d_blocking == 1) ? 1 : cfg.ofm_subtasks;
const libxsmm_blasint ifm_subtasks = (cfg.upd_2d_blocking == 1) ? 1 : cfg.ifm_subtasks;
const libxsmm_blasint bbk = (cfg.upd_2d_blocking == 1) ? bk : bk/ofm_subtasks;
const libxsmm_blasint bbc = (cfg.upd_2d_blocking == 1) ? bc : bc/ifm_subtasks;
const libxsmm_blasint work = nBlocksIFm * ifm_subtasks * nBlocksOFm * ofm_subtasks;
const libxsmm_blasint Cck_work = nBlocksIFm * ifm_subtasks * ofm_subtasks;
const libxsmm_blasint Cc_work = nBlocksIFm * ifm_subtasks;
/* 2D blocking parameters */
libxsmm_blasint use_2d_blocking = cfg.upd_2d_blocking;
libxsmm_blasint N_tasks_per_thread = 0, M_tasks_per_thread = 0, my_M_start = 0, my_M_end = 0, my_N_start = 0, my_N_end = 0, my_col_id = 0, my_row_id = 0, col_teams = 0, row_teams = 0;
/* compute chunk size */
const libxsmm_blasint chunksize = (work % cfg.threads == 0) ? (work / cfg.threads) : ((work / cfg.threads) + 1);
/* compute thr_begin and thr_end */
const libxsmm_blasint thr_begin = (ltid * chunksize < work) ? (ltid * chunksize) : work;
const libxsmm_blasint thr_end = ((ltid + 1) * chunksize < work) ? ((ltid + 1) * chunksize) : work;
libxsmm_blasint BF = cfg.upd_bf;
/* loop variables */
libxsmm_blasint ifm1ofm1 = 0, ifm1 = 0, ifm2 = 0, bfn = 0, mb1ifm1 = 0;
/* Batch reduce related variables */
unsigned long long blocks = nBlocksMB/BF;
LIBXSMM_VLA_DECL(4, const libxsmm_bfloat16, input, (libxsmm_bfloat16* )in_act_ptr, nBlocksIFm, bn, bc);
LIBXSMM_VLA_DECL(5, libxsmm_bfloat16, dfilter, (libxsmm_bfloat16*)dwt_ptr, nBlocksIFm, bc_lp, bk, lpb);
/* Set up tensors for transposing/scratch before vnni reformatting dfilter */
libxsmm_bfloat16 *tr_inp_ptr = (libxsmm_bfloat16*) ((libxsmm_bfloat16*)scratch + cfg.N * cfg.K);
float *dfilter_f32_ptr = (float*) ((libxsmm_bfloat16*)tr_inp_ptr + cfg.N * cfg.C);
LIBXSMM_VLA_DECL(4, libxsmm_bfloat16, input_tr, (libxsmm_bfloat16*)tr_inp_ptr, nBlocksMB, bc, bn);
LIBXSMM_VLA_DECL(4, float, dfilter_f32, (float*)dfilter_f32_ptr, nBlocksIFm, bc, bk);
const libxsmm_blasint tr_out_work = nBlocksMB * nBlocksOFm;
const libxsmm_blasint tr_out_chunksize = (tr_out_work % cfg.threads == 0) ? (tr_out_work / cfg.threads) : ((tr_out_work / cfg.threads) + 1);
const libxsmm_blasint tr_out_thr_begin = (ltid * tr_out_chunksize < tr_out_work) ? (ltid * tr_out_chunksize) : tr_out_work;
const libxsmm_blasint tr_out_thr_end = ((ltid + 1) * tr_out_chunksize < tr_out_work) ? ((ltid + 1) * tr_out_chunksize) : tr_out_work;
const libxsmm_blasint tr_inp_work = nBlocksMB * nBlocksIFm;
const libxsmm_blasint tr_inp_chunksize = (tr_inp_work % cfg.threads == 0) ? (tr_inp_work / cfg.threads) : ((tr_inp_work / cfg.threads) + 1);
const libxsmm_blasint tr_inp_thr_begin = (ltid * tr_inp_chunksize < tr_inp_work) ? (ltid * tr_inp_chunksize) : tr_inp_work;
const libxsmm_blasint tr_inp_thr_end = ((ltid + 1) * tr_inp_chunksize < tr_inp_work) ? ((ltid + 1) * tr_inp_chunksize) : tr_inp_work;
if (use_2d_blocking == 1) {
col_teams = cfg.upd_col_teams;
row_teams = cfg.upd_row_teams;
my_row_id = ltid % row_teams;
my_col_id = ltid / row_teams;
N_tasks_per_thread = (nBlocksIFm + col_teams-1)/col_teams;
M_tasks_per_thread = (nBlocksOFm + row_teams-1)/row_teams;
my_N_start = LIBXSMM_MIN( my_col_id * N_tasks_per_thread, nBlocksIFm);
my_N_end = LIBXSMM_MIN( (my_col_id+1) * N_tasks_per_thread, nBlocksIFm);
my_M_start = LIBXSMM_MIN( my_row_id * M_tasks_per_thread, nBlocksOFm);
my_M_end = LIBXSMM_MIN( (my_row_id+1) * M_tasks_per_thread, nBlocksOFm);
}
/* Required upfront tranposes */
for (mb1ifm1 = tr_inp_thr_begin; mb1ifm1 < tr_inp_thr_end; mb1ifm1++) {
mb1 = mb1ifm1%nBlocksMB;
ifm1 = mb1ifm1/nBlocksMB;
trans_param.in_ptr = &LIBXSMM_VLA_ACCESS(4, input, mb1, ifm1, 0, 0, nBlocksIFm, bn, bc);
trans_param.out_ptr = &LIBXSMM_VLA_ACCESS(4, input_tr, ifm1, mb1, 0, 0, nBlocksMB, bc, bn);
cfg.norm_to_normT_kernel(&trans_param);
}
if (performed_doutput_transpose == 0) {
for (mb1ofm1 = tr_out_thr_begin; mb1ofm1 < tr_out_thr_end; mb1ofm1++) {
mb1 = mb1ofm1%nBlocksMB;
ofm1 = mb1ofm1/nBlocksMB;
trans_param.in_ptr = &LIBXSMM_VLA_ACCESS(4, doutput, mb1, ofm1, 0, 0, nBlocksOFm, bn, bk);
trans_param.out_ptr = &LIBXSMM_VLA_ACCESS(5, doutput_tr, ofm1, mb1, 0, 0, 0, nBlocksMB, bn_lp, bk, lpb);
cfg.norm_to_vnni_kernel(&trans_param);
}
}
libxsmm_barrier_wait(cfg.barrier, ltid);
if (use_2d_blocking == 1) {
ifm2 = 0;
ofm2 = 0;
if (BF == 1) {
for (ofm1 = my_M_start; ofm1 < my_M_end; ++ofm1) {
for (ifm1 = my_N_start; ifm1 < my_N_end; ++ifm1) {
cfg.gemm_upd3(&LIBXSMM_VLA_ACCESS(5, doutput_tr, ofm1, 0, 0, ofm2*bbk, 0, nBlocksMB, bn_lp, bk, lpb), &LIBXSMM_VLA_ACCESS(4, input_tr, ifm1, 0, ifm2*bbc, 0, nBlocksMB, bc, bn), &LIBXSMM_VLA_ACCESS(5, dfilter, ofm1, ifm1, 0, 0, 0, nBlocksIFm, bc_lp, bk, lpb), &blocks);
}
}
} else {
for (bfn = 0; bfn < BF; bfn++) {
for (ofm1 = my_M_start; ofm1 < my_M_end; ++ofm1) {
for (ifm1 = my_N_start; ifm1 < my_N_end; ++ifm1) {
/* initialize current work task to zero */
if (bfn == 0) {
copy_params.out_ptr = &LIBXSMM_VLA_ACCESS(4, dfilter_f32, ofm1, ifm1, ifm2*bbc, ofm2*bbk, nBlocksIFm, bc, bk);
cfg.upd_zero_kernel(©_params);
}
cfg.gemm_upd(&LIBXSMM_VLA_ACCESS(5, doutput_tr, ofm1, bfn*blocks, 0, ofm2*bbk, 0, nBlocksMB, bn_lp, bk, lpb), &LIBXSMM_VLA_ACCESS(4, input_tr, ifm1, bfn*blocks, ifm2*bbc, 0, nBlocksMB, bc, bn), &LIBXSMM_VLA_ACCESS(4, dfilter_f32, ofm1, ifm1, ifm2*bbc, ofm2*bbk, nBlocksIFm, bc, bk), &blocks);
/* Downconvert result to BF16 and vnni format */
if (bfn == BF-1) {
eltwise_params.in_ptr = &LIBXSMM_VLA_ACCESS(4, dfilter_f32, ofm1, ifm1, 0, 0, nBlocksIFm, bc, bk);
eltwise_params.out_ptr = &LIBXSMM_VLA_ACCESS(5, dfilter, ofm1, ifm1, 0, 0, 0, nBlocksIFm, bc_lp, bk, lpb);
eltwise_kernel2(&eltwise_params);
}
}
}
}
}
} else {
if (BF == 1) {
for ( ifm1ofm1 = thr_begin; ifm1ofm1 < thr_end; ++ifm1ofm1 ) {
ofm1 = ifm1ofm1 / Cck_work;
ofm2 = (ifm1ofm1 % Cck_work) / Cc_work;
ifm1 = ((ifm1ofm1 % Cck_work) % Cc_work) / ifm_subtasks;
ifm2 = ((ifm1ofm1 % Cck_work) % Cc_work) % ifm_subtasks;
cfg.gemm_upd3(&LIBXSMM_VLA_ACCESS(5, doutput_tr, ofm1, 0, 0, ofm2*bbk, 0, nBlocksMB, bn_lp, bk, lpb), &LIBXSMM_VLA_ACCESS(4, input_tr, ifm1, 0, ifm2*bbc, 0, nBlocksMB, bc, bn), &LIBXSMM_VLA_ACCESS(5, dfilter, ofm1, ifm1, (ifm2*bbc)/lpb, ofm2*bbk, 0, nBlocksIFm, bc_lp, bk, lpb), &blocks);
}
} else {
for (bfn = 0; bfn < BF; bfn++) {
for ( ifm1ofm1 = thr_begin; ifm1ofm1 < thr_end; ++ifm1ofm1 ) {
ofm1 = ifm1ofm1 / Cck_work;
ofm2 = (ifm1ofm1 % Cck_work) / Cc_work;
ifm1 = ((ifm1ofm1 % Cck_work) % Cc_work) / ifm_subtasks;
ifm2 = ((ifm1ofm1 % Cck_work) % Cc_work) % ifm_subtasks;
/* initialize current work task to zero */
if (bfn == 0) {
copy_params.out_ptr = &LIBXSMM_VLA_ACCESS(4, dfilter_f32, ofm1, ifm1, ifm2*bbc, ofm2*bbk, nBlocksIFm, bc, bk);
cfg.upd_zero_kernel(©_params);
}
cfg.gemm_upd(&LIBXSMM_VLA_ACCESS(5, doutput_tr, ofm1, bfn*blocks, 0, ofm2*bbk, 0, nBlocksMB, bn_lp, bk, lpb), &LIBXSMM_VLA_ACCESS(4, input_tr, ifm1, bfn*blocks, ifm2*bbc, 0, nBlocksMB, bc, bn), &LIBXSMM_VLA_ACCESS(4, dfilter_f32, ofm1, ifm1, ifm2*bbc, ofm2*bbk, nBlocksIFm, bc, bk), &blocks);
/* Downconvert result to BF16 and vnni format */
if (bfn == BF-1) {
eltwise_params.in_ptr = &LIBXSMM_VLA_ACCESS(4, dfilter_f32, ofm1, ifm1, ifm2*bbc, ofm2*bbk, nBlocksIFm, bc, bk);
eltwise_params.out_ptr = &LIBXSMM_VLA_ACCESS(5, dfilter, ofm1, ifm1, (ifm2*bbc)/lpb, ofm2*bbk, 0, nBlocksIFm, bc_lp, bk, lpb);
eltwise_kernel2(&eltwise_params);
}
}
}
}
}
libxsmm_barrier_wait(cfg.barrier, ltid);
}
cfg.tilerelease_kernel(NULL, NULL, NULL);
}
void my_opt_exec( my_opt_config cfg, libxsmm_bfloat16* wt_ptr, float* master_wt_ptr, const libxsmm_bfloat16* delwt_ptr, int start_tid, int my_tid, void* scratch ) {
/* loop counters */
libxsmm_blasint i;
/* computing first logical thread */
const libxsmm_blasint ltid = my_tid - start_tid;
/* number of tasks that could run in parallel for the filters */
const libxsmm_blasint work = cfg.C * cfg.K;
/* compute chunk size */
const libxsmm_blasint chunksize = (work % cfg.threads == 0) ? (work / cfg.threads) : ((work / cfg.threads) + 1);
/* compute thr_begin and thr_end */
const libxsmm_blasint thr_begin = (ltid * chunksize < work) ? (ltid * chunksize) : work;
const libxsmm_blasint thr_end = ((ltid + 1) * chunksize < work) ? ((ltid + 1) * chunksize) : work;
/* lazy barrier init */
libxsmm_barrier_init( cfg.barrier, ltid );
#if defined(__AVX512BW__)
libxsmm_blasint iv = ( (thr_end-thr_begin)/16 ) * 16; /* compute iterations which are vectorizable */
__m512 vlr = _mm512_set1_ps( cfg.lr );
for ( i = thr_begin; i < thr_begin+iv; i+=16 ) {
__m512 newfilter = _mm512_sub_ps( _mm512_loadu_ps( master_wt_ptr+i ), _mm512_mul_ps( vlr, _mm512_load_fil( delwt_ptr + i ) ) );
_mm512_store_fil( wt_ptr+i, newfilter );
_mm512_storeu_ps( master_wt_ptr+i, newfilter );
}
for ( i = thr_begin+iv; i < thr_end; ++i ) {
libxsmm_bfloat16_hp t1, t2;
t1.i[0] =0;
t1.i[1] = delwt_ptr[i];
master_wt_ptr[i] = master_wt_ptr[i] - (cfg.lr*t1.f);
t2.f = master_wt_ptr[i];
wt_ptr[i] = t2.i[1];
}
#else
for ( i = thr_begin; i < thr_end; ++i ) {
libxsmm_bfloat16_hp t1, t2;
t1.i[0] =0;
t1.i[1] = delwt_ptr[i];
master_wt_ptr[i] = master_wt_ptr[i] - (cfg.lr*t1.f);
t2.f = master_wt_ptr[i];
wt_ptr[i] = t2.i[1];
}
#endif
libxsmm_barrier_wait( cfg.barrier, ltid );
}
void my_smax_fwd_exec( my_smax_fwd_config cfg, const libxsmm_bfloat16* in_act_ptr, libxsmm_bfloat16* out_act_ptr, const int* label_ptr, float* loss, int start_tid, int my_tid, void* scratch ) {
libxsmm_blasint bn = cfg.bn;
libxsmm_blasint Bn = cfg.N/cfg.bn;
libxsmm_blasint bc = cfg.bc;
libxsmm_blasint Bc = cfg.C/cfg.bc;
/* loop counters */
libxsmm_blasint i = 0;
libxsmm_blasint img1, img2, ifm1, ifm2;
/* computing first logical thread */
const libxsmm_blasint ltid = my_tid - start_tid;
/* number of tasks that could run in parallel for the batch */
const libxsmm_blasint n_work = Bn * bn;
/* compute chunk size */
const libxsmm_blasint n_chunksize = (n_work % cfg.threads == 0) ? (n_work / cfg.threads) : ((n_work / cfg.threads) + 1);
/* compute thr_begin and thr_end */
const libxsmm_blasint n_thr_begin = (ltid * n_chunksize < n_work) ? (ltid * n_chunksize) : n_work;
const libxsmm_blasint n_thr_end = ((ltid + 1) * n_chunksize < n_work) ? ((ltid + 1) * n_chunksize) : n_work;
/* number of tasks that could run in parallel for the batch */
const libxsmm_blasint nc_work = Bn * bn;
/* compute chunk size */
const libxsmm_blasint nc_chunksize = (nc_work % cfg.threads == 0) ? (nc_work / cfg.threads) : ((nc_work / cfg.threads) + 1);
/* compute thr_begin and thr_end */
const libxsmm_blasint nc_thr_begin = (ltid * nc_chunksize < nc_work) ? (ltid * nc_chunksize) : nc_work;
const libxsmm_blasint nc_thr_end = ((ltid + 1) * nc_chunksize < nc_work) ? ((ltid + 1) * nc_chunksize) : nc_work;
libxsmm_bfloat16* poutput_bf16 = out_act_ptr;
const libxsmm_bfloat16* pinput_bf16 = in_act_ptr;
float* poutput_fp32 = (float*)scratch;
float* pinput_fp32 = ((float*)scratch)+(cfg.N*cfg.C);
LIBXSMM_VLA_DECL(4, float, output, poutput_fp32, Bc, bn, bc);
LIBXSMM_VLA_DECL(4, const float, input, pinput_fp32, Bc, bn, bc);
LIBXSMM_VLA_DECL(2, const int, label, label_ptr, bn);
/* lazy barrier init */
libxsmm_barrier_init( cfg.barrier, ltid );
for ( i = nc_thr_begin; i < nc_thr_end; ++i ) {
libxsmm_bfloat16_hp in;
in.i[0] = 0;
in.i[1] = pinput_bf16[i];
pinput_fp32[i] = in.f;
}
libxsmm_barrier_wait( cfg.barrier, ltid );
for ( i = n_thr_begin; i < n_thr_end; ++i ) {
float max = FLT_MIN;
float sum_of_exp = 0.0f;
img1 = i/bn;
img2 = i%bn;
/* set output to input and set compute max per image */
for ( ifm1 = 0; ifm1 < Bc; ++ifm1 ) {
for ( ifm2 = 0; ifm2 < bc; ++ifm2 ) {
LIBXSMM_VLA_ACCESS( 4, output, img1, ifm1, img2, ifm2, Bc, bn, bc ) = LIBXSMM_VLA_ACCESS( 4, input, img1, ifm1, img2, ifm2, Bc, bn, bc );
if ( LIBXSMM_VLA_ACCESS( 4, input, img1, ifm1, img2, ifm2, Bc, bn, bc ) > max ) {
max = LIBXSMM_VLA_ACCESS( 4, input, img1, ifm1, img2, ifm2, Bc, bn, bc );
}
}
}
/* sum exp over outputs */
for ( ifm1 = 0; ifm1 < Bc; ++ifm1 ) {
for ( ifm2 = 0; ifm2 < bc; ++ifm2 ) {
LIBXSMM_VLA_ACCESS( 4, output, img1, ifm1, img2, ifm2, Bc, bn, bc ) = (float)exp( (double)(LIBXSMM_VLA_ACCESS( 4, output, img1, ifm1, img2, ifm2, Bc, bn, bc ) - max) );
sum_of_exp += LIBXSMM_VLA_ACCESS( 4, output, img1, ifm1, img2, ifm2, Bc, bn, bc );
}
}
/* scale output */
sum_of_exp = 1.0f/sum_of_exp;
for ( ifm1 = 0; ifm1 < Bc; ++ifm1 ) {
for ( ifm2 = 0; ifm2 < bc; ++ifm2 ) {
LIBXSMM_VLA_ACCESS( 4, output, img1, ifm1, img2, ifm2, Bc, bn, bc ) = LIBXSMM_VLA_ACCESS( 4, output, img1, ifm1, img2, ifm2, Bc, bn, bc ) * sum_of_exp;
}
}
}
libxsmm_barrier_wait( cfg.barrier, ltid );
/* calculate loss single threaded */
if ( ltid == 0 ) {
(*loss) = 0.0f;
for ( img1 = 0; img1 < Bn; ++img1 ) {
for ( img2 = 0; img2 <bn; ++img2 ) {
libxsmm_blasint ifm = (libxsmm_blasint)LIBXSMM_VLA_ACCESS( 2, label, img1, img2, bn );
libxsmm_blasint ifm1b = ifm/bc;
libxsmm_blasint ifm2b = ifm%bc;
float val = ( LIBXSMM_VLA_ACCESS( 4, output, img1, ifm1b, img2, ifm2b, Bc, bn, bc ) > FLT_MIN ) ? LIBXSMM_VLA_ACCESS( 4, output, img1, ifm1b, img2, ifm2b, Bc, bn, bc ) : FLT_MIN;
*loss = LIBXSMM_LOGF( val );
}
}
*loss = ((-1.0f)*(*loss))/cfg.N;
}
libxsmm_barrier_wait( cfg.barrier, ltid );
for ( i = nc_thr_begin; i < nc_thr_end; ++i ) {
libxsmm_bfloat16_hp in;
in.f = poutput_fp32[i];
poutput_bf16[i] = in.i[1];
}
libxsmm_barrier_wait( cfg.barrier, ltid );
}
void my_smax_bwd_exec( my_smax_bwd_config cfg, libxsmm_bfloat16* delin_act_ptr, const libxsmm_bfloat16* out_act_ptr, const int* label_ptr, int start_tid, int my_tid, void* scratch ) {
libxsmm_blasint bn = cfg.bn;
libxsmm_blasint Bn = cfg.N/cfg.bn;
libxsmm_blasint bc = cfg.bc;
libxsmm_blasint Bc = cfg.C/cfg.bc;
/* loop counters */
libxsmm_blasint i = 0;
libxsmm_blasint img1, img2, ifm1, ifm2;
float rcp_N = 1.0f/cfg.N;
/* computing first logical thread */
const libxsmm_blasint ltid = my_tid - start_tid;
/* number of tasks that could run in parallel for the batch */
const libxsmm_blasint n_work = Bn * bn;
/* compute chunk size */
const libxsmm_blasint n_chunksize = (n_work % cfg.threads == 0) ? (n_work / cfg.threads) : ((n_work / cfg.threads) + 1);
/* compute thr_begin and thr_end */
const libxsmm_blasint n_thr_begin = (ltid * n_chunksize < n_work) ? (ltid * n_chunksize) : n_work;
const libxsmm_blasint n_thr_end = ((ltid + 1) * n_chunksize < n_work) ? ((ltid + 1) * n_chunksize) : n_work;
/* number of tasks that could run in parallel for the batch */
const int nc_work = Bn * bn;
/* compute chunk size */
const int nc_chunksize = (nc_work % cfg.threads == 0) ? (nc_work / cfg.threads) : ((nc_work / cfg.threads) + 1);
/* compute thr_begin and thr_end */
const int nc_thr_begin = (ltid * nc_chunksize < nc_work) ? (ltid * nc_chunksize) : nc_work;
const int nc_thr_end = ((ltid + 1) * nc_chunksize < nc_work) ? ((ltid + 1) * nc_chunksize) : nc_work;
const libxsmm_bfloat16* poutput_bf16 = out_act_ptr;
libxsmm_bfloat16* pdinput_bf16 = delin_act_ptr;
float* poutput_fp32 = (float*)scratch;
float* pdinput_fp32 = ((float*)scratch)+(cfg.N*cfg.C);
LIBXSMM_VLA_DECL(4, const float, output, poutput_fp32, Bc, bn, bc);
LIBXSMM_VLA_DECL(4, float, dinput, pdinput_fp32, Bc, bn, bc);
LIBXSMM_VLA_DECL(2, const int, label, label_ptr, bn);
/* lazy barrier init */
libxsmm_barrier_init( cfg.barrier, ltid );
for ( i = nc_thr_begin; i < nc_thr_end; ++i ) {
libxsmm_bfloat16_hp out;
out.i[0] = 0;
out.i[1] = poutput_bf16[i];
poutput_fp32[i] = out.f;
}
libxsmm_barrier_wait( cfg.barrier, ltid );
for ( i = n_thr_begin; i < n_thr_end; ++i ) {
img1 = i/bn;
img2 = i%bn;
/* set output to input and set compute max per image */
for ( ifm1 = 0; ifm1 < Bc; ++ifm1 ) {
for ( ifm2 = 0; ifm2 < bc; ++ifm2 ) {
if ( (ifm1*Bc)+ifm2 == (libxsmm_blasint)LIBXSMM_VLA_ACCESS( 2, label, img1, img2, bn ) ) {
LIBXSMM_VLA_ACCESS( 4, dinput, img1, ifm1, img2, ifm2, Bc, bn, bc ) =
( LIBXSMM_VLA_ACCESS( 4, output, img1, ifm1, img2, ifm2, Bc, bn, bc ) - 1.0f ) * rcp_N * cfg.loss_weight;
} else {
LIBXSMM_VLA_ACCESS( 4, dinput, img1, ifm1, img2, ifm2, Bc, bn, bc ) =
LIBXSMM_VLA_ACCESS( 4, output, img1, ifm1, img2, ifm2, Bc, bn, bc ) * rcp_N * cfg.loss_weight;
}
}
}
}
libxsmm_barrier_wait( cfg.barrier, ltid );
for ( i = nc_thr_begin; i < nc_thr_end; ++i ) {
libxsmm_bfloat16_hp in;
in.f = pdinput_fp32[i];
pdinput_bf16[i] = in.i[1];
}
libxsmm_barrier_wait( cfg.barrier, ltid );
}
void *numa_alloc_onnode_aligned(size_t size, int numa_node, int alignment_) {
#if 0
int alignment = alignment_ - 1;
size_t adj_size = sizeof(size_t) + alignment;
void *r_ptr = NULL;
void *t_ptr = numa_alloc_onnode(size + adj_size, numa_node);
if (t_ptr == NULL) return NULL;
r_ptr = (void *)(((size_t)t_ptr + adj_size) & ~alignment);
*((size_t*)r_ptr - 1) = (size_t)r_ptr - (size_t)t_ptr;
return r_ptr;
#else
return numa_alloc_onnode(size, numa_node);
#endif
}
void numa_free_aligned(void *ptr, size_t size) {
#if 0
if (ptr == NULL) return;
void *t_ptr = (void*)((size_t*)ptr - *((size_t*)ptr - 1));
numa_free(t_ptr, size);
#else
numa_free(ptr, size);
#endif
}
int setup_my_numa(my_numa_thr_cfg **numa_thr_cfg_, int num_layers, int n_threads) {
int max_nodes = numa_max_node() + 1;
int max_cfg_nodes = numa_num_configured_nodes();
int max_cfg_cpus = numa_num_configured_cpus();
int max_task_cpus = numa_num_task_cpus();
my_numa_thr_cfg *numa_thr_cfg = (my_numa_thr_cfg *) malloc(sizeof(my_numa_thr_cfg) * max_cfg_nodes);
printf("FWD NUMA configuration:\n");
printf("There are %d numa nodes on the system\n", max_nodes);
printf("There are %d configured numa nodes on the system\n", max_cfg_nodes);
printf("There are %d configured CPUs on the system\n", max_cfg_cpus);
printf("There are %d CPUs asigned for the current task\n", max_task_cpus);
struct bitmask* bmask = numa_bitmask_alloc(max_cfg_cpus);
int thr_count = 0, i = 0;
for (i = 0; i < max_cfg_nodes; i++) {
numa_node_to_cpus(i, bmask);
numa_thr_cfg[i].scratch = (libxsmm_bfloat16**) malloc(sizeof(libxsmm_bfloat16*) * num_layers);
numa_thr_cfg[i].layer_size = (size_t*)malloc(sizeof(size_t)*num_layers);
numa_thr_cfg[i].blocksOFm_s = (int*)malloc(sizeof(int)*num_layers);
numa_thr_cfg[i].blocksOFm_e = (int*)malloc(sizeof(int)*num_layers);
/*
printf("@@@@@ node %d size %zd cpus ", i, bmask->size);
size_t j = 0;
for(j = 0; j < bmask->size; j++)
printf("%d", numa_bitmask_isbitset(bmask, j));
printf("\n");
*/
int num_threads_in_mask = 0;
int t = 0;
for (t = 0; t < bmask->size; t++)
if (numa_bitmask_isbitset(bmask, t)) num_threads_in_mask++;
int node_threads = 0;
while(thr_count < n_threads && node_threads < num_threads_in_mask) {
if (numa_bitmask_isbitset(bmask, thr_count)) {
numa_thr_cfg[i].thr_s = thr_count;
break;
}
thr_count++; node_threads++;
}
while(thr_count < n_threads && node_threads < num_threads_in_mask) {
if (numa_bitmask_isbitset(bmask, thr_count))
numa_thr_cfg[i].thr_e = thr_count;
thr_count++; node_threads++;
}
}
*numa_thr_cfg_ = numa_thr_cfg;
return 1;
}
int setup_my_numa_fwd(my_numa_thr_cfg **numa_thr_cfg_, int num_layers, my_fc_fwd_config* my_fc_fwd) {
my_numa_thr_cfg *numa_thr_cfg = *numa_thr_cfg_;
int max_cfg_nodes = numa_num_configured_nodes();
int i = 0;
for (i = 0; i < max_cfg_nodes; i++) {
int l = 0;
for (l = 0; l < num_layers; l++) {
if (my_fc_fwd[l].fwd_bf > 1) {
printf("@@@ NUMA ERROR: doesn't support this configuration\n");
return -1;
}
int thr = 0;
const libxsmm_blasint nBlocksOFm = my_fc_fwd[l].K / my_fc_fwd[l].bk;
const libxsmm_blasint nBlocksMB = my_fc_fwd[l].N / my_fc_fwd[l].bn;
if (my_fc_fwd[l].fwd_2d_blocking == 1) {
libxsmm_blasint row_teams = my_fc_fwd[l].fwd_row_teams;
libxsmm_blasint M_tasks_per_thread = LIBXSMM_UPDIV(nBlocksOFm, row_teams);
numa_thr_cfg[i].blocksOFm_s[l] = nBlocksOFm;
numa_thr_cfg[i].blocksOFm_e[l] = 0;
for (thr = numa_thr_cfg[i].thr_s; thr <= numa_thr_cfg[i].thr_e
&& numa_thr_cfg[i].thr_s != numa_thr_cfg[i].thr_e; thr++) {
libxsmm_blasint my_row_id = thr % row_teams; /* ltid */
libxsmm_blasint my_M_start = LIBXSMM_MIN(my_row_id * M_tasks_per_thread, nBlocksOFm);
libxsmm_blasint my_M_end = LIBXSMM_MIN((my_row_id+1) * M_tasks_per_thread, nBlocksOFm);
numa_thr_cfg[i].blocksOFm_s[l] = (my_M_start <= numa_thr_cfg[i].blocksOFm_s[l])
? my_M_start
: numa_thr_cfg[i].blocksOFm_s[l];
numa_thr_cfg[i].blocksOFm_e[l] = (my_M_end >= numa_thr_cfg[i].blocksOFm_e[l])
? my_M_end
: numa_thr_cfg[i].blocksOFm_e[l];
}
} else {
numa_thr_cfg[i].blocksOFm_s[l] = nBlocksOFm;
numa_thr_cfg[i].blocksOFm_e[l] = 0;
for (thr = numa_thr_cfg[i].thr_s; thr <= numa_thr_cfg[i].thr_e
&& numa_thr_cfg[i].thr_s != numa_thr_cfg[i].thr_e; thr++) {
const libxsmm_blasint work = nBlocksOFm * nBlocksMB;
const libxsmm_blasint chunksize = (work % my_fc_fwd[l].threads == 0) ?
(work / my_fc_fwd[l].threads) : ((work / my_fc_fwd[l].threads) + 1);
const libxsmm_blasint thr_begin = (thr * chunksize < work) ? (thr * chunksize) : work;
const libxsmm_blasint thr_end = ((thr + 1) * chunksize < work) ? ((thr + 1) * chunksize) : work;
int ofm_s = thr_begin / nBlocksMB;
int ofm_e = thr_end / nBlocksMB;
numa_thr_cfg[i].blocksOFm_s[l] = (ofm_s <= numa_thr_cfg[i].blocksOFm_s[l])
? ofm_s
: numa_thr_cfg[i].blocksOFm_s[l];
numa_thr_cfg[i].blocksOFm_e[l] = (ofm_e >= numa_thr_cfg[i].blocksOFm_e[l])
? ofm_e
: numa_thr_cfg[i].blocksOFm_e[l];
}
}
}
}
return 1;
}
int allocate_numa_buffers_fwd(my_numa_thr_cfg **numa_thr_cfg_, int num_layers, my_fc_fwd_config* my_fc_fwd) {
my_numa_thr_cfg *numa_thr_cfg = *numa_thr_cfg_;
int max_cfg_nodes = numa_num_configured_nodes();
int i = 0, l = 0;
for (i = 0; i < max_cfg_nodes; i++) {
for (l = 0; l < num_layers; l++) {
const libxsmm_blasint nBlocksIFm = my_fc_fwd[l].C / my_fc_fwd[l].bc;
const libxsmm_blasint BOFM_shift = nBlocksIFm * my_fc_fwd[l].bc * my_fc_fwd[l].bk;
int l_nBlocksOFm = (numa_thr_cfg[i].blocksOFm_e[l] - numa_thr_cfg[i].blocksOFm_s[l]) + 1;
if (l_nBlocksOFm <= 0)
continue;
numa_thr_cfg[i].layer_size[l] = sizeof(libxsmm_bfloat16) * ((l_nBlocksOFm) * BOFM_shift);
numa_thr_cfg[i].scratch[l] = (libxsmm_bfloat16*)numa_alloc_onnode_aligned(numa_thr_cfg[i].layer_size[l], i, 2097152);
if (numa_thr_cfg[i].scratch[l] == NULL) {
printf("@@@ NUMA ERROR: cannot allocate on node #%d\n", i);
return -1;
}
}
}
return 1;
}
int copy_to_numa_buffers_fwd_inf(my_numa_thr_cfg **numa_thr_cfg_, int num_layers, my_fc_fwd_config* my_fc_fwd, libxsmm_bfloat16 **fil_libxsmm) {
my_numa_thr_cfg *numa_thr_cfg = *numa_thr_cfg_;
int max_cfg_nodes = numa_num_configured_nodes();
int i, l;
#pragma omp parallel for collapse(2) private (i,l)
for (i = 0; i < max_cfg_nodes; i++) {
for (l = 0; l < num_layers; l++) {
const libxsmm_blasint nBlocksIFm = my_fc_fwd[l].C / my_fc_fwd[l].bc;
const libxsmm_blasint BOFM_shift = nBlocksIFm * my_fc_fwd[l].bc * my_fc_fwd[l].bk;
int l_nBlocksOFm = (numa_thr_cfg[i].blocksOFm_e[l] - numa_thr_cfg[i].blocksOFm_s[l]) + 1;
int j = 0;
for (j = 0; j < l_nBlocksOFm ; j++) {
size_t l_BOFM_shift = j * BOFM_shift;
libxsmm_bfloat16 *out = numa_thr_cfg[i].scratch[l] + l_BOFM_shift;
libxsmm_bfloat16 *inp = fil_libxsmm[l] + numa_thr_cfg[i].blocksOFm_s[l] * BOFM_shift + l_BOFM_shift;
memcpy(out, inp, sizeof(libxsmm_bfloat16) * nBlocksIFm * my_fc_fwd[l].bc * my_fc_fwd[l].bk);
}
}
}
return 1;
}
int main(int argc, char* argv[])
{
libxsmm_bfloat16 **act_libxsmm, **fil_libxsmm, **delact_libxsmm, **delfil_libxsmm;
libxsmm_bfloat16 **bias_libxsmm, **delbias_libxsmm;
float **fil_master;
unsigned char **relumask_libxsmm;
int *label_libxsmm;
my_eltwise_fuse my_fuse;
my_fc_fwd_config* my_fc_fwd;
my_fc_bwd_config* my_fc_bwd;
my_opt_config* my_opt;
my_smax_fwd_config my_smax_fwd;
my_smax_bwd_config my_smax_bwd;
void* scratch = NULL;
size_t scratch_size = 0;
#ifdef CHECK_L1
float *last_act_fwd_f32 = NULL;
float *first_wt_bwdupd_f32 = NULL;
#endif
/* some parameters we can overwrite via cli,
default is some inner layer of overfeat */
int iters = 10; /* repetitions of benchmark */
int MB = 32; /* mini-batch size, "N" */
int fuse_type = 0; /* 0: nothing fused, 1: relu fused, 2: elementwise fused, 3: relu and elementwise fused */
char type = 'A'; /* 'A': ALL, 'F': FP, 'B': BP */
int bn = 64;
int bk = 64;
int bc = 64;
int *C; /* number of input feature maps, "C" */
int num_layers = 0;
const char *const env_check = getenv("CHECK");
const double check = LIBXSMM_ABS(0 == env_check ? 1 : atof(env_check));
#if defined(_OPENMP)
int nThreads = omp_get_max_threads(); /* number of threads */
#else
int nThreads = 1; /* number of threads */
#endif
unsigned long long l_start, l_end;
double l_total = 0.0;
double gflop = 0.0;
int i, j;
double act_size = 0.0;
double fil_size = 0.0;
float lr = 0.2f;
float loss_weight = 0.1f;
libxsmm_matdiff_info norms_fwd, norms_bwd, norms_upd, diff;
libxsmm_matdiff_clear(&norms_fwd);
libxsmm_matdiff_clear(&norms_bwd);
libxsmm_matdiff_clear(&norms_upd);
libxsmm_matdiff_clear(&diff);
if (argc > 1 && !strncmp(argv[1], "-h", 3)) {
printf("Usage: %s iters MB fuse_type type bn bk bc C1 C2 ... CN\n", argv[0]);
return 0;
}
libxsmm_rng_set_seed(1);
/* reading new values from cli */
i = 1;
num_layers = argc - 9;
if (argc > i) iters = atoi(argv[i++]);
if (argc > i) MB = atoi(argv[i++]);
if (argc > i) fuse_type = atoi(argv[i++]);
if (argc > i) type = *(argv[i++]);
if (argc > i) bn = atoi(argv[i++]);
if (argc > i) bk = atoi(argv[i++]);
if (argc > i) bc = atoi(argv[i++]);
/* allocate the number of channles buffer */
if ( num_layers < 1 ) {
printf("Usage: %s iters MB fuse_type type bn bk bc C1 C2 ... CN\n", argv[0]);
return 0;
}
C = (int*)malloc((num_layers+2)*sizeof(int));
for (j = 0 ; i < argc; ++i, ++j ) {
C[j] = atoi(argv[i]);
}
/* handle softmax config */
C[num_layers+1] = C[num_layers];
if (type != 'A' && type != 'F' && type != 'B') {
printf("type needs to be 'A' (All), 'F' (FP only), 'B' (BP only)\n");
return -1;
}
if ( (fuse_type < 0) || (fuse_type > 5) ) {
printf("fuse type needs to be 0 (None), 1 (Bias), 2 (ReLU), 3 (Sigmoid), 4 (Bias+ReLU), 5 (Bias+Sigmoid)\n");
return -1;
}
#if defined(__SSE3__)
_MM_SET_FLUSH_ZERO_MODE(_MM_FLUSH_ZERO_ON);
_MM_SET_DENORMALS_ZERO_MODE(_MM_DENORMALS_ZERO_ON);
_MM_SET_ROUNDING_MODE(_MM_ROUND_NEAREST);
#endif
/* print some summary */
printf("##########################################\n");
printf("# Setting Up (Common) #\n");
printf("##########################################\n");
printf("PARAMS: N:%d\n", MB);
printf("PARAMS: Layers: %d\n", num_layers);
printf("PARAMS: ITERS:%d", iters); if (LIBXSMM_FEQ(0, check)) printf(" Threads:%d\n", nThreads); else printf("\n");
for (i = 0; i < num_layers; ++i ) {
if (i == 0) {
act_size += (double)(MB*C[i]*sizeof(libxsmm_bfloat16))/(1024.0*1024.0);
printf("SIZE Activations %i (%dx%d): %10.2f MiB\n", i, MB, C[i], (double)(MB*C[i]*sizeof(libxsmm_bfloat16))/(1024.0*1024.0) );
}
act_size += (double)(MB*C[i+1]*sizeof(libxsmm_bfloat16))/(1024.0*1024.0);
fil_size += (double)(C[i]*C[i+1]*sizeof(libxsmm_bfloat16))/(1024.0*1024.0);
printf("SIZE Filter %i (%dx%d): %10.2f MiB\n", i, C[i], C[i+1], (double)(C[i]*C[i+1]*sizeof(libxsmm_bfloat16))/(1024.0*1024.0) );
printf("SIZE Activations %i (%dx%d): %10.2f MiB\n", i+1, MB, C[i+1], (double)(MB*C[i+1]*sizeof(libxsmm_bfloat16))/(1024.0*1024.0) );
}
act_size += (double)(MB*C[num_layers+1]*sizeof(float))/(1024.0*1024.0);
printf("SIZE Activations softmax (%dx%d): %10.2f MiB\n", MB, C[num_layers+1], (double)(MB*C[num_layers+1]*sizeof(libxsmm_bfloat16))/(1024.0*1024.0) );
printf("\nTOTAL SIZE Activations: %10.2f MiB\n", act_size );
printf("TOTAL SIZE Filter (incl. master): %10.2f MiB\n", 3.0*fil_size );
printf("TOTAL SIZE delActivations: %10.2f MiB\n", act_size );
printf("TOTAL SIZE delFilter: %10.2f MiB\n", fil_size );
printf("TOTAL SIZE MLP: %10.2f MiB\n", (4.0*fil_size) + (2.0*act_size) );
/* allocate data */
act_libxsmm = (libxsmm_bfloat16**)malloc( (num_layers+2)*sizeof(libxsmm_bfloat16*) );
delact_libxsmm = (libxsmm_bfloat16**)malloc( (num_layers+1)*sizeof(libxsmm_bfloat16*) );
for ( i = 0 ; i < num_layers+2; ++i ) {
#ifdef ACT_NUMA_INTERLEAVED
act_libxsmm[i] = (libxsmm_bfloat16*)numa_alloc_interleaved( MB*C[i]*sizeof(libxsmm_bfloat16));
#else
act_libxsmm[i] = (libxsmm_bfloat16*)libxsmm_aligned_malloc( MB*C[i]*sizeof(libxsmm_bfloat16), 2097152);
#endif
/* softmax has no incoming gradients */
if ( i < num_layers+1 ) {
delact_libxsmm[i] = (libxsmm_bfloat16*)libxsmm_aligned_malloc( MB*C[i]*sizeof(libxsmm_bfloat16), 2097152);
}
}
fil_master = (float**) malloc( num_layers*sizeof(float*) );
fil_libxsmm = (libxsmm_bfloat16**)malloc( num_layers*sizeof(libxsmm_bfloat16*) );
delfil_libxsmm = (libxsmm_bfloat16**)malloc( num_layers*sizeof(libxsmm_bfloat16*) );
for ( i = 0 ; i < num_layers; ++i ) {
fil_master[i] = (float*) libxsmm_aligned_malloc( C[i]*C[i+1]*sizeof(float), 2097152);
fil_libxsmm[i] = (libxsmm_bfloat16*)libxsmm_aligned_malloc( C[i]*C[i+1]*sizeof(libxsmm_bfloat16), 2097152);
delfil_libxsmm[i] = (libxsmm_bfloat16*)libxsmm_aligned_malloc( C[i]*C[i+1]*sizeof(libxsmm_bfloat16), 2097152);
}
bias_libxsmm = (libxsmm_bfloat16**)malloc( num_layers*sizeof(libxsmm_bfloat16*) );
delbias_libxsmm = (libxsmm_bfloat16**)malloc( num_layers*sizeof(libxsmm_bfloat16*) );
for ( i = 0 ; i < num_layers; ++i ) {
bias_libxsmm[i] = (libxsmm_bfloat16*)libxsmm_aligned_malloc( C[i+1]*sizeof(libxsmm_bfloat16), 2097152);
delbias_libxsmm[i] = (libxsmm_bfloat16*)libxsmm_aligned_malloc( C[i+1]*sizeof(libxsmm_bfloat16), 2097152);
}
relumask_libxsmm = (unsigned char**)malloc( num_layers*sizeof(unsigned char*) );
for ( i = 0 ; i < num_layers; ++i ) {
relumask_libxsmm[i] = (unsigned char*)libxsmm_aligned_malloc( MB*C[i+1]*sizeof(unsigned char), 2097152);
}
label_libxsmm = (int*)libxsmm_aligned_malloc( MB*sizeof(int), 2097152);
/* init data */
for ( i = 0 ; i < num_layers+2; ++i ) {
my_init_buf_bf16( act_libxsmm[i], MB*C[i], 0, 0 );
}
for ( i = 0 ; i < num_layers+1; ++i ) {
my_init_buf_bf16( delact_libxsmm[i], MB*C[i], 0, 0 );
}
for ( i = 0 ; i < num_layers; ++i ) {
#if 0
{
float *cur_fil = (float*) malloc(C[i]*C[i+1]*sizeof(float));
my_init_buf( cur_fil, C[i]*C[i+1], 0, 0 );
my_matrix_copy_KCCK_to_KCCK_vnni(cur_fil, fil_master[i], C[i], C[i+1], bc, bk);
libxsmm_rne_convert_fp32_bf16( fil_master[i], fil_libxsmm[i], C[i]*C[i+1] );
free(cur_fil);
}
#else
my_init_buf( fil_master[i], C[i]*C[i+1], 0, 0 );
libxsmm_rne_convert_fp32_bf16( fil_master[i], fil_libxsmm[i], C[i]*C[i+1] );
#endif
}
for ( i = 0 ; i < num_layers; ++i ) {
#if 0
float *cur_fil = (float*) malloc(C[i]*C[i+1]*sizeof(float));
float *cur_fil_vnni = (float*) malloc(C[i]*C[i+1]*sizeof(float));
my_init_buf( cur_fil, C[i]*C[i+1], 0, 0 );
my_matrix_copy_KCCK_to_KCCK_vnni(cur_fil, cur_fil_vnni, C[i], C[i+1], bc, bk);
libxsmm_rne_convert_fp32_bf16( cur_fil_vnni, delfil_libxsmm[i], C[i]*C[i+1] );
free(cur_fil);
free(cur_fil_vnni);
#else
my_init_buf_bf16( delfil_libxsmm[i], C[i]*C[i+1], 0, 0 );
#endif
}
for ( i = 0 ; i < num_layers; ++i ) {
my_init_buf_bf16( bias_libxsmm[i], C[i+1], 0, 0 );
}
for ( i = 0 ; i < num_layers; ++i ) {
my_init_buf_bf16( delbias_libxsmm[i], C[i+1], 0, 0 );
}
for ( i = 0 ; i < num_layers; ++i ) {
zero_buf_uint8( relumask_libxsmm[i], MB*C[i+1] );
}
zero_buf_int32( label_libxsmm, MB );
printf("\n");
printf("##########################################\n");
printf("# Setting Up (custom-Storage) #\n");
printf("##########################################\n");
if ( fuse_type == 0 ) {
my_fuse = MY_ELTWISE_FUSE_NONE;
} else if ( fuse_type == 1 ) {
my_fuse = MY_ELTWISE_FUSE_BIAS;
} else if ( fuse_type == 2 ) {
my_fuse = MY_ELTWISE_FUSE_RELU;
} else if ( fuse_type == 4 ) {
my_fuse = MY_ELTWISE_FUSE_BIAS_RELU;
} else {
my_fuse = MY_ELTWISE_FUSE_NONE;
}
/* allocating handles */
my_fc_fwd = (my_fc_fwd_config*) malloc( num_layers*sizeof(my_fc_fwd_config) );
my_fc_bwd = (my_fc_bwd_config*) malloc( num_layers*sizeof(my_fc_bwd_config) );
my_opt = (my_opt_config*) malloc( num_layers*sizeof(my_opt_config) );
/* setting up handles + scratch */
for ( i = 0; i < num_layers; ++i ) {
my_fc_fwd[i] = setup_my_fc_fwd(MB, C[i], C[i+1], (MB % bn == 0) ? bn : MB,
(C[i ] % bc == 0) ? bc : C[i ],
(C[i+1] % bk == 0) ? bk : C[i+1],
nThreads, my_fuse);
my_fc_bwd[i] = setup_my_fc_bwd(MB, C[i], C[i+1], (MB % bn == 0) ? bn : MB,
(C[i ] % bc == 0) ? bc : C[i ],
(C[i+1] % bk == 0) ? bk : C[i+1],
nThreads, my_fuse);
my_opt[i] = setup_my_opt( C[i], C[i+1], (C[i ] % bc == 0) ? bc : C[i ],
(C[i+1] % bk == 0) ? bk : C[i+1],
nThreads, lr );
/* let's allocate and bind scratch */
if ( my_fc_fwd[i].scratch_size > 0 || my_fc_bwd[i].scratch_size > 0 || my_opt[i].scratch_size > 0 ) {
size_t alloc_size = LIBXSMM_MAX( LIBXSMM_MAX( my_fc_fwd[i].scratch_size, my_fc_bwd[i].scratch_size), my_opt[i].scratch_size );
if ( alloc_size > scratch_size ) {
if ( scratch != NULL ) libxsmm_free( scratch );
scratch_size = alloc_size;
scratch = libxsmm_aligned_scratch( scratch_size, 2097152 );
my_init_buf( (float*)(scratch), (scratch_size)/4, 0, 0 );
}
}
}
/* softmax+loss is treated as N+! layer */
my_smax_fwd = setup_my_smax_fwd( MB, C[num_layers+1], (MB % bn == 0) ? bn : MB,
(C[num_layers+1] % bk == 0) ? bk : C[num_layers+1],
nThreads );
my_smax_bwd = setup_my_smax_bwd( MB, C[num_layers+1], (MB % bn == 0) ? bn : MB,
(C[num_layers+1] % bk == 0) ? bk : C[num_layers+1],
nThreads, loss_weight );
if ( my_smax_fwd.scratch_size > 0 || my_smax_bwd.scratch_size > 0 ) {
size_t alloc_size = LIBXSMM_MAX( my_smax_fwd.scratch_size, my_smax_bwd.scratch_size );
if ( alloc_size > scratch_size ) {
if ( scratch != NULL ) libxsmm_free( scratch );
scratch_size = alloc_size;
scratch = libxsmm_aligned_scratch( scratch_size, 2097152 );
my_init_buf( (float*)(scratch), (scratch_size)/4, 0, 0 );
}
}
my_numa_thr_cfg *numa_thr_cfg;
setup_my_numa(&numa_thr_cfg, num_layers, nThreads);
if ( type == 'F') {
printf("##########################################\n");
printf("# Performance - FWD (custom-Storage) #\n");
printf("##########################################\n");
setup_my_numa_fwd(&numa_thr_cfg, num_layers, my_fc_fwd);
allocate_numa_buffers_fwd(&numa_thr_cfg, num_layers, my_fc_fwd);
l_start = libxsmm_timer_tick();
copy_to_numa_buffers_fwd_inf(&numa_thr_cfg, num_layers, my_fc_fwd, fil_libxsmm);
#if defined(_OPENMP)
# pragma omp parallel private(i,j)
#endif
{
#if defined(_OPENMP)
const int tid = omp_get_thread_num();
#else
const int tid = 0;
#endif
const int numa_node = numa_node_of_cpu(tid);
for (j = 0; j < iters; ++j) {
for ( i = 0; i < num_layers; ++i) {
libxsmm_bfloat16 *filt = numa_thr_cfg[numa_node].scratch[i];
my_fc_fwd_exec( my_fc_fwd[i], filt, act_libxsmm[i], act_libxsmm[i+1],
bias_libxsmm[i], relumask_libxsmm[i], 0, tid, scratch, &numa_thr_cfg[numa_node], i);
}
#ifdef USE_SOFTMAX
my_smax_fwd_exec( my_smax_fwd, act_libxsmm[num_layers], act_libxsmm[num_layers+1], label_libxsmm, &loss,
0, tid, scratch );
#endif
}
}
l_end = libxsmm_timer_tick();
l_total = libxsmm_timer_duration(l_start, l_end);
gflop = 0.0;
for ( i = 0; i < num_layers; ++i) {
gflop += (2.0*(double)MB*(double)C[i]*(double)C[i+1]*(double)iters) / (1000.0*1000.0*1000.0);
}
printf("GFLOP = %.5g\n", gflop/(double)iters);
printf("fp time = %.5g\n", ((double)(l_total/iters)));
printf("GFLOPS = %.5g\n", gflop/l_total);
printf("PERFDUMP,FP,%s,%i,%i,", LIBXSMM_VERSION, nThreads, MB );
for ( i = 0; i < num_layers; ++i ) {
printf("%i,", C[i] );
}
printf("%f,%f\n", ((double)(l_total/iters)), gflop/l_total);
/* Print some norms on last act for fwd and weights of first layer after all iterations */
last_act_fwd_f32 = (float*) malloc(MB*C[num_layers]*sizeof(float));
libxsmm_convert_bf16_f32( act_libxsmm[num_layers], last_act_fwd_f32, MB*C[num_layers]);
libxsmm_matdiff(&norms_fwd, LIBXSMM_DATATYPE_F32, MB*C[num_layers], 1, last_act_fwd_f32, last_act_fwd_f32, 0, 0);
printf("L1 of act[num_layers] : %.25g\n", norms_fwd.l1_ref);
}
if (type == 'B') {
printf("##########################################\n");
printf("# Performance - BWD (custom-Storage) #\n");
printf("##########################################\n");
l_start = libxsmm_timer_tick();
#if defined(_OPENMP)
# pragma omp parallel private(i,j)
#endif
{
#if defined(_OPENMP)
const int tid = omp_get_thread_num();
#else
const int tid = 0;
#endif
for (j = 0; j < iters; ++j) {
#ifdef USE_SOFTMAX
my_smax_bwd_exec( my_smax_bwd, delact_libxsmm[num_layers], act_libxsmm[num_layers+1], label_libxsmm,
0, tid, scratch );
#endif
for ( i = num_layers-1; i > 0; --i) {
my_fc_bwd_exec( my_fc_bwd[i], fil_libxsmm[i], delact_libxsmm[i], delact_libxsmm[i+1], delfil_libxsmm[i],
act_libxsmm[i], delbias_libxsmm[i], relumask_libxsmm[i], MY_PASS_BWD, 0, tid, scratch );
my_opt_exec( my_opt[i], fil_libxsmm[i], fil_master[i], delfil_libxsmm[i], 0, tid, scratch );
}
my_fc_bwd_exec( my_fc_bwd[0], fil_libxsmm[0], delact_libxsmm[0], delact_libxsmm[0+1], delfil_libxsmm[0],
act_libxsmm[0], delbias_libxsmm[0], relumask_libxsmm[0], MY_PASS_BWD_W, 0, tid, scratch );
my_opt_exec( my_opt[0], fil_libxsmm[0], fil_master[0], delfil_libxsmm[0], 0, tid, scratch );
}
}
l_end = libxsmm_timer_tick();
l_total = libxsmm_timer_duration(l_start, l_end);
gflop = 0.0;
for ( i = num_layers-1; i > 0; --i) {
gflop += (4.0*(double)MB*(double)C[i]*(double)C[i+1]*(double)iters) / (1000.0*1000.0*1000.0);
}
gflop += (2.0*(double)MB*(double)C[0]*(double)C[1]*(double)iters) / (1000.0*1000.0*1000.0);
printf("GFLOP = %.5g\n", gflop/(double)iters);
printf("fp time = %.5g\n", ((double)(l_total/iters)));
printf("GFLOPS = %.5g\n", gflop/l_total);
printf("PERFDUMP,BP,%s,%i,%i,", LIBXSMM_VERSION, nThreads, MB );
for ( i = 0; i < num_layers; ++i ) {
printf("%i,", C[i] );
}
printf("%f,%f\n", ((double)(l_total/iters)), gflop/l_total);
}
if (type == 'A') {
printf("#########################################################\n");
printf("# Unimplemented: Performance - FWD-BWD (custom-Storage) #\n");
printf("#########################################################\n");
exit(-1);
l_start = libxsmm_timer_tick();
#if defined(_OPENMP)
# pragma omp parallel private(i,j)
#endif
{
#if defined(_OPENMP)
const int tid = omp_get_thread_num();
#else
const int tid = 0;
#endif
for (j = 0; j < iters; ++j) {
for ( i = 0; i < num_layers; ++i) {
my_fc_fwd_exec( my_fc_fwd[i], fil_libxsmm[i], act_libxsmm[i], act_libxsmm[i+1],
bias_libxsmm[i], relumask_libxsmm[i], 0, tid, scratch, NULL, 0);
}
#ifdef USE_SOFTMAX
my_smax_fwd_exec( my_smax_fwd, act_libxsmm[num_layers], act_libxsmm[num_layers+1], label_libxsmm, &loss,
0, tid, scratch );
my_smax_bwd_exec( my_smax_bwd, delact_libxsmm[num_layers], act_libxsmm[num_layers+1], label_libxsmm,
0, tid, scratch );
#endif
for ( i = num_layers-1; i > 0; --i) {
my_fc_bwd_exec( my_fc_bwd[i], fil_libxsmm[i], delact_libxsmm[i], delact_libxsmm[i+1], delfil_libxsmm[i],
act_libxsmm[i], delbias_libxsmm[i], relumask_libxsmm[i], MY_PASS_BWD, 0, tid, scratch );
my_opt_exec( my_opt[i], fil_libxsmm[i], fil_master[i], delfil_libxsmm[i], 0, tid, scratch );
}
my_fc_bwd_exec( my_fc_bwd[0], fil_libxsmm[0], delact_libxsmm[0], delact_libxsmm[0+1], delfil_libxsmm[0],
act_libxsmm[0], delbias_libxsmm[0], relumask_libxsmm[0], MY_PASS_BWD_W, 0, tid, scratch );
my_opt_exec( my_opt[0], fil_libxsmm[0], fil_master[0], delfil_libxsmm[0], 0, tid, scratch );
}
}
l_end = libxsmm_timer_tick();
l_total = libxsmm_timer_duration(l_start, l_end);
#ifdef CHECK_L1
/* Print some norms on last act for fwd and weights of first layer after all iterations */
last_act_fwd_f32 = (float*) malloc(MB*C[num_layers]*sizeof(float));
first_wt_bwdupd_f32 = (float*) malloc(C[0]*C[1]*sizeof(float));
libxsmm_convert_bf16_f32( act_libxsmm[num_layers], last_act_fwd_f32, MB*C[num_layers]);
#if 1
libxsmm_convert_bf16_f32( fil_libxsmm[0], first_wt_bwdupd_f32, C[0]*C[1]);
libxsmm_matdiff(&norms_fwd, LIBXSMM_DATATYPE_F32, MB*C[num_layers], 1, last_act_fwd_f32, last_act_fwd_f32, 0, 0);
printf("L1 of act[num_layers] : %.25g\n", norms_fwd.l1_ref);
libxsmm_matdiff_reduce(&diff, &norms_fwd);
libxsmm_matdiff(&norms_bwd, LIBXSMM_DATATYPE_F32, C[0]*C[1], 1, first_wt_bwdupd_f32, first_wt_bwdupd_f32, 0, 0);
printf("L1 of wt[0] : %.25g\n", norms_bwd.l1_ref);
libxsmm_matdiff_reduce(&diff, &norms_bwd);
#else
{
int e = 0;
FILE *fileAct, *fileWt;
float *ref_last_act_fwd_f32 = (float*) malloc(MB*C[num_layers]*sizeof(float));
float *ref_first_wt_bwdupd_f32 = (float*) malloc(C[0]*C[1]*sizeof(float));
float *ref_first_wt_bwdupd_f32_kc = (float*) malloc(C[0]*C[1]*sizeof(float));
libxsmm_bfloat16 *first_wt_bwdupd_bf16 = (libxsmm_bfloat16*) malloc(C[0]*C[1]*sizeof(libxsmm_bfloat16));
fileAct = fopen("acts.txt","r");
if (fileAct != NULL) {
int bufferLength = 255;
char buffer[bufferLength];
e = 0;
while(fgets(buffer, bufferLength, fileAct)) {
ref_last_act_fwd_f32[e] = atof(buffer);
e++;
}
fclose(fileAct);
}
/* compare */
libxsmm_matdiff(&norms_fwd, LIBXSMM_DATATYPE_F32, MB*C[num_layers], 1, ref_last_act_fwd_f32, last_act_fwd_f32, 0, 0);
printf("##########################################\n");
printf("# Correctness - Last fwd act #\n");
printf("##########################################\n");
printf("L1 reference : %.25g\n", norms_fwd.l1_ref);
printf("L1 test : %.25g\n", norms_fwd.l1_tst);
printf("L2 abs.error : %.24f\n", norms_fwd.l2_abs);
printf("L2 rel.error : %.24f\n", norms_fwd.l2_rel);
printf("Linf abs.error: %.24f\n", norms_fwd.linf_abs);
printf("Linf rel.error: %.24f\n", norms_fwd.linf_rel);
printf("Check-norm : %.24f\n", norms_fwd.normf_rel);
libxsmm_matdiff_reduce(&diff, &norms_fwd);
fileWt = fopen("weights.txt","r");
if (fileWt != NULL) {
int bufferLength = 255;
char buffer[bufferLength];
e = 0;
while(fgets(buffer, bufferLength, fileWt)) {
ref_first_wt_bwdupd_f32[e] = atof(buffer);
e++;
}
fclose(fileWt);
}
matrix_copy_KCCK_to_KC( ref_first_wt_bwdupd_f32, ref_first_wt_bwdupd_f32_kc, C[0], C[1], bc, bk );
matrix_copy_KCCK_to_KC_bf16( fil_libxsmm[0], first_wt_bwdupd_bf16, C[0], C[1], bc, bk );
libxsmm_convert_bf16_f32( first_wt_bwdupd_bf16, first_wt_bwdupd_f32, C[0]*C[1] );
/* compare */
libxsmm_matdiff(&norms_bwd, LIBXSMM_DATATYPE_F32, C[0]*C[1], 1, ref_first_wt_bwdupd_f32_kc, first_wt_bwdupd_f32, 0, 0);
printf("##########################################\n");
printf("# Correctness - First bwdupd wt #\n");
printf("##########################################\n");
printf("L1 reference : %.25g\n", norms_bwd.l1_ref);
printf("L1 test : %.25g\n", norms_bwd.l1_tst);
printf("L2 abs.error : %.24f\n", norms_bwd.l2_abs);
printf("L2 rel.error : %.24f\n", norms_bwd.l2_rel);
printf("Linf abs.error: %.24f\n", norms_bwd.linf_abs);
printf("Linf rel.error: %.24f\n", norms_bwd.linf_rel);
printf("Check-norm : %.24f\n", norms_bwd.normf_rel);
libxsmm_matdiff_reduce(&diff, &norms_bwd);
free(ref_last_act_fwd_f32);
free(ref_first_wt_bwdupd_f32);
free(ref_first_wt_bwdupd_f32_kc);
free(first_wt_bwdupd_bf16);
}
#endif
free(first_wt_bwdupd_f32);
free(last_act_fwd_f32);
#endif
gflop = 0.0;
for ( i = num_layers-1; i > 0; --i) {
gflop += (6.0*(double)MB*(double)C[i]*(double)C[i+1]*(double)iters) / (1000.0*1000.0*1000.0);
}
gflop += (4.0*(double)MB*(double)C[0]*(double)C[1]*(double)iters) / (1000.0*1000.0*1000.0);
printf("GFLOP = %.5g\n", gflop/(double)iters);
printf("fp time = %.5g\n", ((double)(l_total/iters)));
printf("GFLOPS = %.5g\n", gflop/l_total);
printf("PERFDUMP,BP,%s,%i,%i,", LIBXSMM_VERSION, nThreads, MB );
for ( i = 0; i < num_layers; ++i ) {
printf("%i,", C[i] );
}
printf("%f,%f\n", ((double)(l_total/iters)), gflop/l_total);
}
/* deallocate data */
if ( scratch != NULL ) {
libxsmm_free(scratch);
}
for ( i = 0; i < num_layers; ++i ) {
if ( i == 0 ) {
#ifdef ACT_NUMA_INTERLEAVED
numa_free(act_libxsmm[i], MB*C[i]*sizeof(libxsmm_bfloat16));
#else
libxsmm_free(act_libxsmm[i]);
#endif
libxsmm_free(delact_libxsmm[i]);
}
#ifdef ACT_NUMA_INTERLEAVED
numa_free(act_libxsmm[i+1], MB*C[i+1]*sizeof(libxsmm_bfloat16));
#else
libxsmm_free(act_libxsmm[i+1]);
#endif
libxsmm_free(delact_libxsmm[i+1]);
libxsmm_free(fil_libxsmm[i]);
libxsmm_free(delfil_libxsmm[i]);
libxsmm_free(bias_libxsmm[i]);
libxsmm_free(delbias_libxsmm[i]);
libxsmm_free(relumask_libxsmm[i]);
libxsmm_free(fil_master[i]);
}
#ifdef ACT_NUMA_INTERLEAVED
numa_free(act_libxsmm[num_layers+1], MB*C[num_layers+1]*sizeof(libxsmm_bfloat16));
#else
libxsmm_free(act_libxsmm[num_layers+1]);
#endif
libxsmm_free(label_libxsmm);
for (i = 0; i < numa_num_configured_nodes(); i++) {
free(numa_thr_cfg[i].blocksOFm_s);
free(numa_thr_cfg[i].blocksOFm_e);
for (j = 0; j < num_layers; j++)
numa_free_aligned(numa_thr_cfg[i].scratch[j], numa_thr_cfg[i].layer_size[j]);
free(numa_thr_cfg[i].scratch);
free(numa_thr_cfg[i].layer_size);
}
free(numa_thr_cfg);
free( my_opt );
free( my_fc_fwd );
free( my_fc_bwd );
free( act_libxsmm );
free( delact_libxsmm );
free( fil_master );
free( fil_libxsmm );
free( delfil_libxsmm );
free( bias_libxsmm );
free( delbias_libxsmm );
free( relumask_libxsmm );
free( C );
/* some empty lines at the end */
printf("\n\n\n");
return 0;
}
|
openmp-ex15.c | /* This example for computing pi is adapted from Hager & Wellein, Listing 6.2.
*
* We compute $\pi = \int_0^1 \frac{4}{1 + x^2} dx$.
*
* In this example we use a midpoint rule.
*/
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <unistd.h>
#include <tictoc.h>
int main(int argc, char **argv)
{
int i, j, M = 10, N = 10;
double h, relerr, pi = M_PI;
double mintime = 0., maxtime = 0., avgtime = 0.;
/* if this program is run with an argument, take the first argument to be N */
if (argc > 1) {
N = atoi(argv[1]);
}
/* h is the width of each interval */
h = 1. / N;
for (j = 0; j < M; j++) {
TicTocTimer timer;
double time;
pi = 0.;
timer = tic();
#pragma omp parallel for reduction(+:pi)
for (i = 0; i < N; i++) {
double x = h * (i + 0.5);
/* let's pretend this is a lengthier calculation */
usleep(1);
pi += h * 4. / (1. + x*x);
}
time = toc(&timer);
if (j == 1) {
mintime = maxtime = avgtime = time;
} else if (j > 1) {
mintime = time < mintime ? time : mintime;
maxtime = time > maxtime ? time : maxtime;
avgtime += time;
}
}
avgtime /= (M - 1);
relerr = fabs(M_PI - pi) / M_PI;
printf("Computed pi %g, relative error %g\n", pi, relerr);
printf("Calculation time %g [%g, %g]\n", avgtime, mintime, maxtime);
return 0;
}
|
3d25pt_var.c | /*
* 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] = 16;
tile_size[1] = 16;
tile_size[2] = 24;
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<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
#pragma scop
for (t = 0; t < Nt; t++) {
for (i = 4; i < Nz-4; i++) {
for (j = 4; j < Ny-4; j++) {
for (k = 4; k < Nx-4; 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 ] + A[(t)%2][i+1][j ][k ]) +
coef[2][i][j][k] * (A[(t)%2][i ][j-1][k ] + A[(t)%2][i ][j+1][k ]) +
coef[3][i][j][k] * (A[(t)%2][i ][j ][k-1] + A[(t)%2][i ][j ][k+1]) +
coef[4][i][j][k] * (A[(t)%2][i-2][j ][k ] + A[(t)%2][i+2][j ][k ]) +
coef[5][i][j][k] * (A[(t)%2][i ][j-2][k ] + A[(t)%2][i ][j+2][k ]) +
coef[6][i][j][k] * (A[(t)%2][i ][j ][k-2] + A[(t)%2][i ][j ][k+2]) +
coef[7][i][j][k] * (A[(t)%2][i-3][j ][k ] + A[(t)%2][i+3][j ][k ]) +
coef[8][i][j][k] * (A[(t)%2][i ][j-3][k ] + A[(t)%2][i ][j+3][k ]) +
coef[9][i][j][k] * (A[(t)%2][i ][j ][k-3] + A[(t)%2][i ][j ][k+3]) +
coef[10][i][j][k]* (A[(t)%2][i-4][j ][k ] + A[(t)%2][i+4][j ][k ]) +
coef[11][i][j][k]* (A[(t)%2][i ][j-4][k ] + A[(t)%2][i ][j+4][k ]) +
coef[12][i][j][k]* (A[(t)%2][i ][j ][k-4] + A[(t)%2][i ][j ][k+4]) ;
}
}
}
}
#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(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;
}
|
GB_unop__minv_int64_int64.c | //------------------------------------------------------------------------------
// GB_unop: hard-coded functions for each built-in unary operator
//------------------------------------------------------------------------------
// SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2021, All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
//------------------------------------------------------------------------------
// If this file is in the Generated/ folder, do not edit it (auto-generated).
#include "GB.h"
#ifndef GBCOMPACT
#include "GB_control.h"
#include "GB_atomics.h"
#include "GB_unop__include.h"
// C=unop(A) is defined by the following types and operators:
// op(A) function: GB_unop_apply__minv_int64_int64
// op(A') function: GB_unop_tran__minv_int64_int64
// C type: int64_t
// A type: int64_t
// cast: int64_t cij = aij
// unaryop: cij = GB_IMINV_SIGNED (aij, 64)
#define GB_ATYPE \
int64_t
#define GB_CTYPE \
int64_t
// aij = Ax [pA]
#define GB_GETA(aij,Ax,pA) \
int64_t aij = Ax [pA]
#define GB_CX(p) Cx [p]
// unary operator
#define GB_OP(z, x) \
z = GB_IMINV_SIGNED (x, 64) ;
// casting
#define GB_CAST(z, aij) \
int64_t z = aij ;
// cij = op (aij)
#define GB_CAST_OP(pC,pA) \
{ \
/* aij = Ax [pA] */ \
int64_t aij = Ax [pA] ; \
/* Cx [pC] = op (cast (aij)) */ \
int64_t z = aij ; \
Cx [pC] = GB_IMINV_SIGNED (z, 64) ; \
}
// true if operator is the identity op with no typecasting
#define GB_OP_IS_IDENTITY_WITH_NO_TYPECAST \
0
// disable this operator and use the generic case if these conditions hold
#define GB_DISABLE \
(GxB_NO_MINV || GxB_NO_INT64)
//------------------------------------------------------------------------------
// Cx = op (cast (Ax)): apply a unary operator
//------------------------------------------------------------------------------
GrB_Info GB_unop_apply__minv_int64_int64
(
int64_t *Cx, // Cx and Ax may be aliased
const int64_t *Ax,
const int8_t *GB_RESTRICT Ab, // A->b if A is bitmap
int64_t anz,
int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
int64_t p ;
if (Ab == NULL)
{
#if ( GB_OP_IS_IDENTITY_WITH_NO_TYPECAST )
GB_memcpy (Cx, Ax, anz * sizeof (int64_t), nthreads) ;
#else
#pragma omp parallel for num_threads(nthreads) schedule(static)
for (p = 0 ; p < anz ; p++)
{
int64_t aij = Ax [p] ;
int64_t z = aij ;
Cx [p] = GB_IMINV_SIGNED (z, 64) ;
}
#endif
}
else
{
// bitmap case, no transpose; A->b already memcpy'd into C->b
#pragma omp parallel for num_threads(nthreads) schedule(static)
for (p = 0 ; p < anz ; p++)
{
if (!Ab [p]) continue ;
int64_t aij = Ax [p] ;
int64_t z = aij ;
Cx [p] = GB_IMINV_SIGNED (z, 64) ;
}
}
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// C = op (cast (A')): transpose, typecast, and apply a unary operator
//------------------------------------------------------------------------------
GrB_Info GB_unop_tran__minv_int64_int64
(
GrB_Matrix C,
const GrB_Matrix A,
int64_t *GB_RESTRICT *Workspaces,
const int64_t *GB_RESTRICT A_slice,
int nworkspaces,
int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
#include "GB_unop_transpose.c"
return (GrB_SUCCESS) ;
#endif
}
#endif
|
GB_unop__atan_fc64_fc64.c | //------------------------------------------------------------------------------
// GB_unop: hard-coded functions for each built-in unary operator
//------------------------------------------------------------------------------
// SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2021, All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
//------------------------------------------------------------------------------
// If this file is in the Generated/ folder, do not edit it (auto-generated).
#include "GB.h"
#ifndef GBCOMPACT
#include "GB_control.h"
#include "GB_atomics.h"
#include "GB_unop__include.h"
// C=unop(A) is defined by the following types and operators:
// op(A) function: GB_unop_apply__atan_fc64_fc64
// op(A') function: GB_unop_tran__atan_fc64_fc64
// C type: GxB_FC64_t
// A type: GxB_FC64_t
// cast: GxB_FC64_t cij = aij
// unaryop: cij = catan (aij)
#define GB_ATYPE \
GxB_FC64_t
#define GB_CTYPE \
GxB_FC64_t
// aij = Ax [pA]
#define GB_GETA(aij,Ax,pA) \
GxB_FC64_t aij = Ax [pA]
#define GB_CX(p) Cx [p]
// unary operator
#define GB_OP(z, x) \
z = catan (x) ;
// casting
#define GB_CAST(z, aij) \
GxB_FC64_t z = aij ;
// cij = op (aij)
#define GB_CAST_OP(pC,pA) \
{ \
/* aij = Ax [pA] */ \
GxB_FC64_t aij = Ax [pA] ; \
/* Cx [pC] = op (cast (aij)) */ \
GxB_FC64_t z = aij ; \
Cx [pC] = catan (z) ; \
}
// true if operator is the identity op with no typecasting
#define GB_OP_IS_IDENTITY_WITH_NO_TYPECAST \
0
// disable this operator and use the generic case if these conditions hold
#define GB_DISABLE \
(GxB_NO_ATAN || GxB_NO_FC64)
//------------------------------------------------------------------------------
// Cx = op (cast (Ax)): apply a unary operator
//------------------------------------------------------------------------------
GrB_Info GB_unop_apply__atan_fc64_fc64
(
GxB_FC64_t *Cx, // Cx and Ax may be aliased
const GxB_FC64_t *Ax,
const int8_t *GB_RESTRICT Ab, // A->b if A is bitmap
int64_t anz,
int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
int64_t p ;
if (Ab == NULL)
{
#if ( GB_OP_IS_IDENTITY_WITH_NO_TYPECAST )
GB_memcpy (Cx, Ax, anz * sizeof (GxB_FC64_t), nthreads) ;
#else
#pragma omp parallel for num_threads(nthreads) schedule(static)
for (p = 0 ; p < anz ; p++)
{
GxB_FC64_t aij = Ax [p] ;
GxB_FC64_t z = aij ;
Cx [p] = catan (z) ;
}
#endif
}
else
{
// bitmap case, no transpose; A->b already memcpy'd into C->b
#pragma omp parallel for num_threads(nthreads) schedule(static)
for (p = 0 ; p < anz ; p++)
{
if (!Ab [p]) continue ;
GxB_FC64_t aij = Ax [p] ;
GxB_FC64_t z = aij ;
Cx [p] = catan (z) ;
}
}
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// C = op (cast (A')): transpose, typecast, and apply a unary operator
//------------------------------------------------------------------------------
GrB_Info GB_unop_tran__atan_fc64_fc64
(
GrB_Matrix C,
const GrB_Matrix A,
int64_t *GB_RESTRICT *Workspaces,
const int64_t *GB_RESTRICT A_slice,
int nworkspaces,
int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
#include "GB_unop_transpose.c"
return (GrB_SUCCESS) ;
#endif
}
#endif
|
hermm_c_dia_n_hi_row.c | #include "alphasparse/kernel.h"
#include "alphasparse/util.h"
#include "alphasparse/opt.h"
#ifdef _OPENMP
#include <omp.h>
#endif
#include <memory.h>
#include <stdlib.h>
alphasparse_status_t ONAME(const ALPHA_Complex alpha, const ALPHA_SPMAT_DIA *mat, const ALPHA_Complex *x, const ALPHA_INT columns, const ALPHA_INT ldx, const ALPHA_Complex beta, ALPHA_Complex *y, const ALPHA_INT ldy)
{
ALPHA_INT num_threads = alpha_get_thread_num();
#ifdef _OPENMP
#pragma omp parallel for num_threads(num_threads)
#endif
for (ALPHA_INT r = 0; r < mat->rows; r++)
for(ALPHA_INT c = 0; c < columns; c++)
alpha_mul(y[index2(r,c,ldy)],y[index2(r,c,ldy)],beta);
#ifdef _OPENMP
#pragma omp parallel num_threads(num_threads)
#endif
{
ALPHA_INT tid = alpha_get_thread_id();
ALPHA_INT bcl = cross_block_low(tid,num_threads,columns);
ALPHA_INT bch = cross_block_high(tid,num_threads,columns);
for(ALPHA_INT di = 0; di < mat->ndiag;++di){
ALPHA_INT d = mat->distance[di];
if(d > 0){
ALPHA_INT ars = alpha_max(0,-d);
ALPHA_INT acs = alpha_max(0,d);
ALPHA_INT an = alpha_min(mat->rows - ars,mat->cols - acs);
for(ALPHA_INT i = 0; i < an; ++i){
ALPHA_INT ar = ars + i;
ALPHA_INT ac = acs + i;
ALPHA_Complex val,val_c;
alpha_mul(val,mat->values[index2(di,ar,mat->lval)],alpha);
alpha_mul_2c(val_c,mat->values[index2(di,ar,mat->lval)],alpha);
for(ALPHA_INT bc = bcl;bc < bch;++bc){
alpha_madde(y[index2(ar,bc,ldy)],val,x[index2(ac,bc,ldx)]);
alpha_madde(y[index2(ac,bc,ldy)],val_c,x[index2(ar,bc,ldx)]);
}
}
}
if(d == 0){
for(ALPHA_INT r = 0; r < mat->rows; ++r){
ALPHA_Number val;
alpha_mul(val,mat->values[index2(di,r,mat->lval)],alpha);
for(ALPHA_INT bc = bcl;bc < bch;++bc){
alpha_madde(y[index2(r,bc,ldy)],val,x[index2(r,bc,ldx)]);
}
}
}
}
}
return ALPHA_SPARSE_STATUS_SUCCESS;
}
|
requantize_leakyrelu_pack4.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 requantize_leakyrelu_pack4_neon(const Mat& bottom_blob, Mat& top_blob, const Mat& scale_in_data, const Mat& scale_out_data, const Mat& bias_data, float slope, const Option& opt)
{
int w = bottom_blob.w;
int h = bottom_blob.h;
int channels = bottom_blob.c;
int size = w * h;
int outc = top_blob.c;
int out_elempack = top_blob.elempack;
int scale_in_data_size = scale_in_data.w;
int scale_out_data_size = scale_out_data.w;
int bias_data_size = bias_data.w;
// int8(leakyrelu(v * scale_in, slope) * scale_out)
// int8_leakyrelu(v * (scale_in * scale_out), slope)
// int8(leakyrelu(v * scale_in + bias, slope) * scale_out)
// int8_leakyrelu(v * (scale_in * scale_out) + (bias * scale_out), slope)
if (out_elempack == 8)
{
if (bias_data_size == 0)
{
#pragma omp parallel for num_threads(opt.num_threads)
for (int q = 0; q < outc; q++)
{
const int* intptr0 = bottom_blob.channel(q * 2);
const int* intptr1 = bottom_blob.channel(q * 2 + 1);
signed char* ptr = top_blob.channel(q);
float32x4_t _scale_in0 = scale_in_data_size == 1 ? vdupq_n_f32(scale_in_data[0]) : vld1q_f32((const float*)scale_in_data + q * 8);
float32x4_t _scale_in1 = scale_in_data_size == 1 ? vdupq_n_f32(scale_in_data[0]) : vld1q_f32((const float*)scale_in_data + q * 8 + 4);
float32x4_t _scale_out0 = scale_out_data_size == 1 ? vdupq_n_f32(scale_out_data[0]) : vld1q_f32((const float*)scale_out_data + q * 8);
float32x4_t _scale_out1 = scale_out_data_size == 1 ? vdupq_n_f32(scale_out_data[0]) : vld1q_f32((const float*)scale_out_data + q * 8 + 4);
float32x4_t _scale0 = vmulq_f32(_scale_in0, _scale_out0);
float32x4_t _scale1 = vmulq_f32(_scale_in1, _scale_out1);
float32x4_t _slope = vdupq_n_f32(slope);
int i = 0;
#if __aarch64__
for (; i + 3 < size; i += 4)
{
float32x4_t _v00 = vcvtq_f32_s32(vld1q_s32(intptr0));
float32x4_t _v01 = vcvtq_f32_s32(vld1q_s32(intptr0 + 4));
float32x4_t _v02 = vcvtq_f32_s32(vld1q_s32(intptr0 + 8));
float32x4_t _v03 = vcvtq_f32_s32(vld1q_s32(intptr0 + 12));
float32x4_t _v10 = vcvtq_f32_s32(vld1q_s32(intptr1));
float32x4_t _v11 = vcvtq_f32_s32(vld1q_s32(intptr1 + 4));
float32x4_t _v12 = vcvtq_f32_s32(vld1q_s32(intptr1 + 8));
float32x4_t _v13 = vcvtq_f32_s32(vld1q_s32(intptr1 + 12));
_v00 = vmulq_f32(_v00, _scale0);
_v01 = vmulq_f32(_v01, _scale0);
_v02 = vmulq_f32(_v02, _scale0);
_v03 = vmulq_f32(_v03, _scale0);
_v10 = vmulq_f32(_v10, _scale1);
_v11 = vmulq_f32(_v11, _scale1);
_v12 = vmulq_f32(_v12, _scale1);
_v13 = vmulq_f32(_v13, _scale1);
vst1_s8(ptr, float2int8leakyrelu(_v00, _v10, _slope));
vst1_s8(ptr + 8, float2int8leakyrelu(_v01, _v11, _slope));
vst1_s8(ptr + 16, float2int8leakyrelu(_v02, _v12, _slope));
vst1_s8(ptr + 24, float2int8leakyrelu(_v03, _v13, _slope));
intptr0 += 16;
intptr1 += 16;
ptr += 32;
}
#endif // __aarch64__
for (; i < size; i++)
{
float32x4_t _v0 = vcvtq_f32_s32(vld1q_s32(intptr0));
float32x4_t _v1 = vcvtq_f32_s32(vld1q_s32(intptr1));
_v0 = vmulq_f32(_v0, _scale0);
_v1 = vmulq_f32(_v1, _scale1);
vst1_s8(ptr, float2int8leakyrelu(_v0, _v1, _slope));
intptr0 += 4;
intptr1 += 4;
ptr += 8;
}
}
}
else
{
#pragma omp parallel for num_threads(opt.num_threads)
for (int q = 0; q < outc; q++)
{
const int* intptr0 = bottom_blob.channel(q * 2);
const int* intptr1 = bottom_blob.channel(q * 2 + 1);
signed char* ptr = top_blob.channel(q);
float32x4_t _scale_in0 = scale_in_data_size == 1 ? vdupq_n_f32(scale_in_data[0]) : vld1q_f32((const float*)scale_in_data + q * 8);
float32x4_t _scale_in1 = scale_in_data_size == 1 ? vdupq_n_f32(scale_in_data[0]) : vld1q_f32((const float*)scale_in_data + q * 8 + 4);
float32x4_t _scale_out0 = scale_out_data_size == 1 ? vdupq_n_f32(scale_out_data[0]) : vld1q_f32((const float*)scale_out_data + q * 8);
float32x4_t _scale_out1 = scale_out_data_size == 1 ? vdupq_n_f32(scale_out_data[0]) : vld1q_f32((const float*)scale_out_data + q * 8 + 4);
float32x4_t _bias0 = bias_data_size == 1 ? vdupq_n_f32(bias_data[0]) : vld1q_f32((const float*)bias_data + q * 8);
float32x4_t _bias1 = bias_data_size == 1 ? vdupq_n_f32(bias_data[0]) : vld1q_f32((const float*)bias_data + q * 8 + 4);
float32x4_t _scale0 = vmulq_f32(_scale_in0, _scale_out0);
float32x4_t _scale1 = vmulq_f32(_scale_in1, _scale_out1);
_bias0 = vmulq_f32(_bias0, _scale_out0);
_bias1 = vmulq_f32(_bias1, _scale_out1);
float32x4_t _slope = vdupq_n_f32(slope);
int i = 0;
#if __aarch64__
for (; i + 3 < size; i += 4)
{
float32x4_t _v00 = vcvtq_f32_s32(vld1q_s32(intptr0));
float32x4_t _v01 = vcvtq_f32_s32(vld1q_s32(intptr0 + 4));
float32x4_t _v02 = vcvtq_f32_s32(vld1q_s32(intptr0 + 8));
float32x4_t _v03 = vcvtq_f32_s32(vld1q_s32(intptr0 + 12));
float32x4_t _v10 = vcvtq_f32_s32(vld1q_s32(intptr1));
float32x4_t _v11 = vcvtq_f32_s32(vld1q_s32(intptr1 + 4));
float32x4_t _v12 = vcvtq_f32_s32(vld1q_s32(intptr1 + 8));
float32x4_t _v13 = vcvtq_f32_s32(vld1q_s32(intptr1 + 12));
_v00 = vfmaq_f32(_bias0, _v00, _scale0);
_v01 = vfmaq_f32(_bias0, _v01, _scale0);
_v02 = vfmaq_f32(_bias0, _v02, _scale0);
_v03 = vfmaq_f32(_bias0, _v03, _scale0);
_v10 = vfmaq_f32(_bias1, _v10, _scale1);
_v11 = vfmaq_f32(_bias1, _v11, _scale1);
_v12 = vfmaq_f32(_bias1, _v12, _scale1);
_v13 = vfmaq_f32(_bias1, _v13, _scale1);
vst1_s8(ptr, float2int8leakyrelu(_v00, _v10, _slope));
vst1_s8(ptr + 8, float2int8leakyrelu(_v01, _v11, _slope));
vst1_s8(ptr + 16, float2int8leakyrelu(_v02, _v12, _slope));
vst1_s8(ptr + 24, float2int8leakyrelu(_v03, _v13, _slope));
intptr0 += 16;
intptr1 += 16;
ptr += 32;
}
#endif // __aarch64__
for (; i + 1 < size; i += 2)
{
float32x4_t _v00 = vcvtq_f32_s32(vld1q_s32(intptr0));
float32x4_t _v01 = vcvtq_f32_s32(vld1q_s32(intptr0 + 4));
float32x4_t _v10 = vcvtq_f32_s32(vld1q_s32(intptr1));
float32x4_t _v11 = vcvtq_f32_s32(vld1q_s32(intptr1 + 4));
#if __aarch64__
_v00 = vfmaq_f32(_bias0, _v00, _scale0);
_v01 = vfmaq_f32(_bias0, _v01, _scale0);
_v10 = vfmaq_f32(_bias1, _v10, _scale1);
_v11 = vfmaq_f32(_bias1, _v11, _scale1);
#else // __aarch64__
_v00 = vmlaq_f32(_bias0, _v00, _scale0);
_v01 = vmlaq_f32(_bias0, _v01, _scale0);
_v10 = vmlaq_f32(_bias1, _v10, _scale1);
_v11 = vmlaq_f32(_bias1, _v11, _scale1);
#endif // __aarch64__
vst1_s8(ptr, float2int8leakyrelu(_v00, _v10, _slope));
vst1_s8(ptr + 8, float2int8leakyrelu(_v01, _v11, _slope));
intptr0 += 8;
intptr1 += 8;
ptr += 16;
}
for (; i < size; i++)
{
float32x4_t _v0 = vcvtq_f32_s32(vld1q_s32(intptr0));
float32x4_t _v1 = vcvtq_f32_s32(vld1q_s32(intptr1));
#if __aarch64__
_v0 = vfmaq_f32(_bias0, _v0, _scale0);
_v1 = vfmaq_f32(_bias1, _v1, _scale1);
#else // __aarch64__
_v0 = vmlaq_f32(_bias0, _v0, _scale0);
_v1 = vmlaq_f32(_bias1, _v1, _scale1);
#endif // __aarch64__
vst1_s8(ptr, float2int8leakyrelu(_v0, _v1, _slope));
intptr0 += 4;
intptr1 += 4;
ptr += 8;
}
}
}
}
if (out_elempack == 1)
{
if (bias_data_size == 0)
{
#pragma omp parallel for num_threads(opt.num_threads)
for (int q = 0; q < channels; q++)
{
const int* intptr = bottom_blob.channel(q);
signed char* ptr0 = top_blob.channel(q * 4);
signed char* ptr1 = top_blob.channel(q * 4 + 1);
signed char* ptr2 = top_blob.channel(q * 4 + 2);
signed char* ptr3 = top_blob.channel(q * 4 + 3);
float32x4_t _scale_in = scale_in_data_size == 1 ? vdupq_n_f32(scale_in_data[0]) : vld1q_f32((const float*)scale_in_data + q * 4);
float32x4_t _scale_out = scale_out_data_size == 1 ? vdupq_n_f32(scale_out_data[0]) : vld1q_f32((const float*)scale_out_data + q * 4);
float32x4_t _scale = vmulq_f32(_scale_in, _scale_out);
float32x4_t _slope = vdupq_n_f32(slope);
int i = 0;
for (; i < size; i++)
{
float32x4_t _v = vcvtq_f32_s32(vld1q_s32(intptr));
_v = vmulq_f32(_v, _scale);
int8x8_t v = float2int8leakyrelu(_v, _v, _slope);
ptr0[0] = vget_lane_s8(v, 0);
ptr1[0] = vget_lane_s8(v, 1);
ptr2[0] = vget_lane_s8(v, 2);
ptr3[0] = vget_lane_s8(v, 3);
intptr += 4;
ptr0 += 1;
ptr1 += 1;
ptr2 += 1;
ptr3 += 1;
}
}
}
else
{
#pragma omp parallel for num_threads(opt.num_threads)
for (int q = 0; q < channels; q++)
{
const int* intptr = bottom_blob.channel(q);
signed char* ptr0 = top_blob.channel(q * 4);
signed char* ptr1 = top_blob.channel(q * 4 + 1);
signed char* ptr2 = top_blob.channel(q * 4 + 2);
signed char* ptr3 = top_blob.channel(q * 4 + 3);
float32x4_t _scale_in = scale_in_data_size == 1 ? vdupq_n_f32(scale_in_data[0]) : vld1q_f32((const float*)scale_in_data + q * 4);
float32x4_t _scale_out = scale_out_data_size == 1 ? vdupq_n_f32(scale_out_data[0]) : vld1q_f32((const float*)scale_out_data + q * 4);
float32x4_t _bias = bias_data_size == 1 ? vdupq_n_f32(bias_data[0]) : vld1q_f32((const float*)bias_data + q * 4);
float32x4_t _scale = vmulq_f32(_scale_in, _scale_out);
_bias = vmulq_f32(_bias, _scale_out);
float32x4_t _slope = vdupq_n_f32(slope);
int i = 0;
for (; i < size; i++)
{
float32x4_t _v = vcvtq_f32_s32(vld1q_s32(intptr));
#if __aarch64__
_v = vfmaq_f32(_bias, _v, _scale);
#else
_v = vmlaq_f32(_bias, _v, _scale);
#endif
int8x8_t v = float2int8leakyrelu(_v, _v, _slope);
ptr0[0] = vget_lane_s8(v, 0);
ptr1[0] = vget_lane_s8(v, 1);
ptr2[0] = vget_lane_s8(v, 2);
ptr3[0] = vget_lane_s8(v, 3);
intptr += 4;
ptr0 += 1;
ptr1 += 1;
ptr2 += 1;
ptr3 += 1;
}
}
}
}
}
|
ARM_NLMS.h | /*
==============================================================================
ARM_NLMS.h
Created: 13 Sep 2019 12:13:21pm
Author: michu
==============================================================================
*/
#pragma once
#include <stdio.h>
#include <string.h>
#include <chrono>
//#include <omp.h>
/**
* @brief Instance structure for the floating-point normalized LMS filter.
*/
typedef struct
{
int numTaps; /**< number of coefficients in the filter. */
float *pState; /**< points to the state variable array. The array is of length numTaps+blockSize-1. */
float *pCoeffs; /**< points to the coefficient array. The array is of length numTaps. */
float mu; /**< step size that control filter coefficient updates. */
float energy; /**< saves previous frame energy. */
float x0; /**< saves previous input sample. */
} arm_lms_norm_instance_f32;
typedef struct
{
int numTaps; /**< number of coefficients in the filter. */
float *pState; /**< points to the state variable array. The array is of length numTaps+blockSize-1. */
float *pCoeffs; /**< points to the coefficient array. The array is of length numTaps. */
float mu; /**< step size that controls filter coefficient updates. */
} arm_lms_instance_f32;
typedef struct
{
int numTaps; /**< number of filter coefficients in the filter. */
float *pState; /**< points to the state variable array. The array is of length numTaps+blockSize-1. */
const float *pCoeffs; /**< points to the coefficient array. The array is of length numTaps. */
} arm_fir_instance_f32;
/**
* @brief Processing function for floating-point normalized LMS filter.
* @param[in] *S points to an instance of the floating-point normalized LMS filter structure.
* @param[in] *pSrc points to the block of input data.
* @param[in] *pRef points to the block of reference data.
* @param[out] *pOut points to the block of output data.
* @param[out] *pErr points to the block of error data.
* @param[in] blockSize number of samples to process.
* @return none.
*/
void arm_lms_norm_f32(
arm_lms_norm_instance_f32 * S,
const float * pSrc,
float * pRef,
float * pOut,
float * pErr,
int blockSize);
void arm_lms_f32(
arm_lms_instance_f32 * S,
const float * pSrc,
float * pRef,
float * pOut,
float * pErr,
int blockSize);
void arm_lms_norm_anc(
arm_lms_norm_instance_f32 * S,
const float * pSrc,
float * pErrIn,
float * pOut,
float * pErr,
int blockSize);
void arm_lms_anc(
arm_lms_instance_f32 * S,
const float * pSrc,
float * pErrIn,
float * pOut,
float * pErr,
int blockSize);
/**
* @brief Initialization function for floating-point normalized LMS filter.
* @param[in] *S points to an instance of the floating-point LMS filter structure.
* @param[in] numTaps number of filter coefficients.
* @param[in] *pCoeffs points to coefficient buffer.
* @param[in] *pState points to state buffer.
* @param[in] mu step size that controls filter coefficient updates.
* @param[in] blockSize number of samples to process.
* @return none.
*/
void arm_lms_norm_init_f32(
arm_lms_norm_instance_f32 * S,
int numTaps,
float * pCoeffs,
float * pState,
float mu,
int blockSize);
void arm_lms_init_f32(
arm_lms_instance_f32 * S,
int numTaps,
float * pCoeffs,
float * pState,
float mu,
int blockSize);
void arm_fir_init_f32(
arm_fir_instance_f32 * S,
int numTaps,
const float* pCoeffs,
float * pState,
int blockSize)
{
/* Assign filter taps */
S->numTaps = numTaps;
/* Assign coefficient pointer */
S->pCoeffs = pCoeffs;
/* Clear state buffer. The size is always (blockSize + numTaps - 1) */
memset(pState, 0, (numTaps + (blockSize - 1U)) * sizeof(float));
/* Assign state pointer */
S->pState = pState;
}
/*-----------------------------------------------------------------------------
* Copyright (C) 2010 ARM Limited. All rights reserved.
*
* $Date: 29. November 2010
* $Revision: V1.0.3
*
* Project: CMSIS DSP Library
* Title: arm_lms_norm_init_f32.c
*
* Description: Floating-point NLMS filter initialization function.
*
* Target Processor: Cortex-M4/Cortex-M3
*
* Version 1.0.3 2010/11/29
* Re-organized the CMSIS folders and updated documentation.
*
* Version 1.0.2 2010/11/11
* Documentation updated.
*
* Version 1.0.1 2010/10/05
* Production release and review comments incorporated.
*
* Version 1.0.0 2010/09/20
* Production release and review comments incorporated
*
* Version 0.0.7 2010/06/10
* Misra-C changes done
* ---------------------------------------------------------------------------*/
/**
* @ingroup groupFilters
*/
/**
* @addtogroup LMS_NORM
* @{
*/
/**
* @brief Initialization function for floating-point normalized LMS filter.
* @param[in] *S points to an instance of the floating-point LMS filter structure.
* @param[in] numTaps number of filter coefficients.
* @param[in] *pCoeffs points to coefficient buffer.
* @param[in] *pState points to state buffer.
* @param[in] mu step size that controls filter coefficient updates.
* @param[in] blockSize number of samples to process.
* @return none.
*
* \par Description:
* <code>pCoeffs</code> points to the array of filter coefficients stored in time reversed order:
* <pre>
* {b[numTaps-1], b[numTaps-2], b[N-2], ..., b[1], b[0]}
* </pre>
* The initial filter coefficients serve as a starting point for the adaptive filter.
* <code>pState</code> points to an array of length <code>numTaps+blockSize-1</code> samples,
* where <code>blockSize</code> is the number of input samples processed by each call to <code>arm_lms_norm_f32()</code>.
*/
void arm_fir_f32(
const arm_fir_instance_f32 * S,
const float * pSrc,
float * pDst,
int blockSize)
{
float *pState = S->pState; /* State pointer */
const float *pCoeffs = S->pCoeffs; /* Coefficient pointer */
float *pStateCurnt; /* Points to the current sample of the state */
float *px; /* Temporary pointer for state buffer */
const float *pb; /* Temporary pointer for coefficient buffer */
float acc0; /* Accumulator */
int numTaps = S->numTaps; /* Number of filter coefficients in the filter */
int i, tapCnt, blkCnt; /* Loop counters */
float acc1, acc2, acc3, acc4, acc5, acc6, acc7; /* Accumulators */
float x0, x1, x2, x3, x4, x5, x6, x7; /* Temporary variables to hold state values */
float c0; /* Temporary variable to hold coefficient value */
/* S->pState points to state array which contains previous frame (numTaps - 1) samples */
/* pStateCurnt points to the location where the new input data should be written */
pStateCurnt = &(S->pState[(numTaps - 1U)]);
/* Loop unrolling: Compute 8 output values simultaneously.
* The variables acc0 ... acc7 hold output values that are being computed:
*
* acc0 = b[numTaps-1] * x[n-numTaps-1] + b[numTaps-2] * x[n-numTaps-2] + b[numTaps-3] * x[n-numTaps-3] +...+ b[0] * x[0]
* acc1 = b[numTaps-1] * x[n-numTaps] + b[numTaps-2] * x[n-numTaps-1] + b[numTaps-3] * x[n-numTaps-2] +...+ b[0] * x[1]
* acc2 = b[numTaps-1] * x[n-numTaps+1] + b[numTaps-2] * x[n-numTaps] + b[numTaps-3] * x[n-numTaps-1] +...+ b[0] * x[2]
* acc3 = b[numTaps-1] * x[n-numTaps+2] + b[numTaps-2] * x[n-numTaps+1] + b[numTaps-3] * x[n-numTaps] +...+ b[0] * x[3]
*/
blkCnt = blockSize >> 3U;
while (blkCnt > 0U)
{
/* Copy 4 new input samples into the state buffer. */
*pStateCurnt++ = *pSrc++;
*pStateCurnt++ = *pSrc++;
*pStateCurnt++ = *pSrc++;
*pStateCurnt++ = *pSrc++;
/* Set all accumulators to zero */
acc0 = 0.0f;
acc1 = 0.0f;
acc2 = 0.0f;
acc3 = 0.0f;
acc4 = 0.0f;
acc5 = 0.0f;
acc6 = 0.0f;
acc7 = 0.0f;
/* Initialize state pointer */
px = pState;
/* Initialize coefficient pointer */
pb = pCoeffs;
/* This is separated from the others to avoid
* a call to __aeabi_memmove which would be slower
*/
*pStateCurnt++ = *pSrc++;
*pStateCurnt++ = *pSrc++;
*pStateCurnt++ = *pSrc++;
*pStateCurnt++ = *pSrc++;
/* Read the first 7 samples from the state buffer: x[n-numTaps], x[n-numTaps-1], x[n-numTaps-2] */
x0 = *px++;
x1 = *px++;
x2 = *px++;
x3 = *px++;
x4 = *px++;
x5 = *px++;
x6 = *px++;
/* Loop unrolling: process 8 taps at a time. */
tapCnt = numTaps >> 3U;
while (tapCnt > 0U)
{
/* Read the b[numTaps-1] coefficient */
c0 = *(pb++);
/* Read x[n-numTaps-3] sample */
x7 = *(px++);
/* acc0 += b[numTaps-1] * x[n-numTaps] */
acc0 += x0 * c0;
/* acc1 += b[numTaps-1] * x[n-numTaps-1] */
acc1 += x1 * c0;
/* acc2 += b[numTaps-1] * x[n-numTaps-2] */
acc2 += x2 * c0;
/* acc3 += b[numTaps-1] * x[n-numTaps-3] */
acc3 += x3 * c0;
/* acc4 += b[numTaps-1] * x[n-numTaps-4] */
acc4 += x4 * c0;
/* acc1 += b[numTaps-1] * x[n-numTaps-5] */
acc5 += x5 * c0;
/* acc2 += b[numTaps-1] * x[n-numTaps-6] */
acc6 += x6 * c0;
/* acc3 += b[numTaps-1] * x[n-numTaps-7] */
acc7 += x7 * c0;
/* Read the b[numTaps-2] coefficient */
c0 = *(pb++);
/* Read x[n-numTaps-4] sample */
x0 = *(px++);
/* Perform the multiply-accumulate */
acc0 += x1 * c0;
acc1 += x2 * c0;
acc2 += x3 * c0;
acc3 += x4 * c0;
acc4 += x5 * c0;
acc5 += x6 * c0;
acc6 += x7 * c0;
acc7 += x0 * c0;
/* Read the b[numTaps-3] coefficient */
c0 = *(pb++);
/* Read x[n-numTaps-5] sample */
x1 = *(px++);
/* Perform the multiply-accumulates */
acc0 += x2 * c0;
acc1 += x3 * c0;
acc2 += x4 * c0;
acc3 += x5 * c0;
acc4 += x6 * c0;
acc5 += x7 * c0;
acc6 += x0 * c0;
acc7 += x1 * c0;
/* Read the b[numTaps-4] coefficient */
c0 = *(pb++);
/* Read x[n-numTaps-6] sample */
x2 = *(px++);
/* Perform the multiply-accumulates */
acc0 += x3 * c0;
acc1 += x4 * c0;
acc2 += x5 * c0;
acc3 += x6 * c0;
acc4 += x7 * c0;
acc5 += x0 * c0;
acc6 += x1 * c0;
acc7 += x2 * c0;
/* Read the b[numTaps-4] coefficient */
c0 = *(pb++);
/* Read x[n-numTaps-6] sample */
x3 = *(px++);
/* Perform the multiply-accumulates */
acc0 += x4 * c0;
acc1 += x5 * c0;
acc2 += x6 * c0;
acc3 += x7 * c0;
acc4 += x0 * c0;
acc5 += x1 * c0;
acc6 += x2 * c0;
acc7 += x3 * c0;
/* Read the b[numTaps-4] coefficient */
c0 = *(pb++);
/* Read x[n-numTaps-6] sample */
x4 = *(px++);
/* Perform the multiply-accumulates */
acc0 += x5 * c0;
acc1 += x6 * c0;
acc2 += x7 * c0;
acc3 += x0 * c0;
acc4 += x1 * c0;
acc5 += x2 * c0;
acc6 += x3 * c0;
acc7 += x4 * c0;
/* Read the b[numTaps-4] coefficient */
c0 = *(pb++);
/* Read x[n-numTaps-6] sample */
x5 = *(px++);
/* Perform the multiply-accumulates */
acc0 += x6 * c0;
acc1 += x7 * c0;
acc2 += x0 * c0;
acc3 += x1 * c0;
acc4 += x2 * c0;
acc5 += x3 * c0;
acc6 += x4 * c0;
acc7 += x5 * c0;
/* Read the b[numTaps-4] coefficient */
c0 = *(pb++);
/* Read x[n-numTaps-6] sample */
x6 = *(px++);
/* Perform the multiply-accumulates */
acc0 += x7 * c0;
acc1 += x0 * c0;
acc2 += x1 * c0;
acc3 += x2 * c0;
acc4 += x3 * c0;
acc5 += x4 * c0;
acc6 += x5 * c0;
acc7 += x6 * c0;
/* Decrement loop counter */
tapCnt--;
}
/* Loop unrolling: Compute remaining outputs */
tapCnt = numTaps % 0x8U;
while (tapCnt > 0U)
{
/* Read coefficients */
c0 = *(pb++);
/* Fetch 1 state variable */
x7 = *(px++);
/* Perform the multiply-accumulates */
acc0 += x0 * c0;
acc1 += x1 * c0;
acc2 += x2 * c0;
acc3 += x3 * c0;
acc4 += x4 * c0;
acc5 += x5 * c0;
acc6 += x6 * c0;
acc7 += x7 * c0;
/* Reuse the present sample states for next sample */
x0 = x1;
x1 = x2;
x2 = x3;
x3 = x4;
x4 = x5;
x5 = x6;
x6 = x7;
/* Decrement loop counter */
tapCnt--;
}
/* Advance the state pointer by 8 to process the next group of 8 samples */
pState = pState + 8;
/* The results in the 8 accumulators, store in the destination buffer. */
*pDst++ = acc0;
*pDst++ = acc1;
*pDst++ = acc2;
*pDst++ = acc3;
*pDst++ = acc4;
*pDst++ = acc5;
*pDst++ = acc6;
*pDst++ = acc7;
/* Decrement loop counter */
blkCnt--;
}
/* Loop unrolling: Compute remaining output samples */
blkCnt = blockSize % 0x8U;
while (blkCnt > 0U)
{
/* Copy one sample at a time into state buffer */
*pStateCurnt++ = *pSrc++;
/* Set the accumulator to zero */
acc0 = 0.0f;
/* Initialize state pointer */
px = pState;
/* Initialize Coefficient pointer */
pb = pCoeffs;
i = numTaps;
/* Perform the multiply-accumulates */
while (i > 0U)
{
/* acc = b[numTaps-1] * x[n-numTaps-1] + b[numTaps-2] * x[n-numTaps-2] + b[numTaps-3] * x[n-numTaps-3] +...+ b[0] * x[0] */
acc0 += *px++ * *pb++;
i--;
}
/* Store result in destination buffer. */
*pDst++ = acc0;
/* Advance state pointer by 1 for the next sample */
pState = pState + 1U;
/* Decrement loop counter */
blkCnt--;
}
/* Processing is complete.
Now copy the last numTaps - 1 samples to the start of the state buffer.
This prepares the state buffer for the next function call. */
/* Points to the start of the state buffer */
pStateCurnt = S->pState;
/* Loop unrolling: Compute 4 taps at a time */
tapCnt = (numTaps - 1U) >> 2U;
/* Copy data */
while (tapCnt > 0U)
{
*pStateCurnt++ = *pState++;
*pStateCurnt++ = *pState++;
*pStateCurnt++ = *pState++;
*pStateCurnt++ = *pState++;
/* Decrement loop counter */
tapCnt--;
}
/* Calculate remaining number of copies */
tapCnt = (numTaps - 1U) % 0x4U;
/* Copy remaining data */
while (tapCnt > 0U)
{
*pStateCurnt++ = *pState++;
/* Decrement loop counter */
tapCnt--;
}
}
void arm_lms_norm_init_f32(
arm_lms_norm_instance_f32 * S,
int numTaps,
float * pCoeffs,
float * pState,
float mu,
int blockSize)
{
/* Assign filter taps */
S->numTaps = numTaps;
/* Assign coefficient pointer */
S->pCoeffs = pCoeffs;
/* Clear state buffer and size is always blockSize + numTaps - 1 */
memset(pState, 0, (numTaps + (blockSize - 1u)) * sizeof(float));
/* Assign state pointer */
S->pState = pState;
/* Assign Step size value */
S->mu = mu;
/* Initialise Energy to zero */
S->energy = 0.0f;
/* Initialise x0 to zero */
S->x0 = 0.0f;
}
void arm_lms_init_f32(
arm_lms_instance_f32 * S,
int numTaps,
float * pCoeffs,
float * pState,
float mu,
int blockSize)
{
/* Assign filter taps */
S->numTaps = numTaps;
/* Assign coefficient pointer */
S->pCoeffs = pCoeffs;
/* Clear state buffer and size is always blockSize + numTaps */
memset(pState, 0, (numTaps + (blockSize - 1)) * sizeof(float));
/* Assign state pointer */
S->pState = pState;
/* Assign Step size value */
S->mu = mu;
}
/**
* @} end of LMS_NORM group
*/
/* ----------------------------------------------------------------------
* Copyright (C) 2010 ARM Limited. All rights reserved.
*
* $Date: 29. November 2010
* $Revision: V1.0.3
*
* Project: CMSIS DSP Library
* Title: arm_lms_norm_f32.c
*
* Description: Processing function for the floating-point Normalised LMS.
*
* Target Processor: Cortex-M4/Cortex-M3
*
* Version 1.0.3 2010/11/29
* Re-organized the CMSIS folders and updated documentation.
*
* Version 1.0.2 2010/11/11
* Documentation updated.
*
* Version 1.0.1 2010/10/05
* Production release and review comments incorporated.
*
* Version 1.0.0 2010/09/20
* Production release and review comments incorporated
*
* Version 0.0.7 2010/06/10
* Misra-C changes done
* -------------------------------------------------------------------- */
/**
* @ingroup groupFilters
*/
/**
* @defgroup LMS_NORM Normalized LMS Filters
*
* This set of functions implements a commonly used adaptive filter.
* It is related to the Least Mean Square (LMS) adaptive filter and includes an additional normalization
* factor which increases the adaptation rate of the filter.
* The CMSIS DSP Library contains normalized LMS filter functions that operate on Q15, Q31, and floating-point data types.
*
* A normalized least mean square (NLMS) filter consists of two components as shown below.
* The first component is a standard transversal or FIR filter.
* The second component is a coefficient update mechanism.
* The NLMS filter has two input signals.
* The "input" feeds the FIR filter while the "reference input" corresponds to the desired output of the FIR filter.
* That is, the FIR filter coefficients are updated so that the output of the FIR filter matches the reference input.
* The filter coefficient update mechanism is based on the difference between the FIR filter output and the reference input.
* This "error signal" tends towards zero as the filter adapts.
* The NLMS processing functions accept the input and reference input signals and generate the filter output and error signal.
* \image html LMS.gif "Internal structure of the NLMS adaptive filter"
*
* The functions operate on blocks of data and each call to the function processes
* <code>blockSize</code> samples through the filter.
* <code>pSrc</code> points to input signal, <code>pRef</code> points to reference signal,
* <code>pOut</code> points to output signal and <code>pErr</code> points to error signal.
* All arrays contain <code>blockSize</code> values.
*
* The API functions operate on a block-by-block basis.
* Internally, the filter coefficients <code>b[n]</code> are updated on a sample-by-sample basis.
* The convergence of the LMS filter is slower compared to the normalized LMS algorithm.
*
* \par Algorithm:
* The output signal <code>y[n]</code> is computed by a standard FIR filter:
* <pre>
* y[n] = b[0] * x[n] + b[1] * x[n-1] + b[2] * x[n-2] + ...+ b[numTaps-1] * x[n-numTaps+1]
* </pre>
*
* \par
* The error signal equals the difference between the reference signal <code>d[n]</code> and the filter output:
* <pre>
* e[n] = d[n] - y[n].
* </pre>
*
* \par
* After each sample of the error signal is computed the instanteous energy of the filter state variables is calculated:
* <pre>
* E = x[n]^2 + x[n-1]^2 + ... + x[n-numTaps+1]^2.
* </pre>
* The filter coefficients <code>b[k]</code> are then updated on a sample-by-sample basis:
* <pre>
* b[k] = b[k] + e[n] * (mu/E) * x[n-k], for k=0, 1, ..., numTaps-1
* </pre>
* where <code>mu</code> is the step size and controls the rate of coefficient convergence.
*\par
* In the APIs, <code>pCoeffs</code> points to a coefficient array of size <code>numTaps</code>.
* Coefficients are stored in time reversed order.
* \par
* <pre>
* {b[numTaps-1], b[numTaps-2], b[N-2], ..., b[1], b[0]}
* </pre>
* \par
* <code>pState</code> points to a state array of size <code>numTaps + blockSize - 1</code>.
* Samples in the state buffer are stored in the order:
* \par
* <pre>
* {x[n-numTaps+1], x[n-numTaps], x[n-numTaps-1], x[n-numTaps-2]....x[0], x[1], ..., x[blockSize-1]}
* </pre>
* \par
* Note that the length of the state buffer exceeds the length of the coefficient array by <code>blockSize-1</code> samples.
* The increased state buffer length allows circular addressing, which is traditionally used in FIR filters,
* to be avoided and yields a significant speed improvement.
* The state variables are updated after each block of data is processed.
* \par Instance Structure
* The coefficients and state variables for a filter are stored together in an instance data structure.
* A separate instance structure must be defined for each filter and
* coefficient and state arrays cannot be shared among instances.
* There are separate instance structure declarations for each of the 3 supported data types.
*
* \par Initialization Functions
* There is also an associated initialization function for each data type.
* The initialization function performs the following operations:
* - Sets the values of the internal structure fields.
* - Zeros out the values in the state buffer.
* \par
* Instance structure cannot be placed into a const data section and it is recommended to use the initialization function.
* \par Fixed-Point Behavior:
* Care must be taken when using the Q15 and Q31 versions of the normalised LMS filter.
* The following issues must be considered:
* - Scaling of coefficients
* - Overflow and saturation
*
* \par Scaling of Coefficients:
* Filter coefficients are represented as fractional values and
* coefficients are restricted to lie in the range <code>[-1 +1)</code>.
* The fixed-point functions have an additional scaling parameter <code>postShift</code>.
* At the output of the filter's accumulator is a shift register which shifts the result by <code>postShift</code> bits.
* This essentially scales the filter coefficients by <code>2^postShift</code> and
* allows the filter coefficients to exceed the range <code>[+1 -1)</code>.
* The value of <code>postShift</code> is set by the user based on the expected gain through the system being modeled.
*
* \par Overflow and Saturation:
* Overflow and saturation behavior of the fixed-point Q15 and Q31 versions are
* described separately as part of the function specific documentation below.
*/
/**
* @addtogroup LMS_NORM
* @{
*/
/**
* @brief Processing function for floating-point normalized LMS filter.
* @param[in] *S points to an instance of the floating-point normalized LMS filter structure.
* @param[in] *pSrc points to the block of input data.
* @param[in] *pRef points to the block of reference data.
* @param[out] *pOut points to the block of output data.
* @param[out] *pErr points to the block of error data.
* @param[in] blockSize number of samples to process.
* @return none.
*/
void arm_lms_norm_f32(
arm_lms_norm_instance_f32 * S,
const float * pSrc,
float * pRef,
float * pOut,
float * pErr,
int blockSize)
{
float *pState = S->pState; /* State pointer */
float *pCoeffs = S->pCoeffs; /* Coefficient pointer */
float *pStateCurnt; /* Points to the current sample of the state */
float *px, *pb; /* Temporary pointers for state and coefficient buffers */
float mu = S->mu; /* Adaptive factor */
int numTaps = S->numTaps; /* Number of filter coefficients in the filter */
int tapCnt, blkCnt; /* Loop counters */
float energy; /* Energy of the input */
float sum, e, d; /* accumulator, error, reference data sample */
float w, x0, in; /* weight factor, temporary variable to hold input sample and state */
/* Initializations of error, difference, Coefficient update */
e = 0.0f;
d = 0.0f;
w = 0.0f;
energy = S->energy;
x0 = S->x0;
/* S->pState points to buffer which contains previous frame (numTaps - 1) samples */
/* pStateCurnt points to the location where the new input data should be written */
pStateCurnt = &(S->pState[(numTaps - 1u)]);
blkCnt = blockSize;
while (blkCnt > 0u)
{
/* Copy the new input sample into the state buffer */
*pStateCurnt++ = *pSrc;
/* Initialize pState pointer */
px = pState;
/* Initialize coeff pointer */
pb = (pCoeffs);
/* Read the sample from input buffer */
in = *pSrc++;
/* Update the energy calculation */
energy -= x0 * x0;
energy += in * in;
/* Set the accumulator to zero */
sum = 0.0f;
/* Loop unrolling. Process 4 taps at a time. */
tapCnt = numTaps >> 2;
while (tapCnt > 0u)
{
/* Perform the multiply-accumulate */
sum += (*px++) * (*pb++);
sum += (*px++) * (*pb++);
sum += (*px++) * (*pb++);
sum += (*px++) * (*pb++);
/* Decrement the loop counter */
tapCnt--;
}
/* If the filter length is not a multiple of 4, compute the remaining filter taps */
tapCnt = numTaps % 0x4u;
while (tapCnt > 0u)
{
/* Perform the multiply-accumulate */
sum += (*px++) * (*pb++);
/* Decrement the loop counter */
tapCnt--;
}
/* The result in the accumulator, store in the destination buffer. */
*pOut++ = sum;
/* Compute and store error */
d = (float)(*pRef++);
e = d - sum;
*pErr++ = e;
/* Calculation of Weighting factor for updating filter coefficients */
/* epsilon value 0.000000119209289f */
w = (e * mu) / (energy + 0.000000119209289f);
/* Initialize pState pointer */
px = pState;
/* Initialize coeff pointer */
pb = (pCoeffs);
/* Loop unrolling. Process 4 taps at a time. */
tapCnt = numTaps >> 2;
/* Update filter coefficients */
while (tapCnt > 0u)
{
/* Perform the multiply-accumulate */
*pb += w * (*px++);
pb++;
*pb += w * (*px++);
pb++;
*pb += w * (*px++);
pb++;
*pb += w * (*px++);
pb++;
/* Decrement the loop counter */
tapCnt--;
}
/* If the filter length is not a multiple of 4, compute the remaining filter taps */
tapCnt = numTaps % 0x4u;
while (tapCnt > 0u)
{
/* Perform the multiply-accumulate */
*pb += w * (*px++);
pb++;
/* Decrement the loop counter */
tapCnt--;
}
x0 = *pState;
/* Advance state pointer by 1 for the next sample */
pState = pState + 1;
/* Decrement the loop counter */
blkCnt--;
}
S->energy = energy;
S->x0 = x0;
/* Processing is complete. Now copy the last numTaps - 1 samples to the
satrt of the state buffer. This prepares the state buffer for the
next function call. */
/* Points to the start of the pState buffer */
pStateCurnt = S->pState;
/* Loop unrolling for (numTaps - 1u)/4 samples copy */
tapCnt = (numTaps - 1u) >> 2u;
/* copy data */
while (tapCnt > 0u)
{
*pStateCurnt++ = *pState++;
*pStateCurnt++ = *pState++;
*pStateCurnt++ = *pState++;
*pStateCurnt++ = *pState++;
/* Decrement the loop counter */
tapCnt--;
}
/* Calculate remaining number of copies */
tapCnt = (numTaps - 1u) % 0x4u;
/* Copy the remaining q31_t data */
while (tapCnt > 0u)
{
*pStateCurnt++ = *pState++;
/* Decrement the loop counter */
tapCnt--;
}
}
void arm_lms_f32(
arm_lms_instance_f32 * S,
const float * pSrc,
float * pRef,
float * pOut,
float * pErr,
int blockSize)
{
volatile float *pState = S->pState; /* State pointer */
volatile float *pCoeffs = S->pCoeffs; /* Coefficient pointer */
volatile float *pStateCurnt; /* Points to the current sample of the state */
volatile float *px, *pb; /* Temporary pointers for state and coefficient buffers */
volatile float mu = S->mu; /* Adaptive factor */
volatile float acc, e; /* Accumulator, error */
volatile float w; /* Weight factor */
volatile int numTaps = S->numTaps; /* Number of filter coefficients in the filter */
volatile int tapCnt, blkCnt; /* Loop counters */
/* Initializations of error, difference, Coefficient update */
e = 0.0f;
w = 0.0f;
/* S->pState points to state array which contains previous frame (numTaps - 1) samples */
/* pStateCurnt points to the location where the new input data should be written */
pStateCurnt = &(S->pState[(numTaps - 1U)]);
/* initialise loop count */
blkCnt = blockSize;
while (blkCnt > 0U)
{
/* Copy the new input sample into the state buffer */
*pStateCurnt++ = *pSrc++;
/* Initialize pState pointer */
px = pState;
/* Initialize coefficient pointer */
pb = pCoeffs;
/* Set the accumulator to zero */
acc = 0.0f;
/* Loop unrolling: Compute 4 taps at a time. */
tapCnt = numTaps >> 2U;
while (tapCnt > 0U)
{
/* Perform the multiply-accumulate */
acc += (*px++) * (*pb++);
acc += (*px++) * (*pb++);
acc += (*px++) * (*pb++);
acc += (*px++) * (*pb++);
/* Decrement loop counter */
tapCnt--;
}
/* Loop unrolling: Compute remaining taps */
tapCnt = numTaps % 0x4U;
while (tapCnt > 0U)
{
/* Perform the multiply-accumulate */
acc += (*px++) * (*pb++);
/* Decrement the loop counter */
tapCnt--;
}
/* Store the result from accumulator into the destination buffer. */
*pOut++ = acc;
/* Compute and store error */
e = (float)*pRef++ - acc;
*pErr++ = e;
/* Calculation of Weighting factor for updating filter coefficients */
w = e * mu;
/* Initialize pState pointer */
/* Advance state pointer by 1 for the next sample */
px = pState++;
/* Initialize coefficient pointer */
pb = pCoeffs;
/* Loop unrolling: Compute 4 taps at a time. */
tapCnt = numTaps >> 2U;
/* Update filter coefficients */
while (tapCnt > 0U)
{
/* Perform the multiply-accumulate */
*pb += w * (*px++);
pb++;
*pb += w * (*px++);
pb++;
*pb += w * (*px++);
pb++;
*pb += w * (*px++);
pb++;
/* Decrement loop counter */
tapCnt--;
}
/* Loop unrolling: Compute remaining taps */
tapCnt = numTaps % 0x4U;
while (tapCnt > 0U)
{
/* Perform the multiply-accumulate */
*pb += w * (*px++);
pb++;
/* Decrement loop counter */
tapCnt--;
}
/* Decrement loop counter */
blkCnt--;
}
/* Processing is complete.
Now copy the last numTaps - 1 samples to the start of the state buffer.
This prepares the state buffer for the next function call. */
/* Points to the start of the pState buffer */
pStateCurnt = S->pState;
/* copy data */
/* Loop unrolling: Compute 4 taps at a time. */
tapCnt = (numTaps - 1U) >> 2U;
while (tapCnt > 0U)
{
*pStateCurnt++ = *pState++;
*pStateCurnt++ = *pState++;
*pStateCurnt++ = *pState++;
*pStateCurnt++ = *pState++;
/* Decrement loop counter */
tapCnt--;
}
/* Loop unrolling: Compute remaining taps */
tapCnt = (numTaps - 1U) % 0x4U;
while (tapCnt > 0U)
{
*pStateCurnt++ = *pState++;
/* Decrement loop counter */
tapCnt--;
}
}
/**
* @} end of LMS_NORM group
*/
void arm_lms_norm_anc(
arm_lms_norm_instance_f32 * S,
const float * pSrc,
float * pErrIn,
float * pOut,
float * pErr,
int blockSize)
{
float *pState = S->pState; /* State pointer */
float *pCoeffs = S->pCoeffs; /* Coefficient pointer */
float *pStateCurnt; /* Points to the current sample of the state */
float *px, *pb; /* Temporary pointers for state and coefficient buffers */
float mu = S->mu; /* Adaptive factor */
float acc, e; /* Accumulator, error */
float w; /* Weight factor */
int numTaps = S->numTaps; /* Number of filter coefficients in the filter */
int tapCnt, blkCnt; /* Loop counters */
float energy; /* Energy of the input */
float x0, in; /* Temporary variable to hold input sample and state */
/* Initializations of error, difference, Coefficient update */
e = 0.0f;
w = 0.0f;
energy = S->energy;
x0 = S->x0;
/* S->pState points to buffer which contains previous frame (numTaps - 1) samples */
/* pStateCurnt points to the location where the new input data should be written */
pStateCurnt = &(S->pState[(numTaps - 1U)]);
/* initialise loop count */
blkCnt = blockSize;
while (blkCnt > 0U)
{
/* Copy the new input sample into the state buffer */
*pStateCurnt++ = *pSrc;
/* Initialize pState pointer */
px = pState;
/* Initialize coefficient pointer */
pb = pCoeffs;
/* Read the sample from input buffer */
in = *pSrc++;
/* Update the energy calculation */
energy -= x0 * x0;
energy += in * in;
/* Set the accumulator to zero */
acc = 0.0f;
/* Loop unrolling: Compute 4 taps at a time. */
tapCnt = numTaps >> 2U;
while (tapCnt > 0U)
{
/* Perform the multiply-accumulate */
acc += (*px++) * (*pb++);
acc += (*px++) * (*pb++);
acc += (*px++) * (*pb++);
acc += (*px++) * (*pb++);
/* Decrement loop counter */
tapCnt--;
}
/* Loop unrolling: Compute remaining taps */
tapCnt = numTaps % 0x4U;
while (tapCnt > 0U)
{
/* Perform the multiply-accumulate */
acc += (*px++) * (*pb++);
/* Decrement the loop counter */
tapCnt--;
}
/* Store the result from accumulator into the destination buffer. */
*pOut++ = -acc;
/* Compute and store error */
e = -(float)*pErrIn++;
*pErr++ = e;
/* Calculation of Weighting factor for updating filter coefficients */
/* epsilon value 0.000000119209289f */
w = (e * mu) / (energy + 0.000000119209289f);
/* Initialize pState pointer */
px = pState;
/* Initialize coefficient pointer */
pb = pCoeffs;
/* Loop unrolling: Compute 4 taps at a time. */
tapCnt = numTaps >> 2U;
/* Update filter coefficients */
while (tapCnt > 0U)
{
/* Perform the multiply-accumulate */
*pb = (*pb) * 0.999f + w * (*px++);
pb++;
*pb = (*pb) * 0.999f + w * (*px++);
pb++;
*pb = (*pb) * 0.999f + w * (*px++);
pb++;
*pb = (*pb) * 0.999f + w * (*px++);
pb++;
/* Decrement loop counter */
tapCnt--;
}
/* Loop unrolling: Compute remaining taps */
tapCnt = numTaps % 0x4U;
while (tapCnt > 0U)
{
/* Perform the multiply-accumulate */
*pb = (*pb) * 0.999f + w * (*px++);
pb++;
/* Decrement loop counter */
tapCnt--;
}
x0 = *pState;
/* Advance state pointer by 1 for the next sample */
pState = pState + 1;
/* Decrement loop counter */
blkCnt--;
}
/* Save energy and x0 values for the next frame */
S->energy = energy;
S->x0 = x0;
/* Processing is complete.
Now copy the last numTaps - 1 samples to the start of the state buffer.
This prepares the state buffer for the next function call. */
/* Points to the start of the pState buffer */
pStateCurnt = S->pState;
/* copy data */
/* Loop unrolling: Compute 4 taps at a time. */
tapCnt = (numTaps - 1U) >> 2U;
while (tapCnt > 0U)
{
*pStateCurnt++ = *pState++;
*pStateCurnt++ = *pState++;
*pStateCurnt++ = *pState++;
*pStateCurnt++ = *pState++;
/* Decrement loop counter */
tapCnt--;
}
/* Loop unrolling: Compute remaining taps */
tapCnt = (numTaps - 1U) % 0x4U;
while (tapCnt > 0U)
{
*pStateCurnt++ = *pState++;
/* Decrement loop counter */
tapCnt--;
}
}
void arm_lms_anc(
arm_lms_instance_f32 * S,
const float * pSrc,
float * pErrIn,
float * pOut,
float * pErr,
int blockSize)
{
volatile float *pState = S->pState; /* State pointer */
volatile float *pCoeffs = S->pCoeffs; /* Coefficient pointer */
volatile float *pStateCurnt; /* Points to the current sample of the state */
volatile float *px, *pb; /* Temporary pointers for state and coefficient buffers */
volatile float mu = S->mu; /* Adaptive factor */
volatile float acc, e; /* Accumulator, error */
volatile float w; /* Weight factor */
volatile int numTaps = S->numTaps; /* Number of filter coefficients in the filter */
volatile int tapCnt, blkCnt; /* Loop counters */
/* Initializations of error, difference, Coefficient update */
e = 0.0f;
w = 0.0f;
/* S->pState points to state array which contains previous frame (numTaps - 1) samples */
/* pStateCurnt points to the location where the new input data should be written */
pStateCurnt = &(S->pState[(numTaps - 1U)]);
/* initialise loop count */
blkCnt = blockSize;
while (blkCnt > 0U)
{
/* Copy the new input sample into the state buffer */
*pStateCurnt++ = *pSrc++;
/* Initialize pState pointer */
px = pState;
/* Initialize coefficient pointer */
pb = pCoeffs;
/* Set the accumulator to zero */
acc = 0.0f;
/* Loop unrolling: Compute 4 taps at a time. */
tapCnt = numTaps >> 2U;
while (tapCnt > 0U)
{
/* Perform the multiply-accumulate */
acc += (*px++) * (*pb++);
acc += (*px++) * (*pb++);
acc += (*px++) * (*pb++);
acc += (*px++) * (*pb++);
/* Decrement loop counter */
tapCnt--;
}
/* Loop unrolling: Compute remaining taps */
tapCnt = numTaps % 0x4U;
while (tapCnt > 0U)
{
/* Perform the multiply-accumulate */
acc += (*px++) * (*pb++);
/* Decrement the loop counter */
tapCnt--;
}
/* Store the result from accumulator into the destination buffer. */
*pOut++ = acc;
/* Compute and store error */
e = (float)*pErrIn++;
*pErr++ = e;
/* Calculation of Weighting factor for updating filter coefficients */
w = e * mu;
/* Initialize pState pointer */
/* Advance state pointer by 1 for the next sample */
px = pState++;
/* Initialize coefficient pointer */
pb = pCoeffs;
/* Loop unrolling: Compute 4 taps at a time. */
tapCnt = numTaps >> 2U;
/* Update filter coefficients */
while (tapCnt > 0U)
{
/* Perform the multiply-accumulate */
*pb = (*pb) * 0.999f + w * (*px++);
pb++;
*pb = (*pb) * 0.999f + w * (*px++);
pb++;
*pb = (*pb) * 0.999f + w * (*px++);
pb++;
*pb = (*pb) * 0.999f + w * (*px++);
pb++;
/* Decrement loop counter */
tapCnt--;
}
/* Loop unrolling: Compute remaining taps */
tapCnt = numTaps % 0x4U;
while (tapCnt > 0U)
{
/* Perform the multiply-accumulate */
*pb = (*pb) * 0.999f + w * (*px++);
pb++;
/* Decrement loop counter */
tapCnt--;
}
/* Decrement loop counter */
blkCnt--;
}
/* Processing is complete.
Now copy the last numTaps - 1 samples to the start of the state buffer.
This prepares the state buffer for the next function call. */
/* Points to the start of the pState buffer */
pStateCurnt = S->pState;
/* copy data */
/* Loop unrolling: Compute 4 taps at a time. */
tapCnt = (numTaps - 1U) >> 2U;
while (tapCnt > 0U)
{
*pStateCurnt++ = *pState++;
*pStateCurnt++ = *pState++;
*pStateCurnt++ = *pState++;
*pStateCurnt++ = *pState++;
/* Decrement loop counter */
tapCnt--;
}
/* Loop unrolling: Compute remaining taps */
tapCnt = (numTaps - 1U) % 0x4U;
while (tapCnt > 0U)
{
*pStateCurnt++ = *pState++;
/* Decrement loop counter */
tapCnt--;
}
}
/**
* @brief Caluclation of SNR
* @param float* Pointer to the reference buffer
* @param float* Pointer to the test buffer
* @param uint32_t total number of samples
* @return float SNR
* The function Caluclates signal to noise ratio for the reference output
* and test output
*/
float arm_snr_f32(float *pRef, float *pTest, uint32_t buffSize)
{
float EnergySignal = 0.0, EnergyError = 0.0;
uint32_t i;
float SNR;
int temp;
int *test;
for (i = 0; i < buffSize; i++)
{
/* Checking for a NAN value in pRef array */
test = (int *)(&pRef[i]);
temp = *test;
if (temp == 0x7FC00000)
{
return(0);
}
/* Checking for a NAN value in pTest array */
test = (int *)(&pTest[i]);
temp = *test;
if (temp == 0x7FC00000)
{
return(0);
}
EnergySignal += pRef[i] * pRef[i];
EnergyError += (pRef[i] - pTest[i]) * (pRef[i] - pTest[i]);
}
/* Checking for a NAN value in EnergyError */
test = (int *)(&EnergyError);
temp = *test;
if (temp == 0x7FC00000)
{
return(0);
}
SNR = 10 * log10(EnergySignal / EnergyError);
return (SNR);
}
void arm_dot_prod_f32(
const float * pSrcA,
const float * pSrcB,
int blockSize,
float * result)
{
int blkCnt; /* Loop counter */
float sum = 0.0f; /* Temporary return variable */
/* Loop unrolling: Compute 4 outputs at a time */
blkCnt = blockSize >> 2U;
/* First part of the processing with loop unrolling. Compute 4 outputs at a time.
** a second loop below computes the remaining 1 to 3 samples. */
while (blkCnt > 0U)
{
/* C = A[0]* B[0] + A[1]* B[1] + A[2]* B[2] + .....+ A[blockSize-1]* B[blockSize-1] */
/* Calculate dot product and store result in a temporary buffer. */
sum += (*pSrcA++) * (*pSrcB++);
sum += (*pSrcA++) * (*pSrcB++);
sum += (*pSrcA++) * (*pSrcB++);
sum += (*pSrcA++) * (*pSrcB++);
/* Decrement loop counter */
blkCnt--;
}
/* Loop unrolling: Compute remaining outputs */
blkCnt = blockSize % 0x4U;
while (blkCnt > 0U)
{
/* C = A[0]* B[0] + A[1]* B[1] + A[2]* B[2] + .....+ A[blockSize-1]* B[blockSize-1] */
/* Calculate dot product and store result in a temporary buffer. */
sum += (*pSrcA++) * (*pSrcB++);
/* Decrement loop counter */
blkCnt--;
}
/* Store result in destination buffer */
*result = sum;
}
void arm_add_f32(
const float * pSrcA,
const float * pSrcB,
float * pDst,
int blockSize)
{
int blkCnt; /* Loop counter */
/* Loop unrolling: Compute 4 outputs at a time */
blkCnt = blockSize >> 2U;
while (blkCnt > 0U)
{
/* C = A + B */
/* Add and store result in destination buffer. */
*pDst++ = (*pSrcA++) + (*pSrcB++);
*pDst++ = (*pSrcA++) + (*pSrcB++);
*pDst++ = (*pSrcA++) + (*pSrcB++);
*pDst++ = (*pSrcA++) + (*pSrcB++);
/* Decrement loop counter */
blkCnt--;
}
/* Loop unrolling: Compute remaining outputs */
blkCnt = blockSize % 0x4U;
while (blkCnt > 0U)
{
/* C = A + B */
/* Add and store result in destination buffer. */
*pDst++ = (*pSrcA++) + (*pSrcB++);
/* Decrement loop counter */
blkCnt--;
}
}
void arm_scale_f32(
const float *pSrc,
float scale,
float *pDst,
int blockSize)
{
int blkCnt; /* Loop counter */
/* Loop unrolling: Compute 4 outputs at a time */
blkCnt = blockSize >> 2U;
while (blkCnt > 0U)
{
/* C = A * scale */
/* Scale input and store result in destination buffer. */
*pDst++ = (*pSrc++) * scale;
*pDst++ = (*pSrc++) * scale;
*pDst++ = (*pSrc++) * scale;
*pDst++ = (*pSrc++) * scale;
/* Decrement loop counter */
blkCnt--;
}
/* Loop unrolling: Compute remaining outputs */
blkCnt = blockSize % 0x4U;
while (blkCnt > 0U)
{
/* C = A * scale */
/* Scale input and store result in destination buffer. */
*pDst++ = (*pSrc++) * scale;
/* Decrement loop counter */
blkCnt--;
}
}
#include <array>
#include <limits>
#include <vector>
#include <fstream>
#include <assert.h>
#include "constants.h"
template<int filter_length>
class FIRFilter {
public:
typedef std::array<float, filter_length> samples_array;
typedef std::array<float, filter_length> filter_coeffs_array;
FIRFilter() : _filter_coefficients{ {0.0f} }, _samples_buffer{ {0.0} }, filterSize{ filter_length }{}
FIRFilter(filter_coeffs_array coefficients) : _filter_coefficients(coefficients),
_samples_buffer{ 0.0 }, filterSize{ filter_length } {
}
FIRFilter(int filter_size) : _filter_coefficients{ 0.0 },
_samples_buffer{ 0.0 }, filterSize{ filter_size } {
}
FIRFilter(filter_coeffs_array coefficients, int filter_size) : _filter_coefficients(coefficients),
_samples_buffer{ 0.0 }, filterSize{ filter_size } {
}
float fir_step(float new_sample) {
float new_val = 0;
// Shift sample_buffer (FIFO style)
for (long unsigned int i = filter_length - 1; i >= 1; --i) {
_samples_buffer[i] = _samples_buffer[i - 1];
}
_samples_buffer[0] = new_sample;
// Multiply and accumulate
for (long unsigned int i = 0; i < filter_length; ++i) {
new_val += _samples_buffer[i] * _filter_coefficients[i];
}
return new_val;
}
filter_coeffs_array get_coefficients() {
return _filter_coefficients;
}
void set_coefficients(filter_coeffs_array new_coefficients) {
_filter_coefficients = new_coefficients;
}
void reset_sample_buffer() {
_samples_buffer = { 0 };
}
private:
filter_coeffs_array _filter_coefficients;
samples_array _samples_buffer;
int filterSize;
};
//template<int filter_length>
//class FIRFilter {
//public:
// typedef std::array<float, filter_length> samples_array;
// typedef std::array<float, filter_length> filter_coeffs_array;
//
// FIRFilter() : _filter_coefficients{ {0.0f} }, _samples_buffer{ {0.0} }, filterSize{filter_length} {}
//
// FIRFilter(int _filterSize) : _filter_coefficients{ {0.0f} }, _samples_buffer{ {0.0} }, filterSize{ _filterSize } {}
//
// FIRFilter(int _filterSize, filter_coeffs_array coefficients) : _filter_coefficients(coefficients), filterSize{ _filterSize },
// _samples_buffer{ 0.0 } {}
//
// FIRFilter(filter_coeffs_array coefficients) : _filter_coefficients(coefficients), _samples_buffer{ 0.0 } {}
//
// float fir_step(float new_sample) {
// float new_val = 0;
// // Shift sample_buffer (FIFO style)
// for (long unsigned int i = filterSize - 1; i >= 1; --i) {
// _samples_buffer[i] = _samples_buffer[i - 1];
// }
// _samples_buffer[0] = new_sample;
// // Multiply and accumulate
// for (long unsigned int i = 0; i < filterSize; ++i) {
// new_val += _samples_buffer[i] * _filter_coefficients[i];
// }
// return new_val;
// }
//
// filter_coeffs_array get_coefficients() {
// return _filter_coefficients;
// }
//
// void set_coefficients(filter_coeffs_array new_coefficients) {
// _filter_coefficients = new_coefficients;
// }
//
// void reset_sample_buffer() {
// _samples_buffer = { 0 };
// }
//
//private:
// int filterSize;
// filter_coeffs_array _filter_coefficients;
// samples_array _samples_buffer;
//};
//void dc_removal(float *samples_bufferE, float *samples_bufferR, float *out1, float *out2, long unsigned int buffer_length) {
// static float last_error_sample = 0.0f;
// static float last_ref_sample = 0.0f;
//
// static FIRFilter<ANTYALIAS_FILTER_LENGTH> aa_filter_error(ANTYALIAS_FILTER_COEFFS);
// static FIRFilter<ANTYALIAS_FILTER_LENGTH> aa_filter_ref(ANTYALIAS_FILTER_COEFFS);
//
// for (unsigned long i = 1; i < buffer_length; i ++) {
// float error_sample = samples_bufferE[i];
// float reference_sample = samples_bufferR[i - 1];
// error samples filtering
// float new_err = error_sample + DC_REMOVAL_ALPHA * last_error_sample;
// float out_err = new_err - last_error_sample;
// last_error_sample = new_err;
// out_err = aa_filter_error.fir_step(out_err);
// out1[i] = out_err;
// reference samples filtering
// float new_ref = reference_sample + DC_REMOVAL_ALPHA * last_ref_sample;
// float out_ref = new_ref - last_ref_sample;
// last_ref_sample = out_ref;
// out_ref = aa_filter_ref.fir_step(out_ref);
// out2[i - 1] = out_ref;
// }
//}
template<int filter_length>
class NLMSFilter {
public:
typedef std::array<float, filter_length> samples_array;
typedef std::array<float, filter_length> filter_coeffs_array;
FIRFilter<filter_length> fir_filter;
NLMSFilter() : mu{ 0.5 }, _nlms_coefficients{ {0} }, _samples_buffer{ {0} }, filterSize{ filter_length }
{
fir_filter = FIRFilter<filter_length>(filterSize);
fir_filter.set_coefficients(_nlms_coefficients);
}
NLMSFilter(float mu, int filterSize) : mu{ mu }, _nlms_coefficients{ {0} }, _samples_buffer{ {0} }, filterSize(filterSize)
{
fir_filter = FIRFilter<filter_length>(filterSize);
fir_filter.set_coefficients(_nlms_coefficients);
}
NLMSFilter(float mu, filter_coeffs_array initial_filter) : mu{ mu }, filterSize(filter_length), _nlms_coefficients{0.0}, _samples_buffer{ {0.0} }
{
fir_filter = FIRFilter<filter_length>(filterSize);
fir_filter.set_coefficients(initial_filter);
}
void nlms_step(float *x_reference_sample, float *error_sample, float *outputBuffer, int blockSize) {
for (int j = 0; j < blockSize; j++)
{
// Shift samples buffer
for (long int i = filterSize - 1; i >= 1; --i) {
_samples_buffer[i] = _samples_buffer[i - 1];
}
_samples_buffer[0] = x_reference_sample[j];
// Update filter coefficients
nlms_filter_update((mu) *(error_sample[j]));
//x0 = _samples_buffer.at(filterSize - 1);
// Perform filtering step, to generate new y correction sample
*(outputBuffer++) = fir_filter.fir_step(x_reference_sample[j]);
}
}
void nlms_filter_update(float update_step) {
filter_coeffs_array filter_coeffs = fir_filter.get_coefficients();
for (int i = 0; i < filterSize; ++i) {
filter_coeffs.at(i) += _samples_buffer.at(i) * update_step;
}
fir_filter.set_coefficients(filter_coeffs);
}
private:
float mu; /**< step size that control filter coefficient updates. */
int filterSize;
filter_coeffs_array _nlms_coefficients;
samples_array _samples_buffer;
};
#pragma once
/*
MATLAB code for my NLMS
x = x;
xx = zeros(M,1);
w1 = zeros(M,1);
y = zeros(Ns,1);
e = zeros(Ns,1);
for n = 1:Ns
xx = [xx(2:M);x(n)];
y(n) = w1' * xx;
k = mu/(a + xx'*xx);
e(n) = d(n) - y(n);
w1 = w1 + k * e(n) * xx;
w(:,n) = w1;
end
*/
#include <vector>
#include <string.h>
#include "config.h"
//#include <omp.h>
namespace Adaptive {
class NLMS
{
int NumOfTaps; //filter size
float mu; //step size
float a; //R factor
int bufferSize = 0;
// Signal vectors
float y[FRAMES_PER_BUFFER] = { 0 }; // Output data
float w1[NUM_OF_TAPS] = { 0 }; // filter coeff.
float xx[NUM_OF_TAPS] = { 0 }; // vector to apply filter to
float err[FRAMES_PER_BUFFER] = { 0 };
float k = { 0 };
float errOutput[FRAMES_PER_BUFFER] = { 0 };
float Out[FRAMES_PER_BUFFER] = { 0 };
float AntyAliasOut[FRAMES_PER_BUFFER] = { 0 };
public:
NLMS(void);
NLMS(int size);
NLMS(int x, float y, float z);
~NLMS();
inline void processNLMS(float *x, float *e, float *out, int blockSize);
inline const float* getCoeff();
private:
inline void pushBack(float *a, float x);
};
//--------------------------------------------------------------------------------------------------------------------
/**
@brief Default constructor of NLMS class
@author Michal Berdzik
@version 0.1 05-07-2019
*/
NLMS::NLMS() : NumOfTaps(100), mu(0.5f), a(0.0001f)
{
memset(y, 0.0f, FRAMES_PER_BUFFER);
memset(xx, 0.0f, NumOfTaps);
memset(w1, 0.0f, NumOfTaps);
for (int i = 0; i < NumOfTaps; i++)
{
w1[i] = -1.0f + static_cast <float> (rand()) / (static_cast <float> (RAND_MAX / (2.0f)));
}
}
//--------------------------------------------------------------------------------------------------------------------
/**
@brief Parametrized constructor of NLMS class
@author Michal Berdzik
@version 0.1 05-07-2019
@param filterSize
@param stepSize
@param RFactor
*/
NLMS::NLMS(int filterSize, float stepSize, float RFactor) : NumOfTaps(filterSize), mu(stepSize), a(RFactor)
{
memset(y, 0, FRAMES_PER_BUFFER);
memset(xx, 0, NumOfTaps);
memset(w1, 0, NumOfTaps);
for (int i = 0; i < NumOfTaps; i++)
{
w1[i] = -1.0f + static_cast <float> (rand()) / (static_cast <float> (RAND_MAX / (2.0f)));
}
}
//--------------------------------------------------------------------------------------------------------------------
/**
@brief Destructor of NLMS class
@author Michal Berdzik
@version 0.1 05-07-2019
*/
NLMS::~NLMS()
{
}
//--------------------------------------------------------------------------------------------------------------------
/**
@brief processNLMS method of NLMS class
@author Michal Berdzik
@version 0.1 05-07-2019
@param vector<float> d - destiny sound input data
@param vector<float> x - noise sound input data
*/
/*
MATLAB code for my NLMS
x = x;
xx = zeros(M,1);
w1 = zeros(M,1);
y = zeros(Ns,1);
e = zeros(Ns,1);
for n = 1:Ns
xx = [xx(2:M);x(n)];
y(n) = w1' * xx;
k = mu/(a + xx'*xx);
e(n) = d(n) - y(n);
w1 = w1 + k * e(n) * xx;
w(:,n) = w1;
end
*/
//--------------------------------------------------------------------------------------------------------------------
/**
@brief processNLMS method of NLMS class
@author Michal Berdzik
@version 0.1 05-07-2019
@param float d - destiny sound input data
@param float x - noise sound input data
*/
void NLMS::processNLMS(float *x, float *d, float *out, int blockSize)
{
int i = 0;
int j = 0;
int l = 0;
float temp;
#pragma omp parallel sections
{
#pragma omp section
{
memset(&out[0], 0, blockSize * sizeof(float));
memset(&y[0], 0, blockSize * sizeof(float));
memset(&err[0], 0, blockSize * sizeof(float));
}
#pragma omp section
{
for (i = 0; i < blockSize; i++) {
pushBack(&xx[0], x[i]);
//xx[NumOfTaps - 1] = x[i];
xx[0] = x[i];
// filter input data
#pragma omp parallel for schedule(static, 4) reduction(+:y) reduction(+:temp)
for (j = 0, temp = 0; j < NumOfTaps; j+=4) {
y[i] += w1[j] * xx[j];
temp += xx[j] * xx[j];
y[i] += w1[j + 1] * xx[j + 1];
temp += xx[j + 1] * xx[j + 1];
y[i] += w1[j + 1] * xx[j + 1];
temp += xx[j + 1] * xx[j + 1];
y[i] += w1[j + 1] * xx[j + 1];
temp += xx[j + 1] * xx[j + 1];
}
out[i] = -y[i];
err[i] = d[i] - y[i];
k = mu / (a + temp);
// update filter coeff.
#pragma omp parallel for schedule(static, 4) reduction(+:w1)
for (l = 0; l < NumOfTaps; l+=4) {
w1[l] += (k * err[i] * xx[l]);
w1[l + 1] += (k * err[i] * xx[l + 1]);
w1[l + 2] += (k * err[i] * xx[l + 2]);
w1[l + 3] += (k * err[i] * xx[l + 3]);
}
//for (l = 0; l < NumOfTaps; l += 4) {
// w1[l] += (k * (-d[i]) * xx[l]);
// w1[l + 1] += (k * (-d[i]) * xx[l + 1]);
// w1[l + 2] += (k * (-d[i]) * xx[l + 2]);
// w1[l + 3] += (k * (-d[i]) * xx[l + 3]);
//}
}
}
}
}
//--------------------------------------------------------------------------------------------------------------------
/**
@brief pushBack method of NLMS class
@author Michal Berdzik
@version 0.1 05-07-2019
@param float &a - reference to array to push data to
@param float x - pushed data
*/
void NLMS::pushBack(float *a, float x)
{
//memmove(&a[0],&a[1], (NUM_OF_TAPS - 1) * sizeof(float));
//a[NUM_OF_TAPS] = x;
for (int i = NumOfTaps - 1; i > 0; --i) {
a[i] = a[i - 1];
}
}
const float* NLMS::getCoeff()
{
return &w1[0];
}
}
namespace Adaptive {
class FbLMS
{
int NumOfTaps; //filter size
//float mu = 0.0001; // Step Size
float w[NUM_OF_TAPS] = { 0 }; // Secondary Path
float out; // Filter Coefficient
float c[NUM_OF_TAPS];
float muedf[NUM_OF_TAPS];
float yQueue[NUM_OF_TAPS];
float dQueue[NUM_OF_TAPS];
float dfQueue[NUM_OF_TAPS];
float y; // Speaker Output
float yw; // Speaker Output Signal After Secondary Acoustic Path
float xw;
float d; // Estimated Reference Signal
float e;
float mue; // mu*e
float df; // Filtered Reference Signal
// FOR PREDICTING SEC-PATH
float r;
//float d; // Error Mic Input
float mu; // Step Size
float muTrain = 0.0000005f; // Step Size
float x[NUM_OF_TAPS]; // Generated Noise Queue
//float w[NUM_OF_TAPS]; // Secondary Path Coefficient
float muEX[NUM_OF_TAPS]; // mu*e*x Queue
//float y; // Estimated Error Mic Input
//float e; // e = d - y
//float mue; // mu*e
public:
FbLMS(void);
FbLMS(int size);
FbLMS(int x, float y);
~FbLMS();
void processFbLMS(float *error, float *output, int blockSize);
void predictSecPath(float *error, float *output, int blockSize);
void prepareForANC();
inline const float* getCoeff();
};
//--------------------------------------------------------------------------------------------------------------------
/**
@brief Default constructor of NLMS class
@author Michal Berdzik
@version 0.1 05-07-2019
*/
FbLMS::FbLMS() : NumOfTaps(100), mu(0.5)
{
}
//--------------------------------------------------------------------------------------------------------------------
/**
@brief Parametrized constructor of NLMS class
@author Michal Berdzik
@version 0.1 05-07-2019
@param filterSize
@param stepSize
@param RFactor
*/
FbLMS::FbLMS(int filterSize, float stepSize) : NumOfTaps(filterSize), mu(stepSize)
{
memset(c, 0.00001f, sizeof(float)*NUM_OF_TAPS);
memset(muedf, 0.00001f, sizeof(float)*NUM_OF_TAPS);
memset(yQueue, 0.00001f, sizeof(float)*NUM_OF_TAPS);
memset(dQueue, 0.00001f, sizeof(float)*NUM_OF_TAPS);
memset(dfQueue, 0.00001f, sizeof(float)*NUM_OF_TAPS);
memset(x, 0.00001f, sizeof(float)*NUM_OF_TAPS);
memset(muEX, 0.00001f, sizeof(float)*NUM_OF_TAPS);
}
//--------------------------------------------------------------------------------------------------------------------
/**
@brief Destructor of NLMS class
@author Michal Berdzik
@version 0.1 05-07-2019
*/
FbLMS::~FbLMS()
{
}
//--------------------------------------------------------------------------------------------------------------------
/**
@brief processNLMS method of NLMS class
@author Michal Berdzik
@version 0.1 05-07-2019
@param float d - destiny sound input data
@param float x - noise sound input data
*/
void FbLMS::processFbLMS(float *error, float *output, int blockSize)
{
for (int blockCount = 0; blockCount < blockSize; blockCount++)
{
arm_dot_prod_f32(w, yQueue, NumOfTaps, &yw);
d = e + yw;
int i = NumOfTaps;
while (i > 1)
{
dQueue[i - 1] = dQueue[i - 2];
i--;
}
dQueue[0] = d;
arm_dot_prod_f32(dQueue, c, NumOfTaps, &y);
out = -y;
//analogWrite(speakerPin, out);
output[blockCount] = out;
i = NumOfTaps;
while (i > 1)
{
yQueue[i - 1] = yQueue[i - 2];
i--;
}
yQueue[0] = y;
arm_dot_prod_f32(yQueue, w, NumOfTaps, &yw);
//adc->adc0->analogRead(micPin);
e = error[blockCount] - yw;
arm_dot_prod_f32(dQueue, w, NumOfTaps, &df);
i = NumOfTaps;
while (i > 1)
{
dfQueue[i - 1] = dfQueue[i - 2];
i--;
}
dfQueue[0] = df;
mue = mu * e;
arm_scale_f32(dfQueue, mue, muedf, NumOfTaps);
arm_add_f32(c, muedf, c, NumOfTaps);
}
}
void FbLMS::predictSecPath(float * error, float * output, int blockSize)
{
for (int blockCount = 0; blockCount < blockSize; blockCount++)
{
// Shift elements in Queue to the right and add latest element at the 0 position
int k = NumOfTaps;
while (k > 1)
{
x[k - 1] = x[k - 2];
k--;
}
r = -.6f + static_cast <float> (rand()) / (static_cast <float> (RAND_MAX / (1.2f)));
x[0] = r;
// Write signal to the speaker
//analogWrite(speakerPin, r);
output[blockCount] = r;
// Dot product
arm_dot_prod_f32(x, w, NumOfTaps, &y);
//adc->adc0->analogRead(micPin);
d = error[blockCount];
e = d - y;
mue = muTrain * e;
arm_scale_f32(x, mue, muEX, NumOfTaps);
arm_add_f32(w, muEX, w, NumOfTaps);
}
}
void FbLMS::prepareForANC()
{
float out = 0;
float y = 0; // Speaker Output
float yw = 0; // Speaker Output Signal After Secondary Acoustic Path
float d = 0; // Estimated Reference Signal
float e = 0;
float mue = 0; // mu*e
float df = 0;
}
//--------------------------------------------------------------------------------------------------------------------
const float* FbLMS::getCoeff()
{
return &c[0];
}
}
template<int filter_length>
class LMSFilter {
public:
typedef std::array<float, filter_length> samples_array;
typedef std::array<float, filter_length> filter_coeffs_array;
FIRFilter<filter_length> fir_filter;
LMSFilter(float alpha_val) : _alpha{ alpha_val }, _lms_coefficients{ {0} }, _samples_buffer{ {0} } {
fir_filter.set_coefficients(_lms_coefficients);
}
LMSFilter(float alpha_val, int filter_size) : _alpha{ alpha_val }, _lms_coefficients{ {0} }, _samples_buffer{ {0} }, filterSize(filter_size)
{
fir_filter.set_coefficients(_lms_coefficients);
}
LMSFilter(float alpha_val, filter_coeffs_array initial_filter) : _alpha{ alpha_val },
_lms_coefficients{
0.0 },
_samples_buffer{ {0.0} } {
fir_filter.set_coefficients(initial_filter);
}
LMSFilter(float alpha_val, filter_coeffs_array initial_filter, int filter_size) : _alpha{ alpha_val },
_lms_coefficients{ 0.0 }, _samples_buffer{ {0.0} }, filterSize(filter_size)
{
fir_filter.set_coefficients(initial_filter);
}
virtual float lms_step(float x_reference_sample, float error_sample,
float unfiltered_x_sample) {
// Shift samples buffer
for (long int i = filter_length - 1; i >= 1; --i) {
_samples_buffer[i] = _samples_buffer[i - 1];
}
_samples_buffer[0] = x_reference_sample;
// Update filter coefficients
lms_filter_update(
-(_alpha) *
(error_sample));
// Perform filtering step, to generate new y correction sample
return fir_filter.fir_step(unfiltered_x_sample);
}
void lms_filter_update(float update_step) {
filter_coeffs_array filter_coeffs = fir_filter.get_coefficients();
for (int i = 0; i < filter_length; ++i) {
filter_coeffs.at(i) = _lms_leak_factor * filter_coeffs.at(i)
+ _samples_buffer.at(i) * update_step;
}
fir_filter.set_coefficients(filter_coeffs);
}
filter_coeffs_array _lms_coefficients;
private:
float _alpha;
float _lms_leak_factor = LMS_LEAK_FACTOR;
int filterSize;
samples_array _samples_buffer;
};
template<int fx_filter_length, int filter_length>
class FxLMSFilter : public LMSFilter<filter_length> {
public:
typedef std::array<float, fx_filter_length> fx_filter_coeffs_array;
FxLMSFilter(float alpha_val, const fx_filter_coeffs_array s_filter) :
LMSFilter<filter_length>(alpha_val), _s_filter{ s_filter } {};
FxLMSFilter(float alpha_val, const fx_filter_coeffs_array s_filter, int filter_size) :
LMSFilter<filter_length>(alpha_val, filter_size), _s_filter{ s_filter }, filtersize(filter_size) {};
float lms_step(float x_reference_sample, float error_sample) {
float filtered_x_sample = _s_filter.fir_step(x_reference_sample);
return LMSFilter<filter_length>::lms_step(filtered_x_sample, error_sample, x_reference_sample);
}
void set_s_filter_coefficient(fx_filter_coeffs_array new_coeffs) {
_s_filter.set_coefficients(new_coeffs);
}
private:
FIRFilter<fx_filter_length> _s_filter;
int filtersize;
}; |
transpose_x_csc.c | #include "alphasparse/format.h"
#include <stdlib.h>
#include <alphasparse/opt.h>
#include <alphasparse/util.h>
#include <memory.h>
alphasparse_status_t ONAME(const ALPHA_SPMAT_CSC *A, ALPHA_SPMAT_CSC **B)
{
ALPHA_SPMAT_CSC *mat = alpha_malloc(sizeof(ALPHA_SPMAT_CSC));
*B = mat;
ALPHA_INT rowA = A->rows;
ALPHA_INT colA = A->cols;
mat->rows = colA;
mat->cols = rowA;
ALPHA_INT nnz = A->cols_end[colA - 1];
ALPHA_INT *cols_offset = alpha_memalign((mat->cols + 1) * sizeof(ALPHA_INT), DEFAULT_ALIGNMENT);
mat->cols_start = cols_offset;
mat->cols_end = cols_offset + 1;
mat->row_indx = alpha_memalign(nnz * sizeof(ALPHA_INT), DEFAULT_ALIGNMENT);
mat->values = alpha_memalign(nnz * sizeof(ALPHA_Number), DEFAULT_ALIGNMENT);
ALPHA_INT row_counter[rowA];
ALPHA_INT col_offset[mat->cols];
memset(row_counter, '\0', rowA * sizeof(ALPHA_INT));
for (ALPHA_INT i = 0; i < nnz; ++i)
{
row_counter[A->row_indx[i]] += 1;
}
col_offset[0] = 0;
mat->cols_start[0] = 0;
for (ALPHA_INT i = 1; i < mat->cols; ++i)
{
col_offset[i] = col_offset[i - 1] + row_counter[i - 1];
mat->cols_end[i - 1] = col_offset[i];
}
mat->cols_end[mat->cols - 1] = nnz;
ALPHA_INT num_threads = alpha_get_thread_num();
ALPHA_INT partition[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 = 0; ac < colA; ++ac)
{
for (ALPHA_INT ai = A->cols_start[ac]; ai < A->cols_end[ac]; ++ai)
{
ALPHA_INT bc = A->row_indx[ai];
if (bc < lcs || bc >= lch)
continue;
ALPHA_INT index = col_offset[bc];
mat->row_indx[index] = ac;
mat->values[index] = A->values[ai];
col_offset[bc] += 1;
}
}
}
return ALPHA_SPARSE_STATUS_SUCCESS;
} |
test3.c | int main() {
int x;
#pragma omp parallel
{
0;
int p;
if (1) {
2;
if (3) {
#pragma omp atomic write
x = 0;
4;
#pragma omp barrier
5;
} else {
6;
#pragma omp barrier
7;
}
8;
} else {
9;
if (10) {
11;
#pragma omp barrier
12;
} else {
13;
#pragma omp atomic read
p = x;
#pragma omp barrier
x;
14;
}
15;
}
16;
}
x = 10;
17;
}
|
ops.h | /*******************************************************************************
* Copyright (c) 2015-2018 Skymind, Inc.
*
* This program and the accompanying materials are made available under the
* terms of the Apache License, Version 2.0 which is available at
* https://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.
*
* SPDX-License-Identifier: Apache-2.0
******************************************************************************/
#pragma once
#ifndef OPS_H_
#define OPS_H_
#include <op_boilerplate.h>
#include <array/DataTypeUtils.h>
#include <helpers/shape.h>
#include <vector>
#include <Environment.h>
#include <loops/summarystatsreduce.h>
#include <loops/ReduceType.h>
#define MIN_V 1e-12
#define MAX_FLOAT 1e37
#define MIN_FLOAT 1e-37
#define MAX_INT 2147483647
#define MIN_CUTFOFF -3.79297773665f
#define FLOAT_MIN_NORMAL 1.17549435e-38
#define EPS 1e-5
#define AFFINITY close
#define DOUBLE_PI_T T(2.0 * 3.14159265358979323846)
#define DOUBLE_PI_X X(2.0 * 3.14159265358979323846)
#define no_op_exec_special_any static const bool requiresSpecial = false; static void execSpecial(X *dx, Nd4jLong *xShapeBuffer, Z *result, Nd4jLong *resultShapeBuffer, X *extraParams, Nd4jLong *tadShapeInfo, Nd4jLong *tadOffsets) {}
#define no_op_exec_special_bool static const bool requiresSpecial = false; static void execSpecial(X *dx, Nd4jLong *xShapeBuffer, Z *result, Nd4jLong *resultShapeBuffer, X *extraParams, Nd4jLong *tadShapeInfo, Nd4jLong *tadOffsets) {}
#define no_op_exec_special_same static const bool requiresSpecial = false; static void execSpecial(X *dx, Nd4jLong *xShapeBuffer, X *result, Nd4jLong *resultShapeBuffer, X *extraParams, Nd4jLong *tadShapeInfo, Nd4jLong *tadOffsets) {}
#define no_op_exec_special static const bool requiresSpecial = false; static void execSpecial(X *dx, Nd4jLong *xShapeBuffer, Z *result, Nd4jLong *resultShapeBuffer, Z *extraParams, Nd4jLong *tadShapeInfo, Nd4jLong *tadOffsets) {}
#define no_op_exec_special_accumulation static const bool requiresSpecialAccumulation = false; static void execSpecial(X *x, Nd4jLong *xShapeInfo, Z *extraParams, Z *result, Nd4jLong *resultShapeInfoBuffer, int *dimension, int dimensionLength, Nd4jLong *tadShapeInfo, Nd4jLong *tadOffset){}
#define no_op_exec_special_accumulation_long static const bool requiresSpecialAccumulation = false; static void execSpecial(X *x, Nd4jLong *xShapeInfo, X *extraParams, Z *result, Nd4jLong *resultShapeInfoBuffer, int *dimension, int dimensionLength, Nd4jLong *tadShapeInfo, Nd4jLong *tadOffset){}
#define no_op_exec_special_accumulation_same static const bool requiresSpecialAccumulation = false; static void execSpecial(X *x, Nd4jLong *xShapeInfo, X *extraParams, X *result, Nd4jLong *resultShapeInfoBuffer, int *dimension, int dimensionLength, Nd4jLong *tadShapeInfo, Nd4jLong *tadOffset){}
#ifdef __CUDACC__
#define no_op_exec_special_any_cuda static __device__ void execSpecialCuda(X *dx, Nd4jLong *xShapeBuffer, Z *result, Nd4jLong *resultShapeBuffer, X *extraParams, int *allocationPointer, Z *reductionPointer, Nd4jLong *tadShapeInfo, Nd4jLong *tadOffsets) {}
#define no_op_exec_special_bool_cuda static __device__ void execSpecialCuda(X *dx, Nd4jLong *xShapeBuffer, Z *result, Nd4jLong *resultShapeBuffer, X *extraParams, int *allocationPointer, Z *reductionPointer, Nd4jLong *tadShapeInfo, Nd4jLong *tadOffsets) {}
#define no_op_exec_special_same_cuda static __device__ void execSpecialCuda(X *dx, Nd4jLong *xShapeBuffer, X *result, Nd4jLong *resultShapeBuffer, X *extraParams, int *allocationPointer, X *reductionPointer, Nd4jLong *tadShapeInfo, Nd4jLong *tadOffsets) {}
#define no_op_exec_special_cuda static __device__ void execSpecialCuda(X *dx, Nd4jLong *xShapeBuffer,Z *result, Nd4jLong *resultShapeBuffer,Z *extraParams, int *allocationPointer, Z *reductionPointer, Nd4jLong *tadShapeInfo, Nd4jLong *tadOffsets) {}
#define no_op_exec_special_accumulation_same_cuda static inline __device__ void execSpecialCuda(X *dx, Nd4jLong *xShapeInfo, X *extraParams, X *result, Nd4jLong *resultShapeInfo, int *dimension, int dimensionLength, X *reductionBuffer, Nd4jLong *tadOnlyShapeInfo, Nd4jLong *tadOffsets) {}
#define no_op_exec_special_accumulation_long_cuda static inline __device__ void execSpecialCuda(X *dx, Nd4jLong *xShapeInfo, X *extraParams, Z *result, Nd4jLong *resultShapeInfo, int *dimension, int dimensionLength, Z *reductionBuffer, Nd4jLong *tadOnlyShapeInfo, Nd4jLong *tadOffsets) {}
#define no_op_exec_special_accumulation_cuda static inline __device__ void execSpecialCuda(X *dx, Nd4jLong *xShapeInfo, Z *extraParams, Z *result, Nd4jLong *resultShapeInfo, int *dimension, int dimensionLength, Z *reductionBuffer, Nd4jLong *tadOnlyShapeInfo, Nd4jLong *tadOffsets) {}
#else
// hacky fix for isnan/being being out of scope
//#ifdef IOS
//#define isinf(x) 0 // this isn't right. But std::isinf fails
//#define isnan(x) 0
//#else
//#define isnan std::isnan
//#define isinf std::isinf
//#endif
#define no_op_exec_special_cuda
#define no_op_exec_special_accumulation_cuda
#define no_op_exec_special_accumulation_same_cuda
#define no_op_exec_special_accumulation_long_cuda
#define no_op_exec_special_any_cuda
#define no_op_exec_special_bool_cuda
#define no_op_exec_special_same_cuda
#define no_op_exec_special_accumulation_same_cuda
#endif
#define SELU_ALPHA 1.6732632423543772848170429916717
#define SELU_LAMBDA 1.0507009873554804934193349852946
#ifdef _OPENMP
#pragma omp declare reduction(maxTF : float,double,float16,bfloat16 : \
omp_out = nd4j::math::nd4j_max(omp_in, omp_out) )\
initializer (omp_priv=-MAX_FLOAT)
#pragma omp declare reduction(minTF : float,double,float16,bfloat16 : \
omp_out = nd4j::math::nd4j_min(omp_in, omp_out) )\
initializer (omp_priv=MAX_FLOAT)
#pragma omp declare reduction(maxT : float,double,float16,bfloat16,int,Nd4jLong,Nd4jULong,int8_t,uint8_t,bool,int16_t,uint16_t,uint32_t : \
omp_out = nd4j::math::nd4j_max(omp_in, omp_out) )\
initializer (omp_priv=0)
#pragma omp declare reduction(minT : float,double,float16,bfloat16,int,Nd4jLong,Nd4jULong,int8_t,uint8_t,bool,int16_t,uint16_t,uint32_t : \
omp_out = nd4j::math::nd4j_min(omp_in, omp_out) )\
initializer (omp_priv=0)
#pragma omp declare reduction(amaxT : float,double,float16,bfloat16,int,Nd4jLong,Nd4jULong,int8_t,uint8_t,bool,int16_t,uint16_t,uint32_t : \
omp_out = nd4j::math::nd4j_max(nd4j::math::nd4j_abs(omp_in), nd4j::math::nd4j_abs(omp_out)) )
#pragma omp declare reduction(aminT : float,double,float16,bfloat16,int,Nd4jLong,Nd4jULong,int8_t,uint8_t,bool,int16_t,uint16_t,uint32_t : \
omp_out = nd4j::math::nd4j_min(nd4j::math::nd4j_abs(omp_in), nd4j::math::nd4j_abs(omp_out)) )
#pragma omp declare reduction(asumT : float,double,float16,bfloat16,int,Nd4jLong,Nd4jULong,int8_t,uint8_t,bool,int16_t,uint16_t,uint32_t : \
omp_out = nd4j::math::nd4j_abs(omp_in) + nd4j::math::nd4j_abs(omp_out))\
initializer (omp_priv=0)
#pragma omp declare reduction(sumT : float,double,float16,bfloat16,int,Nd4jLong,Nd4jULong,int8_t,uint8_t,bool,int16_t,uint16_t,uint32_t : \
omp_out = omp_in + omp_out)\
initializer (omp_priv=0)
#pragma omp declare reduction(prodT : float,double,float16,bfloat16,int,Nd4jLong,Nd4jULong,int8_t,uint8_t,bool,int16_t,uint16_t,uint32_t : \
omp_out = omp_in * omp_out)\
initializer (omp_priv=1)
#endif
namespace functions {
namespace indexreduce {
template <typename T>
struct IndexValue {
T value;
Nd4jLong index;
_CUDA_HD IndexValue() = default;
_CUDA_HD IndexValue(const T val, const Nd4jLong ind): index(ind), value(val) {}
};
}
namespace summarystats {
template <typename T>
class SummaryStatsData;
}
}
namespace simdOps {
template <typename X, typename Y, typename Z>
class Add {
public:
op_def static Z op(X d1, Y d2) {
return static_cast<Z>(d1 + d2);
}
op_def static Z op(X d1, Y d2, Z *params) {
return static_cast<Z>(d1 + d2);
}
op_def static Z op(X d1) {
return static_cast<Z>(d1);
}
// op for MetaOps
op_def static Z op(X d1, Y *params) {
return static_cast<Z>(d1 + params[0]);
}
op_def static X startingValue() {
return static_cast<X>(0.f);
}
};
template <typename X, typename Y>
class NewAdd {
public:
op_def static X op(X d1, Y d2, X *params) {
return d1 + d2;
}
};
template <typename X, typename Y, typename Z>
class Subtract {
public:
op_def static Z op(X d1, Y d2) {
return static_cast<Z>(d1 - d2);
}
op_def static Z op(X d1, Y d2, Z *params) {
return static_cast<Z>(d1 - d2);
}
op_def static Z op(X d1) {
return static_cast<Z>(d1);
}
// op for MetaOps
op_def static Z op(X d1, Y *params) {
return static_cast<Z>(d1 - params[0]);
}
};
template <typename X, typename Y, typename Z>
class SquaredSubtract {
public:
op_def static Z op(X d1, Y d2) {
auto d = static_cast<Z>(d1 - d2);
return d * d;
}
op_def static Z op(X d1, Y d2, Z *params) {
auto d = static_cast<Z>(d1 - d2);
return d * d;
}
op_def static Z op(X d1) {
return d1;
}
// op for MetaOps
op_def static Z op(X d1, Y *params) {
auto d = static_cast<Z>(d1 - params[0]);
return d * d;
}
};
template <typename X, typename Y, typename Z>
class SquaredReverseSubtract {
public:
op_def static Z op(X d1, Y d2) {
auto d = static_cast<Z>(d2 - d1);
return d * d;
}
op_def static Z op(X d1, Y d2, Z *params) {
auto d = static_cast<Z>(d2 - d1);
return d * d;
}
op_def static Z op(X d1) {
return d1;
}
// op for MetaOps
op_def static Z op(X d1, Y *params) {
auto d = static_cast<Z>(params[0] - d1);
return d * d;
}
};
template <typename X, typename Y, typename Z>
class ReverseSubtract {
public:
op_def static Z op(X d1, Y d2) {
return static_cast<Z>(d2 - d1);
}
op_def static Z op(X d1, Y d2, Z *params) {
return static_cast<Z>(d2 - d1);
}
op_def static Z op(X d1) {
return d1;
}
// op for MetaOps
op_def static Z op(X d1, Y *params) {
return static_cast<Z>(params[0] - d1);
}
};
template <typename X, typename Y, typename Z>
class LogPoissonLossFull {
public:
op_def static Z op(X z, Y c) {
auto zz = static_cast<Z>(z);
auto zc = static_cast<Z>(c);
return (nd4j::math::nd4j_exp<Y, Z>(c) - zz * zc + (zz * nd4j::math::nd4j_log<X, Z>(z) - zz + static_cast<Z>(0.5f) * nd4j::math::nd4j_log<Z, Z>(static_cast<Z>(DOUBLE_PI_X) * zz)));
}
op_def static Z op(X z, Y c, Z *params) {
auto zz = static_cast<Z>(z);
auto zc = static_cast<Z>(c);
return (nd4j::math::nd4j_exp<Y, Z>(c) - zz * zc + (zz * nd4j::math::nd4j_log<X, Z>(z) - zz + static_cast<Z>(0.5f) * nd4j::math::nd4j_log<Z, Z>(static_cast<Z>(DOUBLE_PI_X) * zz)));
}
op_def static Z op(X z) {
auto zz = static_cast<Z>(z);
return (zz * nd4j::math::nd4j_log<Y, Z>(z) - zz + static_cast<Z>(0.5f) * nd4j::math::nd4j_log<Z, Z>(static_cast<Z>(DOUBLE_PI_X) * zz));
}
// op for MetaOps
op_def static X op(X z, Y *params) {
return (nd4j::math::nd4j_exp<X, X>(params[0]) - z * params[0] + (z * nd4j::math::nd4j_log<X, Z>(z) - z + static_cast<X>(0.5f) * nd4j::math::nd4j_log<X, Z>(DOUBLE_PI_X * z)));
}
};
template <typename X, typename Y, typename Z>
class LogPoissonLoss {
public:
op_def static Z op(X z, Y c) {
auto zz = static_cast<Z>(z);
auto zc = static_cast<Z>(c);
return (nd4j::math::nd4j_exp<Y, Z>(c) - zz * zc);
}
op_def static Z op(X z, Y c, Z *params) {
auto zz = static_cast<Z>(z);
auto zc = static_cast<Z>(c);
return (nd4j::math::nd4j_exp<Y, Z>(c) - zz * zc);
}
op_def static Z op(X z) {
return static_cast<Z>(z);
}
// op for MetaOps
op_def static Z op(X z, Y *params) {
return (nd4j::math::nd4j_exp<Y, Z>(params[0]) - static_cast<Z>(z) * static_cast<Z>(params[0]));
}
};
template <typename X, typename Y, typename Z>
class Multiply {
public:
op_def static Z op(X d1, Y d2) {
return static_cast<Z>(d1 * d2);
}
op_def static Z op(X d1, Y d2, Z *params) {
return static_cast<Z>(d1 * d2);
}
op_def static Z op(X d1) {
return static_cast<Z>(d1);
}
// op for MetaOps
op_def static Z op(X d1, Y *params) {
return static_cast<Z>(d1 * params[0]);
}
op_def static X startingValue() {
return static_cast<X>(1.f);
}
};
template <typename X, typename Y, typename Z>
class Divide {
public:
op_def static Z op(X d1, Y d2) {
return static_cast<Z>(d1 / d2);
}
op_def static Z op(X d1, Y d2, Z *params) {
return static_cast<Z>(d1 / d2);
}
op_def static Z op(X d1) {
return static_cast<Z>(d1);
}
// op for MetaOps
op_def static Z op(X d1, Y *params) {
return static_cast<Z>(d1 / params[0]);
}
op_def static X startingValue() {
return static_cast<X>(1);
}
};
template <typename X, typename Y, typename Z>
class SafeDivide {
public:
op_def static Z op(X d1, Y d2) {
if(d2 == static_cast<Y>(0))
return static_cast<Z>(0);
return static_cast<Z>(d1 / d2);
}
op_def static Z op(X d1, Y d2, Z *params) {
if(d2 == static_cast<Y>(0))
return static_cast<Z>(0);
return static_cast<Z>(d1 / d2);
}
op_def static Z op(X d1) {
return static_cast<Z>(d1);
}
// op for MetaOps
op_def static Z op(X d1, Y *params) {
if(params[0] == static_cast<Y>(0))
return static_cast<Z>(0);
return static_cast<Z>(d1 / params[0]);
}
};
template <typename X, typename Y, typename Z>
class FloorDiv {
public:
op_def static Z op(X d1, Y d2) {
return nd4j::math::nd4j_floor<Z,Z>(static_cast<Z>(d1 / d2));
}
op_def static Z op(X d1, Y d2, Z *params) {
return nd4j::math::nd4j_floor<Z,Z>(static_cast<Z>(d1 / d2));
}
op_def static Z op(X d1) {
return nd4j::math::nd4j_floor<Z,Z>(static_cast<Z>(d1));
}
// op for MetaOps
op_def static Z op(X d1, Y *params) {
return nd4j::math::nd4j_floor<Z,Z>(static_cast<Z>(d1 / params[0]));
}
};
template <typename X, typename Y, typename Z>
class TruncateDiv {
public:
op_def static Z op(X d1, Y d2) {
auto i1 = static_cast<int>(d1);
auto i2 = static_cast<int>(d2);
return static_cast<Z>(i1 / i2);
}
op_def static Z op(X d1, Y d2, Z *params) {
auto i1 = static_cast<int>(d1);
auto i2 = static_cast<int>(d2);
return static_cast<Z>(i1 / i2);
}
op_def static Z op(X d1) {
return d1;
}
// op for MetaOps
op_def static Z op(X d1, Y *params) {
auto i1 = static_cast<int>(d1);
auto i2 = static_cast<int>(params[0]);
return static_cast<Z>(i1 / i2);
}
};
template <typename X, typename Y, typename Z>
class TruncateMod {
public:
op_def static Z op(X d1, Y d2) {
auto i1 = static_cast<int>(d1);
auto i2 = static_cast<int>(d2);
return static_cast<Z>(i1 % i2);
}
op_def static Z op(X d1, Y d2, Z *params) {
auto i1 = static_cast<int>(d1);
auto i2 = static_cast<int>(d2);
return static_cast<Z>(i1 % i2);
}
op_def static Z op(X d1) {
return static_cast<Z>(d1);
}
// op for MetaOps
op_def static Z op(X d1, Y *params) {
auto i1 = static_cast<int>(d1);
auto i2 = static_cast<int>(params[0]);
return static_cast<Z>(i1 % i2);
}
};
template<typename X, typename Y, typename Z>
class Remainder {
public:
op_def static Z op(X d1, Y d2) {
return nd4j::math::nd4j_remainder<X, Y, Z>(d1, d2);
}
op_def static Z op(X d1, Y d2, Z *params) {
return nd4j::math::nd4j_remainder<X, Y, Z>(d1, d2);
}
op_def static Z op(X d1) {
return d1;
}
// op for MetaOps
op_def static Z op(X d1, Y *params) {
return nd4j::math::nd4j_remainder<X, Y, Z>(d1, params[0]);
}
};
template <typename X, typename Y, typename Z>
class FMod {
public:
op_def static Z op(X d1, Y d2) {
return nd4j::math::nd4j_fmod<X, Y, Z>(d1, d2);
}
op_def static Z op(X d1, Y d2, Z *params) {
return nd4j::math::nd4j_fmod<X, Y, Z>(d1, d2);
}
op_def static Z op(X d1) {
return d1;
}
// op for MetaOps
op_def static Z op(X d1, Y *params) {
return nd4j::math::nd4j_fmod<X, Y, Z>(d1, params[0]);
}
};
template <typename X, typename Y, typename Z>
class FloorMod {
public:
op_def static Z op(X d1, Y d2) {
auto m = nd4j::math::nd4j_fmod<X, Y, Z>(d1, d2);
return (d1 < static_cast<X>(0)) == (d2 < static_cast<Y>(0)) ? m : nd4j::math::nd4j_fmod<Z, Y, Z>(m + static_cast<Z>(d2), d2);
}
op_def static Z op(X d1, Y d2, Z *params) {
auto m = nd4j::math::nd4j_fmod<X, Y, Z>(d1, d2);
return (d1 < static_cast<X>(0.0f)) == (d2 < static_cast<Y>(0)) ? m : nd4j::math::nd4j_fmod<Z, Y, Z>(m + static_cast<Z>(d2), d2);
}
op_def static Z op(X d1) {
return d1;
}
// op for MetaOps
op_def static Z op(X d1, Y *params) {
return op(d1, params[0]);
}
};
template <typename X, typename Y, typename Z>
class ReverseDivide {
public:
op_def static Z op(X d1, Y d2) {
return static_cast<Z>(d2 / d1);
}
op_def static Z op(X d1, Y d2, Z *params) {
return static_cast<Z>(d2 / d1);
}
op_def static Z op(X d1) {
return static_cast<Z>(d1);
}
// op for MetaOps
op_def static Z op(X d1, Y *params) {
return static_cast<Z>(params[0] / d1);
}
};
template <typename X, typename Y, typename Z>
class CopyPws {
public:
op_def static Z op(X d1, Y d2) {
return static_cast<Z>(d2);
}
op_def static Z op(X d1, Y d2, Z *params) {
return static_cast<Z>(d2);
}
op_def static Z op(X d1) {
return static_cast<Z>(d1);
}
op_def static Z op(X d1, Y *params) {
return static_cast<Z>(d1);
}
};
template <typename X>
class Copy {
public:
no_op_exec_special_same
no_op_exec_special_same_cuda
op_def static X op(X d1, X *params) {
return d1;
}
};
template <typename X, typename Y, typename Z>
class Copy2 {
public:
op_def static Z op(X d1, Y d2) {
return static_cast<Z>(d2);
}
op_def static Z op(X d1, Y d2, Z *params) {
return static_cast<Z>(d2);
}
op_def static Z op(X d1) {
return static_cast<Z>(d1);
}
op_def static Z op(X d1, Y *params) {
return static_cast<Z>(d1);
}
};
template <typename X, typename Y, typename Z>
class Axpy {
public:
op_def static Z op(X d1, Y d2) {
return static_cast<Z>(d2 + d1);
}
op_def static Z op(X d1, Y d2, Z *params) {
auto alpha = params[0];
return alpha * static_cast<Z>(d1) + static_cast<Z>(d2);
}
op_def static Z op(X d1) {
return static_cast<Z>(d1);
}
};
template <typename X, typename Z>
class Assign {
public:
no_op_exec_special_any
no_op_exec_special_any_cuda
op_def static Z op(X d1, X *params) {
return static_cast<Z>(d1);
}
};
template <typename X, typename Z>
class And {
public:
no_op_exec_special_bool
no_op_exec_special_bool_cuda
op_def static Z op(X d1, X d2) {
return d2 + d1;
}
op_def static Z op(X d1, X d2, X *params) {
if (params != nullptr) {
auto comp = params[0];
return d1 != comp && d2 != comp ? static_cast<Z>(1) : static_cast<Z>(0);
} else {
auto b1 = static_cast<bool>(d1);
auto b2 = static_cast<bool>(d2);
return (b1 && b2) ? static_cast<Z>(1) : static_cast<Z>(0);
}
}
op_def static Z op(X d1) {
return d1;
}
// op for MetaOps
op_def static Z op(X d1, X *params) {
return static_cast<Z>(119);
}
};
template <typename X>
class IntOr {
public:
op_def static X op(X d1, X d2) {
return d2 | d1;
}
op_def static X op(X d1, X d2, X *params) {
return op(d1, d2);
}
};
template <typename X>
class IntAnd {
public:
op_def static X op(X d1, X d2) {
return d2 & d1;
}
op_def static X op(X d1, X d2, X *params) {
return op(d1, d2);
}
};
template <typename X>
class IntXor {
public:
op_def static X op(X d1, X d2) {
return d2 ^ d1;
}
op_def static X op(X d1, X d2, X *params) {
return op(d1, d2);
}
};
template <typename X>
class ShiftLeft {
public:
op_def static X op(X d1, X d2) {
return d1 << d2;
}
op_def static X op(X d1, X d2, X *params) {
return op(d1, d2);
}
};
template <typename X>
class ShiftRight {
public:
op_def static X op(X d1, X d2) {
return d1 >> d2;
}
op_def static X op(X d1, X d2, X *params) {
return op(d1, d2);
}
};
template <typename X>
class CyclicShiftLeft {
public:
op_def static X op(X d1, X d2) {
return d1 << d2 | d1 >> ((sizeof(X) * 8) - d2);
}
op_def static X op(X d1, X d2, X *params) {
return op(d1, d2);
}
};
template <typename X>
class CyclicShiftRight {
public:
op_def static X op(X d1, X d2) {
return d1 >> d2 | d1 << ((sizeof(X) * 8) - d2);
}
op_def static X op(X d1, X d2, X *params) {
return op(d1, d2);
}
};
template <typename X, typename Z>
class Or {
public:
no_op_exec_special_bool
no_op_exec_special_bool_cuda
op_def static Z op(X d1, X d2) {
return d2 + d1;
}
op_def static Z op(X d1, X d2, X *params) {
if (params != nullptr) {
auto comp = params[0];
return d1 != comp || d2 != comp ? static_cast<Z>(1) : static_cast<Z>(0);
} else {
auto b1 = static_cast<bool>(d1);
auto b2 = static_cast<bool>(d2);
return b1 || b2 ? static_cast<Z>(1) : static_cast<Z>(0);
}
}
op_def static Z op(X d1) {
return d1;
}
// op for MetaOps
op_def static Z op(X d1, X *params) {
return static_cast<Z>(119);
}
};
template <typename X, typename Z>
class Xor {
public:
no_op_exec_special_bool
no_op_exec_special_bool_cuda
op_def static Z op(X d1, X d2) {
return d2 + d1;
}
op_def static Z op(X d1, X d2, X *params) {
if (params != nullptr) {
auto comp = params[0];
return ((d1 == comp && d2 != comp) || (d1 != comp && d2 == comp)) ? static_cast<Z>(1) : static_cast<Z>(0);
} else {
auto b1 = static_cast<bool>(d1);
auto b2 = static_cast<bool>(d2);
return (!b1 && b2 )||(b1 && !b2) ? static_cast<Z>(1) : static_cast<Z>(0);
}
}
op_def static Z op(X d1) {
return d1;
}
};
template <typename X, typename Z>
class Not {
public:
no_op_exec_special_bool
no_op_exec_special_bool_cuda
op_def static Z op(X d1, X d2) {
return static_cast<Z>(0);
}
op_def static Z op(X d1, X d2, X *params) {
return d1 != d2 ? static_cast<Z>(1) : static_cast<Z>(0);
}
// this transform op should run only on boolean input
op_def static Z op(X d1, X *params) {
auto b1 = static_cast<bool>(d1);
return !b1;
}
};
template <typename X, typename Y, typename Z>
class LogicalNot {
public:
op_def static Z op(X d1, Y d2) {
return !((int) d1 && (int) d2);
}
op_def static Z op(X d1, Y d2, Z *params) {
return static_cast<X>(!(static_cast<int>(d1) && static_cast<int>(d2)));
}
op_def static Z op(X d1) {
return d1;
}
// op for MetaOps
op_def static Z op(X d1, Y *params) {
return static_cast<X>(119);
}
};
template <typename X, typename Y, typename Z>
class LogicalXor {
public:
op_def static Z op(X d1, Y d2) {
auto i1 = static_cast<int>(d1);
auto i2 = static_cast<int>(d2);
return (i1 | i2) &~ (i1 & i2);
}
op_def static Z op(X d1, Y d2, Z *params) {
return op(d1, d2);
}
op_def static Z op(X d1) {
return d1;
}
// op for MetaOps
op_def static Z op(X d1, Y *params) {
return static_cast<Z>(119);
}
};
template <typename X, typename Y, typename Z>
class LogicalAnd {
public:
op_def static Z op(X d1, Y d2) {
return static_cast<int>(d1) & static_cast<int>(d2);
}
op_def static Z op(X d1, Y d2, Z *params) {
return op(d1, d2);
}
op_def static Z op(Y d1) {
return d1;
}
// op for MetaOps
op_def static Z op(X d1, Y *params) {
return static_cast<Z>(119);
}
};
template <typename X, typename Y, typename Z>
class LogicalOr {
public:
op_def static Z op(X d1, Y d2) {
return static_cast<int>(d1) | static_cast<int>(d2);
}
op_def static Z op(X d1, Y d2, Z *params) {
return op(d1, d2);
}
op_def static Z op(X d1) {
return d1;
}
// op for MetaOps
op_def static Z op(X d1, Y *params) {
return static_cast<X>(119);
}
};
template <typename X, typename Y, typename Z>
class Mod {
public:
/*
// just a optional note, feel free to remove later
op_def static half op(half d1, half d2, half *params) {
return __float2half(simdOps::Mod<float>::op(__half2float(d1), __half2float(d2), nullptr));
}
*/
op_def static Z op(X d1, Y d2) {
return static_cast<int>(d1) % static_cast<int>(d2);
}
op_def static Z op(X d1, Y d2, Z *params) {
return op(d1, d2);
}
// op for MetaOp
op_def static Z op(X d1, Y *params) {
return op(d1, params[0]);
}
};
template <typename X, typename Y, typename Z>
class ReverseMod {
public:
op_def static Z op(X d1, Y d2) {
return static_cast<int>(d2) % static_cast<int>(d1);
}
op_def static Z op(X d1, Y d2, Z *params) {
return op(d1, d2);
}
// op for MetaOp
op_def static Z op(X d1, Y *params) {
return op(d1, params[0]);
}
};
/**
* Whether 2 elements in an array
* are epsilion equal
*/
template <typename X, typename Z>
class Epsilon {
public:
op_def static Z op(X d1, X d2) {
X diff = d1 - d2;
X absDiff = nd4j::math::nd4j_abs<X>(diff);
if (absDiff <= static_cast<X>(MIN_V))
return static_cast<Z>(1);
return static_cast<Z>(0);
}
op_def static Z op(X d1, X d2, X *params) {
return op(d1, d2);
}
op_def static Z op(X d1, X *params) {
return d1;
}
};
template <typename X, typename Z>
class EqualTo {
public:
op_def static Z op(X d1, X d2) {
return d1 == d2;
}
op_def static Z op(X d1, X d2, X *params) {
return op(d1, d2);
}
op_def static Z op(X d1, X *params) {
return d1;
}
};
template <typename X, typename Z>
class NotEqualTo {
public:
op_def static Z op(X d1, X d2) {
return d1 != d2;
}
op_def static Z op(X d1, X d2, X *params) {
return op(d1, d2);
}
op_def static Z op(X d1, X *params) {
return d1;
}
};
template <typename X, typename Z>
class GreaterThanOrEqual {
public:
op_def static Z op(X d1, X d2) {
return d1 >= d2;
}
op_def static Z op(X d1, X d2, X *params) {
return op(d1, d2);
}
// FIXME: this signature clashes with MetaOp stuff
op_def static Z op(X d1, X *params) {
return d1;
}
};
template <typename X, typename Z>
class GreaterThan {
public:
op_def static Z op(X d1, X d2) {
return d1 > d2;
}
op_def static Z op(X d1, X d2, X *params) {
return op(d1, d2);
}
// FIXME: this signature clashes with MetaOp stuff
op_def static Z op(X d1, X *params) {
return d1;
}
};
template <typename X, typename Z>
class LessThan {
public:
op_def static Z op(X d1, X d2) {
return d1 < d2;
}
op_def static Z op(X d1, X d2, X *params) {
return op(d1, d2);
}
op_def static Z op(X d1, X *params) {
return d1;
}
};
template <typename X, typename Z>
class LessThanOrEqual {
public:
op_def static Z op(X d1, X d2) {
return d1 <= d2;
}
op_def static Z op(X d1, X d2, X *params) {
return op(d1, d2);
}
op_def static Z op(X d1, X *params) {
return d1;
}
};
template <typename X>
class Abs {
public:
no_op_exec_special_same
no_op_exec_special_same_cuda
op_def static X op(X d1, X *params) {
return nd4j::math::nd4j_abs<X>(d1);
}
};
template <typename X>
class Ceiling {
public:
no_op_exec_special_same
no_op_exec_special_same_cuda
op_def static X op(X d1, X *params) {
return nd4j::math::nd4j_ceil<X,X>(d1);
}
};
template <typename X>
class Cosine {
public:
no_op_exec_special_same
no_op_exec_special_same_cuda
op_def static X op(X d1, X *params) {
return nd4j::math::nd4j_cos<X,X>(d1);
}
};
template <typename X>
class Exp {
public:
no_op_exec_special_same
no_op_exec_special_same_cuda
op_def static X op(X d1, X *params) {
return nd4j::math::nd4j_exp<X, X>(d1);
}
};
template <typename X>
class HardTanhDerivative {
public:
no_op_exec_special_same
no_op_exec_special_same_cuda
op_def static X op(X d1, X *params) {
return ((d1 >= static_cast<X>(-1.f) && d1 <= static_cast<X>(1.f)) ? static_cast<X>(1.f) : static_cast<X>(0.f));
}
};
template <typename X>
class HardTanh {
public:
no_op_exec_special_same
no_op_exec_special_same_cuda
op_def static X op(X d1, X *params) {
if (d1 < static_cast<X>(-1))
return static_cast<X>(-1);
else if (d1 > static_cast<X>(1))
return static_cast<X>(1);
else
return d1;
}
};
template <typename X>
class Floor {
public:
no_op_exec_special_same
no_op_exec_special_same_cuda
op_def static X op(X d1, X *params) {
return nd4j::math::nd4j_floor<X,X>(d1);
}
};
template <typename X>
class Log {
public:
no_op_exec_special_same
no_op_exec_special_same_cuda
op_def static X op(X d1, X *params) {
return nd4j::math::nd4j_log<X, X>(d1);
}
};
template <typename X>
class Log1p {
public:
no_op_exec_special_same
no_op_exec_special_same_cuda
op_def static X op(X d1, X *params) {
return nd4j::math::nd4j_log<X, X>(1 + d1);
}
};
template <typename X, typename Y, typename Z>
class LogX {
public:
op_def static Z op(X d1, Y d2, Z *params) {
return nd4j::math::nd4j_log<X, Z>(d1) / nd4j::math::nd4j_log<Y, Z>(d2) ;
}
};
template <typename X>
class StabilizeFP16 {
public:
no_op_exec_special_same
no_op_exec_special_same_cuda
op_def static X op(X d1, X *params) {
if (d1 <= static_cast<X>(0))
return static_cast<X>(nd4j::DataTypeUtils::min<float16>());
else return d1;
}
};
template <typename X>
class StabilizeX {
public:
no_op_exec_special_same
no_op_exec_special_same_cuda
op_def static X op(X d1, X *params) {
if (d1 <= static_cast<X>(0))
return nd4j::DataTypeUtils::min<X>();
else return d1;
}
};
template <typename X>
class SpecialDerivative {
public:
no_op_exec_special_same
no_op_exec_special_same_cuda
op_def static X op(X d1, X *params) {
return d1 * (static_cast<X>(1.f) - d1);
}
};
template <typename X>
class Neg {
public:
no_op_exec_special_same
no_op_exec_special_same_cuda
op_def static X op(X d1, X *params) {
return -d1;
}
};
template <typename X>
class Erf {
public:
no_op_exec_special_same
no_op_exec_special_same_cuda
op_def static X op(X d1, X *params) {
return nd4j::math::nd4j_erf<X,X>(d1);
}
};
template <typename X>
class Erfc {
public:
no_op_exec_special_same
no_op_exec_special_same_cuda
op_def static X op(X d1, X *params) {
return nd4j::math::nd4j_erfc<X,X>(d1);
}
};
template <typename X>
class Reciprocal {
public:
no_op_exec_special_same
no_op_exec_special_same_cuda
// op_def static T op(T d1) {
// return (T(1.0f) / d1);
// }
// op for MetaOps
op_def static X op(X d1, X *params) {
return (static_cast<X>(1) / d1);
}
};
template <typename X, typename Z>
class Sqr {
public:
no_op_exec_special
no_op_exec_special_cuda
op_def static Z op(X d1, Z *params) {
return nd4j::math::nd4j_pow<X, X, Z>(d1, static_cast<X>(2));
}
op_def static Z op(X d1) {
return nd4j::math::nd4j_pow<X, X, Z>(d1, static_cast<X>(2));
}
};
template <typename X, typename Y, typename Z>
class RelativeError {
public:
no_op_exec_special
no_op_exec_special_cuda
op_def static Z op(X d1, Y d2) {
return nd4j::math::nd4j_re<X>(d1, d2);
}
op_def static Z op(X d1, Y d2, Z *params) {
return op(d1, d2);
}
op_def static Z op(X d1) {
return static_cast<Z>(0);
}
};
template <typename X, typename Y, typename Z>
class BinaryRelativeError {
public:
no_op_exec_special
no_op_exec_special_cuda
op_def static Z op(X d1, Y d2, Z *params) {
X threshold = params[0];
return nd4j::math::nd4j_re<X>(d1, d2) > threshold ? static_cast<Z>(1) : static_cast<Z>(0);
}
op_def static Z op(X d1) {
return static_cast<Z>(0);
}
};
template <typename X, typename Y, typename Z>
class BinaryMinimumAbsoluteRelativeError {
public:
no_op_exec_special
no_op_exec_special_cuda
op_def static Z op(X d1, X *params) {
X d2 = params[0];
X thresholdRelative = params[1];
X thresholdAbsolute = params[2];
return nd4j::math::nd4j_re<X>(d1, d2) > thresholdRelative ? (nd4j::math::nd4j_abs<X>(d1 - static_cast<X>(d2)) < thresholdAbsolute ? static_cast<Z>(0) : static_cast<Z>(1)) : static_cast<Z>(0);
}
op_def static Z op(X d1, Y d2, Z *params) {
X thresholdRelative = params[0];
X thresholdAbsolute = params[1];
return nd4j::math::nd4j_re<X>(d1, d2) > thresholdRelative ? (nd4j::math::nd4j_abs<X>(d1 - static_cast<X>(d2)) < thresholdAbsolute ? static_cast<Z>(0) : static_cast<Z>(1)) : static_cast<Z>(0);
}
op_def static Z op(X d1) {
return static_cast<Z>(0);
}
};
template <typename X, typename Y, typename Z>
class ReversePow {
public:
no_op_exec_special
no_op_exec_special_cuda
op_def static Z op(X d1, Z *params) {
return nd4j::math::nd4j_pow<X, X, Z>(params[0], d1);
}
op_def static Z op(X d1, Y d2) {
return nd4j::math::nd4j_pow<X, Y, Z>(d2, d1);
}
op_def static Z op(X d1, Y d2, Z *params) {
return nd4j::math::nd4j_pow<X, Y, Z>(d2, d1);
}
op_def static Z op(X d1) {
return d1;
}
};
template <typename X, typename Y, typename Z>
class Pow {
public:
no_op_exec_special
no_op_exec_special_cuda
op_def static Z op(X d1, Z *params) {
return nd4j::math::nd4j_pow<X, X, Z>(d1, params[0]);
}
op_def static Z op(X d1, Y d2) {
return nd4j::math::nd4j_pow<X, Y, Z>(d1, d2);
}
op_def static Z op(X d1, Y d2, Z *params) {
return nd4j::math::nd4j_pow<X, Y, Z>(d1, d2);
}
op_def static Z op(X d1) {
return d1;
}
};
template <typename X, typename Y, typename Z>
class PowDerivative {
public:
no_op_exec_special
no_op_exec_special_cuda
op_def static Z op(X d1, Z *params) {
return params[0] * nd4j::math::nd4j_pow<X, Z, Z>(d1, static_cast<Z>(params[0]) - static_cast<Z>(1.f));
}
op_def static Z op(X d1, Y d2) {
return static_cast<Z>(d2) * nd4j::math::nd4j_pow<X, Z, Z>(d1, static_cast<Z>(d2) - static_cast<Z>(1.f));
}
op_def static Z op(X d1, Y d2, Z *params) {
return static_cast<Z>(d2) * nd4j::math::nd4j_pow<X, Z, Z>(d1, static_cast<Z>(d2) - static_cast<Z>(1.f));
}
op_def static Z op(X d1) {
return d1;
}
};
template <typename X>
class Round {
public:
no_op_exec_special_same
no_op_exec_special_same_cuda
op_def static X op(X d1, X *params) {
return nd4j::math::nd4j_round<X,X>(d1);
}
};
template <typename X, typename Z>
class IsNan {
public:
no_op_exec_special_bool
no_op_exec_special_bool_cuda
no_op_exec_special_accumulation
no_op_exec_special_accumulation_cuda
op_def static Z op(X d1, X *params) {
return nd4j::math::nd4j_isnan(d1) ? static_cast<X>(1) : static_cast<X>(0);
}
op_def static X startingValue(const X *input) {
return static_cast<X>(0);
}
op_def static Z merge(X old, X opOutput, X *extraParams) {
return opOutput + old;
}
op_def static Z update(X old, X opOutput, X *extraParams) {
return opOutput + old;
}
op_def static Z postProcess(X reduction, Nd4jLong n, X *extraParams) {
return reduction;
}
};
template <typename X>
class Expm1 {
public:
no_op_exec_special_same
no_op_exec_special_same_cuda
op_def static X op(X d1, X *params) {
return nd4j::math::nd4j_exp<X, X>(d1) - static_cast<X>(1);
}
};
template <typename X, typename Z>
class IsPositive {
public:
no_op_exec_special_bool
no_op_exec_special_bool_cuda
no_op_exec_special_accumulation
no_op_exec_special_accumulation_cuda
op_def static Z op(X d1, X *params) {
return d1 > (X)0.f;
}
op_def static X startingValue(const X *input) {
return static_cast<X>(0);
}
op_def static Z merge(X old, X opOutput, X *extraParams) {
return opOutput + old;
}
op_def static Z update(X old, X opOutput, X *extraParams) {
return opOutput + old;
}
op_def static Z postProcess(X reduction, Nd4jLong n, X *extraParams) {
return reduction;
}
};
template <typename X, typename Z>
class IsInf {
public:
no_op_exec_special_bool
no_op_exec_special_bool_cuda
no_op_exec_special_accumulation
no_op_exec_special_accumulation_cuda
op_def static Z op(X d1, X *params) {
return nd4j::math::nd4j_isinf<X>(d1) ? static_cast<Z>(1) : static_cast<Z>(0);
}
op_def static X startingValue(const X *input) {
return static_cast<X>(0);
}
op_def static Z merge(X old, X opOutput, X *extraParams) {
return opOutput + old;
}
op_def static Z update(X old, X opOutput, X *extraParams) {
return opOutput + old;
}
op_def static Z postProcess(X reduction, Nd4jLong n, X *extraParams) {
return reduction;
}
};
template <typename X, typename Z>
class IsInfOrNan{
public:
no_op_exec_special_bool
no_op_exec_special_bool_cuda
no_op_exec_special_accumulation
no_op_exec_special_accumulation_cuda
op_def static Z op(X d1, X *params) {
return nd4j::math::nd4j_isfin<X>(d1) ? static_cast<Z>(0) : static_cast<Z>(1);
}
op_def static X startingValue(const X *input) {
return static_cast<X>(0);
}
op_def static Z merge(X old, X opOutput, X *extraParams) {
return opOutput == static_cast<X>(0) && old == static_cast<X>(0) ? static_cast<Z>(0) : static_cast<Z>(1);
}
op_def static Z update(X old, X opOutput, X *extraParams) {
return opOutput == static_cast<X>(0) && old == static_cast<X>(0) ? static_cast<Z>(0) : static_cast<Z>(1);
}
op_def static Z postProcess(X reduction, Nd4jLong n, X *extraParams) {
return reduction != static_cast<X>(0);
}
};
template <typename X, typename Z>
class IsFinite {
public:
no_op_exec_special_bool
no_op_exec_special_bool_cuda
no_op_exec_special_accumulation
no_op_exec_special_accumulation_cuda
op_def static Z op(X d1, X *params) {
return nd4j::math::nd4j_isfin<X>(d1) ? static_cast<Z>(1) : static_cast<Z>(0);
}
op_def static X startingValue(const X *input) {
return static_cast<X>(1);
}
op_def static Z merge(X old, X opOutput, X *extraParams) {
return opOutput == static_cast<X>(0) || old == static_cast<X>(0) ? static_cast<Z>(0) : static_cast<Z>(1);
}
op_def static Z update(X old, X opOutput, X *extraParams) {
return opOutput == static_cast<X>(0) || old == static_cast<X>(0) ? static_cast<Z>(0) : static_cast<Z>(1);
}
op_def static Z postProcess(X reduction, Nd4jLong n, X *extraParams) {
return reduction != static_cast<X>(0);
}
};
template <typename X>
class ClipByValue {
public:
no_op_exec_special_same
no_op_exec_special_same_cuda
op_def static X op(X d1, X *params) {
if (d1 > params[1])
return params[1];
if (d1 < params[0])
return params[0];
return d1;
}
};
template <typename X, typename Y, typename Z>
class LstmClip {
public:
no_op_exec_special
no_op_exec_special_cuda
op_def static Z op(X d1, Y d2, Z *params) {
X _v = (X) d2;
if (d1 > _v)
return _v;
else if (d1 < -_v)
return -_v;
else return d1;
}
};
template <typename X>
class Swish {
public:
no_op_exec_special_same
no_op_exec_special_same_cuda
op_def static X op(X d1, X *params) {
return d1 * nd4j::math::nd4j_sigmoid<X,X>(d1);
}
};
template <typename X>
class GELU {
public:
no_op_exec_special_same
no_op_exec_special_same_cuda
op_def static X op(X d1, X *params) {
return d1 * nd4j::math::nd4j_sigmoid<X,X>(static_cast<X>(1.702f) * d1);
}
};
template <typename X>
class PreciseGELU {
public:
no_op_exec_special_same
no_op_exec_special_same_cuda
op_def static X op(X d1, X *params) {
auto sp = nd4j::math::nd4j_sqrt<X, X>(static_cast<X>(2) / static_cast<X>(M_PI));
auto xp = d1 + nd4j::math::nd4j_pow<X, X, X>(static_cast<X>(0.044715) * d1, static_cast<X>(3));
return (d1 / static_cast<X>(2)) * (static_cast<X>(1) + nd4j::math::nd4j_tanh<X, X>(sp * xp));
}
};
template <typename X>
class GELUDerivative {
public:
no_op_exec_special_same
no_op_exec_special_same_cuda
op_def static X op(X d1, X *params) {
auto x17 = static_cast<X>(1.702f) * d1;
auto ep = nd4j::math::nd4j_pow<X,X,X>(static_cast<X>(M_E), x17);
// (E^(1.702 x) (1. + E^(1.702 x) + 1.702 x))/(1. + E^(1.702 x))^2
return (ep * (static_cast<X>(1.f) + ep + x17)) / nd4j::math::nd4j_pow<X, int, X>((static_cast<X>(1.f) + ep), 2);
}
};
template <typename X>
class PreciseGELUDerivative {
public:
no_op_exec_special_same
no_op_exec_special_same_cuda
op_def static X op(X d1, X *params) {
auto x79 = static_cast<X>(0.797885) * d1;
auto x03 = nd4j::math::nd4j_pow<X, int, X>(static_cast<X>(0.0356774) * d1, 3);
auto x39 = static_cast<X>(0.398942) * d1;
auto x05 = nd4j::math::nd4j_pow<X, int, X>(static_cast<X>(0.0535161) * d1, 3);
auto scz = nd4j::math::nd4j_sech<X, X>(x79 + x03);
// 0.5 + (0.398942 x + 0.0535161 x^3) Sech[0.797885 x + 0.0356774 x^3]^2 + 0.5 Tanh[0.797885 x + 0.0356774 x^3]
return static_cast<X>(0.5) + (x39 + x05) * (scz * scz) + static_cast<X>(0.5) * nd4j::math::nd4j_tanh<X, X>(x79 + x03);
}
};
template <typename X>
class SwishDerivative {
public:
no_op_exec_special_same
no_op_exec_special_same_cuda
op_def static X op(X d1, X *params) {
X ex = nd4j::math::nd4j_pow<X, X, X>(static_cast<X>(M_E), d1);
return (ex * (d1 + ex + static_cast<X>(1.f))) / nd4j::math::nd4j_pow<X, X, X>((ex + static_cast<X>(1.f)) , static_cast<X>(2.f));
}
};
template <typename X>
class LogSigmoid {
public:
no_op_exec_special_same
no_op_exec_special_same_cuda
op_def static X op(X d1, X *params) {
return nd4j::math::nd4j_log<X, X>(nd4j::math::nd4j_sigmoid<X, X>(d1));
}
};
template <typename X>
class LogSigmoidDerivative {
public:
no_op_exec_special_same
no_op_exec_special_same_cuda
op_def static X op(X d1, X *params) {
X ex = nd4j::math::nd4j_pow<X, X, X>(M_E, d1);
return static_cast<X>(1.f) / (ex + static_cast<X>(1.f));
}
};
template <typename X>
class Sigmoid {
public:
no_op_exec_special_same
no_op_exec_special_same_cuda
op_def static X op(X d1, X *params) {
return nd4j::math::nd4j_sigmoid<X, X>(d1);
}
};
template <typename X>
class SigmoidDerivative {
public:
no_op_exec_special_same
no_op_exec_special_same_cuda
op_def static X op(X d1, X *params) {
return nd4j::math::nd4j_sigmoidderivative<X, X>(d1);
}
};
template <typename X>
class HardSigmoid {
public:
no_op_exec_special_same
no_op_exec_special_same_cuda
op_def static X op(X d1, X *params) {
return nd4j::math::nd4j_min<X>(static_cast<X>(1), nd4j::math::nd4j_max<X>(static_cast<X>(0), (static_cast<X>(0.2f)) * d1 + static_cast<X>(0.5f)));
}
};
template <typename X>
class HardSigmoidDerivative {
public:
no_op_exec_special_same
no_op_exec_special_same_cuda
op_def static X op(X d1, X *params) {
return d1 < static_cast<X>(-2.5f) || d1 > static_cast<X>(2.5f) ? static_cast<X>(0.f) : static_cast<X>(0.2f);
}
};
/**
* Scale to be between a min and max
*/
template <typename X>
class SetRange {
public:
no_op_exec_special_same
no_op_exec_special_same_cuda
op_def static X op(X d1, X *params) {
auto min = params[0];
auto max = params[1];
if (static_cast<X>(d1) >= min && static_cast<X>(d1) <= max)
return d1;
if (min == static_cast<X>(0) && max == static_cast<X>(1)) {
auto val = static_cast<X>(1) / (static_cast<X>(1) + nd4j::math::nd4j_exp<X, X>(-d1));
return (nd4j::math::nd4j_floor<X,X>(val * (max - min)) + min);
}
return (nd4j::math::nd4j_floor<X,X>(d1 * (max - min)) + min);
}
};
template <typename X>
class Sin {
public:
no_op_exec_special_same
no_op_exec_special_same_cuda
op_def static X op(X d1, X *params) {
return nd4j::math::nd4j_sin<X,X>(d1);
}
};
template <typename X>
class Square {
public:
no_op_exec_special_same
no_op_exec_special_same_cuda
op_def static X op(X d1, X *params) {
return d1 * d1;
}
};
template <typename X, typename Z>
class Sqrt {
public:
no_op_exec_special
no_op_exec_special_cuda
op_def static Z op(X d1, Z *params) {
return nd4j::math::nd4j_sqrt<X, Z>(d1);
}
};
template <typename X, typename Z>
class RSqrt {
public:
no_op_exec_special
no_op_exec_special_cuda
op_def static Z op(X d1, Z *params) {
return static_cast<Z>(1) / nd4j::math::nd4j_sqrt<X, Z>(d1);
}
};
template <typename X>
class Rint {
public:
no_op_exec_special_same
no_op_exec_special_same_cuda
op_def static X op(X d1, X *params) {
return nd4j::math::nd4j_rint<X,X>(d1);
}
};
template <typename X>
class SoftPlus {
public:
no_op_exec_special_same
no_op_exec_special_same_cuda
op_def static X op(X d1, X *params) {
return nd4j::math::softplus<X, X>(d1);
}
};
template <typename X>
class Sign {
public:
no_op_exec_special_same
no_op_exec_special_same_cuda
op_def static X op(X d1, X *params) {
return (d1 > static_cast<X>(0)) - (d1 < static_cast<X>(0));
}
};
template <typename X>
class TimesOneMinus {
public:
no_op_exec_special_same
no_op_exec_special_same_cuda
op_def static X op(X d1, X *params) {
return d1 * (static_cast<X>(1) - d1);
}
};
template <typename X>
class RationalTanh {
public:
no_op_exec_special_same
no_op_exec_special_same_cuda
op_def static X op(X d1, X *params) {
// keep 2/3 as runtime variable, to match precision
auto dis = (static_cast<X>(2) / static_cast<X>(3)) * d1;
auto tanh = nd4j::math::nd4j_sgn<X,X>(dis) * (static_cast<X>(1) - (static_cast<X>(1) / (static_cast<X>(1) + static_cast<X>(nd4j::math::nd4j_abs<X>(dis)) + nd4j::math::nd4j_pow<X, X, X>(dis, static_cast<X>(2)) + static_cast<X>(1.41645f) * nd4j::math::nd4j_pow<X, X, X>(dis, static_cast<X>(4)) )));
return static_cast<X>(1.7159f) * tanh;
}
};
template <typename X>
class RationalTanhDerivative {
public:
no_op_exec_special_same
no_op_exec_special_same_cuda
op_def static X op(X d1, X *params) {
auto dis = (static_cast<X>(2.f) / static_cast<X>(3.f)) * d1;
auto a = static_cast<X>(1.f) + nd4j::math::nd4j_abs<X>(dis) + nd4j::math::nd4j_pow<X, X, X>(dis, static_cast<X>(2.f)) + static_cast<X>(1.41645f) * nd4j::math::nd4j_pow<X, X, X>(dis, static_cast<X>(4));
auto tDeriv = (static_cast<X>(1.f) + nd4j::math::nd4j_sign<X,X>(dis) * (static_cast<X>(2.f) * dis + static_cast<X>(4.f) * static_cast<X>(1.41645f) * nd4j::math::nd4j_pow<X, X, X>(dis, static_cast<X>(3)))) / (a * a);
return static_cast<X>(1.7159f) * (static_cast<X>(2.f) / static_cast<X>(3.f)) * tDeriv;
}
};
template <typename X>
class Tanh {
public:
no_op_exec_special_same
no_op_exec_special_same_cuda
op_def static X op(X d1, X *params) {
return nd4j::math::nd4j_tanh<X, X>(d1);
}
};
template <typename X>
class RectifiedTanh {
public:
no_op_exec_special_same
no_op_exec_special_same_cuda
op_def static X op(X d1, X *params) {
return nd4j::math::nd4j_max<X>(static_cast<X>(0), nd4j::math::nd4j_tanh<X,X>(d1));
}
};
template <typename X>
class RectifiedTanhDerivative {
public:
no_op_exec_special_same
no_op_exec_special_same_cuda
op_def static X op(X d1, X *params) {
return d1 > static_cast<X>(0.f) ? nd4j::math::nd4j_tanhderivative<X,X>(d1) : static_cast<X>(0.f);
}
};
template <typename X>
class ATanh {
public:
no_op_exec_special_same
no_op_exec_special_same_cuda
op_def static X op(X d1, X *params) {
return nd4j::math::nd4j_atanh<X,X>(d1);
}
};
template <typename X>
class TanhDerivative {
public:
no_op_exec_special_same
no_op_exec_special_same_cuda
op_def static X op(X d1, X *params) {
return nd4j::math::nd4j_tanhderivative<X,X>(d1);
}
};
template <typename X>
class Cube {
public:
no_op_exec_special_same
no_op_exec_special_same_cuda
op_def static X op(X d1, X *params) {
return d1 * d1 * d1;
}
};
template <typename X>
class CubeDerivative {
public:
no_op_exec_special_same
no_op_exec_special_same_cuda
op_def static X op(X d1, X *params) {
return static_cast<X>(3) * d1 * d1;
}
};
template <typename X>
class ACos {
public:
no_op_exec_special_same
no_op_exec_special_same_cuda
op_def static X op(X d1, X *params) {
return nd4j::math::nd4j_acos<X, X>(d1);
}
};
template <typename X>
class ASinh {
public:
no_op_exec_special_same
no_op_exec_special_same_cuda
op_def static X op(X d1, X *params) {
return nd4j::math::nd4j_asinh<X, X>(d1);
}
};
template <typename X>
class ASinhDerivative {
public:
no_op_exec_special_same
no_op_exec_special_same_cuda
op_def static X op(X d1, X *params) {
return static_cast<X>(1.f) / (nd4j::math::nd4j_sqrt<X, X>(nd4j::math::nd4j_pow<X, X, X>(d1, static_cast<X>(2.f)) + static_cast<X>(1.f)));
}
};
template <typename X>
class ACosh {
public:
no_op_exec_special_same
no_op_exec_special_same_cuda
op_def static X op(X d1, X *params) {
return nd4j::math::nd4j_acosh<X, X>(d1);
}
};
template <typename X>
class ACoshDerivative {
public:
no_op_exec_special_same
no_op_exec_special_same_cuda
op_def static X op(X d1, X *params) {
return static_cast<X>(1.f) / (nd4j::math::nd4j_sqrt<X, X>(d1 - static_cast<X>(1.f)) * nd4j::math::nd4j_sqrt<X, X>(d1 + static_cast<X>(1.f)));
}
};
template <typename X>
class Ones {
public:
no_op_exec_special_same
no_op_exec_special_same_cuda
op_def static X op(X d1, X *params) {
return static_cast<X>(1.0f);
}
};
template <typename X>
class SoftSign {
public:
no_op_exec_special_same
no_op_exec_special_same_cuda
op_def static X op(X d1, X *params) {
return nd4j::math::nd4j_softsign<X, X>(d1);
}
};
template <typename X>
class SoftSignDerivative {
public:
no_op_exec_special_same
no_op_exec_special_same_cuda
op_def static X op(X d1, X *params) {
return nd4j::math::nd4j_softsignderivative<X,X>(d1);
}
};
template <typename X, typename Z>
class MatchConditionBool {
public:
no_op_exec_special_bool
no_op_exec_special_bool_cuda
// this op return 1.0 if condition met, 0.0 otherwise
op_def static Z op(X d1, X *extraParams) {
X compare = extraParams[0];
X eps = extraParams[1];
auto mode = static_cast<int>(extraParams[2]);
//nd4j_printf("value: %f; comp: %f; eps: %f; mode: %i;\n", d1, compare, eps, mode);
switch (mode) {
case 0: // equals
return nd4j::math::nd4j_abs<X>(d1 - compare) <= eps ? true : false;
case 1: // not equals
return nd4j::math::nd4j_abs<X>(d1 - compare) > eps ? true : false;
case 2: // less_than
return d1 < compare ? true : false;
case 3: // greater_than
return d1 > compare ? true : false;
case 4: // less_or_equals_than
return d1 <= compare ? true : false;
case 5: // greater_or_equals_than
return d1 >= compare ? true : false;
case 6: // abs_less_than
return nd4j::math::nd4j_abs<X>(d1) < compare ? true : false;
case 7: // abs_greater_than
return nd4j::math::nd4j_abs<X>(d1) > compare ? true : false;
case 8: // is inf
return nd4j::math::nd4j_isinf(d1) ? true : false;
case 9: // is nan
return nd4j::math::nd4j_isnan(d1) ? true : false;
case 10:
return (d1 == compare) ? true : false;
case 11:
return (d1 != compare) ? true : false;
case 12: // abs_greater_or_equals_than
return nd4j::math::nd4j_abs<X>(d1) >= compare ? true : false;
case 13: // abs_less_or_equals_than
return nd4j::math::nd4j_abs<X>(d1) <= compare ? true : false;
case 14:
// isFinite
return !(nd4j::math::nd4j_isinf(d1) || nd4j::math::nd4j_isnan(d1));
case 15:
// isInfinite
return nd4j::math::nd4j_isinf(d1) || nd4j::math::nd4j_isnan(d1);
default:
printf("Undefined match condition: [%i]\n", mode);
}
return d1;
}
};
template <typename X, typename Z>
class MatchCondition {
public:
no_op_exec_special
no_op_exec_special_cuda
no_op_exec_special_accumulation_long
no_op_exec_special_accumulation_cuda
op_def static Z startingValue(const X *input) {
return static_cast<Z>(0);
}
op_def static Z merge(Z old, Z opOutput, X *extraParams) {
return old + opOutput;
}
op_def static Z update(Z old, Z opOutput, X *extraParams) {
return old + opOutput;
}
// this op return 1.0 if condition met, 0.0 otherwise
op_def static Z op(X d1, X *extraParams) {
X compare = extraParams[0];
X eps = extraParams[1];
auto mode = static_cast<int>(extraParams[2]);
//printf("value: %f; comp: %f; eps: %f; mode: %i;\n", (float) d1, (float) compare, (float) eps, mode);
switch (mode) {
case 0: // equals
return nd4j::math::nd4j_abs<X>(d1 - compare) <= eps ? 1 : 0;
case 1: // not equals
return nd4j::math::nd4j_abs<X>(d1 - compare) > eps ? 1 : 0;
case 2: // less_than
return d1 < compare ? 1 : 0;
case 3: // greater_than
return d1 > compare ? 1 : 0;
case 4: // less_or_equals_than
return d1 <= compare ? 1 : 0;
case 5: // greater_or_equals_than
return d1 >= compare ? 1 : 0;
case 6: // abs_less_than
return nd4j::math::nd4j_abs<X>(d1) < compare ? 1 : 0;
case 7: // abs_greater_than
return nd4j::math::nd4j_abs<X>(d1) > compare ? 1 : 0;
case 8: // is inf
return nd4j::math::nd4j_isinf(d1) ? 1 : 0;
case 9: // is nan
return nd4j::math::nd4j_isnan(d1) ? 1 : 0;
case 10:
return (d1 == compare) ? 1 : 0;
case 11:
return (d1 != compare) ? 1 : 0;
case 12: // abs_greater_or_equals_than
return nd4j::math::nd4j_abs<X>(d1) >= compare ? 1 : 0;
case 13: // abs_less_or_equals_than
return nd4j::math::nd4j_abs<X>(d1) <= compare ? 1 : 0;
case 14:
// isFinite
return !(nd4j::math::nd4j_isinf(d1) || nd4j::math::nd4j_isnan(d1)) ? 1 : 0;
case 15:
// isInfinite
return nd4j::math::nd4j_isinf(d1) || nd4j::math::nd4j_isnan(d1) ? 1 : 0;
default:
printf("Undefined match condition: [%i]\n", mode);
}
return d1;
}
op_def static Z postProcess(Z reduction, Nd4jLong n, X *extraParams) {
return reduction;
}
};
template <typename X>
class ELU {
public:
no_op_exec_special_same
no_op_exec_special_same_cuda
op_def static X op(X d1, X *params) {
return nd4j::math::nd4j_elu<X,X>(d1);
}
};
template <typename X>
class ELUDerivative {
public:
no_op_exec_special_same
no_op_exec_special_same_cuda
op_def static X op(X d1, X *params) {
return nd4j::math::nd4j_eluderivative<X,X>(d1);
}
};
template <typename X, typename Y, typename Z>
class RELU {
public:
no_op_exec_special_same
no_op_exec_special_same_cuda
op_def static Z op(X d1, Y d2, Z *params) {
auto xt = static_cast<Z>(d1);
auto xf = static_cast<Z>(d2);
return xt < xf ? xf : xt;
}
};
template <typename X, typename Y, typename Z>
class SXELogitsSmoother {
public:
op_def static Z op(X d1, Y d2, Z *params) {
return d1 * ((X)1.f - (X) d2) + (X)(0.5f) * (X) d2;
}
};
template <typename X, typename Y, typename Z>
class RELU6 {
public:
no_op_exec_special_same
no_op_exec_special_same_cuda
op_def static Z op(X d1, Y d2, Z *params) {
auto relu = simdOps::RELU<X,Y,Z>::op(d1, d2, params);
return relu < static_cast<Z>(6) ? relu : static_cast<Z>(6);
}
};
template <typename X, typename Y, typename Z>
class LeakyRELU {
public:
no_op_exec_special
no_op_exec_special_cuda
op_def static Z op(X d1, Y d2, Z *params) {
auto val = static_cast<Z>(d1);
auto alpha = static_cast<Z>(d2);
return val < 0.0f ? alpha * val : val;
}
};
template <typename X>
class SELU {
public:
no_op_exec_special_same
no_op_exec_special_same_cuda
op_def static X op(X d1, X *params) {
return d1 > static_cast<X>(0.0f) ? static_cast<X>(SELU_LAMBDA) * static_cast<X>(d1) : static_cast<X>(SELU_LAMBDA) * (static_cast<X>(SELU_ALPHA) * nd4j::math::nd4j_exp<X, X>(d1) - static_cast<X>(SELU_ALPHA));
}
};
template <typename X>
class SELUDerivative {
public:
no_op_exec_special_same
no_op_exec_special_same_cuda
op_def static X op(X d1, X *params) {
return d1 > static_cast<X>(0.f) ? static_cast<X>(SELU_LAMBDA) : static_cast<X>(SELU_ALPHA) * static_cast<X>(SELU_LAMBDA) * nd4j::math::nd4j_exp<X, X>(d1);
}
};
template <typename X, typename Y, typename Z>
class LeakyRELUDerivative {
public:
no_op_exec_special
no_op_exec_special_cuda
op_def static Z op(X d1, Y d2, Z *params) {
if (d1 >= static_cast<X>(0))
return static_cast<Z>(1);
else
return static_cast<Z>(d2);
}
};
template <typename X>
class ASin {
public:
no_op_exec_special_same
no_op_exec_special_same_cuda
op_def static X op(X d1, X *params) {
return nd4j::math::nd4j_asin<X,X>(d1);
}
};
template <typename X>
class Sinh {
public:
no_op_exec_special_same
no_op_exec_special_same_cuda
op_def static X op(X d1, X *params) {
return nd4j::math::nd4j_sinh<X,X>(d1);
}
};
template <typename X>
class SinhDerivative {
public:
no_op_exec_special_same
no_op_exec_special_same_cuda
op_def static X op(X d1, X *params) {
return nd4j::math::nd4j_cosh<X, X>(d1);
}
};
template <typename X>
class Cosh {
public:
no_op_exec_special_same
no_op_exec_special_same_cuda
op_def static X op(X d1, X *params) {
return nd4j::math::nd4j_cosh<X,X>(d1);
}
};
template <typename X>
class Tan {
public:
no_op_exec_special_same
no_op_exec_special_same_cuda
op_def static X op(X d1, X *params) {
return nd4j::math::nd4j_tan<X,X>(d1);
}
};
template <typename X>
class TanDerivative {
public:
no_op_exec_special_same
no_op_exec_special_same_cuda
op_def static X op(X d1, X *params) {
return static_cast<X>(1.f) / nd4j::math::nd4j_pow<X, X, X>(nd4j::math::nd4j_cos<X, X>(d1), static_cast<X>(2.0f));
}
};
template <typename X>
class ATan {
public:
no_op_exec_special_same
no_op_exec_special_same_cuda
op_def static X op(X d1, X *params) {
return nd4j::math::nd4j_atan<X, X>(d1);
}
};
template <typename X, typename Y, typename Z>
class Atan2 {
public:
no_op_exec_special
no_op_exec_special_cuda
op_def static Z op(X d1, Y d2) {
return nd4j::math::nd4j_atan2<X, Z>(d2, d1);
}
op_def static Z op(X d1, Y d2, Z *params) {
return op(d1, d2);
}
// op for MetaOps
op_def static Z op(X d1, Y *params) {
return op(d1, params[0]);
}
};
template <typename X>
class Identity {
public:
no_op_exec_special_same
no_op_exec_special_same_cuda
op_def static X op(X d1, X *params) {
return d1;
}
};
template <typename X>
class Stabilize {
public:
no_op_exec_special_same
no_op_exec_special_same_cuda
op_def static X op(X d1, X *params) {
X k = params[0];
if (d1 * k > static_cast<X>(- MIN_CUTFOFF))
return static_cast<X>(- MIN_CUTFOFF) / k;
else if (d1 * k < static_cast<X>(MIN_CUTFOFF))
return static_cast<X>(MIN_CUTFOFF) / k;
return d1;
}
};
template <typename X, typename Y, typename Z>
class Step {
public:
no_op_exec_special_same
no_op_exec_special_same_cuda
op_def static Z op(X d1, Y d2, Z *params) {
return (d1 > static_cast<X>(d2) ? static_cast<Z>(1) : static_cast<Z>(0));
}
};
template <typename X>
class OneMinus {
public:
no_op_exec_special_same
no_op_exec_special_same_cuda
op_def static X op(X d1, X *params) {
return static_cast<X>(1) - d1;
}
};
template <typename X>
class Sum {
public:
no_op_exec_special_accumulation_same
no_op_exec_special_accumulation_same_cuda
op_def static X startingValue(const X *input) {
return static_cast<X>(0.0f);
}
op_def static X merge(X old, X opOutput, X *extraParams) {
return opOutput + old;
}
op_def static X update(X old, X opOutput, X *extraParams) {
return opOutput + old;
}
op_def static X op(X d1, X *extraParams) {
return d1;
}
op_def static X postProcess(X reduction, Nd4jLong n, X *extraParams) {
return reduction;
}
};
template <typename X>
class ReduceSameBenchmarkOp {
public:
no_op_exec_special_accumulation_same
no_op_exec_special_accumulation_same_cuda
const static functions::ReduceType reduceType = functions::ReduceType::SUM;
op_def static X startingValue(const X *input) {
return static_cast<X>(0.0f);
}
op_def static X merge(X old, X opOutput, X *extraParams) {
return opOutput + old;
}
op_def static X update(X old, X opOutput, X *extraParams) {
return opOutput + old;
}
op_def static X op(X d1, X *extraParams) {
auto f1 = static_cast<float>(d1);
return static_cast<X>(nd4j::math::nd4j_pow<float,float,float>(f1, 3)
+ nd4j::math::nd4j_log<float,float>(f1) * nd4j::math::nd4j_sin<float,float>(f1)
/ nd4j::math::nd4j_tanh<float,float>(static_cast<float>(M_E) * static_cast<float>(M_PI) * f1)
* nd4j::math::nd4j_sqrt<float,float>(static_cast<float>(M_PI) / f1)
- nd4j::math::nd4j_atan<float,float>(static_cast<float>(M_E) / f1));
}
op_def static X postProcess(X reduction, Nd4jLong n, X *extraParams) {
return reduction;
}
};
template <typename X, typename Z>
class ShannonEntropy {
public:
no_op_exec_special_accumulation
no_op_exec_special_accumulation_cuda
const static functions::ReduceType reduceType = functions::ReduceType::SUM;
op_def static X startingValue(const X *input) {
return static_cast<X>(0);
}
op_def static Z merge(Z old, Z opOutput, Z *extraParams) {
return opOutput + old;
}
op_def static Z update(Z old, Z opOutput, Z *extraParams) {
return opOutput + old;
}
op_def static Z op(X d1, Z *extraParams) {
auto p = d1 * d1;
return static_cast<Z>(p) * nd4j::math::nd4j_log<X, Z>(p);
}
op_def static Z postProcess(Z reduction, Nd4jLong n, Z *extraParams) {
return -reduction;
}
};
template <typename X, typename Z>
class LogEntropy {
public:
no_op_exec_special_accumulation
no_op_exec_special_accumulation_cuda
const static functions::ReduceType reduceType = functions::ReduceType::SUM;
op_def static X startingValue(const X *input) {
return static_cast<X>(0);
}
op_def static Z merge(Z old, Z opOutput, Z *extraParams) {
return opOutput + old;
}
op_def static Z update(Z old, Z opOutput, Z *extraParams) {
return opOutput + old;
}
op_def static Z op(X d1, Z *extraParams) {
return static_cast<Z>(d1) * nd4j::math::nd4j_log<X, Z>(d1);
}
op_def static Z postProcess(Z reduction, Nd4jLong n, Z *extraParams) {
//entropy is -sum(p(x) * log(p(x))); log entropy is log of this
return nd4j::math::nd4j_log<Z, Z>(-reduction);
}
};
template <typename X, typename Z>
class Entropy {
public:
no_op_exec_special_accumulation
no_op_exec_special_accumulation_cuda
const static functions::ReduceType reduceType = functions::ReduceType::SUM;
op_def static X startingValue(const X *input) {
return static_cast<X>(0);
}
op_def static Z merge(Z old, Z opOutput, Z *extraParams) {
return opOutput + old;
}
op_def static Z update(Z old, Z opOutput, Z *extraParams) {
return opOutput + old;
}
op_def static Z op(X d1, Z *extraParams) {
return static_cast<Z>(d1) * nd4j::math::nd4j_log<X, Z>(d1);
}
op_def static Z postProcess(Z reduction, Nd4jLong n, Z *extraParams) {
return static_cast<Z>(-reduction); //entropy is -sum(p(x) * log(p(x)))
}
};
template <typename X>
class ASum {
public:
no_op_exec_special_accumulation_same
no_op_exec_special_accumulation_same_cuda
const static functions::ReduceType reduceType = functions::ReduceType::ASUM;
op_def static X startingValue(const X *input) {
return static_cast<X>(0);
}
op_def static X merge(X old, X opOutput, X *extraParams) {
return nd4j::math::nd4j_abs<X>(opOutput) + nd4j::math::nd4j_abs<X>(old);
}
op_def static X update(X old, X opOutput, X *extraParams) {
return nd4j::math::nd4j_abs<X>(opOutput) + nd4j::math::nd4j_abs<X>(old);
}
op_def static X op(X d1, X *extraParams) {
return nd4j::math::nd4j_abs<X>(d1);
}
op_def static X postProcess(X reduction, Nd4jLong n, X *extraParams) {
return nd4j::math::nd4j_abs<X>(reduction);
}
};
template <typename X, typename Z>
class CountNonZero {
public:
no_op_exec_special_accumulation_long
no_op_exec_special_accumulation_cuda
const static functions::ReduceType reduceType = functions::ReduceType::ASUM;
op_def static Z startingValue(const X *input) {
return static_cast<Z>(0);
}
op_def static Z merge(Z old, Z opOutput, X *extraParams) {
return opOutput + old;
}
op_def static Z update(Z old, Z opOutput, X *extraParams) {
return opOutput + old;
}
op_def static Z op(X d1, X *extraParams) {
return d1 == static_cast<X>(0.0f) ? static_cast<Z>(0.0f) : static_cast<Z>(1.0f);
}
op_def static Z postProcess(Z reduction, Nd4jLong n, X *extraParams) {
return reduction;
}
};
template <typename X, typename Z>
class CountZero {
public:
no_op_exec_special_accumulation_long
no_op_exec_special_accumulation_cuda
const static functions::ReduceType reduceType = functions::ReduceType::SUM;
op_def static Z startingValue(const X *input) {
return static_cast<Z>(0.0f);
}
op_def static Z merge(Z old, Z opOutput, X *extraParams) {
return opOutput + old;
}
op_def static Z update(Z old, Z opOutput, X *extraParams) {
return opOutput + old;
}
op_def static Z op(X d1, X *extraParams) {
return d1 == static_cast<X>(0) ? static_cast<X>(1) : static_cast<X>(0);
}
op_def static Z postProcess(X reduction, Nd4jLong n, X *extraParams) {
return static_cast<Z>(reduction);
}
};
template <typename X>
class Prod {
public:
no_op_exec_special_accumulation_same
no_op_exec_special_accumulation_same_cuda
const static functions::ReduceType reduceType = functions::ReduceType::PRODUCT;
op_def static X startingValue(const X *input) {
return static_cast<X>(1);
}
op_def static X merge(X old, X opOutput, X *extraParams) {
return opOutput * old;
}
op_def static X update(X old, X opOutput, X *extraParams) {
return opOutput * old;
}
op_def static X op(X d1, X *extraParams) {
return d1;
}
op_def static X postProcess(X reduction, Nd4jLong n, X *extraParams) {
return reduction;
}
};
template <typename X, typename Z>
class Any {
public:
no_op_exec_special_accumulation
no_op_exec_special_accumulation_cuda
const static functions::ReduceType reduceType = functions::ReduceType::SUM;
op_def static X startingValue(const X *input) {
return static_cast<X>(0.0f);
}
op_def static Z merge(X old, X opOutput, X *extraParams) {
return opOutput + old;
}
op_def static Z update(X old, X opOutput, X *extraParams) {
return opOutput + old;
}
op_def static Z op(X d1, X *extraParams) {
return d1;
}
op_def static Z postProcess(X reduction, Nd4jLong n, X *extraParams) {
return reduction > static_cast<X>(0) ? static_cast<Z>(1) : static_cast<Z>(0) ;
}
};
template <typename X, typename Z>
class All {
public:
no_op_exec_special_accumulation
no_op_exec_special_accumulation_cuda
const static functions::ReduceType reduceType = functions::ReduceType::PRODUCT;
op_def static X startingValue(const X *input) {
return static_cast<X>(1);
}
op_def static Z merge(X old, X opOutput, X *extraParams) {
return opOutput * old;
}
op_def static Z update(X old, X opOutput, X *extraParams) {
return opOutput * old;
}
op_def static Z op(X d1, X *extraParams) {
return d1;
}
op_def static Z postProcess(X reduction, Nd4jLong n, X *extraParams) {
return reduction > static_cast<X>(0) ? static_cast<Z>(1) : static_cast<Z>(0);
}
};
template <typename X, typename Z>
class Mean {
public:
no_op_exec_special_accumulation
no_op_exec_special_accumulation_cuda
const static functions::ReduceType reduceType = functions::ReduceType::SUM;
op_def static X startingValue(const X *input) {
return static_cast<X>(0);
}
op_def static Z merge(Z old, Z opOutput, Z *extraParams) {
return opOutput + old;
}
op_def static Z update(Z old, Z opOutput, Z *extraParams) {
return opOutput + old;
}
op_def static Z op(X d1, Z *extraParams) {
return d1;
}
op_def static Z postProcess(Z reduction, Nd4jLong n, Z *extraParams) {
return reduction / (Z) n;
}
};
template <typename X, typename Z>
class ReduceFloatBenchmarkOp {
public:
no_op_exec_special_accumulation
no_op_exec_special_accumulation_cuda
const static functions::ReduceType reduceType = functions::ReduceType::SUM;
op_def static X startingValue(const X *input) {
return static_cast<X>(0);
}
op_def static Z merge(Z old, Z opOutput, Z *extraParams) {
return opOutput + old;
}
op_def static Z update(Z old, Z opOutput, Z *extraParams) {
return opOutput + old;
}
op_def static Z op(X d1, Z *extraParams) {
auto f1 = static_cast<float>(d1);
return static_cast<Z>(nd4j::math::nd4j_pow<float,float,float>(f1, 3)
+ nd4j::math::nd4j_log<float,float>(f1) * nd4j::math::nd4j_sin<float,float>(f1)
/ nd4j::math::nd4j_tanh<float,float>(static_cast<float>(M_E) * static_cast<float>(M_PI) * f1)
* nd4j::math::nd4j_sqrt<float,float>(static_cast<float>(M_PI) / f1)
- nd4j::math::nd4j_atan<float,float>(static_cast<float>(M_E) / f1));
}
op_def static Z postProcess(Z reduction, Nd4jLong n, Z *extraParams) {
return (Z) reduction / (Z) n;
}
};
template <typename X, typename Z>
class AMean {
public:
no_op_exec_special_accumulation
no_op_exec_special_accumulation_cuda
const static functions::ReduceType reduceType = functions::ReduceType::SUM;
op_def static X startingValue(const X *input) {
return static_cast<X>(0);
}
op_def static Z merge(Z old, Z opOutput, Z *extraParams) {
return nd4j::math::nd4j_abs<X>(opOutput) + nd4j::math::nd4j_abs<X>(old);
}
op_def static Z update(Z old, Z opOutput, Z *extraParams) {
return opOutput + old;
}
op_def static Z op(X d1, Z *extraParams) {
return nd4j::math::nd4j_abs<X>(d1);
}
op_def static Z postProcess(Z reduction, Nd4jLong n, Z *extraParams) {
return nd4j::math::nd4j_abs<Z>(reduction) / static_cast<Z>(n);
}
};
template <typename X>
class Max {
public:
no_op_exec_special_accumulation_same
no_op_exec_special_accumulation_same_cuda
const static functions::ReduceType reduceType = functions::ReduceType::MAX;
op_def static X startingValue(const X *input) {
return -nd4j::DataTypeUtils::infOrMax<X>();
}
op_def static X merge(X old, X opOutput, X *extraParams) {
return nd4j::math::nd4j_max<X>(old, opOutput);
}
op_def static X update(X old, X opOutput, X *extraParams) {
return nd4j::math::nd4j_max<X>(opOutput, old);
}
op_def static X op(X d1, X d2, X *params) {
return nd4j::math::nd4j_max<X>(d1, d2);
}
op_def static X op(X d1, X d2) {
return nd4j::math::nd4j_max<X>(d1, d2);
}
// FIXME: this signature overlaps with MetaOp
op_def static X op(X d1, X *extraParams) {
return d1;
}
op_def static X postProcess(X reduction, Nd4jLong n, X *extraParams) {
return reduction;
}
};
template <typename X, typename Y, typename Z>
class AMaxPairwise {
public:
op_def static Z op(X d1, Y d2, Z *params) {
return op(d1, d2);
}
op_def static Z op(X d1, Y d2) {
auto z1 = static_cast<Z>(d1);
auto z2 = static_cast<Z>(d2);
if (nd4j::math::nd4j_abs<Z>(z1) > nd4j::math::nd4j_abs<Z>(z2))
return z1;
else
return z2;
}
};
template <typename X, typename Y, typename Z>
class AMinPairwise {
public:
op_def static Z op(X d1, Y d2, Z *params) {
return op(d1, d2);
}
op_def static Z op(X d1, Y d2) {
auto z1 = static_cast<Z>(d1);
auto z2 = static_cast<Z>(d2);
if (nd4j::math::nd4j_abs<Z>(z1) < nd4j::math::nd4j_abs<Z>(z2))
return z1;
else
return z2;
}
};
template <typename X, typename Y, typename Z>
class MaxPairwise {
public:
op_def static Z op(X d1, Y d2, Z *params) {
return nd4j::math::nd4j_max<Z>(static_cast<Z>(d1), static_cast<Z>(d2));
}
op_def static Z op(X d1, Y d2) {
return nd4j::math::nd4j_max<Z>(static_cast<Z>(d1), static_cast<Z>(d2));
}
};
template <typename X, typename Y, typename Z>
class MinPairwise {
public:
op_def static Z op(X d1, Y d2, Z *params) {
return nd4j::math::nd4j_min<Z>(static_cast<Z>(d1), static_cast<Z>(d2));
}
op_def static Z op(X d1, Y d2) {
return nd4j::math::nd4j_min<Z>(static_cast<Z>(d1), static_cast<Z>(d2));
}
};
template <typename X>
class AMax {
public:
no_op_exec_special_accumulation_same
no_op_exec_special_accumulation_same_cuda
const static functions::ReduceType reduceType = functions::ReduceType::AMAX;
op_def static X startingValue(const X *input) {
return input[0];
}
op_def static X merge(X old, X opOutput, X *extraParams) {
return nd4j::math::nd4j_max<X>(nd4j::math::nd4j_abs<X>(old), nd4j::math::nd4j_abs<X>(opOutput));
}
op_def static X update(X old, X opOutput, X *extraParams) {
return nd4j::math::nd4j_max<X>(nd4j::math::nd4j_abs<X>(opOutput), nd4j::math::nd4j_abs<X>(old));
}
op_def static X op(X d1, X d2, X *params) {
return nd4j::math::nd4j_max<X>(nd4j::math::nd4j_abs<X>(d1), nd4j::math::nd4j_abs<X>(d2));
}
op_def static X op(X d1, X d2) {
return nd4j::math::nd4j_abs<X>(d1) > nd4j::math::nd4j_abs<X>(d2) ? d1 : d2;
}
// FIXME: this signature overlaps with MetaOp
op_def static X op(X d1, X *extraParams) {
return nd4j::math::nd4j_abs<X>(d1);
}
op_def static X postProcess(X reduction, Nd4jLong n, X *extraParams) {
return nd4j::math::nd4j_abs<X>(reduction);
}
};
template <typename X>
class AMin {
public:
no_op_exec_special_accumulation_same
no_op_exec_special_accumulation_same_cuda
const static functions::ReduceType reduceType = functions::ReduceType::AMIN;
op_def static X startingValue(const X *input) {
return input[0];
}
op_def static X merge(X old, X opOutput, X *extraParams) {
return nd4j::math::nd4j_min<X>(nd4j::math::nd4j_abs<X>(old), nd4j::math::nd4j_abs<X>(opOutput));
}
op_def static X update(X old, X opOutput, X *extraParams) {
return nd4j::math::nd4j_min<X>(nd4j::math::nd4j_abs<X>(opOutput), nd4j::math::nd4j_abs<X>(old));
}
op_def static X op(X d1, X d2, X *params) {
return nd4j::math::nd4j_min<X>(nd4j::math::nd4j_abs<X>(d1), nd4j::math::nd4j_abs<X>(d2));
}
op_def static X op(X d1, X d2) {
return nd4j::math::nd4j_min<X>(nd4j::math::nd4j_abs<X>(d1), nd4j::math::nd4j_abs<X>(d2));
}
// FIXME: this signature overlaps with MetaOp
op_def static X op(X d1, X *extraParams) {
return nd4j::math::nd4j_abs<X>(d1);
}
op_def static X postProcess(X reduction, Nd4jLong n, X *extraParams) {
return nd4j::math::nd4j_abs<X>(reduction);
}
};
template <typename X>
class Min {
public:
no_op_exec_special_accumulation_same
no_op_exec_special_accumulation_same_cuda
const static functions::ReduceType reduceType = functions::ReduceType::MIN;
op_def static X startingValue(const X *input) {
return nd4j::DataTypeUtils::infOrMax<X>();
}
op_def static X merge(X old, X opOutput, X *extraParams) {
return nd4j::math::nd4j_min<X>(old, opOutput);
}
op_def static X update(X old, X opOutput, X *extraParams) {
return nd4j::math::nd4j_min<X>(opOutput, old);
}
op_def static X op(X d1, X d2, X *params) {
return nd4j::math::nd4j_min<X>(d1, d2);
}
op_def static X op(X d1, X d2) {
return nd4j::math::nd4j_min<X>(d1, d2);
}
// FIXME: this signature overlaps with MetaOp
op_def static X op(X d1, X *extraParams) {
return d1;
}
op_def static X postProcess(X reduction, Nd4jLong n, X *extraParams) {
return reduction;
}
};
template <typename X, typename Z>
class Norm1 {
public:
no_op_exec_special_accumulation
no_op_exec_special_accumulation_cuda
const static functions::ReduceType reduceType = functions::ReduceType::SUM;
op_def static X startingValue(const X *input) {
return static_cast<X>(0);
}
op_def static Z merge(Z old, Z opOutput, Z *extraParams) {
return opOutput + old;
}
op_def static Z update(Z old, Z opOutput, Z *extraParams) {
return opOutput + old;
}
op_def static Z op(X d1, Z *extraParams) {
return static_cast<Z>(nd4j::math::nd4j_abs<X>(d1));
}
op_def static Z postProcess(Z reduction, Nd4jLong n, Z *extraParams) {
return reduction;
}
};
template <typename X, typename Z>
class Norm2 {
public:
no_op_exec_special_accumulation
no_op_exec_special_accumulation_cuda
const static functions::ReduceType reduceType = functions::ReduceType::SUM;
op_def static X startingValue(const X *input) {
return static_cast<X>(0);
}
op_def static Z merge(Z old, Z opOutput, Z *extraParams) {
return opOutput + old;
}
op_def static Z update(Z old, Z opOutput, Z *extraParams) {
return opOutput + old;
}
op_def static Z postProcess(Z reduction, Nd4jLong n, Z *extraParams) {
return nd4j::math::nd4j_sqrt<Z, Z>(reduction);
}
op_def static Z op(X d1, Z *extraParams) {
return static_cast<Z>(d1 * d1);
}
};
template <typename X, typename Z>
class SquaredNorm {
public:
no_op_exec_special_accumulation
no_op_exec_special_accumulation_cuda
const static functions::ReduceType reduceType = functions::ReduceType::SUM;
op_def static X startingValue(const X *input) {
return static_cast<X>(0);
}
op_def static Z merge(Z old, Z opOutput, Z *extraParams) {
return opOutput + old;
}
op_def static Z update(Z old, Z opOutput, Z *extraParams) {
return opOutput + old;
}
op_def static Z op(X d1, Z *extraParams) {
return static_cast<Z>(d1 * d1);
}
op_def static Z postProcess(Z reduction, Nd4jLong n, Z *extraParams) {
return reduction;
}
};
template <typename X, typename Z>
class NormFrobenius {
public:
no_op_exec_special_accumulation
no_op_exec_special_accumulation_cuda
const static functions::ReduceType reduceType = functions::ReduceType::SUM;
op_def static X startingValue(const X *input) {
return static_cast<X>(0);
}
op_def static Z merge(Z old, Z opOutput, Z *extraParams) {
return opOutput + old;
}
op_def static Z update(Z old, Z opOutput, Z *extraParams) {
return opOutput + old;
}
op_def static Z op(X d1, Z *extraParams) {
X v = nd4j::math::nd4j_abs<X>(d1);
return static_cast<Z>(v * v);
}
op_def static Z postProcess(Z reduction, Nd4jLong n, Z *extraParams) {
return nd4j::math::nd4j_sqrt<Z, Z>(reduction);
}
};
template <typename X, typename Z>
class NormP {
public:
no_op_exec_special_accumulation
no_op_exec_special_accumulation_cuda
const static functions::ReduceType reduceType = functions::ReduceType::SUM;
op_def static X startingValue(const X *input) {
return static_cast<X>(0);
}
op_def static Z merge(Z old, Z opOutput, Z *extraParams) {
return opOutput + old;
}
op_def static Z update(Z old, Z opOutput, Z *extraParams) {
return opOutput + old;
}
op_def static Z op(X d1, Z *extraParams) {
return nd4j::math::nd4j_pow<X, Z, Z>(nd4j::math::nd4j_abs<X>(d1), extraParams[0]);
}
op_def static Z postProcess(Z reduction, Nd4jLong n, Z *extraParams) {
return nd4j::math::nd4j_pow<Z, Z, Z>(reduction, static_cast<Z>(1.0f) / extraParams[0]);
}
};
template <typename X, typename Z>
class NormMax {
public:
no_op_exec_special_accumulation
no_op_exec_special_accumulation_cuda
const static functions::ReduceType reduceType = functions::ReduceType::SUM;
op_def static X startingValue(const X *input) {
return static_cast<X>(0);
}
op_def static Z merge(Z old, Z opOutput, Z *extraParams) {
return opOutput + old;
}
op_def static Z update(Z old, Z opOutput, Z *extraParams) {
return nd4j::math::nd4j_max<Z>(nd4j::math::nd4j_abs<Z>(old),
nd4j::math::nd4j_abs<Z>(opOutput));
}
op_def static Z op(X d1, Z *extraParams) {
return static_cast<Z>(d1);
}
op_def static Z postProcess(Z reduction, Nd4jLong n, Z *extraParams) {
return nd4j::math::nd4j_max<Z>(nd4j::math::nd4j_abs<Z>(reduction), nd4j::math::nd4j_abs<Z>(reduction));
}
};
template <typename X, typename Z>
class Variance {
public:
no_op_exec_special_accumulation
no_op_exec_special_accumulation_cuda
const static functions::ReduceType reduceType = functions::ReduceType::SUM;
op_def static X startingValue(const X *input) {
return static_cast<X>(0.0f);
}
op_def static Z merge(X old, X opOutput, Z *extraParams) {
return old + opOutput;
}
op_def static Z update(X old, X opOutput, Z *extraParams) {
return old + opOutput;
}
op_def static X op(X d1, Z *extraParams) {
X mean = static_cast<X>(extraParams[0]);
X ret = d1 - mean;
return ret * ret;
}
op_def static Z postProcess(X reduction, Nd4jLong n, Z *extraParams) {
// T bias = extraParams[1];
// return (reduction - (nd4j::math::nd4j_pow<T>(bias, static_cast<T>(2.0f)) / static_cast<T>(n))) / (n - 1)
return static_cast<Z>(reduction) / static_cast<Z>(n - 1);
}
};
/**
* Standard deviation of a buffer
*/
template <typename X, typename Z>
class StandardDeviation {
public:
no_op_exec_special_accumulation
no_op_exec_special_accumulation_cuda
const static functions::ReduceType reduceType = functions::ReduceType::SUM;
op_def static X startingValue(const X *input) {
return static_cast<X>(0.0f);
}
op_def static Z merge(X old, X opOutput, Z *extraParams) {
return old + opOutput;
}
op_def static Z update(X old, X opOutput, Z *extraParams) {
return old + opOutput;
}
op_def static Z op(X d1, Z *extraParams) {
X mean = extraParams[0];
X ret = d1 - mean;
return ret * ret;
}
op_def static Z postProcess(X reduction, Nd4jLong n, Z *extraParams) {
Z ret = Variance<X,Z>::postProcess(reduction, n, extraParams);
Z sqrtRet = nd4j::math::nd4j_sqrt<X, Z>(ret);
return sqrtRet;
}
};
template <typename X, typename Y>
class CosineSimilarity {
public:
static const int extraParamsLen = 2;
op_def static X *generateExtraParams() {
//T *extraParams = new T[2];
return nullptr;
}
op_def static void finalizeExtraParams(X *extraParams) {
//delete[] extraParams;
}
op_def static Y startingValue(const X *input) {
return static_cast<Y>(0.0f);
}
op_def static Y postProcess(Y reduction, Nd4jLong n, Y *extraParams) {
return reduction / (nd4j::math::nd4j_sqrt<Y, Y>(extraParams[0]) * nd4j::math::nd4j_sqrt<Y, Y>(extraParams[1]));
}
op_def static Y op(X d1, X d2, Y *extraParams) {
extraParams[0] += static_cast<Y>(d1 * d1);
extraParams[1] += static_cast<Y>(d2 * d2);
return static_cast<Y>(d1 * d2);
}
op_def static void aggregateExtraParams(Y *extraParamsTotal, Y *extraParamsLocal) {
extraParamsTotal[0] += extraParamsLocal[0];
extraParamsTotal[1] += extraParamsLocal[1];
}
#ifdef __CUDACC__
static _CUDA_D inline Y opAtomic(X d1, X d2, Y *extraParams) {
nd4j::math::atomics::nd4j_atomicAdd(&extraParams[0],static_cast<Y>(d1 * d1));
nd4j::math::atomics::nd4j_atomicAdd(&extraParams[1],static_cast<Y>(d2 * d2));
return static_cast<Y>(d1 * d2);
}
#endif
op_def static Y update(Y old, Y opOutput, Y *extraParams) {
return old + opOutput;
}
op_def static Y merge(Y old, Y opOutput, Y *extraParams) {
return update(old, opOutput, extraParams);
}
};
template <typename X, typename Y>
class JaccardDistance {
public:
static const int extraParamsLen = 2;
op_def static X *generateExtraParams() {
//T *extraParams = new T[2];
return nullptr;
}
op_def static void finalizeExtraParams(X *extraParams) {
//delete[] extraParams;
}
op_def static Y startingValue(const X *input) {
return static_cast<X>(0.0f);
}
op_def static Y postProcess(Y reduction, Nd4jLong n, Y *extraParams) {
// num / denom
return (static_cast<Y>(1.0f)) - (extraParams[0] / extraParams[1]);
}
op_def static Y num(X d1, X d2) {
return nd4j::math::nd4j_min<X>(d1, d2);
}
op_def static Y denom(X d1, X d2) {
return nd4j::math::nd4j_max<X>(d1, d2);
}
op_def static Y op(X d1, X d2, Y *extraParams) {
extraParams[0] += static_cast<Y>(num(d1, d2));
extraParams[1] += static_cast<Y>(denom(d1, d2));
return static_cast<Y>(0.0f);
}
op_def static void aggregateExtraParams(Y *extraParamsTotal, Y *extraParamsLocal) {
extraParamsTotal[0] += extraParamsLocal[0];
extraParamsTotal[1] += extraParamsLocal[1];
}
#ifdef __CUDACC__
__device__
static inline Y opAtomic(X d1, X d2, Y *extraParams) {
nd4j::math::atomics::nd4j_atomicAdd(&extraParams[0],num(d1, d2));
nd4j::math::atomics::nd4j_atomicAdd(&extraParams[1], denom(d1, d2));
return static_cast<Y>(0.0f);
}
#endif
op_def static Y update(Y old, Y opOutput, Y *extraParams) {
return old + opOutput;
}
op_def static Y merge(Y old, Y opOutput, Y *extraParams) {
return update(old, opOutput, extraParams);
}
};
template <typename X, typename Y>
class SimpleHammingDistance {
public:
static const int extraParamsLen = 0;
op_def static X *generateExtraParams() {
//T *extraParams = new T[2];
return nullptr;
}
op_def static void finalizeExtraParams(X *extraParams) {
//delete[] extraParams;
}
op_def static Y startingValue(const X *input) {
return static_cast<Y>(0.0f);
}
op_def static Y postProcess(Y reduction, Nd4jLong n, Y *extraParams) {
return static_cast<Y>(reduction / n);
}
op_def static Y op(X d1, X d2, Y *extraParams) {
return (d1 == d2) ? static_cast<Y>(0.0f) : static_cast<Y>(1.0f);
}
op_def static void aggregateExtraParams(Y *extraParamsTotal, Y *extraParamsLocal) {
}
#ifdef __CUDACC__
__device__
static inline Y opAtomic(X d1, X d2, Y *extraParams) {
return op(d1, d2, extraParams);
}
#endif
op_def static Y update(Y old, Y opOutput, Y *extraParams) {
return old + opOutput;
}
op_def static Y merge(Y old, Y opOutput, Y *extraParams) {
return update(old, opOutput, extraParams);
}
};
template <typename X, typename Y>
class CosineDistance {
public:
static const int extraParamsLen = 2;
op_def static X *generateExtraParams() {
//T *extraParams = new T[2];
return nullptr;
}
op_def static void finalizeExtraParams(X *extraParams) {
//delete[] extraParams;
}
op_def static Y startingValue(const X *input) {
return static_cast<Y>(0.0f);
}
op_def static Y postProcess(Y reduction, Nd4jLong n, Y *extraParams) {
return (static_cast<Y>(1.0f)) - (reduction / (nd4j::math::nd4j_sqrt<Y, Y>(extraParams[0]) * nd4j::math::nd4j_sqrt<Y, Y>(extraParams[1])));
}
op_def static Y op(X d1, X d2, Y *extraParams) {
extraParams[0] += static_cast<Y>(nd4j::math::nd4j_abs<X>(d1) * nd4j::math::nd4j_abs<X>(d1));
extraParams[1] += static_cast<Y>(nd4j::math::nd4j_abs<X>(d2) * nd4j::math::nd4j_abs<X>(d2));
return (d1 * d2);
}
op_def static void aggregateExtraParams(Y *extraParamsTotal, Y *extraParamsLocal) {
extraParamsTotal[0] += extraParamsLocal[0];
extraParamsTotal[1] += extraParamsLocal[1];
}
#ifdef __CUDACC__
static _CUDA_D inline Y opAtomic(X d1, X d2, Y *extraParams) {
nd4j::math::atomics::nd4j_atomicAdd(&extraParams[0], nd4j::math::nd4j_abs<Y>(d1) * nd4j::math::nd4j_abs<Y>(d1));
nd4j::math::atomics::nd4j_atomicAdd(&extraParams[1], nd4j::math::nd4j_abs<Y>(d2) * nd4j::math::nd4j_abs<Y>(d2));
return (d1 * d2);
}
#endif
op_def static Y update(Y old, Y opOutput, Y *extraParams) {
return old + opOutput;
}
op_def static Y merge(Y old, Y opOutput, Y *extraParams) {
return update(old, opOutput, extraParams);
}
};
/**
* Dot product between 2 arrays
*/
template <typename X, typename Y>
class Dot {
public:
static const int extraParamsLen = 0;
op_def static X * generateExtraParams() {
return nullptr;
}
op_def static void finalizeExtraParams(X *extraParamsRef) {
//no-op
//delete[] * extraParamsRef;
}
op_def static Y startingValue(const X *input) {
return static_cast<Y>(0.0f);
}
op_def static Y postProcess(Y reduction, Nd4jLong n, Y *extraParamsRef) {
return reduction;
}
op_def static Y op(X d1, X d2, Y *extraParamsRef) {
return static_cast<Y>(d1 * d2);
}
#ifdef __CUDACC__
__device__
static inline Y opAtomic(X d1, X d2, Y *extraParamsRef) {
return op(d1, d2, extraParamsRef);
}
#endif
op_def static Y update(Y old, Y opOutput, Y *extraParamsRef) {
return opOutput + old;
}
op_def static Y merge(Y old, Y opOutput, Y *extraParamsRef) {
return update(old, opOutput, extraParamsRef);
}
op_def static void aggregateExtraParams(Y *extraParamsTotal, Y *extraParamsLocal) {}
};
/**
* Op to check equality within arrays
*/
template <typename X, typename Z>
class EqualsWithEps {
public:
static const int extraParamsLen = 0;
op_def static X * generateExtraParams() {
return nullptr;
}
op_def static void finalizeExtraParams(X *extraParamsRef) {
//no-op
}
op_def static Z startingValue(const X *input) {
return static_cast<Z>(0.0f);
}
op_def static Z postProcess(Z reduction, Nd4jLong n, Z *extraParamsRef) {
return reduction;
}
op_def static Z op(X d1, X d2, Z *extraParamsRef) {
double eps = nd4j::math::nd4j_abs<double>(extraParamsRef[2]);
return static_cast<Z>(!nd4j::math::nd4j_eq<X>(d1, d2, eps));
}
#ifdef __CUDACC__
__device__
static inline Z opAtomic(X d1, X d2, Z *extraParamsRef) {
return op(d1, d2, extraParamsRef);
}
#endif
op_def static Z update(Z old, Z opOutput, Z *extraParamsRef) {
return opOutput + old;
}
op_def static Z merge(X old, Z opOutput, Z *extraParamsRef) {
return update(old, opOutput, extraParamsRef);
}
op_def static void aggregateExtraParams(Z *extraParamsTotal, Z *extraParamsLocal) {}
};
template <typename X, typename Y>
class EuclideanDistance {
public:
static const int extraParamsLen = 0;
op_def static X * generateExtraParams() {
return nullptr;
}
op_def static void finalizeExtraParams(X *extraParamsRef) {
//no-op
}
op_def static Y startingValue(const X *input) {
return static_cast<Y>(0.0f);
}
op_def static Y postProcess(Y reduction, Nd4jLong n, Y *extraParamsRef) {
return nd4j::math::nd4j_sqrt<Y, Y>(reduction);
}
op_def static Y op(X d1, X d2, Y *extraParamsRef) {
X ret = d1 - d2;
return static_cast<Y>(ret * ret);
}
#ifdef __CUDACC__
__device__
static inline Y opAtomic(X d1, X d2, Y *extraParamsRef) {
return op(d1, d2, extraParamsRef);
}
#endif
op_def static Y update(Y old, Y opOutput, Y *extraParamsRef) {
return opOutput + old;
}
op_def static Y merge(Y old, Y opOutput, Y *extraParamsRef) {
return update(old, opOutput, extraParamsRef);
}
op_def static void aggregateExtraParams(Y *extraParamsTotal, Y *extraParamsLocal) {}
};
template <typename X, typename Y>
class ManhattanDistance {
public:
static const int extraParamsLen = 0;
op_def static X * generateExtraParams() {
return nullptr;
}
op_def static void finalizeExtraParams(X *extraParamsRef) {
//no-op
}
op_def static Y startingValue(const X *input) {
return static_cast<Y>(0.0f);
}
op_def static Y postProcess(Y reduction, Nd4jLong n, Y *extraParamsRef) {
return reduction;
}
op_def static Y op(X d1, X d2, Y *extraParamsRef) {
return nd4j::math::nd4j_abs<X>(d1 - d2);
}
op_def static Y update(Y old, Y opOutput, Y *extraParamsRef) {
return old + opOutput;
}
op_def static void aggregateExtraParams(Y *extraParamsTotal, Y *extraParamsLocal) {
}
#ifdef __CUDACC__
__device__
static inline Y opAtomic(X d1, X d2, Y *extraParamsRef) {
return op(d1, d2, extraParamsRef);
}
#endif
#ifndef __clang__
#pragma omp declare simd uniform(extraParamsRef)
#endif
op_def static Y merge(X old, X opOutput, X *extraParamsRef) {
return update(old, opOutput, extraParamsRef);
}
};
template <typename X, typename Z>
class IndexAbsoluteMax {
public:
static _CUDA_HD inline functions::indexreduce::IndexValue<X> op(functions::indexreduce::IndexValue<X> val, X *extraParams) {
return nd4j::math::nd4j_abs<X>(val);
}
static _CUDA_HD inline functions::indexreduce::IndexValue<X> update(functions::indexreduce::IndexValue<X> &old, functions::indexreduce::IndexValue<X> &opOutput, X *extraParams) {
opOutput.value = nd4j::math::nd4j_abs<X>(opOutput.value);
old.value = nd4j::math::nd4j_abs<X>(old.value);
if (opOutput.value > old.value)
return opOutput;
#ifdef __CUDACC__
// workaround for cuda race condition at merge phase
else if (opOutput.value == old.value && opOutput.index < old.index)
return opOutput;
#elif defined(__GNUC__)
#endif
return old;
}
static _CUDA_HD inline functions::indexreduce::IndexValue<X> merge(
functions::indexreduce::IndexValue<X> f1,
functions::indexreduce::IndexValue<X> f2, X *extraParams) {
if (nd4j::math::nd4j_abs<X>(f1.value) > nd4j::math::nd4j_abs<X>(f2.value))
return f2;
return f1;
}
static _CUDA_HD inline functions::indexreduce::IndexValue<X> postProcess(
functions::indexreduce::IndexValue<X> reduction, int n, int xOffset,
X *dx, int incx, X *extraParams, X *result) {
return reduction;
}
static _CUDA_HD inline X startingValue(const X *input) {
return 0;
}
static _CUDA_HD inline functions::indexreduce::IndexValue<X> startingIndexValue(X *input) {
functions::indexreduce::IndexValue<X> local;
local.value = startingValue(input);
local.index = 0;
return local;
}
static _CUDA_HD inline functions::indexreduce::IndexValue<X> op(functions::indexreduce::IndexValue<X> d1,
functions::indexreduce::IndexValue<X> d2, X *extraParams) {
return d1;
}
};
template <typename X, typename Z>
class FirstIndex {
public:
static _CUDA_HD inline functions::indexreduce::IndexValue<X> op(functions::indexreduce::IndexValue<X> val, X *extraParams) {
return val;
}
static _CUDA_HD functions::indexreduce::IndexValue<X> update(functions::indexreduce::IndexValue<X> &old, functions::indexreduce::IndexValue<X> &opOutput, X *extraParams) {
#ifdef __CUDACC__
if (opOutput.index < 0)
return old;
#endif
auto res = simdOps::MatchCondition<X,X>::op(opOutput.value, extraParams);
//printf("res: %f; oldIdx: %i; newIdx: %i\n", res, old.index, opOutput.index);
if (res == static_cast<X>(0))
return old;
if (old.index < 0)
return opOutput;
if (old.index > opOutput.index)
return opOutput;
return old;
}
static _CUDA_HD inline X startingValue(const X *input) {
return -nd4j::DataTypeUtils::infOrMax<X>();
}
static _CUDA_HD inline functions::indexreduce::IndexValue<X> startingIndexValue(X *input) {
functions::indexreduce::IndexValue<X> local;
local.value = startingValue(input);
local.index = -1;
return local;
}
static _CUDA_HD inline functions::indexreduce::IndexValue<X> op(functions::indexreduce::IndexValue<X> d1,
functions::indexreduce::IndexValue<X> d2, X *extraParams) {
return d1;
}
static _CUDA_HD inline functions::indexreduce::IndexValue<X> merge(
functions::indexreduce::IndexValue<X> f1,
functions::indexreduce::IndexValue<X> f2, X *extraParams) {
if (f1.index > f2.index)
return f2;
return f1;
}
static _CUDA_HD inline functions::indexreduce::IndexValue<X> postProcess(
functions::indexreduce::IndexValue<X> reduction, int n, int xOffset,
X *dx, int incx, X *extraParams, X *result) {
return reduction;
}
};
template <typename X, typename Z>
class LastIndex {
public:
static _CUDA_HD inline functions::indexreduce::IndexValue<X> op(functions::indexreduce::IndexValue<X> val, X *extraParams) {
return val;
}
static _CUDA_HD functions::indexreduce::IndexValue<X> update(functions::indexreduce::IndexValue<X> &old, functions::indexreduce::IndexValue<X> &opOutput, X *extraParams) {
#ifdef __CUDACC__
if (opOutput.index < 0)
return old;
#endif
auto res = simdOps::MatchCondition<X,X>::op(opOutput.value, extraParams);
if (res == static_cast<X>(0))
return old;
if (old.index < 0)
return opOutput;
if (old.index < opOutput.index)
return opOutput;
return old;
}
static _CUDA_HD inline X startingValue(const X *input) {
return -nd4j::DataTypeUtils::infOrMax<X>();
}
static _CUDA_HD inline functions::indexreduce::IndexValue<X> startingIndexValue(X *input) {
functions::indexreduce::IndexValue<X> local;
local.value = startingValue(input);
local.index = -1;
return local;
}
static _CUDA_HD inline functions::indexreduce::IndexValue<X> op(functions::indexreduce::IndexValue<X> d1,
functions::indexreduce::IndexValue<X> d2, X *extraParams) {
return d1;
}
static _CUDA_HD inline functions::indexreduce::IndexValue<X> merge(
functions::indexreduce::IndexValue<X> f1,
functions::indexreduce::IndexValue<X> f2, X *extraParams) {
if (f1.index < f2.index)
return f2;
return f1;
}
static _CUDA_HD inline functions::indexreduce::IndexValue<X> postProcess(
functions::indexreduce::IndexValue<X> reduction, int n, int xOffset,
X *dx, int incx, X *extraParams, X *result) {
return reduction;
}
};
template <typename X, typename Z>
class IndexMax {
public:
static _CUDA_HD inline functions::indexreduce::IndexValue<X> op(functions::indexreduce::IndexValue<X> val, X *extraParams) {
return val;
}
static _CUDA_HD functions::indexreduce::IndexValue<X> update(functions::indexreduce::IndexValue<X> &old, functions::indexreduce::IndexValue<X> &opOutput, X *extraParams) {
if (opOutput.value > old.value) {
return opOutput;
}
#ifdef __CUDACC__
// workaround for cuda race condition at merge phase
else if (opOutput.value == old.value && opOutput.index < old.index)
return opOutput;
#elif defined(__GNUC__)
#endif
return old;
}
static _CUDA_HD inline functions::indexreduce::IndexValue<X> merge(
functions::indexreduce::IndexValue<X> f1,
functions::indexreduce::IndexValue<X> f2, X *extraParams) {
if (f1.value > f2.value)
return f2;
return f1;
}
static _CUDA_HD inline functions::indexreduce::IndexValue<X> postProcess(
functions::indexreduce::IndexValue<X> reduction, int n, int xOffset,
X *dx, int incx, X *extraParams, X *result) {
return reduction;
}
static _CUDA_HD inline X startingValue(const X *input) {
return -nd4j::DataTypeUtils::infOrMax<X>();
}
static _CUDA_HD inline functions::indexreduce::IndexValue<X> startingIndexValue(X *input) {
functions::indexreduce::IndexValue<X> local;
local.value = startingValue(input);
local.index = 0;
return local;
}
static _CUDA_HD inline functions::indexreduce::IndexValue<X> op(functions::indexreduce::IndexValue<X> d1,
functions::indexreduce::IndexValue<X> d2, X *extraParams) {
return d1;
}
};
template <typename X, typename Z>
class IndexAbsoluteMin {
public:
static _CUDA_HD inline functions::indexreduce::IndexValue<X> op(
functions::indexreduce::IndexValue<X> val, X *extraParams) {
return val;
}
static _CUDA_HD inline X startingValue(const X *input) {
return nd4j::DataTypeUtils::infOrMax<X>();
}
static _CUDA_HD inline functions::indexreduce::IndexValue<X> startingIndexValue(X *input) {
functions::indexreduce::IndexValue<X> local;
local.value = startingValue(input);
local.index = 0;
return local;
}
static _CUDA_HD inline functions::indexreduce::IndexValue<X> update(functions::indexreduce::IndexValue<X> &old, functions::indexreduce::IndexValue<X> &opOutput, X *extraParams) {
opOutput.value = nd4j::math::nd4j_abs<X>(opOutput.value);
old.value = nd4j::math::nd4j_abs<X>(old.value);
if (opOutput.value < old.value)
return opOutput;
#ifdef __CUDACC__
// workaround for cuda race condition at merge phase
else if (opOutput.value == old.value && opOutput.index < old.index)
return opOutput;
#elif defined(__GNUC__)
#endif
return old;
}
static _CUDA_HD inline functions::indexreduce::IndexValue<X> merge(
functions::indexreduce::IndexValue<X> f1,
functions::indexreduce::IndexValue<X> f2, X *extraParams) {
if (nd4j::math::nd4j_abs<X>(f1.value) < nd4j::math::nd4j_abs<X>(f2.value))
return f2;
return f1;
}
static _CUDA_HD inline functions::indexreduce::IndexValue<X> postProcess(
functions::indexreduce::IndexValue<X> reduction, int n, int xOffset,
X *dx, int incx, X *extraParams, X *result) {
return reduction;
}
static _CUDA_HD inline functions::indexreduce::IndexValue<X> op(functions::indexreduce::IndexValue<X> d1,
functions::indexreduce::IndexValue<X> d2, X *extraParams) {
return d1;
}
};
template <typename X, typename Z>
class IndexMin {
public:
static _CUDA_HD inline functions::indexreduce::IndexValue<X> op(
functions::indexreduce::IndexValue<X> val, X *extraParams) {
return val;
}
static _CUDA_HD inline X startingValue(const X *input) {
return nd4j::DataTypeUtils::infOrMax<X>();
}
static _CUDA_HD inline functions::indexreduce::IndexValue<X> startingIndexValue(X *input) {
functions::indexreduce::IndexValue<X> local;
local.value = startingValue(input);
local.index = 0;
return local;
}
static _CUDA_HD inline functions::indexreduce::IndexValue<X> update(functions::indexreduce::IndexValue<X> &old, functions::indexreduce::IndexValue<X> &opOutput, X *extraParams) {
if (opOutput.value < old.value)
return opOutput;
#ifdef __CUDACC__
// workaround for cuda race condition at merge phase
else if (opOutput.value == old.value && opOutput.index < old.index)
return opOutput;
#elif defined(__GNUC__)
#endif
return old;
}
static _CUDA_HD inline functions::indexreduce::IndexValue<X> merge(
functions::indexreduce::IndexValue<X> f1,
functions::indexreduce::IndexValue<X> f2, X *extraParams) {
if (f1.value < f2.value)
return f2;
return f1;
}
static _CUDA_HD inline functions::indexreduce::IndexValue<X> postProcess(
functions::indexreduce::IndexValue<X> reduction, int n, int xOffset,
X *dx, int incx, X *extraParams, X *result) {
return reduction;
}
static _CUDA_HD inline functions::indexreduce::IndexValue<X> op(functions::indexreduce::IndexValue<X> d1,
functions::indexreduce::IndexValue<X> d2, X *extraParams) {
return d1;
}
};
template <typename X, typename Z>
class SummaryStatsVariance {
public:
static _CUDA_HD inline Z getValue(const bool biasCorrected, functions::summarystats::SummaryStatsData<X> val) {
if (biasCorrected) {
Z ret = static_cast<Z>(val.varianceBiasCorrected());
if (ret < static_cast<Z>(0.0f))
return static_cast<Z>(val.variance());
return ret;
}
return static_cast<Z>(val.variance());
}
static _CUDA_HD inline functions::summarystats::SummaryStatsData<X> op(functions::summarystats::SummaryStatsData<X> d1, Z *extraParams) {
return d1;
}
};
template <typename X, typename Z>
class SummaryStatsStandardDeviation {
public:
static _CUDA_HD inline Z getValue(const bool biasCorrected, functions::summarystats::SummaryStatsData<X> val) {
if (biasCorrected) {
auto ret = static_cast<Z>(val.varianceBiasCorrected());
if (ret < static_cast<Z>(0.0f))
return nd4j::math::nd4j_sqrt<double, Z>(val.variance());
else
return nd4j::math::nd4j_sqrt<double, Z>(ret);
}
return nd4j::math::nd4j_sqrt<double, Z>(val.variance());
}
static _CUDA_HD inline functions::summarystats::SummaryStatsData<X> op(functions::summarystats::SummaryStatsData<X> d1, Z *extraParams) {
return d1;
}
};
template <typename X>
class DropOut {
public:
no_op_exec_special_same
no_op_exec_special_same_cuda
inline _CUDA_D static X op(X d1, X *params) {
X prob = params[0];
#ifdef __CUDACC__
X length = params[1];
X tid = blockIdx.x * blockDim.x + threadIdx.x;
X rnd = nd4j::math::nd4j_abs<X>(nd4j::math::nd4j_cos<X>(static_cast<X>(clock64()) * static_cast<X>(tid) + static_cast<X>(length) * static_cast<X>(tid)));
#else
X rnd = static_cast<X>(rand() / RAND_MAX);
#endif
return rnd >= prob ? static_cast<X>(0.0f) : d1;
}
};
template <typename X, typename Y, typename Z>
class DropOutInverted {
public:
no_op_exec_special
no_op_exec_special_cuda
#ifdef __CUDACC__
__device__
#endif
inline static Z op(X d1, Y d2, Z *params) {
Y prob = d2;
#ifdef __CUDACC__
X length = params[1];
X tid = blockIdx.x * blockDim.x + threadIdx.x;
X rnd = nd4j::math::nd4j_abs<X>(nd4j::math::nd4j_cos<X>(static_cast<X>(clock64()) * static_cast<X>(tid) + static_cast<X>(length) * static_cast<X>(tid)));
#else
X rnd = static_cast<X>(rand() / RAND_MAX);
#endif
return rnd >= static_cast<X>(prob) ? static_cast<Z>(0.0f) : reinterpret_cast<Z>(d1 / static_cast<X>(prob));
}
};
template <typename X, typename Y, typename Z>
class ReplaceNans {
public:
no_op_exec_special
no_op_exec_special_cuda
op_def static Z op(X d1, Y d2, Z *params) {
return nd4j::math::nd4j_isnan(d1) ? static_cast<Z>(d2) : static_cast<Z>(d1) ;
}
};
// this op is used for conditional pairwise transforms only
template <typename X, typename Y, typename Z>
class CompareAndReplace{
public:
// op definition for PairWise Transform
op_def static Z op(X d1, Y d2, Z *params) {
auto zd1 = static_cast<Z>(d1);
auto zd2 = static_cast<Z>(d2);
auto compare = params[0];
auto eps = params[2];
int mode = (int) params[3];
if (mode == 0) // equals
if (nd4j::math::nd4j_abs<Z>(zd1 - compare) <= eps)
return zd2;
else
return zd1;
else if (mode == 1) // not equals eps
if (nd4j::math::nd4j_abs<Z>(zd1 - compare) > eps)
return zd2;
else
return zd1;
else if (mode == 2) // less_than eps
if (zd1 < compare)
return zd2;
else
return zd1;
else if (mode ==3) // greater_than
if (zd1 > compare)
return zd2;
else
return zd1;
else if (mode == 4) // less_or_equals_than
if (zd1 <= compare)
return zd2;
else
return zd1;
else if (mode == 5) // greater_or_equals_than
if (zd1 >= compare)
return zd2;
else
return zd1;
else if (mode == 6) // abs_less_than
if (nd4j::math::nd4j_abs<Z>(zd1) < compare)
return zd2;
else
return zd1;
else if (mode == 7) // abs_greater_than
if (nd4j::math::nd4j_abs<Z>(zd1) > compare)
return zd2;
else
return zd1;
else if (mode == 8) // is inf
if (nd4j::math::nd4j_isinf(zd1))
return zd2;
else
return zd1;
else if (mode == 9) // is nan
if (nd4j::math::nd4j_isnan(zd1))
return zd2;
else
return zd1;
else if (mode == 10)
if (zd1 == compare)
return zd2;
else
return zd1;
else if (mode == 11)
if (zd1 != compare)
return zd2;
else
return zd1;
else if (mode == 12) // abs_greater_or_equals_than
if (nd4j::math::nd4j_abs<Z>(zd1) >= compare)
return zd2;
else
return zd1;
else if (mode == 13) // abs_less_or_equals_than
if (nd4j::math::nd4j_abs<Z>(zd1) <= compare)
return zd2;
else
return zd1;
else
printf("Undefined boolean operation: [%i]\n", mode);
return zd1;
}
};
template <typename X, typename Y, typename Z>
class CompareAndSet {
public:
// op definition for PairWise Transform
op_def static Z op(X dX, Y dY, Z *params) {
auto d1 = static_cast<Z>(dX);
auto d2 = static_cast<Z>(dY);
auto compare = params[0];
auto eps = params[2];
auto mode = static_cast<int>(params[3]);
if (mode == 0) // equals
if (nd4j::math::nd4j_abs<Z>(d2 - compare) <= eps)
return d2;
else
return d1;
else if (mode == 1) // not equals
if (nd4j::math::nd4j_abs<Z>(d2 - compare) > eps)
return d2;
else
return d1;
else if (mode == 2) // less_than
if (d2 < compare)
return d2;
else
return d1;
else if (mode ==3) // greater_than
if (d2 > compare)
return d2;
else
return d1;
else if (mode == 4) // less_or_equals_than
if (d2 <= compare)
return d2;
else
return d1;
else if (mode == 5) // greater_or_equals_than
if (d2 >= compare)
return d2;
else
return d1;
else if (mode == 6) // abs_less_than
if (nd4j::math::nd4j_abs<Z>(d2) < compare)
return d2;
else
return d1;
else if (mode == 7) // abs_greater_than
if (nd4j::math::nd4j_abs<Z>(d2) > compare)
return d2;
else
return d1;
else if (mode == 8) // is inf
if (nd4j::math::nd4j_isinf(d2))
return d2;
else
return d1;
else if (mode == 9) // is nan
if (nd4j::math::nd4j_isnan(d2))
return d2;
else
return d1;
else if (mode == 10)
if (d2 == compare)
return d2;
else
return d1;
else if (mode == 11)
if (d2 != compare)
return d2;
else
return d1;
else if (mode == 12) // abs_greater_or_equals_than
if (nd4j::math::nd4j_abs<Z>(d1) >= compare)
return d2;
else
return d1;
else if (mode == 13) // abs_less_or_equals_than
if (nd4j::math::nd4j_abs<Z>(d1) <= compare)
return d2;
else
return d1;
else
printf("Undefined boolean operation: [%i]\n", mode);
return d1;
}
};
template <typename X>
class CompareAndSetTransform {
public:
no_op_exec_special_same
no_op_exec_special_same_cuda
// op definition for Transform
op_def static X op(X d1, X *params) {
auto compare = params[0];
auto set = params[1];
auto eps = params[2];
// with mode == 0 we do set if d1 equals to compare, and with mode == 1 - we go otherwise
int mode = (int) params[3];
if (mode == 0) // equals
if (nd4j::math::nd4j_abs<X>(d1 - compare) <= eps)
return set;
else
return d1;
//return nd4j::math::nd4j_abs<T>(d1 - compare) <= eps ? set : d1;
else if (mode == 1) // not equals
if (nd4j::math::nd4j_abs<X>(d1 - compare) > eps)
return set;
else
return d1;
//return nd4j::math::nd4j_abs<T>(d1 - compare) > eps ? set : d1;
else if (mode == 2) // less_than
if (d1 < compare)
return set;
else
return d1;
else if (mode ==3) // greater_than
if (d1 > compare)
return set;
else
return d1;
else if (mode == 4) // less_or_equals_than
if (d1 <= compare)
return set;
else
return d1;
else if (mode == 5) // greater_or_equals_than
if (d1 >= compare)
return set;
else
return d1;
else if (mode == 6) // abs_less_than
if (nd4j::math::nd4j_abs<X>(d1) < compare)
return set;
else
return d1;
else if (mode == 7) // abs_greater_than
if (nd4j::math::nd4j_abs<X>(d1) > compare)
return set;
else
return d1;
else if (mode == 8) // is inf
if (nd4j::math::nd4j_isinf(d1))
return set;
else
return d1;
else if (mode == 9) // is nan
if (nd4j::math::nd4j_isnan(d1))
return set;
else
return d1;
else if (mode == 10)
if (d1 == compare)
return set;
else
return d1;
else if (mode == 11)
if (d1 != compare)
return set;
else
return d1;
else if (mode == 12) // abs_greater_or_equals_than
if (nd4j::math::nd4j_abs<X>(d1) >= compare)
return set;
else
return d1;
else if (mode == 13) // abs_less_or_equals_than
if (nd4j::math::nd4j_abs<X>(d1) <= compare)
return set;
else
return d1;
else
printf("Undefined boolean operation: [%i]\n", mode);
return d1;
}
};
}
#endif
|
DRACC_OMP_052_Counter_working_atomic_no.c | /*
Concurrent access on an atomic counter. Inter and Intra Region.
*/
#include <stdio.h>
#define N 100000
int countervar = 0;
int count(){
#pragma omp target map(tofrom:countervar) device(0)
#pragma omp teams distribute parallel for
for (int i=0; i<N; i++){
#pragma omp atomic update
countervar++;
}
return 0;
}
int main(){
count();
printf("counter: %i expected: 100000\n ",countervar);
return 0;
} |
GB_unaryop__minv_uint16_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__minv_uint16_int8
// op(A') function: GB_tran__minv_uint16_int8
// C type: uint16_t
// A type: int8_t
// cast: uint16_t cij = (uint16_t) aij
// unaryop: cij = GB_IMINV_UNSIGNED (aij, 16)
#define GB_ATYPE \
int8_t
#define GB_CTYPE \
uint16_t
// 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 = GB_IMINV_UNSIGNED (x, 16) ;
// casting
#define GB_CASTING(z, aij) \
uint16_t z = (uint16_t) aij ;
// cij = op (cast (aij))
#define GB_CAST_OP(pC,pA) \
{ \
/* aij = Ax [pA] */ \
GB_GETA (aij, Ax, pA) ; \
/* Cx [pC] = op (cast (aij)) */ \
GB_CASTING (z, aij) ; \
GB_OP (GB_CX (pC), z) ; \
}
// disable this operator and use the generic case if these conditions hold
#define GB_DISABLE \
(GxB_NO_MINV || GxB_NO_UINT16 || GxB_NO_INT8)
//------------------------------------------------------------------------------
// Cx = op (cast (Ax)): apply a unary operator
//------------------------------------------------------------------------------
GrB_Info GB_unop__minv_uint16_int8
(
uint16_t *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__minv_uint16_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
|
app.c |
#include <assert.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <stdint.h>
#include <omp.h>
#include "../../support/matrix.h"
#include "../../support/params.h"
#include "../../support/timer.h"
#include "../../support/utils.h"
int main(int argc, char** argv) {
// Process parameters
struct Params p = input_params(argc, argv);
// Initialize SpMV data structures
PRINT_INFO(p.verbosity >= 1, "Reading matrix %s", p.fileName);
struct COOMatrix cooMatrix = readCOOMatrix(p.fileName);
PRINT_INFO(p.verbosity >= 1, " %u rows, %u columns, %u nonzeros", cooMatrix.numRows, cooMatrix.numCols, cooMatrix.numNonzeros);
struct CSRMatrix csrMatrix = coo2csr(cooMatrix);
float* inVector = malloc(csrMatrix.numCols*sizeof(float));
float* outVector = malloc(csrMatrix.numRows*sizeof(float));
initVector(inVector, csrMatrix.numCols);
// Calculating result on CPU
PRINT_INFO(p.verbosity >= 1, "Calculating result on CPU");
omp_set_num_threads(4);
Timer timer;
startTimer(&timer);
#pragma omp parallel for
for(uint32_t rowIdx = 0; rowIdx < csrMatrix.numRows; ++rowIdx) {
float sum = 0.0f;
for(uint32_t i = csrMatrix.rowPtrs[rowIdx]; i < csrMatrix.rowPtrs[rowIdx + 1]; ++i) {
uint32_t colIdx = csrMatrix.nonzeros[i].col;
float value = csrMatrix.nonzeros[i].value;
sum += inVector[colIdx]*value;
}
outVector[rowIdx] = sum;
}
stopTimer(&timer);
if(p.verbosity == 0) PRINT("%f", getElapsedTime(timer)*1e3);
PRINT_INFO(p.verbosity >= 1, " Elapsed time: %f ms", getElapsedTime(timer)*1e3);
// Deallocate data structures
freeCOOMatrix(cooMatrix);
freeCSRMatrix(csrMatrix);
free(inVector);
free(outVector);
return 0;
}
|
rose_v1_jacobi_seq.c | /* An example code
*
* */
#include <stdio.h>
#include <math.h>
#include <omp.h>
void driver();
void initialize();
void jacobi();
void error_check();
#define MSIZE 200
int n;
int m;
int mits;
double tol;
double relax = 1.0;
double alpha = 0.0543;
double u[200][200];
double f[200][200];
double uold[200][200];
double dx;
double dy;
int main()
{
// float toler;
/* printf("Input n,m (< %d) - grid dimension in x,y direction:\n",MSIZE);
scanf ("%d",&n);
scanf ("%d",&m);
printf("Input tol - error tolerance for iterative solver\n");
scanf("%f",&toler);
tol=(double)toler;
printf("Input mits - Maximum iterations for solver\n");
scanf("%d",&mits);
*/
n = 200;
m = 200;
tol = 0.0000000001;
mits = 1000;
driver();
return 1;
}
/*************************************************************
* Subroutine driver ()
* This is where the arrays are allocated and initialzed.
*
* Working varaibles/arrays
* dx - grid spacing in x direction
* dy - grid spacing in y direction
*************************************************************/
void driver()
{
initialize();
/* Solve Helmholtz equation */
jacobi();
/* error_check (n,m,alpha,dx,dy,u,f) */
error_check();
}
/* subroutine initialize (n,m,alpha,dx,dy,u,f)
******************************************************
* Initializes data
* Assumes exact solution is u(x,y) = (1-x^2)*(1-y^2)
*
******************************************************/
void initialize()
{
int i;
int j;
int xx;
int yy;
// double PI = 3.1415926;
dx = 2.0 / (n - 1);
// -->dx@112:2
dy = 2.0 / (m - 1);
//-->dy@113:2
/* Initialize initial condition and RHS */
//#pragma omp parallel for private(i,j,xx,yy)
#pragma omp parallel for private (xx,yy,i,j) firstprivate (n,m)
for (i = 0; i <= n - 1; i += 1) {
#pragma omp parallel for private (xx,yy,j) firstprivate (alpha,dx,dy)
for (j = 0; j <= m - 1; j += 1) {
xx = ((int )(- 1.0 + dx * (i - 1)));
/* -1 < x < 1 */
yy = ((int )(- 1.0 + dy * (j - 1)));
/* -1 < y < 1 */
u[i][j] = 0.0;
f[i][j] = - 1.0 * alpha * (1.0 - (xx * xx)) * (1.0 - (yy * yy)) - 2.0 * (1.0 - (xx * xx)) - 2.0 * (1.0 - (yy * yy));
}
}
}
/* subroutine jacobi (n,m,dx,dy,alpha,omega,u,f,tol,maxit)
******************************************************************
* Subroutine HelmholtzJ
* Solves poisson equation on rectangular grid assuming :
* (1) Uniform discretization in each direction, and
* (2) Dirichlect boundary conditions
*
* Jacobi method is used in this routine
*
* Input : n,m Number of grid points in the X/Y directions
* dx,dy Grid spacing in the X/Y directions
* alpha Helmholtz eqn. coefficient
* omega Relaxation factor
* f(n,m) Right hand side function
* u(n,m) Dependent variable/Solution
* tol Tolerance for iterative solver
* maxit Maximum number of iterations
*
* Output : u(n,m) - Solution
*****************************************************************/
void jacobi()
{
double omega;
int i;
int j;
int k;
double error;
double resid;
double ax;
double ay;
double b;
omega = relax;
/*
* Initialize coefficients */
ax = 1.0 / (dx * dx);
/* X-direction coef */
ay = 1.0 / (dy * dy);
/* Y-direction coef */
b = - 2.0 / (dx * dx) - 2.0 / (dy * dy) - alpha;
/* Central coeff */
error = 10.0 * tol;
k = 1;
while(k <= mits && error > tol){
error = 0.0;
/* Copy new solution into old */
//#pragma omp parallel
{
//#pragma omp for private(i,j)
#pragma omp parallel for private (i,j)
for (i = 0; i <= n - 1; i += 1) {
#pragma omp parallel for private (j)
for (j = 0; j <= m - 1; j += 1) {
uold[i][j] = u[i][j];
}
}
//#pragma omp for private(i,j,resid) reduction(+:error) nowait
for (i = 1; i <= n - 1 - 1; i += 1) {
for (j = 1; j <= m - 1 - 1; j += 1) {
resid = (ax * (uold[i - 1][j] + uold[i + 1][j]) + ay * (uold[i][j - 1] + uold[i][j + 1]) + b * uold[i][j] - f[i][j]) / b;
u[i][j] = uold[i][j] - omega * resid;
error = error + resid * resid;
}
}
}
/* omp end parallel */
/* Error check */
// k = k + 1;
error = sqrt(error) / (n * m);
/* End iteration loop */
}
printf("Total Number of Iterations:%d\n",k);
printf("Residual:%E\n",error);
}
void error_check()
{
int i;
int j;
double xx;
double yy;
double temp;
double error;
dx = 2.0 / (n - 1);
dy = 2.0 / (m - 1);
error = 0.0;
//#pragma omp parallel for private(i,j,xx,yy,temp) reduction(+:error)
#pragma omp parallel for private (xx,yy,temp,i,j) reduction (+:error)
for (i = 0; i <= n - 1; i += 1) {
#pragma omp parallel for private (xx,yy,temp,j) reduction (+:error) firstprivate (dx,dy)
for (j = 0; j <= m - 1; j += 1) {
xx = - 1.0 + dx * (i - 1);
yy = - 1.0 + dy * (j - 1);
temp = u[i][j] - (1.0 - xx * xx) * (1.0 - yy * yy);
error = error + temp * temp;
}
}
error = sqrt(error) / (n * m);
printf("Solution Error :%E \n",error);
}
|
profiler_interface.h | /*
# =============================================================================
# Copyright (c) 2016 - 2021 Blue Brain Project/EPFL
#
# See top-level LICENSE file for details.
# =============================================================================
*/
#pragma once
#include <initializer_list>
#include <type_traits>
#if defined(CORENEURON_CALIPER)
#include <caliper/cali.h>
#endif
#ifdef CORENEURON_CUDA_PROFILING
#include <cuda_profiler_api.h>
#endif
#if defined(CRAYPAT)
#include <pat_api.h>
#endif
#if defined(TAU)
#include <TAU.h>
#endif
#if defined(LIKWID_PERFMON)
#include <likwid.h>
#endif
namespace coreneuron {
namespace detail {
/*! \class Instrumentor
* \brief Instrumentation infrastructure for benchmarking and profiling.
*
* The Instrumentor class exposes static methods that can be used to
* toggle with fine-grained resolution the profiling of specific
* areas within the code.
*/
template <class... TProfilerImpl>
struct Instrumentor {
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wunused-value"
/*! \fn phase_begin
* \brief Activate the collection of profiling data within a code region.
*
* This function semantically defines the beginning of a region
* of code that the user wishes to profile.
* Loops through all enabled profilers and calls the relevant
* `phase_begin` function.
* This function should have a non-empty implementation only for
* profilers that allow multiple code regions with different names
* to be profiled concurrently.
*
* @param name the (unique) identifier of the code region to be profiled
*/
inline static void phase_begin(const char* name) {
std::initializer_list<int>{(TProfilerImpl::phase_begin(name), 0)...};
}
/*! \fn phase_end
* \brief Deactivate the collection of profiling data within a code region.
*
* This function semantically defines the end of a region
* of code that the user wishes to profile.
* Loops through all enabled profilers and calls the relevant
* `phase_end` function.
* This function should have a non-empty implementation only for
* profilers that allow multiple code regions with different names
* to be profiled concurrently.
*
* @param name the (unique) identifier of the code region to be profiled
*/
inline static void phase_end(const char* name) {
std::initializer_list<int>{(TProfilerImpl::phase_end(name), 0)...};
}
/*! \fn start_profile
* \brief Globally activate the collection of profiling data.
*
* Activate the collection of profiler data without defining
* a region of interest with a given name, as opposed to `phase_begin`.
* Loops through all enabled profilers and calls the relevant
* `start_profile` function.
* This function should have a non-empty implementation only for
* profilers that expose simply a global begin/end interface, without
* named regions.
*/
inline static void start_profile() {
std::initializer_list<int>{(TProfilerImpl::start_profile(), 0)...};
}
/*! \fn stop_profile
* \brief Globally deactivate the collection of profiling data.
*
* Deactivate the collection of profiler data without defining
* a region of interest with a given name, as opposed to `phase_end`.
* Loops through all enabled profilers and calls the relevant
* `stop_profile` function.
* This function should have a non-empty implementation only for
* profilers that expose simply a global begin/end interface, without
* named regions.
*/
inline static void stop_profile() {
std::initializer_list<int>{(TProfilerImpl::stop_profile(), 0)...};
}
/*! \fn init_profile
* \brief Initialize the profiler.
*
* Initialize a profiler's internal structure, without activating yet
* any data collection, similar in concept to MPI_Init.
* Loops through all enabled profilers and calls the relevant
* `init_profile` function.
* This function should have a non-empty implementation only for
* profilers that require special initialization, typically before
* any memory allocation is done.
*/
inline static void init_profile() {
std::initializer_list<int>{(TProfilerImpl::init_profile(), 0)...};
}
/*! \fn finalize_profile
* \brief Finalize the profiler.
*
* Finalize a profiler's internal structure, without activating yet
* any data collection, similar in concept to MPI_Finalize.
* Loops through all enabled profilers and calls the relevant
* `finalize_profile` function.
* This function should have a non-empty implementation only for
* profilers that require special finalization.
*/
inline static void finalize_profile() {
std::initializer_list<int>{(TProfilerImpl::finalize_profile(), 0)...};
}
#pragma clang diagnostic pop
};
#if defined(CORENEURON_CALIPER)
struct Caliper {
inline static void phase_begin(const char* name) {
CALI_MARK_BEGIN(name);
};
inline static void phase_end(const char* name) {
CALI_MARK_END(name);
};
inline static void start_profile(){};
inline static void stop_profile(){};
inline static void init_profile(){};
inline static void finalize_profile(){};
};
#endif
#ifdef CORENEURON_CUDA_PROFILING
struct CudaProfiling {
inline static void phase_begin(const char* name){};
inline static void phase_end(const char* name){};
inline static void start_profile() {
cudaProfilerStart();
};
inline static void stop_profile() {
cudaProfilerStop();
};
inline static void init_profile(){};
inline static void finalize_profile(){};
};
#endif
#if defined(CRAYPAT)
struct CrayPat {
inline static void phase_begin(const char* name){};
inline static void phase_end(const char* name){};
inline static void start_profile() {
PAT_record(PAT_STATE_ON);
};
inline static void stop_profile() {
PAT_record(PAT_STATE_OFF);
};
inline static void init_profile(){};
inline static void finalize_profile(){};
};
#endif
#if defined(TAU)
struct Tau {
inline static void phase_begin(const char* name){};
inline static void phase_end(const char* name){};
inline static void start_profile() {
TAU_ENABLE_INSTRUMENTATION();
};
inline static void stop_profile() {
TAU_DISABLE_INSTRUMENTATION();
};
inline static void init_profile(){};
inline static void finalize_profile(){};
};
#endif
#if defined(LIKWID_PERFMON)
struct Likwid {
inline static void phase_begin(const char* name) {
LIKWID_MARKER_START(name);
};
inline static void phase_end(const char* name) {
LIKWID_MARKER_STOP(name);
};
inline static void start_profile(){};
inline static void stop_profile(){};
inline static void init_profile() {
LIKWID_MARKER_INIT;
#pragma omp parallel
{ LIKWID_MARKER_THREADINIT; }
};
inline static void finalize_profile() {
LIKWID_MARKER_CLOSE;
};
};
#endif
struct NullInstrumentor {
inline static void phase_begin(const char* name){};
inline static void phase_end(const char* name){};
inline static void start_profile(){};
inline static void stop_profile(){};
inline static void init_profile(){};
inline static void finalize_profile(){};
};
using InstrumentorImpl = detail::Instrumentor<
#if defined CORENEURON_CALIPER
detail::Caliper,
#endif
#ifdef CORENEURON_CUDA_PROFILING
detail::CudaProfiling,
#endif
#if defined(CRAYPAT)
detail::CrayPat,
#endif
#if defined(TAU)
detail::Tau,
#endif
#if defined(LIKWID_PERFMON)
detail::Likwid,
#endif
detail::NullInstrumentor>;
} // namespace detail
namespace Instrumentor {
struct phase {
const char* phase_name;
phase(const char* name)
: phase_name(name) {
detail::InstrumentorImpl::phase_begin(phase_name);
}
~phase() {
detail::InstrumentorImpl::phase_end(phase_name);
}
};
inline static void start_profile() {
detail::InstrumentorImpl::start_profile();
}
inline static void stop_profile() {
detail::InstrumentorImpl::stop_profile();
}
inline static void phase_begin(const char* name) {
detail::InstrumentorImpl::phase_begin(name);
}
inline static void phase_end(const char* name) {
detail::InstrumentorImpl::phase_end(name);
}
inline static void init_profile() {
detail::InstrumentorImpl::init_profile();
}
inline static void finalize_profile() {
detail::InstrumentorImpl::finalize_profile();
}
} // namespace Instrumentor
} // namespace coreneuron
|
fill.c |
/* Fill the nonzero term of the A matrix */
#include <petscmat.h>
#include <petscvec.h>
#include <petscsnes.h>
#include <../src/mat/impls/baij/seq/baij.h>
#include <omp.h>
#include "inc/ktime.h"
#include "inc/geometry.h"
#include "inc/ker/phy.h"
#include "inc/ker/kernel.h"
int
fill_mat(struct fill *restrict fill)
{
struct ktime ktime;
setktime(&ktime);
const double *restrict q = fill->q;
const struct geometry *restrict g = fill->g;
const struct ivals *restrict iv = fill->iv;
const struct ts *restrict ts = fill->ts;
Mat A = fill->A;
int ierr;
uint32_t i;
Mat_SeqBAIJ *restrict a = (Mat_SeqBAIJ *) A->data;
size_t sz = (a->bs2 * a->i[a->mbs]);
__assume_aligned(a->a, 64);
memset(a->a, 0, sz * sizeof(double));
size_t nnodes = g->n->sz;
size_t bsz = g->c->bsz;
double cfl = ts->cfl;
double *restrict area = g->n->area;
double *restrict cdt = ts->cdt;
/*
Loop over the nodes to compute the local indices of each row
and column to insert the values using PETSc routine
*/
#pragma omp parallel for
for(i = 0; i < nnodes; i++)
{
double tmp = area[i] / (cfl * cdt[i]);
uint32_t j;
for(j = 0; j < bsz; j++)
{
uint32_t idx = j + bsz * i;
/*
Inserts or adds values into certain locations of a matrix,
using a local ordering of the nodes
*/
MatSetValues(A, 1, (const int *) &idx, 1, (const int *) &idx,
(const double *) &tmp, ADD_VALUES);
}
}
struct edge *restrict eptr = g->e->eptr;
struct xyzn *restrict xyzn = g->e->xyzn;
uint32_t *restrict ie = g->s->ie;
uint32_t *restrict part = g->s->part;
#pragma omp parallel
{
uint32_t t = omp_get_thread_num();
uint32_t ie0 = ie[t];
uint32_t ie1 = ie[t+1];
uint32_t i;
for(i = ie0; i < ie1; i++)
{
uint32_t n0 = eptr->n0[i];
uint32_t n1 = eptr->n1[i];
double xn = xyzn->x0[i];
double yn = xyzn->x1[i];
double zn = xyzn->x2[i];
double ln = xyzn->x3[i];
/*
Now lets get our other 2 vectors
For first vector, use {1,0,0} and subtract off the component
in the direction of the face normal. If the inner product of
{1,0,0} is close to unity, use {0,1,0}
*/
double dot = xn;
double X1, Y1, Z1;
if(fabs(dot) < 0.95f)
{
X1 = 1.f - dot * xn;
Y1 = - dot * yn;
Z1 = - dot * zn;
}
else
{
dot = yn;
X1 = - dot * xn;
Y1 = 1.f - dot * yn;
Z1 = - dot * zn;
}
/* Normalize the first vector */
double size = X1 * X1;
size += Y1 * Y1;
size += Z1 * Z1;
size = sqrt(size);
X1 /= size;
Y1 /= size;
Z1 /= size;
/* Take cross-product of normal and V1 to get V2 */
double X2 = yn * Z1;
X2 -= zn * Y1;
double Y2 = zn * X1;
Y2 -= xn * Z1;
double Z2 = xn * Y1;
Z2 -= yn * X1;
/* Variables on left */
// Velocity u
double uL = q[bsz * n0 + 1];
// Velocity v
double vL = q[bsz * n0 + 2];
// Velocity w
double wL = q[bsz * n0 + 3];
double ubarL = xn * uL;
ubarL += yn * vL;
ubarL += zn * wL;
/* Variables on right */
// Velocity u
double uR = q[bsz * n1 + 1];
// Velocity v
double vR = q[bsz * n1 + 2];
// Velocity w
double wR = q[bsz * n1 + 3];
double ubarR = xn * uR;
ubarR += yn * vR;
ubarR += zn * wR;
/*
Now compute eigenvalues and |A| from averaged variables
Avergage variables
*/
double u = 0.5f * (uL + uR);
double v = 0.5f * (vL + vR);
double w = 0.5f * (wL + wR);
double ubar = xn * u;
ubar += yn * v;
ubar += zn * w;
double c2 = ubar * ubar + BETA;
double c = sqrt(c2);
/* Put in the eigenvalue smoothing stuff */
double eig1 = ln * fabs(ubar);
double eig2 = ln * fabs(ubar);
double eig3 = ln * fabs(ubar + c);
double eig4 = ln * fabs(ubar - c);
double phi1 = xn * BETA;
phi1 += u * ubar;
double phi2 = yn * BETA;
phi2 += v * ubar;
double phi3 = zn * BETA;
phi3 += w * ubar;
double phi4 = Y2 * phi3;
phi4 -= Z2 * phi2;
double phi5 = Z2 * phi1;
phi5 -= X2 * phi3;
double phi6 = X2 * phi2;
phi6 -= Y2 * phi1;
double phi7 = Z1 * phi2;
phi7 -= Y1 * phi3;
double phi8 = X1 * phi3;
phi8 -= Z1 * phi1;
double phi9 = Y1 * phi1;
phi9 -= X1 * phi2;
/* Components of T(inverse) (call this y) */
double c2inv = 1.f / c2;
double y11 = u * phi4;
y11 += v * phi5;
y11 += w * phi6;
y11 = -c2inv * y11 / BETA;
double y21 = u * phi7;
y21 += v * phi8;
y21 += w * phi9;
y21 = -c2inv * y21 / BETA;
double y31 = c2inv * (c - ubar);
y31 = 0.5f * y31 / BETA;
double y41 = c2inv * (c + ubar);
y41 = -0.5f * y41 / BETA;
double y12 = c2inv * phi4;
double y22 = c2inv * phi7;
double y32 = c2inv * 0.5f * xn;
double y42 = c2inv * 0.5f * xn;
double y13 = c2inv * phi5;
double y23 = c2inv * phi8;
double y33 = c2inv * 0.5f * yn;
double y43 = c2inv * 0.5f * yn;
double y14 = c2inv * phi6;
double y24 = c2inv * phi9;
double y34 = c2inv * 0.5f * zn;
double y44 = c2inv * 0.5f * zn;
/* Now get elements of T */
double t13 = c * BETA;
double t23 = u * (ubar + c);
t23 += xn * BETA;
double t33 = v * (ubar + c);
t33 += yn * BETA;
double t43 = w * (ubar + c);
t43 += zn * BETA;
double t14 = -c * BETA;
double t24 = u * (ubar - c);
t24 += xn * BETA;
double t34 = v * (ubar - c);
t34 += yn * BETA;
double t44 = w * (ubar - c);
t44 += zn * BETA;
/* Compute T * |lambda| * T(inv) */
double a11 = eig3 * t13 * y31;
a11 += eig4 * t14 * y41;
double a12 = eig3 * t13 * y32;
a12 += eig4 * t14 * y42;
double a13 = eig3 * t13 * y33;
a13 += eig4 * t14 * y43;
double a14 = eig3 * t13 * y34;
a14 += eig4 * t14 * y44;
double a21 = eig1 * X1 * y11;
a21 += eig2 * X2 * y21;
a21 += eig3 * t23 * y31;
a21 += eig4 * t24 * y41;
double a22 = eig1 * X1 * y12;
a22 += eig2 * X2 * y22;
a22 += eig3 * t23 * y32;
a22 += eig4 * t24 * y42;
double a23 = eig1 * X1 * y13;
a23 += eig2 * X2 * y23;
a23 += eig3 * t23 * y33;
a23 += eig4 * t24 * y43;
double a24 = eig1 * X1 * y14;
a24 += eig2 * X2 * y24;
a24 += eig3 * t23 * y34;
a24 += eig4 * t24 * y44;
double a31 = eig1 * Y1 * y11;
a31 += eig2 * Y2 * y21;
a31 += eig3 * t33 * y31;
a31 += eig4 * t34 * y41;
double a32 = eig1 * Y1 * y12;
a32 += eig2 * Y2 * y22;
a32 += eig3 * t33 * y32;
a32 += eig4 * t34 * y42;
double a33 = eig1 * Y1 * y13;
a33 += eig2 * Y2 * y23;
a33 += eig3 * t33 * y33;
a33 += eig4 * t34 * y43;
double a34 = eig1 * Y1* y14;
a34 += eig2 * Y2 * y24;
a34 += eig3 * t33 * y34;
a34 += eig4 * t34 * y44;
double a41 = eig1 * Z1 * y11;
a41 += eig2 * Z2 * y21;
a41 += eig3 * t43 * y31;
a41 += eig4 * t44 * y41;
double a42 = eig1 * Z1 * y12;
a42 += eig2 * Z2 * y22;
a42 += eig3 * t43 * y32;
a42 += eig4 * t44 * y42;
double a43 = eig1 * Z1 * y13;
a43 += eig2 * Z2 * y23;
a43 += eig3 * t43 * y33;
a43 += eig4 * t44 * y43;
double a44 = eig1 * Z1 * y14;
a44 += eig2 * Z2 * y24;
a44 += eig3 * t43 * y34;
a44 += eig4 * t44 * y44;
/* Regular Jacobians on left: Form 0.5 * (A + |A|) */
double lb = ln * BETA;
double lx = ln * xn;
double ly = ln * yn;
double lz = ln * zn;
double val[4][8];
val[0][0] = 0.5f * a11;
val[0][1] = 0.5f * ((lb * xn) + a12);
val[0][2] = 0.5f * ((lb * yn) + a13);
val[0][3] = 0.5f * ((lb * zn) + a14);
val[1][0] = 0.5f * (lx + a21);
val[1][1] = 0.5f * ((ln * (ubarL + xn * uL)) + a22);
val[1][2] = 0.5f * ((ly * uL) + a23);
val[1][3] = 0.5f * ((lz * uL) + a24);
val[2][0] = 0.5f * (ly + a31);
val[2][1] = 0.5f * ((lx * vL) + a32);
val[2][2] = 0.5f * ((ln * (ubarL + yn * vL)) + a33);
val[2][3] = 0.5f * ((lz * vL) + a34);
val[3][0] = 0.5f * (lz + a41);
val[3][1] = 0.5f * ((lx * wL) + a42);
val[3][2] = 0.5f * ((ly * wL) + a43);
val[3][3] = 0.5f * ((ln * (ubarL + zn * wL)) + a44);
/* Regular Jaobians on right */
val[0][4] = 0.5f * -a11;
val[0][5] = 0.5f * ((lb * xn) - a12);
val[0][6] = 0.5f * ((lb * yn) - a13);
val[0][7] = 0.5f * ((lb * zn) - a14);
val[1][4] = 0.5f * (lx - a21);
val[1][5] = 0.5f * ((ln * (ubarR + xn * uR)) - a22);
val[1][6] = 0.5f * ((ly * uR) - a23);
val[1][7] = 0.5f * ((lz * uR) - a24);
val[2][4] = 0.5f * (ly - a31);
val[2][5] = 0.5f * ((lx * vR) - a32);
val[2][6] = 0.5f * ((ln * (ubarR + yn * vR)) - a33);
val[2][7] = 0.5f * ((lz * vR) - a34);
val[3][4] = 0.5f * (lz - a41);
val[3][5] = 0.5f * ((lx * wR) - a42);
val[3][6] = 0.5f * ((ly * wR) - a43);
val[3][7] = 0.5f * ((ln * (ubarR + zn * wR)) - a44);
uint32_t idxn[2];
idxn[0] = n0;
idxn[1] = n1;
if(part[n0] == t)
{
MatSetValuesBlocked(A, 1, (const int *) &n0, 2, (const int *) idxn,
(const double *) val, ADD_VALUES);
}
if(part[n1] == t)
{
/*
Exchange elements in place
*/
uint32_t j;
for(j = 0; j < bsz; j++)
{
uint32_t k;
for(k = 0; k < 8; k++) val[j][k] = -val[j][k];
}
MatSetValuesBlocked(A, 1, (const int *) &n1, 2, (const int *) idxn,
(const double *) val, ADD_VALUES);
}
}
}
size_t nsnodes = g->b->s->n->sz;
uint32_t *restrict nsptr = g->b->s->n->nptr;
struct xyz *restrict s_xyz = g->b->s->n->xyz;
/* Solid boundary points */
#pragma omp parallel for
for(i = 0; i < nsnodes; i++)
{
uint32_t n = nsptr[i];
double v[3];
v[0] = s_xyz->x0[i];
v[1] = s_xyz->x1[i];
v[2] = s_xyz->x2[i];
uint32_t idxm[3];
idxm[0] = bsz * n + 1;
idxm[1] = bsz * n + 2;
idxm[2] = bsz * n + 3;
uint32_t idxn = bsz * n;
MatSetValues(A, 3, (const int *) idxm, 1, (const int *) &idxn,
(const double *) v, ADD_VALUES);
}
size_t nfnodes = g->b->f->n->sz;
uint32_t *restrict nfptr = g->b->f->n->nptr;
struct xyz *restrict f_xyz = g->b->f->n->xyz;
/* Free boundary points */
#pragma omp parallel for
for(i = 0; i < nfnodes; i++)
{
uint32_t n = nfptr[i];
double xn = f_xyz->x0[i];
double yn = f_xyz->x1[i];
double zn = f_xyz->x2[i];
double ln = sqrt(xn * xn + yn * yn + zn * zn);
xn /= ln;
yn /= ln;
zn /= ln;
/* 9 FLOPS */
/*
Now lets get our other 2 vectors
For first vector, use {1,0,0} and subtract off the component
in the direction of the face normal. If the inner product of
{1,0,0} is close to unity, use {0,1,0}
*/
double dot = xn;
double X1, Y1, Z1;
if(fabs(dot) < 0.95f)
{
X1 = 1.f - dot * xn;
Y1 = - dot * yn;
Z1 = - dot * zn;
}
else
{
dot = yn;
X1 = - dot * xn;
Y1 = 1.f - dot * yn;
Z1 = - dot * zn;
}
/* 6 FLOPS */
/* Normalize the first vector (V1) */
double size = sqrt(X1 * X1 + Y1 * Y1 + Z1 * Z1);
X1 /= size;
Y1 /= size;
Z1 /= size;
/* 9 FLOPS */
/* Take cross-product of normal with V1 to get V2 */
double X2 = yn * Z1 - zn * Y1;
double Y2 = zn * X1 - xn * Z1;
double Z2 = xn * Y1 - yn * X1;
/* 9 FLOPS */
/* Calculate elements of T and T(inverse)
evaluated at freestream */
double ubar0 = xn * iv->u;
ubar0 += yn * iv->v;
ubar0 += zn * iv->w;
double c20 = ubar0 * ubar0 + BETA;
double c0 = sqrt(c20);
double phi1 = xn * BETA;
phi1 += iv->u * ubar0;
double phi2 = yn * BETA;
phi2 += iv->v * ubar0;
double phi3 = zn * BETA;
phi3 += iv->w * ubar0;
double phi4 = Y2 * phi3;
phi4 -= Z2 * phi2;
double phi5 = Z2 * phi1;
phi5 -= X2 * phi3;
double phi6 = X2 * phi2;
phi6 -= Y2 * phi1;
double phi7 = Z1 * phi2;
phi7 -= Y1 * phi3;
double phi8 = X1 * phi3;
phi8 -= Z1 * phi1;
double phi9 = Y1 * phi1;
phi9 -= X1 * phi2;
/* 9 * 3 + 8 FLOPS */
double t13 = c0 * BETA;
double t23 = iv->u * (ubar0 + c0);
t23 += xn * BETA;
double t33 = iv->v * (ubar0 + c0);
t33 += yn * BETA;
double t43 = iv->w * (ubar0 + c0);
t43 += zn * BETA;
double t14 = -c0 * BETA;
double t24 = iv->u * (ubar0 - c0);
t24 += xn * BETA;
double t34 = iv->v * (ubar0 - c0);
t34 += yn * BETA;
double t44 = iv->w * (ubar0 - c0);
t44 += zn * BETA;
double ti11 = iv->u * phi4;
ti11 += iv->v * phi5;
ti11 += iv->w * phi6;
ti11 = -ti11 / BETA / c20;
double ti21 = iv->u * phi7;
ti21 += iv->v * phi8;
ti21 += iv->w * phi9;
ti21 = -ti21 / BETA / c20;
double ti31 = (c0 - ubar0) / (2.f * BETA * c20);
double ti41 = -(c0 + ubar0) / (2.f * BETA * c20);
double ti12 = phi4 / c20;
double ti22 = phi7 / c20;
double ti32 = 0.5f * xn / c20;
double ti42 = 0.5f * xn / c20;
double ti13 = phi5 / c20;
double ti23 = phi8 / c20;
double ti33 = 0.5f * yn / c20;
double ti43 = 0.5f * yn / c20;
double ti14 = phi6 / c20;
double ti24 = phi9 / c20;
double ti34 = 0.5f * zn / c20;
double ti44 = 0.5f * zn / c20;
/* 27 + 16 + 9 + 6 + 6 + 6 FLOPS */
/* Now, get the variables on the "inside" */
double pi = q[bsz * n + 0];
double ui = q[bsz * n + 1];
double vi = q[bsz * n + 2];
double wi = q[bsz * n + 3];
double un = xn * ui;
un += yn * vi;
un += zn * wi;
/* 5 FLOPS */
/* If ubar is negative, take the reference
condition from outside */
double pr, prp, ur, uru, vr, vrv, wr, wrw;
if(un > 0.f)
{
pr = pi;
prp = 1.f;
ur = ui;
uru = 1.f;
vr = vi;
vrv = 1.f;
wr = wi;
wrw = 1.f;
}
else
{
pr = iv->p;
prp = 0.f;
ur = iv->u;
uru = 0.f;
vr = iv->v;
vrv = 0.f;
wr = iv->w;
wrw = 0.f;
}
/* Set rhs */
double rhs1 = ti11 * pr;
rhs1 += ti12 * ur;
rhs1 += ti13 * vr;
rhs1 += ti14 * wr;
double rhs1p = ti11 * prp;
double rhs1u = ti12 * uru;
double rhs1v = ti13 * vrv;
double rhs1w = ti14 * wrw;
double rhs2 = ti21 * pr;
rhs2 += ti22 * ur;
rhs2 += ti23 * vr;
rhs2 += ti24 * wr;
double rhs2p = ti21 * prp;
double rhs2u = ti22 * uru;
double rhs2v = ti23 * vrv;
double rhs2w = ti24 * wrw;
double rhs3 = ti31 * pi;
rhs3 += ti32 * ui;
rhs3 += ti33 * vi;
rhs3 += ti34 * wi;
double rhs4 = ti41 * iv->p;
rhs4 += ti42 * iv->u;
rhs4 += ti43 * iv->v;
rhs4 += ti44 * iv->w;
/* 12 + 24 FLOPS */
/* Now do matrix multiplication to get values on boundary */
double pb = t13 * rhs3;
pb += t14 * rhs4;
double pbp = t13 * ti31;
double pbu = t13 * ti32;
double pbv = t13 * ti33;
double pbw = t13 * ti34;
double ub = X1 * rhs1;
ub += X2 * rhs2;
ub += t23 * rhs3;
ub += t24 * rhs4;
double ubp = X1 * rhs1p;
ubp += X2 * rhs2p;
ubp += t23 * ti31;
double ubu = X1 * rhs1u;
ubu += X2 * rhs2u;
ubu += t23 * ti32;
double ubv = X1 * rhs1v;
ubv += X2 * rhs2v;
ubv += t23 * ti33;
double ubw = X1 * rhs1w;
ubw += X2 * rhs2w;
ubw += t23 * ti34;
double vb = Y1 * rhs1;
vb += Y2 * rhs2;
vb += t33 * rhs3;
vb += t34 * rhs4;
double vbp = Y1 * rhs1p;
vbp += Y2 * rhs2p;
vbp += t33 * ti31;
double vbu = Y1 * rhs1u;
vbu += Y2 * rhs2u;
vbu += t33 * ti32;
double vbv = Y1 * rhs1v;
vbv += Y2 * rhs2v;
vbv += t33 * ti33;
double vbw = Y1 * rhs1w;
vbw += Y2 * rhs2w;
vbw += t33 * ti34;
double wb = Z1 * rhs1;
wb += Z2 * rhs2;
wb += t43 * rhs3;
wb += t44 * rhs4;
double wbp = Z1 * rhs1p;
wbp += Z2 * rhs2p;
wbp += t43 * ti31;
double wbu = Z1 * rhs1u;
wbu += Z2 * rhs2u;
wbu += t43 * ti32;
double wbv = Z1 * rhs1v;
wbv += Z2 * rhs2v;
wbv += t43 * ti33;
double wbw = Z1 * rhs1w;
wbw += Z2 * rhs2w;
wbw += t43 * ti34;
/* 5 * 15 + 6 + 5 + 2 FLOPS */
double unb = xn * ub;
unb += yn * vb;
unb += zn * wb;
double unbp = xn * ubp;
unbp += yn * vbp;
unbp += zn * wbp;
double unbu = xn * ubu;
unbu += yn * vbu;
unbu += zn * wbu;
double unbv = xn * ubv;
unbv += yn * vbv;
unbv += zn * wbv;
double unbw = xn * ubw;
unbw += yn * vbw;
unbw += zn * wbw;
/* 5 * 5 FLOPS */
/* Now add contribution to lhs */
double v[16];
v[0] = ln * BETA * unbp;
v[1] = ln * BETA * unbu;
v[2] = ln * BETA * unbv;
v[3] = ln * BETA * unbw;
v[4] = ln * (ub * unbp + unb * ubp + xn * pbp);
v[5] = ln * (ub * unbu + unb * ubu + xn * pbu);
v[6] = ln * (ub * unbv + unb * ubv + xn * pbv);
v[7] = ln * (ub * unbw + unb * ubw + xn * pbw);
v[8] = ln * (vb * unbp + unb * vbp + yn * pbp);
v[9] = ln * (vb * unbu + unb * vbu + yn * pbu);
v[10] = ln * (vb * unbv + unb * vbv + yn * pbv);
v[11] = ln * (vb * unbw + unb * vbw + yn * pbw);
v[12] = ln * (wb * unbp + unb * wbp + zn * pbp);
v[13] = ln * (wb * unbu + unb * wbu + zn * pbu);
v[14] = ln * (wb * unbv + unb * wbv + zn * pbv);
v[15] = ln * (wb * unbw + unb * wbw + zn * pbw);
/* 6 * 12 + 8 FLOPS */
MatSetValuesBlocked(A, 1, (const int *) &n, 1, (const int *) &n,
(const double *) v, ADD_VALUES);
}
ierr = MatAssemblyBegin(A, MAT_FINAL_ASSEMBLY);
CHKERRQ(ierr);
ierr = MatAssemblyEnd(A, MAT_FINAL_ASSEMBLY);
CHKERRQ(ierr);
compute_time(&ktime, &fill->t->fill);
return 0;
}
|
mp_func.h | #pragma once
#pragma comment(lib, "k4a.lib")
#include <omp.h>
#include <Windows.h>
#include <k4a/k4a.h>
#include <k4arecord/playback.h>
#include <k4arecord/record.h>
#include <k4arecord/k4arecord_export.h>
#include <k4arecord/types.h>
#include <opencv2/opencv.hpp>
#include <stdio.h>
#include <stdlib.h>
#include <iostream>
#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/imgproc/imgproc.hpp>
#include <time.h>
using namespace std;
using namespace cv;
// "C:\Program Files\Azure Kinect SDK v1.4.1\tools\k4arecorder.exe" -l 10 -c 2160p -d WFOV_UNBINNED -r 15 "C:\Users\anstn\Desktop\output_2160p_3.mkv"
// "C:\Program Files\Azure Kinect SDK v1.4.1\tools\k4aviewer.exe"
int MP_Sensor2Image()
{
// getting the capture
k4a_capture_t capture;
k4a_calibration_t calibration;
k4a_transformation_t transformation;
k4a_image_t transformed_depth_image;
k4a_image_t aligned_point_cloud_depth_image;
const int32_t TIMEOUT_IN_MS = 10000;
clock_t start, end;
double result;
char title_d[100];
char title_c[100];
char title_t[100];
char title_pc[100];
int max_frame = 41;
int frame_count = 0;
uint32_t count = k4a_device_get_installed_count();
if (count == 0)
{
printf("No k4a devices attached!\n");
return 1;
}
// Open the first plugged in Kinect device
k4a_device_t device = NULL;
if (K4A_FAILED(k4a_device_open(K4A_DEVICE_DEFAULT, &device)))
{
printf("Failed to open k4a device!\n");
return 1;
}
// Get the size of the serial number
size_t serial_size = 0;
k4a_device_get_serialnum(device, NULL, &serial_size);
// Allocate memory for the serial, then acquire it
char* serial = (char*)(malloc(serial_size));
k4a_device_get_serialnum(device, serial, &serial_size);
printf("Opened device: %s\n", serial);
free(serial);
// Configure a stream of 4096x3072 BRGA color data at 15 frames per second
k4a_device_configuration_t config = K4A_DEVICE_CONFIG_INIT_DISABLE_ALL;
config.camera_fps = K4A_FRAMES_PER_SECOND_15;
config.color_format = K4A_IMAGE_FORMAT_COLOR_BGRA32;
config.color_resolution = K4A_COLOR_RESOLUTION_1536P;
config.depth_mode = K4A_DEPTH_MODE_WFOV_UNBINNED;
config.synchronized_images_only = true;
if (K4A_RESULT_SUCCEEDED !=
k4a_device_get_calibration(device, config.depth_mode, config.color_resolution, &calibration))
{
cout << "Failed to get calibration" << endl;
return 0;
}
// Start the camera with the given configuration
k4a_device_start_cameras(device, &config);
for (frame_count; frame_count < max_frame; frame_count++)
{
start = clock();
k4a_device_get_capture(device, &capture, TIMEOUT_IN_MS);
k4a_image_t color_image = k4a_capture_get_color_image(capture);
uint8_t* color_buffer = k4a_image_get_buffer(color_image);
int rows = k4a_image_get_height_pixels(color_image);
int cols = k4a_image_get_width_pixels(color_image);
k4a_image_t depth_image = k4a_capture_get_depth_image(capture);
uint8_t* depth_buffer = k4a_image_get_buffer(depth_image);
int depth_rows = k4a_image_get_height_pixels(depth_image);
int depth_cols = k4a_image_get_width_pixels(depth_image);
#pragma omp parallel for
for (int step = 0; step < 3; step++)
{
if (step == 0) //Align Depth & 3D Transform
{
transformation = k4a_transformation_create(&calibration);
if (K4A_RESULT_SUCCEEDED != k4a_image_create(K4A_IMAGE_FORMAT_DEPTH16,
cols,
rows,
cols * (int)sizeof(uint16_t),
&transformed_depth_image))
{
cout << "Failed to create transformed depth image" << endl;
//return false;
}
if (K4A_RESULT_SUCCEEDED != k4a_transformation_depth_image_to_color_camera(transformation, depth_image, transformed_depth_image))
{
cout << "Failed to compute transformed depth image" << endl;
//return false;
}
uint8_t* buffer = k4a_image_get_buffer(transformed_depth_image);
int transdepth_rows = k4a_image_get_height_pixels(transformed_depth_image);
int transdepth_cols = k4a_image_get_width_pixels(transformed_depth_image);
cv::Mat transdepth(transdepth_rows, transdepth_cols, CV_16UC1, (void*)buffer, cv::Mat::AUTO_STEP);
sprintf_s(title_t, "C:\\Users\\anstn\\Desktop\\AzureKinectDK\\output\\trans\\%03d.png", frame_count);
cv::imwrite(title_t, transdepth);
if (K4A_RESULT_SUCCEEDED != k4a_image_create(K4A_IMAGE_FORMAT_CUSTOM, cols, rows, cols * (int)sizeof(int16_t) * 3, &aligned_point_cloud_depth_image))
{
cout << "Failed to create aligned depth point_cloud" << endl;
//return false;
}
if (K4A_RESULT_SUCCEEDED != k4a_transformation_depth_image_to_point_cloud(transformation, transformed_depth_image, K4A_CALIBRATION_TYPE_COLOR, aligned_point_cloud_depth_image))
{
cout << "Failed to compute aligned depth point_cloud" << endl;
//return false;
}
uint8_t* point_cloud_buffer = k4a_image_get_buffer(aligned_point_cloud_depth_image);
cv::Mat point_cloud(rows, cols, CV_16UC3, (void*)point_cloud_buffer, cv::Mat::AUTO_STEP);
sprintf_s(title_pc, "C:\\Users\\anstn\\Desktop\\AzureKinectDK\\output\\point\\%03d.png", frame_count);
cv::imwrite(title_pc, point_cloud);
k4a_image_release(transformed_depth_image);
k4a_image_release(aligned_point_cloud_depth_image);
}
else if (step == 1) //Color
{
cv::Mat color(rows, cols, CV_8UC4, (void*)color_buffer, cv::Mat::AUTO_STEP);
sprintf_s(title_c, "C:\\Users\\anstn\\Desktop\\AzureKinectDK\\output\\color\\%03d.png", frame_count);
cv::imwrite(title_c, color);
k4a_image_release(color_image);
}
else //Depth
{
cv::Mat depth(depth_rows, depth_cols, CV_16UC1, (void*)depth_buffer, cv::Mat::AUTO_STEP);
sprintf_s(title_d, "C:\\Users\\anstn\\Desktop\\AzureKinectDK\\output\\depth\\%03d.png", frame_count);
cv::imwrite(title_d, depth);
k4a_image_release(depth_image);
}
}
end = clock();
result = (double)(end - start);
cout << "Total Processing Time on Multi Processing : " << ((result) / CLOCKS_PER_SEC) << " seconds" << endl;
}
k4a_device_stop_cameras(device);
k4a_device_close(device);
return 0;
}
|
bias_ref.c | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* License); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* AS IS BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
/*
* Copyright (c) 2021, OPEN AI LAB
* Author: chh@openailab.com
*/
#include "graph/tensor.h"
#include "graph/node.h"
#include "graph/graph.h"
#include "utility/sys_port.h"
#include "utility/log.h"
#include "device/cpu/cpu_node.h"
#include "device/cpu/cpu_graph.h"
#include "device/cpu/cpu_module.h"
#include <math.h>
int ref_bias_fp32(struct tensor* input_tensor, struct tensor* output_tensor, struct tensor* bias_tensor,
int num_thread)
{
int channels = input_tensor->dims[1];
int h = input_tensor->dims[2];
int w = input_tensor->dims[3];
int size = h * w;
float* in_data = input_tensor->data;
float* bias = bias_tensor->data;
float* out_data = output_tensor->data;
#pragma omp parallel for num_threads(num_thread)
for (int c = 0; c < channels; c++)
{
float* out_ptr = out_data + c * size;
float* in_ptr = in_data + c * size;
for (int i = 0; i < size; i++)
{
out_ptr[i] = in_ptr[i] + bias[c];
}
}
return 0;
}
static int init_node(struct node_ops* node_ops, struct exec_node* exec_node, struct exec_graph* exec_graph)
{
return 0;
}
static int release_node(struct node_ops* node_ops, struct exec_node* exec_node, struct exec_graph* exec_graph)
{
return 0;
}
static int prerun(struct node_ops* node_ops, struct exec_node* exec_node, struct exec_graph* exec_graph)
{
return 0;
}
static int run(struct node_ops* node_ops, struct exec_node* exec_node, struct exec_graph* exec_graph)
{
struct node* ir_node = exec_node->ir_node;
struct graph* ir_graph = ir_node->graph;
struct tensor* input_tensor;
struct tensor* bias_tensor;
struct tensor* output_tensor;
int layout = ir_graph->graph_layout;
input_tensor = get_ir_graph_tensor(ir_graph, ir_node->input_tensors[0]);
bias_tensor = get_ir_graph_tensor(ir_graph, ir_node->input_tensors[1]);
output_tensor = get_ir_graph_tensor(ir_graph, ir_node->output_tensors[0]);
int ret = -1;
if (input_tensor->data_type == TENGINE_DT_FP32)
ret = ref_bias_fp32(input_tensor, output_tensor, bias_tensor, exec_graph->num_thread);
else
TLOG_ERR("Input data type %d not to be supported.\n", input_tensor->data_type);
return ret;
}
static int score(struct node_ops* node_ops, struct exec_graph* exec_graph, struct node* exec_node)
{
return OPS_SCORE_CANDO;
}
static struct node_ops hcl_node_ops = {.prerun = prerun,
.run = run,
.reshape = NULL,
.postrun = NULL,
.init_node = init_node,
.release_node = release_node,
.score = score};
int register_bias_ref_op()
{
return register_builtin_node_ops(OP_BIAS, &hcl_node_ops);
}
int unregister_bias_ref_op()
{
return unregister_builtin_node_ops(OP_BIAS, &hcl_node_ops);
}
|
nevpt_contract.c | /* Copyright 2014-2018 The PySCF Developers. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*
* Author: Qiming Sun <osirpt.sun@gmail.com>
*/
#include <stdlib.h>
#include <string.h>
//#include <omp.h>
#include "config.h"
#include "vhf/fblas.h"
#include "fci.h"
#define MIN(X,Y) ((X)<(Y)?(X):(Y))
#define BLK 48
#define BUFBASE 96
double FCI_t1ci_sf(double *ci0, double *t1, int bcount,
int stra_id, int strb_id,
int norb, int na, int nb, int nlinka, int nlinkb,
_LinkT *clink_indexa, _LinkT *clink_indexb);
double FCI_t2ci_sf(double *ci0, double *t1, int bcount,
int stra_id, int strb_id,
int norb, int na, int nb, int nlinka, int nlinkb,
_LinkT *clink_indexa, _LinkT *clink_indexb);
static void tril2pdm_particle_symm(double *rdm2, double *tbra, double *tket,
int bcount, int ncre, int norb)
{
const char TRANS_N = 'N';
const char TRANS_T = 'T';
const double D1 = 1;
int nnorb = norb * norb;
int nncre = norb * ncre;
dgemm_(&TRANS_N, &TRANS_T, &nnorb, &nncre, &bcount,
&D1, tket, &nnorb, tbra, &nnorb, &D1, rdm2, &nnorb);
}
// (df|ce) E^d_f E^a_e|0> = t_ac
void NEVPTkern_dfec_dfae(double *gt2, double *eri, double *t2ket,
int bcount, int norb, int na, int nb)
{
const char TRANS_N = 'N';
const char TRANS_T = 'T';
const double D0 = 0;
const double D1 = 1;
const int nnorb = norb * norb;
const int n4 = nnorb * nnorb;
const int n3 = nnorb * norb;
int i, m, n;
size_t k;
double *cp0, *cp1;
double *t2t; // E^d_fE^a_e with ae transposed
#pragma omp parallel default(none) \
shared(gt2, eri, t2ket, bcount, norb, na, nb) \
private(cp0, cp1, t2t, m, n, i, k)
{
t2t = malloc(sizeof(double) * n4);
#pragma omp for schedule(dynamic, 4)
for (k = 0; k < bcount; k++) {
for (i = 0; i < nnorb; i++) {
cp0 = t2ket + k * n4 + i * nnorb;
cp1 = t2t + i * nnorb;
for (m = 0; m < norb; m++) {
for (n = 0; n < norb; n++) {
cp1[n*norb+m] = cp0[m*norb+n];
}
}
}
dgemm_(&TRANS_N, &TRANS_T, &norb, &norb, &n3,
&D1, eri, &norb, t2t, &norb,
&D0, gt2+nnorb*k, &norb);
}
free(t2t);
}
}
// (df|ea) E^e_c E^d_f|0> = t_ac
void NEVPTkern_aedf_ecdf(double *gt2, double *eri, double *t2ket,
int bcount, int norb, int na, int nb)
{
const char TRANS_N = 'N';
const char TRANS_T = 'T';
const double D0 = 0;
const double D1 = 1;
const int nnorb = norb * norb;
const int n4 = nnorb * nnorb;
const int n3 = nnorb * norb;
int i, m, n;
size_t k;
double *cp0, *cp1;
double *t2t;
#pragma omp parallel default(none) \
shared(gt2, eri, t2ket, bcount, norb, na, nb) \
private(cp0, cp1, t2t, m, n, i, k)
{
t2t = malloc(sizeof(double) * n4);
#pragma omp for schedule(dynamic, 4)
for (k = 0; k < bcount; k++) {
for (m = 0; m < norb; m++) {
for (n = 0; n < norb; n++) {
cp0 = t2ket + k * n4 + (m*norb+n) * nnorb;
cp1 = t2t + (n*norb+m) * nnorb;
for (i = 0; i < nnorb; i++) {
cp1[i] = cp0[i];
}
}
}
dgemm_(&TRANS_T, &TRANS_N, &norb, &norb, &n3,
&D1, t2t, &n3, eri, &n3,
&D0, gt2+nnorb*k, &norb);
}
free(t2t);
}
}
// (df|ce) E^a_e E^d_f|0> = t_ac
void NEVPTkern_cedf_aedf(double *gt2, double *eri, double *t2ket,
int bcount, int norb, int na, int nb)
{
const char TRANS_N = 'N';
const char TRANS_T = 'T';
const double D0 = 0;
const double D1 = 1;
const int nnorb = norb * norb;
const int n4 = nnorb * nnorb;
const int n3 = nnorb * norb;
size_t k;
int blen;
#pragma omp parallel default(none) \
shared(gt2, eri, t2ket, bcount, norb, na, nb) \
private(k, blen)
#pragma omp for schedule(dynamic, 1)
for (k = 0; k < bcount; k+=8) {
blen = MIN(bcount-k, 8) * norb;
dgemm_(&TRANS_T, &TRANS_N, &norb, &blen, &n3,
&D1, eri, &n3, t2ket+n4*k, &n3,
&D0, gt2+nnorb*k, &norb);
}
}
// (df|ea) E^d_f E^e_c|0> = t_ac
void NEVPTkern_dfea_dfec(double *gt2, double *eri, double *t2ket,
int bcount, int norb, int na, int nb)
{
const char TRANS_N = 'N';
const char TRANS_T = 'T';
const double D0 = 0;
const double D1 = 1;
const int nnorb = norb * norb;
const int n4 = nnorb * nnorb;
const int n3 = nnorb * norb;
size_t k;
#pragma omp parallel default(none) \
shared(gt2, eri, t2ket, bcount, norb, na, nb) \
private(k)
#pragma omp for schedule(dynamic, 4)
for (k = 0; k < bcount; k++) {
dgemm_(&TRANS_N, &TRANS_T, &norb, &norb, &n3,
&D1, t2ket+n4*k, &norb, eri, &norb,
&D0, gt2+nnorb*k, &norb);
}
}
// TODO: NEVPTkern_spin0 stra_id >= strb_id as FCI4pdm_kern_spin0
void NEVPTkern_sf(void (*contract_kernel)(),
double *rdm2, double *rdm3, double *eri, double *ci0,
int bcount, int stra_id, int strb_id,
int norb, int na, int nb, int nlinka, int nlinkb,
_LinkT *clink_indexa, _LinkT *clink_indexb)
{
const int nnorb = norb * norb;
const int n4 = nnorb * nnorb;
const int n3 = nnorb * norb;
int i, j, k, l, ij;
size_t n;
double *t1ket = malloc(sizeof(double) * nnorb * bcount);
double *t2ket = malloc(sizeof(double) * n4 * bcount);
double *gt2 = malloc(sizeof(double) * nnorb * bcount);
double *tbra, *pbra, *pt2;
// t2[:,i,j,k,l] = E^i_j E^k_l|ket>
FCI_t1ci_sf(ci0, t1ket, bcount, stra_id, strb_id,
norb, na, nb, nlinka, nlinkb, clink_indexa, clink_indexb);
FCI_t2ci_sf(ci0, t2ket, bcount, stra_id, strb_id,
norb, na, nb, nlinka, nlinkb, clink_indexa, clink_indexb);
(*contract_kernel)(gt2, eri, t2ket, bcount, norb, na, nb);
#pragma omp parallel default(none) \
shared(rdm2, rdm3, t1ket, t2ket, gt2, norb, bcount), \
private(ij, i, j, k, l, n, tbra, pbra, pt2)
{
tbra = malloc(sizeof(double) * nnorb * bcount);
#pragma omp for schedule(dynamic, 4)
for (ij = 0; ij < nnorb; ij++) { // loop ij for (<ket| E^j_i E^l_k)
i = ij / norb;
j = ij - i * norb;
for (n = 0; n < bcount; n++) {
for (k = 0; k <= j; k++) {
pbra = tbra + n * nnorb + k*norb;
pt2 = t2ket + n * n4 + k*nnorb + ij;
for (l = 0; l < norb; l++) {
pbra[l] = pt2[l*n3];
}
}
}
tril2pdm_particle_symm(rdm3+(j*norb+i)*n4, tbra, gt2,
bcount, j+1, norb);
}
free(tbra);
}
// reordering of rdm2 is needed: rdm2.transpose(1,0,2,3)
const char TRANS_N = 'N';
const char TRANS_T = 'T';
const double D1 = 1;
dgemm_(&TRANS_N, &TRANS_T, &nnorb, &nnorb, &bcount,
&D1, gt2, &nnorb, t1ket, &nnorb,
&D1, rdm2, &nnorb);
free(gt2);
free(t1ket);
free(t2ket);
}
void NEVPTcontract(void (*kernel)(),
double *rdm2, double *rdm3, double *eri, double *ci0,
int norb, int na, int nb, int nlinka, int nlinkb,
int *link_indexa, int *link_indexb)
{
const size_t nnorb = norb * norb;
const size_t n4 = nnorb * nnorb;
int i, j, k, ib, strk, bcount;
double *pdm2 = malloc(sizeof(double) * n4);
double *cp1, *cp0;
_LinkT *clinka = malloc(sizeof(_LinkT) * nlinka * na);
_LinkT *clinkb = malloc(sizeof(_LinkT) * nlinkb * nb);
FCIcompress_link(clinka, link_indexa, norb, na, nlinka);
FCIcompress_link(clinkb, link_indexb, norb, nb, nlinkb);
memset(pdm2, 0, sizeof(double) * n4);
memset(rdm3, 0, sizeof(double) * n4 * nnorb);
for (strk = 0; strk < na; strk++) {
for (ib = 0; ib < nb; ib += BUFBASE) {
bcount = MIN(BUFBASE, nb-ib);
NEVPTkern_sf(kernel, pdm2, rdm3,
eri, ci0, bcount, strk, ib,
norb, na, nb, nlinka, nlinkb, clinka, clinkb);
}
}
free(clinka);
free(clinkb);
for (i = 0; i < norb; i++) {
for (j = 0; j < norb; j++) {
cp1 = rdm2 + (i*norb+j) * nnorb;
cp0 = pdm2 + (j*norb+i) * nnorb;
for (k = 0; k < nnorb; k++) {
cp1[k] = cp0[k];
}
} }
free(pdm2);
}
|
3d25pt.c | /*
* Order-2, 3D 25 point stencil
* Adapted from PLUTO and Pochoir test bench
*
* Tareq Malas
*/
#include <stdio.h>
#include <stdlib.h>
#include <sys/time.h>
#ifdef LIKWID_PERFMON
#include <likwid.h>
#endif
#include "print_utils.h"
#define TESTS 2
#define MAX(a,b) ((a) > (b) ? a : b)
#define MIN(a,b) ((a) < (b) ? a : b)
#ifndef min
#define min(x,y) ((x) < (y)? (x) : (y))
#endif
/* Subtract the `struct timeval' values X and Y,
* storing the result in RESULT.
*
* Return 1 if the difference is negative, otherwise 0.
*/
int timeval_subtract(struct timeval *result, struct timeval *x, struct timeval *y)
{
/* Perform the carry for the later subtraction by updating y. */
if (x->tv_usec < y->tv_usec)
{
int nsec = (y->tv_usec - x->tv_usec) / 1000000 + 1;
y->tv_usec -= 1000000 * nsec;
y->tv_sec += nsec;
}
if (x->tv_usec - y->tv_usec > 1000000)
{
int nsec = (x->tv_usec - y->tv_usec) / 1000000;
y->tv_usec += 1000000 * nsec;
y->tv_sec -= nsec;
}
/* Compute the time remaining to wait.
* tv_usec is certainly positive.
*/
result->tv_sec = x->tv_sec - y->tv_sec;
result->tv_usec = x->tv_usec - y->tv_usec;
/* Return 1 if result is negative. */
return x->tv_sec < y->tv_sec;
}
int main(int argc, char *argv[])
{
int t, i, j, k, test;
int Nx, Ny, Nz, Nt;
if (argc > 3) {
Nx = atoi(argv[1])+8;
Ny = atoi(argv[2])+8;
Nz = atoi(argv[3])+8;
}
if (argc > 4)
Nt = atoi(argv[4]);
double ****A = (double ****) malloc(sizeof(double***)*2);
double ***roc2 = (double ***) malloc(sizeof(double**));
A[0] = (double ***) malloc(sizeof(double**)*Nz);
A[1] = (double ***) malloc(sizeof(double**)*Nz);
roc2 = (double ***) malloc(sizeof(double**)*Nz);
for(i=0; i<Nz; i++){
A[0][i] = (double**) malloc(sizeof(double*)*Ny);
A[1][i] = (double**) malloc(sizeof(double*)*Ny);
roc2[i] = (double**) malloc(sizeof(double*)*Ny);
for(j=0;j<Ny;j++){
A[0][i][j] = (double*) malloc(sizeof(double)*Nx);
A[1][i][j] = (double*) malloc(sizeof(double)*Nx);
roc2[i][j] = (double*) malloc(sizeof(double)*Nx);
}
}
// tile size information, including extra element to decide the list length
int *tile_size = (int*) malloc(sizeof(int));
tile_size[0] = -1;
// The list is modified here before source-to-source transformations
tile_size = (int*) realloc((void *)tile_size, sizeof(int)*5);
tile_size[0] = 24;
tile_size[1] = 24;
tile_size[2] = 16;
tile_size[3] = 2048;
tile_size[4] = -1;
// for timekeeping
int ts_return = -1;
struct timeval start, end, result;
double tdiff = 0.0, min_tdiff=1.e100;
const int BASE = 1024;
// initialize variables
//
srand(42);
for (i = 1; i < Nz; i++) {
for (j = 1; j < Ny; j++) {
for (k = 1; k < Nx; k++) {
A[0][i][j][k] = 1.0 * (rand() % BASE);
roc2[i][j][k] = 2.0 * (rand() % BASE);
}
}
}
#ifdef LIKWID_PERFMON
LIKWID_MARKER_INIT;
#pragma omp parallel
{
LIKWID_MARKER_THREADINIT;
#pragma omp barrier
LIKWID_MARKER_START("calc");
}
#endif
int num_threads = 1;
#if defined(_OPENMP)
num_threads = omp_get_max_threads();
#endif
const double coef0 = -0.28472;
const double coef1 = 0.16000;
const double coef2 = -0.02000;
const double coef3 = 0.00254;
const double coef4 = -0.00018;
for(test=0; test<TESTS; test++){
gettimeofday(&start, 0);
// serial execution - Addition: 6 && Multiplication: 2
#pragma scop
for (t = 0; t < Nt; t++) {
for (i = 4; i < Nz-4; i++) {
for (j = 4; j < Ny-4; j++) {
for (k = 4; k < Nx-4; k++) {
A[(t+1)%2][i][j][k] = 2.0*A[t%2][i][j][k] - A[(t+1)%2][i][j][k] + roc2[i][j][k]*(
coef0* A[t%2][i ][j ][k ] +
coef1*(A[t%2][i-1][j ][k ] + A[t%2][i+1][j ][k ] +
A[t%2][i ][j-1][k ] + A[t%2][i ][j+1][k ] +
A[t%2][i ][j ][k-1] + A[t%2][i ][j ][k+1]) +
coef2*(A[t%2][i-2][j ][k ] + A[t%2][i+2][j ][k ] +
A[t%2][i ][j-2][k ] + A[t%2][i ][j+2][k ] +
A[t%2][i ][j ][k-2] + A[t%2][i ][j ][k+2]) +
coef3*(A[t%2][i-3][j ][k ] + A[t%2][i+3][j ][k ] +
A[t%2][i ][j-3][k ] + A[t%2][i ][j+3][k ] +
A[t%2][i ][j ][k-3] + A[t%2][i ][j ][k+3]) +
coef4*(A[t%2][i-4][j ][k ] + A[t%2][i+4][j ][k ] +
A[t%2][i ][j-4][k ] + A[t%2][i ][j+4][k ] +
A[t%2][i ][j ][k-4] + A[t%2][i ][j ][k+4]) );
}
}
}
}
#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(4, "constant")
#ifdef LIKWID_PERFMON
#pragma omp parallel
{
LIKWID_MARKER_STOP("calc");
}
LIKWID_MARKER_CLOSE;
#endif
// Free allocated arrays
for(i=0; i<Nz; i++){
for(j=0;j<Ny;j++){
free(A[0][i][j]);
free(A[1][i][j]);
free(roc2[i][j]);
}
free(A[0][i]);
free(A[1][i]);
free(roc2[i]);
}
free(A[0]);
free(A[1]);
free(roc2);
return 0;
}
|
ideal_gas_kernel_c.c | /*Crown Copyright 2012 AWE.
*
* This file is part of CloverLeaf.
*
* CloverLeaf 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.
*
* CloverLeaf 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
* CloverLeaf. If not, see http://www.gnu.org/licenses/. */
/**
* @brief C ideal gas kernel.
* @author Wayne Gaudin
* @details Calculates the pressure and sound speed for the mesh chunk using
* the ideal gas equation of state, with a fixed gamma of 1.4.
*/
#include <stdio.h>
#include <stdlib.h>
#include "ftocmacros.h"
#include <math.h>
void ideal_gas_kernel_c_(int *xmin,int *xmax,int *ymin,int *ymax,
double *density,
double *energy,
double *pressure,
double *soundspeed)
{
int x_min=*xmin;
int x_max=*xmax;
int y_min=*ymin;
int y_max=*ymax;
int j,k;
double sound_speed_squared,v,pressurebyenergy,pressurebyvolume;
#pragma omp parallel private(j)
{
#pragma omp for private(v,pressurebyenergy,pressurebyvolume,sound_speed_squared)
for (k=y_min;k<=y_max;k++) {
#pragma ivdep
for (j=x_min;j<=x_max;j++) {
v=1.0/density[FTNREF2D(j ,k ,x_max+4,x_min-2,y_min-2)];
pressure[FTNREF2D(j ,k ,x_max+4,x_min-2,y_min-2)]=(1.4-1.0)*density[FTNREF2D(j ,k ,x_max+4,x_min-2,y_min-2)]
*energy[FTNREF2D(j ,k ,x_max+4,x_min-2,y_min-2)];
pressurebyenergy=(1.4-1.0)*density[FTNREF2D(j ,k ,x_max+4,x_min-2,y_min-2)];
pressurebyvolume=-density[FTNREF2D(j ,k ,x_max+4,x_min-2,y_min-2)]*pressure[FTNREF2D(j ,k ,x_max+4,x_min-2,y_min-2)];
sound_speed_squared=v*v*(pressure[FTNREF2D(j ,k ,x_max+4,x_min-2,y_min-2)]*pressurebyenergy-pressurebyvolume);
soundspeed[FTNREF2D(j ,k ,x_max+4,x_min-2,y_min-2)]=sqrt(sound_speed_squared);
}
}
}
}
|
GB_binop__pair_fp64.c |
//------------------------------------------------------------------------------
// GB_binop: hard-coded functions for each built-in binary operator
//------------------------------------------------------------------------------
// SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2021, All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
//------------------------------------------------------------------------------
// If this file is in the Generated2/ folder, do not edit it
// (it is auto-generated from Generator/*).
#include "GB.h"
#ifndef GBCOMPACT
#include "GB_emult.h"
#include "GB_control.h"
#include "GB_ek_slice.h"
#include "GB_dense.h"
#include "GB_atomics.h"
#include "GB_bitmap_assign_methods.h"
#include "GB_binop__include.h"
// C=binop(A,B) is defined by the following types and operators:
// A+B function (eWiseAdd): GB (_AaddB__pair_fp64)
// A.*B function (eWiseMult): GB ((none))
// A.*B function (eWiseMult): GB ((none))
// A.*B function (eWiseMult): GB ((none))
// A.*B function (eWiseMult): GB ((none))
// A*D function (colscale): GB ((none))
// D*A function (rowscale): GB ((none))
// C+=B function (dense accum): GB (_Cdense_accumB__pair_fp64)
// C+=b function (dense accum): GB (_Cdense_accumb__pair_fp64)
// C+=A+B function (dense ewise3): GB ((none))
// C=A+B function (dense ewise3): GB (_Cdense_ewise3_noaccum__pair_fp64)
// C=scalar+B GB ((none))
// C=scalar+B' GB ((none))
// C=A+scalar GB ((none))
// C=A'+scalar GB ((none))
// C type: double
// A type: double
// A pattern? 1
// B type: double
// B pattern? 1
// BinaryOp: cij = 1
#define GB_ATYPE \
double
#define GB_BTYPE \
double
#define GB_CTYPE \
double
// true if the types of A and B are identical
#define GB_ATYPE_IS_BTYPE \
1
// true if the types of C and A are identical
#define GB_CTYPE_IS_ATYPE \
1
// true if the types of C and B are identical
#define GB_CTYPE_IS_BTYPE \
1
// aij = Ax [pA]
#define GB_GETA(aij,Ax,pA,A_iso) \
;
// true if values of A are not used
#define GB_A_IS_PATTERN \
1 \
// bij = Bx [pB]
#define GB_GETB(bij,Bx,pB,B_iso) \
;
// true if values of B are not used
#define GB_B_IS_PATTERN \
1 \
// declare scalar of the same type as C
#define GB_CTYPE_SCALAR(t) \
double t
// cij = Ax [pA]
#define GB_COPY_A_TO_C(cij,Ax,pA,A_iso) \
cij = GBX (Ax, pA, A_iso)
// cij = Bx [pB]
#define GB_COPY_B_TO_C(cij,Bx,pB,B_iso) \
cij = GBX (Bx, pB, B_iso)
#define GB_CX(p) Cx [p]
// binary operator
#define GB_BINOP(z,x,y,i,j) \
z = 1 ;
// 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_PAIR || GxB_NO_FP64 || GxB_NO_PAIR_FP64)
//------------------------------------------------------------------------------
// C += A+B, all 3 matrices dense
//------------------------------------------------------------------------------
#if 0
// The op must be MIN, MAX, PLUS, MINUS, RMINUS, TIMES, DIV, or RDIV.
void GB ((none))
(
GrB_Matrix C,
const GrB_Matrix A,
const GrB_Matrix B,
const int nthreads
)
{
#include "GB_dense_ewise3_accum_template.c"
}
#endif
//------------------------------------------------------------------------------
// C = A+B, all 3 matrices dense
//------------------------------------------------------------------------------
void GB (_Cdense_ewise3_noaccum__pair_fp64)
(
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__pair_fp64)
(
GrB_Matrix C,
const GrB_Matrix B,
const int64_t *B_ek_slicing, const int B_ntasks, const int B_nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
{
#include "GB_dense_subassign_23_template.c"
}
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// C += b, accumulate a scalar into a dense matrix
//------------------------------------------------------------------------------
GrB_Info GB (_Cdense_accumb__pair_fp64)
(
GrB_Matrix C,
const GB_void *p_bwork,
const int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
{
// get the scalar b for C += b, of type double
double bwork = (*((double *) p_bwork)) ;
#include "GB_dense_subassign_22_template.c"
return (GrB_SUCCESS) ;
}
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// C = A*D, column scale with diagonal D matrix
//------------------------------------------------------------------------------
#if 0
GrB_Info GB ((none))
(
GrB_Matrix C,
const GrB_Matrix A,
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
double *restrict Cx = (double *) C->x ;
#include "GB_AxB_colscale_template.c"
return (GrB_SUCCESS) ;
#endif
}
#endif
//------------------------------------------------------------------------------
// C = D*B, row scale with diagonal D matrix
//------------------------------------------------------------------------------
#if 0
GrB_Info GB ((none))
(
GrB_Matrix C,
const GrB_Matrix D,
const GrB_Matrix B,
int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
double *restrict Cx = (double *) C->x ;
#include "GB_AxB_rowscale_template.c"
return (GrB_SUCCESS) ;
#endif
}
#endif
//------------------------------------------------------------------------------
// eWiseAdd: C=A+B, C<M>=A+B, C<!M>=A+B
//------------------------------------------------------------------------------
GrB_Info GB (_AaddB__pair_fp64)
(
GrB_Matrix C,
const int C_sparsity,
const GrB_Matrix M,
const bool Mask_struct,
const bool Mask_comp,
const GrB_Matrix A,
const GrB_Matrix B,
const bool 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) ;
double alpha_scalar ;
double beta_scalar ;
if (is_eWiseUnion)
{
alpha_scalar = (*((double *) alpha_scalar_in)) ;
beta_scalar = (*((double *) 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
//------------------------------------------------------------------------------
#if 0
GrB_Info GB ((none))
(
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
}
#endif
//------------------------------------------------------------------------------
// eWiseMult: C<#> = A.*B when A is sparse/hyper and B is bitmap/full
//------------------------------------------------------------------------------
#if 0
GrB_Info GB ((none))
(
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
}
#endif
//------------------------------------------------------------------------------
// eWiseMult: C<M> = A.*B, M sparse/hyper, A and B bitmap/full
//------------------------------------------------------------------------------
#if 0
GrB_Info GB ((none))
(
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
}
#endif
//------------------------------------------------------------------------------
// eWiseMult: C=A.*B, C<M>=A.*B, C<!M>=A.*B where C is bitmap
//------------------------------------------------------------------------------
#if 0
GrB_Info GB ((none))
(
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
}
#endif
//------------------------------------------------------------------------------
// Cx = op (x,Bx): apply a binary operator to a matrix with scalar bind1st
//------------------------------------------------------------------------------
#if 0
GrB_Info GB ((none))
(
GB_void *Cx_output, // Cx and Bx may be aliased
const GB_void *x_input,
const GB_void *Bx_input,
const int8_t *restrict Bb,
int64_t bnz,
int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
double *Cx = (double *) Cx_output ;
double x = (*((double *) x_input)) ;
double *Bx = (double *) Bx_input ;
int64_t p ;
#pragma omp parallel for num_threads(nthreads) schedule(static)
for (p = 0 ; p < bnz ; p++)
{
if (!GBB (Bb, p)) continue ;
; ;
Cx [p] = 1 ;
}
return (GrB_SUCCESS) ;
#endif
}
#endif
//------------------------------------------------------------------------------
// Cx = op (Ax,y): apply a binary operator to a matrix with scalar bind2nd
//------------------------------------------------------------------------------
#if 0
GrB_Info GB ((none))
(
GB_void *Cx_output, // Cx and Ax may be aliased
const GB_void *Ax_input,
const GB_void *y_input,
const int8_t *restrict Ab,
int64_t anz,
int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
int64_t p ;
double *Cx = (double *) Cx_output ;
double *Ax = (double *) Ax_input ;
double y = (*((double *) y_input)) ;
#pragma omp parallel for num_threads(nthreads) schedule(static)
for (p = 0 ; p < anz ; p++)
{
if (!GBB (Ab, p)) continue ;
; ;
Cx [p] = 1 ;
}
return (GrB_SUCCESS) ;
#endif
}
#endif
//------------------------------------------------------------------------------
// C = op (x, A'): transpose and apply a binary operator
//------------------------------------------------------------------------------
#if 0
// cij = op (x, aij), no typecasting (in spite of the macro name)
#undef GB_CAST_OP
#define GB_CAST_OP(pC,pA) \
{ \
; ; \
Cx [pC] = 1 ; \
}
GrB_Info GB ((none))
(
GrB_Matrix C,
const GB_void *x_input,
const GrB_Matrix A,
int64_t *restrict *Workspaces,
const int64_t *restrict A_slice,
int nworkspaces,
int nthreads
)
{
// GB_unop_transpose.c uses GB_ATYPE, but A is
// the 2nd input to binary operator z=f(x,y).
#undef GB_ATYPE
#define GB_ATYPE \
double
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
double x = (*((const double *) x_input)) ;
#include "GB_unop_transpose.c"
return (GrB_SUCCESS) ;
#endif
#undef GB_ATYPE
#define GB_ATYPE \
double
}
#endif
//------------------------------------------------------------------------------
// C = op (A', y): transpose and apply a binary operator
//------------------------------------------------------------------------------
#if 0
// cij = op (aij, y), no typecasting (in spite of the macro name)
#undef GB_CAST_OP
#define GB_CAST_OP(pC,pA) \
{ \
; ; \
Cx [pC] = 1 ; \
}
GrB_Info GB ((none))
(
GrB_Matrix C,
const GrB_Matrix A,
const GB_void *y_input,
int64_t *restrict *Workspaces,
const int64_t *restrict A_slice,
int nworkspaces,
int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
double y = (*((const double *) y_input)) ;
#include "GB_unop_transpose.c"
return (GrB_SUCCESS) ;
#endif
}
#endif
#endif
|
GB_unop__cimag_fp32_fc32.c | //------------------------------------------------------------------------------
// GB_unop: hard-coded functions for each built-in unary operator
//------------------------------------------------------------------------------
// SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2021, All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
//------------------------------------------------------------------------------
// If this file is in the Generated/ folder, do not edit it (auto-generated).
#include "GB.h"
#ifndef GBCOMPACT
#include "GB_control.h"
#include "GB_atomics.h"
#include "GB_unop__include.h"
// C=unop(A) is defined by the following types and operators:
// op(A) function: GB (_unop_apply__cimag_fp32_fc32)
// op(A') function: GB (_unop_tran__cimag_fp32_fc32)
// C type: float
// A type: GxB_FC32_t
// cast: GxB_FC32_t cij = (aij)
// unaryop: cij = cimagf (aij)
#define GB_ATYPE \
GxB_FC32_t
#define GB_CTYPE \
float
// aij = Ax [pA]
#define GB_GETA(aij,Ax,pA) \
GxB_FC32_t aij = Ax [pA]
#define GB_CX(p) Cx [p]
// unary operator
#define GB_OP(z, x) \
z = cimagf (x) ;
// casting
#define GB_CAST(z, aij) \
GxB_FC32_t z = (aij) ;
// cij = op (aij)
#define GB_CAST_OP(pC,pA) \
{ \
/* aij = Ax [pA] */ \
GxB_FC32_t aij = Ax [pA] ; \
/* Cx [pC] = op (cast (aij)) */ \
GxB_FC32_t z = (aij) ; \
Cx [pC] = cimagf (z) ; \
}
// true if operator is the identity op with no typecasting
#define GB_OP_IS_IDENTITY_WITH_NO_TYPECAST \
0
// disable this operator and use the generic case if these conditions hold
#define GB_DISABLE \
(GxB_NO_CIMAG || GxB_NO_FP32 || GxB_NO_FC32)
//------------------------------------------------------------------------------
// Cx = op (cast (Ax)): apply a unary operator
//------------------------------------------------------------------------------
GrB_Info GB (_unop_apply__cimag_fp32_fc32)
(
float *Cx, // Cx and Ax may be aliased
const GxB_FC32_t *Ax,
const int8_t *restrict Ab, // A->b if A is bitmap
int64_t anz,
int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
int64_t p ;
// TODO: if OP is ONE and uniform-valued matrices are exploited, then
// do this in O(1) time
if (Ab == NULL)
{
#if ( GB_OP_IS_IDENTITY_WITH_NO_TYPECAST )
GB_memcpy (Cx, Ax, anz * sizeof (GxB_FC32_t), nthreads) ;
#else
#pragma omp parallel for num_threads(nthreads) schedule(static)
for (p = 0 ; p < anz ; p++)
{
GxB_FC32_t aij = Ax [p] ;
GxB_FC32_t z = (aij) ;
Cx [p] = cimagf (z) ;
}
#endif
}
else
{
// bitmap case, no transpose; A->b already memcpy'd into C->b
#pragma omp parallel for num_threads(nthreads) schedule(static)
for (p = 0 ; p < anz ; p++)
{
if (!Ab [p]) continue ;
GxB_FC32_t aij = Ax [p] ;
GxB_FC32_t z = (aij) ;
Cx [p] = cimagf (z) ;
}
}
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// C = op (cast (A')): transpose, typecast, and apply a unary operator
//------------------------------------------------------------------------------
GrB_Info GB (_unop_tran__cimag_fp32_fc32)
(
GrB_Matrix C,
const GrB_Matrix A,
int64_t *restrict *Workspaces,
const int64_t *restrict A_slice,
int nworkspaces,
int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
#include "GB_unop_transpose.c"
return (GrB_SUCCESS) ;
#endif
}
#endif
|
wshfl.c | /* Copyright 2018-2019. Massachusetts Institute of Technology.
* All rights reserved. Use of this source code is governed by
* a BSD-style license which can be found in the LICENSE file.
*
* Authors:
* 2018-2019 Siddharth Iyer <ssi@mit.edu>
*
* Tamir J, Uecker M, Chen W, Lai P, Alley MT, Vasanawala SS, Lustig M.
* T2 shuffling: Sharp, multicontrast, volumetric fast spin‐echo imaging.
* Magnetic resonance in medicine. 2017 Jan 1;77(1):180-95.
*
* B Bilgic, BA Gagoski, SF Cauley, AP Fan, JR Polimeni, PE Grant,
* LL Wald, and K Setsompop, Wave-CAIPI for highly accelerated 3D
* imaging. Magn Reson Med (2014) doi: 10.1002/mrm.25347
*
* Iyer S, Bilgic B, Setsompop K.
* Faster T2 shuffling with Wave.
* Presented in the session: "Signal Encoding and Decoding" at ISMRM 2018.
* https://www.ismrm.org/18/program_files/O67.htm
*/
#include <stdbool.h>
#include <complex.h>
#include <math.h>
#ifdef _OPENMP
#include <omp.h>
#endif
#include "num/multind.h"
#include "num/flpmath.h"
#include "num/fft.h"
#include "num/init.h"
#include "num/iovec.h"
#include "num/ops.h"
#include "num/ops_p.h"
#ifdef USE_CUDA
#include "num/gpuops.h"
#endif
#include "iter/iter.h"
#include "iter/lsqr.h"
#include "iter/misc.h"
#include "linops/linop.h"
#include "linops/fmac.h"
#include "linops/someops.h"
#include "linops/decompose_complex.h"
#include "misc/debug.h"
#include "misc/mri.h"
#include "misc/utils.h"
#include "misc/mmio.h"
#include "misc/misc.h"
#include "misc/opts.h"
#include "wavelet/wavthresh.h"
#include "lowrank/lrthresh.h"
static const char usage_str[] = "<maps> <wave> <phi> <reorder> <table> <output>";
static const char help_str[] =
"Perform a wave-shuffling reconstruction.\n\n"
"Conventions:\n"
" * (sx, sy, sz) - Spatial dimensions.\n"
" * wx - Extended FOV in READ_DIM due to\n"
" wave's voxel spreading.\n"
" * (nc, md) - Number of channels and ESPIRiT's \n"
" extended-SENSE model operator\n"
" dimensions (or # of maps).\n"
" * (tf, tk) - Turbo-factor and the rank\n"
" of the temporal basis used in\n"
" shuffling.\n"
" * ntr - Number of TRs, or the number of\n"
" (ky, kz) points acquired of one\n"
" echo image.\n"
" * n - Total number of (ky, kz) points\n"
" acquired. This is equal to the\n"
" product of ntr and tf.\n\n"
"Descriptions:\n"
" * reorder is an (n by 3) index matrix such that\n"
" [ky, kz, t] = reorder(i, :) represents the\n"
" (ky, kz) kspace position of the readout line\n"
" acquired at echo number (t), and 0 <= ky < sy,\n"
" 0 <= kz < sz, 0 <= t < tf).\n"
" * table is a (wx by nc by n) matrix such that\n"
" table(:, :, k) represents the kth multichannel\n"
" kspace line.\n\n"
"Expected dimensions:\n"
" * maps - ( sx, sy, sz, nc, md, 1, 1)\n"
" * wave - ( wx, sy, sz, 1, 1, 1, 1)\n"
" * phi - ( 1, 1, 1, 1, 1, tf, tk)\n"
" * output - ( sx, sy, sz, 1, md, 1, tk)\n"
" * reorder - ( n, 3, 1, 1, 1, 1, 1)\n"
" * table - ( wx, nc, n, 1, 1, 1, 1)";
/* Helper function to print out operator dimensions. */
static void print_opdims(const struct linop_s* op)
{
const struct iovec_s* domain = linop_domain(op);
const struct iovec_s* codomain = linop_codomain(op);
debug_printf(DP_INFO, "\tDomain: [");
for (long k = 0; k < domain->N; k ++)
debug_printf(DP_INFO, "%6ld", domain->dims[k]);
debug_printf(DP_INFO, "]\n");
debug_printf(DP_INFO, "\tCodomain: [");
for (long k = 0; k < codomain->N; k ++)
debug_printf(DP_INFO, "%6ld", codomain->dims[k]);
debug_printf(DP_INFO, "]\n");
}
/* Construct sampling mask array from reorder tables. */
static void construct_mask(
long reorder_dims[DIMS], complex float* reorder,
long mask_dims[DIMS], complex float* mask)
{
long n = reorder_dims[0];
long sy = mask_dims[1];
long sz = mask_dims[2];
long y = 0;
long z = 0;
long t = 0;
for (int i = 0; i < n; i++) {
y = lround(creal(reorder[i]));
z = lround(creal(reorder[i + n]));
t = lround(creal(reorder[i + 2 * n]));
mask[(y + z * sy) + t * sy * sz] = 1;
}
}
struct kern_s {
INTERFACE(linop_data_t);
unsigned int N;
long* reorder_dims; // Dimension of the index table: ( n, 3, 1, 1, 1, 1, 1, 1)
long* phi_dims; // Dimension of the temporal basis: ( 1, 1, 1, 1, 1, tf, tk, 1)
long* table_dims; // Dimension of the data table: (wx, nc, n, 1, 1, 1, 1, 1)
long* kernel_dims; // Dimension of the kernel: ( 1, sy, sz, 1, 1, 1, tk, tk)
complex float* reorder;
complex float* phi;
complex float* kernel;
complex float* gpu_kernel;
};
static DEF_TYPEID(kern_s);
/* Go to table from coefficient-kspace with memory efficiency. */
static void kern_apply(const linop_data_t* _data, complex float* dst, const complex float* src)
{
const struct kern_s* data = CAST_DOWN(kern_s, _data);
long wx = data->table_dims[0];
long sy = data->kernel_dims[1];
long sz = data->kernel_dims[2];
long nc = data->table_dims[1];
long n = data->reorder_dims[0];
long tf = data->phi_dims[5];
long tk = data->phi_dims[6];
long input_dims[] = { [0 ... DIMS - 1] = 1 };
input_dims[0] = wx;
input_dims[1] = sy;
input_dims[2] = sz;
input_dims[3] = nc;
input_dims[6] = tk;
long perm_dims[] = { [0 ... DIMS - 1] = 1 };
perm_dims[0] = wx;
perm_dims[1] = nc;
perm_dims[3] = tk;
perm_dims[4] = sy;
perm_dims[5] = sz;
complex float* perm = md_alloc_sameplace(DIMS, perm_dims, CFL_SIZE, src);
unsigned int permute_order[DIMS] = {0, 3, 5, 6, 1, 2, 4, 7};
for (unsigned int i = 8; i < DIMS; i++)
permute_order[i] = i;
md_permute(DIMS, permute_order, perm_dims, perm, input_dims, src, CFL_SIZE);
long vec_dims[] = {wx, nc, tf, 1};
long phi_mat_dims[] = { 1, 1, tf, tk};
long phi_in_dims[] = {wx, nc, 1, tk};
long fmac_dims[] = {wx, nc, tf, tk};
long line_dims[] = {wx, nc, 1, 1};
complex float* vec = md_alloc_sameplace(4, vec_dims, CFL_SIZE, src);
long vec_str[4];
md_calc_strides(4, vec_str, vec_dims, CFL_SIZE);
long phi_mat_str[4];
md_calc_strides(4, phi_mat_str, phi_mat_dims, CFL_SIZE);
long phi_in_str[4];
md_calc_strides(4, phi_in_str, phi_in_dims, CFL_SIZE);
long fmac_str[4];
md_calc_strides(4, fmac_str, fmac_dims, CFL_SIZE);
int y = -1;
int z = -1;
int t = -1;
for (int i = 0; i < n; i ++) {
y = lround(creal(data->reorder[i]));
z = lround(creal(data->reorder[i + n]));
t = lround(creal(data->reorder[i + 2 * n]));
md_clear(4, vec_dims, vec, CFL_SIZE);
md_zfmac2(4, fmac_dims, vec_str, vec, phi_in_str, (perm + ((wx * nc * tk) * (y + z * sy))), phi_mat_str, data->phi);
md_copy(4, line_dims, dst + (i * wx * nc), vec + (t * wx * nc), CFL_SIZE);
}
md_free(perm);
md_free(vec);
}
/* Collapse data table into the temporal basis for memory efficiency. */
static void kern_adjoint(const linop_data_t* _data, complex float* dst, const complex float* src)
{
struct kern_s* data = CAST_DOWN(kern_s, _data);
long wx = data->table_dims[0];
long sy = data->kernel_dims[1];
long sz = data->kernel_dims[2];
long nc = data->table_dims[1];
long n = data->reorder_dims[0];
long tf = data->phi_dims[5];
long tk = data->phi_dims[6];
long perm_dims[] = { [0 ... DIMS - 1] = 1 };
perm_dims[0] = wx;
perm_dims[1] = nc;
perm_dims[3] = tk;
perm_dims[4] = sy;
perm_dims[5] = sz;
complex float* perm = md_alloc_sameplace(DIMS, perm_dims, CFL_SIZE, dst);
md_clear(DIMS, perm_dims, perm, CFL_SIZE);
#ifdef _OPENMP
long num_threads = omp_get_max_threads();
#else
long num_threads = 1;
#endif
long vec_dims[] = {wx, nc, tf, 1};
long phi_mat_dims[] = { 1, 1, tf, tk};
long phi_out_dims[] = {wx, nc, 1, tk};
long fmac_dims[] = {wx, nc, tf, tk};
long line_dims[] = {wx, nc, 1, 1};
long vthrd_dims[] = {wx, nc, tf, 1, num_threads};
complex float* vec = md_alloc_sameplace(5, vthrd_dims, CFL_SIZE, dst);
md_clear(DIMS, vthrd_dims, vec, CFL_SIZE);
long vec_str[4];
md_calc_strides(4, vec_str, vec_dims, CFL_SIZE);
long phi_mat_str[4];
md_calc_strides(4, phi_mat_str, phi_mat_dims, CFL_SIZE);
long phi_out_str[4];
md_calc_strides(4, phi_out_str, phi_out_dims, CFL_SIZE);
long fmac_str[4];
md_calc_strides(4, fmac_str, fmac_dims, CFL_SIZE);
long flag_dims[1] = { n };
complex float* flags = md_calloc(1, flag_dims, CFL_SIZE);
#pragma omp parallel for
for (int k = 0; k < n; k ++) {
#ifdef _OPENMP
int tid = omp_get_thread_num();
#else
int tid = 0;
#endif
int y = lround(creal(data->reorder[k]));
int z = lround(creal(data->reorder[k + n]));
int t = -1;
if (0 == flags[k]) {
md_clear(4, vec_dims, vec + (wx * nc * tf * tid), CFL_SIZE);
for (int i = k; i < n; i ++) {
if ((y == lround(creal(data->reorder[i]))) && (z == lround(creal(data->reorder[i + n])))) {
flags[i] = 1;
t = lround(creal(data->reorder[i + 2 * n]));
md_copy(4, line_dims, (vec + (wx * nc * tf * tid) + t * wx * nc), (src + i * wx * nc), CFL_SIZE);
}
}
md_zfmacc2(4, fmac_dims, phi_out_str, perm + (y + z * sy) * (wx * nc * tk), vec_str, vec + (wx * nc * tf * tid), phi_mat_str, data->phi);
}
}
long out_dims[] = { [0 ... DIMS - 1] = 1 };
out_dims[0] = wx;
out_dims[1] = sy;
out_dims[2] = sz;
out_dims[3] = nc;
out_dims[6] = tk;
unsigned int permute_order[DIMS] = {0, 4, 5, 1, 6, 2, 3, 7};
for (unsigned int i = 8; i < DIMS; i++)
permute_order[i] = i;
md_permute(DIMS, permute_order, out_dims, dst, perm_dims, perm, CFL_SIZE);
md_free(vec);
md_free(perm);
md_free(flags);
}
static void kern_normal(const linop_data_t* _data, complex float* dst, const complex float* src)
{
const struct kern_s* data = CAST_DOWN(kern_s, _data);
long wx = data->table_dims[0];
long sy = data->kernel_dims[1];
long sz = data->kernel_dims[2];
long nc = data->table_dims[1];
long tk = data->phi_dims[6];
long input_dims[DIMS] = { [0 ... DIMS - 1] = 1 };
input_dims[0] = wx;
input_dims[1] = sy;
input_dims[2] = sz;
input_dims[3] = nc;
input_dims[6] = tk;
long input_str[DIMS];
md_calc_strides(DIMS, input_str, input_dims, CFL_SIZE);
long output_dims[DIMS];
md_copy_dims(DIMS, output_dims, input_dims);
output_dims[6] = 1;
output_dims[7] = tk;
long output_str[DIMS];
md_calc_strides(DIMS, output_str, output_dims, CFL_SIZE);
long gpu_kernel_dims[DIMS] = { [0 ... DIMS - 1] = 1};
md_copy_dims(DIMS, gpu_kernel_dims, data->kernel_dims);
gpu_kernel_dims[0] = wx;
gpu_kernel_dims[3] = nc;
long kernel_str[DIMS];
md_calc_strides(DIMS, kernel_str, data->kernel_dims, CFL_SIZE);
long gpu_kernel_str[DIMS];
md_calc_strides(DIMS, gpu_kernel_str, gpu_kernel_dims, CFL_SIZE);
long fmac_dims[DIMS];
md_merge_dims(DIMS, fmac_dims, input_dims, data->kernel_dims);
md_clear(DIMS, output_dims, dst, CFL_SIZE);
#ifdef USE_CUDA
if(cuda_ondevice(src))
md_zfmac2(DIMS, fmac_dims, output_str, dst, input_str, src, gpu_kernel_str, data->gpu_kernel);
else
#endif
md_zfmac2(DIMS, fmac_dims, output_str, dst, input_str, src, kernel_str, data->kernel);
}
static void kern_free(const linop_data_t* _data)
{
const struct kern_s* data = CAST_DOWN(kern_s, _data);
xfree(data->reorder_dims);
xfree(data->phi_dims);
xfree(data->table_dims);
xfree(data->kernel_dims);
#ifdef USE_CUDA
if (data->gpu_kernel != NULL)
md_free(data->gpu_kernel);
#endif
xfree(data);
}
static const struct linop_s* linop_kern_create(bool gpu_flag,
const long _reorder_dims[DIMS], complex float* reorder,
const long _phi_dims[DIMS], complex float* phi,
const long _kernel_dims[DIMS], complex float* kernel,
const long _table_dims[DIMS])
{
PTR_ALLOC(struct kern_s, data);
SET_TYPEID(kern_s, data);
PTR_ALLOC(long[DIMS], reorder_dims);
PTR_ALLOC(long[DIMS], phi_dims);
PTR_ALLOC(long[DIMS], table_dims);
PTR_ALLOC(long[DIMS], kernel_dims);
md_copy_dims(DIMS, *reorder_dims, _reorder_dims);
md_copy_dims(DIMS, *phi_dims, _phi_dims);
md_copy_dims(DIMS, *table_dims, _table_dims);
md_copy_dims(DIMS, *kernel_dims, _kernel_dims);
data->reorder_dims = *PTR_PASS(reorder_dims);
data->phi_dims = *PTR_PASS(phi_dims);
data->table_dims = *PTR_PASS(table_dims);
data->kernel_dims = *PTR_PASS(kernel_dims);
data->reorder = reorder;
data->phi = phi;
data->kernel = kernel;
data->gpu_kernel = NULL;
#ifdef USE_CUDA
if(gpu_flag) {
long repmat_kernel_dims[DIMS] = { [0 ... DIMS - 1] = 1};
md_copy_dims(DIMS, repmat_kernel_dims, _kernel_dims);
repmat_kernel_dims[0] = _table_dims[0];
repmat_kernel_dims[3] = _table_dims[1];
long kernel_strs[DIMS];
long repmat_kernel_strs[DIMS];
md_calc_strides(DIMS, kernel_strs, _kernel_dims, CFL_SIZE);
md_calc_strides(DIMS, repmat_kernel_strs, repmat_kernel_dims, CFL_SIZE);
complex float* repmat_kernel = md_calloc(DIMS, repmat_kernel_dims, CFL_SIZE);
md_copy2(DIMS, repmat_kernel_dims, repmat_kernel_strs, repmat_kernel, kernel_strs, kernel, CFL_SIZE);
data->gpu_kernel = md_gpu_move(DIMS, repmat_kernel_dims, repmat_kernel, CFL_SIZE);
md_free(repmat_kernel);
}
#else
UNUSED(gpu_flag);
#endif
long input_dims[DIMS] = { [0 ... DIMS - 1] = 1 };
input_dims[0] = _table_dims[0];
input_dims[1] = _kernel_dims[1];
input_dims[2] = _kernel_dims[2];
input_dims[3] = _table_dims[1];
input_dims[6] = _phi_dims[6];
long output_dims[DIMS] = { [0 ... DIMS - 1] = 1 };
output_dims[0] = _table_dims[0];
output_dims[1] = _table_dims[1];
output_dims[2] = _reorder_dims[0];
const struct linop_s* K = linop_create(DIMS, output_dims, DIMS, input_dims, CAST_UP(PTR_PASS(data)), kern_apply, kern_adjoint, kern_normal, NULL, kern_free);
return K;
}
struct multc_s {
INTERFACE(linop_data_t);
unsigned int nc;
unsigned int md;
const complex float* maps;
const struct linop_s* sc_op; // Single channel operator.
};
static DEF_TYPEID(multc_s);
static void multc_apply(const linop_data_t* _data, complex float* dst, const complex float* src)
{
const struct multc_s* data = CAST_DOWN(multc_s, _data);
// Loading single channel operator.
const struct operator_s* fwd = data->sc_op->forward;
const long* sc_inp_dims = linop_domain(data->sc_op)->dims;
const long* sc_out_dims = linop_codomain(data->sc_op)->dims;
long sx = sc_inp_dims[0];
long sy = sc_inp_dims[1];
long sz = sc_inp_dims[2];
long wx = sc_out_dims[0];
long n = sc_out_dims[2];
long nc = data->nc;
long md = data->md;
long src_dims[] = { [0 ... DIMS - 1] = 1};
md_copy_dims(DIMS, src_dims, sc_inp_dims);
src_dims[MAPS_DIM] = md;
long dst_dims[] = { [0 ... DIMS - 1] = 1};
md_copy_dims(DIMS, dst_dims, sc_out_dims);
dst_dims[1] = nc;
long map_dims[] = { [0 ... DIMS - 1] = 1};
map_dims[0] = sx;
map_dims[1] = sy;
map_dims[2] = sz;
map_dims[3] = nc;
map_dims[4] = md;
long single_map_dims[] = { [0 ... DIMS - 1] = 1 };
md_copy_dims(DIMS, single_map_dims, map_dims);
single_map_dims[COIL_DIM] = 1;
complex float* single_map = md_alloc_sameplace(DIMS, single_map_dims, CFL_SIZE, src);
complex float* buffer = md_alloc_sameplace(DIMS, sc_inp_dims, CFL_SIZE, src);
long tbl_dims[] = { [0 ... DIMS - 1] = 1};
tbl_dims[0] = wx;
tbl_dims[1] = n;
tbl_dims[2] = nc;
complex float* tbl = md_alloc_sameplace(DIMS, tbl_dims, CFL_SIZE, src);
md_clear(DIMS, tbl_dims, tbl, CFL_SIZE);
long pos[] = { [0 ... DIMS - 1] = 0 };
long zfmac_dims[] = { [0 ... DIMS - 1] = 1 };
md_copy_dims(DIMS, zfmac_dims, src_dims);
long strides_single_map[DIMS];
md_calc_strides(DIMS, strides_single_map, single_map_dims, CFL_SIZE);
long strides_src[DIMS];
md_calc_strides(DIMS, strides_src, src_dims, CFL_SIZE);
long strides_sc_inp[DIMS];
md_calc_strides(DIMS, strides_sc_inp, sc_inp_dims, CFL_SIZE);
for (long k = 0; k < data->nc; k++) {
md_clear(DIMS, single_map_dims, single_map, CFL_SIZE);
md_clear(DIMS, sc_inp_dims, buffer, CFL_SIZE);
pos[COIL_DIM] = k;
md_slice(DIMS, COIL_FLAG, pos, map_dims, single_map, data->maps, CFL_SIZE);
pos[COIL_DIM] = 0;
md_zfmac2(DIMS, zfmac_dims, strides_sc_inp, buffer, strides_src, src, strides_single_map, single_map);
operator_apply(fwd, DIMS, sc_out_dims, tbl + (wx * n * k), DIMS, sc_inp_dims, buffer);
}
md_clear(DIMS, dst_dims, dst, CFL_SIZE);
unsigned int permute_order[DIMS] = {0, 2, 1};
for (unsigned int i = 3; i < DIMS; i++)
permute_order[i] = i;
md_permute(DIMS, permute_order, dst_dims, dst, tbl_dims, tbl, CFL_SIZE);
md_free(single_map);
md_free(buffer);
md_free(tbl);
}
static void multc_adjoint(const linop_data_t* _data, complex float* dst, const complex float* src)
{
const struct multc_s* data = CAST_DOWN(multc_s, _data);
// Loading single channel operator.
const struct operator_s* adj = data->sc_op->adjoint;
const long* sc_inp_dims = linop_codomain(data->sc_op)->dims;
const long* sc_out_dims = linop_domain(data->sc_op)->dims;
long sx = sc_out_dims[0];
long sy = sc_out_dims[1];
long sz = sc_out_dims[2];
long wx = sc_inp_dims[0];
long n = sc_inp_dims[2];
long nc = data->nc;
long md = data->md;
long src_dims[] = { [0 ... DIMS - 1] = 1};
md_copy_dims(DIMS, src_dims, sc_inp_dims);
src_dims[1] = nc;
long dst_dims[] = { [0 ... DIMS - 1] = 1};
md_copy_dims(DIMS, dst_dims, sc_out_dims);
dst_dims[MAPS_DIM] = md;
long map_dims[] = { [0 ... DIMS - 1] = 1};
map_dims[0] = sx;
map_dims[1] = sy;
map_dims[2] = sz;
map_dims[3] = nc;
map_dims[4] = md;
long single_map_dims[] = { [0 ... DIMS - 1] = 1 };
md_copy_dims(DIMS, single_map_dims, map_dims);
single_map_dims[COIL_DIM] = 1;
complex float* single_map = md_alloc_sameplace(DIMS, single_map_dims, CFL_SIZE, src);
complex float* buffer1 = md_alloc_sameplace(DIMS, sc_out_dims, CFL_SIZE, src);
complex float* buffer2 = md_alloc_sameplace(DIMS, dst_dims, CFL_SIZE, src);
long tbl_dims[] = { [0 ... DIMS - 1] = 1};
tbl_dims[0] = wx;
tbl_dims[2] = n;
complex float* tbl = md_alloc_sameplace(DIMS, tbl_dims, CFL_SIZE, src);
long pos[] = { [0 ... DIMS - 1] = 0 };
long strides_single_map[DIMS];
md_calc_strides(DIMS, strides_single_map, single_map_dims, CFL_SIZE);
long strides_sc_out[DIMS];
md_calc_strides(DIMS, strides_sc_out, sc_out_dims, CFL_SIZE);
long strides_dst[DIMS];
md_calc_strides(DIMS, strides_dst, dst_dims, CFL_SIZE);
md_clear(DIMS, dst_dims, dst, CFL_SIZE);
for (long k = 0; k < data->nc; k++) {
md_clear(DIMS, single_map_dims, single_map, CFL_SIZE);
md_clear(DIMS, sc_out_dims, buffer1, CFL_SIZE);
md_clear(DIMS, dst_dims, buffer2, CFL_SIZE);
md_clear(DIMS, tbl_dims, tbl, CFL_SIZE);
pos[1] = k;
md_slice(DIMS, 2, pos, src_dims, tbl, src, CFL_SIZE);
pos[1] = 0;
operator_apply(adj, DIMS, sc_out_dims, buffer1, DIMS, tbl_dims, tbl);
pos[COIL_DIM] = k;
md_slice(DIMS, COIL_FLAG, pos, map_dims, single_map, data->maps, CFL_SIZE);
pos[COIL_DIM] = 0;
md_zfmacc2(DIMS, dst_dims, strides_dst, buffer2, strides_sc_out, buffer1, strides_single_map, single_map);
md_zadd(DIMS, dst_dims, dst, dst, buffer2);
}
md_free(single_map);
md_free(buffer1);
md_free(buffer2);
md_free(tbl);
}
static void multc_normal(const linop_data_t* _data, complex float* dst, const complex float* src)
{
const struct multc_s* data = CAST_DOWN(multc_s, _data);
// Loading single channel operator.
const struct operator_s* nrm = data->sc_op->normal;
const long* sc_dims = linop_domain(data->sc_op)->dims;
long sx = sc_dims[0];
long sy = sc_dims[1];
long sz = sc_dims[2];
long nc = data->nc;
long md = data->md;
long dims[] = { [0 ... DIMS - 1] = 1};
md_copy_dims(DIMS, dims, sc_dims);
dims[MAPS_DIM] = md;
long map_dims[] = { [0 ... DIMS - 1] = 1};
map_dims[0] = sx;
map_dims[1] = sy;
map_dims[2] = sz;
map_dims[3] = nc;
map_dims[4] = md;
long single_map_dims[] = { [0 ... DIMS - 1] = 1 };
md_copy_dims(DIMS, single_map_dims, map_dims);
single_map_dims[COIL_DIM] = 1;
complex float* single_map = md_alloc_sameplace(DIMS, single_map_dims, CFL_SIZE, src);
complex float* buffer1 = md_alloc_sameplace(DIMS, sc_dims, CFL_SIZE, src);
complex float* buffer2 = md_alloc_sameplace(DIMS, sc_dims, CFL_SIZE, src);
complex float* buffer3 = md_alloc_sameplace(DIMS, dims, CFL_SIZE, src);
long pos[] = { [0 ... DIMS - 1] = 0 };
long strides_single_map[DIMS];
md_calc_strides(DIMS, strides_single_map, single_map_dims, CFL_SIZE);
long strides_sc[DIMS];
md_calc_strides(DIMS, strides_sc, sc_dims, CFL_SIZE);
long strides[DIMS];
md_calc_strides(DIMS, strides, dims, CFL_SIZE);
md_clear(DIMS, dims, dst, CFL_SIZE);
for (long k = 0; k < data->nc; k++) {
md_clear(DIMS, single_map_dims, single_map, CFL_SIZE);
md_clear(DIMS, sc_dims, buffer1, CFL_SIZE);
md_clear(DIMS, sc_dims, buffer2, CFL_SIZE);
md_clear(DIMS, dims, buffer3, CFL_SIZE);
pos[COIL_DIM] = k;
md_slice(DIMS, COIL_FLAG, pos, map_dims, single_map, data->maps, CFL_SIZE);
pos[COIL_DIM] = 0;
md_zfmac2(DIMS, dims, strides_sc, buffer1, strides, src, strides_single_map, single_map);
operator_apply(nrm, DIMS, sc_dims, buffer2, DIMS, sc_dims, buffer1);
md_zfmacc2(DIMS, dims, strides, buffer3, strides_sc, buffer2, strides_single_map, single_map);
md_zadd(DIMS, dims, dst, dst, buffer3);
}
md_free(single_map);
md_free(buffer1);
md_free(buffer2);
md_free(buffer3);
}
static void multc_free(const linop_data_t* _data)
{
const struct multc_s* data = CAST_DOWN(multc_s, _data);
xfree(data);
}
static struct linop_s* linop_multc_create(long nc, long md, const complex float* maps, const struct linop_s* sc_op)
{
PTR_ALLOC(struct multc_s, data);
SET_TYPEID(multc_s, data);
data->nc = nc;
data->md = md;
data->maps = maps;
data->sc_op = sc_op;
long* op_inp_dims = (long*) linop_domain(sc_op)->dims;
long* op_out_dims = (long*) linop_codomain(sc_op)->dims;
long input_dims[] = { [0 ... DIMS - 1] = 1 };
md_copy_dims(DIMS, input_dims, op_inp_dims);
input_dims[MAPS_DIM] = md;
long output_dims[] = { [0 ... DIMS - 1] = 1 };
md_copy_dims(DIMS, output_dims, op_out_dims);
output_dims[1] = nc;
struct linop_s* E = linop_create(DIMS, output_dims, DIMS, input_dims, CAST_UP(PTR_PASS(data)), multc_apply, multc_adjoint, multc_normal, NULL, multc_free);
return E;
}
/* Resize operator. */
static const struct linop_s* linop_wavereshape_create(long wx, long sx, long sy, long sz, long nc, long tk)
{
long input_dims[] = { [0 ... DIMS - 1] = 1};
input_dims[0] = sx;
input_dims[1] = sy;
input_dims[2] = sz;
input_dims[3] = nc;
input_dims[6] = tk;
long output_dims[DIMS];
md_copy_dims(DIMS, output_dims, input_dims);
output_dims[0] = wx;
struct linop_s* R = linop_resize_create(DIMS, output_dims, input_dims);
return R;
}
/* Fx operator. */
static const struct linop_s* linop_fx_create(long wx, long sy, long sz, long nc, long tk, bool centered)
{
long dims[] = { [0 ... DIMS - 1] = 1};
dims[0] = wx;
dims[1] = sy;
dims[2] = sz;
dims[3] = nc;
dims[6] = tk;
struct linop_s* Fx = NULL;
if (centered)
Fx = linop_fftc_create(DIMS, dims, READ_FLAG);
else
Fx = linop_fft_create(DIMS, dims, READ_FLAG);
return Fx;
}
/* Wave operator. */
static const struct linop_s* linop_wave_create(long wx, long sy, long sz, long nc, long tk, long psf_tk, complex float* psf)
{
long dims[] = { [0 ... DIMS - 1] = 1};
dims[0] = wx;
dims[1] = sy;
dims[2] = sz;
dims[3] = nc;
dims[6] = tk;
return (psf_tk > 1) ? linop_cdiag_create(DIMS, dims, FFT_FLAGS | COEFF_FLAG, psf) : linop_cdiag_create(DIMS, dims, FFT_FLAGS, psf);
}
/* Fyz operator. */
static const struct linop_s* linop_fyz_create(long wx, long sy, long sz, long nc, long tk, bool centered)
{
long dims[] = { [0 ... DIMS - 1] = 1};
dims[0] = wx;
dims[1] = sy;
dims[2] = sz;
dims[3] = nc;
dims[6] = tk;
struct linop_s* Fyz = NULL;
if (centered)
Fyz = linop_fftc_create(DIMS, dims, PHS1_FLAG|PHS2_FLAG);
else
Fyz = linop_fft_create(DIMS, dims, PHS1_FLAG|PHS2_FLAG);
return Fyz;
}
/* Construction sampling temporal kernel.*/
static void construct_kernel(
long mask_dims[DIMS], complex float* mask,
long phi_dims[DIMS], complex float* phi,
long kern_dims[DIMS], complex float* kern)
{
long sy = mask_dims[1];
long sz = mask_dims[2];
long tf = phi_dims[5];
long tk = phi_dims[6];
long cvec_dims[] = { [0 ... DIMS - 1] = 1 };
cvec_dims[6] = tk;
long cvec_str[DIMS];
md_calc_strides(DIMS, cvec_str, cvec_dims, CFL_SIZE);
complex float cvec[tk];
long tvec_dims[] = { [0 ... DIMS - 1] = 1 };
tvec_dims[5] = tf;
long tvec_str[DIMS];
md_calc_strides(DIMS, tvec_str, tvec_dims, CFL_SIZE);
complex float mvec[tf];
complex float tvec1[tf];
complex float tvec2[tf];
long phi_str[DIMS];
md_calc_strides(DIMS, phi_str, phi_dims, CFL_SIZE);
long out_dims[] = { [0 ... DIMS - 1] = 1 };
out_dims[0] = tk;
out_dims[1] = sy;
out_dims[2] = sz;
out_dims[3] = tk;
complex float* out = md_calloc(DIMS, out_dims, CFL_SIZE);
for (int y = 0; y < sy; y ++) {
for (int z = 0; z < sz; z ++) {
for (int t = 0; t < tf; t ++)
mvec[t] = mask[(y + sy * z) + (sy * sz) * t];
for (int t = 0; t < tk; t ++) {
cvec[t] = 1;
md_clear(DIMS, tvec_dims, tvec1, CFL_SIZE);
md_zfmac2(DIMS, phi_dims, tvec_str, tvec1, cvec_str, cvec, phi_str, phi);
md_clear(DIMS, tvec_dims, tvec2, CFL_SIZE);
md_zfmac2(DIMS, tvec_dims, tvec_str, tvec2, tvec_str, tvec1, tvec_str, mvec);
md_clear(DIMS, cvec_dims, out + y * tk + z * sy * tk + t * sy * sz * tk, CFL_SIZE);
md_zfmacc2(DIMS, phi_dims, cvec_str, out + y * tk + z * sy * tk + t * sy * sz * tk,
tvec_str, tvec2, phi_str, phi);
cvec[t] = 0;
}
}
}
unsigned int permute_order[DIMS] = {4, 1, 2, 5, 6, 7, 3, 0};
for (unsigned int i = 8; i < DIMS; i++)
permute_order[i] = i;
md_permute(DIMS, permute_order, kern_dims, kern, out_dims, out, CFL_SIZE);
md_free(out);
}
static void fftmod_apply(long sy, long sz,
long reorder_dims[DIMS], complex float* reorder,
long table_dims[DIMS], complex float* table,
long maps_dims[DIMS], complex float* maps)
{
long wx = table_dims[0];
long nc = table_dims[1];
fftmod(DIMS, table_dims, READ_FLAG, table, table);
fftmod(DIMS, maps_dims, FFT_FLAGS, maps, maps);
long y = -1;
long z = -1;
double dy = ((double) sy/2)/((double) sy);
double dz = ((double) sz/2)/((double) sz);
complex float py = 1;
complex float pz = 1;
long dims[] = { [0 ... DIMS] = 1};
dims[0] = wx;
dims[1] = nc;
long n = reorder_dims[0];
for (long k = 0; k < n; k++) {
y = lround(creal(reorder[k]));
z = lround(creal(reorder[k + n]));
py = cexp(2.i * M_PI * dy * y);
pz = cexp(2.i * M_PI * dz * z);
md_zsmul(DIMS, dims, table + k * wx * nc, table + k * wx * nc, py * pz);
}
}
enum algo_t { CG, IST, FISTA };
int main_wshfl(int argc, char* argv[])
{
double start_time = timestamp();
float lambda = 1E-5;
int maxiter = 300;
int blksize = 8;
float step = 0.5;
float tol = 1.E-3;
bool llr = false;
bool wav = false;
bool fista = false;
bool hgwld = false;
float cont = 1;
float eval = -1;
const char* fwd = NULL;
const char* x0 = NULL;
int gpun = -1;
bool dcx = false;
bool pf = false;
const struct opt_s opts[] = {
OPT_FLOAT( 'r', &lambda, "lambda", "Soft threshold lambda for wavelet or locally low rank."),
OPT_INT( 'b', &blksize, "blkdim", "Block size for locally low rank."),
OPT_INT( 'i', &maxiter, "mxiter", "Maximum number of iterations."),
OPT_FLOAT( 's', &step, "stepsz", "Step size for iterative method."),
OPT_FLOAT( 'c', &cont, "cntnu", "Continuation value for IST/FISTA."),
OPT_FLOAT( 't', &tol, "toler", "Tolerance convergence condition for iterative method."),
OPT_FLOAT( 'e', &eval, "eigvl", "Maximum eigenvalue of normal operator, if known."),
OPT_STRING('F', &fwd, "frwrd", "Go from shfl-coeffs to data-table. Pass in coeffs path."),
OPT_STRING('O', &x0, "initl", "Initialize reconstruction with guess."),
OPT_INT( 'g', &gpun, "gpunm", "GPU device number."),
OPT_SET( 'f', &fista, "Reconstruct using FISTA instead of IST."),
OPT_SET( 'H', &hgwld, "Use hogwild in IST/FISTA."),
OPT_SET( 'v', &dcx, "Split coefficients to real and imaginary components."),
OPT_SET( 'w', &wav, "Use wavelet."),
OPT_SET( 'l', &llr, "Use locally low rank across temporal coefficients."),
OPT_SET( 'p', &pf, "Use locally low rank and real-imaginary components for partial fourier."),
};
cmdline(&argc, argv, 6, 6, usage_str, help_str, ARRAY_SIZE(opts), opts);
if (pf)
dcx = true;
debug_printf(DP_INFO, "Loading data... ");
long maps_dims[DIMS];
complex float* maps = load_cfl(argv[1], DIMS, maps_dims);
long wave_dims[DIMS];
complex float* wave = load_cfl(argv[2], DIMS, wave_dims);
long phi_dims[DIMS];
complex float* phi = load_cfl(argv[3], DIMS, phi_dims);
long reorder_dims[DIMS];
complex float* reorder = load_cfl(argv[4], DIMS, reorder_dims);
long table_dims[DIMS];
complex float* table = load_cfl(argv[5], DIMS, table_dims);
debug_printf(DP_INFO, "Done.\n");
if (gpun >= 0)
num_init_gpu_device(gpun);
else
num_init();
int wx = wave_dims[0];
int sx = maps_dims[0];
int sy = maps_dims[1];
int sz = maps_dims[2];
int nc = maps_dims[3];
int md = maps_dims[4];
int tf = phi_dims[5];
int tk = phi_dims[6];
debug_printf(DP_INFO, "Constructing sampling mask from reorder table... ");
long mask_dims[] = { [0 ... DIMS - 1] = 1 };
mask_dims[1] = sy;
mask_dims[2] = sz;
mask_dims[5] = tf;
complex float* mask = md_calloc(DIMS, mask_dims, CFL_SIZE);
construct_mask(reorder_dims, reorder, mask_dims, mask);
debug_printf(DP_INFO, "Done.\n");
debug_printf(DP_INFO, "Constructing sampling-temporal kernel... ");
long kernel_dims[] = { [0 ... DIMS - 1] = 1 };
kernel_dims[1] = sy;
kernel_dims[2] = sz;
kernel_dims[6] = tk;
kernel_dims[7] = tk;
complex float* kernel = md_calloc(DIMS, kernel_dims, CFL_SIZE);
construct_kernel(mask_dims, mask, phi_dims, phi, kernel_dims, kernel);
md_free(mask);
debug_printf(DP_INFO, "Done.\n");
long coeff_dims[] = { [0 ... DIMS - 1] = 1 };
coeff_dims[0] = sx;
coeff_dims[1] = sy;
coeff_dims[2] = sz;
coeff_dims[4] = md;
coeff_dims[6] = tk;
coeff_dims[8] = dcx ? 2 : 1;
debug_printf(DP_INFO, "Creating single channel linear operators:\n");
double t1;
double t2;
t1 = timestamp();
const struct linop_s* R = linop_wavereshape_create(wx, sx, sy, sz, 1, tk);
t2 = timestamp();
debug_printf(DP_INFO, "\tR: %f seconds.\n", t2 - t1);
t1 = timestamp();
const struct linop_s* Fx = linop_fx_create(wx, sy, sz, 1, tk, false);
t2 = timestamp();
debug_printf(DP_INFO, "\tFx: %f seconds.\n", t2 - t1);
t1 = timestamp();
const struct linop_s* W = linop_wave_create(wx, sy, sz, 1, tk, wave_dims[COEFF_DIM], wave);
t2 = timestamp();
debug_printf(DP_INFO, "\tW: %f seconds.\n", t2 - t1);
t1 = timestamp();
const struct linop_s* Fyz = linop_fyz_create(wx, sy, sz, 1, tk, false);
t2 = timestamp();
debug_printf(DP_INFO, "\tFyz: %f seconds.\n", t2 - t1);
t1 = timestamp();
long single_channel_table_dims[] = { [0 ... DIMS - 1] = 1 };
md_copy_dims(DIMS, single_channel_table_dims, table_dims);
single_channel_table_dims[1] = 1;
const struct linop_s* K = linop_kern_create(gpun >= 0, reorder_dims, reorder, phi_dims, phi, kernel_dims, kernel, single_channel_table_dims);
t2 = timestamp();
debug_printf(DP_INFO, "\tK: %f seconds.\n", t2 - t1);
struct linop_s* A_sc = linop_chain_FF(linop_chain_FF(linop_chain_FF(linop_chain_FF(
R, Fx), W), Fyz), K);
debug_printf(DP_INFO, "Single channel forward operator information:\n");
print_opdims(A_sc);
if (eval < 0)
#ifdef USE_CUDA
eval = (gpun >= 0) ? estimate_maxeigenval_gpu(A_sc->normal) : estimate_maxeigenval(A_sc->normal);
#else
eval = estimate_maxeigenval(A_sc->normal);
#endif
debug_printf(DP_INFO, "\tMax eval: %.2e\n", eval);
step /= eval;
struct linop_s* A = linop_multc_create(nc, md, maps, A_sc);
debug_printf(DP_INFO, "Overall forward linear operator information:\n");
print_opdims(A);
if (fwd != NULL) {
debug_printf(DP_INFO, "Going from coefficients to data table... ");
complex float* coeffs_to_fwd = load_cfl(fwd, DIMS, coeff_dims);
complex float* table_forward = create_cfl(argv[6], DIMS, table_dims);
const struct linop_s* R = linop_wavereshape_create(wx, sx, sy, sz, 1, tk);
const struct linop_s* CFx = linop_fx_create( wx, sy, sz, 1, tk, true);
const struct linop_s* W = linop_wave_create(wx, sy, sz, 1, tk, wave_dims[COEFF_DIM], wave);
const struct linop_s* CFyz = linop_fyz_create(wx, sy, sz, 1, tk, true);
const struct linop_s* K = linop_kern_create(gpun >= 0, reorder_dims, reorder, phi_dims, phi, kernel_dims, kernel, single_channel_table_dims);
struct linop_s* AC_sc = linop_chain_FF(linop_chain_FF(linop_chain_FF(linop_chain_FF(
R, CFx), W), CFyz), K);
struct linop_s* AC = linop_multc_create(nc, md, maps, AC_sc);
operator_apply(AC->forward, DIMS, table_dims, table_forward, DIMS, coeff_dims, coeffs_to_fwd);
debug_printf(DP_INFO, "Done.\n");
debug_printf(DP_INFO, "Cleaning up... ");
linop_free(AC);
linop_free(AC_sc);
md_free(kernel);
unmap_cfl(DIMS, maps_dims, maps);
unmap_cfl(DIMS, wave_dims, wave);
unmap_cfl(DIMS, phi_dims, phi);
unmap_cfl(DIMS, reorder_dims, reorder);
unmap_cfl(DIMS, table_dims, table);
unmap_cfl(DIMS, table_dims, table_forward);
debug_printf(DP_INFO, "Done.\n");
return 0;
}
if (dcx) {
debug_printf(DP_INFO, "\tSplitting result into real and imaginary components.\n");
struct linop_s* tmp = A;
struct linop_s* dcxop = linop_decompose_complex_create(DIMS, ITER_DIM, linop_domain(A)->dims);
A = linop_chain(dcxop, tmp);
linop_free(dcxop);
linop_free(tmp);
}
debug_printf(DP_INFO, "Normalizing data table and applying fftmod to table and maps... ");
float norm = md_znorm(DIMS, table_dims, table);
md_zsmul(DIMS, table_dims, table, table, 1. / norm);
fftmod_apply(sy, sz, reorder_dims, reorder, table_dims, table, maps_dims, maps);
debug_printf(DP_INFO, "Done.\n");
const struct operator_p_s* T = NULL;
long blkdims[MAX_LEV][DIMS];
long minsize[] = { [0 ... DIMS - 1] = 1 };
minsize[0] = MIN(sx, 16);
minsize[1] = MIN(sy, 16);
minsize[2] = MIN(sz, 16);
unsigned int WAVFLAG = (sx > 1) * READ_FLAG | (sy > 1) * PHS1_FLAG | (sz > 2) * PHS2_FLAG;
enum algo_t algo = CG;
if ((wav) || (llr) || (pf)) {
algo = (fista) ? FISTA : IST;
if (wav) {
debug_printf(DP_INFO, "Creating wavelet threshold operator... ");
T = prox_wavelet_thresh_create(DIMS, coeff_dims, WAVFLAG, 0u, minsize, lambda, true);
} else if (llr) {
debug_printf(DP_INFO, "Creating locally low rank threshold operator across coeff and real-imag... ");
llr_blkdims(blkdims, ~(COEFF_FLAG | ITER_FLAG), coeff_dims, blksize);
T = lrthresh_create(coeff_dims, true, ~(COEFF_FLAG | ITER_FLAG), (const long (*)[])blkdims, lambda, false, false, false);
} else {
assert(dcx);
debug_printf(DP_INFO, "Creating locally low rank threshold operator across real-imag... ");
llr_blkdims(blkdims, ~ITER_FLAG, coeff_dims, blksize);
T = lrthresh_create(coeff_dims, true, ~ITER_FLAG, (const long (*)[])blkdims, lambda, false, false, false);
}
debug_printf(DP_INFO, "Done.\n");
}
italgo_fun2_t italgo = iter2_call_iter;
struct iter_call_s iter2_data;
SET_TYPEID(iter_call_s, &iter2_data);
iter_conf* iconf = CAST_UP(&iter2_data);
struct iter_conjgrad_conf cgconf = iter_conjgrad_defaults;
struct iter_fista_conf fsconf = iter_fista_defaults;
struct iter_ist_conf isconf = iter_ist_defaults;
switch(algo) {
case IST:
debug_printf(DP_INFO, "Using IST.\n");
debug_printf(DP_INFO, "\tLambda: %0.2e\n", lambda);
debug_printf(DP_INFO, "\tMaximum iterations: %d\n", maxiter);
debug_printf(DP_INFO, "\tStep size: %0.2e\n", step);
debug_printf(DP_INFO, "\tHogwild: %d\n", (int) hgwld);
debug_printf(DP_INFO, "\tTolerance: %0.2e\n", tol);
debug_printf(DP_INFO, "\tContinuation: %0.2e\n", cont);
isconf = iter_ist_defaults;
isconf.step = step;
isconf.maxiter = maxiter;
isconf.tol = tol;
isconf.continuation = cont;
isconf.hogwild = hgwld;
iter2_data.fun = iter_ist;
iter2_data._conf = CAST_UP(&isconf);
break;
case FISTA:
debug_printf(DP_INFO, "Using FISTA.\n");
debug_printf(DP_INFO, "\tLambda: %0.2e\n", lambda);
debug_printf(DP_INFO, "\tMaximum iterations: %d\n", maxiter);
debug_printf(DP_INFO, "\tStep size: %0.2e\n", step);
debug_printf(DP_INFO, "\tHogwild: %d\n", (int) hgwld);
debug_printf(DP_INFO, "\tTolerance: %0.2e\n", tol);
debug_printf(DP_INFO, "\tContinuation: %0.2e\n", cont);
fsconf = iter_fista_defaults;
fsconf.maxiter = maxiter;
fsconf.step = step;
fsconf.hogwild = hgwld;
fsconf.tol = tol;
fsconf.continuation = cont;
iter2_data.fun = iter_fista;
iter2_data._conf = CAST_UP(&fsconf);
break;
default:
case CG:
debug_printf(DP_INFO, "Using CG.\n");
debug_printf(DP_INFO, "\tMaximum iterations: %d\n", maxiter);
debug_printf(DP_INFO, "\tTolerance: %0.2e\n", tol);
cgconf = iter_conjgrad_defaults;
cgconf.maxiter = maxiter;
cgconf.l2lambda = 0;
cgconf.tol = tol;
iter2_data.fun = iter_conjgrad;
iter2_data._conf = CAST_UP(&cgconf);
break;
}
complex float* init = NULL;
if (x0 != NULL) {
debug_printf(DP_INFO, "Loading in initial guess... ");
init = load_cfl(x0, DIMS, coeff_dims);
debug_printf(DP_INFO, "Done.\n");
}
debug_printf(DP_INFO, "Reconstruction... ");
complex float* recon = create_cfl(argv[6], DIMS, coeff_dims);
struct lsqr_conf lsqr_conf = { 0., gpun >= 0 };
double recon_start = timestamp();
const struct operator_p_s* J = lsqr2_create(&lsqr_conf, italgo, iconf, (const float*) init, A, NULL, 1, &T, NULL, NULL);
operator_p_apply(J, 1., DIMS, coeff_dims, recon, DIMS, table_dims, table);
double recon_end = timestamp();
debug_printf(DP_INFO, "Done.\nReconstruction time: %f seconds.\n", recon_end - recon_start);
debug_printf(DP_INFO, "Cleaning up and saving result... ");
operator_p_free(J);
linop_free(A);
linop_free(A_sc);
md_free(kernel);
unmap_cfl(DIMS, maps_dims, maps);
unmap_cfl(DIMS, wave_dims, wave);
unmap_cfl(DIMS, phi_dims, phi);
unmap_cfl(DIMS, reorder_dims, reorder);
unmap_cfl(DIMS, table_dims, table);
unmap_cfl(DIMS, coeff_dims, recon);
if (x0 != NULL)
unmap_cfl(DIMS, coeff_dims, init);
debug_printf(DP_INFO, "Done.\n");
double end_time = timestamp();
debug_printf(DP_INFO, "Total time: %f seconds.\n", end_time - start_time);
return 0;
}
|
GB_unop__identity_uint8_uint64.c | //------------------------------------------------------------------------------
// GB_unop: hard-coded functions for each built-in unary operator
//------------------------------------------------------------------------------
// SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2021, All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
//------------------------------------------------------------------------------
// If this file is in the Generated/ folder, do not edit it (auto-generated).
#include "GB.h"
#ifndef GBCOMPACT
#include "GB_control.h"
#include "GB_atomics.h"
#include "GB_unop__include.h"
// C=unop(A) is defined by the following types and operators:
// op(A) function: GB (_unop_apply__identity_uint8_uint64)
// op(A') function: GB (_unop_tran__identity_uint8_uint64)
// C type: uint8_t
// A type: uint64_t
// cast: uint8_t cij = (uint8_t) aij
// unaryop: cij = aij
#define GB_ATYPE \
uint64_t
#define GB_CTYPE \
uint8_t
// aij = Ax [pA]
#define GB_GETA(aij,Ax,pA) \
uint64_t aij = Ax [pA]
#define GB_CX(p) Cx [p]
// unary operator
#define GB_OP(z, x) \
z = x ;
// casting
#define GB_CAST(z, aij) \
uint8_t z = (uint8_t) aij ;
// cij = op (aij)
#define GB_CAST_OP(pC,pA) \
{ \
/* aij = Ax [pA] */ \
uint64_t aij = Ax [pA] ; \
/* Cx [pC] = op (cast (aij)) */ \
uint8_t z = (uint8_t) aij ; \
Cx [pC] = z ; \
}
// true if operator is the identity op with no typecasting
#define GB_OP_IS_IDENTITY_WITH_NO_TYPECAST \
0
// disable this operator and use the generic case if these conditions hold
#define GB_DISABLE \
(GxB_NO_IDENTITY || GxB_NO_UINT8 || GxB_NO_UINT64)
//------------------------------------------------------------------------------
// Cx = op (cast (Ax)): apply a unary operator
//------------------------------------------------------------------------------
GrB_Info GB (_unop_apply__identity_uint8_uint64)
(
uint8_t *Cx, // Cx and Ax may be aliased
const uint64_t *Ax,
const int8_t *restrict Ab, // A->b if A is bitmap
int64_t anz,
int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
int64_t p ;
// TODO: if OP is ONE and uniform-valued matrices are exploited, then
// do this in O(1) time
if (Ab == NULL)
{
#if ( GB_OP_IS_IDENTITY_WITH_NO_TYPECAST )
GB_memcpy (Cx, Ax, anz * sizeof (uint64_t), nthreads) ;
#else
#pragma omp parallel for num_threads(nthreads) schedule(static)
for (p = 0 ; p < anz ; p++)
{
uint64_t aij = Ax [p] ;
uint8_t z = (uint8_t) aij ;
Cx [p] = z ;
}
#endif
}
else
{
// bitmap case, no transpose; A->b already memcpy'd into C->b
#pragma omp parallel for num_threads(nthreads) schedule(static)
for (p = 0 ; p < anz ; p++)
{
if (!Ab [p]) continue ;
uint64_t aij = Ax [p] ;
uint8_t z = (uint8_t) aij ;
Cx [p] = z ;
}
}
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// C = op (cast (A')): transpose, typecast, and apply a unary operator
//------------------------------------------------------------------------------
GrB_Info GB (_unop_tran__identity_uint8_uint64)
(
GrB_Matrix C,
const GrB_Matrix A,
int64_t *restrict *Workspaces,
const int64_t *restrict A_slice,
int nworkspaces,
int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
#include "GB_unop_transpose.c"
return (GrB_SUCCESS) ;
#endif
}
#endif
|
matmul.c | //------------------------------------------------------------------------------------------------------------------------------
// Samuel Williams
// SWWilliams@lbl.gov
// Lawrence Berkeley National Lab
//------------------------------------------------------------------------------------------------------------------------------
void matmul(level_type * level, double *C, int * id_A, int * id_B, int rows, int cols, int A_equals_B_transpose){
// *id_A = m vector_id's (conceptually pointers to the rows of a m x level->num_my_boxes*volume matrix)
// *id_B = n vector_id's (conceptually pointers to the columns of a level->num_my_boxes*volume matrix x n)
// *C is a mxn matrix where C[rows][cols] = dot(id_A[rows],id_B[cols])
// FIX, id_A and id_B are likely the same and thus C[][] will be symmetric (modulo missing row?)
// if(A_equals_B_transpose && (cols>=rows)) then use id_B and only run for nn>=mm // common case for s-step Krylov methods
// C_is_symmetric && cols< rows (use id_A)
int omp_across_matrix = 1;
int omp_within_a_box = 0;
int mm,nn;
uint64_t _timeStart = CycleTime();
#pragma omp parallel for schedule(static,1) collapse(2)
for(mm=0;mm<rows;mm++){
for(nn=0;nn<cols;nn++){
if(nn>=mm){ // upper triangular
int box;
double a_dot_b_level = 0.0;
for(box=0;box<level->num_my_boxes;box++){
int i,j,k;
int jStride = level->my_boxes[box].jStride;
int kStride = level->my_boxes[box].kStride;
int ghosts = level->my_boxes[box].ghosts;
int dim = level->my_boxes[box].dim;
double * __restrict__ grid_a = level->my_boxes[box].vectors[id_A[mm]] + ghosts*(1+jStride+kStride); // i.e. [0] = first non ghost zone point
double * __restrict__ grid_b = level->my_boxes[box].vectors[id_B[nn]] + ghosts*(1+jStride+kStride);
double a_dot_b_box = 0.0;
for(k=0;k<dim;k++){
for(j=0;j<dim;j++){
for(i=0;i<dim;i++){
int ijk = i + j*jStride + k*kStride;
a_dot_b_box += grid_a[ijk]*grid_b[ijk];
}}}
a_dot_b_level+=a_dot_b_box;
}
C[mm*cols + nn] = a_dot_b_level; // C[mm][nn]
if((mm<cols)&&(nn<rows)){C[nn*cols + mm] = a_dot_b_level;}// C[nn][mm]
}
}}
level->cycles.blas3 += (uint64_t)(CycleTime()-_timeStart);
#ifdef USE_MPI
double *send_buffer = (double*)malloc(rows*cols*sizeof(double));
for(mm=0;mm<rows;mm++){
for(nn=0;nn<cols;nn++){
send_buffer[mm*cols + nn] = C[mm*cols + nn];
}}
uint64_t _timeStartAllReduce = CycleTime();
//MPI_Allreduce(send_buffer,C,rows*cols,MPI_DOUBLE,MPI_SUM,MPI_COMM_WORLD);
MPI_Allreduce(send_buffer,C,rows*cols,MPI_DOUBLE,MPI_SUM,level->MPI_COMM_ALLREDUCE);
uint64_t _timeEndAllReduce = CycleTime();
level->cycles.collectives += (uint64_t)(_timeEndAllReduce-_timeStartAllReduce);
free(send_buffer);
#endif
}
|
multiply.c | /*
Copyright 2005-2013 Intel Corporation. All Rights Reserved.
The source code contained or described herein and all documents related
to the source code ("Material") are owned by Intel Corporation or its
suppliers or licensors. Title to the Material remains with Intel
Corporation or its suppliers and licensors. The Material is protected
by worldwide copyright laws and treaty provisions. No part of the
Material may be used, copied, reproduced, modified, published, uploaded,
posted, transmitted, distributed, or disclosed in any way without
Intel's prior express written permission.
No license under any patent, copyright, trade secret or other
intellectual property right is granted to or conferred upon you by
disclosure or delivery of the Materials, either expressly, by
implication, inducement, estoppel or otherwise. Any license under such
intellectual property rights must be express and approved by Intel in
writing.
*/
// matrix multiply routines
#include "multiply.h"
void multiply0(int msize, int tidx, int numt, TYPE a[][NUM], TYPE b[][NUM], TYPE c[][NUM], TYPE t[][NUM])
{
int i,j,k;
// #pragma omp parallel for
for(i=0; i<msize; i++) {
for(j=0; j<msize; j++) {
for(k=0; k<msize; k++) {
c[i][j] = c[i][j] + a[i][k] * b[k][j];
}
}
}
}
|
organismsbuffer.h | #pragma once
#include "organism.h"
#include "rng.h"
#include <assert.h>
namespace NEAT {
template<typename TOrganism = Organism>
class OrganismsBuffer {
size_t _n;
std::vector<TOrganism> _a;
std::vector<TOrganism> _b;
std::vector<TOrganism> *_curr;
std::vector<TOrganism> *_prev;
public:
OrganismsBuffer(rng_t rng,
std::vector<std::unique_ptr<Genome>> &seeds,
size_t n,
size_t population_index = 0)
: _n(n) {
_a.reserve(n);
_b.reserve(n);
_curr = &_a;
_prev = &_b;
for(size_t i = 0; i < n; i++) {
_a.emplace_back(*seeds[i + population_index]);
size_t ipop = i + population_index;
_a[i].population_index = ipop;
_a[i].net->population_index = ipop;
_a[i].genome->genome_id = ipop;
_a[i].genome->rng.seed(rng.integer());
}
for(size_t i = 0; i < n; i++) {
_b.emplace_back(*seeds[i + population_index]);
size_t ipop = i + population_index;
_b[i].population_index = ipop;
_b[i].net->population_index = ipop;
_b[i].genome->genome_id = ipop;
_b[i].genome->rng.seed(rng.integer());
}
}
void init_phenotypes() {
#pragma omp parallel for
for(size_t i = 0; i < _n; i++) {
Organism &org = curr()[i];
org.genome->init_phenotype(*org.net);
}
}
size_t size(){
return _n;
}
std::vector<TOrganism> &curr() {
return *_curr;
}
std::vector<TOrganism> &prev() {
return *_prev;
}
void next_generation(int generation) {
if(_curr == &_a) {
_curr = &_b;
_prev = &_a;
} else {
_curr = &_a;
_prev = &_b;
}
assert( _curr->size() == _n );
for(TOrganism &org: curr())
org.init(generation);
}
};
}
|
train_share_states.h | /*!
* Copyright (c) 2016 Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See LICENSE file in the project root for license information.
*/
#ifndef LIGHTGBM_TRAIN_SHARE_STATES_H_
#define LIGHTGBM_TRAIN_SHARE_STATES_H_
#include <LightGBM/bin.h>
#include <LightGBM/feature_group.h>
#include <LightGBM/meta.h>
#include <LightGBM/utils/threading.h>
#include <algorithm>
#include <memory>
#include <vector>
namespace LightGBM {
class MultiValBinWrapper {
public:
MultiValBinWrapper(MultiValBin* bin, data_size_t num_data,
const std::vector<int>& feature_groups_contained);
bool IsSparse() {
if (multi_val_bin_ != nullptr) {
return multi_val_bin_->IsSparse();
}
return false;
}
void InitTrain(const std::vector<int>& group_feature_start,
const std::vector<std::unique_ptr<FeatureGroup>>& feature_groups,
const std::vector<int8_t>& is_feature_used,
const data_size_t* bagging_use_indices,
data_size_t bagging_indices_cnt);
void HistMove(const std::vector<hist_t, Common::AlignmentAllocator<hist_t, kAlignedSize>>& hist_buf);
void HistMerge(std::vector<hist_t, Common::AlignmentAllocator<hist_t, kAlignedSize>>* hist_buf);
void ResizeHistBuf(std::vector<hist_t, Common::AlignmentAllocator<hist_t, kAlignedSize>>* hist_buf,
MultiValBin* sub_multi_val_bin,
hist_t* origin_hist_data);
template <bool USE_INDICES, bool ORDERED>
void ConstructHistograms(const data_size_t* data_indices,
data_size_t num_data,
const score_t* gradients,
const score_t* hessians,
std::vector<hist_t, Common::AlignmentAllocator<hist_t, kAlignedSize>>* hist_buf,
hist_t* origin_hist_data) {
const auto cur_multi_val_bin = (is_use_subcol_ || is_use_subrow_)
? multi_val_bin_subset_.get()
: multi_val_bin_.get();
if (cur_multi_val_bin != nullptr) {
global_timer.Start("Dataset::sparse_bin_histogram");
n_data_block_ = 1;
data_block_size_ = num_data;
Threading::BlockInfo<data_size_t>(num_threads_, num_data, min_block_size_,
max_block_size_, &n_data_block_, &data_block_size_);
ResizeHistBuf(hist_buf, cur_multi_val_bin, origin_hist_data);
OMP_INIT_EX();
#pragma omp parallel for schedule(static) num_threads(num_threads_)
for (int block_id = 0; block_id < n_data_block_; ++block_id) {
OMP_LOOP_EX_BEGIN();
data_size_t start = block_id * data_block_size_;
data_size_t end = std::min<data_size_t>(start + data_block_size_, num_data);
ConstructHistogramsForBlock<USE_INDICES, ORDERED>(
cur_multi_val_bin, start, end, data_indices, gradients, hessians,
block_id, hist_buf);
OMP_LOOP_EX_END();
}
OMP_THROW_EX();
global_timer.Stop("Dataset::sparse_bin_histogram");
global_timer.Start("Dataset::sparse_bin_histogram_merge");
HistMerge(hist_buf);
global_timer.Stop("Dataset::sparse_bin_histogram_merge");
global_timer.Start("Dataset::sparse_bin_histogram_move");
HistMove(*hist_buf);
global_timer.Stop("Dataset::sparse_bin_histogram_move");
}
}
template <bool USE_INDICES, bool ORDERED>
void ConstructHistogramsForBlock(const MultiValBin* sub_multi_val_bin,
data_size_t start, data_size_t end, const data_size_t* data_indices,
const score_t* gradients, const score_t* hessians, int block_id,
std::vector<hist_t, Common::AlignmentAllocator<hist_t, kAlignedSize>>* hist_buf) {
hist_t* data_ptr = origin_hist_data_;
if (block_id == 0) {
if (is_use_subcol_) {
data_ptr = hist_buf->data() + hist_buf->size() - 2 * static_cast<size_t>(num_bin_aligned_);
}
} else {
data_ptr = hist_buf->data() +
static_cast<size_t>(num_bin_aligned_) * (block_id - 1) * 2;
}
std::memset(reinterpret_cast<void*>(data_ptr), 0, num_bin_ * kHistBufferEntrySize);
if (USE_INDICES) {
if (ORDERED) {
sub_multi_val_bin->ConstructHistogramOrdered(data_indices, start, end,
gradients, hessians, data_ptr);
} else {
sub_multi_val_bin->ConstructHistogram(data_indices, start, end, gradients,
hessians, data_ptr);
}
} else {
sub_multi_val_bin->ConstructHistogram(start, end, gradients, hessians,
data_ptr);
}
}
void CopyMultiValBinSubset(const std::vector<int>& group_feature_start,
const std::vector<std::unique_ptr<FeatureGroup>>& feature_groups,
const std::vector<int8_t>& is_feature_used,
const data_size_t* bagging_use_indices,
data_size_t bagging_indices_cnt);
void SetUseSubrow(bool is_use_subrow) {
is_use_subrow_ = is_use_subrow;
}
void SetSubrowCopied(bool is_subrow_copied) {
is_subrow_copied_ = is_subrow_copied;
}
private:
bool is_use_subcol_ = false;
bool is_use_subrow_ = false;
bool is_subrow_copied_ = false;
std::unique_ptr<MultiValBin> multi_val_bin_;
std::unique_ptr<MultiValBin> multi_val_bin_subset_;
std::vector<uint32_t> hist_move_src_;
std::vector<uint32_t> hist_move_dest_;
std::vector<uint32_t> hist_move_size_;
const std::vector<int> feature_groups_contained_;
int num_threads_;
int max_block_size_;
int num_bin_;
int num_bin_aligned_;
int n_data_block_;
int data_block_size_;
int min_block_size_;
int num_data_;
hist_t* origin_hist_data_;
const size_t kHistBufferEntrySize = 2 * sizeof(hist_t);
};
struct TrainingShareStates {
int num_threads = 0;
bool is_col_wise = true;
bool is_constant_hessian = true;
const data_size_t* bagging_use_indices;
data_size_t bagging_indices_cnt;
TrainingShareStates() {
multi_val_bin_wrapper_.reset(nullptr);
}
int num_hist_total_bin() { return num_hist_total_bin_; }
const std::vector<uint32_t>& feature_hist_offsets() { return feature_hist_offsets_; }
bool IsSparseRowwise() {
return (multi_val_bin_wrapper_ != nullptr && multi_val_bin_wrapper_->IsSparse());
}
void SetMultiValBin(MultiValBin* bin, data_size_t num_data,
const std::vector<std::unique_ptr<FeatureGroup>>& feature_groups,
bool dense_only, bool sparse_only);
void CalcBinOffsets(const std::vector<std::unique_ptr<FeatureGroup>>& feature_groups,
std::vector<uint32_t>* offsets, bool is_col_wise);
void InitTrain(const std::vector<int>& group_feature_start,
const std::vector<std::unique_ptr<FeatureGroup>>& feature_groups,
const std::vector<int8_t>& is_feature_used) {
if (multi_val_bin_wrapper_ != nullptr) {
multi_val_bin_wrapper_->InitTrain(group_feature_start,
feature_groups,
is_feature_used,
bagging_use_indices,
bagging_indices_cnt);
}
}
template <bool USE_INDICES, bool ORDERED>
void ConstructHistograms(const data_size_t* data_indices,
data_size_t num_data,
const score_t* gradients,
const score_t* hessians,
hist_t* hist_data) {
if (multi_val_bin_wrapper_ != nullptr) {
multi_val_bin_wrapper_->ConstructHistograms<USE_INDICES, ORDERED>(
data_indices, num_data, gradients, hessians, &hist_buf_, hist_data);
}
}
void SetUseSubrow(bool is_use_subrow) {
if (multi_val_bin_wrapper_ != nullptr) {
multi_val_bin_wrapper_->SetUseSubrow(is_use_subrow);
}
}
void SetSubrowCopied(bool is_subrow_copied) {
if (multi_val_bin_wrapper_ != nullptr) {
multi_val_bin_wrapper_->SetSubrowCopied(is_subrow_copied);
}
}
private:
std::vector<uint32_t> feature_hist_offsets_;
int num_hist_total_bin_ = 0;
std::unique_ptr<MultiValBinWrapper> multi_val_bin_wrapper_;
std::vector<hist_t, Common::AlignmentAllocator<hist_t, kAlignedSize>> hist_buf_;
int num_total_bin_ = 0;
double num_elements_per_row_ = 0.0f;
};
} // namespace LightGBM
#endif // LightGBM_TRAIN_SHARE_STATES_H_
|
SpatialClassNLLCriterion.c | #ifndef TH_GENERIC_FILE
#define TH_GENERIC_FILE "generic/SpatialClassNLLCriterion.c"
#else
#define INITIAL_CHECK \
THArgCheck(THIndexTensor_(nDimension)(target) == 3, 3, \
"only batches of spatial targets supported (3D tensors)" \
" but got targets of dimension: %d", \
THIndexTensor_(nDimension)(target)); \
THArgCheck(THTensor_(nDimension)(input) == 4, 2, \
"only batches of spatial inputs supported (4D tensors), " \
"but got input of dimension: %d", THTensor_(nDimension)(input)); \
if (weights && THTensor_(nElement)(weights) != THTensor_(size)(input, 1)) { \
THError("weight tensor should be defined either for all or no classes"); \
} \
\
{ \
int64_t input0 = THTensor_(size)(input, 0); \
int64_t input1 = THTensor_(size)(input, 1); \
int64_t input2 = THTensor_(size)(input, 2); \
int64_t input3 = THTensor_(size)(input, 3); \
int64_t target0 = THIndexTensor_(size)(target, 0); \
int64_t target1 = THIndexTensor_(size)(target, 1); \
int64_t target2 = THIndexTensor_(size)(target, 2); \
THAssertMsg(input0 == target0 && input2 == target1 && input3 == target2, \
"size mismatch (got input: %ldx%ldx%ldx%ld, target: %ldx%ldx%ld)", \
input0, input1, input2, input3, target0, target1, target2); \
}
void THNN_(SpatialClassNLLCriterion_updateOutput)(
THNNState *state,
THTensor *input,
THIndexTensor *target,
THTensor *output,
bool sizeAverage,
THTensor *weights,
THTensor *total_weight)
{
INITIAL_CHECK;
input = THTensor_(newContiguous)(input);
target = THIndexTensor_(newContiguous)(target);
weights = weights ? THTensor_(newContiguous)(weights) : NULL;
real *input_data = THTensor_(data)(input);
THIndex_t *target_data = THIndexTensor_(data)(target);
real *weights_data = weights ? THTensor_(data)(weights) : NULL;
real *output_data = THTensor_(data)(output);
real *total_weight_data = THTensor_(data)(total_weight);
int64_t batch_size = THTensor_(size)(input, 0);
int64_t n_classes = THTensor_(size)(input, 1);
int64_t map_size = THTensor_(size)(input, 2) * THTensor_(size)(input, 3);
int64_t sample_size = map_size * n_classes;
real total_weight_acc = 0;
real output_acc = 0;
for (int b = 0; b < batch_size; b++) {
for (int elem = 0; elem < map_size; elem++) {
int cur_target = target_data[b * map_size + elem] - TH_INDEX_BASE;
THAssert(cur_target >= 0 && cur_target < n_classes);
real cur_weight = weights ? weights_data[cur_target] : 1.0f;
total_weight_acc += cur_weight;
output_acc -= input_data[b * sample_size + cur_target * map_size + elem] * cur_weight;
}
}
*total_weight_data = total_weight_acc;
*output_data = output_acc;
if (sizeAverage && *total_weight_data)
*output_data /= *total_weight_data;
THTensor_(free)(input);
THIndexTensor_(free)(target);
if (weights)
THTensor_(free)(weights);
}
void THNN_(SpatialClassNLLCriterion_updateGradInput)(
THNNState *state,
THTensor *input,
THIndexTensor *target,
THTensor *gradInput,
bool sizeAverage,
THTensor *weights,
THTensor *total_weight)
{
INITIAL_CHECK;
THArgCheck(THTensor_(isContiguous)(gradInput), 4,
"gradInput must be contiguous");
real *total_weight_data = THTensor_(data)(total_weight);
if (*total_weight_data <= 0)
return;
target = THIndexTensor_(newContiguous)(target);
weights = weights ? THTensor_(newContiguous)(weights) : NULL;
THIndex_t *target_data = THIndexTensor_(data)(target);
real *weights_data = weights ? THTensor_(data)(weights) : NULL;
real *gradInput_data = THTensor_(data)(gradInput);
int64_t batch_size = THTensor_(size)(input, 0);
int64_t n_classes = THTensor_(size)(input, 1);
int64_t map_size = THTensor_(size)(input, 2) * THTensor_(size)(input, 3);
int64_t sample_size = map_size * n_classes;
real normalize = sizeAverage ? *total_weight_data : 1.0f;
int b;
#pragma omp parallel for
for (b = 0; b < batch_size; b++) {
int elem;
for (elem = 0; elem < map_size; elem++) {
int cur_target = target_data[b * map_size + elem] - TH_INDEX_BASE;
THAssert(cur_target >= 0 && cur_target < n_classes);
gradInput_data[b * sample_size + cur_target * map_size + elem] =
-(weights ? weights_data[cur_target] : 1.0f) / normalize;
}
}
THIndexTensor_(free)(target);
if (weights)
THTensor_(free)(weights);
}
#undef INITIAL_CHECK
#endif
|
image_random-inl.h | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
/*!
* \file image_random-inl.h
* \brief
* \author
*/
#ifndef MXNET_OPERATOR_IMAGE_IMAGE_RANDOM_INL_H_
#define MXNET_OPERATOR_IMAGE_IMAGE_RANDOM_INL_H_
#include <algorithm>
#include <cmath>
#include <limits>
#include <tuple>
#include <utility>
#include <vector>
#include "mxnet/base.h"
#include "../mxnet_op.h"
#include "../operator_common.h"
#if MXNET_USE_OPENCV
#include <opencv2/opencv.hpp>
#endif // MXNET_USE_OPENCV
namespace mxnet {
namespace op {
namespace image {
using namespace mshadow;
#if MXNET_USE_CUDA
// NOTE: Kernel launch/map was extremely costly.
// Hence, we use separate CUDA kernels for these operators.
template <typename DType, typename T1, typename T2>
void ToTensorImplCUDA(mshadow::Stream<gpu>* s,
const T1 input,
const T2 output,
const int req,
const float normalize_factor);
template <typename DType>
void NormalizeImplCUDA(mshadow::Stream<gpu>* s,
const DType* input,
DType* output,
const int req,
const int N,
const int C,
const int H,
const int W,
const float mean_d0,
const float mean_d1,
const float mean_d2,
const float std_d0,
const float std_d1,
const float std_d2);
template <typename DType>
void NormalizeBackwardImplCUDA(mshadow::Stream<gpu>* s,
const DType* out_grad,
DType* in_grad,
const int req,
const int N,
const int C,
const int H,
const int W,
const float std_d0,
const float std_d1,
const float std_d2);
#endif // MXNET_USE_CUDA
// Shape and Type inference for image to tensor operator
inline bool ToTensorShape(const nnvm::NodeAttrs& attrs,
mxnet::ShapeVector* in_attrs,
mxnet::ShapeVector* out_attrs) {
CHECK_EQ(in_attrs->size(), 1U);
CHECK_EQ(out_attrs->size(), 1U);
mxnet::TShape& shp = (*in_attrs)[0];
if (!shape_is_known(shp))
return false;
CHECK((shp.ndim() == 3) || (shp.ndim() == 4))
<< "Input image must have shape (height, width, channels), or "
<< "(N, height, width, channels) but got " << shp;
if (shp.ndim() == 3) {
SHAPE_ASSIGN_CHECK(*out_attrs, 0, mxnet::TShape({shp[2], shp[0], shp[1]}));
} else if (shp.ndim() == 4) {
SHAPE_ASSIGN_CHECK(*out_attrs, 0, mxnet::TShape({shp[0], shp[3], shp[1], shp[2]}));
}
return true;
}
inline bool ToTensorType(const nnvm::NodeAttrs& attrs,
std::vector<int>* in_attrs,
std::vector<int>* out_attrs) {
CHECK_EQ(in_attrs->size(), 1U);
CHECK_EQ(out_attrs->size(), 1U);
TYPE_ASSIGN_CHECK(*out_attrs, 0, mshadow::kFloat32);
return (*in_attrs)[0] != -1;
}
// Operator Implementation
template <typename DType, int req>
inline void ToTensor(float* out_data,
const DType* in_data,
const int length,
const int channels,
const float normalize_factor,
const int step) {
// Microsoft Visual C++ compiler does not support omp collapse
#ifdef _MSC_VER
#pragma omp parallel for
#else
#pragma omp parallel for collapse(2)
#endif // _MSC_VER
for (int c = 0; c < channels; ++c) {
for (int i = 0; i < length; ++i) {
KERNEL_ASSIGN(out_data[step + c * length + i],
req,
(in_data[step + i * channels + c]) / normalize_factor);
}
}
}
inline void ToTensorImpl(const std::vector<TBlob>& inputs,
const std::vector<TBlob>& outputs,
const std::vector<OpReqType>& req,
const int length,
const int channel,
const float normalize_factor,
const int step) {
MSHADOW_TYPE_SWITCH(inputs[0].type_flag_, DType, {
MXNET_ASSIGN_REQ_SWITCH(req[0], req_type, {
float* output = outputs[0].dptr<float>();
DType* input = inputs[0].dptr<DType>();
ToTensor<DType, req_type>(output, input, length, channel, normalize_factor, step);
});
});
}
template <typename xpu>
void ToTensorOpForward(const nnvm::NodeAttrs& attrs,
const OpContext& ctx,
const std::vector<TBlob>& inputs,
const std::vector<OpReqType>& req,
const std::vector<TBlob>& outputs) {
CHECK_EQ(inputs.size(), 1U);
CHECK_EQ(outputs.size(), 1U);
CHECK_EQ(req.size(), 1U);
// We do not use temp buffer when performance the operation.
// Hence, this check is necessary.
CHECK_EQ(req[0], kWriteTo) << "`to_tensor` does not support inplace updates";
const float normalize_factor = 255.0f;
if (std::is_same<xpu, gpu>::value) {
#if MXNET_USE_CUDA
mshadow::Stream<gpu>* s = ctx.get_stream<gpu>();
MSHADOW_TYPE_SWITCH(inputs[0].type_flag_, DType, {
MXNET_ASSIGN_REQ_SWITCH(req[0], req_type, {
if (inputs[0].ndim() == 3) {
Tensor<gpu, 3, DType> input = inputs[0].get<gpu, 3, DType>(s);
Tensor<gpu, 3, float> output = outputs[0].get<gpu, 3, float>(s);
ToTensorImplCUDA<DType, Tensor<gpu, 3, DType>, Tensor<gpu, 3, float>>(
s, input, output, req_type, normalize_factor);
} else {
Tensor<gpu, 4, DType> input = inputs[0].get<gpu, 4, DType>(s);
Tensor<gpu, 4, float> output = outputs[0].get<gpu, 4, float>(s);
ToTensorImplCUDA<DType, Tensor<gpu, 4, DType>, Tensor<gpu, 4, float>>(
s, input, output, req_type, normalize_factor);
}
});
});
#else
LOG(FATAL) << "Compile with USE_CUDA=1 to use ToTensor operator on GPU.";
#endif // MXNET_USE_CUDA
} else if (inputs[0].ndim() == 3) {
// 3D Input - (h, w, c)
const int length = inputs[0].shape_[0] * inputs[0].shape_[1];
const int channel = static_cast<int>(inputs[0].shape_[2]);
const int step = 0;
ToTensorImpl(inputs, outputs, req, length, channel, normalize_factor, step);
} else if (inputs[0].ndim() == 4) {
// 4D input (n, h, w, c)
const int batch_size = inputs[0].shape_[0];
const int length = inputs[0].shape_[1] * inputs[0].shape_[2];
const int channel = static_cast<int>(inputs[0].shape_[3]);
const int step = channel * length;
#pragma omp parallel for
for (auto n = 0; n < batch_size; ++n) {
ToTensorImpl(inputs, outputs, req, length, channel, normalize_factor, n * step);
}
}
}
struct NormalizeParam : public dmlc::Parameter<NormalizeParam> {
mxnet::Tuple<float> mean;
mxnet::Tuple<float> std;
DMLC_DECLARE_PARAMETER(NormalizeParam) {
DMLC_DECLARE_FIELD(mean)
.set_default(mxnet::Tuple<float>{0.0f, 0.0f, 0.0f, 0.0f})
.describe(
"Sequence of means for each channel. "
"Default value is 0.");
DMLC_DECLARE_FIELD(std)
.set_default(mxnet::Tuple<float>{1.0f, 1.0f, 1.0f, 1.0f})
.describe(
"Sequence of standard deviations for each channel. "
"Default value is 1.");
}
};
// Shape and Type inference for image Normalize operator
// Shape inference
inline bool NormalizeOpShape(const nnvm::NodeAttrs& attrs,
mxnet::ShapeVector* in_attrs,
mxnet::ShapeVector* out_attrs) {
const NormalizeParam& param = nnvm::get<NormalizeParam>(attrs.parsed);
const auto& dshape = (*in_attrs)[0];
if (!dshape.ndim())
return false;
CHECK((dshape.ndim() == 3) || (dshape.ndim() == 4))
<< "Input tensor must have shape (channels, height, width), or "
<< "(N, channels, height, width), but got " << dshape;
int nchannels = 0;
if (dshape.ndim() == 3) {
nchannels = dshape[0];
CHECK(nchannels == 3 || nchannels == 1)
<< "The first dimension of input tensor must be the channel dimension with "
<< "either 1 or 3 elements, but got input with shape " << dshape;
} else if (dshape.ndim() == 4) {
nchannels = dshape[1];
CHECK(nchannels == 3 || nchannels == 1)
<< "The second dimension of input tensor must be the channel dimension with "
<< "either 1 or 3 elements, but got input with shape " << dshape;
}
CHECK((param.mean.ndim() == 1) || (param.mean.ndim() == nchannels))
<< "Invalid mean for input with shape " << dshape << ". mean must have either 1 or "
<< nchannels << " elements, but got " << param.mean;
CHECK(param.std.ndim() == 1 || param.std.ndim() == nchannels)
<< "Invalid std for input with shape " << dshape << ". std must have either 1 or "
<< nchannels << " elements, but got " << param.std;
SHAPE_ASSIGN_CHECK(*out_attrs, 0, dshape);
return true;
}
// Type Inference
inline bool NormalizeOpType(const nnvm::NodeAttrs& attrs,
std::vector<int>* in_attrs,
std::vector<int>* out_attrs) {
CHECK_EQ(in_attrs->size(), 1U);
CHECK_EQ(out_attrs->size(), 1U);
TYPE_ASSIGN_CHECK(*out_attrs, 0, in_attrs->at(0));
TYPE_ASSIGN_CHECK(*in_attrs, 0, out_attrs->at(0));
return out_attrs->at(0) != -1;
}
template <typename DType, int req>
inline void Normalize(DType* out_data,
const DType* in_data,
const int length,
const int channels,
const int step,
const std::vector<float> mean,
const std::vector<float> std) {
// Microsoft Visual C++ compiler does not support omp collapse
#ifdef _MSC_VER
#pragma omp parallel for
#else
#pragma omp parallel for collapse(2)
#endif // _MSC_VER
for (int c = 0; c < channels; ++c) {
for (int i = 0; i < length; ++i) {
KERNEL_ASSIGN(out_data[step + c * length + i],
req,
(in_data[step + c * length + i] - mean[c]) / std[c]);
}
}
}
inline void NormalizeImpl(const std::vector<TBlob>& inputs,
const std::vector<TBlob>& outputs,
const std::vector<OpReqType>& req,
const int length,
const int channels,
const int step,
const std::vector<float> mean,
const std::vector<float> std) {
MSHADOW_TYPE_SWITCH(outputs[0].type_flag_, DType, {
MXNET_ASSIGN_REQ_SWITCH(req[0], req_type, {
DType* input = inputs[0].dptr<DType>();
DType* output = outputs[0].dptr<DType>();
Normalize<DType, req_type>(output, input, length, channels, step, mean, std);
});
});
}
template <typename xpu>
void NormalizeOpForward(const nnvm::NodeAttrs& attrs,
const OpContext& ctx,
const std::vector<TBlob>& inputs,
const std::vector<OpReqType>& req,
const std::vector<TBlob>& outputs) {
CHECK_EQ(inputs.size(), 1U);
CHECK_EQ(outputs.size(), 1U);
CHECK_EQ(req.size(), 1U);
const NormalizeParam& param = nnvm::get<NormalizeParam>(attrs.parsed);
// Mean and Std can be 1 or 3D only.
std::vector<float> mean(3);
std::vector<float> std(3);
if (param.mean.ndim() == 1) {
mean[0] = mean[1] = mean[2] = param.mean[0];
} else {
mean[0] = param.mean[0];
mean[1] = param.mean[1];
mean[2] = param.mean[2];
}
if (param.std.ndim() == 1) {
std[0] = std[1] = std[2] = param.std[0];
} else {
std[0] = param.std[0];
std[1] = param.std[1];
std[2] = param.std[2];
}
if (std::is_same<xpu, gpu>::value) {
#if MXNET_USE_CUDA
mshadow::Stream<gpu>* s = ctx.get_stream<gpu>();
MSHADOW_TYPE_SWITCH(inputs[0].type_flag_, DType, {
MXNET_ASSIGN_REQ_SWITCH(req[0], req_type, {
int N, C, H, W;
DType* input = nullptr;
DType* output = nullptr;
if (inputs[0].ndim() == 3) {
N = 1;
C = static_cast<int>(inputs[0].shape_[0]);
H = static_cast<int>(inputs[0].shape_[1]);
W = static_cast<int>(inputs[0].shape_[2]);
input = (inputs[0].get<gpu, 3, DType>(s)).dptr_;
output = (outputs[0].get<gpu, 3, DType>(s)).dptr_;
} else {
N = static_cast<int>(inputs[0].shape_[0]);
C = static_cast<int>(inputs[0].shape_[1]);
H = static_cast<int>(inputs[0].shape_[2]);
W = static_cast<int>(inputs[0].shape_[3]);
input = (inputs[0].get<gpu, 4, DType>(s)).dptr_;
output = (outputs[0].get<gpu, 4, DType>(s)).dptr_;
}
NormalizeImplCUDA<DType>(s,
input,
output,
req_type,
N,
C,
H,
W,
mean[0],
mean[1],
mean[2],
std[0],
std[1],
std[2]);
});
});
#else
LOG(FATAL) << "Compile with USE_CUDA=1 to use Normalize operator on GPU.";
#endif // MXNET_USE_CUDA
} else if (inputs[0].ndim() == 3) {
// 3D input (c, h, w)
const int length = inputs[0].shape_[1] * inputs[0].shape_[2];
const int channel = static_cast<int>(inputs[0].shape_[0]);
const int step = 0;
NormalizeImpl(inputs, outputs, req, length, channel, step, mean, std);
} else if (inputs[0].ndim() == 4) {
// 4D input (n, c, h, w)
const int batch_size = inputs[0].shape_[0];
const int length = inputs[0].shape_[2] * inputs[0].shape_[3];
const int channel = static_cast<int>(inputs[0].shape_[1]);
const int step = channel * length;
#pragma omp parallel for
for (auto n = 0; n < batch_size; ++n) {
NormalizeImpl(inputs, outputs, req, length, channel, n * step, mean, std);
}
}
}
// Backward function
template <typename DType, int req>
inline void NormalizeBackward(const DType* out_grad,
DType* in_grad,
const int length,
const int channels,
const int step,
const std::vector<float> std) {
// Microsoft Visual C++ compiler does not support omp collapse
#ifdef _MSC_VER
#pragma omp parallel for
#else
#pragma omp parallel for collapse(2)
#endif // _MSC_VER
for (int c = 0; c < channels; ++c) {
for (int i = 0; i < length; ++i) {
KERNEL_ASSIGN(
in_grad[step + c * length + i], req, out_grad[step + c * length + i] * (1.0 / std[c]));
}
}
}
inline void NormalizeBackwardImpl(const std::vector<TBlob>& inputs,
const std::vector<TBlob>& outputs,
const std::vector<OpReqType>& req,
const int length,
const int channels,
const int step,
const std::vector<float> std) {
MSHADOW_TYPE_SWITCH(outputs[0].type_flag_, DType, {
MXNET_ASSIGN_REQ_SWITCH(req[0], req_type, {
DType* out_grad = inputs[0].dptr<DType>();
DType* in_grad = outputs[0].dptr<DType>();
NormalizeBackward<DType, req_type>(out_grad, in_grad, length, channels, step, std);
});
});
}
template <typename xpu>
void NormalizeOpBackward(const nnvm::NodeAttrs& attrs,
const OpContext& ctx,
const std::vector<TBlob>& inputs,
const std::vector<OpReqType>& req,
const std::vector<TBlob>& outputs) {
CHECK_EQ(inputs.size(), 2U);
CHECK_EQ(outputs.size(), 1U);
CHECK_EQ(req.size(), 1U);
const NormalizeParam& param = nnvm::get<NormalizeParam>(attrs.parsed);
// Std can be 1 or 3D only.
std::vector<float> std(3);
if (param.std.ndim() == 1) {
std[0] = std[1] = std[2] = param.std[0];
} else {
std[0] = param.std[0];
std[1] = param.std[1];
std[2] = param.std[2];
}
// Note: inputs[0] is out_grad
const TBlob& in_data = inputs[1];
if (std::is_same<xpu, gpu>::value) {
#if MXNET_USE_CUDA
mshadow::Stream<gpu>* s = ctx.get_stream<gpu>();
MSHADOW_TYPE_SWITCH(outputs[0].type_flag_, DType, {
MXNET_ASSIGN_REQ_SWITCH(req[0], req_type, {
int N, C, H, W;
DType* in_grad = nullptr;
DType* out_grad = nullptr;
if (in_data.ndim() == 3) {
N = 1;
C = static_cast<int>(in_data.shape_[0]);
H = static_cast<int>(in_data.shape_[1]);
W = static_cast<int>(in_data.shape_[2]);
out_grad = (inputs[0].get<gpu, 3, DType>(s)).dptr_;
in_grad = (outputs[0].get<gpu, 3, DType>(s)).dptr_;
} else {
N = static_cast<int>(in_data.shape_[0]);
C = static_cast<int>(in_data.shape_[1]);
H = static_cast<int>(in_data.shape_[2]);
W = static_cast<int>(in_data.shape_[3]);
out_grad = (inputs[0].get<gpu, 4, DType>(s)).dptr_;
in_grad = (outputs[0].get<gpu, 4, DType>(s)).dptr_;
}
NormalizeBackwardImplCUDA<DType>(
s, out_grad, in_grad, req_type, N, C, H, W, std[0], std[1], std[2]);
});
});
#else
LOG(FATAL) << "Compile with USE_CUDA=1 to use Normalize backward operator on GPU.";
#endif // MXNET_USE_CUDA
} else if (in_data.ndim() == 3) {
// 3D input (c, h, w)
const int length = in_data.shape_[1] * in_data.shape_[2];
const int channel = static_cast<int>(in_data.shape_[0]);
const int step = 0;
NormalizeBackwardImpl(inputs, outputs, req, length, channel, step, std);
} else if (in_data.ndim() == 4) {
// 4D input (n, c, h, w)
const int batch_size = in_data.shape_[0];
const int length = in_data.shape_[2] * in_data.shape_[3];
const int channel = static_cast<int>(in_data.shape_[1]);
const int step = channel * length;
#pragma omp parallel for
for (auto n = 0; n < batch_size; ++n) {
NormalizeBackwardImpl(inputs, outputs, req, length, channel, n * step, std);
}
}
}
template <typename DType>
inline DType saturate_cast(const float& src) {
return static_cast<DType>(src);
}
template <>
inline uint8_t saturate_cast(const float& src) {
return std::min(std::max(src, 0.f), 255.f);
}
inline bool ImageShape(const nnvm::NodeAttrs& attrs,
mxnet::ShapeVector* in_attrs,
mxnet::ShapeVector* out_attrs) {
mxnet::TShape& dshape = (*in_attrs)[0];
CHECK_EQ(dshape.ndim(), 3) << "Input image must have shape (height, width, channels), but got "
<< dshape;
auto nchannels = dshape[dshape.ndim() - 1];
CHECK(nchannels == 3 || nchannels == 1)
<< "The last dimension of input image must be the channel dimension with "
<< "either 1 or 3 elements, but got input with shape " << dshape;
SHAPE_ASSIGN_CHECK(*out_attrs, 0, dshape);
return true;
}
template <typename DType, int axis>
void FlipImpl(const mxnet::TShape& shape, DType* src, DType* dst) {
int head = 1, mid = shape[axis], tail = 1;
for (int i = 0; i < axis; ++i)
head *= shape[i];
for (int i = axis + 1; i < shape.ndim(); ++i)
tail *= shape[i];
for (int i = 0; i < head; ++i) {
// if inplace flip, skip the mid point in axis, otherwise copy is required
int mid2 = (src == dst) ? mid >> 1 : (mid + 1) >> 1;
for (int j = 0; j < mid2; ++j) {
int idx1 = (i * mid + j) * tail;
int idx2 = idx1 + (mid - (j << 1) - 1) * tail;
for (int k = 0; k < tail; ++k, ++idx1, ++idx2) {
DType tmp = src[idx1];
dst[idx1] = src[idx2];
dst[idx2] = tmp;
}
}
}
}
inline void FlipLeftRight(const nnvm::NodeAttrs& attrs,
const OpContext& ctx,
const std::vector<TBlob>& inputs,
const std::vector<OpReqType>& req,
const std::vector<TBlob>& outputs) {
using namespace mshadow;
MSHADOW_TYPE_SWITCH(outputs[0].type_flag_, DType, {
FlipImpl<DType, 1>(inputs[0].shape_, inputs[0].dptr<DType>(), outputs[0].dptr<DType>());
});
}
inline void FlipTopBottom(const nnvm::NodeAttrs& attrs,
const OpContext& ctx,
const std::vector<TBlob>& inputs,
const std::vector<OpReqType>& req,
const std::vector<TBlob>& outputs) {
using namespace mshadow;
MSHADOW_TYPE_SWITCH(outputs[0].type_flag_, DType, {
FlipImpl<DType, 0>(inputs[0].shape_, inputs[0].dptr<DType>(), outputs[0].dptr<DType>());
});
}
struct RandomFlipParam : public dmlc::Parameter<RandomFlipParam> {
float p;
DMLC_DECLARE_PARAMETER(RandomFlipParam) {
DMLC_DECLARE_FIELD(p).set_default(0.5f).describe("The probablity of flipping the image.");
}
};
inline void RandomFlipLeftRight(const nnvm::NodeAttrs& attrs,
const OpContext& ctx,
const std::vector<TBlob>& inputs,
const std::vector<OpReqType>& req,
const std::vector<TBlob>& outputs) {
using namespace mshadow;
const RandomFlipParam& param = nnvm::get<RandomFlipParam>(attrs.parsed);
Stream<cpu>* s = ctx.get_stream<cpu>();
Random<cpu>* prnd = ctx.requested[0].get_random<cpu, float>(s);
std::normal_distribution<float> dist(0, 1);
MSHADOW_TYPE_SWITCH(outputs[0].type_flag_, DType, {
if (dist(prnd->GetRndEngine()) > param.p) {
if (outputs[0].dptr_ != inputs[0].dptr_) {
std::memcpy(outputs[0].dptr_, inputs[0].dptr_, inputs[0].Size() * sizeof(DType));
}
} else {
FlipImpl<DType, 1>(inputs[0].shape_, inputs[0].dptr<DType>(), outputs[0].dptr<DType>());
}
});
}
inline void RandomFlipTopBottom(const nnvm::NodeAttrs& attrs,
const OpContext& ctx,
const std::vector<TBlob>& inputs,
const std::vector<OpReqType>& req,
const std::vector<TBlob>& outputs) {
using namespace mshadow;
const RandomFlipParam& param = nnvm::get<RandomFlipParam>(attrs.parsed);
Stream<cpu>* s = ctx.get_stream<cpu>();
Random<cpu>* prnd = ctx.requested[0].get_random<cpu, float>(s);
std::normal_distribution<float> dist(0, 1);
MSHADOW_TYPE_SWITCH(outputs[0].type_flag_, DType, {
if (dist(prnd->GetRndEngine()) > param.p) {
if (outputs[0].dptr_ != inputs[0].dptr_) {
std::memcpy(outputs[0].dptr_, inputs[0].dptr_, inputs[0].Size() * sizeof(DType));
}
} else {
FlipImpl<DType, 0>(inputs[0].shape_, inputs[0].dptr<DType>(), outputs[0].dptr<DType>());
}
});
}
struct RandomEnhanceParam : public dmlc::Parameter<RandomEnhanceParam> {
float min_factor;
float max_factor;
DMLC_DECLARE_PARAMETER(RandomEnhanceParam) {
DMLC_DECLARE_FIELD(min_factor).set_lower_bound(0.0).describe("Minimum factor.");
DMLC_DECLARE_FIELD(max_factor).set_lower_bound(0.0).describe("Maximum factor.");
}
};
inline void AdjustBrightnessImpl(const float& alpha_b,
const OpContext& ctx,
const std::vector<TBlob>& inputs,
const std::vector<OpReqType>& req,
const std::vector<TBlob>& outputs) {
using namespace mshadow;
int length = inputs[0].Size();
MSHADOW_TYPE_SWITCH(outputs[0].type_flag_, DType, {
DType* output = outputs[0].dptr<DType>();
DType* input = inputs[0].dptr<DType>();
for (int l = 0; l < length; ++l) {
float val = static_cast<float>(input[l]) * alpha_b;
output[l] = saturate_cast<DType>(val);
}
});
}
inline void RandomBrightness(const nnvm::NodeAttrs& attrs,
const OpContext& ctx,
const std::vector<TBlob>& inputs,
const std::vector<OpReqType>& req,
const std::vector<TBlob>& outputs) {
using namespace mshadow;
const RandomEnhanceParam& param = nnvm::get<RandomEnhanceParam>(attrs.parsed);
Stream<cpu>* s = ctx.get_stream<cpu>();
Random<cpu>* prnd = ctx.requested[0].get_random<cpu, float>(s);
float alpha_b = std::uniform_real_distribution<float>(param.min_factor,
param.max_factor)(prnd->GetRndEngine());
AdjustBrightnessImpl(alpha_b, ctx, inputs, req, outputs);
}
inline void AdjustContrastImpl(const float& alpha_c,
const OpContext& ctx,
const std::vector<TBlob>& inputs,
const std::vector<OpReqType>& req,
const std::vector<TBlob>& outputs) {
using namespace mshadow;
static const float coef[] = {0.299f, 0.587f, 0.114f};
int length = inputs[0].shape_[0] * inputs[0].shape_[1];
int nchannels = inputs[0].shape_[2];
MSHADOW_TYPE_SWITCH(outputs[0].type_flag_, DType, {
DType* output = outputs[0].dptr<DType>();
DType* input = inputs[0].dptr<DType>();
float sum = 0.f;
if (nchannels > 1) {
for (int l = 0; l < length; ++l) {
for (int c = 0; c < 3; ++c)
sum += input[l * 3 + c] * coef[c];
}
} else {
for (int l = 0; l < length; ++l)
sum += input[l];
}
float gray_mean = sum / static_cast<float>(length);
float beta = (1 - alpha_c) * gray_mean;
for (int l = 0; l < length * nchannels; ++l) {
float val = input[l] * alpha_c + beta;
output[l] = saturate_cast<DType>(val);
}
});
}
inline void RandomContrast(const nnvm::NodeAttrs& attrs,
const OpContext& ctx,
const std::vector<TBlob>& inputs,
const std::vector<OpReqType>& req,
const std::vector<TBlob>& outputs) {
using namespace mshadow;
const RandomEnhanceParam& param = nnvm::get<RandomEnhanceParam>(attrs.parsed);
Stream<cpu>* s = ctx.get_stream<cpu>();
Random<cpu>* prnd = ctx.requested[0].get_random<cpu, real_t>(s);
float alpha_c = std::uniform_real_distribution<float>(param.min_factor,
param.max_factor)(prnd->GetRndEngine());
AdjustContrastImpl(alpha_c, ctx, inputs, req, outputs);
}
inline void AdjustSaturationImpl(const float& alpha_s,
const OpContext& ctx,
const std::vector<TBlob>& inputs,
const std::vector<OpReqType>& req,
const std::vector<TBlob>& outputs) {
static const float coef[] = {0.299f, 0.587f, 0.114f};
int length = inputs[0].shape_[0] * inputs[0].shape_[1];
int nchannels = inputs[0].shape_[2];
float alpha_o = 1.f - alpha_s;
MSHADOW_TYPE_SWITCH(outputs[0].type_flag_, DType, {
DType* output = outputs[0].dptr<DType>();
DType* input = inputs[0].dptr<DType>();
if (nchannels == 1) {
for (int l = 0; l < length; ++l)
output[l] = input[l];
return;
}
for (int l = 0; l < length; ++l) {
float gray = 0.f;
for (int c = 0; c < 3; ++c) {
gray = input[l * 3 + c] * coef[c];
}
gray *= alpha_o;
for (int c = 0; c < 3; ++c) {
float val = gray + input[l * 3 + c] * alpha_s;
output[l * 3 + c] = saturate_cast<DType>(val);
}
}
});
}
inline void RandomSaturation(const nnvm::NodeAttrs& attrs,
const OpContext& ctx,
const std::vector<TBlob>& inputs,
const std::vector<OpReqType>& req,
const std::vector<TBlob>& outputs) {
using namespace mshadow;
const RandomEnhanceParam& param = nnvm::get<RandomEnhanceParam>(attrs.parsed);
Stream<cpu>* s = ctx.get_stream<cpu>();
Random<cpu>* prnd = ctx.requested[0].get_random<cpu, real_t>(s);
float alpha_s = std::uniform_real_distribution<float>(param.min_factor,
param.max_factor)(prnd->GetRndEngine());
AdjustSaturationImpl(alpha_s, ctx, inputs, req, outputs);
}
inline void RGB2HLSConvert(const float& src_r,
const float& src_g,
const float& src_b,
float* dst_h,
float* dst_l,
float* dst_s) {
float b = src_b / 255.f, g = src_g / 255.f, r = src_r / 255.f;
float h = 0.f, s = 0.f, l;
float vmin;
float vmax;
float diff;
vmax = vmin = r;
vmax = std::fmax(vmax, g);
vmax = std::fmax(vmax, b);
vmin = std::fmin(vmin, g);
vmin = std::fmin(vmin, b);
diff = vmax - vmin;
l = (vmax + vmin) * 0.5f;
if (diff > std::numeric_limits<float>::epsilon()) {
s = (l < 0.5f) * diff / (vmax + vmin);
s += (l >= 0.5f) * diff / (2.0f - vmax - vmin);
diff = 60.f / diff;
h = (vmax == r) * (g - b) * diff;
h += (vmax != r && vmax == g) * ((b - r) * diff + 120.f);
h += (vmax != r && vmax != g) * ((r - g) * diff + 240.f);
h += (h < 0.f) * 360.f;
}
*dst_h = h;
*dst_l = l;
*dst_s = s;
}
inline void HLS2RGBConvert(const float& src_h,
const float& src_l,
const float& src_s,
float* dst_r,
float* dst_g,
float* dst_b) {
static const int c_HlsSectorData[6][3] = {
{1, 3, 0}, {1, 0, 2}, {3, 0, 1}, {0, 2, 1}, {0, 1, 3}, {2, 1, 0}};
float h = src_h, l = src_l, s = src_s;
float b = l, g = l, r = l;
if (s != 0) {
float p2 = (l <= 0.5f) * l * (1 + s);
p2 += (l > 0.5f) * (l + s - l * s);
float p1 = 2 * l - p2;
h *= 1.f / 60.f;
if (h < 0) {
do {
h += 6;
} while (h < 0);
}
if (h >= 6) { // h + 6 >= 6 holds true for some h < 0
do {
h -= 6;
} while (h >= 6);
}
int sector = static_cast<int>(h);
h -= sector;
float tab[4];
tab[0] = p2;
tab[1] = p1;
tab[2] = p1 + (p2 - p1) * (1 - h);
tab[3] = p1 + (p2 - p1) * h;
b = tab[c_HlsSectorData[sector][0]];
g = tab[c_HlsSectorData[sector][1]];
r = tab[c_HlsSectorData[sector][2]];
}
*dst_b = b * 255.f;
*dst_g = g * 255.f;
*dst_r = r * 255.f;
}
inline void AdjustHueImpl(float alpha,
const OpContext& ctx,
const std::vector<TBlob>& inputs,
const std::vector<OpReqType>& req,
const std::vector<TBlob>& outputs) {
int length = inputs[0].shape_[0] * inputs[0].shape_[1];
if (inputs[0].shape_[2] == 1)
return;
MSHADOW_TYPE_SWITCH(outputs[0].type_flag_, DType, {
DType* input = inputs[0].dptr<DType>();
DType* output = outputs[0].dptr<DType>();
for (int i = 0; i < length; ++i) {
float h, l, s;
float r = static_cast<float>(*(input++));
float g = static_cast<float>(*(input++));
float b = static_cast<float>(*(input++));
RGB2HLSConvert(r, g, b, &h, &l, &s);
h += alpha * 360.f;
HLS2RGBConvert(h, l, s, &r, &g, &b);
*(output++) = saturate_cast<DType>(r);
*(output++) = saturate_cast<DType>(g);
*(output++) = saturate_cast<DType>(b);
}
});
}
inline void RandomHue(const nnvm::NodeAttrs& attrs,
const OpContext& ctx,
const std::vector<TBlob>& inputs,
const std::vector<OpReqType>& req,
const std::vector<TBlob>& outputs) {
using namespace mshadow;
const RandomEnhanceParam& param = nnvm::get<RandomEnhanceParam>(attrs.parsed);
Stream<cpu>* s = ctx.get_stream<cpu>();
Random<cpu>* prnd = ctx.requested[0].get_random<cpu, real_t>(s);
float alpha = std::uniform_real_distribution<float>(param.min_factor,
param.max_factor)(prnd->GetRndEngine());
AdjustHueImpl(alpha, ctx, inputs, req, outputs);
}
struct RandomColorJitterParam : public dmlc::Parameter<RandomColorJitterParam> {
float brightness;
float contrast;
float saturation;
float hue;
DMLC_DECLARE_PARAMETER(RandomColorJitterParam) {
DMLC_DECLARE_FIELD(brightness).describe("How much to jitter brightness.");
DMLC_DECLARE_FIELD(contrast).describe("How much to jitter contrast.");
DMLC_DECLARE_FIELD(saturation).describe("How much to jitter saturation.");
DMLC_DECLARE_FIELD(hue).describe("How much to jitter hue.");
}
};
inline void RandomColorJitter(const nnvm::NodeAttrs& attrs,
const OpContext& ctx,
const std::vector<TBlob>& inputs,
const std::vector<OpReqType>& req,
const std::vector<TBlob>& outputs) {
using namespace mshadow;
const RandomColorJitterParam& param = nnvm::get<RandomColorJitterParam>(attrs.parsed);
Stream<cpu>* s = ctx.get_stream<cpu>();
Random<cpu>* prnd = ctx.requested[0].get_random<cpu, real_t>(s);
int order[4] = {0, 1, 2, 3};
std::shuffle(order, order + 4, prnd->GetRndEngine());
bool flag = false;
for (int i = 0; i < 4; ++i) {
switch (order[i]) {
case 0:
if (param.brightness > 0) {
float alpha_b = 1.0 + std::uniform_real_distribution<float>(
-param.brightness, param.brightness)(prnd->GetRndEngine());
AdjustBrightnessImpl(alpha_b, ctx, flag ? outputs : inputs, req, outputs);
flag = true;
}
break;
case 1:
if (param.contrast > 0) {
float alpha_c = 1.0 + std::uniform_real_distribution<float>(
-param.contrast, param.contrast)(prnd->GetRndEngine());
AdjustContrastImpl(alpha_c, ctx, flag ? outputs : inputs, req, outputs);
flag = true;
}
break;
case 2:
if (param.saturation > 0) {
float alpha_s = 1.f + std::uniform_real_distribution<float>(
-param.saturation, param.saturation)(prnd->GetRndEngine());
AdjustSaturationImpl(alpha_s, ctx, flag ? outputs : inputs, req, outputs);
flag = true;
}
break;
case 3:
if (param.hue > 0) {
float alpha_h =
std::uniform_real_distribution<float>(-param.hue, param.hue)(prnd->GetRndEngine());
AdjustHueImpl(alpha_h, ctx, flag ? outputs : inputs, req, outputs);
flag = true;
}
break;
}
}
}
struct AdjustLightingParam : public dmlc::Parameter<AdjustLightingParam> {
mxnet::Tuple<float> alpha;
DMLC_DECLARE_PARAMETER(AdjustLightingParam) {
DMLC_DECLARE_FIELD(alpha).describe("The lighting alphas for the R, G, B channels.");
}
};
struct RandomLightingParam : public dmlc::Parameter<RandomLightingParam> {
float alpha_std;
DMLC_DECLARE_PARAMETER(RandomLightingParam) {
DMLC_DECLARE_FIELD(alpha_std).set_default(0.05).describe("Level of the lighting noise.");
}
};
inline void AdjustLightingImpl(const mxnet::Tuple<float>& alpha,
const OpContext& ctx,
const std::vector<TBlob>& inputs,
const std::vector<OpReqType>& req,
const std::vector<TBlob>& outputs) {
static const float eig[3][3] = {{55.46 * -0.5675, 4.794 * 0.7192, 1.148 * 0.4009},
{55.46 * -0.5808, 4.794 * -0.0045, 1.148 * -0.8140},
{55.46 * -0.5836, 4.794 * -0.6948, 1.148 * 0.4203}};
int length = inputs[0].shape_[0] * inputs[0].shape_[1];
int channels = inputs[0].shape_[2];
if (channels == 1)
return;
float pca_r = eig[0][0] * alpha[0] + eig[0][1] * alpha[1] + eig[0][2] * alpha[2];
float pca_g = eig[1][0] * alpha[0] + eig[1][1] * alpha[1] + eig[1][2] * alpha[2];
float pca_b = eig[2][0] * alpha[0] + eig[2][1] * alpha[1] + eig[2][2] * alpha[2];
MSHADOW_TYPE_SWITCH(outputs[0].type_flag_, DType, {
DType* output = outputs[0].dptr<DType>();
DType* input = inputs[0].dptr<DType>();
for (int i = 0; i < length; i++) {
int base_ind = 3 * i;
float in_r = static_cast<float>(input[base_ind]);
float in_g = static_cast<float>(input[base_ind + 1]);
float in_b = static_cast<float>(input[base_ind + 2]);
output[base_ind] = saturate_cast<DType>(in_r + pca_r);
output[base_ind + 1] = saturate_cast<DType>(in_g + pca_g);
output[base_ind + 2] = saturate_cast<DType>(in_b + pca_b);
}
});
}
inline void AdjustLighting(const nnvm::NodeAttrs& attrs,
const OpContext& ctx,
const std::vector<TBlob>& inputs,
const std::vector<OpReqType>& req,
const std::vector<TBlob>& outputs) {
using namespace mshadow;
const AdjustLightingParam& param = nnvm::get<AdjustLightingParam>(attrs.parsed);
AdjustLightingImpl(param.alpha, ctx, inputs, req, outputs);
}
inline void RandomLighting(const nnvm::NodeAttrs& attrs,
const OpContext& ctx,
const std::vector<TBlob>& inputs,
const std::vector<OpReqType>& req,
const std::vector<TBlob>& outputs) {
using namespace mshadow;
const RandomLightingParam& param = nnvm::get<RandomLightingParam>(attrs.parsed);
Stream<cpu>* s = ctx.get_stream<cpu>();
Random<cpu>* prnd = ctx.requested[0].get_random<cpu, float>(s);
std::normal_distribution<float> dist(0, param.alpha_std);
float alpha_r = dist(prnd->GetRndEngine());
float alpha_g = dist(prnd->GetRndEngine());
float alpha_b = dist(prnd->GetRndEngine());
AdjustLightingImpl({alpha_r, alpha_g, alpha_b}, ctx, inputs, req, outputs);
}
#define MXNET_REGISTER_IMAGE_AUG_OP(name) \
NNVM_REGISTER_OP(name) \
.set_num_inputs(1) \
.set_num_outputs(1) \
.set_attr<nnvm::FInplaceOption>("FInplaceOption", \
[](const NodeAttrs& attrs) { \
return std::vector<std::pair<int, int>>{{0, 0}}; \
}) \
.set_attr<mxnet::FInferShape>("FInferShape", ImageShape) \
.set_attr<nnvm::FInferType>("FInferType", ElemwiseType<1, 1>) \
.set_attr<nnvm::FGradient>("FGradient", ElemwiseGradUseNone{"_copy"}) \
.add_argument("data", "NDArray-or-Symbol", "The input.")
#define MXNET_REGISTER_IMAGE_RND_AUG_OP(name) \
MXNET_REGISTER_IMAGE_AUG_OP(name).set_attr<FResourceRequest>( \
"FResourceRequest", [](const NodeAttrs& attrs) { \
return std::vector<ResourceRequest>{ResourceRequest::kRandom}; \
})
} // namespace image
} // namespace op
} // namespace mxnet
#endif // MXNET_OPERATOR_IMAGE_IMAGE_RANDOM_INL_H_
|
Cmrc_analysis_p.c | #include <Python.h>
#define NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION
#include "numpy/arrayobject.h"
#include <math.h>
// #include <fftw3.h>
#ifdef _OPENMP
#include <omp.h>
#endif
#define SQR(x) ((x)*(x))
#define MAX(x,y) ((x)>(y)?(x):(y))
#define MIN(x,y) ((x)<(y)?(x):(y))
static PyObject *Cgaussian(PyObject *self, PyObject *args, PyObject *kwargs)
{
PyArrayObject *m,*r;
int i,j,k,l;
double s=-10;
static char *kwlist[] = {"matrix", "sigma", "result", NULL};
if (!PyArg_ParseTupleAndKeywords(args, kwargs, "OdO", kwlist,
&m, &s, &r))
return Py_BuildValue("Os", Py_None,"Couldn't parse variable from C function.");
m=PyArray_GETCONTIGUOUS(m);
double *matrix = (double *) PyArray_DATA(m);
r=PyArray_GETCONTIGUOUS(r);
double *result = (double *) PyArray_DATA(r);
int shape[3]={PyArray_DIM(m,0),PyArray_DIM(m,1),PyArray_DIM(m,2)};
double ss=SQR(s);
int sl=(int)(s*4+0.5);
if ((sl>shape[0])|(sl>shape[1])|(sl>shape[2])){
Py_XDECREF(r);
Py_XDECREF(m);
result=NULL;matrix=NULL;
return Py_BuildValue("Os", Py_None,"Sigma is too big for the matrix.");
}
double *temp= (double *)malloc(shape[0]*shape[1]*shape[2]*sizeof(double));
double *weight=(double *)malloc((sl+1)*sizeof(double)),sum=1.;
weight[0]=1.;
for (i=1;i<=sl;i++){
weight[i]=exp(-0.5*SQR(i)/ss);
sum+=2*weight[i];
}
for (i=0;i<sl+1;i++){
weight[i]/=sum;
}
#define matrix(i,j,k) matrix[((i)*shape[1]+(j))*shape[2]+(k)]
#define result(i,j,k) result[((i)*shape[1]+(j))*shape[2]+(k)]
#define temp(i,j,k) temp[((i)*shape[1]+(j))*shape[2]+(k)]
int index1,index2,index3;
double *pp=NULL,*rpp=NULL;
int tempstep=shape[1]*shape[2],ttstep=shape[0]*shape[1]*shape[2];
int *indhere=(int *)malloc((sl+1)*sizeof(int)),*indhere1=(int *)malloc((sl+1)*sizeof(int));
// filter last dimension
for (i=0;i<=sl;i++){
indhere1[i]=-i+shape[2];
}
#pragma omp parallel for schedule(guided) private(j,k,l,index1,index2,index3) firstprivate(sl,weight,pp,rpp)
for (i=0;i<shape[0];i++){
index1=i*tempstep;
for (j=0;j<shape[1];j++){
index2=index1+j*shape[2];
for (k=0;k<sl;k++){
index3=index2+k;
pp=matrix+index3;
rpp=result+index3;
rpp[0]=weight[0]*pp[0];
for (l=-sl;l<-k;l++) rpp[0]+=weight[-l]*pp[indhere1[-l]];
for (l=-k;l<0;l++) rpp[0]+=weight[-l]*pp[l];
for (l=1;l<=sl;l++) rpp[0]+=weight[l]*pp[l];
}
for (k=sl;k<shape[2]-sl;k++){
index3=index2+k;
pp=matrix+index3;
rpp=result+index3;
rpp[0]=weight[0]*pp[0];
for (l=1;l<=sl;l++) rpp[0]+=weight[l]*(pp[-l]+pp[l]);
}
for (k=shape[2]-sl;k<shape[2];k++){
index3=index2+k;
pp=matrix+index3;
rpp=result+index3;
rpp[0]=weight[0]*pp[0];
for (l=-sl;l<0;l++) rpp[0]+=weight[-l]*pp[l];
for (l=1;l<shape[2]-k;l++) rpp[0]+=weight[l]*pp[l];
for (l=shape[2]-k;l<=sl;l++) rpp[0]+=weight[l]*pp[-indhere1[l]];
}
}
}
memcpy(temp,result,shape[0]*shape[1]*shape[2]*sizeof(double));
// filter second dimension
for (i=0;i<=sl;i++){
indhere[i]=i*shape[2];
indhere1[i]=indhere[i]-tempstep;
}
#pragma omp parallel for schedule(guided) private(j,k,l,index1,index2,index3) firstprivate(sl,weight,pp,rpp)
for (i=0;i<shape[0];i++){
index1=i*tempstep;
for (k=0;k<shape[2];k++){
index2=index1+k;
for (j=0;j<sl;j++){
index3=index2+j*shape[2];
pp=temp+index3;
rpp=result+index3;
rpp[0]=weight[0]*pp[0];
for (l=-sl;l<-j;l++) rpp[0]+=weight[-l]*pp[-indhere1[-l]];
for (l=-j;l<0;l++) rpp[0]+=weight[-l]*pp[-indhere[-l]];
for (l=1;l<=sl;l++) rpp[0]+=weight[l]*pp[indhere[l]];
}
for (j=sl;j<shape[1]-sl;j++){
index3=index2+j*shape[2];
pp=temp+index3;
rpp=result+index3;
rpp[0]=weight[0]*pp[0];
for (l=1;l<=sl;l++) rpp[0]+=weight[l]*(pp[-indhere[l]]+pp[indhere[l]]);
}
for (j=shape[1]-sl;j<shape[1];j++){
index3=index2+j*shape[2];
pp=temp+index3;
rpp=result+index3;
rpp[0]=weight[0]*pp[0];
for (l=-sl;l<0;l++) rpp[0]+=weight[-l]*pp[-indhere[-l]];
for (l=1;l<shape[1]-j;l++) rpp[0]+=weight[l]*pp[indhere[l]];
for (l=shape[1]-j;l<=sl;l++) rpp[0]+=weight[l]*pp[indhere1[l]];
}
}
}
// filter the first dimension
memcpy(temp,result,shape[0]*shape[1]*shape[2]*sizeof(double));
for (i=0;i<=sl;i++){
indhere[i]=i*tempstep;
indhere1[i]=indhere[i]-ttstep;
}
#pragma omp parallel for schedule(guided) private(i,k,l,index1,index2,index3) firstprivate(sl,weight,pp,rpp)
for (j=0;j<shape[1];j++){
index1=j*shape[2];
for (k=0;k<shape[2];k++){
index2=index1+k;
for (i=0;i<sl;i++){
index3=index2+i*tempstep;
pp=temp+index3;
rpp=result+index3;
rpp[0]=weight[0]*pp[0];
for (l=-sl;l<-i;l++) rpp[0]+=weight[-l]*pp[-indhere1[-l]];
for (l=-i;l<0;l++) rpp[0]+=weight[-l]*pp[-indhere[-l]];
for (l=1;l<=sl;l++) rpp[0]+=weight[l]*pp[indhere[l]];
}
for (i=sl;i<shape[0]-sl;i++){
index3=index2+i*tempstep;
pp=temp+index3;
rpp=result+index3;
rpp[0]=weight[0]*pp[0];
for (l=1;l<=sl;l++) rpp[0]+=weight[l]*(pp[-indhere[l]]+pp[indhere[l]]);
}
for (i=shape[0]-sl;i<shape[0];i++){
index3=index2+i*tempstep;
pp=temp+index3;
rpp=result+index3;
rpp[0]=weight[0]*pp[0];
for (l=-sl;l<0;l++) rpp[0]+=weight[-l]*pp[-indhere[-l]];
for (l=1;l<shape[0]-i;l++) rpp[0]+=weight[l]*pp[indhere[l]];
for (l=shape[0]-i;l<=sl;l++) rpp[0]+=weight[l]*pp[indhere1[l]];
}
}
}
#undef matrix
#undef result
#undef temp
free(indhere);
free(indhere1);
free(temp);
free(weight);
Py_XDECREF(r);
Py_XDECREF(m);
result=NULL;
matrix=NULL;
pp=NULL;
return Py_BuildValue("O", r);
}
static PyMethodDef Cmrc_analysis_p_methods[] = {
{"Cgaussian", (PyCFunction)Cgaussian,
METH_VARARGS | METH_KEYWORDS,
"Perform Gaussian filter to 3D map.\n"},
{NULL, NULL, 0, NULL}
};
#if PY_MAJOR_VERSION >= 3
static struct PyModuleDef Cmrc_analysis_pmodule = {
PyModuleDef_HEAD_INIT,
"Cmrc_analysis_p",
"MRC analysis tools with parallel.",
-1,
Cmrc_analysis_p_methods,
};
PyMODINIT_FUNC PyInit_Cmrc_analysis_p(void) {
import_array();
return PyModule_Create(&Cmrc_analysis_pmodule);
}
#else
PyMODINIT_FUNC initCmrc_analysis_p(void) {
Py_InitModule3("Cmrc_analysis_p", Cmrc_analysis_p_methods,
"MRC analysis tools.");
import_array();
}
#endif |
pbvh.c | /*
* $Id: pbvh.c 40539 2011-09-25 12:33:51Z ender79 $
*
* ***** BEGIN GPL LICENSE BLOCK *****
*
* 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.
*
* ***** END GPL LICENSE BLOCK *****
*/
/** \file blender/blenlib/intern/pbvh.c
* \ingroup bli
*/
#include "DNA_meshdata_types.h"
#include "MEM_guardedalloc.h"
#include "BLI_math.h"
#include "BLI_utildefines.h"
#include "BLI_ghash.h"
#include "BLI_pbvh.h"
#include "BKE_DerivedMesh.h"
#include "BKE_mesh.h" /* for mesh_calc_normals */
#include "BKE_global.h" /* for mesh_calc_normals */
#include "GPU_buffers.h"
#define LEAF_LIMIT 10000
//#define PERFCNTRS
/* Bitmap */
typedef char* BLI_bitmap;
static BLI_bitmap BLI_bitmap_new(int tot)
{
return MEM_callocN((tot >> 3) + 1, "BLI bitmap");
}
static int BLI_bitmap_get(BLI_bitmap b, int index)
{
return b[index >> 3] & (1 << (index & 7));
}
static void BLI_bitmap_set(BLI_bitmap b, int index)
{
b[index >> 3] |= (1 << (index & 7));
}
#if 0 /* UNUSED */
static void BLI_bitmap_clear(BLI_bitmap b, int index)
{
b[index >> 3] &= ~(1 << (index & 7));
}
#endif
/* Axis-aligned bounding box */
typedef struct {
float bmin[3], bmax[3];
} BB;
/* Axis-aligned bounding box with centroid */
typedef struct {
float bmin[3], bmax[3], bcentroid[3];
} BBC;
struct PBVHNode {
/* Opaque handle for drawing code */
void *draw_buffers;
/* Voxel bounds */
BB vb;
BB orig_vb;
/* For internal nodes, the offset of the children in the PBVH
'nodes' array. */
int children_offset;
/* Pointer into the PBVH prim_indices array and the number of
primitives used by this leaf node.
Used for leaf nodes in both mesh- and multires-based PBVHs.
*/
int *prim_indices;
unsigned int totprim;
/* Array of indices into the mesh's MVert array. Contains the
indices of all vertices used by faces that are within this
node's bounding box.
Note that a vertex might be used by a multiple faces, and
these faces might be in different leaf nodes. Such a vertex
will appear in the vert_indices array of each of those leaf
nodes.
In order to support cases where you want access to multiple
nodes' vertices without duplication, the vert_indices array
is ordered such that the first part of the array, up to
index 'uniq_verts', contains "unique" vertex indices. These
vertices might not be truly unique to this node, but if
they appear in another node's vert_indices array, they will
be above that node's 'uniq_verts' value.
Used for leaf nodes in a mesh-based PBVH (not multires.)
*/
int *vert_indices;
unsigned int uniq_verts, face_verts;
/* An array mapping face corners into the vert_indices
array. The array is sized to match 'totprim', and each of
the face's corners gets an index into the vert_indices
array, in the same order as the corners in the original
MFace. The fourth value should not be used if the original
face is a triangle.
Used for leaf nodes in a mesh-based PBVH (not multires.)
*/
int (*face_vert_indices)[4];
/* Indicates whether this node is a leaf or not; also used for
marking various updates that need to be applied. */
PBVHNodeFlags flag : 8;
/* Used for raycasting: how close bb is to the ray point. */
float tmin;
int proxy_count;
PBVHProxyNode* proxies;
};
struct PBVH {
PBVHNode *nodes;
int node_mem_count, totnode;
int *prim_indices;
int totprim;
int totvert;
int leaf_limit;
/* Mesh data */
MVert *verts;
MFace *faces;
/* Grid Data */
DMGridData **grids;
DMGridAdjacency *gridadj;
void **gridfaces;
int totgrid;
int gridsize;
/* Only used during BVH build and update,
don't need to remain valid after */
BLI_bitmap vert_bitmap;
#ifdef PERFCNTRS
int perf_modified;
#endif
/* flag are verts/faces deformed */
int deformed;
};
#define STACK_FIXED_DEPTH 100
typedef struct PBVHStack {
PBVHNode *node;
int revisiting;
} PBVHStack;
typedef struct PBVHIter {
PBVH *bvh;
BLI_pbvh_SearchCallback scb;
void *search_data;
PBVHStack *stack;
int stacksize;
PBVHStack stackfixed[STACK_FIXED_DEPTH];
int stackspace;
} PBVHIter;
static void BB_reset(BB *bb)
{
bb->bmin[0] = bb->bmin[1] = bb->bmin[2] = FLT_MAX;
bb->bmax[0] = bb->bmax[1] = bb->bmax[2] = -FLT_MAX;
}
/* Expand the bounding box to include a new coordinate */
static void BB_expand(BB *bb, float co[3])
{
int i;
for(i = 0; i < 3; ++i) {
bb->bmin[i] = MIN2(bb->bmin[i], co[i]);
bb->bmax[i] = MAX2(bb->bmax[i], co[i]);
}
}
/* Expand the bounding box to include another bounding box */
static void BB_expand_with_bb(BB *bb, BB *bb2)
{
int i;
for(i = 0; i < 3; ++i) {
bb->bmin[i] = MIN2(bb->bmin[i], bb2->bmin[i]);
bb->bmax[i] = MAX2(bb->bmax[i], bb2->bmax[i]);
}
}
/* Return 0, 1, or 2 to indicate the widest axis of the bounding box */
static int BB_widest_axis(BB *bb)
{
float dim[3];
int i;
for(i = 0; i < 3; ++i)
dim[i] = bb->bmax[i] - bb->bmin[i];
if(dim[0] > dim[1]) {
if(dim[0] > dim[2])
return 0;
else
return 2;
}
else {
if(dim[1] > dim[2])
return 1;
else
return 2;
}
}
static void BBC_update_centroid(BBC *bbc)
{
int i;
for(i = 0; i < 3; ++i)
bbc->bcentroid[i] = (bbc->bmin[i] + bbc->bmax[i]) * 0.5f;
}
/* Not recursive */
static void update_node_vb(PBVH *bvh, PBVHNode *node)
{
BB vb;
BB_reset(&vb);
if(node->flag & PBVH_Leaf) {
PBVHVertexIter vd;
BLI_pbvh_vertex_iter_begin(bvh, node, vd, PBVH_ITER_ALL) {
BB_expand(&vb, vd.co);
}
BLI_pbvh_vertex_iter_end;
}
else {
BB_expand_with_bb(&vb,
&bvh->nodes[node->children_offset].vb);
BB_expand_with_bb(&vb,
&bvh->nodes[node->children_offset + 1].vb);
}
node->vb= vb;
}
//void BLI_pbvh_node_BB_reset(PBVHNode* node)
//{
// BB_reset(&node->vb);
//}
//
//void BLI_pbvh_node_BB_expand(PBVHNode* node, float co[3])
//{
// BB_expand(&node->vb, co);
//}
/* Adapted from BLI_kdopbvh.c */
/* Returns the index of the first element on the right of the partition */
static int partition_indices(int *prim_indices, int lo, int hi, int axis,
float mid, BBC *prim_bbc)
{
int i=lo, j=hi;
for(;;) {
for(; prim_bbc[prim_indices[i]].bcentroid[axis] < mid; i++);
for(; mid < prim_bbc[prim_indices[j]].bcentroid[axis]; j--);
if(!(i < j))
return i;
SWAP(int, prim_indices[i], prim_indices[j]);
i++;
}
}
static void check_partitioning(int *prim_indices, int lo, int hi, int axis,
float mid, BBC *prim_bbc, int index_of_2nd_partition)
{
int i;
for(i = lo; i <= hi; ++i) {
const float c = prim_bbc[prim_indices[i]].bcentroid[axis];
if((i < index_of_2nd_partition && c > mid) ||
(i > index_of_2nd_partition && c < mid)) {
printf("fail\n");
}
}
}
static void grow_nodes(PBVH *bvh, int totnode)
{
if(totnode > bvh->node_mem_count) {
PBVHNode *prev = bvh->nodes;
bvh->node_mem_count *= 1.33;
if(bvh->node_mem_count < totnode)
bvh->node_mem_count = totnode;
bvh->nodes = MEM_callocN(sizeof(PBVHNode) * bvh->node_mem_count,
"bvh nodes");
memcpy(bvh->nodes, prev, bvh->totnode * sizeof(PBVHNode));
MEM_freeN(prev);
}
bvh->totnode = totnode;
}
/* Add a vertex to the map, with a positive value for unique vertices and
a negative value for additional vertices */
static int map_insert_vert(PBVH *bvh, GHash *map,
unsigned int *face_verts,
unsigned int *uniq_verts, int vertex)
{
void *value, *key = SET_INT_IN_POINTER(vertex);
if(!BLI_ghash_haskey(map, key)) {
if(BLI_bitmap_get(bvh->vert_bitmap, vertex)) {
value = SET_INT_IN_POINTER(~(*face_verts));
++(*face_verts);
}
else {
BLI_bitmap_set(bvh->vert_bitmap, vertex);
value = SET_INT_IN_POINTER(*uniq_verts);
++(*uniq_verts);
}
BLI_ghash_insert(map, key, value);
return GET_INT_FROM_POINTER(value);
}
else
return GET_INT_FROM_POINTER(BLI_ghash_lookup(map, key));
}
/* Find vertices used by the faces in this node and update the draw buffers */
static void build_mesh_leaf_node(PBVH *bvh, PBVHNode *node)
{
GHashIterator *iter;
GHash *map;
int i, j, totface;
map = BLI_ghash_new(BLI_ghashutil_inthash, BLI_ghashutil_intcmp, "build_mesh_leaf_node gh");
node->uniq_verts = node->face_verts = 0;
totface= node->totprim;
node->face_vert_indices = MEM_callocN(sizeof(int) * 4*totface,
"bvh node face vert indices");
for(i = 0; i < totface; ++i) {
MFace *f = bvh->faces + node->prim_indices[i];
int sides = f->v4 ? 4 : 3;
for(j = 0; j < sides; ++j) {
node->face_vert_indices[i][j]=
map_insert_vert(bvh, map, &node->face_verts,
&node->uniq_verts, (&f->v1)[j]);
}
}
node->vert_indices = MEM_callocN(sizeof(int) *
(node->uniq_verts + node->face_verts),
"bvh node vert indices");
/* Build the vertex list, unique verts first */
for(iter = BLI_ghashIterator_new(map), i = 0;
!BLI_ghashIterator_isDone(iter);
BLI_ghashIterator_step(iter), ++i) {
void *value = BLI_ghashIterator_getValue(iter);
int ndx = GET_INT_FROM_POINTER(value);
if(ndx < 0)
ndx = -ndx + node->uniq_verts - 1;
node->vert_indices[ndx] =
GET_INT_FROM_POINTER(BLI_ghashIterator_getKey(iter));
}
BLI_ghashIterator_free(iter);
for(i = 0; i < totface; ++i) {
MFace *f = bvh->faces + node->prim_indices[i];
int sides = f->v4 ? 4 : 3;
for(j = 0; j < sides; ++j) {
if(node->face_vert_indices[i][j] < 0)
node->face_vert_indices[i][j]=
-node->face_vert_indices[i][j] +
node->uniq_verts - 1;
}
}
if(!G.background) {
node->draw_buffers =
GPU_build_mesh_buffers(map, bvh->verts, bvh->faces,
node->prim_indices,
node->totprim, node->vert_indices,
node->uniq_verts,
node->uniq_verts + node->face_verts);
}
node->flag |= PBVH_UpdateDrawBuffers;
BLI_ghash_free(map, NULL, NULL);
}
static void build_grids_leaf_node(PBVH *bvh, PBVHNode *node)
{
if(!G.background) {
node->draw_buffers =
GPU_build_grid_buffers(bvh->grids, node->prim_indices,
node->totprim, bvh->gridsize);
}
node->flag |= PBVH_UpdateDrawBuffers;
}
/* Recursively build a node in the tree
vb is the voxel box around all of the primitives contained in
this node.
cb is the bounding box around all the centroids of the primitives
contained in this node
offset and start indicate a range in the array of primitive indices
*/
static void build_sub(PBVH *bvh, int node_index, BB *cb, BBC *prim_bbc,
int offset, int count)
{
int i, axis, end;
BB cb_backing;
/* Decide whether this is a leaf or not */
// XXX adapt leaf limit for grids
if(count <= bvh->leaf_limit) {
bvh->nodes[node_index].flag |= PBVH_Leaf;
bvh->nodes[node_index].prim_indices = bvh->prim_indices + offset;
bvh->nodes[node_index].totprim = count;
/* Still need vb for searches */
BB_reset(&bvh->nodes[node_index].vb);
for(i = offset + count - 1; i >= offset; --i) {
BB_expand_with_bb(&bvh->nodes[node_index].vb,
(BB*)(prim_bbc +
bvh->prim_indices[i]));
}
if(bvh->faces)
build_mesh_leaf_node(bvh, bvh->nodes + node_index);
else
build_grids_leaf_node(bvh, bvh->nodes + node_index);
bvh->nodes[node_index].orig_vb= bvh->nodes[node_index].vb;
/* Done with this subtree */
return;
}
else {
BB_reset(&bvh->nodes[node_index].vb);
bvh->nodes[node_index].children_offset = bvh->totnode;
grow_nodes(bvh, bvh->totnode + 2);
if(!cb) {
cb = &cb_backing;
BB_reset(cb);
for(i = offset + count - 1; i >= offset; --i)
BB_expand(cb, prim_bbc[bvh->prim_indices[i]].bcentroid);
}
}
axis = BB_widest_axis(cb);
for(i = offset + count - 1; i >= offset; --i) {
BB_expand_with_bb(&bvh->nodes[node_index].vb,
(BB*)(prim_bbc + bvh->prim_indices[i]));
}
bvh->nodes[node_index].orig_vb= bvh->nodes[node_index].vb;
end = partition_indices(bvh->prim_indices, offset, offset + count - 1,
axis,
(cb->bmax[axis] + cb->bmin[axis]) * 0.5f,
prim_bbc);
check_partitioning(bvh->prim_indices, offset, offset + count - 1,
axis,
(cb->bmax[axis] + cb->bmin[axis]) * 0.5f,
prim_bbc, end);
build_sub(bvh, bvh->nodes[node_index].children_offset, NULL,
prim_bbc, offset, end - offset);
build_sub(bvh, bvh->nodes[node_index].children_offset + 1, NULL,
prim_bbc, end, offset + count - end);
}
static void pbvh_build(PBVH *bvh, BB *cb, BBC *prim_bbc, int totprim)
{
int i;
if(totprim != bvh->totprim) {
bvh->totprim = totprim;
if(bvh->nodes) MEM_freeN(bvh->nodes);
if(bvh->prim_indices) MEM_freeN(bvh->prim_indices);
bvh->prim_indices = MEM_callocN(sizeof(int) * totprim,
"bvh prim indices");
for(i = 0; i < totprim; ++i)
bvh->prim_indices[i] = i;
bvh->totnode = 0;
if(bvh->node_mem_count < 100) {
bvh->node_mem_count = 100;
bvh->nodes = MEM_callocN(sizeof(PBVHNode) *
bvh->node_mem_count,
"bvh initial nodes");
}
}
bvh->totnode = 1;
build_sub(bvh, 0, cb, prim_bbc, 0, totprim);
}
/* Do a full rebuild with on Mesh data structure */
void BLI_pbvh_build_mesh(PBVH *bvh, MFace *faces, MVert *verts, int totface, int totvert)
{
BBC *prim_bbc = NULL;
BB cb;
int i, j;
bvh->faces = faces;
bvh->verts = verts;
bvh->vert_bitmap = BLI_bitmap_new(totvert);
bvh->totvert = totvert;
bvh->leaf_limit = LEAF_LIMIT;
BB_reset(&cb);
/* For each face, store the AABB and the AABB centroid */
prim_bbc = MEM_mallocN(sizeof(BBC) * totface, "prim_bbc");
for(i = 0; i < totface; ++i) {
MFace *f = faces + i;
const int sides = f->v4 ? 4 : 3;
BBC *bbc = prim_bbc + i;
BB_reset((BB*)bbc);
for(j = 0; j < sides; ++j)
BB_expand((BB*)bbc, verts[(&f->v1)[j]].co);
BBC_update_centroid(bbc);
BB_expand(&cb, bbc->bcentroid);
}
if(totface)
pbvh_build(bvh, &cb, prim_bbc, totface);
MEM_freeN(prim_bbc);
MEM_freeN(bvh->vert_bitmap);
}
/* Do a full rebuild with on Grids data structure */
void BLI_pbvh_build_grids(PBVH *bvh, DMGridData **grids, DMGridAdjacency *gridadj,
int totgrid, int gridsize, void **gridfaces)
{
BBC *prim_bbc = NULL;
BB cb;
int i, j;
bvh->grids= grids;
bvh->gridadj= gridadj;
bvh->gridfaces= gridfaces;
bvh->totgrid= totgrid;
bvh->gridsize= gridsize;
bvh->leaf_limit = MAX2(LEAF_LIMIT/((gridsize-1)*(gridsize-1)), 1);
BB_reset(&cb);
/* For each grid, store the AABB and the AABB centroid */
prim_bbc = MEM_mallocN(sizeof(BBC) * totgrid, "prim_bbc");
for(i = 0; i < totgrid; ++i) {
DMGridData *grid= grids[i];
BBC *bbc = prim_bbc + i;
BB_reset((BB*)bbc);
for(j = 0; j < gridsize*gridsize; ++j)
BB_expand((BB*)bbc, grid[j].co);
BBC_update_centroid(bbc);
BB_expand(&cb, bbc->bcentroid);
}
if(totgrid)
pbvh_build(bvh, &cb, prim_bbc, totgrid);
MEM_freeN(prim_bbc);
}
PBVH *BLI_pbvh_new(void)
{
PBVH *bvh = MEM_callocN(sizeof(PBVH), "pbvh");
return bvh;
}
void BLI_pbvh_free(PBVH *bvh)
{
PBVHNode *node;
int i;
for(i = 0; i < bvh->totnode; ++i) {
node= &bvh->nodes[i];
if(node->flag & PBVH_Leaf) {
if(node->draw_buffers)
GPU_free_buffers(node->draw_buffers);
if(node->vert_indices)
MEM_freeN(node->vert_indices);
if(node->face_vert_indices)
MEM_freeN(node->face_vert_indices);
}
}
if (bvh->deformed) {
if (bvh->verts) {
/* if pbvh was deformed, new memory was allocated for verts/faces -- free it */
MEM_freeN(bvh->verts);
MEM_freeN(bvh->faces);
}
}
MEM_freeN(bvh->nodes);
MEM_freeN(bvh->prim_indices);
MEM_freeN(bvh);
}
static void pbvh_iter_begin(PBVHIter *iter, PBVH *bvh, BLI_pbvh_SearchCallback scb, void *search_data)
{
iter->bvh= bvh;
iter->scb= scb;
iter->search_data= search_data;
iter->stack= iter->stackfixed;
iter->stackspace= STACK_FIXED_DEPTH;
iter->stack[0].node= bvh->nodes;
iter->stack[0].revisiting= 0;
iter->stacksize= 1;
}
static void pbvh_iter_end(PBVHIter *iter)
{
if(iter->stackspace > STACK_FIXED_DEPTH)
MEM_freeN(iter->stack);
}
static void pbvh_stack_push(PBVHIter *iter, PBVHNode *node, int revisiting)
{
if(iter->stacksize == iter->stackspace) {
PBVHStack *newstack;
iter->stackspace *= 2;
newstack= MEM_callocN(sizeof(PBVHStack)*iter->stackspace, "PBVHStack");
memcpy(newstack, iter->stack, sizeof(PBVHStack)*iter->stacksize);
if(iter->stackspace > STACK_FIXED_DEPTH)
MEM_freeN(iter->stack);
iter->stack= newstack;
}
iter->stack[iter->stacksize].node= node;
iter->stack[iter->stacksize].revisiting= revisiting;
iter->stacksize++;
}
static PBVHNode *pbvh_iter_next(PBVHIter *iter)
{
PBVHNode *node;
int revisiting;
/* purpose here is to traverse tree, visiting child nodes before their
parents, this order is necessary for e.g. computing bounding boxes */
while(iter->stacksize) {
/* pop node */
iter->stacksize--;
node= iter->stack[iter->stacksize].node;
/* on a mesh with no faces this can happen
* can remove this check if we know meshes have at least 1 face */
if(node==NULL)
return NULL;
revisiting= iter->stack[iter->stacksize].revisiting;
/* revisiting node already checked */
if(revisiting)
return node;
if(iter->scb && !iter->scb(node, iter->search_data))
continue; /* don't traverse, outside of search zone */
if(node->flag & PBVH_Leaf) {
/* immediately hit leaf node */
return node;
}
else {
/* come back later when children are done */
pbvh_stack_push(iter, node, 1);
/* push two child nodes on the stack */
pbvh_stack_push(iter, iter->bvh->nodes+node->children_offset+1, 0);
pbvh_stack_push(iter, iter->bvh->nodes+node->children_offset, 0);
}
}
return NULL;
}
static PBVHNode *pbvh_iter_next_occluded(PBVHIter *iter)
{
PBVHNode *node;
while(iter->stacksize) {
/* pop node */
iter->stacksize--;
node= iter->stack[iter->stacksize].node;
/* on a mesh with no faces this can happen
* can remove this check if we know meshes have at least 1 face */
if(node==NULL) return NULL;
if(iter->scb && !iter->scb(node, iter->search_data)) continue; /* don't traverse, outside of search zone */
if(node->flag & PBVH_Leaf) {
/* immediately hit leaf node */
return node;
}
else {
pbvh_stack_push(iter, iter->bvh->nodes+node->children_offset+1, 0);
pbvh_stack_push(iter, iter->bvh->nodes+node->children_offset, 0);
}
}
return NULL;
}
void BLI_pbvh_search_gather(PBVH *bvh,
BLI_pbvh_SearchCallback scb, void *search_data,
PBVHNode ***r_array, int *r_tot)
{
PBVHIter iter;
PBVHNode **array= NULL, **newarray, *node;
int tot= 0, space= 0;
pbvh_iter_begin(&iter, bvh, scb, search_data);
while((node=pbvh_iter_next(&iter))) {
if(node->flag & PBVH_Leaf) {
if(tot == space) {
/* resize array if needed */
space= (tot == 0)? 32: space*2;
newarray= MEM_callocN(sizeof(PBVHNode)*space, "PBVHNodeSearch");
if(array) {
memcpy(newarray, array, sizeof(PBVHNode)*tot);
MEM_freeN(array);
}
array= newarray;
}
array[tot]= node;
tot++;
}
}
pbvh_iter_end(&iter);
if(tot == 0 && array) {
MEM_freeN(array);
array= NULL;
}
*r_array= array;
*r_tot= tot;
}
void BLI_pbvh_search_callback(PBVH *bvh,
BLI_pbvh_SearchCallback scb, void *search_data,
BLI_pbvh_HitCallback hcb, void *hit_data)
{
PBVHIter iter;
PBVHNode *node;
pbvh_iter_begin(&iter, bvh, scb, search_data);
while((node=pbvh_iter_next(&iter)))
if (node->flag & PBVH_Leaf)
hcb(node, hit_data);
pbvh_iter_end(&iter);
}
typedef struct node_tree {
PBVHNode* data;
struct node_tree* left;
struct node_tree* right;
} node_tree;
static void node_tree_insert(node_tree* tree, node_tree* new_node)
{
if (new_node->data->tmin < tree->data->tmin) {
if (tree->left) {
node_tree_insert(tree->left, new_node);
}
else {
tree->left = new_node;
}
}
else {
if (tree->right) {
node_tree_insert(tree->right, new_node);
}
else {
tree->right = new_node;
}
}
}
static void traverse_tree(node_tree* tree, BLI_pbvh_HitOccludedCallback hcb, void* hit_data, float* tmin)
{
if (tree->left) traverse_tree(tree->left, hcb, hit_data, tmin);
hcb(tree->data, hit_data, tmin);
if (tree->right) traverse_tree(tree->right, hcb, hit_data, tmin);
}
static void free_tree(node_tree* tree)
{
if (tree->left) {
free_tree(tree->left);
tree->left = 0;
}
if (tree->right) {
free_tree(tree->right);
tree->right = 0;
}
free(tree);
}
float BLI_pbvh_node_get_tmin(PBVHNode* node)
{
return node->tmin;
}
static void BLI_pbvh_search_callback_occluded(PBVH *bvh,
BLI_pbvh_SearchCallback scb, void *search_data,
BLI_pbvh_HitOccludedCallback hcb, void *hit_data)
{
PBVHIter iter;
PBVHNode *node;
node_tree *tree = 0;
pbvh_iter_begin(&iter, bvh, scb, search_data);
while((node=pbvh_iter_next_occluded(&iter))) {
if(node->flag & PBVH_Leaf) {
node_tree* new_node = malloc(sizeof(node_tree));
new_node->data = node;
new_node->left = NULL;
new_node->right = NULL;
if (tree) {
node_tree_insert(tree, new_node);
}
else {
tree = new_node;
}
}
}
pbvh_iter_end(&iter);
if (tree) {
float tmin = FLT_MAX;
traverse_tree(tree, hcb, hit_data, &tmin);
free_tree(tree);
}
}
static int update_search_cb(PBVHNode *node, void *data_v)
{
int flag= GET_INT_FROM_POINTER(data_v);
if(node->flag & PBVH_Leaf)
return (node->flag & flag);
return 1;
}
static void pbvh_update_normals(PBVH *bvh, PBVHNode **nodes,
int totnode, float (*face_nors)[3])
{
float (*vnor)[3];
int n;
if(bvh->grids)
return;
/* could be per node to save some memory, but also means
we have to store for each vertex which node it is in */
vnor= MEM_callocN(sizeof(float)*3*bvh->totvert, "bvh temp vnors");
/* subtle assumptions:
- We know that for all edited vertices, the nodes with faces
adjacent to these vertices have been marked with PBVH_UpdateNormals.
This is true because if the vertex is inside the brush radius, the
bounding box of it's adjacent faces will be as well.
- However this is only true for the vertices that have actually been
edited, not for all vertices in the nodes marked for update, so we
can only update vertices marked with ME_VERT_PBVH_UPDATE.
*/
#pragma omp parallel for private(n) schedule(static)
for(n = 0; n < totnode; n++) {
PBVHNode *node= nodes[n];
if((node->flag & PBVH_UpdateNormals)) {
int i, j, totface, *faces;
faces= node->prim_indices;
totface= node->totprim;
for(i = 0; i < totface; ++i) {
MFace *f= bvh->faces + faces[i];
float fn[3];
unsigned int *fv = &f->v1;
int sides= (f->v4)? 4: 3;
if(f->v4)
normal_quad_v3(fn, bvh->verts[f->v1].co, bvh->verts[f->v2].co,
bvh->verts[f->v3].co, bvh->verts[f->v4].co);
else
normal_tri_v3(fn, bvh->verts[f->v1].co, bvh->verts[f->v2].co,
bvh->verts[f->v3].co);
for(j = 0; j < sides; ++j) {
int v= fv[j];
if(bvh->verts[v].flag & ME_VERT_PBVH_UPDATE) {
/* this seems like it could be very slow but profile
does not show this, so just leave it for now? */
#pragma omp atomic
vnor[v][0] += fn[0];
#pragma omp atomic
vnor[v][1] += fn[1];
#pragma omp atomic
vnor[v][2] += fn[2];
}
}
if(face_nors)
copy_v3_v3(face_nors[faces[i]], fn);
}
}
}
#pragma omp parallel for private(n) schedule(static)
for(n = 0; n < totnode; n++) {
PBVHNode *node= nodes[n];
if(node->flag & PBVH_UpdateNormals) {
int i, *verts, totvert;
verts= node->vert_indices;
totvert= node->uniq_verts;
for(i = 0; i < totvert; ++i) {
const int v = verts[i];
MVert *mvert= &bvh->verts[v];
if(mvert->flag & ME_VERT_PBVH_UPDATE) {
float no[3];
copy_v3_v3(no, vnor[v]);
normalize_v3(no);
mvert->no[0] = (short)(no[0]*32767.0f);
mvert->no[1] = (short)(no[1]*32767.0f);
mvert->no[2] = (short)(no[2]*32767.0f);
mvert->flag &= ~ME_VERT_PBVH_UPDATE;
}
}
node->flag &= ~PBVH_UpdateNormals;
}
}
MEM_freeN(vnor);
}
static void pbvh_update_BB_redraw(PBVH *bvh, PBVHNode **nodes,
int totnode, int flag)
{
int n;
/* update BB, redraw flag */
#pragma omp parallel for private(n) schedule(static)
for(n = 0; n < totnode; n++) {
PBVHNode *node= nodes[n];
if((flag & PBVH_UpdateBB) && (node->flag & PBVH_UpdateBB))
/* don't clear flag yet, leave it for flushing later */
update_node_vb(bvh, node);
if((flag & PBVH_UpdateOriginalBB) && (node->flag & PBVH_UpdateOriginalBB))
node->orig_vb= node->vb;
if((flag & PBVH_UpdateRedraw) && (node->flag & PBVH_UpdateRedraw))
node->flag &= ~PBVH_UpdateRedraw;
}
}
static void pbvh_update_draw_buffers(PBVH *bvh, PBVHNode **nodes, int totnode, int smooth)
{
PBVHNode *node;
int n;
/* can't be done in parallel with OpenGL */
for(n = 0; n < totnode; n++) {
node= nodes[n];
if(node->flag & PBVH_UpdateDrawBuffers) {
if(bvh->grids) {
GPU_update_grid_buffers(node->draw_buffers,
bvh->grids,
node->prim_indices,
node->totprim,
bvh->gridsize,
smooth);
}
else {
GPU_update_mesh_buffers(node->draw_buffers,
bvh->verts,
node->vert_indices,
node->uniq_verts +
node->face_verts);
}
node->flag &= ~PBVH_UpdateDrawBuffers;
}
}
}
static int pbvh_flush_bb(PBVH *bvh, PBVHNode *node, int flag)
{
int update= 0;
/* difficult to multithread well, we just do single threaded recursive */
if(node->flag & PBVH_Leaf) {
if(flag & PBVH_UpdateBB) {
update |= (node->flag & PBVH_UpdateBB);
node->flag &= ~PBVH_UpdateBB;
}
if(flag & PBVH_UpdateOriginalBB) {
update |= (node->flag & PBVH_UpdateOriginalBB);
node->flag &= ~PBVH_UpdateOriginalBB;
}
return update;
}
else {
update |= pbvh_flush_bb(bvh, bvh->nodes + node->children_offset, flag);
update |= pbvh_flush_bb(bvh, bvh->nodes + node->children_offset + 1, flag);
if(update & PBVH_UpdateBB)
update_node_vb(bvh, node);
if(update & PBVH_UpdateOriginalBB)
node->orig_vb= node->vb;
}
return update;
}
void BLI_pbvh_update(PBVH *bvh, int flag, float (*face_nors)[3])
{
PBVHNode **nodes;
int totnode;
BLI_pbvh_search_gather(bvh, update_search_cb, SET_INT_IN_POINTER(flag),
&nodes, &totnode);
if(flag & PBVH_UpdateNormals)
pbvh_update_normals(bvh, nodes, totnode, face_nors);
if(flag & (PBVH_UpdateBB|PBVH_UpdateOriginalBB|PBVH_UpdateRedraw))
pbvh_update_BB_redraw(bvh, nodes, totnode, flag);
if(flag & (PBVH_UpdateBB|PBVH_UpdateOriginalBB))
pbvh_flush_bb(bvh, bvh->nodes, flag);
if(nodes) MEM_freeN(nodes);
}
void BLI_pbvh_redraw_BB(PBVH *bvh, float bb_min[3], float bb_max[3])
{
PBVHIter iter;
PBVHNode *node;
BB bb;
BB_reset(&bb);
pbvh_iter_begin(&iter, bvh, NULL, NULL);
while((node=pbvh_iter_next(&iter)))
if(node->flag & PBVH_UpdateRedraw)
BB_expand_with_bb(&bb, &node->vb);
pbvh_iter_end(&iter);
copy_v3_v3(bb_min, bb.bmin);
copy_v3_v3(bb_max, bb.bmax);
}
void BLI_pbvh_get_grid_updates(PBVH *bvh, int clear, void ***gridfaces, int *totface)
{
PBVHIter iter;
PBVHNode *node;
GHashIterator *hiter;
GHash *map;
void *face, **faces;
unsigned i;
int tot;
map = BLI_ghash_new(BLI_ghashutil_ptrhash, BLI_ghashutil_ptrcmp, "pbvh_get_grid_updates gh");
pbvh_iter_begin(&iter, bvh, NULL, NULL);
while((node=pbvh_iter_next(&iter))) {
if(node->flag & PBVH_UpdateNormals) {
for(i = 0; i < node->totprim; ++i) {
face= bvh->gridfaces[node->prim_indices[i]];
if(!BLI_ghash_lookup(map, face))
BLI_ghash_insert(map, face, face);
}
if(clear)
node->flag &= ~PBVH_UpdateNormals;
}
}
pbvh_iter_end(&iter);
tot= BLI_ghash_size(map);
if(tot == 0) {
*totface= 0;
*gridfaces= NULL;
BLI_ghash_free(map, NULL, NULL);
return;
}
faces= MEM_callocN(sizeof(void*)*tot, "PBVH Grid Faces");
for(hiter = BLI_ghashIterator_new(map), i = 0;
!BLI_ghashIterator_isDone(hiter);
BLI_ghashIterator_step(hiter), ++i)
faces[i]= BLI_ghashIterator_getKey(hiter);
BLI_ghashIterator_free(hiter);
BLI_ghash_free(map, NULL, NULL);
*totface= tot;
*gridfaces= faces;
}
/***************************** Node Access ***********************************/
void BLI_pbvh_node_mark_update(PBVHNode *node)
{
node->flag |= PBVH_UpdateNormals|PBVH_UpdateBB|PBVH_UpdateOriginalBB|PBVH_UpdateDrawBuffers|PBVH_UpdateRedraw;
}
void BLI_pbvh_node_get_verts(PBVH *bvh, PBVHNode *node, int **vert_indices, MVert **verts)
{
if(vert_indices) *vert_indices= node->vert_indices;
if(verts) *verts= bvh->verts;
}
void BLI_pbvh_node_num_verts(PBVH *bvh, PBVHNode *node, int *uniquevert, int *totvert)
{
if(bvh->grids) {
const int tot= node->totprim*bvh->gridsize*bvh->gridsize;
if(totvert) *totvert= tot;
if(uniquevert) *uniquevert= tot;
}
else {
if(totvert) *totvert= node->uniq_verts + node->face_verts;
if(uniquevert) *uniquevert= node->uniq_verts;
}
}
void BLI_pbvh_node_get_grids(PBVH *bvh, PBVHNode *node, int **grid_indices, int *totgrid, int *maxgrid, int *gridsize, DMGridData ***griddata, DMGridAdjacency **gridadj)
{
if(bvh->grids) {
if(grid_indices) *grid_indices= node->prim_indices;
if(totgrid) *totgrid= node->totprim;
if(maxgrid) *maxgrid= bvh->totgrid;
if(gridsize) *gridsize= bvh->gridsize;
if(griddata) *griddata= bvh->grids;
if(gridadj) *gridadj= bvh->gridadj;
}
else {
if(grid_indices) *grid_indices= NULL;
if(totgrid) *totgrid= 0;
if(maxgrid) *maxgrid= 0;
if(gridsize) *gridsize= 0;
if(griddata) *griddata= NULL;
if(gridadj) *gridadj= NULL;
}
}
void BLI_pbvh_node_get_BB(PBVHNode *node, float bb_min[3], float bb_max[3])
{
copy_v3_v3(bb_min, node->vb.bmin);
copy_v3_v3(bb_max, node->vb.bmax);
}
void BLI_pbvh_node_get_original_BB(PBVHNode *node, float bb_min[3], float bb_max[3])
{
copy_v3_v3(bb_min, node->orig_vb.bmin);
copy_v3_v3(bb_max, node->orig_vb.bmax);
}
void BLI_pbvh_node_get_proxies(PBVHNode* node, PBVHProxyNode** proxies, int* proxy_count)
{
if (node->proxy_count > 0) {
if (proxies) *proxies = node->proxies;
if (proxy_count) *proxy_count = node->proxy_count;
}
else {
if (proxies) *proxies = 0;
if (proxy_count) *proxy_count = 0;
}
}
/********************************* Raycast ***********************************/
typedef struct {
/* Ray */
float start[3];
int sign[3];
float inv_dir[3];
int original;
} RaycastData;
/* Adapted from here: http://www.gamedev.net/community/forums/topic.asp?topic_id=459973 */
static int ray_aabb_intersect(PBVHNode *node, void *data_v)
{
RaycastData *ray = data_v;
float bbox[2][3];
float tmin, tmax, tymin, tymax, tzmin, tzmax;
if(ray->original)
BLI_pbvh_node_get_original_BB(node, bbox[0], bbox[1]);
else
BLI_pbvh_node_get_BB(node, bbox[0], bbox[1]);
tmin = (bbox[ray->sign[0]][0] - ray->start[0]) * ray->inv_dir[0];
tmax = (bbox[1-ray->sign[0]][0] - ray->start[0]) * ray->inv_dir[0];
tymin = (bbox[ray->sign[1]][1] - ray->start[1]) * ray->inv_dir[1];
tymax = (bbox[1-ray->sign[1]][1] - ray->start[1]) * ray->inv_dir[1];
if((tmin > tymax) || (tymin > tmax))
return 0;
if(tymin > tmin)
tmin = tymin;
if(tymax < tmax)
tmax = tymax;
tzmin = (bbox[ray->sign[2]][2] - ray->start[2]) * ray->inv_dir[2];
tzmax = (bbox[1-ray->sign[2]][2] - ray->start[2]) * ray->inv_dir[2];
if((tmin > tzmax) || (tzmin > tmax))
return 0;
if(tzmin > tmin)
tmin = tzmin;
// XXX jwilkins: tmax does not need to be updated since we don't use it
// keeping this here for future reference
//if(tzmax < tmax) tmax = tzmax;
node->tmin = tmin;
return 1;
}
void BLI_pbvh_raycast(PBVH *bvh, BLI_pbvh_HitOccludedCallback cb, void *data,
float ray_start[3], float ray_normal[3], int original)
{
RaycastData rcd;
copy_v3_v3(rcd.start, ray_start);
rcd.inv_dir[0] = 1.0f / ray_normal[0];
rcd.inv_dir[1] = 1.0f / ray_normal[1];
rcd.inv_dir[2] = 1.0f / ray_normal[2];
rcd.sign[0] = rcd.inv_dir[0] < 0;
rcd.sign[1] = rcd.inv_dir[1] < 0;
rcd.sign[2] = rcd.inv_dir[2] < 0;
rcd.original = original;
BLI_pbvh_search_callback_occluded(bvh, ray_aabb_intersect, &rcd, cb, data);
}
static int ray_face_intersection(float ray_start[3], float ray_normal[3],
float *t0, float *t1, float *t2, float *t3,
float *fdist)
{
float dist;
if ((isect_ray_tri_epsilon_v3(ray_start, ray_normal, t0, t1, t2, &dist, NULL, 0.1f) && dist < *fdist) ||
(t3 && isect_ray_tri_epsilon_v3(ray_start, ray_normal, t0, t2, t3, &dist, NULL, 0.1f) && dist < *fdist))
{
*fdist = dist;
return 1;
}
else {
return 0;
}
}
int BLI_pbvh_node_raycast(PBVH *bvh, PBVHNode *node, float (*origco)[3],
float ray_start[3], float ray_normal[3], float *dist)
{
int hit= 0;
if(bvh->faces) {
MVert *vert = bvh->verts;
int *faces= node->prim_indices;
int totface= node->totprim;
int i;
for(i = 0; i < totface; ++i) {
MFace *f = bvh->faces + faces[i];
int *face_verts = node->face_vert_indices[i];
if(origco) {
/* intersect with backuped original coordinates */
hit |= ray_face_intersection(ray_start, ray_normal,
origco[face_verts[0]],
origco[face_verts[1]],
origco[face_verts[2]],
f->v4? origco[face_verts[3]]: NULL,
dist);
}
else {
/* intersect with current coordinates */
hit |= ray_face_intersection(ray_start, ray_normal,
vert[f->v1].co,
vert[f->v2].co,
vert[f->v3].co,
f->v4 ? vert[f->v4].co : NULL,
dist);
}
}
}
else {
int totgrid= node->totprim;
int gridsize= bvh->gridsize;
int i, x, y;
for(i = 0; i < totgrid; ++i) {
DMGridData *grid= bvh->grids[node->prim_indices[i]];
if (!grid)
continue;
for(y = 0; y < gridsize-1; ++y) {
for(x = 0; x < gridsize-1; ++x) {
if(origco) {
hit |= ray_face_intersection(ray_start, ray_normal,
origco[y*gridsize + x],
origco[y*gridsize + x+1],
origco[(y+1)*gridsize + x+1],
origco[(y+1)*gridsize + x],
dist);
}
else {
hit |= ray_face_intersection(ray_start, ray_normal,
grid[y*gridsize + x].co,
grid[y*gridsize + x+1].co,
grid[(y+1)*gridsize + x+1].co,
grid[(y+1)*gridsize + x].co,
dist);
}
}
}
if(origco)
origco += gridsize*gridsize;
}
}
return hit;
}
//#include <GL/glew.h>
void BLI_pbvh_node_draw(PBVHNode *node, void *UNUSED(data))
{
#if 0
/* XXX: Just some quick code to show leaf nodes in different colors */
float col[3]; int i;
if(0) { //is_partial) {
col[0] = (rand() / (float)RAND_MAX); col[1] = col[2] = 0.6;
}
else {
srand((long long)node);
for(i = 0; i < 3; ++i)
col[i] = (rand() / (float)RAND_MAX) * 0.3 + 0.7;
}
glMaterialfv(GL_FRONT_AND_BACK, GL_DIFFUSE, col);
glColor3f(1, 0, 0);
#endif
GPU_draw_buffers(node->draw_buffers);
}
/* Adapted from:
http://www.gamedev.net/community/forums/topic.asp?topic_id=512123
Returns true if the AABB is at least partially within the frustum
(ok, not a real frustum), false otherwise.
*/
int BLI_pbvh_node_planes_contain_AABB(PBVHNode *node, void *data)
{
float (*planes)[4] = data;
int i, axis;
float vmin[3] /*, vmax[3]*/, bb_min[3], bb_max[3];
BLI_pbvh_node_get_BB(node, bb_min, bb_max);
for(i = 0; i < 4; ++i) {
for(axis = 0; axis < 3; ++axis) {
if(planes[i][axis] > 0) {
vmin[axis] = bb_min[axis];
/*vmax[axis] = bb_max[axis];*/ /*UNUSED*/
}
else {
vmin[axis] = bb_max[axis];
/*vmax[axis] = bb_min[axis];*/ /*UNUSED*/
}
}
if(dot_v3v3(planes[i], vmin) + planes[i][3] > 0)
return 0;
}
return 1;
}
void BLI_pbvh_draw(PBVH *bvh, float (*planes)[4], float (*face_nors)[3], int smooth)
{
PBVHNode **nodes;
int totnode;
BLI_pbvh_search_gather(bvh, update_search_cb, SET_INT_IN_POINTER(PBVH_UpdateNormals|PBVH_UpdateDrawBuffers),
&nodes, &totnode);
pbvh_update_normals(bvh, nodes, totnode, face_nors);
pbvh_update_draw_buffers(bvh, nodes, totnode, smooth);
if(nodes) MEM_freeN(nodes);
if(planes) {
BLI_pbvh_search_callback(bvh, BLI_pbvh_node_planes_contain_AABB,
planes, BLI_pbvh_node_draw, NULL);
}
else {
BLI_pbvh_search_callback(bvh, NULL, NULL, BLI_pbvh_node_draw, NULL);
}
}
void BLI_pbvh_grids_update(PBVH *bvh, DMGridData **grids, DMGridAdjacency *gridadj, void **gridfaces)
{
bvh->grids= grids;
bvh->gridadj= gridadj;
bvh->gridfaces= gridfaces;
}
float (*BLI_pbvh_get_vertCos(PBVH *pbvh))[3]
{
int a;
float (*vertCos)[3]= NULL;
if (pbvh->verts) {
float *co;
MVert *mvert= pbvh->verts;
vertCos= MEM_callocN(3*pbvh->totvert*sizeof(float), "BLI_pbvh_get_vertCoords");
co= (float*)vertCos;
for (a= 0; a<pbvh->totvert; a++, mvert++, co+= 3) {
copy_v3_v3(co, mvert->co);
}
}
return vertCos;
}
void BLI_pbvh_apply_vertCos(PBVH *pbvh, float (*vertCos)[3])
{
int a;
if (!pbvh->deformed) {
if (pbvh->verts) {
/* if pbvh is not already deformed, verts/faces points to the */
/* original data and applying new coords to this arrays would lead to */
/* unneeded deformation -- duplicate verts/faces to avoid this */
pbvh->verts= MEM_dupallocN(pbvh->verts);
pbvh->faces= MEM_dupallocN(pbvh->faces);
pbvh->deformed= 1;
}
}
if (pbvh->verts) {
MVert *mvert= pbvh->verts;
/* copy new verts coords */
for (a= 0; a < pbvh->totvert; ++a, ++mvert) {
copy_v3_v3(mvert->co, vertCos[a]);
mvert->flag |= ME_VERT_PBVH_UPDATE;
}
/* coordinates are new -- normals should also be updated */
mesh_calc_normals(pbvh->verts, pbvh->totvert, pbvh->faces, pbvh->totprim, NULL);
for (a= 0; a < pbvh->totnode; ++a)
BLI_pbvh_node_mark_update(&pbvh->nodes[a]);
BLI_pbvh_update(pbvh, PBVH_UpdateBB, NULL);
BLI_pbvh_update(pbvh, PBVH_UpdateOriginalBB, NULL);
}
}
int BLI_pbvh_isDeformed(PBVH *pbvh)
{
return pbvh->deformed;
}
/* Proxies */
PBVHProxyNode* BLI_pbvh_node_add_proxy(PBVH* bvh, PBVHNode* node)
{
int index, totverts;
#pragma omp critical
{
index = node->proxy_count;
node->proxy_count++;
if (node->proxies)
node->proxies= MEM_reallocN(node->proxies, node->proxy_count*sizeof(PBVHProxyNode));
else
node->proxies= MEM_mallocN(sizeof(PBVHProxyNode), "PBVHNodeProxy");
if (bvh->grids)
totverts = node->totprim*bvh->gridsize*bvh->gridsize;
else
totverts = node->uniq_verts;
node->proxies[index].co= MEM_callocN(sizeof(float[3])*totverts, "PBVHNodeProxy.co");
}
return node->proxies + index;
}
void BLI_pbvh_node_free_proxies(PBVHNode* node)
{
#pragma omp critical
{
int p;
for (p= 0; p < node->proxy_count; p++) {
MEM_freeN(node->proxies[p].co);
node->proxies[p].co= 0;
}
MEM_freeN(node->proxies);
node->proxies = 0;
node->proxy_count= 0;
}
}
void BLI_pbvh_gather_proxies(PBVH* pbvh, PBVHNode*** r_array, int* r_tot)
{
PBVHNode **array= NULL, **newarray, *node;
int tot= 0, space= 0;
int n;
for (n= 0; n < pbvh->totnode; n++) {
node = pbvh->nodes + n;
if(node->proxy_count > 0) {
if(tot == space) {
/* resize array if needed */
space= (tot == 0)? 32: space*2;
newarray= MEM_callocN(sizeof(PBVHNode)*space, "BLI_pbvh_gather_proxies");
if (array) {
memcpy(newarray, array, sizeof(PBVHNode)*tot);
MEM_freeN(array);
}
array= newarray;
}
array[tot]= node;
tot++;
}
}
if(tot == 0 && array) {
MEM_freeN(array);
array= NULL;
}
*r_array= array;
*r_tot= tot;
}
|
GB_AxB_saxpy3_template.c | //------------------------------------------------------------------------------
// GB_AxB_saxpy3_template: C=A*B, C<M>=A*B, or C<!M>=A*B via saxpy3 method
//------------------------------------------------------------------------------
// SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2021, All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
//------------------------------------------------------------------------------
// GB_AxB_saxpy3_template.c computes C=A*B for any semiring and matrix types,
// where C is sparse or hypersparse.
#include "GB_unused.h"
//------------------------------------------------------------------------------
// template code for C=A*B via the saxpy3 method
//------------------------------------------------------------------------------
{
// double ttt = omp_get_wtime ( ) ;
//--------------------------------------------------------------------------
// get the chunk size
//--------------------------------------------------------------------------
GB_GET_NTHREADS_MAX (nthreads_max, chunk, Context) ;
//--------------------------------------------------------------------------
// get M, A, B, and C
//--------------------------------------------------------------------------
int64_t *GB_RESTRICT Cp = C->p ;
// const int64_t *GB_RESTRICT Ch = C->h ;
const int64_t cvlen = C->vlen ;
const int64_t cnvec = C->nvec ;
const int64_t *GB_RESTRICT Bp = B->p ;
const int64_t *GB_RESTRICT Bh = B->h ;
const int8_t *GB_RESTRICT Bb = B->b ;
const int64_t *GB_RESTRICT Bi = B->i ;
const GB_BTYPE *GB_RESTRICT Bx = (GB_BTYPE *) (B_is_pattern ? NULL : B->x) ;
const int64_t bvlen = B->vlen ;
const bool B_jumbled = B->jumbled ;
const bool B_is_sparse = GB_IS_SPARSE (B) ;
const bool B_is_hyper = GB_IS_HYPERSPARSE (B) ;
const bool B_is_bitmap = GB_IS_BITMAP (B) ;
const bool B_is_sparse_or_hyper = B_is_sparse || B_is_hyper ;
const int64_t *GB_RESTRICT Ap = A->p ;
const int64_t *GB_RESTRICT Ah = A->h ;
const int8_t *GB_RESTRICT Ab = A->b ;
const int64_t *GB_RESTRICT Ai = A->i ;
const int64_t anvec = A->nvec ;
const int64_t avlen = A->vlen ;
const bool A_is_sparse = GB_IS_SPARSE (A) ;
const bool A_is_hyper = GB_IS_HYPERSPARSE (A) ;
const bool A_is_bitmap = GB_IS_BITMAP (A) ;
const GB_ATYPE *GB_RESTRICT Ax = (GB_ATYPE *) (A_is_pattern ? NULL : A->x) ;
const bool A_jumbled = A->jumbled ;
const bool A_ok_for_binary_search =
((A_is_sparse || A_is_hyper) && !A_jumbled) ;
const int64_t *GB_RESTRICT Mp = NULL ;
const int64_t *GB_RESTRICT Mh = NULL ;
const int8_t *GB_RESTRICT Mb = NULL ;
const int64_t *GB_RESTRICT Mi = NULL ;
const GB_void *GB_RESTRICT Mx = NULL ;
size_t msize = 0 ;
int64_t mnvec = 0 ;
int64_t mvlen = 0 ;
const bool M_is_hyper = GB_IS_HYPERSPARSE (M) ;
const bool M_is_bitmap = GB_IS_BITMAP (M) ;
const bool M_jumbled = GB_JUMBLED (M) ;
if (M != NULL)
{
Mp = M->p ;
Mh = M->h ;
Mb = M->b ;
Mi = M->i ;
Mx = (GB_void *) (Mask_struct ? NULL : (M->x)) ;
msize = M->type->size ;
mnvec = M->nvec ;
mvlen = M->vlen ;
}
// 3 cases:
// M not present and Mask_comp false: compute C=A*B
// M present and Mask_comp false: compute C<M>=A*B
// M present and Mask_comp true : compute C<!M>=A*B
// If M is NULL on input, then Mask_comp is also false on input.
const bool mask_is_M = (M != NULL && !Mask_comp) ;
// ignore the mask if present, not complemented, dense and
// used in place, structural, and not bitmap. In this case,
// all entries in M are true, so M can be ignored.
const bool ignore_mask = mask_is_M && M_dense_in_place &&
Mask_struct && !M_is_bitmap ;
//==========================================================================
// phase2: numeric work for fine tasks
//==========================================================================
// Coarse tasks: nothing to do in phase2.
// Fine tasks: compute nnz (C(:,j)), and values in Hx via atomics.
int taskid ;
#pragma omp parallel for num_threads(nthreads) schedule(dynamic,1)
for (taskid = 0 ; taskid < nfine ; taskid++)
{
//----------------------------------------------------------------------
// get the task descriptor
//----------------------------------------------------------------------
int64_t kk = TaskList [taskid].vector ;
int team_size = TaskList [taskid].team_size ;
int64_t hash_size = TaskList [taskid].hsize ;
bool use_Gustavson = (hash_size == cvlen) ;
int64_t pB = TaskList [taskid].start ;
int64_t pB_end = TaskList [taskid].end + 1 ;
int64_t pleft = 0, pright = anvec-1 ;
int64_t j = GBH (Bh, kk) ;
GB_GET_T_FOR_SECONDJ ;
#if !GB_IS_ANY_PAIR_SEMIRING
GB_CTYPE *GB_RESTRICT Hx = (GB_CTYPE *) TaskList [taskid].Hx ;
#endif
#if GB_IS_PLUS_FC32_MONOID
float *GB_RESTRICT Hx_real = (float *) Hx ;
float *GB_RESTRICT Hx_imag = Hx_real + 1 ;
#elif GB_IS_PLUS_FC64_MONOID
double *GB_RESTRICT Hx_real = (double *) Hx ;
double *GB_RESTRICT Hx_imag = Hx_real + 1 ;
#endif
if (use_Gustavson)
{
//------------------------------------------------------------------
// phase2: fine Gustavson task
//------------------------------------------------------------------
// Hf [i] == 0: unlocked, i has not been seen in C(:,j).
// Hx [i] is not initialized.
// M(i,j) is 0, or M is not present.
// if M: Hf [i] stays equal to 0 (or 3 if locked)
// if !M, or no M: C(i,j) is a new entry seen for 1st time
// Hf [i] == 1: unlocked, i has not been seen in C(:,j).
// Hx [i] is not initialized. M is present.
// M(i,j) is 1. (either M or !M case)
// if M: C(i,j) is a new entry seen for the first time.
// if !M: Hf [i] stays equal to 1 (or 3 if locked)
// Hf [i] == 2: unlocked, i has been seen in C(:,j).
// Hx [i] is initialized. This case is independent of M.
// Hf [i] == 3: locked. Hx [i] cannot be accessed.
int8_t *GB_RESTRICT Hf = (int8_t *GB_RESTRICT) TaskList [taskid].Hf;
if (M == NULL)
{
//--------------------------------------------------------------
// phase2: fine Gustavson task, C(:,j)=A*B(:,j)
//--------------------------------------------------------------
// Hf [i] is initially 0.
// 0 -> 3 : to lock, if i seen for first time
// 2 -> 3 : to lock, if i seen already
// 3 -> 2 : to unlock; now i has been seen
for ( ; pB < pB_end ; pB++) // scan B(:,j)
{
GB_GET_B_kj_INDEX ; // get index k of B(k,j)
GB_GET_A_k ; // get A(:,k)
if (aknz == 0) continue ;
GB_GET_B_kj ; // bkj = B(k,j)
// scan A(:,k)
for (int64_t pA = pA_start ; pA < pA_end ; pA++)
{
GB_GET_A_ik_INDEX ; // get index i of A(i,j)
GB_MULT_A_ik_B_kj ; // t = A(i,k) * B(k,j)
int8_t f ;
#if GB_IS_ANY_MONOID
//--------------------------------------------------
// C(i,j) += t ; with the ANY monoid
//--------------------------------------------------
GB_ATOMIC_READ
f = Hf [i] ; // grab the entry
if (f == 2) continue ; // check if already updated
GB_ATOMIC_WRITE_HX (i, t) ; // Hx [i] = t
#else
//--------------------------------------------------
// C(i,j) += t ; with all other monoids
//--------------------------------------------------
#if GB_HAS_ATOMIC
// if C(i,j) is already present (f==2), and the
// monoid can be done atomically, then do the
// atomic update. No need to modify Hf [i].
GB_ATOMIC_READ
f = Hf [i] ; // grab the entry
if (f == 2) // if true, update C(i,j)
{
GB_ATOMIC_UPDATE_HX (i, t) ; // Hx [i] += t
continue ; // C(i,j) has been updated
}
#endif
do // lock the entry
{
// do this atomically:
// { f = Hf [i] ; Hf [i] = 3 ; }
GB_ATOMIC_CAPTURE_INT8 (f, Hf [i], 3) ;
} while (f == 3) ; // lock owner gets f=0 or 2
if (f == 0)
{
// C(i,j) is a new entry
GB_ATOMIC_WRITE_HX (i, t) ; // Hx [i] = t
}
else // f == 2
{
// C(i,j) already appears in C(:,j)
GB_ATOMIC_UPDATE_HX (i, t) ; // Hx [i] += t
}
#endif
GB_ATOMIC_WRITE
Hf [i] = 2 ; // flag/unlock the entry
}
}
}
else if (mask_is_M)
{
//--------------------------------------------------------------
// phase2: fine Gustavson task, C(:,j)<M(:,j)>=A*B(:,j)
//--------------------------------------------------------------
// Hf [i] is 0 if M(i,j) not present or M(i,j)=0.
// 0 -> 1 : has already been done in phase0 if M(i,j)=1.
// 0 -> 0 : to ignore, if M(i,j)=0
// 1 -> 3 : to lock, if i seen for first time
// 2 -> 3 : to lock, if i seen already
// 3 -> 2 : to unlock; now i has been seen
GB_GET_M_j ; // get M(:,j)
GB_GET_M_j_RANGE (16) ; // get first and last in M(:,j)
for ( ; pB < pB_end ; pB++) // scan B(:,j)
{
GB_GET_B_kj_INDEX ; // get index k of B(k,j)
GB_GET_A_k ; // get A(:,k)
if (aknz == 0) continue ;
GB_GET_B_kj ; // bkj = B(k,j)
#if GB_IS_ANY_MONOID
//------------------------------------------------------
// C(i,j) += A(i,k)*B(k,j) ; with the ANY monoid
//------------------------------------------------------
#define GB_IKJ \
int8_t f ; \
GB_ATOMIC_READ \
f = Hf [i] ; /* grab the entry */ \
if (f == 0 || f == 2) continue ; \
GB_ATOMIC_WRITE \
Hf [i] = 2 ; /* unlock the entry */ \
GB_MULT_A_ik_B_kj ; /* t = A(i,k) * B(k,j) */ \
GB_ATOMIC_WRITE_HX (i, t) ; /* Hx [i] = t */
#else
//------------------------------------------------------
// C(i,j) += A(i,k)*B(k,j) ; all other monoids
//------------------------------------------------------
#define GB_IKJ \
{ \
GB_MULT_A_ik_B_kj ; /* t = A(i,k) * B(k,j) */ \
int8_t f ; \
GB_ATOMIC_READ \
f = Hf [i] ; /* grab the entry */ \
if (GB_HAS_ATOMIC && (f == 2)) \
{ \
/* C(i,j) already seen; update it */ \
GB_ATOMIC_UPDATE_HX (i, t) ; /* Hx [i] += t */ \
continue ; /* C(i,j) has been updated */ \
} \
if (f == 0) continue ; /* M(i,j)=0; ignore C(i,j)*/\
do /* lock the entry */ \
{ \
/* do this atomically: */ \
/* { f = Hf [i] ; Hf [i] = 3 ; } */ \
GB_ATOMIC_CAPTURE_INT8 (f, Hf [i], 3) ; \
} while (f == 3) ; /* lock owner gets f=1 or 2 */ \
if (f == 1) \
{ \
/* C(i,j) is a new entry */ \
GB_ATOMIC_WRITE_HX (i, t) ; /* Hx [i] = t */ \
} \
else /* f == 2 */ \
{ \
/* C(i,j) already appears in C(:,j) */ \
GB_ATOMIC_UPDATE_HX (i, t) ; /* Hx [i] += t */ \
} \
GB_ATOMIC_WRITE \
Hf [i] = 2 ; /* unlock the entry */ \
}
#endif
GB_SCAN_M_j_OR_A_k (A_ok_for_binary_search) ;
#undef GB_IKJ
}
}
else
{
//--------------------------------------------------------------
// phase2: fine Gustavson task, C(:,j)<!M(:,j)>=A*B(:,j)
//--------------------------------------------------------------
// Hf [i] is 0 if M(i,j) not present or M(i,j)=0.
// 0 -> 1 : has already been done in phase0 if M(i,j)=1
// 1 -> 1 : to ignore, if M(i,j)=1
// 0 -> 3 : to lock, if i seen for first time
// 2 -> 3 : to lock, if i seen already
// 3 -> 2 : to unlock; now i has been seen
GB_GET_M_j ; // get M(:,j)
for ( ; pB < pB_end ; pB++) // scan B(:,j)
{
GB_GET_B_kj_INDEX ; // get index k of B(k,j)
GB_GET_A_k ; // get A(:,k)
if (aknz == 0) continue ;
GB_GET_B_kj ; // bkj = B(k,j)
// scan A(:,k)
for (int64_t pA = pA_start ; pA < pA_end ; pA++)
{
GB_GET_A_ik_INDEX ; // get index i of A(i,j)
GB_MULT_A_ik_B_kj ; // t = A(i,k) * B(k,j)
int8_t f ;
#if GB_IS_ANY_MONOID
//--------------------------------------------------
// ANY monoid
//--------------------------------------------------
// lock state (3) not needed
// 0: not seen: update with new value, f becomes 2
// 1: masked, do nothing, f stays 1
// 2: already updated, do nothing, f stays 2
// 3: state not used, f can be 2
GB_ATOMIC_READ
f = Hf [i] ;
if (!f)
{
GB_ATOMIC_WRITE
Hf [i] = 2 ;
GB_ATOMIC_WRITE_HX (i, t) ; // Hx [i] = t
}
#else
GB_ATOMIC_READ
f = Hf [i] ; // grab the entry
#if GB_HAS_ATOMIC
if (f == 2) // if true, update C(i,j)
{
GB_ATOMIC_UPDATE_HX (i, t) ; // Hx [i] += t
continue ; // C(i,j) has been updated
}
#endif
if (f == 1) continue ; // M(i,j)=1; ignore C(i,j)
do // lock the entry
{
// do this atomically:
// { f = Hf [i] ; Hf [i] = 3 ; }
GB_ATOMIC_CAPTURE_INT8 (f, Hf [i], 3) ;
} while (f == 3) ; // lock owner of gets f=0 or 2
if (f == 0)
{
// C(i,j) is a new entry
GB_ATOMIC_WRITE_HX (i, t) ; // Hx [i] = t
}
else // f == 2
{
// C(i,j) already seen
GB_ATOMIC_UPDATE_HX (i, t) ; // Hx [i] += t
}
GB_ATOMIC_WRITE
Hf [i] = 2 ; // unlock the entry
#endif
}
}
}
}
else
{
//------------------------------------------------------------------
// phase2: fine hash task
//------------------------------------------------------------------
// Each hash entry Hf [hash] splits into two parts, (h,f). f
// is in the 2 least significant bits. h is 62 bits, and is
// the 1-based index i of the C(i,j) entry stored at that
// location in the hash table.
// If M is present (M or !M), and M(i,j)=1, then (i+1,1)
// has been inserted into the hash table, in phase0.
// Given Hf [hash] split into (h,f)
// h == 0, f == 0: unlocked and unoccupied.
// note that if f=0, h must be zero too.
// h == i+1, f == 1: unlocked, occupied by M(i,j)=1.
// C(i,j) has not been seen, or is ignored.
// Hx is not initialized. M is present.
// if !M: this entry will be ignored in C.
// h == i+1, f == 2: unlocked, occupied by C(i,j).
// Hx is initialized. M is no longer
// relevant.
// h == (anything), f == 3: locked.
int64_t *GB_RESTRICT
Hf = (int64_t *GB_RESTRICT) TaskList [taskid].Hf ;
int64_t hash_bits = (hash_size-1) ;
if (M == NULL || ignore_mask)
{
//--------------------------------------------------------------
// phase2: fine hash task, C(:,j)=A*B(:,j)
//--------------------------------------------------------------
// no mask present, or mask ignored
#undef GB_CHECK_MASK_ij
#include "GB_AxB_saxpy3_fineHash_phase2.c"
}
else if (mask_is_M)
{
//--------------------------------------------------------------
// phase2: fine hash task, C(:,j)<M(:,j)>=A*B(:,j)
//--------------------------------------------------------------
GB_GET_M_j ; // get M(:,j)
if (M_dense_in_place)
{
//----------------------------------------------------------
// M(:,j) is dense. M is not scattered into Hf.
//----------------------------------------------------------
ASSERT (!Mask_struct || M_is_bitmap) ;
#undef GB_CHECK_MASK_ij
#define GB_CHECK_MASK_ij \
bool mij = \
(M_is_bitmap ? Mjb [i] : 1) && \
(Mask_struct ? 1 : (Mjx [i] != 0)) ; \
if (!mij) continue ;
switch (msize)
{
default:
case 1 :
#define M_TYPE uint8_t
#include "GB_AxB_saxpy3_fineHash_phase2.c"
break ;
case 2 :
#define M_TYPE uint16_t
#include "GB_AxB_saxpy3_fineHash_phase2.c"
break ;
case 4 :
#define M_TYPE uint32_t
#include "GB_AxB_saxpy3_fineHash_phase2.c"
break ;
case 8 :
#define M_TYPE uint64_t
#include "GB_AxB_saxpy3_fineHash_phase2.c"
break ;
case 16 :
#define M_TYPE uint64_t
#define M_SIZE 2
#undef GB_CHECK_MASK_ij
#define GB_CHECK_MASK_ij \
bool mij = \
(M_is_bitmap ? Mjb [i] : 1) && \
(Mask_struct ? 1 : \
(Mjx [2*i] != 0) || \
(Mjx [2*i+1] != 0)) ; \
if (!mij) continue ;
#include "GB_AxB_saxpy3_fineHash_phase2.c"
break ;
}
// the task is finished: go to the next task
continue ;
}
//--------------------------------------------------------------
// M is sparse and scattered into Hf
//--------------------------------------------------------------
// Given Hf [hash] split into (h,f)
// h == 0 , f == 0 : unlocked, unoccupied. C(i,j) ignored
// h == i+1, f == 1 : unlocked, occupied by M(i,j)=1.
// C(i,j) has not been seen.
// Hx is not initialized.
// h == i+1, f == 2 : unlocked, occupied by C(i,j), M(i,j)=1
// Hx is initialized.
// h == ..., f == 3 : locked.
// 0 -> 0 : to ignore, if M(i,j)=0
// 1 -> 3 : to lock, if i seen for first time
// 2 -> 3 : to lock, if i seen already
// 3 -> 2 : to unlock; now i has been seen
GB_GET_M_j_RANGE (16) ; // get first and last in M(:,j)
for ( ; pB < pB_end ; pB++) // scan B(:,j)
{
GB_GET_B_kj_INDEX ; // get index k of B(k,j)
GB_GET_A_k ; // get A(:,k)
if (aknz == 0) continue ;
GB_GET_B_kj ; // bkj = B(k,j)
#define GB_IKJ \
{ \
GB_MULT_A_ik_B_kj ; /* t = A(i,k) * B(k,j) */ \
int64_t i1 = i + 1 ; /* i1 = one-based index */ \
int64_t i_unlocked = (i1 << 2) + 2 ; /* (i+1,2) */ \
for (GB_HASH (i)) /* find i in hash table */ \
{ \
int64_t hf ; \
GB_ATOMIC_READ \
hf = Hf [hash] ; /* grab the entry */ \
if (GB_HAS_ATOMIC && (hf == i_unlocked)) \
{ \
/* Hx [hash] += t */ \
GB_ATOMIC_UPDATE_HX (hash, t) ; \
break ; /* C(i,j) has been updated */ \
} \
if (hf == 0) break ; /* M(i,j)=0; ignore Cij */ \
if ((hf >> 2) == i1) /* if true, i found */ \
{ \
do /* lock the entry */ \
{ \
/* do this atomically: */ \
/* { hf = Hf [hash] ; Hf [hash] |= 3 ; }*/ \
GB_ATOMIC_CAPTURE_INT64_OR (hf,Hf[hash],3);\
} while ((hf & 3) == 3) ; /* own: f=1,2 */ \
if ((hf & 3) == 1) /* f == 1 */ \
{ \
/* C(i,j) is a new entry in C(:,j) */ \
/* Hx [hash] = t */ \
GB_ATOMIC_WRITE_HX (hash, t) ; \
} \
else /* f == 2 */ \
{ \
/* C(i,j) already appears in C(:,j) */ \
/* Hx [hash] += t */ \
GB_ATOMIC_UPDATE_HX (hash, t) ; \
} \
GB_ATOMIC_WRITE \
Hf [hash] = i_unlocked ; /* unlock entry */ \
break ; \
} \
} \
}
GB_SCAN_M_j_OR_A_k (A_ok_for_binary_search) ;
#undef GB_IKJ
}
}
else
{
//--------------------------------------------------------------
// phase2: fine hash task, C(:,j)<!M(:,j)>=A*B(:,j)
//--------------------------------------------------------------
GB_GET_M_j ; // get M(:,j)
if (M_dense_in_place)
{
//----------------------------------------------------------
// M(:,j) is dense. M is not scattered into Hf.
//----------------------------------------------------------
if (Mask_struct && !M_is_bitmap)
{
// structural mask, complemented, and not bitmap.
// No work to do.
continue ;
}
#undef GB_CHECK_MASK_ij
#define GB_CHECK_MASK_ij \
bool mij = \
(M_is_bitmap ? Mjb [i] : 1) && \
(Mask_struct ? 1 : (Mjx [i] != 0)) ; \
if (mij) continue ;
switch (msize)
{
default:
case 1 :
#define M_TYPE uint8_t
#include "GB_AxB_saxpy3_fineHash_phase2.c"
break ;
case 2 :
#define M_TYPE uint16_t
#include "GB_AxB_saxpy3_fineHash_phase2.c"
break ;
case 4 :
#define M_TYPE uint32_t
#include "GB_AxB_saxpy3_fineHash_phase2.c"
break ;
case 8 :
#define M_TYPE uint64_t
#include "GB_AxB_saxpy3_fineHash_phase2.c"
break ;
case 16 :
#define M_TYPE uint64_t
#define M_SIZE 2
#undef GB_CHECK_MASK_ij
#define GB_CHECK_MASK_ij \
bool mij = \
(M_is_bitmap ? Mjb [i] : 1) && \
(Mask_struct ? 1 : \
(Mjx [2*i] != 0) || \
(Mjx [2*i+1] != 0)) ; \
if (mij) continue ;
#include "GB_AxB_saxpy3_fineHash_phase2.c"
break ;
}
// the task is finished: go to the next task
continue ;
}
//--------------------------------------------------------------
// M is sparse and scattered into Hf
//--------------------------------------------------------------
// Given Hf [hash] split into (h,f)
// h == 0 , f == 0 : unlocked and unoccupied.
// h == i+1, f == 1 : unlocked, occupied by M(i,j)=1.
// C(i,j) is ignored.
// h == i+1, f == 2 : unlocked, occupied by C(i,j).
// Hx is initialized.
// h == (anything), f == 3: locked.
// 1 -> 1 : to ignore, if M(i,j)=1
// 0 -> 3 : to lock, if i seen for first time
// 2 -> 3 : to lock, if i seen already
// 3 -> 2 : to unlock; now i has been seen
for ( ; pB < pB_end ; pB++) // scan B(:,j)
{
GB_GET_B_kj_INDEX ; // get index k of B(k,j)
GB_GET_A_k ; // get A(:,k)
if (aknz == 0) continue ;
GB_GET_B_kj ; // bkj = B(k,j)
// scan A(:,k)
for (int64_t pA = pA_start ; pA < pA_end ; pA++)
{
GB_GET_A_ik_INDEX ; // get index i of A(i,j)
GB_MULT_A_ik_B_kj ; // t = A(i,k) * B(k,j)
int64_t i1 = i + 1 ; // i1 = one-based index
int64_t i_unlocked = (i1 << 2) + 2 ; // (i+1,2)
int64_t i_masked = (i1 << 2) + 1 ; // (i+1,1)
for (GB_HASH (i)) // find i in hash table
{
int64_t hf ;
GB_ATOMIC_READ
hf = Hf [hash] ; // grab the entry
#if GB_HAS_ATOMIC
if (hf == i_unlocked) // if true, update C(i,j)
{
GB_ATOMIC_UPDATE_HX (hash, t) ;// Hx [.]+=t
break ; // C(i,j) has been updated
}
#endif
if (hf == i_masked) break ; // M(i,j)=1; ignore
int64_t h = (hf >> 2) ;
if (h == 0 || h == i1)
{
// h=0: unoccupied, h=i1: occupied by i
do // lock the entry
{
// do this atomically:
// { hf = Hf [hash] ; Hf [hash] |= 3 ; }
GB_ATOMIC_CAPTURE_INT64_OR (hf,Hf[hash],3) ;
} while ((hf & 3) == 3) ; // owner: f=0,1,2
if (hf == 0) // f == 0
{
// C(i,j) is a new entry in C(:,j)
// Hx [hash] = t
GB_ATOMIC_WRITE_HX (hash, t) ;
GB_ATOMIC_WRITE
Hf [hash] = i_unlocked ; // unlock entry
break ;
}
if (hf == i_unlocked) // f == 2
{
// C(i,j) already appears in C(:,j)
// Hx [hash] += t
GB_ATOMIC_UPDATE_HX (hash, t) ;
GB_ATOMIC_WRITE
Hf [hash] = i_unlocked ; // unlock entry
break ;
}
// hash table occupied, but not with i,
// or with i but M(i,j)=1 so C(i,j) ignored
GB_ATOMIC_WRITE
Hf [hash] = hf ; // unlock with prior value
}
}
}
}
}
}
}
// ttt = omp_get_wtime ( ) - ttt ;
// GB_Global_timing_add (9, ttt) ;
// ttt = omp_get_wtime ( ) ;
//==========================================================================
// phase3/phase4: count nnz(C(:,j)) for fine tasks, cumsum of Cp
//==========================================================================
GB_AxB_saxpy3_cumsum (C, TaskList, nfine, chunk, nthreads) ;
// ttt = omp_get_wtime ( ) - ttt ;
// GB_Global_timing_add (10, ttt) ;
// ttt = omp_get_wtime ( ) ;
//==========================================================================
// phase5: numeric phase for coarse tasks, gather for fine tasks
//==========================================================================
// allocate Ci and Cx
int64_t cnz = Cp [cnvec] ;
GrB_Info info = GB_bix_alloc (C, cnz, false, false, true, true, Context) ;
if (info != GrB_SUCCESS)
{
// out of memory
return (GrB_OUT_OF_MEMORY) ;
}
int64_t *GB_RESTRICT Ci = C->i ;
GB_CTYPE *GB_RESTRICT Cx = (GB_CTYPE *) C->x ;
#if GB_IS_ANY_PAIR_SEMIRING
// TODO: create C as a constant-value matrix.
// ANY_PAIR semiring: result is purely symbolic
int64_t pC ;
#pragma omp parallel for num_threads(nthreads) schedule(static)
for (pC = 0 ; pC < cnz ; pC++)
{
Cx [pC] = GB_CTYPE_CAST (1, 0) ;
}
// Just a precaution; these variables are not used below. Any attempt
// to access them will lead to a compile error.
#define Cx is not used
#define Hx is not used
// these have been renamed to ANY_PAIR:
// EQ_PAIR
// LAND_PAIR
// LOR_PAIR
// MAX_PAIR
// MIN_PAIR
// TIMES_PAIR
#endif
// ttt = omp_get_wtime ( ) - ttt ;
// GB_Global_timing_add (11, ttt) ;
// ttt = omp_get_wtime ( ) ;
bool C_jumbled = false ;
#pragma omp parallel for num_threads(nthreads) schedule(dynamic,1) \
reduction(||:C_jumbled)
for (taskid = 0 ; taskid < ntasks ; taskid++)
{
//----------------------------------------------------------------------
// get the task descriptor
//----------------------------------------------------------------------
#if !GB_IS_ANY_PAIR_SEMIRING
GB_CTYPE *GB_RESTRICT Hx = (GB_CTYPE *) TaskList [taskid].Hx ;
#endif
int64_t hash_size = TaskList [taskid].hsize ;
bool use_Gustavson = (hash_size == cvlen) ;
bool task_C_jumbled = false ;
if (taskid < nfine)
{
//------------------------------------------------------------------
// fine task: gather pattern and values
//------------------------------------------------------------------
int64_t kk = TaskList [taskid].vector ;
int team_size = TaskList [taskid].team_size ;
int leader = TaskList [taskid].leader ;
int my_teamid = taskid - leader ;
int64_t pC = Cp [kk] ;
if (use_Gustavson)
{
//--------------------------------------------------------------
// phase5: fine Gustavson task, C=A*B, C<M>=A*B, or C<!M>=A*B
//--------------------------------------------------------------
// Hf [i] == 2 if C(i,j) is an entry in C(:,j)
int8_t *GB_RESTRICT
Hf = (int8_t *GB_RESTRICT) TaskList [taskid].Hf ;
int64_t cjnz = Cp [kk+1] - pC ;
int64_t istart, iend ;
GB_PARTITION (istart, iend, cvlen, my_teamid, team_size) ;
if (cjnz == cvlen)
{
// C(:,j) is dense
for (int64_t i = istart ; i < iend ; i++)
{
Ci [pC + i] = i ;
}
#if !GB_IS_ANY_PAIR_SEMIRING
// copy Hx [istart:iend-1] into Cx [pC+istart:pC+iend-1]
GB_CIJ_MEMCPY (pC + istart, istart, iend - istart) ;
#endif
}
else
{
// C(:,j) is sparse
pC += TaskList [taskid].my_cjnz ;
for (int64_t i = istart ; i < iend ; i++)
{
if (Hf [i] == 2)
{
GB_CIJ_GATHER (pC, i) ; // Cx [pC] = Hx [i]
Ci [pC++] = i ;
}
}
}
}
else
{
//--------------------------------------------------------------
// phase5: fine hash task, C=A*B, C<M>=A*B, C<!M>=A*B
//--------------------------------------------------------------
// (Hf [hash] & 3) == 2 if C(i,j) is an entry in C(:,j),
// and the index i of the entry is (Hf [hash] >> 2) - 1.
int64_t *GB_RESTRICT
Hf = (int64_t *GB_RESTRICT) TaskList [taskid].Hf ;
int64_t mystart, myend ;
GB_PARTITION (mystart, myend, hash_size, my_teamid, team_size) ;
pC += TaskList [taskid].my_cjnz ;
for (int64_t hash = mystart ; hash < myend ; hash++)
{
int64_t hf = Hf [hash] ;
if ((hf & 3) == 2)
{
int64_t i = (hf >> 2) - 1 ; // found C(i,j) in hash
Ci [pC] = i ;
GB_CIJ_GATHER (pC, hash) ; // Cx [pC] = Hx [hash]
pC++ ;
}
}
task_C_jumbled = true ;
}
}
else
{
//------------------------------------------------------------------
// numeric coarse task: compute C(:,kfirst:klast)
//------------------------------------------------------------------
int64_t *GB_RESTRICT
Hf = (int64_t *GB_RESTRICT) TaskList [taskid].Hf ;
int64_t kfirst = TaskList [taskid].start ;
int64_t klast = TaskList [taskid].end ;
int64_t nk = klast - kfirst + 1 ;
int64_t mark = 2*nk + 1 ;
if (use_Gustavson)
{
//--------------------------------------------------------------
// phase5: coarse Gustavson task
//--------------------------------------------------------------
if (M == NULL)
{
//----------------------------------------------------------
// phase5: coarse Gustavson task, C=A*B
//----------------------------------------------------------
#if GB_IS_PERFORMANCE_CRITICAL_SEMIRING
#define GB_SAXPY_COARSE_GUSTAVSON_NOMASK_PHASE5
#include "GB_meta16_factory.c"
#undef GB_SAXPY_COARSE_GUSTAVSON_NOMASK_PHASE5
#else
#include "GB_AxB_saxpy3_coarseGus_noM_phase5.c"
#endif
}
else if (mask_is_M)
{
//----------------------------------------------------------
// phase5: coarse Gustavson task, C<M>=A*B
//----------------------------------------------------------
// Initially, Hf [...] < mark for all of Hf.
// Hf [i] < mark : M(i,j)=0, C(i,j) is ignored.
// Hf [i] == mark : M(i,j)=1, and C(i,j) not yet seen.
// Hf [i] == mark+1 : M(i,j)=1, and C(i,j) has been seen.
for (int64_t kk = kfirst ; kk <= klast ; kk++)
{
int64_t pC = Cp [kk] ;
int64_t cjnz = Cp [kk+1] - pC ;
if (cjnz == 0) continue ; // nothing to do
GB_GET_B_j ; // get B(:,j)
#ifdef GB_IDENTITY
if (cjnz == cvlen) // C(:,j) is dense
{
// this requires the monoid identity. It is not
// defined for the generic saxpy3.
GB_COMPUTE_DENSE_C_j ; // C(:,j) = A*B(:,j)
continue ;
}
#endif
GB_GET_M_j ; // get M(:,j)
GB_GET_M_j_RANGE (64) ; // get first and last in M(:,j)
mark += 2 ;
int64_t mark1 = mark+1 ;
// scatter M(:,j)
GB_SCATTER_M_j (pM_start, pM_end, mark) ;
if (16 * cjnz > cvlen) // C(:,j) is not very sparse
{
for ( ; pB < pB_end ; pB++) // scan B(:,j)
{
GB_GET_B_kj_INDEX ; // get k of B(k,j)
GB_GET_A_k ; // get A(:,k)
if (aknz == 0) continue ;
GB_GET_B_kj ; // bkj = B(k,j)
#define GB_IKJ \
{ \
int64_t hf = Hf [i] ; \
if (hf == mark) \
{ \
/* C(i,j) = A(i,k) * B(k,j) */ \
Hf [i] = mark1 ; /* mark as seen */\
GB_MULT_A_ik_B_kj ; /* t = aik*bkj */ \
GB_HX_WRITE (i, t) ; /* Hx [i] = t */ \
} \
else if (hf == mark1) \
{ \
/* C(i,j) += A(i,k) * B(k,j) */ \
GB_MULT_A_ik_B_kj ; /* t = aik*bkj */ \
GB_HX_UPDATE (i, t) ;/* Hx [i] += t */ \
} \
}
GB_SCAN_M_j_OR_A_k (A_ok_for_binary_search) ;
#undef GB_IKJ
}
GB_GATHER_ALL_C_j(mark1) ; // gather into C(:,j)
}
else // C(:,j) is very sparse
{
for ( ; pB < pB_end ; pB++) // scan B(:,j)
{
GB_GET_B_kj_INDEX ; // get k of B(k,j)
GB_GET_A_k ; // get A(:,k)
if (aknz == 0) continue ;
GB_GET_B_kj ; // bkj = B(k,j)
#define GB_IKJ \
{ \
int64_t hf = Hf [i] ; \
if (hf == mark) \
{ \
/* C(i,j) = A(i,k) * B(k,j) */ \
Hf [i] = mark1 ; /* mark as seen */\
GB_MULT_A_ik_B_kj ; /* t = aik*bkj */ \
GB_HX_WRITE (i, t) ; /* Hx [i] = t */ \
Ci [pC++] = i ; /* C(:,j) pattern */ \
} \
else if (hf == mark1) \
{ \
/* C(i,j) += A(i,k) * B(k,j) */ \
GB_MULT_A_ik_B_kj ; /* t = aik*bkj */ \
GB_HX_UPDATE (i, t) ;/* Hx [i] += t */ \
} \
}
GB_SCAN_M_j_OR_A_k (A_ok_for_binary_search) ;
#undef GB_IKJ
}
GB_SORT_AND_GATHER_C_j ; // gather into C(:,j)
}
}
}
else
{
//----------------------------------------------------------
// phase5: coarse Gustavson task, C<!M>=A*B
//----------------------------------------------------------
// Since the mask is !M:
// Hf [i] < mark : M(i,j)=0, C(i,j) is not yet seen.
// Hf [i] == mark : M(i,j)=1, so C(i,j) is ignored.
// Hf [i] == mark+1 : M(i,j)=0, and C(i,j) has been seen.
for (int64_t kk = kfirst ; kk <= klast ; kk++)
{
int64_t pC = Cp [kk] ;
int64_t cjnz = Cp [kk+1] - pC ;
if (cjnz == 0) continue ; // nothing to do
GB_GET_B_j ; // get B(:,j)
#ifdef GB_IDENTITY
if (cjnz == cvlen) // C(:,j) is dense
{
// this requires the monoid identity. It is not
// defined for the generic saxpy3.
GB_COMPUTE_DENSE_C_j ; // C(:,j) = A*B(:,j)
continue ;
}
#endif
GB_GET_M_j ; // get M(:,j)
mark += 2 ;
int64_t mark1 = mark+1 ;
// scatter M(:,j)
GB_SCATTER_M_j (pM_start, pM_end, mark) ;
if (16 * cjnz > cvlen) // C(:,j) is not very sparse
{
for ( ; pB < pB_end ; pB++) // scan B(:,j)
{
GB_GET_B_kj_INDEX ; // get k of B(k,j)
GB_GET_A_k ; // get A(:,k)
if (aknz == 0) continue ;
GB_GET_B_kj ; // bkj = B(k,j)
// scan A(:,k)
for (int64_t pA = pA_start ; pA < pA_end ; pA++)
{
GB_GET_A_ik_INDEX ; // get i of A(i,j)
int64_t hf = Hf [i] ;
if (hf < mark)
{
// C(i,j) = A(i,k) * B(k,j)
Hf [i] = mark1 ; // mark as seen
GB_MULT_A_ik_B_kj ; // t =A(i,k)*B(k,j)
GB_HX_WRITE (i, t) ; // Hx [i] = t
}
else if (hf == mark1)
{
// C(i,j) += A(i,k) * B(k,j)
GB_MULT_A_ik_B_kj ; // t =A(i,k)*B(k,j)
GB_HX_UPDATE (i, t) ;// Hx [i] += t
}
}
}
GB_GATHER_ALL_C_j(mark1) ; // gather into C(:,j)
}
else // C(:,j) is very sparse
{
for ( ; pB < pB_end ; pB++) // scan B(:,j)
{
GB_GET_B_kj_INDEX ; // get k of B(k,j)
GB_GET_A_k ; // get A(:,k)
if (aknz == 0) continue ;
GB_GET_B_kj ; // bkj = B(k,j)
// scan A(:,k)
for (int64_t pA = pA_start ; pA < pA_end ; pA++)
{
GB_GET_A_ik_INDEX ; // get i of A(i,j)
int64_t hf = Hf [i] ;
if (hf < mark)
{
// C(i,j) = A(i,k) * B(k,j)
Hf [i] = mark1 ; // mark as seen
GB_MULT_A_ik_B_kj ; // t =A(i,k)*B(k,j)
GB_HX_WRITE (i, t) ; // Hx [i] = t
Ci [pC++] = i ; // create C(:,j) pattern
}
else if (hf == mark1)
{
// C(i,j) += A(i,k) * B(k,j)
GB_MULT_A_ik_B_kj ; // t =A(i,k)*B(k,j)
GB_HX_UPDATE (i, t) ; // Hx [i] += t
}
}
}
GB_SORT_AND_GATHER_C_j ; // gather into C(:,j)
}
}
}
}
else
{
//--------------------------------------------------------------
// phase5: coarse hash task
//--------------------------------------------------------------
int64_t *GB_RESTRICT Hi = TaskList [taskid].Hi ;
int64_t hash_bits = (hash_size-1) ;
if (M == NULL || ignore_mask)
{
//----------------------------------------------------------
// phase5: coarse hash task, C=A*B
//----------------------------------------------------------
// no mask present, or mask ignored (see below)
#undef GB_CHECK_MASK_ij
#include "GB_AxB_saxpy3_coarseHash_phase5.c"
}
else if (mask_is_M)
{
//----------------------------------------------------------
// phase5: coarse hash task, C<M>=A*B
//----------------------------------------------------------
if (M_dense_in_place)
{
ASSERT (!Mask_struct || M_is_bitmap) ;
#define GB_CHECK_MASK_ij \
bool mij = \
(M_is_bitmap ? Mjb [i] : 1) && \
(Mask_struct ? 1 : (Mjx [i] != 0)) ; \
if (!mij) continue ;
switch (msize)
{
default:
case 1 :
#define M_TYPE uint8_t
#include "GB_AxB_saxpy3_coarseHash_phase5.c"
break ;
case 2 :
#define M_TYPE uint16_t
#include "GB_AxB_saxpy3_coarseHash_phase5.c"
break ;
case 4 :
#define M_TYPE uint32_t
#include "GB_AxB_saxpy3_coarseHash_phase5.c"
break ;
case 8 :
#define M_TYPE uint64_t
#include "GB_AxB_saxpy3_coarseHash_phase5.c"
break ;
case 16 :
#define M_TYPE uint64_t
#define M_SIZE 2
#undef GB_CHECK_MASK_ij
#define GB_CHECK_MASK_ij \
bool mij = \
(M_is_bitmap ? Mjb [i] : 1) && \
(Mask_struct ? 1 : \
(Mjx [2*i] != 0) || \
(Mjx [2*i+1] != 0)) ; \
if (!mij) continue ;
#include "GB_AxB_saxpy3_coarseHash_phase5.c"
break ;
}
}
else
{
//----------------------------------------------------------
// M is sparse and scattered into Hf
//----------------------------------------------------------
// Initially, Hf [...] < mark for all of Hf.
// Let h = Hi [hash] and f = Hf [hash].
// f < mark : M(i,j)=0, C(i,j) is ignored.
// h == i, f == mark : M(i,j)=1, and C(i,j) not yet seen.
// h == i, f == mark+1 : M(i,j)=1, and C(i,j) has been seen.
for (int64_t kk = kfirst ; kk <= klast ; kk++)
{
int64_t pC = Cp [kk] ;
int64_t cjnz = Cp [kk+1] - pC ;
if (cjnz == 0) continue ; // nothing to do
GB_GET_M_j ; // get M(:,j)
GB_GET_M_j_RANGE (64) ; // get 1st & last in M(:,j)
mark += 2 ;
int64_t mark1 = mark+1 ;
GB_HASH_M_j ; // hash M(:,j)
GB_GET_B_j ; // get B(:,j)
for ( ; pB < pB_end ; pB++) // scan B(:,j)
{
GB_GET_B_kj_INDEX ; // get index k of B(k,j)
GB_GET_A_k ; // get A(:,k)
if (aknz == 0) continue ;
GB_GET_B_kj ; // bkj = B(k,j)
#define GB_IKJ \
{ \
for (GB_HASH (i)) /* find i in hash */ \
{ \
int64_t f = Hf [hash] ; \
if (f < mark) break ; /* M(i,j)=0, ignore*/\
if (Hi [hash] == i) \
{ \
GB_MULT_A_ik_B_kj ; /* t = aik*bkj */ \
if (f == mark) /* if true, i is new */ \
{ \
/* C(i,j) is new */ \
Hf [hash] = mark1 ; /* mark seen */\
GB_HX_WRITE (hash, t) ;/*Hx[.]=t */\
Ci [pC++] = i ; \
} \
else \
{ \
/* C(i,j) has been seen; update */ \
GB_HX_UPDATE (hash, t) ; \
} \
break ; \
} \
} \
}
GB_SCAN_M_j_OR_A_k (A_ok_for_binary_search) ;
#undef GB_IKJ
}
GB_SORT_AND_GATHER_HASHED_C_j (mark1) ;
}
}
}
else
{
//----------------------------------------------------------
// phase5: coarse hash task, C<!M>=A*B
//----------------------------------------------------------
if (M_dense_in_place)
{
//------------------------------------------------------
// M(:,j) is dense. M is not scattered into Hf.
//------------------------------------------------------
if (Mask_struct && !M_is_bitmap)
{
// structural mask, complemented, not bitmap.
// No work to do; C is empty.
continue ;
}
#undef GB_CHECK_MASK_ij
#define GB_CHECK_MASK_ij \
bool mij = \
(M_is_bitmap ? Mjb [i] : 1) && \
(Mask_struct ? 1 : (Mjx [i] != 0)) ; \
if (mij) continue ;
switch (msize)
{
default:
case 1 :
#define M_TYPE uint8_t
#include "GB_AxB_saxpy3_coarseHash_phase5.c"
break ;
case 2 :
#define M_TYPE uint16_t
#include "GB_AxB_saxpy3_coarseHash_phase5.c"
break ;
case 4 :
#define M_TYPE uint32_t
#include "GB_AxB_saxpy3_coarseHash_phase5.c"
break ;
case 8 :
#define M_TYPE uint64_t
#include "GB_AxB_saxpy3_coarseHash_phase5.c"
break ;
case 16 :
#define M_TYPE uint64_t
#define M_SIZE 2
#undef GB_CHECK_MASK_ij
#define GB_CHECK_MASK_ij \
bool mij = \
(M_is_bitmap ? Mjb [i] : 1) && \
(Mask_struct ? 1 : \
(Mjx [2*i] != 0) || \
(Mjx [2*i+1] != 0)) ; \
if (mij) continue ;
#include "GB_AxB_saxpy3_coarseHash_phase5.c"
break ;
}
}
else
{
//----------------------------------------------------------
// M is sparse and scattered into Hf
//----------------------------------------------------------
// Initially, Hf [...] < mark for all of Hf.
// Let h = Hi [hash] and f = Hf [hash].
// f < mark: unoccupied, M(i,j)=0, and C(i,j) not yet seen.
// h == i, f == mark : M(i,j)=1. C(i,j) ignored.
// h == i, f == mark+1 : M(i,j)=0, and C(i,j) has been seen.
for (int64_t kk = kfirst ; kk <= klast ; kk++)
{
int64_t pC = Cp [kk] ;
int64_t cjnz = Cp [kk+1] - pC ;
if (cjnz == 0) continue ; // nothing to do
GB_GET_M_j ; // get M(:,j)
mark += 2 ;
int64_t mark1 = mark+1 ;
GB_HASH_M_j ; // hash M(:,j)
GB_GET_B_j ; // get B(:,j)
for ( ; pB < pB_end ; pB++) // scan B(:,j)
{
GB_GET_B_kj_INDEX ; // get index k of B(k,j)
GB_GET_A_k ; // get A(:,k)
if (aknz == 0) continue ;
GB_GET_B_kj ; // bkj = B(k,j)
// scan A(:,k)
for (int64_t pA = pA_start ; pA < pA_end ; pA++)
{
GB_GET_A_ik_INDEX ; // get index i of A(i,j)
for (GB_HASH (i)) // find i in hash
{
int64_t f = Hf [hash] ;
if (f < mark) // if true, i is new
{
// C(i,j) is new
Hf [hash] = mark1 ; // mark C(i,j) seen
Hi [hash] = i ;
GB_MULT_A_ik_B_kj ; // t = A(i,k)*B(k,j)
GB_HX_WRITE (hash, t) ; // Hx [hash] = t
Ci [pC++] = i ;
break ;
}
if (Hi [hash] == i)
{
if (f == mark1)
{
// C(i,j) has been seen; update it.
GB_MULT_A_ik_B_kj ;//t=A(i,k)*B(k,j)
GB_HX_UPDATE (hash, t) ;//Hx[ ] += t
}
break ;
}
}
}
}
GB_SORT_AND_GATHER_HASHED_C_j (mark1) ;
}
}
}
}
}
C_jumbled = C_jumbled || task_C_jumbled ;
}
//--------------------------------------------------------------------------
// log the state of C->jumbled
//--------------------------------------------------------------------------
C->jumbled = C_jumbled ; // C is jumbled if any task left it jumbled
// ttt = omp_get_wtime ( ) - ttt ;
// GB_Global_timing_add (12, ttt) ;
}
#undef Cx
#undef Hx
|
thread_num.c | #include <stdio.h>
#include <omp.h>
int main() {
#pragma omp parallel num_threads(4)
{
int i = omp_get_thread_num();
printf("Hello from thread %d\n", i);
}
}
|
GB_unop__identity_int8_int64.c | //------------------------------------------------------------------------------
// GB_unop: hard-coded functions for each built-in unary operator
//------------------------------------------------------------------------------
// SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2022, All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
//------------------------------------------------------------------------------
// If this file is in the Generated2/ folder, do not edit it
// (it is auto-generated from Generator/*).
#include "GB.h"
#ifndef GBCOMPACT
#include "GB_control.h"
#include "GB_atomics.h"
#include "GB_unop__include.h"
// C=unop(A) is defined by the following types and operators:
// op(A) function: GB (_unop_apply__identity_int8_int64)
// op(A') function: GB (_unop_tran__identity_int8_int64)
// C type: int8_t
// A type: int64_t
// cast: int8_t cij = (int8_t) aij
// unaryop: cij = aij
#define GB_ATYPE \
int64_t
#define GB_CTYPE \
int8_t
// aij = Ax [pA]
#define GB_GETA(aij,Ax,pA) \
int64_t aij = Ax [pA]
#define GB_CX(p) Cx [p]
// unary operator
#define GB_OP(z, x) \
z = x ;
// casting
#define GB_CAST(z, aij) \
int8_t z = (int8_t) aij ;
// cij = op (aij)
#define GB_CAST_OP(pC,pA) \
{ \
/* aij = Ax [pA] */ \
int64_t aij = Ax [pA] ; \
/* Cx [pC] = op (cast (aij)) */ \
int8_t z = (int8_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_INT8 || GxB_NO_INT64)
//------------------------------------------------------------------------------
// Cx = op (cast (Ax)): apply a unary operator
//------------------------------------------------------------------------------
GrB_Info GB (_unop_apply__identity_int8_int64)
(
int8_t *Cx, // Cx and Ax may be aliased
const int64_t *Ax,
const int8_t *restrict Ab, // A->b if A is bitmap
int64_t anz,
int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
int64_t p ;
if (Ab == NULL)
{
#pragma omp parallel for num_threads(nthreads) schedule(static)
for (p = 0 ; p < anz ; p++)
{
int64_t aij = Ax [p] ;
int8_t z = (int8_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 ;
int64_t aij = Ax [p] ;
int8_t z = (int8_t) aij ;
Cx [p] = z ;
}
}
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// C = op (cast (A')): transpose, typecast, and apply a unary operator
//------------------------------------------------------------------------------
GrB_Info GB (_unop_tran__identity_int8_int64)
(
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
|
particle_utilities.h | // | / |
// ' / __| _` | __| _ \ __|
// . \ | ( | | ( |\__ `
// _|\_\_| \__,_|\__|\___/ ____/
// Multi-Physics
//
// License: BSD License
// Kratos default license: kratos/license.txt
//
// Main authors: Author Julio Marti.
//
#if !defined(KRATOS_PARTICLES_UTILITIES_INCLUDED )
#define KRATOS_PARTICLES_UTILITIES_INCLUDED
#define PRESSURE_ON_EULERIAN_MESH
#define USE_FEW_PARTICLES
// System includes
#include <string>
#include <iostream>
#include <algorithm>
// External includes
// Project includes
#include "includes/define.h"
#include "includes/model_part.h"
#include "includes/node.h"
#include "includes/kratos_flags.h"
#include "utilities/geometry_utilities.h"
#include "geometries/tetrahedra_3d_4.h"
#include "pfem_2_application_variables.h"
#include "spatial_containers/spatial_containers.h"
#include "utilities/timer.h"
#include "processes/node_erase_process.h"
#include "utilities/binbased_fast_point_locator.h"
//#include "utilities/enrichment_utilities.h"
#include <boost/timer.hpp>
#include "utilities/timer.h"
#ifdef _OPENMP
#include "omp.h"
#endif
namespace Kratos
{
template< class T, std::size_t dim >
class DistanceCalculator1
{
public:
double operator()(T const& p1, T const& p2)
{
double dist = 0.0;
for (std::size_t i = 0; i < dim; i++)
{
double tmp = p1[i] - p2[i];
dist += tmp*tmp;
}
return dist; //square distance because it is easier to work without the square root//
}
};
template<std::size_t TDim> class ParticleUtils
{
public:
KRATOS_CLASS_POINTER_DEFINITION(ParticleUtils<TDim>);
void EstimateTime(ModelPart& rEulerianModelPart,const double max_dt)
{
KRATOS_TRY
// KRATOS_ERROR(std::logic_error, "NEGATIVE VALUE OF Time step estimated" , "");
//initializee dt with max dt
//initialize dt with incredible value
double /*dt, glob_min_dt,*/ dummy;
// double h, nu;
array_1d<double,3> N = ZeroVector(3);
array_1d<double,3> aux = ZeroVector(3); //dimension = number of nodes
array_1d<double,3> vel = ZeroVector(3); //dimension = number of nodes
BoundedMatrix<double,3,2> DN_DX = ZeroMatrix(3,2);
array_1d<double,2> ms_vel_gauss = ZeroVector(2); //dimesion coincides with space dimension
//initialize it with given value
// glob_min_dt=max_dt;
// dt=0.0;
for(ModelPart::ElementsContainerType::iterator im = rEulerianModelPart.ElementsBegin() ; im !=rEulerianModelPart.ElementsEnd() ; ++im)
{
GeometryUtils::CalculateGeometryData(im->GetGeometry(),DN_DX,N,dummy);
double h = sqrt(2.00*dummy);
array_1d<double,3> const& v = im->GetGeometry()[0].FastGetSolutionStepValue(VELOCITY);
ms_vel_gauss[0] = v[0];
ms_vel_gauss[1] = v[1];
//direction of the height is stored in the auxilliary vector
for (unsigned int i=1; i<3; i++)
{
array_1d<double,3> const& vi = im->GetGeometry()[i].FastGetSolutionStepValue(VELOCITY);
ms_vel_gauss[0] += vi[0];
ms_vel_gauss[1] += vi[1];
}
ms_vel_gauss *=0.3333;
double norm_u = ms_vel_gauss[0]*ms_vel_gauss[0] + ms_vel_gauss[1]*ms_vel_gauss[1];
norm_u = sqrt(norm_u);
double courant= norm_u * max_dt / h;
double& counter = im->GetValue(POISSON_RATIO);
counter = courant;
}
KRATOS_CATCH("");
}
void VisualizationModelPart(ModelPart& rCompleteModelPart, ModelPart& rEulerianModelPart, ModelPart & rLagrangianModelPart)
{
KRATOS_TRY;
rCompleteModelPart.Elements() = rEulerianModelPart.Elements();
rCompleteModelPart.Nodes() = rEulerianModelPart.Nodes();
unsigned int id;
if(rEulerianModelPart.Nodes().size()!= 0)
id = (rEulerianModelPart.Nodes().end() - 1)->Id() + 1;
else
id = 1;
//preallocate the memory needed
int tot_nodes = rEulerianModelPart.Nodes().size() + rLagrangianModelPart.Nodes().size();
rCompleteModelPart.Nodes().reserve( tot_nodes );
//note that here we renumber the nodes
for (ModelPart::NodesContainerType::iterator node_it = rLagrangianModelPart.NodesBegin();
node_it != rLagrangianModelPart.NodesEnd(); node_it++)
{
node_it->SetId(id++);
rCompleteModelPart.AddNode(*(node_it.base()));
}
KRATOS_CATCH("");
}
void TransferToEulerianMesh_Face_Heat_Flux(ModelPart& rEulerianModelPart, ModelPart & rLagrangianModelPart)
{
KRATOS_TRY
//defintions for spatial search
typedef Node < 3 > PointType;
typedef Node < 3 > ::Pointer PointTypePointer;
typedef std::vector<PointType::Pointer> PointVector;
typedef std::vector<PointType::Pointer>::iterator PointIterator;
typedef std::vector<double> DistanceVector;
typedef std::vector<double>::iterator DistanceIterator;
//creating an auxiliary list for the new nodes
PointVector list_of_nodes;
//*************
// Bucket types
typedef Bucket< TDim, PointType, PointVector, PointTypePointer, PointIterator, DistanceIterator > BucketType;
typedef Tree< KDTreePartition<BucketType> > tree; //Kdtree;
//starting calculating time of construction of the kdtree
boost::timer kdtree_construction;
for (ModelPart::NodesContainerType::iterator node_it = rLagrangianModelPart.NodesBegin();
node_it != rLagrangianModelPart.NodesEnd(); ++node_it)
{
PointTypePointer pnode = *(node_it.base());
//putting the nodes of the destination_model part in an auxiliary list
list_of_nodes.push_back(pnode);
}
std::cout << "kdt constructin time " << kdtree_construction.elapsed() << std::endl;
//create a spatial database with the list of new nodes
unsigned int bucket_size = 20;
tree nodes_tree(list_of_nodes.begin(), list_of_nodes.end(), bucket_size);
//work arrays
Node < 3 > work_point(0, 0.0, 0.0, 0.0);
unsigned int MaximumNumberOfResults = 10000;
PointVector Results(MaximumNumberOfResults);
DistanceVector SquaredResultsDistances(MaximumNumberOfResults);
if (rEulerianModelPart.NodesBegin()->SolutionStepsDataHas(NODAL_H) == false)
KRATOS_ERROR<<"Add ----NODAL_H---- variable!!!!!! ERROR";
double sigma = 0.0;
if (TDim == 2)
sigma = 10.0 / (7.0 * 3.1415926);
else
sigma = 1.0 / 3.1415926;
for (ModelPart::NodesContainerType::iterator node_it = rEulerianModelPart.NodesBegin(); node_it != rEulerianModelPart.NodesEnd(); node_it++)
{
if( (node_it)->FastGetSolutionStepValue(IS_FREE_SURFACE)==true or (node_it)->FastGetSolutionStepValue(IS_WATER)==1 )
{ //IS_FREE_SURFACE
work_point.X() = node_it->X();
work_point.Y() = node_it->Y();
work_point.Z() = node_it->Z();
double radius = 1.5 * node_it->FastGetSolutionStepValue(NODAL_H);
//find all of the new nodes within the radius
int number_of_points_in_radius;
//look between the new nodes which of them is inside the radius of the circumscribed cyrcle
number_of_points_in_radius = nodes_tree.SearchInRadius(work_point, radius, Results.begin(), SquaredResultsDistances.begin(), MaximumNumberOfResults);
if (number_of_points_in_radius > 0)
{
double& temperature = (node_it)->FastGetSolutionStepValue(FACE_HEAT_FLUX);
//double temperature=0.0;
double temperature_aux = 0.0;
double tot_weight = 0.0;
for (int k = 0; k < number_of_points_in_radius; k++)
{
double distance = sqrt(*(SquaredResultsDistances.begin() + k));
double weight = SPHCubicKernel(sigma, distance, radius);
PointIterator it_found = Results.begin() + k;
if((*it_found)->FastGetSolutionStepValue(IS_INTERFACE)==1) //MATERIAL_VARIABLE
{
temperature_aux += weight * (*it_found)->FastGetSolutionStepValue(INCIDENT_RADIATION_FUNCTION);//);//FACE_HEAT_FLUX
tot_weight += weight;
}
}
if(tot_weight>0.0)
{
temperature_aux /= tot_weight;
temperature +=(0.5 * temperature_aux * 1.00); //1.5 //1.25
}
}
}
}
KRATOS_CATCH("")
}
void TransferToEulerianMesh(ModelPart& rEulerianModelPart, ModelPart & rLagrangianModelPart)
{
KRATOS_TRY
//defintions for spatial search
typedef Node < 3 > PointType;
typedef Node < 3 > ::Pointer PointTypePointer;
typedef std::vector<PointType::Pointer> PointVector;
typedef std::vector<PointType::Pointer>::iterator PointIterator;
typedef std::vector<double> DistanceVector;
typedef std::vector<double>::iterator DistanceIterator;
//creating an auxiliary list for the new nodes
PointVector list_of_nodes;
//*************
// Bucket types
typedef Bucket< TDim, PointType, PointVector, PointTypePointer, PointIterator, DistanceIterator > BucketType;
typedef Tree< KDTreePartition<BucketType> > tree; //Kdtree;
//starting calculating time of construction of the kdtree
boost::timer kdtree_construction;
for (ModelPart::NodesContainerType::iterator node_it = rLagrangianModelPart.NodesBegin();
node_it != rLagrangianModelPart.NodesEnd(); ++node_it)
{
PointTypePointer pnode = *(node_it.base());
//putting the nodes of the destination_model part in an auxiliary list
list_of_nodes.push_back(pnode);
}
std::cout << "kdt constructin time " << kdtree_construction.elapsed() << std::endl;
//create a spatial database with the list of new nodes
unsigned int bucket_size = 20;
tree nodes_tree(list_of_nodes.begin(), list_of_nodes.end(), bucket_size);
//work arrays
Node < 3 > work_point(0, 0.0, 0.0, 0.0);
unsigned int MaximumNumberOfResults = 10000;
PointVector Results(MaximumNumberOfResults);
DistanceVector SquaredResultsDistances(MaximumNumberOfResults);
if (rEulerianModelPart.NodesBegin()->SolutionStepsDataHas(NODAL_H) == false)
KRATOS_ERROR<<"Add ----NODAL_H---- variable!!!!!! ERROR";
double sigma = 0.0;
if (TDim == 2)
sigma = 10.0 / (7.0 * 3.1415926);
else
sigma = 1.0 / 3.1415926;
for (ModelPart::NodesContainerType::iterator node_it = rEulerianModelPart.NodesBegin(); node_it != rEulerianModelPart.NodesEnd(); node_it++)
{
if((node_it)->FastGetSolutionStepValue(IS_INTERFACE)==1)
{ //IS_FREE_SURFACE
work_point.X() = node_it->X();
work_point.Y() = node_it->Y();
work_point.Z() = node_it->Z();
//KRATOS_ERROR(std::logic_error, "Add ----NODAL_H---- variable!!!!!! ERROR", "");
double radius = 2.0 * node_it->FastGetSolutionStepValue(NODAL_H);
//find all of the new nodes within the radius
int number_of_points_in_radius;
//look between the new nodes which of them is inside the radius of the circumscribed cyrcle
number_of_points_in_radius = nodes_tree.SearchInRadius(work_point, radius, Results.begin(), SquaredResultsDistances.begin(), MaximumNumberOfResults);
if (number_of_points_in_radius > 0)
{
//double& temperature = (node_it)->FastGetSolutionStepValue(TEMPERATURE);
double temperature_aux = 0.0;
double tot_weight = 0.0;
for (int k = 0; k < number_of_points_in_radius; k++)
{
double distance = sqrt(*(SquaredResultsDistances.begin() + k));
double weight = SPHCubicKernel(sigma, distance, radius);
PointIterator it_found = Results.begin() + k;
//if((*it_found)->FastGetSolutionStepValue(IS_BOUNDARY)>0.5) //MATERIAL_VARIABLE
if((*it_found)->FastGetSolutionStepValue(IS_FREE_SURFACE) ==1 or (*it_found)->FastGetSolutionStepValue(IS_WATER) ==1 ) //MATERIAL_VARIABLE
{
double tempp=0.0;
tempp=(*it_found)->FastGetSolutionStepValue(YCH4);
//KRATOS_ERROR(std::logic_error, "nodo without temperature", "");
if(tempp<298.0) tempp=298.0;
//else tempp=(*it_found)->FastGetSolutionStepValue(YCH4);
temperature_aux += weight * tempp;//temperature
tot_weight += weight;
//KRATOS_ERROR(std::logic_error, "Add ----NODAL_H---- variable!!!!!! ERROR", "");
}
}
if(tot_weight>0.0)
{
temperature_aux /= tot_weight;
(node_it)->FastGetSolutionStepValue(FUEL)=temperature_aux;
}
else
{
KRATOS_WATCH(tot_weight);
KRATOS_WATCH((node_it)->X());
KRATOS_WATCH((node_it)->Y());
if((node_it)->FastGetSolutionStepValue(TEMPERATURE)<298.0) (node_it)->FastGetSolutionStepValue(FUEL)=298.0;
else (node_it)->FastGetSolutionStepValue(FUEL)=(node_it)->FastGetSolutionStepValue(TEMPERATURE);
}
}
}
else
{
//(node_it)->FastGetSolutionStepValue(FUEL)=(node_it)->FastGetSolutionStepValue(TEMPERATURE);
}
}
KRATOS_CATCH("")
}
void TransferToEulerianMeshShapeBased_aux(ModelPart& rEulerianModelPart, ModelPart & rLagrangianModelPart, BinBasedFastPointLocator<TDim>& node_locator)
{
KRATOS_TRY
Vector N;
const int max_results = 1000;
typename BinBasedFastPointLocator<TDim>::ResultContainerType results(max_results);
const int nparticles = rLagrangianModelPart.Nodes().size();
#pragma omp parallel for firstprivate(results,N)
for (int i = 0; i < nparticles; i++)
{
ModelPart::NodesContainerType::iterator iparticle = rLagrangianModelPart.NodesBegin() + i;
Node < 3 > ::Pointer pparticle = *(iparticle.base());
typename BinBasedFastPointLocator<TDim>::ResultIteratorType result_begin = results.begin();
Element::Pointer pelement;
bool is_found = node_locator.FindPointOnMesh(pparticle->Coordinates(), N, pelement, result_begin, max_results);
if (is_found == true)
{
Geometry<Node<3> >& geom = pelement->GetGeometry();
BoundedMatrix<double, 3, 2 > msDN_DX;
array_1d<double, 3 > N;
//array_1d<double, 3 > N;
double Area=0.0;
GeometryUtils::CalculateGeometryData(geom, msDN_DX, N, Area);
int s0=0;
int s1=0;
int s2=0;
int sum=0;
if(geom[0].FastGetSolutionStepValue(IS_INTERFACE)>0.5) s0=1; //IS_INTERFACE
if(geom[1].FastGetSolutionStepValue(IS_INTERFACE)>0.5) s1=1;
if(geom[2].FastGetSolutionStepValue(IS_INTERFACE)>0.5) s2=1;
sum=s0 + s1 + s2;
array_1d<double, 2 > qrad=ZeroVector(2);
array_1d<double, 2 > qrad_P1=ZeroVector(2);
array_1d<double,2> interface_segment=ZeroVector(2);
array_1d<double,2> normaledge1=ZeroVector(2);
for (unsigned int jj = 0; jj < 2; jj++)
{
for (unsigned int kk = 0; kk < 3; kk++)
{
qrad[jj] += msDN_DX(kk, jj) * geom[kk].FastGetSolutionStepValue(TEMPERATURE);
qrad_P1[jj] += msDN_DX(kk, jj) * geom[kk].FastGetSolutionStepValue(INCIDENT_RADIATION_FUNCTION);
}
}
double faceheatflux=0.0;
//double faceheatflux_P1=0.0;
if(sum==2)
{
if((geom[1].FastGetSolutionStepValue(IS_INTERFACE)>0.5 && geom[0].FastGetSolutionStepValue(IS_INTERFACE)>0.5)) //IS_INTERFACE
{
double norm=0.0;
//KRATOS_ERROR(std::logic_error, "element with zero vol found", "");
interface_segment[0] = (geom[0].X()-geom[1].X());
interface_segment[1] = (geom[0].Y()-geom[1].Y());
norm = sqrt( pow((interface_segment[0]),2) + pow((interface_segment[1]),2));
//double area1=norm;
normaledge1(0)= -interface_segment[1]/norm;
normaledge1(1)= interface_segment[0]/norm;
faceheatflux += abs(1.0*(qrad[0]*normaledge1(0)+qrad[1]*normaledge1(1))*0.0131);
}
if((geom[1].FastGetSolutionStepValue(IS_INTERFACE)>0.5 && geom[2].FastGetSolutionStepValue(IS_INTERFACE)>0.5))
{
double norm=0.0;
interface_segment[0] = (geom[1].X()-geom[2].X());
interface_segment[1] = (geom[1].Y()-geom[2].Y());
norm = sqrt( pow((interface_segment[0]),2) + pow((interface_segment[1]),2));
//double area1=norm;
normaledge1(0)= -interface_segment[1]/norm;
normaledge1(1)= interface_segment[0]/norm;
faceheatflux += abs(1.0*(qrad[0]*normaledge1(0)+qrad[1]*normaledge1(1))*0.0131);
}
if((geom[2].FastGetSolutionStepValue(IS_INTERFACE)>0.5 && geom[0].FastGetSolutionStepValue(IS_INTERFACE)>0.5))
{
double norm=0.0;
interface_segment[0] = (geom[2].X()-geom[0].X());
interface_segment[1] = (geom[2].Y()-geom[0].Y());
norm = sqrt( pow((interface_segment[0]),2) + pow((interface_segment[1]),2));
normaledge1(0)= -interface_segment[1]/norm;
normaledge1(1)= interface_segment[0]/norm;
faceheatflux += abs(1.0*(qrad[0]*normaledge1(0)+qrad[1]*normaledge1(1))*0.0131);
}
}
if(sum==1)
{
if((geom[1].FastGetSolutionStepValue(IS_INTERFACE)<0.5 && geom[0].FastGetSolutionStepValue(IS_INTERFACE)<0.5)) //IS_INTERFACE
{
double norm=0.0;
interface_segment[0] = (geom[0].X()-geom[1].X());
interface_segment[1] = (geom[0].Y()-geom[1].Y());
norm = sqrt( pow((interface_segment[0]),2) + pow((interface_segment[1]),2));
normaledge1(0)= -interface_segment[1]/norm;
normaledge1(1)= interface_segment[0]/norm;
faceheatflux += abs(1.0*(qrad[0]*normaledge1(0)+qrad[1]*normaledge1(1))*0.0131);
}
if((geom[1].FastGetSolutionStepValue(IS_INTERFACE)<0.5 && geom[2].FastGetSolutionStepValue(IS_INTERFACE)<0.5))
{
double norm=0.0;
interface_segment[0] = (geom[1].X()-geom[2].X());
interface_segment[1] = (geom[1].Y()-geom[2].Y());
norm = sqrt( pow((interface_segment[0]),2) + pow((interface_segment[1]),2));
normaledge1(0)= -interface_segment[1]/norm;
normaledge1(1)= interface_segment[0]/norm;
faceheatflux += abs(1.0*(qrad[0]*normaledge1(0)+qrad[1]*normaledge1(1))*0.0131);
}
if((geom[2].FastGetSolutionStepValue(IS_INTERFACE)<0.5 && geom[0].FastGetSolutionStepValue(IS_INTERFACE)<0.5))
{
double norm=0.0;
interface_segment[0] = (geom[2].X()-geom[0].X());
interface_segment[1] = (geom[2].Y()-geom[0].Y());
norm = sqrt( pow((interface_segment[0]),2) + pow((interface_segment[1]),2));
normaledge1(0)= -interface_segment[1]/norm;
normaledge1(1)= interface_segment[0]/norm;
faceheatflux += abs(1.0*(qrad[0]*normaledge1(0)+qrad[1]*normaledge1(1))*0.0131);
}
}
(iparticle)->FastGetSolutionStepValue(FACE_HEAT_FLUX)+=(faceheatflux /*+ fhf+ faceheatflux_P1*/);
}
}
KRATOS_CATCH("")
}
///3D
void CalculateNormal(ModelPart& full_model_part)
{
KRATOS_TRY
//resetting the normals
array_1d<double,3> zero;
noalias(zero) = ZeroVector(3);
for(ModelPart::NodesContainerType::const_iterator in = full_model_part.NodesBegin(); in!=full_model_part.NodesEnd(); in++)
{
in->FastGetSolutionStepValue(NORMAL) = zero;
}
array_1d<double,3> v1;
array_1d<double,3> v2;
//array_1d<double,3>& An =zero;
//double area_normal=0.0;
array_1d<double,3> area_normal;
for(ModelPart::ElementsContainerType::iterator iii = full_model_part.ElementsBegin(); iii != full_model_part.ElementsEnd(); iii++)
{
if( iii->GetGeometry()[1].FastGetSolutionStepValue(IS_BOUNDARY) == 1.0 && iii->GetGeometry()[2].FastGetSolutionStepValue(IS_BOUNDARY) == 1.0 && iii->GetGeometry()[3].FastGetSolutionStepValue(IS_BOUNDARY) == 1.0)
{
v1[0] = iii->GetGeometry()[1].X() -iii->GetGeometry()[3].X();
v1[1] = iii->GetGeometry()[1].Y() - iii->GetGeometry()[3].Y();
v1[2] = iii->GetGeometry()[1].Z() - iii->GetGeometry()[3].Z();
v2[0] = iii->GetGeometry()[2].X() - iii->GetGeometry()[3].X();
v2[1] = iii->GetGeometry()[2].Y() - iii->GetGeometry()[3].Y();
v2[2] = iii->GetGeometry()[2].Z() - iii->GetGeometry()[3].Z();
MathUtils<double>::CrossProduct(area_normal,v1,v2);
//area_normal *= -0.5;
array_1d<double,3> msAuxVec = ZeroVector(3);
double c0 = abs(area_normal[0]);
double c1 = abs(area_normal[1]);
double c2 = abs(area_normal[2]);
msAuxVec[0]=c0;
msAuxVec[1]=c1;
msAuxVec[2]=c2;
// double norm_c =norm_2(msAuxVec);
double norm_u = msAuxVec[0]*msAuxVec[0] + msAuxVec[1]*msAuxVec[1] + msAuxVec[2]*msAuxVec[2];
double norm_c =sqrt(norm_u);
iii->GetGeometry()[1].FastGetSolutionStepValue(NORMAL) += area_normal/ norm_c;
iii->GetGeometry()[2].FastGetSolutionStepValue(NORMAL) += area_normal/ norm_c;
iii->GetGeometry()[3].FastGetSolutionStepValue(NORMAL) += area_normal/ norm_c;
}
if( iii->GetGeometry()[0].FastGetSolutionStepValue(IS_BOUNDARY) == 1.0 && iii->GetGeometry()[3].FastGetSolutionStepValue(IS_BOUNDARY) == 1.0 && iii->GetGeometry()[2].FastGetSolutionStepValue(IS_BOUNDARY) == 1.0)
{
v1[0] = iii->GetGeometry()[0].X() -iii->GetGeometry()[2].X();
v1[1] = iii->GetGeometry()[0].Y() - iii->GetGeometry()[2].Y();
v1[2] = iii->GetGeometry()[0].Z() - iii->GetGeometry()[2].Z();
v2[0] = iii->GetGeometry()[3].X() - iii->GetGeometry()[2].X();
v2[1] = iii->GetGeometry()[3].Y() - iii->GetGeometry()[2].Y();
v2[2] = iii->GetGeometry()[3].Z() - iii->GetGeometry()[2].Z();
MathUtils<double>::CrossProduct(area_normal,v1,v2);
//area_normal *= -0.5;
array_1d<double,3> msAuxVec = ZeroVector(3);
double c0 = abs(area_normal[0]);
double c1 = abs(area_normal[1]);
double c2 = abs(area_normal[2]);
msAuxVec[0]=c0;
msAuxVec[1]=c1;
msAuxVec[2]=c2;
//double norm_c =norm_2(msAuxVec);
double norm_u = msAuxVec[0]*msAuxVec[0] + msAuxVec[1]*msAuxVec[1] + msAuxVec[2]*msAuxVec[2];
double norm_c =sqrt(norm_u);
iii->GetGeometry()[0].FastGetSolutionStepValue(NORMAL) += area_normal/ norm_c;
iii->GetGeometry()[3].FastGetSolutionStepValue(NORMAL) += area_normal/ norm_c;
iii->GetGeometry()[2].FastGetSolutionStepValue(NORMAL) += area_normal/ norm_c;
}
if( iii->GetGeometry()[0].FastGetSolutionStepValue(IS_BOUNDARY) == 1.0 && iii->GetGeometry()[1].FastGetSolutionStepValue(IS_BOUNDARY) == 1.0 && iii->GetGeometry()[3].FastGetSolutionStepValue(IS_BOUNDARY) == 1.0)
{
v1[0] = iii->GetGeometry()[0].X() -iii->GetGeometry()[3].X();
v1[1] = iii->GetGeometry()[0].Y() - iii->GetGeometry()[3].Y();
v1[2] = iii->GetGeometry()[0].Z() - iii->GetGeometry()[3].Z();
v2[0] = iii->GetGeometry()[1].X() - iii->GetGeometry()[3].X();
v2[1] = iii->GetGeometry()[1].Y() - iii->GetGeometry()[3].Y();
v2[2] = iii->GetGeometry()[1].Z() - iii->GetGeometry()[3].Z();
MathUtils<double>::CrossProduct(area_normal,v1,v2);
//area_normal *= -0.5;
array_1d<double,3> msAuxVec = ZeroVector(3);
double c0 = abs(area_normal[0]);
double c1 = abs(area_normal[1]);
double c2 = abs(area_normal[2]);
msAuxVec[0]=c0;
msAuxVec[1]=c1;
msAuxVec[2]=c2;
double norm_u = msAuxVec[0]*msAuxVec[0] + msAuxVec[1]*msAuxVec[1] + msAuxVec[2]*msAuxVec[2];
double norm_c =sqrt(norm_u);
iii->GetGeometry()[0].FastGetSolutionStepValue(NORMAL) += area_normal/ norm_c;
iii->GetGeometry()[1].FastGetSolutionStepValue(NORMAL) += area_normal/ norm_c;
iii->GetGeometry()[3].FastGetSolutionStepValue(NORMAL) += area_normal/ norm_c;
}
if( iii->GetGeometry()[0].FastGetSolutionStepValue(IS_BOUNDARY) == 1.0 && iii->GetGeometry()[2].FastGetSolutionStepValue(IS_BOUNDARY) == 1.0 && iii->GetGeometry()[1].FastGetSolutionStepValue(IS_BOUNDARY) == 1.0)
{
v1[0] = iii->GetGeometry()[0].X() -iii->GetGeometry()[1].X();
v1[1] = iii->GetGeometry()[0].Y() - iii->GetGeometry()[1].Y();
v1[2] = iii->GetGeometry()[0].Z() - iii->GetGeometry()[1].Z();
v2[0] = iii->GetGeometry()[2].X() - iii->GetGeometry()[1].X();
v2[1] = iii->GetGeometry()[2].Y() - iii->GetGeometry()[1].Y();
v2[2] = iii->GetGeometry()[2].Z() - iii->GetGeometry()[1].Z();
MathUtils<double>::CrossProduct(area_normal,v1,v2);
//area_normal *= -0.5;
array_1d<double,3> msAuxVec = ZeroVector(3);
double c0 = abs(area_normal[0]);
double c1 = abs(area_normal[1]);
double c2 = abs(area_normal[2]);
msAuxVec[0]=c0;
msAuxVec[1]=c1;
msAuxVec[2]=c2;
// double norm_c =norm_2(msAuxVec);
double norm_u = msAuxVec[0]*msAuxVec[0] + msAuxVec[1]*msAuxVec[1] + msAuxVec[2]*msAuxVec[2];
double norm_c =sqrt(norm_u);
iii->GetGeometry()[0].FastGetSolutionStepValue(NORMAL) += area_normal/ norm_c;
iii->GetGeometry()[2].FastGetSolutionStepValue(NORMAL) += area_normal/ norm_c;
iii->GetGeometry()[1].FastGetSolutionStepValue(NORMAL) += area_normal/ norm_c;
}
}
for(ModelPart::NodesContainerType::iterator iii = full_model_part.NodesBegin(); iii != full_model_part.NodesEnd(); iii++)
{
if(iii->FastGetSolutionStepValue(IS_BOUNDARY)==1.0){
array_1d<double,3>& value_y1 = iii->FastGetSolutionStepValue(NORMAL);
double norm_y1 =norm_2(value_y1);
value_y1 /=(norm_y1 + 1e-9);
}
}
KRATOS_CATCH("")
}
void TransferToEulerianMeshShapeBased_aux_3D(ModelPart& rEulerianModelPart, ModelPart & rLagrangianModelPart, BinBasedFastPointLocator<TDim>& node_locator)
{
KRATOS_TRY
//typedef Node < 3 > PointType;
//typedef Node < 3 > ::Pointer PointTypePointer;
Vector N;
const int max_results = 1000;
typename BinBasedFastPointLocator<TDim>::ResultContainerType results(max_results);
const int nparticles = rLagrangianModelPart.Nodes().size();
#pragma omp parallel for firstprivate(results,N)
for (int i = 0; i < nparticles; i++)
{
ModelPart::NodesContainerType::iterator iparticle = rLagrangianModelPart.NodesBegin() + i;
Node < 3 > ::Pointer pparticle = *(iparticle.base());
typename BinBasedFastPointLocator<TDim>::ResultIteratorType result_begin = results.begin();
Element::Pointer pelement;
bool is_found = node_locator.FindPointOnMesh(pparticle->Coordinates(), N, pelement, result_begin, max_results);
if (is_found == true)
{
Geometry<Node<3> >& geom = pelement->GetGeometry();
BoundedMatrix<double, 4, 3 > msDN_DX;
array_1d<double, 4 > N;
double Area=0.0;
GeometryUtils::CalculateGeometryData(geom, msDN_DX, N, Area);
array_1d<double, 3 > qrad=ZeroVector(3);
double temmp=0.0;
for (unsigned int jj = 0; jj < 3; jj++)
{
for (unsigned int kk = 0; kk < 4; kk++)
{
temmp=geom[kk].FastGetSolutionStepValue(TEMPERATURE);
if(temmp<298.0) temmp=298.0;
qrad[jj] += msDN_DX(kk, jj) * temmp;//geom[kk].FastGetSolutionStepValue(TEMPERATURE);
}
}
//double faceheatflux=0.0;
(iparticle)->FastGetSolutionStepValue(NORMAL) *=(-1.0);
(iparticle)->FastGetSolutionStepValue(FACE_HEAT_FLUX) += abs( (iparticle)->FastGetSolutionStepValue(NORMAL_X) * qrad[0] + (iparticle)->FastGetSolutionStepValue(NORMAL_Y) * qrad[1] + (iparticle)->FastGetSolutionStepValue(NORMAL_Z) * qrad[2]) *0.0131;
}
}
KRATOS_CATCH("")
}
//restarting the step from the beginning
void RestartStep(ModelPart & rModelPart)
{
KRATOS_TRY;
//setting the variables to their value at the beginning of the time step
rModelPart.OverwriteSolutionStepData(1, 0);
//setting the coordinates to their value at the beginning of the step
for (ModelPart::NodesContainerType::iterator node_it = rModelPart.NodesBegin();node_it != rModelPart.NodesEnd(); node_it++)
{
array_1d<double, 3 > & coords = node_it->Coordinates();
const array_1d<double, 3 > & old_disp = node_it->FastGetSolutionStepValue(DISPLACEMENT, 1);
coords[0] = node_it->X0() + old_disp[0];
coords[1] = node_it->Y0() + old_disp[1];
coords[2] = node_it->Z0() + old_disp[2];
}
KRATOS_CATCH("");
}
void MoveMesh_Streamlines_freesurfaceflows(ModelPart& rModelPart, unsigned int substeps)
{
const double dt = rModelPart.GetProcessInfo()[DELTA_TIME];
//KRATOS_ERROR(std::logic_error, "element with zero vol found", "");
BinBasedFastPointLocator<TDim> SearchStructure(rModelPart);
SearchStructure.UpdateSearchDatabase();
//do movement
array_1d<double, 3 > veulerian;
//double temperature=0.0;
array_1d<double, 3 > acc_particle;
Vector N;
const int max_results = 10000;
typename BinBasedFastPointLocator<TDim>::ResultContainerType results(max_results);
const int nparticles = rModelPart.Nodes().size();
#pragma omp parallel for firstprivate(results,N,veulerian,acc_particle)
for (int i = 0; i < nparticles; i++)
{
//int substep = 0;
int subdivisions = 5;
//double temperature=0.0;
ModelPart::NodesContainerType::iterator iparticle = rModelPart.NodesBegin() + i;
Node < 3 > ::Pointer pparticle = *(iparticle.base());
//small_dt = dt / subdivisions;
bool do_move = true;
bool first_time=false;
iparticle->FastGetSolutionStepValue(DISTANCE)=0.0;
iparticle->FastGetSolutionStepValue(EMBEDDED_VELOCITY) = iparticle->FastGetSolutionStepValue(VELOCITY,1); //AUX_VEL
if(iparticle->Is(SLIP)) do_move = false;
//iparticle->FastGetSolutionStepValue(TEMPERATURE) = 298.0;
if( do_move == true ) //note that we suppose the velocity components to be all fixed
{
array_1d<double,3> old_position = pparticle->Coordinates();
array_1d<double,3> current_position = pparticle->Coordinates();
noalias(iparticle->GetInitialPosition()) = old_position;
iparticle->FastGetSolutionStepValue(DISPLACEMENT,1) = ZeroVector(3);
//array_1d<double, 3 > & vel_particle = iparticle->FastGetSolutionStepValue(VELOCITY);
//subdivisions=10;
const double small_dt = dt / subdivisions;
//
for (int substep = 0; substep < subdivisions; substep++)
{
typename BinBasedFastPointLocator<TDim>::ResultIteratorType result_begin = results.begin();
Element::Pointer pelement;
bool is_found = SearchStructure.FindPointOnMesh(current_position, N, pelement, result_begin, max_results);
iparticle->Set(TO_ERASE, true);
//(iparticle)->GetValue(ERASE_FLAG) = true;
//KRATOS_WATCH(is_found);
if (is_found == true)
{
Geometry< Node < 3 > >& geom = pelement->GetGeometry();
//int nn=0;
noalias(veulerian) = ZeroVector(3); //0.0;//N[0] * geom[0].FastGetSolutionStepValue(VELOCITY,1);
//temperature=0.0;//N[0] * geom[0].FastGetSolutionStepValue(TEMPERATURE);
for (unsigned int k = 0; k < geom.size(); k++)
{
noalias(veulerian) += N[k] * geom[k].FastGetSolutionStepValue(VELOCITY,1);
}
/*if(iparticle->FastGetSolutionStepValue(IS_LAGRANGIAN_INLET)==1)
{
veulerian(0)*=0.0;
veulerian(2)*=0.0;
}*/
first_time=true;
noalias(current_position) += small_dt*veulerian;
pparticle->Set(TO_ERASE, false);
iparticle->FastGetSolutionStepValue(DISTANCE) += small_dt;
iparticle->FastGetSolutionStepValue(EMBEDDED_VELOCITY)=veulerian;
}
else
{
double time1=iparticle->FastGetSolutionStepValue(DISTANCE);
array_1d<double,3> acc;
acc[0] = 0.0;
acc[1] = -10.0;
acc[2] = 0.0;
if( first_time == false /*&& iparticle->Is(SLIP) == false*/ )
{
noalias(current_position) += small_dt *iparticle->FastGetSolutionStepValue(EMBEDDED_VELOCITY);
//noalias(current_position) += small_dt * small_dt * acc;
pparticle->Set(TO_ERASE, false);
}
else
{
time1 -=small_dt;
//double tiempo_restante=dt-time1;
noalias(current_position) += small_dt *iparticle->FastGetSolutionStepValue(EMBEDDED_VELOCITY);
//noalias(current_position) += small_dt * small_dt * acc;
pparticle->Set(TO_ERASE, false);
}
}
}//for
//update the displacement BUT DO NOT OVERWRITE THE POSITION!!
iparticle->FastGetSolutionStepValue(DISPLACEMENT) = current_position - iparticle->GetInitialPosition();
//KRATOS_WATCH(iparticle->FastGetSolutionStepValue(DISPLACEMENT));
}//move
}
//compute mesh velocity
for(ModelPart::NodesContainerType::iterator it = rModelPart.NodesBegin(); it!=rModelPart.NodesEnd(); it++)
{
//array_1d<double,3>& dn = it->FastGetSolutionStepValue(DISPLACEMENT,1);
array_1d<double,3>& dn1 = it->FastGetSolutionStepValue(DISPLACEMENT);
noalias(it->Coordinates()) = it->GetInitialPosition();
noalias(it->Coordinates()) += dn1;
}
}
void MoveLonelyNodes(ModelPart& ThisModelPart)
{
KRATOS_TRY;
double Dt = ThisModelPart.GetProcessInfo()[DELTA_TIME];
array_1d<double,3> DeltaDisp, acc;
for(ModelPart::NodeIterator i = ThisModelPart.NodesBegin() ;
i != ThisModelPart.NodesEnd() ; ++i)
{
if(
(i)->Is(SLIP) == false &&
(i)->GetValue(NEIGHBOUR_ELEMENTS).size() == 0 &&
((i)->GetDof(VELOCITY_X).IsFixed() == false || (i)->GetDof(VELOCITY_Y).IsFixed() == false || (i)->GetDof(VELOCITY_Z).IsFixed() == false)
)
{
//i->Set(TO_ERASE,true);
//set to zero the pressure
(i)->FastGetSolutionStepValue(PRESSURE) = 0;
const array_1d<double,3>& old_vel = (i)->FastGetSolutionStepValue(VELOCITY,1);
array_1d<double,3>& vel = (i)->FastGetSolutionStepValue(VELOCITY);
//array_1d<double,3>& acc = (i)->FastGetSolutionStepValue(ACCELERATION);
noalias(acc) = (i)->FastGetSolutionStepValue(BODY_FORCE);
acc[0]= 0.0;
acc[1]= -10.0;
acc[2]= 0.0;
noalias(vel) = old_vel;
noalias(vel) += Dt * acc ;
//calculate displacements
//noalias(DeltaDisp) = Dt * vel;
//array_1d<double,3>& disp = i->FastGetSolutionStepValue(DISPLACEMENT);
//noalias(disp) = i->FastGetSolutionStepValue(DISPLACEMENT,1);
//noalias(disp) += DeltaDisp;
noalias(i->Coordinates()) += Dt * Dt * acc;
}
}
KRATOS_CATCH("")
}
void MarkExcessivelyCloseNodes(ModelPart::NodesContainerType& rNodes)
{
KRATOS_TRY;
KRATOS_WATCH("ENTERD Mark close nodes")
//double fact2 = admissible_distance_factor*admissible_distance_factor;
for(ModelPart::NodesContainerType::iterator in = rNodes.begin(); in!=rNodes.end(); in++)
{
if(in->FastGetSolutionStepValue(IS_LAGRANGIAN_INLET) ==1) //if it is not a wall node i can erase
{
int nf=0;
//loop on neighbours and erase if they are too close
for( GlobalPointersVector< Node<3> >::iterator i = in->GetValue(NEIGHBOUR_NODES).begin(); i != in->GetValue(NEIGHBOUR_NODES).end(); i++)
{
//KRATOS_ERROR(std::logic_error, "element with zero vol found", "");
if( /*i->FastGetSolutionStepValue(IS_LAGRANGIAN_INLET) ==1 and*/ i->FastGetSolutionStepValue(IS_FREE_SURFACE) ==1) //we can erase the current node only if the neighb is not to be erased
{
//KRATOS_ERROR(std::logic_error, "element with zero vol found", "");
nf++;
//KRATOS_WATCH(nf)
}
if(nf>=2) {in->FastGetSolutionStepValue(IS_WATER)= 1;
//KRATOS_ERROR(std::logic_error, "element with zero vol found", "");
}
}
}
}
KRATOS_CATCH("")
}
void TransferToParticlesAirVelocity(ModelPart& rEulerianModelPart, ModelPart & rLagrangianModelPart, BinBasedFastPointLocator<TDim>& node_locator)
{
KRATOS_TRY
//defintions for spatial search
//typedef Node < 3 > PointType;
//typedef Node < 3 > ::Pointer PointTypePointer;
Vector N;
const int max_results = 1000;
typename BinBasedFastPointLocator<TDim>::ResultContainerType results(max_results);
const int nparticles = rLagrangianModelPart.Nodes().size();
#pragma omp parallel for firstprivate(results,N)
for (int i = 0; i < nparticles; i++)
{
ModelPart::NodesContainerType::iterator iparticle = rLagrangianModelPart.NodesBegin() + i;
Node < 3 > ::Pointer pparticle = *(iparticle.base());
typename BinBasedFastPointLocator<TDim>::ResultIteratorType result_begin = results.begin();
Element::Pointer pelement;
bool is_found = node_locator.FindPointOnMesh(pparticle->Coordinates(), N, pelement, result_begin, max_results);
if (is_found == true)
{
Geometry<Node<3> >& geom = pelement->GetGeometry();
BoundedMatrix<double, 4, 3 > msDN_DX;
array_1d<double, 4 > N;
double Area=0.0;
GeometryUtils::CalculateGeometryData(geom, msDN_DX, N, Area);
array_1d<double, 3 > velocity=ZeroVector(3);
array_1d<double, 3 > temmp=ZeroVector(3);
//double temmp=0.0;
for (unsigned int jj = 0; jj < 3; jj++)
{
temmp=geom[jj].FastGetSolutionStepValue(VELOCITY);
velocity =N(jj) * temmp;
}
//KRATOS_WATCH(qrad);
//double faceheatflux=0.0;
(iparticle)->FastGetSolutionStepValue(ANGULAR_VELOCITY) = velocity;
}
}
KRATOS_CATCH("")
}
double Calculate_Vol(ModelPart & rLagrangianModelPart)
{
KRATOS_TRY
//defintions for spatial search
//typedef Node < 3 > PointType;
//typedef Node < 3 > ::Pointer PointTypePointer;
//particles
for (ModelPart::NodesContainerType::iterator node_it = rLagrangianModelPart.NodesBegin(); node_it != rLagrangianModelPart.NodesEnd(); node_it++)
{
if( node_it->GetValue(NEIGHBOUR_ELEMENTS).size() != 0) (node_it)->FastGetSolutionStepValue(K0) = 0.0;
//if( node_it->FastGetSolutionStepValue(NODAL_MASS) == 0.0) KRATOS_ERROR(std::logic_error, "element with zero vol found", "");
}
for (ModelPart::ElementsContainerType::iterator el_it = rLagrangianModelPart.ElementsBegin();el_it != rLagrangianModelPart.ElementsEnd(); el_it++)
{
Geometry<Node < 3 > >& geom = el_it->GetGeometry();
double x0 = geom[0].X();
double y0 = geom[0].Y();
double z0 = geom[0].Z();
double x1 = geom[1].X();
double y1 = geom[1].Y();
double z1 = geom[1].Z();
double x2 = geom[2].X();
double y2 = geom[2].Y();
double z2 = geom[2].Z();
double x3 = geom[3].X();
double y3 = geom[3].Y();
double z3 = geom[3].Z();
double area=0.0;
area=CalculateVol(x0, y0, z0, x1, y1, z1, x2, y2, z2, x3, y3, z3);
geom[0].FastGetSolutionStepValue(K0) += area * 0.25;
geom[1].FastGetSolutionStepValue(K0) += area * 0.25;
geom[2].FastGetSolutionStepValue(K0) += area * 0.25;
geom[3].FastGetSolutionStepValue(K0) += area * 0.25;
}
double sum=0.0;
for (ModelPart::NodesContainerType::iterator node_it = rLagrangianModelPart.NodesBegin(); node_it != rLagrangianModelPart.NodesEnd(); node_it++)
{
sum +=(node_it)->FastGetSolutionStepValue(K0) ;
}
return sum;
KRATOS_CATCH("")
}
void DetectAllOilClusters(ModelPart & mp_local_model_part)
{
int mnumber_of_oil_clusters=0;
for (ModelPart::NodesContainerType::iterator inode = mp_local_model_part.NodesBegin(); inode != mp_local_model_part.NodesEnd(); inode++)
{
inode->FastGetSolutionStepValue(DIAMETER) = -1; //OIL_CLUSTER
}
for (ModelPart::ElementsContainerType::iterator ielem = mp_local_model_part.ElementsBegin();ielem != mp_local_model_part.ElementsEnd(); ielem++)
{
Geometry< Node<3> >& geom = ielem->GetGeometry();
if(geom.size()>1)
{
ielem->GetValue(DIAMETER) = -1;
}
}
//fist we paint all the nodes connected to the outlet:
int color = 0;
for (ModelPart::NodesContainerType::iterator inode = mp_local_model_part.NodesBegin(); inode != mp_local_model_part.NodesEnd(); inode++)
{
if(inode->IsFixed(POROSITY) && inode->FastGetSolutionStepValue(DIAMETER)!=0) //nodes connected to the outlet are flagged as cluster zero. // if(inode->IsFixed(CONNECTED_TO_OUTLET) && inode->FastGetSolutionStepValue(OIL_CLUSTER)!=0)
{
ColorOilClusters(inode, 0);
}
}
//having painted those nodes, we proceed with the rest of the colours
for (ModelPart::NodesContainerType::iterator inode = mp_local_model_part.NodesBegin(); inode != mp_local_model_part.NodesEnd(); inode++)
{
if(inode->FastGetSolutionStepValue(DIAMETER) < 0 )
{
color++;
ColorOilClusters(inode, color);
}
}
for (ModelPart::ElementsContainerType::iterator ielem = mp_local_model_part.ElementsBegin(); ielem != mp_local_model_part.ElementsEnd(); ielem++)
{
Geometry< Node<3> >& geom = ielem->GetGeometry();
if(geom.size()>1 && ielem->GetValue(DIAMETER) < 0 )
{
color++;
ielem->GetValue(DIAMETER) = color;
}
}
//finally we flag the nodes with cluster=0 as connected to outlet
for (ModelPart::NodesContainerType::iterator inode = mp_local_model_part.NodesBegin(); inode != mp_local_model_part.NodesEnd(); inode++)
{
if(inode->FastGetSolutionStepValue(DIAMETER) == 0)
inode->FastGetSolutionStepValue(POROSITY)=1.0;
}
mnumber_of_oil_clusters = color;
double area=0.0;
array_1d<double, 3 > velocity_a=ZeroVector(3);
array_1d<double, 3 > velocity_p=ZeroVector(3);
array_1d<double, 3 > temmp=ZeroVector(3);
array_1d<double, 3 > drag_coefficient=ZeroVector(3);
//KRATOS_WATCH(mnumber_of_oil_clusters);
int zz= mnumber_of_oil_clusters + 1;
for(int jj=0; jj< zz; jj++ )
{
if(jj!=0)
{
if(jj==0) KRATOS_ERROR<<"element with zero vol found";
//KRATOS_ERROR(std::logic_error, "element with zero vol found", "");
area=0.0;
velocity_a=ZeroVector(3);
velocity_p=ZeroVector(3);
drag_coefficient=ZeroVector(3);
int nn=0;
for (ModelPart::NodesContainerType::iterator inode = mp_local_model_part.NodesBegin(); inode != mp_local_model_part.NodesEnd(); inode++)
{
int colour_p = (inode)->FastGetSolutionStepValue(DIAMETER);
if(colour_p==jj)
{
area += (inode)->FastGetSolutionStepValue(K0);
velocity_a += (inode)->FastGetSolutionStepValue(ANGULAR_VELOCITY);
velocity_p += (inode)->FastGetSolutionStepValue(VELOCITY);
nn++;
}
}
velocity_a *=(1.0/nn);
velocity_p *=(1.0/nn);
//KRATOS_WATCH("AREA_ANTES");
//KRATOS_WATCH("area");
ComputedDragCoefficient(area, velocity_a, velocity_p, drag_coefficient );
for (ModelPart::NodesContainerType::iterator inode = mp_local_model_part.NodesBegin(); inode != mp_local_model_part.NodesEnd(); inode++)
{
int colour_p = (inode)->FastGetSolutionStepValue(DIAMETER);
if(colour_p==jj)
{
inode->FastGetSolutionStepValue(DRAG_FORCE_X)=drag_coefficient(0);
inode->FastGetSolutionStepValue(DRAG_FORCE_Y)=drag_coefficient(1);
inode->FastGetSolutionStepValue(DRAG_FORCE_Z)=drag_coefficient(2);
}
}
}
}
}
void ComputedDragCoefficient(double nodal_mass, array_1d<double, 3> velocity_air, array_1d<double, 3> velocity_polymer, array_1d<double, 3> & drag_coefficient )
{
KRATOS_TRY
double drag_coeff=0.0;
//array_1d<double, 3> drag_coefficient=ZeroVector(3);
//nodal_mass=0.0;
array_1d<double, 3> vrelative;
//nodal_mass=(node_it)->FastGetSolutionStepValue(NODAL_MASS);
double aux=nodal_mass * 3.0/(3.0*3.1416);
double Radius= pow(aux, 0.3333333);
double area=4.0 * 3.1416 * Radius * Radius;
noalias(vrelative)=velocity_air-velocity_polymer;
double norm_u = norm_2(vrelative);
double reynolds = 2 * Radius * norm_u / 0.00001; // 2 * mRadius * mNormOfSlipVel / mKinematicViscosity
if (reynolds < 0.01)
{
reynolds = 0.01;
}
CalculateNewtonianDragCoefficient(reynolds, drag_coeff);
noalias(drag_coefficient) = 0.5 * 1.0 * area * drag_coeff * norm_u* vrelative * (1.0 / nodal_mass); //drag_coeff = 0.5 * mFluidDensity * area * drag_coeff * mNormOfSlipVel;
KRATOS_CATCH("")
}
void CalculateNewtonianDragCoefficient(const double reynolds, double& drag_coeff)
{
KRATOS_TRY
if (reynolds < 1){
drag_coeff = 24.0; // Reynolds;
}
else {
if (reynolds > 1000){
drag_coeff = 0.44;
}
else{
drag_coeff = 24.0 / reynolds * (1.0 + 0.15 * pow(reynolds, 0.687));
}
}
KRATOS_CATCH("")
}
void ColorOilClusters(ModelPart::NodesContainerType::iterator iNode, const int color)
{
if(iNode->GetSolutionStepValue(DIAMETER) < 0 ) // if(iNode->GetSolutionStepValue(OIL_CLUSTER) < 0 && ( water_fraction<0.99999999999999 || theta>1.57079632679) )
iNode->GetSolutionStepValue(DIAMETER)=color;
ModelPart::NodesContainerType front_nodes;
GlobalPointersVector<Element >& r_neighbour_elements = iNode->GetValue(NEIGHBOUR_ELEMENTS);
for(GlobalPointersVector<Element >::iterator i_neighbour_element = r_neighbour_elements.begin() ; i_neighbour_element != r_neighbour_elements.end() ; i_neighbour_element++)
{
if(i_neighbour_element->GetValue(DIAMETER) < 0 )
{
i_neighbour_element->SetValue(DIAMETER, color);
Element::GeometryType& p_geometry = i_neighbour_element->GetGeometry();
for(unsigned int i = 0; i < p_geometry.size(); i++)
{
if(p_geometry[i].GetSolutionStepValue(DIAMETER) < 0 )
{
p_geometry[i].GetSolutionStepValue(DIAMETER) = color;
front_nodes.push_back(p_geometry(i));
}
}
}
}
while(!front_nodes.empty())
{
ModelPart::NodesContainerType new_front_nodes;
for(ModelPart::NodesContainerType::iterator i_node = front_nodes.begin() ; i_node != front_nodes.end() ; i_node++)
{
GlobalPointersVector<Element >& r_neighbour_elements = i_node->GetValue(NEIGHBOUR_ELEMENTS);
for(GlobalPointersVector<Element >::iterator i_neighbour_element = r_neighbour_elements.begin() ; i_neighbour_element != r_neighbour_elements.end() ; i_neighbour_element++)
{
if(i_neighbour_element->GetValue(DIAMETER) < 0 )
{
i_neighbour_element->SetValue(DIAMETER, color);
Element::GeometryType& p_geometry = i_neighbour_element->GetGeometry();
for(unsigned int i = 0; i < p_geometry.size(); i++)
{
if(p_geometry[i].GetSolutionStepValue(DIAMETER) < 0 )
{
p_geometry[i].GetSolutionStepValue(DIAMETER) = color;
new_front_nodes.push_back(p_geometry(i));
}
}
}
}
}
front_nodes.clear();// (o resize ( 0 ), si clear no existe)
for( ModelPart::NodesContainerType::iterator i_node = new_front_nodes.begin() ; i_node != new_front_nodes.end() ; i_node++)
front_nodes.push_back(*(i_node.base()));
}
}
void movethermocouples(ModelPart& rEulerianModelPart, ModelPart& rLagrangianModelPart, BinBasedFastPointLocator<TDim>& node_locator)
{
KRATOS_TRY
array_1d<double, 3 > veulerian;
double temperature;
Vector N;
//double G;
const int max_results = 1000;
typename BinBasedFastPointLocator<TDim>::ResultContainerType results(max_results);
double dt =0.01;
const int nparticles = rLagrangianModelPart.Nodes().size();
#pragma omp parallel for firstprivate(results,N,veulerian,temperature)
for (int i = 0; i < nparticles; i++)
{
ModelPart::NodesContainerType::iterator iparticle = rLagrangianModelPart.NodesBegin() + i;
int subdivisions=5.0;
const double small_dt = dt / subdivisions;
for (unsigned int substep = 0; substep < subdivisions; substep++)
{
Node < 3 > ::Pointer pparticle = *(iparticle.base());
typename BinBasedFastPointLocator<TDim>::ResultIteratorType result_begin = results.begin();
Element::Pointer pelement;
bool is_found = node_locator.FindPointOnMesh(pparticle->Coordinates(), N, pelement, result_begin, max_results);
if (is_found == true)
{
Geometry< Node < 3 > >& geom = pelement->GetGeometry();
//move according to the streamline
noalias(veulerian) = N[0] * geom[0].FastGetSolutionStepValue(VELOCITY, 1);
temperature = N[0] * geom[0].FastGetSolutionStepValue(YCH4);
for (unsigned int k = 1; k < geom.size(); k++)
{
noalias(veulerian) += N[k] * geom[k].FastGetSolutionStepValue(VELOCITY, 1);
temperature += N[k] * geom[k].FastGetSolutionStepValue(YCH4);
//KRATOS_WATCH(geom[k].FastGetSolutionStepValue(YCH4));
}
double & temp = (iparticle)->FastGetSolutionStepValue(YCH4);
temp =temperature;
veulerian(0) *=0.0;
veulerian(2) *=0.0;
array_1d<double, 3 > & disp = (iparticle)->FastGetSolutionStepValue(DISPLACEMENT);
noalias(disp) += small_dt*veulerian;
noalias(iparticle->Coordinates()) = iparticle->GetInitialPosition();
noalias(iparticle->Coordinates()) += iparticle->FastGetSolutionStepValue(DISPLACEMENT);
}
}
}
KRATOS_CATCH("")
}
void TransferToEulerianMesh_2(ModelPart& rEulerianModelPart, ModelPart & rLagrangianModelPart)
{
KRATOS_TRY
//defintions for spatial search
typedef Node < 3 > PointType;
typedef Node < 3 > ::Pointer PointTypePointer;
typedef std::vector<PointType::Pointer> PointVector;
typedef std::vector<PointType::Pointer>::iterator PointIterator;
typedef std::vector<double> DistanceVector;
typedef std::vector<double>::iterator DistanceIterator;
//creating an auxiliary list for the new nodes
PointVector list_of_nodes;
//*************
// Bucket types
typedef Bucket< TDim, PointType, PointVector, PointTypePointer, PointIterator, DistanceIterator > BucketType;
typedef Tree< KDTreePartition<BucketType> > tree; //Kdtree;
//starting calculating time of construction of the kdtree
boost::timer kdtree_construction;
for (ModelPart::NodesContainerType::iterator node_it = rLagrangianModelPart.NodesBegin();
node_it != rLagrangianModelPart.NodesEnd(); ++node_it)
{
PointTypePointer pnode = *(node_it.base());
//putting the nodes of the destination_model part in an auxiliary list
list_of_nodes.push_back(pnode);
}
std::cout << "kdt constructin time " << kdtree_construction.elapsed() << std::endl;
//create a spatial database with the list of new nodes
unsigned int bucket_size = 20;
tree nodes_tree(list_of_nodes.begin(), list_of_nodes.end(), bucket_size);
//work arrays
Node < 3 > work_point(0, 0.0, 0.0, 0.0);
unsigned int MaximumNumberOfResults = 10000;
PointVector Results(MaximumNumberOfResults);
DistanceVector SquaredResultsDistances(MaximumNumberOfResults);
if (rEulerianModelPart.NodesBegin()->SolutionStepsDataHas(NODAL_H) == false)
KRATOS_ERROR<<"Add ----NODAL_H---- variable!!!!!! ERROR";
double sigma = 0.0;
if (TDim == 2)
sigma = 10.0 / (7.0 * 3.1415926);
else
sigma = 1.0 / 3.1415926;
for (ModelPart::NodesContainerType::iterator node_it = rEulerianModelPart.NodesBegin(); node_it != rEulerianModelPart.NodesEnd(); node_it++)
{
if((node_it)->Y()< -0.15102 )
{
work_point.X() = node_it->X();
work_point.Y() = node_it->Y();
work_point.Z() = node_it->Z();
double radius = 2.0 * node_it->FastGetSolutionStepValue(NODAL_H);
//find all of the new nodes within the radius
int number_of_points_in_radius;
//look between the new nodes which of them is inside the radius of the circumscribed cyrcle
number_of_points_in_radius = nodes_tree.SearchInRadius(work_point, radius, Results.begin(), SquaredResultsDistances.begin(), MaximumNumberOfResults);
if (number_of_points_in_radius > 0)
{
//double& temperature = (node_it)->FastGetSolutionStepValue(TEMPERATURE);
double temperature_aux = 0.0;
double tot_weight = 0.0;
double C = 1.19e15;
double E_over_R = 24067.0;
for (int k = 0; k < number_of_points_in_radius; k++)
{
double distance = sqrt(*(SquaredResultsDistances.begin() + k));
double weight = SPHCubicKernel(sigma, distance, radius);
PointIterator it_found = Results.begin() + k;
if( (*it_found)->FastGetSolutionStepValue(DIAMETER) >0 && (*it_found)->FastGetSolutionStepValue(YN2) ==0.0) //MATERIAL_VARIABLE
{
double tempp=0.0;
tempp=(*it_found)->FastGetSolutionStepValue(YCH4);
//if(tempp<298.0) tempp=298.0;
//else tempp=(*it_found)->FastGetSolutionStepValue(YCH4);
temperature_aux += weight * 27400.0 * 1.0 * C * exp(-E_over_R / tempp ) * 905.0 ;//temperature
tot_weight += weight;
}
}
if(tot_weight>0.0)
{
//(node_it)->FastGetSolutionStepValue(FUEL)=1500.0;
//double nodal_mass = node_it->FastGetSolutionStepValue(NODAL_MASS);
//KRATOS_WATCH(node_it->FastGetSolutionStepValue(NODAL_MASS))
//double& heat = node_it->FastGetSolutionStepValue(HEAT_FLUX);
temperature_aux /= (tot_weight );
//temperature= 1500.0;//temperature_aux;
if(temperature_aux>1e9) (node_it)->FastGetSolutionStepValue(HEAT_FLUX) += 1e9;
else (node_it)->FastGetSolutionStepValue(HEAT_FLUX) += temperature_aux;
}
}
}
}
KRATOS_CATCH("")
}
void TransferToEulerianMeshShapeBased(ModelPart& rEulerianModelPart, ModelPart & rLagrangianModelPart, BinBasedFastPointLocator<TDim>& node_locator)
{
KRATOS_TRY
for (ModelPart::NodesContainerType::iterator node_it = rEulerianModelPart.NodesBegin(); node_it != rEulerianModelPart.NodesEnd(); node_it++)
{
(node_it)->GetValue(POISSON_RATIO) = 0.0;
(node_it)->GetValue(YOUNG_MODULUS) = 0.0;
(node_it)->GetValue(NODAL_MASS) = 0.0;
(node_it)->GetValue(HEAT_FLUX) = 0.0;
}
for (ModelPart::ElementsContainerType::iterator el_it = rEulerianModelPart.ElementsBegin();el_it != rEulerianModelPart.ElementsEnd(); el_it++)
{
el_it->SetValue(YOUNG_MODULUS,0.0);
}
Vector N;
const int max_results = 1000;
typename BinBasedFastPointLocator<TDim>::ResultContainerType results(max_results);
const int nparticles = rLagrangianModelPart.Nodes().size();
double C = 1.19e15;
double E_over_R = 24067.0;
double A=0.0;
#pragma omp parallel for firstprivate(results,N)
for (int i = 0; i < nparticles; i++)
{
ModelPart::NodesContainerType::iterator iparticle = rLagrangianModelPart.NodesBegin() + i;
//KRATOS_ERROR(std::logic_error, "Add ----FORCE---- variable!!!!!! ERROR", "");
Node < 3 > ::Pointer pparticle = *(iparticle.base());
typename BinBasedFastPointLocator<TDim>::ResultIteratorType result_begin = results.begin();
Element::Pointer pelement;
bool is_found = node_locator.FindPointOnMesh(pparticle->Coordinates(), N, pelement, result_begin, max_results);
if (is_found == true)
{
Geometry<Node<3> >& geom = pelement->GetGeometry();
const array_1d<double, 3 > & vel_particle = (iparticle)->FastGetSolutionStepValue(VELOCITY);
double density_particle = (iparticle)->FastGetSolutionStepValue(DENSITY);
double Tp=(iparticle)->FastGetSolutionStepValue(YCH4); //HEAT_FLUX
if(Tp>1000.0) Tp=1000.0;
double temperature = 0.3e+8;//1000000.0;//(iparticle)->FastGetSolutionStepValue(TEMPERATURE);
temperature = 2e+7;
if( (iparticle)->FastGetSolutionStepValue(DIAMETER)>0)// ((iparticle)->GetValue(NEIGHBOUR_ELEMENTS)).size() == 0)
{
(iparticle)->FastGetSolutionStepValue(YN2)=1.0;
// KRATOS_ERROR(std::logic_error, "Add ----FORCE---- variable!!!!!! ERROR", "");
KRATOS_WATCH("aloneeeeeeeeeeeeeeeeeeeee");
KRATOS_WATCH((iparticle)->FastGetSolutionStepValue(DIAMETER));
for (unsigned int k = 0; k < geom.size(); k++)
{
//KRATOS_ERROR(std::logic_error, "Add ----FORCE---- variable!!!!!! ERROR", "");
geom[k].SetLock();
geom[k].GetValue(YOUNG_MODULUS) += N[k] * 27400.0 * 1.0 * C * exp(-E_over_R/(Tp)) *905.0 * (iparticle)->FastGetSolutionStepValue(K0);//0.0001;
KRATOS_WATCH("K0");
KRATOS_WATCH((iparticle)->FastGetSolutionStepValue(K0));
geom[k].GetValue(POISSON_RATIO) += N[k];
geom[k].UnSetLock();
}
}
}
}
for (ModelPart::ElementsContainerType::iterator el_it = rEulerianModelPart.ElementsBegin();el_it != rEulerianModelPart.ElementsEnd(); el_it++)
{
Geometry<Node < 3 > >& geom = el_it->GetGeometry();
double x0 = geom[0].X();
double y0 = geom[0].Y();
double z0 = geom[0].Z();
double x1 = geom[1].X();
double y1 = geom[1].Y();
double z1 = geom[1].Z();
double x2 = geom[2].X();
double y2 = geom[2].Y();
double z2 = geom[2].Z();
double x3 = geom[3].X();
double y3 = geom[3].Y();
double z3 = geom[3].Z();
double area=0.0;
//if(TDim==2) area=CalculateVol(x0, y0, x1, y1, x2, y2);
//else
area=CalculateVol(x0, y0, z0, x1, y1, z1, x2, y2, z2, x3, y3, z3);
geom[0].FastGetSolutionStepValue(NODAL_MASS) += area * 0.25;
geom[1].FastGetSolutionStepValue(NODAL_MASS) += area * 0.25;
geom[2].FastGetSolutionStepValue(NODAL_MASS) += area * 0.25;
geom[3].FastGetSolutionStepValue(NODAL_MASS) += area * 0.25;
}
for (ModelPart::NodesContainerType::iterator node_it = rEulerianModelPart.NodesBegin(); node_it != rEulerianModelPart.NodesEnd(); node_it++)
{
const double NN = (node_it)->GetValue(POISSON_RATIO);
const double tt = (node_it)->GetValue(YOUNG_MODULUS);
if (NN != 0.0)
{
//KRATOS_ERROR(std::logic_error, "element with zero vol found", "");
//KRATOS_WATCH(tt);
//KRATOS_WATCH(NN);
double nodal_mass = node_it->FastGetSolutionStepValue(NODAL_MASS);
double& heat = node_it->FastGetSolutionStepValue(HEAT_FLUX);
double heat_value=tt/NN * (1.0/nodal_mass);
if (heat_value>1e9 /*0.5e+7*/) heat_value = 1e9 /*0.5e+7*/; //0.5e+7;
heat= heat_value;
KRATOS_WATCH(heat);
}
//}
}
// Timer::Stop("Interpolacion");
//KRATOS_WATCH(time)
KRATOS_CATCH("")
}
private:
inline double SPHCubicKernel(const double sigma, const double r, const double hmax)
{
double h_half = 0.5 * hmax;
const double s = r / h_half;
const double coeff = sigma / pow(h_half, static_cast<int>(TDim));
if (s <= 1.0)
return coeff * (1.0 - 1.5 * s * s + 0.75 * s * s * s);
else if (s <= 2.0)
return 0.25 * coeff * pow(2.0 - s, 3);
else
return 0.0;
}
inline void CalculateCenterAndSearchRadius(Geometry<Node < 3 > >&geom, double& xc, double& yc, double& zc, double& R, array_1d<double, 3 > & N )
{
double x0 = geom[0].X();
double y0 = geom[0].Y();
double x1 = geom[1].X();
double y1 = geom[1].Y();
double x2 = geom[2].X();
double y2 = geom[2].Y();
xc = 0.3333333333333333333 * (x0 + x1 + x2);
yc = 0.3333333333333333333 * (y0 + y1 + y2);
zc = 0.0;
double R1 = (xc - x0)*(xc - x0) + (yc - y0)*(yc - y0);
double R2 = (xc - x1)*(xc - x1) + (yc - y1)*(yc - y1);
double R3 = (xc - x2)*(xc - x2) + (yc - y2)*(yc - y2);
R = R1;
if (R2 > R) R = R2;
if (R3 > R) R = R3;
R = 1.01 * sqrt(R);
}
inline void CalculateCenterAndSearchRadius(Geometry<Node < 3 > >&geom, double& xc, double& yc, double& zc, double& R, array_1d<double, 4 > & N )
{
double x0 = geom[0].X();
double y0 = geom[0].Y();
double z0 = geom[0].Z();
double x1 = geom[1].X();
double y1 = geom[1].Y();
double z1 = geom[1].Z();
double x2 = geom[2].X();
double y2 = geom[2].Y();
double z2 = geom[2].Z();
double x3 = geom[3].X();
double y3 = geom[3].Y();
double z3 = geom[3].Z();
xc = 0.25 * (x0 + x1 + x2 + x3);
yc = 0.25 * (y0 + y1 + y2 + y3);
zc = 0.25 * (z0 + z1 + z2 + z3);
double R1 = (xc - x0)*(xc - x0) + (yc - y0)*(yc - y0) + (zc - z0)*(zc - z0);
double R2 = (xc - x1)*(xc - x1) + (yc - y1)*(yc - y1) + (zc - z1)*(zc - z1);
double R3 = (xc - x2)*(xc - x2) + (yc - y2)*(yc - y2) + (zc - z2)*(zc - z2);
double R4 = (xc - x3)*(xc - x3) + (yc - y3)*(yc - y3) + (zc - z3)*(zc - z3);
R = R1;
if (R2 > R) R = R2;
if (R3 > R) R = R3;
if (R4 > R) R = R4;
R = sqrt(R);
}
inline bool CalculatePosition(Geometry<Node < 3 > >&geom,const double xc, const double yc, const double zc, array_1d<double, 4 > & N )
{
double x0 = geom[0].X();
double y0 = geom[0].Y();
double z0 = geom[0].Z();
double x1 = geom[1].X();
double y1 = geom[1].Y();
double z1 = geom[1].Z();
double x2 = geom[2].X();
double y2 = geom[2].Y();
double z2 = geom[2].Z();
double x3 = geom[3].X();
double y3 = geom[3].Y();
double z3 = geom[3].Z();
double vol = CalculateVol(x0, y0, z0, x1, y1, z1, x2, y2, z2, x3, y3, z3);
double inv_vol = 0.0;
if (vol < 0.0000000000001)
{
KRATOS_ERROR<<"element with zero vol found";
}
else
{
inv_vol = 1.0 / vol;
}
N[0] = CalculateVol(x1, y1, z1, x3, y3, z3, x2, y2, z2, xc, yc, zc) * inv_vol;
N[1] = CalculateVol(x0, y0, z0, x1, y1, z1, x2, y2, z2, xc, yc, zc) * inv_vol;
N[2] = CalculateVol(x3, y3, z3, x1, y1, z1, x0, y0, z0, xc, yc, zc) * inv_vol;
N[3] = CalculateVol(x3, y3, z3, x0, y0, z0, x2, y2, z2, xc, yc, zc) * inv_vol;
if (N[0] >= 0.0 && N[1] >= 0.0 && N[2] >= 0.0 && N[3] >= 0.0 &&
N[0] <= 1.0 && N[1] <= 1.0 && N[2] <= 1.0 && N[3] <= 1.0)
//if the xc yc zc is inside the tetrahedron return true
return true;
return false;
}
inline double CalculateVol(const double x0, const double y0,
const double x1, const double y1,
const double x2, const double y2
)
{
return 0.5 * ((x1 - x0)*(y2 - y0)- (y1 - y0)*(x2 - x0));
}
inline double CalculateVol(const double x0, const double y0, const double z0, const double x1, const double y1, const double z1, const double x2, const double y2, const double z2,const double x3, const double y3, const double z3 )
{
double x10 = x1 - x0;
double y10 = y1 - y0;
double z10 = z1 - z0;
double x20 = x2 - x0;
double y20 = y2 - y0;
double z20 = z2 - z0;
double x30 = x3 - x0;
double y30 = y3 - y0;
double z30 = z3 - z0;
double detJ = x10 * y20 * z30 - x10 * y30 * z20 + y10 * z20 * x30 - y10 * x20 * z30 + z10 * x20 * y30 - z10 * y20 * x30;
return detJ * 0.1666666666666666666667;
}
void ComputeGaussPointPositions(Geometry< Node < 3 > >& geom, BoundedMatrix<double, 4, 3 > & pos, BoundedMatrix<double, 4, 3 > & N)
{
double one_third = 1.0 / 3.0;
double one_sixt = 1.0 / 6.0;
double two_third = 2.0 * one_third;
N(0, 0) = one_sixt;
N(0, 1) = one_sixt;
N(0, 2) = two_third;
N(1, 0) = two_third;
N(1, 1) = one_sixt;
N(1, 2) = one_sixt;
N(2, 0) = one_sixt;
N(2, 1) = two_third;
N(2, 2) = one_sixt;
N(3, 0) = one_third;
N(3, 1) = one_third;
N(3, 2) = one_third;
//first
pos(0, 0) = one_sixt * geom[0].X() + one_sixt * geom[1].X() + two_third * geom[2].X();
pos(0, 1) = one_sixt * geom[0].Y() + one_sixt * geom[1].Y() + two_third * geom[2].Y();
pos(0, 2) = one_sixt * geom[0].Z() + one_sixt * geom[1].Z() + two_third * geom[2].Z();
//second
pos(1, 0) = two_third * geom[0].X() + one_sixt * geom[1].X() + one_sixt * geom[2].X();
pos(1, 1) = two_third * geom[0].Y() + one_sixt * geom[1].Y() + one_sixt * geom[2].Y();
pos(1, 2) = two_third * geom[0].Z() + one_sixt * geom[1].Z() + one_sixt * geom[2].Z();
//third
pos(2, 0) = one_sixt * geom[0].X() + two_third * geom[1].X() + one_sixt * geom[2].X();
pos(2, 1) = one_sixt * geom[0].Y() + two_third * geom[1].Y() + one_sixt * geom[2].Y();
pos(2, 2) = one_sixt * geom[0].Z() + two_third * geom[1].Z() + one_sixt * geom[2].Z();
//fourth
pos(3, 0) = one_third * geom[0].X() + one_third * geom[1].X() + one_third * geom[2].X();
pos(3, 1) = one_third * geom[0].Y() + one_third * geom[1].Y() + one_third * geom[2].Y();
pos(3, 2) = one_third * geom[0].Z() + one_third * geom[1].Z() + one_third * geom[2].Z();
}
void ComputeGaussPointPositions(Geometry< Node < 3 > >& geom, BoundedMatrix<double, 16, 3 > & pos, BoundedMatrix<double, 16, 3 > & N)
{
//lower diagonal terms
double ypos = 1.0 / 12.0;
int pos_counter = 0;
for (unsigned int i = 0; i < 4; i++)
{
double xpos = 1.0 / 12.0;
for (unsigned int j = 0; j < 4 - i; j++)
{
double N1 = xpos;
double N2 = ypos;
double N3 = 1.0 - xpos - ypos;
pos(pos_counter, 0) = N1 * geom[0].X() + N2 * geom[1].X() + N3 * geom[2].X();
pos(pos_counter, 1) = N1 * geom[0].Y() + N2 * geom[1].Y() + N3 * geom[2].Y();
pos(pos_counter, 2) = N1 * geom[0].Z() + N2 * geom[1].Z() + N3 * geom[2].Z();
N(pos_counter, 0) = N1;
N(pos_counter, 1) = N2;
N(pos_counter, 2) = N3;
xpos += 1.0 / 4.0;
pos_counter += 1;
}
ypos += 1.0 / 4.0;
}
//lower diagonal terms
ypos = 2.0 / 12.0;
// pos_counter = 8;
for (unsigned int i = 0; i < 3; i++)
{
double xpos = 2.0 / 12.0;
for (unsigned int j = 0; j < 4 - i; j++)
{
double N1 = xpos;
double N2 = ypos;
double N3 = 1.0 - xpos - ypos;
pos(pos_counter, 0) = N1 * geom[0].X() + N2 * geom[1].X() + N3 * geom[2].X();
pos(pos_counter, 1) = N1 * geom[0].Y() + N2 * geom[1].Y() + N3 * geom[2].Y();
pos(pos_counter, 2) = N1 * geom[0].Z() + N2 * geom[1].Z() + N3 * geom[2].Z();
N(pos_counter, 0) = N1;
N(pos_counter, 1) = N2;
N(pos_counter, 2) = N3;
xpos += 1.0 / 4.0;
pos_counter += 1;
}
ypos += 1.0 / 4.0;
}
}
void ConsistentMassMatrix(const double A, BoundedMatrix<double, 3, 3 > & M)
{
double c1 = A / 12.0;
double c2 = 2.0 * c1;
M(0, 0) = c2;
M(0, 1) = c1;
M(0, 2) = c1;
M(1, 0) = c1;
M(1, 1) = c2;
M(1, 2) = c1;
M(2, 0) = c1;
M(2, 1) = c1;
M(2, 2) = c2;
}
void CalculateInterfaceNormal(BoundedMatrix<double, 3, 2 >& rPoints, array_1d<double,3>& rDistances, array_1d<double,2>& normal, double & interface_area, array_1d<double,3>& Ninterface, BoundedMatrix<double, 2, 2 >& rInterfacePoints)
{
double sign_correction=1.0;
BoundedMatrix<double, 2, 2 > InterfacePoints;
array_1d<bool,3> cut_edges;
array_1d<double,2> interface_segment=ZeroVector(2);
if ((rDistances(0)*rDistances(1))<0.0) cut_edges[0]=true;//edge 12 is cut
else cut_edges[0]=false;
if ((rDistances(1)*rDistances(2))<0.0) cut_edges[1]=true;//edge 23 is cut.
else cut_edges[1]=false;
if ((rDistances(2)*rDistances(0))<0.0) cut_edges[2]=true;//edge 13 is cut.
else cut_edges[2]=false;
if (cut_edges[0])
{
if (rDistances(0)>0.0) sign_correction=1.0;
else sign_correction=-1.0;
const double relative_position = abs(rDistances(1)/(rDistances(1)-rDistances(0) ) );
InterfacePoints(0,0) = relative_position*rPoints(0,0) + (1.0-relative_position)*rPoints(1,0);
InterfacePoints(0,1) = relative_position*rPoints(0,1) + (1.0-relative_position)*rPoints(1,1);
if (cut_edges[1])
{
const double relative_position2 = abs(rDistances(2)/(rDistances(1)-rDistances(2) ) );
InterfacePoints(1,0) = relative_position2*rPoints(1,0) + (1.0-relative_position2)*rPoints(2,0);
InterfacePoints(1,1) = relative_position2*rPoints(1,1) + (1.0-relative_position2)*rPoints(2,1);
}
else
{
const double relative_position2 = abs(rDistances(0)/(rDistances(2)-rDistances(0) ) );
InterfacePoints(1,0) = relative_position2*rPoints(2,0) + (1.0-relative_position2)*rPoints(0,0);
InterfacePoints(1,1) = relative_position2*rPoints(2,1) + (1.0-relative_position2)*rPoints(0,1);
}
}
else
{
if (rDistances(1)>0.0) sign_correction=1.0;
else sign_correction=-1.0;
const double relative_position = abs(rDistances(2)/(rDistances(2)-rDistances(1) ) );
InterfacePoints(0,0) = relative_position*rPoints(1,0) + (1.0-relative_position)*rPoints(2,0);
InterfacePoints(0,1) = relative_position*rPoints(1,1) + (1.0-relative_position)*rPoints(2,1);
const double relative_position2 = abs(rDistances(0)/(rDistances(2)-rDistances(0) ) );
InterfacePoints(1,0) = relative_position2*rPoints(2,0) + (1.0-relative_position2)*rPoints(0,0);
InterfacePoints(1,1) = relative_position2*rPoints(2,1) + (1.0-relative_position2)*rPoints(0,1);
}
interface_segment[0] = (InterfacePoints(1,0)-InterfacePoints(0,0));
interface_segment[1] = (InterfacePoints(1,1)-InterfacePoints(0,1));
const double norm = sqrt( pow((interface_segment[0]),2) + pow((interface_segment[1]),2));
normal(0)= -interface_segment[1]*sign_correction/norm;
normal(1)= interface_segment[0]*sign_correction/norm;
//KRATOS_WATCH(interface_segment)
//KRATOS_WATCH(InterfacePoints)
interface_area=norm;
rInterfacePoints(0,0)=InterfacePoints(0,0);
rInterfacePoints(0,1)=InterfacePoints(0,1);
rInterfacePoints(1,0)=InterfacePoints(1,0);
rInterfacePoints(1,1)=InterfacePoints(1,1);
const double x_interface = 0.5*(InterfacePoints(0,0)+InterfacePoints(1,0));
const double y_interface = 0.5*(InterfacePoints(0,1)+InterfacePoints(1,1));
// CalculatePosition(rPoints, x_interface, y_interface, 0.0, Ninterface );
///meto aqui el CalculatePosition(rPoints, x_interface, y_interface, 0.0, Ninterface );
double x0 = rPoints(0,0);
double y0 = rPoints(0,1);
double x1 = rPoints(1,0);
double y1 = rPoints(1,1);
double x2 = rPoints(2,0);
double y2 = rPoints(2,1);
double area = CalculateVol(x0, y0, x1, y1, x2, y2);
double inv_area = 0.0;
if (area == 0.0)
{
KRATOS_ERROR<<"element with zero area found";
}
else
{
inv_area = 1.0 / area;
}
Ninterface[0]= CalculateVol(x1, y1, x2, y2, x_interface, y_interface) * inv_area;
Ninterface[1] = CalculateVol(x2, y2, x0, y0, x_interface, y_interface) * inv_area;
Ninterface[2] = CalculateVol(x0, y0, x1, y1, x_interface, y_interface) * inv_area;
}
bool CalculatePosition(Geometry<Node < 3 > >&geom,const double xc, const double yc, const double zc,array_1d<double, 3 > & N )
{
double x0 = geom[0].X();
double y0 = geom[0].Y();
double x1 = geom[1].X();
double y1 = geom[1].Y();
double x2 = geom[2].X();
double y2 = geom[2].Y();
double area = CalculateVol(x0, y0, x1, y1, x2, y2);
double inv_area = 0.0;
if (area == 0.0)
{
KRATOS_ERROR<<"element with zero area found";
}
else
{
inv_area = 1.0 / area;
}
N[0] = CalculateVol(x1, y1, x2, y2, xc, yc) * inv_area;
N[1] = CalculateVol(x2, y2, x0, y0, xc, yc) * inv_area;
N[2] = CalculateVol(x0, y0, x1, y1, xc, yc) * inv_area;
if (N[0] >= 0.0 && N[1] >= 0.0 && N[2] >= 0.0 && N[0] <= 1.0 && N[1] <= 1.0 && N[2] <= 1.0) //if the xc yc is inside the triangle return true
return true;
return false;
}
template<class T>
bool InvertMatrix(const T& input, T& inverse)
{
typedef permutation_matrix<std::size_t> pmatrix;
// create a working copy of the input
T A(input);
// create a permutation matrix for the LU-factorization
pmatrix pm(A.size1());
// perform LU-factorization
int res = lu_factorize(A, pm);
if (res != 0)
return false;
// create identity matrix of "inverse"
inverse.assign(identity_matrix<double> (A.size1()));
// backsubstitute to get the inverse
lu_substitute(A, pm, inverse);
return true;
}
};
} // namespace Kratos.
#endif // KRATOS_LAGRANGIAN_PARTICLES_UTILITIES_INCLUDED defined
|
colorspace.c | /*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% CCCC OOO L OOO RRRR SSSSS PPPP AAA CCCC EEEEE %
% C O O L O O R R SS P P A A C E %
% C O O L O O RRRR SSS PPPP AAAAA C EEE %
% C O O L O O R R SS P A A C E %
% CCCC OOO LLLLL OOO R R SSSSS P A A CCCC EEEEE %
% %
% %
% MagickCore Image Colorspace Methods %
% %
% Software Design %
% Cristy %
% July 1992 %
% %
% %
% Copyright 1999-2021 ImageMagick Studio LLC, a non-profit organization %
% dedicated to making software imaging solutions freely available. %
% %
% You may not use this file except in compliance with the License. You may %
% obtain a copy of the License at %
% %
% https://imagemagick.org/script/license.php %
% %
% Unless required by applicable law or agreed to in writing, software %
% distributed under the License is distributed on an "AS IS" BASIS, %
% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. %
% See the License for the specific language governing permissions and %
% limitations under the License. %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
%
*/
/*
Include declarations.
*/
#include "MagickCore/studio.h"
#include "MagickCore/attribute.h"
#include "MagickCore/property.h"
#include "MagickCore/cache.h"
#include "MagickCore/cache-private.h"
#include "MagickCore/cache-view.h"
#include "MagickCore/color.h"
#include "MagickCore/color-private.h"
#include "MagickCore/colorspace.h"
#include "MagickCore/colorspace-private.h"
#include "MagickCore/exception.h"
#include "MagickCore/exception-private.h"
#include "MagickCore/enhance.h"
#include "MagickCore/image.h"
#include "MagickCore/image-private.h"
#include "MagickCore/gem.h"
#include "MagickCore/gem-private.h"
#include "MagickCore/memory_.h"
#include "MagickCore/monitor.h"
#include "MagickCore/monitor-private.h"
#include "MagickCore/pixel-accessor.h"
#include "MagickCore/pixel-private.h"
#include "MagickCore/quantize.h"
#include "MagickCore/quantum.h"
#include "MagickCore/quantum-private.h"
#include "MagickCore/resource_.h"
#include "MagickCore/string_.h"
#include "MagickCore/string-private.h"
#include "MagickCore/utility.h"
/*
Typedef declarations.
*/
typedef struct _TransformPacket
{
MagickRealType
x,
y,
z;
} TransformPacket;
/*
Forward declarations.
*/
static MagickBooleanType
TransformsRGBImage(Image *,ExceptionInfo *);
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% G e t I m a g e C o l o r s p a c e T y p e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% GetImageColorspaceType() returns the potential type of image:
% sRGBColorspaceType, RGBColorspaceType, GRAYColorspaceType, etc.
%
% To ensure the image type matches its potential, use SetImageColorspaceType():
%
% (void) SetImageColorspaceType(image,GetImageColorspaceType(image),
% exception);
%
% The format of the GetImageColorspaceType method is:
%
% ColorspaceType GetImageColorspaceType(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 ColorspaceType GetImageColorspaceType(const Image *image,
ExceptionInfo *exception)
{
ColorspaceType
colorspace;
ImageType
type;
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
colorspace=image->colorspace;
type=IdentifyImageType(image,exception);
if ((type == BilevelType) || (type == GrayscaleType) ||
(type == GrayscaleAlphaType))
colorspace=GRAYColorspace;
return(colorspace);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
+ s R G B T r a n s f o r m I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% sRGBTransformImage() converts the reference image from sRGB to an alternate
% colorspace. The transformation matrices are not the standard ones: the
% weights are rescaled to normalized the range of the transformed values to
% be [0..QuantumRange].
%
% The format of the sRGBTransformImage method is:
%
% MagickBooleanType sRGBTransformImage(Image *image,
% const ColorspaceType colorspace,EsceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o colorspace: the colorspace to transform the image to.
%
% o exception: return any errors or warnings in this structure.
%
*/
static inline void ConvertAdobe98ToRGB(const double r,const double g,
const double b,double *red,double *green,double *blue)
{
double
X,
Y,
Z;
ConvertAdobe98ToXYZ(r,g,b,&X,&Y,&Z);
ConvertXYZToRGB(X,Y,Z,red,green,blue);
}
static inline void ConvertDisplayP3ToRGB(const double r,const double g,
const double b,double *red,double *green,double *blue)
{
double
X,
Y,
Z;
ConvertDisplayP3ToXYZ(r,g,b,&X,&Y,&Z);
ConvertXYZToRGB(X,Y,Z,red,green,blue);
}
static inline void ConvertProPhotoToRGB(const double r,const double g,
const double b,double *red,double *green,double *blue)
{
double
X,
Y,
Z;
ConvertProPhotoToXYZ(r,g,b,&X,&Y,&Z);
ConvertXYZToRGB(X,Y,Z,red,green,blue);
}
static inline void ConvertRGBToCMY(const double red,const double green,
const double blue,double *cyan,double *magenta,double *yellow)
{
*cyan=QuantumScale*(QuantumRange-red);
*magenta=QuantumScale*(QuantumRange-green);
*yellow=QuantumScale*(QuantumRange-blue);
}
static void ConvertRGBToAdobe98(const double red,const double green,
const double blue,double *r,double *g,double *b)
{
double
X,
Y,
Z;
ConvertRGBToXYZ(red,green,blue,&X,&Y,&Z);
ConvertXYZToAdobe98(X,Y,Z,r,g,b);
}
static void ConvertRGBToDisplayP3(const double red,const double green,
const double blue,double *r,double *g,double *b)
{
double
X,
Y,
Z;
ConvertRGBToXYZ(red,green,blue,&X,&Y,&Z);
ConvertXYZToDisplayP3(X,Y,Z,r,g,b);
}
static void ConvertRGBToProPhoto(const double red,const double green,
const double blue,double *r,double *g,double *b)
{
double
X,
Y,
Z;
ConvertRGBToXYZ(red,green,blue,&X,&Y,&Z);
ConvertXYZToProPhoto(X,Y,Z,r,g,b);
}
static inline void ConvertXYZToLMS(const double x,const double y,
const double z,double *L,double *M,double *S)
{
*L=0.7328*x+0.4296*y-0.1624*z;
*M=(-0.7036*x+1.6975*y+0.0061*z);
*S=0.0030*x+0.0136*y+0.9834*z;
}
static void ConvertRGBToLMS(const double red,const double green,
const double blue,double *L,double *M,double *S)
{
double
X,
Y,
Z;
ConvertRGBToXYZ(red,green,blue,&X,&Y,&Z);
ConvertXYZToLMS(X,Y,Z,L,M,S);
}
static void ConvertRGBToLuv(const double red,const double green,
const double blue,double *L,double *u,double *v)
{
double
X,
Y,
Z;
ConvertRGBToXYZ(red,green,blue,&X,&Y,&Z);
ConvertXYZToLuv(X,Y,Z,L,u,v);
}
static void ConvertRGBToxyY(const double red,const double green,
const double blue,double *low_x,double *low_y,double *cap_Y)
{
double
gamma,
X,
Y,
Z;
ConvertRGBToXYZ(red,green,blue,&X,&Y,&Z);
gamma=PerceptibleReciprocal(X+Y+Z);
*low_x=gamma*X;
*low_y=gamma*Y;
*cap_Y=Y;
}
static void inline ConvertXYZToJzazbz(const double X,const double Y,
const double Z,const double white_luminance,double *Jz,double *az,double *bz)
{
#define Jzazbz_b 1.15 /* https://observablehq.com/@jrus/jzazbz */
#define Jzazbz_g 0.66
#define Jzazbz_c1 (3424.0/4096.0)
#define Jzazbz_c2 (2413.0/128.0)
#define Jzazbz_c3 (2392.0/128.0)
#define Jzazbz_n (2610.0/16384.0)
#define Jzazbz_p (1.7*2523.0/32.0)
#define Jzazbz_d (-0.56)
#define Jzazbz_d0 (1.6295499532821566e-11)
double
gamma,
Iz,
L,
Lp,
M,
Mp,
S,
Sp,
Xp,
Yp,
Zp;
Xp=(Jzazbz_b*X-Z*(Jzazbz_b-1));
Yp=(Jzazbz_g*Y-X*(Jzazbz_g-1));
Zp=Z;
L=0.41478972*Xp+0.579999*Yp+0.0146480*Zp;
M=(-0.2015100)*Xp+1.120649*Yp+0.0531008*Zp;
S=(-0.0166008)*Xp+0.264800*Yp+0.6684799*Zp;
gamma=pow(L/white_luminance,Jzazbz_n);
Lp=pow((Jzazbz_c1+Jzazbz_c2*gamma)/(1.0+Jzazbz_c3*gamma),Jzazbz_p);
gamma=pow(M/white_luminance,Jzazbz_n);
Mp=pow((Jzazbz_c1+Jzazbz_c2*gamma)/(1.0+Jzazbz_c3*gamma),Jzazbz_p);
gamma=pow(S/white_luminance,Jzazbz_n);
Sp=pow((Jzazbz_c1+Jzazbz_c2*gamma)/(1.0+Jzazbz_c3*gamma),Jzazbz_p);
Iz=0.5*Lp+0.5*Mp;
*az=3.52400*Lp-4.066708*Mp+0.542708*Sp+0.5;
*bz=0.199076*Lp+1.096799*Mp-1.295875*Sp+0.5;
*Jz=((Jzazbz_d+1.0)*Iz)/(Jzazbz_d*Iz+1.0)-Jzazbz_d0;
}
static void inline ConvertJzazbzToXYZ(const double Jz,const double az,
const double bz,const double white_luminance,double *X,double *Y,double *Z)
{
double
azz,
bzz,
gamma,
Iz,
L,
Lp,
M,
Mp,
S,
Sp,
Xp,
Yp,
Zp;
gamma=Jz+Jzazbz_d0;
Iz=gamma/(Jzazbz_d-Jzazbz_d*gamma+1.0);
azz=az-0.5;
bzz=bz-0.5;
Lp=Iz+0.138605043271539*azz+0.0580473161561189*bzz;
Mp=Iz-0.138605043271539*azz-0.0580473161561189*bzz;
Sp=Iz-0.0960192420263189*azz-0.811891896056039*bzz;
gamma=pow(Lp,1.0/Jzazbz_p);
L=white_luminance*pow((Jzazbz_c1-gamma)/(Jzazbz_c3*gamma-Jzazbz_c2),1.0/
Jzazbz_n);
gamma=pow(Mp,1.0/Jzazbz_p);
M=white_luminance*pow((Jzazbz_c1-gamma)/(Jzazbz_c3*gamma-Jzazbz_c2),1.0/
Jzazbz_n);
gamma=pow(Sp,1.0/Jzazbz_p);
S=white_luminance*pow((Jzazbz_c1-gamma)/(Jzazbz_c3*gamma-Jzazbz_c2),1.0/
Jzazbz_n);
Xp=1.92422643578761*L-1.00479231259537*M+0.037651404030618*S;
Yp=0.350316762094999*L+0.726481193931655*M-0.065384422948085*S;
Zp=(-0.0909828109828476)*L-0.312728290523074*M+1.52276656130526*S;
*X=(Xp+(Jzazbz_b-1.0)*Zp)/Jzazbz_b;
*Y=(Yp+(Jzazbz_g-1.0)**X)/Jzazbz_g;
*Z=Zp;
}
static void ConvertRGBToJzazbz(const double red,const double green,
const double blue,const double white_luminance,double *Jz,double *az,
double *bz)
{
double
X,
Y,
Z;
ConvertRGBToXYZ(red,blue,green,&X,&Y,&Z);
ConvertXYZToJzazbz(X,Y,Z,white_luminance,Jz,az,bz);
}
static void ConvertJzazbzToRGB(const double Jz,const double az,
const double bz,const double white_luminance,double *red,double *green,
double *blue)
{
double
X,
Y,
Z;
ConvertJzazbzToXYZ(Jz,az,bz,white_luminance,&X,&Y,&Z);
ConvertXYZToRGB(X,Y,Z,red,blue,green);
}
static void ConvertRGBToYDbDr(const double red,const double green,
const double blue,double *Y,double *Db,double *Dr)
{
*Y=QuantumScale*(0.298839*red+0.586811*green+0.114350*blue);
*Db=QuantumScale*(-0.450*red-0.883*green+1.333*blue)+0.5;
*Dr=QuantumScale*(-1.333*red+1.116*green+0.217*blue)+0.5;
}
static void ConvertRGBToYIQ(const double red,const double green,
const double blue,double *Y,double *I,double *Q)
{
*Y=QuantumScale*(0.298839*red+0.586811*green+0.114350*blue);
*I=QuantumScale*(0.595716*red-0.274453*green-0.321263*blue)+0.5;
*Q=QuantumScale*(0.211456*red-0.522591*green+0.311135*blue)+0.5;
}
static void ConvertRGBToYPbPr(const double red,const double green,
const double blue,double *Y,double *Pb,double *Pr)
{
*Y=QuantumScale*(0.298839*red+0.586811*green+0.114350*blue);
*Pb=QuantumScale*((-0.1687367)*red-0.331264*green+0.5*blue)+0.5;
*Pr=QuantumScale*(0.5*red-0.418688*green-0.081312*blue)+0.5;
}
static void ConvertRGBToYCbCr(const double red,const double green,
const double blue,double *Y,double *Cb,double *Cr)
{
ConvertRGBToYPbPr(red,green,blue,Y,Cb,Cr);
}
static void ConvertRGBToYUV(const double red,const double green,
const double blue,double *Y,double *U,double *V)
{
*Y=QuantumScale*(0.298839*red+0.586811*green+0.114350*blue);
*U=QuantumScale*((-0.147)*red-0.289*green+0.436*blue)+0.5;
*V=QuantumScale*(0.615*red-0.515*green-0.100*blue)+0.5;
}
static MagickBooleanType sRGBTransformImage(Image *image,
const ColorspaceType colorspace,ExceptionInfo *exception)
{
#define sRGBTransformImageTag "RGBTransform/Image"
CacheView
*image_view;
MagickBooleanType
status;
MagickOffsetType
progress;
PrimaryInfo
primary_info;
ssize_t
i;
ssize_t
y;
TransformPacket
*x_map,
*y_map,
*z_map;
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
assert(colorspace != sRGBColorspace);
assert(colorspace != TransparentColorspace);
assert(colorspace != UndefinedColorspace);
status=MagickTrue;
progress=0;
switch (colorspace)
{
case CMYKColorspace:
{
PixelInfo
zero;
/*
Convert RGB to CMYK colorspace.
*/
if (image->storage_class == PseudoClass)
{
if (SyncImage(image,exception) == MagickFalse)
return(MagickFalse);
if (SetImageStorageClass(image,DirectClass,exception) == MagickFalse)
return(MagickFalse);
}
if (SetImageColorspace(image,colorspace,exception) == MagickFalse)
return(MagickFalse);
GetPixelInfo(image,&zero);
image_view=AcquireAuthenticCacheView(image,exception);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static) shared(status) \
magick_number_threads(image,image,image->rows,1)
#endif
for (y=0; y < (ssize_t) image->rows; y++)
{
MagickBooleanType
sync;
PixelInfo
pixel;
ssize_t
x;
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;
}
pixel=zero;
for (x=0; x < (ssize_t) image->columns; x++)
{
GetPixelInfoPixel(image,q,&pixel);
ConvertRGBToCMYK(&pixel);
SetPixelViaPixelInfo(image,&pixel,q);
q+=GetPixelChannels(image);
}
sync=SyncCacheViewAuthenticPixels(image_view,exception);
if (sync == MagickFalse)
status=MagickFalse;
}
image_view=DestroyCacheView(image_view);
image->type=image->alpha_trait == UndefinedPixelTrait ?
ColorSeparationType : ColorSeparationAlphaType;
if (SetImageColorspace(image,colorspace,exception) == MagickFalse)
return(MagickFalse);
return(status);
}
case LinearGRAYColorspace:
{
/*
Transform image from sRGB to GRAY.
*/
if (image->storage_class == PseudoClass)
{
if (SyncImage(image,exception) == MagickFalse)
return(MagickFalse);
if (SetImageStorageClass(image,DirectClass,exception) == MagickFalse)
return(MagickFalse);
}
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++)
{
MagickBooleanType
sync;
ssize_t
x;
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++)
{
MagickRealType
gray;
gray=0.212656*GetPixelRed(image,q)+0.715158*GetPixelGreen(image,q)+
0.072186*GetPixelBlue(image,q);
SetPixelGray(image,ClampToQuantum(DecodePixelGamma(gray)),q);
q+=GetPixelChannels(image);
}
sync=SyncCacheViewAuthenticPixels(image_view,exception);
if (sync == MagickFalse)
status=MagickFalse;
}
image_view=DestroyCacheView(image_view);
if (SetImageColorspace(image,colorspace,exception) == MagickFalse)
return(MagickFalse);
image->type=GrayscaleType;
return(status);
}
case GRAYColorspace:
{
/*
Transform image from sRGB to GRAY.
*/
if (image->storage_class == PseudoClass)
{
if (SyncImage(image,exception) == MagickFalse)
return(MagickFalse);
if (SetImageStorageClass(image,DirectClass,exception) == MagickFalse)
return(MagickFalse);
}
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++)
{
MagickBooleanType
sync;
ssize_t
x;
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++)
{
MagickRealType
gray;
gray=0.212656*GetPixelRed(image,q)+0.715158*GetPixelGreen(image,q)+
0.072186*GetPixelBlue(image,q);
SetPixelGray(image,ClampToQuantum(gray),q);
q+=GetPixelChannels(image);
}
sync=SyncCacheViewAuthenticPixels(image_view,exception);
if (sync == MagickFalse)
status=MagickFalse;
}
image_view=DestroyCacheView(image_view);
if (SetImageColorspace(image,colorspace,exception) == MagickFalse)
return(MagickFalse);
image->type=GrayscaleType;
return(status);
}
case CMYColorspace:
case Adobe98Colorspace:
case DisplayP3Colorspace:
case HCLColorspace:
case HCLpColorspace:
case HSBColorspace:
case HSIColorspace:
case HSLColorspace:
case HSVColorspace:
case HWBColorspace:
case JzazbzColorspace:
case LabColorspace:
case LCHColorspace:
case LCHabColorspace:
case LCHuvColorspace:
case LMSColorspace:
case LuvColorspace:
case ProPhotoColorspace:
case xyYColorspace:
case XYZColorspace:
case YCbCrColorspace:
case YDbDrColorspace:
case YIQColorspace:
case YPbPrColorspace:
case YUVColorspace:
{
const char
*value;
double
white_luminance;
/*
Transform image from sRGB to target colorspace.
*/
white_luminance=10000.0;
value=GetImageProperty(image,"white-luminance",exception);
if (value != (const char *) NULL)
white_luminance=StringToDouble(value,(char **) NULL);
if (image->storage_class == PseudoClass)
{
if (SyncImage(image,exception) == MagickFalse)
return(MagickFalse);
if (SetImageStorageClass(image,DirectClass,exception) == MagickFalse)
return(MagickFalse);
}
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++)
{
MagickBooleanType
sync;
ssize_t
x;
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++)
{
double
blue,
green,
red,
X,
Y,
Z;
red=(double) GetPixelRed(image,q);
green=(double) GetPixelGreen(image,q);
blue=(double) GetPixelBlue(image,q);
switch (colorspace)
{
case Adobe98Colorspace:
{
ConvertRGBToAdobe98(red,green,blue,&X,&Y,&Z);
break;
}
case CMYColorspace:
{
ConvertRGBToCMY(red,green,blue,&X,&Y,&Z);
break;
}
case DisplayP3Colorspace:
{
ConvertRGBToDisplayP3(red,green,blue,&X,&Y,&Z);
break;
}
case HCLColorspace:
{
ConvertRGBToHCL(red,green,blue,&X,&Y,&Z);
break;
}
case HCLpColorspace:
{
ConvertRGBToHCLp(red,green,blue,&X,&Y,&Z);
break;
}
case HSBColorspace:
{
ConvertRGBToHSB(red,green,blue,&X,&Y,&Z);
break;
}
case HSIColorspace:
{
ConvertRGBToHSI(red,green,blue,&X,&Y,&Z);
break;
}
case HSLColorspace:
{
ConvertRGBToHSL(red,green,blue,&X,&Y,&Z);
break;
}
case HSVColorspace:
{
ConvertRGBToHSV(red,green,blue,&X,&Y,&Z);
break;
}
case HWBColorspace:
{
ConvertRGBToHWB(red,green,blue,&X,&Y,&Z);
break;
}
case JzazbzColorspace:
{
ConvertRGBToJzazbz(red,green,blue,white_luminance,&X,&Y,&Z);
break;
}
case LabColorspace:
{
ConvertRGBToLab(red,green,blue,&X,&Y,&Z);
break;
}
case LCHColorspace:
case LCHabColorspace:
{
ConvertRGBToLCHab(red,green,blue,&X,&Y,&Z);
break;
}
case LCHuvColorspace:
{
ConvertRGBToLCHuv(red,green,blue,&X,&Y,&Z);
break;
}
case LMSColorspace:
{
ConvertRGBToLMS(red,green,blue,&X,&Y,&Z);
break;
}
case LuvColorspace:
{
ConvertRGBToLuv(red,green,blue,&X,&Y,&Z);
break;
}
case ProPhotoColorspace:
{
ConvertRGBToProPhoto(red,green,blue,&X,&Y,&Z);
break;
}
case xyYColorspace:
{
ConvertRGBToxyY(red,green,blue,&X,&Y,&Z);
break;
}
case XYZColorspace:
{
ConvertRGBToXYZ(red,green,blue,&X,&Y,&Z);
break;
}
case YCbCrColorspace:
{
ConvertRGBToYCbCr(red,green,blue,&X,&Y,&Z);
break;
}
case YDbDrColorspace:
{
ConvertRGBToYDbDr(red,green,blue,&X,&Y,&Z);
break;
}
case YIQColorspace:
{
ConvertRGBToYIQ(red,green,blue,&X,&Y,&Z);
break;
}
case YPbPrColorspace:
{
ConvertRGBToYPbPr(red,green,blue,&X,&Y,&Z);
break;
}
case YUVColorspace:
{
ConvertRGBToYUV(red,green,blue,&X,&Y,&Z);
break;
}
default:
{
X=QuantumScale*red;
Y=QuantumScale*green;
Z=QuantumScale*blue;
break;
}
}
SetPixelRed(image,ClampToQuantum(QuantumRange*X),q);
SetPixelGreen(image,ClampToQuantum(QuantumRange*Y),q);
SetPixelBlue(image,ClampToQuantum(QuantumRange*Z),q);
q+=GetPixelChannels(image);
}
sync=SyncCacheViewAuthenticPixels(image_view,exception);
if (sync == MagickFalse)
status=MagickFalse;
}
image_view=DestroyCacheView(image_view);
if (SetImageColorspace(image,colorspace,exception) == MagickFalse)
return(MagickFalse);
return(status);
}
case LogColorspace:
{
#define DisplayGamma (1.0/1.7)
#define FilmGamma 0.6
#define ReferenceBlack 95.0
#define ReferenceWhite 685.0
const char
*value;
double
black,
density,
film_gamma,
gamma,
reference_black,
reference_white;
Quantum
*logmap;
/*
Transform RGB to Log colorspace.
*/
density=DisplayGamma;
gamma=DisplayGamma;
value=GetImageProperty(image,"gamma",exception);
if (value != (const char *) NULL)
gamma=PerceptibleReciprocal(StringToDouble(value,(char **) NULL));
film_gamma=FilmGamma;
value=GetImageProperty(image,"film-gamma",exception);
if (value != (const char *) NULL)
film_gamma=StringToDouble(value,(char **) NULL);
reference_black=ReferenceBlack;
value=GetImageProperty(image,"reference-black",exception);
if (value != (const char *) NULL)
reference_black=StringToDouble(value,(char **) NULL);
reference_white=ReferenceWhite;
value=GetImageProperty(image,"reference-white",exception);
if (value != (const char *) NULL)
reference_white=StringToDouble(value,(char **) NULL);
logmap=(Quantum *) AcquireQuantumMemory((size_t) MaxMap+1UL,
sizeof(*logmap));
if (logmap == (Quantum *) NULL)
ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
image->filename);
black=pow(10.0,(reference_black-reference_white)*(gamma/density)*0.002/
film_gamma);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static)
#endif
for (i=0; i <= (ssize_t) MaxMap; i++)
logmap[i]=ScaleMapToQuantum((double) (MaxMap*(reference_white+
log10(black+(1.0*i/MaxMap)*(1.0-black))/((gamma/density)*0.002/
film_gamma))/1024.0));
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++)
{
MagickBooleanType
sync;
ssize_t
x;
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=(ssize_t) image->columns; x != 0; x--)
{
double
blue,
green,
red;
red=(double) DecodePixelGamma((MagickRealType)
GetPixelRed(image,q));
green=(double) DecodePixelGamma((MagickRealType)
GetPixelGreen(image,q));
blue=(double) DecodePixelGamma((MagickRealType)
GetPixelBlue(image,q));
SetPixelRed(image,logmap[ScaleQuantumToMap(ClampToQuantum(red))],q);
SetPixelGreen(image,logmap[ScaleQuantumToMap(ClampToQuantum(green))],
q);
SetPixelBlue(image,logmap[ScaleQuantumToMap(ClampToQuantum(blue))],q);
q+=GetPixelChannels(image);
}
sync=SyncCacheViewAuthenticPixels(image_view,exception);
if (sync == MagickFalse)
status=MagickFalse;
}
image_view=DestroyCacheView(image_view);
logmap=(Quantum *) RelinquishMagickMemory(logmap);
if (SetImageColorspace(image,colorspace,exception) == MagickFalse)
return(MagickFalse);
return(status);
}
case RGBColorspace:
case scRGBColorspace:
{
/*
Transform image from sRGB to linear RGB.
*/
if (image->storage_class == PseudoClass)
{
if (SyncImage(image,exception) == MagickFalse)
return(MagickFalse);
if (SetImageStorageClass(image,DirectClass,exception) == MagickFalse)
return(MagickFalse);
}
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++)
{
MagickBooleanType
sync;
ssize_t
x;
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++)
{
double
blue,
green,
red;
red=DecodePixelGamma((MagickRealType) GetPixelRed(image,q));
green=DecodePixelGamma((MagickRealType) GetPixelGreen(image,q));
blue=DecodePixelGamma((MagickRealType) GetPixelBlue(image,q));
SetPixelRed(image,ClampToQuantum(red),q);
SetPixelGreen(image,ClampToQuantum(green),q);
SetPixelBlue(image,ClampToQuantum(blue),q);
q+=GetPixelChannels(image);
}
sync=SyncCacheViewAuthenticPixels(image_view,exception);
if (sync == MagickFalse)
status=MagickFalse;
}
image_view=DestroyCacheView(image_view);
if (SetImageColorspace(image,colorspace,exception) == MagickFalse)
return(MagickFalse);
return(status);
}
default:
break;
}
/*
Allocate the tables.
*/
x_map=(TransformPacket *) AcquireQuantumMemory((size_t) MaxMap+1UL,
sizeof(*x_map));
y_map=(TransformPacket *) AcquireQuantumMemory((size_t) MaxMap+1UL,
sizeof(*y_map));
z_map=(TransformPacket *) AcquireQuantumMemory((size_t) MaxMap+1UL,
sizeof(*z_map));
if ((x_map == (TransformPacket *) NULL) ||
(y_map == (TransformPacket *) NULL) ||
(z_map == (TransformPacket *) NULL))
{
if (x_map != (TransformPacket *) NULL)
x_map=(TransformPacket *) RelinquishMagickMemory(x_map);
if (y_map != (TransformPacket *) NULL)
y_map=(TransformPacket *) RelinquishMagickMemory(y_map);
if (z_map != (TransformPacket *) NULL)
z_map=(TransformPacket *) RelinquishMagickMemory(z_map);
ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
image->filename);
}
(void) memset(&primary_info,0,sizeof(primary_info));
switch (colorspace)
{
case OHTAColorspace:
{
/*
Initialize OHTA tables:
I1 = 0.33333*R+0.33334*G+0.33333*B
I2 = 0.50000*R+0.00000*G-0.50000*B
I3 =-0.25000*R+0.50000*G-0.25000*B
I and Q, normally -0.5 through 0.5, are normalized to the range 0
through QuantumRange.
*/
primary_info.y=(double) (MaxMap+1.0)/2.0;
primary_info.z=(double) (MaxMap+1.0)/2.0;
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static)
#endif
for (i=0; i <= (ssize_t) MaxMap; i++)
{
x_map[i].x=(MagickRealType) (0.33333*(double) i);
x_map[i].y=(MagickRealType) (0.50000*(double) i);
x_map[i].z=(MagickRealType) (-0.25000*(double) i);
y_map[i].x=(MagickRealType) (0.33334*(double) i);
y_map[i].y=(MagickRealType) (0.00000*(double) i);
y_map[i].z=(MagickRealType) (0.50000*(double) i);
z_map[i].x=(MagickRealType) (0.33333*(double) i);
z_map[i].y=(MagickRealType) (-0.50000*(double) i);
z_map[i].z=(MagickRealType) (-0.25000*(double) i);
}
break;
}
case Rec601YCbCrColorspace:
{
/*
Initialize YCbCr tables (ITU-R BT.601):
Y = 0.2988390*R+0.5868110*G+0.1143500*B
Cb= -0.1687367*R-0.3312640*G+0.5000000*B
Cr= 0.5000000*R-0.4186880*G-0.0813120*B
Cb and Cr, normally -0.5 through 0.5, are normalized to the range 0
through QuantumRange.
*/
primary_info.y=(double) (MaxMap+1.0)/2.0;
primary_info.z=(double) (MaxMap+1.0)/2.0;
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static)
#endif
for (i=0; i <= (ssize_t) MaxMap; i++)
{
x_map[i].x=(MagickRealType) (0.298839*(double) i);
x_map[i].y=(MagickRealType) (-0.1687367*(double) i);
x_map[i].z=(MagickRealType) (0.500000*(double) i);
y_map[i].x=(MagickRealType) (0.586811*(double) i);
y_map[i].y=(MagickRealType) (-0.331264*(double) i);
y_map[i].z=(MagickRealType) (-0.418688*(double) i);
z_map[i].x=(MagickRealType) (0.114350*(double) i);
z_map[i].y=(MagickRealType) (0.500000*(double) i);
z_map[i].z=(MagickRealType) (-0.081312*(double) i);
}
break;
}
case Rec709YCbCrColorspace:
{
/*
Initialize YCbCr tables (ITU-R BT.709):
Y = 0.212656*R+0.715158*G+0.072186*B
Cb= -0.114572*R-0.385428*G+0.500000*B
Cr= 0.500000*R-0.454153*G-0.045847*B
Cb and Cr, normally -0.5 through 0.5, are normalized to the range 0
through QuantumRange.
*/
primary_info.y=(double) (MaxMap+1.0)/2.0;
primary_info.z=(double) (MaxMap+1.0)/2.0;
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static)
#endif
for (i=0; i <= (ssize_t) MaxMap; i++)
{
x_map[i].x=(MagickRealType) (0.212656*(double) i);
x_map[i].y=(MagickRealType) (-0.114572*(double) i);
x_map[i].z=(MagickRealType) (0.500000*(double) i);
y_map[i].x=(MagickRealType) (0.715158*(double) i);
y_map[i].y=(MagickRealType) (-0.385428*(double) i);
y_map[i].z=(MagickRealType) (-0.454153*(double) i);
z_map[i].x=(MagickRealType) (0.072186*(double) i);
z_map[i].y=(MagickRealType) (0.500000*(double) i);
z_map[i].z=(MagickRealType) (-0.045847*(double) i);
}
break;
}
case YCCColorspace:
{
/*
Initialize YCC tables:
Y = 0.298839*R+0.586811*G+0.114350*B
C1= -0.298839*R-0.586811*G+0.88600*B
C2= 0.70100*R-0.586811*G-0.114350*B
YCC is scaled by 1.3584. C1 zero is 156 and C2 is at 137.
*/
primary_info.y=(double) ScaleQuantumToMap(ScaleCharToQuantum(156));
primary_info.z=(double) ScaleQuantumToMap(ScaleCharToQuantum(137));
for (i=0; i <= (ssize_t) (0.018*MaxMap); i++)
{
x_map[i].x=0.005382*i;
x_map[i].y=(-0.003296)*i;
x_map[i].z=0.009410*i;
y_map[i].x=0.010566*i;
y_map[i].y=(-0.006471)*i;
y_map[i].z=(-0.007880)*i;
z_map[i].x=0.002052*i;
z_map[i].y=0.009768*i;
z_map[i].z=(-0.001530)*i;
}
for ( ; i <= (ssize_t) MaxMap; i++)
{
x_map[i].x=0.298839*(1.099*i-0.099);
x_map[i].y=(-0.298839)*(1.099*i-0.099);
x_map[i].z=0.70100*(1.099*i-0.099);
y_map[i].x=0.586811*(1.099*i-0.099);
y_map[i].y=(-0.586811)*(1.099*i-0.099);
y_map[i].z=(-0.586811)*(1.099*i-0.099);
z_map[i].x=0.114350*(1.099*i-0.099);
z_map[i].y=0.88600*(1.099*i-0.099);
z_map[i].z=(-0.114350)*(1.099*i-0.099);
}
break;
}
default:
{
/*
Linear conversion tables.
*/
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static)
#endif
for (i=0; i <= (ssize_t) MaxMap; i++)
{
x_map[i].x=(MagickRealType) (1.0*(double) i);
x_map[i].y=(MagickRealType) 0.0;
x_map[i].z=(MagickRealType) 0.0;
y_map[i].x=(MagickRealType) 0.0;
y_map[i].y=(MagickRealType) (1.0*(double) i);
y_map[i].z=(MagickRealType) 0.0;
z_map[i].x=(MagickRealType) 0.0;
z_map[i].y=(MagickRealType) 0.0;
z_map[i].z=(MagickRealType) (1.0*(double) i);
}
break;
}
}
/*
Convert from sRGB.
*/
switch (image->storage_class)
{
case DirectClass:
default:
{
/*
Convert DirectClass image.
*/
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++)
{
MagickBooleanType
sync;
PixelInfo
pixel;
Quantum
*magick_restrict q;
ssize_t
x;
unsigned int
blue,
green,
red;
if (status == MagickFalse)
continue;
q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,
exception);
if (q == (Quantum *) NULL)
{
status=MagickFalse;
continue;
}
for (x=0; x < (ssize_t) image->columns; x++)
{
red=ScaleQuantumToMap(ClampToQuantum((MagickRealType)
GetPixelRed(image,q)));
green=ScaleQuantumToMap(ClampToQuantum((MagickRealType)
GetPixelGreen(image,q)));
blue=ScaleQuantumToMap(ClampToQuantum((MagickRealType)
GetPixelBlue(image,q)));
pixel.red=(x_map[red].x+y_map[green].x+z_map[blue].x)+
primary_info.x;
pixel.green=(x_map[red].y+y_map[green].y+z_map[blue].y)+
primary_info.y;
pixel.blue=(x_map[red].z+y_map[green].z+z_map[blue].z)+
primary_info.z;
SetPixelRed(image,ScaleMapToQuantum(pixel.red),q);
SetPixelGreen(image,ScaleMapToQuantum(pixel.green),q);
SetPixelBlue(image,ScaleMapToQuantum(pixel.blue),q);
q+=GetPixelChannels(image);
}
sync=SyncCacheViewAuthenticPixels(image_view,exception);
if (sync == MagickFalse)
status=MagickFalse;
if (image->progress_monitor != (MagickProgressMonitor) NULL)
{
MagickBooleanType
proceed;
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp atomic
#endif
progress++;
proceed=SetImageProgress(image,sRGBTransformImageTag,progress,
image->rows);
if (proceed == MagickFalse)
status=MagickFalse;
}
}
image_view=DestroyCacheView(image_view);
break;
}
case PseudoClass:
{
unsigned int
blue,
green,
red;
/*
Convert PseudoClass image.
*/
for (i=0; i < (ssize_t) image->colors; i++)
{
PixelInfo
pixel;
red=ScaleQuantumToMap(ClampToQuantum(image->colormap[i].red));
green=ScaleQuantumToMap(ClampToQuantum(image->colormap[i].green));
blue=ScaleQuantumToMap(ClampToQuantum(image->colormap[i].blue));
pixel.red=x_map[red].x+y_map[green].x+z_map[blue].x+primary_info.x;
pixel.green=x_map[red].y+y_map[green].y+z_map[blue].y+primary_info.y;
pixel.blue=x_map[red].z+y_map[green].z+z_map[blue].z+primary_info.z;
image->colormap[i].red=(double) ScaleMapToQuantum(pixel.red);
image->colormap[i].green=(double) ScaleMapToQuantum(pixel.green);
image->colormap[i].blue=(double) ScaleMapToQuantum(pixel.blue);
}
(void) SyncImage(image,exception);
break;
}
}
/*
Relinquish resources.
*/
z_map=(TransformPacket *) RelinquishMagickMemory(z_map);
y_map=(TransformPacket *) RelinquishMagickMemory(y_map);
x_map=(TransformPacket *) RelinquishMagickMemory(x_map);
if (SetImageColorspace(image,colorspace,exception) == MagickFalse)
return(MagickFalse);
return(status);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% S e t I m a g e C o l o r s p a c e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% SetImageColorspace() sets the colorspace member of the Image structure.
%
% The format of the SetImageColorspace method is:
%
% MagickBooleanType SetImageColorspace(Image *image,
% const ColorspaceType colorspace,ExceptiionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o colorspace: the colorspace.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport MagickBooleanType SetImageColorspace(Image *image,
const ColorspaceType colorspace,ExceptionInfo *exception)
{
ImageType
type;
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);
if (image->colorspace == colorspace)
return(MagickTrue);
image->colorspace=colorspace;
image->rendering_intent=UndefinedIntent;
image->gamma=1.000/2.200;
(void) memset(&image->chromaticity,0,sizeof(image->chromaticity));
type=image->type;
if (IsGrayColorspace(colorspace) != MagickFalse)
{
if (colorspace == LinearGRAYColorspace)
image->gamma=1.000;
type=GrayscaleType;
}
else
if ((IsRGBColorspace(colorspace) != MagickFalse) ||
(colorspace == XYZColorspace) || (colorspace == xyYColorspace))
image->gamma=1.000;
else
{
image->rendering_intent=PerceptualIntent;
image->chromaticity.red_primary.x=0.6400;
image->chromaticity.red_primary.y=0.3300;
image->chromaticity.red_primary.z=0.0300;
image->chromaticity.green_primary.x=0.3000;
image->chromaticity.green_primary.y=0.6000;
image->chromaticity.green_primary.z=0.1000;
image->chromaticity.blue_primary.x=0.1500;
image->chromaticity.blue_primary.y=0.0600;
image->chromaticity.blue_primary.z=0.7900;
image->chromaticity.white_point.x=0.3127;
image->chromaticity.white_point.y=0.3290;
image->chromaticity.white_point.z=0.3583;
}
status=SyncImagePixelCache(image,exception);
image->type=type;
return(status);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% S e t I m a g e G r a y %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% SetImageGray() returns MagickTrue if all the pixels in the image have the
% same red, green, and blue intensities and changes the type of the image to
% bi-level or grayscale.
%
% The format of the SetImageGray method is:
%
% MagickBooleanType SetImageGray(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 MagickBooleanType SetImageGray(Image *image,
ExceptionInfo *exception)
{
const char
*value;
ImageType
type;
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
if (IsImageGray(image) != MagickFalse)
return(MagickTrue);
if (IssRGBCompatibleColorspace(image->colorspace) == MagickFalse)
return(MagickFalse);
value=GetImageProperty(image,"colorspace:auto-grayscale",exception);
if (IsStringFalse(value) != MagickFalse)
return(MagickFalse);
type=IdentifyImageGray(image,exception);
if (type == UndefinedType)
return(MagickFalse);
image->colorspace=GRAYColorspace;
if (SyncImagePixelCache((Image *) image,exception) == MagickFalse)
return(MagickFalse);
image->type=type;
return(MagickTrue);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% S e t I m a g e M o n o c h r o m e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% SetImageMonochrome() returns MagickTrue if all the pixels in the image have
% the same red, green, and blue intensities and the intensity is either
% 0 or QuantumRange and changes the type of the image to bi-level.
%
% The format of the SetImageMonochrome method is:
%
% MagickBooleanType SetImageMonochrome(Image *image,
% ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport MagickBooleanType SetImageMonochrome(Image *image,
ExceptionInfo *exception)
{
const char
*value;
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
if (image->type == BilevelType)
return(MagickTrue);
if (IssRGBCompatibleColorspace(image->colorspace) == MagickFalse)
return(MagickFalse);
value=GetImageProperty(image,"colorspace:auto-grayscale",exception);
if (IsStringFalse(value) != MagickFalse)
return(MagickFalse);
if (IdentifyImageMonochrome(image,exception) == MagickFalse)
return(MagickFalse);
image->colorspace=GRAYColorspace;
if (SyncImagePixelCache((Image *) image,exception) == MagickFalse)
return(MagickFalse);
image->type=BilevelType;
return(MagickTrue);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% T r a n s f o r m I m a g e C o l o r s p a c e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% TransformImageColorspace() transforms an image colorspace, changing the
% image data to reflect the new colorspace.
%
% The format of the TransformImageColorspace method is:
%
% MagickBooleanType TransformImageColorspace(Image *image,
% const ColorspaceType colorspace,ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o colorspace: the colorspace.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport MagickBooleanType TransformImageColorspace(Image *image,
const ColorspaceType colorspace,ExceptionInfo *exception)
{
MagickBooleanType
status;
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
if (image->colorspace == colorspace)
return(SetImageColorspace(image,colorspace,exception));
(void) DeleteImageProfile(image,"icc");
(void) DeleteImageProfile(image,"icm");
if (colorspace == UndefinedColorspace)
return(SetImageColorspace(image,colorspace,exception));
/*
Convert the reference image from an alternate colorspace to sRGB.
*/
if (IssRGBColorspace(colorspace) != MagickFalse)
return(TransformsRGBImage(image,exception));
status=MagickTrue;
if (IssRGBColorspace(image->colorspace) == MagickFalse)
status=TransformsRGBImage(image,exception);
if (status == MagickFalse)
return(status);
/*
Convert the reference image from sRGB to an alternate colorspace.
*/
if (sRGBTransformImage(image,colorspace,exception) == MagickFalse)
status=MagickFalse;
return(status);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
+ T r a n s f o r m s R G B I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% TransformsRGBImage() converts the reference image from an alternate
% colorspace to sRGB. The transformation matrices are not the standard ones:
% the weights are rescaled to normalize the range of the transformed values
% to be [0..QuantumRange].
%
% The format of the TransformsRGBImage method is:
%
% MagickBooleanType TransformsRGBImage(Image *image,
% ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o exception: return any errors or warnings in this structure.
%
*/
static inline void ConvertCMYToRGB(const double cyan,const double magenta,
const double yellow,double *red,double *green,double *blue)
{
*red=QuantumRange*(1.0-cyan);
*green=QuantumRange*(1.0-magenta);
*blue=QuantumRange*(1.0-yellow);
}
static inline void ConvertLMSToXYZ(const double L,const double M,const double S,
double *X,double *Y,double *Z)
{
*X=1.096123820835514*L-0.278869000218287*M+0.182745179382773*S;
*Y=0.454369041975359*L+0.473533154307412*M+0.072097803717229*S;
*Z=(-0.009627608738429)*L-0.005698031216113*M+1.015325639954543*S;
}
static inline void ConvertLMSToRGB(const double L,const double M,
const double S,double *red,double *green,double *blue)
{
double
X,
Y,
Z;
ConvertLMSToXYZ(L,M,S,&X,&Y,&Z);
ConvertXYZToRGB(X,Y,Z,red,green,blue);
}
static inline void ConvertLuvToRGB(const double L,const double u,
const double v,double *red,double *green,double *blue)
{
double
X,
Y,
Z;
ConvertLuvToXYZ(100.0*L,354.0*u-134.0,262.0*v-140.0,&X,&Y,&Z);
ConvertXYZToRGB(X,Y,Z,red,green,blue);
}
static inline ssize_t RoundToYCC(const double value)
{
if (value <= 0.0)
return(0);
if (value >= 1388.0)
return(1388);
return((ssize_t) (value+0.5));
}
static inline void ConvertLabToRGB(const double L,const double a,
const double b,double *red,double *green,double *blue)
{
double
X,
Y,
Z;
ConvertLabToXYZ(100.0*L,255.0*(a-0.5),255.0*(b-0.5),&X,&Y,&Z);
ConvertXYZToRGB(X,Y,Z,red,green,blue);
}
static inline void ConvertxyYToRGB(const double low_x,const double low_y,
const double cap_Y,double *red,double *green,double *blue)
{
double
gamma,
X,
Y,
Z;
gamma=PerceptibleReciprocal(low_y);
X=gamma*cap_Y*low_x;
Y=cap_Y;
Z=gamma*cap_Y*(1.0-low_x-low_y);
ConvertXYZToRGB(X,Y,Z,red,green,blue);
}
static void ConvertYPbPrToRGB(const double Y,const double Pb,const double Pr,
double *red,double *green,double *blue)
{
*red=QuantumRange*(0.99999999999914679361*Y-1.2188941887145875e-06*(Pb-0.5)+
1.4019995886561440468*(Pr-0.5));
*green=QuantumRange*(0.99999975910502514331*Y-0.34413567816504303521*(Pb-0.5)-
0.71413649331646789076*(Pr-0.5));
*blue=QuantumRange*(1.00000124040004623180*Y+1.77200006607230409200*(Pb-0.5)+
2.1453384174593273e-06*(Pr-0.5));
}
static void ConvertYCbCrToRGB(const double Y,const double Cb,
const double Cr,double *red,double *green,double *blue)
{
ConvertYPbPrToRGB(Y,Cb,Cr,red,green,blue);
}
static void ConvertYIQToRGB(const double Y,const double I,const double Q,
double *red,double *green,double *blue)
{
*red=QuantumRange*(Y+0.9562957197589482261*(I-0.5)+0.6210244164652610754*
(Q-0.5));
*green=QuantumRange*(Y-0.2721220993185104464*(I-0.5)-0.6473805968256950427*
(Q-0.5));
*blue=QuantumRange*(Y-1.1069890167364901945*(I-0.5)+1.7046149983646481374*
(Q-0.5));
}
static void ConvertYDbDrToRGB(const double Y,const double Db,const double Dr,
double *red,double *green,double *blue)
{
*red=QuantumRange*(Y+9.2303716147657e-05*(Db-0.5)-
0.52591263066186533*(Dr-0.5));
*green=QuantumRange*(Y-0.12913289889050927*(Db-0.5)+
0.26789932820759876*(Dr-0.5));
*blue=QuantumRange*(Y+0.66467905997895482*(Db-0.5)-
7.9202543533108e-05*(Dr-0.5));
}
static void ConvertYUVToRGB(const double Y,const double U,const double V,
double *red,double *green,double *blue)
{
*red=QuantumRange*(Y-3.945707070708279e-05*(U-0.5)+1.1398279671717170825*
(V-0.5));
*green=QuantumRange*(Y-0.3946101641414141437*(U-0.5)-0.5805003156565656797*
(V-0.5));
*blue=QuantumRange*(Y+2.0319996843434342537*(U-0.5)-4.813762626262513e-04*
(V-0.5));
}
static MagickBooleanType TransformsRGBImage(Image *image,
ExceptionInfo *exception)
{
#define TransformsRGBImageTag "Transform/Image"
static const float
YCCMap[1389] =
{
0.000000f, 0.000720f, 0.001441f, 0.002161f, 0.002882f, 0.003602f,
0.004323f, 0.005043f, 0.005764f, 0.006484f, 0.007205f, 0.007925f,
0.008646f, 0.009366f, 0.010086f, 0.010807f, 0.011527f, 0.012248f,
0.012968f, 0.013689f, 0.014409f, 0.015130f, 0.015850f, 0.016571f,
0.017291f, 0.018012f, 0.018732f, 0.019452f, 0.020173f, 0.020893f,
0.021614f, 0.022334f, 0.023055f, 0.023775f, 0.024496f, 0.025216f,
0.025937f, 0.026657f, 0.027378f, 0.028098f, 0.028818f, 0.029539f,
0.030259f, 0.030980f, 0.031700f, 0.032421f, 0.033141f, 0.033862f,
0.034582f, 0.035303f, 0.036023f, 0.036744f, 0.037464f, 0.038184f,
0.038905f, 0.039625f, 0.040346f, 0.041066f, 0.041787f, 0.042507f,
0.043228f, 0.043948f, 0.044669f, 0.045389f, 0.046110f, 0.046830f,
0.047550f, 0.048271f, 0.048991f, 0.049712f, 0.050432f, 0.051153f,
0.051873f, 0.052594f, 0.053314f, 0.054035f, 0.054755f, 0.055476f,
0.056196f, 0.056916f, 0.057637f, 0.058357f, 0.059078f, 0.059798f,
0.060519f, 0.061239f, 0.061960f, 0.062680f, 0.063401f, 0.064121f,
0.064842f, 0.065562f, 0.066282f, 0.067003f, 0.067723f, 0.068444f,
0.069164f, 0.069885f, 0.070605f, 0.071326f, 0.072046f, 0.072767f,
0.073487f, 0.074207f, 0.074928f, 0.075648f, 0.076369f, 0.077089f,
0.077810f, 0.078530f, 0.079251f, 0.079971f, 0.080692f, 0.081412f,
0.082133f, 0.082853f, 0.083573f, 0.084294f, 0.085014f, 0.085735f,
0.086455f, 0.087176f, 0.087896f, 0.088617f, 0.089337f, 0.090058f,
0.090778f, 0.091499f, 0.092219f, 0.092939f, 0.093660f, 0.094380f,
0.095101f, 0.095821f, 0.096542f, 0.097262f, 0.097983f, 0.098703f,
0.099424f, 0.100144f, 0.100865f, 0.101585f, 0.102305f, 0.103026f,
0.103746f, 0.104467f, 0.105187f, 0.105908f, 0.106628f, 0.107349f,
0.108069f, 0.108790f, 0.109510f, 0.110231f, 0.110951f, 0.111671f,
0.112392f, 0.113112f, 0.113833f, 0.114553f, 0.115274f, 0.115994f,
0.116715f, 0.117435f, 0.118156f, 0.118876f, 0.119597f, 0.120317f,
0.121037f, 0.121758f, 0.122478f, 0.123199f, 0.123919f, 0.124640f,
0.125360f, 0.126081f, 0.126801f, 0.127522f, 0.128242f, 0.128963f,
0.129683f, 0.130403f, 0.131124f, 0.131844f, 0.132565f, 0.133285f,
0.134006f, 0.134726f, 0.135447f, 0.136167f, 0.136888f, 0.137608f,
0.138329f, 0.139049f, 0.139769f, 0.140490f, 0.141210f, 0.141931f,
0.142651f, 0.143372f, 0.144092f, 0.144813f, 0.145533f, 0.146254f,
0.146974f, 0.147695f, 0.148415f, 0.149135f, 0.149856f, 0.150576f,
0.151297f, 0.152017f, 0.152738f, 0.153458f, 0.154179f, 0.154899f,
0.155620f, 0.156340f, 0.157061f, 0.157781f, 0.158501f, 0.159222f,
0.159942f, 0.160663f, 0.161383f, 0.162104f, 0.162824f, 0.163545f,
0.164265f, 0.164986f, 0.165706f, 0.166427f, 0.167147f, 0.167867f,
0.168588f, 0.169308f, 0.170029f, 0.170749f, 0.171470f, 0.172190f,
0.172911f, 0.173631f, 0.174352f, 0.175072f, 0.175793f, 0.176513f,
0.177233f, 0.177954f, 0.178674f, 0.179395f, 0.180115f, 0.180836f,
0.181556f, 0.182277f, 0.182997f, 0.183718f, 0.184438f, 0.185159f,
0.185879f, 0.186599f, 0.187320f, 0.188040f, 0.188761f, 0.189481f,
0.190202f, 0.190922f, 0.191643f, 0.192363f, 0.193084f, 0.193804f,
0.194524f, 0.195245f, 0.195965f, 0.196686f, 0.197406f, 0.198127f,
0.198847f, 0.199568f, 0.200288f, 0.201009f, 0.201729f, 0.202450f,
0.203170f, 0.203890f, 0.204611f, 0.205331f, 0.206052f, 0.206772f,
0.207493f, 0.208213f, 0.208934f, 0.209654f, 0.210375f, 0.211095f,
0.211816f, 0.212536f, 0.213256f, 0.213977f, 0.214697f, 0.215418f,
0.216138f, 0.216859f, 0.217579f, 0.218300f, 0.219020f, 0.219741f,
0.220461f, 0.221182f, 0.221902f, 0.222622f, 0.223343f, 0.224063f,
0.224784f, 0.225504f, 0.226225f, 0.226945f, 0.227666f, 0.228386f,
0.229107f, 0.229827f, 0.230548f, 0.231268f, 0.231988f, 0.232709f,
0.233429f, 0.234150f, 0.234870f, 0.235591f, 0.236311f, 0.237032f,
0.237752f, 0.238473f, 0.239193f, 0.239914f, 0.240634f, 0.241354f,
0.242075f, 0.242795f, 0.243516f, 0.244236f, 0.244957f, 0.245677f,
0.246398f, 0.247118f, 0.247839f, 0.248559f, 0.249280f, 0.250000f,
0.250720f, 0.251441f, 0.252161f, 0.252882f, 0.253602f, 0.254323f,
0.255043f, 0.255764f, 0.256484f, 0.257205f, 0.257925f, 0.258646f,
0.259366f, 0.260086f, 0.260807f, 0.261527f, 0.262248f, 0.262968f,
0.263689f, 0.264409f, 0.265130f, 0.265850f, 0.266571f, 0.267291f,
0.268012f, 0.268732f, 0.269452f, 0.270173f, 0.270893f, 0.271614f,
0.272334f, 0.273055f, 0.273775f, 0.274496f, 0.275216f, 0.275937f,
0.276657f, 0.277378f, 0.278098f, 0.278818f, 0.279539f, 0.280259f,
0.280980f, 0.281700f, 0.282421f, 0.283141f, 0.283862f, 0.284582f,
0.285303f, 0.286023f, 0.286744f, 0.287464f, 0.288184f, 0.288905f,
0.289625f, 0.290346f, 0.291066f, 0.291787f, 0.292507f, 0.293228f,
0.293948f, 0.294669f, 0.295389f, 0.296109f, 0.296830f, 0.297550f,
0.298271f, 0.298991f, 0.299712f, 0.300432f, 0.301153f, 0.301873f,
0.302594f, 0.303314f, 0.304035f, 0.304755f, 0.305476f, 0.306196f,
0.306916f, 0.307637f, 0.308357f, 0.309078f, 0.309798f, 0.310519f,
0.311239f, 0.311960f, 0.312680f, 0.313401f, 0.314121f, 0.314842f,
0.315562f, 0.316282f, 0.317003f, 0.317723f, 0.318444f, 0.319164f,
0.319885f, 0.320605f, 0.321326f, 0.322046f, 0.322767f, 0.323487f,
0.324207f, 0.324928f, 0.325648f, 0.326369f, 0.327089f, 0.327810f,
0.328530f, 0.329251f, 0.329971f, 0.330692f, 0.331412f, 0.332133f,
0.332853f, 0.333573f, 0.334294f, 0.335014f, 0.335735f, 0.336455f,
0.337176f, 0.337896f, 0.338617f, 0.339337f, 0.340058f, 0.340778f,
0.341499f, 0.342219f, 0.342939f, 0.343660f, 0.344380f, 0.345101f,
0.345821f, 0.346542f, 0.347262f, 0.347983f, 0.348703f, 0.349424f,
0.350144f, 0.350865f, 0.351585f, 0.352305f, 0.353026f, 0.353746f,
0.354467f, 0.355187f, 0.355908f, 0.356628f, 0.357349f, 0.358069f,
0.358790f, 0.359510f, 0.360231f, 0.360951f, 0.361671f, 0.362392f,
0.363112f, 0.363833f, 0.364553f, 0.365274f, 0.365994f, 0.366715f,
0.367435f, 0.368156f, 0.368876f, 0.369597f, 0.370317f, 0.371037f,
0.371758f, 0.372478f, 0.373199f, 0.373919f, 0.374640f, 0.375360f,
0.376081f, 0.376801f, 0.377522f, 0.378242f, 0.378963f, 0.379683f,
0.380403f, 0.381124f, 0.381844f, 0.382565f, 0.383285f, 0.384006f,
0.384726f, 0.385447f, 0.386167f, 0.386888f, 0.387608f, 0.388329f,
0.389049f, 0.389769f, 0.390490f, 0.391210f, 0.391931f, 0.392651f,
0.393372f, 0.394092f, 0.394813f, 0.395533f, 0.396254f, 0.396974f,
0.397695f, 0.398415f, 0.399135f, 0.399856f, 0.400576f, 0.401297f,
0.402017f, 0.402738f, 0.403458f, 0.404179f, 0.404899f, 0.405620f,
0.406340f, 0.407061f, 0.407781f, 0.408501f, 0.409222f, 0.409942f,
0.410663f, 0.411383f, 0.412104f, 0.412824f, 0.413545f, 0.414265f,
0.414986f, 0.415706f, 0.416427f, 0.417147f, 0.417867f, 0.418588f,
0.419308f, 0.420029f, 0.420749f, 0.421470f, 0.422190f, 0.422911f,
0.423631f, 0.424352f, 0.425072f, 0.425793f, 0.426513f, 0.427233f,
0.427954f, 0.428674f, 0.429395f, 0.430115f, 0.430836f, 0.431556f,
0.432277f, 0.432997f, 0.433718f, 0.434438f, 0.435158f, 0.435879f,
0.436599f, 0.437320f, 0.438040f, 0.438761f, 0.439481f, 0.440202f,
0.440922f, 0.441643f, 0.442363f, 0.443084f, 0.443804f, 0.444524f,
0.445245f, 0.445965f, 0.446686f, 0.447406f, 0.448127f, 0.448847f,
0.449568f, 0.450288f, 0.451009f, 0.451729f, 0.452450f, 0.453170f,
0.453891f, 0.454611f, 0.455331f, 0.456052f, 0.456772f, 0.457493f,
0.458213f, 0.458934f, 0.459654f, 0.460375f, 0.461095f, 0.461816f,
0.462536f, 0.463256f, 0.463977f, 0.464697f, 0.465418f, 0.466138f,
0.466859f, 0.467579f, 0.468300f, 0.469020f, 0.469741f, 0.470461f,
0.471182f, 0.471902f, 0.472622f, 0.473343f, 0.474063f, 0.474784f,
0.475504f, 0.476225f, 0.476945f, 0.477666f, 0.478386f, 0.479107f,
0.479827f, 0.480548f, 0.481268f, 0.481988f, 0.482709f, 0.483429f,
0.484150f, 0.484870f, 0.485591f, 0.486311f, 0.487032f, 0.487752f,
0.488473f, 0.489193f, 0.489914f, 0.490634f, 0.491354f, 0.492075f,
0.492795f, 0.493516f, 0.494236f, 0.494957f, 0.495677f, 0.496398f,
0.497118f, 0.497839f, 0.498559f, 0.499280f, 0.500000f, 0.500720f,
0.501441f, 0.502161f, 0.502882f, 0.503602f, 0.504323f, 0.505043f,
0.505764f, 0.506484f, 0.507205f, 0.507925f, 0.508646f, 0.509366f,
0.510086f, 0.510807f, 0.511527f, 0.512248f, 0.512968f, 0.513689f,
0.514409f, 0.515130f, 0.515850f, 0.516571f, 0.517291f, 0.518012f,
0.518732f, 0.519452f, 0.520173f, 0.520893f, 0.521614f, 0.522334f,
0.523055f, 0.523775f, 0.524496f, 0.525216f, 0.525937f, 0.526657f,
0.527378f, 0.528098f, 0.528818f, 0.529539f, 0.530259f, 0.530980f,
0.531700f, 0.532421f, 0.533141f, 0.533862f, 0.534582f, 0.535303f,
0.536023f, 0.536744f, 0.537464f, 0.538184f, 0.538905f, 0.539625f,
0.540346f, 0.541066f, 0.541787f, 0.542507f, 0.543228f, 0.543948f,
0.544669f, 0.545389f, 0.546109f, 0.546830f, 0.547550f, 0.548271f,
0.548991f, 0.549712f, 0.550432f, 0.551153f, 0.551873f, 0.552594f,
0.553314f, 0.554035f, 0.554755f, 0.555476f, 0.556196f, 0.556916f,
0.557637f, 0.558357f, 0.559078f, 0.559798f, 0.560519f, 0.561239f,
0.561960f, 0.562680f, 0.563401f, 0.564121f, 0.564842f, 0.565562f,
0.566282f, 0.567003f, 0.567723f, 0.568444f, 0.569164f, 0.569885f,
0.570605f, 0.571326f, 0.572046f, 0.572767f, 0.573487f, 0.574207f,
0.574928f, 0.575648f, 0.576369f, 0.577089f, 0.577810f, 0.578530f,
0.579251f, 0.579971f, 0.580692f, 0.581412f, 0.582133f, 0.582853f,
0.583573f, 0.584294f, 0.585014f, 0.585735f, 0.586455f, 0.587176f,
0.587896f, 0.588617f, 0.589337f, 0.590058f, 0.590778f, 0.591499f,
0.592219f, 0.592939f, 0.593660f, 0.594380f, 0.595101f, 0.595821f,
0.596542f, 0.597262f, 0.597983f, 0.598703f, 0.599424f, 0.600144f,
0.600865f, 0.601585f, 0.602305f, 0.603026f, 0.603746f, 0.604467f,
0.605187f, 0.605908f, 0.606628f, 0.607349f, 0.608069f, 0.608790f,
0.609510f, 0.610231f, 0.610951f, 0.611671f, 0.612392f, 0.613112f,
0.613833f, 0.614553f, 0.615274f, 0.615994f, 0.616715f, 0.617435f,
0.618156f, 0.618876f, 0.619597f, 0.620317f, 0.621037f, 0.621758f,
0.622478f, 0.623199f, 0.623919f, 0.624640f, 0.625360f, 0.626081f,
0.626801f, 0.627522f, 0.628242f, 0.628963f, 0.629683f, 0.630403f,
0.631124f, 0.631844f, 0.632565f, 0.633285f, 0.634006f, 0.634726f,
0.635447f, 0.636167f, 0.636888f, 0.637608f, 0.638329f, 0.639049f,
0.639769f, 0.640490f, 0.641210f, 0.641931f, 0.642651f, 0.643372f,
0.644092f, 0.644813f, 0.645533f, 0.646254f, 0.646974f, 0.647695f,
0.648415f, 0.649135f, 0.649856f, 0.650576f, 0.651297f, 0.652017f,
0.652738f, 0.653458f, 0.654179f, 0.654899f, 0.655620f, 0.656340f,
0.657061f, 0.657781f, 0.658501f, 0.659222f, 0.659942f, 0.660663f,
0.661383f, 0.662104f, 0.662824f, 0.663545f, 0.664265f, 0.664986f,
0.665706f, 0.666427f, 0.667147f, 0.667867f, 0.668588f, 0.669308f,
0.670029f, 0.670749f, 0.671470f, 0.672190f, 0.672911f, 0.673631f,
0.674352f, 0.675072f, 0.675793f, 0.676513f, 0.677233f, 0.677954f,
0.678674f, 0.679395f, 0.680115f, 0.680836f, 0.681556f, 0.682277f,
0.682997f, 0.683718f, 0.684438f, 0.685158f, 0.685879f, 0.686599f,
0.687320f, 0.688040f, 0.688761f, 0.689481f, 0.690202f, 0.690922f,
0.691643f, 0.692363f, 0.693084f, 0.693804f, 0.694524f, 0.695245f,
0.695965f, 0.696686f, 0.697406f, 0.698127f, 0.698847f, 0.699568f,
0.700288f, 0.701009f, 0.701729f, 0.702450f, 0.703170f, 0.703891f,
0.704611f, 0.705331f, 0.706052f, 0.706772f, 0.707493f, 0.708213f,
0.708934f, 0.709654f, 0.710375f, 0.711095f, 0.711816f, 0.712536f,
0.713256f, 0.713977f, 0.714697f, 0.715418f, 0.716138f, 0.716859f,
0.717579f, 0.718300f, 0.719020f, 0.719741f, 0.720461f, 0.721182f,
0.721902f, 0.722622f, 0.723343f, 0.724063f, 0.724784f, 0.725504f,
0.726225f, 0.726945f, 0.727666f, 0.728386f, 0.729107f, 0.729827f,
0.730548f, 0.731268f, 0.731988f, 0.732709f, 0.733429f, 0.734150f,
0.734870f, 0.735591f, 0.736311f, 0.737032f, 0.737752f, 0.738473f,
0.739193f, 0.739914f, 0.740634f, 0.741354f, 0.742075f, 0.742795f,
0.743516f, 0.744236f, 0.744957f, 0.745677f, 0.746398f, 0.747118f,
0.747839f, 0.748559f, 0.749280f, 0.750000f, 0.750720f, 0.751441f,
0.752161f, 0.752882f, 0.753602f, 0.754323f, 0.755043f, 0.755764f,
0.756484f, 0.757205f, 0.757925f, 0.758646f, 0.759366f, 0.760086f,
0.760807f, 0.761527f, 0.762248f, 0.762968f, 0.763689f, 0.764409f,
0.765130f, 0.765850f, 0.766571f, 0.767291f, 0.768012f, 0.768732f,
0.769452f, 0.770173f, 0.770893f, 0.771614f, 0.772334f, 0.773055f,
0.773775f, 0.774496f, 0.775216f, 0.775937f, 0.776657f, 0.777378f,
0.778098f, 0.778818f, 0.779539f, 0.780259f, 0.780980f, 0.781700f,
0.782421f, 0.783141f, 0.783862f, 0.784582f, 0.785303f, 0.786023f,
0.786744f, 0.787464f, 0.788184f, 0.788905f, 0.789625f, 0.790346f,
0.791066f, 0.791787f, 0.792507f, 0.793228f, 0.793948f, 0.794669f,
0.795389f, 0.796109f, 0.796830f, 0.797550f, 0.798271f, 0.798991f,
0.799712f, 0.800432f, 0.801153f, 0.801873f, 0.802594f, 0.803314f,
0.804035f, 0.804755f, 0.805476f, 0.806196f, 0.806916f, 0.807637f,
0.808357f, 0.809078f, 0.809798f, 0.810519f, 0.811239f, 0.811960f,
0.812680f, 0.813401f, 0.814121f, 0.814842f, 0.815562f, 0.816282f,
0.817003f, 0.817723f, 0.818444f, 0.819164f, 0.819885f, 0.820605f,
0.821326f, 0.822046f, 0.822767f, 0.823487f, 0.824207f, 0.824928f,
0.825648f, 0.826369f, 0.827089f, 0.827810f, 0.828530f, 0.829251f,
0.829971f, 0.830692f, 0.831412f, 0.832133f, 0.832853f, 0.833573f,
0.834294f, 0.835014f, 0.835735f, 0.836455f, 0.837176f, 0.837896f,
0.838617f, 0.839337f, 0.840058f, 0.840778f, 0.841499f, 0.842219f,
0.842939f, 0.843660f, 0.844380f, 0.845101f, 0.845821f, 0.846542f,
0.847262f, 0.847983f, 0.848703f, 0.849424f, 0.850144f, 0.850865f,
0.851585f, 0.852305f, 0.853026f, 0.853746f, 0.854467f, 0.855187f,
0.855908f, 0.856628f, 0.857349f, 0.858069f, 0.858790f, 0.859510f,
0.860231f, 0.860951f, 0.861671f, 0.862392f, 0.863112f, 0.863833f,
0.864553f, 0.865274f, 0.865994f, 0.866715f, 0.867435f, 0.868156f,
0.868876f, 0.869597f, 0.870317f, 0.871037f, 0.871758f, 0.872478f,
0.873199f, 0.873919f, 0.874640f, 0.875360f, 0.876081f, 0.876801f,
0.877522f, 0.878242f, 0.878963f, 0.879683f, 0.880403f, 0.881124f,
0.881844f, 0.882565f, 0.883285f, 0.884006f, 0.884726f, 0.885447f,
0.886167f, 0.886888f, 0.887608f, 0.888329f, 0.889049f, 0.889769f,
0.890490f, 0.891210f, 0.891931f, 0.892651f, 0.893372f, 0.894092f,
0.894813f, 0.895533f, 0.896254f, 0.896974f, 0.897695f, 0.898415f,
0.899135f, 0.899856f, 0.900576f, 0.901297f, 0.902017f, 0.902738f,
0.903458f, 0.904179f, 0.904899f, 0.905620f, 0.906340f, 0.907061f,
0.907781f, 0.908501f, 0.909222f, 0.909942f, 0.910663f, 0.911383f,
0.912104f, 0.912824f, 0.913545f, 0.914265f, 0.914986f, 0.915706f,
0.916427f, 0.917147f, 0.917867f, 0.918588f, 0.919308f, 0.920029f,
0.920749f, 0.921470f, 0.922190f, 0.922911f, 0.923631f, 0.924352f,
0.925072f, 0.925793f, 0.926513f, 0.927233f, 0.927954f, 0.928674f,
0.929395f, 0.930115f, 0.930836f, 0.931556f, 0.932277f, 0.932997f,
0.933718f, 0.934438f, 0.935158f, 0.935879f, 0.936599f, 0.937320f,
0.938040f, 0.938761f, 0.939481f, 0.940202f, 0.940922f, 0.941643f,
0.942363f, 0.943084f, 0.943804f, 0.944524f, 0.945245f, 0.945965f,
0.946686f, 0.947406f, 0.948127f, 0.948847f, 0.949568f, 0.950288f,
0.951009f, 0.951729f, 0.952450f, 0.953170f, 0.953891f, 0.954611f,
0.955331f, 0.956052f, 0.956772f, 0.957493f, 0.958213f, 0.958934f,
0.959654f, 0.960375f, 0.961095f, 0.961816f, 0.962536f, 0.963256f,
0.963977f, 0.964697f, 0.965418f, 0.966138f, 0.966859f, 0.967579f,
0.968300f, 0.969020f, 0.969741f, 0.970461f, 0.971182f, 0.971902f,
0.972622f, 0.973343f, 0.974063f, 0.974784f, 0.975504f, 0.976225f,
0.976945f, 0.977666f, 0.978386f, 0.979107f, 0.979827f, 0.980548f,
0.981268f, 0.981988f, 0.982709f, 0.983429f, 0.984150f, 0.984870f,
0.985591f, 0.986311f, 0.987032f, 0.987752f, 0.988473f, 0.989193f,
0.989914f, 0.990634f, 0.991354f, 0.992075f, 0.992795f, 0.993516f,
0.994236f, 0.994957f, 0.995677f, 0.996398f, 0.997118f, 0.997839f,
0.998559f, 0.999280f, 1.000000f
};
CacheView
*image_view;
MagickBooleanType
status;
MagickOffsetType
progress;
ssize_t
i;
ssize_t
y;
TransformPacket
*y_map,
*x_map,
*z_map;
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
status=MagickTrue;
progress=0;
switch (image->colorspace)
{
case CMYKColorspace:
{
PixelInfo
zero;
/*
Transform image from CMYK to sRGB.
*/
if (image->storage_class == PseudoClass)
{
if (SyncImage(image,exception) == MagickFalse)
return(MagickFalse);
if (SetImageStorageClass(image,DirectClass,exception) == MagickFalse)
return(MagickFalse);
}
GetPixelInfo(image,&zero);
image_view=AcquireAuthenticCacheView(image,exception);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static) shared(status) \
magick_number_threads(image,image,image->rows,1)
#endif
for (y=0; y < (ssize_t) image->rows; y++)
{
MagickBooleanType
sync;
PixelInfo
pixel;
ssize_t
x;
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;
}
pixel=zero;
for (x=0; x < (ssize_t) image->columns; x++)
{
GetPixelInfoPixel(image,q,&pixel);
ConvertCMYKToRGB(&pixel);
SetPixelViaPixelInfo(image,&pixel,q);
q+=GetPixelChannels(image);
}
sync=SyncCacheViewAuthenticPixels(image_view,exception);
if (sync == MagickFalse)
status=MagickFalse;
}
image_view=DestroyCacheView(image_view);
if (SetImageColorspace(image,sRGBColorspace,exception) == MagickFalse)
return(MagickFalse);
return(status);
}
case LinearGRAYColorspace:
{
/*
Transform linear GRAY to sRGB colorspace.
*/
if (image->storage_class == PseudoClass)
{
if (SyncImage(image,exception) == MagickFalse)
return(MagickFalse);
if (SetImageStorageClass(image,DirectClass,exception) == MagickFalse)
return(MagickFalse);
}
if (SetImageColorspace(image,sRGBColorspace,exception) == MagickFalse)
return(MagickFalse);
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++)
{
MagickBooleanType
sync;
ssize_t
x;
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=(ssize_t) image->columns; x != 0; x--)
{
MagickRealType
gray;
gray=0.212656*GetPixelRed(image,q)+0.715158*GetPixelGreen(image,q)+
0.072186*GetPixelBlue(image,q);
gray=EncodePixelGamma(gray);
SetPixelRed(image,ClampToQuantum(gray),q);
SetPixelGreen(image,ClampToQuantum(gray),q);
SetPixelBlue(image,ClampToQuantum(gray),q);
q+=GetPixelChannels(image);
}
sync=SyncCacheViewAuthenticPixels(image_view,exception);
if (sync == MagickFalse)
status=MagickFalse;
}
image_view=DestroyCacheView(image_view);
if (SetImageColorspace(image,sRGBColorspace,exception) == MagickFalse)
return(MagickFalse);
return(status);
}
case GRAYColorspace:
{
/*
Transform linear GRAY to sRGB colorspace.
*/
if (image->storage_class == PseudoClass)
{
if (SyncImage(image,exception) == MagickFalse)
return(MagickFalse);
if (SetImageStorageClass(image,DirectClass,exception) == MagickFalse)
return(MagickFalse);
}
if (SetImageColorspace(image,sRGBColorspace,exception) == MagickFalse)
return(MagickFalse);
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++)
{
MagickBooleanType
sync;
ssize_t
x;
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=(ssize_t) image->columns; x != 0; x--)
{
MagickRealType
gray;
gray=0.212656*GetPixelRed(image,q)+0.715158*GetPixelGreen(image,q)+
0.072186*GetPixelBlue(image,q);
SetPixelRed(image,ClampToQuantum(gray),q);
SetPixelGreen(image,ClampToQuantum(gray),q);
SetPixelBlue(image,ClampToQuantum(gray),q);
q+=GetPixelChannels(image);
}
sync=SyncCacheViewAuthenticPixels(image_view,exception);
if (sync == MagickFalse)
status=MagickFalse;
}
image_view=DestroyCacheView(image_view);
if (SetImageColorspace(image,sRGBColorspace,exception) == MagickFalse)
return(MagickFalse);
return(status);
}
case Adobe98Colorspace:
case CMYColorspace:
case DisplayP3Colorspace:
case HCLColorspace:
case HCLpColorspace:
case HSBColorspace:
case HSIColorspace:
case HSLColorspace:
case HSVColorspace:
case HWBColorspace:
case JzazbzColorspace:
case LabColorspace:
case LCHColorspace:
case LCHabColorspace:
case LCHuvColorspace:
case LMSColorspace:
case LuvColorspace:
case ProPhotoColorspace:
case xyYColorspace:
case XYZColorspace:
case YCbCrColorspace:
case YDbDrColorspace:
case YIQColorspace:
case YPbPrColorspace:
case YUVColorspace:
{
const char
*value;
double
white_luminance;
/*
Transform image from source colorspace to sRGB.
*/
white_luminance=10000.0;
value=GetImageProperty(image,"white-luminance",exception);
if (value != (const char *) NULL)
white_luminance=StringToDouble(value,(char **) NULL);
if (image->storage_class == PseudoClass)
{
if (SyncImage(image,exception) == MagickFalse)
return(MagickFalse);
if (SetImageStorageClass(image,DirectClass,exception) == MagickFalse)
return(MagickFalse);
}
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++)
{
MagickBooleanType
sync;
ssize_t
x;
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++)
{
double
blue,
green,
red,
X,
Y,
Z;
X=QuantumScale*GetPixelRed(image,q);
Y=QuantumScale*GetPixelGreen(image,q);
Z=QuantumScale*GetPixelBlue(image,q);
switch (image->colorspace)
{
case Adobe98Colorspace:
{
ConvertAdobe98ToRGB(X,Y,Z,&red,&green,&blue);
break;
}
case CMYColorspace:
{
ConvertCMYToRGB(X,Y,Z,&red,&green,&blue);
break;
}
case DisplayP3Colorspace:
{
ConvertDisplayP3ToRGB(X,Y,Z,&red,&green,&blue);
break;
}
case HCLColorspace:
{
ConvertHCLToRGB(X,Y,Z,&red,&green,&blue);
break;
}
case HCLpColorspace:
{
ConvertHCLpToRGB(X,Y,Z,&red,&green,&blue);
break;
}
case HSBColorspace:
{
ConvertHSBToRGB(X,Y,Z,&red,&green,&blue);
break;
}
case HSIColorspace:
{
ConvertHSIToRGB(X,Y,Z,&red,&green,&blue);
break;
}
case HSLColorspace:
{
ConvertHSLToRGB(X,Y,Z,&red,&green,&blue);
break;
}
case HSVColorspace:
{
ConvertHSVToRGB(X,Y,Z,&red,&green,&blue);
break;
}
case HWBColorspace:
{
ConvertHWBToRGB(X,Y,Z,&red,&green,&blue);
break;
}
case JzazbzColorspace:
{
ConvertJzazbzToRGB(X,Y,Z,white_luminance,&red,&green,&blue);
break;
}
case LabColorspace:
{
ConvertLabToRGB(X,Y,Z,&red,&green,&blue);
break;
}
case LCHColorspace:
case LCHabColorspace:
{
ConvertLCHabToRGB(X,Y,Z,&red,&green,&blue);
break;
}
case LCHuvColorspace:
{
ConvertLCHuvToRGB(X,Y,Z,&red,&green,&blue);
break;
}
case LMSColorspace:
{
ConvertLMSToRGB(X,Y,Z,&red,&green,&blue);
break;
}
case LuvColorspace:
{
ConvertLuvToRGB(X,Y,Z,&red,&green,&blue);
break;
}
case ProPhotoColorspace:
{
ConvertProPhotoToRGB(X,Y,Z,&red,&green,&blue);
break;
}
case xyYColorspace:
{
ConvertxyYToRGB(X,Y,Z,&red,&green,&blue);
break;
}
case XYZColorspace:
{
ConvertXYZToRGB(X,Y,Z,&red,&green,&blue);
break;
}
case YCbCrColorspace:
{
ConvertYCbCrToRGB(X,Y,Z,&red,&green,&blue);
break;
}
case YDbDrColorspace:
{
ConvertYDbDrToRGB(X,Y,Z,&red,&green,&blue);
break;
}
case YIQColorspace:
{
ConvertYIQToRGB(X,Y,Z,&red,&green,&blue);
break;
}
case YPbPrColorspace:
{
ConvertYPbPrToRGB(X,Y,Z,&red,&green,&blue);
break;
}
case YUVColorspace:
{
ConvertYUVToRGB(X,Y,Z,&red,&green,&blue);
break;
}
default:
{
red=QuantumRange*X;
green=QuantumRange*Y;
blue=QuantumRange*Z;
break;
}
}
SetPixelRed(image,ClampToQuantum(red),q);
SetPixelGreen(image,ClampToQuantum(green),q);
SetPixelBlue(image,ClampToQuantum(blue),q);
q+=GetPixelChannels(image);
}
sync=SyncCacheViewAuthenticPixels(image_view,exception);
if (sync == MagickFalse)
status=MagickFalse;
}
image_view=DestroyCacheView(image_view);
if (SetImageColorspace(image,sRGBColorspace,exception) == MagickFalse)
return(MagickFalse);
return(status);
}
case LogColorspace:
{
const char
*value;
double
black,
density,
film_gamma,
gamma,
reference_black,
reference_white;
Quantum
*logmap;
/*
Transform Log to sRGB colorspace.
*/
density=DisplayGamma;
gamma=DisplayGamma;
value=GetImageProperty(image,"gamma",exception);
if (value != (const char *) NULL)
gamma=PerceptibleReciprocal(StringToDouble(value,(char **) NULL));
film_gamma=FilmGamma;
value=GetImageProperty(image,"film-gamma",exception);
if (value != (const char *) NULL)
film_gamma=StringToDouble(value,(char **) NULL);
reference_black=ReferenceBlack;
value=GetImageProperty(image,"reference-black",exception);
if (value != (const char *) NULL)
reference_black=StringToDouble(value,(char **) NULL);
reference_white=ReferenceWhite;
value=GetImageProperty(image,"reference-white",exception);
if (value != (const char *) NULL)
reference_white=StringToDouble(value,(char **) NULL);
logmap=(Quantum *) AcquireQuantumMemory((size_t) MaxMap+1UL,
sizeof(*logmap));
if (logmap == (Quantum *) NULL)
ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
image->filename);
black=pow(10.0,(reference_black-reference_white)*(gamma/density)*0.002/
film_gamma);
for (i=0; i <= (ssize_t) (reference_black*MaxMap/1024.0); i++)
logmap[i]=(Quantum) 0;
for ( ; i < (ssize_t) (reference_white*MaxMap/1024.0); i++)
logmap[i]=ClampToQuantum(QuantumRange/(1.0-black)*
(pow(10.0,(1024.0*i/MaxMap-reference_white)*(gamma/density)*0.002/
film_gamma)-black));
for ( ; i <= (ssize_t) MaxMap; i++)
logmap[i]=QuantumRange;
if (image->storage_class == PseudoClass)
{
if (SyncImage(image,exception) == MagickFalse)
return(MagickFalse);
if (SetImageStorageClass(image,DirectClass,exception) == MagickFalse)
return(MagickFalse);
}
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++)
{
MagickBooleanType
sync;
ssize_t
x;
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=(ssize_t) image->columns; x != 0; x--)
{
double
blue,
green,
red;
red=(double) logmap[ScaleQuantumToMap(GetPixelRed(image,q))];
green=(double) logmap[ScaleQuantumToMap(GetPixelGreen(image,q))];
blue=(double) logmap[ScaleQuantumToMap(GetPixelBlue(image,q))];
SetPixelRed(image,ClampToQuantum(EncodePixelGamma((MagickRealType)
red)),q);
SetPixelGreen(image,ClampToQuantum(EncodePixelGamma((MagickRealType)
green)),q);
SetPixelBlue(image,ClampToQuantum(EncodePixelGamma((MagickRealType)
blue)),q);
q+=GetPixelChannels(image);
}
sync=SyncCacheViewAuthenticPixels(image_view,exception);
if (sync == MagickFalse)
status=MagickFalse;
}
image_view=DestroyCacheView(image_view);
logmap=(Quantum *) RelinquishMagickMemory(logmap);
if (SetImageColorspace(image,sRGBColorspace,exception) == MagickFalse)
return(MagickFalse);
return(status);
}
case RGBColorspace:
case scRGBColorspace:
{
/*
Transform linear RGB to sRGB colorspace.
*/
if (image->storage_class == PseudoClass)
{
if (SyncImage(image,exception) == MagickFalse)
return(MagickFalse);
if (SetImageStorageClass(image,DirectClass,exception) == MagickFalse)
return(MagickFalse);
}
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++)
{
MagickBooleanType
sync;
ssize_t
x;
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=(ssize_t) image->columns; x != 0; x--)
{
double
blue,
green,
red;
red=EncodePixelGamma((MagickRealType) GetPixelRed(image,q));
green=EncodePixelGamma((MagickRealType) GetPixelGreen(image,q));
blue=EncodePixelGamma((MagickRealType) GetPixelBlue(image,q));
SetPixelRed(image,ClampToQuantum(red),q);
SetPixelGreen(image,ClampToQuantum(green),q);
SetPixelBlue(image,ClampToQuantum(blue),q);
q+=GetPixelChannels(image);
}
sync=SyncCacheViewAuthenticPixels(image_view,exception);
if (sync == MagickFalse)
status=MagickFalse;
}
image_view=DestroyCacheView(image_view);
if (SetImageColorspace(image,sRGBColorspace,exception) == MagickFalse)
return(MagickFalse);
return(status);
}
default:
break;
}
/*
Allocate the tables.
*/
x_map=(TransformPacket *) AcquireQuantumMemory((size_t) MaxMap+1UL,
sizeof(*x_map));
y_map=(TransformPacket *) AcquireQuantumMemory((size_t) MaxMap+1UL,
sizeof(*y_map));
z_map=(TransformPacket *) AcquireQuantumMemory((size_t) MaxMap+1UL,
sizeof(*z_map));
if ((x_map == (TransformPacket *) NULL) ||
(y_map == (TransformPacket *) NULL) ||
(z_map == (TransformPacket *) NULL))
{
if (z_map != (TransformPacket *) NULL)
z_map=(TransformPacket *) RelinquishMagickMemory(z_map);
if (y_map != (TransformPacket *) NULL)
y_map=(TransformPacket *) RelinquishMagickMemory(y_map);
if (x_map != (TransformPacket *) NULL)
x_map=(TransformPacket *) RelinquishMagickMemory(x_map);
ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
image->filename);
}
switch (image->colorspace)
{
case OHTAColorspace:
{
/*
Initialize OHTA tables:
I1 = 0.33333*R+0.33334*G+0.33333*B
I2 = 0.50000*R+0.00000*G-0.50000*B
I3 =-0.25000*R+0.50000*G-0.25000*B
R = I1+1.00000*I2-0.66668*I3
G = I1+0.00000*I2+1.33333*I3
B = I1-1.00000*I2-0.66668*I3
I and Q, normally -0.5 through 0.5, must be normalized to the range 0
through QuantumRange.
*/
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static)
#endif
for (i=0; i <= (ssize_t) MaxMap; i++)
{
x_map[i].x=(MagickRealType) (1.0*(double) i);
y_map[i].x=(MagickRealType) (0.5*1.00000*(2.0*(double) i-MaxMap));
z_map[i].x=(MagickRealType) (-0.5*0.66668*(2.0*(double) i-MaxMap));
x_map[i].y=(MagickRealType) (1.0*(double) i);
y_map[i].y=(MagickRealType) (0.5*0.00000*(2.0*(double) i-MaxMap));
z_map[i].y=(MagickRealType) (0.5*1.33333*(2.0*(double) i-MaxMap));
x_map[i].z=(MagickRealType) (1.0*(double) i);
y_map[i].z=(MagickRealType) (-0.5*1.00000*(2.0*(double) i-MaxMap));
z_map[i].z=(MagickRealType) (-0.5*0.66668*(2.0*(double) i-MaxMap));
}
break;
}
case Rec601YCbCrColorspace:
{
/*
Initialize YCbCr tables:
R = Y +1.402000*Cr
G = Y-0.344136*Cb-0.714136*Cr
B = Y+1.772000*Cb
Cb and Cr, normally -0.5 through 0.5, must be normalized to the range 0
through QuantumRange.
*/
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static)
#endif
for (i=0; i <= (ssize_t) MaxMap; i++)
{
x_map[i].x=0.99999999999914679361*(double) i;
y_map[i].x=0.5*(-1.2188941887145875e-06)*(2.00*(double) i-MaxMap);
z_map[i].x=0.5*1.4019995886561440468*(2.00*(double) i-MaxMap);
x_map[i].y=0.99999975910502514331*(double) i;
y_map[i].y=0.5*(-0.34413567816504303521)*(2.00*(double) i-MaxMap);
z_map[i].y=0.5*(-0.71413649331646789076)*(2.00*(double) i-MaxMap);
x_map[i].z=1.00000124040004623180*(double) i;
y_map[i].z=0.5*1.77200006607230409200*(2.00*(double) i-MaxMap);
z_map[i].z=0.5*2.1453384174593273e-06*(2.00*(double) i-MaxMap);
}
break;
}
case Rec709YCbCrColorspace:
{
/*
Initialize YCbCr tables:
R = Y +1.574800*Cr
G = Y-0.187324*Cb-0.468124*Cr
B = Y+1.855600*Cb
Cb and Cr, normally -0.5 through 0.5, must be normalized to the range 0
through QuantumRange.
*/
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static)
#endif
for (i=0; i <= (ssize_t) MaxMap; i++)
{
x_map[i].x=(MagickRealType) (1.0*i);
y_map[i].x=(MagickRealType) (0.5*0.000000*(2.0*i-MaxMap));
z_map[i].x=(MagickRealType) (0.5*1.574800*(2.0*i-MaxMap));
x_map[i].y=(MagickRealType) (1.0*i);
y_map[i].y=(MagickRealType) (0.5*(-0.187324)*(2.0*i-MaxMap));
z_map[i].y=(MagickRealType) (0.5*(-0.468124)*(2.0*i-MaxMap));
x_map[i].z=(MagickRealType) (1.0*i);
y_map[i].z=(MagickRealType) (0.5*1.855600*(2.0*i-MaxMap));
z_map[i].z=(MagickRealType) (0.5*0.000000*(2.0*i-MaxMap));
}
break;
}
case YCCColorspace:
{
/*
Initialize YCC tables:
R = Y +1.340762*C2
G = Y-0.317038*C1-0.682243*C2
B = Y+1.632639*C1
YCC is scaled by 1.3584. C1 zero is 156 and C2 is at 137.
*/
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static)
#endif
for (i=0; i <= (ssize_t) MaxMap; i++)
{
x_map[i].x=(MagickRealType) (1.3584000*(double) i);
y_map[i].x=(MagickRealType) 0.0000000;
z_map[i].x=(MagickRealType) (1.8215000*(1.0*(double) i-(double)
ScaleQuantumToMap(ScaleCharToQuantum(137))));
x_map[i].y=(MagickRealType) (1.3584000*(double) i);
y_map[i].y=(MagickRealType) (-0.4302726*(1.0*(double) i-(double)
ScaleQuantumToMap(ScaleCharToQuantum(156))));
z_map[i].y=(MagickRealType) (-0.9271435*(1.0*(double) i-(double)
ScaleQuantumToMap(ScaleCharToQuantum(137))));
x_map[i].z=(MagickRealType) (1.3584000*(double) i);
y_map[i].z=(MagickRealType) (2.2179000*(1.0*(double) i-(double)
ScaleQuantumToMap(ScaleCharToQuantum(156))));
z_map[i].z=(MagickRealType) 0.0000000;
}
break;
}
default:
{
/*
Linear conversion tables.
*/
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static)
#endif
for (i=0; i <= (ssize_t) MaxMap; i++)
{
x_map[i].x=(MagickRealType) (1.0*(double) i);
y_map[i].x=(MagickRealType) 0.0;
z_map[i].x=(MagickRealType) 0.0;
x_map[i].y=(MagickRealType) 0.0;
y_map[i].y=(MagickRealType) (1.0*(double) i);
z_map[i].y=(MagickRealType) 0.0;
x_map[i].z=(MagickRealType) 0.0;
y_map[i].z=(MagickRealType) 0.0;
z_map[i].z=(MagickRealType) (1.0*(double) i);
}
break;
}
}
/*
Convert to sRGB.
*/
switch (image->storage_class)
{
case DirectClass:
default:
{
/*
Convert DirectClass image.
*/
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++)
{
MagickBooleanType
sync;
PixelInfo
pixel;
ssize_t
x;
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++)
{
size_t
blue,
green,
red;
red=ScaleQuantumToMap(GetPixelRed(image,q));
green=ScaleQuantumToMap(GetPixelGreen(image,q));
blue=ScaleQuantumToMap(GetPixelBlue(image,q));
pixel.red=x_map[red].x+y_map[green].x+z_map[blue].x;
pixel.green=x_map[red].y+y_map[green].y+z_map[blue].y;
pixel.blue=x_map[red].z+y_map[green].z+z_map[blue].z;
if (image->colorspace == YCCColorspace)
{
pixel.red=QuantumRange*YCCMap[RoundToYCC(1024.0*pixel.red/
(double) MaxMap)];
pixel.green=QuantumRange*YCCMap[RoundToYCC(1024.0*pixel.green/
(double) MaxMap)];
pixel.blue=QuantumRange*YCCMap[RoundToYCC(1024.0*pixel.blue/
(double) MaxMap)];
}
else
{
pixel.red=(MagickRealType) ScaleMapToQuantum(pixel.red);
pixel.green=(MagickRealType) ScaleMapToQuantum(pixel.green);
pixel.blue=(MagickRealType) ScaleMapToQuantum(pixel.blue);
}
SetPixelRed(image,ClampToQuantum(pixel.red),q);
SetPixelGreen(image,ClampToQuantum(pixel.green),q);
SetPixelBlue(image,ClampToQuantum(pixel.blue),q);
q+=GetPixelChannels(image);
}
sync=SyncCacheViewAuthenticPixels(image_view,exception);
if (sync == MagickFalse)
status=MagickFalse;
if (image->progress_monitor != (MagickProgressMonitor) NULL)
{
MagickBooleanType
proceed;
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp atomic
#endif
progress++;
proceed=SetImageProgress(image,TransformsRGBImageTag,progress,
image->rows);
if (proceed == MagickFalse)
status=MagickFalse;
}
}
image_view=DestroyCacheView(image_view);
break;
}
case PseudoClass:
{
/*
Convert PseudoClass image.
*/
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static) shared(status) \
magick_number_threads(image,image,image->rows,1)
#endif
for (i=0; i < (ssize_t) image->colors; i++)
{
PixelInfo
pixel;
size_t
blue,
green,
red;
red=ScaleQuantumToMap(ClampToQuantum(image->colormap[i].red));
green=ScaleQuantumToMap(ClampToQuantum(image->colormap[i].green));
blue=ScaleQuantumToMap(ClampToQuantum(image->colormap[i].blue));
pixel.red=x_map[red].x+y_map[green].x+z_map[blue].x;
pixel.green=x_map[red].y+y_map[green].y+z_map[blue].y;
pixel.blue=x_map[red].z+y_map[green].z+z_map[blue].z;
if (image->colorspace == YCCColorspace)
{
pixel.red=QuantumRange*YCCMap[RoundToYCC(1024.0*pixel.red/
(double) MaxMap)];
pixel.green=QuantumRange*YCCMap[RoundToYCC(1024.0*pixel.green/
(double) MaxMap)];
pixel.blue=QuantumRange*YCCMap[RoundToYCC(1024.0*pixel.blue/
(double) MaxMap)];
}
else
{
pixel.red=(MagickRealType) ScaleMapToQuantum(pixel.red);
pixel.green=(MagickRealType) ScaleMapToQuantum(pixel.green);
pixel.blue=(MagickRealType) ScaleMapToQuantum(pixel.blue);
}
image->colormap[i].red=(double) ClampToQuantum(pixel.red);
image->colormap[i].green=(double) ClampToQuantum(pixel.green);
image->colormap[i].blue=(double) ClampToQuantum(pixel.blue);
}
(void) SyncImage(image,exception);
break;
}
}
/*
Relinquish resources.
*/
z_map=(TransformPacket *) RelinquishMagickMemory(z_map);
y_map=(TransformPacket *) RelinquishMagickMemory(y_map);
x_map=(TransformPacket *) RelinquishMagickMemory(x_map);
if (SetImageColorspace(image,sRGBColorspace,exception) == MagickFalse)
return(MagickFalse);
return(MagickTrue);
}
|
c3_fmt.c | /*
* Generic crypt(3) support, as well as support for glibc's crypt_r(3) and
* Solaris' MT-safe crypt(3C) with OpenMP parallelization.
*
* This file is part of John the Ripper password cracker,
* Copyright (c) 2009-2015 by Solar Designer
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted.
*
* There's ABSOLUTELY NO WARRANTY, express or implied.
*/
#if AC_BUILT
#include "autoconfig.h"
#endif
#if HAVE_CRYPT
/* if this comes after the #define crap below, there are often
* problems with strdup or other things not being defined. We
* move this block of includes to above the _XOPEN_* defines
*/
#if STRING_WITH_STRINGS
#include <string.h>
#include <strings.h>
#elif HAVE_STRING_H
#include <string.h>
#elif HAVE_STRINGS_H
#include <strings.h>
#endif
#if !AC_BUILT
#include <string.h>
#ifndef _MSC_VER
#include <strings.h>
#endif
#undef _XOPEN_VERSION
#undef _XOPEN_SOURCE
#undef _XOPEN_SOURCE_EXTENDED
#undef _GNU_SOURCE
#define _XOPEN_SOURCE 4 /* for crypt(3) */
#define _XOPEN_SOURCE_EXTENDED 1 /* for OpenBSD */
#define _XOPEN_VERSION 4
#define _XPG4_2
#define _GNU_SOURCE 1 /* for crypt_r(3) */
#include <stdio.h>
#ifdef __CYGWIN__
#include <crypt.h>
#endif
#if defined(_OPENMP) && defined(__GLIBC__)
#include <crypt.h>
#else
#if (!AC_BUILT || HAVE_UNISTD_H) && !_MSC_VER
#include <unistd.h>
#endif
#endif
#endif
#if (!AC_BUILT && defined(HAVE_CRYPT))
#undef HAVE_CRYPT_H
#define HAVE_CRYPT_H 1
#endif
#if HAVE_CRYPT_H
#include <crypt.h>
#endif
#if (!AC_BUILT || HAVE_UNISTD_H) && !_MSC_VER
#include <unistd.h>
#endif
#if defined(_OPENMP)
#include <omp.h> /* for omp_get_thread_num() */
#endif
#include "options.h"
#include "arch.h"
#include "misc.h"
#include "params.h"
#include "memory.h"
#include "common.h"
#include "formats.h"
#include "loader.h"
#include "john.h"
#ifdef HAVE_MPI
#include "john-mpi.h"
#endif
#include "memdbg.h"
#define FORMAT_LABEL "crypt"
#define FORMAT_NAME "generic crypt(3)"
#define ALGORITHM_NAME "?/" ARCH_BITS_STR
#define BENCHMARK_COMMENT " DES"
#define BENCHMARK_LENGTH 0
#define PLAINTEXT_LENGTH 72
#define BINARY_SIZE 128
#define BINARY_ALIGN 1
#define SALT_SIZE BINARY_SIZE
#define SALT_ALIGN 1
#define MIN_KEYS_PER_CRYPT 96
#define MAX_KEYS_PER_CRYPT 96
static struct fmt_tests tests[] = {
{"CCNf8Sbh3HDfQ", "U*U*U*U*"},
{"CCX.K.MFy4Ois", "U*U***U"},
{"CC4rMpbg9AMZ.", "U*U***U*"},
{"XXxzOu6maQKqQ", "*U*U*U*U"},
{"SDbsugeBiC58A", ""},
{NULL}
};
static char saved_key[MAX_KEYS_PER_CRYPT][PLAINTEXT_LENGTH + 1];
static char saved_salt[SALT_SIZE];
static char crypt_out[MAX_KEYS_PER_CRYPT][BINARY_SIZE];
#if defined(_OPENMP) && defined(__GLIBC__)
#define MAX_THREADS MAX_KEYS_PER_CRYPT
/* We assume that this is zero-initialized (all NULL pointers) */
static struct crypt_data *crypt_data[MAX_THREADS];
#endif
static void init(struct fmt_main *self)
{
if (options.subformat) {
int i;
char *salt = tests[0].ciphertext;
#if defined(_OPENMP) && defined(__GLIBC__)
struct crypt_data data;
data.initialized = 0;
#endif
/*
* Allow
* ./john --list=format-tests --format=crypt --subformat=md5crypt
* in addition to
* ./john --test --format=crypt --subformat=md5crypt
*
* That's why, don't require FLG_TEST_CHK to be set.
*/
if (options.flags & FLG_PASSWD) {
fprintf(stderr,
"\n%s: --subformat option is only for --test or --list=format-tests\n", FORMAT_LABEL);
error();
}
if (!strcmp(options.subformat, "?")) {
fprintf(stderr, "Subformat may either be a verbatim salt, or: descrypt, md5crypt, bcrypt, sha256crypt, sha512crypt, sun-md5\n\n");
error();
} else if (!strcasecmp(options.subformat, "md5crypt") ||
!strcasecmp(options.subformat, "md5")) {
static struct fmt_tests tests[] = {
{"$1$12345678$aIccj83HRDBo6ux1bVx7D1", "0123456789ABCDE"},
{"$1$12345678$f8QoJuo0DpBRfQSD0vglc1", "12345678"},
{"$1$$qRPK7m23GJusamGpoGLby/", ""},
{NULL} };
self->params.tests = tests;
self->params.benchmark_comment = " MD5";
salt = "$1$dXc3I7Rw$";
} else if (!strcasecmp(options.subformat, "sunmd5") ||
!strcasecmp(options.subformat, "sun-md5")) {
static struct fmt_tests tests[] = {
{"$md5$rounds=904$Vc3VgyFx44iS8.Yu$Scf90iLWN6O6mT9TA06NK/", "test"},
{"$md5$rounds=904$ZZZig8GS.S0pRNhc$dw5NMYJoxLlnFq4E.phLy.", "Don41dL33"},
{"$md5$rounds=904$zSuVTn567UJLv14u$q2n2ZBFwKg2tElFBIzUq/0", "J4ck!3Wood"},
{NULL} };
self->params.tests = tests;
self->params.benchmark_comment = " SunMD5";
salt = "$md5$rounds=904$Vc3VgyFx44iS8.Yu$dummy";
} else if ((!strcasecmp(options.subformat, "sha256crypt")) ||
(!strcasecmp(options.subformat, "sha-256")) ||
(!strcasecmp(options.subformat, "sha256"))) {
static struct fmt_tests tests[] = {
{"$5$LKO/Ute40T3FNF95$U0prpBQd4PloSGU0pnpM4z9wKn4vZ1.jsrzQfPqxph9", "U*U*U*U*"},
{"$5$LKO/Ute40T3FNF95$fdgfoJEBoMajNxCv3Ru9LyQ0xZgv0OBMQoq80LQ/Qd.", "U*U***U"},
{"$5$LKO/Ute40T3FNF95$8Ry82xGnnPI/6HtFYnvPBTYgOL23sdMXn8C29aO.x/A", "U*U***U*"},
{NULL} };
self->params.tests = tests;
self->params.benchmark_comment = " SHA-256 rounds=5000";
salt = "$5$LKO/Ute40T3FNF95$";
} else if ((!strcasecmp(options.subformat, "sha512crypt")) ||
(!strcasecmp(options.subformat, "sha-512")) ||
(!strcasecmp(options.subformat, "sha512"))) {
static struct fmt_tests tests[] = {
{"$6$LKO/Ute40T3FNF95$6S/6T2YuOIHY0N3XpLKABJ3soYcXD9mB7uVbtEZDj/LNscVhZoZ9DEH.sBciDrMsHOWOoASbNLTypH/5X26gN0", "U*U*U*U*"},
{"$6$LKO/Ute40T3FNF95$wK80cNqkiAUzFuVGxW6eFe8J.fSVI65MD5yEm8EjYMaJuDrhwe5XXpHDJpwF/kY.afsUs1LlgQAaOapVNbggZ1", "U*U***U"},
{"$6$LKO/Ute40T3FNF95$YS81pp1uhOHTgKLhSMtQCr2cDiUiN03Ud3gyD4ameviK1Zqz.w3oXsMgO6LrqmIEcG3hiqaUqHi/WEE2zrZqa/", "U*U***U*"},
{NULL} };
self->params.tests = tests;
self->params.benchmark_comment = " SHA-512 rounds=5000";
salt = "$6$LKO/Ute40T3FNF95$";
} else if ((!strcasecmp(options.subformat, "bf")) ||
(!strcasecmp(options.subformat, "blowfish")) ||
(!strcasecmp(options.subformat, "bcrypt"))) {
static struct fmt_tests tests[] = {
{"$2a$05$CCCCCCCCCCCCCCCCCCCCC.E5YPO9kmyuRGyh0XouQYb4YMJKvyOeW","U*U"},
{"$2a$05$CCCCCCCCCCCCCCCCCCCCC.VGOzA784oUp/Z0DY336zx7pLYAy0lwK","U*U*"},
{"$2a$05$XXXXXXXXXXXXXXXXXXXXXOAcXxm9kjPGEMsLznoKqmqw7tc8WCx4a","U*U*U"},
{NULL} };
self->params.tests = tests;
self->params.benchmark_comment = " BF x32";
salt = "$2a$05$AD6y0uWY62Xk2TXZ";
} else if (!strcasecmp(options.subformat, "descrypt") ||
!strcasecmp(options.subformat, "des")) {
salt = "CC";
} else {
char *p = mem_alloc_tiny(strlen(options.subformat) + 2,
MEM_ALIGN_NONE);
strcpy(p, " ");
strcat(p, options.subformat);
self->params.benchmark_comment = p;
salt = options.subformat;
/* turn off many salts test, since we are not updating the */
/* params.tests structure data. */
self->params.benchmark_length = -1;
}
for (i = 0; i < 5; i++)
{
char *c;
#if defined(_OPENMP) && defined(__GLIBC__)
c = crypt_r(tests[i].plaintext, salt, &data);
#else
c = crypt(tests[i].plaintext, salt);
#endif
if (c && strlen(c) >= 7)
tests[i].ciphertext = strdup(c);
else {
fprintf(stderr, "%s not supported on this system\n",
options.subformat);
error();
}
}
if (strlen(tests[0].ciphertext) == 13 &&
strcasecmp(options.subformat, "descrypt") &&
strcasecmp(options.subformat, "des")) {
fprintf(stderr, "%s not supported on this system\n",
options.subformat);
error();
}
}
}
static int valid(char *ciphertext, struct fmt_main *self)
{
int length, count_base64, count_base64_2, id, pw_length;
char pw[PLAINTEXT_LENGTH + 1], *new_ciphertext;
/* We assume that these are zero-initialized */
static char sup_length[BINARY_SIZE], sup_id[0x80];
length = count_base64 = count_base64_2 = 0;
while (ciphertext[length]) {
if (atoi64[ARCH_INDEX(ciphertext[length])] != 0x7F) {
count_base64++;
if (length >= 2)
count_base64_2++;
}
length++;
}
if (length < 13 || length >= BINARY_SIZE)
return 0;
id = 0;
if (length == 13 && count_base64 == 13) /* valid salt */
id = 1;
else
if (length == 13 && count_base64_2 == 11) /* invalid salt */
id = 2;
else
if (length >= 13 &&
count_base64_2 >= length - 2 && /* allow for invalid salt */
(length - 2) % 11 == 0)
id = 3;
else
if (length == 20 && count_base64 == 19 && ciphertext[0] == '_')
id = 4;
else
if (ciphertext[0] == '$') {
id = (unsigned char)ciphertext[1];
if (id <= 0x20 || id >= 0x80)
id = 9;
} else
if (ciphertext[0] == '*' || ciphertext[0] == '!') /* likely locked */
id = 10;
/* Previously detected as supported */
if (sup_length[length] > 0 && sup_id[id] > 0)
return 1;
/* Previously detected as unsupported */
if (sup_length[length] < 0 && sup_id[id] < 0)
return 0;
pw_length = ((length - 2) / 11) << 3;
if (pw_length >= sizeof(pw))
pw_length = sizeof(pw) - 1;
memcpy(pw, ciphertext, pw_length); /* reuse the string, why not? */
pw[pw_length] = 0;
#if defined(_OPENMP) && defined(__GLIBC__)
/*
* Let's use crypt_r(3) just like we will in crypt_all() below.
* It is possible that crypt(3) and crypt_r(3) differ in their supported hash
* types on a given system.
*/
{
struct crypt_data **data = &crypt_data[0];
if (!*data) {
/*
* **data is not exactly tiny, but we use mem_alloc_tiny() for its alignment
* support and error checking. We do not need to free() this memory anyway.
*
* The page alignment is to keep different threads' data on different pages.
*/
*data = mem_alloc_tiny(sizeof(**data), MEM_ALIGN_PAGE);
memset(*data, 0, sizeof(**data));
}
new_ciphertext = crypt_r(pw, ciphertext, *data);
}
#else
new_ciphertext = crypt(pw, ciphertext);
#endif
if (new_ciphertext && strlen(new_ciphertext) == length &&
!strncmp(new_ciphertext, ciphertext, 2)) {
sup_length[length] = 1;
sup_id[id] = 1;
return 1;
}
if (id != 10 && !ldr_in_pot)
if (john_main_process)
fprintf(stderr, "Warning: "
"hash encoding string length %d, type id %c%c\n"
"appears to be unsupported on this system; "
"will not load such hashes.\n",
length, id > 0x20 ? '$' : '#', id > 0x20 ? id : '0' + id);
if (!sup_length[length])
sup_length[length] = -1;
if (!sup_id[id])
sup_id[id] = -1;
return 0;
}
static void *binary(char *ciphertext)
{
static char out[BINARY_SIZE];
strncpy(out, ciphertext, sizeof(out)); /* NUL padding is required */
return out;
}
static void *salt(char *ciphertext)
{
static char out[SALT_SIZE];
int cut = sizeof(out);
#if 1
/* This piece is optional, but matching salts are not detected without it */
int length = strlen(ciphertext);
switch (length) {
case 13:
case 24:
cut = 2;
break;
case 20:
if (ciphertext[0] == '_') cut = 9;
break;
case 35:
case 46:
case 57:
if (ciphertext[0] != '$') cut = 2;
/* fall through */
default:
if ((length >= 26 && length <= 34 &&
!strncmp(ciphertext, "$1$", 3)) ||
(length >= 47 && !strncmp(ciphertext, "$5$", 3)) ||
(length >= 90 && !strncmp(ciphertext, "$6$", 3))) {
char *p = strrchr(ciphertext + 3, '$');
if (p) cut = p - ciphertext;
} else
if (length == 59 && !strncmp(ciphertext, "$2$", 3))
cut = 28;
else
if (length == 60 &&
(!strncmp(ciphertext, "$2a$", 4) ||
!strncmp(ciphertext, "$2b$", 4) ||
!strncmp(ciphertext, "$2x$", 4) ||
!strncmp(ciphertext, "$2y$", 4)))
cut = 29;
else
if (length >= 27 &&
(!strncmp(ciphertext, "$md5$", 5) ||
!strncmp(ciphertext, "$md5,", 5))) {
char *p = strrchr(ciphertext + 4, '$');
if (p) {
/* NUL padding is required */
memset(out, 0, sizeof(out));
memcpy(out, ciphertext, ++p - ciphertext);
/*
* Workaround what looks like a bug in sunmd5.c: crypt_genhash_impl() where it
* takes a different substring as salt depending on whether the optional
* existing hash encoding is present after the salt or not. Specifically, the
* last '$' delimiter is included into the salt when there's no existing hash
* encoding after it, but is omitted from the salt otherwise.
*/
out[p - ciphertext] = 'x';
return out;
}
}
}
#endif
/* NUL padding is required */
memset(out, 0, sizeof(out));
memcpy(out, ciphertext, cut);
return out;
}
#define H(s, i) \
((int)(unsigned char)(atoi64[ARCH_INDEX((s)[(i)])] ^ (s)[(i) - 1]))
#define H0(s) \
int i = strlen(s) - 2; \
return i > 0 ? H((s), i) & PH_MASK_0 : 0
#define H1(s) \
int i = strlen(s) - 2; \
return i > 2 ? (H((s), i) ^ (H((s), i - 2) << 4)) & PH_MASK_1 : 0
#define H2(s) \
int i = strlen(s) - 2; \
return i > 2 ? (H((s), i) ^ (H((s), i - 2) << 6)) & PH_MASK_2 : 0
#define H3(s) \
int i = strlen(s) - 2; \
return i > 4 ? (H((s), i) ^ (H((s), i - 2) << 5) ^ \
(H((s), i - 4) << 10)) & PH_MASK_3 : 0
#define H4(s) \
int i = strlen(s) - 2; \
return i > 6 ? (H((s), i) ^ (H((s), i - 2) << 5) ^ \
(H((s), i - 4) << 10) ^ (H((s), i - 6) << 15)) & PH_MASK_4 : 0
static int binary_hash_0(void *binary)
{
H0((char *)binary);
}
static int binary_hash_1(void *binary)
{
H1((char *)binary);
}
static int binary_hash_2(void *binary)
{
H2((char *)binary);
}
static int binary_hash_3(void *binary)
{
H3((char *)binary);
}
static int binary_hash_4(void *binary)
{
H4((char *)binary);
}
static int get_hash_0(int index)
{
H0(crypt_out[index]);
}
static int get_hash_1(int index)
{
H1(crypt_out[index]);
}
static int get_hash_2(int index)
{
H2(crypt_out[index]);
}
static int get_hash_3(int index)
{
H3(crypt_out[index]);
}
static int get_hash_4(int index)
{
H4(crypt_out[index]);
}
static int salt_hash(void *salt)
{
int i, h;
i = strlen((char *)salt) - 1;
if (i > 1) i--;
h = (unsigned char)atoi64[ARCH_INDEX(((char *)salt)[i])];
h ^= ((unsigned char *)salt)[i - 1];
h <<= 6;
h ^= (unsigned char)atoi64[ARCH_INDEX(((char *)salt)[i - 1])];
h ^= ((unsigned char *)salt)[i];
return h & (SALT_HASH_SIZE - 1);
}
static void set_salt(void *salt)
{
strcpy(saved_salt, salt);
}
static void set_key(char *key, int index)
{
strnzcpy(saved_key[index], key, PLAINTEXT_LENGTH + 1);
}
static char *get_key(int index)
{
return saved_key[index];
}
static int crypt_all(int *pcount, struct db_salt *salt)
{
static int warned = 0;
int count = *pcount;
int index;
#if defined(_OPENMP) && defined(__GLIBC__)
#pragma omp parallel for default(none) private(index) shared(warned, count, crypt_out, saved_key, saved_salt, crypt_data, stderr)
for (index = 0; index < count; index++) {
char *hash;
int t = omp_get_thread_num();
if (t < MAX_THREADS) {
struct crypt_data **data = &crypt_data[t];
if (!*data) {
/* Stagger the structs to reduce their competition for the same cache lines */
size_t mask = MEM_ALIGN_PAGE, shift = 0;
while (t) {
mask >>= 1;
if (mask < MEM_ALIGN_CACHE)
break;
if (t & 1)
shift += mask;
t >>= 1;
}
*data = (void *)((char *)
mem_alloc_tiny(sizeof(**data) +
shift, MEM_ALIGN_PAGE) + shift);
memset(*data, 0, sizeof(**data));
}
hash = crypt_r(saved_key[index], saved_salt, *data);
} else { /* should not happen */
struct crypt_data data;
memset(&data, 0, sizeof(data));
hash = crypt_r(saved_key[index], saved_salt, &data);
}
if (!hash) {
#pragma omp critical
if (!warned) {
fprintf(stderr,
"Warning: crypt_r() returned NULL\n");
warned = 1;
}
hash = "";
}
strnzcpy(crypt_out[index], hash, BINARY_SIZE);
}
#else
#if defined(_OPENMP) && defined(__sun)
/*
* crypt(3C) is MT-safe on Solaris. For traditional DES-based hashes, this is
* implemented with locking (hence there's no speedup from the use of multiple
* threads, and the per-thread performance is extremely poor anyway). For
* modern hash types, the function is actually able to compute multiple hashes
* in parallel by different threads (and the performance for some hash types is
* reasonable). Overall, this code is reasonable to use for SHA-crypt and
* SunMD5 hashes, which are not yet supported by non-jumbo John natively.
*/
#pragma omp parallel for /* default(none) private(index) shared(warned, count, crypt_out, saved_key, saved_salt, stderr) or __iob */
#endif
for (index = 0; index < count; index++) {
char *hash = crypt(saved_key[index], saved_salt);
if (!hash) {
#if defined(_OPENMP) && defined(__sun)
#pragma omp critical
#endif
if (!warned) {
fprintf(stderr,
"Warning: crypt() returned NULL\n");
warned = 1;
}
hash = "";
}
strnzcpy(crypt_out[index], hash, BINARY_SIZE);
}
#endif
return count;
}
static int cmp_all(void *binary, int count)
{
int index;
for (index = 0; index < count; index++)
if (!strcmp((char *)binary, crypt_out[index]))
return 1;
return 0;
}
static int cmp_one(void *binary, int index)
{
return !strcmp((char *)binary, crypt_out[index]);
}
static int cmp_exact(char *source, int index)
{
return 1;
}
/*
* For generic crypt(3), the algorithm is returned as the first "tunable cost":
* 0: unknown (shouldn't happen
* 1: descrypt
* 2: md5crypt
* 3: sunmd5
* 4: bcrypt
* 5: sha256crypt
* 6: sha512crypt
* New subformats should be added to the end of the list.
* Otherwise, restored sessions might contine cracking different hashes
* if the (not yet implemented) option --cost= had been used
* when starting that session.
*/
static unsigned int c3_subformat_algorithm(void *salt)
{
char *c3_salt;
c3_salt = salt;
if (!c3_salt[0] || !c3_salt[1] )
return 0;
if (!c3_salt[2])
return 1;
if (c3_salt[0] != '$')
return 0;
if (c3_salt[1] == '1')
return 2;
if (c3_salt[1] == 'm')
return 3;
if (c3_salt[1] == '2' && c3_salt[2] == 'a')
return 4;
if (c3_salt[1] == '5')
return 5;
if (c3_salt[1] == '6')
return 6;
return 0;
}
static unsigned int c3_algorithm_specific_cost1(void *salt)
{
unsigned int algorithm, rounds;
char *c3_salt;
c3_salt = salt;
algorithm = c3_subformat_algorithm(salt);
if(algorithm < 3)
/* no tunable cost parameters */
return 1;
switch (algorithm) {
case 1:
// DES
return 25;
case 2:
// cryptmd5
return 1000;
case 3: // sun_md5
c3_salt = strstr(c3_salt, "rounds=");
if (!c3_salt) {
return 904+4096; // default
}
sscanf(c3_salt, "rounds=%d", &rounds);
return rounds+4096;
case 4: // bf
c3_salt += 4;
sscanf(c3_salt, "%d", &rounds);
return rounds;
case 5:
case 6:
// sha256crypt and sha512crypt handled the same: $x$rounds=xxxx$salt$hash (or $x$salt$hash for 5000 round default);
c3_salt += 3;
if (strncmp(c3_salt, "rounds=", 7))
return 5000; // default
sscanf(c3_salt, "rounds=%d", &rounds);
return rounds;
}
return 1;
}
struct fmt_main fmt_crypt = {
{
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,
{
/*
* use algorithm as first tunable cost:
* (0: unknown)
* descrypt, md5crypt, sunmd5, bcrypt, sha512crypt, sha256crypt
*/
"algorithm [1:descrypt 2:md5crypt 3:sunmd5 4:bcrypt 5:sha256crypt 6:sha512crypt]",
"algorithm specific iterations",
},
tests
}, {
init,
fmt_default_done,
fmt_default_reset,
fmt_default_prepare,
valid,
fmt_default_split,
binary,
salt,
{
c3_subformat_algorithm,
#if 1
c3_algorithm_specific_cost1
#endif
},
fmt_default_source,
{
binary_hash_0,
binary_hash_1,
binary_hash_2,
binary_hash_3,
binary_hash_4,
NULL,
NULL
},
salt_hash,
NULL,
set_salt,
set_key,
get_key,
fmt_default_clear_keys,
crypt_all,
{
get_hash_0,
get_hash_1,
get_hash_2,
get_hash_3,
get_hash_4,
NULL,
NULL
},
cmp_all,
cmp_one,
cmp_exact
}
};
#endif // HAVE_CRYPT
|
GB_binop__ne_int32.c | //------------------------------------------------------------------------------
// GB_binop: hard-coded functions for each built-in binary operator
//------------------------------------------------------------------------------
// SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2020, All Rights Reserved.
// http://suitesparse.com See GraphBLAS/Doc/License.txt for license.
//------------------------------------------------------------------------------
// If this file is in the Generated/ folder, do not edit it (auto-generated).
#include "GB.h"
#ifndef GBCOMPACT
#include "GB_control.h"
#include "GB_ek_slice.h"
#include "GB_dense.h"
#include "GB_mkl.h"
#include "GB_binop__include.h"
// C=binop(A,B) is defined by the following types and operators:
// A+B function (eWiseAdd): GB_AaddB__ne_int32
// A.*B function (eWiseMult): GB_AemultB__ne_int32
// A*D function (colscale): GB_AxD__ne_int32
// D*A function (rowscale): GB_DxB__ne_int32
// C+=B function (dense accum): GB_Cdense_accumB__ne_int32
// C+=b function (dense accum): GB_Cdense_accumb__ne_int32
// C+=A+B function (dense ewise3): (none)
// C=A+B function (dense ewise3): GB_Cdense_ewise3_noaccum__ne_int32
// C=scalar+B GB_bind1st__ne_int32
// C=scalar+B' GB_bind1st_tran__ne_int32
// C=A+scalar GB_bind2nd__ne_int32
// C=A'+scalar GB_bind2nd_tran__ne_int32
// C type: bool
// A type: int32_t
// B,b type: int32_t
// BinaryOp: cij = (aij != bij)
#define GB_ATYPE \
int32_t
#define GB_BTYPE \
int32_t
#define GB_CTYPE \
bool
// true if the types of A and B are identical
#define GB_ATYPE_IS_BTYPE \
1
// true if the types of C and A are identical
#define GB_CTYPE_IS_ATYPE \
0
// true if the types of C and B are identical
#define GB_CTYPE_IS_BTYPE \
0
// aij = Ax [pA]
#define GB_GETA(aij,Ax,pA) \
int32_t aij = Ax [pA]
// bij = Bx [pB]
#define GB_GETB(bij,Bx,pB) \
int32_t bij = Bx [pB]
// declare scalar of the same type as C
#define GB_CTYPE_SCALAR(t) \
bool t
// cij = Ax [pA]
#define GB_COPY_A_TO_C(cij,Ax,pA) \
cij = Ax [pA]
// cij = Bx [pB]
#define GB_COPY_B_TO_C(cij,Bx,pB) \
cij = Bx [pB]
#define GB_CX(p) Cx [p]
// binary operator
#define GB_BINOP(z, x, y) \
z = (x != y) ;
// op is second
#define GB_OP_IS_SECOND \
0
// op is plus_fp32 or plus_fp64
#define GB_OP_IS_PLUS_REAL \
0
// op is minus_fp32 or minus_fp64
#define GB_OP_IS_MINUS_REAL \
0
// GB_cblas_*axpy gateway routine, if it exists for this operator and type:
#define GB_CBLAS_AXPY \
(none)
// do the numerical phases of GB_add and GB_emult
#define GB_PHASE_2_OF_2
// hard-coded loops can be vectorized
#define GB_PRAGMA_SIMD_VECTORIZE GB_PRAGMA_SIMD
// disable this operator and use the generic case if these conditions hold
#define GB_DISABLE \
(GxB_NO_NE || GxB_NO_INT32 || GxB_NO_NE_INT32)
//------------------------------------------------------------------------------
// 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__ne_int32
(
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__ne_int32
(
GrB_Matrix C,
const GrB_Matrix B,
const int64_t *GB_RESTRICT kfirst_slice,
const int64_t *GB_RESTRICT klast_slice,
const int64_t *GB_RESTRICT pstart_slice,
const int ntasks,
const int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
#if 0
{
#include "GB_dense_subassign_23_template.c"
}
#endif
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// C += b, accumulate a scalar into a dense matrix
//------------------------------------------------------------------------------
GrB_Info GB_Cdense_accumb__ne_int32
(
GrB_Matrix C,
const GB_void *p_bwork,
const int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
#if 0
{
// get the scalar b for C += b, of type int32_t
int32_t bwork = (*((int32_t *) p_bwork)) ;
#include "GB_dense_subassign_22_template.c"
return (GrB_SUCCESS) ;
}
#endif
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// C = A*D, column scale with diagonal D matrix
//------------------------------------------------------------------------------
GrB_Info GB_AxD__ne_int32
(
GrB_Matrix C,
const GrB_Matrix A, bool A_is_pattern,
const GrB_Matrix D, bool D_is_pattern,
const int64_t *GB_RESTRICT kfirst_slice,
const int64_t *GB_RESTRICT klast_slice,
const int64_t *GB_RESTRICT pstart_slice,
const int ntasks,
const int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
bool *GB_RESTRICT Cx = (bool *) C->x ;
#include "GB_AxB_colscale_meta.c"
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// C = D*B, row scale with diagonal D matrix
//------------------------------------------------------------------------------
GrB_Info GB_DxB__ne_int32
(
GrB_Matrix C,
const GrB_Matrix D, bool D_is_pattern,
const GrB_Matrix B, bool B_is_pattern,
int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
bool *GB_RESTRICT Cx = (bool *) C->x ;
#include "GB_AxB_rowscale_meta.c"
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// eWiseAdd: C = A+B or C<M> = A+B
//------------------------------------------------------------------------------
GrB_Info GB_AaddB__ne_int32
(
GrB_Matrix C,
const GrB_Matrix M,
const bool Mask_struct,
const GrB_Matrix A,
const GrB_Matrix B,
const bool Ch_is_Mh,
const int64_t *GB_RESTRICT C_to_M,
const int64_t *GB_RESTRICT C_to_A,
const int64_t *GB_RESTRICT C_to_B,
const GB_task_struct *GB_RESTRICT TaskList,
const int ntasks,
const int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
#include "GB_add_template.c"
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// eWiseMult: C = A.*B or C<M> = A.*B
//------------------------------------------------------------------------------
GrB_Info GB_AemultB__ne_int32
(
GrB_Matrix C,
const GrB_Matrix M,
const bool Mask_struct,
const GrB_Matrix A,
const GrB_Matrix B,
const int64_t *GB_RESTRICT C_to_M,
const int64_t *GB_RESTRICT C_to_A,
const int64_t *GB_RESTRICT C_to_B,
const GB_task_struct *GB_RESTRICT TaskList,
const int ntasks,
const int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
#include "GB_emult_template.c"
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// Cx = op (x,Bx): apply a binary operator to a matrix with scalar bind1st
//------------------------------------------------------------------------------
GrB_Info GB_bind1st__ne_int32
(
GB_void *Cx_output, // Cx and Bx may be aliased
const GB_void *x_input,
const GB_void *Bx_input,
int64_t anz,
int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
bool *Cx = (bool *) 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 < anz ; p++)
{
int32_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__ne_int32
(
GB_void *Cx_output, // Cx and Ax may be aliased
const GB_void *Ax_input,
const GB_void *y_input,
int64_t anz,
int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
int64_t p ;
bool *Cx = (bool *) 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++)
{
int32_t aij = Ax [p] ;
Cx [p] = (aij != y) ;
}
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// C = op (x, A'): transpose and apply a binary operator
//------------------------------------------------------------------------------
// cij = op (x, aij), no typcasting (in spite of the macro name)
#undef GB_CAST_OP
#define GB_CAST_OP(pC,pA) \
{ \
int32_t aij = Ax [pA] ; \
Cx [pC] = (x != aij) ; \
}
GrB_Info GB_bind1st_tran__ne_int32
(
GrB_Matrix C,
const GB_void *x_input,
const GrB_Matrix A,
int64_t *GB_RESTRICT *Rowcounts,
GBI_single_iterator Iter,
const int64_t *GB_RESTRICT A_slice,
int naslice
)
{
// GB_unop_transpose.c uses GB_ATYPE, but A is
// the 2nd input to binary operator z=f(x,y).
#undef GB_ATYPE
#define GB_ATYPE \
int32_t
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
int32_t x = (*((const int32_t *) x_input)) ;
#define GB_PHASE_2_OF_2
#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 typcasting (in spite of the macro name)
#undef GB_CAST_OP
#define GB_CAST_OP(pC,pA) \
{ \
int32_t aij = Ax [pA] ; \
Cx [pC] = (aij != y) ; \
}
GrB_Info GB_bind2nd_tran__ne_int32
(
GrB_Matrix C,
const GrB_Matrix A,
const GB_void *y_input,
int64_t *GB_RESTRICT *Rowcounts,
GBI_single_iterator Iter,
const int64_t *GB_RESTRICT A_slice,
int naslice
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
int32_t y = (*((const int32_t *) y_input)) ;
#define GB_PHASE_2_OF_2
#include "GB_unop_transpose.c"
return (GrB_SUCCESS) ;
#endif
}
#endif
|
GB_binop__lxor_fp64.c |
//------------------------------------------------------------------------------
// GB_binop: hard-coded functions for each built-in binary operator
//------------------------------------------------------------------------------
// SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2021, All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
//------------------------------------------------------------------------------
// If this file is in the Generated2/ folder, do not edit it
// (it is auto-generated from Generator/*).
#include "GB.h"
#ifndef GBCOMPACT
#include "GB_emult.h"
#include "GB_control.h"
#include "GB_ek_slice.h"
#include "GB_dense.h"
#include "GB_atomics.h"
#include "GB_bitmap_assign_methods.h"
#include "GB_binop__include.h"
// C=binop(A,B) is defined by the following types and operators:
// A+B function (eWiseAdd): GB (_AaddB__lxor_fp64)
// A.*B function (eWiseMult): GB (_AemultB_08__lxor_fp64)
// A.*B function (eWiseMult): GB (_AemultB_02__lxor_fp64)
// A.*B function (eWiseMult): GB (_AemultB_04__lxor_fp64)
// A.*B function (eWiseMult): GB (_AemultB_bitmap__lxor_fp64)
// A*D function (colscale): GB (_AxD__lxor_fp64)
// D*A function (rowscale): GB (_DxB__lxor_fp64)
// C+=B function (dense accum): GB (_Cdense_accumB__lxor_fp64)
// C+=b function (dense accum): GB (_Cdense_accumb__lxor_fp64)
// C+=A+B function (dense ewise3): GB ((none))
// C=A+B function (dense ewise3): GB (_Cdense_ewise3_noaccum__lxor_fp64)
// C=scalar+B GB (_bind1st__lxor_fp64)
// C=scalar+B' GB (_bind1st_tran__lxor_fp64)
// C=A+scalar GB (_bind2nd__lxor_fp64)
// C=A'+scalar GB (_bind2nd_tran__lxor_fp64)
// C type: double
// A type: double
// A pattern? 0
// B type: double
// B pattern? 0
// BinaryOp: cij = ((aij != 0) != (bij != 0))
#define GB_ATYPE \
double
#define GB_BTYPE \
double
#define GB_CTYPE \
double
// true if the types of A and B are identical
#define GB_ATYPE_IS_BTYPE \
1
// true if the types of C and A are identical
#define GB_CTYPE_IS_ATYPE \
1
// true if the types of C and B are identical
#define GB_CTYPE_IS_BTYPE \
1
// aij = Ax [pA]
#define GB_GETA(aij,Ax,pA,A_iso) \
double aij = GBX (Ax, pA, A_iso)
// 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) \
double 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) \
double t
// cij = Ax [pA]
#define GB_COPY_A_TO_C(cij,Ax,pA,A_iso) \
cij = GBX (Ax, pA, A_iso)
// cij = Bx [pB]
#define GB_COPY_B_TO_C(cij,Bx,pB,B_iso) \
cij = GBX (Bx, pB, B_iso)
#define GB_CX(p) Cx [p]
// binary operator
#define GB_BINOP(z,x,y,i,j) \
z = ((x != 0) != (y != 0)) ;
// true if the binop must be flipped
#define GB_BINOP_FLIP \
0
// op is second
#define GB_OP_IS_SECOND \
0
// do the numerical phases of GB_add and GB_emult
#define GB_PHASE_2_OF_2
// hard-coded loops can be vectorized
#define GB_PRAGMA_SIMD_VECTORIZE GB_PRAGMA_SIMD
// disable this operator and use the generic case if these conditions hold
#define GB_DISABLE \
(GxB_NO_LXOR || GxB_NO_FP64 || GxB_NO_LXOR_FP64)
//------------------------------------------------------------------------------
// C += A+B, all 3 matrices dense
//------------------------------------------------------------------------------
#if 0
// The op must be MIN, MAX, PLUS, MINUS, RMINUS, TIMES, DIV, or RDIV.
void GB ((none))
(
GrB_Matrix C,
const GrB_Matrix A,
const GrB_Matrix B,
const int nthreads
)
{
#include "GB_dense_ewise3_accum_template.c"
}
#endif
//------------------------------------------------------------------------------
// C = A+B, all 3 matrices dense
//------------------------------------------------------------------------------
void GB (_Cdense_ewise3_noaccum__lxor_fp64)
(
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__lxor_fp64)
(
GrB_Matrix C,
const GrB_Matrix B,
const int64_t *B_ek_slicing, const int B_ntasks, const int B_nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
{
#include "GB_dense_subassign_23_template.c"
}
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// C += b, accumulate a scalar into a dense matrix
//------------------------------------------------------------------------------
GrB_Info GB (_Cdense_accumb__lxor_fp64)
(
GrB_Matrix C,
const GB_void *p_bwork,
const int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
{
// get the scalar b for C += b, of type double
double bwork = (*((double *) p_bwork)) ;
#include "GB_dense_subassign_22_template.c"
return (GrB_SUCCESS) ;
}
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// C = A*D, column scale with diagonal D matrix
//------------------------------------------------------------------------------
GrB_Info GB (_AxD__lxor_fp64)
(
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
double *restrict Cx = (double *) 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__lxor_fp64)
(
GrB_Matrix C,
const GrB_Matrix D,
const GrB_Matrix B,
int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
double *restrict Cx = (double *) C->x ;
#include "GB_AxB_rowscale_template.c"
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// eWiseAdd: C=A+B, C<M>=A+B, C<!M>=A+B
//------------------------------------------------------------------------------
GrB_Info GB (_AaddB__lxor_fp64)
(
GrB_Matrix C,
const int C_sparsity,
const GrB_Matrix M,
const bool Mask_struct,
const bool Mask_comp,
const GrB_Matrix A,
const GrB_Matrix B,
const bool 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) ;
double alpha_scalar ;
double beta_scalar ;
if (is_eWiseUnion)
{
alpha_scalar = (*((double *) alpha_scalar_in)) ;
beta_scalar = (*((double *) 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__lxor_fp64)
(
GrB_Matrix C,
const int C_sparsity,
const int ewise_method,
const GrB_Matrix M,
const bool Mask_struct,
const bool Mask_comp,
const GrB_Matrix A,
const GrB_Matrix B,
const int64_t *restrict C_to_M,
const int64_t *restrict C_to_A,
const int64_t *restrict C_to_B,
const GB_task_struct *restrict TaskList,
const int C_ntasks,
const int C_nthreads,
GB_Context Context
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
#include "GB_emult_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__lxor_fp64)
(
GrB_Matrix C,
const GrB_Matrix M,
const bool Mask_struct,
const bool Mask_comp,
const GrB_Matrix A,
const GrB_Matrix B,
const bool flipxy,
const int64_t *restrict Cp_kfirst,
const int64_t *A_ek_slicing, const int A_ntasks, const int A_nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
#if GB_BINOP_FLIP
// The operator is not commutative, and does not have a flipped
// variant. For example z=atan2(y,x).
if (flipxy)
{
// use fmult(y,x)
#undef GB_FLIPPED
#define GB_FLIPPED 1
#include "GB_emult_02_template.c"
}
else
{
// use fmult(x,y)
#undef GB_FLIPPED
#define GB_FLIPPED 0
#include "GB_emult_02_template.c"
}
#else
// No need to handle the flip: the operator is either commutative, or
// has been handled by changing z=div(y,x) to z=rdiv(x,y) for example.
#undef GB_FLIPPED
#define GB_FLIPPED 0
#include "GB_emult_02_template.c"
#endif
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// eWiseMult: C<M> = A.*B, M sparse/hyper, A and B bitmap/full
//------------------------------------------------------------------------------
GrB_Info GB (_AemultB_04__lxor_fp64)
(
GrB_Matrix C,
const GrB_Matrix M,
const bool Mask_struct,
const GrB_Matrix A,
const GrB_Matrix B,
const int64_t *restrict Cp_kfirst,
const int64_t *M_ek_slicing, const int M_ntasks, const int M_nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
#include "GB_emult_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__lxor_fp64)
(
GrB_Matrix C,
const int ewise_method,
const GrB_Matrix M,
const bool Mask_struct,
const bool Mask_comp,
const GrB_Matrix A,
const GrB_Matrix B,
const int64_t *M_ek_slicing, const int M_ntasks, const int M_nthreads,
const int C_nthreads,
GB_Context Context
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
#include "GB_bitmap_emult_template.c"
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// Cx = op (x,Bx): apply a binary operator to a matrix with scalar bind1st
//------------------------------------------------------------------------------
GrB_Info GB (_bind1st__lxor_fp64)
(
GB_void *Cx_output, // Cx and Bx may be aliased
const GB_void *x_input,
const GB_void *Bx_input,
const int8_t *restrict Bb,
int64_t bnz,
int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
double *Cx = (double *) Cx_output ;
double x = (*((double *) x_input)) ;
double *Bx = (double *) Bx_input ;
int64_t p ;
#pragma omp parallel for num_threads(nthreads) schedule(static)
for (p = 0 ; p < bnz ; p++)
{
if (!GBB (Bb, p)) continue ;
double bij = GBX (Bx, p, false) ;
Cx [p] = ((x != 0) != (bij != 0)) ;
}
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// Cx = op (Ax,y): apply a binary operator to a matrix with scalar bind2nd
//------------------------------------------------------------------------------
GrB_Info GB (_bind2nd__lxor_fp64)
(
GB_void *Cx_output, // Cx and Ax may be aliased
const GB_void *Ax_input,
const GB_void *y_input,
const int8_t *restrict Ab,
int64_t anz,
int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
int64_t p ;
double *Cx = (double *) Cx_output ;
double *Ax = (double *) Ax_input ;
double y = (*((double *) y_input)) ;
#pragma omp parallel for num_threads(nthreads) schedule(static)
for (p = 0 ; p < anz ; p++)
{
if (!GBB (Ab, p)) continue ;
double aij = GBX (Ax, p, false) ;
Cx [p] = ((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) \
{ \
double aij = GBX (Ax, pA, false) ; \
Cx [pC] = ((x != 0) != (aij != 0)) ; \
}
GrB_Info GB (_bind1st_tran__lxor_fp64)
(
GrB_Matrix C,
const GB_void *x_input,
const GrB_Matrix A,
int64_t *restrict *Workspaces,
const int64_t *restrict A_slice,
int nworkspaces,
int nthreads
)
{
// GB_unop_transpose.c uses GB_ATYPE, but A is
// the 2nd input to binary operator z=f(x,y).
#undef GB_ATYPE
#define GB_ATYPE \
double
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
double x = (*((const double *) x_input)) ;
#include "GB_unop_transpose.c"
return (GrB_SUCCESS) ;
#endif
#undef GB_ATYPE
#define GB_ATYPE \
double
}
//------------------------------------------------------------------------------
// C = op (A', y): transpose and apply a binary operator
//------------------------------------------------------------------------------
// cij = op (aij, y), no typecasting (in spite of the macro name)
#undef GB_CAST_OP
#define GB_CAST_OP(pC,pA) \
{ \
double aij = GBX (Ax, pA, false) ; \
Cx [pC] = ((aij != 0) != (y != 0)) ; \
}
GrB_Info GB (_bind2nd_tran__lxor_fp64)
(
GrB_Matrix C,
const GrB_Matrix A,
const GB_void *y_input,
int64_t *restrict *Workspaces,
const int64_t *restrict A_slice,
int nworkspaces,
int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
double y = (*((const double *) y_input)) ;
#include "GB_unop_transpose.c"
return (GrB_SUCCESS) ;
#endif
}
#endif
|
GB_selector.c | //------------------------------------------------------------------------------
// GB_selector: select entries from a matrix
//------------------------------------------------------------------------------
// SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2022, All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
//------------------------------------------------------------------------------
// GB_selector does the work for GB_select and the GxB_*select methods. It
// also deletes zombies for GB_wait using the NONZOMBIE operator, and deletes
// entries outside a smaller matrix for GxB_*resize.
// TODO: GB_selector does not exploit the mask.
// If C is NULL on input, A is modified in-place.
// Otherwise, C is an uninitialized static header.
#include "GB_select.h"
#include "GB_ek_slice.h"
#include "GB_sel__include.h"
#include "GB_scalar.h"
#include "GB_transpose.h"
#define GB_FREE_WORKSPACE \
{ \
GB_FREE_WORK (&Zp, Zp_size) ; \
GB_WERK_POP (Work, int64_t) ; \
GB_WERK_POP (A_ek_slicing, int64_t) ; \
GB_FREE (&Cp, Cp_size) ; \
GB_FREE (&Ch, Ch_size) ; \
GB_FREE (&Ci, Ci_size) ; \
GB_FREE (&Cx, Cx_size) ; \
}
#define GB_FREE_ALL \
{ \
GB_phbix_free (C) ; \
GB_FREE_WORKSPACE ; \
}
GrB_Info GB_selector
(
GrB_Matrix C, // output matrix, NULL or static header
GB_Opcode opcode, // selector opcode
const GB_Operator op, // user operator, NULL for resize/nonzombie
const bool flipij, // if true, flip i and j for user operator
GrB_Matrix A, // input matrix
int64_t ithunk, // (int64_t) Thunk, if Thunk is NULL
const GrB_Scalar Thunk, // optional input for select operator
GB_Context Context
)
{
//--------------------------------------------------------------------------
// check inputs
//--------------------------------------------------------------------------
GrB_Info info ;
ASSERT_OP_OK_OR_NULL (op, "selectop/idxunop for GB_selector", GB0) ;
ASSERT_SCALAR_OK_OR_NULL (Thunk, "Thunk for GB_selector", GB0) ;
ASSERT (GB_IS_SELECTOP_CODE (opcode) || GB_IS_INDEXUNARYOP_CODE (opcode)) ;
ASSERT_MATRIX_OK (A, "A input for GB_selector", GB_FLIP (GB0)) ;
// positional selector (tril, triu, diag, offdiag, resize, rowindex, ...):
// can't be jumbled. nonzombie, entry-valued op, user op: jumbled OK
ASSERT (GB_IMPLIES (GB_OPCODE_IS_POSITIONAL (opcode), !GB_JUMBLED (A))) ;
ASSERT (C == NULL || (C != NULL && C->static_header)) ;
//--------------------------------------------------------------------------
// declare workspace
//--------------------------------------------------------------------------
bool in_place_A = (C == NULL) ; // GrB_wait and GB_resize only
int64_t *restrict Zp = NULL ; size_t Zp_size = 0 ;
GB_WERK_DECLARE (Work, int64_t) ;
int64_t *restrict Wfirst = NULL ;
int64_t *restrict Wlast = NULL ;
int64_t *restrict Cp_kfirst = NULL ;
GB_WERK_DECLARE (A_ek_slicing, int64_t) ;
int64_t avlen = A->vlen ;
int64_t avdim = A->vdim ;
const bool A_iso = A->iso ;
int64_t *restrict Cp = NULL ; size_t Cp_size = 0 ;
int64_t *restrict Ch = NULL ; size_t Ch_size = 0 ;
int64_t *restrict Ci = NULL ; size_t Ci_size = 0 ;
GB_void *restrict Cx = NULL ; size_t Cx_size = 0 ;
//--------------------------------------------------------------------------
// get Thunk
//--------------------------------------------------------------------------
// The scalar value of Thunk has already been typecasted to an integer
// (int64_t ithunk).
// It is also now typecast to the same type as A (to the scalar athunk)
// which is required for GxB_SelectOps, and to the op->ytype (the scalar
// ythunk) for GrB_IndexUnaryOps.
// If Thunk is NULL, or has no entry, it is treated as a scalar value
// of zero.
const size_t asize = A->type->size ;
const GB_Type_code acode = A->type->code ;
GrB_Type ytype = NULL, xtype = NULL ;
GB_Type_code ycode = GB_ignore_code, xcode = GB_ignore_code ;
size_t ysize = 1, xsize = 1 ;
if (op != NULL)
{
if (op->ytype != NULL)
{
// get the type of the thunk input of the operator
ytype = op->ytype ;
ycode = ytype->code ;
ysize = ytype->size ;
}
if (op->xtype != NULL)
{
// get the type of the A input of the operator
xtype = op->xtype ;
xcode = xtype->code ;
xsize = xtype->size ;
}
}
// athunk = (A->type) Thunk, for selectop thunk comparators only
GB_void athunk [GB_VLA(asize)] ;
memset (athunk, 0, asize) ;
// ythunk = (op->ytype) Thunk, for idxnunop
GB_void ythunk [GB_VLA(ysize)] ;
memset (ythunk, 0, ysize) ;
bool op_is_selectop = GB_IS_SELECTOP_CODE (opcode) ;
bool op_is_idxunop = GB_IS_INDEXUNARYOP_CODE (opcode) ;
bool op_is_positional = GB_OPCODE_IS_POSITIONAL (opcode) ;
if (Thunk != NULL)
{
// Thunk is passed to GB_selector only if it is non-empty
ASSERT (GB_nnz ((GrB_Matrix) Thunk) > 0) ;
const GB_Type_code tcode = Thunk->type->code ;
if (op_is_selectop && opcode != GB_USER_selop_code)
{
// athunk = (atype) Thunk, for built-in GxB_SelectOps only
GB_cast_scalar (athunk, acode, Thunk->x, tcode, asize) ;
}
if (ytype != NULL)
{
// ythunk = (op->ytype) Thunk
GB_cast_scalar (ythunk, ycode, Thunk->x, tcode, ysize) ;
}
}
//--------------------------------------------------------------------------
// handle iso case for built-in select ops that depend only on the value
//--------------------------------------------------------------------------
bool op_is_select_valued =
opcode >= GB_NONZERO_selop_code && opcode <= GB_LE_THUNK_selop_code ;
bool op_is_idxunop_valued =
opcode >= GB_VALUENE_idxunop_code && opcode <= GB_VALUELE_idxunop_code ;
if (A_iso && (op_is_select_valued || op_is_idxunop_valued))
{
// select op is NONZERO, EQ_ZERO, GT_ZERO, GE_ZERO, LT_ZERO, LE_ZERO,
// EQ_THUNK, GT_THUNK, GE_THUNK, LT_THUNK, or LE_THUNK, or the idxunop
// VALUE* operators. All of these select/idxunop ops depend only on
// the value of A(i,j). Since A is iso, either all entries in A will
// be copied to C and thus C can be created as a shallow copy of A, or
// no entries from A will be copied to C and thus C is an empty matrix.
// The select factory is not needed, except to check the iso value via
// GB_bitmap_selector.
ASSERT (!in_place_A) ;
ASSERT (C != NULL && C->static_header) ;
// construct a scalar containing the iso scalar of A
// xscalar = (op->xtype) A->x for idxunops
GB_void xscalar [GB_VLA(xsize)] ;
memset (xscalar, 0, xsize) ;
struct GB_Scalar_opaque S_header ;
GrB_Scalar S ;
if (op_is_select_valued)
{
// wrap the iso-value of A in the scalar S, with no typecasting
S = GB_Scalar_wrap (&S_header, A->type, A->x) ;
}
else
{
// wrap the iso-value of A in the scalar S, typecasted to xtype
// xscalar = (op->xtype) A->x
GB_cast_scalar (xscalar, xcode, A->x, acode, asize) ;
S = GB_Scalar_wrap (&S_header, xtype, xscalar) ;
}
S->iso = false ; // but ensure S is not iso
ASSERT_SCALAR_OK (S, "iso scalar wrap", GB0) ;
// apply the select operator to the iso scalar S
GB_OK (GB_bitmap_selector (C, false, opcode, op, false,
(GrB_Matrix) S, ithunk, athunk, ythunk, Context)) ;
ASSERT_MATRIX_OK (C, "C from iso scalar test", GB0) ;
bool C_empty = (GB_nnz (C) == 0) ;
GB_phbix_free (C) ;
// check if C has 0 or 1 entry
if (C_empty)
{
// C is an empty matrix
return (GB_new (&C, true, // static header
A->type, avlen, avdim, GB_Ap_calloc, true,
GxB_SPARSE + GxB_HYPERSPARSE, GB_Global_hyper_switch_get ( ),
1, Context)) ;
}
else
{
// C is a shallow copy of A with all the same entries as A
// set C->iso = A->iso OK
return (GB_shallow_copy (C, true, A, Context)) ;
}
}
// now if A is iso, the following operators still need to be handled:
// GB_TRIL_selop_code : use GB_sel__tril_iso
// GB_TRIU_selop_code : use GB_sel__triu_iso
// GB_DIAG_selop_code : use GB_sel__diag_iso
// GB_OFFDIAG_selop_code : use GB_sel__offdiag_iso
// GB_NONZOMBIE_selop_code : use GB_sel__nonzombie_iso
// GB_USER_selop_code : use GB_sel__user_iso
// GB_ROWINDEX_idxunop_code : use GB_sel__rowindex_iso
// GB_ROWLE_idxunop_code : use GB_sel__rowle_iso
// GB_ROWGT_idxunop_code : use GB_sel__rowle_iso
// all other idxunop : use GB_sel__idxunop_iso
// column selectors are handled below:
// GB_COLINDEX_idxunop_code :
// GB_COLLE_idxunop_code :
// GB_COLGT_idxunop_code :
// Except for GB_USER_selop_code and idxunop, the GB_sel__*_iso methods do
// not access the values of A and C, just the pattern.
//--------------------------------------------------------------------------
// handle the bitmap/as-if-full case
//--------------------------------------------------------------------------
bool use_bitmap_selector ;
if (opcode == GB_NONZOMBIE_selop_code || in_place_A)
{
// GB_bitmap_selector does not support the nonzombie opcode, nor does
// it support operating on A in place. For the NONZOMBIE operator, A
// will never be bitmap.
use_bitmap_selector = false ;
}
else if (opcode == GB_DIAG_selop_code)
{
// GB_bitmap_selector supports the DIAG operator, but it is currently
// not efficient (GB_bitmap_selector should return a sparse diagonal
// matrix, not bitmap). So use the sparse case if A is not bitmap,
// since the sparse case below does not support the bitmap case.
use_bitmap_selector = GB_IS_BITMAP (A) ;
}
else
{
// For bitmap, full, or as-if-full matrices (sparse/hypersparse with
// all entries present, not jumbled, no zombies, and no pending
// tuples), use the bitmap selector for all other operators (TRIL,
// TRIU, OFFDIAG, NONZERO, EQ*, GT*, GE*, LT*, LE*, and user-defined
// operators).
use_bitmap_selector = GB_IS_BITMAP (A) || GB_as_if_full (A) ;
}
//--------------------------------------------------------------------------
// determine if C is iso for a non-iso A
//--------------------------------------------------------------------------
bool C_iso = A_iso || // C iso value is Ax [0]
(opcode == GB_EQ_ZERO_selop_code) || // C iso value is zero
(opcode == GB_EQ_THUNK_selop_code) || // C iso value is thunk
(opcode == GB_NONZERO_selop_code &&
acode == GB_BOOL_code) ; // C iso value is true
if (C_iso)
{
GB_BURBLE_MATRIX (A, "(iso select) ") ;
}
//==========================================================================
// bitmap/full case
//==========================================================================
if (use_bitmap_selector)
{
GB_BURBLE_MATRIX (A, "(bitmap select) ") ;
ASSERT (C != NULL && C->static_header) ;
return (GB_bitmap_selector (C, C_iso, opcode, op,
flipij, A, ithunk, athunk, ythunk, Context)) ;
}
//==========================================================================
// sparse/hypersparse case
//==========================================================================
//--------------------------------------------------------------------------
// determine the max number of threads to use
//--------------------------------------------------------------------------
GB_GET_NTHREADS_MAX (nthreads_max, chunk, Context) ;
//--------------------------------------------------------------------------
// get A: sparse, hypersparse, or full
//--------------------------------------------------------------------------
// the case when A is bitmap is always handled above by GB_bitmap_selector
ASSERT (!GB_IS_BITMAP (A)) ;
int64_t *restrict Ap = A->p ; size_t Ap_size = A->p_size ;
int64_t *restrict Ah = A->h ;
int64_t *restrict Ai = A->i ; size_t Ai_size = A->i_size ;
GB_void *restrict Ax = (GB_void *) A->x ; size_t Ax_size = A->x_size ;
int64_t anvec = A->nvec ;
bool A_jumbled = A->jumbled ;
bool A_is_hyper = (Ah != NULL) ;
//==========================================================================
// column selector
//==========================================================================
// The column selectors can be done in a single pass.
if (opcode == GB_COLINDEX_idxunop_code ||
opcode == GB_COLLE_idxunop_code ||
opcode == GB_COLGT_idxunop_code)
{
//----------------------------------------------------------------------
// find column j in A
//----------------------------------------------------------------------
ASSERT_MATRIX_OK (A, "A for col selector", GB_FLIP (GB0)) ;
int nth = nthreads_max ;
ASSERT (!in_place_A) ;
ASSERT (C != NULL && C->static_header) ;
ASSERT (GB_JUMBLED_OK (A)) ;
int64_t j = (opcode == GB_COLINDEX_idxunop_code) ? (-ithunk) : ithunk ;
int64_t k = 0 ;
bool found ;
if (j < 0)
{
// j is outside the range of columns of A
k = 0 ;
found = false ;
}
else if (j >= avdim)
{
// j is outside the range of columns of A
k = anvec ;
found = false ;
}
else if (A_is_hyper)
{
// find the column j in the hyperlist of A
int64_t kright = anvec-1 ;
GB_SPLIT_BINARY_SEARCH (j, Ah, k, kright, found) ;
// if found is true the Ah [k] == j
// if found is false, then Ah [0..k-1] < j and Ah [k..anvec-1] > j
}
else
{
// j appears as the jth column in A; found is always true
k = j ;
found = true ;
}
//----------------------------------------------------------------------
// determine the # of entries and # of vectors in C
//----------------------------------------------------------------------
int64_t pstart = Ap [k] ;
int64_t pend = found ? Ap [k+1] : pstart ;
int64_t ajnz = pend - pstart ;
int64_t cnz, cnvec ;
int64_t anz = Ap [anvec] ;
if (opcode == GB_COLINDEX_idxunop_code)
{
// COLINDEX: delete column j: C = A (:, [0:j-1 j+1:end])
cnz = anz - ajnz ;
cnvec = (A_is_hyper && found) ? (anvec-1) : anvec ;
}
else if (opcode == GB_COLLE_idxunop_code)
{
// COLLE: C = A (:, 0:j)
cnz = pend ;
cnvec = (A_is_hyper) ? (found ? (k+1) : k) : anvec ;
}
else // (opcode == GB_COLGT_idxunop_code)
{
// COLGT: C = A (:, j+1:end)
cnz = anz - pend ;
cnvec = anvec - ((A_is_hyper) ? (found ? (k+1) : k) : 0) ;
}
if (cnz == anz)
{
// C is the same as A: return it a pure shallow copy
return (GB_shallow_copy (C, true, A, Context)) ;
}
else if (cnz == 0)
{
// return C as empty
return (GB_new (&C, true, // auto (sparse or hyper), static header
A->type, avlen, avdim, GB_Ap_calloc, true,
GxB_HYPERSPARSE, GB_Global_hyper_switch_get ( ), 1, Context)) ;
}
//----------------------------------------------------------------------
// allocate C
//----------------------------------------------------------------------
int sparsity = (A_is_hyper) ? GxB_HYPERSPARSE : GxB_SPARSE ;
GB_OK (GB_new_bix (&C, true, // sparse or hyper (from A), static header
A->type, avlen, avdim, GB_Ap_malloc, true, sparsity, false,
A->hyper_switch, cnvec, cnz, true, A_iso, Context)) ;
ASSERT (info == GrB_SUCCESS) ;
int nth2 = GB_nthreads (cnvec, chunk, nth) ;
int64_t *restrict Cp = C->p ;
int64_t *restrict Ch = C->h ;
int64_t *restrict Ci = C->i ;
GB_void *restrict Cx = (GB_void *) C->x ;
int64_t kk ;
//----------------------------------------------------------------------
// construct C
//----------------------------------------------------------------------
if (A_iso)
{
// Cx [0] = Ax [0]
memcpy (Cx, Ax, asize) ;
}
if (opcode == GB_COLINDEX_idxunop_code)
{
//------------------------------------------------------------------
// COLINDEX: delete the column j
//------------------------------------------------------------------
if (A_is_hyper)
{
ASSERT (found) ;
// Cp [0:k-1] = Ap [0:k-1]
GB_memcpy (Cp, Ap, k * sizeof (int64_t), nth) ;
// Cp [k:cnvec] = Ap [k+1:anvec] - ajnz
#pragma omp parallel for num_threads(nth2)
for (kk = k ; kk <= cnvec ; kk++)
{
Cp [kk] = Ap [kk+1] - ajnz ;
}
// Ch [0:k-1] = Ah [0:k-1]
GB_memcpy (Ch, Ah, k * sizeof (int64_t), nth) ;
// Ch [k:cnvec-1] = Ah [k+1:anvec-1]
GB_memcpy (Ch + k, Ah + (k+1), (cnvec-k) * sizeof (int64_t),
nth) ;
}
else
{
// Cp [0:k] = Ap [0:k]
GB_memcpy (Cp, Ap, (k+1) * sizeof (int64_t), nth) ;
// Cp [k+1:anvec] = Ap [k+1:anvec] - ajnz
#pragma omp parallel for num_threads(nth2)
for (kk = k+1 ; kk <= cnvec ; kk++)
{
Cp [kk] = Ap [kk] - ajnz ;
}
}
// Ci [0:pstart-1] = Ai [0:pstart-1]
GB_memcpy (Ci, Ai, pstart * sizeof (int64_t), nth) ;
// Ci [pstart:cnz-1] = Ai [pend:anz-1]
GB_memcpy (Ci + pstart, Ai + pend,
(cnz - pstart) * sizeof (int64_t), nth) ;
if (!A_iso)
{
// Cx [0:pstart-1] = Ax [0:pstart-1]
GB_memcpy (Cx, Ax, pstart * asize, nth) ;
// Cx [pstart:cnz-1] = Ax [pend:anz-1]
GB_memcpy (Cx + pstart * asize, Ax + pend * asize,
(cnz - pstart) * asize, nth) ;
}
}
else if (opcode == GB_COLLE_idxunop_code)
{
//------------------------------------------------------------------
// COLLE: C = A (:, 0:j)
//------------------------------------------------------------------
if (A_is_hyper)
{
// Cp [0:cnvec] = Ap [0:cnvec]
GB_memcpy (Cp, Ap, (cnvec+1) * sizeof (int64_t), nth) ;
// Ch [0:cnvec-1] = Ah [0:cnvec-1]
GB_memcpy (Ch, Ah, (cnvec) * sizeof (int64_t), nth) ;
}
else
{
// Cp [0:k+1] = Ap [0:k+1]
ASSERT (found) ;
GB_memcpy (Cp, Ap, (k+2) * sizeof (int64_t), nth) ;
// Cp [k+2:cnvec] = cnz
#pragma omp parallel for num_threads(nth2)
for (kk = k+2 ; kk <= cnvec ; kk++)
{
Cp [kk] = cnz ;
}
}
// Ci [0:cnz-1] = Ai [0:cnz-1]
GB_memcpy (Ci, Ai, cnz * sizeof (int64_t), nth) ;
if (!A_iso)
{
// Cx [0:cnz-1] = Ax [0:cnz-1]
GB_memcpy (Cx, Ax, cnz * asize, nth) ;
}
}
else // (opcode == GB_COLGT_idxunop_code)
{
//------------------------------------------------------------------
// COLGT: C = A (:, j+1:end)
//------------------------------------------------------------------
if (A_is_hyper)
{
// Cp [0:cnvec] = Ap [k+found:anvec] - pend
#pragma omp parallel for num_threads(nth2)
for (kk = 0 ; kk <= cnvec ; kk++)
{
Cp [kk] = Ap [kk + k + found] - pend ;
}
// Ch [0:cnvec-1] = Ah [k+found:anvec-1]
GB_memcpy (Ch, Ah + k + found, cnvec * sizeof (int64_t), nth) ;
}
else
{
ASSERT (found) ;
// Cp [0:k] = 0
GB_memset (Cp, 0, (k+1) * sizeof (int64_t), nth) ;
// Cp [k+1:cnvec] = Ap [k+1:cnvec] - pend
#pragma omp parallel for num_threads(nth2)
for (kk = k+1 ; kk <= cnvec ; kk++)
{
Cp [kk] = Ap [kk] - pend ;
}
}
// Ci [0:cnz-1] = Ai [pend:anz-1]
GB_memcpy (Ci, Ai + pend, cnz * sizeof (int64_t), nth) ;
if (!A_iso)
{
// Cx [0:cnz-1] = Ax [pend:anz-1]
GB_memcpy (Cx, Ax + pend * asize, cnz * asize, nth) ;
}
}
//----------------------------------------------------------------------
// finalize the matrix, free workspace, and return result
//----------------------------------------------------------------------
C->nvec = cnvec ;
C->magic = GB_MAGIC ;
C->jumbled = A_jumbled ; // C is jumbled if A is jumbled
C->iso = C_iso ; // OK: burble already done above
C->nvec_nonempty = GB_nvec_nonempty (C, Context) ;
ASSERT_MATRIX_OK (C, "C output for GB_selector (column select)", GB0) ;
return (GrB_SUCCESS) ;
}
//==========================================================================
// all other select/idxunop operators
//==========================================================================
#undef GB_FREE_ALL
#define GB_FREE_ALL \
{ \
GB_phbix_free (C) ; \
GB_FREE_WORKSPACE ; \
}
//--------------------------------------------------------------------------
// allocate the new vector pointers of C
//--------------------------------------------------------------------------
int64_t cnz = 0 ;
Cp = GB_CALLOC (anvec+1, int64_t, &Cp_size) ;
if (Cp == NULL)
{
// out of memory
return (GrB_OUT_OF_MEMORY) ;
}
//--------------------------------------------------------------------------
// slice the entries for each task
//--------------------------------------------------------------------------
int A_ntasks, A_nthreads ;
double work = 8*anvec
+ ((opcode == GB_DIAG_selop_code) ? 0 : GB_nnz_held (A)) ;
GB_SLICE_MATRIX_WORK (A, 8, chunk, work) ;
//--------------------------------------------------------------------------
// allocate workspace for each task
//--------------------------------------------------------------------------
GB_WERK_PUSH (Work, 3*A_ntasks, int64_t) ;
if (Work == NULL)
{
// out of memory
GB_FREE_ALL ;
return (GrB_OUT_OF_MEMORY) ;
}
Wfirst = Work ;
Wlast = Work + A_ntasks ;
Cp_kfirst = Work + A_ntasks * 2 ;
//--------------------------------------------------------------------------
// allocate workspace for phase1
//--------------------------------------------------------------------------
// phase1 counts the number of live entries in each vector of A. The
// result is computed in Cp, where Cp [k] is the number of live entries in
// the kth vector of A. Zp [k] is the location of the A(i,k) entry, for
// positional operators.
if (op_is_positional)
{
// allocate Zp
Zp = GB_MALLOC_WORK (anvec, int64_t, &Zp_size) ;
if (Zp == NULL)
{
// out of memory
GB_FREE_ALL ;
return (GrB_OUT_OF_MEMORY) ;
}
}
//--------------------------------------------------------------------------
// phase1: count the live entries in each column
//--------------------------------------------------------------------------
// define the worker for the switch factory
#define GB_SELECT_PHASE1
#define GB_sel1(opname,aname) GB (_sel_phase1_ ## opname ## aname)
#define GB_SEL_WORKER(opname,aname,atype) \
{ \
GB_sel1 (opname, aname) (Zp, Cp, Wfirst, Wlast, A, \
flipij, ithunk, (atype *) athunk, ythunk, op, \
A_ek_slicing, A_ntasks, A_nthreads) ; \
} \
break ;
// launch the switch factory
const GB_Type_code typecode = (A_iso) ? GB_ignore_code : acode ;
#include "GB_select_factory.c"
#undef GB_SELECT_PHASE1
#undef GB_SEL_WORKER
//--------------------------------------------------------------------------
// cumulative sum of Cp and compute Cp_kfirst
//--------------------------------------------------------------------------
int64_t C_nvec_nonempty ;
GB_ek_slice_merge2 (&C_nvec_nonempty, Cp_kfirst, Cp, anvec,
Wfirst, Wlast, A_ek_slicing, A_ntasks, A_nthreads, Context) ;
//--------------------------------------------------------------------------
// allocate new space for the compacted Ci and Cx
//--------------------------------------------------------------------------
cnz = Cp [anvec] ;
cnz = GB_IMAX (cnz, 1) ;
Ci = GB_MALLOC (cnz, int64_t, &Ci_size) ;
// use calloc since C is sparse, not bitmap
Cx = (GB_void *) GB_XALLOC (false, C_iso, cnz, asize, &Cx_size) ; // x:OK
if (Ci == NULL || Cx == NULL)
{
// out of memory
GB_FREE_ALL ;
return (GrB_OUT_OF_MEMORY) ;
}
//--------------------------------------------------------------------------
// set the iso value of C
//--------------------------------------------------------------------------
if (C_iso)
{
// The pattern of C is computed by the worker below, for the DIAG,
// OFFDIAG, TRIL, TRIU, NONZOMBIE, and USER select operators.
GB_iso_select (Cx, opcode, athunk, Ax, acode, asize) ;
}
//--------------------------------------------------------------------------
// phase2: select the entries
//--------------------------------------------------------------------------
// define the worker for the switch factory
#define GB_SELECT_PHASE2
#define GB_sel2(opname,aname) GB (_sel_phase2_ ## opname ## aname)
#define GB_SEL_WORKER(opname,aname,atype) \
{ \
GB_sel2 (opname, aname) (Ci, (atype *) Cx, Zp, Cp, Cp_kfirst, A, \
flipij, ithunk, (atype *) athunk, ythunk, op, \
A_ek_slicing, A_ntasks, A_nthreads) ; \
} \
break ;
// launch the switch factory
#include "GB_select_factory.c"
//--------------------------------------------------------------------------
// create the result
//--------------------------------------------------------------------------
if (in_place_A)
{
//----------------------------------------------------------------------
// transplant Cp, Ci, Cx back into A
//----------------------------------------------------------------------
// TODO: this is not parallel: use GB_hyper_prune
if (A->h != NULL && C_nvec_nonempty < anvec)
{
// prune empty vectors from Ah and Ap
int64_t cnvec = 0 ;
for (int64_t k = 0 ; k < anvec ; k++)
{
if (Cp [k] < Cp [k+1])
{
Ah [cnvec] = Ah [k] ;
Ap [cnvec] = Cp [k] ;
cnvec++ ;
}
}
Ap [cnvec] = Cp [anvec] ;
A->nvec = cnvec ;
ASSERT (A->nvec == C_nvec_nonempty) ;
GB_FREE (&Cp, Cp_size) ;
}
else
{
// free the old A->p and transplant in Cp as the new A->p
GB_FREE (&Ap, Ap_size) ;
A->p = Cp ; Cp = NULL ; A->p_size = Cp_size ;
A->plen = anvec ;
}
ASSERT (Cp == NULL) ;
GB_FREE (&Ai, Ai_size) ;
GB_FREE (&Ax, Ax_size) ;
A->i = Ci ; Ci = NULL ; A->i_size = Ci_size ;
A->x = Cx ; Cx = NULL ; A->x_size = Cx_size ;
A->nvec_nonempty = C_nvec_nonempty ;
A->jumbled = A_jumbled ; // A remains jumbled (in-place select)
A->iso = C_iso ; // OK: burble already done above
// the NONZOMBIE opcode may have removed all zombies, but A->nzombie
// is still nonzero. It is set to zero in GB_wait.
ASSERT_MATRIX_OK (A, "A output for GB_selector", GB_FLIP (GB0)) ;
}
else
{
//----------------------------------------------------------------------
// create C and transplant Cp, Ch, Ci, Cx into C
//----------------------------------------------------------------------
int sparsity = (A_is_hyper) ? GxB_HYPERSPARSE : GxB_SPARSE ;
ASSERT (C != NULL && C->static_header) ;
info = GB_new (&C, true, // sparse or hyper (from A), static header
A->type, avlen, avdim, GB_Ap_null, true,
sparsity, A->hyper_switch, anvec, Context) ;
ASSERT (info == GrB_SUCCESS) ;
if (A->h != NULL)
{
//------------------------------------------------------------------
// A and C are hypersparse: copy non-empty vectors from Ah to Ch
//------------------------------------------------------------------
Ch = GB_MALLOC (anvec, int64_t, &Ch_size) ;
if (Ch == NULL)
{
// out of memory
GB_FREE_ALL ;
return (GrB_OUT_OF_MEMORY) ;
}
// TODO: do in parallel: use GB_hyper_prune
int64_t cnvec = 0 ;
for (int64_t k = 0 ; k < anvec ; k++)
{
if (Cp [k] < Cp [k+1])
{
Ch [cnvec] = Ah [k] ;
Cp [cnvec] = Cp [k] ;
cnvec++ ;
}
}
Cp [cnvec] = Cp [anvec] ;
C->nvec = cnvec ;
ASSERT (C->nvec == C_nvec_nonempty) ;
}
C->p = Cp ; Cp = NULL ; C->p_size = Cp_size ;
C->h = Ch ; Ch = NULL ; C->h_size = Ch_size ;
C->i = Ci ; Ci = NULL ; C->i_size = Ci_size ;
C->x = Cx ; Cx = NULL ; C->x_size = Cx_size ;
C->plen = anvec ;
C->magic = GB_MAGIC ;
C->nvec_nonempty = C_nvec_nonempty ;
C->jumbled = A_jumbled ; // C is jumbled if A is jumbled
C->iso = C_iso ; // OK: burble already done above
ASSERT_MATRIX_OK (C, "C output for GB_selector", GB0) ;
}
//--------------------------------------------------------------------------
// free workspace and return result
//--------------------------------------------------------------------------
GB_FREE_WORKSPACE ;
return (GrB_SUCCESS) ;
}
|
gbdt.h | #ifndef LIGHTGBM_BOOSTING_GBDT_H_
#define LIGHTGBM_BOOSTING_GBDT_H_
#include <LightGBM/boosting.h>
#include <LightGBM/objective_function.h>
#include <LightGBM/prediction_early_stop.h>
#include <LightGBM/json11.hpp>
#include "score_updater.hpp"
#include <cstdio>
#include <vector>
#include <string>
#include <fstream>
#include <memory>
#include <mutex>
#include <map>
using namespace json11;
namespace LightGBM {
/*!
* \brief GBDT algorithm implementation. including Training, prediction, bagging.
*/
class GBDT : public GBDTBase {
public:
/*!
* \brief Constructor
*/
GBDT();
/*!
* \brief Destructor
*/
~GBDT();
/*!
* \brief Initialization logic
* \param gbdt_config Config for boosting
* \param train_data Training data
* \param objective_function Training objective function
* \param training_metrics Training metrics
*/
void Init(const BoostingConfig* gbdt_config, const Dataset* train_data,
const ObjectiveFunction* objective_function,
const std::vector<const Metric*>& training_metrics) override;
/*!
* \brief Merge model from other boosting object. Will insert to the front of current boosting object
* \param other
*/
void MergeFrom(const Boosting* other) override {
auto other_gbdt = reinterpret_cast<const GBDT*>(other);
// tmp move to other vector
auto original_models = std::move(models_);
models_ = std::vector<std::unique_ptr<Tree>>();
// push model from other first
for (const auto& tree : other_gbdt->models_) {
auto new_tree = std::unique_ptr<Tree>(new Tree(*(tree.get())));
models_.push_back(std::move(new_tree));
}
num_init_iteration_ = static_cast<int>(models_.size()) / num_tree_per_iteration_;
// push model in current object
for (const auto& tree : original_models) {
auto new_tree = std::unique_ptr<Tree>(new Tree(*(tree.get())));
models_.push_back(std::move(new_tree));
}
num_iteration_for_pred_ = static_cast<int>(models_.size()) / num_tree_per_iteration_;
}
/*!
* \brief Reset the training data
* \param train_data New Training data
* \param objective_function Training objective function
* \param training_metrics Training metrics
*/
void ResetTrainingData(const Dataset* train_data, const ObjectiveFunction* objective_function,
const std::vector<const Metric*>& training_metrics) override;
/*!
* \brief Reset Boosting Config
* \param gbdt_config Config for boosting
*/
void ResetConfig(const BoostingConfig* gbdt_config) override;
/*!
* \brief Adding a validation dataset
* \param valid_data Validation dataset
* \param valid_metrics Metrics for validation dataset
*/
void AddValidDataset(const Dataset* valid_data,
const std::vector<const Metric*>& valid_metrics) override;
/*!
* \brief Perform a full training procedure
* \param snapshot_freq frequence of snapshot
* \param model_output_path path of model file
*/
void Train(int snapshot_freq, const std::string& model_output_path) override;
void RefitTree(const std::vector<std::vector<int>>& tree_leaf_prediction) override;
/*!
* \brief Training logic
* \param gradients nullptr for using default objective, otherwise use self-defined boosting
* \param hessians nullptr for using default objective, otherwise use self-defined boosting
* \return True if cannot train any more
*/
virtual bool TrainOneIter(const score_t* gradients, const score_t* hessians) override;
/*!
* \brief Rollback one iteration
*/
void RollbackOneIter() override;
/*!
* \brief Get current iteration
*/
int GetCurrentIteration() const override { return static_cast<int>(models_.size()) / num_tree_per_iteration_; }
/*!
* \brief Can use early stopping for prediction or not
* \return True if cannot use early stopping for prediction
*/
bool NeedAccuratePrediction() const override {
if (objective_function_ == nullptr) {
return true;
} else {
return objective_function_->NeedAccuratePrediction();
}
}
/*!
* \brief Get evaluation result at data_idx data
* \param data_idx 0: training data, 1: 1st validation data
* \return evaluation result
*/
std::vector<double> GetEvalAt(int data_idx) const override;
/*!
* \brief Get current training score
* \param out_len length of returned score
* \return training score
*/
virtual const double* GetTrainingScore(int64_t* out_len) override;
/*!
* \brief Get size of prediction at data_idx data
* \param data_idx 0: training data, 1: 1st validation data
* \return The size of prediction
*/
virtual int64_t GetNumPredictAt(int data_idx) const override {
CHECK(data_idx >= 0 && data_idx <= static_cast<int>(valid_score_updater_.size()));
data_size_t num_data = train_data_->num_data();
if (data_idx > 0) {
num_data = valid_score_updater_[data_idx - 1]->num_data();
}
return num_data * num_class_;
}
/*!
* \brief Get prediction result at data_idx data
* \param data_idx 0: training data, 1: 1st validation data
* \param result used to store prediction result, should allocate memory before call this function
* \param out_len length of returned score
*/
void GetPredictAt(int data_idx, double* out_result, int64_t* out_len) override;
/*!
* \brief Get number of prediction for one data
* \param num_iteration number of used iterations
* \param is_pred_leaf True if predicting leaf index
* \param is_pred_contrib True if predicting feature contribution
* \return number of prediction
*/
inline int NumPredictOneRow(int num_iteration, bool is_pred_leaf, bool is_pred_contrib) const override {
int num_preb_in_one_row = num_class_;
if (is_pred_leaf) {
int max_iteration = GetCurrentIteration();
if (num_iteration > 0) {
num_preb_in_one_row *= static_cast<int>(std::min(max_iteration, num_iteration));
} else {
num_preb_in_one_row *= max_iteration;
}
} else if (is_pred_contrib) {
num_preb_in_one_row = num_tree_per_iteration_ * (max_feature_idx_ + 2); // +1 for 0-based indexing, +1 for baseline
}
return num_preb_in_one_row;
}
void PredictRaw(const double* features, double* output,
const PredictionEarlyStopInstance* earlyStop) const override;
void PredictRawByMap(const std::unordered_map<int, double>& features, double* output,
const PredictionEarlyStopInstance* early_stop) const override;
void Predict(const double* features, double* output,
const PredictionEarlyStopInstance* earlyStop) const override;
void PredictByMap(const std::unordered_map<int, double>& features, double* output,
const PredictionEarlyStopInstance* early_stop) const override;
void PredictLeafIndex(const double* features, double* output) const override;
void PredictLeafIndexByMap(const std::unordered_map<int, double>& features, double* output) const override;
void PredictContrib(const double* features, double* output,
const PredictionEarlyStopInstance* earlyStop) const override;
/*!
* \brief Dump model to json format string
* \param num_iteration Number of iterations that want to dump, -1 means dump all
* \return Json format string of model
*/
std::string DumpModel(int num_iteration) const override;
/*!
* \brief Translate model to if-else statement
* \param num_iteration Number of iterations that want to translate, -1 means translate all
* \return if-else format codes of model
*/
std::string ModelToIfElse(int num_iteration) const override;
/*!
* \brief Translate model to if-else statement
* \param num_iteration Number of iterations that want to translate, -1 means translate all
* \param filename Filename that want to save to
* \return is_finish Is training finished or not
*/
bool SaveModelToIfElse(int num_iteration, const char* filename) const override;
/*!
* \brief Save model to file
* \param num_iterations Number of model that want to save, -1 means save all
* \param filename Filename that want to save to
* \return is_finish Is training finished or not
*/
virtual bool SaveModelToFile(int num_iterations, const char* filename) const override;
/*!
* \brief Save model to string
* \param num_iterations Number of model that want to save, -1 means save all
* \return Non-empty string if succeeded
*/
virtual std::string SaveModelToString(int num_iterations) const override;
/*!
* \brief Restore from a serialized buffer
*/
bool LoadModelFromString(const char* buffer, size_t len) override;
/*!
* \brief Calculate feature importances
* \param num_iteration Number of model that want to use for feature importance, -1 means use all
* \param importance_type: 0 for split, 1 for gain
* \return vector of feature_importance
*/
std::vector<double> FeatureImportance(int num_iteration, int importance_type) const override;
/*!
* \brief Get max feature index of this model
* \return Max feature index of this model
*/
inline int MaxFeatureIdx() const override { return max_feature_idx_; }
/*!
* \brief Get feature names of this model
* \return Feature names of this model
*/
inline std::vector<std::string> FeatureNames() const override { return feature_names_; }
/*!
* \brief Get index of label column
* \return index of label column
*/
inline int LabelIdx() const override { return label_idx_; }
/*!
* \brief Get number of weak sub-models
* \return Number of weak sub-models
*/
inline int NumberOfTotalModel() const override { return static_cast<int>(models_.size()); }
/*!
* \brief Get number of tree per iteration
* \return number of tree per iteration
*/
inline int NumModelPerIteration() const override { return num_tree_per_iteration_; }
/*!
* \brief Get number of classes
* \return Number of classes
*/
inline int NumberOfClasses() const override { return num_class_; }
inline void InitPredict(int num_iteration, bool is_pred_contrib) override {
num_iteration_for_pred_ = static_cast<int>(models_.size()) / num_tree_per_iteration_;
if (num_iteration > 0) {
num_iteration_for_pred_ = std::min(num_iteration, num_iteration_for_pred_);
}
if (is_pred_contrib) {
#pragma omp parallel for schedule(static)
for (int i = 0; i < static_cast<int>(models_.size()); ++i) {
models_[i]->RecomputeMaxDepth();
}
}
}
inline double GetLeafValue(int tree_idx, int leaf_idx) const override {
CHECK(tree_idx >= 0 && static_cast<size_t>(tree_idx) < models_.size());
CHECK(leaf_idx >= 0 && leaf_idx < models_[tree_idx]->num_leaves());
return models_[tree_idx]->LeafOutput(leaf_idx);
}
inline void SetLeafValue(int tree_idx, int leaf_idx, double val) override {
CHECK(tree_idx >= 0 && static_cast<size_t>(tree_idx) < models_.size());
CHECK(leaf_idx >= 0 && leaf_idx < models_[tree_idx]->num_leaves());
models_[tree_idx]->SetLeafOutput(leaf_idx, val);
}
/*!
* \brief Get Type name of this boosting object
*/
virtual const char* SubModelName() const override { return "tree"; }
protected:
/*!
* \brief Print eval result and check early stopping
*/
bool EvalAndCheckEarlyStopping();
/*!
* \brief reset config for bagging
*/
void ResetBaggingConfig(const BoostingConfig* config, bool is_change_dataset);
/*!
* \brief Implement bagging logic
* \param iter Current interation
*/
virtual void Bagging(int iter);
/*!
* \brief Helper function for bagging, used for multi-threading optimization
* \param start start indice of bagging
* \param cnt count
* \param buffer output buffer
* \return count of left size
*/
data_size_t BaggingHelper(Random& cur_rand, data_size_t start, data_size_t cnt, data_size_t* buffer);
/*!
* \brief calculate the object function
*/
virtual void Boosting();
/*!
* \brief updating score after tree was trained
* \param tree Trained tree of this iteration
* \param cur_tree_id Current tree for multiclass training
*/
virtual void UpdateScore(const Tree* tree, const int cur_tree_id);
/*!
* \brief eval results for one metric
*/
virtual std::vector<double> EvalOneMetric(const Metric* metric, const double* score) const;
/*!
* \brief Print metric result of current iteration
* \param iter Current interation
* \return best_msg if met early_stopping
*/
std::string OutputMetric(int iter);
double BoostFromAverage();
/*! \brief current iteration */
int iter_;
/*! \brief Pointer to training data */
const Dataset* train_data_;
/*! \brief Config of gbdt */
std::unique_ptr<BoostingConfig> gbdt_config_;
/*! \brief Tree learner, will use this class to learn trees */
std::unique_ptr<TreeLearner> tree_learner_;
/*! \brief Objective function */
const ObjectiveFunction* objective_function_;
/*! \brief Store and update training data's score */
std::unique_ptr<ScoreUpdater> train_score_updater_;
/*! \brief Metrics for training data */
std::vector<const Metric*> training_metrics_;
/*! \brief Store and update validation data's scores */
std::vector<std::unique_ptr<ScoreUpdater>> valid_score_updater_;
/*! \brief Metric for validation data */
std::vector<std::vector<const Metric*>> valid_metrics_;
/*! \brief Number of rounds for early stopping */
int early_stopping_round_;
/*! \brief Best iteration(s) for early stopping */
std::vector<std::vector<int>> best_iter_;
/*! \brief Best score(s) for early stopping */
std::vector<std::vector<double>> best_score_;
/*! \brief output message of best iteration */
std::vector<std::vector<std::string>> best_msg_;
/*! \brief Trained models(trees) */
std::vector<std::unique_ptr<Tree>> models_;
/*! \brief Max feature index of training data*/
int max_feature_idx_;
/*! \brief First order derivative of training data */
std::vector<score_t> gradients_;
/*! \brief Secend order derivative of training data */
std::vector<score_t> hessians_;
/*! \brief Store the indices of in-bag data */
std::vector<data_size_t> bag_data_indices_;
/*! \brief Number of in-bag data */
data_size_t bag_data_cnt_;
/*! \brief Store the indices of in-bag data */
std::vector<data_size_t> tmp_indices_;
/*! \brief Number of training data */
data_size_t num_data_;
/*! \brief Number of trees per iterations */
int num_tree_per_iteration_;
/*! \brief Number of class */
int num_class_;
/*! \brief Index of label column */
data_size_t label_idx_;
/*! \brief number of used model */
int num_iteration_for_pred_;
/*! \brief Shrinkage rate for one iteration */
double shrinkage_rate_;
/*! \brief Number of loaded initial models */
int num_init_iteration_;
/*! \brief Feature names */
std::vector<std::string> feature_names_;
std::vector<std::string> feature_infos_;
/*! \brief number of threads */
int num_threads_;
/*! \brief Buffer for multi-threading bagging */
std::vector<data_size_t> offsets_buf_;
/*! \brief Buffer for multi-threading bagging */
std::vector<data_size_t> left_cnts_buf_;
/*! \brief Buffer for multi-threading bagging */
std::vector<data_size_t> right_cnts_buf_;
/*! \brief Buffer for multi-threading bagging */
std::vector<data_size_t> left_write_pos_buf_;
/*! \brief Buffer for multi-threading bagging */
std::vector<data_size_t> right_write_pos_buf_;
std::unique_ptr<Dataset> tmp_subset_;
bool is_use_subset_;
std::vector<bool> class_need_train_;
std::vector<double> class_default_output_;
bool is_constant_hessian_;
std::unique_ptr<ObjectiveFunction> loaded_objective_;
bool average_output_;
bool need_re_bagging_;
Json forced_splits_json_;
};
} // namespace LightGBM
#endif // LightGBM_BOOSTING_GBDT_H_
|
zoom.c | // This program is free software: you can use, modify and/or redistribute it
// under the terms of the simplified BSD License. You should have received a
// copy of this license along this program. If not, see
// <http://www.opensource.org/licenses/bsd-license.html>.
//
// Copyright (C) 2012, Javier Sánchez Pérez <jsanchez@dis.ulpgc.es>
// All rights reserved.
#ifndef ZOOM_C
#define ZOOM_C
#include "xmalloc.c"
#include "mask.c"
#include "bicubic_interpolation.c"
#define ZOOM_SIGMA_ZERO 0.6
/**
*
* Compute the size of a zoomed image from the zoom factor
*
**/
void zoom_size(
int nx, // width of the orignal image
int ny, // height of the orignal image
int *nxx, // width of the zoomed image
int *nyy, // height of the zoomed image
float factor // zoom factor between 0 and 1
)
{
*nxx = (int)((float) nx * factor + 0.5);
*nyy = (int)((float) ny * factor + 0.5);
}
/**
*
* Downsample an image
*
**/
void zoom_out(
const float *I, // input image
float *Iout, // output image
const int nx, // image width
const int ny, // image height
const float factor // zoom factor between 0 and 1
)
{
// temporary working image
float *Is = xmalloc(nx * ny * sizeof*Is);
for(int i = 0; i < nx * ny; i++)
Is[i] = I[i];
// compute the size of the zoomed image
int nxx, nyy;
zoom_size(nx, ny, &nxx, &nyy, factor);
// compute the Gaussian sigma for smoothing
const float sigma = ZOOM_SIGMA_ZERO * sqrt(1.0/(factor*factor) - 1.0);
// pre-smooth the image
gaussian(Is, nx, ny, sigma);
// re-sample the image using bicubic interpolation
#pragma omp parallel for
for (int i1 = 0; i1 < nyy; i1++)
for (int j1 = 0; j1 < nxx; j1++)
{
const float i2 = (float) i1 / factor;
const float j2 = (float) j1 / factor;
float g = bicubic_interpolation_at(Is, j2, i2, nx, ny, false);
Iout[i1 * nxx + j1] = g;
}
free(Is);
}
/**
*
* Function to upsample the image
*
**/
void zoom_in(
const float *I, // input image
float *Iout, // output image
int nx, // width of the original image
int ny, // height of the original image
int nxx, // width of the zoomed image
int nyy // height of the zoomed image
)
{
// compute the zoom factor
const float factorx = ((float)nxx / nx);
const float factory = ((float)nyy / ny);
// re-sample the image using bicubic interpolation
#pragma omp parallel for
for (int i1 = 0; i1 < nyy; i1++)
for (int j1 = 0; j1 < nxx; j1++)
{
float i2 = (float) i1 / factory;
float j2 = (float) j1 / factorx;
float g = bicubic_interpolation_at(I, j2, i2, nx, ny, false);
Iout[i1 * nxx + j1] = g;
}
}
#endif//ZOOM_C
|
mm_v2.c | /*
* Assignment2 (CSE436)
* Kazumi Malhan
* 06/08/2016
*/
/* Note
*
* This program assumes that size of matrix is dividable
* by number of tasks
* /
/* Ongoing issues !! */
// Need to put init code back
// Need to remove all debug printf
// Current code assumes that N and M are dividable by num_tasks
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <string.h>
#include <sys/timeb.h>
/* read timer in second */
double read_timer() {
struct timeb tm;
ftime(&tm);
return (double) tm.time + (double) tm.millitm / 1000.0;
}
/* read timer in ms */
double read_timer_ms() {
struct timeb tm;
ftime(&tm);
return (double) tm.time * 1000.0 + (double) tm.millitm;
}
#define REAL float
#define VECTOR_LENGTH 512
/* 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();
A[i] = i;
}
}
/* Function Prototypes */
void mm(int N, int K, int M, REAL * A, REAL * B, REAL * C);
void mm_parallel_row(int N, int K, int M, REAL * A, REAL * B, REAL * C, int num_tasks);
void mm_parallel_col(int N, int K, int M, REAL * A, REAL * B, REAL * C, int num_tasks);
void mm_parallel_rowcol(int N, int K, int M, REAL * A, REAL * B, REAL * C, int num_tasks);
void mm_parallel_for_row(int N, int K, int M, REAL * A, REAL * B, REAL * C, int num_tasks);
void mm_parallel_for_col(int N, int K, int M, REAL * A, REAL * B, REAL * C, int num_tasks);
void mm_parallel_for_rowcol(int N, int K, int M, REAL * A, REAL * B, REAL * C, int num_tasks);
/**
* To compile: gcc mm.c -fopenmp -o mm
*/
int main(int argc, char *argv[]) {
int N = VECTOR_LENGTH;
int M = N;
int K = N;
int num_tasks = 4;
double elapsed; /* for timing */
if (argc < 5) {
fprintf(stderr, "Usage: mm [<N(%d)>] <K(%d) [<M(%d)>] [<#tasks(%d)>]\n", N,K,M,num_tasks);
fprintf(stderr, "\t Example: ./mm %d %d %d %d\n", N,K,M,num_tasks);
} else {
N = atoi(argv[1]);
K = atoi(argv[2]);
M = atoi(argv[3]);
num_tasks = atoi(argv[4]);
}
printf("\tC[%d][%d] = A[%d][%d] * B[%d][%d] with %d tasks\n", N, M, N, K, K, M, num_tasks);
REAL * A = malloc(sizeof(REAL)*N*K);
REAL * B = malloc(sizeof(REAL)*K*M);
REAL * C = malloc(sizeof(REAL)*N*M);
srand48((1 << 12));
init(A, N*K);
init(B, K*M);
/* Serial program */
double elapsed_mm = read_timer();
mm(N, K, M, A, B, C);
elapsed_mm = (read_timer() - elapsed_mm);
/* Parallel program */
double elapsed_mm_parallel_row = read_timer();
mm_parallel_row(N, K, M, A, B, C, num_tasks);
elapsed_mm_parallel_row = (read_timer() - elapsed_mm_parallel_row);
double elapsed_mm_parallel_col = read_timer();
mm_parallel_col(N, K, M, A, B, C, num_tasks);
elapsed_mm_parallel_col = (read_timer() - elapsed_mm_parallel_col);
double elapsed_mm_parallel_rowcol = read_timer();
mm_parallel_rowcol(N, K, M, A, B, C, num_tasks);
elapsed_mm_parallel_rowcol = (read_timer() - elapsed_mm_parallel_rowcol);
/* Parallel for program */
double elapsed_mm_parallel_for_row = read_timer();
mm_parallel_for_row(N, K, M, A, B, C, num_tasks);
elapsed_mm_parallel_for_row = (read_timer() - elapsed_mm_parallel_for_row);
double elapsed_mm_parallel_for_col = read_timer();
mm_parallel_for_col(N, K, M, A, B, C, num_tasks);
elapsed_mm_parallel_for_col = (read_timer() - elapsed_mm_parallel_for_col);
double elapsed_mm_parallel_for_rowcol = read_timer();
mm_parallel_for_rowcol(N, K, M, A, B, C, num_tasks);
elapsed_mm_parallel_for_rowcol = (read_timer() - elapsed_mm_parallel_for_rowcol);
/* you should add the call to each function and time the execution */
printf("======================================================================================================\n");
printf("\tC[%d][%d] = A[%d][%d] * B[%d][%d] with %d tasks\n", N, M, N, K, K, M, num_tasks);
printf("------------------------------------------------------------------------------------------------------\n");
printf("Performance:\t\t\t\tRuntime (ms)\t MFLOPS \n");
printf("------------------------------------------------------------------------------------------------------\n");
printf("mm:\t\t\t\t%4f\t%4f\n", elapsed_mm * 1.0e3, M*N*K / (1.0e6 * elapsed_mm));
printf("mm_parallel_row:\t\t%4f\t%4f\n", elapsed_mm_parallel_row * 1.0e3, M*N*K / (1.0e6 * elapsed_mm_parallel_row));
printf("mm_parallel_col:\t\t%4f\t%4f\n", elapsed_mm_parallel_col * 1.0e3, M*N*K / (1.0e6 * elapsed_mm_parallel_col));
printf("mm_parallel_rowcol:\t\t%4f\t%4f\n", elapsed_mm_parallel_rowcol * 1.0e3, M*N*K / (1.0e6 * elapsed_mm_parallel_rowcol));
printf("mm_parallel_for_row:\t\t%4f\t%4f\n", elapsed_mm_parallel_for_row * 1.0e3, M*N*K / (1.0e6 * elapsed_mm_parallel_for_row));
printf("mm_parallel_for_col:\t\t%4f\t%4f\n", elapsed_mm_parallel_for_col * 1.0e3, M*N*K / (1.0e6 * elapsed_mm_parallel_for_col));
printf("mm_parallel_for_rowcol:\t\t%4f\t%4f\n", elapsed_mm_parallel_for_rowcol * 1.0e3, M*N*K / (1.0e6 * elapsed_mm_parallel_for_rowcol));
free(A);
free(B);
free(C);
return 0;
}
/* Serial */
void mm(int N, int K, int M, REAL * A, REAL * B, REAL * C) {
int i, j, w;
for (i=0; i<N; i++)
for (j=0; j<M; j++) {
REAL temp = 0.0;
for (w=0; w<K; w++)
temp += A[i*K+w]*B[w*M+j];
C[i*M+j] = temp;
}
}
/* Parallel Row */
void mm_parallel_row(int N, int K, int M, REAL * A, REAL * B, REAL * C, int num_tasks){
int i, j, w;
omp_set_num_threads(num_tasks);
#pragma omp parallel shared (N, K, M, A, B, C, num_tasks) private (i, j, w)
{
int tid, istart, iend;
tid = omp_get_thread_num();
istart = tid * (N / num_tasks);
iend = (tid + 1) * (N / num_tasks);
//printf("tid is %d\t, istart is %d\t, iend is %d\n", tid, istart, iend);
for (i=istart; i<iend; i++) { /* decompose this loop */
for (j=0; j<M; j++) {
REAL temp = 0.0;
for (w=0; w<K; w++)
temp += A[i*K+w]*B[w*M+j];
C[i*M+j] = temp;
}
}
}/* end of parallel */
}
/* Parallel Column */
void mm_parallel_col(int N, int K, int M, REAL * A, REAL * B, REAL * C, int num_tasks){
int i, j, w;
omp_set_num_threads(num_tasks);
#pragma omp parallel shared (N, K, M, A, B, C, num_tasks) private (i, j, w)
{
int tid, jstart, jend;
tid = omp_get_thread_num();
jstart = tid * (M / num_tasks);
jend = (tid + 1) * (M / num_tasks);
for (i=0; i<N; i++) {
for (j=jstart; j<jend; j++) { /* decompose this loop */
REAL temp = 0.0;
for (w=0; w<K; w++)
temp += A[i*K+w]*B[w*M+j];
C[i*M+j] = temp;
}
}
} /* end of parallel */
}
/* Parallel Row Column */
void mm_parallel_rowcol(int N, int K, int M, REAL * A, REAL * B, REAL * C, int num_tasks){
int i, j, w;
int task_r, task_c;
/* Calculate amount of work for each thread */
if (num_tasks == 1){
task_r = 1;
task_c = 1;
} else {
task_r = num_tasks / 2;
task_c = num_tasks / task_r;
}
#pragma omp parallel shared (N, K, M, A, B, C, task_r, task_c) private (i, j, w) num_threads(num_tasks)
{
int tid, istart, jstart, iend, jend;
tid = omp_get_thread_num();
istart = ((tid/task_c) * (N/task_r)%N);
iend = ((tid/task_c + 1) * (N/task_r)%N);
if (iend == 0) {iend = N;}
jstart = ((tid%task_r) * (M/task_c)%M);
jend = ((tid%task_r + 1) * (M/task_c)%M);
if (jend == 0) {jend = M;}
//printf("tid %d perform i: %d to %d, j: %d to %d\n", tid, istart, iend, jstart, jend);
for (i=istart; i<iend; i++) { /* decompose this loop */
for (j=jstart; j<jend; j++) { /* decompose this loop */
REAL temp = 0.0;
for (w=0; w<K; w++) {
temp += A[i*K+w]*B[w*M+j];
}
C[i*M+j] = temp;
}
}
} /* end of parallel */
}
/* Parallel For Row */
void mm_parallel_for_row(int N, int K, int M, REAL * A, REAL * B, REAL * C, int num_tasks){
int i, j, w;
omp_set_num_threads(num_tasks);
#pragma omp parallel shared (N, K, M, A, B, C, num_tasks) private (i, j, w)
{
#pragma omp for schedule(static) nowait
for (i=0; i<N; i++) {
for (j=0; j<M; j++) {
REAL temp = 0.0;
for (w=0; w<K; w++)
temp += A[i*K+w]*B[w*M+j];
C[i*M+j] = temp;
}
}
} /* end of parallel */
}
/* Parallel For Column */
void mm_parallel_for_col(int N, int K, int M, REAL * A, REAL * B, REAL * C, int num_tasks){
int i, j, w;
omp_set_num_threads(num_tasks);
#pragma omp parallel shared (N, K, M, A, B, C, num_tasks) private (i, j, w)
{
for (i=0; i<N; i++) {
#pragma omp for schedule(static) nowait
for (j=0; j<M; j++) {
REAL temp = 0.0;
for (w=0; w<K; w++)
temp += A[i*K+w]*B[w*M+j];
C[i*M+j] = temp;
}
}
} /* end of parallel */
}
/* Parallel For Row Column */
void mm_parallel_for_rowcol(int N, int K, int M, REAL * A, REAL * B, REAL * C, int num_tasks){
int i, j, w;
omp_set_num_threads(num_tasks);
#pragma omp parallel shared (N, K, M, A, B, C, num_tasks) private (i, j, w)
{
#pragma omp for collapse(2) schedule(static) nowait
for (i=0; i<N; i++) {
for (j=0; j<M; j++) {
REAL temp = 0.0;
for (w=0; w<K; w++)
temp += A[i*K+w]*B[w*M+j];
C[i*M+j] = temp;
}
}
} /* end of parallel */
}
|
residualbased_elimination_builder_and_solver_componentwise.h | // | / |
// ' / __| _` | __| _ \ __|
// . \ | ( | | ( |\__ `
// _|\_\_| \__,_|\__|\___/ ____/
// Multi-Physics
//
// License: BSD License
// Kratos default license: kratos/license.txt
//
// Main authors: Riccardo Rossi
//
//
#if !defined(KRATOS_RESIDUAL_BASED_ELIMINATION_BUILDER_AND_SOLVERCOMPONENTWISE )
#define KRATOS_RESIDUAL_BASED_ELIMINATION_BUILDER_AND_SOLVERCOMPONENTWISE
/* System includes */
#include <set>
#ifdef _OPENMP
#include <omp.h>
#endif
/* External includes */
/* Project includes */
#include "includes/define.h"
#include "solving_strategies/builder_and_solvers/residualbased_elimination_builder_and_solver.h"
namespace Kratos
{
/**@name Kratos Globals */
/*@{ */
/*@} */
/**@name Type Definitions */
/*@{ */
/*@} */
/**@name Enum's */
/*@{ */
/*@} */
/**@name Functions */
/*@{ */
/*@} */
/**@name Kratos Classes */
/*@{ */
/** Short class definition.
Detail class definition.
This is a specialization of the standard buliding strategy to the case in which a single variable is to be used in the
building.
the creation of the DofList and the construction of the system matrix is in this case much faster
as the neighborhood relationships are considered to be known
\URL[Example of use html]{ extended_documentation/no_ex_of_use.html}
\URL[Example of use pdf]{ extended_documentation/no_ex_of_use.pdf}
\URL[Example of use doc]{ extended_documentation/no_ex_of_use.doc}
\URL[Example of use ps]{ extended_documentation/no_ex_of_use.ps}
\URL[Extended documentation html]{ extended_documentation/no_ext_doc.html}
\URL[Extended documentation pdf]{ extended_documentation/no_ext_doc.pdf}
\URL[Extended documentation doc]{ extended_documentation/no_ext_doc.doc}
\URL[Extended documentation ps]{ extended_documentation/no_ext_doc.ps}
*/
template<class TSparseSpace,
class TDenseSpace ,
class TLinearSolver,
class TVariableType
>
class ResidualBasedEliminationBuilderAndSolverComponentwise
: public ResidualBasedEliminationBuilderAndSolver< TSparseSpace,TDenseSpace,TLinearSolver >
{
public:
/**@name Type Definitions */
/*@{ */
KRATOS_CLASS_POINTER_DEFINITION( ResidualBasedEliminationBuilderAndSolverComponentwise );
typedef BuilderAndSolver<TSparseSpace,TDenseSpace, TLinearSolver> BaseType;
typedef ResidualBasedEliminationBuilderAndSolver<TSparseSpace,TDenseSpace, TLinearSolver> ResidualBasedEliminationBuilderAndSolverType;
typedef typename BaseType::TSchemeType TSchemeType;
typedef typename BaseType::TDataType TDataType;
typedef typename BaseType::DofsArrayType DofsArrayType;
typedef typename BaseType::TSystemMatrixType TSystemMatrixType;
typedef typename BaseType::TSystemVectorType TSystemVectorType;
typedef typename BaseType::LocalSystemVectorType LocalSystemVectorType;
typedef typename BaseType::LocalSystemMatrixType LocalSystemMatrixType;
typedef typename BaseType::TSystemMatrixPointerType TSystemMatrixPointerType;
typedef typename BaseType::TSystemVectorPointerType TSystemVectorPointerType;
typedef typename BaseType::NodesArrayType NodesArrayType;
typedef typename BaseType::ElementsArrayType ElementsArrayType;
typedef typename BaseType::ConditionsArrayType ConditionsArrayType;
typedef typename BaseType::ElementsContainerType ElementsContainerType;
///@}
///@name Life Cycle
///@{
/**
* @brief Default constructor. (with parameters)
*/
explicit ResidualBasedEliminationBuilderAndSolverComponentwise(
typename TLinearSolver::Pointer pNewLinearSystemSolver,
Parameters ThisParameters
) : ResidualBasedEliminationBuilderAndSolverType(pNewLinearSystemSolver)
{
// Validate default parameters
Parameters default_parameters = Parameters(R"(
{
"components_wise_variable" : "SCALAR_VARIABLE_OR_COMPONENT"
})" );
ThisParameters.ValidateAndAssignDefaults(default_parameters);
rVar = KratosComponents<TVariableType>::Get(ThisParameters["components_wise_variable"].GetString());
}
/**
* @brief Default constructor. Constructor.
*/
explicit ResidualBasedEliminationBuilderAndSolverComponentwise(
typename TLinearSolver::Pointer pNewLinearSystemSolver,TVariableType const& Var)
: ResidualBasedEliminationBuilderAndSolverType(pNewLinearSystemSolver)
, rVar(Var)
{
/* std::cout << "using the standard builder and solver " << std::endl; */
}
/** Destructor.
*/
~ResidualBasedEliminationBuilderAndSolverComponentwise() override {}
/*@} */
/**@name Operators
*/
/*@{ */
//**************************************************************************
//**************************************************************************
void Build(
typename TSchemeType::Pointer pScheme,
ModelPart& r_model_part,
TSystemMatrixType& A,
TSystemVectorType& b) override
{
KRATOS_TRY
if(!pScheme)
KRATOS_THROW_ERROR(std::runtime_error, "No scheme provided!", "");
//getting the elements from the model
ElementsArrayType& pElements = r_model_part.Elements();
//getting the array of the conditions
ConditionsArrayType& ConditionsArray = r_model_part.Conditions();
//resetting to zero the vector of reactions
TSparseSpace::SetToZero( *(BaseType::mpReactionsVector) );
//create a partition of the element array
int number_of_threads = OpenMPUtils::GetNumThreads();
#ifdef _OPENMP
int A_size = A.size1();
//creating an array of lock variables of the size of the system matrix
std::vector< omp_lock_t > lock_array(A.size1());
for(int i = 0; i<A_size; i++)
omp_init_lock(&lock_array[i]);
#endif
DenseVector<unsigned int> element_partition;
CreatePartition(number_of_threads, pElements.size(), element_partition);
if (this->GetEchoLevel()>0)
{
KRATOS_WATCH( number_of_threads );
KRATOS_WATCH( element_partition );
}
double start_prod = OpenMPUtils::GetCurrentTime();
#pragma omp parallel for firstprivate(number_of_threads) schedule(static,1)
for(int k=0; k<number_of_threads; k++)
{
//contributions to the system
LocalSystemMatrixType LHS_Contribution = LocalSystemMatrixType(0,0);
LocalSystemVectorType RHS_Contribution = LocalSystemVectorType(0);
//vector containing the localization in the system of the different
//terms
Element::EquationIdVectorType EquationId;
ProcessInfo& CurrentProcessInfo = r_model_part.GetProcessInfo();
typename ElementsArrayType::ptr_iterator it_begin=pElements.ptr_begin()+element_partition[k];
typename ElementsArrayType::ptr_iterator it_end=pElements.ptr_begin()+element_partition[k+1];
unsigned int pos = (r_model_part.Nodes().begin())->GetDofPosition(rVar);
// assemble all elements
for (typename ElementsArrayType::ptr_iterator it=it_begin; it!=it_end; ++it)
{
//calculate elemental contribution
(*it)->InitializeNonLinearIteration(CurrentProcessInfo);
(*it)->CalculateLocalSystem(LHS_Contribution,RHS_Contribution,CurrentProcessInfo);
Geometry< Node<3> >& geom = (*it)->GetGeometry();
if(EquationId.size() != geom.size()) EquationId.resize(geom.size(),false);
for(unsigned int i=0; i<geom.size(); i++)
EquationId[i] = geom[i].GetDof(rVar,pos).EquationId();
//assemble the elemental contribution
#ifdef USE_LOCKS_IN_ASSEMBLY
this->Assemble(A,b,LHS_Contribution,RHS_Contribution,EquationId,lock_array);
#else
this->Assemble(A,b,LHS_Contribution,RHS_Contribution,EquationId);
#endif
}
}
DenseVector<unsigned int> condition_partition;
CreatePartition(number_of_threads, ConditionsArray.size(), condition_partition);
#pragma omp parallel for firstprivate(number_of_threads) schedule(static,1)
for(int k=0; k<number_of_threads; k++)
{
//contributions to the system
LocalSystemMatrixType LHS_Contribution = LocalSystemMatrixType(0,0);
LocalSystemVectorType RHS_Contribution = LocalSystemVectorType(0);
Condition::EquationIdVectorType EquationId;
ProcessInfo& CurrentProcessInfo = r_model_part.GetProcessInfo();
typename ConditionsArrayType::ptr_iterator it_begin=ConditionsArray.ptr_begin()+condition_partition[k];
typename ConditionsArrayType::ptr_iterator it_end=ConditionsArray.ptr_begin()+condition_partition[k+1];
unsigned int pos = (r_model_part.Nodes().begin())->GetDofPosition(rVar);
// A all elements
for (typename ConditionsArrayType::ptr_iterator it=it_begin; it!=it_end; ++it)
{
//calculate elemental contribution
(*it)->InitializeNonLinearIteration(CurrentProcessInfo);
(*it)->CalculateLocalSystem(LHS_Contribution,RHS_Contribution,CurrentProcessInfo);
Geometry< Node<3> >& geom = (*it)->GetGeometry();
if(EquationId.size() != geom.size()) EquationId.resize(geom.size(),false);
for(unsigned int i=0; i<geom.size(); i++)
{
EquationId[i] = geom[i].GetDof(rVar,pos).EquationId();
}
#ifdef USE_LOCKS_IN_ASSEMBLY
this->Assemble(A,b,LHS_Contribution,RHS_Contribution,EquationId,lock_array);
#else
this->Assemble(A,b,LHS_Contribution,RHS_Contribution,EquationId);
#endif
}
}
if (this->GetEchoLevel()>0)
{
double stop_prod = OpenMPUtils::GetCurrentTime();
std::cout << "parallel building time: " << stop_prod - start_prod << std::endl;
}
#ifdef _OPENMP
for(int i = 0; i<A_size; i++)
omp_destroy_lock(&lock_array[i]);
#endif
KRATOS_CATCH("")
}
//**************************************************************************
//**************************************************************************
void SetUpDofSet(
typename TSchemeType::Pointer pScheme,
ModelPart& r_model_part
) override
{
KRATOS_TRY
//fills a list of "active" nodes defined as nodes which have neighbours
// AND no fixed pressure
mActiveNodes.clear();
mActiveNodes.reserve(r_model_part.Nodes().size() );
for (typename NodesArrayType::iterator it=r_model_part.NodesBegin(); it!=r_model_part.NodesEnd(); ++it)
{
if( (it->GetValue(NEIGHBOUR_NODES)).size() != 0 )
{
mActiveNodes.push_back(*(it.base() ));
}
}
//fills the DofList and give a unique progressive tag to each node
BaseType::mDofSet.clear();
BaseType::mDofSet.reserve(mActiveNodes.size() );
for(WeakPointerVector< Node<3> >::iterator iii = mActiveNodes.begin(); iii!=mActiveNodes.end(); iii++)
{
BaseType::mDofSet.push_back( iii->pGetDof(rVar).get() );
}
//throws an execption if there are no Degrees of freedom involved in the analysis
if (BaseType::mDofSet.size()==0)
KRATOS_THROW_ERROR(std::logic_error, "No degrees of freedom!", "");
BaseType::mDofSetIsInitialized = true;
// If reactions are to be calculated, we check if all the dofs have reactions defined
// This is tobe done only in debug mode
#ifdef KRATOS_DEBUG
if(BaseType::GetCalculateReactionsFlag())
{
for(auto dof_iterator = BaseType::mDofSet.begin(); dof_iterator != BaseType::mDofSet.end(); ++dof_iterator)
{
KRATOS_ERROR_IF_NOT(dof_iterator->HasReaction()) << "Reaction variable not set for the following : " <<std::endl
<< "Node : "<<dof_iterator->Id()<< std::endl
<< "Dof : "<<(*dof_iterator)<<std::endl<<"Not possible to calculate reactions."<<std::endl;
}
}
#endif
KRATOS_CATCH("")
}
//**************************************************************************
//**************************************************************************
void ResizeAndInitializeVectors(
typename TSchemeType::Pointer pScheme,
TSystemMatrixPointerType& pA,
TSystemVectorPointerType& pDx,
TSystemVectorPointerType& pb,
ModelPart& rModelPart
) override
{
KRATOS_TRY
if(pA == NULL) //if the pointer is not initialized initialize it to an empty matrix
{
TSystemMatrixPointerType pNewA = TSystemMatrixPointerType(new TSystemMatrixType(0,0) );
pA.swap(pNewA);
}
if(pDx == NULL) //if the pointer is not initialized initialize it to an empty matrix
{
TSystemVectorPointerType pNewDx = TSystemVectorPointerType(new TSystemVectorType(0) );
pDx.swap(pNewDx);
}
if(pb == NULL) //if the pointer is not initialized initialize it to an empty matrix
{
TSystemVectorPointerType pNewb = TSystemVectorPointerType(new TSystemVectorType(0) );
pb.swap(pNewb);
}
if(BaseType::mpReactionsVector == NULL) //if the pointer is not initialized initialize it to an empty matrix
{
TSystemVectorPointerType pNewReactionsVector = TSystemVectorPointerType(new TSystemVectorType(0) );
BaseType::mpReactionsVector.swap(pNewReactionsVector);
}
TSystemMatrixType& A = *pA;
TSystemVectorType& Dx = *pDx;
TSystemVectorType& b = *pb;
//resizing the system vectors and matrix
if (A.size1() == 0 || BaseType::GetReshapeMatrixFlag() == true) //if the matrix is not initialized
{
A.resize(BaseType::mEquationSystemSize,BaseType::mEquationSystemSize,false);
#ifdef _OPENMP
ParallelConstructGraph(A);
#else
ConstructGraph(A);
#endif
}
else
{
if(A.size1() != BaseType::mEquationSystemSize || A.size2() != BaseType::mEquationSystemSize)
{
//KRATOS_WATCH("it should not come here!!!!!!!! ... this is SLOW");
KRATOS_ERROR <<"The equation system size has changed during the simulation. This is not permited."<<std::endl;
A.resize(BaseType::mEquationSystemSize,BaseType::mEquationSystemSize,true);
#ifdef _OPENMP
ParallelConstructGraph(A);
#else
ConstructGraph(A);
#endif
}
}
if(Dx.size() != BaseType::mEquationSystemSize)
Dx.resize(BaseType::mEquationSystemSize,false);
if(b.size() != BaseType::mEquationSystemSize)
b.resize(BaseType::mEquationSystemSize,false);
//
//if needed resize the vector for the calculation of reactions
if(BaseType::mCalculateReactionsFlag == true)
{
unsigned int ReactionsVectorSize = BaseType::mDofSet.size();
if(BaseType::mpReactionsVector->size() != ReactionsVectorSize)
BaseType::mpReactionsVector->resize(ReactionsVectorSize,false);
}
//swapping pointers
// pA.swap(pNewA);
// pDx.swap(pNewDx);
// pb.swap(pNewb);
#ifndef __SUNPRO_CC
KRATOS_CATCH("")
#endif
}
//**************************************************************************
//**************************************************************************
void Clear() override
{
this->mDofSet = DofsArrayType();
if(this->mpReactionsVector != NULL)
{
TSparseSpace::Clear( (this->mpReactionsVector) );
}
// *(this->mpReactionsVector) = TSystemVectorType();
if (this->GetEchoLevel()>1)
{
KRATOS_WATCH("ResidualBasedEliminationBuilderAndSolver Clear Function called");
}
}
/*@} */
/**@name Operations */
/*@{ */
/*@} */
/**@name Access */
/*@{ */
/*@} */
/**@name Inquiry */
/*@{ */
///@}
///@name Input and output
///@{
/// Turn back information as a string.
std::string Info() const override
{
return "ResidualBasedEliminationBuilderAndSolverComponentwise";
}
/// Print information about this object.
void PrintInfo(std::ostream& rOStream) const override
{
rOStream << Info();
}
/// Print object's data.
void PrintData(std::ostream& rOStream) const override
{
rOStream << Info();
}
/*@} */
/**@name Friends */
/*@{ */
/*@} */
protected:
/**@name Protected static Member Variables */
/*@{ */
/*@} */
/**@name Protected member Variables */
/*@{ */
/*@} */
/**@name Protected Operators*/
/*@{ */
//**************************************************************************
//**************************************************************************
//**************************************************************************
//**************************************************************************
void ConstructGraph(TSystemMatrixType& A)
{
KRATOS_TRY
std::vector< std::vector<int> > index_list(BaseType::mEquationSystemSize);
int total_size = 0;
unsigned int pos = (mActiveNodes.begin())->GetDofPosition(rVar);
//constructing the system matrix row by row
int index_i;
for(WeakPointerVector< Node<3> >::iterator in = mActiveNodes.begin();
in!=mActiveNodes.end(); in++)
{
const Node<3>::DofType& current_dof = in->GetDof(rVar,pos);
if( current_dof.IsFixed() == false)
{
index_i = (current_dof).EquationId();
WeakPointerVector< Node<3> >& neighb_nodes = in->GetValue(NEIGHBOUR_NODES);
std::vector<int>& indices = index_list[index_i];
indices.reserve(neighb_nodes.size()+1);
//filling the first neighbours list
indices.push_back(index_i);
for( WeakPointerVector< Node<3> >::iterator i = neighb_nodes.begin();
i != neighb_nodes.end(); i++)
{
const Node<3>::DofType& neighb_dof = i->GetDof(rVar,pos);
if(neighb_dof.IsFixed() == false )
{
int index_j = (neighb_dof).EquationId();
indices.push_back(index_j);
}
}
//sorting the indices and elminating the duplicates
std::sort(indices.begin(),indices.end());
typename std::vector<int>::iterator new_end = std::unique(indices.begin(),indices.end());
indices.erase(new_end,indices.end());
total_size += indices.size();
}
}
A.reserve(total_size,false);
//setting to zero the matrix (and the diagonal matrix)
for(unsigned int i=0; i<BaseType::mEquationSystemSize; i++)
{
std::vector<int>& indices = index_list[i];
for(unsigned int j=0; j<indices.size(); j++)
{
A.push_back(i,indices[j] , 0.00);
}
}
KRATOS_CATCH("")
}
//**************************************************************************
//**************************************************************************
//**************************************************************************
//**************************************************************************
#ifdef _OPENMP
void ParallelConstructGraph(TSystemMatrixType& A)
{
#ifndef __SUNPRO_CC
KRATOS_TRY
#endif
std::vector< std::vector<int> > index_list(BaseType::mEquationSystemSize);
int number_of_threads = omp_get_max_threads();
unsigned int pos = (mActiveNodes.begin())->GetDofPosition(rVar);
//constructing the system matrix row by row
DenseVector<unsigned int> partition;
DenseVector<unsigned int> local_sizes(number_of_threads);
for(int i=0; i<number_of_threads; i++)
local_sizes[i] = 0;
CreatePartition(number_of_threads, mActiveNodes.size(), partition);
#pragma omp parallel for firstprivate(number_of_threads,pos) schedule(static,1)
for(int k=0; k<number_of_threads; k++)
{
WeakPointerVector< Node<3> >::iterator it_begin = mActiveNodes.begin()+partition[k];
WeakPointerVector< Node<3> >::iterator it_end = mActiveNodes.begin()+partition[k+1];
for(WeakPointerVector< Node<3> >::iterator in = it_begin;
in!=it_end; in++)
{
const Node<3>::DofType& current_dof = in->GetDof(rVar,pos);
if( current_dof.IsFixed() == false)
{
int index_i = (current_dof).EquationId();
WeakPointerVector< Node<3> >& neighb_nodes = in->GetValue(NEIGHBOUR_NODES);
std::vector<int>& indices = index_list[index_i];
indices.reserve(neighb_nodes.size()+1);
//filling the first neighbours list
indices.push_back(index_i);
for( WeakPointerVector< Node<3> >::iterator i = neighb_nodes.begin();
i != neighb_nodes.end(); i++)
{
const Node<3>::DofType& neighb_dof = i->GetDof(rVar,pos);
if(neighb_dof.IsFixed() == false )
{
int index_j = (neighb_dof).EquationId();
indices.push_back(index_j);
}
}
//sorting the indices and elminating the duplicates
std::sort(indices.begin(),indices.end());
typename std::vector<int>::iterator new_end = std::unique(indices.begin(),indices.end());
indices.erase(new_end,indices.end());
local_sizes[k] += indices.size();
}
}
}
//calculate the total size of the system
int total_size = 0.0;
for(int i=0; i<number_of_threads; i++)
total_size += local_sizes[i];
A.reserve(total_size,false);
//setting to zero the matrix (and the diagonal matrix)
for(unsigned int i=0; i<BaseType::mEquationSystemSize; i++)
{
std::vector<int>& indices = index_list[i];
for(unsigned int j=0; j<indices.size(); j++)
{
A.push_back(i,indices[j] , 0.00);
}
}
#ifndef __SUNPRO_CC
KRATOS_CATCH("")
#endif
}
#endif
/*@} */
/**@name Protected Operations*/
/*@{ */
/*@} */
/**@name Protected Access */
/*@{ */
/*@} */
/**@name Protected Inquiry */
/*@{ */
/*@} */
/**@name Protected LifeCycle */
/*@{ */
/*@} */
private:
/**@name Static Member Variables */
/*@{ */
/*@} */
/**@name Member Variables */
/*@{ */
TVariableType const & rVar;
WeakPointerVector<Node<3> > mActiveNodes;
/*@} */
/**@name Private Operators*/
/*@{ */
//******************************************************************************************
//******************************************************************************************
inline void CreatePartition(unsigned int number_of_threads,const int number_of_rows, DenseVector<unsigned int>& partitions)
{
partitions.resize(number_of_threads+1);
int partition_size = number_of_rows / number_of_threads;
partitions[0] = 0;
partitions[number_of_threads] = number_of_rows;
for(unsigned int i = 1; i<number_of_threads; i++)
partitions[i] = partitions[i-1] + partition_size ;
}
/*@} */
/**@name Private Operations*/
/*@{ */
/*@} */
/**@name Private Access */
/*@{ */
/*@} */
/**@name Private Inquiry */
/*@{ */
/*@} */
/**@name Un accessible methods */
/*@{ */
/*@} */
}; /* Class ResidualBasedEliminationBuilderAndSolverComponentwise */
/*@} */
/**@name Type Definitions */
/*@{ */
/*@} */
} /* namespace Kratos.*/
#endif /* KRATOS_RESIDUAL_BASED_ELIMINATION_BUILDER_AND_SOLVERCOMPONENTWISE defined */
|
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"
#include "mace/kernels/fixpoint.h"
#include "mace/kernels/gemmlowp_util.h"
#include "mace/kernels/quantize.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;
}
};
static const int kInputDeltaIntBits = 5;
static const int kSumExpIntBits = 12;
template<>
struct SoftmaxFunctor<DeviceType::CPU, uint8_t> {
MaceStatus operator()(const Tensor *input,
Tensor *output,
StatsFuture *future) {
MACE_UNUSED(future);
// Ignore range stat, fix range to [0, 1]. For large depth, each softmax
// output may be too small (<<1), which causes precision issue. But it is
// fine when doing classification inference.
output->SetScale(1.f / 255);
output->SetZeroPoint(0);
using FixPointInputDelta = gemmlowp::FixedPoint<int32_t,
kInputDeltaIntBits>;
using FixPointSumExp = gemmlowp::FixedPoint<int32_t, kSumExpIntBits>;
using FixPoint0 = gemmlowp::FixedPoint<int32_t, 0>;
MACE_CHECK(input->dim_size() == 2 || input->dim_size() == 4,
"Softmax does not support dim size: ",
input->dim_size());
index_t batch;
index_t depth;
if (input->dim_size() == 2) {
batch = input->dim(0);
depth = input->dim(1);
} else {
batch = input->dim(0) * input->dim(1) * input->dim(2);
depth = input->dim(3);
}
Tensor::MappingGuard input_guard(input);
Tensor::MappingGuard output_guard(output);
const uint8_t *input_data = input->data<uint8_t>();
float input_scale = input->scale();
uint8_t *output_data = output->mutable_data<uint8_t>();
// If depth is short, do it using float32. Float computation should not
// be here, but as long as it is on CPU, it is fine.
if (depth < 32) {
#pragma omp parallel for
for (index_t b = 0; b < batch; ++b) {
const uint8_t *input_ptr = input_data + b * depth;
uint8_t *output_ptr = output_data + b * depth;
uint8_t max_value = FindMax(input_ptr, depth);
float sum = 0;
std::vector<float> depth_cache(depth);
for (index_t d = 0; d < depth; ++d) {
float exp_value = ::exp((static_cast<int>(input_ptr[d]) - max_value)
* input_scale);
sum += exp_value;
depth_cache[d] = exp_value;
}
sum = std::max(sum, std::numeric_limits<float>::min());
for (index_t d = 0; d < depth; ++d) {
double output_f = depth_cache[d] / sum;
output_ptr[d] = static_cast<uint8_t>(output_f * 255);
}
}
return MACE_SUCCESS;
}
int32_t scale_q = static_cast<int32_t>(std::min(
static_cast<double>(input_scale) * (1 << (31 - kInputDeltaIntBits)),
(1ll << 31) - 1.0));
int32_t input_delta_limit = -((1ll << 31) - 1) / scale_q;
#pragma omp parallel for
for (index_t b = 0; b < batch; ++b) {
const uint8_t *input_ptr = input_data + b * depth;
uint8_t *output_ptr = output_data + b * depth;
FixPointSumExp sum = FixPointSumExp::Zero();
uint8_t max_value = FindMax(input_ptr, depth);
index_t d = 0;
// Neon optimization is not useful so far as we benchmark.
// Enable it when we find a case that proves it useful.
#if 0 && defined(MACE_ENABLE_NEON)
using FixPointInputDeltaInt32x4 = gemmlowp::FixedPoint<int32x4_t,
kInputDeltaIntBits>;
using FixPointSumExpInt32x4 = gemmlowp::FixedPoint<int32x4_t,
kSumExpIntBits>;
using FixPoint0Int32x4 = gemmlowp::FixedPoint<int32x4_t, 0>;
int16x8_t vmax_value_s16 = vdupq_n_s16(max_value);
int32x4_t vinput_delta_limit_s32 = vdupq_n_s32(input_delta_limit);
FixPointSumExpInt32x4 vsum_s32_fp_0 = FixPointSumExpInt32x4::Zero();
FixPointSumExpInt32x4 vsum_s32_fp_1 = FixPointSumExpInt32x4::Zero();
FixPointSumExpInt32x4 vzero_s32_fp = FixPointSumExpInt32x4::Zero();
int32_t scale_q_multipler, scale_q_shift;
QuantizeMultiplier(scale_q, &scale_q_multipler, &scale_q_shift);
FixPointInputDeltaInt32x4 vscale_s32_fp =
FixPointInputDeltaInt32x4::FromScalarRaw(scale_q);
FixPoint0Int32x4 vscale_s32_fp_multiplier =
FixPoint0Int32x4::FromScalarRaw(scale_q_multipler);
for (; d <= depth - 8; d += 8) {
uint16x8_t vinput_u16 = vmovl_u8(vld1_u8(input_ptr + d));
int16x8_t vinput_delta_s16 =
vsubq_s16(vreinterpretq_s16_u16(vinput_u16), vmax_value_s16);
int32x4_t input_delta_s32_0 = vmovl_s16(vget_low_s16(vinput_delta_s16));
int32x4_t
input_delta_s32_1 = vmovl_s16(vget_high_s16(vinput_delta_s16));
int32x4_t vmask_s32_0 =
gemmlowp::MaskIfGreaterThanOrEqual(input_delta_s32_0,
vinput_delta_limit_s32);
int32x4_t vmask_s32_1 =
gemmlowp::MaskIfGreaterThanOrEqual(input_delta_s32_1,
vinput_delta_limit_s32);
FixPointInputDeltaInt32x4
vscaled_input_delta_s32_fp_0 = vscale_s32_fp_multiplier *
FixPointInputDeltaInt32x4::FromRaw(
gemmlowp::ShiftLeft(input_delta_s32_0, scale_q_shift));
FixPointInputDeltaInt32x4
vscaled_input_delta_s32_fp_1 = vscale_s32_fp_multiplier *
FixPointInputDeltaInt32x4::FromRaw(
gemmlowp::ShiftLeft(input_delta_s32_1, scale_q_shift));
FixPointSumExpInt32x4 vexp_s32_fp_0 = gemmlowp::Rescale<kSumExpIntBits>(
exp_on_negative_values(vscaled_input_delta_s32_fp_0));
FixPointSumExpInt32x4 vexp_s32_fp_1 = gemmlowp::Rescale<kSumExpIntBits>(
exp_on_negative_values(vscaled_input_delta_s32_fp_1));
FixPointSumExpInt32x4 vmasked_exp_s32_fp_0 =
SelectUsingMask(vmask_s32_0, vexp_s32_fp_0, vzero_s32_fp);
FixPointSumExpInt32x4 vmasked_exp_s32_fp_1 =
SelectUsingMask(vmask_s32_1, vexp_s32_fp_1, vzero_s32_fp);
vsum_s32_fp_0 = vsum_s32_fp_0 + vmasked_exp_s32_fp_0;
vsum_s32_fp_1 = vsum_s32_fp_1 + vmasked_exp_s32_fp_1;
}
int32x4_t vsum_s32 = (vsum_s32_fp_0 + vsum_s32_fp_1).raw();
int32x2_t vsum_reduced_2_s32 =
vadd_s32(vget_low_s32(vsum_s32), vget_high_s32(vsum_s32));
int32x2_t vsum_reduced_1_s32 =
vpadd_s32(vsum_reduced_2_s32, vsum_reduced_2_s32);
sum = FixPointSumExp::FromRaw(vget_lane_s32(vsum_reduced_1_s32, 0));
#endif
for (; d < depth; ++d) {
int32_t input_delta = static_cast<int32_t>(input_ptr[d]) - max_value;
if (input_delta >= input_delta_limit) {
int32_t scaled_input_delta_q = scale_q * input_delta;
FixPointInputDelta scaled_input_delta_fp =
FixPointInputDelta::FromRaw(scaled_input_delta_q);
sum = sum + gemmlowp::Rescale<kSumExpIntBits>(
exp_on_negative_values(scaled_input_delta_fp));
}
}
int32_t sum_q = sum.raw();
int left_zero_count =
__builtin_clz(static_cast<uint32_t>(sum_q));
int tail_count = kSumExpIntBits - left_zero_count;
int32_t fractional_q0 = static_cast<int32_t>(
(static_cast<uint32_t>(sum_q) << left_zero_count) -
(static_cast<uint32_t>(1) << 31));
FixPoint0 recip_sum_q0 = gemmlowp::one_over_one_plus_x_for_x_in_0_1(
FixPoint0::FromRaw(fractional_q0));
d = 0;
// Neon optimization is not useful so far as we benchmark.
// Enable it when we find a case that proves it useful.
#if 0 && defined(MACE_ENABLE_NEON)
FixPoint0Int32x4 vrecip_sum_q0_s32_fp =
FixPoint0Int32x4::FromScalarRaw(recip_sum_q0.raw());
int16x8_t vinput_delta_limit_s16 = vdupq_n_s16(input_delta_limit);
for (; d <= depth - 8; d += 8) {
uint16x8_t vinput_u16 = vmovl_u8(vld1_u8(input_ptr + d));
int16x8_t vinput_delta_s16 =
vsubq_s16(vreinterpretq_s16_u16(vinput_u16), vmax_value_s16);
int32x4_t input_delta_s32_0 = vmovl_s16(vget_low_s16(vinput_delta_s16));
int32x4_t
input_delta_s32_1 = vmovl_s16(vget_high_s16(vinput_delta_s16));
int16x8_t vmask_s16 = gemmlowp::MaskIfGreaterThanOrEqual(
vinput_delta_s16,
vinput_delta_limit_s16);
FixPointInputDeltaInt32x4
vscaled_input_delta_s32_fp_0 = vscale_s32_fp_multiplier *
FixPointInputDeltaInt32x4::FromRaw(
gemmlowp::ShiftLeft(input_delta_s32_0, scale_q_shift));
FixPointInputDeltaInt32x4
vscaled_input_delta_s32_fp_1 = vscale_s32_fp_multiplier *
FixPointInputDeltaInt32x4::FromRaw(
gemmlowp::ShiftLeft(input_delta_s32_1, scale_q_shift));
FixPoint0Int32x4 vexp_s32_fp_0 =
exp_on_negative_values(vscaled_input_delta_s32_fp_0);
FixPoint0Int32x4 vexp_s32_fp_1 =
exp_on_negative_values(vscaled_input_delta_s32_fp_1);
int32x4_t voutput_data_s32_0 = gemmlowp::RoundingDivideByPOT(
(vrecip_sum_q0_s32_fp * vexp_s32_fp_0).raw(), tail_count + 31 - 8);
int32x4_t voutput_data_s32_1 = gemmlowp::RoundingDivideByPOT(
(vrecip_sum_q0_s32_fp * vexp_s32_fp_1).raw(), tail_count + 31 - 8);
int16x8_t voutput_data_s16 =
vcombine_s16(vqmovn_s32(voutput_data_s32_0),
vqmovn_s32(voutput_data_s32_1));
int16x8_t masked_voutput_data_s16 =
gemmlowp::SelectUsingMask(vmask_s16,
voutput_data_s16,
vdupq_n_s16(0));
uint8x8_t voutput_u8 = vqmovun_s16(masked_voutput_data_s16);
vst1_u8(output_ptr + d, voutput_u8);
}
#endif
for (; d < depth; ++d) {
int32_t input_delta = static_cast<int32_t>(input_ptr[d]) - max_value;
if (input_delta >= input_delta_limit) {
int32_t scaled_input_delta_q = scale_q * input_delta;
FixPointInputDelta scaled_input_delta_fp =
FixPointInputDelta::FromRaw(scaled_input_delta_q);
FixPoint0 exp = exp_on_negative_values(scaled_input_delta_fp);
int32_t output_data = gemmlowp::RoundingDivideByPOT(
(recip_sum_q0 * exp).raw(), tail_count + 31 - 8);
output_ptr[d] = std::max(std::min(output_data, 255), 0);
}
}
}
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_
|
NeighborhoodGraph.h | // Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
#ifndef _SPTAG_COMMON_NG_H_
#define _SPTAG_COMMON_NG_H_
#include "../VectorIndex.h"
#include "CommonUtils.h"
#include "Dataset.h"
#include "FineGrainedLock.h"
#include "QueryResultSet.h"
namespace SPTAG
{
namespace COMMON
{
class NeighborhoodGraph
{
public:
NeighborhoodGraph(): m_iTPTNumber(32),
m_iTPTLeafSize(2000),
m_iSamples(1000),
m_numTopDimensionTPTSplit(5),
m_iNeighborhoodSize(32),
m_iNeighborhoodScale(2),
m_iCEFScale(2),
m_iRefineIter(0),
m_iCEF(1000),
m_iMaxCheckForRefineGraph(10000)
{
m_pNeighborhoodGraph.SetName("Graph");
}
~NeighborhoodGraph() {}
virtual void InsertNeighbors(VectorIndex* index, const SizeType node, SizeType insertNode, float insertDist) = 0;
virtual void RebuildNeighbors(VectorIndex* index, const SizeType node, SizeType* nodes, const BasicResult* queryResults, const int numResults) = 0;
virtual float GraphAccuracyEstimation(VectorIndex* index, const SizeType samples, const std::unordered_map<SizeType, SizeType>* idmap = nullptr) = 0;
template <typename T>
void BuildGraph(VectorIndex* index, const std::unordered_map<SizeType, SizeType>* idmap = nullptr)
{
std::cout << "build RNG graph!" << std::endl;
m_iGraphSize = index->GetNumSamples();
m_iNeighborhoodSize = m_iNeighborhoodSize * m_iNeighborhoodScale;
m_pNeighborhoodGraph.Initialize(m_iGraphSize, m_iNeighborhoodSize);
m_dataUpdateLock.resize(m_iGraphSize);
if (m_iGraphSize < 1000) {
RefineGraph<T>(index, idmap);
std::cout << "Build RNG Graph end!" << std::endl;
return;
}
{
COMMON::Dataset<float> NeighborhoodDists(m_iGraphSize, m_iNeighborhoodSize);
std::vector<std::vector<SizeType>> TptreeDataIndices(m_iTPTNumber, std::vector<SizeType>(m_iGraphSize));
std::vector<std::vector<std::pair<SizeType, SizeType>>> TptreeLeafNodes(m_iTPTNumber, std::vector<std::pair<SizeType, SizeType>>());
for (SizeType i = 0; i < m_iGraphSize; i++)
for (DimensionType j = 0; j < m_iNeighborhoodSize; j++)
(NeighborhoodDists)[i][j] = MaxDist;
std::cout << "Parallel TpTree Partition begin " << std::endl;
#pragma omp parallel for schedule(dynamic)
for (int i = 0; i < m_iTPTNumber; i++)
{
Sleep(i * 100); std::srand(clock());
for (SizeType j = 0; j < m_iGraphSize; j++) TptreeDataIndices[i][j] = j;
std::random_shuffle(TptreeDataIndices[i].begin(), TptreeDataIndices[i].end());
PartitionByTptree<T>(index, TptreeDataIndices[i], 0, m_iGraphSize - 1, TptreeLeafNodes[i]);
std::cout << "Finish Getting Leaves for Tree " << i << std::endl;
}
std::cout << "Parallel TpTree Partition done" << std::endl;
for (int i = 0; i < m_iTPTNumber; i++)
{
#pragma omp parallel for schedule(dynamic)
for (SizeType j = 0; j < (SizeType)TptreeLeafNodes[i].size(); j++)
{
SizeType start_index = TptreeLeafNodes[i][j].first;
SizeType end_index = TptreeLeafNodes[i][j].second;
if (omp_get_thread_num() == 0) std::cout << "\rProcessing Tree " << i << ' ' << j * 100 / TptreeLeafNodes[i].size() << '%';
for (SizeType x = start_index; x < end_index; x++)
{
for (SizeType y = x + 1; y <= end_index; y++)
{
SizeType p1 = TptreeDataIndices[i][x];
SizeType p2 = TptreeDataIndices[i][y];
float dist = index->ComputeDistance(index->GetSample(p1), index->GetSample(p2));
if (idmap != nullptr) {
p1 = (idmap->find(p1) == idmap->end()) ? p1 : idmap->at(p1);
p2 = (idmap->find(p2) == idmap->end()) ? p2 : idmap->at(p2);
}
COMMON::Utils::AddNeighbor(p2, dist, (m_pNeighborhoodGraph)[p1], (NeighborhoodDists)[p1], m_iNeighborhoodSize);
COMMON::Utils::AddNeighbor(p1, dist, (m_pNeighborhoodGraph)[p2], (NeighborhoodDists)[p2], m_iNeighborhoodSize);
}
}
}
TptreeDataIndices[i].clear();
TptreeLeafNodes[i].clear();
std::cout << std::endl;
}
TptreeDataIndices.clear();
TptreeLeafNodes.clear();
}
if (m_iMaxCheckForRefineGraph > 0) {
RefineGraph<T>(index, idmap);
}
}
template <typename T>
void RefineGraph(VectorIndex* index, const std::unordered_map<SizeType, SizeType>* idmap = nullptr)
{
std::cout << "before RNG, graph acc:" << GraphAccuracyEstimation(index, 100, idmap) << std::endl;
m_iCEF *= m_iCEFScale;
m_iMaxCheckForRefineGraph *= m_iCEFScale;
#pragma omp parallel for schedule(dynamic)
for (SizeType i = 0; i < m_iGraphSize; i++)
{
RefineNode<T>(index, i, false);
if (i % 1000 == 0) std::cout << "\rRefine 1 " << (i * 100 / m_iGraphSize) << "%";
}
std::cout << "Refine RNG, graph acc:" << GraphAccuracyEstimation(index, 100, idmap) << std::endl;
m_iCEF /= m_iCEFScale;
m_iMaxCheckForRefineGraph /= m_iCEFScale;
m_iNeighborhoodSize /= m_iNeighborhoodScale;
#pragma omp parallel for schedule(dynamic)
for (SizeType i = 0; i < m_iGraphSize; i++)
{
RefineNode<T>(index, i, false);
if (i % 1000 == 0) std::cout << "\rRefine 2 " << (i * 100 / m_iGraphSize) << "%";
}
std::cout << "Refine RNG, graph acc:" << GraphAccuracyEstimation(index, 100, idmap) << std::endl;
if (idmap != nullptr) {
for (auto iter = idmap->begin(); iter != idmap->end(); iter++)
if (iter->first < 0)
{
m_pNeighborhoodGraph[-1 - iter->first][m_iNeighborhoodSize - 1] = -2 - iter->second;
}
}
}
template <typename T>
ErrorCode RefineGraph(VectorIndex* index, std::vector<SizeType>& indices, std::vector<SizeType>& reverseIndices,
std::ostream& output, const std::unordered_map<SizeType, SizeType>* idmap = nullptr)
{
SizeType R = (SizeType)indices.size();
#pragma omp parallel for schedule(dynamic)
for (SizeType i = 0; i < R; i++)
{
RefineNode<T>(index, indices[i], false);
SizeType* nodes = m_pNeighborhoodGraph[indices[i]];
for (DimensionType j = 0; j < m_iNeighborhoodSize; j++)
{
if (nodes[j] < 0) nodes[j] = -1;
else nodes[j] = reverseIndices[nodes[j]];
}
if (idmap == nullptr || idmap->find(-1 - indices[i]) == idmap->end()) continue;
nodes[m_iNeighborhoodSize - 1] = -2 - idmap->at(-1 - indices[i]);
}
m_pNeighborhoodGraph.Refine(indices, output);
return ErrorCode::Success;
}
template <typename T>
void RefineNode(VectorIndex* index, const SizeType node, bool updateNeighbors)
{
COMMON::QueryResultSet<T> query((const T*)index->GetSample(node), m_iCEF + 1);
index->SearchIndex(query);
RebuildNeighbors(index, node, m_pNeighborhoodGraph[node], query.GetResults(), m_iCEF + 1);
if (updateNeighbors) {
// update neighbors
for (int j = 0; j <= m_iCEF; j++)
{
BasicResult* item = query.GetResult(j);
if (item->VID < 0) break;
if (item->VID == node) continue;
std::lock_guard<std::mutex> lock(m_dataUpdateLock[item->VID]);
InsertNeighbors(index, item->VID, node, item->Dist);
}
}
}
template <typename T>
void PartitionByTptree(VectorIndex* index, std::vector<SizeType>& indices, const SizeType first, const SizeType last,
std::vector<std::pair<SizeType, SizeType>> & leaves)
{
if (last - first <= m_iTPTLeafSize)
{
leaves.push_back(std::make_pair(first, last));
}
else
{
std::vector<float> Mean(index->GetFeatureDim(), 0);
int iIteration = 100;
SizeType end = min(first + m_iSamples, last);
SizeType count = end - first + 1;
// calculate the mean of each dimension
for (SizeType j = first; j <= end; j++)
{
const T* v = (const T*)index->GetSample(indices[j]);
for (DimensionType k = 0; k < index->GetFeatureDim(); k++)
{
Mean[k] += v[k];
}
}
for (DimensionType k = 0; k < index->GetFeatureDim(); k++)
{
Mean[k] /= count;
}
std::vector<BasicResult> Variance;
Variance.reserve(index->GetFeatureDim());
for (DimensionType j = 0; j < index->GetFeatureDim(); j++)
{
Variance.push_back(BasicResult(j, 0));
}
// calculate the variance of each dimension
for (SizeType j = first; j <= end; j++)
{
const T* v = (const T*)index->GetSample(indices[j]);
for (DimensionType k = 0; k < index->GetFeatureDim(); k++)
{
float dist = v[k] - Mean[k];
Variance[k].Dist += dist*dist;
}
}
std::sort(Variance.begin(), Variance.end(), COMMON::Compare);
std::vector<SizeType> indexs(m_numTopDimensionTPTSplit);
std::vector<float> weight(m_numTopDimensionTPTSplit), bestweight(m_numTopDimensionTPTSplit);
float bestvariance = Variance[index->GetFeatureDim() - 1].Dist;
for (int i = 0; i < m_numTopDimensionTPTSplit; i++)
{
indexs[i] = Variance[index->GetFeatureDim() - 1 - i].VID;
bestweight[i] = 0;
}
bestweight[0] = 1;
float bestmean = Mean[indexs[0]];
std::vector<float> Val(count);
for (int i = 0; i < iIteration; i++)
{
float sumweight = 0;
for (int j = 0; j < m_numTopDimensionTPTSplit; j++)
{
weight[j] = float(rand() % 10000) / 5000.0f - 1.0f;
sumweight += weight[j] * weight[j];
}
sumweight = sqrt(sumweight);
for (int j = 0; j < m_numTopDimensionTPTSplit; j++)
{
weight[j] /= sumweight;
}
float mean = 0;
for (SizeType j = 0; j < count; j++)
{
Val[j] = 0;
const T* v = (const T*)index->GetSample(indices[first + j]);
for (int k = 0; k < m_numTopDimensionTPTSplit; k++)
{
Val[j] += weight[k] * v[indexs[k]];
}
mean += Val[j];
}
mean /= count;
float var = 0;
for (SizeType j = 0; j < count; j++)
{
float dist = Val[j] - mean;
var += dist * dist;
}
if (var > bestvariance)
{
bestvariance = var;
bestmean = mean;
for (int j = 0; j < m_numTopDimensionTPTSplit; j++)
{
bestweight[j] = weight[j];
}
}
}
SizeType i = first;
SizeType j = last;
// decide which child one point belongs
while (i <= j)
{
float val = 0;
const T* v = (const T*)index->GetSample(indices[i]);
for (int k = 0; k < m_numTopDimensionTPTSplit; k++)
{
val += bestweight[k] * v[indexs[k]];
}
if (val < bestmean)
{
i++;
}
else
{
std::swap(indices[i], indices[j]);
j--;
}
}
// if all the points in the node are equal,equally split the node into 2
if ((i == first) || (i == last + 1))
{
i = (first + last + 1) / 2;
}
Mean.clear();
Variance.clear();
Val.clear();
indexs.clear();
weight.clear();
bestweight.clear();
PartitionByTptree<T>(index, indices, first, i - 1, leaves);
PartitionByTptree<T>(index, indices, i, last, leaves);
}
}
inline std::uint64_t BufferSize() const
{
return m_pNeighborhoodGraph.BufferSize();
}
bool LoadGraph(std::string sGraphFilename)
{
if (!m_pNeighborhoodGraph.Load(sGraphFilename)) return false;
m_iGraphSize = m_pNeighborhoodGraph.R();
m_iNeighborhoodSize = m_pNeighborhoodGraph.C();
m_dataUpdateLock.resize(m_iGraphSize);
return true;
}
bool LoadGraph(char* pGraphMemFile)
{
m_pNeighborhoodGraph.Load(pGraphMemFile);
m_iGraphSize = m_pNeighborhoodGraph.R();
m_iNeighborhoodSize = m_pNeighborhoodGraph.C();
m_dataUpdateLock.resize(m_iGraphSize);
return true;
}
bool SaveGraph(std::string sGraphFilename) const
{
return m_pNeighborhoodGraph.Save(sGraphFilename);
}
bool SaveGraph(std::ostream& output) const
{
return m_pNeighborhoodGraph.Save(output);
}
inline ErrorCode AddBatch(SizeType num)
{
ErrorCode ret = m_pNeighborhoodGraph.AddBatch(num);
if (ret != ErrorCode::Success) return ret;
m_iGraphSize += num;
m_dataUpdateLock.resize(m_iGraphSize);
return ErrorCode::Success;
}
inline SizeType* operator[](SizeType index) { return m_pNeighborhoodGraph[index]; }
inline const SizeType* operator[](SizeType index) const { return m_pNeighborhoodGraph[index]; }
inline void SetR(SizeType rows) { m_pNeighborhoodGraph.SetR(rows); m_iGraphSize = rows; m_dataUpdateLock.resize(m_iGraphSize); }
inline SizeType R() const { return m_iGraphSize; }
static std::shared_ptr<NeighborhoodGraph> CreateInstance(std::string type);
protected:
// Graph structure
SizeType m_iGraphSize;
COMMON::Dataset<SizeType> m_pNeighborhoodGraph;
COMMON::FineGrainedLock m_dataUpdateLock; // protect one row of the graph
public:
int m_iTPTNumber, m_iTPTLeafSize, m_iSamples, m_numTopDimensionTPTSplit;
DimensionType m_iNeighborhoodSize;
int m_iNeighborhoodScale, m_iCEFScale, m_iRefineIter, m_iCEF, m_iMaxCheckForRefineGraph;
};
}
}
#endif
|
updater_basemaker-inl.h | /*!
* Copyright 2014 by Contributors
* \file updater_basemaker-inl.h
* \brief implement a common tree constructor
* \author Tianqi Chen
*/
#ifndef XGBOOST_TREE_UPDATER_BASEMAKER_INL_H_
#define XGBOOST_TREE_UPDATER_BASEMAKER_INL_H_
#include <xgboost/base.h>
#include <xgboost/tree_updater.h>
#include <vector>
#include <algorithm>
#include <string>
#include <limits>
#include <utility>
#include "./param.h"
#include "../common/sync.h"
#include "../common/io.h"
#include "../common/random.h"
#include "../common/quantile.h"
namespace xgboost {
namespace tree {
/*!
* \brief base tree maker class that defines common operation
* needed in tree making
*/
class BaseMaker: public TreeUpdater {
public:
void Init(const std::vector<std::pair<std::string, std::string> >& args) override {
param_.InitAllowUnknown(args);
}
protected:
// helper to collect and query feature meta information
struct FMetaHelper {
public:
/*! \brief find type of each feature, use column format */
inline void InitByCol(DMatrix* p_fmat,
const RegTree& tree) {
fminmax_.resize(tree.param.num_feature * 2);
std::fill(fminmax_.begin(), fminmax_.end(),
-std::numeric_limits<bst_float>::max());
// start accumulating statistics
auto iter = p_fmat->ColIterator();
iter->BeforeFirst();
while (iter->Next()) {
auto &batch = iter->Value();
for (bst_uint fid = 0; fid < batch.Size(); ++fid) {
auto c = batch[fid];
if (c.length != 0) {
fminmax_[fid * 2 + 0] = std::max(-c[0].fvalue, fminmax_[fid * 2 + 0]);
fminmax_[fid * 2 + 1] = std::max(c[c.length - 1].fvalue, fminmax_[fid * 2 + 1]);
}
}
}
}
/*! \brief synchronize the information */
inline void SyncInfo() {
rabit::Allreduce<rabit::op::Max>(dmlc::BeginPtr(fminmax_), fminmax_.size());
}
// get feature type, 0:empty 1:binary 2:real
inline int Type(bst_uint fid) const {
CHECK_LT(fid * 2 + 1, fminmax_.size())
<< "FeatHelper fid exceed query bound ";
bst_float a = fminmax_[fid * 2];
bst_float b = fminmax_[fid * 2 + 1];
if (a == -std::numeric_limits<bst_float>::max()) return 0;
if (-a == b) {
return 1;
} else {
return 2;
}
}
inline bst_float MaxValue(bst_uint fid) const {
return fminmax_[fid *2 + 1];
}
inline void SampleCol(float p, std::vector<bst_uint> *p_findex) const {
std::vector<bst_uint> &findex = *p_findex;
findex.clear();
for (size_t i = 0; i < fminmax_.size(); i += 2) {
const auto fid = static_cast<bst_uint>(i / 2);
if (this->Type(fid) != 0) findex.push_back(fid);
}
auto n = static_cast<unsigned>(p * findex.size());
std::shuffle(findex.begin(), findex.end(), common::GlobalRandom());
findex.resize(n);
// sync the findex if it is subsample
std::string s_cache;
common::MemoryBufferStream fc(&s_cache);
dmlc::Stream& fs = fc;
if (rabit::GetRank() == 0) {
fs.Write(findex);
}
rabit::Broadcast(&s_cache, 0);
fs.Read(&findex);
}
private:
std::vector<bst_float> fminmax_;
};
// ------static helper functions ------
// helper function to get to next level of the tree
/*! \brief this is helper function for row based data*/
inline static int NextLevel(const SparsePage::Inst &inst, const RegTree &tree, int nid) {
const RegTree::Node &n = tree[nid];
bst_uint findex = n.SplitIndex();
for (unsigned i = 0; i < inst.length; ++i) {
if (findex == inst[i].index) {
if (inst[i].fvalue < n.SplitCond()) {
return n.LeftChild();
} else {
return n.RightChild();
}
}
}
return n.DefaultChild();
}
// ------class member helpers---------
/*! \brief initialize temp data structure */
inline void InitData(const std::vector<GradientPair> &gpair,
const DMatrix &fmat,
const RegTree &tree) {
CHECK_EQ(tree.param.num_nodes, tree.param.num_roots)
<< "TreeMaker: can only grow new tree";
const std::vector<unsigned> &root_index = fmat.Info().root_index_;
{
// setup position
position_.resize(gpair.size());
if (root_index.size() == 0) {
std::fill(position_.begin(), position_.end(), 0);
} else {
for (size_t i = 0; i < position_.size(); ++i) {
position_[i] = root_index[i];
CHECK_LT(root_index[i], (unsigned)tree.param.num_roots)
<< "root index exceed setting";
}
}
// mark delete for the deleted datas
for (size_t i = 0; i < position_.size(); ++i) {
if (gpair[i].GetHess() < 0.0f) position_[i] = ~position_[i];
}
// mark subsample
if (param_.subsample < 1.0f) {
std::bernoulli_distribution coin_flip(param_.subsample);
auto& rnd = common::GlobalRandom();
for (size_t i = 0; i < position_.size(); ++i) {
if (gpair[i].GetHess() < 0.0f) continue;
if (!coin_flip(rnd)) position_[i] = ~position_[i];
}
}
}
{
// expand query
qexpand_.reserve(256); qexpand_.clear();
for (int i = 0; i < tree.param.num_roots; ++i) {
qexpand_.push_back(i);
}
this->UpdateNode2WorkIndex(tree);
}
}
/*! \brief update queue expand add in new leaves */
inline void UpdateQueueExpand(const RegTree &tree) {
std::vector<int> newnodes;
for (int nid : qexpand_) {
if (!tree[nid].IsLeaf()) {
newnodes.push_back(tree[nid].LeftChild());
newnodes.push_back(tree[nid].RightChild());
}
}
// use new nodes for qexpand
qexpand_ = newnodes;
this->UpdateNode2WorkIndex(tree);
}
// return decoded position
inline int DecodePosition(bst_uint ridx) const {
const int pid = position_[ridx];
return pid < 0 ? ~pid : pid;
}
// encode the encoded position value for ridx
inline void SetEncodePosition(bst_uint ridx, int nid) {
if (position_[ridx] < 0) {
position_[ridx] = ~nid;
} else {
position_[ridx] = nid;
}
}
/*!
* \brief this is helper function uses column based data structure,
* reset the positions to the lastest one
* \param nodes the set of nodes that contains the split to be used
* \param p_fmat feature matrix needed for tree construction
* \param tree the regression tree structure
*/
inline void ResetPositionCol(const std::vector<int> &nodes,
DMatrix *p_fmat,
const RegTree &tree) {
// set the positions in the nondefault
this->SetNonDefaultPositionCol(nodes, p_fmat, tree);
this->SetDefaultPostion(p_fmat, tree);
}
/*!
* \brief helper function to set the non-leaf positions to default direction.
* This function can be applied multiple times and will get the same result.
* \param p_fmat feature matrix needed for tree construction
* \param tree the regression tree structure
*/
inline void SetDefaultPostion(DMatrix *p_fmat,
const RegTree &tree) {
// set rest of instances to default position
const RowSet &rowset = p_fmat->BufferedRowset();
// set default direct nodes to default
// for leaf nodes that are not fresh, mark then to ~nid,
// so that they are ignored in future statistics collection
const auto ndata = static_cast<bst_omp_uint>(rowset.Size());
#pragma omp parallel for schedule(static)
for (bst_omp_uint i = 0; i < ndata; ++i) {
const bst_uint ridx = rowset[i];
const int nid = this->DecodePosition(ridx);
if (tree[nid].IsLeaf()) {
// mark finish when it is not a fresh leaf
if (tree[nid].RightChild() == -1) {
position_[ridx] = ~nid;
}
} else {
// push to default branch
if (tree[nid].DefaultLeft()) {
this->SetEncodePosition(ridx, tree[nid].LeftChild());
} else {
this->SetEncodePosition(ridx, tree[nid].RightChild());
}
}
}
}
/*!
* \brief this is helper function uses column based data structure,
* to CORRECT the positions of non-default directions that WAS set to default
* before calling this function.
* \param batch The column batch
* \param sorted_split_set The set of index that contains split solutions.
* \param tree the regression tree structure
*/
inline void CorrectNonDefaultPositionByBatch(
const SparsePage &batch, const std::vector<bst_uint> &sorted_split_set,
const RegTree &tree) {
for (size_t fid = 0; fid < batch.Size(); ++fid) {
auto col = batch[fid];
auto it = std::lower_bound(sorted_split_set.begin(), sorted_split_set.end(), fid);
if (it != sorted_split_set.end() && *it == fid) {
const auto ndata = static_cast<bst_omp_uint>(col.length);
#pragma omp parallel for schedule(static)
for (bst_omp_uint j = 0; j < ndata; ++j) {
const bst_uint ridx = col[j].index;
const bst_float fvalue = col[j].fvalue;
const int nid = this->DecodePosition(ridx);
CHECK(tree[nid].IsLeaf());
int pid = tree[nid].Parent();
// go back to parent, correct those who are not default
if (!tree[nid].IsRoot() && tree[pid].SplitIndex() == fid) {
if (fvalue < tree[pid].SplitCond()) {
this->SetEncodePosition(ridx, tree[pid].LeftChild());
} else {
this->SetEncodePosition(ridx, tree[pid].RightChild());
}
}
}
}
}
}
/*!
* \brief this is helper function uses column based data structure,
* \param nodes the set of nodes that contains the split to be used
* \param tree the regression tree structure
* \param out_split_set The split index set
*/
inline void GetSplitSet(const std::vector<int> &nodes,
const RegTree &tree,
std::vector<unsigned>* out_split_set) {
std::vector<unsigned>& fsplits = *out_split_set;
fsplits.clear();
// step 1, classify the non-default data into right places
for (int nid : nodes) {
if (!tree[nid].IsLeaf()) {
fsplits.push_back(tree[nid].SplitIndex());
}
}
std::sort(fsplits.begin(), fsplits.end());
fsplits.resize(std::unique(fsplits.begin(), fsplits.end()) - fsplits.begin());
}
/*!
* \brief this is helper function uses column based data structure,
* update all positions into nondefault branch, if any, ignore the default branch
* \param nodes the set of nodes that contains the split to be used
* \param p_fmat feature matrix needed for tree construction
* \param tree the regression tree structure
*/
virtual void SetNonDefaultPositionCol(const std::vector<int> &nodes,
DMatrix *p_fmat,
const RegTree &tree) {
std::vector<unsigned> fsplits;
this->GetSplitSet(nodes, tree, &fsplits);
auto iter = p_fmat->ColIterator();
while (iter->Next()) {
auto &batch = iter->Value();
for (auto fid : fsplits) {
auto col = batch[fid];
const auto ndata = static_cast<bst_omp_uint>(col.length);
#pragma omp parallel for schedule(static)
for (bst_omp_uint j = 0; j < ndata; ++j) {
const bst_uint ridx = col[j].index;
const bst_float fvalue = col[j].fvalue;
const int nid = this->DecodePosition(ridx);
// go back to parent, correct those who are not default
if (!tree[nid].IsLeaf() && tree[nid].SplitIndex() == fid) {
if (fvalue < tree[nid].SplitCond()) {
this->SetEncodePosition(ridx, tree[nid].LeftChild());
} else {
this->SetEncodePosition(ridx, tree[nid].RightChild());
}
}
}
}
}
}
/*! \brief helper function to get statistics from a tree */
template<typename TStats>
inline void GetNodeStats(const std::vector<GradientPair> &gpair,
const DMatrix &fmat,
const RegTree &tree,
std::vector< std::vector<TStats> > *p_thread_temp,
std::vector<TStats> *p_node_stats) {
std::vector< std::vector<TStats> > &thread_temp = *p_thread_temp;
const MetaInfo &info = fmat.Info();
thread_temp.resize(omp_get_max_threads());
p_node_stats->resize(tree.param.num_nodes);
#pragma omp parallel
{
const int tid = omp_get_thread_num();
thread_temp[tid].resize(tree.param.num_nodes, TStats(param_));
for (unsigned int nid : qexpand_) {
thread_temp[tid][nid].Clear();
}
}
const RowSet &rowset = fmat.BufferedRowset();
// setup position
const auto ndata = static_cast<bst_omp_uint>(rowset.Size());
#pragma omp parallel for schedule(static)
for (bst_omp_uint i = 0; i < ndata; ++i) {
const bst_uint ridx = rowset[i];
const int nid = position_[ridx];
const int tid = omp_get_thread_num();
if (nid >= 0) {
thread_temp[tid][nid].Add(gpair, info, ridx);
}
}
// sum the per thread statistics together
for (int nid : qexpand_) {
TStats &s = (*p_node_stats)[nid];
s.Clear();
for (size_t tid = 0; tid < thread_temp.size(); ++tid) {
s.Add(thread_temp[tid][nid]);
}
}
}
/*! \brief common helper data structure to build sketch */
struct SketchEntry {
/*! \brief total sum of amount to be met */
double sum_total;
/*! \brief statistics used in the sketch */
double rmin, wmin;
/*! \brief last seen feature value */
bst_float last_fvalue;
/*! \brief current size of sketch */
double next_goal;
// pointer to the sketch to put things in
common::WXQuantileSketch<bst_float, bst_float> *sketch;
// initialize the space
inline void Init(unsigned max_size) {
next_goal = -1.0f;
rmin = wmin = 0.0f;
sketch->temp.Reserve(max_size + 1);
sketch->temp.size = 0;
}
/*!
* \brief push a new element to sketch
* \param fvalue feature value, comes in sorted ascending order
* \param w weight
* \param max_size
*/
inline void Push(bst_float fvalue, bst_float w, unsigned max_size) {
if (next_goal == -1.0f) {
next_goal = 0.0f;
last_fvalue = fvalue;
wmin = w;
return;
}
if (last_fvalue != fvalue) {
double rmax = rmin + wmin;
if (rmax >= next_goal && sketch->temp.size != max_size) {
if (sketch->temp.size == 0 ||
last_fvalue > sketch->temp.data[sketch->temp.size-1].value) {
// push to sketch
sketch->temp.data[sketch->temp.size] =
common::WXQuantileSketch<bst_float, bst_float>::
Entry(static_cast<bst_float>(rmin),
static_cast<bst_float>(rmax),
static_cast<bst_float>(wmin), last_fvalue);
CHECK_LT(sketch->temp.size, max_size)
<< "invalid maximum size max_size=" << max_size
<< ", stemp.size" << sketch->temp.size;
++sketch->temp.size;
}
if (sketch->temp.size == max_size) {
next_goal = sum_total * 2.0f + 1e-5f;
} else {
next_goal = static_cast<bst_float>(sketch->temp.size * sum_total / max_size);
}
} else {
if (rmax >= next_goal) {
LOG(TRACKER) << "INFO: rmax=" << rmax
<< ", sum_total=" << sum_total
<< ", naxt_goal=" << next_goal
<< ", size=" << sketch->temp.size;
}
}
rmin = rmax;
wmin = w;
last_fvalue = fvalue;
} else {
wmin += w;
}
}
/*! \brief push final unfinished value to the sketch */
inline void Finalize(unsigned max_size) {
double rmax = rmin + wmin;
if (sketch->temp.size == 0 || last_fvalue > sketch->temp.data[sketch->temp.size-1].value) {
CHECK_LE(sketch->temp.size, max_size)
<< "Finalize: invalid maximum size, max_size=" << max_size
<< ", stemp.size=" << sketch->temp.size;
// push to sketch
sketch->temp.data[sketch->temp.size] =
common::WXQuantileSketch<bst_float, bst_float>::
Entry(static_cast<bst_float>(rmin),
static_cast<bst_float>(rmax),
static_cast<bst_float>(wmin), last_fvalue);
++sketch->temp.size;
}
sketch->PushTemp();
}
};
/*! \brief training parameter of tree grower */
TrainParam param_;
/*! \brief queue of nodes to be expanded */
std::vector<int> qexpand_;
/*!
* \brief map active node to is working index offset in qexpand,
* can be -1, which means the node is node actively expanding
*/
std::vector<int> node2workindex_;
/*!
* \brief position of each instance in the tree
* can be negative, which means this position is no longer expanding
* see also Decode/EncodePosition
*/
std::vector<int> position_;
private:
inline void UpdateNode2WorkIndex(const RegTree &tree) {
// update the node2workindex
std::fill(node2workindex_.begin(), node2workindex_.end(), -1);
node2workindex_.resize(tree.param.num_nodes);
for (size_t i = 0; i < qexpand_.size(); ++i) {
node2workindex_[qexpand_[i]] = static_cast<int>(i);
}
}
};
} // namespace tree
} // namespace xgboost
#endif // XGBOOST_TREE_UPDATER_BASEMAKER_INL_H_
|
perftest.c | #define _GNU_SOURCE
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <omp.h>
#include <pthread.h>
#include <linux/perf_event.h>
#include <linux/hw_breakpoint.h>
#include <sys/ioctl.h>
#include <asm/unistd.h>
#include <errno.h>
#include <error.h>
#include <perfmon/pfmlib.h>
#include <perfmon/pfmlib_perf_event.h>
#include <pthread.h>
#include <sched.h>
#include <sys/sysinfo.h>
#include <hwloc.h>
#define N 16777216
static long perf_event_open_mine(struct perf_event_attr *hw_event, pid_t pid,
int cpu, int group_fd, unsigned long flags){
int ret;
ret = syscall(__NR_perf_event_open, hw_event, pid, cpu,
group_fd, flags);
return ret;
}
int main(){
int CPUS;
hwloc_topology_t sTopology;
if (hwloc_topology_init(&sTopology) == 0 &&
hwloc_topology_load(sTopology) == 0){
CPUS = hwloc_get_nbobjs_by_type(sTopology, HWLOC_OBJ_CORE);
hwloc_topology_destroy(sTopology);
}
omp_set_num_threads(CPUS);
int retval;
unsigned long int tid;
int *array;
int handles[CPUS];
int handles2[CPUS];
int handles3[CPUS];
int handles4[CPUS];
pfm_initialize();
struct perf_event_attr pe[CPUS];
struct perf_event_attr pe2[CPUS];
struct perf_event_attr pe3[CPUS];
struct perf_event_attr pe4[CPUS];
for(int i =0; i < CPUS; i++){
memset(&pe[i],0,sizeof(struct perf_event_attr));
memset(&pe2[i],0,sizeof(struct perf_event_attr));
memset(&pe3[i],0,sizeof(struct perf_event_attr));
memset(&pe4[i],0,sizeof(struct perf_event_attr));
// pe[i].type = PERF_TYPE_HARDWARE;
// pe[i].type = PERF_TYPE_RAW;
pe[i].type = PERF_TYPE_HW_CACHE;
pe[i].config = ( PERF_COUNT_HW_CACHE_NODE ) | ( PERF_COUNT_HW_CACHE_OP_READ << 8 ) | ( PERF_COUNT_HW_CACHE_RESULT_ACCESS << 16 );
pe[i].size = sizeof(struct perf_event_attr);
pe[i].disabled =1;
pe[i].exclude_kernel=1;
pe[i].exclude_hv=1;
/* pe2[i].type = PERF_TYPE_HARDWARE;
pe2[i].config = PERF_COUNT_HW_CACHE_MISSES;*/
pe2[i].type = PERF_TYPE_HW_CACHE;
pe2[i].config = ( PERF_COUNT_HW_CACHE_NODE ) | ( PERF_COUNT_HW_CACHE_OP_READ << 8 ) | ( PERF_COUNT_HW_CACHE_RESULT_MISS << 16 );
pe2[i].size = sizeof(struct perf_event_attr);
pe2[i].disabled =1;
pe2[i].exclude_kernel=1;
pe2[i].exclude_hv=1;
pe3[i].type = PERF_TYPE_HARDWARE;
// pe3[i].type = PERF_TYPE_RAW;
// pfm_get_perf_event_encoding("OFFCORE_REQUESTS:L3_MISS_DEMAND_DATA_RD",PFM_PLM3,&pe3[i],NULL,NULL );
pe3[i].config = PERF_COUNT_HW_CPU_CYCLES;
pe3[i].size = sizeof(struct perf_event_attr);
pe3[i].disabled =1;
pe3[i].exclude_kernel=1;
pe3[i].exclude_hv=1;
/* pe4[i].type = PERF_TYPE_RAW;
int x = pfm_get_perf_event_encoding("OFFCORE_RESPONSE_0:DMND_DATA_RD:L3_MISS_LOCAL:SNP_ANY",PFM_PLM3,&pe4[i],NULL,NULL);
if(x != PFM_SUCCESS) printf("%s\n", pfm_strerror(x));*/
pe4[i].type = PERF_TYPE_HARDWARE;
pe4[i].type = PERF_COUNT_HW_CACHE_MISSES;
pe4[i].size = sizeof(struct perf_event_attr);
pe4[i].disabled =1;
pe4[i].exclude_kernel=1;
pe4[i].exclude_hv=1;
}
array = _mm_malloc(sizeof(int)*N,512);
#pragma omp parallel default(none) shared(array)
{
// if(omp_get_thread_num() == 21){
#pragma omp for schedule(static)
// #pragma omp master
for(int i = 0; i < N; i++){
array[i] = i;
}
// }
}
#pragma omp parallel default(none) shared(array, handles, stderr,pe,pe2, handles2, pe3,pe4,handles3,handles4,CPUS)
{
cpu_set_t cpuset;
int core_id = omp_get_thread_num();
pthread_getaffinity_np(pthread_self(), sizeof(cpu_set_t), &cpuset);
if(CPU_COUNT(&cpuset) > 1) printf("Affinity not set, thread assigned to %i cores\n", CPU_COUNT(&cpuset));
for(int i = 0; i < CPUS; i++){
if(CPU_ISSET(i, &cpuset)){
core_id = i;
break;
}
}
for(int i = 0; i < omp_get_num_threads(); i++){
// if(i == omp_get_thread_num()){
handles[core_id] = perf_event_open_mine(&pe[core_id],0,core_id,-1,0);
handles2[core_id] = perf_event_open_mine(&pe2[core_id],0,core_id,-1,0);
handles3[core_id] = perf_event_open_mine(&pe3[core_id],0,core_id,-1,0);
handles4[core_id] = perf_event_open_mine(&pe4[core_id],0,core_id,-1,0);
if(handles[core_id] == -1 || handles2[core_id] == -1 || handles3[core_id] == -1 || handles4[core_id] == -1){
fprintf(stderr, "%i %i %i %i\n", handles[core_id], handles2[core_id], handles3[core_id], handles4[core_id]);
fprintf(stderr,"error opening %i %i\n", core_id,errno);
exit(EXIT_FAILURE);
}
// }
// #pragma omp barrier
}
if( ioctl(handles[core_id],PERF_EVENT_IOC_RESET,0) == -1){
exit(EXIT_FAILURE);
}
if( ioctl(handles2[core_id],PERF_EVENT_IOC_RESET,0) == -1){
exit(EXIT_FAILURE);
}
if( ioctl(handles3[core_id],PERF_EVENT_IOC_RESET,0) == -1){
exit(EXIT_FAILURE);
}
if( ioctl(handles4[core_id],PERF_EVENT_IOC_RESET,0) == -1){
exit(EXIT_FAILURE);
}
printf("Setup %i\n", omp_get_thread_num());
if( ioctl(handles[core_id],PERF_EVENT_IOC_ENABLE,0) == -1) {
exit(EXIT_FAILURE);
}
if( ioctl(handles2[core_id],PERF_EVENT_IOC_ENABLE,0) == -1) {
exit(EXIT_FAILURE);
}
if( ioctl(handles3[core_id],PERF_EVENT_IOC_ENABLE,0) == -1) {
exit(EXIT_FAILURE);
}
if( ioctl(handles4[core_id],PERF_EVENT_IOC_ENABLE,0) == -1) {
exit(EXIT_FAILURE);
}
#pragma omp for simd schedule(static) aligned(array:32)
// #pragma omp for schedule(dynamic, 32)
for(int i = 0; i < N; i++){
array[i] = array[i] + 1;
}
if( ioctl(handles[core_id],PERF_EVENT_IOC_DISABLE,0) == -1) {
exit(EXIT_FAILURE);
}
if( ioctl(handles2[core_id],PERF_EVENT_IOC_DISABLE,0) == -1) {
exit(EXIT_FAILURE);
}
if( ioctl(handles3[core_id],PERF_EVENT_IOC_DISABLE,0) == -1) {
exit(EXIT_FAILURE);
}
if( ioctl(handles4[core_id],PERF_EVENT_IOC_DISABLE,0) == -1) {
exit(EXIT_FAILURE);
}
long long count=-1, count2=-1,count3=-1, count4=-1;
ssize_t z = read(handles[core_id], &count, sizeof(long long));
ssize_t z2 = read(handles2[core_id], &count2, sizeof(long long));
ssize_t z3 = read(handles3[core_id], &count3, sizeof(long long));
ssize_t z4 = read(handles4[core_id], &count4, sizeof(long long));
if(z * z2 * z3 * z4 < 0) printf("error in reading files from thread %i\n", omp_get_thread_num());
for(int i = 0; i < omp_get_num_threads(); i++){
#pragma omp barrier
if(i == omp_get_thread_num())
printf("%i %i: %lli %lli %lli %lli \n",omp_get_thread_num(), core_id, count, count2, count3, count4);
}
}
_mm_free(array);
}
|
composite.c | /*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% CCCC OOO M M PPPP OOO SSSSS IIIII TTTTT EEEEE %
% C O O MM MM P P O O SS I T E %
% C O O M M M PPPP O O SSS I T EEE %
% C O O M M P O O SS I T E %
% CCCC OOO M M P OOO SSSSS IIIII T EEEEE %
% %
% %
% MagickCore Image Composite Methods %
% %
% Software Design %
% Cristy %
% July 1992 %
% %
% %
% Copyright 1999-2021 ImageMagick Studio LLC, a non-profit organization %
% dedicated to making software imaging solutions freely available. %
% %
% You may not use this file except in compliance with the License. You may %
% obtain a copy of the License at %
% %
% https://imagemagick.org/script/license.php %
% %
% Unless required by applicable law or agreed to in writing, software %
% distributed under the License is distributed on an "AS IS" BASIS, %
% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. %
% See the License for the specific language governing permissions and %
% limitations under the License. %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
%
%
*/
/*
Include declarations.
*/
#include "MagickCore/studio.h"
#include "MagickCore/artifact.h"
#include "MagickCore/cache.h"
#include "MagickCore/cache-private.h"
#include "MagickCore/cache-view.h"
#include "MagickCore/channel.h"
#include "MagickCore/client.h"
#include "MagickCore/color.h"
#include "MagickCore/color-private.h"
#include "MagickCore/colorspace.h"
#include "MagickCore/colorspace-private.h"
#include "MagickCore/composite.h"
#include "MagickCore/composite-private.h"
#include "MagickCore/constitute.h"
#include "MagickCore/draw.h"
#include "MagickCore/exception-private.h"
#include "MagickCore/fx.h"
#include "MagickCore/gem.h"
#include "MagickCore/geometry.h"
#include "MagickCore/image.h"
#include "MagickCore/image-private.h"
#include "MagickCore/list.h"
#include "MagickCore/log.h"
#include "MagickCore/memory_.h"
#include "MagickCore/monitor.h"
#include "MagickCore/monitor-private.h"
#include "MagickCore/morphology.h"
#include "MagickCore/option.h"
#include "MagickCore/pixel-accessor.h"
#include "MagickCore/property.h"
#include "MagickCore/quantum.h"
#include "MagickCore/resample.h"
#include "MagickCore/resource_.h"
#include "MagickCore/string_.h"
#include "MagickCore/thread-private.h"
#include "MagickCore/threshold.h"
#include "MagickCore/token.h"
#include "MagickCore/transform.h"
#include "MagickCore/utility.h"
#include "MagickCore/utility-private.h"
#include "MagickCore/version.h"
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% C o m p o s i t e I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% CompositeImage() returns the second image composited onto the first
% at the specified offset, using the specified composite method.
%
% The format of the CompositeImage method is:
%
% MagickBooleanType CompositeImage(Image *image,
% const Image *source_image,const CompositeOperator compose,
% const MagickBooleanType clip_to_self,const ssize_t x_offset,
% const ssize_t y_offset,ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the canvas image, modified by he composition
%
% o source_image: the source image.
%
% o compose: This operator affects how the composite is applied to
% the image. The operators and how they are utilized are listed here
% http://www.w3.org/TR/SVG12/#compositing.
%
% o clip_to_self: set to MagickTrue to limit composition to area composed.
%
% o x_offset: the column offset of the composited image.
%
% o y_offset: the row offset of the composited image.
%
% Extra Controls from Image meta-data in 'image' (artifacts)
%
% o "compose:args"
% A string containing extra numerical arguments for specific compose
% methods, generally expressed as a 'geometry' or a comma separated list
% of numbers.
%
% Compose methods needing such arguments include "BlendCompositeOp" and
% "DisplaceCompositeOp".
%
% o exception: return any errors or warnings in this structure.
%
*/
/*
Composition based on the SVG specification:
A Composition is defined by...
Color Function : f(Sc,Dc) where Sc and Dc are the normizalized colors
Blending areas : X = 1 for area of overlap, ie: f(Sc,Dc)
Y = 1 for source preserved
Z = 1 for canvas preserved
Conversion to transparency (then optimized)
Dca' = f(Sc, Dc)*Sa*Da + Y*Sca*(1-Da) + Z*Dca*(1-Sa)
Da' = X*Sa*Da + Y*Sa*(1-Da) + Z*Da*(1-Sa)
Where...
Sca = Sc*Sa normalized Source color divided by Source alpha
Dca = Dc*Da normalized Dest color divided by Dest alpha
Dc' = Dca'/Da' the desired color value for this channel.
Da' in in the follow formula as 'gamma' The resulting alpla value.
Most functions use a blending mode of over (X=1,Y=1,Z=1) this results in
the following optimizations...
gamma = Sa+Da-Sa*Da;
gamma = 1 - QuantumScale*alpha * QuantumScale*beta;
opacity = QuantumScale*alpha*beta; // over blend, optimized 1-Gamma
The above SVG definitions also define that Mathematical Composition
methods should use a 'Over' blending mode for Alpha Channel.
It however was not applied for composition modes of 'Plus', 'Minus',
the modulus versions of 'Add' and 'Subtract'.
Mathematical operator changes to be applied from IM v6.7...
1) Modulus modes 'Add' and 'Subtract' are obsoleted and renamed
'ModulusAdd' and 'ModulusSubtract' for clarity.
2) All mathematical compositions work as per the SVG specification
with regard to blending. This now includes 'ModulusAdd' and
'ModulusSubtract'.
3) When the special channel flag 'sync' (syncronize channel updates)
is turned off (enabled by default) then mathematical compositions are
only performed on the channels specified, and are applied
independantally of each other. In other words the mathematics is
performed as 'pure' mathematical operations, rather than as image
operations.
*/
static Image *BlendConvolveImage(const Image *image,const char *kernel,
ExceptionInfo *exception)
{
Image
*clone_image,
*convolve_image;
KernelInfo
*kernel_info;
/*
Convolve image with a kernel.
*/
kernel_info=AcquireKernelInfo(kernel,exception);
if (kernel_info == (KernelInfo *) NULL)
return((Image *) NULL);
clone_image=CloneImage(image,0,0,MagickTrue,exception);
if (clone_image == (Image *) NULL)
{
kernel_info=DestroyKernelInfo(kernel_info);
return((Image *) NULL);
}
(void) SetImageAlphaChannel(clone_image,OffAlphaChannel,exception);
convolve_image=ConvolveImage(clone_image,kernel_info,exception);
kernel_info=DestroyKernelInfo(kernel_info);
clone_image=DestroyImage(clone_image);
return(convolve_image);
}
static Image *BlendMagnitudeImage(const Image *dx_image,const Image *dy_image,
ExceptionInfo *exception)
{
CacheView
*dx_view,
*dy_view,
*magnitude_view;
Image
*magnitude_image;
MagickBooleanType
status = MagickTrue;
ssize_t
y;
/*
Generate the magnitude between two images.
*/
magnitude_image=CloneImage(dx_image,0,0,MagickTrue,exception);
if (magnitude_image == (Image *) NULL)
return(magnitude_image);
dx_view=AcquireVirtualCacheView(dx_image,exception);
dy_view=AcquireVirtualCacheView(dy_image,exception);
magnitude_view=AcquireAuthenticCacheView(magnitude_image,exception);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static) shared(status) \
magick_number_threads(dx_image,magnitude_image,dx_image->rows,1)
#endif
for (y=0; y < (ssize_t) dx_image->rows; y++)
{
const Quantum
*magick_restrict p,
*magick_restrict q;
Quantum
*magick_restrict r;
ssize_t
x;
if (status == MagickFalse)
continue;
p=GetCacheViewVirtualPixels(dx_view,0,y,dx_image->columns,1,exception);
q=GetCacheViewVirtualPixels(dy_view,0,y,dx_image->columns,1,exception);
r=GetCacheViewAuthenticPixels(magnitude_view,0,y,dx_image->columns,1,
exception);
if ((p == (const Quantum *) NULL) || (q == (const Quantum *) NULL) ||
(r == (Quantum *) NULL))
{
status=MagickFalse;
continue;
}
for (x=0; x < (ssize_t) dx_image->columns; x++)
{
ssize_t
i;
for (i=0; i < (ssize_t) GetPixelChannels(dx_image); i++)
{
PixelChannel channel = GetPixelChannelChannel(dx_image,i);
PixelTrait traits = GetPixelChannelTraits(dx_image,channel);
PixelTrait dy_traits = GetPixelChannelTraits(dy_image,channel);
if ((traits == UndefinedPixelTrait) ||
(dy_traits == UndefinedPixelTrait) ||
((dy_traits & UpdatePixelTrait) == 0))
continue;
r[i]=ClampToQuantum(hypot((double) p[i],(double)
GetPixelChannel(dy_image,channel,q)));
}
p+=GetPixelChannels(dx_image);
q+=GetPixelChannels(dy_image);
r+=GetPixelChannels(magnitude_image);
}
if (SyncCacheViewAuthenticPixels(magnitude_view,exception) == MagickFalse)
status=MagickFalse;
}
magnitude_view=DestroyCacheView(magnitude_view);
dy_view=DestroyCacheView(dy_view);
dx_view=DestroyCacheView(dx_view);
if (status == MagickFalse)
magnitude_image=DestroyImage(magnitude_image);
return(magnitude_image);
}
static Image *BlendMaxMagnitudeImage(const Image *alpha_image,
const Image *beta_image,const Image *dx_image,const Image *dy_image,
ExceptionInfo *exception)
{
CacheView
*alpha_view,
*beta_view,
*dx_view,
*dy_view,
*magnitude_view;
Image
*magnitude_image;
MagickBooleanType
status = MagickTrue;
ssize_t
y;
/*
Select the larger of two magnitudes.
*/
magnitude_image=CloneImage(alpha_image,0,0,MagickTrue,exception);
if (magnitude_image == (Image *) NULL)
return(magnitude_image);
alpha_view=AcquireVirtualCacheView(alpha_image,exception);
beta_view=AcquireVirtualCacheView(beta_image,exception);
dx_view=AcquireVirtualCacheView(dx_image,exception);
dy_view=AcquireVirtualCacheView(dy_image,exception);
magnitude_view=AcquireAuthenticCacheView(magnitude_image,exception);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static) shared(status) \
magick_number_threads(alpha_image,magnitude_image,alpha_image->rows,1)
#endif
for (y=0; y < (ssize_t) alpha_image->rows; y++)
{
const Quantum
*magick_restrict p,
*magick_restrict q,
*magick_restrict r,
*magick_restrict s;
Quantum
*magick_restrict t;
ssize_t
x;
if (status == MagickFalse)
continue;
p=GetCacheViewVirtualPixels(alpha_view,0,y,alpha_image->columns,1,
exception);
q=GetCacheViewVirtualPixels(beta_view,0,y,alpha_image->columns,1,exception);
r=GetCacheViewVirtualPixels(dx_view,0,y,alpha_image->columns,1,exception);
s=GetCacheViewVirtualPixels(dy_view,0,y,alpha_image->columns,1,exception);
t=GetCacheViewAuthenticPixels(magnitude_view,0,y,alpha_image->columns,1,
exception);
if ((p == (const Quantum *) NULL) || (q == (const Quantum *) NULL) ||
(r == (const Quantum *) NULL) || (s == (const Quantum *) NULL) ||
(r == (Quantum *) NULL))
{
status=MagickFalse;
continue;
}
for (x=0; x < (ssize_t) alpha_image->columns; x++)
{
ssize_t
i;
for (i=0; i < (ssize_t) GetPixelChannels(alpha_image); i++)
{
PixelChannel channel = GetPixelChannelChannel(alpha_image,i);
PixelTrait traits = GetPixelChannelTraits(alpha_image,channel);
PixelTrait beta_traits = GetPixelChannelTraits(beta_image,channel);
if ((traits == UndefinedPixelTrait) ||
(beta_traits == UndefinedPixelTrait) ||
((beta_traits & UpdatePixelTrait) == 0))
continue;
if (p[i] > GetPixelChannel(beta_image,channel,q))
t[i]=GetPixelChannel(dx_image,channel,r);
else
t[i]=GetPixelChannel(dy_image,channel,s);
}
p+=GetPixelChannels(alpha_image);
q+=GetPixelChannels(beta_image);
r+=GetPixelChannels(dx_image);
s+=GetPixelChannels(dy_image);
t+=GetPixelChannels(magnitude_image);
}
if (SyncCacheViewAuthenticPixels(magnitude_view,exception) == MagickFalse)
status=MagickFalse;
}
magnitude_view=DestroyCacheView(magnitude_view);
dy_view=DestroyCacheView(dy_view);
dx_view=DestroyCacheView(dx_view);
beta_view=DestroyCacheView(beta_view);
alpha_view=DestroyCacheView(alpha_view);
if (status == MagickFalse)
magnitude_image=DestroyImage(magnitude_image);
return(magnitude_image);
}
static Image *BlendSumImage(const Image *alpha_image,const Image *beta_image,
const double attenuate,const double sign,ExceptionInfo *exception)
{
CacheView
*alpha_view,
*beta_view,
*sum_view;
Image
*sum_image;
MagickBooleanType
status = MagickTrue;
ssize_t
y;
/*
Add or subtract and optionally attenuate two images.
*/
sum_image=CloneImage(alpha_image,0,0,MagickTrue,exception);
if (sum_image == (Image *) NULL)
return(sum_image);
alpha_view=AcquireVirtualCacheView(alpha_image,exception);
beta_view=AcquireVirtualCacheView(beta_image,exception);
sum_view=AcquireAuthenticCacheView(sum_image,exception);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static) shared(status) \
magick_number_threads(alpha_image,sum_image,alpha_image->rows,1)
#endif
for (y=0; y < (ssize_t) alpha_image->rows; y++)
{
const Quantum
*magick_restrict p,
*magick_restrict q;
Quantum
*magick_restrict r;
ssize_t
x;
if (status == MagickFalse)
continue;
p=GetCacheViewVirtualPixels(alpha_view,0,y,alpha_image->columns,1,
exception);
q=GetCacheViewVirtualPixels(beta_view,0,y,alpha_image->columns,1,exception);
r=GetCacheViewAuthenticPixels(sum_view,0,y,alpha_image->columns,1,
exception);
if ((p == (const Quantum *) NULL) || (q == (const Quantum *) NULL) ||
(r == (Quantum *) NULL))
{
status=MagickFalse;
continue;
}
for (x=0; x < (ssize_t) alpha_image->columns; x++)
{
ssize_t
i;
for (i=0; i < (ssize_t) GetPixelChannels(alpha_image); i++)
{
PixelChannel channel = GetPixelChannelChannel(alpha_image,i);
PixelTrait traits = GetPixelChannelTraits(alpha_image,channel);
PixelTrait beta_traits = GetPixelChannelTraits(beta_image,channel);
if ((traits == UndefinedPixelTrait) ||
(beta_traits == UndefinedPixelTrait) ||
((beta_traits & UpdatePixelTrait) == 0))
continue;
r[i]=ClampToQuantum(attenuate*(p[i]+sign*
GetPixelChannel(beta_image,channel,q)));
}
p+=GetPixelChannels(alpha_image);
q+=GetPixelChannels(beta_image);
r+=GetPixelChannels(sum_image);
}
if (SyncCacheViewAuthenticPixels(sum_view,exception) == MagickFalse)
status=MagickFalse;
}
sum_view=DestroyCacheView(sum_view);
beta_view=DestroyCacheView(beta_view);
alpha_view=DestroyCacheView(alpha_view);
if (status == MagickFalse)
sum_image=DestroyImage(sum_image);
return(sum_image);
}
static Image *BlendDivergentImage(const Image *alpha_image,
const Image *beta_image,ExceptionInfo *exception)
{
#define FreeDivergentResources() \
{ \
if (dy_image != (Image *) NULL) \
dy_image=DestroyImage(dy_image); \
if (dx_image != (Image *) NULL) \
dx_image=DestroyImage(dx_image); \
if (magnitude_beta != (Image *) NULL) \
magnitude_beta=DestroyImage(magnitude_beta); \
if (dy_beta != (Image *) NULL) \
dy_beta=DestroyImage(dy_beta); \
if (dx_beta != (Image *) NULL) \
dx_beta=DestroyImage(dx_beta); \
if (magnitude_alpha != (Image *) NULL) \
magnitude_alpha=DestroyImage(magnitude_alpha); \
if (dy_alpha != (Image *) NULL) \
dy_alpha=DestroyImage(dy_alpha); \
if (dx_alpha != (Image *) NULL) \
dx_alpha=DestroyImage(dx_alpha); \
}
Image
*divergent_image = (Image *) NULL,
*dx_alpha = (Image *) NULL,
*dx_beta = (Image *) NULL,
*dx_divergent = (Image *) NULL,
*dx_image = (Image *) NULL,
*dy_alpha = (Image *) NULL,
*dy_beta = (Image *) NULL,
*dy_divergent = (Image *) NULL,
*dy_image = (Image *) NULL,
*magnitude_alpha = (Image *) NULL,
*magnitude_beta = (Image *) NULL;
/*
Create X and Y gradient images for alpha image and the magnitude.
*/
dx_alpha=BlendConvolveImage(alpha_image,"3x1:-0.5,0.0,0.5",exception);
if (dx_alpha == (Image *) NULL)
{
FreeDivergentResources();
return((Image *) NULL);
}
dy_alpha=BlendConvolveImage(alpha_image,"1x3:-0.5,0.0,0.5",exception);
if (dy_alpha == (Image *) NULL)
{
FreeDivergentResources();
return((Image *) NULL);
}
magnitude_alpha=BlendMagnitudeImage(dx_alpha,dy_alpha,exception);
if (magnitude_alpha == (Image *) NULL)
{
FreeDivergentResources();
return((Image *) NULL);
}
/*
Create X and Y gradient images for beta and the magnitude.
*/
dx_beta=BlendConvolveImage(beta_image,"3x1:-0.5,0.0,0.5",exception);
if (dx_beta == (Image *) NULL)
{
FreeDivergentResources();
return((Image *) NULL);
}
dy_beta=BlendConvolveImage(beta_image,"1x3:-0.5,0.0,0.5",exception);
if (dy_beta == (Image *) NULL)
{
FreeDivergentResources();
return((Image *) NULL);
}
magnitude_beta=BlendMagnitudeImage(dx_beta,dy_beta,exception);
if (magnitude_beta == (Image *) NULL)
{
FreeDivergentResources();
return((Image *) NULL);
}
/*
Select alpha or beta gradient for larger of two magnitudes.
*/
dx_image=BlendMaxMagnitudeImage(magnitude_alpha,magnitude_beta,dx_alpha,
dx_beta,exception);
if (dx_image == (Image *) NULL)
{
FreeDivergentResources();
return((Image *) NULL);
}
dy_image=BlendMaxMagnitudeImage(magnitude_alpha,magnitude_beta,dy_alpha,
dy_beta,exception);
if (dy_image == (Image *) NULL)
{
FreeDivergentResources();
return((Image *) NULL);
}
dx_beta=DestroyImage(dx_beta);
dx_alpha=DestroyImage(dx_alpha);
magnitude_beta=DestroyImage(magnitude_beta);
magnitude_alpha=DestroyImage(magnitude_alpha);
/*
Create divergence of gradients dx and dy and divide by 4 as guide image.
*/
dx_divergent=BlendConvolveImage(dx_image,"3x1:-0.5,0.0,0.5",exception);
if (dx_divergent == (Image *) NULL)
{
FreeDivergentResources();
return((Image *) NULL);
}
dy_divergent=BlendConvolveImage(dy_image,"1x3:-0.5,0.0,0.5",exception);
if (dy_divergent == (Image *) NULL)
{
FreeDivergentResources();
return((Image *) NULL);
}
divergent_image=BlendSumImage(dx_divergent,dy_divergent,0.25,1.0,exception);
dy_divergent=DestroyImage(dy_divergent);
dx_divergent=DestroyImage(dx_divergent);
if (divergent_image == (Image *) NULL)
{
FreeDivergentResources();
return((Image *) NULL);
}
FreeDivergentResources();
return(divergent_image);
}
static MagickBooleanType BlendMaskAlphaChannel(Image *image,
const Image *mask_image,ExceptionInfo *exception)
{
CacheView
*image_view,
*mask_view;
MagickBooleanType
status = MagickTrue;
ssize_t
y;
/*
Threshold the alpha channel.
*/
if (SetImageAlpha(image,OpaqueAlpha,exception) == MagickFalse)
return(MagickFalse);
image_view=AcquireAuthenticCacheView(image,exception);
mask_view=AcquireVirtualCacheView(mask_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++)
{
const Quantum
*magick_restrict p;
Quantum
*magick_restrict q;
ssize_t
x;
if (status == MagickFalse)
continue;
p=GetCacheViewVirtualPixels(mask_view,0,y,image->columns,1,exception);
q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception);
if ((p == (const Quantum *) NULL) || (q == (Quantum *) NULL))
{
status=MagickFalse;
continue;
}
for (x=0; x < (ssize_t) image->columns; x++)
{
Quantum
alpha = GetPixelAlpha(mask_image,p);
ssize_t
i = GetPixelChannelOffset(image,AlphaPixelChannel);
if (fabs((double) alpha) >= MagickEpsilon)
q[i]=(Quantum) 0;
p+=GetPixelChannels(mask_image);
q+=GetPixelChannels(image);
}
if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
status=MagickFalse;
}
mask_view=DestroyCacheView(mask_view);
image_view=DestroyCacheView(image_view);
return(status);
}
static Image *BlendMeanImage(Image *image,const Image *mask_image,
ExceptionInfo *exception)
{
CacheView
*alpha_view,
*mask_view,
*mean_view;
double
mean[MaxPixelChannels];
Image
*mean_image;
MagickBooleanType
status = MagickTrue;
ssize_t
j,
y;
/*
Compute the mean of the image.
*/
(void) memset(mean,0,MaxPixelChannels*sizeof(*mean));
alpha_view=AcquireVirtualCacheView(image,exception);
for (y=0; y < (ssize_t) image->rows; y++)
{
const Quantum
*magick_restrict p;
ssize_t
x;
p=GetCacheViewVirtualPixels(alpha_view,0,y,image->columns,1,
exception);
if (p == (const Quantum *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
ssize_t
i;
for (i=0; i < (ssize_t) GetPixelChannels(image); i++)
{
PixelChannel channel = GetPixelChannelChannel(image,i);
PixelTrait traits = GetPixelChannelTraits(image,channel);
if (traits == UndefinedPixelTrait)
continue;
mean[i]+=QuantumScale*p[i];
}
p+=GetPixelChannels(image);
}
}
alpha_view=DestroyCacheView(alpha_view);
if (y < (ssize_t) image->rows)
return((Image *) NULL);
for (j=0; j < (ssize_t) GetPixelChannels(image); j++)
mean[j]=(double) QuantumRange*mean[j]/image->columns/
image->rows;
/*
Replace any unmasked pixels with the mean pixel.
*/
mean_image=CloneImage(image,0,0,MagickTrue,exception);
if (mean_image == (Image *) NULL)
return(mean_image);
mask_view=AcquireVirtualCacheView(mask_image,exception);
mean_view=AcquireAuthenticCacheView(mean_image,exception);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static) shared(status) \
magick_number_threads(mask_image,mean_image,mean_image->rows,1)
#endif
for (y=0; y < (ssize_t) mean_image->rows; y++)
{
const Quantum
*magick_restrict p;
Quantum
*magick_restrict q;
ssize_t
x;
if (status == MagickFalse)
continue;
p=GetCacheViewVirtualPixels(mask_view,0,y,mean_image->columns,1,exception);
q=GetCacheViewAuthenticPixels(mean_view,0,y,mean_image->columns,1,
exception);
if ((p == (const Quantum *) NULL) || (q == (Quantum *) NULL))
{
status=MagickFalse;
continue;
}
for (x=0; x < (ssize_t) mean_image->columns; x++)
{
Quantum
alpha = GetPixelAlpha(mask_image,p),
mask = GetPixelReadMask(mask_image,p);
ssize_t
i;
for (i=0; i < (ssize_t) GetPixelChannels(mean_image); i++)
{
PixelChannel channel = GetPixelChannelChannel(mean_image,i);
PixelTrait traits = GetPixelChannelTraits(mean_image,channel);
if (traits == UndefinedPixelTrait)
continue;
if (mask <= (QuantumRange/2))
q[i]=(Quantum) 0;
else
if (fabs((double) alpha) >= MagickEpsilon)
q[i]=ClampToQuantum(mean[i]);
}
p+=GetPixelChannels(mask_image);
q+=GetPixelChannels(mean_image);
}
if (SyncCacheViewAuthenticPixels(mean_view,exception) == MagickFalse)
status=MagickFalse;
}
mask_view=DestroyCacheView(mask_view);
mean_view=DestroyCacheView(mean_view);
if (status == MagickFalse)
mean_image=DestroyImage(mean_image);
return(mean_image);
}
static MagickBooleanType BlendRMSEResidual(const Image *alpha_image,
const Image *beta_image,double *residual,ExceptionInfo *exception)
{
CacheView
*alpha_view,
*beta_view;
double
area = 0.0;
MagickBooleanType
status = MagickTrue;
size_t
columns = MagickMax(alpha_image->columns,beta_image->columns),
rows = MagickMax(alpha_image->rows,beta_image->rows);
ssize_t
y;
*residual=0.0;
alpha_view=AcquireVirtualCacheView(alpha_image,exception);
beta_view=AcquireVirtualCacheView(beta_image,exception);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static) shared(status) \
magick_number_threads(alpha_image,alpha_image,rows,1)
#endif
for (y=0; y < (ssize_t) rows; y++)
{
const Quantum
*magick_restrict p,
*magick_restrict q;
double
channel_residual;
size_t
local_area = 0;
ssize_t
x;
if (status == MagickFalse)
continue;
p=GetCacheViewVirtualPixels(alpha_view,0,y,columns,1,exception);
q=GetCacheViewVirtualPixels(beta_view,0,y,columns,1,exception);
if ((p == (const Quantum *) NULL) || (q == (const Quantum *) NULL))
{
status=MagickFalse;
continue;
}
channel_residual=0.0;
for (x=0; x < (ssize_t) columns; x++)
{
double
Da,
Sa;
ssize_t
i;
if ((GetPixelReadMask(alpha_image,p) <= (QuantumRange/2)) ||
(GetPixelReadMask(beta_image,q) <= (QuantumRange/2)))
{
p+=GetPixelChannels(alpha_image);
q+=GetPixelChannels(beta_image);
continue;
}
Sa=QuantumScale*GetPixelAlpha(alpha_image,p);
Da=QuantumScale*GetPixelAlpha(beta_image,q);
for (i=0; i < (ssize_t) GetPixelChannels(alpha_image); i++)
{
double
distance;
PixelChannel channel = GetPixelChannelChannel(alpha_image,i);
PixelTrait traits = GetPixelChannelTraits(alpha_image,channel);
PixelTrait beta_traits = GetPixelChannelTraits(beta_image,channel);
if ((traits == UndefinedPixelTrait) ||
(beta_traits == UndefinedPixelTrait) ||
((beta_traits & UpdatePixelTrait) == 0))
continue;
if (channel == AlphaPixelChannel)
distance=QuantumScale*(p[i]-GetPixelChannel(beta_image,channel,q));
else
distance=QuantumScale*(Sa*p[i]-Da*GetPixelChannel(beta_image,channel,
q));
channel_residual+=distance*distance;
}
local_area++;
p+=GetPixelChannels(alpha_image);
q+=GetPixelChannels(beta_image);
}
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp critical (MagickCore_BlendRMSEResidual)
#endif
{
area+=local_area;
*residual+=channel_residual;
}
}
area=PerceptibleReciprocal(area);
beta_view=DestroyCacheView(beta_view);
alpha_view=DestroyCacheView(alpha_view);
*residual=sqrt(*residual*area/(double) GetImageChannels(alpha_image));
return(status);
}
static void CompositeHCL(const MagickRealType red,const MagickRealType green,
const MagickRealType blue,MagickRealType *hue,MagickRealType *chroma,
MagickRealType *luma)
{
MagickRealType
b,
c,
g,
h,
max,
r;
/*
Convert RGB to HCL colorspace.
*/
assert(hue != (MagickRealType *) NULL);
assert(chroma != (MagickRealType *) NULL);
assert(luma != (MagickRealType *) NULL);
r=red;
g=green;
b=blue;
max=MagickMax(r,MagickMax(g,b));
c=max-(MagickRealType) MagickMin(r,MagickMin(g,b));
h=0.0;
if (c == 0)
h=0.0;
else
if (red == max)
h=fmod((g-b)/c+6.0,6.0);
else
if (green == max)
h=((b-r)/c)+2.0;
else
if (blue == max)
h=((r-g)/c)+4.0;
*hue=(h/6.0);
*chroma=QuantumScale*c;
*luma=QuantumScale*(0.298839*r+0.586811*g+0.114350*b);
}
static MagickBooleanType CompositeOverImage(Image *image,
const Image *source_image,const MagickBooleanType clip_to_self,
const ssize_t x_offset,const ssize_t y_offset,ExceptionInfo *exception)
{
#define CompositeImageTag "Composite/Image"
CacheView
*image_view,
*source_view;
const char
*value;
MagickBooleanType
clamp,
status;
MagickOffsetType
progress;
ssize_t
y;
/*
Composite image.
*/
status=MagickTrue;
progress=0;
clamp=MagickTrue;
value=GetImageArtifact(image,"compose:clamp");
if (value != (const char *) NULL)
clamp=IsStringTrue(value);
status=MagickTrue;
progress=0;
source_view=AcquireVirtualCacheView(source_image,exception);
image_view=AcquireAuthenticCacheView(image,exception);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static) shared(progress,status) \
magick_number_threads(source_image,image,image->rows,1)
#endif
for (y=0; y < (ssize_t) image->rows; y++)
{
const Quantum
*pixels;
PixelInfo
canvas_pixel,
source_pixel;
const Quantum
*magick_restrict p;
Quantum
*magick_restrict q;
ssize_t
x;
if (status == MagickFalse)
continue;
if (clip_to_self != MagickFalse)
{
if (y < y_offset)
continue;
if ((y-y_offset) >= (ssize_t) source_image->rows)
continue;
}
/*
If pixels is NULL, y is outside overlay region.
*/
pixels=(Quantum *) NULL;
p=(Quantum *) NULL;
if ((y >= y_offset) && ((y-y_offset) < (ssize_t) source_image->rows))
{
p=GetCacheViewVirtualPixels(source_view,0,y-y_offset,
source_image->columns,1,exception);
if (p == (const Quantum *) NULL)
{
status=MagickFalse;
continue;
}
pixels=p;
if (x_offset < 0)
p-=x_offset*(ssize_t) GetPixelChannels(source_image);
}
q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception);
if (q == (Quantum *) NULL)
{
status=MagickFalse;
continue;
}
GetPixelInfo(image,&canvas_pixel);
GetPixelInfo(source_image,&source_pixel);
for (x=0; x < (ssize_t) image->columns; x++)
{
double
gamma;
MagickRealType
alpha,
Da,
Dc,
Dca,
Sa,
Sc,
Sca;
ssize_t
i;
size_t
channels;
if (clip_to_self != MagickFalse)
{
if (x < x_offset)
{
q+=GetPixelChannels(image);
continue;
}
if ((x-x_offset) >= (ssize_t) source_image->columns)
break;
}
if ((pixels == (Quantum *) NULL) || (x < x_offset) ||
((x-x_offset) >= (ssize_t) source_image->columns))
{
Quantum
source[MaxPixelChannels];
/*
Virtual composite:
Sc: source color.
Dc: canvas color.
*/
(void) GetOneVirtualPixel(source_image,x-x_offset,y-y_offset,source,
exception);
for (i=0; i < (ssize_t) GetPixelChannels(image); i++)
{
MagickRealType
pixel;
PixelChannel channel = GetPixelChannelChannel(image,i);
PixelTrait traits = GetPixelChannelTraits(image,channel);
PixelTrait source_traits=GetPixelChannelTraits(source_image,
channel);
if ((traits == UndefinedPixelTrait) ||
(source_traits == UndefinedPixelTrait))
continue;
if (channel == AlphaPixelChannel)
pixel=(MagickRealType) TransparentAlpha;
else
pixel=(MagickRealType) q[i];
q[i]=clamp != MagickFalse ? ClampPixel(pixel) :
ClampToQuantum(pixel);
}
q+=GetPixelChannels(image);
continue;
}
/*
Authentic composite:
Sa: normalized source alpha.
Da: normalized canvas alpha.
*/
Sa=QuantumScale*GetPixelAlpha(source_image,p);
Da=QuantumScale*GetPixelAlpha(image,q);
alpha=Sa+Da-Sa*Da;
for (i=0; i < (ssize_t) GetPixelChannels(image); i++)
{
MagickRealType
pixel;
PixelChannel channel = GetPixelChannelChannel(image,i);
PixelTrait traits = GetPixelChannelTraits(image,channel);
PixelTrait source_traits=GetPixelChannelTraits(source_image,channel);
if (traits == UndefinedPixelTrait)
continue;
if ((source_traits == UndefinedPixelTrait) &&
(channel != AlphaPixelChannel))
continue;
if (channel == AlphaPixelChannel)
{
/*
Set alpha channel.
*/
pixel=QuantumRange*alpha;
q[i]=clamp != MagickFalse ? ClampPixel(pixel) :
ClampToQuantum(pixel);
continue;
}
/*
Sc: source color.
Dc: canvas color.
*/
Sc=(MagickRealType) GetPixelChannel(source_image,channel,p);
Dc=(MagickRealType) q[i];
if ((traits & CopyPixelTrait) != 0)
{
/*
Copy channel.
*/
q[i]=ClampToQuantum(Sc);
continue;
}
/*
Porter-Duff compositions:
Sca: source normalized color multiplied by alpha.
Dca: normalized canvas color multiplied by alpha.
*/
Sca=QuantumScale*Sa*Sc;
Dca=QuantumScale*Da*Dc;
gamma=PerceptibleReciprocal(alpha);
pixel=QuantumRange*gamma*(Sca+Dca*(1.0-Sa));
q[i]=clamp != MagickFalse ? ClampPixel(pixel) : ClampToQuantum(pixel);
}
p+=GetPixelChannels(source_image);
channels=GetPixelChannels(source_image);
if (p >= (pixels+channels*source_image->columns))
p=pixels;
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,CompositeImageTag,progress,image->rows);
if (proceed == MagickFalse)
status=MagickFalse;
}
}
source_view=DestroyCacheView(source_view);
image_view=DestroyCacheView(image_view);
return(status);
}
static void HCLComposite(const MagickRealType hue,const MagickRealType chroma,
const MagickRealType luma,MagickRealType *red,MagickRealType *green,
MagickRealType *blue)
{
MagickRealType
b,
c,
g,
h,
m,
r,
x;
/*
Convert HCL to RGB colorspace.
*/
assert(red != (MagickRealType *) NULL);
assert(green != (MagickRealType *) NULL);
assert(blue != (MagickRealType *) NULL);
h=6.0*hue;
c=chroma;
x=c*(1.0-fabs(fmod(h,2.0)-1.0));
r=0.0;
g=0.0;
b=0.0;
if ((0.0 <= h) && (h < 1.0))
{
r=c;
g=x;
}
else
if ((1.0 <= h) && (h < 2.0))
{
r=x;
g=c;
}
else
if ((2.0 <= h) && (h < 3.0))
{
g=c;
b=x;
}
else
if ((3.0 <= h) && (h < 4.0))
{
g=x;
b=c;
}
else
if ((4.0 <= h) && (h < 5.0))
{
r=x;
b=c;
}
else
if ((5.0 <= h) && (h < 6.0))
{
r=c;
b=x;
}
m=luma-(0.298839*r+0.586811*g+0.114350*b);
*red=QuantumRange*(r+m);
*green=QuantumRange*(g+m);
*blue=QuantumRange*(b+m);
}
static MagickBooleanType SaliencyBlendImage(Image *image,
const Image *source_image,const ssize_t x_offset,const ssize_t y_offset,
const double iterations,const double residual_threshold,const size_t tick,
ExceptionInfo *exception)
{
Image
*crop_image,
*divergent_image,
*relax_image,
*residual_image = (Image *) NULL;
KernelInfo
*kernel_info;
MagickBooleanType
status = MagickTrue,
verbose = MagickFalse;
RectangleInfo
crop_info = {
source_image->columns,
source_image->rows,
x_offset,
y_offset
};
ssize_t
i;
/*
Saliency blend composite operator.
*/
crop_image=CropImage(image,&crop_info,exception);
if (crop_image == (Image *) NULL)
return(MagickFalse);
divergent_image=BlendDivergentImage(source_image,crop_image,exception);
if (divergent_image == (Image *) NULL)
{
crop_image=DestroyImage(crop_image);
return(MagickFalse);
}
(void) ResetImagePage(crop_image,"0x0+0+0");
relax_image=BlendMeanImage(crop_image,source_image,exception);
if (relax_image == (Image *) NULL)
{
divergent_image=DestroyImage(divergent_image);
return(MagickFalse);
}
residual_image=CloneImage(relax_image,0,0,MagickTrue,exception);
if (residual_image == (Image *) NULL)
{
relax_image=DestroyImage(relax_image);
return(MagickFalse);
}
/*
Convolve relaxed image and blur area of interest.
*/
kernel_info=AcquireKernelInfo("3x3:0,0.25,0,0.25,0,0.25,0,0.25,0",exception);
if (kernel_info == (KernelInfo *) NULL)
{
residual_image=DestroyImage(residual_image);
relax_image=DestroyImage(relax_image);
return(MagickFalse);
}
verbose=IsStringTrue(GetImageArtifact(image,"verbose"));
if (verbose != MagickFalse)
(void) FormatLocaleFile(stderr,"saliency blending:\n");
for (i=0; i < (ssize_t) iterations; i++)
{
double
residual = 1.0;
Image
*convolve_image,
*sum_image;
convolve_image=ConvolveImage(relax_image,kernel_info,exception);
if (convolve_image == (Image *) NULL)
break;
relax_image=DestroyImage(relax_image);
relax_image=convolve_image;
sum_image=BlendSumImage(relax_image,divergent_image,1.0,-1.0,exception);
if (sum_image == (Image *) NULL)
break;
relax_image=DestroyImage(relax_image);
relax_image=sum_image;
status=BlendRMSEResidual(relax_image,residual_image,&residual,exception);
if (status == MagickFalse)
break;
if ((verbose != MagickFalse) && ((i % MagickMax(tick,1)) == 0))
(void) FormatLocaleFile(stderr," %g: %g\n",(double) i,(double) residual);
if (residual < residual_threshold)
{
if (verbose != MagickFalse)
(void) FormatLocaleFile(stderr," %g: %g\n",(double) i,(double)
residual);
break;
}
residual_image=DestroyImage(residual_image);
residual_image=CloneImage(relax_image,0,0,MagickTrue,exception);
if (residual_image == (Image *) NULL)
break;
}
kernel_info=DestroyKernelInfo(kernel_info);
divergent_image=DestroyImage(divergent_image);
residual_image=DestroyImage(residual_image);
/*
Composite relaxed over the background image.
*/
status=CompositeOverImage(image,relax_image,MagickTrue,x_offset,y_offset,
exception);
return(status);
}
static MagickBooleanType SeamlessBlendImage(Image *image,
const Image *source_image,const ssize_t x_offset,const ssize_t y_offset,
const double iterations,const double residual_threshold,const size_t tick,
ExceptionInfo *exception)
{
Image
*crop_image,
*foreground_image,
*mean_image,
*relax_image,
*residual_image,
*sum_image;
KernelInfo
*kernel_info;
MagickBooleanType
status = MagickTrue,
verbose = MagickFalse;
RectangleInfo
crop_info = {
source_image->columns,
source_image->rows,
x_offset,
y_offset
};
ssize_t
i;
/*
Seamless blend composite operator.
*/
crop_image=CropImage(image,&crop_info,exception);
if (crop_image == (Image *) NULL)
return(MagickFalse);
(void) ResetImagePage(crop_image,"0x0+0+0");
sum_image=BlendSumImage(crop_image,source_image,1.0,-1.0,exception);
crop_image=DestroyImage(crop_image);
if (sum_image == (Image *) NULL)
return(MagickFalse);
mean_image=BlendMeanImage(sum_image,source_image,exception);
sum_image=DestroyImage(sum_image);
if (mean_image == (Image *) NULL)
return(MagickFalse);
relax_image=CloneImage(mean_image,0,0,MagickTrue,exception);
if (relax_image == (Image *) NULL)
{
mean_image=DestroyImage(mean_image);
return(MagickFalse);
}
status=BlendMaskAlphaChannel(mean_image,source_image,exception);
if (status == MagickFalse)
{
relax_image=DestroyImage(relax_image);
mean_image=DestroyImage(mean_image);
return(MagickFalse);
}
residual_image=CloneImage(relax_image,0,0,MagickTrue,exception);
if (residual_image == (Image *) NULL)
{
relax_image=DestroyImage(relax_image);
mean_image=DestroyImage(mean_image);
return(MagickFalse);
}
/*
Convolve relaxed image and blur area of interest.
*/
kernel_info=AcquireKernelInfo("3x3:0,0.25,0,0.25,0,0.25,0,0.25,0",exception);
if (kernel_info == (KernelInfo *) NULL)
{
residual_image=DestroyImage(residual_image);
relax_image=DestroyImage(relax_image);
mean_image=DestroyImage(mean_image);
return(MagickFalse);
}
verbose=IsStringTrue(GetImageArtifact(image,"verbose"));
if (verbose != MagickFalse)
(void) FormatLocaleFile(stderr,"seamless blending:\n");
for (i=0; i < (ssize_t) iterations; i++)
{
double
residual = 1.0;
Image
*convolve_image;
convolve_image=ConvolveImage(relax_image,kernel_info,exception);
if (convolve_image == (Image *) NULL)
break;
relax_image=DestroyImage(relax_image);
relax_image=convolve_image;
status=CompositeOverImage(relax_image,mean_image,MagickTrue,0,0,exception);
if (status == MagickFalse)
break;
status=BlendRMSEResidual(relax_image,residual_image,&residual,exception);
if (status == MagickFalse)
break;
if ((verbose != MagickFalse) && ((i % MagickMax(tick,1)) == 0))
(void) FormatLocaleFile(stderr," %g: %g\n",(double) i,(double) residual);
if (residual < residual_threshold)
{
if (verbose != MagickFalse)
(void) FormatLocaleFile(stderr," %g: %g\n",(double) i,(double)
residual);
break;
}
if (residual_image != (Image *) NULL)
residual_image=DestroyImage(residual_image);
residual_image=CloneImage(relax_image,0,0,MagickTrue,exception);
if (residual_image == (Image *) NULL)
break;
}
kernel_info=DestroyKernelInfo(kernel_info);
mean_image=DestroyImage(mean_image);
residual_image=DestroyImage(residual_image);
/*
Composite the foreground image over the background image.
*/
foreground_image=BlendSumImage(source_image,relax_image,1.0,1.0,exception);
relax_image=DestroyImage(relax_image);
if (foreground_image == (Image *) NULL)
return(MagickFalse);
(void) SetImageMask(foreground_image,ReadPixelMask,(const Image *) NULL,
exception);
status=CompositeOverImage(image,foreground_image,MagickTrue,x_offset,y_offset,
exception);
foreground_image=DestroyImage(foreground_image);
return(status);
}
MagickExport MagickBooleanType CompositeImage(Image *image,
const Image *composite,const CompositeOperator compose,
const MagickBooleanType clip_to_self,const ssize_t x_offset,
const ssize_t y_offset,ExceptionInfo *exception)
{
#define CompositeImageTag "Composite/Image"
CacheView
*source_view,
*image_view;
const char
*value;
GeometryInfo
geometry_info;
Image
*canvas_image,
*source_image;
MagickBooleanType
clamp,
compose_sync,
status;
MagickOffsetType
progress;
MagickRealType
amount,
canvas_dissolve,
midpoint,
percent_luma,
percent_chroma,
source_dissolve,
threshold;
MagickStatusType
flags;
ssize_t
y;
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
assert(composite != (Image *) NULL);
assert(composite->signature == MagickCoreSignature);
if (SetImageStorageClass(image,DirectClass,exception) == MagickFalse)
return(MagickFalse);
source_image=CloneImage(composite,0,0,MagickTrue,exception);
if (source_image == (const Image *) NULL)
return(MagickFalse);
(void) SetImageColorspace(source_image,image->colorspace,exception);
if ((compose == OverCompositeOp) || (compose == SrcOverCompositeOp))
{
status=CompositeOverImage(image,source_image,clip_to_self,x_offset,
y_offset,exception);
source_image=DestroyImage(source_image);
return(status);
}
amount=0.5;
canvas_image=(Image *) NULL;
canvas_dissolve=1.0;
clamp=MagickTrue;
value=GetImageArtifact(image,"compose:clamp");
if (value != (const char *) NULL)
clamp=IsStringTrue(value);
compose_sync=MagickTrue;
value=GetImageArtifact(image,"compose:sync");
if (value != (const char *) NULL)
compose_sync=IsStringTrue(value);
SetGeometryInfo(&geometry_info);
percent_luma=100.0;
percent_chroma=100.0;
source_dissolve=1.0;
threshold=0.05f;
switch (compose)
{
case CopyCompositeOp:
{
if ((x_offset < 0) || (y_offset < 0))
break;
if ((x_offset+(ssize_t) source_image->columns) > (ssize_t) image->columns)
break;
if ((y_offset+(ssize_t) source_image->rows) > (ssize_t) image->rows)
break;
if ((source_image->alpha_trait == UndefinedPixelTrait) &&
(image->alpha_trait != UndefinedPixelTrait))
(void) SetImageAlphaChannel(source_image,OpaqueAlphaChannel,exception);
status=MagickTrue;
source_view=AcquireVirtualCacheView(source_image,exception);
image_view=AcquireAuthenticCacheView(image,exception);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static) shared(status) \
magick_number_threads(source_image,image,source_image->rows,1)
#endif
for (y=0; y < (ssize_t) source_image->rows; y++)
{
MagickBooleanType
sync;
const Quantum
*p;
Quantum
*q;
ssize_t
x;
if (status == MagickFalse)
continue;
p=GetCacheViewVirtualPixels(source_view,0,y,source_image->columns,1,
exception);
q=GetCacheViewAuthenticPixels(image_view,x_offset,y+y_offset,
source_image->columns,1,exception);
if ((p == (const Quantum *) NULL) || (q == (Quantum *) NULL))
{
status=MagickFalse;
continue;
}
for (x=0; x < (ssize_t) source_image->columns; x++)
{
ssize_t
i;
if (GetPixelReadMask(source_image,p) <= (QuantumRange/2))
{
p+=GetPixelChannels(source_image);
q+=GetPixelChannels(image);
continue;
}
for (i=0; i < (ssize_t) GetPixelChannels(source_image); i++)
{
PixelChannel channel = GetPixelChannelChannel(source_image,i);
PixelTrait source_traits = GetPixelChannelTraits(source_image,
channel);
PixelTrait traits = GetPixelChannelTraits(image,channel);
if ((source_traits == UndefinedPixelTrait) ||
(traits == UndefinedPixelTrait))
continue;
SetPixelChannel(image,channel,p[i],q);
}
p+=GetPixelChannels(source_image);
q+=GetPixelChannels(image);
}
sync=SyncCacheViewAuthenticPixels(image_view,exception);
if (sync == MagickFalse)
status=MagickFalse;
if (image->progress_monitor != (MagickProgressMonitor) NULL)
{
MagickBooleanType
proceed;
proceed=SetImageProgress(image,CompositeImageTag,(MagickOffsetType)
y,image->rows);
if (proceed == MagickFalse)
status=MagickFalse;
}
}
source_view=DestroyCacheView(source_view);
image_view=DestroyCacheView(image_view);
source_image=DestroyImage(source_image);
return(status);
}
case IntensityCompositeOp:
{
if ((x_offset < 0) || (y_offset < 0))
break;
if ((x_offset+(ssize_t) source_image->columns) > (ssize_t) image->columns)
break;
if ((y_offset+(ssize_t) source_image->rows) > (ssize_t) image->rows)
break;
status=MagickTrue;
source_view=AcquireVirtualCacheView(source_image,exception);
image_view=AcquireAuthenticCacheView(image,exception);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static) shared(status) \
magick_number_threads(source_image,image,source_image->rows,1)
#endif
for (y=0; y < (ssize_t) source_image->rows; y++)
{
MagickBooleanType
sync;
const Quantum
*p;
Quantum
*q;
ssize_t
x;
if (status == MagickFalse)
continue;
p=GetCacheViewVirtualPixels(source_view,0,y,source_image->columns,1,
exception);
q=GetCacheViewAuthenticPixels(image_view,x_offset,y+y_offset,
source_image->columns,1,exception);
if ((p == (const Quantum *) NULL) || (q == (Quantum *) NULL))
{
status=MagickFalse;
continue;
}
for (x=0; x < (ssize_t) source_image->columns; x++)
{
if (GetPixelReadMask(source_image,p) <= (QuantumRange/2))
{
p+=GetPixelChannels(source_image);
q+=GetPixelChannels(image);
continue;
}
SetPixelAlpha(image,clamp != MagickFalse ?
ClampPixel(GetPixelIntensity(source_image,p)) :
ClampToQuantum(GetPixelIntensity(source_image,p)),q);
p+=GetPixelChannels(source_image);
q+=GetPixelChannels(image);
}
sync=SyncCacheViewAuthenticPixels(image_view,exception);
if (sync == MagickFalse)
status=MagickFalse;
if (image->progress_monitor != (MagickProgressMonitor) NULL)
{
MagickBooleanType
proceed;
proceed=SetImageProgress(image,CompositeImageTag,(MagickOffsetType)
y,image->rows);
if (proceed == MagickFalse)
status=MagickFalse;
}
}
source_view=DestroyCacheView(source_view);
image_view=DestroyCacheView(image_view);
source_image=DestroyImage(source_image);
return(status);
}
case CopyAlphaCompositeOp:
case ChangeMaskCompositeOp:
{
/*
Modify canvas outside the overlaid region and require an alpha
channel to exist, to add transparency.
*/
if (image->alpha_trait == UndefinedPixelTrait)
(void) SetImageAlphaChannel(image,OpaqueAlphaChannel,exception);
break;
}
case BlurCompositeOp:
{
CacheView
*canvas_view;
double
angle_range,
angle_start,
height,
width;
PixelInfo
pixel;
ResampleFilter
*resample_filter;
SegmentInfo
blur;
/*
Blur Image by resampling dictated by an overlay gradient map:
X = red_channel; Y = green_channel; compose:args =
x_scale[,y_scale[,angle]].
*/
canvas_image=CloneImage(image,0,0,MagickTrue,exception);
if (canvas_image == (Image *) NULL)
{
source_image=DestroyImage(source_image);
return(MagickFalse);
}
/*
Gather the maximum blur sigma values from user.
*/
flags=NoValue;
value=GetImageArtifact(image,"compose:args");
if (value != (const char *) NULL)
flags=ParseGeometry(value,&geometry_info);
if ((flags & WidthValue) == 0)
{
(void) ThrowMagickException(exception,GetMagickModule(),OptionWarning,
"InvalidSetting","'%s' '%s'","compose:args",value);
source_image=DestroyImage(source_image);
canvas_image=DestroyImage(canvas_image);
return(MagickFalse);
}
/*
Users input sigma now needs to be converted to the EWA ellipse size.
The filter defaults to a sigma of 0.5 so to make this match the users
input the ellipse size needs to be doubled.
*/
width=2.0*geometry_info.rho;
height=width;
if ((flags & HeightValue) != 0)
height=2.0*geometry_info.sigma;
/*
Default the unrotated ellipse width and height axis vectors.
*/
blur.x1=width;
blur.x2=0.0;
blur.y1=0.0;
blur.y2=height;
if ((flags & XValue) != 0 )
{
MagickRealType
angle;
/*
Rotate vectors if a rotation angle is given.
*/
angle=DegreesToRadians(geometry_info.xi);
blur.x1=width*cos(angle);
blur.x2=width*sin(angle);
blur.y1=(-height*sin(angle));
blur.y2=height*cos(angle);
}
angle_start=0.0;
angle_range=0.0;
if ((flags & YValue) != 0 )
{
/*
Lets set a angle range and calculate in the loop.
*/
angle_start=DegreesToRadians(geometry_info.xi);
angle_range=DegreesToRadians(geometry_info.psi)-angle_start;
}
/*
Set up a gaussian cylindrical filter for EWA Bluring.
As the minimum ellipse radius of support*1.0 the EWA algorithm
can only produce a minimum blur of 0.5 for Gaussian (support=2.0)
This means that even 'No Blur' will be still a little blurry! The
solution (as well as the problem of preventing any user expert filter
settings, is to set our own user settings, restore them afterwards.
*/
resample_filter=AcquireResampleFilter(image,exception);
SetResampleFilter(resample_filter,GaussianFilter);
/*
Perform the variable blurring of each pixel in image.
*/
GetPixelInfo(image,&pixel);
source_view=AcquireVirtualCacheView(source_image,exception);
canvas_view=AcquireAuthenticCacheView(canvas_image,exception);
for (y=0; y < (ssize_t) source_image->rows; y++)
{
MagickBooleanType
sync;
const Quantum
*magick_restrict p;
Quantum
*magick_restrict q;
ssize_t
x;
if (((y+y_offset) < 0) || ((y+y_offset) >= (ssize_t) image->rows))
continue;
p=GetCacheViewVirtualPixels(source_view,0,y,source_image->columns,1,
exception);
q=QueueCacheViewAuthenticPixels(canvas_view,0,y,canvas_image->columns,1,
exception);
if ((p == (const Quantum *) NULL) || (q == (Quantum *) NULL))
break;
for (x=0; x < (ssize_t) source_image->columns; x++)
{
if (((x_offset+x) < 0) || ((x_offset+x) >= (ssize_t) image->columns))
{
p+=GetPixelChannels(source_image);
continue;
}
if (fabs(angle_range) > MagickEpsilon)
{
MagickRealType
angle;
angle=angle_start+angle_range*QuantumScale*
GetPixelBlue(source_image,p);
blur.x1=width*cos(angle);
blur.x2=width*sin(angle);
blur.y1=(-height*sin(angle));
blur.y2=height*cos(angle);
}
ScaleResampleFilter(resample_filter,
blur.x1*QuantumScale*GetPixelRed(source_image,p),
blur.y1*QuantumScale*GetPixelGreen(source_image,p),
blur.x2*QuantumScale*GetPixelRed(source_image,p),
blur.y2*QuantumScale*GetPixelGreen(source_image,p) );
(void) ResamplePixelColor(resample_filter,(double) x_offset+x,
(double) y_offset+y,&pixel,exception);
SetPixelViaPixelInfo(canvas_image,&pixel,q);
p+=GetPixelChannels(source_image);
q+=GetPixelChannels(canvas_image);
}
sync=SyncCacheViewAuthenticPixels(canvas_view,exception);
if (sync == MagickFalse)
break;
}
resample_filter=DestroyResampleFilter(resample_filter);
source_view=DestroyCacheView(source_view);
canvas_view=DestroyCacheView(canvas_view);
source_image=DestroyImage(source_image);
source_image=canvas_image;
break;
}
case DisplaceCompositeOp:
case DistortCompositeOp:
{
CacheView
*canvas_view;
MagickRealType
horizontal_scale,
vertical_scale;
PixelInfo
pixel;
PointInfo
center,
offset;
/*
Displace/Distort based on overlay gradient map:
X = red_channel; Y = green_channel;
compose:args = x_scale[,y_scale[,center.x,center.y]]
*/
canvas_image=CloneImage(image,0,0,MagickTrue,exception);
if (canvas_image == (Image *) NULL)
{
source_image=DestroyImage(source_image);
return(MagickFalse);
}
SetGeometryInfo(&geometry_info);
flags=NoValue;
value=GetImageArtifact(image,"compose:args");
if (value != (char *) NULL)
flags=ParseGeometry(value,&geometry_info);
if ((flags & (WidthValue | HeightValue)) == 0 )
{
if ((flags & AspectValue) == 0)
{
horizontal_scale=(MagickRealType) (source_image->columns-1)/2.0;
vertical_scale=(MagickRealType) (source_image->rows-1)/2.0;
}
else
{
horizontal_scale=(MagickRealType) (image->columns-1)/2.0;
vertical_scale=(MagickRealType) (image->rows-1)/2.0;
}
}
else
{
horizontal_scale=geometry_info.rho;
vertical_scale=geometry_info.sigma;
if ((flags & PercentValue) != 0)
{
if ((flags & AspectValue) == 0)
{
horizontal_scale*=(source_image->columns-1)/200.0;
vertical_scale*=(source_image->rows-1)/200.0;
}
else
{
horizontal_scale*=(image->columns-1)/200.0;
vertical_scale*=(image->rows-1)/200.0;
}
}
if ((flags & HeightValue) == 0)
vertical_scale=horizontal_scale;
}
/*
Determine fixed center point for absolute distortion map
Absolute distort ==
Displace offset relative to a fixed absolute point
Select that point according to +X+Y user inputs.
default = center of overlay image
arg flag '!' = locations/percentage relative to background image
*/
center.x=(MagickRealType) x_offset;
center.y=(MagickRealType) y_offset;
if (compose == DistortCompositeOp)
{
if ((flags & XValue) == 0)
if ((flags & AspectValue) != 0)
center.x=(MagickRealType) ((image->columns-1)/2.0);
else
center.x=(MagickRealType) (x_offset+(source_image->columns-1)/
2.0);
else
if ((flags & AspectValue) != 0)
center.x=geometry_info.xi;
else
center.x=(MagickRealType) (x_offset+geometry_info.xi);
if ((flags & YValue) == 0)
if ((flags & AspectValue) != 0)
center.y=(MagickRealType) ((image->rows-1)/2.0);
else
center.y=(MagickRealType) (y_offset+(source_image->rows-1)/2.0);
else
if ((flags & AspectValue) != 0)
center.y=geometry_info.psi;
else
center.y=(MagickRealType) (y_offset+geometry_info.psi);
}
/*
Shift the pixel offset point as defined by the provided,
displacement/distortion map. -- Like a lens...
*/
GetPixelInfo(image,&pixel);
image_view=AcquireVirtualCacheView(image,exception);
source_view=AcquireVirtualCacheView(source_image,exception);
canvas_view=AcquireAuthenticCacheView(canvas_image,exception);
for (y=0; y < (ssize_t) source_image->rows; y++)
{
MagickBooleanType
sync;
const Quantum
*magick_restrict p;
Quantum
*magick_restrict q;
ssize_t
x;
if (((y+y_offset) < 0) || ((y+y_offset) >= (ssize_t) image->rows))
continue;
p=GetCacheViewVirtualPixels(source_view,0,y,source_image->columns,1,
exception);
q=QueueCacheViewAuthenticPixels(canvas_view,0,y,canvas_image->columns,1,
exception);
if ((p == (const Quantum *) NULL) || (q == (Quantum *) NULL))
break;
for (x=0; x < (ssize_t) source_image->columns; x++)
{
if (((x_offset+x) < 0) || ((x_offset+x) >= (ssize_t) image->columns))
{
p+=GetPixelChannels(source_image);
continue;
}
/*
Displace the offset.
*/
offset.x=(double) (horizontal_scale*(GetPixelRed(source_image,p)-
(((MagickRealType) QuantumRange+1.0)/2.0)))/(((MagickRealType)
QuantumRange+1.0)/2.0)+center.x+((compose == DisplaceCompositeOp) ?
x : 0);
offset.y=(double) (vertical_scale*(GetPixelGreen(source_image,p)-
(((MagickRealType) QuantumRange+1.0)/2.0)))/(((MagickRealType)
QuantumRange+1.0)/2.0)+center.y+((compose == DisplaceCompositeOp) ?
y : 0);
status=InterpolatePixelInfo(image,image_view,
UndefinedInterpolatePixel,(double) offset.x,(double) offset.y,
&pixel,exception);
if (status == MagickFalse)
break;
/*
Mask with the 'invalid pixel mask' in alpha channel.
*/
pixel.alpha=(MagickRealType) QuantumRange*(QuantumScale*pixel.alpha)*
(QuantumScale*GetPixelAlpha(source_image,p));
SetPixelViaPixelInfo(canvas_image,&pixel,q);
p+=GetPixelChannels(source_image);
q+=GetPixelChannels(canvas_image);
}
if (x < (ssize_t) source_image->columns)
break;
sync=SyncCacheViewAuthenticPixels(canvas_view,exception);
if (sync == MagickFalse)
break;
}
canvas_view=DestroyCacheView(canvas_view);
source_view=DestroyCacheView(source_view);
image_view=DestroyCacheView(image_view);
source_image=DestroyImage(source_image);
source_image=canvas_image;
break;
}
case DissolveCompositeOp:
{
/*
Geometry arguments to dissolve factors.
*/
value=GetImageArtifact(image,"compose:args");
if (value != (char *) NULL)
{
flags=ParseGeometry(value,&geometry_info);
source_dissolve=geometry_info.rho/100.0;
canvas_dissolve=1.0;
if ((source_dissolve-MagickEpsilon) < 0.0)
source_dissolve=0.0;
if ((source_dissolve+MagickEpsilon) > 1.0)
{
canvas_dissolve=2.0-source_dissolve;
source_dissolve=1.0;
}
if ((flags & SigmaValue) != 0)
canvas_dissolve=geometry_info.sigma/100.0;
if ((canvas_dissolve-MagickEpsilon) < 0.0)
canvas_dissolve=0.0;
}
break;
}
case BlendCompositeOp:
{
value=GetImageArtifact(image,"compose:args");
if (value != (char *) NULL)
{
flags=ParseGeometry(value,&geometry_info);
source_dissolve=geometry_info.rho/100.0;
canvas_dissolve=1.0-source_dissolve;
if ((flags & SigmaValue) != 0)
canvas_dissolve=geometry_info.sigma/100.0;
}
break;
}
case SaliencyBlendCompositeOp:
{
double
residual_threshold = 0.0002,
iterations = 400.0;
size_t
tick = 100;
value=GetImageArtifact(image,"compose:args");
if (value != (char *) NULL)
{
flags=ParseGeometry(value,&geometry_info);
iterations=geometry_info.rho;
if ((flags & SigmaValue) != 0)
residual_threshold=geometry_info.sigma;
if ((flags & XiValue) != 0)
tick=(size_t) geometry_info.xi;
}
status=SaliencyBlendImage(image,composite,x_offset,y_offset,iterations,
residual_threshold,tick,exception);
source_image=DestroyImage(source_image);
return(status);
}
case SeamlessBlendCompositeOp:
{
double
residual_threshold = 0.0002,
iterations = 400.0;
size_t
tick = 100;
value=GetImageArtifact(image,"compose:args");
if (value != (char *) NULL)
{
flags=ParseGeometry(value,&geometry_info);
iterations=geometry_info.rho;
if ((flags & SigmaValue) != 0)
residual_threshold=geometry_info.sigma;
if ((flags & XiValue) != 0)
tick=(size_t) geometry_info.xi;
}
status=SeamlessBlendImage(image,composite,x_offset,y_offset,iterations,
residual_threshold,tick,exception);
source_image=DestroyImage(source_image);
return(status);
}
case MathematicsCompositeOp:
{
/*
Just collect the values from "compose:args", setting.
Unused values are set to zero automagically.
Arguments are normally a comma separated list, so this probably should
be changed to some 'general comma list' parser, (with a minimum
number of values)
*/
SetGeometryInfo(&geometry_info);
value=GetImageArtifact(image,"compose:args");
if (value != (char *) NULL)
{
flags=ParseGeometry(value,&geometry_info);
if (flags == NoValue)
(void) ThrowMagickException(exception,GetMagickModule(),OptionError,
"InvalidGeometry","`%s'",value);
}
break;
}
case ModulateCompositeOp:
{
/*
Determine the luma and chroma scale.
*/
value=GetImageArtifact(image,"compose:args");
if (value != (char *) NULL)
{
flags=ParseGeometry(value,&geometry_info);
percent_luma=geometry_info.rho;
if ((flags & SigmaValue) != 0)
percent_chroma=geometry_info.sigma;
}
break;
}
case ThresholdCompositeOp:
{
/*
Determine the amount and threshold.
*/
value=GetImageArtifact(image,"compose:args");
if (value != (char *) NULL)
{
flags=ParseGeometry(value,&geometry_info);
amount=geometry_info.rho;
threshold=geometry_info.sigma;
if ((flags & SigmaValue) == 0)
threshold=0.05f;
}
threshold*=QuantumRange;
break;
}
default:
break;
}
/*
Composite image.
*/
status=MagickTrue;
progress=0;
midpoint=((MagickRealType) QuantumRange+1.0)/2;
source_view=AcquireVirtualCacheView(source_image,exception);
image_view=AcquireAuthenticCacheView(image,exception);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static) shared(progress,status) \
magick_number_threads(source_image,image,image->rows,1)
#endif
for (y=0; y < (ssize_t) image->rows; y++)
{
const Quantum
*pixels;
MagickRealType
blue,
chroma,
green,
hue,
luma,
red;
PixelInfo
canvas_pixel,
source_pixel;
const Quantum
*magick_restrict p;
Quantum
*magick_restrict q;
ssize_t
x;
if (status == MagickFalse)
continue;
if (clip_to_self != MagickFalse)
{
if (y < y_offset)
continue;
if ((y-y_offset) >= (ssize_t) source_image->rows)
continue;
}
/*
If pixels is NULL, y is outside overlay region.
*/
pixels=(Quantum *) NULL;
p=(Quantum *) NULL;
if ((y >= y_offset) && ((y-y_offset) < (ssize_t) source_image->rows))
{
p=GetCacheViewVirtualPixels(source_view,0,y-y_offset,
source_image->columns,1,exception);
if (p == (const Quantum *) NULL)
{
status=MagickFalse;
continue;
}
pixels=p;
if (x_offset < 0)
p-=x_offset*(ssize_t) GetPixelChannels(source_image);
}
q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception);
if (q == (Quantum *) NULL)
{
status=MagickFalse;
continue;
}
hue=0.0;
chroma=0.0;
luma=0.0;
GetPixelInfo(image,&canvas_pixel);
GetPixelInfo(source_image,&source_pixel);
for (x=0; x < (ssize_t) image->columns; x++)
{
double
gamma;
MagickRealType
alpha,
Da,
Dc,
Dca,
DcaDa,
Sa,
SaSca,
Sc,
Sca;
ssize_t
i;
size_t
channels;
if (clip_to_self != MagickFalse)
{
if (x < x_offset)
{
q+=GetPixelChannels(image);
continue;
}
if ((x-x_offset) >= (ssize_t) source_image->columns)
break;
}
if ((pixels == (Quantum *) NULL) || (x < x_offset) ||
((x-x_offset) >= (ssize_t) source_image->columns))
{
Quantum
source[MaxPixelChannels];
/*
Virtual composite:
Sc: source color.
Dc: canvas color.
*/
(void) GetOneVirtualPixel(source_image,x-x_offset,y-y_offset,source,
exception);
for (i=0; i < (ssize_t) GetPixelChannels(image); i++)
{
MagickRealType
pixel;
PixelChannel channel = GetPixelChannelChannel(image,i);
PixelTrait traits = GetPixelChannelTraits(image,channel);
PixelTrait source_traits=GetPixelChannelTraits(source_image,
channel);
if ((traits == UndefinedPixelTrait) ||
(source_traits == UndefinedPixelTrait))
continue;
switch (compose)
{
case AlphaCompositeOp:
case ChangeMaskCompositeOp:
case CopyAlphaCompositeOp:
case DstAtopCompositeOp:
case DstInCompositeOp:
case InCompositeOp:
case OutCompositeOp:
case SrcInCompositeOp:
case SrcOutCompositeOp:
{
if (channel == AlphaPixelChannel)
pixel=(MagickRealType) TransparentAlpha;
else
pixel=(MagickRealType) q[i];
break;
}
case ClearCompositeOp:
case CopyCompositeOp:
case ReplaceCompositeOp:
case SrcCompositeOp:
{
if (channel == AlphaPixelChannel)
pixel=(MagickRealType) TransparentAlpha;
else
pixel=0.0;
break;
}
case BlendCompositeOp:
case DissolveCompositeOp:
{
if (channel == AlphaPixelChannel)
pixel=canvas_dissolve*GetPixelAlpha(source_image,source);
else
pixel=(MagickRealType) source[channel];
break;
}
default:
{
pixel=(MagickRealType) source[channel];
break;
}
}
q[i]=clamp != MagickFalse ? ClampPixel(pixel) :
ClampToQuantum(pixel);
}
q+=GetPixelChannels(image);
continue;
}
/*
Authentic composite:
Sa: normalized source alpha.
Da: normalized canvas alpha.
*/
Sa=QuantumScale*GetPixelAlpha(source_image,p);
Da=QuantumScale*GetPixelAlpha(image,q);
switch (compose)
{
case BumpmapCompositeOp:
case ColorBurnCompositeOp:
case ColorDodgeCompositeOp:
case DarkenCompositeOp:
case DifferenceCompositeOp:
case DivideDstCompositeOp:
case DivideSrcCompositeOp:
case ExclusionCompositeOp:
case FreezeCompositeOp:
case HardLightCompositeOp:
case HardMixCompositeOp:
case InterpolateCompositeOp:
case LightenCompositeOp:
case LinearBurnCompositeOp:
case LinearDodgeCompositeOp:
case LinearLightCompositeOp:
case MathematicsCompositeOp:
case MinusDstCompositeOp:
case MinusSrcCompositeOp:
case MultiplyCompositeOp:
case NegateCompositeOp:
case OverlayCompositeOp:
case PegtopLightCompositeOp:
case PinLightCompositeOp:
case ReflectCompositeOp:
case ScreenCompositeOp:
case SoftBurnCompositeOp:
case SoftDodgeCompositeOp:
case SoftLightCompositeOp:
case StampCompositeOp:
case VividLightCompositeOp:
{
alpha=RoundToUnity(Sa+Da-Sa*Da);
break;
}
case DstAtopCompositeOp:
case DstInCompositeOp:
case InCompositeOp:
case SrcInCompositeOp:
{
alpha=Sa*Da;
break;
}
case DissolveCompositeOp:
{
alpha=source_dissolve*Sa*(-canvas_dissolve*Da)+source_dissolve*Sa+
canvas_dissolve*Da;
break;
}
case DstOverCompositeOp:
case OverCompositeOp:
case SrcOverCompositeOp:
{
alpha=Sa+Da-Sa*Da;
break;
}
case DstOutCompositeOp:
{
alpha=Da*(1.0-Sa);
break;
}
case OutCompositeOp:
case SrcOutCompositeOp:
{
alpha=Sa*(1.0-Da);
break;
}
case BlendCompositeOp:
case PlusCompositeOp:
{
alpha=RoundToUnity(source_dissolve*Sa+canvas_dissolve*Da);
break;
}
case XorCompositeOp:
{
alpha=Sa+Da-2.0*Sa*Da;
break;
}
case ModulusAddCompositeOp:
{
if ((Sa+Da) <= 1.0)
{
alpha=(Sa+Da);
break;
}
alpha=((Sa+Da)-1.0);
break;
}
case ModulusSubtractCompositeOp:
{
if ((Sa-Da) >= 0.0)
{
alpha=(Sa-Da);
break;
}
alpha=((Sa-Da)+1.0);
break;
}
default:
{
alpha=1.0;
break;
}
}
switch (compose)
{
case ColorizeCompositeOp:
case HueCompositeOp:
case LuminizeCompositeOp:
case ModulateCompositeOp:
case RMSECompositeOp:
case SaturateCompositeOp:
{
GetPixelInfoPixel(source_image,p,&source_pixel);
GetPixelInfoPixel(image,q,&canvas_pixel);
break;
}
default:
break;
}
for (i=0; i < (ssize_t) GetPixelChannels(image); i++)
{
MagickRealType
pixel,
sans;
PixelChannel channel = GetPixelChannelChannel(image,i);
PixelTrait traits = GetPixelChannelTraits(image,channel);
PixelTrait source_traits = GetPixelChannelTraits(source_image,channel);
if (traits == UndefinedPixelTrait)
continue;
if ((channel == AlphaPixelChannel) &&
((traits & UpdatePixelTrait) != 0))
{
/*
Set alpha channel.
*/
switch (compose)
{
case AlphaCompositeOp:
{
pixel=QuantumRange*Sa;
break;
}
case AtopCompositeOp:
case CopyBlackCompositeOp:
case CopyBlueCompositeOp:
case CopyCyanCompositeOp:
case CopyGreenCompositeOp:
case CopyMagentaCompositeOp:
case CopyRedCompositeOp:
case CopyYellowCompositeOp:
case SrcAtopCompositeOp:
case DstCompositeOp:
case NoCompositeOp:
{
pixel=QuantumRange*Da;
break;
}
case BumpmapCompositeOp:
{
pixel=GetPixelIntensity(source_image,p)*Da;
break;
}
case ChangeMaskCompositeOp:
{
if (IsFuzzyEquivalencePixel(source_image,p,image,q) != MagickFalse)
pixel=(MagickRealType) TransparentAlpha;
else
pixel=QuantumRange*Da;
break;
}
case ClearCompositeOp:
{
pixel=(MagickRealType) TransparentAlpha;
break;
}
case ColorizeCompositeOp:
case HueCompositeOp:
case LuminizeCompositeOp:
case RMSECompositeOp:
case SaturateCompositeOp:
{
if (fabs((double) (QuantumRange*Sa-TransparentAlpha)) < MagickEpsilon)
{
pixel=QuantumRange*Da;
break;
}
if (fabs((double) (QuantumRange*Da-TransparentAlpha)) < MagickEpsilon)
{
pixel=QuantumRange*Sa;
break;
}
if (Sa < Da)
{
pixel=QuantumRange*Da;
break;
}
pixel=QuantumRange*Sa;
break;
}
case CopyAlphaCompositeOp:
{
if (source_image->alpha_trait == UndefinedPixelTrait)
pixel=GetPixelIntensity(source_image,p);
else
pixel=QuantumRange*Sa;
break;
}
case BlurCompositeOp:
case CopyCompositeOp:
case DisplaceCompositeOp:
case DistortCompositeOp:
case DstAtopCompositeOp:
case ReplaceCompositeOp:
case SrcCompositeOp:
{
pixel=QuantumRange*Sa;
break;
}
case DarkenIntensityCompositeOp:
{
if (compose_sync == MagickFalse)
{
pixel=GetPixelIntensity(source_image,p) <
GetPixelIntensity(image,q) ? Sa : Da;
break;
}
pixel=Sa*GetPixelIntensity(source_image,p) <
Da*GetPixelIntensity(image,q) ? Sa : Da;
break;
}
case DifferenceCompositeOp:
{
pixel=QuantumRange*fabs((double) (Sa-Da));
break;
}
case FreezeCompositeOp:
{
pixel=QuantumRange*(1.0-(1.0-Sa)*(1.0-Sa)*
PerceptibleReciprocal(Da));
if (pixel < 0.0)
pixel=0.0;
break;
}
case InterpolateCompositeOp:
{
pixel=QuantumRange*(0.5-0.25*cos(MagickPI*Sa)-0.25*
cos(MagickPI*Da));
break;
}
case LightenIntensityCompositeOp:
{
if (compose_sync == MagickFalse)
{
pixel=GetPixelIntensity(source_image,p) >
GetPixelIntensity(image,q) ? Sa : Da;
break;
}
pixel=Sa*GetPixelIntensity(source_image,p) >
Da*GetPixelIntensity(image,q) ? Sa : Da;
break;
}
case ModulateCompositeOp:
{
pixel=QuantumRange*Da;
break;
}
case MultiplyCompositeOp:
{
if (compose_sync == MagickFalse)
{
pixel=QuantumRange*Sa*Da;
break;
}
pixel=QuantumRange*alpha;
break;
}
case NegateCompositeOp:
{
pixel=QuantumRange*((1.0-Sa-Da));
break;
}
case ReflectCompositeOp:
{
pixel=QuantumRange*(Sa*Sa*PerceptibleReciprocal(1.0-Da));
if (pixel > QuantumRange)
pixel=QuantumRange;
break;
}
case StampCompositeOp:
{
pixel=QuantumRange*(Sa+Da*Da-1.0);
break;
}
case StereoCompositeOp:
{
pixel=QuantumRange*(Sa+Da)/2;
break;
}
default:
{
pixel=QuantumRange*alpha;
break;
}
}
q[i]=clamp != MagickFalse ? ClampPixel(pixel) :
ClampToQuantum(pixel);
continue;
}
if (source_traits == UndefinedPixelTrait)
continue;
/*
Sc: source color.
Dc: canvas color.
*/
Sc=(MagickRealType) GetPixelChannel(source_image,channel,p);
Dc=(MagickRealType) q[i];
if ((traits & CopyPixelTrait) != 0)
{
/*
Copy channel.
*/
q[i]=ClampToQuantum(Dc);
continue;
}
/*
Porter-Duff compositions:
Sca: source normalized color multiplied by alpha.
Dca: normalized canvas color multiplied by alpha.
*/
Sca=QuantumScale*Sa*Sc;
Dca=QuantumScale*Da*Dc;
SaSca=Sa*PerceptibleReciprocal(Sca);
DcaDa=Dca*PerceptibleReciprocal(Da);
switch (compose)
{
case DarkenCompositeOp:
case LightenCompositeOp:
case ModulusSubtractCompositeOp:
{
gamma=PerceptibleReciprocal(1.0-alpha);
break;
}
default:
{
gamma=PerceptibleReciprocal(alpha);
break;
}
}
pixel=Dc;
switch (compose)
{
case AlphaCompositeOp:
{
pixel=QuantumRange*Sa;
break;
}
case AtopCompositeOp:
case SrcAtopCompositeOp:
{
pixel=QuantumRange*(Sca*Da+Dca*(1.0-Sa));
break;
}
case BlendCompositeOp:
{
pixel=gamma*(source_dissolve*Sa*Sc+canvas_dissolve*Da*Dc);
break;
}
case CopyCompositeOp:
case ReplaceCompositeOp:
case SrcCompositeOp:
{
pixel=QuantumRange*Sca;
break;
}
case BlurCompositeOp:
case DisplaceCompositeOp:
case DistortCompositeOp:
{
pixel=Sc;
break;
}
case BumpmapCompositeOp:
{
if (fabs((double) (QuantumRange*Sa-TransparentAlpha)) < MagickEpsilon)
{
pixel=Dc;
break;
}
pixel=QuantumScale*GetPixelIntensity(source_image,p)*Dc;
break;
}
case ChangeMaskCompositeOp:
{
pixel=Dc;
break;
}
case ClearCompositeOp:
{
pixel=0.0;
break;
}
case ColorBurnCompositeOp:
{
if ((Sca == 0.0) && (Dca == Da))
{
pixel=QuantumRange*gamma*(Sa*Da+Dca*(1.0-Sa));
break;
}
if (Sca == 0.0)
{
pixel=QuantumRange*gamma*(Dca*(1.0-Sa));
break;
}
pixel=QuantumRange*gamma*(Sa*Da-Sa*Da*MagickMin(1.0,(1.0-DcaDa)*
SaSca)+Sca*(1.0-Da)+Dca*(1.0-Sa));
break;
}
case ColorDodgeCompositeOp:
{
if ((Sca*Da+Dca*Sa) >= Sa*Da)
pixel=QuantumRange*gamma*(Sa*Da+Sca*(1.0-Da)+Dca*(1.0-Sa));
else
pixel=QuantumRange*gamma*(Dca*Sa*Sa*PerceptibleReciprocal(Sa-Sca)+
Sca*(1.0-Da)+Dca*(1.0-Sa));
break;
}
case ColorizeCompositeOp:
{
if (fabs((double) (QuantumRange*Sa-TransparentAlpha)) < MagickEpsilon)
{
pixel=Dc;
break;
}
if (fabs((double) (QuantumRange*Da-TransparentAlpha)) < MagickEpsilon)
{
pixel=Sc;
break;
}
CompositeHCL(canvas_pixel.red,canvas_pixel.green,canvas_pixel.blue,
&sans,&sans,&luma);
CompositeHCL(source_pixel.red,source_pixel.green,source_pixel.blue,
&hue,&chroma,&sans);
HCLComposite(hue,chroma,luma,&red,&green,&blue);
switch (channel)
{
case RedPixelChannel: pixel=red; break;
case GreenPixelChannel: pixel=green; break;
case BluePixelChannel: pixel=blue; break;
default: pixel=Dc; break;
}
break;
}
case CopyAlphaCompositeOp:
{
pixel=Dc;
break;
}
case CopyBlackCompositeOp:
{
if (channel == BlackPixelChannel)
pixel=(MagickRealType) GetPixelBlack(source_image,p);
break;
}
case CopyBlueCompositeOp:
case CopyYellowCompositeOp:
{
if (channel == BluePixelChannel)
pixel=(MagickRealType) GetPixelBlue(source_image,p);
break;
}
case CopyGreenCompositeOp:
case CopyMagentaCompositeOp:
{
if (channel == GreenPixelChannel)
pixel=(MagickRealType) GetPixelGreen(source_image,p);
break;
}
case CopyRedCompositeOp:
case CopyCyanCompositeOp:
{
if (channel == RedPixelChannel)
pixel=(MagickRealType) GetPixelRed(source_image,p);
break;
}
case DarkenCompositeOp:
{
/*
Darken is equivalent to a 'Minimum' method
OR a greyscale version of a binary 'Or'
OR the 'Intersection' of pixel sets.
*/
if (compose_sync == MagickFalse)
{
pixel=MagickMin(Sc,Dc);
break;
}
if ((Sca*Da) < (Dca*Sa))
{
pixel=QuantumRange*(Sca+Dca*(1.0-Sa));
break;
}
pixel=QuantumRange*(Dca+Sca*(1.0-Da));
break;
}
case DarkenIntensityCompositeOp:
{
if (compose_sync == MagickFalse)
{
pixel=GetPixelIntensity(source_image,p) <
GetPixelIntensity(image,q) ? Sc : Dc;
break;
}
pixel=Sa*GetPixelIntensity(source_image,p) <
Da*GetPixelIntensity(image,q) ? Sc : Dc;
break;
}
case DifferenceCompositeOp:
{
if (compose_sync == MagickFalse)
{
pixel=fabs((double) Sc-Dc);
break;
}
pixel=QuantumRange*gamma*(Sca+Dca-2.0*MagickMin(Sca*Da,Dca*Sa));
break;
}
case DissolveCompositeOp:
{
pixel=gamma*(source_dissolve*Sa*Sc-source_dissolve*Sa*
canvas_dissolve*Da*Dc+canvas_dissolve*Da*Dc);
break;
}
case DivideDstCompositeOp:
{
if (compose_sync == MagickFalse)
{
pixel=QuantumRange*(Sc/PerceptibleReciprocal(Dc));
break;
}
if ((fabs((double) Sca) < MagickEpsilon) &&
(fabs((double) Dca) < MagickEpsilon))
{
pixel=QuantumRange*gamma*(Sca*(1.0-Da)+Dca*(1.0-Sa));
break;
}
if (fabs((double) Dca) < MagickEpsilon)
{
pixel=QuantumRange*gamma*(Sa*Da+Sca*(1.0-Da)+Dca*(1.0-Sa));
break;
}
pixel=QuantumRange*gamma*(Sca*Da*Da/Dca+Sca*(1.0-Da)+Dca*(1.0-Sa));
break;
}
case DivideSrcCompositeOp:
{
if (compose_sync == MagickFalse)
{
pixel=QuantumRange*(Dc/PerceptibleReciprocal(Sc));
break;
}
if ((fabs((double) Dca) < MagickEpsilon) &&
(fabs((double) Sca) < MagickEpsilon))
{
pixel=QuantumRange*gamma*(Dca*(1.0-Sa)+Sca*(1.0-Da));
break;
}
if (fabs((double) Sca) < MagickEpsilon)
{
pixel=QuantumRange*gamma*(Da*Sa+Dca*(1.0-Sa)+Sca*(1.0-Da));
break;
}
pixel=QuantumRange*gamma*(Dca*Sa*SaSca+Dca*(1.0-Sa)+Sca*(1.0-Da));
break;
}
case DstAtopCompositeOp:
{
pixel=QuantumRange*(Dca*Sa+Sca*(1.0-Da));
break;
}
case DstCompositeOp:
case NoCompositeOp:
{
pixel=QuantumRange*Dca;
break;
}
case DstInCompositeOp:
{
pixel=QuantumRange*gamma*(Dca*Sa);
break;
}
case DstOutCompositeOp:
{
pixel=QuantumRange*gamma*(Dca*(1.0-Sa));
break;
}
case DstOverCompositeOp:
{
pixel=QuantumRange*gamma*(Dca+Sca*(1.0-Da));
break;
}
case ExclusionCompositeOp:
{
pixel=QuantumRange*gamma*(Sca*Da+Dca*Sa-2.0*Sca*Dca+Sca*(1.0-Da)+
Dca*(1.0-Sa));
break;
}
case FreezeCompositeOp:
{
pixel=QuantumRange*gamma*(1.0-(1.0-Sca)*(1.0-Sca)*
PerceptibleReciprocal(Dca));
if (pixel < 0.0)
pixel=0.0;
break;
}
case HardLightCompositeOp:
{
if ((2.0*Sca) < Sa)
{
pixel=QuantumRange*gamma*(2.0*Sca*Dca+Sca*(1.0-Da)+Dca*(1.0-
Sa));
break;
}
pixel=QuantumRange*gamma*(Sa*Da-2.0*(Da-Dca)*(Sa-Sca)+Sca*(1.0-Da)+
Dca*(1.0-Sa));
break;
}
case HardMixCompositeOp:
{
pixel=gamma*(((Sca+Dca) < 1.0) ? 0.0 : QuantumRange);
break;
}
case HueCompositeOp:
{
if (fabs((double) (QuantumRange*Sa-TransparentAlpha)) < MagickEpsilon)
{
pixel=Dc;
break;
}
if (fabs((double) (QuantumRange*Da-TransparentAlpha)) < MagickEpsilon)
{
pixel=Sc;
break;
}
CompositeHCL(canvas_pixel.red,canvas_pixel.green,canvas_pixel.blue,
&hue,&chroma,&luma);
CompositeHCL(source_pixel.red,source_pixel.green,source_pixel.blue,
&hue,&sans,&sans);
HCLComposite(hue,chroma,luma,&red,&green,&blue);
switch (channel)
{
case RedPixelChannel: pixel=red; break;
case GreenPixelChannel: pixel=green; break;
case BluePixelChannel: pixel=blue; break;
default: pixel=Dc; break;
}
break;
}
case InCompositeOp:
case SrcInCompositeOp:
{
pixel=QuantumRange*(Sca*Da);
break;
}
case InterpolateCompositeOp:
{
pixel=QuantumRange*(0.5-0.25*cos(MagickPI*Sca)-0.25*
cos(MagickPI*Dca));
break;
}
case LinearBurnCompositeOp:
{
/*
LinearBurn: as defined by Abode Photoshop, according to
http://www.simplefilter.de/en/basics/mixmods.html is:
f(Sc,Dc) = Sc + Dc - 1
*/
pixel=QuantumRange*gamma*(Sca+Dca-Sa*Da);
break;
}
case LinearDodgeCompositeOp:
{
pixel=gamma*(Sa*Sc+Da*Dc);
break;
}
case LinearLightCompositeOp:
{
/*
LinearLight: as defined by Abode Photoshop, according to
http://www.simplefilter.de/en/basics/mixmods.html is:
f(Sc,Dc) = Dc + 2*Sc - 1
*/
pixel=QuantumRange*gamma*((Sca-Sa)*Da+Sca+Dca);
break;
}
case LightenCompositeOp:
{
if (compose_sync == MagickFalse)
{
pixel=MagickMax(Sc,Dc);
break;
}
if ((Sca*Da) > (Dca*Sa))
{
pixel=QuantumRange*(Sca+Dca*(1.0-Sa));
break;
}
pixel=QuantumRange*(Dca+Sca*(1.0-Da));
break;
}
case LightenIntensityCompositeOp:
{
/*
Lighten is equivalent to a 'Maximum' method
OR a greyscale version of a binary 'And'
OR the 'Union' of pixel sets.
*/
if (compose_sync == MagickFalse)
{
pixel=GetPixelIntensity(source_image,p) >
GetPixelIntensity(image,q) ? Sc : Dc;
break;
}
pixel=Sa*GetPixelIntensity(source_image,p) >
Da*GetPixelIntensity(image,q) ? Sc : Dc;
break;
}
case LuminizeCompositeOp:
{
if (fabs((double) (QuantumRange*Sa-TransparentAlpha)) < MagickEpsilon)
{
pixel=Dc;
break;
}
if (fabs((double) (QuantumRange*Da-TransparentAlpha)) < MagickEpsilon)
{
pixel=Sc;
break;
}
CompositeHCL(canvas_pixel.red,canvas_pixel.green,canvas_pixel.blue,
&hue,&chroma,&luma);
CompositeHCL(source_pixel.red,source_pixel.green,source_pixel.blue,
&sans,&sans,&luma);
HCLComposite(hue,chroma,luma,&red,&green,&blue);
switch (channel)
{
case RedPixelChannel: pixel=red; break;
case GreenPixelChannel: pixel=green; break;
case BluePixelChannel: pixel=blue; break;
default: pixel=Dc; break;
}
break;
}
case MathematicsCompositeOp:
{
/*
'Mathematics' a free form user control mathematical composition
is defined as...
f(Sc,Dc) = A*Sc*Dc + B*Sc + C*Dc + D
Where the arguments A,B,C,D are (currently) passed to composite
as a command separated 'geometry' string in "compose:args" image
artifact.
A = a->rho, B = a->sigma, C = a->xi, D = a->psi
Applying the SVG transparency formula (see above), we get...
Dca' = Sa*Da*f(Sc,Dc) + Sca*(1.0-Da) + Dca*(1.0-Sa)
Dca' = A*Sca*Dca + B*Sca*Da + C*Dca*Sa + D*Sa*Da + Sca*(1.0-Da) +
Dca*(1.0-Sa)
*/
if (compose_sync == MagickFalse)
{
pixel=geometry_info.rho*Sc*Dc+geometry_info.sigma*Sc+
geometry_info.xi*Dc+geometry_info.psi;
break;
}
pixel=QuantumRange*gamma*(geometry_info.rho*Sca*Dca+
geometry_info.sigma*Sca*Da+geometry_info.xi*Dca*Sa+
geometry_info.psi*Sa*Da+Sca*(1.0-Da)+Dca*(1.0-Sa));
break;
}
case MinusDstCompositeOp:
{
if (compose_sync == MagickFalse)
{
pixel=Dc-Sc;
break;
}
pixel=gamma*(Sa*Sc+Da*Dc-2.0*Da*Dc*Sa);
break;
}
case MinusSrcCompositeOp:
{
/*
Minus source from canvas.
f(Sc,Dc) = Sc - Dc
*/
if (compose_sync == MagickFalse)
{
pixel=Sc-Dc;
break;
}
pixel=gamma*(Da*Dc+Sa*Sc-2.0*Sa*Sc*Da);
break;
}
case ModulateCompositeOp:
{
ssize_t
offset;
if (fabs((double) (QuantumRange*Sa-TransparentAlpha)) < MagickEpsilon)
{
pixel=Dc;
break;
}
offset=(ssize_t) (GetPixelIntensity(source_image,p)-midpoint);
if (offset == 0)
{
pixel=Dc;
break;
}
CompositeHCL(canvas_pixel.red,canvas_pixel.green,canvas_pixel.blue,
&hue,&chroma,&luma);
luma+=(0.01*percent_luma*offset)/midpoint;
chroma*=0.01*percent_chroma;
HCLComposite(hue,chroma,luma,&red,&green,&blue);
switch (channel)
{
case RedPixelChannel: pixel=red; break;
case GreenPixelChannel: pixel=green; break;
case BluePixelChannel: pixel=blue; break;
default: pixel=Dc; break;
}
break;
}
case ModulusAddCompositeOp:
{
if (compose_sync == MagickFalse)
{
pixel=(Sc+Dc);
break;
}
if ((Sca+Dca) <= 1.0)
{
pixel=QuantumRange*(Sca+Dca);
break;
}
pixel=QuantumRange*((Sca+Dca)-1.0);
break;
}
case ModulusSubtractCompositeOp:
{
if (compose_sync == MagickFalse)
{
pixel=(Sc-Dc);
break;
}
if ((Sca-Dca) >= 0.0)
{
pixel=QuantumRange*(Sca-Dca);
break;
}
pixel=QuantumRange*((Sca-Dca)+1.0);
break;
}
case MultiplyCompositeOp:
{
if (compose_sync == MagickFalse)
{
pixel=QuantumScale*Dc*Sc;
break;
}
pixel=QuantumRange*gamma*(Sca*Dca+Sca*(1.0-Da)+Dca*(1.0-Sa));
break;
}
case NegateCompositeOp:
{
pixel=QuantumRange*(1.0-fabs(1.0-Sca-Dca));
break;
}
case OutCompositeOp:
case SrcOutCompositeOp:
{
pixel=QuantumRange*(Sca*(1.0-Da));
break;
}
case OverCompositeOp:
case SrcOverCompositeOp:
{
pixel=QuantumRange*gamma*(Sca+Dca*(1.0-Sa));
break;
}
case OverlayCompositeOp:
{
if ((2.0*Dca) < Da)
{
pixel=QuantumRange*gamma*(2.0*Dca*Sca+Dca*(1.0-Sa)+Sca*(1.0-
Da));
break;
}
pixel=QuantumRange*gamma*(Da*Sa-2.0*(Sa-Sca)*(Da-Dca)+Dca*(1.0-Sa)+
Sca*(1.0-Da));
break;
}
case PegtopLightCompositeOp:
{
/*
PegTop: A Soft-Light alternative: A continuous version of the
Softlight function, producing very similar results.
f(Sc,Dc) = Dc^2*(1-2*Sc) + 2*Sc*Dc
http://www.pegtop.net/delphi/articles/blendmodes/softlight.htm.
*/
if (fabs((double) Da) < MagickEpsilon)
{
pixel=QuantumRange*gamma*Sca;
break;
}
pixel=QuantumRange*gamma*(Dca*Dca*(Sa-2.0*Sca)/Da+Sca*(2.0*Dca+1.0-
Da)+Dca*(1.0-Sa));
break;
}
case PinLightCompositeOp:
{
/*
PinLight: A Photoshop 7 composition method
http://www.simplefilter.de/en/basics/mixmods.html
f(Sc,Dc) = Dc<2*Sc-1 ? 2*Sc-1 : Dc>2*Sc ? 2*Sc : Dc
*/
if ((Dca*Sa) < (Da*(2.0*Sca-Sa)))
{
pixel=QuantumRange*gamma*(Sca*(Da+1.0)-Sa*Da+Dca*(1.0-Sa));
break;
}
if ((Dca*Sa) > (2.0*Sca*Da))
{
pixel=QuantumRange*gamma*(Sca*Da+Sca+Dca*(1.0-Sa));
break;
}
pixel=QuantumRange*gamma*(Sca*(1.0-Da)+Dca);
break;
}
case PlusCompositeOp:
{
if (compose_sync == MagickFalse)
{
pixel=(Dc+Sc);
break;
}
pixel=QuantumRange*(Sca+Dca);
break;
}
case ReflectCompositeOp:
{
pixel=QuantumRange*gamma*(Sca*Sca*PerceptibleReciprocal(1.0-Dca));
if (pixel > QuantumRange)
pixel=QuantumRange;
break;
}
case RMSECompositeOp:
{
double
gray;
if (fabs((double) (QuantumRange*Sa-TransparentAlpha)) < MagickEpsilon)
{
pixel=Dc;
break;
}
if (fabs((double) (QuantumRange*Da-TransparentAlpha)) < MagickEpsilon)
{
pixel=Sc;
break;
}
gray=sqrt(
(canvas_pixel.red-source_pixel.red)*
(canvas_pixel.red-source_pixel.red)+
(canvas_pixel.green-source_pixel.green)*
(canvas_pixel.green-source_pixel.green)+
(canvas_pixel.blue-source_pixel.blue)*
(canvas_pixel.blue-source_pixel.blue)/3.0);
switch (channel)
{
case RedPixelChannel: pixel=gray; break;
case GreenPixelChannel: pixel=gray; break;
case BluePixelChannel: pixel=gray; break;
default: pixel=Dc; break;
}
break;
}
case SaturateCompositeOp:
{
if (fabs((double) (QuantumRange*Sa-TransparentAlpha)) < MagickEpsilon)
{
pixel=Dc;
break;
}
if (fabs((double) (QuantumRange*Da-TransparentAlpha)) < MagickEpsilon)
{
pixel=Sc;
break;
}
CompositeHCL(canvas_pixel.red,canvas_pixel.green,canvas_pixel.blue,
&hue,&chroma,&luma);
CompositeHCL(source_pixel.red,source_pixel.green,source_pixel.blue,
&sans,&chroma,&sans);
HCLComposite(hue,chroma,luma,&red,&green,&blue);
switch (channel)
{
case RedPixelChannel: pixel=red; break;
case GreenPixelChannel: pixel=green; break;
case BluePixelChannel: pixel=blue; break;
default: pixel=Dc; break;
}
break;
}
case ScreenCompositeOp:
{
/*
Screen: a negated multiply:
f(Sc,Dc) = 1.0-(1.0-Sc)*(1.0-Dc)
*/
if (compose_sync == MagickFalse)
{
pixel=Sc+Dc-Sc*Dc;
break;
}
pixel=QuantumRange*gamma*(Sca+Dca-Sca*Dca);
break;
}
case SoftBurnCompositeOp:
{
if ((Sca+Dca) < 1.0)
pixel=QuantumRange*gamma*(0.5*Dca*PerceptibleReciprocal(1.0-Sca));
else
pixel=QuantumRange*gamma*(1.0-0.5*(1.0-Sca)*
PerceptibleReciprocal(Dca));
break;
}
case SoftDodgeCompositeOp:
{
if ((Sca+Dca) < 1.0)
pixel=QuantumRange*gamma*(0.5*Sca*PerceptibleReciprocal(1.0-Dca));
else
pixel=QuantumRange*gamma*(1.0-0.5*(1.0-Dca)*
PerceptibleReciprocal(Sca));
break;
}
case SoftLightCompositeOp:
{
if ((2.0*Sca) < Sa)
{
pixel=QuantumRange*gamma*(Dca*(Sa+(2.0*Sca-Sa)*(1.0-DcaDa))+
Sca*(1.0-Da)+Dca*(1.0-Sa));
break;
}
if (((2.0*Sca) > Sa) && ((4.0*Dca) <= Da))
{
pixel=QuantumRange*gamma*(Dca*Sa+Da*(2.0*Sca-Sa)*(4.0*DcaDa*
(4.0*DcaDa+1.0)*(DcaDa-1.0)+7.0*DcaDa)+Sca*(1.0-Da)+
Dca*(1.0-Sa));
break;
}
pixel=QuantumRange*gamma*(Dca*Sa+Da*(2.0*Sca-Sa)*(pow(DcaDa,0.5)-
DcaDa)+Sca*(1.0-Da)+Dca*(1.0-Sa));
break;
}
case StampCompositeOp:
{
pixel=QuantumRange*(Sca+Dca*Dca-1.0);
break;
}
case StereoCompositeOp:
{
if (channel == RedPixelChannel)
pixel=(MagickRealType) GetPixelRed(source_image,p);
break;
}
case ThresholdCompositeOp:
{
MagickRealType
delta;
delta=Sc-Dc;
if ((MagickRealType) fabs((double) (2.0*delta)) < threshold)
{
pixel=gamma*Dc;
break;
}
pixel=gamma*(Dc+delta*amount);
break;
}
case VividLightCompositeOp:
{
/*
VividLight: A Photoshop 7 composition method. See
http://www.simplefilter.de/en/basics/mixmods.html.
f(Sc,Dc) = (2*Sc < 1) ? 1-(1-Dc)/(2*Sc) : Dc/(2*(1-Sc))
*/
if ((fabs((double) Sa) < MagickEpsilon) ||
(fabs((double) (Sca-Sa)) < MagickEpsilon))
{
pixel=QuantumRange*gamma*(Sa*Da+Sca*(1.0-Da)+Dca*(1.0-Sa));
break;
}
if ((2.0*Sca) <= Sa)
{
pixel=QuantumRange*gamma*(Sa*(Da+Sa*(Dca-Da)*
PerceptibleReciprocal(2.0*Sca))+Sca*(1.0-Da)+Dca*(1.0-Sa));
break;
}
pixel=QuantumRange*gamma*(Dca*Sa*Sa*PerceptibleReciprocal(2.0*
(Sa-Sca))+Sca*(1.0-Da)+Dca*(1.0-Sa));
break;
}
case XorCompositeOp:
{
pixel=QuantumRange*(Sca*(1.0-Da)+Dca*(1.0-Sa));
break;
}
default:
{
pixel=Sc;
break;
}
}
q[i]=clamp != MagickFalse ? ClampPixel(pixel) : ClampToQuantum(pixel);
}
p+=GetPixelChannels(source_image);
channels=GetPixelChannels(source_image);
if (p >= (pixels+channels*source_image->columns))
p=pixels;
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,CompositeImageTag,progress,image->rows);
if (proceed == MagickFalse)
status=MagickFalse;
}
}
source_view=DestroyCacheView(source_view);
image_view=DestroyCacheView(image_view);
if (canvas_image != (Image * ) NULL)
canvas_image=DestroyImage(canvas_image);
else
source_image=DestroyImage(source_image);
return(status);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% T e x t u r e I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% TextureImage() repeatedly tiles the texture image across and down the image
% canvas.
%
% The format of the TextureImage method is:
%
% MagickBooleanType TextureImage(Image *image,const Image *texture,
% ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o texture_image: This image is the texture to layer on the background.
%
*/
MagickExport MagickBooleanType TextureImage(Image *image,const Image *texture,
ExceptionInfo *exception)
{
#define TextureImageTag "Texture/Image"
CacheView
*image_view,
*texture_view;
Image
*texture_image;
MagickBooleanType
status;
ssize_t
y;
assert(image != (Image *) NULL);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"...");
assert(image->signature == MagickCoreSignature);
if (texture == (const Image *) NULL)
return(MagickFalse);
if (SetImageStorageClass(image,DirectClass,exception) == MagickFalse)
return(MagickFalse);
texture_image=CloneImage(texture,0,0,MagickTrue,exception);
if (texture_image == (const Image *) NULL)
return(MagickFalse);
(void) TransformImageColorspace(texture_image,image->colorspace,exception);
(void) SetImageVirtualPixelMethod(texture_image,TileVirtualPixelMethod,
exception);
status=MagickTrue;
if ((image->compose != CopyCompositeOp) &&
((image->compose != OverCompositeOp) ||
(image->alpha_trait != UndefinedPixelTrait) ||
(texture_image->alpha_trait != UndefinedPixelTrait)))
{
/*
Tile texture onto the image background.
*/
for (y=0; y < (ssize_t) image->rows; y+=(ssize_t) texture_image->rows)
{
ssize_t
x;
if (status == MagickFalse)
continue;
for (x=0; x < (ssize_t) image->columns; x+=(ssize_t) texture_image->columns)
{
MagickBooleanType
thread_status;
thread_status=CompositeImage(image,texture_image,image->compose,
MagickTrue,x+texture_image->tile_offset.x,y+
texture_image->tile_offset.y,exception);
if (thread_status == MagickFalse)
{
status=thread_status;
break;
}
}
if (image->progress_monitor != (MagickProgressMonitor) NULL)
{
MagickBooleanType
proceed;
proceed=SetImageProgress(image,TextureImageTag,(MagickOffsetType) y,
image->rows);
if (proceed == MagickFalse)
status=MagickFalse;
}
}
(void) SetImageProgress(image,TextureImageTag,(MagickOffsetType)
image->rows,image->rows);
texture_image=DestroyImage(texture_image);
return(status);
}
/*
Tile texture onto the image background (optimized).
*/
status=MagickTrue;
texture_view=AcquireVirtualCacheView(texture_image,exception);
image_view=AcquireAuthenticCacheView(image,exception);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static) shared(status) \
magick_number_threads(texture_image,image,image->rows,1)
#endif
for (y=0; y < (ssize_t) image->rows; y++)
{
MagickBooleanType
sync;
const Quantum
*p,
*pixels;
ssize_t
x;
Quantum
*q;
size_t
width;
if (status == MagickFalse)
continue;
pixels=GetCacheViewVirtualPixels(texture_view,texture_image->tile_offset.x,
(y+texture_image->tile_offset.y) % texture_image->rows,
texture_image->columns,1,exception);
q=QueueCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception);
if ((pixels == (const Quantum *) NULL) || (q == (Quantum *) NULL))
{
status=MagickFalse;
continue;
}
for (x=0; x < (ssize_t) image->columns; x+=(ssize_t) texture_image->columns)
{
ssize_t
j;
p=pixels;
width=texture_image->columns;
if ((x+(ssize_t) width) > (ssize_t) image->columns)
width=image->columns-x;
for (j=0; j < (ssize_t) width; j++)
{
ssize_t
i;
for (i=0; i < (ssize_t) GetPixelChannels(texture_image); i++)
{
PixelChannel channel = GetPixelChannelChannel(texture_image,i);
PixelTrait traits = GetPixelChannelTraits(image,channel);
PixelTrait texture_traits=GetPixelChannelTraits(texture_image,
channel);
if ((traits == UndefinedPixelTrait) ||
(texture_traits == UndefinedPixelTrait))
continue;
SetPixelChannel(image,channel,p[i],q);
}
p+=GetPixelChannels(texture_image);
q+=GetPixelChannels(image);
}
}
sync=SyncCacheViewAuthenticPixels(image_view,exception);
if (sync == MagickFalse)
status=MagickFalse;
if (image->progress_monitor != (MagickProgressMonitor) NULL)
{
MagickBooleanType
proceed;
proceed=SetImageProgress(image,TextureImageTag,(MagickOffsetType) y,
image->rows);
if (proceed == MagickFalse)
status=MagickFalse;
}
}
texture_view=DestroyCacheView(texture_view);
image_view=DestroyCacheView(image_view);
texture_image=DestroyImage(texture_image);
return(status);
}
|
ch_ompss.c |
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <errno.h>
#include <assert.h>
#include "ch_common.h"
#include "../extrae.h"
#include "../timing.h"
/**
* TODO: What is the lower bound for a circular deadlock? (0 waits for 1 waits for 2 waits for 0)
* Example: Execution order on 1 is reversed:
* 0 waits for 1/2/3,
* 1 waits for 3/2/0,
* 2 waits for 0/1/3,
* 3 waits for 0/1/2
* OR
* 0 waits for 1/2/3/4,
* 1 waits for 0/2/3/4,
* 2 waits for 4/3/2/0,
* 3 waits for 0/1/2/4,
* 4 waits for 0/1/2/3
* OR
* 0 waits for 1/2/3/4/5,
* 1 waits for 0/2/3/4/5,
* 2 waits for 5/4/3/2/0,
* 3 waits for 0/1/2/4/5,
* 4 waits for 0/1/2/3/5,
* 5 waits for 0/1/2/3/5
*
* NOTE: circular dependencies may happen if at least one of the inner ranks
* (1 or 2, not 0 or 3) reverse their order
* HYPOTHESIS: we need at least (p-(p/2)) (ceil(0.5p)) threads to avoid deadlock from reversal
* Generalization to some ordered graph traversal problem?
*/
void cholesky_mpi(const int ts, const int nt, double *A[nt][nt], double *B, double *C[nt], int *block_rank)
{
int *send_blocks = malloc((nt) * sizeof(int));
int *recv_blocks = malloc((nt) * sizeof(int));
REGISTER_EXTRAE();
#pragma omp parallel
{
#pragma omp single
{
INIT_TIMING(omp_get_num_threads());
char dst_sentinels[np];
START_TIMING(TIME_TOTAL);
{
START_TIMING(TIME_CREATE);
for (int k = 0; k < nt; k++) {
if (block_rank[k*nt+k] == mype) {
#pragma omp task out(A[k][k]) firstprivate(k) no_copy_deps
{
EXTRAE_ENTER(EVENT_POTRF);
START_TIMING(TIME_POTRF);
omp_potrf(A[k][k], ts, ts);
END_TIMING(TIME_POTRF);
EXTRAE_EXIT(EVENT_POTRF);
}
}
if (block_rank[k*nt+k] == mype && np != 1) {
#pragma omp task in(A[k][k]) firstprivate(k) no_copy_deps untied
{
START_TIMING(TIME_COMM);
MPI_Request *reqs = NULL;
int nreqs = 0;
char send_flags[np];
reset_send_flags(send_flags);
for (int kk = k+1; kk < nt; kk++) {
if (!send_flags[block_rank[k*nt+kk]]) {
++nreqs;
send_flags[block_rank[k*nt+kk]] = 1;
}
}
reqs = malloc(sizeof(MPI_Request)*nreqs);
nreqs = 0;
for (int dst = 0; dst < np; dst++) {
if (send_flags[dst] && dst != mype) {
MPI_Request send_req;
MPI_Isend(A[k][k], ts*ts, MPI_DOUBLE, dst, k*nt+k, MPI_COMM_WORLD, &send_req);
reqs[nreqs++] = send_req;
}
}
waitall(reqs, nreqs);
free(reqs);
END_TIMING(TIME_COMM);
}
}
if (block_rank[k*nt+k] != mype) {
#pragma omp task out(B) firstprivate(k) no_copy_deps untied
{
START_TIMING(TIME_COMM);
int recv_flag = 0;
for (int i = k + 1; i < nt; i++) {
if (block_rank[k*nt+i] == mype) {
recv_flag = 1;
break;
}
}
if (recv_flag) {
MPI_Request recv_req;
MPI_Irecv(B, ts*ts, MPI_DOUBLE, block_rank[k*nt+k], k*nt+k, MPI_COMM_WORLD, &recv_req);
waitall(&recv_req, 1);
}
END_TIMING(TIME_COMM);
}
}
for (int i = k + 1; i < nt; i++) {
if (block_rank[k*nt+i] == mype) {
if (block_rank[k*nt+k] == mype) {
#pragma omp task in(A[k][k]) out(A[k][i]) firstprivate(k, i) no_copy_deps
{
EXTRAE_ENTER(EVENT_TRSM);
START_TIMING(TIME_TRSM);
omp_trsm(A[k][k], A[k][i], ts, ts);
END_TIMING(TIME_TRSM);
EXTRAE_EXIT(EVENT_TRSM);
}
} else {
#pragma omp task in(B) out(A[k][i]) firstprivate(k, i) no_copy_deps
{
EXTRAE_ENTER(EVENT_TRSM);
START_TIMING(TIME_TRSM);
omp_trsm(B, A[k][i], ts, ts);
END_TIMING(TIME_TRSM);
EXTRAE_EXIT(EVENT_TRSM);
}
}
}
}
for (int dst = 0; dst < np; dst++) {
if (dst == mype) continue;
int send_cnt = 0;
int recv_cnt = 0;
// populate list of blocks to send/recv to/from this unit
for (int i = k + 1; i < nt; i++) {
if (block_rank[k*nt+i] == mype && np != 1) {
int send_flag = 0;
for (int ii = k + 1; ii < i; ii++) {
if (!send_flag && block_rank[ii*nt+i] == dst) {
send_flag = 1;
break;
}
}
for (int ii = i + 1; ii < nt; ii++) {
if (!send_flag && block_rank[i*nt+ii] == dst) {
send_flag = 1;
break;
}
}
if (!send_flag && block_rank[i*nt+i] == dst) send_flag = 1;
if (send_flag) {
send_blocks[send_cnt++] = i;
}
}
if (block_rank[k*nt+i] != mype && block_rank[k*nt+i] == dst) {
int recv_flag = 0;
for (int ii = k + 1; ii < i; ii++) {
if (block_rank[ii*nt+i] == mype) recv_flag = 1;
}
for (int ii = i + 1; ii < nt; ii++) {
if (block_rank[i*nt+ii] == mype) recv_flag = 1;
}
if (block_rank[i*nt+i] == mype) recv_flag = 1;
if (recv_flag) {
recv_blocks[recv_cnt++] = i;
}
}
}
//printf("send_cnt: %d, recv_cnt: %d, blocks: %d\n", send_cnt, recv_cnt, (nt-(k+1)));
// NOTE: we have to wait for all of the above tasks using comm_sentinel
// dependency iterators might help here
#pragma omp task no_copy_deps firstprivate(k, dst) out({C[recv_blocks[it]], it=0;recv_cnt}) in({A[k][send_blocks[it]], it=0;send_cnt}) untied
{
START_TIMING(TIME_COMM);
int nreqs = 0;
// upper bound in case all our blocks have to be sent
int max_req = (nt-k);
MPI_Request *reqs = malloc(sizeof(*reqs)*max_req);
for (int i = k + 1; i < nt; i++) {
if (block_rank[k*nt+i] == mype && np != 1) {
int send_flag = 0;
for (int ii = k + 1; ii < i; ii++) {
if (!send_flag && block_rank[ii*nt+i] == dst) {
send_flag = 1;
}
}
for (int ii = i + 1; ii < nt; ii++) {
if (!send_flag && block_rank[i*nt+ii] == dst) {
send_flag = 1;
}
}
if (!send_flag && block_rank[i*nt+i] == dst) send_flag = 1;
if (send_flag) {
MPI_Request send_req;
MPI_Isend(A[k][i], ts*ts, MPI_DOUBLE, dst, k*nt+i, MPI_COMM_WORLD, &send_req);
reqs[nreqs++] = send_req;
}
}
if (block_rank[k*nt+i] != mype && block_rank[k*nt+i] == dst) {
int recv_flag = 0;
for (int ii = k + 1; ii < i; ii++) {
if (block_rank[ii*nt+i] == mype) recv_flag = 1;
}
for (int ii = i + 1; ii < nt; ii++) {
if (block_rank[i*nt+ii] == mype) recv_flag = 1;
}
if (block_rank[i*nt+i] == mype) recv_flag = 1;
if (recv_flag) {
MPI_Request recv_req;
MPI_Irecv(C[i], ts*ts, MPI_DOUBLE, block_rank[k*nt+i], k*nt+i, MPI_COMM_WORLD, &recv_req);
reqs[nreqs++] = recv_req;
}
}
}
//printf("Waiting for trsm blocks from %d in k=%d\n", dst, k);
waitall(reqs, nreqs);
free(reqs);
END_TIMING(TIME_COMM);
}
}
for (int i = k + 1; i < nt; i++) {
for (int j = k + 1; j < i; j++) {
if (block_rank[j*nt+i] == mype) {
if (block_rank[k*nt+i] == mype && block_rank[k*nt+j] == mype) {
#pragma omp task in(A[k][i], A[k][j]) out(A[j][i]) firstprivate(k, j, i) no_copy_deps
{
EXTRAE_ENTER(EVENT_GEMM);
START_TIMING(TIME_GEMM);
omp_gemm(A[k][i], A[k][j], A[j][i], ts, ts);
END_TIMING(TIME_GEMM);
EXTRAE_EXIT(EVENT_GEMM);
}
} else if (block_rank[k*nt+i] != mype && block_rank[k*nt+j] == mype) {
#pragma omp task in(A[k][j], C[i]) out(A[j][i]) firstprivate(k, j, i) no_copy_deps
{
EXTRAE_ENTER(EVENT_GEMM);
START_TIMING(TIME_GEMM);
omp_gemm(C[i], A[k][j], A[j][i], ts, ts);
END_TIMING(TIME_GEMM);
EXTRAE_EXIT(EVENT_GEMM);
}
} else if (block_rank[k*nt+i] == mype && block_rank[k*nt+j] != mype) {
// TODO: the content of C[j] may be overwritten but we cannot specify a dependency on it :(
#pragma omp task in(A[k][i], C[j]) out(A[j][i]) firstprivate(k, j, i) no_copy_deps
{
EXTRAE_ENTER(EVENT_GEMM);
START_TIMING(TIME_GEMM);
omp_gemm(A[k][i], C[j], A[j][i], ts, ts);
END_TIMING(TIME_GEMM);
EXTRAE_EXIT(EVENT_GEMM);
}
} else {
#pragma omp task in(C[i], C[j]) out(A[j][i]) firstprivate(k, j, i) no_copy_deps
{
EXTRAE_ENTER(EVENT_GEMM);
START_TIMING(TIME_GEMM);
omp_gemm(C[i], C[j], A[j][i], ts, ts);
END_TIMING(TIME_GEMM);
EXTRAE_EXIT(EVENT_GEMM);
}
}
}
}
if (block_rank[i*nt+i] == mype) {
if (block_rank[k*nt+i] == mype) {
#pragma omp task in(A[k][i]) out(A[i][i]) firstprivate(k, i) no_copy_deps
{
EXTRAE_ENTER(EVENT_SYRK);
START_TIMING(TIME_SYRK);
omp_syrk(A[k][i], A[i][i], ts, ts);
END_TIMING(TIME_SYRK);
EXTRAE_EXIT(EVENT_SYRK);
}
} else {
#pragma omp task in(C[i]) out(A[i][i]) firstprivate(k, i) no_copy_deps
{
EXTRAE_ENTER(EVENT_SYRK);
START_TIMING(TIME_SYRK);
omp_syrk(C[i], A[i][i], ts, ts);
END_TIMING(TIME_SYRK);
EXTRAE_EXIT(EVENT_SYRK);
}
}
}
}
}
END_TIMING(TIME_CREATE);
}
#pragma omp taskwait
END_TIMING(TIME_TOTAL);
MPI_Barrier(MPI_COMM_WORLD);
PRINT_TIMINGS();
FREE_TIMING();
}// pragma omp single
}// pragma omp parallel
free(send_blocks);
free(recv_blocks);
}
|
GB_assign_zombie3.c | //------------------------------------------------------------------------------
// GB_assign_zombie3: delete entries in C(:,j) for C_replace_phase
//------------------------------------------------------------------------------
// SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2020, All Rights Reserved.
// http://suitesparse.com See GraphBLAS/Doc/License.txt for license.
//------------------------------------------------------------------------------
// For GrB_Row_assign or GrB_Col_assign, C(I,j)<#M,repl>=any must delete all
// entries C(i,j) outside of C(I,j), if the mask M(i,0) (or its complement) is
// zero. This step is not done for GxB_*_subassign, since that method does not
// modify anything outside IxJ.
// GB_assign_zombie3 and GB_assign_zombie4 are transposes of each other.
#include "GB_assign.h"
void GB_assign_zombie3
(
GrB_Matrix Z, // the matrix C, or a copy
const GrB_Matrix M,
const bool Mask_comp,
const bool Mask_struct,
const int64_t j, // vector index with entries to delete
const GrB_Index *I,
const int64_t nI,
const int Ikind,
const int64_t Icolon [3],
GB_Context Context
)
{
//--------------------------------------------------------------------------
// get Z (:,j)
//--------------------------------------------------------------------------
const int64_t *GB_RESTRICT Zh = Z->h ;
const int64_t *GB_RESTRICT Zp = Z->p ;
int64_t *GB_RESTRICT Zi = Z->i ;
int64_t pZ_start, pZ_end, pleft = 0, pright = Z->nvec-1 ;
GB_lookup (Z->is_hyper, Zh, Zp, &pleft, pright, j, &pZ_start, &pZ_end) ;
int64_t nzombies = Z->nzombies ;
const int64_t zjnz = pZ_end - pZ_start ;
//--------------------------------------------------------------------------
// get M(:,0)
//--------------------------------------------------------------------------
const int64_t *GB_RESTRICT Mp = M->p ;
const int64_t *GB_RESTRICT Mi = M->i ;
const GB_void *GB_RESTRICT Mx = (GB_void *) (Mask_struct ? NULL : (M->x)) ;
const size_t msize = M->type->size ;
int64_t pM_start = Mp [0] ;
int64_t pM_end = Mp [1] ;
//--------------------------------------------------------------------------
// determine the number of threads to use
//--------------------------------------------------------------------------
GB_GET_NTHREADS_MAX (nthreads_max, chunk, Context) ;
int nthreads = GB_nthreads (zjnz, chunk, nthreads_max) ;
int ntasks = (nthreads == 1) ? 1 : (64 * nthreads) ;
//--------------------------------------------------------------------------
// delete entries from Z(:,j) that are outside I, if the mask M allows it
//--------------------------------------------------------------------------
int taskid ;
#pragma omp parallel for num_threads(nthreads) schedule(dynamic,1) \
reduction(+:nzombies)
for (taskid = 0 ; taskid < ntasks ; taskid++)
{
int64_t p1, p2 ;
GB_PARTITION (p1, p2, zjnz, taskid, ntasks) ;
for (int64_t pZ = pZ_start + p1 ; pZ < pZ_start + p2 ; pZ++)
{
//------------------------------------------------------------------
// get Z(i,j)
//------------------------------------------------------------------
int64_t i = Zi [pZ] ;
if (!GB_IS_ZOMBIE (i))
{
//--------------------------------------------------------------
// Z(i,j) is outside Z(I,j) if i is not in the list I
//--------------------------------------------------------------
bool i_outside = !GB_ij_is_in_list (I, nI, i, Ikind, Icolon) ;
if (i_outside)
{
//----------------------------------------------------------
// Z(i,j) is a live entry not in the Z(I,J) submatrix
//----------------------------------------------------------
// Check the mask M to see if it should be deleted.
int64_t pM = pM_start ;
int64_t pright = pM_end - 1 ;
bool found ;
GB_BINARY_SEARCH (i, Mi, pM, pright, found) ;
bool mij = false ;
if (found)
{
// found it
mij = GB_mcast (Mx, pM, msize) ;
}
if (Mask_comp)
{
// negate the mask if Mask_comp is true
mij = !mij ;
}
if (!mij)
{
// delete Z(i,j) by marking it as a zombie
nzombies++ ;
Zi [pZ] = GB_FLIP (i) ;
}
}
}
}
}
//--------------------------------------------------------------------------
// return result
//--------------------------------------------------------------------------
Z->nzombies = nzombies ;
}
|
GxB_Matrix_iso.c | //------------------------------------------------------------------------------
// GxB_Matrix_iso: report if a matrix is iso-valued or not
//------------------------------------------------------------------------------
// SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2021, All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
//------------------------------------------------------------------------------
#include "GB.h"
GrB_Info GxB_Matrix_iso // return iso status of a matrix
(
bool *iso, // true if the matrix is iso-valued
const GrB_Matrix A // matrix to query
)
{
//--------------------------------------------------------------------------
// check inputs
//--------------------------------------------------------------------------
GB_WHERE1 ("GxB_Matrix_iso (&iso, A)") ;
GB_RETURN_IF_NULL (iso) ;
GB_RETURN_IF_NULL_OR_FAULTY (A) ;
//--------------------------------------------------------------------------
// return the iso status of a matrix
//--------------------------------------------------------------------------
(*iso) = A->iso ;
#pragma omp flush
return (GrB_SUCCESS) ;
}
|
convolution_1x1_pack1to8.h | // Tencent is pleased to support the open source community by making ncnn available.
//
// Copyright (C) 2022 THL A29 Limited, a Tencent company. All rights reserved.
//
// Licensed under the BSD 3-Clause License (the "License"); you may not use this file except
// in compliance with the License. You may obtain a copy of the License at
//
// https://opensource.org/licenses/BSD-3-Clause
//
// Unless required by applicable law or agreed to in writing, software distributed
// under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
// CONDITIONS OF ANY KIND, either express or implied. See the License for the
// specific language governing permissions and limitations under the License.
static void conv1x1s1_sgemm_pack1to8_avx(const Mat& bottom_blob, Mat& top_blob, const Mat& kernel, const Mat& _bias, const Option& opt)
{
int w = bottom_blob.w;
int h = bottom_blob.h;
const int size = w * h;
Mat bottom_im2col = bottom_blob;
bottom_im2col.w = size;
bottom_im2col.h = 1;
im2col_sgemm_pack1to8_avx(bottom_im2col, top_blob, kernel, _bias, opt);
}
static void conv1x1s2_sgemm_pack1to8_avx(const Mat& bottom_blob, Mat& top_blob, const Mat& kernel, const Mat& _bias, const Option& opt)
{
int w = bottom_blob.w;
int channels = bottom_blob.c;
size_t elemsize = bottom_blob.elemsize;
int elempack = bottom_blob.elempack;
int outw = top_blob.w;
int outh = top_blob.h;
const int tailstep = w - 2 * outw + w;
Mat bottom_blob_shrinked;
bottom_blob_shrinked.create(outw, outh, channels, elemsize, elempack, opt.workspace_allocator);
#pragma omp parallel for num_threads(opt.num_threads)
for (int p = 0; p < channels; p++)
{
const float* r0 = bottom_blob.channel(p);
float* outptr = bottom_blob_shrinked.channel(p);
for (int i = 0; i < outh; i++)
{
for (int j = 0; j < outw; j++)
{
outptr[0] = r0[0];
r0 += 2;
outptr += 1;
}
r0 += tailstep;
}
}
conv1x1s1_sgemm_pack1to8_avx(bottom_blob_shrinked, top_blob, kernel, _bias, opt);
}
|
GB_unaryop__abs_uint32_fp64.c | //------------------------------------------------------------------------------
// GB_unaryop: hard-coded functions for each built-in unary operator
//------------------------------------------------------------------------------
// SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2019, All Rights Reserved.
// http://suitesparse.com See GraphBLAS/Doc/License.txt for license.
//------------------------------------------------------------------------------
// If this file is in the Generated/ folder, do not edit it (auto-generated).
#include "GB.h"
#ifndef GBCOMPACT
#include "GB_control.h"
#include "GB_iterator.h"
#include "GB_unaryop__include.h"
// C=unop(A) is defined by the following types and operators:
// op(A) function: GB_unop__abs_uint32_fp64
// op(A') function: GB_tran__abs_uint32_fp64
// C type: uint32_t
// A type: double
// cast: uint32_t cij ; GB_CAST_UNSIGNED(cij,aij,32)
// unaryop: cij = aij
#define GB_ATYPE \
double
#define GB_CTYPE \
uint32_t
// aij = Ax [pA]
#define GB_GETA(aij,Ax,pA) \
double aij = Ax [pA]
#define GB_CX(p) Cx [p]
// unary operator
#define GB_OP(z, x) \
z = x ;
// casting
#define GB_CASTING(z, x) \
uint32_t z ; GB_CAST_UNSIGNED(z,x,32) ;
// cij = op (cast (aij))
#define GB_CAST_OP(pC,pA) \
{ \
/* aij = Ax [pA] */ \
GB_GETA (aij, Ax, pA) ; \
/* Cx [pC] = op (cast (aij)) */ \
GB_CASTING (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_UINT32 || GxB_NO_FP64)
//------------------------------------------------------------------------------
// Cx = op (cast (Ax)): apply a unary operator
//------------------------------------------------------------------------------
GrB_Info GB_unop__abs_uint32_fp64
(
uint32_t *restrict Cx,
const double *restrict Ax,
int64_t anz,
int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
#pragma omp parallel for num_threads(nthreads) schedule(static)
for (int64_t p = 0 ; p < anz ; p++)
{
GB_CAST_OP (p, p) ;
}
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// C = op (cast (A')): transpose, typecast, and apply a unary operator
//------------------------------------------------------------------------------
GrB_Info GB_tran__abs_uint32_fp64
(
GrB_Matrix C,
const GrB_Matrix A,
int64_t **Rowcounts,
GBI_single_iterator Iter,
const int64_t *restrict A_slice,
int naslice
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
#define GB_PHASE_2_OF_2
#include "GB_unaryop_transpose.c"
return (GrB_SUCCESS) ;
#endif
}
#endif
|
5-2.c | #include <omp.h>
#include <stdio.h>
int main() {
int w = 10;
#pragma omp parallel num_threads(2)
#pragma omp for firstprivate(w)
for (int i = 0; i < 100; i++) {
int id = omp_get_thread_num();
printf("T%d:ai%d w=%d\n", id, i, w++);
}
printf("W=%d\n", w);
}
|
1.race7.c | // RUN: clang %loadLLOV %s -o /dev/null 2>&1 | FileCheck %s
#include <omp.h>
#define N 20
int main() {
int A[N][N];
#pragma omp parallel for schedule(auto)
for (int i = 1; i < N; i++)
for (int j = 1; j < N; j++)
A[i][j] = A[i - 1][j - 1];
}
// CHECK: Data Race detected
// END
|
j3d27pt.gold.h | #include <cstring>
using std::memcpy;
template <class T>
void jacobi_gold(T *fout, const T *fin, double h2inv, double a, double b, int L, int M, int N) {
double (*out)[M][N] = (double (*)[M][N]) fout;
double (*in)[M][N] = (double (*)[M][N]) fin;
auto ftemp1 = new T[L * M * N];
auto ftemp2 = new T[L * M * N];
memset(ftemp1, 0, sizeof(T)*L*M*N);
memset(ftemp2, 0, sizeof(T)*L*M*N);
double (*temp1)[M][N] = (T (*)[M][N]) ftemp1;
double (*temp2)[M][N] = (T (*)[M][N]) ftemp2;
memcpy(ftemp1, fin, sizeof(T)*L*M*N);
double c = b * h2inv;
double d = c * 0.5;
double e = c * 0.125;
double f = c * 0.3;
for (int t = 0; t < 12; t++) {
#pragma omp parallel for
for (int k = 1; k < L - 1; ++k) {
for (int j = 1; j < M - 1; ++j) {
for (int i = 1; i < N - 1; ++i) {
if (!(t%2)) {
temp2[k][j][i] = a*temp1[k][j][i] -
d*(temp1[k-1][j-1][i-1] +
temp1[k-1][j-1][i+1] +
temp1[k-1][j+1][i-1] +
temp1[k-1][j+1][i+1] +
temp1[k+1][j-1][i-1] +
temp1[k+1][j-1][i+1] +
temp1[k+1][j+1][i-1] +
temp1[k+1][j+1][i+1]) +
e*(temp1[k-1][j-1][i] +
temp1[k-1][j][i-1] +
temp1[k-1][j][i+1] +
temp1[k-1][j+1][i] +
temp1[k][j-1][i-1] +
temp1[k][j-1][i+1] +
temp1[k][j+1][i-1] +
temp1[k][j+1][i+1] +
temp1[k+1][j-1][i] +
temp1[k+1][j][i-1] +
temp1[k+1][j][i+1] +
temp1[k][j+1][i]) +
f*(temp1[k-1][j][i] +
temp1[k][j-1][i] +
temp1[k][j][i-1] +
temp1[k][j][i+1] +
temp1[k][j+1][i] +
temp1[k+1][j][i]) +
0.13*temp1[k][j][i];
} else {
temp1[k][j][i] = a*temp2[k][j][i] -
d*(temp2[k-1][j-1][i-1] +
temp2[k-1][j-1][i+1] +
temp2[k-1][j+1][i-1] +
temp2[k-1][j+1][i+1] +
temp2[k+1][j-1][i-1] +
temp2[k+1][j-1][i+1] +
temp2[k+1][j+1][i-1] +
temp2[k+1][j+1][i+1]) +
e*(temp2[k-1][j-1][i] +
temp2[k-1][j][i-1] +
temp2[k-1][j][i+1] +
temp2[k-1][j+1][i] +
temp2[k][j-1][i-1] +
temp2[k][j-1][i+1] +
temp2[k][j+1][i-1] +
temp2[k][j+1][i+1] +
temp2[k+1][j-1][i] +
temp2[k+1][j][i-1] +
temp2[k+1][j][i+1] +
temp2[k][j+1][i]) +
f*(temp2[k-1][j][i] +
temp2[k][j-1][i] +
temp2[k][j][i-1] +
temp2[k][j][i+1] +
temp2[k][j+1][i] +
temp2[k+1][j][i]) +
0.13*temp2[k][j][i];
}
}
}
}
}
memcpy(fout, ftemp1, sizeof(T)*L*M*N);
}
|
pr80809-1.c | /* PR middle-end/80809 */
/* { dg-do run } */
__attribute__((noinline, noclone)) void
foo (int x)
{
int i, j, v[x], *w[16];
for (i = 0; i < x; i++)
v[i] = i;
#pragma omp parallel
#pragma omp single
for (i = 0; i < 16; i++)
/* Make sure v is implicitly determined shared in task, because it
is shared on the parallel. */
#pragma omp task private (j)
w[i] = v;
for (i = 0; i < 16; i++)
if (w[i] != v)
__builtin_abort ();
}
int
main ()
{
foo (4);
foo (27);
foo (196);
return 0;
}
|
t001.c | #include<stdint.h>
#include<stdlib.h>
#include<stdio.h>
#include<omp.h>
typedef struct {int64_t nteam; int64_t nthread; int64_t team_n; int64_t thread_n;} tinfo;
int
main(int argc, char **argv)
{
const int64_t narr = 1 << 10;
tinfo tinit = {-1, -1, -1, -1};
tinfo *t = malloc(sizeof(tinfo)*narr);
for(int64_t i = 0; i < narr; ++i) t[i] = tinit;
#pragma omp target teams distribute parallel for simd map(t[0:narr])
for(int64_t i = 0; i < narr; ++i){
t[i].nteam = omp_get_num_teams();
t[i].nthread = omp_get_num_threads();
t[i].team_n = omp_get_team_num();
t[i].thread_n = omp_get_thread_num();
}
for(int64_t i = 0; i < narr; ++i){
printf("%4ld: nteam: %ld nthread: %ld team_n: %ld thread_n: %ld\n",
i, t[i].nteam, t[i].nthread, t[i].team_n, t[i].thread_n);
}
int ret = 0;
//if(t->nteam <= 0 || t->nthread <= 0) ret = 1;
free(t);
return ret;
}
|
StateStorage.h | /*
* Copyright (C) 2021 FISCO BCOS.
* SPDX-License-Identifier: Apache-2.0
* 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.
*
* @brief interface of Table
* @file Table.h
* @author: xingqiangbai
* @date: 2021-04-07
* @brief interface of Table
* @file StateStorage.h
* @author: ancelmo
* @date: 2021-09-01
*/
#pragma once
#include "bcos-framework/interfaces/storage/StorageInterface.h"
#include "bcos-framework/interfaces/storage/Table.h"
#include "tbb/enumerable_thread_specific.h"
#include <bcos-utilities/Error.h>
#include <boost/core/ignore_unused.hpp>
#include <boost/format.hpp>
#include <boost/multi_index/hashed_index.hpp>
#include <boost/multi_index/identity.hpp>
#include <boost/multi_index/key.hpp>
#include <boost/multi_index/mem_fun.hpp>
#include <boost/multi_index/sequenced_index.hpp>
#include <boost/multi_index_container.hpp>
#include <boost/property_map/property_map.hpp>
#include <boost/throw_exception.hpp>
#include <future>
#include <memory>
#include <optional>
#include <shared_mutex>
#include <type_traits>
namespace bcos::storage
{
class Recoder
{
public:
using Ptr = std::shared_ptr<Recoder>;
using ConstPtr = std::shared_ptr<Recoder>;
struct Change
{
Change(std::string _table, std::string _key, std::optional<Entry> _entry)
: table(std::move(_table)), key(std::move(_key)), entry(std::move(_entry))
{}
Change(const Change&) = delete;
Change& operator=(const Change&) = delete;
Change(Change&&) noexcept = default;
Change& operator=(Change&&) noexcept = default;
std::string table;
std::string key;
std::optional<Entry> entry;
};
void log(Change&& change) { m_changes.emplace_front(std::move(change)); }
auto begin() const { return m_changes.cbegin(); }
auto end() const { return m_changes.cend(); }
void clear() { m_changes.clear(); }
private:
std::list<Change> m_changes;
};
template <bool enableLRU = false>
class BaseStorage : public virtual storage::TraverseStorageInterface,
public virtual storage::MergeableStorageInterface
{
private:
#define STORAGE_REPORT_GET(table, key, entry, desc) \
if (c_fileLogLevel >= bcos::LogLevel::TRACE) \
{ \
} \
// log("GET", (table), (key), (entry), (desc))
#define STORAGE_REPORT_SET(table, key, entry, desc) \
if (c_fileLogLevel >= bcos::LogLevel::TRACE) \
{ \
} \
// log("SET", (table), (key), (entry), (desc))
// for debug
void log(const std::string_view& op, const std::string_view& table, const std::string_view& key,
const std::optional<Entry>& entry, const std::string_view& desc = "")
{
if (!m_readOnly)
{
if (entry)
{
STORAGE_LOG(TRACE)
<< op << "|" << table << "|" << toHex(key) << "|[" << toHex(entry->getField(0))
<< "]|" << (int32_t)entry->status() << "|" << desc;
}
else
{
STORAGE_LOG(TRACE) << op << "|" << table << "|" << toHex(key) << "|"
<< "[]"
<< "|"
<< "NO ENTRY"
<< "|" << desc;
}
}
}
public:
using Ptr = std::shared_ptr<BaseStorage<enableLRU>>;
explicit BaseStorage(std::shared_ptr<StorageInterface> prev)
: storage::TraverseStorageInterface(),
m_prev(std::move(prev)),
m_buckets(std::thread::hardware_concurrency())
{}
BaseStorage(const BaseStorage&) = delete;
BaseStorage& operator=(const BaseStorage&) = delete;
BaseStorage(BaseStorage&&) = delete;
BaseStorage& operator=(BaseStorage&&) = delete;
virtual ~BaseStorage() { m_recoder.clear(); }
void asyncGetPrimaryKeys(std::string_view table,
const std::optional<storage::Condition const>& _condition,
std::function<void(Error::UniquePtr, std::vector<std::string>)> _callback) override
{
std::map<std::string_view, storage::Entry::Status> localKeys;
if (m_enableTraverse)
{
#pragma omp parallel for
for (size_t i = 0; i < m_buckets.size(); ++i)
{
auto& bucket = m_buckets[i];
std::unique_lock<std::mutex> lock(bucket.mutex);
decltype(localKeys) bucketKeys;
for (auto& it : bucket.container)
{
if (it.table == table && (!_condition || _condition->isValid(it.key)))
{
bucketKeys.emplace(it.key, it.entry.status());
}
}
#pragma omp critical
localKeys.merge(std::move(bucketKeys));
}
}
auto prev = getPrev();
if (!prev)
{
std::vector<std::string> resultKeys;
for (auto& localIt : localKeys)
{
if (localIt.second == Entry::NORMAL)
{
resultKeys.push_back(std::string(localIt.first));
}
}
_callback(nullptr, std::move(resultKeys));
return;
}
prev->asyncGetPrimaryKeys(table, _condition,
[localKeys = std::move(localKeys), callback = std::move(_callback)](
auto&& error, auto&& remoteKeys) mutable {
if (error)
{
callback(BCOS_ERROR_WITH_PREV_UNIQUE_PTR(StorageError::ReadError,
"Get primary keys from prev failed!", *error),
std::vector<std::string>());
return;
}
for (auto it = remoteKeys.begin(); it != remoteKeys.end();)
{
bool deleted = false;
auto localIt = localKeys.find(*it);
if (localIt != localKeys.end())
{
if (localIt->second != Entry::NORMAL)
{
it = remoteKeys.erase(it);
deleted = true;
}
localKeys.erase(localIt);
}
if (!deleted)
{
++it;
}
}
for (auto& localIt : localKeys)
{
if (localIt.second == Entry::NORMAL)
{
remoteKeys.push_back(std::string(localIt.first));
}
}
callback(nullptr, std::move(remoteKeys));
});
}
void asyncGetRow(std::string_view tableView, std::string_view keyView,
std::function<void(Error::UniquePtr, std::optional<Entry>)> _callback) override
{
auto [bucket, lock] = getBucket(tableView, keyView);
boost::ignore_unused(lock);
auto it = bucket->container.template get<0>().find(std::make_tuple(tableView, keyView));
if (it != bucket->container.template get<0>().end())
{
auto& entry = it->entry;
if (entry.status() != Entry::NORMAL)
{
lock.unlock();
STORAGE_REPORT_GET(tableView, keyView, std::nullopt, "DELETED");
_callback(nullptr, std::nullopt);
}
else
{
auto optionalEntry = std::make_optional(entry);
if constexpr (enableLRU)
{
updateMRUAndCheck(*bucket, it);
}
lock.unlock();
STORAGE_REPORT_GET(tableView, keyView, optionalEntry, "FOUND");
_callback(nullptr, std::move(optionalEntry));
}
return;
}
else
{
STORAGE_REPORT_GET(tableView, keyView, std::nullopt, "NO ENTRY");
}
lock.unlock();
auto prev = getPrev();
if (prev)
{
prev->asyncGetRow(tableView, keyView,
[this, prev, table = std::string(tableView), key = std::string(keyView), _callback](
Error::UniquePtr error, std::optional<Entry> entry) {
if (error)
{
_callback(BCOS_ERROR_WITH_PREV_UNIQUE_PTR(StorageError::ReadError,
"Get row from storage failed!", *error),
{});
return;
}
if (entry)
{
STORAGE_REPORT_GET(table, key, entry, "PREV FOUND");
_callback(nullptr,
std::make_optional(importExistingEntry(table, key, std::move(*entry))));
}
else
{
STORAGE_REPORT_GET(table, key, std::nullopt, "PREV NOT FOUND");
_callback(nullptr, std::nullopt);
}
});
}
else
{
_callback(nullptr, std::nullopt);
}
}
void asyncGetRows(std::string_view tableView,
const std::variant<const gsl::span<std::string_view const>,
const gsl::span<std::string const>>& _keys,
std::function<void(Error::UniquePtr, std::vector<std::optional<Entry>>)> _callback) override
{
std::visit(
[this, &tableView, &_callback](auto&& _keys) {
std::vector<std::optional<Entry>> results(_keys.size());
auto missinges = std::tuple<std::vector<std::string_view>,
std::vector<std::tuple<std::string, size_t>>>();
std::atomic_long existsCount = 0;
#pragma omp parallel for
for (gsl::index i = 0; i < _keys.size(); ++i)
{
auto [bucket, lock] = getBucket(tableView, _keys[i]);
boost::ignore_unused(lock);
auto it = bucket->container.find(
std::make_tuple(tableView, std::string_view(_keys[i])));
if (it != bucket->container.end())
{
auto& entry = it->entry;
if (entry.status() == Entry::NORMAL)
{
results[i].emplace(entry);
if constexpr (enableLRU)
{
updateMRUAndCheck(*bucket, it);
}
}
else
{
results[i] = std::nullopt;
}
++existsCount;
}
else
{
#pragma omp critical
{
std::get<1>(missinges).emplace_back(std::string(_keys[i]), i);
std::get<0>(missinges).emplace_back(_keys[i]);
}
}
}
auto prev = getPrev();
if (existsCount < _keys.size() && prev)
{
prev->asyncGetRows(tableView, std::get<0>(missinges),
[this, table = std::string(tableView), callback = std::move(_callback),
missingIndexes = std::move(std::get<1>(missinges)),
results = std::move(results)](
auto&& error, std::vector<std::optional<Entry>>&& entries) mutable {
if (error)
{
callback(BCOS_ERROR_WITH_PREV_UNIQUE_PTR(StorageError::ReadError,
"async get perv rows failed!", *error),
std::vector<std::optional<Entry>>());
return;
}
#pragma omp parallel for
for (size_t i = 0; i < entries.size(); ++i)
{
auto& entry = entries[i];
if (entry)
{
results[std::get<1>(missingIndexes[i])].emplace(
importExistingEntry(table,
std::move(std::get<0>(missingIndexes[i])),
std::move(*entry)));
}
}
callback(nullptr, std::move(results));
});
}
else
{
_callback(nullptr, std::move(results));
}
},
_keys);
}
void asyncSetRow(std::string_view tableView, std::string_view keyView, Entry entry,
std::function<void(Error::UniquePtr)> callback) override
{
if (m_readOnly)
{
callback(BCOS_ERROR_UNIQUE_PTR(
StorageError::ReadOnly, "Try to operate a read-only storage"));
return;
}
ssize_t updatedCapacity = entry.size();
std::optional<Entry> entryOld;
auto [bucket, lock] = getBucket(tableView, keyView);
boost::ignore_unused(lock);
auto it = bucket->container.find(std::make_tuple(tableView, keyView));
if (it != bucket->container.end())
{
auto& existsEntry = it->entry;
entryOld.emplace(std::move(existsEntry));
updatedCapacity -= entryOld->size();
STORAGE_REPORT_SET(tableView, keyView, entry, "UPDATE");
bucket->container.modify(it, [&entry](Data& data) { data.entry = std::move(entry); });
if constexpr (enableLRU)
{
updateMRUAndCheck(*bucket, it);
}
}
else
{
bucket->container.emplace(
Data{std::string(tableView), std::string(keyView), std::move(entry)});
STORAGE_REPORT_SET(tableView, keyView, std::nullopt, "INSERT");
}
if (m_recoder.local())
{
m_recoder.local()->log(
Recoder::Change(std::string(tableView), std::string(keyView), std::move(entryOld)));
}
bucket->capacity += updatedCapacity;
lock.unlock();
callback(nullptr);
}
void parallelTraverse(bool onlyDirty, std::function<bool(const std::string_view& table,
const std::string_view& key, const Entry& entry)>
callback) const override
{
#pragma omp parallel for
for (size_t i = 0; i < m_buckets.size(); ++i)
{
auto& bucket = m_buckets[i];
for (auto& it : bucket.container)
{
auto& entry = it.entry;
if (!onlyDirty || entry.dirty())
{
callback(it.table, it.key, entry);
}
}
}
}
void merge(bool onlyDirty, const TraverseStorageInterface& source) override
{
if (&source == this)
{
STORAGE_LOG(ERROR) << "Can't merge from self!";
BOOST_THROW_EXCEPTION(BCOS_ERROR(-1, "Can't merge from self!"));
}
std::atomic_size_t count = 0;
source.parallelTraverse(
onlyDirty, [this, &count](const std::string_view& table, const std::string_view& key,
const storage::Entry& entry) {
asyncSetRow(table, key, entry, [](Error::UniquePtr) {});
++count;
return true;
});
STORAGE_LOG(INFO) << "Successful merged " << count << " records";
}
std::optional<Table> openTable(const std::string_view& tableView)
{
std::promise<std::tuple<Error::UniquePtr, std::optional<Table>>> openPromise;
asyncOpenTable(tableView, [&](auto&& error, auto&& table) {
openPromise.set_value({std::move(error), std::move(table)});
});
auto [error, table] = openPromise.get_future().get();
if (error)
{
BOOST_THROW_EXCEPTION(*error);
}
return table;
}
std::optional<Table> createTable(std::string _tableName, std::string _valueFields)
{
std::promise<std::tuple<Error::UniquePtr, std::optional<Table>>> createPromise;
asyncCreateTable(
_tableName, _valueFields, [&](Error::UniquePtr&& error, std::optional<Table>&& table) {
createPromise.set_value({std::move(error), std::move(table)});
});
auto [error, table] = createPromise.get_future().get();
if (error)
{
BOOST_THROW_EXCEPTION(*error);
}
return table;
}
crypto::HashType hash(const bcos::crypto::Hash::Ptr& hashImpl) const
{
bcos::crypto::HashType totalHash;
#pragma omp parallel for
for (size_t i = 0; i < m_buckets.size(); ++i)
{
auto& bucket = m_buckets[i];
bcos::crypto::HashType bucketHash;
for (auto& it : bucket.container)
{
auto& entry = it.entry;
if (entry.dirty())
{
auto hash = hashImpl->hash(it.table);
hash ^= hashImpl->hash(it.key);
if (entry.status() != Entry::DELETED)
{
auto value = entry.getField(0);
bcos::bytesConstRef ref((const bcos::byte*)value.data(), value.size());
auto entryHash = hashImpl->hash(ref);
if (c_fileLogLevel >= TRACE)
{
STORAGE_LOG(TRACE)
<< "Calc hash, dirty entry: " << it.table << " | " << toHex(it.key)
<< " | " << toHex(value) << LOG_KV("hash", entryHash.abridged());
}
hash ^= entryHash;
}
else
{
auto entryHash = bcos::crypto::HashType(0x1);
if (c_fileLogLevel >= TRACE)
{
STORAGE_LOG(TRACE)
<< "Calc hash, deleted entry: " << it.table << " | "
<< toHex(toHex(it.key)) << LOG_KV("hash", entryHash.abridged());
}
hash ^= entryHash;
}
bucketHash ^= hash;
}
}
#pragma omp critical
totalHash ^= bucketHash;
}
return totalHash;
}
void setPrev(std::shared_ptr<StorageInterface> prev)
{
std::unique_lock<std::shared_mutex> lock(m_prevMutex);
m_prev = std::move(prev);
}
typename Recoder::Ptr newRecoder() { return std::make_shared<Recoder>(); }
void setRecoder(typename Recoder::Ptr recoder) { m_recoder.local().swap(recoder); }
void rollback(const Recoder& recoder)
{
if (m_readOnly)
{
return;
}
for (auto& change : recoder)
{
ssize_t updateCapacity = 0;
auto [bucket, lock] = getBucket(change.table, change.key);
boost::ignore_unused(lock);
auto it = bucket->container.find(
std::make_tuple(std::string_view(change.table), std::string_view(change.key)));
if (change.entry)
{
if (it != bucket->container.end())
{
if (c_fileLogLevel >= bcos::LogLevel::TRACE)
{
STORAGE_LOG(TRACE)
<< "Revert exists: " << change.table << " | " << toHex(change.key)
<< " | " << toHex(change.entry->get());
}
updateCapacity = change.entry->size() - it->entry.size();
auto& rollbackEntry = change.entry;
bucket->container.modify(it,
[&rollbackEntry](Data& data) { data.entry = std::move(*rollbackEntry); });
}
else
{
if (c_fileLogLevel >= bcos::LogLevel::TRACE)
{
STORAGE_LOG(TRACE)
<< "Revert deleted: " << change.table << " | " << toHex(change.key)
<< " | " << toHex(change.entry->get());
}
updateCapacity = change.entry->size();
bucket->container.emplace(
Data{change.table, change.key, std::move(*(change.entry))});
}
}
else
{ // nullopt means the key is not exist in m_cache
if (it != bucket->container.end())
{
if (c_fileLogLevel >= bcos::LogLevel::TRACE)
{
STORAGE_LOG(TRACE)
<< "Revert insert: " << change.table << " | " << toHex(change.key);
}
updateCapacity = 0 - it->entry.size();
bucket->container.erase(it);
}
else
{
auto message = (boost::format("Not found rollback entry: %s:%s") %
change.table % change.key)
.str();
BOOST_THROW_EXCEPTION(BCOS_ERROR(StorageError::UnknownError, message));
}
}
bucket->capacity += updateCapacity;
}
}
void setEnableTraverse(bool enableTraverse) { m_enableTraverse = enableTraverse; }
void setReadOnly(bool readOnly) { m_readOnly = readOnly; }
void setMaxCapacity(ssize_t capacity) { m_maxCapacity = capacity; }
private:
Entry importExistingEntry(std::string_view table, std::string_view key, Entry entry)
{
if (m_readOnly)
{
return entry;
}
entry.setDirty(false);
auto updateCapacity = entry.size();
auto [bucket, lock] = getBucket(table, key);
boost::ignore_unused(lock);
auto it = bucket->container.find(std::make_tuple(table, key));
if (it == bucket->container.end())
{
STORAGE_REPORT_SET(
std::get<0>(entryIt->first), key, std::make_optional(entryIt->second), "IMPORT");
it = bucket->container
.emplace(Data{std::string(table), std::string(key), std::move(entry)})
.first;
bucket->capacity += updateCapacity;
}
else
{
STORAGE_REPORT_SET(
std::get<0>(entryIt->first), key, entryIt->second, "IMPORT EXISTS FAILED");
STORAGE_LOG(WARNING) << "Fail import existsing entry, " << table << " | " << toHex(key);
}
return it->entry;
}
std::shared_ptr<StorageInterface> getPrev()
{
std::shared_lock<std::shared_mutex> lock(m_prevMutex);
auto prev = m_prev;
return prev;
}
tbb::enumerable_thread_specific<typename Recoder::Ptr> m_recoder;
std::shared_ptr<StorageInterface> m_prev;
std::shared_mutex m_prevMutex;
bool m_enableTraverse = false;
bool m_readOnly = false;
ssize_t m_maxCapacity = 32 * 1024 * 1024;
struct Data
{
std::string table;
std::string key;
Entry entry;
std::tuple<std::string_view, std::string_view> view() const
{
return std::make_tuple(std::string_view(table), std::string_view(key));
}
};
using HashContainer = boost::multi_index_container<Data,
boost::multi_index::indexed_by<boost::multi_index::hashed_unique<boost::multi_index::
const_mem_fun<Data, std::tuple<std::string_view, std::string_view>, &Data::view>>>>;
using LRUHashContainer = boost::multi_index_container<Data,
boost::multi_index::indexed_by<
boost::multi_index::hashed_unique<boost::multi_index::const_mem_fun<Data,
std::tuple<std::string_view, std::string_view>, &Data::view>>,
boost::multi_index::sequenced<>>>;
using Container = std::conditional_t<enableLRU, LRUHashContainer, HashContainer>;
struct Bucket
{
Container container;
std::mutex mutex;
ssize_t capacity = 0;
};
std::vector<Bucket> m_buckets;
std::tuple<Bucket*, std::unique_lock<std::mutex>> getBucket(
std::string_view table, std::string_view key)
{
auto hash = std::hash<std::string_view>{}(table);
boost::hash_combine(hash, std::hash<std::string_view>{}(key));
auto index = hash % m_buckets.size();
auto& bucket = m_buckets[index];
return std::make_tuple(&bucket, std::unique_lock<std::mutex>(bucket.mutex));
}
void updateMRUAndCheck(
Bucket& bucket, typename Container::template nth_index<0>::type::iterator it)
{
auto seqIt = bucket.container.template get<1>().iterator_to(*it);
bucket.container.template get<1>().relocate(
bucket.container.template get<1>().end(), seqIt);
size_t clearCount = 0;
while (bucket.capacity > m_maxCapacity && !bucket.container.empty())
{
auto& item = bucket.container.template get<1>().front();
bucket.capacity -= item.entry.size();
bucket.container.template get<1>().pop_front();
++clearCount;
}
if (clearCount > 0)
{
STORAGE_LOG(TRACE) << "LRUStorage cleared:" << clearCount
<< ", current size: " << bucket.container.size();
}
}
};
using StateStorage = BaseStorage<false>;
using LRUStateStorage = BaseStorage<true>;
} // namespace bcos::storage
|
ejercicio9.c | #include <stdlib.h>
#include <stdio.h>
#include <time.h>
#ifdef _OPENMP
#include <omp.h>
#else
#define omp_get_thread_num()0
#endif
#define PRINTF_ALL
#define VECTOR_DYNAMIC //descomentar para que los vectores sean variables ...
//dinámicas (memoria reautilizable durante la ejecución)
int main(int argc, char** argv){
int i,j,k,temporal;
struct timespec cgt1,cgt2;
double ncgt; //para tiempo de ejecución
if(argc<2){
printf("Faltan nº componentes de las matrices <nº_filas_matriz_y_nº_columnas_matriz>\n");
exit(-1);
}
unsigned int N=atoi(argv[1]);
int **matriz, **matriz2, **resultado;
//Reservamos espacio para las matrices
//***********************************************
matriz= (int**) malloc(N*sizeof(int*));
for(i=0;i<N;i++)
matriz[i]=(int *) malloc(N*sizeof(int));
matriz2= (int**) malloc(N*sizeof(int*));
for(i=0;i<N;i++)
matriz2[i]=(int *) malloc(N*sizeof(int));
resultado= (int**) malloc(N*sizeof(int*)); //matriz resultante de la multiplicación
for(i=0;i<N;i++)
resultado[i]=(int *) malloc(N*sizeof(int));
//************************************************
if((matriz==NULL) || (matriz2==NULL) || (resultado==NULL)){
printf("Error en la reserva de espacio para los vectores\n");
exit(-2);
}
//Inicializar matrices
#pragma omp parallel for
for(i=0;i<N;i++){
for(j=0;j<N;j++){
matriz[i][j]= i*j;
printf("/matriz[%d][%d] con valor[%d] ejecutado por la hebra: %d\n", i,j,matriz[i][j],omp_get_thread_num());
}
}
#pragma omp parallel for
for(i=0;i<N;i++){
for(j=0;j<N;j++){
matriz2[i][j]= i*j;
printf("/matriz2[%d][%d] con valor [%d] ejecutado por la hebra: %d\n", i,j,matriz2[i][j],omp_get_thread_num());
}
}
#pragma omp parallel for
for(i=0;i<N;i++){
for(j=0;j<N;j++){
resultado[i][j]=0;
printf("/resultado[%d][%d] con valor [%d] ejecutado por la hebra: %d\n", i,j,resultado[i][j],omp_get_thread_num());
}
}
//***********************
clock_gettime(CLOCK_REALTIME,&cgt1);
//Calcular multiplicación de la matrices
//**************************************
#pragma omp parallel for default(none) shared(N,i,j,matriz2,matriz,temporal,resultado) private(k)
for(i=0;i<N;i++){ //filas de la matriz resultante
for(j=0;j<N;j++){ //columnas de la matriz resultante
#pragma omp parallel for reduction(+:temporal)
for(k=0;k<N;k++) //empezamos a multiplicar los elementos de la matriz
temporal+=matriz[i][k] * matriz2[k][j];
#pragma omp atomic
resultado[i][j]+=temporal;
printf("Operación: /matriz[%d][%d]*matriz2[%d][%d](%d*%d=%d) ejecutado por la hebra: %d\n", i,j,i,j,matriz[i][j],matriz2[i][j],matriz[i][j] * matriz2[i][j],omp_get_thread_num());
}
}
//**************************************
clock_gettime(CLOCK_REALTIME,&cgt2);
ncgt=(double) (cgt2.tv_sec-cgt1.tv_sec) + (double) ((cgt2.tv_nsec-cgt1.tv_nsec)/(1.e+9));
#ifdef PRINTF_ALL
printf("Tiempo(seg.): %11.9f\t / Tamaño Vectores:%u\n",ncgt,N);
for(i=0;i<N;i++){
printf("Mostramos resultados intermedios:\n");
for(j=0;j<N;j++)
printf("/matriz[%d][%d]*matriz2[%d][%d](%d*%d=%d)/\n", i,j,i,j,matriz[i][j],matriz2[i][j],matriz[i][j] * matriz2[i][j]);
}
printf("Mostramos resultados finales:\n");
for(i=0;i<N;i++){
for(j=0;j<N;j++)
printf("resultado[%d][%d]= %d\n", i,j,resultado[i][j]);
}
#else
printf("Tiempo(seg.): %11.9f\t / Tamaño Vectores:%u\n",
ncgt,N,matriz[0][0],matriz2[0][0],resultado[0][0],N-1,N-1,N-1,matriz[N-1][N-1],matriz2[N-1][N-1],resultado[N-1][N-1]);
#endif
#ifdef VECTOR_DYNAMIC
free(matriz); //libera el espacio reservado para v1
free(matriz2); //libera el espacio reservado para v2
free(resultado); //libera el espacio reservado para v3
#endif
return 0;
} |
index.c | #include <string.h>
#include <stdint.h>
#include <omp.h>
#include "allocator.h"
#include "index.h"
/* Merge the two sorted lists using temporary array */
static void
imerge(
uint32_t *b,
uint32_t *l1,
uint32_t *h1,
uint32_t *l2,
uint32_t *h2,
uint32_t *l_)
{
for(;(l1 != h1) && (l2 != h2);)
{
if(*(b + *(l2)) < *(b + *(l1)))
memcpy(l_++, l2++, sizeof(uint32_t));
else
memcpy(l_++, l1++, sizeof(uint32_t));
}
/* Move the leftover data */
memcpy(l_, l1, (size_t) (h1 - l1) * sizeof(uint32_t));
memcpy(l_, l2, (size_t) (h2 - l2) * sizeof(uint32_t));
}
/* Sequential sort used to sort a small array list */
static void
srt(uint32_t *b, uint32_t *l, uint32_t *h)
{
uint32_t * i;
for(i = l; i < h; i++)
{
uint32_t * elm = b + *(i);
uint32_t * j;
for(j = (i+1); j < h; j++)
{
if(*(elm) > *(b + *(j)))
{
XCHG(*(i), *(j)); // Swap the elements
elm = b + *(i); // Change the base index
}
}
}
}
/* Index sort: Find the index of an array that gives a
* sorted array */
static void
isort(
uint32_t *b,
uint32_t *l,
uint32_t *h,
uint32_t *l_,
uint8_t flg)
{
if((h - l) <= LIMIT) // Maximum sort limit
{
srt(b, l, h);
if(!flg) memcpy(l_, l, (size_t) (h - l) * sizeof(uint32_t));
}
else
{
/* Use merge-sort to divide the array into subarrays */
uint32_t * m = l + (h - l) / 2;
uint32_t * m_ = l_ + (m - l);
uint32_t * h_ = l_ + (h - l);
/* Launch OpenMP task-based parallelism for each half of
* the array */
#pragma omp task
isort(b, l, m, l_, (unsigned char) !flg);
isort(b, m, h, m_, (unsigned char) !flg);
#pragma omp taskwait
/* Merge the sorted sequences */
if(flg) imerge(b, l_, m_, m_, h_, l);
else imerge(b, l, m, m, h, l_);
}
}
/* Initialize the find indexing function
* sz: size of the original array
* b: the base array
* l: the low address of the output permutation array */
void
imain(const size_t sz, uint32_t *b, uint32_t *d)
{
/* initialize the output array
* Assume that the original list is already sorted */
uint32_t i;
for(i = 0; i < sz; i++) d[i] = i;
/* A temporary buffer used for sorting */
uint32_t *l = (uint32_t *) fun3d_malloc(sz, sizeof(uint32_t));
/* Launch the parallel region and start sorting based on an
* index list */
#pragma omp parallel
{
#pragma omp single
{
isort(b, d, (d + sz), l, 1); // Index sort
}
}
fun3d_free(l);
} |
display.c | /* display.c -- Graphical display control
*
* Copyright (c) 2018-2020, Liu chao <lc-soft@live.cn> 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 LCUI 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.
*/
#include "config.h"
#ifdef USE_OPENMP
#include <omp.h>
#endif
#include <time.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <LCUI_Build.h>
#include <LCUI/LCUI.h>
#include <LCUI/input.h>
#include <LCUI/timer.h>
#include <LCUI/cursor.h>
#include <LCUI/thread.h>
#include <LCUI/display.h>
#include <LCUI/platform.h>
#include <LCUI/settings.h>
#include <LCUI/main.h>
#ifdef LCUI_DISPLAY_H
#include LCUI_DISPLAY_H
#endif
/* clang-format off */
#define DEFAULT_WIDTH 800
#define DEFAULT_HEIGHT 600
typedef struct FlashRectRec_ {
int64_t paint_time;
LCUI_Rect rect;
} FlashRectRec, *FlashRect;
typedef struct SurfaceRecordRec_ {
/** whether new content has been rendered */
LCUI_BOOL rendered;
/** dirty rectangles for rendering */
LinkedList rects;
/** flashing rect list */
LinkedList flash_rects;
LCUI_Surface surface;
LCUI_Widget widget;
} SurfaceRecordRec, *SurfaceRecord;
static struct LCUI_DisplayModule {
unsigned width, height;
LCUI_BOOL active;
LCUI_DisplayMode mode;
LinkedList surfaces;
LinkedList rects;
LCUI_DisplayDriver driver;
LCUI_SettingsRec settings;
int settings_change_handler_id;
} display;
/* clang-format on */
#define LCUIDisplay_CleanSurfaces() \
LinkedList_Clear(&display.surfaces, OnDestroySurfaceRecord)
INLINE int is_rect_equals(const LCUI_Rect *a, const LCUI_Rect *b)
{
return a->x == b->x && a->y == b->y && a->width == b->width &&
a->height == b->height;
}
static void OnDestroySurfaceRecord(void *data)
{
SurfaceRecord record = data;
Surface_Close(record->surface);
LinkedList_Clear(&record->rects, free);
LinkedList_Clear(&record->flash_rects, free);
free(record);
}
static void OnSettingsChangeEvent(LCUI_SysEvent e, void *arg)
{
Settings_Init(&display.settings);
}
static size_t LCUIDisplay_RenderFlashRect(SurfaceRecord record,
FlashRect flash_rect)
{
size_t count;
int64_t period;
float duraion = 1000;
LCUI_Pos pos;
LCUI_Color color;
LCUI_Graph mask;
LCUI_PaintContext paint;
paint = Surface_BeginPaint(record->surface, &flash_rect->rect);
if (!paint) {
return 0;
}
period = LCUI_GetTimeDelta(flash_rect->paint_time);
count = Widget_Render(record->widget, paint);
if (period >= duraion) {
flash_rect->paint_time = 0;
Surface_EndPaint(record->surface, paint);
return count;
}
Graph_Init(&mask);
mask.color_type = LCUI_COLOR_TYPE_ARGB;
Graph_Create(&mask, flash_rect->rect.width, flash_rect->rect.height);
Graph_FillRect(&mask, ARGB(125, 124, 179, 5), NULL, TRUE);
mask.opacity = 0.6f * (duraion - (float)period) / duraion;
pos.x = pos.y = 0;
color = RGB(124, 179, 5);
Graph_DrawHorizLine(&mask, color, 1, pos, mask.width - 1);
Graph_DrawVertiLine(&mask, color, 1, pos, mask.height - 1);
pos.x = mask.width - 1;
Graph_DrawVertiLine(&mask, color, 1, pos, mask.height - 1);
pos.x = 0;
pos.y = mask.height - 1;
Graph_DrawHorizLine(&mask, color, 1, pos, mask.width - 1);
Graph_Mix(&paint->canvas, &mask, 0, 0, TRUE);
Graph_Free(&mask);
Surface_EndPaint(record->surface, paint);
return count;
}
static size_t LCUIDisplay_UpdateFlashRects(SurfaceRecord record)
{
size_t count = 0;
FlashRect flash_rect;
LinkedListNode *node, *prev;
for (LinkedList_Each(node, &record->flash_rects)) {
flash_rect = node->data;
if (flash_rect->paint_time == 0) {
prev = node->prev;
free(node->data);
LinkedList_DeleteNode(&record->flash_rects, node);
node = prev;
continue;
}
LCUIDisplay_RenderFlashRect(record, flash_rect);
record->rendered = TRUE;
}
return count;
}
static void LCUIDisplay_AppendFlashRects(SurfaceRecord record, LCUI_Rect *rect)
{
LinkedListNode *node;
FlashRect flash_rect;
for (LinkedList_Each(node, &record->flash_rects)) {
flash_rect = node->data;
if (is_rect_equals(&flash_rect->rect, rect)) {
flash_rect->paint_time = LCUI_GetTime();
return;
}
}
flash_rect = NEW(FlashRectRec, 1);
flash_rect->rect = *rect;
flash_rect->paint_time = LCUI_GetTime();
LinkedList_Append(&record->flash_rects, flash_rect);
}
static void GetRenderingLayerSize(int *width, int *height)
{
float scale = LCUIMetrics_GetScale();
*width = (int)(LCUIDisplay_GetWidth() * scale);
*height = (int)(LCUIDisplay_GetHeight() * scale);
*height =
max(200, *height / display.settings.parallel_rendering_threads + 1);
}
static void SurfaceRecord_DumpRects(SurfaceRecord record, LinkedList *rects)
{
typedef struct DirtyLayerRec {
LinkedList rects;
LCUI_Rect rect;
int diry;
} DirtyLayerRec, *DirtyLayer;
int i;
int max_dirty;
int layer_width;
int layer_height;
LCUI_Rect rect;
LCUI_Rect *sub_rect;
DirtyLayer layer;
DirtyLayerRec *layers;
LinkedListNode *node;
GetRenderingLayerSize(&layer_width, &layer_height);
max_dirty = (int)(0.8 * layer_width * layer_height);
layers = malloc(sizeof(DirtyLayerRec) *
display.settings.parallel_rendering_threads);
for (i = 0; i < display.settings.parallel_rendering_threads; ++i) {
layer = &layers[i];
layer->diry = 0;
layer->rect.y = i * layer_height;
layer->rect.x = 0;
layer->rect.width = layer_width;
layer->rect.height = layer_height;
LinkedList_Init(&layer->rects);
}
sub_rect = malloc(sizeof(LCUI_Rect));
for (LinkedList_Each(node, &record->rects)) {
rect = *(LCUI_Rect *)node->data;
for (i = 0; i < display.settings.parallel_rendering_threads;
++i) {
layer = &layers[i];
if (layer->diry >= max_dirty) {
continue;
}
if (!LCUIRect_GetOverlayRect(&layer->rect, &rect,
sub_rect)) {
continue;
}
LinkedList_Append(&layer->rects, sub_rect);
rect.y += sub_rect->height;
rect.height -= sub_rect->height;
layer->diry += sub_rect->width * sub_rect->height;
sub_rect = malloc(sizeof(LCUI_Rect));
if (rect.height < 1) {
break;
}
}
}
for (i = 0; i < display.settings.parallel_rendering_threads; ++i) {
layer = &layers[i];
if (layer->diry >= max_dirty) {
RectList_AddEx(rects, &layer->rect, FALSE);
RectList_Clear(&layer->rects);
} else {
LinkedList_Concat(rects, &layer->rects);
}
}
RectList_Clear(&record->rects);
free(sub_rect);
free(layers);
}
static size_t LCUIDisplay_RenderSurfaceRect(SurfaceRecord record,
LCUI_Rect *rect)
{
size_t count;
LCUI_PaintContext paint;
if (!record->widget || !record->surface ||
!Surface_IsReady(record->surface)) {
return 0;
}
paint = Surface_BeginPaint(record->surface, rect);
if (!paint) {
return 0;
}
DEBUG_MSG("[thread %d/%d] rect: (%d,%d,%d,%d)\n", omp_get_thread_num(),
omp_get_num_threads(), paint->rect.x, paint->rect.y,
paint->rect.width, paint->rect.height);
count = Widget_Render(record->widget, paint);
if (display.settings.paint_flashing) {
LCUIDisplay_AppendFlashRects(record, &paint->rect);
}
if (display.mode != LCUI_DMODE_SEAMLESS) {
LCUICursor_Paint(paint);
}
Surface_EndPaint(record->surface, paint);
return count;
}
static size_t LCUIDisplay_RenderSurface(SurfaceRecord record)
{
int i = 0;
int dirty = 0;
int layer_width;
int layer_height;
size_t count = 0;
LCUI_Rect **rect_array;
LinkedList rects;
LinkedListNode *node;
LinkedList_Init(&rects);
GetRenderingLayerSize(&layer_width, &layer_height);
SurfaceRecord_DumpRects(record, &rects);
if (rects.length < 1) {
return 0;
}
rect_array = (LCUI_Rect **)malloc(sizeof(LCUI_Rect *) * rects.length);
for (LinkedList_Each(node, &rects)) {
LCUI_SysEventRec ev;
rect_array[i] = node->data;
ev.type = LCUI_PAINT;
ev.paint.rect = *rect_array[i];
LCUI_TriggerEvent(&ev, NULL);
dirty += rect_array[i]->width * rect_array[i]->height;
i++;
}
// Use OPENMP if the render area is larger than two render layers
if (dirty >= layer_width * layer_height * 2) {
#ifdef USE_OPENMP
#pragma omp parallel for \
default(none) \
shared(display, rects, rect_array) \
firstprivate(record) \
reduction(+:count)
#endif
for (i = 0; i < (int)rects.length; ++i) {
count += LCUIDisplay_RenderSurfaceRect(record,
rect_array[i]);
}
} else {
for (i = 0; i < (int)rects.length; ++i) {
count += LCUIDisplay_RenderSurfaceRect(record,
rect_array[i]);
}
}
free(rect_array);
RectList_Clear(&rects);
record->rendered = count > 0;
count += LCUIDisplay_UpdateFlashRects(record);
return count;
}
void LCUIDisplay_Update(void)
{
LCUI_Surface surface;
LinkedListNode *node;
SurfaceRecord record = NULL;
if (!display.active) {
return;
}
for (LinkedList_Each(node, &display.surfaces)) {
record = node->data;
surface = record->surface;
if (record->widget && surface && Surface_IsReady(surface)) {
Surface_Update(surface);
}
Widget_GetInvalidArea(record->widget, &record->rects);
}
if (display.mode == LCUI_DMODE_SEAMLESS || !record) {
return;
}
LinkedList_Concat(&record->rects, &display.rects);
}
size_t LCUIDisplay_Render(void)
{
size_t count = 0;
LinkedListNode *node;
if (!display.active) {
return 0;
}
for (LinkedList_Each(node, &display.surfaces)) {
count += LCUIDisplay_RenderSurface(node->data);
count += LCUIDisplay_UpdateFlashRects(node->data);
}
return count;
}
void LCUIDisplay_Present(void)
{
LinkedListNode *sn;
if (!display.active) {
return;
}
for (LinkedList_Each(sn, &display.surfaces)) {
SurfaceRecord record = sn->data;
LCUI_Surface surface = record->surface;
if (!surface || !Surface_IsReady(surface)) {
continue;
}
if (record->rendered) {
Surface_Present(surface);
}
}
}
void LCUIDisplay_InvalidateArea(LCUI_Rect *rect)
{
LCUI_Rect area;
if (!display.active) {
return;
}
if (!rect) {
area.x = 0;
area.y = 0;
area.width = LCUIDisplay_GetWidth();
area.height = LCUIDisplay_GetHeight();
rect = &area;
}
RectToInvalidArea(rect, &area);
RectList_Add(&display.rects, &area);
}
static LCUI_Widget LCUIDisplay_GetBindWidget(LCUI_Surface surface)
{
SurfaceRecord record;
LinkedListNode *node;
for (LinkedList_Each(node, &display.surfaces)) {
record = node->data;
if (record && record->surface == surface) {
return record->widget;
}
}
return NULL;
}
static LCUI_Surface LCUIDisplay_GetBindSurface(LCUI_Widget widget)
{
SurfaceRecord record;
LinkedListNode *node;
for (LinkedList_Each(node, &display.surfaces)) {
record = node->data;
if (record && record->widget == widget) {
return record->surface;
}
}
return NULL;
}
LCUI_Surface LCUIDisplay_GetSurfaceOwner(LCUI_Widget w)
{
if (LCUIDisplay_GetMode() == LCUI_DMODE_SEAMLESS) {
while (w->parent) {
w = w->parent;
}
} else {
w = LCUIWidget_GetRoot();
}
return LCUIDisplay_GetBindSurface(w);
}
LCUI_Surface LCUIDisplay_GetSurfaceByHandle(void *handle)
{
LinkedListNode *node;
for (LinkedList_Each(node, &display.surfaces)) {
SurfaceRecord record = node->data;
if (Surface_GetHandle(record->surface) == handle) {
return record->surface;
}
}
return NULL;
}
/** 将 widget 与 sruface 进行绑定 */
static void LCUIDisplay_BindSurface(LCUI_Widget widget)
{
LCUI_Rect rect;
SurfaceRecord record;
if (LCUIDisplay_GetBindSurface(widget)) {
return;
}
record = NEW(SurfaceRecordRec, 1);
record->surface = Surface_New();
record->widget = widget;
record->rendered = FALSE;
LinkedList_Init(&record->flash_rects);
LCUIMetrics_ComputeRectActual(&rect, &widget->box.canvas);
if (Widget_CheckStyleValid(widget, key_top) &&
Widget_CheckStyleValid(widget, key_left)) {
Surface_Move(record->surface, rect.x, rect.y);
}
Surface_SetCaptionW(record->surface, widget->title);
Surface_Resize(record->surface, rect.width, rect.height);
if (widget->computed_style.visible) {
Surface_Show(record->surface);
} else {
Surface_Hide(record->surface);
}
Widget_InvalidateArea(widget, NULL, SV_GRAPH_BOX);
LinkedList_Append(&display.surfaces, record);
}
/** 解除 widget 与 sruface 的绑定 */
static void LCUIDisplay_UnbindSurface(LCUI_Widget widget)
{
SurfaceRecord record;
LinkedListNode *node;
for (LinkedList_Each(node, &display.surfaces)) {
record = node->data;
if (record && record->widget == widget) {
Surface_Close(record->surface);
LinkedList_DeleteNode(&display.surfaces, node);
break;
}
}
}
static int LCUIDisplay_Windowed(void)
{
LCUI_Widget root;
root = LCUIWidget_GetRoot();
switch (display.mode) {
case LCUI_DMODE_WINDOWED:
return 0;
case LCUI_DMODE_FULLSCREEN:
LCUIDisplay_GetBindSurface(root);
break;
case LCUI_DMODE_SEAMLESS:
default:
LCUIDisplay_CleanSurfaces();
LCUIDisplay_BindSurface(root);
break;
}
LCUIDisplay_SetSize(display.width, display.height);
display.mode = LCUI_DMODE_WINDOWED;
return 0;
}
static int LCUIDisplay_FullScreen(void)
{
LCUI_Widget root;
root = LCUIWidget_GetRoot();
switch (display.mode) {
case LCUI_DMODE_SEAMLESS:
LCUIDisplay_CleanSurfaces();
LCUIDisplay_BindSurface(root);
case LCUI_DMODE_WINDOWED:
default:
break;
case LCUI_DMODE_FULLSCREEN:
return 0;
}
display.mode = LCUI_DMODE_FULLSCREEN;
display.width = LCUIDisplay_GetWidth();
display.height = LCUIDisplay_GetHeight();
LCUIDisplay_SetSize(display.width, display.height);
return 0;
}
/* FIXME: improve the seamless display mode
* the seamless display mode has not been updated for a long time, we not
* sure if it can work.
*/
static int LCUIDisplay_Seamless(void)
{
LinkedListNode *node;
LCUI_Widget root = LCUIWidget_GetRoot();
switch (display.mode) {
case LCUI_DMODE_SEAMLESS:
return 0;
case LCUI_DMODE_FULLSCREEN:
case LCUI_DMODE_WINDOWED:
default:
LCUIDisplay_CleanSurfaces();
break;
}
for (LinkedList_Each(node, &root->children)) {
LCUIDisplay_BindSurface(node->data);
}
display.mode = LCUI_DMODE_SEAMLESS;
return 0;
}
/* 设置呈现模式 */
int LCUIDisplay_SetMode(int mode)
{
int ret;
switch (mode) {
case LCUI_DMODE_WINDOWED:
ret = LCUIDisplay_Windowed();
break;
case LCUI_DMODE_SEAMLESS:
ret = LCUIDisplay_Seamless();
break;
case LCUI_DMODE_FULLSCREEN:
default:
ret = LCUIDisplay_FullScreen();
break;
}
return ret;
}
/* 获取呈现模式 */
int LCUIDisplay_GetMode(void)
{
return display.mode;
}
void LCUIDisplay_EnablePaintFlashing(LCUI_BOOL enable)
{
LCUI_SettingsRec settings;
Settings_Init(&settings);
settings.paint_flashing = enable;
LCUI_ApplySettings(&settings);
}
/** 设置显示区域的尺寸,仅在窗口化、全屏模式下有效 */
void LCUIDisplay_SetSize(int width, int height)
{
float scale;
LCUI_Widget root;
LCUI_Surface surface;
if (display.mode == LCUI_DMODE_SEAMLESS) {
return;
}
root = LCUIWidget_GetRoot();
scale = LCUIMetrics_GetScale();
surface = LCUIDisplay_GetBindSurface(root);
Surface_Resize(surface, width, height);
Widget_Resize(root, width / scale, height / scale);
}
int LCUIDisplay_GetWidth(void)
{
if (!display.active) {
return 0;
}
if (display.mode == LCUI_DMODE_WINDOWED ||
display.mode == LCUI_DMODE_FULLSCREEN) {
return iround(LCUIWidget_GetRoot()->width);
}
return display.driver->getWidth();
}
int LCUIDisplay_GetHeight(void)
{
if (!display.active) {
return 0;
}
if (display.mode == LCUI_DMODE_WINDOWED ||
display.mode == LCUI_DMODE_FULLSCREEN) {
return iround(LCUIWidget_GetRoot()->height);
}
return display.driver->getHeight();
}
void Surface_Close(LCUI_Surface surface)
{
if (display.active) {
display.driver->close(surface);
}
}
void Surface_Destroy(LCUI_Surface surface)
{
LinkedListNode *node;
if (!display.active) {
return;
}
for (LinkedList_Each(node, &display.surfaces)) {
SurfaceRecord record = node->data;
if (record && record->surface == surface) {
LinkedList_DeleteNode(&display.surfaces, node);
display.driver->destroy(surface);
free(record);
break;
}
}
}
LCUI_Surface Surface_New(void)
{
if (display.driver) {
return display.driver->create();
}
return NULL;
}
LCUI_BOOL Surface_IsReady(LCUI_Surface surface)
{
if (display.driver) {
return display.driver->isReady(surface);
}
return TRUE;
}
void Surface_Move(LCUI_Surface surface, int x, int y)
{
if (display.driver) {
display.driver->move(surface, x, y);
}
}
int Surface_GetWidth(LCUI_Surface surface)
{
if (display.driver) {
return display.driver->getSurfaceWidth(surface);
}
return 0;
}
int Surface_GetHeight(LCUI_Surface surface)
{
if (display.driver) {
return display.driver->getSurfaceHeight(surface);
}
return 0;
}
void Surface_Resize(LCUI_Surface surface, int w, int h)
{
if (display.driver) {
display.driver->resize(surface, w, h);
}
}
void Surface_SetCaptionW(LCUI_Surface surface, const wchar_t *str)
{
if (display.driver) {
display.driver->setCaptionW(surface, str);
}
}
void Surface_Show(LCUI_Surface surface)
{
if (display.driver) {
display.driver->show(surface);
}
}
void Surface_Hide(LCUI_Surface surface)
{
if (display.driver) {
display.driver->hide(surface);
}
}
void *Surface_GetHandle(LCUI_Surface surface)
{
if (display.driver) {
return display.driver->getHandle(surface);
}
return NULL;
}
void Surface_SetRenderMode(LCUI_Surface surface, int mode)
{
if (display.driver) {
display.driver->setRenderMode(surface, mode);
}
}
void Surface_Update(LCUI_Surface surface)
{
if (display.driver) {
display.driver->update(surface);
}
}
LCUI_PaintContext Surface_BeginPaint(LCUI_Surface surface, LCUI_Rect *rect)
{
if (display.driver) {
return display.driver->beginPaint(surface, rect);
}
return NULL;
}
void Surface_EndPaint(LCUI_Surface surface, LCUI_PaintContext paint)
{
if (display.driver) {
display.driver->endPaint(surface, paint);
}
}
void Surface_Present(LCUI_Surface surface)
{
if (display.driver) {
display.driver->present(surface);
}
}
/** 响应顶级部件的各种事件 */
static void OnSurfaceEvent(LCUI_Widget w, LCUI_WidgetEvent e, void *arg)
{
LCUI_Widget root;
LCUI_RectF *rect;
LCUI_Surface surface;
int *data, event_type, sync_props;
data = (int *)arg;
event_type = data[0];
sync_props = data[1];
root = LCUIWidget_GetRoot();
surface = LCUIDisplay_GetBindSurface(e->target);
if (display.mode == LCUI_DMODE_SEAMLESS) {
if (!surface && event_type != LCUI_WEVENT_LINK) {
return;
}
} else if (e->target == root) {
if (!surface && event_type != LCUI_WEVENT_LINK) {
return;
}
} else {
return;
}
rect = &e->target->box.canvas;
switch (event_type) {
case LCUI_WEVENT_LINK:
LCUIDisplay_BindSurface(e->target);
break;
case LCUI_WEVENT_UNLINK:
case LCUI_WEVENT_DESTROY:
LCUIDisplay_UnbindSurface(e->target);
break;
case LCUI_WEVENT_SHOW:
Surface_Show(surface);
break;
case LCUI_WEVENT_HIDE:
Surface_Hide(surface);
break;
case LCUI_WEVENT_RESIZE: {
LCUI_Rect area;
RectFToInvalidArea(rect, &area);
if (sync_props) {
Surface_Resize(surface, area.width, area.height);
}
break;
}
case LCUI_WEVENT_TITLE:
Surface_SetCaptionW(surface, e->target->title);
break;
default:
break;
}
}
/** 在 surface 主动产生无效区域并需要绘制的时候 */
static void OnPaint(LCUI_Event e, void *arg)
{
LCUI_RectF rect;
LinkedListNode *node;
SurfaceRecord record;
LCUI_DisplayEvent dpy_ev = arg;
for (LinkedList_Each(node, &display.surfaces)) {
record = node->data;
if (record && record->surface != dpy_ev->surface) {
continue;
}
LCUIRect_ToRectF(&dpy_ev->paint.rect, &rect, 1.0f);
Widget_InvalidateArea(record->widget, &rect, SV_GRAPH_BOX);
}
}
static void OnResize(LCUI_Event e, void *arg)
{
LCUI_Widget widget;
LCUI_DisplayEvent dpy_ev = arg;
float scale = LCUIMetrics_GetScale();
float width = dpy_ev->resize.width / scale;
float height = dpy_ev->resize.height / scale;
widget = LCUIDisplay_GetBindWidget(dpy_ev->surface);
if (widget) {
Widget_Resize(widget, width, height);
widget->task.skip_surface_props_sync = TRUE;
}
LCUI_RunFrame();
}
static void OnMinMaxInfo(LCUI_Event e, void *arg)
{
LCUI_BOOL resizable = FALSE;
LCUI_DisplayEvent dpy_ev = arg;
LCUI_Surface s = dpy_ev->surface;
LCUI_Widget widget = LCUIDisplay_GetBindWidget(s);
LCUI_WidgetStyle *style = &widget->computed_style;
int width = Surface_GetWidth(s);
int height = Surface_GetHeight(s);
if (style->min_width >= 0) {
dpy_ev->minmaxinfo.min_width = iround(style->min_width);
resizable = resizable || width < style->min_width;
}
if (style->max_width >= 0) {
dpy_ev->minmaxinfo.max_width = iround(style->max_width);
resizable = resizable || width > style->max_width;
}
if (style->min_height >= 0) {
dpy_ev->minmaxinfo.min_height = iround(style->min_height);
resizable = resizable || height < style->min_height;
}
if (style->max_height >= 0) {
dpy_ev->minmaxinfo.max_height = iround(style->max_height);
resizable = resizable || height > style->max_height;
}
if (resizable) {
LCUI_Rect area;
RectFToInvalidArea(&widget->box.canvas, &area);
Surface_Resize(s, area.width, area.height);
}
}
int LCUIDisplay_BindEvent(int event_id, LCUI_EventFunc func, void *arg,
void *data, void (*destroy_data)(void *))
{
if (display.active) {
return display.driver->bindEvent(event_id, func, data,
destroy_data);
}
return -1;
}
int LCUI_InitDisplay(LCUI_DisplayDriver driver)
{
LCUI_Widget root;
if (display.active) {
return -1;
}
Logger_Debug("[display] init ...\n");
display.mode = 0;
display.driver = driver;
display.active = TRUE;
display.width = DEFAULT_WIDTH;
display.height = DEFAULT_HEIGHT;
Settings_Init(&display.settings);
display.settings_change_handler_id = LCUI_BindEvent(
LCUI_SETTINGS_CHANGE, OnSettingsChangeEvent, NULL, NULL);
LinkedList_Init(&display.rects);
LinkedList_Init(&display.surfaces);
if (!display.driver) {
display.driver = LCUI_CreateDisplayDriver();
}
if (!display.driver) {
Logger_Warning("[display] init failed\n");
LCUIDisplay_SetMode(LCUI_DMODE_DEFAULT);
LCUIDisplay_Update();
return -2;
}
root = LCUIWidget_GetRoot();
display.driver->bindEvent(LCUI_DEVENT_RESIZE, OnResize, NULL, NULL);
display.driver->bindEvent(LCUI_DEVENT_MINMAXINFO, OnMinMaxInfo, NULL,
NULL);
display.driver->bindEvent(LCUI_DEVENT_PAINT, OnPaint, NULL, NULL);
Widget_BindEvent(root, "surface", OnSurfaceEvent, NULL, NULL);
LCUIDisplay_SetMode(LCUI_DMODE_DEFAULT);
LCUIDisplay_Update();
Logger_Debug("[display] init ok, driver name: %s\n",
display.driver->name);
return 0;
}
/** 停用图形输出模块 */
int LCUI_FreeDisplay(void)
{
if (!display.active) {
return -1;
}
display.active = FALSE;
RectList_Clear(&display.rects);
LCUIDisplay_CleanSurfaces();
if (display.driver) {
LCUI_DestroyDisplayDriver(display.driver);
}
LCUI_UnbindEvent(display.settings_change_handler_id);
display.settings_change_handler_id = -1;
return 0;
}
|
DRB079-taskdep3-orig-no.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.
*/
/*
tasks with depend clauses to ensure execution order, no data races.
*/
#include <stdio.h>
#include <assert.h>
#include <unistd.h>
int main()
{
int i=0, j, k;
#pragma omp parallel
#pragma omp single
{
#pragma omp task depend (out:i)
{
sleep(3);
i = 1;
}
#pragma omp task depend (in:i)
j =i;
#pragma omp task depend (in:i)
k =i;
}
printf ("j=%d k=%d\n", j, k);
assert (j==1 && k==1);
return 0;
}
|
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] = 32;
tile_size[3] = 2048;
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;
}
|
laplace.h | #ifndef laplace_h
#define laplace_h
#include "exafmm.h"
namespace exafmm {
inline int oddOrEven(int n) {
return (((n) & 1) == 1) ? -1 : 1;
}
inline int ipow2n(int n) {
return (n >= 0) ? 1 : oddOrEven(n);
}
void cart2sph(const vec3 & dX, real_t & r, real_t & theta, real_t & phi) {
r = sqrt(norm(dX));
theta = r == 0 ? 0 : acos(dX[2] / r);
phi = atan2(dX[1], dX[0]);
}
void sph2cart(real_t r, real_t theta, real_t phi, const vec3 & spherical, vec3 & cartesian) {
real_t invSinTheta = theta == 0 ? 0 : 1 / std::sin(theta);
real_t invR = r == 0 ? 0 : 1 / r;
cartesian[0] = std::sin(theta) * std::cos(phi) * spherical[0]
+ std::cos(theta) * std::cos(phi) * invR * spherical[1]
- std::sin(phi) * invR * invSinTheta * spherical[2];
cartesian[1] = std::sin(theta) * std::sin(phi) * spherical[0]
+ std::cos(theta) * std::sin(phi) * invR * spherical[1]
+ std::cos(phi) * invR * invSinTheta * spherical[2];
cartesian[2] = std::cos(theta) * spherical[0]
- std::sin(theta) * invR * spherical[1];
}
void evalMultipole(real_t rho, real_t alpha, real_t beta, complex_t * Ynm, complex_t * YnmTheta) {
real_t x = std::cos(alpha);
real_t y = std::sin(alpha);
real_t invY = y == 0 ? 0 : 1 / y;
real_t fact = 1;
real_t pn = 1;
real_t rhom = 1;
complex_t ei = std::exp(I * beta);
complex_t eim = 1.0;
for (int m=0; m<P; m++) {
real_t p = pn;
int npn = m * m + 2 * m;
int nmn = m * m;
Ynm[npn] = rhom * p * eim;
Ynm[nmn] = std::conj(Ynm[npn]);
real_t p1 = p;
p = x * (2 * m + 1) * p1;
YnmTheta[npn] = rhom * (p - (m + 1) * x * p1) * invY * eim;
rhom *= rho;
real_t rhon = rhom;
for (int n=m+1; n<P; n++) {
int npm = n * n + n + m;
int nmm = n * n + n - m;
rhon /= -(n + m);
Ynm[npm] = rhon * p * eim;
Ynm[nmm] = std::conj(Ynm[npm]);
real_t p2 = p1;
p1 = p;
p = (x * (2 * n + 1) * p1 - (n + m) * p2) / (n - m + 1);
YnmTheta[npm] = rhon * ((n - m + 1) * p - (n + 1) * x * p1) * invY * eim;
rhon *= rho;
}
rhom /= -(2 * m + 2) * (2 * m + 1);
pn = -pn * fact * y;
fact += 2;
eim *= ei;
}
}
void evalLocal(real_t rho, real_t alpha, real_t beta, complex_t * Ynm) {
real_t x = std::cos(alpha);
real_t y = std::sin(alpha);
real_t fact = 1;
real_t pn = 1;
real_t invR = -1.0 / rho;
real_t rhom = -invR;
complex_t ei = std::exp(I * beta);
complex_t eim = 1.0;
for (int m=0; m<P; m++) {
real_t p = pn;
int npn = m * m + 2 * m;
int nmn = m * m;
Ynm[npn] = rhom * p * eim;
Ynm[nmn] = std::conj(Ynm[npn]);
real_t p1 = p;
p = x * (2 * m + 1) * p1;
rhom *= invR;
real_t rhon = rhom;
for (int n=m+1; n<P; n++) {
int npm = n * n + n + m;
int nmm = n * n + n - m;
Ynm[npm] = rhon * p * eim;
Ynm[nmm] = std::conj(Ynm[npm]);
real_t p2 = p1;
p1 = p;
p = (x * (2 * n + 1) * p1 - (n + m) * p2) / (n - m + 1);
rhon *= invR * (n - m + 1);
}
pn = -pn * fact * y;
fact += 2;
eim *= ei;
}
}
void initKernel() {
NTERM = P * (P + 1) / 2;
}
#if 1
void P2P(Cell * Ci, Cell * Cj) {
Body * Bi = Ci->body;
Body * Bj = Cj->body;
int i, j, num = Ci->numBodies;
#pragma omp parallel for private(j)
for (i=0; i<num; i+=NSIMD) {
simdvec zero((real_t)0);
simdvec p(zero);
simdvec Fx(zero);
simdvec Fy(zero);
simdvec Fz(zero);
simdvec invR(zero);
simdvec xi(&Bi[i].X[0], (int)sizeof(Body));
simdvec yi(&Bi[i].X[1], (int)sizeof(Body));
simdvec zi(&Bi[i].X[2], (int)sizeof(Body));
simdvec R2(zero);
simdvec x2(Bj[0].X[0]);
x2 = x2 - xi + IX[0] * CYCLE;
simdvec y2(Bj[0].X[1]);
y2 = y2 - yi + IX[1] * CYCLE;
simdvec z2(Bj[0].X[2]);
z2 = z2 - zi + IX[2] * CYCLE;
simdvec q(Bj[0].q);
simdvec xj = x2;
R2 = R2 + x2 * x2;
simdvec yj = y2;
R2 = R2 + y2 * y2;
simdvec zj = z2;
R2 = R2 + z2 * z2;
x2 = Bj[1].X[0];
y2 = Bj[1].X[1];
z2 = Bj[1].X[2];
for (j=1; j<Cj->numBodies-1; j++) {
invR = rsqrt(R2);
invR &= R2 > zero;
R2 = zero;
x2 = x2 - xi + IX[0] * CYCLE;
y2 = y2 - yi + IX[1] * CYCLE;
z2 = z2 - zi + IX[2] * CYCLE;
q = q * invR;
p = p + q;
invR = invR * invR * q;
q = Bj[j].q;
Fx = Fx + xj * invR;
xj = x2;
R2 = R2 + x2 * x2;
x2 = Bj[j+1].X[0];
Fy = Fy + yj * invR;
yj = y2;
R2 = R2 + y2 * y2;
y2 = Bj[j+1].X[1];
Fz = Fz + zj * invR;
zj = z2;
R2 = R2 + z2 * z2;
z2 = Bj[j+1].X[2];
}
invR = rsqrt(R2);
invR &= R2 > zero;
R2 = zero;
q = q * invR;
p = p + q;
invR = invR * invR * q;
q = Bj[Cj->numBodies-1].q;
Fx = Fx + xj * invR;
Fy = Fy + yj * invR;
Fz = Fz + zj * invR;
if(Cj->numBodies > 1) {
x2 = x2 - xi + IX[0] * CYCLE;
y2 = y2 - yi + IX[1] * CYCLE;
z2 = z2 - zi + IX[2] * CYCLE;
R2 = R2 + x2 * x2;
R2 = R2 + y2 * y2;
R2 = R2 + z2 * z2;
xj = x2;
yj = y2;
zj = z2;
invR = rsqrt(R2);
invR &= R2 > zero;
q = q * invR;
p = p + q;
invR = invR * invR;
invR = invR * q;
xj = xj * invR;
Fx = Fx + xj;
yj = yj * invR;
Fy = Fy + yj;
zj = zj * invR;
Fz = Fz + zj;
}
for (int k=0; k<NSIMD && i+k<num; k++) {
Bi[i+k].p += p[k];
Bi[i+k].F[0] += Fx[k];
Bi[i+k].F[1] += Fy[k];
Bi[i+k].F[2] += Fz[k];
}
}
}
#else
void P2P(Cell * Ci, Cell * Cj) {
Body * Bi = Ci->body;
Body * Bj = Cj->body;
for (int i=0; i<Ci->numBodies; i++) {
real_t p = 0;
vec3 F = 0;
for (int j=0; j<Cj->numBodies; j++) {
vec3 dX;
for (int d=0; d<3; d++) dX[d] = Bi[i].X[d] - Bj[j].X[d] - IX[d] * CYCLE;
real_t R2 = norm(dX);
if (R2 != 0) {
real_t invR2 = 1.0 / R2;
real_t invR = Bj[j].q * sqrt(invR2);
p += invR;
F += dX * invR2 * invR;
}
}
#pragma omp atomic
Bi[i].p += p;
for (int d=0; d<3; d++) {
#pragma omp atomic
Bi[i].F[d] -= F[d];
}
}
}
#endif
void P2M(Cell * C) {
complex_t Ynm[P*P], YnmTheta[P*P];
for (Body * B=C->body; B!=C->body+C->numBodies; B++) {
vec3 dX = B->X - C->X;
real_t rho, alpha, beta;
cart2sph(dX, rho, alpha, beta);
evalMultipole(rho, alpha, -beta, Ynm, YnmTheta);
for (int n=0; n<P; n++) {
for (int m=0; m<=n; m++) {
int nm = n * n + n + m;
int nms = n * (n + 1) / 2 + m;
C->M[nms] += B->q * Ynm[nm];
}
}
}
}
void M2M(Cell * Ci) {
complex_t Ynm[P*P], YnmTheta[P*P];
for (Cell * Cj=Ci->child; Cj!=Ci->child+Ci->numChilds; Cj++) {
vec3 dX = Ci->X - Cj->X;
real_t rho, alpha, beta;
cart2sph(dX, rho, alpha, beta);
evalMultipole(rho, alpha, beta, Ynm, YnmTheta);
for (int j=0; j<P; j++) {
for (int k=0; k<=j; k++) {
int jks = j * (j + 1) / 2 + k;
complex_t M = 0;
for (int n=0; n<=j; n++) {
for (int m=std::max(-n,-j+k+n); m<=std::min(k-1,n); m++) {
int jnkms = (j - n) * (j - n + 1) / 2 + k - m;
int nm = n * n + n - m;
M += Cj->M[jnkms] * Ynm[nm] * real_t(ipow2n(m) * oddOrEven(n));
}
for (int m=k; m<=std::min(n,j+k-n); m++) {
int jnkms = (j - n) * (j - n + 1) / 2 - k + m;
int nm = n * n + n - m;
M += std::conj(Cj->M[jnkms]) * Ynm[nm] * real_t(oddOrEven(k+n+m));
}
}
Ci->M[jks] += M;
}
}
}
}
void M2L(Cell * Ci, Cell * Cj) {
complex_t Ynm2[4*P*P];
vec3 dX;
for (int d=0; d<3; d++) dX[d] = Ci->X[d] - Cj->X[d] - IX[d] * CYCLE;
real_t rho, alpha, beta;
cart2sph(dX, rho, alpha, beta);
evalLocal(rho, alpha, beta, Ynm2);
for (int j=0; j<P; j++) {
real_t Cnm = oddOrEven(j);
for (int k=0; k<=j; k++) {
int jks = j * (j + 1) / 2 + k;
complex_t L = 0;
for (int n=0; n<P; n++) {
for (int m=-n; m<0; m++) {
int nms = n * (n + 1) / 2 - m;
int jnkm = (j + n) * (j + n) + j + n + m - k;
L += std::conj(Cj->M[nms]) * Cnm * Ynm2[jnkm];
}
for (int m=0; m<=n; m++) {
int nms = n * (n + 1) / 2 + m;
int jnkm = (j + n) * (j + n) + j + n + m - k;
real_t Cnm2 = Cnm * oddOrEven((k-m)*(k<m)+m);
L += Cj->M[nms] * Cnm2 * Ynm2[jnkm];
}
}
Ci->L[jks] += L;
}
}
}
void L2L(Cell * Cj) {
complex_t Ynm[P*P], YnmTheta[P*P];
for (Cell * Ci=Cj->child; Ci!=Cj->child+Cj->numChilds; Ci++) {
vec3 dX = Ci->X - Cj->X;
real_t rho, alpha, beta;
cart2sph(dX, rho, alpha, beta);
evalMultipole(rho, alpha, beta, Ynm, YnmTheta);
for (int j=0; j<P; j++) {
for (int k=0; k<=j; k++) {
int jks = j * (j + 1) / 2 + k;
complex_t L = 0;
for (int n=j; n<P; n++) {
for (int m=j+k-n; m<0; m++) {
int jnkm = (n - j) * (n - j) + n - j + m - k;
int nms = n * (n + 1) / 2 - m;
L += std::conj(Cj->L[nms]) * Ynm[jnkm] * real_t(oddOrEven(k));
}
for (int m=0; m<=n; m++) {
if (n-j >= abs(m-k)) {
int jnkm = (n - j) * (n - j) + n - j + m - k;
int nms = n * (n + 1) / 2 + m;
L += Cj->L[nms] * Ynm[jnkm] * real_t(oddOrEven((m-k)*(m<k)));
}
}
}
Ci->L[jks] += L;
}
}
}
}
void L2P(Cell * C) {
complex_t Ynm[P*P], YnmTheta[P*P];
for (Body * B=C->body; B!=C->body+C->numBodies; B++) {
vec3 dX = B->X - C->X;
vec3 spherical = 0;
vec3 cartesian = 0;
real_t r, theta, phi;
cart2sph(dX, r, theta, phi);
evalMultipole(r, theta, phi, Ynm, YnmTheta);
for (int n=0; n<P; n++) {
int nm = n * n + n;
int nms = n * (n + 1) / 2;
B->p += std::real(C->L[nms] * Ynm[nm]);
spherical[0] += std::real(C->L[nms] * Ynm[nm]) / r * n;
spherical[1] += std::real(C->L[nms] * YnmTheta[nm]);
for (int m=1; m<=n; m++) {
nm = n * n + n + m;
nms = n * (n + 1) / 2 + m;
B->p += 2 * std::real(C->L[nms] * Ynm[nm]);
spherical[0] += 2 * std::real(C->L[nms] * Ynm[nm]) / r * n;
spherical[1] += 2 * std::real(C->L[nms] * YnmTheta[nm]);
spherical[2] += 2 * std::real(C->L[nms] * Ynm[nm] * I) * m;
}
}
sph2cart(r, theta, phi, spherical, cartesian);
B->F += cartesian;
}
}
}
#endif
|
GB_unaryop__lnot_int64_int16.c | //------------------------------------------------------------------------------
// GB_unaryop: hard-coded functions for each built-in unary operator
//------------------------------------------------------------------------------
// SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2019, All Rights Reserved.
// http://suitesparse.com See GraphBLAS/Doc/License.txt for license.
//------------------------------------------------------------------------------
// If this file is in the Generated/ folder, do not edit it (auto-generated).
#include "GB.h"
#ifndef GBCOMPACT
#include "GB_control.h"
#include "GB_iterator.h"
#include "GB_unaryop__include.h"
// C=unop(A) is defined by the following types and operators:
// op(A) function: GB_unop__lnot_int64_int16
// op(A') function: GB_tran__lnot_int64_int16
// C type: int64_t
// A type: int16_t
// cast: int64_t cij = (int64_t) aij
// unaryop: cij = !(aij != 0)
#define GB_ATYPE \
int16_t
#define GB_CTYPE \
int64_t
// aij = Ax [pA]
#define GB_GETA(aij,Ax,pA) \
int16_t aij = Ax [pA]
#define GB_CX(p) Cx [p]
// unary operator
#define GB_OP(z, x) \
z = !(x != 0) ;
// casting
#define GB_CASTING(z, x) \
int64_t z = (int64_t) x ;
// cij = op (cast (aij))
#define GB_CAST_OP(pC,pA) \
{ \
/* aij = Ax [pA] */ \
GB_GETA (aij, Ax, pA) ; \
/* Cx [pC] = op (cast (aij)) */ \
GB_CASTING (x, aij) ; \
GB_OP (GB_CX (pC), x) ; \
}
// disable this operator and use the generic case if these conditions hold
#define GB_DISABLE \
(GxB_NO_LNOT || GxB_NO_INT64 || GxB_NO_INT16)
//------------------------------------------------------------------------------
// Cx = op (cast (Ax)): apply a unary operator
//------------------------------------------------------------------------------
GrB_Info GB_unop__lnot_int64_int16
(
int64_t *restrict Cx,
const int16_t *restrict Ax,
int64_t anz,
int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
#pragma omp parallel for num_threads(nthreads) schedule(static)
for (int64_t p = 0 ; p < anz ; p++)
{
GB_CAST_OP (p, p) ;
}
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// C = op (cast (A')): transpose, typecast, and apply a unary operator
//------------------------------------------------------------------------------
GrB_Info GB_tran__lnot_int64_int16
(
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
|
wino_multiply.h | /*******************************************************************************
* Copyright (c) Malith Jayaweera - All rights reserved. *
* This file is part of the MARLIN library. *
* *
* For information on the license, see the LICENSE file. *
* Further information: https://github.com/malithj/marlin/ *
* SPDX-License-Identifier: BSD-3-Clause *
******************************************************************************/
/* Malith Jayaweera
*******************************************************************************/
#ifndef __WINO_MULTIPLY_H__
#define __WINO_MULTIPLY_H__
#include <immintrin.h>
#include "asm_wino.h"
#include "jit/wino_jitter.h"
#include "types/types.h"
namespace MARLIN {
// Performs Winograd elementwise multiplication
// The following variables are used to define the functionality
//
// parameters
// ----------
// transformed filter data - transformed winograd filter
// transform in - transformed winograd input
// in tile area - input tile area after transformation
// out channels - number of filters
// tile count - numer of tiles in input image
// in channels - number of input channels
// transform out - transformed winograd output
template <typename T>
#ifdef ENABLE_JIT
void compute(const T* transform_in, const index_t in_tile_area,
const index_t out_channels, const index_t tile_count,
const index_t in_channels, T* transform_out,
std::shared_ptr<WinoJitter<T>> jitter) {
#else
void compute(const T* transformed_filter_data, const T* transform_in,
const index_t in_tile_area, const index_t out_channels,
const index_t tile_count, const index_t in_channels,
T* transform_out) {
#endif
#pragma omp parallel for collapse(2)
for (index_t m = 0; m < out_channels; ++m) {
for (index_t tile = 0; tile < tile_count; tile += 16) {
const uint16_t mask =
tile + 16 <= tile_count ? 0xffff : ~(0xffff << (tile_count - tile));
for (index_t tidx = 0; tidx < in_tile_area; tidx += 8) {
const T* a_ptr =
transform_in + tile + (tidx * tile_count) * in_channels;
const index_t a_stride = tile_count * in_channels;
const index_t c_stride = tile_count * out_channels;
T* c_ptr = transform_out + m * tile_count + tile + tidx * c_stride;
#ifndef ENABLE_JIT
const index_t b_stride = in_channels * out_channels;
const T* b_ptr =
transformed_filter_data + tidx * b_stride + m * in_channels;
__m512 c0 = _mm512_setzero_ps();
__m512 c1 = _mm512_setzero_ps();
__m512 c2 = _mm512_setzero_ps();
__m512 c3 = _mm512_setzero_ps();
__m512 c4 = _mm512_setzero_ps();
__m512 c5 = _mm512_setzero_ps();
__m512 c6 = _mm512_setzero_ps();
__m512 c7 = _mm512_setzero_ps();
for (index_t c = 0; c < in_channels; ++c) {
const T* a_ptr_ = a_ptr + tile_count * c;
const T* b_ptr_ = b_ptr + c;
__m512 a0 = _mm512_maskz_loadu_ps(mask, a_ptr_);
__m512 a1 = _mm512_maskz_loadu_ps(mask, a_ptr_ + a_stride);
__m512 a2 = _mm512_maskz_loadu_ps(mask, a_ptr_ + 2 * a_stride);
__m512 a3 = _mm512_maskz_loadu_ps(mask, a_ptr_ + 3 * a_stride);
__m512 a4 = _mm512_maskz_loadu_ps(mask, a_ptr_ + 4 * a_stride);
__m512 a5 = _mm512_maskz_loadu_ps(mask, a_ptr_ + 5 * a_stride);
__m512 a6 = _mm512_maskz_loadu_ps(mask, a_ptr_ + 6 * a_stride);
__m512 a7 = _mm512_maskz_loadu_ps(mask, a_ptr_ + 7 * a_stride);
__m128 b_reg;
b_reg = _mm_set1_ps(*b_ptr_);
__m512 b0 = _mm512_broadcastss_ps(b_reg);
b_reg = _mm_set1_ps(*(b_ptr_ + b_stride));
__m512 b1 = _mm512_broadcastss_ps(b_reg);
b_reg = _mm_set1_ps(*(b_ptr_ + 2 * b_stride));
__m512 b2 = _mm512_broadcastss_ps(b_reg);
b_reg = _mm_set1_ps(*(b_ptr_ + 3 * b_stride));
__m512 b3 = _mm512_broadcastss_ps(b_reg);
b_reg = _mm_set1_ps(*(b_ptr_ + 4 * b_stride));
__m512 b4 = _mm512_broadcastss_ps(b_reg);
b_reg = _mm_set1_ps(*(b_ptr_ + 5 * b_stride));
__m512 b5 = _mm512_broadcastss_ps(b_reg);
b_reg = _mm_set1_ps(*(b_ptr_ + 6 * b_stride));
__m512 b6 = _mm512_broadcastss_ps(b_reg);
b_reg = _mm_set1_ps(*(b_ptr_ + 7 * b_stride));
__m512 b7 = _mm512_broadcastss_ps(b_reg);
c0 = _mm512_fmadd_ps(a0, b0, c0);
c1 = _mm512_fmadd_ps(a1, b1, c1);
c2 = _mm512_fmadd_ps(a2, b2, c2);
c3 = _mm512_fmadd_ps(a3, b3, c3);
c4 = _mm512_fmadd_ps(a4, b4, c4);
c5 = _mm512_fmadd_ps(a5, b5, c5);
c6 = _mm512_fmadd_ps(a6, b6, c6);
c7 = _mm512_fmadd_ps(a7, b7, c7);
}
_mm512_mask_storeu_ps(c_ptr, mask, c0);
_mm512_mask_storeu_ps(c_ptr + c_stride, mask, c1);
_mm512_mask_storeu_ps(c_ptr + 2 * c_stride, mask, c2);
_mm512_mask_storeu_ps(c_ptr + 3 * c_stride, mask, c3);
_mm512_mask_storeu_ps(c_ptr + 4 * c_stride, mask, c4);
_mm512_mask_storeu_ps(c_ptr + 5 * c_stride, mask, c5);
_mm512_mask_storeu_ps(c_ptr + 6 * c_stride, mask, c6);
_mm512_mask_storeu_ps(c_ptr + 7 * c_stride, mask, c7);
#else
const index_t idx =
(in_tile_area / 8) * in_channels * m + (tidx / 8) * in_channels;
asm_wino_multiply(a_stride, c_stride, tile_count, in_channels, mask,
a_ptr, c_ptr, jitter->get_p_addr(),
jitter->get_offset_data(), idx);
#endif
}
}
}
}
} // namespace MARLIN
#endif
|
Vec.h | #ifndef VEC_H
#define VEC_H
/*
Szymon Rusinkiewicz
Princeton University
Vec.h
Class for a constant-length vector
Supports the following operations:
vec v1; // Initialized to (0,0,0)
vec v2(1,2,3); // Initialized to (1,2,3)
vec v3(v2); // Copy constructor
float farray[3];
vec v4 = vec(farray); // Explicit: "v4 = farray" won't work
Vec<3,double> vd; // The "vec" used above is Vec<3,float>
point p1, p2, p3; // Same as vec
v3 = v1 + v2; // Also -, *, / (all componentwise)
v3 = 3.5f * v1; // Also vec * scalar, vec / scalar
// NOTE: scalar has to be the same type:
// it won't work to do double * vec<float>
v1 = min(v2,v3); // Componentwise min/max
v1 = sin(v2); // Componentwise - all the usual functions...
swap(v1,v2); // In-place swap
v3 = v1 DOT v2; // Actually operator^
v3 = v1 CROSS v2; // Actually operator%
float f = v1[0]; // Subscript
float *fp = v1; // Implicit conversion to float *
f = len(v1); // Length (also len2 == squared length)
f = dist(p1, p2); // Distance (also dist2 == squared distance)
normalize(v1); // Normalize (i.e., make it unit length)
// normalize(vec(0,0,0)) => vec(1,0,0)
v1 = trinorm(p1,p2,p3); // Normal of triangle
cout << v1 << endl; // iostream output in the form (1,2,3)
cin >> v2; // iostream input using the same syntax
Also defines the utility functions sqr, cube, sgn, fract, clamp, mix,
step, smoothstep, faceforward, reflect, and refract
*/
// Windows defines these as macros, which prevents us from using the
// type-safe versions from std::, as well as interfering with method defns
#undef min
#undef max
#include <cmath>
#include <iostream>
#include <algorithm>
using std::min;
using std::max;
using std::swap;
using std::sqrt;
// Let gcc optimize conditional branches a bit better...
#ifndef likely
# if !defined(__GNUC__) || (__GNUC__ == 2 && __GNUC_MINOR__ < 96)
# define likely(x) (x)
# define unlikely(x) (x)
# else
# define likely(x) (__builtin_expect((x), 1))
# define unlikely(x) (__builtin_expect((x), 0))
# endif
#endif
// Utility functions for square and cube, to go along with sqrt and cbrt
template <class T>
static inline T sqr(const T &x)
{
return x*x;
}
// Boost-like compile-time assertion checking
template <bool X> struct VEC_STATIC_ASSERTION_FAILURE;
template <> struct VEC_STATIC_ASSERTION_FAILURE<true>
{ void operator () () {} };
#define VEC_STATIC_CHECK(expr) VEC_STATIC_ASSERTION_FAILURE<bool(expr)>()
template <int D, class T = float>
class Vec {
protected:
T v[D];
public:
// Constructor for no arguments. Everything initialized to 0.
Vec() { for (int i = 0; i < D; i++) v[i] = T(0); }
// Uninitialized constructor - meant mostly for internal use
#define VEC_UNINITIALIZED ((void *) 0)
Vec(void *) {}
// Constructors for 2-4 arguments
Vec(T x, T y)
{ VEC_STATIC_CHECK(D == 2); v[0] = x; v[1] = y; }
Vec(T x, T y, T z)
{ VEC_STATIC_CHECK(D == 3); v[0] = x; v[1] = y; v[2] = z; }
Vec(T x, T y, T z, T w)
{ VEC_STATIC_CHECK(D == 4); v[0] = x; v[1] = y; v[2] = z; v[3] = w; }
// Constructor from anything that can be accessed using []
// Pretty aggressive, so marked as explicit.
template <class S> explicit Vec(const S &x)
{ for (int i = 0; i < D; i++) v[i] = T(x[i]); }
// No destructor or assignment operator needed
// Array reference and conversion to pointer - no bounds checking
const T &operator [] (int i) const
{ return v[i]; }
T &operator [] (int i)
{ return v[i]; }
operator const T * () const
{ return v; }
operator const T * ()
{ return v; }
operator T * ()
{ return v; }
// Member operators
Vec<D,T> &operator += (const Vec<D,T> &x)
{
for (int i = 0; i < D; i++)
#pragma omp atomic
v[i] += x[i];
return *this;
}
Vec<D,T> &operator -= (const Vec<D,T> &x)
{
for (int i = 0; i < D; i++)
#pragma omp atomic
v[i] -= x[i];
return *this;
}
Vec<D,T> &operator *= (const Vec<D,T> &x)
{
for (int i = 0; i < D; i++)
#pragma omp atomic
v[i] *= x[i];
return *this;
}
Vec<D,T> &operator *= (const T &x)
{
for (int i = 0; i < D; i++)
#pragma omp atomic
v[i] *= x;
return *this;
}
Vec<D,T> &operator /= (const Vec<D,T> &x)
{
for (int i = 0; i < D; i++)
#pragma omp atomic
v[i] /= x[i];
return *this;
}
Vec<D,T> &operator /= (const T &x)
{
for (int i = 0; i < D; i++)
#pragma omp atomic
v[i] /= x;
return *this;
}
// Set each component to min/max of this and the other vector
Vec<D,T> &min(const Vec<D,T> &x)
{
#pragma omp critical
for (int i = 0; i < D; i++)
if (x[i] < v[i]) v[i] = x[i];
return *this;
}
Vec<D,T> &max(const Vec<D,T> &x)
{
#pragma omp critical
for (int i = 0; i < D; i++)
if (x[i] > v[i]) v[i] = x[i];
return *this;
}
// Outside of class: + - * / % ^ << >>
// Some partial compatibility with valarrays and vectors
typedef T value_type;
size_t size() const
{ return D; }
T sum() const
{ T total = v[0];
for (int i = 1; i < D; i++) total += v[i];
return total; }
T avg() const
{ return sum() / D; }
T product() const
{ T total = v[0];
for (int i = 1; i < D; i++) total *= v[i];
return total; }
T min() const
{ T m = v[0];
for (int i = 1; i < D; i++)
if (v[i] < m) m = v[i];
return m; }
T max() const
{ T m = v[0];
for (int i = 1; i < D; i++)
if (v[i] > m) m = v[i];
return m; }
T *begin() { return &(v[0]); }
const T *begin() const { return &(v[0]); }
T *end() { return begin() + D; }
const T *end() const { return begin() + D; }
void clear() { for (int i = 0; i < D; i++) v[i] = T(0); }
bool empty() const
{ for (int i = 0; i < D; i++)
if (v[i]) return false;
return true; }
Vec<D,T> apply(T func(T)) const
{ Vec<D,T> result(VEC_UNINITIALIZED);
for (int i = 0; i < D; i++) result[i] = func(v[i]);
return result; }
Vec<D,T> apply(T func(const T&)) const
{ Vec<D,T> result(VEC_UNINITIALIZED);
for (int i = 0; i < D; i++) result[i] = func(v[i]);
return result; }
};
typedef Vec<3,float> vec;
typedef Vec<3,float> point;
typedef Vec<2,float> vec2;
typedef Vec<3,float> vec3;
typedef Vec<4,float> vec4;
typedef Vec<2,int> ivec2;
typedef Vec<3,int> ivec3;
typedef Vec<4,int> ivec4;
// Nonmember operators that take two Vecs
template <int D, class T>
static inline const Vec<D,T> operator + (const Vec<D,T> &v1, const Vec<D,T> &v2)
{
Vec<D,T> result(VEC_UNINITIALIZED);
for (int i = 0; i < D; i++)
result[i] = v1[i] + v2[i];
return result;
}
template <int D, class T>
static inline const Vec<D,T> operator - (const Vec<D,T> &v1, const Vec<D,T> &v2)
{
Vec<D,T> result(VEC_UNINITIALIZED);
for (int i = 0; i < D; i++)
result[i] = v1[i] - v2[i];
return result;
}
template <int D, class T>
static inline const Vec<D,T> operator * (const Vec<D,T> &v1, const Vec<D,T> &v2)
{
Vec<D,T> result(VEC_UNINITIALIZED);
for (int i = 0; i < D; i++)
result[i] = v1[i] * v2[i];
return result;
}
template <int D, class T>
static inline const Vec<D,T> operator / (const Vec<D,T> &v1, const Vec<D,T> &v2)
{
Vec<D,T> result(VEC_UNINITIALIZED);
for (int i = 0; i < D; i++)
result[i] = v1[i] / v2[i];
return result;
}
// Dot product in any dimension
template <int D, class T>
static inline const T operator ^ (const Vec<D,T> &v1, const Vec<D,T> &v2)
{
T sum = v1[0] * v2[0];
for (int i = 1; i < D; i++)
sum += v1[i] * v2[i];
return sum;
}
#define DOT ^
// Cross product - only in 3 dimensions
template <class T>
static inline const Vec<3,T> operator % (const Vec<3,T> &v1, const Vec<3,T> &v2)
{
return Vec<3,T>(v1[1]*v2[2] - v1[2]*v2[1],
v1[2]*v2[0] - v1[0]*v2[2],
v1[0]*v2[1] - v1[1]*v2[0]);
}
#define CROSS %
// Component-wise equality and inequality (#include the usual caveats
// about comparing floats for equality...)
template <int D, class T>
static inline bool operator == (const Vec<D,T> &v1, const Vec<D,T> &v2)
{
for (int i = 0; i < D; i++)
if (v1[i] != v2[i])
return false;
return true;
}
template <int D, class T>
static inline bool operator != (const Vec<D,T> &v1, const Vec<D,T> &v2)
{
for (int i = 0; i < D; i++)
if (v1[i] != v2[i])
return true;
return false;
}
// Unary operators
template <int D, class T>
static inline const Vec<D,T> &operator + (const Vec<D,T> &v)
{
return v;
}
template <int D, class T>
static inline const Vec<D,T> operator - (const Vec<D,T> &v)
{
Vec<D,T> result(VEC_UNINITIALIZED);
for (int i = 0; i < D; i++)
result[i] = -v[i];
return result;
}
template <int D, class T>
static inline bool operator ! (const Vec<D,T> &v)
{
return v.empty();
}
// Vec/scalar operators
template <int D, class T>
static inline const Vec<D,T> operator * (const T &x, const Vec<D,T> &v)
{
Vec<D,T> result(VEC_UNINITIALIZED);
for (int i = 0; i < D; i++)
result[i] = x * v[i];
return result;
}
template <int D, class T>
static inline const Vec<D,T> operator * (const Vec<D,T> &v, const T &x)
{
Vec<D,T> result(VEC_UNINITIALIZED);
for (int i = 0; i < D; i++)
result[i] = v[i] * x;
return result;
}
template <int D, class T>
static inline const Vec<D,T> operator / (const T &x, const Vec<D,T> &v)
{
Vec<D,T> result(VEC_UNINITIALIZED);
for (int i = 0; i < D; i++)
result[i] = x / v[i];
return result;
}
template <int D, class T>
static inline const Vec<D,T> operator / (const Vec<D,T> &v, const T &x)
{
Vec<D,T> result(VEC_UNINITIALIZED);
for (int i = 0; i < D; i++)
result[i] = v[i] / x;
return result;
}
// iostream operators
template <int D, class T>
static inline std::ostream &operator << (std::ostream &os, const Vec<D,T> &v)
{
os << "(";
for (int i = 0; i < D-1; i++)
os << v[i] << ", ";
return os << v[D-1] << ")";
}
template <int D, class T>
static inline std::istream &operator >> (std::istream &is, Vec<D,T> &v)
{
char c1 = 0, c2 = 0;
is >> c1;
if (c1 == '(' || c1 == '[') {
is >> v[0] >> std::ws >> c2;
for (int i = 1; i < D; i++) {
if (c2 == ',')
is >> v[i] >> std::ws >> c2;
else
is.setstate(std::ios::failbit);
}
}
if (c1 == '(' && c2 != ')')
is.setstate(std::ios::failbit);
else if (c1 == '[' && c2 != ']')
is.setstate(std::ios::failbit);
return is;
}
// Functions on Vecs
template <int D, class T>
static inline void swap(const Vec<D,T> &v1, const Vec<D,T> &v2)
{
for (int i = 0; i < D; i++)
swap(v1[i], v2[i]);
}
template <int D, class T>
static inline const T len2(const Vec<D,T> &v)
{
T l2 = v[0] * v[0];
for (int i = 1; i < D; i++)
l2 += v[i] * v[i];
return l2;
}
template <int D, class T>
static inline const T len(const Vec<D,T> &v)
{
return sqrt(len2(v));
}
template <int D, class T>
static inline const T dist2(const Vec<D,T> &v1, const Vec<D,T> &v2)
{
T d2 = sqr(v2[0]-v1[0]);
for (int i = 1; i < D; i++)
d2 += sqr(v2[i]-v1[i]);
return d2;
}
template <int D, class T>
static inline const T dist(const Vec<D,T> &v1, const Vec<D,T> &v2)
{
return sqrt(dist2(v1,v2));
}
template <int D, class T>
static inline Vec<D,T> normalize(Vec<D,T> &v)
{
T l = len(v);
if (unlikely(l <= T(0))) {
v[0] = T(1);
for (int i = 1; i < D; i++)
v[i] = T(0);
return v;
}
l = T(1) / l;
for (int i = 0; i < D; i++)
v[i] *= l;
return v;
}
// Area-weighted triangle face normal
template <class T>
static inline T trinorm(const T &v0, const T &v1, const T &v2)
{
return (typename T::value_type) 0.5 * ((v1 - v0) CROSS (v2 - v0));
}
template <class T>
static inline T cube(const T &x)
{
return x*x*x;
}
// Sign of a scalar
template <class T>
static inline T sgn(const T &x)
{
return (x < T(0)) ? T(-1) : T(1);
}
// Utility functions based on GLSL
template <class T>
static inline T fract(const T &x)
{
return x - floor(x);
}
template <class T>
static inline T clamp(const T &x, const T &a, const T &b)
{
return x > a ? x < b ? x : b : a; // returns a on NaN
}
template <class T, class S>
static inline T mix(const T &x, const T &y, const S &a)
{
return (S(1)-a) * x + a * y;
}
template <class T>
static inline T step(const T &x, const T &a)
{
return x < a ? T(0) : T(1);
}
template <class T>
static inline T smoothstep(const T &x, const T &a, const T &b)
{
if (b <= a) return step(x,a);
T t = (x - a) / (b - a);
return t <= T(0) ? T(0) : t >= T(1) ? T(1) : t * t * (T(3) - T(2) * t);
}
template <int D, class T>
static inline T faceforward(const Vec<D,T> &N, const Vec<D,T> &I,
const Vec<D,T> &Nref)
{
return ((Nref DOT I) < T(0)) ? N : -N;
}
template <int D, class T>
static inline T reflect(const Vec<D,T> &I, const Vec<D,T> &N)
{
return I - (T(2) * (N DOT I)) * N;
}
template <int D, class T>
static inline T refract(const Vec<D,T> &I, const Vec<D,T> &N,
const T &eta)
{
T NdotI = N DOT I;
T k = T(1) - sqr(eta) * (T(1) - sqr(NdotI));
return (k < T(0)) ? T(0) : eta * I - (eta * NdotI * sqrt(k)) * N;
}
// Generic macros for declaring 1-, 2-, and 3- argument
// componentwise functions on vecs
#define VEC_DECLARE_ONEARG(name) \
template <int D, class T> \
static inline Vec<D,T> name(const Vec<D,T> &v) \
{ \
Vec<D,T> result(VEC_UNINITIALIZED); \
for (int i = 0; i < D; i++) \
result[i] = name(v[i]); \
return result; \
}
#define VEC_DECLARE_TWOARG(name) \
template <int D, class T> \
static inline Vec<D,T> name(const Vec<D,T> &v, const T &w) \
{ \
Vec<D,T> result(VEC_UNINITIALIZED); \
for (int i = 0; i < D; i++) \
result[i] = name(v[i], w); \
return result; \
} \
template <int D, class T> \
static inline Vec<D,T> name(const Vec<D,T> &v, const Vec<D,T> &w) \
{ \
Vec<D,T> result(VEC_UNINITIALIZED); \
for (int i = 0; i < D; i++) \
result[i] = name(v[i], w[i]); \
return result; \
}
#define VEC_DECLARE_THREEARG(name) \
template <int D, class T> \
static inline Vec<D,T> name(const Vec<D,T> &v, const T &w, const T &x) \
{ \
Vec<D,T> result(VEC_UNINITIALIZED); \
for (int i = 0; i < D; i++) \
result[i] = name(v[i], w, x); \
return result; \
} \
template <int D, class T> \
static inline Vec<D,T> name(const Vec<D,T> &v, const Vec<D,T> &w, const Vec<D,T> &x) \
{ \
Vec<D,T> result(VEC_UNINITIALIZED); \
for (int i = 0; i < D; i++) \
result[i] = name(v[i], w[i], x[i]); \
return result; \
}
VEC_DECLARE_ONEARG(fabs)
VEC_DECLARE_ONEARG(floor)
VEC_DECLARE_ONEARG(ceil)
VEC_DECLARE_ONEARG(round)
VEC_DECLARE_ONEARG(trunc)
VEC_DECLARE_ONEARG(sin)
VEC_DECLARE_ONEARG(asin)
VEC_DECLARE_ONEARG(cos)
VEC_DECLARE_ONEARG(acos)
VEC_DECLARE_ONEARG(tan)
VEC_DECLARE_ONEARG(atan)
VEC_DECLARE_ONEARG(exp)
VEC_DECLARE_ONEARG(log)
VEC_DECLARE_ONEARG(sqrt)
VEC_DECLARE_ONEARG(sqr)
VEC_DECLARE_ONEARG(cbrt)
VEC_DECLARE_ONEARG(cube)
VEC_DECLARE_ONEARG(sgn)
VEC_DECLARE_TWOARG(min)
VEC_DECLARE_TWOARG(max)
VEC_DECLARE_TWOARG(atan2)
VEC_DECLARE_TWOARG(pow)
VEC_DECLARE_TWOARG(fmod)
VEC_DECLARE_TWOARG(step)
VEC_DECLARE_THREEARG(smoothstep)
VEC_DECLARE_THREEARG(clamp)
#undef VEC_DECLARE_ONEARG
#undef VEC_DECLARE_TWOARG
#undef VEC_DECLARE_THREEARG
// Both valarrays and GLSL use abs() on a vector to mean fabs().
// Let's be compatible...
template <int D, class T>
static inline Vec<D,T> abs(const Vec<D,T> &v)
{
return fabs(v);
}
#endif
|
private-clauseModificado3.c | #include <stdio.h>
#ifdef _OPENMP
#include <omp.h>
#else
#define omp_get_thread_num() 0
#endif
main()
{
int i, n = 7;
int a[n], suma;
for (i=0; i<n; i++)
a[i] = i;
#pragma omp parallel
{
suma=0;
#pragma omp for
for (i=0; i<n; i++)
{
suma = suma + a[i];
printf("thread %d suma a[%d] / ", omp_get_thread_num(), i);
}
printf("\n* thread %d suma= %d", omp_get_thread_num(), suma);
}
printf("\n");
}
|
host_as_target.c | // Check that specifying device as omp_get_initial_device():
// - Doesn't cause the runtime to fail.
// - Offloads code to the host.
// - Doesn't transfer data. In this case, just check that neither host data nor
// default device data are affected by the specified transfers.
// - Works whether it's specified directly or as the default device.
// RUN: %libomptarget-compile-run-and-check-generic
// amdgpu does not have a working printf definition
// XFAIL: amdgcn-amd-amdhsa
// XFAIL: amdgcn-amd-amdhsa-newRTL
#include <stdio.h>
#include <omp.h>
static void check(char *X, int Dev) {
printf(" host X = %c\n", *X);
#pragma omp target device(Dev)
printf("device X = %c\n", *X);
}
#define CHECK_DATA() check(&X, DevDefault)
int main(void) {
int DevDefault = omp_get_default_device();
int DevInit = omp_get_initial_device();
//--------------------------------------------------
// Initialize data on the host and default device.
//--------------------------------------------------
// CHECK: host X = h
// CHECK-NEXT: device X = d
char X = 'd';
#pragma omp target enter data map(to:X)
X = 'h';
CHECK_DATA();
//--------------------------------------------------
// Check behavior when specifying host directly.
//--------------------------------------------------
// CHECK-NEXT: omp_is_initial_device() = 1
// CHECK-NEXT: host X = h
// CHECK-NEXT: device X = d
#pragma omp target device(DevInit) map(always,tofrom:X)
printf("omp_is_initial_device() = %d\n", omp_is_initial_device());
CHECK_DATA();
// CHECK-NEXT: omp_is_initial_device() = 1
// CHECK-NEXT: host X = h
// CHECK-NEXT: device X = d
#pragma omp target teams device(DevInit) num_teams(1) map(always,tofrom:X)
printf("omp_is_initial_device() = %d\n", omp_is_initial_device());
CHECK_DATA();
// Check that __kmpc_push_target_tripcount_mapper doesn't fail. I'm not sure
// how to check that it actually pushes to the initial device.
#pragma omp target teams device(DevInit) num_teams(1)
#pragma omp distribute
for (int i = 0; i < 2; ++i)
;
// CHECK-NEXT: host X = h
// CHECK-NEXT: device X = d
#pragma omp target data device(DevInit) map(always,tofrom:X)
;
CHECK_DATA();
// CHECK-NEXT: host X = h
// CHECK-NEXT: device X = d
#pragma omp target enter data device(DevInit) map(always,to:X)
;
CHECK_DATA();
// CHECK-NEXT: host X = h
// CHECK-NEXT: device X = d
#pragma omp target exit data device(DevInit) map(always,from:X)
;
CHECK_DATA();
// CHECK-NEXT: host X = h
// CHECK-NEXT: device X = d
#pragma omp target update device(DevInit) to(X)
;
CHECK_DATA();
// CHECK-NEXT: host X = h
// CHECK-NEXT: device X = d
#pragma omp target update device(DevInit) from(X)
;
CHECK_DATA();
//--------------------------------------------------
// Check behavior when device defaults to host.
//--------------------------------------------------
omp_set_default_device(DevInit);
// CHECK-NEXT: omp_is_initial_device() = 1
// CHECK-NEXT: host X = h
// CHECK-NEXT: device X = d
#pragma omp target map(always,tofrom:X)
printf("omp_is_initial_device() = %d\n", omp_is_initial_device());
CHECK_DATA();
// CHECK-NEXT: omp_is_initial_device() = 1
// CHECK-NEXT: host X = h
// CHECK-NEXT: device X = d
#pragma omp target teams num_teams(1) map(always,tofrom:X)
printf("omp_is_initial_device() = %d\n", omp_is_initial_device());
CHECK_DATA();
// Check that __kmpc_push_target_tripcount_mapper doesn't fail. I'm not sure
// how to check that it actually pushes to the initial device.
#pragma omp target teams num_teams(1)
#pragma omp distribute
for (int i = 0; i < 2; ++i)
;
// CHECK-NEXT: host X = h
// CHECK-NEXT: device X = d
#pragma omp target data map(always,tofrom:X)
;
CHECK_DATA();
// CHECK-NEXT: host X = h
// CHECK-NEXT: device X = d
#pragma omp target enter data map(always,to:X)
;
CHECK_DATA();
// CHECK-NEXT: host X = h
// CHECK-NEXT: device X = d
#pragma omp target exit data map(always,from:X)
;
CHECK_DATA();
// CHECK-NEXT: host X = h
// CHECK-NEXT: device X = d
#pragma omp target update to(X)
;
CHECK_DATA();
// CHECK-NEXT: host X = h
// CHECK-NEXT: device X = d
#pragma omp target update from(X)
;
CHECK_DATA();
return 0;
}
|
matrix.c | /* Matrix multiplication example with OpenMP. Work-sharing using omp for
* and omp sections. You can play with matrix sizes to see the effects
* of parallelization.
*
* Compile either single-threaded (without OpenMP)
* gcc -Wall -o hello_omp hello_omp.c
* or multi-threaded (with OpenMP)
* gcc -Wall -fopenmp -o hello_omp hello_omp.c
*
* When you compile this program using OpenMP, by default it will create
* as many threads as there are cores in your computer. You can, however,
* set an environment variable to control the number of threads that should
* be created. To test this behavior, run
*
* export OMP_NUM_THREADS=2
* ./matrix
* unset OMP_NUM_THREADS
*
* Note: Depending on your operating system, the definition of environment
* variabled may differ from the example.
*
* Sven Reissmann <sven.reissmann@rz.hs-fulda.de>
*/
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#ifdef _OPENMP
#include <omp.h>
#endif
#define P 32
#define Q 32
#define R 32
#define PRINT 0
int main (int argc, char *argv[])
{
int tid, nthreads, chunk; /* Thread control variables */
int i, j, k; /* Loop variables */
static long int a[P][Q], /* Source matrix a */
b[Q][R], /* Source matrix b */
c[P][R]; /* Result matrix c */
time_t start_wall, end_wall; /* start/end time (wall clock) */
clock_t cpu_time; /* used cpu time */
tid = 0;
nthreads = 1;
chunk = 10;
start_wall = time (NULL);
cpu_time = clock ();
#pragma omp parallel default (none) \
shared (a, b, c, nthreads, chunk) private (tid, i, j, k)
{
#ifdef _OPENMP
tid = omp_get_thread_num ();
#endif
/* Get number of threads and print a header (only once) */
#pragma omp single
{
#ifdef _OPENMP
nthreads = omp_get_num_threads ();
#endif
printf ("Thread %d: Running with %d threads\n", tid, nthreads);
printf ("Thread %d: Initializing matrices ...\n", tid);
}
/* Initialization of source matrices using sections.
* Two threads from the team will be picked to initialize
* one of the source matrices each.
*/
#pragma omp sections
{
#pragma omp section
{
printf ("Thread %d: Initializing matrix a\n", tid);
for (i = 0; i < P; i++)
{
for (j = 0; j < Q; j++)
{
a[i][j] = i + j;
}
}
}
#pragma omp section
{
printf ("Thread %d: Initializing matrix b\n", tid);
for (i = 0; i < Q; i++)
{
for (j = 0; j < R; j++)
{
b[i][j] = i * j;
}
}
}
}
/* Matrix multiplication using for work-sharing construct.
* Work sharing happens on the outer loop only.
*/
printf ("Thread %d: Starting matrix multiplication ...\n", tid);
#pragma omp for schedule (static, chunk)
for (i = 0; i < P; i++)
{
printf ("Thread %d: Calculating row %d\n", tid, i);
for (j = 0; j < Q; j++)
{
for (k = 0; k < R; k++)
{
c[i][j] += a[i][k] * b[k][j];
}
}
}
}
end_wall = time (NULL);
cpu_time = clock () - cpu_time;
/* Print results */
#if (PRINT == 1)
printf ("Result Matrix:\n");
for (i = 0; i < P; i++)
{
for (j = 0; j < R; j++)
{
printf ("%12ld", c[i][j]);
}
printf("\n");
}
#endif
printf ("elapsed time cpu time\n"
" %6.2f s %6.2f s\n",
difftime (end_wall, start_wall),
(double) cpu_time / CLOCKS_PER_SEC);
}
|
GB_unop__lnot_int8_int8.c | //------------------------------------------------------------------------------
// GB_unop: hard-coded functions for each built-in unary operator
//------------------------------------------------------------------------------
// SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2021, All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
//------------------------------------------------------------------------------
// If this file is in the Generated/ folder, do not edit it (auto-generated).
#include "GB.h"
#ifndef GBCOMPACT
#include "GB_control.h"
#include "GB_atomics.h"
#include "GB_unop__include.h"
// C=unop(A) is defined by the following types and operators:
// op(A) function: GB_unop_apply__lnot_int8_int8
// op(A') function: GB_unop_tran__lnot_int8_int8
// C type: int8_t
// A type: int8_t
// cast: int8_t cij = aij
// unaryop: cij = !(aij != 0)
#define GB_ATYPE \
int8_t
#define GB_CTYPE \
int8_t
// 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 != 0) ;
// casting
#define GB_CAST(z, aij) \
int8_t z = aij ;
// cij = op (aij)
#define GB_CAST_OP(pC,pA) \
{ \
/* aij = Ax [pA] */ \
int8_t aij = Ax [pA] ; \
/* Cx [pC] = op (cast (aij)) */ \
int8_t z = aij ; \
Cx [pC] = !(z != 0) ; \
}
// true if operator is the identity op with no typecasting
#define GB_OP_IS_IDENTITY_WITH_NO_TYPECAST \
0
// disable this operator and use the generic case if these conditions hold
#define GB_DISABLE \
(GxB_NO_LNOT || GxB_NO_INT8)
//------------------------------------------------------------------------------
// Cx = op (cast (Ax)): apply a unary operator
//------------------------------------------------------------------------------
GrB_Info GB_unop_apply__lnot_int8_int8
(
int8_t *Cx, // Cx and Ax may be aliased
const int8_t *Ax,
const int8_t *GB_RESTRICT Ab, // A->b if A is bitmap
int64_t anz,
int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
int64_t p ;
if (Ab == NULL)
{
#if ( GB_OP_IS_IDENTITY_WITH_NO_TYPECAST )
GB_memcpy (Cx, Ax, anz * sizeof (int8_t), nthreads) ;
#else
#pragma omp parallel for num_threads(nthreads) schedule(static)
for (p = 0 ; p < anz ; p++)
{
int8_t aij = Ax [p] ;
int8_t z = aij ;
Cx [p] = !(z != 0) ;
}
#endif
}
else
{
// bitmap case, no transpose; A->b already memcpy'd into C->b
#pragma omp parallel for num_threads(nthreads) schedule(static)
for (p = 0 ; p < anz ; p++)
{
if (!Ab [p]) continue ;
int8_t aij = Ax [p] ;
int8_t z = aij ;
Cx [p] = !(z != 0) ;
}
}
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// C = op (cast (A')): transpose, typecast, and apply a unary operator
//------------------------------------------------------------------------------
GrB_Info GB_unop_tran__lnot_int8_int8
(
GrB_Matrix C,
const GrB_Matrix A,
int64_t *GB_RESTRICT *Workspaces,
const int64_t *GB_RESTRICT A_slice,
int nworkspaces,
int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
#include "GB_unop_transpose.c"
return (GrB_SUCCESS) ;
#endif
}
#endif
|
AtomicOperations.h | // Copyright (c) 2004-2022 Tomáš Oberhuber et al.
//
// This file is part of TNL - Template Numerical Library (https://tnl-project.org/)
//
// SPDX-License-Identifier: MIT
// Implemented by: Tomas Oberhuber, Jakub Klinkovsky
#pragma once
#ifdef HAVE_CUDA
#include <cuda.h>
#endif
#include <noa/3rdparty/tnl-noa/src/TNL/Devices/Sequential.h>
#include <noa/3rdparty/tnl-noa/src/TNL/Devices/Host.h>
#include <noa/3rdparty/tnl-noa/src/TNL/Devices/Cuda.h>
namespace noa::TNL {
namespace Algorithms {
template< typename Device >
struct AtomicOperations
{};
template<>
struct AtomicOperations< Devices::Host >
{
// this is __cuda_callable__ only to silence nvcc warnings (all methods inside class
// template specializations must have the same execution space specifier, otherwise
// nvcc complains)
TNL_NVCC_HD_WARNING_DISABLE
template< typename Value >
__cuda_callable__
static void
add( Value& v, const Value& a )
{
#pragma omp atomic update
v += a;
}
};
template<>
struct AtomicOperations< Devices::Sequential >
{
// this is __cuda_callable__ only to silence nvcc warnings (all methods inside class
// template specializations must have the same execution space specifier, otherwise
// nvcc complains)
TNL_NVCC_HD_WARNING_DISABLE
template< typename Value >
__cuda_callable__
static void
add( Value& v, const Value& a )
{
v += a;
}
};
template<>
struct AtomicOperations< Devices::Cuda >
{
template< typename Value >
__cuda_callable__
static void
add( Value& v, const Value& a )
{
#ifdef HAVE_CUDA
atomicAdd( &v, a );
#endif // HAVE_CUDA
}
#ifdef HAVE_CUDA
__device__
static void
add( double& v, const double& a )
{
#if __CUDA_ARCH__ < 600
unsigned long long int* v_as_ull = (unsigned long long int*) &v;
unsigned long long int old = *v_as_ull, assumed;
do {
assumed = old;
old = atomicCAS( v_as_ull, assumed, __double_as_longlong( a + __longlong_as_double( assumed ) ) );
// Note: uses integer comparison to avoid hang in case of NaN (since NaN != NaN)
} while( assumed != old );
#else // __CUDA_ARCH__ < 600
atomicAdd( &v, a );
#endif //__CUDA_ARCH__ < 600
}
#else // HAVE_CUDA
static void
add( double& v, const double& a )
{}
#endif // HAVE_CUDA
__cuda_callable__
static void
add( long int& v, const long int& a )
{
#ifdef HAVE_CUDA
TNL_ASSERT_TRUE( false, "Atomic add for long int is not supported on CUDA." );
#endif // HAVE_CUDA
}
__cuda_callable__
static void
add( short int& v, const short int& a )
{
#ifdef HAVE_CUDA
TNL_ASSERT_TRUE( false, "Atomic add for short int is not supported on CUDA." );
#endif // HAVE_CUDA
}
};
} // namespace Algorithms
} // namespace noa::TNL
|
comm.h | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
/**
* Copyright (c) 2015 by Contributors
*/
#ifndef MXNET_KVSTORE_COMM_H_
#define MXNET_KVSTORE_COMM_H_
#include <dmlc/omp.h>
#include <string>
#include <algorithm>
#include <utility>
#include <limits>
#include <vector>
#include <tuple>
#include <thread>
#include "mxnet/ndarray.h"
#include "gradient_compression.h"
#include "../ndarray/ndarray_function.h"
#include "../operator/tensor/sparse_retain-inl.h"
#include "./kvstore_utils.h"
namespace mxnet {
namespace kvstore {
/**
* \brief multiple device commmunication
*/
class Comm {
public:
Comm() {
pinned_ctx_ = Context::CPUPinned(0);
}
virtual ~Comm() { }
/**
* \brief init key with the data shape and storage shape
*/
virtual void Init(int key, const NDArrayStorageType stype,
const TShape& shape, int dtype = mshadow::kFloat32) = 0;
/**
* \brief returns src[0] + .. + src[src.size()-1]
*/
virtual const NDArray& Reduce(
int key, const std::vector<NDArray>& src, int priority) = 0;
/**
* \brief copy from src to dst[i] for every i
*/
virtual void Broadcast(
int key, const NDArray& src,
const std::vector<NDArray*> dst, int priority) = 0;
/**
* \brief broadcast src to dst[i] with target row_ids for every i
* \param key the identifier key for the stored ndarray
* \param src the source row_sparse ndarray to broadcast
* \param dst a list of destination row_sparse NDArray and its target row_ids to broadcast,
where the row_ids are expected to be unique and sorted in row_id.data()
* \param priority the priority of the operation
*/
virtual void BroadcastRowSparse(int key, const NDArray& src,
const std::vector<std::pair<NDArray*, NDArray>>& dst,
const int priority) = 0;
/**
* \brief return a pinned contex
*/
Context pinned_ctx() const {
return pinned_ctx_;
}
/**
* \brief Sets gradient compression parameters to be able to
* perform reduce with compressed gradients
*/
void SetGradientCompression(std::shared_ptr<GradientCompression> gc) {
gc_ = gc;
}
protected:
Context pinned_ctx_;
std::shared_ptr<GradientCompression> gc_;
};
/**
* \brief an implemention of Comm that first copy data to CPU memeory, and then
* reduce there
*/
class CommCPU : public Comm {
public:
CommCPU() {
nthread_reduction_ = dmlc::GetEnv("MXNET_KVSTORE_REDUCTION_NTHREADS", 4);
bigarray_bound_ = dmlc::GetEnv("MXNET_KVSTORE_BIGARRAY_BOUND", 1000 * 1000);
// TODO(junwu) delete the following data member, now for benchmark only
is_serial_push_ = dmlc::GetEnv("MXNET_KVSTORE_SERIAL_PUSH", 0);
}
virtual ~CommCPU() { }
void Init(int key, const NDArrayStorageType stype, const TShape& shape,
int type = mshadow::kFloat32) override {
if (stype == kDefaultStorage) {
merge_buf_[key].merged = NDArray(shape, pinned_ctx_, false, type);
} else {
merge_buf_[key].merged = NDArray(stype, shape, pinned_ctx_, true, type);
}
}
const NDArray& Reduce(int key, const std::vector<NDArray>& src,
int priority) override {
auto& buf = merge_buf_[key];
// avoid extra copy for single device, but it may bring problems for
// abnormal usage of kvstore
if (src.size() == 1) {
if (src[0].storage_type() == kDefaultStorage) {
return src[0];
} else { // if sparse and only one GPU, always update weight on CPU
CopyFromTo(src[0], &buf.merged, priority);
return buf.merged;
}
}
if (buf.merged.storage_type() == kDefaultStorage) {
std::vector<Engine::VarHandle> const_vars(src.size() - 1);
std::vector<NDArray> reduce(src.size());
CopyFromTo(src[0], &buf.merged, priority);
reduce[0] = buf.merged;
if (buf.copy_buf.empty()) {
buf.copy_buf.resize(src.size()-1);
for (size_t j = 0; j < src.size() - 1; ++j) {
// allocate NDArray based on storage type
buf.copy_buf[j] = NDArray(
src[0].shape(), pinned_ctx_, false, src[0].dtype());
}
}
for (size_t i = 1; i < src.size(); ++i) {
CopyFromTo(src[i], &(buf.copy_buf[i-1]), priority);
reduce[i] = buf.copy_buf[i-1];
const_vars[i-1] = reduce[i].var();
}
Engine::Get()->PushAsync(
[reduce, this](RunContext rctx, Engine::CallbackOnComplete on_complete) {
ReduceSumCPU(reduce);
on_complete();
}, Context::CPU(), const_vars, {reduce[0].var()},
FnProperty::kCPUPrioritized, priority, "KVStoreReduce");
} else {
// buf.merged is a sparse ndarray.
std::vector<Engine::VarHandle> const_vars(src.size());
std::vector<NDArray> reduce(src.size());
if (buf.copy_buf.empty()) {
buf.copy_buf.resize(src.size());
for (size_t j = 0; j < src.size(); ++j) {
buf.copy_buf[j] = NDArray(
src[0].storage_type(), src[0].shape(), pinned_ctx_, true, src[0].dtype());
}
}
for (size_t i = 0; i < src.size(); ++i) {
CopyFromTo(src[i], &(buf.copy_buf[i]), priority);
reduce[i] = buf.copy_buf[i];
const_vars[i] = reduce[i].var();
}
NDArray result = buf.merged;
Resource rsc = ResourceManager::Get()->Request(result.ctx(),
ResourceRequest(ResourceRequest::kTempSpace));
Engine::Get()->PushAsync(
[reduce, result, rsc, this](RunContext rctx, Engine::CallbackOnComplete on_complete) {
NDArray out = result;
is_serial_push_?
ReduceSumCPUExSerial(reduce, &out)
: mxnet::ndarray::ElementwiseSum(rctx.get_stream<cpu>(), rsc, reduce, &out);
on_complete();
}, Context::CPU(), const_vars, {result.var(), rsc.var},
FnProperty::kCPUPrioritized, priority, "KVStoreReduce");
}
return buf.merged;
}
void Broadcast(int key, const NDArray& src,
const std::vector<NDArray*> dst, int priority) override {
int mask = src.ctx().dev_mask();
if (mask == Context::kCPU) {
for (auto d : dst) CopyFromTo(src, d, priority);
} else {
// first copy data to cpu, then broadcast
auto& buf = merge_buf_[key];
CopyFromTo(src, &buf.merged, priority);
for (auto d : dst) CopyFromTo(buf.merged, d, priority);
}
}
void BroadcastRowSparse(int key, const NDArray& src,
const std::vector<std::pair<NDArray*, NDArray>>& dst,
const int priority) override {
using namespace mshadow;
CHECK_EQ(src.storage_type(), kRowSparseStorage)
<< "BroadcastRowSparse expects row-sparse src NDArray";
CHECK_EQ(src.ctx().dev_mask(), Context::kCPU)
<< "BroadcastRowSparse with src on gpu context not supported";
for (size_t i = 0; i < dst.size(); ++i) {
NDArray* out = dst[i].first;
NDArray row_id = dst[i].second;
CHECK_EQ(out->storage_type(), kRowSparseStorage)
<< "BroadcastRowSparse expects row_sparse dst NDArray";
CHECK_EQ(row_id.ctx().dev_mask(), Context::kCPU)
<< "BroadcastRowSparse with row_indices on gpu context not supported";
// retain according to unique indices
const bool is_same_ctx = out->ctx() == src.ctx();
const bool is_diff_var = out->var() != src.var();
NDArray retained_cpu = (is_same_ctx && is_diff_var) ? *out :
NDArray(kRowSparseStorage, src.shape(), src.ctx(), true,
src.dtype(), src.aux_types());
Engine::Get()->PushAsync(
[=](RunContext rctx, Engine::CallbackOnComplete on_complete) {
const TBlob& indices = row_id.data();
NDArray temp = retained_cpu; // get rid the of const qualifier
op::SparseRetainOpForwardRspImpl<cpu>(rctx.get_stream<cpu>(),
src, indices, kWriteTo,
&temp);
on_complete();
}, Context::CPU(), {src.var(), row_id.var()}, {retained_cpu.var()},
FnProperty::kNormal, priority, "KVStoreSparseRetain");
// if retained_cpu == out, CopyFromTo will ignore the copy operation
CopyFromTo(retained_cpu, out, priority);
}
}
private:
// reduce sum into val[0]
inline void ReduceSumCPU(const std::vector<NDArray> &in_data) {
MSHADOW_TYPE_SWITCH(in_data[0].dtype(), DType, {
std::vector<DType*> dptr(in_data.size());
for (size_t i = 0; i < in_data.size(); ++i) {
TBlob data = in_data[i].data();
CHECK(data.CheckContiguous());
dptr[i] = data.FlatTo2D<cpu, DType>().dptr_;
}
size_t total = in_data[0].shape().Size();
ReduceSumCPUImpl(dptr, total);
});
}
// serial implementation of reduce sum for row sparse NDArray.
inline void ReduceSumCPUExSerial(const std::vector<NDArray> &in, NDArray *out) {
using namespace rowsparse;
using namespace mshadow;
auto stype = out->storage_type();
CHECK_EQ(stype, kRowSparseStorage) << "Unexpected storage type " << stype;
size_t total_num_rows = 0;
size_t num_in = in.size();
// skip the ones with empty indices and values
std::vector<bool> skip(num_in, false);
// the values tensor of the inputs
MSHADOW_TYPE_SWITCH(out->dtype(), DType, {
MSHADOW_IDX_TYPE_SWITCH(out->aux_type(kIdx), IType, {
std::vector<Tensor<cpu, 2, DType>> in_vals(num_in);
std::vector<Tensor<cpu, 1, IType>> in_indices(num_in);
// offset to the values tensor of all inputs
std::vector<size_t> offsets(num_in, 0);
std::vector<size_t> num_rows(num_in, 0);
for (size_t i = 0; i < num_in; i++) {
if (!in[i].storage_initialized()) {
skip[i] = true;
continue;
}
auto size = in[i].aux_shape(kIdx).Size();
num_rows[i] = size;
total_num_rows += size;
in_vals[i] = in[i].data().FlatTo2D<cpu, DType>();
in_indices[i] = in[i].aux_data(kIdx).FlatTo1D<cpu, IType>();
}
std::vector<IType> indices;
indices.reserve(total_num_rows);
// gather indices from all inputs
for (size_t i = 0; i < num_in; i++) {
for (size_t j = 0; j < num_rows[i]; j++) {
indices.emplace_back(in_indices[i][j]);
}
}
CHECK_EQ(indices.size(), total_num_rows);
// dedup indices
std::sort(indices.begin(), indices.end());
indices.resize(std::unique(indices.begin(), indices.end()) - indices.begin());
// the one left are unique non-zero rows
size_t nnr = indices.size();
// allocate memory for output
out->CheckAndAlloc({Shape1(nnr)});
auto idx_data = out->aux_data(kIdx).FlatTo1D<cpu, IType>();
auto val_data = out->data().FlatTo2D<cpu, DType>();
for (size_t i = 0; i < nnr; i++) {
// copy indices back
idx_data[i] = indices[i];
bool zeros = true;
for (size_t j = 0; j < num_in; j++) {
if (skip[j]) continue;
size_t offset = offsets[j];
if (offset < num_rows[j]) {
if (indices[i] == in_indices[j][offset]) {
if (zeros) {
Copy(val_data[i], in_vals[j][offset], nullptr);
zeros = false;
} else {
val_data[i] += in_vals[j][offset];
}
offsets[j] += 1;
}
}
}
}
});
});
}
template<typename DType>
inline static void ReduceSumCPU(
const std::vector<DType*> &dptr, size_t offset, index_t size) {
using namespace mshadow; // NOLINT(*)
Tensor<cpu, 1, DType> in_0(dptr[0] + offset, Shape1(size));
for (size_t i = 1; i < dptr.size(); i+=4) {
switch (dptr.size() - i) {
case 1: {
Tensor<cpu, 1, DType> in_1(dptr[i] + offset, Shape1(size));
in_0 += in_1;
break;
}
case 2: {
Tensor<cpu, 1, DType> in_1(dptr[i] + offset, Shape1(size));
Tensor<cpu, 1, DType> in_2(dptr[i+1] + offset, Shape1(size));
in_0 += in_1 + in_2;
break;
}
case 3: {
Tensor<cpu, 1, DType> in_1(dptr[i] + offset, Shape1(size));
Tensor<cpu, 1, DType> in_2(dptr[i+1] + offset, Shape1(size));
Tensor<cpu, 1, DType> in_3(dptr[i+2] + offset, Shape1(size));
in_0 += in_1 + in_2 + in_3;
break;
}
default: {
Tensor<cpu, 1, DType> in_1(dptr[i] + offset, Shape1(size));
Tensor<cpu, 1, DType> in_2(dptr[i+1] + offset, Shape1(size));
Tensor<cpu, 1, DType> in_3(dptr[i+2] + offset, Shape1(size));
Tensor<cpu, 1, DType> in_4(dptr[i+3] + offset, Shape1(size));
in_0 += in_1 + in_2 + in_3 + in_4;
break;
}
}
}
}
template<typename DType>
inline void ReduceSumCPUImpl(std::vector<DType*> dptr, size_t total) {
const size_t step = std::min(bigarray_bound_, static_cast<size_t>(4 << 10));
long ntask = (total + step - 1) / step; // NOLINT(*)
if (total < bigarray_bound_ || nthread_reduction_ <= 1) {
ReduceSumCPU(dptr, 0, total);
} else {
#pragma omp parallel for schedule(static) num_threads(nthread_reduction_)
for (long j = 0; j < ntask; ++j) { // NOLINT(*)
size_t k = static_cast<size_t>(j);
size_t begin = std::min(k * step, total);
size_t end = std::min((k + 1) * step, total);
if (j == ntask - 1) CHECK_EQ(end, total);
ReduceSumCPU(dptr, begin, static_cast<index_t>(end - begin));
}
}
}
/// \brief temporal space for pushing and pulling
struct BufferEntry {
/// \brief the merged value
NDArray merged;
/// \brief the cpu buffer for gpu data
std::vector<NDArray> copy_buf;
};
std::unordered_map<int, BufferEntry> merge_buf_;
size_t bigarray_bound_;
int nthread_reduction_;
bool is_serial_push_;
};
/**
* \brief an implementation of Comm that performs reduction on device
* directly.
*
* It is faster if the total device-to-device bandwidths is larger than
* device-to-cpu, which is often true for 4 or 8 GPUs. But it uses more device
* memory.
*/
class CommDevice : public Comm {
public:
CommDevice() {
inited_ = false;
}
virtual ~CommDevice() { }
void Init(int key, const NDArrayStorageType stype, const TShape& shape,
int dtype = mshadow::kFloat32) override {
sorted_key_attrs_.emplace_back(key, shape, dtype, stype);
}
void InitBuffersAndComm(const std::vector<NDArray>& src) {
if (!inited_) {
std::vector<Context> devs;
for (const auto& a : src) {
devs.push_back(a.ctx());
}
InitMergeBuffer(devs);
if (dmlc::GetEnv("MXNET_ENABLE_GPU_P2P", 1)) {
EnableP2P(devs);
}
}
}
const NDArray& Reduce(int key, const std::vector<NDArray>& src,
int priority) override {
// when this reduce is called from kvstore_dist, gc is not set
// we don't do compression twice in dist_sync_device
if ((gc_ != nullptr) && (gc_->get_type() != CompressionType::kNone)) {
return ReduceCompressed(key, src, priority);
}
// avoid extra copy for single device, but it may bring problems for
// abnormal usage of kvstore
if (src.size() == 1) {
return src[0];
}
InitBuffersAndComm(src);
auto& buf = merge_buf_[key];
std::vector<NDArray> reduce(src.size());
const NDArrayStorageType stype = buf.merged.storage_type();
if (stype == kDefaultStorage) {
CopyFromTo(src[0], &(buf.merged), priority);
reduce[0] = buf.merged;
if (buf.copy_buf.empty()) {
// TODO(mli) this results in large device memory usage for huge ndarray,
// such as the largest fullc in VGG. consider to do segment reduce with
// NDArray.Slice or gpu direct memory access. for the latter, we need to
// remove some ctx check, and also it reduces 20% perf
buf.copy_buf.resize(src.size()-1);
for (size_t i = 0; i < src.size()-1; ++i) {
buf.copy_buf[i] = NDArray(
buf.merged.shape(), buf.merged.ctx(), false, buf.merged.dtype());
}
}
for (size_t i = 0; i < src.size()-1; ++i) {
CopyFromTo(src[i+1], &(buf.copy_buf[i]), priority);
reduce[i+1] = buf.copy_buf[i];
}
} else {
if (buf.copy_buf.empty()) {
buf.copy_buf.resize(src.size());
for (size_t j = 0; j < src.size(); ++j) {
buf.copy_buf[j] = NDArray(
buf.merged.storage_type(), buf.merged.shape(), buf.merged.ctx(),
true, buf.merged.dtype());
}
}
for (size_t i = 0; i < src.size(); ++i) {
CopyFromTo(src[i], &(buf.copy_buf[i]), priority);
reduce[i] = buf.copy_buf[i];
}
}
ElementwiseSum(reduce, &buf.merged, priority);
return buf.merged;
}
const NDArray& ReduceCompressed(int key, const std::vector<NDArray>& src,
int priority) {
InitBuffersAndComm(src);
auto& buf = merge_buf_[key];
std::vector<NDArray> reduce(src.size());
if (buf.copy_buf.empty()) {
// one buf for each context
buf.copy_buf.resize(src.size());
buf.compressed_recv_buf.resize(src.size());
buf.compressed_send_buf.resize(src.size());
buf.residual.resize(src.size());
for (size_t i = 0; i < src.size(); ++i) {
buf.copy_buf[i] = NDArray(buf.merged.shape(), buf.merged.ctx(),
false, buf.merged.dtype());
buf.residual[i] = NDArray(buf.merged.shape(), src[i].ctx(),
false, buf.merged.dtype());
buf.residual[i] = 0;
int64_t small_size = gc_->GetCompressedSize(buf.merged.shape().Size());
buf.compressed_recv_buf[i] = NDArray(TShape{small_size}, buf.merged.ctx(),
false, buf.merged.dtype());
buf.compressed_send_buf[i] = NDArray(TShape{small_size}, src[i].ctx(),
false, buf.merged.dtype());
}
}
for (size_t i = 0; i < src.size(); ++i) {
// compress before copy
// this is done even if the data is on same context as copy_buf because
// we don't want the training to be biased towards data on this GPU
gc_->Quantize(src[i], &(buf.compressed_send_buf[i]), &(buf.residual[i]), priority);
if (buf.compressed_send_buf[i].ctx() != buf.compressed_recv_buf[i].ctx()) {
CopyFromTo(buf.compressed_send_buf[i], &(buf.compressed_recv_buf[i]), priority);
} else {
// avoid memory copy when they are on same context
buf.compressed_recv_buf[i] = buf.compressed_send_buf[i];
}
gc_->Dequantize(buf.compressed_recv_buf[i], &(buf.copy_buf[i]), priority);
reduce[i] = buf.copy_buf[i];
}
ElementwiseSum(reduce, &buf.merged);
return buf.merged;
}
void Broadcast(int key, const NDArray& src,
const std::vector<NDArray*> dst, int priority) override {
if (!inited_) {
// copy to a random device first
int dev_id = key % dst.size();
CopyFromTo(src, dst[dev_id], priority);
for (size_t i = 0; i < dst.size(); ++i) {
if (i != static_cast<size_t>(dev_id)) {
CopyFromTo(*dst[dev_id], dst[i], priority);
}
}
} else {
auto& buf = merge_buf_[key];
CopyFromTo(src, &buf.merged, priority);
for (auto d : dst) {
CopyFromTo(buf.merged, d, priority);
}
}
}
void BroadcastRowSparse(int key, const NDArray& src,
const std::vector<std::pair<NDArray*, NDArray>>& dst,
const int priority) override {
CHECK_EQ(src.storage_type(), kRowSparseStorage)
<< "BroadcastRowSparse expects row-sparse src NDArray";
for (size_t i = 0; i < dst.size(); ++i) {
NDArray* out = dst[i].first;
NDArray row_id = dst[i].second;
CHECK_EQ(out->storage_type(), kRowSparseStorage)
<< "BroadcastRowSparse expects row_sparse dst NDArray";
CHECK_EQ(row_id.ctx(), src.ctx())
<< "row_id and src are expected to be on the same context";
// retain according to indices
const bool is_same_ctx = out->ctx() == src.ctx();
const bool is_diff_var = out->var() != src.var();
NDArray retained_gpu = (is_same_ctx && is_diff_var) ? *out :
NDArray(kRowSparseStorage, out->shape(), src.ctx(), true,
out->dtype(), out->aux_types());
Engine::Get()->PushAsync([=](RunContext rctx, Engine::CallbackOnComplete on_complete) {
const TBlob& indices = row_id.data();
using namespace mxnet::common;
NDArray temp = retained_gpu;
switch (temp.ctx().dev_mask()) {
case cpu::kDevMask: {
SparseRetainOpForwardRspWrapper<cpu>(rctx.get_stream<cpu>(),
src, indices, kWriteTo, &temp);
break;
}
#if MXNET_USE_CUDA
case gpu::kDevMask: {
SparseRetainOpForwardRspWrapper<gpu>(rctx.get_stream<gpu>(),
src, indices, kWriteTo, &temp);
// wait for GPU operations to complete
rctx.get_stream<gpu>()->Wait();
break;
}
#endif
default: LOG(FATAL) << MXNET_GPU_NOT_ENABLED_ERROR;
}
on_complete();
}, retained_gpu.ctx(), {src.var(), row_id.var()}, {retained_gpu.var()},
FnProperty::kNormal, priority, "KVStoreSparseRetain");
CopyFromTo(retained_gpu, out, priority);
}
}
private:
void EnableP2P(const std::vector<Context>& devs) {
#if MXNET_USE_CUDA
std::vector<int> gpus;
for (const auto& d : devs) {
if (d.dev_mask() == gpu::kDevMask) {
gpus.push_back(d.dev_id);
}
}
int n = static_cast<int>(gpus.size());
int enabled = 0;
std::vector<int> p2p(n*n);
for (int i = 0; i < n; ++i) {
cudaSetDevice(gpus[i]);
for (int j = 0; j < n; j++) {
int access;
cudaDeviceCanAccessPeer(&access, gpus[i], gpus[j]);
if (access) {
cudaError_t e = cudaDeviceEnablePeerAccess(gpus[j], 0);
if (e == cudaSuccess || e == cudaErrorPeerAccessAlreadyEnabled) {
++enabled;
p2p[i*n+j] = 1;
}
}
}
}
if (enabled != n*(n-1)) {
// print warning info if not fully enabled
LOG(WARNING) << "only " << enabled << " out of "
<< n*(n-1) << " GPU pairs are enabled direct access. "
<< "It may affect the performance. "
<< "You can set MXNET_ENABLE_GPU_P2P=0 to turn it off";
std::string access(n, '.');
for (int i = 0; i < n; ++i) {
for (int j = 0; j < n; ++j) {
access[j] = p2p[i*n+j] ? 'v' : '.';
}
LOG(WARNING) << access;
}
}
#endif
}
using KeyAttrs = std::tuple<int, TShape, int, NDArrayStorageType>;
// try to allocate buff on device evenly
void InitMergeBuffer(const std::vector<Context>& devs) {
std::sort(sorted_key_attrs_.begin(), sorted_key_attrs_.end(), [](
const KeyAttrs& a, const KeyAttrs& b) {
return std::get<1>(a).Size() > std::get<1>(b).Size();
});
std::unordered_map<int, std::pair<Context, size_t>> ctx_info;
for (auto d : devs) {
ctx_info[d.dev_id] = std::make_pair(d, 0);
}
for (size_t i = 0; i < sorted_key_attrs_.size(); ++i) {
const int key = std::get<0>(sorted_key_attrs_[i]);
const TShape& shape = std::get<1>(sorted_key_attrs_[i]);
const int type = std::get<2>(sorted_key_attrs_[i]);
const NDArrayStorageType stype = std::get<3>(sorted_key_attrs_[i]);
auto& buf = merge_buf_[key];
Context ctx;
size_t min_size = std::numeric_limits<size_t>::max();
for (auto it = ctx_info.begin(); it != ctx_info.end(); ++it) {
size_t size = it->second.second;
if (size <= min_size) {
ctx = it->second.first;
min_size = size;
}
}
if (stype == kDefaultStorage) {
buf.merged = NDArray(shape, ctx, false, type);
} else {
buf.merged = NDArray(stype, shape, ctx, true, type);
}
ctx_info[ctx.dev_id].second += shape.Size();
}
inited_ = true;
}
std::vector<KeyAttrs> sorted_key_attrs_;
/// \brief temporal space for pushing and pulling
struct BufferEntry {
/// \brief the merged value
NDArray merged;
/// \brief the gpu buffer
std::vector<NDArray> copy_buf;
/// \brief the residual buffer for gradient compression
std::vector<NDArray> residual;
/// \brief the small buffer for compressed data in sender
std::vector<NDArray> compressed_send_buf;
/// \brief the small buffer for compressed data in receiver
std::vector<NDArray> compressed_recv_buf;
};
std::unordered_map<int, BufferEntry> merge_buf_;
bool inited_;
};
} // namespace kvstore
} // namespace mxnet
#endif // MXNET_KVSTORE_COMM_H_
|
ConverterOSG.h | /* -*-c++-*- IfcQuery www.ifcquery.com
*
MIT License
Copyright (c) 2017 Fabian Gerold
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 <osg/CullFace>
#include <osg/Geode>
#include <osg/Hint>
#include <osg/LineWidth>
#include <osg/Material>
#include <osg/Point>
#include <osgUtil/Tessellator>
#include <ifcpp/model/BasicTypes.h>
#include <ifcpp/model/OpenMPIncludes.h>
#include <ifcpp/model/StatusCallback.h>
#include <ifcpp/IFC4/include/IfcCurtainWall.h>
#include <ifcpp/IFC4/include/IfcFeatureElementSubtraction.h>
#include <ifcpp/IFC4/include/IfcGloballyUniqueId.h>
#include <ifcpp/IFC4/include/IfcProject.h>
#include <ifcpp/IFC4/include/IfcPropertySetDefinitionSet.h>
#include <ifcpp/IFC4/include/IfcRelAggregates.h>
#include <ifcpp/IFC4/include/IfcSpace.h>
#include <ifcpp/IFC4/include/IfcWindow.h>
#include <ifcpp/geometry/GeometrySettings.h>
#include <ifcpp/geometry/SceneGraphUtils.h>
#include <ifcpp/geometry/AppearanceData.h>
#include "GeometryInputData.h"
#include "IncludeCarveHeaders.h"
#include "CSG_Adapter.h"
class ConverterOSG : public StatusCallback
{
protected:
shared_ptr<GeometrySettings> m_geom_settings;
std::map<std::string, osg::ref_ptr<osg::Switch> > m_map_entity_guid_to_switch;
std::map<int, osg::ref_ptr<osg::Switch> > m_map_representation_id_to_switch;
double m_recent_progress;
osg::ref_ptr<osg::CullFace> m_cull_back_off;
public:
ConverterOSG( shared_ptr<GeometrySettings>& geom_settings ) : m_geom_settings(geom_settings)
{
m_cull_back_off = new osg::CullFace( osg::CullFace::BACK );
}
virtual ~ConverterOSG() {}
// Map: IfcProduct ID -> scenegraph switch
std::map<std::string, osg::ref_ptr<osg::Switch> >& getMapEntityGUIDToSwitch() { return m_map_entity_guid_to_switch; }
// Map: Representation Identifier -> scenegraph switch
std::map<int, osg::ref_ptr<osg::Switch> >& getMapRepresentationToSwitch() { return m_map_representation_id_to_switch; }
void clearInputCache()
{
m_map_entity_guid_to_switch.clear();
m_map_representation_id_to_switch.clear();
}
static void drawBoundingBox( const carve::geom::aabb<3>& aabb, osg::Geometry* geom )
{
osg::ref_ptr<osg::Vec3Array> vertices = dynamic_cast<osg::Vec3Array*>( geom->getVertexArray() );
if( !vertices )
{
vertices = new osg::Vec3Array();
geom->setVertexArray( vertices );
}
const carve::geom::vector<3>& aabb_pos = aabb.pos;
const carve::geom::vector<3>& extent = aabb.extent;
const double dex = extent.x;
const double dey = extent.y;
const double dez = extent.z;
const int vert_id_offset = vertices->size();
vertices->push_back( osg::Vec3f( aabb_pos.x - dex, aabb_pos.y - dey, aabb_pos.z - dez ) );
vertices->push_back( osg::Vec3f( aabb_pos.x + dex, aabb_pos.y - dey, aabb_pos.z - dez ) );
vertices->push_back( osg::Vec3f( aabb_pos.x + dex, aabb_pos.y + dey, aabb_pos.z - dez ) );
vertices->push_back( osg::Vec3f( aabb_pos.x - dex, aabb_pos.y + dey, aabb_pos.z - dez ) );
vertices->push_back( osg::Vec3f( aabb_pos.x - dex, aabb_pos.y - dey, aabb_pos.z + dez ) );
vertices->push_back( osg::Vec3f( aabb_pos.x + dex, aabb_pos.y - dey, aabb_pos.z + dez ) );
vertices->push_back( osg::Vec3f( aabb_pos.x + dex, aabb_pos.y + dey, aabb_pos.z + dez ) );
vertices->push_back( osg::Vec3f( aabb_pos.x - dex, aabb_pos.y + dey, aabb_pos.z + dez ) );
osg::ref_ptr<osg::DrawElementsUInt> box_lines = new osg::DrawElementsUInt( GL_LINE_STRIP, 0 );
box_lines->push_back( vert_id_offset + 0 );
box_lines->push_back( vert_id_offset + 1 );
box_lines->push_back( vert_id_offset + 2 );
box_lines->push_back( vert_id_offset + 3 );
box_lines->push_back( vert_id_offset + 0 );
box_lines->push_back( vert_id_offset + 4 );
box_lines->push_back( vert_id_offset + 5 );
box_lines->push_back( vert_id_offset + 1 );
box_lines->push_back( vert_id_offset + 5 );
box_lines->push_back( vert_id_offset + 6 );
box_lines->push_back( vert_id_offset + 2 );
box_lines->push_back( vert_id_offset + 6 );
box_lines->push_back( vert_id_offset + 7 );
box_lines->push_back( vert_id_offset + 3 );
box_lines->push_back( vert_id_offset + 7 );
box_lines->push_back( vert_id_offset + 4 );
geom->addPrimitiveSet( box_lines );
osg::ref_ptr<osg::Material> mat = new osg::Material();
if( !mat ) { throw OutOfMemoryException(); }
osg::Vec4f ambientColor( 1.f, 0.2f, 0.1f, 1.f );
mat->setAmbient( osg::Material::FRONT, ambientColor );
mat->setDiffuse( osg::Material::FRONT, ambientColor );
mat->setSpecular( osg::Material::FRONT, ambientColor );
//mat->setShininess( osg::Material::FRONT, shininess );
//mat->setColorMode( osg::Material::SPECULAR );
osg::StateSet* stateset = geom->getOrCreateStateSet();
if( !stateset ) { throw OutOfMemoryException(); }
stateset->setAttribute( mat, osg::StateAttribute::ON );
stateset->setMode( GL_LIGHTING, osg::StateAttribute::OFF );
}
static void drawFace( const carve::mesh::Face<3>* face, osg::Geode* geode, bool add_color_array = false )
{
#ifdef _DEBUG
std::cout << "not triangulated" << std::endl;
#endif
std::vector<vec3> face_vertices;
face_vertices.resize( face->nVertices() );
carve::mesh::Edge<3> *e = face->edge;
const size_t num_vertices = face->nVertices();
for( size_t i = 0; i < num_vertices; ++i )
{
face_vertices[i] = e->v1()->v;
e = e->next;
}
if( num_vertices < 4 )
{
std::cout << "drawFace is meant only for num vertices > 4" << std::endl;
}
vec3* vertex_vec;
osg::ref_ptr<osg::Vec3Array> vertices = new osg::Vec3Array( num_vertices );
if( !vertices ) { throw OutOfMemoryException(); }
osg::ref_ptr<osg::DrawElementsUInt> triangles = new osg::DrawElementsUInt( osg::PrimitiveSet::POLYGON, num_vertices );
if( !triangles ) { throw OutOfMemoryException(); }
for( size_t i = 0; i < num_vertices; ++i )
{
vertex_vec = &face_vertices[num_vertices - i - 1];
( *vertices )[i].set( vertex_vec->x, vertex_vec->y, vertex_vec->z );
( *triangles )[i] = i;
}
osg::Vec3f poly_normal = SceneGraphUtils::computePolygonNormal( vertices );
osg::ref_ptr<osg::Vec3Array> normals = new osg::Vec3Array();
normals->resize( num_vertices, poly_normal );
osg::ref_ptr<osg::Geometry> geometry = new osg::Geometry();
geometry->setVertexArray( vertices );
geometry->setNormalArray( normals );
normals->setBinding( osg::Array::BIND_PER_VERTEX );
geometry->addPrimitiveSet( new osg::DrawArrays( osg::PrimitiveSet::POLYGON, 0, vertices->size() ) );
if( add_color_array )
{
osg::ref_ptr<osg::Vec4Array> colors = new osg::Vec4Array();
colors->resize( vertices->size(), osg::Vec4f( 0.6f, 0.6f, 0.6f, 0.1f ) );
colors->setBinding( osg::Array::BIND_PER_VERTEX );
geometry->setColorArray( colors );
}
if( num_vertices > 4 )
{
// TODO: check if polygon is convex with Gift wrapping algorithm
osg::ref_ptr<osgUtil::Tessellator> tesselator = new osgUtil::Tessellator();
tesselator->setTessellationType( osgUtil::Tessellator::TESS_TYPE_POLYGONS );
//tesselator->setWindingType( osgUtil::Tessellator::TESS_WINDING_ODD );
tesselator->retessellatePolygons( *geometry );
}
geode->addDrawable( geometry );
#ifdef DEBUG_DRAW_NORMALS
osg::ref_ptr<osg::Vec3Array> vertices_normals = new osg::Vec3Array();
for( size_t i = 0; i < num_vertices; ++i )
{
vertex_vec = &face_vertices[num_vertices - i - 1];
vertices_normals->push_back( osg::Vec3f( vertex_vec->x, vertex_vec->y, vertex_vec->z ) );
vertices_normals->push_back( osg::Vec3f( vertex_vec->x, vertex_vec->y, vertex_vec->z ) + poly_normal );
}
osg::ref_ptr<osg::Vec4Array> colors_normals = new osg::Vec4Array();
colors_normals->resize( num_vertices * 2, osg::Vec4f( 0.4f, 0.7f, 0.4f, 1.f ) );
osg::ref_ptr<osg::Geometry> geometry_normals = new osg::Geometry();
geometry_normals->setVertexArray( vertices_normals );
geometry_normals->setColorArray( colors_normals );
geometry_normals->setColorBinding( osg::Geometry::BIND_PER_VERTEX );
geometry_normals->getOrCreateStateSet()->setMode( GL_LIGHTING, osg::StateAttribute::OFF );
geometry_normals->setNormalBinding( osg::Geometry::BIND_OFF );
geometry_normals->addPrimitiveSet( new osg::DrawArrays( osg::PrimitiveSet::LINES, 0, vertices_normals->size() ) );
geode->addDrawable( geometry_normals );
#endif
}
//#define DEBUG_DRAW_NORMALS
static void drawMeshSet( const shared_ptr<carve::mesh::MeshSet<3> >& meshset, osg::Geode* geode, double crease_angle, double min_triangle_area, bool add_color_array = false )
{
if( !meshset )
{
return;
}
osg::ref_ptr<osg::Vec3Array> vertices_tri = new osg::Vec3Array();
if( !vertices_tri ) { throw OutOfMemoryException(); }
osg::ref_ptr<osg::Vec3Array> normals_tri = new osg::Vec3Array();
if( !normals_tri ) { throw OutOfMemoryException(); }
osg::ref_ptr<osg::Vec3Array> vertices_quad;
osg::ref_ptr<osg::Vec3Array> normals_quad;
const size_t max_num_faces_per_vertex = 10000;
std::map<carve::mesh::Face<3>*, double> map_face_area;
std::map<carve::mesh::Face<3>*, double>::iterator it_face_area;
if( crease_angle > 0 )
{
for( size_t i_mesh = 0; i_mesh < meshset->meshes.size(); ++i_mesh )
{
const carve::mesh::Mesh<3>* mesh = meshset->meshes[i_mesh];
const size_t num_faces = mesh->faces.size();
for( size_t i_face = 0; i_face != num_faces; ++i_face )
{
carve::mesh::Face<3>* face = mesh->faces[i_face];
// compute area of projected face:
std::vector<vec2> projected;
face->getProjectedVertices( projected );
double face_area = carve::geom2d::signedArea( projected );
map_face_area[face] = abs( face_area );
}
}
}
for( size_t i_mesh = 0; i_mesh < meshset->meshes.size(); ++i_mesh )
{
const carve::mesh::Mesh<3>* mesh = meshset->meshes[i_mesh];
const size_t num_faces = mesh->faces.size();
for( size_t i_face = 0; i_face != num_faces; ++i_face )
{
carve::mesh::Face<3>* face = mesh->faces[i_face];
const size_t n_vertices = face->nVertices();
if( n_vertices > 4 )
{
drawFace( face, geode );
continue;
}
const vec3 face_normal = face->plane.N;
if( crease_angle > 0 )
{
carve::mesh::Edge<3>* e = face->edge;
for( size_t jj = 0; jj < n_vertices; ++jj )
{
carve::mesh::Vertex<3>* vertex = e->vert;
vec3 intermediate_normal;
// collect all faces at vertex
// | ^
// | |
// f1 e->rev | | e face
// v |
// <---e1------- <---------------
//-------------> --------------->
// | ^
// | |
// v |
carve::mesh::Edge<3>* e1 = e;// ->rev->next;
carve::mesh::Face<3>* f1 = e1->face;
#ifdef _DEBUG
if( f1 != face )
{
std::cout << "f1 != face" << std::endl;
}
#endif
for( size_t i3 = 0; i3 < max_num_faces_per_vertex; ++i3 )
{
if( !e1->rev )
{
break;
}
if( !e1->rev->next )
{
break;
}
vec3 f1_normal = f1->plane.N;
const double cos_angle = dot( f1_normal, face_normal );
if( cos_angle > 0 )
{
const double deviation = std::abs( cos_angle - 1.0 );
if( deviation < crease_angle )
{
double weight = 0.0;
it_face_area = map_face_area.find( f1 );
if( it_face_area != map_face_area.end() )
{
weight = it_face_area->second;
}
intermediate_normal += weight*f1_normal;
}
}
if( !e1->rev )
{
// it's an open mesh
break;
}
e1 = e1->rev->next;
if( !e1 )
{
break;
}
f1 = e1->face;
#ifdef _DEBUG
if( e1->vert != vertex )
{
std::cout << "e1->vert != vertex" << std::endl;
}
#endif
if( f1 == face )
{
break;
}
}
const double intermediate_normal_length = intermediate_normal.length();
if( intermediate_normal_length < 0.0000000001 )
{
intermediate_normal = face_normal;
}
else
{
// normalize:
intermediate_normal *= 1.0 / intermediate_normal_length;
}
const vec3& vertex_v = vertex->v;
if( face->n_edges == 3 )
{
const carve::mesh::Edge<3>* edge0 = face->edge;
const carve::mesh::Edge<3>* edge1 = edge0->next;
const carve::mesh::Edge<3>* edge2 = edge1->next;
const carve::mesh::Vertex<3>* v0 = edge0->vert;
const carve::mesh::Vertex<3>* v1 = edge1->vert;
const carve::mesh::Vertex<3>* v2 = edge2->vert;
vec3 vert0 = v0->v;
vec3 vert1 = v1->v;
vec3 vert2 = v2->v;
vec3 v0v1 = vert1 - vert0;
vec3 v0v2 = vert2 - vert0;
double area = (carve::geom::cross(v0v1, v0v2).length())*0.5;
if (abs(area) > min_triangle_area) // skip degenerated triangle
{
vertices_tri->push_back(osg::Vec3(vertex_v.x, vertex_v.y, vertex_v.z));
normals_tri->push_back(osg::Vec3(intermediate_normal.x, intermediate_normal.y, intermediate_normal.z));
}
}
else if( face->n_edges == 4 )
{
if( !vertices_quad ) vertices_quad = new osg::Vec3Array();
vertices_quad->push_back( osg::Vec3( vertex_v.x, vertex_v.y, vertex_v.z ) );
if( !normals_quad ) normals_quad = new osg::Vec3Array();
normals_quad->push_back( osg::Vec3( intermediate_normal.x, intermediate_normal.y, intermediate_normal.z ) );
}
e = e->next;
}
}
else
{
carve::mesh::Edge<3>* e = face->edge;
for( size_t jj = 0; jj < n_vertices; ++jj )
{
carve::mesh::Vertex<3>* vertex = e->vert;
const vec3& vertex_v = vertex->v;
if( face->n_edges == 3 )
{
const carve::mesh::Edge<3>* edge0 = face->edge;
const carve::mesh::Edge<3>* edge1 = edge0->next;
const carve::mesh::Edge<3>* edge2 = edge1->next;
const carve::mesh::Vertex<3>* v0 = edge0->vert;
const carve::mesh::Vertex<3>* v1 = edge1->vert;
const carve::mesh::Vertex<3>* v2 = edge2->vert;
vec3 vert0 = v0->v;
vec3 vert1 = v1->v;
vec3 vert2 = v2->v;
vec3 v0v1 = vert1 - vert0;
vec3 v0v2 = vert2 - vert0;
double area = (carve::geom::cross(v0v1, v0v2).length())*0.5;
if (abs(area) > min_triangle_area) // skip degenerated triangle
{
vertices_tri->push_back(osg::Vec3(vertex_v.x, vertex_v.y, vertex_v.z));
normals_tri->push_back(osg::Vec3(face_normal.x, face_normal.y, face_normal.z));
}
}
else if( face->n_edges == 4 )
{
if( !vertices_quad ) vertices_quad = new osg::Vec3Array();
vertices_quad->push_back( osg::Vec3( vertex_v.x, vertex_v.y, vertex_v.z ) );
if( !normals_quad ) normals_quad = new osg::Vec3Array();
normals_quad->push_back( osg::Vec3( face_normal.x, face_normal.y, face_normal.z ) );
}
e = e->next;
}
}
}
}
if( vertices_tri->size() > 0 )
{
osg::ref_ptr<osg::Geometry> geometry = new osg::Geometry();
if( !geometry ) { throw OutOfMemoryException(); }
geometry->setVertexArray( vertices_tri );
geometry->setNormalArray( normals_tri );
normals_tri->setBinding( osg::Array::BIND_PER_VERTEX );
if( add_color_array )
{
osg::ref_ptr<osg::Vec4Array> colors = new osg::Vec4Array();
if( !colors ) { throw OutOfMemoryException(); }
colors->resize( vertices_tri->size(), osg::Vec4f( 0.6f, 0.6f, 0.6f, 0.1f ) );
colors->setBinding( osg::Array::BIND_PER_VERTEX );
geometry->setColorArray( colors );
}
geometry->addPrimitiveSet( new osg::DrawArrays( osg::PrimitiveSet::TRIANGLES, 0, vertices_tri->size() ) );
if( !geometry ) { throw OutOfMemoryException(); }
geode->addDrawable( geometry );
#ifdef DEBUG_DRAW_NORMALS
osg::ref_ptr<osg::Vec3Array> vertices_normals = new osg::Vec3Array();
for( size_t i = 0; i < vertices_tri->size(); ++i )
{
osg::Vec3f& vertex_vec = vertices_tri->at( i );// [i];
osg::Vec3f& normal_vec = normals_tri->at( i );
vertices_normals->push_back( osg::Vec3f( vertex_vec.x(), vertex_vec.y(), vertex_vec.z() ) );
vertices_normals->push_back( osg::Vec3f( vertex_vec.x(), vertex_vec.y(), vertex_vec.z() ) + normal_vec );
}
osg::ref_ptr<osg::Vec4Array> colors_normals = new osg::Vec4Array();
colors_normals->resize( vertices_normals->size(), osg::Vec4f( 0.4f, 0.7f, 0.4f, 1.f ) );
osg::ref_ptr<osg::Geometry> geometry_normals = new osg::Geometry();
geometry_normals->setVertexArray( vertices_normals );
geometry_normals->setColorArray( colors_normals );
geometry_normals->setColorBinding( osg::Geometry::BIND_PER_VERTEX );
geometry_normals->getOrCreateStateSet()->setMode( GL_LIGHTING, osg::StateAttribute::OFF );
geometry_normals->setNormalBinding( osg::Geometry::BIND_OFF );
geometry_normals->addPrimitiveSet( new osg::DrawArrays( osg::PrimitiveSet::LINES, 0, vertices_normals->size() ) );
geode->addDrawable( geometry_normals );
#endif
}
if( vertices_quad )
{
if( vertices_quad->size() > 0 )
{
osg::ref_ptr<osg::Geometry> geometry = new osg::Geometry();
if( !geometry ) { throw OutOfMemoryException(); }
geometry->setVertexArray( vertices_quad );
if( normals_quad )
{
normals_quad->setBinding( osg::Array::BIND_PER_VERTEX );
geometry->setNormalArray( normals_quad );
}
if( add_color_array )
{
osg::ref_ptr<osg::Vec4Array> colors = new osg::Vec4Array();
if( !colors ) { throw OutOfMemoryException(); }
colors->resize( vertices_quad->size(), osg::Vec4f( 0.6f, 0.6f, 0.6f, 0.1f ) );
colors->setBinding( osg::Array::BIND_PER_VERTEX );
geometry->setColorArray( colors );
}
geometry->addPrimitiveSet( new osg::DrawArrays( osg::PrimitiveSet::QUADS, 0, vertices_quad->size() ) );
if( !geometry ) { throw OutOfMemoryException(); }
geode->addDrawable( geometry );
}
}
}
static void drawPolyline( const carve::input::PolylineSetData* polyline_data, osg::Geode* geode, bool add_color_array = false )
{
osg::ref_ptr<osg::Vec3Array> vertices = new osg::Vec3Array();
if( !vertices ) { throw OutOfMemoryException(); }
carve::line::PolylineSet* polyline_set = polyline_data->create( carve::input::opts() );
if( polyline_set->vertices.size() < 2 )
{
#ifdef _DEBUG
std::cout << __FUNC__ << ": polyline_set->vertices.size() < 2" << std::endl;
#endif
return;
}
for( auto it = polyline_set->lines.begin(); it != polyline_set->lines.end(); ++it )
{
const carve::line::Polyline* pline = *it;
size_t vertex_count = pline->vertexCount();
for( size_t vertex_i = 0; vertex_i < vertex_count; ++vertex_i )
{
if( vertex_i >= polyline_set->vertices.size() )
{
#ifdef _DEBUG
std::cout << __FUNC__ << ": vertex_i >= polyline_set->vertices.size()" << std::endl;
#endif
continue;
}
const carve::line::Vertex* v = pline->vertex( vertex_i );
vertices->push_back( osg::Vec3d( v->v[0], v->v[1], v->v[2] ) );
}
}
osg::ref_ptr<osg::Geometry> geometry = new osg::Geometry();
if( !geometry ) { throw OutOfMemoryException(); }
geometry->setVertexArray( vertices );
geometry->addPrimitiveSet( new osg::DrawArrays( osg::PrimitiveSet::LINE_STRIP, 0, vertices->size() ) );
if( add_color_array )
{
osg::Vec4f color( 0.6f, 0.6f, 0.6f, 0.1f );
osg::ref_ptr<osg::Vec4Array> colors = new osg::Vec4Array( vertices->size(), &color );
if( !colors ) { throw OutOfMemoryException(); }
colors->setBinding( osg::Array::BIND_PER_VERTEX );
geometry->setColorArray( colors );
}
geode->addDrawable( geometry );
}
static void computeCreaseEdgesFromMeshset( const shared_ptr<carve::mesh::MeshSet<3> >& meshset, std::vector<carve::mesh::Edge<3>* >& vec_edges_out, const double crease_angle )
{
if( !meshset )
{
return;
}
for( size_t i_mesh = 0; i_mesh < meshset->meshes.size(); ++i_mesh )
{
const carve::mesh::Mesh<3>* mesh = meshset->meshes[i_mesh];
const std::vector<carve::mesh::Edge<3>* >& vec_closed_edges = mesh->closed_edges;
for( size_t i_edge = 0; i_edge < vec_closed_edges.size(); ++i_edge )
{
carve::mesh::Edge<3>* edge = vec_closed_edges[i_edge];
if( !edge )
{
continue;
}
carve::mesh::Edge<3>* edge_reverse = edge->rev;
if( !edge_reverse )
{
continue;
}
carve::mesh::Face<3>* face = edge->face;
carve::mesh::Face<3>* face_reverse = edge_reverse->face;
const carve::geom::vector<3>& f1_normal = face->plane.N;
const carve::geom::vector<3>& f2_normal = face_reverse->plane.N;
const double cos_angle = dot( f1_normal, f2_normal );
if( cos_angle > 0 )
{
const double deviation = std::abs( cos_angle - 1.0 );
if( deviation < crease_angle )
{
continue;
}
}
// TODO: if area of face and face_reverse is equal, skip the crease edge. It could be the inside or outside of a cylinder. Check also if > 2 faces in a row have same normal angle differences
vec_edges_out.push_back( edge );
}
}
}
static void renderMeshsetCreaseEdges( const shared_ptr<carve::mesh::MeshSet<3> >& meshset, osg::Geode* target_geode, const double crease_angle, const float line_width )
{
if( !meshset )
{
return;
}
if( !target_geode )
{
return;
}
std::vector<carve::mesh::Edge<3>* > vec_crease_edges;
computeCreaseEdgesFromMeshset( meshset, vec_crease_edges, crease_angle );
if( vec_crease_edges.size() > 0 )
{
osg::ref_ptr<osg::Vec3Array> vertices = new osg::Vec3Array();
for( size_t i_edge = 0; i_edge < vec_crease_edges.size(); ++i_edge )
{
const carve::mesh::Edge<3>* edge = vec_crease_edges[i_edge];
const carve::geom::vector<3>& vertex1 = edge->v1()->v;
const carve::geom::vector<3>& vertex2 = edge->v2()->v;
vertices->push_back( osg::Vec3d( vertex1.x, vertex1.y, vertex1.z ) );
vertices->push_back( osg::Vec3d( vertex2.x, vertex2.y, vertex2.z ) );
}
osg::ref_ptr<osg::Geometry> geometry = new osg::Geometry();
geometry->setName("creaseEdges");
geometry->setVertexArray( vertices );
geometry->addPrimitiveSet( new osg::DrawArrays( osg::PrimitiveSet::LINES, 0, vertices->size() ) );
geometry->getOrCreateStateSet()->setMode( GL_LIGHTING, osg::StateAttribute::OFF );
geometry->getOrCreateStateSet()->setMode( GL_BLEND, osg::StateAttribute::ON );
geometry->getOrCreateStateSet()->setAttributeAndModes( new osg::LineWidth( line_width ), osg::StateAttribute::ON );
osg::Material* mat = new osg::Material();
mat->setDiffuse(osg::Material::FRONT, osg::Vec4f(0.3f, 0.3f, 0.35f, 0.8f));
geometry->getOrCreateStateSet()->setAttributeAndModes(mat, osg::StateAttribute::ON);
geometry->getOrCreateStateSet()->setMode( GL_LINE_SMOOTH, osg::StateAttribute::ON );
geometry->getOrCreateStateSet()->setAttributeAndModes( new osg::Hint( GL_LINE_SMOOTH_HINT, GL_NICEST ), osg::StateAttribute::ON );
geometry->getOrCreateStateSet()->setRenderBinDetails( 10, "RenderBin");
target_geode->addDrawable( geometry );
}
}
void applyAppearancesToGroup( const std::vector<shared_ptr<AppearanceData> >& vec_product_appearances, osg::Group* grp )
{
for( size_t ii = 0; ii < vec_product_appearances.size(); ++ii )
{
const shared_ptr<AppearanceData>& appearance = vec_product_appearances[ii];
if( !appearance )
{
continue;
}
if( appearance->m_apply_to_geometry_type == AppearanceData::GEOM_TYPE_SURFACE || appearance->m_apply_to_geometry_type == AppearanceData::GEOM_TYPE_ANY )
{
osg::ref_ptr<osg::StateSet> item_stateset;
convertToOSGStateSet( appearance, item_stateset );
if( item_stateset )
{
osg::StateSet* existing_item_stateset = grp->getStateSet();
if( existing_item_stateset )
{
if( existing_item_stateset != item_stateset )
{
existing_item_stateset->merge( *item_stateset );
}
}
else
{
grp->setStateSet( item_stateset );
}
}
}
else if( appearance->m_apply_to_geometry_type == AppearanceData::GEOM_TYPE_CURVE )
{
}
}
}
osg::Matrixd convertMatrixToOSG( const carve::math::Matrix& mat_in )
{
return osg::Matrixd( mat_in.m[0][0], mat_in.m[0][1], mat_in.m[0][2], mat_in.m[0][3],
mat_in.m[1][0], mat_in.m[1][1], mat_in.m[1][2], mat_in.m[1][3],
mat_in.m[2][0], mat_in.m[2][1], mat_in.m[2][2], mat_in.m[2][3],
mat_in.m[3][0], mat_in.m[3][1], mat_in.m[3][2], mat_in.m[3][3] );
}
//\brief method convertProductShapeToOSG: creates geometry objects from an IfcProduct object
// caution: when using OpenMP, this method runs in parallel threads, so every write access to member variables needs a write lock
void convertProductShapeToOSG( shared_ptr<ProductShapeData>& product_shape, std::map<int, osg::ref_ptr<osg::Switch> >& map_representation_switches )
{
if( product_shape->m_ifc_object_definition.expired() )
{
return;
}
shared_ptr<IfcObjectDefinition> ifc_object_def(product_shape->m_ifc_object_definition);
shared_ptr<IfcProduct> ifc_product = dynamic_pointer_cast<IfcProduct>(ifc_object_def);
if( !ifc_product )
{
return;
}
std::string product_guid;
if (ifc_product->m_GlobalId)
{
std::wstring_convert<std::codecvt_utf8<wchar_t>, wchar_t> converterX;
product_guid = converterX.to_bytes(ifc_product->m_GlobalId->m_value);
}
std::stringstream strs_product_switch_name;
strs_product_switch_name << product_guid << ":" << ifc_product->className() << " group";
bool draw_bounding_box = false;
double crease_angle = m_geom_settings->getCoplanarFacesMaxDeltaAngle();
double min_triangle_area = m_geom_settings->getMinTriangleArea();
std::vector<osg::ref_ptr<osg::Switch> > vec_current_switches;
// create OSG objects
std::vector<shared_ptr<RepresentationData> >& vec_product_representations = product_shape->m_vec_representations;
for( size_t ii_representation = 0; ii_representation < vec_product_representations.size(); ++ii_representation )
{
const shared_ptr<RepresentationData>& product_representation_data = vec_product_representations[ii_representation];
if( product_representation_data->m_ifc_representation.expired() )
{
continue;
}
shared_ptr<IfcRepresentation> ifc_representation( product_representation_data->m_ifc_representation );
const int representation_id = ifc_representation->m_entity_id;
osg::ref_ptr<osg::Switch> representation_switch = new osg::Switch();
#ifdef _DEBUG
std::stringstream strs_representation_name;
strs_representation_name << strs_product_switch_name.str().c_str() << ", representation " << ii_representation;
representation_switch->setName( strs_representation_name.str().c_str() );
#endif
const std::vector<shared_ptr<ItemShapeData> >& product_items = product_representation_data->m_vec_item_data;
for( size_t i_item = 0; i_item < product_items.size(); ++i_item )
{
const shared_ptr<ItemShapeData>& item_shape = product_items[i_item];
osg::ref_ptr<osg::MatrixTransform> item_group = new osg::MatrixTransform();
if( !item_group ) { throw OutOfMemoryException( __FUNC__ ); }
#ifdef _DEBUG
std::stringstream strs_item_name;
strs_item_name << strs_representation_name.str().c_str() << ", item " << i_item;
item_group->setName( strs_item_name.str().c_str() );
#endif
// create shape for open shells
for( size_t ii = 0; ii < item_shape->m_meshsets_open.size(); ++ii )
{
shared_ptr<carve::mesh::MeshSet<3> >& item_meshset = item_shape->m_meshsets_open[ii];
CSG_Adapter::retriangulateMeshSet( item_meshset );
osg::ref_ptr<osg::Geode> geode = new osg::Geode();
if( !geode ) { throw OutOfMemoryException( __FUNC__ ); }
drawMeshSet( item_meshset, geode, crease_angle, min_triangle_area );
if( m_geom_settings->getRenderCreaseEdges() )
{
renderMeshsetCreaseEdges( item_meshset, geode, m_geom_settings->getCreaseEdgesMaxDeltaAngle(), m_geom_settings->getCreaseEdgesLineWidth() );
}
// disable back face culling for open meshes
geode->getOrCreateStateSet()->setAttributeAndModes( m_cull_back_off.get(), osg::StateAttribute::OFF );
item_group->addChild( geode );
if( draw_bounding_box )
{
carve::geom::aabb<3> bbox = item_meshset->getAABB();
osg::ref_ptr<osg::Geometry> bbox_geom = new osg::Geometry();
drawBoundingBox( bbox, bbox_geom );
geode->addDrawable( bbox_geom );
}
#ifdef _DEBUG
std::stringstream strs_item_meshset_name;
strs_item_meshset_name << strs_item_name.str().c_str() << ", open meshset " << ii;
geode->setName( strs_item_meshset_name.str().c_str() );
#endif
}
// create shape for meshsets
for( size_t ii = 0; ii < item_shape->m_meshsets.size(); ++ii )
{
shared_ptr<carve::mesh::MeshSet<3> >& item_meshset = item_shape->m_meshsets[ii];
CSG_Adapter::retriangulateMeshSet( item_meshset );
osg::ref_ptr<osg::Geode> geode_meshset = new osg::Geode();
if( !geode_meshset ) { throw OutOfMemoryException( __FUNC__ ); }
drawMeshSet( item_meshset, geode_meshset, crease_angle, min_triangle_area);
item_group->addChild( geode_meshset );
if( m_geom_settings->getRenderCreaseEdges() )
{
renderMeshsetCreaseEdges( item_meshset, geode_meshset, m_geom_settings->getCreaseEdgesMaxDeltaAngle(), m_geom_settings->getCreaseEdgesLineWidth() );
}
if( draw_bounding_box )
{
carve::geom::aabb<3> bbox = item_meshset->getAABB();
osg::ref_ptr<osg::Geometry> bbox_geom = new osg::Geometry();
drawBoundingBox( bbox, bbox_geom );
geode_meshset->addDrawable( bbox_geom );
}
#ifdef _DEBUG
std::stringstream strs_item_meshset_name;
strs_item_meshset_name << strs_item_name.str().c_str() << ", meshset " << ii;
geode_meshset->setName( strs_item_meshset_name.str().c_str() );
#endif
}
// create shape for points
const std::vector<shared_ptr<carve::input::VertexData> >& vertex_points = item_shape->getVertexPoints();
for( size_t ii = 0; ii < vertex_points.size(); ++ii )
{
const shared_ptr<carve::input::VertexData>& pointset_data = vertex_points[ii];
if( pointset_data )
{
if( pointset_data->points.size() > 0 )
{
osg::ref_ptr<osg::Geode> geode = new osg::Geode();
if( !geode ) { throw OutOfMemoryException( __FUNC__ ); }
osg::ref_ptr<osg::Vec3Array> vertices = new osg::Vec3Array();
for( size_t i_pointset_point = 0; i_pointset_point < pointset_data->points.size(); ++i_pointset_point )
{
vec3& carve_point = pointset_data->points[i_pointset_point];
vertices->push_back( osg::Vec3d( carve_point.x, carve_point.y, carve_point.z ) );
}
osg::ref_ptr<osg::Geometry> geometry = new osg::Geometry();
geometry->setVertexArray( vertices );
geometry->addPrimitiveSet( new osg::DrawArrays( osg::PrimitiveSet::POINTS, 0, vertices->size() ) );
geode->getOrCreateStateSet()->setMode( GL_LIGHTING, osg::StateAttribute::OFF );
geode->getOrCreateStateSet()->setAttribute( new osg::Point( 3.0f ), osg::StateAttribute::ON );
geode->addDrawable( geometry );
geode->setCullingActive( false );
item_group->addChild( geode );
#ifdef _DEBUG
std::stringstream strs_item_meshset_name;
strs_item_meshset_name << strs_item_name.str().c_str() << ", vertex_point " << ii;
geode->setName( strs_item_meshset_name.str().c_str() );
#endif
}
}
}
// create shape for polylines
for( size_t ii = 0; ii < item_shape->m_polylines.size(); ++ii )
{
shared_ptr<carve::input::PolylineSetData>& polyline_data = item_shape->m_polylines[ii];
osg::ref_ptr<osg::Geode> geode = new osg::Geode();
if( !geode ) { throw OutOfMemoryException( __FUNC__ ); }
geode->getOrCreateStateSet()->setMode( GL_LIGHTING, osg::StateAttribute::OFF );
drawPolyline( polyline_data.get(), geode );
item_group->addChild( geode );
#ifdef _DEBUG
std::stringstream strs_item_meshset_name;
strs_item_meshset_name << strs_item_name.str().c_str() << ", polylines " << ii;
geode->setName( strs_item_meshset_name.str().c_str() );
#endif
}
if( m_geom_settings->isShowTextLiterals() )
{
for( size_t ii = 0; ii < item_shape->m_vec_text_literals.size(); ++ii )
{
shared_ptr<TextItemData>& text_data = item_shape->m_vec_text_literals[ii];
if( !text_data )
{
continue;
}
carve::math::Matrix& text_pos = text_data->m_text_position;
// TODO: handle rotation
std::string text_str;
text_str.assign( text_data->m_text.begin(), text_data->m_text.end() );
osg::Vec3 pos2( text_pos._41, text_pos._42, text_pos._43 );
osg::ref_ptr<osgText::Text> txt = new osgText::Text();
if( !txt )
{
throw OutOfMemoryException( __FUNC__ );
}
txt->setFont( "fonts/arial.ttf" );
txt->setColor( osg::Vec4f( 0, 0, 0, 1 ) );
txt->setCharacterSize( 0.1f );
txt->setAutoRotateToScreen( true );
txt->setPosition( pos2 );
txt->setText( text_str.c_str() );
txt->getOrCreateStateSet()->setMode( GL_LIGHTING, osg::StateAttribute::OFF );
osg::ref_ptr<osg::Geode> geode = new osg::Geode();
if( !geode ){ throw OutOfMemoryException( __FUNC__ ); }
geode->addDrawable( txt );
item_group->addChild( geode );
}
}
// apply statesets if there are any
if( item_shape->m_vec_item_appearances.size() > 0 )
{
applyAppearancesToGroup( item_shape->m_vec_item_appearances, item_group );
}
// If anything has been created, add it to the representation group
if( item_group->getNumChildren() > 0 )
{
#ifdef _DEBUG
if( item_group->getNumParents() > 0 )
{
std::cout << __FUNC__ << ": item_group->getNumParents() > 0" << std::endl;
}
#endif
representation_switch->addChild( item_group );
}
}
// apply statesets if there are any
if( product_representation_data->m_vec_representation_appearances.size() > 0 )
{
applyAppearancesToGroup( product_representation_data->m_vec_representation_appearances, representation_switch );
}
// If anything has been created, add it to the product group
if( representation_switch->getNumChildren() > 0 )
{
#ifdef _DEBUG
if( representation_switch->getNumParents() > 0 )
{
std::cout << __FUNC__ << ": product_representation_switch->getNumParents() > 0" << std::endl;
}
#endif
// enable transparency for certain objects
if( dynamic_pointer_cast<IfcSpace>(ifc_product) )
{
SceneGraphUtils::setMaterialAlpha(representation_switch, 0.1f, true);
}
else if( dynamic_pointer_cast<IfcCurtainWall>(ifc_product) || dynamic_pointer_cast<IfcWindow>(ifc_product) )
{
SceneGraphUtils::setMaterialAlpha( representation_switch, 0.2f, false );
}
// check if parent building element is window
if( ifc_product->m_Decomposes_inverse.size() > 0 )
{
for( size_t ii_decomposes = 0; ii_decomposes < ifc_product->m_Decomposes_inverse.size(); ++ii_decomposes )
{
const weak_ptr<IfcRelAggregates>& decomposes_weak = ifc_product->m_Decomposes_inverse[ii_decomposes];
if( decomposes_weak.expired() )
{
continue;
}
shared_ptr<IfcRelAggregates> decomposes_ptr(decomposes_weak);
shared_ptr<IfcObjectDefinition>& relating_object = decomposes_ptr->m_RelatingObject;
if( relating_object )
{
if( dynamic_pointer_cast<IfcCurtainWall>(relating_object) || dynamic_pointer_cast<IfcWindow>(relating_object) )
{
SceneGraphUtils::setMaterialAlpha(representation_switch, 0.6f, false);
}
}
}
}
map_representation_switches.insert( std::make_pair( representation_id, representation_switch ) );
vec_current_switches.push_back(representation_switch);
}
}
// TODO: if no color or material is given, set color 231/219/169 for walls, 140/140/140 for slabs
if (product_shape->m_vec_product_appearances.size() > 0)
{
for (auto representation_switch : vec_current_switches)
{
applyAppearancesToGroup(product_shape->m_vec_product_appearances, representation_switch);
}
}
}
/*\brief method convertToOSG: Creates geometry for OpenSceneGraph from given ProductShapeData.
\param[out] parent_group Group to append the geometry.
**/
void convertToOSG( const std::map<std::string, shared_ptr<ProductShapeData> >& map_shape_data, osg::ref_ptr<osg::Switch> parent_group )
{
progressTextCallback( L"Converting geometry to OpenGL format ..." );
progressValueCallback( 0, "scenegraph" );
m_map_entity_guid_to_switch.clear();
m_map_representation_id_to_switch.clear();
shared_ptr<ProductShapeData> ifc_project_data;
std::vector<shared_ptr<ProductShapeData> > vec_products;
for( auto it = map_shape_data.begin(); it != map_shape_data.end(); ++it )
{
shared_ptr<ProductShapeData> shape_data = it->second;
if( shape_data )
{
vec_products.push_back( shape_data );
}
}
// create geometry for for each IfcProduct independently, spatial structure will be resolved later
std::map<std::string, osg::ref_ptr<osg::Switch> >* map_entity_guid = &m_map_entity_guid_to_switch;
std::map<int, osg::ref_ptr<osg::Switch> >* map_representations = &m_map_representation_id_to_switch;
const int num_products = (int)vec_products.size();
#ifdef ENABLE_OPENMP
Mutex writelock_map;
Mutex writelock_ifc_project;
Mutex writelock_message_callback;
#pragma omp parallel firstprivate(num_products) shared(map_entity_guid, map_representations)
{
// time for one product may vary significantly, so schedule not so many
#pragma omp for schedule(dynamic,40)
#endif
for( int i = 0; i < num_products; ++i )
{
shared_ptr<ProductShapeData>& shape_data = vec_products[i];
weak_ptr<IfcObjectDefinition>& ifc_object_def_weak = shape_data->m_ifc_object_definition;
if( ifc_object_def_weak.expired() )
{
continue;
}
shared_ptr<IfcObjectDefinition> ifc_object_def(shape_data->m_ifc_object_definition);
shared_ptr<IfcProject> ifc_project = dynamic_pointer_cast<IfcProject>(ifc_object_def);
if (ifc_project)
{
#ifdef ENABLE_OPENMP
ScopedLock scoped_lock(writelock_ifc_project);
#endif
ifc_project_data = shape_data;
}
shared_ptr<IfcProduct> ifc_product = dynamic_pointer_cast<IfcProduct>(ifc_object_def);
if (!ifc_product)
{
continue;
}
std::stringstream thread_err;
if( dynamic_pointer_cast<IfcFeatureElementSubtraction>(ifc_product) )
{
// geometry will be created in method subtractOpenings
continue;
}
if( !ifc_product->m_Representation )
{
continue;
}
const int product_id = ifc_product->m_entity_id;
std::string product_guid;
std::map<int, osg::ref_ptr<osg::Switch> > map_representation_switches;
try
{
convertProductShapeToOSG( shape_data, map_representation_switches );
}
catch( OutOfMemoryException& e )
{
throw e;
}
catch( BuildingException& e )
{
thread_err << e.what();
}
catch( carve::exception& e )
{
thread_err << e.str();
}
catch( std::exception& e )
{
thread_err << e.what();
}
catch( ... )
{
thread_err << "undefined error, product id " << product_id;
}
if (ifc_product->m_GlobalId)
{
std::wstring_convert<std::codecvt_utf8<wchar_t>, wchar_t> converterX;
product_guid = converterX.to_bytes(ifc_product->m_GlobalId->m_value);
}
if( map_representation_switches.size() > 0 )
{
osg::ref_ptr<osg::Switch> product_switch = new osg::Switch();
osg::ref_ptr<osg::MatrixTransform> product_transform = new osg::MatrixTransform();
product_transform->setMatrix( convertMatrixToOSG( shape_data->getTransform() ) );
product_switch->addChild( product_transform );
std::stringstream strs_product_switch_name;
strs_product_switch_name << product_guid << ":" << ifc_product->className() << " group";
product_switch->setName( strs_product_switch_name.str().c_str() );
for( auto it_map = map_representation_switches.begin(); it_map != map_representation_switches.end(); ++it_map )
{
osg::ref_ptr<osg::Switch>& repres_switch = it_map->second;
product_transform->addChild( repres_switch );
}
// apply statesets if there are any
const std::vector<shared_ptr<AppearanceData> >& vec_product_appearances = shape_data->getAppearances();
if( vec_product_appearances.size() > 0 )
{
applyAppearancesToGroup( vec_product_appearances, product_switch );
}
#ifdef ENABLE_OPENMP
ScopedLock scoped_lock( writelock_map );
#endif
map_entity_guid->insert(std::make_pair(product_guid, product_switch));
map_representations->insert( map_representation_switches.begin(), map_representation_switches.end() );
}
if( thread_err.tellp() > 0 )
{
#ifdef ENABLE_OPENMP
ScopedLock scoped_lock( writelock_message_callback );
#endif
messageCallback( thread_err.str().c_str(), StatusCallback::MESSAGE_TYPE_ERROR, __FUNC__ );
}
// progress callback
double progress = (double)i / (double)num_products;
if( progress - m_recent_progress > 0.02 )
{
#ifdef ENABLE_OPENMP
if( omp_get_thread_num() == 0 )
#endif
{
// leave 10% of progress to openscenegraph internals
progressValueCallback( progress*0.9, "scenegraph" );
m_recent_progress = progress;
}
}
}
#ifdef ENABLE_OPENMP
} // implicit barrier
#endif
try
{
// now resolve spatial structure
if( ifc_project_data )
{
resolveProjectStructure( ifc_project_data, parent_group );
}
}
catch( OutOfMemoryException& e )
{
throw e;
}
catch( BuildingException& e )
{
messageCallback( e.what(), StatusCallback::MESSAGE_TYPE_ERROR, "" );
}
catch( std::exception& e )
{
messageCallback( e.what(), StatusCallback::MESSAGE_TYPE_ERROR, "" );
}
catch( ... )
{
messageCallback( "undefined error", StatusCallback::MESSAGE_TYPE_ERROR, __FUNC__ );
}
progressValueCallback( 0.9, "scenegraph" );
}
void addNodes( const std::map<std::string, shared_ptr<BuildingObject> >& map_shape_data, osg::ref_ptr<osg::Switch>& target_group )
{
// check if there are entities that are not in spatial structure
if( !target_group )
{
target_group = new osg::Switch();
}
for( auto it_product_shapes = map_shape_data.begin(); it_product_shapes != map_shape_data.end(); ++it_product_shapes )
{
std::string product_guid = it_product_shapes->first;
auto it_find = m_map_entity_guid_to_switch.find(product_guid);
if( it_find != m_map_entity_guid_to_switch.end() )
{
osg::ref_ptr<osg::Switch>& sw = it_find->second;
if( sw )
{
target_group->addChild( sw );
}
}
}
}
void resolveProjectStructure( const shared_ptr<ProductShapeData>& product_data, osg::ref_ptr<osg::Switch> group )
{
if( !product_data )
{
return;
}
if( product_data->m_ifc_object_definition.expired() )
{
return;
}
shared_ptr<IfcObjectDefinition> ifc_object_def(product_data->m_ifc_object_definition);
if (!ifc_object_def)
{
return;
}
std::string guid;
if (ifc_object_def->m_GlobalId)
{
std::wstring_convert<std::codecvt_utf8<wchar_t>, wchar_t> converterX;
guid = converterX.to_bytes(ifc_object_def->m_GlobalId->m_value);
}
if( SceneGraphUtils::inParentList(guid, group ) )
{
messageCallback( "Cycle in project structure detected", StatusCallback::MESSAGE_TYPE_ERROR, __FUNC__, ifc_object_def.get() );
return;
}
const std::vector<shared_ptr<ProductShapeData> >& vec_children = product_data->getChildren();
for( size_t ii = 0; ii < vec_children.size(); ++ii )
{
const shared_ptr<ProductShapeData>& child_product_data = vec_children[ii];
if( !child_product_data )
{
continue;
}
osg::ref_ptr<osg::Switch> group_subparts = new osg::Switch();
if( !child_product_data->m_ifc_object_definition.expired() )
{
shared_ptr<IfcObjectDefinition> child_obj_def( child_product_data->m_ifc_object_definition );
std::stringstream group_subparts_name;
group_subparts_name << guid << ":" << ifc_object_def->className();
group_subparts->setName( group_subparts_name.str().c_str() );
}
group->addChild( group_subparts );
resolveProjectStructure( child_product_data, group_subparts );
}
auto it_product_map = m_map_entity_guid_to_switch.find(guid);
if( it_product_map != m_map_entity_guid_to_switch.end() )
{
const osg::ref_ptr<osg::Switch>& product_switch = it_product_map->second;
if( product_switch )
{
group->addChild( product_switch );
}
}
else
{
if( group->getNumChildren() == 0 )
{
osg::ref_ptr<osg::Switch> product_switch = new osg::Switch();
group->addChild( product_switch );
std::stringstream switch_name;
switch_name << guid << ":" << ifc_object_def->className();
product_switch->setName( switch_name.str().c_str() );
}
m_map_entity_guid_to_switch[guid] = group;
}
}
void convertToOSGStateSet( const shared_ptr<AppearanceData>& appearence, osg::ref_ptr<osg::StateSet>& target_stateset )
{
if( !appearence )
{
return;
}
const float shininess = appearence->m_shininess;
const float transparency = appearence->m_transparency;
const bool set_transparent = appearence->m_set_transparent;
const float color_ambient_r = appearence->m_color_ambient.r();
const float color_ambient_g = appearence->m_color_ambient.g();
const float color_ambient_b = appearence->m_color_ambient.b();
const float color_ambient_a = appearence->m_color_ambient.a();
const float color_diffuse_r = appearence->m_color_diffuse.r();
const float color_diffuse_g = appearence->m_color_diffuse.g();
const float color_diffuse_b = appearence->m_color_diffuse.b();
const float color_diffuse_a = appearence->m_color_diffuse.a();
const float color_specular_r = appearence->m_color_specular.r();
const float color_specular_g = appearence->m_color_specular.g();
const float color_specular_b = appearence->m_color_specular.b();
const float color_specular_a = appearence->m_color_specular.a();
osg::Vec4f ambientColor( color_ambient_r, color_ambient_g, color_ambient_b, transparency );
osg::Vec4f diffuseColor( color_diffuse_r, color_diffuse_g, color_diffuse_b, transparency );
osg::Vec4f specularColor( color_specular_r, color_specular_g, color_specular_b, transparency );
// TODO: material caching and re-use
osg::ref_ptr<osg::Material> mat = new osg::Material();
if( !mat ){ throw OutOfMemoryException(); }
mat->setAmbient( osg::Material::FRONT, ambientColor );
mat->setDiffuse( osg::Material::FRONT, diffuseColor );
mat->setSpecular( osg::Material::FRONT, specularColor );
mat->setShininess( osg::Material::FRONT, shininess );
mat->setColorMode( osg::Material::SPECULAR );
target_stateset = new osg::StateSet();
if( !target_stateset ){ throw OutOfMemoryException(); }
target_stateset->setAttribute( mat, osg::StateAttribute::ON );
if( appearence->m_set_transparent )
{
mat->setTransparency( osg::Material::FRONT, transparency );
target_stateset->setMode( GL_BLEND, osg::StateAttribute::ON );
target_stateset->setRenderingHint( osg::StateSet::TRANSPARENT_BIN );
}
if( appearence->m_specular_exponent != 0.f )
{
//osg::ref_ptr<osgFX::SpecularHighlights> spec_highlights = new osgFX::SpecularHighlights();
//spec_highlights->setSpecularExponent( spec->m_value );
// todo: add to scenegraph
}
}
};
|
mixed_tentusscher_myo_epi_2004_S2_2.c | // Scenario 2 - Mixed-Model TenTusscher 2004 (Myocardium + Epicardium)
// (AP + max:dvdt)
#include <stdio.h>
#include "mixed_tentusscher_myo_epi_2004_S2_2.h"
GET_CELL_MODEL_DATA(init_cell_model_data)
{
if(get_initial_v)
cell_model->initial_v = INITIAL_V;
if(get_neq)
cell_model->number_of_ode_equations = NEQ;
}
SET_ODE_INITIAL_CONDITIONS_CPU(set_model_initial_conditions_cpu)
{
static bool first_call = true;
if(first_call)
{
print_to_stdout_and_file("Using mixed version of TenTusscher 2004 myocardium + epicardium CPU model\n");
first_call = false;
}
// Get the mapping array
uint32_t *mapping = NULL;
if(extra_data)
{
mapping = (uint32_t*)extra_data;
}
else
{
print_to_stderr_and_file_and_exit("You need to specify a mask function when using a mixed model!\n");
}
// Initial conditions for TenTusscher myocardium
if (mapping[sv_id] == 0)
{
// Default initial conditions
/*
sv[0] = INITIAL_V; // V; millivolt
sv[1] = 0.f; //M
sv[2] = 0.75; //H
sv[3] = 0.75f; //J
sv[4] = 0.f; //Xr1
sv[5] = 1.f; //Xr2
sv[6] = 0.f; //Xs
sv[7] = 1.f; //S
sv[8] = 0.f; //R
sv[9] = 0.f; //D
sv[10] = 1.f; //F
sv[11] = 1.f; //FCa
sv[12] = 1.f; //G
sv[13] = 0.0002; //Cai
sv[14] = 0.2f; //CaSR
sv[15] = 11.6f; //Nai
sv[16] = 138.3f; //Ki
*/
// Elnaz's steady-state initial conditions
real sv_sst[]={-86.3965119057144,0.00133824305081220,0.775463576993407,0.775278393595599,0.000179499343643571,0.483303039835057,0.00297647859235379,0.999998290403642,1.98961879737287e-08,1.93486789479597e-05,0.999599147019885,1.00646342475688,0.999975178010127,5.97703651642618e-05,0.418325344820368,10.7429775420171,138.918155900633};
for (uint32_t i = 0; i < NEQ; i++)
sv[i] = sv_sst[i];
}
// Initial conditions for TenTusscher epicardium
else
{
// Default initial conditions
/*
sv[0] = INITIAL_V; // V; millivolt
sv[1] = 0.f; //M
sv[2] = 0.75; //H
sv[3] = 0.75f; //J
sv[4] = 0.f; //Xr1
sv[5] = 1.f; //Xr2
sv[6] = 0.f; //Xs
sv[7] = 1.f; //S
sv[8] = 0.f; //R
sv[9] = 0.f; //D
sv[10] = 1.f; //F
sv[11] = 1.f; //FCa
sv[12] = 1.f; //G
sv[13] = 0.0002; //Cai
sv[14] = 0.2f; //CaSR
sv[15] = 11.6f; //Nai
sv[16] = 138.3f; //Ki
*/
// Elnaz's steady-state initial conditions
real sv_sst[]={-86.5625425078510,0.00129164511648619,0.779570574758225,0.779427091418077,0.000174878991569467,0.485030733457084,0.00294149421393105,0.999998346195388,1.93532833226023e-08,1.89250710693833e-05,0.999770305344151,1.00711648268532,0.999995670118449,4.46785769336173e-05,0.704594271439916,9.53343199663547,139.935102489521}; for (uint32_t i = 0; i < NEQ; i++)
sv[i] = sv_sst[i];
}
}
SOLVE_MODEL_ODES_CPU(solve_model_odes_cpu)
{
// Get the mapping array
uint32_t *mapping = NULL;
if(extra_data)
{
mapping = (uint32_t*)extra_data;
}
else
{
print_to_stderr_and_file_and_exit("You need to specify a mask function when using a mixed model!\n");
}
uint32_t sv_id;
int i;
#pragma omp parallel for private(sv_id)
for (i = 0; i < num_cells_to_solve; i++)
{
if(cells_to_solve)
sv_id = cells_to_solve[i];
else
sv_id = (uint32_t )i;
for (int j = 0; j < num_steps; ++j)
{
if (mapping[i] == 0)
solve_model_ode_cpu_myo(dt, sv + (sv_id * NEQ), stim_currents[i]);
else
solve_model_ode_cpu_epi(dt, sv + (sv_id * NEQ), stim_currents[i]);
}
}
}
void solve_model_ode_cpu_myo (real dt, real *sv, real stim_current)
{
real rY[NEQ], rDY[NEQ];
for(int i = 0; i < NEQ; i++)
rY[i] = sv[i];
RHS_cpu_myo(rY, rDY, stim_current, dt);
for(int i = 0; i < NEQ; i++)
sv[i] = rDY[i];
}
void RHS_cpu_myo(const real *sv, real *rDY_, real stim_current, real dt)
{
// State variables
real svolt = sv[0];
real sm = sv[1];
real sh = sv[2];
real sj = sv[3];
real sxr1 = sv[4];
real sxr2 = sv[5];
real sxs = sv[6];
real ss = sv[7];
real sr = sv[8];
real sd = sv[9];
real sf = sv[10];
real sfca = sv[11];
real sg = sv[12];
real Cai = sv[13];
real CaSR = sv[14];
real Nai = sv[15];
real Ki = sv[16];
//External concentrations
real Ko=5.4;
real Cao=2.0;
real Nao=140.0;
//Intracellular volumes
real Vc=0.016404;
real Vsr=0.001094;
//Calcium dynamics
real Bufc=0.15f;
real Kbufc=0.001f;
real Bufsr=10.f;
real Kbufsr=0.3f;
real taufca=2.f;
real taug=2.f;
real Vmaxup=0.000425f;
real Kup=0.00025f;
//Constants
const real R = 8314.472f;
const real F = 96485.3415f;
const real T =310.0f;
real RTONF =(R*T)/F;
//Cellular capacitance
real CAPACITANCE=0.185;
//Parameters for currents
//Parameters for IKr
real Gkr=0.096;
//Parameters for Iks
real pKNa=0.03;
// [!] Myocardium cell
real Gks=0.062;
//Parameters for Ik1
real GK1=5.405;
//Parameters for Ito
// [!] Myocardium cell
real Gto=0.294;
//Parameters for INa
real GNa=14.838;
//Parameters for IbNa
real GbNa=0.00029;
//Parameters for INaK
real KmK=1.0;
real KmNa=40.0;
real knak=1.362;
//Parameters for ICaL
real GCaL=0.000175;
//Parameters for IbCa
real GbCa=0.000592;
//Parameters for INaCa
real knaca=1000;
real KmNai=87.5;
real KmCa=1.38;
real ksat=0.1;
real n=0.35;
//Parameters for IpCa
real GpCa=0.825;
real KpCa=0.0005;
//Parameters for IpK;
real GpK=0.0146;
real IKr;
real IKs;
real IK1;
real Ito;
real INa;
real IbNa;
real ICaL;
real IbCa;
real INaCa;
real IpCa;
real IpK;
real INaK;
real Irel;
real Ileak;
real dNai;
real dKi;
real dCai;
real dCaSR;
real A;
// real BufferFactorc;
// real BufferFactorsr;
real SERCA;
real Caisquare;
real CaSRsquare;
real CaCurrent;
real CaSRCurrent;
real fcaold;
real gold;
real Ek;
real Ena;
real Eks;
real Eca;
real CaCSQN;
real bjsr;
real cjsr;
real CaBuf;
real bc;
real cc;
real Ak1;
real Bk1;
real rec_iK1;
real rec_ipK;
real rec_iNaK;
real AM;
real BM;
real AH_1;
real BH_1;
real AH_2;
real BH_2;
real AJ_1;
real BJ_1;
real AJ_2;
real BJ_2;
real M_INF;
real H_INF;
real J_INF;
real TAU_M;
real TAU_H;
real TAU_J;
real axr1;
real bxr1;
real axr2;
real bxr2;
real Xr1_INF;
real Xr2_INF;
real TAU_Xr1;
real TAU_Xr2;
real Axs;
real Bxs;
real Xs_INF;
real TAU_Xs;
real R_INF;
real TAU_R;
real S_INF;
real TAU_S;
real Ad;
real Bd;
real Cd;
real TAU_D;
real D_INF;
real TAU_F;
real F_INF;
real FCa_INF;
real G_INF;
real inverseVcF2=1/(2*Vc*F);
real inverseVcF=1./(Vc*F);
real Kupsquare=Kup*Kup;
// real BufcKbufc=Bufc*Kbufc;
// real Kbufcsquare=Kbufc*Kbufc;
// real Kbufc2=2*Kbufc;
// real BufsrKbufsr=Bufsr*Kbufsr;
// const real Kbufsrsquare=Kbufsr*Kbufsr;
// const real Kbufsr2=2*Kbufsr;
const real exptaufca=exp(-dt/taufca);
const real exptaug=exp(-dt/taug);
real sItot;
//Needed to compute currents
Ek=RTONF*(log((Ko/Ki)));
Ena=RTONF*(log((Nao/Nai)));
Eks=RTONF*(log((Ko+pKNa*Nao)/(Ki+pKNa*Nai)));
Eca=0.5*RTONF*(log((Cao/Cai)));
Ak1=0.1/(1.+exp(0.06*(svolt-Ek-200)));
Bk1=(3.*exp(0.0002*(svolt-Ek+100))+
exp(0.1*(svolt-Ek-10)))/(1.+exp(-0.5*(svolt-Ek)));
rec_iK1=Ak1/(Ak1+Bk1);
rec_iNaK=(1./(1.+0.1245*exp(-0.1*svolt*F/(R*T))+0.0353*exp(-svolt*F/(R*T))));
rec_ipK=1./(1.+exp((25-svolt)/5.98));
//Compute currents
INa=GNa*sm*sm*sm*sh*sj*(svolt-Ena);
ICaL=GCaL*sd*sf*sfca*4*svolt*(F*F/(R*T))*
(exp(2*svolt*F/(R*T))*Cai-0.341*Cao)/(exp(2*svolt*F/(R*T))-1.);
Ito=Gto*sr*ss*(svolt-Ek);
IKr=Gkr*sqrt(Ko/5.4)*sxr1*sxr2*(svolt-Ek);
IKs=Gks*sxs*sxs*(svolt-Eks);
IK1=GK1*rec_iK1*(svolt-Ek);
INaCa=knaca*(1./(KmNai*KmNai*KmNai+Nao*Nao*Nao))*(1./(KmCa+Cao))*
(1./(1+ksat*exp((n-1)*svolt*F/(R*T))))*
(exp(n*svolt*F/(R*T))*Nai*Nai*Nai*Cao-
exp((n-1)*svolt*F/(R*T))*Nao*Nao*Nao*Cai*2.5);
INaK=knak*(Ko/(Ko+KmK))*(Nai/(Nai+KmNa))*rec_iNaK;
IpCa=GpCa*Cai/(KpCa+Cai);
IpK=GpK*rec_ipK*(svolt-Ek);
IbNa=GbNa*(svolt-Ena);
IbCa=GbCa*(svolt-Eca);
//Determine total current
(sItot) = IKr +
IKs +
IK1 +
Ito +
INa +
IbNa +
ICaL +
IbCa +
INaK +
INaCa +
IpCa +
IpK +
stim_current;
//update concentrations
Caisquare=Cai*Cai;
CaSRsquare=CaSR*CaSR;
CaCurrent=-(ICaL+IbCa+IpCa-2.0f*INaCa)*inverseVcF2*CAPACITANCE;
A=0.016464f*CaSRsquare/(0.0625f+CaSRsquare)+0.008232f;
Irel=A*sd*sg;
Ileak=0.00008f*(CaSR-Cai);
SERCA=Vmaxup/(1.f+(Kupsquare/Caisquare));
CaSRCurrent=SERCA-Irel-Ileak;
CaCSQN=Bufsr*CaSR/(CaSR+Kbufsr);
dCaSR=dt*(Vc/Vsr)*CaSRCurrent;
bjsr=Bufsr-CaCSQN-dCaSR-CaSR+Kbufsr;
cjsr=Kbufsr*(CaCSQN+dCaSR+CaSR);
CaSR=(sqrt(bjsr*bjsr+4.*cjsr)-bjsr)/2.;
CaBuf=Bufc*Cai/(Cai+Kbufc);
dCai=dt*(CaCurrent-CaSRCurrent);
bc=Bufc-CaBuf-dCai-Cai+Kbufc;
cc=Kbufc*(CaBuf+dCai+Cai);
Cai=(sqrt(bc*bc+4*cc)-bc)/2;
dNai=-(INa+IbNa+3*INaK+3*INaCa)*inverseVcF*CAPACITANCE;
Nai+=dt*dNai;
dKi=-(stim_current+IK1+Ito+IKr+IKs-2*INaK+IpK)*inverseVcF*CAPACITANCE;
Ki+=dt*dKi;
//compute steady state values and time constants
AM=1./(1.+exp((-60.-svolt)/5.));
BM=0.1/(1.+exp((svolt+35.)/5.))+0.10/(1.+exp((svolt-50.)/200.));
TAU_M=AM*BM;
M_INF=1./((1.+exp((-56.86-svolt)/9.03))*(1.+exp((-56.86-svolt)/9.03)));
if (svolt>=-40.)
{
AH_1=0.;
BH_1=(0.77/(0.13*(1.+exp(-(svolt+10.66)/11.1))));
TAU_H= 1.0/(AH_1+BH_1);
}
else
{
AH_2=(0.057*exp(-(svolt+80.)/6.8));
BH_2=(2.7*exp(0.079*svolt)+(3.1e5)*exp(0.3485*svolt));
TAU_H=1.0/(AH_2+BH_2);
}
H_INF=1./((1.+exp((svolt+71.55)/7.43))*(1.+exp((svolt+71.55)/7.43)));
if(svolt>=-40.)
{
AJ_1=0.;
BJ_1=(0.6*exp((0.057)*svolt)/(1.+exp(-0.1*(svolt+32.))));
TAU_J= 1.0/(AJ_1+BJ_1);
}
else
{
AJ_2=(((-2.5428e4)*exp(0.2444*svolt)-(6.948e-6)*
exp(-0.04391*svolt))*(svolt+37.78)/
(1.+exp(0.311*(svolt+79.23))));
BJ_2=(0.02424*exp(-0.01052*svolt)/(1.+exp(-0.1378*(svolt+40.14))));
TAU_J= 1.0/(AJ_2+BJ_2);
}
J_INF=H_INF;
Xr1_INF=1./(1.+exp((-26.-svolt)/7.));
axr1=450./(1.+exp((-45.-svolt)/10.));
bxr1=6./(1.+exp((svolt-(-30.))/11.5));
TAU_Xr1=axr1*bxr1;
Xr2_INF=1./(1.+exp((svolt-(-88.))/24.));
axr2=3./(1.+exp((-60.-svolt)/20.));
bxr2=1.12/(1.+exp((svolt-60.)/20.));
TAU_Xr2=axr2*bxr2;
Xs_INF=1./(1.+exp((-5.-svolt)/14.));
Axs=1100./(sqrt(1.+exp((-10.-svolt)/6)));
Bxs=1./(1.+exp((svolt-60.)/20.));
TAU_Xs=Axs*Bxs;
// [!] Myocardium cell
R_INF=1./(1.+exp((20-svolt)/6.));
S_INF=1./(1.+exp((svolt+20)/5.));
TAU_R=9.5*exp(-(svolt+40.)*(svolt+40.)/1800.)+0.8;
TAU_S=85.*exp(-(svolt+45.)*(svolt+45.)/320.)+5./(1.+exp((svolt-20.)/5.))+3.;
D_INF=1./(1.+exp((-5-svolt)/7.5));
Ad=1.4/(1.+exp((-35-svolt)/13))+0.25;
Bd=1.4/(1.+exp((svolt+5)/5));
Cd=1./(1.+exp((50-svolt)/20));
TAU_D=Ad*Bd+Cd;
F_INF=1./(1.+exp((svolt+20)/7));
//TAU_F=1125*exp(-(svolt+27)*(svolt+27)/300)+80+165/(1.+exp((25-svolt)/10));
TAU_F=1125*exp(-(svolt+27)*(svolt+27)/240)+80+165/(1.+exp((25-svolt)/10)); // Updated from CellML
FCa_INF=(1./(1.+pow((Cai/0.000325),8))+
0.1/(1.+exp((Cai-0.0005)/0.0001))+
0.20/(1.+exp((Cai-0.00075)/0.0008))+
0.23 )/1.46;
if(Cai<0.00035)
G_INF=1./(1.+pow((Cai/0.00035),6));
else
G_INF=1./(1.+pow((Cai/0.00035),16));
//Update gates
rDY_[1] = M_INF-(M_INF-sm)*exp(-dt/TAU_M);
rDY_[2] = H_INF-(H_INF-sh)*exp(-dt/TAU_H);
rDY_[3] = J_INF-(J_INF-sj)*exp(-dt/TAU_J);
rDY_[4] = Xr1_INF-(Xr1_INF-sxr1)*exp(-dt/TAU_Xr1);
rDY_[5] = Xr2_INF-(Xr2_INF-sxr2)*exp(-dt/TAU_Xr2);
rDY_[6] = Xs_INF-(Xs_INF-sxs)*exp(-dt/TAU_Xs);
rDY_[7] = S_INF-(S_INF-ss)*exp(-dt/TAU_S);
rDY_[8] = R_INF-(R_INF-sr)*exp(-dt/TAU_R);
rDY_[9] = D_INF-(D_INF-sd)*exp(-dt/TAU_D);
rDY_[10] = F_INF-(F_INF-sf)*exp(-dt/TAU_F);
fcaold= sfca;
sfca = FCa_INF-(FCa_INF-sfca)*exptaufca;
if(sfca>fcaold && (svolt)>-37.0)
sfca = fcaold;
gold = sg;
sg = G_INF-(G_INF-sg)*exptaug;
if(sg>gold && (svolt)>-37.0)
sg=gold;
//update voltage
rDY_[0] = svolt + dt*(-sItot);
rDY_[11] = sfca;
rDY_[12] = sg;
rDY_[13] = Cai;
rDY_[14] = CaSR;
rDY_[15] = Nai;
rDY_[16] = Ki;
}
void solve_model_ode_cpu_epi (real dt, real *sv, real stim_current)
{
real rY[NEQ], rDY[NEQ];
for(int i = 0; i < NEQ; i++)
rY[i] = sv[i];
RHS_cpu_epi(rY, rDY, stim_current, dt);
for(int i = 0; i < NEQ; i++)
sv[i] = rDY[i];
}
void RHS_cpu_epi(const real *sv, real *rDY_, real stim_current, real dt)
{
// State variables
real svolt = sv[0];
real sm = sv[1];
real sh = sv[2];
real sj = sv[3];
real sxr1 = sv[4];
real sxr2 = sv[5];
real sxs = sv[6];
real ss = sv[7];
real sr = sv[8];
real sd = sv[9];
real sf = sv[10];
real sfca = sv[11];
real sg = sv[12];
real Cai = sv[13];
real CaSR = sv[14];
real Nai = sv[15];
real Ki = sv[16];
//External concentrations
real Ko=5.4;
real Cao=2.0;
real Nao=140.0;
//Intracellular volumes
real Vc=0.016404;
real Vsr=0.001094;
//Calcium dynamics
real Bufc=0.15f;
real Kbufc=0.001f;
real Bufsr=10.f;
real Kbufsr=0.3f;
real taufca=2.f;
real taug=2.f;
real Vmaxup=0.000425f;
real Kup=0.00025f;
//Constants
const real R = 8314.472f;
const real F = 96485.3415f;
const real T =310.0f;
real RTONF =(R*T)/F;
//Cellular capacitance
real CAPACITANCE=0.185;
//Parameters for currents
//Parameters for IKr
real Gkr=0.096;
//Parameters for Iks
real pKNa=0.03;
// [!] Epicardium cell
real Gks=0.245;
//Parameters for Ik1
real GK1=5.405;
//Parameters for Ito
// [!] Epicardium cell
real Gto=0.294;
//Parameters for INa
real GNa=14.838;
//Parameters for IbNa
real GbNa=0.00029;
//Parameters for INaK
real KmK=1.0;
real KmNa=40.0;
real knak=1.362;
//Parameters for ICaL
real GCaL=0.000175;
//Parameters for IbCa
real GbCa=0.000592;
//Parameters for INaCa
real knaca=1000;
real KmNai=87.5;
real KmCa=1.38;
real ksat=0.1;
real n=0.35;
//Parameters for IpCa
real GpCa=0.825;
real KpCa=0.0005;
//Parameters for IpK;
real GpK=0.0146;
real parameters []={13.9775467344317,0.000166600423473182,0.000157288679125758,0.000709118450301612,0.263558270150583,0.168176898499067,0.121036017649477,3.67579958026615,0.0132247972184402,2.23991491317412,1099.99539877590,0.000482074874077319,0.582903159280657,0.0176425810465345,0.00547174746535614,2.73565215234459e-05};
GNa=parameters[0];
GbNa=parameters[1];
GCaL=parameters[2];
GbCa=parameters[3];
Gto=parameters[4];
Gkr=parameters[5];
Gks=parameters[6];
GK1=parameters[7];
GpK=parameters[8];
knak=parameters[9];
knaca=parameters[10];
Vmaxup=parameters[11];
GpCa=parameters[12];
real arel=parameters[13];
real crel=parameters[14];
real Vleak=parameters[15];
real IKr;
real IKs;
real IK1;
real Ito;
real INa;
real IbNa;
real ICaL;
real IbCa;
real INaCa;
real IpCa;
real IpK;
real INaK;
real Irel;
real Ileak;
real dNai;
real dKi;
real dCai;
real dCaSR;
real A;
// real BufferFactorc;
// real BufferFactorsr;
real SERCA;
real Caisquare;
real CaSRsquare;
real CaCurrent;
real CaSRCurrent;
real fcaold;
real gold;
real Ek;
real Ena;
real Eks;
real Eca;
real CaCSQN;
real bjsr;
real cjsr;
real CaBuf;
real bc;
real cc;
real Ak1;
real Bk1;
real rec_iK1;
real rec_ipK;
real rec_iNaK;
real AM;
real BM;
real AH_1;
real BH_1;
real AH_2;
real BH_2;
real AJ_1;
real BJ_1;
real AJ_2;
real BJ_2;
real M_INF;
real H_INF;
real J_INF;
real TAU_M;
real TAU_H;
real TAU_J;
real axr1;
real bxr1;
real axr2;
real bxr2;
real Xr1_INF;
real Xr2_INF;
real TAU_Xr1;
real TAU_Xr2;
real Axs;
real Bxs;
real Xs_INF;
real TAU_Xs;
real R_INF;
real TAU_R;
real S_INF;
real TAU_S;
real Ad;
real Bd;
real Cd;
real TAU_D;
real D_INF;
real TAU_F;
real F_INF;
real FCa_INF;
real G_INF;
real inverseVcF2=1/(2*Vc*F);
real inverseVcF=1./(Vc*F);
real Kupsquare=Kup*Kup;
// real BufcKbufc=Bufc*Kbufc;
// real Kbufcsquare=Kbufc*Kbufc;
// real Kbufc2=2*Kbufc;
// real BufsrKbufsr=Bufsr*Kbufsr;
// const real Kbufsrsquare=Kbufsr*Kbufsr;
// const real Kbufsr2=2*Kbufsr;
const real exptaufca=exp(-dt/taufca);
const real exptaug=exp(-dt/taug);
real sItot;
//Needed to compute currents
Ek=RTONF*(log((Ko/Ki)));
Ena=RTONF*(log((Nao/Nai)));
Eks=RTONF*(log((Ko+pKNa*Nao)/(Ki+pKNa*Nai)));
Eca=0.5*RTONF*(log((Cao/Cai)));
Ak1=0.1/(1.+exp(0.06*(svolt-Ek-200)));
Bk1=(3.*exp(0.0002*(svolt-Ek+100))+
exp(0.1*(svolt-Ek-10)))/(1.+exp(-0.5*(svolt-Ek)));
rec_iK1=Ak1/(Ak1+Bk1);
rec_iNaK=(1./(1.+0.1245*exp(-0.1*svolt*F/(R*T))+0.0353*exp(-svolt*F/(R*T))));
rec_ipK=1./(1.+exp((25-svolt)/5.98));
//Compute currents
INa=GNa*sm*sm*sm*sh*sj*(svolt-Ena);
ICaL=GCaL*sd*sf*sfca*4*svolt*(F*F/(R*T))*
(exp(2*svolt*F/(R*T))*Cai-0.341*Cao)/(exp(2*svolt*F/(R*T))-1.);
Ito=Gto*sr*ss*(svolt-Ek);
IKr=Gkr*sqrt(Ko/5.4)*sxr1*sxr2*(svolt-Ek);
IKs=Gks*sxs*sxs*(svolt-Eks);
IK1=GK1*rec_iK1*(svolt-Ek);
INaCa=knaca*(1./(KmNai*KmNai*KmNai+Nao*Nao*Nao))*(1./(KmCa+Cao))*
(1./(1+ksat*exp((n-1)*svolt*F/(R*T))))*
(exp(n*svolt*F/(R*T))*Nai*Nai*Nai*Cao-
exp((n-1)*svolt*F/(R*T))*Nao*Nao*Nao*Cai*2.5);
INaK=knak*(Ko/(Ko+KmK))*(Nai/(Nai+KmNa))*rec_iNaK;
IpCa=GpCa*Cai/(KpCa+Cai);
IpK=GpK*rec_ipK*(svolt-Ek);
IbNa=GbNa*(svolt-Ena);
IbCa=GbCa*(svolt-Eca);
//Determine total current
(sItot) = IKr +
IKs +
IK1 +
Ito +
INa +
IbNa +
ICaL +
IbCa +
INaK +
INaCa +
IpCa +
IpK +
stim_current;
//update concentrations
Caisquare=Cai*Cai;
CaSRsquare=CaSR*CaSR;
CaCurrent=-(ICaL+IbCa+IpCa-2.0f*INaCa)*inverseVcF2*CAPACITANCE;
A=arel*CaSRsquare/(0.0625f+CaSRsquare)+crel;
Irel=A*sd*sg;
Ileak=Vleak*(CaSR-Cai);
SERCA=Vmaxup/(1.f+(Kupsquare/Caisquare));
CaSRCurrent=SERCA-Irel-Ileak;
CaCSQN=Bufsr*CaSR/(CaSR+Kbufsr);
dCaSR=dt*(Vc/Vsr)*CaSRCurrent;
bjsr=Bufsr-CaCSQN-dCaSR-CaSR+Kbufsr;
cjsr=Kbufsr*(CaCSQN+dCaSR+CaSR);
CaSR=(sqrt(bjsr*bjsr+4.*cjsr)-bjsr)/2.;
CaBuf=Bufc*Cai/(Cai+Kbufc);
dCai=dt*(CaCurrent-CaSRCurrent);
bc=Bufc-CaBuf-dCai-Cai+Kbufc;
cc=Kbufc*(CaBuf+dCai+Cai);
Cai=(sqrt(bc*bc+4*cc)-bc)/2;
dNai=-(INa+IbNa+3*INaK+3*INaCa)*inverseVcF*CAPACITANCE;
Nai+=dt*dNai;
dKi=-(stim_current+IK1+Ito+IKr+IKs-2*INaK+IpK)*inverseVcF*CAPACITANCE;
Ki+=dt*dKi;
//compute steady state values and time constants
AM=1./(1.+exp((-60.-svolt)/5.));
BM=0.1/(1.+exp((svolt+35.)/5.))+0.10/(1.+exp((svolt-50.)/200.));
TAU_M=AM*BM;
M_INF=1./((1.+exp((-56.86-svolt)/9.03))*(1.+exp((-56.86-svolt)/9.03)));
if (svolt>=-40.)
{
AH_1=0.;
BH_1=(0.77/(0.13*(1.+exp(-(svolt+10.66)/11.1))));
TAU_H= 1.0/(AH_1+BH_1);
}
else
{
AH_2=(0.057*exp(-(svolt+80.)/6.8));
BH_2=(2.7*exp(0.079*svolt)+(3.1e5)*exp(0.3485*svolt));
TAU_H=1.0/(AH_2+BH_2);
}
H_INF=1./((1.+exp((svolt+71.55)/7.43))*(1.+exp((svolt+71.55)/7.43)));
if(svolt>=-40.)
{
AJ_1=0.;
BJ_1=(0.6*exp((0.057)*svolt)/(1.+exp(-0.1*(svolt+32.))));
TAU_J= 1.0/(AJ_1+BJ_1);
}
else
{
AJ_2=(((-2.5428e4)*exp(0.2444*svolt)-(6.948e-6)*
exp(-0.04391*svolt))*(svolt+37.78)/
(1.+exp(0.311*(svolt+79.23))));
BJ_2=(0.02424*exp(-0.01052*svolt)/(1.+exp(-0.1378*(svolt+40.14))));
TAU_J= 1.0/(AJ_2+BJ_2);
}
J_INF=H_INF;
Xr1_INF=1./(1.+exp((-26.-svolt)/7.));
axr1=450./(1.+exp((-45.-svolt)/10.));
bxr1=6./(1.+exp((svolt-(-30.))/11.5));
TAU_Xr1=axr1*bxr1;
Xr2_INF=1./(1.+exp((svolt-(-88.))/24.));
axr2=3./(1.+exp((-60.-svolt)/20.));
bxr2=1.12/(1.+exp((svolt-60.)/20.));
TAU_Xr2=axr2*bxr2;
Xs_INF=1./(1.+exp((-5.-svolt)/14.));
Axs=1100./(sqrt(1.+exp((-10.-svolt)/6)));
Bxs=1./(1.+exp((svolt-60.)/20.));
TAU_Xs=Axs*Bxs;
R_INF=1./(1.+exp((20-svolt)/6.));
S_INF=1./(1.+exp((svolt+20)/5.));
TAU_R=9.5*exp(-(svolt+40.)*(svolt+40.)/1800.)+0.8;
TAU_S=85.*exp(-(svolt+45.)*(svolt+45.)/320.)+5./(1.+exp((svolt-20.)/5.))+3.;
D_INF=1./(1.+exp((-5-svolt)/7.5));
Ad=1.4/(1.+exp((-35-svolt)/13))+0.25;
Bd=1.4/(1.+exp((svolt+5)/5));
Cd=1./(1.+exp((50-svolt)/20));
TAU_D=Ad*Bd+Cd;
F_INF=1./(1.+exp((svolt+20)/7));
//TAU_F=1125*exp(-(svolt+27)*(svolt+27)/300)+80+165/(1.+exp((25-svolt)/10));
TAU_F=1125*exp(-(svolt+27)*(svolt+27)/240)+80+165/(1.+exp((25-svolt)/10)); // Updated from CellML
FCa_INF=(1./(1.+pow((Cai/0.000325),8))+
0.1/(1.+exp((Cai-0.0005)/0.0001))+
0.20/(1.+exp((Cai-0.00075)/0.0008))+
0.23 )/1.46;
if(Cai<0.00035)
G_INF=1./(1.+pow((Cai/0.00035),6));
else
G_INF=1./(1.+pow((Cai/0.00035),16));
//Update gates
rDY_[1] = M_INF-(M_INF-sm)*exp(-dt/TAU_M);
rDY_[2] = H_INF-(H_INF-sh)*exp(-dt/TAU_H);
rDY_[3] = J_INF-(J_INF-sj)*exp(-dt/TAU_J);
rDY_[4] = Xr1_INF-(Xr1_INF-sxr1)*exp(-dt/TAU_Xr1);
rDY_[5] = Xr2_INF-(Xr2_INF-sxr2)*exp(-dt/TAU_Xr2);
rDY_[6] = Xs_INF-(Xs_INF-sxs)*exp(-dt/TAU_Xs);
rDY_[7] = S_INF-(S_INF-ss)*exp(-dt/TAU_S);
rDY_[8] = R_INF-(R_INF-sr)*exp(-dt/TAU_R);
rDY_[9] = D_INF-(D_INF-sd)*exp(-dt/TAU_D);
rDY_[10] = F_INF-(F_INF-sf)*exp(-dt/TAU_F);
fcaold= sfca;
sfca = FCa_INF-(FCa_INF-sfca)*exptaufca;
if(sfca>fcaold && (svolt)>-37.0)
sfca = fcaold;
gold = sg;
sg = G_INF-(G_INF-sg)*exptaug;
if(sg>gold && (svolt)>-37.0)
sg=gold;
//update voltage
rDY_[0] = svolt + dt*(-sItot);
rDY_[11] = sfca;
rDY_[12] = sg;
rDY_[13] = Cai;
rDY_[14] = CaSR;
rDY_[15] = Nai;
rDY_[16] = Ki;
}
|
GB_unop__cosh_fc64_fc64.c | //------------------------------------------------------------------------------
// GB_unop: hard-coded functions for each built-in unary operator
//------------------------------------------------------------------------------
// SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2022, All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
//------------------------------------------------------------------------------
// If this file is in the Generated2/ folder, do not edit it
// (it is auto-generated from Generator/*).
#include "GB.h"
#ifndef GBCUDA_DEV
#include "GB_control.h"
#include "GB_atomics.h"
#include "GB_unop__include.h"
// C=unop(A) is defined by the following types and operators:
// op(A) function: GB (_unop_apply__cosh_fc64_fc64)
// op(A') function: GB (_unop_tran__cosh_fc64_fc64)
// C type: GxB_FC64_t
// A type: GxB_FC64_t
// cast: GxB_FC64_t cij = aij
// unaryop: cij = ccosh (aij)
#define GB_ATYPE \
GxB_FC64_t
#define GB_CTYPE \
GxB_FC64_t
// aij = Ax [pA]
#define GB_GETA(aij,Ax,pA) \
GxB_FC64_t aij = Ax [pA]
#define GB_CX(p) Cx [p]
// unary operator
#define GB_OP(z, x) \
z = ccosh (x) ;
// casting
#define GB_CAST(z, aij) \
GxB_FC64_t z = aij ;
// cij = op (aij)
#define GB_CAST_OP(pC,pA) \
{ \
/* aij = Ax [pA] */ \
GxB_FC64_t aij = Ax [pA] ; \
/* Cx [pC] = op (cast (aij)) */ \
GxB_FC64_t z = aij ; \
Cx [pC] = ccosh (z) ; \
}
// disable this operator and use the generic case if these conditions hold
#define GB_DISABLE \
(GxB_NO_COSH || GxB_NO_FC64)
//------------------------------------------------------------------------------
// Cx = op (cast (Ax)): apply a unary operator
//------------------------------------------------------------------------------
GrB_Info GB (_unop_apply__cosh_fc64_fc64)
(
GxB_FC64_t *Cx, // Cx and Ax may be aliased
const GxB_FC64_t *Ax,
const int8_t *restrict Ab, // A->b if A is bitmap
int64_t anz,
int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
int64_t p ;
if (Ab == NULL)
{
#pragma omp parallel for num_threads(nthreads) schedule(static)
for (p = 0 ; p < anz ; p++)
{
GxB_FC64_t aij = Ax [p] ;
GxB_FC64_t z = aij ;
Cx [p] = ccosh (z) ;
}
}
else
{
// bitmap case, no transpose; A->b already memcpy'd into C->b
#pragma omp parallel for num_threads(nthreads) schedule(static)
for (p = 0 ; p < anz ; p++)
{
if (!Ab [p]) continue ;
GxB_FC64_t aij = Ax [p] ;
GxB_FC64_t z = aij ;
Cx [p] = ccosh (z) ;
}
}
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// C = op (cast (A')): transpose, typecast, and apply a unary operator
//------------------------------------------------------------------------------
GrB_Info GB (_unop_tran__cosh_fc64_fc64)
(
GrB_Matrix C,
const GrB_Matrix A,
int64_t *restrict *Workspaces,
const int64_t *restrict A_slice,
int nworkspaces,
int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
#include "GB_unop_transpose.c"
return (GrB_SUCCESS) ;
#endif
}
#endif
|
spmv_tile_balance_avx.h | #ifndef SPMV_TILE_BALANCE_AVX
#define SPMV_TILE_BALANCE_AVX
#include"common.h"
// #include"mmio_highlevel.h"
//#include"mmio.h"
#include"utils.h"
#include"tilespmv_warp_bal.h"
#include"tilespmv_warp_avx.h"
void tilespmv_balance_avx(Beidou_Tile_Matrix *matrix, int rowblkblock,
MAT_VAL_TYPE *x, MAT_VAL_TYPE *y_bal,
int *flag_tilerow_start, int *flag_tilerow_stop, int BLOCK_SIZE, MAT_VAL_TYPE *Ysum, MAT_VAL_TYPE *Ypartialsum)
{
int *rowpointer=matrix->rowpointer;
int *columnidx = matrix->columnidx;
MAT_VAL_TYPE *value = matrix->value;
int m = matrix->m;
int n = matrix->n;
int tilem = matrix->tilem;
int tilen = matrix->tilen;
MAT_PTR_TYPE *tile_ptr = matrix->tile_ptr;
int numtile = matrix->numtile;
int *tile_columnidx = matrix->tile_columnidx;
int *tile_nnz = matrix->tile_nnz;
char *Format = matrix->Format;
int *blknnz = matrix->blknnz;
char *blkwidth = matrix->blkwidth;
MAT_VAL_TYPE *Tile_csr_Val = matrix->Tile_csr_Val;
unsigned char *Tile_csr_Col = matrix->Tile_csr_Col;
unsigned char *Tile_csr_Ptr = matrix->Tile_csr_Ptr;
MAT_VAL_TYPE *Tile_coo_Val = matrix->Tile_coo_Val;
unsigned char *Tile_coo_colIdx = matrix->Tile_coo_colIdx;
unsigned char *Tile_coo_rowIdx = matrix->Tile_coo_rowIdx;
MAT_VAL_TYPE *Tile_ell_Val = matrix->Tile_ell_Val;
unsigned char *Tile_ell_colIdx = matrix->Tile_ell_colIdx;
MAT_VAL_TYPE *Tile_hyb_Val = matrix->Tile_hyb_Val;
unsigned char *Tile_hyb_ellcolIdx = matrix->Tile_hyb_ellcolIdx;
unsigned char *Tile_hyb_coorowIdx = matrix->Tile_hyb_coorowIdx;
MAT_VAL_TYPE *Tile_dns_Val = matrix->Tile_dns_Val;
MAT_VAL_TYPE *Tile_dnsrow_Val = matrix->Tile_dnsrow_Val;
char *Tile_dnsrow_idx = matrix->Tile_dnsrow_idx;
MAT_VAL_TYPE *Tile_dnscol_Val = matrix->Tile_dnscol_Val;
char *Tile_dnscol_idx = matrix->Tile_dnscol_idx;
int *denserowptr = matrix->denserowptr;
int *densecolptr = matrix->densecolptr;
unsigned int *flag_bal_tile_rowidx = matrix->flag_bal_tile_rowidx;
int *tile_bal_rowidx_colstart = matrix->tile_bal_rowidx_colstart ;
int *tile_bal_rowidx_colstop = matrix->tile_bal_rowidx_colstop;
unsigned char *csr_ptr = matrix->csr_ptr;
int *hyb_coocount = matrix->hyb_coocount;
int *csr_offset = matrix->csr_offset;
int *csrptr_offset = matrix->csrptr_offset;
int *coo_offset = matrix->coo_offset;
int *ell_offset = matrix->ell_offset;
int *hyb_offset = matrix->hyb_offset;
int *dns_offset = matrix->dns_offset;
int *dnsrow_offset = matrix->dnsrow_offset;
int *dnscol_offset = matrix->dnscol_offset;
int nthreads = omp_get_max_threads();
MAT_VAL_TYPE *y_temp_g = (MAT_VAL_TYPE *)malloc(sizeof(MAT_VAL_TYPE) * BLOCK_SIZE * nthreads);
int *flag_lastgroup_rowidx = (int *)malloc(nthreads * sizeof(int));
memset(flag_lastgroup_rowidx, 0, nthreads * sizeof(int));
// int *flag_tilerow_start = (int *)malloc(nthreads * sizeof(int));
// memset(flag_tilerow_start, 0, nthreads * sizeof(int));
// int *flag_tilerow_end = (int *)malloc(nthreads * sizeof(int));
// memset(flag_tilerow_end, 0, nthreads * sizeof(int));
// printf("balance rowblkblock = %i\n",rowblkblock);
// int rowblk_ave = rowblkblock / nthreads;
// int rowblk_ave_rest = rowblkblock % nthreads ;
// // printf("tile group_ave = %i\n",rowblk_ave);
// #pragma omp parallel for
// for (int i =0; i < nthreads; i ++)
// {
// if (i < rowblk_ave_rest)
// {
// flag_tilerow_start[i] = i * (rowblk_ave +1);
// flag_tilerow_stop[i] = (i +1) * (rowblk_ave +1);
// }
// else{
// flag_tilerow_start[i] = (rowblk_ave +1) * rowblk_ave_rest + (i - rowblk_ave_rest) * rowblk_ave;
// flag_tilerow_stop[i] = (rowblk_ave +1) * rowblk_ave_rest + (i +1 - rowblk_ave_rest) * rowblk_ave;
// }
// }
#pragma omp parallel for
for (int ti =0; ti < nthreads; ti ++)
{
int start_groupid = flag_tilerow_start[ti];
int end_groupid = flag_tilerow_stop[ti];
int thread_id = omp_get_thread_num();
MAT_VAL_TYPE *y_local = (MAT_VAL_TYPE *)malloc (BLOCK_SIZE * sizeof(MAT_VAL_TYPE));
memset(y_local, 0, BLOCK_SIZE * sizeof(MAT_VAL_TYPE));
for (int blki = start_groupid; blki < end_groupid ; blki ++)
{
int tile_rowidx_current = flag_bal_tile_rowidx[blki];
int tile_rowidx_next = flag_bal_tile_rowidx[blki +1];
int rowlen= tile_rowidx_current==tilem-1 ? m-(tilem-1)*BLOCK_SIZE : BLOCK_SIZE ;
for (int blkj = tile_bal_rowidx_colstart[blki]; blkj < tile_bal_rowidx_colstop[blki]; blkj ++)
{
int collen = tile_columnidx[blkj] == tilen-1 ? n - (tilen-1 ) * BLOCK_SIZE : BLOCK_SIZE ;
int tilennz = tile_nnz[blkj +1] - tile_nnz[blkj];
char format = Format[blkj];
int x_offset = tile_columnidx[blkj] * BLOCK_SIZE;
switch (format)
{
case 0:
{
warplevel_csr_bal_avx(matrix, tile_rowidx_current, blkj, csr_offset, csrptr_offset,
x, y_local, x_offset, BLOCK_SIZE);
break;
}
case 1:
{
// warplevel_coo_bal(matrix, tile_rowidx_current, blkj, coo_offset,
// x, y_local, x_offset);
break;
}
case 2:
{
warplevel_ell_bal_avx(matrix, tile_rowidx_current, blkj, ell_offset,
x, y_local, x_offset, BLOCK_SIZE);
break;
}
case 3:
{
warplevel_hyb_bal_avx(matrix, tile_rowidx_current, blkj,hyb_coocount, hyb_offset,
x, y_local, x_offset, BLOCK_SIZE);
break;
}
case 4:
{
warplevel_dns_bal_avx(matrix, tile_rowidx_current, blkj, dns_offset,
x, y_local, x_offset, BLOCK_SIZE);
break;
}
case 5:
{
warplevel_dnsrow_bal_avx(matrix, tile_rowidx_current, blkj, dnsrow_offset,
x, y_local, x_offset, BLOCK_SIZE);
break;
}
case 6:
{
warplevel_dnscol_bal_avx(matrix, tile_rowidx_current, blkj, dnscol_offset,
x, y_local, x_offset, BLOCK_SIZE);
break;
}
default:
break;
}
}
if (blki == end_groupid - 1)
{
if(tile_rowidx_current != tile_rowidx_next)
{
for (int ri =0; ri < rowlen; ri ++)
{
y_bal[tile_rowidx_current * BLOCK_SIZE +ri] = y_local[ri];
}
}
else
{
flag_lastgroup_rowidx[thread_id] = tile_rowidx_current;
for (int ri =0; ri < rowlen; ri ++)
{
y_temp_g[thread_id * BLOCK_SIZE + ri] = y_local[ri];
}
}
}
else
{
if(tile_rowidx_current != tile_rowidx_next)
{
for (int ri =0; ri < rowlen; ri ++)
{
y_bal[tile_rowidx_current * BLOCK_SIZE +ri] = y_local[ri];
}
memset(y_local, 0, BLOCK_SIZE * sizeof(MAT_VAL_TYPE));
}
}
}
}
for (int ti =0; ti < nthreads; ti ++)
{
int rowidx_temp = flag_lastgroup_rowidx[ti];
int rowlen = rowidx_temp == tilem-1 ? m-(tilem-1)*BLOCK_SIZE : BLOCK_SIZE ;
for (int ri =0; ri < rowlen; ri ++)
{
y_bal[rowidx_temp * BLOCK_SIZE + ri] += y_temp_g[ti * BLOCK_SIZE +ri];
}
}
#pragma omp parallel for
for (int tid = 0; tid < nthreads; tid++)
{
if (matrix->Yid[tid] == -1 )
{
for (int u = matrix->csrSplitter_yid[tid]; u < matrix->csrSplitter_yid[tid+1]; u++)
{
int rowidx = matrix->coo_new_rowidx[u];
double sum = 0;
for (int j = matrix->coo_new_matrix_ptr[u]; j < matrix->coo_new_matrix_ptr[u + 1]; j++)
{
int csrcolidx = matrix->coo_new_matrix_colidx[j];
sum += matrix->coo_new_matrix_value[j] * x[csrcolidx];
}
y_bal[rowidx] += sum;
}
}
else if (matrix->label[tid] != 0)
{
for (int u = matrix->Start1[tid]; u < matrix->End1[tid]; u++)
{
int rowidx = matrix->coo_new_rowidx[u];
double sum = 0;
for (int j = matrix->coo_new_matrix_ptr[u]; j < matrix->coo_new_matrix_ptr[u + 1]; j++)
{
int csrcolidx = matrix->coo_new_matrix_colidx[j];
sum += matrix->coo_new_matrix_value[j] * x[csrcolidx];
}
y_bal[rowidx] = sum;
}
}
else if (matrix->Yid[tid] != -1 && matrix->label[tid] == 0)//youwenti
{
Ysum[tid] = 0;
Ypartialsum[tid] = 0;
for (int j = matrix->Start2[tid]; j < matrix->End2[tid]; j++)
{
int csrcolidx = matrix->coo_new_matrix_colidx[j];
Ypartialsum[tid] += matrix->coo_new_matrix_value[j] * x[csrcolidx];
}
Ysum[tid] += Ypartialsum[tid];
y_bal[matrix->Yid[tid]] += Ysum[tid];
}
}
}
#endif
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.