Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 12 additions & 2 deletions Gaussian2DFilter.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -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
72 changes: 53 additions & 19 deletions Gaussian2DFilter.h
Original file line number Diff line number Diff line change
@@ -1,17 +1,19 @@
#pragma once

#include <algorithm>
#include <array>
#include <cassert>
#include <cmath>
#include <cstddef>
#include <vector>

void FastGaussian2D(float *data, std::size_t width, std::size_t height,
float sigma);

namespace gaussian_internal {

// Eq 11b
template <typename F> inline float q(F sigma) {
template <typename F> inline F q(F sigma) {
assert(sigma > F(0.0));

// Note: This function, as given in the paper, is not continuous at sigma =
Expand Down Expand Up @@ -58,49 +60,41 @@ template <typename F> inline F B(std::array<F, 3> bp) {
template <typename F, std::size_t Stride = 0>
inline void ForwardFilter(F *data, std::size_t size, F B, std::array<F, 3> 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;
}
}

// Eq 9b (Stride == 0 uses dynamic stride)
template <typename F, std::size_t Stride = 0>
inline void BackwardFilter(F *data, std::size_t size, F B, std::array<F, 3> 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;
}
}

Expand All @@ -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 <typename F>
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<std::ptrdiff_t>(
1, static_cast<std::ptrdiff_t>(std::ceil(F(3) * sigma)));
std::vector<F> kernel(static_cast<std::size_t>(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<std::size_t>(k + radius)] = w;
sum += w;
}
for (auto &w : kernel)
w /= sum;

std::vector<F> 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<std::ptrdiff_t>(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<std::ptrdiff_t>(k + m, 0, last);
acc += kernel[static_cast<std::size_t>(m + radius)] *
buf[static_cast<std::size_t>(idx)];
}
line[static_cast<std::size_t>(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);
Expand Down
4 changes: 2 additions & 2 deletions SimObjectiveTurret.h
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,7 @@ class SimObjectiveTurret : public CStateDeviceBase<SimObjectiveTurret> {
// -----
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;

Expand Down Expand Up @@ -122,5 +122,5 @@ class SimObjectiveTurret : public CStateDeviceBase<SimObjectiveTurret> {
std::string name_;
SimHub *hub_ = nullptr;
// Read by the camera thread via the hub
std::atomic<long> state_{0};
std::atomic<long> state_{1};
};
60 changes: 39 additions & 21 deletions Specimen.h
Original file line number Diff line number Diff line change
Expand Up @@ -12,14 +12,19 @@
#include <vector>

constexpr double PI = 3.1415926535897;
constexpr float EMISSION_WAVELENGTH_UM = 0.52f; // GFP-like

template <typename F>
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 *
Expand All @@ -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<int>(width), static_cast<int>(height),
BL_FORMAT_XRGB32);
const std::size_t nPixels = width * height;

BLImage img;
if (img.create(static_cast<int>(width), static_cast<int>(height),
BL_FORMAT_XRGB32) != BL_SUCCESS) {
std::fill(signal, signal + nPixels, 0.0f);
return;
}
BLContext ctx(img);
ctx.clearAll();

Expand All @@ -51,31 +62,27 @@ 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) {
std::fill(signal, signal + nPixels, 0.0f);
return; // Give up (shouldn't happen).
}

const auto *pix = static_cast<const std::uint32_t *>(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<const std::uint8_t *>(data.pixelData);
for (std::size_t j = 0; j < height; ++j) {
const auto *row = reinterpret_cast<const std::uint32_t *>(
base + std::intptr_t(j) * data.stride);
for (std::size_t i = 0; i < width; ++i) {
// Green sample
signal[i + j * width] = static_cast<float>((p >> 8) & 0xff);
signal[i + j * width] = static_cast<float>((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);

Expand All @@ -91,6 +98,9 @@ class FilamentsSpecimen {

std::vector<Filament> filaments_;

static constexpr double filamentWidthUm_ = 0.025; // microtubule
static constexpr double relativeBrightness_ = 0.1; // arbitrary

public:
explicit FilamentsSpecimen() {
using std::cos;
Expand All @@ -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);
Expand Down
84 changes: 84 additions & 0 deletions test_SimulatedCamera.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
#include <catch2/matchers/catch_matchers_floating_point.hpp>

#include <algorithm>
#include <array>
#include <cmath>
#include <cstdint>
#include <functional>
Expand Down Expand Up @@ -248,6 +249,70 @@ TEST_CASE("FastGaussian2D") {
}
}

TEST_CASE("DirectGaussian2D") {
using Catch::Matchers::WithinAbs;
constexpr float sigma = 0.7f;

SECTION("impulse") {
std::vector<float> 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<float> 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<float> 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<float> 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);
Expand Down Expand Up @@ -337,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<float> a(width * height, -1.0f);
Expand Down
Loading