use of uk.ac.sussex.gdsc.core.ij.plugin.WindowOrganiser in project GDSC-SMLM by aherbert.
the class BenchmarkFit method runFit.
private void runFit() {
// Initialise the answer.
answer[Gaussian2DFunction.BACKGROUND] = benchmarkParameters.getBackground();
answer[Gaussian2DFunction.SIGNAL] = benchmarkParameters.getSignal();
answer[Gaussian2DFunction.X_POSITION] = benchmarkParameters.x;
answer[Gaussian2DFunction.Y_POSITION] = benchmarkParameters.y;
answer[Gaussian2DFunction.Z_POSITION] = benchmarkParameters.z;
answer[Gaussian2DFunction.X_SD] = benchmarkParameters.sd / benchmarkParameters.pixelPitch;
answer[Gaussian2DFunction.Y_SD] = benchmarkParameters.sd / benchmarkParameters.pixelPitch;
// Set up the fit region. Always round down since 0.5 is the centre of the pixel.
final int x = (int) benchmarkParameters.x;
final int y = (int) benchmarkParameters.y;
region = new Rectangle(x - regionSize, y - regionSize, 2 * regionSize + 1, 2 * regionSize + 1);
if (!new Rectangle(0, 0, imp.getWidth(), imp.getHeight()).contains(region)) {
// Check if it is incorrect by only 1 pixel
if (region.width <= imp.getWidth() + 1 && region.height <= imp.getHeight() + 1) {
ImageJUtils.log("Adjusting region %s to fit within image bounds (%dx%d)", region.toString(), imp.getWidth(), imp.getHeight());
region = new Rectangle(0, 0, imp.getWidth(), imp.getHeight());
} else {
IJ.error(TITLE, "Fit region does not fit within the image");
return;
}
}
// Adjust the centre & account for 0.5 pixel offset during fitting
answer[Gaussian2DFunction.X_POSITION] -= (region.x + 0.5);
answer[Gaussian2DFunction.Y_POSITION] -= (region.y + 0.5);
// Configure for fitting
fitConfig.setBackgroundFitting(backgroundFitting);
fitConfig.setNotSignalFitting(!signalFitting);
fitConfig.setComputeDeviations(false);
// Create the camera model
CameraModel cameraModel = fitConfig.getCameraModel();
// Crop for speed. Reset origin first so the region is within the model
cameraModel.setOrigin(0, 0);
cameraModel = cameraModel.crop(region, false);
final ImageStack stack = imp.getImageStack();
final int totalFrames = benchmarkParameters.frames;
// Create a pool of workers
final int nThreads = Prefs.getThreads();
final BlockingQueue<Integer> jobs = new ArrayBlockingQueue<>(nThreads * 2);
final List<Worker> workers = new LinkedList<>();
final List<Thread> threads = new LinkedList<>();
final Ticker ticker = ImageJUtils.createTicker(totalFrames, nThreads, "Fitting frames ...");
for (int i = 0; i < nThreads; i++) {
final Worker worker = new Worker(jobs, stack, region, fitConfig, cameraModel, ticker);
final Thread t = new Thread(worker);
workers.add(worker);
threads.add(t);
t.start();
}
// Store all the fitting results
results = new double[totalFrames * startPoints.length][];
resultsTime = new long[results.length];
// Fit the frames
for (int i = 0; i < totalFrames; i++) {
// Only fit if there were simulated photons
if (benchmarkParameters.framePhotons[i] > 0) {
put(jobs, i);
}
}
// Finish all the worker threads by passing in a null job
for (int i = 0; i < threads.size(); i++) {
put(jobs, -1);
}
// Wait for all to finish
for (int i = 0; i < threads.size(); i++) {
try {
threads.get(i).join();
} catch (final InterruptedException ex) {
Thread.currentThread().interrupt();
throw new ConcurrentRuntimeException(ex);
}
}
threads.clear();
if (hasOffsetXy()) {
ImageJUtils.log(TITLE + ": CoM within start offset = %d / %d (%s%%)", comValid.intValue(), totalFrames, MathUtils.rounded((100.0 * comValid.intValue()) / totalFrames));
}
ImageJUtils.finished("Collecting results ...");
// Collect the results
Statistics[] stats = null;
for (int i = 0; i < workers.size(); i++) {
final Statistics[] next = workers.get(i).stats;
if (stats == null) {
stats = next;
continue;
}
for (int j = 0; j < next.length; j++) {
stats[j].add(next[j]);
}
}
workers.clear();
Objects.requireNonNull(stats, "No statistics were computed");
// Show a table of the results
summariseResults(stats, cameraModel);
// Optionally show histograms
if (showHistograms) {
IJ.showStatus("Calculating histograms ...");
final WindowOrganiser windowOrganiser = new WindowOrganiser();
final double[] convert = getConversionFactors();
final HistogramPlotBuilder builder = new HistogramPlotBuilder(TITLE).setNumberOfBins(histogramBins);
for (int i = 0; i < NAMES.length; i++) {
if (displayHistograms[i] && convert[i] != 0) {
// We will have to convert the values...
final double[] tmp = ((StoredDataStatistics) stats[i]).getValues();
for (int j = 0; j < tmp.length; j++) {
tmp[j] *= convert[i];
}
final StoredDataStatistics tmpStats = StoredDataStatistics.create(tmp);
builder.setData(tmpStats).setName(NAMES[i]).setPlotLabel(String.format("%s +/- %s", MathUtils.rounded(tmpStats.getMean()), MathUtils.rounded(tmpStats.getStandardDeviation()))).show(windowOrganiser);
}
}
windowOrganiser.tile();
}
if (saveRawData) {
final String dir = ImageJUtils.getDirectory("Data_directory", rawDataDirectory);
if (dir != null) {
saveData(stats, dir);
}
}
IJ.showStatus("");
}
use of uk.ac.sussex.gdsc.core.ij.plugin.WindowOrganiser in project GDSC-SMLM by aherbert.
the class Fire method run.
@Override
public void run(String arg) {
extraOptions = ImageJUtils.isExtraOptions();
SmlmUsageTracker.recordPlugin(this.getClass(), arg);
// Require some fit results and selected regions
final int size = MemoryPeakResults.countMemorySize();
if (size == 0) {
IJ.error(pluginTitle, "There are no fitting results in memory");
return;
}
settings = Settings.load();
settings.save();
if ("q".equals(arg)) {
pluginTitle += " Q estimation";
runQEstimation();
return;
}
IJ.showStatus(pluginTitle + " ...");
if (!showInputDialog()) {
return;
}
MemoryPeakResults inputResults1 = ResultsManager.loadInputResults(settings.inputOption, false, null, null);
if (MemoryPeakResults.isEmpty(inputResults1)) {
IJ.error(pluginTitle, "No results could be loaded");
return;
}
MemoryPeakResults inputResults2 = ResultsManager.loadInputResults(settings.inputOption2, false, null, null);
inputResults1 = cropToRoi(inputResults1);
if (inputResults1.size() < 2) {
IJ.error(pluginTitle, "No results within the crop region");
return;
}
if (inputResults2 != null) {
inputResults2 = cropToRoi(inputResults2);
if (inputResults2.size() < 2) {
IJ.error(pluginTitle, "No results2 within the crop region");
return;
}
}
initialise(inputResults1, inputResults2);
if (!showDialog()) {
return;
}
final long start = System.currentTimeMillis();
// Compute FIRE
String name = inputResults1.getName();
final double fourierImageScale = Settings.scaleValues[settings.imageScaleIndex];
final int imageSize = Settings.imageSizeValues[settings.imageSizeIndex];
if (this.results2 != null) {
name += " vs " + this.results2.getName();
final FireResult result = calculateFireNumber(fourierMethod, samplingMethod, thresholdMethod, fourierImageScale, imageSize);
if (result != null) {
logResult(name, result);
if (settings.showFrcCurve) {
showFrcCurve(name, result, thresholdMethod);
}
}
} else {
FireResult result = null;
final int repeats = (settings.randomSplit) ? Math.max(1, settings.repeats) : 1;
setProgress(repeats);
if (repeats == 1) {
result = calculateFireNumber(fourierMethod, samplingMethod, thresholdMethod, fourierImageScale, imageSize);
if (result != null) {
logResult(name, result);
if (settings.showFrcCurve) {
showFrcCurve(name, result, thresholdMethod);
}
}
} else {
// Multi-thread this ...
final int nThreads = MathUtils.min(repeats, getThreads());
final ExecutorService executor = Executors.newFixedThreadPool(nThreads);
final LocalList<Future<?>> futures = new LocalList<>(repeats);
final LocalList<FireWorker> workers = new LocalList<>(repeats);
IJ.showProgress(0);
IJ.showStatus(pluginTitle + " computing ...");
for (int i = 1; i <= repeats; i++) {
final FireWorker w = new FireWorker(i, fourierImageScale, imageSize);
workers.add(w);
futures.add(executor.submit(w));
}
// Wait for all to finish
executor.shutdown();
ConcurrencyUtils.waitForCompletionUnchecked(futures);
IJ.showProgress(1);
// Show a combined FRC curve plot of all the smoothed curves if we have multiples.
final LUT valuesLut = LutHelper.createLut(LutColour.FIRE_GLOW);
final LutHelper.DefaultLutMapper mapper = new LutHelper.DefaultLutMapper(0, repeats);
final FrcCurvePlot curve = new FrcCurvePlot();
final Statistics stats = new Statistics();
final WindowOrganiser wo = new WindowOrganiser();
boolean oom = false;
for (int i = 0; i < repeats; i++) {
final FireWorker w = workers.get(i);
if (w.oom) {
oom = true;
}
if (w.result == null) {
continue;
}
result = w.result;
if (!Double.isNaN(result.fireNumber)) {
stats.add(result.fireNumber);
}
if (settings.showFrcCurveRepeats) {
// Output each FRC curve using a suffix.
logResult(w.name, result);
wo.add(ImageJUtils.display(w.plot.getTitle(), w.plot));
}
if (settings.showFrcCurve) {
final int index = mapper.map(i + 1);
curve.add(name, result, thresholdMethod, LutHelper.getColour(valuesLut, index), Color.blue, null);
}
}
if (result != null) {
wo.cascade();
final double mean = stats.getMean();
logResult(name, result, mean, stats);
if (settings.showFrcCurve) {
curve.addResolution(mean);
final Plot plot = curve.getPlot();
ImageJUtils.display(plot.getTitle(), plot);
}
}
if (oom) {
// @formatter:off
IJ.error(pluginTitle, "ERROR - Parallel computation out-of-memory.\n \n" + TextUtils.wrap("The number of results will be reduced. " + "Please reduce the size of the Fourier image " + "or change the number of threads " + "using the extra options (hold down the 'Shift' " + "key when running the plugin).", 80));
// @formatter:on
}
}
// Only do this once
if (settings.showFrcTimeEvolution && result != null && !Double.isNaN(result.fireNumber)) {
showFrcTimeEvolution(name, result.fireNumber, thresholdMethod, nmPerUnit / result.getNmPerPixel(), imageSize);
}
}
IJ.showStatus(pluginTitle + " complete : " + TextUtils.millisToString(System.currentTimeMillis() - start));
}
use of uk.ac.sussex.gdsc.core.ij.plugin.WindowOrganiser in project GDSC-SMLM by aherbert.
the class DriftCalculator method plotDrift.
private static PlotWindow plotDrift(PlotWindow parent, double[][] interpolated, double[][] original, String name, int index) {
// Create plot
final double[] xlimits = MathUtils.limits(interpolated[0]);
double[] ylimits = MathUtils.limits(original[index]);
ylimits = MathUtils.limits(ylimits, interpolated[index]);
final Plot plot = new Plot(name, "Frame", "Drift (px)");
plot.setLimits(xlimits[0], xlimits[1], ylimits[0], ylimits[1]);
// De-saturated blue
plot.setColor(new Color(0, 0, 155));
plot.addPoints(original[0], original[index], Plot.CROSS);
plot.setColor(java.awt.Color.RED);
plot.addPoints(interpolated[0], interpolated[index], Plot.LINE);
final WindowOrganiser wo = new WindowOrganiser();
final PlotWindow window = ImageJUtils.display(name, plot, wo);
if (wo.isNotEmpty() && parent != null) {
final Point location = parent.getLocation();
location.y += parent.getHeight();
window.setLocation(location);
}
return window;
}
use of uk.ac.sussex.gdsc.core.ij.plugin.WindowOrganiser in project GDSC-SMLM by aherbert.
the class PsfEstimator method calculateStatistics.
private boolean calculateStatistics(PeakFit fitter, double[] params, double[] paramsDev) {
debug(" Fitting PSF");
swapStatistics();
// Create the fit engine using the PeakFit plugin
final FitConfiguration fitConfig = config.getFitConfiguration();
fitConfig.setInitialPeakStdDev0((float) params[1]);
try {
fitConfig.setInitialPeakStdDev1((float) params[2]);
fitConfig.setInitialAngle((float) Math.toRadians(params[0]));
} catch (IllegalStateException ex) {
// Ignore this as the current PSF is not a 2 axis and theta Gaussian PSF
}
final ImageStack stack = imp.getImageStack();
final Rectangle roi = stack.getProcessor(1).getRoi();
ImageSource source = new IJImageSource(imp);
// Allow interlaced data by wrapping the image source
if (interlacedData) {
source = new InterlacedImageSource(source, dataStart, dataBlock, dataSkip);
}
// Allow frame aggregation by wrapping the image source
if (integrateFrames > 1) {
source = new AggregatedImageSource(source, integrateFrames);
}
fitter.initialiseImage(source, roi, true);
fitter.addPeakResults(this);
fitter.initialiseFitting();
final FitEngine engine = fitter.createFitEngine();
// Use random slices
final int[] slices = new int[stack.getSize()];
for (int i = 0; i < slices.length; i++) {
slices[i] = i + 1;
}
RandomUtils.shuffle(slices, UniformRandomProviders.create());
IJ.showStatus("Fitting ...");
// Use multi-threaded code for speed
int sliceIndex;
for (sliceIndex = 0; sliceIndex < slices.length; sliceIndex++) {
final int slice = slices[sliceIndex];
IJ.showProgress(size(), settings.getNumberOfPeaks());
final ImageProcessor ip = stack.getProcessor(slice);
// stack processor does not set the bounds required by ImageConverter
ip.setRoi(roi);
final FitJob job = new FitJob(slice, ImageJImageConverter.getData(ip), roi);
engine.run(job);
if (sampleSizeReached() || ImageJUtils.isInterrupted()) {
break;
}
}
if (ImageJUtils.isInterrupted()) {
IJ.showProgress(1);
engine.end(true);
return false;
}
// Wait until we have enough results
while (!sampleSizeReached() && !engine.isQueueEmpty()) {
IJ.showProgress(size(), settings.getNumberOfPeaks());
try {
Thread.sleep(50);
} catch (final InterruptedException ex) {
Thread.currentThread().interrupt();
throw new ConcurrentRuntimeException("Unexpected interruption", ex);
}
}
// End now if we have enough samples
engine.end(sampleSizeReached());
ImageJUtils.finished();
// This count will be an over-estimate given that the provider is ahead of the consumer
// in this multi-threaded system
debug(" Processed %d/%d slices (%d peaks)", sliceIndex, slices.length, size());
setParams(ANGLE, params, paramsDev, sampleNew[ANGLE]);
setParams(X, params, paramsDev, sampleNew[X]);
setParams(Y, params, paramsDev, sampleNew[Y]);
if (settings.getShowHistograms()) {
final HistogramPlotBuilder builder = new HistogramPlotBuilder(TITLE).setNumberOfBins(settings.getHistogramBins());
final WindowOrganiser wo = new WindowOrganiser();
for (int ii = 0; ii < 3; ii++) {
if (sampleNew[ii].getN() == 0) {
continue;
}
final StoredDataStatistics stats = StoredDataStatistics.create(sampleNew[ii].getValues());
builder.setData(stats).setName(NAMES[ii]).setPlotLabel("Mean = " + MathUtils.rounded(stats.getMean()) + ". Median = " + MathUtils.rounded(sampleNew[ii].getPercentile(50))).show(wo);
}
wo.tile();
}
if (size() < 2) {
log("ERROR: Insufficient number of fitted peaks, terminating ...");
return false;
}
return true;
}
use of uk.ac.sussex.gdsc.core.ij.plugin.WindowOrganiser in project GDSC-SMLM by aherbert.
the class MeanVarianceTest method run.
@Override
public void run(String arg) {
SmlmUsageTracker.recordPlugin(this.getClass(), arg);
settings = Settings.load();
settings.save();
String helpKey = "mean-variance-test";
if (ImageJUtils.isExtraOptions()) {
final ImagePlus imp = WindowManager.getCurrentImage();
if (imp.getStackSize() > 1) {
final GenericDialog gd = new GenericDialog(TITLE);
gd.addMessage("Perform single image analysis on the current image?");
gd.addNumericField("Bias", settings.bias, 0);
gd.addHelp(HelpUrls.getUrl(helpKey));
gd.showDialog();
if (gd.wasCanceled()) {
return;
}
singleImage = true;
settings.bias = Math.abs(gd.getNextNumber());
} else {
IJ.error(TITLE, "Single-image mode requires a stack");
return;
}
}
List<ImageSample> images;
String inputDirectory = "";
if (singleImage) {
IJ.showStatus("Loading images...");
images = getImages();
if (images.size() == 0) {
IJ.error(TITLE, "Not enough images for analysis");
return;
}
} else {
inputDirectory = IJ.getDirectory("Select image series ...");
if (inputDirectory == null) {
return;
}
final SeriesOpener series = new SeriesOpener(inputDirectory);
series.setVariableSize(true);
if (series.getNumberOfImages() < 3) {
IJ.error(TITLE, "Not enough images in the selected directory");
return;
}
if (!IJ.showMessageWithCancel(TITLE, String.format("Analyse %d images, first image:\n%s", series.getNumberOfImages(), series.getImageList()[0]))) {
return;
}
IJ.showStatus("Loading images");
images = getImages(series);
if (images.size() < 3) {
IJ.error(TITLE, "Not enough images for analysis");
return;
}
if (images.get(0).exposure != 0) {
IJ.error(TITLE, "First image in series must have exposure 0 (Bias image)");
return;
}
}
final boolean emMode = (arg != null && arg.contains("em"));
GenericDialog gd = new GenericDialog(TITLE);
gd.addMessage("Set the output options:");
gd.addCheckbox("Show_table", settings.showTable);
gd.addCheckbox("Show_charts", settings.showCharts);
if (emMode) {
// Ask the user for the camera gain ...
gd.addMessage("Estimating the EM-gain requires the camera gain without EM readout enabled");
gd.addNumericField("Camera_gain (Count/e-)", settings.cameraGain, 4);
}
if (emMode) {
helpKey += "-em-ccd";
}
gd.addHelp(HelpUrls.getUrl(helpKey));
gd.showDialog();
if (gd.wasCanceled()) {
return;
}
settings.showTable = gd.getNextBoolean();
settings.showCharts = gd.getNextBoolean();
if (emMode) {
settings.cameraGain = gd.getNextNumber();
}
IJ.showStatus("Computing mean & variance");
final double nImages = images.size();
for (int i = 0; i < images.size(); i++) {
IJ.showStatus(String.format("Computing mean & variance %d/%d", i + 1, images.size()));
images.get(i).compute(singleImage, i / nImages, (i + 1) / nImages);
}
IJ.showProgress(1);
IJ.showStatus("Computing results");
// Allow user to input multiple bias images
int start = 0;
final Statistics biasStats = new Statistics();
final Statistics noiseStats = new Statistics();
final double bias;
if (singleImage) {
bias = settings.bias;
} else {
while (start < images.size()) {
final ImageSample sample = images.get(start);
if (sample.exposure == 0) {
biasStats.add(sample.means);
for (final PairSample pair : sample.samples) {
noiseStats.add(pair.variance);
}
start++;
} else {
break;
}
}
bias = biasStats.getMean();
}
// Get the mean-variance data
int total = 0;
for (int i = start; i < images.size(); i++) {
total += images.get(i).samples.size();
}
if (settings.showTable && total > 2000) {
gd = new GenericDialog(TITLE);
gd.addMessage("Table output requires " + total + " entries.\n \nYou may want to disable the table.");
gd.addCheckbox("Show_table", settings.showTable);
gd.showDialog();
if (gd.wasCanceled()) {
return;
}
settings.showTable = gd.getNextBoolean();
}
final TextWindow results = (settings.showTable) ? createResultsWindow() : null;
double[] mean = new double[total];
double[] variance = new double[mean.length];
final Statistics gainStats = (singleImage) ? new StoredDataStatistics(total) : new Statistics();
final WeightedObservedPoints obs = new WeightedObservedPoints();
for (int i = (singleImage) ? 0 : start, j = 0; i < images.size(); i++) {
final StringBuilder sb = (settings.showTable) ? new StringBuilder() : null;
final ImageSample sample = images.get(i);
for (final PairSample pair : sample.samples) {
if (j % 16 == 0) {
IJ.showProgress(j, total);
}
mean[j] = pair.getMean();
variance[j] = pair.variance;
// Gain is in Count / e
double gain = variance[j] / (mean[j] - bias);
gainStats.add(gain);
obs.add(mean[j], variance[j]);
if (emMode) {
gain /= (2 * settings.cameraGain);
}
if (sb != null) {
sb.append(sample.title).append('\t');
sb.append(sample.exposure).append('\t');
sb.append(pair.slice1).append('\t');
sb.append(pair.slice2).append('\t');
sb.append(IJ.d2s(pair.mean1, 2)).append('\t');
sb.append(IJ.d2s(pair.mean2, 2)).append('\t');
sb.append(IJ.d2s(mean[j], 2)).append('\t');
sb.append(IJ.d2s(variance[j], 2)).append('\t');
sb.append(MathUtils.rounded(gain, 4)).append("\n");
}
j++;
}
if (results != null && sb != null) {
results.append(sb.toString());
}
}
IJ.showProgress(1);
if (singleImage) {
StoredDataStatistics stats = (StoredDataStatistics) gainStats;
ImageJUtils.log(TITLE);
if (emMode) {
final double[] values = stats.getValues();
MathArrays.scaleInPlace(0.5, values);
stats = StoredDataStatistics.create(values);
}
if (settings.showCharts) {
// Plot the gain over time
final String title = TITLE + " Gain vs Frame";
final Plot plot = new Plot(title, "Slice", "Gain");
plot.addPoints(SimpleArrayUtils.newArray(gainStats.getN(), 1, 1.0), stats.getValues(), Plot.LINE);
final PlotWindow pw = ImageJUtils.display(title, plot);
// Show a histogram
final String label = String.format("Mean = %s, Median = %s", MathUtils.rounded(stats.getMean()), MathUtils.rounded(stats.getMedian()));
final WindowOrganiser wo = new WindowOrganiser();
final PlotWindow pw2 = new HistogramPlotBuilder(TITLE, stats, "Gain").setRemoveOutliersOption(1).setPlotLabel(label).show(wo);
if (wo.isNotEmpty()) {
final Point point = pw.getLocation();
point.y += pw.getHeight();
pw2.setLocation(point);
}
}
ImageJUtils.log("Single-image mode: %s camera", (emMode) ? "EM-CCD" : "Standard");
final double gain = stats.getMedian();
if (emMode) {
final double totalGain = gain;
final double emGain = totalGain / settings.cameraGain;
ImageJUtils.log(" Gain = 1 / %s (Count/e-)", MathUtils.rounded(settings.cameraGain, 4));
ImageJUtils.log(" EM-Gain = %s", MathUtils.rounded(emGain, 4));
ImageJUtils.log(" Total Gain = %s (Count/e-)", MathUtils.rounded(totalGain, 4));
} else {
settings.cameraGain = gain;
ImageJUtils.log(" Gain = 1 / %s (Count/e-)", MathUtils.rounded(settings.cameraGain, 4));
}
} else {
IJ.showStatus("Computing fit");
// Sort
final int[] indices = rank(mean);
mean = reorder(mean, indices);
variance = reorder(variance, indices);
// Compute optimal coefficients.
// a - b x
final double[] init = { 0, 1 / gainStats.getMean() };
final PolynomialCurveFitter fitter = PolynomialCurveFitter.create(2).withStartPoint(init);
final double[] best = fitter.fit(obs.toList());
// Construct the polynomial that best fits the data.
final PolynomialFunction fitted = new PolynomialFunction(best);
if (settings.showCharts) {
// Plot mean verses variance. Gradient is gain in Count/e.
final String title = TITLE + " results";
final Plot plot = new Plot(title, "Mean", "Variance");
final double[] xlimits = MathUtils.limits(mean);
final double[] ylimits = MathUtils.limits(variance);
double xrange = (xlimits[1] - xlimits[0]) * 0.05;
if (xrange == 0) {
xrange = 0.05;
}
double yrange = (ylimits[1] - ylimits[0]) * 0.05;
if (yrange == 0) {
yrange = 0.05;
}
plot.setLimits(xlimits[0] - xrange, xlimits[1] + xrange, ylimits[0] - yrange, ylimits[1] + yrange);
plot.setColor(Color.blue);
plot.addPoints(mean, variance, Plot.CROSS);
plot.setColor(Color.red);
plot.addPoints(new double[] { mean[0], mean[mean.length - 1] }, new double[] { fitted.value(mean[0]), fitted.value(mean[mean.length - 1]) }, Plot.LINE);
ImageJUtils.display(title, plot);
}
final double avBiasNoise = Math.sqrt(noiseStats.getMean());
ImageJUtils.log(TITLE);
ImageJUtils.log(" Directory = %s", inputDirectory);
ImageJUtils.log(" Bias = %s +/- %s (Count)", MathUtils.rounded(bias, 4), MathUtils.rounded(avBiasNoise, 4));
ImageJUtils.log(" Variance = %s + %s * mean", MathUtils.rounded(best[0], 4), MathUtils.rounded(best[1], 4));
if (emMode) {
// The gradient is the observed gain of the noise.
// In an EM-CCD there is a noise factor of 2.
// Q. Is this true for a correct noise factor calibration:
// double noiseFactor = (Read Noise EM-CCD) / (Read Noise CCD)
// Em-gain is the observed gain divided by the noise factor multiplied by camera gain
final double emGain = best[1] / (2 * settings.cameraGain);
// Compute total gain
final double totalGain = emGain * settings.cameraGain;
final double readNoise = avBiasNoise / settings.cameraGain;
// Effective noise is standard deviation of the bias image divided by the total gain (in
// Count/e-)
final double readNoiseE = avBiasNoise / totalGain;
ImageJUtils.log(" Read Noise = %s (e-) [%s (Count)]", MathUtils.rounded(readNoise, 4), MathUtils.rounded(avBiasNoise, 4));
ImageJUtils.log(" Gain = 1 / %s (Count/e-)", MathUtils.rounded(1 / settings.cameraGain, 4));
ImageJUtils.log(" EM-Gain = %s", MathUtils.rounded(emGain, 4));
ImageJUtils.log(" Total Gain = %s (Count/e-)", MathUtils.rounded(totalGain, 4));
ImageJUtils.log(" Effective Read Noise = %s (e-) (Read Noise/Total Gain)", MathUtils.rounded(readNoiseE, 4));
} else {
// The gradient is the observed gain of the noise.
settings.cameraGain = best[1];
// Noise is standard deviation of the bias image divided by the gain (in Count/e-)
final double readNoise = avBiasNoise / settings.cameraGain;
ImageJUtils.log(" Read Noise = %s (e-) [%s (Count)]", MathUtils.rounded(readNoise, 4), MathUtils.rounded(avBiasNoise, 4));
ImageJUtils.log(" Gain = 1 / %s (Count/e-)", MathUtils.rounded(1 / settings.cameraGain, 4));
}
}
IJ.showStatus("");
}
Aggregations