Skip to content
56 changes: 56 additions & 0 deletions Detector.h
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
#pragma once

#include "Random.h"

#include <algorithm>
#include <cmath>
#include <cstddef>
#include <cstdint>
#include <limits>

// Fast Poisson sampling (avoid std::poisson_distribution, which is slow to
// construct for each sample of different lambda).
// - For small lambda: Knuth DE, The Art of Computer Programming, Volume 2:
// Seminumerical Algorithms, 3rd ed, section 3.4.1.F.3.
// - For large lambda: Gaussian approximation N(lambda, sqrt(lambda))
template <typename F, typename RNG>
F FastPoisson(F lambda, RNG &rng,
rnd::uniform_real_distribution<F> &uniformDist) {
if (lambda > F(10.0)) {
rnd::normal_distribution<F> gaussianDist(lambda, std::sqrt(lambda));
return std::max(F(0), gaussianDist(rng));
} else {
F const L = std::exp(-lambda);
F p = 1.0;
int k = 0;
do {
++k;
p *= uniformDist(rng);
} while (p > L);
return static_cast<F>(k - 1);
}
}

// Simulates sensor readout. signal is the expected photoelectron count per
// pixel, or nullptr for no light. Applies shot noise (to signal), read noise,
// and offset, then rounds and clamps to the pixel range.
template <typename RNG>
void ReadOut(const float *signal, std::uint16_t *out, std::size_t nPixels,
float readNoise, float offset, RNG &rng) {
const bool hasReadNoise = readNoise > 0.0f;
rnd::normal_distribution<float> readNoiseDistrib(
0.0f, hasReadNoise ? readNoise : 1.0f);
rnd::uniform_real_distribution<float> uniformDistForPoisson(0.0f, 1.0f);
const float maxVal = float(std::numeric_limits<std::uint16_t>::max());
for (std::size_t i = 0; i < nPixels; ++i) {
float v = offset;
if (hasReadNoise) {
v += readNoiseDistrib(rng);
}
if (signal && signal[i] > 0.0f) {
v += FastPoisson(signal[i], rng, uniformDistForPoisson);
}
out[i] = static_cast<std::uint16_t>(
std::clamp(std::round(v), 0.0f, maxVal));
}
}
4 changes: 4 additions & 0 deletions DeviceAdapter.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
#include "SimFocus.h"
#include "SimHub.h"
#include "SimObjectiveTurret.h"
#include "SimShutter.h"
#include "SimXY.h"

#include "DeviceBase.h"
Expand Down Expand Up @@ -31,6 +32,9 @@ MODULE_API MM::Device *CreateDevice(const char *name) {
if (n == "SimObjectiveTurret") {
return new SimObjectiveTurret("SimObjectiveTurret");
}
if (n == "SimShutter") {
return new SimShutter("SimShutter");
}
return nullptr;
}

Expand Down
9 changes: 9 additions & 0 deletions Random.h
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
#pragma once

#ifdef USE_BOOST_RANDOM
#include <boost/random.hpp>
namespace rnd = boost::random;
#else
#include <random>
namespace rnd = std;
#endif
34 changes: 26 additions & 8 deletions SimCam.h
Original file line number Diff line number Diff line change
@@ -1,18 +1,23 @@
#pragma once

#include "Detector.h"
#include "SimHub.h"
#include "Specimen.h"

#include "DeviceBase.h"

#include <algorithm>
#include <cassert>
#include <chrono>
#include <cmath>
#include <condition_variable>
#include <cstdint>
#include <limits>
#include <memory>
#include <mutex>
#include <string>
#include <thread>
#include <vector>

