From c59aeef2e0c86ec3f0f34ce77c205f3ef0b034cc Mon Sep 17 00:00:00 2001 From: "Claudius \"keldu\" Holeksa" Date: Sun, 8 Nov 2026 22:04:06 +0100 Subject: Abstract move. Forstio independence --- modules/core/.nix/derivation.nix | 7 +- modules/core/c++/SConscript | 6 + modules/core/c++/abstract/common.hpp | 12 +- modules/core/c++/abstract/data.hpp | 979 ++++++++++++++++++-- modules/core/c++/abstract/data_math.hpp | 162 ++++ modules/core/c++/abstract/encode.hpp | 34 +- modules/core/c++/abstract/error.hpp | 240 ++++- modules/core/c++/abstract/iterator.hpp | 64 ++ modules/core/c++/abstract/json.hpp | 1126 +++++++++++++++++++++++ modules/core/c++/abstract/math.hpp | 279 ++++++ modules/core/c++/abstract/schema.hpp | 301 +++++- modules/core/c++/abstract/schema_factory.hpp | 130 +++ modules/core/c++/abstract/stringify_schema.hpp | 200 +++- modules/core/c++/abstract/templates.hpp | 207 ++++- modules/core/c++/abstract/unit.hpp | 275 ++++++ modules/core/c++/abstract/unit_print.hpp | 62 ++ modules/core/c++/boundary.hpp | 138 +-- modules/core/c++/chunk.hpp | 34 +- modules/core/c++/collision.hpp | 86 +- modules/core/c++/common.hpp | 5 +- modules/core/c++/component.hpp | 6 +- modules/core/c++/component/psm.hpp | 18 +- modules/core/c++/config.hpp | 31 +- modules/core/c++/converter.hpp | 37 +- modules/core/c++/descriptor.hpp | 76 +- modules/core/c++/descriptor/common.hpp | 1 - modules/core/c++/descriptor/d1q3.hpp | 6 +- modules/core/c++/descriptor/d2q4.hpp | 6 +- modules/core/c++/descriptor/d2q5.hpp | 6 +- modules/core/c++/descriptor/d2q9.hpp | 6 +- modules/core/c++/descriptor/d3q19.hpp | 6 +- modules/core/c++/descriptor/d3q27.hpp | 6 +- modules/core/c++/environment.hpp | 10 +- modules/core/c++/equilibrium.hpp | 12 +- modules/core/c++/flatten.hpp | 13 +- modules/core/c++/fplbm.hpp | 62 +- modules/core/c++/geometry.hpp | 2 +- modules/core/c++/geometry/poiseulle_channel.hpp | 2 +- modules/core/c++/grid.hpp | 10 +- modules/core/c++/hlbm.hpp | 56 +- modules/core/c++/index.hpp | 10 +- modules/core/c++/iterator.hpp | 40 +- modules/core/c++/lbm.hpp | 13 +- modules/core/c++/lbm_unit.hpp | 3 +- modules/core/c++/macroscopic.hpp | 16 +- modules/core/c++/math/n_closest.hpp | 12 +- modules/core/c++/math/n_linear.hpp | 44 +- modules/core/c++/math/round.hpp | 8 +- modules/core/c++/memory.hpp | 16 +- modules/core/c++/momentum_gather.hpp | 8 +- modules/core/c++/over/chunk.hpp | 4 +- modules/core/c++/particle.hpp | 6 +- modules/core/c++/particle/aabb.hpp | 18 +- modules/core/c++/particle/blur.hpp | 12 +- modules/core/c++/particle/cuboid/aabb.hpp | 6 +- modules/core/c++/particle/geometry/circle.hpp | 24 +- modules/core/c++/particle/geometry/cube.hpp | 4 +- modules/core/c++/particle/particle.hpp | 100 +- modules/core/c++/particle/particle_opa.hpp | 18 +- modules/core/c++/particle/porosity.hpp | 38 +- modules/core/c++/particle/schema.hpp | 1 - modules/core/c++/psm.hpp | 72 +- modules/core/c++/rar.hpp | 4 +- modules/core/c++/schema.hpp | 3 +- modules/core/c++/stream.hpp | 8 +- modules/core/c++/util.hpp | 10 +- modules/core/c++/write_csv.hpp | 58 +- modules/core/c++/write_json.hpp | 32 +- modules/core/c++/write_vtk.hpp | 86 +- modules/core/tests/abstract_data.cpp | 390 ++++++++ modules/core/tests/abstract_foundation.cpp | 189 ++++ modules/core/tests/abstract_json.cpp | 326 +++++++ modules/core/tests/chunk.cpp | 4 +- modules/core/tests/converter.cpp | 2 +- modules/core/tests/equilibrium.cpp | 8 +- modules/core/tests/flatten.cpp | 8 +- modules/core/tests/iterator.cpp | 30 +- modules/core/tests/math.cpp | 12 +- modules/core/tests/memory.cpp | 2 +- modules/core/tests/particles.cpp | 40 +- modules/core/tests/vtk_write.cpp | 4 +- 81 files changed, 5555 insertions(+), 853 deletions(-) create mode 100644 modules/core/c++/abstract/data_math.hpp create mode 100644 modules/core/c++/abstract/iterator.hpp create mode 100644 modules/core/c++/abstract/json.hpp create mode 100644 modules/core/c++/abstract/math.hpp create mode 100644 modules/core/c++/abstract/schema_factory.hpp create mode 100644 modules/core/c++/abstract/unit.hpp create mode 100644 modules/core/c++/abstract/unit_print.hpp create mode 100644 modules/core/tests/abstract_data.cpp create mode 100644 modules/core/tests/abstract_foundation.cpp create mode 100644 modules/core/tests/abstract_json.cpp (limited to 'modules/core') diff --git a/modules/core/.nix/derivation.nix b/modules/core/.nix/derivation.nix index 55a414f..cf7e37c 100644 --- a/modules/core/.nix/derivation.nix +++ b/modules/core/.nix/derivation.nix @@ -16,12 +16,11 @@ stdenv.mkDerivation { clang-tools ]; + # The library itself is forstio free; only the test suite still uses + # forstio/test/suite.hpp, which needs core for its common.hpp and the + # forstio-test runner. buildInputs = [ forstio.core - forstio.async - forstio.codec - forstio.codec-unit - forstio.codec-json ]; doCheck = true; diff --git a/modules/core/c++/SConscript b/modules/core/c++/SConscript index f45660c..5bc93a1 100644 --- a/modules/core/c++/SConscript +++ b/modules/core/c++/SConscript @@ -15,6 +15,10 @@ core_env = env.Clone(); core_env.sources = sorted(glob.glob(dir_path + "/*.cpp")); core_env.headers = sorted(glob.glob(dir_path + "/*.hpp")); +core_env.abstract_headers = sorted(glob.glob(dir_path + "/abstract/*.hpp")); + +core_env.component_headers = sorted(glob.glob(dir_path + "/component/*.hpp")); + core_env.descriptor_headers = sorted(glob.glob(dir_path + "/descriptor/*.hpp")); core_env.particle_headers = sorted(glob.glob(dir_path + "/particle/*.hpp")); core_env.particle_geometry_headers = sorted(glob.glob(dir_path + "/particle/geometry/*.hpp")); @@ -31,6 +35,8 @@ env.library_static = core_env.StaticLibrary('#build/kel-lbm', [objects]); env.Install('$prefix/lib/', env.library_static); env.Install('$prefix/include/kel/lbm/', core_env.headers); +env.Install('$prefix/include/kel/lbm/abstract/', core_env.abstract_headers); +env.Install('$prefix/include/kel/lbm/component/', core_env.component_headers); env.Install('$prefix/include/kel/lbm/descriptor/', core_env.descriptor_headers); env.Install('$prefix/include/kel/lbm/particle/', core_env.particle_headers); env.Install('$prefix/include/kel/lbm/particle/geometry/', core_env.particle_geometry_headers); diff --git a/modules/core/c++/abstract/common.hpp b/modules/core/c++/abstract/common.hpp index 1b4e150..c3237ff 100644 --- a/modules/core/c++/abstract/common.hpp +++ b/modules/core/c++/abstract/common.hpp @@ -1,11 +1,13 @@ #pragma once +#include #include #include #include #include -namespace saw { +namespace kel { +namespace lbm { #define KEL_CONCAT_(x, y) x##y #define KEL_CONCAT(x, y) KEL_CONCAT_(x, y) @@ -138,8 +140,11 @@ struct void_t {}; /** * Helper function since changing returns between void_t{} and make_error<...>() is a bit annoying. + * + * Inline, because lbm's core is header only and the SConscript globs cpp files + * directly under c++ only, so a unit under abstract would never be compiled. */ -void_t make_void(); +inline void_t make_void() { return {}; } template struct void_fix { typedef T Type; }; template <> struct void_fix { typedef void_t Type; }; @@ -150,4 +155,5 @@ template <> struct void_unfix { typedef void Type; }; template using unfix_void = typename void_unfix::Type; template constexpr bool always_false = false; -} // namespace saw +} // namespace lbm +} // namespace kel diff --git a/modules/core/c++/abstract/data.hpp b/modules/core/c++/abstract/data.hpp index bef9a73..3b3c9f3 100644 --- a/modules/core/c++/abstract/data.hpp +++ b/modules/core/c++/abstract/data.hpp @@ -1,111 +1,946 @@ #pragma once -#include "schema.hpp" -#include "encode.hpp" +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include + #include "common.hpp" +#include "encode.hpp" +#include "error.hpp" +#include "schema.hpp" +#include "templates.hpp" namespace kel { namespace lbm { -template -class data final { - static_assert(always_false, "Invalid schema + encode in data specialization"); + +/** + * Maps a Primitive schema onto the C++ type that actually holds it. + */ +template struct native_data_type; + +template <> struct native_data_type> { + using type = int8_t; +}; +template <> struct native_data_type> { + using type = int16_t; +}; +template <> struct native_data_type> { + using type = int32_t; +}; +template <> struct native_data_type> { + using type = int64_t; +}; + +template <> struct native_data_type> { + using type = uint8_t; +}; +template <> struct native_data_type> { + using type = uint16_t; +}; +template <> struct native_data_type> { + using type = uint32_t; +}; +template <> struct native_data_type> { + using type = uint64_t; }; -template -class data,Encode> final { +template <> struct native_data_type> { + using type = float; +}; +template <> struct native_data_type> { + using type = double; +}; + +/** + * MixedPrecision reads as its interface type, so that is what a caller sees. + */ +template +struct native_data_type> { + using type = typename native_data_type::type; +}; + +template +class data { + static_assert(always_false, + "Invalid schema + encode in data specialization"); +}; + +/** + * The index type used to address a shape of the given rank. + */ +template +using index_data = data, enc::Native>; + +template <> class data final { +public: + using Schema = sch::Void; + using MetaSchema = typename Schema::Meta; + + constexpr data() = default; +}; + +template <> class data final { public: - using Schema = sch::Primitive; - using Encode = Encode; + using Schema = sch::Bool; + using MetaSchema = typename Schema::Meta; + private: - native_data_type::type value_; + bool value_; + public: - data(): - value_{} - {} + constexpr data() : value_{false} {} + constexpr data(data) : value_{false} {} + + KEL_DEFAULT_COPY(data); + KEL_DEFAULT_MOVE(data); + + constexpr data(bool value__) : value_{value__} {} + + constexpr void set(bool val) { value_ = val; } + + constexpr bool get() const { return value_; } + + template + constexpr bool equals(const data &rhs) const { + return get() == rhs.get(); + } + + template + constexpr bool operator==(const data &rhs) const { + return equals(rhs); + } - data(native_data_type::type value__): - value_{value__} + template + constexpr bool operator!=(const data &rhs) const { + return get() != rhs.get(); + } + + constexpr data operator!() const { return {!get()}; } + + template + constexpr data + operator&&(const data &rhs) const { + return {get() && rhs.get()}; + } + + template + constexpr data + operator||(const data &rhs) const { + return {get() || rhs.get()}; + } + + template + constexpr data cast_to() const { + return {static_cast::type>(value_)}; + } +}; + +template +class data, enc::Native> final { +public: + using Schema = sch::Primitive; + using MetaSchema = typename Schema::Meta; + using NativeType = typename native_data_type::type; + +private: + NativeType value_; + +public: + constexpr data() : value_{} {} + constexpr data(data) : value_{} {} + + KEL_DEFAULT_COPY(data); + KEL_DEFAULT_MOVE(data); + + constexpr data(NativeType value__) : value_{std::move(value__)} {} + + constexpr void set(NativeType val) { value_ = val; } + + constexpr NativeType get() const { return value_; } + + constexpr data + operator*(const data &rhs) const { + return {static_cast(get() * rhs.get())}; + } + + constexpr data + operator/(const data &rhs) const { + return {static_cast(get() / rhs.get())}; + } + + constexpr data + operator+(const data &rhs) const { + return {static_cast(get() + rhs.get())}; + } + + constexpr data + operator-(const data &rhs) const { + return {static_cast(get() - rhs.get())}; + } + + constexpr data operator-() const { + return {static_cast(-get())}; + } + + constexpr data & + operator+=(const data &rhs) { + value_ = static_cast(value_ + rhs.get()); + return *this; + } + + constexpr data & + operator-=(const data &rhs) { + value_ = static_cast(value_ - rhs.get()); + return *this; + } + + constexpr data & + operator*=(const data &rhs) { + value_ = static_cast(value_ * rhs.get()); + return *this; + } + + constexpr data & + operator/=(const data &rhs) { + value_ = static_cast(value_ / rhs.get()); + return *this; + } + + constexpr data &operator++() { + set(static_cast(get() + static_cast(1))); + return *this; + } + + template + constexpr bool equals(const data &rhs) const { + return get() == rhs.get(); + } + + template + constexpr bool operator==(const data &rhs) const { + return equals(rhs); + } + + template + constexpr bool operator!=(const data &rhs) const { + return get() != rhs.get(); + } + + template + constexpr bool operator<(const data &rhs) const { + return get() < rhs.get(); + } + + template + constexpr bool operator>(const data &rhs) const { + return get() > rhs.get(); + } + + template + constexpr bool operator<=(const data &rhs) const { + return get() <= rhs.get(); + } + + template + constexpr bool operator>=(const data &rhs) const { + return get() >= rhs.get(); + } + + template + constexpr data cast_to() const { + return {static_cast::type>(value_)}; + } +}; + +/** + * Stored narrow, read wide. The stored value is kept as StorageType and every + * read widens it to InterfaceType, so arithmetic happens at interface + * precision and only the resting representation is narrow. + */ +template +class data, enc::Native> final { +public: + using Schema = sch::MixedPrecision; + using MetaSchema = typename Schema::Meta; + using StorageType = StorageT; + using InterfaceType = InterfaceT; + using NativeType = typename native_data_type::type; + +private: + data value_; + + static constexpr typename native_data_type::type + narrow(NativeType val) { + return static_cast::type>(val); + } + +public: + constexpr data() : value_{} {} + constexpr data(data) : value_{} {} + + KEL_DEFAULT_COPY(data); + KEL_DEFAULT_MOVE(data); + + constexpr data(NativeType val__) : value_{narrow(val__)} {} + + constexpr data(const data &val) + : value_{val.template cast_to()} {} + + constexpr NativeType get() const { + return value_.template cast_to().get(); + } + + constexpr void set(NativeType val) { value_.set(narrow(val)); } + + constexpr data + operator*(const data &rhs) const { + return {static_cast(get() * rhs.get())}; + } + + constexpr data + operator/(const data &rhs) const { + return {static_cast(get() / rhs.get())}; + } + + constexpr data + operator+(const data &rhs) const { + return {static_cast(get() + rhs.get())}; + } + + constexpr data + operator-(const data &rhs) const { + return {static_cast(get() - rhs.get())}; + } + + constexpr data operator-() const { + return {static_cast(-get())}; + } + + constexpr data & + operator+=(const data &rhs) { + set(static_cast(get() + rhs.get())); + return *this; + } + + constexpr data & + operator-=(const data &rhs) { + set(static_cast(get() - rhs.get())); + return *this; + } + + constexpr data & + operator*=(const data &rhs) { + set(static_cast(get() * rhs.get())); + return *this; + } + + constexpr data & + operator/=(const data &rhs) { + set(static_cast(get() / rhs.get())); + return *this; + } + + template + constexpr bool operator==(const data &rhs) const { + return get() == rhs.get(); + } + + template + constexpr bool operator!=(const data &rhs) const { + return get() != rhs.get(); + } + + template + constexpr bool operator<(const data &rhs) const { + return get() < rhs.get(); + } + + template + constexpr bool operator>(const data &rhs) const { + return get() > rhs.get(); + } + + template + constexpr data cast_to() const { + return {static_cast::type>(get())}; + } +}; + +/** + * Array whose extents are known at compile time. + * + * A rank zero FixedArray holds exactly one element, because the empty product + * is one. That is what makes Scalar work without a special case. + */ +template +class data, enc::Native> final { +public: + using Schema = sch::FixedArray; + using MetaSchema = typename Schema::Meta; + using Inner = data; + + static constexpr uint64_t Rank = sizeof...(D); + static constexpr uint64_t FlatSize = ct_multiply::value; + +private: + using ArrayT = std::array; + ArrayT value_; + + static constexpr std::array dims_{D...}; + + constexpr uint64_t get_flat_index(const index_data &i) const { + uint64_t s = 0; + uint64_t stride = 1; + + for (uint64_t iter = 0; iter < Rank; ++iter) { + assert(i.flat_at(iter).get() < dims_.at(iter)); + s += i.flat_at(iter).get() * stride; + stride *= dims_.at(iter); + } + + return s; + } + +public: + constexpr data() = default; + constexpr data(data) + requires(not std::is_same_v) {} - constexpr auto get() const { - return value_; + constexpr data(const ArrayT &value__) : value_{value__} {} + + /** + * Forwarding constructor, so the elements can be written without spelling + * out the inner array: data>{0,1,2}. + * + * The guards keep it clear of the copy constructor and of the metadata + * constructor. + * + * It is deliberately implicit even for a single element. That is what lets + * a rank one shape be addressed as at({i}) as well as at({{i}}): the index + * is built here rather than through a separate data overload. + * Offering both spellings as overloads instead makes at({{i}}) ambiguous, + * since a one element list converts equally well to either. + */ + template + requires(sizeof...(Args) == FlatSize) && + (sizeof...(Args) > 1u || + (!std::same_as, data> && ...)) && + (!std::same_as, + data> && + ...) && + (std::constructible_from && ...) + constexpr data(Args &&...args) + : value_{Inner{std::forward(args)}...} {} + + KEL_DEFAULT_COPY(data); + KEL_DEFAULT_MOVE(data); + + constexpr Inner &at(const index_data &i) { + return value_.at(this->get_flat_index(i)); } - void set(native_data_type value__){ - value_ = value__; + constexpr const Inner &at(const index_data &i) const { + return value_.at(this->get_flat_index(i)); } - constexpr bool operator==(const data& rhs) const { - return value_ == rhs.value_; + constexpr Inner &operator()(const index_data &i) { + return value_.at(this->get_flat_index(i)); } - - constexpr bool operator!=(const data& rhs) const { - return value_ != rhs.value_; + + constexpr const Inner &operator()(const index_data &i) const { + return value_.at(this->get_flat_index(i)); } - - constexpr bool operator>(const data& rhs) const { - return value_ > rhs.value_; + + /** + * Rank agnostic access by position in the flattened storage. + * + * This is what lets a rank N index array be walked element by element. + * at() cannot serve that purpose, since for rank other than one a bare + * integer is not a valid index into this shape. + */ + constexpr Inner &flat_at(uint64_t i) { return value_.at(i); } + + constexpr const Inner &flat_at(uint64_t i) const { return value_.at(i); } + + template static constexpr uint64_t get_dim_size() { + static_assert(i < Rank, "Dimension index is too large for this shape"); + return parameter_pack_value::value; + } + + static constexpr uint64_t get_dim_size(uint64_t i) { return dims_.at(i); } + + static constexpr index_data get_dims() { return {D...}; } + + static constexpr data flat_dims() { + return {FlatSize}; + } + + static constexpr data size() { + return {FlatSize}; + } + + constexpr Inner *flat_data() { + if constexpr (FlatSize == 0u) { + return nullptr; + } else { + return &value_[0u]; + } + } + + constexpr const Inner *flat_data() const { + if constexpr (FlatSize == 0u) { + return nullptr; + } else { + return &value_[0u]; + } + } + + template + constexpr bool operator==(const data &rhs) const { + for (uint64_t i = 0; i < FlatSize; ++i) { + if (!(flat_at(i) == rhs.flat_at(i))) { + return false; + } + } + return true; + } +}; + +/** + * Array whose extents are only known at runtime. The extents are the metadata, + * so constructing one from its MetaSchema is what gives it a shape. + */ +template +class data, enc::Native> final { +public: + using Schema = sch::Array; + using MetaSchema = typename Schema::Meta; + using Inner = data; + + static constexpr uint64_t Rank = Dim; + +private: + index_data dims_; + std::vector value_; + + constexpr uint64_t get_full_size() const { + uint64_t s = 1; + for (uint64_t iter = 0; iter < Dim; ++iter) { + s *= dims_.flat_at(iter).get(); + } + return s; + } + + uint64_t get_flat_index(const index_data &i) const { + assert(value_.size() == get_full_size()); + uint64_t s = 0; + uint64_t stride = 1; + + for (uint64_t iter = 0; iter < Dim; ++iter) { + uint64_t ind = i.flat_at(iter).get(); + assert(ind < dims_.flat_at(iter).get()); + s += ind * stride; + stride *= dims_.flat_at(iter).get(); + } + + return s; + } + +public: + data() : dims_{}, value_{} { + for (uint64_t iter = 0; iter < Dim; ++iter) { + dims_.flat_at(iter).set(0u); + } + } + + KEL_DEFAULT_COPY(data); + KEL_DEFAULT_MOVE(data); + + data(const data &init__) + : dims_{init__}, value_{} { + value_.resize(get_full_size()); + } + + template + requires(sizeof...(Dims) == Dim) + data(Dims... size_) + : data{index_data{static_cast(size_)...}} {} + + template error_or add(Inner val) { + /** + * Only the last dimension can grow without moving anything, since it + * is the one that does not take part in the stride. Higher dimensional + * growth would mean restriding the whole buffer, so it is left out. + */ + static_assert(Dim == 1, "Currently can't deal with higher dims"); + static_assert(i < Dim, + "Can't add to dimension. Index i larger than dimension size"); + + try { + value_.emplace_back(std::move(val)); + } catch (const std::exception &e) { + (void)e; + return make_error(); + } + + ++dims_.flat_at(i); + + return make_void(); + } + + Inner &at(const index_data &i) { + return value_.at(this->get_flat_index(i)); + } + + const Inner &at(const index_data &i) const { + return value_.at(this->get_flat_index(i)); + } + + Inner &operator()(const index_data &i) { + return value_.at(this->get_flat_index(i)); + } + + const Inner &operator()(const index_data &i) const { + return value_.at(this->get_flat_index(i)); + } + + Inner &flat_at(uint64_t i) { return value_.at(i); } + + const Inner &flat_at(uint64_t i) const { return value_.at(i); } + + template + constexpr data get_dim_size() const { + static_assert(i < Dim, "Dimension index is too large for this shape"); + return dims_.flat_at(i); + } + + constexpr std::size_t get_dim_size(uint64_t i) const { + return dims_.flat_at(i).get(); + } + + constexpr data size() const { + return {value_.size()}; + } + + index_data get_dims() const { return dims_; } + + /** + * The metadata of a value is whatever it would take to rebuild its shape. + */ + index_data meta() const { return dims_; } + + index_data dims() const { return dims_; } + + data flat_size() const { + return {value_.size()}; + } + + Inner *flat_data() { + if (value_.size() == 0u) { + return nullptr; + } + return &value_[0u]; + } + + const Inner *flat_data() const { + if (value_.size() == 0u) { + return nullptr; + } + return &value_[0u]; + } +}; + +/** + * Variable length string. Its length is its metadata. + */ +template <> class data final { +public: + using Schema = sch::String; + using MetaSchema = typename Schema::Meta; + +private: + std::string value_; + +public: + data() = default; + + KEL_DEFAULT_COPY(data); + KEL_DEFAULT_MOVE(data); + + data(data init) { value_.resize(init.get()); } + + data(std::string value__) : value_{std::move(value__)} {} + + data(const char *value__) : value_{value__} {} + + data size() const { return {value_.size()}; } + + void set(std::string str) { value_ = std::move(str); } + + char &at(data i) { return value_.at(i.get()); } + + const char &at(data i) const { + return value_.at(i.get()); } - - constexpr bool operator<(const data& rhs) const { - return value_ < rhs.value_; + + char get_at(data i) const { + return value_.at(i.get()); } - - constexpr bool operator>=(const data& rhs) const { - return value_ >= rhs.value_; + + void set_at(data i, char val) { + value_.at(i.get()) = val; } - - constexpr bool operator<=(const data& rhs) const { - return value_ >= rhs.value_; + + std::string_view stl_view() { return value_; } + + std::string_view stl_view() const { return value_; } + + std::string stl_string() const { return value_; } + + template + bool operator==(const data &rhs) const { + return stl_view() == rhs.stl_view(); } - - constexpr bool equals(const data& rhs) const { - return (*this) == rhs; + + template + bool operator!=(const data &rhs) const { + return stl_view() != rhs.stl_view(); } - data operator+(const data& rhs) const { - return {value_ + rhs.value_}; + template + bool operator<(const data &rhs) const { + return stl_view() < rhs.stl_view(); } - - data operator-(const data& rhs) const { - return {value_ - rhs.value_}; +}; + +template class data, enc::Native> final { +public: + using Schema = sch::Tuple; + using MetaSchema = typename Schema::Meta; + +private: + std::tuple...> value_; + + template struct init_helper { + static void apply(std::tuple...> &val, + const data &init) { + std::get(val) = {init.template get()}; + + if constexpr ((i + 1u) < sizeof...(T)) { + init_helper::apply(val, init); + } + } + }; + +public: + data() = default; + + data(const data &init) + requires(not std::is_same_v) + { + if constexpr (0u < sizeof...(T)) { + init_helper<0u>::apply(value_, init); + } } - - data operator*(const data& rhs) const { - return {value_ * rhs.value_}; + + KEL_DEFAULT_COPY(data); + KEL_DEFAULT_MOVE(data); + + template + data::type, enc::Native> &get() { + return std::get(value_); } - - data operator/(const data& rhs) const { - return {value_ / rhs.value_}; + + template + const data::type, enc::Native> & + get() const { + return std::get(value_); } - - data& operator+=(const data& rhs) { - value_ += rhs.value_; - return *this + + static constexpr uint64_t size() { return sizeof...(T); } +}; + +template +class data...>, enc::Native> final { +public: + using Schema = sch::Struct...>; + using MetaSchema = typename Schema::Meta; + +private: + std::tuple...> value_; + + template struct init_helper { + static void apply(std::tuple...> &val, + const data &init) { + std::get(val) = { + init.template get::literal>()}; + + if constexpr ((i + 1u) < sizeof...(T)) { + init_helper::apply(val, init); + } + } + }; + + template + static constexpr size_t index_of = + parameter_key_pack_index::value; + +public: + data() = default; + + data(const data &init) + requires(not std::is_same_v) + { + if constexpr (0u < sizeof...(T)) { + init_helper<0u>::apply(value_, init); + } } - - data& operator-=(const data& rhs) { - value_ -= rhs.value_; - return *this + + KEL_DEFAULT_COPY(data); + KEL_DEFAULT_MOVE(data); + + template + data, T...>::type, + enc::Native> & + get() { + return std::get>(value_); } - - data& operator*=(const data& rhs) { - value_ *= rhs.value_; - return *this + + template + const data, T...>::type, + enc::Native> & + get() const { + return std::get>(value_); } - - data& operator/=(const data& rhs) { - value_ /= rhs.value_; - return *this + + template + data::type, enc::Native> & + get_at_index() { + return std::get(value_); } - template - data cast_to() const { - data val{static_cast::type>(value_)}; - return val; + template + const data::type, enc::Native> & + get_at_index() const { + return std::get(value_); + } + + static constexpr data size() { + return {sizeof...(T)}; + } +}; + +template +class data...>, enc::Native> final { +public: + using Schema = sch::Union...>; + using MetaSchema = typename Schema::Meta; + +private: + std::variant...> value_; + + template + static constexpr size_t index_of = + parameter_key_pack_index::value; + +public: + data() = default; + + KEL_DEFAULT_COPY(data); + KEL_DEFAULT_MOVE(data); + + template + void set(data, T...>::type, + enc::Native> + val) { + value_ = std::move(val); + } + + template + data, T...>::type, enc::Native> & + init() { + value_.template emplace>(); + return get(); + } + + template bool holds_alternative() const { + return index_of == value_.index(); + } + + template + data, T...>::type, enc::Native> & + get() { + return std::get>(value_); + } + + template + const data, T...>::type, + enc::Native> & + get() const { + return std::get>(value_); + } + + constexpr data index() const { + return {value_.index()}; } }; +template +class data, enc::Native> final { +public: + using Schema = sch::Map; + using MetaSchema = typename Schema::Meta; + +private: + std::map, data> vals_; + +public: + data() = default; + + KEL_DEFAULT_COPY(data); + KEL_DEFAULT_MOVE(data); + + data(data) {} + + error_or emplace(ref> key, + ref> value) { + auto insert = vals_.emplace(std::make_pair(key(), value())); + if (!insert.second) { + return make_error(); + } + return make_void(); + } + + error_or erase(ref> key) { + auto erased = vals_.erase(key()); + if (erased == 0u) { + return make_error(); + } + return make_void(); + } + + error_or>> find(ref> key) { + auto found = vals_.find(key()); + if (found == vals_.end()) { + return make_error(); + } + + return ptr>{found->second}; + } + + data size() const { return {vals_.size()}; } +}; -} -} +} // namespace lbm +} // namespace kel diff --git a/modules/core/c++/abstract/data_math.hpp b/modules/core/c++/abstract/data_math.hpp new file mode 100644 index 0000000..eb3f2df --- /dev/null +++ b/modules/core/c++/abstract/data_math.hpp @@ -0,0 +1,162 @@ +#pragma once + +#include + +#include "data.hpp" +#include "iterator.hpp" + +namespace kel { +namespace lbm { + +/** + * Tensor of compile time extents over `Inner`. + * + * Storage is a FixedArray of the same extents; the tensor adds the algebra on + * top. Rank zero is a scalar and still holds one element. + */ +template +class data, enc::Native> final { +public: + using Schema = sch::Tensor; + using MetaSchema = typename Schema::Meta; + using InnerData = data; + using Storage = data, enc::Native>; + + static constexpr uint64_t Rank = sizeof...(Dims); + static constexpr uint64_t FlatSize = ct_multiply::value; + +private: + Storage values_; + +public: + data() = default; + + KEL_DEFAULT_COPY(data); + KEL_DEFAULT_MOVE(data); + + data(const InnerData &inner_value__) + requires(Rank == 0u) + : values_{inner_value__} {} + + data(const Storage &inner_values__) + requires(Rank > 0u) + : values_{inner_values__} {} + + /** + * Forwarding constructor, so a tensor can be written as its elements in + * row major order: data>{1.0, 2.0, 3.0, 4.0}. + * + * The guards keep it clear of the copy constructor and of the two + * constructors above in the single element case. + */ + template + requires(sizeof...(Args) == FlatSize) && + (sizeof...(Args) > 1u || + (!std::same_as, data> && ...)) && + (!std::same_as, InnerData> && ...) && + (!std::same_as, Storage> && ...) && + (std::constructible_from && ...) + data(Args &&...args) : values_{std::forward(args)...} {} + + InnerData &at(const index_data &index) { return values_.at(index); } + + const InnerData &at(const index_data &index) const { + return values_.at(index); + } + + InnerData &operator()(const index_data &index) { + return values_.at(index); + } + + const InnerData &operator()(const index_data &index) const { + return values_.at(index); + } + + InnerData &flat_at(uint64_t i) { return values_.flat_at(i); } + + const InnerData &flat_at(uint64_t i) const { return values_.flat_at(i); } + + static constexpr data size() { + return {FlatSize}; + } + + data + operator+(const data &rhs) const { + data c; + for (uint64_t i = 0; i < FlatSize; ++i) { + c.flat_at(i) = flat_at(i) + rhs.flat_at(i); + } + return c; + } + + data + operator-(const data &rhs) const { + data c; + for (uint64_t i = 0; i < FlatSize; ++i) { + c.flat_at(i) = flat_at(i) - rhs.flat_at(i); + } + return c; + } + + data operator-() const { + data c; + for (uint64_t i = 0; i < FlatSize; ++i) { + c.flat_at(i) = -flat_at(i); + } + return c; + } + + data &operator+=(const data &rhs) { + for (uint64_t i = 0; i < FlatSize; ++i) { + flat_at(i) += rhs.flat_at(i); + } + return *this; + } + + data &operator-=(const data &rhs) { + for (uint64_t i = 0; i < FlatSize; ++i) { + flat_at(i) -= rhs.flat_at(i); + } + return *this; + } + + data + operator*(const data, enc::Native> &scal) const { + data c; + for (uint64_t i = 0; i < FlatSize; ++i) { + c.flat_at(i) = flat_at(i) * scal.flat_at(0u); + } + return c; + } + + data + operator/(const data, enc::Native> &scal) const { + data c; + for (uint64_t i = 0; i < FlatSize; ++i) { + c.flat_at(i) = flat_at(i) / scal.flat_at(0u); + } + return c; + } + + template + bool operator==(const data &rhs) const { + for (uint64_t i = 0; i < FlatSize; ++i) { + if (!(flat_at(i) == rhs.flat_at(i))) { + return false; + } + } + return true; + } + + template + data, enc::Native> cast_to() const { + data, enc::Native> changed; + for (uint64_t i = 0; i < FlatSize; ++i) { + changed.flat_at(i) = flat_at(i).template cast_to(); + } + return changed; + } +}; + +} // namespace lbm +} // namespace kel diff --git a/modules/core/c++/abstract/encode.hpp b/modules/core/c++/abstract/encode.hpp index 64aef4a..571722a 100644 --- a/modules/core/c++/abstract/encode.hpp +++ b/modules/core/c++/abstract/encode.hpp @@ -1,9 +1,35 @@ #pragma once +#include "string_literal.hpp" + namespace kel { namespace lbm { namespace enc { -struct Native {}; -} -} -} +/** + * The in-memory layout the data class uses by default: every value is held as + * the native C++ type the schema maps onto. + */ +struct Native { + static constexpr string_literal name = "enc::Native"; +}; + +/** + * Contiguous, directly addressable layout. Kept distinct from Native because + * an encoding that can hand out a raw pointer is a stronger guarantee than one + * that merely stores values natively. + */ +struct NativeRaw { + static constexpr string_literal name = "enc::NativeRaw"; +}; + +struct Json { + static constexpr string_literal name = "enc::Json"; +}; +} // namespace enc + +#ifndef KEL_LBM_DEFAULT_DATA_ENCODING +#define KEL_LBM_DEFAULT_DATA_ENCODING ::kel::lbm::enc::Native +#endif + +} // namespace lbm +} // namespace kel diff --git a/modules/core/c++/abstract/error.hpp b/modules/core/c++/abstract/error.hpp index 94a2c35..be161a9 100644 --- a/modules/core/c++/abstract/error.hpp +++ b/modules/core/c++/abstract/error.hpp @@ -5,6 +5,7 @@ #include #include #include +#include #include #include @@ -12,7 +13,8 @@ #include "common.hpp" -namespace saw { +namespace kel { +namespace lbm { /** * Utility class for generating errors. Has a base distinction between * critical and recoverable errors. Additional code ids can be provided to the @@ -39,10 +41,10 @@ private: std::variant error_message_; public: - error(error::code id, bool is_critical); - error(error::code id, bool is_critical, const std::string_view &msg); - error(error::code id, bool is_critical, std::string&& msg); - error(error &&error); + inline error(error::code id, bool is_critical); + inline error(error::code id, bool is_critical, const std::string_view &msg); + inline error(error::code id, bool is_critical, std::string&& msg); + inline error(error &&error); KEL_FORBID_COPY(error); @@ -51,37 +53,37 @@ public: /** * Returns a string view to the message */ - const std::string_view get_message() const; + inline const std::string_view get_message() const; /** * Returns a string view which describes which error this is. */ - const std::string_view get_category() const; + inline const std::string_view get_category() const; /** * Checks if it's an error at all, since 0 is reserved for no error. */ - bool failed() const; + inline bool failed() const; /** * Checks if the error is critical. */ - bool is_critical() const; + inline bool is_critical() const; /** * Checks if the error is recoverable. */ - bool is_recoverable() const; + inline bool is_recoverable() const; /** * Replaces the copy constructor. We need this since we want to explicitly copy and not implicitly */ - error copy_error() const; + inline error copy_error() const; /** * Return the id. */ - code get_id() const; + inline code get_id() const; /** * Provide an error struct and check if it matches the type @@ -113,21 +115,21 @@ private: std::vector infos_; public: - error_registry(); + inline error_registry(); KEL_FORBID_COPY(error_registry); KEL_FORBID_MOVE(error_registry); - error_or search_category(const error::code& id) const; + inline error_or search_category(const error::code& id) const; - error_or search_id(const std::string_view& desc) const; + inline error_or search_id(const std::string_view& desc) const; - error_or search_or_register_id(const std::string_view& desc, bool is_critical); + inline error_or search_or_register_id(const std::string_view& desc, bool is_critical); - bool is_critical(error::code cd) const; + inline bool is_critical(error::code cd) const; }; -error_registry& get_error_registry(); +inline error_registry& get_error_registry(); template error::code get_template_error_id(){ @@ -148,7 +150,7 @@ error::code get_template_error_id(){ } } -error make_error(error::code code, const std::string_view &generic); +inline error make_error(error::code code, const std::string_view &generic); template error make_error(const std::string_view& generic){ error::code id = impl::get_template_error_id(); @@ -156,6 +158,22 @@ template error make_error(const std::string_view& generic){ return error{id, T::is_critical, generic}; } +/** + * Overload taking ownership of the message. + * + * The string_view overload above stores the view, not a copy, so it is only + * safe for messages that outlive the error -- string literals, in practice. + * Use this one whenever the text is built at runtime or borrowed from + * something about to go away. + */ +template +requires std::is_same_v, std::string> +error make_error(S&& generic){ + error::code id = impl::get_template_error_id(); + // Keep error, don't use make_error + return error{id, T::is_critical, std::string{std::forward(generic)}}; +} + template error make_error(){ error::code id = impl::get_template_error_id(); // Keep error, don't use make_error @@ -179,7 +197,7 @@ public: func_ = [](){return "";}; return error{id, T::is_critical, std::move(err_str)}; }catch(const std::exception&){} - return make_error(generic); + return lbm::make_error(generic); } }; @@ -243,7 +261,7 @@ struct already_exists { /** * Shorthand for no error happened */ -error no_error(); +inline error no_error(); /** * Exception alternative. Since I code without exceptions this class is @@ -318,7 +336,183 @@ bool error::is_type() const { return error_code_ == impl::get_template_error_id(); } -} // namespace saw +/** + * Implementation. + * + * These live in the header and are inline, because lbm's core is header only: + * the SConscript globs cpp files directly under c++ only, so a translation + * unit placed under abstract would never be handed to the compiler. + */ + +inline error::error(error::code code_, bool is_critical__) + : error_code_{static_cast(code_)}, is_critical_{is_critical__} {} + +inline error::error(error::code code_, bool is_critical__, const std::string_view &msg) + : + error_code_{static_cast(code_)} + , is_critical_{is_critical__}, error_message_{msg}{} + +inline error::error(error::code code_, bool is_critical__, std::string&& msg): + error_code_{static_cast(code_)}, + is_critical_{is_critical__}, + error_message_{std::move(msg)} +{} + +inline error::error(error &&error) + : + error_code_{std::move(error.error_code_)} + , is_critical_{std::move(error.is_critical_)} + , error_message_{std::move(error.error_message_)}{} + +inline const std::string_view error::get_category() const { + auto& reg = impl::get_error_registry(); + + auto eov = reg.search_category(error_code_); + KEL_ASSERT(eov.is_value()){ + return "Error category not found. Report this error to the lbm maintainer"; + } + + return eov.get_value(); +} + +inline const std::string_view error::get_message() const { + return std::visit( + [](auto &&arg) -> const std::string_view { + using T = std::decay_t; + + if constexpr (std::is_same_v) { + return std::string_view{arg}; + } else if constexpr (std::is_same_v) { + return arg; + } else { + return "Error in class Error. Good luck :)"; + } + }, + error_message_); +} + +inline bool error::failed() const { + return !this->is_type(); +} + +inline bool error::is_critical() const { + return is_critical_; +} + +inline bool error::is_recoverable() const { + return !is_critical_; +} + +inline error error::copy_error() const { + auto copy_error_code = error_code_; + error error{copy_error_code, is_critical_}; + + try { + error.error_message_ = error_message_; + } catch (const std::bad_alloc &) { + error.error_message_ = + std::string_view{"Error while copying Error string. Out of memory"}; + } + + return error; +} + +inline error::code error::get_id() const { return error_code_; } + +namespace impl { +inline error_registry& get_error_registry() { + static own reg = nullptr; + if(!reg){ + reg = heap(); + } + + assert(reg); + return *reg; +} +} + +inline error no_error(){ + return make_error(); +} + +namespace impl { +inline error_registry::error_registry(): + infos_{ + { + err::no_error::description, + err::no_error::is_critical + }, + { + err::not_found::description, + err::not_found::is_critical + }, + { + err::out_of_memory::description, + err::out_of_memory::is_critical + } + } +{} + +inline error_or error_registry::search_category(const error::code& id) const { + if( id >= infos_.size()){ + return make_error(); + } + + return infos_.at(id).description; +} + +inline error_or error_registry::search_id(const std::string_view& desc)const{ + /** + * Search the index in the vector + */ + size_t i{}; + size_t info_max_size = std::min(infos_.size(), std::numeric_limits::max()); + for(i = 0; i < info_max_size; ++i){ + if(infos_.at(i).description == desc){ + break; + } + } + + if(i == info_max_size){ + return make_error(); + } + + return static_cast(i); +} + +inline error_or error_registry::search_or_register_id(const std::string_view& desc, bool is_critical){ + auto err_or_id = search_id(desc); + + if(err_or_id.is_value()){ + return err_or_id.get_value(); + } + + auto& err = err_or_id.get_error(); + + if(err.is_type()){ + size_t new_index = infos_.size(); + if(new_index == std::numeric_limits::max()){ + return make_error("Error registry ids are exhausted"); + } + infos_.emplace_back(error_info{desc, is_critical}); + return static_cast(new_index); + } + + return std::move(err); +} + +inline bool error_registry::is_critical(error::code cd) const { + return infos_.at(cd).is_critical; +} +} + +inline error make_error(error::code cd, const std::string_view& generic){ + auto& reg = impl::get_error_registry(); + return error{cd, reg.is_critical(cd), generic}; +} + +} // namespace lbm +} // namespace kel #define KEL_MAKE_ERROR(ErrType, ErrMsg) \ - return saw::make_error(ErrMsg) + return ::kel::lbm::make_error(ErrMsg) diff --git a/modules/core/c++/abstract/iterator.hpp b/modules/core/c++/abstract/iterator.hpp new file mode 100644 index 0000000..81d5609 --- /dev/null +++ b/modules/core/c++/abstract/iterator.hpp @@ -0,0 +1,64 @@ +#pragma once + +#include "data.hpp" + +namespace kel { +namespace lbm { +namespace impl { + +template struct iterator_in_bounds { +private: + static constexpr uint64_t Rank = sizeof...(Dims); + static constexpr std::array dims_{Dims...}; + + template + static error_or apply_i(Func &func, index_data &index) { + if constexpr (level >= Rank) { + return func(index); + } else { + /** + * flat_at rather than at, because the index being walked is itself + * a rank Rank shape: a bare integer is only a valid index into it + * when Rank happens to be one. + */ + auto &coord = index.flat_at(level); + for (coord.set(0u); + coord.get() < parameter_pack_value::value; + ++coord) { + auto eov = apply_i(func, index); + if (eov.is_error()) { + return eov; + } + } + return make_void(); + } + } + +public: + static error_or apply(Func &func) { + index_data index; + return apply_i<0u>(func, index); + } +}; + +/** + * Rank zero still has exactly one position to visit, so the callback runs once + * with an empty index. + */ +template struct iterator_in_bounds { + static error_or apply(Func &func) { + index_data<0u> index; + return func(index); + } +}; + +} // namespace impl + +template struct rank_iterator { + template static error_or in_fixed_bounds(Func &&func) { + return impl::iterator_in_bounds::apply(func); + } +}; + +} // namespace lbm +} // namespace kel diff --git a/modules/core/c++/abstract/json.hpp b/modules/core/c++/abstract/json.hpp new file mode 100644 index 0000000..49bb87f --- /dev/null +++ b/modules/core/c++/abstract/json.hpp @@ -0,0 +1,1126 @@ +#pragma once + +#include +#include +#include +#include +#include + +#include "data.hpp" +#include "data_math.hpp" +#include "encode.hpp" +#include "error.hpp" +#include "schema.hpp" + +namespace kel { +namespace lbm { + +/** + * A value in its JSON form: simply the text. + * + * forstio's equivalent sat on a ring buffer, because its codecs feed off + * streaming I/O. Nothing in lbm's core streams JSON -- a config is read whole + * and a document is written whole -- so the text itself is the representation + * and the buffer machinery is not needed. + */ +template class data final { +public: + using SchemaType = Schema; + +private: + std::string value_; + +public: + data() = default; + + KEL_DEFAULT_COPY(data); + KEL_DEFAULT_MOVE(data); + + explicit data(std::string value__) : value_{std::move(value__)} {} + explicit data(std::string_view value__) : value_{value__} {} + + void set(std::string value__) { value_ = std::move(value__); } + + const std::string &stl_string() const { return value_; } + + std::string_view stl_view() const { return value_; } + + std::string &stl_string() { return value_; } + + data size() const { return {value_.size()}; } +}; + +template struct codec_config; + +template <> struct codec_config { + /** + * Indent nested values across multiple lines. + */ + bool pretty = false; + /** + * Strict decoding demands a fully described dataset: every member of a + * Struct has to be present. Non strict is the default, since config files + * usually only state the deviations from the defaults. + */ + bool strict = false; + /** + * Guards against pathological nesting in untrusted input. + */ + uint64_t depth = 64u; +}; + +namespace err { +struct json_malformed { + static constexpr std::string_view description = "Malformed JSON"; + static constexpr bool is_critical = false; +}; + +struct json_type_mismatch { + static constexpr std::string_view description = + "JSON value does not match the schema"; + static constexpr bool is_critical = false; +}; + +struct json_too_deep { + static constexpr std::string_view description = "JSON nesting is too deep"; + static constexpr bool is_critical = false; +}; + +struct json_missing_member { + static constexpr std::string_view description = + "JSON object is missing a required member"; + static constexpr bool is_critical = false; +}; +} // namespace err + +namespace impl { + +/** + * Cursor over the JSON text. Every read either advances past a well formed + * token or leaves the position untouched and reports an error. + */ +class json_parser final { +private: + std::string_view src_; + uint64_t pos_; + uint64_t depth_; + uint64_t max_depth_; + +public: + json_parser(std::string_view src__, uint64_t max_depth__) + : src_{src__}, pos_{0u}, depth_{0u}, max_depth_{max_depth__} {} + + uint64_t offset() const { return pos_; } + + bool at_end() const { return pos_ >= src_.size(); } + + void skip_whitespace() { + while (pos_ < src_.size()) { + const char c = src_[pos_]; + if (c == ' ' || c == '\t' || c == '\n' || c == '\r') { + ++pos_; + } else { + break; + } + } + } + + error_or peek() { + skip_whitespace(); + if (at_end()) { + return make_error("Unexpected end of input"); + } + return src_[pos_]; + } + + error_or expect(char c) { + auto eo_c = peek(); + if (eo_c.is_error()) { + return std::move(eo_c.get_error()); + } + if (eo_c.get_value() != c) { + return make_error("Unexpected character"); + } + ++pos_; + return make_void(); + } + + bool consume_if(char c) { + skip_whitespace(); + if (!at_end() && src_[pos_] == c) { + ++pos_; + return true; + } + return false; + } + + error_or enter() { + ++depth_; + if (depth_ > max_depth_) { + return make_error(); + } + return make_void(); + } + + void leave() { + if (depth_ > 0u) { + --depth_; + } + } + + /** + * Reads a quoted string, resolving the escapes JSON defines. \u is decoded + * to UTF-8; a lone surrogate is passed through as the replacement + * character rather than rejected, so one bad escape cannot sink a config. + */ + error_or parse_string() { + auto eo_q = expect('"'); + if (eo_q.is_error()) { + return std::move(eo_q.get_error()); + } + + std::string out; + while (true) { + if (at_end()) { + return make_error("Unterminated string"); + } + const char c = src_[pos_++]; + if (c == '"') { + return out; + } + if (c != '\\') { + out.push_back(c); + continue; + } + if (at_end()) { + return make_error("Dangling escape"); + } + const char e = src_[pos_++]; + switch (e) { + case '"': out.push_back('"'); break; + case '\\': out.push_back('\\'); break; + case '/': out.push_back('/'); break; + case 'b': out.push_back('\b'); break; + case 'f': out.push_back('\f'); break; + case 'n': out.push_back('\n'); break; + case 'r': out.push_back('\r'); break; + case 't': out.push_back('\t'); break; + case 'u': { + auto eo_cp = parse_hex4(); + if (eo_cp.is_error()) { + return std::move(eo_cp.get_error()); + } + uint32_t cp = eo_cp.get_value(); + if (cp >= 0xD800u && cp <= 0xDBFFu) { + // High surrogate: a low one must follow to form a pair. + if (pos_ + 1u < src_.size() && src_[pos_] == '\\' && + src_[pos_ + 1u] == 'u') { + pos_ += 2u; + auto eo_lo = parse_hex4(); + if (eo_lo.is_error()) { + return std::move(eo_lo.get_error()); + } + const uint32_t lo = eo_lo.get_value(); + if (lo >= 0xDC00u && lo <= 0xDFFFu) { + cp = 0x10000u + ((cp - 0xD800u) << 10) + + (lo - 0xDC00u); + } else { + cp = 0xFFFDu; + } + } else { + cp = 0xFFFDu; + } + } else if (cp >= 0xDC00u && cp <= 0xDFFFu) { + cp = 0xFFFDu; + } + append_utf8(out, cp); + break; + } + default: + return make_error("Unknown escape"); + } + } + } + + /** + * Returns the raw token of a JSON number, leaving the numeric conversion + * to the caller who knows the target type. + */ + error_or parse_number_token() { + skip_whitespace(); + const uint64_t start = pos_; + + if (!at_end() && (src_[pos_] == '-' || src_[pos_] == '+')) { + ++pos_; + } + while (!at_end() && src_[pos_] >= '0' && src_[pos_] <= '9') { + ++pos_; + } + if (!at_end() && src_[pos_] == '.') { + ++pos_; + while (!at_end() && src_[pos_] >= '0' && src_[pos_] <= '9') { + ++pos_; + } + } + if (!at_end() && (src_[pos_] == 'e' || src_[pos_] == 'E')) { + ++pos_; + if (!at_end() && (src_[pos_] == '-' || src_[pos_] == '+')) { + ++pos_; + } + while (!at_end() && src_[pos_] >= '0' && src_[pos_] <= '9') { + ++pos_; + } + } + + if (pos_ == start) { + return make_error("Expected a number"); + } + + return src_.substr(start, pos_ - start); + } + + error_or parse_bool() { + skip_whitespace(); + if (src_.compare(pos_, 4u, "true") == 0) { + pos_ += 4u; + return true; + } + if (src_.compare(pos_, 5u, "false") == 0) { + pos_ += 5u; + return false; + } + return make_error("Expected a boolean"); + } + + bool consume_null() { + skip_whitespace(); + if (src_.compare(pos_, 4u, "null") == 0) { + pos_ += 4u; + return true; + } + return false; + } + + /** + * Steps over an entire value without interpreting it. Used to ignore + * members the schema does not declare. + */ + error_or skip_value() { + auto eo_c = peek(); + if (eo_c.is_error()) { + return std::move(eo_c.get_error()); + } + + auto eo_enter = enter(); + if (eo_enter.is_error()) { + return std::move(eo_enter.get_error()); + } + + const char c = eo_c.get_value(); + error_or result = make_void(); + + if (c == '{' || c == '[') { + const char close = (c == '{') ? '}' : ']'; + ++pos_; + if (!consume_if(close)) { + while (true) { + if (c == '{') { + auto eo_key = parse_string(); + if (eo_key.is_error()) { + result = std::move(eo_key.get_error()); + break; + } + auto eo_colon = expect(':'); + if (eo_colon.is_error()) { + result = std::move(eo_colon.get_error()); + break; + } + } + auto eo_inner = skip_value(); + if (eo_inner.is_error()) { + result = std::move(eo_inner.get_error()); + break; + } + if (consume_if(close)) { + break; + } + auto eo_comma = expect(','); + if (eo_comma.is_error()) { + result = std::move(eo_comma.get_error()); + break; + } + } + } + } else if (c == '"') { + auto eo_s = parse_string(); + if (eo_s.is_error()) { + result = std::move(eo_s.get_error()); + } + } else if (consume_null()) { + // nothing to do + } else if (c == 't' || c == 'f') { + auto eo_b = parse_bool(); + if (eo_b.is_error()) { + result = std::move(eo_b.get_error()); + } + } else { + auto eo_n = parse_number_token(); + if (eo_n.is_error()) { + result = std::move(eo_n.get_error()); + } + } + + leave(); + return result; + } + +private: + error_or parse_hex4() { + if (pos_ + 4u > src_.size()) { + return make_error("Truncated \\u escape"); + } + uint32_t v = 0u; + for (uint64_t i = 0u; i < 4u; ++i) { + const char h = src_[pos_ + i]; + uint32_t d; + if (h >= '0' && h <= '9') { + d = static_cast(h - '0'); + } else if (h >= 'a' && h <= 'f') { + d = static_cast(h - 'a') + 10u; + } else if (h >= 'A' && h <= 'F') { + d = static_cast(h - 'A') + 10u; + } else { + return make_error("Bad hex digit"); + } + v = (v << 4) | d; + } + pos_ += 4u; + return v; + } + + static void append_utf8(std::string &out, uint32_t cp) { + if (cp < 0x80u) { + out.push_back(static_cast(cp)); + } else if (cp < 0x800u) { + out.push_back(static_cast(0xC0u | (cp >> 6))); + out.push_back(static_cast(0x80u | (cp & 0x3Fu))); + } else if (cp < 0x10000u) { + out.push_back(static_cast(0xE0u | (cp >> 12))); + out.push_back(static_cast(0x80u | ((cp >> 6) & 0x3Fu))); + out.push_back(static_cast(0x80u | (cp & 0x3Fu))); + } else { + out.push_back(static_cast(0xF0u | (cp >> 18))); + out.push_back(static_cast(0x80u | ((cp >> 12) & 0x3Fu))); + out.push_back(static_cast(0x80u | ((cp >> 6) & 0x3Fu))); + out.push_back(static_cast(0x80u | (cp & 0x3Fu))); + } + } +}; + +inline void json_append_escaped(std::string &out, std::string_view in) { + out.push_back('"'); + for (const char c : in) { + switch (c) { + case '"': out += "\\\""; break; + case '\\': out += "\\\\"; break; + case '\b': out += "\\b"; break; + case '\f': out += "\\f"; break; + case '\n': out += "\\n"; break; + case '\r': out += "\\r"; break; + case '\t': out += "\\t"; break; + default: + if (static_cast(c) < 0x20u) { + char buf[7]; + std::snprintf(buf, sizeof(buf), "\\u%04x", + static_cast(static_cast(c))); + out += buf; + } else { + out.push_back(c); + } + } + } + out.push_back('"'); +} + +inline void json_newline_indent(std::string &out, bool pretty, uint64_t level) { + if (!pretty) { + return; + } + out.push_back('\n'); + for (uint64_t i = 0u; i < level; ++i) { + out += " "; + } +} + +/** + * Renders a native value as JSON text. + */ +template struct json_encode { + static_assert(always_false, + "This schema has no JSON representation"); +}; + +template <> struct json_encode { + static error_or apply(const data &, + std::string &out, bool, uint64_t) { + out += "null"; + return make_void(); + } +}; + +template <> struct json_encode { + static error_or apply(const data &in, + std::string &out, bool, uint64_t) { + out += in.get() ? "true" : "false"; + return make_void(); + } +}; + +template struct json_encode> { + static error_or + apply(const data, enc::Native> &in, std::string &out, + bool, uint64_t) { + using Native = typename native_data_type>::type; + const Native v = in.get(); + + if constexpr (std::is_floating_point_v) { + /** + * max_digits10 is the shortest precision that always round trips + * back to the same value, so a config survives a save/load cycle. + */ + char buf[64]; + std::snprintf(buf, sizeof(buf), "%.*g", + std::numeric_limits::max_digits10, + static_cast(v)); + out += buf; + } else if constexpr (std::is_signed_v) { + out += std::to_string(static_cast(v)); + } else { + out += std::to_string(static_cast(v)); + } + return make_void(); + } +}; + +template +struct json_encode> { + static error_or + apply(const data, enc::Native> &in, + std::string &out, bool pretty, uint64_t level) { + // A mixed precision value reads as its interface type. + data widened{in.get()}; + return json_encode::apply(widened, out, pretty, level); + } +}; + +template <> struct json_encode { + static error_or apply(const data &in, + std::string &out, bool, uint64_t) { + json_append_escaped(out, in.stl_view()); + return make_void(); + } +}; + +/** + * Writes the elements of a flat sequence as a JSON array. + */ +template +inline error_or json_encode_sequence(const Container &in, uint64_t count, + std::string &out, bool pretty, + uint64_t level) { + out.push_back('['); + for (uint64_t i = 0u; i < count; ++i) { + if (i > 0u) { + out.push_back(','); + } + json_newline_indent(out, pretty, level + 1u); + auto eov = json_encode::apply(in.flat_at(i), out, pretty, + level + 1u); + if (eov.is_error()) { + return eov; + } + } + if (count > 0u) { + json_newline_indent(out, pretty, level); + } + out.push_back(']'); + return make_void(); +} + +template +struct json_encode> { + static error_or + apply(const data, enc::Native> &in, + std::string &out, bool pretty, uint64_t level) { + constexpr uint64_t flat = ct_multiply::value; + return json_encode_sequence(in, flat, out, pretty, level); + } +}; + +template struct json_encode> { + static error_or + apply(const data, enc::Native> &in, std::string &out, + bool pretty, uint64_t level) { + return json_encode_sequence(in, in.size().get(), out, pretty, level); + } +}; + +template +struct json_encode> { + static error_or + apply(const data, enc::Native> &in, + std::string &out, bool pretty, uint64_t level) { + constexpr uint64_t flat = ct_multiply::value; + return json_encode_sequence(in, flat, out, pretty, level); + } +}; + +template struct json_encode> { + template + static error_or + apply_element(const data, enc::Native> &in, + std::string &out, bool pretty, uint64_t level) { + if constexpr (i < sizeof...(T)) { + if constexpr (i > 0u) { + out.push_back(','); + } + json_newline_indent(out, pretty, level + 1u); + using Element = typename parameter_pack_type::type; + auto eov = json_encode::apply(in.template get(), out, + pretty, level + 1u); + if (eov.is_error()) { + return eov; + } + return apply_element(in, out, pretty, level); + } else { + return make_void(); + } + } + + static error_or apply(const data, enc::Native> &in, + std::string &out, bool pretty, uint64_t level) { + out.push_back('['); + auto eov = apply_element<0u>(in, out, pretty, level); + if (eov.is_error()) { + return eov; + } + if constexpr (sizeof...(T) > 0u) { + json_newline_indent(out, pretty, level); + } + out.push_back(']'); + return make_void(); + } +}; + +template +struct json_encode...>> { + using Schema = sch::Struct...>; + + template + static error_or apply_member(const data &in, + std::string &out, bool pretty, + uint64_t level) { + if constexpr (i < sizeof...(T)) { + if constexpr (i > 0u) { + out.push_back(','); + } + json_newline_indent(out, pretty, level + 1u); + json_append_escaped( + out, parameter_key_pack_type::literal.view()); + out.push_back(':'); + if (pretty) { + out.push_back(' '); + } + using Member = typename parameter_pack_type::type; + auto eov = json_encode::apply( + in.template get_at_index(), out, pretty, level + 1u); + if (eov.is_error()) { + return eov; + } + return apply_member(in, out, pretty, level); + } else { + return make_void(); + } + } + + static error_or apply(const data &in, + std::string &out, bool pretty, uint64_t level) { + out.push_back('{'); + auto eov = apply_member<0u>(in, out, pretty, level); + if (eov.is_error()) { + return eov; + } + if constexpr (sizeof...(T) > 0u) { + json_newline_indent(out, pretty, level); + } + out.push_back('}'); + return make_void(); + } +}; + +/** + * Reads a native value back out of JSON text. + */ +template struct json_decode { + static_assert(always_false, + "This schema has no JSON representation"); +}; + +template <> struct json_decode { + static error_or apply(json_parser &p, data &, + const codec_config &) { + if (!p.consume_null()) { + return make_error("Expected null"); + } + return make_void(); + } +}; + +template <> struct json_decode { + static error_or apply(json_parser &p, + data &out, + const codec_config &) { + auto eo_b = p.parse_bool(); + if (eo_b.is_error()) { + return std::move(eo_b.get_error()); + } + out.set(eo_b.get_value()); + return make_void(); + } +}; + +template struct json_decode> { + static error_or apply(json_parser &p, + data, enc::Native> &out, + const codec_config &) { + using Native = typename native_data_type>::type; + + auto eo_tok = p.parse_number_token(); + if (eo_tok.is_error()) { + return std::move(eo_tok.get_error()); + } + const std::string_view tok = eo_tok.get_value(); + + if constexpr (std::is_floating_point_v) { + /** + * from_chars for floating point is not available everywhere this + * builds, so the token is copied into a terminated buffer and run + * through strtod. + */ + std::string buf{tok}; + char *end = nullptr; + const double v = std::strtod(buf.c_str(), &end); + if (end == buf.c_str()) { + return make_error("Bad floating point"); + } + out.set(static_cast(v)); + } else { + // Accept a float-looking token for an integer field only when it + // names an exact integer, rather than silently truncating. + int64_t sv = 0; + uint64_t uv = 0u; + const char *first = tok.data(); + const char *last = tok.data() + tok.size(); + + std::from_chars_result r{}; + if constexpr (std::is_signed_v) { + r = std::from_chars(first, last, sv); + } else { + if (!tok.empty() && tok.front() == '-') { + return make_error( + "Negative value for an unsigned field"); + } + const char *begin = (!tok.empty() && tok.front() == '+') + ? first + 1 + : first; + r = std::from_chars(begin, last, uv); + } + + if (r.ec != std::errc{}) { + return make_error("Bad integer"); + } + if (r.ptr != last) { + return make_error( + "Expected an integer"); + } + + if constexpr (std::is_signed_v) { + out.set(static_cast(sv)); + } else { + out.set(static_cast(uv)); + } + } + return make_void(); + } +}; + +template +struct json_decode> { + static error_or + apply(json_parser &p, data, enc::Native> &out, + const codec_config &cfg) { + data widened; + auto eov = json_decode::apply(p, widened, cfg); + if (eov.is_error()) { + return eov; + } + out.set(widened.get()); + return make_void(); + } +}; + +template <> struct json_decode { + static error_or apply(json_parser &p, + data &out, + const codec_config &) { + auto eo_s = p.parse_string(); + if (eo_s.is_error()) { + return std::move(eo_s.get_error()); + } + out.set(std::move(eo_s.get_value())); + return make_void(); + } +}; + +/** + * Reads a JSON array into a fixed length sequence. The element count has to + * match exactly, since there is nowhere to put a surplus and no default for a + * shortfall. + */ +template +inline error_or json_decode_fixed_sequence(json_parser &p, Container &out, + uint64_t count, + const codec_config &cfg) { + auto eo_enter = p.enter(); + if (eo_enter.is_error()) { + return std::move(eo_enter.get_error()); + } + + auto eo_open = p.expect('['); + if (eo_open.is_error()) { + p.leave(); + return std::move(eo_open.get_error()); + } + + uint64_t i = 0u; + if (!p.consume_if(']')) { + while (true) { + if (i >= count) { + p.leave(); + return make_error( + "JSON array is longer than the schema allows"); + } + auto eov = json_decode::apply(p, out.flat_at(i), cfg); + if (eov.is_error()) { + p.leave(); + return eov; + } + ++i; + if (p.consume_if(']')) { + break; + } + auto eo_comma = p.expect(','); + if (eo_comma.is_error()) { + p.leave(); + return std::move(eo_comma.get_error()); + } + } + } + + p.leave(); + + if (i != count) { + return make_error( + "JSON array is shorter than the schema requires"); + } + return make_void(); +} + +template +struct json_decode> { + static error_or + apply(json_parser &p, data, enc::Native> &out, + const codec_config &cfg) { + constexpr uint64_t flat = ct_multiply::value; + return json_decode_fixed_sequence(p, out, flat, cfg); + } +}; + +template +struct json_decode> { + static error_or + apply(json_parser &p, data, enc::Native> &out, + const codec_config &cfg) { + constexpr uint64_t flat = ct_multiply::value; + return json_decode_fixed_sequence(p, out, flat, cfg); + } +}; + +/** + * A dynamically sized Array grows to fit whatever the document holds, so only + * the one dimensional case has a well defined meaning here. + */ +template struct json_decode> { + static error_or apply(json_parser &p, + data, enc::Native> &out, + const codec_config &cfg) { + static_assert(Dim == 1u, + "Only a one dimensional Array can be grown from JSON"); + + auto eo_enter = p.enter(); + if (eo_enter.is_error()) { + return std::move(eo_enter.get_error()); + } + + auto eo_open = p.expect('['); + if (eo_open.is_error()) { + p.leave(); + return std::move(eo_open.get_error()); + } + + out = data, enc::Native>{}; + + if (!p.consume_if(']')) { + while (true) { + data element; + auto eov = json_decode::apply(p, element, cfg); + if (eov.is_error()) { + p.leave(); + return eov; + } + auto eo_add = out.add(std::move(element)); + if (eo_add.is_error()) { + p.leave(); + return eo_add; + } + if (p.consume_if(']')) { + break; + } + auto eo_comma = p.expect(','); + if (eo_comma.is_error()) { + p.leave(); + return std::move(eo_comma.get_error()); + } + } + } + + p.leave(); + return make_void(); + } +}; + +template struct json_decode> { + using Schema = sch::Tuple; + + template + static error_or apply_element(json_parser &p, + data &out, + const codec_config &cfg) { + if constexpr (i < sizeof...(T)) { + if constexpr (i > 0u) { + auto eo_comma = p.expect(','); + if (eo_comma.is_error()) { + return std::move(eo_comma.get_error()); + } + } + using Element = typename parameter_pack_type::type; + auto eov = + json_decode::apply(p, out.template get(), cfg); + if (eov.is_error()) { + return eov; + } + return apply_element(p, out, cfg); + } else { + return make_void(); + } + } + + static error_or apply(json_parser &p, data &out, + const codec_config &cfg) { + auto eo_enter = p.enter(); + if (eo_enter.is_error()) { + return std::move(eo_enter.get_error()); + } + + auto eo_open = p.expect('['); + if (eo_open.is_error()) { + p.leave(); + return std::move(eo_open.get_error()); + } + + auto eov = apply_element<0u>(p, out, cfg); + if (eov.is_error()) { + p.leave(); + return eov; + } + + auto eo_close = p.expect(']'); + p.leave(); + if (eo_close.is_error()) { + return std::move(eo_close.get_error()); + } + return make_void(); + } +}; + +template +struct json_decode...>> { + using Schema = sch::Struct...>; + + /** + * Matches the parsed key against the member literals and decodes into the + * one that matches. Reports whether a member took the value, so the caller + * can skip over keys the schema does not declare. + */ + template + static error_or dispatch(std::string_view key, json_parser &p, + data &out, + const codec_config &cfg, + bool (&seen)[sizeof...(T) > 0u ? sizeof...(T) : 1u]) { + if constexpr (i < sizeof...(T)) { + if (key == parameter_key_pack_type::literal.view()) { + using Member = typename parameter_pack_type::type; + auto eov = json_decode::apply( + p, out.template get_at_index(), cfg); + if (eov.is_error()) { + return std::move(eov.get_error()); + } + seen[i] = true; + return true; + } + return dispatch(key, p, out, cfg, seen); + } else { + (void)key; + (void)p; + (void)out; + (void)cfg; + (void)seen; + return false; + } + } + + static error_or apply(json_parser &p, data &out, + const codec_config &cfg) { + auto eo_enter = p.enter(); + if (eo_enter.is_error()) { + return std::move(eo_enter.get_error()); + } + + auto eo_open = p.expect('{'); + if (eo_open.is_error()) { + p.leave(); + return std::move(eo_open.get_error()); + } + + bool seen[sizeof...(T) > 0u ? sizeof...(T) : 1u] = {}; + + if (!p.consume_if('}')) { + while (true) { + auto eo_key = p.parse_string(); + if (eo_key.is_error()) { + p.leave(); + return std::move(eo_key.get_error()); + } + auto eo_colon = p.expect(':'); + if (eo_colon.is_error()) { + p.leave(); + return std::move(eo_colon.get_error()); + } + + auto eo_taken = + dispatch<0u>(eo_key.get_value(), p, out, cfg, seen); + if (eo_taken.is_error()) { + p.leave(); + return std::move(eo_taken.get_error()); + } + if (!eo_taken.get_value()) { + // A key the schema does not declare: step over its value. + auto eo_skip = p.skip_value(); + if (eo_skip.is_error()) { + p.leave(); + return std::move(eo_skip.get_error()); + } + } + + if (p.consume_if('}')) { + break; + } + auto eo_comma = p.expect(','); + if (eo_comma.is_error()) { + p.leave(); + return std::move(eo_comma.get_error()); + } + } + } + + p.leave(); + + if (cfg.strict) { + for (uint64_t i = 0u; i < sizeof...(T); ++i) { + if (!seen[i]) { + return make_error(); + } + } + } + + return make_void(); + } +}; + +} // namespace impl + +template class codec; + +/** + * Translates between a native value and its JSON text. + */ +template class codec final { +private: + codec_config cfg_; + +public: + codec() = default; + + explicit codec(const codec_config &cfg__) : cfg_{cfg__} {} + + KEL_FORBID_COPY(codec); + KEL_DEFAULT_MOVE(codec); + + error_or encode(const data &from, + data &to) { + std::string out; + auto eov = impl::json_encode::apply(from, out, cfg_.pretty, 0u); + if (eov.is_error()) { + return eov; + } + to.set(std::move(out)); + return make_void(); + } + + error_or decode(const data &from, + data &to) { + impl::json_parser p{from.stl_view(), cfg_.depth}; + + auto eov = impl::json_decode::apply(p, to, cfg_); + if (eov.is_error()) { + return eov; + } + + // Anything after the top level value means the document is not what it + // claimed to be, so it is reported rather than quietly ignored. + p.skip_whitespace(); + if (!p.at_end()) { + return make_error( + "Trailing content after the JSON value"); + } + + return make_void(); + } + + void set_pretty(bool pretty) { cfg_.pretty = pretty; } + + void set_strict(bool strict) { cfg_.strict = strict; } +}; + +} // namespace lbm +} // namespace kel diff --git a/modules/core/c++/abstract/math.hpp b/modules/core/c++/abstract/math.hpp new file mode 100644 index 0000000..d692be1 --- /dev/null +++ b/modules/core/c++/abstract/math.hpp @@ -0,0 +1,279 @@ +#pragma once + +#include + +#include "data.hpp" +#include "data_math.hpp" + +namespace kel { +namespace lbm { +namespace math { + +/** + * Builds a scalar from its native value. Shorthand for the two step + * data{value} -> data>{...} conversion, which the language won't + * do implicitly. + */ +template +constexpr data, Encoding> +make_scalar(typename native_data_type::type value) { + return data, Encoding>{data{value}}; +} + +/** + * Builds a vector from its native component values. The dimension is deduced + * from the argument count. + */ +template +constexpr data, Encoding> +make_vector(Args... args) { + return data, Encoding>{ + data, Encoding>{ + std::array, sizeof...(Args)>{data{ + static_cast::type>(args)}...}}}; +} + +template +data, Encoding> dot(const data, Encoding> &left, + const data, Encoding> &right) { + data, Encoding> val; + auto &inner = val.flat_at(0u); + for (uint64_t i = 0u; i < D; ++i) { + inner = inner + left.flat_at(i) * right.flat_at(i); + } + + return val; +} + +template +data, Encoding> sqrt(const data, Encoding> &inp) { + data, Encoding> out; + out.flat_at(0u).set(std::sqrt(inp.flat_at(0u).get())); + return out; +} + +/** + * Euclidean length of a vector. + */ +template +data, Encoding> +norm(const data, Encoding> &input) { + return sqrt(dot(input, input)); +} + +/** + * Unit length copy of a vector. A zero vector has no direction to preserve, so + * it is returned unchanged rather than divided by zero. + */ +template +data, Encoding> +normalize(const data, Encoding> &input) { + auto inp_dot = dot(input, input); + if (inp_dot.flat_at(0u).get() <= 0) { + return input; + } + auto sqrt_inp_dot = sqrt(inp_dot); + + data, Encoding> out; + for (uint64_t i = 0u; i < D; ++i) { + out.flat_at(i) = input.flat_at(i) / sqrt_inp_dot.flat_at(0u); + } + return out; +} + +/** + * Reinterprets a plain fixed array as a vector, so the algebra below applies + * to it. + */ +template +data, Encoding> +vectorize_data(const data, Encoding> &dat) { + data, Encoding> vec_data; + for (uint64_t i = 0u; i < D; ++i) { + vec_data.flat_at(i) = dat.flat_at(i); + } + + return vec_data; +} + +template +data, Encoding> +multiply(const data, Encoding> &left, + const data, Encoding> &right) { + data, Encoding> lr; + + for (uint64_t i = 0u; i < M; ++i) { + for (uint64_t j = 0u; j < N; ++j) { + auto &target = lr.at({{i, j}}); + for (uint64_t k = 0u; k < K; ++k) { + target = target + left.at({{i, k}}) * right.at({{k, j}}); + } + } + } + + return lr; +} + +template +data, Encoding> +multiply(const data, Encoding> &left, + const data, Encoding> &right) { + data, Encoding> lr; + + for (uint64_t i = 0u; i < M; ++i) { + auto &target = lr.flat_at(i); + for (uint64_t j = 0u; j < N; ++j) { + target = target + left.at({{i, j}}) * right.flat_at(j); + } + } + + return lr; +} + +template +data, Encoding> +cross(const data, Encoding> &lh, + const data, Encoding> &rh) { + data, Encoding> cross_prod; + + cross_prod.flat_at(0u) = lh.flat_at(1u) * rh.flat_at(2u) - lh.flat_at(2u) * rh.flat_at(1u); + cross_prod.flat_at(1u) = lh.flat_at(2u) * rh.flat_at(0u) - lh.flat_at(0u) * rh.flat_at(2u); + cross_prod.flat_at(2u) = lh.flat_at(0u) * rh.flat_at(1u) - lh.flat_at(1u) * rh.flat_at(0u); + + return cross_prod; +} + +/** + * In two dimensions the cross product has only the component normal to the + * plane, so it comes back as a scalar. + */ +template +data, Encoding> +cross(const data, Encoding> &lh, + const data, Encoding> &rh) { + data, Encoding> cross_prod; + + cross_prod.flat_at(0u) = + lh.flat_at(0u) * rh.flat_at(1u) - lh.flat_at(1u) * rh.flat_at(0u); + + return cross_prod; +} + +/** + * Cross product of an out of plane scalar with an in plane vector, which is + * the rotation of that vector by a quarter turn, scaled. + */ +template +data, Encoding> +cross(const data, Encoding> &lh, + const data, Encoding> &rh) { + data, Encoding> cross_prod; + + cross_prod.flat_at(0u) = -(lh.flat_at(0u) * rh.flat_at(1u)); + cross_prod.flat_at(1u) = lh.flat_at(0u) * rh.flat_at(0u); + + return cross_prod; +} + +template +data, Encoding> cos(const data, Encoding> &val) { + data, Encoding> ret; + ret.flat_at(0u).set(std::cos(val.flat_at(0u).get())); + return ret; +} + +template +data, Encoding> sin(const data, Encoding> &val) { + data, Encoding> ret; + ret.flat_at(0u).set(std::sin(val.flat_at(0u).get())); + return ret; +} + +/** + * Angle of a 2d vector measured counter clockwise from the positive x axis. + * Inverse of unit_vector(). + */ +template +data, Encoding> +angle(const data, Encoding> &vec) { + data, Encoding> ret; + ret.flat_at(0u).set(std::atan2(vec.flat_at(1u).get(), vec.flat_at(0u).get())); + return ret; +} + +/** + * Unit length 2d vector pointing along the given angle. Inverse of angle(). + */ +template +data, Encoding> +unit_vector(const data, Encoding> &rot) { + data, Encoding> ret; + ret.flat_at(0u) = cos(rot).flat_at(0u); + ret.flat_at(1u) = sin(rot).flat_at(0u); + return ret; +} + +/** + * Rotates a 2d vector counter clockwise by the given angle. + */ +template +data, Encoding> +rotate(const data, Encoding> &vec, + const data, Encoding> &rot) { + data, Encoding> rot_vec; + + auto c = cos(rot).flat_at(0u); + auto s = sin(rot).flat_at(0u); + + rot_vec.flat_at(0u) = vec.flat_at(0u) * c - vec.flat_at(1u) * s; + rot_vec.flat_at(1u) = vec.flat_at(0u) * s + vec.flat_at(1u) * c; + + return rot_vec; +} + +template +data, Encoding> +scale(const data, Encoding> &vec, + const data, Encoding> &scale_) { + data, Encoding> sc_vec; + for (uint64_t i = 0u; i < D; ++i) { + sc_vec.flat_at(i) = vec.flat_at(i) * scale_.flat_at(0u); + } + return sc_vec; +} + +template +void fill(data, Encoding> &tbf, + const data &filler) { + constexpr uint64_t flat = ct_multiply::value; + for (uint64_t i = 0u; i < flat; ++i) { + tbf.flat_at(i) = filler; + } +} + +template +data, Encoding> +sum(const data, Encoding> &tens) { + data, Encoding> s; + + constexpr uint64_t flat = ct_multiply::value; + for (uint64_t i = 0u; i < flat; ++i) { + s.flat_at(0u) = s.flat_at(0u) + tens.flat_at(i); + } + + return s; +} + +} // namespace math +} // namespace lbm +} // namespace kel diff --git a/modules/core/c++/abstract/schema.hpp b/modules/core/c++/abstract/schema.hpp index 89d9c2e..63b38b5 100644 --- a/modules/core/c++/abstract/schema.hpp +++ b/modules/core/c++/abstract/schema.hpp @@ -1,77 +1,292 @@ #pragma once +#include +#include +#include + #include "string_literal.hpp" #include "templates.hpp" namespace kel { namespace lbm { namespace sch { -struct Void {}; -struct UnsignedInteger {}; -struct SignedInteger {}; -struct FloatingPoint {}; +/** + * Every schema in here carries its own metadata schema as a nested `Meta` + * typedef, rather than exposing it through a separate trait. `Meta` is the + * schema of the runtime information a value needs before it can be addressed + * at all -- the extents of a dynamically sized Array, the length of a String. + * Schemas whose shape is fully known at compile time report `Meta = Void`. + */ -template -struct MixedPrecision { +struct Void { using Meta = Void; - using StorageType = StorageT; - using InterfaceType = InterfaceT; + static constexpr string_literal name = "Void"; +}; + +struct Bool { + using Meta = Void; + static constexpr string_literal name = "Bool"; +}; + +/** + * Primitive kinds. These are tags describing how the bytes of a Primitive are + * to be interpreted; they are not schemas in their own right. + */ +struct UnsignedInteger { + static constexpr string_literal name = "UnsignedInteger"; +}; +struct SignedInteger { + static constexpr string_literal name = "SignedInteger"; }; +struct FloatingPoint { + static constexpr string_literal name = "FloatingPoint"; +}; + +template struct is_primitive_kind : std::false_type {}; +template <> struct is_primitive_kind : std::true_type {}; +template <> struct is_primitive_kind : std::true_type {}; +template <> struct is_primitive_kind : std::true_type {}; + +/** + * A primitive of kind `PrimType` occupying `N` bytes. + * + * `StorageType` and `InterfaceType` are both schemas, and for a plain + * Primitive they are the type itself -- it is stored exactly as it is read. + * MixedPrecision is the case where the two come apart. `Kind` names the + * interpretation tag and `Bytes` the width. + */ +template struct Primitive { + static_assert(is_primitive_kind::value, + "Primitive needs one of UnsignedInteger, SignedInteger or " + "FloatingPoint as its kind"); + static_assert(((std::is_same_v || + std::is_same_v) && + (N == 1u || N == 2u || N == 4u || N == 8u)) || + (std::is_same_v && + (N == 4u || N == 8u)), + "Primitive Type is not supported"); -template -struct Primitive { using Meta = Void; - using StorageType = PrimType; - using InterfaceType = PrimType; + using Kind = PrimType; + using StorageType = Primitive; + using InterfaceType = Primitive; static constexpr uint64_t Bytes = N; + static constexpr string_literal name = "Primitive"; }; -using UInt8 = Primitive; -using UInt16 = Primitive; -using UInt32 = Primitive; -using UInt64 = Primitive; +template struct is_primitive : std::false_type {}; +template +struct is_primitive> : std::true_type {}; + +using UInt8 = Primitive; +using UInt16 = Primitive; +using UInt32 = Primitive; +using UInt64 = Primitive; + +using Int8 = Primitive; +using Int16 = Primitive; +using Int32 = Primitive; +using Int64 = Primitive; -using Int8 = Primitive; -using Int16 = Primitive; -using Int32 = Primitive; -using Int64 = Primitive; +using Float32 = Primitive; +using Float64 = Primitive; -using Float8 = Primitive; -using Float16 = Primitive; -using Float32 = Primitive; -using Float64 = Primitive; +/** + * A value stored as `StorageT` but read and written as `InterfaceT`. + * + * Note the argument order: storage first, interface second. forstio's + * schema::MixedPrecision took them the other way round, so any call site + * carried over from there needs its arguments swapped. + */ +template struct MixedPrecision { + static_assert(is_primitive::value, + "StorageType needs to be a Primitive"); + static_assert(is_primitive::value, + "InterfaceType needs to be a Primitive"); -template -struct FixedArray { + using Meta = Void; + using StorageType = StorageT; + using InterfaceType = InterfaceT; + static constexpr string_literal name = "MixedPrecision"; +}; + +/** + * A variable length string. Its length is the metadata. + */ +struct String { + using Meta = UInt64; + static constexpr string_literal name = "String"; +}; + +/** + * Named member of a Struct or a Union. + */ +template struct Member { + using ValueType = Value; + static constexpr string_literal KeyLiteral = Key_; + static constexpr string_literal Key = Key_; + static constexpr string_literal name = "Member"; +}; + +/** + * Array whose extents are fixed at compile time, so there is nothing to carry + * at runtime and `Meta` is Void. + */ +template struct FixedArray { using Meta = Void; using Inner = T; - static constexpr std::array Dimensions{Dims...}; + /// Spelling carried over from forstio, kept so existing call sites read. + using ValueType = T; + static constexpr uint64_t Rank = sizeof...(Dims); + static constexpr std::array Dimensions{Dims...}; + static constexpr uint64_t FlatSize = ct_multiply::value; + static constexpr string_literal name = "FixedArray"; }; -template -struct Array { - using Meta = FixedArray; +/** + * Array of rank `Dims` whose extents are only known at runtime, so the extents + * themselves are the metadata. + */ +template struct Array { + using Meta = FixedArray; using Inner = T; - static constexpr std::array Dimensions{Dims}; + using ValueType = T; + static constexpr uint64_t Rank = Dims; + static constexpr string_literal name = "Array"; +}; + +/** + * Heterogeneous fixed sequence. Its metadata is the tuple of its members' + * metadata, so that a Tuple of dynamically sized members can still be built. + */ +template struct Tuple { + using Meta = Tuple; + static constexpr uint64_t Size = sizeof...(T); + static constexpr string_literal name = "Tuple"; }; -template -struct Tuple { +template struct Struct { + static_assert(always_false, + "Struct only accepts Member parameters"); }; -template -struct Member {}; +template +struct Struct...> { + using Meta = Struct...>; + static constexpr uint64_t Size = sizeof...(Schema); + static constexpr string_literal name = "Struct"; +}; -template -struct Struct {}; +template struct Union { + static_assert(always_false, + "Union only accepts Member parameters"); +}; -} +template +struct Union...> { + using Meta = Union...>; + static constexpr uint64_t Size = sizeof...(Schema); + static constexpr string_literal name = "Union"; +}; + +template struct Map { + using Meta = Void; + using KeyType = Key; + using ValueType = Value; + static constexpr string_literal name = "Map"; +}; + +/** + * The schema counterpart of ref. + */ +template struct Ref { + using Meta = Void; + using ValueType = Schema; + static constexpr string_literal name = "Ref"; +}; + +/** + * The schema counterpart of ptr. + * + * Its advantage is that data> keeps the interface of + * data -- arithmetic still reads the same -- while the storage is + * borrowed rather than owned. This is what lets an Array be handed + * out as a double* without losing the data accessor on top of it. + */ +template struct Ptr { + using Meta = Void; + using ValueType = Schema; + static constexpr string_literal name = "Ptr"; +}; + +/** + * Separator between encodings that are nested in one another, e.g. a base64 + * blob transported inside JSON. + */ +template struct Wrapper { + using Meta = typename Schema::Meta; + using ValueType = Schema; + using Encoding = Enc; + static constexpr string_literal name = "Wrapper"; +}; + +/** + * Tensor of rank sizeof...(D) over `Inner`. + * + * The extents are compile time constants, but the metadata is still the extent + * list: consumers index a tensor through a rank sized index, and that index + * schema is what `Meta` names. + */ +template struct Tensor { + using Meta = FixedArray; + using Inner_ = Inner; + using ValueType = Inner; + static constexpr uint64_t Rank = sizeof...(D); + static constexpr std::array Dimension{D...}; + static constexpr uint64_t FlatSize = ct_multiply::value; + static constexpr string_literal name = "Tensor"; +}; + +template using Scalar = Tensor; + +template using Vector = Tensor; + +template +using Matrix = Tensor; + +} // namespace sch + +/** + * Convenience accessor, so `Meta` can be spelled as a trait where a nested + * typedef would be awkward to reach. + */ +template struct meta_schema { + using Schema_ = Schema; + using MetaSchema = typename Schema::Meta; +}; + +template struct schema { using Type = Sch; }; + +/** + * Index into the members of a structural schema. + */ +template struct schema_type_at_index; + +template +struct schema_type_at_index> { + using Type = typename parameter_pack_type::type; +}; + +template +struct schema_type_at_index> { + using Type = typename parameter_pack_type::type; +}; -template -struct schema { - using Type = Sch; +template +struct schema_type_at_index> { + using Type = typename parameter_pack_type::type; }; -} -} +} // namespace lbm +} // namespace kel diff --git a/modules/core/c++/abstract/schema_factory.hpp b/modules/core/c++/abstract/schema_factory.hpp new file mode 100644 index 0000000..f87c33c --- /dev/null +++ b/modules/core/c++/abstract/schema_factory.hpp @@ -0,0 +1,130 @@ +#pragma once + +#include "schema.hpp" + +namespace kel { +namespace lbm { + +/** + * Compile time predicate: does this structural schema already carry `Key`? + */ +template struct schema_has_key; + +template +struct schema_has_key...>> { + static constexpr bool value = ((Key == Keys) || ...); +}; + +template +struct schema_has_key...>> { + static constexpr bool value = ((Key == Keys) || ...); +}; + +/** + * Compile time predicate: does this structural schema already carry exactly + * this member, key and type both? + */ +template struct schema_has_member; + +template +struct schema_has_member, + sch::Struct...>> { + static constexpr bool value = + ((MK == Keys && std::is_same_v) || ...); +}; + +template +struct schema_has_member, + sch::Union...>> { + static constexpr bool value = + ((MK == Keys && std::is_same_v) || ...); +}; + +/** + * Builds a structural schema a member at a time. Every add() yields a new + * factory over a wider schema, so the schema is assembled purely in the type + * system. + */ +template struct schema_factory { + using Schema = T; + static_assert(always_false, "Not supported"); +}; + +template +struct schema_factory...>> { + using Schema = sch::Struct...>; + + template static constexpr bool has_key() noexcept { + return schema_has_key::value; + } + + template + static constexpr bool has_member() noexcept { + return schema_has_member, Schema>::value; + } + + /** + * Adds the member unless it is already there. Re-adding the very same + * member is a no-op; re-using a key for a different type is an error, + * because that would silently change what the existing key means. + */ + template + constexpr auto add_maybe() const noexcept { + if constexpr (!has_key()) { + return schema_factory< + sch::Struct..., sch::Member>>{}; + } else if constexpr (has_member()) { + return schema_factory...>>{}; + } else { + static_assert( + always_false, + "Struct already has the provided Key, but a mismatching Type"); + } + } + + template + constexpr schema_factory< + sch::Struct..., sch::Member>> + add() const noexcept { + static_assert(!has_key(), + "Can't add member. Name is already in use."); + return {}; + } +}; + +template +struct schema_factory...>> { + using Schema = sch::Union...>; + + template static constexpr bool has_key() noexcept { + return schema_has_key::value; + } + + template + constexpr schema_factory< + sch::Union..., sch::Member>> + add() const noexcept { + static_assert(!has_key(), + "Can't add member. Name is already in use."); + return {}; + } +}; + +template struct schema_factory> { + using Schema = sch::Tuple; + + template + constexpr schema_factory> add() const noexcept { + return {}; + } +}; + +/** + * Creates the base schema to build on: an empty struct, tuple or union. + */ +template constexpr schema_factory build_schema() noexcept { + return {}; +} + +} // namespace lbm +} // namespace kel diff --git a/modules/core/c++/abstract/stringify_schema.hpp b/modules/core/c++/abstract/stringify_schema.hpp index dd218d0..2c96e4c 100644 --- a/modules/core/c++/abstract/stringify_schema.hpp +++ b/modules/core/c++/abstract/stringify_schema.hpp @@ -2,6 +2,7 @@ #include "schema.hpp" #include "string_literal.hpp" +#include "templates.hpp" namespace kel { namespace lbm { @@ -15,6 +16,27 @@ struct schema_to_string_helper { } }; +template<> +struct schema_to_string_helper final { + static constexpr auto apply(){ + return string_literal{"Void"}; + } +}; + +template<> +struct schema_to_string_helper final { + static constexpr auto apply(){ + return string_literal{"Bool"}; + } +}; + +template<> +struct schema_to_string_helper final { + static constexpr auto apply(){ + return string_literal{"String"}; + } +}; + template<> struct schema_to_string_helper final { static constexpr auto apply(){ @@ -36,17 +58,189 @@ struct schema_to_string_helper final { } }; +/** + * Renders a compile time number as its decimal digits. string_literal has no + * operator+ for integers, so the number has to be turned into a literal first. + */ +template +constexpr auto number_literal(){ + return ct_convert_to_digits::literal; +} + +/** + * Joins a parameter pack of literals with ',' separators. + */ +template +struct schema_list_to_string_helper; + +template<> +struct schema_list_to_string_helper<> final { + static constexpr auto apply(){ + return string_literal{""}; + } +}; + +template +struct schema_list_to_string_helper final { + static constexpr auto apply(){ + return schema_to_string_helper::apply(); + } +}; + +template +struct schema_list_to_string_helper final { + static constexpr auto apply(){ + return schema_to_string_helper::apply() + + string_literal{","} + + schema_list_to_string_helper::apply(); + } +}; + +/** + * Joins a pack of compile time numbers with ',' separators. + */ +template +struct number_list_to_string_helper; + +template<> +struct number_list_to_string_helper<> final { + static constexpr auto apply(){ + return string_literal{""}; + } +}; + +template +struct number_list_to_string_helper final { + static constexpr auto apply(){ + return number_literal(); + } +}; + +template +struct number_list_to_string_helper final { + static constexpr auto apply(){ + return number_literal() + + string_literal{","} + + number_list_to_string_helper::apply(); + } +}; + template struct schema_to_string_helper> final { static constexpr auto apply(){ - return string_literal{"Primitive<"}+schema_to_string_helper::apply()+string_literal{","}+N+string_literal{">"}; + return string_literal{"Primitive<"} + + schema_to_string_helper::apply() + + string_literal{","} + + number_literal() + + string_literal{">"}; + } +}; + +template +struct schema_to_string_helper> final { + static constexpr auto apply(){ + return string_literal{"MixedPrecision<"} + + schema_to_string_helper::apply() + + string_literal{","} + + schema_to_string_helper::apply() + + string_literal{">"}; + } +}; + +template +struct schema_to_string_helper> final { + static constexpr auto apply(){ + return string_literal{"FixedArray<"} + + schema_to_string_helper::apply() + + string_literal{","} + + number_list_to_string_helper::apply() + + string_literal{">"}; + } +}; + +template +struct schema_to_string_helper> final { + static constexpr auto apply(){ + return string_literal{"Array<"} + + schema_to_string_helper::apply() + + string_literal{","} + + number_literal() + + string_literal{">"}; + } +}; + +template +struct schema_to_string_helper> final { + static constexpr auto apply(){ + return string_literal{"Tensor<"} + + schema_to_string_helper::apply() + + string_literal{","} + + number_list_to_string_helper::apply() + + string_literal{">"}; + } +}; + +template +struct schema_to_string_helper> final { + static constexpr auto apply(){ + return string_literal{"Tuple<"} + + schema_list_to_string_helper::apply() + + string_literal{">"}; + } +}; + +template +struct schema_to_string_helper> final { + static constexpr auto apply(){ + return string_literal{"Member<"} + + schema_to_string_helper::apply() + + string_literal{","} + + K + + string_literal{">"}; + } +}; + +template +struct schema_to_string_helper...>> final { + static constexpr auto apply(){ + return string_literal{"Struct<"} + + schema_list_to_string_helper...>::apply() + + string_literal{">"}; + } +}; + +template +struct schema_to_string_helper...>> final { + static constexpr auto apply(){ + return string_literal{"Union<"} + + schema_list_to_string_helper...>::apply() + + string_literal{">"}; + } +}; + +template +struct schema_to_string_helper> final { + static constexpr auto apply(){ + return string_literal{"Ptr<"} + + schema_to_string_helper::apply() + + string_literal{">"}; + } +}; + +template +struct schema_to_string_helper> final { + static constexpr auto apply(){ + return string_literal{"Ref<"} + + schema_to_string_helper::apply() + + string_literal{">"}; } }; } template -struct schema_to_string{ - static constexpr std::string_view value = impl::schema_to_string_helper::apply().view(); +struct schema_to_string { + static constexpr auto literal = impl::schema_to_string_helper::apply(); + static constexpr std::string_view value = literal.view(); }; } } diff --git a/modules/core/c++/abstract/templates.hpp b/modules/core/c++/abstract/templates.hpp index d9d9faa..6c5fd5d 100644 --- a/modules/core/c++/abstract/templates.hpp +++ b/modules/core/c++/abstract/templates.hpp @@ -1,8 +1,207 @@ #pragma once +#include +#include +#include + +#include "common.hpp" +#include "string_literal.hpp" + namespace kel { namespace lbm { -template -constexpr bool always_false = false; -} -} + +/** + * This type is meant for grouping of template types + */ +template struct tmpl_group { + static constexpr string_literal name = "tmpl_group"; + static constexpr uint64_t size = sizeof...(T); +}; + +template struct tmpl_value_group { + static constexpr string_literal name = "tmpl_value_group"; + static constexpr uint64_t size = sizeof...(values); +}; + +/** + * Concats two tmpl_group into one + */ +template struct tmpl_concat; + +template +struct tmpl_concat, tmpl_group> { + using type = tmpl_group; +}; + +template +struct tmpl_concat, tmpl_value_group> { + using type = tmpl_value_group; +}; + +/** + * Returns the position of the parameter type in the parameter pack + */ +template struct parameter_pack_index; + +template struct parameter_pack_index { + static constexpr size_t value = 0u; +}; + +template +struct parameter_pack_index { + static constexpr size_t value = 1u + parameter_pack_index::value; +}; + +template struct parameter_pack_type { + static_assert(always_false, + "Should've been caught by the specializations"); +}; + +template struct parameter_pack_type<0, TN, T...> { + using type = TN; +}; + +template +struct parameter_pack_type { + static_assert(sizeof...(T) > 0, "Exhausted parameters"); + static_assert(N > 0, "Invalid number. Should've been caught"); + using type = typename parameter_pack_type::type; +}; + +/* + * Nightmare inducing compiler problems found here. Somehow non-type + * string_literals cannot be resolved as non-type primitive template values can. + * This is the workaround + */ +template +struct parameter_key_pack_index_helper { + static constexpr size_t value = + (V == Key0) + ? (0u) + : (1u + parameter_key_pack_index_helper::value); +}; + +template +struct parameter_key_pack_index_helper { + static constexpr size_t value = (V == Key0) ? (0u) : (1u); +}; + +template +struct parameter_key_pack_index { + static constexpr size_t value = + parameter_key_pack_index_helper::value; + static_assert(value < sizeof...(Keys), + "Provided string_literal doesn't exist in searched list"); +}; + +template +struct parameter_key_pack_type_helper { + static constexpr string_literal literal = + parameter_key_pack_type_helper::literal; +}; + +template +struct parameter_key_pack_type_helper { + static constexpr string_literal literal = Key0; +}; + +template struct parameter_key_pack_type { + static constexpr string_literal literal = + parameter_key_pack_type_helper::literal; + + static_assert(i < sizeof...(Keys), "Provided index is too large for list"); +}; + +template +struct parameter_pack_value_helper { + static constexpr T value = parameter_pack_value_helper::value; +}; + +template +struct parameter_pack_value_helper { + static constexpr T value = V0; +}; + +template struct parameter_pack_value { + static constexpr T value = + parameter_pack_value_helper::value; + static_assert(i < sizeof...(Values), + "Provided index is too large for list"); +}; + +template struct tmpl_group_pack_type; + +template +struct tmpl_group_pack_type> { + using type = typename parameter_pack_type::type; +}; + +/** + * Compile time product of a value pack. Empty pack is the multiplicative + * identity, which is what makes a rank zero tensor hold exactly one element. + */ +template struct ct_multiply; + +template struct ct_multiply { + static constexpr T value = 1; +}; + +template struct ct_multiply { + static constexpr T value = V0 * ct_multiply::value; +}; + +namespace impl { +template struct ct_convert_digits_table_helper { + static constexpr std::array table = {'0', '1', '2', '3', '4', '5', + '6', '7', '8', '9', 'A', 'B', + 'C', 'D', 'E', 'F'}; + + template static constexpr T value() { + static_assert(i < 16, "Only conversion up to hex is supported"); + return table[i]; + }; +}; + +template +struct ct_convert_digits_helper { + static constexpr size_t size = + ct_convert_digits_helper::size; + static constexpr std::array value = + ct_convert_digits_helper::value; + static constexpr string_literal literal = + ct_convert_digits_helper::literal; +}; + +template +struct ct_convert_digits_helper<0, Base, Digs...> { + static constexpr size_t size = sizeof...(Digs); + static constexpr std::array value = {Digs...}; + static constexpr string_literal literal = { + {ct_convert_digits_table_helper::value()..., '\0'}}; +}; + +template struct ct_convert_digits_helper<0, Base> { + static constexpr size_t size = 0; + static constexpr std::array value = {0}; + static constexpr string_literal literal = "0"_sl; +}; +} // namespace impl + +template struct ct_convert_to_digits { + static_assert(Base <= 16, "Only conversion up to hex is supported"); + + static constexpr size_t size = impl::ct_convert_digits_helper::size; + static constexpr std::array value = + impl::ct_convert_digits_helper::value; + static constexpr string_literal literal = + impl::ct_convert_digits_helper::literal; +}; + +/** + * Decimal rendering of a compile time number, for schema stringification. + */ +template +using ct_decimal_literal = ct_convert_to_digits; + +} // namespace lbm +} // namespace kel diff --git a/modules/core/c++/abstract/unit.hpp b/modules/core/c++/abstract/unit.hpp new file mode 100644 index 0000000..406cb2f --- /dev/null +++ b/modules/core/c++/abstract/unit.hpp @@ -0,0 +1,275 @@ +#pragma once + +#include + +#include "data.hpp" +#include "schema.hpp" + +namespace kel { +namespace lbm { +namespace sch { + +/** + * One factor of a unit: a base quantity raised to `Expo`, at scale `Scal`. + * + * Scaling distinguishes units of the same quantity that are not + * interchangeable, e.g. lattice metres from SI metres, so that mixing them is + * a compile time error rather than a silent numeric mistake. + */ +template struct UnitElement { + using Schema = Un; + static constexpr int64_t Exponent = Expo; + static constexpr int64_t Scaling = Scal; + static constexpr string_literal name = "UnitElement"; +}; + +/** + * A value of `BaseSchema` carrying a unit made of `Components`. + */ +template struct Unit { + using Meta = typename BaseSchema::Meta; + using Schema = BaseSchema; + static constexpr string_literal name = "Unit"; +}; + +/** + * A dimensionless value: a unit with no components at all. + */ +template using Pure = Unit; + +} // namespace sch + +namespace impl { + +template class unit_matching; + +template class unit_redux_list { + static_assert(sizeof...(T) == 0u, "Template type not supported"); + + using Type = unit_redux_list<>; +}; + +template +struct unit_redux_list, + sch::UnitElement...> { + using Type = typename unit_matching< + unit_redux_list, + sch::UnitElement...>, + unit_redux_list<>>::TypeList; +}; + +template class unit_matching_reduce { +public: + static_assert(always_false, "Template type not supported"); +}; + +/** + * Walks the remaining list looking for factors of the same base quantity and + * scale as the one being accumulated, folding their exponents together. + */ +template +class unit_matching_reduce< + sch::UnitElement, + unit_redux_list, + sch::UnitElement...>, + unit_redux_list...>> { +public: + static constexpr bool is_same = std::is_same_v and (S == S0); + + using ReducedType = + typename std::conditional, + sch::UnitElement>::type; + using ReducedTypeList = typename std::conditional< + is_same, unit_redux_list...>, + unit_redux_list..., + sch::UnitElement>>::type; + + using NextMatcher = + unit_matching_reduce...>, + ReducedTypeList>; + using Type = typename NextMatcher::Type; + using TypeList = typename NextMatcher::TypeList; + static constexpr int64_t Num = NextMatcher::Num; +}; + +/** + * End of the walk: the accumulated factor on the left, everything that did not + * match on the right. + */ +template +class unit_matching_reduce, unit_redux_list<>, + unit_redux_list...>> { +public: + using Type = sch::UnitElement; + using TypeList = unit_redux_list...>; + static constexpr int64_t Num = E; + static constexpr int64_t Scale = S; +}; + +template class unit_matching { + static_assert(always_false, "Template type not supported"); +}; + +template +class unit_matching, unit_redux_list> { +public: + using TypeList = unit_redux_list; +}; + +template +class unit_matching, unit_redux_list> { +public: + using MatchReducer = + unit_matching_reduce, unit_redux_list<>>; + + using ReducedType = typename MatchReducer::Type; + using ReducedTypeList = typename MatchReducer::TypeList; + static constexpr int64_t Num = MatchReducer::Num; + + /** + * A factor whose exponents cancelled to zero is dropped rather than kept + * as a zero power, so that m/m really is dimensionless. + */ + using TypeRightList = + typename std::conditional, + unit_redux_list>::type; + using TypeList = typename unit_matching::TypeList; +}; + +template class unit_add_base { + static_assert(always_false, "Template type not supported"); +}; + +template +class unit_add_base> { +public: + using Schema = sch::Unit; +}; + +} // namespace impl + +template struct unit_element_reduction { + using TypeList = + typename impl::unit_matching, + impl::unit_redux_list<>>::TypeList; + using Schema = typename impl::unit_add_base::Schema; +}; + +template struct unit_multiplication { + static_assert(always_false, "Template type not supported"); +}; + +template +struct unit_multiplication< + sch::Unit...>, + sch::Unit...>> { + using Schema = typename unit_element_reduction< + BaseSchema, sch::UnitElement..., + sch::UnitElement...>::Schema; +}; + +template struct unit_division { + static_assert(always_false, "Template type not supported"); +}; + +/** + * Division is multiplication by the negated exponents. + */ +template +struct unit_division< + sch::Unit...>, + sch::Unit...>> { + using Schema = typename unit_element_reduction< + BaseSchema, sch::UnitElement..., + sch::UnitElement...>::Schema; +}; + +/** + * A united value. It wraps the plain value and only allows arithmetic that the + * unit algebra agrees with: addition needs identical units, while + * multiplication and division derive the resulting unit. + */ +template +class data, enc::Native> final { +public: + using Schema = sch::Unit; + using MetaSchema = typename Schema::Meta; + using BaseData = data; + +private: + BaseData dat_; + +public: + data() = default; + + KEL_DEFAULT_COPY(data); + KEL_DEFAULT_MOVE(data); + + data(const BaseData &dat__) : dat_{dat__} {} + + data(BaseData &&dat__) : dat_{std::move(dat__)} {} + + data operator+(const data &rhs) const { + return {dat_ + rhs.handle()}; + } + + data operator-(const data &rhs) const { + return {dat_ - rhs.handle()}; + } + + data &operator+=(const data &rhs) { + dat_ += rhs.handle(); + return *this; + } + + data &operator-=(const data &rhs) { + dat_ -= rhs.handle(); + return *this; + } + + bool operator==(const data &rhs) const { + return dat_ == rhs.handle(); + } + + bool operator!=(const data &rhs) const { + return !(dat_ == rhs.handle()); + } + + bool operator<(const data &rhs) const { + return dat_ < rhs.handle(); + } + + bool operator>(const data &rhs) const { + return dat_ > rhs.handle(); + } + + template + data::Schema, enc::Native> + operator*(const data &rhs) const { + return {dat_ * rhs.handle()}; + } + + template + data::Schema, enc::Native> + operator/(const data &rhs) const { + return {dat_ / rhs.handle()}; + } + + /** + * The underlying value, with the unit stripped. Mostly for the + * multiplication and division operators above. + */ + const BaseData &handle() const { return dat_; } + + BaseData &handle() { return dat_; } +}; + +} // namespace lbm +} // namespace kel diff --git a/modules/core/c++/abstract/unit_print.hpp b/modules/core/c++/abstract/unit_print.hpp new file mode 100644 index 0000000..049e54f --- /dev/null +++ b/modules/core/c++/abstract/unit_print.hpp @@ -0,0 +1,62 @@ +#pragma once + +#include + +#include "unit.hpp" + +namespace std { +template +inline ostream &operator<<(ostream &o, + const ::kel::lbm::sch::UnitElement &) { + o << UT::short_name; + if constexpr (UE != 1) { + o << '^' << '(' << UE << ')'; + } + return o; +} +} // namespace std + +namespace kel { +namespace lbm { +namespace impl { +template struct unit_print { + static_assert(always_false, "Template type not supported"); +}; + +template +struct unit_print, sch::UnitElement...> { + static std::ostream &print(std::ostream &o) { + sch::UnitElement element; + + std::ostream &o_ret = o << element; + + if constexpr (sizeof...(UTL) > 0) { + std::ostream &o_ret_next = o_ret << ' ' << '*' << ' '; + return unit_print...>::print(o_ret_next); + } + + return o_ret << ']'; + } +}; +} // namespace impl +} // namespace lbm +} // namespace kel + +namespace std { +template +inline ostream & +operator<<(ostream &o, + const ::kel::lbm::data< + ::kel::lbm::sch::Unit< + StorageT, ::kel::lbm::sch::UnitElement...>, + Encode> &unit) { + o << unit.handle().get(); + if constexpr (sizeof...(UnitT) > 0) { + auto &o_ret = o << ' ' << '['; + return ::kel::lbm::impl::unit_print< + ::kel::lbm::sch::UnitElement...>::print(o_ret); + } + return o; +} +} // namespace std diff --git a/modules/core/c++/boundary.hpp b/modules/core/c++/boundary.hpp index ca2b228..d9ac941 100644 --- a/modules/core/c++/boundary.hpp +++ b/modules/core/c++/boundary.hpp @@ -47,15 +47,15 @@ public: /** * Thoughts regarding automating order setup */ - static constexpr saw::string_literal name = "full_way_bounce_back"; - static constexpr saw::string_literal after = ""; - static constexpr saw::string_literal before = "streaming"; + static constexpr kel::lbm::string_literal name = "full_way_bounce_back"; + static constexpr kel::lbm::string_literal after = ""; + static constexpr kel::lbm::string_literal before = "streaming"; /** * Raw setup */ template - void apply(const saw::data& field, const saw::data>& index, saw::data time_step)const{ + void apply(const kel::lbm::data& field, const kel::lbm::data>& index, kel::lbm::data time_step)const{ bool is_even = ((time_step.get() % 2u) == 0u); // This is a ref @@ -96,15 +96,15 @@ public: /** * Thoughts regarding automating order setup */ - static constexpr saw::string_literal name = "full_way_anti_bounce_back"; - static constexpr saw::string_literal after = ""; - static constexpr saw::string_literal before = "streaming"; + static constexpr kel::lbm::string_literal name = "full_way_anti_bounce_back"; + static constexpr kel::lbm::string_literal after = ""; + static constexpr kel::lbm::string_literal before = "streaming"; /** * Raw setup */ template - void apply(const saw::data& field, const saw::data>& index, saw::data time_step)const{ + void apply(const kel::lbm::data& field, const kel::lbm::data>& index, kel::lbm::data time_step)const{ bool is_even = ((time_step.get() % 2u) == 0u); // This is a ref @@ -135,19 +135,19 @@ public: template class component final { private: - saw::data> density_; - saw::data> momentum_; + kel::lbm::data> density_; + kel::lbm::data> momentum_; public: component( - saw::data> density__, - saw::data> momentum__ + kel::lbm::data> density__, + kel::lbm::data> momentum__ ): density_{density__}, momentum_{momentum__} {} template - void apply(const saw::data& field, const saw::data>& index, saw::data time_step) const { + void apply(const kel::lbm::data& field, const kel::lbm::data>& index, kel::lbm::data time_step) const { bool is_even = ((time_step.get() % 2u) == 0u); using dfi = df_info; @@ -177,14 +177,14 @@ class component, cmpt::ZouHePressureX, Encode> f public: using Descriptor = sch::Descriptor<2u,9u>; private: - saw::data rho_setting_; + kel::lbm::data rho_setting_; public: - component(const saw::data& rho_setting__): + component(const kel::lbm::data& rho_setting__): rho_setting_{rho_setting__} {} template - void apply(const saw::data& field, saw::data> index, saw::data time_step) const { + void apply(const kel::lbm::data& field, kel::lbm::data> index, kel::lbm::data time_step) const { using dfi = df_info; bool is_even = ((time_step.get() % 2) == 0); @@ -196,7 +196,7 @@ public: auto& dfs_old = dfs_old_f.at(index); - auto rho_vel_x = [&]() -> saw::data { + auto rho_vel_x = [&]() -> kel::lbm::data { if constexpr (Dir){ auto S = dfs_old.at({0u}) + dfs_old.at({3u}) + dfs_old.at({4u}) @@ -215,13 +215,13 @@ public: // static_assert(Descriptor::D == 2u and Descriptor::Q == 9u, "Some parts are hard coded sadly"); if constexpr (Dir) { - dfs_old.at({2u}) = dfs_old.at({1u}) + saw::data{2.0 / 3.0} * rho_vel_x; - dfs_old.at({6u}) = dfs_old.at({5u}) + saw::data{1.0 / 6.0} * rho_vel_x + saw::data{0.5} * (dfs_old.at({3u}) - dfs_old.at({4u})); - dfs_old.at({8u}) = dfs_old.at({7u}) + saw::data{1.0 / 6.0} * rho_vel_x + saw::data{0.5} * (dfs_old.at({4u}) - dfs_old.at({3u})); + dfs_old.at({2u}) = dfs_old.at({1u}) + kel::lbm::data{2.0 / 3.0} * rho_vel_x; + dfs_old.at({6u}) = dfs_old.at({5u}) + kel::lbm::data{1.0 / 6.0} * rho_vel_x + kel::lbm::data{0.5} * (dfs_old.at({3u}) - dfs_old.at({4u})); + dfs_old.at({8u}) = dfs_old.at({7u}) + kel::lbm::data{1.0 / 6.0} * rho_vel_x + kel::lbm::data{0.5} * (dfs_old.at({4u}) - dfs_old.at({3u})); }else if constexpr (not Dir){ - dfs_old.at({1u}) = dfs_old.at({2u}) - saw::data{2.0 / 3.0} * rho_vel_x; - dfs_old.at({5u}) = dfs_old.at({6u}) - saw::data{1.0 / 6.0} * rho_vel_x + saw::data{0.5} * (dfs_old.at({4u}) - dfs_old.at({3u})); - dfs_old.at({7u}) = dfs_old.at({8u}) - saw::data{1.0 / 6.0} * rho_vel_x + saw::data{0.5} * (dfs_old.at({3u}) - dfs_old.at({4u})); + dfs_old.at({1u}) = dfs_old.at({2u}) - kel::lbm::data{2.0 / 3.0} * rho_vel_x; + dfs_old.at({5u}) = dfs_old.at({6u}) - kel::lbm::data{1.0 / 6.0} * rho_vel_x + kel::lbm::data{0.5} * (dfs_old.at({4u}) - dfs_old.at({3u})); + dfs_old.at({7u}) = dfs_old.at({8u}) - kel::lbm::data{1.0 / 6.0} * rho_vel_x + kel::lbm::data{0.5} * (dfs_old.at({3u}) - dfs_old.at({4u})); } } }; @@ -231,14 +231,14 @@ class component, cmpt::ZouHePressureX, Encode> public: using Descriptor = sch::Descriptor<3u,27u>; private: - saw::data rho_setting_; + kel::lbm::data rho_setting_; public: - component(const saw::data& rho_setting__): + component(const kel::lbm::data& rho_setting__): rho_setting_{rho_setting__} {} template - void apply(const saw::data& field, saw::data> index, saw::data time_step) const { + void apply(const kel::lbm::data& field, kel::lbm::data> index, kel::lbm::data time_step) const { using dfi = df_info; bool is_even = ((time_step.get() % 2) == 0); @@ -288,7 +288,7 @@ public: * rho*ux = S - rho */ - saw::data S; + kel::lbm::data S; if constexpr (East) { @@ -305,7 +305,7 @@ public: + f.at({24u}) // cx = +1 - + saw::data{2.0} * ( + + kel::lbm::data{2.0} * ( f.at({2u}) + f.at({5u}) + f.at({8u}) @@ -332,7 +332,7 @@ public: + f.at({24u}) // cx = -1 - + saw::data{2.0} * ( + + kel::lbm::data{2.0} * ( f.at({1u}) + f.at({4u}) + f.at({7u}) @@ -345,7 +345,7 @@ public: ); } - saw::data rho_ux; + kel::lbm::data rho_ux; if constexpr (East) { rho_ux = rho_setting_ - S; @@ -375,8 +375,8 @@ public: * + 2*x=-1 contribution */ - saw::data rho_uy; - saw::data rho_uz; + kel::lbm::data rho_uy; + kel::lbm::data rho_uz; if constexpr (East) { @@ -390,7 +390,7 @@ public: + f.at({24u}) // cx = +1 - + saw::data{2.0} * ( + + kel::lbm::data{2.0} * ( -f.at({5u}) + f.at({8u}) -f.at({14u}) @@ -409,7 +409,7 @@ public: + f.at({24u}) // cx = +1 - + saw::data{2.0} * ( + + kel::lbm::data{2.0} * ( -f.at({11u}) -f.at({14u}) -f.at({17u}) @@ -430,7 +430,7 @@ public: + f.at({24u}) // cx = -1 - + saw::data{2.0} * ( + + kel::lbm::data{2.0} * ( -f.at({4u}) + f.at({7u}) -f.at({13u}) @@ -449,7 +449,7 @@ public: +f.at({24u}) // cx = -1 - + saw::data{2.0} * ( + + kel::lbm::data{2.0} * ( -f.at({10u}) -f.at({13u}) -f.at({16u}) @@ -466,9 +466,9 @@ public: * ============================================================ */ - saw::data ux = rho_ux / rho_setting_; - saw::data uy = rho_uy / rho_setting_; - saw::data uz = rho_uz / rho_setting_; + kel::lbm::data ux = rho_ux / rho_setting_; + kel::lbm::data uy = rho_uy / rho_setting_; + kel::lbm::data uz = rho_uz / rho_setting_; /* @@ -516,7 +516,7 @@ public: f.at({1u}) = f.at({2u}) - - saw::data{1.0 / 6.0} * rho_ux; + - kel::lbm::data{1.0 / 6.0} * rho_ux; /* @@ -527,7 +527,7 @@ public: f.at({4u}) = f.at({5u}) - - saw::data{1.0 / 9.0} + - kel::lbm::data{1.0 / 9.0} * (rho_ux + rho_uy); @@ -539,7 +539,7 @@ public: f.at({7u}) = f.at({8u}) - + saw::data{1.0 / 9.0} + + kel::lbm::data{1.0 / 9.0} * (-rho_ux + rho_uy); @@ -551,7 +551,7 @@ public: f.at({10u}) = f.at({11u}) - - saw::data{1.0 / 9.0} + - kel::lbm::data{1.0 / 9.0} * (rho_ux + rho_uz); @@ -563,7 +563,7 @@ public: f.at({13u}) = f.at({14u}) - - saw::data{1.0 / 36.0} + - kel::lbm::data{1.0 / 36.0} * (rho_ux + rho_uy + rho_uz); @@ -575,7 +575,7 @@ public: f.at({16u}) = f.at({17u}) - + saw::data{1.0 / 36.0} + + kel::lbm::data{1.0 / 36.0} * (-rho_ux + rho_uy + rho_uz); @@ -587,7 +587,7 @@ public: f.at({19u}) = f.at({20u}) - + saw::data{1.0 / 9.0} + + kel::lbm::data{1.0 / 9.0} * (-rho_ux + rho_uz); @@ -599,7 +599,7 @@ public: f.at({22u}) = f.at({23u}) - + saw::data{1.0 / 36.0} + + kel::lbm::data{1.0 / 36.0} * (-rho_ux - rho_uy + rho_uz); @@ -611,7 +611,7 @@ public: f.at({25u}) = f.at({26u}) - + saw::data{1.0 / 36.0} + + kel::lbm::data{1.0 / 36.0} * (-rho_ux + rho_uy + rho_uz); } else { @@ -624,7 +624,7 @@ public: f.at({2u}) = f.at({1u}) - + saw::data{1.0 / 6.0} * rho_ux; + + kel::lbm::data{1.0 / 6.0} * rho_ux; /* @@ -635,7 +635,7 @@ public: f.at({5u}) = f.at({4u}) - + saw::data{1.0 / 9.0} + + kel::lbm::data{1.0 / 9.0} * (rho_ux - rho_uy); @@ -647,7 +647,7 @@ public: f.at({8u}) = f.at({7u}) - + saw::data{1.0 / 9.0} + + kel::lbm::data{1.0 / 9.0} * (rho_ux + rho_uy); @@ -659,7 +659,7 @@ public: f.at({11u}) = f.at({10u}) - + saw::data{1.0 / 9.0} + + kel::lbm::data{1.0 / 9.0} * (rho_ux - rho_uz); @@ -671,7 +671,7 @@ public: f.at({14u}) = f.at({13u}) - + saw::data{1.0 / 36.0} + + kel::lbm::data{1.0 / 36.0} * (rho_ux - rho_uy - rho_uz); @@ -683,7 +683,7 @@ public: f.at({17u}) = f.at({16u}) - + saw::data{1.0 / 36.0} + + kel::lbm::data{1.0 / 36.0} * (rho_ux + rho_uy - rho_uz); @@ -695,7 +695,7 @@ public: f.at({20u}) = f.at({19u}) - + saw::data{1.0 / 9.0} + + kel::lbm::data{1.0 / 9.0} * (rho_ux + rho_uz); @@ -707,7 +707,7 @@ public: f.at({23u}) = f.at({22u}) - + saw::data{1.0 / 36.0} + + kel::lbm::data{1.0 / 36.0} * (rho_ux - rho_uy + rho_uz); @@ -719,7 +719,7 @@ public: f.at({26u}) = f.at({25u}) - + saw::data{1.0 / 36.0} + + kel::lbm::data{1.0 / 36.0} * (rho_ux + rho_uy + rho_uz); } } @@ -729,16 +729,16 @@ public: template class component, Encode> final { private: - saw::data> velocity_; + kel::lbm::data> velocity_; public: component( - const saw::data>& velocity__ + const kel::lbm::data>& velocity__ ): velocity_{velocity__} {} template - void apply(const saw::data& field, const saw::data>& index, saw::data time_step) const { + void apply(const kel::lbm::data& field, const kel::lbm::data>& index, kel::lbm::data time_step) const { bool is_even = ((time_step.get() % 2u) == 0u); using dfi = df_info; @@ -748,27 +748,27 @@ public: auto& dfs = dfs_old_f.at(index); - saw::data dir_sum; + kel::lbm::data dir_sum; if constexpr (East) { dir_sum = dfs.at({1u}) + dfs.at({5u}) + dfs.at({7u}); } else if constexpr(not East){ dir_sum = dfs.at({2u}) + dfs.at({6u}) + dfs.at({8u}); } - saw::data> rho; - rho.at({}) = (dfs.at({0u}) + dfs.at({4u}) + dfs.at({3u}) + dir_sum * 2) / (velocity_.at({{0u}}) + saw::data{static_cast::type>(1.0)}); + kel::lbm::data> rho; + rho.at({}) = (dfs.at({0u}) + dfs.at({4u}) + dfs.at({3u}) + dir_sum * 2) / (velocity_.at({{0u}}) + kel::lbm::data{static_cast::type>(1.0)}); if constexpr (East) { - dfs.at({2u}) = dfs.at({1u}) + saw::data{static_cast::type>(2.0 / 3.0)} * rho.at({}) * velocity_.at({{0u}}); - dfs.at({6u}) = dfs.at({5u}) + saw::data{static_cast::type>(1.0 / 6.0)} * rho.at({}) * velocity_.at({{0u}}) + dfs.at({2u}) = dfs.at({1u}) + kel::lbm::data{static_cast::type>(2.0 / 3.0)} * rho.at({}) * velocity_.at({{0u}}); + dfs.at({6u}) = dfs.at({5u}) + kel::lbm::data{static_cast::type>(1.0 / 6.0)} * rho.at({}) * velocity_.at({{0u}}) + (dfs.at({3u}) - dfs.at({4u}) + rho.at({}) * velocity_.at({{1u}})) * 0.5f; - dfs.at({8u}) = dfs.at({7u}) + saw::data{static_cast::type>(1.0 / 6.0)} * rho.at({}) * velocity_.at({{0u}}) + dfs.at({8u}) = dfs.at({7u}) + kel::lbm::data{static_cast::type>(1.0 / 6.0)} * rho.at({}) * velocity_.at({{0u}}) + (dfs.at({4u}) - dfs.at({3u}) + rho.at({}) * velocity_.at({{1u}})) * 0.5f; }else if constexpr ( not East ){ - dfs.at({1u}) = dfs.at({2u}) + saw::data{static_cast::type>(2.0 / 3.0)} * rho.at({}) * velocity_.at({{0u}}); - dfs.at({5u}) = dfs.at({6u}) + saw::data{static_cast::type>(1.0 / 6.0)} * rho.at({}) * velocity_.at({{0u}}) + dfs.at({1u}) = dfs.at({2u}) + kel::lbm::data{static_cast::type>(2.0 / 3.0)} * rho.at({}) * velocity_.at({{0u}}); + dfs.at({5u}) = dfs.at({6u}) + kel::lbm::data{static_cast::type>(1.0 / 6.0)} * rho.at({}) * velocity_.at({{0u}}) + (dfs.at({4u}) - dfs.at({3u}) + rho.at({}) * velocity_.at({{1u}}))*0.5f; - dfs.at({7u}) = dfs.at({8u}) + saw::data{static_cast::type>(1.0 / 6.0)} * rho.at({}) * velocity_.at({{0u}}) + dfs.at({7u}) = dfs.at({8u}) + kel::lbm::data{static_cast::type>(1.0 / 6.0)} * rho.at({}) * velocity_.at({{0u}}) + (dfs.at({3u}) - dfs.at({4u}) + rho.at({}) * velocity_.at({{1u}}))*0.5f; } } diff --git a/modules/core/c++/chunk.hpp b/modules/core/c++/chunk.hpp index 635af91..126add8 100644 --- a/modules/core/c++/chunk.hpp +++ b/modules/core/c++/chunk.hpp @@ -7,16 +7,16 @@ namespace kel { namespace lbm { namespace sch { namespace impl { -template> +template> struct chunk_schema_type_helper; template -struct chunk_schema_type_helper, saw::tmpl_value_group> final { - using Schema = typename chunk_schema_type_helper, saw::tmpl_value_group>::Schema; +struct chunk_schema_type_helper, kel::lbm::tmpl_value_group> final { + using Schema = typename chunk_schema_type_helper, kel::lbm::tmpl_value_group>::Schema; }; template -struct chunk_schema_type_helper, saw::tmpl_value_group> final { +struct chunk_schema_type_helper, kel::lbm::tmpl_value_group> final { using Schema = FixedArray; }; } @@ -24,7 +24,13 @@ struct chunk_schema_type_helper, saw template struct Chunk { - using InnerSchema = typename impl::chunk_schema_type_helper>::Schema; + /** + * A chunk's extents are compile time constants, so it carries nothing of + * its own at runtime; whatever metadata its stored value needs is all + * there is. + */ + using Meta = typename Sch::Meta; + using InnerSchema = typename impl::chunk_schema_type_helper>::Schema; using StoredValueSchema = Sch; }; @@ -35,7 +41,8 @@ using SuperChunk = Array; } } -namespace saw { +namespace kel { +namespace lbm { template class data,Encode> final { @@ -47,11 +54,11 @@ private: data values_; public: - data& ghost_at(const data>& index){ + data& ghost_at(const data>& index){ return values_.at(index); } - const data& ghost_at(const data>& index) const { + const data& ghost_at(const data>& index) const { return values_.at(index); } @@ -59,7 +66,7 @@ public: return data::get_dims(); } - static constexpr auto to_ghost_index(const data>& index){ + static constexpr auto to_ghost_index(const data>& index){ std::decay_t ind; for(uint64_t i = 0u; i < sizeof...(Sides); ++i){ ind.at({i}) = index.at({i}) + Ghost; @@ -67,23 +74,23 @@ public: return ind; } - data& at(const data>& index){ + data& at(const data>& index){ std::decay_t ind = to_ghost_index(index); return values_.at(ind); } - const data& at(const data>& index) const { + const data& at(const data>& index) const { std::decay_t ind = to_ghost_index(index); return values_.at(ind); } /* - const data& neighbour_at(const data>& index) const { + const data& neighbour_at(const data>& index) const { } */ static constexpr auto get_dims(){ - return data,Encode>{{Sides...}}; + return data,Encode>{{Sides...}}; } auto flat_data(){ @@ -101,3 +108,4 @@ struct meta_schema> { }; } +} diff --git a/modules/core/c++/collision.hpp b/modules/core/c++/collision.hpp index ec21b5f..d3e70cb 100644 --- a/modules/core/c++/collision.hpp +++ b/modules/core/c++/collision.hpp @@ -19,22 +19,22 @@ struct BGKGuo {}; template class component { private: - saw::data relaxation_; - saw::data frequency_; + kel::lbm::data relaxation_; + kel::lbm::data frequency_; public: - component(typename saw::native_data_type::type relaxation__): + component(typename kel::lbm::native_data_type::type relaxation__): relaxation_{{relaxation__}}, - frequency_{saw::data{1} / relaxation_} + frequency_{kel::lbm::data{1} / relaxation_} {} - component(const saw::data& relaxation__): + component(const kel::lbm::data& relaxation__): relaxation_{relaxation__}, - frequency_{saw::data{1} / relaxation_} + frequency_{kel::lbm::data{1} / relaxation_} {} - component(const saw::data>& relaxation__): + component(const kel::lbm::data>& relaxation__): relaxation_{relaxation__.handle()}, - frequency_{saw::data{typename saw::native_data_type::type(1)} / relaxation_} + frequency_{kel::lbm::data{typename kel::lbm::native_data_type::type(1)} / relaxation_} {} using Component = cmpt::BGK; @@ -49,22 +49,22 @@ public: /** * Thoughts regarding automating order setup */ - static constexpr saw::string_literal name = "collision"; - static constexpr saw::string_literal after = ""; - static constexpr saw::string_literal before = "streaming"; + static constexpr kel::lbm::string_literal name = "collision"; + static constexpr kel::lbm::string_literal after = ""; + static constexpr kel::lbm::string_literal before = "streaming"; /** * Raw setup */ template - void apply(const saw::data& field, saw::data> index, saw::data time_step) const { + void apply(const kel::lbm::data& field, kel::lbm::data> index, kel::lbm::data time_step) const { bool is_even = ((time_step.get() % 2) == 0); // auto& dfs_f = (is_even) ? field.template get<"dfs">() : field.template get<"dfs_old">(); auto& dfs_old_f = (is_even) ? field.template get<"dfs_old">() : field.template get<"dfs">(); - saw::data> rho; - saw::data> vel; + kel::lbm::data> rho; + kel::lbm::data> vel; compute_rho_u(dfs_old_f.at(index),rho,vel); auto eq = equilibrium(rho,vel); @@ -74,7 +74,7 @@ public: } template - void apply(const saw::data& field, const saw::data& macros, saw::data> index, saw::data time_step) const { + void apply(const kel::lbm::data& field, const kel::lbm::data& macros, kel::lbm::data> index, kel::lbm::data time_step) const { bool is_even = ((time_step.get() % 2) == 0); // auto& dfs_f = (is_even) ? field.template get<"dfs">() : field.template get<"dfs_old">(); @@ -83,8 +83,8 @@ public: auto& rho_f = macros.template get<"density">(); auto& vel_f = macros.template get<"momentum">(); - saw::data>& rho = rho_f.at(index); - saw::data>& vel = vel_f.at(index); + kel::lbm::data>& rho = rho_f.at(index); + kel::lbm::data>& vel = vel_f.at(index); compute_rho_u(dfs_old_f.at(index),rho,vel); @@ -99,22 +99,22 @@ public: template class component { private: - typename saw::native_data_type::type relaxation_; - saw::data frequency_; - saw::data> global_force_; + typename kel::lbm::native_data_type::type relaxation_; + kel::lbm::data frequency_; + kel::lbm::data> global_force_; public: - component(typename saw::native_data_type::type relaxation__): + component(typename kel::lbm::native_data_type::type relaxation__): relaxation_{relaxation__}, - frequency_{typename saw::native_data_type::type(1) / relaxation_}, + frequency_{typename kel::lbm::native_data_type::type(1) / relaxation_}, global_force_{} {} component( - typename saw::native_data_type::type relaxation__, - saw::data>& global_force__ + typename kel::lbm::native_data_type::type relaxation__, + kel::lbm::data>& global_force__ ): relaxation_{relaxation__}, - frequency_{typename saw::native_data_type::type(1) / relaxation_}, + frequency_{typename kel::lbm::native_data_type::type(1) / relaxation_}, global_force_{global_force__} {} @@ -128,13 +128,13 @@ public: /** * Thoughts regarding automating order setup */ - static constexpr saw::string_literal name = "collision"; - static constexpr saw::string_literal after = ""; - static constexpr saw::string_literal before = "streaming"; + static constexpr kel::lbm::string_literal name = "collision"; + static constexpr kel::lbm::string_literal after = ""; + static constexpr kel::lbm::string_literal before = "streaming"; template - void apply(const saw::data& field, const saw::data& macros, saw::data> index, saw::data time_step) const { - // void apply(saw::data& field, saw::data> index, saw::data time_step){ + void apply(const kel::lbm::data& field, const kel::lbm::data& macros, kel::lbm::data> index, kel::lbm::data time_step) const { + // void apply(kel::lbm::data& field, kel::lbm::data> index, kel::lbm::data time_step){ bool is_even = ((time_step.get() % 2) == 0); auto& dfs_old_f = (is_even) ? field.template get<"dfs_old">() : field.template get<"dfs">(); @@ -143,14 +143,14 @@ public: auto& rho_f = macros.template get<"density">(); auto& vel_f = macros.template get<"momentum">(); - saw::data>& rho = rho_f.at(index); + kel::lbm::data>& rho = rho_f.at(index); auto& force_f = macros.template get<"force">(); auto& force = force_f.at(index); auto total_force = force + global_force_; - saw::data> half; + kel::lbm::data> half; half.at({}).set(0.5); auto& vel = vel_f.at(index); vel = vel + total_force * ( half / rho ); @@ -161,29 +161,29 @@ public: using dfi = df_info; - saw::data> dfi_inv_cs2; + kel::lbm::data> dfi_inv_cs2; dfi_inv_cs2.at({}).set(dfi::inv_cs2); // auto vel = vel_f.at(index); for(uint64_t i = 0u; i < Descriptor::Q; ++i){ - // saw::data ci_min_u{0}; - saw::data> ci; + // kel::lbm::data ci_min_u{0}; + kel::lbm::data> ci; for(uint64_t d = 0u; d < Descriptor::D; ++d){ - ci.at({{d}}).set(static_cast::type>(dfi::directions[i][d])); + ci.at({{d}}).set(static_cast::type>(dfi::directions[i][d])); } - auto ci_dot_u = saw::math::dot(ci,vel); + auto ci_dot_u = kel::lbm::math::dot(ci,vel); - // saw::data> F_i; + // kel::lbm::data> F_i; // F_i = f * ((c_i - u) * ics2 + * c_i * ics2 * ics2) * w_i; - saw::data> w; + kel::lbm::data> w; w.at({}).set(dfi::weights[i]); /* - saw::data> F_i_sum; + kel::lbm::data> F_i_sum; for(uint64_t d = 0u; d < Descriptor::D; ++d){ - saw::data> F_i_d; + kel::lbm::data> F_i_d; F_i_d.at({}) = F_i.at({{d}}); F_i_sum = F_i_sum + F_i_d; } @@ -191,7 +191,7 @@ public: auto term1 = (ci-vel) * dfi_inv_cs2; auto term2 = ci * (ci_dot_u * dfi_inv_cs2 * dfi_inv_cs2); - auto force_projection = saw::math::dot(term1 + term2, total_force); + auto force_projection = kel::lbm::math::dot(term1 + term2, total_force); auto F_i = w * force_projection; @@ -199,7 +199,7 @@ public: + frequency_ * (eq.at(i) - dfs.at({i}) ) + F_i.at({}) - * (saw::data{1} - saw::data{0.5f} * frequency_); + * (kel::lbm::data{1} - kel::lbm::data{0.5f} * frequency_); } } }; diff --git a/modules/core/c++/common.hpp b/modules/core/c++/common.hpp index 280d953..52265e2 100644 --- a/modules/core/c++/common.hpp +++ b/modules/core/c++/common.hpp @@ -1,12 +1,11 @@ #pragma once -#include -#include +#include "abstract/data.hpp" +#include "abstract/math.hpp" namespace kel { namespace lbm { namespace sch { -using namespace saw::schema; } } } diff --git a/modules/core/c++/component.hpp b/modules/core/c++/component.hpp index 1e5dbbf..46dd58f 100644 --- a/modules/core/c++/component.hpp +++ b/modules/core/c++/component.hpp @@ -10,10 +10,10 @@ namespace cmpt { /** * Maybe for the future */ -template +template class access { public: - static constexpr saw::string_literal name = Name; + static constexpr kel::lbm::string_literal name = Name; static constexpr uint64_t distance = Dist; static constexpr bool read = Read; static constexpr bool write = Write; @@ -32,7 +32,7 @@ public: /** * Component class which forms the basis of each processing step */ -template +template class component {}; } } diff --git a/modules/core/c++/component/psm.hpp b/modules/core/c++/component/psm.hpp index 5832760..e3ffa67 100644 --- a/modules/core/c++/component/psm.hpp +++ b/modules/core/c++/component/psm.hpp @@ -2,7 +2,7 @@ #include "../macroscopic.hpp" #include "../equilibrium.hpp" -#include "common.hpp" +#include "../component.hpp" namespace kel { namespace lbm { @@ -16,21 +16,21 @@ struct PSM {}; template class component { private: - saw::data relaxation_; - saw::data frequency_; + kel::lbm::data relaxation_; + kel::lbm::data frequency_; public: component( - typename saw::native_data_type::type relaxation__ + typename kel::lbm::native_data_type::type relaxation__ ): relaxation_{relaxation__} { - saw::data one; + kel::lbm::data one; one = 1.0; frequency_ = one / relaxation_; } template - void apply(const saw::data& field, const saw::data& macros, saw::data> index, saw::data time_step) const { + void apply(const kel::lbm::data& field, const kel::lbm::data& macros, kel::lbm::data> index, kel::lbm::data time_step) const { using dfi = df_info; bool is_even = ((time_step.get() % 2) == 0); @@ -41,14 +41,14 @@ public: auto& rho_f = macros.template get<"density">(); auto& vel_f = macros.template get<"momentum">(); - saw::data>& rho = rho_f.at(index); - saw::data>& vel = vel_f.at(index); + kel::lbm::data>& rho = rho_f.at(index); + kel::lbm::data>& vel = vel_f.at(index); compute_rho_u(dfs_old_f.at(index),rho,vel); auto eq = equilibrium(rho,vel); - saw::data one{1.0}; + kel::lbm::data one{1.0}; auto& porous = porous_f.at(index); auto flip_porous = one - porous.at({}); diff --git a/modules/core/c++/config.hpp b/modules/core/c++/config.hpp index 64f7a0f..0665081 100644 --- a/modules/core/c++/config.hpp +++ b/modules/core/c++/config.hpp @@ -1,9 +1,10 @@ #pragma once -#include -#include +#include "abstract/data.hpp" +#include "abstract/json.hpp" #include +#include #include #include #include @@ -11,7 +12,6 @@ namespace kel { namespace lbm { namespace sch { -using namespace saw::schema; template using LbmConfig = Struct< Member, @@ -21,25 +21,26 @@ using LbmConfig = Struct< } template -saw::error_or>> load_lbm_config(std::string_view file_name){ - std::ifstream file{std::string{file_name}}; +error_or>> load_lbm_config(std::string_view file_name){ + std::ifstream file{std::string{file_name}, std::ios::binary}; if(!file.is_open()){ - return saw::make_error("Couldn't open file"); + return make_error("Couldn't open file"); } - saw::data, saw::encode::Json> lbm_json_conf{saw::heap(1u)}; + std::string contents{ + std::istreambuf_iterator{file}, + std::istreambuf_iterator{} + }; - uint8_t ele{}; - while(file.readsome(reinterpret_cast(&ele), 1u) > 0u){ - auto err = lbm_json_conf.get_buffer().push(ele,1u); - if(err.failed()){ - return err; - } + if(file.bad()){ + return make_error("Couldn't read file"); } - saw::data> lbm_conf; - saw::codec, saw::encode::Json> json_codec; + data, enc::Json> lbm_json_conf{std::move(contents)}; + + data> lbm_conf; + codec, enc::Json> json_codec; { auto eov = json_codec.decode(lbm_json_conf, lbm_conf); if(eov.is_error()){ diff --git a/modules/core/c++/converter.hpp b/modules/core/c++/converter.hpp index 3f0638b..93c7617 100644 --- a/modules/core/c++/converter.hpp +++ b/modules/core/c++/converter.hpp @@ -7,7 +7,6 @@ namespace kel { namespace lbm { namespace sch { -using namespace saw::schema; } /** @@ -16,13 +15,13 @@ using namespace saw::schema; template class converter { private: - saw::data, sch::LbmMeter >::Schema > meter_conv_; - saw::data, sch::LbmSecond >::Schema > second_conv_; + kel::lbm::data, sch::LbmMeter >::Schema > meter_conv_; + kel::lbm::data, sch::LbmSecond >::Schema > second_conv_; public: converter() = delete; converter( - saw::data, sch::LbmMeter >::Schema > meter_conv__, - saw::data, sch::LbmSecond >::Schema > second_conv__ + kel::lbm::data, sch::LbmMeter >::Schema > meter_conv__, + kel::lbm::data, sch::LbmSecond >::Schema > second_conv__ ): meter_conv_{meter_conv__}, second_conv_{second_conv__} @@ -43,53 +42,53 @@ public: } auto delta_x() const { - return meter_conv_*saw::data>{1.0}; + return meter_conv_*kel::lbm::data>{1.0}; } auto delta_t() const { - return second_conv_*saw::data>{1.0}; + return second_conv_*kel::lbm::data>{1.0}; } auto delta_v() const { - return (meter_conv_ / second_conv_) * saw::data>{1.0}; + return (meter_conv_ / second_conv_) * kel::lbm::data>{1.0}; } auto delta_a() const { - return (meter_conv_ / (second_conv_*second_conv_)) * saw::data>{1.0}; + return (meter_conv_ / (second_conv_*second_conv_)) * kel::lbm::data>{1.0}; } - saw::data> meter_si_to_lbm(const saw::data>& m_si) const { + kel::lbm::data> meter_si_to_lbm(const kel::lbm::data>& m_si) const { return m_si / meter_conv_; } - saw::data> meter_lbm_to_si(const saw::data>& m_lbm) const { + kel::lbm::data> meter_lbm_to_si(const kel::lbm::data>& m_lbm) const { return m_lbm * meter_conv_; } - saw::data> second_si_to_lbm(const saw::data>& s_si) const { + kel::lbm::data> second_si_to_lbm(const kel::lbm::data>& s_si) const { return s_si / second_conv_; } - saw::data> velocity_si_to_lbm(const saw::data>& vel_si) const { + kel::lbm::data> velocity_si_to_lbm(const kel::lbm::data>& vel_si) const { return (vel_si / meter_conv_) * second_conv_; } - saw::data> acceleration_si_to_lbm(const saw::data>& acc_si) const { + kel::lbm::data> acceleration_si_to_lbm(const kel::lbm::data>& acc_si) const { return (acc_si / meter_conv_) * (second_conv_ * second_conv_); } - saw::data> kinematic_viscosity_si_to_lbm (const saw::data>& kin_si) const { + kel::lbm::data> kinematic_viscosity_si_to_lbm (const kel::lbm::data>& kin_si) const { return (kin_si / (meter_conv_ * meter_conv_)) * second_conv_; } template - saw::data> kinematic_viscosity_si_to_tau(const saw::data>& kin_si) const { - return saw::data>{saw::data, sch::LbmKinematicViscosity>::Schema >{df_info::inv_cs2} * kinematic_viscosity_si_to_lbm(kin_si) + saw::data>{0.5}}; + kel::lbm::data> kinematic_viscosity_si_to_tau(const kel::lbm::data>& kin_si) const { + return kel::lbm::data>{kel::lbm::data, sch::LbmKinematicViscosity>::Schema >{df_info::inv_cs2} * kinematic_viscosity_si_to_lbm(kin_si) + kel::lbm::data>{0.5}}; } template - saw::data> kinematic_viscosity_lbm_to_tau(const saw::data>& kin_lbm) const { - return saw::data>{saw::data, sch::LbmKinematicViscosity>::Schema >{df_info::inv_cs2} * kin_lbm + saw::data>{0.5}}; + kel::lbm::data> kinematic_viscosity_lbm_to_tau(const kel::lbm::data>& kin_lbm) const { + return kel::lbm::data>{kel::lbm::data, sch::LbmKinematicViscosity>::Schema >{df_info::inv_cs2} * kin_lbm + kel::lbm::data>{0.5}}; } }; } diff --git a/modules/core/c++/descriptor.hpp b/modules/core/c++/descriptor.hpp index ac09e7b..268a516 100644 --- a/modules/core/c++/descriptor.hpp +++ b/modules/core/c++/descriptor.hpp @@ -1,8 +1,8 @@ #pragma once -#include -#include -#include +#include "abstract/data.hpp" +#include "abstract/data_math.hpp" +#include "abstract/schema_factory.hpp" #include "descriptor/d1q3.hpp" #include "descriptor/d2q5.hpp" @@ -13,10 +13,11 @@ namespace kel { namespace lbm { namespace sch { -using namespace saw::schema; template struct Cell { + /// Mirrors the meta_schema specialisation further down this file. + using Meta = Void; using Descriptor = Desc; static constexpr uint64_t SC = SC_V; static constexpr uint64_t DC = DC_V; @@ -26,23 +27,26 @@ struct Cell { template struct CellField{ + /// A field is laid out over the grid, so the grid extents are its metadata. + using Meta = FixedArray; using Descriptor = Desc; }; -template +template struct CellField< Desc, Struct< Member... > > { + using Meta = FixedArray; using Descriptor = Desc; }; template struct CellFieldStruct { + using Meta = FixedArray; using Descriptor = Desc; - // using MetaSchema = FixedArray; }; } @@ -66,16 +70,16 @@ struct df_ct_helper { template class cell_schema_builder { private: - saw::schema_factory factory_struct_; + kel::lbm::schema_factory factory_struct_; public: cell_schema_builder() = default; - cell_schema_builder(saw::schema_factory inp): + cell_schema_builder(kel::lbm::schema_factory inp): factory_struct_{inp} {} /* - template + template constexpr auto require() const noexcept { return {factory_struct_.add_maybe()}; } @@ -85,23 +89,24 @@ public: } } -namespace saw { +namespace kel { +namespace lbm { template struct meta_schema> { - using MetaSchema = schema::Void; + using MetaSchema = sch::Void; using Schema = kel::lbm::sch::Cell; }; template struct meta_schema> { - using MetaSchema = schema::FixedArray; + using MetaSchema = sch::FixedArray; using Schema = kel::lbm::sch::CellField; }; template -struct meta_schema>> { - using MetaSchema = schema::FixedArray; - using Schema = kel::lbm::sch::CellFieldStruct>; +struct meta_schema>> { + using MetaSchema = sch::FixedArray; + using Schema = kel::lbm::sch::CellFieldStruct>; }; template @@ -110,15 +115,15 @@ public: using Schema = kel::lbm::sch::Cell; using MetaSchema = typename meta_schema::MetaSchema; private: - data, Encode> inner_; + data, Encode> inner_; public: data() = default; - data& operator()(const data& index){ + data& operator()(const data& index){ return inner_.at(index); } - const data& operator()(const data& index)const{ + const data& operator()(const data& index)const{ return inner_.at(index); } @@ -136,7 +141,7 @@ public: using Schema = kel::lbm::sch::CellField; using MetaSchema = typename meta_schema::MetaSchema; private: - data, Encode> inner_; + data, Encode> inner_; public: data() = default; data(const data& inner_meta__): @@ -148,28 +153,28 @@ public: } template - data get_dim_size() const { + data get_dim_size() const { static_assert(i < Desc::D, "Not enough dimensions"); return inner_.template get_dim_size(); } - const data& operator()(const data, Encode>& index)const{ + const data& operator()(const data, Encode>& index)const{ return inner_.at(index); } - data& operator()(const data, Encode>& index){ + data& operator()(const data, Encode>& index){ return inner_.at(index); } - const data& at(const data, Encode>& index)const{ + const data& at(const data, Encode>& index)const{ return inner_.at(index); } - data& at(const data, Encode>& index){ + data& at(const data, Encode>& index){ return inner_.at(index); } - data internal_size() const { + data internal_size() const { return inner_.internal_size(); } @@ -182,45 +187,45 @@ public: * Is basically a struct, but additionally has members for meta() calls. It technically is a Field of a struct, but organized through a struct of fields. */ template -class data>, Encode> final { +class data>, Encode> final { public: - using Schema = kel::lbm::sch::CellFieldStruct>; + using Schema = kel::lbm::sch::CellFieldStruct>; /// @TODO Add MetaSchema to Schema using MetaSchema = typename meta_schema::MetaSchema; private: static_assert(sizeof...(CellFieldsT) > 0u, ""); - data, Encode> inner_; + data, Encode> inner_; template - saw::error_or helper_constructor(const data>& grid_size){ - using MemT = saw::parameter_pack_type::type; + kel::lbm::error_or helper_constructor(const data>& grid_size){ + using MemT = kel::lbm::parameter_pack_type::type; { inner_.template get() = {grid_size}; } if constexpr (sizeof...(CellFieldsT) > (i+1u)){ return helper_constructor(grid_size); } - return saw::make_void(); + return kel::lbm::make_void(); } public: data() = delete; - data(const data>& grid_size__){ + data(const data>& grid_size__){ auto eov = helper_constructor<0u>(grid_size__); (void)eov; } const data meta() const { - using MemT = saw::parameter_pack_type<0u,CellFieldsT...>::type; + using MemT = kel::lbm::parameter_pack_type<0u,CellFieldsT...>::type; return inner_.template get().meta(); } - template + template auto& get() { return inner_.template get(); } - template + template const auto& get() const { return inner_.template get(); } @@ -228,3 +233,4 @@ public: } +} diff --git a/modules/core/c++/descriptor/common.hpp b/modules/core/c++/descriptor/common.hpp index a20e2ef..920d87b 100644 --- a/modules/core/c++/descriptor/common.hpp +++ b/modules/core/c++/descriptor/common.hpp @@ -5,7 +5,6 @@ namespace kel { namespace lbm { namespace sch { -using namespace saw::schema; template struct Descriptor { diff --git a/modules/core/c++/descriptor/d1q3.hpp b/modules/core/c++/descriptor/d1q3.hpp index 9ea0a35..7eb5827 100644 --- a/modules/core/c++/descriptor/d1q3.hpp +++ b/modules/core/c++/descriptor/d1q3.hpp @@ -22,7 +22,7 @@ public: { 1} }}; - static constexpr std::array::type, Q> weights = { + static constexpr std::array::type, Q> weights = { 2./3., 1./6., 1./6. @@ -32,8 +32,8 @@ public: 0,2,1 }; - static constexpr typename saw::native_data_type::type inv_cs2 = 3.0; - static constexpr typename saw::native_data_type::type cs2 = 1./3.; + static constexpr typename kel::lbm::native_data_type::type inv_cs2 = 3.0; + static constexpr typename kel::lbm::native_data_type::type cs2 = 1./3.; }; } diff --git a/modules/core/c++/descriptor/d2q4.hpp b/modules/core/c++/descriptor/d2q4.hpp index e867bbc..0476c80 100644 --- a/modules/core/c++/descriptor/d2q4.hpp +++ b/modules/core/c++/descriptor/d2q4.hpp @@ -23,7 +23,7 @@ public: { 0,-1}, // 3 }}; - static constexpr std::array::type,Q> weights = { + static constexpr std::array::type,Q> weights = { 1./3., 1./6., 1./6., @@ -39,8 +39,8 @@ public: }; */ - static constexpr typename saw::native_data_type::type inv_cs2 = 3.0; - static constexpr typename saw::native_data_type::type cs2 = 1./3.; + static constexpr typename kel::lbm::native_data_type::type inv_cs2 = 3.0; + static constexpr typename kel::lbm::native_data_type::type cs2 = 1./3.; }; diff --git a/modules/core/c++/descriptor/d2q5.hpp b/modules/core/c++/descriptor/d2q5.hpp index fef9c40..8a58b16 100644 --- a/modules/core/c++/descriptor/d2q5.hpp +++ b/modules/core/c++/descriptor/d2q5.hpp @@ -24,7 +24,7 @@ public: { 0, 1} // 4 }}; - static constexpr std::array::type,Q> weights = { + static constexpr std::array::type,Q> weights = { 1./3., 1./6., 1./6., @@ -40,8 +40,8 @@ public: 3 }; - static constexpr typename saw::native_data_type::type inv_cs2 = 3.0; - static constexpr typename saw::native_data_type::type cs2 = 1./3.; + static constexpr typename kel::lbm::native_data_type::type inv_cs2 = 3.0; + static constexpr typename kel::lbm::native_data_type::type cs2 = 1./3.; }; diff --git a/modules/core/c++/descriptor/d2q9.hpp b/modules/core/c++/descriptor/d2q9.hpp index 44c6e28..e950df1 100644 --- a/modules/core/c++/descriptor/d2q9.hpp +++ b/modules/core/c++/descriptor/d2q9.hpp @@ -28,7 +28,7 @@ public: { 1,-1} // 8 }}; - static constexpr std::array::type,Q> weights = { + static constexpr std::array::type,Q> weights = { 4./9., 1./9., 1./9., @@ -52,8 +52,8 @@ public: 7 }; - static constexpr typename saw::native_data_type::type inv_cs2 = 3.0; - static constexpr typename saw::native_data_type::type cs2 = 1./3.; + static constexpr typename kel::lbm::native_data_type::type inv_cs2 = 3.0; + static constexpr typename kel::lbm::native_data_type::type cs2 = 1./3.; }; diff --git a/modules/core/c++/descriptor/d3q19.hpp b/modules/core/c++/descriptor/d3q19.hpp index bbd1bd1..c1c8ccd 100644 --- a/modules/core/c++/descriptor/d3q19.hpp +++ b/modules/core/c++/descriptor/d3q19.hpp @@ -40,7 +40,7 @@ public: { 0, 1, 1} //18 }}; - static constexpr std::array::type,Q> weights = { + static constexpr std::array::type,Q> weights = { 1./3., 1./18., 1./18., @@ -65,8 +65,8 @@ public: 18,17,16,15 }; - static constexpr typename saw::native_data_type::type inv_cs2 = 3.0; - static constexpr typename saw::native_data_type::type cs2 = 1./3.; + static constexpr typename kel::lbm::native_data_type::type inv_cs2 = 3.0; + static constexpr typename kel::lbm::native_data_type::type cs2 = 1./3.; }; } } diff --git a/modules/core/c++/descriptor/d3q27.hpp b/modules/core/c++/descriptor/d3q27.hpp index 7b3c84f..9358852 100644 --- a/modules/core/c++/descriptor/d3q27.hpp +++ b/modules/core/c++/descriptor/d3q27.hpp @@ -47,7 +47,7 @@ public: { 1, 1, 1} // 26 }}; - static constexpr std::array::type,Q> weights = { + static constexpr std::array::type,Q> weights = { 8./27., // 1D 1./36., @@ -86,8 +86,8 @@ public: 18,20,19,24,26,25,21,23,22,9,11,10,15,17,16,12,14,13 }; - static constexpr typename saw::native_data_type::type inv_cs2 = 3.0; - static constexpr typename saw::native_data_type::type cs2 = 1./3.; + static constexpr typename kel::lbm::native_data_type::type inv_cs2 = 3.0; + static constexpr typename kel::lbm::native_data_type::type cs2 = 1./3.; }; } } diff --git a/modules/core/c++/environment.hpp b/modules/core/c++/environment.hpp index 51092d5..0e2f6b9 100644 --- a/modules/core/c++/environment.hpp +++ b/modules/core/c++/environment.hpp @@ -1,6 +1,6 @@ #pragma once -#include +#include "abstract/error.hpp" #include #include @@ -18,7 +18,7 @@ public: }; template -saw::error_or init_lbm_env(const saw::data& args){ +kel::lbm::error_or init_lbm_env(const kel::lbm::data& args){ namespace fs = std::filesystem; auto& args_n = args.template get<"args">(); @@ -26,7 +26,7 @@ saw::error_or init_lbm_env(const saw::data& args){ const char* home_dir = std::getenv("HOME"); if(not home_dir){ - return saw::make_error("Couldn't find home dir"); + return kel::lbm::make_error("Couldn't find home dir"); } environment env; @@ -62,12 +62,12 @@ saw::error_or init_lbm_env(const saw::data& args){ * Located outside the project dir because dispatching build jobs with output data in the git directory * also copies simulated data which takes a long time. */ -saw::error_or output_directory(){ +kel::lbm::error_or output_directory(){ namespace fs = std::filesystem; const char* home_dir = std::getenv("HOME"); if(not home_dir){ - return saw::make_error("Couldn't find home dir"); + return kel::lbm::make_error("Couldn't find home dir"); } auto lbm_dir = std::filesystem::path{home_dir} / ".lbm"; diff --git a/modules/core/c++/equilibrium.hpp b/modules/core/c++/equilibrium.hpp index eb2b043..9c07fd4 100644 --- a/modules/core/c++/equilibrium.hpp +++ b/modules/core/c++/equilibrium.hpp @@ -5,10 +5,10 @@ namespace kel { namespace lbm { template -saw::data> equilibrium(saw::data> rho, saw::data> vel){ +kel::lbm::data> equilibrium(kel::lbm::data> rho, kel::lbm::data> vel){ using dfi = df_info; - saw::data> eq; + kel::lbm::data> eq; // Brain broken, here's an owl // ^ // 0.0 @@ -16,7 +16,7 @@ saw::data> equilibrium(saw::data_2 - saw::data vel_vel{0.0}; + kel::lbm::data vel_vel{0.0}; for(uint64_t j = 0u; j < Descriptor::D; ++j){ vel_vel = vel_vel + vel.at({{j}}) * vel.at({{j}}); } @@ -25,13 +25,13 @@ saw::data> equilibrium(saw::data vel_c{}; + kel::lbm::data vel_c{}; for(uint64_t j = 0u; j < Descriptor::D; ++j){ // _2 - vel_c = vel_c + (vel.at({{j}}) * saw::data{static_cast::type>(dfi::directions[i][j])}); + vel_c = vel_c + (vel.at({{j}}) * kel::lbm::data{static_cast::type>(dfi::directions[i][j])}); } - auto vel_c_cs2 = vel_c * saw::data{dfi::inv_cs2}; + auto vel_c_cs2 = vel_c * kel::lbm::data{dfi::inv_cs2}; eq.at(i).set( dfi::weights[i] * rho.at({}).get() * diff --git a/modules/core/c++/flatten.hpp b/modules/core/c++/flatten.hpp index 1609589..14d2e33 100644 --- a/modules/core/c++/flatten.hpp +++ b/modules/core/c++/flatten.hpp @@ -1,19 +1,18 @@ #pragma once -#include -#include +#include "abstract/error.hpp" +#include "abstract/data.hpp" namespace kel { namespace lbm { namespace sch { -using namespace saw::schema; } template struct flatten_index { public: template - static constexpr saw::data stride(const saw::data>& meta) { + static constexpr kel::lbm::data stride(const kel::lbm::data>& meta) { if constexpr (i > 0u){ return stride(meta) * meta.at({i-1u}); } @@ -25,15 +24,15 @@ private: /// i + j * 2 + k * 3*2 /// 1 + 2 * 2 + 3 * 3*2 = 1+4+18 = 23 template - static void apply_i(saw::data& flat_ind, const saw::data>& index, const saw::data>& meta){ + static void apply_i(kel::lbm::data& flat_ind, const kel::lbm::data>& index, const kel::lbm::data>& meta){ if constexpr ( D > i ) { flat_ind = flat_ind + index.at({i}) * stride(meta); apply_i(flat_ind,index,meta); } } public: - static saw::data apply(const saw::data>& index, const saw::data>& meta){ - saw::data flat_ind{0u}; + static kel::lbm::data apply(const kel::lbm::data>& index, const kel::lbm::data>& meta){ + kel::lbm::data flat_ind{0u}; apply_i<0u>(flat_ind, index, meta); return flat_ind; } diff --git a/modules/core/c++/fplbm.hpp b/modules/core/c++/fplbm.hpp index b141cae..6783f12 100644 --- a/modules/core/c++/fplbm.hpp +++ b/modules/core/c++/fplbm.hpp @@ -26,7 +26,7 @@ public: component() = default; template - void apply(const saw::data& field, const saw::data& macros, saw::data> index, saw::data time_step) const { + void apply(const kel::lbm::data& field, const kel::lbm::data& macros, kel::lbm::data> index, kel::lbm::data time_step) const { auto& por_f = macros.template get<"porosity">(); auto& por = por_f.at(index); @@ -57,39 +57,39 @@ public: template class component final { private: - saw::data relaxation_; - saw::data frequency_; + kel::lbm::data relaxation_; + kel::lbm::data frequency_; public: using Component = cmpt::FpLbm; public: - component(typename saw::native_data_type::type relaxation__): + component(typename kel::lbm::native_data_type::type relaxation__): relaxation_{{relaxation__}}, - frequency_{saw::data{1} / relaxation_} + frequency_{kel::lbm::data{1} / relaxation_} {} - component(const saw::data& relaxation__): + component(const kel::lbm::data& relaxation__): relaxation_{relaxation__}, - frequency_{saw::data{1} / relaxation_} + frequency_{kel::lbm::data{1} / relaxation_} {} - component(const saw::data>& relaxation__): + component(const kel::lbm::data>& relaxation__): relaxation_{relaxation__.handle()}, - frequency_{saw::data{typename saw::native_data_type::type(1)} / relaxation_} + frequency_{kel::lbm::data{typename kel::lbm::native_data_type::type(1)} / relaxation_} {} template - void apply(const saw::data& field, const saw::data& macros, saw::data> index, saw::data time_step) const { + void apply(const kel::lbm::data& field, const kel::lbm::data& macros, kel::lbm::data> index, kel::lbm::data time_step) const { bool is_even = ((time_step.get() % 2) == 0); auto& dfs_old_f = (is_even) ? field.template get<"dfs_old">() : field.template get<"dfs">(); auto& dfs = dfs_old_f.at(index); - saw::data> half; + kel::lbm::data> half; half.at({}) = 0.5f; auto& rho_f = macros.template get<"density">(); - saw::data>& rho = rho_f.at(index); + kel::lbm::data>& rho = rho_f.at(index); auto& force_f = macros.template get<"force">(); auto& force = force_f.at(index); @@ -108,23 +108,23 @@ public: auto& por_f = macros.template get<"porosity">(); auto& por = por_f.at(index); - saw::data> dfi_inv_cs2; + kel::lbm::data> dfi_inv_cs2; dfi_inv_cs2.at({}).set(dfi::inv_cs2); for(uint64_t i{0u}; i < Descriptor::Q; ++i){ - saw::data> ci; + kel::lbm::data> ci; for(uint64_t d{0u}; d < Descriptor::D; ++d){ - ci.at({{d}}).set(static_cast::type>(dfi::directions[i][d])); + ci.at({{d}}).set(static_cast::type>(dfi::directions[i][d])); } - auto ci_dot_u = saw::math::dot(ci,vel); + auto ci_dot_u = kel::lbm::math::dot(ci,vel); - saw::data> w; + kel::lbm::data> w; w.at({}).set(dfi::weights[i]); auto term1 = (ci-vel) * dfi_inv_cs2; auto term2 = ci * (ci_dot_u * dfi_inv_cs2 * dfi_inv_cs2); - auto force_projection = saw::math::dot(term1 + term2, force); + auto force_projection = kel::lbm::math::dot(term1 + term2, force); auto F_i = w * force_projection; @@ -132,7 +132,7 @@ public: + frequency_ * (eq.at(i) - dfs.at({i}) ) + F_i.at({}) - * (saw::data{1} - saw::data{0.5f} * frequency_); + * (kel::lbm::data{1} - kel::lbm::data{0.5f} * frequency_); } } }; @@ -142,18 +142,18 @@ class component final { public: using Component = cmpt::FpLbmOneParticle; private: - saw::data> global_force_; + kel::lbm::data> global_force_; public: component(): global_force_{} {} - component(saw::data> global_force__): + component(kel::lbm::data> global_force__): global_force_{global_force__} {} template - void apply(const saw::data& field, const saw::data& macros, const saw::data& pg, saw::data> index, saw::data time_step, saw::data sub_steps) const { - // void apply(saw::data& field, saw::data> index, saw::data time_step){ + void apply(const kel::lbm::data& field, const kel::lbm::data& macros, const kel::lbm::data& pg, kel::lbm::data> index, kel::lbm::data time_step, kel::lbm::data sub_steps) const { + // void apply(kel::lbm::data& field, kel::lbm::data> index, kel::lbm::data time_step){ bool is_even = ((time_step.get() % 2) == 0); //auto& dfs_old_f = (is_even) ? field.template get<"dfs_old">() : field.template get<"dfs">(); @@ -188,23 +188,23 @@ public: } auto& aabb = eo_aabb.get_value(); - saw::data> three; + kel::lbm::data> three; three.at({}).set(3.0f); - saw::data> two; + kel::lbm::data> two; two.at({}).set(2.0f); - saw::data> one; + kel::lbm::data> one; one.at({}) = 1.0f; - saw::data> eps; + kel::lbm::data> eps; eps.at({}) = 1.5f; - saw::data> sss; + kel::lbm::data> sss; sss.at({}) = sub_steps.template cast_to(); auto vel_s = (pirb_pos-pirb_pos_old) * sss; - saw::data> force_p{{}}; + kel::lbm::data> force_p{{}}; //= global_force_; iterator::apply([&](const auto& index_f) -> void { @@ -213,7 +213,7 @@ public: auto& por = por_f.at(index_f); auto& rho = rho_f.at(index_f); - saw::data> rel_dist = saw::math::vectorize_data(index_f).template cast_to() - pirb_pos; + kel::lbm::data> rel_dist = kel::lbm::math::vectorize_data(index_f).template cast_to() - pirb_pos; por = particle_porosity>::calculate(rel_dist,p_rad,eps); auto flip_por = one - por; @@ -232,7 +232,7 @@ public: if(sub_steps.get() > 0u){ auto sss_inv = one / sss; - for(saw::data i{0u}; i < sub_steps; ++i){ + for(kel::lbm::data i{0u}; i < sub_steps; ++i){ verlet_step_lambda(pi,sss_inv); } } diff --git a/modules/core/c++/geometry.hpp b/modules/core/c++/geometry.hpp index 1c5d0a3..dba1ccd 100644 --- a/modules/core/c++/geometry.hpp +++ b/modules/core/c++/geometry.hpp @@ -7,7 +7,7 @@ namespace lbm { /* template struct geometry { - void apply(const saw::data& field, const saw::data>& start, const saw::data>& end, const saw::data& type){ + void apply(const kel::lbm::data& field, const kel::lbm::data>& start, const kel::lbm::data>& end, const kel::lbm::data& type){ } }; diff --git a/modules/core/c++/geometry/poiseulle_channel.hpp b/modules/core/c++/geometry/poiseulle_channel.hpp index f719ec4..d7e8c5d 100644 --- a/modules/core/c++/geometry/poiseulle_channel.hpp +++ b/modules/core/c++/geometry/poiseulle_channel.hpp @@ -13,7 +13,7 @@ class component final { private: public: template - void apply(saw::data& field, const saw::data){ + void apply(kel::lbm::data& field, const kel::lbm::data){ auto& info_f = field.template get<"info">(); } }; diff --git a/modules/core/c++/grid.hpp b/modules/core/c++/grid.hpp index c9a3b05..506f503 100644 --- a/modules/core/c++/grid.hpp +++ b/modules/core/c++/grid.hpp @@ -11,13 +11,13 @@ namespace lbm { template class domain_registry final { private: - saw::data> infos_; + kel::lbm::data> infos_; public: template - saw::data get_template_id() { - static saw::data id{std::numeric_limits::type>::max()}; + kel::lbm::data get_template_id() { + static kel::lbm::data id{std::numeric_limits::type>::max()}; - if( id == std::numeric_limits::type>::max() ){ + if( id == std::numeric_limits::type>::max() ){ auto err_or_id = search_or_register_id(T::name); if(err_or_id.is_error()){ // Unsure about recovery from this @@ -28,7 +28,7 @@ public: }; template -void clean_grid(saw::data& info_field){ +void clean_grid(kel::lbm::data& info_field){ } } } diff --git a/modules/core/c++/hlbm.hpp b/modules/core/c++/hlbm.hpp index fc61f6a..4f22cbc 100644 --- a/modules/core/c++/hlbm.hpp +++ b/modules/core/c++/hlbm.hpp @@ -27,7 +27,7 @@ public: component() = default; template - void apply(const saw::data& field, const saw::data& macros, saw::data> index, saw::data time_step) const { + void apply(const kel::lbm::data& field, const kel::lbm::data& macros, kel::lbm::data> index, kel::lbm::data time_step) const { auto& porosity_f = macros.template get<"porosity">(); auto& particle_N_f = field.template get<"particle_N">(); auto& particle_D_f = field.template get<"particle_D">(); @@ -51,21 +51,21 @@ public: template class component final { private: - typename saw::native_data_type::type relaxation_; - saw::data frequency_; + typename kel::lbm::native_data_type::type relaxation_; + kel::lbm::data frequency_; public: - component(typename saw::native_data_type::type relaxation__): + component(typename kel::lbm::native_data_type::type relaxation__): relaxation_{relaxation__}, - frequency_{typename saw::native_data_type::type(1) / relaxation_} + frequency_{typename kel::lbm::native_data_type::type(1) / relaxation_} {} - component(const saw::data>& relaxation__): + component(const kel::lbm::data>& relaxation__): relaxation_{relaxation__.handle().get()}, - frequency_{typename saw::native_data_type::type(1) / relaxation_} + frequency_{typename kel::lbm::native_data_type::type(1) / relaxation_} {} template - void apply(const saw::data& field, const saw::data& macros, saw::data> index, saw::data time_step) const { + void apply(const kel::lbm::data& field, const kel::lbm::data& macros, kel::lbm::data> index, kel::lbm::data time_step) const { bool is_even = ((time_step.get() % 2) == 0); @@ -77,13 +77,13 @@ public: auto& rho_f = macros.template get<"density">(); auto& vel_f = macros.template get<"momentum">(); - saw::data>& rho = rho_f.at(index); - saw::data>& vel = vel_f.at(index); + kel::lbm::data>& rho = rho_f.at(index); + kel::lbm::data>& vel = vel_f.at(index); compute_rho_u(dfs_old_f.at(index), rho, vel); auto& porosity = porosity_f.at(index); - saw::data> one; + kel::lbm::data> one; one.at({}) = 1.0; auto flip_porosity = one - porosity; @@ -91,7 +91,7 @@ public: auto& D = particle_D_f.at(index); // Convex combination of velocities - vel = vel * porosity + [&]() -> saw::data> { + vel = vel * porosity + [&]() -> kel::lbm::data> { return (D.at({}).get() > 0.0) ? ( N * flip_porosity / D ): N; }(); // Equilibrium @@ -109,7 +109,7 @@ class component final { private: public: template - void apply(const saw::data& field, const saw::data& macros, const saw::data& part_group, saw::data> index, saw::data time_step, saw::data sub_steps) const { + void apply(const kel::lbm::data& field, const kel::lbm::data& macros, const kel::lbm::data& part_group, kel::lbm::data> index, kel::lbm::data time_step, kel::lbm::data sub_steps) const { /// Figure out how to access the particle list // auto& p = particles.at(i); @@ -118,7 +118,7 @@ public: using dfi = df_info; bool is_even = ((time_step.get() % 2) == 0); - saw::data> one; + kel::lbm::data> one; one.at({}) = 1.0; auto& dfs_old_f = (is_even) ? field.template get<"dfs_old">() : field.template get<"dfs">(); @@ -139,15 +139,15 @@ public: auto& pi = parts.at(index); auto& pirb = pi.template get<"rigid_body">(); - saw::data>& pirb_pos = pirb.template get<"position">(); + kel::lbm::data>& pirb_pos = pirb.template get<"position">(); auto& pirb_pos_old = pirb.template get<"position_old">(); // TODO !!!! Divide by actual time step - for now it's ok - saw::data> ts; + kel::lbm::data> ts; ts.at({}) = one.at({}) / sub_steps.template cast_to(); - saw::data> start; - saw::data> stop; + kel::lbm::data> start; + kel::lbm::data> stop; auto eo_aabb = particle_aabb::calculate(part_spheroid_group,{{0u}},mvel_f.meta()); if(eo_aabb.is_error()){ @@ -159,7 +159,7 @@ public: start = aabb.template get<"a">(); stop = aabb.template get<"b">(); - saw::data> force_p; + kel::lbm::data> force_p; for(uint64_t i{0u}; i < Desc::D; ++i){ force_p.at({{i}}) = 0.0; } @@ -167,8 +167,8 @@ public: iterator::apply([&](const auto& index_f) -> void{ auto& dfs = dfs_old_f.at(index_f); - saw::data> rel_dist = saw::math::vectorize_data(index_f).template cast_to() - pirb_pos; - saw::data> eps; + kel::lbm::data> rel_dist = kel::lbm::math::vectorize_data(index_f).template cast_to() - pirb_pos; + kel::lbm::data> eps; eps.at({}) = 1.5f; auto& mpor = mpor_f.at(index_f); @@ -178,14 +178,14 @@ public: return; } - saw::data> momentum; + kel::lbm::data> momentum; for(uint64_t i{0u}; i < Desc::D; ++i){ momentum.at({{i}}) = 0.0; } for(uint64_t i{0u}; i < Desc::Q; ++i){ - saw::data> e_i; - saw::data> n_ind_i; + kel::lbm::data> e_i; + kel::lbm::data> n_ind_i; for(uint64_t k{0u}; k < Desc::D; ++k){ e_i.at({{k}}) = (dfi::directions[i])[k]; n_ind_i.at({k}) = index_f.at({k}) + (dfi::directions[i])[k]; @@ -193,10 +193,10 @@ public: uint64_t i_opp = dfi::opposite_index[i]; - auto u_p_e = saw::math::dot(e_i,vel_p_old); + auto u_p_e = kel::lbm::math::dot(e_i,vel_p_old); - saw::data dfs_added = dfs.at({i})*(saw::data{1}-u_p_e.at({})) + dfs_old_f.at(n_ind_i).at({i_opp})*(saw::data{1}+u_p_e.at({})); - saw::data> dfs_added_v; + kel::lbm::data dfs_added = dfs.at({i})*(kel::lbm::data{1}-u_p_e.at({})) + dfs_old_f.at(n_ind_i).at({i_opp})*(kel::lbm::data{1}+u_p_e.at({})); + kel::lbm::data> dfs_added_v; dfs_added_v.at({}) = dfs_added; auto ei_dfs = e_i * dfs_added_v; @@ -214,7 +214,7 @@ public: auto& pirb_acc = pirb.template get<"acceleration">(); pirb_acc = - force_p / part_spheroid_group.template get<"total_mass">().at({}); - for(saw::data i{0u}; i < sub_steps; ++i){ + for(kel::lbm::data i{0u}; i < sub_steps; ++i){ verlet_step_lambda(pi,ts); } auto vel_p = (pirb_pos-pirb_pos_old) / ts; diff --git a/modules/core/c++/index.hpp b/modules/core/c++/index.hpp index 00e597e..6fd6802 100644 --- a/modules/core/c++/index.hpp +++ b/modules/core/c++/index.hpp @@ -6,10 +6,10 @@ namespace kel { namespace lbm { template -saw::data> lower_index_from_pos(const saw::data>& pos){ - saw::data> ind; +kel::lbm::data> lower_index_from_pos(const kel::lbm::data>& pos){ + kel::lbm::data> ind; - for(saw::data i{0u}; i < ind.size(); ++i){ + for(kel::lbm::data i{0u}; i < ind.size(); ++i){ ind.at(i).set(std::max(pos.at(i).template cast_to().get(),0)); } @@ -17,10 +17,10 @@ saw::data> lower_index_from_pos(const saw::data -saw::data> upper_index_from_pos(const saw::data>& pos){ +kel::lbm::data> upper_index_from_pos(const kel::lbm::data>& pos){ auto ind = lower_index_from_pos(pos); - for(saw::data i{0u}; i < ind.size(); ++i){ + for(kel::lbm::data i{0u}; i < ind.size(); ++i){ ++ind.at(i); } return ind; diff --git a/modules/core/c++/iterator.hpp b/modules/core/c++/iterator.hpp index 7fd6f58..e786446 100644 --- a/modules/core/c++/iterator.hpp +++ b/modules/core/c++/iterator.hpp @@ -5,10 +5,10 @@ namespace kel { namespace lbm { template -void iterate_over(Func&& func, const saw::data>& start, const saw::data>& end, const saw::data>& dist = {{{0u,0u}}}){ +void iterate_over(Func&& func, const kel::lbm::data>& start, const kel::lbm::data>& end, const kel::lbm::data>& dist = {{{0u,0u}}}){ // static_assert(D == 2u, "Currently a lazy implementation for AND combinations of intervalls."); - for(saw::data i{start.at({0u}) + dist.at({0u})}; (i+dist.at({0u})) < end.at({0u}); ++i){ - for(saw::data j{start.at({1u}) + dist.at({1u})}; (j+dist.at({1u})) < end.at({1u}); ++j){ + for(kel::lbm::data i{start.at({0u}) + dist.at({0u})}; (i+dist.at({0u})) < end.at({0u}); ++i){ + for(kel::lbm::data j{start.at({1u}) + dist.at({1u})}; (j+dist.at({1u})) < end.at({1u}); ++j){ func({{i,j}}); } } @@ -23,10 +23,10 @@ struct iterator { private: template static void iterate_over_i(Func& func, - const saw::data>& start, - const saw::data>& end, - const saw::data>& dist, - saw::data>& iter + const kel::lbm::data>& start, + const kel::lbm::data>& end, + const kel::lbm::data>& dist, + kel::lbm::data>& iter ){ static_assert(i <= D, "Eh. Too tired to think of a good message"); if constexpr ( i == D ){ @@ -41,11 +41,11 @@ public: template static void apply( Func&& func, - const saw::data>& start, - const saw::data>& end, - const saw::data>& dist = {} + const kel::lbm::data>& start, + const kel::lbm::data>& end, + const kel::lbm::data>& dist = {} ){ - saw::data> iter; + kel::lbm::data> iter; iterate_over_i<0u,Func>(func, start, end, dist, iter); } }; @@ -57,9 +57,9 @@ template struct ct_tuple_iterator> final { private: template - static constexpr saw::error_or apply_i( + static constexpr kel::lbm::error_or apply_i( Func& func, - saw::data>& tup + kel::lbm::data>& tup ){ if constexpr ( i < sizeof...(Tup) ){ auto eov = func(tup.template get()); @@ -69,13 +69,13 @@ private: return apply_i(func,tup); } - return saw::make_void(); + return kel::lbm::make_void(); } public: template - static constexpr saw::error_or apply( + static constexpr kel::lbm::error_or apply( Func&& func, - saw::data>& tup + kel::lbm::data>& tup ){ return apply_i(func,tup); } @@ -83,11 +83,11 @@ public: /* Ambiguous template -void iterate_over(Func&& func, const saw::data>& start, const saw::data>& end, const saw::data>& dist = {{{0u,0u,0u}}}){ +void iterate_over(Func&& func, const kel::lbm::data>& start, const kel::lbm::data>& end, const kel::lbm::data>& dist = {{{0u,0u,0u}}}){ // static_assert(D == 2u, "Currently a lazy implementation for AND combinations of intervalls."); - for(saw::data i{start.at({0u}) + dist.at({0u})}; (i+dist.at({0u})) < end.at({0u}); ++i){ - for(saw::data j{start.at({1u}) + dist.at({1u})}; (j+dist.at({1u})) < end.at({1u}); ++j){ - for(saw::data k{start.at({2u}) + dist.at({2u})}; (j+dist.at({2u})) < end.at({2u}); ++j){ + for(kel::lbm::data i{start.at({0u}) + dist.at({0u})}; (i+dist.at({0u})) < end.at({0u}); ++i){ + for(kel::lbm::data j{start.at({1u}) + dist.at({1u})}; (j+dist.at({1u})) < end.at({1u}); ++j){ + for(kel::lbm::data k{start.at({2u}) + dist.at({2u})}; (j+dist.at({2u})) < end.at({2u}); ++j){ func({{k,j,i}}); } } diff --git a/modules/core/c++/lbm.hpp b/modules/core/c++/lbm.hpp index 4e73537..8c48e54 100644 --- a/modules/core/c++/lbm.hpp +++ b/modules/core/c++/lbm.hpp @@ -18,6 +18,7 @@ #include "momentum_gather.hpp" #include "memory.hpp" #include "psm.hpp" +#include "component/psm.hpp" #include "stream.hpp" #include "write_csv.hpp" #include "write_vtk.hpp" @@ -25,7 +26,7 @@ #include "math/math.hpp" -#include +#include "abstract/unit_print.hpp" #include namespace kel { @@ -33,15 +34,15 @@ namespace lbm { template void print_lbm_meta( const converter& conv, - const saw::data>& kin_vis_si, - const saw::data>& char_vel, - const saw::data>& char_len + const kel::lbm::data>& kin_vis_si, + const kel::lbm::data>& char_vel, + const kel::lbm::data>& char_len ){ std::cout <<"[Meta]\n" <<"======\n" <<"Re: "<<(char_vel * char_len / kin_vis_si)<<"\n" - <<"Ma: "<<(char_vel * saw::data, sch::SiVelocity>::Schema>{std::sqrt(df_info::inv_cs2)})<<"\n" + <<"Ma: "<<(char_vel * kel::lbm::data, sch::SiVelocity>::Schema>{std::sqrt(df_info::inv_cs2)})<<"\n" <<"\n" <<"[SI]\n" <<"====\n" @@ -56,7 +57,7 @@ void print_lbm_meta( <<"[LBM]\n" <<"=====\n" <<"KinVis: "<, sch::LbmKinematicViscosity>::Schema >{df_info::inv_cs2} * conv.kinematic_viscosity_si_to_lbm(kin_vis_si) + saw::data>{0.5})<<"\n" + <<"Ï„: "<<(kel::lbm::data, sch::LbmKinematicViscosity>::Schema >{df_info::inv_cs2} * conv.kinematic_viscosity_si_to_lbm(kin_vis_si) + kel::lbm::data>{0.5})<<"\n" < +#include "abstract/unit.hpp" #include @@ -34,7 +34,6 @@ struct second { } namespace sch { -using namespace saw::schema; template using SiMeter = Unit>; diff --git a/modules/core/c++/macroscopic.hpp b/modules/core/c++/macroscopic.hpp index 9db1538..bd72503 100644 --- a/modules/core/c++/macroscopic.hpp +++ b/modules/core/c++/macroscopic.hpp @@ -9,9 +9,9 @@ namespace lbm { */ template void compute_rho_u ( - const saw::data>& dfs, - saw::ref>> rho, - saw::ref>> vel + const kel::lbm::data>& dfs, + kel::lbm::ref>> rho, + kel::lbm::ref>> vel ) { using dfi = df_info; @@ -24,7 +24,7 @@ void compute_rho_u ( for(size_t j = 0; j < Desc::Q; ++j){ rho().at({}) = rho().at({}) + dfs.at({j}); for(size_t i = 0; i < Desc::D; ++i){ - vel().at({{i}}) = vel().at({{i}}) + saw::data{static_cast::type>(dfi::directions[j][i])} * dfs.at({j}); + vel().at({{i}}) = vel().at({{i}}) + kel::lbm::data{static_cast::type>(dfi::directions[j][i])} * dfs.at({j}); } } @@ -39,9 +39,9 @@ void compute_rho_u ( */ template void compute_rho_momentum ( - const saw::data>& dfs, - saw::ref>> rho, - saw::ref>> mom + const kel::lbm::data>& dfs, + kel::lbm::ref>> rho, + kel::lbm::ref>> mom ) { using dfi = df_info; @@ -54,7 +54,7 @@ void compute_rho_momentum ( for(size_t j = 0; j < Desc::Q; ++j){ rho().at({}) = rho().at({}) + dfs.at({j}); for(size_t i = 0; i < Desc::D; ++i){ - mom().at({{i}}) = mom().at({{i}}) + saw::data{static_cast::type>(dfi::directions[j][i])} * dfs.at({j}); + mom().at({{i}}) = mom().at({{i}}) + kel::lbm::data{static_cast::type>(dfi::directions[j][i])} * dfs.at({j}); } } } diff --git a/modules/core/c++/math/n_closest.hpp b/modules/core/c++/math/n_closest.hpp index ac0fe2f..7ce7c97 100644 --- a/modules/core/c++/math/n_closest.hpp +++ b/modules/core/c++/math/n_closest.hpp @@ -7,18 +7,18 @@ namespace kel { namespace lbm { template -saw::data n_closest_read(const saw::data,Encode>& f, const saw::data>& frac_ind){ +kel::lbm::data n_closest_read(const kel::lbm::data,Encode>& f, const kel::lbm::data>& frac_ind){ auto shift_frac_ind = frac_ind; for(uint64_t i{0u}; i < D; ++i){ - shift_frac_ind.at({{i}}) = shift_frac_ind.at({{i}}) + saw::data{0.5}; + shift_frac_ind.at({{i}}) = shift_frac_ind.at({{i}}) + kel::lbm::data{0.5}; if(shift_frac_ind.at({{i}}).get() < 0){ shift_frac_ind.at({{i}}) = {}; } } - saw::data> shift_ind; + kel::lbm::data> shift_ind; for(uint64_t i{0u}; i < D; ++i){ shift_ind.at({i}) = frac_ind.at({{i}}).template cast_to(); } @@ -27,18 +27,18 @@ saw::data n_closest_read(const saw::dat } template -void n_closest_add(const saw::data,Encode>& f, const saw::data>& frac_ind, const saw::data& val){ +void n_closest_add(const kel::lbm::data,Encode>& f, const kel::lbm::data>& frac_ind, const kel::lbm::data& val){ auto shift_frac_ind = frac_ind; for(uint64_t i{0u}; i < D; ++i){ - shift_frac_ind.at({{i}}) = shift_frac_ind.at({{i}}) + saw::data{0.5}; + shift_frac_ind.at({{i}}) = shift_frac_ind.at({{i}}) + kel::lbm::data{0.5}; if(shift_frac_ind.at({{i}}).get() < 0){ shift_frac_ind.at({{i}}) = {}; } } auto f_meta = f.meta(); - saw::data> shift_ind; + kel::lbm::data> shift_ind; for(uint64_t i{0u}; i < D; ++i){ shift_ind.at({i}) = frac_ind.at({{i}}).template cast_to(); if(shift_ind.at({i}) < f_meta.at({i})){ diff --git a/modules/core/c++/math/n_linear.hpp b/modules/core/c++/math/n_linear.hpp index b378440..81070c3 100644 --- a/modules/core/c++/math/n_linear.hpp +++ b/modules/core/c++/math/n_linear.hpp @@ -9,15 +9,15 @@ namespace impl { template struct n_linear_interpolate_helper final { template - auto apply(const saw::data& field, const saw::data>& pos){ + auto apply(const kel::lbm::data& field, const kel::lbm::data>& pos){ return pos; } }; } template -saw::data,sch::Vector>> position_to_index_and_fraction(const saw::data>& pos){ - saw::data,sch::Vector>> sep; +kel::lbm::data,sch::Vector>> position_to_index_and_fraction(const kel::lbm::data>& pos){ + kel::lbm::data,sch::Vector>> sep; auto& ind = sep.template get<0u>(); auto& frac = sep.template get<1u>(); @@ -25,7 +25,7 @@ saw::data,sch::Vector>> position_to_i auto pos_cpy = pos; // Guarantee that the pos is at least 0 for(uint64_t i = 0u; i < D; ++i){ - pos_cpy.at({{i}}).set(std::max(pos.at({{i}}).get(), static_cast::type>(0))); + pos_cpy.at({{i}}).set(std::max(pos.at({{i}}).get(), static_cast::type>(0))); } // Now we can cast to uint64_t @@ -39,14 +39,14 @@ saw::data,sch::Vector>> position_to_i } template -auto floor_index_from_position(const saw::data>& pos){ +auto floor_index_from_position(const kel::lbm::data>& pos){ return position_to_index_and_fraction(pos).template get<0u>(); } template -saw::data,sch::Vector>> position_to_index_and_fraction_bounded( - const saw::data>& pos, - const saw::data>& bound) +kel::lbm::data,sch::Vector>> position_to_index_and_fraction_bounded( + const kel::lbm::data>& pos, + const kel::lbm::data>& bound) { auto infr = position_to_index_and_fraction(pos); auto& ind = infr.template get<0u>(); @@ -64,7 +64,7 @@ saw::data,sch::Vector>> position_to_i template auto n_linear_interpolate( - const saw::data& field, const saw::data>& pos){ + const kel::lbm::data& field, const kel::lbm::data>& pos){ // Pos auto pos_bound = pos; @@ -73,9 +73,9 @@ auto n_linear_interpolate( auto meta = field.dims(); // Lower Index - saw::data> ind; + kel::lbm::data> ind; - for(saw::data i{0u}; i < saw::data{D}; ++i){ + for(kel::lbm::data i{0u}; i < kel::lbm::data{D}; ++i){ // Native Positive i auto npos_i = pos.at({i}).get(); @@ -91,31 +91,31 @@ auto n_linear_interpolate( // Set index to i ind.at(i).set(nind_i); } - saw::data> pos_frac; - for(saw::data i{0u}; i < saw::data{D}; ++i){ + kel::lbm::data> pos_frac; + for(kel::lbm::data i{0u}; i < kel::lbm::data{D}; ++i){ pos_frac.at({i}) = pos_bound.at({i}) - ind.at(i).template cast_to(); } // Base value - saw::data res; + kel::lbm::data res; // constexpr uint64_t d_corners = 1ul << D; - saw::data> ones_ind; - for(saw::data i{0u}; i < saw::data{D}; ++i){ + kel::lbm::data> ones_ind; + for(kel::lbm::data i{0u}; i < kel::lbm::data{D}; ++i){ ones_ind.at({i}).set(1u); } iterator::apply([&](auto ind){ // Iterates over (0,0,0) to (1,1,1) - saw::data weight{1.0}; + kel::lbm::data weight{1.0}; - for(saw::data d{0u}; d < saw::data{D}; ++d){ + for(kel::lbm::data d{0u}; d < kel::lbm::data{D}; ++d){ - saw::data t = pos_frac.at({d}); + kel::lbm::data t = pos_frac.at({d}); if(ind.at(d).get() == 0u){ - weight = weight * (saw::data{1} - t); + weight = weight * (kel::lbm::data{1} - t); }else{ weight = weight * t; } @@ -128,8 +128,8 @@ auto n_linear_interpolate( } template -saw::data> bilinear_interpolate(const saw::data& field, const saw::data>& pos){ - saw::data> res; +kel::lbm::data> bilinear_interpolate(const kel::lbm::data& field, const kel::lbm::data>& pos){ + kel::lbm::data> res; { } diff --git a/modules/core/c++/math/round.hpp b/modules/core/c++/math/round.hpp index d3a2586..4b586c5 100644 --- a/modules/core/c++/math/round.hpp +++ b/modules/core/c++/math/round.hpp @@ -6,11 +6,11 @@ namespace kel { namespace lbm { template -saw::data> round_to_unsigned(const saw::data>& inp){ - saw::data> rv; +kel::lbm::data> round_to_unsigned(const kel::lbm::data>& inp){ + kel::lbm::data> rv; - auto zero = static_cast::type>(0); - auto half = static_cast::type>(0.5); + auto zero = static_cast::type>(0); + auto half = static_cast::type>(0.5); for(uint64_t i{0u}; i < D; ++i){ auto val = inp.at({{i}}).get()+half; diff --git a/modules/core/c++/memory.hpp b/modules/core/c++/memory.hpp index e97c7fc..dd9b3f6 100644 --- a/modules/core/c++/memory.hpp +++ b/modules/core/c++/memory.hpp @@ -18,12 +18,12 @@ struct memory_size_helper> { template struct memory_size_helper> { - static constexpr uint64_t bytes = saw::ct_multiply::value * memory_size_helper::bytes; + static constexpr uint64_t bytes = kel::lbm::ct_multiply::value * memory_size_helper::bytes; }; template struct memory_size_helper> { - static constexpr uint64_t bytes = saw::ct_multiply::value * memory_size_helper::bytes; + static constexpr uint64_t bytes = kel::lbm::ct_multiply::value * memory_size_helper::bytes; }; template @@ -37,7 +37,7 @@ struct memory_size_helper> { template static constexpr uint64_t apply_i() { if constexpr ( i < sizeof...(Members) ){ - using M_I = typename saw::parameter_pack_type::type; + using M_I = typename kel::lbm::parameter_pack_type::type; return apply_i() + memory_size_helper::bytes; } return 0u; @@ -51,10 +51,10 @@ class memory_estimate_helper final { private: template - static void apply_i(saw::data& bytes){ + static void apply_i(kel::lbm::data& bytes){ if constexpr ( i < sizeof...(T)){ - using T_I = typename saw::parameter_pack_type::type; + using T_I = typename kel::lbm::parameter_pack_type::type; bytes.set(bytes.get() + memory_size_helper::bytes); @@ -64,15 +64,15 @@ private: public: - static void apply(saw::data& bytes){ + static void apply(kel::lbm::data& bytes){ apply_i<0u>(bytes); } }; } template -saw::data memory_estimate(){ - saw::data bytes; +kel::lbm::data memory_estimate(){ + kel::lbm::data bytes; impl::memory_estimate_helper::apply(bytes); diff --git a/modules/core/c++/momentum_gather.hpp b/modules/core/c++/momentum_gather.hpp index 7b1fc96..62157c7 100644 --- a/modules/core/c++/momentum_gather.hpp +++ b/modules/core/c++/momentum_gather.hpp @@ -17,8 +17,8 @@ class component { private: public: template - void apply(const saw::data& field, const saw::data& macros, - saw::data> index, saw::data time_step) const { + void apply(const kel::lbm::data& field, const kel::lbm::data& macros, + kel::lbm::data> index, kel::lbm::data time_step) const { using dfi = df_info; bool is_even = ((time_step.get() % 2) == 0); @@ -40,11 +40,11 @@ public: uint64_t i_opp = dfi::opposite_index[i]; auto dfs_diff = dfs.at({i}) - dfs.at({i_opp}); for(uint64_t k{0u}; k < Descriptor::D; ++k){ - force.at({{k}}) = force.at({{k}}) + dfs_diff * saw::data{dfi::directions[i][k]}; + force.at({{k}}) = force.at({{k}}) + dfs_diff * kel::lbm::data{dfi::directions[i][k]}; } } - saw::data> one; + kel::lbm::data> one; one.at({}) = 1.0; auto flip_porous = one - porous; force = force * flip_porous; diff --git a/modules/core/c++/over/chunk.hpp b/modules/core/c++/over/chunk.hpp index 4c5bc76..e7abde3 100644 --- a/modules/core/c++/over/chunk.hpp +++ b/modules/core/c++/over/chunk.hpp @@ -15,7 +15,8 @@ using OverChunk = Array; } } -namespace saw { +namespace kel { +namespace lbm { template