From 78940602a8b496af86255b46c5d2973b08f05e3e Mon Sep 17 00:00:00 2001 From: "Mark A. Tsuchida" Date: Fri, 25 Sep 2026 16:45:01 -0500 Subject: [PATCH 1/3] Fix gaussian blur issues MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - q() now returns F instead of float. - ForwardFilter / BackwardFilter are rewritten with index loops, so they no longer create pointers outside the array. The existing tests for them, including the nullptr, 0 cases, pass unchanged. - DirectGaussian2D is new in gaussian_internal. It blurs rows then columns with a sampled Gaussian kernel that reaches out to max(1, ceil(3σ)) and is scaled to sum to 1. Edge pixels are repeated at the borders, and a single line buffer is reused. - FastGaussian2D: - It returns early unless sigma > 0. - It uses DirectGaussian2D when sigma < 1, with a rationale comment. - Otherwise it goes to SIMD or scalar, now using #else. - New tests: - DirectGaussian2D at σ=0.7: a single-pixel spike blurs to a total of ≈1, the result is mirror- and diagonal-symmetric, the center value equals w0², and a constant image stays constant. - FastGaussian2D-small-sigma for σ ∈ {0.1, 0.3, 0.7}: no negative values, a total of ≈1, and a constant image stays constant. (Assisted by Claude Code; any errors are mine.) --- Gaussian2DFilter.cpp | 14 ++++++-- Gaussian2DFilter.h | 72 +++++++++++++++++++++++++++++----------- test_SimulatedCamera.cpp | 65 ++++++++++++++++++++++++++++++++++++ 3 files changed, 130 insertions(+), 21 deletions(-) diff --git a/Gaussian2DFilter.cpp b/Gaussian2DFilter.cpp index 1a69fb0..26c58f5 100644 --- a/Gaussian2DFilter.cpp +++ b/Gaussian2DFilter.cpp @@ -248,10 +248,20 @@ void FastGaussian2DSIMD(float *data, std::size_t width, std::size_t height, // Entry point void FastGaussian2D(float *data, std::size_t width, std::size_t height, float sigma) { + if (!(sigma > 0.0f)) + return; + // Recursive coefficients (Eq 11b) are valid only for sigma >= 0.5 and + // inaccurate near that bound; direct convolution is cheap for such small + // kernels. + if (sigma < 1.0f) { + gaussian_internal::DirectGaussian2D(data, width, height, sigma); + return; + } #ifdef USE_HIGHWAY_SIMD - return gaussian_internal::FastGaussian2DSIMD(data, width, height, sigma); -#endif + gaussian_internal::FastGaussian2DSIMD(data, width, height, sigma); +#else gaussian_internal::FastGaussian2DScalar(data, width, height, sigma); +#endif } #endif diff --git a/Gaussian2DFilter.h b/Gaussian2DFilter.h index 11476b8..ecf4989 100644 --- a/Gaussian2DFilter.h +++ b/Gaussian2DFilter.h @@ -1,9 +1,11 @@ #pragma once +#include #include #include #include #include +#include void FastGaussian2D(float *data, std::size_t width, std::size_t height, float sigma); @@ -11,7 +13,7 @@ void FastGaussian2D(float *data, std::size_t width, std::size_t height, namespace gaussian_internal { // Eq 11b -template inline float q(F sigma) { +template inline F q(F sigma) { assert(sigma > F(0.0)); // Note: This function, as given in the paper, is not continuous at sigma = @@ -58,24 +60,20 @@ template inline F B(std::array bp) { template inline void ForwardFilter(F *data, std::size_t size, F B, std::array bp, std::size_t stride = Stride) { - const auto s = Stride > 0 ? Stride : stride; - F *const pend = data + size * s; - F *p = data; if (size < 1) return; - F cur = *p; + const auto s = Stride > 0 ? Stride : stride; + F cur = data[0]; // Replicate the 3 pixels outside the border. F prev1 = cur; F prev2 = cur; F prev3 = cur; - p += s; - for (; p < pend; p += s) { + for (std::size_t k = 1; k < size; ++k) { prev3 = prev2; prev2 = prev1; prev1 = cur; - cur = *p; - cur = B * cur + bp[0] * prev1 + bp[1] * prev2 + bp[2] * prev3; - *p = cur; + cur = B * data[k * s] + bp[0] * prev1 + bp[1] * prev2 + bp[2] * prev3; + data[k * s] = cur; } } @@ -83,24 +81,20 @@ inline void ForwardFilter(F *data, std::size_t size, F B, std::array bp, template inline void BackwardFilter(F *data, std::size_t size, F B, std::array bp, std::size_t stride = Stride) { - const auto s = Stride > 0 ? Stride : stride; - F *const prend = data - 1; - F *p = data + (size - 1) * s; if (size < 1) return; - F cur = *p; + const auto s = Stride > 0 ? Stride : stride; + F cur = data[(size - 1) * s]; // Replicate the 3 pixels outside of the border. F next1 = cur; F next2 = cur; F next3 = cur; - p -= s; - for (; p > prend; p -= s) { + for (std::size_t k = size - 1; k-- > 0;) { next3 = next2; next2 = next1; next1 = cur; - cur = *p; - cur = B * cur + bp[0] * next1 + bp[1] * next2 + bp[2] * next3; - *p = cur; + cur = B * data[k * s] + bp[0] * next1 + bp[1] * next2 + bp[2] * next3; + data[k * s] = cur; } } @@ -123,6 +117,46 @@ void FastGaussian2DScalar(F *data, std::size_t width, std::size_t height, } } +// Separable convolution with a sampled Gaussian kernel truncated at 3 sigma, +// with replicated boundaries. +template +void DirectGaussian2D(F *data, std::size_t width, std::size_t height, + F sigma) { + if (width == 0 || height == 0) + return; + const auto radius = std::max( + 1, static_cast(std::ceil(F(3) * sigma))); + std::vector kernel(static_cast(2 * radius + 1)); + F sum = 0; + for (std::ptrdiff_t k = -radius; k <= radius; ++k) { + const F w = std::exp(-F(k * k) / (F(2) * sigma * sigma)); + kernel[static_cast(k + radius)] = w; + sum += w; + } + for (auto &w : kernel) + w /= sum; + + std::vector buf(std::max(width, height)); + const auto convolve = [&](std::size_t size, std::size_t stride, F *line) { + for (std::size_t k = 0; k < size; ++k) + buf[k] = line[k * stride]; + const auto last = static_cast(size) - 1; + for (std::ptrdiff_t k = 0; k <= last; ++k) { + F acc = 0; + for (std::ptrdiff_t m = -radius; m <= radius; ++m) { + const auto idx = std::clamp(k + m, 0, last); + acc += kernel[static_cast(m + radius)] * + buf[static_cast(idx)]; + } + line[static_cast(k) * stride] = acc; + } + }; + for (std::size_t j = 0; j < height; ++j) + convolve(width, 1, data + j * width); + for (std::size_t i = 0; i < width; ++i) + convolve(height, width, data + i); +} + // For unit test access void FastGaussian2DSIMD(float *data, std::size_t width, std::size_t height, float sigma); diff --git a/test_SimulatedCamera.cpp b/test_SimulatedCamera.cpp index 184386a..6d8463b 100644 --- a/test_SimulatedCamera.cpp +++ b/test_SimulatedCamera.cpp @@ -7,6 +7,7 @@ #include #include +#include #include #include #include @@ -248,6 +249,70 @@ TEST_CASE("FastGaussian2D") { } } +TEST_CASE("DirectGaussian2D") { + using Catch::Matchers::WithinAbs; + constexpr float sigma = 0.7f; + + SECTION("impulse") { + std::vector data(7 * 7); + data[7 * 3 + 3] = 1.0f; + gaussian_internal::DirectGaussian2D(data.data(), 7, 7, sigma); + + CHECK_THAT(std::accumulate(data.begin(), data.end(), 0.0), + WithinAbs(1.0, 1e-5)); + for (std::size_t j = 0; j < 7; ++j) { + for (std::size_t i = 0; i < 7; ++i) { + CAPTURE(j, i); + CHECK_THAT(data[j * 7 + i], + WithinAbs(data[j * 7 + 7 - i - 1], 1e-7)); + CHECK_THAT(data[j * 7 + i], + WithinAbs(data[(7 - j - 1) * 7 + i], 1e-7)); + CHECK_THAT(data[j * 7 + i], WithinAbs(data[i * 7 + j], 1e-7)); + } + } + + const int radius = int(std::ceil(3.0f * sigma)); + float wsum = 0.0f; + for (int k = -radius; k <= radius; ++k) { + wsum += std::exp(-float(k * k) / (2.0f * sigma * sigma)); + } + const float w0 = 1.0f / wsum; + CHECK_THAT(data[7 * 3 + 3], WithinAbs(w0 * w0, 1e-6)); + } + + SECTION("constant") { + std::vector data(7 * 5, 3.0f); + gaussian_internal::DirectGaussian2D(data.data(), 7, 5, sigma); + for (float v : data) { + CHECK_THAT(v, WithinAbs(3.0f, 1e-5)); + } + } +} + +TEST_CASE("FastGaussian2D-small-sigma") { + using Catch::Matchers::WithinAbs; + const float sigma = GENERATE(0.1f, 0.3f, 0.7f); + CAPTURE(sigma); + + SECTION("impulse") { + std::vector data(7 * 7); + data[7 * 3 + 3] = 1.0f; + FastGaussian2D(data.data(), 7, 7, sigma); + CHECK(std::all_of(data.begin(), data.end(), + [](float v) { return v >= 0.0f; })); + CHECK_THAT(std::accumulate(data.begin(), data.end(), 0.0), + WithinAbs(1.0, 1e-5)); + } + + SECTION("constant") { + std::vector data(7 * 5, 3.0f); + FastGaussian2D(data.data(), 7, 5, sigma); + for (float v : data) { + CHECK_THAT(v, WithinAbs(3.0f, 1e-5)); + } + } +} + TEST_CASE("FastPoisson-mean-variance") { using Catch::Matchers::WithinAbs; rnd::mt19937 rng(12345); From 1355c2b141b696dad221166abc76e20f9f92ba91 Mon Sep 17 00:00:00 2001 From: "Mark A. Tsuchida" Date: Fri, 25 Sep 2026 16:56:26 -0500 Subject: [PATCH 2/3] Fix rendering issues MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Blur when (close to) in focus; magnification-dependent filament thickness/brightness. - Image readback: rows are now addressed with the byte stride, which works whichever direction Blend2D stores the image. The image is created with img.create(...), and if that fails the signal is filled with zeros. - Blur now depends on NA: GaussianSigmaForDefocus takes the emission wavelength. The in-focus width is 0.21 λ / NA and the defocus width is 0.5 · NA · |dz| / n; the two combine as a root sum of squares. There's a new EMISSION_WAVELENGTH_UM = 0.52f constant. - Filament width: filaments are 0.025 µm wide. They're drawn at least 1 px wide, with intensity scaled down by filamentWidthUm_ / strokeWidth. The origin marker gets the same intensity scaling. - relativeBrightness_ manually set to be reasonable-ish. (Assisted by Claude Code; any errors are mine.) --- Specimen.h | 60 ++++++++++++++++++++++++++-------------- test_SimulatedCamera.cpp | 19 +++++++++++++ 2 files changed, 58 insertions(+), 21 deletions(-) diff --git a/Specimen.h b/Specimen.h index c767665..7d8bea8 100644 --- a/Specimen.h +++ b/Specimen.h @@ -12,14 +12,19 @@ #include constexpr double PI = 3.1415926535897; +constexpr float EMISSION_WAVELENGTH_UM = 0.52f; // GFP-like template inline F GaussianSigmaForDefocus(F defocus_um, F numericalAperture, - F refractiveIndex) { - const auto radius = - numericalAperture * std::fabs(defocus_um) / refractiveIndex; - // Apply an (arbitrary) multiplier and minimum. - return F(0.5) * radius + F(1.0); + F refractiveIndex, F wavelength_um) { + // Gaussian approximation of the in-focus widefield PSF (Zhang et al. + // 2007, Appl Opt 46:1819): sigma = 0.21 lambda / NA. + const F sigma0 = F(0.21) * wavelength_um / numericalAperture; + // Geometric defocus blur radius, with an (arbitrary) scaling to sigma. + const F sigmaDefocus = + F(0.5) * numericalAperture * std::fabs(defocus_um) / refractiveIndex; + // Convolved Gaussians add in variance. + return std::sqrt(sigma0 * sigma0 + sigmaDefocus * sigmaDefocus); } // Renders the expected (noise-free) signal of a specimen into signal (width * @@ -33,8 +38,14 @@ void RenderSpecimenImage(float *signal, double x_um, double y_um, double z_um, std::size_t width, std::size_t height, double um_per_px, double na, double intensity, ContentFn &&drawContent) { - BLImage img(static_cast(width), static_cast(height), - BL_FORMAT_XRGB32); + const std::size_t nPixels = width * height; + + BLImage img; + if (img.create(static_cast(width), static_cast(height), + BL_FORMAT_XRGB32) != BL_SUCCESS) { + std::fill(signal, signal + nPixels, 0.0f); + return; + } BLContext ctx(img); ctx.clearAll(); @@ -51,8 +62,6 @@ void RenderSpecimenImage(float *signal, double x_um, double y_um, double z_um, ctx.end(); - const std::size_t nPixels = width * height; - BLImageData data; BLResult status = img.getData(&data); if (status != BL_SUCCESS) { @@ -60,22 +69,20 @@ void RenderSpecimenImage(float *signal, double x_um, double y_um, double z_um, return; // Give up (shouldn't happen). } - const auto *pix = static_cast(data.pixelData); - - // Stride is the stride of scanlines; negative stride means bottom-up. - const std::intptr_t stride = data.stride / sizeof(std::uint32_t); - const std::intptr_t start = stride >= 0 ? 0 : (height - 1) * (-stride); - for (std::intptr_t j = 0; j < std::intptr_t(height); ++j) { - for (std::intptr_t i = 0; i < std::intptr_t(width); ++i) { - const auto p = pix[start + i + j * stride]; + // pixelData points to the top-left pixel; stride (bytes) may be negative. + const auto *base = static_cast(data.pixelData); + for (std::size_t j = 0; j < height; ++j) { + const auto *row = reinterpret_cast( + base + std::intptr_t(j) * data.stride); + for (std::size_t i = 0; i < width; ++i) { // Green sample - signal[i + j * width] = static_cast((p >> 8) & 0xff); + signal[i + j * width] = static_cast((row[i] >> 8) & 0xff); } } // Defocus - const auto sigmaUm = - GaussianSigmaForDefocus(float(z_um), float(na), 1.33f); + const auto sigmaUm = GaussianSigmaForDefocus(float(z_um), float(na), 1.33f, + EMISSION_WAVELENGTH_UM); const auto sigmaPixels = sigmaUm / float(um_per_px); FastGaussian2D(signal, width, height, sigmaPixels); @@ -91,6 +98,9 @@ class FilamentsSpecimen { std::vector filaments_; + static constexpr double filamentWidthUm_ = 0.025; // microtubule + static constexpr double relativeBrightness_ = 0.1; // arbitrary + public: explicit FilamentsSpecimen() { using std::cos; @@ -114,8 +124,16 @@ class FilamentsSpecimen { std::size_t width, std::size_t height, double um_per_px, double na, double intensity) const { const auto &filaments = filaments_; + // Blend2D renders 8-bit, so a sub-pixel stroke would quantize away. + // Draw at least 1 px wide and scale intensity by the width ratio, + // preserving signal per unit length (antialiasing gives the pixel + // coverage). + const double strokeWidth = std::max(filamentWidthUm_, um_per_px); + const double filamentIntensity = + intensity * relativeBrightness_ * filamentWidthUm_ / strokeWidth; RenderSpecimenImage(signal, x_um, y_um, z_um, width, height, um_per_px, - na, intensity, [&](BLContext &ctx) { + na, filamentIntensity, [&](BLContext &ctx) { + ctx.setStrokeWidth(strokeWidth); for (const Filament &f : filaments) { BLPath path; path.moveTo(f.x0, f.y0); diff --git a/test_SimulatedCamera.cpp b/test_SimulatedCamera.cpp index 6d8463b..9b2e538 100644 --- a/test_SimulatedCamera.cpp +++ b/test_SimulatedCamera.cpp @@ -402,6 +402,25 @@ TEST_CASE("ReadOut-clamp") { [](std::uint16_t v) { return v == 65535; })); } +TEST_CASE("GaussianSigmaForDefocus") { + using Catch::Matchers::WithinRel; + const float na = GENERATE(0.3f, 0.75f, 1.4f); + CAPTURE(na); + + SECTION("in focus") { + CHECK_THAT(GaussianSigmaForDefocus(0.0f, na, 1.33f, 0.52f), + WithinRel(0.21f * 0.52f / na, 1e-5f)); + } + + SECTION("large defocus") { + for (const float dz : {-200.0f, 200.0f}) { + CAPTURE(dz); + CHECK_THAT(GaussianSigmaForDefocus(dz, na, 1.33f, 0.52f), + WithinRel(0.5f * na * std::fabs(dz) / 1.33f, 1e-3f)); + } + } +} + TEST_CASE("Specimen-Draw-deterministic") { const std::size_t width = 64, height = 48; std::vector a(width * height, -1.0f); From 9179d847c4f6397711a6b232c71292312d026a86 Mon Sep 17 00:00:00 2001 From: "Mark A. Tsuchida" Date: Fri, 25 Sep 2026 17:24:03 -0500 Subject: [PATCH 3/3] Default to 20x With the current filament intensity, filaments aren't visible at 10x under default settings. (Assisted by Claude Code; any errors are mine.) --- SimObjectiveTurret.h | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/SimObjectiveTurret.h b/SimObjectiveTurret.h index d32c1b6..6ae0404 100644 --- a/SimObjectiveTurret.h +++ b/SimObjectiveTurret.h @@ -60,7 +60,7 @@ class SimObjectiveTurret : public CStateDeviceBase { // ----- CPropertyAction *pAct = new CPropertyAction(this, &SimObjectiveTurret::OnState); - ret = CreateIntegerProperty(MM::g_Keyword_State, 0, false, pAct); + ret = CreateIntegerProperty(MM::g_Keyword_State, 1, false, pAct); if (ret != DEVICE_OK) return ret; @@ -122,5 +122,5 @@ class SimObjectiveTurret : public CStateDeviceBase { std::string name_; SimHub *hub_ = nullptr; // Read by the camera thread via the hub - std::atomic state_{0}; + std::atomic state_{1}; };