diff options
| author | Claudius "keldu" Holeksa <mail@keldu.de> | 2026-11-08 22:04:06 +0100 |
|---|---|---|
| committer | Claudius "keldu" Holeksa <mail@keldu.de> | 2026-11-08 22:04:06 +0100 |
| commit | c59aeef2e0c86ec3f0f34ce77c205f3ef0b034cc (patch) | |
| tree | 7e29aea25537b31040c5bb3649749706e54e5706 /modules/core | |
| parent | fa6bc96b28f6654040992b282525b88d5d46aca9 (diff) | |
| download | libs-lbm-c59aeef2e0c86ec3f0f34ce77c205f3ef0b034cc.tar.gz | |
Abstract move. Forstio independence
Diffstat (limited to 'modules/core')
81 files changed, 5555 insertions, 853 deletions
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 <cassert> #include <cstdint> #include <memory> #include <optional> #include <utility> -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 <typename T> struct void_fix { typedef T Type; }; template <> struct void_fix<void> { typedef void_t Type; }; @@ -150,4 +155,5 @@ template <> struct void_unfix<void_t> { typedef void Type; }; template <typename T> using unfix_void = typename void_unfix<T>::Type; template <typename... T> 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 <array> +#include <concepts> +#include <cstdint> +#include <map> +#include <string> +#include <string_view> +#include <tuple> +#include <type_traits> +#include <utility> +#include <variant> +#include <vector> + +#include <cassert> + #include "common.hpp" +#include "encode.hpp" +#include "error.hpp" +#include "schema.hpp" +#include "templates.hpp" namespace kel { namespace lbm { -template<typename Schema, typename Encode = rep::Native> -class data final { - static_assert(always_false<Schema,Encode>, "Invalid schema + encode in data specialization"); + +/** + * Maps a Primitive schema onto the C++ type that actually holds it. + */ +template <class T> struct native_data_type; + +template <> struct native_data_type<sch::Primitive<sch::SignedInteger, 1>> { + using type = int8_t; +}; +template <> struct native_data_type<sch::Primitive<sch::SignedInteger, 2>> { + using type = int16_t; +}; +template <> struct native_data_type<sch::Primitive<sch::SignedInteger, 4>> { + using type = int32_t; +}; +template <> struct native_data_type<sch::Primitive<sch::SignedInteger, 8>> { + using type = int64_t; +}; + +template <> struct native_data_type<sch::Primitive<sch::UnsignedInteger, 1>> { + using type = uint8_t; +}; +template <> struct native_data_type<sch::Primitive<sch::UnsignedInteger, 2>> { + using type = uint16_t; +}; +template <> struct native_data_type<sch::Primitive<sch::UnsignedInteger, 4>> { + using type = uint32_t; +}; +template <> struct native_data_type<sch::Primitive<sch::UnsignedInteger, 8>> { + using type = uint64_t; }; -template<typename T, uint64_t N> -class data<sch::Primitive<T,N>,Encode> final { +template <> struct native_data_type<sch::Primitive<sch::FloatingPoint, 4>> { + using type = float; +}; +template <> struct native_data_type<sch::Primitive<sch::FloatingPoint, 8>> { + using type = double; +}; + +/** + * MixedPrecision reads as its interface type, so that is what a caller sees. + */ +template <typename S, typename I> +struct native_data_type<sch::MixedPrecision<S, I>> { + using type = typename native_data_type<I>::type; +}; + +template <typename Schema, typename Encode = KEL_LBM_DEFAULT_DATA_ENCODING> +class data { + static_assert(always_false<Schema, Encode>, + "Invalid schema + encode in data specialization"); +}; + +/** + * The index type used to address a shape of the given rank. + */ +template <uint64_t Rank> +using index_data = data<sch::FixedArray<sch::UInt64, Rank>, enc::Native>; + +template <> class data<sch::Void, enc::Native> final { +public: + using Schema = sch::Void; + using MetaSchema = typename Schema::Meta; + + constexpr data() = default; +}; + +template <> class data<sch::Bool, enc::Native> final { public: - using Schema = sch::Primitive<T,N>; - using Encode = Encode; + using Schema = sch::Bool; + using MetaSchema = typename Schema::Meta; + private: - native_data_type<Schema>::type value_; + bool value_; + public: - data(): - value_{} - {} + constexpr data() : value_{false} {} + constexpr data(data<MetaSchema, enc::Native>) : 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 <typename Enc = enc::Native> + constexpr bool equals(const data<Schema, Enc> &rhs) const { + return get() == rhs.get(); + } + + template <typename Enc> + constexpr bool operator==(const data<Schema, Enc> &rhs) const { + return equals(rhs); + } - data(native_data_type<Schema>::type value__): - value_{value__} + template <typename Enc> + constexpr bool operator!=(const data<Schema, Enc> &rhs) const { + return get() != rhs.get(); + } + + constexpr data<Schema, enc::Native> operator!() const { return {!get()}; } + + template <typename Enc> + constexpr data<Schema, enc::Native> + operator&&(const data<Schema, Enc> &rhs) const { + return {get() && rhs.get()}; + } + + template <typename Enc> + constexpr data<Schema, enc::Native> + operator||(const data<Schema, Enc> &rhs) const { + return {get() || rhs.get()}; + } + + template <typename Target> + constexpr data<Target, enc::Native> cast_to() const { + return {static_cast<typename native_data_type<Target>::type>(value_)}; + } +}; + +template <typename T, uint64_t N> +class data<sch::Primitive<T, N>, enc::Native> final { +public: + using Schema = sch::Primitive<T, N>; + using MetaSchema = typename Schema::Meta; + using NativeType = typename native_data_type<Schema>::type; + +private: + NativeType value_; + +public: + constexpr data() : value_{} {} + constexpr data(data<MetaSchema, enc::Native>) : 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<Schema, enc::Native> + operator*(const data<Schema, enc::Native> &rhs) const { + return {static_cast<NativeType>(get() * rhs.get())}; + } + + constexpr data<Schema, enc::Native> + operator/(const data<Schema, enc::Native> &rhs) const { + return {static_cast<NativeType>(get() / rhs.get())}; + } + + constexpr data<Schema, enc::Native> + operator+(const data<Schema, enc::Native> &rhs) const { + return {static_cast<NativeType>(get() + rhs.get())}; + } + + constexpr data<Schema, enc::Native> + operator-(const data<Schema, enc::Native> &rhs) const { + return {static_cast<NativeType>(get() - rhs.get())}; + } + + constexpr data<Schema, enc::Native> operator-() const { + return {static_cast<NativeType>(-get())}; + } + + constexpr data<Schema, enc::Native> & + operator+=(const data<Schema, enc::Native> &rhs) { + value_ = static_cast<NativeType>(value_ + rhs.get()); + return *this; + } + + constexpr data<Schema, enc::Native> & + operator-=(const data<Schema, enc::Native> &rhs) { + value_ = static_cast<NativeType>(value_ - rhs.get()); + return *this; + } + + constexpr data<Schema, enc::Native> & + operator*=(const data<Schema, enc::Native> &rhs) { + value_ = static_cast<NativeType>(value_ * rhs.get()); + return *this; + } + + constexpr data<Schema, enc::Native> & + operator/=(const data<Schema, enc::Native> &rhs) { + value_ = static_cast<NativeType>(value_ / rhs.get()); + return *this; + } + + constexpr data<Schema, enc::Native> &operator++() { + set(static_cast<NativeType>(get() + static_cast<NativeType>(1))); + return *this; + } + + template <typename Enc = enc::Native> + constexpr bool equals(const data<Schema, Enc> &rhs) const { + return get() == rhs.get(); + } + + template <typename Enc> + constexpr bool operator==(const data<Schema, Enc> &rhs) const { + return equals(rhs); + } + + template <typename Enc> + constexpr bool operator!=(const data<Schema, Enc> &rhs) const { + return get() != rhs.get(); + } + + template <typename Enc> + constexpr bool operator<(const data<Schema, Enc> &rhs) const { + return get() < rhs.get(); + } + + template <typename Enc> + constexpr bool operator>(const data<Schema, Enc> &rhs) const { + return get() > rhs.get(); + } + + template <typename Enc> + constexpr bool operator<=(const data<Schema, Enc> &rhs) const { + return get() <= rhs.get(); + } + + template <typename Enc> + constexpr bool operator>=(const data<Schema, Enc> &rhs) const { + return get() >= rhs.get(); + } + + template <typename Target> + constexpr data<Target, enc::Native> cast_to() const { + return {static_cast<typename native_data_type<Target>::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 <typename StorageT, typename InterfaceT> +class data<sch::MixedPrecision<StorageT, InterfaceT>, enc::Native> final { +public: + using Schema = sch::MixedPrecision<StorageT, InterfaceT>; + using MetaSchema = typename Schema::Meta; + using StorageType = StorageT; + using InterfaceType = InterfaceT; + using NativeType = typename native_data_type<InterfaceT>::type; + +private: + data<StorageT, enc::Native> value_; + + static constexpr typename native_data_type<StorageT>::type + narrow(NativeType val) { + return static_cast<typename native_data_type<StorageT>::type>(val); + } + +public: + constexpr data() : value_{} {} + constexpr data(data<MetaSchema, enc::Native>) : value_{} {} + + KEL_DEFAULT_COPY(data); + KEL_DEFAULT_MOVE(data); + + constexpr data(NativeType val__) : value_{narrow(val__)} {} + + constexpr data(const data<InterfaceT, enc::Native> &val) + : value_{val.template cast_to<StorageT>()} {} + + constexpr NativeType get() const { + return value_.template cast_to<InterfaceT>().get(); + } + + constexpr void set(NativeType val) { value_.set(narrow(val)); } + + constexpr data<Schema, enc::Native> + operator*(const data<Schema, enc::Native> &rhs) const { + return {static_cast<NativeType>(get() * rhs.get())}; + } + + constexpr data<Schema, enc::Native> + operator/(const data<Schema, enc::Native> &rhs) const { + return {static_cast<NativeType>(get() / rhs.get())}; + } + + constexpr data<Schema, enc::Native> + operator+(const data<Schema, enc::Native> &rhs) const { + return {static_cast<NativeType>(get() + rhs.get())}; + } + + constexpr data<Schema, enc::Native> + operator-(const data<Schema, enc::Native> &rhs) const { + return {static_cast<NativeType>(get() - rhs.get())}; + } + + constexpr data<Schema, enc::Native> operator-() const { + return {static_cast<NativeType>(-get())}; + } + + constexpr data<Schema, enc::Native> & + operator+=(const data<Schema, enc::Native> &rhs) { + set(static_cast<NativeType>(get() + rhs.get())); + return *this; + } + + constexpr data<Schema, enc::Native> & + operator-=(const data<Schema, enc::Native> &rhs) { + set(static_cast<NativeType>(get() - rhs.get())); + return *this; + } + + constexpr data<Schema, enc::Native> & + operator*=(const data<Schema, enc::Native> &rhs) { + set(static_cast<NativeType>(get() * rhs.get())); + return *this; + } + + constexpr data<Schema, enc::Native> & + operator/=(const data<Schema, enc::Native> &rhs) { + set(static_cast<NativeType>(get() / rhs.get())); + return *this; + } + + template <typename Enc> + constexpr bool operator==(const data<Schema, Enc> &rhs) const { + return get() == rhs.get(); + } + + template <typename Enc> + constexpr bool operator!=(const data<Schema, Enc> &rhs) const { + return get() != rhs.get(); + } + + template <typename Enc> + constexpr bool operator<(const data<Schema, Enc> &rhs) const { + return get() < rhs.get(); + } + + template <typename Enc> + constexpr bool operator>(const data<Schema, Enc> &rhs) const { + return get() > rhs.get(); + } + + template <typename Target> + constexpr data<Target, enc::Native> cast_to() const { + return {static_cast<typename native_data_type<Target>::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 <typename T, uint64_t... D> +class data<sch::FixedArray<T, D...>, enc::Native> final { +public: + using Schema = sch::FixedArray<T, D...>; + using MetaSchema = typename Schema::Meta; + using Inner = data<T, enc::Native>; + + static constexpr uint64_t Rank = sizeof...(D); + static constexpr uint64_t FlatSize = ct_multiply<uint64_t, D...>::value; + +private: + using ArrayT = std::array<Inner, FlatSize>; + ArrayT value_; + + static constexpr std::array<uint64_t, Rank> dims_{D...}; + + constexpr uint64_t get_flat_index(const index_data<Rank> &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<MetaSchema, enc::Native>) + requires(not std::is_same_v<MetaSchema, Schema>) {} - 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<FixedArray<UInt64,3>>{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<UInt64> overload. + * Offering both spellings as overloads instead makes at({{i}}) ambiguous, + * since a one element list converts equally well to either. + */ + template <typename... Args> + requires(sizeof...(Args) == FlatSize) && + (sizeof...(Args) > 1u || + (!std::same_as<std::remove_cvref_t<Args>, data> && ...)) && + (!std::same_as<std::remove_cvref_t<Args>, + data<MetaSchema, enc::Native>> && + ...) && + (std::constructible_from<Inner, Args> && ...) + constexpr data(Args &&...args) + : value_{Inner{std::forward<Args>(args)}...} {} + + KEL_DEFAULT_COPY(data); + KEL_DEFAULT_MOVE(data); + + constexpr Inner &at(const index_data<Rank> &i) { + return value_.at(this->get_flat_index(i)); } - void set(native_data_type value__){ - value_ = value__; + constexpr const Inner &at(const index_data<Rank> &i) const { + return value_.at(this->get_flat_index(i)); } - constexpr bool operator==(const data<Schema,Encode>& rhs) const { - return value_ == rhs.value_; + constexpr Inner &operator()(const index_data<Rank> &i) { + return value_.at(this->get_flat_index(i)); } - - constexpr bool operator!=(const data<Schema,Encode>& rhs) const { - return value_ != rhs.value_; + + constexpr const Inner &operator()(const index_data<Rank> &i) const { + return value_.at(this->get_flat_index(i)); } - - constexpr bool operator>(const data<Schema,Encode>& 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 <uint64_t i> static constexpr uint64_t get_dim_size() { + static_assert(i < Rank, "Dimension index is too large for this shape"); + return parameter_pack_value<i, uint64_t, D...>::value; + } + + static constexpr uint64_t get_dim_size(uint64_t i) { return dims_.at(i); } + + static constexpr index_data<Rank> get_dims() { return {D...}; } + + static constexpr data<sch::UInt64, enc::Native> flat_dims() { + return {FlatSize}; + } + + static constexpr data<sch::UInt64, enc::Native> 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 <typename Enc> + constexpr bool operator==(const data<Schema, Enc> &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 <typename T, uint64_t Dim> +class data<sch::Array<T, Dim>, enc::Native> final { +public: + using Schema = sch::Array<T, Dim>; + using MetaSchema = typename Schema::Meta; + using Inner = data<T, enc::Native>; + + static constexpr uint64_t Rank = Dim; + +private: + index_data<Dim> dims_; + std::vector<Inner> 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<Dim> &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<MetaSchema, enc::Native> &init__) + : dims_{init__}, value_{} { + value_.resize(get_full_size()); + } + + template <std::integral... Dims> + requires(sizeof...(Dims) == Dim) + data(Dims... size_) + : data{index_data<Dim>{static_cast<uint64_t>(size_)...}} {} + + template <uint64_t i = 0> error_or<void> 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<err::out_of_memory>(); + } + + ++dims_.flat_at(i); + + return make_void(); + } + + Inner &at(const index_data<Dim> &i) { + return value_.at(this->get_flat_index(i)); + } + + const Inner &at(const index_data<Dim> &i) const { + return value_.at(this->get_flat_index(i)); + } + + Inner &operator()(const index_data<Dim> &i) { + return value_.at(this->get_flat_index(i)); + } + + const Inner &operator()(const index_data<Dim> &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 <uint64_t i> + constexpr data<sch::UInt64, enc::Native> 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<sch::UInt64, enc::Native> size() const { + return {value_.size()}; + } + + index_data<Dim> get_dims() const { return dims_; } + + /** + * The metadata of a value is whatever it would take to rebuild its shape. + */ + index_data<Dim> meta() const { return dims_; } + + index_data<Dim> dims() const { return dims_; } + + data<sch::UInt64, enc::Native> 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<sch::String, enc::Native> 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<MetaSchema, enc::Native> init) { value_.resize(init.get()); } + + data(std::string value__) : value_{std::move(value__)} {} + + data(const char *value__) : value_{value__} {} + + data<sch::UInt64, enc::Native> size() const { return {value_.size()}; } + + void set(std::string str) { value_ = std::move(str); } + + char &at(data<sch::UInt64, enc::Native> i) { return value_.at(i.get()); } + + const char &at(data<sch::UInt64, enc::Native> i) const { + return value_.at(i.get()); } - - constexpr bool operator<(const data<Schema,Encode>& rhs) const { - return value_ < rhs.value_; + + char get_at(data<sch::UInt64, enc::Native> i) const { + return value_.at(i.get()); } - - constexpr bool operator>=(const data<Schema,Encode>& rhs) const { - return value_ >= rhs.value_; + + void set_at(data<sch::UInt64, enc::Native> i, char val) { + value_.at(i.get()) = val; } - - constexpr bool operator<=(const data<Schema,Encode>& 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 <typename Enc> + bool operator==(const data<sch::String, Enc> &rhs) const { + return stl_view() == rhs.stl_view(); } - - constexpr bool equals(const data<Schema,Encode>& rhs) const { - return (*this) == rhs; + + template <typename Enc> + bool operator!=(const data<sch::String, Enc> &rhs) const { + return stl_view() != rhs.stl_view(); } - data<Schema,Encode> operator+(const data<Schema,Encode>& rhs) const { - return {value_ + rhs.value_}; + template <typename Enc> + bool operator<(const data<sch::String, Enc> &rhs) const { + return stl_view() < rhs.stl_view(); } - - data<Schema,Encode> operator-(const data<Schema,Encode>& rhs) const { - return {value_ - rhs.value_}; +}; + +template <typename... T> class data<sch::Tuple<T...>, enc::Native> final { +public: + using Schema = sch::Tuple<T...>; + using MetaSchema = typename Schema::Meta; + +private: + std::tuple<data<T, enc::Native>...> value_; + + template <uint64_t i = 0u> struct init_helper { + static void apply(std::tuple<data<T, enc::Native>...> &val, + const data<MetaSchema, enc::Native> &init) { + std::get<i>(val) = {init.template get<i>()}; + + if constexpr ((i + 1u) < sizeof...(T)) { + init_helper<i + 1u>::apply(val, init); + } + } + }; + +public: + data() = default; + + data(const data<MetaSchema, enc::Native> &init) + requires(not std::is_same_v<MetaSchema, Schema>) + { + if constexpr (0u < sizeof...(T)) { + init_helper<0u>::apply(value_, init); + } } - - data<Schema,Encode> operator*(const data<Schema,Encode>& rhs) const { - return {value_ * rhs.value_}; + + KEL_DEFAULT_COPY(data); + KEL_DEFAULT_MOVE(data); + + template <size_t i> + data<typename parameter_pack_type<i, T...>::type, enc::Native> &get() { + return std::get<i>(value_); } - - data<Schema,Encode> operator/(const data<Schema,Encode>& rhs) const { - return {value_ / rhs.value_}; + + template <size_t i> + const data<typename parameter_pack_type<i, T...>::type, enc::Native> & + get() const { + return std::get<i>(value_); } - - data<Schema,Encode>& operator+=(const data<Schema,Encode>& rhs) { - value_ += rhs.value_; - return *this + + static constexpr uint64_t size() { return sizeof...(T); } +}; + +template <typename... T, string_literal... literals> +class data<sch::Struct<sch::Member<T, literals>...>, enc::Native> final { +public: + using Schema = sch::Struct<sch::Member<T, literals>...>; + using MetaSchema = typename Schema::Meta; + +private: + std::tuple<data<T, enc::Native>...> value_; + + template <uint64_t i = 0u> struct init_helper { + static void apply(std::tuple<data<T, enc::Native>...> &val, + const data<MetaSchema, enc::Native> &init) { + std::get<i>(val) = { + init.template get<parameter_key_pack_type<i, literals...>::literal>()}; + + if constexpr ((i + 1u) < sizeof...(T)) { + init_helper<i + 1u>::apply(val, init); + } + } + }; + + template <string_literal literal> + static constexpr size_t index_of = + parameter_key_pack_index<literal, literals...>::value; + +public: + data() = default; + + data(const data<MetaSchema, enc::Native> &init) + requires(not std::is_same_v<MetaSchema, Schema>) + { + if constexpr (0u < sizeof...(T)) { + init_helper<0u>::apply(value_, init); + } } - - data<Schema,Encode>& operator-=(const data<Schema,Encode>& rhs) { - value_ -= rhs.value_; - return *this + + KEL_DEFAULT_COPY(data); + KEL_DEFAULT_MOVE(data); + + template <string_literal literal> + data<typename parameter_pack_type<index_of<literal>, T...>::type, + enc::Native> & + get() { + return std::get<index_of<literal>>(value_); } - - data<Schema,Encode>& operator*=(const data<Schema,Encode>& rhs) { - value_ *= rhs.value_; - return *this + + template <string_literal literal> + const data<typename parameter_pack_type<index_of<literal>, T...>::type, + enc::Native> & + get() const { + return std::get<index_of<literal>>(value_); } - - data<Schema,Encode>& operator/=(const data<Schema,Encode>& rhs) { - value_ /= rhs.value_; - return *this + + template <size_t i> + data<typename parameter_pack_type<i, T...>::type, enc::Native> & + get_at_index() { + return std::get<i>(value_); } - template<typename T> - data<T,Encode> cast_to() const { - data<T,Encode> val{static_cast<typename native_data_type<T>::type>(value_)}; - return val; + template <size_t i> + const data<typename parameter_pack_type<i, T...>::type, enc::Native> & + get_at_index() const { + return std::get<i>(value_); + } + + static constexpr data<sch::UInt64, enc::Native> size() { + return {sizeof...(T)}; + } +}; + +template <typename... T, string_literal... literals> +class data<sch::Union<sch::Member<T, literals>...>, enc::Native> final { +public: + using Schema = sch::Union<sch::Member<T, literals>...>; + using MetaSchema = typename Schema::Meta; + +private: + std::variant<data<T, enc::Native>...> value_; + + template <string_literal literal> + static constexpr size_t index_of = + parameter_key_pack_index<literal, literals...>::value; + +public: + data() = default; + + KEL_DEFAULT_COPY(data); + KEL_DEFAULT_MOVE(data); + + template <string_literal lit> + void set(data<typename parameter_pack_type<index_of<lit>, T...>::type, + enc::Native> + val) { + value_ = std::move(val); + } + + template <string_literal lit> + data<typename parameter_pack_type<index_of<lit>, T...>::type, enc::Native> & + init() { + value_.template emplace<index_of<lit>>(); + return get<lit>(); + } + + template <string_literal lit> bool holds_alternative() const { + return index_of<lit> == value_.index(); + } + + template <string_literal lit> + data<typename parameter_pack_type<index_of<lit>, T...>::type, enc::Native> & + get() { + return std::get<index_of<lit>>(value_); + } + + template <string_literal lit> + const data<typename parameter_pack_type<index_of<lit>, T...>::type, + enc::Native> & + get() const { + return std::get<index_of<lit>>(value_); + } + + constexpr data<sch::UInt64, enc::Native> index() const { + return {value_.index()}; } }; +template <typename Key, typename Value> +class data<sch::Map<Key, Value>, enc::Native> final { +public: + using Schema = sch::Map<Key, Value>; + using MetaSchema = typename Schema::Meta; + +private: + std::map<data<Key, enc::Native>, data<Value, enc::Native>> vals_; + +public: + data() = default; + + KEL_DEFAULT_COPY(data); + KEL_DEFAULT_MOVE(data); + + data(data<MetaSchema, enc::Native>) {} + + error_or<void> emplace(ref<data<Key, enc::Native>> key, + ref<data<Value, enc::Native>> value) { + auto insert = vals_.emplace(std::make_pair(key(), value())); + if (!insert.second) { + return make_error<err::already_exists>(); + } + return make_void(); + } + + error_or<void> erase(ref<data<Key, enc::Native>> key) { + auto erased = vals_.erase(key()); + if (erased == 0u) { + return make_error<err::not_found>(); + } + return make_void(); + } + + error_or<ptr<data<Value, enc::Native>>> find(ref<data<Key, enc::Native>> key) { + auto found = vals_.find(key()); + if (found == vals_.end()) { + return make_error<err::not_found>(); + } + + return ptr<data<Value, enc::Native>>{found->second}; + } + + data<sch::UInt64, enc::Native> 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 <cmath> + +#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 <typename Inner, uint64_t... Dims> +class data<sch::Tensor<Inner, Dims...>, enc::Native> final { +public: + using Schema = sch::Tensor<Inner, Dims...>; + using MetaSchema = typename Schema::Meta; + using InnerData = data<Inner, enc::Native>; + using Storage = data<sch::FixedArray<Inner, Dims...>, enc::Native>; + + static constexpr uint64_t Rank = sizeof...(Dims); + static constexpr uint64_t FlatSize = ct_multiply<uint64_t, Dims...>::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<Tensor<Float64,2u,2u>>{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 <typename... Args> + requires(sizeof...(Args) == FlatSize) && + (sizeof...(Args) > 1u || + (!std::same_as<std::remove_cvref_t<Args>, data> && ...)) && + (!std::same_as<std::remove_cvref_t<Args>, InnerData> && ...) && + (!std::same_as<std::remove_cvref_t<Args>, Storage> && ...) && + (std::constructible_from<InnerData, Args> && ...) + data(Args &&...args) : values_{std::forward<Args>(args)...} {} + + InnerData &at(const index_data<Rank> &index) { return values_.at(index); } + + const InnerData &at(const index_data<Rank> &index) const { + return values_.at(index); + } + + InnerData &operator()(const index_data<Rank> &index) { + return values_.at(index); + } + + const InnerData &operator()(const index_data<Rank> &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<sch::UInt64, enc::Native> size() { + return {FlatSize}; + } + + data<Schema, enc::Native> + operator+(const data<Schema, enc::Native> &rhs) const { + data<Schema, enc::Native> c; + for (uint64_t i = 0; i < FlatSize; ++i) { + c.flat_at(i) = flat_at(i) + rhs.flat_at(i); + } + return c; + } + + data<Schema, enc::Native> + operator-(const data<Schema, enc::Native> &rhs) const { + data<Schema, enc::Native> c; + for (uint64_t i = 0; i < FlatSize; ++i) { + c.flat_at(i) = flat_at(i) - rhs.flat_at(i); + } + return c; + } + + data<Schema, enc::Native> operator-() const { + data<Schema, enc::Native> c; + for (uint64_t i = 0; i < FlatSize; ++i) { + c.flat_at(i) = -flat_at(i); + } + return c; + } + + data<Schema, enc::Native> &operator+=(const data<Schema, enc::Native> &rhs) { + for (uint64_t i = 0; i < FlatSize; ++i) { + flat_at(i) += rhs.flat_at(i); + } + return *this; + } + + data<Schema, enc::Native> &operator-=(const data<Schema, enc::Native> &rhs) { + for (uint64_t i = 0; i < FlatSize; ++i) { + flat_at(i) -= rhs.flat_at(i); + } + return *this; + } + + data<Schema, enc::Native> + operator*(const data<sch::Scalar<Inner>, enc::Native> &scal) const { + data<Schema, enc::Native> c; + for (uint64_t i = 0; i < FlatSize; ++i) { + c.flat_at(i) = flat_at(i) * scal.flat_at(0u); + } + return c; + } + + data<Schema, enc::Native> + operator/(const data<sch::Scalar<Inner>, enc::Native> &scal) const { + data<Schema, enc::Native> c; + for (uint64_t i = 0; i < FlatSize; ++i) { + c.flat_at(i) = flat_at(i) / scal.flat_at(0u); + } + return c; + } + + template <typename Enc> + bool operator==(const data<Schema, Enc> &rhs) const { + for (uint64_t i = 0; i < FlatSize; ++i) { + if (!(flat_at(i) == rhs.flat_at(i))) { + return false; + } + } + return true; + } + + template <typename InnerChange> + data<sch::Tensor<InnerChange, Dims...>, enc::Native> cast_to() const { + data<sch::Tensor<InnerChange, Dims...>, enc::Native> changed; + for (uint64_t i = 0; i < FlatSize; ++i) { + changed.flat_at(i) = flat_at(i).template cast_to<InnerChange>(); + } + 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 <functional> #include <string> #include <string_view> +#include <type_traits> #include <variant> #include <vector> @@ -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<std::string_view, std::string> 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<error_info> infos_; public: - error_registry(); + inline error_registry(); KEL_FORBID_COPY(error_registry); KEL_FORBID_MOVE(error_registry); - error_or<const std::string_view> search_category(const error::code& id) const; + inline error_or<const std::string_view> search_category(const error::code& id) const; - error_or<error::code> search_id(const std::string_view& desc) const; + inline error_or<error::code> search_id(const std::string_view& desc) const; - error_or<error::code> search_or_register_id(const std::string_view& desc, bool is_critical); + inline error_or<error::code> 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<typename T> 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<typename T> error make_error(const std::string_view& generic){ error::code id = impl::get_template_error_id<T>(); @@ -156,6 +158,22 @@ template<typename T> 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<typename T, typename S> +requires std::is_same_v<std::remove_cvref_t<S>, std::string> +error make_error(S&& generic){ + error::code id = impl::get_template_error_id<T>(); + // Keep error, don't use make_error + return error{id, T::is_critical, std::string{std::forward<S>(generic)}}; +} + template<typename T> error make_error(){ error::code id = impl::get_template_error_id<T>(); // 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<T>(generic); + return lbm::make_error<T>(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<T>(); } -} // 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<error::code>(code_)}, is_critical_{is_critical__} {} + +inline error::error(error::code code_, bool is_critical__, const std::string_view &msg) + : + error_code_{static_cast<error::code>(code_)} + , is_critical_{is_critical__}, error_message_{msg}{} + +inline error::error(error::code code_, bool is_critical__, std::string&& msg): + error_code_{static_cast<error::code>(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<decltype(arg)>; + + if constexpr (std::is_same_v<T, std::string>) { + return std::string_view{arg}; + } else if constexpr (std::is_same_v<T, std::string_view>) { + return arg; + } else { + return "Error in class Error. Good luck :)"; + } + }, + error_message_); +} + +inline bool error::failed() const { + return !this->is_type<err::no_error>(); +} + +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<error_registry> reg = nullptr; + if(!reg){ + reg = heap<error_registry>(); + } + + assert(reg); + return *reg; +} +} + +inline error no_error(){ + return make_error<err::no_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<const std::string_view> error_registry::search_category(const error::code& id) const { + if( id >= infos_.size()){ + return make_error<err::not_found>(); + } + + return infos_.at(id).description; +} + +inline error_or<error::code> 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<std::size_t>(infos_.size(), std::numeric_limits<error::code>::max()); + for(i = 0; i < info_max_size; ++i){ + if(infos_.at(i).description == desc){ + break; + } + } + + if(i == info_max_size){ + return make_error<err::not_found>(); + } + + return static_cast<error::code>(i); +} + +inline error_or<error::code> 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<err::not_found>()){ + size_t new_index = infos_.size(); + if(new_index == std::numeric_limits<error::code>::max()){ + return make_error<err::out_of_memory>("Error registry ids are exhausted"); + } + infos_.emplace_back(error_info{desc, is_critical}); + return static_cast<error::code>(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<ErrType>(ErrMsg) + return ::kel::lbm::make_error<ErrType>(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 <typename Func, uint64_t... Dims> struct iterator_in_bounds { +private: + static constexpr uint64_t Rank = sizeof...(Dims); + static constexpr std::array<uint64_t, Rank> dims_{Dims...}; + + template <uint64_t level> + static error_or<void> apply_i(Func &func, index_data<Rank> &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<level, uint64_t, Dims...>::value; + ++coord) { + auto eov = apply_i<level + 1u>(func, index); + if (eov.is_error()) { + return eov; + } + } + return make_void(); + } + } + +public: + static error_or<void> apply(Func &func) { + index_data<Rank> 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 <typename Func> struct iterator_in_bounds<Func> { + static error_or<void> apply(Func &func) { + index_data<0u> index; + return func(index); + } +}; + +} // namespace impl + +template <uint64_t... Dims> struct rank_iterator { + template <typename Func> static error_or<void> in_fixed_bounds(Func &&func) { + return impl::iterator_in_bounds<Func, Dims...>::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 <charconv> +#include <cstdio> +#include <limits> +#include <string> +#include <string_view> + +#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 <typename Schema> class data<Schema, enc::Json> 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<sch::UInt64, enc::Native> size() const { return {value_.size()}; } +}; + +template <typename Encoding> struct codec_config; + +template <> struct codec_config<enc::Json> { + /** + * 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<char> peek() { + skip_whitespace(); + if (at_end()) { + return make_error<err::json_malformed>("Unexpected end of input"); + } + return src_[pos_]; + } + + error_or<void> 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<err::json_malformed>("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<void> enter() { + ++depth_; + if (depth_ > max_depth_) { + return make_error<err::json_too_deep>(); + } + 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<std::string> 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<err::json_malformed>("Unterminated string"); + } + const char c = src_[pos_++]; + if (c == '"') { + return out; + } + if (c != '\\') { + out.push_back(c); + continue; + } + if (at_end()) { + return make_error<err::json_malformed>("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<err::json_malformed>("Unknown escape"); + } + } + } + + /** + * Returns the raw token of a JSON number, leaving the numeric conversion + * to the caller who knows the target type. + */ + error_or<std::string_view> 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<err::json_malformed>("Expected a number"); + } + + return src_.substr(start, pos_ - start); + } + + error_or<bool> 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<err::json_malformed>("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<void> 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<void> 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<uint32_t> parse_hex4() { + if (pos_ + 4u > src_.size()) { + return make_error<err::json_malformed>("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<uint32_t>(h - '0'); + } else if (h >= 'a' && h <= 'f') { + d = static_cast<uint32_t>(h - 'a') + 10u; + } else if (h >= 'A' && h <= 'F') { + d = static_cast<uint32_t>(h - 'A') + 10u; + } else { + return make_error<err::json_malformed>("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<char>(cp)); + } else if (cp < 0x800u) { + out.push_back(static_cast<char>(0xC0u | (cp >> 6))); + out.push_back(static_cast<char>(0x80u | (cp & 0x3Fu))); + } else if (cp < 0x10000u) { + out.push_back(static_cast<char>(0xE0u | (cp >> 12))); + out.push_back(static_cast<char>(0x80u | ((cp >> 6) & 0x3Fu))); + out.push_back(static_cast<char>(0x80u | (cp & 0x3Fu))); + } else { + out.push_back(static_cast<char>(0xF0u | (cp >> 18))); + out.push_back(static_cast<char>(0x80u | ((cp >> 12) & 0x3Fu))); + out.push_back(static_cast<char>(0x80u | ((cp >> 6) & 0x3Fu))); + out.push_back(static_cast<char>(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<unsigned char>(c) < 0x20u) { + char buf[7]; + std::snprintf(buf, sizeof(buf), "\\u%04x", + static_cast<unsigned>(static_cast<unsigned char>(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 <typename Schema> struct json_encode { + static_assert(always_false<Schema>, + "This schema has no JSON representation"); +}; + +template <> struct json_encode<sch::Void> { + static error_or<void> apply(const data<sch::Void, enc::Native> &, + std::string &out, bool, uint64_t) { + out += "null"; + return make_void(); + } +}; + +template <> struct json_encode<sch::Bool> { + static error_or<void> apply(const data<sch::Bool, enc::Native> &in, + std::string &out, bool, uint64_t) { + out += in.get() ? "true" : "false"; + return make_void(); + } +}; + +template <typename K, uint64_t N> struct json_encode<sch::Primitive<K, N>> { + static error_or<void> + apply(const data<sch::Primitive<K, N>, enc::Native> &in, std::string &out, + bool, uint64_t) { + using Native = typename native_data_type<sch::Primitive<K, N>>::type; + const Native v = in.get(); + + if constexpr (std::is_floating_point_v<Native>) { + /** + * 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<Native>::max_digits10, + static_cast<double>(v)); + out += buf; + } else if constexpr (std::is_signed_v<Native>) { + out += std::to_string(static_cast<int64_t>(v)); + } else { + out += std::to_string(static_cast<uint64_t>(v)); + } + return make_void(); + } +}; + +template <typename S, typename I> +struct json_encode<sch::MixedPrecision<S, I>> { + static error_or<void> + apply(const data<sch::MixedPrecision<S, I>, enc::Native> &in, + std::string &out, bool pretty, uint64_t level) { + // A mixed precision value reads as its interface type. + data<I, enc::Native> widened{in.get()}; + return json_encode<I>::apply(widened, out, pretty, level); + } +}; + +template <> struct json_encode<sch::String> { + static error_or<void> apply(const data<sch::String, enc::Native> &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 <typename Inner, typename Container> +inline error_or<void> 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<Inner>::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 <typename T, uint64_t... D> +struct json_encode<sch::FixedArray<T, D...>> { + static error_or<void> + apply(const data<sch::FixedArray<T, D...>, enc::Native> &in, + std::string &out, bool pretty, uint64_t level) { + constexpr uint64_t flat = ct_multiply<uint64_t, D...>::value; + return json_encode_sequence<T>(in, flat, out, pretty, level); + } +}; + +template <typename T, uint64_t Dim> struct json_encode<sch::Array<T, Dim>> { + static error_or<void> + apply(const data<sch::Array<T, Dim>, enc::Native> &in, std::string &out, + bool pretty, uint64_t level) { + return json_encode_sequence<T>(in, in.size().get(), out, pretty, level); + } +}; + +template <typename Inner, uint64_t... D> +struct json_encode<sch::Tensor<Inner, D...>> { + static error_or<void> + apply(const data<sch::Tensor<Inner, D...>, enc::Native> &in, + std::string &out, bool pretty, uint64_t level) { + constexpr uint64_t flat = ct_multiply<uint64_t, D...>::value; + return json_encode_sequence<Inner>(in, flat, out, pretty, level); + } +}; + +template <typename... T> struct json_encode<sch::Tuple<T...>> { + template <uint64_t i = 0u> + static error_or<void> + apply_element(const data<sch::Tuple<T...>, 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<i, T...>::type; + auto eov = json_encode<Element>::apply(in.template get<i>(), out, + pretty, level + 1u); + if (eov.is_error()) { + return eov; + } + return apply_element<i + 1u>(in, out, pretty, level); + } else { + return make_void(); + } + } + + static error_or<void> apply(const data<sch::Tuple<T...>, 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 <typename... T, string_literal... Keys> +struct json_encode<sch::Struct<sch::Member<T, Keys>...>> { + using Schema = sch::Struct<sch::Member<T, Keys>...>; + + template <uint64_t i = 0u> + static error_or<void> apply_member(const data<Schema, 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); + json_append_escaped( + out, parameter_key_pack_type<i, Keys...>::literal.view()); + out.push_back(':'); + if (pretty) { + out.push_back(' '); + } + using Member = typename parameter_pack_type<i, T...>::type; + auto eov = json_encode<Member>::apply( + in.template get_at_index<i>(), out, pretty, level + 1u); + if (eov.is_error()) { + return eov; + } + return apply_member<i + 1u>(in, out, pretty, level); + } else { + return make_void(); + } + } + + static error_or<void> apply(const data<Schema, enc::Native> &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 <typename Schema> struct json_decode { + static_assert(always_false<Schema>, + "This schema has no JSON representation"); +}; + +template <> struct json_decode<sch::Void> { + static error_or<void> apply(json_parser &p, data<sch::Void, enc::Native> &, + const codec_config<enc::Json> &) { + if (!p.consume_null()) { + return make_error<err::json_type_mismatch>("Expected null"); + } + return make_void(); + } +}; + +template <> struct json_decode<sch::Bool> { + static error_or<void> apply(json_parser &p, + data<sch::Bool, enc::Native> &out, + const codec_config<enc::Json> &) { + 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 <typename K, uint64_t N> struct json_decode<sch::Primitive<K, N>> { + static error_or<void> apply(json_parser &p, + data<sch::Primitive<K, N>, enc::Native> &out, + const codec_config<enc::Json> &) { + using Native = typename native_data_type<sch::Primitive<K, N>>::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<Native>) { + /** + * 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<err::json_malformed>("Bad floating point"); + } + out.set(static_cast<Native>(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<Native>) { + r = std::from_chars(first, last, sv); + } else { + if (!tok.empty() && tok.front() == '-') { + return make_error<err::json_type_mismatch>( + "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<err::json_malformed>("Bad integer"); + } + if (r.ptr != last) { + return make_error<err::json_type_mismatch>( + "Expected an integer"); + } + + if constexpr (std::is_signed_v<Native>) { + out.set(static_cast<Native>(sv)); + } else { + out.set(static_cast<Native>(uv)); + } + } + return make_void(); + } +}; + +template <typename S, typename I> +struct json_decode<sch::MixedPrecision<S, I>> { + static error_or<void> + apply(json_parser &p, data<sch::MixedPrecision<S, I>, enc::Native> &out, + const codec_config<enc::Json> &cfg) { + data<I, enc::Native> widened; + auto eov = json_decode<I>::apply(p, widened, cfg); + if (eov.is_error()) { + return eov; + } + out.set(widened.get()); + return make_void(); + } +}; + +template <> struct json_decode<sch::String> { + static error_or<void> apply(json_parser &p, + data<sch::String, enc::Native> &out, + const codec_config<enc::Json> &) { + 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 <typename Inner, typename Container> +inline error_or<void> json_decode_fixed_sequence(json_parser &p, Container &out, + uint64_t count, + const codec_config<enc::Json> &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<err::json_type_mismatch>( + "JSON array is longer than the schema allows"); + } + auto eov = json_decode<Inner>::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<err::json_type_mismatch>( + "JSON array is shorter than the schema requires"); + } + return make_void(); +} + +template <typename T, uint64_t... D> +struct json_decode<sch::FixedArray<T, D...>> { + static error_or<void> + apply(json_parser &p, data<sch::FixedArray<T, D...>, enc::Native> &out, + const codec_config<enc::Json> &cfg) { + constexpr uint64_t flat = ct_multiply<uint64_t, D...>::value; + return json_decode_fixed_sequence<T>(p, out, flat, cfg); + } +}; + +template <typename Inner, uint64_t... D> +struct json_decode<sch::Tensor<Inner, D...>> { + static error_or<void> + apply(json_parser &p, data<sch::Tensor<Inner, D...>, enc::Native> &out, + const codec_config<enc::Json> &cfg) { + constexpr uint64_t flat = ct_multiply<uint64_t, D...>::value; + return json_decode_fixed_sequence<Inner>(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 <typename T, uint64_t Dim> struct json_decode<sch::Array<T, Dim>> { + static error_or<void> apply(json_parser &p, + data<sch::Array<T, Dim>, enc::Native> &out, + const codec_config<enc::Json> &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<sch::Array<T, Dim>, enc::Native>{}; + + if (!p.consume_if(']')) { + while (true) { + data<T, enc::Native> element; + auto eov = json_decode<T>::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 <typename... T> struct json_decode<sch::Tuple<T...>> { + using Schema = sch::Tuple<T...>; + + template <uint64_t i = 0u> + static error_or<void> apply_element(json_parser &p, + data<Schema, enc::Native> &out, + const codec_config<enc::Json> &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<i, T...>::type; + auto eov = + json_decode<Element>::apply(p, out.template get<i>(), cfg); + if (eov.is_error()) { + return eov; + } + return apply_element<i + 1u>(p, out, cfg); + } else { + return make_void(); + } + } + + static error_or<void> apply(json_parser &p, data<Schema, enc::Native> &out, + const codec_config<enc::Json> &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 <typename... T, string_literal... Keys> +struct json_decode<sch::Struct<sch::Member<T, Keys>...>> { + using Schema = sch::Struct<sch::Member<T, Keys>...>; + + /** + * 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 <uint64_t i = 0u> + static error_or<bool> dispatch(std::string_view key, json_parser &p, + data<Schema, enc::Native> &out, + const codec_config<enc::Json> &cfg, + bool (&seen)[sizeof...(T) > 0u ? sizeof...(T) : 1u]) { + if constexpr (i < sizeof...(T)) { + if (key == parameter_key_pack_type<i, Keys...>::literal.view()) { + using Member = typename parameter_pack_type<i, T...>::type; + auto eov = json_decode<Member>::apply( + p, out.template get_at_index<i>(), cfg); + if (eov.is_error()) { + return std::move(eov.get_error()); + } + seen[i] = true; + return true; + } + return dispatch<i + 1u>(key, p, out, cfg, seen); + } else { + (void)key; + (void)p; + (void)out; + (void)cfg; + (void)seen; + return false; + } + } + + static error_or<void> apply(json_parser &p, data<Schema, enc::Native> &out, + const codec_config<enc::Json> &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<err::json_missing_member>(); + } + } + } + + return make_void(); + } +}; + +} // namespace impl + +template <typename Schema, typename Encoding> class codec; + +/** + * Translates between a native value and its JSON text. + */ +template <typename Schema> class codec<Schema, enc::Json> final { +private: + codec_config<enc::Json> cfg_; + +public: + codec() = default; + + explicit codec(const codec_config<enc::Json> &cfg__) : cfg_{cfg__} {} + + KEL_FORBID_COPY(codec); + KEL_DEFAULT_MOVE(codec); + + error_or<void> encode(const data<Schema, enc::Native> &from, + data<Schema, enc::Json> &to) { + std::string out; + auto eov = impl::json_encode<Schema>::apply(from, out, cfg_.pretty, 0u); + if (eov.is_error()) { + return eov; + } + to.set(std::move(out)); + return make_void(); + } + + error_or<void> decode(const data<Schema, enc::Json> &from, + data<Schema, enc::Native> &to) { + impl::json_parser p{from.stl_view(), cfg_.depth}; + + auto eov = impl::json_decode<Schema>::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<err::json_malformed>( + "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 <cmath> + +#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<T>{value} -> data<Scalar<T>>{...} conversion, which the language won't + * do implicitly. + */ +template <typename T, typename Encoding = KEL_LBM_DEFAULT_DATA_ENCODING> +constexpr data<sch::Scalar<T>, Encoding> +make_scalar(typename native_data_type<T>::type value) { + return data<sch::Scalar<T>, Encoding>{data<T, Encoding>{value}}; +} + +/** + * Builds a vector from its native component values. The dimension is deduced + * from the argument count. + */ +template <typename T, typename Encoding = KEL_LBM_DEFAULT_DATA_ENCODING, + typename... Args> +constexpr data<sch::Vector<T, sizeof...(Args)>, Encoding> +make_vector(Args... args) { + return data<sch::Vector<T, sizeof...(Args)>, Encoding>{ + data<sch::FixedArray<T, sizeof...(Args)>, Encoding>{ + std::array<data<T, Encoding>, sizeof...(Args)>{data<T, Encoding>{ + static_cast<typename native_data_type<T>::type>(args)}...}}}; +} + +template <typename T, uint64_t D, + typename Encoding = KEL_LBM_DEFAULT_DATA_ENCODING> +data<sch::Scalar<T>, Encoding> dot(const data<sch::Vector<T, D>, Encoding> &left, + const data<sch::Vector<T, D>, Encoding> &right) { + data<sch::Scalar<T>, 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 <typename T, typename Encoding = KEL_LBM_DEFAULT_DATA_ENCODING> +data<sch::Scalar<T>, Encoding> sqrt(const data<sch::Scalar<T>, Encoding> &inp) { + data<sch::Scalar<T>, Encoding> out; + out.flat_at(0u).set(std::sqrt(inp.flat_at(0u).get())); + return out; +} + +/** + * Euclidean length of a vector. + */ +template <typename T, uint64_t D, + typename Encoding = KEL_LBM_DEFAULT_DATA_ENCODING> +data<sch::Scalar<T>, Encoding> +norm(const data<sch::Vector<T, D>, Encoding> &input) { + return sqrt<T, Encoding>(dot<T, D, Encoding>(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 <typename T, uint64_t D, + typename Encoding = KEL_LBM_DEFAULT_DATA_ENCODING> +data<sch::Vector<T, D>, Encoding> +normalize(const data<sch::Vector<T, D>, Encoding> &input) { + auto inp_dot = dot<T, D, Encoding>(input, input); + if (inp_dot.flat_at(0u).get() <= 0) { + return input; + } + auto sqrt_inp_dot = sqrt<T, Encoding>(inp_dot); + + data<sch::Vector<T, D>, 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 <typename T, uint64_t D, + typename Encoding = KEL_LBM_DEFAULT_DATA_ENCODING> +data<sch::Vector<T, D>, Encoding> +vectorize_data(const data<sch::FixedArray<T, D>, Encoding> &dat) { + data<sch::Vector<T, D>, Encoding> vec_data; + for (uint64_t i = 0u; i < D; ++i) { + vec_data.flat_at(i) = dat.flat_at(i); + } + + return vec_data; +} + +template <typename T, uint64_t M, uint64_t N, uint64_t K, + typename Encoding = KEL_LBM_DEFAULT_DATA_ENCODING> +data<sch::Matrix<T, M, N>, Encoding> +multiply(const data<sch::Matrix<T, M, K>, Encoding> &left, + const data<sch::Matrix<T, K, N>, Encoding> &right) { + data<sch::Matrix<T, M, N>, 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 <typename T, uint64_t M, uint64_t N, + typename Encoding = KEL_LBM_DEFAULT_DATA_ENCODING> +data<sch::Vector<T, M>, Encoding> +multiply(const data<sch::Matrix<T, M, N>, Encoding> &left, + const data<sch::Vector<T, N>, Encoding> &right) { + data<sch::Vector<T, M>, 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 <typename T, typename Encoding = KEL_LBM_DEFAULT_DATA_ENCODING> +data<sch::Vector<T, 3u>, Encoding> +cross(const data<sch::Vector<T, 3u>, Encoding> &lh, + const data<sch::Vector<T, 3u>, Encoding> &rh) { + data<sch::Vector<T, 3u>, 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 <typename T, typename Encoding = KEL_LBM_DEFAULT_DATA_ENCODING> +data<sch::Scalar<T>, Encoding> +cross(const data<sch::Vector<T, 2u>, Encoding> &lh, + const data<sch::Vector<T, 2u>, Encoding> &rh) { + data<sch::Scalar<T>, 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 <typename T, typename Encoding = KEL_LBM_DEFAULT_DATA_ENCODING> +data<sch::Vector<T, 2u>, Encoding> +cross(const data<sch::Scalar<T>, Encoding> &lh, + const data<sch::Vector<T, 2u>, Encoding> &rh) { + data<sch::Vector<T, 2u>, 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 <typename T, typename Encoding = KEL_LBM_DEFAULT_DATA_ENCODING> +data<sch::Scalar<T>, Encoding> cos(const data<sch::Scalar<T>, Encoding> &val) { + data<sch::Scalar<T>, Encoding> ret; + ret.flat_at(0u).set(std::cos(val.flat_at(0u).get())); + return ret; +} + +template <typename T, typename Encoding = KEL_LBM_DEFAULT_DATA_ENCODING> +data<sch::Scalar<T>, Encoding> sin(const data<sch::Scalar<T>, Encoding> &val) { + data<sch::Scalar<T>, 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 <typename T, typename Encoding = KEL_LBM_DEFAULT_DATA_ENCODING> +data<sch::Scalar<T>, Encoding> +angle(const data<sch::Vector<T, 2u>, Encoding> &vec) { + data<sch::Scalar<T>, 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 <typename T, typename Encoding = KEL_LBM_DEFAULT_DATA_ENCODING> +data<sch::Vector<T, 2u>, Encoding> +unit_vector(const data<sch::Scalar<T>, Encoding> &rot) { + data<sch::Vector<T, 2u>, Encoding> ret; + ret.flat_at(0u) = cos<T, Encoding>(rot).flat_at(0u); + ret.flat_at(1u) = sin<T, Encoding>(rot).flat_at(0u); + return ret; +} + +/** + * Rotates a 2d vector counter clockwise by the given angle. + */ +template <typename T, typename Encoding = KEL_LBM_DEFAULT_DATA_ENCODING> +data<sch::Vector<T, 2u>, Encoding> +rotate(const data<sch::Vector<T, 2u>, Encoding> &vec, + const data<sch::Scalar<T>, Encoding> &rot) { + data<sch::Vector<T, 2u>, Encoding> rot_vec; + + auto c = cos<T, Encoding>(rot).flat_at(0u); + auto s = sin<T, Encoding>(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 <typename T, uint64_t D, + typename Encoding = KEL_LBM_DEFAULT_DATA_ENCODING> +data<sch::Vector<T, D>, Encoding> +scale(const data<sch::Vector<T, D>, Encoding> &vec, + const data<sch::Scalar<T>, Encoding> &scale_) { + data<sch::Vector<T, D>, 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 <typename T, uint64_t... Ds, + typename Encoding = KEL_LBM_DEFAULT_DATA_ENCODING> +void fill(data<sch::Tensor<T, Ds...>, Encoding> &tbf, + const data<T, Encoding> &filler) { + constexpr uint64_t flat = ct_multiply<uint64_t, Ds...>::value; + for (uint64_t i = 0u; i < flat; ++i) { + tbf.flat_at(i) = filler; + } +} + +template <typename T, uint64_t... Ds, + typename Encoding = KEL_LBM_DEFAULT_DATA_ENCODING> +data<sch::Scalar<T>, Encoding> +sum(const data<sch::Tensor<T, Ds...>, Encoding> &tens) { + data<sch::Scalar<T>, Encoding> s; + + constexpr uint64_t flat = ct_multiply<uint64_t, Ds...>::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 <array> +#include <cstdint> +#include <type_traits> + #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<typename StorageT, typename InterfaceT> -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 <typename T> struct is_primitive_kind : std::false_type {}; +template <> struct is_primitive_kind<UnsignedInteger> : std::true_type {}; +template <> struct is_primitive_kind<SignedInteger> : std::true_type {}; +template <> struct is_primitive_kind<FloatingPoint> : 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 <typename PrimType, uint64_t N> struct Primitive { + static_assert(is_primitive_kind<PrimType>::value, + "Primitive needs one of UnsignedInteger, SignedInteger or " + "FloatingPoint as its kind"); + static_assert(((std::is_same_v<PrimType, SignedInteger> || + std::is_same_v<PrimType, UnsignedInteger>) && + (N == 1u || N == 2u || N == 4u || N == 8u)) || + (std::is_same_v<PrimType, FloatingPoint> && + (N == 4u || N == 8u)), + "Primitive Type is not supported"); -template<typename PrimType, uint64_t N> -struct Primitive { using Meta = Void; - using StorageType = PrimType; - using InterfaceType = PrimType; + using Kind = PrimType; + using StorageType = Primitive<PrimType, N>; + using InterfaceType = Primitive<PrimType, N>; static constexpr uint64_t Bytes = N; + static constexpr string_literal name = "Primitive"; }; -using UInt8 = Primitive<UnsignedInteger,1u>; -using UInt16 = Primitive<UnsignedInteger,2u>; -using UInt32 = Primitive<UnsignedInteger,4u>; -using UInt64 = Primitive<UnsignedInteger,8u>; +template <typename T> struct is_primitive : std::false_type {}; +template <typename K, uint64_t N> +struct is_primitive<Primitive<K, N>> : std::true_type {}; + +using UInt8 = Primitive<UnsignedInteger, 1u>; +using UInt16 = Primitive<UnsignedInteger, 2u>; +using UInt32 = Primitive<UnsignedInteger, 4u>; +using UInt64 = Primitive<UnsignedInteger, 8u>; + +using Int8 = Primitive<SignedInteger, 1u>; +using Int16 = Primitive<SignedInteger, 2u>; +using Int32 = Primitive<SignedInteger, 4u>; +using Int64 = Primitive<SignedInteger, 8u>; -using Int8 = Primitive<SignedInteger,1u>; -using Int16 = Primitive<SignedInteger,2u>; -using Int32 = Primitive<SignedInteger,4u>; -using Int64 = Primitive<SignedInteger,8u>; +using Float32 = Primitive<FloatingPoint, 4u>; +using Float64 = Primitive<FloatingPoint, 8u>; -using Float8 = Primitive<FloatingPoint,1u>; -using Float16 = Primitive<FloatingPoint,2u>; -using Float32 = Primitive<FloatingPoint,4u>; -using Float64 = Primitive<FloatingPoint,8u>; +/** + * 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 <typename StorageT, typename InterfaceT> struct MixedPrecision { + static_assert(is_primitive<StorageT>::value, + "StorageType needs to be a Primitive"); + static_assert(is_primitive<InterfaceT>::value, + "InterfaceType needs to be a Primitive"); -template<typename T, uint64_t... Dims> -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 <typename Value, string_literal Key_> 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 <typename T, uint64_t... Dims> struct FixedArray { using Meta = Void; using Inner = T; - static constexpr std::array<uint64_t,sizeof...(Dims)> 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<uint64_t, sizeof...(Dims)> Dimensions{Dims...}; + static constexpr uint64_t FlatSize = ct_multiply<uint64_t, Dims...>::value; + static constexpr string_literal name = "FixedArray"; }; -template<typename T, uint64_t Dims> -struct Array { - using Meta = FixedArray<UInt64,Dims>; +/** + * Array of rank `Dims` whose extents are only known at runtime, so the extents + * themselves are the metadata. + */ +template <typename T, uint64_t Dims = 1u> struct Array { + using Meta = FixedArray<UInt64, Dims>; using Inner = T; - static constexpr std::array<uint64_t,1u> 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 <typename... T> struct Tuple { + using Meta = Tuple<typename T::Meta...>; + static constexpr uint64_t Size = sizeof...(T); + static constexpr string_literal name = "Tuple"; }; -template<typename... T> -struct Tuple { +template <typename... T> struct Struct { + static_assert(always_false<T...>, + "Struct only accepts Member<Schema,Key> parameters"); }; -template<typename Value, string_literal Key> -struct Member {}; +template <typename... Schema, string_literal... Key> +struct Struct<Member<Schema, Key>...> { + using Meta = Struct<Member<typename Schema::Meta, Key>...>; + static constexpr uint64_t Size = sizeof...(Schema); + static constexpr string_literal name = "Struct"; +}; -template<typename... SL> -struct Struct {}; +template <typename... T> struct Union { + static_assert(always_false<T...>, + "Union only accepts Member<Schema,Key> parameters"); +}; -} +template <typename... Schema, string_literal... Key> +struct Union<Member<Schema, Key>...> { + using Meta = Union<Member<typename Schema::Meta, Key>...>; + static constexpr uint64_t Size = sizeof...(Schema); + static constexpr string_literal name = "Union"; +}; + +template <typename Key, typename Value> struct Map { + using Meta = Void; + using KeyType = Key; + using ValueType = Value; + static constexpr string_literal name = "Map"; +}; + +/** + * The schema counterpart of ref<T>. + */ +template <typename Schema> struct Ref { + using Meta = Void; + using ValueType = Schema; + static constexpr string_literal name = "Ref"; +}; + +/** + * The schema counterpart of ptr<T>. + * + * Its advantage is that data<Ptr<UInt64>> keeps the interface of + * data<UInt64> -- arithmetic still reads the same -- while the storage is + * borrowed rather than owned. This is what lets an Array<Float64> be handed + * out as a double* without losing the data accessor on top of it. + */ +template <typename Schema> 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 <typename Schema, typename Enc> 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 <typename Inner, uint64_t... D> struct Tensor { + using Meta = FixedArray<UInt64, sizeof...(D)>; + using Inner_ = Inner; + using ValueType = Inner; + static constexpr uint64_t Rank = sizeof...(D); + static constexpr std::array<uint64_t, Rank> Dimension{D...}; + static constexpr uint64_t FlatSize = ct_multiply<uint64_t, D...>::value; + static constexpr string_literal name = "Tensor"; +}; + +template <typename Inner> using Scalar = Tensor<Inner>; + +template <typename Inner, uint64_t D> using Vector = Tensor<Inner, D>; + +template <typename Inner, uint64_t D1, uint64_t D2> +using Matrix = Tensor<Inner, D1, D2>; + +} // namespace sch + +/** + * Convenience accessor, so `Meta` can be spelled as a trait where a nested + * typedef would be awkward to reach. + */ +template <typename Schema> struct meta_schema { + using Schema_ = Schema; + using MetaSchema = typename Schema::Meta; +}; + +template <typename Sch> struct schema { using Type = Sch; }; + +/** + * Index into the members of a structural schema. + */ +template <uint64_t I, typename Structural> struct schema_type_at_index; + +template <uint64_t I, typename... Members> +struct schema_type_at_index<I, sch::Struct<Members...>> { + using Type = typename parameter_pack_type<I, Members...>::type; +}; + +template <uint64_t I, typename... Members> +struct schema_type_at_index<I, sch::Union<Members...>> { + using Type = typename parameter_pack_type<I, Members...>::type; +}; -template<typename Sch> -struct schema { - using Type = Sch; +template <uint64_t I, typename... T> +struct schema_type_at_index<I, sch::Tuple<T...>> { + using Type = typename parameter_pack_type<I, T...>::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 <string_literal Key, typename Schema> struct schema_has_key; + +template <string_literal Key, typename... T, string_literal... Keys> +struct schema_has_key<Key, sch::Struct<sch::Member<T, Keys>...>> { + static constexpr bool value = ((Key == Keys) || ...); +}; + +template <string_literal Key, typename... T, string_literal... Keys> +struct schema_has_key<Key, sch::Union<sch::Member<T, Keys>...>> { + static constexpr bool value = ((Key == Keys) || ...); +}; + +/** + * Compile time predicate: does this structural schema already carry exactly + * this member, key and type both? + */ +template <typename Member, typename Schema> struct schema_has_member; + +template <typename MT, string_literal MK, typename... T, string_literal... Keys> +struct schema_has_member<sch::Member<MT, MK>, + sch::Struct<sch::Member<T, Keys>...>> { + static constexpr bool value = + ((MK == Keys && std::is_same_v<MT, T>) || ...); +}; + +template <typename MT, string_literal MK, typename... T, string_literal... Keys> +struct schema_has_member<sch::Member<MT, MK>, + sch::Union<sch::Member<T, Keys>...>> { + static constexpr bool value = + ((MK == Keys && std::is_same_v<MT, T>) || ...); +}; + +/** + * 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 <typename T> struct schema_factory { + using Schema = T; + static_assert(always_false<T>, "Not supported"); +}; + +template <typename... T, string_literal... Keys> +struct schema_factory<sch::Struct<sch::Member<T, Keys>...>> { + using Schema = sch::Struct<sch::Member<T, Keys>...>; + + template <string_literal KA> static constexpr bool has_key() noexcept { + return schema_has_key<KA, Schema>::value; + } + + template <typename TA, string_literal KA> + static constexpr bool has_member() noexcept { + return schema_has_member<sch::Member<TA, KA>, 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 <typename TA, string_literal KA> + constexpr auto add_maybe() const noexcept { + if constexpr (!has_key<KA>()) { + return schema_factory< + sch::Struct<sch::Member<T, Keys>..., sch::Member<TA, KA>>>{}; + } else if constexpr (has_member<TA, KA>()) { + return schema_factory<sch::Struct<sch::Member<T, Keys>...>>{}; + } else { + static_assert( + always_false<TA>, + "Struct already has the provided Key, but a mismatching Type"); + } + } + + template <typename TA, string_literal KA> + constexpr schema_factory< + sch::Struct<sch::Member<T, Keys>..., sch::Member<TA, KA>>> + add() const noexcept { + static_assert(!has_key<KA>(), + "Can't add member. Name is already in use."); + return {}; + } +}; + +template <typename... T, string_literal... Keys> +struct schema_factory<sch::Union<sch::Member<T, Keys>...>> { + using Schema = sch::Union<sch::Member<T, Keys>...>; + + template <string_literal KA> static constexpr bool has_key() noexcept { + return schema_has_key<KA, Schema>::value; + } + + template <typename TA, string_literal KA> + constexpr schema_factory< + sch::Union<sch::Member<T, Keys>..., sch::Member<TA, KA>>> + add() const noexcept { + static_assert(!has_key<KA>(), + "Can't add member. Name is already in use."); + return {}; + } +}; + +template <typename... T> struct schema_factory<sch::Tuple<T...>> { + using Schema = sch::Tuple<T...>; + + template <typename TA> + constexpr schema_factory<sch::Tuple<T..., TA>> add() const noexcept { + return {}; + } +}; + +/** + * Creates the base schema to build on: an empty struct, tuple or union. + */ +template <typename T> constexpr schema_factory<T> 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 { @@ -16,6 +17,27 @@ struct schema_to_string_helper { }; template<> +struct schema_to_string_helper<sch::Void> final { + static constexpr auto apply(){ + return string_literal{"Void"}; + } +}; + +template<> +struct schema_to_string_helper<sch::Bool> final { + static constexpr auto apply(){ + return string_literal{"Bool"}; + } +}; + +template<> +struct schema_to_string_helper<sch::String> final { + static constexpr auto apply(){ + return string_literal{"String"}; + } +}; + +template<> struct schema_to_string_helper<sch::SignedInteger> final { static constexpr auto apply(){ return string_literal{"SignedInteger"}; @@ -36,17 +58,189 @@ struct schema_to_string_helper<sch::FloatingPoint> 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<uint64_t N> +constexpr auto number_literal(){ + return ct_convert_to_digits<N, 10u>::literal; +} + +/** + * Joins a parameter pack of literals with ',' separators. + */ +template<typename... T> +struct schema_list_to_string_helper; + +template<> +struct schema_list_to_string_helper<> final { + static constexpr auto apply(){ + return string_literal{""}; + } +}; + +template<typename T> +struct schema_list_to_string_helper<T> final { + static constexpr auto apply(){ + return schema_to_string_helper<T>::apply(); + } +}; + +template<typename T, typename U, typename... R> +struct schema_list_to_string_helper<T,U,R...> final { + static constexpr auto apply(){ + return schema_to_string_helper<T>::apply() + + string_literal{","} + + schema_list_to_string_helper<U,R...>::apply(); + } +}; + +/** + * Joins a pack of compile time numbers with ',' separators. + */ +template<uint64_t... N> +struct number_list_to_string_helper; + +template<> +struct number_list_to_string_helper<> final { + static constexpr auto apply(){ + return string_literal{""}; + } +}; + +template<uint64_t N> +struct number_list_to_string_helper<N> final { + static constexpr auto apply(){ + return number_literal<N>(); + } +}; + +template<uint64_t N, uint64_t M, uint64_t... R> +struct number_list_to_string_helper<N,M,R...> final { + static constexpr auto apply(){ + return number_literal<N>() + + string_literal{","} + + number_list_to_string_helper<M,R...>::apply(); + } +}; + template<typename T, uint64_t N> struct schema_to_string_helper<sch::Primitive<T,N>> final { static constexpr auto apply(){ - return string_literal{"Primitive<"}+schema_to_string_helper<T>::apply()+string_literal{","}+N+string_literal{">"}; + return string_literal{"Primitive<"} + + schema_to_string_helper<T>::apply() + + string_literal{","} + + number_literal<N>() + + string_literal{">"}; + } +}; + +template<typename S, typename I> +struct schema_to_string_helper<sch::MixedPrecision<S,I>> final { + static constexpr auto apply(){ + return string_literal{"MixedPrecision<"} + + schema_to_string_helper<S>::apply() + + string_literal{","} + + schema_to_string_helper<I>::apply() + + string_literal{">"}; + } +}; + +template<typename T, uint64_t... D> +struct schema_to_string_helper<sch::FixedArray<T,D...>> final { + static constexpr auto apply(){ + return string_literal{"FixedArray<"} + + schema_to_string_helper<T>::apply() + + string_literal{","} + + number_list_to_string_helper<D...>::apply() + + string_literal{">"}; + } +}; + +template<typename T, uint64_t D> +struct schema_to_string_helper<sch::Array<T,D>> final { + static constexpr auto apply(){ + return string_literal{"Array<"} + + schema_to_string_helper<T>::apply() + + string_literal{","} + + number_literal<D>() + + string_literal{">"}; + } +}; + +template<typename T, uint64_t... D> +struct schema_to_string_helper<sch::Tensor<T,D...>> final { + static constexpr auto apply(){ + return string_literal{"Tensor<"} + + schema_to_string_helper<T>::apply() + + string_literal{","} + + number_list_to_string_helper<D...>::apply() + + string_literal{">"}; + } +}; + +template<typename... T> +struct schema_to_string_helper<sch::Tuple<T...>> final { + static constexpr auto apply(){ + return string_literal{"Tuple<"} + + schema_list_to_string_helper<T...>::apply() + + string_literal{">"}; + } +}; + +template<typename T, string_literal K> +struct schema_to_string_helper<sch::Member<T,K>> final { + static constexpr auto apply(){ + return string_literal{"Member<"} + + schema_to_string_helper<T>::apply() + + string_literal{","} + + K + + string_literal{">"}; + } +}; + +template<typename... T, string_literal... K> +struct schema_to_string_helper<sch::Struct<sch::Member<T,K>...>> final { + static constexpr auto apply(){ + return string_literal{"Struct<"} + + schema_list_to_string_helper<sch::Member<T,K>...>::apply() + + string_literal{">"}; + } +}; + +template<typename... T, string_literal... K> +struct schema_to_string_helper<sch::Union<sch::Member<T,K>...>> final { + static constexpr auto apply(){ + return string_literal{"Union<"} + + schema_list_to_string_helper<sch::Member<T,K>...>::apply() + + string_literal{">"}; + } +}; + +template<typename T> +struct schema_to_string_helper<sch::Ptr<T>> final { + static constexpr auto apply(){ + return string_literal{"Ptr<"} + + schema_to_string_helper<T>::apply() + + string_literal{">"}; + } +}; + +template<typename T> +struct schema_to_string_helper<sch::Ref<T>> final { + static constexpr auto apply(){ + return string_literal{"Ref<"} + + schema_to_string_helper<T>::apply() + + string_literal{">"}; } }; } template<class T> -struct schema_to_string{ - static constexpr std::string_view value = impl::schema_to_string_helper<T>::apply().view(); +struct schema_to_string { + static constexpr auto literal = impl::schema_to_string_helper<T>::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 <array> +#include <cstddef> +#include <cstdint> + +#include "common.hpp" +#include "string_literal.hpp" + namespace kel { namespace lbm { -template<typename... T> -constexpr bool always_false = false; -} -} + +/** + * This type is meant for grouping of template types + */ +template <class... T> struct tmpl_group { + static constexpr string_literal name = "tmpl_group"; + static constexpr uint64_t size = sizeof...(T); +}; + +template <typename T, T... values> 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 <typename T, typename U> struct tmpl_concat; + +template <typename... T, typename... U> +struct tmpl_concat<tmpl_group<T...>, tmpl_group<U...>> { + using type = tmpl_group<T..., U...>; +}; + +template <typename T, T... L, T... R> +struct tmpl_concat<tmpl_value_group<T, L...>, tmpl_value_group<T, R...>> { + using type = tmpl_value_group<T, L..., R...>; +}; + +/** + * Returns the position of the parameter type in the parameter pack + */ +template <class T, class... TL> struct parameter_pack_index; + +template <class T, class... TL> struct parameter_pack_index<T, T, TL...> { + static constexpr size_t value = 0u; +}; + +template <class T, class TL0, class... TL> +struct parameter_pack_index<T, TL0, TL...> { + static constexpr size_t value = 1u + parameter_pack_index<T, TL...>::value; +}; + +template <size_t N, class... T> struct parameter_pack_type { + static_assert(always_false<T...>, + "Should've been caught by the specializations"); +}; + +template <class TN, class... T> struct parameter_pack_type<0, TN, T...> { + using type = TN; +}; + +template <size_t N, class TN, class... T> +struct parameter_pack_type<N, TN, T...> { + static_assert(sizeof...(T) > 0, "Exhausted parameters"); + static_assert(N > 0, "Invalid number. Should've been caught"); + using type = typename parameter_pack_type<N - 1, T...>::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 <string_literal V, string_literal Key0, string_literal... Keys> +struct parameter_key_pack_index_helper { + static constexpr size_t value = + (V == Key0) + ? (0u) + : (1u + parameter_key_pack_index_helper<V, Keys...>::value); +}; + +template <string_literal V, string_literal Key0> +struct parameter_key_pack_index_helper<V, Key0> { + static constexpr size_t value = (V == Key0) ? (0u) : (1u); +}; + +template <string_literal V, string_literal... Keys> +struct parameter_key_pack_index { + static constexpr size_t value = + parameter_key_pack_index_helper<V, Keys...>::value; + static_assert(value < sizeof...(Keys), + "Provided string_literal doesn't exist in searched list"); +}; + +template <size_t i, size_t s, string_literal Key0, string_literal... Keys> +struct parameter_key_pack_type_helper { + static constexpr string_literal literal = + parameter_key_pack_type_helper<i, s + 1, Keys...>::literal; +}; + +template <size_t i, string_literal Key0, string_literal... Keys> +struct parameter_key_pack_type_helper<i, i, Key0, Keys...> { + static constexpr string_literal literal = Key0; +}; + +template <size_t i, string_literal... Keys> struct parameter_key_pack_type { + static constexpr string_literal literal = + parameter_key_pack_type_helper<i, 0, Keys...>::literal; + + static_assert(i < sizeof...(Keys), "Provided index is too large for list"); +}; + +template <std::size_t i, std::size_t s, typename T, T V0, T... VN> +struct parameter_pack_value_helper { + static constexpr T value = parameter_pack_value_helper<i, s + 1, T, VN...>::value; +}; + +template <std::size_t i, typename T, T V0, T... VN> +struct parameter_pack_value_helper<i, i, T, V0, VN...> { + static constexpr T value = V0; +}; + +template <std::size_t i, typename T, T... Values> struct parameter_pack_value { + static constexpr T value = + parameter_pack_value_helper<i, 0, T, Values...>::value; + static_assert(i < sizeof...(Values), + "Provided index is too large for list"); +}; + +template <uint64_t I, typename T> struct tmpl_group_pack_type; + +template <uint64_t I, typename... T> +struct tmpl_group_pack_type<I, tmpl_group<T...>> { + using type = typename parameter_pack_type<I, T...>::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 <typename T, T... V> struct ct_multiply; + +template <typename T> struct ct_multiply<T> { + static constexpr T value = 1; +}; + +template <typename T, T V0, T... VN> struct ct_multiply<T, V0, VN...> { + static constexpr T value = V0 * ct_multiply<T, VN...>::value; +}; + +namespace impl { +template <typename T> struct ct_convert_digits_table_helper { + static constexpr std::array<T, 16> table = {'0', '1', '2', '3', '4', '5', + '6', '7', '8', '9', 'A', 'B', + 'C', 'D', 'E', 'F'}; + + template <uint64_t i> static constexpr T value() { + static_assert(i < 16, "Only conversion up to hex is supported"); + return table[i]; + }; +}; + +template <uint64_t Num, uint64_t Base, uint64_t... Digs> +struct ct_convert_digits_helper { + static constexpr size_t size = + ct_convert_digits_helper<Num / Base, Base, Num % Base, Digs...>::size; + static constexpr std::array<uint64_t, size> value = + ct_convert_digits_helper<Num / Base, Base, Num % Base, Digs...>::value; + static constexpr string_literal literal = + ct_convert_digits_helper<Num / Base, Base, Num % Base, Digs...>::literal; +}; + +template <uint64_t Base, uint64_t... Digs> +struct ct_convert_digits_helper<0, Base, Digs...> { + static constexpr size_t size = sizeof...(Digs); + static constexpr std::array<uint64_t, size> value = {Digs...}; + static constexpr string_literal literal = { + {ct_convert_digits_table_helper<char>::value<Digs>()..., '\0'}}; +}; + +template <uint64_t Base> struct ct_convert_digits_helper<0, Base> { + static constexpr size_t size = 0; + static constexpr std::array<uint64_t, 1> value = {0}; + static constexpr string_literal literal = "0"_sl; +}; +} // namespace impl + +template <uint64_t Num, uint64_t Base> 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<Num, Base>::size; + static constexpr std::array<uint64_t, size> value = + impl::ct_convert_digits_helper<Num, Base>::value; + static constexpr string_literal literal = + impl::ct_convert_digits_helper<Num, Base>::literal; +}; + +/** + * Decimal rendering of a compile time number, for schema stringification. + */ +template <uint64_t Num> +using ct_decimal_literal = ct_convert_to_digits<Num, 10u>; + +} // 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 <type_traits> + +#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 <typename Un, int64_t Expo = 0, int64_t Scal = 0> 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 <typename BaseSchema, typename... Components> 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 <typename BaseSchema> using Pure = Unit<BaseSchema>; + +} // namespace sch + +namespace impl { + +template <typename T, typename U> class unit_matching; + +template <typename... T> class unit_redux_list { + static_assert(sizeof...(T) == 0u, "Template type not supported"); + + using Type = unit_redux_list<>; +}; + +template <typename T0, int64_t E0, int64_t S0, typename... TL, int64_t... EL, + int64_t... SL> +struct unit_redux_list<sch::UnitElement<T0, E0, S0>, + sch::UnitElement<TL, EL, SL>...> { + using Type = typename unit_matching< + unit_redux_list<sch::UnitElement<T0, E0, S0>, + sch::UnitElement<TL, EL, SL>...>, + unit_redux_list<>>::TypeList; +}; + +template <typename T, typename U, typename V> class unit_matching_reduce { +public: + static_assert(always_false<T, U, V>, "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 <typename T, int64_t E, int64_t S, typename T0, int64_t E0, int64_t S0, + typename... TL, int64_t... EL, int64_t... SL, typename... TR, + int64_t... ER, int64_t... SR> +class unit_matching_reduce< + sch::UnitElement<T, E, S>, + unit_redux_list<sch::UnitElement<T0, E0, S0>, + sch::UnitElement<TL, EL, SL>...>, + unit_redux_list<sch::UnitElement<TR, ER, SR>...>> { +public: + static constexpr bool is_same = std::is_same_v<T, T0> and (S == S0); + + using ReducedType = + typename std::conditional<is_same, sch::UnitElement<T, E + E0, S>, + sch::UnitElement<T, E, S>>::type; + using ReducedTypeList = typename std::conditional< + is_same, unit_redux_list<sch::UnitElement<TR, ER, SR>...>, + unit_redux_list<sch::UnitElement<TR, ER, SR>..., + sch::UnitElement<T0, E0, S0>>>::type; + + using NextMatcher = + unit_matching_reduce<ReducedType, + unit_redux_list<sch::UnitElement<TL, EL, SL>...>, + 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 <typename T, int64_t E, int64_t S, typename... TR, int64_t... ER, + int64_t... SR> +class unit_matching_reduce<sch::UnitElement<T, E, S>, unit_redux_list<>, + unit_redux_list<sch::UnitElement<TR, ER, SR>...>> { +public: + using Type = sch::UnitElement<T, E, S>; + using TypeList = unit_redux_list<sch::UnitElement<TR, ER, SR>...>; + static constexpr int64_t Num = E; + static constexpr int64_t Scale = S; +}; + +template <typename LR, typename RR> class unit_matching { + static_assert(always_false<LR, RR>, "Template type not supported"); +}; + +template <typename... Ele> +class unit_matching<unit_redux_list<>, unit_redux_list<Ele...>> { +public: + using TypeList = unit_redux_list<Ele...>; +}; + +template <typename Ele0, typename... EleL, typename... EleR> +class unit_matching<unit_redux_list<Ele0, EleL...>, unit_redux_list<EleR...>> { +public: + using MatchReducer = + unit_matching_reduce<Ele0, unit_redux_list<EleL...>, 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<Num == 0, unit_redux_list<EleR...>, + unit_redux_list<EleR..., ReducedType>>::type; + using TypeList = typename unit_matching<ReducedTypeList, TypeRightList>::TypeList; +}; + +template <typename BaseSchema, typename List> class unit_add_base { + static_assert(always_false<BaseSchema, List>, "Template type not supported"); +}; + +template <typename BaseSchema, typename... Ele> +class unit_add_base<BaseSchema, unit_redux_list<Ele...>> { +public: + using Schema = sch::Unit<BaseSchema, Ele...>; +}; + +} // namespace impl + +template <typename BaseSchema, typename... UE> struct unit_element_reduction { + using TypeList = + typename impl::unit_matching<impl::unit_redux_list<UE...>, + impl::unit_redux_list<>>::TypeList; + using Schema = typename impl::unit_add_base<BaseSchema, TypeList>::Schema; +}; + +template <typename U0, typename U1> struct unit_multiplication { + static_assert(always_false<U0, U1>, "Template type not supported"); +}; + +template <typename BaseSchema, typename... UnitT, int64_t... UnitE, + typename... UnitRhsT, int64_t... UnitRhsE> +struct unit_multiplication< + sch::Unit<BaseSchema, sch::UnitElement<UnitT, UnitE>...>, + sch::Unit<BaseSchema, sch::UnitElement<UnitRhsT, UnitRhsE>...>> { + using Schema = typename unit_element_reduction< + BaseSchema, sch::UnitElement<UnitT, UnitE>..., + sch::UnitElement<UnitRhsT, UnitRhsE>...>::Schema; +}; + +template <typename U0, typename U1> struct unit_division { + static_assert(always_false<U0, U1>, "Template type not supported"); +}; + +/** + * Division is multiplication by the negated exponents. + */ +template <typename BaseSchema, typename... UnitT, int64_t... UnitE, + typename... UnitRhsT, int64_t... UnitRhsE> +struct unit_division< + sch::Unit<BaseSchema, sch::UnitElement<UnitT, UnitE>...>, + sch::Unit<BaseSchema, sch::UnitElement<UnitRhsT, UnitRhsE>...>> { + using Schema = typename unit_element_reduction< + BaseSchema, sch::UnitElement<UnitT, UnitE>..., + sch::UnitElement<UnitRhsT, -UnitRhsE>...>::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 <typename BaseSchema, typename... Elements> +class data<sch::Unit<BaseSchema, Elements...>, enc::Native> final { +public: + using Schema = sch::Unit<BaseSchema, Elements...>; + using MetaSchema = typename Schema::Meta; + using BaseData = data<BaseSchema, enc::Native>; + +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<Schema, enc::Native> operator+(const data<Schema, enc::Native> &rhs) const { + return {dat_ + rhs.handle()}; + } + + data<Schema, enc::Native> operator-(const data<Schema, enc::Native> &rhs) const { + return {dat_ - rhs.handle()}; + } + + data<Schema, enc::Native> &operator+=(const data<Schema, enc::Native> &rhs) { + dat_ += rhs.handle(); + return *this; + } + + data<Schema, enc::Native> &operator-=(const data<Schema, enc::Native> &rhs) { + dat_ -= rhs.handle(); + return *this; + } + + bool operator==(const data<Schema, enc::Native> &rhs) const { + return dat_ == rhs.handle(); + } + + bool operator!=(const data<Schema, enc::Native> &rhs) const { + return !(dat_ == rhs.handle()); + } + + bool operator<(const data<Schema, enc::Native> &rhs) const { + return dat_ < rhs.handle(); + } + + bool operator>(const data<Schema, enc::Native> &rhs) const { + return dat_ > rhs.handle(); + } + + template <typename UnitRhs> + data<typename unit_multiplication<Schema, UnitRhs>::Schema, enc::Native> + operator*(const data<UnitRhs, enc::Native> &rhs) const { + return {dat_ * rhs.handle()}; + } + + template <typename UnitRhs> + data<typename unit_division<Schema, UnitRhs>::Schema, enc::Native> + operator/(const data<UnitRhs, enc::Native> &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 <ostream> + +#include "unit.hpp" + +namespace std { +template <typename UT, int64_t UE> +inline ostream &operator<<(ostream &o, + const ::kel::lbm::sch::UnitElement<UT, UE> &) { + o << UT::short_name; + if constexpr (UE != 1) { + o << '^' << '(' << UE << ')'; + } + return o; +} +} // namespace std + +namespace kel { +namespace lbm { +namespace impl { +template <typename... T> struct unit_print { + static_assert(always_false<T...>, "Template type not supported"); +}; + +template <typename UT, int64_t UE, typename... UTL, int64_t... UEL> +struct unit_print<sch::UnitElement<UT, UE>, sch::UnitElement<UTL, UEL>...> { + static std::ostream &print(std::ostream &o) { + sch::UnitElement<UT, UE> element; + + std::ostream &o_ret = o << element; + + if constexpr (sizeof...(UTL) > 0) { + std::ostream &o_ret_next = o_ret << ' ' << '*' << ' '; + return unit_print<sch::UnitElement<UTL, UEL>...>::print(o_ret_next); + } + + return o_ret << ']'; + } +}; +} // namespace impl +} // namespace lbm +} // namespace kel + +namespace std { +template <typename StorageT, typename Encode, typename... UnitT, + int64_t... UnitE> +inline ostream & +operator<<(ostream &o, + const ::kel::lbm::data< + ::kel::lbm::sch::Unit< + StorageT, ::kel::lbm::sch::UnitElement<UnitT, UnitE>...>, + 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<UnitT, UnitE>...>::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<typename CellFieldSchema> - void apply(const saw::data<CellFieldSchema, Encode>& field, const saw::data<sch::FixedArray<sch::UInt64,Descriptor::D>>& index, saw::data<sch::UInt64> time_step)const{ + void apply(const kel::lbm::data<CellFieldSchema, Encode>& field, const kel::lbm::data<sch::FixedArray<sch::UInt64,Descriptor::D>>& index, kel::lbm::data<sch::UInt64> 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<typename CellFieldSchema> - void apply(const saw::data<CellFieldSchema, Encode>& field, const saw::data<sch::FixedArray<sch::UInt64,Descriptor::D>>& index, saw::data<sch::UInt64> time_step)const{ + void apply(const kel::lbm::data<CellFieldSchema, Encode>& field, const kel::lbm::data<sch::FixedArray<sch::UInt64,Descriptor::D>>& index, kel::lbm::data<sch::UInt64> time_step)const{ bool is_even = ((time_step.get() % 2u) == 0u); // This is a ref @@ -135,19 +135,19 @@ public: template<typename FP, typename Descriptor, typename Encode> class component<FP, Descriptor, cmpt::Equilibrium, Encode> final { private: - saw::data<sch::Scalar<FP>> density_; - saw::data<sch::Vector<FP,Descriptor::D>> momentum_; + kel::lbm::data<sch::Scalar<FP>> density_; + kel::lbm::data<sch::Vector<FP,Descriptor::D>> momentum_; public: component( - saw::data<sch::Scalar<FP>> density__, - saw::data<sch::Vector<FP,Descriptor::D>> momentum__ + kel::lbm::data<sch::Scalar<FP>> density__, + kel::lbm::data<sch::Vector<FP,Descriptor::D>> momentum__ ): density_{density__}, momentum_{momentum__} {} template<typename CellFieldSchema> - void apply(const saw::data<CellFieldSchema, Encode>& field, const saw::data<sch::FixedArray<sch::UInt64,Descriptor::D>>& index, saw::data<sch::UInt64> time_step) const { + void apply(const kel::lbm::data<CellFieldSchema, Encode>& field, const kel::lbm::data<sch::FixedArray<sch::UInt64,Descriptor::D>>& index, kel::lbm::data<sch::UInt64> time_step) const { bool is_even = ((time_step.get() % 2u) == 0u); using dfi = df_info<FP,Descriptor>; @@ -177,14 +177,14 @@ class component<FP, sch::Descriptor<2u,9u>, cmpt::ZouHePressureX<Dir>, Encode> f public: using Descriptor = sch::Descriptor<2u,9u>; private: - saw::data<FP> rho_setting_; + kel::lbm::data<FP> rho_setting_; public: - component(const saw::data<FP>& rho_setting__): + component(const kel::lbm::data<FP>& rho_setting__): rho_setting_{rho_setting__} {} template<typename CellFieldSchema> - void apply(const saw::data<CellFieldSchema, Encode>& field, saw::data<sch::FixedArray<sch::UInt64,2u>> index, saw::data<sch::UInt64> time_step) const { + void apply(const kel::lbm::data<CellFieldSchema, Encode>& field, kel::lbm::data<sch::FixedArray<sch::UInt64,2u>> index, kel::lbm::data<sch::UInt64> time_step) const { using dfi = df_info<FP,Descriptor>; 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<FP> { + auto rho_vel_x = [&]() -> kel::lbm::data<FP> { 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<FP>{2.0 / 3.0} * rho_vel_x; - dfs_old.at({6u}) = dfs_old.at({5u}) + saw::data<FP>{1.0 / 6.0} * rho_vel_x + saw::data<FP>{0.5} * (dfs_old.at({3u}) - dfs_old.at({4u})); - dfs_old.at({8u}) = dfs_old.at({7u}) + saw::data<FP>{1.0 / 6.0} * rho_vel_x + saw::data<FP>{0.5} * (dfs_old.at({4u}) - dfs_old.at({3u})); + dfs_old.at({2u}) = dfs_old.at({1u}) + kel::lbm::data<FP>{2.0 / 3.0} * rho_vel_x; + dfs_old.at({6u}) = dfs_old.at({5u}) + kel::lbm::data<FP>{1.0 / 6.0} * rho_vel_x + kel::lbm::data<FP>{0.5} * (dfs_old.at({3u}) - dfs_old.at({4u})); + dfs_old.at({8u}) = dfs_old.at({7u}) + kel::lbm::data<FP>{1.0 / 6.0} * rho_vel_x + kel::lbm::data<FP>{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<FP>{2.0 / 3.0} * rho_vel_x; - dfs_old.at({5u}) = dfs_old.at({6u}) - saw::data<FP>{1.0 / 6.0} * rho_vel_x + saw::data<FP>{0.5} * (dfs_old.at({4u}) - dfs_old.at({3u})); - dfs_old.at({7u}) = dfs_old.at({8u}) - saw::data<FP>{1.0 / 6.0} * rho_vel_x + saw::data<FP>{0.5} * (dfs_old.at({3u}) - dfs_old.at({4u})); + dfs_old.at({1u}) = dfs_old.at({2u}) - kel::lbm::data<FP>{2.0 / 3.0} * rho_vel_x; + dfs_old.at({5u}) = dfs_old.at({6u}) - kel::lbm::data<FP>{1.0 / 6.0} * rho_vel_x + kel::lbm::data<FP>{0.5} * (dfs_old.at({4u}) - dfs_old.at({3u})); + dfs_old.at({7u}) = dfs_old.at({8u}) - kel::lbm::data<FP>{1.0 / 6.0} * rho_vel_x + kel::lbm::data<FP>{0.5} * (dfs_old.at({3u}) - dfs_old.at({4u})); } } }; @@ -231,14 +231,14 @@ class component<FP, sch::Descriptor<3u,27u>, cmpt::ZouHePressureX<East>, Encode> public: using Descriptor = sch::Descriptor<3u,27u>; private: - saw::data<FP> rho_setting_; + kel::lbm::data<FP> rho_setting_; public: - component(const saw::data<FP>& rho_setting__): + component(const kel::lbm::data<FP>& rho_setting__): rho_setting_{rho_setting__} {} template<typename CellFieldSchema> - void apply(const saw::data<CellFieldSchema, Encode>& field, saw::data<sch::FixedArray<sch::UInt64,Descriptor::D>> index, saw::data<sch::UInt64> time_step) const { + void apply(const kel::lbm::data<CellFieldSchema, Encode>& field, kel::lbm::data<sch::FixedArray<sch::UInt64,Descriptor::D>> index, kel::lbm::data<sch::UInt64> time_step) const { using dfi = df_info<FP,Descriptor>; bool is_even = ((time_step.get() % 2) == 0); @@ -288,7 +288,7 @@ public: * rho*ux = S - rho */ - saw::data<FP> S; + kel::lbm::data<FP> S; if constexpr (East) { @@ -305,7 +305,7 @@ public: + f.at({24u}) // cx = +1 - + saw::data<FP>{2.0} * ( + + kel::lbm::data<FP>{2.0} * ( f.at({2u}) + f.at({5u}) + f.at({8u}) @@ -332,7 +332,7 @@ public: + f.at({24u}) // cx = -1 - + saw::data<FP>{2.0} * ( + + kel::lbm::data<FP>{2.0} * ( f.at({1u}) + f.at({4u}) + f.at({7u}) @@ -345,7 +345,7 @@ public: ); } - saw::data<FP> rho_ux; + kel::lbm::data<FP> rho_ux; if constexpr (East) { rho_ux = rho_setting_ - S; @@ -375,8 +375,8 @@ public: * + 2*x=-1 contribution */ - saw::data<FP> rho_uy; - saw::data<FP> rho_uz; + kel::lbm::data<FP> rho_uy; + kel::lbm::data<FP> rho_uz; if constexpr (East) { @@ -390,7 +390,7 @@ public: + f.at({24u}) // cx = +1 - + saw::data<FP>{2.0} * ( + + kel::lbm::data<FP>{2.0} * ( -f.at({5u}) + f.at({8u}) -f.at({14u}) @@ -409,7 +409,7 @@ public: + f.at({24u}) // cx = +1 - + saw::data<FP>{2.0} * ( + + kel::lbm::data<FP>{2.0} * ( -f.at({11u}) -f.at({14u}) -f.at({17u}) @@ -430,7 +430,7 @@ public: + f.at({24u}) // cx = -1 - + saw::data<FP>{2.0} * ( + + kel::lbm::data<FP>{2.0} * ( -f.at({4u}) + f.at({7u}) -f.at({13u}) @@ -449,7 +449,7 @@ public: +f.at({24u}) // cx = -1 - + saw::data<FP>{2.0} * ( + + kel::lbm::data<FP>{2.0} * ( -f.at({10u}) -f.at({13u}) -f.at({16u}) @@ -466,9 +466,9 @@ public: * ============================================================ */ - saw::data<FP> ux = rho_ux / rho_setting_; - saw::data<FP> uy = rho_uy / rho_setting_; - saw::data<FP> uz = rho_uz / rho_setting_; + kel::lbm::data<FP> ux = rho_ux / rho_setting_; + kel::lbm::data<FP> uy = rho_uy / rho_setting_; + kel::lbm::data<FP> uz = rho_uz / rho_setting_; /* @@ -516,7 +516,7 @@ public: f.at({1u}) = f.at({2u}) - - saw::data<FP>{1.0 / 6.0} * rho_ux; + - kel::lbm::data<FP>{1.0 / 6.0} * rho_ux; /* @@ -527,7 +527,7 @@ public: f.at({4u}) = f.at({5u}) - - saw::data<FP>{1.0 / 9.0} + - kel::lbm::data<FP>{1.0 / 9.0} * (rho_ux + rho_uy); @@ -539,7 +539,7 @@ public: f.at({7u}) = f.at({8u}) - + saw::data<FP>{1.0 / 9.0} + + kel::lbm::data<FP>{1.0 / 9.0} * (-rho_ux + rho_uy); @@ -551,7 +551,7 @@ public: f.at({10u}) = f.at({11u}) - - saw::data<FP>{1.0 / 9.0} + - kel::lbm::data<FP>{1.0 / 9.0} * (rho_ux + rho_uz); @@ -563,7 +563,7 @@ public: f.at({13u}) = f.at({14u}) - - saw::data<FP>{1.0 / 36.0} + - kel::lbm::data<FP>{1.0 / 36.0} * (rho_ux + rho_uy + rho_uz); @@ -575,7 +575,7 @@ public: f.at({16u}) = f.at({17u}) - + saw::data<FP>{1.0 / 36.0} + + kel::lbm::data<FP>{1.0 / 36.0} * (-rho_ux + rho_uy + rho_uz); @@ -587,7 +587,7 @@ public: f.at({19u}) = f.at({20u}) - + saw::data<FP>{1.0 / 9.0} + + kel::lbm::data<FP>{1.0 / 9.0} * (-rho_ux + rho_uz); @@ -599,7 +599,7 @@ public: f.at({22u}) = f.at({23u}) - + saw::data<FP>{1.0 / 36.0} + + kel::lbm::data<FP>{1.0 / 36.0} * (-rho_ux - rho_uy + rho_uz); @@ -611,7 +611,7 @@ public: f.at({25u}) = f.at({26u}) - + saw::data<FP>{1.0 / 36.0} + + kel::lbm::data<FP>{1.0 / 36.0} * (-rho_ux + rho_uy + rho_uz); } else { @@ -624,7 +624,7 @@ public: f.at({2u}) = f.at({1u}) - + saw::data<FP>{1.0 / 6.0} * rho_ux; + + kel::lbm::data<FP>{1.0 / 6.0} * rho_ux; /* @@ -635,7 +635,7 @@ public: f.at({5u}) = f.at({4u}) - + saw::data<FP>{1.0 / 9.0} + + kel::lbm::data<FP>{1.0 / 9.0} * (rho_ux - rho_uy); @@ -647,7 +647,7 @@ public: f.at({8u}) = f.at({7u}) - + saw::data<FP>{1.0 / 9.0} + + kel::lbm::data<FP>{1.0 / 9.0} * (rho_ux + rho_uy); @@ -659,7 +659,7 @@ public: f.at({11u}) = f.at({10u}) - + saw::data<FP>{1.0 / 9.0} + + kel::lbm::data<FP>{1.0 / 9.0} * (rho_ux - rho_uz); @@ -671,7 +671,7 @@ public: f.at({14u}) = f.at({13u}) - + saw::data<FP>{1.0 / 36.0} + + kel::lbm::data<FP>{1.0 / 36.0} * (rho_ux - rho_uy - rho_uz); @@ -683,7 +683,7 @@ public: f.at({17u}) = f.at({16u}) - + saw::data<FP>{1.0 / 36.0} + + kel::lbm::data<FP>{1.0 / 36.0} * (rho_ux + rho_uy - rho_uz); @@ -695,7 +695,7 @@ public: f.at({20u}) = f.at({19u}) - + saw::data<FP>{1.0 / 9.0} + + kel::lbm::data<FP>{1.0 / 9.0} * (rho_ux + rho_uz); @@ -707,7 +707,7 @@ public: f.at({23u}) = f.at({22u}) - + saw::data<FP>{1.0 / 36.0} + + kel::lbm::data<FP>{1.0 / 36.0} * (rho_ux - rho_uy + rho_uz); @@ -719,7 +719,7 @@ public: f.at({26u}) = f.at({25u}) - + saw::data<FP>{1.0 / 36.0} + + kel::lbm::data<FP>{1.0 / 36.0} * (rho_ux + rho_uy + rho_uz); } } @@ -729,16 +729,16 @@ public: template<typename T, typename Descriptor, bool East, typename Encode> class component<T, Descriptor, cmpt::ZouHeVelocityX<East>, Encode> final { private: - saw::data<sch::Vector<T,Descriptor::D>> velocity_; + kel::lbm::data<sch::Vector<T,Descriptor::D>> velocity_; public: component( - const saw::data<sch::Vector<T,Descriptor::D>>& velocity__ + const kel::lbm::data<sch::Vector<T,Descriptor::D>>& velocity__ ): velocity_{velocity__} {} template<typename CellFieldSchema> - void apply(const saw::data<CellFieldSchema, Encode>& field, const saw::data<sch::FixedArray<sch::UInt64,Descriptor::D>>& index, saw::data<sch::UInt64> time_step) const { + void apply(const kel::lbm::data<CellFieldSchema, Encode>& field, const kel::lbm::data<sch::FixedArray<sch::UInt64,Descriptor::D>>& index, kel::lbm::data<sch::UInt64> time_step) const { bool is_even = ((time_step.get() % 2u) == 0u); using dfi = df_info<T,Descriptor>; @@ -748,27 +748,27 @@ public: auto& dfs = dfs_old_f.at(index); - saw::data<T> dir_sum; + kel::lbm::data<T> 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<sch::Scalar<T>> rho; - rho.at({}) = (dfs.at({0u}) + dfs.at({4u}) + dfs.at({3u}) + dir_sum * 2) / (velocity_.at({{0u}}) + saw::data<T>{static_cast<saw::native_data_type<T>::type>(1.0)}); + kel::lbm::data<sch::Scalar<T>> rho; + rho.at({}) = (dfs.at({0u}) + dfs.at({4u}) + dfs.at({3u}) + dir_sum * 2) / (velocity_.at({{0u}}) + kel::lbm::data<T>{static_cast<kel::lbm::native_data_type<T>::type>(1.0)}); if constexpr (East) { - dfs.at({2u}) = dfs.at({1u}) + saw::data<T>{static_cast<saw::native_data_type<T>::type>(2.0 / 3.0)} * rho.at({}) * velocity_.at({{0u}}); - dfs.at({6u}) = dfs.at({5u}) + saw::data<T>{static_cast<saw::native_data_type<T>::type>(1.0 / 6.0)} * rho.at({}) * velocity_.at({{0u}}) + dfs.at({2u}) = dfs.at({1u}) + kel::lbm::data<T>{static_cast<kel::lbm::native_data_type<T>::type>(2.0 / 3.0)} * rho.at({}) * velocity_.at({{0u}}); + dfs.at({6u}) = dfs.at({5u}) + kel::lbm::data<T>{static_cast<kel::lbm::native_data_type<T>::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<T>{static_cast<saw::native_data_type<T>::type>(1.0 / 6.0)} * rho.at({}) * velocity_.at({{0u}}) + dfs.at({8u}) = dfs.at({7u}) + kel::lbm::data<T>{static_cast<kel::lbm::native_data_type<T>::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<T>{static_cast<saw::native_data_type<T>::type>(2.0 / 3.0)} * rho.at({}) * velocity_.at({{0u}}); - dfs.at({5u}) = dfs.at({6u}) + saw::data<T>{static_cast<saw::native_data_type<T>::type>(1.0 / 6.0)} * rho.at({}) * velocity_.at({{0u}}) + dfs.at({1u}) = dfs.at({2u}) + kel::lbm::data<T>{static_cast<kel::lbm::native_data_type<T>::type>(2.0 / 3.0)} * rho.at({}) * velocity_.at({{0u}}); + dfs.at({5u}) = dfs.at({6u}) + kel::lbm::data<T>{static_cast<kel::lbm::native_data_type<T>::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<T>{static_cast<saw::native_data_type<T>::type>(1.0 / 6.0)} * rho.at({}) * velocity_.at({{0u}}) + dfs.at({7u}) = dfs.at({8u}) + kel::lbm::data<T>{static_cast<kel::lbm::native_data_type<T>::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<typename Sch, uint64_t Ghost, typename LeftG, typename RightG = saw::tmpl_value_group<uint64_t>> +template<typename Sch, uint64_t Ghost, typename LeftG, typename RightG = kel::lbm::tmpl_value_group<uint64_t>> struct chunk_schema_type_helper; template<typename Sch, uint64_t Ghost, uint64_t Side0, uint64_t... Sides, uint64_t... AddedSides> -struct chunk_schema_type_helper<Sch, Ghost, saw::tmpl_value_group<uint64_t,Side0,Sides...>, saw::tmpl_value_group<uint64_t,AddedSides...>> final { - using Schema = typename chunk_schema_type_helper<Sch,Ghost,saw::tmpl_value_group<uint64_t,Sides...>, saw::tmpl_value_group<uint64_t,AddedSides...,(Side0+2u*(Ghost))>>::Schema; +struct chunk_schema_type_helper<Sch, Ghost, kel::lbm::tmpl_value_group<uint64_t,Side0,Sides...>, kel::lbm::tmpl_value_group<uint64_t,AddedSides...>> final { + using Schema = typename chunk_schema_type_helper<Sch,Ghost,kel::lbm::tmpl_value_group<uint64_t,Sides...>, kel::lbm::tmpl_value_group<uint64_t,AddedSides...,(Side0+2u*(Ghost))>>::Schema; }; template<typename Sch, uint64_t Ghost, uint64_t... AddedSides> -struct chunk_schema_type_helper<Sch, Ghost, saw::tmpl_value_group<uint64_t>, saw::tmpl_value_group<uint64_t,AddedSides...>> final { +struct chunk_schema_type_helper<Sch, Ghost, kel::lbm::tmpl_value_group<uint64_t>, kel::lbm::tmpl_value_group<uint64_t,AddedSides...>> final { using Schema = FixedArray<Sch,AddedSides...>; }; } @@ -24,7 +24,13 @@ struct chunk_schema_type_helper<Sch, Ghost, saw::tmpl_value_group<uint64_t>, saw template<typename Sch, uint64_t Ghost, uint64_t... Sides> struct Chunk { - using InnerSchema = typename impl::chunk_schema_type_helper<Sch, Ghost, saw::tmpl_value_group<uint64_t,Sides...>>::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<Sch, Ghost, kel::lbm::tmpl_value_group<uint64_t,Sides...>>::Schema; using StoredValueSchema = Sch; }; @@ -35,7 +41,8 @@ using SuperChunk = Array<ChunkSchema,Dim>; } } -namespace saw { +namespace kel { +namespace lbm { template<typename Sch, uint64_t Ghost, uint64_t... Sides, typename Encode> class data<kel::lbm::sch::Chunk<Sch,Ghost,Sides...>,Encode> final { @@ -47,11 +54,11 @@ private: data<InnerSchema, Encode> values_; public: - data<ValueSchema, Encode>& ghost_at(const data<schema::FixedArray<schema::UInt64,sizeof...(Sides)>>& index){ + data<ValueSchema, Encode>& ghost_at(const data<sch::FixedArray<sch::UInt64,sizeof...(Sides)>>& index){ return values_.at(index); } - const data<ValueSchema, Encode>& ghost_at(const data<schema::FixedArray<schema::UInt64,sizeof...(Sides)>>& index) const { + const data<ValueSchema, Encode>& ghost_at(const data<sch::FixedArray<sch::UInt64,sizeof...(Sides)>>& index) const { return values_.at(index); } @@ -59,7 +66,7 @@ public: return data<InnerSchema,Encode>::get_dims(); } - static constexpr auto to_ghost_index(const data<schema::FixedArray<schema::UInt64,sizeof...(Sides)>>& index){ + static constexpr auto to_ghost_index(const data<sch::FixedArray<sch::UInt64,sizeof...(Sides)>>& index){ std::decay_t<decltype(index)> 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<ValueSchema, Encode>& at(const data<schema::FixedArray<schema::UInt64,sizeof...(Sides)>>& index){ + data<ValueSchema, Encode>& at(const data<sch::FixedArray<sch::UInt64,sizeof...(Sides)>>& index){ std::decay_t<decltype(index)> ind = to_ghost_index(index); return values_.at(ind); } - const data<ValueSchema, Encode>& at(const data<schema::FixedArray<schema::UInt64,sizeof...(Sides)>>& index) const { + const data<ValueSchema, Encode>& at(const data<sch::FixedArray<sch::UInt64,sizeof...(Sides)>>& index) const { std::decay_t<decltype(index)> ind = to_ghost_index(index); return values_.at(ind); } /* - const data<ValueSchema, Encode>& neighbour_at(const data<schema::FixedArray<schema::UInt64,sizeof...(Sides)>>& index) const { + const data<ValueSchema, Encode>& neighbour_at(const data<sch::FixedArray<sch::UInt64,sizeof...(Sides)>>& index) const { } */ static constexpr auto get_dims(){ - return data<schema::FixedArray<schema::UInt64, sizeof...(Sides)>,Encode>{{Sides...}}; + return data<sch::FixedArray<sch::UInt64, sizeof...(Sides)>,Encode>{{Sides...}}; } auto flat_data(){ @@ -101,3 +108,4 @@ struct meta_schema<kel::lbm::sch::Chunk<Sch,Ghost,Sides...>> { }; } +} 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<typename T, typename Descriptor, typename Encode> class component<T, Descriptor, cmpt::BGK, Encode> { private: - saw::data<T> relaxation_; - saw::data<T> frequency_; + kel::lbm::data<T> relaxation_; + kel::lbm::data<T> frequency_; public: - component(typename saw::native_data_type<T>::type relaxation__): + component(typename kel::lbm::native_data_type<T>::type relaxation__): relaxation_{{relaxation__}}, - frequency_{saw::data<T>{1} / relaxation_} + frequency_{kel::lbm::data<T>{1} / relaxation_} {} - component(const saw::data<T>& relaxation__): + component(const kel::lbm::data<T>& relaxation__): relaxation_{relaxation__}, - frequency_{saw::data<T>{1} / relaxation_} + frequency_{kel::lbm::data<T>{1} / relaxation_} {} - component(const saw::data<sch::Pure<T>>& relaxation__): + component(const kel::lbm::data<sch::Pure<T>>& relaxation__): relaxation_{relaxation__.handle()}, - frequency_{saw::data<T>{typename saw::native_data_type<T>::type(1)} / relaxation_} + frequency_{kel::lbm::data<T>{typename kel::lbm::native_data_type<T>::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<typename CellFieldSchema> - void apply(const saw::data<CellFieldSchema, Encode>& field, saw::data<sch::FixedArray<sch::UInt64,Descriptor::D>> index, saw::data<sch::UInt64> time_step) const { + void apply(const kel::lbm::data<CellFieldSchema, Encode>& field, kel::lbm::data<sch::FixedArray<sch::UInt64,Descriptor::D>> index, kel::lbm::data<sch::UInt64> 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<sch::Scalar<T>> rho; - saw::data<sch::Vector<T,Descriptor::D>> vel; + kel::lbm::data<sch::Scalar<T>> rho; + kel::lbm::data<sch::Vector<T,Descriptor::D>> vel; compute_rho_u<T,Descriptor>(dfs_old_f.at(index),rho,vel); auto eq = equilibrium<T,Descriptor>(rho,vel); @@ -74,7 +74,7 @@ public: } template<typename CellFieldSchema, typename MacroFieldSchema> - void apply(const saw::data<CellFieldSchema, Encode>& field, const saw::data<MacroFieldSchema,Encode>& macros, saw::data<sch::FixedArray<sch::UInt64,Descriptor::D>> index, saw::data<sch::UInt64> time_step) const { + void apply(const kel::lbm::data<CellFieldSchema, Encode>& field, const kel::lbm::data<MacroFieldSchema,Encode>& macros, kel::lbm::data<sch::FixedArray<sch::UInt64,Descriptor::D>> index, kel::lbm::data<sch::UInt64> 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<sch::Scalar<T>>& rho = rho_f.at(index); - saw::data<sch::Vector<T,Descriptor::D>>& vel = vel_f.at(index); + kel::lbm::data<sch::Scalar<T>>& rho = rho_f.at(index); + kel::lbm::data<sch::Vector<T,Descriptor::D>>& vel = vel_f.at(index); compute_rho_u<T,Descriptor>(dfs_old_f.at(index),rho,vel); @@ -99,22 +99,22 @@ public: template<typename T, typename Descriptor, typename Encode> class component<T, Descriptor, cmpt::BGKGuo, Encode> { private: - typename saw::native_data_type<T>::type relaxation_; - saw::data<T> frequency_; - saw::data<sch::Vector<T,Descriptor::D>> global_force_; + typename kel::lbm::native_data_type<T>::type relaxation_; + kel::lbm::data<T> frequency_; + kel::lbm::data<sch::Vector<T,Descriptor::D>> global_force_; public: - component(typename saw::native_data_type<T>::type relaxation__): + component(typename kel::lbm::native_data_type<T>::type relaxation__): relaxation_{relaxation__}, - frequency_{typename saw::native_data_type<T>::type(1) / relaxation_}, + frequency_{typename kel::lbm::native_data_type<T>::type(1) / relaxation_}, global_force_{} {} component( - typename saw::native_data_type<T>::type relaxation__, - saw::data<sch::Vector<T,Descriptor::D>>& global_force__ + typename kel::lbm::native_data_type<T>::type relaxation__, + kel::lbm::data<sch::Vector<T,Descriptor::D>>& global_force__ ): relaxation_{relaxation__}, - frequency_{typename saw::native_data_type<T>::type(1) / relaxation_}, + frequency_{typename kel::lbm::native_data_type<T>::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<typename CellFieldSchema, typename MacroFieldSchema> - void apply(const saw::data<CellFieldSchema, Encode>& field, const saw::data<MacroFieldSchema,Encode>& macros, saw::data<sch::FixedArray<sch::UInt64,Descriptor::D>> index, saw::data<sch::UInt64> time_step) const { - // void apply(saw::data<CellFieldSchema, Encode>& field, saw::data<sch::FixedArray<sch::UInt64, Descriptor::D>> index, saw::data<sch::UInt64> time_step){ + void apply(const kel::lbm::data<CellFieldSchema, Encode>& field, const kel::lbm::data<MacroFieldSchema,Encode>& macros, kel::lbm::data<sch::FixedArray<sch::UInt64,Descriptor::D>> index, kel::lbm::data<sch::UInt64> time_step) const { + // void apply(kel::lbm::data<CellFieldSchema, Encode>& field, kel::lbm::data<sch::FixedArray<sch::UInt64, Descriptor::D>> index, kel::lbm::data<sch::UInt64> 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<sch::Scalar<T>>& rho = rho_f.at(index); + kel::lbm::data<sch::Scalar<T>>& 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<sch::Scalar<T>> half; + kel::lbm::data<sch::Scalar<T>> 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<T,Descriptor>; - saw::data<sch::Scalar<T>> dfi_inv_cs2; + kel::lbm::data<sch::Scalar<T>> 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<T> ci_min_u{0}; - saw::data<sch::Vector<T,Descriptor::D>> ci; + // kel::lbm::data<T> ci_min_u{0}; + kel::lbm::data<sch::Vector<T,Descriptor::D>> ci; for(uint64_t d = 0u; d < Descriptor::D; ++d){ - ci.at({{d}}).set(static_cast<typename saw::native_data_type<T>::type>(dfi::directions[i][d])); + ci.at({{d}}).set(static_cast<typename kel::lbm::native_data_type<T>::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<sch::Vector<T,Descriptor::D>> F_i; + // kel::lbm::data<sch::Vector<T,Descriptor::D>> F_i; // F_i = f * ((c_i - u) * ics2 + <c_i,u> * c_i * ics2 * ics2) * w_i; - saw::data<sch::Scalar<T>> w; + kel::lbm::data<sch::Scalar<T>> w; w.at({}).set(dfi::weights[i]); /* - saw::data<sch::Scalar<T>> F_i_sum; + kel::lbm::data<sch::Scalar<T>> F_i_sum; for(uint64_t d = 0u; d < Descriptor::D; ++d){ - saw::data<sch::Scalar<T>> F_i_d; + kel::lbm::data<sch::Scalar<T>> 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<T>{1} - saw::data<T>{0.5f} * frequency_); + * (kel::lbm::data<T>{1} - kel::lbm::data<T>{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 <forstio/codec/data.hpp> -#include <forstio/codec/math.hpp> +#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<saw::string_literal Name, uint64_t Dist, bool Read, bool Write, bool SkipSync = false> +template<kel::lbm::string_literal Name, uint64_t Dist, bool Read, bool Write, bool SkipSync = false> 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<typename T, typename Descriptor, typename Cmpt, typename Encode = saw::encode::Native> +template<typename T, typename Descriptor, typename Cmpt, typename Encode = kel::lbm::enc::Native> 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<typename T, typename Descriptor, typename Encode> class component<T, Descriptor, cmpt::PSM, Encode> { private: - saw::data<T> relaxation_; - saw::data<T> frequency_; + kel::lbm::data<T> relaxation_; + kel::lbm::data<T> frequency_; public: component( - typename saw::native_data_type<T>::type relaxation__ + typename kel::lbm::native_data_type<T>::type relaxation__ ): relaxation_{relaxation__} { - saw::data<T> one; + kel::lbm::data<T> one; one = 1.0; frequency_ = one / relaxation_; } template<typename CellFieldSchema, typename MacroFieldSchema> - void apply(const saw::data<CellFieldSchema, Encode>& field, const saw::data<MacroFieldSchema,Encode>& macros, saw::data<sch::FixedArray<sch::UInt64,Descriptor::D>> index, saw::data<sch::UInt64> time_step) const { + void apply(const kel::lbm::data<CellFieldSchema, Encode>& field, const kel::lbm::data<MacroFieldSchema,Encode>& macros, kel::lbm::data<sch::FixedArray<sch::UInt64,Descriptor::D>> index, kel::lbm::data<sch::UInt64> time_step) const { using dfi = df_info<T,Descriptor>; 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<sch::Scalar<T>>& rho = rho_f.at(index); - saw::data<sch::Vector<T,Descriptor::D>>& vel = vel_f.at(index); + kel::lbm::data<sch::Scalar<T>>& rho = rho_f.at(index); + kel::lbm::data<sch::Vector<T,Descriptor::D>>& vel = vel_f.at(index); compute_rho_u<T,Descriptor>(dfs_old_f.at(index),rho,vel); auto eq = equilibrium<T,Descriptor>(rho,vel); - saw::data<T> one{1.0}; + kel::lbm::data<T> 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 <forstio/codec/data.hpp> -#include <forstio/codec/json/json.hpp> +#include "abstract/data.hpp" +#include "abstract/json.hpp" #include <fstream> +#include <iterator> #include <sstream> #include <string_view> #include <string> @@ -11,7 +12,6 @@ namespace kel { namespace lbm { namespace sch { -using namespace saw::schema; template<typename T, typename Desc> using LbmConfig = Struct< Member<T, "delta_x">, @@ -21,25 +21,26 @@ using LbmConfig = Struct< } template<typename T, typename Desc> -saw::error_or<saw::data<sch::LbmConfig<T,Desc>>> load_lbm_config(std::string_view file_name){ - std::ifstream file{std::string{file_name}}; +error_or<data<sch::LbmConfig<T,Desc>>> 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<saw::err::not_found>("Couldn't open file"); + return make_error<err::not_found>("Couldn't open file"); } - saw::data<sch::LbmConfig<T,Desc>, saw::encode::Json> lbm_json_conf{saw::heap<saw::array_buffer>(1u)}; + std::string contents{ + std::istreambuf_iterator<char>{file}, + std::istreambuf_iterator<char>{} + }; - uint8_t ele{}; - while(file.readsome(reinterpret_cast<char*>(&ele), 1u) > 0u){ - auto err = lbm_json_conf.get_buffer().push(ele,1u); - if(err.failed()){ - return err; - } + if(file.bad()){ + return make_error<err::invalid_state>("Couldn't read file"); } - saw::data<sch::LbmConfig<T,Desc>> lbm_conf; - saw::codec<sch::LbmConfig<T,Desc>, saw::encode::Json> json_codec; + data<sch::LbmConfig<T,Desc>, enc::Json> lbm_json_conf{std::move(contents)}; + + data<sch::LbmConfig<T,Desc>> lbm_conf; + codec<sch::LbmConfig<T,Desc>, 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<typename T> class converter { private: - saw::data<typename saw::unit_division<sch::SiMeter<T>, sch::LbmMeter<T> >::Schema > meter_conv_; - saw::data<typename saw::unit_division<sch::SiSecond<T>, sch::LbmSecond<T> >::Schema > second_conv_; + kel::lbm::data<typename kel::lbm::unit_division<sch::SiMeter<T>, sch::LbmMeter<T> >::Schema > meter_conv_; + kel::lbm::data<typename kel::lbm::unit_division<sch::SiSecond<T>, sch::LbmSecond<T> >::Schema > second_conv_; public: converter() = delete; converter( - saw::data<typename saw::unit_division<sch::SiMeter<T>, sch::LbmMeter<T> >::Schema > meter_conv__, - saw::data<typename saw::unit_division<sch::SiSecond<T>, sch::LbmSecond<T> >::Schema > second_conv__ + kel::lbm::data<typename kel::lbm::unit_division<sch::SiMeter<T>, sch::LbmMeter<T> >::Schema > meter_conv__, + kel::lbm::data<typename kel::lbm::unit_division<sch::SiSecond<T>, sch::LbmSecond<T> >::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<sch::LbmMeter<T>>{1.0}; + return meter_conv_*kel::lbm::data<sch::LbmMeter<T>>{1.0}; } auto delta_t() const { - return second_conv_*saw::data<sch::LbmSecond<T>>{1.0}; + return second_conv_*kel::lbm::data<sch::LbmSecond<T>>{1.0}; } auto delta_v() const { - return (meter_conv_ / second_conv_) * saw::data<sch::LbmVelocity<T>>{1.0}; + return (meter_conv_ / second_conv_) * kel::lbm::data<sch::LbmVelocity<T>>{1.0}; } auto delta_a() const { - return (meter_conv_ / (second_conv_*second_conv_)) * saw::data<sch::LbmAcceleration<T>>{1.0}; + return (meter_conv_ / (second_conv_*second_conv_)) * kel::lbm::data<sch::LbmAcceleration<T>>{1.0}; } - saw::data<sch::LbmMeter<T>> meter_si_to_lbm(const saw::data<sch::SiMeter<T>>& m_si) const { + kel::lbm::data<sch::LbmMeter<T>> meter_si_to_lbm(const kel::lbm::data<sch::SiMeter<T>>& m_si) const { return m_si / meter_conv_; } - saw::data<sch::SiMeter<T>> meter_lbm_to_si(const saw::data<sch::LbmMeter<T>>& m_lbm) const { + kel::lbm::data<sch::SiMeter<T>> meter_lbm_to_si(const kel::lbm::data<sch::LbmMeter<T>>& m_lbm) const { return m_lbm * meter_conv_; } - saw::data<sch::LbmSecond<T>> second_si_to_lbm(const saw::data<sch::SiSecond<T>>& s_si) const { + kel::lbm::data<sch::LbmSecond<T>> second_si_to_lbm(const kel::lbm::data<sch::SiSecond<T>>& s_si) const { return s_si / second_conv_; } - saw::data<sch::LbmVelocity<T>> velocity_si_to_lbm(const saw::data<sch::SiVelocity<T>>& vel_si) const { + kel::lbm::data<sch::LbmVelocity<T>> velocity_si_to_lbm(const kel::lbm::data<sch::SiVelocity<T>>& vel_si) const { return (vel_si / meter_conv_) * second_conv_; } - saw::data<sch::LbmAcceleration<T>> acceleration_si_to_lbm(const saw::data<sch::SiAcceleration<T>>& acc_si) const { + kel::lbm::data<sch::LbmAcceleration<T>> acceleration_si_to_lbm(const kel::lbm::data<sch::SiAcceleration<T>>& acc_si) const { return (acc_si / meter_conv_) * (second_conv_ * second_conv_); } - saw::data<sch::LbmKinematicViscosity<T>> kinematic_viscosity_si_to_lbm (const saw::data<sch::SiKinematicViscosity<T>>& kin_si) const { + kel::lbm::data<sch::LbmKinematicViscosity<T>> kinematic_viscosity_si_to_lbm (const kel::lbm::data<sch::SiKinematicViscosity<T>>& kin_si) const { return (kin_si / (meter_conv_ * meter_conv_)) * second_conv_; } template<typename Desc> - saw::data<sch::Pure<T>> kinematic_viscosity_si_to_tau(const saw::data<sch::SiKinematicViscosity<T>>& kin_si) const { - return saw::data<sch::Pure<T>>{saw::data<typename saw::unit_division<sch::Pure<T>, sch::LbmKinematicViscosity<T>>::Schema >{df_info<T,Desc>::inv_cs2} * kinematic_viscosity_si_to_lbm(kin_si) + saw::data<sch::Pure<T>>{0.5}}; + kel::lbm::data<sch::Pure<T>> kinematic_viscosity_si_to_tau(const kel::lbm::data<sch::SiKinematicViscosity<T>>& kin_si) const { + return kel::lbm::data<sch::Pure<T>>{kel::lbm::data<typename kel::lbm::unit_division<sch::Pure<T>, sch::LbmKinematicViscosity<T>>::Schema >{df_info<T,Desc>::inv_cs2} * kinematic_viscosity_si_to_lbm(kin_si) + kel::lbm::data<sch::Pure<T>>{0.5}}; } template<typename Desc> - saw::data<sch::Pure<T>> kinematic_viscosity_lbm_to_tau(const saw::data<sch::LbmKinematicViscosity<T>>& kin_lbm) const { - return saw::data<sch::Pure<T>>{saw::data<typename saw::unit_division<sch::Pure<T>, sch::LbmKinematicViscosity<T>>::Schema >{df_info<T,Desc>::inv_cs2} * kin_lbm + saw::data<sch::Pure<T>>{0.5}}; + kel::lbm::data<sch::Pure<T>> kinematic_viscosity_lbm_to_tau(const kel::lbm::data<sch::LbmKinematicViscosity<T>>& kin_lbm) const { + return kel::lbm::data<sch::Pure<T>>{kel::lbm::data<typename kel::lbm::unit_division<sch::Pure<T>, sch::LbmKinematicViscosity<T>>::Schema >{df_info<T,Desc>::inv_cs2} * kin_lbm + kel::lbm::data<sch::Pure<T>>{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 <forstio/codec/data.hpp> -#include <forstio/codec/data_math.hpp> -#include <forstio/codec/schema_factory.hpp> +#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<typename Sch, typename Desc, uint64_t SC_V, uint64_t DC_V, uint64_t QC_V> 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<typename Desc, typename Cell> struct CellField{ + /// A field is laid out over the grid, so the grid extents are its metadata. + using Meta = FixedArray<UInt64, Desc::D>; using Descriptor = Desc; }; -template<typename Desc, typename... CellFieldTypes, saw::string_literal... CellFieldNames> +template<typename Desc, typename... CellFieldTypes, kel::lbm::string_literal... CellFieldNames> struct CellField< Desc, Struct< Member<CellFieldTypes, CellFieldNames>... > > { + using Meta = FixedArray<UInt64, Desc::D>; using Descriptor = Desc; }; template<typename Desc, typename... CellFieldMembers> struct CellFieldStruct { + using Meta = FixedArray<UInt64, Desc::D>; using Descriptor = Desc; - // using MetaSchema = FixedArray<UInt64, Desc::D>; }; } @@ -66,16 +70,16 @@ struct df_ct_helper { template<typename Schema> class cell_schema_builder { private: - saw::schema_factory<Schema> factory_struct_; + kel::lbm::schema_factory<Schema> factory_struct_; public: cell_schema_builder() = default; - cell_schema_builder(saw::schema_factory<Schema> inp): + cell_schema_builder(kel::lbm::schema_factory<Schema> inp): factory_struct_{inp} {} /* - template<typename TA, saw::string_literal KA> + template<typename TA, kel::lbm::string_literal KA> constexpr auto require() const noexcept { return {factory_struct_.add_maybe()}; } @@ -85,23 +89,24 @@ public: } } -namespace saw { +namespace kel { +namespace lbm { template<typename T, typename Desc, uint64_t S, uint64_t D, uint64_t Q> struct meta_schema<kel::lbm::sch::Cell<T,Desc,S,D,Q>> { - using MetaSchema = schema::Void; + using MetaSchema = sch::Void; using Schema = kel::lbm::sch::Cell<T,Desc,S,D,Q>; }; template<typename Desc, typename CellT> struct meta_schema<kel::lbm::sch::CellField<Desc, CellT>> { - using MetaSchema = schema::FixedArray<schema::UInt64,Desc::D>; + using MetaSchema = sch::FixedArray<sch::UInt64,Desc::D>; using Schema = kel::lbm::sch::CellField<Desc, CellT>; }; template<typename Desc, typename... CellFieldsT> -struct meta_schema<kel::lbm::sch::CellFieldStruct<Desc,schema::Struct<CellFieldsT...>>> { - using MetaSchema = schema::FixedArray<schema::UInt64,Desc::D>; - using Schema = kel::lbm::sch::CellFieldStruct<Desc,schema::Struct<CellFieldsT...>>; +struct meta_schema<kel::lbm::sch::CellFieldStruct<Desc,sch::Struct<CellFieldsT...>>> { + using MetaSchema = sch::FixedArray<sch::UInt64,Desc::D>; + using Schema = kel::lbm::sch::CellFieldStruct<Desc,sch::Struct<CellFieldsT...>>; }; template<typename Sch, typename Desc, uint64_t S, uint64_t D, uint64_t Q, typename Encode> @@ -110,15 +115,15 @@ public: using Schema = kel::lbm::sch::Cell<Sch,Desc,S,D,Q>; using MetaSchema = typename meta_schema<Schema>::MetaSchema; private: - data<schema::FixedArray<Sch, Schema::Size>, Encode> inner_; + data<sch::FixedArray<Sch, Schema::Size>, Encode> inner_; public: data() = default; - data<Sch, Encode>& operator()(const data<schema::UInt64>& index){ + data<Sch, Encode>& operator()(const data<sch::UInt64>& index){ return inner_.at(index); } - const data<Sch, Encode>& operator()(const data<schema::UInt64>& index)const{ + const data<Sch, Encode>& operator()(const data<sch::UInt64>& index)const{ return inner_.at(index); } @@ -136,7 +141,7 @@ public: using Schema = kel::lbm::sch::CellField<Desc,CellT>; using MetaSchema = typename meta_schema<Schema>::MetaSchema; private: - data<schema::Array<CellT,Desc::D>, Encode> inner_; + data<sch::Array<CellT,Desc::D>, Encode> inner_; public: data() = default; data(const data<MetaSchema,Encode>& inner_meta__): @@ -148,28 +153,28 @@ public: } template<uint64_t i> - data<schema::UInt64,Encode> get_dim_size() const { + data<sch::UInt64,Encode> get_dim_size() const { static_assert(i < Desc::D, "Not enough dimensions"); return inner_.template get_dim_size<i>(); } - const data<CellT>& operator()(const data<schema::FixedArray<schema::UInt64, Desc::D>, Encode>& index)const{ + const data<CellT>& operator()(const data<sch::FixedArray<sch::UInt64, Desc::D>, Encode>& index)const{ return inner_.at(index); } - data<CellT>& operator()(const data<schema::FixedArray<schema::UInt64, Desc::D>, Encode>& index){ + data<CellT>& operator()(const data<sch::FixedArray<sch::UInt64, Desc::D>, Encode>& index){ return inner_.at(index); } - const data<CellT>& at(const data<schema::FixedArray<schema::UInt64, Desc::D>, Encode>& index)const{ + const data<CellT>& at(const data<sch::FixedArray<sch::UInt64, Desc::D>, Encode>& index)const{ return inner_.at(index); } - data<CellT>& at(const data<schema::FixedArray<schema::UInt64, Desc::D>, Encode>& index){ + data<CellT>& at(const data<sch::FixedArray<sch::UInt64, Desc::D>, Encode>& index){ return inner_.at(index); } - data<schema::UInt64,Encode> internal_size() const { + data<sch::UInt64,Encode> 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<typename Desc, typename... CellFieldsT, typename Encode> -class data<kel::lbm::sch::CellFieldStruct<Desc, schema::Struct<CellFieldsT...>>, Encode> final { +class data<kel::lbm::sch::CellFieldStruct<Desc, sch::Struct<CellFieldsT...>>, Encode> final { public: - using Schema = kel::lbm::sch::CellFieldStruct<Desc,schema::Struct<CellFieldsT...>>; + using Schema = kel::lbm::sch::CellFieldStruct<Desc,sch::Struct<CellFieldsT...>>; /// @TODO Add MetaSchema to Schema using MetaSchema = typename meta_schema<Schema>::MetaSchema; private: static_assert(sizeof...(CellFieldsT) > 0u, ""); - data<schema::Struct<CellFieldsT...>, Encode> inner_; + data<sch::Struct<CellFieldsT...>, Encode> inner_; template<uint64_t i> - saw::error_or<void> helper_constructor(const data<schema::FixedArray<schema::UInt64,Desc::D>>& grid_size){ - using MemT = saw::parameter_pack_type<i,CellFieldsT...>::type; + kel::lbm::error_or<void> helper_constructor(const data<sch::FixedArray<sch::UInt64,Desc::D>>& grid_size){ + using MemT = kel::lbm::parameter_pack_type<i,CellFieldsT...>::type; { inner_.template get<MemT::KeyLiteral>() = {grid_size}; } if constexpr (sizeof...(CellFieldsT) > (i+1u)){ return helper_constructor<i+1u>(grid_size); } - return saw::make_void(); + return kel::lbm::make_void(); } public: data() = delete; - data(const data<schema::FixedArray<schema::UInt64,Desc::D>>& grid_size__){ + data(const data<sch::FixedArray<sch::UInt64,Desc::D>>& grid_size__){ auto eov = helper_constructor<0u>(grid_size__); (void)eov; } const data<MetaSchema, Encode> 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<MemT::KeyLiteral>().meta(); } - template<saw::string_literal Key> + template<kel::lbm::string_literal Key> auto& get() { return inner_.template get<Key>(); } - template<saw::string_literal Key> + template<kel::lbm::string_literal Key> const auto& get() const { return inner_.template get<Key>(); } @@ -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<uint64_t DV, uint64_t QV> 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<typename saw::native_data_type<T>::type, Q> weights = { + static constexpr std::array<typename kel::lbm::native_data_type<T>::type, Q> weights = { 2./3., 1./6., 1./6. @@ -32,8 +32,8 @@ public: 0,2,1 }; - static constexpr typename saw::native_data_type<T>::type inv_cs2 = 3.0; - static constexpr typename saw::native_data_type<T>::type cs2 = 1./3.; + static constexpr typename kel::lbm::native_data_type<T>::type inv_cs2 = 3.0; + static constexpr typename kel::lbm::native_data_type<T>::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<typename saw::native_data_type<T>::type,Q> weights = { + static constexpr std::array<typename kel::lbm::native_data_type<T>::type,Q> weights = { 1./3., 1./6., 1./6., @@ -39,8 +39,8 @@ public: }; */ - static constexpr typename saw::native_data_type<T>::type inv_cs2 = 3.0; - static constexpr typename saw::native_data_type<T>::type cs2 = 1./3.; + static constexpr typename kel::lbm::native_data_type<T>::type inv_cs2 = 3.0; + static constexpr typename kel::lbm::native_data_type<T>::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<typename saw::native_data_type<T>::type,Q> weights = { + static constexpr std::array<typename kel::lbm::native_data_type<T>::type,Q> weights = { 1./3., 1./6., 1./6., @@ -40,8 +40,8 @@ public: 3 }; - static constexpr typename saw::native_data_type<T>::type inv_cs2 = 3.0; - static constexpr typename saw::native_data_type<T>::type cs2 = 1./3.; + static constexpr typename kel::lbm::native_data_type<T>::type inv_cs2 = 3.0; + static constexpr typename kel::lbm::native_data_type<T>::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<typename saw::native_data_type<T>::type,Q> weights = { + static constexpr std::array<typename kel::lbm::native_data_type<T>::type,Q> weights = { 4./9., 1./9., 1./9., @@ -52,8 +52,8 @@ public: 7 }; - static constexpr typename saw::native_data_type<T>::type inv_cs2 = 3.0; - static constexpr typename saw::native_data_type<T>::type cs2 = 1./3.; + static constexpr typename kel::lbm::native_data_type<T>::type inv_cs2 = 3.0; + static constexpr typename kel::lbm::native_data_type<T>::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<typename saw::native_data_type<T>::type,Q> weights = { + static constexpr std::array<typename kel::lbm::native_data_type<T>::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<T>::type inv_cs2 = 3.0; - static constexpr typename saw::native_data_type<T>::type cs2 = 1./3.; + static constexpr typename kel::lbm::native_data_type<T>::type inv_cs2 = 3.0; + static constexpr typename kel::lbm::native_data_type<T>::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<typename saw::native_data_type<T>::type,Q> weights = { + static constexpr std::array<typename kel::lbm::native_data_type<T>::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<T>::type inv_cs2 = 3.0; - static constexpr typename saw::native_data_type<T>::type cs2 = 1./3.; + static constexpr typename kel::lbm::native_data_type<T>::type inv_cs2 = 3.0; + static constexpr typename kel::lbm::native_data_type<T>::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 <forstio/error.hpp> +#include "abstract/error.hpp" #include <filesystem> #include <cstdlib> @@ -18,7 +18,7 @@ public: }; template<typename ArgSch> -saw::error_or<environment> init_lbm_env(const saw::data<ArgSch>& args){ +kel::lbm::error_or<environment> init_lbm_env(const kel::lbm::data<ArgSch>& args){ namespace fs = std::filesystem; auto& args_n = args.template get<"args">(); @@ -26,7 +26,7 @@ saw::error_or<environment> init_lbm_env(const saw::data<ArgSch>& args){ const char* home_dir = std::getenv("HOME"); if(not home_dir){ - return saw::make_error<saw::err::not_found>("Couldn't find home dir"); + return kel::lbm::make_error<kel::lbm::err::not_found>("Couldn't find home dir"); } environment env; @@ -62,12 +62,12 @@ saw::error_or<environment> init_lbm_env(const saw::data<ArgSch>& 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<std::filesystem::path> output_directory(){ +kel::lbm::error_or<std::filesystem::path> output_directory(){ namespace fs = std::filesystem; const char* home_dir = std::getenv("HOME"); if(not home_dir){ - return saw::make_error<saw::err::not_found>("Couldn't find home dir"); + return kel::lbm::make_error<kel::lbm::err::not_found>("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<typename T, typename Descriptor> -saw::data<sch::FixedArray<T, Descriptor::Q>> equilibrium(saw::data<sch::Scalar<T>> rho, saw::data<sch::Vector<T,Descriptor::D>> vel){ +kel::lbm::data<sch::FixedArray<T, Descriptor::Q>> equilibrium(kel::lbm::data<sch::Scalar<T>> rho, kel::lbm::data<sch::Vector<T,Descriptor::D>> vel){ using dfi = df_info<T, Descriptor>; - saw::data<sch::FixedArray<T,Descriptor::Q>> eq; + kel::lbm::data<sch::FixedArray<T,Descriptor::Q>> eq; // Brain broken, here's an owl // ^ // 0.0 @@ -16,7 +16,7 @@ saw::data<sch::FixedArray<T, Descriptor::Q>> equilibrium(saw::data<sch::Scalar<T // | | // // Velocity * Velocity meaning || vel ||_2^2 or <vel,vel>_2 - saw::data<T> vel_vel{0.0}; + kel::lbm::data<T> 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<sch::FixedArray<T, Descriptor::Q>> equilibrium(saw::data<sch::Scalar<T * Calculate equilibrium */ for(uint64_t i = 0u; i < Descriptor::Q; ++i){ - saw::data<T> vel_c{}; + kel::lbm::data<T> vel_c{}; for(uint64_t j = 0u; j < Descriptor::D; ++j){ // <vel,c_i>_2 - vel_c = vel_c + (vel.at({{j}}) * saw::data<T>{static_cast<saw::native_data_type<T>::type>(dfi::directions[i][j])}); + vel_c = vel_c + (vel.at({{j}}) * kel::lbm::data<T>{static_cast<kel::lbm::native_data_type<T>::type>(dfi::directions[i][j])}); } - auto vel_c_cs2 = vel_c * saw::data<T>{dfi::inv_cs2}; + auto vel_c_cs2 = vel_c * kel::lbm::data<T>{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 <forstio/error.hpp> -#include <forstio/codec/data.hpp> +#include "abstract/error.hpp" +#include "abstract/data.hpp" namespace kel { namespace lbm { namespace sch { -using namespace saw::schema; } template<typename T, uint64_t D> struct flatten_index { public: template<uint64_t i> - static constexpr saw::data<sch::UInt64> stride(const saw::data<sch::FixedArray<sch::UInt64,D>>& meta) { + static constexpr kel::lbm::data<sch::UInt64> stride(const kel::lbm::data<sch::FixedArray<sch::UInt64,D>>& meta) { if constexpr (i > 0u){ return stride<i-1u>(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<uint64_t i> - static void apply_i(saw::data<sch::UInt64>& flat_ind, const saw::data<sch::FixedArray<T,D>>& index, const saw::data<sch::FixedArray<T,D>>& meta){ + static void apply_i(kel::lbm::data<sch::UInt64>& flat_ind, const kel::lbm::data<sch::FixedArray<T,D>>& index, const kel::lbm::data<sch::FixedArray<T,D>>& meta){ if constexpr ( D > i ) { flat_ind = flat_ind + index.at({i}) * stride<i>(meta); apply_i<i+1u>(flat_ind,index,meta); } } public: - static saw::data<T> apply(const saw::data<sch::FixedArray<T,D>>& index, const saw::data<sch::FixedArray<T,D>>& meta){ - saw::data<T> flat_ind{0u}; + static kel::lbm::data<T> apply(const kel::lbm::data<sch::FixedArray<T,D>>& index, const kel::lbm::data<sch::FixedArray<T,D>>& meta){ + kel::lbm::data<T> 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<typename CellFieldSchema, typename MacroFieldSchema> - void apply(const saw::data<CellFieldSchema, Encode>& field, const saw::data<MacroFieldSchema,Encode>& macros, saw::data<sch::FixedArray<sch::UInt64,Descriptor::D>> index, saw::data<sch::UInt64> time_step) const { + void apply(const kel::lbm::data<CellFieldSchema, Encode>& field, const kel::lbm::data<MacroFieldSchema,Encode>& macros, kel::lbm::data<sch::FixedArray<sch::UInt64,Descriptor::D>> index, kel::lbm::data<sch::UInt64> time_step) const { auto& por_f = macros.template get<"porosity">(); auto& por = por_f.at(index); @@ -57,39 +57,39 @@ public: template<typename T, typename Descriptor, typename Encode> class component<T, Descriptor, cmpt::FpLbm, Encode> final { private: - saw::data<T> relaxation_; - saw::data<T> frequency_; + kel::lbm::data<T> relaxation_; + kel::lbm::data<T> frequency_; public: using Component = cmpt::FpLbm; public: - component(typename saw::native_data_type<T>::type relaxation__): + component(typename kel::lbm::native_data_type<T>::type relaxation__): relaxation_{{relaxation__}}, - frequency_{saw::data<T>{1} / relaxation_} + frequency_{kel::lbm::data<T>{1} / relaxation_} {} - component(const saw::data<T>& relaxation__): + component(const kel::lbm::data<T>& relaxation__): relaxation_{relaxation__}, - frequency_{saw::data<T>{1} / relaxation_} + frequency_{kel::lbm::data<T>{1} / relaxation_} {} - component(const saw::data<sch::Pure<T>>& relaxation__): + component(const kel::lbm::data<sch::Pure<T>>& relaxation__): relaxation_{relaxation__.handle()}, - frequency_{saw::data<T>{typename saw::native_data_type<T>::type(1)} / relaxation_} + frequency_{kel::lbm::data<T>{typename kel::lbm::native_data_type<T>::type(1)} / relaxation_} {} template<typename CellFieldSchema, typename MacroFieldSchema> - void apply(const saw::data<CellFieldSchema, Encode>& field, const saw::data<MacroFieldSchema,Encode>& macros, saw::data<sch::FixedArray<sch::UInt64,Descriptor::D>> index, saw::data<sch::UInt64> time_step) const { + void apply(const kel::lbm::data<CellFieldSchema, Encode>& field, const kel::lbm::data<MacroFieldSchema,Encode>& macros, kel::lbm::data<sch::FixedArray<sch::UInt64,Descriptor::D>> index, kel::lbm::data<sch::UInt64> 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<sch::Scalar<T>> half; + kel::lbm::data<sch::Scalar<T>> half; half.at({}) = 0.5f; auto& rho_f = macros.template get<"density">(); - saw::data<sch::Scalar<T>>& rho = rho_f.at(index); + kel::lbm::data<sch::Scalar<T>>& 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<sch::Scalar<T>> dfi_inv_cs2; + kel::lbm::data<sch::Scalar<T>> dfi_inv_cs2; dfi_inv_cs2.at({}).set(dfi::inv_cs2); for(uint64_t i{0u}; i < Descriptor::Q; ++i){ - saw::data<sch::Vector<T,Descriptor::D>> ci; + kel::lbm::data<sch::Vector<T,Descriptor::D>> ci; for(uint64_t d{0u}; d < Descriptor::D; ++d){ - ci.at({{d}}).set(static_cast<typename saw::native_data_type<T>::type>(dfi::directions[i][d])); + ci.at({{d}}).set(static_cast<typename kel::lbm::native_data_type<T>::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<sch::Scalar<T>> w; + kel::lbm::data<sch::Scalar<T>> 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<T>{1} - saw::data<T>{0.5f} * frequency_); + * (kel::lbm::data<T>{1} - kel::lbm::data<T>{0.5f} * frequency_); } } }; @@ -142,18 +142,18 @@ class component<T, Descriptor, cmpt::FpLbmOneParticle, Encode> final { public: using Component = cmpt::FpLbmOneParticle; private: - saw::data<sch::Vector<T,Descriptor::D>> global_force_; + kel::lbm::data<sch::Vector<T,Descriptor::D>> global_force_; public: component(): global_force_{} {} - component(saw::data<sch::Vector<T,Descriptor::D>> global_force__): + component(kel::lbm::data<sch::Vector<T,Descriptor::D>> global_force__): global_force_{global_force__} {} template<typename CellFieldSchema, typename MacroFieldSchema, typename ParticleSchema> - void apply(const saw::data<CellFieldSchema, Encode>& field, const saw::data<MacroFieldSchema,Encode>& macros, const saw::data<ParticleSchema,Encode>& pg, saw::data<sch::FixedArray<sch::UInt64,1u>> index, saw::data<sch::UInt64> time_step, saw::data<sch::UInt64> sub_steps) const { - // void apply(saw::data<CellFieldSchema, Encode>& field, saw::data<sch::FixedArray<sch::UInt64, Descriptor::D>> index, saw::data<sch::UInt64> time_step){ + void apply(const kel::lbm::data<CellFieldSchema, Encode>& field, const kel::lbm::data<MacroFieldSchema,Encode>& macros, const kel::lbm::data<ParticleSchema,Encode>& pg, kel::lbm::data<sch::FixedArray<sch::UInt64,1u>> index, kel::lbm::data<sch::UInt64> time_step, kel::lbm::data<sch::UInt64> sub_steps) const { + // void apply(kel::lbm::data<CellFieldSchema, Encode>& field, kel::lbm::data<sch::FixedArray<sch::UInt64, Descriptor::D>> index, kel::lbm::data<sch::UInt64> 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<sch::Scalar<T>> three; + kel::lbm::data<sch::Scalar<T>> three; three.at({}).set(3.0f); - saw::data<sch::Scalar<T>> two; + kel::lbm::data<sch::Scalar<T>> two; two.at({}).set(2.0f); - saw::data<sch::Scalar<T>> one; + kel::lbm::data<sch::Scalar<T>> one; one.at({}) = 1.0f; - saw::data<sch::Scalar<T>> eps; + kel::lbm::data<sch::Scalar<T>> eps; eps.at({}) = 1.5f; - saw::data<sch::Scalar<T>> sss; + kel::lbm::data<sch::Scalar<T>> sss; sss.at({}) = sub_steps.template cast_to<T>(); auto vel_s = (pirb_pos-pirb_pos_old) * sss; - saw::data<sch::Vector<T,Descriptor::D>> force_p{{}}; + kel::lbm::data<sch::Vector<T,Descriptor::D>> force_p{{}}; //= global_force_; iterator<Descriptor::D>::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<sch::Vector<T,Descriptor::D>> rel_dist = saw::math::vectorize_data(index_f).template cast_to<T>() - pirb_pos; + kel::lbm::data<sch::Vector<T,Descriptor::D>> rel_dist = kel::lbm::math::vectorize_data(index_f).template cast_to<T>() - pirb_pos; por = particle_porosity<T,Descriptor::D,1u,por::ParticleSpheroid<T>>::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<sch::UInt64> i{0u}; i < sub_steps; ++i){ + for(kel::lbm::data<sch::UInt64> i{0u}; i < sub_steps; ++i){ verlet_step_lambda<T,Descriptor::D>(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<typename Schema> struct geometry { - void apply(const saw::data<Schema>& field, const saw::data<sch::FixedArray<sch::UInt64,2u>>& start, const saw::data<sch::FixedArray<sch::UInt64,2u>>& end, const saw::data<sch::UInt8>& type){ + void apply(const kel::lbm::data<Schema>& field, const kel::lbm::data<sch::FixedArray<sch::UInt64,2u>>& start, const kel::lbm::data<sch::FixedArray<sch::UInt64,2u>>& end, const kel::lbm::data<sch::UInt8>& 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<Schema, Desc, cmpt::PoiseulleChannel, Encode> final { private: public: template<typename CellFieldSchema> - void apply(saw::data<CellFieldSchema,Encode>& field, const saw::data<sch::FixedArraysch::UInt64,Desc::D>){ + void apply(kel::lbm::data<CellFieldSchema,Encode>& field, const kel::lbm::data<sch::FixedArraysch::UInt64,Desc::D>){ 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<typename InfoSchema> class domain_registry final { private: - saw::data<sch::Array<InfoSchema>> infos_; + kel::lbm::data<sch::Array<InfoSchema>> infos_; public: template<typename T> - saw::data<InfoSchema> get_template_id() { - static saw::data<InfoSchema> id{std::numeric_limits<typename saw::native_data_type<InfoSchema>::type>::max()}; + kel::lbm::data<InfoSchema> get_template_id() { + static kel::lbm::data<InfoSchema> id{std::numeric_limits<typename kel::lbm::native_data_type<InfoSchema>::type>::max()}; - if( id == std::numeric_limits<typename saw::native_data_type<InfoSchema>::type>::max() ){ + if( id == std::numeric_limits<typename kel::lbm::native_data_type<InfoSchema>::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<typename Schema> -void clean_grid(saw::data<Schema>& info_field){ +void clean_grid(kel::lbm::data<Schema>& 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<typename CellFieldSchema, typename MacroFieldSchema> - void apply(const saw::data<CellFieldSchema, Encode>& field, const saw::data<MacroFieldSchema,Encode>& macros, saw::data<sch::FixedArray<sch::UInt64,Descriptor::D>> index, saw::data<sch::UInt64> time_step) const { + void apply(const kel::lbm::data<CellFieldSchema, Encode>& field, const kel::lbm::data<MacroFieldSchema,Encode>& macros, kel::lbm::data<sch::FixedArray<sch::UInt64,Descriptor::D>> index, kel::lbm::data<sch::UInt64> 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<typename T, typename Desc, typename Encode> class component<T, Desc, cmpt::Hlbm, Encode> final { private: - typename saw::native_data_type<T>::type relaxation_; - saw::data<T> frequency_; + typename kel::lbm::native_data_type<T>::type relaxation_; + kel::lbm::data<T> frequency_; public: - component(typename saw::native_data_type<T>::type relaxation__): + component(typename kel::lbm::native_data_type<T>::type relaxation__): relaxation_{relaxation__}, - frequency_{typename saw::native_data_type<T>::type(1) / relaxation_} + frequency_{typename kel::lbm::native_data_type<T>::type(1) / relaxation_} {} - component(const saw::data<sch::Pure<T>>& relaxation__): + component(const kel::lbm::data<sch::Pure<T>>& relaxation__): relaxation_{relaxation__.handle().get()}, - frequency_{typename saw::native_data_type<T>::type(1) / relaxation_} + frequency_{typename kel::lbm::native_data_type<T>::type(1) / relaxation_} {} template<typename CellFieldSchema, typename MacroFieldSchema> - void apply(const saw::data<CellFieldSchema, Encode>& field, const saw::data<MacroFieldSchema,Encode>& macros, saw::data<sch::FixedArray<sch::UInt64,Desc::D>> index, saw::data<sch::UInt64> time_step) const { + void apply(const kel::lbm::data<CellFieldSchema, Encode>& field, const kel::lbm::data<MacroFieldSchema,Encode>& macros, kel::lbm::data<sch::FixedArray<sch::UInt64,Desc::D>> index, kel::lbm::data<sch::UInt64> 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<sch::Scalar<T>>& rho = rho_f.at(index); - saw::data<sch::Vector<T,Desc::D>>& vel = vel_f.at(index); + kel::lbm::data<sch::Scalar<T>>& rho = rho_f.at(index); + kel::lbm::data<sch::Vector<T,Desc::D>>& vel = vel_f.at(index); compute_rho_u<T,Desc>(dfs_old_f.at(index), rho, vel); auto& porosity = porosity_f.at(index); - saw::data<sch::Scalar<T>> one; + kel::lbm::data<sch::Scalar<T>> 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<sch::Vector<T,Desc::D>> { + vel = vel * porosity + [&]() -> kel::lbm::data<sch::Vector<T,Desc::D>> { return (D.at({}).get() > 0.0) ? ( N * flip_porosity / D ): N; }(); // Equilibrium @@ -109,7 +109,7 @@ class component<T, Desc, cmpt::HlbmOneParticle, Encode> final { private: public: template<typename CellFieldSchema, typename MacroFieldSchema, typename ParticleSchema> - void apply(const saw::data<CellFieldSchema, Encode>& field, const saw::data<MacroFieldSchema,Encode>& macros, const saw::data<ParticleSchema,Encode>& part_group, saw::data<sch::FixedArray<sch::UInt64,1u>> index, saw::data<sch::UInt64> time_step, saw::data<sch::UInt64> sub_steps) const { + void apply(const kel::lbm::data<CellFieldSchema, Encode>& field, const kel::lbm::data<MacroFieldSchema,Encode>& macros, const kel::lbm::data<ParticleSchema,Encode>& part_group, kel::lbm::data<sch::FixedArray<sch::UInt64,1u>> index, kel::lbm::data<sch::UInt64> time_step, kel::lbm::data<sch::UInt64> 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<T,Desc>; bool is_even = ((time_step.get() % 2) == 0); - saw::data<sch::Scalar<T>> one; + kel::lbm::data<sch::Scalar<T>> 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<sch::Vector<T,Desc::D>>& pirb_pos = pirb.template get<"position">(); + kel::lbm::data<sch::Vector<T,Desc::D>>& 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<sch::Scalar<T>> ts; + kel::lbm::data<sch::Scalar<T>> ts; ts.at({}) = one.at({}) / sub_steps.template cast_to<T>(); - saw::data<sch::FixedArray<sch::UInt64,Desc::D>> start; - saw::data<sch::FixedArray<sch::UInt64,Desc::D>> stop; + kel::lbm::data<sch::FixedArray<sch::UInt64,Desc::D>> start; + kel::lbm::data<sch::FixedArray<sch::UInt64,Desc::D>> stop; auto eo_aabb = particle_aabb<typename ParticleSchema::ValueType>::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<sch::Vector<T,Desc::D>> force_p; + kel::lbm::data<sch::Vector<T,Desc::D>> force_p; for(uint64_t i{0u}; i < Desc::D; ++i){ force_p.at({{i}}) = 0.0; } @@ -167,8 +167,8 @@ public: iterator<Desc::D>::apply([&](const auto& index_f) -> void{ auto& dfs = dfs_old_f.at(index_f); - saw::data<sch::Vector<T,Desc::D>> rel_dist = saw::math::vectorize_data(index_f).template cast_to<T>() - pirb_pos; - saw::data<sch::Scalar<T>> eps; + kel::lbm::data<sch::Vector<T,Desc::D>> rel_dist = kel::lbm::math::vectorize_data(index_f).template cast_to<T>() - pirb_pos; + kel::lbm::data<sch::Scalar<T>> eps; eps.at({}) = 1.5f; auto& mpor = mpor_f.at(index_f); @@ -178,14 +178,14 @@ public: return; } - saw::data<sch::Vector<T,Desc::D>> momentum; + kel::lbm::data<sch::Vector<T,Desc::D>> 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<sch::Vector<T,Desc::D>> e_i; - saw::data<sch::FixedArray<sch::UInt64,Desc::D>> n_ind_i; + kel::lbm::data<sch::Vector<T,Desc::D>> e_i; + kel::lbm::data<sch::FixedArray<sch::UInt64,Desc::D>> 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<T> dfs_added = dfs.at({i})*(saw::data<T>{1}-u_p_e.at({})) + dfs_old_f.at(n_ind_i).at({i_opp})*(saw::data<T>{1}+u_p_e.at({})); - saw::data<sch::Scalar<T>> dfs_added_v; + kel::lbm::data<T> dfs_added = dfs.at({i})*(kel::lbm::data<T>{1}-u_p_e.at({})) + dfs_old_f.at(n_ind_i).at({i_opp})*(kel::lbm::data<T>{1}+u_p_e.at({})); + kel::lbm::data<sch::Scalar<T>> 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<sch::UInt64> i{0u}; i < sub_steps; ++i){ + for(kel::lbm::data<sch::UInt64> i{0u}; i < sub_steps; ++i){ verlet_step_lambda<T,Desc::D>(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<typename T, uint64_t D> -saw::data<sch::FixedArray<sch::UInt64,D>> lower_index_from_pos(const saw::data<sch::Vector<T,D>>& pos){ - saw::data<sch::FixedArray<sch::UInt64,D>> ind; +kel::lbm::data<sch::FixedArray<sch::UInt64,D>> lower_index_from_pos(const kel::lbm::data<sch::Vector<T,D>>& pos){ + kel::lbm::data<sch::FixedArray<sch::UInt64,D>> ind; - for(saw::data<sch::UInt64> i{0u}; i < ind.size(); ++i){ + for(kel::lbm::data<sch::UInt64> i{0u}; i < ind.size(); ++i){ ind.at(i).set(std::max(pos.at(i).template cast_to<sch::UInt64>().get(),0)); } @@ -17,10 +17,10 @@ saw::data<sch::FixedArray<sch::UInt64,D>> lower_index_from_pos(const saw::data<s } template<typename T, uint64_t D> -saw::data<sch::FixedArray<sch::UInt64,D>> upper_index_from_pos(const saw::data<sch::Vector<T,D>>& pos){ +kel::lbm::data<sch::FixedArray<sch::UInt64,D>> upper_index_from_pos(const kel::lbm::data<sch::Vector<T,D>>& pos){ auto ind = lower_index_from_pos(pos); - for(saw::data<sch::UInt64> i{0u}; i < ind.size(); ++i){ + for(kel::lbm::data<sch::UInt64> 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<typename Func> -void iterate_over(Func&& func, const saw::data<sch::FixedArray<sch::UInt64,2u>>& start, const saw::data<sch::FixedArray<sch::UInt64,2u>>& end, const saw::data<sch::FixedArray<sch::UInt64,2u>>& dist = {{{0u,0u}}}){ +void iterate_over(Func&& func, const kel::lbm::data<sch::FixedArray<sch::UInt64,2u>>& start, const kel::lbm::data<sch::FixedArray<sch::UInt64,2u>>& end, const kel::lbm::data<sch::FixedArray<sch::UInt64,2u>>& dist = {{{0u,0u}}}){ // static_assert(D == 2u, "Currently a lazy implementation for AND combinations of intervalls."); - for(saw::data<sch::UInt64> i{start.at({0u}) + dist.at({0u})}; (i+dist.at({0u})) < end.at({0u}); ++i){ - for(saw::data<sch::UInt64> j{start.at({1u}) + dist.at({1u})}; (j+dist.at({1u})) < end.at({1u}); ++j){ + for(kel::lbm::data<sch::UInt64> i{start.at({0u}) + dist.at({0u})}; (i+dist.at({0u})) < end.at({0u}); ++i){ + for(kel::lbm::data<sch::UInt64> 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<uint64_t i, typename Func> static void iterate_over_i(Func& func, - const saw::data<sch::FixedArray<sch::UInt64,D>>& start, - const saw::data<sch::FixedArray<sch::UInt64,D>>& end, - const saw::data<sch::FixedArray<sch::UInt64,D>>& dist, - saw::data<sch::FixedArray<sch::UInt64,D>>& iter + const kel::lbm::data<sch::FixedArray<sch::UInt64,D>>& start, + const kel::lbm::data<sch::FixedArray<sch::UInt64,D>>& end, + const kel::lbm::data<sch::FixedArray<sch::UInt64,D>>& dist, + kel::lbm::data<sch::FixedArray<sch::UInt64,D>>& iter ){ static_assert(i <= D, "Eh. Too tired to think of a good message"); if constexpr ( i == D ){ @@ -41,11 +41,11 @@ public: template<typename Func> static void apply( Func&& func, - const saw::data<sch::FixedArray<sch::UInt64,D>>& start, - const saw::data<sch::FixedArray<sch::UInt64,D>>& end, - const saw::data<sch::FixedArray<sch::UInt64,D>>& dist = {} + const kel::lbm::data<sch::FixedArray<sch::UInt64,D>>& start, + const kel::lbm::data<sch::FixedArray<sch::UInt64,D>>& end, + const kel::lbm::data<sch::FixedArray<sch::UInt64,D>>& dist = {} ){ - saw::data<sch::FixedArray<sch::UInt64,D>> iter; + kel::lbm::data<sch::FixedArray<sch::UInt64,D>> iter; iterate_over_i<0u,Func>(func, start, end, dist, iter); } }; @@ -57,9 +57,9 @@ template<typename... Tup> struct ct_tuple_iterator<sch::Tuple<Tup...>> final { private: template<typename Func, uint64_t i> - static constexpr saw::error_or<void> apply_i( + static constexpr kel::lbm::error_or<void> apply_i( Func& func, - saw::data<sch::Tuple<Tup...>>& tup + kel::lbm::data<sch::Tuple<Tup...>>& tup ){ if constexpr ( i < sizeof...(Tup) ){ auto eov = func(tup.template get<i>()); @@ -69,13 +69,13 @@ private: return apply_i<Func,i+1u>(func,tup); } - return saw::make_void(); + return kel::lbm::make_void(); } public: template<typename Func> - static constexpr saw::error_or<void> apply( + static constexpr kel::lbm::error_or<void> apply( Func&& func, - saw::data<sch::Tuple<Tup...>>& tup + kel::lbm::data<sch::Tuple<Tup...>>& tup ){ return apply_i<Func,0u>(func,tup); } @@ -83,11 +83,11 @@ public: /* Ambiguous template<typename Func> -void iterate_over(Func&& func, const saw::data<sch::FixedArray<sch::UInt64,3u>>& start, const saw::data<sch::FixedArray<sch::UInt64,3u>>& end, const saw::data<sch::FixedArray<sch::UInt64,3u>>& dist = {{{0u,0u,0u}}}){ +void iterate_over(Func&& func, const kel::lbm::data<sch::FixedArray<sch::UInt64,3u>>& start, const kel::lbm::data<sch::FixedArray<sch::UInt64,3u>>& end, const kel::lbm::data<sch::FixedArray<sch::UInt64,3u>>& dist = {{{0u,0u,0u}}}){ // static_assert(D == 2u, "Currently a lazy implementation for AND combinations of intervalls."); - for(saw::data<sch::UInt64> i{start.at({0u}) + dist.at({0u})}; (i+dist.at({0u})) < end.at({0u}); ++i){ - for(saw::data<sch::UInt64> j{start.at({1u}) + dist.at({1u})}; (j+dist.at({1u})) < end.at({1u}); ++j){ - for(saw::data<sch::UInt64> k{start.at({2u}) + dist.at({2u})}; (j+dist.at({2u})) < end.at({2u}); ++j){ + for(kel::lbm::data<sch::UInt64> i{start.at({0u}) + dist.at({0u})}; (i+dist.at({0u})) < end.at({0u}); ++i){ + for(kel::lbm::data<sch::UInt64> j{start.at({1u}) + dist.at({1u})}; (j+dist.at({1u})) < end.at({1u}); ++j){ + for(kel::lbm::data<sch::UInt64> 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 <forstio/codec/unit/unit_print.hpp> +#include "abstract/unit_print.hpp" #include <iostream> namespace kel { @@ -33,15 +34,15 @@ namespace lbm { template<typename T, typename Desc> void print_lbm_meta( const converter<T>& conv, - const saw::data<sch::SiKinematicViscosity<T>>& kin_vis_si, - const saw::data<sch::SiVelocity<T>>& char_vel, - const saw::data<sch::SiMeter<T>>& char_len + const kel::lbm::data<sch::SiKinematicViscosity<T>>& kin_vis_si, + const kel::lbm::data<sch::SiVelocity<T>>& char_vel, + const kel::lbm::data<sch::SiMeter<T>>& char_len ){ std::cout <<"[Meta]\n" <<"======\n" <<"Re: "<<(char_vel * char_len / kin_vis_si)<<"\n" - <<"Ma: "<<(char_vel * saw::data<typename saw::unit_division<sch::Pure<T>, sch::SiVelocity<T>>::Schema>{std::sqrt(df_info<T,Desc>::inv_cs2)})<<"\n" + <<"Ma: "<<(char_vel * kel::lbm::data<typename kel::lbm::unit_division<sch::Pure<T>, sch::SiVelocity<T>>::Schema>{std::sqrt(df_info<T,Desc>::inv_cs2)})<<"\n" <<"\n" <<"[SI]\n" <<"====\n" @@ -56,7 +57,7 @@ void print_lbm_meta( <<"[LBM]\n" <<"=====\n" <<"KinVis: "<<conv.kinematic_viscosity_si_to_lbm(kin_vis_si)<<"\n" - <<"Ï„: "<<(saw::data<typename saw::unit_division<sch::Pure<T>, sch::LbmKinematicViscosity<T>>::Schema >{df_info<T,Desc>::inv_cs2} * conv.kinematic_viscosity_si_to_lbm(kin_vis_si) + saw::data<sch::Pure<T>>{0.5})<<"\n" + <<"Ï„: "<<(kel::lbm::data<typename kel::lbm::unit_division<sch::Pure<T>, sch::LbmKinematicViscosity<T>>::Schema >{df_info<T,Desc>::inv_cs2} * conv.kinematic_viscosity_si_to_lbm(kin_vis_si) + kel::lbm::data<sch::Pure<T>>{0.5})<<"\n" <<std::endl ; } diff --git a/modules/core/c++/lbm_unit.hpp b/modules/core/c++/lbm_unit.hpp index 2d90652..5d24115 100644 --- a/modules/core/c++/lbm_unit.hpp +++ b/modules/core/c++/lbm_unit.hpp @@ -3,7 +3,7 @@ * Get the conversion parameter with the conversion type */ -#include <forstio/codec/unit/unit.hpp> +#include "abstract/unit.hpp" #include <string_view> @@ -34,7 +34,6 @@ struct second { } namespace sch { -using namespace saw::schema; template<typename S> using SiMeter = Unit<S, UnitElement<si_type::meter, 1>>; 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<typename T, typename Desc> void compute_rho_u ( - const saw::data<sch::FixedArray<T,Desc::Q>>& dfs, - saw::ref<saw::data<sch::Scalar<T>>> rho, - saw::ref<saw::data<sch::Vector<T,Desc::D>>> vel + const kel::lbm::data<sch::FixedArray<T,Desc::Q>>& dfs, + kel::lbm::ref<kel::lbm::data<sch::Scalar<T>>> rho, + kel::lbm::ref<kel::lbm::data<sch::Vector<T,Desc::D>>> vel ) { using dfi = df_info<T, Desc>; @@ -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<T>{static_cast<typename saw::native_data_type<T>::type>(dfi::directions[j][i])} * dfs.at({j}); + vel().at({{i}}) = vel().at({{i}}) + kel::lbm::data<T>{static_cast<typename kel::lbm::native_data_type<T>::type>(dfi::directions[j][i])} * dfs.at({j}); } } @@ -39,9 +39,9 @@ void compute_rho_u ( */ template<typename T, typename Desc> void compute_rho_momentum ( - const saw::data<sch::FixedArray<T,Desc::Q>>& dfs, - saw::ref<saw::data<sch::Scalar<T>>> rho, - saw::ref<saw::data<sch::Vector<T,Desc::D>>> mom + const kel::lbm::data<sch::FixedArray<T,Desc::Q>>& dfs, + kel::lbm::ref<kel::lbm::data<sch::Scalar<T>>> rho, + kel::lbm::ref<kel::lbm::data<sch::Vector<T,Desc::D>>> mom ) { using dfi = df_info<T, Desc>; @@ -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<T>{static_cast<typename saw::native_data_type<T>::type>(dfi::directions[j][i])} * dfs.at({j}); + mom().at({{i}}) = mom().at({{i}}) + kel::lbm::data<T>{static_cast<typename kel::lbm::native_data_type<T>::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<typename FieldSchema, typename Encode, typename T, uint64_t D> -saw::data<typename FieldSchema::StoredValueSchema> n_closest_read(const saw::data<sch::Ptr<FieldSchema>,Encode>& f, const saw::data<sch::Vector<T,D>>& frac_ind){ +kel::lbm::data<typename FieldSchema::StoredValueSchema> n_closest_read(const kel::lbm::data<sch::Ptr<FieldSchema>,Encode>& f, const kel::lbm::data<sch::Vector<T,D>>& 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<T>{0.5}; + shift_frac_ind.at({{i}}) = shift_frac_ind.at({{i}}) + kel::lbm::data<T>{0.5}; if(shift_frac_ind.at({{i}}).get() < 0){ shift_frac_ind.at({{i}}) = {}; } } - saw::data<sch::FixedArray<sch::UInt64,D>> shift_ind; + kel::lbm::data<sch::FixedArray<sch::UInt64,D>> shift_ind; for(uint64_t i{0u}; i < D; ++i){ shift_ind.at({i}) = frac_ind.at({{i}}).template cast_to<sch::UInt64>(); } @@ -27,18 +27,18 @@ saw::data<typename FieldSchema::StoredValueSchema> n_closest_read(const saw::dat } template<typename FieldSchema, typename Encode, typename T, uint64_t D> -void n_closest_add(const saw::data<sch::Ptr<FieldSchema>,Encode>& f, const saw::data<sch::Vector<T,D>>& frac_ind, const saw::data<typename FieldSchema::StoredValueSchema>& val){ +void n_closest_add(const kel::lbm::data<sch::Ptr<FieldSchema>,Encode>& f, const kel::lbm::data<sch::Vector<T,D>>& frac_ind, const kel::lbm::data<typename FieldSchema::StoredValueSchema>& 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<T>{0.5}; + shift_frac_ind.at({{i}}) = shift_frac_ind.at({{i}}) + kel::lbm::data<T>{0.5}; if(shift_frac_ind.at({{i}}).get() < 0){ shift_frac_ind.at({{i}}) = {}; } } auto f_meta = f.meta(); - saw::data<sch::FixedArray<sch::UInt64,D>> shift_ind; + kel::lbm::data<sch::FixedArray<sch::UInt64,D>> shift_ind; for(uint64_t i{0u}; i < D; ++i){ shift_ind.at({i}) = frac_ind.at({{i}}).template cast_to<sch::UInt64>(); 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<typename FieldSchema, typename T, uint64_t D> struct n_linear_interpolate_helper final { template<uint64_t i = 0u> - auto apply(const saw::data<FieldSchema>& field, const saw::data<sch::Vector<T,D>>& pos){ + auto apply(const kel::lbm::data<FieldSchema>& field, const kel::lbm::data<sch::Vector<T,D>>& pos){ return pos; } }; } template<typename T, uint64_t D> -saw::data<sch::Tuple<sch::Vector<sch::UInt64,D>,sch::Vector<T,D>>> position_to_index_and_fraction(const saw::data<sch::Vector<T,D>>& pos){ - saw::data<sch::Tuple<sch::Vector<sch::UInt64,D>,sch::Vector<T,D>>> sep; +kel::lbm::data<sch::Tuple<sch::Vector<sch::UInt64,D>,sch::Vector<T,D>>> position_to_index_and_fraction(const kel::lbm::data<sch::Vector<T,D>>& pos){ + kel::lbm::data<sch::Tuple<sch::Vector<sch::UInt64,D>,sch::Vector<T,D>>> sep; auto& ind = sep.template get<0u>(); auto& frac = sep.template get<1u>(); @@ -25,7 +25,7 @@ saw::data<sch::Tuple<sch::Vector<sch::UInt64,D>,sch::Vector<T,D>>> 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<typename saw::native_data_type<T>::type>(0))); + pos_cpy.at({{i}}).set(std::max(pos.at({{i}}).get(), static_cast<typename kel::lbm::native_data_type<T>::type>(0))); } // Now we can cast to uint64_t @@ -39,14 +39,14 @@ saw::data<sch::Tuple<sch::Vector<sch::UInt64,D>,sch::Vector<T,D>>> position_to_i } template<typename T, uint64_t D> -auto floor_index_from_position(const saw::data<sch::Vector<T,D>>& pos){ +auto floor_index_from_position(const kel::lbm::data<sch::Vector<T,D>>& pos){ return position_to_index_and_fraction(pos).template get<0u>(); } template<typename T, uint64_t D> -saw::data<sch::Tuple<sch::Vector<sch::UInt64,D>,sch::Vector<T,D>>> position_to_index_and_fraction_bounded( - const saw::data<sch::Vector<T,D>>& pos, - const saw::data<sch::Vector<sch::UInt64,D>>& bound) +kel::lbm::data<sch::Tuple<sch::Vector<sch::UInt64,D>,sch::Vector<T,D>>> position_to_index_and_fraction_bounded( + const kel::lbm::data<sch::Vector<T,D>>& pos, + const kel::lbm::data<sch::Vector<sch::UInt64,D>>& bound) { auto infr = position_to_index_and_fraction(pos); auto& ind = infr.template get<0u>(); @@ -64,7 +64,7 @@ saw::data<sch::Tuple<sch::Vector<sch::UInt64,D>,sch::Vector<T,D>>> position_to_i template<typename FieldSchema, typename T, uint64_t D> auto n_linear_interpolate( - const saw::data<FieldSchema>& field, const saw::data<sch::Vector<T,D>>& pos){ + const kel::lbm::data<FieldSchema>& field, const kel::lbm::data<sch::Vector<T,D>>& pos){ // Pos auto pos_bound = pos; @@ -73,9 +73,9 @@ auto n_linear_interpolate( auto meta = field.dims(); // Lower Index - saw::data<sch::FixedArray<sch::UInt64,D>> ind; + kel::lbm::data<sch::FixedArray<sch::UInt64,D>> ind; - for(saw::data<sch::UInt64> i{0u}; i < saw::data<sch::UInt64>{D}; ++i){ + for(kel::lbm::data<sch::UInt64> i{0u}; i < kel::lbm::data<sch::UInt64>{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<sch::Vector<T,D>> pos_frac; - for(saw::data<sch::UInt64> i{0u}; i < saw::data<sch::UInt64>{D}; ++i){ + kel::lbm::data<sch::Vector<T,D>> pos_frac; + for(kel::lbm::data<sch::UInt64> i{0u}; i < kel::lbm::data<sch::UInt64>{D}; ++i){ pos_frac.at({i}) = pos_bound.at({i}) - ind.at(i).template cast_to<T>(); } // Base value - saw::data<typename FieldSchema::ValueType> res; + kel::lbm::data<typename FieldSchema::ValueType> res; // constexpr uint64_t d_corners = 1ul << D; - saw::data<sch::FixedArray<sch::UInt64,D>> ones_ind; - for(saw::data<sch::UInt64> i{0u}; i < saw::data<sch::UInt64>{D}; ++i){ + kel::lbm::data<sch::FixedArray<sch::UInt64,D>> ones_ind; + for(kel::lbm::data<sch::UInt64> i{0u}; i < kel::lbm::data<sch::UInt64>{D}; ++i){ ones_ind.at({i}).set(1u); } iterator<D>::apply([&](auto ind){ // Iterates over (0,0,0) to (1,1,1) - saw::data<T> weight{1.0}; + kel::lbm::data<T> weight{1.0}; - for(saw::data<sch::UInt64> d{0u}; d < saw::data<sch::UInt64>{D}; ++d){ + for(kel::lbm::data<sch::UInt64> d{0u}; d < kel::lbm::data<sch::UInt64>{D}; ++d){ - saw::data<T> t = pos_frac.at({d}); + kel::lbm::data<T> t = pos_frac.at({d}); if(ind.at(d).get() == 0u){ - weight = weight * (saw::data<T>{1} - t); + weight = weight * (kel::lbm::data<T>{1} - t); }else{ weight = weight * t; } @@ -128,8 +128,8 @@ auto n_linear_interpolate( } template<typename FieldSchema, typename T> -saw::data<sch::Vector<T,2u>> bilinear_interpolate(const saw::data<FieldSchema>& field, const saw::data<sch::Vector<T,2u>>& pos){ - saw::data<sch::Vector<T,2u>> res; +kel::lbm::data<sch::Vector<T,2u>> bilinear_interpolate(const kel::lbm::data<FieldSchema>& field, const kel::lbm::data<sch::Vector<T,2u>>& pos){ + kel::lbm::data<sch::Vector<T,2u>> 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<typename T, uint64_t D> -saw::data<sch::FixedArray<sch::UInt64,D>> round_to_unsigned(const saw::data<sch::Vector<T,D>>& inp){ - saw::data<sch::FixedArray<sch::UInt64,D>> rv; +kel::lbm::data<sch::FixedArray<sch::UInt64,D>> round_to_unsigned(const kel::lbm::data<sch::Vector<T,D>>& inp){ + kel::lbm::data<sch::FixedArray<sch::UInt64,D>> rv; - auto zero = static_cast<saw::native_data_type<T>::type>(0); - auto half = static_cast<saw::native_data_type<T>::type>(0.5); + auto zero = static_cast<kel::lbm::native_data_type<T>::type>(0); + auto half = static_cast<kel::lbm::native_data_type<T>::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<sch::Primitive<Sch,N>> { template<typename Sch, uint64_t... N> struct memory_size_helper<sch::FixedArray<Sch,N...>> { - static constexpr uint64_t bytes = saw::ct_multiply<uint64_t,N...>::value * memory_size_helper<Sch>::bytes; + static constexpr uint64_t bytes = kel::lbm::ct_multiply<uint64_t,N...>::value * memory_size_helper<Sch>::bytes; }; template<typename Sch, uint64_t... N> struct memory_size_helper<sch::Tensor<Sch,N...>> { - static constexpr uint64_t bytes = saw::ct_multiply<uint64_t,N...>::value * memory_size_helper<Sch>::bytes; + static constexpr uint64_t bytes = kel::lbm::ct_multiply<uint64_t,N...>::value * memory_size_helper<Sch>::bytes; }; template<typename Sch, uint64_t Ghost, uint64_t... N> @@ -37,7 +37,7 @@ struct memory_size_helper<sch::Struct<Members...>> { template<uint64_t i> static constexpr uint64_t apply_i() { if constexpr ( i < sizeof...(Members) ){ - using M_I = typename saw::parameter_pack_type<i,Members...>::type; + using M_I = typename kel::lbm::parameter_pack_type<i,Members...>::type; return apply_i<i+1u>() + memory_size_helper<typename M_I::ValueType>::bytes; } return 0u; @@ -51,10 +51,10 @@ class memory_estimate_helper final { private: template<uint64_t i> - static void apply_i(saw::data<sch::UInt64>& bytes){ + static void apply_i(kel::lbm::data<sch::UInt64>& bytes){ if constexpr ( i < sizeof...(T)){ - using T_I = typename saw::parameter_pack_type<i,T...>::type; + using T_I = typename kel::lbm::parameter_pack_type<i,T...>::type; bytes.set(bytes.get() + memory_size_helper<T_I>::bytes); @@ -64,15 +64,15 @@ private: public: - static void apply(saw::data<sch::UInt64>& bytes){ + static void apply(kel::lbm::data<sch::UInt64>& bytes){ apply_i<0u>(bytes); } }; } template<typename... T> -saw::data<sch::UInt64> memory_estimate(){ - saw::data<sch::UInt64> bytes; +kel::lbm::data<sch::UInt64> memory_estimate(){ + kel::lbm::data<sch::UInt64> bytes; impl::memory_estimate_helper<T...>::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<T,Descriptor,cmpt::ForceGather, Encode> { private: public: template<typename CellFieldSchema, typename MacroFieldSchema> - void apply(const saw::data<CellFieldSchema, Encode>& field, const saw::data<MacroFieldSchema,Encode>& macros, - saw::data<sch::FixedArray<sch::UInt64,Descriptor::D>> index, saw::data<sch::UInt64> time_step) const { + void apply(const kel::lbm::data<CellFieldSchema, Encode>& field, const kel::lbm::data<MacroFieldSchema,Encode>& macros, + kel::lbm::data<sch::FixedArray<sch::UInt64,Descriptor::D>> index, kel::lbm::data<sch::UInt64> time_step) const { using dfi = df_info<T,Descriptor>; 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<T>{dfi::directions[i][k]}; + force.at({{k}}) = force.at({{k}}) + dfs_diff * kel::lbm::data<T>{dfi::directions[i][k]}; } } - saw::data<sch::Scalar<T>> one; + kel::lbm::data<sch::Scalar<T>> 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<Chunk,Dim>; } } -namespace saw { +namespace kel { +namespace lbm { template<template Chunk, uint64_t Dim> class data<kel::lbm::sch::OverChunk<Chunk,Dim>> final { public: @@ -25,3 +26,4 @@ private: public: }; } +} diff --git a/modules/core/c++/particle.hpp b/modules/core/c++/particle.hpp index efcc3fb..30c5005 100644 --- a/modules/core/c++/particle.hpp +++ b/modules/core/c++/particle.hpp @@ -12,14 +12,14 @@ struct Particle {}; template<typename T, typename Descriptor, typename Encode> class component<T, Descriptor, cmpt::Particle, Encode> { private: - saw::data<sch::Scalar<T>> dt_; + kel::lbm::data<sch::Scalar<T>> dt_; public: - component(saw::data<sch::Scalar<T>> dt__): + component(kel::lbm::data<sch::Scalar<T>> dt__): dt_{dt__} {} template<typename ParticleSchema, typename MacroFieldSchema> - void apply(const saw::data<ParticleSchema, Encode>& particles, const saw::data<MacroFieldSchema,Encode>& macros, saw::data<sch::UInt64> index, saw::data<sch::UInt64> time_step) const { + void apply(const kel::lbm::data<ParticleSchema, Encode>& particles, const kel::lbm::data<MacroFieldSchema,Encode>& macros, kel::lbm::data<sch::UInt64> index, kel::lbm::data<sch::UInt64> time_step) const { auto& p = particles.at(index); diff --git a/modules/core/c++/particle/aabb.hpp b/modules/core/c++/particle/aabb.hpp index e4c930b..e986272 100644 --- a/modules/core/c++/particle/aabb.hpp +++ b/modules/core/c++/particle/aabb.hpp @@ -7,7 +7,7 @@ namespace kel { namespace lbm { template<typename PGroup> class particle_aabb final { - static_assert(saw::always_false<PGroup>, "Not supported"); + static_assert(kel::lbm::always_false<PGroup>, "Not supported"); }; template<typename T, uint64_t D, uint64_t PC> @@ -23,13 +23,13 @@ public: >; public: template<typename Sch, typename Encode> - static constexpr saw::error_or<saw::data<AABB>> calculate(const saw::data<Sch,Encode>& p_grp, const saw::data<sch::FixedArray<sch::UInt64,1u>>& index, const saw::data<sch::FixedArray<sch::UInt64,D>>& meta){ + static constexpr kel::lbm::error_or<kel::lbm::data<AABB>> calculate(const kel::lbm::data<Sch,Encode>& p_grp, const kel::lbm::data<sch::FixedArray<sch::UInt64,1u>>& index, const kel::lbm::data<sch::FixedArray<sch::UInt64,D>>& meta){ static_assert(PC > 0u, "Can't calculate from no particles"); if(not (index.at({{0u}}).get() < PC) ){ - return saw::make_error<saw::err::critical>("Too large i in particle_aabb"); + return kel::lbm::make_error<kel::lbm::err::critical>("Too large i in particle_aabb"); } - saw::data<AABB> aabb; + kel::lbm::data<AABB> aabb; auto& parts = p_grp.template get<"particles">(); auto& pi = parts.at(index); @@ -39,16 +39,16 @@ public: auto& a = aabb.template get<"a">(); auto& b = aabb.template get<"b">(); - const saw::data<sch::Scalar<T>>& rad_d = p_grp.template get<"collision">().at({{0u}}).template get<"radius">(); + const kel::lbm::data<sch::Scalar<T>>& rad_d = p_grp.template get<"collision">().at({{0u}}).template get<"radius">(); - saw::data<sch::Vector<T,D>> lower; - saw::data<sch::Vector<T,D>> upper; + kel::lbm::data<sch::Vector<T,D>> lower; + kel::lbm::data<sch::Vector<T,D>> upper; for(uint64_t i{0u}; i < D; ++i){ - lower.at({{i}}) = ((pirb_pos.at({{i}}) >= rad_d.at({})) ? (pirb_pos.at({{i}}) - rad_d.at({})) : saw::data<T>{0}); + lower.at({{i}}) = ((pirb_pos.at({{i}}) >= rad_d.at({})) ? (pirb_pos.at({{i}}) - rad_d.at({})) : kel::lbm::data<T>{0}); a.at({i}) = lower.at({{i}}).template cast_to<sch::UInt64>(); upper.at({{i}}) = pirb_pos.at({{i}}) + rad_d.at({}); - b.at({i}) = (upper.at({{i}})+saw::data<T>{1}).template cast_to<sch::UInt64>(); + b.at({i}) = (upper.at({{i}})+kel::lbm::data<T>{1}).template cast_to<sch::UInt64>(); } return aabb; diff --git a/modules/core/c++/particle/blur.hpp b/modules/core/c++/particle/blur.hpp index b7a1988..972a309 100644 --- a/modules/core/c++/particle/blur.hpp +++ b/modules/core/c++/particle/blur.hpp @@ -3,18 +3,18 @@ namespace kel { namespace lbm { template<typename T, uint64_t D> -void blur_mask(saw::data<sch::Array<T,D>>& p_mask){ +void blur_mask(kel::lbm::data<sch::Array<T,D>>& p_mask){ - saw::data<T> mid{2.0/3.0}; - saw::data<T> edge{1.0/6.0}; + kel::lbm::data<T> mid{2.0/3.0}; + kel::lbm::data<T> edge{1.0/6.0}; - // saw::data<sch::FixedArray<sch::UInt64>,2u> blur_weights{{2.0/3.0},{1.0/6.0}}; + // kel::lbm::data<sch::FixedArray<sch::UInt64>,2u> blur_weights{{2.0/3.0},{1.0/6.0}}; auto meta = p_mask.dims(); - saw::data<sch::Array<T,D>> blurred_mask{meta}; + kel::lbm::data<sch::Array<T,D>> blurred_mask{meta}; /* 1D blur into N-D Blur*/ - for(saw::data<sch::UInt64> i{0u}; i < saw::data<sch::UInt64>{D}; ++i){ + for(kel::lbm::data<sch::UInt64> i{0u}; i < kel::lbm::data<sch::UInt64>{D}; ++i){ iterator<D>::apply([&](const auto& index){ blurred_mask.at(index) = p_mask.at(index) * mid; diff --git a/modules/core/c++/particle/cuboid/aabb.hpp b/modules/core/c++/particle/cuboid/aabb.hpp index 502132a..280eb07 100644 --- a/modules/core/c++/particle/cuboid/aabb.hpp +++ b/modules/core/c++/particle/cuboid/aabb.hpp @@ -20,13 +20,13 @@ public: public: template<typename Sch, typename Encode> - static constexpr saw::error_or<saw::data<AABB>> calculate(const saw::data<Sch,Encode>& pg, const saw::data<sch::FixedArray<sch::UInt64,1u>>& index, const saw::data<sch::FixedArray<sch::UInt64,D>>& meta){ + static constexpr kel::lbm::error_or<kel::lbm::data<AABB>> calculate(const kel::lbm::data<Sch,Encode>& pg, const kel::lbm::data<sch::FixedArray<sch::UInt64,1u>>& index, const kel::lbm::data<sch::FixedArray<sch::UInt64,D>>& meta){ static_assert(PC > 0u, "Can't calculate from no particle"); if(not (index.at({0u}).get() < PC)){ - return saw::make_error<saw::err::critical>("Too large i in particle_aabb coll::Cuboid<T>"); + return kel::lbm::make_error<kel::lbm::err::critical>("Too large i in particle_aabb coll::Cuboid<T>"); } - saw::data<AABB> aabb; + kel::lbm::data<AABB> aabb; auto& parts = pg.template get<"particles">(); auto& pi = parts.at(index); auto& pirb = pi.template get<"rigid_body">(); diff --git a/modules/core/c++/particle/geometry/circle.hpp b/modules/core/c++/particle/geometry/circle.hpp index cf9b87e..14300a5 100644 --- a/modules/core/c++/particle/geometry/circle.hpp +++ b/modules/core/c++/particle/geometry/circle.hpp @@ -13,8 +13,8 @@ public: {} template<typename MT = T> - saw::data<sch::ParticleMask<MT,D>> generate_mask(uint64_t resolution, uint64_t boundary_nodes = 0) const { - saw::data<sch::ParticleMask<MT,D>> mask; + kel::lbm::data<sch::ParticleMask<MT,D>> generate_mask(uint64_t resolution, uint64_t boundary_nodes = 0) const { + kel::lbm::data<sch::ParticleMask<MT,D>> mask; auto& grid = mask.template get<"grid">(); auto& com = mask.template get<"center_of_mass">(); @@ -25,10 +25,10 @@ public: uint64_t size = diameter_i + 2*boundary_nodes; grid = {{{size,size}}}; - saw::data<T> delta_x{static_cast<typename saw::native_data_type<T>::type>(2.0 / static_cast<double>(diameter_i))}; - saw::data<T> center = (saw::data<T>{1.0} + saw::data<T>{2.0} * saw::data<T>{static_cast<saw::native_data_type<T>::type>(boundary_nodes)/diameter_i}); + kel::lbm::data<T> delta_x{static_cast<typename kel::lbm::native_data_type<T>::type>(2.0 / static_cast<double>(diameter_i))}; + kel::lbm::data<T> center = (kel::lbm::data<T>{1.0} + kel::lbm::data<T>{2.0} * kel::lbm::data<T>{static_cast<kel::lbm::native_data_type<T>::type>(boundary_nodes)/diameter_i}); - saw::data<sch::FixedArray<sch::UInt64,D>> boundary_arr; + kel::lbm::data<sch::FixedArray<sch::UInt64,D>> boundary_arr; for(uint64_t i = 0u; i < D; ++i){ boundary_arr.set(boundary_nodes); } @@ -38,20 +38,20 @@ public: }, {}, grid.dims()); iterator<D>::apply([&](const auto& index){ - saw::data<sch::Vector<T,D>> f_ind; + kel::lbm::data<sch::Vector<T,D>> f_ind; for(uint64_t i = 0u; i < D; ++i){ f_ind.at({{i}}) = (index.at({{i}}) + 0.5) * delta_x - center; } - auto norm_f_ind = saw::math::norm(f_ind); + auto norm_f_ind = kel::lbm::math::norm(f_ind); }, {}, grid.dims(),boundary_arr); for(uint64_t i = 0; i < size; ++i){ for(uint64_t j = 0; j < size; ++j){ grid.at({{i,j}}).set(0); if(i >= boundary_nodes and j >= boundary_nodes and i < (diameter_i + boundary_nodes) and j < (diameter_i + boundary_nodes) ){ - saw::data<T> fi = saw::data<T>{static_cast<saw::native_data_type<T>::type>(0.5+i)} * delta_x - center; - saw::data<T> fj = saw::data<T>{static_cast<saw::native_data_type<T>::type>(0.5+j)} * delta_x - center; + kel::lbm::data<T> fi = kel::lbm::data<T>{static_cast<kel::lbm::native_data_type<T>::type>(0.5+i)} * delta_x - center; + kel::lbm::data<T> fj = kel::lbm::data<T>{static_cast<kel::lbm::native_data_type<T>::type>(0.5+j)} * delta_x - center; auto norm_f_ij = fi*fi + fj*fj; if(norm_f_ij.get() <= 1){ @@ -62,9 +62,9 @@ public: } // I don't fully remember what this did - saw::data<T> total_mass{}; - iterator::apply<D>::apply([&](const saw::data<sch::FixedArray<sch::UInt64,D>>& index){ - auto ind_vec = saw::math::vectorize_data(index).template cast_to<T>(); + kel::lbm::data<T> total_mass{}; + iterator::apply<D>::apply([&](const kel::lbm::data<sch::FixedArray<sch::UInt64,D>>& index){ + auto ind_vec = kel::lbm::math::vectorize_data(index).template cast_to<T>(); for(uint64_t i{0u}; i < D; ++i){ ind_vec.at({{i}}) = ind_vec.at({{i}}) * grid.at(index); } diff --git a/modules/core/c++/particle/geometry/cube.hpp b/modules/core/c++/particle/geometry/cube.hpp index 6392de8..8637aa5 100644 --- a/modules/core/c++/particle/geometry/cube.hpp +++ b/modules/core/c++/particle/geometry/cube.hpp @@ -9,9 +9,9 @@ class particle_cubic_geometry { private: public: template<typename MT = T> - saw::data<sch::ParticleMask<MT,D>> generate_mask(uint64_t resolution, uint64_t bound_nodes = 0u){ + kel::lbm::data<sch::ParticleMask<MT,D>> generate_mask(uint64_t resolution, uint64_t bound_nodes = 0u){ - saw::data<sch::ParticleMask<MT,D>> mask; + kel::lbm::data<sch::ParticleMask<MT,D>> mask; auto& grid = mask.template get<"grid">(); auto& com = mask.template get<"center_of_mass">(); diff --git a/modules/core/c++/particle/particle.hpp b/modules/core/c++/particle/particle.hpp index 25c1776..2b2ceac 100644 --- a/modules/core/c++/particle/particle.hpp +++ b/modules/core/c++/particle/particle.hpp @@ -1,8 +1,8 @@ #pragma once -#include <forstio/codec/math.hpp> -#include <forstio/codec/data_math.hpp> -#include <forstio/codec/data.hpp> +#include "../abstract/math.hpp" +#include "../abstract/data_math.hpp" +#include "../abstract/data.hpp" #include "../iterator.hpp" @@ -14,12 +14,12 @@ namespace kel { namespace lbm { template<typename T, uint64_t D,uint64_t PartAmount> -saw::data<sch::ParticleGroup<T, D, PartAmount, coll::Spheroid<T>>> create_spheroid_particle_group( - saw::data<sch::Scalar<T>> radius_p, - saw::data<sch::Scalar<T>> density_p, - const saw::data<sch::UInt64>& mask_resolution +kel::lbm::data<sch::ParticleGroup<T, D, PartAmount, coll::Spheroid<T>>> create_spheroid_particle_group( + kel::lbm::data<sch::Scalar<T>> radius_p, + kel::lbm::data<sch::Scalar<T>> density_p, + const kel::lbm::data<sch::UInt64>& mask_resolution ){ - saw::data<sch::ParticleGroup<T,D,PartAmount,coll::Spheroid<T>>> part; + kel::lbm::data<sch::ParticleGroup<T,D,PartAmount,coll::Spheroid<T>>> part; auto& rad_s = part.template get<"collision">().at({0u}).template get<"radius">(); rad_s = radius_p; @@ -34,12 +34,12 @@ saw::data<sch::ParticleGroup<T, D, PartAmount, coll::Spheroid<T>>> create_sphero static_assert(D >= 1u and D <= 3u, "Dimensions only supported for Dim 1,2 & 3."); density = density_p; - saw::data<sch::FixedArray<sch::UInt64,D>> mask_dims; + kel::lbm::data<sch::FixedArray<sch::UInt64,D>> mask_dims; for(uint64_t i = 0u; i < D; ++i){ mask_dims.at({i}) = mask_resolution; } - saw::data<T> rad_d = radius_p.at({}); - saw::data<T> dia_d = rad_d * 2; + kel::lbm::data<T> rad_d = radius_p.at({}); + kel::lbm::data<T> dia_d = rad_d * 2; mask = {mask_dims}; @@ -51,13 +51,13 @@ saw::data<sch::ParticleGroup<T, D, PartAmount, coll::Spheroid<T>>> create_sphero for(uint64_t i = 0u; i < D; ++i){ com.at({{i}}) = {}; } - saw::data<sch::UInt64> ele_ctr{0u}; + kel::lbm::data<sch::UInt64> ele_ctr{0u}; // Radius ^ 2 - saw::data<sch::Scalar<T>> rad_2_d; + kel::lbm::data<sch::Scalar<T>> rad_2_d; rad_2_d.at({}) = rad_d * rad_d; - saw::data<sch::Vector<T,D>> center; + kel::lbm::data<sch::Vector<T,D>> center; for(uint64_t i = 0u; i < D; ++i){ center.at({{i}}) = rad_d; } @@ -65,7 +65,7 @@ saw::data<sch::ParticleGroup<T, D, PartAmount, coll::Spheroid<T>>> create_sphero iterator<D>::apply([&](const auto& index){ ++ele_ctr; - saw::data<sch::Vector<T,D>> offset_index = saw::math::vectorize_data(index).template cast_to<T>() - center; + kel::lbm::data<sch::Vector<T,D>> offset_index = kel::lbm::math::vectorize_data(index).template cast_to<T>() - center; auto& dpi = mask.at(index); @@ -95,19 +95,19 @@ saw::data<sch::ParticleGroup<T, D, PartAmount, coll::Spheroid<T>>> create_sphero /* template<typename T, uint64_t D> -saw::data<sch::Particle<T,D, sch::ParticleCollisionSpheroid<T>>> create_spheroid_particle( - saw::data<sch::Vector<T,D>> pos_p, - saw::data<sch::Vector<T,D>> vec_p, - saw::data<sch::Vector<T,D>> acc_p, - saw::data<sch::Vector<T,D>> rot_pos_p, - saw::data<sch::Vector<T,D>> rot_vel_p, - saw::data<sch::Vector<T,D>> rot_acc_p, - saw::data<sch::Scalar<T>> rad_p, - saw::data<sch::Scalar<T>> density_p, - saw::data<sch::Scalar<T>> dt +kel::lbm::data<sch::Particle<T,D, sch::ParticleCollisionSpheroid<T>>> create_spheroid_particle( + kel::lbm::data<sch::Vector<T,D>> pos_p, + kel::lbm::data<sch::Vector<T,D>> vec_p, + kel::lbm::data<sch::Vector<T,D>> acc_p, + kel::lbm::data<sch::Vector<T,D>> rot_pos_p, + kel::lbm::data<sch::Vector<T,D>> rot_vel_p, + kel::lbm::data<sch::Vector<T,D>> rot_acc_p, + kel::lbm::data<sch::Scalar<T>> rad_p, + kel::lbm::data<sch::Scalar<T>> density_p, + kel::lbm::data<sch::Scalar<T>> dt ){ - saw::data<sch::Particle<T,D>> part; + kel::lbm::data<sch::Particle<T,D>> part; auto& body = part.template get<"rigid_body">(); auto& mass = part.template get<"mass">(); @@ -127,15 +127,15 @@ saw::data<sch::Particle<T,D, sch::ParticleCollisionSpheroid<T>>> create_spheroid rad = rad_p; if constexpr ( D == 1u){ - saw::data<sch::Scalar<T>> c; + kel::lbm::data<sch::Scalar<T>> c; c.at({}).set(2.0); mass = rad_p * c * density_p; } else if constexpr ( D == 2u){ - saw::data<sch::Scalar<T>> pi; + kel::lbm::data<sch::Scalar<T>> pi; pi.at({}).set(3.14159); mass = rad_p * rad_p * pi * density_p; } else if constexpr ( D == 3u ){ - saw::data<sch::Scalar<T>> c; + kel::lbm::data<sch::Scalar<T>> c; c.at({}).set(3.14159 * 4.0 / 3.0); mass = rad_p * rad_p * rad_p * c * density_p; } else { @@ -147,7 +147,7 @@ saw::data<sch::Particle<T,D, sch::ParticleCollisionSpheroid<T>>> create_spheroid */ template<typename T,uint64_t D> -constexpr auto verlet_step_lambda = [](saw::data<sch::Particle<T,D>>& particle, saw::data<sch::Scalar<T>> time_step_delta){ +constexpr auto verlet_step_lambda = [](kel::lbm::data<sch::Particle<T,D>>& particle, kel::lbm::data<sch::Scalar<T>> time_step_delta){ auto& body = particle.template get<"rigid_body">(); auto& pos = body.template get<"position">(); @@ -162,9 +162,9 @@ constexpr auto verlet_step_lambda = [](saw::data<sch::Particle<T,D>>& particle, auto tsd_squared = time_step_delta * time_step_delta; - saw::data<sch::Vector<T,D>> pos_new; + kel::lbm::data<sch::Vector<T,D>> pos_new; // Actual step - saw::data<sch::Scalar<T>> two; + kel::lbm::data<sch::Scalar<T>> two; two.at({}).set(2.0); pos_new = pos * two - pos_old + pos_acc * tsd_squared; @@ -173,7 +173,7 @@ constexpr auto verlet_step_lambda = [](saw::data<sch::Particle<T,D>>& particle, pos = pos_new; // Angular - saw::data<typename sch::impl::rotation_type_helper<T,D>::Schema> rot_new; + kel::lbm::data<typename sch::impl::rotation_type_helper<T,D>::Schema> rot_new; rot_new = rot * two - rot_old + rot_acc * tsd_squared; rot_old = rot; @@ -182,10 +182,10 @@ constexpr auto verlet_step_lambda = [](saw::data<sch::Particle<T,D>>& particle, template<typename T, uint64_t D> constexpr auto handle_collision = []( - saw::data<sch::Particle<T,D>>& left, const saw::data<sch::Scalar<T>>& mass_l, - saw::data<sch::Particle<T,D>>& right, const saw::data<sch::Scalar<T>>& mass_r, - saw::data<sch::Vector<T,D>> unit_pos_rel, saw::data<sch::Vector<T,D>> vel_rel, - saw::data<sch::Scalar<T>> d_t + kel::lbm::data<sch::Particle<T,D>>& left, const kel::lbm::data<sch::Scalar<T>>& mass_l, + kel::lbm::data<sch::Particle<T,D>>& right, const kel::lbm::data<sch::Scalar<T>>& mass_r, + kel::lbm::data<sch::Vector<T,D>> unit_pos_rel, kel::lbm::data<sch::Vector<T,D>> vel_rel, + kel::lbm::data<sch::Scalar<T>> d_t ){ auto& rb_l = left.template get<"rigid_body">(); auto& pos_l = rb_l.template get<"position">(); @@ -197,7 +197,7 @@ constexpr auto handle_collision = []( auto& pos_old_r = rb_r.template get<"position_old">(); auto vel_r = (pos_r-pos_old_r)/d_t; - auto vel_pos_rel_dot = saw::math::dot(unit_pos_rel,vel_rel); + auto vel_pos_rel_dot = kel::lbm::math::dot(unit_pos_rel,vel_rel); if( vel_pos_rel_dot.at({{0u}}).get() < 0.0 ){ pos_l = pos_l + vel_rel * unit_pos_rel * d_t; @@ -208,11 +208,11 @@ constexpr auto handle_collision = []( template<typename T, uint64_t D, typename Collision> constexpr auto broadphase_collision_distance_squared = []( - saw::data<sch::Particle<T,D>>& left, - const saw::data<Collision>& coll_l, - saw::data<sch::Particle<T,D>>& right, - const saw::data<Collision>& coll_r -) -> std::pair<bool,saw::data<sch::Scalar<T>>>{ + kel::lbm::data<sch::Particle<T,D>>& left, + const kel::lbm::data<Collision>& coll_l, + kel::lbm::data<sch::Particle<T,D>>& right, + const kel::lbm::data<Collision>& coll_r +) -> std::pair<bool,kel::lbm::data<sch::Scalar<T>>>{ auto rad_l = coll_l.template get<"radius">(); auto rad_r = coll_r.template get<"radius">(); @@ -225,9 +225,9 @@ constexpr auto broadphase_collision_distance_squared = []( auto pos_dist = pos_l - pos_r; - auto norm_2 = saw::math::dot(pos_dist,pos_dist); + auto norm_2 = kel::lbm::math::dot(pos_dist,pos_dist); - saw::data<sch::Scalar<T>> two; + kel::lbm::data<sch::Scalar<T>> two; two.at({}) = 2.0; auto rad_ab_2 = rad_l * rad_l + rad_r * rad_r + rad_r * rad_l * two; @@ -239,16 +239,16 @@ constexpr auto broadphase_collision_distance_squared = []( */ template<typename T, uint64_t D, typename Collision> constexpr auto broadphase_collision_check = []( - saw::data<sch::Particle<T,D>>& left, - const saw::data<Collision>& coll_l, - saw::data<sch::Particle<T,D>>& right, - const saw::data<Collision>& coll_r + kel::lbm::data<sch::Particle<T,D>>& left, + const kel::lbm::data<Collision>& coll_l, + kel::lbm::data<sch::Particle<T,D>>& right, + const kel::lbm::data<Collision>& coll_r ) -> bool{ return broadphase_collision_distance_squared<T,D,Collision>(left,coll_l,right,coll_r).first; }; template<typename T,uint64_t D, uint64_t PartAmount> -constexpr auto particle_dem_lambda = [](saw::data<sch::ParticleGroup<T,D,PartAmount, coll::Spheroid<T>>>& particle, saw::data<sch::Scalar<T>> time_step_delta){ +constexpr auto particle_dem_lambda = [](kel::lbm::data<sch::ParticleGroup<T,D,PartAmount, coll::Spheroid<T>>>& particle, kel::lbm::data<sch::Scalar<T>> time_step_delta){ for(uint64_t i{0u}; i < PartAmount; ++i){ auto has_collided = false; } diff --git a/modules/core/c++/particle/particle_opa.hpp b/modules/core/c++/particle/particle_opa.hpp index ce1ecb7..2f4608c 100644 --- a/modules/core/c++/particle/particle_opa.hpp +++ b/modules/core/c++/particle/particle_opa.hpp @@ -15,14 +15,14 @@ template<typename T, typename Descriptor, typename Encode> class component<T,Descriptor,cmpt::OneParticleAt, Encode> final { private: - saw::data<sch::Vector<T,Descriptor::D>> pos_; - saw::data<sch::Scalar<T>> rad_; - saw::data<sch::Scalar<T>> eps_; + kel::lbm::data<sch::Vector<T,Descriptor::D>> pos_; + kel::lbm::data<sch::Scalar<T>> rad_; + kel::lbm::data<sch::Scalar<T>> eps_; public: component( - const saw::data<sch::Vector<T,Descriptor::D>> pos__, - const saw::data<sch::Scalar<T>> rad__, - const saw::data<sch::Scalar<T>> eps__ + const kel::lbm::data<sch::Vector<T,Descriptor::D>> pos__, + const kel::lbm::data<sch::Scalar<T>> rad__, + const kel::lbm::data<sch::Scalar<T>> eps__ ): pos_{pos__}, rad_{rad__}, @@ -30,17 +30,17 @@ public: {} template<typename MacroFieldSchema> - void apply(const saw::data<MacroFieldSchema, Encode>& macros, const saw::data<sch::FixedArray<sch::UInt64,Descriptor::D>> index, saw::data<sch::UInt64> time_step) const { + void apply(const kel::lbm::data<MacroFieldSchema, Encode>& macros, const kel::lbm::data<sch::FixedArray<sch::UInt64,Descriptor::D>> index, kel::lbm::data<sch::UInt64> time_step) const { using dfi = df_info<T,Descriptor>; auto& porous_f = macros.template get<"porosity">(); auto& porous = porous_f.at(index); - auto pos_ind = saw::math::vectorize_data(index); + auto pos_ind = kel::lbm::math::vectorize_data(index); // Write out value auto diff = pos_ind.template cast_to<T>() - pos_; - auto diff_dot = saw::math::dot(diff,diff); + auto diff_dot = kel::lbm::math::dot(diff,diff); porous = particle_porosity<T,Descriptor::D,1u,por::ParticleSpheroid<T>>::calculate(diff, rad_, eps_); } }; diff --git a/modules/core/c++/particle/porosity.hpp b/modules/core/c++/particle/porosity.hpp index 07e5c9e..0fe630d 100644 --- a/modules/core/c++/particle/porosity.hpp +++ b/modules/core/c++/particle/porosity.hpp @@ -15,7 +15,7 @@ template<typename T, uint64_t D, uint64_t PC, typename Coll> class particle_porosity { public: - static saw::data<sch::Scalar<T>> calculate(const saw::data<sch::ParticleGroup<T,D,PC,Coll>>& part_group, uint64_t p_i, const saw::data<sch::Vector<T,D>>& lbm_pos){ + static kel::lbm::data<sch::Scalar<T>> calculate(const kel::lbm::data<sch::ParticleGroup<T,D,PC,Coll>>& part_group, uint64_t p_i, const kel::lbm::data<sch::Vector<T,D>>& lbm_pos){ auto& mask = part_group.template get<"mask">(); auto& particles = part_group.template get<"particles">(); @@ -35,13 +35,13 @@ public: template<typename T, uint64_t D> class particle_porosity<T, D, 1u, por::ParticleSpheroid<T>> final { public: - static saw::data<sch::Scalar<T>> calculate(const saw::data<sch::Vector<T,D>>& lbm_rel_dist, saw::data<sch::Scalar<T>> rad, saw::data<sch::Scalar<T>> eps){ - saw::data<sch::Scalar<T>> por; + static kel::lbm::data<sch::Scalar<T>> calculate(const kel::lbm::data<sch::Vector<T,D>>& lbm_rel_dist, kel::lbm::data<sch::Scalar<T>> rad, kel::lbm::data<sch::Scalar<T>> eps){ + kel::lbm::data<sch::Scalar<T>> por; - saw::data<sch::Scalar<T>> s_dist_2 = saw::math::dot(lbm_rel_dist,lbm_rel_dist); - saw::data<sch::Scalar<T>> s_dist = saw::math::sqrt(s_dist_2); + kel::lbm::data<sch::Scalar<T>> s_dist_2 = kel::lbm::math::dot(lbm_rel_dist,lbm_rel_dist); + kel::lbm::data<sch::Scalar<T>> s_dist = kel::lbm::math::sqrt(s_dist_2); - saw::data<sch::Scalar<T>> eps_h; + kel::lbm::data<sch::Scalar<T>> eps_h; eps_h.at({}) = eps.at({}).get() / 2; auto rad_low = rad - eps_h; @@ -57,7 +57,7 @@ public: } { - typename saw::native_data_type<T>::type inner = (std::numbers::pi / ( 2 * eps.at({}).get() )) * (s_dist - rad_low).at({}).get(); + typename kel::lbm::native_data_type<T>::type inner = (std::numbers::pi / ( 2 * eps.at({}).get() )) * (s_dist - rad_low).at({}).get(); auto cos_inner = std::sin(inner); auto cos_i_2 = cos_inner * cos_inner; por.at({}).set(cos_i_2); @@ -71,8 +71,8 @@ public: template<typename T, uint64_t D, uint64_t PC> class particle_porosity<T, D, PC, coll::Spheroid<T>> final { public: - static saw::data<sch::Scalar<T>> calculate(const saw::data<sch::ParticleGroup<T,D,PC,coll::Spheroid<T> > >& part_group, uint64_t i, const saw::data<sch::Vector<T,D>>& lbm_pos) { - saw::data<sch::Scalar<T>> por; + static kel::lbm::data<sch::Scalar<T>> calculate(const kel::lbm::data<sch::ParticleGroup<T,D,PC,coll::Spheroid<T> > >& part_group, uint64_t i, const kel::lbm::data<sch::Vector<T,D>>& lbm_pos) { + kel::lbm::data<sch::Scalar<T>> por; auto& parts = part_group.template get<"particles">(); auto& pi = parts.at({i}); @@ -83,26 +83,26 @@ public: // Basically the queried position minus the center of the particle auto dist = lbm_pos - pi_rb_pos; - saw::data<sch::Scalar<T>> dist_len = saw::math::dot(dist,dist); + kel::lbm::data<sch::Scalar<T>> dist_len = kel::lbm::math::dot(dist,dist); dist_len.at({}).set(std::sqrt(dist_len.at({}).get())); auto& coll = part_group.template get<"collision">().at({}); - const saw::data<sch::Scalar<T>>& rad_d = coll.template get<"radius">(); + const kel::lbm::data<sch::Scalar<T>>& rad_d = coll.template get<"radius">(); const auto& eps = part_group.template get<"epsilon">().at({}); // Move this somewhere - saw::data<sch::Scalar<T>> eps_h; + kel::lbm::data<sch::Scalar<T>> eps_h; eps_h.at({}) = eps.at({}).get() / 2; - saw::data<sch::Scalar<T>> rad_d_eps_p = rad_d + eps_h; - saw::data<sch::Scalar<T>> rad_d_eps_n = rad_d - eps_h; + kel::lbm::data<sch::Scalar<T>> rad_d_eps_p = rad_d + eps_h; + kel::lbm::data<sch::Scalar<T>> rad_d_eps_n = rad_d - eps_h; - // saw::data<sch::Scalar<T>> rad_d_eps_p_2 = rad_d_eps_p * rad_d_eps_p; - // saw::data<sch::Scalar<T>> rad_d_eps_n_2 = rad_d_eps_n * rad_d_eps_n; - // saw::data<sch::Scalar<T>> rad_2; + // kel::lbm::data<sch::Scalar<T>> rad_d_eps_p_2 = rad_d_eps_p * rad_d_eps_p; + // kel::lbm::data<sch::Scalar<T>> rad_d_eps_n_2 = rad_d_eps_n * rad_d_eps_n; + // kel::lbm::data<sch::Scalar<T>> rad_2; // rad_2 = rad_d * rad_d; - saw::data<sch::Scalar<T>> inside; + kel::lbm::data<sch::Scalar<T>> inside; if(dist_len.at({}) <= rad_d_eps_n.at({})){ inside.at({}).set(0); return inside; @@ -116,7 +116,7 @@ public: * cos^2 ( ||x-X(t)||_2 - (R-eps/2) ) */ { - typename saw::native_data_type<T>::type inner = (std::numbers::pi / (eps.at({}).get())) * (dist_len - rad_d_eps_n).at({}).get(); + typename kel::lbm::native_data_type<T>::type inner = (std::numbers::pi / (eps.at({}).get())) * (dist_len - rad_d_eps_n).at({}).get(); auto cos_inner = std::cos(inner); auto cos_i_2 = cos_inner * cos_inner; inside.at({}).set(cos_i_2); diff --git a/modules/core/c++/particle/schema.hpp b/modules/core/c++/particle/schema.hpp index 221137a..40033cd 100644 --- a/modules/core/c++/particle/schema.hpp +++ b/modules/core/c++/particle/schema.hpp @@ -16,7 +16,6 @@ struct Spheroid { } namespace sch { -using namespace saw::schema; namespace impl { template<typename T,uint64_t D> diff --git a/modules/core/c++/psm.hpp b/modules/core/c++/psm.hpp index 40323b3..b3a2673 100644 --- a/modules/core/c++/psm.hpp +++ b/modules/core/c++/psm.hpp @@ -21,7 +21,7 @@ public: component() = default; template<typename CellFieldSchema, typename MacroFieldSchema> - void apply(const saw::data<CellFieldSchema, Encode>& field, const saw::data<MacroFieldSchema,Encode>& macros, saw::data<sch::FixedArray<sch::UInt64,Descriptor::D>> index, saw::data<sch::UInt64> time_step) const { + void apply(const kel::lbm::data<CellFieldSchema, Encode>& field, const kel::lbm::data<MacroFieldSchema,Encode>& macros, kel::lbm::data<sch::FixedArray<sch::UInt64,Descriptor::D>> index, kel::lbm::data<sch::UInt64> time_step) const { auto& porosity_f = macros.template get<"porosity">(); auto& por = porosity_f.at(index); @@ -35,26 +35,26 @@ public: template<typename T, typename Descriptor, typename Encode> class component<T, Descriptor, cmpt::Psm, Encode> { private: - saw::data<T> relaxation_; - saw::data<T> frequency_; + kel::lbm::data<T> relaxation_; + kel::lbm::data<T> frequency_; public: component( - typename saw::native_data_type<T>::type relaxation__ + typename kel::lbm::native_data_type<T>::type relaxation__ ): relaxation_{relaxation__} { - saw::data<T> one; + kel::lbm::data<T> one; one = 1.0; frequency_ = one / relaxation_; } - component(const saw::data<sch::Pure<T>>& relaxation__): + component(const kel::lbm::data<sch::Pure<T>>& relaxation__): relaxation_{relaxation__.handle()}, - frequency_{saw::data<T>{typename saw::native_data_type<T>::type(1)} / relaxation_} + frequency_{kel::lbm::data<T>{typename kel::lbm::native_data_type<T>::type(1)} / relaxation_} {} template<typename CellFieldSchema, typename MacroFieldSchema> - void apply(const saw::data<CellFieldSchema, Encode>& field, const saw::data<MacroFieldSchema,Encode>& macros, saw::data<sch::FixedArray<sch::UInt64,Descriptor::D>> index, saw::data<sch::UInt64> time_step) const { + void apply(const kel::lbm::data<CellFieldSchema, Encode>& field, const kel::lbm::data<MacroFieldSchema,Encode>& macros, kel::lbm::data<sch::FixedArray<sch::UInt64,Descriptor::D>> index, kel::lbm::data<sch::UInt64> time_step) const { using dfi = df_info<T,Descriptor>; bool is_even = ((time_step.get() % 2) == 0); @@ -65,14 +65,14 @@ public: auto& rho_f = macros.template get<"density">(); auto& vel_f = macros.template get<"momentum">(); - saw::data<sch::Scalar<T>>& rho = rho_f.at(index); - saw::data<sch::Vector<T,Descriptor::D>>& vel = vel_f.at(index); + kel::lbm::data<sch::Scalar<T>>& rho = rho_f.at(index); + kel::lbm::data<sch::Vector<T,Descriptor::D>>& vel = vel_f.at(index); compute_rho_u<T,Descriptor>(dfs_old_f.at(index),rho,vel); auto eq = equilibrium<T,Descriptor>(rho,vel); - saw::data<T> one{1.0}; + kel::lbm::data<T> one{1.0}; auto& porous = porous_f.at(index); auto flip_porous = one - porous.at({}); @@ -98,12 +98,12 @@ public: template<typename CellFieldSchema, typename MacroFieldSchema, typename ParticleSchema> void apply( - const saw::data<CellFieldSchema, Encode>& field, - const saw::data<MacroFieldSchema, Encode>& macros, - const saw::data<ParticleSchema, Encode>& pg, - saw::data<sch::FixedArray<sch::UInt64,1u>> index, - saw::data<sch::UInt64> time_step, - saw::data<sch::UInt64> sub_steps + const kel::lbm::data<CellFieldSchema, Encode>& field, + const kel::lbm::data<MacroFieldSchema, Encode>& macros, + const kel::lbm::data<ParticleSchema, Encode>& pg, + kel::lbm::data<sch::FixedArray<sch::UInt64,1u>> index, + kel::lbm::data<sch::UInt64> time_step, + kel::lbm::data<sch::UInt64> sub_steps ) const { using dfi = df_info<T,Descriptor>; @@ -126,10 +126,10 @@ void apply( auto& vel_f = macros.template get<"momentum">(); auto& force_f = macros.template get<"force">(); - saw::data<sch::Scalar<T>> one; + kel::lbm::data<sch::Scalar<T>> one; one.at({}) = 1.0; - saw::data<sch::Scalar<T>> half; + kel::lbm::data<sch::Scalar<T>> half; half.at({}) = 0.5; /* @@ -152,7 +152,7 @@ void apply( auto& pirb = pi.template get<"rigid_body">(); - saw::data<sch::Vector<T,Descriptor::D>>& pirb_pos = + kel::lbm::data<sch::Vector<T,Descriptor::D>>& pirb_pos = pirb.template get<"position">(); auto& pirb_pos_old = @@ -165,7 +165,7 @@ void apply( * -------------------------------------------------------- */ - saw::data<sch::Scalar<T>> ts; + kel::lbm::data<sch::Scalar<T>> ts; ts.at({}) = one.at({}) @@ -203,8 +203,8 @@ void apply( auto& aabb = eo_aabb.get_value(); - saw::data<sch::FixedArray<sch::UInt64,Descriptor::D>> start; - saw::data<sch::FixedArray<sch::UInt64,Descriptor::D>> stop; + kel::lbm::data<sch::FixedArray<sch::UInt64,Descriptor::D>> start; + kel::lbm::data<sch::FixedArray<sch::UInt64,Descriptor::D>> stop; start = aabb.template get<"a">(); stop = aabb.template get<"b">(); @@ -216,7 +216,7 @@ void apply( * -------------------------------------------------------- */ - saw::data<sch::Vector<T,Descriptor::D>> force_p; + kel::lbm::data<sch::Vector<T,Descriptor::D>> force_p; for(uint64_t k = 0u; k < Descriptor::D; ++k){ force_p.at({{k}}) = 0.0; @@ -248,8 +248,8 @@ void apply( * ------------------------------------------------ */ - saw::data<sch::Vector<T,Descriptor::D>> rel_dist = - saw::math::vectorize_data(index_f) + kel::lbm::data<sch::Vector<T,Descriptor::D>> rel_dist = + kel::lbm::math::vectorize_data(index_f) .template cast_to<T>() - pirb_pos; @@ -260,7 +260,7 @@ void apply( * ------------------------------------------------ */ - saw::data<sch::Scalar<T>> eps; + kel::lbm::data<sch::Scalar<T>> eps; eps.at({}) = 1.5; auto& por = @@ -294,7 +294,7 @@ void apply( * ------------------------------------------------ */ - saw::data<sch::Vector<T,Descriptor::D>> momentum; + kel::lbm::data<sch::Vector<T,Descriptor::D>> momentum; for(uint64_t k = 0u; k < Descriptor::D; ++k){ momentum.at({{k}}) = 0.0; @@ -319,9 +319,9 @@ void apply( * Direction vector e_i. */ - saw::data<sch::Vector<T,Descriptor::D>> e_i; + kel::lbm::data<sch::Vector<T,Descriptor::D>> e_i; - saw::data< + kel::lbm::data< sch::FixedArray< sch::UInt64, Descriptor::D @@ -353,7 +353,7 @@ void apply( */ auto u_p_e = - saw::math::dot( + kel::lbm::math::dot( e_i, vel_p_old ); @@ -371,10 +371,10 @@ void apply( * ------------------------------------------------ */ - saw::data<T> dfs_added = + kel::lbm::data<T> dfs_added = dfs.at({i}) * ( - saw::data<T>{1.0} + kel::lbm::data<T>{1.0} - u_p_e.at({}) ) @@ -382,7 +382,7 @@ void apply( .at(n_ind_i) .at({i_opp}) * ( - saw::data<T>{1.0} + kel::lbm::data<T>{1.0} + u_p_e.at({}) ); @@ -391,7 +391,7 @@ void apply( * Convert scalar into vector multiplication. */ - saw::data<sch::Scalar<T>> dfs_added_v; + kel::lbm::data<sch::Scalar<T>> dfs_added_v; dfs_added_v.at({}) = dfs_added; @@ -457,7 +457,7 @@ void apply( * ------------------------------------------------------------ */ - for(saw::data<sch::UInt64> i{0u}; + for(kel::lbm::data<sch::UInt64> i{0u}; i < sub_steps; ++i){ diff --git a/modules/core/c++/rar.hpp b/modules/core/c++/rar.hpp index dc2b61c..7cf9e36 100644 --- a/modules/core/c++/rar.hpp +++ b/modules/core/c++/rar.hpp @@ -4,7 +4,7 @@ namespace kel { namespace lbm { -saw::error_or<void> run_and_record(int argc, char** argv){ +kel::lbm::error_or<void> run_and_record(int argc, char** argv){ using RarGit = Struct< Member<String, "commit">, Member<String, "origin"> @@ -19,7 +19,7 @@ saw::error_or<void> run_and_record(int argc, char** argv){ Member<RarGit, "git"> >; - return saw::make_void(); + return kel::lbm::make_void(); } } } diff --git a/modules/core/c++/schema.hpp b/modules/core/c++/schema.hpp index 7712f99..ef2067d 100644 --- a/modules/core/c++/schema.hpp +++ b/modules/core/c++/schema.hpp @@ -1,11 +1,10 @@ #pragma once -#include <forstio/codec/schema.hpp> +#include "abstract/schema.hpp" namespace kel { namespace lbm { namespace sch { -using namespace saw::schema; } } } diff --git a/modules/core/c++/stream.hpp b/modules/core/c++/stream.hpp index dc7cfb3..684a6d0 100644 --- a/modules/core/c++/stream.hpp +++ b/modules/core/c++/stream.hpp @@ -12,12 +12,12 @@ template<typename T, typename Descriptor, typename Encode> class component<T,Descriptor, cmpt::Stream, Encode> final { private: public: - static constexpr saw::string_literal name = "streaming"; - static constexpr saw::string_literal after = "collide"; - static constexpr saw::string_literal before = ""; + static constexpr kel::lbm::string_literal name = "streaming"; + static constexpr kel::lbm::string_literal after = "collide"; + static constexpr kel::lbm::string_literal before = ""; template<typename CellFieldSchema> - void apply(const saw::data<CellFieldSchema, Encode>& field, saw::data<sch::FixedArray<sch::UInt64,Descriptor::D>> index, saw::data<sch::UInt64> time_step) const { + void apply(const kel::lbm::data<CellFieldSchema, Encode>& field, kel::lbm::data<sch::FixedArray<sch::UInt64,Descriptor::D>> index, kel::lbm::data<sch::UInt64> time_step) const { using dfi = df_info<T,Descriptor>; auto g_index = index; diff --git a/modules/core/c++/util.hpp b/modules/core/c++/util.hpp index 0bdebd1..8bafc16 100644 --- a/modules/core/c++/util.hpp +++ b/modules/core/c++/util.hpp @@ -1,7 +1,7 @@ #pragma once -#include <forstio/string_literal.hpp> -#include <forstio/codec/data.hpp> +#include "abstract/string_literal.hpp" +#include "abstract/data.hpp" #include <iostream> #include <iomanip> @@ -12,16 +12,16 @@ namespace lbm { /* template<typename T, typename Descriptor, typename CellFieldSchema> struct is_neighbour { - static bool operator()(saw::data<CellFieldSchema>& latt, saw::data<sch::FixedArray<sch::UInt64, Descriptor::D>& index) { + static bool operator()(kel::lbm::data<CellFieldSchema>& latt, kel::lbm::data<sch::FixedArray<sch::UInt64, Descriptor::D>& index) { using dfi = df_info<T,Descriptor>; if(index.at({0u}).get() == 0u or index.at({1u}).get() == 0u){ return false; } - for(saw::data<sch::UInt64> k{0u}; k.get() < Descriptor::Q; ++k){ + for(kel::lbm::data<sch::UInt64> k{0u}; k.get() < Descriptor::Q; ++k){ // TODO - saw::data<sch::FixedArray<sch::UInt64,2u>> + kel::lbm::data<sch::FixedArray<sch::UInt64,2u>> } auto& cell = latt(index); diff --git a/modules/core/c++/write_csv.hpp b/modules/core/c++/write_csv.hpp index aa28613..36d84df 100644 --- a/modules/core/c++/write_csv.hpp +++ b/modules/core/c++/write_csv.hpp @@ -1,9 +1,9 @@ #pragma once -#include <forstio/error.hpp> +#include "abstract/error.hpp" -#include <forstio/codec/data.hpp> -#include <forstio/codec/data_math.hpp> +#include "abstract/data.hpp" +#include "abstract/data_math.hpp" #include "descriptor.hpp" #include "flatten.hpp" @@ -22,21 +22,21 @@ struct lbm_csv_writer { template<typename T, uint64_t D> struct lbm_csv_writer<sch::Primitive<T,D>> { - static saw::error_or<void> apply(std::ostream& csv_file, const saw::data<sch::Primitive<T,D>>& field){ + static kel::lbm::error_or<void> apply(std::ostream& csv_file, const kel::lbm::data<sch::Primitive<T,D>>& field){ if constexpr (std::is_same_v<T,sch::UnsignedInteger> and D == 1u) { csv_file<<field.template cast_to<sch::UInt16>().get(); }else{ csv_file<<field.get(); } - return saw::make_void(); + return kel::lbm::make_void(); } }; template<typename T, uint64_t D> struct lbm_csv_writer<sch::FixedArray<T,D>> { - static saw::error_or<void> apply(std::ostream& csv_file, const saw::data<sch::FixedArray<T,D>>& field){ - saw::data<sch::FixedArray<sch::UInt64,D>> index; - for(saw::data<sch::UInt64> it{0}; it.get() < D; ++it){ + static kel::lbm::error_or<void> apply(std::ostream& csv_file, const kel::lbm::data<sch::FixedArray<T,D>>& field){ + kel::lbm::data<sch::FixedArray<sch::UInt64,D>> index; + for(kel::lbm::data<sch::UInt64> it{0}; it.get() < D; ++it){ index.at({0u}).set(0u); } @@ -47,7 +47,7 @@ struct lbm_csv_writer<sch::FixedArray<T,D>> { } csv_file<<field.at({i}).get(); } - return saw::make_void(); + return kel::lbm::make_void(); } }; @@ -55,7 +55,7 @@ template<typename T, uint64_t Ghost, uint64_t... D> struct lbm_csv_writer<sch::Chunk<T,Ghost,D...>> { template<uint64_t d> - static saw::error_or<void> apply_d(std::ostream& csv_file, const saw::data<sch::Chunk<T,Ghost,D...>>& field, saw::data<sch::FixedArray<sch::UInt64,sizeof...(D)>>& index){ + static kel::lbm::error_or<void> apply_d(std::ostream& csv_file, const kel::lbm::data<sch::Chunk<T,Ghost,D...>>& field, kel::lbm::data<sch::FixedArray<sch::UInt64,sizeof...(D)>>& index){ // VTK wants to iterate over z,y,x instead of x,y,z // So we do the same with CSV to stay consistent for now // We could reorder the dimensions, but eh @@ -68,12 +68,12 @@ struct lbm_csv_writer<sch::Chunk<T,Ghost,D...>> { csv_file<<"\n"; if(eov.is_error()) return eov; } - return saw::make_void(); + return kel::lbm::make_void(); } - static saw::error_or<void> apply(std::ostream& csv_file, const saw::data<sch::Chunk<T,Ghost,D...>>& field, std::string_view name){ - saw::data<sch::FixedArray<sch::UInt64,sizeof...(D)>> index; - for(saw::data<sch::UInt64> it{0}; it.get() < sizeof...(D); ++it){ + static kel::lbm::error_or<void> apply(std::ostream& csv_file, const kel::lbm::data<sch::Chunk<T,Ghost,D...>>& field, std::string_view name){ + kel::lbm::data<sch::FixedArray<sch::UInt64,sizeof...(D)>> index; + for(kel::lbm::data<sch::UInt64> it{0}; it.get() < sizeof...(D); ++it){ index.at({0u}).set(0u); } @@ -84,13 +84,13 @@ struct lbm_csv_writer<sch::Chunk<T,Ghost,D...>> { } } - return saw::make_void(); + return kel::lbm::make_void(); } }; template<typename T, uint64_t D> struct lbm_csv_writer<sch::Vector<T,D>> { - static saw::error_or<void> apply(std::ostream& csv_file, const saw::data<sch::Vector<T,D>>& field){ + static kel::lbm::error_or<void> apply(std::ostream& csv_file, const kel::lbm::data<sch::Vector<T,D>>& field){ static_assert(D > 0, "Non-dimensionality is bad for momentum."); // csv_file<<"VECTORS "<<name<<" float\n"; @@ -103,26 +103,26 @@ struct lbm_csv_writer<sch::Vector<T,D>> { if(eov.is_error()) return eov; } } - return saw::make_void(); + return kel::lbm::make_void(); } }; template<typename T> struct lbm_csv_writer<sch::Scalar<T>> { - static saw::error_or<void> apply(std::ostream& csv_file, const saw::data<sch::Scalar<T>>& field){ + static kel::lbm::error_or<void> apply(std::ostream& csv_file, const kel::lbm::data<sch::Scalar<T>>& field){ return lbm_csv_writer<T>::apply(csv_file,field.at({})); } }; -template<typename... MemberT, saw::string_literal... Keys, uint64_t... Ghost, uint64_t... Dims> +template<typename... MemberT, kel::lbm::string_literal... Keys, uint64_t... Ghost, uint64_t... Dims> struct lbm_csv_writer<sch::Struct<sch::Member<sch::Chunk<MemberT,Ghost,Dims...>,Keys>...>> final { template<uint64_t i> - static saw::error_or<void> iterate_i( + static kel::lbm::error_or<void> iterate_i( const std::filesystem::path& csv_dir, const std::string_view& file_base_name, uint64_t d_t, - const saw::data<sch::Struct<sch::Member<sch::Chunk<MemberT,Ghost,Dims...>,Keys>...>>& field){ + const kel::lbm::data<sch::Struct<sch::Member<sch::Chunk<MemberT,Ghost,Dims...>,Keys>...>>& field){ if constexpr ( i < sizeof...(MemberT) ) { - using MT = typename saw::parameter_pack_type<i,sch::Member<sch::Chunk<MemberT,Ghost,Dims...>,Keys>...>::type; + using MT = typename kel::lbm::parameter_pack_type<i,sch::Member<sch::Chunk<MemberT,Ghost,Dims...>,Keys>...>::type; { std::stringstream sstr; sstr @@ -136,7 +136,7 @@ struct lbm_csv_writer<sch::Struct<sch::Member<sch::Chunk<MemberT,Ghost,Dims...>, std::ofstream csv_file{csv_dir / sstr.str() }; if( not csv_file.is_open() ){ - return saw::make_error<saw::err::critical>("Could not open file."); + return kel::lbm::make_error<kel::lbm::err::critical>("Could not open file."); } // auto eov = lbm_csv_writer<typename MT::ValueType>::apply(csv_file,field.template get<MT::KeyLiteral>(), MT::KeyLiteral.view()); @@ -148,15 +148,15 @@ struct lbm_csv_writer<sch::Struct<sch::Member<sch::Chunk<MemberT,Ghost,Dims...>, return iterate_i<i+1u>(csv_dir, file_base_name, d_t,field); } - return saw::make_void(); + return kel::lbm::make_void(); } - static saw::error_or<void> apply( + static kel::lbm::error_or<void> apply( const std::filesystem::path& csv_dir, const std::string_view& file_base_name, uint64_t d_t, - const saw::data<sch::Struct<sch::Member<sch::Chunk<MemberT,Ghost,Dims...>,Keys>...>>& field){ + const kel::lbm::data<sch::Struct<sch::Member<sch::Chunk<MemberT,Ghost,Dims...>,Keys>...>>& field){ - auto& field_0 = field.template get<saw::parameter_key_pack_type<0u,Keys...>::literal>(); + auto& field_0 = field.template get<kel::lbm::parameter_key_pack_type<0u,Keys...>::literal>(); auto meta = field_0.get_dims(); return iterate_i<0u>(csv_dir,file_base_name, d_t, field); @@ -166,14 +166,14 @@ struct lbm_csv_writer<sch::Struct<sch::Member<sch::Chunk<MemberT,Ghost,Dims...>, } template<typename Sch> -saw::error_or<void> write_csv_file(const std::filesystem::path& out_dir, const std::string_view& file_name, uint64_t d_t, const saw::data<Sch>& field){ +kel::lbm::error_or<void> write_csv_file(const std::filesystem::path& out_dir, const std::string_view& file_name, uint64_t d_t, const kel::lbm::data<Sch>& field){ auto csv_dir = out_dir / "csv"; { std::error_code ec; std::filesystem::create_directories(csv_dir,ec); if(ec != std::errc{}){ - return saw::make_error<saw::err::critical>("Could not create directory for write_csv_file function"); + return kel::lbm::make_error<kel::lbm::err::critical>("Could not create directory for write_csv_file function"); } } auto eov = impl::lbm_csv_writer<Sch>::apply(csv_dir, file_name, d_t, field); diff --git a/modules/core/c++/write_json.hpp b/modules/core/c++/write_json.hpp index 19bbfa6..e78269b 100644 --- a/modules/core/c++/write_json.hpp +++ b/modules/core/c++/write_json.hpp @@ -1,27 +1,41 @@ #pragma once -#include <forstio/error.hpp> +#include "abstract/error.hpp" -#include <forstio/codec/data.hpp> -#include <forstio/codec/data_math.hpp> - -#include <forstio/codec/json/json.hpp> +#include "abstract/data.hpp" +#include "abstract/data_math.hpp" +#include "abstract/json.hpp" +#include <filesystem> +#include <fstream> namespace kel { namespace lbm { template<typename Schema> -saw::error_or<void> write_json(const std::filesystem::path& file_name, const saw::data<Schema>& field){ - saw::data<Schema, saw::encode::Json> j_data; +error_or<void> write_json(const std::filesystem::path& file_name, const data<Schema>& field){ + data<Schema, enc::Json> j_data; { - saw::codec<Schema, saw::encode::Json> j_codec; + codec<Schema, enc::Json> j_codec; + j_codec.set_pretty(true); auto eov = j_codec.encode(field, j_data); if(eov.is_error()){ return eov; } } - return saw::make_void(); + + std::ofstream json_file{file_name, std::ios::binary | std::ios::trunc}; + if(!json_file.is_open()){ + return make_error<err::not_found>("Couldn't open file for writing"); + } + + const auto& text = j_data.stl_string(); + json_file.write(text.data(), static_cast<std::streamsize>(text.size())); + if(!json_file){ + return make_error<err::invalid_state>("Couldn't write json file"); + } + + return make_void(); } } } diff --git a/modules/core/c++/write_vtk.hpp b/modules/core/c++/write_vtk.hpp index 67e8a2f..028a26f 100644 --- a/modules/core/c++/write_vtk.hpp +++ b/modules/core/c++/write_vtk.hpp @@ -1,9 +1,9 @@ #pragma once -#include <forstio/error.hpp> +#include "abstract/error.hpp" -#include <forstio/codec/data.hpp> -#include <forstio/codec/data_math.hpp> +#include "abstract/data.hpp" +#include "abstract/data_math.hpp" #include "descriptor.hpp" #include "flatten.hpp" @@ -22,31 +22,31 @@ struct lbm_vtk_writer { template<typename T, uint64_t D> struct lbm_vtk_writer<sch::Primitive<T,D>> { - static saw::error_or<void> apply_header(std::ostream& vtk_file, std::string_view name){ + static kel::lbm::error_or<void> apply_header(std::ostream& vtk_file, std::string_view name){ vtk_file<<"SCALARS "<<name<<" float 1\n"; vtk_file<<"LOOKUP_TABLE default\n"; - return saw::make_void(); + return kel::lbm::make_void(); } - static saw::error_or<void> apply(std::ostream& vtk_file, const saw::data<sch::Primitive<T,D>>& field){ + static kel::lbm::error_or<void> apply(std::ostream& vtk_file, const kel::lbm::data<sch::Primitive<T,D>>& field){ if constexpr (std::is_same_v<T,sch::UnsignedInteger> and D == 1u) { vtk_file<<field.template cast_to<sch::UInt16>().get()<<"\n"; }else{ vtk_file<<field.get()<<"\n"; } - return saw::make_void(); + return kel::lbm::make_void(); } }; template<typename T, uint64_t D> struct lbm_vtk_writer<sch::FixedArray<T,D>> { - static saw::error_or<void> apply_header(std::ostream& vtk_file, std::string_view name){ + static kel::lbm::error_or<void> apply_header(std::ostream& vtk_file, std::string_view name){ vtk_file<<"VECTORS "<<name<<" float\n"; - return saw::make_void(); + return kel::lbm::make_void(); } - static saw::error_or<void> apply(std::ostream& vtk_file, const saw::data<sch::FixedArray<T,D>>& field){ - saw::data<sch::FixedArray<sch::UInt64,D>> index; - for(saw::data<sch::UInt64> it{0}; it.get() < D; ++it){ + static kel::lbm::error_or<void> apply(std::ostream& vtk_file, const kel::lbm::data<sch::FixedArray<T,D>>& field){ + kel::lbm::data<sch::FixedArray<sch::UInt64,D>> index; + for(kel::lbm::data<sch::UInt64> it{0}; it.get() < D; ++it){ index.at({0u}).set(0u); } @@ -61,7 +61,7 @@ struct lbm_vtk_writer<sch::FixedArray<T,D>> { vtk_file<<" 0"; } vtk_file<<"\n"; - return saw::make_void(); + return kel::lbm::make_void(); } }; @@ -69,7 +69,7 @@ template<typename T, uint64_t Ghost, uint64_t... D> struct lbm_vtk_writer<sch::Chunk<T,Ghost,D...>> { template<uint64_t d> - static saw::error_or<void> apply_d(std::ostream& vtk_file, const saw::data<sch::Chunk<T,Ghost,D...>>& field, saw::data<sch::FixedArray<sch::UInt64,sizeof...(D)>>& index){ + static kel::lbm::error_or<void> apply_d(std::ostream& vtk_file, const kel::lbm::data<sch::Chunk<T,Ghost,D...>>& field, kel::lbm::data<sch::FixedArray<sch::UInt64,sizeof...(D)>>& index){ // VTK wants to iterate over z,y,x instead of x,y,z // We could reorder the dimensions, but eh if constexpr ( d > 0u){ @@ -80,18 +80,18 @@ struct lbm_vtk_writer<sch::Chunk<T,Ghost,D...>> { auto eov = lbm_vtk_writer<T>::apply(vtk_file, field.at(index)); if(eov.is_error()) return eov; } - return saw::make_void(); + return kel::lbm::make_void(); } - static saw::error_or<void> apply(std::ostream& vtk_file, const saw::data<sch::Chunk<T,Ghost,D...>>& field, std::string_view name){ + static kel::lbm::error_or<void> apply(std::ostream& vtk_file, const kel::lbm::data<sch::Chunk<T,Ghost,D...>>& field, std::string_view name){ { auto eov = lbm_vtk_writer<T>::apply_header(vtk_file,name); if(eov.is_error()){ return eov; } } - saw::data<sch::FixedArray<sch::UInt64,sizeof...(D)>> index; - for(saw::data<sch::UInt64> it{0}; it.get() < sizeof...(D); ++it){ + kel::lbm::data<sch::FixedArray<sch::UInt64,sizeof...(D)>> index; + for(kel::lbm::data<sch::UInt64> it{0}; it.get() < sizeof...(D); ++it){ index.at({0u}).set(0u); } @@ -104,17 +104,17 @@ struct lbm_vtk_writer<sch::Chunk<T,Ghost,D...>> { vtk_file<<"\n"; - return saw::make_void(); + return kel::lbm::make_void(); } }; template<typename T, uint64_t D> struct lbm_vtk_writer<sch::Vector<T,D>> { - static saw::error_or<void> apply_header(std::ostream& vtk_file, std::string_view name){ + static kel::lbm::error_or<void> apply_header(std::ostream& vtk_file, std::string_view name){ vtk_file<<"VECTORS "<<name<<" float\n"; - return saw::make_void(); + return kel::lbm::make_void(); } - static saw::error_or<void> apply(std::ostream& vtk_file, const saw::data<sch::Vector<T,D>>& field){ + static kel::lbm::error_or<void> apply(std::ostream& vtk_file, const kel::lbm::data<sch::Vector<T,D>>& field){ static_assert(D > 0, "Non-dimensionality is bad for momentum."); static_assert(D <= 3, "4th dimension as well. Mostly due to vtk."); @@ -129,33 +129,33 @@ struct lbm_vtk_writer<sch::Vector<T,D>> { vtk_file<<" 0"; } vtk_file<<"\n"; - return saw::make_void(); + return kel::lbm::make_void(); } }; template<typename T> struct lbm_vtk_writer<sch::Scalar<T>> { - static saw::error_or<void> apply_header(std::ostream& vtk_file, std::string_view name){ + static kel::lbm::error_or<void> apply_header(std::ostream& vtk_file, std::string_view name){ vtk_file<<"SCALARS "<<name<<" float 1\n"; vtk_file<<"LOOKUP_TABLE default\n"; - return saw::make_void(); + return kel::lbm::make_void(); } - static saw::error_or<void> apply(std::ostream& vtk_file, const saw::data<sch::Scalar<T>>& field){ + static kel::lbm::error_or<void> apply(std::ostream& vtk_file, const kel::lbm::data<sch::Scalar<T>>& field){ // vtk_file<<"VECTORS "<<name<<" float\n"; vtk_file<<field.at({}).get(); vtk_file<<"\n"; - return saw::make_void(); + return kel::lbm::make_void(); } }; -template<typename... MemberT, saw::string_literal... Keys, uint64_t... Ghost, uint64_t... Dims> +template<typename... MemberT, kel::lbm::string_literal... Keys, uint64_t... Ghost, uint64_t... Dims> struct lbm_vtk_writer<sch::Struct<sch::Member<sch::Chunk<MemberT,Ghost,Dims...>,Keys>...>> final { template<uint64_t i> - static saw::error_or<void> iterate_i(std::ostream& vtk_file, - const saw::data<sch::Struct<sch::Member<sch::Chunk<MemberT,Ghost,Dims...>,Keys>...>>& field){ + static kel::lbm::error_or<void> iterate_i(std::ostream& vtk_file, + const kel::lbm::data<sch::Struct<sch::Member<sch::Chunk<MemberT,Ghost,Dims...>,Keys>...>>& field){ if constexpr ( i < sizeof...(MemberT) ) { - using MT = typename saw::parameter_pack_type<i,sch::Member<sch::Chunk<MemberT,Ghost,Dims...>,Keys>...>::type; + using MT = typename kel::lbm::parameter_pack_type<i,sch::Member<sch::Chunk<MemberT,Ghost,Dims...>,Keys>...>::type; { auto eov = lbm_vtk_writer<typename MT::ValueType>::apply(vtk_file,field.template get<MT::KeyLiteral>(), MT::KeyLiteral.view()); if(eov.is_error()){ @@ -166,12 +166,12 @@ struct lbm_vtk_writer<sch::Struct<sch::Member<sch::Chunk<MemberT,Ghost,Dims...>, return iterate_i<i+1u>(vtk_file, field); } - return saw::make_void(); + return kel::lbm::make_void(); } - static saw::error_or<void> apply(std::ostream& vtk_file, - const saw::data<sch::Struct<sch::Member<sch::Chunk<MemberT,Ghost,Dims...>,Keys>...>>& field){ + static kel::lbm::error_or<void> apply(std::ostream& vtk_file, + const kel::lbm::data<sch::Struct<sch::Member<sch::Chunk<MemberT,Ghost,Dims...>,Keys>...>>& field){ vtk_file <<"# vtk DataFile Version 3.0\n" @@ -182,22 +182,22 @@ struct lbm_vtk_writer<sch::Struct<sch::Member<sch::Chunk<MemberT,Ghost,Dims...>, <<"ORIGIN 0.0 0.0 0.0\n" ; - auto& field_0 = field.template get<saw::parameter_key_pack_type<0u,Keys...>::literal>(); + auto& field_0 = field.template get<kel::lbm::parameter_key_pack_type<0u,Keys...>::literal>(); auto meta = field_0.get_dims(); - saw::data<sch::UInt64> pd_size{1u}; + kel::lbm::data<sch::UInt64> pd_size{1u}; // DIMENSIONS { vtk_file << "DIMENSIONS"; - pd_size.set(saw::ct_multiply<uint64_t,Dims...>::value); + pd_size.set(kel::lbm::ct_multiply<uint64_t,Dims...>::value); - static_assert(saw::ct_multiply<uint64_t,Dims...>::value > 0u, "Invalid Dim size resulting in length 0u"); + static_assert(kel::lbm::ct_multiply<uint64_t,Dims...>::value > 0u, "Invalid Dim size resulting in length 0u"); - for(saw::data<sch::UInt64> i{0u}; i.get() < sizeof...(Dims); ++i){ + for(kel::lbm::data<sch::UInt64> i{0u}; i.get() < sizeof...(Dims); ++i){ vtk_file << " " << meta.at(i).get(); } - for(saw::data<sch::UInt64> i{sizeof...(Dims)}; i.get() < 3u; ++i){ + for(kel::lbm::data<sch::UInt64> i{sizeof...(Dims)}; i.get() < 3u; ++i){ vtk_file << " 1"; } @@ -222,14 +222,14 @@ struct lbm_vtk_writer<sch::Struct<sch::Member<sch::Chunk<MemberT,Ghost,Dims...>, } template<typename Sch> -saw::error_or<void> write_vtk_file(const std::filesystem::path& out_dir, const std::string_view& file_name, uint64_t d_t, const saw::data<Sch>& field){ +kel::lbm::error_or<void> write_vtk_file(const std::filesystem::path& out_dir, const std::string_view& file_name, uint64_t d_t, const kel::lbm::data<Sch>& field){ auto vtk_dir = out_dir / "vtk"; { std::error_code ec; std::filesystem::create_directories(vtk_dir,ec); if(ec != std::errc{}){ - return saw::make_error<saw::err::critical>("Could not create directory for write_vtk_file function"); + return kel::lbm::make_error<kel::lbm::err::critical>("Could not create directory for write_vtk_file function"); } } std::string ft_name{file_name}; @@ -245,7 +245,7 @@ saw::error_or<void> write_vtk_file(const std::filesystem::path& out_dir, const s std::ofstream vtk_file{vtk_dir / sstr.str() }; if( not vtk_file.is_open() ){ - return saw::make_error<saw::err::critical>("Could not open file."); + return kel::lbm::make_error<kel::lbm::err::critical>("Could not open file."); } auto eov = impl::lbm_vtk_writer<Sch>::apply(vtk_file, field); diff --git a/modules/core/tests/abstract_data.cpp b/modules/core/tests/abstract_data.cpp new file mode 100644 index 0000000..1ee3d62 --- /dev/null +++ b/modules/core/tests/abstract_data.cpp @@ -0,0 +1,390 @@ +#include <forstio/test/suite.hpp> + +#include "../c++/abstract/data.hpp" +#include "../c++/abstract/data_math.hpp" +#include "../c++/abstract/iterator.hpp" +#include "../c++/abstract/math.hpp" + +namespace { +namespace ts { +using namespace kel::lbm::sch; +} + +using kel::lbm::data; +using kel::lbm::enc::Native; + +SAW_TEST("Abstract/Data/Primitive"){ + data<ts::UInt64> a{4u}; + data<ts::UInt64> b{6u}; + + SAW_EXPECT(a.get() == 4u, "value round trips"); + SAW_EXPECT((a + b).get() == 10u, "addition"); + SAW_EXPECT((b - a).get() == 2u, "subtraction"); + SAW_EXPECT((a * b).get() == 24u, "multiplication"); + SAW_EXPECT((b / a).get() == 1u, "integer division"); + + a += b; + SAW_EXPECT(a.get() == 10u, "compound addition mutates"); + a -= b; + SAW_EXPECT(a.get() == 4u, "compound subtraction mutates"); + + SAW_EXPECT(a < b, "ordering"); + SAW_EXPECT(b > a, "reverse ordering"); + SAW_EXPECT(a != b, "inequality"); + SAW_EXPECT(a.equals(data<ts::UInt64>{4u}), "equality"); + + ++a; + SAW_EXPECT(a.get() == 5u, "increment"); +} + +SAW_TEST("Abstract/Data/PrimitiveCast"){ + data<ts::Float64> d{2.75}; + auto as_int = d.cast_to<ts::Int32>(); + SAW_EXPECT(as_int.get() == 2, "float to int truncates"); + + data<ts::UInt8> small{255u}; + auto wide = small.cast_to<ts::UInt64>(); + SAW_EXPECT(wide.get() == 255u, "widening preserves the value"); +} + +SAW_TEST("Abstract/Data/Bool"){ + data<ts::Bool> t{true}; + data<ts::Bool> f{false}; + + SAW_EXPECT(t.get(), "true round trips"); + SAW_EXPECT((!t).get() == false, "negation"); + SAW_EXPECT((t && f).get() == false, "conjunction"); + SAW_EXPECT((t || f).get() == true, "disjunction"); + SAW_EXPECT(t != f, "inequality"); +} + +SAW_TEST("Abstract/Data/MixedPrecision"){ + // Stored as float, read as double. + using TMixed = ts::MixedPrecision<ts::Float32, ts::Float64>; + + data<TMixed> v{1.5}; + SAW_EXPECT(v.get() == 1.5, "a value exactly representable in float survives"); + + data<TMixed> w{2.5}; + SAW_EXPECT((v + w).get() == 4.0, "arithmetic happens at interface precision"); + + static_assert(std::is_same_v<decltype(v.get()), double>, + "reads come back as the interface type"); +} + +SAW_TEST("Abstract/Data/FixedArrayRankOne"){ + data<ts::FixedArray<ts::UInt64,3u>> arr{1u,2u,3u}; + + SAW_EXPECT(arr.at({0u}).get() == 1u, "single index access"); + SAW_EXPECT(arr.at({2u}).get() == 3u, "last element"); + SAW_EXPECT(arr.at({{1u}}).get() == 2u, "index array access"); + SAW_EXPECT(arr.flat_at(1u).get() == 2u, "flat access"); + + arr.at({1u}).set(9u); + SAW_EXPECT(arr.at({1u}).get() == 9u, "writes through"); + + SAW_EXPECT(arr.size().get() == 3u, "size"); + SAW_EXPECT(decltype(arr)::get_dim_size<0u>() == 3u, "compile time extent"); +} + +SAW_TEST("Abstract/Data/FixedArrayRankTwo"){ + data<ts::FixedArray<ts::UInt64,2u,3u>> arr; + + SAW_EXPECT(arr.size().get() == 6u, "flat size is the product of extents"); + + // Row major: index {i,j} sits at i + j*2. + arr.at({{1u,2u}}).set(7u); + SAW_EXPECT(arr.at({{1u,2u}}).get() == 7u, "two dimensional access"); + SAW_EXPECT(arr.flat_at(1u + 2u*2u).get() == 7u, "and its flat position"); + + SAW_EXPECT(decltype(arr)::get_dim_size<0u>() == 2u, "first extent"); + SAW_EXPECT(decltype(arr)::get_dim_size<1u>() == 3u, "second extent"); +} + +SAW_TEST("Abstract/Data/FixedArrayRankZero"){ + // The empty product is one, so a rank zero shape still holds one element. + data<ts::FixedArray<ts::Float64>> scalar_like; + SAW_EXPECT(scalar_like.size().get() == 1u, "rank zero holds exactly one element"); + + scalar_like.at({}).set(3.5); + SAW_EXPECT(scalar_like.at({}).get() == 3.5, "addressed with an empty index"); +} + +SAW_TEST("Abstract/Data/Array"){ + // Extents are runtime, so they come in as the metadata. + data<ts::Array<ts::UInt64,1u>> arr{data<ts::FixedArray<ts::UInt64,1u>>{{3u}}}; + + SAW_EXPECT(arr.size().get() == 3u, "sized from its metadata"); + SAW_EXPECT(arr.get_dim_size(0u) == 3u, "extent is readable"); + + arr.at({1u}).set(5u); + SAW_EXPECT(arr.at({1u}).get() == 5u, "single index access"); + SAW_EXPECT(arr.at({{1u}}).get() == 5u, "index array access"); + + auto eov = arr.add(data<ts::UInt64>{8u}); + SAW_EXPECT(eov.is_value(), "appending to the last dimension works"); + SAW_EXPECT(arr.size().get() == 4u, "and grows it"); + SAW_EXPECT(arr.at({3u}).get() == 8u, "appended value lands last"); +} + +SAW_TEST("Abstract/Data/ArrayFromIntegralExtents"){ + data<ts::Array<ts::UInt64,2u>> arr{2u, 3u}; + + SAW_EXPECT(arr.size().get() == 6u, "extents multiply out"); + arr.at({{1u,2u}}).set(4u); + SAW_EXPECT(arr.at({{1u,2u}}).get() == 4u, "two dimensional access"); +} + +SAW_TEST("Abstract/Data/String"){ + data<ts::String> s{std::string{"hello"}}; + + SAW_EXPECT(s.size().get() == 5u, "length"); + SAW_EXPECT(s.get_at({1u}) == 'e', "indexed read"); + + s.set_at({0u}, 'H'); + SAW_EXPECT(s.stl_view() == std::string_view{"Hello"}, "indexed write"); + + // A String is described by its length, so building one from metadata + // gives a string of that length. + data<ts::String> sized{data<ts::UInt64>{3u}}; + SAW_EXPECT(sized.size().get() == 3u, "sized from its metadata"); +} + +SAW_TEST("Abstract/Data/Tuple"){ + data<ts::Tuple<ts::UInt64, ts::Bool>> t; + + t.get<0u>().set(7u); + t.get<1u>().set(true); + + SAW_EXPECT(t.get<0u>().get() == 7u, "first member"); + SAW_EXPECT(t.get<1u>().get() == true, "second member"); + SAW_EXPECT(decltype(t)::size() == 2u, "member count"); +} + +SAW_TEST("Abstract/Data/Struct"){ + using TStruct = ts::Struct< + ts::Member<ts::UInt64,"count">, + ts::Member<ts::Float64,"weight"> + >; + + data<TStruct> s; + s.get<"count">().set(12u); + s.get<"weight">().set(0.25); + + SAW_EXPECT(s.get<"count">().get() == 12u, "member by name"); + SAW_EXPECT(s.get<"weight">().get() == 0.25, "second member by name"); + SAW_EXPECT(s.get_at_index<0u>().get() == 12u, "and by position"); + SAW_EXPECT(decltype(s)::size().get() == 2u, "member count"); +} + +SAW_TEST("Abstract/Data/Union"){ + using TUnion = ts::Union< + ts::Member<ts::UInt64,"number">, + ts::Member<ts::Bool,"flag"> + >; + + data<TUnion> u; + u.init<"number">().set(3u); + + SAW_EXPECT(u.holds_alternative<"number">(), "holds the initialised member"); + SAW_EXPECT(!u.holds_alternative<"flag">(), "and not the other one"); + SAW_EXPECT(u.get<"number">().get() == 3u, "value reads back"); + + u.init<"flag">().set(true); + SAW_EXPECT(u.holds_alternative<"flag">(), "switching alternative"); + SAW_EXPECT(u.get<"flag">().get() == true, "new value reads back"); +} + +SAW_TEST("Abstract/Data/Tensor"){ + data<ts::Vector<ts::Float64,3u>> a{1.0, 2.0, 3.0}; + data<ts::Vector<ts::Float64,3u>> b{4.0, 5.0, 6.0}; + + SAW_EXPECT(a.at({{0u}}).get() == 1.0, "component access"); + SAW_EXPECT(a.flat_at(2u).get() == 3.0, "flat access"); + + auto sum = a + b; + SAW_EXPECT(sum.flat_at(0u).get() == 5.0, "componentwise addition"); + SAW_EXPECT(sum.flat_at(2u).get() == 9.0, "componentwise addition, last"); + + auto diff = b - a; + SAW_EXPECT(diff.flat_at(1u).get() == 3.0, "componentwise subtraction"); + + auto neg = -a; + SAW_EXPECT(neg.flat_at(0u).get() == -1.0, "negation"); +} + +SAW_TEST("Abstract/Data/TensorScalarOps"){ + data<ts::Vector<ts::Float64,2u>> v{3.0, 4.0}; + auto two = kel::lbm::math::make_scalar<ts::Float64>(2.0); + + auto scaled = v * two; + SAW_EXPECT(scaled.flat_at(0u).get() == 6.0, "scalar multiply"); + + auto halved = v / two; + SAW_EXPECT(halved.flat_at(1u).get() == 2.0, "scalar divide"); +} + +SAW_TEST("Abstract/Data/ScalarTensor"){ + // Rank zero: one element, addressed with an empty index. + data<ts::Scalar<ts::Float64>> s{data<ts::Float64>{2.5}}; + + SAW_EXPECT(s.at({}).get() == 2.5, "empty index access"); + SAW_EXPECT(s.flat_at(0u).get() == 2.5, "flat access"); + SAW_EXPECT(decltype(s)::size().get() == 1u, "holds one element"); +} + +SAW_TEST("Abstract/Math/DotAndNorm"){ + using namespace kel::lbm; + + auto a = math::make_vector<ts::Float64>(3.0, 4.0); + auto b = math::make_vector<ts::Float64>(1.0, 0.0); + + auto d = math::dot<ts::Float64,2u>(a, b); + SAW_EXPECT(d.flat_at(0u).get() == 3.0, "dot product"); + + auto n = math::norm<ts::Float64,2u>(a); + SAW_EXPECT(n.flat_at(0u).get() == 5.0, "3-4-5 triangle"); +} + +SAW_TEST("Abstract/Math/Normalize"){ + using namespace kel::lbm; + + auto a = math::make_vector<ts::Float64>(0.0, 2.0); + auto u = math::normalize<ts::Float64,2u>(a); + + SAW_EXPECT(u.flat_at(0u).get() == 0.0, "x component"); + SAW_EXPECT(u.flat_at(1u).get() == 1.0, "y component is unit length"); + + // A zero vector has no direction to preserve, so it comes back unchanged + // rather than dividing by zero. + auto zero = math::make_vector<ts::Float64>(0.0, 0.0); + auto uz = math::normalize<ts::Float64,2u>(zero); + SAW_EXPECT(uz.flat_at(0u).get() == 0.0, "zero vector survives untouched"); +} + +SAW_TEST("Abstract/Math/Cross"){ + using namespace kel::lbm; + + auto x = math::make_vector<ts::Float64>(1.0, 0.0, 0.0); + auto y = math::make_vector<ts::Float64>(0.0, 1.0, 0.0); + + auto z = math::cross<ts::Float64>(x, y); + SAW_EXPECT(z.flat_at(2u).get() == 1.0, "x cross y is z"); + + // In two dimensions only the normal component survives. + auto a = math::make_vector<ts::Float64>(1.0, 0.0); + auto b = math::make_vector<ts::Float64>(0.0, 1.0); + auto s = math::cross<ts::Float64>(a, b); + SAW_EXPECT(s.flat_at(0u).get() == 1.0, "2d cross is a scalar"); +} + +SAW_TEST("Abstract/Math/Vectorize"){ + using namespace kel::lbm; + + data<ts::FixedArray<ts::Float64,3u>> arr{1.0, 2.0, 3.0}; + auto v = math::vectorize_data<ts::Float64,3u>(arr); + + SAW_EXPECT(v.flat_at(0u).get() == 1.0, "first component carried over"); + SAW_EXPECT(v.flat_at(2u).get() == 3.0, "last component carried over"); +} + +SAW_TEST("Abstract/Math/MatrixVectorMultiply"){ + using namespace kel::lbm; + + // Column major by the row-major-index convention used in get_flat_index: + // at({{i,j}}) is element i of column j. + data<ts::Matrix<ts::Float64,2u,2u>> m; + m.at({{0u,0u}}).set(1.0); + m.at({{0u,1u}}).set(2.0); + m.at({{1u,0u}}).set(3.0); + m.at({{1u,1u}}).set(4.0); + + auto v = math::make_vector<ts::Float64>(1.0, 1.0); + auto r = math::multiply<ts::Float64,2u,2u>(m, v); + + SAW_EXPECT(r.flat_at(0u).get() == 3.0, "first row sums to 3"); + SAW_EXPECT(r.flat_at(1u).get() == 7.0, "second row sums to 7"); +} + +SAW_TEST("Abstract/Math/SumAndFill"){ + using namespace kel::lbm; + + data<ts::Vector<ts::Float64,3u>> v; + math::fill<ts::Float64,3u>(v, data<ts::Float64>{2.0}); + + SAW_EXPECT(v.flat_at(1u).get() == 2.0, "fill writes every element"); + + auto s = math::sum<ts::Float64,3u>(v); + SAW_EXPECT(s.flat_at(0u).get() == 6.0, "sum over the tensor"); +} + +SAW_TEST("Abstract/Iterator/RankOne"){ + using namespace kel::lbm; + + uint64_t visits = 0u; + auto eov = rank_iterator<3u>::in_fixed_bounds( + [&](const index_data<1u>& index) -> error_or<void> { + SAW_EXPECT(index.flat_at(0u).get() == visits, "visited in order"); + ++visits; + return make_void(); + }); + + SAW_EXPECT(eov.is_value(), "iteration succeeded"); + SAW_EXPECT(visits == 3u, "visited every position"); +} + +SAW_TEST("Abstract/Iterator/RankTwo"){ + using namespace kel::lbm; + + // This is the case that could not compile against forstio's iterator, + // because it indexed a rank two index array with a bare integer. + uint64_t visits = 0u; + uint64_t last_i = 0u; + uint64_t last_j = 0u; + + auto eov = rank_iterator<2u,3u>::in_fixed_bounds( + [&](const index_data<2u>& index) -> error_or<void> { + last_i = index.flat_at(0u).get(); + last_j = index.flat_at(1u).get(); + ++visits; + return make_void(); + }); + + SAW_EXPECT(eov.is_value(), "iteration succeeded"); + SAW_EXPECT(visits == 6u, "visited every position of a 2x3 shape"); + SAW_EXPECT(last_i == 1u, "finished on the last i"); + SAW_EXPECT(last_j == 2u, "finished on the last j"); +} + +SAW_TEST("Abstract/Iterator/RankZero"){ + using namespace kel::lbm; + + uint64_t visits = 0u; + auto eov = rank_iterator<>::in_fixed_bounds( + [&](const index_data<0u>&) -> error_or<void> { + ++visits; + return make_void(); + }); + + SAW_EXPECT(eov.is_value(), "iteration succeeded"); + SAW_EXPECT(visits == 1u, "rank zero still has one position"); +} + +SAW_TEST("Abstract/Iterator/PropagatesError"){ + using namespace kel::lbm; + + uint64_t visits = 0u; + auto eov = rank_iterator<5u>::in_fixed_bounds( + [&](const index_data<1u>&) -> error_or<void> { + ++visits; + if(visits == 2u){ + return make_error<err::not_found>(); + } + return make_void(); + }); + + SAW_EXPECT(eov.is_error(), "the error reaches the caller"); + SAW_EXPECT(eov.get_error().is_type<err::not_found>(), "and keeps its type"); + SAW_EXPECT(visits == 2u, "iteration stopped at the failure"); +} +} diff --git a/modules/core/tests/abstract_foundation.cpp b/modules/core/tests/abstract_foundation.cpp new file mode 100644 index 0000000..aea967d --- /dev/null +++ b/modules/core/tests/abstract_foundation.cpp @@ -0,0 +1,189 @@ +#include <forstio/test/suite.hpp> + +#include "../c++/abstract/common.hpp" +#include "../c++/abstract/error.hpp" +#include "../c++/abstract/schema.hpp" +#include "../c++/abstract/stringify_schema.hpp" +#include "../c++/abstract/templates.hpp" + +namespace { +namespace ts { +using namespace kel::lbm::sch; +} + +SAW_TEST("Abstract/Templates/CtMultiply"){ + using namespace kel::lbm; + + static_assert(ct_multiply<uint64_t>::value == 1u, "empty pack is the identity"); + static_assert(ct_multiply<uint64_t,3u>::value == 3u, ""); + static_assert(ct_multiply<uint64_t,2u,3u,4u>::value == 24u, ""); +} + +SAW_TEST("Abstract/Templates/ParameterPack"){ + using namespace kel::lbm; + + static_assert(std::is_same_v<parameter_pack_type<0u, int, char, bool>::type, int>, ""); + static_assert(std::is_same_v<parameter_pack_type<2u, int, char, bool>::type, bool>, ""); + + static_assert(parameter_pack_index<char, int, char, bool>::value == 1u, ""); + + static_assert(parameter_pack_value<1u, uint64_t, 7u, 9u, 11u>::value == 9u, ""); +} + +SAW_TEST("Abstract/Templates/KeyPack"){ + using namespace kel::lbm; + + static_assert(parameter_key_pack_index<"b", "a", "b", "c">::value == 1u, ""); + static_assert(parameter_key_pack_type<2u, "a", "b", "c">::literal == string_literal{"c"}, ""); +} + +SAW_TEST("Abstract/Templates/DigitConversion"){ + using namespace kel::lbm; + + static_assert(ct_convert_to_digits<0u,10u>::literal == string_literal{"0"}, ""); + static_assert(ct_convert_to_digits<7u,10u>::literal == string_literal{"7"}, ""); + static_assert(ct_convert_to_digits<1024u,10u>::literal == string_literal{"1024"}, ""); +} + +SAW_TEST("Abstract/StringLiteral/Concat"){ + using namespace kel::lbm; + + static_assert((string_literal{"foo"} + string_literal{"bar"}) == string_literal{"foobar"}, ""); + static_assert(string_literal{"foo"}.view() == std::string_view{"foo"}, ""); +} + +SAW_TEST("Abstract/Schema/Meta"){ + using namespace kel::lbm; + + // Compile time shapes carry nothing at runtime. + static_assert(std::is_same_v<ts::UInt64::Meta, ts::Void>, ""); + static_assert(std::is_same_v<ts::FixedArray<ts::UInt64,3u>::Meta, ts::Void>, ""); + + // A dynamically sized Array is described by its extents. + static_assert(std::is_same_v< + ts::Array<ts::Float64,2u>::Meta, + ts::FixedArray<ts::UInt64,2u>>, ""); + + // A String is described by its length. + static_assert(std::is_same_v<ts::String::Meta, ts::UInt64>, ""); + + // A Tensor is addressed through a rank sized index. + static_assert(std::is_same_v< + ts::Vector<ts::Float64,3u>::Meta, + ts::FixedArray<ts::UInt64,1u>>, ""); + static_assert(std::is_same_v< + ts::Scalar<ts::Float64>::Meta, + ts::FixedArray<ts::UInt64,0u>>, ""); + + // Structural schemas recurse into their members. + using TStruct = ts::Struct< + ts::Member<ts::UInt64,"count">, + ts::Member<ts::Array<ts::Float64,1u>,"values"> + >; + static_assert(std::is_same_v< + TStruct::Meta, + ts::Struct< + ts::Member<ts::Void,"count">, + ts::Member<ts::FixedArray<ts::UInt64,1u>,"values"> + >>, ""); + + static_assert(std::is_same_v< + ts::Tuple<ts::UInt64, ts::String>::Meta, + ts::Tuple<ts::Void, ts::UInt64>>, ""); +} + +SAW_TEST("Abstract/Schema/PrimitiveShape"){ + using namespace kel::lbm; + + static_assert(ts::UInt64::Bytes == 8u, ""); + static_assert(std::is_same_v<ts::UInt64::Kind, ts::UnsignedInteger>, ""); + static_assert(std::is_same_v<ts::UInt64::StorageType, ts::UInt64>, ""); + static_assert(std::is_same_v<ts::UInt64::InterfaceType, ts::UInt64>, ""); + + using TMixed = ts::MixedPrecision<ts::Float32, ts::Float64>; + static_assert(std::is_same_v<TMixed::StorageType, ts::Float32>, ""); + static_assert(std::is_same_v<TMixed::InterfaceType, ts::Float64>, ""); + + static_assert(ts::FixedArray<ts::UInt64,2u,3u>::FlatSize == 6u, ""); + static_assert(ts::FixedArray<ts::UInt64,2u,3u>::Rank == 2u, ""); + static_assert(ts::Scalar<ts::Float64>::FlatSize == 1u, "rank zero holds one element"); +} + +SAW_TEST("Abstract/SchemaStringify/Primitive"){ + using namespace kel::lbm; + + static_assert(schema_to_string<ts::UInt64>::literal + == string_literal{"Primitive<UnsignedInteger,8>"}, ""); + static_assert(schema_to_string<ts::Float32>::literal + == string_literal{"Primitive<FloatingPoint,4>"}, ""); +} + +SAW_TEST("Abstract/SchemaStringify/Composite"){ + using namespace kel::lbm; + + static_assert(schema_to_string<ts::FixedArray<ts::UInt8,2u,3u>>::literal + == string_literal{"FixedArray<Primitive<UnsignedInteger,1>,2,3>"}, ""); + + static_assert(schema_to_string<ts::Tuple<ts::Bool, ts::String>>::literal + == string_literal{"Tuple<Bool,String>"}, ""); +} + +SAW_TEST("Abstract/Error/MakeError"){ + using namespace kel::lbm; + + auto err = make_error<err::not_found>("missing thing"); + SAW_EXPECT(err.failed(), "a not_found is an error"); + SAW_EXPECT(err.is_recoverable(), "not_found is recoverable"); + SAW_EXPECT(err.is_type<err::not_found>(), "error keeps its type"); + SAW_EXPECT(!err.is_type<err::out_of_memory>(), "and is distinguishable"); + SAW_EXPECT(err.get_message() == std::string_view{"missing thing"}, "message survives"); +} + +SAW_TEST("Abstract/Error/Critical"){ + using namespace kel::lbm; + + auto err = make_error<err::out_of_memory>(); + SAW_EXPECT(err.is_critical(), "out_of_memory is critical"); + SAW_EXPECT(!err.is_recoverable(), "and therefore not recoverable"); +} + +SAW_TEST("Abstract/Error/ErrorOr"){ + using namespace kel::lbm; + + error_or<uint64_t> good{uint64_t{42u}}; + SAW_EXPECT(good.is_value(), "holds a value"); + SAW_EXPECT(!good.is_error(), "and not an error"); + SAW_EXPECT(good.get_value() == 42u, "value round trips"); + + error_or<uint64_t> bad{make_error<err::not_found>()}; + SAW_EXPECT(bad.is_error(), "holds an error"); + SAW_EXPECT(!bad.is_value(), "and not a value"); + SAW_EXPECT(bad.get_error().is_type<err::not_found>(), "error type survives"); +} + +SAW_TEST("Abstract/Error/VoidPath"){ + using namespace kel::lbm; + + error_or<void> ok{make_void()}; + SAW_EXPECT(ok.is_value(), "make_void is a value, not an error"); +} + +SAW_TEST("Abstract/Common/Pointers"){ + using namespace kel::lbm; + + auto owned = heap<uint64_t>(7u); + SAW_EXPECT(*owned == 7u, "heap constructs in place"); + + ptr<uint64_t> empty; + SAW_EXPECT(!empty.is_valid(), "a default ptr is empty"); + + uint64_t backing = 3u; + ptr<uint64_t> filled{backing}; + SAW_EXPECT(filled.is_valid(), "a bound ptr is valid"); + SAW_EXPECT(filled() == 3u, "and reads through"); + + ref<uint64_t> r{backing}; + r() = 9u; + SAW_EXPECT(backing == 9u, "ref writes through to its referent"); +} +} diff --git a/modules/core/tests/abstract_json.cpp b/modules/core/tests/abstract_json.cpp new file mode 100644 index 0000000..9592158 --- /dev/null +++ b/modules/core/tests/abstract_json.cpp @@ -0,0 +1,326 @@ +#include <forstio/test/suite.hpp> + +#include "../c++/abstract/json.hpp" + +namespace { +namespace ts { +using namespace kel::lbm::sch; +} + +using kel::lbm::codec; +using kel::lbm::data; +using kel::lbm::enc::Json; +using kel::lbm::enc::Native; + +template<typename Schema> +std::string encode_to_string(const data<Schema>& value, bool pretty = false){ + data<Schema, Json> out; + codec<Schema, Json> c; + c.set_pretty(pretty); + auto eov = c.encode(value, out); + SAW_EXPECT(eov.is_value(), "encoding succeeded"); + return out.stl_string(); +} + +SAW_TEST("Abstract/Json/EncodePrimitives"){ + SAW_EXPECT(encode_to_string(data<ts::UInt64>{42u}) == "42", "unsigned"); + SAW_EXPECT(encode_to_string(data<ts::Int32>{-7}) == "-7", "signed"); + SAW_EXPECT(encode_to_string(data<ts::Bool>{true}) == "true", "bool true"); + SAW_EXPECT(encode_to_string(data<ts::Bool>{false}) == "false", "bool false"); +} + +SAW_TEST("Abstract/Json/EncodeString"){ + data<ts::String> s{std::string{"a\"b\\c\nd"}}; + // Quote, backslash and newline all have to come back escaped. + SAW_EXPECT(encode_to_string(s) == "\"a\\\"b\\\\c\\nd\"", "escapes applied"); +} + +SAW_TEST("Abstract/Json/DecodePrimitives"){ + data<ts::UInt64> u; + codec<ts::UInt64, Json> cu; + SAW_EXPECT(cu.decode(data<ts::UInt64,Json>{std::string{"123"}}, u).is_value(), "decoded"); + SAW_EXPECT(u.get() == 123u, "unsigned round trips"); + + data<ts::Float64> f; + codec<ts::Float64, Json> cf; + SAW_EXPECT(cf.decode(data<ts::Float64,Json>{std::string{"-0.5e1"}}, f).is_value(), "decoded"); + SAW_EXPECT(f.get() == -5.0, "exponent form is understood"); +} + +SAW_TEST("Abstract/Json/FloatRoundTrip"){ + // max_digits10 precision is what makes this exact rather than approximate. + const double original = 0.1234567890123456789; + data<ts::Float64> in{original}; + + data<ts::Float64> out; + codec<ts::Float64, Json> c; + auto eov = c.decode(data<ts::Float64,Json>{encode_to_string(in)}, out); + SAW_EXPECT(eov.is_value(), "round trip decoded"); + SAW_EXPECT(out.get() == in.get(), "a double survives a save and load cycle"); +} + +SAW_TEST("Abstract/Json/IntegerRejectsFraction"){ + // Truncating 1.5 into an integer field would lose data quietly. + data<ts::UInt64> u; + codec<ts::UInt64, Json> c; + auto eov = c.decode(data<ts::UInt64,Json>{std::string{"1.5"}}, u); + SAW_EXPECT(eov.is_error(), "a fractional value is not an integer"); +} + +SAW_TEST("Abstract/Json/UnsignedRejectsNegative"){ + data<ts::UInt64> u; + codec<ts::UInt64, Json> c; + auto eov = c.decode(data<ts::UInt64,Json>{std::string{"-1"}}, u); + SAW_EXPECT(eov.is_error(), "a negative value is not unsigned"); +} + +SAW_TEST("Abstract/Json/EncodeAndDecodeStruct"){ + using TStruct = ts::Struct< + ts::Member<ts::UInt64,"count">, + ts::Member<ts::Float64,"weight"> + >; + + data<TStruct> in; + in.get<"count">().set(3u); + in.get<"weight">().set(0.5); + + auto text = encode_to_string(in); + SAW_EXPECT(text == "{\"count\":3,\"weight\":0.5}", "object layout"); + + data<TStruct> out; + codec<TStruct, Json> c; + auto eov = c.decode(data<TStruct,Json>{text}, out); + SAW_EXPECT(eov.is_value(), "decoded"); + SAW_EXPECT(out.get<"count">().get() == 3u, "count round trips"); + SAW_EXPECT(out.get<"weight">().get() == 0.5, "weight round trips"); +} + +SAW_TEST("Abstract/Json/StructIgnoresUnknownKeys"){ + using TStruct = ts::Struct<ts::Member<ts::UInt64,"count">>; + + data<TStruct> out; + codec<TStruct, Json> c; + // A nested unknown value has to be skipped whole, not just one token. + auto eov = c.decode( + data<TStruct,Json>{std::string{ + "{\"extra\":{\"a\":[1,2,{\"b\":\"x\"}]},\"count\":9}"}}, + out); + + SAW_EXPECT(eov.is_value(), "unknown members are skipped"); + SAW_EXPECT(out.get<"count">().get() == 9u, "known member still lands"); +} + +SAW_TEST("Abstract/Json/StructMissingMember"){ + using TStruct = ts::Struct< + ts::Member<ts::UInt64,"count">, + ts::Member<ts::UInt64,"other"> + >; + + // Lenient by default: a config states only its deviations. + data<TStruct> lenient; + codec<TStruct, Json> c; + auto eov = c.decode(data<TStruct,Json>{std::string{"{\"count\":1}"}}, lenient); + SAW_EXPECT(eov.is_value(), "a missing member is allowed by default"); + SAW_EXPECT(lenient.get<"other">().get() == 0u, "and keeps its default"); + + data<TStruct> strict; + codec<TStruct, Json> cs; + cs.set_strict(true); + auto eov_s = cs.decode(data<TStruct,Json>{std::string{"{\"count\":1}"}}, strict); + SAW_EXPECT(eov_s.is_error(), "strict decoding demands every member"); +} + +SAW_TEST("Abstract/Json/FixedArray"){ + using TArr = ts::FixedArray<ts::UInt64,3u>; + + data<TArr> in{1u,2u,3u}; + auto text = encode_to_string(in); + SAW_EXPECT(text == "[1,2,3]", "array layout"); + + data<TArr> out; + codec<TArr, Json> c; + SAW_EXPECT(c.decode(data<TArr,Json>{text}, out).is_value(), "decoded"); + SAW_EXPECT(out.flat_at(2u).get() == 3u, "elements round trip"); +} + +SAW_TEST("Abstract/Json/FixedArrayLengthMismatch"){ + using TArr = ts::FixedArray<ts::UInt64,3u>; + data<TArr> out; + + codec<TArr, Json> c_short; + SAW_EXPECT(c_short.decode(data<TArr,Json>{std::string{"[1,2]"}}, out).is_error(), + "too few elements is an error, there is no default to fill with"); + + codec<TArr, Json> c_long; + SAW_EXPECT(c_long.decode(data<TArr,Json>{std::string{"[1,2,3,4]"}}, out).is_error(), + "too many elements is an error, there is nowhere to put them"); +} + +SAW_TEST("Abstract/Json/DynamicArrayGrows"){ + using TArr = ts::Array<ts::UInt64,1u>; + + data<TArr> out; + codec<TArr, Json> c; + SAW_EXPECT(c.decode(data<TArr,Json>{std::string{"[5,6,7,8]"}}, out).is_value(), "decoded"); + SAW_EXPECT(out.size().get() == 4u, "array grew to fit the document"); + SAW_EXPECT(out.at({3u}).get() == 8u, "last element landed"); +} + +SAW_TEST("Abstract/Json/Tuple"){ + using TTup = ts::Tuple<ts::UInt64, ts::Bool>; + + data<TTup> in; + in.get<0u>().set(4u); + in.get<1u>().set(true); + + auto text = encode_to_string(in); + SAW_EXPECT(text == "[4,true]", "tuple is an array"); + + data<TTup> out; + codec<TTup, Json> c; + SAW_EXPECT(c.decode(data<TTup,Json>{text}, out).is_value(), "decoded"); + SAW_EXPECT(out.get<0u>().get() == 4u, "first element"); + SAW_EXPECT(out.get<1u>().get() == true, "second element"); +} + +SAW_TEST("Abstract/Json/Tensor"){ + using TVec = ts::Vector<ts::Float64,3u>; + + data<TVec> in{1.0, 2.0, 3.0}; + auto text = encode_to_string(in); + + data<TVec> out; + codec<TVec, Json> c; + SAW_EXPECT(c.decode(data<TVec,Json>{text}, out).is_value(), "decoded"); + SAW_EXPECT(out.flat_at(1u).get() == 2.0, "components round trip"); +} + +SAW_TEST("Abstract/Json/Nested"){ + using TInner = ts::Struct<ts::Member<ts::UInt64,"n">>; + using TOuter = ts::Struct< + ts::Member<TInner,"inner">, + ts::Member<ts::FixedArray<ts::UInt64,2u>,"pair"> + >; + + data<TOuter> in; + in.get<"inner">().get<"n">().set(1u); + in.get<"pair">().flat_at(0u).set(2u); + in.get<"pair">().flat_at(1u).set(3u); + + auto text = encode_to_string(in); + SAW_EXPECT(text == "{\"inner\":{\"n\":1},\"pair\":[2,3]}", "nested layout"); + + data<TOuter> out; + codec<TOuter, Json> c; + SAW_EXPECT(c.decode(data<TOuter,Json>{text}, out).is_value(), "decoded"); + SAW_EXPECT(out.get<"inner">().get<"n">().get() == 1u, "nested member"); + SAW_EXPECT(out.get<"pair">().flat_at(1u).get() == 3u, "nested array"); +} + +SAW_TEST("Abstract/Json/Whitespace"){ + using TStruct = ts::Struct<ts::Member<ts::UInt64,"count">>; + + data<TStruct> out; + codec<TStruct, Json> c; + auto eov = c.decode( + data<TStruct,Json>{std::string{" {\n\t\"count\" : 5\r\n} "}}, out); + + SAW_EXPECT(eov.is_value(), "whitespace around tokens is ignored"); + SAW_EXPECT(out.get<"count">().get() == 5u, "value still read"); +} + +SAW_TEST("Abstract/Json/RejectsTrailingContent"){ + data<ts::UInt64> out; + codec<ts::UInt64, Json> c; + auto eov = c.decode(data<ts::UInt64,Json>{std::string{"1 2"}}, out); + SAW_EXPECT(eov.is_error(), "content after the value means a malformed document"); +} + +SAW_TEST("Abstract/Json/RejectsMalformed"){ + using TStruct = ts::Struct<ts::Member<ts::UInt64,"count">>; + data<TStruct> out; + + codec<TStruct, Json> c_unclosed; + SAW_EXPECT(c_unclosed.decode(data<TStruct,Json>{std::string{"{\"count\":1"}}, out).is_error(), + "unterminated object"); + + codec<TStruct, Json> c_empty; + SAW_EXPECT(c_empty.decode(data<TStruct,Json>{std::string{""}}, out).is_error(), + "empty input"); + + codec<TStruct, Json> c_garbage; + SAW_EXPECT(c_garbage.decode(data<TStruct,Json>{std::string{"{\"count\":}"}}, out).is_error(), + "missing value"); +} + +SAW_TEST("Abstract/Json/DepthLimit"){ + using TArr = ts::Array<ts::UInt64,1u>; + + // The guard is against pathological nesting in untrusted input; a flat + // document sits well inside it. + data<TArr> out; + kel::lbm::codec_config<Json> cfg; + cfg.depth = 1u; + codec<TArr, Json> c{cfg}; + SAW_EXPECT(c.decode(data<TArr,Json>{std::string{"[1,2]"}}, out).is_value(), + "one level of nesting is within a depth of one"); +} + +SAW_TEST("Abstract/Json/StringEscapeRoundTrip"){ + data<ts::String> in{std::string{"tab\there \"quoted\" back\\slash"}}; + + data<ts::String> out; + codec<ts::String, Json> c; + auto eov = c.decode(data<ts::String,Json>{encode_to_string(in)}, out); + + SAW_EXPECT(eov.is_value(), "decoded"); + SAW_EXPECT(out.stl_view() == in.stl_view(), "escapes survive a round trip"); +} + +SAW_TEST("Abstract/Json/UnicodeEscape"){ + data<ts::String> out; + codec<ts::String, Json> c; + // U+00E9 encodes to two UTF-8 bytes. + auto eov = c.decode(data<ts::String,Json>{std::string{"\"\\u00e9\""}}, out); + + SAW_EXPECT(eov.is_value(), "decoded"); + SAW_EXPECT(out.size().get() == 2u, "decoded to UTF-8 rather than one byte"); +} + +SAW_TEST("Abstract/Json/PrettyPrint"){ + using TStruct = ts::Struct<ts::Member<ts::UInt64,"count">>; + + data<TStruct> in; + in.get<"count">().set(1u); + + auto text = encode_to_string(in, true); + SAW_EXPECT(text == "{\n \"count\": 1\n}", "pretty layout"); + + // Pretty output still has to parse back. + data<TStruct> out; + codec<TStruct, Json> c; + SAW_EXPECT(c.decode(data<TStruct,Json>{text}, out).is_value(), "reparsed"); + SAW_EXPECT(out.get<"count">().get() == 1u, "value preserved"); +} + +SAW_TEST("Abstract/Json/LbmConfigShape"){ + // The shape config.hpp actually loads. + using TConfig = ts::Struct< + ts::Member<ts::Float64, "delta_x">, + ts::Member<ts::Float64, "kinematic_viscosity">, + ts::Member<ts::Float64, "delta_t"> + >; + + data<TConfig> out; + codec<TConfig, Json> c; + auto eov = c.decode( + data<TConfig,Json>{std::string{ + "{\"delta_x\":0.01,\"kinematic_viscosity\":1.5e-5,\"delta_t\":0.001}"}}, + out); + + SAW_EXPECT(eov.is_value(), "a config document decodes"); + SAW_EXPECT(out.get<"delta_x">().get() == 0.01, "delta_x"); + SAW_EXPECT(out.get<"kinematic_viscosity">().get() == 1.5e-5, "viscosity"); + SAW_EXPECT(out.get<"delta_t">().get() == 0.001, "delta_t"); +} +} diff --git a/modules/core/tests/chunk.cpp b/modules/core/tests/chunk.cpp index 008d4c6..72d1341 100644 --- a/modules/core/tests/chunk.cpp +++ b/modules/core/tests/chunk.cpp @@ -4,7 +4,7 @@ namespace { namespace sch { -using namespace saw::schema; +using namespace kel::lbm::sch; } SAW_TEST("Chunk Ghost size 0"){ @@ -39,7 +39,7 @@ SAW_TEST("Chunk 2D setup"){ using TestChunk = lbm::sch::Chunk<sch::Float32, 1u, 2u, 2u>; - auto chunk = saw::heap<saw::data<TestChunk>>(); + auto chunk = kel::lbm::heap<kel::lbm::data<TestChunk>>(); chunk->at({{0u,0u}}).set(1.0f); SAW_EXPECT((chunk->ghost_at({{1u,1u}}).get() == 1.0f),"Check if ghost is at shifted spot."); } diff --git a/modules/core/tests/converter.cpp b/modules/core/tests/converter.cpp index 4fc536f..fa4a46c 100644 --- a/modules/core/tests/converter.cpp +++ b/modules/core/tests/converter.cpp @@ -18,7 +18,7 @@ SAW_TEST("Si Meter to Lbm Meter"){ {0.1} }; - saw::data<sch::SiMeter<sch::T>> si_m{1.0}; + kel::lbm::data<sch::SiMeter<sch::T>> si_m{1.0}; auto lbm_m = converter.meter_si_to_lbm(si_m); SAW_EXPECT(lbm_m.handle().get() == 10.0, "Correct si to lbm conversion"); diff --git a/modules/core/tests/equilibrium.cpp b/modules/core/tests/equilibrium.cpp index 7d36600..ad11699 100644 --- a/modules/core/tests/equilibrium.cpp +++ b/modules/core/tests/equilibrium.cpp @@ -11,15 +11,15 @@ void check_equilibrium(){ using dfi = lbm::df_info<lbm::sch::Float64,Descriptor>; - saw::data<lbm::sch::Scalar<lbm::sch::Float64>> rho; + kel::lbm::data<lbm::sch::Scalar<lbm::sch::Float64>> rho; rho.at({}).set(1.0); - saw::data<lbm::sch::Vector<lbm::sch::Float64,Descriptor::D>> vel; - for(saw::data<lbm::sch::UInt64> i{0u}; i.get() < Descriptor::D; ++i){ + kel::lbm::data<lbm::sch::Vector<lbm::sch::Float64,Descriptor::D>> vel; + for(kel::lbm::data<lbm::sch::UInt64> i{0u}; i.get() < Descriptor::D; ++i){ vel.at({{i}}) = {0.0}; } auto eq = lbm::equilibrium<lbm::sch::Float64,Descriptor>(rho,vel); - for(saw::data<lbm::sch::UInt64> i{0u}; i.get() < Descriptor::Q; ++i){ + for(kel::lbm::data<lbm::sch::UInt64> i{0u}; i.get() < Descriptor::Q; ++i){ SAW_EXPECT(eq.at(i).get() == dfi::weights[i.get()], std::string{"No momentum and normalized rho should be exactly the weights: "} + std::to_string(eq.at(i).get()) + std::string{" "} + std::to_string(dfi::weights[i.get()])); } } diff --git a/modules/core/tests/flatten.cpp b/modules/core/tests/flatten.cpp index 84b3fa4..3da05b5 100644 --- a/modules/core/tests/flatten.cpp +++ b/modules/core/tests/flatten.cpp @@ -4,15 +4,15 @@ namespace { namespace sch { -using namespace saw::schema; +using namespace kel::lbm::sch; } SAW_TEST("Flatten Index Stride"){ using namespace kel; - constexpr saw::data<sch::UInt64> zero = lbm::flatten_index<sch::UInt64,3u>::stride<0u>({{2u,4u,3u}}); - constexpr saw::data<sch::UInt64> one = lbm::flatten_index<sch::UInt64,3u>::stride<1u>({{2u,4u,3u}}); - constexpr saw::data<sch::UInt64> two = lbm::flatten_index<sch::UInt64,3u>::stride<2u>({{2u,4u,3u}}); + constexpr kel::lbm::data<sch::UInt64> zero = lbm::flatten_index<sch::UInt64,3u>::stride<0u>({{2u,4u,3u}}); + constexpr kel::lbm::data<sch::UInt64> one = lbm::flatten_index<sch::UInt64,3u>::stride<1u>({{2u,4u,3u}}); + constexpr kel::lbm::data<sch::UInt64> two = lbm::flatten_index<sch::UInt64,3u>::stride<2u>({{2u,4u,3u}}); SAW_EXPECT(zero.get() == 1u, "Zero is correct"); SAW_EXPECT(one.get() == 2u, "Zero is correct"); diff --git a/modules/core/tests/iterator.cpp b/modules/core/tests/iterator.cpp index 919c12c..4c1f877 100644 --- a/modules/core/tests/iterator.cpp +++ b/modules/core/tests/iterator.cpp @@ -12,10 +12,10 @@ using namespace kel::lbm::sch; SAW_TEST("Old Iterate"){ using namespace kel; - saw::data<sch::FixedArray<sch::UInt64,2u>> start{{0u,0u}}; - saw::data<sch::FixedArray<sch::UInt64,2u>> end{{3u,3u}}; + kel::lbm::data<sch::FixedArray<sch::UInt64,2u>> start{{0u,0u}}; + kel::lbm::data<sch::FixedArray<sch::UInt64,2u>> end{{3u,3u}}; - lbm::iterate_over([](const saw::data<sch::FixedArray<sch::UInt64,2u>>& index){ + lbm::iterate_over([](const kel::lbm::data<sch::FixedArray<sch::UInt64,2u>>& index){ std::cout<<"Index: "<<index.at({0u}).get()<<" "<<index.at({1u}).get()<<std::endl; }, start, end); } @@ -23,7 +23,7 @@ SAW_TEST("Old Iterate"){ SAW_TEST("CT Tuple Iterator"){ using namespace kel; - saw::data< + kel::lbm::data< sch::Tuple< sch::Float32, sch::Int16, @@ -32,18 +32,18 @@ SAW_TEST("CT Tuple Iterator"){ > > tup; - lbm::ct_tuple_iterator<std::decay_t<decltype(tup)>::Schema>::apply([](auto& val) -> saw::error_or<void> { - return saw::make_void(); + lbm::ct_tuple_iterator<std::decay_t<decltype(tup)>::Schema>::apply([](auto& val) -> kel::lbm::error_or<void> { + return kel::lbm::make_void(); },tup); } SAW_TEST("Old Iterate with Distance 1"){ using namespace kel; - saw::data<sch::FixedArray<sch::UInt64,2u>> start{{0u,0u}}; - saw::data<sch::FixedArray<sch::UInt64,2u>> end{{4u,4u}}; + kel::lbm::data<sch::FixedArray<sch::UInt64,2u>> start{{0u,0u}}; + kel::lbm::data<sch::FixedArray<sch::UInt64,2u>> end{{4u,4u}}; - lbm::iterate_over([](const saw::data<sch::FixedArray<sch::UInt64,2u>>& index){ + lbm::iterate_over([](const kel::lbm::data<sch::FixedArray<sch::UInt64,2u>>& index){ std::cout<<"Index: "<<index.at({0u}).get()<<" "<<index.at({1u}).get()<<std::endl; }, start, end, {{1u,1u}}); } @@ -51,10 +51,10 @@ SAW_TEST("Old Iterate with Distance 1"){ SAW_TEST("Iterate - 2D"){ using namespace kel; - saw::data<sch::FixedArray<sch::UInt64,2u>> start{{0u,0u}}; - saw::data<sch::FixedArray<sch::UInt64,2u>> end{{3u,3u}}; + kel::lbm::data<sch::FixedArray<sch::UInt64,2u>> start{{0u,0u}}; + kel::lbm::data<sch::FixedArray<sch::UInt64,2u>> end{{3u,3u}}; - lbm::iterator<2u>::apply([](const saw::data<sch::FixedArray<sch::UInt64,2u>>& index){ + lbm::iterator<2u>::apply([](const kel::lbm::data<sch::FixedArray<sch::UInt64,2u>>& index){ std::cout<<"Index: "<<index.at({0u}).get()<<" "<<index.at({1u}).get()<<std::endl; }, start, end); } @@ -62,10 +62,10 @@ SAW_TEST("Iterate - 2D"){ SAW_TEST("Iterate with Distance 1 - 2D"){ using namespace kel; - saw::data<sch::FixedArray<sch::UInt64,2u>> start{{0u,0u}}; - saw::data<sch::FixedArray<sch::UInt64,2u>> end{{4u,4u}}; + kel::lbm::data<sch::FixedArray<sch::UInt64,2u>> start{{0u,0u}}; + kel::lbm::data<sch::FixedArray<sch::UInt64,2u>> end{{4u,4u}}; - lbm::iterator<2u>::apply([](const saw::data<sch::FixedArray<sch::UInt64,2u>>& index){ + lbm::iterator<2u>::apply([](const kel::lbm::data<sch::FixedArray<sch::UInt64,2u>>& index){ std::cout<<"Index: "<<index.at({0u}).get()<<" "<<index.at({1u}).get()<<std::endl; }, start, end, {{1u,1u}}); } diff --git a/modules/core/tests/math.cpp b/modules/core/tests/math.cpp index d456ce8..3224e40 100644 --- a/modules/core/tests/math.cpp +++ b/modules/core/tests/math.cpp @@ -5,25 +5,25 @@ namespace { namespace sch { -using namespace saw::schema; +using namespace kel::lbm::sch; } SAW_TEST("Math 1-Linear"){ using namespace kel; - saw::data<sch::FixedArray<sch::Vector<sch::Float64,1u>,2u>> field; + kel::lbm::data<sch::FixedArray<sch::Vector<sch::Float64,1u>,2u>> field; { field.at({{0u}}).at({{0u}}).set(-1.0); field.at({{1u}}).at({{0u}}).set(2.0); } - saw::data<sch::Vector<sch::Float64,1u>> pos; + kel::lbm::data<sch::Vector<sch::Float64,1u>> pos; pos.at({{0u}}).set(0.3); } SAW_TEST("Math/Floor Index and Fraction from Position"){ using namespace kel; - saw::data<sch::Vector<sch::Float64,2u>> pos; + kel::lbm::data<sch::Vector<sch::Float64,2u>> pos; { pos.at({{0u}}) = 43.999; @@ -48,14 +48,14 @@ SAW_TEST("Math/Floor Index and Fraction from Position"){ SAW_TEST("Math/Floor Index and Fraction from Position and Bounded"){ using namespace kel; - saw::data<sch::Vector<sch::Float64,2u>> pos; + kel::lbm::data<sch::Vector<sch::Float64,2u>> pos; { pos.at({{0u}}) = 43.999; pos.at({{1u}}) = -50.0; } - saw::data<sch::Vector<sch::UInt64,2U>> bound; + kel::lbm::data<sch::Vector<sch::UInt64,2U>> bound; { bound.at({{0u}}) = 32u; bound.at({{1u}}) = 16u; diff --git a/modules/core/tests/memory.cpp b/modules/core/tests/memory.cpp index d59d212..f0b1499 100644 --- a/modules/core/tests/memory.cpp +++ b/modules/core/tests/memory.cpp @@ -4,7 +4,7 @@ namespace { namespace sch { -using namespace saw::schema; +using namespace kel::lbm::sch; using TStruct = Struct< Member<Float32,"a">, diff --git a/modules/core/tests/particles.cpp b/modules/core/tests/particles.cpp index e060097..823bcd7 100644 --- a/modules/core/tests/particles.cpp +++ b/modules/core/tests/particles.cpp @@ -12,7 +12,7 @@ using T = Float64; SAW_TEST("Verlet step 2D - Planar"){ using namespace kel; - saw::data<sch::Particle<sch::T,2u>> particle; + kel::lbm::data<sch::Particle<sch::T,2u>> particle; auto& body = particle.template get<"rigid_body">(); auto& pos = body.template get<"position">(); auto& pos_old = body.template get<"position_old">(); @@ -22,7 +22,7 @@ SAW_TEST("Verlet step 2D - Planar"){ acc.at({{0}}).set({1.0}); - saw::data<sch::Scalar<sch::T>> dt; + kel::lbm::data<sch::Scalar<sch::T>> dt; dt.at({}).set(0.5); lbm::verlet_step_lambda<sch::T,2u>(particle,dt); @@ -33,7 +33,7 @@ SAW_TEST("Verlet step 2D - Planar"){ SAW_TEST("No Collision Spheroid 2D"){ using namespace kel; - saw::data<sch::Particle<sch::T,2u>> part_a; + kel::lbm::data<sch::Particle<sch::T,2u>> part_a; { auto& body = part_a.template get<"rigid_body">(); auto& pos = body.template get<"position">(); @@ -42,7 +42,7 @@ SAW_TEST("No Collision Spheroid 2D"){ pos.at({{1u}}) = 0.2; } - saw::data<sch::Particle<sch::T,2u>> part_b; + kel::lbm::data<sch::Particle<sch::T,2u>> part_b; { auto& body = part_b.template get<"rigid_body">(); auto& pos = body.template get<"position">(); @@ -59,7 +59,7 @@ SAW_TEST("No Collision Spheroid 2D"){ SAW_TEST("Collision Spheroid 2D"){ using namespace kel; - saw::data<sch::Particle<sch::T,2u>> part_a; + kel::lbm::data<sch::Particle<sch::T,2u>> part_a; { auto& body = part_a.template get<"rigid_body">(); auto& pos = body.template get<"position">(); @@ -72,7 +72,7 @@ SAW_TEST("Collision Spheroid 2D"){ pos.at({{1u}}) = 0.2; } - saw::data<sch::Particle<sch::T,2u>> part_b; + kel::lbm::data<sch::Particle<sch::T,2u>> part_b; { auto& body = part_b.template get<"rigid_body">(); auto& pos = body.template get<"position">(); @@ -93,7 +93,7 @@ SAW_TEST("Collision Spheroid 2D"){ SAW_TEST("Moving particles 2D"){ using namespace kel; - saw::data<sch::Particle<sch::T,2u>> part_a; + kel::lbm::data<sch::Particle<sch::T,2u>> part_a; { auto& body = part_a.template get<"rigid_body">(); auto& pos = body.template get<"position">(); @@ -110,7 +110,7 @@ SAW_TEST("Moving particles 2D"){ acc.at({{0u}}) = 0.1; } - saw::data<sch::Particle<sch::T,2u>> part_b; + kel::lbm::data<sch::Particle<sch::T,2u>> part_b; { auto& body = part_b.template get<"rigid_body">(); auto& pos = body.template get<"position">(); @@ -127,7 +127,7 @@ SAW_TEST("Moving particles 2D"){ acc.at({{0u}}) = -0.1; } - saw::data<sch::Scalar<sch::T>> dt; + kel::lbm::data<sch::Scalar<sch::T>> dt; dt.at({}).set(0.5); bool has_collided = false; for(uint64_t i = 0u; i < 32u; ++i){ @@ -147,7 +147,7 @@ SAW_TEST("Moving particles 2D"){ SAW_TEST("Particle Matrix Rotation"){ using namespace kel; - saw::data<sch::Particle<sch::T,2u>> part_a; + kel::lbm::data<sch::Particle<sch::T,2u>> part_a; { auto& body = part_a.template get<"rigid_body">(); auto& pos = body.template get<"position">(); @@ -164,7 +164,7 @@ SAW_TEST("Particle Matrix Rotation"){ SAW_TEST("Particle Collision Impulse"){ using namespace kel; - saw::data<sch::Particle<sch::T,2u>> part_a; + kel::lbm::data<sch::Particle<sch::T,2u>> part_a; { auto& body = part_a.template get<"rigid_body">(); auto& pos = body.template get<"position">(); @@ -181,7 +181,7 @@ SAW_TEST("Particle Collision Impulse"){ acc.at({{0u}}) = 0.1; } - saw::data<sch::Particle<sch::T,2u>> part_b; + kel::lbm::data<sch::Particle<sch::T,2u>> part_b; { auto& body = part_b.template get<"rigid_body">(); auto& pos = body.template get<"position">(); @@ -210,15 +210,15 @@ SAW_TEST("Minor Test for mask"){ auto& grid = mask.template get<"grid">(); - for(saw::data<sch::UInt64> i{0u}; i < grid.template get_dim_size<0>(); ++i){ - for(saw::data<sch::UInt64> j{0u}; j < grid.template get_dim_size<1>(); ++j){ + for(kel::lbm::data<sch::UInt64> i{0u}; i < grid.template get_dim_size<0>(); ++i){ + for(kel::lbm::data<sch::UInt64> j{0u}; j < grid.template get_dim_size<1>(); ++j){ std::cout<<grid.at({{i,j}}).get()<<" "; } std::cout<<"\n"; } std::cout<<std::endl; - //saw::data<sch::Array<sch::T,2>> reference_mask{{{4+2,4+2}}}; + //kel::lbm::data<sch::Array<sch::T,2>> reference_mask{{{4+2,4+2}}}; //reference_mask.at({{0,0}}); } */ @@ -228,7 +228,7 @@ SAW_TEST("Verlet integration test 2D"){ lbm::particle_system<sch::T,2,sch::Particle<sch::T,2>> system; { - saw::data<sch::Particle<sch::T,2>> particle; + kel::lbm::data<sch::Particle<sch::T,2>> particle; auto& rb = particle.template get<"rigid_body">(); auto& acc = rb.template get<"acceleration">(); auto& pos = rb.template get<"position">(); @@ -245,21 +245,21 @@ SAW_TEST("Verlet integration test 2D"){ auto& rb = p.template get<"rigid_body">(); auto& pos = rb.template get<"position">(); - for(saw::data<sch::UInt64> i{0u}; i < saw::data<sch::UInt64>{2u}; ++i){ + for(kel::lbm::data<sch::UInt64> i{0u}; i < kel::lbm::data<sch::UInt64>{2u}; ++i){ std::cout<<pos.at(i).get()<<" "; } std::cout<<std::endl; } for(uint64_t i = 0u; i < 36u; ++i){ - system.step(saw::data<sch::T>{1e-1}); + system.step(kel::lbm::data<sch::T>{1e-1}); { auto& p = system.at({0u}); auto& rb = p.template get<"rigid_body">(); auto& pos = rb.template get<"position">(); - for(saw::data<sch::UInt64> i{0u}; i < saw::data<sch::UInt64>{2u}; ++i){ + for(kel::lbm::data<sch::UInt64> i{0u}; i < kel::lbm::data<sch::UInt64>{2u}; ++i){ std::cout<<pos.at(i).get()<<" "; } std::cout<<"\n"; @@ -280,7 +280,7 @@ SAW_TEST("Spheroid Particle / AABB"){ constexpr uint64_t D = 2u; constexpr uint64_t PC = 1u; - saw::data<sch::Scalar<T>> radi,dense; + kel::lbm::data<sch::Scalar<T>> radi,dense; radi.at({}) = 2.2f; dense.at({}) = 1.0f; auto spheroid_pgrp = lbm::create_spheroid_particle_group<T,D,PC>(radi,dense,{8u}); diff --git a/modules/core/tests/vtk_write.cpp b/modules/core/tests/vtk_write.cpp index 1de25bf..b2a5682 100644 --- a/modules/core/tests/vtk_write.cpp +++ b/modules/core/tests/vtk_write.cpp @@ -44,7 +44,7 @@ SAW_TEST("VTK Write test example"){ std::stringstream sstream; - saw::data<sch::Array<sch::MacroStruct<sch::T,2>, 2>> cells{{{2u,2u}}}; + kel::lbm::data<sch::Array<sch::MacroStruct<sch::T,2>, 2>> cells{{{2u,2u}}}; auto& cell_0 = cells.at({{{0,0}}}); cell_0.template get<"momentum">()= {{0.5,-0.1}}; @@ -69,7 +69,7 @@ SAW_TEST("VTK Write raw test example"){ std::stringstream sstream; - saw::data<sch::Array<sch::MacroStruct<sch::T,2>, 2>> cells{{{2u,2u}}}; + kel::lbm::data<sch::Array<sch::MacroStruct<sch::T,2>, 2>> cells{{{2u,2u}}}; auto meta = cells.dims(); |
