src/analysis/spectrum.cpp
| Line | Branch | Exec | Source |
|---|---|---|---|
| 1 | // SPDX-License-Identifier: BSD-3-Clause | ||
| 2 | |||
| 3 | #include "terraingen/analysis/spectrum.h" | ||
| 4 | |||
| 5 | #include "analysis/radial_spectrum.h" | ||
| 6 | #include "terraingen/geometry/plane_fit.h" | ||
| 7 | #include "terraingen/raster/cell_loops.h" | ||
| 8 | #include "terraingen/raster/geo_transform.h" | ||
| 9 | #include "terraingen/raster/grid.h" | ||
| 10 | #include "terraingen/util/bits.h" | ||
| 11 | #include "util/checks.h" | ||
| 12 | #include "util/fft.h" | ||
| 13 | |||
| 14 | #include <algorithm> | ||
| 15 | #include <array> | ||
| 16 | #include <cmath> | ||
| 17 | #include <complex> | ||
| 18 | #include <limits> | ||
| 19 | #include <stdexcept> | ||
| 20 | #include <utility> | ||
| 21 | |||
| 22 | namespace terraingen { | ||
| 23 | |||
| 24 | namespace { | ||
| 25 | |||
| 26 | constexpr double kBinsPerOctave = 4.0; | ||
| 27 | constexpr std::size_t kMinWindow = 8; | ||
| 28 | constexpr std::size_t kMinFitBins = 3; | ||
| 29 | constexpr double kMinSlope = 2.0; | ||
| 30 | constexpr double kMaxSlope = 4.0; | ||
| 31 | constexpr double kFlatSlope = 3.0; | ||
| 32 | |||
| 33 | 84 | std::size_t FloorPowerOfTwo(std::size_t n) { | |
| 34 | 84 | std::size_t power = 1; | |
| 35 | 684 | while (power * 2 <= n) { | |
| 36 | power *= 2; | ||
| 37 | } | ||
| 38 | 84 | return power; | |
| 39 | } | ||
| 40 | |||
| 41 | /// The integral of f^(1 - `slope`) over the octave from `nyquist` to twice it. | ||
| 42 | 35094 | double OctaveIntegral(double slope, double nyquist) { | |
| 43 | 35094 | const double exponent = 2.0 - slope; | |
| 44 | 35094 | if (std::fabs(exponent) < 1e-9) { | |
| 45 | return std::log(2.0); | ||
| 46 | } | ||
| 47 | 35092 | return std::pow(nyquist, exponent) * (std::pow(2.0, exponent) - 1.0) / exponent; | |
| 48 | } | ||
| 49 | |||
| 50 | /// The Hann window over `n` samples at sample `i`. | ||
| 51 | 4125784 | double Hann(std::size_t i, std::size_t n) { | |
| 52 | 4125784 | return 0.5 - | |
| 53 | 4125784 | 0.5 * std::cos(2.0 * kPi * (static_cast<double>(i) + 0.5) / static_cast<double>(n)); | |
| 54 | } | ||
| 55 | |||
| 56 | /// The centered power-of-2 window of a raster. | ||
| 57 | 43 | PixelWindow CenteredWindow(const Raster<float>& heights) { | |
| 58 | 43 | if (heights.Width() < kMinWindow || heights.Height() < kMinWindow) { | |
| 59 | 1 | throw std::invalid_argument("A power spectrum needs a raster at least 8 cells a side"); | |
| 60 | } | ||
| 61 | 42 | const std::size_t width = FloorPowerOfTwo(heights.Width()); | |
| 62 | 42 | const std::size_t height = FloorPowerOfTwo(heights.Height()); | |
| 63 | 42 | const std::size_t col0 = (heights.Width() - width) / 2; | |
| 64 | 42 | const std::size_t row0 = (heights.Height() - height) / 2; | |
| 65 | 42 | return {col0, col0 + width, row0, row0 + height}; | |
| 66 | } | ||
| 67 | |||
| 68 | /// The offset of cell `i` of `n` from their center, in cells. | ||
| 69 | 8228848 | double Centered(std::size_t i, std::size_t n) { | |
| 70 | 8228848 | return static_cast<double>(i) - 0.5 * static_cast<double>(n - 1); | |
| 71 | } | ||
| 72 | |||
| 73 | /// The least-squares plane through the cells of `window` holding data, in cells from the | ||
| 74 | /// window's center. | ||
| 75 | /// @throws std::invalid_argument for a window without data. | ||
| 76 | 25 | Plane FitPlane(const Raster<float>& heights, const PixelWindow& window) { | |
| 77 | 25 | PlaneFit fit; | |
| 78 | 11410 | for (std::size_t row = 0; row < window.Height(); ++row) { | |
| 79 | 4126304 | for (std::size_t col = 0; col < window.Width(); ++col) { | |
| 80 | 2057472 | const float value = heights(window.colBegin + col, window.rowBegin + row); | |
| 81 | 2057472 | if (!heights.IsMissing(value)) { | |
| 82 | 4114424 | fit.Add(Centered(col, window.Width()), Centered(row, window.Height()), | |
| 83 | static_cast<double>(value)); | ||
| 84 | } | ||
| 85 | } | ||
| 86 | } | ||
| 87 | 25 | if (fit.Empty()) { | |
| 88 | 1 | throw std::invalid_argument("A power spectrum needs cells with data"); | |
| 89 | } | ||
| 90 | 24 | return fit.Solve(); | |
| 91 | } | ||
| 92 | |||
| 93 | /// The window's heights minus their plane, zero without data, times the 2D Hann window; and the | ||
| 94 | /// window's summed squared weights. | ||
| 95 | 25 | std::pair<std::vector<std::complex<double>>, double> TaperedWindow(const Raster<float>& heights, | |
| 96 | const PixelWindow& window) { | ||
| 97 | 25 | const Plane plane = FitPlane(heights, window); | |
| 98 | 72 | std::vector<std::complex<double>> values(window.Width() * window.Height()); | |
| 99 | 24 | double energyX = 0.0; | |
| 100 | 24 | double energyY = 0.0; | |
| 101 | 11440 | for (std::size_t col = 0; col < window.Width(); ++col) { | |
| 102 | 5696 | energyX += Hann(col, window.Width()) * Hann(col, window.Width()); | |
| 103 | } | ||
| 104 | 11376 | for (std::size_t row = 0; row < window.Height(); ++row) { | |
| 105 | 5664 | energyY += Hann(row, window.Height()) * Hann(row, window.Height()); | |
| 106 | 4125760 | for (std::size_t col = 0; col < window.Width(); ++col) { | |
| 107 | 2057216 | const float value = heights(window.colBegin + col, window.rowBegin + row); | |
| 108 | 2057216 | if (heights.IsMissing(value)) { | |
| 109 | 4 | continue; | |
| 110 | } | ||
| 111 | 2057212 | const double trend = plane.a + plane.b * Centered(col, window.Width()) + | |
| 112 | 2057212 | plane.c * Centered(row, window.Height()); | |
| 113 | 2057212 | values[row * window.Width() + col] = (static_cast<double>(value) - trend) * | |
| 114 | 2057212 | Hann(col, window.Width()) * | |
| 115 | 2057212 | Hann(row, window.Height()); | |
| 116 | } | ||
| 117 | } | ||
| 118 | 24 | return {std::move(values), energyX * energyY}; | |
| 119 | 24 | } | |
| 120 | |||
| 121 | /// The signed frequency index of FFT bin `k` of `n`. | ||
| 122 | 2062880 | double SignedIndex(std::size_t k, std::size_t n) { | |
| 123 | 2062880 | return k <= n / 2 ? static_cast<double>(k) : static_cast<double>(k) - static_cast<double>(n); | |
| 124 | } | ||
| 125 | |||
| 126 | /// A line fitted to log power over log frequency. | ||
| 127 | struct LogLine { | ||
| 128 | double gradient = 0.0; | ||
| 129 | double meanX = 0.0; ///< Weighted mean log frequency. | ||
| 130 | double meanY = 0.0; ///< Weighted mean log power. | ||
| 131 | }; | ||
| 132 | |||
| 133 | /// The least-squares line through log power over log frequency of `bins`, each weighted by its | ||
| 134 | /// frequency samples, as the variance of its mean falls with their number. | ||
| 135 | 15 | LogLine FitLogLine(const std::vector<SpectrumBin>& bins) { | |
| 136 | 15 | const double floor = std::numeric_limits<double>::min(); | |
| 137 | 15 | double weights = 0.0; | |
| 138 | 15 | LogLine line; | |
| 139 | 197 | for (const SpectrumBin& bin : bins) { | |
| 140 | 182 | const auto weight = static_cast<double>(bin.count); | |
| 141 | 182 | weights += weight; | |
| 142 | 182 | line.meanX += weight * std::log(bin.frequency); | |
| 143 | 182 | line.meanY += weight * std::log(std::max(bin.power, floor)); | |
| 144 | } | ||
| 145 | 15 | line.meanX /= weights; | |
| 146 | 15 | line.meanY /= weights; | |
| 147 | 15 | double sxx = 0.0; | |
| 148 | 15 | double sxy = 0.0; | |
| 149 | 197 | for (const SpectrumBin& bin : bins) { | |
| 150 | 182 | const auto weight = static_cast<double>(bin.count); | |
| 151 | 182 | const double x = std::log(bin.frequency) - line.meanX; | |
| 152 | 182 | sxx += weight * x * x; | |
| 153 | 182 | sxy += weight * x * (std::log(std::max(bin.power, floor)) - line.meanY); | |
| 154 | } | ||
| 155 | 15 | line.gradient = sxy / sxx; | |
| 156 | 15 | return line; | |
| 157 | } | ||
| 158 | |||
| 159 | } // namespace | ||
| 160 | |||
| 161 | 35079 | double PowerLawSpectrum::Coefficient(double nyquist) const { | |
| 162 | 35079 | return octaveRms * octaveRms / (2.0 * kPi * OctaveIntegral(slope, nyquist)); | |
| 163 | } | ||
| 164 | |||
| 165 | 27 | std::vector<SpectrumBin> RadialPowerSpectrum(const Raster<float>& heights) { | |
| 166 | 27 | const GeoTransform& transform = heights.Transform(); | |
| 167 | 27 | if (transform.IsRotated()) { | |
| 168 | 1 | throw std::invalid_argument("A power spectrum needs an unrotated raster"); | |
| 169 | } | ||
| 170 | 26 | const PixelWindow window = CenteredWindow(heights); | |
| 171 | 25 | auto [values, energy] = TaperedWindow(heights, window); | |
| 172 | 72 | Fft2(values, window.Width(), window.Height(), -1.0); | |
| 173 | 24 | const double dx = std::fabs(transform.pixelWidth); | |
| 174 | 24 | const double dy = std::fabs(transform.pixelHeight); | |
| 175 | 48 | const double fundamental = 1.0 / std::max(static_cast<double>(window.Width()) * dx, | |
| 176 | 24 | static_cast<double>(window.Height()) * dy); | |
| 177 | 24 | const double nyquist = 0.5 / std::max(dx, dy); | |
| 178 | 24 | const auto bins = static_cast<std::size_t>( | |
| 179 | 24 | std::floor(kBinsPerOctave * std::log2(nyquist / fundamental) + 1e-9) + 1.0); | |
| 180 | 24 | std::vector<SpectrumBin> sums(bins); | |
| 181 | 24 | const double scale = dx * dy / energy; | |
| 182 | 5688 | for (std::size_t v = 0; v < window.Height(); ++v) { | |
| 183 | 5664 | const double fy = | |
| 184 | 5664 | SignedIndex(v, window.Height()) / (static_cast<double>(window.Height()) * dy); | |
| 185 | 2062880 | for (std::size_t u = 0; u < window.Width(); ++u) { | |
| 186 | 2057216 | const double fx = | |
| 187 | 2057216 | SignedIndex(u, window.Width()) / (static_cast<double>(window.Width()) * dx); | |
| 188 | 2057216 | const double f = std::hypot(fx, fy); | |
| 189 | 2057216 | if (f == 0.0 || f > nyquist * (1.0 + 1e-12)) { | |
| 190 | 442076 | continue; | |
| 191 | } | ||
| 192 | 1615140 | const auto bin = static_cast<std::size_t>( | |
| 193 | 3230280 | std::clamp(std::floor(kBinsPerOctave * std::log2(f / fundamental) + 1e-9), 0.0, | |
| 194 | 1615140 | static_cast<double>(bins - 1))); | |
| 195 | 1615140 | sums[bin].frequency += f; | |
| 196 | 1615140 | sums[bin].power += std::norm(values[v * window.Width() + u]) * scale; | |
| 197 | 1615140 | ++sums[bin].count; | |
| 198 | } | ||
| 199 | } | ||
| 200 | 24 | std::vector<SpectrumBin> spectrum; | |
| 201 | 668 | for (SpectrumBin& bin : sums) { | |
| 202 | 644 | if (bin.count > 0) { | |
| 203 | 570 | bin.frequency /= static_cast<double>(bin.count); | |
| 204 | 570 | bin.power /= static_cast<double>(bin.count); | |
| 205 | 570 | spectrum.push_back(bin); | |
| 206 | } | ||
| 207 | } | ||
| 208 | 48 | return spectrum; | |
| 209 | 24 | } | |
| 210 | |||
| 211 | 26 | void ValidateSpectrumFitBand(const SpectrumFitBand& band) { | |
| 212 | 26 | RequireFinite(band.minPixels, "Spectrum fit min pixels"); | |
| 213 | 26 | if (band.minPixels < 2.0) { | |
| 214 | 2 | throw std::invalid_argument("Spectrum fit min pixels must be at least 2"); | |
| 215 | } | ||
| 216 | 24 | RequireFinite(band.maxPixels, "Spectrum fit max pixels"); | |
| 217 | 24 | if (band.maxPixels != 0.0 && !(band.maxPixels > band.minPixels)) { | |
| 218 | 2 | throw std::invalid_argument("Spectrum fit max pixels must be 0 or above min pixels"); | |
| 219 | } | ||
| 220 | 22 | } | |
| 221 | |||
| 222 | 17 | PowerLawSpectrum EstimatePowerLawSpectrum(const Raster<float>& heights, | |
| 223 | const SpectrumFitBand& band) { | ||
| 224 | 17 | ValidateSpectrumFitBand(band); | |
| 225 | 17 | const double pixel = heights.Grid().PixelSize(); | |
| 226 | 17 | const PixelWindow window = CenteredWindow(heights); | |
| 227 | 17 | const double maxPixels = | |
| 228 | 17 | band.maxPixels > 0.0 | |
| 229 | 17 | ? band.maxPixels | |
| 230 | 26 | : 0.25 * static_cast<double>(std::min(window.Width(), window.Height())); | |
| 231 | 17 | const double low = 1.0 / (maxPixels * pixel) * (1.0 - 1e-9); | |
| 232 | 17 | const double high = 1.0 / (band.minPixels * pixel) * (1.0 + 1e-9); | |
| 233 | 17 | std::vector<SpectrumBin> bins; | |
| 234 | 389 | for (const SpectrumBin& bin : RadialPowerSpectrum(heights)) { | |
| 235 | 372 | if (bin.frequency >= low && bin.frequency <= high) { | |
| 236 | 191 | bins.push_back(bin); | |
| 237 | } | ||
| 238 | 17 | } | |
| 239 | 17 | if (bins.size() < kMinFitBins) { | |
| 240 | 1 | throw std::invalid_argument("A power-law fit needs at least 3 spectrum bins in its band"); | |
| 241 | } | ||
| 242 | 16 | PowerLawSpectrum fit; | |
| 243 | 16 | const bool relief = std::any_of(bins.begin(), bins.end(), | |
| 244 | 17 | [](const SpectrumBin& bin) { return bin.power > 0.0; }); | |
| 245 | 16 | if (!relief) { | |
| 246 | fit.slope = kFlatSlope; | ||
| 247 | return fit; | ||
| 248 | } | ||
| 249 | 15 | const LogLine line = FitLogLine(bins); | |
| 250 | 15 | fit.slope = std::clamp(-line.gradient, kMinSlope, kMaxSlope); | |
| 251 | 15 | fit.clipped = fit.slope != -line.gradient; | |
| 252 | 15 | const double logCoefficient = line.meanY + fit.slope * line.meanX; | |
| 253 | 30 | fit.octaveRms = | |
| 254 | 15 | std::sqrt(2.0 * kPi * std::exp(logCoefficient) * OctaveIntegral(fit.slope, 0.5 / pixel)); | |
| 255 | 15 | return fit; | |
| 256 | 17 | } | |
| 257 | |||
| 258 | } // namespace terraingen | ||
| 259 |