はじめに
2D関数は、入力が2D空間内の点で、出力が1Dの値である関数のことをここでは言います。このような関数を視覚的に理解するためにヒートマップを使用することができます。OpenSiv3Dを活用すれば、最適化のプロセスを含む多岐にわたる用途で利用可能です。
#include <Siv3D.hpp>
struct FunctionImage {
const double resolution;
const Vec2 rangeStart;
const Vec2 rangeEnd;
const Image image;
const Texture texture;
FunctionImage(std::function<double(const Vec2&)> func, double res, Vec2 start, Vec2 end, double minValue = 0.0, double maxValue = 1.0, ColormapType colormapType = ColormapType::Gray)
: resolution(res), rangeStart(start), rangeEnd(end), image(createImage(func, res, start, end, minValue, maxValue, colormapType)), texture(image) {}
void draw() const {
texture.scaled(resolution).drawAt((rangeStart + rangeEnd) / 2);
}
private:
Image createImage(std::function<double(const Vec2&)> func, double res, Vec2 start, Vec2 end, double minValue, double maxValue, ColormapType colormapType) const {
const int width = static_cast<int>((end.x - start.x) / res);
const int height = static_cast<int>((end.y - start.y) / res);
Image img(width, height);
for (int y = 0; y < height; ++y) {
for (int x = 0; x < width; ++x) {
double value = func(Vec2(x * res + start.x, y * res + start.y));
const double mappedValue = mapValue(value, minValue, maxValue, 0.0, 1.0);
img[y][x] = Colormap01(mappedValue, colormapType);
}
}
return img;
}
double mapValue(double x, double in_min, double in_max, double out_min, double out_max) const {
return (x - in_min) * (out_max - out_min) / (in_max - in_min) + out_min;
}
};
void Main() {
constexpr double resolution = 0.1;
constexpr Vec2 rangeStart(-10, -10);
constexpr Vec2 rangeEnd(10.0, 10.0);
const std::function<double(const Vec2&)> func = [](const Vec2& pos) {
return (std::sin(pos.x) + std::cos(pos.y)) / 2.0 + 0.5;
};
const FunctionImage funcImage(func, resolution, rangeStart, rangeEnd, -1.0, 2.0);
Camera2D camera((rangeStart + rangeEnd) / 2, 100.0);
while (System::Update()) {
camera.update();
{
const auto t = camera.createTransformer();
funcImage.draw();
}
}
}
2D関数とヒートマップ
2D関数の定義
- 2D関数: 入力が2次元の座標、出力が1次元の値。
- 例: ( z = f(x, y) )
ヒートマップの利用
- ヒートマップ: 2D関数の値を色で表現。
- 色の対応: 出力値と色の間のマッピング(例: 高い値→赤、低い値→青)。
面白い使用方法
- 教育的ツール: 関数の地形を視覚化して理解を深める。
- リアルタイム最適化: ヒートマップ上で最適化プロセスのリアルタイム追跡。
結論
2D関数とヒートマップの組み合わせは、関数の挙動を直感的に理解し、最適化などのプロセスを視覚化する強力な手法です。OpenSiv3Dを使用すると、このプロセスを容易に実装し、多岐にわたるアプリケーションで使用することができます。