summaryrefslogtreecommitdiff
path: root/modules/core/c++
diff options
context:
space:
mode:
authorClaudius "keldu" Holeksa <mail@keldu.de>2026-11-11 01:16:44 +0100
committerClaudius "keldu" Holeksa <mail@keldu.de>2026-11-11 01:16:44 +0100
commit0c0087ef9482634273ec1a23d3a915754f94926d (patch)
tree972a8e48c1fae67af23b982d7a9e1a506fc8705f /modules/core/c++
parent2e63c4a31f946a8bafa92c49c1a0a116c0eb6dae (diff)
downloadlibs-lbm-0c0087ef9482634273ec1a23d3a915754f94926d.tar.gz
Snapshot. Migration to Lbm Unit
Diffstat (limited to 'modules/core/c++')
-rw-r--r--modules/core/c++/abstract/math.hpp63
-rw-r--r--modules/core/c++/abstract/unit.hpp247
-rw-r--r--modules/core/c++/abstract/unit_print.hpp75
-rw-r--r--modules/core/c++/boundary.hpp46
-rw-r--r--modules/core/c++/collision.hpp4
-rw-r--r--modules/core/c++/component/psm.hpp2
-rw-r--r--modules/core/c++/converter.hpp2
-rw-r--r--modules/core/c++/descriptor/d3q27.hpp70
-rw-r--r--modules/core/c++/fplbm.hpp41
-rw-r--r--modules/core/c++/hlbm.hpp55
-rw-r--r--modules/core/c++/particle/aabb.hpp2
-rw-r--r--modules/core/c++/particle/contact.hpp20
-rw-r--r--modules/core/c++/particle/couple.hpp2
-rw-r--r--modules/core/c++/particle/integrate.hpp166
-rw-r--r--modules/core/c++/particle/particle.hpp26
-rw-r--r--modules/core/c++/particle/porosity.hpp2
-rw-r--r--modules/core/c++/particle/schema.hpp22
-rw-r--r--modules/core/c++/psm.hpp18
18 files changed, 714 insertions, 149 deletions
diff --git a/modules/core/c++/abstract/math.hpp b/modules/core/c++/abstract/math.hpp
index d692be1..2d32a43 100644
--- a/modules/core/c++/abstract/math.hpp
+++ b/modules/core/c++/abstract/math.hpp
@@ -4,6 +4,7 @@
#include "data.hpp"
#include "data_math.hpp"
+#include "unit.hpp"
namespace kel {
namespace lbm {
@@ -86,6 +87,68 @@ normalize(const data<sch::Vector<T, D>, Encoding> &input) {
}
/**
+ * Square root of a unit carrying scalar: the exponents halve, so the root of
+ * an area is a length.
+ *
+ * Only defined when every exponent is even -- a half power of a base unit is
+ * not expressible here, and silently truncating would be worse than refusing.
+ */
+template <typename T, typename... U, int64_t... E, int64_t... S,
+ typename Encoding = KEL_LBM_DEFAULT_DATA_ENCODING>
+data<sch::Unit<sch::Scalar<T>, sch::UnitElement<U, E / 2, S>...>, Encoding>
+sqrt(const data<sch::Unit<sch::Scalar<T>, sch::UnitElement<U, E, S>...>,
+ Encoding> &inp) {
+ static_assert(((E % 2 == 0) && ...),
+ "sqrt of a unit needs even exponents");
+ return data<sch::Unit<sch::Scalar<T>, sch::UnitElement<U, E / 2, S>...>,
+ Encoding>{sqrt<T, Encoding>(inp.handle())};
+}
+
+/**
+ * Unit aware vector algebra.
+ *
+ * A unit belongs to the vector as a whole (see unit.hpp), so each of these
+ * recovers the raw vector, reuses the plain implementation above, and then
+ * re-attaches the unit the result actually carries. The result unit is
+ * computed rather than copied: the dot product of two lengths is an area, and
+ * a normalised vector is a direction and therefore dimensionless.
+ */
+template <typename T, uint64_t D, typename... EleL, typename... EleR,
+ typename Encoding = KEL_LBM_DEFAULT_DATA_ENCODING>
+auto dot(const data<sch::Unit<sch::Vector<T, D>, EleL...>, Encoding> &left,
+ const data<sch::Unit<sch::Vector<T, D>, EleR...>, Encoding> &right) {
+ using ResultSchema =
+ typename kel::lbm::unit_multiplication<sch::Unit<sch::Scalar<T>, EleL...>,
+ sch::Unit<sch::Scalar<T>, EleR...>>::Schema;
+ return data<ResultSchema, Encoding>{
+ dot<T, D, Encoding>(left.handle(), right.handle())};
+}
+
+/**
+ * Length of a unit carrying vector. sqrt of an area is a length, so the unit
+ * is unchanged.
+ */
+template <typename T, uint64_t D, typename... Ele,
+ typename Encoding = KEL_LBM_DEFAULT_DATA_ENCODING>
+data<sch::Unit<sch::Scalar<T>, Ele...>, Encoding>
+norm(const data<sch::Unit<sch::Vector<T, D>, Ele...>, Encoding> &input) {
+ return data<sch::Unit<sch::Scalar<T>, Ele...>, Encoding>{
+ sqrt<T, Encoding>(dot<T, D, Encoding>(input.handle(), input.handle()))};
+}
+
+/**
+ * A direction is dimensionless, and dimensionless is spelled Pure -- a bare
+ * Vector would only mean "carries no annotation", which is a different claim.
+ */
+template <typename T, uint64_t D, typename... Ele,
+ typename Encoding = KEL_LBM_DEFAULT_DATA_ENCODING>
+data<sch::Pure<sch::Vector<T, D>>, Encoding>
+normalize(const data<sch::Unit<sch::Vector<T, D>, Ele...>, Encoding> &input) {
+ return data<sch::Pure<sch::Vector<T, D>>, Encoding>{
+ normalize<T, D, Encoding>(input.handle())};
+}
+
+/**
* Reinterprets a plain fixed array as a vector, so the algebra below applies
* to it.
*/
diff --git a/modules/core/c++/abstract/unit.hpp b/modules/core/c++/abstract/unit.hpp
index 406cb2f..b3d7391 100644
--- a/modules/core/c++/abstract/unit.hpp
+++ b/modules/core/c++/abstract/unit.hpp
@@ -10,11 +10,21 @@ namespace lbm {
namespace sch {
/**
- * One factor of a unit: a base quantity raised to `Expo`, at scale `Scal`.
+ * One factor of a unit: a base quantity raised to `Expo`, at decimal 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.
+ * `Scal` is an SI prefix exponent -- nano -9, micro -6, milli -3, none 0, kilo
+ * 3, mega 6, giga 9. It is a pure tag: the stored number is the value as
+ * written, so 2 km holds 2.0 and nothing is ever multiplied by a power of ten.
+ *
+ * It is NOT what separates lattice from SI. That comes from the base tag type
+ * itself -- `lbm_type::meter` and `si_type::meter` are distinct types, so
+ * mixing them cannot compile regardless of scale (see lbm_unit.hpp).
+ *
+ * Two factors fold their exponents only when base AND scale match
+ * (unit_matching_reduce below). Differently scaled quantities therefore do not
+ * add: km + m is a compile error by type identity. Implicit rescaling is
+ * deliberately absent -- add it here if it is ever wanted.
*/
template <typename Un, int64_t Expo = 0, int64_t Scal = 0> struct UnitElement {
using Schema = Un;
@@ -43,21 +53,19 @@ namespace impl {
template <typename T, typename U> class unit_matching;
+/**
+ * A plain type list of UnitElements, used only to carry a pack around while
+ * the factors are being reduced. It holds no members: the specialisation below
+ * exists purely so that a non empty pack does not hit this assert.
+ */
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;
-};
+ sch::UnitElement<TL, EL, SL>...> {};
template <typename T, typename U, typename V> class unit_matching_reduce {
public:
@@ -108,7 +116,6 @@ 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 {
@@ -141,6 +148,85 @@ public:
using TypeList = typename unit_matching<ReducedTypeList, TypeRightList>::TypeList;
};
+/**
+ * Whether a schema is a Unit at all. Lets the arithmetic below tell a united
+ * operand from a bare one.
+ */
+template <typename S> struct is_unit_schema : std::false_type {};
+
+template <typename B, typename... E>
+struct is_unit_schema<sch::Unit<B, E...>> : std::true_type {};
+
+/**
+ * Splits a Unit into its base schema and its component list, so the list can
+ * be re-hosted on a different base.
+ *
+ * Needed because multiplying a unit vector by a unit scalar changes the base
+ * (Vector * Scalar -> Vector) while the component lists still have to be
+ * combined against each other. unit_multiplication requires both operands to
+ * share a base, so both are rebased onto the result first.
+ */
+template <typename U> struct unit_parts;
+
+template <typename B, typename... E> struct unit_parts<sch::Unit<B, E...>> {
+ using Base = B;
+ template <typename NewBase> using Rebase = sch::Unit<NewBase, E...>;
+};
+
+/**
+ * A total order on unit factors, so that the same physical unit is always the
+ * same C++ type.
+ *
+ * Without this the reduction keeps encounter order, and m * s^-1 produces a
+ * different type from s^-1 * m -- the same quantity reached two ways then
+ * fails to match, and the mismatch shows up as a baffling template error far
+ * from its cause. Sorting by the base tag name gives a canonical form; the
+ * scale breaks ties so that factors differing only in prefix still order
+ * deterministically.
+ */
+template <typename A, typename B> struct unit_element_less;
+
+template <typename TA, int64_t EA, int64_t SA, typename TB, int64_t EB, int64_t SB>
+struct unit_element_less<sch::UnitElement<TA, EA, SA>, sch::UnitElement<TB, EB, SB>> {
+ static constexpr bool value =
+ (TA::name != TB::name) ? (TA::name < TB::name) : (SA < SB);
+};
+
+template <typename Ele, typename List> struct unit_prepend;
+
+template <typename Ele, typename... L>
+struct unit_prepend<Ele, unit_redux_list<L...>> {
+ using Type = unit_redux_list<Ele, L...>;
+};
+
+template <typename Ele, typename List> struct unit_insert;
+
+template <typename Ele> struct unit_insert<Ele, unit_redux_list<>> {
+ using Type = unit_redux_list<Ele>;
+};
+
+template <typename Ele, typename Head, typename... Tail>
+struct unit_insert<Ele, unit_redux_list<Head, Tail...>> {
+ using Type = typename std::conditional<
+ unit_element_less<Ele, Head>::value,
+ unit_redux_list<Ele, Head, Tail...>,
+ typename unit_prepend<
+ Head,
+ typename unit_insert<Ele, unit_redux_list<Tail...>>::Type>::Type>::type;
+};
+
+template <typename List> struct unit_sort;
+
+template <> struct unit_sort<unit_redux_list<>> {
+ using Type = unit_redux_list<>;
+};
+
+template <typename Head, typename... Tail>
+struct unit_sort<unit_redux_list<Head, Tail...>> {
+ using Type = typename unit_insert<
+ Head, typename unit_sort<unit_redux_list<Tail...>>::Type>::Type;
+};
+
template <typename BaseSchema, typename List> class unit_add_base {
static_assert(always_false<BaseSchema, List>, "Template type not supported");
};
@@ -154,24 +240,47 @@ public:
} // namespace impl
template <typename BaseSchema, typename... UE> struct unit_element_reduction {
- using TypeList =
+ // Sorted after reducing, so the result is canonical regardless of the
+ // order the factors arrived in.
+ using TypeList = typename impl::unit_sort<
typename impl::unit_matching<impl::unit_redux_list<UE...>,
- impl::unit_redux_list<>>::TypeList;
+ impl::unit_redux_list<>>::TypeList>::Type;
using Schema = typename impl::unit_add_base<BaseSchema, TypeList>::Schema;
};
+/**
+ * Labels a bare value with a unit.
+ *
+ * The deliberate way to cross from untyped to typed now that the wrapping
+ * constructor is explicit. Being a named function, every such crossing is
+ * greppable instead of happening silently at a call site.
+ */
+template <typename UnitSchema, typename S,
+ typename Encoding = KEL_LBM_DEFAULT_DATA_ENCODING>
+constexpr data<UnitSchema, Encoding> as_unit(const data<S, Encoding> &value) {
+ return data<UnitSchema, Encoding>{value};
+}
+
template <typename U0, typename U1> struct unit_multiplication {
static_assert(always_false<U0, U1>, "Template type not supported");
};
+/**
+ * The scale packs have to be deduced explicitly. Writing
+ * `sch::UnitElement<UnitT, UnitE>` here would mean
+ * `sch::UnitElement<UnitT, UnitE, 0>` after the default argument is
+ * substituted, so the specialisation would only ever match zero scaled factors
+ * and anything prefixed would fall through to the always_false primary.
+ */
template <typename BaseSchema, typename... UnitT, int64_t... UnitE,
- typename... UnitRhsT, int64_t... UnitRhsE>
+ int64_t... UnitS, typename... UnitRhsT, int64_t... UnitRhsE,
+ int64_t... UnitRhsS>
struct unit_multiplication<
- sch::Unit<BaseSchema, sch::UnitElement<UnitT, UnitE>...>,
- sch::Unit<BaseSchema, sch::UnitElement<UnitRhsT, UnitRhsE>...>> {
+ sch::Unit<BaseSchema, sch::UnitElement<UnitT, UnitE, UnitS>...>,
+ sch::Unit<BaseSchema, sch::UnitElement<UnitRhsT, UnitRhsE, UnitRhsS>...>> {
using Schema = typename unit_element_reduction<
- BaseSchema, sch::UnitElement<UnitT, UnitE>...,
- sch::UnitElement<UnitRhsT, UnitRhsE>...>::Schema;
+ BaseSchema, sch::UnitElement<UnitT, UnitE, UnitS>...,
+ sch::UnitElement<UnitRhsT, UnitRhsE, UnitRhsS>...>::Schema;
};
template <typename U0, typename U1> struct unit_division {
@@ -180,15 +289,21 @@ template <typename U0, typename U1> struct unit_division {
/**
* Division is multiplication by the negated exponents.
+ *
+ * The scale is deliberately NOT negated. Scale says which base unit is meant
+ * -- km rather than m -- while the exponent says what power it is raised to.
+ * So (km)^-1 is scale 3, exponent -1; negating the scale as well would quietly
+ * turn it into (mm)^-1. The symmetry with the exponent is only apparent.
*/
template <typename BaseSchema, typename... UnitT, int64_t... UnitE,
- typename... UnitRhsT, int64_t... UnitRhsE>
+ int64_t... UnitS, typename... UnitRhsT, int64_t... UnitRhsE,
+ int64_t... UnitRhsS>
struct unit_division<
- sch::Unit<BaseSchema, sch::UnitElement<UnitT, UnitE>...>,
- sch::Unit<BaseSchema, sch::UnitElement<UnitRhsT, UnitRhsE>...>> {
+ sch::Unit<BaseSchema, sch::UnitElement<UnitT, UnitE, UnitS>...>,
+ sch::Unit<BaseSchema, sch::UnitElement<UnitRhsT, UnitRhsE, UnitRhsS>...>> {
using Schema = typename unit_element_reduction<
- BaseSchema, sch::UnitElement<UnitT, UnitE>...,
- sch::UnitElement<UnitRhsT, -UnitRhsE>...>::Schema;
+ BaseSchema, sch::UnitElement<UnitT, UnitE, UnitS>...,
+ sch::UnitElement<UnitRhsT, -UnitRhsE, UnitRhsS>...>::Schema;
};
/**
@@ -212,16 +327,32 @@ public:
KEL_DEFAULT_COPY(data);
KEL_DEFAULT_MOVE(data);
- data(const BaseData &dat__) : dat_{dat__} {}
+/**
+ * Explicit: an already built value of the base type does not get to pick
+ * up a unit just because a unit was expected there. That is how an
+ * untyped sub step scalar silently became a time.
+ */
+ explicit data(const BaseData &dat__) : dat_{dat__} {}
+
+ explicit data(BaseData &&dat__) : dat_{std::move(dat__)} {}
- data(BaseData &&dat__) : dat_{std::move(dat__)} {}
+ /**
+ * A bare literal is still allowed to become a united quantity at a
+ * construction site, because that is where the author is stating the
+ * unit. Only primitives, so this never competes with the base copy above
+ * for tensor valued units.
+ */
+ template <typename V, typename B = BaseSchema>
+ requires(sch::is_primitive<B>::value && std::is_arithmetic_v<V>)
+ data(V value__)
+ : dat_{static_cast<typename native_data_type<B>::type>(value__)} {}
data<Schema, enc::Native> operator+(const data<Schema, enc::Native> &rhs) const {
- return {dat_ + rhs.handle()};
+ return data<Schema, enc::Native>{dat_ + rhs.handle()};
}
data<Schema, enc::Native> operator-(const data<Schema, enc::Native> &rhs) const {
- return {dat_ - rhs.handle()};
+ return data<Schema, enc::Native>{dat_ - rhs.handle()};
}
data<Schema, enc::Native> &operator+=(const data<Schema, enc::Native> &rhs) {
@@ -250,22 +381,68 @@ public:
return dat_ > rhs.handle();
}
+/**
+ * The operands need not share a base schema: a length vector times a
+ * dimensionless scalar is a length vector. The base of the result is
+ * whatever the underlying arithmetic produces, and both component lists
+ * are rebased onto it before being combined.
+ */
template <typename UnitRhs>
- data<typename unit_multiplication<Schema, UnitRhs>::Schema, enc::Native>
- operator*(const data<UnitRhs, enc::Native> &rhs) const {
- return {dat_ * rhs.handle()};
+ requires impl::is_unit_schema<UnitRhs>::value
+ auto operator*(const data<UnitRhs, enc::Native> &rhs) const {
+ auto raw = dat_ * rhs.handle();
+ using ResultBase = typename std::remove_cvref_t<decltype(raw)>::Schema;
+ using ResultSchema = typename unit_multiplication<
+ typename impl::unit_parts<Schema>::template Rebase<ResultBase>,
+ typename impl::unit_parts<UnitRhs>::template Rebase<ResultBase>>::Schema;
+ return data<ResultSchema, enc::Native>{raw};
}
template <typename UnitRhs>
- data<typename unit_division<Schema, UnitRhs>::Schema, enc::Native>
- operator/(const data<UnitRhs, enc::Native> &rhs) const {
- return {dat_ / rhs.handle()};
+ requires impl::is_unit_schema<UnitRhs>::value
+ auto operator/(const data<UnitRhs, enc::Native> &rhs) const {
+ auto raw = dat_ / rhs.handle();
+ using ResultBase = typename std::remove_cvref_t<decltype(raw)>::Schema;
+ using ResultSchema = typename unit_division<
+ typename impl::unit_parts<Schema>::template Rebase<ResultBase>,
+ typename impl::unit_parts<UnitRhs>::template Rebase<ResultBase>>::Schema;
+ return data<ResultSchema, enc::Native>{raw};
}
/**
* The underlying value, with the unit stripped. Mostly for the
* multiplication and division operators above.
*/
+/**
+ * Element access forwards to the underlying tensor and returns the raw
+ * element.
+ *
+ * The unit belongs to the quantity as a whole, not to one component -- a
+ * position is metres in every component -- so there is nothing distinct to
+ * attach per element. The wrapper is also not stored per element, so a
+ * reference to a unit typed component could not be formed even if it were
+ * wanted. Mixing is still caught, just at the vector level.
+ */
+ /**
+ * The rank is taken through a defaulted template parameter so that it is
+ * a substitution failure, not a hard error, when the base is not a tensor.
+ * The parameter type itself stays concrete, because a braced index like
+ * at({{0u}}) cannot be deduced against a template parameter.
+ */
+ template <typename B = BaseSchema>
+ auto &at(const index_data<B::Rank> &index) {
+ return dat_.at(index);
+ }
+
+ template <typename B = BaseSchema>
+ const auto &at(const index_data<B::Rank> &index) const {
+ return dat_.at(index);
+ }
+
+ auto &flat_at(uint64_t i) { return dat_.flat_at(i); }
+
+ const auto &flat_at(uint64_t i) const { return dat_.flat_at(i); }
+
const BaseData &handle() const { return dat_; }
BaseData &handle() { return dat_; }
diff --git a/modules/core/c++/abstract/unit_print.hpp b/modules/core/c++/abstract/unit_print.hpp
index 049e54f..2cb2ba6 100644
--- a/modules/core/c++/abstract/unit_print.hpp
+++ b/modules/core/c++/abstract/unit_print.hpp
@@ -1,13 +1,66 @@
#pragma once
#include <ostream>
+#include <string_view>
#include "unit.hpp"
+namespace kel {
+namespace lbm {
+namespace impl {
+/**
+ * SI prefix symbol for a decimal scale exponent.
+ *
+ * Returns an empty view for the unprefixed case and for anything outside the
+ * table, which the caller renders as an explicit 10^n instead. Printing a
+ * scaled unit identically to an unscaled one would be worse than not printing
+ * it at all, so there is no silent fallback.
+ */
+inline constexpr std::string_view unit_prefix_symbol(int64_t scale) {
+ switch (scale) {
+ case -9:
+ return "n";
+ case -6:
+ return "u";
+ case -3:
+ return "m";
+ case 0:
+ return "";
+ case 3:
+ return "k";
+ case 6:
+ return "M";
+ case 9:
+ return "G";
+ default:
+ return "";
+ }
+}
+
+inline constexpr bool unit_prefix_known(int64_t scale) {
+ return scale == -9 || scale == -6 || scale == -3 || scale == 0 ||
+ scale == 3 || scale == 6 || scale == 9;
+}
+} // namespace impl
+} // namespace lbm
+} // namespace kel
+
namespace std {
-template <typename UT, int64_t UE>
+/**
+ * The scale has to be deduced, not defaulted: writing UnitElement<UT, UE> here
+ * would only ever match zero scaled factors, and a prefixed one would fail to
+ * bind at all.
+ */
+template <typename UT, int64_t UE, int64_t US>
inline ostream &operator<<(ostream &o,
- const ::kel::lbm::sch::UnitElement<UT, UE> &) {
+ const ::kel::lbm::sch::UnitElement<UT, UE, US> &) {
+ if constexpr (US != 0) {
+ if constexpr (::kel::lbm::impl::unit_prefix_known(US)) {
+ o << ::kel::lbm::impl::unit_prefix_symbol(US);
+ } else {
+ o << "10^(" << US << ')' << '*';
+ }
+ }
o << UT::short_name;
if constexpr (UE != 1) {
o << '^' << '(' << UE << ')';
@@ -23,16 +76,19 @@ 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>...> {
+template <typename UT, int64_t UE, int64_t US, typename... UTL, int64_t... UEL,
+ int64_t... USL>
+struct unit_print<sch::UnitElement<UT, UE, US>,
+ sch::UnitElement<UTL, UEL, USL>...> {
static std::ostream &print(std::ostream &o) {
- sch::UnitElement<UT, UE> element;
+ sch::UnitElement<UT, UE, US> 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 unit_print<sch::UnitElement<UTL, UEL, USL>...>::print(
+ o_ret_next);
}
return o_ret << ']';
@@ -44,18 +100,19 @@ struct unit_print<sch::UnitElement<UT, UE>, sch::UnitElement<UTL, UEL>...> {
namespace std {
template <typename StorageT, typename Encode, typename... UnitT,
- int64_t... UnitE>
+ int64_t... UnitE, int64_t... UnitS>
inline ostream &
operator<<(ostream &o,
const ::kel::lbm::data<
::kel::lbm::sch::Unit<
- StorageT, ::kel::lbm::sch::UnitElement<UnitT, UnitE>...>,
+ StorageT,
+ ::kel::lbm::sch::UnitElement<UnitT, UnitE, UnitS>...>,
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);
+ ::kel::lbm::sch::UnitElement<UnitT, UnitE, UnitS>...>::print(o_ret);
}
return o;
}
diff --git a/modules/core/c++/boundary.hpp b/modules/core/c++/boundary.hpp
index d9ac941..7e5e65b 100644
--- a/modules/core/c++/boundary.hpp
+++ b/modules/core/c++/boundary.hpp
@@ -231,6 +231,22 @@ class component<FP, sch::Descriptor<3u,27u>, cmpt::ZouHePressureX<East>, Encode>
public:
using Descriptor = sch::Descriptor<3u,27u>;
private:
+ /**
+ * The flag has to mean the same thing here as it does in the D2Q9
+ * specialisation above, or the same call site picks a different wall
+ * depending on the descriptor.
+ *
+ * There, Dir == true reconstructs the populations with cx = +1, which are
+ * the unknowns at the x = 0 inlet. The body below is written for the
+ * opposite wall (unknowns with cx = -1, i.e. x = max), so the sense is
+ * flipped once here instead of at each branch.
+ *
+ * This used to be inverted, and since every example passes true for the
+ * inlet -- correct for D2Q9 -- the 3D cases drove the wrong face and
+ * diverged.
+ */
+ static constexpr bool AtXMax = not East;
+private:
kel::lbm::data<FP> rho_setting_;
public:
component(const kel::lbm::data<FP>& rho_setting__):
@@ -290,7 +306,7 @@ public:
kel::lbm::data<FP> S;
- if constexpr (East) {
+ if constexpr (AtXMax) {
S =
// cx = 0
@@ -347,10 +363,24 @@ public:
kel::lbm::data<FP> rho_ux;
- if constexpr (East) {
- rho_ux = rho_setting_ - S;
- } else {
+ /*
+ * With S = S0 + 2*S_known:
+ *
+ * x = max (unknown cx = -1):
+ * S_unknown = rho - S0 - S_known
+ * rho*ux = S_known - S_unknown = S - rho
+ *
+ * x = 0 (unknown cx = +1):
+ * rho*ux = S_unknown - S_known = rho - S
+ *
+ * Both of these were inverted, which drove the inlet and outlet the wrong
+ * way round and pumped mass into the domain every step. The D2Q9
+ * specialisation above already has the correct signs.
+ */
+ if constexpr (AtXMax) {
rho_ux = S - rho_setting_;
+ } else {
+ rho_ux = rho_setting_ - S;
}
@@ -378,7 +408,7 @@ public:
kel::lbm::data<FP> rho_uy;
kel::lbm::data<FP> rho_uz;
- if constexpr (East) {
+ if constexpr (AtXMax) {
rho_uy =
// cx = 0
@@ -506,7 +536,7 @@ public:
* ============================================================
*/
- if constexpr (East) {
+ if constexpr (AtXMax) {
/*
* --------------------------------------------------------
@@ -516,7 +546,7 @@ public:
f.at({1u}) =
f.at({2u})
- - kel::lbm::data<FP>{1.0 / 6.0} * rho_ux;
+ - kel::lbm::data<FP>{4.0 / 9.0} * rho_ux;
/*
@@ -624,7 +654,7 @@ public:
f.at({2u}) =
f.at({1u})
- + kel::lbm::data<FP>{1.0 / 6.0} * rho_ux;
+ + kel::lbm::data<FP>{4.0 / 9.0} * rho_ux;
/*
diff --git a/modules/core/c++/collision.hpp b/modules/core/c++/collision.hpp
index d3e70cb..bf83994 100644
--- a/modules/core/c++/collision.hpp
+++ b/modules/core/c++/collision.hpp
@@ -81,7 +81,7 @@ public:
auto& dfs_old_f = (is_even) ? field.template get<"dfs_old">() : field.template get<"dfs">();
auto& rho_f = macros.template get<"density">();
- auto& vel_f = macros.template get<"momentum">();
+ auto& vel_f = macros.template get<"velocity">();
kel::lbm::data<sch::Scalar<T>>& rho = rho_f.at(index);
kel::lbm::data<sch::Vector<T,Descriptor::D>>& vel = vel_f.at(index);
@@ -141,7 +141,7 @@ public:
auto& dfs = dfs_old_f.at(index);
auto& rho_f = macros.template get<"density">();
- auto& vel_f = macros.template get<"momentum">();
+ auto& vel_f = macros.template get<"velocity">();
kel::lbm::data<sch::Scalar<T>>& rho = rho_f.at(index);
diff --git a/modules/core/c++/component/psm.hpp b/modules/core/c++/component/psm.hpp
index e3ffa67..de71228 100644
--- a/modules/core/c++/component/psm.hpp
+++ b/modules/core/c++/component/psm.hpp
@@ -39,7 +39,7 @@ public:
auto& porous_f = macros.template get<"porosity">();
auto& rho_f = macros.template get<"density">();
- auto& vel_f = macros.template get<"momentum">();
+ auto& vel_f = macros.template get<"velocity">();
kel::lbm::data<sch::Scalar<T>>& rho = rho_f.at(index);
kel::lbm::data<sch::Vector<T,Descriptor::D>>& vel = vel_f.at(index);
diff --git a/modules/core/c++/converter.hpp b/modules/core/c++/converter.hpp
index 93c7617..a3c348d 100644
--- a/modules/core/c++/converter.hpp
+++ b/modules/core/c++/converter.hpp
@@ -19,7 +19,7 @@ private:
kel::lbm::data<typename kel::lbm::unit_division<sch::SiSecond<T>, sch::LbmSecond<T> >::Schema > second_conv_;
public:
converter() = delete;
- converter(
+ explicit converter(
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__
):
diff --git a/modules/core/c++/descriptor/d3q27.hpp b/modules/core/c++/descriptor/d3q27.hpp
index 9358852..4190f15 100644
--- a/modules/core/c++/descriptor/d3q27.hpp
+++ b/modules/core/c++/descriptor/d3q27.hpp
@@ -47,37 +47,49 @@ public:
{ 1, 1, 1} // 26
}};
+ /**
+ * D3Q27 weights, keyed on |e_i|^2:
+ *
+ * rest (|e|^2 = 0, 1 of them) 8/27
+ * face (|e|^2 = 1, 6 of them) 2/27
+ * edge (|e|^2 = 2, 12 of them) 1/54
+ * corner (|e|^2 = 3, 8 of them) 1/216
+ *
+ * These sum to 1. The six face weights used to read 1/36, which summed to
+ * 13/18 -- equilibrium then returned less mass than it was given and any
+ * 3D run diverged within a handful of steps.
+ */
static constexpr std::array<typename kel::lbm::native_data_type<T>::type,Q> weights = {
- 8./27.,
+ 8./27., // 0 rest
// 1D
- 1./36.,
- 1./36.,
- // 2D
- 1./36.,
- 1./54.,
- 1./54.,
- 1./36.,
- 1./54.,
- 1./54.,
- // 3D
- 1./36.,
- 1./54.,
- 1./54.,
- 1./54.,
- 1./216.,
- 1./216.,
- 1./54.,
- 1./216.,
- 1./216.,
- 1./36.,
- 1./54.,
- 1./54.,
- 1./54.,
- 1./216.,
- 1./216.,
- 1./54.,
- 1./216.,
- 1./216.
+ 2./27., // 1 face
+ 2./27., // 2 face
+ // Expand into 2D
+ 2./27., // 3 face
+ 1./54., // 4 edge
+ 1./54., // 5 edge
+ 2./27., // 6 face
+ 1./54., // 7 edge
+ 1./54., // 8 edge
+ // Expand into 3D
+ 2./27., // 9 face
+ 1./54., // 10 edge
+ 1./54., // 11 edge
+ 1./54., // 12 edge
+ 1./216., // 13 corner
+ 1./216., // 14 corner
+ 1./54., // 15 edge
+ 1./216., // 16 corner
+ 1./216., // 17 corner
+ 2./27., // 18 face
+ 1./54., // 19 edge
+ 1./54., // 20 edge
+ 1./54., // 21 edge
+ 1./216., // 22 corner
+ 1./216., // 23 corner
+ 1./54., // 24 edge
+ 1./216., // 25 corner
+ 1./216. // 26 corner
};
static constexpr std::array<uint64_t,Q> opposite_index = {
diff --git a/modules/core/c++/fplbm.hpp b/modules/core/c++/fplbm.hpp
index f961bc9..bc99da5 100644
--- a/modules/core/c++/fplbm.hpp
+++ b/modules/core/c++/fplbm.hpp
@@ -48,7 +48,7 @@ public:
auto& rho_f = macros.template get<"density">();
auto& rho = rho_f.at(index);
- auto& vel_f = macros.template get<"momentum">();
+ auto& vel_f = macros.template get<"velocity">();
auto& vel = vel_f.at(index);
compute_rho_momentum<T,Descriptor>(dfs,rho,vel);
@@ -96,7 +96,7 @@ public:
auto& force_f = macros.template get<"force">();
auto& force = force_f.at(index);
- auto& mom_f = macros.template get<"momentum">();
+ auto& mom_f = macros.template get<"velocity">();
auto& mom = mom_f.at(index);
// We already computed this in reset
@@ -144,13 +144,14 @@ class component<T, Descriptor, cmpt::FpLbmOneParticleGather, Encode> final {
public:
using Component = cmpt::FpLbmOneParticleGather;
private:
- kel::lbm::data<sch::Vector<T,Descriptor::D>> global_force_;
+ // An acceleration, as the comment above says -- now typed as one.
+ kel::lbm::data<sch::LbmAcceleration<sch::Vector<T,Descriptor::D>>> body_acceleration_;
public:
component():
- global_force_{}
+ body_acceleration_{}
{}
- component(kel::lbm::data<sch::Vector<T,Descriptor::D>> global_force__):
- global_force_{global_force__}
+ component(kel::lbm::data<sch::LbmAcceleration<sch::Vector<T,Descriptor::D>>> body_acceleration__):
+ body_acceleration_{body_acceleration__}
{}
template<typename CellFieldSchema, typename MacroFieldSchema, typename ParticleSchema>
@@ -162,7 +163,7 @@ public:
// auto& dfs = dfs_old_f.at(index);
auto& rho_f = macros.template get<"density">();
- auto& mom_f = macros.template get<"momentum">();
+ auto& mom_f = macros.template get<"velocity">();
auto& por_f = macros.template get<"porosity">();
auto& force_f = macros.template get<"force">();
@@ -177,9 +178,9 @@ public:
auto& pi = parts.at(index);
auto& pirb = pi.template get<"rigid_body">();
- auto& pirb_pos = pirb.template get<"position">();
- auto& pirb_pos_old = pirb.template get<"position_old">();
- auto& p_rad = pi.template get<"collision">().template get<"radius">();
+ auto& pirb_pos = pirb.template get<"position">().handle();
+ auto& pirb_pos_old = pirb.template get<"position_old">().handle();
+ auto& p_rad = pi.template get<"collision">().template get<"radius">().handle();
@@ -205,7 +206,7 @@ public:
auto vel_s = (pirb_pos-pirb_pos_old) * sss;
kel::lbm::data<sch::Vector<T,Descriptor::D>> force_p{{}};
- //= global_force_;
+ //= body_acceleration_;
iterator<Descriptor::D>::apply([&](const auto& index_f) -> void {
auto& force = force_f.at(index_f);
@@ -220,7 +221,7 @@ public:
// vel_s is technically time the density of the particle?
- // force = global_force_ * por + ( vel_s - mom) * two * flip_por;
+ // force = body_acceleration_ * por + ( vel_s - mom) * two * flip_por;
force = ( vel_s - mom) * two * flip_por;
// force = (vel_s - mom) * flip_por / (flip_por / two + one);
@@ -238,28 +239,30 @@ public:
/**
* The original fused one-particle step, kept so existing call sites keep
- * working. global_force_ is an acceleration, so it rides along as the
- * integrator's body acceleration.
+ * working. The body acceleration rides straight through to the integrator;
+ * it used to be called global_force_, which it never was -- the integrator
+ * takes an acceleration, not a force.
*/
template<typename T, typename Descriptor, typename Encode>
class component<T, Descriptor, cmpt::FpLbmOneParticle, Encode> final {
public:
using Component = cmpt::FpLbmOneParticle;
private:
- kel::lbm::data<sch::Vector<T,Descriptor::D>> global_force_;
+ // An acceleration, as the comment above says -- now typed as one.
+ kel::lbm::data<sch::LbmAcceleration<sch::Vector<T,Descriptor::D>>> body_acceleration_;
public:
component():
- global_force_{}
+ body_acceleration_{}
{}
- component(kel::lbm::data<sch::Vector<T,Descriptor::D>> global_force__):
- global_force_{global_force__}
+ component(kel::lbm::data<sch::LbmAcceleration<sch::Vector<T,Descriptor::D>>> body_acceleration__):
+ body_acceleration_{body_acceleration__}
{}
template<typename CellFieldSchema, typename MacroFieldSchema, typename ParticleSchema>
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 {
component<T,Descriptor,cmpt::ParticleForceReset,Encode> reset;
component<T,Descriptor,cmpt::FpLbmOneParticleGather,Encode> gather;
- component<T,Descriptor,cmpt::ParticleIntegrate,Encode> integrate{global_force_};
+ component<T,Descriptor,cmpt::ParticleIntegrate,Encode> integrate{body_acceleration_};
reset.apply(pg,index,time_step);
gather.apply(field,macros,pg,index,time_step,sub_steps);
diff --git a/modules/core/c++/hlbm.hpp b/modules/core/c++/hlbm.hpp
index acb2121..3bfdd6c 100644
--- a/modules/core/c++/hlbm.hpp
+++ b/modules/core/c++/hlbm.hpp
@@ -78,7 +78,7 @@ public:
auto& porosity_f = macros.template get<"porosity">();
auto& rho_f = macros.template get<"density">();
- auto& vel_f = macros.template get<"momentum">();
+ auto& vel_f = macros.template get<"velocity">();
kel::lbm::data<sch::Scalar<T>>& rho = rho_f.at(index);
kel::lbm::data<sch::Vector<T,Desc::D>>& vel = vel_f.at(index);
@@ -128,7 +128,7 @@ public:
auto& dfs_old_f = (is_even) ? field.template get<"dfs_old">() : field.template get<"dfs">();
auto& part_spheroid_group = part_group;
- auto& mvel_f = macros.template get<"momentum">();
+ auto& mvel_f = macros.template get<"velocity">();
auto& mrho_f = macros.template get<"density">();
auto& mpor_f = macros.template get<"porosity">();
{
@@ -136,9 +136,15 @@ public:
auto& pi = parts.at(index);
auto& pirb = pi.template get<"rigid_body">();
- auto& p_rad = pi.template get<"collision">().template get<"radius">();
- kel::lbm::data<sch::Vector<T,Desc::D>>& pirb_pos = pirb.template get<"position">();
- auto& pirb_pos_old = pirb.template get<"position_old">();
+ auto& p_rad = pi.template get<"collision">().template get<"radius">().handle();
+ /**
+ * Unwrapped once here. The unit is checked where the position is
+ * stored and assigned; inside the sweep it meets lattice
+ * coordinates and lattice directions, which carry no unit yet, so
+ * the kernel works on the raw vector.
+ */
+ auto& pirb_pos = pirb.template get<"position">().handle();
+ auto& pirb_pos_old = pirb.template get<"position_old">().handle();
// Matches cmpt::ParticleIntegrate: zero sub steps means one step.
uint64_t steps = sub_steps.get();
@@ -163,6 +169,16 @@ public:
for(uint64_t i{0u}; i < Desc::D; ++i){
force_p.at({{i}}) = 0.0;
}
+
+ /**
+ * Hydrodynamic torque about the body centre.
+ *
+ * Accumulated from the same per-cell momentum as force_p and with
+ * the same sign applied at the end, so the two cannot disagree
+ * about which way the reaction points.
+ */
+ kel::lbm::data<typename sch::impl::rotation_type_helper<T,Desc::D>::Schema> torque_p{};
+
auto vel_p_old = (pirb_pos-pirb_pos_old) / ts;
iterator<Desc::D>::apply([&](const auto& index_f) -> void{
@@ -203,18 +219,37 @@ public:
momentum = momentum + ei_dfs;
}
- // TODO technically needs to adjust for rotation as well
-
auto& rho = mrho_f.at(index_f);
(void) rho;
macros.template get<"force">().at(index_f) = momentum;
force_p = force_p + momentum;
+
+ /**
+ * r x f, with r the cell offset from the body centre already
+ * computed above. cross() returns a Scalar in 2D and a
+ * Vector3 in 3D, which is exactly the rotation type in each
+ * case, so one spelling covers both.
+ */
+ torque_p = torque_p + kel::lbm::math::cross<T>(rel_dist,momentum);
},start,stop);
// Accumulate, do not assign: contact adds to this before integration.
auto& pirb_force = pirb.template get<"force">();
pirb_force = pirb_force - force_p;
+
+ /**
+ * Same sign as the force above -- the per-cell momentum is what
+ * the fluid gained, so the body gets the negative of it.
+ *
+ * Gated: accumulating a torque no integrator will consume is a
+ * silent no-op, and in 3D only the fixed-axis integrator consumes
+ * it (see particle_fixed_axis_supported).
+ */
+ if constexpr ( particle_angular_supported<Desc::D> or particle_fixed_axis_supported<Desc::D> ){
+ auto& pirb_torque = pirb.template get<"torque">();
+ pirb_torque = pirb_torque - torque_p;
+ }
}
}
};
@@ -236,7 +271,7 @@ public:
kel::lbm::data<sch::Scalar<T>> one;
one.at({}) = 1.0;
- auto& mvel_f = macros.template get<"momentum">();
+ auto& mvel_f = macros.template get<"velocity">();
auto& mpor_f = macros.template get<"porosity">();
auto& particle_N_f = field.template get<"particle_N">();
auto& particle_D_f = field.template get<"particle_D">();
@@ -244,8 +279,8 @@ public:
auto parts = part_group.template get<"particles">();
auto& pi = parts.at(index);
auto& pirb = pi.template get<"rigid_body">();
- auto& pirb_pos = pirb.template get<"position">();
- auto& pirb_pos_old = pirb.template get<"position_old">();
+ auto& pirb_pos = pirb.template get<"position">().handle();
+ auto& pirb_pos_old = pirb.template get<"position_old">().handle();
uint64_t steps = sub_steps.get();
if(steps == 0u){
diff --git a/modules/core/c++/particle/aabb.hpp b/modules/core/c++/particle/aabb.hpp
index e207ad8..125232d 100644
--- a/modules/core/c++/particle/aabb.hpp
+++ b/modules/core/c++/particle/aabb.hpp
@@ -56,7 +56,7 @@ public:
auto& b = aabb.template get<"b">();
// Radius is per particle now, so a group can hold mixed sizes.
- const kel::lbm::data<sch::Scalar<T>>& rad_d = pi.template get<"collision">().template get<"radius">();
+ const kel::lbm::data<sch::Scalar<T>>& rad_d = pi.template get<"collision">().template get<"radius">().handle();
kel::lbm::data<sch::Vector<T,D>> lower;
kel::lbm::data<sch::Vector<T,D>> upper;
diff --git a/modules/core/c++/particle/contact.hpp b/modules/core/c++/particle/contact.hpp
index 857e116..cda4a01 100644
--- a/modules/core/c++/particle/contact.hpp
+++ b/modules/core/c++/particle/contact.hpp
@@ -269,7 +269,7 @@ contact_response<T,D> soft_shell_response(
* Velocity is implicit in position-Verlet, recovered from the position pair.
*/
template<typename T, uint64_t D, typename PRef>
-kel::lbm::data<sch::Vector<T,D>> surface_velocity(
+kel::lbm::data<sch::LbmVelocity<sch::Vector<T,D>>> surface_velocity(
const PRef& p,
const kel::lbm::data<sch::Vector<T,D>>& r,
typename kel::lbm::native_data_type<T>::type steps
@@ -304,7 +304,10 @@ kel::lbm::data<sch::Vector<T,D>> surface_velocity(
}
}
- return v;
+ // (position difference) * steps is a lattice velocity, and saying so is
+ // the whole point of the label. The force law downstream is still untyped,
+ // because there is no mass base unit yet.
+ return kel::lbm::as_unit<sch::LbmVelocity<sch::Vector<T,D>>>(v);
}
}
@@ -348,16 +351,16 @@ contact_response<T,D> particle_contact_response(
auto v_s = impl::surface_velocity<T,D>(self,r_s,steps);
auto v_o = impl::surface_velocity<T,D>(other,r_o,steps);
- kel::lbm::data<sch::Vector<T,D>> v_rel;
- for(uint64_t i{0u}; i < D; ++i){
- v_rel.at({{i}}).set(v_s.at({{i}}).get() - v_o.at({{i}}).get());
- }
+ // Velocity minus velocity is a velocity, checked rather than assumed.
+ auto v_rel = v_s - v_o;
auto m_s = self.template get<"rigid_body">().template get<"mass">().at({}).get();
auto m_o = other.template get<"rigid_body">().template get<"mass">().at({}).get();
auto m_eff = (m_s * m_o) / (m_s + m_o);
- return impl::soft_shell_response<T,D>(m,r_s,v_rel,m_eff,dem);
+ // Unwrapped here: the spring-dashpot produces a force, and force has no
+ // unit until there is a mass base unit.
+ return impl::soft_shell_response<T,D>(m,r_s,v_rel.handle(),m_eff,dem);
}
/**
@@ -390,7 +393,8 @@ contact_response<T,D> wall_contact_response(
auto m_s = self.template get<"rigid_body">().template get<"mass">().at({}).get();
- return impl::soft_shell_response<T,D>(m,r_s,v_rel,m_s,dem);
+ // Same boundary as the pair case: the force law is untyped.
+ return impl::soft_shell_response<T,D>(m,r_s,v_rel.handle(),m_s,dem);
}
/**
diff --git a/modules/core/c++/particle/couple.hpp b/modules/core/c++/particle/couple.hpp
index 19a276c..d882081 100644
--- a/modules/core/c++/particle/couple.hpp
+++ b/modules/core/c++/particle/couple.hpp
@@ -43,7 +43,7 @@ kel::lbm::data<sch::Scalar<T>> cell_porosity(
for_each_bin_candidate<T,D,CellCapacity>(cl,cell,[&](uint64_t p){
auto& pi = parts.at({p});
auto& pos = pi.template get<"rigid_body">().template get<"position">();
- auto rad = pi.template get<"collision">().template get<"radius">();
+ auto rad = pi.template get<"collision">().template get<"radius">().handle();
kel::lbm::data<sch::Vector<T,D>> rel;
for(uint64_t i{0u}; i < D; ++i){
diff --git a/modules/core/c++/particle/integrate.hpp b/modules/core/c++/particle/integrate.hpp
index a84cd37..1e85338 100644
--- a/modules/core/c++/particle/integrate.hpp
+++ b/modules/core/c++/particle/integrate.hpp
@@ -45,21 +45,29 @@ constexpr bool particle_angular_supported = (D == 2u);
template<typename T, uint64_t D>
void integrate_particle(
kel::lbm::data<sch::Particle<T,D>>& pi,
- const kel::lbm::data<sch::Vector<T,D>>& body_acceleration,
+ const kel::lbm::data<sch::LbmAcceleration<sch::Vector<T,D>>>& body_acceleration,
kel::lbm::data<sch::UInt64> sub_steps
){
auto& pirb = pi.template get<"rigid_body">();
const uint64_t steps = particle_sub_steps(sub_steps);
- kel::lbm::data<sch::Scalar<T>> ts;
+ // A sub step is a lattice time, not a bare number.
+ kel::lbm::data<sch::LbmSecond<sch::Scalar<T>>> ts;
ts.at({}).set(
typename kel::lbm::native_data_type<T>::type(1)
/ static_cast<typename kel::lbm::native_data_type<T>::type>(steps)
);
+ /**
+ * The seam between the typed and untyped halves. Force and mass carry no
+ * units yet -- there is no mass base unit -- so their quotient is a bare
+ * vector and the acceleration unit is attached here, deliberately and in
+ * one place, rather than being acquired silently at an assignment.
+ */
pirb.template get<"acceleration">() =
- pirb.template get<"force">() / pirb.template get<"mass">()
+ kel::lbm::data<sch::LbmAcceleration<sch::Vector<T,D>>>{
+ pirb.template get<"force">() / pirb.template get<"mass">()}
+ body_acceleration;
// See particle_angular_supported for why 3D is excluded rather than
@@ -75,6 +83,113 @@ void integrate_particle(
}
/**
+ * Whether rotation about a single FIXED axis can be integrated exactly.
+ *
+ * True in 3D as well as 2D, unlike particle_angular_supported. Constraining
+ * the body to one axis does not paper over the three problems listed there --
+ * it removes all of them:
+ *
+ * - Rotation composition only fails to commute when the axis moves. If the
+ * angular acceleration is always parallel to a fixed axis and the rotation
+ * starts parallel to it, the rotation vector stays parallel to it for all
+ * time, so verlet_step_lambda's component-wise update is exact rather than
+ * a small-angle approximation.
+ * - omega x (I omega) vanishes when omega lies along a principal axis. Every
+ * axis of a sphere is principal, and a rotor symmetric about its own axis
+ * has that axis principal. The term is genuinely zero, not neglected.
+ * - A scalar inertia is exactly the moment about that one axis.
+ *
+ * This is the wind turbine case: a body pinned in place, free to spin about
+ * one axis and nothing else.
+ */
+template<uint64_t D>
+constexpr bool particle_fixed_axis_supported = (D == 2u or D == 3u);
+
+namespace impl {
+/**
+ * The spin axis has the same schema as the rotation it drives: a signed scalar
+ * in 2D (there is only the out-of-plane direction), a unit vector in 3D.
+ */
+template<typename T, uint64_t D>
+using spin_axis_schema = typename sch::impl::rotation_type_helper<T,D>::Schema;
+
+template<typename T, uint64_t D>
+kel::lbm::data<spin_axis_schema<T,D>> normalise_spin_axis(
+ const kel::lbm::data<spin_axis_schema<T,D>>& axis
+){
+ if constexpr ( D == 2u ){
+ kel::lbm::data<spin_axis_schema<T,D>> out;
+ const auto a = axis.at({}).get();
+ out.at({}).set((a < 0) ? -1 : 1);
+ return out;
+ }else{
+ // math::normalize returns a zero vector unchanged rather than NaN, so
+ // a caller that forgets the axis gets a body that never spins instead
+ // of one that poisons the whole simulation.
+ return kel::lbm::math::normalize(axis);
+ }
+}
+}
+
+/**
+ * Projects the accumulated torque onto a fixed axis and advances the body
+ * about it, holding the position fixed.
+ *
+ * The position is pinned by zeroing the acceleration, not by writing the
+ * position back each step. Position-Verlet is x_new = 2x - x_old + a dt^2, so
+ * with x_old == x at construction and a == 0 the body stays exactly where it
+ * started, every step, bitwise, with no drift to correct for.
+ */
+template<typename T, uint64_t D>
+void integrate_particle_fixed_axis(
+ kel::lbm::data<sch::Particle<T,D>>& pi,
+ const kel::lbm::data<impl::spin_axis_schema<T,D>>& axis,
+ kel::lbm::data<sch::UInt64> sub_steps
+){
+ static_assert(particle_fixed_axis_supported<D>, "Fixed axis spin needs D == 2 or D == 3");
+
+ auto& pirb = pi.template get<"rigid_body">();
+
+ const uint64_t steps = particle_sub_steps(sub_steps);
+
+ // A sub step is a lattice time, not a bare number.
+ kel::lbm::data<sch::LbmSecond<sch::Scalar<T>>> ts;
+ ts.at({}).set(
+ typename kel::lbm::native_data_type<T>::type(1)
+ / static_cast<typename kel::lbm::native_data_type<T>::type>(steps)
+ );
+
+ // Pinned: the accumulated force is deliberately ignored.
+ auto& acc = pirb.template get<"acceleration">();
+ for(uint64_t i{0u}; i < D; ++i){
+ acc.at({{i}}).set(0);
+ }
+
+ auto& torque = pirb.template get<"torque">();
+ auto& inertia = pirb.template get<"inertia">();
+ auto& ang_acc = pirb.template get<"angular_acceleration">();
+
+ if constexpr ( D == 2u ){
+ ang_acc.at({}).set(
+ axis.at({}).get() * torque.at({}).get() / inertia.at({}).get()
+ );
+ }else{
+ // tau_axis = axis . torque, then alpha = axis * (tau_axis / I). Any
+ // torque component off the axis is reacted by the mounting and does
+ // not accelerate the rotor.
+ const auto tau_axis = kel::lbm::math::dot(axis,torque).at({}).get();
+ const auto alpha = tau_axis / inertia.at({}).get();
+ for(uint64_t i{0u}; i < 3u; ++i){
+ ang_acc.at({{i}}).set(axis.at({{i}}).get() * alpha);
+ }
+ }
+
+ for(uint64_t i{0u}; i < steps; ++i){
+ verlet_step_lambda<T,D>(pi,ts);
+ }
+}
+
+/**
* Clears the force/torque accumulators. Must run before any contributor.
*/
template<typename T, uint64_t D>
@@ -113,6 +228,16 @@ struct ParticleForceReset {};
* acceleration directly, so a second contributor silently overwrote the first.
*/
struct ParticleIntegrate {};
+
+/**
+ * Integrates a body pinned in place and free to spin about one fixed axis.
+ *
+ * The rotor case: the fluid torque projected onto the axis spins it, the
+ * position never moves, and angular velocity is an output. Unlike
+ * ParticleIntegrate this works in 3D -- see particle_fixed_axis_supported for
+ * why the constraint makes that exact rather than approximate.
+ */
+struct ParticleAxisIntegrate {};
}
template<typename T, typename Descriptor, typename Encode>
@@ -145,14 +270,14 @@ private:
* Body acceleration applied to every particle, e.g. gravity. Kept as an
* acceleration rather than a force so it does not need the mass.
*/
- kel::lbm::data<sch::Vector<T,Descriptor::D>> body_acceleration_;
+ kel::lbm::data<sch::LbmAcceleration<sch::Vector<T,Descriptor::D>>> body_acceleration_;
public:
component():
body_acceleration_{}
{}
- component(const kel::lbm::data<sch::Vector<T,Descriptor::D>>& body_acceleration__):
+ component(const kel::lbm::data<sch::LbmAcceleration<sch::Vector<T,Descriptor::D>>>& body_acceleration__):
body_acceleration_{body_acceleration__}
{}
@@ -170,5 +295,36 @@ public:
}
};
+template<typename T, typename Descriptor, typename Encode>
+class component<T, Descriptor, cmpt::ParticleAxisIntegrate, Encode> final {
+public:
+ using Component = cmpt::ParticleAxisIntegrate;
+
+private:
+ /**
+ * Normalised once here rather than per step, so the kernel never divides
+ * by a length and a caller cannot change the axis mid-run.
+ */
+ kel::lbm::data<impl::spin_axis_schema<T,Descriptor::D>> axis_;
+
+public:
+ component(const kel::lbm::data<impl::spin_axis_schema<T,Descriptor::D>>& axis__):
+ axis_{impl::normalise_spin_axis<T,Descriptor::D>(axis__)}
+ {}
+
+ template<typename ParticleSchema>
+ void apply(
+ 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) time_step;
+
+ auto& parts = pg.template get<"particles">();
+ integrate_particle_fixed_axis<T,Descriptor::D>(parts.at(index), axis_, sub_steps);
+ }
+};
+
}
}
diff --git a/modules/core/c++/particle/particle.hpp b/modules/core/c++/particle/particle.hpp
index 00e401a..4d96440 100644
--- a/modules/core/c++/particle/particle.hpp
+++ b/modules/core/c++/particle/particle.hpp
@@ -18,7 +18,7 @@ namespace lbm {
*/
template<typename T, uint64_t D,uint64_t PartAmount>
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::LbmMeter<sch::Scalar<T>>> radius_p,
kel::lbm::data<sch::Scalar<T>> density_p,
const kel::lbm::data<sch::UInt64>& mask_resolution
){
@@ -169,7 +169,7 @@ kel::lbm::data<sch::Particle<T,D, sch::ParticleCollisionSpheroid<T>>> create_sph
*/
template<typename T,uint64_t D>
-constexpr auto verlet_step_lambda = [](kel::lbm::data<sch::Particle<T,D>>& particle, kel::lbm::data<sch::Scalar<T>> time_step_delta){
+constexpr auto verlet_step_lambda = [](kel::lbm::data<sch::Particle<T,D>>& particle, kel::lbm::data<sch::LbmSecond<sch::Scalar<T>>> time_step_delta){
auto& body = particle.template get<"rigid_body">();
auto& pos = body.template get<"position">();
@@ -184,10 +184,13 @@ constexpr auto verlet_step_lambda = [](kel::lbm::data<sch::Particle<T,D>>& parti
auto tsd_squared = time_step_delta * time_step_delta;
- kel::lbm::data<sch::Vector<T,D>> pos_new;
+ kel::lbm::data<sch::LbmMeter<sch::Vector<T,D>>> pos_new;
// Actual step
- kel::lbm::data<sch::Scalar<T>> two;
+ // Dimensionless, and spelled as such: Pure is the claim, Scalar is only
+ // the shape.
+ kel::lbm::data<sch::Pure<sch::Scalar<T>>> two;
two.at({}).set(2.0);
+ // m + (m/s^2)*s^2 = m.
pos_new = pos * two - pos_old + pos_acc * tsd_squared;
// Swap - Could be std::swap? No, this is device code
@@ -196,7 +199,12 @@ constexpr auto verlet_step_lambda = [](kel::lbm::data<sch::Particle<T,D>>& parti
// Angular
kel::lbm::data<typename sch::impl::rotation_type_helper<T,D>::Schema> rot_new;
- rot_new = rot * two - rot_old + rot_acc * tsd_squared;
+ /**
+ * The angular half runs on raw values. Torque and inertia have no units
+ * yet (there is no mass base unit), so angular acceleration cannot be
+ * typed either, and the timestep has to be unwrapped to meet it.
+ */
+ rot_new = rot * two.handle() - rot_old + rot_acc * tsd_squared.handle();
rot_old = rot;
rot = rot_new;
@@ -240,7 +248,8 @@ template<typename T, uint64_t D, typename Collision = coll::Spheroid<T>>
constexpr auto broadphase_collision_distance_squared = []<typename PRef>(
const PRef& left,
const PRef& right
-) -> std::pair<bool,kel::lbm::data<sch::Scalar<T>>>{
+) -> std::pair<bool, kel::lbm::data<typename kel::lbm::unit_multiplication<
+ sch::LbmMeter<sch::Scalar<T>>, sch::LbmMeter<sch::Scalar<T>>>::Schema>>{
auto rad_l = left.template get<"collision">().template get<"radius">();
auto rad_r = right.template get<"collision">().template get<"radius">();
@@ -252,9 +261,10 @@ constexpr auto broadphase_collision_distance_squared = []<typename PRef>(
auto norm_2 = kel::lbm::math::dot(pos_dist,pos_dist);
- kel::lbm::data<sch::Scalar<T>> two;
+ // Dimensionless factor, so it has to say Pure.
+ kel::lbm::data<sch::Pure<sch::Scalar<T>>> two;
two.at({}) = 2.0;
- // (r_l + r_r)^2
+ // (r_l + r_r)^2 -- an area, matching the squared centre distance above.
auto rad_ab_2 = rad_l * rad_l + rad_r * rad_r + rad_r * rad_l * two;
return std::make_pair((norm_2.at({}).get() < rad_ab_2.at({}).get()), norm_2);
diff --git a/modules/core/c++/particle/porosity.hpp b/modules/core/c++/particle/porosity.hpp
index cd4e804..f393eb1 100644
--- a/modules/core/c++/particle/porosity.hpp
+++ b/modules/core/c++/particle/porosity.hpp
@@ -106,7 +106,7 @@ public:
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 = pi.template get<"collision">();
- const kel::lbm::data<sch::Scalar<T>>& rad_d = coll.template get<"radius">();
+ const kel::lbm::data<sch::Scalar<T>>& rad_d = coll.template get<"radius">().handle();
const auto& eps = part_group.template get<"epsilon">().at({});
// Move this somewhere
diff --git a/modules/core/c++/particle/schema.hpp b/modules/core/c++/particle/schema.hpp
index 39e1a36..b0a6f5d 100644
--- a/modules/core/c++/particle/schema.hpp
+++ b/modules/core/c++/particle/schema.hpp
@@ -2,6 +2,8 @@
#include "common.hpp"
+#include "../lbm_unit.hpp"
+
namespace kel {
namespace lbm {
@@ -10,7 +12,8 @@ template<typename T>
struct Spheroid {
using ValueSchema = T;
using Schema = sch::Struct<
- sch::Member<sch::Scalar<ValueSchema>,"radius">
+ // A radius is a lattice length, like the position it is compared against.
+ sch::Member<sch::LbmMeter<sch::Scalar<ValueSchema>>,"radius">
>;
};
}
@@ -47,12 +50,23 @@ struct inertia_type_helper {
template<typename T, uint64_t D>
using ParticleRigidBody = Struct<
- Member<Vector<T,D>, "position">,
- Member<Vector<T,D>, "position_old">,
+ /**
+ * Lattice length. The unit sits on the vector rather than on its
+ * components: a position is metres in every direction, and the component
+ * type is what the kernels index.
+ */
+ Member<LbmMeter<Vector<T,D>>, "position">,
+ Member<LbmMeter<Vector<T,D>>, "position_old">,
Member<typename impl::rotation_type_helper<T,D>::Schema, "rotation">,
Member<typename impl::rotation_type_helper<T,D>::Schema, "rotation_old">,
- Member<Vector<T,D>, "acceleration">,
+ /**
+ * Lattice acceleration. Typed because the Verlet update adds
+ * acceleration * dt^2 to a position and so must come out in metres.
+ * It is also where the typed and untyped halves meet: force and mass have
+ * no units yet, so integrate_particle attaches this one explicitly.
+ */
+ Member<LbmAcceleration<Vector<T,D>>, "acceleration">,
Member<typename impl::rotation_type_helper<T,D>::Schema, "angular_acceleration">,
/**
diff --git a/modules/core/c++/psm.hpp b/modules/core/c++/psm.hpp
index b540f38..7f43e2d 100644
--- a/modules/core/c++/psm.hpp
+++ b/modules/core/c++/psm.hpp
@@ -65,7 +65,7 @@ public:
auto& porous_f = macros.template get<"porosity">();
auto& rho_f = macros.template get<"density">();
- auto& vel_f = macros.template get<"momentum">();
+ auto& vel_f = macros.template get<"velocity">();
kel::lbm::data<sch::Scalar<T>>& rho = rho_f.at(index);
kel::lbm::data<sch::Vector<T,Descriptor::D>>& vel = vel_f.at(index);
@@ -125,7 +125,7 @@ void apply(
auto& por_f = macros.template get<"porosity">();
auto& rho_f = macros.template get<"density">();
- auto& vel_f = macros.template get<"momentum">();
+ auto& vel_f = macros.template get<"velocity">();
auto& force_f = macros.template get<"force">();
kel::lbm::data<sch::Scalar<T>> one;
@@ -145,16 +145,20 @@ void apply(
auto& pi = parts.at(index);
auto& p_rad =
- pi.template get<"collision">().template get<"radius">();
+ pi.template get<"collision">().template get<"radius">().handle();
auto& pirb =
pi.template get<"rigid_body">();
- kel::lbm::data<sch::Vector<T,Descriptor::D>>& pirb_pos =
- pirb.template get<"position">();
+ /**
+ * Unwrapped once here. The unit is checked where the position is
+ * stored and assigned; inside the sweep it meets lattice coordinates
+ * and lattice directions, which carry no unit yet, so the kernel
+ * works on the raw vector.
+ */
+ auto& pirb_pos = pirb.template get<"position">().handle();
- auto& pirb_pos_old =
- pirb.template get<"position_old">();
+ auto& pirb_pos_old = pirb.template get<"position_old">().handle();
/*