// In C++17 can make static constexpr member of SimCam
constexpr double EXPOSURE_MS_MIN = 0.001;
Expand All @@ -27,8 +32,8 @@ class SimCam : public CCameraBase<SimCam> {
static constexpr const char *modeFilaments_ = "Filaments";
static constexpr const char *modeNuclei_ = "Nuclei";

FilamentsSpecimen<std::uint16_t> filamentsSpecimen_;
NucleiSpecimen<std::uint16_t> nucleiSpecimen_;
FilamentsSpecimen filamentsSpecimen_;
NucleiSpecimen nucleiSpecimen_;
std::string mode_ = modeFilaments_;

// Camera state
Expand All @@ -41,6 +46,9 @@ class SimCam : public CCameraBase<SimCam> {
// Last snap (always equal to ROI width/height)
std::unique_ptr<std::uint16_t[]> snapBuffer_;

std::vector<float> signal_;
rnd::mt19937 rng_;

// Sequence acquisition state
std::thread seqThread_;
std::mutex seqMutex_;
Expand Down Expand Up @@ -139,13 +147,23 @@ class SimCam : public CCameraBase<SimCam> {
const double intensity = 2800.0 * GetExposure() * GetBinning() *
GetBinning() * (na * na * na * na) /
(magnification * magnification);
if (mode_ == modeNuclei_) {
nucleiSpecimen_.Draw(snapBuffer_.get(), x, y, z, roiWidth_,
roiHeight_, umPerPx, na, intensity);
} else {
filamentsSpecimen_.Draw(snapBuffer_.get(), x, y, z, roiWidth_,
roiHeight_, umPerPx, na, intensity);
const float *signal = nullptr;
if (hub->IsShutterOpen()) {
signal_.resize(nPixels);
if (mode_ == modeNuclei_) {
nucleiSpecimen_.Draw(signal_.data(), x, y, z, roiWidth_,
roiHeight_, umPerPx, na, intensity);
} else {
filamentsSpecimen_.Draw(signal_.data(), x, y, z, roiWidth_,
roiHeight_, umPerPx, na, intensity);
}
signal = signal_.data();
}
// TODO: Make read noise and offset adjustable?
constexpr float readNoise = 50.0f;
constexpr float darkOffset = 100.0f;
ReadOut(signal, snapBuffer_.get(), nPixels, readNoise, darkOffset,
rng_);

std::chrono::duration<double, std::milli> exposure(GetExposure());
const auto finishTime =
Expand Down
4 changes: 3 additions & 1 deletion SimHub.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
#include "SimCam.h"
#include "SimFocus.h"
#include "SimObjectiveTurret.h"
#include "SimShutter.h"
#include "SimXY.h"

int SimHub::DetectInstalledDevices() {
Expand All @@ -11,5 +12,6 @@ int SimHub::DetectInstalledDevices() {
AddInstalledDevice(new SimFocus<AsyncProcessModel<1>>("SimFocus"));
AddInstalledDevice(new SimObjectiveTurret("SimObjectiveTurret"));
AddInstalledDevice(new SimXY<AsyncProcessModel<2>>("SimXY"));
AddInstalledDevice(new SimShutter("SimShutter"));
return DEVICE_OK;
}
}
8 changes: 7 additions & 1 deletion SimHub.h
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ class SimHub : public HubBase<SimHub> {
};
std::function<double()> getMagnificationFunc_ = [] { return 1.0; };
std::function<double()> getNAFunc_ = [] { return 1.0; };
std::function<bool()> getShutterOpenFunc_ = [] { return true; };

public:
explicit SimHub(std::string name) : name_(std::move(name)) {}
Expand All @@ -39,8 +40,13 @@ class SimHub : public HubBase<SimHub> {

template <typename F> void SetGetNAFunction(F f) { getNAFunc_ = f; }

template <typename F> void SetGetShutterOpenFunction(F f) {
getShutterOpenFunc_ = f;
}

double GetFocusUm() { return getFocusUmFunc_(); }
std::pair<double, double> GetXYUm() { return getXYUmFunc_(); }
double GetMagnification() { return getMagnificationFunc_(); }
double GetNA() { return getNAFunc_(); }
};
bool IsShutterOpen() { return getShutterOpenFunc_(); }
};
84 changes: 84 additions & 0 deletions SimShutter.h
Original file line number Diff line number Diff line change
@@ -0,0 +1,84 @@
#pragma once

#include "SimHub.h"

#include "DeviceBase.h"

#include <atomic>
#include <string>
#include <utility>

class SimShutter : public CShutterBase<SimShutter> {
std::string name_;
bool initialized_ = false;

// Shutter state
std::atomic<bool> isOpen_{false};

public:
explicit SimShutter(std::string name) : name_(std::move(name)) {}

~SimShutter() { Shutdown(); }

bool Busy() final {
// TODO: Could introduce a small delay here
return false;
}

void GetName(char *name) const final {
CDeviceUtils::CopyLimitedString(name, name_.c_str());
}

int Fire(double /*deltaT*/) final { return DEVICE_UNSUPPORTED_COMMAND; }

int Initialize() final {
isOpen_ = false;

int ret = CreateIntegerProperty(
MM::g_Keyword_State, 0, false,
new MM::ActionLambda(
[this](MM::PropertyBase *pProp, MM::ActionType eAct) {
if (eAct == MM::BeforeGet) {
pProp->Set(isOpen_ ? 1L : 0L);
} else if (eAct == MM::AfterSet) {
long v{};
pProp->Get(v);
return SetOpen(v != 0);
}
return DEVICE_OK;
}));
if (ret != DEVICE_OK)
return ret;
ret = AddAllowedValue(MM::g_Keyword_State, "0");
if (ret != DEVICE_OK)
return ret;
ret = AddAllowedValue(MM::g_Keyword_State, "1");
if (ret != DEVICE_OK)
return ret;

auto *hub = static_cast<SimHub *>(GetParentHub());
hub->SetGetShutterOpenFunction([this] { return isOpen_.load(); });
initialized_ = true;
return DEVICE_OK;
}

int Shutdown() final {
isOpen_ = false;
if (initialized_) {
auto *hub = static_cast<SimHub *>(GetParentHub());
hub->SetGetShutterOpenFunction([] { return true; });
initialized_ = false;
}
return DEVICE_OK;
}

int SetOpen(bool open = true) final {
isOpen_ = open;
return DEVICE_OK;
}

int GetOpen(bool &open) final {
open = isOpen_;
return DEVICE_OK;
}
};
Loading
Loading