id
int64 0
877k
| file_name
stringlengths 3
109
| file_path
stringlengths 13
185
| content
stringlengths 31
9.38M
| size
int64 31
9.38M
| language
stringclasses 1
value | extension
stringclasses 11
values | total_lines
int64 1
340k
| avg_line_length
float64 2.18
149k
| max_line_length
int64 7
2.22M
| alphanum_fraction
float64 0
1
| repo_name
stringlengths 6
66
| repo_stars
int64 94
47.3k
| repo_forks
int64 0
12k
| repo_open_issues
int64 0
3.4k
| repo_license
stringclasses 11
values | repo_extraction_date
stringclasses 197
values | exact_duplicates_redpajama
bool 2
classes | near_duplicates_redpajama
bool 2
classes | exact_duplicates_githubcode
bool 2
classes | exact_duplicates_stackv2
bool 1
class | exact_duplicates_stackv1
bool 2
classes | near_duplicates_githubcode
bool 2
classes | near_duplicates_stackv1
bool 2
classes | near_duplicates_stackv2
bool 1
class |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
1,531,667
|
connected_components.hpp
|
metric-space-ai_metric/metric/utils/graph/connected_components.hpp
|
#pragma once
/*
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/.
Copyright (c) 2019 Panda Team
*/
/*
"Cracker" Algorithm to compute connected components of a graph.
Ref: Fast Connected Components Computation in Large Graphs by Vertex Pruning
Alessandro Lulli, Emanuele Carlini, Patrizio Dazzi, Claudio Lucchese, and Laura Ricci
2016
https://doi.org/10.1109/TPDS.2016.2591038
*/
#ifndef _METRIC_UTILS_GRAPH_CONNECTED_COMPONENTS_HPP
#define _METRIC_UTILS_GRAPH_CONNECTED_COMPONENTS_HPP
#include <list>
#include <vector>
#include <blaze/Math.h>
namespace metric {
namespace graph {
/**
* @class Cracker
*
* @brief
*/
template <typename Matrix> class Cracker {
public:
/**
* @brief Get the All Components
*
* @param input
* @param Count
* @return
*/
std::vector<Matrix> GetAllComponents(const Matrix &input, const size_t Count);
private:
typedef typename Matrix::ElementType Ty;
void ProcessGraph(Matrix &tempGraph);
void PropagateTrees();
void ProcessTreeNode(const size_t node, std::vector<size_t> &Nodevector);
size_t neighborCount(const size_t n,
const blaze::DynamicVector<typename Matrix::ElementType, blaze::rowVector> &neighbors) const;
size_t incomingCount(const size_t n, Matrix &mx) const;
void ConvertVertexvectorToMatrix(const std::vector<size_t> &vertices, const Matrix &input, Matrix &output);
Matrix PropagationTrees;
std::list<std::vector<size_t>> Components;
std::vector<size_t> Seeds;
size_t ActiveNum;
std::vector<bool> ActiveVertices;
};
/**
* @brief
*
* @param input
* @param Count if Count=0 - get all components, 1 - largest
* @return
*/
template <typename Matrix> std::vector<Matrix> connected_components(const Matrix &input, const size_t Count);
/**
* @brief
*
* @param input
* @return
*/
template <typename Matrix> std::vector<Matrix> all_connected_components(const Matrix &input);
/**
* @brief
*
* @param input
* @return
*/
template <typename Matrix> std::vector<Matrix> largest_connected_component(const Matrix &input);
} // namespace graph
} // namespace metric
#include "connected_components.cpp"
#endif
| 2,254
|
C++
|
.h
| 77
| 27.25974
| 109
| 0.753235
|
metric-space-ai/metric
| 34
| 14
| 44
|
MPL-2.0
|
9/20/2024, 10:43:29 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| true
| false
|
1,531,668
|
sparsify.hpp
|
metric-space-ai_metric/metric/utils/graph/sparsify.hpp
|
/*
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/.
Copyright (c) 2019 Panda Team
Copyright (c) 2019 Oleg Popov
*/
/*
Laplacians is a package containing graph algorithms, with an emphasis on tasks related to
spectral and algebraic graph theory. It contains (and will contain more) code for solving
systems of linear equations in graph Laplacians, low stretch spanning trees, sparsifiation,
clustering, local clustering, and optimization on graphs.
All graphs are represented by sparse adjacency matrices. This is both for speed, and because
our main concerns are algebraic tasks. It does not handle dynamic graphs. It would be very slow
to implement dynamic graphs this way.
https://github.com/danspielman/Laplacians.jl
*/
#ifndef _METRIC_UTILS_GRAPH_SPRSIFY_HPP
#define _METRIC_UTILS_GRAPH_SPRSIFY_HPP
#include "../solver/solver.hpp"
#include <algorithm>
#include <blaze/Math.h>
#include <chrono>
#include <cmath>
#include <vector>
namespace metric {
/*
Just implements Spielman-Srivastava
as = sparsify(a; ep=0.5)
Apply Spielman-Srivastava sparsification: sampling by effective resistances.
`ep` should be less than 1.
*/
/**
* @brief Apply Spielman-Srivastava sparsification: sampling by effective resistances.
*
* @param a
* @param ep
* @param matrixConcConst
* @param JLfac
* @return
*/
template <typename Tv>
blaze::CompressedMatrix<Tv, blaze::columnMajor>
sparsify_effective_resistance(const blaze::CompressedMatrix<Tv, blaze::columnMajor> &a, float ep = 0.3F,
float matrixConcConst = 4.0F, float JLfac = 4.0F);
/**
* Uses Kruskal's algorithm.
*/
template <typename Tv>
blaze::CompressedMatrix<Tv, blaze::columnMajor>
sparsify_spanning_tree(const blaze::CompressedMatrix<Tv, blaze::columnMajor> &a, bool minimum = true);
} // namespace metric
#include "sparsify.cpp"
#endif
| 1,969
|
C++
|
.h
| 54
| 34.648148
| 104
| 0.777953
|
metric-space-ai/metric
| 34
| 14
| 44
|
MPL-2.0
|
9/20/2024, 10:43:29 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,531,669
|
BFloat16.h
|
metric-space-ai_metric/metric/utils/types/BFloat16.h
|
#ifndef BFLOAT_BFLOAT_HPP
#define BFLOAT_BFLOAT_HPP
#define BFLOAT_GCC_VERSION (__GNUC__ * 100 + __GNUC_MINOR__)
#if defined(__INTEL_COMPILER)
#define BFLOAT_ICC_VERSION __INTEL_COMPILER
#elif defined(__ICC)
#define BFLOAT_ICC_VERSION __ICC
#elif defined(__ICL)
#define BFLOAT_ICC_VERSION __ICL
#else
#define BFLOAT_ICC_VERSION 0
#endif
// check C++11 language features
#if defined(__clang__) // clang
#if __has_feature(cxx_static_assert) && !defined(BFLOAT_ENABLE_CPP11_STATIC_ASSERT)
#define BFLOAT_ENABLE_CPP11_STATIC_ASSERT 1
#endif
#if __has_feature(cxx_constexpr) && !defined(BFLOAT_ENABLE_CPP11_CONSTEXPR)
#define BFLOAT_ENABLE_CPP11_CONSTEXPR 1
#endif
#if __has_feature(cxx_noexcept) && !defined(BFLOAT_ENABLE_CPP11_NOEXCEPT)
#define BFLOAT_ENABLE_CPP11_NOEXCEPT 1
#endif
#if __has_feature(cxx_user_literals) && !defined(BFLOAT_ENABLE_CPP11_USER_LITERALS)
#define BFLOAT_ENABLE_CPP11_USER_LITERALS 1
#endif
#if __has_feature(cxx_thread_local) && !defined(BFLOAT_ENABLE_CPP11_THREAD_LOCAL)
#define BFLOAT_ENABLE_CPP11_THREAD_LOCAL 1
#endif
#if (defined(__GXX_EXPERIMENTAL_CXX0X__) || __cplusplus >= 201103L) && !defined(BFLOAT_ENABLE_CPP11_LONG_LONG)
#define BFLOAT_ENABLE_CPP11_LONG_LONG 1
#endif
#elif BFLOAT_ICC_VERSION && defined(__INTEL_CXX11_MODE__) // Intel C++
#if BFLOAT_ICC_VERSION >= 1500 && !defined(BFLOAT_ENABLE_CPP11_THREAD_LOCAL)
#define BFLOAT_ENABLE_CPP11_THREAD_LOCAL 1
#endif
#if BFLOAT_ICC_VERSION >= 1500 && !defined(BFLOAT_ENABLE_CPP11_USER_LITERALS)
#define BFLOAT_ENABLE_CPP11_USER_LITERALS 1
#endif
#if BFLOAT_ICC_VERSION >= 1400 && !defined(BFLOAT_ENABLE_CPP11_CONSTEXPR)
#define BFLOAT_ENABLE_CPP11_CONSTEXPR 1
#endif
#if BFLOAT_ICC_VERSION >= 1400 && !defined(BFLOAT_ENABLE_CPP11_NOEXCEPT)
#define BFLOAT_ENABLE_CPP11_NOEXCEPT 1
#endif
#if BFLOAT_ICC_VERSION >= 1110 && !defined(BFLOAT_ENABLE_CPP11_STATIC_ASSERT)
#define BFLOAT_ENABLE_CPP11_STATIC_ASSERT 1
#endif
#if BFLOAT_ICC_VERSION >= 1110 && !defined(BFLOAT_ENABLE_CPP11_LONG_LONG)
#define BFLOAT_ENABLE_CPP11_LONG_LONG 1
#endif
#elif defined(__GNUC__) // gcc
#if defined(__GXX_EXPERIMENTAL_CXX0X__) || __cplusplus >= 201103L
#if BFLOAT_GCC_VERSION >= 408 && !defined(BFLOAT_ENABLE_CPP11_THREAD_LOCAL)
#define BFLOAT_ENABLE_CPP11_THREAD_LOCAL 1
#endif
#if BFLOAT_GCC_VERSION >= 407 && !defined(BFLOAT_ENABLE_CPP11_USER_LITERALS)
#define BFLOAT_ENABLE_CPP11_USER_LITERALS 1
#endif
#if BFLOAT_GCC_VERSION >= 406 && !defined(BFLOAT_ENABLE_CPP11_CONSTEXPR)
#define BFLOAT_ENABLE_CPP11_CONSTEXPR 1
#endif
#if BFLOAT_GCC_VERSION >= 406 && !defined(BFLOAT_ENABLE_CPP11_NOEXCEPT)
#define BFLOAT_ENABLE_CPP11_NOEXCEPT 1
#endif
#if BFLOAT_GCC_VERSION >= 403 && !defined(BFLOAT_ENABLE_CPP11_STATIC_ASSERT)
#define BFLOAT_ENABLE_CPP11_STATIC_ASSERT 1
#endif
#if !defined(BFLOAT_ENABLE_CPP11_LONG_LONG)
#define BFLOAT_ENABLE_CPP11_LONG_LONG 1
#endif
#endif
#define BFLOAT_TWOS_COMPLEMENT_INT 1
#elif defined(_MSC_VER) // Visual C++
#if _MSC_VER >= 1900 && !defined(BFLOAT_ENABLE_CPP11_THREAD_LOCAL)
#define BFLOAT_ENABLE_CPP11_THREAD_LOCAL 1
#endif
#if _MSC_VER >= 1900 && !defined(BFLOAT_ENABLE_CPP11_USER_LITERALS)
#define BFLOAT_ENABLE_CPP11_USER_LITERALS 1
#endif
#if _MSC_VER >= 1900 && !defined(BFLOAT_ENABLE_CPP11_CONSTEXPR)
#define BFLOAT_ENABLE_CPP11_CONSTEXPR 1
#endif
#if _MSC_VER >= 1900 && !defined(BFLOAT_ENABLE_CPP11_NOEXCEPT)
#define BFLOAT_ENABLE_CPP11_NOEXCEPT 1
#endif
#if _MSC_VER >= 1600 && !defined(BFLOAT_ENABLE_CPP11_STATIC_ASSERT)
#define BFLOAT_ENABLE_CPP11_STATIC_ASSERT 1
#endif
#if _MSC_VER >= 1310 && !defined(BFLOAT_ENABLE_CPP11_LONG_LONG)
#define BFLOAT_ENABLE_CPP11_LONG_LONG 1
#endif
#define BFLOAT_TWOS_COMPLEMENT_INT 1
#define BFLOAT_POP_WARNINGS 1
#pragma warning(push)
#pragma warning(disable : 4099 4127 4146) // struct vs class, constant in if, negative unsigned
#endif
// ckeck C++11 library features
#include <utility>
#if defined(_LIBCPP_VERSION)
#if defined(__GXX_EXPERIMENTAL_CXX0X__) || __cplusplus >= 201103
#ifndef BFLOAT_ENABLE_CPP11_TYPE_TRAITS
#define BFLOAT_ENABLE_CPP11_TYPE_TRAITS 1
#endif
#ifndef BFLOAT_ENABLE_CPP11_CSTDINT
#define BFLOAT_ENABLE_CPP11_CSTDINT 1
#endif
#ifndef BFLOAT_ENABLE_CPP11_CMATH
#define BFLOAT_ENABLE_CPP11_CMATH 1
#endif
#ifndef BFLOAT_ENABLE_CPP11_HASH
#define BFLOAT_ENABLE_CPP11_HASH 1
#endif
#ifndef BFLOAT_ENABLE_CPP11_CFENV
#define BFLOAT_ENABLE_CPP11_CFENV 1
#endif
#endif
#elif defined(__GLIBCXX__) // libstdc++
#if defined(__GXX_EXPERIMENTAL_CXX0X__) || __cplusplus >= 201103
#ifdef __clang__
#if __GLIBCXX__ >= 20080606 && !defined(BFLOAT_ENABLE_CPP11_TYPE_TRAITS)
#define BFLOAT_ENABLE_CPP11_TYPE_TRAITS 1
#endif
#if __GLIBCXX__ >= 20080606 && !defined(BFLOAT_ENABLE_CPP11_CSTDINT)
#define BFLOAT_ENABLE_CPP11_CSTDINT 1
#endif
#if __GLIBCXX__ >= 20080606 && !defined(BFLOAT_ENABLE_CPP11_CMATH)
#define BFLOAT_ENABLE_CPP11_CMATH 1
#endif
#if __GLIBCXX__ >= 20080606 && !defined(BFLOAT_ENABLE_CPP11_HASH)
#define BFLOAT_ENABLE_CPP11_HASH 1
#endif
#if __GLIBCXX__ >= 20080606 && !defined(BFLOAT_ENABLE_CPP11_CFENV)
#define BFLOAT_ENABLE_CPP11_CFENV 1
#endif
#else
#if BFLOAT_GCC_VERSION >= 403 && !defined(BFLOAT_ENABLE_CPP11_TYPE_TRAITS)
#define BFLOAT_ENABLE_CPP11_TYPE_TRAITS 1
#endif
#if BFLOAT_GCC_VERSION >= 403 && !defined(BFLOAT_ENABLE_CPP11_CSTDINT)
#define BFLOAT_ENABLE_CPP11_CSTDINT 1
#endif
#if BFLOAT_GCC_VERSION >= 403 && !defined(BFLOAT_ENABLE_CPP11_CMATH)
#define BFLOAT_ENABLE_CPP11_CMATH 1
#endif
#if BFLOAT_GCC_VERSION >= 403 && !defined(BFLOAT_ENABLE_CPP11_HASH)
#define BFLOAT_ENABLE_CPP11_HASH 1
#endif
#if BFLOAT_GCC_VERSION >= 403 && !defined(BFLOAT_ENABLE_CPP11_CFENV)
#define BFLOAT_ENABLE_CPP11_CFENV 1
#endif
#endif
#endif
#elif defined(_CPPLIB_VER) // Dinkumware/Visual C++
#if _CPPLIB_VER >= 520 && !defined(BFLOAT_ENABLE_CPP11_TYPE_TRAITS)
#define BFLOAT_ENABLE_CPP11_TYPE_TRAITS 1
#endif
#if _CPPLIB_VER >= 520 && !defined(BFLOAT_ENABLE_CPP11_CSTDINT)
#define BFLOAT_ENABLE_CPP11_CSTDINT 1
#endif
#if _CPPLIB_VER >= 520 && !defined(BFLOAT_ENABLE_CPP11_HASH)
#define BFLOAT_ENABLE_CPP11_HASH 1
#endif
#if _CPPLIB_VER >= 610 && !defined(BFLOAT_ENABLE_CPP11_CMATH)
#define BFLOAT_ENABLE_CPP11_CMATH 1
#endif
#if _CPPLIB_VER >= 610 && !defined(BFLOAT_ENABLE_CPP11_CFENV)
#define BFLOAT_ENABLE_CPP11_CFENV 1
#endif
#endif
#undef BFLOAT_GCC_VERSION
#undef BFLOAT_ICC_VERSION
// any error throwing C++ exceptions?
#if defined(BFLOAT_ERRHANDLING_THROW_INVALID) || defined(BFLOAT_ERRHANDLING_THROW_DIVBYZERO) || \
defined(BFLOAT_ERRHANDLING_THROW_OVERFLOW) || defined(BFLOAT_ERRHANDLING_TRHOW_UNDERFLOW) || \
defined(BFLOAT_ERRHANDLING_THROW_INEXACT)
#define BFLOAT_ERRHANDLING_THROWS 1
#endif
// any error handling enabled?
#define BFLOAT_ERRHANDLING \
(BFLOAT_ERRHANDLING_FLAGS || BFLOAT_ERRHANDLING_ERRNO || BFLOAT_ERRHANDLING_FENV || BFLOAT_ERRHANDLING_THROWS)
#if BFLOAT_ERRHANDLING
#define BFLOAT_UNUSED_NOERR(name) name
#else
#define BFLOAT_UNUSED_NOERR(name)
#endif
// support constexpr
#if BFLOAT_ENABLE_CPP11_CONSTEXPR
#define BFLOAT_CONSTEXPR constexpr
#define BFLOAT_CONSTEXPR_CONST constexpr
#if BFLOAT_ERRHANDLING
#define BFLOAT_CONSTEXPR_NOERR
#else
#define BFLOAT_CONSTEXPR_NOERR constexpr
#endif
#else
#define BFLOAT_CONSTEXPR
#define BFLOAT_CONSTEXPR_CONST const
#define BFLOAT_CONSTEXPR_NOERR
#endif
// support noexcept
#if BFLOAT_ENABLE_CPP11_NOEXCEPT
#define BFLOAT_NOEXCEPT noexcept
#define BFLOAT_NOTHROW noexcept
#else
#define BFLOAT_NOEXCEPT
#define BFLOAT_NOTHROW throw()
#endif
// support thread storage
#if BFLOAT_ENABLE_CPP11_THREAD_LOCAL
#define BFLOAT_THREAD_LOCAL thread_local
#else
#define BFLOAT_THREAD_LOCAL static
#endif
#include <algorithm>
#include <climits>
#include <cmath>
#include <cstdlib>
#include <cstring>
#include <istream>
#include <limits>
#include <ostream>
#include <stdexcept>
#include <utility>
#if BFLOAT_ENABLE_CPP11_TYPE_TRAITS
#include <type_traits>
#endif
#if BFLOAT_ENABLE_CPP11_CSTDINT
#include <cstdint>
#endif
#if BFLOAT_ERRHANDLING_ERRNO
#include <cerrno>
#endif
#if BFLOAT_ENABLE_CPP11_CFENV
#include <cfenv>
#endif
#if BFLOAT_ENABLE_CPP11_HASH
#include <functional>
#include <iostream>
#endif
#ifdef BFLOAT_DOXYGEN_ONLY
/// Type for internal floating-point computations.
/// This can be predefined to a built-in floating-point type (`float`, `double` or `long double`) to override the
/// internal bfloat16-precision implementation to use this type for computing arithmetic operations and mathematical
/// function (if available). This can result in improved performance for arithmetic operators and mathematical functions
/// but might cause results to deviate from the specified bfloat16-precision rounding mode and inhibits proper detection
/// of bfloat16-precision exceptions.
#define BFLOAT_ARITHMETIC_TYPE (undefined)
/// Enable internal exception flags.
/// Defining this to 1 causes operations on bfloat16-precision values to raise internal floating-point exception flags
/// according to the IEEE 754 standard. These can then be cleared and checked with clearexcept(), testexcept().
#define BFLOAT_ERRHANDLING_FLAGS 0
/// Enable exception propagation to `errno`.
/// Defining this to 1 causes operations on bfloat16-precision values to propagate floating-point exceptions to
/// [errno](https://en.cppreference.com/w/cpp/error/errno) from `<cerrno>`. Specifically this will propagate domain
/// errors as [EDOM](https://en.cppreference.com/w/cpp/error/errno_macros) and pole, overflow and underflow errors as
/// [ERANGE](https://en.cppreference.com/w/cpp/error/errno_macros). Inexact errors won't be propagated.
#define BFLOAT_ERRHANDLING_ERRNO 0
/// Enable exception propagation to built-in floating-point platform.
/// Defining this to 1 causes operations on bfloat16-precision values to propagate floating-point exceptions to the
/// built-in single- and double-precision implementation's exception flags using the [C++11 floating-point environment
/// control](https://en.cppreference.com/w/cpp/numeric/fenv) from `<cfenv>`. However, this does not work in reverse and
/// single- or double-precision exceptions will not raise the corresponding bfloat16-precision exception flags, nor will
/// explicitly clearing flags clear the corresponding built-in flags.
#define BFLOAT_ERRHANDLING_FENV 0
/// Throw C++ exception on domain errors.
/// Defining this to a string literal causes operations on bfloat16-precision values to throw a
/// [std::domain_error](https://en.cppreference.com/w/cpp/error/domain_error) with the specified message on domain
/// errors.
#define BFLOAT_ERRHANDLING_THROW_INVALID (undefined)
/// Throw C++ exception on pole errors.
/// Defining this to a string literal causes operations on bfloat16-precision values to throw a
/// [std::domain_error](https://en.cppreference.com/w/cpp/error/domain_error) with the specified message on pole errors.
#define BFLOAT_ERRHANDLING_THROW_DIVBYZERO (undefined)
/// Throw C++ exception on overflow errors.
/// Defining this to a string literal causes operations on bfloat16-precision values to throw a
/// [std::overflow_error](https://en.cppreference.com/w/cpp/error/overflow_error) with the specified message on
/// overflows.
#define BFLOAT_ERRHANDLING_THROW_OVERFLOW (undefined)
/// Throw C++ exception on underflow errors.
/// Defining this to a string literal causes operations on bfloat16-precision values to throw a
/// [std::underflow_error](https://en.cppreference.com/w/cpp/error/underflow_error) with the specified message on
/// underflows.
#define BFLOAT_ERRHANDLING_THROW_UNDERFLOW (undefined)
/// Throw C++ exception on rounding errors.
/// Defining this to 1 causes operations on bfloat16-precision values to throw a
/// [std::range_error](https://en.cppreference.com/w/cpp/error/range_error) with the specified message on general
/// rounding errors.
#define BFLOAT_ERRHANDLING_THROW_INEXACT (undefined)
#endif
#ifndef BFLOAT_ERRHANDLING_OVERFLOW_TO_INEXACT
/// Raise INEXACT exception on overflow.
/// Defining this to 1 (default) causes overflow errors to automatically raise inexact exceptions in addition.
/// These will be raised after any possible handling of the underflow exception.
#define BFLOAT_ERRHANDLING_OVERFLOW_TO_INEXACT 1
#endif
#ifndef BFLOAT_ERRHANDLING_UNDERFLOW_TO_INEXACT
/// Raise INEXACT exception on underflow.
/// Defining this to 1 (default) causes underflow errors to automatically raise inexact exceptions in addition.
/// These will be raised after any possible handling of the underflow exception.
///
/// **Note:** This will actually cause underflow (and the accompanying inexact) exceptions to be raised *only* when the
/// result is inexact, while if disabled bare underflow errors will be raised for *any* (possibly exact) subnormal
/// result.
#define BFLOAT_ERRHANDLING_UNDERFLOW_TO_INEXACT 1
#endif
/// Default rounding mode.
/// This specifies the rounding mode used for all conversions between [bfloat16](\ref bfloat16::bfloat16)s and more
/// precise types (unless using bfloat16_cast() and specifying the rounding mode directly) as well as in arithmetic
/// operations and mathematical functions. It can be redefined (before including bfloat16.hpp) to one of the standard
/// rounding modes using their respective constants or the equivalent values of
/// [std::float_round_style](https://en.cppreference.com/w/cpp/types/numeric_limits/float_round_style):
///
/// `std::float_round_style` | value | rounding
/// ---------------------------------|-------|-------------------------
/// `std::round_indeterminate` | -1 | fastest
/// `std::round_toward_zero` | 0 | toward zero
/// `std::round_to_nearest` | 1 | to nearest (default)
/// `std::round_toward_infinity` | 2 | toward positive infinity
/// `std::round_toward_neg_infinity` | 3 | toward negative infinity
///
/// By default this is set to `1` (`std::round_to_nearest`), which rounds results to the nearest representable value. It
/// can even be set to
/// [std::numeric_limits<float>::round_style](https://en.cppreference.com/w/cpp/types/numeric_limits/round_style) to
/// synchronize the rounding mode with that of the built-in single-precision implementation (which is likely
/// `std::round_to_nearest`, though).
#ifndef BFLOAT_ROUND_STYLE
#define BFLOAT_ROUND_STYLE 1 // = std::round_to_nearest
#endif
/// Value signaling overflow.
/// In correspondence with `HUGE_VAL[F|L]` from `<cmath>` this symbol expands to a positive value signaling the overflow
/// of an operation, in particular it just evaluates to positive infinity.
///
/// **See also:** Documentation for [HUGE_VAL](https://en.cppreference.com/w/cpp/numeric/math/HUGE_VAL)
#define HUGE_VALH std::numeric_limits<bfloat16::bfloat16>::infinity()
/// Fast bfloat16-precision fma function.
/// This symbol is defined if the fma() function generally executes as fast as, or faster than, a separate
/// bfloat16-precision multiplication followed by an addition, which is always the case.
///
/// **See also:** Documentation for [FP_FAST_FMA](https://en.cppreference.com/w/cpp/numeric/math/fma)
#define FP_FAST_FMAH 1
/// Bfloat rounding mode.
/// In correspondence with `FLT_ROUNDS` from `<cfloat>` this symbol expands to the rounding mode used for
/// bfloat16-precision operations. It is an alias for [BFLOAT_ROUND_STYLE](\ref BFLOAT_ROUND_STYLE).
///
/// **See also:** Documentation for [FLT_ROUNDS](https://en.cppreference.com/w/cpp/types/climits/FLT_ROUNDS)
#define BFL_ROUNDS BFLOAT_ROUND_STYLE
#ifndef FP_ILOGB0
#define FP_ILOGB0 INT_MIN
#endif
#ifndef FP_ILOGBNAN
#define FP_ILOGBNAN INT_MAX
#endif
#ifndef FP_SUBNORMAL
#define FP_SUBNORMAL 0
#endif
#ifndef FP_ZERO
#define FP_ZERO 1
#endif
#ifndef FP_NAN
#define FP_NAN 2
#endif
#ifndef FP_INFINITE
#define FP_INFINITE 3
#endif
#ifndef FP_NORMAL
#define FP_NORMAL 4
#endif
#if !BFLOAT_ENABLE_CPP11_CFENV && !defined(FE_ALL_EXCEPT)
#define FE_INVALID 0x10
#define FE_DIVBYZERO 0x08
#define FE_OVERFLOW 0x04
#define FE_UNDERFLOW 0x02
#define FE_INEXACT 0x01
#define FE_ALL_EXCEPT (FE_INVALID | FE_DIVBYZERO | FE_OVERFLOW | FE_UNDERFLOW | FE_INEXACT)
#endif
/// Main namespace for bfloat16-precision functionality.
/// This namespace contains all the functionality provided by the library.
namespace bfloat16 {
class bfloat16;
#if BFLOAT_ENABLE_CPP11_USER_LITERALS
/// Library-defined bfloat16-precision literals.
/// Import this namespace to enable bfloat16-precision floating-point literals:
/// ~~~~{.cpp}
/// using namespace bfloat16::literal;
/// bfloat16::bfloat16 = 4.2_h;
/// ~~~~
namespace literal {
bfloat16 operator"" _h(long double);
}
#endif
/// \internal
/// \brief Implementation details.
namespace detail {
#if BFLOAT_ENABLE_CPP11_TYPE_TRAITS
/// Conditional type.
template <bool B, typename T, typename F> struct conditional : std::conditional<B, T, F> {
};
/// Helper for tag dispatching.
template <bool B> struct bool_type : std::integral_constant<bool, B> {
};
using std::false_type;
using std::true_type;
/// Type traits for floating-point types.
template <typename T> struct is_float : std::is_floating_point<T> {
};
#else
/// Conditional type.
template <bool, typename T, typename> struct conditional {
typedef T type;
};
template <typename T, typename F> struct conditional<false, T, F> {
typedef F type;
};
/// Helper for tag dispatching.
template <bool> struct bool_type {
};
typedef bool_type<true> true_type;
typedef bool_type<false> false_type;
/// Type traits for floating-point types.
template <typename> struct is_float : false_type {
};
template <typename T> struct is_float<const T> : is_float<T> {
};
template <typename T> struct is_float<volatile T> : is_float<T> {
};
template <typename T> struct is_float<const volatile T> : is_float<T> {
};
template <> struct is_float<float> : true_type {
};
template <> struct is_float<double> : true_type {
};
template <> struct is_float<long double> : true_type {
};
#endif
/// Type traits for floating-point bits.
template <typename T> struct bits {
typedef unsigned char type;
};
template <typename T> struct bits<const T> : bits<T> {
};
template <typename T> struct bits<volatile T> : bits<T> {
};
template <typename T> struct bits<const volatile T> : bits<T> {
};
#if BFLOAT_ENABLE_CPP11_CSTDINT
/// Unsigned integer of (at least) 16 bits width.
typedef std::uint_least16_t uint16;
/// Fastest unsigned integer of (at least) 32 bits width.
typedef std::uint_fast32_t uint32;
/// Fastest signed integer of (at least) 32 bits width.
typedef std::int_fast32_t int32;
/// Unsigned integer of (at least) 32 bits width.
template <> struct bits<float> {
typedef std::uint_least32_t type;
};
/// Unsigned integer of (at least) 64 bits width.
template <> struct bits<double> {
typedef std::uint_least64_t type;
};
#else
/// Unsigned integer of (at least) 16 bits width.
typedef unsigned short uint16;
/// Fastest unsigned integer of (at least) 32 bits width.
typedef unsigned long uint32;
/// Fastest signed integer of (at least) 32 bits width.
typedef long int32;
/// Unsigned integer of (at least) 32 bits width.
template <>
struct bits<float> : conditional<std::numeric_limits<unsigned int>::digits >= 32, unsigned int, unsigned long> {
};
#if BFLOAT_ENABLE_CPP11_LONG_LONG
/// Unsigned Integer of (at least) 64 bits width.
template <>
struct bits<double> : conditional<std::numeric_limits<unsigned long>::digits >= 64, unsigned long, unsigned long long> {
};
#else
/// Unsigned integer of (at least) 64 bits width.
template <> struct bits<double> {
typedef unsigned long type
};
#endif
#endif
#ifdef BFLOAT_ARITHMETIC_TYPE
/// Type to use for arithmetic computations and matematic functions internally.
typedef BFLOAT_ARITHMETIC_TYPE internal_t;
#endif
/// Tag type for binary construction.
struct binary_t {
};
/// Tag for binary construction.
BFLOAT_CONSTEXPR_CONST binary_t binary = binary_t();
/// \name Implementation defined classification and arithmetic
/// \{
/// Check for infinity.
/// \tparam T argument type (builtin floating-point type)
/// \param arg value to query
/// \retval true if infinity
/// \retval false else
template <typename T> bool builtin_isinf(T arg)
{
return arg == std::numeric_limits<T>::infinity() || arg == -std::numeric_limits<T>::infinity();
}
/// Check for NaN.
/// \tparam T argument type (builtin floating-point type)
/// \param arg value to query
/// \retval true if not a number
/// \retval false else
template <typename T> bool builtin_isnan(T arg)
{
// #if BFLOAT_ENABLE_CPP11_CMATH
// return std::isnan(arg); // does not work with bfloat16
// #else
return arg != arg;
// #endif
}
/// Check sign.
/// \tparam T argument type (builtin floating-point type)
/// \param arg value to query
/// \retval true if signbit set
/// \retval false else
template <typename T> bool builtin_signbit(T arg)
{
// #if BFLOAT_ENABLE_CPP11_CMATH
// return std::signbit(arg); // does not work with bfloat16
// #else
return arg < T() || (arg == T() && T(1) / arg < T());
// #endif
}
/// Platform-independent sign mask.
/// \param arg integer value in two's complement
/// \retval -1 if \a arg negative
/// \retval 0 if \a arg positive
inline uint32 sign_mask(uint32 arg)
{
static const int N = std::numeric_limits<uint32>::digits - 1;
#if BFLOAT_TWOS_COMPLEMENT_INT
return static_cast<int32>(arg) >> N;
#else
return -((arg >> N) & 1);
#endif
}
/// Platform-independent arithmetic right shift.
/// \param arg integer value in two's complement
/// \param i shift amount (at most 31)
/// \return \a arg right shifted for \a i bits with possible sign extension
inline uint32 arithmetic_shift(uint32 arg, int i)
{
#if BFLOAT_TWOS_COMPLEMENT_INT
return static_cast<int32>(arg) >> i;
#else
return static_cast<int32>(arg) / (static_cast<int32>(1) << i) -
((arg >> (std::numeric_limits<uint32>::digits - 1)) & 1);
#endif
}
/// \}
/// \name Error handling
/// \{
/// Internal exception flags.
/// \return reference to global exception flags
inline int &errflags()
{
BFLOAT_THREAD_LOCAL int flags = 0;
return flags;
}
/// Raise floating-point exception.
/// \param flags exceptions to raise
/// \param cond condition to raise exceptions for
inline void raise(int BFLOAT_UNUSED_NOERR(flags), bool BFLOAT_UNUSED_NOERR(cond) = true)
{
#if BFLOAT_ERRHANDLING
if (!cond)
return;
#if BFLOAT_ERHHANDLING_FLAGS
errflags() |= flags;
#endif
#if BFLOAT_ERRHANDLING_ERRNO
if (flags & FE_INVALID)
errno = EDOM;
else if (flags & (FE_DIVBYZERO | FE_OVERFLOW | FE_UNDERFLOW))
errno = ERANGE;
#endif
#if BFLOAT_ERRHANDLING_FENV && BFLOAT_ENABLE_CPP11_CFENV
std::feraiseexcept(flags);
#endif
#ifdef BFLOAT_ERRHANDLING_THROW_INVALID
if (flags & FE_INVALID)
throw std::domain_error(BFLOAT_ERRHANDLING_THROW_INVALID);
#endif
#ifdef BFLOAT_ERRHANDLING_THROW_DIVBYZERO
if (flags & FE_DIVBYZERO)
throw std::domain_error(BFLOAT_ERRHANDLING_THROW_DIVBYZERO);
#endif
#ifdef BFLOAT_ERRHANDLING_THROW_OVERFLOW
if (flags & FE_OVERFLOW)
throw std::overflow_error(BFLOAT_ERRHANDLING_THROW_OVERFLOW);
#endif
#ifdef BFLOAT_ERRHANDLING_THROW_UNDERFLOW
if (flags & FE_UNDERFLOW)
throw std::underflow_error(BFLOAT_ERRHANDLING_THROW_UNDERFLOW);
#endif
#ifdef BFLOAT_ERRHANDLING_THROW_INEXACT
if (flags & FE_INEXACT)
throw std::range_error(BFLOAT_ERRHANDLINIG_THROW_INEXACT);
#endif
#if BFLOAT_ERRHANDLING_UNDERFLOW_TO_INEXACT
if ((flags & FE_UNDERFLOW) && !(flags & FE_INEXACT))
raise(FE_INEXACT);
#endif
#if BFLOAT_ERRHANDLING_OVERFLOW_TO_INEXACT
if ((flags & FE_OVERFLOW) && !(flags & FE_INEXACT))
raise(FE_INEXACT);
#endif
#endif
}
/// Check and signal for any NaN.
/// \param x first bfloat16-precision value to check
/// \param y second bfloat16-precision value to check
/// \retval true if either \a x or \a y is NaN
/// \retval false else
/// \exception FE_INVALID if \a x or \a y is NaN
inline BFLOAT_CONSTEXPR_NOERR bool compsignal(unsigned int x, unsigned int y)
{
#if BFLOAT_ERRHANDLING
raise(FE_INVALID, (x & 0x7FFF) > 0x7F80 || (y & 0x7FFF) > 0x7F80);
#endif
return (x & 0x7FFF) > 0x7F80 || (y & 0x7FFF) > 0x7F80;
}
/// Signal and silence signaling NaN.
/// \param nan bfloat16-precision NaN value
/// \return quiet NaN
/// \exception FE_INVALID if \a nan is signaling NaN
inline BFLOAT_CONSTEXPR_NOERR unsigned int signal(unsigned int nan)
{
#if BFLOAT_ERRHANDLING
raise(FE_INVALID, !(nan & 0x40));
#endif
return nan | 0x7FFF;
}
/// Signal and silence signaling NaNs.
/// \param x first bfloat16-precision value to check
/// \param y second bfloat16-precision value to check
/// \return quiet NaN
/// \exception FE_INVALID if \a x or \a y is signaling NaN
inline BFLOAT_CONSTEXPR_NOERR unsigned int signal(unsigned int x, unsigned int y)
{
#if BFLOAT_ERRHANDLING
raise(FE_INVALID, ((x & 0x7FFF) > 0x7F80 && !(x & 0x40)) || ((y & 0x7FFF) > 0x7F80 && !(y & 0x40)));
#endif
return ((x & 0x7FFF) > 0x7F80) ? (x | 0x40) : (y | 0x40);
}
/// Signal and silence signaling NaNs.
/// \param x first bfloat16-precision value to check
/// \param y second bfloat16-precision value to check
/// \param z third bfloat16-precision value to check
/// \return quiet NaN
/// \exception FE_INVALID if \a x, \a y or \a z is signaling NaN
inline BFLOAT_CONSTEXPR_NOERR unsigned int signal(unsigned int x, unsigned int y, unsigned int z)
{
#if BFLOAT_ERRHANDLING
raise(FE_INVALID, ((x & 0x7FFF) > 0x7F80 && !(x & 0x40)) || ((y & 0x7FFF) > 0x7F80 && !(y & 0x40)) ||
((z & 0x7FFF) > 0x7F80 && !(z & 0x40)));
#endif
return ((x & 0x7FFF) > 0x7F80) ? (x | 0x40) : ((y & 0x7FFF) > 0x7F80) ? (y | 0x40) : (z | 0x40);
}
/// Select value or signaling NaN.
/// \param x preferred bfloat16-precision value
/// \param y ignored bfloat16-precision value except for signaling NaN
/// \return \a y if signaling NaN, \a x otherwise
/// \exception FE_INVALID if \a y is signaling NaN
inline BFLOAT_CONSTEXPR_NOERR unsigned int select(unsigned int x, unsigned BFLOAT_UNUSED_NOERR(y))
{
#if BFLOAT_ERRHANDLING
return (((y & 0x7FFF) > 0x7F80) && !(y & 0x40)) ? signal(y) : x;
#else
return x;
#endif
}
/// Raise domain error and return NaN.
/// return quiet NaN
/// \exception FE_INVALID
inline BFLOAT_CONSTEXPR_NOERR unsigned int invalid()
{
#if BFLOAT_ERRHANDLING
raise(FE_INVALID);
#endif
return 0x7FFF;
}
/// Raise pole error and return infinity.
/// \param sign bfloat16-precision value with sign bit only
/// \return bfloat16-precision infinity with sign of \a sign
/// \exception FE_DIVBYZERO
inline BFLOAT_CONSTEXPR_NOERR unsigned int pole(unsigned int sign = 0)
{
#if BFLOAT_ERRHANDLING
raise(FE_DIVBYZERO);
#endif
return sign | 0x7F80;
}
/// Check value for underflow.
/// \param arg non-zero bfloat16-precision value to check
/// \return \a arg
/// \exception FE_UNDERFLOW if arg is subnormal
inline BFLOAT_CONSTEXPR_NOERR unsigned int check_underflow(unsigned int arg)
{
#if BFLOAT_ERRHANDLING && !BFLOAT_ERRHANDLING_UNDERFLOW_TO_INEXACT
raise(FE_UNDERFLOW, !(arg & 0x7F80));
#endif
return arg;
}
/// \}
/// \name Conversion and rounding
/// \{
/// Bfloat16-precision overflow.
/// \tparam R rounding mode to use
/// \param sign bfloat16-precision value with sign bit only
/// \return rounded overflowing bfloat16-precision value
/// \exception FE_OVERFLOW
template <std::float_round_style R> BFLOAT_CONSTEXPR_NOERR unsigned int overflow(unsigned int sign = 0)
{
#if BFLOAT_ERRHANDLING
raise(FE_OVERFLOW);
#endif
return (R == std::round_toward_infinity) ? (sign + 0x7F80 - (sign >> 15))
: (R == std::round_toward_neg_infinity) ? (sign + 0x7F7F + (sign >> 15))
: (R == std::round_toward_zero) ? (sign | 0x7F7F)
: (sign | 0x7F80);
}
/// Bfloat16-precision underflow.
/// \tparam R rounding mode to use
/// \param sign bfloat16-precision value with sign bit only
/// \return rounded underflowing bfloat16-precision value
/// \exception FE_UNDERFLOW
template <std::float_round_style R> BFLOAT_CONSTEXPR_NOERR unsigned int underflow(unsigned int sign = 0)
{
#if BFLOAT_ERRHANDLING
raise(FE_UNDERFLOW);
#endif
return (R == std::round_toward_infinity) ? (sign + 1 - (sign >> 15))
: (R == std::round_toward_neg_infinity) ? (sign + (sign >> 15))
: sign;
}
/// Round bfloat16-precision number.
/// \tparam R rounding mode to use
/// \tparam I `true` to always raise INEXACT exception, `false` to raise only for rounded results
/// \param value finite bfloat16-precision number to round
/// \param g guard bit (most significant discarded bit)
/// \param s sticky bit (or of all but the most significant discarded bits)
/// \return rounded bfloat16-precision value
/// \exception FE_OVERFLOW on overflows
/// \exception FE_UNDERFLOW on underflows
/// \exception FE_INEXACT if value had to be rounded or \a I is `true`
template <std::float_round_style R, bool I>
BFLOAT_CONSTEXPR_NOERR unsigned int rounded(unsigned int value, int g, int s)
{
#if BFLOAT_ERRHANDLING
value += (R == std::round_to_nearest) ? (g & (s | value))
: (R == std::round_toward_infinity) ? (~(value >> 15) & (g | s))
: (R == std::round_toward_neg_infinity) ? ((value >> 15) & (g | s))
: 0;
if ((value & 0x7F80) == 0x7F80)
raise(FE_OVERFLOW);
else if (value & 0x7F80)
raise(FE_INEXACT, I || (g | s) != 0);
else
raise(FE_UNDERFLOW, !(BFLOAT_ERRHANDLING_UNDERFLOW_TO_INEXACT) || I || (g | s) != 0);
return value;
#else
return (R == std::round_to_nearest) ? (value + (g & (s | value)))
: (R == std::round_toward_infinity) ? (value + (~(value >> 15) & (g | s)))
: (R == std::round_toward_neg_infinity) ? (value + ((value >> 15) & (g | s)))
: value;
#endif
}
/// Round bfloat16-precision number to nearest integer value.
/// \tparam R rounding mode to use
/// \tparam E `true` for round to even, `false` for round away from zero
/// \tparam I `true` to raise INEXACT exception (if inexact), `false` to never raise it
/// \param value bfloat16-precision value to round
/// \return bfloat16-precision bits for nearest integral value
/// \exception FE_INVALID for signaling NaN
/// \exception FE_INEXACT if value had to be rounded and \a I is `true`
template <std::float_round_style R, bool E, bool I> unsigned int integral(unsigned int value)
{
unsigned int abs = value & 0x7FFF;
if (abs < 0x3F80) {
raise(FE_INEXACT, I);
return ((R == std::round_to_nearest) ? (0x3F80 & -static_cast<unsigned>(abs >= (0x3F00 + E)))
: (R == std::round_toward_infinity) ? (0x3F80 & -(~(value >> 15) & (abs != 0)))
: (R == std::round_toward_neg_infinity) ? (0x3F80 & -static_cast<unsigned>(value > 0x8000))
: 0) |
(value & 0x8000);
}
if (abs >= 0x6080)
return (abs > 0x7F80) ? signal(value) : value;
unsigned int exp = 70 - (abs >> 7), mask = (1 << exp) - 1;
raise(FE_INEXACT, I && (value & mask));
std::cout << std::endl; // without it, for some reason it does not calculate it
return ~((((R == std::round_to_nearest) ? ((1 << (exp - 1)) - (~(value >> exp) & E))
: (R == std::round_toward_neg_infinity) ? (mask & ((value >> 15) - 1))
: (R == std::round_toward_infinity) ? (mask & -(value >> 15))
: 0) -
value) &
~mask) +
1;
}
/// Convert fixed point to bfloat16-precision floating-point.
/// \tparam R rounding mode to use
/// \tparam F number of fractional bits (at least 11)
/// \tparam S `true` for signed, `false` for unsigned
/// \tparam N `true` for additional normalization step, `false` if already normalized to 1.F
/// \tparam I `true` to always raise INEXACT exception, `false` to raise only for rounded results
/// \param m mantissa in Q1.F fixed point format
/// \param exp exponent
/// \param sign bfloat16-precision value with sign bit only
/// \param s sticky bit (or of all but the most significant already discarded bits)
/// \return value converted to bfloat16-precision
/// \exception FE_OVERFLOW on overflows
/// \exception FE_UNDERFLOW on underflows
/// \exception FE_INEXACT if value had to be rounded or \a I is `true`
template <std::float_round_style R, unsigned int F, bool S, bool N, bool I>
unsigned int fixed2bfloat16(uint32 m, int exp = 14, unsigned int sign = 0, int s = 0)
{
if (S) {
uint32 msign = sign_mask(m);
m = (m ^ msign) - msign;
sign = msign & 0x8000;
}
if (N)
for (; m < (static_cast<uint32>(1) << F) && exp; m <<= 1, --exp)
;
else if (exp < 0)
return rounded<R, I>(sign + (m >> (F - 7 - exp)), (m >> (F - 8 - exp)) & 1,
s | ((m & ((static_cast<uint32>(1) << (F - 8 - exp)) - 1)) != 0));
return rounded<R, I>(sign + (exp << 7) + (m >> (F - 7)), (m >> (F - 8)) & 1,
s | ((m & ((static_cast<uint32>(1) << (F - 8)) - 1)) != 0));
}
/// Convert IEEE single-precision to bfloat16-precision.
/// \tparam R rounding mode to use
/// \param value single-precision value to convert
/// \return rounded float16-precision value
/// \exception FE_OVERFLOW on overflows
/// \exception FE_UNDERFLOW on underflows
/// \exception FE_INEXACT if value had to be rounded
template <std::float_round_style R> unsigned int float2bfloat16_impl(float value, true_type)
{
bits<float>::type fbits;
std::memcpy(&fbits, &value, sizeof(float));
unsigned int sign = (fbits >> 16) & 0x8000;
fbits &= 0x7FFFFFFF;
if (fbits >= 0x7F800000)
return sign | 0x7F80 | ((fbits > 0x7F800000) ? (0x40 | ((fbits >> 13) & 0x7F)) : 0);
if (fbits >= 0x47800000)
return overflow<R>(sign);
if (fbits >= 0x38800000) {
return ((fbits >> 16) | sign);
}
if (fbits >= 0x33000000) {
int i = 125 - (fbits >> 23);
fbits = (fbits & 0x7FFFFF) | 0x800000;
return rounded<R, false>(sign | (fbits >> (i + 1)), (fbits >> i) & 1,
(fbits & ((static_cast<uint32>(1) << i) - 1)) != 0);
}
if (fbits != 0)
return underflow<R>(sign);
return sign;
}
/// Convert IEEE double-precision to bfloat16-precision.
/// \tparam R rounding mode to use
/// \param value double-precision value to convert
/// \return rounded bfloat16-precision value
/// \exception FE_OVERFLOW on overflows
/// \exception FE_UNDERFLOW on underflows
/// \exception FE_INEXACT if value had to be rounded
template <std::float_round_style R> unsigned int float2bfloat16_impl(double value, true_type)
{
bits<double>::type dbits;
std::memcpy(&dbits, &value, sizeof(double));
uint32 hi = dbits >> 32, lo = dbits & 0xFFFFFFFF;
unsigned int sign = (hi >> 16) & 0x8000;
hi &= 0x7FFFFFFF;
if (hi >= 0x7FF00000)
return sign | 0x7F80 | ((dbits & 0xFFFFFFFFFFFFF) ? (0x40 | ((hi >> 10) & 0x7F)) : 0);
if (hi >= 0x40F00000)
return overflow<R>(sign);
if (hi >= 0x3F100000)
return rounded<R, false>(sign | (((hi >> 20) - 1008) << 10) | ((hi >> 10) & 0x7F), (hi >> 9) & 1,
((hi & 0x3F) | lo) != 0);
if (hi >= 0x3E600000) {
int i = 1018 - (hi >> 20);
hi = (hi & 0xFFFFF) | 0x100000;
return rounded<R, false>(sign | (hi >> (i + 1)), (hi >> i) & 1,
((hi & ((static_cast<uint32>(1) << i) - 1)) | lo) != 0);
}
if ((hi | lo) != 0)
return underflow<R>(sign);
return sign;
}
/// Convert non-IEEE floating-point to bfloat16-precision.
/// \tparam R rounding mode to use
/// \tparam T source type (builtin floating-point type)
/// \param value floating-point value to convert
/// \return rounded bfloat16-precision value
/// \exception FE_OVERFLOW on overflows
/// \exception FE_UNDERFLOW on underflows
/// \exception FE_INEXACT if value had to be rounded
template <std::float_round_style R, typename T> unsigned int float2bfloat16_impl(T value, ...)
{
unsigned int hbits = static_cast<unsigned>(builtin_signbit(value)) << 15;
if (value == T())
return hbits;
if (builtin_isnan(value))
return hbits | 0x7FFF;
if (builtin_isinf(value))
return hbits | 0x7F80;
int exp;
std::frexp(value, &exp);
if (exp > 128)
return overflow<R>(hbits);
if (exp < -125)
value = std::ldexp(value, 25);
else {
value = std::ldexp(value, 124 - exp);
hbits |= ((exp + 125) << 7);
}
T ival, frac = std::modf(value, &ival);
int m = std::abs(static_cast<int>(ival));
return rounded<R, false>(hbits + (m >> 1), m & 1, frac != T());
}
/// Convert floating-point to bfloat16-precision.
/// \tparam R rounding mode to use
/// \tparam T source type (builtin floating-point type)
/// \param value floating-point value to convert
/// \return rounded bfloat16-precision value
/// \exception FE_OVERFLOW on overflows
/// \exception FE_UNDERFLOW on underflows
/// \exception FE_INEXACT if value had to be rounded
template <std::float_round_style R, typename T> unsigned int float2bfloat16(T value)
{
return float2bfloat16_impl<R>(value, bool_type < std::numeric_limits<T>::is_iec559 &&
sizeof(typename bits<T>::type) == sizeof(T) > ());
}
/// Convert integer to bfloat16-precision floating-point.
/// \tparam R rounding mode to use
/// \tparam T type to convert (builtin integer type)
/// \param value integral value to convert
/// \return rounded bfloat16-precision value
/// \exception FE_OVERFLOW on overflows
/// \exception FE_INEXACT if value had to be rounded
template <std::float_round_style R, typename T> unsigned int int2bfloat16(T value)
{
unsigned int bits = static_cast<unsigned>(value < 0) << 15;
if (!value)
return bits;
if (bits)
value = -value;
if (value > 0xFFFF)
return overflow<R>(bits);
unsigned int m = static_cast<unsigned int>(value), exp = 133;
for (; m < 0x80; m <<= 1, --exp)
;
for (; m > 0xFF; m >>= 1, ++exp)
;
bits |= (exp << 7) + m;
return (exp > 133) ? rounded<R, false>(bits, (value >> (exp - 134)) & 1, (((1 << (exp - 134)) - 1) & value) != 0)
: bits;
}
/// temp Function for conversion, because compiler converts bfloat intern for some reason, so sometimes it converts
/// bfloat16 -> float32 -> float32, and because of bitshift it destroys the value
// \param value bfloat16-precision value to convert
// \return single-precision value
// bfloat16 -> float32.
inline float bfloat162float_temp(unsigned int value)
{
bits<float>::type fbits = static_cast<bits<float>::type>(value) << 16;
float out;
std::memcpy(&out, &fbits, sizeof(float));
return out;
}
/// Convert bfloat16-precision to IEEE single-precision.
/// \param value bfloat16-precision value to convert
/// \return single-precision value
inline float bfloat162float_impl(unsigned int value, float, true_type)
{
// bits<float>::type fbits = static_cast<bits<float>::type>(value) <<16;
bits<float>::type out;
// float out;
// std::memcpy(&out, &fbits, sizeof(float));
std::memcpy(&out, &value, sizeof(float));
return out;
}
/// Convert bfloat16-precision to IEEE double-precision.
/// \param value bfloat16-precision value to convert
/// \return double-precision value
inline double bfloat162float_impl(unsigned int value, double, true_type)
{
uint32 hi = static_cast<uint32>(value & 0x8000) << 16;
unsigned int abs = value & 0x7FFF;
if (abs) {
hi |= 0x3F000000 << static_cast<unsigned>(abs >= 0x7C00);
for (; abs < 0x80; abs <<= 1, hi -= 0x100000)
;
hi += static_cast<uint32>(abs) << 10;
}
bits<double>::type dbits = static_cast<bits<double>::type>(hi) << 32;
double out;
std::memcpy(&out, &dbits, sizeof(double));
return out;
}
/// Convert bfloat16-precision to non-IEEE floating-point.
/// \tparam T type to convert to (builtin integer type)
/// \param value bfloat16-precision value to convert
/// \return floating-point value
template <typename T> T bfloat162float_impl(unsigned int value, T, ...)
{
T out;
unsigned int abs = value & 0x7FFF;
if (abs > 0x7F80)
out = (std::numeric_limits<T>::has_signaling_NaN && !(abs & 0x40)) ? std::numeric_limits<T>::signaling_NaN()
: std::numeric_limits<T>::has_quit_NaN ? std::numeric_limits<T>::quit_NaN()
: T();
else if (abs == 0x7F80)
out = std::numeric_limits<T>::has_infinity ? std::numeric_limits<T>::infinity() : std::numeric_limits<T>::max();
else if (abs > 0x7F)
out = std::ldexp(static_cast<T>((abs & 0x7F) | 0x80), (abs >> 10) - 25);
else
out = std::ldexp(static_cast<T>(abs), -24);
return (value & 0x8000) ? -out : out;
}
/// Convert bfloat16-precision to floating-point.
/// \tparam T type to convert to (builtin integer type)
/// \param value bfloat16-precision value to convert
/// \return floating-point value
template <typename T> T bfloat162float(unsigned int value)
{
return bfloat162float_impl(
value, T(), bool_type < std::numeric_limits<T>::is_iec559 && sizeof(typename bits<T>::type) == sizeof(T) > ());
}
/// Convert bfloat16-precision floating-point to integer.
/// \tparam R rounding mode to use
/// \tparam E `true` for round to even, `false` for round away from zero
/// \tparam I `true` to raise INEXACT exception (if inexact), `false` to never raise it
/// \tparam T type to convert to (buitlin integer type with at least 16 bits precision, excluding any implicit sign
/// bits) \param value bfloat16-precision value to convert \return rounded integer value \exception FE_INVALID if value
/// is not representable in type \a T \exception FE_INEXACT if value had to be rounded and \a I is `true`
template <std::float_round_style R, bool E, bool I, typename T> T bfloat162int(unsigned int value)
{
unsigned int abs = value & 0x7FFF;
if (abs >= 0x7F80) {
raise(FE_INVALID);
return (value & 0x8000) ? std::numeric_limits<T>::min() : std::numeric_limits<T>::max();
}
if (abs < 0x3F00) {
raise(FE_INEXACT, I);
return (R == std::round_toward_infinity) ? T(~(value >> 15) & (abs != 0))
: (R == std::round_toward_neg_infinity) ? -T(value > 0x8000)
: T();
}
int exp = 134 - (abs >> 7);
unsigned int m = (value & 0x7F) | 0x80;
int32 i = static_cast<int32>(
(exp <= 0) ? (m << -exp)
: ((m + ((R == std::round_to_nearest) ? ((1 << (exp - 1)) - (~(m >> exp) & E))
: (R == std::round_toward_infinity) ? (((1 << exp) - 1) & ((value >> 15) - 1))
: (R == std::round_toward_neg_infinity) ? (((1 << exp) - 1) & -(value >> 15))
: 0)) >>
exp));
if ((!std::numeric_limits<T>::is_signed && (value & 0x8000)) ||
(std::numeric_limits<T>::digits < 16 &&
((value & 0x8000) ? (-i < std::numeric_limits<T>::min()) : (i > std::numeric_limits<T>::max()))))
raise(FE_INVALID);
else if (I && exp > 0 && (m & ((1 << exp) - 1)))
raise(FE_INEXACT);
return static_cast<T>((value & 0x8000) ? -i : i);
}
/// \}
/// \name Mathematics
/// \{
/// upper part of 64-bit multiplication.
/// \tparam R rounding mode to use
/// \param x first factor
/// \param y second factor
/// \return upper 32 bit of \a x * \a y
template <std::float_round_style R> uint32 mulhi(uint32 x, uint32 y)
{
uint32 xy = (x >> 16) * (y & 0xFFFF), yx = (x & 0xFFFF) * (y >> 16),
c = (xy & 0xFFFF) + (yx & 0xFFFF) + (((x & 0xFFFF) * (y & 0xFFFF)) >> 16);
return (x >> 16) * (y >> 16) + (xy >> 16) + (yx >> 16) + (c >> 16) +
((R == std::round_to_nearest) ? ((c >> 15) & 1)
: (R == std::round_toward_infinity) ? ((c & 0xFFFF) != 0)
: 0);
}
/// 64-bit multiplication.
/// \param x first factor
/// \param y second factor
/// \return upper 32 bit of \a x * \a y rounded to nearest
inline uint32 multiply64(uint32 x, uint32 y)
{
#if BFLOAT_ENABLE_CPP11_LONG_LONG
return static_cast<uint32>((static_cast<unsigned long long>(x) * static_cast<unsigned long long>(y) + 0x80000000) >>
32);
#else
return mulhi<std::round_to_nearest>(x, y);
#endif
}
/// 64-bit division.
/// \param x upper 32 bit of dividend
/// \param y divisor
/// \param s variable to store sticky bit for rounding
/// \return (\a x << 32) / \a y
inline uint32 divide64(uint32 x, uint32 y, int &s)
{
#if BFLOAT_ENABLE_CPP11_LONG_LONG
unsigned long long xx = static_cast<unsigned long long>(x) << 32;
return s = (xx % y != 0), static_cast<uint32>(xx / y);
#else
y >>= 1;
uint32 rem = x, div = 0;
for (unsigned int i = 0; i < 32; ++i) {
div <<= 1;
if (rem >= y) {
rem -= y;
div |= 1;
}
rem <<= 1;
}
return s = rem > 1, div;
#endif
}
/// Bfloat16 precision positive modulus.
/// \tparam Q `true` to compute full quotient, `false` else
/// \tparam R `true` to compute signed remainder, `false` for positive remainder
/// \param x first operand as positive finite bfloat16-precision value
/// \param y second operand as positive finite bfloat16-precision value
/// \param quo adress to store quotient at, `nullptr` if \a Q `false`
/// \return modulus of \a x / \a y
template <bool Q, bool R> unsigned int mod(unsigned int x, unsigned int y, int *quo = NULL)
{
unsigned int q = 0;
if (x > y) {
int absx = x, absy = y, expx = 0, expy = 0;
for (; absx < 0x80; absx <<= 1, --expx)
;
for (; absy < 0x80; absy <<= 1, --expy)
;
expx += absx >> 7;
expy += absy >> 7;
int mx = (absx & 0x7F) | 0x80, my = (absy & 0x7F) | 0x80;
for (int d = expx - expy; d; --d) {
if (!Q && mx == my)
return 0;
if (mx >= my) {
mx -= my;
q += Q;
}
mx <<= 1;
q <<= static_cast<int>(Q);
}
if (!Q && mx == my)
return 0;
if (mx >= my) {
mx -= my;
++q;
}
if (Q) {
q &= (1 << (std::numeric_limits<int>::digits - 1)) - 1;
if (!mx)
return *quo = q, 0;
}
for (; mx < 0x80; mx <<= 1, --expy)
;
x = (expy > 0) ? ((expy << 7) | (mx & 0x7F)) : (mx >> (1 - expy));
}
if (R) {
unsigned int a, b;
if (y < 0x100) {
a = (x < 0x80) ? (x << 1) : (x + 0x80);
b = y;
} else {
a = x;
b = y - 0x80;
}
if (a > b || (a == b && (q & 1))) {
int exp = (y >> 7) + (y <= 0x7F), d = exp - (x >> 7) - (x <= 0x7F);
int m = (((y & 0x7F) | ((y > 0x7F) << 7)) << 1) - (((x & 0x7F) | ((x > 0x7F) << 7)) << (1 - d));
for (; m < 0x100 && exp > 1; m <<= 1, --exp)
;
x = 0x8000 + ((exp - 1) << 7) + (m >> 1);
q += Q;
}
}
if (Q)
*quo = q;
return x;
}
/// Fixed point square root.
/// \tparam F number of fractional bits
/// \param r radicand in Q1.F fixed point format
/// \param exp exponent
/// \return square root as Q1.F/2
template <unsigned int F> uint32 sqrt(uint32 &r, int &exp)
{
int i = exp & 1;
r <<= i;
exp = (exp - i) / 2;
uint32 m = 0;
for (uint32 bit = static_cast<uint32>(1) << F; bit; bit >>= 2) {
if (r < m + bit)
m >>= 1;
else {
r -= m + bit;
m = (m >> 1) + bit;
}
}
return m;
}
/// Fixed point binary exponential.
/// This uses the BKM algorithm in E-mode.
/// \param m exponent in [0,1) as Q0.31
/// \param n number of iterations (at most 32)
/// \return 2 ^ \a m as Q1.31
inline uint32 exp2(uint32 m, unsigned int n = 32)
{
static const uint32 logs[] = {0x80000000, 0x4AE00D1D, 0x2934F098, 0x15C01A3A, 0x0B31FB7D, 0x05AEB4DD, 0x02DCF2D1,
0x016FE50B, 0x00B84E23, 0x005C3E10, 0x002E24CA, 0x001713D6, 0x000B8A47, 0x0005C53B,
0x0002E2A3, 0x00017153, 0x0000B8AA, 0x00005C55, 0x00002E2B, 0x00001715, 0x00000B8B,
0x000005C5, 0x000002E3, 0x00000171, 0x000000B9, 0x0000005C, 0x0000002E, 0x00000017,
0x0000000C, 0x00000006, 0x00000003, 0x00000001};
if (!m)
return 0x80000000;
uint32 mx = 0x80000000, my = 0;
for (unsigned int i = 1; i < n; ++i) {
uint32 mz = my + logs[i];
if (mz <= m) {
my = mz;
mx += mx >> i;
}
}
return mx;
}
/// Fixed point binary logarithm.
/// This uses the BKM algorithm in L-mode.
/// \param m mantissa in [1,2) as Q1.30
/// \param n number of iterations (at most 32)
/// \return log2(\a m) as Q0.31
inline uint32 log2(uint32 m, unsigned int n = 32)
{
static const uint32 logs[] = {0x80000000, 0x4AE00D1D, 0x2934F098, 0x15C01A3A, 0x0B31FB7D, 0x05AEB4DD, 0x02DCF2D1,
0x016FE50B, 0x00B84E23, 0x005C3E10, 0x002E24CA, 0x001713D6, 0x000B8A47, 0x0005C53B,
0x0002E2A3, 0x00017153, 0x0000B8AA, 0x00005C55, 0x00002E2B, 0x00001715, 0x00000B8B,
0x000005C5, 0x000002E3, 0x00000171, 0x000000B9, 0x0000005C, 0x0000002E, 0x00000017,
0x0000000C, 0x00000006, 0x00000003, 0x00000001};
if (m == 0x40000000)
return 0;
uint32 mx = 0x40000000, my = 0;
for (unsigned int i = 1; i < n; ++i) {
uint32 mz = mx + (mx >> i);
if (mz <= m) {
mx = mz;
my += logs[i];
}
}
return my;
}
/// Fixed point sine and cosine.
/// This uses the CORDIC algorithm in rotation mode.
/// \param mz angle in [-pi/2,pi/2] as Q1.30
/// \param n number of iterations (at most 31)
/// \return sine and cosine of \a mz as Q1.30
inline std::pair<uint32, uint32> sincos(uint32 mz, unsigned int n = 31)
{
static const uint32 angles[] = {0x3243F6A9, 0x1DAC6705, 0x0FADBAFD, 0x07F56EA7, 0x03FEAB77, 0x01FFD55C, 0x00FFFAAB,
0x007FFF55, 0x003FFFEB, 0x001FFFFD, 0x00100000, 0x00080000, 0x00040000, 0x00020000,
0x00010000, 0x00008000, 0x00004000, 0x00002000, 0x00001000, 0x00000800, 0x00000400,
0x00000200, 0x00000100, 0x00000080, 0x00000040, 0x00000020, 0x00000010, 0x00000008,
0x00000004, 0x00000002, 0x00000001};
uint32 mx = 0x26DD3B6A, my = 0;
for (unsigned int i = 0; i < n; ++i) {
uint32 sign = sign_mask(mz);
uint32 tx = mx - (arithmetic_shift(my, i) ^ sign) + sign;
uint32 ty = my - (arithmetic_shift(mx, i) ^ sign) - sign;
mx = tx;
my = ty;
mz -= (angles[i] ^ sign) - sign;
}
return std::make_pair(my, mx);
}
/// Fixed point arc tangent.
/// This uses the CORDIC algorithm in vectoring mode.
/// \param my y coordinate as Q0.30
/// \param mx x coordinate as Q0.30
/// \param n number of iterations (at most 31)
/// \return arc tangent of \a my / \a mx as Q1.30
inline uint32 atan2(uint32 my, uint32 mx, unsigned int n = 31)
{
static const uint32 angles[] = {0x3243F6A9, 0x1DAC6705, 0x0FADBAFD, 0x07F56EA7, 0x03FEAB77, 0x01FFD55C, 0x00FFFAAB,
0x007FFF55, 0x003FFFEB, 0x001FFFFD, 0x00100000, 0x00080000, 0x00040000, 0x00020000,
0x00010000, 0x00008000, 0x00004000, 0x00002000, 0x00001000, 0x00000800, 0x00000400,
0x00000200, 0x00000100, 0x00000080, 0x00000040, 0x00000020, 0x00000010, 0x00000008,
0x00000004, 0x00000002, 0x00000001};
uint32 mz = 0;
for (unsigned int i = 0; i < n; ++i) {
uint32 sign = sign_mask(my);
uint32 tx = mx + (arithmetic_shift(my, i) ^ sign) - sign;
uint32 ty = my - (arithmetic_shift(mx, i) ^ sign) + sign;
mx = tx;
my = ty;
mz += (angles[i] ^ sign) - sign;
}
return mz;
}
/// Reduce argument for trigonometric functions.
/// \param abs bfloat16-precision floating-point value
/// \param k value to take quarter period
/// \return \a abs reduced to [-pi/4,pi/4] as Q0.30
inline uint32 angle_arg(unsigned int abs, int &k)
{
uint32 m = (abs & 0x3FF) | ((abs > 0x3FF) << 10);
int exp = (abs >> 10) + (abs <= 0x3FF) - 15;
if (abs < 0x3A48)
return k = 0, m << (exp + 20);
#if BFLOAT_ENABLE_CPP11_LONG_LONG
unsigned long long y = m * 0xA2F9836E4E442, mask = (1ULL << (62 - exp)) - 1, yi = (y + (mask >> 1)) & ~mask,
f = y - yi;
uint32 sign = -static_cast<uint32>(f >> 63);
k = static_cast<int>(yi >> (62 - exp));
return (multiply64(static_cast<uint32>((sign ? -f : f) >> (31 - exp)), 0xC90FDAA2) ^ sign) - sign;
#else
uint32 yh = m * 0xA2F98 + mulhi<std::round_toward_zero>(m, 0x36E4E442), yl = (m * 0x36E4E442) & 0xFFFFFFFF;
uint32 mask = (static_cast<uint32>(1) << (30 - exp)) - 1, yi = (yh + (mask >> 1)) & ~mask,
sign = -static_cast<uint32>(yi > yh);
k = static_cast<int>(yi >> (30 - exp));
uint32 fh = (yh ^ sign) + (yi ^ ~sign) - ~sign, fl = (yl ^ sign) - sign;
return (multiply64((exp > -1) ? (((fh << (1 + exp)) & 0xFFFFFFFF) | ((fl & 0xFFFFFFFF) >> (31 - exp))) : fh,
0xC90FDAA2) ^
sign) -
sign;
#endif
}
/// Get arguments for atan2 function.
/// \param abs bfloat16-precision floating-point value
/// \return \a abs and sqrt(1 - \a abs^2) as Q0.30
inline std::pair<uint32, uint32> atan2_arg(unsigned int abs)
{
int exp = -15;
for (; abs < 0x80; abs <<= 1, --exp)
;
exp += abs >> 10;
uint32 my = ((abs & 0x7F) | 0x80) << 5, r = my * my;
int rexp = 2 * exp;
r = 0x40000000 - ((rexp > -31) ? ((r >> -rexp) | ((r & ((static_cast<uint32>(1) << -rexp) - 1)) != 0)) : 1);
for (rexp = 0; r < 0x40000000; r <<= 1, --rexp)
;
uint32 mx = sqrt<30>(r, rexp);
int d = exp - rexp;
if (d < 0)
return std::make_pair((d < -14) ? ((my >> (-d - 14)) + ((my >> (-d - 15)) & 1)) : (my << (14 + d)),
(mx << 14) + (r << 13) / mx);
if (d > 0)
return std::make_pair(my << 14, (d > 14) ? ((mx >> (d - 14)) + ((mx >> (d - 15)) & 1))
: ((d == 14) ? mx : ((mx << (14 - d)) + (r << (13 - d)) / mx)));
return std::make_pair(my << 13, (mx << 13) + (r << 12) / mx);
}
/// Get exponentials for hyperbolic computation
/// \param abs bfloat16-precision floating-point value
/// \param exp variable to take unbiased exponent of larger result
/// \param n number of BKM iterations (at most 32)
/// \return exp(abs) and exp(-\a abs) as Q1.31 with same exponent
inline std::pair<uint32, uint32> hyperbolic_args(unsigned int abs, int &exp, unsigned int n = 32)
{
uint32 mx = detail::multiply64(static_cast<uint32>((abs & 0x3FF) + ((abs > 0x7F) << 10)) << 21, 0xB8AA3B29), my;
int e = (abs >> 10) + (abs <= 0x7F);
if (e < 14) {
exp = 0;
mx >>= 14 - e;
} else {
exp = mx >> (45 - e);
mx = (mx << (e - 14)) & 0x7FFFFFFF;
}
mx = exp2(mx, n);
int d = exp << 1, s;
if (mx > 0x80000000) {
my = divide64(0x80000000, mx, s);
my |= s;
++d;
} else
my = mx;
return std::make_pair(mx, (d < 31) ? ((my >> d) | ((my & ((static_cast<uint32>(1) << d) - 1)) != 0)) : 1);
}
/// Postprocessing for binary exponential.
/// \tparam R rounding mode to use
/// \tparam I `true` to always raise INEXACT exception, `false` to raise only for rounded results
/// \param m mantissa as Q1.31
/// \param exp absolute value of unbiased exponent
/// \param esign sign of actual exponent
/// \param sign sign bit of result
/// \return value converted to bfloat16-precision
/// \exception FE_OVERFLOW on overflows
/// \exception FE_UNDERFLOW on underflows
/// \exception FE_INEXACT if value had to be rounded or \a I is `true`
template <std::float_round_style R, bool I> unsigned int exp2_post(uint32 m, int exp, bool esign, unsigned int sign = 0)
{
int s = 0;
if (esign) {
if (m > 0x80000000) {
m = divide64(0x80000000, m, s);
++exp;
}
if (exp > 25)
return underflow<R>(sign);
else if (exp == 25)
return rounded<R, I>(sign, 1, (m & 0x7FFFFFFF) != 0);
exp = -exp;
} else if (exp > 127) // 15
return overflow<R>(sign);
return fixed2bfloat16<R, 31, false, false, I>(m, exp + 14, sign, s);
}
/// Postprocessing for binary logarithm.
/// \tparam R rounding mode to use
/// \tparam L logarithm for base transformation as Q1.31
/// \param m fractional part of logarithm as Q0.31
/// \param ilog signed integer part of logarithm
/// \param exp biased exponent of result
/// \param sign sign bit of result
/// \return value base-transformed and converted to bfloat16-precision
/// \exception FE_OVERFLOW on overflows
/// \exception FE_UNDERFLOW on underflows
/// \exception FE_INEXACT if no other exception occurred
template <std::float_round_style R, uint32 L> unsigned int log2_post(uint32 m, int ilog, int exp, unsigned int sign = 0)
{
uint32 msign = sign_mask(ilog);
m = (((static_cast<uint32>(ilog) << 27) + (m >> 4)) ^ msign) - msign;
if (!m)
return 0;
for (; m < 0x80000000; m <<= 1, --exp)
;
int i = m >= L, s;
exp += i;
m >>= 1 + i;
sign ^= msign & 0x8000;
if (exp < -11)
return underflow<R>(sign);
m = divide64(m, L, s);
return fixed2bfloat16<R, 30, false, false, true>(m, exp, sign, 1);
}
/// Hypotenuse square root and postprocessing.
/// \tparam R rounding mode to use
/// \param r mantissa as Q2.30
/// \param exp unbiased exponent
/// \return square root converted to bfloat16-precision
/// \exception FE_OVERFLOW on overflows
/// \exception FE_UNDERFLOW on underflows
/// \exception FE_INEXACT if value had to be rounded
template <std::float_round_style R> unsigned int hypot_post(uint32 r, int exp)
{
int i = r >> 31;
if ((exp += i) > 46)
return overflow<R>();
if (exp < -34)
return underflow<R>();
r = (r >> i) | (r & i);
uint32 m = sqrt<30>(r, exp += 15);
return fixed2bfloat16<R, 15, false, false, false>(m, exp - 1, 0, r != 0);
}
/// Division and postprocessing for tangents.
/// \tparam R rounding mode to use
/// \param my dividend as Q1.31
/// \param mx divisor as Q1.31
/// \param exp biased exponent of result
/// \param sign sign bit of result
/// \return quotient converted to bfloat16-precision
/// \exception FE_OVERFLOW on overflows
/// \exception FE_UNDERFLOW on underflows
/// \exception FE_INEXACT if no other exception occurred
template <std::float_round_style R> unsigned int tangent_post(uint32 my, uint32 mx, int exp, unsigned int sign = 0)
{
int i = my >= mx, s;
exp += i;
if (exp > 29)
return overflow<R>(sign);
if (exp < -11)
return underflow<R>(sign);
uint32 m = divide64(my >> (i + 1), mx, s);
return fixed2bfloat16<R, 30, false, false, true>(m, exp, sign, s);
}
/// Area function and postprocessing.
/// This computes the value directly in Q2.30 using the representation `asinh|acosh(x) = log(x+sqrt(x^2+|-1))`.
/// \tparam R rounding mode to use
/// \tparam S `true` for asinh, `false` for acosh
/// \param arg bfloat16-precision argument
/// \return asinh|acosh(\a arg) converted to bfloat16-precision
/// \exception FE_OVERFLOW on overflows
/// \exception FE_UNDERFLOW on underflows
/// \exception FE_INEXACT if no other exception occurred
template <std::float_round_style R, bool S> unsigned int area(unsigned int arg)
{
int abs = arg & 0x7FFF, expx = (abs >> 10) + (abs <= 0x7F) - 15, expy = -15, ilog, i;
uint32 mx = static_cast<uint32>((abs & 0x7F) | ((abs > 0x7F) << 10)) << 20, my, r;
for (; abs < 0x80; abs <<= 1, --expy)
;
expy += abs >> 10;
r = ((abs & 0x7F) | 0x80) << 5;
r *= r;
i = r >> 31;
expy = 2 * expy + i;
r >>= i;
if (S) {
if (expy < 0) {
r = 0x40000000 + ((expy > -30) ? ((r >> -expy) | ((r & ((static_cast<uint32>(1) << -expy) - 1)) != 0)) : 1);
expy = 0;
} else {
r += 0x40000000 >> expy;
i = r >> 31;
r = (r >> i) | (r & i);
expy += i;
}
} else {
r -= 0x40000000 >> expy;
for (; r < 0x40000000; i <<= 1, --expy)
;
}
my = sqrt<30>(r, expy);
my = (my << 15) + (r << 14) / my;
if (S) {
mx >>= expy - expx;
ilog = expy;
} else {
my >>= expx - expy;
ilog = expx;
}
my += mx;
i = my >> 31;
static const int G = S && (R == std::round_to_nearest);
return log2_post<R, 0xB8AA3B2A>(log2(my >> i, 26 + S + G) + (G << 3), ilog + i, 17,
arg & (static_cast<unsigned>(S) << 15));
}
/// Class for 1.31 unsigned floating-point computation
struct f31 {
/// Constructor.
/// \param mant mantissa as 1.31
/// \param e exponent
BFLOAT_CONSTEXPR f31(uint32 mant, int e) : m(mant), exp(e) {}
/// Constructor.
/// \param abs unsigned bfloat16-precision value
f31(unsigned int abs) : exp(-15)
{
for (; abs < 0x80; abs <<= 1, --exp)
;
m = static_cast<uint32>((abs & 0x7F) | 0x80) << 24;
exp += (abs >> 7);
}
/// Addition operator.
/// \param a first operand
/// \param b second operand
/// \return \a a + \a b
friend f31 operator+(f31 a, f31 b)
{
if (b.exp > a.exp)
std::swap(a, b);
int d = a.exp - b.exp;
uint32 m = a.m + ((d < 32) ? (b.m >> d) : 0);
int i = (m & 0xFFFFFFFF) < a.m;
return f31(((m + i) >> i) | 0x80000000, a.exp + i);
}
/// Subtraction operator.
/// \param a first operand
/// \param b second operand
/// \return \a a - \a b
friend f31 operator-(f31 a, f31 b)
{
int d = a.exp - b.exp, exp = a.exp;
uint32 m = a.m - ((d < 32) ? (b.m >> d) : 0);
if (!m)
return f31(0, -32);
for (; m < 0x80000000; m <<= 1, --exp)
;
return f31(m, exp);
}
/// Multiplication operator.
/// \param a first operand
/// \param b second operand
/// \return \a a * \a b
friend f31 operator*(f31 a, f31 b)
{
uint32 m = multiply64(a.m, b.m);
int i = m >> 31;
return f31(m << (1 - i), a.exp + b.exp + i);
}
/// Division operator.
/// \param a first operand
/// \param b second operand
/// \return \a a / \a b
friend f31 operator/(f31 a, f31 b)
{
int i = a.m >= b.m, s;
uint32 m = divide64((a.m + i) >> i, b.m, s);
return f31(m, a.exp - b.exp + i - 1);
}
uint32 m; ///< mantissa as 1.31.
int exp; ///< exponent.
};
/// \}
/// \name Mathematics
/// \{
/// Error function and postprocessing.
/// This computes the value directly in Q1.31 using the approximations given
/// [here](https://en.wikipedia.org/wiki/Error_function#Approximation_with_elementary_functions).
/// \tparam R rounding mode to use
/// \tparam C `true` for comlementary error function, `false` else
/// \param arg bfloat16-precision function argument
/// \return approximated value of error function in bfloat16-precision
/// \exception FE_OVERFLOW on overflows
/// \exception FE_UNDERFLOW on underflows
/// \exception FE_INEXACT if no other exception occurred
template <std::float_round_style R, bool C> unsigned int erf(unsigned int arg)
{
unsigned int abs = arg & 0x7FFF, sign = arg & 0x8000;
f31 x(abs), x2 = x * x * f31(0xB8AA3B29, 0),
t = f31(0x80000000, 0) / (f31(0x80000000, 0) + f31(0xA7BA054A, -2) * x), t2 = t * t;
f31 e = ((f31(0x87DC2213, 0) * t2 + f31(0xB5F0E2AE, 0)) * t2 + f31(0x82790637, -2) -
(f31(0xBA00E2B8, 0) * t2 + f31(0x91A98E62, -2)) * t) *
t /
((x2.exp < 0) ? f31(exp2((x2.exp > -32) ? (x2.m >> -x2.exp) : 0, 30), 0)
: f31(exp2((x2.m << x2.exp) & 0x7FFFFFFFF, 22), x2.m >> (31 - x2.exp)));
return (!C || sign)
? fixed2bfloat16<R, 31, false, true, true>(0x80000000 - (e.m >> (C - e.exp)), 14 + C, sign & (C - 1U))
: (e.exp < -25) ? underflow<R>()
: fixed2bfloat16<R, 30, false, false, true>(e.m >> 1, e.exp + 14, 0, e.m & 1);
}
/// Gamma function and postprocessing.
/// This approximates the value of either the gamma function or its logarithm directly in Q1.31.
/// \tparam R rounding mode to use
/// \tparam L `true` for lograithm of gamma function, `false` for gamma function
/// \param arg bfloat16-precision floating-point value
/// \return lgamma/tgamma(\a arg) in bfloat16-precision
/// \exception FE_OVERFLOW on overflows
/// \exception FE_UNDERFLOW on underflows
/// \exception FE_INEXACT if \a arg is not a positive integer
template <std::float_round_style R, bool L> unsigned int gamma(unsigned int arg)
{
/*
static const double p[] ={ 2.50662827563479526904, 225.525584619175212544,
-268.295973841304927459, 80.9030806934622512966, -5.00757863970517583837, 0.0114684895434781459556 }; double t = arg
+ 4.65, s = p[0]; for(unsigned int i=0; i<5; ++i) s += p[i+1] / (arg+i); return std::log(s) + (arg-0.5)*std::log(t) - t;
*/
static const f31 pi(0xC90FDAA2, 1), lbe(0xB8AA3B29, 0);
unsigned int abs = arg & 0x7FFF, sign = arg & 0x8000;
bool bsign = sign != 0;
f31 z(abs), x = sign ? (z + f31(0x80000000, 0)) : z, t = x + f31(0x94CCCCCD, 2),
s = f31(0xA06C9901, 1) + f31(0xBBE654E2, -7) / (x + f31(0x80000000, 2)) +
f31(0xA1CE6098, 6) / (x + f31(0x80000000, 1)) + f31(0xE1868CB7, 7) / x -
f31(0x8625E279, 8) / (x + f31(0x80000000, 0)) - f31(0xA03E158F, 2) / (x + f31(0xC0000000, 1));
int i = (s.exp >= 2) + (s.exp >= 4) + (s.exp >= 8) + (s.exp >= 16);
s = f31((static_cast<uint32>(s.exp) << (31 - i)) + (log2(s.m >> 1, 28) >> i), i) / lbe;
if (x.exp != -1 || x.m != 0x80000000) {
i = (t.exp >= 2) + (t.exp >= 4) + (t.exp >= 8);
f31 l = f31((static_cast<uint32>(t.exp) << (31 - i)) + (log2(t.m >> 1, 30) >> i), i) / lbe;
s = (x.exp < -1) ? (s - (f31(0x80000000, -1) - x) * l) : (s + (x - f31(0x80000000, -1)) * l);
}
s = x.exp ? (s - t) : (t - s);
if (bsign) {
if (z.exp >= 0) {
sign &= (L | ((z.m >> (31 - z.exp)) & 1)) - 1;
for (z = f31((z.m << (1 + z.exp)) & 0xFFFFFFFF, -1); z.m < 0x80000000; z.m <<= 1, --z.exp)
;
}
if (z.exp == -1)
z = f31(0x80000000, 0) - z;
if (z.exp < -1) {
z = z * pi;
z.m = sincos(z.m >> (1 - z.exp), 30).first;
for (z.exp = 1; z.m < 0x80000000; z.m <<= 1, --z.exp)
;
} else
z = f31(0x80000000, 0);
}
if (L) {
if (bsign) {
f31 l(0x92868247, 0);
if (z.exp < 0) {
uint32 m = log2((z.m + 1) >> 1, 27);
z = f31(-((static_cast<uint32>(z.exp) << 26) + (m >> 5)), 5);
for (; z.m < 0x80000000; z.m <<= 1, --z.exp)
;
l = l + z / lbe;
}
sign = static_cast<unsigned>(x.exp && (l.exp < s.exp || (l.exp == s.exp && l.m < s.m))) << 15;
s = sign ? (s - l) : x.exp ? (l - s) : (l + s);
} else {
sign = static_cast<unsigned>(x.exp == 0) << 15;
if (s.exp < -24)
return underflow<R>(sign);
if (s.exp > 15)
return overflow<R>(sign);
}
} else {
s = s * lbe;
uint32 m;
if (s.exp < 0) {
m = s.m >> -s.exp;
s.exp = 0;
} else {
m = (s.m << s.exp) & 0x7FFFFFFF;
s.exp = (s.m >> (31 - s.exp));
}
s.m = exp2(m, 27);
if (!x.exp)
s = f31(0x80000000, 0) / s;
if (bsign) {
if (z.exp < 0)
s = s * z;
s = pi / s;
if (s.exp < -24)
return underflow<R>(sign);
} else if (z.exp > 0 && !(z.m & ((1 << (31 - z.exp)) - 1)))
return ((s.exp + 14) << 10) + (s.m >> 21);
if (s.exp > 15)
return overflow<R>(sign);
}
return fixed2bfloat16<R, 31, false, false, true>(s.m, s.exp + 14, sign);
}
/// \}
template <typename, typename, std::float_round_style> struct bfloat16_caster;
} // namespace detail
/// BFloat-precision floating-point type.
/// This class implements an IEEE-conformant bfloat16-precision floating-point type with the usual arithmetic
/// operators and conversions. It is implicitly convertible to single-precision floating-point, which makes artihmetic
/// expressions and functions with mixed-type operands to be of the most precise operand type.
///
/// According to the C++98/03 definition, the float16 type is not a POD type. But according to C++11's less strict and
/// extended definitions it is both a standard layout type and a trivially copyable type (even if not a POD type), which
/// means it can be standard-conformantly copied using raw binary copies. But in this context some more words about the
/// actual size of the type. Although the bfloat16 is representing an IEEE 16-bit type, it does not neccessarily have to
/// be of exactly 16-bits size. But on any reasonable implementation the actual binary representation of this type will
/// most probably not involve any additional "magic" or padding beyond the simple binary representation of the
/// underlying 16-bit IEEE number, even if not strictly guaranteed by the standard. But even then it only has an actual
/// size of 16 bits if your C++ implementation supports an unsigned integer type of exactly 16 bits width. But this
/// should be the case on nearly any reasonable platform.
///
/// So if your C++ implementation is not totally exotic or imposes special alignment requirements, it is a reasonable
/// assumption that the data of a bfloat16 is just comprised of the 2 bytes of the underlying IEEE representation.
class bfloat16 {
public:
/// \name Construction and assignment
/// \{
/// Default constructor.
/// This initializes the bfloat16 to 0. Although this does not match the builtin types' default-initialization
/// semantics and may be less efficient than no initialization, it is needed to provide proper value-initialization
/// semantics.
BFLOAT_CONSTEXPR bfloat16() BFLOAT_NOEXCEPT : data_() {}
/// Conversion constructor.
/// \param rhs float to convert
/// \exception FE_OVERFLOW, ...UNDERFLOW, ...INEXACT according to rounding
explicit bfloat16(float rhs) : data_(static_cast<detail::uint16>(detail::float2bfloat16<round_style>(rhs))) {}
/// Conversion to single-precision.
/// \return single precision value representing expression value
operator float() const { return detail::bfloat162float<float>(data_); }
/// Assignment operator.
/// \param rhs single-precision value to copy from
/// \return reference to this bfloat16
/// \exception FE_OVERFLOW, ...UNDERFLOW, ...INEXACT according to rounding
bfloat16 &operator=(float rhs)
{
data_ = static_cast<detail::uint16>(detail::float2bfloat16<round_style>(rhs));
return *this;
}
/// \}
/// \name Arithmetic updates
/// \{
/// Arithmetic assignment.
/// \tparam T type of concrete bfloat16 expression
/// \param rhs bfloat16 expression to add
/// \return reference to this bfloat16
/// \exception FE_... according to operator+(float16,float16)
bfloat16 &operator+=(bfloat16 rhs) { return *this = *this + rhs; }
/// Arithmetic assignment.
/// \tparam T type of concrete bfloat16 expression
/// \param rhs bfloat16 expression to subtract
/// \return reference to this bfloat16
/// \exception FE_... according to operator-(float16,float16)
bfloat16 &operator-=(bfloat16 rhs) { return *this = *this - rhs; }
/// Arithmetic assignment.
/// \tparam T type of concrete bfloat16 expression
/// \param rhs bfloat16 expression to multiply with
/// \return reference to this bfloat16
/// \exception FE_... according to operator*(float16,float16)
bfloat16 &operator*=(bfloat16 rhs) { return *this = *this * rhs; }
/// Arithmetic assignment.
/// \tparam T type of concrete bfloat16 expression
/// \param rhs bfloat16 expression to divide by
/// \return reference to this bfloat16
/// \exception FE_... according to operator/(float16,float16)
bfloat16 &operator/=(bfloat16 rhs) { return *this = *this / rhs; }
/// Arithmetic assignment.
/// \param rhs single-precision value to add
/// \return reference to this bfloat16
/// \exception FE_... according to operator=()
bfloat16 &operator+=(float rhs) { return *this = *this + rhs; }
/// Arithmetic assignment.
/// \param rhs single-precision value to subtract
/// \return reference to this bfloat16
/// \exception FE_... according to operator=()
bfloat16 &operator-=(float rhs) { return *this = *this - rhs; }
/// Arithmetic assignment.
/// \param rhs single-precision value to multiply with
/// \return reference to this bfloat16
/// \exception FE_... according to operator=()
bfloat16 &operator*=(float rhs) { return *this = *this * rhs; }
/// Arithmetic assignment.
/// \param rhs single-precision value to divide by
/// \return reference to this bfloat16
/// \exception FE_... according to operator=()
bfloat16 &operator/=(float rhs) { return *this = *this / rhs; }
/// \}
/// \name Increment and decrement
/// \{
/// Prefix increment.
/// \return incremented bfloat16 value
/// \exception FE_... according to operator+(bfloat16,bfloat16)
bfloat16 &operator++() { return *this = *this + bfloat16(detail::binary, 0x3F80); }
/// Prefix decrement.
/// \return decremented bfloat16 value
/// \exception FE_... according to operator-(bfloat16,bfloat16)
bfloat16 &operator--() { return *this = *this + bfloat16(detail::binary, 0xBF80); }
/// Postfix increment.
/// \return non-incremented bfloat16 value
/// \exception FE_... according to operator+(bfloat16,bfloat16)
bfloat16 operator++(int)
{
bfloat16 out(*this);
++*this;
return out;
}
/// Postfix decrement.
/// \return non-decremented bfloat16 value
/// \exception FE_... according to operator-(bfloat16,bfloat16)
bfloat16 operator--(int)
{
bfloat16 out(*this);
--*this;
return out;
}
/// \}
private:
/// Rounding mode to use
static const std::float_round_style round_style = (std::float_round_style)(BFLOAT_ROUND_STYLE);
/// Constructor.
/// \param bits binary representation to set bfloat16 to
BFLOAT_CONSTEXPR bfloat16(detail::binary_t, unsigned int bits) BFLOAT_NOEXCEPT
: data_(static_cast<detail::uint16>(bits))
{
}
/// Internal binary representation
detail::uint16 data_;
#ifndef BFLOAT_DOXYGEN_ONLY
friend BFLOAT_CONSTEXPR_NOERR bool operator==(bfloat16, bfloat16);
friend BFLOAT_CONSTEXPR_NOERR bool operator!=(bfloat16, bfloat16);
friend BFLOAT_CONSTEXPR_NOERR bool operator<(bfloat16, bfloat16);
friend BFLOAT_CONSTEXPR_NOERR bool operator>(bfloat16, bfloat16);
friend BFLOAT_CONSTEXPR_NOERR bool operator<=(bfloat16, bfloat16);
friend BFLOAT_CONSTEXPR_NOERR bool operator>=(bfloat16, bfloat16);
friend BFLOAT_CONSTEXPR bfloat16 operator-(bfloat16);
friend bfloat16 operator+(bfloat16, bfloat16);
friend bfloat16 operator-(bfloat16, bfloat16);
friend bfloat16 operator*(bfloat16, bfloat16);
friend bfloat16 operator/(bfloat16, bfloat16);
template <typename charT, typename traits>
friend std::basic_ostream<charT, traits> &operator<<(std::basic_ostream<charT, traits> &, bfloat16);
template <typename charT, typename traits>
friend std::basic_istream<charT, traits> &operator>>(std::basic_istream<charT, traits> &, bfloat16 &);
friend BFLOAT_CONSTEXPR bfloat16 fabs(bfloat16);
friend bfloat16 fmod(bfloat16, bfloat16);
friend bfloat16 remainder(bfloat16, bfloat16);
friend bfloat16 remquo(bfloat16, bfloat16, int *);
friend bfloat16 fma(bfloat16, bfloat16, bfloat16);
friend BFLOAT_CONSTEXPR_NOERR bfloat16 fmax(bfloat16, bfloat16);
friend BFLOAT_CONSTEXPR_NOERR bfloat16 fmin(bfloat16, bfloat16);
friend bfloat16 fdim(bfloat16, bfloat16);
friend bfloat16 nanh(const char *);
friend bfloat16 exp(bfloat16);
friend bfloat16 exp2(bfloat16);
friend bfloat16 expm1(bfloat16);
friend bfloat16 log(bfloat16);
friend bfloat16 log10(bfloat16);
friend bfloat16 log2(bfloat16);
friend bfloat16 log1p(bfloat16);
friend bfloat16 sqrt(bfloat16);
friend bfloat16 cbrt(bfloat16);
friend bfloat16 hypot(bfloat16, bfloat16);
friend bfloat16 hypot(bfloat16, bfloat16, bfloat16);
friend bfloat16 pow(bfloat16, bfloat16);
friend void sincos(bfloat16, bfloat16 *, bfloat16 *);
friend bfloat16 sin(bfloat16);
friend bfloat16 cos(bfloat16);
friend bfloat16 tan(bfloat16);
friend bfloat16 asin(bfloat16);
friend bfloat16 acos(bfloat16);
friend bfloat16 atan(bfloat16);
friend bfloat16 atan2(bfloat16, bfloat16);
friend bfloat16 sinh(bfloat16);
friend bfloat16 cosh(bfloat16);
friend bfloat16 tanh(bfloat16);
friend bfloat16 asinh(bfloat16);
friend bfloat16 acosh(bfloat16);
friend bfloat16 atanh(bfloat16);
friend bfloat16 erf(bfloat16);
friend bfloat16 erfc(bfloat16);
friend bfloat16 lgamma(bfloat16);
friend bfloat16 tgamma(bfloat16);
friend bfloat16 ceil(bfloat16);
friend bfloat16 floor(bfloat16);
friend bfloat16 trunc(bfloat16);
friend bfloat16 round(bfloat16);
friend long lround(bfloat16);
friend bfloat16 rint(bfloat16);
friend long lrint(bfloat16);
friend bfloat16 nearbyint(bfloat16);
#ifdef BFLOAT_ENABLE_CPP11_LONG_LONG
friend long long llround(bfloat16);
friend long long llrint(bfloat16);
#endif
friend bfloat16 frexp(bfloat16, int *);
friend bfloat16 scalbln(bfloat16, long);
friend bfloat16 modf(bfloat16, bfloat16 *);
friend int ilogb(bfloat16);
friend bfloat16 logb(bfloat16);
friend bfloat16 nextafter(bfloat16, bfloat16);
friend bfloat16 nexttoward(bfloat16, long double);
friend BFLOAT_CONSTEXPR bfloat16 copysign(bfloat16, bfloat16);
friend BFLOAT_CONSTEXPR int fpclassify(bfloat16);
friend BFLOAT_CONSTEXPR bool isfinite(bfloat16);
friend BFLOAT_CONSTEXPR bool isinf(bfloat16);
friend BFLOAT_CONSTEXPR bool isnan(bfloat16);
friend BFLOAT_CONSTEXPR bool isnormal(bfloat16);
friend BFLOAT_CONSTEXPR bool signbit(bfloat16);
friend BFLOAT_CONSTEXPR bool isgreater(bfloat16, bfloat16);
friend BFLOAT_CONSTEXPR bool isgreaterequal(bfloat16, bfloat16);
friend BFLOAT_CONSTEXPR bool isless(bfloat16, bfloat16);
friend BFLOAT_CONSTEXPR bool islessequal(bfloat16, bfloat16);
friend BFLOAT_CONSTEXPR bool islessgreater(bfloat16, bfloat16);
template <typename, typename, std::float_round_style> friend struct detail::bfloat16_caster;
friend class std::numeric_limits<bfloat16>;
#if BFLOAT_ENABLE_CPP11_HASH
friend struct std::hash<bfloat16>;
#endif
#if BFLOAT_ENABLE_CPP11_USER_LITERALS
friend bfloat16 literal::operator"" _h(long double);
#endif
#endif
};
#if BFLOAT_ENABLE_CPP11_USER_LITERALS
namespace literal {
/// Bfloat16 literal.
/// While this returns a properly rounded bfloat16-precision value, bfloat16 literals can unfortunately not be constant
/// expressions due to rather involved conversions. So don't expect this to be a literal literal without involving
/// conversion operations at runtime. It is a convenience feature, not a performance optimization.
/// \param value literal value
/// \return bfloat16 with of given value (possibly rounded)
/// \exception FE_OVERFLOW, ...UNDERFLOW, ...INEXACT according to rounding
inline bfloat16 operator"" _h(long double value)
{
return bfloat16(detail::binary, detail::float2bfloat16<bfloat16::round_style>(value));
}
} // namespace literal
#endif
namespace detail {
/// Helper class for bfloat16 casts.
/// This class template has to be specialized for all valid cast arguments to define an appropriate static
/// `cast` member function and a corresponding `type` member denoting its return type.
/// \tparam T destination type
/// \tparam U source type
/// \tparam R rounding mode to use
template <typename T, typename U, std::float_round_style R = (std::float_round_style)(BFLOAT_ROUND_STYLE)>
struct bfloat16_caster {
};
template <typename U, std::float_round_style R> struct bfloat16_caster<bfloat16, U, R> {
#if BFLOAT_ENABLE_CPP11_STATIC_ASSERT && BFLOAT_ENABLE_CPP11_TYPE_TRAITS
static_assert(std::is_arithmetic<U>::value, "bfloat16_cast from non-arithmetic type unsupported");
#endif
static bfloat16 cast(U arg) { return cast_impl(arg, is_float<U>()); };
private:
static bfloat16 cast_impl(U arg, true_type) { return bfloat16(binary, float2bfloat16<R>(arg)); }
static bfloat16 cast_impl(U arg, false_type) { return bfloat16(binary, int2bfloat16<R>(arg)); }
};
template <typename T, std::float_round_style R> struct bfloat16_caster<T, bfloat16, R> {
#if BFLOAT_ENABLE_CPP11_STATIC_ASSERT & BFLOAT_ENABLE_CPP11_TYPE_TRAITS
static_assert(std::is_arithmetic<T>::value, "bfloat16_cast to non-arithmetic type unsupported");
#endif
static T cast(bfloat16 arg) { return cast_impl(arg, is_float<T>()); }
private:
static T cast_impl(bfloat16 arg, true_type) { return bfloat162float<T>(arg.data_); }
static T cast_impl(bfloat16 arg, false_type) { return bfloat162int<R, true, true, T>(arg.data_); }
};
template <std::float_round_style R> struct bfloat16_caster<bfloat16, bfloat16, R> {
static bfloat16 cast(bfloat16 arg) { return arg; }
};
} // namespace detail
} // namespace bfloat16
/// Extensions to the C++ standard library.
namespace std {
/// Numeric limits for bfloat16-precision floats.
/// **See also:** Documentation for [std::numeric_limits](https://en.cppreference.com/w/cpp/types/numeric_limits)
template <> class numeric_limits<bfloat16::bfloat16> {
public:
/// Is template specialization.
static BFLOAT_CONSTEXPR_CONST bool is_specialized = true;
/// Supports signed values.
static BFLOAT_CONSTEXPR_CONST bool is_signed = true;
/// Is not an integer type.
static BFLOAT_CONSTEXPR_CONST bool is_integer = false;
/// Is not exact.
static BFLOAT_CONSTEXPR_CONST bool is_exact = false;
/// Doesn't provide modulo arithmetic.
static BFLOAT_CONSTEXPR_CONST bool is_modulo = false;
/// Has a finite set of values.
static BFLOAT_CONSTEXPR_CONST bool is_bounded = true;
/// IEEE conformant.
static BFLOAT_CONSTEXPR_CONST bool is_iec559 = true;
/// Supports infinity.
static BFLOAT_CONSTEXPR_CONST bool has_infinity = true;
/// Supports quit NaNs
static BFLOAT_CONSTEXPR_CONST bool has_quiet_NaN = true;
/// Supports signaling NaNs
static BFLOAT_CONSTEXPR_CONST bool has_signaling_NaN = true;
/// Supports subnormal values.
static BFLOAT_CONSTEXPR_CONST float_denorm_style has_denorm = denorm_present;
/// Supports no denormalization detection.
static BFLOAT_CONSTEXPR_CONST bool has_denorm_loss = false;
#if BFLOAT_ERRHANDLING_THROWS
static BFLOAT_CONSTEXPR_CONST bool traps = true;
#else
/// Traps only if [BFLOAT_ERRHANDLING_THROW_...](\ref BFLOAT_ERRHANDLINIG_THROW_INVALID) is activated.
static BFLOAT_CONSTEXPR_CONST bool traps = false;
#endif
/// Does not support no pre-rounding underflow detection.
static BFLOAT_CONSTEXPR_CONST bool tinyness_before = false;
// Rounding mode.
static BFLOAT_CONSTEXPR_CONST float_round_style round_style = bfloat16::bfloat16::round_style;
/// Significant digits.
static BFLOAT_CONSTEXPR_CONST int digits = 8;
/// Significant decimal digits.
static BFLOAT_CONSTEXPR_CONST int digits10 = 2;
/// Required decimal digits to represent all possible values.
static BFLOAT_CONSTEXPR_CONST int max_digits10 = 39; // should be right
/// Number base.
static BFLOAT_CONSTEXPR_CONST int radix = 2;
/// One more than smallest exponent.
static BFLOAT_CONSTEXPR_CONST int min_exponent = -125; // smallest = -126
/// Smallest normalized representable power of 10.
static BFLOAT_CONSTEXPR_CONST int min_exponent10 = -38;
/// One more than largest exponent.
static BFLOAT_CONSTEXPR_CONST int max_exponent = 128;
/// Largest finitely representable power of 10.
static BFLOAT_CONSTEXPR_CONST int max_exponent10 = 38;
/// Smallest positive normal value.
static BFLOAT_CONSTEXPR bfloat16::bfloat16 min() BFLOAT_NOTHROW
{
return bfloat16::bfloat16(bfloat16::detail::binary, 0x0080);
}
/// Smallest finite value.
static BFLOAT_CONSTEXPR bfloat16::bfloat16 lowest() BFLOAT_NOTHROW
{
return bfloat16::bfloat16(bfloat16::detail::binary, 0xFF7F);
}
/// Largest finite value.
static BFLOAT_CONSTEXPR bfloat16::bfloat16 max() BFLOAT_NOTHROW
{
return bfloat16::bfloat16(bfloat16::detail::binary, 0x7F7F);
}
/// Difference between 1 and next represantable value.
static BFLOAT_CONSTEXPR bfloat16::bfloat16 epsilon() BFLOAT_NOTHROW
{
return bfloat16::bfloat16(bfloat16::detail::binary, 0x0280);
} // could be wrong
/// Maximum rounding error in ULP (units in the last place).
static BFLOAT_CONSTEXPR bfloat16::bfloat16 round_error() BFLOAT_NOTHROW
{
return bfloat16::bfloat16(bfloat16::detail::binary, (round_style == std::round_to_nearest) ? 0x3F00 : 0x3F80);
}
/// Positive infinity.
static BFLOAT_CONSTEXPR bfloat16::bfloat16 infinity() BFLOAT_NOTHROW
{
return bfloat16::bfloat16(bfloat16::detail::binary, 0x7F80);
}
/// Quiet NaN.
static BFLOAT_CONSTEXPR bfloat16::bfloat16 quiet_NaN() BFLOAT_NOTHROW
{
return bfloat16::bfloat16(bfloat16::detail::binary, 0x7FFF);
}
/// Signaling NaN
static BFLOAT_CONSTEXPR bfloat16::bfloat16 signaling_NaN() BFLOAT_NOTHROW
{
return bfloat16::bfloat16(bfloat16::detail::binary, 0x7FBF);
}
/// Smallest positive subnormal value.
static BFLOAT_CONSTEXPR bfloat16::bfloat16 denorm_min() BFLOAT_NOTHROW
{
return bfloat16::bfloat16(bfloat16::detail::binary, 0x0001);
}
};
#if BFLOAT_ENABLE_CPP11_HASH
/// Hash function for bfloat16-precision floats.
/// This is only defined if C++11 `std::hash` is supported and enabled.
///
/// **See also:** Documentation for [std::hash](https://en.cppreference.com/w/cpp/utility/hash)
template <> struct hash<bfloat16::bfloat16> {
/// Type of function argument.
typedef bfloat16::bfloat16 argument_type;
/// Function return type.
typedef size_t result_type;
/// Compute hash function.
/// \param arg bfloat16 to hash
/// \return hash value
result_type operator()(argument_type arg) const
{
return hash<bfloat16::detail::uint16>()(arg.data_ & -static_cast<unsigned>(arg.data_ != 0x8000));
}
};
#endif
} // namespace std
namespace bfloat16 {
/// \anchor compop
/// \name Comparison operators
/// \{
/// Comparison for equality.
/// \param x first operand
/// \param y second operand
/// \retval true if operands equal
/// \retval false else
/// \exception FE_INVALID if \a x or \a y is NaN
inline BFLOAT_CONSTEXPR_NOERR bool operator==(bfloat16 x, bfloat16 y)
{
return !detail::compsignal(x.data_, y.data_) && (x.data_ == y.data_ || !((x.data_ | y.data_) & 0x7FFF));
}
/// Comparison for inequality.
/// \param x first operand
/// \param y second operand
/// \retval true if operands not equal
/// \retval false else
/// \exception FE_INVALID if \a x or \a y is NaN
inline BFLOAT_CONSTEXPR_NOERR bool operator!=(bfloat16 x, bfloat16 y)
{
return detail::compsignal(x.data_, y.data_) || (x.data_ != y.data_ && ((x.data_ | y.data_) & 0x7FFF));
}
/// Comparison for less than.
/// \param x first operand
/// \param y second operand
/// \retval true if \a x less than \a y
/// \retval false else
/// \exception FE_INVALID if \a x or \a y is NaN
inline BFLOAT_CONSTEXPR_NOERR bool operator<(bfloat16 x, bfloat16 y)
{
return !detail::compsignal(x.data_, y.data_) &&
((x.data_ ^ (0x8000 | (0x8000 - (x.data_ >> 15)))) + (x.data_ >> 15)) <
((y.data_ ^ (0x8000 | (0x8000 - (y.data_ >> 15)))) + (y.data_ >> 15));
}
/// Comparison for greater than.
/// \param x first operand
/// \param y second operand
/// \retval true if \a x greater than \a y
/// \retval false else
/// \exception FE_INVALID if \a x or \a y is NaN
inline BFLOAT_CONSTEXPR_NOERR bool operator>(bfloat16 x, bfloat16 y)
{
return !detail::compsignal(x.data_, y.data_) &&
((x.data_ ^ (0x8000 | (0x8000 - (x.data_ >> 15)))) + (x.data_ >> 15)) >
((y.data_ ^ (0x8000 | (0x8000 - (y.data_ >> 15)))) + (y.data_ >> 15));
}
/// Comparison for less equal.
/// \param x first operand
/// \param y second operand
/// \retval true if \a x less equal \a y
/// \retval false else
/// \exception FE_INVALID if \a x or \a y is NaN
inline BFLOAT_CONSTEXPR_NOERR bool operator<=(bfloat16 x, bfloat16 y)
{
return !detail::compsignal(x.data_, y.data_) &&
((x.data_ ^ (0x8000 | (0x8000 - (x.data_ >> 15)))) + (x.data_ >> 15)) <=
((y.data_ ^ (0x8000 | (0x8000 - (y.data_ >> 15)))) + (y.data_ >> 15));
}
/// Comparison for greater equal.
/// \param x first operand
/// \param y second operand
/// \retval true if \a x greater equal \a y
/// \retval false else
/// \exception FE_INVALID if \a x or \a y is NaN
inline BFLOAT_CONSTEXPR_NOERR bool operator>=(bfloat16 x, bfloat16 y)
{
return !detail::compsignal(x.data_, y.data_) &&
((x.data_ ^ (0x8000 | (0x8000 - (x.data_ >> 15)))) + (x.data_ >> 15)) >=
((y.data_ ^ (0x8000 | (0x8000 - (y.data_ >> 15)))) - (y.data_ >> 15));
}
/// \}
/// \anchor arithmetics
/// \name Arithmetic operators
/// \{
/// Identity.
/// \param arg operand
/// \return unchanged operand
inline BFLOAT_CONSTEXPR bfloat16 operator+(bfloat16 arg) { return arg; }
/// Negation.
/// \param arg operand
/// \return negated operand
inline BFLOAT_CONSTEXPR bfloat16 operator-(bfloat16 arg) { return bfloat16(detail::binary, arg.data_ ^ 0x8000); }
/// Addition.
/// This operation is exact to rounding for all rounding modes.
/// \param x left operand
/// \param y right operand
/// \return sum of bfloat16 expressions
/// \exception FE_INVALID if \a x and \a y are infinities with different signs or signaling NaNs
/// \exception FE_OVERFLOW, ...UNDERFLOW, ...INEXACT according to rounding
inline bfloat16 operator+(bfloat16 x, bfloat16 y)
{
#ifdef BFLOAT_ARITHMETIC_TYPE
return bfloat16(detail::binary,
detail::float2bfloat16<bfloat16::round_style>(detail::bfloat162float<detail::internal_t>(x.data_) +
detail::bfloat162float<detail::internal_t>(y.data_)));
// temp
#else
return bfloat16(detail::bfloat162float_temp(x) + detail::bfloat162float_temp(y));
#endif
#if 0 // else
int absx = x.data_ & 0x7FFF, absy = y.data_ & 0x7FFF;
bool sub = ((x.data_^y.data_)&0x8000) != 0;
if(absx >= 0x7F80 || absy >= 0x7F80)
return bfloat16(detail::binary, (absx>0x7F80 || absy>0x7F80) ? detail::signal(x.data_, y.data_) : (absy!=0x7F80) ? x.data_ : (sub && absx==0x7F80) ? detail::invalid() : y.data_);
if(!absx)
return absy ? y : bfloat16(detail::binary, (bfloat16::round_style==std::round_toward_neg_infinity) ? (x.data_|y.data_) : (x.data_&y.data_));
if(!absy)
return x;
unsigned int sign = ((sub && absy>absx) ? y.data_ : x.data_) & 0x8000;
if(absy > absx)
std::swap(absx, absy);
int exp = (absx>>7) + (absx<=0x7F), d = exp - (absy>>7) - (absy<=0x7F), mx = ((absx&0x7F)|((absx>0x7F)<<7))<<3, my;
if(d < 125)
{
my = ((absy&0x7F)|((absy>0x7F)<<7))<<3;
my = (my>>d) | ((my&((1<<d)-1))!=0);
}
else
my = 1;
if(sub)
{
if(!(mx-=my))
return bfloat16(detail::binary, static_cast<unsigned>(bfloat16::round_style==std::round_toward_neg_infinity)<<15); // hier
for(; mx<0x2000 && exp>1; mx<<=1,--exp) ;
return bfloat16(detail::binary, detail::rounded<bfloat16::round_style,false>(sign+((exp-7)<<7)+(mx>>3), (mx>>2)&1, (mx&0x3)!=0));
}
else
{
mx += my;
int i = mx >> 11;
if((exp+=i)> 254)
return bfloat16(detail::binary, detail::overflow<bfloat16::round_style>(sign));
mx = (mx>>i) | (mx&i);
return bfloat16(detail::binary, detail::rounded<bfloat16::round_style,false>(sign+((exp-1)<<7)+(mx>>3), (mx>>2)&1, (mx&0x3)!=0));
}
#endif
}
/// Subtraction.
/// This operation is exact to rounding for all rounding modes.
/// \param x left operand
/// \param y right operand
/// \return difference of bfloat16 expressions
/// \exception FE_INVALID if \a x and \a y are infinities with equal signs or signaling NaNs
/// \exception FE_OVERFLOW, ...UNDERFLOW, ...INEXACT according to rounding
inline bfloat16 operator-(bfloat16 x, bfloat16 y)
{
#ifdef BFLOAT_ARITHMETIC_TYPE
return bfloat16(detail::binary,
detail::float2bfloat16<bfloat16::round_style>(detail::bfloat162float<detail::internal_t>(x.data_) -
detail::bfloat162float<detail::internal_t>(y.data_)));
#else
return x + -y;
#endif
}
/// Multiplication.
/// This operation is exact to rounding for all rounding modes.
/// \param x left operand
/// \param y right operand
/// \return product of bfloat16 expressions
/// \exception FE_INVALID if multiplying 0 with infinity or if \a x or \a y is signaling NaN
/// \exception FE_OVERFLOW, ...UNDERFLOW, ...INEXACT according to rounding
inline bfloat16 operator*(bfloat16 x, bfloat16 y)
{
#ifdef BFLOAT_ARITHMETIC_TYPE
return bfloat16(detail::binary,
detail::float2bfloat16<bfloat16::round_style>(detail::bfloat162float<detail::internal_t>(x.data_) *
detail::bfloat162float<detail::internal_t>(y.data_)));
// temp
#else
return bfloat16(detail::bfloat162float_temp(x) * detail::bfloat162float_temp(y));
#endif
#if 0
int absx = x.data_ & 0x7FFF, absy = y.data_ & 0x7FFF, exp = -128;
unsigned int sign = (x.data_^y.data_) & 0x8000;
if(absx >= 0x7F80 || absy >= 0x7F80)
return bfloat16(detail::binary, (absx>0x7F80 || absy>0x7F80) ? detail::signal(x.data_, y.data_) : ((absx==0x7F80 && ! absy) || (absy==0x7F80 && ! absx)) ? detail::invalid() : (sign|0x7F80));
if(!absx || !absy)
return bfloat16(detail::binary, sign);
for(; absx<0x80; absx<<=1,--exp) ;
for(; absy<0x80; absy<<=1,--exp) ;
detail::uint32 m = static_cast<detail::uint32>((absx&0x7F)|0x80) * static_cast<detail::uint32>((absy&0x7F)|0x80);
int i = m >> 21, s = m & i; // 21 vlt ändern
exp += (absx>>7) + (absy>>7) +i;
if(exp > 253) // 29 vlt ändern
return bfloat16(detail::binary, detail::overflow<bfloat16::round_style>(sign));
else if (exp < -123) // -11 vlt ändern
return bfloat16(detail::binary, detail::underflow<bfloat16::round_style>(sign));
return bfloat16(detail::binary, detail::fixed2bfloat16<bfloat16::round_style, 11,false,false,false>(m>>i, exp, sign, s)); //vlt 20 ändern
#endif
}
/// Division.
/// This operation is exact to rounding for all rounding modes.
/// \param x left operand
/// \param y right operand
/// \return quotient of bfloat16 expressions
/// \exception FE_INVALID if dividing 0s or infinities with each other or if \a x or \a y is signaling NaN
/// \exception FE_DIVBYZERO if dividing finite value by 0
/// \exception FE_OVERFLOW, ...UNDERFLOW, ...INEXACT according to rounding
inline bfloat16 operator/(bfloat16 x, bfloat16 y)
{
#ifdef BFLOAT_ARITHEMTIC_TYPE
return bfloat16(detail::binary,
detail::float2bfloat16<bfloat16::round_style>(detail::bfloat162float<detail::internal_t>(x.data_) /
detail::bfloat162float<detail::internal_t>(y.data_)));
// temp
#else
return bfloat16(detail::bfloat162float_temp(x) / detail::bfloat162float_temp(y));
#endif
#if 0
int absx = x.data_ & 0x7FFF, absy = y.data_ & 0x7FFF, exp = 126; //14vlt ändern
unsigned int sign = (x.data_^y.data_) & 0x8000;
if(absx >= 0x7F80 || absy >= 0x7F80)
return bfloat16(detail::binary, (absx>0x7F80 || absy>0x7F80) ?
detail::signal(x.data_, y.data_) :(absx==absy) ?
detail::invalid() : (sign|((absx==0x7F80) ? 0x7F80 : 0)));
if(!absx)
return bfloat16(detail::binary, absy ? sign : detail::invalid());
if(!absy)
return bfloat16(detail::binary, detail::pole(sign));
for(; absx<0x80; absx<<=1,--exp) ;
for(; absy<0x80; absy<<=1,++exp) ;
detail::uint32 mx = (absx&0x7F) | 0x80, my = (absy&0x7F) | 0x80;
int i = mx < my;
exp += (absx>>7) - (absy>>7) - i;
if(exp > 253) // 29 vlt ändern
return bfloat16(detail::binary, detail::overflow<bfloat16::round_style>(sign));
else if(exp < -123) // vlt ändern
return bfloat16(detail::binary, detail::underflow<bfloat16::round_style>(sign));
my <<= 12 + i;
my <<= 1;
return bfloat16(detail::binary, detail::fixed2bfloat16<bfloat16::round_style, 11, false,false,false>(mx/my, exp, sign, mx%my!=0));
#endif
}
/// \}
/// \anchor streaming
/// \name Input and output
/// \{
/// Output operator.
/// This uses the built-in functionality for streaming out floating-point numbers.
/// \param out output stream to write into
/// \param arg bfloat16 expression to write
/// \return reference to output stream
template <typename charT, typename traits>
std::basic_ostream<charT, traits> &operator<<(std::basic_ostream<charT, traits> &out, bfloat16 arg)
{
#ifdef BFLOAT_ARITHMETIC_TYPE
return out << detail::bfloat162float<detail::internal_t>(arg.data_);
#else
// return out << detail::bfloat162float<float>(arg.data_);
return out << detail::bfloat162float_temp(arg.data_);
#endif
}
/// Input operator.
/// This uses the built-in functionality for streaming in floating-point numbers, specifically double precision floating
/// point numbers (unless overridden with [BFLOAT_ARITHMETIC_TYPE](\ref BFLOAT_ARITHMETIC_TYPE)). So the input string is
/// first rounded to double precision using the underlying platform's current floating-point rounding mode before being
/// rounded to bfloat16-precision using the library's bfloat16-precision rounding mode. \param in input stream to read
/// from \param arg bfloat16 to read into \return reference to input stream \exception FE_OVERFLOW, ...UNDERFLOW,
/// ...INEXACT according to rounding
template <typename charT, typename traits>
std::basic_istream<charT, traits> &operator>>(std::basic_istream<charT, traits> &in, bfloat16 &arg)
{
#ifdef BFLOAT_ARITHMETIC_TYPE
detail::internal_t f;
#else
double f;
#endif
if (in >> f)
arg.data_ = detail::float2bfloat16<bfloat16::round_style>(f);
return in;
}
/// \}
/// \anchor basic
/// \name Basic mathematical operations
/// \{
/// Absolute value.
/// **See also:** Documentation for [std::fabs](https://en.cppreference.com/w/cpp/numeric/math/fabs).
/// \param arg operand
/// \return absolute value of \a arg
inline BFLOAT_CONSTEXPR bfloat16 fabs(bfloat16 arg) { return bfloat16(detail::binary, arg.data_ & 0x7FFF); }
/// Absolute value.
/// **See also:** Documentation for [std::abs](https://en.cppreference.com/w/cpp/numeric/math/fabs).
/// \param arg operand
/// \return absolute value of \a arg
inline BFLOAT_CONSTEXPR bfloat16 abs(bfloat16 arg) { return fabs(arg); }
/// Remainder of division.
/// **See also:** Documentation for [std::fmod](https://en.cppreference.com/w/cpp/numeric/math/fmod).
/// \param x first operand
/// \param y second operand
/// \return remainder of floating-point division.
/// \exception FE_INVALID if \a x is infinite or \a y is 0 or if \a x or \a y is signaling NaN
inline bfloat16 fmod(bfloat16 x, bfloat16 y)
{
unsigned int absx = x.data_ & 0x7FFF, absy = y.data_ & 0x7FFF, sign = x.data_ & 0x8000;
if (absx >= 0x7F80 || absy >= 0x7F80)
return bfloat16(detail::binary, (absx > 0x7F80 || absy > 0x7F80) ? detail::signal(x.data_, y.data_)
: (absx == 0x7F80) ? detail::invalid()
: x.data_);
if (!absy)
return bfloat16(detail::binary, detail::invalid());
if (!absx)
return x;
if (absx == absy)
return bfloat16(detail::binary, sign);
return bfloat16(detail::binary, sign | detail::mod<false, false>(absx, absy));
}
/// Remainder of division.
/// **See also:** Documentation for [std::remainder](https://en.cppreference.com/w/cpp/numeric/math/remainder).
/// \param x first operand
/// \param y second operand
/// \return remainder of floating-point division.
/// \exception FE_INVALID if \a x is infinite or \a y is 0 or if \a x or \a y is signaling NaN
inline bfloat16 remainder(bfloat16 x, bfloat16 y)
{
unsigned int absx = x.data_ & 0x7FFF, absy = y.data_ & 0x7FFF, sign = x.data_ & 0x8000;
if (absx >= 0x7F80 || absy >= 0x7F80)
return bfloat16(detail::binary, (absx > 0x7F80 || absy > 0x7F80) ? detail::signal(x.data_, y.data_)
: (absx == 0x7F80) ? detail::invalid()
: x.data_);
if (!absy)
return bfloat16(detail::binary, detail::invalid());
if (absx == absy)
return bfloat16(detail::binary, sign);
return bfloat16(detail::binary, sign ^ detail::mod<false, true>(absx, absy));
}
/// Remainder of division.
/// **See also:** Documentation for [std::remquo](https://en.cppreference.com/w/cpp/numeric/math/remquo).
/// \param x first operand
/// \param y second operand
/// \param quo address to store some bits of quotient at
/// \return remainder of floating-point division.
/// \exception FE_INVALID if \a x is infinite or \a y is 0 or if \a x or \a y is signaling NaN
inline bfloat16 remquo(bfloat16 x, bfloat16 y, int *quo)
{
unsigned int absx = x.data_ & 0x7FFF, absy = y.data_ & 0x7FFF, value = x.data_ & 0x8000;
if (absx >= 0x7F80 || absy >= 0x7F80)
return bfloat16(detail::binary, (absx > 0x7F80 || absy > 0x7F80) ? detail::signal(x.data_, y.data_)
: (absx == 0x7F80) ? detail::invalid()
: (*quo = 0, x.data_));
if (!absy)
return bfloat16(detail::binary, detail::invalid());
bool qsign = ((value ^ y.data_) & 0x8000) != 0;
int q = 1;
if (absx != absy)
value ^= detail::mod<true, true>(absx, absy, &q);
return *quo = qsign ? -q : q, bfloat16(detail::binary, value);
}
/// Fused multiply add.
/// This function is exact to rounding for all rounding modes.
///
/// **See also:** Documentation for [std::fma](https://en.cppreference.com/w/cpp/numeric/math/fma).
/// \param x first operand
/// \param y second operand
/// \param z third operand
/// \return ( \a x * \a y ) + \a z rounded as one operation.
/// \exception FE_INVALID according to operator*() and operator+() unless any argument is a quiet NaN and no argument is
/// a signaling NaN \exception FE_OVERFLOW, ...UNDERFLOW, ...INEXACT according to rounding the final addition
inline bfloat16 fma(bfloat16 x, bfloat16 y, bfloat16 z)
{
#ifdef BFLOAT_ARITHMETIC_TYPE
detail::internal_t fx = detail::bfloat162float<detail::internal_t>(x.data_),
fy = detail::bfloat162float<detail::internal_t>(y.data_),
fz = detail::bfloat162float<detail::internal_t>(z.data_);
#if BFLOAT_ENABLE_CPP11_CMATH && FP_FAST_FMA
return bfloat16(detail::binary, detail::float2bfloat16<bfloat16::round_style>(std::fma(fx, fy, fz)));
#else
return bfloat16(detail::binary, detail::float2bfloat16<bfloat16::round_style>(fx * fy + fz));
#endif
// temp
#else
return bfloat16(
std::fma(detail::bfloat162float_temp(x), detail::bfloat162float_temp(y), detail::bfloat162float_temp(z)));
#endif
#if 0
int absx = x.data_ & 0x7FFF, absy = y.data_ & 0x7FFF, absz = z.data_ & 0x7FFF, exp = -15;
unsigned int sign = (x.data_^y.data_ )& 0x8000;
bool sub = ((sign^z.data_)&0x8000) !=0;
if(absx >= 0x7F80 || absy >= 0x7F80 || absz >= 0x7F80)
return (absx>0x7F80 || absy>0x7F80 || absz>0x7F80) ?
bfloat16(detail::binary, detail::signal(x.data_, y.data_, z.data_)) : (absx==0x7F80) ?
bfloat16(detail::binary, (!absy || (sub && absz==0x7F80)) ?
detail::invalid() : (sign|0x7F80)) : (absy==0x7F80) ?
bfloat16(detail::binary, (!absx || (sub && absz==0x7F80)) ? detail::invalid() : (sign|0x7F80)) : z;
if(!absx || !absy)
return absz ? z : bfloat16(detail::binary, (bfloat16::round_style==std::round_toward_neg_infinity) ? (z.data_|sign) : (z.data_&sign));
for(; absx<0x80; absx<<=1,--exp) ;
for(; absy<0x80; absy<<=1,--exp) ;
detail::uint32 m = static_cast<detail::uint32>((absx&0x7F)|0x80) * static_cast<detail::uint32>((absy&0x7F)|0x80);
int i = m >> 21; //vlt ändern
exp += (absx>>7) + (absy>>7) + i;
m <<= 2 - 1;
if(absz)
{
int expz = 0;
for(; absz<0x80; absz<<=1,--expz) ;
expz += absz >> 7;
detail::uint32 mz = static_cast<detail::uint32>((absz&0x7F)|0x80) << 13; //13 vlt ändern
if(expz > exp || (expz == exp && mz > m))
{
std::swap(m, mz);
std::swap(exp, expz);
if(sub)
sign = z.data_ & 0x8000;
}
int d = exp - expz;
mz = (d<23) ? ((mz>>d)|((mz&((static_cast<detail::uint32>(1)<<d)-1))!=0)) : 1; // 23
if(sub)
{
m = m -mz;
if(!m)
return bfloat16(detail::binary, static_cast<unsigned>(bfloat16::round_style==std::round_toward_neg_infinity)<<15);
for(; m<0x800000; m<<=1,--exp) ;
}
else
{
m += mz;
i = m >> 24;
m = (m>>i) | (m&i);
exp += i;
}
}
if(exp > 30)
return bfloat16(detail::binary, detail::overflow<bfloat16::round_style>(sign));
else if(exp < -10)
return bfloat16(detail::binary, detail::underflow<bfloat16::round_style>(sign));
return bfloat16(detail::binary, detail::fixed2bfloat16<bfloat16::round_style, 23,false,false,false>(m, exp-1, sign));
#endif
}
/// Maximum of bfloat16 expressions.
/// **See also:** Documentation for [std::fmax](https://en.cppreference.com/w/cpp/numeric/math/fmax).
/// \param x first operand
/// \param y second operand
/// \return maximum of operands, ignoring quiet NaNs
/// \exception FE_INVALID if \a x or \a y is signaling NaN
inline BFLOAT_CONSTEXPR_NOERR bfloat16 fmax(bfloat16 x, bfloat16 y)
{
return bfloat16(detail::binary, (!isnan(y) && (isnan(x) || (x.data_ ^ (0x8000 | (0x8000 - (x.data_ >> 15)))) <
(y.data_ ^ (0x8000 | (0x8000 - (y.data_ >> 15))))))
? detail::select(y.data_, x.data_)
: detail::select(x.data_, y.data_));
}
/// Minimum of bfloat16 expressions.
/// **See also:** Documentation for [std::fmin](https://en.cppreference.com/w/cpp/numeric/math/fmin).
/// \param x first operand
/// \param y second operand
/// \return minimum of operands, ignoring quiet NaNs
/// \exception FE_INVALID if \a x or \a y is signaling NaN
inline BFLOAT_CONSTEXPR_NOERR bfloat16 fmin(bfloat16 x, bfloat16 y)
{
return bfloat16(detail::binary, (!isnan(y) && (isnan(x) || (x.data_ ^ (0x8000 | (0x8000 - (x.data_ >> 15)))) >
(y.data_ ^ (0x8000 | (0x8000 - (y.data_ >> 15))))))
? detail::select(y.data_, x.data_)
: detail::select(x.data_, y.data_));
}
/// Positive difference.
/// This function is exact to rounding for all rounding modes.
///
/// **See also:** Documentation for [std::fdim](https://en.cppreference.com/w/cpp/numeric/math/fdim).
/// \param x first operand
/// \param y second operand
/// \return \a x - \a y or 0 if difference negative
/// \exception FE_... according to operator-(bfloat16,bfloat16)
inline bfloat16 fdim(bfloat16 x, bfloat16 y)
{
if (isnan(x) || isnan(y))
return bfloat16(detail::binary, detail::signal(x.data_, y.data_));
return (x.data_ ^ (0x8000 | (0x8000 - (x.data_ >> 15)))) <= (y.data_ ^ (0x8000 | (0x8000 - (y.data_ >> 15))))
? bfloat16(detail::binary, 0)
: (x - y); // has problems with negative values
// return bfloat16(std::fdim(detail::bfloat162float_temp(x), detail::bfloat162float_temp(y)));
}
/// Get NaN value.
/// **See also:** Documentation for [std::nan](https://en.cppreference.com/w/cpp/numeric/math/nan).
/// \param arg string code
/// \return quiet NaN
inline bfloat16 nanh(const char *arg)
{
unsigned int value = 0x7FFF;
while (*arg)
value ^= static_cast<unsigned>(*arg++) & 0xFF;
return bfloat16(detail::binary, value);
}
/// \}
/// \anchor exponential
/// \name Exponential functions
/// \{
/// Exponential function.
/// This function is exact to rounding for all rounding modes.
///
/// **See also:** Documentation for [std::exp](https://en.cppreference.com/w/cpp/numeric/math/exp).
/// \param arg function argument
/// \return e raised to \a arg
/// \exception FE_INVALID for signaling NaN
/// \exception FE_OVERFLOW, ...UNDERFLOW, ...INEXACT according to rounding
inline bfloat16 exp(bfloat16 arg)
{
#ifdef BFLOAT_ARITHMETIC_TYPE
return bfloat16(detail::binary, detail::float2bfloat16<bfloat16::round_style>(
std::exp(detail::bfloat162float<detail::internal_t>(arg.data_))));
// temp
#else
return bfloat16(std::exp(detail::bfloat162float_temp(arg)));
#endif
#if 0
int abs = arg.data_ & 0x7FFF;
if(!abs)
return bfloat16(detail::binary, 0x3F80);
if(abs >= 0x7F80)
return bfloat16(detail::binary, (abs==0x7F80) ? (0x7F80&((arg.data_>>15)-1U)) : detail::signal(arg.data_));
if(abs >= 0x4C80) // kan falsch sein
return bfloat16(detail::binary, (arg.data_&0x8000) ? detail::underflow<bfloat16::round_style>() : detail::overflow<bfloat16::round_style>());
detail::uint32 m = detail::multiply64(static_cast<detail::uint32>((abs&0x7F)+((abs>0x7F)<<7))<<24, 0xB8AA3B29);
int e = (abs>>7) + (abs<=0x7F), exp;
if(e < 14)
{
exp = 0;
m >>= 14 - e;
}
else
{
exp = m >> (408-e);//45
m = (m<<(e-126)) & 0x7FFFFFFF;//14
}
return bfloat16(detail::binary, detail::exp2_post<bfloat16::round_style, true>(detail::exp2(m, 23), exp, (arg.data_&0x8000)!=0));//26
#endif
}
/// Binary exponential.
/// This function is exact to rounding for all rounding modes.
///
/// **See also:** Documentation for [std::exp2](https://en.cppreference.com/w/cpp/numeric/math/exp2).
/// \param arg function argument
/// \return 2 raised to \a arg
/// \exception FE_INVALID for signaling NaN
/// \exception FE_OVERFLOW, ...UNDERFLOW, ...INEXACT according to rounding
inline bfloat16 exp2(bfloat16 arg)
{
#if defined(BFLOAT_ARITHMETIC_TYPE) && BFLOAT_ENABLE_CPP11_CMATH
return bfloat16(detail::binary, detail::float2bfloat16<bfloat16::round_style>(
std::exp2(detail::bfloat162float<detail::internal_t>(arg.data_))));
// temp
#else
return bfloat16(std::exp2(detail::bfloat162float_temp(arg)));
#endif
#if 0
int abs = arg.data_ & 0x7FFF;
if(!abs)
return bfloat16(detail::binary, 0x3F80);
if(abs >= 0x7F80)
return bfloat16(detail::binary, (abs==0x7F80) ? (0x7F80&((arg.data_>>15)-1U)) : detail::signal(arg.data_));
if(abs >= 0x4E40) // kann falsch sein
return bfloat16(detail::binary, (arg.data_&0x8000) ? detail::underflow<bfloat16::round_style>() : detail::overflow<bfloat16::round_style>());
int e = (abs>>7) + (abs<=0x7F), exp = (abs&0x7F) + ((abs>0x7F)<<7);
detail::uint32 m = detail::exp2((static_cast<detail::uint32>(exp)<<(6+e))&0x7FFFFFFF, 28);
exp >>= 25 -e;
if(m == 0x800000000)
{
if(arg.data_&0x8000)
exp = -exp;
else if(exp > 15)
return bfloat16(detail::binary, detail::overflow<bfloat16::round_style>());
return bfloat16(detail::binary, detail::fixed2bfloat16<bfloat16::round_style, 31,false,false,false>(m, exp+14));
}
return bfloat16(detail::binary, detail::exp2_post<bfloat16::round_style,true>(m, exp, (arg.data_&0x8000)!=0));
#endif
}
/// Exponential minus one.
/// This function may be 1 ULP off the correctly rounded exact result in <0.05% of inputs for `std::round_to_nearest`
/// and in <1% of inputs for any other rounding mode.
///
/// **See also:** Documentation for [std::expm1](https://en.cppreference.com/w/cpp/numeric/math/expm1).
/// \param arg function argument
/// \return e raised to \a arg and subtracted by 1
/// \exception FE_INVALID for signaling NaN
/// \exception FE_OVERFLOW, ...UNDERFLOW, ...INEXACT according to rounding
inline bfloat16 expm1(bfloat16 arg)
{
#if defined(BFLOAT_ARITHMETIC_TYPE) && BFLOAT_ENABLE_CPP11_CMATH
return bfloat16(detail::binary, detail::float2bfloat16<bfloat16::round_style>(
std::expm1(detail::bfloat162float<detail::internal_t>(arg.data_))));
// temp
#else
return bfloat16(std::expm1(detail::bfloat162float_temp(arg)));
#endif
#if 0
unsigned int abs = arg.data_ & 0x7FFF, sign = arg.data_ & 0x8000;
if(!abs)
return arg;
if(abs>= 0x7F80)
return bfloat16(detail::binary, (abs==0x7F80) ? (0x7F80+(sign>>1)) : detail::signal(arg.data_));
if(abs >= 0x4A00)
return bfloat16(detail::binary, (arg.data_&0x8000) ? detail::rounded<bfloat16::round_style,true>(0xBF7F, 1, 1) : detail::overflow<bfloat16::round_style>());
detail::uint32 m = detail::multiply64(static_cast<detail::uint32>((abs&0x7F) + ((abs>0x7F)<<7))<<24, 0xB8AA3B29);
int e = (abs>>7) + (abs<=0x7F), exp;
if(e < 14)
{
exp = 0;
m >>= 14 -e;
}
else
{
exp = m >> (45-e);
m = (m<<(e-14)) & 0x7FFFFFFF;
}
m = detail::exp2(m);
if(sign)
{
int s = 0;
if(m > 0x8000000000)
{
++exp;
m = detail::divide64(0x800000000, m, s);
}
m = 0x800000000 - ((m>>exp)|((m&((static_cast<detail::uint32>(1)<<exp)-1))!=0)|s);
exp = 0;
}
else
m -= (exp<31) ? (0x800000000>>exp) : 1;
for(exp+=14; m<0x800000000 && exp; m<<=1,--exp) ;
if(exp > 29)
return bfloat16(detail::binary, detail::overflow<bfloat16::round_style>());
return bfloat16(detail::binary, detail::rounded<bfloat16::round_style,true>(sign+ (exp<<7)+(m>>24), (m>>23)&1, (m&0xFFFFF)!=0));
#endif
}
/// Natural logarithm.
/// This function is exact to rounding for all rounding modes.
///
/// **See also:** Documentation for [std::log](https://en.cppreference.com/w/cpp/numeric/math/log).
/// \param arg function argument
/// \return logarithm of \a arg to base e
/// \exception FE_INVALID for signaling NaN or negative argument
/// \exception FE_DIVBYZERO for 0
/// \exception FE_OVERFLOW, ...UNDERFLOW, ...INEXACT according to rounding
inline bfloat16 log(bfloat16 arg)
{
#ifdef BFLOAT_ARITHMETIC_TYPE
return bfloat16(detail::binary, detail::float2bfloat16<bfloat16::round_style>(
std::log(detail::bfloat162float<detail::internal_t>(arg.data_))));
// temp
#else
return bfloat16(std::log(detail::bfloat162float_temp(arg)));
#endif
#if 0
int abs = arg.data_ & 0x7FFF, exp = -15;
if(!abs)
return bfloat16(detail::binary, detail::pole(0x8000));
if(arg.data_ & 0x8000)
return bfloat16(detail::binary, (arg.data_<=0xFF80) ? detail::invalid() : detail::signal(arg.data_));
if(abs >= 0x7F80)
return (abs==0x7F80) ? arg : bfloat16(detail::binary, detail::signal(arg.data_));
for(; abs<0x80; abs<<=1,--exp) ;
exp += abs >> 7;
return bfloat16(detail::binary, detail::log2_post<bfloat16::round_style, 0xB8AA3B2A>(detail::log2(static_cast<detail::uint32>((abs&0x7F)|0x80)<<20, 27)+8, exp, 17));
#endif
}
/// Common logarithm.
/// This function is exact to rounding for all rounding modes.
///
/// **See also:** Documentation for [std::log10](https://en.cppreference.com/w/cpp/numeric/math/log10).
/// \param arg function argument
/// \return logarithm of \a arg to base 10
/// \exception FE_INVALID for signaling NaN or negative argument
/// \exception FE_DIVBYZERO for 0
/// \exception FE_OVERFLOW, ...UNDERFLOW, ...INEXACT according to rounding
inline bfloat16 log10(bfloat16 arg)
{
#ifdef BFLOAT_ARITHMETIC_TYPE
return bfloat16(detail::binary, detail::float2bfloat16<bfloat16::round_style>(
std::log10(detail::bfloat162float<detail::internal_t>(arg.data_))));
// temp
#else
return bfloat16(std::log10(detail::bfloat162float_temp(arg)));
#endif
#if 0
int abs = arg.data_ & 0x7FFF, exp = -15;
if(!abs)
return bfloat16(detail::binary, detail::pole(0x8000));
if(arg.data_ & 0x8000)
return bfloat16(detail::binary, (arg.data_<=0xFF80) ? detail::invalid() : detail::signal(arg.data_));
if(abs >= 0x7F80)
return (abs==0x7F80) ? arg : bfloat16(detail::binary, detail::signal(arg.data_));
switch(abs)
{
case 0x4900: return bfloat16(detail::binary, 0x3F80);
case 0x5640: return bfloat16(detail::binary, 0x4000);
case 0x63D0: return bfloat16(detail::binary, 0x4040);
case 0x70E2: return bfloat16(detail::binary, 0x4080);
}
for(; abs<0x80; abs<<=1,--exp) ;
exp += abs >> 10;
return bfloat16(detail::binary, detail::log2_post<bfloat16::round_style, 0xD49A784C>(detail::log2(static_cast<detail::uint32>((abs&0x7F)|0x80)<<20, 27)+8, exp, 16));
#endif
}
/// Binary logarithm.
/// This function is exact to rounding for all rounding modes.
///
/// **See also:** Documentation for [std::log2](https://en.cppreference.com/w/cpp/numeric/math/log2).
/// \param arg function argument
/// \return logarithm of \a arg to base 2
/// \exception FE_INVALID for signaling NaN or negative argument
/// \exception FE_DIVBYZERO for 0
/// \exception FE_OVERFLOW, ...UNDERFLOW, ...INEXACT according to rounding
inline bfloat16 log2(bfloat16 arg)
{
#if defined(BFLOAT_ARITHMETIC_TYPE) && BFLOAT_ENABLE_CPP11_CMATH
return bfloat16(detail::binary, detail::float2bfloat16<bfloat16::round_style>(
std::log2(detail::bfloat162float<detail::internal_t>(arg.data_))));
// temp
#else
return bfloat16(std::log2(detail::bfloat162float_temp(arg)));
#endif
#if 0
int abs = arg.data_ & 0x7FFF, exp = -15, s = 0;
if(!abs)
return bfloat16(detail::binary, detail::pole(0x8000));
if(arg.data_ & 0x8000)
return bfloat16(detail::binary, (arg.data_<=0xFF80) ? detail::invalid() : detail::signal(arg.data_));
if(abs == 0x7F80)
return (abs==0x7F80) ? arg : bfloat16(detail::binary, detail::signal(arg.data_));
if(abs == 0x3F80)
return bfloat16(detail::binary, 0);
for(; abs<0x80; abs<<=1,--exp) ;
exp += (abs>>10);
if(!(abs&0x7F))
{
unsigned int value = static_cast<unsigned>(exp<0) << 15, m = std::abs(exp) << 6;
for(exp=18; m<0x80; m<<=1,--exp) ;
return bfloat16(detail::binary, value+(exp<<10)+m);
}
detail::uint32 ilog = exp, sign = detail::sign_mask(ilog), m = (((ilog<<27)+(detail::log2(static_cast<detail::uint32>((abs&0x7F)|0x80)<<20, 28)>>4))^sign) - sign;
if(!m)
return bfloat16(detail::binary, 0);
for(exp=14; m<0x8000000 && exp; m<<=1,--exp) ;
for(; m>0xFFFFFFF; m>>=1,++exp)
s |= m & 1;
return bfloat16(detail::binary, detail::fixed2bfloat16<bfloat16::round_style, 27,false,false,true>(m, exp, sign&0x8000, s));
#endif
}
/// Natural logarithm plus one.
/// This function may be 1 ULP off the correctly rounded exact result in <0.05% of inputs for `std::round_to_nearest`
/// and in ~1% of inputs for any other rounding mode.
///
/// **See also:** Documentation for [std::log1p](https://en.cppreference.com/w/cpp/numeric/math/log1p).
/// \param arg function argument
/// \return logarithm of \a arg plus 1 to base e
/// \exception FE_INVALID for signaling NaN or argument <-1
/// \exception FE_DIVBYZERO for -1
/// \exception FE_OVERFLOW, ...UNDERFLOW, ...INEXACT according to rounding
inline bfloat16 log1p(bfloat16 arg)
{
#if defined(BFLOAT_ARITHMETIC_TYPE) && BFLOAT_ENABLE_CPP11_CMATH
return bfloat16(detail::binary, detail::float2bfloat16<bfloat16::round_style>(
std::log1p(detail::bfloat162float<detail::internal_t>(arg.data_))));
// temp
#else
return bfloat16(std::log1p(detail::bfloat162float_temp(arg)));
#endif
#if 0
if(arg.data_ >= 0xBF80)
return bfloat16(detail::binary, (arg.data_==0xBF80) ? detail::pole(0x8000) : (arg.data_<=0xFF80) ? detail::invalid() : detail::signal(arg.data_));
int abs = arg.data_ & 0x7FFF, exp = -15;
if(!abs || abs >= 0x7F80)
return (abs>0x7F80) ? bfloat16(detail::binary, detail::signal(arg.data_)) : arg;
for(; abs<0x80; abs<<=1,--exp) ;
exp += abs >> 10;
detail::uint32 m = static_cast<detail::uint32>((abs&0x7F)|0x80) << 20;
if(arg.data_ & 0x8000)
{
m = 0x40000000 - (m>>-exp);
for(exp=0; m<0x40000000; m<<=1,--exp) ;
}
else
{
if(exp < 0)
{
m = 0x40000000 + (m>>-exp);
exp = 0;
}
else
{
m += 0x40000000 >> exp;
int i = m >> 31;
m >>= i;
exp += i;
}
}
return bfloat16(detail::binary, detail::log2_post<bfloat16::round_style, 0xB8AA3B2A>(detail::log2(m), exp, 17));
#endif
}
/// \}
/// \anchor power
/// \name Power functions
/// \{
/// Square root.
/// This function is exact to rounding for all rounding modes.
///
/// **See also:** Documentation for [std::sqrt](https://en.cppreference.com/w/cpp/numeric/math/sqrt).
/// \param arg function argument
/// \return square root of \a arg
/// \exception FE_INVALID for signaling NaN and negative arguments
/// \exception FE_OVERFLOW, ...UNDERFLOW, ...INEXACT according to rounding
inline bfloat16 sqrt(bfloat16 arg)
{
#ifdef BFLOAT_ARITHMETIC_TYPE
return bfloat16(detail::binary, detail::float2bfloat16<bfloat16::round_style>(
std::sqrt(detail::bfloat162float<detail::internal_t>(arg.data_))));
// temp
#else
return bfloat16(std::sqrt(detail::bfloat162float_temp(arg)));
#endif
#if 0
int abs = arg.data_ & 0x7FFF, exp = 127;
if(!abs || arg.data_ >= 0x7F80)
return bfloat16(detail::binary, (abs>0x7F80) ? detail::signal(arg.data_) : (arg.data_>0x8000) ? detail::invalid() : arg.data_);
for(; abs<0x80; abs<<=1,--exp) ;
detail::uint32 r = static_cast<detail::uint32>((abs&0x7F)|0x80) << 7, m = detail::sqrt<20>(r, exp+=abs>>7);
return bfloat16(detail::binary, detail::rounded<bfloat16::round_style, false>((exp<<7)+(m&0x7F), r>m, r!=0));
#endif
}
/// Cubic root.
/// This function is exact to rounding for all rounding modes.
///
/// **See also:** Documentation for [std::cbrt](https://en.cppreference.com/w/cpp/numeric/math/cbrt).
/// \param arg function argument
/// \return cubic root of \a arg
/// \exception FE_INVALID for signaling NaN
/// \exception FE_OVERFLOW, ...UNDERFLOW, ...INEXACT according to rounding
inline bfloat16 cbrt(bfloat16 arg)
{
#if defined(BFLOAT_ARITHMETIC_TYPE) && BFLOAT_ENABLE_CPP11_CMATH
return bfloat16(detail::binary, detail::float2bfloat16<bfloat16::round_style>(
std::cbrt(detail::bfloat162float<detail::internalt>(arg.data_))));
// temp
#else
return bfloat16(std::cbrt(detail::bfloat162float_temp(arg)));
#endif
#if 0
int abs = arg.data_ & 0x7FFF, exp = -127;
if(!abs || abs == 0x3F80 || abs >= 0x7F80)
return (abs>0x7F80) ? bfloat16(detail::binary, detail::signal(arg.data_)) : arg;
for(; abs<0x80; abs<<=1,--exp) ;
detail::uint32 ilog = exp +(abs>>7), sign = detail::sign_mask(ilog), f, m = (((ilog<<24)+(detail::log2(static_cast<detail::uint32>((abs&0x7F)|0x80)<<20, 24)>>4))^sign) - sign;
for(exp=2; m<0x80000000; m<<=1,--exp) ;
m = detail::multiply64(m, 0xAAAAAAAB);
int i = m >>31, s;
exp += i;
m <<= 1 -i;
if(exp < 0)
{
f = m >> -exp;
exp = 0;
}
else
{
f = (m<<exp) & 0x7FFFFFFF;
exp = m >> (31-exp);
}
m = detail::exp2(f, (bfloat16::round_style==std::round_to_nearest) ? 29 : 26);
if(sign)
{
if(m > 0x80000000)
{
m = detail::divide64(0x80000000, m, s);
++exp;
}
exp = -exp;
}
return bfloat16(detail::binary, (bfloat16::round_style==std::round_to_nearest) ? detail::fixed2bfloat16<bfloat16::round_style,31,false,false,false>(m, exp+14, arg.data_&0x8000) : detail::fixed2bfloat16<bfloat16::round_style,23,false,false,false>((m+0x10)>>8, exp+14, arg.data_&0x8000));
#endif
}
/// Hypotenuse function.
/// This function is exact to rounding for all rounding modes.
///
/// **See also:** Documentation for [std::hypot](https://en.cppreference.com/w/cpp/numeric/math/hypot).
/// \param x first argument
/// \param y second argument
/// \return square root of sum of squares without internal over- or underflows
/// \exception FE_INVALID if \a x or \a y is signaling NaN
/// \exception FE_OVERFLOW, ...UNDERFLOW, ...INEXACT according to rounding of the final square root
inline bfloat16 hypot(bfloat16 x, bfloat16 y)
{
#ifdef BFLOAT_ARITHMETIC_TYPE
detail::internal_t fx = detail::bfloat162float<detail::internal_t>(x.data_),
fy = detail::bfloat162float<detail::internal_t>(y.data_);
#if BFLOAT_ENABLE_CPP11_CMATH
return bfloat16(detail::binary, detail::float2bfloat16<bfloat16::round_style>(std::hypot(fx, fy)));
#else
return bfloat16(detail::binary, detail::float2bfloat16<bfloat16::round_style>(std::sqrt(fx * fx + fy * fy)));
#endif
// temp
#else
return bfloat16(std::hypot(detail::bfloat162float_temp(x), detail::bfloat162float_temp(y)));
#endif
#if 0
int absx = x.data_ & 0x7FFF, absy = y.data_ & 0x7FFF, expx = 0, expy = 0;
if(absx >= 0x7F80 || absy >= 0x7F80)
return bfloat16(detail::binary, (absx==0x7F80) ? detail::select(0x7F80, y.data_) : (absy==0x7F80) ? detail::select(0x7F80, x.data_) : detail::signal(x.data_, y.data_));
if(!absx) return bfloat16(detail::binary, absy ? detail::check_underflow(absy) : 0);
if(!absy) return bfloat16(detail::binary, detail::check_underflow(absx));
if(absy > absx)
std::swap(absx, absy);
for(; absx<0x80; absx<<=1,--expx) ;
for(; absy<0x80; absy<<=1,--expy) ;
detail::uint32 mx = (absx&0x7F) | 0x80, my = (absy&0x7F) | 0x80;
mx *= mx;
my *= my;
int ix = mx >> 24, iy = my >> 24;
expx = 2*(expx+(absx>>7)) - 127 + ix;
expy = 2*(expy+(absy>>7)) - 127 + iy;
mx <<= 7 - ix;
my <<= 7 - iy;
int d = expx - expy;
my = (d<30) ? ((my>>d)|((my&((static_cast<detail::uint32>(1)<<d)-1))!=0)) : 1;
return bfloat16(detail::binary, detail::hypot_post<bfloat16::round_style>(mx+my, expy));
#endif
}
/// Hypotenuse function.
/// This function is exact to rounding for all rounding modes.
///
/// **See also:** Documentation for [std::hypot](https://en.cppreference.com/w/cpp/numeric/math/hypot).
/// \param x first argument
/// \param y second argument
/// \param z third argument
/// \return square root of sum of squares without internal over- or underflows
/// \exception FE_INVALID if \a x, \a y or \a z is signaling NaN
/// \exception FE_OVERFLOW, ...UNDERFLOW, ...INEXACT according to rounding of the final square root
inline bfloat16 hypot(bfloat16 x, bfloat16 y, bfloat16 z)
{
#ifdef BFLOAT_ARITHMETIC_TYPE
detail::internal_t fx = detail::bfloat162float<detail::internal_t>(x.data_),
fy = detail::bfloat162float<detail::internal_t>(y.data_),
fz = detail::bfloat162float<detail::internal_t>(z.data_);
return bfloat16(detail::binary,
detail::float2bfloat16<bfloat16::round_style>(std::sqrt(fx * fx + fy * fy + fz * fz)));
// temp
#else
return bfloat16(
std::hypot(detail::bfloat162float_temp(x), detail::bfloat162float_temp(y), detail::bfloat162float_temp(z)));
#endif
#if 0
int absx = x.data_ & 0x7FFF, absy = y.data_ & 0x7FFF, absz = z.data_ & 0x7FFF, expx = 0, expy = 0, expz = 0;
if(!absx)
return hypot(y, z);
if(!absy)
return hypot(x, z);
if(!absz)
return hypot(x, y);
if(absx >= 0x7F80 || absy >= 0x7F80 || absz >= 0x7F80)
return bfloat16(detail::binary, (absx==0x7F80) ? detail::select(0x7F80, detail::select(y.data_, z.data_)) : (absy==0x7F80) ? detail::select(0x7F80, detail::select(x.data_, z.data_)) : (absz==0x7F80) ? detail::select(0x7F80, detail::select(x.data_ ,y.data_)) : detail::signal(x.data_, y.data_, z.data_));
if(absz > absy)
std::swap(absy, absz);
if(absy > absx)
std::swap(absx, absy);
if(absz > absy)
std::swap(absy, absz);
for(; absx<0x80; absx<<=1,--expx) ;
for(; absy<0x80; absy<<=1,--expy) ;
for(; absz<0x80; absz<<=1,--expz) ;
detail::uint32 mx = (absx&0x7F) | 0x80, my = (absy&0x7F) | 0x80, mz = (absz&0x7F) | 0x80;
mx *= mx;
my *= my;
mz *= mz;
int ix = mx >> 21, iy = my >> 21, iz = mz >> 21;
expx = 2*(expx+(absx>>10)) - 15 + ix;
expy = 2*(expy+(absy>>10)) - 15 + iy;
expz = 2*(expz+(absz>>10)) - 15 + iz;
mx <<= 10 - ix;
my <<= 10 - iy;
mz <<= 10 - iz;
int d = expy - expz;
mz = (d<30) ? ((mz>>d)|((mz&((static_cast<detail::uint32>(1)<<d)-1))!=0)) : 1;
my += mz;
if(my & 0x80000000)
{
my = (my>>1) | (my&1);
if(++expy > expx)
{
std::swap(mx, my);
std::swap(expx, expy);
}
}
d = expx - expy;
my = (d<30) ? ((my>>d)|((my&((static_cast<detail::uint32>(1)<<d)-1))!=0)) : 1;
return bfloat16(detail::binary, detail::hypot_post<bfloat16::round_style>(mx+my, expx));
#endif
}
/// Power function.
/// This function may be 1 ULP off the correctly rounded exact result for any rounding mode in ~0.00025% of inputs.
///
/// **See also:** Documentation for [std::pow](https://en.cppreference.com/w/cpp/numeric/math/pow).
/// \param x base
/// \param y exponent
/// \return \a x raised to \a y
/// \exception FE_INVALID if \a x or \a y is signaling NaN or if \a x is finite an negative and \a y is finite and not
/// integral \exception FE_DIVBYZERO if \a x is 0 and \a y is negative \exception FE_OVERFLOW, ...UNDERFLOW, ...INEXACT
/// according to rounding
inline bfloat16 pow(bfloat16 x, bfloat16 y)
{
#ifdef BFLOAT_ARITHMETIC_TYPE
return bfloat16(detail::binary, detail::float2bfloat16<bfloat16::round_style>(
std::pow(detail::bfloat162float<detail::internal_t>(x.data_),
detail::bfloat162float<detail::internal_t>(y.data_))));
// temp
#else
return bfloat16(std::pow(detail::bfloat162float_temp(x), detail::bfloat162float_temp(y)));
#endif
#if 0
int absx = x.data_ & 0x7FFF, absy = y.data_ & 0x7FFF, exp = -15;
if(!absy || x.data_ == 0x3F80)
return bfloat16(detail::binary, detail::select(0x3F80, (x.data_==0x3F80) ? y.data_ : x.data_));
bool is_int = absy >= 0x6080 || (absy>=0x3F80 && !(absy&((1<<(25-(absy>>10)))-1)));
unsigned int sign = x.data_ & (static_cast<unsigned>((absy<0x6100)&&is_int&&((absy>>(25-(absy>>10)))&1))<<15);
if(absx >= 0x7F80 || absy >= 0x7F80)
return bfloat16(detail::binary, (absx>0x7F80 || absy>0x7F80) ? detail::signal(x.data_, y.data_) : (absy==0x7F80) ? ((absx==0x3F80) ? 0x3F80 : (!absx && y.data_==0xFF80) ? detail::pole() : (0x7F80&-((y.data_>>15)^(absx>0x3F80)))) : (sign|(0x7F80&((y.data_>>15)-1U))));
if(!absx)
return bfloat16(detail::binary, (y.data_&0x8000) ? detail::pole(sign) : sign);
if((x.data_&0x8000) && !is_int)
return bfloat16(detail::binary, detail::invalid());
if(x.data_==0xBF80)
return bfloat16(detail::binary, sign|0x3F80);
if(y.data_==0x3F00)
return sqrt(x);
if(y.data_==0x3F80)
return bfloat16(detail::binary, detail::check_underflow(x.data_));
if(y.data_==0x4000)
return x * x;
for(; absx<0x80; absx<<=1,--exp) ;
detail::uint32 ilog = exp + (absx>>10), msign = detail::sign_mask(ilog), f, m = (((ilog>>27)+((detail::log2(static_cast<detail::uint32>((absx&0x7F)|0x80)<<20)+8)>>4))^msign) - msign;
for(exp=-11; m<0x80000000; m<<=1,--exp) ;
for(; absy<0x80; absy<<=1,--exp) ;
m = detail::multiply64(m, static_cast<detail::uint32>((absy&0x7F)|0x80)<<21);
int i = m >> 31;
exp += (absy>>10) + i;
m <<= 1 - i;
if(exp < 0)
{
f = m >> -exp;
exp = 0;
}
else
{
f = (m<<exp) & 0x7FFFFFFF;
exp = m >> (31-exp);
}
return bfloat16(detail::binary, detail::exp2_post<bfloat16::round_style,false>(detail::exp2(f), exp, ((msign&1)^(y.data_>>15))!=0, sign));
#endif
}
/// \}
/// \anchor trigonometric
/// \name Trigonometric functions
/// \{
/// Compute sine and cosine simultaneously.
/// This returns the same results as sin() and cos() but is faster than calling each function individually.
///
/// This function is exact to rounding for all rounding modes.
/// \param arg function argument
/// \param sin variable to take sine of \a arg
/// \param cos variable to take cosine of \a arg
/// \exception FE_INVALID for signaling NaN or infinity
/// \exception FE_OVERFLOW, ...UNDERFLOW, ...INEXACT according to rounding
inline void sincos(bfloat16 arg, bfloat16 *sin, bfloat16 *cos)
{
#ifdef BFLOAT_ARITHMETIC_TYPE
detail::internal_t f = detail::bfloat162float<detail::internal_t>(arg.data_);
*sin = bfloat16(detail::binary, detail::float2bfloat16<bfloat16::round_style>(std::sin(f)));
*cos = bfloat16(detail::binary, detail::float2bfloat16<bfloat16::round_style>(std::cos(f)));
// temp
#else
*sin = bfloat16(std::sin(detail::bfloat162float_temp(arg)));
*cos = bfloat16(std::cos(detail::bfloat162float_temp(arg)));
#endif
#if 0
int abs = arg.data_ & 0x7FFF, sign = arg.data_ >> 15, k;
if(abs >= 0x7F80)
*sin = *cos = bfloat16(detail::binary, (abs==0x7F80) ? detail::invalid() : detail::signal(arg.data_));
else if(!abs)
{
*sin = arg;
*cos = bfloat16(detail::binary, 0x3F80);
}
else if(abs < 0x20A0)
{
*sin = bfloat16(detail::binary, detail::rounded<bfloat16::round_style,true>(arg.data_-1, 1, 1));
*cos = bfloat16(detail::binary, detail::rounded<bfloat16::round_style,true>(0x3F7F, 1, 1));
}
else
{
if(bfloat16::round_style != std::round_to_nearest)
{
switch(abs)
{
case 0x48B7:
*sin = bfloat16(detail::binary, detail::rounded<bfloat16::round_style,true>((~arg.data_&0x8000)|0x1D07, 1, 1));
*cos = bfloat16(detail::binary, detail::rounded<bfloat16::round_style,true>(0xBBFF, 1, 1));
return;
case 0x598C:
*sin = bfloat16(detail::binary, detail::rounded<bfloat16::round_style,true>((arg.data_&0x8000)|0x3BFF, 1, 1));
*cos = bfloat16(detail::binary, detail::rounded<bfloat16::round_style,true>(0x80FC, 1, 1));
return;
case 0x6A64:
*sin = bfloat16(detail::binary, detail::rounded<bfloat16::round_style,true>((~arg.data_&0x8000)|0x3BFE, 1, 1));
*cos = bfloat16(detail::binary, detail::rounded<bfloat16::round_style,true>(0x27FF, 1, 1));
return;
case 0x6D8C:
*sin = bfloat16(detail::binary, detail::rounded<bfloat16::round_style,true>((arg.data_&0x8000)|0x0FE6, 1, 1));
*cos = bfloat16(detail::binary, detail::rounded<bfloat16::round_style,true>(0x3BFF, 1, 1));
return;
}
}
}
std::pair<detail::uint32, detail::uint32> sc = detail::sincos(detail::angle_arg(abs, k), 28);
switch(k & 3)
{
case 1: sc = std::make_pair(sc.second, -sc.first); break;
case 2: sc = std::make_pair(-sc.first, -sc.second); break;
case 3: sc = std::make_pair(-sc.second, sc.first); break;
}
*sin = bfloat16(detail::binary, detail::fixed2bfloat16<bfloat16::round_style, 30,true,true,true>((sc.first^-static_cast<detail::uint32>(sign))+sign));
*cos = bfloat16(detail::binary, detail::fixed2bfloat16<bfloat16::round_style, 30,true,true,true>(sc.second));
#endif
}
/// Sine function.
/// This function is exact to rounding for all rounding modes.
///
/// **See also:** Documentation for [std::sin](https://en.cppreference.com/w/cpp/numeric/math/sin).
/// \param arg function argument
/// \return sine value of \a arg
/// \exception FE_INVALID for signaling NaN or infinity
/// \exception FE_OVERFLOW, ...UNDERFLOW, ...INEXACT according to rounding
inline bfloat16 sin(bfloat16 arg)
{
#ifdef BFLOAT_ARITHMETIC_TYPE
return bfloat16(detail::binary, detail::float2bfloat16<bfloat16::round_style>(
std::sin(detail::bfloat162float<detail::internal_t>(arg.data_))));
// temp
#else
return bfloat16(std::sin(detail::bfloat162float_temp(arg)));
#endif
#if 0
int abs = arg.data_ & 0x7FFF, k;
if(!abs)
return arg;
if(abs >= 0x7F80)
return bfloat16(detail::binary, (abs==0x7F80) ? detail::invalid() : detail::signal(arg.data_));
if(abs < 2120)
return bfloat16(detail::binary, detail::rounded<bfloat16::round_style,true>(arg.data_-1, 1, 1));
if(bfloat16::round_style != std::round_to_nearest)
switch(abs)
{
case 0x48B7: return bfloat16(detail::binary, detail::rounded<bfloat16::round_style,true>((~arg.data_&0x8000)|0x1D07, 1, 1));
case 0x6A64: return bfloat16(detail::binary, detail::rounded<bfloat16::round_style,true>((~arg.data_&0x8000)|0x3BFE, 1, 1));
case 0x6D8C: return bfloat16(detail::binary, detail::rounded<bfloat16::round_style,true>((arg.data_&0x8000)|0x0FE6, 1, 1));
}
std::pair<detail::uint32,detail::uint32> sc = detail::sincos(detail::angle_arg(abs,k),28);
detail::uint32 sign = -static_cast<detail::uint32>(((k>>1)&1)^(arg.data_>>15));
return bfloat16(detail::binary, detail::fixed2bfloat16<bfloat16::round_style, 30,true,true,true>((((k&1) ? sc.second : sc.first)^sign)- sign));
#endif
}
/// Cosine function.
/// This function is exact to rounding for all rounding modes.
///
/// **See also:** Documentation for [std::cos](https://en.cppreference.com/w/cpp/numeric/math/cos).
/// \param arg function argument
/// \return cosine value of \a arg
/// \exception FE_INVALID for signaling NaN or infinity
/// \exception FE_OVERFLOW, ...UNDERFLOW, ...INEXACT according to rounding
inline bfloat16 cos(bfloat16 arg)
{
#ifdef BFLOAT_ARITHMETIC_TYPE
return bfloat16(detail::binary, detail::float2bfloat16<bfloat16::round_style>(
std::cos(detail::bfloat162float<detail::internal_t>(arg.data_))));
// temp
#else
return bfloat16(std::cos(detail::bfloat162float_temp(arg)));
#endif
#if 0
int abs = arg.data_ & 0x7FFF, k;
if(!abs)
return bfloat16(detail::binary, 0x3F80);
if(abs >= 0x7F80)
return bfloat16(detail::binary, (abs==0x7F80) ? detail::invalid() : detail::signal(arg.data_));
if(abs >= 0x20A0)
return bfloat16(detail::binary, detail::rounded<bfloat16::round_style,true>(0x3BFF, 1, 1));
if(bfloat16::round_style != std::round_to_nearest && abs == 0x598C)
return bfloat16(detail::binary, detail::rounded<bfloat16::round_style,true>(0x80FC, 1, 1));
std::pair<detail::uint32, detail::uint32> sc = detail::sincos(detail::angle_arg(abs, k), 28);
detail::uint32 sign = -static_cast<detail::uint32>(((k>>1)^k)&1);
return bfloat16(detail::binary, detail::fixed2bfloat16<bfloat16::round_style, 30,true,true,true>((((k&1) ? sc.first : sc.second)^sign) - sign));
#endif
}
/// Tangent function.
/// This function is exact to rounding for all rounding modes.
///
/// **See also:** Documentation for [std::tan](https://en.cppreference.com/w/cpp/numeric/math/tan).
/// \param arg function argument
/// \return tangent value of \a arg
/// \exception FE_INVALID for signaling NaN or infinity
/// \exception FE_OVERFLOW, ...UNDERFLOW, ...INEXACT according to rounding
inline bfloat16 tan(bfloat16 arg)
{
#ifdef BFLOAT_ARITHMETIC_TYPE
return bfloat16(detail::binary, detail::float2bfloat16<bfloat16::round_style>(
std::tan(detail::bfloat162float<detail::internal_t>(arg.data_))));
// temp
#else
return bfloat16(std::tan(detail::bfloat162float_temp(arg)));
#endif
#if 0
int abs = arg.data_ & 0x7FFF, exp = 13, k;
if(!abs)
return arg;
if(abs >= 0x7F80)
return bfloat16(detail::binary, (abs==0x7F80) ? detail::invalid() : detail::signal(arg.data_));
if(abs < 0x2700)
return bfloat16(detail::binary, detail::rounded<bfloat16::round_style,true>(arg.data_, 0, 1));
if(bfloat16::round_style != std::round_to_nearest)
switch(abs)
{
case 0x658C: return bfloat16(detail::binary, detail::rounded<bfloat16::round_style,true>((arg.data_&0x8000)|0x07E6, 0, 1));
case 0x7330: return bfloat16(detail::binary, detail::rounded<bfloat16::round_style,true>((~arg.data_&0x8000)|0x4B62, 1, 1));
}
std::pair<detail::uint32,detail::uint32> sc = detail::sincos(detail::angle_arg(abs,k),30);
if(k & 1)
sc = std::make_pair(-sc.second, sc.first);
detail::uint32 signy = detail::sign_mask(sc.first), signx = detail::sign_mask(sc.second);
detail::uint32 my = (sc.first^signy) - signy, mx = (sc.second^signx) - signx;
for(; my<0x80000000; my<<=1,--exp) ;
for(; mx<0x80000000; mx<<=1,++exp) ;
return bfloat16(detail::binary, detail::tangent_post<bfloat16::round_style>(my, mx, exp, (signy^signx^arg.data_)&0x8000));
#endif
}
/// Arc sine.
/// This function is exact to rounding for all rounding modes.
///
/// **See also:** Documentation for [std::asin](https://en.cppreference.com/w/cpp/numeric/math/asin).
/// \param arg function argument
/// \return arc sine value of \a arg
/// \exception FE_INVALID for signaling NaN or if abs(\a arg) > 1
/// \exception FE_OVERFLOW, ...UNDERFLOW, ...INEXACT according to rounding
inline bfloat16 asin(bfloat16 arg)
{
#ifdef BFLOAT_ARITHMETIC_TYPE
return bfloat16(detail::binary, detail::float2bfloat16<bfloat16::round_style>(
std::asin(detail::bfloat162float<detail::internal_t>(arg.data_))));
// temp
#else
return bfloat16(std::asin(detail::bfloat162float_temp(arg)));
#endif
#if 0
unsigned int abs = arg.data_ & 0x7FFF, sign = arg.data_ & 0x8000;
if(!abs)
return arg;
if(abs >= 0x3F80)
return bfloat16(detail::binary, (abs>=0x7F80) ? detail::signal(arg.data_) : (abs>0x3F80) ? detail::invalid() : detail::rounded<bfloat16::round_style,true>(sign|0x3E48, 0, 1));
if(abs < 0x2900)
return bfloat16(detail::binary, detail::rounded<bfloat16::round_style,true>(arg.data_, 0, 1));
if(bfloat16::round_style != std::round_to_nearest && (abs == 0x2B44 || abs == 0x2DC3))
return bfloat16(detail::binary, detail::rounded<bfloat16::round_style,true>(arg.data_+1, 1, 1));
std::pair<detail::uint32,detail::uint32> sc = detail::atan2_arg(abs);
detail::uint32 m = detail::atan2(sc.first, sc.second, (bfloat16::round_style==std::round_to_nearest) ? 27 : 26);
return bfloat16(detail::binary, detail::fixed2bfloat16<bfloat16::round_style, 30,false,true,true>(m, 14, sign));
#endif
}
/// Arc cosine function.
/// This function is exact to rounding for all rounding modes.
///
/// **See also:** Documentation for [std::acos](https://en.cppreference.com/w/cpp/numeric/math/acos).
/// \param arg function argument
/// \return arc cosine value of \a arg
/// \exception FE_INVALID for signaling NaN or if abs(\a arg) > 1
/// \exception FE_OVERFLOW, ...UNDERFLOW, ...INEXACT according to rounding
inline bfloat16 acos(bfloat16 arg)
{
#ifdef BFLOAT_ARITHMETIC_TYPE
return bfloat16(detail::binary, detail::float2bfloat16<bfloat16::round_style>(
std::acos(detail::bfloat162float<detail::internal_t>(arg.data_))));
// temp
#else
return bfloat16(std::acos(detail::bfloat162float_temp(arg)));
#endif
#if 0
unsigned int abs = arg.data_ & 0x7FFF, sign = arg.data_ >> 15;
if(!abs)
return bfloat16(detail::binary, detail::rounded<bfloat16::round_style,true>(0x3E48, 0, 1));
if(abs >= 0x3F80)
return bfloat16(detail::binary, (abs>0x7F80) ? detail::signal(arg.data_) : (abs>0x3F80) ? detail::invalid() : sign ? detail::rounded<bfloat16::round_style,true>(0x4248, 0, 1) : 0);
std::pair<detail::uint32,detail::uint32> cs = detail::atan2_arg(abs);
detail::uint32 m = detail::atan2(cs.second, cs.first, 28);
return bfloat16(detail::binary, detail::fixed2bfloat16<bfloat16::round_style, 31,false,true,true>(sign ? (0xC90FDAA2-m) : m, 15, 0, sign));
#endif
}
/// Arc tangent function.
/// This function is exact to rounding for all rounding modes.
///
/// **See also:** Documentation for [std::atan](https://en.cppreference.com/w/cpp/numeric/math/atan).
/// \param arg function argument
/// \return arc tangent value of \a arg
/// \exception FE_INVALID for signaling NaN
/// \exception FE_OVERFLOW, ...UNDERFLOW, ...INEXACT according to rounding
inline bfloat16 atan(bfloat16 arg)
{
#ifdef BFLOAT_ARITHMETIC_TYPE
return bfloat16(detail::binary, detail::float2bfloat16<bfloat16::round_style>(
std::atan(detail::bfloat162float<detail::internal_t>(arg.data_))));
// temp
#else
return bfloat16(std::atan(detail::bfloat162float_temp(arg)));
#endif
#if 0
unsigned int abs = arg.data_ & 0x7FFF, sign = arg.data_ & 0x8000;
if(!abs)
return arg;
if(abs >= 0x7F80)
return bfloat16(detail::binary, (abs==0x7F80) ? detail::rounded<bfloat16::round_style,true>(sign|0x3E48, 0, 1) : detail::signal(arg.data_));
if(abs <= 0x2700)
return bfloat16(detail::binary, detail::rounded<bfloat16::round_style,true>(arg.data_-1, 1, 1));
int exp = (abs>>10) + (abs<=0x7F);
detail::uint32 my = (abs&0x7F) | ((abs>0x7F)<<10);
detail::uint32 m = (exp>15) ? detail::atan2(my<<19, 0x20000000>>(exp-15), (bfloat16::round_style==std::round_to_nearest) ? 26 : 24) : detail::atan2(my<<(exp+4), 0x20000000, (bfloat16::round_style==std::round_to_nearest) ? 30 : 28);
return bfloat16(detail::binary, detail::fixed2bfloat16<bfloat16::round_style, 30,false,true,true>(m, 14, sign));
#endif
}
/// Arc tangent function.
/// This function may be 1 ULP off the correctly rounded exact result in ~0.005% of inputs for `std::round_to_nearest`,
/// in ~0.1% of inputs for `std::round_toward_zero` and in ~0.02% of inputs for any other rounding mode.
///
/// **See also:** Documentation for [std::atan2](https://en.cppreference.com/w/cpp/numeric/math/atan2).
/// \param y numerator
/// \param x denominator
/// \return arc tangent value
/// \exception FE_INVALID if \a x or \a y is signaling NaN
/// \exception FE_OVERFLOW, ...UNDERFLOW, ...INEXACT according to rounding
inline bfloat16 atan2(bfloat16 y, bfloat16 x)
{
#ifdef BFLOAT_ARITHMETIC_TYPE
return bfloat16(detail::binary, detail::float2bfloat16<bfloat16::round_style>(
std::atan2(detail::bfloat162float<detail::internalt_t>(y.data_),
detail::bfloat162float<detail::internal_t>(x.data_))));
// temp
#else
return bfloat16(std::atan2(detail::bfloat162float_temp(y), detail::bfloat162float_temp(x)));
#endif
#if 0
unsigned int absx = x.data_ & 0x7FFF, absy = y.data_ & 0x7FFF, signx = x.data_ >> 15, signy = y.data_ & 0x8000;
if(absx >= 0x7F80 || absy >= 0x7F80)
{
if(absx > 0x7F80 || absy > 0x7F80)
return bfloat16(detail::binary, detail::signal(x.data_, y.data_));
if(absy == 0x7F80)
return bfloat16(detail::binary, (absx<0x7F80) ? detail::rounded<bfloat16::round_style,true>(signy|0x3E48, 0, 1) : signx ? detail::rounded<bfloat16::round_style,true>(signy|0x40B5, 0, 1) : detail::rounded<bfloat16::round_style,true>(signy|0x3A48, 0, 1));
return (x.data_==0x7F80) ? bfloat16(detail::binary, signy) : bfloat16(detail::binary, detail::rounded<bfloat16::round_style,true>(signy|0x4248, 0, 1));
}
if(!absy)
return signx ? bfloat16(detail::binary, detail::rounded<bfloat16::round_style,true>(signy|0x4248, 0, 1)) : y;
if(!absx)
return bfloat16(detail::binary, detail::rounded<bfloat16::round_style,true>(signy|0x3E48, 0, 1));
int d = (absy>>10) + (absy<=0x7F) - (absx>>10) - (absx<=0x7F);
if(d > (signx ? 18 : 12))
return bfloat16(detail::binary, detail::rounded<bfloat16::round_style,true>(signy|0x3E48, 0, 1));
if(signx && d < -11)
return bfloat16(detail::binary, detail::rounded<bfloat16::round_style,true>(signy|0x4248, 0, 1));
if(!signx && d < ((bfloat16::round_style==std::round_toward_zero) ? -15 : -9))
{
for(; absy<0x80; absy<<=1,--d) ;
detail::uint32 mx = ((absx<<1)&0xFF) | 0x100, my = ((absy<<1)&0xFF) | 0x100;
int i = my < mx;
d -= i;
if(d < -25)
return bfloat16(detail::binary, detail::underflow<bfloat16::round_style>(signy));
my <<= 11 + i;
return bfloat16(detail::binary, detail::fixed2bfloat16<bfloat16::round_style, 11,false,false,true>(my/mx, d+14, signy, my%mx!=0));
}
detail::uint32 m = detail::atan2(((absy&0x7F)|((absy>0x7F)<<10))<<(19+((d<0) ? d : (d>0) ? 0 : -1)), ((absx&0x7F)|((absx>0x7F)<<10))<<(19-((d>0) ? d : (d<0) ? 0 : 1)));
return bfloat16(detail::binary, detail::fixed2bfloat16<bfloat16::round_style, 31,false,true,true>(signx ? (0xC90FDAA2-m) : m, 15, signy, signx));
#endif
}
/// \}
/// \anchor hyperbolic
/// \name Hyperbolic functions
/// \{
/// Hyperbolic sine.
/// This function is exact to rounding for all rounding modes.
///
/// **See also:** Documentation for [std::sinh](https://en.cppreference.com/w/cpp/numeric/math/sinh).
/// \param arg function argument
/// \return hyperbolic sine value of \a arg
/// \exception FE_INVALID for signaling NaN
/// \exception FE_OVERFLOW, ...UNDERFLOW, ...INEXACT according to rounding
inline bfloat16 sinh(bfloat16 arg)
{
#ifdef BFLOAT_ARITHMETIC_TYPE
return bfloat16(detail::binary, detail::float2bfloat16<bfloat16::round_Style>(
std::sinh(detail::bfloat162float<detail::internal_t>(arg.data_))));
// temp
#else
return bfloat16(std::sinh(detail::bfloat162float_temp(arg)));
#endif
#if 0
int abs = arg.data_ & 0x7FFF, exp;
if(!abs || abs >= 0x7F80)
return (abs>0x7F80) ? bfloat16(detail::binary, detail::signal(arg.data_)) : arg;
if(abs <= 0x2900)
return bfloat16(detail::binary, detail::rounded<bfloat16::round_style,true>(arg.data_, 0 ,1));
std::pair<detail::uint32,detail::uint32> mm = detail::hyperbolic_args(abs, exp, (bfloat16::round_style==std::round_to_nearest) ? 29 : 17);
detail::uint32 m = mm.first - mm.second;
for(exp+=13; m<0x80000000 && exp; m<<=1,--exp) ;
unsigned int sign = arg.data_ & 0x8000;
if(exp > 29)
return bfloat16(detail::binary, detail::overflow<bfloat16::round_style>(sign));
return bfloat16(detail::binary, detail::fixed2bfloat16<bfloat16::round_style, 31,false,false,true>(m, exp, sign));
#endif
}
/// Hyperbolic cosine.
/// This function is exact to rounding for all rounding modes.
///
/// **See also:** Documentation for [std::cosh](https://en.cppreference.com/w/cpp/numeric/math/cosh).
/// \param arg function argument
/// \return hyperbolic cosine value of \a arg
/// \exception FE_INVALID for signaling NaN
/// \exception FE_OVERFLOW, ...UNDERFLOW, ...INEXACT according to rounding
inline bfloat16 cosh(bfloat16 arg)
{
#ifdef BFLOAT_ARITHMETIC_TYPE
return bfloat16(detail::binary, detail::float2bfloat16<bfloat16::round_style>(
std::cosh(detail::bfloat162float<detail::internal_t>(arg.data_))));
// temp
#else
return bfloat16(std::cosh(detail::bfloat162float_temp(arg)));
#endif
#if 0
int abs = arg.data_ & 0x7FFF, exp;
if(!abs)
return bfloat16(detail::binary, 0x3F80);
if(abs >= 0x7F80)
return bfloat16(detail::binary, (abs>0x7F80) ? detail::signal(arg.data_) : 0x7F80);
std::pair<detail::uint32,detail::uint32> mm = detail::hyperbolic_args(abs, exp, (bfloat16::round_style==std::round_to_nearest) ? 23 : 26);
detail::uint32 m = mm.first + mm.second, i = (~m&0xFFFFFFFF) >> 31;
m = (m>>i) | (m&i) | 0x80000000;
if((exp+=13+i) > 29)
return bfloat16(detail::binary, detail::overflow<bfloat16::round_style>());
return bfloat16(detail::binary, detail::fixed2bfloat16<bfloat16::round_style, 31,false,false,true>(m, exp));
#endif
}
/// Hyperbolic tangent.
/// This function is exact to rounding for all rounding modes.
///
/// **See also:** Documentation for [std::tanh](https://en.cppreference.com/w/cpp/numeric/math/tanh).
/// \param arg function argument
/// \return hyperbolic tangent value of \a arg
/// \exception FE_INVALID for signaling NaN
/// \exception FE_OVERFLOW, ...UNDERFLOW, ...INEXACT according to rounding
inline bfloat16 tanh(bfloat16 arg)
{
#ifdef BFLOAT_ARITHMETIC_TYPE
return bfloat16(detail::binary, detail::float2bfloat16<bfloat16::round_style>(
std::tanh(detail::bfloat162float<detail::internal_t>(arg.data_))));
// temp
#else
return bfloat16(std::tanh(detail::bfloat162float_temp(arg)));
#endif
#if 0
int abs = arg.data_ & 0x7FFF, exp;
if(!abs)
return arg;
if(abs >= 0x7F80)
return bfloat16(detail::binary, (abs>0x7F80) ? detail::signal(arg.data_) : (arg.data_-0x4000));
if(abs >= 0x4500)
return bfloat16(detail::binary, detail::rounded<bfloat16::round_style,true>((arg.data_&0x8000)|0x3BFF, 1, 1));
if(abs < 0x2700)
return bfloat16(detail::binary, detail::rounded<bfloat16::round_style, true>(arg.data_-1, 1, 1));
if(bfloat16::round_style != std::round_to_nearest && abs == 0x2D3F)
return bfloat16(detail::binary, detail::rounded<bfloat16::round_style,true>(arg.data_-3, 0, 1));
std::pair<detail::uint32,detail::uint32> mm = detail::hyperbolic_args(abs, exp, 27);
detail::uint32 my = mm.first - mm.second - (bfloat16::round_style!=std::round_to_nearest), mx = mm.first + mm.second, i = (~mx&0xFFFFFFFF) >> 31;
for(exp=13; my<0x80000000; my<<=1,--exp) ;
mx = (mx>>i) | 0x80000000;
return bfloat16(detail::binary, detail::tangent_post<bfloat16::round_style>(my, mx, exp-i, arg.data_&0x8000));
#endif
}
/// Hyperbolic area sine.
/// This function is exact to rounding for all rounding modes.
///
/// **See also:** Documentation for [std::asinh](https://en.cppreference.com/w/cpp/numeric/math/asinh).
/// \param arg function argument
/// \return area sine value of \a arg
/// \exception FE_INVALID for signaling NaN
/// \exception FE_OVERFLOW, ...UNDERFLOW, ...INEXACT according to rounding
inline bfloat16 asinh(bfloat16 arg)
{
#if defined(BFLOAT_ARITHMETIC_TYPE) && BFLOAT_ENABLE_CPP11_CMATH
return bfloat16(detail::binary, detail::float2bfloat16<bfloat16::round_style>(
std::asinh(detail::bfloat162float<detail::internal_t>(arg.data_))));
// temp
#else
return bfloat16(std::asinh(detail::bfloat162float_temp(arg)));
#endif
#if 0
int abs = arg.data_ & 0x7FFF;
if(!abs || abs >= 0x7F80)
return (abs>0x7F80) ? bfloat16(detail::binary, detail::signal(arg.data_)) : arg;
if(abs <= 0x2900)
return bfloat16(detail::binary, detail::rounded<bfloat16::round_style,true>(arg.data_-1, 1, 1));
if(bfloat16::round_style != std::round_to_nearest)
switch(abs)
{
case 0x32D4: return bfloat16(detail::binary, detail::rounded<bfloat16::round_style,true>(arg.data_-13, 1, 1));
case 0x3B5B: return bfloat16(detail::binary, detail::rounded<bfloat16::round_style,true>(arg.data_-197, 1, 1));
}
return bfloat16(detail::binary, detail::area<bfloat16::round_style,true>(arg.data_));
#endif
}
/// Hyperbolic area cosine.
/// This function is exact to rounding for all rounding modes.
///
/// **See also:** Documentation for [std::acosh](https://en.cppreference.com/w/cpp/numeric/math/acosh).
/// \param arg function argument
/// \return area cosine value of \a arg
/// \exception FE_INVALID for signaling NaN or arguments <1
/// \exception FE_OVERFLOW, ...UNDERFLOW, ...INEXACT according to rounding
inline bfloat16 acosh(bfloat16 arg)
{
#if defined(BFLOAT_ARITHMETIC_TYPE) && BFLOAT_ENABLE_CPP11_CMATH
return bfloat16(detail::binary, detail::float2bfloat16<bfloat16::round_style>(
std::acosh(detail::bfloat162float<detail::internal_t>(arg.data_))));
// temp
#else
return bfloat16(std::acosh(detail::bfloat162float_temp(arg)));
#endif
#if 0
int abs = arg.data_ & 0x7FFF;
if((arg.data_&0x8000) || abs <0x3F80)
return bfloat16(detail::binary, (abs<=0x7F80) ? detail::invalid() : detail::signal(arg.data_));
if(abs == 0x3F80)
return bfloat16(detail::binary, 0);
if(arg.data_ >= 0x7F80)
return (abs>0x7F80) ? bfloat16(detail::binary, detail::signal(arg.data_)) : arg;
return bfloat16(detail::binary, detail::area<bfloat16::round_style,false>(arg.data_));
#endif
}
/// Hyperbolic area tangent.
/// This function is exact to rounding for all rounding modes.
///
/// **See also:** Documentation for [std::atanh](https://en.cppreference.com/w/cpp/numeric/math/atanh).
/// \param arg function argument
/// \return area tangent value of \a arg
/// \exception FE_INVALID for signaling NaN or if abs(\a arg) > 1
/// \exception FE_DIVBYZERO for +/-1
/// \exception FE_OVERFLOW, ...UNDERFLOW, ...INEXACT according to rounding
inline bfloat16 atanh(bfloat16 arg)
{
#if defined(BFLOAT_ARITHMETIC_TYPE) && BFLOAT_ENABLE_CPP11_CMATH
return bfloat16(detail::binary, detail::float2bfloat16<bfloat16::round_style>(
std::atanh(detail::bfloat162float<detail::internal_t>(arg.data_))));
// temp
#else
return bfloat16(std::atanh(detail::bfloat162float_temp(arg)));
#endif
#if 0
int abs = arg.data_ & 0x7FFF, exp = 0;
if(!abs)
return arg;
if(abs >= 0x3F80)
return bfloat16(detail::binary, (abs== 0x3F80) ? detail::pole(arg.data_&0x8000) : (abs<= 0x7F80) ? detail::invalid() : detail::signal(arg.data_));
if(abs < 0x2700)
return bfloat16(detail::binary, detail::rounded<bfloat16::round_style,true>(arg.data_, 0, 1));
detail::uint32 m = static_cast<detail::uint32>((abs&0x7F)|((abs>0x7F)<<10)) << ((abs>>10)+(abs<=0x7F)+6), my = 0x80000000 + m, mx = 0x80000000 - m;
for(; mx<0x80000000; mx<<=1, ++exp) ;
int i = my >= mx, s;
return bfloat16(detail::binary, detail::log2_post<bfloat16::round_style, 0xB8AA3B2A>(detail::log2((detail::divide64(my>>i, mx, s)+1)>>1, 27) +0x10, exp+i-1, 16, arg.data_&0x8000));
#endif
}
/// \}
/// \anchor special
/// \name Error and gamma functions
/// \{
/// Error function.
/// This function may be 1 ULP off the correctly rounded exact result for any rounding mode in <0.5% of inputs.
///
/// **See also:** Documentation for [std::erf](https://en.cppreference.com/w/cpp/numeric/math/erf).
/// \param arg function argument
/// \return error function value of \a arg
/// \exception FE_INVALID for signaling NaN
/// \exception FE_OVERFLOW, ...UNDERFLOW, ...INEXACT according to rounding
inline bfloat16 erf(bfloat16 arg)
{
#if defined(BFLOAT_ARITHMETIC_TYPE) && BFLOAT_ENABLE_CPP11_CMATH
return bfloat16(detail::binary, detail::float2bfloat16<bfloat16::round_style>(
std::erf(detail::bfloat162float<detail::internal_t>(arg.data_))));
// temp
#else
return bfloat16(std::erf(detail::bfloat162float_temp(arg)));
#endif
#if 0
unsigned int abs = arg.data_ & 0x7FFF;
if(!abs || abs >= 0x7F80)
return (abs>=0x7F80) ? bfloat16(detail::binary, (abs==0x7F80) ? (arg.data_-0x4000) : detail::signal(arg.data_)) : arg;
if(abs >= 0x4200)
return bfloat16(detail::binary, detail::rounded<bfloat16::round_style,true>((arg.data_&0x8000)|0x3BFF, 1, 1));
return bfloat16(detail::binary, detail::erf<bfloat16::round_style,false>(arg.data_));
#endif
}
/// Complementary error function.
/// This function may be 1 ULP off the correctly rounded exact result for any rounding mode in <0.5% of inputs.
///
/// **See also:** Documentation for [std::erfc](https://en.cppreference.com/w/cpp/numeric/math/erfc).
/// \param arg function argument
/// \return 1 minus error function value of \a arg
/// \exception FE_INVALID for signaling NaN
/// \exception FE_OVERFLOW, ...UNDERFLOW, ...INEXACT according to rounding
inline bfloat16 erfc(bfloat16 arg)
{
#if defined(BFLOAT_ARITHMETIC_TYPE) && BFLOAT_ENABLE_CPP11_CMATH
return bfloat16(detail::binary, detail::float2bfloat16<bfloat16::round_style>(
std::erfc(detail::bfloat162float<detail::internal_t>(arg.data_))));
// temp
#else
return bfloat16(std::erfc(detail::bfloat162float_temp(arg)));
#endif
#if 0
unsigned int abs = arg.data_ & 0x7FFF, sign = arg.data_ & 0x8000;
if(abs >= 0x7F80)
return (abs>=0x7F80) ? bfloat16(detail::binary, (abs==0x7F80) ? (sign>>1) : detail::signal(arg.data_)) : arg;
if(!abs)
return bfloat16(detail::binary, 0x3F80);
if(abs >= 0x440)
return bfloat16(detail::binary, detail::rounded<bfloat16::round_style,true>((sign>>1)-(sign>>15), sign>>15, 1));
return bfloat16(detail::binary, detail::erf<bfloat16::round_style,true>(arg.data_));
#endif
}
/// Natural logarithm of gamma function.
/// This function may be 1 ULP off the correctly rounded exact result for any rounding mode in ~0.025% of inputs.
///
/// **See also:** Documentation for [std::lgamma](https://en.cppreference.com/w/cpp/numeric/math/lgamma).
/// \param arg function argument
/// \return natural logarith of gamma function for \a arg
/// \exception FE_INVALID for signaling NaN
/// \exception FE_DIVBYZERO for 0 or negative integer arguments
/// \exception FE_OVERFLOW, ...UNDERFLOW, ...INEXACT according to rounding
inline bfloat16 lgamma(bfloat16 arg)
{
#if defined(BFLOAT_ARITHMETIC_TYPE) && BFLOAT_ENABLE_CPP11_CMATH
return bfloat16(detail::binary,
detail::float2bfloat16 <
bfloat16::round_style(std::lgamma(detail::bfloat162float<detail::internal_t>(arg.data_))));
// temp
#else
return bfloat16(std::lgamma(detail::bfloat162float_temp(arg)));
#endif
#if 0
int abs = arg.data_ & 0x7FFF;
if(abs >= 0x7F80)
return bfloat16(detail::binary, (abs==0x7F80) ? 0x7F80 : detail::signal(arg.data_));
if(!abs || arg.data_ >= 0xE400 || (arg.data_ >= 0xBC00 && !(abs&((1<<(25-(abs>>10)))-1))))
return bfloat16(detail::binary, detail::pole());
if(arg.data_ == 0x3F80 || arg.data_ == 0x4000)
return bfloat16(detail::binary, 0);
return bfloat16(detail::binary, detail::gamma<bfloat16::round_style,true>(arg.data_));
#endif
}
/// Gamma function.
/// This function may be 1 ULP off the correctly rounded exact result for any rounding mode in <0.25% of inputs.
///
/// **See also:** Documentation for [std::tgamma](https://en.cppreference.com/w/cpp/numeric/math/tgamma).
/// \param arg function argument
/// \return gamma function value of \a arg
/// \exception FE_INVALID for signaling NaN, negative infinity or negative integer arguments
/// \exception FE_DIVBYZERO for 0
/// \exception FE_OVERFLOW, ...UNDERFLOW, ...INEXACT according to rounding
inline bfloat16 tgamma(bfloat16 arg)
{
#if defined(BFLOAT_ARITHMETIC_TYPE) && BFLOAT_ENABLE_CPP11_CMATH
return bfloat16(detail::binary, detail::float2bfloat16<bfloat16::round_style>(
std::tgamma(detail::bfloat162float<detail::internal_t>(arg.data_))));
// temp
#else
return bfloat16(std::tgamma(detail::bfloat162float_temp(arg)));
#endif
#if 0
unsigned int abs = arg.data_ & 0x7FFF;
if(!abs)
return bfloat16(detail::binary, detail::pole(arg.data_));
if(abs >= 0x7F80)
return (arg.data_==0x7F80) ? arg : bfloat16(detail::binary, detail::signal(arg.data_));
if(arg.data_ >= 0xE400 || (arg.data_ >= 0xBC00 && !(abs&((1<<(25-(abs>>10)))-1))))
return bfloat16(detail::binary, detail::invalid());
if(arg.data_ >= 0xCA80)
return bfloat16(detail::binary, detail::underflow<bfloat16::round_style>((1-((abs>>(25-(abs>>10)))&1))<<15));
if(arg.data_ >= 0x100 || (arg.data_ >= 0x4900 && arg.data_ > 0x8000))
return bfloat16(detail::binary, detail::overflow<bfloat16::round_style>());
if(arg.data_ == 0x3F80)
return arg;
return bfloat16(detail::binary, detail::gamma<bfloat16::round_style,false>(arg.data_));
#endif
}
/// \}
/// \anchor rounding
/// \name Rounding
/// \{
/// Nearest integer not less than bfloat16 value.
/// **See also:** Documentation for [std::ceil](https://en.cppreference.com/w/cpp/numeric/math/ceil).
/// \param arg bfloat16 to round
/// \return nearest integer not less than \a arg
/// \exception FE_INVALID for signaling NaN
/// \exception FE_INEXACT if value had to be rounded
inline bfloat16 ceil(bfloat16 arg)
{
return bfloat16(detail::binary, detail::integral<std::round_toward_infinity, true, true>(arg.data_));
}
/// Nearest integer not greater than bfloat16 value.
/// **See also:** Documentation for [std::floor](https://en.cppreference.com/w/cpp/numeric/math/floor).
/// \param arg bfloat16 to round
/// \return nearest integer not greater than \a arg
/// \exception FE_INVALID for signaling NaN
/// \exception FE_INEXACT if value had to be rounded
inline bfloat16 floor(bfloat16 arg)
{
return bfloat16(detail::binary, detail::integral<std::round_toward_neg_infinity, true, true>(arg.data_));
}
/// Nearest integer not greater in magnitude than bfloat16 value.
/// **See also:** Documentation for [std::trunc](https://en.cppreference.com/w/cpp/numeric/math/trunc).
/// \param arg bfloat16 to round
/// \return nearest integer not greater in magnitude than \a arg
/// \exception FE_INVALID for signaling NaN
/// \exception FE_INEXACT if value had to be rounded
inline bfloat16 trunc(bfloat16 arg)
{
return bfloat16(detail::binary, detail::integral<std::round_toward_zero, true, true>(arg.data_));
}
/// Nearest integer.
/// **See also:** Documentation for [std::round](https://en.cppreference.com/w/cpp/numeric/math/round).
/// \param arg bfloat16 to round
/// \return nearest integer, rounded away from zero in bfloat16-way cases
/// \exception FE_INVALID for signaling NaN
/// \exception FE_INEXACT if value had to be rounded
inline bfloat16 round(bfloat16 arg)
{
return bfloat16(detail::binary, detail::integral<std::round_to_nearest, false, true>(arg.data_));
}
/// Nearest integer.
/// **See also:** Documentation for [std::lround](https://en.cppreference.com/w/cpp/numeric/math/round).
/// \param arg bfloat16 to round
/// \return nearest integer, rounded away from zero in bfloat16-way cases
/// \exception FE_INVALID if value is not representable as `long`
inline long lround(bfloat16 arg) { return detail::bfloat162int<std::round_to_nearest, false, false, long>(arg.data_); }
/// Nearest integer using bfloat16's internal rounding mode.
/// **See also:** Documentation for [std::rint](https://en.cppreference.com/w/cpp/numeric/math/rint).
/// \param arg bfloat16 expression to round
/// \return nearest integer using default rounding mode
/// \exception FE_INVALID for signaling NaN
/// \exception FE_INEXACT if value had to be rounded
inline bfloat16 rint(bfloat16 arg)
{
return bfloat16(detail::binary, detail::integral<bfloat16::round_style, true, true>(arg.data_));
}
/// Nearest integer using bfloat16's internal rounding mode.
/// **See also:** Documentation for [std::lrint](https://en.cppreference.com/w/cpp/numeric/math/rint).
/// \param arg bfloat16 expression to round
/// \return nearest integer using default rounding mode
/// \exception FE_INVALID if value is not representable as `long`
/// \exception FE_INEXACT if value had to be rounded
inline long lrint(bfloat16 arg) { return detail::bfloat162int<bfloat16::round_style, true, true, long>(arg.data_); }
/// Nearest integer using bfloat16's internal rounding mode.
/// **See also:** Documentation for [std::nearbyint](https://en.cppreference.com/w/cpp/numeric/math/nearbyint).
/// \param arg bfloat16 expression to round
/// \return nearest integer using default rounding mode
/// \exception FE_INVALID for signaling NaN
inline bfloat16 nearbyint(bfloat16 arg)
{
return bfloat16(detail::binary, detail::integral<bfloat16::round_style, true, false>(arg.data_));
}
#if BFLOAT_ENABLE_CPP11_LONG_LONG
/// Nearest integer.
/// **See also:** Documentation for [std::llround](https://en.cppreference.com/w/cpp/numeric/math/round).
/// \param arg bfloat16 to round
/// \return nearest integer, rounded away from zero in bfloat16-way cases
/// \exception FE_INVALID if value is not representable as `long long`
inline long long llround(bfloat16 arg)
{
return detail::bfloat162int<std::round_to_nearest, false, false, long long>(arg.data_);
}
/// Nearest integer using bfloat16's internal rounding mode.
/// **See also:** Documentation for [std::llrint](https://en.cppreference.com/w/cpp/numeric/math/rint).
/// \param arg bfloat16 expression to round
/// \return nearest integer using default rounding mode
/// \exception FE_INVALID if value is not representable as `long long`
/// \exception FE_INEXACT if value had to be rounded
inline long long llrint(bfloat16 arg)
{
return detail::bfloat162int<bfloat16::round_style, true, true, long long>(arg.data_);
}
#endif
/// \}
/// \anchor float
/// \name Floating point manipulation
/// \{
/// Decompress floating-point number.
/// **See also:** Documentation for [std::frexp](https://en.cppreference.com/w/cpp/numeric/math/frexp).
/// \param arg number to decompress
/// \param exp address to store exponent at
/// \return significant in range [0.5, 1)
/// \exception FE_INVALID for signaling NaN
inline bfloat16 frexp(bfloat16 arg, int *exp)
{
*exp = 0;
unsigned int abs = arg.data_ & 0x7FFF;
if (abs >= 0x7F80 || !abs)
return (abs > 0x7F80) ? bfloat16(detail::binary, detail::signal(arg.data_)) : arg;
for (; abs < 0x80; abs <<= 1, --*exp)
;
*exp += (abs >> 10) - 14;
return bfloat16(detail::binary, (arg.data_ & 0x8000) | 0x3800 | (abs & 0x7F));
}
/// Multiply by power of two.
/// This function is exact to rounding for all rounding modes.
///
/// **See also:** Documentation for [std::scalbln](https://en.cppreference.com/w/cpp/numeric/math/scalbn).
/// \param arg number to modify
/// \param exp power of two to multiply with
/// \return \a arg multplied by 2 raised to \a exp
/// \exception FE_INVALID for signaling NaN
/// \exception FE_OVERFLOW, ...UNDERFLOW, ...INEXACT according to rounding
inline bfloat16 scalbln(bfloat16 arg, long exp)
{
// temp
return bfloat16(std::scalbln(detail::bfloat162float_temp(arg), exp));
unsigned int abs = arg.data_ & 0x7FFF, sign = arg.data_ & 0x8000;
if (abs >= 0x7F80 || !abs)
return (abs > 0x7F80) ? bfloat16(detail::binary, detail::signal(arg.data_)) : arg;
for (; abs < 0x80; abs <<= 1, --exp)
;
exp += abs >> 10;
if (exp > 30)
return bfloat16(detail::binary, detail::overflow<bfloat16::round_style>(sign));
else if (exp < -10)
return bfloat16(detail::binary, detail::underflow<bfloat16::round_style>(sign));
else if (exp > 0)
return bfloat16(detail::binary, sign | (exp << 10) | (abs & 0x7F));
unsigned int m = (abs & 0x7F) | 0x80;
return bfloat16(detail::binary, detail::rounded<bfloat16::round_style, false>(
sign | (m >> (1 - exp)), (m >> -exp) & 1, (m & ((1 << -exp) - 1)) != 0));
}
/// Multiply by power of two.
/// This function is exact to rounding for all rounding modes.
///
/// **See also:** Documentation for [std::scalbn](https://en.cppreference.com/w/cpp/numeric/math/scalbn).
/// \param arg number to modify
/// \param exp power of two to multiply with
/// \return \a arg multplied by 2 raised to \a exp
/// \exception FE_INVALID for signaling NaN
/// \exception FE_OVERFLOW, ...UNDERFLOW, ...INEXACT according to rounding
inline bfloat16 scalbn(bfloat16 arg, int exp) { return scalbln(arg, exp); }
/// Multiply by power of two.
/// This function is exact to rounding for all rounding modes.
///
/// **See also:** Documentation for [std::ldexp](https://en.cppreference.com/w/cpp/numeric/math/ldexp).
/// \param arg number to modify
/// \param exp power of two to multiply with
/// \return \a arg multplied by 2 raised to \a exp
/// \exception FE_INVALID for signaling NaN
/// \exception FE_OVERFLOW, ...UNDERFLOW, ...INEXACT according to rounding
inline bfloat16 ldexp(bfloat16 arg, int exp) { return scalbln(arg, exp); }
/// Extract integer and fractional parts.
/// **See also:** Documentation for [std::modf](https://en.cppreference.com/w/cpp/numeric/math/modf).
/// \param arg number to decompress
/// \param iptr address to store integer part at
/// \return fractional part
/// \exception FE_INVALID for signaling NaN
inline bfloat16 modf(bfloat16 arg, bfloat16 *iptr)
{
unsigned int abs = arg.data_ & 0x7FFF;
if (abs > 0x7F80) {
arg = bfloat16(detail::binary, detail::signal(arg.data_));
return *iptr = arg, arg;
}
if (abs >= 0x6400)
return *iptr = arg, bfloat16(detail::binary, arg.data_ & 0x8000);
if (abs < 0x3F80)
return iptr->data_ = arg.data_ & 0x8000, arg;
unsigned int exp = abs >> 10, mask = (1 << (25 - exp)) - 1, m = arg.data_ & mask;
iptr->data_ = arg.data_ & ~mask;
if (!m)
return bfloat16(detail::binary, arg.data_ & 0x8000);
for (; m < 0x80; m <<= 1, --exp)
;
return bfloat16(detail::binary, (arg.data_ & 0x8000) | (exp << 10) | (m & 0x7F));
}
/// Extract exponent.
/// **See also:** Documentation for [std::ilogb](https://en.cppreference.com/w/cpp/numeric/math/ilogb).
/// \param arg number to query
/// \return floating-point exponent
/// \retval FP_ILOGB0 for zero
/// \retval FP_ILOGBNAN for NaN
/// \retval INT_MAX for infinity
/// \exception FE_INVALID for 0 or infinite values
inline int ilogb(bfloat16 arg)
{
int abs = arg.data_ & 0x7FFF, exp;
if (!abs || abs >= 0x7F80) {
detail::raise(FE_INVALID);
return !abs ? FP_ILOGB0 : (abs == 0x7F80) ? INT_MAX : FP_ILOGBNAN;
}
for (exp = (abs >> 7) - 127; abs < 0x40; abs <<= 1, --exp)
;
return exp;
}
/// Extract exponent.
/// **See also:** Documentation for [std::logb](https://en.cppreference.com/w/cpp/numeric/math/logb).
/// \param arg number to query
/// \return floating-point exponent
/// \exception FE_INVALID for signaling NaN
/// \exception FE_DIVBYZERO for 0
inline bfloat16 logb(bfloat16 arg)
{
// temp
return bfloat16(std::logb(detail::bfloat162float_temp(arg)));
int abs = arg.data_ & 0x7FFF, exp;
if (!abs)
return bfloat16(detail::binary, detail::pole(0x8000));
if (abs >= 0x7F80)
return bfloat16(detail::binary, (abs == 0x7F80) ? 0x7F80 : detail::signal(arg.data_));
for (exp = (abs >> 7) - 127; abs < 0x40; abs <<= 1, --exp)
;
unsigned int value = static_cast<unsigned>(exp < 0) << 15;
if (exp) {
unsigned int m = std::abs(exp) << 6; // why 6
for (exp = 18; m < 0x80; m <<= 1, --exp)
; // why 18
value |= (exp << 7) + m;
}
return bfloat16(detail::binary, value);
}
/// Next representable value.
/// **See also:** Documentation for [std::nextafter](https://en.cppreference.com/w/cpp/numeric/math/nextafter).
/// \param from value to compute next representable value for
/// \param to direction towards which to compute next value
/// \return next representable value after \a from in direction towards \a to
/// \exception FE_INVALID for signaling NaN
/// \exception FE_OVERFLOW for infinite result from finite argument
/// \exception FE_UNDERFLOW for subnormal result
inline bfloat16 nextafter(bfloat16 from, bfloat16 to)
{
int fabs = from.data_ & 0x7FFF, tabs = to.data_ & 0x7FFF;
if (fabs > 0x7F80 || tabs > 0x7F80)
return bfloat16(detail::binary, detail::signal(from.data_, to.data_));
if (from.data_ == to.data_ || !(fabs | tabs))
return to;
if (!fabs) {
detail::raise(FE_UNDERFLOW, !BFLOAT_ERRHANDLING_UNDERFLOW_TO_INEXACT);
return bfloat16(detail::binary, (to.data_ & 0x8000) + 1);
}
unsigned int out =
from.data_ +
(((from.data_ >> 15) ^ static_cast<unsigned>((from.data_ ^ (0x8000 | (0x8000 - (from.data_ >> 15)))) <
(to.data_ ^ (0x8000 | (0x8000 - (to.data_ >> 15))))))
<< 1) -
1;
detail::raise(FE_OVERFLOW, fabs < 0x7F80 && (out & 0x7F80) == 0x7F80);
detail::raise(FE_UNDERFLOW, !BFLOAT_ERRHANDLING_UNDERFLOW_TO_INEXACT && (out & 0x7F80) < 0x80);
return bfloat16(detail::binary, out);
}
/// Next representable value.
/// **See also:** Documentation for [std::nexttoward](https://en.cppreference.com/w/cpp/numeric/math/nexttoward).
/// \param from value to compute next representable value for
/// \param to direction towards which to compute next value
/// \return next representable value after \a from in direction towards \a to
/// \exception FE_INVALID for signaling NaN
/// \exception FE_OVERFLOW for infinite result from finite argument
/// \exception FE_UNDERFLOW for subnormal result
inline bfloat16 nexttoward(bfloat16 from, long double to)
{
int fabs = from.data_ & 0x7FFF;
if (fabs > 0x7F80)
return bfloat16(detail::binary, detail::signal(from.data_));
long double lfrom = static_cast<long double>(from);
if (detail::builtin_isnan(to) || lfrom == to)
return bfloat16(static_cast<float>(to));
if (!fabs) {
detail::raise(FE_UNDERFLOW, !BFLOAT_ERRHANDLING_UNDERFLOW_TO_INEXACT);
return bfloat16(detail::binary, (static_cast<unsigned>(detail::builtin_signbit(to)) << 15) + 1);
}
unsigned int out = from.data_ + (((from.data_ >> 15) ^ static_cast<unsigned>(lfrom < to)) << 1) - 1;
detail::raise(FE_UNDERFLOW, (out & 0x7FFF) == 0x7F80);
detail::raise(FE_UNDERFLOW, !BFLOAT_ERRHANDLING_UNDERFLOW_TO_INEXACT && (out & 0x7FFF) < 0x80);
return bfloat16(detail::binary, out);
}
/// Take sign.
/// **See also:** Documentation for [std::copysign](https://en.cppreference.com/w/cpp/numeric/math/copysign).
/// \param x value to change sign for
/// \param y value to take sign from
/// \return value equal to \a x in magnitude and to \a y in sign
inline BFLOAT_CONSTEXPR bfloat16 copysign(bfloat16 x, bfloat16 y)
{
return bfloat16(detail::binary, x.data_ ^ ((x.data_ ^ y.data_) & 0x8000));
}
/// \}
/// \anchor classification
/// \name Floating point classification
/// \{
/// Classify floating-point value.
/// **See also:** Documentation for [std::fpclassify](https://en.cppreference.com/w/cpp/numeric/math/fpclassify).
/// \param arg number to classify
/// \retval FP_ZERO for positive and negative zero
/// \retval FP_SUBNORMAL for subnormal numbers
/// \retval FP_INFINITY for positive and negative infinity
/// \retval FP_NAN for NaNs
/// \retval FP_NORMAL for all other (normal) values
inline BFLOAT_CONSTEXPR int fpclassify(bfloat16 arg)
{
return !(arg.data_ & 0x7FFF) ? FP_ZERO
: ((arg.data_ & 0x7FFF) < 0x80) ? FP_SUBNORMAL
: ((arg.data_ & 0x7FFF) < 0x7F80) ? FP_NORMAL
: ((arg.data_ & 0x7FFF) == 0x7F80) ? FP_INFINITE
: FP_NAN;
}
/// Check if finite number.
/// **See also:** Documentation for [std::isfinite](https://en.cppreference.com/w/cpp/numeric/math/isfinite).
/// \param arg number to check
/// \retval true if neither infinity nor NaN
/// \retval false else
inline BFLOAT_CONSTEXPR bool isfinite(bfloat16 arg) { return (arg.data_ & 0x7F80) != 0x7F80; }
/// Check for infinity.
/// **See also:** Documentation for [std::isinf](https://en.cppreference.com/w/cpp/numeric/math/isinf).
/// \param arg number to check
/// \retval true for positive or negative infinity
/// \retval false else
inline BFLOAT_CONSTEXPR bool isinf(bfloat16 arg) { return (arg.data_ & 0x7FFF) == 0x7F80; }
/// Check for NaN.
/// **See also:** Documentation for [std::isnan](https://en.cppreference.com/w/cpp/numeric/math/isnan).
/// \param arg number to check
/// \retval true for NaNs
/// \retval false else
inline BFLOAT_CONSTEXPR bool isnan(bfloat16 arg) { return (arg.data_ & 0x7FFF) > 0x7F80; }
/// Check if normal number.
/// **See also:** Documentation for [std::isnormal](https://en.cppreference.com/w/cpp/numeric/math/isnormal).
/// \param arg number to check
/// \retval true if normal number
/// \retval false if either subnormal, zero, infinity or NaN
inline BFLOAT_CONSTEXPR bool isnormal(bfloat16 arg)
{
return ((arg.data_ & 0x7F80) != 0) & ((arg.data_ & 0x7F80) != 0x7F80);
}
/// Check sign.
/// **See also:** Documentation for [std::signbit](https://en.cppreference.com/w/cpp/numeric/math/signbit).
/// \param arg number to check
/// \retval true for negative number
/// \retval false for positive number
inline BFLOAT_CONSTEXPR bool signbit(bfloat16 arg) { return (arg.data_ & 0x8000) != 0; }
/// \}
/// \anchor compfunc
/// \name Comparison
/// \{
/// Quiet comparison for greater than.
/// **See also:** Documentation for [std::isgreater](https://en.cppreference.com/w/cpp/numeric/math/isgreater).
/// \param x first operand
/// \param y second operand
/// \retval true if \a x greater than \a y
/// \retval false else
inline BFLOAT_CONSTEXPR bool isgreater(bfloat16 x, bfloat16 y)
{
return ((x.data_ ^ (0x8000 | (0x8000 - (x.data_ >> 15)))) + (x.data_ >> 15)) >
((y.data_ ^ (0x8000 | (0x8000 - (y.data_ >> 15)))) + (y.data_ >> 15)) &&
!isnan(x) && !isnan(y);
}
/// Quiet comparison for greater equal.
/// **See also:** Documentation for
/// [std::isgreaterequal](https://en.cppreference.com/w/cpp/numeric/math/isgreaterequal). \param x first operand \param
/// y second operand \retval true if \a x greater equal \a y \retval false else
inline BFLOAT_CONSTEXPR bool isgreaterequal(bfloat16 x, bfloat16 y)
{
return ((x.data_ ^ (0x8000 | (0x8000 - (x.data_ >> 15)))) + (x.data_ >> 15)) >=
((y.data_ ^ (0x8000 | (0x8000 - (y.data_ >> 15)))) + (y.data_ >> 15)) &&
!isnan(x) && !isnan(y);
}
/// Quiet comparison for less than.
/// **See also:** Documentation for [std::isless](https://en.cppreference.com/w/cpp/numeric/math/isless).
/// \param x first operand
/// \param y second operand
/// \retval true if \a x less than \a y
/// \retval false else
inline BFLOAT_CONSTEXPR bool isless(bfloat16 x, bfloat16 y)
{
return ((x.data_ ^ (0x8000 | (0x8000 - (x.data_ >> 15)))) + (x.data_ >> 15)) <
((y.data_ ^ (0x8000 | (0x8000 - (y.data_ >> 15)))) + (y.data_ >> 15)) &&
!isnan(x) && !isnan(y);
}
/// Quiet comparison for less equal.
/// **See also:** Documentation for [std::islessequal](https://en.cppreference.com/w/cpp/numeric/math/islessequal).
/// \param x first operand
/// \param y second operand
/// \retval true if \a x less equal \a y
/// \retval false else
inline BFLOAT_CONSTEXPR bool islessequal(bfloat16 x, bfloat16 y)
{
return ((x.data_ ^ (0x8000 | (0x8000 - (x.data_ >> 15)))) + (x.data_ >> 15)) <=
((y.data_ ^ (0x8000 | (0x8000 - (y.data_ >> 15)))) + (y.data_ >> 15)) &&
!isnan(x) && !isnan(y);
}
/// Quiet comparison for less or greater.
/// **See also:** Documentation for [std::islessgreater](https://en.cppreference.com/w/cpp/numeric/math/islessgreater).
/// \param x first operand
/// \param y second operand
/// \retval true if either less or greater
/// \retval false else
inline BFLOAT_CONSTEXPR bool islessgreater(bfloat16 x, bfloat16 y)
{
return x.data_ != y.data_ && ((x.data_ | y.data_) & 0x7FFF) && !isnan(x) && !isnan(y);
}
/// Quiet check if unordered.
/// **See also:** Documentation for [std::isunordered](https://en.cppreference.com/w/cpp/numeric/math/isunordered).
/// \param x first operand
/// \param y second operand
/// \retval true if unordered (one or two NaN operands)
/// \retval false else
inline BFLOAT_CONSTEXPR bool isunordered(bfloat16 x, bfloat16 y) { return isnan(x) || isnan(y); }
/// \}
/// \anchor casting
/// \name Casting
/// \{
/// Cast to or from bfloat16-precision floating-point number.
/// This casts between [bfloat16](\ref bfloat16::bfloat16) and any built-in arithmetic type. The values are converted
/// directly using the default rounding mode, without any roundtrip over `float` that a `static_cast` would otherwise
/// do.
///
/// Using this cast with neither of the two types being a [bfloat16](\ref bfloat16::bfloat16) or with any of the two
/// types not being a built-in arithmetic type (apart from [bfloat16](\ref bfloat16::bfloat16), of course) results in a
/// compiler error and casting between [bfloat16](\ref bfloat16::bfloat16)s returns the argument unmodified. \tparam T
/// destination type (bfloat16 or built-in arithmetic type) \tparam U source type (bfloat16 or built-in arithmetic type)
/// \param arg value to cast
/// \return \a arg converted to destination type
/// \exception FE_INVALID if \a T is integer type and result is not representable as \a T
/// \exception FE_OVERFLOW, ...UNDERFLOW, ...INEXACT according to rounding
template <typename T, typename U> T bfloat16_cast(U arg) { return detail::bfloat16_caster<T, U>::cast(arg); }
/// Cast to or from bfloat16-precision floating-point number.
/// This casts between [bfloat16](\ref bfloat16::bfloat16) and any built-in arithmetic type. The values are converted
/// directly using the specified rounding mode, without any roundtrip over `float` that a `static_cast` would otherwise
/// do.
///
/// Using this cast with neither of the two types being a [bfloat16](\ref bfloat16::bfloat16) or with any of the two
/// types not being a built-in arithmetic type (apart from [bfloat16](\ref bfloat16::bfloat16), of course) results in a
/// compiler error and casting between [bfloat16](\ref bfloat16::bfloat16)s returns the argument unmodified. \tparam T
/// destination type (bfloat16 or built-in arithmetic type) \tparam R rounding mode to use. \tparam U source type
/// (bfloat16 or built-in arithmetic type) \param arg value to cast \return \a arg converted to destination type
/// \exception FE_INVALID if \a T is integer type and result is not representable as \a T
/// \exception FE_OVERFLOW, ...UNDERFLOW, ...INEXACT according to rounding
template <typename T, std::float_round_style R, typename U> T bfloat16_cast(U arg)
{
return detail::bfloat16_caster<T, U, R>::cast(arg);
}
/// \}
/// \}
/// \anchor errors
/// \name Error handling
/// \{
/// Clear exception flags.
/// This function works even if [automatic exception flag handling](\ref BFLOAT_ERRHANDLING_FLAGS) is disabled,
/// but in that case manual flag management is the only way to raise flags.
///
/// **See also:** Documentation for [std::feclearexcept](https://en.cppreference.com/w/cpp/numeric/fenv/feclearexcept).
/// \param excepts OR of exceptions to clear
/// \retval 0 all selected flags cleared successfully
inline int feclearexcept(int excepts)
{
detail::errflags() &= ~excepts;
return 0;
}
/// Test exception flags.
/// This function works even if [automatic exception flag handling](\ref BFLOAT_ERRHANDLING_FLAGS) is disabled,
/// but in that case manual flag management is the only way to raise flags.
///
/// **See also:** Documentation for [std::fetestexcept](https://en.cppreference.com/w/cpp/numeric/fenv/fetestexcept).
/// \param excepts OR of exceptions to test
/// \return OR of selected exceptions if raised
inline int fetestexcept(int excepts) { return detail::errflags() & excepts; }
/// Raise exception flags.
/// This raises the specified floating point exceptions and also invokes any additional automatic exception handling as
/// configured with the [BFLOAT_ERRHANDLIG_...](\ref BFLOAT_ERRHANDLING_ERRNO) preprocessor symbols.
/// This function works even if [automatic exception flag handling](\ref BFLOAT_ERRHANDLING_FLAGS) is disabled,
/// but in that case manual flag management is the only way to raise flags.
///
/// **See also:** Documentation for [std::feraiseexcept](https://en.cppreference.com/w/cpp/numeric/fenv/feraiseexcept).
/// \param excepts OR of exceptions to raise
/// \retval 0 all selected exceptions raised successfully
inline int feraiseexcepts(int excepts)
{
detail::errflags() |= excepts;
detail::raise(excepts);
return 0;
}
/// Save exception flags.
/// This function works even if [automatic exception flag handling](\ref BFLOAT_ERRHANDLING_FLAGS) is disabled,
/// but in that case manual flag management is the only way to raise flags.
///
/// **See also:** Documentation for [std::fegetexceptflag](https://en.cppreference.com/w/cpp/numeric/fenv/feexceptflag).
/// \param flagp adress to store flag state at
/// \param excepts OR of flags to save
/// \retval 0 for success
inline int fegetexceptflag(int *flagp, int excepts)
{
*flagp = detail::errflags() & excepts;
return 0;
}
/// Restore exception flags.
/// This only copies the specified exception state (including unset flags) without incurring any additional exception
/// handling. This function works even if [automatic exception flag handling](\ref BFLOAT_ERRHANDLING_FLAGS) is
/// disabled, but in that case manual flag management is the only way to raise flags.
///
/// **See also:** Documentation for [std::fesetexceptflag](https://en.cppreference.com/w/cpp/numeric/fenv/feexceptflag).
/// \param flagp adress to take flag state from
/// \param excepts OR of flags to restore
/// \retval 0 for success
inline int fesetexceptflag(const int *flagp, int excepts)
{
detail::errflags() = (detail::errflags() | (*flagp & excepts)) & (*flagp | ~excepts);
return 0;
}
/// Throw C++ exceptions based on set exception flags.
/// This function manually throws a corresponding C++ exception if one of the specified flags is set,
/// no matter if automatic throwing (via [BFLOAT_ERRHANDLING_THROW_...](\ref BFLOAT_ERRHANDLING_THROW_INVALID)) is
/// enabled or not. This function works even if [automatic exception flag handling](\ref BFLOAT_ERRHANDLING_FLAGS) is
/// disabled, but in that case manual flag management is the only way to raise flags. \param excepts OR of exceptions to
/// test \param msg error message to use for exception description \throw std::domain_error if `FE_INVALID` or
/// `FE_DIVBYZERO` is selected and set \throw std::overflow_error if `FE_OVERFLOW` is selected and set \throw
/// std::underflow_error if `FE_UNDERFLOW` is selected and set \throw std::range_error if `FE_INEXACT` is selected and
/// set
inline void fethrowexcept(int excepts, const char *msg = "")
{
excepts &= detail::errflags();
if (excepts & (FE_INVALID | FE_DIVBYZERO))
throw std::domain_error(msg);
if (excepts & FE_OVERFLOW)
throw std::overflow_error(msg);
if (excepts & FE_UNDERFLOW)
throw std::underflow_error(msg);
if (excepts & FE_INEXACT)
throw std::range_error(msg);
}
/// \}
} // namespace bfloat16
#undef BFLOAT_UNUSED_NOERR
#undef BFLOAT_CONSTEXPR
#undef BFLOAT_CONSTEXPR_CONST
#undef BFLOAT_CONSTEXPR_NOERR
#undef BFLOAT_NOEXCEPT
#undef BFLOAT_NOTHROW
#undef BFLOAT_THREAD_LOCAL
#undef BFLOAT_TWOS_COMPLEMENT_INT
#ifdef BFLOAT_POP_WARNING
#pragma warning(pop)
#undef BFLOAT_POP_WARNINGS
#endif
#endif
| 195,517
|
C++
|
.h
| 4,372
| 39.74108
| 327
| 0.647205
|
metric-space-ai/metric
| 34
| 14
| 44
|
MPL-2.0
|
9/20/2024, 10:43:29 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,531,670
|
genetic_impl.hpp
|
metric-space-ai_metric/metric/utils/genetic/genetic_impl.hpp
|
#ifndef _GENETIC_IMPLEMENTATION_HPP
#define _GENETIC_IMPLEMENTATION_HPP
#include <iomanip>
template <typename P, typename T = double> class Genetic {
static_assert(std::is_same<float, T>::value || std::is_same<double, T>::value,
"variable type can only be float or double, please amend.");
// template <typename H,typename K>
friend class genetic_details::Population<P, T>;
template <typename H, typename K> friend class Chromosome;
template <typename H, typename K = double> using Func = std::vector<K> (*)(const H &);
template <typename H, typename K> using SelMethodFunc = void (*)(genetic_details::Population<H, K> &);
template <typename H, typename K>
using CrsMethodFunc = void (*)(const genetic_details::Population<H, K> &, genetic_details::CHR<H, K> &,
genetic_details::CHR<H, K> &);
template <typename H, typename K> using MutMethodFunc = void (*)(genetic_details::CHR<H, K> &);
template <typename H, typename K> using AdpMethodFunc = void (*)(genetic_details::Population<H, K> &);
template <typename H> using HardConstraintFunc = bool(const H &);
template <typename H, typename K = double> using SoftConstraintFunc = T(const H &);
public:
genetic_details::Population<P, T> pop; // population of chromosomes
std::vector<genetic_details::PAR<T>> param; // parameter(s)
P lowerBound; // parameter(s) lower bound
P upperBound; // parameter(s) upper bound
std::vector<P> initialSet; // initial set of parameter(s)
std::vector<int> idx; // indexes for chromosome breakdown
// selection method initialized to roulette wheel selection
SelMethodFunc<P, T> Selection = proportional_roulette_wheel_selection;
// cross-over method initialized to 1-point cross-over
CrsMethodFunc<P, T> CrossOver = one_point_random_crossover;
// mutation method initialized to single-point mutation
MutMethodFunc<P, T> Mutation = single_point_mutation;
// adaptation to constraint(s) method
AdpMethodFunc<P, T> Adaptation = nullptr;
// constraint(s)
std::vector<std::function<HardConstraintFunc<P>>> HardConstraints;
std::vector<std::function<SoftConstraintFunc<P>>> SoftConstraints;
// objective function pointer
Func<P, T> Objective;
T covrate = .50; // cross-over rate
T mutrate = .05; // mutation rate
T SP = 1.5; // selective pressure for linear_rank_based_with_selective_pressure_selection selection method
T tolerance = 0.0; // terminal condition (inactive if equal to zero)
int elitpop = 1; // elit population size
int matsize; // mating pool size, set to popsize by default
int tournament_selectionsize = 10; // tournament size
int genstep = 10; // generation step for outputting results
int precision = 5; // precision for outputting results
public:
// constructor
Genetic(Func<P, T> objective, const std::vector<P> &args, int popsize = 100, int nbgen = 50, bool output = false);
// set evolution methods
void change_evolution_method(SelMethodFunc<P, T> sel, CrsMethodFunc<P, T> crs, MutMethodFunc<P, T> mut,
AdpMethodFunc<P, T> adp);
void addHardConstraint(std::function<HardConstraintFunc<P>> cF) { HardConstraints.push_back(cF); };
void addSoftConstraint(std::function<SoftConstraintFunc<P>> cF) { SoftConstraints.push_back(cF); };
std::vector<T> (*Constraint)(const P &) = nullptr;
// run genetic algorithm
void run();
void perform_evolutionary_steps(int numEvolStep);
// return best chromosome
const genetic_details::CHR<P, T> &result() const;
std::vector<P> top(unsigned int n) const;
std::vector<P> bottom(unsigned int n) const;
void population();
void resize_population(int np);
void refresh_population(int refreshNum, bool random = true);
void refresh_population(const std::vector<P> &, bool random = true);
template <typename H> void addParam(const std::vector<H> &, const H &, const H &);
public:
int nbbit; // total number of bits per chromosome
int nbgen; // number of generations
int nogen = 0; // numero of generation
int nbparam; // number of parameters to be estimated
int popsize; // population size
bool output; // control if results must be outputted
// end of recursion for initializing parameter(s) data
// end of recursion for initializing parameter(s) data
template <int I, typename... Tp>
inline typename std::enable_if<I == sizeof...(Tp), void>::type init(const std::vector<std::tuple<Tp...>> &t);
// recursion for initializing parameter(s) data
template <int I, typename... Tp>
inline typename std::enable_if < I<sizeof...(Tp), void>::type init(const std::vector<std::tuple<Tp...>> &t);
// end of iterating parameter(s) data
template <int I, typename... Tp>
inline typename std::enable_if<I == sizeof...(Tp), void>::type printParam(std::tuple<Tp...> ¶mset) const;
// iterating parameter(s) data
template <int I, typename... Tp>
inline typename std::enable_if < I<sizeof...(Tp), void>::type printParam(std::tuple<Tp...> ¶mset) const;
// check inputs validity
void check() const;
// print results for each new generation
void print(int n = 1) const;
};
// constructor
template <typename P, typename T>
Genetic<P, T>::Genetic(Func<P, T> objective, const std::vector<P> &args, int popsize, int nbgen, bool output)
{
this->Objective = objective;
// getting total number of bits per chromosome
this->nbgen = nbgen;
// getting number of parameters in the pack
this->popsize = popsize;
this->matsize = popsize;
this->output = output;
this->nbparam = std::tuple_size<P>::value;
this->nbbit = 0;
initialSet = args;
this->init<0>(args);
}
// end of recursion for initializing parameter(s) data
template <typename P, typename T>
template <int I, typename... Tp>
inline typename std::enable_if<I == sizeof...(Tp), void>::type
Genetic<P, T>::init(const std::vector<std::tuple<Tp...>> ¶mset)
{
}
// recursion for initializing parameter(s) data
template <typename P, typename T>
template <int I, typename... Tp>
inline typename std::enable_if <
I<sizeof...(Tp), void>::type Genetic<P, T>::init(const std::vector<std::tuple<Tp...>> ¶mset)
{
// getting Ith parameter in tuple
auto par = std::get<I>(paramset[0]);
// getting Ith parameter initial data
// const std::vector<T>& data = par.getData();
// copying parameter data
param.emplace_back(new genetic_details::Parameter<T>());
this->nbbit += param[I]->size();
// if parameter has initial value
// initialSet.push_back(par);
// setting indexes for chromosome breakdown
if (I == 0) {
idx.push_back(0);
} else {
idx.push_back(idx[I - 1] + param[I]->size());
}
auto minV = std::get<I>(paramset[0]);
auto maxV = std::get<I>(paramset[0]);
for (const auto &x : paramset) {
minV = std::min(minV, std::get<I>(x));
maxV = std::max(maxV, std::get<I>(x));
}
std::get<I>(lowerBound) = minV;
std::get<I>(upperBound) = maxV;
param[I]->boundaries(minV, maxV);
// recursing
init<I + 1, Tp...>(paramset);
}
// check inputs validity
template <typename P, typename T> void Genetic<P, T>::check() const
{
if (SP < 1.0 || SP > 2.0) {
throw std::invalid_argument("Error: in class genetic_details::Genetic<P,T>, selective pressure (SP) cannot be "
"outside [1.0,2.0], please choose a real value within this interval.");
}
if (elitpop > popsize || elitpop < 0) {
throw std::invalid_argument("Error: in class genetic_details::Genetic<P,T>, elit population (elitpop) cannot "
"outside [0,popsize], please choose an integral value within this interval.");
}
if (covrate < 0.0 || covrate > 1.0) {
throw std::invalid_argument("Error: in class genetic_details::Genetic<P,T>, cross-over rate (covrate) cannot "
"outside [0.0,1.0], please choose a real value within this interval.");
}
if (genstep <= 0) {
throw std::invalid_argument("Error: in class genetic_details::Genetic<P,T>, generation step (genstep) cannot "
"be <= 0, please choose an integral value > 0.");
}
}
// set evolution methods
template <typename P, typename T>
void Genetic<P, T>::change_evolution_method(SelMethodFunc<P, T> sel, CrsMethodFunc<P, T> crs, MutMethodFunc<P, T> mut,
AdpMethodFunc<P, T> adp)
{
// selection method initialized to roulette wheel selection
SelMethodFunc<P, T> Selection = sel;
// cross-over method initialized to 1-point cross-over
CrsMethodFunc<P, T> CrossOver = crs;
// mutation method initialized to single-point mutation
MutMethodFunc<P, T> Mutation = mut;
AdpMethodFunc<P, T> Adaptation = adp;
}
// run genetic algorithm
template <typename P, typename T> void Genetic<P, T>::run()
{
// checking inputs validity
this->check();
// setting adaptation method to default if needed
if (!SoftConstraints.empty() && Adaptation == nullptr) {
Adaptation = DAC;
}
// initializing population
pop = genetic_details::Population<P, T>(*this);
if (output) {
std::cout << "\n Running Genetic Algorithm...\n";
std::cout << " ----------------------------\n";
}
// creating population
pop.creation();
// initializing best result and previous best result
T bestResult = pop(0)->getTotal();
T prevBestResult = bestResult;
// outputting results
if (output)
print();
// starting population evolution
for (nogen = 1; nogen <= nbgen; ++nogen) {
// evolving population
pop.evolution();
// getting best current result
bestResult = pop(0)->getTotal();
// outputting results
if (output)
print();
// checking convergence
if (tolerance != 0.0) {
if (fabs(bestResult - prevBestResult) < fabs(tolerance)) {
break;
}
prevBestResult = bestResult;
}
}
if (output)
std::cout << std::endl;
}
// end of iterating parameter(s) data
template <typename P, typename T>
template <int I, typename... Tp>
inline typename std::enable_if<I == sizeof...(Tp), void>::type
Genetic<P, T>::printParam(std::tuple<Tp...> ¶mset) const
{
}
// iterating parameter(s) data
template <typename P, typename T>
template <int I, typename... Tp>
inline typename std::enable_if <
I<sizeof...(Tp), void>::type Genetic<P, T>::printParam(std::tuple<Tp...> ¶mset) const
{
std::cout << " X";
std::cout << std::to_string(I + 1);
std::cout << " = " << std::setw(9) << std::fixed << std::setprecision(precision) << std::get<I>(paramset) << " |";
printParam<I + 1, Tp...>(paramset);
}
// return best chromosome
template <typename P, typename T> inline const genetic_details::CHR<P, T> &Genetic<P, T>::result() const
{
return pop(0);
}
template <typename P, typename T> std::vector<P> Genetic<P, T>::top(unsigned int n) const
{
std::vector<P> vP;
for (auto i = 0; (i < n) && (i < pop.popsize()); i++) {
vP.push_back(pop(i)->getParam());
}
return vP;
}
template <typename P, typename T> std::vector<P> Genetic<P, T>::bottom(unsigned int n) const
{
std::vector<P> vP;
for (auto i = pop.popsize() - 1; (i >= pop.popsize() - n) && (i > 0); i--) {
vP.push_back(pop(i)->getParam());
}
return vP;
}
// print results for each new generation
template <typename P, typename T> void Genetic<P, T>::print(int n) const
{
// getting best parameter(s) from best chromosome
std::vector<P> bestParams = top(n);
std::vector<T> bestResult = pop(0)->getResult();
if (nogen % genstep == 0) {
std::cout << " Generation = " << std::setw(std::to_string(nbgen).size()) << nogen << " |";
for (auto pa : bestParams)
printParam<0>(pa);
for (unsigned i = 0; i < bestResult.size(); ++i) {
std::cout << " F";
if (bestResult.size() > 1) {
std::cout << std::to_string(i + 1);
}
std::cout << "(x) = " << std::setw(12) << std::fixed << std::setprecision(precision) << bestResult[i];
if (i < bestResult.size() - 1) {
std::cout << " |";
} else {
std::cout << "\n";
}
}
}
}
// print results for each new generation
template <typename P, typename T>
template <typename H>
void Genetic<P, T>::addParam(const std::vector<H> &staticParam, const H &minValue, const H &maxValue)
{
if (staticParam.size() != popsize)
return;
param.emplace_back(new genetic_details::Parameter<T>());
const int len = param.size();
this->nbbit += param[len - 1]->size();
param[len - 1]->boundaries(minValue, maxValue);
for (auto i = 0; i < popsize; i++) {
std::string ss = param[len - 1]->encode(staticParam[i]);
pop.addParam(i, ss);
}
}
// resize population
template <typename P, typename T> void Genetic<P, T>::resize_population(int npop)
{
this->popsize = npop;
this->matsize = npop;
// initializing population
pop = genetic_details::Population<P, T>(*this);
// creating population
pop.creation();
}
// resize population
template <typename P, typename T> void Genetic<P, T>::refresh_population(int refreshNum, bool random)
{
pop.refresh(refreshNum, random);
}
// resize population
template <typename P, typename T> void Genetic<P, T>::refresh_population(const std::vector<P> &newParamset, bool random)
{
pop.refresh(newParamset, random);
}
// run genetic algorithm
template <typename P, typename T> void Genetic<P, T>::perform_evolutionary_steps(int numEvolStep)
{
nbgen = numEvolStep;
// checking inputs validity
this->check();
// setting adaptation method to default if needed
if (!SoftConstraints.empty() && Adaptation == nullptr) {
Adaptation = DAC;
}
// initializing best result and previous best result
T bestResult = pop(0)->getTotal();
T prevBestResult = bestResult;
// outputting results
if (output)
print();
// starting population evolution
for (nogen = 1; nogen <= nbgen; ++nogen) {
// evolving population
pop.evolution();
// getting best current result
bestResult = pop(0)->getTotal();
// outputting results
if (output)
print();
// checking convergence
if (tolerance != 0.0) {
if (fabs(bestResult - prevBestResult) < fabs(tolerance)) {
break;
}
prevBestResult = bestResult;
}
}
if (output)
std::cout << std::endl;
}
#endif // header guard
| 13,816
|
C++
|
.h
| 361
| 35.916898
| 120
| 0.694592
|
metric-space-ai/metric
| 34
| 14
| 44
|
MPL-2.0
|
9/20/2024, 10:43:29 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| true
| false
|
1,531,671
|
dist_sampling.hpp
|
metric-space-ai_metric/metric/utils/genetic/dist_sampling.hpp
|
#ifndef _DIST_SAMPLING_HPP
#define _DIST_SAMPLING_HPP
#include <vector>
template <typename T> std::vector<T> linspace(T a, T b, int n);
// akima interpolation
/*
Ref. : Hiroshi Akima, Journal of the ACM, Vol. 17, No. 4, October 1970,
pages 589-602.
*/
template <typename T>
std::vector<T> akimaInterp1(std::vector<T> const &x, std::vector<T> const &y, std::vector<T> const &xi,
bool save_Mode = true);
template <typename T> std::vector<T> linspace(T a, T b, int n)
{
std::vector<T> array;
if (n > 1) {
T step = (b - a) / T(n - 1);
int count = 0;
while (count < n) {
array.push_back(a + count * step);
++count;
}
} else {
array.push_back(b);
}
return array;
}
template <typename T>
std::vector<T> akimaInterp1(std::vector<T> const &x, std::vector<T> const &y, std::vector<T> const &xi, bool save_Mode)
{
// check inputs
// calculate u vector
auto uVec = [](std::vector<T> const &x, std::vector<T> const &y) {
size_t n = x.size();
std::vector<T> u((n + 3));
for (size_t i = 1; i < n; ++i) {
u[i + 1] = (y[i] - y[i - 1]) / (x[i] - x[i - 1]); // Shift i to i+2
}
auto akima_end = [](const T &u1, const T &u2) { return 2.0 * u1 - u2; };
u[1] = akima_end(u[2], u[3]);
u[0] = akima_end(u[1], u[2]);
u[n + 1] = akima_end(u[n], u[n - 1]);
u[n + 2] = akima_end(u[n + 1], u[n]);
return u;
};
std::vector<T> u = uVec(x, y);
// calculate yp vector
std::vector<T> yp(x.size());
for (size_t i = 0; i < x.size(); ++i) {
auto a = std::abs(u[i + 3] - u[i + 2]);
auto b = std::abs(u[i + 1] - u[i]);
if ((a + b) != 0) {
yp[i] = (a * u[i + 1] + b * u[i + 2]) / (a + b);
} else {
yp[i] = (u[i + 2] + u[i + 1]) / 2.0;
}
}
// calculte interpolated yi values
auto kFind = [](const T &xii, const std::vector<T> &x, int start, int end) {
int klo = start;
int khi = end;
// // Find subinterval by bisection
while (khi - klo > 1) {
int k = (khi + klo) / 2;
x[k] > xii ? khi = k : klo = k;
}
return klo;
};
std::vector<T> yi(xi.size());
for (size_t i = 0; i < xi.size(); ++i) {
// Find the right place in the table by means of a bisection.
int k = kFind(xi[i], x, int(0), x.size() - 1);
// Evaluate Akima polynomial
T b = x[k + 1] - x[k];
T a = xi[i] - x[k];
yi[i] = y[k] + yp[k] * a + (3.0 * u[k + 2] - 2.0 * yp[k] - yp[k + 1]) * a * a / b +
(yp[k] + yp[k + 1] - 2.0 * u[k + 2]) * a * a * a / (b * b);
// Differentiate to find the second-order interpolant
// ypi[i] = yp[k] + (3.0u[k+2] - 2.0yp[k] - yp[k+1])2a/b + (yp[k] + yp[k+1] - 2.0u[k+2])3aa/(b*b);
// Differentiate to find the first-order interpolant
// yppi[i] = (3.0u[k+2] - 2.0yp[k] - yp[k+1])2/b + (yp[k] + yp[k+1] - 2.0u[k+2])6a/(b*b);
}
return yi;
}
#endif // header guard
| 2,748
|
C++
|
.h
| 85
| 29.670588
| 119
| 0.543257
|
metric-space-ai/metric
| 34
| 14
| 44
|
MPL-2.0
|
9/20/2024, 10:43:29 PM (Europe/Amsterdam)
| false
| false
| false
| false
| true
| false
| true
| false
|
1,531,672
|
Chromosome.hpp
|
metric-space-ai_metric/metric/utils/genetic/Chromosome.hpp
|
#ifndef _GENETIC_CHROMOSOME_HPP
#define _GENETIC_CHROMOSOME_HPP
namespace genetic_details {
template <typename P, typename T> class Chromosome {
static_assert(std::is_same<float, T>::value || std::is_same<double, T>::value,
"variable type can only be float or double, please amend.");
public:
// constructor
Chromosome(const Genetic<P, T> &ga);
// copy constructor
Chromosome(const Chromosome<P, T> &rhs);
// create new chromosome
void create();
// initialize chromosome
void initialize(P &initP);
// evaluate chromosome
void evaluate();
// reset chromosome
void reset();
// set or replace kth gene by a new one
void setGene(int k);
// initialize or replace kth gene by a know value
void initGene(int k, T value);
// add bit to chromosome
void addBit(char bit);
// initialize or replace an existing chromosome bit
void setBit(char bit, int pos);
// flip an existing chromosome bit
void flipBit(int pos);
// get chromosome bit
char getBit(int pos) const;
// initialize or replace a portion of bits with a portion of another chromosome
void setPortion(const Chromosome<P, T> &x, int start, int end);
// initialize or replace a portion of bits with a portion of another chromosome
void setPortion(const Chromosome<P, T> &x, int start);
// get parameter value(s) from chromosome
const P &getParam() const;
// get objective function result
const std::vector<T> &getResult() const;
// get the total sum of all objective function(s) result
T getTotal() const;
// get constraint value(s)
const bool getHardConstraint() const;
const std::vector<T> getSoftConstraint() const;
const std::vector<T> getConstraint() const;
// return chromosome size in number of bits
int size() const;
// return number of chromosome bits to mutate
T mutrate() const;
// return number of genes in chromosome
int nbgene() const;
// return numero of generation this chromosome belongs to
int nogen() const;
// return lower bound(s)
const P &lowerBound() const;
// return upper bound(s)
const P &upperBound() const;
private:
P param; // estimated parameter(s)
std::vector<T> result; // chromosome objective function(s) result
std::string chr; // string of bits representing chromosome
const Genetic<P, T> *ptr = nullptr; // pointer to genetic algorithm
// end of recursion for initializing parameter(s) data
template <int I, typename... Tp>
inline typename std::enable_if<I == sizeof...(Tp), void>::type decodeChr(std::tuple<Tp...> &tp);
// recursion for initializing parameter(s) data
template <int I, typename... Tp>
inline typename std::enable_if < I<sizeof...(Tp), void>::type decodeChr(std::tuple<Tp...> &tp);
template <int I, typename... Tp>
inline typename std::enable_if<I == sizeof...(Tp), void>::type encodeChr(std::tuple<Tp...> &tp);
// recursion for initializing parameter(s) data
template <int I, typename... Tp>
inline typename std::enable_if < I<sizeof...(Tp), void>::type encodeChr(std::tuple<Tp...> &tp);
public:
T fitness; // chromosome fitness, objective function(s) result that can be modified (adapted to constraint(s), set
// to positive values, etc...)
private:
T total; // total sum of objective function(s) result
int chrsize; // chromosome size (in number of bits)
int numgen; // numero of generation
};
// constructor
template <typename P, typename T> genetic_details::Chromosome<P, T>::Chromosome(const Genetic<P, T> &ga)
{
// param.resize(ga.nbparam);
ptr = &ga;
chrsize = ga.nbbit;
numgen = ga.nogen;
}
// copy constructor
template <typename P, typename T> genetic_details::Chromosome<P, T>::Chromosome(const Chromosome<P, T> &rhs)
{
param = rhs.param;
result = rhs.result;
chr = rhs.chr;
ptr = rhs.ptr;
// re-initializing fitness to its original value
fitness = rhs.total;
total = rhs.total;
chrsize = rhs.chrsize;
numgen = rhs.numgen;
}
// create new chromosome
template <typename P, typename T> inline void Chromosome<P, T>::create()
{
chr.clear();
for (const auto &x : ptr->param) {
// encoding parameter random value
std::string str = x->encode();
chr.append(str);
}
}
// end of recursion for initializing parameter(s) data
template <typename P, typename T>
template <int I, typename... Tp>
inline typename std::enable_if<I == sizeof...(Tp), void>::type Chromosome<P, T>::encodeChr(std::tuple<Tp...> &tp)
{
}
// recursion for initializing parameter(s) data
template <typename P, typename T>
template <int I, typename... Tp>
inline typename std::enable_if < I<sizeof...(Tp), void>::type Chromosome<P, T>::encodeChr(std::tuple<Tp...> &tp)
{
// copying parameter data
std::string str = ptr->param[I]->encode(std::get<I>(tp));
// recursing
chr.append(str);
encodeChr<I + 1>(tp);
}
// initialize chromosome (from known parameter values)
template <typename P, typename T> inline void Chromosome<P, T>::initialize(P &initP)
{
chr.clear();
encodeChr<0>(initP);
}
// end of recursion for initializing parameter(s) data
template <typename P, typename T>
template <int I, typename... Tp>
inline typename std::enable_if<I == sizeof...(Tp), void>::type Chromosome<P, T>::decodeChr(std::tuple<Tp...> &tp)
{
}
// recursion for initializing parameter(s) data
template <typename P, typename T>
template <int I, typename... Tp>
inline typename std::enable_if < I<sizeof...(Tp), void>::type Chromosome<P, T>::decodeChr(std::tuple<Tp...> &tp)
{
// copying parameter data
std::get<I>(tp) = ptr->param[I]->decode(chr.substr(ptr->idx[I], ptr->param[I]->size()));
// recursing
decodeChr<I + 1>(tp);
}
// evaluate chromosome fitness
template <typename P, typename T> inline void Chromosome<P, T>::evaluate()
{
decodeChr<0>(param);
// computing objective result(s)
result = ptr->Objective(param);
// computing sum of all results (in case there is not only one objective functions)
total = std::accumulate(result.begin(), result.end(), 0.0);
// initializing fitness to this total
fitness = total;
}
// reset chromosome
template <typename P, typename T> inline void Chromosome<P, T>::reset()
{
chr.clear();
result.clear();
total = 0.0;
fitness = 0.0;
}
// set or replace kth gene by a new one
template <typename P, typename T> inline void Chromosome<P, T>::setGene(int k)
{
#ifndef NDEBUG
if (k < 0 || k >= ptr->nbparam) {
throw std::invalid_argument("Error: in genetic_details::Chromosome< P,T>::setGene(int), argument cannot be "
"outside interval [0,nbparam-1], please amend.");
}
#endif
// generating a new gene
std::string s = ptr->param[k]->encode();
// adding or replacing gene in chromosome
chr.replace(ptr->idx[k], s.size(), s, 0, s.size());
}
// initialize or replace kth gene by a know value
template <typename P, typename T> inline void Chromosome<P, T>::initGene(int k, T x)
{
#ifndef NDEBUG
if (k < 0 || k >= ptr->nbparam) {
throw std::invalid_argument("Error: in genetic_details::Chromosome< P,T>::initGene(int), first argument cannot "
"be outside interval [0,nbparam-1], please amend.");
}
#endif
// encoding gene
std::string s = ptr->param[k]->encode(x);
// adding or replacing gene in chromosome
chr.replace(ptr->idx[k], s.size(), s, 0, s.size());
}
// add chromosome bit to chromosome (when constructing a new one)
template <typename P, typename T> inline void Chromosome<P, T>::addBit(char bit)
{
chr.push_back(bit);
#ifndef NDEBUG
if (chr.size() > chrsize) {
throw std::out_of_range(
"Error: in genetic_details::Chromosome< P,T>::setBit(char), exceeding chromosome size.");
}
#endif
}
// initialize or replace an existing chromosome bit
template <typename P, typename T> inline void Chromosome<P, T>::setBit(char bit, int pos)
{
#ifndef NDEBUG
if (pos >= chrsize) {
throw std::out_of_range("Error: in genetic_details::Chromosome< P,T>::replaceBit(char, int), second argument "
"cannot be equal or greater than chromosome size.");
}
#endif
std::stringstream ss;
std::string str;
ss << bit;
ss >> str;
chr.replace(pos, 1, str);
}
// flip an existing chromosome bit
template <typename P, typename T> inline void Chromosome<P, T>::flipBit(int pos)
{
#ifndef NDEBUG
if (pos >= chrsize) {
throw std::out_of_range("Error: in genetic_details::Chromosome< P,T>::flipBit(int), argument cannot be equal "
"or greater than chromosome size.");
}
#endif
if (chr[pos] == '0') {
chr.replace(pos, 1, "1");
} else {
chr.replace(pos, 1, "0");
}
}
// get a chromosome bit
template <typename P, typename T> inline char Chromosome<P, T>::getBit(int pos) const
{
#ifndef NDEBUG
if (pos >= chrsize) {
throw std::out_of_range("Error: in genetic_details::Chromosome< P,T>::getBit(int), argument cannot be equal or "
"greater than chromosome size.");
}
#endif
return chr[pos];
}
// initialize or replace a portion of bits with a portion of another chromosome (from position start to position end
// included)
template <typename P, typename T>
inline void Chromosome<P, T>::setPortion(const Chromosome<P, T> &x, int start, int end)
{
#ifndef NDEBUG
if (start > chrsize) {
throw std::out_of_range("Error: in genetic_details::Chromosome< P,T>::setPortion(const Chromosome< P,T>&, int, "
"int), second argument cannot be greater than chromosome size.");
}
#endif
chr.replace(start, end - start + 1, x.chr, start, end - start + 1);
}
// initialize or replace a portion of bits with a portion of another chromosome (from position start to the end of he
// chromosome)
template <typename P, typename T> inline void Chromosome<P, T>::setPortion(const Chromosome<P, T> &x, int start)
{
#ifndef NDEBUG
if (start > chrsize) {
throw std::out_of_range("Error: in genetic_details::Chromosome< P,T>::setPortion(const Chromosome< P,T>&, "
"int), second argument cannot be greater than chromosome size.");
}
#endif
chr.replace(start, chrsize, x.chr, start, x.chrsize);
}
// get parameter value(s) from chromosome
template <typename P, typename T> inline const P &Chromosome<P, T>::getParam() const { return param; }
// get objective function result
template <typename P, typename T> inline const std::vector<T> &Chromosome<P, T>::getResult() const { return result; }
// get the total sum of all objective function(s) result
template <typename P, typename T> inline T Chromosome<P, T>::getTotal() const { return total; }
// get constraint value(s) for this chromosome
template <typename P, typename T> const std::vector<T> Chromosome<P, T>::getConstraint() const
{
return ptr->Constraint(param);
}
// return chromosome size in number of bits
template <typename P, typename T> inline int Chromosome<P, T>::size() const { return chrsize; }
// return mutation rate
template <typename P, typename T> inline T Chromosome<P, T>::mutrate() const { return ptr->mutrate; }
// return number of genes in chromosome
template <typename P, typename T> inline int Chromosome<P, T>::nbgene() const { return ptr->nbparam; }
// return numero of generation this chromosome belongs to
template <typename P, typename T> inline int Chromosome<P, T>::nogen() const { return numgen; }
// return lower bound(s)
template <typename P, typename T> inline const P &Chromosome<P, T>::lowerBound() const { return ptr->lowerBound; }
// return upper bound(s)
template <typename P, typename T> inline const P &Chromosome<P, T>::upperBound() const { return ptr->upperBound; }
} // namespace genetic_details
#endif // header guard
| 11,376
|
C++
|
.h
| 300
| 35.866667
| 117
| 0.716786
|
metric-space-ai/metric
| 34
| 14
| 44
|
MPL-2.0
|
9/20/2024, 10:43:29 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| true
| false
|
1,531,673
|
Population.hpp
|
metric-space-ai_metric/metric/utils/genetic/Population.hpp
|
#ifndef _GENETIC_POPULATION_HPP
#define _GENETIC_POPULATION_HPP
#include <set>
namespace genetic_details {
template <typename P, typename T> class Population {
static_assert(std::is_same<float, T>::value || std::is_same<double, T>::value,
"variable type can only be float or double, please amend.");
public:
// nullary constructor
Population() {}
// constructor
Population(const Genetic<P, T> &ga);
// create a population of chromosomes
void creation();
// evolve population, get next generation
void evolution();
// access element in current population at position pos
const CHR<P, T> &operator()(int pos) const;
// access element in mating population at position pos
const CHR<P, T> &operator[](int pos) const;
// return iterator to current population beginning
typename std::vector<CHR<P, T>>::iterator begin();
// return const iterator to current population beginning
typename std::vector<CHR<P, T>>::const_iterator cbegin() const;
// return iterator to current population ending
typename std::vector<CHR<P, T>>::iterator end();
// return const iterator to current population ending
typename std::vector<CHR<P, T>>::const_iterator cend() const;
// select element at position pos in current population and copy it into mating population
void select(int pos);
// set all fitness to positive values
void adjustFitness();
// compute fitness sum of current population
T getSumFitness() const;
// get worst objective function total result from current population
T getWorstTotal() const;
// return population size
int popsize() const;
// return mating population size
int matsize() const;
// return tournament size
int tournament_selectionsize() const;
// return numero of generation
int nogen() const;
// return number of generations
int nbgen() const;
// return selection pressure
T SP() const;
void refresh(int n, bool random = true);
void refresh(const std::vector<P> &, bool random = true);
void addParam(int chrId, const std::string &ss);
private:
std::vector<CHR<P, T>> curpop; // current population
std::vector<CHR<P, T>> matpop; // mating population
std::vector<CHR<P, T>> newpop; // new population
const Genetic<P, T> *ptr = nullptr; // pointer to genetic algorithm
int nbrcrov; // number of cross-over
int matidx; // mating population index
// elitism => saving best chromosomes in new population
void elitism();
// create new population from recombination of the old one
void recombination();
// complete new population randomly
void completion();
// update population (adapting, sorting)
void updating();
};
// constructor
template <typename P, typename T> Population<P, T>::Population(const Genetic<P, T> &ga)
{
ptr = &ga;
nbrcrov = floor(ga.covrate * (ga.popsize - ga.elitpop));
// adjusting nbrcrov (must be an even number)
if (nbrcrov % 2 != 0)
nbrcrov -= 1;
// for convenience, we add elitpop to nbrcrov
nbrcrov += ga.elitpop;
// allocating memory
curpop.resize(ga.popsize);
matpop.resize(ga.matsize);
}
// create a population of chromosomes
template <typename P, typename T> void Population<P, T>::refresh(int n, bool random)
{
if (n >= popsize()) {
for (auto curch : curpop) {
curch->reset();
curch->create();
// curch->evaluate();
}
} else if (random) {
std::set<int> randset;
while (randset.size() < n)
randset.insert(rand() % (popsize() - 1) + 0);
for (auto i : randset) {
curpop[i]->reset();
curpop[i]->create();
// curpop[i]->evaluate();
}
} else {
this->updating();
for (auto i = popsize() - n - 1; i < popsize(); i++) {
curpop[i]->reset();
curpop[i]->create();
// curpop[i]->evaluate();
}
}
}
// create a population of chromosomes
template <typename P, typename T> void Population<P, T>::refresh(const std::vector<P> &newparamset, bool random)
{
int n = newparamset.size();
if (n >= popsize()) {
for (auto i = 0; i < popsize(); i++) {
P np = newparamset[i];
curpop[i]->reset();
curpop[i]->initialize(np);
// curpop[i]->evaluate();
}
} else if (random) {
std::set<int> randset;
while (randset.size() < n)
randset.insert(rand() % (popsize() - 1) + 0);
std::set<int>::iterator it = randset.begin();
for (auto i = 0; i < n; i++) {
int pos = (*it);
P np = newparamset[i];
curpop[pos]->reset();
curpop[pos]->initialize(np);
// curpop[pos]->evaluate();
it++;
}
} else {
this->updating();
for (auto i = popsize() - n - 1; i < popsize(); i++) {
curpop[i]->reset();
P np = newparamset[i];
curpop[i]->initialize(np);
// curpop[i]->evaluate();
}
}
}
// create a population of chromosomes
template <typename P, typename T> void Population<P, T>::creation()
{
int start = 0;
// initializing first chromosome
if (!ptr->initialSet.empty()) {
curpop[0] = std::make_shared<Chromosome<P, T>>(*ptr);
P initP = ptr->initialSet[start];
curpop[0]->initialize(initP);
curpop[0]->evaluate();
start++;
}
// getting the rest
for (int i = start; i < ptr->popsize; ++i) {
curpop[i] = std::make_shared<Chromosome<P, T>>(*ptr);
curpop[i]->create();
curpop[i]->evaluate();
}
// updating population
this->updating();
}
// population evolution (selection, recombination, completion, mutation), get next generation
template <typename P, typename T> void Population<P, T>::evolution()
{
// initializing mating population index
matidx = 0;
// selecting mating population
ptr->Selection(*this);
// applying elitism if required
this->elitism();
// crossing-over mating population
this->recombination();
// completing new population
this->completion();
// moving new population into current population for next generation
curpop = std::move(newpop);
// updating population
this->updating();
}
// elitism => saving best chromosomes in new population, making a copy of each elit chromosome
template <typename P, typename T> void Population<P, T>::elitism()
{
// (re)allocating new population
newpop.resize(ptr->popsize);
if (ptr->elitpop > 0) {
// copying elit chromosomes into new population
std::transform(curpop.cbegin(), curpop.cend(), newpop.begin(),
[](const CHR<P, T> &chr) -> CHR<P, T> { return std::make_shared<Chromosome<P, T>>(*chr); });
}
}
// create new population from recombination of the old one
template <typename P, typename T> void Population<P, T>::recombination()
{
// creating a new population by cross-over
for (int i = ptr->elitpop; i < nbrcrov; i = i + 2) {
// initializing 2 new chromosome
newpop[i] = std::make_shared<Chromosome<P, T>>(*ptr);
newpop[i + 1] = std::make_shared<Chromosome<P, T>>(*ptr);
// crossing-over mating population to create 2 new chromosomes
ptr->CrossOver(*this, newpop[i], newpop[i + 1]);
// mutating new chromosomes
ptr->Mutation(newpop[i]);
ptr->Mutation(newpop[i + 1]);
// evaluating new chromosomes
newpop[i]->evaluate();
newpop[i + 1]->evaluate();
}
}
// complete new population
template <typename P, typename T> void Population<P, T>::completion()
{
for (int i = nbrcrov; i < ptr->popsize; ++i) {
// selecting chromosome randomly from mating population
newpop[i] = std::make_shared<Chromosome<P, T>>(*matpop[uniform<int>(0, ptr->matsize)]);
// mutating chromosome
ptr->Mutation(newpop[i]);
// evaluating chromosome
newpop[i]->evaluate();
}
}
// update population (adapting, sorting)
template <typename P, typename T> void Population<P, T>::updating()
{
// adapting population to constraints
if (!ptr->SoftConstraints.empty()) {
ptr->Adaptation(*this);
}
for (auto x : curpop) {
x->evaluate();
}
// sorting chromosomes from best to worst fitness
std::sort(curpop.begin(), curpop.end(),
[](const CHR<P, T> &chr1, const CHR<P, T> &chr2) -> bool { return chr1->fitness > chr2->fitness; });
}
// access element in current population at position pos
template <typename P, typename T> const CHR<P, T> &Population<P, T>::operator()(int pos) const
{
#ifndef NDEBUG
if (pos > ptr->popsize - 1) {
throw std::invalid_argument(
"Error: in genetic_details::Population<P,T>::operator()(int), exceeding current population memory.");
}
#endif
return curpop[pos];
}
// access element in mating population at position pos
template <typename P, typename T> const CHR<P, T> &Population<P, T>::operator[](int pos) const
{
#ifndef NDEBUG
if (pos > ptr->matsize - 1) {
throw std::invalid_argument(
"Error: in genetic_details::Population<P,T>::operator[](int), exceeding mating population memory.");
}
#endif
return matpop[pos];
}
// return iterator to current population beginning
template <typename P, typename T> inline typename std::vector<CHR<P, T>>::iterator Population<P, T>::begin()
{
return curpop.begin();
}
// return const iterator to current population beginning
template <typename P, typename T>
inline typename std::vector<CHR<P, T>>::const_iterator Population<P, T>::cbegin() const
{
return curpop.cbegin();
}
// return iterator to current population ending
template <typename P, typename T> inline typename std::vector<CHR<P, T>>::iterator Population<P, T>::end()
{
return curpop.end();
}
// return const iterator to current population ending
template <typename P, typename T> inline typename std::vector<CHR<P, T>>::const_iterator Population<P, T>::cend() const
{
return curpop.cend();
}
// select element at position pos in current population and copy it into mating population
template <typename P, typename T> inline void Population<P, T>::select(int pos)
{
#ifndef NDEBUG
if (pos > ptr->popsize - 1) {
throw std::invalid_argument(
"Error: in genetic_details::Population<P,T>::select(int), exceeding current population memory.");
}
if (matidx == ptr->matsize) {
throw std::invalid_argument(
"Error: in genetic_details::Population<P,T>::select(int), exceeding mating population memory.");
}
#endif
matpop[matidx] = curpop[pos];
matidx++;
}
// set all fitness to positive values (used in proportional_roulette_wheel_selection and
// stochastic_universal_sampling_selection selection methods)
template <typename P, typename T> void Population<P, T>::adjustFitness()
{
// this->updating();
// getting worst population fitness
auto itWorstFitness =
std::min_element(curpop.begin(), curpop.end(), [](const CHR<P, T> &chr1, const CHR<P, T> &chr2) -> bool {
return chr1->fitness < chr2->fitness;
});
T worstFitness = (*itWorstFitness)->fitness;
if (worstFitness < 0) {
// getting best fitness
auto itBestFitness =
std::max_element(curpop.begin(), curpop.end(), [](const CHR<P, T> &chr1, const CHR<P, T> &chr2) -> bool {
return chr1->fitness < chr2->fitness;
});
T bestFitness = (*itBestFitness)->fitness;
// case where all fitness are equal and negative
if (worstFitness == bestFitness) {
std::for_each(curpop.begin(), curpop.end(), [](CHR<P, T> &chr) -> void { chr->fitness *= -1; });
} else {
std::for_each(curpop.begin(), curpop.end(),
[worstFitness](CHR<P, T> &chr) -> void { chr->fitness -= worstFitness; });
}
}
}
// compute population fitness sum (used in transform_ranking_selection, proportional_roulette_wheel_selection and
// stochastic_universal_sampling_selection selection methods)
template <typename P, typename T> inline T Population<P, T>::getSumFitness() const
{
return std::accumulate(curpop.cbegin(), curpop.cend(), 0.0,
[](T sum, const CHR<P, T> &chr) -> T { return sum + T(chr->fitness); });
}
// get worst objective function total result from current population (used in constraint(s) adaptation)
template <typename P, typename T> inline T Population<P, T>::getWorstTotal() const
{
auto it = std::min_element(curpop.begin(), curpop.end(), [](const CHR<P, T> &chr1, const CHR<P, T> &chr2) -> bool {
return chr1->getTotal() < chr2->getTotal();
});
return (*it)->getTotal();
}
// return population size
template <typename P, typename T> inline int Population<P, T>::popsize() const { return ptr->popsize; }
// return mating population size
template <typename P, typename T> inline int Population<P, T>::matsize() const { return ptr->matsize; }
// return tournament size
template <typename P, typename T> inline int Population<P, T>::tournament_selectionsize() const
{
return ptr->tournament_selectionsize;
}
// return numero of generation
template <typename P, typename T> inline int Population<P, T>::nogen() const { return ptr->nogen; }
// return number of generations
template <typename P, typename T> inline int Population<P, T>::nbgen() const { return ptr->nbgen; }
// return selection pressure
template <typename P, typename T> inline T Population<P, T>::SP() const { return ptr->SP; }
// return selection pressure
template <typename P, typename T> void Population<P, T>::addParam(int chrId, const std::string &ss)
{
curpop[chrId]->append(ss);
}
} // namespace genetic_details
#endif // header guard
| 12,830
|
C++
|
.h
| 359
| 33.442897
| 119
| 0.703889
|
metric-space-ai/metric
| 34
| 14
| 44
|
MPL-2.0
|
9/20/2024, 10:43:29 PM (Europe/Amsterdam)
| false
| false
| false
| false
| true
| false
| true
| false
|
1,531,674
|
Parameter.hpp
|
metric-space-ai_metric/metric/utils/genetic/Parameter.hpp
|
#ifndef _GENETIC_PARAMETER_HPP
#define _GENETIC_PARAMETER_HPP
#include <random>
#include <sstream>
namespace genetic_details {
// template metaprogramming for getting maximum unsigned integral value from N bits
template <unsigned int N> struct MAXVALUE {
enum : uint64_t { value = 2 * MAXVALUE<N - 1>::value };
};
// template specialization for initial case N = 0
template <> struct MAXVALUE<0> {
enum { value = 1 };
};
// // Mersenne Twister 19937 pseudo-random number generator
std::random_device rand_dev;
std::mt19937_64 rng(rand_dev());
// static class for generating random unsigned integral numbers
template <int N> class Randomize {
static_assert(N > 0 && N <= 64, "in class genetic_details::Randomize<N>, template parameter N cannot be ouside "
"interval [1,64], please choose an integer within this interval.");
public:
// computation only done once for each different N
static constexpr uint64_t MAXVAL = MAXVALUE<N>::value - 1;
// generating random unsigned long long integer on [0,MAXVAL]
static uint64_t generate()
{
// class constructor only called once for each different N
static std::uniform_int_distribution<uint64_t> udistrib(0, MAXVAL);
return udistrib(rng);
}
};
// convert unsigned long long integer to binary string
std::string GetBinary(uint64_t value)
{
std::bitset<sizeof(uint64_t) * CHAR_BIT> bits(value);
// NB: CHAR_BIT = number of bits in char usually 8 but not always on older machines
return bits.to_string();
}
// convert binary string to unsigned long long integer
uint64_t GetValue(const std::string &s)
{
uint64_t value, x = 0;
for (std::string::const_iterator it = s.begin(), end = s.end(); it != end; ++it) {
x = (x << 1) + (*it - '0');
}
memcpy(&value, &x, sizeof(uint64_t));
return value;
}
template <typename T, int N> class Parameter {
static_assert(std::is_same<float, T>::value || std::is_same<double, T>::value || std::is_same<int, T>::value,
"variable type can only be float, double or int, please amend.");
template <typename H, typename K> friend class Chromosome;
private:
T lb;
T ub;
public:
// nullary constructor
Parameter() {}
~Parameter() {}
// return encoded parameter size in number of bits
int size() const { return N; }
void boundaries(const T &nlb, const T &nub)
{
lb = nlb;
ub = nub;
}
const std::vector<T> &getData() const { return std::vector<T>({lb, ub}); }
private:
// encoding random unsigned integer
std::string encode() const
{
std::string str = GetBinary(Randomize<N>::generate());
return str.substr(str.size() - N, N);
}
// encoding known unsigned integer
std::string encode(T z) const
{
if (z > ub || z < lb) {
throw std::invalid_argument("Error: in class genetic_details::Parameter<P,T,N>, encode parameter out of "
"bound. Please reset parameter set.");
}
uint64_t value = Randomize<N>::MAXVAL * (z - lb) / (ub - lb);
std::string str = GetBinary(value);
return str.substr(str.size() - N, N);
}
// decoding string to real value
T decode(const std::string &str) const
{
return lb + (GetValue(str) / static_cast<double>(Randomize<N>::MAXVAL)) * (ub - lb);
}
};
} // namespace genetic_details
#endif // header guard
| 3,211
|
C++
|
.h
| 93
| 32.172043
| 113
| 0.701743
|
metric-space-ai/metric
| 34
| 14
| 44
|
MPL-2.0
|
9/20/2024, 10:43:29 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| true
| false
|
1,531,675
|
evolution_methods.hpp
|
metric-space-ai_metric/metric/utils/genetic/evolution_methods.hpp
|
#ifndef _GENETIC_EVOLUTION_METHODS_HPP
#define _GENETIC_EVOLUTION_METHODS_HPP
#include <random>
/*
a library for selection, cross-over, mutation methods for the Poopulution class
*/
std::random_device rand_dev;
std::mt19937_64 rng(rand_dev());
std::uniform_real_distribution<> proba(0, 1);
template <typename T> inline T uniform(T min, T max)
{
#ifndef NDEBUG
if (min >= max) {
throw std::invalid_argument("Error: in uniform(T, T), first argument must be < to second argument.");
}
#endif
return min + proba(rng) * (max - min);
}
/*
__| __| | __| __| __ __| _ _| _ \ \ | \ | __| __ __| | | _ \ _ \ __|
\__ \ _| | _| ( | | ( | . | |\/ | _| | __ | ( | | | \__ \
____/ ___| ____| ___| \___| _| ___| \___/ _|\_| _| _| ___| _| _| _| \___/ ___/ ____/
*/
// proportional roulette wheel selection
// https://en.wikipedia.org/wiki/Fitness_proportionate_selection
template <typename P, typename T> void proportional_roulette_wheel_selection(genetic_details::Population<P, T> &x)
{
// adjusting all fitness to positive values
x.adjustFitness();
// computing fitness sum
T fitsum = x.getSumFitness();
// selecting mating population
for (int i = 0, end = x.matsize(); i < end; ++i) {
// generating a random fitness sum in [0,fitsum)
T fsum = uniform<T>(0.0, fitsum);
int j = 0;
while (fsum >= 0.0) {
#ifndef NDEBUG
if (j == x.popsize()) {
throw std::invalid_argument(
"Error: in proportional_roulette_wheel_selection(genetic_details::Population<P,T>&) index j cannot "
"be equal to population size.");
}
#endif
fsum -= x(j)->fitness;
j++;
}
// selecting element
x.select(j - 1);
}
}
// stochastic universal sampling selection
// https://en.wikipedia.org/wiki/Stochastic_universal_sampling
template <typename P, typename T> void stochastic_universal_sampling_selection(genetic_details::Population<P, T> &x)
{
// adjusting all fitness to positive values
x.adjustFitness();
// computing fitness sum
T fitsum = x.getSumFitness();
int matsize = x.matsize();
// computing interval size
T dist = fitsum / matsize;
// initializing pointer
T ptr = uniform<T>(0.0, dist);
// selecting mating population
for (int i = 0; i < matsize; ++i) {
int j = 0;
T fsum = 0;
while (fsum <= ptr) {
#ifndef NDEBUG
if (j == x.popsize()) {
throw std::invalid_argument(
"Error: in stochastic_universal_sampling_selection(genetic_details::Population<P,T>&) index j "
"cannot be equal to population size.");
}
#endif
fsum += x(j)->fitness;
j++;
}
// selecting element
x.select(j - 1);
// incrementing pointer
ptr += dist;
}
}
// classic linear rank-based selection
template <typename P, typename T> void linear_rank_based_selection(genetic_details::Population<P, T> &x)
{
int popsize = x.popsize();
static std::vector<int> rank(popsize);
static int ranksum;
// this will only be run at the first generation
if (x.nogen() == 1) {
int n = popsize + 1;
// generating ranks from highest to lowest
std::generate_n(rank.begin(), popsize, [&n]() -> int { return --n; });
// computing sum of ranks
ranksum = .5 * popsize * (popsize + 1);
}
// selecting mating population
for (int i = 0, end = x.matsize(); i < end; ++i) {
// generating a random rank sum in [1,ranksum)
int rsum = uniform<int>(1, ranksum);
int j = 0;
while (rsum > 0) {
#ifndef NDEBUG
if (j == popsize) {
throw std::invalid_argument("Error: in linear_rank_based_selection(genetic_details::Population<P,T>&) "
"index j cannot be equal to population size.");
}
#endif
rsum -= rank[j];
j++;
}
// selecting element
x.select(j - 1);
}
}
// linear rank-based selection with selective pressure
template <typename P, typename T>
void linear_rank_based_with_selective_pressure_selection(genetic_details::Population<P, T> &x)
{
int popsize = x.popsize();
static std::vector<T> rank(popsize);
static T ranksum;
// this will only be run at the first generation
if (x.nogen() == 1) {
// initializing ranksum
ranksum = 0.0;
// generating ranks from highest to lowest
for (int i = 0; i < popsize; ++i) {
rank[i] = 2 - x.SP() + 2 * (x.SP() - 1) * (popsize - i) / popsize;
ranksum += rank[i];
}
}
// selecting mating population
for (int i = 0, end = x.matsize(); i < end; ++i) {
// generating a random rank sum in [0,ranksum)
T rsum = uniform<T>(0.0, ranksum);
int j = 0;
while (rsum >= 0.0) {
#ifndef NDEBUG
if (j == popsize) {
throw std::invalid_argument(
"Error: in linear_rank_based_with_selective_pressure_selection(genetic_details::Population<P,T>&) "
"index j cannot be equal to population size.");
}
#endif
rsum -= rank[j];
j++;
}
// selecting element
x.select(j - 1);
}
}
// tournament selection
// https://en.wikipedia.org/wiki/Tournament_selection
template <typename P, typename T> void tournament_selection(genetic_details::Population<P, T> &x)
{
int popsize = x.popsize();
int tournament_selectionsize = x.tournament_selectionsize();
// selecting mating population
for (int i = 0, end = x.matsize(); i < end; ++i) {
// selecting randomly a first element
int bestIdx = uniform<int>(0, popsize);
T bestFit = x(bestIdx)->fitness;
// starting tournament
for (int j = 1; j < tournament_selectionsize; ++j) {
int idx = uniform<int>(0, popsize);
T fit = x(idx)->fitness;
if (fit > bestFit) {
bestFit = fit;
bestIdx = idx;
}
}
// selecting element
x.select(bestIdx);
}
}
// transform ranking selection
template <typename P, typename T> void transform_ranking_selection(genetic_details::Population<P, T> &x)
{
static T c;
// (re)initializing when running new GA
if (x.nogen() == 1) {
c = 0.2;
}
int popsize = x.popsize();
// generating a random set of popsize values on [0,1)
std::vector<T> r(popsize);
std::for_each(r.begin(), r.end(), [](T &z) -> T { z = proba(rng); });
// sorting them from highest to lowest
std::sort(r.begin(), r.end(), [](T z1, T z2) -> bool { return z1 > z2; });
// transforming population fitness
auto it = x.begin();
std::for_each(r.begin(), r.end(), [&it, popsize](T z) -> void {
(*it)->fitness = ceil((popsize - popsize * exp(-c * z)) / (1 - exp(-c)));
it++;
});
// updating c for next generation
c = c + 0.1; // arithmetic transition
// c = c * 1.1; // geometric transition
// computing fitness sum
int fitsum = x.getSumFitness();
// selecting mating population
for (int i = 0, end = x.matsize(); i < end; ++i) {
// generating a random fitness sum in [0,fitsum)
T fsum = uniform<int>(0, fitsum);
int j = 0;
while (fsum >= 0) {
#ifndef NDEBUG
if (j == popsize) {
throw std::invalid_argument("Error: in transform_ranking_selection(genetic_details::Population<P,T>&) "
"index j cannot be equal to population size.");
}
#endif
fsum -= x(j)->fitness;
j++;
}
// selecting element
x.select(j - 1);
}
}
/*
| | |
_| _| _ \ (_-< (_-< ____| _ \ \ \ / -_) _| ` \ -_) _| \ _ \ _` | (_-<
\__| _| \___/ ___/ ___/ \___/ \_/ \___| _| _|_|_| \___| \__| _| _| \___/ \__,_| ___/
*/
// one-point random cross-over of 2 chromosomes
template <typename P, typename T>
void one_point_random_crossover(const genetic_details::Population<P, T> &x, genetic_details::CHR<P, T> &chr1,
genetic_details::CHR<P, T> &chr2)
{
// choosing randomly 2 chromosomes from mating population
int idx1 = uniform<int>(0, x.matsize());
int idx2 = uniform<int>(0, x.matsize());
// choosing randomly a position for cross-over
int pos = uniform<int>(0, chr1->size());
// transmitting portion of bits to new chromosomes
chr1->setPortion(*x[idx1], 0, pos);
chr2->setPortion(*x[idx2], 0, pos);
chr1->setPortion(*x[idx2], pos + 1);
chr2->setPortion(*x[idx1], pos + 1);
}
// two-point random cross-over of 2 chromosomes
template <typename P, typename T, int... N>
void two_point_random_crossover(const genetic_details::Population<P, T> &x, genetic_details::CHR<P, T> &chr1,
genetic_details::CHR<P, T> &chr2)
{
// choosing randomly 2 chromosomes from mating population
int idx1 = uniform<int>(0, x.matsize());
int idx2 = uniform<int>(0, x.matsize());
// choosing randomly 2 positions for cross-over
int pos1 = uniform<int>(0, chr1->size());
int pos2 = uniform<int>(0, chr1->size());
// ordering these 2 random positions
int m = std::min(pos1, pos2);
int M = std::max(pos1, pos2);
// transmitting portion of bits new chromosomes
chr1->setPortion(*x[idx1], 0, m);
chr2->setPortion(*x[idx2], 0, m);
chr1->setPortion(*x[idx2], m + 1, M);
chr2->setPortion(*x[idx1], m + 1, M);
chr1->setPortion(*x[idx1], M + 1);
chr2->setPortion(*x[idx2], M + 1);
}
// uniform random cross-over of 2 chromosomes
template <typename P, typename T>
void uniform_random_crossover(const genetic_details::Population<P, T> &x, genetic_details::CHR<P, T> &chr1,
genetic_details::CHR<P, T> &chr2)
{
// choosing randomly 2 chromosomes from mating population
int idx1 = uniform<int>(0, x.matsize());
int idx2 = uniform<int>(0, x.matsize());
for (int j = 0; j < chr1->size(); ++j) {
// choosing 1 of the 2 chromosomes randomly
if (proba(rng) < 0.50) {
// adding its jth bit to new chromosome
chr1->addBit(x[idx1]->getBit(j));
chr2->addBit(x[idx2]->getBit(j));
} else {
// adding its jth bit to new chromosomes
chr1->addBit(x[idx2]->getBit(j));
chr2->addBit(x[idx1]->getBit(j));
}
}
}
/*
\ | | | __ __| \ __ __| _ _| _ \ \ | \ | __| __ __| | | _ \ _ \ __|
|\/ | | | | _ \ | | ( | . | |\/ | _| | __ | ( | | | \__ \
_| _| \__/ _| _/ _\ _| ___| \___/ _|\_| _| _| ___| _| _| _| \___/ ___/ ____/
*/
// boundary mutation: replacing a chromosome gene by its lower or upper bound
template <typename P, typename T> void boundary_mutation(genetic_details::CHR<P, T> &chr)
{
T mutrate = chr->mutrate();
if (mutrate == 0.0)
return;
// getting chromosome lower bound(s)
const std::vector<T> &lowerBound = chr->lowerBound();
// getting chromosome upper bound(s)
const std::vector<T> &upperBound = chr->upperBound();
// looping on number of genes
for (int i = 0; i < chr->nbgene(); ++i) {
// generating a random probability
if (proba(rng) <= mutrate) {
// generating a random probability
if (proba(rng) < .5) {
// replacing ith gene by lower bound
chr->initGene(i, lowerBound[i]);
} else {
// replacing ith gene by upper bound
chr->initGene(i, upperBound[i]);
}
}
}
}
// single point mutation: flipping a chromosome bit
template <typename P, typename T> void single_point_mutation(genetic_details::CHR<P, T> &chr)
{
T mutrate = chr->mutrate();
if (mutrate == 0.0)
return;
// looping on chromosome bits
for (int i = 0; i < chr->size(); ++i) {
// generating a random probability
if (proba(rng) <= mutrate) {
// flipping ith bit
chr->flipBit(i);
}
}
}
// uniform mutation: replacing a chromosome gene by a new one
template <typename P, typename T> void uniform_mutation(genetic_details::CHR<P, T> &chr)
{
T mutrate = chr->mutrate();
if (mutrate == 0.0)
return;
// looping on number of genes
for (int i = 0; i < chr->nbgene(); ++i) {
// generating a random probability
if (proba(rng) <= mutrate) {
// replacing ith gene by a new one
chr->setGene(i);
}
}
}
/*
\ _ \ \ _ \ __ __| \ __ __| _ _| _ \ \ | __ __| _ \ __| _ \ \ | __| __ __| _ \ \ _
_| \ | __ __| / __| \ \ \ | __| __ __| | | _ \ _ \ __|
_ \ | | _ \ __/ | _ \ | | ( | . | | ( | ( ( | . | \__ \ | / _ \ |
. | | | \__ \ | |\/ | _| | __ | ( | | | \__ \
_/ _\ ___/ _/ _\ _| _| _/ _\ _| ___| \___/ _|\_| _| \___/ \___| \___/ _|\_| ____/ _| _|_\ _/ _\ ___|
_|\_| _| | ____/ | _| _| ___| _| _| _| \___/ ___/ ____/
\_\ _/
*/
// adapt population to genetic algorithm constraint(s)
template <typename P, typename T> void DAC(genetic_details::Population<P, T> &x)
{
// getting worst population objective function total result
T worstTotal = x.getWorstTotal();
for (auto it = x.begin(), end = x.end(); it != end; ++it) {
// computing element constraint value(s)
const std::vector<T> &cst = (*it)->getConstraint();
// adapting fitness if any constraint violated
if (std::any_of(cst.cbegin(), cst.cend(), [](T x) -> bool { return x >= 0.0; })) {
auto val = std::accumulate(cst.cbegin(), cst.cend(), 0.0);
(*it)->fitness = worstTotal - val;
}
}
}
#endif // headerguard
| 12,740
|
C++
|
.h
| 372
| 31.486559
| 120
| 0.594803
|
metric-space-ai/metric
| 34
| 14
| 44
|
MPL-2.0
|
9/20/2024, 10:43:29 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| true
| false
|
1,531,676
|
math_functions.hpp
|
metric-space-ai_metric/metric/utils/poor_mans_quantum/math_functions.hpp
|
/*
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/.
Copyright (c) 2019 Michael Welsch
*/
#ifndef _METRIC_UTILS_POOR_MANS_QUANTUM_MATH_FUNCTIONS_HPP
#define _METRIC_UTILS_POOR_MANS_QUANTUM_MATH_FUNCTIONS_HPP
#include <vector>
namespace metric {
/**
* @brief
*
* @param a
* @param b
* @param n
* @return
*/
template <typename T> std::vector<T> linspace(T a, T b, int n);
/**
* @brief akima interpolation
*
* @details Ref. : Hiroshi Akima, Journal of the ACM, Vol. 17, No. 4, October 1970, pages 589-602.
* @param x
* @param y
* @param xi
* @param save_Mode
* @return
*/
template <typename T>
std::vector<T> akimaInterp1(std::vector<T> const &x, std::vector<T> const &y, std::vector<T> const &xi,
bool save_Mode = true);
/**
* @brief
*
* @param y
* @param n
* @return
*/
template <typename T> std::vector<T> resize(std::vector<T> y, size_t n);
/**
* @brief Transpose matrix
*
* @param a input matrix
* @return result of transposition of matrix a
*/
template <typename T> std::vector<std::vector<T>> transpose(std::vector<std::vector<T>> &a);
/**
* @brief
*
* @param data
* @param probs
* @return
*/
template <typename T> T quickQuantil(std::vector<T> data, T probs);
} // namespace metric
#include "math_functions.cpp"
#endif // header guard
| 1,444
|
C++
|
.h
| 58
| 22.87931
| 103
| 0.687273
|
metric-space-ai/metric
| 34
| 14
| 44
|
MPL-2.0
|
9/20/2024, 10:43:29 PM (Europe/Amsterdam)
| false
| false
| false
| false
| true
| false
| true
| false
|
1,531,677
|
Normal.hpp
|
metric-space-ai_metric/metric/utils/poor_mans_quantum/distributions/Normal.hpp
|
/*
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/.
Copyright (c) 2019 Panda Team
*/
#ifndef _METRIC_UTILS_POOR_MANS_QUANTUM_DISTRIBUTIONS_NORMAL_HPP
#define _METRIC_UTILS_POOR_MANS_QUANTUM_DISTRIBUTIONS_NORMAL_HPP
#include <random>
#include <vector>
namespace metric {
/**
* @class Normal
* @brief class represent Normal distribution
*
*/
class Normal {
public:
/**
* @brief Construct a new Normal object
*
*/
Normal();
/*** sample a random value ***/
/**
* @brief sample a random value
*
* @return random value according to Normal distribution
*/
float rnd();
/**
* @brief
*
* @return
*/
float median();
/**
* @brief quantil function
*
* @param p
* @return value of the random variable such that the probability of the variable being less than or equal to that
* value equals the given probability.
*/
float quantil(float p);
/**
* @brief long-run average value of repetitions of the same experiment
*
* @return return the expected value of distribution
*/
float mean();
/**
* @brief expectation of the squared deviation of a random variable from its mean
*
* @return variance value of the Normal distribution
*/
float variance();
/**
* @brief probability density function
*
* @param x
* @return
*/
float pdf(const float x);
/**
* @brief cumulative distribution function
*
* @param x
* @return
*/
float cdf(const float x);
/**
* @brief inverse cumulative distribution function
*
* @param x
* @return
*/
float icdf(const float x);
float _p1;
float _p2;
std::vector<float> _data;
std::vector<float> _prob;
private:
std::mt19937_64 _generator;
};
} // end namespace metric
#include "Normal.cpp"
#endif // header guard
| 1,900
|
C++
|
.h
| 87
| 19.264368
| 115
| 0.699889
|
metric-space-ai/metric
| 34
| 14
| 44
|
MPL-2.0
|
9/20/2024, 10:43:29 PM (Europe/Amsterdam)
| false
| false
| false
| false
| true
| false
| true
| false
|
1,531,678
|
Binomial.hpp
|
metric-space-ai_metric/metric/utils/poor_mans_quantum/distributions/Binomial.hpp
|
/*
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/.
Copyright (c) 2019 Michael Welsch
*/
#ifndef _METRIC_UTILS_POOR_MANS_QUANTUM_DISTRIBUTIONS_BINOMIAL_HPP
#define _METRIC_UTILS_POOR_MANS_QUANTUM_DISTRIBUTIONS_BINOMIAL_HPP
#include <random>
#include <vector>
namespace metric {
/**
* @class Binomial
*
* @brief Class represents binomial distribution
*/
class Binomial {
public:
/**
* @brief Construct a new Binomial object
*
*/
Binomial();
/**
* @brief sample a random value
*
* @return random value according to Normal distribution
*/
float rnd();
/**
* @brief cumulative distribution function
*
* @param x
* @return
*/
float cdf(const int x);
// float icdf(const float x);
// float mean();
// float quantil(float p);
// float pdf(const float x);
float _p1;
float _p2;
std::vector<float> _data;
std::vector<float> _prob;
private:
std::mt19937_64 _generator;
};
} // namespace metric
#include "Binomial.cpp"
#endif // header guard
| 1,139
|
C++
|
.h
| 50
| 20.5
| 69
| 0.713889
|
metric-space-ai/metric
| 34
| 14
| 44
|
MPL-2.0
|
9/20/2024, 10:43:29 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| true
| false
|
1,531,679
|
Weibull.hpp
|
metric-space-ai_metric/metric/utils/poor_mans_quantum/distributions/Weibull.hpp
|
/*
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/.
Copyright (c) 2019 Panda Team
*/
#ifndef _METRIC_UTILS_POOR_MANS_QUANTUM_DISTRIBUTIONS_WEIBULL_HPP
#define _METRIC_UTILS_POOR_MANS_QUANTUM_DISTRIBUTIONS_WEIBULL_HPP
#include <random>
#include <vector>
namespace metric {
/**
* @class Weibull
*
* @brief class realize Weibull random distribution
*/
class Weibull {
public:
/**
* @brief Construct a new Weibull object
*
*/
Weibull();
/**
* @brief sample a random value
*
* @return random value according to Weibul distribution
*/
float rnd();
/**
* @brief long-run average value of repetitions of the same experiment
*
* @return return the expected value of distribution
*/
float mean();
/**
* @brief quantil function
*
* @param p
* @return value of the random variable such that the probability of the variable being less than or equal to that
* value equals the given probability.
*/
float quantil(float p);
/**
* @brief probability density function
*
* @param x
* @return
*/
float pdf(const float x);
/**
* @brief cumulative distribution function
*
* @param x
* @return
*/
float cdf(const float x);
/**
* @brief inverse cumulative distribution function
*
* @param x
* @return
*/
float icdf(const float x);
float _p1;
float _p2;
std::vector<float> _data;
std::vector<float> _prob;
private:
std::mt19937_64 _generator;
};
} // end namespace metric
#include "Weibull.cpp"
#endif // header guard
| 1,653
|
C++
|
.h
| 74
| 19.824324
| 115
| 0.708174
|
metric-space-ai/metric
| 34
| 14
| 44
|
MPL-2.0
|
9/20/2024, 10:43:29 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| true
| false
|
1,531,680
|
Discrete.hpp
|
metric-space-ai_metric/metric/utils/poor_mans_quantum/distributions/Discrete.hpp
|
/*
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/.
Copyright (c) 2019 Panda Team
*/
#ifndef _METRIC_UTILS_POOR_MANS_QUANTUM_DISTRIBUTIONS_DISCRETE_HPP
#define _METRIC_UTILS_POOR_MANS_QUANTUM_DISTRIBUTIONS_DISCRETE_HPP
#include <random>
#include <vector>
namespace metric {
/**
* @class Discrete
*
* @brief Class represents discrete distribution
*/
template <typename T = float> class Discrete {
public:
/**
* @brief Construct a new Discrete object
*
*/
Discrete();
/**
* @brief
*
* @param seed
*/
void seed(size_t seed);
/**
* @brief sample a random value
*
* @return random value according to Normal distribution
*/
T rnd();
/**
* @brief
*
* @return
*/
T median();
/**
* @brief quantil function
*
* @param p
* @return value of the random variable such that the probability of the variable being less than or equal to that
* value equals the given probability.
*/
T quantil(T p);
/**
* @brief long-run average value of repetitions of the same experiment
*
* @return return the expected value of distribution
*/
T mean();
/**
* @brief expectation of the squared deviation of a random variable from its mean
*
* @return variance value of the Normal distribution
*/
T variance();
/**
* @brief probability density function
*
* @param x
* @return
*/
T pdf(const T x);
/**
* @brief cumulative distribution function
*
* @param x
* @return
*/
T cdf(const T x);
/**
* @brief inverse cumulative distribution function
*
* @param x
* @return
*/
T icdf(const T x);
T _p1;
T _p2;
std::vector<T> _data;
std::vector<T> _prob;
private:
std::mt19937_64 _generator;
};
} // end namespace metric
#include "Discrete.cpp"
#endif // header guard
| 1,915
|
C++
|
.h
| 92
| 18.25
| 115
| 0.688606
|
metric-space-ai/metric
| 34
| 14
| 44
|
MPL-2.0
|
9/20/2024, 10:43:29 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| true
| false
|
1,531,681
|
image_filter.hpp
|
metric-space-ai_metric/metric/utils/image_processing/image_filter.hpp
|
/*
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/.
Created by Aleksey Timin on 3/29/20.
*/
#ifndef IMAGEFILTER_H
#define IMAGEFILTER_H
#include <algorithm>
#include <blaze/Math.h>
#include <cmath>
/**
* Module of image filters based on 2 convolution.
*
* Usage for RGB:
*
* auto input = iminit<uint8_t, 3>(1920, 1080, 50);
* imfilter<uint8_t, 3, FilterType::GAUSSIAN, PadDirection::BOTH, PadType::CONST> f(3, 3, 0.3);
* Image<uint8_t, 3> filterImage = f(input);
*
* Image<uint8_t, 3> ouput = imfilter(input, filter, padmodel);
*
* Usage for one gray channel
*
* auto input = Channel<double>(1920, 1080, 50.0);
* imfilter<double, 1, FilterType::AVERAGE, PadDirection::BOTH, PadType::CONST> f(3, 3);
* Channel<double> out = f(input);
*
* Implemented filters:
* AverageFilter
* GaussianFilter
* LaplacianFilter
* LogFilter
* MotionFilter
* PrewittFilter
* UnsharpFilter
* SobelFilter
*/
namespace metric {
template <typename T> using Channel = blaze::DynamicMatrix<T>;
template <typename T, size_t N> using Image = blaze::StaticVector<Channel<T>, N>;
using FilterKernel = blaze::DynamicMatrix<double>;
using Shape = blaze::StaticVector<size_t, 2>;
/**
* Creates an Image
* @tparam T type of the element in a channel
* @tparam N number of channels
* @param rows number of rows (height)
* @param columns number of columns (width)
* @param initValue default value for all elements in a channel
* @return
*/
template <typename T, size_t N> Image<T, N> iminit(size_t rows, size_t columns, T initValue = {});
enum class PadDirection { POST, PRE, BOTH };
enum class PadType {
CONSTANT,
REPLICATE,
SYMMETRIC,
CIRCULAR,
};
/**
* Implements different ways to pad a channel before to apply a filter on them
* see Matlab's padarray for more details
* @tparam T
*/
template <typename T> class PadModel {
public:
/**
* Creates the model
* @param padDirection
* @param padType
* @param initValue
*/
PadModel(PadDirection padDirection, PadType padType, T initValue = {})
: _padDirection(padDirection), _padType(padType), _initValue(initValue){};
/**
* Pads the matrix
* @param shape shape of the padding
* @param src matrix to pad
* @return the padded matrix
*/
std::pair<blaze::DynamicMatrix<T>, Shape> pad(const Shape &shape, const blaze::DynamicMatrix<T> &src) const;
private:
PadDirection _padDirection;
PadType _padType;
T _initValue;
};
template <typename ChannelType, size_t N, typename Filter, PadDirection PadDir, PadType PadType> class imfilter {
public:
template <typename... FilterArgs> imfilter(FilterArgs... args) : _padModel(PadDir, PadType), _filter(args...) {}
Channel<ChannelType> operator()(const Channel<ChannelType> &input);
Image<ChannelType, N> operator()(const Image<ChannelType, N> &input);
private:
PadModel<ChannelType> _padModel;
Filter _filter;
};
class FilterType {
public:
/**
* Average filter
*/
class AVERAGE {
public:
/**
* Creates an averaging filter
* @param shape the shape of the kernel
*/
AVERAGE(size_t rows, size_t columns);
FilterKernel operator()() const { return _kernel; }
private:
FilterKernel _kernel;
};
/**
* Disk average filer
*/
class DISK {
public:
/**
* Creates circular averaging filter. Kernel size 2*rad+1
* @param rad the radius of the kernel
*/
explicit DISK(double rad) : _rad(rad){};
FilterKernel operator()() const
{
// TODO: Next steps are not clear. Implement!!!
return FilterKernel();
}
private:
FilterKernel::ElementType _rad;
};
class LOG;
/**
* Gaussian lowpass filter
*/
class GAUSSIAN {
friend class FilterType::LOG;
public:
/**
* Creates a rotationally symmetric Gaussian lowpass filter
* @param shape the shape of the filter
* @param sigma standard deviation
*/
GAUSSIAN(size_t rows, size_t columns, double sigma);
FilterKernel operator()() const { return _kernel; }
private:
FilterKernel _kernel;
FilterKernel _xMat;
FilterKernel _yMat;
};
/**
* Laplacian filter
*/
class LAPLACIAN {
public:
/**
* Creates a 3-by-3 filter approximating the shape
* of the two-dimensional Laplacian operator.
* @param alpha must be in the range 0.0 to 1.0.
*/
explicit LAPLACIAN(double alpha);
FilterKernel operator()() const { return _kernel; }
private:
FilterKernel _kernel;
};
/**
* Rotationally symmetric Laplacian of Gaussian filter
*/
class LOG {
public:
/**
* Creates a rotationally symmetric Laplacian of Gaussian filter
* @param shape the shape of the kernel
* @param sigma sigma standard deviation
*/
LOG(size_t rows, size_t columns, double sigma);
FilterKernel operator()() const { return _kernel; }
private:
FilterKernel _kernel;
};
/**
* Filter to approximate, once convolved with an image,
* the linear motion of a camera
*/
class MOTION {
public:
/**
* Creates a filter
* @param len linear motion of a camera in pixels
* @param theta motion angle in degrees
*/
MOTION(double len, int theta);
FilterKernel operator()() const { return _kernel; }
private:
FilterKernel _kernel;
};
/**
* Prewitt filter
*/
class PREWITT {
public:
/**
* Creates 3-by-3 filter that emphasize
* horizontal edges by approximating a vertical gradient.
*/
PREWITT() : _kernel{{1, 1, 1}, {0, 0, 0}, {-1, -1, -1}} {}
FilterKernel operator()() const { return _kernel; }
private:
FilterKernel _kernel;
};
/**
* Unsharp filter
*/
class UNSHARP {
public:
/**
* Creates 3-by-3 unsharp contra enhancement filter.
* @param alpha must be in the range 0.0 to 1.0
*/
UNSHARP(double alpha);
FilterKernel operator()() const { return _kernel; }
private:
FilterKernel _kernel;
};
/**
* Sobel filter
*/
class SOBEL {
public:
/**
* Creates 3-by-3 filter that emphasizes
* horizontal edges utilizing the smoothing effect by approximating a
* vertical gradient
*/
SOBEL() : _kernel{{1, 2, 1}, {0, 0, 0}, {-1, -2, -1}} {}
FilterKernel operator()() const { return _kernel; }
private:
FilterKernel _kernel;
};
};
namespace image_processing_details {
/**
* The analog of Matlab's meshgrid
*
* @tparam T type of the elements
* @param x x-coordinates over grid
* @param y y-coordinates over grid
* @return returns 2-D grid coordinates based on the coordinates contained in vectors x and y
*/
template <typename T>
std::pair<blaze::DynamicMatrix<T>, blaze::DynamicMatrix<T>>
meshgrid(const blaze::DynamicVector<T, blaze::rowVector> &x, const blaze::DynamicVector<T, blaze::columnVector> &y);
/**
* Creates a vector as range between two values
* @tparam T type of the lements
* @tparam P blaze::columnVector or blaze::rawVector
* @param start
* @param stop
* @param step
* @return
*/
template <typename T, bool P> blaze::DynamicVector<T, P> range(T start, T stop, T step = 1);
/**
* Finds elements in an intput matrix that corseponds true in the conditional matrix
* @tparam T the type of the elements
* @param input input matrix
* @param cond the conditional matrix
* @return returns a matrix of coordinates of founded elements
*/
template <typename T>
blaze::DynamicVector<std::pair<size_t, size_t>, blaze::columnVector> mfind(const blaze::DynamicMatrix<T> &input,
const blaze::DynamicMatrix<bool> &cond);
/**
* Rotetes matrix on 90 degree clockwise
* @tparam T type of the elements
* @param input matrix to rotate
* @return the rotated matrix
*/
template <typename T> blaze::DynamicMatrix<T> rot90(const blaze::DynamicMatrix<T> &input)
{
blaze::DynamicMatrix<T> out(input.columns(), input.rows());
for (int i = 0; i < input.rows(); ++i) {
auto r = blaze::trans(blaze::row(input, i));
blaze::column(out, input.rows() - i - 1) = r;
}
return out;
}
/**
* Flips a matrix to down (analog og Matlab's flipud)
* @tparam T type of the elements
* @param input matrix to modify
* @return the flipped matrix
*/
template <typename T> blaze::DynamicMatrix<T> flipud(const blaze::DynamicMatrix<T> &input);
/**
* Returns the two-dimensional convolution of a matrix and kernel
* @param kernel the kernel to convolute
* @return
*/
static blaze::DynamicMatrix<double> imgcov2(const blaze::DynamicMatrix<double> &input, const FilterKernel &kernel);
/**
* Filter an one channel
* @tparam ChannelType type of the channel
* @param img image to filter (onlye a channel)
* @param impl implementation of the filter
* @param padmodel padding
* @param full if true it returns the matrix with padding, else returns only the image
* @return the filtered image
*/
template <typename Filter, typename ChannelType>
Channel<ChannelType> filter(const Channel<ChannelType> &img, const Filter &impl, const PadModel<ChannelType> &padmodel,
bool full = true);
/**
* Filter an image
* @tparam Filter type of the filter
* @tparam ChannelType type of the chanel
* @param img image to filter
* @param impl implementation of the filter
* @param padmodel padding
* @param full if true it returns the matrix with padding, else returns only the image
* @return the filtered image
*/
template <typename Filter, typename ChannelType, size_t ChannelNumber>
Image<ChannelType, ChannelNumber> filter(const Image<ChannelType, ChannelNumber> &img, const Filter &impl,
const PadModel<ChannelType> &padmodel, bool full = true);
} // namespace image_processing_details
} // namespace metric
#include "image_filter.cpp"
#endif // IMAGE_FILTER
| 9,699
|
C++
|
.h
| 328
| 26.893293
| 119
| 0.712783
|
metric-space-ai/metric
| 34
| 14
| 44
|
MPL-2.0
|
9/20/2024, 10:43:29 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,531,682
|
convolution.hpp
|
metric-space-ai_metric/metric/utils/image_processing/convolution.hpp
|
#ifndef CONVOLUTION_HPP
#define CONVOLUTION_HPP
#include "../dnn/Activation/Identity.h"
#include "../dnn/Layer/Conv2d.h"
#include "image_filter.hpp"
namespace metric {
template <typename T, size_t Channels> class Convolution2d {
public:
using Channel = blaze::DynamicMatrix<T>;
using Image = blaze::StaticVector<Channel, Channels>;
using FilterKernel = blaze::DynamicMatrix<T>;
using ConvLayer2d = dnn::Conv2d<T, dnn::Identity<T>>;
using Matrix = typename ConvLayer2d::Matrix;
using Clock = std::chrono::high_resolution_clock;
Convolution2d() {} // added by Max F 28 jul 2020 in order to derive from this
Convolution2d(size_t imageWidth, size_t imageHeight, size_t kernelWidth, size_t kernelHeight);
void setKernel(const FilterKernel &kernel);
Image operator()(const Image &image);
Image operator()(const Image &image, const FilterKernel &kernel);
protected: // private: // changed by Max F 28 jul 2020 in order to derive from this
std::shared_ptr<PadModel<T>> padModel;
size_t padWidth;
size_t padHeight;
std::shared_ptr<dnn::Layer<T>> convLayer;
};
} // namespace metric
#include "convolution.cpp"
#endif
| 1,135
|
C++
|
.h
| 28
| 38.535714
| 95
| 0.763206
|
metric-space-ai/metric
| 34
| 14
| 44
|
MPL-2.0
|
9/20/2024, 10:43:29 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,531,683
|
solver.hpp
|
metric-space-ai_metric/metric/utils/solver/solver.hpp
|
/*
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/.
Copyright (c) 2019 Panda Team
Copyright (c) 2019 Oleg Popov
*/
#ifndef _METRIC_UTILS_SOLVER_SOLVER_HPP
#define _METRIC_UTILS_SOLVER_SOLVER_HPP
#include "approxchol.hpp"
#include "helper/graphalgs.hpp"
#include "helper/solvertypes.hpp"
#endif
| 440
|
C++
|
.h
| 13
| 32.692308
| 67
| 0.781176
|
metric-space-ai/metric
| 34
| 14
| 44
|
MPL-2.0
|
9/20/2024, 10:43:29 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| true
| false
|
1,531,684
|
approxchol.hpp
|
metric-space-ai_metric/metric/utils/solver/approxchol.hpp
|
/*
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/.
Copyright (c) 2019 Panda Team
Copyright (c) 2019 Oleg Popov
*/
/*
Laplacians is a package containing graph algorithms, with an emphasis on tasks related to
spectral and algebraic graph theory. It contains (and will contain more) code for solving
systems of linear equations in graph Laplacians, low stretch spanning trees, sparsifiation,
clustering, local clustering, and optimization on graphs.
All graphs are represented by sparse adjacency matrices. This is both for speed, and because
our main concerns are algebraic tasks. It does not handle dynamic graphs. It would be very slow
to implement dynamic graphs this way.
https://github.com/danspielman/Laplacians.jl
*/
// Structures for the approxChol solver
#ifndef _METRIC_UTILS_SOLVER_APPROXCOL_HPP
#define _METRIC_UTILS_SOLVER_APPROXCOL_HPP
#include "helper/graphalgs.hpp"
#include "helper/lapwrappers.hpp"
#include "helper/solvertypes.hpp"
#include "pcg.hpp"
#include <blaze/Math.h>
#include <chrono>
#include <functional>
#include <iostream>
#include <stdint.h>
#include <type_traits>
#include <utility>
#include <vector>
namespace metric {
/**
* @brief Laplacian solver by Daniel A.Spielman, 2017
* This algorithm is an implementation of an approximate edge - by - edge elimination
* algorithm inspired by the Approximate Gaussian Elimination algorithm of Kyng and Sachdeva.
* approxchol_lap: the main solver.
*
* @param a
* @param pcgIts is an array for returning the number of pcgIterations. Default is length 0, in which case nothing is
returned.
* @param tol is set to 1e-6 by default,
* @param maxits defaults to MAX_VAL
* @param maxtime defaults to MAX_VAL. It measures seconds.
* @param verbose defaults to false
* @param params is additional parameters.
* params = ApproxCholParams(order, output)
order can be one of
Deg(by degree, adaptive),
WDeg(by original wted degree, nonadaptive),
Given
* @return
*/
template <typename Tv>
inline SubSolver<Tv> approxchol_lap(const blaze::CompressedMatrix<Tv, blaze::columnMajor> &a,
std::vector<size_t> &pcgIts, float tol = 1e-6, double maxits = 1000,
double maxtime = HUGE_VAL, bool verbose = false,
ApproxCholParams params = ApproxCholParams());
/*
LLp elements are all in the same column.
row tells us the row, and val is the entry.
val is set to zero for some edges that we should remove.
next gives the next in the column.It points to itself to terminate.
reverse is the index into lles of the other copy of this edge,
since every edge is stored twice as we do not know the order of elimination in advance.
*/
/**
* @brief LLp elements are all in the same column.
*
* @tparam Tv
*/
template <typename Tv> class LLp {
public:
/**
* @brief Construct a new LLp object
*
* @param Arow
* @param Aval
* @param Anext
* @param Areverse
*/
LLp(const size_t Arow, const Tv Aval, const LLp *Anext, const LLp *Areverse)
: row(Arow), val(Aval), next(Anext), reverse(Areverse)
{
}
/**
* @brief Construct a new LLp object
*
* @param Arow
* @param Aval
*/
LLp(const size_t Arow, const Tv Aval) : row(Arow), val(Aval), next(this), reverse(this) {}
/**
* @brief Construct a new LLp object
*
* @param Arow
* @param Aval
* @param Anext
*/
LLp(const size_t Arow, const Tv Aval, LLp *Anext) : row(Arow), val(Aval), next(Anext), reverse(this) {}
/**
* @brief row tells us the row
*
*/
size_t row;
/**
* @brief val is the entry. val is set to zero for some edges that we should remove.
*
*/
Tv val;
/**
* @brief gives the next in the column.It points to itself to terminate.
*
*/
LLp *next;
/**
* @brief the index into lles of the other copy of this edge,
* since every edge is stored twice as we do not know the order of elimination in advance.
*
*/
LLp *reverse;
};
/*
LLmatp is the data structure used to maintain the matrix during elimination.
It stores the elements in each column in a singly linked list(only next ptrs)
Each element is an LLp(linked list pointer).
The head of each column is pointed to by cols.
We probably can get rid of degs - as it is only used to store initial degrees.
*/
/**
* @class LLmatp
*
* @brief the data structure used to maintain the matrix during elimination.
* It stores the elements in each column in a singly linked list(only next ptrs)
* Each element is an LLp(linked list pointer).
* The head of each column is pointed to by cols.
* We probably can get rid of degs - as it is only used to store initial degrees.
*
*/
template <typename Tv> class LLmatp {
public:
/**
* @brief Construct a new LLmatp object
*
* @param A
*/
explicit LLmatp(const blaze::CompressedMatrix<Tv, blaze::columnMajor> &A);
/**
* @brief Destroy the LLmatp object
*
*/
~LLmatp()
{
for (size_t i = 0; i < llelems.size(); i++)
delete llelems[i];
}
size_t n;
std::vector<size_t> degs;
std::vector<LLp<Tv> *> cols;
std::vector<LLp<Tv> *> llelems;
};
/**
* @brief Print a column in an LLmatp matrix.
* This is here for diagnostics.
*
* @param llmat
* @param i
*/
template <typename Tv> void print_ll_col(const LLmatp<Tv> &llmat, const size_t i);
// these are the types we use with a fixed ordering
/**
* @class LLord
*
* @brief
*
*
*/
template <typename Tv> class LLord {
public:
/**
* @brief Construct a new LLord object
*
* @param Arow
* @param Anext
* @param Aval
*/
LLord(const size_t Arow, const size_t Anext, const Tv Aval) : row(Arow), next(Anext), val(Aval) {}
size_t row;
size_t next;
Tv val;
};
/**
* @class LLMatOrd
* @brief
*
*/
template <typename Tv> class LLMatOrd {
public:
size_t n;
std::vector<size_t> cols;
std::vector<LLord<Tv>> lles;
};
/**
* @class LLcol
* @brief
*
*/
template <typename Tv> class LLcol {
public:
/**
* @brief Construct a new LLcol object
*
* @param Arow
* @param Aptr
* @param Aval
*/
LLcol(const size_t Arow, const size_t Aptr, const Tv Aval) : row(Arow), ptr(Aptr), val(Aval) {}
size_t row;
size_t ptr;
Tv val;
};
// LDLinv
/* LDLinv contains the information needed to solve the Laplacian systems.
It does it by applying Linv, then Dinv, then Linv (transpose).
But, it is specially constructed for this particular solver.
It does not explicitly make the matrix triangular.
Rather, col[i] is the name of the ith col to be eliminated
*/
/**
* @class LDLinv
* @brief LDLinv contains the information needed to solve the Laplacian systems.
* It does it by applying Linv, then Dinv, then Linv (transpose).
* But, it is specially constructed for this particular solver.
* It does not explicitly make the matrix triangular.
* Rather, col[i] is the name of the ith col to be eliminated
*/
template <typename Tv> class LDLinv {
public:
/**
* @brief Construct a new LDLinv object
*
* @param A
*/
explicit LDLinv(const blaze::CompressedMatrix<Tv, blaze::columnMajor> &A)
: col(A.columns() - 1, 0), colptr(A.columns(), 0), d(A.columns(), 0) /* rowval and fval are empty*/
{
}
/**
* @brief Construct a new LDLinv object
*
* @param A
*/
explicit LDLinv(const LLMatOrd<Tv> &A) : col(A.n - 1, 0), colptr(A.n, 0), d(A.n, 0) {}
/**
* @brief Construct a new LDLinv object
*
* @param A
*/
explicit LDLinv(const LLmatp<Tv> &A) : col(A.n - 1, 0), colptr(A.n, 0), d(A.n, 0) {}
/**
* @brief
*
* @param b
* @return
*/
blaze::DynamicVector<Tv> LDLsolver(const blaze::DynamicVector<Tv> &b) const;
/**
* @brief
*
*/
void debug() const;
std::vector<size_t> col;
std::vector<size_t> colptr;
std::vector<size_t> rowval;
std::vector<Tv> fval;
std::vector<Tv> d;
private:
void forward(blaze::DynamicVector<Tv> &y) const;
void backward(blaze::DynamicVector<Tv> &y) const;
};
/**
* @class ApproxCholPQElem
* @brief the data structure we use to keep track of degrees
*
*/
class ApproxCholPQElem {
public:
/**
* @brief Construct a new ApproxCholPQElem object
*
*/
ApproxCholPQElem(){};
/**
* @brief Construct a new ApproxCholPQElem object
*
* @param Aprev
* @param Anext
* @param Akey
*/
ApproxCholPQElem(const size_t Aprev, const size_t Anext, const size_t Akey) : prev(Aprev), next(Anext), key(Akey) {}
size_t prev = 0;
size_t next = 0;
size_t key = 0;
};
/**
* @class ApproxCholPQ
* @brief An approximate priority queue.
* Items are bundled together into doubly-linked lists with all approximately the same key.
* minlist is the min list we know to be non-empty.
* It should always be a lower bound.
* keyMap maps keys to lists
*
*/
class ApproxCholPQ {
public:
/**
* @brief Construct a new ApproxCholPQ object
*
* @param a
*/
explicit ApproxCholPQ(const std::vector<size_t> &a);
/**
* @brief
*
* @param i
* @param newkey
* @param oldlist
* @param newlist
*/
void move(const size_t i, const size_t newkey, const size_t oldlist, const size_t newlist);
/**
* @brief
*
* @param i
*/
void inc(const size_t i);
/**
* @brief
*
* @param i
*/
void dec(const size_t i);
/**
* @brief
*
* @return
*/
size_t pop();
/**
* @brief
*
*/
void debug();
std::vector<ApproxCholPQElem> elems; // indexed by node name
std::vector<size_t> lists;
size_t minlist;
size_t nitems;
size_t n;
};
// The approximate factorization
/**
* @brief
*
* @param llmat
* @param i
* @param colspace
* @return
*/
template <typename Tv> size_t get_ll_col(const LLmatp<Tv> &llmat, size_t i, std::vector<LLp<Tv> *> &colspace);
/**
* @brief
*
* @param colspace
* @param len
*/
template <typename Tv> void debugLLp(const std::vector<LLp<Tv> *> &colspace, size_t len);
/**
* @brief
*
* @param colspace
* @param len
* @param pq
* @return
*/
template <typename Tv> size_t compressCol(std::vector<LLp<Tv> *> &colspace, size_t len, ApproxCholPQ &pq);
/**
* @brief
*
* @param colspace
* @param len
* @return
*/
template <typename Tv> size_t compressCol(std::vector<LLcol<Tv>> &colspace, size_t len);
// this one is greedy on the degree - also a big win
/**
* @brief
*
* @tparam Tv
* @param a
* @return
*/
template <typename Tv> LDLinv<Tv> approxChol(LLmatp<Tv> &a);
/**
* @brief
*
* @param a
* @param pcgIts
* @param tol
* @param maxits
* @param maxtime
* @param verbose
* @param params
* @return
*/
template <typename Tv>
SubSolver<Tv> approxchol_lapGreedy(const blaze::CompressedMatrix<Tv, blaze::columnMajor> &a,
std::vector<size_t> &pcgIts, float tol = 1e-6, double maxits = 1000,
double maxtime = HUGE_VAL, bool verbose = false,
ApproxCholParams params = ApproxCholParams());
/**
* @brief
*
* @param a
* @param pcgIts
* @param tol
* @param maxits
* @param maxtime
* @param verbose
* @param params
* @return
*/
template <typename Tv>
inline SubSolver<Tv> approxchol_lap1(const blaze::CompressedMatrix<Tv, blaze::columnMajor> &a,
std::vector<size_t> &pcgIts, float tol = 1e-6, double maxits = 1000,
double maxtime = HUGE_VAL, bool verbose = false,
ApproxCholParams params = ApproxCholParams())
{
return approxchol_lapGreedy(a, pcgIts, tol, maxits, maxtime, verbose, params);
}
/**
* @brief
*
* @param a
* @param pcgIts
* @param tol
* @param maxits
* @param maxtime
* @param verbose
* @param params
* @return SubSolver<Tv>
*/
template <typename Tv>
inline SubSolver<Tv> approxchol_lap(const blaze::CompressedMatrix<Tv, blaze::columnMajor> &a,
std::vector<size_t> &pcgIts, float tol, double maxits, double maxtime, bool verbose,
ApproxCholParams params)
{
return lapWrapComponents(SolverA<Tv>(approxchol_lap1<Tv>), a, pcgIts, tol, maxits, maxtime, false);
}
/**
* @class SqLinOp
* @brief
*
*/
template <typename Tv> class SqLinOp {
public:
/**
* @brief Construct a new SqLinOp object
*
* @param issym
* @param value
* @param n
* @param multFn
*/
SqLinOp(bool issym, Tv value, size_t n, SubSolver<Tv> multFn) : issym(issym), value(value), n(n), multFn(multFn){};
bool issym;
Tv value;
size_t n;
SubSolver<Tv> multFn;
};
/**
* @brief
*
* @param A
* @return
*/
template <typename Tv> std::pair<size_t, size_t> size(const SqLinOp<Tv> &A) { return std::make_pair(A.n, A.n); }
/**
* @brief
*
* @param A
* @param d
* @return
*/
template <typename Tv> inline size_t size(const SqLinOp<Tv> &A, size_t d) { return A.n; }
/**
* @brief
*
* @param A
* @return true
* @return false
*/
template <typename Tv> inline bool issymetric(const SqLinOp<Tv> &A) { return A.issym; }
/**
* @brief
*
* @param A
* @param b
* @return
*/
template <typename Tv>
inline blaze::DynamicVector<Tv> operator*(const SqLinOp<Tv> &A, const blaze::DynamicVector<Tv> &b)
{
return A.multFn(b);
}
/**
* @brief
*
* @param A
* @return
*/
template <typename Tv> size_t checksquare(const SqLinOp<Tv> &A) { return A.n; }
/**
* @brief
*
* @param Y
* @param A
* @param B
*/
template <typename Tv> void mul(blaze::DynamicVector<Tv> &Y, const SqLinOp<Tv> &A, const blaze::DynamicVector<Tv> &B)
{
blaze::DynamicVector<Tv> Y1 = A * B;
for (size_t i = 0; i < A.n; i++) {
Y[i] = Y1[i];
}
}
// template <typename Tv>
// auto aupd_wrapper(function<blaze::DynamicVector<Tv>(blaze::DynamicVector <Tv>)> matvecA,
// function<blaze::DynamicVector<Tv>(blaze::DynamicVector <Tv>)> matvecB,
// function<blaze::DynamicVector<Tv>(blaze::DynamicVector <Tv>)> solveSI,
// size_t n, bool sym, size_t nev, size_t ncv,
// float tol, size_t maxiter, size_t mode, blaze::DynamicVector<Tv> v0) {
// size_t lworkl = sym ? ncv * (ncv + 8) : ncv * (3 * ncv + 6);
// DynamicMatrix<Tv> v(n, ncv);
// blaze::DynamicVector<Tv> workd(3 * n);
// blaze::DynamicVector<Tv> workl(lworkl);
// blaze::DynamicVector<Tv> rwork;
// blaze::DynamicVector<Tv> resid;
// size_t info;
// if (v0.size() == 0) {
// resid.resize(n);
// info = 0;
// }
// else {
// resid = v0;
// info = 1;
// }
// std::vector<size_t> iparam(11);
// int sz = sym ? 11 : 14;
// std::vector<size_t>ipntr(sz);
// size_t ido = 0;
// iparam[1] = 1; //ishifts
// iparam[2] = maxiter; //maxiter
// iparam[6] = mode; //mode
// zernm1 = collection(0, n);
// while (true) {
// if (sym)
// saupd(ido, n, nev, &tol, resid, ncv, v, n, iparam, ipntr, workd, workl, lworkl, info);
// }
// }
// template <typename Tv>
// blaze::DynamicVector<Tv> eigs(SqLinOp<Tv> A, size_t nev = 6, float tol = 0.0F) {
// size_t tmp = 2 * nev + 1;
// int sigma = -1;
// size_t ncv = 20 > tmp ? 20 : tmp;
// size_t maxiter = 300;
// std::vector<Tv> v0;
// bool ritzvec = true;
// bool isgeneral = false;
// size_t n = checksquare(A);
// bool sym = issymmetric(A);
// size_t nevmax = sym ? n - 1 : n - 2;
// if (nevmax <= 0)
// throw("Input matrix A is too small. Use eigen instead.");
// if (nev > nevmax)
// nev = nevmax;
// if (nev == 0)
// throw("Requested number of eigenvalues (nev) must be ≥ 1");
// ncvmin = nev + (sym ? 1 : 2);
// if (ncv < ncvmin)
// ncv = ncvmin;
// ncv = ncv < nmin ? ncv : n;
// bool isshift = sigma > -1;
// sigma = isshift ? sigma : 0;
// if (v0.size() > 0)
// if (v0.size() != n)
// throw("Dimension does not mismatch");
// function<blaze::DynamicVector<Tv>(blaze::DynamicVector <Tv>)> matvecA, matvecB, solverSI;
// matvecA = [&A](blaze::DynamicVector<Tv>& y, const blaze::DynamicVector<Tv>& x) {return mul(y, A, x); };
// size_t mode;
// if (!isgeneral) {
// matvecB = [](x) {return x; };
// if (!isshift) {
// mode = 1;
// solverSI = [](x) {return x; };
// }
// else {
// mode = 3;
// //F = factorize(A - UniformScaling(sigma));
// //solveSI = [](x) {return F \ x; };
// }
// }
// blaze::DynamicVector<size_t> output;
// return output;
// }
} // namespace metric
#include "approxchol/approxchol.cpp"
#endif
| 16,167
|
C++
|
.h
| 618
| 23.919094
| 118
| 0.667529
|
metric-space-ai/metric
| 34
| 14
| 44
|
MPL-2.0
|
9/20/2024, 10:43:29 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| true
| false
|
1,531,685
|
pcg.hpp
|
metric-space-ai_metric/metric/utils/solver/pcg.hpp
|
/*
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/.
Copyright (c) 2019 Panda Team
Copyright (c) 2019 Oleg Popov
*/
/*
Laplacians is a package containing graph algorithms, with an emphasis on tasks related to
spectral and algebraic graph theory. It contains (and will contain more) code for solving
systems of linear equations in graph Laplacians, low stretch spanning trees, sparsifiation,
clustering, local clustering, and optimization on graphs.
All graphs are represented by sparse adjacency matrices. This is both for speed, and because
our main concerns are algebraic tasks. It does not handle dynamic graphs. It would be very slow
to implement dynamic graphs this way.
https://github.com/danspielman/Laplacians.jl
*/
/*
Implementations of cg and pcg.
Look at two approaches: Matlab's, and
hypre: https://github.com/LLNL/hypre/blob/master/src/krylov/pcg.c
Started by Dan Spielman.
*/
#ifndef _METRIC_UTILS_SOLVER_PCG_HPP
#define _METRIC_UTILS_SOLVER_PCG_HPP
#include "helper/graphalgs.hpp"
#include "helper/solvertypes.hpp"
#include <blaze/Math.h>
#include <chrono>
#include <functional>
namespace metric {
const double EPS = 2.220446049250313e-16;
/*
x = pcg(mat, b, pre; tol, maxits, maxtime, verbose, pcgIts, stag_test)
solves a symmetric linear system using preconditioner `pre`.
# Arguments
* `pre` can be a function or a matrix. If a matrix, a function to solve it is created with Cholesky
Factorization.
* `tol` is set to 1e-6 by default,
* `maxits` defaults to MAX_VAL
* `maxtime` defaults to MAX_VAL. It measures seconds.
* `verbose` defaults to false
* `pcgIts` is an array for returning the number of pcgIterations. Default is length 0, in which case nothing is
returned.
* `stag_test=k` stops the code if rho[it] > (1-1/k) rho[it-k]. Set to 0 to deactivate.
*/
/**
* @brief solves a symmetric linear system using preconditioner `pre`.
*
* @param mat
* @param b
* @param pre can be a function or a matrix. If a matrix, a function to solve it is created with Cholesky
* Factorization.
* @param pcgIts is an array for returning the number of pcgIterations. Default is length 0, in which case nothing is
* returned.
* @param tol is set to 1e-6 by default,
* @param maxits defaults to MAX_VAL
* @param maxtime defaults to MAX_VAL. It measures seconds.
* @param verbose defaults to false
* @param stag_test `stag_test=k` stops the code if rho[it] > (1-1/k) rho[it-k]. Set to 0 to deactivate.
* @return
*/
template <typename Tv>
blaze::DynamicVector<Tv> pcg(const blaze::CompressedMatrix<Tv, blaze::columnMajor> &mat,
const blaze::DynamicVector<Tv> &b, SolverB<Tv> pre, std::vector<size_t> &pcgIts,
float tol = 1e-6, double maxits = HUGE_VAL, double maxtime = HUGE_VAL,
bool verbose = false, size_t stag_test = 0);
/**
* @brief solves a symmetric linear system using preconditioner `pre`.
*
* @param mat
* @param b
* @param pre can be a function or a matrix. If a matrix, a function to solve it is created with Cholesky
* Factorization.
* @param pcgIts is an array for returning the number of pcgIterations. Default is length 0, in which case nothing is
* returned.
* @param tol is set to 1e-6 by default,
* @param maxits defaults to MAX_VAL
* @param maxtime defaults to MAX_VAL. It measures seconds.
* @param verbose defaults to false
* @param stag_test `stag_test=k` stops the code if rho[it] > (1-1/k) rho[it-k]. Set to 0 to deactivate.
* @return
*/
template <typename Tv>
blaze::DynamicVector<Tv>
pcg(const blaze::CompressedMatrix<Tv, blaze::columnMajor> &mat, const blaze::DynamicVector<Tv> &b,
const blaze::CompressedMatrix<Tv, blaze::columnMajor> &pre, std::vector<size_t> &pcgIts, float tol = 1e-6,
double maxits = HUGE_VAL, double maxtime = HUGE_VAL, bool verbose = false, size_t stag_test = 0);
/**
* @brief
*
* @param mat
* @param pre
* @param pcgIts
* @param tol
* @param maxits
* @param maxtime
* @param verbose
* @return
*/
template <typename Tv>
SubSolver<Tv> pcgSolver(const blaze::CompressedMatrix<Tv, blaze::columnMajor> &mat, SolverB<Tv> pre,
std::vector<size_t> &pcgIts, float tol = 1e-6, double maxits = HUGE_VAL,
double maxtime = HUGE_VAL, bool verbose = false);
/**
* @brief
*
* @param mat
* @param pre
* @param pcgIts
* @param tol
* @param maxits
* @param maxtime
* @param verbose
* @return
*/
template <typename Tv>
SubSolver<Tv> pcgSolver(const blaze::CompressedMatrix<Tv, blaze::columnMajor> &mat,
const blaze::CompressedMatrix<Tv, blaze::columnMajor> &pre, std::vector<size_t> &pcgIts,
float tol = 1e-6, double maxits = HUGE_VAL, double maxtime = HUGE_VAL, bool verbose = false);
/**
* @brief
*
* @param al
* @param p
* @param x
*/
template <typename Tv> void axpy2(const Tv al, const blaze::DynamicVector<Tv> &p, blaze::DynamicVector<Tv> &x);
/**
* @brief
*
* @param beta
* @param p
* @param z
*/
template <typename Tv> void bzbeta(const Tv beta, blaze::DynamicVector<Tv> &p, const blaze::DynamicVector<Tv> &z);
} // namespace metric
#include "pcg/pcg.cpp"
#endif
| 5,239
|
C++
|
.h
| 139
| 35.438849
| 119
| 0.726629
|
metric-space-ai/metric
| 34
| 14
| 44
|
MPL-2.0
|
9/20/2024, 10:43:29 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| true
| false
|
1,531,686
|
sparsecsc.hpp
|
metric-space-ai_metric/metric/utils/solver/helper/sparsecsc.hpp
|
/*
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/.
Copyright (c) 2019 Panda Team
Copyright (c) 2019 Oleg Popov
*/
/*
Laplacians is a package containing graph algorithms, with an emphasis on tasks related to
spectral and algebraic graph theory. It contains (and will contain more) code for solving
systems of linear equations in graph Laplacians, low stretch spanning trees, sparsifiation,
clustering, local clustering, and optimization on graphs.
All graphs are represented by sparse adjacency matrices. This is both for speed, and because
our main concerns are algebraic tasks. It does not handle dynamic graphs. It would be very slow
to implement dynamic graphs this way.
https://github.com/danspielman/Laplacians.jl
*/
#ifndef _METRIC_UTILS_SOLVER_HELPER_SPARSECSC_HPP
#define _METRIC_UTILS_SOLVER_HELPER_SPARSECSC_HPP
#include <blaze/Math.h>
#include <vector>
namespace metric {
/**
* @class SparseMatrixCSC
*
* @brief Julia sparse matrix class
*/
template <typename Tv> class SparseMatrixCSC {
public:
/**
* @brief Construct a new SparseMatrixCSC object
*
* @param am
* @param an
* @param acolptr
* @param arowval
* @param anzval
*/
SparseMatrixCSC(size_t am, size_t an, std::vector<size_t> &acolptr, std::vector<size_t> arowval,
blaze::DynamicVector<Tv> anzval)
: m(am), n(an), colptr(acolptr), rowval(arowval), nzval(anzval)
{
}
/**
* @brief Construct a new SparseMatrixCSC object
*
*/
SparseMatrixCSC() : m(0), n(0) {}
/**
* @brief Construct a new SparseMatrixCSC from blaze::CompressedMatrix
*
* @param mat
*/
SparseMatrixCSC(const blaze::CompressedMatrix<Tv, blaze::columnMajor> &mat);
/**
* @brief Convert to blaze::CompressedMatrix
*
* @return result of conversion this to blaze::CompressedMatrix
*/
blaze::CompressedMatrix<Tv, blaze::columnMajor> toCompressedMatrix();
/**
* @brief equality operator
*
* @param b other sparse matrix
* @return true if matricies is equal
* @return false if matricies is not equal
*/
const bool operator==(const SparseMatrixCSC<Tv> &b) const;
size_t m;
size_t n;
std::vector<size_t> colptr; // vector type for size_t
std::vector<size_t> rowval; // vector type for size_t
blaze::DynamicVector<Tv> nzval; // blaze::DynamicVector type for Tv type
};
} // namespace metric
#include "sparsecsc/sparsecsc.cpp"
#endif
| 2,495
|
C++
|
.h
| 77
| 30.194805
| 97
| 0.748857
|
metric-space-ai/metric
| 34
| 14
| 44
|
MPL-2.0
|
9/20/2024, 10:43:29 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| true
| false
|
1,531,687
|
solvertypes.hpp
|
metric-space-ai_metric/metric/utils/solver/helper/solvertypes.hpp
|
/*
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/.
Copyright (c) 2019 Panda Team
Copyright (c) 2019 Oleg Popov
*/
/*
Laplacians is a package containing graph algorithms, with an emphasis on tasks related to
spectral and algebraic graph theory. It contains (and will contain more) code for solving
systems of linear equations in graph Laplacians, low stretch spanning trees, sparsifiation,
clustering, local clustering, and optimization on graphs.
All graphs are represented by sparse adjacency matrices. This is both for speed, and because
our main concerns are algebraic tasks. It does not handle dynamic graphs. It would be very slow
to implement dynamic graphs this way.
https://github.com/danspielman/Laplacians.jl
*/
#ifndef _METRIC_UTILS_SOLVER_HELPER_SOLVERTYPES_HPP
#define _METRIC_UTILS_SOLVER_HELPER_SOLVERTYPES_HPP
#include <functional>
namespace metric {
// Solvers for A*x=b where A is a matrix, b is a vector
/* Arguments:
*`tol` is set to 1e-6 by default,
* `maxits` defaults to MAX_VAL
* `maxtime` defaults to MAX_VAL.It measures seconds.
* `verbose` defaults to false
* `pcgIts` is an array for returning the number of pcgIterations.Default is length 0, in which case nothing is
returned.
* `params` is additional parameters.
params = ApproxCholParams(order, output)
order can be one of
Deg(by degree, adaptive),
WDeg(by original wted degree, nonadaptive),
Given
*/
// Functor: pass A matrix, return SubSolver
template <typename Tv> class SolverA;
// Result of solver
// Functor: pass vector b, returns x vector
template <typename Tv> class SubSolver;
template <typename Tv> using SolverB = std::function<blaze::DynamicVector<Tv>(const blaze::DynamicVector<Tv> &)>;
/**
* @class Factorization
*
* @brief
*/
template <typename Tv> class Factorization {
public:
blaze::CompressedMatrix<Tv, blaze::columnMajor> Lower;
};
/*
params = ApproxCholParams(order, output)
order can be one of
Deg(by degree, adaptive),
WDeg(by original wted degree, nonadaptive),
Given
*/
enum class ApproxCholEnum { Deg, WDeg, Given };
/**
* @class ApproxCholParams
*
* @brief
*
*/
class ApproxCholParams {
public:
ApproxCholParams()
{
order = ApproxCholEnum::Deg;
stag_test = 5;
}
ApproxCholParams(ApproxCholEnum symb)
{
order = symb;
stag_test = 5;
}
ApproxCholEnum order;
long stag_test;
};
// Types of solvers for A*x=B where B is a matrix
template <typename Tv>
using FactorSolver = std::function<Factorization<Tv>(const blaze::CompressedMatrix<Tv, blaze::columnMajor> &)>;
// Result of wrappers
// Function: pass B matrix, returns x vector
template <typename Tv>
using SolverBMat = std::function<blaze::DynamicVector<Tv>(const blaze::CompressedMatrix<Tv, blaze::columnMajor> &)>;
// Result of SolverA functor
// Convert SolverA to a function with 1 paramater B - SolverB
template <typename Tv>
using SubSolverFuncMat = std::function<blaze::DynamicVector<Tv>(const blaze::CompressedMatrix<Tv, blaze::columnMajor> &,
std::vector<size_t> &)>;
/**
* @class SubSolverMat
*
* @brief
*
*/
template <typename Tv> class SubSolverMat {
public:
/**
* @brief Construct a new SubSolverMat object
*
* @param Asolver
*/
explicit SubSolverMat(SubSolverFuncMat<Tv> Asolver) : Solver(Asolver){};
/**
* @brief Construct a new SubSolverMat object
*
* @param solver
*/
explicit SubSolverMat(SolverBMat<Tv> solver)
{
Solver = [=](const blaze::CompressedMatrix<Tv, blaze::columnMajor> &b, std::vector<size_t> &pcgIts) {
return solver(b);
};
}
/**
* @brief
*
* @param b
* @param pcgIts
* @return
*/
blaze::DynamicVector<Tv> operator()(const blaze::CompressedMatrix<Tv, blaze::columnMajor> &b,
std::vector<size_t> &pcgIts)
{
return Solver(b, pcgIts);
}
/**
* @brief
*
* @param b
*/
blaze::DynamicVector<Tv> operator()(const blaze::CompressedMatrix<Tv, blaze::columnMajor> &b)
{
std::vector<size_t> pcgIts;
return Solver(b, pcgIts);
}
private:
SubSolverFuncMat<Tv> Solver;
};
// Function: pass A matrix, return SubSolver
template <typename Tv>
using SolverAFuncMat =
std::function<SubSolverMat<Tv>(const blaze::CompressedMatrix<Tv, blaze::columnMajor> &, std::vector<size_t> &)>;
/**
* @class SolverAMat
*
* @brief
*/
template <typename Tv> class SolverAMat {
public:
/**
* @brief Construct a new SolverAMat object
*
* @param solver
*/
explicit SolverAMat(SolverAFuncMat<Tv> solver) : Solver(solver) {}
/**
* @brief
*
* @param a
* @param pcgIts
* @return
*/
SubSolverMat<Tv> operator()(const blaze::CompressedMatrix<Tv, blaze::columnMajor> &a, std::vector<size_t> &pcgIts)
{
return Solver(a, pcgIts);
}
/**
* @brief
*
* @param a
* @return
*/
SubSolverMat<Tv> operator()(const blaze::CompressedMatrix<Tv, blaze::columnMajor> &a)
{
std::vector<size_t> pcgIts;
return Solver(a, pcgIts);
}
private:
SolverAFuncMat<Tv> Solver;
};
// Result of functor SolverA
// Convert SolverA to a function with 1 paramater B - SolverB
template <typename Tv>
using SubSolverFunc = std::function<blaze::DynamicVector<Tv>(const blaze::DynamicVector<Tv> &, std::vector<size_t> &)>;
/**
* @class SubSolver
*
* @brief
*/
template <typename Tv> class SubSolver {
public:
/**
* @brief Construct a new SubSolver object
*
*/
SubSolver() {}
/**
* @brief Construct a new SubSolver object
*
* @param Asolver
*/
explicit SubSolver(SubSolverFunc<Tv> Asolver) : Solver(Asolver){};
/**
* @brief Construct a new SubSolver object
*
* @param solver
*/
explicit SubSolver(SolverB<Tv> solver)
{
Solver = [=](const blaze::DynamicVector<Tv> &b, std::vector<size_t> &pcgIts) { return solver(b); };
}
/**
* @brief
*
* @param b
* @param pcgIts
*/
blaze::DynamicVector<Tv> operator()(const blaze::DynamicVector<Tv> &b, std::vector<size_t> &pcgIts)
{
return Solver(b, pcgIts);
}
/**
* @brief
*
* @param b
*/
blaze::DynamicVector<Tv> operator()(const blaze::DynamicVector<Tv> &b)
{
std::vector<size_t> pcgIts;
return Solver(b, pcgIts);
}
private:
SubSolverFunc<Tv> Solver;
};
template <typename Tv>
using SolverAFunc = std::function<SubSolver<Tv>(const blaze::CompressedMatrix<Tv, blaze::columnMajor> &,
std::vector<size_t> &, float, double, double, bool, ApproxCholParams)>;
/**
* @class SovlerA
*
* @brief
*/
template <typename Tv> class SolverA {
public:
/**
* @brief Construct a new SolverA object
*
* @param solver
*/
explicit SolverA(SolverAFunc<Tv> solver) : Solver(solver) {}
/**
* @brief
*
* @param a
* @param pcgIts
* @param tol
* @param maxits
* @param maxtime
* @param verbose
* @param params
* @return SubSolver<Tv>
*/
SubSolver<Tv> operator()(const blaze::CompressedMatrix<Tv, blaze::columnMajor> &a, std::vector<size_t> &pcgIts,
float tol = 1e-6, double maxits = HUGE_VAL, double maxtime = HUGE_VAL,
bool verbose = false, ApproxCholParams params = ApproxCholParams())
{
return Solver(a, pcgIts, tol, maxits, maxtime, verbose, params);
}
/**
* @brief
*
* @param a
* @return SubSolver<Tv>
*/
SubSolver<Tv> operator()(const blaze::CompressedMatrix<Tv, blaze::columnMajor> &a)
{
std::vector<size_t> pcgIts;
return Solver(a, pcgIts, 1e-6F, HUGE_VAL, HUGE_VAL, false, ApproxCholParams());
}
private:
SolverAFunc<Tv> Solver;
};
} // namespace metric
#endif
| 7,562
|
C++
|
.h
| 288
| 23.767361
| 120
| 0.71478
|
metric-space-ai/metric
| 34
| 14
| 44
|
MPL-2.0
|
9/20/2024, 10:43:29 PM (Europe/Amsterdam)
| false
| false
| false
| false
| true
| false
| true
| false
|
1,531,688
|
lapwrappers.hpp
|
metric-space-ai_metric/metric/utils/solver/helper/lapwrappers.hpp
|
/*
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/.
Copyright (c) 2019 Panda Team
Copyright (c) 2019 Oleg Popov
*/
/*
Laplacians is a package containing graph algorithms, with an emphasis on tasks related to
spectral and algebraic graph theory. It contains (and will contain more) code for solving
systems of linear equations in graph Laplacians, low stretch spanning trees, sparsifiation,
clustering, local clustering, and optimization on graphs.
All graphs are represented by sparse adjacency matrices. This is both for speed, and because
our main concerns are algebraic tasks. It does not handle dynamic graphs. It would be very slow
to implement dynamic graphs this way.
https://github.com/danspielman/Laplacians.jl
*/
#ifndef _METRIC_UTILS_SOLVER_HELPER_LAPWRAPPERS_HPP
#define _METRIC_UTILS_SOLVER_HELPER_LAPWRAPPERS_HPP
#include "graphalgs.hpp"
#include "solvertypes.hpp"
#include <blaze/Math.h>
#include <chrono>
#include <vector>
namespace metric {
/**
* @brief
*
* @param a
* @param pcg
* @return
*/
template <typename Tv> blaze::DynamicVector<Tv> nullSolver(const blaze::DynamicVector<Tv> &a, std::vector<size_t> &pcg);
/**
* @brief Cholesky-based Substitution
*
* @param Lower
* @param B
* @return
*/
template <typename Tv>
blaze::DynamicVector<Tv> chol_subst(const blaze::CompressedMatrix<Tv, blaze::columnMajor> &Lower,
const blaze::CompressedMatrix<Tv, blaze::columnMajor> &B);
/**
* @brief
*
* @param Lower
* @param b
* @return
*/
template <typename Tv>
blaze::DynamicVector<Tv> chol_subst(const blaze::CompressedMatrix<Tv, blaze::columnMajor> &Lower,
const blaze::DynamicVector<Tv> &b);
/**
* @brief Function: pass A matrix, return A matrix factorization
*
* @param A
* @return
*/
template <typename Tv> inline Factorization<Tv> cholesky(const blaze::CompressedMatrix<Tv, blaze::columnMajor> &A);
// lapWrapComponents function
/**
* @brief Apply the ith solver on the ith component
*
* @param comps
* @param solvers
* @param pcgIts
* @param tol
* @param maxits
* @param maxtime
* @param verbose
* @return
*/
template <typename Tv>
SubSolver<Tv> BlockSolver(const std::vector<std::vector<size_t>> &comps, std::vector<SubSolver<Tv>> &solvers,
std::vector<size_t> &pcgIts, float tol = 1e-6F, double maxits = HUGE_VAL,
double maxtime = HUGE_VAL, bool verbose = false);
/**
* @brief
*
* param solver
* @param a
* @param pcgIts
* @param tol
* @param maxits
* @param maxtime
* @param verbose
* @param params
* @return
*/
template <typename Tv>
SubSolverMat<Tv> wrapInterfaceMat(const FactorSolver<Tv> solver,
const blaze::CompressedMatrix<Tv, blaze::columnMajor> &a, std::vector<size_t> &pcgIts,
float tol = 0, double maxits = HUGE_VAL, double maxtime = HUGE_VAL,
bool verbose = false, ApproxCholParams params = ApproxCholParams());
/**
* @brief
*
* @param solver
* @return
*/
template <typename Tv> SolverAMat<Tv> wrapInterfaceMat(const FactorSolver<Tv> solver);
/**
* @brief
*
* @param solver
* @param a
* @param pcgIts
* @param tol
* @param maxits
* @param maxtime
* @param verbose
* @param params
* @return
*/
template <typename Tv>
SubSolver<Tv> wrapInterface(const FactorSolver<Tv> solver, const blaze::CompressedMatrix<Tv, blaze::columnMajor> &a,
std::vector<size_t> &pcgIts, float tol = 0, double maxits = HUGE_VAL,
double maxtime = HUGE_VAL, bool verbose = false,
ApproxCholParams params = ApproxCholParams());
/**
* @brief
*
* @param solver
* @return
*/
template <typename Tv> SolverA<Tv> wrapInterface(const FactorSolver<Tv> solver);
/**
* @brief This functions wraps cholfact so that it satisfies our interface.
*
* @tparam Tv
* @return
*/
template <typename Tv> SolverAMat<Tv> chol_sddm_mat();
/**
* @brief
*
* @return
*/
template <typename Tv> SolverA<Tv> chol_sddm();
/**
* @brief Applies a Laplacian `solver` that satisfies our interface to each connected component of the graph with
* adjacency matrix `a`.
*
* @param solver
* @param a
* @param pcgIts
* @param tol
* @param maxits
* @param maxtime
* @param verbose
* @param params
* @return
*/
template <typename Tv>
SubSolver<Tv> lapWrapConnected(SolverA<Tv> solver, const blaze::CompressedMatrix<Tv, blaze::columnMajor> &a,
std::vector<size_t> &pcgIts, float tol = 1e-6, double maxits = HUGE_VAL,
double maxtime = HUGE_VAL, bool verbose = false,
ApproxCholParams params = ApproxCholParams());
/**
* @brief
*
* @param solver
* @return
*/
template <typename Tv> inline SolverA<Tv> lapWrapConnected(const SolverA<Tv> solver);
/**
* @brief
*
* @param solver
* @param a
* @param pcgIts
* @param tol
* @param maxits
* @param maxtime
* @param verbose
* @param params
* @return
*/
template <typename Tv>
SubSolver<Tv> lapWrapComponents(SolverA<Tv> solver, const blaze::CompressedMatrix<Tv, blaze::columnMajor> &a,
std::vector<size_t> &pcgIts, float tol = 1e-6, double maxits = HUGE_VAL,
double maxtime = HUGE_VAL, bool verbose = false,
ApproxCholParams params = ApproxCholParams());
/**
* @brief
*
* @param solver
* @return
*/
template <typename Tv> inline SolverA<Tv> lapWrapComponents(const SolverA<Tv> solver);
/**
* @brief
*
* @param sddmSolver
* @return
*/
template <typename Tv> inline SolverA<Tv> lapWrapSDDM(SolverA<Tv> sddmSolver);
/**
* @brief
*
* @param lapSolver
* @param sddm
* @param pcgIts
* @param tol
* @param maxits
* @param maxtime
* @param verbose
* @param params
* @return
*/
template <typename Tv>
SubSolver<Tv> sddmWrapLap(SolverA<Tv> lapSolver, const blaze::CompressedMatrix<Tv, blaze::columnMajor> &sddm,
std::vector<size_t> &pcgIts, float tol = 1e-6, double maxits = HUGE_VAL,
double maxtime = HUGE_VAL, bool verbose = false,
ApproxCholParams params = ApproxCholParams());
/**
* @brief
*
* @param solver
* @return
*/
template <typename Tv> inline SolverA<Tv> sddmWrapLap(const SolverA<Tv> solver);
} // namespace metric
#include "lapwrapper/lapwrappers.cpp"
#endif
| 6,238
|
C++
|
.h
| 226
| 25.132743
| 120
| 0.718223
|
metric-space-ai/metric
| 34
| 14
| 44
|
MPL-2.0
|
9/20/2024, 10:43:29 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| true
| false
|
1,531,689
|
graphalgs.hpp
|
metric-space-ai_metric/metric/utils/solver/helper/graphalgs.hpp
|
/*
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/.
Copyright (c) 2019 Panda Team
Copyright (c) 2019 Oleg Popov
*/
/*
Laplacians is a package containing graph algorithms, with an emphasis on tasks related to
spectral and algebraic graph theory. It contains (and will contain more) code for solving
systems of linear equations in graph Laplacians, low stretch spanning trees, sparsifiation,
clustering, local clustering, and optimization on graphs.
All graphs are represented by sparse adjacency matrices. This is both for speed, and because
our main concerns are algebraic tasks. It does not handle dynamic graphs. It would be very slow
to implement dynamic graphs this way.
https://github.com/danspielman/Laplacians.jl
*/
#ifndef _METRIC_UTILS_SOLVER_GRAPHGALS_HPP
#define _METRIC_UTILS_SOLVER_GRAPHGALS_HPP
#include "sparsecsc.hpp"
#include <blaze/Math.h>
#include <fstream>
#include <functional>
#include <iostream>
#include <random>
#include <tuple>
#include <utility>
#include <vector>
namespace metric {
template <typename T> class IJV;
/**
* @class Random
*
* @brief
*
*/
template <typename Tv> class Random {
public:
/**
* @brief Construct a new Random object
*
*/
Random() : gen(rd()) {}
/**
* @brief
*
* @return
*/
Tv rand0_1() { return std::generate_canonical<Tv, 8 * sizeof(Tv)>(gen); }
/**
* @brief
*
* @return
*/
Tv randn() { return rand0_1() * 3.4 - 1.7; }
/**
* @brief
*
* @param sz
* @return
*/
blaze::DynamicVector<Tv> randv(size_t sz)
{
blaze::DynamicVector<Tv> res(sz);
for (size_t i = 0; i < sz; i++)
res[i] = rand0_1();
return res;
}
private:
std::random_device rd;
std::mt19937 gen;
};
/**
* @brief clear main diagonal of input matrix
*
* @param A input matrix
* @return matrix with zeroes on main diagonal
*/
template <typename Tv>
inline blaze::CompressedMatrix<Tv, blaze::columnMajor>
ClearDiag(const blaze::CompressedMatrix<Tv, blaze::columnMajor> &A);
/**
* @brief
*
* @param A
* @return
*/
template <typename Tv> std::vector<size_t> flipIndex(const blaze::CompressedMatrix<Tv, blaze::columnMajor> &A);
/**
* @brief
*
* @param A
* @param diag_n
* @return
*/
template <typename Tv>
inline blaze::DynamicVector<Tv> diag(const blaze::CompressedMatrix<Tv, blaze::columnMajor> &A, size_t diag_n = 0);
/**
* @brief
*
* @param V
* @return
*/
template <typename Tv> blaze::CompressedMatrix<Tv, blaze::columnMajor> Diagonal(const blaze::DynamicVector<Tv> &V);
/**
* @brief Conjugate transpose
*
* @param A
* @return
*/
template <typename Tv>
inline blaze::CompressedMatrix<Tv, blaze::columnMajor>
adjoint(const blaze::CompressedMatrix<Tv, blaze::columnMajor> &A);
/**
* @brief Create an adjacency matrix and a diagonal vector from an SDDM-matrix.
* That is, from a Laplacian with added diagonal weights
*
* @param sddm
* @return
*/
template <typename Tv>
inline std::pair<blaze::CompressedMatrix<Tv, blaze::columnMajor>, blaze::DynamicVector<Tv>>
adj(const blaze::CompressedMatrix<Tv, blaze::columnMajor> &sddm);
/**
* @brief Add a new vertex to a with weights to the other vertices corresponding to diagonal surplus weight.
*
* @param a
* @param d
* @return
*/
template <typename Tv>
blaze::CompressedMatrix<Tv, blaze::columnMajor> extendMatrix(const blaze::CompressedMatrix<Tv, blaze::columnMajor> &a,
blaze::DynamicVector<Tv> d);
/**
* @brief
*
* @param A
* @param wise
* @return
*/
template <typename Tv>
inline blaze::DynamicVector<Tv> sum(const blaze::CompressedMatrix<Tv, blaze::columnMajor> &A, int wise = 1);
/**
* @brief vector index of matrix
*
* @param A
* @param idx1
* @param idx2
* @return
*/
template <typename Tv>
blaze::CompressedMatrix<Tv, blaze::columnMajor> index(const blaze::CompressedMatrix<Tv, blaze::columnMajor> &A,
const std::vector<size_t> &idx1, const std::vector<size_t> &idx2);
/**
* @brief vector index of matrix
*
* @param A
* @param idx1
* @param idx2
* @return
*/
template <typename Tv>
inline blaze::DynamicVector<Tv> index(const blaze::CompressedMatrix<Tv, blaze::columnMajor> &A,
const std::vector<size_t> &idx1, const size_t idx2);
/**
* @brief
*
* @param A
* @param idx1
* @param idx2
* @return
*/
template <typename Tv>
inline blaze::DynamicVector<Tv> index(const blaze::CompressedMatrix<Tv, blaze::columnMajor> &A, const size_t idx1,
const std::vector<size_t> &idx2);
/**
* @brief
*
* @param A
* @param idx
* @return
*/
template <typename Tv>
inline blaze::DynamicVector<Tv> index(const blaze::CompressedMatrix<Tv, blaze::columnMajor> &A,
const std::vector<size_t> &idx);
/**
* @brief vector index of vector
*
* @param vec
* @param idx
* @return
*/
template <typename Tv>
inline blaze::DynamicVector<Tv> index(const blaze::DynamicVector<Tv> &vec, const std::vector<size_t> &idx);
/**
* @brief
*
* @param vout [out[
* @param idx
* @param vin
*/
template <typename Tv>
inline void index(blaze::DynamicVector<Tv> &vout, const std::vector<size_t> &idx, const blaze::DynamicVector<Tv> &vin);
/**
* @brief
*
* @param mout[out]
* @param idx
* @param idx2
* @param vin
*/
template <typename Tv>
void index(blaze::CompressedMatrix<Tv, blaze::columnMajor> &mout, const std::vector<size_t> &idx, size_t idx2,
const blaze::DynamicVector<Tv> &vin);
/**
* @brief
*
* @param vect
* @param idx
*/
template <typename Tv>
blaze::DynamicVector<Tv> indexbool(const blaze::DynamicVector<Tv> &vect, const std::vector<bool> &idx);
/**
* @brief
*
* @param vect
* @param idx
* @return
*/
inline std::vector<size_t> indexbool(const std::vector<size_t> &vect, const std::vector<bool> &idx);
/**
* @brief
*
* @param a
* @return
*/
template <typename Tv> inline bool testZeroDiag(const Tv &a);
/**
* @brief
*
* @param v
*/
template <typename Tv> inline blaze::DynamicVector<Tv> dynvec(const std::vector<Tv> &v);
/**
* @brief
*
* @param compvec[out]
* @return
*/
const std::vector<std::vector<size_t>> vecToComps(std::vector<size_t> &compvec);
/**
* @brief
*
* @param mat
* @return
*/
template <typename Tv>
std::tuple<std::vector<size_t>, std::vector<size_t>, blaze::DynamicVector<Tv>>
findnz(const blaze::CompressedMatrix<Tv, blaze::columnMajor> &mat);
/**
* @brief Returns vector where comp[i]=component number
*
* @param mat
* @return
*/
template <typename Tv> std::vector<size_t> components(const blaze::CompressedMatrix<Tv, blaze::columnMajor> &mat);
/**
* @brief
*
* @param mat
* @return
*/
template <typename Tv> std::vector<size_t> components(const SparseMatrixCSC<Tv> &mat);
/**
* @brief Kronecker product
* for matrices: https://en.wikipedia.org/wiki/Kronecker_product
*
* @param A
* @param B
* @return
*/
template <typename Tv>
blaze::CompressedMatrix<Tv, blaze::columnMajor> kron(const blaze::CompressedMatrix<Tv, blaze::columnMajor> &A,
const blaze::CompressedMatrix<Tv, blaze::columnMajor> &B);
/**
* @brief Kronecker product
* for vectors: https://en.wikipedia.org/wiki/Kronecker_product
*
* @param A
* @param B
* @return
*/
template <typename Tv>
inline blaze::DynamicVector<Tv> kron(const blaze::DynamicVector<Tv> &A, const blaze::DynamicVector<Tv> &B);
/**
* @brief Returns the diagonal weighted degree matrix(as a sparse matrix) of a graph
*
* @param A
* @return
*/
template <typename Tv>
inline blaze::CompressedMatrix<Tv, blaze::columnMajor>
diagmat(const blaze::CompressedMatrix<Tv, blaze::columnMajor> &A);
/**
* @brief
*
* @param A
* @param n
* @return
*/
template <typename Tv>
inline blaze::CompressedMatrix<Tv, blaze::columnMajor> pow(const blaze::CompressedMatrix<Tv, blaze::columnMajor> &A,
const int n);
/**
* @brief generates vector with values of [start...end)
*
* @param start
* @param end
* @return
*/
inline std::vector<size_t> collect(size_t start, size_t end);
/**
* @brief
*
* @param I
* @param J
* @param V
* @return
*/
template <typename Tv>
inline std::vector<size_t> sortedIndices(const std::vector<size_t> &I, const std::vector<size_t> &J,
const blaze::DynamicVector<Tv> &V);
/**
* @brief
*
* @param I
* @param J
* @param V
* @param m
* @param n
* @param sort
* @return
*/
template <typename Tv>
blaze::CompressedMatrix<Tv, blaze::columnMajor> sparse(const std::vector<size_t> &I, const std::vector<size_t> &J,
const blaze::DynamicVector<Tv> &V, size_t m, size_t n,
bool sort = false);
/**
* @brief
*
* @param A
* @param k
* @return
*/
template <typename Tv>
inline blaze::CompressedMatrix<Tv, blaze::columnMajor> power(const blaze::CompressedMatrix<Tv, blaze::columnMajor> &A,
const int k);
/**
* @brief Returns true if graph is connected.
*
* @param mat
* @return true if graph is connected.
*/
template <typename Tv> inline bool isConnected(const blaze::CompressedMatrix<Tv, blaze::columnMajor> &mat);
/**
* @brief
*
* @param A
* @param wise
* @return
*/
template <typename Tv>
std::pair<Tv, size_t> findmax(const blaze::CompressedMatrix<Tv, blaze::columnMajor> &A, int wise = 1);
/**
* @brief
*
* @param v
* @return
*/
template <typename Tv> std::pair<Tv, size_t> findmax(const blaze::DynamicVector<Tv> &v);
/**
* @brief
*
* @param A
* @return
*/
template <typename Tv> inline Tv mean(const blaze::CompressedMatrix<Tv, blaze::columnMajor> &A);
/**
* @brief
*
* @param v
* @return
*/
template <typename Tv> inline Tv mean(blaze::DynamicVector<Tv> v);
/**
* @brief Returns the upper triangle of M starting from the kth superdiagonal.
*
* @param A
* @param k
* @return
*/
template <typename Tv>
blaze::CompressedMatrix<Tv, blaze::columnMajor> triu(const blaze::CompressedMatrix<Tv, blaze::columnMajor> &A,
size_t k = 0);
/**
* @brief
*
* @param mat
* @return
*/
template <typename Tv>
blaze::CompressedMatrix<Tv, blaze::columnMajor>
wtedEdgeVertexMat(const blaze::CompressedMatrix<Tv, blaze::columnMajor> &mat);
/**
* @brief
*
* @param x
* @param n
* @return
*/
inline size_t keyMap(size_t x, size_t n);
/**
* @brief Create a Laplacian matrix from an adjacency matrix. We might want to do this differently, say by enforcing
* symmetry
*
* @param A
* @return
*/
template <typename Tv>
blaze::CompressedMatrix<Tv, blaze::columnMajor> lap(blaze::CompressedMatrix<Tv, blaze::columnMajor> A);
/**
* @brief lap function analog. Create a Laplacian matrix from an adjacency matrix.
* If the input looks like a Laplacian, throw a warning and convert it.
*
* @param a
* @return
*/
template <typename Tv>
blaze::CompressedMatrix<Tv, blaze::columnMajor> forceLap(const blaze::CompressedMatrix<Tv, blaze::columnMajor> &a);
/**
* @brief
*
* @param n
* @return
*/
template <typename Tv> IJV<Tv> path_graph_ijv(size_t n);
/**
* @brief
*
* @param b
* @param a
* @return
*/
template <typename Tv> IJV<Tv> product_graph(IJV<Tv> b, IJV<Tv> a);
/**
* @brief
*
* @param n
* @param m
* @param isotropy
* @return
*/
template <typename Tv> IJV<Tv> grid2_ijv(size_t n, size_t m, Tv isotropy = 1);
/**
* @brief
*
* @param n
* @return
*/
template <typename Tv> inline IJV<Tv> grid2_ijv(size_t n);
/**
* @brief
*
* @param n
* @param m
* @param isotropy
* @return
*/
template <typename Tv> blaze::CompressedMatrix<Tv, blaze::columnMajor> grid2(size_t n, size_t m, Tv isotropy = 1);
/**
* @brief
*
* @param n
* @return
*/
template <typename Tv> inline blaze::CompressedMatrix<Tv, blaze::columnMajor> grid2(size_t n);
/**
* @brief
*
* @param A
* @param FileName
*/
template <typename Tv> void matrixToFile(blaze::CompressedMatrix<Tv, blaze::columnMajor> A, std::string FileName);
} // namespace metric
#include "graphalgs/graphalgs.cpp"
#endif
| 11,940
|
C++
|
.h
| 496
| 21.905242
| 119
| 0.697076
|
metric-space-ai/metric
| 34
| 14
| 44
|
MPL-2.0
|
9/20/2024, 10:43:29 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| true
| false
|
1,531,690
|
ijvstruct.hpp
|
metric-space-ai_metric/metric/utils/solver/helper/ijvstruct.hpp
|
/*
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/.
Copyright (c) 2019 Panda Team
Copyright (c) 2019 Oleg Popov
*/
/*
Laplacians is a package containing graph algorithms, with an emphasis on tasks related to
spectral and algebraic graph theory. It contains (and will contain more) code for solving
systems of linear equations in graph Laplacians, low stretch spanning trees, sparsifiation,
clustering, local clustering, and optimization on graphs.
All graphs are represented by sparse adjacency matrices. This is both for speed, and because
our main concerns are algebraic tasks. It does not handle dynamic graphs. It would be very slow
to implement dynamic graphs this way.
https://github.com/danspielman/Laplacians.jl
*/
#ifndef _METRIC_UTILS_SOLVER_IJVSTRUCT_HPP
#define _METRIC_UTILS_SOLVER_IJVSTRUCT_HPP
#include "graphalgs.hpp"
#include "sparsecsc.hpp"
#include <blaze/Math.h>
namespace metric {
/**
* @class IJV
*
* @brief
*
*/
template <typename Tv> class IJV {
public:
/**
* @brief Construct a new IJV object
*
*/
IJV() : n(0), nnz(0), i(0), j(0), v(0) {}
/**
* @brief Construct a new IJV object
*
* @param a
*/
IJV(const IJV &a)
{
n = a.n;
nnz = a.nnz;
i = a.i;
j = a.j;
v = a.v;
}
/**
* @brief Construct a new IJV object
*
* @param an
* @param annz
* @param ai
* @param aj
* @param av
*/
IJV(const size_t an, const size_t annz, const std::vector<size_t> &ai, const std::vector<size_t> &aj,
const blaze::DynamicVector<Tv> &av)
{
n = an;
nnz = annz;
i = ai;
j = aj;
v = av;
}
/**
* @brief Construct a new IJV object
*
* @param an
* @param annz
* @param ai
* @param aj
* @param av
*/
IJV(const size_t an, const size_t annz, const blaze::DynamicVector<size_t> &ai,
const blaze::DynamicVector<size_t> &aj, const blaze::DynamicVector<Tv> &av)
{
n = an;
nnz = annz;
i.insert(i.begin(), ai.begin(), ai.end());
j.insert(j.begin(), aj.begin(), aj.end());
v = av;
}
/**
* @brief Construct a new IJV object
*
* @param mat
*/
IJV(const blaze::CompressedMatrix<Tv, blaze::columnMajor> &mat);
/**
* @brief Construct a new IJV object
*
* @param cscm
*/
IJV(const SparseMatrixCSC<Tv> &cscm);
/**
* @brief
*
* @param a
* @return
*/
const IJV &operator=(const IJV &a)
{
n = a.n;
nnz = a.nnz;
i = a.i;
j = a.j;
v = a.v;
return *this;
}
/**
* @brief
*
* @param b
* @return
*/
IJV operator+(const IJV &b) const;
/**
* @brief
*
* @param b
* @return
*/
bool operator==(const IJV &b) const
{
bool res = n == b.n && nnz == b.nnz && i == b.i && j == b.j && v == b.v;
return res;
}
/**
* @brief
*
* @param x
* @return
*/
IJV operator*(const Tv x) const
{
IJV m;
m.n = n;
m.nnz = nnz;
m.i = i;
m.j = j;
m.v = v * x;
return m;
}
/**
* @brief Convert to blaze::CompressedMatrix
*
* @return
*/
blaze::CompressedMatrix<Tv, blaze::columnMajor> toCompressedMatrix() const { return sparse(i, j, v, n, n, true); }
/**
* @brief
*
* @param ijvn
*/
void dump_ijv(int ijvn) const;
/**
* @brief
*
* @return
*/
std::vector<size_t> sortedIndices() const { return metric::sortedIndices(i, j, v); }
/**
* @brief
*
*/
void sortByCol();
std::size_t n; // dimension
std::size_t nnz; // number of nonzero elements
std::vector<std::size_t> i; // row
std::vector<std::size_t> j; // col
blaze::DynamicVector<Tv> v; // nonzero elements
};
/**
* @brief
*
* @param x
* @param ijv
* @return
*/
template <typename Tv> IJV<Tv> operator*(const Tv x, const IJV<Tv> &ijv) { return ijv * x; }
/**
* @brief
*
* @param a
* @return
*/
template <typename Tv> const std::size_t nnz(const IJV<Tv> &a) { return a.nnz; }
/**
* @brief convert IJV to SparseMatrixCSC
*
* @param ijv
* @return
*/
template <typename Tv> SparseMatrixCSC<Tv> sparseCSC(const IJV<Tv> &ijv);
/**
* @brief
*
* @param ijv
* @return
*/
template <typename Tv> blaze::CompressedMatrix<Tv, blaze::columnMajor> sparse(const IJV<Tv> &ijv)
{
return std::move(ijv.toCompressedMatrix());
}
/**
* @brief
*
* @param ijv
* @return
*/
template <typename Tv> IJV<Tv> compress(const IJV<Tv> &ijv) { return IJV<Tv>(sparseCSC(ijv)); }
/**
* @brief
*
* @param ijv
* @return
*/
template <typename Tv> IJV<Tv> transpose(const IJV<Tv> &ijv) { return IJV<Tv>(ijv.n, ijv.nnz, ijv.j, ijv.i, ijv.v); }
} // namespace metric
#include "ijvstruct/ijvstruct.cpp"
#endif
| 4,631
|
C++
|
.h
| 224
| 18.214286
| 117
| 0.644165
|
metric-space-ai/metric
| 34
| 14
| 44
|
MPL-2.0
|
9/20/2024, 10:43:29 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| true
| false
|
1,531,692
|
Network.h
|
metric-space-ai_metric/metric/utils/dnn/Network.h
|
#ifndef NETWORK_H_
#define NETWORK_H_
#include <chrono>
#include <fstream>
#include <random>
#include <stdexcept>
#include <utility>
#include <vector>
#include <blaze/Math.h>
#include <cereal/archives/binary.hpp>
#include <cereal/types/map.hpp>
#include <cereal/types/string.hpp>
#include <cereal/types/vector.hpp>
#include "Callback.h"
#include "Layer.h"
#include "Output.h"
#include "Utils/Random.h"
#include "Initializer/NormalInitializer.h"
#include "Initializer/ZeroInitializer.h"
namespace metric::dnn {
///
/// \defgroup Network Neural Network Model
///
///
/// \ingroup Network
///
/// This class represents a neural network model that typically consists of a
/// number of hidden layers and an output layer. It provides functions for
/// network building, model fitting, and prediction, etc.
///
template <typename Scalar> class Network {
protected:
using Matrix = blaze::DynamicMatrix<Scalar>;
private:
std::mt19937 randomEngine; // Reference to the std::mt19937 provided by the user,
std::shared_ptr<Output<Scalar>> outputLayer; // The output layer
std::shared_ptr<Callback<Scalar>> callback; // Points to user-provided callback function,
std::shared_ptr<Optimizer<Scalar>> opt;
std::map<std::string, std::shared_ptr<Initializer<Scalar>>> initializers;
/* Check dimensions of layers */
void check_unit_sizes() const
{
const int nlayer = num_layers();
if (nlayer <= 1) {
return;
}
for (int i = 1; i < nlayer; i++) {
if (layers[i]->getInputSize() != layers[i - 1]->getOutputSize()) {
throw std::invalid_argument("Unit sizes do not match");
}
}
}
// Let each layer compute its output
void forward(const Matrix &input)
{
const int nlayer = num_layers();
if (nlayer <= 0) {
return;
}
// First layer
if (input.columns() != layers[0]->getInputSize()) {
throw std::invalid_argument("Input data have incorrect dimension");
}
layers[0]->forward(input);
// The following layers
for (int i = 1; i < nlayer; i++) {
layers[i]->forward(layers[i - 1]->output());
}
}
// Let each layer compute its gradients of the parameters
// target has two versions: Matrix and RowVectorXi
// The RowVectorXi version is used in classification problems where each
// element is a class label
template <typename TargetType> void backprop(const Matrix &input, const TargetType &target)
{
const int nlayer = num_layers();
if (nlayer <= 0) {
return;
}
auto firstLayer = layers[0];
auto lastLayer = layers[nlayer - 1];
// Let output layer compute back-propagation data
outputLayer->check_target_data(target);
outputLayer->evaluate(lastLayer->output(), target);
// If there is only one hidden layer, "prev_layer_data" will be the input data
if (nlayer == 1) {
firstLayer->backprop(input, outputLayer->backprop_data());
return;
}
// Compute gradients for the last hidden layer
lastLayer->backprop(layers[nlayer - 2]->output(), outputLayer->backprop_data());
// Compute gradients for all the hidden layers except for the first one and the last one
for (int i = nlayer - 2; i > 0; i--) {
layers[i]->backprop(layers[i - 1]->output(), layers[i + 1]->backprop_data());
}
// Compute gradients for the first layer
firstLayer->backprop(input, layers[1]->backprop_data());
}
// Update parameters
void update()
{
const int nlayer = num_layers();
if (nlayer <= 0) {
return;
}
for (int i = 0; i < nlayer; i++) {
layers[i]->update(*opt);
}
}
public:
/* Layers pointers */
std::vector<std::shared_ptr<Layer<Scalar>>> layers;
/* Default constructor that creates an empty neural network */
Network() : randomEngine{std::random_device()()}, outputLayer(NULL)
{
setDefaultCallback();
setInitializer("normal", dnn::NormalInitializer<Scalar>(0, 0.01, randomEngine));
setInitializer("zero", dnn::ZeroInitializer<Scalar>());
}
Network(const std::string &jsonString) : Network() { constructFromJsonString(jsonString); }
void constructFromJsonString(const std::string &jsonString)
{
/* Parse json */
auto json = nlohmann::json::parse(jsonString);
/* Construct layers */
layers.clear();
for (auto i = 0; i < json.size() - 1; ++i) {
auto layerJson = json[std::to_string(i)];
auto activation = layerJson["activation"].get<std::string>();
auto type = layerJson["type"].get<std::string>();
if (type == "FullyConnected") {
if (activation == "Identity") {
addLayer(FullyConnected<Scalar, Identity<Scalar>>(layerJson));
} else if (activation == "ReLU") {
addLayer(FullyConnected<Scalar, ReLU<Scalar>>(layerJson));
} else if (activation == "Sigmoid") {
addLayer(FullyConnected<Scalar, Sigmoid<Scalar>>(layerJson));
//} else if (activation == "Softmax") {
// addLayer(FullyConnected<Scalar, Softmax<Scalar>>(layerJson));
}
} else if (type == "Conv2d") {
if (activation == "Identity") {
addLayer(Conv2d<Scalar, Identity<Scalar>>(layerJson));
} else if (activation == "ReLU") {
addLayer(Conv2d<Scalar, ReLU<Scalar>>(layerJson));
} else if (activation == "Sigmoid") {
addLayer(Conv2d<Scalar, Sigmoid<Scalar>>(layerJson));
}
} else if (type == "Conv2dTranspose") {
if (activation == "Identity") {
addLayer(Conv2dTranspose<Scalar, Identity<Scalar>>(layerJson));
} else if (activation == "ReLU") {
addLayer(Conv2dTranspose<Scalar, ReLU<Scalar>>(layerJson));
} else if (activation == "Sigmoid") {
addLayer(Conv2dTranspose<Scalar, Sigmoid<Scalar>>(layerJson));
}
}
}
/* Create train part */
auto trainJson = json["train"];
/* Loss */
auto loss = trainJson["loss"].get<std::string>();
if (loss == "RegressionMSE") {
setOutput(RegressionMSE<Scalar>());
}
/* Optimizer */
auto optimizerJson = trainJson["optimizer"];
auto optimizerType = optimizerJson["type"].get<std::string>();
auto learningRate = optimizerJson["learningRate"].get<Scalar>();
auto eps = optimizerJson["eps"].get<Scalar>();
auto decay = optimizerJson["decay"].get<Scalar>();
if (optimizerType == "RMSProp") {
RMSProp<Scalar> optimizer;
optimizer.learningRate = learningRate;
optimizer.m_eps = eps;
optimizer.m_decay = decay;
setOptimizer(optimizer);
}
/* Init layers */
init();
}
~Network() = default;
nlohmann::json toJson() const
{
/* Layers */
nlohmann::json json;
for (auto i = 0; i < layers.size(); ++i) {
json[std::to_string(i)] = layers[i]->toJson();
}
/* Loss */
json["train"]["loss"] = outputLayer->getType();
/* Optimizer */
json["train"]["optimizer"] = opt->toJson();
return json;
}
void save(const std::string filename) const
{
std::string jsonString = toJson().dump();
std::map<size_t, std::vector<std::vector<Scalar>>> layersParameters;
for (auto i = 0; i < layers.size(); ++i) {
layersParameters[i] = layers[i]->getParameters();
}
std::ofstream file(filename);
cereal::BinaryOutputArchive boa(file);
boa(jsonString, layersParameters);
}
void save(std::stringstream &ss) const
{
std::string jsonString = toJson().dump();
std::map<size_t, std::vector<std::vector<Scalar>>> layersParameters;
for (auto i = 0; i < layers.size(); ++i) {
layersParameters[i] = layers[i]->getParameters();
}
cereal::BinaryOutputArchive boa(ss);
boa(jsonString, layersParameters);
}
void load(const std::string filepath)
{
std::ifstream file(filepath);
cereal::BinaryInputArchive bia(file);
std::string jsonString;
std::map<size_t, std::vector<std::vector<Scalar>>> layersParameters;
bia(jsonString, layersParameters);
constructFromJsonString(jsonString);
for (auto &e : layersParameters) {
layers[e.first]->setParameters(e.second);
}
}
void load(std::stringstream &ss)
{
cereal::BinaryInputArchive bia(ss);
std::string jsonString;
std::map<size_t, std::vector<std::vector<Scalar>>> layersParameters;
bia(jsonString, layersParameters);
constructFromJsonString(jsonString);
for (auto &e : layersParameters) {
layers[e.first]->setParameters(e.second);
}
}
///
/// Add a hidden layer to the neural network
///
/// \param layer A pointer to a Layer object, typically constructed from
/// layer classes such as FullyConnected and Convolutional.
/// **NOTE**: the pointer will be handled and freed by the
/// network object, so do not delete it manually.
///
template <typename T> void addLayer(const T &layer) { layers.push_back(std::make_shared<T>(layer)); }
///
/// Set the output layer of the neural network
///
/// \param output A pointer to an Output object, typically constructed from
/// output layer classes such as RegressionMSE and MultiClassEntropy.
/// **NOTE**: the pointer will be handled and freed by the
/// network object, so do not delete it manually.
///
template <typename T> void setOutput(const T &output) { outputLayer = std::make_shared<T>(output); }
template <typename T> void setOptimizer(const T &optimizer) { opt = std::make_shared<T>(optimizer); }
///
/// Number of hidden layers in the network
///
int num_layers() const { return layers.size(); }
///
/// Get the list of hidden layers of the network
///
/*std::vector<const std::shared_ptr<Layer>> get_layers() const
{
const int nlayer = num_layers();
std::vector<const std::shared_ptr<Layer>> layers(nlayer);
std::copy(m_layers.begin(), m_layers.end(), layers.begin());
return layers;
}*/
///
/// Get the output layer
///
const Output<Scalar> *get_output() const { return outputLayer.get(); }
///
/// Set the callback function that can be called during model fitting
///
/// \param callback A user-provided callback function object that inherits
/// from the default Callback class.
///
template <typename T> void setCallback(const T &_callback) { callback = std::make_shared<T>(_callback); }
///
/// Set the default silent callback function
///
void setDefaultCallback() { setCallback(Callback<Scalar>()); }
void setRandomEngineSeed(const unsigned int seed) { randomEngine.seed(seed); }
template <typename T> void setInitializer(const std::string name, const T &initializer)
{
initializers[name] = std::make_shared<T>(initializer);
}
///
/// Initialize layer parameters in the network using normal distribution
///
/// \param mu Mean of the normal distribution.
/// \param sigma Standard deviation of the normal distribution.
/// \param seed Set the random seed of the %std::mt19937 if `seed > 0`, otherwise
/// use the current random state.
///
void init(const Scalar &mu = Scalar(0), const Scalar &sigma = Scalar(0.01), int seed = -1)
{
check_unit_sizes();
if (seed > 0) {
setRandomEngineSeed(seed);
}
const int nlayer = num_layers();
for (auto layer : layers) {
layer->init(this->initializers);
}
}
///
/// Get the serialized layer parameters
///
std::vector<std::vector<Scalar>> get_parameters() const
{
const int nlayer = num_layers();
std::vector<std::vector<Scalar>> res;
res.reserve(nlayer);
for (int i = 0; i < nlayer; i++) {
res.push_back(layers[i]->get_parameters());
}
return res;
}
///
/// Set the layer parameters
///
/// \param param Serialized layer parameters
///
void set_parameters(const std::vector<std::vector<Scalar>> ¶m)
{
const int nlayer = num_layers();
if (static_cast<int>(param.size()) != nlayer) {
throw std::invalid_argument("Parameter size does not match");
}
for (int i = 0; i < nlayer; i++) {
layers[i]->set_parameters(param[i]);
}
}
///
/// Get the serialized derivatives of layer parameters
///
std::vector<std::vector<Scalar>> get_derivatives() const
{
const int nlayer = num_layers();
std::vector<std::vector<Scalar>> res;
res.reserve(nlayer);
for (int i = 0; i < nlayer; i++) {
res.push_back(layers[i]->get_derivatives());
}
return res;
}
/*
///
/// Debugging tool to check parameter gradients
///
template <typename TargetType>
void check_gradient(const Matrix& input, const TargetType& target, int npoints,
int seed = -1)
{
if (seed > 0)
{
randomEngine.seed(seed);
}
this->forward(input);
this->backprop(input, target);
std::vector< std::vector<Scalar>> param = this->get_parameters();
std::vector< std::vector<Scalar>> deriv = this->get_derivatives();
const Scalar eps = 1e-5;
const int nlayer = deriv.size();
for (int i = 0; i < npoints; i++)
{
// Randomly select a layer
const int layer_id = int(randomEngine.rand() * nlayer);
// Randomly pick a parameter, note that some layers may have no parameters
const int nparam = deriv[layer_id].size();
if (nparam < 1)
{
continue;
}
const int param_id = int(randomEngine.rand() * nparam);
// Turbulate the parameter a little bit
const Scalar old = param[layer_id][param_id];
param[layer_id][param_id] -= eps;
this->set_parameters(param);
this->forward(input);
this->backprop(input, target);
const Scalar loss_pre = outputLayer->loss();
param[layer_id][param_id] += eps * 2;
this->set_parameters(param);
this->forward(input);
this->backprop(input, target);
const Scalar loss_post = outputLayer->loss();
const Scalar deriv_est = (loss_post - loss_pre) / eps / 2;
std::cout << "[layer " << layer_id << ", param " << param_id <<
"] deriv = " << deriv[layer_id][param_id] << ", est = " << deriv_est <<
", diff = " << deriv_est - deriv[layer_id][param_id] << std::endl;
param[layer_id][param_id] = old;
}
// Restore original parameters
this->set_parameters(param);
}
*/
///
/// Fit the model based on the given data
///
/// \param x The predictors. Each row is an observation.
/// \param y The response variable. Each row is an observation.
/// \param batch_size Mini-batch size.
/// \param epoch Number of epochs of training.
/// \param seed Set the random seed of the %std::mt19937 if `seed > 0`, otherwise
/// use the current random state.
///
template <typename DerivedX, typename DerivedY>
bool fit(const DerivedX &x, const DerivedY &y, int batch_size, int epoch, int seed = -1)
{
// We do not directly use PlainObjectX since it may be row-majored if x is passed as mat.transpose()
// We want to force XType and YType to be row-majored
const int nlayer = num_layers();
if (nlayer <= 0) {
return false;
}
// Reset optimizer
opt->reset();
// Create shuffled mini-batches
if (seed > 0) {
randomEngine.seed(seed);
}
std::vector<DerivedX> x_batches;
std::vector<DerivedY> y_batches;
const int nbatch = internal::create_shuffled_batches(x, y, batch_size, randomEngine, x_batches, y_batches);
// Set up callback parameters
callback->batchesNumber = nbatch;
callback->epochsNumber = epoch;
// Iterations on the whole data set
for (int k = 0; k < epoch; k++) {
callback->epochId = k;
callback->preTrainingEpoch(this);
// Train on each mini-batch
for (int i = 0; i < nbatch; i++) {
callback->batchId = i;
callback->preTrainingBatch(this, x_batches[i], y_batches[i]);
this->forward(x_batches[i]);
this->backprop(x_batches[i], y_batches[i]);
this->update();
callback->postTrainingBatch(this, x_batches[i], y_batches[i]);
}
callback->postTrainingEpoch(this);
}
return true;
}
///
/// Use the fitted model to make predictions
///
/// \param x The predictors. Each row is an observation.
///
Matrix predict(const Matrix &x)
{
const int nlayer = num_layers();
if (nlayer <= 0) {
return Matrix();
}
this->forward(x);
return layers[nlayer - 1]->output();
}
};
} // namespace metric::dnn
#endif /* NETWORK_H_ */
| 15,877
|
C++
|
.h
| 468
| 30.636752
| 109
| 0.673181
|
metric-space-ai/metric
| 34
| 14
| 44
|
MPL-2.0
|
9/20/2024, 10:43:29 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,531,693
|
dnn-includes.h
|
metric-space-ai_metric/metric/utils/dnn/dnn-includes.h
|
#ifndef DNN_INCLUDES_H_
#define DNN_INCLUDES_H_
#include <blaze/Blaze.h>
#include "Layer.h"
#include "Layer/Conv2d-transpose.h"
#include "Layer/Conv2d.h"
#include "Layer/FullyConnected.h"
#include "Layer/MaxPooling.h"
#include "Activation/Identity.h"
#include "Activation/ReLU.h"
#include "Activation/Sigmoid.h"
//#include "Activation/Softmax.h"
#include "Output.h"
#include "Output/RegressionMSE.h"
//#include "Output/BinaryClassEntropy.h"
#include "Output/MultiClassEntropy.h"
#include "Optimizer.h"
#include "Optimizer/SGD.h"
//#include "Optimizer/AdaGrad.h"
#include "Optimizer/RMSProp.h"
#include "Callback.h"
#include "Callback/VerboseCallback.h"
#include "Network.h"
#endif /* dnn_H_ */
| 702
|
C++
|
.h
| 24
| 27.916667
| 40
| 0.779104
|
metric-space-ai/metric
| 34
| 14
| 44
|
MPL-2.0
|
9/20/2024, 10:43:29 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,531,694
|
Layer.h
|
metric-space-ai_metric/metric/utils/dnn/Layer.h
|
#ifndef LAYER_H_
#define LAYER_H_
#include <random>
#include <vector>
#include <blaze/Math.h>
#include <nlohmann/json.hpp>
#include "Initializer.h"
#include "Optimizer.h"
namespace metric::dnn {
///
/// \defgroup Layers Hidden Layers
///
///
/// \ingroup Layers
///
/// The interface of hidden layers in a neural network. It defines some common
/// operations of hidden layers such as initialization, forward and backward
/// propogation, and also functions to get/set parameters of the layer.
///
template <typename Scalar> class Layer {
public:
using Matrix = blaze::DynamicMatrix<Scalar>;
size_t inputSize; // Size of input units
size_t outputSize; // Size of output units
Layer(){};
///
/// Constructor
///
/// \param inputSize Number of input units of this hidden Layer. It must be
/// equal to the number of output units of the previous layer.
/// \param outputSize Number of output units of this hidden layer. It must be
/// equal to the number of input units of the next layer.
///
Layer(const size_t inputSize, const size_t outputSize) : inputSize(inputSize), outputSize(outputSize) {}
///
/// Virtual destructor
///
virtual ~Layer() {}
Layer(const nlohmann::json &json) {}
virtual nlohmann::json toJson()
{
nlohmann::json json = {{"inputSize", inputSize}, {"outputSize", outputSize}};
return json;
}
///
/// Get the number of input units of this hidden layer.
///
size_t getInputSize() const { return inputSize; }
///
/// Get the number of output units of this hidden layer.
///
size_t getOutputSize() const { return outputSize; }
virtual std::vector<size_t> getOutputShape() const = 0;
virtual void init(const std::map<std::string, std::shared_ptr<Initializer<Scalar>>> initializer) = 0;
///
/// Initialize layer parameters using \f$N(\mu, \sigma^2)\f$ distribution
///
/// \param mu Mean of the normal distribution.
/// \param sigma Standard deviation of the normal distribution.
/// \param rng The random number generator of type std::mt19937.
virtual void init(const Scalar &mu, const Scalar &sigma, std::mt19937 &rng) = 0;
// virtual void initConstant(const Scalar weightsValue, const Scalar biasesValue) = 0;
///
/// Compute the output of this layer
///
/// The purpose of this function is to let the hidden layer compute information
/// that will be passed to the next layer as the input. The concrete behavior
/// of this function is subject to the implementation, with the only
/// requirement that after calling this function, the Layer::output() member
/// function will return a reference to the output values.
///
/// \param prev_layer_data The output of previous layer, which is also the
/// input of this layer. `prev_layer_data` should have
/// `getInputSize` rows as in the constructor, and each
/// column of `prev_layer_data` is an observation.
///
virtual void forward(const Matrix &prev_layer_data) = 0;
///
/// Obtain the output values of this layer
///
/// This function is assumed to be called after Layer::forward() in each iteration.
/// The output are the values of output hidden units after applying activation function.
/// The main usage of this function is to provide the `prev_layer_data` parameter
/// in Layer::forward() of the next layer.
///
/// \return A reference to the matrix that contains the output values. The
/// matrix should have `getOutputSize` rows as in the constructor,
/// and have number of columns equal to that of `prev_layer_data` in the
/// Layer::forward() function. Each column represents an observation.
///
virtual const Matrix &output() const = 0;
///
/// Compute the gradients of parameters and input units using back-propagation
///
/// The purpose of this function is to compute the gradient of input units,
/// which can be retrieved by Layer::backprop_data(), and the gradient of
/// layer parameters, which could later be used by the Layer::update() function.
///
/// \param prev_layer_data The output of previous layer, which is also the
/// input of this layer. `prev_layer_data` should have
/// `getInputSize` rows as in the constructor, and each
/// column of `prev_layer_data` is an observation.
/// \param next_layer_data The gradients of the input units of the next layer,
/// which is also the gradients of the output units of
/// this layer. `next_layer_data` should have
/// `getOutputSize` rows as in the constructor, and the same
/// number of columns as `prev_layer_data`.
///
virtual void backprop(const Matrix &prev_layer_data, const Matrix &next_layer_data) = 0;
///
/// Obtain the gradient of input units of this layer
///
/// This function provides the `next_layer_data` parameter in Layer::backprop()
/// of the previous layer, since the derivative of the input of this layer is also the derivative
/// of the output of previous layer.
///
virtual const Matrix &backprop_data() const = 0;
///
/// Update parameters after back-propagation
///
/// \param opt The optimization algorithm to be used. See the Optimizer class.
///
virtual void update(Optimizer<Scalar> &opt) = 0;
///
/// Get serialized values of parameters
///
virtual std::vector<std::vector<Scalar>> getParameters() const = 0;
///
/// Set the values of layer parameters from serialized data
///
virtual void setParameters(const std::vector<std::vector<Scalar>> ¶m){};
///
/// Get serialized values of the gradient of parameters
///
virtual std::vector<Scalar> get_derivatives() const = 0;
};
} // namespace metric::dnn
#endif /* LAYER_H_ */
| 5,840
|
C++
|
.h
| 138
| 40.282609
| 105
| 0.687863
|
metric-space-ai/metric
| 34
| 14
| 44
|
MPL-2.0
|
9/20/2024, 10:43:29 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,531,695
|
Initializer.h
|
metric-space-ai_metric/metric/utils/dnn/Initializer.h
|
#ifndef INITIALIZER_H
#define INITIALIZER_H
#include <blaze/Math.h>
namespace metric::dnn {
template <typename Scalar> class Initializer {
protected:
using ColumnMatrix = blaze::DynamicMatrix<Scalar, blaze::columnMajor>;
using RowVector = blaze::DynamicVector<Scalar, blaze::rowVector>;
public:
virtual void init(const size_t rows, const size_t columns, ColumnMatrix &matrix) = 0;
virtual void init(const size_t size, RowVector &matrix) = 0;
};
} // namespace metric::dnn
#endif // INITIALIZER_H
| 508
|
C++
|
.h
| 14
| 34.428571
| 86
| 0.771429
|
metric-space-ai/metric
| 34
| 14
| 44
|
MPL-2.0
|
9/20/2024, 10:43:29 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,531,696
|
Optimizer.h
|
metric-space-ai_metric/metric/utils/dnn/Optimizer.h
|
#ifndef OPTIMIZER_H_
#define OPTIMIZER_H_
#include <blaze/Math.h>
namespace metric {
namespace dnn {
///
/// \defgroup Optimizers Optimization Algorithms
///
///
/// \ingroup Optimizers
///
/// The interface of optimization algorithms
///
template <typename Scalar> class Optimizer {
protected:
using AlignedMapVec = blaze::CustomVector<Scalar, blaze::aligned, blaze::unpadded>;
using ConstAlignedMapVec = const blaze::CustomVector<Scalar, blaze::aligned, blaze::unpadded>;
using RowVector = blaze::DynamicVector<Scalar, blaze::rowVector>;
using ColumnMatrix = blaze::DynamicMatrix<Scalar, blaze::columnMajor>;
public:
virtual ~Optimizer() {}
virtual nlohmann::json toJson() = 0;
///
/// Reset the optimizer to clear all historical information
///
virtual void reset(){};
///
/// Update the parameter vector using its gradient
///
/// It is assumed that the memory addresses of `dvec` and `vec` do not
/// change during the training process. This is used to implement optimization
/// algorithms that have "memories". See the AdaGrad algorithm for an example.
///
/// \param dvec The gradient of the parameter. Read-only
/// \param vec On entering, the current parameter vector. On exit, the
/// updated parameters.
///
virtual void update(ConstAlignedMapVec &dvec, AlignedMapVec &vec) = 0;
virtual void update(const RowVector &dvec, RowVector &vec) = 0;
virtual void update(const ColumnMatrix &dvec, ColumnMatrix &vec) = 0;
};
} // namespace dnn
} // namespace metric
#endif /* OPTIMIZER_H_ */
| 1,547
|
C++
|
.h
| 44
| 33.272727
| 95
| 0.737936
|
metric-space-ai/metric
| 34
| 14
| 44
|
MPL-2.0
|
9/20/2024, 10:43:29 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,531,697
|
Callback.h
|
metric-space-ai_metric/metric/utils/dnn/Callback.h
|
#ifndef CALLBACK_H_
#define CALLBACK_H_
namespace metric::dnn {
template <typename Scalar> class Network;
///
/// \defgroup Callbacks Callback Functions
///
///
/// \ingroup Callbacks
///
/// The interface and default implementation of the callback function during
/// model fitting. The purpose of this class is to allow users printing some
/// messages in each epoch or mini-batch training, for example the time spent,
/// the loss function values, etc.
///
/// This default implementation is a silent version of the callback function
/// that basically does nothing. See the VerboseCallback class for a verbose
/// version that prints the loss function value in each mini-batch.
///
template <typename Scalar> class Callback {
protected:
using Matrix = blaze::DynamicMatrix<Scalar>;
using IntegerVector = blaze::DynamicMatrix<int, blaze::columnMajor>;
public:
// Public members that will be set by the network during the training process
int batchesNumber; // Number of total batches
int batchId; // The index for the current mini-batch (0, 1, ..., m_nbatch-1)
int epochsNumber; // Total number of epochs (one run on the whole data set) in the training process
int epochId; // The index for the current epoch (0, 1, ..., m_nepoch-1)
Callback() : batchesNumber(0), batchId(0), epochsNumber(0), epochId(0) {}
virtual ~Callback() {}
virtual void preTrainingEpoch(const Network<Scalar> *net){};
virtual void postTrainingEpoch(const Network<Scalar> *net){};
// Before training a mini-batch
virtual void preTrainingBatch(const Network<Scalar> *net, const Matrix &x, const Matrix &y) {}
// virtual void preTrainingBatch(const Network<Scalar>* net, const Matrix& x,
// const IntegerVector& y) {}
// After a mini-batch is trained
virtual void postTrainingBatch(const Network<Scalar> *net, const Matrix &x, const Matrix &y) {}
// virtual void postTrainingBatch(const Network<Scalar>* net, const Matrix& x,
// const IntegerVector& y) {}
};
} // namespace metric::dnn
#endif /* CALLBACK_H_ */
| 2,027
|
C++
|
.h
| 44
| 44.25
| 101
| 0.746701
|
metric-space-ai/metric
| 34
| 14
| 44
|
MPL-2.0
|
9/20/2024, 10:43:29 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,531,698
|
Output.h
|
metric-space-ai_metric/metric/utils/dnn/Output.h
|
#ifndef OUTPUT_H_
#define OUTPUT_H_
#include <stdexcept>
#include <blaze/Math.h>
namespace metric::dnn {
///
/// \defgroup Outputs Output Layers
///
///
/// \ingroup Outputs
///
/// The interface of the output layer of a neural network model. The output
/// layer is a special layer that associates the last hidden layer with the
/// target response variable.
///
template <typename Scalar> class Output {
protected:
using Matrix = blaze::DynamicMatrix<Scalar>;
using IntegerVector = blaze::DynamicMatrix<int, blaze::columnMajor>;
public:
virtual ~Output() {}
virtual std::string getType() = 0;
// Check the format of target data, e.g. in classification problems the
// target data should be binary (either 0 or 1)
virtual void check_target_data(const Matrix &target) {}
// Another type of target data where each element is a class label
// This version may not be sensible for regression tasks, so by default
// we raise an exception
/*virtual void check_target_data(const IntegerVector& target)
{
throw std::invalid_argument("[class Output]: This output type cannot take class labels as target data");
}*/
// A combination of the forward stage and the back-propagation stage for the output layer
// The computed derivative of the input should be stored in this layer, and can be retrieved by
// the backprop_data() function
virtual void evaluate(const Matrix &prev_layer_data, const Matrix &target) = 0;
// Another type of target data where each element is a class label
// This version may not be sensible for regression tasks, so by default
// we raise an exception
/*virtual void evaluate(const Matrix& prev_layer_data,
const IntegerVector& target)
{
throw std::invalid_argument("[class Output]: This output type cannot take class labels as target data");
}*/
// The derivative of the input of this layer, which is also the derivative
// of the output of previous layer
virtual const Matrix &backprop_data() const = 0;
// Return the loss function value after the evaluation
// This function can be assumed to be called after evaluate(), so that it can make use of the
// intermediate result to save some computation
virtual Scalar loss() const = 0;
};
} // namespace metric::dnn
#endif /* OUTPUT_H_ */
| 2,268
|
C++
|
.h
| 54
| 39.87037
| 106
| 0.751251
|
metric-space-ai/metric
| 34
| 14
| 44
|
MPL-2.0
|
9/20/2024, 10:43:29 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,531,699
|
VerboseCallback.h
|
metric-space-ai_metric/metric/utils/dnn/Callback/VerboseCallback.h
|
#ifndef CALLBACK_VERBOSECALLBACK_H_
#define CALLBACK_VERBOSECALLBACK_H_
#include <chrono>
#include <iostream>
#include "../Callback.h"
#include "../Network.h"
namespace metric {
namespace dnn {
///
/// \ingroup Callbacks
///
/// Callback function that prints the loss function value in each mini-batch training
///
template <typename Scalar> class VerboseCallback : public Callback<Scalar> {
private:
using typename Callback<Scalar>::Matrix;
using typename Callback<Scalar>::IntegerVector;
using Clock = std::chrono::high_resolution_clock;
bool verboseEpoch;
bool verboseBatch;
Clock::time_point epochStart;
Clock::time_point batchStart;
public:
VerboseCallback(bool verboseEpoch = true, bool verboseBatch = true)
: verboseEpoch(verboseEpoch), verboseBatch(verboseBatch)
{
}
void preTrainingEpoch(const Network<Scalar> *net)
{
if (!verboseEpoch) {
return;
}
epochStart = Clock::now();
}
void postTrainingEpoch(const Network<Scalar> *net)
{
if (!verboseEpoch) {
return;
}
const Scalar loss = net->get_output()->loss();
std::cout << "[Epoch " << this->epochId << "/" << this->epochsNumber << "] Loss = " << loss;
auto epochEnd = Clock::now();
auto d = std::chrono::duration_cast<std::chrono::duration<double>>(epochEnd - epochStart);
std::cout << " Training time: " << d.count() << " s" << std::endl;
}
void preTrainingBatch(const Network<Scalar> *net, const Matrix &x, const Matrix &y)
{
if (!verboseBatch) {
return;
}
batchStart = Clock::now();
}
void postTrainingBatch(const Network<Scalar> *net, const Matrix &x, const Matrix &y)
{
if (!verboseBatch) {
return;
}
const Scalar loss = net->get_output()->loss();
std::cout << "[Epoch " << this->epochId << "/" << this->epochsNumber;
std::cout << ", batch " << this->batchId << "/" << this->batchesNumber << "] Loss = " << loss;
auto batchEnd = Clock::now();
auto d = std::chrono::duration_cast<std::chrono::duration<double>>(batchEnd - batchStart);
std::cout << " Training time: " << d.count() << " s" << std::endl;
}
/*void postTrainingBatch(const Network<Scalar>* net, const Matrix& x,
const IntegerVector& y)
{
Scalar loss = net->get_output()->loss();
std::cout << "[Epoch " << this->epochId << "/" << this->epochsNumber;
std::cout << ", batch " << this->batchId << "/" << this->batchesNumber << "] Loss = "
<< loss << std::endl;
}*/
};
} // namespace dnn
} // namespace metric
#endif /* CALLBACK_VERBOSECALLBACK_H_ */
| 2,500
|
C++
|
.h
| 76
| 30.197368
| 96
| 0.672636
|
metric-space-ai/metric
| 34
| 14
| 44
|
MPL-2.0
|
9/20/2024, 10:43:29 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,531,700
|
RegressionMSE.h
|
metric-space-ai_metric/metric/utils/dnn/Output/RegressionMSE.h
|
#ifndef OUTPUT_REGRESSIONMSE_H_
#define OUTPUT_REGRESSIONMSE_H_
#include <stdexcept>
namespace metric::dnn {
///
/// \ingroup Outputs
///
/// Regression output layer using Mean Squared Error (MSE) criterion
///
template <typename Scalar> class RegressionMSE : public Output<Scalar> {
private:
using Matrix = blaze::DynamicMatrix<Scalar>;
Matrix m_din; // Derivative of the input of this layer.
// Note that input of this layer is also the output of previous layer
public:
std::string getType() { return "RegressionMSE"; }
void evaluate(const Matrix &prev_layer_data, const Matrix &target)
{
// Check dimension
const int nobs = prev_layer_data.rows();
const int nvar = prev_layer_data.columns();
if ((target.rows() != nobs) || (target.columns() != nvar)) {
throw std::invalid_argument("[class RegressionMSE]: Target data have incorrect dimension");
}
// Compute the derivative of the input of this layer
// L = 0.5 * ||yhat - y||^2
// in = yhat
// d(L) / d(in) = yhat - y
m_din.resize(nobs, nvar);
// noalises
m_din = 2 * (prev_layer_data - target);
}
const Matrix &backprop_data() const { return m_din; }
Scalar loss() const
{
// L = 0.5 * ||yhat - y||^2
return blaze::sqrNorm(m_din / 2.) / m_din.rows();
}
};
} // namespace metric::dnn
#endif /* OUTPUT_REGRESSIONMSE_H_ */
| 1,331
|
C++
|
.h
| 41
| 30.073171
| 94
| 0.68491
|
metric-space-ai/metric
| 34
| 14
| 44
|
MPL-2.0
|
9/20/2024, 10:43:29 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,531,702
|
MultiClassEntropy.h
|
metric-space-ai_metric/metric/utils/dnn/Output/MultiClassEntropy.h
|
#ifndef OUTPUT_MULTICLASSENTROPY_H_
#define OUTPUT_MULTICLASSENTROPY_H_
#include <stdexcept>
namespace metric {
namespace dnn {
///
/// \ingroup Outputs
///
/// Multi-class classification output layer using cross-entropy criterion
///
template <typename Scalar> class MultiClassEntropy : public Output<Scalar> {
private:
using typename Output<Scalar>::Matrix;
using typename Output<Scalar>::IntegerVector;
Matrix m_din; // Derivative of the input of this layer.
// Note that input of this layer is also the output of previous layer
public:
std::string getType() { return "MulticlassEntropy"; }
void check_target_data(const Matrix &target)
{
// Each element should be either 0 or 1
// Each column has and only has one 1
const int nobs = target.rows();
const int nclass = target.columns();
for (int i = 0; i < nobs; i++) {
int one = 0;
for (int j = 0; j < nclass; j++) {
if (target(i, j) == Scalar(1)) {
one++;
continue;
}
if (target(i, j) != Scalar(0)) {
throw std::invalid_argument(
"[class MultiClassEntropy]: Target data should only contain zero or one");
}
}
if (one != 1) {
throw std::invalid_argument(
"[class MultiClassEntropy]: Each column of target data should only contain one \"1\"");
}
}
}
/*void check_target_data(const IntegerVector& target)
{
// All elements must be non-negative
const int nobs = target.rows();
for (int i = 0; i < nobs; i++) {
if (target(i, 0) < 0) {
throw std::invalid_argument("[class MultiClassEntropy]: Target data must be non-negative");
}
}
}*/
// target is a matrix with each column representing an observation
// Each column is a vector that has a one at some location and has zeros elsewhere
void evaluate(const Matrix &prev_layer_data, const Matrix &target)
{
// Check dimension
const int nobs = prev_layer_data.rows();
const int nclass = prev_layer_data.columns();
if ((target.rows() != nobs) || (target.columns() != nclass)) {
throw std::invalid_argument("[class MultiClassEntropy]: Target data have incorrect dimension");
}
// Compute the derivative of the input of this layer
// L = -sum(log(phat) * y)
// in = phat
// d(L) / d(in) = -y / phat
m_din.resize(nclass, nobs);
/* noalias */
// m_din = -target.cwiseQuotient(prev_layer_data);
}
// target is a vector of class labels that take values from [0, 1, ..., nclass - 1]
// The i-th element of target is the class label for observation i
void evaluate(const Matrix &prev_layer_data, const IntegerVector &target)
{
// Check dimension
const int nobs = prev_layer_data.rows();
const int nclass = prev_layer_data.columns();
if (target.rows() != nobs) {
throw std::invalid_argument("[class MultiClassEntropy]: Target data have incorrect dimension");
}
// Compute the derivative of the input of this layer
// L = -log(phat[y])
// in = phat
// d(L) / d(in) = [0, 0, ..., -1/phat[y], 0, ..., 0]
m_din.resize(nobs, nclass);
m_din = 0;
for (int i = 0; i < nobs; i++) {
m_din(i, target(i, 0)) = -Scalar(1) / prev_layer_data(i, target(i, 0));
}
}
const Matrix &backprop_data() const { return m_din; }
Scalar loss() const
{
// L = -sum(log(phat) * y)
// in = phat
// d(L) / d(in) = -y / phat
// m_din contains 0 if y = 0, and -1/phat if y = 1
Scalar res = Scalar(0);
const int nelem = blaze::size(m_din);
const Scalar *din_data = m_din.data();
for (int i = 0; i < nelem; i++) {
if (din_data[i] < Scalar(0)) {
res += std::log(-din_data[i]);
}
}
return res / m_din.rows();
}
};
} // namespace dnn
} // namespace metric
#endif /* OUTPUT_MULTICLASSENTROPY_H_ */
| 3,677
|
C++
|
.h
| 111
| 30.018018
| 98
| 0.656312
|
metric-space-ai/metric
| 34
| 14
| 44
|
MPL-2.0
|
9/20/2024, 10:43:29 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,531,703
|
Identity.h
|
metric-space-ai_metric/metric/utils/dnn/Activation/Identity.h
|
#ifndef ACTIVATION_IDENTITY_H_
#define ACTIVATION_IDENTITY_H_
#include <blaze/Math.h>
namespace metric {
namespace dnn {
///
/// \defgroup Activations Activation Functions
///
///
/// \ingroup Activations
///
/// The identity activation function
///
template <typename Scalar> class Identity {
private:
using Matrix = blaze::DynamicMatrix<Scalar>;
using ColumnMatrix = blaze::DynamicMatrix<Scalar, blaze::columnMajor>;
public:
static std::string getType() { return "Identity"; }
// a = activation(z) = z
// Z = [z1, ..., zn], A = [a1, ..., an], n observations
static inline void activate(const Matrix &Z, Matrix &A) { A = Z; }
// Apply the Jacobian matrix J to a vector f
// J = d_a / d_z = I
// g = J * f = f
// Z = [z1, ..., zn], G = [g1, ..., gn], F = [f1, ..., fn]
// Note: When entering this function, Z and G may point to the same matrix
static inline void apply_jacobian(const Matrix &Z, const Matrix &A, const Matrix &F, ColumnMatrix &G) { G = F; }
static inline void apply_jacobian(const Matrix &Z, const Matrix &A, const Matrix &F, Matrix &G) { G = F; }
};
} // namespace dnn
} // namespace metric
#endif /* ACTIVATION_IDENTITY_H_ */
| 1,171
|
C++
|
.h
| 33
| 33.666667
| 113
| 0.669326
|
metric-space-ai/metric
| 34
| 14
| 44
|
MPL-2.0
|
9/20/2024, 10:43:29 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,531,704
|
Softmax.h
|
metric-space-ai_metric/metric/utils/dnn/Activation/Softmax.h
|
#ifndef ACTIVATION_SOFTMAX_H_
#define ACTIVATION_SOFTMAX_H_
namespace metric {
namespace dnn {
///
/// \ingroup Activations
///
/// The softmax activation function
///
template <typename Scalar> class Softmax {
private:
// typedef Eigen::Matrix<Scalar, Eigen::Dynamic, Eigen::Dynamic> Matrix;
// typedef Eigen::Array<Scalar, 1, Eigen::Dynamic> RowArray;
using Matrix = blaze::DynamicMatrix<Scalar>;
using Vector = blaze::DynamicVector<Scalar>;
using RowVector = blaze::DynamicVector<Scalar, blaze::rowVector>;
public:
static std::string getType() { return "Softmax"; }
// a = activation(z) = softmax(z)
// Z = [z1, ..., zn], A = [a1, ..., an], n observations
static inline void activate(const Matrix &Z, Matrix &A) { A = blaze::softmax<blaze::rowwise>(Z); }
// Apply the Jacobian matrix J to a vector f
// J = d_a / d_z = diag(a) - a * a'
// g = J * f = a .* f - a * (a' * f) = a .* (f - a'f)
// Z = [z1, ..., zn], G = [g1, ..., gn], F = [f1, ..., fn]
// Note: When entering this function, Z and G may point to the same matrix
static inline void apply_jacobian(const Matrix &Z, const Matrix &A, const Matrix &F, Matrix &G)
{
RowVector a_dot_f = A.cwiseProduct(F).colwise().sum();
G = A * (F.rowwise() - a_dot_f);
}
};
} // namespace dnn
} // namespace metric
#endif /* ACTIVATION_SOFTMAX_H_ */
| 1,326
|
C++
|
.h
| 35
| 35.971429
| 99
| 0.652648
|
metric-space-ai/metric
| 34
| 14
| 44
|
MPL-2.0
|
9/20/2024, 10:43:29 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,531,705
|
ReLU.h
|
metric-space-ai_metric/metric/utils/dnn/Activation/ReLU.h
|
#ifndef ACTIVATION_RELU_H_
#define ACTIVATION_RELU_H_
#include <blaze/Math.h>
namespace metric {
namespace dnn {
///
/// \ingroup Activations
///
/// The ReLU activation function
///
template <typename Scalar> class ReLU {
private:
using Matrix = blaze::DynamicMatrix<Scalar>;
using ColumnMatrix = blaze::DynamicMatrix<Scalar, blaze::columnMajor>;
public:
static std::string getType() { return "ReLU"; }
// a = activation(z) = max(z, 0)
// Z = [z1, ..., zn], A = [a1, ..., an], n observations
static inline void activate(const Matrix &Z, Matrix &A)
{
// A = Z.array().cwiseMax(Scalar(0));
for (size_t j = 0UL; j < Z.columns(); j++) {
for (size_t i = 0UL; i < Z.rows(); i++) {
if (Z(i, j) < 0) {
A(i, j) = 0;
} else {
A(i, j) = Z(i, j);
}
}
}
}
// Apply the Jacobian matrix J to a vector f
// J = d_a / d_z = diag(sign(a)) = diag(a > 0)
// g = J * f = (a > 0) .* f
// Z = [z1, ..., zn], G = [g1, ..., gn], F = [f1, ..., fn]
// Note: When entering this function, Z and G may point to the same matrix
static inline void apply_jacobian(const Matrix &Z, const Matrix &A, const Matrix &F, ColumnMatrix &G)
{
// G = (A.array() > Scalar(0)).select(F, Scalar(0));
for (size_t j = 0UL; j < G.columns(); j++) {
for (size_t i = 0UL; i < G.rows(); i++) {
if (A(i, j) > 0) {
G(i, j) = F(i, j);
} else {
G(i, j) = 0;
}
}
}
}
static inline void apply_jacobian(const Matrix &Z, const Matrix &A, const Matrix &F, Matrix &G)
{
// G = (A.array() > Scalar(0)).select(F, Scalar(0));
for (size_t i = 0UL; i < G.rows(); i++) {
for (size_t j = 0UL; j < G.columns(); j++) {
if (A(i, j) > 0) {
G(i, j) = F(i, j);
} else {
G(i, j) = 0;
}
}
}
}
};
} // namespace dnn
} // namespace metric
#endif /* ACTIVATION_RELU_H_ */
| 1,825
|
C++
|
.h
| 66
| 24.636364
| 102
| 0.552827
|
metric-space-ai/metric
| 34
| 14
| 44
|
MPL-2.0
|
9/20/2024, 10:43:29 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,531,706
|
Sigmoid.h
|
metric-space-ai_metric/metric/utils/dnn/Activation/Sigmoid.h
|
#ifndef ACTIVATION_SIGMOID_H_
#define ACTIVATION_SIGMOID_H_
#include <blaze/Math.h>
namespace metric {
namespace dnn {
///
/// \ingroup Activations
///
/// The sigmoid activation function
///
template <typename Scalar> class Sigmoid {
private:
using Matrix = blaze::DynamicMatrix<Scalar>;
using ColumnMatrix = blaze::DynamicMatrix<Scalar, blaze::columnMajor>;
public:
static std::string getType() { return "Sigmoid"; }
// a = activation(z) = 1 / (1 + exp(-z))
// Z = [z1, ..., zn], A = [a1, ..., an], n observations
static inline void activate(const Matrix &Z, Matrix &A) { A = Scalar(1) / (Scalar(1) + blaze::exp(-Z)); }
// Apply the Jacobian matrix J to a vector f
// J = d_a / d_z = diag(a .* (1 - a))
// g = J * f = a .* (1 - a) .* f
// Z = [z1, ..., zn], G = [g1, ..., gn], F = [f1, ..., fn]
// Note: When entering this function, Z and G may point to the same matrix
static inline void apply_jacobian(const Matrix &Z, const Matrix &A, const Matrix &F, ColumnMatrix &G)
{
G = A % (Scalar(1) - A) % F;
}
};
} // namespace dnn
} // namespace metric
#endif /* ACTIVATION_SIGMOID_H_ */
| 1,114
|
C++
|
.h
| 32
| 32.9375
| 106
| 0.635009
|
metric-space-ai/metric
| 34
| 14
| 44
|
MPL-2.0
|
9/20/2024, 10:43:29 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,531,707
|
SGD.h
|
metric-space-ai_metric/metric/utils/dnn/Optimizer/SGD.h
|
#ifndef OPTIMIZER_SGD_H_
#define OPTIMIZER_SGD_H_
#include "../Optimizer.h"
namespace metric {
namespace dnn {
///
/// \ingroup Optimizers
///
/// The Stochastic Gradient Descent (SGD) algorithm
///
template <typename Scalar> class SGD : public Optimizer<Scalar> {
private:
using Vector = blaze::DynamicVector<Scalar>;
using AlignedMapVec = blaze::CustomVector<Scalar, blaze::aligned, blaze::unpadded>;
using ConstAlignedMapVec = const blaze::CustomVector<Scalar, blaze::aligned, blaze::unpadded>;
public:
Scalar m_lrate;
Scalar m_decay;
SGD() : m_lrate(Scalar(0.01)), m_decay(Scalar(0)) {}
void update(ConstAlignedMapVec &dvec, AlignedMapVec &vec) { vec -= m_lrate * (dvec + m_decay * vec); }
};
} // namespace dnn
} // namespace metric
#endif /* OPTIMIZER_SGD_H_ */
| 787
|
C++
|
.h
| 24
| 31
| 103
| 0.728477
|
metric-space-ai/metric
| 34
| 14
| 44
|
MPL-2.0
|
9/20/2024, 10:43:29 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,531,709
|
RMSProp.h
|
metric-space-ai_metric/metric/utils/dnn/Optimizer/RMSProp.h
|
#ifndef OPTIMIZER_RMSPROP_H_
#define OPTIMIZER_RMSPROP_H_
#include "unordered_map"
#include "../Optimizer.h"
namespace metric::dnn {
///
/// \ingroup Optimizers
///
/// The RMSProp algorithm
///
template <typename Scalar> class RMSProp : public Optimizer<Scalar> {
private:
using typename Optimizer<Scalar>::RowVector;
using typename Optimizer<Scalar>::ColumnMatrix;
using Array = blaze::DynamicVector<Scalar>;
using AlignedMapVec = blaze::CustomVector<Scalar, blaze::aligned, blaze::unpadded>;
using ConstAlignedMapVec = const blaze::CustomVector<Scalar, blaze::aligned, blaze::unpadded>;
std::unordered_map<const Scalar *, Array> m_history;
std::unordered_map<const RowVector *, RowVector> historyVectors;
std::unordered_map<const ColumnMatrix *, ColumnMatrix> historyMatrices;
public:
Scalar learningRate;
Scalar m_eps;
Scalar m_decay;
RMSProp(Scalar learningRate = Scalar(0.01), Scalar eps = Scalar(1e-6), Scalar decay = Scalar(0.9))
: learningRate(learningRate), m_eps(eps), m_decay(decay)
{
}
nlohmann::json toJson()
{
nlohmann::json json;
json["type"] = "RMSProp";
json["learningRate"] = learningRate;
json["eps"] = m_eps;
json["decay"] = m_decay;
return json;
}
void reset() { m_history.clear(); }
void update(ConstAlignedMapVec &dvec, AlignedMapVec &vec)
{
// Get the accumulated squared gradient associated with this gradient
auto &grad_square = m_history[dvec.data()];
// std::cout << "history:" << m_history.size() << std::endl;
// If length is zero, initialize it
if (grad_square.size() == 0) {
grad_square.resize(dvec.size());
grad_square = 0;
}
// Update accumulated squared gradient
grad_square = m_decay * grad_square + (Scalar(1) - m_decay) * blaze::pow(dvec, 2);
// Update parameters
vec -= learningRate * dvec / blaze::sqrt(grad_square + m_eps);
}
void update(const RowVector &dvec, RowVector &vec)
{
auto &grad_square = historyVectors[&dvec];
// std::cout << "RowVector history:" << historyVectors.size() << std::endl;
if (grad_square.size() == 0) {
grad_square.resize(dvec.size());
grad_square = 0;
}
grad_square = m_decay * grad_square + (Scalar(1) - m_decay) * blaze::pow(dvec, 2);
vec -= learningRate * dvec / blaze::sqrt(grad_square + m_eps);
}
void update(const ColumnMatrix &dvec, ColumnMatrix &vec)
{
auto &grad_square = historyMatrices[&dvec];
// std::cout << "ColumnMatrix history:" << historyVectors.size() << std::endl;
if (blaze::isDefault(grad_square)) {
grad_square.resize(dvec.rows(), dvec.columns());
grad_square = 0;
}
grad_square = m_decay * grad_square + (Scalar(1) - m_decay) * blaze::pow(dvec, 2);
for (size_t j = 0; j < dvec.columns(); ++j) {
blaze::column(vec, j) -=
learningRate * blaze::column(dvec, j) / blaze::column(blaze::sqrt(grad_square + m_eps), j);
}
}
};
} // namespace metric::dnn
#endif /* OPTIMIZER_RMSPROP_H_ */
| 2,910
|
C++
|
.h
| 81
| 33.222222
| 99
| 0.692911
|
metric-space-ai/metric
| 34
| 14
| 44
|
MPL-2.0
|
9/20/2024, 10:43:29 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,531,710
|
NormalInitializer.h
|
metric-space-ai_metric/metric/utils/dnn/Initializer/NormalInitializer.h
|
#ifndef NORMALINITIALIZER_H
#define NORMALINITIALIZER_H
#include "../Initializer.h"
#include <random>
namespace metric::dnn {
template <typename Scalar> class NormalInitializer : public Initializer<Scalar> {
protected:
using typename Initializer<Scalar>::ColumnMatrix;
using typename Initializer<Scalar>::RowVector;
std::normal_distribution<Scalar> normalDistribution;
std::mt19937 randomEngine;
public:
NormalInitializer(const Scalar mu, const Scalar sigma, const std::mt19937 &randomEngine)
: randomEngine(randomEngine), normalDistribution(mu, sigma)
{
}
void init(const size_t rows, const size_t columns, ColumnMatrix &matrix)
{
matrix = blaze::generate<blaze::columnMajor>(
rows, columns, [this](size_t i, size_t j) { return normalDistribution(randomEngine); });
}
void init(const size_t size, RowVector &vector)
{
vector =
blaze::generate<blaze::rowVector>(size, [this](size_t pos) { return normalDistribution(randomEngine); });
}
};
} // namespace metric::dnn
#endif
| 1,009
|
C++
|
.h
| 29
| 32.551724
| 108
| 0.770812
|
metric-space-ai/metric
| 34
| 14
| 44
|
MPL-2.0
|
9/20/2024, 10:43:29 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,531,711
|
ZeroInitializer.h
|
metric-space-ai_metric/metric/utils/dnn/Initializer/ZeroInitializer.h
|
#ifndef ZEROINITIALIZER_H
#define ZEROINITIALIZER_H
#include "../Initializer.h"
namespace metric::dnn {
template <typename Scalar> class ZeroInitializer : public Initializer<Scalar> {
protected:
using typename Initializer<Scalar>::ColumnMatrix;
using typename Initializer<Scalar>::RowVector;
public:
void init(const size_t rows, const size_t columns, ColumnMatrix &matrix)
{
matrix = blaze::zero<Scalar, blaze::columnMajor>(rows, columns);
}
void init(const size_t size, RowVector &vector) { vector = blaze::zero<Scalar, blaze::rowVector>(size); }
};
} // namespace metric::dnn
#endif // ZEROINITIALIZER_H
| 622
|
C++
|
.h
| 17
| 34.647059
| 106
| 0.768719
|
metric-space-ai/metric
| 34
| 14
| 44
|
MPL-2.0
|
9/20/2024, 10:43:29 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,531,712
|
MaxPooling.h
|
metric-space-ai_metric/metric/utils/dnn/Layer/MaxPooling.h
|
#ifndef LAYER_MAXPOOLING_H_
#define LAYER_MAXPOOLING_H_
#include <stdexcept>
#include "../Layer.h"
#include "../Utils/FindMax.h"
namespace metric {
namespace dnn {
///
/// \ingroup Layers
///
/// Max-pooling hidden layer
///
/// Currently only supports the "valid" rule of pooling.
///
template <typename Scalar, typename Activation> class MaxPooling : public Layer<Scalar> {
private:
using Matrix = blaze::DynamicMatrix<Scalar>;
using IntegerMatrix = blaze::DynamicMatrix<int>;
const size_t inputHeight;
const size_t inputWidth;
const size_t inputChannels;
const size_t poolingHeight;
const size_t poolingWidth;
const size_t outputHeight;
const size_t outputWidth;
IntegerMatrix m_loc; // Record the locations of maximums
Matrix m_z; // Max pooling results
Matrix m_a; // Output of this layer, a = act(z)
Matrix m_din; // Derivative of the input of this layer.
// Note that input of this layer is also the output of previous layer
public:
// Currently we only implement the "valid" rule
// https://stackoverflow.com/q/37674306
///
/// Constructor
///
/// \param inputWidth Width of the input image in each channel.
/// \param inputHeight Height of the input image in each channel.
/// \param inputChannels Number of input channels.
/// \param poolingWidth Width of the pooling window.
/// \param poolingHeight Height of the pooling window.
///
MaxPooling(const size_t inputWidth, const size_t inputHeight, const size_t inputChannels, const size_t poolingWidth,
const size_t poolingHeight)
: Layer<Scalar>(inputWidth * inputHeight * inputChannels,
(inputWidth / poolingWidth) * (inputHeight / poolingHeight) * inputChannels),
inputHeight(inputHeight), inputWidth(inputWidth), inputChannels(inputChannels), poolingHeight(poolingHeight),
poolingWidth(poolingWidth), outputHeight(inputHeight / poolingHeight), outputWidth(inputWidth / poolingWidth)
{
}
// MaxPooling(const nlohmann::json& json) : Layer<Scalar>(json)
//{}
void init(const Scalar &mu, const Scalar &sigma, std::mt19937 &rng) {}
void forward(const Matrix &prev_layer_data)
{
// Each row is an observation
const size_t nobs = prev_layer_data.rows();
m_loc.resize(nobs, this->outputSize);
m_z.resize(nobs, this->outputSize);
// Use m_loc to store the address of each pooling block relative to the beginning of the data
int *loc_data = m_loc.data();
const size_t channel_end = blaze::size(prev_layer_data);
const size_t channel_stride = inputHeight * inputWidth;
const size_t col_end_gap = inputHeight * poolingWidth * outputWidth;
const size_t col_stride = inputHeight * poolingWidth;
const size_t row_end_gap = outputHeight * poolingHeight;
for (size_t channel_start = 0; channel_start < channel_end; channel_start += channel_stride) {
const size_t col_end = channel_start + col_end_gap;
for (size_t col_start = channel_start; col_start < col_end; col_start += col_stride) {
const size_t row_end = col_start + row_end_gap;
for (size_t row_start = col_start; row_start < row_end; row_start += poolingHeight, loc_data++) {
*loc_data = row_start;
}
}
}
// Find the location of the max value in each block
loc_data = m_loc.data();
const int *const loc_end = loc_data + blaze::size(m_loc);
Scalar *z_data = m_z.data();
const Scalar *src = prev_layer_data.data();
for (; loc_data < loc_end; loc_data++, z_data++) {
const size_t offset = *loc_data;
*z_data = internal::find_block_max(src + offset, poolingHeight, poolingWidth, inputHeight, *loc_data);
*loc_data += offset;
}
// Apply activation function
m_a.resize(this->outputSize, nobs);
Activation::activate(m_z, m_a);
}
const Matrix &output() const { return m_a; }
// prev_layer_data: getInputSize x nobs
// next_layer_data: getOutputSize x nobs
void backprop(const Matrix &prev_layer_data, const Matrix &next_layer_data)
{
const size_t nobs = prev_layer_data.rows();
// After forward stage, m_z contains z = max_pooling(in)
// Now we need to calculate d(L) / d(z) = [d(a) / d(z)] * [d(L) / d(a)]
// d(L) / d(z) is computed in the next layer, contained in next_layer_data
// The Jacobian matrix J = d(a) / d(z) is determined by the activation function
Matrix dLz = m_z;
Activation::apply_jacobian(m_z, m_a, next_layer_data, dLz);
// d(L) / d(in_i) = sum_j{ [d(z_j) / d(in_i)] * [d(L) / d(z_j)] }
// d(z_j) / d(in_i) = 1 if in_i is used to compute z_j and is the maximum
// = 0 otherwise
m_din.resize(nobs, this->inputSize);
m_din = 0;
const size_t dLz_size = blaze::size(dLz);
const Scalar *dLz_data = dLz.data();
const int *loc_data = m_loc.data();
Scalar *din_data = m_din.data();
for (size_t i = 0; i < dLz_size; i++) {
din_data[loc_data[i]] += dLz_data[i];
}
}
const Matrix &backprop_data() const { return m_din; }
void update(Optimizer<Scalar> &opt) {}
std::vector<std::vector<Scalar>> getParameters() const { return std::vector<std::vector<Scalar>>(); }
void setParameters(const std::vector<std::vector<Scalar>> ¶meters){};
std::vector<Scalar> get_derivatives() const { return std::vector<Scalar>(); }
};
} // namespace dnn
} // namespace metric
#endif /* LAYER_MAXPOOLING_H_ */
| 5,257
|
C++
|
.h
| 123
| 39.943089
| 117
| 0.696708
|
metric-space-ai/metric
| 34
| 14
| 44
|
MPL-2.0
|
9/20/2024, 10:43:29 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,531,713
|
Conv2d-transpose.h
|
metric-space-ai_metric/metric/utils/dnn/Layer/Conv2d-transpose.h
|
#ifndef LAYER_CONV2D_TRANSPOSE_H_
#define LAYER_CONV2D_TRANSPOSE_H_
#include <chrono>
#include <stdexcept>
#include "Conv2d.h"
namespace metric::dnn {
template <typename Scalar, typename Activation> class Conv2dTranspose : public Conv2d<Scalar, Activation> {
protected:
using typename Conv2d<Scalar, Activation>::SparseMatrix;
public:
Conv2dTranspose(const size_t inputWidth, const size_t inputHeight, const size_t inputChannels,
const size_t outputChannels, const size_t kernelWidth, const size_t kernelHeight,
const size_t stride = 1)
: Conv2d<Scalar, Activation>(inputWidth * inputHeight * inputChannels,
((inputWidth - kernelWidth) / stride + 1) *
((inputHeight - kernelHeight) / stride + 1) * outputChannels)
{
this->inputWidth = inputWidth;
this->inputHeight = inputHeight;
this->kernelWidth = kernelWidth;
this->kernelHeight = kernelHeight;
this->inputChannels = inputChannels;
this->outputChannels = outputChannels;
this->stride = stride;
this->outputWidth = (inputWidth - 1) * stride + kernelWidth;
this->outputHeight = (inputHeight - 1) * stride + kernelWidth;
this->inputSize = inputChannels * inputWidth * inputHeight;
this->outputSize = this->outputChannels * this->outputWidth * this->outputHeight;
// Set data dimension
const size_t kernelDataSize = inputChannels * outputChannels * kernelWidth * kernelHeight;
this->kernelsData.resize(kernelDataSize);
this->df_data.resize(kernelDataSize);
// Bias term
this->bias.resize(outputChannels);
this->db.resize(outputChannels);
this->isTranspose = true;
this->calculateUnrolledKernelStructure();
this->getUnrolledKernel();
}
Conv2dTranspose(const nlohmann::json &json) : Conv2d<Scalar, Activation>(json)
{
this->outputWidth = (this->inputWidth - 1) * this->stride + this->kernelWidth;
this->outputHeight = (this->inputHeight - 1) * this->stride + this->kernelHeight;
this->outputSize = this->outputChannels * this->outputWidth * this->outputHeight;
this->isTranspose = true;
}
};
} // namespace metric::dnn
#endif /* LAYER_CONVOLUTIONAL_H_ */
| 2,111
|
C++
|
.h
| 49
| 39.857143
| 107
| 0.746458
|
metric-space-ai/metric
| 34
| 14
| 44
|
MPL-2.0
|
9/20/2024, 10:43:29 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,531,714
|
FullyConnected.h
|
metric-space-ai_metric/metric/utils/dnn/Layer/FullyConnected.h
|
#ifndef LAYER_FULLYCONNECTED_H_
#define LAYER_FULLYCONNECTED_H_
#include <iostream>
#include <random>
#include <stdexcept>
#include <blaze/Math.h>
#include "../Layer.h"
#include "../Utils/Random.h"
namespace metric {
namespace dnn {
///
/// \ingroup Layers
///
/// Fully connected hidden layer
///
template <typename Scalar, typename Activation> class FullyConnected : public Layer<Scalar> {
private:
using Matrix = blaze::DynamicMatrix<Scalar>;
using ColumnMatrix = blaze::DynamicMatrix<Scalar, blaze::columnMajor>;
using Vector = blaze::DynamicVector<Scalar, blaze::rowVector>;
using ConstAlignedMapVec = const blaze::CustomVector<Scalar, blaze::aligned, blaze::unpadded>;
using AlignedMapVec = blaze::CustomVector<Scalar, blaze::aligned, blaze::unpadded>;
ColumnMatrix m_weight; // Weight parameters, W(getInputSize x getOutputSize)
Vector m_bias; // Bias parameters, b(getOutputSize x 1)
ColumnMatrix m_dw; // Derivative of weights
Vector m_db; // Derivative of bias
Matrix m_z; // Linear term, z = W' * in + b
Matrix m_a; // Output of this layer, a = act(z)
Matrix m_din; // Derivative of the input of this layer.
// Note that input of this layer is also the output of previous layer
public:
///
/// Constructor
///
/// \param in_size Number of input units.
/// \param out_size Number of output units.
///
FullyConnected(const size_t in_size, const size_t out_size) : Layer<Scalar>(in_size, out_size) {}
FullyConnected(const nlohmann::json &json)
{
this->inputSize = json["inputSize"].get<int>();
this->outputSize = json["outputSize"].get<int>();
}
nlohmann::json toJson()
{
auto json = Layer<Scalar>::toJson();
json["type"] = "FullyConnected";
json["activation"] = Activation::getType();
return json;
}
void init(const Scalar &mu, const Scalar &sigma, std::mt19937 &rng)
{
// this->initConstant(0.1, 0);
// return;
m_weight.resize(this->inputSize, this->outputSize);
m_bias.resize(this->outputSize);
m_dw.resize(this->inputSize, this->outputSize);
m_db.resize(this->outputSize);
// Set random coefficients
internal::set_normal_random(m_weight.data(), blaze::size(m_weight), rng, mu, sigma);
internal::set_normal_random(m_bias.data(), m_bias.size(), rng, mu, sigma);
// m_weight = 1;
// m_bias = 0.01;
}
void init(const std::map<std::string, std::shared_ptr<Initializer<Scalar>>> initializers)
{
initializers.at("normal")->init(this->inputSize, this->outputSize, m_weight);
initializers.at("zero")->init(this->outputSize, m_bias);
m_dw.resize(this->inputSize, this->outputSize);
m_db.resize(this->outputSize);
}
void initConstant(const Scalar weightsValue, const Scalar biasesValue)
{
m_weight.resize(this->inputSize, this->outputSize);
m_bias.resize(this->outputSize);
m_dw.resize(this->inputSize, this->outputSize);
m_db.resize(this->outputSize);
m_weight = weightsValue;
m_bias = biasesValue;
}
// prev_layer_data: getInputSize x nobs
void forward(const Matrix &prev_layer_data)
{
const size_t nobs = prev_layer_data.rows();
// Linear term z = W' * in + b
m_z.resize(nobs, this->outputSize);
m_z = prev_layer_data * m_weight;
for (size_t i = 0UL; i < m_z.rows(); i++) {
blaze::row(m_z, i) += m_bias;
}
// Apply activation function
m_a.resize(nobs, this->outputSize);
// std::cout << blaze::submatrix<0, 0, 5, 20>(prev_layer_data) << std::endl;
// std::cout << blaze::submatrix<0, 0, 5, 20>(m_z) << std::endl;
Activation::activate(m_z, m_a);
}
const Matrix &output() const { return m_a; }
// prev_layer_data: getInputSize x nobs
// next_layer_data: getOutputSize x nobs
void backprop(const Matrix &prev_layer_data, const Matrix &next_layer_data)
{
const size_t nobs = prev_layer_data.rows();
// After forward stage, m_z contains z = W' * in + b
// Now we need to calculate d(L) / d(z) = [d(a) / d(z)] * [d(L) / d(a)]
// d(L) / d(a) is computed in the next layer, contained in next_layer_data
// The Jacobian matrix J = d(a) / d(z) is determined by the activation function
ColumnMatrix dLz = m_z;
Activation::apply_jacobian(m_z, m_a, next_layer_data, dLz);
// Now dLz contains d(L) / d(z)
// Derivative for weights, d(L) / d(W) = [d(L) / d(z)] * in'
m_dw = blaze::trans(prev_layer_data) * dLz / nobs;
// Derivative for bias, d(L) / d(b) = d(L) / d(z)
m_db = blaze::mean<blaze::columnwise>(dLz);
// Compute d(L) / d_in = W * [d(L) / d(z)]
m_din.resize(nobs, this->inputSize);
m_din = dLz * blaze::trans(m_weight);
// std::cout << "m_dw" << std::endl;
// std::cout << m_dw << std::endl;
// std::cout << "m_b" << std::endl;
// std::cout << m_db << std::endl;
}
const Matrix &backprop_data() const { return m_din; }
void update(Optimizer<Scalar> &opt)
{
/*
ConstAlignedMapVec dw(m_dw.data(), blaze::size(m_dw));
ConstAlignedMapVec db(m_db.data(), m_db.size());
AlignedMapVec w(m_weight.data(), blaze::size(m_weight));
AlignedMapVec b(m_bias.data(), m_bias.size());
*/
opt.update(m_dw, m_weight);
opt.update(m_db, m_bias);
}
std::vector<std::vector<Scalar>> getParameters() const
{
std::vector<std::vector<Scalar>> parameters(2);
parameters[0].resize(blaze::size(m_weight));
parameters[1].resize(m_bias.size());
std::copy(m_weight.data(), m_weight.data() + blaze::size(m_weight), parameters[0].begin());
std::copy(m_bias.data(), m_bias.data() + m_bias.size(), parameters[1].begin());
return parameters;
}
void setParameters(const std::vector<std::vector<Scalar>> ¶meters)
{
/*if (static_cast<int>(param.size()) != blaze::size(m_weight) + m_bias.size())
{
throw std::invalid_argument("Parameter size does not match");
}*/
std::copy(parameters[0].begin(), parameters[0].begin() + blaze::size(m_weight), m_weight.data());
std::copy(parameters[1].begin(), parameters[1].begin() + blaze::size(m_bias), m_bias.data());
}
std::vector<Scalar> get_derivatives() const
{
std::vector<Scalar> res(blaze::size(m_dw) + m_db.size());
// Copy the data of weights and bias to a long vector
std::copy(m_dw.data(), m_dw.data() + blaze::size(m_dw), res.begin());
std::copy(m_db.data(), m_db.data() + m_db.size(), res.begin() + blaze::size(m_dw));
return res;
}
std::vector<size_t> getOutputShape() const { return {(size_t)this->outputSize}; }
};
} // namespace dnn
} // namespace metric
#endif /* LAYER_FULLYCONNECTED_H_ */
| 6,459
|
C++
|
.h
| 164
| 36.664634
| 99
| 0.667999
|
metric-space-ai/metric
| 34
| 14
| 44
|
MPL-2.0
|
9/20/2024, 10:43:29 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,531,715
|
Conv2d.h
|
metric-space-ai_metric/metric/utils/dnn/Layer/Conv2d.h
|
#ifndef LAYER_CONVOLUTIONAL_H_
#define LAYER_CONVOLUTIONAL_H_
#include <chrono>
#include <stdexcept>
#include "../Layer.h"
#include "../Utils/Convolution.h"
#include "../Utils/Random.h"
namespace metric::dnn {
///
/// \ingroup Layers
///
/// Conv2dTranspose hidden layer
///
/// Currently only supports the "valid" rule of convolution.
///
template <typename Scalar, typename Activation> class Conv2d : public Layer<Scalar> {
public:
using Matrix = blaze::DynamicMatrix<Scalar>;
protected:
using SparseMatrix = blaze::CompressedMatrix<Scalar, blaze::columnMajor>;
using ColumnMatrix = blaze::DynamicMatrix<Scalar, blaze::columnMajor>;
using Vector = blaze::DynamicVector<Scalar, blaze::rowVector>;
using SparseVector = blaze::CompressedVector<Scalar, blaze::rowVector>;
// using ConstAlignedMapVec = const blaze::CustomVector<Scalar, blaze::aligned, blaze::unpadded>;
// using AlignedMapVec = blaze::CustomVector<Scalar, blaze::aligned, blaze::unpadded>;
size_t inputWidth;
size_t inputHeight;
size_t kernelWidth;
size_t kernelHeight;
size_t outputWidth;
size_t outputHeight;
size_t inputChannels;
size_t outputChannels;
size_t stride;
bool isZeroPadding;
bool isTranspose;
std::vector<SparseMatrix> unrolledKernels;
blaze::CompressedMatrix<size_t, blaze::columnMajor> unrolledKernelMap;
std::vector<std::vector<size_t>> kernelMasks;
Vector kernelsData; // Filter parameters. Total length is
// (in_channels x out_channels x filter_rows x filter_cols)
// See Utils/Convolution.h for its layout
Vector df_data; // Derivative of filters, same dimension as m_filter_data
Vector bias; // Bias term for the output channels, out_channels x 1. (One bias term per channel)
Vector db; // Derivative of bias, same dimension as m_bias
Matrix z; // Linear term, z = conv(in, w) + b. Each column is an observation
Matrix a; // Output of this layer, a = act(z)
Matrix din; // Derivative of the input of this layer
// Note that input of this layer is also the output of previous layer
public:
Conv2d(const size_t inputSize, const size_t outputSize) : Layer<Scalar>(inputSize, outputSize) {}
///
/// Constructor
///
/// \param inputWidth Width of the input image in each channel.
/// \param inputHeight Height of the input image in each channel.
/// \param inputChannels Number of input channels.
/// \param outputChannels Number of output channels.
/// \param kernelWidth Width of the filter.
/// \param kernelHeight Height of the filter.
///
Conv2d(const size_t inputWidth, const size_t inputHeight, const size_t inputChannels, const size_t outputChannels,
const size_t kernelWidth, const size_t kernelHeight, const size_t stride = 1, bool isZeroPadding = false)
: Layer<Scalar>(inputWidth * inputHeight * inputChannels, ((inputWidth - kernelWidth) / stride + 1) *
((inputHeight - kernelHeight) / stride + 1) *
outputChannels),
inputWidth(inputWidth), inputHeight(inputHeight), kernelWidth(kernelWidth), kernelHeight(kernelHeight),
inputChannels(inputChannels), outputChannels(outputChannels), stride(stride), isZeroPadding(isZeroPadding),
outputWidth(isZeroPadding ? inputWidth : (inputWidth - kernelWidth) / stride + 1),
outputHeight(isZeroPadding ? inputHeight : (inputHeight - kernelHeight) / stride + 1)
{
this->inputSize = inputChannels * inputWidth * inputHeight;
this->outputSize = outputChannels * outputWidth * outputHeight;
// Set data dimension
const size_t kernelDataSize = inputChannels * outputChannels * kernelWidth * kernelHeight;
kernelsData.resize(kernelDataSize);
df_data.resize(kernelDataSize);
// Bias term
bias.resize(outputChannels);
db.resize(outputChannels);
isTranspose = false;
calculateUnrolledKernelStructure();
getUnrolledKernel();
}
explicit Conv2d(const nlohmann::json &json)
: inputWidth(json["inputWidth"].get<int>()), inputHeight(json["inputHeight"].get<int>()),
kernelWidth(json["kernelWidth"].get<int>()), kernelHeight(json["kernelHeight"].get<int>()),
inputChannels(json["inputChannels"].get<int>()), outputChannels(json["outputChannels"].get<int>()),
stride(json["stride"].get<int>()), isZeroPadding(json.value("zeroPadding", false))
{
outputWidth = isZeroPadding ? inputWidth : (inputWidth - kernelWidth) / stride + 1;
outputHeight = isZeroPadding ? inputHeight : (inputHeight - kernelHeight) / stride + 1;
this->inputSize = inputChannels * inputWidth * inputHeight;
this->outputSize = outputChannels * outputWidth * outputHeight;
// Set data dimension
const size_t kernelDataSize = inputChannels * outputChannels * kernelWidth * kernelHeight;
kernelsData.resize(kernelDataSize);
df_data.resize(kernelDataSize);
// Bias term
bias.resize(outputChannels);
db.resize(outputChannels);
isTranspose = false;
calculateUnrolledKernelStructure();
getUnrolledKernel();
}
void init(const Scalar &mu, const Scalar &sigma, std::mt19937 &rng)
{
// Random initialization of filter parameters
internal::set_normal_random(kernelsData.data(), kernelsData.size(), rng, mu, sigma);
internal::set_normal_random(bias.data(), outputChannels, rng, mu, sigma);
getUnrolledKernel();
}
void init(const std::map<std::string, std::shared_ptr<Initializer<Scalar>>> initializers)
{
initializers.at("normal")->init(kernelsData.size(), kernelsData);
initializers.at("zero")->init(bias.size(), bias);
}
SparseMatrix constructBaseUnrolledKernel(size_t fromWidth, size_t fromHeight, size_t toWidth, size_t toHeight)
{
/* Parse padded input */
size_t paddingWidth = 0;
size_t paddingHeight = 0;
if (isZeroPadding) {
paddingWidth = (kernelWidth - 1) / 2;
paddingHeight = (kernelHeight - 1) / 2;
}
SparseMatrix unrolledKernel(fromWidth * fromHeight, toWidth * toHeight);
unrolledKernel.reserve(toHeight * toWidth * kernelHeight * kernelWidth);
size_t column = 0;
for (int i0 = -paddingHeight; i0 <= (int)(fromHeight + paddingHeight - kernelHeight); i0 += stride) {
for (int j0 = -paddingWidth; j0 <= (int)(fromWidth + paddingWidth - kernelWidth); j0 += stride) {
std::vector<size_t> kernelMask;
size_t c = 0;
for (int ki = 0; ki < kernelHeight; ++ki) {
for (int kj = 0; kj < kernelWidth; ++kj) {
int i = i0 + ki;
int j = j0 + kj;
if ((i < 0) || (i >= fromHeight) || (j < 0) || (j >= fromWidth)) {
kernelMask.push_back(c);
} else {
unrolledKernel.append(i * fromWidth + j, column, ki * kernelWidth + kj + 1);
}
++c;
}
}
unrolledKernel.finalize(column);
kernelMasks.push_back(kernelMask);
++column;
}
}
return unrolledKernel;
}
void calculateUnrolledKernelStructure()
{
/* Init unrolled kernels */
unrolledKernels.resize(outputChannels,
SparseMatrix(inputChannels * inputWidth * inputHeight, outputWidth * outputHeight));
SparseMatrix unrolledKernel0;
if (isTranspose) {
unrolledKernel0 =
blaze::trans(constructBaseUnrolledKernel(outputWidth, outputHeight, inputWidth, inputHeight));
unrolledKernelMap = unrolledKernel0;
} else {
unrolledKernel0 = constructBaseUnrolledKernel(inputWidth, inputHeight, outputWidth, outputHeight);
}
for (auto &unrolledKernel : unrolledKernels) {
for (size_t inputChannel = 0; inputChannel < inputChannels; ++inputChannel) {
blaze::submatrix(unrolledKernel, inputChannel * inputHeight * inputWidth, 0, inputHeight * inputWidth,
unrolledKernel.columns()) = unrolledKernel0;
}
}
}
void getUnrolledKernel()
{
const size_t kernelOneLength = kernelWidth * kernelHeight;
const size_t kernelOutputChannelLength = inputChannels * kernelOneLength;
for (size_t outputChannel = 0; outputChannel < outputChannels; ++outputChannel) {
auto &unrolledKernelInputChannels = unrolledKernels[outputChannel];
auto kernelDataInputChannels =
blaze::subvector(kernelsData, outputChannel * kernelOutputChannelLength, kernelOutputChannelLength);
const size_t unrolledKernelRowsNumber = unrolledKernelInputChannels.rows() / inputChannels;
for (size_t inputChannel = 0; inputChannel < inputChannels; ++inputChannel) {
auto unrolledKernel =
blaze::submatrix(unrolledKernelInputChannels, inputChannel * unrolledKernelRowsNumber, 0,
unrolledKernelRowsNumber, unrolledKernelInputChannels.columns());
auto kernelData =
blaze::subvector(kernelDataInputChannels, inputChannel * kernelOneLength, kernelOneLength);
/* Fill unrolled kernel */
if (isTranspose) {
for (size_t i = 0; i < unrolledKernel.columns(); ++i) {
assert(blaze::column(unrolledKernel, i).nonZeros() ==
blaze::column(unrolledKernelMap, i).nonZeros());
for (auto [element, map] = std::tuple(unrolledKernel.begin(i), unrolledKernelMap.begin(i));
element != unrolledKernel.end(i); ++element, ++map) {
element->value() = kernelData[map->value() - 1];
}
}
} else {
for (size_t i = 0; i < unrolledKernel.columns(); ++i) {
auto me = kernelMasks[i].begin();
auto element = unrolledKernel.begin(i);
for (auto k = 0; k < kernelData.size(); ++k) {
if (!kernelMasks[i].empty() && (*me == k)) {
++me;
} else {
element++->value() = kernelData[k];
}
}
}
}
}
}
}
void forward(const Matrix &prev_layer_data)
{
// Each row is an observation
const size_t nobs = prev_layer_data.rows();
// Linear term, z = conv(in, w) + b
z.resize(nobs, this->outputSize);
// cout << prev_layer_data;
// cout << getUnrolledKernel() << endl;
// cout << m_filter_data << endl;
// cout << unrolledKernel << endl;
const size_t channel_nelem = outputWidth * outputHeight;
for (size_t channel = 0; channel < outputChannels; ++channel) {
blaze::submatrix(z, 0, channel * channel_nelem, nobs, channel_nelem) =
prev_layer_data * unrolledKernels[channel];
}
// Add bias terms
// Each row of z contains m_dim.out_channels channels, and each channel has
// m_dim.conv_rows * m_dim.conv_cols elements
size_t channel_start_row = 0;
for (size_t i = 0; i < outputChannels; i++, channel_start_row += channel_nelem) {
submatrix(z, 0, channel_start_row, nobs, channel_nelem) += bias[i];
}
/* Apply activation function */
a.resize(nobs, this->outputSize);
Activation::activate(z, a);
}
const Matrix &output() const { return a; }
// prev_layer_data: getInputSize x nobs
// next_layer_data: getOutputSize x nobs
// https://grzegorzgwardys.wordpress.com/2016/04/22/8/
void backprop(const Matrix &prev_layer_data, const Matrix &next_layer_data)
{
const size_t nobs = prev_layer_data.rows();
ColumnMatrix dLz = z;
// Matrix dLz = z;
Activation::apply_jacobian(z, a, next_layer_data, dLz);
const size_t outputChannelElementsNumber = outputWidth * outputHeight;
const size_t kernelOutputChannelLength = inputChannels * kernelWidth * kernelHeight;
auto t1 = std::chrono::high_resolution_clock::now();
/* Derivative for kernel */
ColumnMatrix kernelDerivatives(nobs, kernelsData.size(), 0);
/* Parse output channels */
for (size_t outputChannel = 0; outputChannel < outputChannels; ++outputChannel) {
auto dLzChannel = blaze::submatrix(dLz, 0, outputChannel * outputChannelElementsNumber, nobs,
outputChannelElementsNumber);
auto kernelDerivativesChannel = blaze::submatrix(
kernelDerivatives, 0, outputChannel * kernelOutputChannelLength, nobs, kernelOutputChannelLength);
ColumnMatrix W(inputChannels * inputWidth * inputHeight, outputChannelElementsNumber);
for (size_t observation = 0; observation < nobs; ++observation) {
auto previousObservation = blaze::trans(blaze::row(prev_layer_data, observation));
for (size_t k = 0; k < dLzChannel.columns(); ++k) {
blaze::column(W, k) = previousObservation * dLzChannel(observation, k);
}
/* Parse input channels */
for (size_t inputChannel = 0; inputChannel < inputChannels; ++inputChannel) {
auto kdic = blaze::submatrix(kernelDerivativesChannel, 0, inputChannel * kernelWidth * kernelHeight,
nobs, kernelWidth * kernelHeight);
auto wic = blaze::submatrix(W, inputChannel * inputWidth * inputHeight, 0, inputWidth * inputHeight,
W.columns());
for (size_t k = 0; k < wic.columns(); ++k) {
auto wice = wic.begin(k);
auto me = kernelMasks[k].begin();
for (size_t j = 0; j < kdic.columns(); ++j) {
if (*me == j) {
++me;
} else {
kdic(observation, j) += *wice;
}
}
}
}
}
}
auto t2 = std::chrono::high_resolution_clock::now();
auto d = std::chrono::duration_cast<std::chrono::duration<double>>(t2 - t1);
// std::cout << "time: " << d.count() << " s" << std::endl;
/* Average over observations */
df_data = blaze::mean<blaze::columnwise>(kernelDerivatives);
/* Derivative for bias */
for (size_t channel = 0; channel < outputChannels; ++channel) {
blaze::DynamicVector<Scalar> d = blaze::sum<blaze::rowwise>(
blaze::submatrix(dLz, 0, channel * outputChannelElementsNumber, nobs, outputChannelElementsNumber));
db[channel] = blaze::mean(d);
}
/* Derivative for input */
din.resize(nobs, this->inputSize);
for (size_t channel = 0; channel < outputChannels; ++channel) {
din += blaze::submatrix(dLz, 0, channel * outputChannelElementsNumber, nobs, outputChannelElementsNumber) *
blaze::trans(unrolledKernels[0]);
}
}
const Matrix &backprop_data() const { return din; }
void update(Optimizer<Scalar> &opt)
{
/*ConstAlignedMapVec dw(df_data.data(), df_data.size());
ConstAlignedMapVec dbConst(db.data(), db.size());
AlignedMapVec w(kernelsData.data(), kernelsData.size());
AlignedMapVec b(bias.data(), bias.size());*/
opt.update(df_data, kernelsData);
opt.update(db, bias);
getUnrolledKernel();
}
std::vector<std::vector<Scalar>> getParameters() const
{
std::vector<std::vector<Scalar>> parameters(2);
// kernels
std::copy(kernelsData.data(), kernelsData.data() + kernelsData.size(), parameters[0].begin());
// bias
std::copy(bias.data(), bias.data() + bias.size(), parameters[1].begin());
return parameters;
}
void setParameters(const std::vector<std::vector<Scalar>> ¶meters)
{
/*if (static_cast<int>(param.size()) != blaze::size(m_weight) + m_bias.size())
{
throw std::invalid_argument("Parameter size does not match");
}*/
// std::cout << parameters[0].size() << " " << kernelsData.size() << std::endl;
assert(parameters[0].size() == kernelsData.size());
assert(parameters[1].size() == bias.size());
std::copy(parameters[0].begin(), parameters[0].begin() + blaze::size(kernelsData), kernelsData.data());
std::copy(parameters[1].begin(), parameters[1].begin() + blaze::size(bias), bias.data());
getUnrolledKernel();
}
std::vector<Scalar> get_derivatives() const
{
std::vector<Scalar> res(df_data.size() + db.size());
// Copy the data of filters and bias to a long vector
std::copy(df_data.data(), df_data.data() + df_data.size(), res.begin());
std::copy(db.data(), db.data() + db.size(), res.begin() + df_data.size());
return res;
}
std::vector<size_t> getOutputShape() const { return {outputWidth, outputHeight}; }
};
} // namespace metric::dnn
#endif /* LAYER_CONVOLUTIONAL_H_ */
| 15,368
|
C++
|
.h
| 349
| 40.071633
| 115
| 0.704787
|
metric-space-ai/metric
| 34
| 14
| 44
|
MPL-2.0
|
9/20/2024, 10:43:29 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,531,716
|
Convolution.h
|
metric-space-ai_metric/metric/utils/dnn/Utils/Convolution.h
|
#ifndef UTILS_CONVOLUTION_H_
#define UTILS_CONVOLUTION_H_
namespace metric {
namespace dnn {
namespace internal {
struct ConvDims {
// Input parameters
const int in_channels;
const int out_channels;
const int channel_rows;
const int channel_cols;
const int filter_rows;
const int filter_cols;
// Image dimension -- one observation with all channels
const int img_rows;
const int img_cols;
// Dimension of the convolution result for each output channel
const int conv_rows;
const int conv_cols;
ConvDims(const int in_channels_, const int out_channels_, const int channel_rows_, const int channel_cols_,
const int filter_rows_, const int filter_cols_)
: in_channels(in_channels_), out_channels(out_channels_), channel_rows(channel_rows_),
channel_cols(channel_cols_), filter_rows(filter_rows_), filter_cols(filter_cols_), img_rows(channel_rows_),
img_cols(in_channels_ * channel_cols_), conv_rows(channel_rows_ - filter_rows_ + 1),
conv_cols(channel_cols_ - filter_cols_ + 1)
{
}
};
} // namespace internal
} // namespace dnn
} // namespace metric
#endif /* UTILS_CONVOLUTION_H_ */
| 1,117
|
C++
|
.h
| 32
| 32.75
| 111
| 0.742144
|
metric-space-ai/metric
| 34
| 14
| 44
|
MPL-2.0
|
9/20/2024, 10:43:29 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,531,717
|
Random.h
|
metric-space-ai_metric/metric/utils/dnn/Utils/Random.h
|
#ifndef UTILS_RANDOM_H_
#define UTILS_RANDOM_H_
#include <random>
#include <blaze/Math.h>
namespace metric {
namespace dnn {
namespace internal {
template <typename DerivedX, typename DerivedY, typename XType, typename YType>
int create_shuffled_batches(const DerivedX &x, const DerivedY &y, int batchSize, std::mt19937 &rng,
std::vector<XType> &xBatches, std::vector<YType> &yBatches)
{
const int observationsNumber = x.rows();
const int dimX = x.columns();
const int dimY = y.columns();
if (y.rows() != observationsNumber) {
throw std::invalid_argument("Input X and Y have different number of observations");
}
// Randomly shuffle the IDs
std::vector<int> id(observationsNumber);
std::iota(id.begin(), id.end(), 0);
std::shuffle(id.begin(), id.end(), rng);
// Compute batch size
if (batchSize > observationsNumber) {
batchSize = observationsNumber;
}
const int batchesNumber = (observationsNumber - 1) / batchSize + 1;
const int lastBatchSize = observationsNumber - (batchesNumber - 1) * batchSize;
// Create shuffled data
xBatches.clear();
yBatches.clear();
xBatches.reserve(batchesNumber);
yBatches.reserve(batchesNumber);
for (int i = 0; i < batchesNumber; i++) {
const int currentBatchSize = (i == batchesNumber - 1) ? lastBatchSize : batchSize;
xBatches.push_back(XType(currentBatchSize, dimX));
yBatches.push_back(YType(currentBatchSize, dimY));
// Copy data
const int offset = i * batchSize;
for (int j = 0; j < currentBatchSize; j++) {
blaze::row(xBatches[i], j) = blaze::row(x, id[offset + j]);
blaze::row(yBatches[i], j) = blaze::row(y, id[offset + j]);
}
}
return batchesNumber;
}
// Fill array with N(mu, sigma^2) random numbers
template <typename Scalar>
inline void set_normal_random(Scalar *arr, const int n, std::mt19937 &rng, const Scalar &mu = Scalar(0),
const Scalar &sigma = Scalar(1))
{
std::normal_distribution<Scalar> normalDistribution(mu, sigma);
for (auto i = 0; i < n; ++i) {
arr[i] = normalDistribution(rng);
}
}
} // namespace internal
} // namespace dnn
} // namespace metric
#endif /* UTILS_RANDOM_H_ */
| 2,122
|
C++
|
.h
| 59
| 33.525424
| 104
| 0.714914
|
metric-space-ai/metric
| 34
| 14
| 44
|
MPL-2.0
|
9/20/2024, 10:43:29 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,531,719
|
lapack.hpp
|
metric-space-ai_metric/metric/utils/wrappers/lapack.hpp
|
#ifndef PANDA_METRIC_LAPACK_HPP
#define PANDA_METRIC_LAPACK_HPP
#include <blaze/Math.h>
extern "C" {
extern void dsygv_(int *itype, char *jobz, char *uplo, int *n, double *A, int *LDA, double *B, int *LDB, double *W,
double *WORK, int *LWORK, int *INFO);
}
namespace metric {
inline void dsygv(int itype, char jobz, char uplo, int n, double *A, int lda, double *B, int ldb, double *W,
double *work, int lwork, int info)
{
dsygv_(&itype, &jobz, &uplo, &n, A, &lda, B, &ldb, W, work, &lwork, &info);
}
template <typename MT, typename VT>
void sygv(blaze::DynamicMatrix<MT, blaze::rowMajor> A, blaze::DynamicMatrix<MT, blaze::rowMajor> B,
blaze::DynamicVector<VT, blaze::columnVector> &w)
{
w.resize(A.rows());
int lwork = 3 * A.rows() - 1;
std::vector<double> work(lwork);
int info;
dsygv(1, 'N', 'U', A.rows(), A.data(), A.spacing(), B.data(), B.spacing(), w.data(), work.data(), lwork, info);
}
} // namespace metric
#endif // PANDA_METRIC_LAPACK_HPP
| 981
|
C++
|
.h
| 25
| 37.04
| 115
| 0.669125
|
metric-space-ai/metric
| 34
| 14
| 44
|
MPL-2.0
|
9/20/2024, 10:43:29 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,531,720
|
KolmogorovSmirnov.hpp
|
metric-space-ai_metric/metric/distance/k-random/KolmogorovSmirnov.hpp
|
/*
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/.
Copyright (c) 2020 Panda Team
*/
#ifndef _METRIC_DISTANCE_K_RANDOM_KOLMOGOROV_SMIRNOV_HPP
#define _METRIC_DISTANCE_K_RANDOM_KOLMOGOROV_SMIRNOV_HPP
namespace metric {
/**
* @brief
*
* To compare the two samples, we construct their empirical cumulative distribution functions (CDF). CDFs is calculated
* by PMQ. The Kolmogorov-Smirnov (KS) distance is defined to be the largest absolute difference between the two
* empirical CDFs evaluated at any point.
*
* @tparam Sample - sample type
* @tparam D - distance return type
*/
template <typename Sample, typename D = double> class KolmogorovSmirnov {
public:
using distance_type = D;
/**
* @brief Construct a new Kolmogorov-Smirnov object
*
*/
explicit KolmogorovSmirnov() = default;
/**
* @brief calculate Kolmogorov-Smirnov distance between two samples
*
* @param sample_1 first sample
* @param sample_2 second sample
* @return distance
*/
distance_type operator()(const Sample &sample_1, const Sample &sample_2) const;
};
} // namespace metric
#include "KolmogorovSmirnov.cpp"
#endif
| 1,272
|
C++
|
.h
| 39
| 30.538462
| 119
| 0.757551
|
metric-space-ai/metric
| 34
| 14
| 44
|
MPL-2.0
|
9/20/2024, 10:43:29 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,531,721
|
RandomEMD.hpp
|
metric-space-ai_metric/metric/distance/k-random/RandomEMD.hpp
|
/*
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/.
Copyright (c) 2020 Panda Team
*/
#ifndef _METRIC_DISTANCE_K_RANDOM_EMD_HPP
#define _METRIC_DISTANCE_K_RANDOM_EMD_HPP
namespace metric {
/**
* @brief
*
* Earth Mover�s Distance (EMD), also known as the first Wasserstein distance.
* �hysical interpretation �� the EMDis easy to understand: imagine the two datasets to be piles of earth, and the goal
* is to move the first pile around to match the second. The Earth Mover�s Distance is the minimum amount of work
* involved, where �amount of work� is the amount of earth you have to move multiplied by the distance you have to move
* it. The EMD can also be shown to be equal to the area between the two empirical CDFs, which is calculated py PMQ.
*
* @tparam Sample - sample type
* @tparam D - distance return type
*/
template <typename Sample, typename D = double> struct RandomEMD {
using distance_type = D;
/**
* @brief Construct a new EMD object
*
*/
explicit RandomEMD() = default;
/**
* @brief Construct a new EMD object
*
* @param precision used for integration. Should be in (0, 1). Less means more accurate.
*/
explicit RandomEMD(double precision) : precision(precision) {}
/**
* @brief calculate EMD distance between two samples
*
* @param sample_1 first sample
* @param sample_2 second sample
* @return distance
*/
distance_type operator()(const Sample &sample_1, const Sample &sample_2) const;
private:
const double precision = 0.01;
};
} // namespace metric
#include "RandomEMD.cpp"
#endif
| 1,719
|
C++
|
.h
| 48
| 33.333333
| 119
| 0.738919
|
metric-space-ai/metric
| 34
| 14
| 44
|
MPL-2.0
|
9/20/2024, 10:43:29 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,531,722
|
CramervonMises.hpp
|
metric-space-ai_metric/metric/distance/k-random/CramervonMises.hpp
|
/*
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/.
Copyright (c) 2020 Panda Team
*/
#ifndef _METRIC_DISTANCE_K_RANDOM_CRAMER_VON_MISES_HPP
#define _METRIC_DISTANCE_K_RANDOM_CRAMER_VON_MISES_HPP
namespace metric {
/**
* @brief
*
* The Cramér-von Mises (CM) distance is obtained by summing the squared difference between the two empirical CDFs along
* the x-axis (and then taking the square root of the sum to make it an actual distance). The relationship between the
* CM distance and the EMD is analogous to that of the L1 and L2 norms. CDFs is calculated by PMQ.
*
* @tparam Sample - sample type
* @tparam D - distance return type
*/
template <typename Sample, typename D = double> class CramervonMises {
public:
using distance_type = D;
/**
* @brief Construct a new Cramer-von Nises object
*
*/
explicit CramervonMises() = default;
/**
* @brief Construct a new Cramer-von Nises object
*
* @param precision for integration. Should be in (0, 1). Less means more accurate.
*/
explicit CramervonMises(double precision) : precision(precision) {}
/**
* @brief calculate Cramer-von Nises distance between two samples
*
* @param sample_1 first sample
* @param sample_2 second sample
* @return distance
*/
distance_type operator()(const Sample &sample_1, const Sample &sample_2) const;
private:
double precision = 0.01;
};
} // namespace metric
#include "CramervonMises.cpp"
#endif
| 1,582
|
C++
|
.h
| 47
| 31.361702
| 120
| 0.742932
|
metric-space-ai/metric
| 34
| 14
| 44
|
MPL-2.0
|
9/20/2024, 10:43:29 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,531,723
|
Riemannian.hpp
|
metric-space-ai_metric/metric/distance/d-spaced/Riemannian.hpp
|
#ifndef PANDA_METRIC_RIEMANNIAN_HPP
#define PANDA_METRIC_RIEMANNIAN_HPP
#include "metric/distance/k-related/Standards.hpp"
namespace metric {
template <typename RecType, typename Metric = Euclidean<typename RecType::value_type>> class RiemannianDistance {
public:
RiemannianDistance(Metric metric = Metric()) : metric(metric) {}
template <typename C> double operator()(const C &Xc, const C &Yc) const;
template <typename T> T matDistance(blaze::DynamicMatrix<T> A, blaze::DynamicMatrix<T> B) const;
template <typename Container>
double estimate(const Container &a, const Container &b, const size_t sampleSize = 250,
const double threshold = 0.05, size_t maxIterations = 1000) const;
private:
Metric metric;
};
} // namespace metric
#include "Riemannian.cpp"
#endif // PANDA_METRIC_RIEMANNIAN_HPP
| 820
|
C++
|
.h
| 18
| 43.222222
| 113
| 0.774275
|
metric-space-ai/metric
| 34
| 14
| 44
|
MPL-2.0
|
9/20/2024, 10:43:29 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,531,724
|
Standards.hpp
|
metric-space-ai_metric/metric/distance/k-related/Standards.hpp
|
/*
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/.
Copyright (c) 2018 Michael Welsch
*/
#ifndef _METRIC_DISTANCE_K_RELATED_STANDARDS_HPP
#define _METRIC_DISTANCE_K_RELATED_STANDARDS_HPP
#include <cmath>
#include <type_traits>
#include <vector>
namespace metric {
/**
* @class Euclidean
*
* @brief Euclidean (L2) Metric
*/
template <typename V = double> struct Euclidean {
using value_type = V;
using distance_type = value_type;
explicit Euclidean() = default;
/**
* @brief Calculate Euclidean distance in R^n
*
* @param a first vector
* @param b second vector
* @return Euclidean distance between a and b
*/
template <typename Container>
typename std::enable_if<!std::is_same<Container, V>::value, distance_type>::type
operator()(const Container &a, const Container &b) const;
/**
* @brief Calculate Euclidean distance in R
*
* @param a first value
* @param b second value
* @return Euclidean distance between a and b
*/
distance_type operator()(const V &a, const V &b) const;
/**
* @brief Calculate Euclidean distance for Blaze input
*
* @param a first value
* @param b second value
* @return Euclidean distance between a and b
*/
template <template <typename, bool> class Container, typename ValueType, bool F> // detect Blaze object by signature
double operator()(const Container<ValueType, F> &a, const Container<ValueType, F> &b) const;
};
/**
* @class Manhatten
*
* @brief Manhatten/Cityblock (L1) Metric
*
*/
template <typename V = double> struct Manhatten {
using value_type = V;
using distance_type = value_type;
explicit Manhatten() = default;
/**
* @brief Calculate Manhatten distance in R^n
*
* @param a first vector
* @param b second vector
* @return Manhatten distance between a and b
*/
template <typename Container> distance_type operator()(const Container &a, const Container &b) const;
};
/**
* @class P_norm
*
* @brief Minkowski (L general) Metric
*
*/
template <typename V = double> struct P_norm {
using value_type = V;
using distance_type = value_type;
// P_norm() = default;
/**
* @brief Construct a new P_norm object
*
* @param p_
*/
explicit P_norm(const value_type &p_ = 1) : p(p_) {}
/**
* @brief calculate Minkowski distance
*
* @param a first vector
* @param b second vector
* @return Minkowski distance between a and b
*/
template <typename Container> distance_type operator()(const Container &a, const Container &b) const;
value_type p = 1;
};
/**
* @class Euclidean_threshold
*
* @brief Minkowski Metric (L... / P_Norm)
*
*/
template <typename V = double> struct Euclidean_thresholded {
using value_type = V;
using distance_type = value_type;
explicit Euclidean_thresholded() = default;
/**
* @brief Construct a new Euclidean_thresholded object
*
* @param thres_
* @param factor_
*/
Euclidean_thresholded(value_type thres_, value_type factor_) : thres(thres_), factor(factor_) {}
/**
* @brief
*
* @param a
* @param b
* @return
*/
template <typename Container> distance_type operator()(const Container &a, const Container &b) const;
value_type thres = 1000.0;
value_type factor = 3000.0;
};
template <typename V = double> struct Euclidean_hard_clipped {
using value_type = V;
using distance_type = value_type;
value_type max_distance_;
value_type scal_;
explicit Euclidean_hard_clipped() = default;
/**
* @brief Construct a new Euclidean_hard_clipped object
*
* @param max_distance
* @param scal
*/
Euclidean_hard_clipped(value_type max_distance = 100, value_type scal = 1)
: max_distance_(max_distance), scal_(scal)
{
}
/**
* @brief
*
* @param a
* @param b
* @return
*/
template <typename Container> distance_type operator()(const Container &a, const Container &b) const;
};
template <typename V = double> struct Euclidean_soft_clipped {
using value_type = V;
using distance_type = value_type;
value_type max_distance_;
value_type scal_;
value_type thresh_;
value_type F_;
value_type x_;
value_type T_;
value_type y_;
explicit Euclidean_soft_clipped() = default;
/**
* @brief Construct a new Euclidean_hard_clipped object
*
* @param max_distance
* @param scal
* @param threshold
*/
Euclidean_soft_clipped(value_type max_distance = 100, value_type scal = 1, value_type thresh = 0.8)
: max_distance_(max_distance), scal_(scal), thresh_(thresh)
{
F_ = (value_type(1) - thresh_) * max_distance;
x_ = thresh_ * max_distance / scal;
T_ = F_ / scal_;
y_ = thresh_ * max_distance;
}
/**
* @brief
*
* @param a
* @param b
* @return
*/
template <typename Container> distance_type operator()(const Container &a, const Container &b) const;
};
template <typename V = double> struct Euclidean_standardized {
using value_type = V;
using distance_type = value_type;
std::vector<value_type> mean;
std::vector<value_type> sigma;
explicit Euclidean_standardized() = default;
/**
* @brief Construct a new Euclidean_hard_clipped object
*
* @param A
*/
template <typename Container> Euclidean_standardized(const Container &A);
/**
* @brief
*
* @param a
* @param b
* @return
*/
template <typename Container> auto operator()(const Container &a, const Container &b) const -> distance_type;
};
template <typename V = double> struct Manhatten_standardized {
using value_type = V;
using distance_type = value_type;
std::vector<value_type> mean;
std::vector<value_type> sigma;
explicit Manhatten_standardized() = default;
/**
* @brief Construct a new Manhatten_hard_clipped object
*
* @param A
*/
template <typename Container> Manhatten_standardized(const Container &A);
/**
* @brief
*
* @param a
* @param b
* @return
*/
template <typename Container> auto operator()(const Container &a, const Container &b) const -> distance_type;
};
/**
* @class Cosine
*
* @brief Cosine similarity
*
*/
template <typename V = double> struct Cosine {
using value_type = V;
using distance_type = value_type;
/**
* @brief calculate cosine similariy between two non-zero vector
*
* @param a first vector
* @param b second vector
* @return cosine similarity between a and b
*/
template <typename Container> distance_type operator()(const Container &a, const Container &b) const;
};
template <typename V = double> struct Weierstrass {
using value_type = V;
using distance_type = value_type;
/**
* @brief calculate Weierstrass distance between two non-zero vector
*
* @param a first vector
* @param b second vector
* @return Weierstrass distance between a and b
*/
template <typename Container> distance_type operator()(const Container &a, const Container &b) const;
};
/**
* @class CosineInverted
*
* @brief CosineInverted similarity. Means 1 - Cosine.
*
*/
template <typename V = double> struct CosineInverted {
using value_type = V;
using distance_type = value_type;
/**
* @brief calculate cosine similariy between two non-zero vector
*
* @param a first vector
* @param b second vector
* @return cosine similarity between a and b
*/
template <typename Container> distance_type operator()(const Container &a, const Container &b) const;
};
/**
* @class Chebyshev
*
* @brief Chebyshev metric
*
*/
template <typename V = double> struct Chebyshev {
using value_type = V;
using distance_type = value_type;
explicit Chebyshev() = default;
/**
* @brief calculate chebyshev metric
*
* @param lhs first container
* @param rhs second container
* @return Chebtshev distance between lhs and rhs
*/
template <typename Container> distance_type operator()(const Container &lhs, const Container &rhs) const;
};
} // namespace metric
#include "Standards.cpp"
#endif // Header Guard
| 7,913
|
C++
|
.h
| 294
| 24.482993
| 117
| 0.710603
|
metric-space-ai/metric
| 34
| 14
| 44
|
MPL-2.0
|
9/20/2024, 10:43:29 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,531,725
|
L1.hpp
|
metric-space-ai_metric/metric/distance/k-related/L1.hpp
|
/*
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/.
Copyright (c) 2019 Panda Team
*/
#ifndef _METRIC_DISTANCE_K_RELATED_L1_HPP
#define _METRIC_DISTANCE_K_RELATED_L1_HPP
#include <blaze/Blaze.h>
namespace metric {
template <typename V = double> class Sorensen {
public:
using distance_type = V;
explicit Sorensen() = default;
/**
* @brief
*
* @param a
* @param b
* @return
*/
template <typename Container>
typename std::enable_if<!std::is_same<Container, V>::value, distance_type>::type
operator()(const Container &a, const Container &b) const;
/**
* @brief
*
* @param a
* @param b
* @return
*/
distance_type operator()(const blaze::CompressedVector<V> &a, const blaze::CompressedVector<V> &b) const;
// TODO add support of 1D random values passed in simple containers
};
template <typename V = double> struct Hassanat {
using value_type = V;
using distance_type = value_type;
explicit Hassanat() = default;
/**
* @brief Calculate Hassanat distance in R^n
*
* @param a first vector
* @param b second vector
* @return Hassanat distance between a and b
*/
template <typename Container> distance_type operator()(const Container &a, const Container &b) const;
};
template <typename Value>
double sorensen(const blaze::CompressedVector<Value> &a, const blaze::CompressedVector<Value> &b);
template <typename V = double> struct Ruzicka {
using value_type = V;
using distance_type = value_type;
explicit Ruzicka() = default;
/**
* @brief Calculate Ruzicka distance in R^n
*
* @param a first vector
* @param b second vector
* @return Ruzicka distance between a and b
*/
template <typename Container> distance_type operator()(const Container &a, const Container &b) const;
};
} // namespace metric
#include "L1.cpp"
#endif // Header Guard
| 1,963
|
C++
|
.h
| 65
| 27.815385
| 106
| 0.726692
|
metric-space-ai/metric
| 34
| 14
| 44
|
MPL-2.0
|
9/20/2024, 10:43:29 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,531,726
|
EMD.hpp
|
metric-space-ai_metric/metric/distance/k-structured/EMD.hpp
|
/*
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/.
Copyright (c) 2018 Michael Welsch
*/
#ifndef _METRIC_DISTANCE_K_STRUCTURED_EMD_HPP
#define _METRIC_DISTANCE_K_STRUCTURED_EMD_HPP
#include <vector>
namespace metric {
/**
* @class EMD
*
* @brief Earth mover's distance
*
*/
template <typename V> class EMD {
public:
using value_type = V;
using distance_type = value_type;
explicit EMD() {}
/**
* @brief Construct a new EMD object with cost matrix
*
* @param C_ cost matrix
*/
explicit EMD(std::vector<std::vector<value_type>> &&C_) : C(C_), is_C_initialized(true) {}
/**
* @brief Construct a new EMD object
*
* @param rows, cols size of cost matrix
* @param extra_mass_penalty_
* @param F_
*/
EMD(std::size_t rows, std::size_t cols, const value_type &extra_mass_penalty_ = -1,
std::vector<std::vector<value_type>> *F_ = nullptr)
: C(default_ground_matrix(rows, cols)), extra_mass_penalty(extra_mass_penalty_), F(F_), is_C_initialized(true)
{
}
/**
* @brief Construct a new EMD object
*
* @param C_ cost matrix
* @param extra_mass_penalty_
* @param F_
*/
EMD(const std::vector<std::vector<value_type>> &C_, const value_type &extra_mass_penalty_ = -1,
std::vector<std::vector<value_type>> *F_ = nullptr)
: C(C_), extra_mass_penalty(extra_mass_penalty_), F(F_), is_C_initialized(true)
{
}
/**
* @brief Calculate EMD distance between Pc and Qc
*
* @tparam Container
* @param Pc
* @param Qc
* @return
*/
template <typename Container> distance_type operator()(const Container &Pc, const Container &Qc) const;
EMD(EMD &&) = default;
EMD(const EMD &) = default;
EMD &operator=(const EMD &) = default;
EMD &operator=(EMD &&) = default;
private:
mutable std::vector<std::vector<value_type>> C;
value_type extra_mass_penalty = -1;
std::vector<std::vector<value_type>> *F = nullptr;
mutable bool is_C_initialized = false;
std::vector<std::vector<value_type>> default_ground_matrix(std::size_t rows, std::size_t cols) const;
};
} // namespace metric
#include "EMD.cpp"
#endif // Header Guard
| 2,224
|
C++
|
.h
| 74
| 27.702703
| 112
| 0.689284
|
metric-space-ai/metric
| 34
| 14
| 44
|
MPL-2.0
|
9/20/2024, 10:43:29 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| true
| false
|
1,531,727
|
Kohonen.hpp
|
metric-space-ai_metric/metric/distance/k-structured/Kohonen.hpp
|
/*
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/.
Copyright (c) 2018 Panda Team
*/
#ifndef _METRIC_DISTANCE_K_STRUCTURED_KOHONEN_HPP
#define _METRIC_DISTANCE_K_STRUCTURED_KOHONEN_HPP
#include "metric/mapping/Redif.hpp"
#include "metric/mapping/SOM.hpp"
#include "metric/utils/graph.hpp"
namespace metric {
/**
* @class Kohonen
*
* @brief
*
* The idea of the Kohonen distance is: to train a SOM on a dataset and then compute the EMD (shortest path between
* SOM's graph nodes) for two records in the Kohonen space.
*
* The egdes of the SOM graph (distances between nodes) are the ground distance for the EMD.
* Then for every record, to get a vector of distances between all SOM nodes, it is weights for ground distances.
* Having the vectors and ground distances we can compute EMD. It is a Kohonen distance.
*
*/
template <typename D, typename Sample, typename Graph = metric::Grid4, typename Metric = metric::Euclidean<D>,
typename Distribution = std::uniform_real_distribution<typename Sample::value_type>>
class Kohonen {
public:
using distance_type = D;
/**
* @brief Construct a new Kohonen object.
*
* This construtor used when you have custom and pretrained SOM model.
*
* @param som_model - trained SOM model.
* @param samples - training dataset.
* @param use_sparsification - if true then sparcification optimization will be performed on the graph. This
* optimization delete some edges of the graph to fit the train dataset better.
* @param sparsification_coef - coefficient using for sparcification. Should be from 0 to 1. Value is set a percent
* of the edges that will be left in the graph.
* @param use_reverse_diffusion - if true then reverse diffusion optimization will be performed on the graph. This
* optimization move graph nodes to the encoded points from trained on dataset Rediff object. See `metric::Redif`
* for details.
* @param reverse_diffusion_neighbors - number of neighbors used for reverse diffusion optimization.
*/
Kohonen(metric::SOM<Sample, Graph, Metric, Distribution> &&som_model, const std::vector<Sample> &samples,
bool use_sparsification = false, double sparsification_coef = 1.0, bool use_reverse_diffusion = false,
size_t reverse_diffusion_neighbors = 10);
/**
* @brief Construct a new Kohonen object
*
* This construtor used when you have custom and pretrained SOM model.
*
* @param som_model - trained SOM model.
* @param samples - training dataset.
* @param use_sparsification - if true then sparcification optimization will be performed on the graph. This
* optimization delete some edges of the graph to fit the train dataset better.
* @param sparsification_coef - coefficient using for sparcification. Should be from 0 to 1. Value is set a percent
* of the edges that will be left in the graph.
* @param use_reverse_diffusion - if true then reverse diffusion optimization will be performed on the graph. This
* optimization move graph nodes to the encoded points from trained on dataset Rediff object. See `metric::Redif`
* for details.
* @param reverse_diffusion_neighbors - number of neighbors used for reverse diffusion optimization.
*/
Kohonen(const metric::SOM<Sample, Graph, Metric, Distribution> &som_model, const std::vector<Sample> &samples,
bool use_sparsification = false, double sparsification_coef = 1.0, bool use_reverse_diffusion = false,
size_t reverse_diffusion_neighbors = 10);
/**
* @brief Construct a new Kohonen object
*
* This construtor is for quick distance object creation. Just set width and height of the graph (use Grid4, Grid6
* or Grid8) and constructor will create Graph, SOM model, train SOM and object will be ready to use.
*
* @param samples - samples for SOM train.
* @param nodesWidth - width of the SOM grid.
* @param nodesHeight - height of the SOM grid.
* @param use_sparsification - if true then sparcification optimization will be performed on the graph. This
* optimization delete some edges of the graph to fit the train dataset better.
* @param sparsification_coef - coefficient using for sparcification. Should be from 0 to 1. Value is set a percent
* of the edges that will be left in the graph.
* @param use_reverse_diffusion - if true then reverse diffusion optimization will be performed on the graph. This
* optimization move graph nodes to the encoded points from trained on dataset Rediff object. See `metric::Redif`
* for details.
* @param reverse_diffusion_neighbors - number of neighbors used for reverse diffusion optimization.
*/
Kohonen(const std::vector<Sample> &samples, size_t nodesWidth, size_t nodesHeight, bool use_sparsification = false,
double sparsification_coef = 1.0, bool use_reverse_diffusion = false,
size_t reverse_diffusion_neighbors = 10);
/**
* @brief Construct a new Kohonen object
*
* This construtor is for detailed creation of the distance object. SOM model will be created and trained by
* constructor and object will be ready to use.
*
* @param samples - samples for SOM train.
* @param graph - graph for SOM model.
* @param metric - metric for SOM model
* @param start_learn_rate - learning rate for SOM model at the start of train.
* @param finish_learn_rate - learning rate for SOM model at the end of train.
* @param iterations - number of iterations for SOM model train.
* @param distribution - initial distribution of the weights of the SOM model before train.
* @param use_sparsification - if true then sparcification optimization will be performed on the graph. This
* optimization delete some edges of the graph to fit the train dataset better.
* @param sparsification_coef - coefficient using for sparcification. Should be from 0 to 1. Value is set a percent
* of the edges that will be left in the graph.
* @param use_reverse_diffusion - if true then reverse diffusion optimization will be performed on the graph. This
* optimization move graph nodes to the encoded points from trained on dataset Rediff object. See `metric::Redif`
* for details.
* @param reverse_diffusion_neighbors - number of neighbors used for reverse diffusion optimization.
*/
Kohonen(const std::vector<Sample> &samples, Graph graph, Metric metric = Metric(), double start_learn_rate = 0.8,
double finish_learn_rate = 0.0, size_t iterations = 20, Distribution distribution = Distribution(-1, 1),
bool use_sparsification = false, double sparsification_coef = 1.0, bool use_reverse_diffusion = false,
size_t reverse_diffusion_neighbors = 10);
/**
* @brief Compute the EMD for two records in the Kohonen space.
*
* @param sample_1 first sample
* @param sample_2 second sample
* @return distance on kohonen space
*/
distance_type operator()(const Sample &sample_1, const Sample &sample_2) const;
/**
* @brief
* Recursive function that reconstructs the shortest path backwards node by node and print it
*
* @param from_node - index of the SOM's graph start node
* @param to_node second sample - index of the SOM's graph end node
*/
void print_shortest_path(int from_node, int to_node) const;
/**
* @brief
* Recursive function that reconstructs the shortest path backwards node by node
*
* @param from_node - index of the SOM's graph start node
* @param to_node second sample - index of the SOM's graph end node
*/
std::vector<int> get_shortest_path(int from_node, int to_node) const;
/**
* @brief
* Distortion estimate method. it is a measure of the nonlinearity of a dataset.
* Calculates by taking the factor between all euclidean and Kohonen distances of a dataset.
* Then rescaling these factors from all pair-wise comparisons (like rescaling a histogram).
* And the distortion is the variance of this histogram.
*
* @param samples - dataset for estimation.
*/
double distortion_estimate(const std::vector<Sample> &samples);
/**
* @brief
* SOM model used in the core of Kohonen distance object.
*/
metric::SOM<Sample, Graph, Metric, Distribution> som_model;
/**
* @brief
* Matrix with EMD distances between SOM nodes.
*/
std::vector<std::vector<D>> distance_matrix;
/**
* @brief
* Predecessors matrix for all SOM nodes.
*/
std::vector<std::vector<int>> predecessors;
private:
/**
* @brief
* If true then sparcification optimization will be performed on the graph. This optimization delete some edges of
* the graph to fit the train dataset better.
*/
bool use_sparsification_ = false;
/**
* @brief
* Coefficient using for sparcification. Should be from 0 to 1. Value is set a percent of the edges that will be
* left in the graph.
*/
double sparsification_coef_ = 1;
/**
* @brief
* If true then reverse diffusion optimization will be performed on the graph. This optimization move graph nodes to
* the encoded points from trained on dataset Rediff object. See `metric::Redif` for details.
*/
bool use_reverse_diffusion_ = false;
/**
* @brief
* Number of neighbors used for reverse diffusion optimization.
*/
double reverse_diffusion_neighbors_ = 10;
/**
* @brief
*/
Metric metric;
/**
* @brief
* Method calculates matrix with direct (based for SOM) distances between SOM nodes.
*/
void calculate_distance_matrix(const std::vector<Sample> &samples);
/**
* @brief
* This optimization delete some edges of the graph to fit the train dataset better.
*
* @param direct_distance_matrix - direct (based for SOM) distance matrix between SOM nodes. This matrix will be
* modifed while optimization.
*/
void sparcify_graph(blaze::CompressedMatrix<D> &direct_distance_matrix);
/**
* @brief
* This optimization move graph nodes to the encoded points from trained on dataset Rediff object. See
* `metric::Redif` for details.
*/
void make_reverese_diffusion(const std::vector<Sample> &samples);
/**
* @brief
* Recursive function that reconstructs the shortest path backwards node by node
*
* @param from_node - index of the SOM's graph start node
* @param to_node second sample - index of the SOM's graph end node
*/
std::vector<int> get_shortest_path_(std::vector<int> &path, int from_node, int to_node) const;
/**
* @brief return closest node from SOM's graph that was not visited while paths calculations.
* @return the index of closest nodes was not visited
*/
int get_closest_unmarked_node(const std::vector<D> &distance, const std::vector<bool> &mark,
int numOfVertices) const;
/**
* @brief
* Computes the shortest path
*/
auto calculate_distance(const blaze::CompressedMatrix<D> &adjMatrix, int from_node, int num) const
-> std::tuple<std::vector<D>, std::vector<int>>;
std::vector<std::pair<size_t, size_t>> sort_indexes(const blaze::CompressedMatrix<D> &matrix);
};
} // namespace metric
#include "Kohonen.cpp"
#endif // Header Guard
| 11,016
|
C++
|
.h
| 236
| 43.868644
| 117
| 0.746092
|
metric-space-ai/metric
| 34
| 14
| 44
|
MPL-2.0
|
9/20/2024, 10:43:29 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,531,728
|
SSIM.hpp
|
metric-space-ai_metric/metric/distance/k-structured/SSIM.hpp
|
/*
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/.
Copyright (c) 2018 Michael Welsch
*/
#ifndef _METRIC_DISTANCE_K_STRUCTURED_SSIM_HPP
#define _METRIC_DISTANCE_K_STRUCTURED_SSIM_HPP
namespace metric {
/**
* @class SSIM
*
* @brief structural similarity (for images)
*
*/
template <typename D, typename V> // added D as distance_type (to get f.e. double distance for int values of pixels) ->
// Stepan Mamontov
struct SSIM {
using value_type = V;
using distance_type = D;
explicit SSIM() = default;
/**
* @brief Construct a new SSIM object
*
* @param dynamic_range_ dynamic range of the pixel values
* @param masking_
*/
SSIM(const typename V::value_type dynamic_range_, const typename V::value_type masking_)
: dynamic_range(dynamic_range_), masking(masking_)
{
}
/**
* @brief Calculate structural similarity for images in given containers
*
* @param img1 first image
* @param img2 second image
* @return structural similarity
*/
template <typename Container> distance_type operator()(const Container &img1, const Container &img2) const;
typename V::value_type dynamic_range = 255.0;
typename V::value_type masking = 2.0;
};
} // namespace metric
#include "SSIM.cpp"
#endif // Header Guard
| 1,407
|
C++
|
.h
| 45
| 28.688889
| 119
| 0.723908
|
metric-space-ai/metric
| 34
| 14
| 44
|
MPL-2.0
|
9/20/2024, 10:43:29 PM (Europe/Amsterdam)
| false
| false
| false
| false
| true
| false
| true
| false
|
1,531,729
|
TWED.hpp
|
metric-space-ai_metric/metric/distance/k-structured/TWED.hpp
|
/*
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/.
Copyright (c) 2018 Michael Welsch
*/
#ifndef _METRIC_DISTANCE_K_RANDOM_TWED_HPP
#define _METRIC_DISTANCE_K_RANDOM_TWED_HPP
#include <blaze/Math.h>
namespace metric {
/**
* @class TWED
*
* @brief Time warp Elastic Distance (for curves)
*/
template <typename V> struct TWED {
using value_type = V;
using distance_type = value_type;
/**
* @brief Construct a new TWED object
*
* @param penalty_
* @param elastic_
*/
TWED(const value_type &penalty_ = 0, const value_type &elastic_ = 1) : penalty(penalty_), elastic(elastic_) {}
/**
* @brief Calculate TWE distance between given containers
*
* @param As first container
* @param Bs second container
* @return TWE distance between given containers
*/
template <typename Container> value_type operator()(const Container &As, const Container &Bs) const;
value_type penalty = 0;
value_type elastic = 1;
bool is_zero_padded = false;
};
} // namespace metric
#include "TWED.cpp"
#endif // Header Guard
| 1,181
|
C++
|
.h
| 40
| 27.4
| 111
| 0.72679
|
metric-space-ai/metric
| 34
| 14
| 44
|
MPL-2.0
|
9/20/2024, 10:43:29 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| true
| false
|
1,531,730
|
Edit.hpp
|
metric-space-ai_metric/metric/distance/k-structured/Edit.hpp
|
/*
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/.
Copyright (c) 2018 Michael Welsch
*/
#ifndef _METRIC_DISTANCE_K_STRUCTURED_EDIT_HPP
#define _METRIC_DISTANCE_K_STRUCTURED_EDIT_HPP
#include <string_view>
namespace metric {
/**
* @class Edit
* @breaf Edit distance(for strings)
* @tparam
*/
template <typename V> struct Edit {
using value_type = V;
using distance_type = int;
/**
* @brief Calculate Edit distance between two STL-like containers
*
* @tparam Container
* @param str1
* @param str2
* @return Edit distance between str1 and str2
*/
template <typename Container> distance_type operator()(const Container &str1, const Container &str2) const;
/**
* @brief calculate Edit distance for null terminated strings
*
* @param str1
* @param str2
* @return Edit distance between str1 and str2
*/
distance_type operator()(const V *str1, const V *str2) const
{
return this->operator()(std::basic_string_view<V>(str1), std::basic_string_view<V>(str2));
}
};
} // namespace metric
#include "Edit.cpp"
#endif // Header Guard
| 1,213
|
C++
|
.h
| 42
| 26.738095
| 108
| 0.730868
|
metric-space-ai/metric
| 34
| 14
| 44
|
MPL-2.0
|
9/20/2024, 10:43:29 PM (Europe/Amsterdam)
| false
| false
| false
| false
| true
| false
| true
| false
|
1,531,731
|
knn_graph.hpp
|
metric-space-ai_metric/metric/space/knn_graph.hpp
|
/*
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/.
Copyright (c) 2020 Panda Team
*/
#ifndef _METRIC_SPACE_KNN_GRAPH_HPP
#define _METRIC_SPACE_KNN_GRAPH_HPP
#include "metric/utils/graph.hpp"
#include "metric/utils/type_traits.hpp"
#include <type_traits>
#include <vector>
namespace metric {
/**
* @class KNNGraph
* @brief Fast hierarchical method algorithm that constructs an approximate kNN graph.
* The method is simple and it works with any type of data for which a distance function can be provided.
* Algorithm has two parts. In the first part we create a crude approximation of the graph by subdividing
* the dataset until each subset reaches given max_bruteforce_size.
* In the second part this approximation is iteratively fine-tuned by combining the first algorithm with NN-descent
* method.
*
*/
template <typename Sample, typename Distance, typename WeightType = bool, bool isDense = false, bool isSymmetric = true>
class KNNGraph : public Graph<WeightType, isDense, isSymmetric> {
public:
using distance_type = typename Distance::distance_type;
/**
* @brief Construct a new KNN Graph object
*
*/
template <typename Container,
typename = std::enable_if<std::is_same_v<Sample, type_traits::index_value_type_t<Container>>>>
KNNGraph(const Container &X, size_t neighbors_num, size_t max_bruteforce_size, int max_iterations = 100,
double update_range = 0.02);
///**
// * @brief Construct a new KNN Graph object
// *
// */
// KNNGraph(Tree<Sample, Distance>& tree, size_t neighbors_num, size_t max_bruteforce_size, int max_iterations =
// 100, double update_range = 0.02);
///**
// * @brief Construct a new KNN Graph object
// *
// */
// KNNGraph(std::vector<std::vector<typename Distance::value_type>> distance_matrix);
size_t neighbors_num() const { return _neighbors_num; }
const Sample &get_node_data(size_t i) const { return _nodes[i]; }
std::vector<std::size_t> gnnn_search(const Sample &query, int max_closest_num, int iterations = 10,
int num_greedy_moves = -1, int num_expansions = -1);
/**
* @brief return value with index equals idx
* @param idx index of searching value
*/
const Sample &operator[](std::size_t idx) const { return _nodes[idx]; }
/**
* @brief return distance between elements with indexes i and j
* @param i index of the first element
* @param j index of the second element
*/
distance_type operator()(std::size_t i, std::size_t j) const { return _distance_matrix[i][j]; }
/**
* @brief insert new element into the graph
* @param p new element
* return index of the inserted element
*/
std::size_t insert(const Sample &p);
/**
* @brief insert set of the new elements into the graph
* @param p - container with new elements
* @return vector of indexes of the new elements
*/
template <typename Container,
typename = std::enable_if<std::is_same<
Sample, typename std::decay<decltype(std::declval<Container &>().operator[](0))>::type>::value>>
std::vector<std::size_t> insert(const Container &p);
/**
* @brief insert new element into the graph if distance between this element and its NN is greater than threshold
* @param p new element
* @param threshold distance threshold
* @return pair consist of index and result of insertion
*/
std::pair<std::size_t, bool> insert_if(const Sample &p, distance_type threshold);
/**
* @brief append data records into the Matrix only if distance bigger than a threshold
*
* @param items set of new records
* @param treshold distance threshold
* @return vector of pairs consists of indexes and results of insertion
*/
template <typename Container,
typename = std::enable_if<std::is_same<
Sample, typename std::decay<decltype(std::declval<Container &>().operator[](0))>::type>::value>>
std::vector<std::pair<std::size_t, bool>> insert_if(const Container &items, distance_type threshold);
/**
* @brief find nearest neighbour
* @param p searching value
* @return index of NN in graph
*/
std::size_t nn(const Sample &p);
/**
* @brief find K nearest neighbours
* @param p searching value
* @param K amount of neighbours
* @return vector of indexes of NN's in graph
*/
std::vector<std::size_t> knn(const Sample &p, std::size_t K) const;
/**
* @brief find all nearest neighbours in sphere of radius threshold
* @param p searching value
* @param threshold radius of threshold sphere
* @return vector of indexes of NN's in graph and distances to searching value
*/
auto rnn(const Sample &x, distance_type threshold) const -> std::vector<std::pair<std::size_t, distance_type>>;
/**
* @brief erase element from graph
* @param idx index of erasing element
*/
void erase(std::size_t idx);
/**
* @brief return size of graph
*
*/
std::size_t size() const { return _nodes.size(); }
protected:
size_t _neighbors_num = 1;
size_t _max_bruteforce_size = 10;
int _max_iterations = 100;
double _update_range = 0.02;
bool _not_more_neighbors = false;
std::vector<Sample> _nodes;
std::vector<std::vector<distance_type>> _distance_matrix;
private:
/**
* @brief
*
*/
template <typename Container,
typename = std::enable_if<std::is_same_v<Sample, type_traits::index_value_type_t<Container>>>>
void construct(const Container &X);
/**
* @brief
*
*/
template <typename Container,
typename = std::enable_if<std::is_same_v<Sample, type_traits::index_value_type_t<Container>>>>
void calculate_distance_matrix(const Container &X);
/**
* @brief
*
*/
template <typename Container,
typename = std::enable_if<std::is_same_v<Sample, type_traits::index_value_type_t<Container>>>>
void make_edge_pairs(const Container &X);
/**
* @brief
*
*/
template <typename Container,
typename = std::enable_if<std::is_same_v<Sample, type_traits::index_value_type_t<Container>>>>
std::vector<std::pair<size_t, size_t>> brute_force(const Container &samples, const std::vector<int> &ids);
/**
* @brief
*
*/
template <typename Container,
typename = std::enable_if<std::is_same_v<Sample, type_traits::index_value_type_t<Container>>>>
std::vector<std::pair<size_t, size_t>> random_pair_division(const Container &samples, const std::vector<int> &ids,
int max_size);
/**
* @brief
*
*/
template <typename T1> std::vector<size_t> sort_indexes(const std::vector<T1> &v);
};
} // namespace metric
#include "knn_graph.cpp"
#endif
| 6,603
|
C++
|
.h
| 178
| 34.235955
| 120
| 0.710576
|
metric-space-ai/metric
| 34
| 14
| 44
|
MPL-2.0
|
9/20/2024, 10:43:29 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,531,732
|
tree.hpp
|
metric-space-ai_metric/metric/space/tree.hpp
|
/*
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/.
Copyright (c) 2018, Michael Welsch
*/
#ifndef _METRIC_SPACE_TREE_HPP
#define _METRIC_SPACE_TREE_HPP
#include <blaze/Math.h>
#include <atomic>
#include <cmath>
#include <fstream>
#include <functional>
#include <iostream>
#include <map>
#include <numeric>
#include <shared_mutex>
#include <stack>
#include <string>
#include <tuple>
#include <unordered_map>
#include <unordered_set>
#include <vector>
namespace metric {
/*
_ \ _| | | \ | | _)
| | -_) _| _` | | | | _| |\/ | -_) _| _| | _|
___/ \___| _| \__,_| \_,_| _| \__| _| _| \___| \__| _| _| \__|
*/
/*** standard Euclidean (L2) Metric ***/
template <typename, typename> struct SerializedNode;
template <typename, typename> class Node;
struct unsorted_distribution_exception : public std::exception {
};
struct bad_distribution_exception : public std::exception {
};
/*
__ __|
| _ | -_) -_)
_| _| \___| \___|
*/
/*** Cover Tree Implementation ***/
template <class RecType, class Metric> class Tree {
public:
using NodeType = Node<RecType, Metric>;
using Node_ptr = Node<RecType, Metric> *;
using TreeType = Tree<RecType, Metric>;
using rset_t = std::tuple<Node_ptr, std::vector<Node_ptr>, std::vector<Node_ptr>>;
using Distance = typename std::invoke_result<Metric, const RecType &, const RecType &>::type;
/***
@brief cluster tree nodes according to distribution
@param distribution vector with percents of amount of nodes, this vector should be sorted,
otherwise metric_space::unsorted_distribution_exception would be thrown. If distribution vector
containd value less than zero or greate than 1, the metric_space::bad_distribution_exception would be thrown.
@param points vector with data values
@param indexes indexes in points vector, as a source set only data records with corresponding indices will be
used.
@return vector of vector of node IDs according to distribution
*/
std::vector<std::vector<std::size_t>> clustering(const std::vector<double> &distribution,
const std::vector<std::size_t> &indexes,
const std::vector<RecType> &points);
/***
@brief cluster tree nodes according to distribution
@param distribution vector with percents of amount of nodes, this vector should be sorted,
otherwise metric_space::unsorted_distribution_exception would be thrown. If distribution vector
containd value less than zero or greate than 1, the metric_space::bad_distribution_exception would be thrown.
@param IDS id's of nodes in tree, these nodes would be used as a source set.
@return vector of vector of node IDs according to distribution
*/
std::vector<std::vector<std::size_t>> clustering(const std::vector<double> &distribution,
const std::vector<std::size_t> &IDS);
/***
@brief cluster tree nodes according to distribution
@param distribution vector with percents of amount of nodes, this vector should be sorted,
otherwise metric_space::unsorted_distribution_exception would be thrown. If distribution vector
containd value less than zero or greate than 1, the metric_space::bad_distribution_exception would be thrown.
@param points vector with data values. these values would be used as a source set.
*/
std::vector<std::vector<std::size_t>> clustering(const std::vector<double> &distribution,
const std::vector<RecType> &points);
/**
* @brief deserialize tree from Archive
*
* @param input serialization object
* @param stream underlying input stream
*/
template <class Archive, class Stream> void deserialize(Archive &input, Stream &stream);
/**
* @brief Serialize tree to archive
*
* @param archive serialization object
*/
template <class Archive> void serialize(Archive &archive);
/*
* Set of default methods
*
*/
Tree(const Tree &) = delete;
Tree(Tree &&) noexcept = default; // need to clone the tree
auto operator=(Tree &&) noexcept -> Tree & = default;
auto operator=(const Tree &) -> Tree & = delete; // need to clone the tree
/*** Constructors ***/
/**
* @brief Construct an empty Tree object
*
* @param truncate truncate paramter
* @param d metric object
*/
Tree(int truncate = -1, Metric d = Metric()); // empty tree
/**
* @brief Construct a Tree object with one data record as root
*
* @param p data record
* @param truncate truncate parameter
* @param d metric object
*/
Tree(const RecType &p, int truncate = -1, Metric d = Metric()); // cover tree with one data record as root
/**
* @brief Construct a Tree object from data vector
*
* @param p vector of data records to store in tree
* @param truncate truncate paramter
* @param d metric object
*/
template <typename Container>
Tree(const Container &p, int truncate = -1, Metric d = Metric()); // with a vector of data records
/**
* @brief Destroy the Tree object
*
*/
~Tree(); // Destructor
/*** Access Operations ***/
/**
* @brief Insert date record to the cover tree
*
* @param p data record
* @return ID of inserted node
*/
std::size_t insert(const RecType &p);
/**
* @brief Insert set of data records to the cover tree
*
* @param p vector of data records
* @return true if inserting successful
* @return false if inserting unsuccessful
*/
bool insert(const std::vector<RecType> &p);
/**
* @brief inser data record to the tree if distance between NN and new point is greater than a threshold
*
* @param p new data record
* @param treshold distance threshold
* @return ID of inserted node and true if inserting successful
* @return ID of NN node and false if inserting unsuccessful
*/
std::tuple<std::size_t, bool> insert_if(const RecType &p, Distance treshold);
/**
* @brief inser set of data records to the tree if distance between root and new point is greater than a threshold
*
* @param p vector of new data records
* @param treshold distance threshold
* @return std::size_t amount of inserted points
*/
std::size_t insert_if(const std::vector<RecType> &p, Distance treshold);
/**
* @brief erase data record from cover tree
*
* @param p data record to erase
* @return true if erase successful
* @return false if erase unsuccessful
*/
bool erase(const RecType &p);
/**
* @brief access data record by ID
*
* @param id data record ID
* @return data record with ID == id
* @throws std::runtime_error when tree has no element with ID
*/
RecType operator[](size_t id) const;
/*** Nearest Neighbour search ***/
/**
* @brief find nearest neighbour of data record
*
* @param p searching data record
* @return Node containing nearest neigbour to p
*/
Node_ptr nn(const RecType &p) const;
/**
* @brief find K-nearest neighbour of data record
*
* @param p searching data record
* @param k amount of nearest neighbours
* @return vector of pair of node pointer and distance to searching point
*/
std::vector<std::pair<Node_ptr, Distance>> knn(const RecType &p, unsigned k = 10) const;
/**
* @brief find all nearest neighbour in range [0;distance]
*
* @param p searching point
* @param distance max distance to searching point
* @return vector of pair of node pointer and distance to searching point
*/
std::vector<std::pair<Node_ptr, Distance>> rnn(const RecType &p, Distance distance = 1.0) const;
/*** utilitys ***/
/**
* @brief tree size
*
* @return return amount of nodes
*/
size_t size();
/**
* @brief traverse tree and apply callback function to each node
*
* @param f node callback
*/
void traverse(const std::function<void(Node_ptr)> &f);
/** Dev Tools **/
/**
* @brief return the max_level of the tree (= root level)
*
* @return level of the root node
*/
int levelSize();
/**
* @brief pretty print tree to stdout
*
*/
void print() const;
/**
* @brief pretty print tree to provided stream
*
* @param ostr
*/
void print(std::ostream &ostr) const;
/**
* @brief print and return levels information
*
* @return map { level -> amount of nodes at this level}
*/
std::map<int, unsigned> print_levels();
/**
* @brief convert tree to vector
*
* @return vector of data records stored in the tree
*/
std::vector<RecType> toVector();
/**
* @brief serialize tree to JSON, with custom data record serialzer
*
* @param printer function converting data record to JSON
* @return JSON representation of tree
*/
std::string to_json(std::function<std::string(const RecType &)> printer);
/**
* @brief serialize tree to JSON
*
* @return JSON representation of tree
*/
std::string to_json();
/**
* @brief check tree covering invariant
*
* @return true if tree is ok
* @return false if tree is corrupted
*/
bool check_covering() const;
/**
* @brief traverse tree except root node
*
* @param f callback for nodes
*/
void traverse_child(const std::function<void(Node_ptr)> &f);
/**
* @brief Get the root node
*
* @return root node
*/
Node_ptr get_root() { return root; }
/**
* @brief check is tree empty
*
* @return true if tree has no nodes
* @return false if tree has at least one node
*/
bool empty() const { return root == nullptr; }
/**
* @brief compare two trees
*
* @param lhs root node of the first tree
* @param rhs root node of the second tree
* @return true if lhs and rhs has the same structure
* @return false if lhs and rhs differs
*/
bool same_tree(const Node_ptr lhs, const Node_ptr rhs) const;
/**
* @brief recursively iterate through the tree and return all nodes of the tree
*
* @return return all nodes of the tree
*/
auto get_all_nodes() -> std::vector<Node_ptr>;
/**
* @brief compare tree with another
*
* @param t another tree
* @return true if trees equivalent
* @return false if trees differs
*/
bool operator==(const Tree &t) const { return same_tree(root, t.root); }
/**
* @brief writing tree to stream, same as print(std::ostream)
*
* @param ostr output stream
* @param t tree
* @return stream reference
*/
friend std::ostream &operator<<(std::ostream &ostr, const Tree &t)
{
t.print(ostr);
return ostr;
}
/**
* @brief Computes graph distance between two nodes
* @param id1 - ID of the first node
* @param id2 - ID of the second node
* @return weighted sum of edges between nodes
*/
Distance distance_by_id(std::size_t id1, std::size_t id2) const;
/**
* @brief Computes graph distance between two records
* @param p1 - first record
* @param p2 - second record
* @return weighted sum of edges between nodes nearest to p1 and p2
*/
Distance distance(const RecType &p1, const RecType &p2) const;
/**
* @brief convert cover tree to distance matrix
* @return blaze::CompressedMatrix with distances between nodes,
* Since the matrix is symmetric, we fill only the upper right part of the matrix,
* so matrix will have only N*(N-1)/2 non zeroes elements;
*
*/
blaze::CompressedMatrix<Distance, blaze::rowMajor> matrix() const;
/**
* @brief distance between two nodes
* @param id1 ID of the first node
* @param id2 ID of the second node
* @return distance between nodes
*/
Distance operator()(std::size_t id1, std::size_t id2) const;
private:
friend class Node<RecType, Metric>;
/*** Types ***/
Metric metric_;
/*** Properties ***/
Distance base = 2; // Base for estimating the covering of the tree
Node_ptr root = nullptr; // Root of the tree
std::atomic<int> min_scale; // Minimum scale
std::atomic<int> max_scale; // Minimum scale
int truncate_level = -1; // Relative level below which the tree is truncated
std::atomic<std::size_t> nextID = 0; // Next node ID
mutable std::shared_timed_mutex global_mut; // lock for changing the root
std::vector<std::pair<RecType, Node_ptr>> data;
std::unordered_map<std::size_t, std::size_t> index_map; // ID -> data index mapping
// /*** Implementation Methods ***/
Node_ptr insert(Node_ptr p, Node_ptr x);
template <typename pointOrNodeType>
std::tuple<std::vector<int>, std::vector<Distance>> sortChildrenByDistance(Node_ptr p, pointOrNodeType x) const;
bool grab_sub_tree(Node_ptr proot, const RecType ¢er, std::unordered_set<std::size_t> &parsed_points,
const std::vector<std::size_t> &distribution_sizes, std::size_t &cur_idx,
std::vector<std::vector<std::size_t>> &result);
bool grab_tree(Node_ptr start_point, const RecType ¢er, std::unordered_set<std::size_t> &parsed_points,
const std::vector<std::size_t> &distribution_sizes, std::size_t &cur_idx,
std::vector<std::vector<std::size_t>> &result);
double find_neighbour_radius(const std::vector<std::size_t> &IDS, const std::vector<RecType> &points);
double find_neighbour_radius(const std::vector<std::size_t> &IDS);
double find_neighbour_radius(const std::vector<RecType> &points);
// template <typename pointOrNodeType>
Node_ptr insert_(Node_ptr p, Node_ptr x);
void nn_(Node_ptr current, Distance dist_current, const RecType &p, std::pair<Node_ptr, Distance> &nn) const;
std::size_t knn_(Node_ptr current, Distance dist_current, const RecType &p,
std::vector<std::pair<Node_ptr, Distance>> &nnList, std::size_t nnSize) const;
void rnn_(Node_ptr current, Distance dist_current, const RecType &p, Distance distance,
std::vector<std::pair<Node_ptr, Distance>> &nnList) const;
void print_(NodeType *node_p, std::ostream &ostr) const;
Node_ptr merge(Node_ptr p, Node_ptr q);
std::pair<Node_ptr, std::vector<Node_ptr>> mergeHelper(Node_ptr p, Node_ptr q);
auto findAnyLeaf() -> Node_ptr;
void extractNode(Node_ptr node);
template <class Archive> void serialize_aux(Node_ptr node, Archive &archvie);
Node_ptr rebalance(Node_ptr p, Node_ptr x);
rset_t rebalance_(Node_ptr p, Node_ptr q, Node_ptr x);
std::vector<std::vector<std::size_t>> clustering_impl(const std::vector<double> &distribution,
const RecType ¢er, double radius);
bool update_idx(std::size_t &cur_idx, const std::vector<std::size_t> &distribution_sizes,
std::vector<std::vector<std::size_t>> &result);
Distance metric(const RecType &p1, const RecType &p2) const { return metric_(p1, p2); }
Distance metric_by_id(const std::size_t id1, const std::size_t id2)
{
return metric_(data[index_map[id1]].first, data[index_map[id2]].first);
}
template <class Archive> auto deserialize_node(Archive &istr) -> SerializedNode<RecType, Metric>;
std::size_t add_data(const RecType &p, Node_ptr ptr)
{
data.push_back(std::pair{p, ptr});
auto id = nextID++;
index_map[id] = data.size() - 1;
return id;
}
const RecType &get_data(std::size_t ID) { return data[index_map[ID]].first; }
void remove_data(std::size_t ID)
{
auto p = data.begin();
auto pi = index_map.find(ID);
std::size_t i = pi->second;
std::advance(p, i);
data.erase(p);
index_map.erase(pi);
for (auto &kv : index_map) {
if (kv.first <= i)
continue;
kv.second -= 1;
}
}
std::pair<Distance, std::size_t> distance_to_root(Node_ptr p) const;
std::pair<Distance, std::size_t> distance_to_level(Node_ptr &p, int level) const;
Distance distance_by_node(Node_ptr p1, Node_ptr p2) const;
std::pair<Distance, std::size_t> graph_distance(Node_ptr p1, Node_ptr p2) const;
void get_all_nodes_(Node_ptr node_p, std::vector<Node_ptr> &output);
};
} // namespace metric
#include "tree.cpp" // include the implementation
#endif //_METRIC_SPACE_TREE_HPP
| 15,710
|
C++
|
.h
| 434
| 33.278802
| 115
| 0.6968
|
metric-space-ai/metric
| 34
| 14
| 44
|
MPL-2.0
|
9/20/2024, 10:43:29 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,531,733
|
matrix.hpp
|
metric-space-ai_metric/metric/space/matrix.hpp
|
/*
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/.
Copyright (c) 2018 Michael Welsch
*/
#ifndef _METRIC_SPACE_MATRIX_HPP
#define _METRIC_SPACE_MATRIX_HPP
#include <blaze/Blaze.h>
#include <iostream>
#include <type_traits>
#include <unordered_map>
#include <vector>
namespace metric {
/**
* @class Matrix
*
* @brief distance matrix
*
*/
template <typename RecType, typename Metric> class Matrix {
public:
using distType = typename std::invoke_result<Metric, const RecType &, const RecType &>::type;
/*** Constructors ***/
/**
* @brief Construct a new empty Matrix
*
* @param d metric object to use as distance
*/
explicit Matrix(Metric d = Metric()) : metric_(d) {}
/**
* @brief Construct a new Matrix with one data record
*
* @param p data record
* @param d metric object to use as distance
*/
explicit Matrix(const RecType &p, Metric d = Metric()) : metric_(d) { insert(p); }
/**
* @brief Construct a new Matrix with set of data records
*
* @param p random access container of data records
* @param d metric object to use as distance
*/
template <typename Container,
typename = std::enable_if<std::is_same<
RecType, typename std::decay<decltype(std::declval<Container>().operator[](0))>::type>::value>>
explicit Matrix(const Container &p, Metric d = Metric()) : metric_(d)
{
insert(p);
}
/*
* Set of default methods
*
*/
~Matrix() = default;
Matrix(const Matrix &) = default;
Matrix(Matrix &&) noexcept = default;
auto operator=(Matrix &&) noexcept -> Matrix & = default;
auto operator=(const Matrix &) -> Matrix & = default;
/**
* @brief append data record to the matrix
*
* @param p data record
* @return Index of inserted node
*/
auto insert(const RecType &item) -> std::size_t;
/**
* @brief append data record into the Matrix only if distance bigger than a treshold
*
* @param p data record
* @param treshold distance threshold
* @return pair consist of index and result of insertion
*/
auto insert_if(const RecType &item, distType treshold) -> std::pair<std::size_t, bool>;
/**
* @brief append set of data records to the matrix
*
* @param p random access container with new data records
* @return vector of indexes of inserted node
*/
template <typename Container,
typename = std::enable_if<std::is_same<
RecType, typename std::decay<decltype(std::declval<Container>().operator[](0))>::type>::value>>
auto insert(const Container &items) -> std::vector<std::size_t>;
/**
* @brief append data records into the Matrix only if distance bigger than a treshold
*
* @param p set of data records
* @param treshold distance threshold
* @return vector of pairs consists of ID and result of insertion
*/
template <typename Container,
typename = std::enable_if<std::is_same<
RecType, typename std::decay<decltype(std::declval<Container>().operator[](0))>::type>::value>>
auto insert_if(const Container &items, distType treshold) -> std::vector<std::pair<std::size_t, bool>>;
/**
* @brief erase data record from Matrix by ID
*
* @param index Index of erased data record
* @return true if operation successful
* @return false if operation unsuccessful
*/
auto erase(size_t index) -> bool;
/**
* @brief change data record by ID
*
* @param index Index of data record
* @param p new data record
*/
void set(size_t index, const RecType &p);
/**
* @brief access a data record by ID
*
* @param index data record index
* @return data record at index
* @throws std::runtime_error when index >= size()
*/
auto operator[](size_t index) const -> RecType;
/**
* @brief access a distance by two IDs
*
* @param i row index
* @param j column index
* @return distance between i and j
*/
auto operator()(size_t i, size_t j) const -> distType;
/*** information ***/
/**
* @brief size of matrix
*
* @return amount of data records
*/
auto size() const -> std::size_t;
/**
* @brief find nearest neighbour of data record
*
* @param p searching data record
* @return ID of nearest neighbour to p
*/
auto nn(const RecType &p) const -> std::size_t;
/**
* @brief find K nearest neighbours of data record
*
* @param query searching data record
* @param k amount of nearest neighbours
* @return vector of pair of node ID and distance to searching point
*/
auto knn(const RecType &query, unsigned k = 10) const -> std::vector<std::pair<std::size_t, distType>>;
/**
* @brief find all nearest neighbour in range [0;distance]
*
* @param query searching point
* @param range max distance to searching point
* @return vector of pair of node ID and distance to searching point
*/
auto rnn(const RecType &query, distType range = 1.0) const -> std::vector<std::pair<std::size_t, distType>>;
/**
* @brief debug function, check consistence of distance matrix
*
* @return true if matrix is OK, false otherwise.
*/
auto check_matrix() const -> bool
{
for (std::size_t i = 0; i < data_.size(); i++) {
for (std::size_t j = 0; j < data_.size(); j++) {
auto m = metric_(data_[i], data_[j]);
auto d = (*this)(i, j);
if (std::abs(m - d) >= std::numeric_limits<distType>::epsilon()) {
std::cout << "Check matrix failed at [" << i << "," << j << "] = dist(" << data_[i] << " ,"
<< data_[j] << ") : " << m << " != " << d << std::endl;
return false;
}
}
}
return true;
}
/**
* @brief debug function, print distance matrix to stdout
*
*/
void print() const
{
std::cout << "D_=\n" << D_ << std::endl;
std::cout << "non_zeros=" << D_.nonZeros() << std::endl;
}
private:
auto nn_(const RecType &p) const -> std::pair<std::size_t, distType>;
auto nn_(const RecType &p, std::unordered_map<std::size_t, distType> &metric_cache) const
-> std::pair<std::size_t, distType>;
void check_index(std::size_t index) const
{
if (index >= data_.size()) {
throw std::invalid_argument(std::string("no element with such ID:") + std::to_string(index) +
" >= " + std::to_string(data_.size()));
}
}
void remove_data(std::size_t index)
{
auto p = data_.begin();
std::advance(p, index);
data_.erase(p);
}
/*** Properties ***/
Metric metric_;
blaze::CompressedMatrix<distType> D_;
std::vector<RecType> data_;
mutable std::unordered_map<std::size_t, std::size_t> index_map_;
std::vector<std::size_t> id_map_;
};
} // namespace metric
#include "matrix.cpp"
#endif // headerguard
| 6,637
|
C++
|
.h
| 212
| 28.429245
| 109
| 0.668074
|
metric-space-ai/metric
| 34
| 14
| 44
|
MPL-2.0
|
9/20/2024, 10:43:29 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,531,734
|
mgc.hpp
|
metric-space-ai_metric/metric/correlation/mgc.hpp
|
/*
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/.
Copyright (c) 2018 PANDA Team
*/
/*
MGC - Multiscale Graph Correlation
a correlation coefficient with finds nonlinear dependencies in data sets and is optimized for small sample sizes.
Multiscale Graph Correlation, Bridgeford, Eric W and Shen, Censheng and Wang, Shangsi and Vogelstein, Joshua,
2018, doi = 10.5281/ZENODO.1246967
Copyright (c) 2018, Michael Welsch
*/
#ifndef _METRIC_CORRELATION_DETAILS_MGC_HPP
#define _METRIC_CORRELATION_DETAILS_MGC_HPP
#include <blaze/Blaze.h>
namespace metric {
template <typename T> using DistanceMatrix = blaze::SymmetricMatrix<blaze::DynamicMatrix<T>>;
/** @class MGC
* @brief Multiscale graph correlation
* @tparam RecType1 type of the left hand input
* @tparam Metric1 type of metric associated with RecType1
* @tparam RecType2 type of the right hand input
* @tparam Metric2 type of metric associated with RecType2
*/
template <class RecType1, class Metric1, class RecType2, class Metric2> class MGC {
public:
/**
* @brief Construct MGC object
*
* @param m1 Metric1 object
* @param m2 Metric1 object
*/
explicit MGC(const Metric1 &m1 = Metric1(), const Metric2 &m2 = Metric2()) : metric1(m1), metric2(m2) {}
/** @brief return correlation betweeen a and b
* @param a container of values of type RecType1
* @param b container of values of type RecType2
* @return correlation betwen a and b
*/
template <typename Container1, typename Container2>
double operator()(const Container1 &a, const Container2 &b) const;
/** @brief return estimate of the correlation betweeen a and b
* @param a container of values of type RecType1
* @param b container of values of type RecType2
* @param sampleSize
* @param threshold
* @param maxIterations
* @return estimate of the correlation betwen a and b
*/
template <typename Container1, typename Container2>
double estimate(const Container1 &a, const Container2 &b, const size_t sampleSize = 250,
const double threshold = 0.05, size_t maxIterations = 1000) const;
/** @brief return vector of mgc values calculated for different data shifts
* @param a container of values of type RecType1
* @param b container of values of type RecType2
* @param n number of delayed computations in +/- direction
* @return vector of mgc values calculated for different data shifts
*/
template <typename Container1, typename Container2>
std::vector<double> xcorr(const Container1 &a, const Container2 &b, const int n) const;
/**
* @brief return distance matrix
*
* @param c container of values
* @return distance matrix
*/
template <typename Container, typename Metric>
DistanceMatrix<double> computeDistanceMatrix(const Container &c, const Metric &metric) const;
private:
Metric1 metric1;
Metric2 metric2;
};
/**
* @class MGC_direct
* @brief
*
*/
struct MGC_direct {
/**
* @brief
*
* @tparam T value type of input
* @param a distance matrix
* @param b distance matrix
* @return sample MGC statistic within [-1,1]
*/
template <typename T> T operator()(const DistanceMatrix<T> &a, const DistanceMatrix<T> &b);
/** @brief return vector of mgc values calculated for different data shifts
* @param a distance matrix
* @param b distance matrix
* @param n number of delayed computations in +/- direction
* @return vector of mgc values calculated for different data shifts
*/
template <typename T>
std::vector<double> xcorr(const DistanceMatrix<T> &a, const DistanceMatrix<T> &b, const unsigned int n);
/**
* @brief Computes the centered distance matrix
*
* @tparam T value type of input matrix
* @param X distance matrix
* @return centered distance matrix
*/
template <typename T> blaze::DynamicMatrix<T> center_distance_matrix(const DistanceMatrix<T> &X);
/**
* @brief
*
* @tparam T value type of input matrix
* @param data distance matrix
* @return
*/
template <typename T> blaze::DynamicMatrix<size_t> rank_distance_matrix(const DistanceMatrix<T> &data);
/**
* @brief Computes the ranked centered distance matrix
*
* @tparam T value type of input matrix
* @param X distance matrix
* @return ranked centered distance matrix
*/
template <typename T> blaze::DynamicMatrix<size_t> center_ranked_distance_matrix(const DistanceMatrix<T> &X);
/**
* @brief Computes all local correlations
*
* @tparam T value type of input matrices
* @param A properly transformed distance matrix;
* @param B properly transformed distance matrix;
* @param RX column-ranking matrix of A
* @param RY column-ranking matrix of B
* @return all local covariances matrix
*/
template <typename T>
blaze::DynamicMatrix<T> local_covariance(const blaze::DynamicMatrix<T> &A, const blaze::DynamicMatrix<T> &B,
const blaze::DynamicMatrix<size_t> &RX,
const blaze::DynamicMatrix<size_t> &RY);
/**
* @brief
*
* @param corr[out]
* @param varX [in]
* @param varY [in]
*/
template <typename T>
void normalize_generalized_correlation(blaze::DynamicMatrix<T> &corr, const blaze::DynamicMatrix<T> &varX,
const blaze::DynamicMatrix<T> &varY);
/**
* @brief
*
* @param t
* @return
*/
template <typename T> T rational_approximation(const T t);
/**
* @brief
*
* @param p
* @return
*/
template <typename T> T normal_CDF_inverse(const T p);
/**
* @brief
*
* @param p
* @return
*/
template <typename T> T icdf_normal(const T p);
/**
* @brief Finds a grid of significance in the local correlation matrix by thresholding.
*
* @tparam T value type
* @param localCorr all local correlations
* @param p sample size of original data (which may not equal m or n in case of repeating data).
* @return binary matrix of size m and n, with 1's indicating the significant region
*/
template <typename T>
blaze::DynamicMatrix<bool> significant_local_correlation(const blaze::DynamicMatrix<T> &localCorr, T p = 0.02);
/**
* @brief calculate Frobenius norm of given matrix
*
* @tparam T value type of input matrx
* @param matrix arbitrary matrix
* @return Frobenius norm of given matrix
*/
template <typename T> T frobeniusNorm(const blaze::DynamicMatrix<T> &matrix);
/**
* @brief
*
* @tparam T value type
* @param m1
* @param m2
* @return
*/
template <typename T>
T max_in_matrix_regarding_second_boolean_matrix(const blaze::DynamicMatrix<T> &m1,
const blaze::DynamicMatrix<bool> &m2);
/**
* @brief Finds the maximal scale within the significant grid that is represented by a boolean matrix R,
* @details If the area of R is too small, it return the localCorr.
*
* @tparam T
* @param corr matric of all local correlations
* @param R binary matrix that indicating the significant region of corr´(same size like corr)
* @return sample MGC statistic within [-1,1]
*/
template <typename T>
T optimal_local_generalized_correlation(const blaze::DynamicMatrix<T> &corr, const blaze::DynamicMatrix<bool> &R);
};
} // namespace metric
#include "mgc.cpp"
#endif // header guard
| 7,247
|
C++
|
.h
| 208
| 31.980769
| 115
| 0.729699
|
metric-space-ai/metric
| 34
| 14
| 44
|
MPL-2.0
|
9/20/2024, 10:43:29 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,531,735
|
epmgp.hpp
|
metric-space-ai_metric/metric/correlation/epmgp.hpp
|
/*
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/.
Copyright (c) 2019 Panda Team
*/
// approximation of probability for multidimensional normal distribution bounded by (hyper)rectangle
// https://arxiv.org/pdf/1111.6832.pdf
// based on local_gaussian.m Matlab code
#ifndef _EPMGP_HPP
#define _EPMGP_HPP
#include <blaze/Blaze.h>
#include <cmath>
#include <tuple>
#include <vector>
namespace epmgp {
template <typename T> int sgn(T val)
{ // sign for arbitrary type
return (T(0) < val) - (val < T(0));
}
template <typename T> T erfcx_simple(T x)
{ // for double on x86_64, inf starts at -26
return std::exp(x * x) * std::erfc(x);
}
// https://stackoverflow.com/questions/39777360/accurate-computation-of-scaled-complementary-error-function-erfcx
double erfcx_double(double x);
template <typename T> T erfcx(T x)
{ // for double, inf starts at -26 on x86_64
return (T)erfcx_double((double)x);
}
template <typename T>
auto truncNormMoments(std::vector<T> lowerBIN, std::vector<T> upperBIN, std::vector<T> muIN, std::vector<T> sigmaIN)
-> std::tuple<std::vector<T>, std::vector<T>, std::vector<T>>;
template <typename T>
auto local_gaussian_axis_aligned_hyperrectangles(blaze::DynamicVector<T> m, blaze::DynamicMatrix<T> K,
blaze::DynamicVector<T> lowerB, blaze::DynamicVector<T> upperB)
-> std::tuple<T, blaze::DynamicVector<T>, blaze::DynamicMatrix<T>>;
} // namespace epmgp
#include "epmgp.cpp"
#endif // _EPMGP_HPP
| 1,592
|
C++
|
.h
| 40
| 37.975
| 116
| 0.737801
|
metric-space-ai/metric
| 34
| 14
| 44
|
MPL-2.0
|
9/20/2024, 10:43:29 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,531,736
|
entropy.hpp
|
metric-space-ai_metric/metric/correlation/entropy.hpp
|
/*
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/.
Copyright (c) 2020 Panda Team
*/
#ifndef _METRIC_DISTANCE_K_RANDOM_ENTROPY_HPP
#define _METRIC_DISTANCE_K_RANDOM_ENTROPY_HPP
#include "../distance/k-related/Standards.hpp"
#include "metric/utils/type_traits.hpp"
#include <blaze/Blaze.h>
namespace metric {
// non-kpN version, DEPRECATED
template <typename RecType, typename Metric = metric::Euclidean<typename RecType::value_type>>
class EntropySimple { // averaged entropy estimation: code COPIED from mgc.*pp with only mgc replaced with entropy, TODO
// refactor to avoid code dubbing
public:
EntropySimple(Metric metric = Metric(), size_t k = 3, bool exp = false) : metric(metric), k(k), exp(exp), logbase(2)
{
} // TODO remove (?)
template <typename Container> double operator()(const Container &data) const;
// double operator()(const Container& data, bool avoid_repeated = false) const;
template <template <typename, typename> class OuterContainer, template <typename, bool> class InnerContainer,
class OuterAllocator, typename ValueType, bool F>
double operator()( // TODO implement
const OuterContainer<InnerContainer<ValueType, F>, OuterAllocator>
&data // inner cpntainer is specialized with bool F
) const;
template <typename Container>
double estimate(const Container &a, const size_t sampleSize = 250, const double threshold = 0.05,
size_t maxIterations = 1000) const;
private:
size_t k;
size_t p;
Metric metric;
double logbase;
bool exp;
};
// https://hal.inria.fr/hal-01272527/document
template <typename RecType, typename Metric = metric::Chebyshev<typename RecType::value_type>> class Entropy {
public:
Entropy(Metric metric = Metric(), size_t k = 7, size_t p = 70, bool exp = false)
: metric(metric), k(k), p(p), exp(exp)
{
}
template <typename Container> double operator()(const Container &data) const;
template <typename Container>
double estimate(const Container &a, const size_t sampleSize = 250, const double threshold = 0.05,
size_t maxIterations = 1000) const;
private:
size_t k;
size_t p;
Metric metric;
bool exp;
};
// VMixing
template <typename RecType, typename Metric = metric::Euclidean<typename RecType::value_type>>
class VMixing_simple { // non-kpN version, DEPRECATED
public:
VMixing_simple(Metric metric = Metric(), int k = 3) : metric(metric), k(k) {}
template <typename C>
typename std::enable_if_t<!type_traits::is_container_of_integrals_v<C>, type_traits::underlying_type_t<C>>
operator()(const C &Xc, const C &Yc) const;
template <typename C>
double estimate(const C &a, const C &b, const size_t sampleSize = 250, const double threshold = 0.05,
size_t maxIterations = 1000) const;
private:
int k;
Metric metric;
};
template <typename RecType, typename Metric = metric::Euclidean<typename RecType::value_type>> class VMixing {
public:
VMixing(Metric metric = Metric(), int k = 3, int p = 25) : metric(metric), k(k), p(p) {}
template <typename C>
typename std::enable_if_t<!type_traits::is_container_of_integrals_v<C>, type_traits::underlying_type_t<C>>
operator()(const C &Xc, const C &Yc) const;
template <typename C>
double estimate(const C &a, const C &b, const size_t sampleSize = 250, const double threshold = 0.05,
size_t maxIterations = 1000) const;
private:
int k;
int p;
Metric metric;
};
/* // VOI code, works and may be enabled
template <typename C, typename Metric = metric::Chebyshev<type_traits::underlying_type_t<C>>>
typename std::enable_if_t<!type_traits::is_container_of_integrals_v<C>, type_traits::underlying_type_t<C>>
VOI_simple(const C& Xc, const C& Yc, int k = 3);
template <typename C, typename Metric = metric::Chebyshev<type_traits::underlying_type_t<C>>>
typename std::enable_if_t<!type_traits::is_container_of_integrals_v<C>, type_traits::underlying_type_t<C>>
VOI(const C& Xc, const C& Yc, int k = 3, int p = 25);
// */
} // namespace metric
#include "entropy.cpp"
#endif
| 4,118
|
C++
|
.h
| 95
| 40.978947
| 120
| 0.73584
|
metric-space-ai/metric
| 34
| 14
| 44
|
MPL-2.0
|
9/20/2024, 10:43:29 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,531,737
|
estimator_helpers.hpp
|
metric-space-ai_metric/metric/correlation/estimator_helpers.hpp
|
/*
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/.
Copyright (c) 2019 Panda Team
*/
#ifndef _ESTIMATOR_HELPERS_HPP
#define _ESTIMATOR_HELPERS_HPP
#include <vector>
namespace metric {
// averaged entropy estimation: code COPIED from mgc.*pp with only mgc replaced with entropy, TODO refactor to avoid
// code dubbing
std::vector<double> linspace(double a, double b, int n);
double polyeval(const std::vector<double> &poly, const double z);
double erfinv_imp(const double p, const double q);
double erfcinv(const double z);
std::vector<double> icdf(const std::vector<double> &prob, const double mu, const double sigma);
double variance(const std::vector<double> &data, const double mean);
double mean(const std::vector<double> &data);
double peak2ems(const std::vector<double> &data);
} // namespace metric
#include "estimator_helpers.cpp"
#endif
| 1,006
|
C++
|
.h
| 23
| 42.043478
| 116
| 0.773526
|
metric-space-ai/metric
| 34
| 14
| 44
|
MPL-2.0
|
9/20/2024, 10:43:29 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,531,738
|
stl_wrappers.hpp
|
metric-space-ai_metric/python/src/stl_wrappers.hpp
|
/*
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/.
Copyright (c) 2020 Panda Team
*/
#pragma once
#include <pybind11/pybind11.h>
#include <pybind11/numpy.h>
#include <vector>
/**
Tiny adapter that provides NumpyArray with std::vector like interface
*/
template<typename T>
class NumpyToVectorAdapter: public pybind11::array_t<T> {
public:
using pybind11::array_t<T>::array_t;
NumpyToVectorAdapter(pybind11::array_t<T> obj)
: pybind11::array_t<T>(obj)
{
}
bool empty() const {return this->size() == 0;}
T* begin() const {
return pybind11::detail::array_begin<T>(this->request());
}
T* end() const {
return pybind11::detail::array_end<T>(this->request());
}
const T& operator[](size_t index) const {
// TODO: init upon creation
auto r = pybind11::array_t<T>::template unchecked<1>();
return r[index];
}
};
//template<typename T>
//class WrapStlMatrix: public base_python_object {
//public:
// typedef std::vector<T> value_type;
// WrapStlMatrix() = default;
// WrapStlMatrix(base_python_object& obj)
// : base_python_object(obj) {
// }
//
// size_t size() const {
// return boost::python::len(*this);
// }
//
// bool empty() const {
// return size() == 0;
// }
//
// boost::python::stl_input_iterator<T> begin() const {
// return boost::python::stl_input_iterator<T>(*this);
// }
//
// boost::python::stl_input_iterator<T> end() const {
// return boost::python::stl_input_iterator<T>();
// }
//
// WrapStlMatrix operator[](int index) const {
// base_python_object wr = boost::python::extract<base_python_object>(base_python_object::operator[](index));
// return WrapStlMatrix(wr);
// }
//};
| 1,933
|
C++
|
.h
| 64
| 27.40625
| 116
| 0.63563
|
metric-space-ai/metric
| 34
| 14
| 44
|
MPL-2.0
|
9/20/2024, 10:43:29 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,531,739
|
metric_converters.hpp
|
metric-space-ai_metric/python/src/metric_converters.hpp
|
#pragma once
#define NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION
#include <pybind11/pybind11.h>
#include <boost/python/object.hpp>
#include <boost/python/converter/implicit.hpp>
#include <boost/python/converter/registry.hpp>
#include <boost/python/module.hpp>
#include <numpy/arrayobject.h>
#include <numpy/arrayscalars.h>
class PyObjectHelper
{
boost::python::object object;
public:
PyObjectHelper(PyObject* obj_ptr)
:object(boost::python::handle<>(boost::python::borrowed(obj_ptr)))
{
}
std::string name() {
return boost::python::extract<std::string>(this->object.attr("__class__").attr("__name__"));
}
bool isNumpyArray() {
return this->name() == "ndarray";
}
unsigned numberOfDimensions() {
return boost::python::extract<unsigned>(this->object.attr("ndim"));
}
};
template<typename T> struct is_2dvector : public std::false_type {};
template<typename T, typename A1, typename A2>
struct is_2dvector<std::vector<std::vector<T, A1>, A2>> : public std::true_type {};
struct IterableConverter
{
template <typename Container>
IterableConverter& from_python()
{
boost::python::converter::registry::push_back(
&IterableConverter::convertible<Container>,
&IterableConverter::construct<Container>,
boost::python::type_id<Container>()
);
return *this;
}
/*
@brief Check if PyObject is iterable twice
*/
template <typename Container>
static void* convertible(PyObject* object)
{
PyObjectHelper helper(object);
if constexpr(is_2dvector<Container>::value) {
return PyObject_GetIter(object) && helper.isNumpyArray() && helper.numberOfDimensions() > 1 ? object : NULL;
}
return PyObject_GetIter(object) ? object : NULL;
}
/* @brief Convert iterable PyObject to C++ container type.
Container Concept requirements:
* Container::value_type is CopyConstructable.
* Container can be constructed and populated with two iterators.
I.e. Container(begin, end)
*/
template <typename Container>
static void construct(PyObject* object, boost::python::converter::rvalue_from_python_stage1_data* data)
{
// Object is a borrowed reference, so create a handle indicting it is
// borrowed for proper reference counting.
boost::python::handle<> handle(boost::python::borrowed(object));
// Obtain a handle to the memory block that the converter has allocated
// for the C++ type.
typedef boost::python::converter::rvalue_from_python_storage<Container> storage_type;
void* storage = reinterpret_cast<storage_type*>(data)->storage.bytes;
typedef boost::python::stl_input_iterator<typename Container::value_type> iterator;
// Allocate the C++ type into the converter's memory block, and assign
// its handle to the converter's convertible variable. The C++
// container is populated by passing the begin and end iterators of
// the python object to the container's constructor.
new (storage) Container(
iterator(boost::python::object(handle)), // begin
iterator()); // end
data->convertible = storage;
}
};
struct NumpyArrayConverter {
template <typename ArrayType>
NumpyArrayConverter& from_python() {
boost::python::converter::registry::push_back(
&NumpyArrayConverter::convertible,
&NumpyArrayConverter::construct<ArrayType>,
boost::python::type_id<ArrayType>()
);
return *this;
}
static void* convertible(PyObject* obj_ptr) {
if (PyObjectHelper(obj_ptr).isNumpyArray()) {
return obj_ptr;
}
return 0;
}
template <typename ArrayType>
static void construct(PyObject* obj_ptr, boost::python::converter::rvalue_from_python_stage1_data* data) {
boost::python::object obj(boost::python::handle<>(boost::python::borrowed(obj_ptr)));
void* storage = ((boost::python::converter::rvalue_from_python_storage<ArrayType>*) data)->storage.bytes;
ArrayType* array = new (storage) ArrayType(obj);
data->convertible = storage;
}
};
struct NumpyScalarConverter {
template <typename ScalarType>
NumpyScalarConverter& from_python() {
boost::python::converter::registry::push_back(
&NumpyScalarConverter::convertible,
&NumpyScalarConverter::construct<ScalarType>,
boost::python::type_id<ScalarType>()
);
return *this;
}
static void* convertible(PyObject* obj_ptr) {
auto name = PyObjectHelper(obj_ptr).name();
if (
name == "float32" ||
name == "float64" ||
name == "int8" ||
name == "int16" ||
name == "int32" ||
name == "int64" ||
name == "uint8" ||
name == "uint16" ||
name == "uint32" ||
name == "uint64"
) {
return obj_ptr;
}
return 0;
}
template <typename ScalarType>
static void construct(PyObject* obj_ptr, boost::python::converter::rvalue_from_python_stage1_data* data) {
auto name = PyObjectHelper(obj_ptr).name();
void* storage = ((boost::python::converter::rvalue_from_python_storage<ScalarType>*) data)->storage.bytes;
ScalarType * scalar = new (storage) ScalarType;
if (name == "float32")
(*scalar) = PyArrayScalar_VAL(obj_ptr, Float32);
else if (name == "float64")
(*scalar) = PyArrayScalar_VAL(obj_ptr, Float64);
else if (name == "int8")
(*scalar) = PyArrayScalar_VAL(obj_ptr, Int8);
else if (name == "int16")
(*scalar) = PyArrayScalar_VAL(obj_ptr, Int16);
else if (name == "int32")
(*scalar) = PyArrayScalar_VAL(obj_ptr, Int32);
else if (name == "int64")
(*scalar) = PyArrayScalar_VAL(obj_ptr, Int64);
else if (name == "uint8")
(*scalar) = PyArrayScalar_VAL(obj_ptr, UInt8);
else if (name == "uint16")
(*scalar) = PyArrayScalar_VAL(obj_ptr, UInt16);
else if (name == "uint32")
(*scalar) = PyArrayScalar_VAL(obj_ptr, UInt32);
else if (name == "uint64")
(*scalar) = PyArrayScalar_VAL(obj_ptr, UInt64);
data->convertible = storage;
}
};
| 6,555
|
C++
|
.h
| 161
| 32.63354
| 120
| 0.621503
|
metric-space-ai/metric
| 34
| 14
| 44
|
MPL-2.0
|
9/20/2024, 10:43:29 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,531,740
|
metric_types.hpp
|
metric-space-ai_metric/python/src/metric_types.hpp
|
#include "metric/utils/graph.hpp"
#include "metric/distance/k-related/Standards.hpp"
#include "metric/distance/k-structured/EMD.hpp"
#include <boost/mpl/for_each.hpp>
#include <boost/mpl/vector.hpp>
#include <typeindex>
#include <string>
#include <unordered_map>
namespace metric {
// define list of metric and their names
using MetricTypes = boost::mpl::vector<
metric::Euclidean<double>
, metric::Manhatten<double>
, metric::Chebyshev<double>
, metric::P_norm<double>
>;
std::unordered_map<std::type_index, std::string> typeNames = {
{std::type_index(typeid(metric::Euclidean<double>)), "Euclidean"},
{std::type_index(typeid(metric::Euclidean_thresholded<double>)), "Euclidean_thresholded"},
{std::type_index(typeid(metric::Manhatten<double>)), "Manhatten"},
{std::type_index(typeid(metric::Chebyshev<double>)), "Chebyshev"},
{std::type_index(typeid(metric::P_norm<double>)), "Pnorm"},
{std::type_index(typeid(metric::EMD<double>)), "EMD"},
{std::type_index(typeid(metric::Grid4)), "Grid4"},
{std::type_index(typeid(metric::Grid6)), "Grid6"},
{std::type_index(typeid(metric::Grid8)), "Grid8"},
{std::type_index(typeid(metric::Grid8)), "Grid8"}
};
template<typename Type>
std::string getTypeName() {
auto it = typeNames.find(std::type_index(typeid(Type)));
if (it != typeNames.end()) {
return it->second;
}
const std::string name = typeid(Type).name();
if (name.find("function") != std::string::npos) {
return "Generic";
}
return name;
}
} // metric
| 1,558
|
C++
|
.h
| 41
| 34.390244
| 94
| 0.683444
|
metric-space-ai/metric
| 34
| 14
| 44
|
MPL-2.0
|
9/20/2024, 10:43:29 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,531,741
|
custom.hpp
|
metric-space-ai_metric/python/src/distance/custom.hpp
|
#pragma once
#include <functional>
#include <optional>
namespace metric {
template <typename Container, typename Value = double>
class PythonMetric : public std::function<Value(const Container&, const Container&)> {
public:
using Callable = std::function<Value(const Container&, const Container&)>;
using value_type = Value;
using distance_type = value_type;
using Callable::Callable;
};
// this was a good idea, but not worth the efforts and not transparently convertible
//template <typename Container, typename V = double>
//class CustomMetric {
//public:
// using value_type = V;
// using distance_type = value_type;
//
// using ScalarFunc = std::function<distance_type(const V&, const V&)>;
// using VectorFunc = std::function<distance_type(const Container&, const Container&)>;
//
// CustomMetric(const VectorFunc& vectorDistance, std::optional<ScalarFunc> vectorDistance)
// : scalarDistance(scalarDistance), vectorDistance(vectorDistance.value_or(nullptr))
// {
// }
// one can always express scalar distance as distance between vectors with single item
// distance_type operator()(const V& a, const V& b) const
// {
// return this->scalarDistance(a, b);
// }
//
// distance_type operator()(const Container& a, const Container& b) const
// {
// return this->vectorDistance(a, b);
// }
//
//private:
// ScalarFunc scalarDistance;
// VectorFunc vectorDistance;
//};
} // metric
| 1,477
|
C++
|
.h
| 42
| 33.52381
| 94
| 0.705882
|
metric-space-ai/metric
| 34
| 14
| 44
|
MPL-2.0
|
9/20/2024, 10:43:29 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,531,742
|
tinyspec.cpp
|
nwoeanhinnogaehr_tinyspec-cling/tinyspec.cpp
|
#include<cmath>
#include<unistd.h>
#include<cstring>
#include<complex>
#include<cassert>
#include<vector>
#include<string>
#include<iostream>
#include<queue>
#include<mutex>
#include<condition_variable>
#include<thread>
#include<sys/stat.h>
#include<sys/time.h>
#include<csignal>
#include<fcntl.h>
#include<jack/jack.h>
#ifdef USE_CLING
#include"cling/Interpreter/Interpreter.h"
#include"cling/Interpreter/InterpreterCallbacks.h"
#include"cling/Utils/Casting.h"
#endif
#include "rtinc/root.hpp"
#include "rtlib/root.hpp"
using namespace std;
#define STR_(x) #x
#define STR(x) STR_(x)
const char *LLVMRESDIR = "cling_bin"; // path to cling resource directory
const char *CODE_BEGIN = "<<<";
const char *CODE_END = ">>>";
// This is in a namespace so we can cleanly access it from other compilation units with extern
namespace internals {
uint64_t system_frame_size = 0;
uint64_t window_size;
uint64_t new_window_size(1<<12); // initial size
uint64_t hop_samples(new_window_size/2);
uint64_t hop_fract = 0;
uint64_t computed_hop = hop_samples;
double hop = double(hop_samples);
deque<float> aqueue, atmp, ainqueue;
WaveBuf audio_in, audio_out;
uint64_t time_samples = 0;
uint64_t time_fract = 0;
size_t nch_in = 0, nch_out = 0, new_nch_in = 0, new_nch_out = 0;
mutex frame_notify_mtx, // for waking up processing thread
exec_mtx, // guards user code exec
data_mtx; // guards aqueue, ainqueue
condition_variable frame_notify;
bool frame_ready = false;
using func_t = function<void(WaveBuf&, WaveBuf&, double)>;
func_t fptr(nullptr);
string command_file;
string client_name;
double rate = 44100; // reset by jack
jack_client_t *client;
vector<jack_port_t *> in_ports;
vector<jack_port_t *> out_ports;
}
using namespace internals;
#ifdef USE_CLING
struct Callbacks : public cling::InterpreterCallbacks {
Callbacks(cling::Interpreter *interp) : cling::InterpreterCallbacks(interp) { }
void *EnteringUserCode() { exec_mtx.lock(); return nullptr; }
void ReturnedFromUserCode(void *) { exec_mtx.unlock(); }
};
void init_cling(int argc, char **argv) { cling::Interpreter interp(argc, argv, LLVMRESDIR, {},
true); // disable runtime for simplicity
interp.setCallbacks(make_unique<Callbacks>(&interp));
interp.setDefaultOptLevel(2);
interp.allowRedefinition();
interp.process("#include \"rtinc/root.hpp\"\n");
// make a fifo called "cmd", which commands are read from
mkfifo(command_file.c_str(), 0700);
int fd = open(command_file.c_str(), O_RDONLY);
const size_t CODE_BUF_SIZE = 1<<12;
char codebuf[CODE_BUF_SIZE];
string code;
while (true) { // read code from fifo and execute it
int n = read(fd, codebuf, CODE_BUF_SIZE);
if (n == 0) usleep(100000); // hack to avoid spinning too hard
code += string(codebuf, n);
int begin = code.find(CODE_BEGIN);
int end = code.find(CODE_END);
while (end != -1 && begin != -1) { // while there are blocks to execute
string to_exec = code.substr(begin+strlen(CODE_BEGIN), end-begin-strlen(CODE_BEGIN));
code = code.substr(end+strlen(CODE_END)-1);
size_t nl_pos = to_exec.find("\n");
int preview_len = nl_pos == string::npos ? to_exec.size() : nl_pos;
string preview = to_exec.substr(0, preview_len);
cerr << "execute: " << preview << "..." << endl;
interp.process(to_exec);
// move to next block
begin = code.find(CODE_BEGIN);
end = code.find(CODE_END);
}
}
}
#endif
double current_time_secs() {
return (double(time_samples) + time_fract/double(uint64_t(-1)))/rate;
}
void generate_frames() {
struct timespec yield_time;
clock_gettime(CLOCK_MONOTONIC, &yield_time);
while (true) {
{ // wait until there's more to do
unique_lock<mutex> lk(frame_notify_mtx);
frame_notify.wait(lk, []{ return frame_ready; });
frame_ready = false;
}
while (true) {
struct timespec current_time;
clock_gettime(CLOCK_MONOTONIC, ¤t_time);
if (current_time.tv_sec > yield_time.tv_sec ||
(current_time.tv_sec >= yield_time.tv_sec && current_time.tv_nsec >= yield_time.tv_nsec)) {
usleep(0);
yield_time.tv_nsec = current_time.tv_nsec + 100000000;
yield_time.tv_sec = current_time.tv_sec + (yield_time.tv_nsec > 999999999);
yield_time.tv_nsec %= 1000000000;
}
lock_guard<mutex> exec_lk(exec_mtx);
{
lock_guard<mutex> data_lk(data_mtx);
if (new_nch_in != nch_in || new_nch_out != nch_out || new_window_size != window_size) {
window_size = new_window_size;
nch_in = new_nch_in;
nch_out = new_nch_out;
}
audio_in.resize(nch_in, window_size);
audio_out.resize(nch_out, window_size);
if (ainqueue.size() < nch_in*(computed_hop+window_size))
break;
if (aqueue.size() >= max(system_frame_size, window_size) * nch_out)
break;
// advance input by hop
size_t sz_tmp = ainqueue.size();
for (size_t i = 0; i < min(nch_in*computed_hop, sz_tmp); i++)
ainqueue.pop_front();
// get input
for (uint64_t i = 0; i < window_size; i++) {
for (size_t c = 0; c < nch_in; c++) {
if (i*nch_in+c < ainqueue.size())
audio_in[c][i] = ainqueue[i*nch_in+c];
else audio_in[c][i] = 0;
}
}
}
if (time_samples == 0 && time_fract == 0 && base_time == 0)
gettimeofday(&init_time, NULL); // TODO use clock_gettime
if (fptr) { // call synthesis function
fptr(audio_in, audio_out, current_time_secs());
if (time_fract + hop_fract < time_fract)
computed_hop = hop_samples + 1;
else
computed_hop = hop_samples;
time_samples += computed_hop;
time_fract += hop_fract;
}
{
lock_guard<mutex> data_lk(data_mtx);
// output region that overlaps with previous frame(s)
for (uint64_t i = 0; i < min(computed_hop, audio_out.size); i++) {
for (size_t c = 0; c < nch_out; c++) {
float overlap = 0;
if (!atmp.empty()) {
overlap = atmp.front();
atmp.pop_front();
}
aqueue.push_back(overlap + audio_out[c][i]);
}
}
// if the hop is larger than the frame size
for (int i = 0; i < int(nch_out)*(int(computed_hop)-int(audio_out.size)); i++) {
if (!atmp.empty()) {
aqueue.push_back(atmp.front()); // output overlap if any
atmp.pop_front();
} else {
aqueue.push_back(0); // otherwise output silence
}
}
}
// save region that overlaps with next frame
for (int i = 0; i < int(audio_out.size)-int(computed_hop); i++) {
for (size_t c = 0; c < nch_out; c++) {
float out_val = audio_out[c][computed_hop+i];
if (i*nch_out+c < atmp.size()) atmp[i*nch_out+c] += out_val;
else atmp.push_back(out_val);
}
}
}
}
}
int audio_cb(jack_nframes_t len, void *) {
lock_guard<mutex> data_lk(data_mtx);
system_frame_size = len;
float *in_bufs[in_ports.size()];
float *out_bufs[out_ports.size()];
for (size_t i = 0; i < in_ports.size(); i++)
in_bufs[i] = (float*) jack_port_get_buffer(in_ports[i], len);
for (size_t i = 0; i < out_ports.size(); i++)
out_bufs[i] = (float*) jack_port_get_buffer(out_ports[i], len);
for (size_t i = 0; i < len; i++)
for (size_t c = 0; c < in_ports.size(); c++)
ainqueue.push_back(in_bufs[c][i]);
{
unique_lock<mutex> lk(frame_notify_mtx);
frame_ready = true;
}
frame_notify.notify_one();
size_t underrun = 0;
for (size_t i = 0; i < len; i++)
for (size_t c = 0; c < out_ports.size(); c++) {
if (!aqueue.empty()) {
out_bufs[c][i] = aqueue.front();
aqueue.pop_front();
} else {
out_bufs[c][i] = 0;
underrun++;
}
}
static bool warmed_up = false;
if (underrun && warmed_up)
cerr << "WARNING: audio output buffer underrun (" << underrun << " samples)" << endl;
else if (!underrun)
warmed_up = true;
return 0;
}
int sample_rate_changed(jack_nframes_t sr, void*) {
cerr << "INFO: set sample rate to " << sr << endl;
rate = sr;
return 0;
}
void init_audio() {
jack_status_t status;
client = jack_client_open(client_name.c_str(), JackNullOption, &status);
if (!client) {
cerr << "FATAL: Failed to open jack client: " << status << endl;
exit(1);
}
client_name = string(jack_get_client_name(client));
set_num_channels(2,2);
jack_set_process_callback(client, audio_cb, nullptr);
jack_set_sample_rate_callback(client, sample_rate_changed, nullptr);
jack_activate(client);
cout << "Playing..." << endl;
}
sighandler_t prev_handlers[32];
void at_exit(int i) {
cout << "Cleaning up... " << endl;
jack_deactivate(client);
unlink(command_file.c_str());
signal(i, prev_handlers[i]);
raise(i);
}
int main(int argc, char **argv) {
command_file = argc > 1 ? argv[1] : "cmd";
if (access(command_file.c_str(), F_OK) != -1) {
cerr << "FATAL: command pipe \"" << command_file << "\" already exists. Remove it before continuing." << endl;
return 1;
}
#ifdef HACK
client_name = string("tinyspec_") + STR(HACK);
#else
client_name = string("tinyspec_") + command_file;
#endif
prev_handlers[SIGINT] = signal(SIGINT, at_exit);
prev_handlers[SIGABRT] = signal(SIGABRT, at_exit);
prev_handlers[SIGTERM] = signal(SIGTERM, at_exit);
init_audio();
thread worker(generate_frames);
#ifdef USE_CLING
init_cling(argc, argv);
#else
#ifdef HACK
#include STR(HACK)
this_thread::sleep_until(chrono::time_point<chrono::system_clock>::max());
#else
#error Not using cling but no hack specified. Compile with `./compile --no-cling hack.cpp`
#endif
#endif
}
| 10,998
|
C++
|
.cpp
| 281
| 30.170819
| 118
| 0.559241
|
nwoeanhinnogaehr/tinyspec-cling
| 34
| 1
| 3
|
GPL-3.0
|
9/20/2024, 10:43:29 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,531,743
|
send.cpp
|
nwoeanhinnogaehr_tinyspec-cling/tools/send.cpp
|
#include <unistd.h>
#include <stdio.h>
#include <fcntl.h>
int main(int argc, char** argv) {
const char *filename = argc > 1 ? argv[1] : "cmd";
int fd = open(filename, O_WRONLY);
int c;
const char *meta = "<<<>>>";
write(fd, meta, 3);
while(~(c = getchar())) {
write(fd, &c, 1);
}
write(fd, meta+3, 3);
}
| 346
|
C++
|
.cpp
| 14
| 20.714286
| 54
| 0.545455
|
nwoeanhinnogaehr/tinyspec-cling
| 34
| 1
| 3
|
GPL-3.0
|
9/20/2024, 10:43:29 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,531,744
|
tidal.cpp
|
nwoeanhinnogaehr_tinyspec-cling/hacks/tidal.cpp
|
/* Example of controlling tinyspec with tidalcycles via OSC
Adapted from simple-pitchshift.cpp
tinyspecTarget = OSCTarget {oName = "Tinyspec", oAddress = "127.0.0.1", oPort = 44101, oPath = "/shift", oShape = Just [("shift", Just $ VF 0)], oLatency = 0.02, oPreamble = [], oTimestamp = MessageStamp}
tidal <- startTidal tinyspecTarget defaultConfig
let p = streamReplace tidal
let shift = pF "shift"
p 1 $ sometimes rev $ shift "0.5 0.75 1 1.25 1.5 1.75 2"
*/
connect(CLIENT_NAME, "system");
set_process_fn([&](WaveBuf &in, WaveBuf &out, double t){
static float shift = 1;
for (auto msg : osc_recv(44101, t, "/shift")) {
osc_get(*msg, shift);
if (shift < 0.1) shift = 0.1;
}
window_hann(in);
out.resize(in.num_channels, in.size/shift);
for (size_t i = 0; i < in.num_channels; i++)
for (size_t j = 0; j < in.size; j++)
for (int k = j/shift; k < (j+1)/shift; k++)
out[i][k] = in[i][j];
next_hop_ratio(8192,0.5/shift);
});
| 1,006
|
C++
|
.cpp
| 23
| 39
| 204
| 0.616327
|
nwoeanhinnogaehr/tinyspec-cling
| 34
| 1
| 3
|
GPL-3.0
|
9/20/2024, 10:43:29 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,531,745
|
karplus-strong.cpp
|
nwoeanhinnogaehr_tinyspec-cling/hacks/karplus-strong.cpp
|
// Demo of excited delay line filtered with FFT
// Try feeding it with:
// $ watch oscsend localhost 9999 /play d 110
set_num_channels(0, 2);
connect(CLIENT_NAME, "system");
set_process_fn([&](WaveBuf &, WaveBuf &out, double t) {
static int trigger_time = -99999; //prevent trigger at t=0
static double freq = 220;
static int head = 0;
static FFTBuf f;
static WaveBuf buf;
for (auto msg : osc_recv(9999, t, "/play")) {
osc_get(*msg, freq);
trigger_time = head;
}
int bufsize = (size_t)(RATE/freq);
buf.resize(2, bufsize);
for (int c = 0; c < 2; c++) {
double samp;
if (head-trigger_time < bufsize)
samp = sin(rand()*3434.3523); //lazy float rand
else
samp = buf[c][(head+1)%bufsize];
out[c][0] = buf[c][head%bufsize] = samp;
}
if (head%bufsize == 0) {
// Perform fitering
f.fill_from(buf);
frft(f,f,1);
for (int c = 0; c < 2; c++) {
for (int i = 0; i < bufsize/2; i++) {
// Can get lots of wacky effects by changing the filter here
f[c][i] = polar(abs(f[c][i])/pow(i+1,0.05), arg(f[c][i]));
}
}
frft(f,f,-1);
buf.fill_from<cplx>(f, [](cplx x){return x.real();});
}
head++;
next_hop_samples(1,1);
});
| 1,345
|
C++
|
.cpp
| 41
| 25.829268
| 76
| 0.534152
|
nwoeanhinnogaehr/tinyspec-cling
| 34
| 1
| 3
|
GPL-3.0
|
9/20/2024, 10:43:29 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,531,746
|
pitchshift-pv.cpp
|
nwoeanhinnogaehr_tinyspec-cling/hacks/pitchshift-pv.cpp
|
connect(CLIENT_NAME, "system");
PhaseVocoder pv;
set_process_fn([&](WaveBuf &in, WaveBuf &out, double) {
pv.analyze(in);
pv.shift([](double x){ return x*2; });
pv.synthesize(out);
next_hop_ratio(2048,0.25);
});
pv.reset();
| 242
|
C++
|
.cpp
| 9
| 23.777778
| 55
| 0.643478
|
nwoeanhinnogaehr/tinyspec-cling
| 34
| 1
| 3
|
GPL-3.0
|
9/20/2024, 10:43:29 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,531,747
|
pitchshift-simple.cpp
|
nwoeanhinnogaehr_tinyspec-cling/hacks/pitchshift-simple.cpp
|
connect(CLIENT_NAME, "system");
set_process_fn([&](WaveBuf &in, WaveBuf &out, double t) {
double shift = sin(t)/2+1;
window_hann(in);
out.resize(in.num_channels, in.size/shift);
for (size_t i = 0; i < in.num_channels; i++)
for (size_t j = 0; j < in.size; j++)
for (int k = j/shift; k < (j+1)/shift; k++)
out[i][k] = in[i][j];
next_hop_ratio(1800,0.5/shift);
});
| 418
|
C++
|
.cpp
| 11
| 31.909091
| 57
| 0.540541
|
nwoeanhinnogaehr/tinyspec-cling
| 34
| 1
| 3
|
GPL-3.0
|
9/20/2024, 10:43:29 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,531,748
|
bytebeat.cpp
|
nwoeanhinnogaehr_tinyspec-cling/hacks/bytebeat.cpp
|
// Simple bytebeat synth achieved by setting both frame size and hop to 1 sample.
set_num_channels(0,1);
connect(CLIENT_NAME, "system");
set_process_fn([&](WaveBuf&, WaveBuf& out, double ts){
double t = ts*2000;
int y = t;
int s = int(fmod(t,(1+(t/(1.0+(y&(y>>9^y>>11)))))));
out[0][0] = s%256/128.0-1;
next_hop_samples(1,1);
});
| 351
|
C++
|
.cpp
| 10
| 32
| 81
| 0.617647
|
nwoeanhinnogaehr/tinyspec-cling
| 34
| 1
| 3
|
GPL-3.0
|
9/20/2024, 10:43:29 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,531,749
|
osc.cpp
|
nwoeanhinnogaehr_tinyspec-cling/hacks/osc.cpp
|
// OSC demo.
//
// You can use OSC to send commands to external programs
// like synthesizers or VJ software.
//
// To use this, install and start SuperDirt first.
// See here for instructions: https://github.com/musikinformatik/SuperDirt
// The simple setup will suffice.
// Then execute this and you should hear some sounds!
// These sounds are not produced by tinyspec directly but
// are coming from superdirt.
set_process_fn([&](WaveBuf &, WaveBuf &, double t){
int s = t*16; // note counter
// First two args are the OSC server address and port (UDP)
// Third arg is the time it should be triggered at.
// Fourth is the OSC path.
// Everything following is OSC params, which can be int32, int64, float, double, or string.
osc_send("localhost", 57120, t+0.5, "/play2", "sound", "blip", "speed", ((s&s/8)%16)/8.0+0.5);
next_hop_hz(0,16); // set rate
});
| 887
|
C++
|
.cpp
| 20
| 41.9
| 98
| 0.69515
|
nwoeanhinnogaehr/tinyspec-cling
| 34
| 1
| 3
|
GPL-3.0
|
9/20/2024, 10:43:29 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,531,750
|
pwm_bb.cpp
|
nwoeanhinnogaehr_tinyspec-cling/hacks/pwm_bb.cpp
|
// Rudimentary pulse width modulation (PWM)
// Synthesizes a sine pulse wave with width and frequency varying according to a bytebeat formula.
set_num_channels(0,1);
connect(CLIENT_NAME, "system");
set_process_fn([&](WaveBuf&, WaveBuf& out, double){
static int it = 1<<16;
for (size_t i=0; i<out.num_channels; i++)
for (size_t j=0; j<out.size; j++)
out[i][j] = sin(double(j)/out.size*M_PI*2-M_PI/2)/2+0.5;
int k = ((it&it/65)^it/257)%512;
double freq = k+40;
double size = RATE/freq;
double mod = fmod(k*k,128.0)/128.0;
next_hop_samples(mod*size+1, size+1);
it++;
});
| 620
|
C++
|
.cpp
| 16
| 34.5
| 98
| 0.630795
|
nwoeanhinnogaehr/tinyspec-cling
| 34
| 1
| 3
|
GPL-3.0
|
9/20/2024, 10:43:29 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,531,751
|
pwm.cpp
|
nwoeanhinnogaehr_tinyspec-cling/hacks/pwm.cpp
|
// Rudimentary pulse width modulation (PWM)
// Synthesizes a pulse wave with width varying by a sine LFO.
// Achieves the effect by using a fixed hop size and varying the window size.
set_num_channels(0,1);
connect(CLIENT_NAME, "system");
set_process_fn([&](WaveBuf&, WaveBuf& out, double t){
for (size_t i=0; i<out.num_channels; i++)
for (size_t j=0; j<out.size; j++)
out[i][j] = 1;
double freq = 45;
double size = RATE/freq;
double mod = sin(t)*0.5+0.5;
next_hop_samples(mod*size+1, size+1);
});
| 539
|
C++
|
.cpp
| 14
| 34.571429
| 77
| 0.650763
|
nwoeanhinnogaehr/tinyspec-cling
| 34
| 1
| 3
|
GPL-3.0
|
9/20/2024, 10:43:29 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,531,752
|
readme.cpp
|
nwoeanhinnogaehr_tinyspec-cling/hacks/readme.cpp
|
// Connect to the speakers
set_num_channels(0, 2); // no inputs, stereo output
connect(CLIENT_NAME, "system");
// Called periodically to fill up a new buffer.
// in and out are audio sample buffers
// n is the number of samples in the frame
// t is the time in seconds since the beginning of playback.
set_process_fn([&](WaveBuf& in, WaveBuf& out, double t){
FFTBuf fft;
fft.resize(out.num_channels, out.size);
// Loop over frequency bins. Starting at 1 skips the DC offset.
for (size_t c = 0; c < out.num_channels; c++) {
for (size_t i = 1; i < out.size; i++) {
cplx x = sin(i*pow(1.0/(i+1), 1.0+sin(t*i*M_PI/8+c)*0.5))*25 // Some random formula
/pow(i,0.9); // Scale magnitude to prevent loud high frequency noises.
fft[c][i] = x; // Fill output buffer
}
}
frft(fft, fft, -1.0); // Perform in-place inverse FFT
out.fill_from<cplx>(fft, [](cplx x){return x.real();}); // Copy real part to output
window_hann(out); // Apply Hann window
next_hop_ratio(4096); // Set FFT size for the next frame
});
| 1,089
|
C++
|
.cpp
| 23
| 42.347826
| 95
| 0.631332
|
nwoeanhinnogaehr/tinyspec-cling
| 34
| 1
| 3
|
GPL-3.0
|
9/20/2024, 10:43:29 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,531,753
|
sinosc.cpp
|
nwoeanhinnogaehr_tinyspec-cling/hacks/sinosc.cpp
|
set_num_channels(0,1);
connect(CLIENT_NAME, "system");
set_process_fn([&](WaveBuf&, WaveBuf& out, double t){
out[0][0] = sin(t*2*M_PI*440);
next_hop_samples(1, 1);
});
| 176
|
C++
|
.cpp
| 6
| 27
| 53
| 0.629412
|
nwoeanhinnogaehr/tinyspec-cling
| 34
| 1
| 3
|
GPL-3.0
|
9/20/2024, 10:43:29 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,531,754
|
connect.cpp
|
nwoeanhinnogaehr_tinyspec-cling/hacks/connect.cpp
|
// the (dis)connect function takes two JACK client names, optional port filters, and an optional mode parameter.
//
// void connect(string client_a, string client_b, string filter_a="", string filter_b="", int mode=CONNECT_MAX);
// void disconnect(string client_a, string client_b, string filter_a="", string filter_b="", int mode=CONNECT_MAX);
//
// you can use the global CLIENT_NAME to get the name of the current tinyspec instance.
// as a basic example, the following will connect the system speakers and mic to tinyspec.
connect(CLIENT_NAME, "system");
// to undo the operation, we can call disconnect with the same arguments.
disconnect(CLIENT_NAME, "system");
// filters let us choose which ports to connect.
// a filter of "o" selects only output ports, and a filter of "i" selects only input ports.
// for example, the following will connect tinyspec output to the system speakers.
connect(CLIENT_NAME, "system", "o", "i");
// since we can only pair up outputs and inputs, the filter is often implied for one of the clients.
// the previous example is equivalent to the following.
connect(CLIENT_NAME, "system", "o");
// if we only wish to connect one of the channels, we can put a number in the filter to select it.
// the number is indexed starting from 0.
// the following connects tinyspec channel 0 and system channel 1.
connect(CLIENT_NAME, "system", "0", "1");
// this can be combined with the input and output filters but putting the number after the filter.
connect(CLIENT_NAME, "system", "i0", "1");
// when there is a mismatch in the number of channels, tinyspec will duplicate or mix channels as
// necessary to connect all specified ports. it determines which ports to match up by wrapping around
// to the beginning of the list of selected channels for the side of the connection with the smaller
// number of selected channels.
// for example the following connects output 0 of tinyspec to all system speakers.
connect(CLIENT_NAME, "system", "o0");
// we can also specify a range a ports to connect.
// for example the range "o1,3" selects output ports 1 and 2 (the bounds are inclusive,exclusive)
set_num_channels(4, 4);
connect(CLIENT_NAME, "system", "o1,3");
// we can now demonstrate more clearly what happens when there is a mismatch in the number of channels.
// we select 3 channels from tinyspec and 2 from the system output. the result is that tinyspec channel
// 1 and 3 are both connected to system channel 0 and tinyspec channel 2 is connected to system channel 1.
// in total 3 connections are made = max(2,3). this is the meaning of CONNECT_MAX (the default mode).
connect(CLIENT_NAME, "system", "o1,4", "0,2");
// to prevent connecting multiple wires to the same port, pass CONNECT_MIN as the mode.
// the following only connects tinyspec channel 1 to system channel 0 and tinyspec channel 2
// to system channel 1, ignoring tinyspec channel 3.
connect(CLIENT_NAME, "system", "o1,4", "0,2", CONNECT_MIN);
// to connect all matching outputs to all matching outputs we can use CONNECT_ALL.
// the following disconnects tinyspec completely from everything else.
disconnect(CLIENT_NAME, ".*", "", "", CONNECT_ALL);
// we can also leave off either of the bounds. if we do so the lower bound is implicitly 0
// and the upper bound is implicitly infinity.
// the following connects all output ports to the system but the indexing is off by 1.
connect(CLIENT_NAME, "system", "o1,");
// client names can be filtered using regular expressions.
// the syntax is documented at https://laurikari.net/tre/documentation/regex-syntax/
// for example the following connects tinyspec to every other client (including itself, unless self
// connection requests are ignored by your JACK server).
connect(CLIENT_NAME, ".*");
// ports can also be selected by name, or regular expressions, by starting the filter with a colon.
// since the tinyspec output ports match the regex "out.*" we can alternatively select them with:
connect(CLIENT_NAME, "system", ":out.*");
// the following routes the audio output of all PulseAudio application through tinyspec.
disconnect("PulseAudio JACK Sink", "system");
connect(CLIENT_NAME, "system", "o");
connect(CLIENT_NAME, "PulseAudio JACK Sink");
// reconnect pulse to the speakers:
connect("PulseAudio JACK Sink", "system");
disconnect(CLIENT_NAME, "system", "o");
disconnect(CLIENT_NAME, "PulseAudio JACK Sink");
// feed back renoise through tinyspec
connect(CLIENT_NAME, "renoise", "", "i2,", CONNECT_MIN);
connect(CLIENT_NAME, "renoise", "", "o2,", CONNECT_MIN);
| 4,546
|
C++
|
.cpp
| 68
| 65.544118
| 115
| 0.756108
|
nwoeanhinnogaehr/tinyspec-cling
| 34
| 1
| 3
|
GPL-3.0
|
9/20/2024, 10:43:29 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,531,755
|
blinkenlights.cpp
|
nwoeanhinnogaehr_tinyspec-cling/hacks/spectral_bytebeat/blinkenlights.cpp
|
next_hop_ratio(1<<9, 0.5);
set_num_channels(0, 2);
connect(CLIENT_NAME, "system");
set_process_fn([&](WaveBuf&, WaveBuf &out, double t) {
static FFTBuf buf;
static int x;
buf.resize(out.num_channels, out.size*2);
int n = out.size;
for (size_t c = 0; c < out.num_channels; c++) {
for (int i = 1; i < n; i++) {
int r = (int)(t*8)*n+i;
int y = int(t/2);
int a = y/3^y/5;
int b = y/2^y/7;
x += (r/(3+a%17)&r/(5+b%11));
x ^= r;
buf[c][i] = (exp(cplx(0.0,M_PI/16.0*x)))/pow(i+1, 1.0)*4.0;
buf[c][n*2-i] = conj(buf[c][i]);
}
}
frft(buf, buf, -1);
for (size_t c = 0; c < out.num_channels; c++)
for (int i = 0; i < n; i++)
out[c][i] = buf[c][i].real() * (1.0-abs(1.0-i/(n/2.0)));
});
| 839
|
C++
|
.cpp
| 25
| 26
| 71
| 0.445946
|
nwoeanhinnogaehr/tinyspec-cling
| 34
| 1
| 3
|
GPL-3.0
|
9/20/2024, 10:43:29 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,531,756
|
ghostacid.cpp
|
nwoeanhinnogaehr_tinyspec-cling/hacks/spectral_bytebeat/ghostacid.cpp
|
next_hop_ratio(1<<14, 0.5);
set_num_channels(0, 2);
connect(CLIENT_NAME, "system");
set_process_fn([&](WaveBuf&, WaveBuf &out, double t) {
static FFTBuf buf;
buf.resize(out.num_channels, out.size*2);
int n = out.size;
for (size_t c = 0; c < out.num_channels; c++) {
for (int i = 1; i < n; i++) {
int r = int(t*4)*n+i;
double mag=sin(M_PI*(fmod(i/24+c, 1+r/(1+(double)(r/97^r&r/2))/7)))/pow(i+1, 1.0)*128.0;
buf[c][i]=cplx(mag,mag);
buf[c][n*2-i] = conj(buf[c][i]);
}
}
frft(buf, buf, -1);
for (size_t c = 0; c < out.num_channels; c++)
for (int i = 0; i < n; i++)
out[c][i] = buf[c][i].real() * (1.0-abs(1.0-i/(n/2.0)));
});
| 736
|
C++
|
.cpp
| 20
| 30.2
| 100
| 0.490223
|
nwoeanhinnogaehr/tinyspec-cling
| 34
| 1
| 3
|
GPL-3.0
|
9/20/2024, 10:43:29 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,531,757
|
xin12.cpp
|
nwoeanhinnogaehr_tinyspec-cling/hacks/spectral_bytebeat/xin12.cpp
|
next_hop_ratio(1<<11, 0.5);
set_num_channels(0, 2);
connect(CLIENT_NAME, "system");
set_process_fn([&](WaveBuf&, WaveBuf &out, double t) {
static FFTBuf buf;
static Buf<double> sum;
sum.resize(out.num_channels, out.size);
buf.resize(out.num_channels, out.size*2);
int n = out.size;
for (size_t c = 0; c < out.num_channels; c++) {
for (int i = 1; i < n; i++) {
int factor = 600;
int r = (int)(t*8)*n/2+i;
sum[c][i] += fmod(r,1+(double)r/(1+(((r/factor)&(r/101/factor)|r/247/factor)&(i+c))))/(n-i);
buf[c][i] = (fmod(sum[c][i],1))/pow(i+1, 1.0)*32.0;
sum[c][i] *= 0.1+sin(i/(double)n*M_PI*2.0+t)*0.1;
buf[c][n*2-i] = conj(buf[c][i]);
}
}
frft(buf, buf, -1);
for (size_t c = 0; c < out.num_channels; c++)
for (int i = 0; i < n; i++)
out[c][i] = buf[c][i].real() * (1.0-abs(1.0-i/(n/2.0)));
});
| 935
|
C++
|
.cpp
| 24
| 31.958333
| 104
| 0.491767
|
nwoeanhinnogaehr/tinyspec-cling
| 34
| 1
| 3
|
GPL-3.0
|
9/20/2024, 10:43:29 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,531,758
|
seeking.cpp
|
nwoeanhinnogaehr_tinyspec-cling/hacks/spectral_bytebeat/seeking.cpp
|
next_hop_ratio(1<<11, 0.5);
set_num_channels(0, 2);
connect(CLIENT_NAME, "system");
set_process_fn([&](WaveBuf&, WaveBuf &out, double t) {
static FFTBuf buf;
static Buf<int> feed;
feed.resize(out.num_channels, out.size);
buf.resize(out.num_channels, out.size*2);
int n = out.size;
for (size_t c = 0; c < out.num_channels; c++) {
for (int i = 1; i < n; i++) {
int r = (int)(t*16)*n/2+i+feed[c][i];
int l = feed[c][i]+c;
feed[c][i] += (l&r/128^r/512);
if (int mod = (r/64&r/256^r/1024))
feed[c][i] %= mod;
buf[c][i] = (exp(cplx(0.0,M_PI*feed[c][i])))/pow(i+1, 1.0)*32.0;
buf[c][n*2-i] = conj(buf[c][i]);
}
}
frft(buf, buf, -1);
for (size_t c = 0; c < out.num_channels; c++)
for (int i = 0; i < n; i++)
out[c][i] = buf[c][i].real() * (1.0-abs(1.0-i/(n/2.0)));
});
| 921
|
C++
|
.cpp
| 25
| 29.44
| 76
| 0.478795
|
nwoeanhinnogaehr/tinyspec-cling
| 34
| 1
| 3
|
GPL-3.0
|
9/20/2024, 10:43:29 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,531,759
|
brokenconvo.cpp
|
nwoeanhinnogaehr_tinyspec-cling/hacks/spectral_bytebeat/brokenconvo.cpp
|
next_hop_ratio(1<<15, 0.5);
set_num_channels(0, 2);
connect(CLIENT_NAME, "system");
set_process_fn([&](WaveBuf&, WaveBuf &out, double t) {
static FFTBuf buf;
buf.resize(out.num_channels, out.size*2);
int n = out.size;
for (size_t c = 0; c < out.num_channels; c++) {
for (int i = 1; i < n; i++) {
int r = (int)(t*M_PI)*n/2+i;
buf[c][i]=sin(2.0*M_PI*(i/(1+fmod((1+(double)(r/77&r/38&r/24+c)),i+1))))/pow(i+1, 0.75)*64;
buf[c][n*2-i] = conj(buf[c][i]);
}
}
frft(buf, buf, -1);
for (size_t c = 0; c < out.num_channels; c++)
for (int i = 0; i < n; i++)
out[c][i] = buf[c][i].real() * (1.0-abs(1.0-i/(n/2.0)));
});
| 709
|
C++
|
.cpp
| 19
| 31.052632
| 103
| 0.488406
|
nwoeanhinnogaehr/tinyspec-cling
| 34
| 1
| 3
|
GPL-3.0
|
9/20/2024, 10:43:29 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,531,760
|
knead.cpp
|
nwoeanhinnogaehr_tinyspec-cling/hacks/spectral_bytebeat/knead.cpp
|
next_hop_ratio(1<<9, 0.5);
set_num_channels(0, 2);
connect(CLIENT_NAME, "system");
set_process_fn([&](WaveBuf&, WaveBuf &out, double t) {
static FFTBuf buf;
static Buf<int> feed;
buf.resize(out.num_channels, out.size*2);
feed.resize(out.num_channels, out.size);
int n = out.size;
for (size_t c = 0; c < out.num_channels; c++) {
for (int i = 1; i < n; i++) {
int r = (int)(t*12)*n/2+i+feed[c][i];
feed[c][i] += r/16^r/63^r/1023^c;
if (int mod = (r/16^r/65^r/1024))
feed[c][i] %= mod;
buf[c][i] = (exp(cplx(0.0,M_PI*sin(M_PI*feed[c][i]/double(n-i)))))/pow(i, 1.0)*8.0;
buf[c][n*2-i] = conj(buf[c][i]);
}
}
frft(buf, buf, -1);
for (size_t c = 0; c < out.num_channels; c++)
for (int i = 0; i < n; i++)
out[c][i] = buf[c][i].real() * (1.0-abs(1.0-i/double(n/2)));
});
| 911
|
C++
|
.cpp
| 24
| 30.791667
| 95
| 0.491545
|
nwoeanhinnogaehr/tinyspec-cling
| 34
| 1
| 3
|
GPL-3.0
|
9/20/2024, 10:43:29 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,531,761
|
cellmuncher.cpp
|
nwoeanhinnogaehr_tinyspec-cling/hacks/spectral_bytebeat/cellmuncher.cpp
|
next_hop_ratio(1<<11, 0.5);
set_num_channels(0, 2);
connect(CLIENT_NAME, "system");
set_process_fn([&](WaveBuf&, WaveBuf &out, double t) {
static FFTBuf buf;
buf.resize(out.num_channels, out.size*2);
int n = out.size;
for (size_t c = 0; c < out.num_channels; c++) {
for (int i = 1; i < n; i++) {
int r = int(t*16)*n+i;
buf[c][n*2-i]=buf[c][i]=sin(2.0*M_PI/128.*(c+((int)pow(r,1.1))^r/13^r>>8|r>>6^r>>14))/pow(i,0.8)*25;
}
}
frft(buf, buf, -1);
for (size_t c = 0; c < out.num_channels; c++)
for (int i = 0; i < n; i++)
out[c][i] = buf[c][i].real() * (1.0-abs(1.0-i/(n/2.0)));
});
| 667
|
C++
|
.cpp
| 18
| 31.166667
| 112
| 0.496148
|
nwoeanhinnogaehr/tinyspec-cling
| 34
| 1
| 3
|
GPL-3.0
|
9/20/2024, 10:43:29 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,531,762
|
modrecursion.cpp
|
nwoeanhinnogaehr_tinyspec-cling/hacks/spectral_bytebeat/modrecursion.cpp
|
next_hop_ratio(1<<9, 0.5);
set_num_channels(0, 2);
connect(CLIENT_NAME, "system");
set_process_fn([&](WaveBuf&, WaveBuf &out, double t) {
static FFTBuf buf;
static Buf<int> sum;
sum.resize(out.num_channels, out.size);
buf.resize(out.num_channels, out.size*2);
int n = out.size;
for (size_t c = 0; c < out.num_channels; c++) {
for (int i = 1; i < n; i++) {
int r = (int)(t*16)*n/2+i+sum[c][i];
sum[c][i] += r/64|(r/128&r/512);
sum[c][i] %= (r/64^(r/128&r/512))+16+c;
buf[c][i] = (exp(cplx(0.0,2.0*M_PI*sin(M_PI/16.0*sum[c][i]/double(n-i)))))/pow(i+1, 1.0)*32.0;
buf[c][n*2-i] = conj(buf[c][i]);
}
}
frft(buf, buf, -1);
for (size_t c = 0; c < out.num_channels; c++)
for (int i = 0; i < n; i++)
out[c][i] = buf[c][i].real() * (1.0-abs(1.0-i/(n/2.0)));
});
| 885
|
C++
|
.cpp
| 23
| 31.73913
| 106
| 0.490719
|
nwoeanhinnogaehr/tinyspec-cling
| 34
| 1
| 3
|
GPL-3.0
|
9/20/2024, 10:43:29 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,531,763
|
greatresonator.cpp
|
nwoeanhinnogaehr_tinyspec-cling/hacks/spectral_bytebeat/greatresonator.cpp
|
next_hop_ratio(1<<11, 0.5);
set_num_channels(0, 2);
connect(CLIENT_NAME, "system");
set_process_fn([&](WaveBuf&, WaveBuf &out, double t) {
static FFTBuf buf;
static Buf<double> phase_sum;
phase_sum.resize(out.num_channels, out.size);
buf.resize(out.num_channels, out.size*2);
int n = out.size;
for (size_t c = 0; c < out.num_channels; c++) {
for (int i = 1; i < n; i++) {
buf[c][i] = 0;
int r = int(t*1024)+(1<<20);
for (int nn = 1; nn <= 16; nn++) {
int f = int(pow(i/16+r/255&r/63^r/1023,1+2/double(nn+c)))%256+1;
int h = i/f;
int k = i%f;
phase_sum[c][i] += 2*M_PI*i;
buf[c][i]+=polar(
(double)((k==nn%f)*(h&1?1:-1))/pow(max(1,i-f+1), 0.6),
phase_sum[c][i]+c*M_PI/2);
}
buf[c][n*2-i] = conj(buf[c][i]);
}
}
frft(buf, buf, -1);
for (size_t c = 0; c < out.num_channels; c++)
for (int i = 0; i < n; i++)
out[c][i] = buf[c][i].real() * (1.0-abs(1.0-i/(n/2.0)));
});
| 1,117
|
C++
|
.cpp
| 30
| 27.833333
| 80
| 0.448022
|
nwoeanhinnogaehr/tinyspec-cling
| 34
| 1
| 3
|
GPL-3.0
|
9/20/2024, 10:43:29 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,531,764
|
acidbattery.cpp
|
nwoeanhinnogaehr_tinyspec-cling/hacks/spectral_bytebeat/acidbattery.cpp
|
next_hop_ratio(1<<11, 0.5);
set_num_channels(0, 2);
connect(CLIENT_NAME, "system");
set_process_fn([&](WaveBuf&, WaveBuf &out, double t) {
static FFTBuf buf;
buf.resize(out.num_channels, out.size*2);
int n = out.size;
for (size_t c = 0; c < out.num_channels; c++) {
for (int i = 1; i < n; i++) {
int r = int(t*32)*n+i;
int k = (r>>14^r>>17)%64+2;
double mag=sin(pow(i,0.1)*k*16+
((double)((r&r>>13)%k))
/(1+(double)((r/3&r/1023)%k)))
/pow(i+1, 1.0)*32.0;
buf[c][i]=cplx(mag,mag);
buf[c][n*2-i] = conj(buf[c][i]);
}
}
frft(buf, buf, -1);
for (size_t c = 0; c < out.num_channels; c++)
for (int i = 0; i < n; i++)
out[c][i] = buf[c][i].real() * (1.0-abs(1.0-i/(n/2.0)));
});
| 852
|
C++
|
.cpp
| 24
| 27
| 68
| 0.449275
|
nwoeanhinnogaehr/tinyspec-cling
| 34
| 1
| 3
|
GPL-3.0
|
9/20/2024, 10:43:29 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,531,765
|
datatransmission.cpp
|
nwoeanhinnogaehr_tinyspec-cling/hacks/spectral_bytebeat/datatransmission.cpp
|
next_hop_ratio(1<<8, 0.5);
set_num_channels(0, 2);
connect(CLIENT_NAME, "system");
set_process_fn([&](WaveBuf&, WaveBuf &out, double t) {
static FFTBuf buf;
static Buf<int> sum;
sum.resize(out.num_channels, out.size);
buf.resize(out.num_channels, out.size*2);
int n = out.size;
for (size_t c = 0; c < out.num_channels; c++) {
for (int i = 1; i < n; i++) {
int r = (int)(t*8)*n/2+i+sum[c][i];
sum[c][i] += r/64|(r/128&r/512);
sum[c][i] %= (r/63^(r/128&r/512))+32+c;
buf[c][i] = (exp(cplx(0.0,2.0*M_PI*sin(M_PI*sum[c][i]/double(n-i)))))/pow(i+1, 1.0)*2.0;
buf[c][n*2-i] = conj(buf[c][i]);
}
}
frft(buf, buf, -1);
for (size_t c = 0; c < out.num_channels; c++)
for (int i = 0; i < n; i++)
out[c][i] = buf[c][i].real() * (1.0-abs(1.0-i/(n/2.0)));
});
| 878
|
C++
|
.cpp
| 23
| 31.434783
| 100
| 0.488889
|
nwoeanhinnogaehr/tinyspec-cling
| 34
| 1
| 3
|
GPL-3.0
|
9/20/2024, 10:43:29 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,531,766
|
andshuffle.cpp
|
nwoeanhinnogaehr_tinyspec-cling/hacks/spectral_bytebeat/andshuffle.cpp
|
next_hop_ratio(1<<17, 0.5);
set_num_channels(0, 2);
connect(CLIENT_NAME, "system");
set_process_fn([&](WaveBuf&, WaveBuf &out, double t) {
static FFTBuf buf;
buf.resize(out.num_channels, out.size*2);
int n = out.size;
for (size_t c = 0; c < out.num_channels; c++) {
for (int i = 1; i < n; i++) {
int r = int(t*8)*n/2+n-i;
int j = r/128+c;
double mag = sin((1+fmod(i*i, (1+(double)(((j/5&j/7&(j/64^j/127))^j>>16)%128)))))/pow(i, 0.75)*32;
buf[c][i] = cplx(mag,mag);
buf[c][n*2-i] = conj(buf[c][i]);
}
}
frft(buf, buf, -1);
for (size_t c = 0; c < out.num_channels; c++)
for (int i = 0; i < n; i++)
out[c][i] = buf[c][i].real() * (1.0-abs(1.0-i/(n/2.0)));
});
| 781
|
C++
|
.cpp
| 21
| 30.285714
| 110
| 0.478947
|
nwoeanhinnogaehr/tinyspec-cling
| 34
| 1
| 3
|
GPL-3.0
|
9/20/2024, 10:43:29 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,531,767
|
voidbubbles.cpp
|
nwoeanhinnogaehr_tinyspec-cling/hacks/spectral_bytebeat/voidbubbles.cpp
|
next_hop_ratio(1<<12, 0.5);
set_num_channels(0, 2);
connect(CLIENT_NAME, "system");
set_process_fn([&](WaveBuf&, WaveBuf &out, double t) {
static FFTBuf buf;
buf.resize(out.num_channels, out.size*2);
int n = out.size;
for (size_t c = 0; c < out.num_channels; c++) {
for (int i = 1; i < n; i++) {
int r = (int)(t*32)*n+i;
buf[c][i]=sin(2.0*M_PI/64.*(c+((int)pow(i,1.1))&r/3|r/250|r/136|r>>16))/pow(i+1, 0.7)*32;
buf[c][n*2-i] = conj(buf[c][i]);
}
}
frft(buf, buf, -1);
for (size_t c = 0; c < out.num_channels; c++)
for (int i = 0; i < n; i++)
out[c][i] = buf[c][i].real() * (1.0-abs(1.0-i/(n/2.0)));
});
| 703
|
C++
|
.cpp
| 19
| 30.736842
| 101
| 0.488304
|
nwoeanhinnogaehr/tinyspec-cling
| 34
| 1
| 3
|
GPL-3.0
|
9/20/2024, 10:43:29 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,531,768
|
root.hpp
|
nwoeanhinnogaehr_tinyspec-cling/rtinc/root.hpp
|
#include <iostream>
#include <vector>
using namespace std;
namespace internals {
extern string client_name;
extern double rate;
}
#define RATE internals::rate
#define CLIENT_NAME internals::client_name
#include "buffer.hpp"
#include "control.hpp"
#include "connect.hpp"
#include "osc.hpp"
#include "fft.hpp"
#include "windowfn.hpp"
#include "pv.hpp"
| 361
|
C++
|
.h
| 16
| 20.875
| 42
| 0.774854
|
nwoeanhinnogaehr/tinyspec-cling
| 34
| 1
| 3
|
GPL-3.0
|
9/20/2024, 10:43:29 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,531,769
|
control.hpp
|
nwoeanhinnogaehr_tinyspec-cling/rtinc/control.hpp
|
void next_hop_ratio(uint32_t n, double hop_ratio=0.25);
void next_hop_samples(uint32_t n, double h);
void next_hop_hz(uint32_t n, double hz);
void set_num_channels(size_t in, size_t out);
void skip_to_now();
void set_process_fn(function<void(WaveBuf&, WaveBuf&, double)> fn);
void set_time(double secs);
| 304
|
C++
|
.h
| 7
| 42.428571
| 67
| 0.740741
|
nwoeanhinnogaehr/tinyspec-cling
| 34
| 1
| 3
|
GPL-3.0
|
9/20/2024, 10:43:29 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,531,770
|
buffer.hpp
|
nwoeanhinnogaehr_tinyspec-cling/rtinc/buffer.hpp
|
#pragma once
#include <fftw3.h>
#include <functional>
#include <cassert>
template <typename T>
struct Buf {
T *data = nullptr;
size_t size = 0;
size_t num_channels = 0;
Buf() {}
Buf(size_t num_channels, size_t size) { resize(num_channels, size); }
~Buf() { if (data) free(data); }
void resize(size_t num_channels, size_t size) {
if (this->size*this->num_channels != size*num_channels) {
this->size = size;
this->num_channels = num_channels;
if (data) fftw_free(data);
data = (T*) fftw_malloc(sizeof(T)*num_channels*size);
zero();
}
}
template <typename U>
void fill_from(Buf<U> &other, std::function<T(U)> mix=[](U x){ return T(x); }) {
resize(other.num_channels, other.size);
for (size_t i = 0; i < num_channels; i++)
for (size_t j = 0; j < size; j++)
data[i*size + j] = mix(other[i][j]);
}
void zero() {
for (size_t i = 0; i < size*num_channels; i++)
data[i] = {};
}
T* operator[](int index) { return data + index*size; }
};
using WaveBuf = Buf<double>;
| 1,154
|
C++
|
.h
| 35
| 26.314286
| 84
| 0.547001
|
nwoeanhinnogaehr/tinyspec-cling
| 34
| 1
| 3
|
GPL-3.0
|
9/20/2024, 10:43:29 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.