feat: add tanh transition curve particle parameter change algorithm

This commit is contained in:
dvdrw 2024-11-25 13:58:02 +01:00
parent cf19cc7183
commit 2b20e90a08
Signed by: dvdrw
GPG Key ID: 3ED4E5A371C20DD7

View File

@ -1,5 +1,6 @@
#pragma once #pragma once
#include <cmath>
#include <cstddef> #include <cstddef>
#include <functional> #include <functional>
@ -45,15 +46,38 @@ namespace ParamChange {
}; };
} }
}; };
template<auto steepness = 3>
struct MTanhAlg {
vec<3> operator()(
float visc, float nostal, float peerp, int curr, int max) {
float pct_done = (float)curr / (float)max;
float scale_factor = (std::tanh(steepness * (pct_done - 0.5)) + 1) / 2;
return {
visc - (0.9f - 0.4f) * scale_factor,
nostal - (2.5f - 0.5f) * scale_factor,
peerp + (2.5f - 0.5f) * scale_factor,
};
}
};
}; };
template<std::size_t N, ParameterChangeAlgorithm A = ParamChange::MLinAlg> template<std::size_t N, ParameterChangeAlgorithm A = ParamChange::MTanhAlg<>>
struct Particle : public Agent<vec<N>> { struct Particle : public Agent<vec<N>> {
std::pair<float, vec<N>> best() const override { return {pb, pb_pos}; }; std::pair<float, vec<N>> best() const override { return {pb, pb_pos}; };
void move(float dt=1) override { position = position + velocity * dt; } void move(float dt=1) override { position = position + velocity * dt; }
void step() override { void step() override {
vec<3> params = alg(kviscosity, knostalgia, kpeer_pressure,
curr_iter, max_iter);
viscosity = params.x;
nostalgia = params.y;
peer_pressure = params.z;
curr_iter++;
velocity = viscosity * velocity velocity = viscosity * velocity
+ nostalgia * (pb_pos - position) + nostalgia * (pb_pos - position)
+ peer_pressure * (peer.best().second - position); + peer_pressure * (peer.best().second - position);
@ -63,15 +87,6 @@ struct Particle : public Agent<vec<N>> {
pb = y; pb = y;
pb_pos = position; pb_pos = position;
} }
vec<3> params = alg(kviscosity, knostalgia, kpeer_pressure,
curr_iter, max_iter);
viscosity = params.x;
nostalgia = params.y;
peer_pressure = params.z;
curr_iter++;
}; };
const float kviscosity = 0.9f; const float kviscosity = 0.9f;
@ -146,7 +161,7 @@ struct Swarm : public Agent<vec<N>> {
const std::vector<Particle<N>>& get_particles() { return particles; }; const std::vector<Particle<N>>& get_particles() { return particles; };
Swarm(Agent<vec<N>>::F f, unsigned max_iter = 150) Swarm(Agent<vec<N>>::F f, unsigned max_iter)
: Agent<vec<N>>(f), max_iter(max_iter) {} : Agent<vec<N>>(f), max_iter(max_iter) {}
private: private:
unsigned max_iter; unsigned max_iter;