keyword stringclasses 7 values | repo_name stringlengths 8 98 | file_path stringlengths 4 244 | file_extension stringclasses 29 values | file_size int64 0 84.1M | line_count int64 0 1.6M | content stringlengths 1 84.1M ⌀ | language stringclasses 14 values |
|---|---|---|---|---|---|---|---|
2D | SMLM-Challenge/Challenge2016 | Simulator/Simulator-Java/src/smlms/sample/SampleFactory_2016.java | .java | 200 | 14 | package smlms.sample;
public class SampleFactory_2016 {
public SampleFactory_2016() {
new SampleFactoryDialog();
}
public static void main(String args[]) {
new SampleFactoryDialog();
}
}
| Java |
2D | SMLM-Challenge/Challenge2016 | Simulator/Simulator-Java/src/smlms/sample/Beads_Generator.java | .java | 3,263 | 120 | package smlms.sample;
import ij.IJ;
import java.util.ArrayList;
import smlms.file.PositionFile;
import smlms.tools.Point3D;
import smlms.tools.PsRandom;
import additionaluserinterface.WalkBar;
public class Beads_Generator {
private int nx = 6400; // 320 * 20 = 6400nm
private int ny = 6400; // 320 * 20 = 6400nm
private int nz = 1500; // 25 * 20 = 1500nm
private double rmax = 50;
private double rmin = 200;
private double tolerance = 80;
private double zoff = 750;
private String filename = "/Users/sage/Desktop/positions-BD.csv";
private int nbeads = 44;
private int nfluos = 120000;
private PsRandom rand = new PsRandom(1234);
private WalkBar walk = new WalkBar("(c) 2016 EPFL, BIG", false, false, true);
public class Bead {
public double x;
public double y;
public double z;
public double r;
public Bead(double x, double y, double z, double r) {
this.x = x;
this.y = y;
this.z = z;
this.r = r;
}
public double distance(Bead bead) {
double d = (x-bead.x)*(x-bead.x) + (y-bead.y)*(y-bead.y) + (z-bead.z)*(z-bead.z);
return Math.sqrt(d) - r - bead.r;
}
public String toString() {
return "Bead " + x + " " + y + " " + z + " " + r;
}
}
public static void main(String args[]) {
new Beads_Generator();
}
public Beads_Generator() {
ArrayList<Bead> beads = new ArrayList<Bead>();
beads.add(create());
for (int i=0; i<nbeads; i++) {
Bead bead = (rand.nextDouble() < 0.6 ? create() : create(beads.get(beads.size()-1)));
boolean close = false;
for(int b=0; b<beads.size(); b++)
if (bead.distance(beads.get(b)) < tolerance)
close = true;
if (!close)
beads.add(bead);
}
int count = 0;
double volume[] = new double[beads.size()];
for(Bead bead : beads) {
volume[count] = (count == 0 ? 0.0 : volume[count-1]) + 4.0*Math.PI/3.0*bead.r*bead.r*bead.r;
IJ.log("" + (count) + " / "+ bead.toString() + " / " + volume[count]);
count++;
}
double max = volume[count-1];
ArrayList<Point3D> positions = new ArrayList<Point3D>();
for(int i=0; i<nfluos; i++) {
double v = rand.nextDouble(0, max);
int k = 0;
for(k=0; k<volume.length; k++)
if (v < volume[k])
break;
Bead bead = beads.get(k);
double r = bead.r;
double x = rand.nextDouble(bead.x - r, bead.x + r);
double y = rand.nextDouble(bead.y - r, bead.y + r);
double z = rand.nextDouble(bead.z - r, bead.z + r);
double d = Math.sqrt((x-bead.x)*(x-bead.x) + (y-bead.y)*(y-bead.y) + (z-bead.z)*(z-bead.z));
if (d < r)
positions.add(new Point3D(x, y, z-zoff));
}
new PositionFile(walk, filename).save(positions);
}
public Bead create() {
double r = rand.nextDouble(rmin, rmax);
double x = rand.nextDouble(r+8*tolerance, nx-r-8*tolerance);
double y = rand.nextDouble(r+8*tolerance, ny-r-8*tolerance);
double z = rand.nextDouble(r+2*tolerance, nz-r-2*tolerance);
return new Bead(x, y, z, r);
}
public Bead create(Bead bead) {
double x = bead.x + rand.nextDouble(-bead.r*1.5, bead.r*1.5);
double y = bead.y + rand.nextDouble(-bead.r*1.5, bead.r*1.5);
double r = rand.nextDouble(rmin, rmax*0.5);
double z = rand.nextDouble(r+tolerance, nz-r-tolerance);
return new Bead(x, y, z, r);
}
}
| Java |
2D | SMLM-Challenge/Challenge2016 | Simulator/Simulator-Java/src/smlms/file/Description.java | .java | 6,919 | 222 | package smlms.file;
import ij.IJ;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import smlms.tools.Tools;
public class Description {
private HashMap<Integer, Fields> fields = new HashMap<Integer, Fields>();
public LinearTransformAxis axisX = new LinearTransformAxis();
public LinearTransformAxis axisY = new LinearTransformAxis();
public LinearTransformAxis axisZ = new LinearTransformAxis();
public LinearTransformAxis axisT = new LinearTransformAxis();
public int numberOfHeadingRows = 0;
private String description = "";
public static void main(String args[]) {
Description desc1 = new Description();
System.out.println("Desc1 \n" + desc1.toString());
Description desc2 = new Description("# sigmax Xnm Ypix ? * Z frame 3 ; X 100 ; T 0.5 0.3 ");
System.out.println("Desc2 \n" + desc2.toString());
Description desc3 = new Description("/Users/sage/Desktop/des.txt");
System.out.println("Desc3 \n" + desc3.toString());
Description desc4 = new Description("activations");
System.out.println("Desc4 \n" + desc4.toString());
}
public static String getDescriptionPath() {
String s = System.getProperty("user.home") + File.separator + "Desktop" + File.separator + "smlms-data" + File.separator + "descriptions" + File.separator;
new File(s).mkdir();
return s;
}
public Description() {
fields.put(1, Fields.ID);
fields.put(2, Fields.X);
fields.put(3, Fields.Y);
fields.put(4, Fields.Z);
fields.put(5, Fields.FRAME);
fields.put(6, Fields.PHOTONS);
}
// Type | Field_sorted_by_columns | ScaleX Y Z T | ShiftX Y Z T
// Type | ID X Y Z * * FRAME | 100 100 1 1 | 0.5 0.5 0.5 0
public Description(String line) {
if (line == null)
return;
line = line.trim();
String items[] = line.split("#");
IJ.log("DECOMPOSE " + line);
if (items.length == 3) {
line = items[1];
IJ.log("IN FILE " + line);
}
else {
File file = new File(getDescriptionPath() + line);
if (file.exists()) {
try {
BufferedReader buffer = new BufferedReader(new FileReader(getDescriptionPath() + line));
line = buffer.readLine();
buffer.close();
}
catch (Exception ex) {
line = "Error in reading " + getDescriptionPath() + line;
}
}
}
line = line.toLowerCase();
description = line.trim();
String features[] = description.split(";");
for (String feature : features) {
String feat = feature.trim().toLowerCase();
if (feat.startsWith("#")) {
createFields(feat);
numberOfHeadingRows = (int) Tools.extractDouble(feat);
}
if (feat.startsWith("x"))
axisX = createAxis(feat);
if (feat.startsWith("y"))
axisY = createAxis(feat);
if (feat.startsWith("z"))
axisZ = createAxis(feat);
if (feat.startsWith("t"))
axisT = createAxis(feat);
}
for (int i = 0; i < fields.size(); i++)
IJ.log("Create Column " + i + " > Fields " + fields.get(i));
IJ.log(" AXIS X " + axisX.a + " " + axisX.b);
}
public void addField(String add) {
String sf = "# ";
Iterator<Integer> iterator = fields.keySet().iterator();
while (iterator.hasNext()) {
Integer mentry = iterator.next();
sf += fields.get(mentry) + " ";
}
createFields(sf + add);
}
public String getDecription() {
return description;
}
public String createDescriptionLine() {
String sf = "# ";
Iterator<Integer> iterator = fields.keySet().iterator();
while (iterator.hasNext()) {
Integer mentry = iterator.next();
sf += fields.get(mentry) + " ";
}
if (numberOfHeadingRows > 0)
sf += " " + numberOfHeadingRows + "; ";
else
sf += "; ";
String sx = axisX.b == 0.0 ? (axisX.a == 1.0 ? "" : "X " + axisX.a + "; ") : "X " + axisX.a + " " + axisX.b + "; ";
String sy = axisY.b == 0.0 ? (axisY.a == 1.0 ? "" : "Y " + axisY.a + "; ") : "Y " + axisY.a + " " + axisY.b + "; ";
String sz = axisZ.b == 0.0 ? (axisZ.a == 1.0 ? "" : "Z " + axisZ.a + "; ") : "Z " + axisZ.a + " " + axisZ.b + "; ";
String st = axisT.b == 0.0 ? (axisT.a == 1.0 ? "" : "T " + axisT.a + "; ") : "T " + axisT.a + " " + axisT.b + "; ";
description = sf + sx + sy + sz + st;
return description;
}
public static String[] getRegisteredDescription() {
String path = getDescriptionPath();
File dir = new File(path);
dir.mkdir();
String list[] = dir.list();
ArrayList<String> listValid = new ArrayList<String>();
for (int i = 0; i < list.length; i++) {
if (!list[i].startsWith(".")) {
listValid.add(list[i]);
}
}
String[] listFinal = new String[listValid.size()];
for (int i = 0; i < listFinal.length; i++) {
listFinal[i] = listValid.get(i);
}
return listFinal;
}
public HashMap<Integer, Fields> getFields() {
return fields;
}
public boolean[] getActiveFields() {
boolean activeFields[] = new boolean[Fluorophore.vectorSize()];
for (int i = 0; i < activeFields.length; i++)
activeFields[i] = false;
String names[] = Fluorophore.vectorNames();
Iterator<Integer> iterator = fields.keySet().iterator();
while (iterator.hasNext()) {
Integer mentry = iterator.next();
for (int i = 0; i < names.length; i++) {
if (names[i].toLowerCase().equals(fields.get(mentry).name().toLowerCase()))
activeFields[i] = true;
}
}
return activeFields;
}
public String toString() {
String s = "Fields: ";
Iterator<Integer> iterator = fields.keySet().iterator();
while (iterator.hasNext()) {
Integer mentry = iterator.next();
s += " " + mentry.toString() + "=" + fields.get(mentry);
}
s += " HeadingRows=" + numberOfHeadingRows + ";\n";
s += "AxisX: " + axisX.a + " * x + " + axisX.b + "; ";
s += "AxisY: " + axisY.a + " * y + " + axisY.b + "; ";
s += "AxisZ: " + axisZ.a + " * z + " + axisZ.b + "; ";
s += "AxisT: " + axisT.a + " * t + " + axisT.b + ";\n";
return s;
}
private void createFields(String text) {
String words[] = text.trim().split("[,:; \t]");
Fields[] types = Fields.values();
fields.clear();
for (int i = 0; i < words.length; i++) {
String word = words[i].trim().toLowerCase();
for (int j = 0; j < types.length; j++) {
if (word.startsWith(types[j].getFieldDescription())) {
int in = fields.size() + 1;
fields.put(in, types[j]);
}
}
}
}
private LinearTransformAxis createAxis(String text) {
LinearTransformAxis axis = new LinearTransformAxis();
ArrayList<Double> doubles = Tools.extractDoubles(text);
axis.a = doubles.size() >= 1 ? doubles.get(0) : 1.0;
axis.b = doubles.size() >= 2 ? doubles.get(1) : 0.0;
return axis;
}
private String getExtension(File f) {
String ext = "";
String s = f.getName();
int i = s.lastIndexOf('.');
if (i > 0 && i < s.length() - 1)
ext = s.substring(i + 1).toLowerCase();
return ext;
}
}
| Java |
2D | SMLM-Challenge/Challenge2016 | Simulator/Simulator-Java/src/smlms/file/FluorophoreComponent.java | .java | 6,254 | 196 | package smlms.file;
import ij.IJ;
import imageware.ImageWare;
import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFileChooser;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import smlms.rendering.Rendering;
import smlms.tools.ArrayOperations;
import smlms.tools.Chart;
import smlms.tools.Point3D;
import smlms.tools.Volume;
import additionaluserinterface.GridPanel;
import additionaluserinterface.Settings;
import additionaluserinterface.SpinnerDouble;
public class FluorophoreComponent extends JPanel implements ActionListener, Runnable {
private Settings settings;
private JButton bnBrowse = new JButton("Browse");
private JButton bnLoad = new JButton("Load");
private JComboBox cmbFormat = new JComboBox();
private JButton bnPreview = new JButton("Preview");
private JButton bnStats = new JButton("Stats");
private JButton bnHisto = new JButton("Histo");
private JButton bnEvolution = new JButton("Frames");
private boolean descriptionToChoose = false;
private SpinnerDouble spnPixelsize = new SpinnerDouble(40, 0.01, 1000, 1);
public JTextField txtFile = new JTextField("-", 20);
public JLabel lblInfo = new JLabel("----------------");
private Fluorophores fluos = null;
private Thread thread = null;
private JTextField lblFormat = new JTextField("", 20);
public FluorophoreComponent(Settings settings, String name) {
descriptionToChoose = true;
this.settings = settings;
doDialog(name);
}
public FluorophoreComponent(Settings settings, String name, String formatForced) {
this.settings = settings;
cmbFormat.setSelectedItem(formatForced);
descriptionToChoose = false;
doDialog(name);
}
private void doDialog(String name) {
settings.record("fluorophores-spnPixelsize-"+name, spnPixelsize, "100");
settings.record("fluorophores-txtFile-"+name, txtFile, "");
settings.record("fluorophores-cmbFormat-"+name, cmbFormat, "");
lblInfo.setBorder(BorderFactory.createEtchedBorder());
lblFormat.setBorder(BorderFactory.createEtchedBorder());
lblFormat.setEditable(false);
lblFormat.setBackground(new Color(220, 220, 250));
cmbFormat.setEditable(true);
String desc[] = Description.getRegisteredDescription();
cmbFormat.addItem("#format#");
for(int i=0; i<desc.length; i++)
cmbFormat.addItem(desc[i]);
GridPanel pn = new GridPanel(name, 1);
pn.place(1, 0, 4, 1, txtFile);
pn.place(1, 4, bnBrowse);
if (descriptionToChoose) {
pn.place(3, 4, 1, 1, cmbFormat);
pn.place(3, 0, 4, 1, lblFormat);
}
pn.place(2, 0, 4, 1, lblInfo);
pn.place(2, 4, bnLoad);
pn.place(4, 0, bnEvolution);
pn.place(4, 1, bnHisto);
pn.place(4, 2, bnStats);
pn.place(4, 3, bnPreview);
pn.place(4, 4, spnPixelsize);
add(pn);
bnStats.addActionListener(this);
bnBrowse.addActionListener(this);
bnLoad.addActionListener(this);
bnPreview.addActionListener(this);
bnHisto.addActionListener(this);
bnEvolution.addActionListener(this);
cmbFormat.addActionListener(this);
update();
}
@Override
public void actionPerformed(ActionEvent e) {
IJ.log(" " + e);
if (e.getSource() == cmbFormat)
update();
else if (e.getSource() == bnBrowse) {
JFileChooser fc = new JFileChooser();
int ret = fc.showOpenDialog(null);
if (ret == JFileChooser.APPROVE_OPTION)
txtFile.setText(fc.getSelectedFile().getAbsolutePath());
update();
}
else if (e.getSource() == bnPreview) {
if (fluos == null)
return;
Rendering rendering = new Rendering(null, spnPixelsize.get(), 1000000);
Point3D dim = new Point3D(fluos.getXMax(100), fluos.getYMax(100), fluos.getZMax(100));
Volume vol = new Volume(new Point3D(0, 0, 0), dim);
ImageWare image = rendering.projection(fluos, Rendering.Method.GAUSSIAN, Rendering.Amplitude.PHOTONS, vol, spnPixelsize.get()*0.5);
image.show("Render");
}
else if (e.getSource() == bnHisto) {
if (fluos == null)
return;
boolean activeFields[] = new Description((String)cmbFormat.getSelectedItem()).getActiveFields();
Statistics stats[] = fluos.getStats();
for(int i=1; i<stats.length; i++)
if (activeFields[i]) {
Chart chart = new Chart(stats[i].name, "Numbers of fluorophores", stats[i].domain);
chart.add(stats[i].name, stats[i].histo);
chart.show(stats[i].name, 800, 400);
}
}
else if (e.getSource() == bnEvolution) {
if (fluos == null)
return;
boolean activeFields[] = new Description((String)cmbFormat.getSelectedItem()).getActiveFields();
Statistics stats[] = fluos.getStats();
for(int i=1; i<stats.length; i++)
if (activeFields[i]) {
double frames[] = ArrayOperations.ramp(stats[i].evolution.length);
Chart chart = new Chart(stats[i].name, "Sum of " + stats[i].name, frames);
chart.add(stats[i].name, stats[i].evolution);
chart.show(stats[i].name, 800, 400);
}
}
else if (e.getSource() == bnStats) {
IJ.log(" " + (fluos == null));
if (fluos == null)
return;
TableStatistics table = new TableStatistics("Fluorophores", fluos.getStats());
table.show(500, 300);
}
else if (e.getSource() == bnLoad) {
if (thread == null) {
thread = new Thread(this);
thread.setPriority(Thread.MIN_PRIORITY);
thread.start();
}
}
}
private void update() {
Description desc = new Description((String)cmbFormat.getSelectedItem());
lblFormat.setText(desc.getDecription());
}
public String[] getSource() {
return new String[] {txtFile.getText(), (String)cmbFormat.getSelectedItem(), lblInfo.getText()};
}
public Fluorophores getFluorophores() {
return fluos;
}
public void setFluorophores(Fluorophores fluos) {
this.fluos = fluos;
}
public Fluorophores[] getFluorophoresPerFrames() {
return fluos.reshapeInFrames();
}
public void run() {
Description.getDescriptionPath();
Description desc = new Description((String)cmbFormat.getSelectedItem());
update();
fluos = Fluorophores.load(txtFile.getText(), desc, lblInfo);
fluos.computeStats();
thread = null;
}
}
| Java |
2D | SMLM-Challenge/Challenge2016 | Simulator/Simulator-Java/src/smlms/file/Fluorophores_Explorer.java | .java | 1,134 | 45 | package smlms.file;
import ij.IJ;
import ij.gui.GUI;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFrame;
import additionaluserinterface.GridPanel;
import additionaluserinterface.Settings;
public class Fluorophores_Explorer extends JDialog implements ActionListener {
private Settings settings = new Settings("localization-microscopy", IJ.getDirectory("plugins") + "smlm-2016.txt");
private JButton bnClose = new JButton("Close");
private FluorophoreComponent pane = new FluorophoreComponent(settings, "Source");
public static void main(String args[]) {
new Fluorophores_Explorer("name");
}
public Fluorophores_Explorer(String name) {
super(new JFrame(), "Fluorophore Panel " + name);
GridPanel main = new GridPanel(false);
main.place(0, 0, pane);
main.place(4, 0, bnClose);
add(main);
bnClose.addActionListener(this);
pack();
GUI.center(this);
setModal(true);
setVisible(true);
}
@Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() == bnClose)
dispose();
}
}
| Java |
2D | SMLM-Challenge/Challenge2016 | Simulator/Simulator-Java/src/smlms/file/Fields.java | .java | 1,203 | 56 | package smlms.file;
import java.util.HashMap;
import java.util.Iterator;
public enum Fields {
ID ("id"),
X ("x"), // in nm
Y ("y"), // in nm
Z ("z"), // in nm
FRAME ("frame"),
PHOTONS ("photons"),
CHANNEL ("channel"),
FRAMEON ("frameon"), // number of frame ON
TOTAL ("total"),
BACKGROUND_MEAN ("background"),
BACKGROUND_STDEV ("noise"),
SIGNAL_MEAN ("intensity"),
SIGNAL_STDEV ("stdev"),
SIGNAL_PEAK ("peak"),
SIGMAX ("sigmax"),
SIGMAY ("sigmay"),
SIGMAZ ("sigmaz"),
UNCERTAINTY ("uncertainty"),
CLOSEST_ID ("closestid"),
CLOSEST_DIST ("closestdistance"),
CLOSEST_COUNT ("closestcount"),
PSNR ("psnr"),
SNR ("snr"),
CNR ("cnr"),
UNKNOWN ("?"),
NOTUSED ("*")
;
private final String fieldDescription;
private Fields(String value) {
fieldDescription = value;
}
public String getFieldDescription() {
return fieldDescription;
}
public static Fields getFields(int i, HashMap<Fields, Integer> fields) {
Iterator<Fields> iterator = fields.keySet().iterator();
while (iterator.hasNext()) {
Fields mentry = iterator.next();
if (i == fields.get(mentry))
return mentry;
}
return null;
}
}
| Java |
2D | SMLM-Challenge/Challenge2016 | Simulator/Simulator-Java/src/smlms/file/TableStatistics.java | .java | 3,263 | 134 | package smlms.file;
import ij.IJ;
import java.awt.Dimension;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableModel;
public class TableStatistics extends JTable {
private Statistics[] stats;
private String name;
private String[] headers = new String[] {"Feature", "Count", "Min", "Max", "Mean", "Stdev"};
public TableStatistics(String name) {
super();
((DefaultTableModel) getModel()).setColumnIdentifiers(headers);
setAutoCreateRowSorter(true);
update();
}
public TableStatistics(String name, Statistics[] stats) {
super();
this.stats = stats;
((DefaultTableModel) getModel()).setColumnIdentifiers(headers);
setAutoCreateRowSorter(true);
update();
}
public JScrollPane pane(int width, int height) {
JScrollPane scrollpane = new JScrollPane(this);
scrollpane.setPreferredSize(new Dimension(width, height));
return scrollpane;
}
public void show(int width, int height) {
JScrollPane pane = pane(width, height);
JFrame frame = new JFrame(name);
frame.add(pane);
frame.pack();
frame.setVisible(true);
}
public int getRow(int id) {
for (int row = 0; row < getRowCount(); row++) {
if (((Integer)getValueAt(row, 0)) == id)
return row;
}
return -1;
}
public void update(Statistics[] stats) {
this.stats = stats;
update();
}
public void update(ArrayList<Statistics> astats) {
if (astats.size() <= 0)
return;
this.stats = new Statistics[astats.size()];
for(int i=0; i<astats.size(); i++)
this.stats[i] = astats.get(i);
update();
}
public void update() {
DefaultTableModel model = (DefaultTableModel) getModel();
model.getDataVector().removeAllElements();
if (stats == null)
return;
int nrow = stats.length;
for (int j=0; j<nrow; j++) {
Object o[] = new Object[6];
o[0] = stats[j].name;
o[1] = stats[j].count;
o[2] = stats[j].min;
o[3] = stats[j].max;
o[4] = stats[j].mean;
o[5] = stats[j].stdev;
model.addRow(o);
}
repaint();
}
public void saveCVS(String filename) {
File file = new File(filename);
try {
BufferedWriter buffer = new BufferedWriter(new FileWriter(file));
String s = "";
for (int i = 0; i < headers.length; i++)
s += headers[i] + ",";
buffer.write(s + "\n");
TableModel model = this.getModel();
int ncols = model.getColumnCount();
int nrows = model.getRowCount();
for (int row = 0; row < nrows; row++) {
s = "";
s += model.getValueAt(row, 0) + ",";
s += model.getValueAt(row, 1) + ",";
for (int col = 2; col < ncols - 1; col++) {
try {
s += IJ.d2s(Double.parseDouble(""+model.getValueAt(row, col)), 3) + ",";
}
catch(Exception ex) {
s += model.getValueAt(row, col) + ",";
}
}
try {
s += IJ.d2s(Double.parseDouble(""+model.getValueAt(row, ncols-1)), 3);
}
catch(Exception ex) {
s += model.getValueAt(row, ncols-1) + ",";
}
buffer.write(s + "\n");
}
buffer.close();
}
catch (IOException ex) {
System.out.println("" + ex);
}
}
}
| Java |
2D | SMLM-Challenge/Challenge2016 | Simulator/Simulator-Java/src/smlms/file/Fluorophores.java | .java | 6,447 | 244 | package smlms.file;
import ij.IJ;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import javax.swing.JLabel;
public class Fluorophores extends ArrayList<Fluorophore> {
private Statistics[] stats;
public Fluorophores() {
super();
}
static public Fluorophores load(String filename, Description desc, JLabel lblNotification) {
Fluorophores fluorophores = new Fluorophores();
IJ.log("Load:" + filename);
int readingErrors = 0;
try {
BufferedReader buffer = new BufferedReader(new FileReader(filename));
HashMap<Integer, Fields> fields = desc.getFields();
for(int i=1; i<fields.size()+1; i++)
IJ.log("Column " + i + " > " + fields.get(i));
int lineNumber = 0;
String line = readLine(buffer);
for(int i=0; i<desc.numberOfHeadingRows; i++)
line = readLine(buffer);
while (line != null) {
try {
String words[] = line.trim().split("[,:;\t]");
Fluorophore fluo = new Fluorophore();
for(int i=0; i<words.length; i++) {
Fields f = fields.get(i+1);
if (f == Fields.X)
fluo.x = desc.axisX.transform(Double.parseDouble(words[i]));
if (f == Fields.Y)
fluo.y = desc.axisY.transform(Double.parseDouble(words[i]));
if (f == Fields.Z)
fluo.z = desc.axisZ.transform(Double.parseDouble(words[i]));
if (f == Fields.PHOTONS)
fluo.photons = Double.parseDouble(words[i]);
if (f == Fields.FRAME)
fluo.frame = (int)desc.axisT.transform((int)Double.parseDouble(words[i]));
if (f == Fields.ID)
fluo.id = (int)Double.parseDouble(words[i]);
}
fluorophores.add(fluo);
}
catch (Exception e) {
IJ.log("Error in line number:" + lineNumber + " <" + line + "> " );
readingErrors++;
}
line = readLine(buffer);
lineNumber++;
if (lblNotification != null && lineNumber % 100 == 0)
lblNotification.setText("fluos:" + fluorophores.size() + " error:" + readingErrors);
}
if (lblNotification != null)
lblNotification.setText("fluos:" + fluorophores.size() + " error:" + readingErrors);
}
catch (Exception ex) {
IJ.log(ex.toString());
}
IJ.log("End of reading:" + fluorophores.size() + " fluos");
return fluorophores;
}
public void save(String filename) {
(new File(filename)).getParentFile().mkdir();
File file = new File(filename);
try {
BufferedWriter buffer = new BufferedWriter(new FileWriter(file));
int count = 0;
for(Fluorophore fluo : this) {
String s = "";
s += "" + (++count) + ", ";
s += IJ.d2s(fluo.frame, 0) + ", ";
s += IJ.d2s(fluo.x, 5) + ", ";
s += IJ.d2s(fluo.y, 5) + ", ";
s += IJ.d2s(fluo.z, 5) + ", ";
s += IJ.d2s(fluo.photons, 5);
buffer.write(s + "\n");
}
buffer.close();
}
catch (IOException ex) {
}
}
/*
public void save(ArrayList<Point3D> positions) {
(new File(filename)).getParentFile().mkdir();
File file = new File(filename);
if (walk != null)
walk.reset();
try {
BufferedWriter buffer = new BufferedWriter(new FileWriter(file));
double n = positions.size();
int count = 0;
for(Point3D position : positions) {
String s = "";
s += IJ.d2s(position.x, 5) + ", ";
s += IJ.d2s(position.y, 5) + ", ";
s += IJ.d2s(position.z, 5);
buffer.write(s + "\n");
count++;
if (walk != null & count % 100 == 0)
walk.progress("" + count, 100.0*count/n);
}
IJ.log("Number of saved fluorophores: " + count);
buffer.close();
}
catch (IOException ex) {
IJ.error("IOException");
}
walk.finish();
}
*/
public Statistics[] getStats() {
if (stats == null)
computeStats();
return stats;
}
public int getFrameMax() {
if (stats == null)
computeStats();
return (int)Math.ceil(stats[4].max);
}
public double getXMax(int round) {
if (stats == null)
computeStats();
return (int)Math.ceil((stats[1].max*round))/round;
}
public double getYMax(int round) {
if (stats == null)
computeStats();
return (int)Math.ceil((stats[2].max*round))/round;
}
public double getZMax(int round) {
if (stats == null)
computeStats();
return (int)Math.ceil((stats[2].max*round))/round;
}
public void computeStats() {
String[] names = Fluorophore.vectorNames();
int n = Fluorophore.vectorSize();
stats = new Statistics[n];
int nfluo = size();
for(int i=0; i<n; i++)
stats[i] = new Statistics(names[i]);
for(Fluorophore fluo : this) {
double[] vect = fluo.vectorValues();
for(int i=0; i<n; i++) {
stats[i].count++;
stats[i].min = Math.min(stats[i].min, vect[i]);
stats[i].max = Math.max(stats[i].max, vect[i]);
stats[i].mean += vect[i];
stats[i].stdev += vect[i] * vect[i];
}
}
if (nfluo > 0) {
for(int i=0; i<n; i++) {
stats[i].mean /= nfluo;
stats[i].stdev = Math.sqrt(stats[i].stdev*n - stats[i].mean*stats[i].mean)/nfluo;
}
for(Fluorophore fluo : this) {
double[] vect = fluo.vectorValues();
for(int i=0; i<n; i++) {
stats[i].addHisto(vect[i]);
}
}
}
int nframes = getFrameMax() + 1;
int count[] = new int[nframes];
for(int i=0; i<n; i++)
stats[i].evolution = new double[nframes];
for(Fluorophore fluo : this) {
double[] vect = fluo.vectorValues();
int frame = (int)vect[4];
if (frame >= 0 && frame < nframes)
for(int i=0; i<n; i++) {
stats[i].evolution[frame] += vect[i];
count[frame]++;
}
}
for(int f=0; f<nframes; f++) {
if (count[f] > 0)
for(int i=0; i<n; i++) {
stats[i].evolution[f] /= count[f];
}
}
}
public Fluorophores[] reshapeInFrames() {
int nframes = getFrameMax() + 1;
Fluorophores[] fluorophores = new Fluorophores[nframes];
for(int i=0; i<nframes; i++)
fluorophores[i] = new Fluorophores();
for(Fluorophore fluo : this) {
int frame = fluo.frame;
if (frame >= 0 && frame < nframes)
fluorophores[frame].add(fluo);
}
return fluorophores;
}
static public String getInfo(Fluorophores[] fluorophores) {
int count = 0;
for(Fluorophores ff : fluorophores)
count += ff.size();
return "" + count + " fluos " + fluorophores.length + " frames";
}
private static String readLine(BufferedReader buffer) {
try {
return buffer.readLine();
}
catch (Exception e) {
return null;
}
}
}
| Java |
2D | SMLM-Challenge/Challenge2016 | Simulator/Simulator-Java/src/smlms/file/LinearTransformAxis.java | .java | 568 | 37 | package smlms.file;
import java.util.ArrayList;
public class LinearTransformAxis {
public double a = 1.0;
public double b = 0.0;
public LinearTransformAxis() {
}
public LinearTransformAxis(double b) {
this.b = b;
}
public LinearTransformAxis(double a, double b) {
this.a = a;
this.b = b;
}
public double transform(double x) {
return a * x + b;
}
public void set(ArrayList<Double> params) {
if (params.size() == 1)
this.b = params.get(0);
if (params.size() > 1) {
this.a = params.get(0);
this.b = params.get(1);
}
}
}
| Java |
2D | SMLM-Challenge/Challenge2016 | Simulator/Simulator-Java/src/smlms/file/Fluorophore.java | .java | 5,217 | 182 | // =========================================================================================
//
// Project: Localization Microscopy
//
// Author : Daniel Sage, Biomedical Imaging Group (BIG),
// http://bigwww.epfl.ch/sage/
//
// Organization: Ecole Polytechnique F�d�rale de Lausanne (EPFL), Lausanne,
// Switzerland
//
// Conditions of use: You'll be free to use this software for research purposes,
// but you
// should not redistribute it without our consent. In addition, we expect you to
// include a
// citation or acknowledgment whenever you present or publish results that are
// based on it.
//
// =========================================================================================
package smlms.file;
import ij.IJ;
import smlms.tools.Point3D;
public class Fluorophore {
public int id = 0;
public double x = 0.0;
public double y = 0.0;
public double z = 0.0;
public int frame = 0;
public double photons = 1;
public int channel = 0;
public int frameon = 0;
public double total = 1;
public double backgroundMean = 0.0;
public double backgroundStdev = 0.0;
public double signalMean = 0.0;
public double signalStdev = 0.0;
public double signalPeak = 0.0;
public double sigmax = 0.0;
public double sigmay = 0.0;
public double sigmaz = 0.0;
public double uncertainty = 0.0;
public int closestID = 0;
public double closestDistance = 0.0;
public int closestCount = 0;
public double cnr = 0.0;
public double snr = 0.0;
public double psnr = 0.0;
public double unknown = 0.0;
public boolean matching = false;
public Fluorophore() {
}
public Fluorophore(int id, double x, double y, double z, int frame, double photons) {
this.id = id;
this.x = x;
this.y = y;
this.z = z;
this.frame = frame;
this.photons = photons;
}
public void setSNR(double backgroundMean, double backgroundStdev, double signalPeak, double signalMean, double signalStdev) {
this.backgroundMean = backgroundMean;
this.backgroundStdev = backgroundStdev;
this.signalPeak = signalPeak;
this.signalMean = signalMean;
this.signalStdev = signalStdev;
this.psnr = backgroundStdev == 0 ? 0 : (signalPeak / backgroundStdev);
this.cnr = backgroundStdev == 0 ? 0 : (signalPeak - backgroundMean) / backgroundStdev;
double sb = Math.sqrt(backgroundStdev * backgroundStdev + signalStdev * signalStdev);
this.snr = sb == 0 ? 0 : (signalPeak - backgroundMean) / sb;
}
public double[] vectorValues() {
return new double[] { id, x, y, z, frame, photons, channel, frameon, total, backgroundMean, backgroundStdev, signalMean, signalStdev, signalPeak, sigmax, sigmay, sigmaz, uncertainty, closestID, closestDistance, closestCount, cnr, snr, psnr, unknown };
}
public static int vectorSize() {
return vectorNames().length;
}
public static String[] vectorNames() {
return new String[] { "ID", "X", "Y", "Z", "Frame", "Photons", "Channel", "Frame ON", "Total", "Background Mean", "Background Stdev", "Signal Mean", "Signal Stdev", "Signal Peak", "Sigma X", "Sigma Y", "Sigma Z", "Uncertainty", "Closest ID", "Closest Distance", "Closest Count", "CNR", "SNR", "PSNR", "Unknown" };
}
public String vectorValuesAsString() {
double[] values = vectorValues();
String s = "";
for (double v : values)
s += "" + v + ", ";
return s + "\n";
}
public double[] getXYZFramePhotons() {
return new double[] { x, y, z, frame, photons };
}
public double distance(Point3D p) {
return Math.sqrt((p.x - x) * (p.x - x) + (p.y - y) * (p.y - y) + (p.z - z) * (p.z - z));
}
public double distance(Fluorophore f) {
return Math.sqrt((f.x - x) * (f.x - x) + (f.y - y) * (f.y - y) + (f.z - z) * (f.z - z));
}
public double deltaX(Fluorophore fluo) {
return fluo.x - x;
}
public double deltaY(Fluorophore fluo) {
return fluo.y - y;
}
public double deltaZ(Fluorophore fluo) {
return fluo.z - z;
}
public double differenceIntensity(Fluorophore fluo) {
return fluo.photons - photons;
}
public int distanceFrame(Fluorophore fluo) {
return Math.abs(fluo.frame - frame);
}
public double distanceLateral(Fluorophore fluo) {
return Math.sqrt((fluo.x - x) * (fluo.x - x) + (fluo.y - y) * (fluo.y - y));
}
public double distanceAxial(Fluorophore fluo) {
return Math.abs(fluo.z - z);
}
public Point3D scale(double scale) {
return new Point3D(x * scale, y * scale, z * scale);
}
public Point3D negate() {
return new Point3D(-x, -y, -z);
}
public void translate(double dx, double dy, double dz) {
x += dx;
y += dy;
z += dz;
}
public void subtract(Point3D delta) {
x = x - delta.x;
y = y - delta.y;
z = z - delta.z;
}
public Point3D translate(Point3D delta) {
return new Point3D(x + delta.x, y + delta.y, z + delta.z);
}
public static Point3D read(String line) {
String[] tokens = line.split("[,]");
if (tokens.length == 3) {
double x = Double.parseDouble(tokens[0]);
double y = Double.parseDouble(tokens[1]);
double z = Double.parseDouble(tokens[2]);
return new Point3D(x, y, z);
}
else {
return new Point3D(0, 0, 0);
}
}
public String toString() {
return " (" + IJ.d2s(x) + ", " + IJ.d2s(y) + ", " + IJ.d2s(z) + ") A=" + photons;
}
}
| Java |
2D | SMLM-Challenge/Challenge2016 | Simulator/Simulator-Java/src/smlms/file/Description_Builder.java | .java | 4,863 | 173 | package smlms.file;
import ij.IJ;
import ij.gui.GUI;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import javax.swing.BorderFactory;
import javax.swing.DefaultListModel;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.ListSelectionModel;
import javax.swing.table.DefaultTableModel;
import additionaluserinterface.GridPanel;
public class Description_Builder extends JDialog implements ActionListener {
private JButton bnNew = new JButton("New");
private JButton bnSave = new JButton("Save");
private JButton bnClose = new JButton("Close");
private JButton bnReload = new JButton("Reload");
private JList lstFields;
private JLabel lblPath = new JLabel(Description.getDescriptionPath());
private JTable table = new JTable();
public static void main(String args[]) {
new Description_Builder();
}
public Description_Builder() {
super(new JFrame(), "Description Builder");
DefaultTableModel model = ((DefaultTableModel)table.getModel());
model.setColumnIdentifiers(new String[] {"File", "Description"});
table.setAutoCreateRowSorter(true);
table.getColumnModel().getColumn(0).setPreferredWidth(50);
load();
DefaultListModel modelList = new DefaultListModel();
for (int i = 0; i < Fields.values().length; i++)
modelList.addElement(Fields.values()[i].name());
lstFields = new JList(modelList);
lstFields.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
lstFields.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent ev) {
if (ev.getClickCount() == 2)
IJ.log((String) lstFields.getSelectedValue());
}
});
lblPath.setBorder(BorderFactory.createEtchedBorder());
JScrollPane scroll = new JScrollPane(table);
scroll.setPreferredSize(new Dimension(800, 200));
GridPanel pn = new GridPanel("Description File", 1);
pn.place(1, 0, 5, 1, lblPath);
pn.place(2, 0, bnClose);
pn.place(2, 1, bnNew);
pn.place(2, 3, bnReload);
pn.place(2, 4, bnSave);
pn.place(3, 0, 5, 1, scroll);
JScrollPane scFields = new JScrollPane(lstFields);
scFields.setPreferredSize(new Dimension(100, 100));
GridPanel pn1 = new GridPanel("Fields");
pn1.place(0, 0, 1, 1, scFields);
GridPanel main = new GridPanel(false);
main.place(0, 0, pn);
main.place(2, 0, pn1);
add(main);
bnNew.addActionListener(this);
bnSave.addActionListener(this);
bnClose.addActionListener(this);
bnReload.addActionListener(this);
pack();
GUI.center(this);
setModal(true);
setVisible(true);
}
private void load() {
String path = Description.getDescriptionPath();
String desc[] = Description.getRegisteredDescription();
DefaultTableModel model = (DefaultTableModel)table.getModel();
model.getDataVector().removeAllElements();
for(int i=0; i<desc.length; i++) {
String line;
try {
BufferedReader buffer = new BufferedReader(new FileReader(path + desc[i]));
line = buffer.readLine();
buffer.close();
}
catch(Exception ex) {
line ="Error in reading " + path + desc[i];
}
model.addRow(new String[] {desc[i], line});
}
}
public void save() {
DefaultTableModel model = ((DefaultTableModel)table.getModel());
for(int i=0; i<table.getRowCount(); i++) {
IJ.log("saev " + i);
String filename = (String)model.getValueAt(i, 0);
String desc = (String)model.getValueAt(i, 1);
try {
BufferedWriter buffer = new BufferedWriter(new FileWriter(Description.getDescriptionPath() + filename));
buffer.write(desc + "\n");
buffer.close();
}
catch (Exception ex) {
IJ.log("Error saving " + filename);
}
}
}
private void create() {
int row = table.getSelectedRow();
String filename = "Untitled";
String desc = "# X Y FRAME;";
if (row >= 0) {
DefaultTableModel model = ((DefaultTableModel)table.getModel());
filename = (String)model.getValueAt(row, 0) + "-copy";
desc = (String)model.getValueAt(row, 1);
}
try {
BufferedWriter buffer = new BufferedWriter(new FileWriter(Description.getDescriptionPath() + filename));
buffer.write(desc + "\n");
buffer.close();
}
catch (Exception ex) {
IJ.log("Error saving " + filename);
}
save();
load();
}
@Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() == bnReload)
load();
else if (e.getSource() == bnClose) {
dispose();
}
else if (e.getSource() == bnSave) {
save();
}
else if (e.getSource() == bnNew)
create();
}
}
| Java |
2D | SMLM-Challenge/Challenge2016 | Simulator/Simulator-Java/src/smlms/file/PositionFile.java | .java | 1,405 | 58 | package smlms.file;
import ij.IJ;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import smlms.tools.Point3D;
import additionaluserinterface.WalkBar;
public class PositionFile {
private String path;
private String filename;
private WalkBar walk;
public PositionFile(WalkBar walk, String filename) {
this.walk = walk;
this.filename = filename;
this.path = new File(filename).getParent() + File.separator;
}
public PositionFile(WalkBar walk, String path, String name) {
this.walk = walk;
filename = path + File.separator + name;
}
public void save(ArrayList<Point3D> positions) {
(new File(path)).mkdir();
File file = new File(filename);
if (walk != null)
walk.reset();
try {
BufferedWriter buffer = new BufferedWriter(new FileWriter(file));
double n = positions.size();
int count = 0;
for(Point3D position : positions) {
String s = "";
s += IJ.d2s(position.x, 5) + ", ";
s += IJ.d2s(position.y, 5) + ", ";
s += IJ.d2s(position.z, 5);
buffer.write(s + "\n");
count++;
if (walk != null & count % 100 == 0)
walk.progress("" + count, 100.0*count/n);
}
IJ.log("Number of saved fluorophores: " + count + " into " + filename);
buffer.close();
}
catch (IOException ex) {
IJ.error("IOException");
}
walk.finish();
}
}
| Java |
2D | SMLM-Challenge/Challenge2016 | Simulator/Simulator-Java/src/smlms/file/Statistics.java | .java | 871 | 44 | package smlms.file;
public class Statistics {
public String name;
public int count;
public double min;
public double max;
public double mean;
public double stdev;
public double histo[];
public double domain[];
public double evolution[] = new double[1];
private int nbins = 100;
private boolean init = false;
public Statistics(String name) {
this.name = name;
this.count = 0;
this.min = Double.MAX_VALUE;
this.max = -Double.MAX_VALUE;
this.mean = 0.0;
this.stdev = 0.0;
this.domain = new double[nbins];
this.histo = new double[nbins];
}
public void initHisto() {
for(int i=0; i<nbins; i++)
domain[i] = min + i * (max - min) / nbins;
init = true;
}
public void addHisto(double x) {
if (init == false)
initHisto();
int h = (int)(nbins * (x - min) / (max - min));
if (h >= 0)
if (h < nbins)
histo[h]++;
}
}
| Java |
2D | SMLM-Challenge/Challenge2016 | Simulator/Simulator-Java/src/smlms/simulation/SequenceFactory_Batch_2016.java | .java | 7,840 | 222 | package smlms.simulation;
import ij.IJ;
import ij.ImagePlus;
import ij.ImageStack;
import ij.gui.GenericDialog;
import ij.io.FileSaver;
import ij.io.Opener;
import imageware.Builder;
import imageware.ImageWare;
import java.io.File;
import java.util.ArrayList;
import smlms.file.Description;
import smlms.file.Fluorophores;
import smlms.tools.Tools;
import smlms.tools.Zip;
public class SequenceFactory_Batch_2016 {
public static String pathRoot = System.getProperty("user.home") + "/Desktop/activation-final/";
public static String pathPSF = System.getProperty("user.home") + "/Desktop/activation-final/psf/";
public String[] psfsAll = new String[] {"2D-Exp", "AS-Exp", "DH-Exp", "BP-250", "BP+250"};
public String[] psfs3D = new String[] {"AS-Exp", "DH-Exp", "BP-250", "BP+250"};
public String[] psf2D = new String[] {"2D-Exp"};
public String[] psfAS = new String[] {"AS-Exp"};
public String[] psfDH = new String[] {"DH-Exp"};
public String[] psfBP = new String[] {"BP-250", "BP+250"};
public static void main(String args[]) {
SequenceFactory_Batch_2016 sf = new SequenceFactory_Batch_2016();
String[] psfs = new String[] {"2D-Exp", "AS-Exp", "DH-Exp", "BP-000-Exp", "BP-500-Exp"};
sf.run(pathRoot, "FP0.N1", 2000, 100, "activations.csv", true, true, true, true, "");
}
public SequenceFactory_Batch_2016() {
GenericDialog dlg = new GenericDialog("Batch");
dlg.addStringField("Dataset", "MT0.N1.HD");
dlg.addNumericField("Number of Frames", 20000, 0);
dlg.addNumericField("AUtofluorescence", 10, 1);
dlg.addCheckbox("2D", true);
dlg.addCheckbox("AS", true);
dlg.addCheckbox("DH", true);
dlg.addCheckbox("BP", true);
dlg.showDialog();
if (dlg.wasCanceled())
return;
String dataset = dlg.getNextString();
int nframes = (int)dlg.getNextNumber();
double autofluo = dlg.getNextNumber();
boolean d2d= dlg.getNextBoolean();
boolean das = dlg.getNextBoolean();
boolean ddh = dlg.getNextBoolean();
boolean dbp = dlg.getNextBoolean();
run(pathRoot, dataset, nframes, autofluo, "activations.csv", d2d, das, ddh, dbp, "BP-Exp");
//run(pathData, "ER0.N1", 0.7, "activations-20000-frames.csv", psfs3Db, "");
//run(pathData, "ER0.N2", 1.1, "activations-20000-frames.csv", psfs3Db, "");
//run(pathData, "MT2.N1", 0.7, "activations-10000-frames.csv", psfs2D, "");
//run(pathData, "MT2.N2", 1.1, "activations-10000-frames.csv", psfs2D, "");
//run(pathData, "MT2.N1", 0.7, "activations-20000-frames.csv", psfs3Db, "");
//run(pathData, "MT2.N2", 1.1, "activations-20000-frames.csv", psfs3Db, "");
}
public void run(String pathData, String dataset, int nframes, double autofluo, String filename, boolean d2d, boolean das, boolean ddh, boolean dbp, String bpname) {
ArrayList<String> list = new ArrayList<String>();
if (d2d)
list.add(psf2D[0]);
if (das)
list.add(psfAS[0]);
if (ddh)
list.add(psfDH[0]);
if (dbp)
list.add(psfBP[0]);
if (dbp)
list.add(psfBP[1]);
String[] psfs = new String[list.size()];
for(int i=0; i<list.size(); i++)
psfs[i] = list.get(i);
String path = pathData + "/" + dataset + "/";
filename = path + filename;
SequenceFactoryDialog dialog = new SequenceFactoryDialog();
dialog.loadParams();
dialog.settings.loadRecordedItems();
dialog.path = path;
dialog.panel.txtFile.setText(filename);
Fluorophores fluos = Fluorophores.load( filename, new Description("activations"), dialog.panel.lblInfo);
dialog.panel.setFluorophores(fluos);
dialog.panel.getFluorophoresPerFrames();
dialog.chkProjection.setSelected(true);
dialog.chkStats.setSelected(true);
dialog.chkReport.setSelected(true);
IJ.log(" " + fluos.size());
fluos.computeStats();
double chrono = System.nanoTime(); // 1 ou 2 (join)
dialog.tabPSF.setSelectedIndex(3);
for(int i=0; i<dialog.txtPSFFile.length; i++)
dialog.txtPSFFile[i].setText("");
for(int i=0; i<psfs.length; i++)
dialog.txtPSFFile[i].setText(pathPSF + psfs[i] + ".tif");
dialog.cmbCameraQuantization.setSelectedIndex(5); // 16-bits
dialog.spnCameraSaturation.set(65535); // 16-bits
dialog.cmbCameraFileFormat.setSelectedIndex(1); // 16-bits
dialog.spnBiplaneDX.set(77.11);
dialog.spnBiplaneDY.set(17.07);
dialog.spnBiplaneRotation.set(1.9);
dialog.spnBiplaneScale.set(1);
dialog.chkNoises[0].setSelected(true);
dialog.chkNoises[1].setSelected(false);
dialog.chkNoises[2].setSelected(false);
dialog.chkNoises[3].setSelected(true);
dialog.chkNoises[4].setSelected(true);
dialog.chkNoises[5].setSelected(false);
dialog.spnNoises[0].set(74.4);
dialog.spnNoises[1].set(0);
dialog.spnNoises[2].set(0);
dialog.spnNoises[3].set(300);
dialog.spnNoises[4].set(0.002);
dialog.spnQuantumEfficiency.set(0.9);
dialog.spnBaseline.set(100);
dialog.spnCameraGain.set(45);
dialog.spnAutofluoOffsetMean.set(1);
dialog.spnAutofluoOffsetStdv.set(autofluo);
dialog.cmbAutofluoMode.setSelectedIndex(1);
dialog.cmbAutofluoSources.setSelectedIndex(0);
dialog.spnAutofluoGain.set(0);
dialog.spnCameraResolution.set(150);
dialog.spnNA.set(1.49);
dialog.cmbThreading.setSelectedIndex(0);
dialog.spnThickness.set(1500);
dialog.spnLastFrame.set(nframes);
dialog.run();
IJ.log("End Batch " + ((System.nanoTime() - chrono)*1e-9));
String pathbp = path + File.separator + bpname ;
(new File(pathbp)).mkdir();
String pathdata = pathRoot + dataset + File.separator + "Data" + File.separator;
(new File(pathdata)).mkdir();
Tools.copyFile(pathRoot + "data.html", pathdata + "data.html");
String pathOracle = pathRoot + dataset + File.separator + psfs[0] + File.separator + "oracle" + File.separator;
Tools.copyFile(pathOracle + "sequence-parameters.html", pathdata + "parameters.html");
merge(dataset, path+"BP-250/sequence/", path+"BP+250/sequence/", pathdata);
IJ.log("end of " + filename);
}
public void merge(String dataset, String path1, String path2, String pathout) {
IJ.log("Path1 " + path1);
IJ.log("Path2 " + path2);
String list1[] = new File(path1).list();
String list2[] = new File(path2).list();
new File(pathout).mkdir();
new File(pathout + "/sequence").mkdir();
Opener opener = new Opener();
IJ.log("Number of files " + list1.length + " in " + path1);
IJ.log("Number of files " + list2.length + " in " + path2);
ImageStack stack = null;
for(int i=0; i<Math.min(list1.length, list2.length); i++) {
IJ.log(" " + list1[i]);
ImagePlus imp1 = opener.openImage(path1 + list1[i]);
ImagePlus imp2 = opener.openImage(path2 + list2[i]);
ImageWare image1 = Builder.wrap(imp1);
ImageWare image2 = Builder.wrap(imp2);
int nx1 = image1.getSizeX();
int nx2 = image1.getSizeX();
int ny1 = image2.getSizeX();
ImageWare image = Builder.create(nx1+nx2, ny1, 1, image1.getType());
image.putXY(0, 0, 0, image1);
image.putXY(nx1, 0, 0, image2);
ImagePlus imp = new ImagePlus("", image.buildImageStack());
(new FileSaver(imp)).saveAsTiff(pathout + "/sequence/" + File.separator + list1[i]);
if (stack == null)
stack = new ImageStack(nx1+nx2, ny1);
stack.addSlice("", image.buildImageStack().getProcessor(1));
}
String pathdata = pathRoot + dataset + File.separator + "Data" + File.separator;
Zip.zipFolder(pathout + "/sequence/", pathdata + "sequence-" + dataset + "-BP-Exp-as-list.zip");
ImagePlus imps = new ImagePlus("as-stack", stack);
imps.show();
String pathStack = pathout + "/sequence-as-stack" + File.separator;
new File(pathStack).mkdir();
(new FileSaver(imps)).saveAsTiffStack(pathStack + "/sequence-" + dataset + "-BP-Exp-as-stack.tif");
Zip.zipFolder(pathStack, pathdata + "sequence-" + dataset + "-BP-Exp-as-stack.zip");
new File(pathStack).delete();
new File(pathout + "/sequence/").delete();
}
}
| Java |
2D | SMLM-Challenge/Challenge2016 | Simulator/Simulator-Java/src/smlms/simulation/SequenceFactory.java | .java | 16,194 | 475 | package smlms.simulation;
import ij.IJ;
import ij.ImagePlus;
import ij.ImageStack;
import ij.gui.Overlay;
import ij.gui.Roi;
import ij.gui.TextRoi;
import ij.io.FileSaver;
import ij.io.Opener;
import ij.process.FloatProcessor;
import imageware.ImageWare;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.util.ArrayList;
import java.util.Vector;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Future;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import smlms.file.Fluorophore;
import smlms.file.Fluorophores;
import smlms.file.Statistics;
import smlms.file.TableStatistics;
import smlms.tools.Chart;
import smlms.tools.Chrono;
import smlms.tools.Tools;
import smlms.tools.Verbose;
public class SequenceFactory {
public static String names[] = new String[] {"Off-1 Thread", "On-Adaptive", "On 1 Core", "On 2 Cores", "On 4 Cores", "On 8 Cores", "On 16 Cores"};
public int MTHREAD_OFF = 0;
public int MTHREAD_ADAPTATIVE = 1;
public int MTHREAD_1_CORE = 2;
public int MTHREAD_2_CORE = 3;
public int MTHREAD_4_CORE = 4;
public int MTHREAD_8_CORE = 5;
public int MTHREAD_16_CORE = 6;
public static String modes[] = new String[] {"PSF+RAM+Cam", "PSF+File+Cam", "Load+Cam", "PSF+Store"};
private AutofluorescenceModule autofluo;
private NoiseModule noise;
private ProjectionModule projection;
private DownsamplingModule downsampling;
private ArrayList<PSFModule> psfs;
private CameraModule camera;
private int upsamplingConvolve;
private int upsamplingWorking;
private Viewport viewportCamera;
private String pathOracle;
private String pathConvolution;
private String pathProjection;
private String pathSequence;
private String pathFluosFrame;
private String dataset;
private int first = 0;
private int last = 0;
private int interval = 0;
private ImageStack stackSequence;
public SequenceFactory(String dataset, int first, int last, int interval,
CameraModule camera, ArrayList<PSFModule> psfs, NoiseModule noise, AutofluorescenceModule autofluo,
Viewport viewportCamera, int upsamplingConvolve , int upsamplingWorking) {
this.dataset = dataset;
this.first = first;
this.last = last;
this.interval = interval;
this.camera = camera;
this.psfs = psfs;
this.noise = noise;
this.autofluo = autofluo;
this.upsamplingConvolve = upsamplingConvolve;
this.upsamplingWorking = upsamplingWorking;
this.viewportCamera = viewportCamera;
downsampling = new DownsamplingModule();
double pxc = viewportCamera.getPixelsize();
Verbose.talk(" Working " + (pxc / upsamplingWorking) + " Convolve " + (pxc / (upsamplingWorking * upsamplingConvolve)));
}
public void generate(String path, int multithread, Fluorophores[] fluorophoresAll, double fwhmNano, int mode, boolean project, boolean stats, SequenceReporting report) {
int cores = getCores(multithread);
int nax = viewportCamera.getFoVXPixel() * upsamplingConvolve;
int nay = viewportCamera.getFoVYPixel() * upsamplingConvolve;
Fluorophores fluosAll = new Fluorophores();
for(Fluorophores fluos : fluorophoresAll)
fluosAll.addAll(fluos);
if (autofluo != null && autofluo.backPoisson > 0) {
double corr = ((double)upsamplingWorking/upsamplingConvolve);
autofluo.create(nax, nay, fluosAll, corr*corr);
}
for(PSFModule psf : psfs) {
IJ.log("\n\n PSF " + psf.getName() + " " + psfs.size());
stackSequence = null;
String pathDataset = new File(path).getParent();
String pathMain = pathDataset + File.separator + psf.getName() + File.separator;
Verbose.talk("PSF " + pathMain);
pathOracle = pathMain + "oracle" + File.separator;
pathSequence = pathMain + "sequence" + File.separator;
pathFluosFrame = pathMain + "fluorophores" + File.separator;
pathProjection = pathOracle + "projection" + File.separator;
pathConvolution = pathMain + "convolution" + File.separator;
(new File(pathMain)).mkdir();
(new File(pathOracle)).mkdir();
(new File(pathSequence)).mkdir();
(new File(pathFluosFrame)).mkdir();
(new File(pathProjection)).mkdir();
(new File(pathConvolution)).mkdir();
generate(pathMain, psf, cores, fluorophoresAll, fwhmNano, mode, project, stats);
report.reportWeb(dataset, pathMain, pathOracle, pathSequence, psf);
}
}
/**
*/
public void generate(String pathMain, PSFModule psf, int cores, Fluorophores[] fluorophoresAll, double fwhmNano, int mode, boolean project, boolean stats) {
last = Math.min(last, fluorophoresAll.length-1);
if (project)
projection = new ProjectionModule(viewportCamera, upsamplingConvolve);
Verbose.talk("\nGenerate for frames " + first + " to " + last + " every " + interval + " on cores: " + cores + " mode (" + mode + ") " + modes[mode]);
Chrono.reset(6);
BufferedWriter buffer = null;
try {
if (stats)
buffer = new BufferedWriter(new FileWriter(new File(pathOracle + "activation-snr.csv")));
}
catch(Exception ex) {};
boolean actions[] = new boolean[4];
actions[0] = mode != 2; // Convolve
actions[1] = mode == 1 || mode == 3; // Store
actions[2] = mode == 1 || mode == 2; // Load
actions[3] = mode != 3; // generate
Fluorophores fluorophoresProcessed = new Fluorophores();
if (cores > 0) {
int nbFrames = last-first+1;
LinkedBlockingQueue<Runnable> queue = new LinkedBlockingQueue<Runnable>(nbFrames);
ExecutorService executor = new ThreadPoolExecutor(cores, cores, 50000L, TimeUnit.MILLISECONDS, queue);
Vector<Future<FrameGenerator>> futures = new Vector<Future<FrameGenerator>>();
for(int frame = first; frame<=last; frame+=interval) {
FrameGenerator task = new FrameGenerator(pathSequence, psf, buffer, fluorophoresAll[frame], frame, fwhmNano, actions, project, stats, fluorophoresProcessed);
Future<FrameGenerator> f = executor.submit(task, task);
futures.add(f);
}
executor.shutdown();
try {
for (int i=0; i<futures.size(); i++) {
Future<?> f = futures.get(i);
f.get();
}
}
catch(Exception ex) {
IJ.log("Error " + ex);
}
}
else {
for(int frame = first; frame<=last; frame+=interval) {
FrameGenerator task = new FrameGenerator(pathSequence, psf, buffer, fluorophoresAll[frame], frame, fwhmNano, actions, project, stats, fluorophoresProcessed);
task.run();
}
}
try {
if (stats)
buffer.close();
} catch(Exception ex) {};
if (project) {
projection.store(pathProjection, camera.getFormat());
//projection.show();
}
if (stats) {
fluorophoresProcessed.computeStats();
Statistics statistics[] = fluorophoresProcessed.getStats();
TableStatistics table = new TableStatistics("Statistics " + psf.getName(), statistics);
//table.show(500, 500);
table.saveCVS(pathOracle + "stats-snr.csv");
String pathHisto = pathOracle + "histo" + File.separator;
new File(pathHisto).mkdir();
for(int i=1; i<statistics.length; i++)
if (statistics[i].max > statistics[i].min) {
Chart chart = new Chart(statistics[i].name + "-" + dataset + "-" + psf.getName(), "Number of fluorophores", statistics[i].domain);
chart.add(statistics[i].name, statistics[i].histo);
if (statistics[i].name.endsWith("X"))
chart.add(statistics[i+1].name, statistics[i+1].histo);
//if (statistics[i].name.endsWith("NR"))
// chart.show(statistics[i].name, 800, 400);
if (!statistics[i].name.endsWith("ID") && !statistics[i].name.endsWith("Count") && !statistics[i].name.endsWith("Y"))
chart.savePNG(pathHisto + "Histogram-" + statistics[i].name + ".png", 800, 400);
}
}
Chrono.print("End", 6);
if (stackSequence != null) {
ImagePlus out = new ImagePlus("sequence-"+psf.getName(), stackSequence);
out.show();
String pathStack = pathMain + "sequence-as-stack" + File.separator;
new File(pathStack).mkdir();
(new FileSaver(out)).saveAsTiffStack(pathStack + "sequence-as-stack-" + dataset + "-" + psf.getName() + ".tif");
}
}
private int getCores(int multihreading) {
int cores = 0;
if (multihreading == MTHREAD_ADAPTATIVE)
cores = Runtime.getRuntime().availableProcessors();
else if (multihreading == MTHREAD_1_CORE)
cores = 1;
else if (multihreading == MTHREAD_2_CORE)
cores = 2;
else if (multihreading == MTHREAD_4_CORE)
cores = 4;
else if (multihreading == MTHREAD_8_CORE)
cores = 8;
else if (multihreading == MTHREAD_16_CORE)
cores = 16;
return cores;
}
/**
* Generate one frame, can run in a separated thread.
*/
public class FrameGenerator implements Runnable {
private int numberFrame;
private String pathFrames;
private boolean actions[];
private boolean project;
private boolean stats;
private double fwhmNano;
private PSFModule psf;
private BufferedWriter buffer;
private Fluorophores fluorophores;
public Fluorophores fluorophoresFrame;
public Fluorophores fluorophoresProcessed;
public FrameGenerator(String pathFrames, PSFModule psf, BufferedWriter buffer, Fluorophores fluorophores,
int numberFrame, double fwhmNano, boolean actions[], boolean project, boolean stats,
Fluorophores fluorophoresProcessed) {
this.pathFrames = pathFrames;
this.fluorophores = fluorophores;
this.numberFrame = numberFrame;
this.actions = actions;
this.project = project;
this.stats = stats;
this.psf = psf;
this.fwhmNano = fwhmNano;
this.buffer = buffer;
this.fluorophoresProcessed = fluorophoresProcessed;
fluorophoresFrame = new Fluorophores();
for(Fluorophore fluo : fluorophores)
if (viewportCamera.insideXY(fluo))
fluorophoresFrame.add(fluo);
}
@Override
public void run() {
double chrono = System.currentTimeMillis();
String filename = pathConvolution + Tools.format(numberFrame);
int fovX = viewportCamera.getFoVXPixel() * upsamplingWorking * upsamplingConvolve;
int fovY = viewportCamera.getFoVYPixel() * upsamplingWorking * upsamplingConvolve;
float imageConvolve[][] = new float[fovX][fovY];
float imageWorking[][] = null;
if (actions[0]) {
//Chrono.reset();
psf.convolve(fluorophoresFrame, imageConvolve, fwhmNano / upsamplingConvolve);
//Debug Builder.create(imageConvolve).show("Conv-" + p + "-" + psf[p].getName());
imageWorking = downsampling.run(imageConvolve, upsamplingWorking);
//Chrono.print("Convolve (" + numberFrame + ") fluos:" + fluorophores.size());
}
if (actions[1]) {
Chrono.reset();
ImagePlus imp = new ImagePlus(filename, new FloatProcessor(imageWorking));
(new FileSaver(imp)).saveAsTiff(filename + ".tif");
Chrono.print("Store " + filename);
}
if (actions[2]) {
Chrono.reset();
ImagePlus imp = new Opener().openImage(filename + ".tif");
imageWorking = ((FloatProcessor)imp.getProcessor()).getFloatArray();
Chrono.print("Load " + filename);
}
if (actions[3] && imageWorking != null) {
//if (autofluo != null)
// autofluo.add(imageWorking);
float imageCam[][] = downsampling.run(imageWorking, upsamplingConvolve);
if (noise != null)
noise.add(imageCam, autofluo.backPoisson);
camera.format(imageCam);
if (stats) {
for(Fluorophore fluo : fluorophores) {
computeSNR(imageCam, fluo, fwhmNano);
}
for(Fluorophore fluo : fluorophores)
computeClosest(fluo, fluorophores, fwhmNano);
for(Fluorophore fluo : fluorophores) {
try { buffer.write(fluo.vectorValuesAsString()); } catch(Exception ex) {};
}
}
if (project)
projection.projectAtCameraResolution(imageCam);
ImagePlus imp = camera.storeFrame(pathFrames, imageCam, numberFrame);
fluorophoresFrame.save(pathFluosFrame + File.separator + Tools.format(numberFrame) + ".csv");
if (stackSequence == null)
stackSequence = new ImageStack(imp.getWidth(), imp.getHeight());
stackSequence.addSlice(""+numberFrame, imp.getProcessor());
}
if (project) {
projection.projectAtWorkingResolution(imageWorking);
}
Verbose.prolix("" + psf.getName() + " f:" + numberFrame + " n:" + fluorophoresFrame.size() + " t:" + IJ.d2s((System.currentTimeMillis()-chrono)*1e-3) + "us");
fluorophoresProcessed.addAll(fluorophoresFrame);
}
public void computeClosest(Fluorophore fluo, Fluorophores fluos, double fwhm) {
int id = 0;
double min = 2 * fwhm;
int count = 0;
for(Fluorophore f : fluos) {
double d = f.distance(fluo);
if (d > 0.0000001) {
if (d < min) {
min = d;
id = f.id;
}
}
if (d < fwhm) {
count++;
}
}
fluo.closestDistance = min;
fluo.closestID = id;
fluo.closestCount = count;
}
public void computeSNR(float[][] image, Fluorophore fluo, double fwhmNano) {
int nx = image.length;
double pixelsize = viewportCamera.getPixelsize();
int i = Tools.round(fluo.x / pixelsize);
int j = Tools.round(fluo.y / pixelsize);
int h = (int) Math.ceil(fwhmNano / pixelsize);
int n = 2 * h;
int m = 2 * n + 1;
int u = m - h - 1;
if (h == 0)
return;
double block[][] = new double[m][m];
double test[][] = new double[m][m];
for (int x = 0; x <m; x++)
for (int y = 0; y <m; y++) {
int ii = i - n + x;
int jj = j - n + y;
if (ii >= 0 && ii < nx)
if (jj >= 0 && jj < nx)
block[x][y] = image[ii][jj];
}
// Signal
double meanSignal = 0.0;
double meanBackground = 0.0;
double maxSignal = 0;
int countSignal = 0;
int countBackground = 0;
for (int x = 0; x <m; x++)
for (int y = 0; y <m; y++) {
if (x > h && x < u && y > h && y < u) {
meanSignal += block[x][y];
maxSignal = Math.max(block[x][y], maxSignal);
countSignal++;
test[x][y] = 100;
}
else {
meanBackground += block[x][y];
countBackground++;
test[x][y] = -100;
}
}
meanSignal = meanSignal / countSignal;
meanBackground = meanBackground / countBackground;
double noiseSignal = 0;
double noiseBackground = 0;
for (int x = 0; x <n; x++)
for (int y = 0; y <n; y++) {
if (x > h && x < u && y > h && y < u)
noiseSignal += (block[x][y]-meanSignal) * (block[x][y]-meanSignal);
else
noiseBackground += (block[x][y] - meanBackground) * (block[x][y] - meanBackground);
}
noiseSignal = Math.sqrt(noiseSignal / countSignal);
noiseBackground = Math.sqrt(noiseBackground / countBackground);
fluo.setSNR(meanBackground, noiseBackground, maxSignal, meanSignal, noiseSignal);
}
public void displaySNR(ImageWare image, Fluorophore fluo, double fwhmPixel, Overlay overlay, int factor, double pixelsize) {
int i = Tools.round(fluo.x / pixelsize);
int j = Tools.round(fluo.y / pixelsize);
int h = (int) Math.ceil(fwhmPixel);
int n = 2 * h + 1;
if (overlay != null) {
overlay.add(new Roi((i-h)*factor, (j-h)*factor, (2*h+1)*factor, (2*h+1)*factor));
overlay.add(new Roi((i-n)*factor, (j-n)*factor, (2*n+1)*factor, (2*n+1)*factor));
overlay.add(new TextRoi(i*factor, j*factor-20, IJ.d2s(fluo.psnr,1)));
}
}
/*
private void computeSNR(int numberFrame, Fluorophores fluos, float[][] array, double fwhmNano, boolean displayPSNR) {
Overlay overlay = null;
ImagePlus imp = null;
int factorPSNR = 5;
if(displayPSNR) {
overlay = new Overlay();
int n = array.length;
imp = new ImagePlus("SNR " + numberFrame, new FloatProcessor(n*factorPSNR, n*factorPSNR));
FloatProcessor fp = (FloatProcessor)imp.getProcessor();
for(int x=0; x<n*factorPSNR; x++)
for(int y=0; y<n*factorPSNR; y++)
fp.putPixelValue(x, y, array[x/factorPSNR][y/factorPSNR]);
imp.show();
}
ImageWare image = Builder.create(array);
double pixelsize = viewportCamera.getPixelsize();
double fwhmPixel = (float)(fwhmNano / pixelsize);
int count = 0;
for(Fluorophore fluo : fluos) {
computeSNR(image, fluo, fwhmPixel, pixelsize);
displaySNR(image, fluo, fwhmPixel, overlay, factorPSNR, pixelsize);
}
if (imp != null && overlay != null) {
imp.setOverlay(overlay);
imp.show();
}
}
*/
}
}
| Java |
2D | SMLM-Challenge/Challenge2016 | Simulator/Simulator-Java/src/smlms/simulation/SequenceReporting.java | .java | 18,608 | 418 | package smlms.simulation;
import ij.IJ;
import ij.ImagePlus;
import ij.io.FileSaver;
import ij.io.Opener;
import imageware.ImageWare;
import java.io.File;
import java.util.ArrayList;
import smlms.tools.Tools;
import smlms.tools.Zip;
public class SequenceReporting {
private SequenceFactoryDialog dialog;
public SequenceReporting(SequenceFactoryDialog dialog) {
this.dialog = dialog;
}
public void reportWeb(String dataset, String pathMain, String pathOracle, String pathSequence, PSFModule psf) {
(new File(pathOracle)).mkdir();
String parent = new File(pathMain).getParent() + File.separator;
Tools.copyFile(parent + "index.html", pathOracle + "index.html");
//Zip.zipFolder(pathPSF, pathOracle + "one-bead-100nm-" + psf.getName() + "-10x10x10-as-list.zip");
reportParameters(pathOracle);
reportExcerpt(pathSequence, pathOracle);
reportProjection(pathOracle);
reportPSF(pathOracle, psf);
double c = dialog.spnOversamplingConvolve.get() * dialog.spnOversamplingWorking.get();
double pixelsize = (dialog.spnPixelsizeCamera.get()/c);
ImageWare psfim = psf.test(100, pixelsize, dialog.spnFocalPlaneTI.get());
String pathPSF = pathMain + File.separator + "psf" + File.separator ;
new File(pathPSF).mkdir();
psf.storeIllustration(psfim, pathOracle, 0.5);
psf.storeSlices(psfim, pathPSF);
String pathData = parent + "Data" + File.separator;
(new File(pathData)).mkdir();
Zip.zipFolder(pathSequence, pathData + "sequence-" + dataset + "-" + psf.getName() + "-as-list.zip");
String pathStack = pathMain + "sequence-as-stack" + File.separator;
String stack = pathData + "sequence-" + dataset + "-" + psf.getName() + "-as-stack.zip";
IJ.log("ZIP " + pathData + " to " + stack);
Zip.zipFolder(pathStack, stack);
}
/**
* Report all elements.
*/
protected void reportAll(String path) {
(new File(path)).mkdir();
try {
String params = Tools.readFile(path + "sequence-parameters.html");
String exceprt = Tools.readFile(path + "sequence-excerpt.html");
String accuracy = Tools.readFile(path + "sequence-accuracy.html");
ReportHTML out = new ReportHTML(path, "sequence.html");
out.print("\n<table cellpadding=0 style=\"border:0px solid #FFFFFF\"><tr><td valign=top style=\"width:480px\">\n");
out.print(params);
out.print(accuracy);
out.print("\n</td><td style=\"width:20px\"></td><td valign=top style=\"width:480px\">");
out.print(exceprt);
out.print("\n</td></tr></table>\n");
out.close();
ReportHTML outc = new ReportHTML(path, "acquisition_parameters.html");
reportChallenge(outc, "");
outc.close();
}
catch(Exception ex) {
IJ.error("" + ex);
}
}
/**
* Report Parameters
*/
protected void reportParameters(String path) {
int first = dialog.spnFirstFrame.get();
int last = dialog.spnLastFrame.get();
int interval = dialog.spnIntervalFrame.get();
String frames = "From " + first + " to " + last;
double pxc = dialog.spnPixelsizeCamera.get();
(new File(path)).mkdir();
try {
ReportHTML out = new ReportHTML(path, "sequence-parameters.html");
out.printSection("Parameters");
out.print("<table class=\"report_table\" style=\"width:480px\">");
out.printHeader("Camera", 3);
out.printParam("Photon converter factor or Quantum efficiency (QE)", dialog.spnQuantumEfficiency.get(), 2, "e<sup>-</sup>/Ph.");
out.printParam("Resolution", dialog.spnCameraResolution.get(), 0, "pixels");
out.printParam("Pixelsize", dialog.spnPixelsizeCamera.get(), 2, "nm");
out.printParam("Field of view", dialog.spnCameraResolution.get() * dialog.spnPixelsizeCamera.get(), 2, "nm");
out.printHeader("Optics", 3);
out.printParam("Wavelength", dialog.spnWavelength.get(), 2, "nm");
out.printParam("Numerical aperture (NA)", dialog.spnNA.get(), 2, "");
out.printHeader("Autofluorescence", 3);
out.printParam("Background level (Gain)", dialog.spnAutofluoOffsetMean.get(), 2, "");
out.printParam("Background level (Poisson distribution)", dialog.spnAutofluoOffsetStdv.get(), 2, "");
if (dialog.cmbAutofluoSources.getSelectedIndex() != AutofluorescenceModule.NONE) {
out.printParam("Location of the sources", (String) dialog.cmbAutofluoSources.getSelectedItem(), "");
out.printParam("Number of sources", dialog.spnAutofluoNbSources.get(), 0, "");
out.printParam("Gain of sources", dialog.spnAutofluoGain.get(), 0, "");
out.printParam("Size of sources", dialog.spnAutofluoSize.get(), 0, "nm");
out.printParam("Percentage of change", dialog.spnAutofluoChange.get(), 0, "%");
}
out.printHeader("Camera Noise", 3);
out.printParam("Distribution: " + NoiseModule.distribution[0], "" + dialog.spnNoises[0].get(), "");
out.printParam("Distribution: " + NoiseModule.distribution[3], "" + dialog.spnNoises[3].get(), "");
out.printParam("Distribution: " + NoiseModule.distribution[4], "" + dialog.spnNoises[4].get(), "");
int c = dialog.spnOversamplingConvolve.get();
int a = dialog.spnOversamplingWorking.get();
out.printHeader("Analog Digital Conversion", 3);
out.printParam("Electron conversion e<sup>-</sup> per ADU", dialog.spnCameraGain.get(), 2, "DN/e<sup>-</sup>");
out.printParam("Baseline", dialog.spnBaseline.get(), 2, "DN");
out.printParam("Saturation", dialog.spnCameraSaturation.get(), 2, "DN");
out.printParam("Quantization", (String) dialog.cmbCameraQuantization.getSelectedItem(), "");
out.printHeader("Computational Parameters", 3);
out.printParam("Thickness", dialog.spnThickness.get(), 2, "nm");
out.printParam("Frames (interval:" + interval +")", frames, "");
out.printParam("Multithreading", (String) dialog.cmbThreading.getSelectedItem(), "");
out.printParam("Pixelsize to PSF convolution", (pxc / (c*a)), 1, "nm");
out.printParam("Pixelsize for autofluorescence", (pxc / (a)), 1, "nm");
out.printParam("Pixelsize of the camera", dialog.spnPixelsizeCamera.get(), 1, "nm");
out.printParam("File format", (String) dialog.cmbCameraFileFormat.getSelectedItem(), "");
out.print("</table>");
out.close();
}
catch (Exception e) {
IJ.error("" + e);
}
}
private void reportChallenge(ReportHTML out, String title) {
out.print("\n<table cellpadding=0 style=\"border:0px solid #FFFFFF\"><tr><td valign=top>\n");
out.printSection("Acquisition Parameters");
// Left column
out.print("<table class=\"report_table\" style=\"width:480px\"cellpadding=3>\n");
out.printHeader("Camera", 3);
out.printParam("Photon converter factor or Quantum efficiency (QE)", dialog.spnQuantumEfficiency.get(), 2, "e<sup>-</sup>/Ph.");
out.print("<td valign=\"top\" class=\"report_param\" colspan=3><i>QE = QE-Gain x QE-interacting [<a href=\"#ref1\">Ref. 1</a>]</i></td>\n");
out.printParam("Resolution", dialog.spnCameraResolution.get(), 0, "pixels");
out.printParam("Pixelsize", dialog.spnPixelsizeCamera.get(), 2, "nm");
out.printParam("Field of view", dialog.spnCameraResolution.get() * dialog.spnPixelsizeCamera.get(), 2, "nm");
out.printHeader("Optics", 3);
out.printParam("Wavelength", dialog.spnWavelength.get(), 2, "nm");
out.printParam("Numerical aperture (NA)", dialog.spnNA.get(), 2, "");
out.printHeader("Analog Digital Conversion", 3);
out.printParam("Electron conversion - Gain", dialog.spnCameraGain.get(), 2, "DN/e<sup>-</sup>");
out.printParam("Electron conversion - Offset", dialog.spnCameraOffset.get(), 2, "DN");
out.printParam("Baseline", dialog.spnBaseline.get(), 2, "DN");
out.printParam("Saturation", dialog.spnCameraSaturation.get(), 2, "DN");
out.printParam("Quantization", (String) dialog.cmbCameraQuantization.getSelectedItem(), "");
out.print("</table>");
out.print("<a name=\"ref1\"></a><p><?php include '../../html/reference_qe.html' ?></p>");
out.print("\n</td><td width=\"20px\"></td><td valign=\"top\">\n");
// Right column
out.print("\n<table class=\"report_table\" style=\"width:480px\">\n");
out.printSection("Point-Spread Function (PSF)");
out.printHeader("Physical Model", 3);
out.printParam("Wavelength", dialog.spnWavelength.get(), 2, "nm");
out.printParam("Numerical aperture (NA)", dialog.spnNA.get(), 2, "");
out.printParam("Offset focal plane ", dialog.getFocalPlane(), 0, "nm");
if (dialog.tabPSF.getSelectedIndex() == 1) {
out.printParam("XY function", "<b>" + (String) dialog.cmbPSFModelXY.getSelectedItem() + "</b>", "");
out.printParam("Z function", (String) dialog.cmbPSFModelZ.getSelectedItem(), "");
out.printParam("Focal plane", dialog.getFocalPlaneDescription(), "");
out.printParam("Defocus plane", dialog.getDefocusPlaneDescription(), "");
}
if (dialog.tabPSF.getSelectedIndex() == 2) {
out.printParam("Model", "<b>" + PSFModule.namesXYZ[0] + "</b>", "");
out.printParam("Refractive index sample", dialog.spnNS.get(), 2, "");
out.printParam("Refractive index immersion", dialog.spnNI.get(), 2, "");
out.printParam("Offest working distance", dialog.spnFocalPlaneTI.get(), 2, "nm");
}
out.print("</td><tr></table>\n");
out.print("</td></tr></table>\n");
}
private String[] getDirectoryList(String path) {
File dir = new File(path);
if (dir != null)
if (dir.exists())
if (dir.isDirectory()) {
return dir.list();
}
return new String []{""};
}
protected void reportPSF(String path) {
ArrayList<PSFModule> psfModules = dialog.createPSFModule();
for(PSFModule psfModule : psfModules) {
reportPSF(path + File.separator + psfModule.getName() + File.separator, psfModule);
}
}
/**
* Report PSF.
*
* Show some frames of the sequence.
*/
private void reportPSF(String path, PSFModule psfModule) {
(new File(path)).mkdir();
try {
double c = dialog.spnOversamplingConvolve.get() * dialog.spnOversamplingWorking.get();
ReportHTML out = new ReportHTML(path, "psf.html");
out.printSection("PSF");
out.print("<table><tr><td valign=\"top\">\n");
// Left column
out.print("\n<table class=\"report_table\" style=\"width:480px\">\n");
out.printHeader("Physical Model", 3);
out.printParam("Wavelength", dialog.spnWavelength.get(), 2, "nm");
out.printParam("Numerical aperture (NA)", dialog.spnNA.get(), 2, "");
out.printParam("Offset focal plane ", dialog.getFocalPlane(), 0, "nm");
if (dialog.tabPSF.getSelectedIndex() == 1) {
out.printParam("XY function", "<b>" + (String) dialog.cmbPSFModelXY.getSelectedItem() + "</b>", "");
out.printParam("Z function", (String) dialog.cmbPSFModelZ.getSelectedItem(), "");
out.printParam("Focal plane", dialog.getFocalPlaneDescription(), "");
out.printParam("Defocus plane", dialog.getDefocusPlaneDescription(), "");
}
if (dialog.tabPSF.getSelectedIndex() == 2) {
out.printParam("Model", "<b>" + PSFModule.namesXYZ[0] + "</b>", "");
out.printParam("Refractive index sample", dialog.spnNS.get(), 2, "");
out.printParam("Refractive index immersion", dialog.spnNI.get(), 2, "");
out.printParam("Offset working distance", dialog.spnFocalPlaneTI.get(), 2, "nm");
}
if (dialog.tabPSF.getSelectedIndex() == 3) {
out.printParam("File", "<b>" + psfModule.getName() + "</b>", "");
}
if (dialog.tabPSF.getSelectedIndex() == 4) {
out.printParam("Depth", dialog.spnBiplaneDepth.get(), 2, "");
out.printParam("ni", dialog.spnBiplaneNI.get(), 2, "");
out.printParam("ns", dialog.spnBiplaneNS.get(), 2, "");
out.printParam("Delta Z 1", dialog.spnBiplaneDeltaZ1.get(), 2, "");
out.printParam("Delta Z 2", dialog.spnBiplaneDeltaZ2.get(), 2, "");
out.printParam("Orientation", (String)dialog.cmbBiplaneOrientation.getSelectedItem(), "Rows");
out.printParam("spnBiplaneTI", dialog.spnBiplaneTI.get(), 2, "");
out.printParam("spnBiplaneDX", dialog.spnBiplaneDX.get(), 2, "");
out.printParam("spnBiplaneDY", dialog.spnBiplaneDY.get(), 2, "");
}
out.printParam("Depth of the PSF", dialog.spnThickness.get(), 1, "nm");
if (dialog.tabPSF.getSelectedIndex() == 2) {
out.printParam("Oversampling in lateral", dialog.spnOversamplingLateral.get(), 0, "");
out.printParam("Oversampling in axial", dialog.spnOversamplingAxial.get(), 0, "");
}
out.print("\n</table>");
out.print("\n<p><span class=\"button toggleintro\" style=\"margin-top:50px;width:400px\">");
out.print("\n<a href=\"one-bead-100nm-" + psfModule.getName() + "-10x10x10-as-list.zip\">");
out.print("\none-bead-100nm-" + psfModule.getName() + "-10x10x10-as-list.zip</a><p>");
out.print("\n</td><td width=\"20px\"></td><td valign=\"top\">\n");
// Right column
out.print("<table class=\"report_table\" style=\"width:480px\">\n");
out.print("<img src=\"illustration.png\" style=\"width:480px; float:right;padding-left:10px\">\n");
out.print("<h4>Orthogonal Section of the PSF</h4>\n");
out.print("<p>Resolution: " + (dialog.spnPixelsizeCamera.get()/c) + " nm per voxel</p>\n");
out.print("</tr><td></table></td></tr></table>\n");
out.close();
}
catch(Exception e) {
IJ.error("" + e);
}
}
/**
* Report Excerpt.
*
* Show some frames of the sequence.
*/
protected void reportExcerpt(String pathSequence, String pathOracle) {
int numberOfRandomFrames = 2;
(new File(pathOracle)).mkdir();
try {
ReportHTML out = new ReportHTML(pathOracle, "sequence-excerpt.html");
out.printSection("Excerpt");
String frames[] = getDirectoryList(pathSequence);
int n = frames.length;
out.print("\n<table class=\"report_table\" style=\"width:480px\">");
IJ.log("" + " " + 0 + " " + frames[0]);
reportFrame(pathSequence, pathOracle, out, "First Frame: ", frames[0]);
for(int i=0; i<numberOfRandomFrames; i++) {
int n1 = Math.max(0, Math.min(n-1, (int)(Math.random() * (n-2)) + 1));
reportFrame(pathSequence, pathOracle, out, "Random Frame: ", frames[n1]);
}
reportFrame(pathSequence, pathOracle, out, "Last Frame: ", frames[n-1]);
out.print("</table>");
out.close();
}
catch(Exception e) {
IJ.error("" + e);
}
}
protected void reportFrame(String pathSequence, String pathOracle, ReportHTML out, String prefix, String frameExt) {
String pathimg = pathOracle + "images";
(new File(pathimg)).mkdir();
String frame = frameExt.substring(0, frameExt.length()-4);
tif2jpeg(pathSequence, pathimg, frame);
String imageHTML = "images/" + frame + ".jpg";
out.print("<tr>");
out.printHeader(prefix + frameExt, 1);
out.print("</tr><tr><td>");
out.print("<p><img src=\"" + imageHTML + "\"><p>\n");
out.print("</tr>");
}
/**
* Report Accuracy
*
* Accuracy is defined according the Thompson rules
*/
protected void reportAccuracy(String path) {
(new File(path)).mkdir();
try {
ReportHTML out = new ReportHTML(path, "sequence-accuracy.html");
double res[] = dialog.testAccuracy();
// return new double[] {N, a, s, b, accStats, accQuant, accBack, accThomson};
out.printSection("Estimation of the Accuracy");
out.print("<table class=\"report_table\" style=\"width:480px\">");
out.printHeader("Accuracy defined by Thomson", 3);
out.printParam("N, number of photons (max. of the frame)", res[0], 2, "");
out.printParam("a, pixelsize of the camera", res[1], 2, "nm");
out.printParam("s, FWHM of the PSF", res[2], 2, "nm");
out.printParam("b, background (average of the frame)", res[3], 2, "");
out.printParam("Accuracy term - Localization", res[4], 2, "nm");
out.printParam("Accuracy term - Quantization", res[5], 2, "nm");
out.printParam("Accuracy term - Background", res[6], 2, "nm");
out.printParam("Accuracy Localization", res[7], 2, "nm");
out.print("</table>");
out.print("<p><?php include '../../html/reference_accuracy.html' ?></p>");
out.close();
}
catch(Exception e) {
IJ.error("" + e);
}
}
protected void reportProjection(String path) {
(new File(path)).mkdir();
try {
ReportHTML out = new ReportHTML(path, "projection.html");
String imageCMax = "max-camera-resolution";
String imageCAvg = "avg-camera-resolution";
String imageWMax = "max-high-resolution";
String imageWAvg = "avg-high-resolution";
double pxc = dialog.spnPixelsizeCamera.get();
out.printSection("Time projection");
out.print("<table><tr><td valign=top style=\"width:480px\">\n");
out.print("<table class=\"report_table\"><tr>");
out.printTH("Average Intensity Projection");
out.print("</tr><tr>");
out.printTD(""+
"<p>Camera Resolution: " + pxc + "nm/pixel (Original size)</p>\n" +
"<p><img src=\"projection/" + imageCAvg + ".jpg\"></p>\n" +
"<p>Download the original <a href=\"projection/" + imageCAvg + ".tif\">image</a><p>\n" +
"<p> </p><p>High Resolution: " + (pxc / dialog.spnOversamplingConvolve.get()) + "nm/pixel <a href=\"projection/" + imageWAvg + ".jpg\"> (Enlarge this image)</a></p>\n" +
"<p><a href=\"projection/" + imageWAvg + ".jpg\"><img src=\"projection/" + imageWAvg + ".jpg\" style=\"width:476px;height:475px\"></a></p>\n"+
"<p>Download the original <a href=\"projection/" + imageWAvg + ".tif\">image</a><p>\n");
out.print("</tr></table>");
out.print("\n</td><td style=\"width:20px\"></td><td valign=top style=\"width:480px\">");
out.print("<table class=\"report_table\"><tr>");
out.printTH("Maximum Intensity Projection");
out.print("</tr><tr>");
out.printTD(""+
"<p>Camera Resolution: " + dialog.spnPixelsizeCamera.get() + "nm/pixel (Original size)</p>\n" +
"<p><img src=\"projection/" + imageCMax + ".jpg\"></p>\n" +
"<p>Download the original <a href=\"projection/" + imageCMax + ".tif\">image</a><p>\n" +
"<p> </p><p>High Resolution: " + (pxc / dialog.spnOversamplingConvolve.get()) + "nm/pixel<a href=\"projection/" + imageWMax + ".jpg\"> (Enlarge this image)</a></p>\n" +
"<p><a href=\"projection/" + imageWMax + ".jpg\"><img src=\"projection/" + imageWMax + ".jpg\" style=\"width:476px;height:475px\"></a></p>\n"+
"<p>Download the original <a href=\"projection/" + imageWMax + ".tif\">image</a><p>\n");
out.print("</tr></table>");
out.print("</td></tr></table>\n");
out.close();
}
catch(Exception ex) {
IJ.error("reportProjection:" + ex + "(" + path + ")");
}
}
private void tif2jpeg(String srcpath, String dstpath, String name) {
String jpgname = dstpath + File.separator + name + ".jpg";
String tifname = srcpath + File.separator + name + ".tif";
Opener opener = new Opener();
ImagePlus imp = opener.openImage(tifname);
if (imp == null) {
IJ.error(" tif2jpeg : File not found " + tifname);
return;
}
(new FileSaver(imp)).saveAsJpeg(jpgname);
}
}
| Java |
2D | SMLM-Challenge/Challenge2016 | Simulator/Simulator-Java/src/smlms/simulation/SequenceFactory_2016.java | .java | 212 | 14 | package smlms.simulation;
public class SequenceFactory_2016 {
public SequenceFactory_2016() {
new SequenceFactoryDialog();
}
public static void main(String args[]) {
new SequenceFactoryDialog();
}
}
| Java |
2D | SMLM-Challenge/Challenge2016 | Simulator/Simulator-Java/src/smlms/simulation/ProjectionModule.java | .java | 3,016 | 97 | package smlms.simulation;
import ij.IJ;
import ij.ImagePlus;
import ij.io.FileSaver;
import ij.process.FloatProcessor;
import ij.process.ImageConverter;
import java.io.File;
public class ProjectionModule {
private FloatProcessor maxPR; // Working resolution
private FloatProcessor maxCR; // Camera resolution
private FloatProcessor avgPR;
private FloatProcessor avgCR;
private double pixelsizeWorking;
private double pixelsizeCamera;
public ProjectionModule(Viewport viewportCamera, double pixelsizeWorking) {
pixelsizeCamera = viewportCamera.getPixelsize();
this.pixelsizeWorking = pixelsizeWorking;
int cx = viewportCamera.getFoVXPixel();
int cy = viewportCamera.getFoVYPixel();
int px = (int)Math.ceil(cx * pixelsizeWorking);
int py = (int)Math.ceil(cy * pixelsizeWorking);
maxPR = new FloatProcessor(px, py);
maxCR = new FloatProcessor(cx, cy);
avgPR = new FloatProcessor(px, py);
avgCR = new FloatProcessor(cx, cy);
}
public void projectAtWorkingResolution(float[][] image) {
if (maxPR == null)
return;
if (avgPR == null)
return;
float[] maxpix = (float[])maxPR.getPixels();
float[] avgpix = (float[])avgPR.getPixels();
int n = image.length;
int index;
for(int x=0; x<n; x++)
for(int y=0; y<n; y++) {
float value = image[x][y];
index = x+y*n;
maxpix[x+y*n] = Math.max(value, maxpix[x+y*n]);
avgpix[index] = value + avgpix[index];
}
}
public void projectAtCameraResolution(float[][] image) {
if (maxCR == null)
return;
if (avgCR == null)
return;
float[] maxpix = (float[])maxCR.getPixels();
float[] avgpix = (float[])avgCR.getPixels();
int n = image.length;
int index;
for(int x=0; x<n; x++)
for(int y=0; y<n; y++) {
float value = image[x][y];
index = x+y*n;
maxpix[x+y*n] = Math.max(value, maxpix[x+y*n]);
avgpix[index] = value + avgpix[index];
}
}
public void show() {
(new ImagePlus("max-" + IJ.d2s(pixelsizeWorking,1) + "-nm", maxPR)).show();
(new ImagePlus("max-" + IJ.d2s(pixelsizeCamera,1) + "-nm", maxCR)).show();
(new ImagePlus("avg-" + IJ.d2s(pixelsizeWorking,1) + "-nm", avgPR)).show();
(new ImagePlus("avg-" + IJ.d2s(pixelsizeCamera,1) + "-nm", avgCR)).show();
}
public void store(String path, String format) {
new File(path).mkdir();
store(maxPR, path + "max-high-resolution", format);
store(maxCR, path + "max-camera-resolution", format);
store(avgPR, path + "avg-high-resolution", format);
store(avgCR, path + "avg-camera-resolution", format);
}
private void store(FloatProcessor fp, String filename, String format) {
ImagePlus imp = new ImagePlus("", fp);
if (format.equals(CameraModule.names[0]))
(new ImageConverter(imp)).convertToGray8();
if (format.equals(CameraModule.names[1]))
(new ImageConverter(imp)).convertToGray16();
if (format.equals(CameraModule.names[2]))
(new ImageConverter(imp)).convertToGray8();
(new FileSaver(imp)).saveAsJpeg(filename + ".jpg");
(new FileSaver(imp)).saveAsTiff(filename + ".tif");
}
}
| Java |
2D | SMLM-Challenge/Challenge2016 | Simulator/Simulator-Java/src/smlms/simulation/DownsamplingModule.java | .java | 532 | 23 | package smlms.simulation;
public class DownsamplingModule {
public float[][] run(float[][] image, int downsampling) {
int mx = image.length;
int my = image[0].length;
int nx = mx / downsampling;
int ny = my / downsampling;
float[][] camera = new float[nx][ny];
for(int x=0; x<nx; x++)
for(int y=0; y<ny; y++) {
float sum = 0f;
for(int i=0; i<downsampling; i++)
for(int j=0; j<downsampling; j++) {
sum += image[x*downsampling+i][ y*downsampling+j];
}
camera[x][y] = sum;
}
return camera;
}
}
| Java |
2D | SMLM-Challenge/Challenge2016 | Simulator/Simulator-Java/src/smlms/simulation/Generate_Beads.java | .java | 2,321 | 72 | package smlms.simulation;
import ij.IJ;
import smlms.file.Description;
import smlms.file.Fluorophores;
public class Generate_Beads {
public static String path = "/Users/sage/Desktop/beads/beads6/";
public static String pathPSF = "/Users/sage/Desktop/beads/psf/";
public static String filename = path + "activations.csv";
public static String[] psfs = new String[] {"2D-Exp", "AS-Exp", "DH-Exp", "BP000-Exp", "BP500-Exp"};
public static void main(String args[]) {
Generate_Beads sf = new Generate_Beads();
sf.run(filename);
}
public Generate_Beads() {
run(filename);
}
public void run(String path) {
SequenceFactoryDialog dialog = new SequenceFactoryDialog();
dialog.loadParams();
dialog.settings.loadRecordedItems();
dialog.path = path;
dialog.panel.txtFile.setText(filename);
Fluorophores fluos = Fluorophores.load(filename, new Description("activations"), dialog.panel.lblInfo);
dialog.panel.setFluorophores(fluos);
dialog.panel.getFluorophoresPerFrames();
dialog.chkProjection.setSelected(true);
dialog.chkStats.setSelected(true);
dialog.chkReport.setSelected(true);
fluos.computeStats();
double chrono = System.nanoTime(); // 1 ou 2 (join)
dialog.tabPSF.setSelectedIndex(3);
for(int i=0; i<dialog.txtPSFFile.length; i++)
dialog.txtPSFFile[i].setText("");
for(int i=0; i<psfs.length; i++)
dialog.txtPSFFile[i].setText(pathPSF + psfs[i] + ".tif");
dialog.spnCameraResolution.set(64);
dialog.spnLastFrame.set(151);
dialog.cmbThreading.setSelectedIndex(0);
dialog.cmbCameraQuantization.setSelectedIndex(5); // 16-bits
dialog.spnCameraSaturation.set(65535); // 16-bits
dialog.cmbCameraFileFormat.setSelectedIndex(1); // 16-bits
dialog.spnBiplaneDX.set(77.11);
dialog.spnBiplaneDY.set(17.07);
dialog.spnBiplaneRotation.set(1.9);
dialog.spnBiplaneScale.set(1);
dialog.chkNoises[0].setSelected(true);
dialog.chkNoises[1].setSelected(true);
dialog.chkNoises[2].setSelected(true);
dialog.chkNoises[3].setSelected(true);
dialog.chkNoises[4].setSelected(false);
dialog.chkNoises[5].setSelected(false);
dialog.spnNoises[0].set(0.5);
dialog.spnNoises[1].set(0.5);
dialog.spnNoises[2].set(0.5);
dialog.spnNoises[3].set(1.41);
dialog.run();
IJ.log("End Batch " + ((System.nanoTime() - chrono)*1e-9));
}
}
| Java |
2D | SMLM-Challenge/Challenge2016 | Simulator/Simulator-Java/src/smlms/simulation/NoiseModule.java | .java | 7,383 | 250 | package smlms.simulation;
import ij.IJ;
import imageware.Builder;
import imageware.ImageWare;
import java.io.PrintStream;
import org.apache.commons.math3.distribution.GammaDistribution;
import org.apache.commons.math3.distribution.PoissonDistribution;
import smlms.tools.ArrayOperations;
import smlms.tools.Chrono;
import smlms.tools.PsRandom;
public class NoiseModule {
public static String[] names = new String[] { "Read-out noise", "Dark noise", "Shot noise", "EM Gain", "Spurious (CIC)", "Dead pixel"};
public static String[] distribution = new String[] { "Gaussian (stdev)", "Poisson", "Poisson", "Gamma", "add poisson", "/10e6 of pixel"};
public static int READOUT = 0;
public static int DARK = 1;
public static int SHOT = 2;
public static int EMCCD = 3;
public static int SPURIOUS_CIC = 4;
public static int DEADPIXELS = 5;
private double quantumEfficiency;
private boolean noiseEnable[];
private double noiseParam[];
private float gain = 1f;
private float offset = 0f;
private float baseline = 0f;
private PsRandom psrand;
public NoiseModule(PsRandom psrand, double gain, double offset, double baseline, double quantumEfficiency, boolean noiseEnable[], double noiseParam[]) {
this.gain = (float)gain;
this.offset = (float)offset;
this.baseline = (float)baseline;
this.psrand = psrand;
this.noiseEnable = noiseEnable;
this.noiseParam = noiseParam;
this.quantumEfficiency = quantumEfficiency;
}
public void test(Viewport viewport) {
int nx = viewport.getFoVXPixel();
int ny = viewport.getFoVXPixel();
ImageWare stack = Builder.create(nx, ny, 1, ImageWare.FLOAT);
for(int f=0; f<1; f++) {
Chrono.reset();
float[][] frame = new float[nx][ny];
for(int i=0; i<nx; i++) {
for(int j=0; j<ny; j++)
frame[i][j] = j;
}
for(int i=nx/4; i<3*nx/4; i++) {
for(int j=ny/2-20; j<ny/2; j++)
frame[i][j] = 100;
for(int j=ny/2; j<ny/2+20; j++)
frame[i][j] = 400;
for(int j=ny/2+20; j<ny/2+40; j++)
frame[i][j] = 0;
}
add_old(frame);
stack.putXY(0, 0, f, frame);
Chrono.print("add noise " + f);
}
stack.show("Test Noise SHOT " + noiseParam[SHOT] + " EMCCD " + noiseParam[EMCCD]);
}
public void add(float[][] frame, double autofluo) {
//double QE=0.9; // Evolve quantum efficiency @700 nm
double EMgain = noiseParam[EMCCD]; // 300
double readout = noiseParam[READOUT]; // 74.4 measured rms electrons for my Evolve
double c = noiseParam[SPURIOUS_CIC]; //0.002; //manufacturer quoted spurious charge (CIC only, dark counts negligible) for my Evolve
double e_per_edu = gain;
int nx = frame.length;
int ny = frame[0].length;
//float im1[][] = new float[nx][ny];
//float im2[][] = new float[nx][ny];
//float im3[][] = new float[nx][ny];
//float im4[][] = new float[nx][ny];
//float im5[][] = new float[nx][ny];
for(int i=0; i<nx; i++)
for(int j=0; j<ny; j++) {
double photons = frame[i][j];
//im1[i][j] = (float)photons;
double n_ie = noiseEnable[SPURIOUS_CIC] ? poisson(quantumEfficiency*(photons+autofluo) + c) : quantumEfficiency*photons;
//im2[i][j] = (float)n_ie;
double n_oe = noiseEnable[EMCCD] ? gamma(n_ie, EMgain) : n_ie;
//im3[i][j] = (float)n_oe;
n_oe += noiseEnable[READOUT] ? gaussian(readout) : 0;
//im4[i][j] = (float)n_oe;
double ADU_out = (int)(n_oe / e_per_edu) + baseline;
//im5[i][j] = (float)ADU_out;
frame[i][j] = (float)ADU_out;
}
//Builder.create(im1).show("in-photons");
//Builder.create(im2).show("n_ie");
//Builder.create(im3).show("n_oe");
//Builder.create(im4).show("n_oe + gaussian");
//Builder.create(im5).show("ADU_out");
}
private double gamma(double shape, double scale) {
shape = Math.max(1E-6, shape);
return new GammaDistribution(shape, scale).sample();
}
private int poisson(double lambda) {
lambda = Math.max(1E-6, lambda);
return new PoissonDistribution(lambda).sample();
}
private double binomial(double p, int ntrials) {
return psrand.nextBinomial(p, ntrials);
}
private double gaussian(double stdev) {
return psrand.nextGaussian(0, stdev);
}
public void add_old(float[][] frame) {
int n = frame.length;
int m = frame[0].length;
ArrayOperations.multiply(frame, (float)quantumEfficiency);
// signal
if (noiseEnable[SHOT]) {
//float norm = ArrayOperations.getNorm(frame);
float factor = 1f / (float)(noiseParam[SHOT]);
float norm = 1f;
ArrayOperations.multiply(frame, factor/norm);
poissonNoise(frame);
//float norm1 = ArrayOperations.getNorm(frame);
//ArrayOperations.multiply(frame, norm/norm1);
ArrayOperations.multiply(frame, (float)(noiseParam[SHOT]));
}
if (noiseEnable[EMCCD]) {
ArrayOperations.linear(frame, (float)noiseParam[EMCCD]*gain, offset);
}
else {
ArrayOperations.linear(frame, gain, offset);
}
// dark current
float dark[][] = new float[n][m];
if (noiseEnable[READOUT])
gaussianNoise(dark, baseline, noiseParam[READOUT]);
else
ArrayOperations.fill(dark, baseline);
if (noiseEnable[DARK]) {
//float norm = ArrayOperations.getNorm(dark);
float norm = 1f;
float factor = 1f / (float)(noiseParam[DARK]);
ArrayOperations.multiply(dark, factor/norm);
poissonNoise(dark);
//float norm1 = ArrayOperations.getNorm(dark);
//ArrayOperations.multiply(dark, norm/norm1);
ArrayOperations.multiply(dark, (float)(noiseParam[DARK]));
}
ArrayOperations.increment(frame, dark);
}
// y = a * (x-b)
// y/a + b = x
// x = (1/a) * y + a *(1/a) * (b)
// x = (1/a) * (y + a * b)
/*
public void rescale(float[][] arr, float a, float b) {
int n = arr.length;
for(int y=0;y<n;y++)
for(int x=0;x<n;x++)
arr[x][y] = a*(arr[x][y]-b);
}
*/
public void poissonNoise(float frame[][]) {
int n = frame.length;
for(int y=0;y<n;y++)
for(int x=0;x<n;x++) {
frame[x][y] = (float)nextPoisson(frame[x][y]);
}
}
public void gaussianNoise(float frame[][], double mean, double stdev) {
int n = frame.length;
for(int y=0;y<n;y++)
for(int x=0;x<n;x++)
frame[x][y] += (float)psrand.nextGaussian(mean, stdev);
}
public void gaussianNoisePositive(float frame[][], double mean, double stdev) {
int n = frame.length;
double g = 0;
for(int y=0;y<n;y++)
for(int x=0;x<n;x++) {
g = (float)psrand.nextGaussian(mean, stdev);
frame[x][y] += (g > 0 ? g : 0.0);
}
}
public double nextPoisson(double lambda) {
if (lambda==0)
return 0.0;
if (lambda<100) {
// Knuth algorithm
double L = Math.exp(-lambda);
int k = 0;
double p = 1;
do {
k++;
p *= psrand.nextDouble();
} while (p >= L);
return (double)(k - 1);
}
else {
// Gaussian distribution which approximates the Poisson one for large lambda values
double value = (psrand.nextGaussian()*Math.sqrt(lambda))+lambda;
return value;
}
}
public void report(PrintStream out) {
out.print("<h2>Noise</h2>");
out.print("<table cellpadding=5>");
for(int i=0; i<names.length; i++) {
String param = " " + noiseParam[i];
if (noiseEnable[i])
out.print("<tr><td></td><td>" + names[i] +
"</td><td> Enable •" + param + " (" + distribution[i] + ")</td><td></td></tr>");
else
out.print("<tr><td></td><td>" + names[i] +
"</td><td> None</td><td></td></tr>");
}
out.print("</table>");
}
}
| Java |
2D | SMLM-Challenge/Challenge2016 | Simulator/Simulator-Java/src/smlms/simulation/AutofluorescenceModule.java | .java | 6,558 | 228 | package smlms.simulation;
import ij.IJ;
import ij.ImagePlus;
import ij.ImageStack;
import ij.process.FloatProcessor;
import imageware.Builder;
import imageware.ImageWare;
import java.util.Vector;
import org.apache.commons.math3.distribution.PoissonDistribution;
import smlms.file.Fluorophores;
import smlms.tools.ArrayOperations;
import smlms.tools.Chrono;
import smlms.tools.PsRandom;
import smlms.tools.Tools;
public class AutofluorescenceModule {
final static public int NONE = 0;
final static public int STATIC = 1;
final static public int DYNAMIC = 2;
final static public String[] evolutions = new String[] {"None", "Static", "Dynamic"};
final static public int STRUCTURE = 1;
final static public int RANDOM = 2;
final static public String[] names = new String[] {"None", "Structure", "Random"};
private int evolution = NONE;
private float[][] background;
private double backGain;
public double backPoisson;
private int nbSources;
private int nbScale;
private double diffusion;
private double displacement;
private double size;
private int type;
private double defocus;
private float gain;
private double change;
private float offset;
private Viewport viewport;
private PsRandom psrand;
private Vector<AutofluorescenceSource> list[] = null;
public AutofluorescenceModule(PsRandom psrand, Viewport viewport, int evolution) {
this.psrand = psrand;
this.viewport = viewport;
this.evolution = evolution;
}
public void setBackground(double backGain, double backPoisson) {
this.backGain = backGain;
this.backPoisson = backPoisson;
}
public void setSources(int type, int nbSources, int nbScale, double defocus, double diffusion, double displacement, double size, double change, double gain) {
this.type = type;
this.nbSources = nbSources;
this.nbScale = nbScale;
this.defocus = defocus;
this.diffusion = diffusion;
this.displacement = displacement;
this.size = size;
this.gain = (float)gain;
this.change = change;
}
public void test(int nbFrames, Fluorophores fluos) {
int nx = viewport.getFoVXPixel();
int ny = viewport.getFoVYPixel();
ImageStack stack = new ImageStack(nx, ny);
for(int frame=0; frame<nbFrames; frame++) {
Chrono.reset();
float[][] image = new float[nx][ny];
create(nx, ny, fluos, 1);
add(image);
FloatProcessor fp = new FloatProcessor(image);
stack.addSlice("", fp);
Chrono.print("add " + frame);
}
ImagePlus imp = new ImagePlus("Test Background", stack);
imp.show();
}
public void add(float image[][]) {
if (image == null)
return;
if (background == null)
return;
ArrayOperations.add(image, background);
}
public void create(int nx, int ny, Fluorophores fluos, double correctionSampling) {
if (evolution == NONE)
return;
viewport.setThicknessNano(Double.MAX_VALUE);
background = new float[nx][ny];
for (int i=0; i<background.length; i++)
for (int j=0; j<background[0].length; j++)
background[i][j] = (float)(backGain* (new PoissonDistribution(backPoisson*correctionSampling).sample()));
/*
if (list == null) {
list = create(viewport, fluos);
place(background, list);
//offset = (float)psrand.nextGaussian(offsetMean, offsetStdv);
if (type != NONE)
ArrayOperations.normalize(background, gain, offset);
else
ArrayOperations.increment(background, offset);
}
if (evolution == DYNAMIC) {
move(list, change);
place(background, list);
if (type != NONE)
ArrayOperations.normalize(background, gain, offset);
else
ArrayOperations.increment(background, offset);
}
*/
}
private void move(Vector<AutofluorescenceSource>[] list, double percentageOfChange) {
int nbScale = list.length;
Vector<AutofluorescenceSource> flatlist = new Vector<AutofluorescenceSource>();
for(int k=0; k<nbScale; k++) {
int ns = list[k].size();
for(int i=0; i<ns; i++) {
flatlist.add(list[k].get(i));
}
}
int n = flatlist.size();
int nchange = Tools.round(n * percentageOfChange / 100.0);
for(int k=0; k<nchange; k++) {
int index = (int)(psrand.nextDouble()*n);
flatlist.get(index).move(displacement);
}
}
private void place(float[][] background, Vector<AutofluorescenceSource>[] list) {
int n = background.length;
int m = background[0].length;
int nbScale = list.length;
ImageWare sum = Builder.create(n, m, 1, ImageWare.FLOAT);
for(int k=0; k<nbScale; k++) {
double sigma = (k+1)*viewport.convertIntegerPixel(defocus)/nbScale;
int ns = list[k].size();
if (ns > 0) {
ImageWare im = Builder.create(n, m, 1, ImageWare.FLOAT);
for(int i=0; i<ns; i++) {
list[k].get(i).draw(im);
}
im.smoothGaussian(sigma);
sum.add(im);
}
}
sum.getBlockXY(0, 0, 0, background, ImageWare.MIRROR);
}
private Vector<AutofluorescenceSource>[] create(Viewport viewport, Fluorophores fluorophoresAll) {
int n = viewport.getFoVXPixel();
int m = viewport.getFoVYPixel();
ImageWare sum = Builder.create(n, m, 1, ImageWare.FLOAT);
double nbSourceMean = nbSources / (double)nbScale;
int nsources[] = new int[nbScale];
for(int k=0; k<nbScale; k++) {
nsources[k] = (int)(0.7*nbSourceMean + psrand.nextGaussian(nbSourceMean*0.3, 1));
}
Vector<AutofluorescenceSource>[] list = new Vector[nbScale];
for(int k=0; k<nbScale; k++) {
double sigma = (k+1)*viewport.convertIntegerPixel(defocus)/nbScale;
ImageWare im = Builder.create(n, m, 1, ImageWare.FLOAT);
list[k] = new Vector<AutofluorescenceSource>();
if (type == STRUCTURE) {
for(int i=0; i<nsources[k]; i++) {
int nf = fluorophoresAll.size();
double min = Double.MAX_VALUE;
double xo = 0;
double yo = 0;
for(int a=0; a<10; a++) {
int index = Math.max(0, Math.min(nf-1, (int)(psrand.nextDouble() * nf)));
double xr = fluorophoresAll.get(index).x;
double yr = fluorophoresAll.get(index).y;
double v = sum.getPixel((int)viewport.screenX(xr), (int)viewport.screenY(yr), 0);
if (v < min) {
min = v;
xo = xr;
yo = yr;
}
}
AutofluorescenceSource source = new AutofluorescenceSource(psrand, viewport, xo, yo, sigma, size, diffusion);
list[k].add(source);
source.draw(im);
}
}
if (type == RANDOM) {
for(int i=0; i<nsources[k]; i++) {
AutofluorescenceSource source = new AutofluorescenceSource(psrand, viewport, sigma, size, diffusion);
list[k].add(source);
source.draw(im);
}
}
im.smoothGaussian(sigma);
sum.add(im);
}
return list;
}
}
| Java |
2D | SMLM-Challenge/Challenge2016 | Simulator/Simulator-Java/src/smlms/simulation/ReportHTML.java | .java | 2,542 | 80 | package smlms.simulation;
import ij.IJ;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.PrintStream;
public class ReportHTML extends PrintStream {
public ReportHTML(String path, String filename) throws FileNotFoundException {
super(new FileOutputStream(path+File.separator+filename));
}
public void printTitle(String name) {
print("<p class=\"report_title\" style=\"clear:both\">" + name + "</p>\n");
}
public void printSection(String name) {
print("<p class=\"report_section\" style=\"clear:both\">" + name + "</p>\n");
}
public void printValue(String value) {
print("<td class=\"report_value\">" + value + "</td>");
}
public void printTH(String name) {
print("<td class=\"report_header\">" + name + "</td>\n");
}
public void printTD(String name) {
print("<td valign=\"top\" class=\"report_param\">" + name + "</td>\n");
}
public void printTD(String name, boolean left) {
if (left)
print("<td valign=\"top\" class=\"report_param_lvert\">" + name + "</td>\n");
else
print("<td valign=\"top\" class=\"report_param_rvert\">" + name + "</td>\n");
}
public void printHeader(String name, int span) {
print("<tr><td colspan=\"" + span + "\" class=\"report_header\">" + name + "</td></tr>\n");
}
public void printParam(String name, double value, int digit, String unit) {
print("<tr><td class=\"report_param\">" + name + "</td><td class=\"report_value\">" + IJ.d2s(value,digit) + "</td><td class=\"report_unit\">" + unit + "</td></tr>\n");
}
public void printParam(String name, String value, String unit) {
print("<tr><td class=\"report_param\">" + name + "</td><td class=\"report_value\">" + value + "</td><td class=\"report_unit\">" + unit + "</td></tr>\n");
}
public void printField(String name, double nx, double ny, int digit, String unit) {
print("<tr><td class=\"report_param\">" + name + "</td><td class=\"report_value\">" + IJ.d2s(nx,digit) + "x" + IJ.d2s(ny,digit) + "</td><td class=\"report_unit\">" + unit + "</td></tr>\n");
}
public void printFile(String filename) {
if (!(new File(filename)).exists())
return;
try {
String content = "";
BufferedReader file = new BufferedReader(new FileReader(filename));
String line;
while((line = file.readLine()) != null) {
content += line + "\n";
}
file.close();
print(content);
}
catch(IOException ex) {
IJ.error("printFile: " + ex);
}
}
}
| Java |
2D | SMLM-Challenge/Challenge2016 | Simulator/Simulator-Java/src/smlms/simulation/SequenceFactoryDialog.java | .java | 40,587 | 985 | package smlms.simulation;
import ij.IJ;
import ij.gui.GUI;
import imageware.ImageWare;
import java.awt.Color;
import java.awt.Frame;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import java.io.File;
import java.util.ArrayList;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JComboBox;
import javax.swing.JDialog;
import javax.swing.JFileChooser;
import javax.swing.JLabel;
import javax.swing.JTabbedPane;
import javax.swing.JTextField;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import smlms.file.FluorophoreComponent;
import smlms.file.Fluorophores;
import smlms.simulation.defocussed2dfunction.ZFunction;
import smlms.simulation.gl.PSFParameters;
import smlms.tools.Chrono;
import smlms.tools.Point3D;
import smlms.tools.PsRandom;
import smlms.tools.Tools;
import smlms.tools.Verbose;
import additionaluserinterface.GridPanel;
import additionaluserinterface.GridToolbar;
import additionaluserinterface.Settings;
import additionaluserinterface.SpinnerDouble;
import additionaluserinterface.SpinnerInteger;
import additionaluserinterface.WalkBar;
import bpalm.simulator.BPALMParameters;
public class SequenceFactoryDialog extends JDialog implements ActionListener, WindowListener, ChangeListener, Runnable {
protected WalkBar walk = new WalkBar("(c) 2010 EPFL, BIG", false, false, true);
protected Settings settings = new Settings("localization-microscopy", IJ.getDirectory("plugins") + "localization-microscopy.txt");
protected Thread thread = null;
protected JButton bnRun = new JButton("Run");
private JButton bnTestAutofluo = new JButton("Test");
private JButton bnTestNoise = new JButton("Test");
private JButton bnTestBeadPSF = new JButton("Generate PSF");
private JButton bnSavePSF = new JButton("Save");
private JButton bnTestAccuracy = new JButton("Test");
private JButton bnReportParameters = new JButton("Parameters");
private JButton bnReportAccuracy = new JButton("Accuracy");
private JButton bnReportPSF = new JButton("PSF");
private JButton bnReportAll = new JButton("All");
private JButton bnSaveParams = new JButton("Store");
private JButton bnLoadParams = new JButton("Load");
private JButton bnBrowsePSF[] = new JButton[] {new JButton("Browse"), new JButton("Browse"), new JButton("Browse")};
private JButton bnLoadPSF[] = new JButton[] {new JButton("Load"), new JButton("Load"), new JButton("Load")};
protected JButton job = bnRun;
protected SpinnerDouble spnFluoPixelsize = new SpinnerDouble(15, 0, 100000, 1);
protected JCheckBox chkFluoAllFrames = new JCheckBox("All Frames", true);
public JComboBox cmbThreading = new JComboBox(SequenceFactory.names);
protected SpinnerInteger spnSeedRandom = new SpinnerInteger(123, 0, 10000, 1);
protected SpinnerDouble spnFluoAmplitude = new SpinnerDouble(2000, 0, 10000000, 100);
// protected SpinnerInteger spnPixelsizeStorePSF = new SpinnerInteger(10, 1, 100, 1);
protected SpinnerInteger spnOversamplingConvolve = new SpinnerInteger(2, 1, 100, 1);
protected SpinnerInteger spnOversamplingWorking = new SpinnerInteger(2, 1, 100, 1);
protected SpinnerDouble spnQuantumEfficiency = new SpinnerDouble(2, 0, 10000000, 1);
protected SpinnerDouble spnCameraGain = new SpinnerDouble(2, 0, 10000000, 1);
protected SpinnerDouble spnCameraOffset = new SpinnerDouble(2, -100000, 10000000, 1);
protected SpinnerInteger spnCameraResolution = new SpinnerInteger(256, 0, 100000, 1);
protected SpinnerDouble spnPixelsizeCamera = new SpinnerDouble(150, 0, 100000, 1);
protected JComboBox cmbCameraQuantization = new JComboBox(CameraModule.quantizationNames);
protected SpinnerDouble spnCameraSaturation = new SpinnerDouble(100000, -10000000, 10000000, 1);
protected JComboBox cmbCameraFileFormat = new JComboBox(CameraModule.names);
protected SpinnerDouble spnBaseline = new SpinnerDouble(0, -10000000, 10000000, 1);
protected JCheckBox chkNoises[] = new JCheckBox[NoiseModule.names.length];
protected SpinnerDouble spnNoises[] = new SpinnerDouble[NoiseModule.names.length];
protected JComboBox cmbVerbose = new JComboBox(Verbose.names);
protected JComboBox cmbAutofluoMode = new JComboBox(AutofluorescenceModule.evolutions);
protected SpinnerDouble spnAutofluoDefocus = new SpinnerDouble(1000, 0, 100000, 100);
protected SpinnerDouble spnAutofluoChange = new SpinnerDouble(100, 0, 100, 100);
protected SpinnerDouble spnAutofluoDiffusion = new SpinnerDouble(100, 0, 100000, 100);
protected SpinnerDouble spnAutofluoDispl = new SpinnerDouble(100, 0, 100000, 100);
protected JComboBox cmbAutofluoSources = new JComboBox(AutofluorescenceModule.names);
protected SpinnerDouble spnAutofluoGain = new SpinnerDouble(100, -100000, 100000, 100);
protected SpinnerDouble spnAutofluoOffsetMean = new SpinnerDouble(100, -100000, 100000, 100);
protected SpinnerDouble spnAutofluoOffsetStdv = new SpinnerDouble(0, 0, 100000, 100);
protected SpinnerInteger spnAutofluoNbSources = new SpinnerInteger(20, 0, 100000, 1);
protected SpinnerInteger spnAutofluoNbScale = new SpinnerInteger(20, 0, 100000, 1);
protected SpinnerDouble spnAutofluoSize = new SpinnerDouble(100, 100, 100000, 100);
protected JCheckBox chkStats = new JCheckBox("Stats");
protected JCheckBox chkProjection = new JCheckBox("Projection");
protected JCheckBox chkReport = new JCheckBox("Report");
protected JComboBox cmbMode = new JComboBox(SequenceFactory.modes);
protected SpinnerInteger spnNbFluorophores = new SpinnerInteger(10000, 1, 10000000, 10000);
protected SpinnerInteger spnFirstFrame = new SpinnerInteger(1, 1, 999999, 1);
protected SpinnerInteger spnLastFrame = new SpinnerInteger(10, 1, 999999, 1);
protected SpinnerInteger spnIntervalFrame = new SpinnerInteger(10, 1, 1000, 1);
protected SpinnerDouble spnBiplaneDepth = new SpinnerDouble(0, -9999, 9999, 100);
protected SpinnerDouble spnBiplaneDeltaZ1 = new SpinnerDouble(0, -9999, 9999, 1);
protected SpinnerDouble spnBiplaneDeltaZ2 = new SpinnerDouble(100, -9999, 9999, 100);
protected SpinnerDouble spnBiplaneNI = new SpinnerDouble(1, 0, 9999, 0.1);
protected SpinnerDouble spnBiplaneNS = new SpinnerDouble(1, 0, 9999, 0.1);
protected SpinnerDouble spnBiplaneTI = new SpinnerDouble(150, 0, 9999, 0.1);
protected SpinnerDouble spnBiplaneDX = new SpinnerDouble(100, 0, 9999, 0.1);
protected SpinnerDouble spnBiplaneDY = new SpinnerDouble(100, 0, 9999, 0.1);
protected SpinnerDouble spnBiplaneRotation = new SpinnerDouble(0, -9999, 9999, 0.1);
protected SpinnerDouble spnBiplaneScale = new SpinnerDouble(1, -9999, 9999, 0.1);
protected JComboBox cmbBiplaneOrientation = new JComboBox(new String[] {"Rows", "Columns", "One channel"});
protected SpinnerDouble spnWavelength = new SpinnerDouble(500, 200, 10000, 10);
protected SpinnerDouble spnNS = new SpinnerDouble(1, 0.1, 100, 0.1);
protected SpinnerDouble spnNI = new SpinnerDouble(1, 0.1, 100, 0.1);
protected SpinnerDouble spnNA = new SpinnerDouble(1, 0.1, 100, 0.1);
protected SpinnerDouble spnFWHMFactor = new SpinnerDouble(1, 0, 100, 1);
protected SpinnerInteger spnOversamplingLateral = new SpinnerInteger(1, 1, 1000, 1);
protected SpinnerInteger spnOversamplingAxial = new SpinnerInteger(1, 1, 1000, 1);
protected SpinnerDouble spnDeltaZ = new SpinnerDouble(20, -10000, 10000, 1);
protected SpinnerDouble spnBeadSize = new SpinnerDouble(0, 0, 10000, 10);
protected SpinnerDouble spnThickness = new SpinnerDouble(500, 0, 100000, 10);
protected SpinnerDouble spnFocalPlaneTI = new SpinnerDouble(500, -100000, 100000, 10);
protected SpinnerDouble spnDefocusPlane = new SpinnerDouble(1000, -100000, 100000, 10);
protected JComboBox cmbPSFModelXY = new JComboBox(PSFModule.namesXY);
protected JComboBox cmbPSFModelXYZ = new JComboBox(PSFModule.namesXYZ);
protected JComboBox cmbPSFModelZ = new JComboBox(ZFunction.names);
private JLabel lblAccuracy_stats = new JLabel("FWHM");
private JLabel lblAccuracy_quant = new JLabel("Pixelsize");
private JLabel lblAccuracy_back = new JLabel("Background");
private JLabel lblAccuracy_N = new JLabel("Nb photons");
private JLabel lblAccuracy_Thomson = new JLabel("Accuracy");
protected JLabel lblDiffractionLimit = new JLabel("000 nm");
protected JLabel lblFoV = new JLabel("Field of view x Depth");
protected JLabel lblFWHM = new JLabel("500 nm");
protected JLabel lblSummaryPlane = new JLabel("Double FWHM");
protected JLabel lblOversampling = new JLabel("Oversampling");
protected JTextField txtPSFFile[] = new JTextField[]
{new JTextField("-", 20), new JTextField("-", 20), new JTextField("-", 20), new JTextField("-", 20), new JTextField("-", 20), new JTextField("-", 20), new JTextField("-", 20)};
protected JLabel lblPSFFile[] = new JLabel[]
{new JLabel(), new JLabel(), new JLabel(), new JLabel(), new JLabel(), new JLabel(), new JLabel()};
protected JTabbedPane tabPSF = new JTabbedPane();
protected JLabel lblConvolveInfo = new JLabel("------------------");
protected PsRandom psrand = new PsRandom();
public String path;
protected FluorophoreComponent panel = new FluorophoreComponent(settings, "Activations");
public SequenceFactoryDialog() {
super(new Frame(), "Sequence Factory");
for(int i=0; i<NoiseModule.names.length; i++) {
chkNoises[i] = new JCheckBox(NoiseModule.names[i]);
spnNoises[i] = new SpinnerDouble(0, -100000, 10000000, 100);
}
loadSettings();
int tabpsf = settings.loadValue("tabpsf", 1);
// Camera
lblFoV.setBorder(BorderFactory.createEtchedBorder());
lblFoV.setBackground(new Color(150, 150, 192, 10));
GridToolbar pnCamera = new GridToolbar("Camera");
pnCamera.place(0, 0, new JLabel("Quantum Efficiency"));
pnCamera.place(0, 1, spnQuantumEfficiency);
pnCamera.place(0, 2, new JLabel("<html>Ph. to e<sup>-</sup>"));
pnCamera.place(2, 0, new JLabel("Thickness"));
pnCamera.place(2, 1, spnThickness);
pnCamera.place(2, 2, new JLabel("nm"));
pnCamera.place(3, 0, new JLabel("Resolution"));
pnCamera.place(3, 1, spnCameraResolution);
pnCamera.place(3, 2, new JLabel("pixels"));
pnCamera.place(4, 0, new JLabel("Pixelsize"));
pnCamera.place(4, 1, spnPixelsizeCamera);
pnCamera.place(4, 2, new JLabel("nm/pix"));
pnCamera.place(5, 0, new JLabel("FoV / DoF"));
pnCamera.place(5, 1, lblFoV);
pnCamera.place(5, 2, new JLabel("nm"));
// Optic
lblDiffractionLimit.setBorder(BorderFactory.createEtchedBorder());
lblDiffractionLimit.setBackground(new Color(150, 150, 192, 10));
GridToolbar pnOptics = new GridToolbar("Optics");
pnOptics.place(1, 0, new JLabel("Wavelength"));
pnOptics.place(1, 1, spnWavelength);
pnOptics.place(1, 2, new JLabel("nm"));
pnOptics.place(2, 0, new JLabel("Numerical Aperture (NA)"));
pnOptics.place(2, 1, spnNA);
pnOptics.place(2, 2, lblDiffractionLimit);
pnOptics.place(4, 0, new JLabel("Focal Plane (TI)"));
pnOptics.place(4, 1, spnFocalPlaneTI);
pnOptics.place(4, 2, new JLabel("nm"));
// Acquistion
GridToolbar pnAcquisition = new GridToolbar(false);
pnAcquisition.place(5, 0, pnCamera);
pnAcquisition.place(7, 0, pnOptics);
// ADC
GridToolbar pnConverter = new GridToolbar("Electron conversion");
pnConverter.place(0, 0, 3, 1, new JLabel(""));
pnConverter.place(1, 0, new JLabel("e- per ADU"));
pnConverter.place(1, 1, spnCameraGain);
pnConverter.place(1, 2, new JLabel("<html>e<sup>-</sup> to DN</html>"));
pnConverter.place(3, 0, new JLabel("Offset"));
pnConverter.place(3, 1, spnCameraOffset);
pnConverter.place(3, 2, new JLabel("<html>DN</html>"));
pnConverter.place(4, 0, new JLabel("Baseline"));
pnConverter.place(4, 1, spnBaseline);
pnConverter.place(4, 2, new JLabel("<html>DN</html>"));
GridToolbar pnQuantization = new GridToolbar("Digitalization");
pnQuantization.place(6, 0, new JLabel("Saturation"));
pnQuantization.place(6, 1, spnCameraSaturation);
pnQuantization.place(7, 0, new JLabel("Quantization"));
pnQuantization.place(7, 1, 2, 1, cmbCameraQuantization);
pnQuantization.place(8, 0, new JLabel("File Format"));
pnQuantization.place(8, 1, cmbCameraFileFormat);
GridToolbar pnADC = new GridToolbar(false);
pnADC.place(5, 0, pnConverter);
pnADC.place(7, 0, pnQuantization);
// FocalPlane
GridPanel pnPSFSave = new GridPanel(false);
pnPSFSave.place(5, 0, new JLabel("Size (nm)"));
pnPSFSave.place(5, 1, spnBeadSize);
pnPSFSave.place(5, 2, bnTestBeadPSF);
//
GridToolbar pnPSF0 = new GridToolbar(false);
pnPSF0.place(1, 0, new JLabel("Dirac function"));
pnPSF0.place(2, 0, new JLabel("Only a point source"));
pnPSF0.place(3, 0, new JLabel("No axial dependency"));
//
GridToolbar pnPSF1 = new GridToolbar(false);
lblFWHM.setBorder(BorderFactory.createEtchedBorder());
lblFWHM.setBackground(new Color(150, 150, 192, 10));
lblSummaryPlane.setBorder(BorderFactory.createEtchedBorder());
lblSummaryPlane.setBackground(new Color(150, 150, 192, 10));
pnPSF1.place(0, 0, new JLabel("XY Function"));
pnPSF1.place(0, 1, 2, 1, cmbPSFModelXY);
pnPSF1.place(1, 0, new JLabel("FWHM factor"));
pnPSF1.place(1, 1, spnFWHMFactor);
pnPSF1.place(2, 0, new JLabel("FWHM"));
pnPSF1.place(2, 1, lblFWHM);
pnPSF1.place(2, 2, new JLabel("nm"));
pnPSF1.place(3, 0, new JLabel("Z Function"));
pnPSF1.place(3, 1, 2, 1, cmbPSFModelZ);
pnPSF1.place(4, 2, new JLabel("nm"));
pnPSF1.place(5, 0, new JLabel("Defocus Plane"));
pnPSF1.place(5, 1, spnDefocusPlane);
pnPSF1.place(5, 2, new JLabel("nm"));
pnPSF1.place(6, 0, 3, 1, lblSummaryPlane);
//
GridToolbar pnPSF2 = new GridToolbar(false);
pnPSF2.place(0, 0, 4, 1, new JComboBox(PSFModule.namesXYZ));
pnPSF2.place(1, 0, 4, 1, new JLabel("Refractive Index"));
pnPSF2.place(2, 0, new JLabel("ns"));
pnPSF2.place(2, 1, spnNS);
pnPSF2.place(2, 2, new JLabel("ni"));
pnPSF2.place(2, 3, spnNI);
pnPSF2.place(3, 0, 4, 1, new JLabel("Oversampling - Accurary vs speed"));
pnPSF2.place(4, 0, new JLabel("Lateral"));
pnPSF2.place(4, 1, spnOversamplingLateral);
pnPSF2.place(4, 2, new JLabel("Axial"));
pnPSF2.place(4, 3, spnOversamplingAxial);
pnPSF2.place(5, 0, new JLabel("DeltaZ"));
pnPSF2.place(5, 1, spnDeltaZ);
GridPanel pnPSF3 = new GridPanel(false, 5);
for(int i=0; i<3; i++) {
lblPSFFile[i].setBorder(BorderFactory.createEtchedBorder());
pnPSF3.place(0+i*2, 0, txtPSFFile[i]);
pnPSF3.place(0+i*2, 1, bnBrowsePSF[i]);
pnPSF3.place(1+i*2, 1, bnLoadPSF[i]);
pnPSF3.place(1+i*2, 0, lblPSFFile[i]);
}
GridPanel pnPSF4 = new GridPanel(false, 5);
pnPSF4.place(0, 0, 3, 1, cmbBiplaneOrientation);
pnPSF4.place(1, 0, new JLabel("Delta Plane 1/2"));
pnPSF4.place(1, 1, spnBiplaneDeltaZ1);
pnPSF4.place(1, 2, spnBiplaneDeltaZ2);
pnPSF4.place(3, 0, new JLabel("Depth / dist (ti)"));
pnPSF4.place(3, 1, spnBiplaneDepth);
pnPSF4.place(3, 2, spnBiplaneTI);
pnPSF4.place(4, 0, new JLabel("Index ni/ns"));
pnPSF4.place(4, 1, spnBiplaneNI);
pnPSF4.place(4, 2, spnBiplaneNS);
pnPSF4.place(5, 0, new JLabel("Trans dx /dx"));
pnPSF4.place(5, 1, spnBiplaneDX);
pnPSF4.place(5, 2, spnBiplaneDY);
pnPSF4.place(6, 0, new JLabel("Rotation/Scale"));
pnPSF4.place(6, 1, spnBiplaneRotation);
pnPSF4.place(6, 2, spnBiplaneScale);
tabPSF.add("PSF Point", pnPSF0);
tabPSF.add("PSF 2Dz", pnPSF1);
tabPSF.add("PSF G&L", pnPSF2);
tabPSF.add("PSF File", pnPSF3);
tabPSF.add("Biplane", pnPSF4);
tabPSF.setSelectedIndex(tabpsf);
GridToolbar pnPSF = new GridToolbar(false, 1);
pnPSF.place(3, 0, pnPSFSave);
pnPSF.place(4, 0, tabPSF);
// Autofluo
GridToolbar pnAutofluo1 = new GridToolbar("Background");
pnAutofluo1.place(1, 0, new JLabel("Gain/Poisson"));
pnAutofluo1.place(1, 1, spnAutofluoOffsetMean);
pnAutofluo1.place(1, 2, spnAutofluoOffsetStdv);
GridToolbar pnAutofluo2 = new GridToolbar("Sources");
pnAutofluo2.place(0, 0, cmbAutofluoSources);
pnAutofluo2.place(0, 1, new JLabel("Nb Sources", JLabel.RIGHT));
pnAutofluo2.place(0, 2, spnAutofluoNbSources);
pnAutofluo2.place(2, 0, new JLabel("Gain/Size (nm)"));
pnAutofluo2.place(2, 1, spnAutofluoGain);
pnAutofluo2.place(2, 2, spnAutofluoSize);
pnAutofluo2.place(3, 0, new JLabel("Move/Diff (nm"));
pnAutofluo2.place(3, 1, spnAutofluoDispl);
pnAutofluo2.place(3, 2, spnAutofluoDiffusion);
pnAutofluo2.place(4, 0, new JLabel("Defocus (nm)/Scale"));
pnAutofluo2.place(4, 1, this.spnAutofluoDefocus);
pnAutofluo2.place(4, 2, this.spnAutofluoNbScale);
pnAutofluo2.place(5, 0, new JLabel("Dynamics"));
pnAutofluo2.place(5, 1, this.spnAutofluoChange);
pnAutofluo2.place(5, 2, new JLabel("% of change"));
GridPanel pnAutofluo = new GridPanel(false);
pnAutofluo.place(7, 0, new JLabel("Evolution"));
pnAutofluo.place(7, 1, cmbAutofluoMode);
pnAutofluo.place(7, 2, bnTestAutofluo);
pnAutofluo.place(8, 0, 3, 1, pnAutofluo1);
pnAutofluo.place(9, 0, 3, 1, pnAutofluo2);
// Noise
GridToolbar pnNoise = new GridToolbar(false);
int row = 1;
for(int i=0; i<NoiseModule.names.length; i++) {
pnNoise.place(row, 0, chkNoises[i]);
pnNoise.place(row, 1, spnNoises[i]);
pnNoise.place(row, 3, new JLabel(NoiseModule.distribution[i]));
row++;
}
pnNoise.place(row, 0, bnTestNoise);
// Sequencer
GridPanel pnSequencer = new GridPanel(false);
lblConvolveInfo.setBorder(BorderFactory.createEtchedBorder());
pnSequencer.place(1, 0, 2, 1, lblConvolveInfo);
pnSequencer.place(1, 2, cmbMode);
pnSequencer.place(4, 0, chkProjection);
pnSequencer.place(4, 1, chkStats);
pnSequencer.place(4, 2, chkReport);
pnSequencer.place(5, 0, spnFirstFrame);
pnSequencer.place(5, 1, spnLastFrame);
pnSequencer.place(5, 2, spnIntervalFrame);
pnSequencer.place(6, 0, cmbThreading);
pnSequencer.place(6, 1, cmbVerbose);
pnSequencer.place(6, 2, bnRun);
// Computation
GridPanel pnComputation = new GridPanel(false);
lblOversampling.setBorder(BorderFactory.createEtchedBorder());
pnComputation.place(0, 0, 2, 1, lblOversampling);
pnComputation.place(0, 2, new JLabel("Random Seed"));
pnComputation.place(0, 3, spnSeedRandom);
pnComputation.place(1, 0, new JLabel("PSF Convolve"));
pnComputation.place(1, 1, spnOversamplingConvolve);
pnComputation.place(1, 2, new JLabel("Working"));
pnComputation.place(1, 3, spnOversamplingWorking);
// Report
GridPanel pnReport = new GridPanel(false);
pnReport.place(0, 0, bnReportAccuracy);
pnReport.place(0, 2, bnReportPSF);
pnReport.place(1, 0, bnReportParameters);
pnReport.place(1, 1, bnReportAll);
pnReport.place(5, 0, bnSaveParams);
pnReport.place(5, 1, bnLoadParams);
// Report
GridPanel pnAccuracy = new GridPanel(false);
lblAccuracy_stats.setBorder(BorderFactory.createEtchedBorder());
lblAccuracy_quant.setBorder(BorderFactory.createEtchedBorder());
lblAccuracy_back.setBorder(BorderFactory.createEtchedBorder());
lblAccuracy_N.setBorder(BorderFactory.createEtchedBorder());
lblAccuracy_Thomson.setBorder(BorderFactory.createEtchedBorder());
pnAccuracy.place(0, 0, new JLabel("Stat"));
pnAccuracy.place(0, 1, lblAccuracy_stats);
pnAccuracy.place(0, 2, new JLabel("Quan"));
pnAccuracy.place(0, 3, lblAccuracy_quant);
pnAccuracy.place(1, 0, new JLabel("Back"));
pnAccuracy.place(1, 1, lblAccuracy_back);
pnAccuracy.place(1, 2, new JLabel("Npht"));
pnAccuracy.place(1, 3, lblAccuracy_N);
pnAccuracy.place(3, 0, 2, 1, new JLabel("Thomson Acc."));
pnAccuracy.place(3, 2, 1, 1, lblAccuracy_Thomson);
pnAccuracy.place(3, 3, 1, 1, bnTestAccuracy);
JTabbedPane tab2 = new JTabbedPane();
tab2.add("Camera", pnAcquisition);
tab2.add("PSF", pnPSF);
tab2.add("Autofluo.", pnAutofluo);
tab2.add("Noise", pnNoise);
tab2.add("ADC", pnADC);
JTabbedPane tab3 = new JTabbedPane();
tab3.add("Sequencer", pnSequencer);
tab3.add("Compute", pnComputation);
tab3.add("Accuracy", pnAccuracy);
tab3.add("Report", pnReport);
// Main
GridPanel pnMain = new GridPanel(false, 1);
pnMain.place(0, 0, panel);
pnMain.place(2, 0, tab2);
pnMain.place(4, 0, tab3);
pnMain.place(5, 0, walk);
addWindowListener(this);
spnNA.addChangeListener(this);
spnWavelength.addChangeListener(this);
spnThickness.addChangeListener(this);
spnCameraResolution.addChangeListener(this);
spnPixelsizeCamera.addChangeListener(this);
spnFWHMFactor.addChangeListener(this);
cmbCameraQuantization.addActionListener(this);
cmbPSFModelXY.addActionListener(this);
spnDefocusPlane.addChangeListener(this);
spnFocalPlaneTI.addChangeListener(this);
spnCameraResolution.addChangeListener(this);
bnReportAccuracy.addActionListener(this);
bnReportPSF.addActionListener(this);
bnReportAll.addActionListener(this);
bnReportParameters.addActionListener(this);
walk.getButtonClose().addActionListener(this);
bnTestAutofluo.addActionListener(this);
bnTestNoise.addActionListener(this);
bnTestBeadPSF.addActionListener(this);
bnSavePSF.addActionListener(this);
bnTestAccuracy.addActionListener(this);
bnRun.addActionListener(this);
bnSaveParams.addActionListener(this);
bnLoadParams.addActionListener(this);
for(int i=0; i<bnLoadPSF.length; i++)
bnLoadPSF[i].addActionListener(this);
for(int i=0; i<bnLoadPSF.length; i++)
bnBrowsePSF[i].addActionListener(this);
spnOversamplingConvolve.addChangeListener(this);
spnOversamplingWorking.addChangeListener(this);
tabPSF.addChangeListener(this);
add(pnMain);
pack();
setResizable(true);
GUI.center(this);
setVisible(true);
updateInterface();
}
public synchronized void actionPerformed(ActionEvent e) {
Verbose.setLevel(cmbVerbose.getSelectedIndex());
if (e.getSource() == walk.getButtonClose()) {
settings.storeValue("tabpsf", tabPSF.getSelectedIndex());
settings.storeRecordedItems();
dispose();
return;
}
for(int i=0; i<bnBrowsePSF.length; i++)
if (e.getSource() == bnBrowsePSF[i]) {
JFileChooser fc = new JFileChooser();
if (fc.showOpenDialog(null) == JFileChooser.APPROVE_OPTION)
txtPSFFile[i].setText(fc.getSelectedFile().getAbsolutePath());
}
for(int i=0; i<bnLoadPSF.length; i++)
if (e.getSource() == bnLoadPSF[i]) {
ArrayList<PSFModule> psfs = createPSFModule();
if (psfs.get(i) != null)
lblPSFFile[i].setText(psfs.get(i).getInfoArrayPSF());
}
if (e.getSource() == bnSavePSF)
new SequenceReporting(this).reportPSF(path);
if (e.getSource() == bnSaveParams)
saveParams();
if (e.getSource() == bnLoadParams)
loadParams();
if (e.getSource() == cmbPSFModelXY || e.getSource() == cmbCameraQuantization) {
updateInterface();
return;
}
if (e.getSource() == bnTestAccuracy)
testAccuracy();
if (e.getSource() == bnReportParameters)
new SequenceReporting(this).reportParameters(path);
if (e.getSource() == bnReportAccuracy)
new SequenceReporting(this).reportAccuracy(path);
if (e.getSource() == bnReportPSF)
new SequenceReporting(this).reportPSF(path);
if (e.getSource() == bnReportAll)
new SequenceReporting(this).reportAll(path);
job = null;
if (e.getSource() instanceof JButton)
job = (JButton)e.getSource();
if (job != null) {
if (thread == null) {
thread = new Thread(this);
thread.setPriority(Thread.MIN_PRIORITY);
thread.start();
}
}
}
public void run() {
psrand.setSeed(spnSeedRandom.get());
double pxc = spnPixelsizeCamera.get();
try {
// Output
Chrono.reset(9);
Viewport vwCamera = createViewport(pxc);
if (job == bnTestAutofluo) {
Fluorophores fluorophores[] = panel.getFluorophoresPerFrames();
createAutofluorescenceModule().test(5, fluorophores[0]);
}
else if (job == bnTestNoise)
createNoiseModule().test(vwCamera);
else if (job == bnTestBeadPSF) {
ArrayList<PSFModule> psfs = createPSFModule();
double c = spnOversamplingConvolve.get()*spnOversamplingWorking.get();
double size = spnBeadSize.get();
ImageWare psf = psfs.get(0).test(size, pxc/c, this.spnFocalPlaneTI.get());
psf.show("PSF-" + size + "-" + psfs.get(0).toString());
}
else if (job == bnRun) {
int first = spnFirstFrame.get();
int last = spnLastFrame.get();
int interval = spnIntervalFrame.get();
double fwhm = getDiffractionLimit() * spnFWHMFactor.get();
int upC = spnOversamplingConvolve.get();
int upW = spnOversamplingWorking.get();
ArrayList<PSFModule> psfs = createPSFModule();
CameraModule camera = createCameraModule();
NoiseModule noise = createNoiseModule();
AutofluorescenceModule autofluo = createAutofluorescenceModule();
path = panel.txtFile.getText();
IJ.log(" path " + path);
IJ.log(" parent " + (new File(path).getParent()));
String dataset = new File((new File(path).getParent())).getName();
IJ.log(" dataset " + dataset);
SequenceFactory sequencer = new SequenceFactory(dataset, first, last, interval, camera, psfs, noise, autofluo, createViewport(pxc), upC, upW);
int multithread = cmbThreading.getSelectedIndex();
int mode = cmbMode.getSelectedIndex();
SequenceReporting reporting = (chkReport.isSelected() ? new SequenceReporting(this) : null);
Fluorophores fluorophores[] = panel.getFluorophoresPerFrames();
sequencer.generate(path, multithread, fluorophores, fwhm, mode, chkProjection.isSelected(), chkStats.isSelected(), reporting);
}
}
catch(Exception ex) {
Verbose.exception(ex);
}
thread = null;
}
/**
* Create StructuralAutofluorescenceModule
*/
private AutofluorescenceModule createAutofluorescenceModule() {
int upC = spnOversamplingConvolve.get();
int upW = spnOversamplingWorking.get();
Viewport viewport = createViewport(spnPixelsizeCamera.get() / (upC * upW));
int mode = cmbAutofluoMode.getSelectedIndex();
int type = cmbAutofluoSources.getSelectedIndex();
int nbScale = spnAutofluoNbScale.get();
int nbSources = spnAutofluoNbSources.get();
double diffusion = spnAutofluoDiffusion.get();
double displacement = spnAutofluoDispl.get();
double defocus = spnAutofluoDefocus.get();
double change = spnAutofluoChange.get();
double gain = spnAutofluoGain.get();
double size = spnAutofluoSize.get();
AutofluorescenceModule autofluo = new AutofluorescenceModule(psrand, viewport, mode);
autofluo.setBackground(spnAutofluoOffsetMean.get(), spnAutofluoOffsetStdv.get());
autofluo.setSources(type, nbSources, nbScale, defocus, diffusion, displacement, size, change, gain);
return autofluo;
}
/**
* Create NoiseModule
*/
protected NoiseModule createNoiseModule() {
double gain = spnCameraGain.get();
double offset = spnCameraOffset.get();
double baseline = spnBaseline.get();
int n = chkNoises.length;
boolean[] enable = new boolean[n];
double[] param = new double[n];
double qe = spnQuantumEfficiency.get();
for(int i=0; i<n; i++) {
enable[i] = chkNoises[i].isSelected();
param[i] = spnNoises[i].get();
}
return new NoiseModule(psrand, gain, offset, baseline, qe, enable, param);
}
/**
* Create CameraModule
*/
protected CameraModule createCameraModule() {
double saturation = spnCameraSaturation.get();
String format = (String)cmbCameraFileFormat.getSelectedItem();
String quantiz = (String)cmbCameraQuantization.getSelectedItem();
return new CameraModule(quantiz, saturation, format);
}
/**
* Create PSFModule
*/
protected ArrayList<PSFModule> createPSFModule() {
double pxc = spnPixelsizeCamera.get();
double fwhm = getDiffractionLimit() * spnFWHMFactor.get();
double c = spnOversamplingConvolve.get()*spnOversamplingWorking.get();
Viewport vwPSF = createViewport(pxc/c);
ArrayList<PSFModule> modules = new ArrayList<PSFModule>();
int tab = tabPSF.getSelectedIndex();
if (tab == 0) {
modules.add(new PSFModule(fwhm, vwPSF));
}
else if (tab == 1) {
double zfocal = spnFocalPlaneTI.get();
double zdefocus = spnDefocusPlane.get();
int zfunc = cmbPSFModelZ.getSelectedIndex();
ZFunction zfunction = new ZFunction(zfunc, zdefocus, zfocal);
modules.add(new PSFModule(fwhm, vwPSF, zfunction, cmbPSFModelXY.getSelectedIndex()));
}
else if (tab == 2) {
PSFParameters paramGL = new PSFParameters();
paramGL.ni = spnNI.get();
paramGL.ns = spnNS.get();
paramGL.delta_ti = -spnFocalPlaneTI.get() * 1E-9; // Focal Axial
paramGL.delta_z = spnDeltaZ.get() * 1E-9;
paramGL.lambda = spnWavelength.get() * 1E-9;
paramGL.NA = spnNA.get();
paramGL.pixelSize = spnOversamplingConvolve.get() * pxc * 1E-9;
paramGL.oversamplingAxial = spnOversamplingAxial.get();
paramGL.oversamplingLateral = spnOversamplingLateral.get();
paramGL.calculateConstants();
modules.add(new PSFModule(fwhm, vwPSF, paramGL));
}
else if (tab == 3) {
for(int i=0; i<txtPSFFile.length; i++) {
if (new File(txtPSFFile[i].getText()).exists()) {
String filename = txtPSFFile[i].getText();
PSFModule module = new PSFModule(txtPSFFile[i].getText(), vwPSF);
module.biplaneAffine = filename.contains("BP500");
module.affineRotation = spnBiplaneRotation.get();
module.affineScale = spnBiplaneScale.get();
module.affineDX = spnBiplaneDX.get();
module.affineDY = spnBiplaneDY.get();
modules.add(module);
}
}
}
else {
double px = spnPixelsizeCamera.get()*1e-9;
BPALMParameters p1 = new BPALMParameters();
p1.doSplit = cmbBiplaneOrientation.getSelectedIndex() != 2;
p1.orientation = (String)cmbBiplaneOrientation.getSelectedItem();
p1.depth = spnBiplaneDepth.get()*1e-9;
p1.delta_z = spnBiplaneDeltaZ1.get()*1e-9;
p1.delta_z2 = spnBiplaneDeltaZ2.get()*1e-9;
p1.ni = spnBiplaneNI.get();
p1.ns = spnBiplaneNS.get();
p1.NA = spnNA.get();
p1.M = 100.0;
p1.ti0 = spnBiplaneTI.get()*1E-6;
p1.lambda = spnWavelength.get()*1E-9;
p1.thick = spnThickness.get()*1E-9;
p1.pixelSize = px;
p1.axialResolution = px;
p1.zd_star = 0.2;
p1.rotation = spnBiplaneRotation.get();
p1.scale = spnBiplaneScale.get();
p1.dx = spnBiplaneDX.get()*1e-9;
p1.dy = spnBiplaneDY.get()*1e-9;
p1.border = 0;
modules.add(new PSFModule(fwhm, vwPSF, p1));
}
return modules;
}
/**
* Create Viewport at the pixelsize resolution
*/
protected Viewport createViewport(double pixelsize) {
double thickness = spnThickness.get();
Point3D origin = new Point3D(0, 0, -thickness/2);
double fovNano = spnCameraResolution.get() * spnPixelsizeCamera.get();
return new Viewport(origin, fovNano, fovNano, thickness, pixelsize);
}
public void stateChanged(ChangeEvent e) {
updateInterface();
}
/**
* Test Accuracy according the Thompson rules.
*/
protected double[] testAccuracy() {
double pxc = spnPixelsizeCamera.get();
double fwhm = getDiffractionLimit() * spnFWHMFactor.get();
int upC = spnOversamplingConvolve.get();
int upW = spnOversamplingWorking.get();
ArrayList<PSFModule> psfs = createPSFModule();
CameraModule camera = createCameraModule();
NoiseModule noise = createNoiseModule();
AutofluorescenceModule autofluo = createAutofluorescenceModule();
String dataset = new File((new File(path).getParent())).getName();
SequenceFactory sequencer = new SequenceFactory(dataset, 1, 3, 1, camera, psfs, noise, autofluo, createViewport(pxc), upC, upW);
/* sequencer.generateFrames(0, fluorophores, fwhm, true, true, true);
double N = test.getMaximum();
double a = spnPixelsizeCamera.get();
double s = 0.5 * spnWavelength.get() / spnNA.get();
double b = test.getMean();
double s4 = s*s*s*s;
double accStats = Math.sqrt((s*s)/N);
double accQuant = Math.sqrt((a*a/12.0)/N);
double accBack = Math.sqrt((8*Math.PI*s4*b*b)/(N*N*a*a));
double accThomson = Math.sqrt(accStats*accStats + accQuant*accQuant + accBack*accBack);
lblAccuracy_N.setText(IJ.d2s(N));
lblAccuracy_back.setText(IJ.d2s(accBack));
lblAccuracy_stats.setText(IJ.d2s(accStats));
lblAccuracy_quant.setText(IJ.d2s(accQuant));
lblAccuracy_Thomson.setText(IJ.d2s(accThomson));
return new double[] {N, a, s, b, accStats, accQuant, accBack, accThomson};
*/
return new double[] {0,0,0,0, 0, 0,0,0,};
}
/**
* Update Interface.
*/
private void updateInterface() {
int tab = tabPSF.getSelectedIndex();
double pxc = spnPixelsizeCamera.get();
int fov = (int)Math.round(pxc * spnCameraResolution.get());
CameraModule camera = createCameraModule();
spnCameraSaturation.set(camera.getSaturation());
lblFoV.setText("" + fov + "x" + fov + "x" + spnThickness.get());
double diffractionLimit = getDiffractionLimit();
lblDiffractionLimit.setText(IJ.d2s(diffractionLimit) + " nm");
lblFWHM.setText(IJ.d2s(diffractionLimit*spnFWHMFactor.get()));
lblSummaryPlane.setText(getDefocusPlaneDescription() + " | " + getFocalPlaneDescription());
int psf = cmbPSFModelXY.getSelectedIndex();
if (psf <= PSFModule.RECTANGLE)
cmbPSFModelZ.setSelectedItem(ZFunction.names[ZFunction.ZFUNC_EXPO]);
else if (psf >= PSFModule.ROTATED_GAUSSIAN)
cmbPSFModelZ.setSelectedItem(ZFunction.names[ZFunction.ZFUNC_ANGLE]);
else if (psf == PSFModule.ASTIGMATISM)
cmbPSFModelZ.setSelectedItem(ZFunction.names[ZFunction.ZFUNC_EXPO2]);
bnSavePSF.setEnabled( tab== 2 || tab == 1);
int c = spnOversamplingConvolve.get();
int w = spnOversamplingWorking.get();
String psfName = (String)cmbPSFModelXY.getSelectedItem();
String p = IJ.d2s((pxc / (c*w)), 2);
if (tab == 2)
psfName =" G&L";
if (tab == 3)
psfName = new File(txtPSFFile[0].getText()).getName();
lblOversampling.setText("Px convolve " + p + " nm");
lblConvolveInfo.setText("" + p + ">" + IJ.d2s((pxc / (c*w)), 2) + ">" + pxc + " " + psfName);
}
protected double getDiffractionLimit() {
return 0.5 * spnWavelength.get() / spnNA.get();
}
protected double getFocalPlane() {
double oz = spnFocalPlaneTI.get();
if (this.tabPSF.getSelectedIndex() == 2) {
oz = oz * spnNI.get() / spnNS.get();
}
return oz;
}
protected String getDefocusPlaneDescription() {
int psf = cmbPSFModelXY.getSelectedIndex();
if (psf <= PSFModule.RECTANGLE)
return "2 x FWHM at " + spnDefocusPlane.get() + " nm";
if (psf >= PSFModule.ROTATED_GAUSSIAN)
return "90 degrees at " + spnDefocusPlane.get() + " nm";
if (psf == PSFModule.ASTIGMATISM)
return "Vertical at " + spnDefocusPlane.get() + " nm";
return "";
}
protected String getFocalPlaneDescription() {
int psf = cmbPSFModelXY.getSelectedIndex();
if (psf <= PSFModule.RECTANGLE)
return "1 x FWHM at " + getFocalPlane() + " nm";
if (psf >= PSFModule.ROTATED_GAUSSIAN)
return "0 degrees at " + getFocalPlane() + " nm";
if (psf == PSFModule.ASTIGMATISM)
return "Horizontal at " + getFocalPlane() + " nm";
return "";
}
public void windowActivated(WindowEvent e) {}
public void windowClosed(WindowEvent e) {}
public void windowDeactivated(WindowEvent e) {}
public void windowDeiconified(WindowEvent e) {}
public void windowIconified(WindowEvent e) {}
public void windowOpened(WindowEvent e) {}
public void windowClosing(WindowEvent e) {dispose();}
private void loadSettings() {
for(int i=0; i<NoiseModule.names.length; i++) {
settings.record("spnNoise-" + NoiseModule.names[i], spnNoises[i], "0");
settings.record("chkNoise-" + NoiseModule.names[i], chkNoises[i], false);
}
settings.record("cmbMode", cmbMode, SequenceFactory.modes[0]);
settings.record("chkProjection", chkProjection, true);
settings.record("chkStats", chkStats, true);
settings.record("chkReport", chkReport, true);
settings.record("spnOversamplingConvolve", spnOversamplingConvolve, "2");
settings.record("spnOversamplingWorking", spnOversamplingWorking, "2");
settings.record("spnZThickness", spnThickness, "500");
settings.record("spnFocalPlane", spnFocalPlaneTI, "0");
settings.record("spnDefocusPlane", spnDefocusPlane, "500");
settings.record("spnCameraResolution", spnCameraResolution, "256");
settings.record("spnPixelsizeCamera", spnPixelsizeCamera, "100");
settings.record("cmbCameraQuantization", cmbCameraQuantization, "14");
settings.record("spnCameraSaturation", spnCameraSaturation, "1000000");
settings.record("spnBaseline", spnBaseline, "100");
settings.record("cmbCameraFileFormat", cmbCameraFileFormat, CameraModule.names[0]);
settings.record("spnQuantumEfficiency", spnQuantumEfficiency, "2");
settings.record("spnCameraGain", spnCameraGain, "2");
settings.record("spnCameraOffset", spnCameraOffset, "2");
settings.record("spnFluoPixelsize", spnFluoPixelsize, "15");
settings.record("chkFluoAllFrames", chkFluoAllFrames, true);
settings.record("spnSeedRandom", spnSeedRandom, "123");
settings.record("spnNbFluorophores", spnNbFluorophores, "1");
settings.record("cmbPSFModelXY", cmbPSFModelXY, PSFModule.namesXY[0]);
settings.record("cmbPSFModelXYZ", cmbPSFModelXYZ, PSFModule.namesXYZ[0]);
settings.record("cmbPSFModelZ", cmbPSFModelZ, ZFunction.names[0]);
settings.record("spnFirstFrame", spnFirstFrame, "1");
settings.record("spnLastFrame", spnLastFrame, "1");
settings.record("spnIntervalFrame", spnIntervalFrame, "1");
settings.record("cmbAutofluoMode", cmbAutofluoMode, AutofluorescenceModule.evolutions[0]);
settings.record("spnAutofluoDiffusion", spnAutofluoDiffusion, "100");
settings.record("spnAutofluoDefocus", spnAutofluoDefocus, "1000");
settings.record("spnAutofluoChange", spnAutofluoChange, "50");
settings.record("spnAutofluoNbScale", spnAutofluoNbScale, "10");
settings.record("spnAutofluoDispl", spnAutofluoDispl, "100");
settings.record("cmbAutofluoSources", cmbAutofluoSources, AutofluorescenceModule.names[0]);
settings.record("spnAutofluoGain", spnAutofluoGain, "100");
settings.record("spnAutofluoOffsetMean", spnAutofluoOffsetMean, "100");
settings.record("spnAutofluoOffsetStdv", spnAutofluoOffsetStdv, "0");
settings.record("spnAutofluoNbSources", spnAutofluoNbSources, "20");
settings.record("spnAutofluoSize", spnAutofluoSize, "200");
settings.record("spnWavelength", spnWavelength, "500");
settings.record("spnNA", spnNA, "1.4");
settings.record("spnNS", spnNS, "1.0");
settings.record("spnNI", spnNI, "1.0");
settings.record("spnFWHMFactor", spnFWHMFactor, "1");
settings.record("spnOversamplingLateral", spnOversamplingLateral, "1");
settings.record("spnOversamplingAxial", spnOversamplingAxial, "1");
settings.record("spnDeltaZ", spnDeltaZ, "0");
settings.record("spnBeadSize", spnBeadSize, "0");
settings.record("spnFluoAmplitude", spnFluoAmplitude, "1000");
settings.record("cmbVerbose", cmbVerbose, "Verbose");
settings.record("cmbThreading", cmbThreading, "Off-1 Thread");
for(int i=0; i<3; i++)
settings.record("txtFilePSF-"+i, txtPSFFile[i], "-");
settings.record("spnBiplaneDepth1", spnBiplaneDepth, "0");
settings.record("spnBiplaneDeltaZ1", spnBiplaneDeltaZ1, "0");
settings.record("spnBiplaneDeltaZ2", spnBiplaneDeltaZ2, "500");
settings.record("spnBiplaneNI", spnBiplaneNI, "1");
settings.record("spnBiplaneNI", spnBiplaneNI, "1");
settings.record("cmbBiplaneOrientation", cmbBiplaneOrientation, "Rows");
settings.record("spnBiplaneTI", spnBiplaneTI, "100");
settings.record("spnBiplaneDX", spnBiplaneDX, "0");
settings.record("spnBiplaneDY", spnBiplaneDY, "0");
settings.record("spnBiplaneRotation", spnBiplaneRotation, "0");
settings.record("spnBiplaneScale", spnBiplaneScale, "1");
settings.loadRecordedItems();
}
public void loadParams() {
File destFile = new File(IJ.getDirectory("plugins") + "localization-microscopy.txt");
File sourceFile = new File(path + "localization-microscopy.txt");
try {
Tools.copyFile(sourceFile, destFile);
settings.loadRecordedItems();
}
catch(Exception ex) {}
}
public void saveParams() {
settings.storeRecordedItems();
File sourceFile = new File(IJ.getDirectory("plugins") + "localization-microscopy.txt");
File destFile = new File(path + "localization-microscopy.txt");
try {
Tools.copyFile(sourceFile, destFile);
}
catch(Exception ex) {}
}
}
| Java |
2D | SMLM-Challenge/Challenge2016 | Simulator/Simulator-Java/src/smlms/simulation/AutofluorescenceSource.java | .java | 2,289 | 74 | package smlms.simulation;
import imageware.ImageWare;
import smlms.tools.PsRandom;
public class AutofluorescenceSource {
private double xo;
private double yo;
private double scale;
private double size;
private double xdiffusion[] = new double[10];
private double ydiffusion[] = new double[10];
private PsRandom psrand;
private Viewport viewport;
public AutofluorescenceSource(PsRandom psrand, Viewport viewport, double scale, double size, double diffusion) {
this.xo = psrand.nextDouble() * viewport.getFoVXNano();
this.yo = psrand.nextDouble() * viewport.getFoVYNano();
this.scale = scale;
this.size = size;
this.psrand = psrand;
this.viewport = viewport;
xdiffusion[0] = 0;
ydiffusion[0] = 0;
double dir = (psrand.nextDouble()-0.5)*Math.PI*4.0;
for(int d=1; d<10; d++) {
xdiffusion[d] = xdiffusion[d-1] + diffusion * Math.sin(dir);
ydiffusion[d] = ydiffusion[d-1] + diffusion * Math.cos(dir);
if (d==5)
dir = (psrand.nextDouble()-0.5)*Math.PI*4.0;
}
}
public AutofluorescenceSource(PsRandom psrand, Viewport viewport, double xo, double yo, double scale, double size, double diffusion) {
this.xo = xo;
this.yo = yo;
this.scale = scale;
this.size = size;
this.psrand = psrand;
this.viewport = viewport;
xdiffusion[0] = 0;
ydiffusion[0] = 0;
double dir = (psrand.nextDouble()-0.5)*Math.PI*4.0;
for(int d=1; d<10; d++) {
xdiffusion[d] = xdiffusion[d-1] + diffusion * Math.sin(dir);
ydiffusion[d] = ydiffusion[d-1] + diffusion * Math.cos(dir);
if (d==5)
dir = (psrand.nextDouble()-0.5)*Math.PI*4.0;
}
}
public void move(double displacement) {
double dir = (psrand.nextDouble()-0.5)*Math.PI*4.0;
xo += displacement * Math.sin(dir);
yo += displacement * Math.cos(dir);
}
public void draw(ImageWare image) {
int sizePixel = (int)Math.ceil(viewport.convertPixel(size));
for(int d=0; d<10; d++) {
int x = (int)viewport.screenX(xo + xdiffusion[d]);
int y = (int)viewport.screenY(yo + ydiffusion[d]);
double value = 1.8*Math.PI*scale*scale;
for(int u=-sizePixel; u<=sizePixel; u++)
for(int v=-sizePixel; v<=sizePixel; v++) {
double r = u*u + v*v;
if (r < sizePixel*sizePixel)
image.putPixel(x+u, y+v, 0, Math.max(image.getPixel(x+u, y+v, 0), value));
}
}
}
}
| Java |
2D | SMLM-Challenge/Challenge2016 | Simulator/Simulator-Java/src/smlms/simulation/Viewport.java | .java | 4,452 | 193 | package smlms.simulation;
import ij.IJ;
import java.io.PrintStream;
import smlms.file.Fluorophore;
import smlms.tools.Point3D;
import smlms.tools.Tools;
public class Viewport {
private double fovx; // nano
private double fovy; // nano
private double thickness; // nano
private double pixelsize; // nano
private Point3D origin; // nano
public Viewport(Point3D origin, double fovx, double fovy, double thickness, double pixelsize) {
this.origin = origin;
this.fovx = fovx;
this.fovy = fovy;
this.thickness = thickness;
this.pixelsize = pixelsize;
}
public Viewport(Point3D origin, Point3D size, double pixelsize) {
this.origin = origin;
this.fovx = size.x;
this.fovy = size.y;
this.thickness = size.z;
this.pixelsize = pixelsize;
}
public double getSurface() {
return fovx*fovy;
}
public boolean inside(Point3D pt) {
if (pt.x < origin.x)
return false;
if (pt.y < origin.y)
return false;
if (pt.z < origin.z)
return false;
if (pt.x > origin.x + fovx)
return false;
if (pt.y > origin.y + fovy)
return false;
if (pt.z > origin.z + thickness)
return false;
return true;
}
public boolean insideXY(Fluorophore fluo) {
if (fluo.x < origin.x)
return false;
if (fluo.y < origin.y)
return false;
if (fluo.x > origin.x + fovx)
return false;
if (fluo.y > origin.y + fovy)
return false;
return true;
}
public String getInfo() {
String sx = "X/" + IJ.d2s(origin.x) + " ... " + IJ.d2s(origin.x+fovx) + " ";
String sy = "Y/" + IJ.d2s(origin.y) + " ... " + IJ.d2s(origin.y+fovy) + " ";
String sz = "Z/" + IJ.d2s(origin.z) + " ... " + IJ.d2s(origin.z+thickness) + " ";
return sx + sy + sz;
}
public void setThicknessNano(double thickness) {
this.thickness = thickness;
}
public double getThicknessNano() {
return thickness;
}
public double getFoVXNano() {
return fovx;
}
public double getFoVYNano() {
return fovy;
}
public int convertIntegerPixel(double anm) {
return Tools.round(anm / pixelsize);
}
public double convertPixel(double anm) {
return anm / pixelsize;
}
public double convertNano(double apix) {
return apix * pixelsize;
}
public double screenX(double xnm) {
return (xnm - origin.x) / pixelsize;
}
public double screenY(double ynm) {
return (ynm - origin.y) / pixelsize;
}
public int screenZ(double znm) {
return Tools.round((znm - origin.z) / pixelsize);
}
public Point3D screenPoint(Point3D pnm) {
return pnm.translate(origin.negate()).scale(1.0/pixelsize);
}
public double getPixelsize() {
return pixelsize;
}
public Point3D getCornerMinNano() {
double x1 = origin.x;
double y1 = origin.y;
double z1 = origin.z;
return (new Point3D(x1, y1, z1));
}
public Point3D getCornerMaxNano() {
double x1 = origin.x + fovx;
double y1 = origin.y + fovy;
double z1 = origin.z + thickness;
return (new Point3D(x1, y1, z1));
}
public Point3D getCornerPixel() {
return getCornerMinNano().scale(1.0/pixelsize);
}
public int getFoVXPixel() {
return (int)Math.round(fovx / pixelsize);
}
public int getFoVYPixel() {
return (int)Math.round(fovy / pixelsize);
}
public int getThicknessPixel() {
return (int)Math.ceil(thickness / pixelsize);
}
public Point3D getSizePixel() {
return getSizeNano().scale(1.0/pixelsize);
}
public Point3D getSizeNano() {
return (new Point3D(fovx, fovy, thickness));
}
public Point3D getCornerMinPixel() {
return getCornerPixel();
}
public Point3D getOrigin() {
return origin;
}
public Point3D getCornerMaxPixel() {
double x2 = origin.x + fovx;
double y2 = origin.y + fovy;
double z2 = origin.z + thickness;
return (new Point3D(x2, y2, z2)).scale(1.0/pixelsize);
}
public String toString() {
return "Vol (" + fovx + "x" + fovy + "x" + thickness + ") at " + pixelsize + " nm";
}
public void report(PrintStream out) {
out.print("<h2>Viewport</h2>");
out.print("<table cellpadding=5>");
out.print("<tr><td>Sample</td><td>Field of view</td><td>" + getFoVXNano() + "x" + getFoVYNano() + "</td><td>nm</td></tr>");
out.print("<tr><td></td><td>Field of view</td><td>" + getFoVXPixel() + "x" + getFoVYPixel() + "</td><td>pixel</td></tr>");
out.print("<tr><td></td><td>Thickness</td><td>" + getThicknessNano() + "</td><td>nm</td></tr>");
out.print("<tr><td></td><td>Thickness</td><td>" + getThicknessPixel() + "</td><td>slices</td></tr>");
out.print("</table>");
}
}
| Java |
2D | SMLM-Challenge/Challenge2016 | Simulator/Simulator-Java/src/smlms/simulation/CameraModule.java | .java | 3,099 | 103 | package smlms.simulation;
import ij.ImagePlus;
import ij.io.FileSaver;
import imageware.Builder;
import imageware.ImageWare;
import smlms.tools.Tools;
public class CameraModule {
public static String[] names = new String[] {"TIFF 8-bits", "TIFF 16-bits", "TIFF 32-bits", "JPEG"};
public static String[] quantizationNames = new String[]
{"No > real value", "8-bit", "10-bit", "12-bit", "14-bit", "16-bit", "20-bit", "24-bit"};
public static int quantizationValue[] = {0, 8, 10, 12, 14, 16, 20, 24};
private String quantization = "No > real";
private double saturation = 10000;
private String format = CameraModule.names[0];
public CameraModule(String quantization, double saturation, String format) {
this.quantization = quantization;
this.saturation = saturation;
this.format = format;
}
public void format(float[][] frame) {
int n = frame.length;
int m = frame[0].length;
int index = 0;
for(int i=0; i<quantizationValue.length; i++)
if (quantization.equals(quantizationNames[i]))
index = i;
int level = quantizationValue[index];
if (level != 0)
saturation = Math.min(saturation, Math.pow(2, level));
for(int x=0;x<n;x++)
for(int y=0;y<m;y++) {
double dn = Math.min(saturation, Math.max(0, frame[x][y]));
if (level == 0)
frame[x][y] = (float)dn;
else
frame[x][y] = (int)Math.floor(dn);
}
}
public double getBaseline() {
if (quantization.equals("No > real value")) {
return -10000000;
}
return 0.0;
}
public double getSaturation() {
if (quantization.equals("No > real value")) {
return 10000000;
}
int index = 0;
for(int i=0; i<quantizationValue.length; i++)
if (quantization.equals(quantizationNames[i]))
index = i;
return Math.pow(2, quantizationValue[index])-1;
}
public ImagePlus storeFrame(String path, float[][] camera, int number) {
ImagePlus imp;
ImageWare im32 = Builder.create(camera);
if (format.equals(names[0]))
imp = new ImagePlus(""+number, im32.convert(ImageWare.BYTE).buildImageStack());
else if (format.equals(names[1]))
imp = new ImagePlus(""+number, im32.convert(ImageWare.SHORT).buildImageStack());
else
imp = new ImagePlus(""+number, im32.buildImageStack());
String filename = path + Tools.format(number);
if (format.equals(names[3]))
(new FileSaver(imp)).saveAsJpeg(filename + ".jpg");
else
(new FileSaver(imp)).saveAsTiff(filename + ".tif");
return imp;
}
public String getFormat() {
return format;
}
/*
public void report(PrintStream out) {
out.print("<h2>Camera</h2>");
out.print("<table cellpadding=5>");
out.print("<tr><td></td><td>Gain</td><td>" + gain + "</td><td></td></tr>");
out.print("<tr><td></td><td>Baseline</td><td>" + baseline + "</td><td></td></tr>");
out.print("<tr><td></td><td>Saturation</td><td>" + saturation + "</td><td></td></tr>");
out.print("<tr><td></td><td>Quantization</td><td>" + quantization + "</td><td>bits</td></tr>");
out.print("<tr><td></td><td>File Format</td><td>" + format + "</td><td></td></tr>");
out.print("</table>");
}*/
}
| Java |
2D | SMLM-Challenge/Challenge2016 | Simulator/Simulator-Java/src/smlms/simulation/Zip_Sequences.java | .java | 1,563 | 53 | package smlms.simulation;
import ij.IJ;
import ij.ImagePlus;
import ij.ImageStack;
import ij.io.FileSaver;
import ij.io.Opener;
import java.io.File;
import smlms.plugins.Merge_Sequence_Frames;
import smlms.tools.Zip;
public class Zip_Sequences {
public static String path = "/Users/dsage/Desktop/beads/beads6/";
public static String[] psfs = new String[] { "2D-Exp", "AS-Exp", "DH-Exp", "BP-Exp" };
public static void main(String args[]) {
new Zip_Sequences();
}
public Zip_Sequences() {
Merge_Sequence_Frames merge = new Merge_Sequence_Frames();
merge.run(path+"BP000-Exp", path+"BP500-Exp", path + "BP-Exp");
for (int i = 0; i < psfs.length; i++) {
String p = path + psfs[i] + File.separator + "sequence/";
Zip.zipFolder(p, path + "stack-beads-100nm-" + psfs[i] + "-100x100x10-as-list.zip");
String[] list = new File(p).list();
ImageStack stack = null;
Opener opener = new Opener();
for (int j = 0; j < list.length; j++) {
IJ.log(p + list[j]);
ImagePlus imp = opener.openImage(p + list[j]);
if (imp != null) {
if (stack == null) stack = new ImageStack(imp.getWidth(), imp.getHeight());
stack.addSlice("", imp.getProcessor());
}
}
String filename = "stack-beads-100nm-" + psfs[i] + "-100x100x10-as-stack";
ImagePlus out = new ImagePlus(filename, stack);
String folder = path + psfs[i] + "-stack/";
new File(folder).mkdir();
FileSaver saver = new FileSaver(out);
saver.saveAsTiffStack(folder + filename + ".tif");
Zip.zipFolder(folder, path + filename + ".zip");
}
}
}
| Java |
2D | SMLM-Challenge/Challenge2016 | Simulator/Simulator-Java/src/smlms/simulation/PSFModule.java | .java | 19,151 | 584 | package smlms.simulation;
import ij.IJ;
import ij.ImagePlus;
import ij.WindowManager;
import ij.io.FileSaver;
import ij.io.Opener;
import ij.process.ImageProcessor;
import imageware.Builder;
import imageware.ImageWare;
import java.io.File;
import smlms.file.Fluorophore;
import smlms.file.Fluorophores;
import smlms.simulation.defocussed2dfunction.Airy;
import smlms.simulation.defocussed2dfunction.Astigmatism;
import smlms.simulation.defocussed2dfunction.Cosine;
import smlms.simulation.defocussed2dfunction.Defocussed2DFunction;
import smlms.simulation.defocussed2dfunction.DoubleHelix;
import smlms.simulation.defocussed2dfunction.ElongatedGaussian;
import smlms.simulation.defocussed2dfunction.Gaussian;
import smlms.simulation.defocussed2dfunction.Linear;
import smlms.simulation.defocussed2dfunction.Lorentz;
import smlms.simulation.defocussed2dfunction.Rectangle;
import smlms.simulation.defocussed2dfunction.ZFunction;
import smlms.simulation.gl.PSFParameters;
import smlms.simulation.gl.PSFValue;
import smlms.tools.Chrono;
import smlms.tools.Point3D;
import smlms.tools.Tools;
import smlms.tools.Verbose;
import bpalm.simulator.BPALMParameters;
import bpalm.simulator.BiplaneAlgorithm;
import bpalm.simulator.Particle;
public class PSFModule {
static public int GAUSSIAN = 0;
static public int LORENTZ = 1;
static public int AIRY = 2;
static public int COSINE = 3;
static public int LINEAR = 4;
static public int RECTANGLE = 5;
static public int PIXELWISE = 6;
static public int ASTIGMATISM = 7;
static public int ROTATED_GAUSSIAN = 8;
static public int DOUBLE_HELIX = 9;
static public int GIBSON_LANNI = 10;
static public int BIPLANE = 11;
static public int FILE = 12;
static public String[] namesXY = new String[] { "Gaussian", "Lorentz", "Airy", "Cosine", "Linear", "Rectangle", "Pixelwise", "Astigmatism", "Elongated Gaussian (Steer)", "Double Helix (Steer)"};
static public String[] namesXYZ = new String[] {"Gibson and Lanni"};
private int psf;
private ZFunction zfunction;
private double fwhm;
private Viewport viewport;
private PSFParameters pgl; // gibson-lanni
private double lineGL[][];
private ImageWare psfArray;
private String name = "Noname";
private double intDensityPSF = 1.0;
public BPALMParameters bpalm;
public boolean biplaneAffine = false;
public double affineDX = 0;
public double affineDY = 0;
public double affineScale = 0;
public double affineRotation = 0;
public PSFModule(double fwhm, Viewport viewport) {
this.name = "Point";
this.psf = PIXELWISE;
this.fwhm = fwhm;
this.viewport = viewport;
}
public PSFModule(double fwhm, Viewport viewport, ZFunction zfunction, int psf) {
this.name = "Point";
this.psf = psf;
this.zfunction = zfunction;
this.fwhm = fwhm;
this.viewport = viewport;
this.name = namesXY[psf] + "-" + zfunction.getName();
}
public PSFModule(double fwhm, Viewport viewport, PSFParameters pgl) {
this.name = "G&L";
this.psf = GIBSON_LANNI;
this.fwhm = fwhm;
this.pgl = pgl;
this.viewport = viewport;
lineGL = (psf == GIBSON_LANNI ? initPSF_GibsonLanni(viewport): null);
}
public PSFModule(double fwhm, Viewport viewport, BPALMParameters bpalm) {
this.name = "Biplane";
this.psf = BIPLANE;
this.fwhm = fwhm;
this.bpalm = bpalm;
this.viewport = viewport;
}
public PSFModule(String filename, Viewport viewport) {
if (!(new File(filename).exists()))
IJ.log("" + filename );
this.name = new File(filename).getName();
if (name.endsWith(".tif"))
name = name.substring(0, name.length()-4);
this.intDensityPSF = 0;
this.psf = FILE;
this.viewport = viewport;
ImagePlus imp = new Opener().openImage(filename);
psfArray = null;
if (imp != null) {
int nx = imp.getWidth();
int ny = imp.getHeight();
int nz = imp.getStackSize();
psfArray = Builder.create(nx, ny, nz, ImageWare.FLOAT);
for(int k=0; k<nz; k++) {
ImageProcessor ip = imp.getStack().getProcessor(k+1);
for(int i=0; i<nx; i++)
for(int j=0; j<ny; j++) {
double v = ip.getPixelValue(i, j);
intDensityPSF += v;
psfArray.putPixel(i, j, k, v);
}
}
}
if (name.startsWith("BP500")) {
biplaneAffine = true;
IJ.log("affineDX " + affineDX);
IJ.log("affineDY " + affineDY);
IJ.log("affineRotation " + affineRotation);
IJ.log("affineScale " + affineScale);
}
IJ.log("Integral Density of " + getName() + " : "+ intDensityPSF );
}
public String getInfoArrayPSF() {
return "" + psfArray.getWidth() + " " + psfArray.getHeight() + " " + psfArray.getDepth();
}
public double getFWHM() {
return fwhm;
}
public String getName() {
return name;
}
public Fluorophores convolve(Fluorophores fluorophores, float[][] image, double fwhm) {
Fluorophores fluorophoresProcessed = new Fluorophores();
Fluorophores fluos = new Fluorophores();
if (biplaneAffine) {
double rotRadians = affineRotation/180.0*Math.PI;
double cosa = Math.cos(rotRadians) * affineScale;
double sina = Math.sin(rotRadians) * affineScale;
for(Fluorophore fluo : fluorophores) {
Fluorophore a = new Fluorophore(0, fluo.x, fluo.y, fluo.z, fluo.frame, fluo.photons);
a.x = fluo.x*cosa + fluo.y*sina + affineDX;
a.y = -fluo.x*sina + fluo.y*cosa + affineDY;
fluos.add(a);
}
//IJ.log("affineDX " + affineDX + " affineDY:" + affineDY + " affineRotation:" + affineRotation + " affineScale:" + affineScale + " " + cosa + " " + sina);
}
else {
for(Fluorophore fluo : fluorophores)
fluos.add(fluo);
}
Verbose.talk("Convolve (biplane:" + (biplaneAffine) + ") nb:" + fluos.size() + " fluos with PSF: " + getName() + (fluos.size() > 0 ? " frame:" + fluos.get(0).frame : ""));
for(Fluorophore fluo : fluos) {
if (viewport.insideXY(fluo)) {
fluorophoresProcessed.add(fluo);
if (psf == PIXELWISE)
convolvePSF_Pixelwise(fluo, viewport, image);
else if (psf == GIBSON_LANNI)
convolvePSF_GibsonLanni(fluo, viewport, image);
else if (psf == FILE)
convolvePSF_File(fluo, viewport, image, fwhm);
else if (psf == BIPLANE)
fluorophoresProcessed.add(fluo);
else
convolveDefocussed2DFunction(fluo, viewport, image);
}
}
//if (psf == BIPLANE)
// convolveBPALM(fluorophores, viewport, image);
return fluorophoresProcessed;
}
/**
* Create a 3D PSF at the resolution pixelsize from z=0 to z=thickness
* @param pixelsize Resolution, pixelsize in nm
* @param thickness in nm
* @param focal in nm
*/
public ImageWare test(double beadSizeNM, double pixelsize, double focalPlaneNM) {
if (psf == FILE)
return psfArray;
int radiusPixel = (int)( (0.5*beadSizeNM) / pixelsize) + 1;
IJ.log(" \n radiusPixel" + radiusPixel);
double supportnm = 50 * radiusPixel * pixelsize;
double thickness = viewport.getThicknessNano();
Viewport viewportTest = new Viewport(new Point3D(0, 0, 0), supportnm, supportnm, thickness, pixelsize);
int nx = viewportTest.getFoVXPixel();
int ny = viewportTest.getFoVYPixel();
int nz = viewportTest.getThicknessPixel();
int nt = nz;
ImageWare vol = Builder.create(nx, ny, nz, ImageWare.FLOAT);
Chrono.reset();
Fluorophores fluorophores[] = new Fluorophores[nt];
double stepNM = radiusPixel * pixelsize * 0.333;
IJ.log(" \n radiusPixel" + radiusPixel + " stepNM " + stepNM );
for(int t=0; t<nt; t++) {
fluorophores[t] = new Fluorophores();
for(int i=-3; i<=3; i++)
for(int j=-3; j<=3; j++)
for(int k=-3; k<=3; k++) {
double d = Math.sqrt(i*i + j*j + k*k) * stepNM;
if (d <= beadSizeNM + 1) {
double znano = focalPlaneNM + k*stepNM + t*pixelsize;
Fluorophore fluo = new Fluorophore(fluorophores[t].size()+1, supportnm*0.5 + i*stepNM, supportnm*0.5+j*stepNM, znano, 0, 1);
fluorophores[t].add(fluo);
}
}
}
for(int z=0; z<nz; z++) {
float[][] image = new float[nx][nx];
convolve(fluorophores[z], image, 25);
vol.putXY(0, 0, z, image);
}
Chrono.print(getName());
return vol;
}
private void convolveBPALM1(Fluorophores fluorophoresProcessed, Viewport viewport, float[][] image) {
// read the parameters from all tabs.
double px = viewport.getPixelsize();
Particle particle[] = new Particle[fluorophoresProcessed.size()];
for(int i=0; i<fluorophoresProcessed.size(); i++) {
particle[i] = new Particle();
Fluorophore fluo = fluorophoresProcessed.get(i);
particle[i].x = fluo.x / px;
particle[i].y = fluo.y / px;
particle[i].z = fluo.z * 1e-9;
}
bpalm.calculateConstants();
bpalm.doSequence = true;
bpalm.calculateConstants();
BiplaneAlgorithm ma = new BiplaneAlgorithm(this);
ma.renderSequence(particle, image);
}
private void add(int i, int j, float [][] image, float value) {
if (i<0)
return;
if (j<0)
return;
if (i>=image.length)
return;
if (j>=image[0].length)
return;
image[i][j] += value;
}
/**
* Dummy convolve with a dirac, impulse to display the fluorophores
*/
public void convolvePSF_Pixelwise(Fluorophore fluo, Viewport viewport, float[][] image) {
int n = image.length-1;
Verbose.prolix("Fluorophore Pixelwise " + fluo.toString());
double A = fluo.photons;
double xpix = viewport.screenX(fluo.x);
double ypix = viewport.screenY(fluo.y);
int xi = Tools.round(xpix);
int yi = Tools.round(ypix);
if (xi > 0 && yi > 0 && xi < n && yi < n)
image[xi][yi] += A;
}
/**
*/
public void convolvePSF_File(Fluorophore fluo, Viewport viewport, float[][] image, double fwhm) {
int nx = psfArray.getWidth();
int ny = psfArray.getHeight();
int nz = psfArray.getDepth();
int hx = nx / 2;
int hy = ny / 2;
Verbose.prolix("Fluorophore Pixelwise " + fluo.toString() + " " + hx + " " + hy);
double norm = 1.0;
double A = fluo.photons * norm;
double xpix = viewport.screenX(fluo.x) - hx - 0.5;
double ypix = viewport.screenY(fluo.y) - hy - 0.5;
double zpix = viewport.screenZ(fluo.z);
int xi = (int)(xpix);
int yi = (int)(ypix);
if (zpix>=0 && zpix<nz) {
for(int i=xi; i<xi+nx; i++)
for(int j=yi; j<yi+ny; j++) {
double v = psfArray.getInterpolatedPixel(-xpix+i, -ypix+j, zpix, ImageWare.MIRROR);
add(i, j, image, (float)(v*A));
}
}
}
/**
* Convolution in the plane domain with a circular function.
*/
public void convolveDefocussed2DFunction(Fluorophore fluo, Viewport viewport, float[][] image) {
int n = image.length;
Chrono.reset();
double defocusFactor = zfunction.getDefocusFactor(fluo.z);
// XY, 2*sqrt(2*ln(2)) = 2.35482005, fwmh = 2*sqrt(2*ln(2)) * sigma
double radiusPix = viewport.convertPixel(fwhm) / 2.35482005;
Defocussed2DFunction func = null;
if (psf == GAUSSIAN)
func = new Gaussian(radiusPix, defocusFactor);
else if (psf == LORENTZ)
func = new Lorentz(radiusPix, defocusFactor);
else if (psf == AIRY)
func = new Airy(radiusPix, defocusFactor);
else if (psf == COSINE)
func = new Cosine(radiusPix, defocusFactor);
else if (psf == LINEAR)
func = new Linear(radiusPix, defocusFactor);
else if (psf == RECTANGLE)
func = new Rectangle(radiusPix, defocusFactor);
else if (psf == ASTIGMATISM)
func = new Astigmatism(radiusPix, defocusFactor);
else if (psf == ROTATED_GAUSSIAN)
func = new ElongatedGaussian(radiusPix, defocusFactor);
else if (psf == DOUBLE_HELIX)
func = new DoubleHelix(radiusPix, defocusFactor);
else
return;
int support = func.getSupport();
if (support < 1)
return;
double xpix = viewport.screenX(fluo.x);
double ypix = viewport.screenY(fluo.y);
int xi = Tools.round(xpix);
int yi = Tools.round(ypix);
double xc = xpix - xi - 0.5;
double yc = ypix - yi - 0.5;
int h = support/2;
if (h > n) {
h = n;
}
double array[][] = new double[2*h+1][2*h+1];
double sum = 1.0;
for(int i=-h; i<=h; i++)
for(int j=-h; j<=h; j++) {
double v = func.eval(xc-i, yc-j);
sum += v;
array[i+h][j+h] = v;
}
if (sum > 0) {
double norm = fluo.photons / sum;
for(int i=-h; i<=h; i++)
for(int j=-h; j<=h; j++)
add(xi+i, yi+j, image, (float)(array[i+h][j+h]*norm));
}
}
public double[][] initPSF_GibsonLanni(Viewport viewport) {
PSFValue psfvalue = new PSFValue(pgl);
double radiusPix = 10.0*viewport.convertPixel(fwhm);
double pixelsize = viewport.getPixelsize() * 1E-9;
int np = (int)Math.ceil((radiusPix*Math.sqrt(2)+1)*pgl.oversamplingLateral);
int nz = viewport.getThicknessPixel() * pgl.oversamplingAxial + 1;
double[] r = new double[np];
for (int nn=0; nn<np; nn++)
r[nn] = nn/pgl.oversamplingLateral;
double[][] lineGL = new double[np][nz];
for(int z=0; z<nz; z++) {
psfvalue.p.zp = z * viewport.getPixelsize() * 1E-9 / pgl.oversamplingAxial;
psfvalue.p.yd = 0;
for (int nn=0; nn<r.length; nn++) {
psfvalue.p.xd = r[nn] * pixelsize;
lineGL[nn][z] = psfvalue.calculate();
}
}
return lineGL;
}
/**
* Gibson and Lanni PSF convolution.
*/
public void convolvePSF_GibsonLanni(Fluorophore fluo, Viewport viewport, float[][] image) {
PSFValue psfvalue = new PSFValue(pgl);
double A[][] = pgl.affineTransformA;
double B[] = pgl.affineTransformB;
double xc = viewport.getFoVXPixel() * 0.5;
double yc = viewport.getFoVYPixel() * 0.5;
double xa = viewport.convertPixel(fluo.x - B[0]) - xc;
double ya = viewport.convertPixel(fluo.y - B[1]) - yc;
double xt = viewport.convertNano(A[0][0]*xa + A[1][0]*ya + xc);
double yt = viewport.convertNano(A[0][1]*xa + A[1][1]*ya + yc);
psfvalue.p.xp = xt * 1E-9;
psfvalue.p.yp = yt * 1E-9;
psfvalue.p.zp = fluo.z * 1E-9;
double radiusPix = 10.0*viewport.convertPixel(fwhm);
int nx = image.length;
int ny = image[0].length;
int nz = viewport.getThicknessPixel() * pgl.oversamplingAxial + 1;
int zi = (int)Math.floor(nz * fluo.z * pgl.oversamplingAxial / viewport.getThicknessNano());
double xp = viewport.screenX(xt-viewport.getPixelsize()*0.5);
double yp = viewport.screenY(yt-viewport.getPixelsize()*0.5);
int np = lineGL.length;
double[] r = new double[np];
for (int nn=0; nn<np; nn++)
r[nn] = nn/pgl.oversamplingLateral;
//IJ.log(" zi " + zi + " " + lineGL[0].length + " " + Math.max(0, Math.min(zi, lineGL[0].length-2)));
zi = Math.max(0, Math.min(zi, lineGL[0].length-2));
/*
int xLow = Math.max(0,(int)Math.ceil(xp-radiusPix));
int xHigh = Math.min(nx-1,(int)Math.floor(xp+radiusPix));
int yLow = Math.max(0,(int)Math.ceil(yp-radiusPix));
int yHigh = Math.min(ny-1,(int)Math.floor(yp+radiusPix));
for (int x=xLow; x<xHigh; x++)
for (int y=yLow; y<yHigh; y++) {
double rPixel = Math.sqrt((x-xp)*(x-xp)+(y-yp)*(y-yp)); // radius of the current pixel in units of [pixels]
int index = (int)(rPixel*pgl.oversamplingLateral);
image[x][y] += lineGL[index][zi] + (lineGL[index+1][zi]-lineGL[index][zi])*(rPixel-r[index])*pgl.oversamplingLateral; // Interpolated value.
}
*/
int x1 = Math.max(0,(int)Math.ceil(xp-radiusPix));
int x2 = Math.min(nx-1,(int)Math.floor(xp+radiusPix));
int px = x2 - x1;
int y1 = Math.max(0,(int)Math.ceil(yp-radiusPix));
int y2 = Math.min(ny-1,(int)Math.floor(yp+radiusPix));
int py = y2 - y1;
double array[][] = new double[px][py];
double sum = 0;
for (int x=0; x<px; x++)
for (int y=0; y<py; y++) {
double rpixel = Math.sqrt((x+x1-xp)*(x+x1-xp)+(y+y1-yp)*(y+y1-yp));
int index = (int)(rpixel*pgl.oversamplingLateral);
array[x][y] = lineGL[index][zi] + (lineGL[index+1][zi]-lineGL[index][zi])*(rpixel-r[index])*pgl.oversamplingLateral; // Interpolated value.
sum += array[x][y];
}
if (sum > 0) {
double norm = fluo.photons / sum;
for (int x=0; x<px; x++)
for (int y=0; y<py; y++) {
add(x1+x, y1+y, image, (float)(array[x][y]*norm));
}
}
/*
int n = image.length;
for (int x=-h; x<=h; x++)
for (int y=-h; y<=h; y++) {
double rPixel = Math.sqrt((x-xp)*(x-xp)+(y-yp)*(y-yp)); // radius of the current pixel in units of [pixels]
int index = (int)(rPixel*pgl.oversamplingLateral);
try{double value = lineGL[index][zi] + (lineGL[index+1][zi]-lineGL[index][zi])*(rPixel-r[index])*pgl.oversamplingLateral; // Interpolated value.
add(xi+x, yi+y, n, image, (float)(value));}
catch(Exception e) {IJ.log("" + x + " " + y + " " + index + " " + zi + r.length);}
}
*/
}
/**
* Gibson and Lanni PSF convolution.
*/
public void convolvePSF_GibsonLanni_ContinuousZ(Fluorophore particle, Viewport viewport, float[][] image) {
PSFValue psfvalue = new PSFValue(pgl);
psfvalue.p.xp = particle.x * 1E-9;
psfvalue.p.yp = particle.y * 1E-9;
psfvalue.p.zp = particle.z * 1E-9;
//int nz = viewport.getThicknessPixel();
//int zi = (int)Math.floor(nz * particle.znano / viewport.getThicknessNano());
double radiusPix = 8*viewport.convertPixel(fwhm);
double pixelsize = viewport.getPixelsize() * 1E-9;
int nx = image.length;
int ny = image[0].length;
int np = (int)Math.ceil((radiusPix*Math.sqrt(2)+1)*pgl.oversamplingLateral);
psfvalue.p.yd = psfvalue.p.yp;
double[] r = new double[np];
double[] h = new double[np];
for (int nn=0; nn<np; nn++) {
r[nn] = nn/pgl.oversamplingLateral;
psfvalue.p.xd = psfvalue.p.xp + r[nn] * pixelsize;
h[nn] = psfvalue.calculate();
}
double xp = viewport.screenX(particle.x);
double yp = viewport.screenY(particle.y);
int xLow = Math.max(0,(int)Math.ceil(xp-radiusPix));
int xHigh = Math.min(nx-1,(int)Math.floor(xp+radiusPix));
int yLow = Math.max(0,(int)Math.ceil(yp-radiusPix));
int yHigh = Math.min(ny-1,(int)Math.floor(yp+radiusPix));
for (int x=xLow; x<xHigh; x++)
for (int y=yLow; y<yHigh; y++) {
double rPixel = Math.sqrt((x-xp)*(x-xp)+(y-yp)*(y-yp)); // radius of the current pixel in units of [pixels]
int index = (int)(rPixel*pgl.oversamplingLateral);
image[x][y] += h[index] + (h[index+1]-h[index])*(rPixel-r[index])*pgl.oversamplingLateral; // Interpolated value.
}
}
public String toString() {
return getName() + " FWHM:" + IJ.d2s(fwhm);
}
public void storeIllustration(ImageWare psf, String path, double zfocalnm) {
int nx = psf.getWidth();
int ny = psf.getHeight();
int nz = psf.getDepth();
double max = psf.getMaximum();
int zfocal = (int)Math.floor(nz*zfocalnm);
ImageWare image = Builder.create(nx+4, ny + nz + 6, 1, ImageWare.FLOAT);
image.fillConstant(max);
for(int i=0; i<nx; i++)
for(int j=0; j<ny; j++)
image.putPixel(i+2, j+2, 0, psf.getPixel(i, j, zfocal));
for(int i=0; i<nx; i++)
for(int k=0; k<nz; k++)
image.putPixel(i+2, k+ny+4, 0, psf.getPixel(i, ny/2, k));
ImagePlus imp = new ImagePlus("PSF XY and YZ", image.buildImageStack());
imp.show();
WindowManager.setTempCurrentImage(imp);
IJ.run("Fire");
new FileSaver(imp).saveAsPng(path + "illustration.png");
}
public void storeSlices(ImageWare psf, String path) {
int nz = psf.getDepth();
ImagePlus imp = new ImagePlus("", psf.buildImageStack());
for(int z=0; z<nz; z++)
new FileSaver(new ImagePlus("", imp.getStack().getProcessor(z+1))).saveAsTiff(path + "z-" + Tools.format(z) + ".tif");
}
}
| Java |
2D | SMLM-Challenge/Challenge2016 | Simulator/Simulator-Java/src/smlms/simulation/gl/Bessel.java | .java | 2,709 | 76 | package smlms.simulation.gl;
//import ij.IJ;
/*
* This class evaluates the Bessel function J0(x).
* It uses the polynomial approximations on p. 369-70 of Abramowitz & Stegun.
* The error in J0 is supposed to be less than or equal to 5 x 10^-8.
* The error in J1 is supposed to be less than or equal to 4 x 10^-8, relative to the value of x.
* The error in J2 depends on the error of J0 and J1, as J2 = 2*J1/x + J0.
*
*/
public class Bessel {
/** Constants for Bessel function approximation according Abramowitz & Stegun */
private static double[] tJ0 = {1.0, -2.2499997, 1.2656208, -0.3163866, 0.0444479, -0.0039444, 0.0002100};
private static double[] pJ0 = {-.78539816, -.04166397, -.00003954, 0.00262573, -.00054125, -.00029333, .00013558};
private static double[] fJ0 = {.79788456, -0.00000077, -.00552740, -.00009512, 0.00137237, -0.00072805, 0.00014476};
private static double[] tJ1 = {0.5, -0.56249985, 0.21093573, -0.03954289, 0.0443319, -0.00031761, 0.0001109};
private static double[] pJ1 = {-2.35619449, 0.12499612, 0.00005650, -0.00637879, 0.00074348, 0.00079824, -0.00029166};
private static double[] fJ1 = {0.79788456, 0.00000156, 0.01689667, 0.00017105, -0.00249511, 0.00113653, -0.00020033};
/**
* Returns the value of the Bessel function of the first kind of order zero (J0) at x.
*/
public static double J0(double x) {
if (x < 0.0)
x *= -1.0;
if (x <= 3.0) {
double y = x*x/9.0;
return tJ0[0] + y*(tJ0[1] + y*(tJ0[2] + y*(tJ0[3] + y*(tJ0[4] + y*(tJ0[5] + y*tJ0[6])))));
}
double y = 3.0/x;
double theta0 = x + pJ0[0] + y*(pJ0[1] + y*(pJ0[2] + y*(pJ0[3] + y*(pJ0[4] + y*(pJ0[5] + y*pJ0[6])))));
double f0 = fJ0[0] + y*(fJ0[1] + y*(fJ0[2] + y*(fJ0[3] + y*(fJ0[4] + y*(fJ0[5] + y*fJ0[6])))));
return Math.sqrt(1.0/x)*f0*Math.cos(theta0);
}
/**
* Returns the value of the Bessel function of the first kind of order one (J1) at x.
*/
public static double J1(double x) {
int sign=1;
if (x < 0.0) {
x *= -1.0;
sign = -1;
}
if (x <= 3.0) {
double y = x*x/9.0;
return sign*x*(tJ1[0] + y*(tJ1[1] + y*(tJ1[2] + y*(tJ1[3] + y*(tJ1[4] + y*(tJ1[5] + y*tJ1[6]))))));
}
double y = 3.0/x;
double theta1 = x + pJ1[0] + y*(pJ1[1] + y*(pJ1[2] + y*(pJ1[3] + y*(pJ1[4] + y*(pJ1[5] + y*pJ1[6])))));
double f1 = fJ1[0] + y*(fJ1[1] + y*(fJ1[2] + y*(fJ1[3] + y*(fJ1[4] + y*(fJ1[5] + y*fJ1[6])))));
return sign*Math.sqrt(1.0/x)*f1*Math.cos(theta1);
}
/**
* Returns the value of the Bessel function of the first kind of order two (J2) at x.
*/
public static double J2(double x) {
double value0 = J0(x);
double value1 = J1(x);
if (x==0.0) return 0.0;
else return 2.0*value1/x + value0;
}
} | Java |
2D | SMLM-Challenge/Challenge2016 | Simulator/Simulator-Java/src/smlms/simulation/gl/PSFParameters.java | .java | 3,686 | 144 | package smlms.simulation.gl;
//import ij.IJ;
public class PSFParameters {
public double affineTransformA[][] = new double[][] {{1, 0}, {0, 1}};
public double affineTransformB[] = new double[] {0, 0};
/* Optical acquisition Parameters (from the user) */
/* ------------------------------------------------ */
/** Stage displacement relative to the working distance. **/
/** A negative value indicates that the immersion layer thickness is less than the working distance.**/
public double delta_ti;
/** Immersion medium refractive index (experimental value).*/
public double ni;
/** Sample refractive index.*/
public double ns;
/** Emission wavelength of the fluorophoes.*/
public double lambda;
/** Numerical aperture */
public double NA;
/** Magnification of the objective */
public double M;
/** Effective size of a single pixels (physical size divided by the magnification).*/
public double pixelSize;
/** Tube length */
public double zd_star;
/* Working distance of the objective (design value). This is also the width of the immersion layer.*/
//public double ti0;
/* Working distance of the objective (experimental value). influenced by the stage displacement.*/
//public double ti;
/* Effective size of a single stage displacement.*/
//public double axialResolution;
/* Additional stage offset [nm]*/
//public double depth;
/* Particle Location */
/* ----------------- */
/** Axial position of the particle **/
public double zp;
/** Lateral position of the particle in image domain in [pixels] **/
public double xp,yp;
/* Detector Location */
/* ----------------- */
/** Axial distance of the detector relative to the design value <em>in terms of stage displacement</em> [nm]*/
public double delta_z;
/** Lateral position of the detector in image domain in [pixels] **/
public double xd,yd;
/* Calculated parameters */
/* --------------------- */
/** Aperture of the objective, projected onto the tube length (Gibson Lanni 1992, page 156) **/
public double a;
/** Distance of the defocused plane relative to the back focal plane **/
public double zd;
/** Wave number **/
public double k0;
/** Radial distance **/
public double r;
public double k_a_over_zd;
public double const2;
public double ns_ts;
public double ni_delta_ti;
public double NA_over_ni_squared;
public double NA_over_ns_squared;
public double xpMinusXd,ypMinusYd;
public int oversamplingLateral = 1;
public int oversamplingAxial = 1;
public PSFParameters() {
M = 100; // Magnification
zd_star = 0.2;
delta_z = 0;
zd = 0.2;
}
public PSFParameters(PSFParameters p) {
this.delta_ti = p.delta_ti;
this.ni = p.ni;
this.ns = p.ns;
this.delta_z = p.delta_z;
this.lambda = p.lambda;
this.NA = p.NA;
this.M = p.M;
this.pixelSize = p.pixelSize;
this.zd_star = p.zd_star;
this.zd = p.zd;
this.zp = p.zp;
this.xp = p.xp;
this.yp = p.yp;
this.xd = p.xd;
this.yd = p.yd;
}
public void calculateConstants() {
k0 = 2*Math.PI/lambda;
a = zd_star*NA/Math.sqrt(M*M-NA*NA); // From equation page 51 Gibson thesis, bottom
zd = (zd_star*a*a*ni)/(delta_z*zd_star*NA*NA+a*a*ni); // From equation page 70 Gibson thesis, bottom
k_a_over_zd = k0*a/zd;
const2 = ((zd_star-zd)*a*a)/(2*zd*zd_star);
ns_ts = ns*zp;
ni_delta_ti = ni*delta_ti;
NA_over_ni_squared = (NA/ni)*(NA/ni);
NA_over_ns_squared = (NA/ns)*(NA/ns);
xpMinusXd = xp-xd;
ypMinusYd = yp-yd;
r = Math.sqrt(xpMinusXd*xpMinusXd+ypMinusYd*ypMinusYd)*M;
}
public String toString() {
String t = new String();
t = t + "NA=" + NA + ", r=" + r + " zp="+zp;
return t;
}
} | Java |
2D | SMLM-Challenge/Challenge2016 | Simulator/Simulator-Java/src/smlms/simulation/gl/PSFValue.java | .java | 4,981 | 164 | package smlms.simulation.gl;
/**
* Calculating values of the Gibson and Lanni PSF model
*
**/
public class PSFValue {
// Gibson & Lanni parameters of the acquisition
public PSFParameters p;
// Gibson and Lanni parameters
public double NA = 1.4;
public double LAMBDA = 500E-9;
public int MAGNIFICATION = 100;
public double ZD_STAR = 200E-3;
public double NI = 1.5;
public double NS = 1.33;
public double PIXEL_SIZE = 150E-9;
public double DELTA_TI = 0;
public double RELATIVE_DIFFERENCE_SIMPSON = 0.1;
public int CONSECUTIVE_SUCCESIVE_ITERATIONS = 2;
// Constructor
public PSFValue(PSFParameters p) { this.p = new PSFParameters(p); }
// calculate()
// Simpson approximation for the Kirchhoff diffraction integral
// The real and imaginary parts are approximated separately
// 'r' is the radial distance of the detector relative to the optical axis in [m].
// 'zp' is the particle depth relative to the coverslip in [m]
public double calculate() {
p.calculateConstants();
// Lower and upper limits of the integral
double a = 0.0;
double b=Math.min(1, p.ns/p.NA); //1.0
int N; // number of sub-intervals
int k; // number of consecutive successful approximations
double del; // integration interval
int iteration; // number of iterations.
double curDifference; // Stopping criterion
double rho;
double[] sum = new double[2];
double[] sumOddIndex = new double[2], sumEvenIndex = new double[2];
double[] valueX0 = new double[2], valueXn = new double[2];
double[] value = new double[2];
double curValue = 0.0, prevValue = 0.0;
// Initialization of the Simpson sum (first iteration)
N=2;
del=(b-a)/2.0;
k=0;
iteration = 1;
rho = (b-a)/2.0;
sumOddIndex = this.integrand(rho);
sumEvenIndex[0] = 0.0; sumEvenIndex[1] = 0.0;
valueX0 = this.integrand(a);
valueXn = this.integrand(b);
sum[0] = valueX0[0] + 2.0*sumEvenIndex[0] + 4.0*sumOddIndex[0] + valueXn[0];
sum[1] = valueX0[1] + 2.0*sumEvenIndex[1] + 4.0*sumOddIndex[1] + valueXn[1];
curValue = (sum[0]*sum[0]+sum[1]*sum[1])*del*del;
prevValue = curValue;
// Finer sampling grid until we meet the RELATIVE_DIFFERENCE_SIMPSON value with the specified number of repetitions, K
while(k<CONSECUTIVE_SUCCESIVE_ITERATIONS) {
iteration++;
N *= 2;
del = del/2;
sumEvenIndex[0] = sumEvenIndex[0] + sumOddIndex[0];
sumEvenIndex[1] = sumEvenIndex[1] + sumOddIndex[1];
sumOddIndex[0] = 0.0;
sumOddIndex[1] = 0.0;
for(int n=1; n<N; n=n+2) {
rho = n*del;
value = this.integrand(rho);
sumOddIndex[0] += value[0];
sumOddIndex[1] += value[1];
}
sum[0] = valueX0[0] + 2.0*sumEvenIndex[0] + 4.0*sumOddIndex[0] + valueXn[0];
sum[1] = valueX0[1] + 2.0*sumEvenIndex[1] + 4.0*sumOddIndex[1] + valueXn[1];
curValue = (sum[0]*sum[0]+sum[1]*sum[1])*del*del;
// Relative error between consecutive approximations
if (prevValue==0.0) curDifference = Math.abs((prevValue-curValue)/1E-5);
else curDifference = Math.abs((prevValue-curValue)/curValue);
if (curDifference<=RELATIVE_DIFFERENCE_SIMPSON) k++;
else k = 0;
prevValue=curValue;
if (iteration>15) {
System.err.println("Integral not converging after "+iteration+"iterations. The optical parameters are: " + p.toString());
return curValue;
}
}
return curValue;
}
double[] integrand(double rho) {
// 'rho' is the integration parameter.
// 'r' is the radial distance of the detector relative to the optical axis in the DETECTOR (i.e. after magnification)
// The return value is a complex number that is described by an array
// The relevant equations in the paper are (4) and (5)
double BesselValueRho = Bessel.J0(p.k_a_over_zd*p.r*rho)*rho;
//double BesselValueRho = Bessel.J0(p.k0*p.NA*r*rho/p.M)*rho;
double OPD_real, OPD_imag, OPD1_real, OPD1_imag, OPD2_real, OPD2_imag, OPD3; // Optical path differences
double[] I = new double[2];
// Phase term due to immersion layer thickness
double X = 1-p.NA_over_ni_squared*rho*rho;
if (X>=0) {
OPD1_real = p.ni*(p.delta_ti)*Math.sqrt(X);
OPD1_imag = 0;
} else {
OPD1_real = 0;
OPD1_imag = p.ni*(p.delta_ti)*Math.sqrt(-X);
}
// Phase term due to point source depth
X = 1-p.NA_over_ns_squared*rho*rho;
if (X>0) {
OPD2_real = p.ns_ts*Math.sqrt(X);
OPD2_imag = 0;
} else {
OPD2_real = 0;
OPD2_imag = p.ns_ts*Math.sqrt(-X);
}
// Defocus in image plane due to imaging plane displacement
OPD3 = p.const2*rho*rho;
// See equation page 50, bottom, Gibson thesis and defocus equation page 70, top
OPD_real = OPD1_real+OPD2_real+OPD3;
OPD_imag = OPD1_imag+OPD2_imag;
double W = p.k0*OPD_real;
// The real part
I[0] = BesselValueRho*Math.cos(W)*Math.exp(-p.k0*OPD_imag); // See eq 4.9, pag 53, Gibson thesis
// The imaginary part
I[1] = BesselValueRho*Math.sin(W)*Math.exp(-p.k0*OPD_imag);
return I;
}
}
| Java |
2D | SMLM-Challenge/Challenge2016 | Simulator/Simulator-Java/src/smlms/simulation/defocussed2dfunction/Cosine.java | .java | 1,218 | 40 | //=========================================================================================
//
// Project: Localization Microscopy
//
// Author : Daniel Sage, Biomedical Imaging Group (BIG), http://bigwww.epfl.ch/sage/
//
// Organization: Ecole Polytechnique Federale de Lausanne (EPFL), Lausanne, Switzerland
//
// Conditions of use: You'll be free to use this software for research purposes, but you
// should not redistribute it without our consent. In addition, we expect you to include a
// citation or acknowledgment whenever you present or publish results that are based on it.
//
//=========================================================================================
package smlms.simulation.defocussed2dfunction;
import smlms.tools.Tools;
public class Cosine extends Defocussed2DFunction {
private double freq = Math.PI * 0.5;
private double size = 1.0;
public Cosine(double radius, double defocusFactor) {
super();
this.size = radius * defocusFactor;
}
public double eval(double x, double y) {
if (size < 0.0000001)
return 0;
double r = Math.sqrt(x*x + y*y) / size;
return Math.max(0, Math.cos(r * freq));
}
public int getSupport() {
return 2*Tools.round(size)+1;
}
}
| Java |
2D | SMLM-Challenge/Challenge2016 | Simulator/Simulator-Java/src/smlms/simulation/defocussed2dfunction/ZFunction.java | .java | 1,262 | 54 | package smlms.simulation.defocussed2dfunction;
public class ZFunction {
final static public int ZFUNC_EXPO = 0;
final static public int ZFUNC_ANGLE = 1;
final static public int ZFUNC_EXPO2 = 2;
final static public int ZFUNC_CONSTANT = 3;
static public String[] names = new String[] {"Exponential", "Linear (angle)", "Exponential (max. 2)", "Constant"};
private int func1D = 1;
private double zdefocus = 1.0;
private double zfocal = 1.0;
public ZFunction(int func1D, double zdefocus, double zfocal) {
this.func1D = func1D;
this.zdefocus = zdefocus;
this.zfocal = zfocal;
}
public double getDefocusFactor(double z) {
double a, za, zf;
zf = z - zfocal;
switch(func1D) {
case ZFUNC_EXPO:
double K = -1.38629436 *0.5; // log(0.5)
za = (zf<0?zf:-zf);
return Math.exp(za*K/zdefocus);
case ZFUNC_EXPO2:
double K2 = -1.38629436 *0.5; // log(0.5)
za = (zf<0?zf:-zf);
return Math.min(2, Math.exp(za*K2/zdefocus));
case ZFUNC_CONSTANT:
return 1.0;
case ZFUNC_ANGLE:
a = Math.PI*0.5/(zdefocus-zfocal);
return a * zf;
}
return 1.0;
}
public String getName() {
return names[func1D];
}
public String toString() {
return names[func1D] + " " + zfocal + " " + zdefocus;
}
}
| Java |
2D | SMLM-Challenge/Challenge2016 | Simulator/Simulator-Java/src/smlms/simulation/defocussed2dfunction/Lorentz.java | .java | 1,309 | 43 | //=========================================================================================
//
// Project: Localization Microscopy
//
// Author : Daniel Sage, Biomedical Imaging Group (BIG), http://bigwww.epfl.ch/sage/
//
// Organization: Ecole Polytechnique Federale de Lausanne (EPFL), Lausanne, Switzerland
//
// Conditions of use: You'll be free to use this software for research purposes, but you
// should not redistribute it without our consent. In addition, we expect you to include a
// citation or acknowledgment whenever you present or publish results that are based on it.
//
//=========================================================================================
package smlms.simulation.defocussed2dfunction;
import smlms.tools.Tools;
public class Lorentz extends Defocussed2DFunction {
private double radius;
private double klorentz;
private double defocusFactor = 1.0;
public Lorentz(double radius, double defocusFactor) {
super();
this.defocusFactor = defocusFactor;
this.radius = radius;
klorentz = Math.sqrt(0.5)/(defocusFactor*radius);
klorentz = klorentz * klorentz;
}
public double eval(double x, double y) {
double r = x*x + y*y;
return 1.0 / (1.0 + r * klorentz);
}
public int getSupport() {
return 12*Tools.round(radius*defocusFactor)+1;
}
}
| Java |
2D | SMLM-Challenge/Challenge2016 | Simulator/Simulator-Java/src/smlms/simulation/defocussed2dfunction/Support.java | .java | 818 | 22 | //=========================================================================================
//
// Project: Localization Microscopy
//
// Author : Daniel Sage, Biomedical Imaging Group (BIG), http://bigwww.epfl.ch/sage/
//
// Organization: Ecole Polytechnique Federale de Lausanne (EPFL), Lausanne, Switzerland
//
// Conditions of use: You'll be free to use this software for research purposes, but you
// should not redistribute it without our consent. In addition, we expect you to include a
// citation or acknowledgment whenever you present or publish results that are based on it.
//
//=========================================================================================
package smlms.simulation.defocussed2dfunction;
public class Support {
public int x1;
public int x2;
public int y1;
public int y2;
}
| Java |
2D | SMLM-Challenge/Challenge2016 | Simulator/Simulator-Java/src/smlms/simulation/defocussed2dfunction/Rectangle.java | .java | 1,136 | 39 | //=========================================================================================
//
// Project: Localization Microscopy
//
// Author : Daniel Sage, Biomedical Imaging Group (BIG), http://bigwww.epfl.ch/sage/
//
// Organization: Ecole Polytechnique Federale de Lausanne (EPFL), Lausanne, Switzerland
//
// Conditions of use: You'll be free to use this software for research purposes, but you
// should not redistribute it without our consent. In addition, we expect you to include a
// citation or acknowledgment whenever you present or publish results that are based on it.
//
//=========================================================================================
package smlms.simulation.defocussed2dfunction;
import smlms.tools.Tools;
public class Rectangle extends Defocussed2DFunction {
private double size;
public Rectangle(double radius, double defocusFactor) {
super();
this.size = radius * defocusFactor;
}
public double eval(double x, double y) {
double r = x*x + y*y;
if (r < size*size)
return 1.0;
return 0.0;
}
public int getSupport() {
return 2*Tools.round(size)+1;
}
}
| Java |
2D | SMLM-Challenge/Challenge2016 | Simulator/Simulator-Java/src/smlms/simulation/defocussed2dfunction/DoubleHelix.java | .java | 1,501 | 48 | //=========================================================================================
//
// Project: Localization Microscopy
//
// Author : Daniel Sage, Biomedical Imaging Group (BIG), http://bigwww.epfl.ch/sage/
//
// Organization: Ecole Polytechnique Federale de Lausanne (EPFL), Lausanne, Switzerland
//
// Conditions of use: You'll be free to use this software for research purposes, but you
// should not redistribute it without our consent. In addition, we expect you to include a
// citation or acknowledgment whenever you present or publish results that are based on it.
//
//=========================================================================================
package smlms.simulation.defocussed2dfunction;
import smlms.tools.Tools;
public class DoubleHelix extends Defocussed2DFunction {
private double radius;
private double sigma;
private double kgauss;
private double cosa;
private double sina;
public DoubleHelix(double radius, double defocusFactor) {
super();
this.radius = radius;
this.sigma = 0.25*radius;
this.kgauss = 1.0 / (sigma * sigma * 2.0);
this.cosa = Math.cos(defocusFactor);
this.sina = Math.sin(defocusFactor);
}
public double eval(double x, double y) {
double u = x * cosa + y * sina;
double v = -x * sina + y * cosa;
double u1 = (u-radius*0.5);
double u2 = (u+radius*0.5);
return Math.exp(-((u1*u1+v*v)*kgauss)) + Math.exp(-((u2*u2+v*v)*kgauss));
}
public int getSupport() {
return 4*Tools.round(sigma*3)+1;
}
}
| Java |
2D | SMLM-Challenge/Challenge2016 | Simulator/Simulator-Java/src/smlms/simulation/defocussed2dfunction/Defocussed2DFunction.java | .java | 862 | 21 | //=========================================================================================
//
// Project: Localization Microscopy
//
// Author : Daniel Sage, Biomedical Imaging Group (BIG), http://bigwww.epfl.ch/sage/
//
// Organization: Ecole Polytechnique Federale de Lausanne (EPFL), Lausanne, Switzerland
//
// Conditions of use: You'll be free to use this software for research purposes, but you
// should not redistribute it without our consent. In addition, we expect you to include a
// citation or acknowledgment whenever you present or publish results that are based on it.
//
//=========================================================================================
package smlms.simulation.defocussed2dfunction;
public abstract class Defocussed2DFunction {
abstract public double eval(double x, double y);
abstract public int getSupport();
}
| Java |
2D | SMLM-Challenge/Challenge2016 | Simulator/Simulator-Java/src/smlms/simulation/defocussed2dfunction/Airy.java | .java | 1,284 | 42 | //=========================================================================================
//
// Project: Localization Microscopy
//
// Author : Daniel Sage, Biomedical Imaging Group (BIG), http://bigwww.epfl.ch/sage/
//
// Organization: Ecole Polytechnique Federale de Lausanne (EPFL), Lausanne, Switzerland
//
// Conditions of use: You'll be free to use this software for research purposes, but you
// should not redistribute it without our consent. In addition, we expect you to include a
// citation or acknowledgment whenever you present or publish results that are based on it.
//
//=========================================================================================
package smlms.simulation.defocussed2dfunction;
import smlms.tools.Tools;
public class Airy extends Defocussed2DFunction {
private double cycle;
private double size = 1.0;
public Airy(double radius, double defocusFactor) {
super();
this.size = radius * defocusFactor;
this.cycle = Math.PI * defocusFactor * defocusFactor;
this.size = radius*defocusFactor;
}
public double eval(double x, double y) {
double r = x*x + y*y;
if (r > size*size)
return 0;
return Math.max(0, (Math.cos(r * cycle)+0.5)*(1.0-r));
}
public int getSupport() {
return 8*Tools.round(size)+1;
}
}
| Java |
2D | SMLM-Challenge/Challenge2016 | Simulator/Simulator-Java/src/smlms/simulation/defocussed2dfunction/Linear.java | .java | 1,140 | 38 | //=========================================================================================
//
// Project: Localization Microscopy
//
// Author : Daniel Sage, Biomedical Imaging Group (BIG), http://bigwww.epfl.ch/sage/
//
// Organization: Ecole Polytechnique Federale de Lausanne (EPFL), Lausanne, Switzerland
//
// Conditions of use: You'll be free to use this software for research purposes, but you
// should not redistribute it without our consent. In addition, we expect you to include a
// citation or acknowledgment whenever you present or publish results that are based on it.
//
//=========================================================================================
package smlms.simulation.defocussed2dfunction;
import smlms.tools.Tools;
public class Linear extends Defocussed2DFunction {
private double size = 1.0;
public Linear(double radius, double defocusFactor) {
super();
this.size = radius * defocusFactor;
}
public double eval(double x, double y) {
double r = x*x + y*y;
if (r < size*size)
return (1.0 - r);
return 0.0;
}
public int getSupport() {
return 2*Tools.round(size)+1;
}
}
| Java |
2D | SMLM-Challenge/Challenge2016 | Simulator/Simulator-Java/src/smlms/simulation/defocussed2dfunction/ElongatedGaussian.java | .java | 1,568 | 52 | //=========================================================================================
//
// Project: Localization Microscopy
//
// Author : Daniel Sage, Biomedical Imaging Group (BIG), http://bigwww.epfl.ch/sage/
//
// Organization: Ecole Polytechnique Federale de Lausanne (EPFL), Lausanne, Switzerland
//
// Conditions of use: You'll be free to use this software for research purposes, but you
// should not redistribute it without our consent. In addition, we expect you to include a
// citation or acknowledgment whenever you present or publish results that are based on it.
//
//=========================================================================================
package smlms.simulation.defocussed2dfunction;
import smlms.tools.Tools;
public class ElongatedGaussian extends Defocussed2DFunction {
private double sigma;
private double elongation = 2.0;
private double cosa;
private double sina;
private double kgaussU;
private double kgaussV;
private double defocusFactor = 1.0;
public ElongatedGaussian(double sigma, double defocusFactor) {
super();
this.sigma = sigma;
this.kgaussU = 1.0 / (sigma * sigma * elongation);
this.kgaussV = 1.0 / (sigma * sigma / elongation);
this.cosa = Math.cos(defocusFactor);
this.sina = Math.sin(defocusFactor);
}
public double eval(double x, double y) {
double u = x * cosa + y * sina;
double v = -x * sina + y * cosa;
u = u * u * kgaussU;
v = v * v * kgaussV;
return Math.exp(-(u + v));
}
public int getSupport() {
return 4*Tools.round(sigma*elongation*2)+1;
}
}
| Java |
2D | SMLM-Challenge/Challenge2016 | Simulator/Simulator-Java/src/smlms/simulation/defocussed2dfunction/Astigmatism.java | .java | 1,305 | 43 | //=========================================================================================
//
// Project: Localization Microscopy
//
// Author : Daniel Sage, Biomedical Imaging Group (BIG), http://bigwww.epfl.ch/sage/
//
// Organization: Ecole Polytechnique Federale de Lausanne (EPFL), Lausanne, Switzerland
//
// Conditions of use: You'll be free to use this software for research purposes, but you
// should not redistribute it without our consent. In addition, we expect you to include a
// citation or acknowledgment whenever you present or publish results that are based on it.
//
//=========================================================================================
package smlms.simulation.defocussed2dfunction;
import smlms.tools.Tools;
public class Astigmatism extends Defocussed2DFunction {
private double sigma;
private double kx;
private double ky;
public Astigmatism(double radius, double defocusFactor) {
super();
this.sigma = 0.8493218*radius; //1/sqrt(-2*log(0.5))
double dy = defocusFactor * 1.5 - 1;
double dx = 1.0 / dy;
this.kx = 1.0/(dx*dx*sigma*sigma*2.0);
this.ky = 1.0/(dy*dy*sigma*sigma*2.0);
}
public double eval(double x, double y) {
return Math.exp(-x*x*kx - y*y*ky);
}
public int getSupport() {
return 4*Tools.round(sigma*2)+1;
}
}
| Java |
2D | SMLM-Challenge/Challenge2016 | Simulator/Simulator-Java/src/smlms/simulation/defocussed2dfunction/Gaussian.java | .java | 1,257 | 40 | //=========================================================================================
//
// Project: Localization Microscopy
//
// Author : Daniel Sage, Biomedical Imaging Group (BIG), http://bigwww.epfl.ch/sage/
//
// Organization: Ecole Polytechnique Federale de Lausanne (EPFL), Lausanne, Switzerland
//
// Conditions of use: You'll be free to use this software for research purposes, but you
// should not redistribute it without our consent. In addition, we expect you to include a
// citation or acknowledgment whenever you present or publish results that are based on it.
//
//=========================================================================================
package smlms.simulation.defocussed2dfunction;
import smlms.tools.Tools;
public class Gaussian extends Defocussed2DFunction {
private double sigma;
private double k;
private double defocusFactor = 1.0;
public Gaussian(double radius, double defocusFactor) {
super();
this.defocusFactor = defocusFactor;
sigma = radius;
this.k = 1.0/(defocusFactor*defocusFactor*sigma*sigma*2.0);
}
public double eval(double x, double y) {
double r = x*x + y*y;
return Math.exp(-r*k);
}
public int getSupport() {
return 4*Tools.round(sigma*defocusFactor*2)+1;
}
}
| Java |
2D | SMLM-Challenge/Challenge2016 | Tools/verifications/check_psf.py | .py | 2,928 | 85 | #!/usr/bin/env python
#
# Check that the PSF in the simulations matches the reference PSF.
#
# Hazen 04/16
#
import numpy
import sys
import tifffile
if (len(sys.argv) != 4):
print "usage: <psf.tiff> <images dir> <activations.csv>"
exit()
#
# This assumes that the z values in the activations file are
# in the range 0 - 1500nm. We are going to calculate the average
# psf with 100nm steps in z.
#
num_z_slices = 15
psf_xy_half_size = 10
psfs = numpy.zeros((num_z_slices, 2*psf_xy_half_size, 2*psf_xy_half_size), dtype = numpy.int64)
psfs_counts = numpy.zeros(num_z_slices, dtype = numpy.int32)
image_size = 128
with open(sys.argv[3]) as act_fp:
counts = 0
act_fp.readline()
for line in act_fp:
data = line.split(",")
f = int(data[1])
x = round(0.01 * float(data[2]))
y = round(0.01 * float(data[3]))
z = int(0.01 * float(data[4]))
if (x >= psf_xy_half_size) and (x < (image_size - psf_xy_half_size)):
if (y >= psf_xy_half_size) and (y < (image_size - psf_xy_half_size)):
image = tifffile.imread(sys.argv[2] + "{0:05d}.tif".format(f)).astype(numpy.int64)
im_slice = image[y-psf_xy_half_size:y+psf_xy_half_size,x-psf_xy_half_size:x+psf_xy_half_size]
psfs[z,:,:] += im_slice
psfs_counts[z] += 1
counts += 1
if ((counts%100) == 0):
print "Accumulated", counts
#if (counts > 100000):
# break
print "Normalizing"
for i in range(num_z_slices):
if (psfs_counts[i] > 0):
print i, psfs_counts[i]
psfs[i,:,:] = psfs[i,:,:]/psfs_counts[i]
psfs = psfs.astype(numpy.int16)
tifffile.imsave(sys.argv[1], psfs)
#
# The MIT License
#
# Copyright (c) 2016 Harvard Center for Advanced Imaging, Harvard University
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
#
| Python |
2D | SMLM-Challenge/Challenge2016 | Tools/CramerRao/computeSplineBasis3.m | .m | 276 | 12 | function x = computeSplineBasis3(x) %n = 3
x = abs(x);
%ind = (x >= 0 & x < 1);
%x(ind) = 2/3 - x(ind).^2 + x(ind).^3/2;
%ind = (x >= 1 & x < 2);
%x(ind) = (2 - x(ind)).^3/6;
%ind = (x >= 2);
%x(ind) = 0;
x = 1/12*(abs(x - 2).^3 - 4*abs(x - 1).^3 + 3*(x - 2).*x.^2 + 4);
end | MATLAB |
2D | SMLM-Challenge/Challenge2016 | Tools/CramerRao/ktensor.m | .m | 196 | 8 | function GR = ktensor(gr)
if length(gr)==2
GR = kron(gr{1}, gr{2}');
else
GRXY = kron(gr{1}, gr{2}');
GR = arrayfun(@(z) z*GRXY,gr{3},'UniformOutput',false);
GR = cat(3,GR{:});
end | MATLAB |
2D | SMLM-Challenge/Challenge2016 | Tools/CramerRao/prob_dens.m | .m | 675 | 21 | function prob_distr = prob_dens(camera_model,gain,eta,u)
%Probability density of camera model for a single initial photonelectron
if min(u)<0
error('u must be positive');
end
switch camera_model
case 'EMCCD'
%2004 Basden / 2016 Chao, exponential distribbution with param
%1/gain, plot p(u) for u=[0,max]
prob_distr = exp(-(u./gain + eta)).*sqrt(eta./(u*gain))...
.*besseli(1,2*sqrt(eta.*u./gain));
prob_distr(u==0) = exp(-eta);
otherwise
error('Not implemented yet');
end
fprintf('Empirical expectation : %1.2e; sum : %1.2e\n',mean(prob_distr.*u),sum(prob_distr));
%figure(10);plot(u,prob_distr);
end | MATLAB |
2D | SMLM-Challenge/Challenge2016 | Tools/CramerRao/main_EMCCD.m | .m | 509 | 22 | %Implementation from
m = 300;
p = 3e2;
c = unique(max(-2e3:2e4 + m*p,0));
n = 1;
gpm = @(c) 1/(factorial(n-1).*m.^n).*c.^(n-1).*exp(-c/m);
%figure(2);
%plot(c,gpm(c));
Gpm = @(c) exp(-p).*(c==0) + sqrt(p./(c.*m)).*exp(-c./m - p).*besseli(1,2*sqrt(c.*p./m));
prob_distr = prob_dens('EMCCD',m, p, c);
figure(3);
plot(c,Gpm(c),'LineWidth',2);hold on;
plot(c,prob_distr,'--','LineWidth',2);
line([m*p,m*p],[0,1.1*max(prob_distr)],'LineWidth',2,'Color','g','LineStyle',':');
legend('version 1','version 2');
| MATLAB |
2D | SMLM-Challenge/Challenge2016 | Tools/CramerRao/computeIntegralDer.m | .m | 5,856 | 110 | function integr = computeIntegralDer(coeffxy,pos_mol,NsplPix,delta,cam_siz,der)
%Output: siz
%Integrate spline basis function of degree 2/3 for der/other dimension rsp.
%Use integral relation with (sum of shifted) basis func of degree 3/4 rsp.
%For one camera pixel (others are shifted version of this integral)
siz = size(coeffxy);
%campix_step = step(1:2).*NsplPix;
integr = zeros(cam_siz);
K = 100;
switch der
case 1
for ind_camx = 1:cam_siz(1)
for ind_camy = 1:cam_siz(2)
int_der = zeros(siz(1),1);
int_other = zeros(siz(2),1);
for n = 1:siz(1)
%Integrate in dim X (horizontal)
%curr_s = inf;
%shift to the camera pixel coordinate (0 at the first included knot)
xprim = n - (ind_camx - 1)*NsplPix(1) - 1;
if xprim <= NsplPix(1) + 2 - 1 && xprim >= - 2 %NsplPix +- spline basis fct support/2
x = NsplPix(1) + (ind_camx - 1)*NsplPix(1) - pos_mol(1)/delta(1) - n + 0.5;% "spline basis domain"
lbx = (ind_camx - 1)*NsplPix(1) - pos_mol(1)/delta(1) - n + 0.5;
integrlbx = sum(computeSplineBasis3(lbx - 0.5 - (0:K)));
int_der(n) = delta(1)*(sum(computeSplineBasis3(x - 0.5 - (0:K))) - integrlbx);
end
end
for m = 1:siz(2)
%Integrate in dim Y
xprim = m - (ind_camy - 1)*NsplPix(2) - 1;
if xprim <= NsplPix(2) + 2 - 1 && xprim >= - 2 %NsplPix +- spline basis fct support/2
y = NsplPix(2) + (ind_camy - 1)*NsplPix(2) - pos_mol(2)/delta(2) - m;% "spline basis domain"
lby = (ind_camy - 1)*NsplPix(2) - pos_mol(2)/delta(2) - m;
integrlby = sum(computeSplineBasis4(lby - 0.5 - (0:K)));
int_other(m) = delta(2)*(sum(computeSplineBasis4(y - 0.5 - (0:K))) - integrlby);
end
end
integr(ind_camx,ind_camy) = sum(sum(kron(int_other',int_der).*coeffxy));
end
end
case 2
for ind_camx = 1:cam_siz(1)
for ind_camy = 1:cam_siz(2)
int_other = zeros(siz(1),1);
int_der = zeros(siz(2),1);
for n = 1:siz(1)
%Integrate in dim X
%curr_s = inf;
%shift to the camera pixel coordinate (0 at the first included knot)
xprim = n - (ind_camx - 1)*NsplPix(1) - 1;
if xprim <= NsplPix(1) + 2 - 1 && xprim >= - 2 %NsplPix +- spline basis fct support/2
x = NsplPix(1) + (ind_camx - 1)*NsplPix(1) - pos_mol(1)/delta(1) - n;% "spline basis domain"
lbx = (ind_camx - 1)*NsplPix(1) - pos_mol(1)/delta(1) - n;
integrlbx = sum(computeSplineBasis4(lbx - 0.5 - (0:K)));
int_other(n) = delta(1)*(sum(computeSplineBasis4(x - 0.5 - (0:K))) - integrlbx);
end
end
for m = 1:siz(2)
%Integrate in dim Y (vertical)
xprim = m - (ind_camy - 1)*NsplPix(2) - 1;
if xprim <= NsplPix(2) + 2 - 1 && xprim >= - 2 %NsplPix +- spline basis fct support/2
y = NsplPix(2) + (ind_camy - 1)*NsplPix(2) - pos_mol(2)/delta(2) - m + 0.5;% "spline basis domain"
lby = (ind_camy - 1)*NsplPix(2) - pos_mol(2)/delta(2) - m + 0.5;
integrlby = sum(computeSplineBasis3(lby - 0.5 - (0:K)));
int_der(m) = delta(2)*(sum(computeSplineBasis3(y - 0.5 - (0:K))) - integrlby);
end
end
integr(ind_camx,ind_camy) = sum(sum(kron(int_der',int_other).*coeffxy));
end
end
case 3
for ind_camx = 1:cam_siz(1)
for ind_camy = 1:cam_siz(2)
int_x = zeros(siz(1),1);
int_y = zeros(siz(2),1);
for n = 1:siz(1)
%Integrate in dim X
%curr_s = inf;
%shift to the camera pixel coordinate (0 at the first included knot)
xprim = n - (ind_camx - 1)*NsplPix(1) - 1;
if xprim <= NsplPix(1) + 2 - 1 && xprim >= - 2 %NsplPix +- spline basis fct support/2
x = NsplPix(1) + (ind_camx - 1)*NsplPix(1) - pos_mol(1)/delta(1) - n;% "spline basis domain"
lbx = (ind_camx - 1)*NsplPix(1) - pos_mol(1)/delta(1) - n;
integrlbx = sum(computeSplineBasis4(lbx - 0.5 - (0:K)));
int_x(n) = delta(1)*(sum(computeSplineBasis4(x - 0.5 - (0:K))) - integrlbx);
end
end
for m = 1:siz(2)
%Integrate in dim Y (vertical)
xprim = m - (ind_camy - 1)*NsplPix(2) - 1;
if xprim <= NsplPix(2) + 2 - 1 && xprim >= - 2 %NsplPix +- spline basis fct support/2
y = NsplPix(2) + (ind_camy - 1)*NsplPix(2) - pos_mol(2)/delta(2) - m;% "spline basis domain"
lby = (ind_camy - 1)*NsplPix(2) - pos_mol(2)/delta(2) - m;
integrlby = sum(computeSplineBasis4(lby - 0.5 - (0:K)));
int_y(m) = delta(2)*(sum(computeSplineBasis4(y - 0.5 - (0:K))) - integrlby);
end
end
integr(ind_camx,ind_camy) = sum(sum(kron(int_y',int_x).*coeffxy));
end
end
otherwise
error('not ready yet');
end
integr = integr(:);
end | MATLAB |
2D | SMLM-Challenge/Challenge2016 | Tools/CramerRao/computeEta.m | .m | 2,211 | 58 | function eta = computeEta(pos_mol,c,delta,cam_siz)
%siz = sqrt(Ntotpix)*ones(1,2);
%siz = ceil([Nx*step(1)/sqrt(Ntotpix),Ny*step(2)/sqrt(Ntotpix)]);%
%campix_step = step(1:2).*NsplPix;
siz = size(c);
Bz = computeSplineBasis3(pos_mol(3)/delta(3) - (1:siz(3))');% Nz x 1
NsplPix = ceil(siz(1:2)./cam_siz);%# splines basis fct per camera pixel
C = prod(delta(1:2))*squeeze(sum(sum(c,1),2))'...
*computeSplineBasis3(pos_mol(3)/delta(3) - (1:siz(3))');%normalization factor
coeff = permute(bsxfun(@(x,y) x.*y, permute(c/C,[3,1,2]), Bz),[2,3,1]);
eta = zeros(cam_siz);
%for cubic spline fitt.
%integr_bound = [-1.5:1:2,2*ones(1,6),1.5:-1:-1.5];
K = 100;
for ind_camx = 1:cam_siz(1)
for ind_camy = 1:cam_siz(2)
integrx = zeros(siz(1),1);
integry = zeros(siz(2),1);
for n = 1:siz(1)
%Integrate in dim X
%curr_s = inf;
%shift to the camera pixel coordinate (0 at the first included knot)
xprim = n - (ind_camx - 1)*NsplPix(1) - 1;
if xprim <= NsplPix(1) + 2 - 1 && xprim >= - 2 %NsplPix +- spline basis fct support/2
x = NsplPix(1) + (ind_camx - 1)*NsplPix(1) - pos_mol(1)/delta(1) - n;% "spline basis domain"
lbx = (ind_camx - 1)*NsplPix(1) - pos_mol(1)/delta(1) - n;
integrlbx = sum(computeSplineBasis4(lbx - 0.5 - (0:K)));
integrx(n) = delta(1)*(sum(computeSplineBasis4(x - 0.5 - (0:K))) - integrlbx);
end
end
for m = 1:siz(2)
%Integrate in dim Y
xprim = m - (ind_camy - 1)*NsplPix(2) - 1;
if xprim <= NsplPix(2) + 2 - 1 && xprim >= - 2 %NsplPix +- spline basis fct support/2
y = NsplPix(2) + (ind_camy - 1)*NsplPix(2) - pos_mol(2)/delta(2) - m;% "spline basis domain"
lby = (ind_camy - 1)*NsplPix(2) - pos_mol(2)/delta(2) - m;
integrlby = sum(computeSplineBasis4(lby - 0.5 - (0:K)));
integry(m) = delta(2)*(sum(computeSplineBasis4(y - 0.5 - (0:K))) - integrlby);
end
end
eta(ind_camx, ind_camy) = sum(sum(kron(integry',integrx).*sum(coeff,3)));
end
end
eta = eta(:); | MATLAB |
2D | SMLM-Challenge/Challenge2016 | Tools/CramerRao/save_parfor.m | .m | 449 | 21 | function save_parfor(name_mat, struct2save)
% save_parfor
%
% Inputs: name_mat: where the .mat will be saved, absolute path is
% recommended.
% varargin: the variables will be saved, don't pass on the names of
% the variables, i.e, strings.
%
% Outputs:
%
%
% EXAMPLE
%
%
% NOTES
% Wenbin, 11-Nov-2014
% History:
% Ver. 11-Nov-2014 1st ed.
save(name_mat,'-struct', 'struct2save','-v7.3'); | MATLAB |
2D | SMLM-Challenge/Challenge2016 | Tools/CramerRao/main_hist_z_photon.m | .m | 283 | 8 | ind = diff(activations.xnano([1:end,end]))==0 & diff(activations.ynano([1:end,end]))==0 & diff(activations.znano([1:end,end]))==0;
Nmol = nnz(ind);
ind = ~ind;
tmp = cumsum(ind);
for kk = 1:Nmol
Nphotons(kk) = sum(activations.intensity(kk==tmp));
Nact(kk) = nnz(kk==tmp);
end | MATLAB |
2D | SMLM-Challenge/Challenge2016 | Tools/CramerRao/main_extract_photons_mat.m | .m | 720 | 22 | z_oi = [-15,15];
fold_name = 'res';
modality = 'DH';
tmp = struct2table(dir(fullfile(fold_name,modality,'stack_*')));
Np_set = height(tmp);
%%
z_vec = -750:10:750;
ind_oi = z_vec > z_oi(1) & z_vec < z_oi(2);
fprintf('Number of z-slices per bin : %i\n', nnz(ind_oi));
CRLB = table(ones(Np_set,1),ones(Np_set,1),ones(Np_set,1),ones(Np_set,1),...
'VariableNames',{'Nphotons','x','y','z'});
for kk = 1:Np_set
load(fullfile(fold_name,modality,tmp.name{kk}));
CRLB.Nphotons(kk) = str2double(tmp.name{kk}(strfind(tmp.name{kk},'photon_')+7:strfind(tmp.name{kk},'_mod')-1));
CRLB.x(kk) = mean(stack.CRLB.x(ind_oi));
CRLB.y(kk) = mean(stack.CRLB.y(ind_oi));
CRLB.z(kk) = mean(stack.CRLB.z(ind_oi));
end | MATLAB |
2D | SMLM-Challenge/Challenge2016 | Tools/CramerRao/computeCubicSplineCoefs.m | .m | 2,203 | 69 | function coefs=computeCubicSplineCoefs(im)
%-------------------------------------------------
% function coefs=computeCubicSplineCoefs(im)
%
% Decompose the image im on a B-spline basis
%
% Exemple (in 2D):
% im=double(imread('cell.tif'));
% coefs=computeCubicSplineCoefs(im);
% sz=size(im);
% [C,R]=meshgrid(1:0.4:sz(2),1:sz(1)); % refine in y direction
% y=evaluateCubicSpline(coefs,cat(3,R,C));
% figure; subplot(1,2,1); imagesc(im); axis image; axis off;
% subplot(1,2,2); imagesc(y); axis image; axis off;
% figure; plot(1:sz(2),im(10,:),'o'); hold all;grid;
% plot(1:0.4:sz(2),y(10,:),'x'); legend('Initial','Interpolated');
% title('Extraction of 10th line');set(gca,'FontSize',14);
% axis([1 sz(2) 40 220]);
%
% See also evaluateCubicSpline
%
% Emmanuel Soubies, emmanuel.soubies@eplf.ch, 2017
%-------------------------------------------------
%% Some parameters
c0=6;
a=sqrt(3)-2;
ndms=ndims(im); % Number of dimnsions
allElements = repmat({':'},1,ndms); % to access elements in a vectorial mode
k0=ceil(log(eps)/log(abs(a))); % number of recursion for initializing causal filter
%% Loop over the dimensions
coefs=im;
for n=1:ndms
if size(im,n)~=1
elem=allElements;
% -- Recursive causal filter
% Initialisation
elem{n}=1;
polek=a;
elemtmp=elem;
for k=2:min(k0,size(im,n))
elemtmp{n}=k;
coefs(elem{:})= coefs(elem{:}) + polek*coefs(elemtmp{:});
polek=polek*a;
end
% Loop
for k=2:size(im,n)
elemprev=elem;
elem{n}=k;
coefs(elem{:})=coefs(elem{:}) + a*coefs(elemprev{:});
end
% -- Recursive anti-causal filter
% Initialisation
elem{n}=size(im,n);
elemprev=elem;elemprev{n}=size(im,n)-1;
coefs(elem{:})=(a/(a^2-1))* (coefs(elem{:}) + a*coefs(elemprev{:}));
% Loop
for k=size(im,n)-1:-1:1
elemprev=elem;
elem{n}=k;
coefs(elem{:})= a*(coefs(elemprev{:})-coefs(elem{:}));
end
% -- Gain
coefs=coefs*c0;
end
end
end
| MATLAB |
2D | SMLM-Challenge/Challenge2016 | Tools/CramerRao/probCamera.m | .m | 1,820 | 47 | function pkz = probCamera(z,nu,sig,umin,umax,gain,cam_model,eta,mode,reltol,abstol,Npoints) %,step_int
%reltol = 1e-8;
%abstol = 1e-11;
%z = vpa(z);
switch cam_model
case 'EMCCD'
switch mode
case 0 %simplified expr.
%integrate over u from umin to umax
pkz = integral(@(u) EMCCD(z, nu, sig, u, gain, eta,0),...
umin,umax,'ArrayValued',0,'RelTol',reltol,'AbsTol',abstol);
%pkz = exp(-nu)/(sqrt(2*pi)*sig)*(1 + pkz);%simplified in expr.
pkz = 1 + pkz;
case 1 %No simplification
%integrate over u from umin to umax
syms u;
pkz = vpaintegral(EMCCD(z, nu, sig, u, gain, eta,1),...
umin,umax,'ArrayValued',0,'RelTol',reltol,'AbsTol',abstol);
pkz = exp(-vpa(nu))/(sqrt(2*pi)*sig)*(exp(-(vpa(z) - eta)^2/(2*sig^2)) + pkz);
case 2 %No simplification, trapezoidal rule
u = linspace(umin,umax,Npoints);
pkz = trapz(u, EMCCD(z, nu, sig, u, gain, eta,1));
pkz = exp(-vpa(nu))/(sqrt(2*pi)*sig)*(exp(-(z - eta)^2/(2*sig^2)) + pkz);
pkz(isinf(pkz) || isnan(pkz)) = 0;
end
%if isnan(out)
% out = 0;
%end
end
end
function out = EMCCD(z,nu,sig,u,gain,eta,mode)
switch mode
case 0
%out = exp(-u.*(u + 2*eta - 2*z)/(2*sig^2) - u/gain);
out = exp((-((u + eta - z).^2 - (eta - z)^2)/(2*sig^2) - u/gain));
out = out.*sqrt(nu*u/gain).*besseli(1, (2*sqrt(nu*u/gain)))./u;
case 1
out = exp(-(z - u - eta).^2/(2*sig^2) - u/gain);
out = out.*sqrt(nu*u/gain).*besseli(1, 2*sqrt(nu*u/gain))./u;
end
%out = double(out);
out(u==0) = 0;
end | MATLAB |
2D | SMLM-Challenge/Challenge2016 | Tools/CramerRao/noise_coef_fct_vec.m | .m | 672 | 27 | function coeff = noise_coef_fct_vec(z, umin, umax, eta, sig, nu, gain, cam_model, reltol, abstol,Npoints)
%fprintf('doing vectorial way...');
%arrayfun is slower than a loop (+0.05 sec/element)
%tic
%coeff = arrayfun(@(x) noise_coef_fct(x, umin, umax, eta, sig, nu, gain, cam_model, reltol, abstol),z);
%toc
%tic
coeff = zeros(size(z));
for k = 1:length(z)
coeff(k) = noise_coef_fct(z(k), umin, umax, eta, sig, nu, gain, cam_model, reltol, abstol,Npoints);
end
%toc
% if isscalar(z)
% diffZ = 1;
% else
% diffZ = diff(z([1,1:end]));
% end
coeff = double(coeff);
T = 1;%min(nu*gain*diffZ,1e0);
coeff(coeff > T) = 0;%sometimes vpa still wrongly behaves
end | MATLAB |
2D | SMLM-Challenge/Challenge2016 | Tools/CramerRao/main_test_bounds.m | .m | 4,873 | 134 | %U: 75, Z: 50 for nu = 0.000213528237267334
maxsigU = 100;%25:25:200;
maxsigZ = 100;%[25:25:200];%[10,25,50,75,100,125,150,175];
minSigU = 100;
minSigZ = 100;
minNu = 1e-5;
maxNu = 250;
Ninterval = 16;
Npoints = 5e3;
parpool(min(feature('NumCores'),Ninterval));
camera_model = 'EMCCD';%'none';%
%nphoton = 5e8;
QE = 0.9;
bg = 0.0002;
sig_readout = 24;%74.4;
EmitPhot = 5000;
autoBg = 109;%Autofluorescence
eta = 0; %Mean of Gaussian random variable due to readout noise
if any(size(c).*delta/cam_pix~=1)
padding = ceil(size(c)./delta).*delta -size(c);
c = padarray(c,[padding(1:2),0],0,'post');
end
[Nx,Ny,~] = size(c);
detector_area = [Nx*delta(1),Ny*delta(2)];
Ncampix = ceil(detector_area/cam_pix);
Ntotpix = prod(Ncampix);
tic
Nphoton = @(N) N*QE;%For later change, if a function is rather output
%nu = Nphoton(EmitPhot)*computeEta(pos_mol,c,Ntotpix,step,Ncampix) + QE*autoBg + bg;
nu = [logspace(-5,2,8),150,200,250];
toc
gain = 1000;
%maximal (approx.) possible number of photons emitted by a fluorophore
%during one frame acquisition on ONE camera pixel
reltol = 1e-3;
abstol = 1e-7;
fact_tol = 1e0;
timer = zeros(length(nu),1); zminVec = timer; zmaxVec = timer;
camer = timer; Uvec = camer; Zvec = camer; noise_coeff = camer;
for k = 1:length(nu)
res = struct;
%for nnn = 1:length(setmaxU)
%for mmm = 1:length(setmaxZ)
curr_sig = sig_readout(min(k,end));
curr_nu = nu(k);
%possible outcomes from amplification of EMCCD, depends on photon input
NsigU = max((maxsigU - minSigU)/log(maxNu/minNu)*log(curr_nu/minNu),0) + minSigU;
NsigZ = max((maxsigZ - minSigZ)/log(maxNu/minNu)*log(curr_nu/minNu),0) + minSigZ;
amp_pcount = nu(k)*gain;
umin = 0.1; umax = max(1.4*(amp_pcount - 20*gain),0) + 50*gain + NsigU*sig_readout;
%possible outcomes from amplification of EMCCD & Gaussian readout noise, depends on photon input
zmin = min(amp_pcount - NsigU*sig_readout,0);
zmax = umax;
fprintf('Starting k : %i, U : %i, Z : %i, zmin/zmax : %1.2e/%1.2e, nu : %1.2e...',...
k,NsigU, NsigZ, zmin,zmax,curr_nu);
%z: camera electron count (realisation of amplification + Gaussian readout noise)
curr_reltol = reltol/(max(fact_tol*(NsigU < 0.5*maxsigU),1));
curr_abstol = abstol/(max(fact_tol*(NsigU < 0.5*maxsigU),1));
tic
intervals = linspace(zmin, zmax, 1 + max(Ninterval,1));
curr_cam = cell(max(Ninterval,1),1);
parfor p = 1:max(Ninterval,1)
curr_zmin = intervals(p);
curr_zmax = intervals(p + 1);
finer_step = curr_nu <= 1e-2 & curr_zmin <= amp_pcount & curr_zmax >= amp_pcount;
curr_N = Npoints*(50^(finer_step));
if true
z_vec = linspace(curr_zmin, curr_zmax,curr_N);
curr_cam{p} = trapz(z_vec,noise_coef_fct_vec(z_vec, umin, umax, eta,...
curr_sig, curr_nu, gain, camera_model, curr_reltol, curr_abstol,Npoints));
else
if amp_pcount >= curr_zmin && amp_pcount <= curr_zmax
waypoints = amp_pcount;
else
waypoints = [];
end
curr_cam{p} = integral(@(z) noise_coef_fct_vec(z, umin, umax, eta,...
curr_sig, curr_nu, gain, camera_model,curr_reltol,curr_abstol),...
curr_zmin,curr_zmax,'ArrayValued',0,'RelTol',curr_reltol,'AbsTol',curr_abstol,...
'Waypoints',waypoints);
end
fprintf('noise coeff %i/%i : %1.2e\n',p,max(Ninterval,1),...
(curr_cam{p} - 1/max(Ninterval,1))*curr_nu);
end
curr_cam = sum(cell2mat(curr_cam));
timer(k) = toc;
camer(k) = curr_cam;
zminVec(k) = zmin;
zmaxVec(k) = zmax;
Uvec(k) = maxsigU;
Zvec(k) = maxsigZ;
noise_coeff(k) = (curr_cam - 1)*curr_nu;
fprintf('cam : %1.2e, noise coeff : %1.3f, time : %1.2f s\n',...
curr_cam, noise_coeff(k), timer(k));
%noise_coeff((nnn-1)*length(setZ) + mmm),timer((nnn-1)*length(setZ) + mmm));
%iter = iter + 1;
%end
end
fname = sprintf('fig8_%i_reltol_%i_abstol_%i.mat', k,log10(curr_reltol),log10(curr_abstol));
counter = 1;
while exist(fname,'file')
fname = sprintf('fig8_%i_reltol_%i_abstol_%i_%i.mat', k, log10(curr_abstol),...
log10(curr_abstol),counter);
counter = counter + 1;
end
%save(fname,'timer','camer','Uvec','Zvec','setU','setZ','curr_nu','noise_coeff');
res.timer = timer; res.camer = camer; res.Uvec = Uvec; res.Zvec = Zvec;
res.setU = maxsigU; res.setZ = maxsigZ; res.curr_nu = curr_nu; res.noise_coeff = noise_coeff;
save_parfor(fname,res);
%%
V = cell2mat(noise_coeff)';
Vtime = cell2mat(timer)';
figure;
subplot(121);
imagesc(maxsigU, maxsigZ, V);colorbar;axis image;title('noise coeff');xlabel('U');ylabel('Z');
subplot(122);
imagesc(maxsigU, maxsigZ, Vtime);colorbar;axis image;title('Time [s]');xlabel('U');ylabel('Z'); | MATLAB |
2D | SMLM-Challenge/Challenge2016 | Tools/CramerRao/main_cramer_rao.m | .m | 3,710 | 133 | %Cramer-Rao bounds
clear
dir_name = '~/Documents/SMLM/analysis/psf/';%'~/Downloads/PSF GL 200x200x151.tif';%
modality = 'AS';
Nz = 151;
[PSF,summedPSF,Nx,Ny] = load_PSF(dir_name,modality,Nz);
%% Fit cubic spline from 3D psf
%[Nx,Ny,Nz] = size(PSF);
d = [3*ones(1,3),0,0,0];%degree of Bsplines
dx = 10;%nm
dy = 10;%nm
dz = 10;%nm
x = (1-Nx/2:Nx/2)*dx; y = (1-Ny/2:Ny/2)*dy; z = (1-Nz/2:Nz/2)*dz;
%%
tic
%c = PSF;
c = computeCubicSplineCoefs(PSF);
%c = spm_bsplinc(PSF,d);
toc
%%
filter1D = [1,4,1]/6;%cubic
filter1D = circshift(filter1D,[0,0]);
filter3D = ktensor({filter1D,filter1D,filter1D});
filter3Dext = padarray(filter3D,[Nx,Ny,Nz]- length(filter1D),'post');
tic
ePSF = ifftn(fftn(c).*fftn(filter3Dext));
toc
err = (ePSF - PSF)./PSF;
fprintf('Average error : %1.4e\n',mean(err(:)));
%% Spatial Conv (Weird)
tic
ePSF = imfilter(c,filter3D,'symmetric','conv');%'replicate', 'symmetric', 'circular'
%ePSF = convn(c,filter3D,'same');
toc
err = (ePSF - PSF)./PSF;
fprintf('Average error : %1.4e\n',mean(err(:)));
%% separable filtering
tic
ePSF = c;
for kk = 1:3
ePSF = filter(filter1D,1,ePSF,[],kk);
end
toc
err = (ePSF - PSF)./PSF;
fprintf('Average error : %1.4e\n',mean(err(:)));
%% reconstruction method
tic
[X, Y, Z] = ndgrid(1:Nx,1:Ny,1:Nz);
ePSF = evaluateCubicSpline(c,[X(:),Y(:),Z(:)]);
toc
err = (ePSF - PSF)./PSF;
fprintf('Average error : %1.4e\n',mean(err(:)));
%%
if ~exist('ePSF','var')
ePSF = PSF;
end
figure(10);
for kk = 76 + 18
subplot(131);imagesc(x,y,ePSF(:,:,kk));
axis image;title(sprintf('Spline, axial position %1.2f nm',z(kk)));colorbar;
subplot(132);imagesc(x,y,PSF(:,:,kk));
axis image;title(sprintf('PSF, axial position %1.2f nm',z(kk)));colorbar;
subplot(133);imagesc(x,y,abs(ePSF(:,:,kk) - PSF(:,:,kk))./PSF(:,:,kk));
axis image;title(sprintf('PSF difference, axial position %1.2f nm',z(kk)));colorbar;
pause(0.001);
end
%% Get CramerRao bounds
cam_pix = 100;%nm
delta = [dx,dy,dz];
%parpool(4);
mkdir('res');
Nphotons_set = [50,250,500,750,1000:500:1e4];
for Nphotons = 1:length(Nphotons_set)
stack = repmat(struct('CRLB',[],'I',[],'cam_coef',[],...
'nu',[],'deta',[],'par',[]),151,1);
parfor k = 1:151
pos_mol = [0,0,k].*delta;%bounds : [-215,215] x [-215,215] x [0,150] .* step
glob_timer = tic;
[stack(k).I,stack(k).cam_coef,stack(k).nu,stack(k).deta,stack(k).par] ...
= computeCramerRao(c, delta, cam_pix, pos_mol,...
'EmitPhot',Nphotons,'camera_model','half');
toc(glob_timer)
CRLB = sqrt(diag(stack(k).I^(-1)));
stack(k).CRLB.x = CRLB(1);
stack(k).CRLB.y = CRLB(2);
stack(k).CRLB.z = CRLB(3);
stack(k).CRLB.photon = CRLB(4);
stack(k).CRLB.bg = CRLB(5);
end
stack = struct2table(stack);
save(sprintf('res/stack_photon_%i.mat',Nphotons_set(Nphotons)),stack);
end
%%
I = zeros(size(I));
for kk = 1:size(I,1)
for ll = 1:size(I,2)
for mm = 1:length(nu)
I(kk,ll) = I(kk,ll) + cam_coef(mm)*deta(mm,kk)*deta(mm,ll);
end
end
end
CRLB = sqrt(diag(I^(-1)))
%%
tmp = I(1:3,1:3);
diag(tmp^(-1))
%%
ind = pairings.Zt <= 5 & pairings.Zt >= -5;
rmseX = sqrt(nanmean((pairings.Xt(ind) - pairings.Xs(ind)).^2))
rmseY = sqrt(nanmean((pairings.Yt(ind) - pairings.Ys(ind)).^2))
rmse = sqrt(nanmean((pairings.Xt(ind) - pairings.Xs(ind)).^2 + (pairings.Yt(ind) - pairings.Ys(ind)).^2))
%%
for k = 1:height(stack)
CRLBx(k) = stack.CRLB{k}(1);
CRLBy(k) = stack.CRLB{k}(2);
CRLBz(k) = stack.CRLB{k}(3);
photon(k) = stack.CRLB{k}(4);
bg(k) = stack.CRLB{k}(5);
end
t = 1:10:151;
figure,plot(t,CRLBx);hold on;
plot(t,CRLBy);
plot(t,CRLBz);
legend('X','Y','Z'); | MATLAB |
2D | SMLM-Challenge/Challenge2016 | Tools/CramerRao/computeSplineBasis2.m | .m | 64 | 5 | function y = computeSplineBasis2(x)
y = max(1 - abs(x),0);
end | MATLAB |
2D | SMLM-Challenge/Challenge2016 | Tools/CramerRao/noise_coef_fct.m | .m | 2,558 | 62 | function coeff = noise_coef_fct(z, umin, umax, eta, sig, nu, gain,cam_model,reltol,abstol,Npoints)
%NOISE_COEF_FCT
%syms u;
integr_type = 2;
if true %max(-(umin:umax).*((umin:umax) + 2*eta - 2*z)/(2*sig^2) - (umin:umax)/gain) > 70
% No simplification
pkz = probCamera(z,nu,sig,umin,umax,gain,cam_model,eta,integr_type,reltol,abstol,Npoints);
if integr_type==1
syms u;
coeff = vpaintegral(u_int(u, z, eta, sig, nu, gain, 1),...
umin, umax,'ArrayValued',0,'RelTol',reltol,'AbsTol',abstol);
coeff = vpa(exp(-vpa(nu))/(sqrt(2*pi)*sig*gain)*coeff);
else
u = linspace(umin,umax,Npoints);
coeff = trapz(u, u_int(u, z, eta, sig, nu, gain, 1));
coeff = vpa(exp(-vpa(nu))/(sqrt(2*pi)*sig*gain)*coeff);
end
if (logical(pkz==0) && logical(coeff==0)) || isnan(pkz) || isnan(coeff)
pkz = probCamera(z,nu,sig,umin,umax,gain,cam_model,eta,0,reltol,abstol);
coeff = integral(@(uprim) u_int(uprim, z, eta, sig, nu, gain,0),...
umin, umax,'ArrayValued',0,'RelTol',reltol,'AbsTol',abstol);
%Note: avoid ^2 (can be (1e+154)^2=inf whereas exp(-(z-eta).^2 [...]) ~=1e-154
%with coeff.*coeff, it is still able to compute it.
coeff = exp(vpa(-(z - eta).^2/(2*sig^2)))...
.*exp(vpa(-nu))/(sqrt(2*pi)*sig*gain^2)... %gain^2 because not simplified in pkz expr.
.*vpa(coeff).*vpa(coeff)/pkz;
else
coeff = coeff.*coeff/pkz;
end
else %simplified expr.
pkz = probCamera(z,nu,sig,umin,umax,gain,cam_model,eta,0,reltol,abstol);
coeff = integral(@(u) u_int(u, z, eta, sig, nu, gain,0),...
umin, umax,'ArrayValued',0,'RelTol',reltol,'AbsTol',abstol);
%Note: avoid ^2 (can be (1e+154)^2=inf whereas exp(-(z-eta).^2 [...]) ~=1e-154
%with coeff.*coeff, it is still able to compute it.
coeff = exp(vpa(-(z - eta).^2/(2*sig^2)))...
.*exp(vpa(-nu))/(sqrt(2*pi)*sig*gain^2)... %gain^2 because not simplified in pkz expr.
.*vpa(coeff).*vpa(coeff)/pkz;
end
%coeff = double(coeff);
end
function coeff = u_int(u, z, eta, sig, nu, gain, mode)
switch mode
case 0
%simplified for EMCCD
%coeff = exp(-u.*(u + 2*eta - 2*z)/(2*sig^2) - u/gain)...
coeff = exp(-((u + eta - z).^2 - (eta - z)^2)/(2*sig^2) - u/gain)...
.*besseli(0,2*sqrt(nu .* u/gain));
case 1
% Not simplified
coeff = exp(-(z - u - eta).^2/(2*sig^2) - u/gain)...
.*besseli(0,2*sqrt(nu .* u/gain));
end
%coeff(isnan(coeff)) = 0;
end | MATLAB |
2D | SMLM-Challenge/Challenge2016 | Tools/CramerRao/computedEta.m | .m | 3,192 | 73 | function deta = computedEta(N, c, Ntotpix, delta, pos_mol,mu,cam_siz)
%Output : Ncampix x ndims(c)
%Ncampix: total number of camera pixel
deta = zeros(Ntotpix,ndims(c));
[Nx,Ny,Nz] = size(c);% V := prod(size(c))
%cam_siz = sqrt(Ntotpix)*ones(1,2);
NsplPix = ceil([Nx,Ny]./cam_siz);%# splines basis fct per camera pixel
Bz = computeSplineBasis3(pos_mol(3)/delta(3) - (1:Nz)');% Nz x 1
C = prod(delta(1:2))*squeeze(sum(sum(c,1),2))'...
*computeSplineBasis3(pos_mol(3)/delta(3) - (1:Nz)');%normalization factor
% derivative wrt x
cpad = padarray(c,[1,0,0],0,'both');
diffC = (circshift(cpad,[-1,0,0]) - cpad)./C;%(Nx + 2) x Ny x Nz
%(Nx + 1) x Ny x Nz
coeff = permute(bsxfun(@(x,y) x.*y, permute(diffC(1:end-1,:,:)/delta(1),[3,1,2]), Bz),[2,3,1]);
% if mod(size(coeff,1),ceil(Nx/cam_siz(1)))~=0
% size of coeff not exactly matching with camera pixel, pad with 0
% coeff = padarray(coeff,[size(coeff,1) - mod(size(coeff,1),ceil(Nx/cam_siz(1))),0,0]/2,0,'both');
% end
% if mod(size(coeff,2),ceil(Ny/sqrt(Ntotpix)))~=0
% coeff = padarray(coeff,[0, size(coeff,2) - mod(size(coeff,1),ceil(Ny/cam_siz(2))),0]/2,0,'both');
% end
deta(:,1) = -N*computeIntegralDer(sum(coeff,3),pos_mol(1:2),NsplPix, delta, cam_siz, 1); %Output : ceil(Nx/sqrt(Ncampix)) x ceil(Ny/sqrt(Ncampix))
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% derivative wrt y
cpad = padarray(c,[0,1,0],0,'both');
diffC = (circshift(cpad,[0,-1,0]) - cpad)./C;%Nx x (Ny + 2) x Nz
%Nx x (Ny + 1) x Nz
coeff = permute(bsxfun(@(x,y) x.*y, permute(diffC(:,1:end-1,:)/delta(2),[3,1,2]), Bz),[2,3,1]);
% if mod(size(coeff,1),ceil(Nx/cam_siz(1)))~=0
% size of coeff not exactly matching with camera pixel, pad with 0
% coeff = padarray(coeff,[size(coeff,1) - mod(size(coeff,1),ceil(Nx/cam_siz(1))),0,0]/2,0,'both');
% end
% if mod(size(coeff,2),ceil(Ny/sqrt(Ntotpix)))~=0
% coeff = padarray(coeff,[0, size(coeff,2) - mod(size(coeff,1),ceil(Ny/cam_siz(2))),0]/2,0,'both');
% end
deta(:,2) = -N*computeIntegralDer(sum(coeff,3),pos_mol(1:2),NsplPix, delta, cam_siz, 2); %Output : ceil(Nx/sqrt(Ncampix)) x ceil(Ny/sqrt(Ncampix))
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% derivative wrt z
cpad = padarray(c,[0,0,1],0,'both');
diffC = (circshift(cpad,[0,0,-1]) - cpad)./C;%Nx x (Ny + 2) x Nz
Bz2 = computeSplineBasis2(pos_mol(3)/delta(3) - (1:(Nz+1))' + 0.5);% Nz x 1
%Nx x Ny x (Nz+1)
coeff = permute(bsxfun(@(x,y) x.*y, permute(diffC(:,:,1:end-1)/delta(3),[3,1,2]), Bz2),[2,3,1]);
% if mod(size(coeff,1),ceil(Nx/cam_siz(1)))~=0
% size of coeff not exactly matching with camera pixel, pad with 0
% coeff = padarray(coeff,[size(coeff,1) - mod(size(coeff,1),ceil(Nx/cam_siz(1))),0,0]/2,0,'both');
% end
% if mod(size(coeff,2),ceil(Ny/sqrt(Ntotpix)))~=0
% coeff = padarray(coeff,[0, size(coeff,2) - mod(size(coeff,1),ceil(Ny/cam_siz(2))),0]/2,0,'both');
% end
deta(:,3) = N*computeIntegralDer(sum(coeff,3),pos_mol(1:2),NsplPix, delta, cam_siz, 3); %Output : ceil(Nx/sqrt(Ncampix)) x ceil(Ny/sqrt(Ncampix))
deta(:,3) = deta(:,3) - sum(coeff(:))*prod(delta(1:2))*mu(:);
end | MATLAB |
2D | SMLM-Challenge/Challenge2016 | Tools/CramerRao/computeCramerRao.m | .m | 3,941 | 110 | function [I,cam_coef,nu,deta,par] = computeCramerRao(c,delta,cam_pix,pos_mol,varargin)
%c: spline coefficients of PSF fitting
%step: step between knot
%cam_pix: camera pixel size in the object plane
%pos: molecule position (0,0) at the top left
par = inputParser;
addParameter(par,'QE',0.9,@isnumeric);
addParameter(par,'spurious_charge',0.0002,@isnumeric);
addParameter(par,'camera_model','half');%'EMCCD','none'
addParameter(par,'sig_readout',74.4,@isnumeric);
addParameter(par,'EmitPhot',5000,@isnumeric);
addParameter(par,'autoBg',109,@isnumeric);
addParameter(par,'eta',0,@isnumeric);
addParameter(par,'gain',300,@isnumeric);
%numerical integration for camera noise coefficient
%related to maximal (approx.) possible number of photons emitted by a fluorophore
%during one frame acquisition on ONE camera pixel
addParameter(par,'NsigU',100,@isnumeric);
addParameter(par,'NsigZ',100,@isnumeric);
addParameter(par,'umin',0.1,@isnumeric);
addParameter(par,'Npoints',1e4,@isnumeric);
addParameter(par,'Npool',4,@isnumeric);
parse(par,varargin{:});
par = par.Results;
reltol = 1e-8; abstol = 1e-11;%deprecated since trapz
par.Npool = max(par.Npool,1);
if any(size(c).*delta/cam_pix~=1)
padding = ceil(size(c)./delta).*delta -size(c);
c = padarray(c,[padding(1:2),0],0,'post');
end
[Nx,Ny,~] = size(c);
detector_area = [Nx*delta(1),Ny*delta(2)];
cam_siz = ceil(detector_area/cam_pix);
Ntotpix = prod(cam_siz);
tic
par.bg = par.spurious_charge + par.autoBg*par.QE;
%Nphoton = @(N) N*QE;%For later change, if a function is rather output
mu = par.EmitPhot*par.QE*computeEta(pos_mol,c,delta,cam_siz);
nu = mu + par.bg;
[nu_unique, ~, ind_nu] = unique(round(nu*10)/10);
toc
%syms z;
tic
switch par.camera_model
case 'EMCCD'
cam_coef = zeros(length(nu_unique),1);
for k = 1:length(nu_unique)
curr_nu = nu_unique(min(k,end));
amp_pcount = curr_nu*par.gain;
umax = max(1.4*(amp_pcount - 20*par.gain),0) + 50*par.gain + par.NsigU*par.sig_readout;
%possible outcomes from amplification of EMCCD & Gaussian readout noise, depends on photon input
zmin = min(amp_pcount - par.NsigU*par.sig_readout,0);
zmax = umax;
fprintf('Starting k : %i, U : %i, Z : %i, zmin/zmax : %1.2e/%1.2e, nu : %1.2e...',...
k, par.NsigU, par.NsigZ, zmin, zmax,curr_nu);
intervals = linspace(zmin, zmax, 1 + par.Npool);
curr_cam = zeros(par.Npool,1);
parfor p = 1:par.Npool
curr_zmin = intervals(p);
curr_zmax = intervals(p + 1);
z_vec = linspace(curr_zmin, curr_zmax, par.Npoints);
curr_cam(p) = trapz(z_vec,noise_coef_fct_vec(z_vec, par.umin, umax, par.eta,...
par.sig_readout, curr_nu, par.gain, par.camera_model, reltol, abstol, par.Npoints));
fprintf('noise coeff %i/%i : %1.2e\n',p,par.Npool,...
(curr_cam(p) - 1/par.Npool)*curr_nu);
end
cam_coef(k) = sum(curr_cam);
if mod(k, 1)==0
fprintf('%i/%i : %1.2f, noise coeff : %1.2e\n',k, length(cam_coef),toc,(cam_coef(k) - 1)*curr_nu);
end
end
cam_coef = cam_coef - 1;
case {'none','Poisson'}
cam_coef = 1./nu_unique;
case 'half'
cam_coef = 5e-1./nu_unique;
otherwise
error('Not implemented yet');
end
cam_coef = cam_coef(ind_nu);
toc
%Compute eta derivative = mu derivative
deta = computedEta(par.EmitPhot,c,Ntotpix,delta,pos_mol,mu,cam_siz); %Output: Ncampix x 3
deta = [deta, mu/par.EmitPhot, ones(Ntotpix,1)];%x,y,z,N,background
I = zeros(size(deta,2));
for kk = 1:size(I,1)
for ll = 1:size(I,2)
for mm = 1:Ntotpix
I(kk,ll) = I(kk,ll) + cam_coef(mm)*deta(mm,kk)*deta(mm,ll);
end
end
end
end
| MATLAB |
2D | SMLM-Challenge/Challenge2016 | Tools/CramerRao/load_PSF.m | .m | 1,605 | 57 | function [PSF,summed,Nx,Ny] = load_PSF(dir_name, modality,Nz)
switch modality
case {'2D','AS','DH'}
fname = fullfile(dir_name, sprintf('%s-Exp.tif', modality));
case 'BP'
fname{1} = fullfile(dir_name, sprintf('%s+250.tif', modality));
fname{2} = fullfile(dir_name, sprintf('%s-250.tif', modality));
otherwise
error('Unknown modality');
end
if iscell(fname)
Ncam = length(fname);
Ny = zeros(Ncam,1);
for kk = 1:Ncam
file{kk} = Tiff(fname{kk},'r');
if kk==1
Nx = file{kk}.getTag('ImageLength');
elseif Nx~=file{kk}.getTag('ImageLength')
error('Loaded Tiffs do not have the same dimension in X');
end
Ny(kk) = file{kk}.getTag('ImageWidth');
end
PSF = zeros(Nx,sum(Ny),Nz);
else
file = Tiff(fname,'r');
Nx = file.getTag('ImageLength');
Ny = file.getTag('ImageWidth');
PSF = zeros(Nx,Ny,Nz);
end
%figure(1);
summed = zeros(Nz,1);
for kk = 1:Nz
if iscell(fname)
for ll = 1:Ncam
PSF(:,1 + sum(Ny(1:(ll-1))):sum(Ny(1:(ll-1)))+Ny(ll),kk) = file{ll}.read;
if kk < Nz
file{ll}.nextDirectory
end
end
summed(kk) = sum(sum(PSF(:,:,kk),1),2);
else
PSF(:,:,kk) = file.read;
%imagesc(PSF(:,:,kk));
summed(kk) = sum(sum(PSF(:,:,kk),1),2);
%axis image;title(sprintf('slice %i, slice sum %1.2f',kk,summed(kk)));
%colorbar;pause(0.001);
if kk < Nz
file.nextDirectory;
end
end
end
Ny = sum(Ny);
PSF = PSF/summed(76);
end | MATLAB |
2D | SMLM-Challenge/Challenge2016 | Tools/CramerRao/evaluateCubicSpline.m | .m | 5,357 | 148 | function y=evaluateCubicSpline(coefs,x)
%-------------------------------------------------
% function y=evaluateCubicSpline(coefs,x)
%
% See the functions below for a description of the parameters
%
% Exemple (in 2D):
% im=double(imread('cell.tif'));
% coefs=computeCubicSplineCoefs(im);
% sz=size(im);
% [C,R]=meshgrid(1:0.4:sz(2),1:sz(1)); % refine in y direction
% y=evaluateCubicSpline(coefs,cat(3,R,C));
% figure; subplot(1,2,1); imagesc(im); axis image; axis off;
% subplot(1,2,2); imagesc(y); axis image; axis off;
% figure; plot(1:sz(2),im(10,:),'o'); hold all;grid;
% plot(1:0.4:sz(2),y(10,:),'x'); legend('Initial','Interpolated');
% title('Extraction of 10th line');set(gca,'FontSize',14);
% axis([1 sz(2) 40 220]);
%
% Note: This code is quite generic since it works for any set of points x
% As a drawback the computation (in particular for 3D x) can tale
% few minutes. There is probably possibilities of improvement.
%
% See also computeCubicSplineCoefs
%
% Emmanuel Soubies, emmanuel.soubies@eplf.ch, 2017
%-------------------------------------------------
%% Some parameters
ndms=ndims(x); % Number of dimensions
if isvector(x), ndms=1; end
%% Loop over the dimensions
switch ndms
case 1
y=evaluateCubicSpline1D(coefs,x);
case 3
y=evaluateCubicSpline2D(coefs,x);
case 4
y=evaluateCubicSpline3D(coefs,x);
end
end
function y=evaluateCubicSpline3D(coefs,x)
%-------------------------------
% function y=evaluateCubicSpline3D(coefs,x)
%
% Evaluate the spline at positions in x
% - coef contains spline coefficients (2D matrix N x M x P)
% - x contains the position where the spline will be
% evaluated (N x M x P x 3 matrix where x(:,:,1) has constant rows with
% values in [1,size(coefs,1)], x(:,:,2) has constant columns with
% values in [1,size(coefs,2)] and x(:,:,3) has constant values in the
% third direction within [1,size(coefs,3)] (extention of the 2D case).
%-------------------------------
fx=floor(x);
sz=size(coefs);
p1{1}=[2,1:sz(1)-1]; p2{1}=[2,1:sz(2)-1]; p3{1}=[2,1:sz(3)-1];
p1{2}=1:sz(1); p2{2}=1:sz(2); p3{2}=1:sz(3);
p1{3}=[2:sz(1),sz(1)-1]; p2{3}=[2:sz(2),sz(2)-1]; p3{3}=[2:sz(3),sz(3)-1];
p1{4}=[3:sz(1),sz(1)-1,sz(1)-2]; p2{4}=[3:sz(2),sz(2)-1,sz(2)-2]; p3{4}=[3:sz(3),sz(3)-1,sz(3)-2];
c=@(p,q,k) arrayfun(@(v,u,w) coefs(p1{p}(v),p2{q}(u),p3{k}(w)),fx(:,:,:,1),fx(:,:,:,2),fx(:,:,:,3));
[w1{1},w1{2},w1{3},w1{4}]=getCubicSpline(x(:,:,:,1)-fx(:,:,:,1));
[w2{1},w2{2},w2{3},w2{4}]=getCubicSpline(x(:,:,:,2)-fx(:,:,:,2));
[w3{1},w3{2},w3{3},w3{4}]=getCubicSpline(x(:,:,:,3)-fx(:,:,:,3));
y=zeros(size(x,1),size(x,2),size(x,3));
id=1;
for ii=1:4
for jj=1:4
for kk=1:4
disp(['Progression : ',num2str(round(id/64*100)),'%']);
y=y+c(ii,jj,kk).*w1{ii}.*w2{jj}.*w3{kk};
id=id+1;
end
end
end
end
function y=evaluateCubicSpline2D(coefs,x)
%-------------------------------
% function y=evaluateCubicSpline2D(coefs,x)
%
% Evaluate the spline at positions in x
% - coef contains spline coefficients (2D matrix N x M)
% - x contains the position where the spline will be
% evaluated (N x M x 2 matrix where x(:,:,1) has constant rows with
% values in [1,size(coefs,1)] and x(:,:,2) has constant columns with
% values in [1,size(coefs,2)]. E.g.
%
% x(:,:,1)=[ 1 1 1 x(:,:,2)=[ 1 1.5 2
% 1.5 1.5 1.5 1 1.5 2
% 2 2 2] 1 1.5 2]
%-------------------------------
fx=floor(x);
sz=size(coefs);
p1{1}=[2,1:sz(1)-1]; p2{1}=[2,1:sz(2)-1];
p1{2}=1:sz(1); p2{2}=1:sz(2);
p1{3}=[2:sz(1),sz(1)-1]; p2{3}=[2:sz(2),sz(2)-1];
p1{4}=[3:sz(1),sz(1)-1,sz(1)-2]; p2{4}=[3:sz(2),sz(2)-1,sz(2)-2];
c=@(p,q) arrayfun(@(v,u) coefs(p1{p}(v),p2{q}(u)),fx(:,:,1),fx(:,:,2));
[w1{1},w1{2},w1{3},w1{4}]=getCubicSpline(x(:,:,1)-fx(:,:,1));
[w2{1},w2{2},w2{3},w2{4}]=getCubicSpline(x(:,:,2)-fx(:,:,2));
y=zeros(size(x,1),size(x,2));
id=1;
for ii=1:4
for jj=1:4
disp(['Progression : ',num2str(round(id/16*100)),'%']);
y=y+c(ii,jj).*w1{ii}.*w2{jj};
id=id+1;
end
end
end
function y=evaluateCubicSpline1D(coefs,x)
%-------------------------------
% function y=evaluateCubicSpline1D(coefs,x)
%
% Evaluate the spline at positions in x
% - coef contains spline coefficients (1D vector)
% - x contains the position where the spline will be
% evaluated (vector with values in [1 length(coefs)])
%-------------------------------
n=length(coefs);
fx=floor(x);
p1=[2,1:n-1]; c1=arrayfun(@(v) coefs(p1(v)),fx);
p2=1:n; c2=arrayfun(@(v) coefs(p2(v)),fx);
p3=[2:n,n-1]; c3=arrayfun(@(v) coefs(p3(v)),fx);
p4=[3:n,n-1,n-2]; c4=arrayfun(@(v) coefs(p4(v)),fx);
[w1,w2,w3,w4]=getCubicSpline(x-fx);
y=c1.*w1+c2.*w2+c3.*w3+c4.*w4;
end
function [v0,v1,v2,v3]=getCubicSpline(t)
%-------------------------------
% function v=getCubicSpline(t)
%
% For a value t in [0 1] return the weights
% to assign to each spline coef
%-------------------------------
assert(all(t(:)>=0) && all(t(:)<=1),'Wrong value for t !');
t1=1-t;
t2=t.^2;
v0=t1.^3/6;
v1=2/3+0.5*t2.*(t-2);
v3=(t2.*t)/6;
v2=1-v3-v1-v0;
end | MATLAB |
2D | SMLM-Challenge/Challenge2016 | Tools/CramerRao/main_auto_run.m | .m | 3,867 | 140 | %Cramer-Rao bounds
clear
modality_set = {'BP','AS','DH','2D'};
Nmod = length(modality_set);
dir_name = '~/Documents/SMLM/analysis/psf/';%'~/Downloads/PSF GL 200x200x151.tif';%
Nz = 151;
%%0
for l = 1%:Nmod
modality = modality_set{l};
[PSF,summedPSF,Nx,Ny] = load_PSF(dir_name,modality,Nz);
%% Fit cubic spline from 3D psf
fprintf('Starting %s\n',modality);
%[Nx,Ny,Nz] = size(PSF);
d = [3*ones(1,3),0,0,0];%degree of Bsplines
dx = 10;%nm
dy = 10;%nm
dz = 10;%nm
x = (1-Nx/2:Nx/2)*dx; y = (1-Ny/2:Ny/2)*dy; z = (1-Nz/2:Nz/2)*dz;
%%
tic
%c = PSF;
c = computeCubicSplineCoefs(PSF);
%c = spm_bsplinc(PSF,d);
toc
%% Get CramerRao bounds
cam_pix = 100;%nm
delta = [dx,dy,dz];
stack = repmat(struct('CRLB',[],'I',[],'cam_coef',[],...
'nu',[],'deta',[]),151,1);
%parpool(4);
for k = 1:151
pos_mol = [0,0,k].*delta;%bounds : [-215,215] x [-215,215] x [0,150] .* step
glob_timer = tic;
[stack(k).I,stack(k).cam_coef,stack(k).nu,stack(k).deta]...
= computeCramerRao(c, delta, cam_pix, pos_mol);
toc(glob_timer)
CRLB = sqrt(diag(stack(k).I^(-1)));
stack(k).CRLB.x = CRLB(1);
stack(k).CRLB.y = CRLB(2);
stack(k).CRLB.z = CRLB(3);
stack(k).CRLB.photon = CRLB(4);
stack(k).CRLB.bg = CRLB(5);
end
stack = struct2table(stack);
stack.CRLB = struct2table(stack.CRLB);
save(sprintf('res_%s.mat',modality),'stack','modality');
end
%%
if false
%%
set(0,'DefaultTextInterpreter','LaTex');
lw = 2;
fs = 14;
z = -750:10:750;
clear h;
%close all;
load('res_AS.mat');
figure(1);
plot(z, stack.CRLB.x,'LineWidth',lw);hold on;
plot(z, stack.CRLB.y,'LineWidth',lw);
plot(z, stack.CRLB.z,'LineWidth',lw);
h(1) = gca;
legend('X','Y','Z');
title(sprintf('Modality : %s',modality),'FontSize',fs);
ylabel('CRLB [nm]','FontSize',fs);
xlabel('Axial position [nm]','FontSize',fs);
axis([z(1),z(end), 0, 80]);
saveas(gcf,sprintf('CRLB_%s',modality),'fig');
load('res_DH.mat');
figure(2);
plot(z, stack.CRLB.x,'LineWidth',lw);hold on;
plot(z, stack.CRLB.y,'LineWidth',lw);
plot(z, stack.CRLB.z,'LineWidth',lw);
h(2) = gca;
legend('X','Y','Z');
title(sprintf('Modality : %s',modality),'FontSize',fs);
ylabel('CRLB [nm]','FontSize',fs);
xlabel('Axial position [nm]','FontSize',fs);
axis([z(1),z(end), 0, 80]);
saveas(gcf,sprintf('CRLB_%s',modality),'fig');
%load('res_BP_bg_50.mat');
load('res_BP_bg_100.mat');
figure(3);
plot(z, stack.CRLB.x,'LineWidth',lw);hold on;
plot(z, stack.CRLB.y,'LineWidth',lw);
plot(z, stack.CRLB.z,'LineWidth',lw);
h(3) = gca;
legend('X','Y','Z');
title(sprintf('Modality : %s',modality),'FontSize',fs);
ylabel('CRLB [nm]','FontSize',fs);
xlabel('Axial position [nm]','FontSize',fs);
axis([z(1),z(end), 0, 80]);
saveas(gcf,sprintf('CRLB_BG_109_%s',modality),'fig');
%saveas(gcf,sprintf('CRLB_bg_54_%s',modality),'fig');
load('res_2D.mat');
figure(4);
plot(z, stack.CRLB.x,'LineWidth',lw);hold on;
plot(z, stack.CRLB.y,'LineWidth',lw);
plot(z, stack.CRLB.z,'LineWidth',lw);
h(4) = gca;
legend('X','Y','Z');
title(sprintf('Modality : %s',modality),'FontSize',fs);
ylabel('CRLB [nm]','FontSize',fs);
xlabel('Axial position [nm]','FontSize',fs);
axis([z(1),z(end), 0, 80]);
saveas(gcf,sprintf('CRLB_%s',modality),'fig');
linkaxes(h,'xy');
%% Check min(nu(:)),max
stats_nu = table(cell(Nmod,1),ones(Nmod,1),ones(Nmod,1),ones(Nmod,1),ones(Nmod,1),...
'VariableNames',{'modality','imin','min','imax','max'});
for kk = 1:length(modality_set)
load(sprintf('res_%s.mat', modality_set{kk}));
stats_nu.modality{kk} = strrep(modality_set{kk},'2D','twodim');
[stats_nu.min(kk),stats_nu.imin(kk)] = min(cellfun(@(x) min(x), stack.nu));
[stats_nu.max(kk), stats_nu.imax(kk)] = max(cellfun(@(x) max(x), stack.nu));
end
%%
%%
end | MATLAB |
2D | SMLM-Challenge/Challenge2016 | Tools/CramerRao/computeSplineBasis4.m | .m | 259 | 7 | function x = computeSplineBasis4(x)
x = 1/48*((x - 5/2).^4.*(-sign(x - 5/2)) + 5*(x - 3/2).^4.*sign(x - 3/2)...
- 10*(x - 1/2).^4.*sign(x - 1/2) + 10*(x + 1/2).^4.*sign(x + 1/2) ...
- 5*(x + 3/2).^4.*sign(x + 3/2) + (x + 5/2).^4.*sign(x + 5/2));
end | MATLAB |
2D | SMLM-Challenge/Challenge2016 | Tools/wobble_correction/generateWobbleStandalone.m | .m | 25 | 2 | mcc -mv wobble_correct.m
| MATLAB |
2D | SMLM-Challenge/Challenge2016 | Tools/wobble_correction/wobble_correct.m | .m | 39,024 | 1,267 | function varargout = wobble_correct(varargin)
% WOBBLE_CORRECT MATLAB code for wobble_correct.fig
% WOBBLE_CORRECT, by itself, creates a new WOBBLE_CORRECT or raises the existing
% singleton*.
%
% H = WOBBLE_CORRECT returns the handle to a new WOBBLE_CORRECT or the handle to
% the existing singleton*.
%
% WOBBLE_CORRECT('CALLBACK',hObject,eventData,handles,...) calls the local
% function named CALLBACK in WOBBLE_CORRECT.M with the given input arguments.
%
% WOBBLE_CORRECT('Property','Value',...) creates a new WOBBLE_CORRECT or raises the
% existing singleton*. Starting from the left, property value pairs are
% applied to the GUI before wobble_correct_OpeningFcn gets called. An
% unrecognized property name or invalid value makes property application
% stop. All inputs are passed to wobble_correct_OpeningFcn via varargin.
%
% *See GUI Options on GUIDE's Tools menu. Choose "GUI allows only one
% instance to run (singleton)".
%
% See also: GUIDE, GUIDATA, GUIHANDLES
% Edit the above text to modify the response to help wobble_correct
% Last Modified by GUIDE v2.5 12-Jun-2016 12:29:36
% Begin initialization code - DO NOT EDIT
gui_Singleton = 1;
gui_State = struct('gui_Name', mfilename, ...
'gui_Singleton', gui_Singleton, ...
'gui_OpeningFcn', @wobble_correct_OpeningFcn, ...
'gui_OutputFcn', @wobble_correct_OutputFcn, ...
'gui_LayoutFcn', [] , ...
'gui_Callback', []);
if nargin && ischar(varargin{1})
gui_State.gui_Callback = str2func(varargin{1});
end
if nargout
[varargout{1:nargout}] = gui_mainfcn(gui_State, varargin{:});
else
gui_mainfcn(gui_State, varargin{:});
end
% End initialization code - DO NOT EDIT
% --- Executes just before wobble_correct is made visible.
function wobble_correct_OpeningFcn(hObject, eventdata, handles, varargin)
% This function has no output args, see OutputFcn.
% hObject handle to figure
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% varargin command line arguments to wobble_correct (see VARARGIN)
% Choose default command line output for wobble_correct
handles.output = hObject;
% Update handles structure
guidata(hObject, handles);
% UIWAIT makes wobble_correct wait for user response (see UIRESUME)
% uiwait(handles.figure1);
% --- Outputs from this function are returned to the command line.
function varargout = wobble_correct_OutputFcn(hObject, eventdata, handles)
% varargout cell array for returning output args (see VARARGOUT);
% hObject handle to figure
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Get default command line output from handles structure
varargout{1} = handles.output;
% --- Executes on button press in pushbutton1.
function pushbutton1_Callback(hObject, eventdata, handles)
% hObject handle to pushbutton1 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% select localization file
[fname, fpath] = uigetfile('*.*');
fullname = fullfile(fpath,fname);
set(handles.text5,'String',fullname);
% --- Executes on button press in pushbutton2.
function pushbutton2_Callback(hObject, eventdata, handles)
% hObject handle to pushbutton2 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% select ground truth file
[fname, fpath] = uigetfile('*.csv');
fullname = fullfile(fpath,fname);
set(handles.text6,'String', fullname);
function edit1_Callback(hObject, eventdata, handles)
% hObject handle to edit1 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Hints: get(hObject,'String') returns contents of edit1 as text
% str2double(get(hObject,'String')) returns contents of edit1 as a double
%if ~exist(get(hObject,'String'),'dir')
% mkdir(get(hObject,'String'));
%end
% --- Executes during object creation, after setting all properties.
function edit1_CreateFcn(hObject, eventdata, handles)
% hObject handle to edit1 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles empty - handles not created until after all CreateFcns called
% Hint: edit controls usually have a white background on Windows.
% See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
set(hObject,'BackgroundColor','white');
end
% --- Executes on button press in pushbutton3.
function pushbutton3_Callback(hObject, eventdata, handles)
% hObject handle to pushbutton3 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
foldpath = uigetdir(pwd,'Select a folder to store the output file');
set(handles.edit1,'String', foldpath);
% --- Executes on button press in pushbutton4.
function pushbutton4_Callback(hObject, eventdata, handles)
% hObject handle to pushbutton4 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
fullnameLoc = get(handles.text5,'String');
%hasHeader = fgetl(fopen(fullnameLoc));
%hasHeader = 1*(sum(isstrprop(hasHeader,'digit'))/length(hasHeader) < .6);
%localData = csvread(fullnameLoc, hasHeader, 0);
%SH: switched to importdata tool and defined columns to make more general
localData =importdata(fullnameLoc);
if isstruct(localData)
%strip the header
localData = localData.data;
end
xCol = str2num(get(handles.edit_x,'String'));
yCol = str2num(get(handles.editY,'String'));
frCol = str2num(get(handles.editFr,'String'));
fullnameGT = get(handles.text6,'String');
%assumes GT file is as defined in competition
%CSV file. X col 3, y col 4.
gtData = importdata(fullnameGT);
XCOLGT =3;
YCOLGT =4;
gtAll = gtData(:,[XCOLGT,YCOLGT]);
gt = unique(gtAll,'rows');
frameIsOneIndexed = get(handles.radiobutton_is1indexed,'Value');
[pathstr,~,~] = fileparts(fullnameLoc);
output_path = pathstr;
xnm = localData(:,xCol);
ynm = localData(:,yCol);
frame = localData(:,frCol);
%might be set by the users in future updates
zmin = -750;zmax = 750;zstep = 10;%nm
roiRadius = 500;%nm
wobbleCorrectSimBead(xnm,ynm,frame, gt,zmin,zstep,zmax,roiRadius,frameIsOneIndexed,output_path)
% --- Executes on button press in pushbutton5.
function pushbutton5_Callback(hObject, eventdata, handles)
% hObject handle to pushbutton5 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
function edit_x_Callback(hObject, eventdata, handles)
% hObject handle to edit_x (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Hints: get(hObject,'String') returns contents of edit_x as text
% str2double(get(hObject,'String')) returns contents of edit_x as a double
% --- Executes during object creation, after setting all properties.
function edit_x_CreateFcn(hObject, eventdata, handles)
% hObject handle to edit_x (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles empty - handles not created until after all CreateFcns called
% Hint: edit controls usually have a white background on Windows.
% See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
set(hObject,'BackgroundColor','white');
end
function editY_Callback(hObject, eventdata, handles)
% hObject handle to editY (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Hints: get(hObject,'String') returns contents of editY as text
% str2double(get(hObject,'String')) returns contents of editY as a double
% --- Executes during object creation, after setting all properties.
function editY_CreateFcn(hObject, eventdata, handles)
% hObject handle to editY (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles empty - handles not created until after all CreateFcns called
% Hint: edit controls usually have a white background on Windows.
% See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
set(hObject,'BackgroundColor','white');
end
function editFr_Callback(hObject, eventdata, handles)
% hObject handle to editFr (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Hints: get(hObject,'String') returns contents of editFr as text
% str2double(get(hObject,'String')) returns contents of editFr as a double
% --- Executes during object creation, after setting all properties.
function editFr_CreateFcn(hObject, eventdata, handles)
% hObject handle to editFr (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles empty - handles not created until after all CreateFcns called
% Hint: edit controls usually have a white background on Windows.
% See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
set(hObject,'BackgroundColor','white');
end
%-------------------------------------------------------
function wobbleCorrectSimBead(xnm,ynm,frame,gt,zmin,zstep,zmax,roiRadius,frameIsOneIndexed,output_path)
nBead = size(gt,1);
for ii = 1:nBead
beadPos = gt(ii,:);
ROInm(ii,1:2) = beadPos-roiRadius;%xmin ymin
ROInm(ii,3:4) = 2*roiRadius;%width height
end
zSlice = zmin:zstep:zmax;
%frameIsOneIndexed = ~sum(frame==0) > 0;%should detect it automatically
if ~frameIsOneIndexed
frame = frame+1;%have to account for possilbe zero-indexing or everthing will get screwed up
end
znm = zSlice(frame)';
wobbleMatrix = wobbleCalibration(xnm, ynm, znm, nBead, 'ROI', ROInm, 'Zfit', zSlice, 'NumSplineBreak', 10,...
'GT', gt);
[~, indCorr] = unique(wobbleMatrix(:,1));
wobbleMatrixUnique = wobbleMatrix(indCorr,[2,3,1]);
%save in csv file, units : nm, column order : X Y Z
csvwrite(fullfile(output_path,'wobbleCorrectionData.csv'), wobbleMatrixUnique);
saveas(gcf,fullfile(output_path,'XY wobble result.fig'));
saveas(gcf,fullfile(output_path,'XY wobble result.png'));
%------------------------------------------------------------------------
function [wobbleMatrix] = wobbleCalibration(x,y,z,nBead,varargin)
% WOBBLECALIBRATION Generate correction data for z-dependent "wobble"
%
% MODIFIED BY THANH-AN 24th May 2016
%
% SYNTAX
% [wobbleMatrix]=wobbleCalibration(x,y,z,nBead)
% [wobbleMatrix]=wobbleCalibration(..., 'SaveWobbleFile',wobbleFileName)
% [wobbleMatrix]=wobbleCalibration(..., 'ZLimit',zLim)
% [wobbleMatrix]=wobbleCalibration(..., 'NumSplineBreak',nBreak)
%
% INPUTS
% x,y,z: A dataset containing the observed localizations 'x,y' of beads at known position 'z'
% Usually generated by imaging fluorescent beads, stepped through z with a
% z-piezo stage. Normally, the exact same data used to generate an astigmatic
% 3D PSF width calibration is used.
% nBead: The number of 'good' (ie non-aggregated beads) in the image, which will
% be manually selected.
% OUTPUTS
% wobbleMatrix
% Lookup table containing a list of axial shifts
% as a function of Z, ie
% wobbleData = [Z1, xShift1, yShift1;...
% Z2, xShift2, yShift2;... etc]
% DESCRIPTION
% [wobbleMatrix]=wobbleCalibration(x,y,z,nBead)
% Plots the bead localizations and prompts the user to manually select 'nBead'
% regions within the image containing only localizations from a single bead.
% The xy-wobble is calculated as a function of z for each bead via spline fitting, and plotted.
% The combined xy-wobble is calculated via a second spline fit to exclude outliers usually arising
% from aggregated or overlapping beads.
% A wobble lookup table 'wobbleMatrix' is generated, which may be used for subsequent correction
% of 3D localization data.
%
% OPTIONS
% [wobbleMatrix]=wobbleCalibration(..., 'SaveWobbleFile',wobbleFileName)
% Save the 'wobbleMatrix' to a text file 'wobbleFileName'
% [wobbleMatrix]=wobbleCalibration(..., 'ZLimit',zLim)
% Only produce a wobble lookup table over specified limits
% zLim = [zMin zMax]. This is useful for excluding regions where fitting is unreliable
% because the beads have become too defocussed. Ie, bead calibration data is usually
% taken over a large Z range. This allows cropping to only the useful z-range
% [wobbleMatrix]=wobbleCalibration(..., 'NumSplineBreak',nBreak)
% Set the number of breaks 'nBreak' (default = 10) to use in the spline fit. If the resolution of the
% spline is insufficient compared to the underlying data, consider increasing 'nBreak'
% [wobbleMatrix]=wobbleCalibration(..., 'ROI',ROI)
% Provides the beads ROIs instead of the manual selection
% [wobbleMatrix]=wobbleCalibration(..., 'Zfit',zfit)
% Set the z-slice for which the XY correction are calculated (e.g.
% -750 nm to 750 nm every 10 nm.
% [wobbleMatrix]=wobbleCalibration(..., 'GT',gt)
% Calculate the xy-shift wrt the ground truth gt instead of the xy @z=0
% It doesn't matter if the beads positions are unordered wrt ROI
% EXAMPLE
% Generate a wobble correction lookup table for the test data supplied with these functions.
%
% The test data below ('bead 0.1um -1.5to1.5 20nm Z-step 3D cal.txt') shows fluorescent beads
% (Invitrogen 0.1um TetraSpeks), stepped in Z with a piezo stage and 2D localized with RapidSTORM
% in X,Y. Z was set to the known position of the piezo via RapidSTORM. This dataset can similarly
% be used to generate a PSF width 3D lookup table for astigmatic Z-localization (see the
% RapidSTORM 3.3 manual for further instructions on how to do this).
%
% Load the x,y,z data (this is the test data supplied with the
% wobble correction functions):
% fname = 'test data\bead 0.1um -1.5to1.5 20nm Z-step 3D cal.txt'
% a=importdata(fname);data=a.data;
% x = data(:,1); y=data(:,3);z=data(:,5);
% You also need to tell the progam how many good beads are in the image. Do this by loading
% up the localizations in your favorite PALM visualization software (eg PALMsiever
% https://github.com/PALMsiever/palm-siever), and counting how many good beads you have
% nBead = 7;
% Run the calibration, saving the output
% [wobbleMatrix]=wobbleCalibration(x,y,z,nBead,'SaveWobbleFile','Wobble-cal test.txt');
% A scatter plot of the XY localizations will appear, you will be prompted to select 'nBead'
% (here, 7) rectangular bead-containing regions.
% Once selected, a plot of XY-wobble vs z for each bead should be generated, together
% with combined fits for all beads.
% Note that the fit, and hence wobble correction, becomes unreliable once the beads go
% out of focus (here z<-750 and z>850). In practice, Z-localization in these regions is also
% unlikely to be feasible. Therefore, exclude these regions from the lookup table,
% either by manually editing the wobble file, or by re-running the calibration with:
% [wobbleMatrix]=wobbleCalibration(x,y,z,nBead, ...,
% 'SaveWobbleFile','Wobble-cal test.txt','ZLimit',[-750 850]);
% The advantage of rerunning the calibration like this is that the (default) 10 spline points
% are spread over a smaller range, giving higher resolution to the spline fit. Alternatively
% run the entire range with a higher number of spline points to begin with:
% [wobbleMatrix]=wobbleCalibration(x,y,z,nBead, ...,
% 'SaveWobbleFile','Wobble-cal test.txt','NumSplineBreak',20);
% and manually crop the text file later.
%
% The generated wobbleMatrix may now be used for wobble correction. See CORRECTWOBBLE documentation
% for details.
%
% This software is released under the GPL v3 (see license file 'gpl.txt'). It is provided AS-IS and no
% warranty is given.
%
% Author: Seamus Holden
% Last update: April 2015
narg = numel(varargin);
nBreak = 10;
zLim = [-Inf Inf];
ii=1;
%doSaveFile = false;
hasROI = false;
wobbleSaveName = [];
zfit = [];
gt = [];
while ii<=narg
if strcmp(varargin{ii},'NumSplineBreak')
nBreak= varargin{ii+1};
ii = ii+2;
elseif strcmp(varargin{ii},'ZLimit')
zLim= varargin{ii+1};
ii = ii+2;
elseif strcmp(varargin{ii},'SaveWobbleFile')
wobbleSaveName= varargin{ii+1};
ii = ii+2;
elseif strcmp(varargin{ii},'ROI')
hasROI = true;
ROI = varargin{ii+1};
ii = ii+2;
elseif strcmp(varargin{ii},'Zfit')
zfit = varargin{ii+1};
ii = ii + 2;
elseif strcmp(varargin{ii},'GT')
gt = varargin{ii+1};
ii = ii + 2;
else
ii = ii+1;
end
end
%Modified by Thanh-an Pham the 16th May 2016
if hasROI
for ii = 1:nBead
bead{ii} = [ROI(ii,1),ROI(ii,2),ROI(ii,3) + ROI(ii,1), ROI(ii,4) + ROI(ii,2)];
end
else
figure;
hF = scatter(x,y,25,z,'.');
set(gca,'YDir','reverse')
for ii = 1:nBead
hR{ii} = imrect(hF);
bead{ii} = getPosition(hR{ii});
bead{ii}(3) = bead{ii}(3) + bead{ii}(1);
bead{ii}(4) = bead{ii}(4) + bead{ii}(2);
end
end
% bead lim are [xmin, ymin, xmax, ymax]
[z,xWobble, yWobble] = xyWobble(x,y,z,bead,zLim,wobbleSaveName,nBreak,zfit,gt);
wobbleMatrix = [z(:),xWobble(:),yWobble(:)];
%---------------------------------------------------
function [zfit,xWobble, yWobble] = xyWobble(x,y,z,beadLim,zlim,fsavename,nBreak,zfit,gt)
WOBBLEWARNINGNM = 300;%warn if values greater than this
bead = beadLim;
n = numel(bead);
zAll = [];
gt_tmp = gt;
k=1;
for ii = 1:n
isBead = x>bead{ii}(1) & y>bead{ii}(2) & x<bead{ii}(3) & y<bead{ii}(4);
xBead{ii} = x(isBead);
yBead{ii} = y(isBead);
zBead{ii} = z(isBead);
%reorder ground truth
for jj = 1:n
if ~isempty(gt_tmp) &&...
gt_tmp(jj,1) > bead{ii}(1) && gt_tmp(jj,2) > bead{ii}(2) &&...
gt_tmp(jj,1) < bead{ii}(3) && gt_tmp(jj,2) < bead{ii}(4)
gt(ii,:) = gt_tmp(jj,:);
end
end
zAll = [zAll;z(isBead)];
end
isOk = zAll>zlim(1)&zAll<zlim(2);
zRangeSet = zAll(isOk);
%Modified by Thanh-an Pham 16.05.2016
if isempty(zfit)
zfit = min(zRangeSet): (max(zRangeSet)-min(zRangeSet))/nBreak:max(zRangeSet);
%zfit = -750:10:750;
end
for ii =1:n
xWobble = fit1Spline(xBead{ii},zBead{ii},zfit,nBreak);
yWobble = fit1Spline(yBead{ii},zBead{ii},zfit,nBreak);
beadFit{ii} = [zfit(:), xWobble(:),yWobble(:)];
end
if isempty(gt)
%find the zfit point nearest to zero, align everything on this
[~, idx] =min(abs(zfit));
for ii =1:n
%shift x
beadFit{ii}(:,2) = beadFit{ii}(:,2) - beadFit{ii}(idx,2);
%shift y
beadFit{ii}(:,3) = beadFit{ii}(:,3) - beadFit{ii}(idx,3);
end
else
%use the ground truth gt for xy for each z
for ii = 1:n
%shift x
beadFit{ii}(:,2) = beadFit{ii}(:,2) - gt(ii,1);
%shift y
beadFit{ii}(:,3) = beadFit{ii}(:,3) - gt(ii,2);
end
end
%combine all the spline fits, one more spline fit to generate the final data
z=[];x=[];y=[];
for ii =1:n
z= [z;beadFit{ii}(:,1)];
x= [x;beadFit{ii}(:,2)];
y= [y;beadFit{ii}(:,3)];
end
xWobble = fit1Spline(x,z,zfit,nBreak);
yWobble = fit1Spline(y,z,zfit,nBreak);
%plot
figure;hold all
plot(zfit,xWobble,'r');
plot(zfit,yWobble,'b');
for ii = 1:n
plot(beadFit{ii}(:,1),beadFit{ii}(:,2),'k');
plot(beadFit{ii}(:,1),beadFit{ii}(:,3),'g');
end
legend('X, combined fit','Y, combined fit', 'X, single bead fit', 'Y, single bead fit');
xlabel('Z (nm)');
ylabel('XY wobble (nm)')
%saveas(gcf,'XY wobble result.fig');
%saveas(gcf,'XY wobble result.png');
calData = [zfit(:), xWobble(:),yWobble(:)];
if ~isempty(fsavename)
dlmwrite(fsavename, calData,' ');
end
if any([xWobble(:);yWobble]>=WOBBLEWARNINGNM)
warning(['Wobble correction values > ', num2str(WOBBLEWARNINGNM),' nm detected, please check the input data for errors.']);
end
%-----------------------------------------
function [xfit] = fit1Spline(x,t,tfit,nBreak)
%fit with splinefit
ppX=splinefit(t,x,nBreak,'r');
xfit = ppval(ppX,tfit);
%-----------------------------------------
function pp = splinefit(varargin)
%SPLINEFIT Fit a spline to noisy data.
% PP = SPLINEFIT(X,Y,BREAKS) fits a piecewise cubic spline with breaks
% (knots) BREAKS to the noisy data (X,Y). X is a vector and Y is a vector
% or an ND array. If Y is an ND array, then X(j) and Y(:,...,:,j) are
% matched. Use PPVAL to evaluate PP.
%
% PP = SPLINEFIT(X,Y,P) where P is a positive integer interpolates the
% breaks linearly from the sorted locations of X. P is the number of
% spline pieces and P+1 is the number of breaks.
%
% OPTIONAL INPUT
% Argument places 4 to 8 are reserved for optional input.
% These optional arguments can be given in any order:
%
% PP = SPLINEFIT(...,'p') applies periodic boundary conditions to
% the spline. The period length is MAX(BREAKS)-MIN(BREAKS).
%
% PP = SPLINEFIT(...,'r') uses robust fitting to reduce the influence
% from outlying data points. Three iterations of weighted least squares
% are performed. Weights are computed from previous residuals.
%
% PP = SPLINEFIT(...,BETA), where 0 < BETA < 1, sets the robust fitting
% parameter BETA and activates robust fitting ('r' can be omitted).
% Default is BETA = 1/2. BETA close to 0 gives all data equal weighting.
% Increase BETA to reduce the influence from outlying data. BETA close
% to 1 may cause instability or rank deficiency.
%
% PP = SPLINEFIT(...,N) sets the spline order to N. Default is a cubic
% spline with order N = 4. A spline with P pieces has P+N-1 degrees of
% freedom. With periodic boundary conditions the degrees of freedom are
% reduced to P.
%
% PP = SPLINEFIT(...,CON) applies linear constraints to the spline.
% CON is a structure with fields 'xc', 'yc' and 'cc':
% 'xc', x-locations (vector)
% 'yc', y-values (vector or ND array)
% 'cc', coefficients (matrix).
%
% Constraints are linear combinations of derivatives of order 0 to N-2
% according to
%
% cc(1,j)*y(x) + cc(2,j)*y'(x) + ... = yc(:,...,:,j), x = xc(j).
%
% The maximum number of rows for 'cc' is N-1. If omitted or empty 'cc'
% defaults to a single row of ones. Default for 'yc' is a zero array.
%
% EXAMPLES
%
% % Noisy data
% x = linspace(0,2*pi,100);
% y = sin(x) + 0.1*randn(size(x));
% % Breaks
% breaks = [0:5,2*pi];
%
% % Fit a spline of order 5
% pp = splinefit(x,y,breaks,5);
%
% % Fit a spline of order 3 with periodic boundary conditions
% pp = splinefit(x,y,breaks,3,'p');
%
% % Constraints: y(0) = 0, y'(0) = 1 and y(3) + y"(3) = 0
% xc = [0 0 3];
% yc = [0 1 0];
% cc = [1 0 1; 0 1 0; 0 0 1];
% con = struct('xc',xc,'yc',yc,'cc',cc);
%
% % Fit a cubic spline with 8 pieces and constraints
% pp = splinefit(x,y,8,con);
%
% % Fit a spline of order 6 with constraints and periodicity
% pp = splinefit(x,y,breaks,con,6,'p');
%
% See also SPLINE, PPVAL, PPDIFF, PPINT
% Author: Jonas Lundgren <splinefit@gmail.com> 2010
% 2009-05-06 Original SPLINEFIT.
% 2010-06-23 New version of SPLINEFIT based on B-splines.
% 2010-09-01 Robust fitting scheme added.
% 2010-09-01 Support for data containing NaNs.
% 2011-07-01 Robust fitting parameter added.
% Check number of arguments
error(nargchk(3,7,nargin));
% Check arguments
[x,y,dim,breaks,n,periodic,beta,constr] = arguments(varargin{:});
% Evaluate B-splines
base = splinebase(breaks,n);
pieces = base.pieces;
A = ppval(base,x);
% Bin data
[junk,ibin] = histc(x,[-inf,breaks(2:end-1),inf]); %#ok
% Sparse system matrix
mx = numel(x);
ii = [ibin; ones(n-1,mx)];
ii = cumsum(ii,1);
jj = repmat(1:mx,n,1);
if periodic
ii = mod(ii-1,pieces) + 1;
A = sparse(ii,jj,A,pieces,mx);
else
A = sparse(ii,jj,A,pieces+n-1,mx);
end
% Don't use the sparse solver for small problems
if pieces < 20*n/log(1.7*n)
A = full(A);
end
% Solve
if isempty(constr)
% Solve Min norm(u*A-y)
u = lsqsolve(A,y,beta);
else
% Evaluate constraints
B = evalcon(base,constr,periodic);
% Solve constraints
[Z,u0] = solvecon(B,constr);
% Solve Min norm(u*A-y), subject to u*B = yc
y = y - u0*A;
A = Z*A;
v = lsqsolve(A,y,beta);
u = u0 + v*Z;
end
% Periodic expansion of solution
if periodic
jj = mod(0:pieces+n-2,pieces) + 1;
u = u(:,jj);
end
% Compute polynomial coefficients
ii = [repmat(1:pieces,1,n); ones(n-1,n*pieces)];
ii = cumsum(ii,1);
jj = repmat(1:n*pieces,n,1);
C = sparse(ii,jj,base.coefs,pieces+n-1,n*pieces);
coefs = u*C;
coefs = reshape(coefs,[],n);
% Make piecewise polynomial
pp = mkpp(breaks,coefs,dim);
%--------------------------------------------------------------------------
function [x,y,dim,breaks,n,periodic,beta,constr] = arguments(varargin)
%ARGUMENTS Lengthy input checking
% x Noisy data x-locations (1 x mx)
% y Noisy data y-values (prod(dim) x mx)
% dim Leading dimensions of y
% breaks Breaks (1 x (pieces+1))
% n Spline order
% periodic True if periodic boundary conditions
% beta Robust fitting parameter, no robust fitting if beta = 0
% constr Constraint structure
% constr.xc x-locations (1 x nx)
% constr.yc y-values (prod(dim) x nx)
% constr.cc Coefficients (?? x nx)
% Reshape x-data
x = varargin{1};
mx = numel(x);
x = reshape(x,1,mx);
% Remove trailing singleton dimensions from y
y = varargin{2};
dim = size(y);
while numel(dim) > 1 && dim(end) == 1
dim(end) = [];
end
my = dim(end);
% Leading dimensions of y
if numel(dim) > 1
dim(end) = [];
else
dim = 1;
end
% Reshape y-data
pdim = prod(dim);
y = reshape(y,pdim,my);
% Check data size
if mx ~= my
mess = 'Last dimension of array y must equal length of vector x.';
error('arguments:datasize',mess)
end
% Treat NaNs in x-data
inan = find(isnan(x));
if ~isempty(inan)
x(inan) = [];
y(:,inan) = [];
mess = 'All data points with NaN as x-location will be ignored.';
warning('arguments:nanx',mess)
end
% Treat NaNs in y-data
inan = find(any(isnan(y),1));
if ~isempty(inan)
x(inan) = [];
y(:,inan) = [];
mess = 'All data points with NaN in their y-value will be ignored.';
warning('arguments:nany',mess)
end
% Check number of data points
mx = numel(x);
if mx == 0
error('arguments:nodata','There must be at least one data point.')
end
% Sort data
if any(diff(x) < 0)
[x,isort] = sort(x);
y = y(:,isort);
end
% Breaks
if isscalar(varargin{3})
% Number of pieces
p = varargin{3};
if ~isreal(p) || ~isfinite(p) || p < 1 || fix(p) < p
mess = 'Argument #3 must be a vector or a positive integer.';
error('arguments:breaks1',mess)
end
if x(1) < x(end)
% Interpolate breaks linearly from x-data
dx = diff(x);
ibreaks = linspace(1,mx,p+1);
[junk,ibin] = histc(ibreaks,[0,2:mx-1,mx+1]); %#ok
breaks = x(ibin) + dx(ibin).*(ibreaks-ibin);
else
breaks = x(1) + linspace(0,1,p+1);
end
else
% Vector of breaks
breaks = reshape(varargin{3},1,[]);
if isempty(breaks) || min(breaks) == max(breaks)
mess = 'At least two unique breaks are required.';
error('arguments:breaks2',mess);
end
end
% Unique breaks
if any(diff(breaks) <= 0)
breaks = unique(breaks);
end
% Optional input defaults
n = 4; % Cubic splines
periodic = false; % No periodic boundaries
robust = false; % No robust fitting scheme
beta = 0.5; % Robust fitting parameter
constr = []; % No constraints
% Loop over optional arguments
for k = 4:nargin
a = varargin{k};
if ischar(a) && isscalar(a) && lower(a) == 'p'
% Periodic conditions
periodic = true;
elseif ischar(a) && isscalar(a) && lower(a) == 'r'
% Robust fitting scheme
robust = true;
elseif isreal(a) && isscalar(a) && isfinite(a) && a > 0 && a < 1
% Robust fitting parameter
beta = a;
robust = true;
elseif isreal(a) && isscalar(a) && isfinite(a) && a > 0 && fix(a) == a
% Spline order
n = a;
elseif isstruct(a) && isscalar(a)
% Constraint structure
constr = a;
else
error('arguments:nonsense','Failed to interpret argument #%d.',k)
end
end
% No robust fitting
if ~robust
beta = 0;
end
% Check exterior data
h = diff(breaks);
xlim1 = breaks(1) - 0.01*h(1);
xlim2 = breaks(end) + 0.01*h(end);
if x(1) < xlim1 || x(end) > xlim2
if periodic
% Move data inside domain
P = breaks(end) - breaks(1);
x = mod(x-breaks(1),P) + breaks(1);
% Sort
[x,isort] = sort(x);
y = y(:,isort);
else
mess = 'Some data points are outside the spline domain.';
warning('arguments:exteriordata',mess)
end
end
% Return
if isempty(constr)
return
end
% Unpack constraints
xc = [];
yc = [];
cc = [];
names = fieldnames(constr);
for k = 1:numel(names)
switch names{k}
case {'xc'}
xc = constr.xc;
case {'yc'}
yc = constr.yc;
case {'cc'}
cc = constr.cc;
otherwise
mess = 'Unknown field ''%s'' in constraint structure.';
warning('arguments:unknownfield',mess,names{k})
end
end
% Check xc
if isempty(xc)
mess = 'Constraints contains no x-locations.';
error('arguments:emptyxc',mess)
else
nx = numel(xc);
xc = reshape(xc,1,nx);
end
% Check yc
if isempty(yc)
% Zero array
yc = zeros(pdim,nx);
elseif numel(yc) == 1
% Constant array
yc = zeros(pdim,nx) + yc;
elseif numel(yc) ~= pdim*nx
% Malformed array
error('arguments:ycsize','Cannot reshape yc to size %dx%d.',pdim,nx)
else
% Reshape array
yc = reshape(yc,pdim,nx);
end
% Check cc
if isempty(cc)
cc = ones(size(xc));
elseif numel(size(cc)) ~= 2
error('arguments:ccsize1','Constraint coefficients cc must be 2D.')
elseif size(cc,2) ~= nx
mess = 'Last dimension of cc must equal length of xc.';
error('arguments:ccsize2',mess)
end
% Check high order derivatives
if size(cc,1) >= n
if any(any(cc(n:end,:)))
mess = 'Constraints involve derivatives of order %d or larger.';
error('arguments:difforder',mess,n-1)
end
cc = cc(1:n-1,:);
end
% Check exterior constraints
if min(xc) < xlim1 || max(xc) > xlim2
if periodic
% Move constraints inside domain
P = breaks(end) - breaks(1);
xc = mod(xc-breaks(1),P) + breaks(1);
else
mess = 'Some constraints are outside the spline domain.';
warning('arguments:exteriorconstr',mess)
end
end
% Pack constraints
constr = struct('xc',xc,'yc',yc,'cc',cc);
%--------------------------------------------------------------------------
function pp = splinebase(breaks,n)
%SPLINEBASE Generate B-spline base PP of order N for breaks BREAKS
breaks = breaks(:); % Breaks
breaks0 = breaks'; % Initial breaks
h = diff(breaks); % Spacing
pieces = numel(h); % Number of pieces
deg = n - 1; % Polynomial degree
% Extend breaks periodically
if deg > 0
if deg <= pieces
hcopy = h;
else
hcopy = repmat(h,ceil(deg/pieces),1);
end
% to the left
hl = hcopy(end:-1:end-deg+1);
bl = breaks(1) - cumsum(hl);
% and to the right
hr = hcopy(1:deg);
br = breaks(end) + cumsum(hr);
% Add breaks
breaks = [bl(deg:-1:1); breaks; br];
h = diff(breaks);
pieces = numel(h);
end
% Initiate polynomial coefficients
coefs = zeros(n*pieces,n);
coefs(1:n:end,1) = 1;
% Expand h
ii = [1:pieces; ones(deg,pieces)];
ii = cumsum(ii,1);
ii = min(ii,pieces);
H = h(ii(:));
% Recursive generation of B-splines
for k = 2:n
% Antiderivatives of splines
for j = 1:k-1
coefs(:,j) = coefs(:,j).*H/(k-j);
end
Q = sum(coefs,2);
Q = reshape(Q,n,pieces);
Q = cumsum(Q,1);
c0 = [zeros(1,pieces); Q(1:deg,:)];
coefs(:,k) = c0(:);
% Normalize antiderivatives by max value
fmax = repmat(Q(n,:),n,1);
fmax = fmax(:);
for j = 1:k
coefs(:,j) = coefs(:,j)./fmax;
end
% Diff of adjacent antiderivatives
coefs(1:end-deg,1:k) = coefs(1:end-deg,1:k) - coefs(n:end,1:k);
coefs(1:n:end,k) = 0;
end
% Scale coefficients
scale = ones(size(H));
for k = 1:n-1
scale = scale./H;
coefs(:,n-k) = scale.*coefs(:,n-k);
end
% Reduce number of pieces
pieces = pieces - 2*deg;
% Sort coefficients by interval number
ii = [n*(1:pieces); deg*ones(deg,pieces)];
ii = cumsum(ii,1);
coefs = coefs(ii(:),:);
% Make piecewise polynomial
pp = mkpp(breaks0,coefs,n);
%--------------------------------------------------------------------------
function B = evalcon(base,constr,periodic)
%EVALCON Evaluate linear constraints
% Unpack structures
breaks = base.breaks;
pieces = base.pieces;
n = base.order;
xc = constr.xc;
cc = constr.cc;
% Bin data
[junk,ibin] = histc(xc,[-inf,breaks(2:end-1),inf]); %#ok
% Evaluate constraints
nx = numel(xc);
B0 = zeros(n,nx);
for k = 1:size(cc,1)
if any(cc(k,:))
B0 = B0 + repmat(cc(k,:),n,1).*ppval(base,xc);
end
% Differentiate base
coefs = base.coefs(:,1:n-k);
for j = 1:n-k-1
coefs(:,j) = (n-k-j+1)*coefs(:,j);
end
base.coefs = coefs;
base.order = n-k;
end
% Sparse output
ii = [ibin; ones(n-1,nx)];
ii = cumsum(ii,1);
jj = repmat(1:nx,n,1);
if periodic
ii = mod(ii-1,pieces) + 1;
B = sparse(ii,jj,B0,pieces,nx);
else
B = sparse(ii,jj,B0,pieces+n-1,nx);
end
%--------------------------------------------------------------------------
function [Z,u0] = solvecon(B,constr)
%SOLVECON Find a particular solution u0 and null space Z (Z*B = 0)
% for constraint equation u*B = yc.
yc = constr.yc;
tol = 1000*eps;
% Remove blank rows
ii = any(B,2);
B2 = full(B(ii,:));
% Null space of B2
if isempty(B2)
Z2 = [];
else
% QR decomposition with column permutation
[Q,R,dummy] = qr(B2); %#ok
R = abs(R);
jj = all(R < R(1)*tol, 2);
Z2 = Q(:,jj)';
end
% Sizes
[m,ncon] = size(B);
m2 = size(B2,1);
nz = size(Z2,1);
% Sparse null space of B
Z = sparse(nz+1:nz+m-m2,find(~ii),1,nz+m-m2,m);
Z(1:nz,ii) = Z2;
% Warning rank deficient
if nz + ncon > m2
mess = 'Rank deficient constraints, rank = %d.';
warning('solvecon:deficient',mess,m2-nz);
end
% Particular solution
u0 = zeros(size(yc,1),m);
if any(yc(:))
% Non-homogeneous case
u0(:,ii) = yc/B2;
% Check solution
if norm(u0*B - yc,'fro') > norm(yc,'fro')*tol
mess = 'Inconsistent constraints. No solution within tolerance.';
error('solvecon:inconsistent',mess)
end
end
%--------------------------------------------------------------------------
function u = lsqsolve(A,y,beta)
%LSQSOLVE Solve Min norm(u*A-y)
% Avoid sparse-complex limitations
if issparse(A) && ~isreal(y)
A = full(A);
end
% Solution
u = y/A;
% Robust fitting
if beta > 0
[m,n] = size(y);
alpha = 0.5*beta/(1-beta)/m;
for k = 1:3
% Residual
r = u*A - y;
rr = r.*conj(r);
rrmean = sum(rr,2)/n;
rrmean(~rrmean) = 1;
rrhat = (alpha./rrmean)'*rr;
% Weights
w = exp(-rrhat);
spw = spdiags(w',0,n,n);
% Solve weighted problem
u = (y*spw)/(A*spw);
end
end
%-----------------------------------------
function qq = ppdiff(pp,j)
%PPDIFF Differentiate piecewise polynomial.
% QQ = PPDIFF(PP,J) returns the J:th derivative of a piecewise
% polynomial PP. PP must be on the form evaluated by PPVAL. QQ is a
% piecewise polynomial on the same form. Default value for J is 1.
%
% Example:
% x = linspace(-pi,pi,9);
% y = sin(x);
% pp = spline(x,y);
% qq = ppdiff(pp);
% xx = linspace(-pi,pi,201);
% plot(xx,cos(xx),'b',xx,ppval(qq,xx),'r')
%
% See also PPVAL, SPLINE, SPLINEFIT, PPINT
% Author: Jonas Lundgren <splinefit@gmail.com> 2009
if nargin < 1, help ppdiff, return, end
if nargin < 2, j = 1; end
% Check diff order
if ~isreal(j) || mod(j,1) || j < 0
msgid = 'PPDIFF:DiffOrder';
message = 'Order of derivative must be a non-negative integer!';
error(msgid,message)
end
% Get coefficients
coefs = pp.coefs;
[m n] = size(coefs);
if j == 0
% Do nothing
elseif j < n
% Derivative of order J
D = [n-j:-1:1; ones(j-1,n-j)];
D = cumsum(D,1);
D = prod(D,1);
coefs = coefs(:,1:n-j);
for k = 1:n-j
coefs(:,k) = D(k)*coefs(:,k);
end
else
% Derivative kills PP
coefs = zeros(m,1);
end
% Set output
qq = pp;
qq.coefs = coefs;
qq.order = size(coefs,2);
%-----------------------------------------
function output = ppint(pp,a,b)
%PPINT Integrate piecewise polynomial.
% QQ = PPINT(PP,A) returns the indefinite integral from A to X of a
% piecewise polynomial PP. PP must be on the form evaluated by PPVAL.
% QQ is a piecewise polynomial on the same form. Default value for A is
% the leftmost break of PP.
%
% I = PPINT(PP,A,B) returns the definite integral from A to B.
%
% Example:
% x = linspace(-pi,pi,7);
% y = sin(x);
% pp = spline(x,y);
% I = ppint(pp,0,pi)
%
% qq = ppint(pp,pi/2);
% xx = linspace(-pi,pi,201);
% plot(xx,-cos(xx),xx,ppval(qq,xx),'r')
%
% See also PPVAL, SPLINE, SPLINEFIT, PPDIFF
% Author: Jonas Lundgren <splinefit@gmail.com> 2009
if nargin < 1, help ppint, return, end
if nargin < 2, a = pp.breaks(1); end
% Get coefficients and breaks
coefs = pp.coefs;
[m n] = size(coefs);
xb = pp.breaks;
pdim = prod(pp.dim);
% Interval lengths
hb = diff(xb);
hb = repmat(hb,pdim,1);
hb = hb(:);
% Integration
coefs(:,1) = coefs(:,1)/n;
y = coefs(:,1).*hb;
for k = 2:n
coefs(:,k) = coefs(:,k)/(n-k+1);
y = (y + coefs(:,k)).*hb;
end
y = reshape(y,pdim,[]);
I = cumsum(y,2);
I = I(:);
coefs(:,n+1) = [zeros(pdim,1); I(1:m-pdim)];
% Set preliminary indefinite integral
qq = pp;
qq.coefs = coefs;
qq.order = n+1;
% Set output
if nargin < 3
% Indefinite integral from a to x
if a ~= xb(1)
I0 = ppval(qq,a);
I0 = I0(:);
I0 = repmat(I0,m/pdim,1);
qq.coefs(:,n+1) = qq.coefs(:,n+1) - I0;
end
output = qq;
else
% Definite integral from a to b
output = ppval(qq,b) - ppval(qq,a);
end
%----------------------------------------- | MATLAB |
2D | SMLM-Challenge/Challenge2016 | Tools/FileConversionUtilities/tiffs_to_tiff.py | .py | 466 | 23 | #!/usr/bin/env python
#
# Convert a mess of tiff files into a single multi-page tiff file.
#
# Hazen 04/16
#
import glob
import sys
import tifffile
if (len(sys.argv) != 3):
print("usage: <tiff file> <tiff dir>")
exit()
tiff_files = sorted(glob.glob(sys.argv[2] + "*.tif"))
with tifffile.TiffWriter(sys.argv[1]) as tif:
for tiff_file in tiff_files:
print(tiff_file)
tiff_image = tifffile.imread(tiff_file)
tif.save(tiff_image)
| Python |
2D | SMLM-Challenge/Challenge2016 | Tools/pupil_functions/zernike.c | .c | 3,009 | 152 | /*
* C library for calculating Zernike polynomials.
* Has issues for polynomials where n >= 13?
*
* Hazen 10/14
*
* Compilation instructions:
*
* Linux:
* gcc -fPIC -g -c -Wall zernike.c
* gcc -shared -Wl,-soname,zernike.so.1 -o zernike.so.1.0.1 zernike.o -lc
* ln -s zernike.so.1.0.1 zernike.so
*
* Windows:
* gcc -c zernike.c
* gcc -shared -o zernike.dll zernike.o
*/
#include <math.h>
#include <stdlib.h>
#include <stdio.h>
int factorial(int);
double pre_fac(int, int, int);
double zernike(int, int, double, double);
void zernike_grid(double *, int, double, double, double, int, int);
double zernike_rad(int, int, double);
/*
* factorial()
*
* Calculate factorial of a integer.
*
* n - The input number.
*
* Returns n!
*/
int factorial(int n)
{
int i, n_fac;
n_fac = 1;
for(i=1;i<=n;i++){
n_fac = n_fac * i;
}
return n_fac;
}
/*
* pre_fac()
*
* Calculate factorial coefficient.
*
* m - zernike m value.
* n - zernike n value.
* k - index.
*
* Returns the factorial coefficient.
*/
double pre_fac(int m, int n, int k)
{
double d1, d2, d3, n1, sign;
sign = pow(-1.0, k);
n1 = (double)factorial(n-k);
d1 = (double)factorial(k);
d2 = (double)factorial((n+m)/2 - k);
d3 = (double)factorial((n-m)/2 - k);
return sign * n1/(d1 * d2 * d3);
}
/*
* zernike()
*
* Calculate the value of a zernike polynomial.
*
* m - zernike m value.
* n - zernike n value.
* rho - radius (0.0 - 1.0).
* phi - angle (in radians).
*
* Returns the zernike polynomial value.
*/
double zernike(int m, int n, double rho, double phi)
{
if (m > 0) return zernike_rad(m, n, rho) * cos(m * phi);
if (m < 0) return zernike_rad(-m, n, rho) * sin(-m * phi);
return zernike_rad(0, n, rho);
}
/*
* zernike_grid()
*
* Add zernike polynomial values to pre-defined grid.
*
* grid - pre-allocated & initialized double storage (square).
* gsize - size of the grid in x / y.
* gcenter - center point of the grid.
* radius - radius on which to calculate the polynomial.
* scale - scaling factor.
* m - zernike m value.
* n - zernike n value.
*/
void zernike_grid(double *grid, int gsize, double gcenter, double radius, double scale, int m, int n)
{
int i, j;
double dd, dx, dy, phi, rr;
rr = radius * radius;
for(i=0;i<gsize;i++){
dx = i - gcenter;
for(j=0;j<gsize;j++){
dy = j - gcenter;
dd = dx * dx + dy * dy;
if(dd <= rr){
dd = sqrt(dd)/radius;
phi = atan2(dy, dx);
grid[i*gsize+j] += scale * zernike(m, n, dd, phi);
}
}
}
}
/*
* zernike_rad()
*
* Calculate the radial component of a Zernike polynomial.
*
* m - m coefficient.
* n - n coefficient.
* rho - radius (0.0 - 1.0).
*
* Returns the radial value.
*/
double zernike_rad(int m, int n, double rho)
{
int k;
double sum;
if((n < 0) || (m < 0) || (abs(m) > n)) return 0.0;
if(((n-m)%2) == 1) return 0.0;
sum = 0.0;
for(k=0;k<((n-m)/2+1);k++){
sum += pre_fac(m, n, k) * pow(rho, (n - 2*k));
}
return sum;
}
| C |
2D | SMLM-Challenge/Challenge2016 | Tools/pupil_functions/pupil_math.py | .py | 8,308 | 241 | #!/usr/bin/python
#
# Some math for calculating PSFs from pupil functions.
#
# All units are in microns.
#
# Hazen 03/16
#
import math
import numpy
import scipy
import scipy.fftpack
import tifffile
import zernike_c as zernikeC
class Geometry(object):
## __init__
#
# @param size The number of pixels in the PSF image, assumed square.
# @param pixel_size The size of the camera pixel in um.
# @param wavelength The wavelength of the flourescence in um.
# @param imm_index The index of the immersion media.
# @param The numerical aperature of the objective.
#
def __init__(self, size, pixel_size, wavelength, imm_index, NA):
self.imm_index = float(imm_index)
self.NA = float(NA)
self.pixel_size = float(pixel_size)
self.size = int(size)
self.wavelength = float(wavelength)
self.k_max = NA/wavelength
dk = 1.0/(size * pixel_size)
self.r_max = self.k_max/dk
[x,y] = numpy.mgrid[ -size/2.0 : size/2.0, -size/2.0 : size/2.0] + 0.5
kx = dk * x
ky = dk * y
self.k = numpy.sqrt(kx*kx + ky*ky)
tmp = imm_index/wavelength
self.kz = numpy.lib.scimath.sqrt(tmp * tmp - self.k * self.k)
self.r = self.k/self.k_max
self.kz[(self.r > 1.0)] = 0.0
self.n_pixels = numpy.sum(self.r <= 1)
self.norm = math.sqrt(self.r.size)
## applyNARestriction
#
# @param pupil_fn The pupil function to restrict the NA of.
#
# @return The NA restricted pupil function.
#
def applyNARestriction(self, pupil_fn):
pupil_fn[(self.r > 1.0)] = 0.0
return pupil_fn
## changeFocus
#
# @param pupil_fn The pupil function.
# @param z_dist The distance to the new focal plane.
#
# @return The pupil function at the new focal plane.
#
def changeFocus(self, pupil_fn, z_dist):
return numpy.exp(1j * 2.0 * numpy.pi * self.kz * z_dist) * pupil_fn
## createPlaneWave
#
# @param n_photons The intensity of the pupil function.
#
# @return The pupil function for a plane wave.
#
def createPlaneWave(self, n_photons):
plane = numpy.sqrt(n_photons/self.n_pixels) * numpy.exp(1j * numpy.zeros(self.r.shape))
return self.applyNARestriction(plane)
## createFromZernike
#
# @param n_photons The intensity of the pupil function
# @param zernike_modes List of lists, [[magnitude (in radians), m, n], [..]]
#
# @return The pupil function for this combination of zernike modes.
#
def createFromZernike(self, n_photons, zernike_modes):
if (len(zernike_modes) == 0):
return self.createPlaneWave(n_photons)
else:
phases = numpy.zeros(self.r.shape)
for zmn in zernike_modes:
phases = zernikeC.zernikeGrid(phases, zmn[0], zmn[1], zmn[2], radius = self.r_max)
zmnpf = numpy.sqrt(n_photons/self.n_pixels) * numpy.exp(1j * phases)
return self.applyNARestriction(zmnpf)
## pfToPSF
#
# @param pf A pupil function.
# @param z_vals The z values (focal planes) of the desired PSF.
# @param want_intensity (Optional) Return intensity, default is True.
# @param scaling_factor (Optional) The OTF rescaling factor, default is None.
#
# @return The PSF that corresponds to pf at the requested z_vals.
#
def pfToPSF(self, pf, z_vals, want_intensity = True, scaling_factor = None):
if want_intensity:
psf = numpy.zeros((len(z_vals), pf.shape[0], pf.shape[1]))
for i, z in enumerate(z_vals):
defocused = toRealSpace(self.changeFocus(pf, z))
if scaling_factor is not None:
otf = scipy.fftpack.fftshift(scipy.fftpack.fft2(intensity(defocused)))
otf_scaled = otf * scaling_factor
psf[i,:,:] = numpy.abs(scipy.fftpack.ifft2(otf_scaled))
else:
psf[i,:,:] = intensity(defocused)
return psf
else:
psf = numpy.zeros((len(z_vals), pf.shape[0], pf.shape[1]),
dtype = numpy.complex_)
for i, z in enumerate(z_vals):
psf[i,:,:] = toRealSpace(self.changeFocus(pf, z))
return psf
## intensity
#
# @param x The (numpy array) to convert to intensity.
#
# @return The product of x and the complex conjugate of x.
#
def intensity(x):
return numpy.abs(x * numpy.conj(x))
## toRealSpace
#
# @param pupil_fn A pupil function.
#
# @return The pupil function in real space (as opposed to fourier space).
#
def toRealSpace(pupil_fn):
return scipy.fftpack.ifftshift(math.sqrt(pupil_fn.size) * scipy.fftpack.ifft2(pupil_fn))
if (__name__ == "__main__"):
import pickle
import sys
if (len(sys.argv) < 2):
print "usage: <psf> <zmn.txt> <amp>"
exit()
pixel_size = 0.010 # 10nm pixel size.
wavelength = 0.6 # 0.6um wavelength.
refractive_index = 1.5 # refractive index of 1.5.
numerical_aperture = 1.4 # numerical aperture of 1.4.
z_range = 1.0 # z range of +- 1um.
geo = Geometry(int(20.0/pixel_size),
pixel_size,
wavelength,
refractive_index,
numerical_aperture)
if (len(sys.argv) == 4):
zmn = []
amp = float(sys.argv[3])
with open(sys.argv[2]) as fp:
for line in fp:
data = line.strip().split(" ")
if (len(data) == 3):
zmn.append([amp * float(data[2]), int(data[0]), int(data[1])])
else:
#zmn = [[1.3, 2, 2]] # Pure astigmatism.
zmn = [] # Plane wave.
pf = geo.createFromZernike(1.0, zmn)
psfs = geo.pfToPSF(pf, numpy.arange(-z_range, z_range + 0.5 * pixel_size, pixel_size))
#
# The generated PSF is large much larger than necessary so that we don't get edge effect.
# It is cut down here to a more useful size (2x larger in pixels in XY than in Z).
#
xy_size = 2.0*psfs.shape[0]
xy_start = 0.5 * (psfs.shape[1] - xy_size)
xy_end = xy_start + xy_size
psfs = psfs[:,xy_start:xy_end,xy_start:xy_end]
if 1:
tifffile.imsave("pf_abs.tif", (1000.0 * numpy.abs(pf)).astype(numpy.uint16))
tifffile.imsave("pf_angle.tif", (1800.0 * numpy.angle(pf)/numpy.pi + 1800).astype(numpy.uint16))
if 1:
with tifffile.TiffWriter(sys.argv[1]) as psf_tif:
temp = (psfs/numpy.max(psfs)).astype(numpy.float32)
psf_tif.save(temp)
if 0:
psfs = (65000.0 * (psfs/numpy.max(psfs))).astype(numpy.uint16)
psf_dict = {"pixel_size" : pixel_size,
"wavelength" : wavelength,
"refractive_index" : refractive_index,
"numerical_aperture" : numerical_aperture,
"z_range" : z_range,
"zmm" : zmn,
"psf" : psfs}
pickle.dump(psf_dict, open(sys.argv[1], "wb"), protocol = 2)
#
# The MIT License
#
# Copyright (c) 2016 Zhuang Lab, Harvard University
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
#
| Python |
2D | SMLM-Challenge/Challenge2016 | Tools/pupil_functions/zernike_c.py | .py | 1,741 | 65 | #!/usr/bin/python
#
# Simple Python interface to zernike.c
#
# Hazen 10/14
#
import ctypes
import numpy
from numpy.ctypeslib import ndpointer
import os
import sys
directory = os.path.dirname(__file__)
if (directory == ""):
directory = "./"
else:
directory += "/"
if(sys.platform == "win32"):
zernike = ctypes.cdll.LoadLibrary(directory + "zernike.dll")
else:
zernike = ctypes.cdll.LoadLibrary(directory + "zernike.so")
zernike.zernike.argtypes = [ctypes.c_int,
ctypes.c_int,
ctypes.c_double,
ctypes.c_double]
zernike.zernike.restype = ctypes.c_double
zernike.zernike_grid.argtypes = [ndpointer(dtype=numpy.float64),
ctypes.c_int,
ctypes.c_double,
ctypes.c_double,
ctypes.c_double,
ctypes.c_int,
ctypes.c_int]
def zernikeGrid(np_array, scale, m, n, radius = None, center = None):
if (np_array.shape[0] != np_array.shape[1]):
print "Array must be square."
return
if radius is None:
radius = np_array.shape[0]/2
if center is None:
center = (np_array.shape[0]/2 - 0.5)
c_np_array = numpy.ascontiguousarray(np_array, dtype=numpy.float64)
zernike.zernike_grid(c_np_array,
np_array.shape[0],
center,
radius,
scale,
m,
n)
return c_np_array
if (__name__ == "__main__"):
print zernike.zernike(1, 13, 0.12345, 0.0)
| Python |
2D | SMLM-Challenge/Challenge2016 | Assessment/RealDataAssessment/NPC_plotter.m | .m | 4,545 | 133 | function NPC_plotter(fname,savename);
%savename = fname(1:end-4);
data =importdata(fname);
fr = data(:,1);
x= data(:,2);
y= data(:,3);
z= data(:,4);
phot= data(:,5);
%whole image
rangez=[-500,500]
rangex = [0,20000];
rangey = [0,20000]
pixSz=20;
satVal3d=0.005
satVal2d=0.005
blurSigma=3;
box = [rangex(1),rangey(1),rangex(2)-rangex(1),rangey(2)-rangey(1)];
figure('Name',fname(1:end-4));
[srIm_RGB] = renderStormData(x,y,'Z',z,'ZLim',rangez,'Saturate',satVal3d,'PixelSize',pixSz,'Sigma',blurSigma,'Box',box);
saveas(gcf,[savename,'_largeFOV_xy',num2str(pixSz),'nmpix.fig']);
imwrite(srIm_RGB,[savename,'_largeFOV_xy',num2str(pixSz),'nmpix.tif']);
figure('Name',fname(1:end-4));
hCbar= plot3DSTORMcolorbar([100, 5], 'v',rangez,2,'FlipCAxis')
saveas(gcf,[savename,'_largeFOV_colorbar',num2str(pixSz),'nmpix.fig']);
saveas(gcf,[savename,'_largeFOV_colorbar',num2str(pixSz),'nmpix.png']);
%2d gray plot of the xz projection
%have to manually filter in Y beforehand URGH
xCrop= x(y>=rangey(1)&y<=rangey(2));
zCrop= z(y>=rangey(1)&y<=rangey(2));
box = [rangex(1),rangez(1),rangex(2)-rangex(1),rangez(2)-rangez(1)];
figure('Name',fname(1:end-4));
[srIm_XZ] = renderStormData(xCrop,zCrop,'Saturate',satVal2d,'PixelSize',pixSz,'Sigma',blurSigma,'Box',box);
saveas(gcf,[savename,'_largeFOV_xz',num2str(pixSz),'nmpix.fig']);
imwrite(srIm_XZ,[savename,'_largeFOV_xz',num2str(pixSz),'nmpix.tif']);
%FOV1
rangez=[-200,200]
rangex = [6000,8000];
rangey = [6000,8000];
pixSz=5;
satVal3d=0.001
satVal2d=0.001
blurSigma=3;
box = [rangex(1),rangey(1),rangex(2)-rangex(1),rangey(2)-rangey(1)];
figure('Name',fname(1:end-4));
[srIm_RGB] = renderStormData(x,y,'Z',z,'ZLim',rangez,'Saturate',satVal3d,'PixelSize',pixSz,'Sigma',blurSigma,'Box',box);
saveas(gcf,[savename,'_FOV1_xy',num2str(pixSz),'nmpix.fig']);
imwrite(srIm_RGB,[savename,'_FOV1_xy',num2str(pixSz),'nmpix.tif']);
figure('Name',fname(1:end-4));
hCbar= plot3DSTORMcolorbar([100, 5], 'v',rangez,2,'FlipCAxis')
saveas(gcf,[savename,'_FOV1_colorbar',num2str(pixSz),'nmpix.fig']);
saveas(gcf,[savename,'_FOV1_colorbar',num2str(pixSz),'nmpix.png']);
%2d gray plot of the xz projection
%have to manually filter in Y beforehand
xCrop= x(y>=rangey(1)&y<=rangey(2));
zCrop= z(y>=rangey(1)&y<=rangey(2));
box = [rangex(1),rangez(1),rangex(2)-rangex(1),rangez(2)-rangez(1)];
figure('Name',fname(1:end-4));
[srIm_XZ] = renderStormData(xCrop,zCrop,'Saturate',satVal2d,'PixelSize',pixSz,'Sigma',blurSigma,'Box',box);
saveas(gcf,[savename,'_FOV1_xz',num2str(pixSz),'nmpix.fig']);
imwrite(srIm_XZ,[savename,'_FOV1_xz',num2str(pixSz),'nmpix.tif']);
%sub image
rangez=[-500,300]
rangex = [7200,16500];
rangey = [3800,5800]
pixSz=3;
satVal3d=0.005
satVal2d=0.005
blurSigma=3;
box = [rangex(1),rangey(1),rangex(2)-rangex(1),rangey(2)-rangey(1)];
figure('Name',fname(1:end-4));
[srIm_RGB,yIm,xIm] = renderStormData(x,y,'Z',z,'ZLim',rangez,'Saturate',satVal3d,'PixelSize',pixSz,'Sigma',blurSigma,'Box',box);
saveas(gcf,[savename,'_profile_xy',num2str(pixSz),'nmpix.fig']);
imwrite(srIm_RGB,[savename,'_profile_xy',num2str(pixSz),'nmpix.tif']);
figure('Name',fname(1:end-4));
hCbar= plot3DSTORMcolorbar([100, 5], 'v',rangez,2,'FlipCAxis')
saveas(gcf,[savename,'_profile_colorbar',num2str(pixSz),'nmpix.fig']);
saveas(gcf,[savename,'_profile_colorbar',num2str(pixSz),'nmpix.png']);
%Line profiles
xyPos =[ 7732, 5223, 8300, -5];
lineWidth =600;
rangez = [-800 800];
pixSz=10;
satVal2d=0.001;
blurSigma=3;
useAngleFormat =true;
figure('Name',fname(1:end-4))
[srIm_XZ X1]=plotZcrossSection(x,y,z,xyPos,lineWidth,rangez, pixSz,satVal2d,blurSigma,useAngleFormat);
imwrite(srIm_XZ,[savename,'_profile_xz',num2str(pixSz),'nmpix.tif']);
figure('Name',fname(1:end-4));
imagesc(xIm,yIm,srIm_RGB)
axis equal
hold all;
ii=1;
%calculate the offsets
offset = lineWidth/2;
X0 = [xyPos(1:2)];
theta = xyPos(4)*pi/180;
thetaUp = theta+pi/2;
thetaDown = theta-pi/2;
X0up=[X0(1)-offset*cos(thetaUp), X0(2)-offset*sin(thetaUp)];
X1up=[X1(1)-offset*cos(thetaUp), X1(2)-offset*sin(thetaUp)];
X0down=[X0(1)-offset*cos(thetaDown), X0(2)-offset*sin(thetaDown)];
X1down=[X1(1)-offset*cos(thetaDown), X1(2)-offset*sin(thetaDown)];
plot([X0up(1) X1up(1)],[X0up(2) X1up(2)],'w--','LineWidth',2)
plot([X0down(1) X1down(1)],[X0down(2) X1down(2)],'w--','LineWidth',2)
%plot([X0(1) X1(1)],[X0(2) X1(2)],'w-','LineWidth',2)
set(gca, 'xtick', 0);
set(gca, 'ytick', 0);
set(gca,'box','off')
saveas(gcf,[savename,'_profile_xy_labelled',num2str(pixSz),'nmpix.fig'])
saveas(gcf,[savename,'_profile_xy_labelled',num2str(pixSz),'nmpix.png'])
| MATLAB |
2D | SMLM-Challenge/Challenge2016 | Assessment/RealDataAssessment/renderStormData.m | .m | 5,683 | 229 | function [srIm,yIm,xIm,density] = renderStormData(X,Y,varargin)
%TODO saturate Xpercent before gamma correction
%TODO use a faster gaussian filter
% box = [xstart ystart xwidth yheight]
%Author: S Holden
pixSize=20;
sigma=10;
gammaVal = 1;
satVal =0.0;
zlim = [-600 600];
nz =10;
satVal=0;
isBox = false;
box=[];
is3D = false;
useZCLim = false;
zclim=[];
ii = 1;
while ii <= numel(varargin)
if strcmp(varargin{ii},'Z')
is3D = true;
Z= varargin{ii+1};
ii = ii + 2;
elseif strcmp(varargin{ii},'ZLim')
zlim = varargin{ii+1};
ii = ii + 2;
elseif strcmp(varargin{ii},'Nz')
nz = varargin{ii+1};
ii = ii + 2;
elseif strcmp(varargin{ii},'PixelSize')
pixSize = varargin{ii+1};
ii = ii + 2;
elseif strcmp(varargin{ii},'Box')
isBox = true;
box = varargin{ii+1};
ii = ii + 2;
elseif strcmp(varargin{ii},'Sigma')
sigma= varargin{ii+1};
ii = ii + 2;
elseif strcmp(varargin{ii},'Gamma')
gammaVal= varargin{ii+1};
ii = ii + 2;
elseif strcmp(varargin{ii},'Saturate')
satVal= varargin{ii+1};
ii = ii + 2;
elseif strcmp(varargin{ii},'ZCLim')
useZCLim= true;
zclim = varargin{ii+1};
ii = ii + 2;
else
ii=ii+1;
end
end
if is3D ==true
[srIm ,m,n,density] = hist3D(X,Y,Z,pixSize,sigma,gammaVal, zlim,nz,satVal,box,zclim);
imshow(srIm);
else
[srIm ,m,n,density] = hist2D(X,Y,pixSize,sigma,gammaVal,satVal, box);
imshow(srIm);
colormap(gray);
end
xIm=n;
yIm=m;
%----------------------------------------------------------
function [srIm,m,n,density] =hist3D(XPosition,YPosition,ZPosition,pixSize,sigma,gammaVal,zlim,nz, satVal,box,zclim)
%HUEMAX = 240/360; %this is when you get range red --> blue (hsv circles around back to red
minC = 0;
maxC =1;
if isempty(box)
minX = min(XPosition);
maxX = max(XPosition);
minY = min(YPosition);
maxY = max(YPosition);
else
minX = box(1);
maxX = box(1)+box(3);
minY = box(2);
maxY = box(2)+box(4);
end
if ~exist('zlim','var')
minZ = min(ZPosition);
maxZ = max(ZPosition);
else
minZ = zlim(1);
maxZ = zlim(2);
end
if isempty(zclim)
useZCLim=false;
else
useZCLim=true;
end
%remove out of bounds data
isInBounds = XPosition > minX & XPosition < maxX ...
& YPosition > minY & YPosition < maxY ...
& ZPosition > minZ & ZPosition < maxZ;
XPosition = XPosition(isInBounds);
YPosition = YPosition(isInBounds);
ZPosition = ZPosition(isInBounds);
if useZCLim
%clip extreme z values but do not discard the points
ZPosition(ZPosition<zclim(1))=zclim(1);
ZPosition(ZPosition>zclim(2))=zclim(2);
%convert z to colour range, limits [0 1];
z_cVal = (ZPosition-zclim(1))/(zclim(2)-zclim(1));
else
%convert z to colour range, limits [0 1];
z_cVal = (ZPosition-minZ)/(maxZ-minZ);
end
%use this to index into a lookuptable, here jet
z_hue=applyStormCmap(z_cVal);
n=minX:pixSize:maxX;
m=minY:pixSize:maxY;
nx = numel(n);
ny = numel(m);
RR = [...
round((ny-1)*(YPosition-minY)/(maxY-minY))+1 ...
round((nx-1)*(XPosition-minX)/(maxX-minX))+1];
density = accumarray(RR,1,[ny,nx]);
zsum = accumarray(RR,z_hue,[ny,nx]);
zavg=zsum./density;
zavgRaw=zavg;
zavg(isnan(zavg))=0;
%make the hsv image
hue = zavg;
sat = ones(size(density));
val = density/max(density(:));
srHSV = cat(3,hue,sat,val);
srRGB = hsv2rgb(srHSV);
%have to gaussian blur in rgb domain
srRGBblur = imgaussfilt(srRGB,sigma/pixSize);
srHSVblur = rgb2hsv(srRGBblur);
% ADJUST GAMMA HERE
val = srHSVblur(:,:,3);
val= saturateImage(val,satVal);
val= adjustGamma(val,gammaVal);
srHSVfinal = cat(3, srHSVblur(:,:,1:2),val);
%then do the final conversion to RGB
srRGBfinal= hsv2rgb(srHSVfinal);
srIm = srRGBfinal;
%keyboard
%-----------------------------------------------------------------------------------------------
function [srIm,m,n,density] =hist2D(XPosition,YPosition,pixSize,sigma,gammaVal,satVal,box)
if isempty(box)
minX = min(XPosition);
maxX = max(XPosition);
minY = min(YPosition);
maxY = max(YPosition);
else
minX = box(1);
maxX = box(1)+box(3);
minY = box(2);
maxY = box(2)+box(4);
end
%remove out of bounds data
isInBounds = XPosition > minX & XPosition < maxX ...
& YPosition > minY & YPosition < maxY ;
XPosition = XPosition(isInBounds);
YPosition = YPosition(isInBounds);
n=minX:pixSize:maxX;
m=minY:pixSize:maxY;
nx = numel(n);
ny = numel(m);
RR = [...
round((ny-1)*(YPosition-minY)/(maxY-minY))+1 ...
round((nx-1)*(XPosition-minX)/(maxX-minX))+1];
density = accumarray(RR,1,[ny,nx]);
%TODO use a faster gauss filter here
sPix = sigma/pixSize;
gWindow = ceil(5*sPix);
gKern = fspecial('gaussian',gWindow, sPix);
dMax = max(density(:));
srIm = density/max(density(:));
srIm = imfilter(srIm,gKern,'replicate');
%srIm = gaussf(srIm/max(srIm(:)),[sigma/pxx sigma/pxy 0]);
% ADJUST GAMMA HERE
srIm(srIm<0)=0;
srIm = saturateImage(srIm,satVal);
srIm = adjustGamma(srIm,gammaVal);
%-----------------------------------------------------------------------------------------------
%-----------------------------------------------------------------------------------------------
function imG= adjustGamma(im,gammaVal)
imMax = max(im(:));
%normalise image
imG = ((im/imMax).^gammaVal)*imMax;
%-----------------------------------
function b= saturateImage(a, satVal)
% function saturateImage(fnameIn, fnameOut, satVal)
%this assumes 0<a<1
satLim = stretchlim(a(:), [0, 1-satVal]);
for ii = 1:size(a,3)
a(:,:,ii)=imadjust(a(:,:,ii), satLim, [0 1]);
end
b=a;
%---------------------
function z_hue=applyStormCmap(z_cVal);
ncolor = 256;
[cmap stormHue linearHue]=stormCmap(ncolor);
z_hue = interp1(linearHue,stormHue,z_cVal);
| MATLAB |
2D | SMLM-Challenge/Challenge2016 | Assessment/RealDataAssessment/plotZcrossSection.m | .m | 1,431 | 47 | function [srIm_XZ X1] = plotZcrossSection(x,y,z,xyPos,lineWidth,rangez, pixSz,satVal,blurSigma,useAngleFormat)
if ~exist('useAngleFormat','var')
useAngleFormat=false;
end
if ~useAngleFormat
Dx = (xyPos(2,1)-xyPos(1,1));
Dy = (xyPos(2,2)-xyPos(1,2));
X0 = [xyPos(1,1),xyPos(1,2)]
lineLength = sqrt(Dx^2+Dy^2)
lineAngle = atan2(Dy,Dx) %in radians
else
X0 = [xyPos(1),xyPos(2)];
lineLength = xyPos(3);
lineAngle = xyPos(4)*pi/180;%input is in degrees
X1 = [X0(1)+lineLength*cos(lineAngle),X0(2)+lineLength*sin(lineAngle)];
end
%rotate the data parallel to x axis
R = [cos(-lineAngle),-sin(-lineAngle);...
sin(-lineAngle),cos(-lineAngle)];
[XYRot]=R*[x';y'];
X0Rot = R*X0';
xRot = XYRot(1,:)' -X0Rot(1) ;
yRot = XYRot(2,:)' - X0Rot(2);
% then flip z & y ax s.t. y'=z & z'=-y.
along_crossSec= xRot;
across_crossSec =-yRot;
z_crossSec = -z ;
% apply the filter
alongMin = 0; alongMax = lineLength;
acrossMin = -lineWidth/2; acrossMax = +lineWidth/2;
isOk = (along_crossSec>=alongMin & along_crossSec<=alongMax...
& across_crossSec>=acrossMin & across_crossSec<=acrossMax);
along_crossCrop= along_crossSec(isOk);
across_crossCrop= across_crossSec(isOk);
z_crossCrop= z_crossSec(isOk);
box = [alongMin,rangez(1),alongMax-alongMin,rangez(2)-rangez(1)];
[srIm_XZ] = renderStormData(along_crossCrop,z_crossCrop,'Saturate',satVal,'PixelSize',pixSz,'Sigma',blurSigma,'Box',box);
| MATLAB |
2D | SMLM-Challenge/Challenge2016 | Assessment/RealDataAssessment/stormCmap.m | .m | 424 | 15 | %---------------------
function [cmap stormHue linearHue]=stormCmap(ncolor);
linearHue = linspace(0,1,ncolor);
cmap=colormap(jet(ncolor));
cmaphsv=rgb2hsv(cmap);
stormHue= cmaphsv(:,1);
stormHue=unique(stormHue,'stable');
nVal = numel(stormHue);
stormHue = [interp1(1:nVal,stormHue,linspace(1,nVal,ncolor))]';
sat = ones(size(stormHue));
val = ones(size(stormHue));
stormHSV = [stormHue,sat,val];
cmap = hsv2rgb(stormHSV);
| MATLAB |
2D | SMLM-Challenge/Challenge2016 | Assessment/RealDataAssessment/lmCompDriftCor.m | .m | 679 | 35 | function savename = lmCompDriftCor(fname )
data =importdata(fname);
fr = data(:,1);
x= data(:,2);
y= data(:,3);
z= data(:,4);
if size(data,2)>4
phot= data(:,5);
end
drift=driftcorrection3D_so(x,y,z,fr,[]);%4th arg is the parameters arg
%have to supply p even if its just empty (standard)
figname = [fname(1:end-4),'_drift.fig'];
saveas(gcf,figname);
pos.xnm=x;
pos.ynm=y;
pos.znm=z;
pos.frame=fr;
poso=applydriftcorrection(drift,pos);
xcorr=poso.xnm;
ycorr=poso.ynm;
zcorr=poso.znm;
if size(data,2)>4
dataout = [fr,xcorr,ycorr,zcorr,phot];
else
dataout = [fr,xcorr,ycorr,zcorr];
end
savename = [fname(1:end-4),'_driftCorr.csv'];
dlmwrite(savename,dataout,',');
| MATLAB |
2D | SMLM-Challenge/Challenge2016 | Assessment/RealDataAssessment/tubulin_plotter.m | .m | 5,905 | 178 | function tubulin_plotter(fname,savename)
data =importdata(fname);
fr = data(:,1);
x= data(:,2);
y= data(:,3);
z= data(:,4);
phot= data(:,5);
%whole image
rangez=[-750,500]
rangex = [0,40000];
rangey = [0,40000]
pixSz=30;
satVal3d=0.005
satVal2d=0.005
blurSigma=3;
box = [rangex(1),rangey(1),rangex(2)-rangex(1),rangey(2)-rangey(1)];
figure('Name',fname(1:end-4));
[srIm_RGB] = renderStormData(x,y,'Z',z,'ZLim',rangez,'Saturate',satVal3d,'PixelSize',pixSz,'Sigma',blurSigma,'Box',box);
saveas(gcf,[savename,'_largeFOV_xy',num2str(pixSz),'nmpix.fig']);
imwrite(srIm_RGB,[savename,'_largeFOV_xy',num2str(pixSz),'nmpix.tif']);
figure('Name',fname(1:end-4));
hCbar= plot3DSTORMcolorbar([100, 5], 'v',rangez,2,'FlipCAxis')
saveas(gcf,[savename,'_largeFOV_colorbar',num2str(pixSz),'nmpix.fig']);
saveas(gcf,[savename,'_largeFOV_colorbar',num2str(pixSz),'nmpix.png']);
%2d gray plot of the xz projection
%have to manually filter in Y beforehand URGH
xCrop= x(y>=rangey(1)&y<=rangey(2));
zCrop= z(y>=rangey(1)&y<=rangey(2));
box = [rangex(1),rangez(1),rangex(2)-rangex(1),rangez(2)-rangez(1)];
figure('Name',fname(1:end-4));
[srIm_XZ] = renderStormData(xCrop,zCrop,'Saturate',satVal2d,'PixelSize',pixSz,'Sigma',blurSigma,'Box',box);
axis normal;
saveas(gcf,[savename,'_largeFOV_xz',num2str(pixSz),'nmpix.fig']);
imwrite(srIm_XZ,[savename,'_largeFOV_xz',num2str(pixSz),'nmpix.tif']);
%FOV1
rangez=[-700,400]
rangex = [20000,30000];
rangey = [17000,27000];
pixSz=5;
satVal3d=0.002
satVal2d=0.002
blurSigma=3;
box = [rangex(1),rangey(1),rangex(2)-rangex(1),rangey(2)-rangey(1)];
figure('Name',fname(1:end-4));
[srIm_RGB] = renderStormData(x,y,'Z',z,'ZLim',rangez,'Saturate',satVal3d,'PixelSize',pixSz,'Sigma',blurSigma,'Box',box);
saveas(gcf,[savename,'_FOV1_xy',num2str(pixSz),'nmpix.fig']);
imwrite(srIm_RGB,[savename,'_FOV1_xy',num2str(pixSz),'nmpix.tif']);
figure('Name',fname(1:end-4));
hCbar= plot3DSTORMcolorbar([100, 5], 'v',rangez,2,'FlipCAxis')
saveas(gcf,[savename,'_FOV1_colorbar',num2str(pixSz),'nmpix.fig']);
saveas(gcf,[savename,'_FOV1_colorbar',num2str(pixSz),'nmpix.png']);
%2d gray plot of the xz projection
%have to manually filter in Y beforehand
xCrop= x(y>=rangey(1)&y<=rangey(2));
zCrop= z(y>=rangey(1)&y<=rangey(2));
box = [rangex(1),rangez(1),rangex(2)-rangex(1),rangez(2)-rangez(1)];
figure('Name',fname(1:end-4));
[srIm_XZ] = renderStormData(xCrop,zCrop,'Saturate',satVal2d,'PixelSize',pixSz,'Sigma',blurSigma,'Box',box);
saveas(gcf,[savename,'_FOV1_xz',num2str(pixSz),'nmpix.fig']);
imwrite(srIm_XZ,[savename,'_FOV1_xz',num2str(pixSz),'nmpix.tif']);
%FOV2
rangez=[-400,400]
rangex = [24000, 26500];
rangey = [20000, 22500 ];
pixSz=5;
satVal3d=0.002
satVal2d=0.002
blurSigma=3;
box = [rangex(1),rangey(1),rangex(2)-rangex(1),rangey(2)-rangey(1)];
figure('Name',fname(1:end-4));
[srIm_RGB] = renderStormData(x,y,'Z',z,'ZLim',rangez,'Saturate',satVal3d,'PixelSize',pixSz,'Sigma',blurSigma,'Box',box);
saveas(gcf,[savename,'_FOV2_xy',num2str(pixSz),'nmpix.fig']);
imwrite(srIm_RGB,[savename,'_FOV2_xy',num2str(pixSz),'nmpix.tif']);
figure('Name',fname(1:end-4));
hCbar= plot3DSTORMcolorbar([100, 5], 'v',rangez,2,'FlipCAxis')
saveas(gcf,[savename,'_FOV2_colorbar',num2str(pixSz),'nmpix.fig']);
saveas(gcf,[savename,'_FOV2_colorbar',num2str(pixSz),'nmpix.png']);
%2d gray plot of the xz projection
%have to manually filter in Y beforehand
xCrop= x(y>=rangey(1)&y<=rangey(2));
zCrop= z(y>=rangey(1)&y<=rangey(2));
box = [rangex(1),rangez(1),rangex(2)-rangex(1),rangez(2)-rangez(1)];
figure('Name',fname(1:end-4));
[srIm_XZ] = renderStormData(xCrop,zCrop,'Saturate',satVal2d,'PixelSize',pixSz,'Sigma',blurSigma,'Box',box);
saveas(gcf,[savename,'_FOV2_xz',num2str(pixSz),'nmpix.fig']);
imwrite(srIm_XZ,[savename,'_FOV2_xz',num2str(pixSz),'nmpix.tif']);
%Line profiles
%FOV_paper
rangez=[-400,300]
rangex = [12000,26500];
rangey = [18500,27000];
pixSz=5;
satVal3d=0.002
satVal2d=0.002
blurSigma=3;
box = [rangex(1),rangey(1),rangex(2)-rangex(1),rangey(2)-rangey(1)];
figure('Name',fname(1:end-4));
[srIm_RGB,yIm,xIm] = renderStormData(x,y,'Z',z,'ZLim',rangez,'Saturate',satVal3d,'PixelSize',pixSz,'Sigma',blurSigma,'Box',box);
saveas(gcf,[savename,'_profiles_xy',num2str(pixSz),'nmpix.fig']);
imwrite(srIm_RGB,[savename,'_profiles_xy',num2str(pixSz),'nmpix.tif']);
figure('Name',fname(1:end-4));
hCbar= plot3DSTORMcolorbar([100, 5], 'v',rangez,2,'FlipCAxis')
saveas(gcf,[savename,'_profiles_colorbar',num2str(pixSz),'nmpix.fig']);
saveas(gcf,[savename,'_profiles_colorbar',num2str(pixSz),'nmpix.png']);
%Line profiles
xyPos{1} = 1.0e+04*[ 1.9740 2.4322;...
1.9932 2.4759]%SF6 profile6
xyPos{2} = 1.0e+04*[1.6509 2.0684;...
1.7113 2.0738]%SF6 profile7
xyPos{3} = 1.0e+04*[1.5723 2.0078
1.6326 2.0337 ]%SF6 profile8
xyPos{4} = 1.0e+04*[ 2.1608 2.0958;...
2.2192 2.1152]%SF6 profile9
%xyPos{5} = 1.0e+04*[ 2.1819 2.6637;...
% 2.2128 2.6413]%SF6 profile10
xyPos{5} = 1.0e+04*[ 2.1282 2.3499;...
2.1537 2.4014]%SF6 profile11
nProfile = numel(xyPos);
lineWidth = 250;
rangez = [-500 500];
pixSz=5;
satVal2d=0.001;
blurSigma=3;
for ii=1:nProfile
figure('Name',fname(1:end-4));
srIm_XZ=plotZcrossSection(x,y,z,xyPos{ii},lineWidth,rangez, pixSz,satVal2d,blurSigma);
imwrite(srIm_XZ,[savename,'_profile',num2str(ii),'_',num2str(pixSz),'nmpix.tif']);
end
figure('Name',fname(1:end-4));
imagesc(xIm,yIm,srIm_RGB)
axis equal
hold all;
for ii = 1:nProfile
plot(xyPos{ii}(:,1),xyPos{ii}(:,2),'w-','LineWidth',2)
xT= xyPos{ii}(1,1)-50;
yT= xyPos{ii}(1,2)-50;
t=text(xT,yT,num2str(ii),'HorizontalAlignment','right');
t.Color='w';
end
set(gca, 'xtick', 0);
set(gca, 'ytick', 0);
set(gca,'box','off')
%set(gca,'Visible','off');
saveas(gcf,[savename,'_profiles_xy_labelled',num2str(pixSz),'nmpix.fig'])
saveas(gcf,[savename,'_profiles_xy_labelled',num2str(pixSz),'nmpix.png'])
| MATLAB |
2D | SMLM-Challenge/Challenge2016 | Assessment/RealDataAssessment/driftCorrectAll.m | .m | 1,316 | 39 | %run this on a directory containing the real data csv files
% Or copy to said directory
%modify this list to match the files you want to analyse
%Need to add to the matlab path:
% 'Challenge2016\Assessment\RealDataAssessment'
% 'Challenge2016\Assessment\Matlab\driftCorrection'
fnameTubulinList = {...
'3D-DAOSTORM-WOBBLE____loca___Tubulin.csv',...
'Cspline____loca___Tubulin.csv',...
'MIAtool-WOBBLE____loca___Tubulin.csv',...
'QuickPALM____loca___Tubulin.csv',...
'RapidSTORM-WOBBLE____loca___Tubulin.csv',...
'SMAP-2018____loca___Tubulin.csv',...
'ThunderSTORM-WOBBLE____loca___Tubulin.csv',...
'WaveTracer____loca___Tubulin.csv'};
fnameNPCList = {...
'3D-DAOSTORM-WOBBLE____loca___NPC.csv',...
'Cspline____loca___NPC.csv',...
'MIAtool-WOBBLE____loca___NPC.csv',...
'QuickPALM____loca___NPC.csv',...
'RapidSTORM-WOBBLE____loca___NPC.csv',...
'ThunderSTORM-WOBBLE____loca___NPC.csv',...
'SMAP-2018____loca___NPC.csv',...
'WaveTracer____loca___NPC.csv'};
nTub = numel(fnameTubulinList);
nNPC = numel(fnameNPCList);
%1. apply drift correction to all files
for ii=1:nTub
f= fnameTubulinList{ii}
lmCompDriftCor(f);
end
for ii=1:nNPC
f= fnameNPCList{ii}
lmCompDriftCor(f);
end
| MATLAB |
2D | SMLM-Challenge/Challenge2016 | Assessment/RealDataAssessment/real3dAnalysis.m | .m | 1,886 | 54 | %run this on a directory containing the real data csv files
% Or copy to said directory
%modify this list to match the files you want to analyse
%Need to add to path:
% 'lm-challenge2016\Challenge2016\Assessment\Matlab\3dPlotTools'
% 'lm-challenge2016\Challenge2016\Assessment\Matlab\driftCorrection\driftcorrection3D'
% 'lm-challenge2016\Challenge2016\Assessment\RealDataAssessment'
fnameTubulinList = {...
'3D-DAOSTORM-WOBBLE____loca___Tubulin_driftCorr.csv',...
'Cspline____loca___Tubulin_driftCorr.csv',...
'MIAtool-WOBBLE____loca___Tubulin_driftCorr.csv',...
'QuickPALM____loca___Tubulin_driftCorr.csv',...
'RapidSTORM-WOBBLE____loca___Tubulin_driftCorr.csv',...
'SMAP-2018____loca___Tubulin_driftCorr.csv',...
'ThunderSTORM-WOBBLE____loca___Tubulin_driftCorr.csv',...
'WaveTracer____loca___Tubulin_driftCorr.csv'};
fnameNPCList = {...
'3D-DAOSTORM-WOBBLE____loca___NPC_driftCorr.csv',...
'Cspline____loca___NPC_driftCorr.csv',...
'MIAtool-WOBBLE____loca___NPC_driftCorr.csv',...
'QuickPALM____loca___NPC_driftCorr.csv',...
'RapidSTORM-WOBBLE____loca___NPC_driftCorr.csv',...
'ThunderSTORM-WOBBLE____loca___NPC_driftCorr.csv',...
'SMAP-2018____loca___NPC_driftCorr.csv',...
'WaveTracer____loca___NPC_driftCorr.csv'};
%1. Tubulin plots
nTub = numel(fnameTubulinList);
for ii=1:nTub
close all
f = fnameTubulinList{ii}
dirname = [f(1:end-4)];
if ~exist(dirname,'dir')
mkdir(dirname)
end
savename = [dirname,filesep(),dirname];
tubulin_plotter(f,savename);
end
nNPC = numel(fnameNPCList);
%2. NPC plots
for ii=1:nNPC
close all
f = fnameNPCList{ii}
dirname = [f(1:end-4)];
if ~exist(dirname,'dir')
mkdir(dirname)
end
savename = [dirname,filesep(),dirname];
NPC_plotter(f,savename);
end
| MATLAB |
2D | SMLM-Challenge/Challenge2016 | Assessment/RealDataAssessment/plot3DSTORMcolorbar.m | .m | 2,619 | 88 | function h = plot3DSTORMcolorbar(dims, orientation,zLim,nTick,varargin)
% PLOT_COLORBAR plot a standalone colorbar for inclusion in a publication
% H = PLOT_COLORBAR(DIMS, ORIENTATION TITLE_STRING) Plot a colorbar for
% inclusion in a publication. DIMS sets the length and width of the
% colorbar (in vertical mode). DIMS(1) will be the size of the colormap
% used and DIMS(2) will be the number of times it is repeated (thickness
% of image). ORIENTATION sets the orientation of the bar -- 'h', or 'v'.
% TITLE_STRING sets the title of the axis used.
%
% H = PLOT_COLORBAR(DIMS, ORIENTATION TITLE_STRING, CMAP) Works as above,
% except that CMAP is a handle to a function to generate the colormap.
%
% Examples:
% h1 = plot_colorbar([100, 5], 'h', 'Test Colormap')
% h2 = plot_colorbar([150, 10], 'v', 'Test Colormap', @hsv)
%
% Bugs:
% May not work well with wide images.
% Feel free to send in patches etc for any problems you find.
%
% Matt Foster <ee1mpf@bath.ac.uk>
%Extended to allow to set the labels 181114 S Holden
HUEMAX = 240/360; %this is when you get range red --> blue (hsv circles around back to red
% Extract the width froms dims, if there is one.
if length(dims) < 2
width = 5;
else
width = dims(2);
end
doReverse=false;
ii = 1;
while ii <= numel(varargin)
if strcmp(varargin{ii},'FlipCAxis')
doReverse=true
ii = ii + 1;
else
ii = ii + 1;
end
end
map = stormCmap(dims(1));
%map = flipud(colormap);
switch lower(orientation)
case {'v', 'vert', 'vertical'}
h = image(repmat(cat(3, map(:,1), map(:,2), map(:,3)), 1, width));
% Remove ticks we dont want.
set(gca, 'xtick', 0);
ticks = get(gca, 'ytick');
ticksMod = linspace(0.5, max(ticks),nTick);
set(gca, 'ytick', ticksMod);
cval = linspace(zLim(1),zLim(2),nTick);
set(gca, 'yticklabel', cval);
% Set up the axis
title('Z (nm)')
axis equal
axis tight
axis xy
if doReverse
set(gca, 'YDir', 'reverse');
end
case {'h', 'horiz', 'horizontal'}
h = image(repmat(cat(3, map(:,1)', map(:,2)', map(:,3)'), width, 1));
% Remove ticks we dont want.
set(gca, 'ytick', 0);
ticks = get(gca, 'xtick');
ticksMod = linspace(0.5, max(ticks),nTick);
set(gca, 'xtick', ticksMod);
cval = linspace(zLim(1),zLim(2),nTick);
set(gca, 'xticklabel', cval);
% Set up the axis
title('Z (nm)')
axis equal
axis tight
axis xy
if doReverse
set(gca, 'XDir', 'reverse');
end
otherwise
error('unknown colorbar orientation');
end
set(gca,'TickLength',[0 0]);
| MATLAB |
2D | SMLM-Challenge/Challenge2016 | Assessment/Matlab/rnd_loc.m | .m | 431 | 21 | function loc = rnd_loc(ave_dens,nframes,fov)
%RND_LOC Random Localization
% ave_dens : Number of fluorophores per frame on average
% nframes : number of frame
% fov : Field Of View
Nmol_tot = ave_dens*nframes;
if iscolumn(fov)
fov = fov';
end
maxInt = 1e4;
loc = repmat([fov, maxInt], Nmol_tot, 1).*rand(Nmol_tot,4);
loc(:,3) = loc(:,3) - fov(3)/2;
loc = [reshape(repmat(1:nframes,ave_dens,1),Nmol_tot,1),loc];
end
| MATLAB |
2D | SMLM-Challenge/Challenge2016 | Assessment/Matlab/importFullPairings.m | .m | 3,220 | 86 | function pairingsMT1 = importFullPairings(filename, startRow, endRow)
%IMPORTFILE Import numeric data from a text file as a matrix.
% PAIRINGSMT1 = IMPORTFILE(FILENAME) Reads data from text file FILENAME
% for the default selection.
%
% PAIRINGSMT1 = IMPORTFILE(FILENAME, STARTROW, ENDROW) Reads data from
% rows STARTROW through ENDROW of text file FILENAME.
%
% Example:
% pairingsMT1 = importfile('pairings____MT1.N1.LD____DH____MIATool-RMS____wobble_no____border_450____photonT_1974____date_19-Aug-2016____dim3D_1____nFeat_5.csv', 1, 16411);
%
% See also TEXTSCAN.
% Auto-generated by MATLAB on 2017/09/26 09:24:39
%% Initialize variables.
delimiter = ',';
if nargin<=2
startRow = 1;
endRow = inf;
end
%% Format string for each line of text:
% column1: double (%f)
% column2: double (%f)
% column3: double (%f)
% column4: double (%f)
% column5: double (%f)
% column6: double (%f)
% column7: double (%f)
% column8: double (%f)
% column9: double (%f)
% column10: double (%f)
% column11: double (%f)
% column12: double (%f)
% column13: double (%f)
% column14: double (%f)
% column15: double (%f)
% column16: double (%f)
% column17: double (%f)
% column18: double (%f)
% column19: double (%f)
% column20: double (%f)
% column21: double (%f)
% column22: double (%f)
% column23: double (%f)
% column24: double (%f)
% column25: double (%f)
% column26: double (%f)
% column27: double (%f)
% column28: double (%f)
% column29: double (%f)
% column30: double (%f)
% column31: double (%f)
% For more information, see the TEXTSCAN documentation.
formatSpec = '%f%f%f%f%f%f%f%f%f%f%f%f%f%f%f%f%f%f%f%f%f%f%f%f%f%f%f%f%f%f%f%[^\n\r]';
%% Open the text file.
fileID = fopen(filename,'r');
%% Read columns of data according to format string.
% This call is based on the structure of the file used to generate this
% code. If an error occurs for a different file, try regenerating the code
% from the Import Tool.
dataArray = textscan(fileID, formatSpec, endRow(1)-startRow(1)+1, 'Delimiter', delimiter, 'EmptyValue' ,NaN,'HeaderLines', startRow(1)-1, 'ReturnOnError', false);
for block=2:length(startRow)
frewind(fileID);
dataArrayBlock = textscan(fileID, formatSpec, endRow(block)-startRow(block)+1, 'Delimiter', delimiter, 'EmptyValue' ,NaN,'HeaderLines', startRow(block)-1, 'ReturnOnError', false);
for col=1:length(dataArray)
dataArray{col} = [dataArray{col};dataArrayBlock{col}];
end
end
%% Close the text file.
fclose(fileID);
%% Post processing for unimportable data.
% No unimportable data rules were applied during the import, so no post
% processing code is included. To generate code which works for
% unimportable data, select unimportable cells in a file and regenerate the
% script.
%% Create output variable
pairingsMT1 = table(dataArray{1:end-1}, 'VariableNames', {'VarName1','VarName2','VarName3','VarName4','VarName5','VarName6','VarName7','VarName8','VarName9','VarName10','VarName11','VarName12','VarName13','VarName14','VarName15','VarName16','VarName17','VarName18','VarName19','VarName20','VarName21','VarName22','VarName23','VarName24','VarName25','VarName26','VarName27','VarName28','VarName29','VarName30','VarName31'});
| MATLAB |
2D | SMLM-Challenge/Challenge2016 | Assessment/Matlab/main_3dcolor_winners.m | .m | 7,136 | 173 | %Script for winners visualisations
%2D LD 3D-DAOSTORM
%2D HD SMfit
%AS LD CSpline
%AS HD SMolPhot
%BP LD MIATool
%BP HD ThunderSTORM
%DH LD CSpline
%DH HD CSpline
clear
winners = table(cell(10,1),cell(10,1),cell(10,1),'VariableNames',{'modality','density','software'});
winners.modality{1} = 'AS';winners.density{1} = 'LD';winners.software{1} = 'GT';
winners.modality{2} = 'AS';winners.density{2} = 'HD';winners.software{2} = 'GT';
winners.modality{3} = '2D';winners.density{3} = 'LD';winners.software{3} = 'GT';
winners.modality{4} = '2D';winners.density{4} = 'HD';winners.software{4} = 'GT';
winners.modality{5} = '2D';winners.density{5} = 'LD';winners.software{5} = '3D-DAOSTORM';
winners.modality{6} = '2D';winners.density{6} = 'HD';winners.software{6} = 'SMfit';
winners.modality{7} = 'AS';winners.density{7} = 'LD';winners.software{7} = 'CSpline';
winners.modality{8} = 'AS';winners.density{8} = 'HD';winners.software{8} = 'SMolPhot';
winners.modality{9} = 'BP';winners.density{9} = 'LD';winners.software{9} = 'MIATool';
winners.modality{10} = 'BP';winners.density{10} = 'HD';winners.software{10} = 'ThunderSTORM';
winners.modality{11} = 'DH';winners.density{11} = 'LD';winners.software{11} = 'CSpline';
winners.modality{12} = 'DH';winners.density{12} = 'HD';winners.software{12} = 'CSpline';
sigmin = 20/(2*sqrt(2*log(2)));
sigmax = 30/(2*sqrt(2*log(2)));
doInt = false;
Nneigh = 10;
save3Dvol = 1;%3D volumes or orthoview/color-coded
center = 0;
pix_size = 5;%don't 1
doCorr = 1;%leave it at 1, boolean for shift in z when gaussian rendering
folder_res = pwd;
if center
folder_res = fullfile(folder_res,'res',strcat(save3Dvol*'3Dvol',~save3Dvol*'3Dcolored'),'full');
else
folder_res = fullfile(folder_res,'res',strcat(save3Dvol*'3Dvol',~save3Dvol*'3Dcolored'),'zoom');
end
addpath(folder_res);
mkdir(folder_res);
set(0,'DefaultTextInterpreter','LaTex');
for kk = 1:height(winners)
for ll = 1:2
software = winners.software{kk};
modality = winners.modality{kk};
if strcmpi(winners.density{kk},'LD')
if ll==1
if strcmpi(winners.modality{kk},'2D')
dataset = 'ER1.N3.LD';
else
dataset = 'MT1.N1.LD';
end
else
dataset = 'MT3.N2.LD';
end
else
if ll==1
if strcmpi(winners.modality{kk},'2D')
dataset = 'ER2.N3.HD';
else
dataset = 'MT2.N1.HD';
end
else
dataset = 'MT4.N2.HD';
end
end
locup = dir(fullfile(software,'standard',sprintf('%s____%s____%s*',...
dataset,modality,software)));
%header = textscan(fullfile(software,'upload',locup(1).name),'Delimiter',',',0,0);
locup = csvread(fullfile(software,'standard',locup(1).name),1,0);
locup = array2table(locup(:,1:end),'VariableNames',{'frame' 'x' 'y' 'z' 'int'});
if center
fov = [6400,6400,1500];
elseif strcmpi(dataset,'MT1.N1.LD')
fov = [1200,3000, 1500];%[500,1200,1500];%
elseif strcmpi(dataset,'MT2.N1.HD')
fov = [800,3000, 1500];
elseif strcmpi(dataset,'MT3.N2.LD')
fov = [1500,600,1500];%[1500, 1800, 1500];
elseif strcmpi(dataset,'MT4.N2.HD')
fov = [2000,1250,1500];%[1800,1500,1500];
elseif strcmpi(dataset,'ER1.N3.LD')
fov = [1400,3000, 1500];
elseif strcmpi(dataset,'ER2.N3.HD')
fov = [1500,3000, 1500];
end
if center
shift = ([6400,6400,1500] - fov)/2;
elseif strcmpi(dataset,'MT1.N1.LD')
shift = [1950,4900,0] - [fov(1:2)/2,0];%[1650,4050,0];%
elseif strcmpi(dataset,'MT2.N1.HD')
shift = [1500,4750,0] - [fov(1:2)/2,0];
elseif strcmpi(dataset,'MT3.N2.LD')
shift = [4500,1600,0]-[fov(1:2)/2,0];%[3750,650,0];
elseif strcmpi(dataset,'MT4.N2.HD')
shift = [3650,1900,0]-[fov(1:2)/2,0];%[2200,4500,0];%MT4
elseif strcmpi(dataset,'ER1.N3.LD')
shift = [1400,4900,0] - [fov(1:2)/2,0];
elseif strcmpi(dataset,'ER2.N3.HD')
shift = [2700,1750,0] - [fov(1:2)/2,0];%croisement a droite %[1900,4900,0]-[fov(1:2)/2,0];%croisement a droite
end
imsize = fov/pix_size;
if prod(imsize)*8 > 1.2e10
fprintf('BIG volume ! > 12 Go...5 seconds for cancelling\n');pause(5);
end
if doInt
thresmax = quantile(locup.int,0.95);
thresmin = quantile(locup.int,0.05);
sig_locup = max(min((locup.int - thresmin)/(thresmax - thresmin),1),0);
sig_locup = sigmax + (sigmin - sigmax).*sqrt(sig_locup);
else
sig_locup = getSigma(sigmin,sigmax,[locup.x,locup.y,locup.z], Nneigh);
end
%sig_locup = sigmin + sig_locup./sqrt(locup.int);
%Get "density map" invers. prop. to sqrt(estimated intensity), see sig exp.
im_locup = gauss_render_intensity([locup.x,locup.y,locup.z] - repmat(shift,height(locup),1),...
sig_locup, pix_size, imsize,doCorr);
if save3Dvol
%im_locup = im_locup*255/max(im_locup(:));
fname = sprintf('dataset_%s_modality_%s_density_%s_software_%s_sig_%1.2f_%1.2f_pixsiz_%i_fov_%ix%ix%i_shift_%ix%ix%i_doInt_%i.tif',...
dataset,modality,winners.density{kk},software,sigmin,sigmax,pix_size,fov,shift,doInt);
try delete(fullfile(folder_res,fname));catch end
for K = 1:imsize(3)
imwrite(im_locup(:, :, K), fullfile(folder_res,fname), 'WriteMode', 'append','Compression','none');
end
else
for dim = 1:3
tic
[im2Dcolored,T1,T2,T3,L] = depthcolor3D(im_locup,'jet',0.99,dim);
toc
fname = sprintf('dataset_%s_modality_%s_density_%s_software_%s_sig_%1.2f_%1.2f_pixsiz_%i_fov_%ix%ix%i_shift_%ix%ix%i_T1_%1.2f_T2_%1.2f_T3_%1.2f_L_%i_doInt_%i',...
dataset,modality,winners.density{kk},software,sigmin,sigmax,pix_size,fov,shift,T1,T2,T3,L,doInt);
switch dim
case 1
fname = sprintf('%s_YZ.tiff',fname);
case 2
fname = sprintf('%s_XZ.tiff',fname);
case 3
fname = sprintf('%s_XY.tiff',fname);
end
if dim==1
im2Dcolored = permute(im2Dcolored,[2,1,3]);
end
figure(5);
imagesc(im2Dcolored);axis image;
title(fname);drawnow;%pause
fprintf('Saving in %s, an RGB image %s\n',folder_res,fname);
imwrite(im2Dcolored,fullfile(folder_res,fname));
end
end
end
end | MATLAB |
2D | SMLM-Challenge/Challenge2016 | Assessment/Matlab/gauss_render_intensity.m | .m | 2,836 | 100 | function im = gauss_render_intensity(data, sig, pix_size, im_size,doCorr)
% data : list of particles Nparticles x 2-3 => (x,y)+z (opt) (nm)
% sig : sigma (nm) for each dimension
% pix_size
% im_size, size of obtained image
% varargin{1} : do the Z correction or not
doNorm = 1;
D = size(data,2);
if isscalar(sig)
sig = sig*ones(size(data,1),1);
end
for d=1:D
if d==3 && doCorr
data(:,d) = data(:,d) + im_size(d)/2*pix_size(min(d,end));%start z_min @ 0
end
%locations below 0 set @ 0, above max_size set @ the limit, should they
%be rather removed ?
%set
%data(:, k) = max(0,min(im_size(k)*pix_size,data(:,k)));
%removed : useful for dispOrthoView of zoomed area
ind_rm = data(:, d) < 0 | data(:, d) > im_size(d)*pix_size(min(d,end));
data(ind_rm,:) = [];
sig(ind_rm) = [];
end
if length(im_size)~=D
fprintf('Image dimension not equal to the data dimension...\n');
return;
end
%if length(pix_size)==1
% pix_size = repmat(pix_size,D,1);
%end
sig = repmat(sig,[1,1 + D - size(sig,2)])./repmat(pix_size,[size(sig,1),1 + D - length(pix_size)]);
data = data./repmat(pix_size,[size(sig,1),1 + D - length(pix_size)]);
ind_data = ceil(data);
ind_data(ind_data==0) = 1;%border case
offset = data - ind_data + 0.5;
for d = 1:size(sig,2)
marg(d) = ceil(3*max(sig(:,d)));
pos(d,:) = -marg(d):marg(d);
end
im = zeros(im_size + 2*marg);
gr = cell(D,1);
%tmp = tic;
fprintf('%i molecules...\n',size(data,1));
for ii=1:size(data,1)
for jj=1:D
gr{jj} = gauss_kernel(offset(ii,jj), sig(ii,jj), pos(jj,:),doNorm);
end
GR = ktensor(gr);
if D==2
im(marg(1) + ind_data(ii,1) + pos(1,:),...
marg(2) + ind_data(ii,2) + pos(2,:)) = ...
im(marg(1) + ind_data(ii,1) + pos(1,:),...
marg(2) + ind_data(ii,2) + pos(2,:)) + GR;
else %D==3 normally
try
im(marg(1) + ind_data(ii,1) + pos(1,:),...
marg(2) + ind_data(ii,2) + pos(2,:),...
marg(3) + ind_data(ii,3) + pos(3,:)) =...
im(marg(1) + ind_data(ii,1) + pos(1,:),...
marg(2) + ind_data(ii,2) + pos(2,:),...
marg(3) + ind_data(ii,3) + pos(3,:)) + GR;
catch ME
fprintf('%i\n',ii);
end
end
end
if D==2
im = im(1 + marg(1):end-marg(1), 1 + marg(2):end-marg(2));
else
im = im(1 + marg(1):end-marg(1), 1 + marg(2):end-marg(2),1 + marg(3):end-marg(3));
end
%fprintf('Gaussian rendering...%1.2f s\n',toc(tmp));
end
function im = gauss_kernel(offset,sig,pos,doNorm)
im = exp(-(offset - pos).^2/(2*sig^2));
if doNorm
im = im/(sqrt(2*pi)*sig);
end
end
function GR = ktensor(gr)
if length(gr)==2
GR = kron(gr{1}, gr{2}');
else
GRXY = kron(gr{1}, gr{2}');
GR = arrayfun(@(z) z*GRXY,gr{3},'UniformOutput',false);
GR = cat(3,GR{:});
end
end | MATLAB |
2D | SMLM-Challenge/Challenge2016 | Assessment/Matlab/main_set_param_plot.m | .m | 2,145 | 68 | %% Load pairings file resulting from assessment program
clear pos
path = '~/Dropbox/smlm/figures/';
software = 'SMAP';%'STORMChaser';%
modality = 'BP';
dataset = 'MT1.N1.LD';
wobble = true;
photonT = true;
%File must be in the path
fname = dir(fullfile('assessment_results',software,...
sprintf('pairings____%s____%s____%s____wobble_%s____border_450____photonT_%s*',...
dataset,modality,software,strcat(wobble*'*',~wobble*'no'),...
strcat(photonT*'*',~photonT*'0'))));
fname = fullfile('assessment_results',software,fname(1).name);
%%
[pos.frame,pos.x,pos.y,pos.z,pos.int] = importLocations(fname);
pos = struct2table(pos);
pos(isnan(pos.x),:) = [];
%% GT
clear gt
fname_gt = dir(fullfile('assessment_results','GT',...
sprintf('pairings____%s____%s____GT____wobble_no____border_450____photonT_%s*',...
dataset,modality,strcat(photonT*'*',~photonT*'0'))));
fname_gt = fullfile('assessment_results','GT',fname_gt(1).name);
[gt.frame,gt.x,gt.y,gt.z,gt.int] = importLocations(fname_gt);
gt = struct2table(gt);
gt(isnan(gt.x),:) = [];
%%
fov = [500, 300, 150];
pix_size = 1;
imsize = fov/pix_size;
doCorr = 0;
sigmin = 2*pix_size/(2*sqrt(2*log(2)));
sigmax = 4*pix_size/(2*sqrt(2*log(2)));
thresmax = quantile(pos.int,0.95);
thresmin = quantile(pos.int,0.05);
sig = max(min((pos.int - thresmin)/(thresmax - thresmin),1),0);
sig = sigmax + (sigmin - sigmax).*sqrt(sig);
shift = [3000,2200,0];%([6400,6400,1500] - fov)/2;
vecx = (1:pix_size:fov(1)) + shift(1);
vecy = (1:pix_size:fov(2)) + shift(2);
vecz = (1:pix_size:fov(3)) + shift(3);
sig_gt = max(min((gt.int - thresmin)/(thresmax - thresmin),1),0);
sig_gt = sigmax + (sigmin - sigmax).*sqrt(sig_gt);
%% Box and rotate
[newloc,ind_box] = boxrotate([pos.x,pos.y,pos.z],shift,fov);
[newloc_gt,ind_box_gt] = boxrotate([gt.x,gt.y,gt.z],shift,fov);
ngt = size(newloc_gt,1);
ntest = size(newloc,1);
%% GT : get gaussian rendered wrt intensity
tic
im_box_gt = gauss_render_intensity(newloc_gt,sig_gt(ind_box_gt), pix_size, imsize,false);
toc
%% Test : get gaussian rendered wrt intensity
tic
im_box = gauss_render_intensity(newloc,sig(ind_box), pix_size, imsize,false);
toc | MATLAB |
2D | SMLM-Challenge/Challenge2016 | Assessment/Matlab/saveResults.m | .m | 10,448 | 214 | function saveResults(results, results_mol, results_graph, res_folder)
%SAVERESULTS Save all the results
%Save results in final file
fname = ['results____',...
results{1}.participant,'.csv'];
fileID = fopen(strcat(res_folder,filesep,...
results{1}.participant,filesep,fname),'w');
formatSpec = strcat('%s,%s,%s,%s,%s,%s,%s,',...%Wobble file
'%f,%f,%f,%i,%s,%s,',...%Name of Test file
'%i,%i,%i,%i,%i,%f,%f,',...%z max
'%f,%i,%i,%i,%f,%f,%f,',...%Recall
'%f,%f,%f,%f,%f,%f,%f,',...%MADz
'%f,%f,%f,%f,%f,%f,%f,%f,',...%FRCxy
'%f,%f,%f,%f,%f,%f,%f,%f,',...%RMSExyz_mol
'%f,%f,%f,%f,%f,%f,',...%Detection ratio_mol
'%f,%f,%f,%f,%f,%f,%f,%f,%f,%f,%f,%f,',...%max_z_range
'%f,%f,%f,%f,%f,%f,%f,%f,%f,%f,%f,%f,',...%stdRMSExy_onRangeZ
'%f,%f,%f,%f,%f,%f,%f,%f,%f,%f,%f,%f,',...%CVRMSExy_onRangeZ
'%f,%f,%f,%f,%f,%f,%f,%f,%f,%f,%f,%f,%f,%f,%f,%f,',...%FWHM Jaccard
'%f,%f,%f,%f,','\n');%T2 Jaccard
fprintf(fileID,strcat('Date Assessment,','Name of Software,','Dataset,','Density,',...
'Modality,','Wobble,','Wobble file,','TolXY,','TolZ,','Border,',...
'dim3D,','Name of GT File,','Name of Test file,',...
'# Fluorophores GT,','# Fluorophores Test,','# Error line,',...
'frame min,','frame max,','z min,','z max,','Thres Photon,',...
'TP,','FP,','FN,','Jaccard,','F-Score,','Recall,','Precision,',...
'RMSExyz,','RMSExy,','RMSEz,','MADxyz,','MADxy,','MADz,',...
'Dx,','Dy,','Dz,','Corr. photons,',...
'FSC,','FRCyz,','FRCxz,','FRCxy,',...
'SNRxyz,','SNRyz,','SNRxz,','SNRxy,',...
'TP_mol,','FN_mol,','Recall_mol,','RMSExyz_mol,','RMSExy_mol,','RMSEz_mol,',...
'MADxyz_mol,','MADxy_mol,','MADz_mol,','Detection ratio_mol,',...
'Min Z Recall T1,','Max Z Recall T1,',...
'Mean RMSExy Recall T1,','STD RMSExy Recall T1,',...
'Mean + STD RMSExy Recall T1,','CV RMSExy Recall T1,',...
'Mean RMSEz Recall T1,','STD RMSEz Recall T1,',...
'Mean + STD RMSEz Recall T1,','CV RMSEz Recall T1,',...
'Min Z Recall T2,','Max Z Recall T2,',...
'Mean RMSExy Recall T2,','STD RMSExy Recall T2,',...
'Mean + STD RMSExy Recall T2,','CV RMSExy Recall T2,',...
'Mean RMSEz Recall T2,','STD RMSEz Recall T2,',...
'Mean + STD RMSEz Recall T2,','CV RMSEz Recall T2,',...
'Min Z Jaccard T1,','Max Z Jaccard T1,',...
'Mean RMSExy Jaccard T1,','STD RMSExy Jaccard T1,',...
'Mean + STD RMSEz Recall T2,','CV RMSExy Jaccard T1,',...
'Mean RMSEz Jaccard T1,','STD RMSEz Jaccard T1,',...
'Mean + STD RMSEz Jaccard T1,','CV RMSEz Jaccard T1,',...
'Min Z Jaccard T2,','Max Z Jaccard T2,',...
'Mean RMSExy Jaccard T2,','STD RMSExy Jaccard T2,',...
'Mean + STD RMSExy Jaccard T2,','CV RMSExy Jaccard T2,',...
'Mean RMSEz Jaccard T2,','STD RMSEz Jaccard T2,',...
'Mean + STD RMSEz Jaccard T2,','CV RMSEz Jaccard T2,',...
'Range Z Recall T1,','Range Z Recall T2,',...
'Range Z Jaccard T1,','Range Z Jaccard T2,',...
'Max Recall,','min Z FWHM Recall,','max Z FWHM Recall,','FWHM Recall,',...
'Max Jaccard,','min Z FWHM Jaccard,','max Z FWHM Jaccard,','FWHM Jaccard,',...
'T1 Recall,','T2 Recall,','T1 Jaccard,','T2 Jaccard,','\n'));
if isempty(results_graph)
results_graph = fill_results_graph(results);
end
initLen = length(results_graph);
for k=1:length(results)
l=1;
notFound = true;
while l <= initLen && notFound
if strcmp(results_graph{l}.modality, results{k}.modality)...
&& strcmp(results_graph{l}.dataset, results{k}.dataset)...
&& strcmp(results_graph{l}.participant, results{k}.participant)...
&& strcmp(results_graph{l}.wobble, results{k}.wobble)...
&& results_graph{l}.photonT==results{k}.photonT
%&& ((strcmp(results_graph{l}.modality, '2D') && results{k}.dim3D==0)...
%|| (~strcmp(results_graph{l}.modality, '2D') && results{k}.dim3D==1))
notFound = false;
else
l = l + 1;
if l > initLen && length(results_graph)==initLen
%results_graph{end+1} = struct;
for fn = fieldnames(results_graph{l-1})'
results_graph{l}.(fn{1}) = deal(nan(size(results_graph{l}.(fn{1}))));
end
end
end
end
if isempty(results{k}.wobble_file)
wobble_file = 'NaN';
else
wobble_file = results{k}.wobble_file;
end
fprintf(fileID,formatSpec,date,results{k}.test_fname,...
results{k}.dataset, results{k}.dataset(end-1:end), results{k}.modality,...
results{k}.wobble,wobble_file,...
results{k}.radTolXY,results{k}.radTolZ,...
results{k}.border,results{k}.dim3D,results{k}.gt_fname,...
results{k}.test_fname,results{k}.nloc_gt_initial,results{k}.nloc_test_initial,...
results{k}.Nerrorline,min(results{k}.loc(:,1)),max(results{k}.loc(:,1)),...
min(results{k}.loc(:,4)),max(results{k}.loc(:,4)),results{k}.photonT,...
results{k}.TP,results{k}.FP,results{k}.FN,...
results{k}.Jaccard,results{k}.Fscore,results{k}.recall,results{k}.precision,...
results{k}.RMSExyz,results{k}.RMSExy,results{k}.RMSEz,...
results{k}.MADxyz,results{k}.MADxy,results{k}.MADz,results{k}.distX,...
results{k}.distY,results{k}.distZ,results{k}.corrPhoton,...
results{k}.FSC,results{k}.FRC{1},results{k}.FRC{2},results{k}.FRC{3},...
results{k}.SNR{1},results{k}.SNR{2},...
results{k}.SNR{3},results{k}.SNR{4},...
results_mol{k}.TPmol,results_mol{k}.FNmol,...
results_mol{k}.recall_mol,...
results_mol{k}.RMSExyz_mol,results_mol{k}.RMSExy_mol,results_mol{k}.RMSEz_mol,...
results_mol{k}.MADxyz_mol,results_mol{k}.MADxy_mol,results_mol{k}.MADz_mol,...
results_mol{k}.ratio_det_per_mol_ave,...
results_graph{l}.min_z_range_metric(1, 1),...
results_graph{l}.max_z_range_metric(1, 1),...
results_graph{l}.meanRMSExy_onRangeZ(1, 1),...
results_graph{l}.stdRMSExy_onRangeZ(1, 1),...
results_graph{l}.meanRMSExy_onRangeZ(1, 1)...
+results_graph{l}.stdRMSExy_onRangeZ(1, 1),...
results_graph{l}.CVRMSExy_onRangeZ(1, 1),...
results_graph{l}.meanRMSEz_onRangeZ(1, 1),...
results_graph{l}.stdRMSEz_onRangeZ(1, 1),...
results_graph{l}.meanRMSEz_onRangeZ(1, 1)...
+results_graph{l}.stdRMSEz_onRangeZ(1, 1),...
results_graph{l}.CVRMSEz_onRangeZ(1, 1),...
results_graph{l}.min_z_range_metric(1, 2),...
results_graph{l}.max_z_range_metric(1, 2),...
results_graph{l}.meanRMSExy_onRangeZ(1, 2),...
results_graph{l}.stdRMSExy_onRangeZ(1, 2),...
results_graph{l}.meanRMSExy_onRangeZ(1, 2)...
+results_graph{l}.stdRMSExy_onRangeZ(1, 2),...
results_graph{l}.CVRMSExy_onRangeZ(1, 2),...
results_graph{l}.meanRMSEz_onRangeZ(1, 2),...
results_graph{l}.stdRMSEz_onRangeZ(1, 2),...
results_graph{l}.meanRMSEz_onRangeZ(1, 2)...
+results_graph{l}.stdRMSEz_onRangeZ(1, 2),...
results_graph{l}.CVRMSEz_onRangeZ(1, 2),...
results_graph{l}.min_z_range_metric(3, 1),...
results_graph{l}.max_z_range_metric(3, 1),...
results_graph{l}.meanRMSExy_onRangeZ(3, 1),...
results_graph{l}.stdRMSExy_onRangeZ(3, 1),...
results_graph{l}.meanRMSExy_onRangeZ(3, 1)...
+results_graph{l}.stdRMSExy_onRangeZ(3, 1),...
results_graph{l}.CVRMSExy_onRangeZ(3, 1),...
results_graph{l}.meanRMSEz_onRangeZ(3, 1),...
results_graph{l}.stdRMSEz_onRangeZ(3, 1),...
results_graph{l}.meanRMSEz_onRangeZ(3, 1)...
+results_graph{l}.stdRMSEz_onRangeZ(3, 1),...
results_graph{l}.CVRMSEz_onRangeZ(3, 1),...
results_graph{l}.min_z_range_metric(3, 2),...
results_graph{l}.max_z_range_metric(3, 2),...
results_graph{l}.meanRMSExy_onRangeZ(3, 2),...
results_graph{l}.stdRMSExy_onRangeZ(3, 2),...
results_graph{l}.meanRMSExy_onRangeZ(3, 2)...
+results_graph{l}.stdRMSExy_onRangeZ(3, 2),...
results_graph{l}.CVRMSExy_onRangeZ(3, 2),...
results_graph{l}.meanRMSEz_onRangeZ(3, 2),...
results_graph{l}.stdRMSEz_onRangeZ(3, 2),...
results_graph{l}.meanRMSEz_onRangeZ(3, 2)...
+results_graph{l}.stdRMSEz_onRangeZ(3, 2),...
results_graph{l}.CVRMSEz_onRangeZ(3, 2),...
results_graph{l}.range_metric(1,1),...
results_graph{l}.range_metric(1,2),...
results_graph{l}.range_metric(3,1),...
results_graph{l}.range_metric(3,2),...
results_graph{l}.max_metric(1),...
results_graph{l}.min_z_FWHM_metric(1),...
results_graph{l}.max_z_FWHM_metric(1),...
results_graph{l}.FWHM(1),...
results_graph{l}.max_metric(3),...
results_graph{l}.min_z_FWHM_metric(3),...
results_graph{l}.max_z_FWHM_metric(3),...
results_graph{l}.FWHM(3),...
results_graph{l}.metric_thres(1,1),...
results_graph{l}.metric_thres(1,2),...
results_graph{l}.metric_thres(3,1),...
results_graph{l}.metric_thres(3,2));
end
fclose(fileID);
fprintf('The assessment results are saved in the file %s\n',fname);
end
function results_graph = fill_results_graph(results)
res_len = length(results);
results_graph = cell(res_len,1);
for l = 1:res_len
results_graph{l}.dim3D = results{l}.dim3D;
results_graph{l}.photonT = results{l}.photonT;
results_graph{l}.wobble = results{l}.wobble;
results_graph{l}.participant = results{l}.participant;
results_graph{l}.dataset = results{l}.dataset;
results_graph{l}.modality = results{l}.modality;
results_graph{l}.min_z_range_metric = nan(3,2);
results_graph{l}.max_z_range_metric = nan(3,2);
results_graph{l}.meanRMSExy_onRangeZ = nan(3,2);
results_graph{l}.stdRMSExy_onRangeZ = nan(3,2);
results_graph{l}.CVRMSExy_onRangeZ = nan(3,2);
results_graph{l}.meanRMSEz_onRangeZ = nan(3,2);
results_graph{l}.stdRMSEz_onRangeZ = nan(3,2);
results_graph{l}.CVRMSEz_onRangeZ = nan(3,2);
results_graph{l}.metric_thres = nan(3,2);
results_graph{l}.metric_thres = nan(3,2);
results_graph{l}.range_metric = nan(3,2);
results_graph{l}.max_metric = nan(3,1);
results_graph{l}.min_z_FWHM_metric = nan(3,1);
results_graph{l}.max_z_FWHM_metric = nan(3,1);
results_graph{l}.FWHM = nan(3,1);
end
end | MATLAB |
2D | SMLM-Challenge/Challenge2016 | Assessment/Matlab/importLocations.m | .m | 2,519 | 67 | function [VarName27,VarName28,VarName29,VarName30,VarName31] = importLocations(filename, startRow, endRow)
%IMPORTFILE Import numeric data from a text file as column vectors.
% [VARNAME27,VARNAME28,VARNAME29,VARNAME30,VARNAME31] =
% IMPORTFILE(FILENAME) Reads data from text file FILENAME for the default
% selection.
%
% [VARNAME27,VARNAME28,VARNAME29,VARNAME30,VARNAME31] =
% IMPORTFILE(FILENAME, STARTROW, ENDROW) Reads data from rows STARTROW
% through ENDROW of text file FILENAME.
%
% Example:
% [VarName27,VarName28,VarName29,VarName30,VarName31] = importfile('pairings____MT1.N1.LD____AS____CSpline____wobble_no____border_450____photonT_1974____date_04-May-2017____dim3D_1____nFeat_5.csv',1, 16411);
%
% See also TEXTSCAN.
% Auto-generated by MATLAB on 2017/08/15 10:21:36
%% Initialize variables.
delimiter = ',';
if nargin<=2
startRow = 1;
endRow = inf;
end
%% Format string for each line of text:
% column27: double (%f)
% column28: double (%f)
% column29: double (%f)
% column30: double (%f)
% column31: double (%f)
% For more information, see the TEXTSCAN documentation.
formatSpec = '%*q%*q%*q%*q%*q%*q%*q%*q%*q%*q%*q%*q%*q%*q%*q%*q%*q%*q%*q%*q%*q%*q%*q%*q%*q%*q%f%f%f%f%f%[^\n\r]';
%% Open the text file.
fileID = fopen(filename,'r');
%% Read columns of data according to format string.
% This call is based on the structure of the file used to generate this
% code. If an error occurs for a different file, try regenerating the code
% from the Import Tool.
dataArray = textscan(fileID, formatSpec, endRow(1)-startRow(1)+1, 'Delimiter', delimiter, 'EmptyValue' ,NaN,'HeaderLines', startRow(1)-1, 'ReturnOnError', false);
for block=2:length(startRow)
frewind(fileID);
dataArrayBlock = textscan(fileID, formatSpec, endRow(block)-startRow(block)+1, 'Delimiter', delimiter, 'EmptyValue' ,NaN,'HeaderLines', startRow(block)-1, 'ReturnOnError', false);
for col=1:length(dataArray)
dataArray{col} = [dataArray{col};dataArrayBlock{col}];
end
end
%% Close the text file.
fclose(fileID);
%% Post processing for unimportable data.
% No unimportable data rules were applied during the import, so no post
% processing code is included. To generate code which works for
% unimportable data, select unimportable cells in a file and regenerate the
% script.
%% Allocate imported array to column variable names
VarName27 = dataArray{:, 1};
VarName28 = dataArray{:, 2};
VarName29 = dataArray{:, 3};
VarName30 = dataArray{:, 4};
VarName31 = dataArray{:, 5};
| MATLAB |
2D | SMLM-Challenge/Challenge2016 | Assessment/Matlab/gauss_render.m | .m | 2,493 | 88 | function im = gauss_render(data, sig, pix_size, im_size,doCorr)
% data : list of particles Nparticles x 2-3 => (x,y)+z (opt) (nm)
% sig : sigma (nm) for each dimension
% pix_size
% im_size, size of obtained image
% varargin{1} : do the Z correction or not
D = size(data,2);
for k=1:D
if k==3 && doCorr
data(:,k) = data(:,k) + im_size(k)/2*pix_size;%start z_min @ 0
end
%locations below 0 set @ 0, above max_size set @ the limit, should they
%be rather removed ?
%set
%data(:, k) = max(0,min(im_size(k)*pix_size,data(:,k)));
%removed : useful for dispOrthoView of zoomed area
data(data(:, k) < 0 | data(:, k) > im_size(k)*pix_size,:) = [];
end
if length(im_size)~=D
fprintf('Image dimension not equal to the data dimension...\n');
return;
end
if length(pix_size)==1
pix_size = repmat(pix_size,D,1);
end
sig = sig./pix_size;
data = data./repmat(pix_size, 1, size(data,1))';
ind_data = ceil(data);
ind_data(ind_data==0) = 1;%border case
offset = data - ind_data + 0.5;
for k = 1:length(sig)
marg(k) = ceil(3*sig(k));
pos(k,:) = -marg(k):marg(k);
end
im = zeros(im_size + 2*marg);
gr = cell(D,1);
%tmp = tic;
for ii=1:size(data,1)
for jj=1:D
gr{jj} = gauss_kernel(offset(ii,jj), sig(jj), pos(jj,:));
end
GR = ktensor(gr);
if D==2
im(marg(1) + ind_data(ii,1) + pos(1,:),...
marg(2) + ind_data(ii,2) + pos(2,:)) = ...
im(marg(1) + ind_data(ii,1) + pos(1,:),...
marg(2) + ind_data(ii,2) + pos(2,:)) + GR;
else %D==3 normally
try
im(marg(1) + ind_data(ii,1) + pos(1,:),...
marg(2) + ind_data(ii,2) + pos(2,:),...
marg(3) + ind_data(ii,3) + pos(3,:)) =...
im(marg(1) + ind_data(ii,1) + pos(1,:),...
marg(2) + ind_data(ii,2) + pos(2,:),...
marg(3) + ind_data(ii,3) + pos(3,:)) + GR;
catch ME
fprintf('%i\n',ii);
end
end
end
if D==2
im = im(1 + marg(1):end-marg(1), 1 + marg(2):end-marg(2));
else
im = im(1 + marg(1):end-marg(1), 1 + marg(2):end-marg(2),1 + marg(3):end-marg(3));
end
%fprintf('Gaussian rendering...%1.2f s\n',toc(tmp));
end
function im = gauss_kernel(offset,sig,pos)
im = exp(-(offset - pos).^2/(2*sig^2));%/(sqrt(2*pi)*sig);
end
function GR = ktensor(gr)
if length(gr)==2
GR = kron(gr{1}, gr{2}');
else
GRXY = kron(gr{1}, gr{2}');
GR = arrayfun(@(z) z*GRXY,gr{3},'UniformOutput',false);
GR = cat(3,GR{:});
end
end | MATLAB |
2D | SMLM-Challenge/Challenge2016 | Assessment/Matlab/main_brut_loc_plot.m | .m | 2,393 | 65 | %% Load Brut loc
locup = dir(fullfile(software,'standard',sprintf('%s____%s____%s*',...
dataset,modality,software)));
%header = textscan(fullfile(software,'upload',locup(1).name),'Delimiter',',',0,0);
locup = csvread(fullfile(software,'standard',locup(1).name),1,0);
locup = array2table(locup(:,1:end),'VariableNames',{'frame' 'x' 'y' 'z' 'int'});
%%
sigmin = 20/(2*sqrt(2*log(2)));
sigmax = 20/(2*sqrt(2*log(2)));
thresmax = quantile(locup.int,0.95);
thresmin = quantile(locup.int,0.05);
sig_locup = max(min((locup.int - thresmin)/(thresmax - thresmin),1),0);
sig_locup = sigmax + (sigmin - sigmax).*sqrt(sig_locup);
%sig_locup = sigmin + sig_locup./sqrt(locup.int);
%Get "density map" invers. prop. to sqrt(estimated intensity), see sig exp.
[im_locup] = gauss_render_intensity([locup.x,locup.y,locup.z] - repmat(shift,height(locup),1),...
sig_locup, pix_size, imsize,doCorr);
%%
tic
im2Dcolored = depthcolor3D(im_gt,'jet',0.99,3);
toc
figure;
imagesc(im2Dcolored);
%% Display 2D XZ view
curr_im = squeeze(sum(im_locup,2))';
figure;
imagesc(vecx,vecz, curr_im);colormap hot
title(sprintf('XZ view brut, %s %s %s',software,modality,dataset),'FontSize',16);
axis image;
%% XY
figure;
imagesc(vecx,vecy,sum(im_locup,3));colormap hot;
title(sprintf('XY view brut, %s %s %s',software,modality,dataset),'FontSize',16);
axis image;
%% YZ
figure;
imagesc(vecy,vecz,squeeze(sum(im_locup,1))');colormap hot;
title(sprintf('YZ view, %s %s %s',software,modality,dataset),'FontSize',16);
%caxis([quantile(curr_im(:),0.01),quantile(curr_im(:),0.999)])
axis image;
%% for color coded scatter
[fig_h_locup,circSize_locup,color_locup,loc_rm] = disp3D([locup.frame,...
locup.x,locup.y,locup.z,locup.int] - repmat([0,shift,0],height(locup),1),sprintf('%s %s %s brut',dataset, software,modality),im_locup,pix_size);
loc_rm = array2table(loc_rm,'VariableNames',locup.Properties.VariableNames);
%%
thresmax = quantile(loc_rm.int,0.95);
thresmin = quantile(loc_rm.int,0.05);
sig_locrm = max(min((loc_rm.int - thresmin)/(thresmax - thresmin),1),0);
sig_locrm = sigmax + (sigmin - sigmax).*sqrt(sig_locrm);
%% Disp brut loc
figure;
scatter3(loc_rm.y,loc_rm.x,loc_rm.z,10,color_locup,'filled');
view(0,90);
set(gcf,'Color','black');
xlim([0,fov(1)]);ylim([0,fov(2)]);
axis off;
%%
javaaddpath('/Applications/MATLAB_R2016a.app/java/mij.jar')
javaaddpath('/Applications/MATLAB_R2016a.app/java/ij.jar') | MATLAB |
2D | SMLM-Challenge/Challenge2016 | Assessment/Matlab/main_cmp_RMSEz_vs_z.m | .m | 3,724 | 103 | %% LOAD RMSEz vs z from one software for all modalities and plot them
clear data
software = 'SMAP';%'SMAP';%'MIATool';
photonT = true;
dataset = 'MT3.N2.LD';
modalities = {'AS','BP','DHNPC'};
metrics = {'Jaccard','RMSEloc z','RMSEloc xy'};
path = fullfile('assessment_results',software);
fdname = metrics;
for kk = 1:length(modalities)
for ll = 1:length(metrics)
curr_path = fullfile(path,modalities{kk},'data');
curr_data = dir(fullfile(curr_path,...
sprintf('%s %s vs Z %s %s photons T %s.csv',...
software,metrics{ll},dataset,modalities{kk},...
strcat(photonT*'*',~photonT*'0'))));
curr_data = csvread(fullfile(curr_path,curr_data(1).name));
fdname{ll} = strrep(metrics{ll},' ','');
data.(modalities{kk}).(fdname{ll}).z = curr_data(:,1);
if size(curr_data,2) < 3
data.(modalities{kk}).(fdname{ll}).metrics = curr_data(:,2);
else
data.(modalities{kk}).(fdname{ll}).metricsnowobble = curr_data(:,2);
data.(modalities{kk}).(fdname{ll}).metrics = curr_data(:,3);
end
end
end
%% Plot
binAVG = 5;
color_set.AS = [0.8,0,0];
color_set.DHNPC = [0,0.8,0];
color_set.BP = [0,0,0.8];
fdname{4} = 'efficiency_RMSExyz';
%fdname{5} = 'efficiency_RMSExy';
LS_set.(fdname{1}) = '-'; LS_set.(fdname{2}) = '-'; LS_set.(fdname{3}) = '-';
LS_set.(fdname{4}) = '-';% LS_set.(fdname{5}) = '-';
Xlim = [-750,750];
Ylim.(fdname{1}) = [0,100];
Ylim.(fdname{2}) = [0,200];
Ylim.(fdname{3}) = [0,100];
Ylim.(fdname{4}) = [0,100];
%Ylim.(fdname{5}) = [0,100];
alp = [0.5,1];
%str_leg = {};
for ll = length(fdname)
figure;%(9 + ll);
clf;hold all;
for kk = 1:length(modalities)
if ll > length(metrics)
efficiency.(modalities{kk}) = 100 ...
- sqrt((100 - data.(modalities{kk}).Jaccard.metrics).^2 ...
+ (data.(modalities{kk}).RMSElocxy.metrics.^2 + (0.5*data.(modalities{kk}).RMSElocz.metrics).^2));
%+ alp(ll - length(metrics))^2 ...
%* data.(modalities{kk}).(fdname{1 + ll - length(metrics)}).metrics.^2);
% plot(data.(modalities{kk}).(fdname{1}).z,...
% efficiency.(modalities{kk}),...
% 'Color',color_set.(modalities{kk}),...
% 'LineStyle',LS_set.(fdname{1}),...
% 'LineWidth',1);
tmp = reshape(efficiency.(modalities{kk}),binAVG,...
length(efficiency.(modalities{kk}))/binAVG);
tmp = repelem(nanmean(tmp),6);
tmp = tmp([2:end,end]);
plot(data.(modalities{kk}).(fdname{1}).z(sort([1:end,5:5:end])),...
tmp,...
'Color',color_set.(modalities{kk}),...
'LineStyle',LS_set.(fdname{1}),...
'LineWidth',1.5);
else
plot(data.(modalities{kk}).(fdname{ll}).z,...
data.(modalities{kk}).(fdname{ll}).metrics,...
'Color',color_set.(modalities{kk}),...
'LineStyle',LS_set.(fdname{ll}),...
'LineWidth',1.5);
%str_leg{end+1} = sprintf('%s %s',modalities{kk},fdname{ll});
%plot(data.(modalities{kk}).(fdname{ll}).z,...
% data.(modalities{kk}).(fdname{ll}).metricsnowobble,'--');
%str_leg{end+1} = sprintf('%s %s no wobble',modalities{kk},fdname{ll});
end
end
grid on;box on;
set(gca,'XLim',Xlim,'YLim',Ylim.(fdname{ll}));
tmp = gca; tmp.XAxis.FontSize = 18;tmp.YAxis.FontSize = 18;
title(sprintf('%s %s %s',software,dataset,fdname{ll}),'FontSize',18);
%legend(str_leg);
str_leg = {};
end
| MATLAB |
2D | SMLM-Challenge/Challenge2016 | Assessment/Matlab/savePublic_old.m | .m | 9,792 | 194 | function savePublic_old(results, results_mol, results_graph,res_folder)
%SAVEPUBLIC_OLD save results in public.csv
for k=1:length(results)
strMod{k} = results{k}.modality;
end
strMod = unique(strMod);
fname = 'public.csv';
if isempty(results_graph)
results_graph = fill_results_graph(results);
end
initLen = length(results_graph);
for m=1:length(strMod)
fileID = fopen(strcat(res_folder,filesep,...
results{1}.participant,filesep, strMod{m},filesep,fname),'w');
formatSpec = strcat('%s,%s,%s,%s,%f,%f,%i,%i,%i,%i,%i,',...%FN
'%f,%f,%f,%f,%f,%f,%f,%f,%f,%f,%f,%f,%f,',...%Dz
'%f,%f,%f,%f,%f,%f,%f,%f,%f,',...%SNRxy
'%f,%f,%f,%f,%f,%f,%f,%f,%f,%f,',...%Detection ratio_mol
'%f,%f,%f,',...%FWDM ( RMSE)
'%f,%f,%f,%f,%f,%f,',...%Thres (RMSE)
'%f,%f,%f,',...%Z max Jaccard
'%f,%f,%f,',...%max jaccard
'%f,%f,%f,',...%FWHM Jaccard
'%f,%f,%f,%f,%f,%f,',...%max Z range FWHM Jaccard
'%f,%f,%f,',...%FWHM Jaccard Thres
'%f,%f,%f,%f,%f,%f,',...%max Z range thres Jaccard
'%f,%f,%f,',...
'%f,%f,%f,%f,%f','\n');%Thres Jaccard\n');
fprintf(fileID,strcat('Dataset,Density,',...
'Modality,','Wobble,','TolXY,','TolZ,',...
'# Fluorophores Test,','Thres Photon,',...
'TP,','FP,','FN,','Jaccard,','F-Score,','Recall,','Precision,',...
'RMSExyz,','RMSExy,','RMSEz,',...
'MADxyz,','MADxy,','MADz,',...
'Dx,','Dy,','Dz,','Corr. photons,',...
'FSC,','FRCyz,','FRCxz,','FRCxy,',...
'SNRxyz,','SNRyz,','SNRxz,','SNRxy,',...
'TP_mol,','FN_mol,','Recall_mol,','RMSExyz_mol,','RMSExy_mol,','RMSEz_mol,',...
'MADxyz_mol,','MADxy_mol,','MADz_mol,',...
'Detection ratio_mol,',...
'Z min RMSE,','min RMSE,','FWDM (RMSE),',...
'min Z range FWDM (RMSE),','max Z range FWDM (RMSE),','FWDM Thres (RMSE),',...
'min Z range Thres (RMSE),','max Z range Thres (RMSE),','Thres (RMSE),',...
'Z max recall,','Z max precision,','Z max Jaccard,',...
'max recall,','max precision,','max Jaccard,',...
'FWHM recall,','FWHM precision,','FWHM Jaccard,',...
'min Z range FWHM recall,','max Z range FWHM recall,',...
'min Z range FWHM precision,','max Z range FWHM precision,',...
'min Z range FWHM Jaccard,','max Z range FWHM Jaccard,',...
'Range recall Thres,','Range precision Thres,','Range Jaccard Thres,',...
'min Z range thres recall,','max Z range thres recall,',...
'min Z range thres precision,','max Z range thres precision,',...
'min Z range thres Jaccard,','max Z range thres Jaccard,',...
'Thres recall,','Thres precision,','Thres Jaccard,',...
'Z min fitted RMSE,','min fitted RMSE,','FWDM (RMSE) fitted,',...
'min Z range FWDM (RMSE) fitted,','max Z range FWDM (RMSE) fitted','\n'));
for k=1:length(results)
l=1;
notFound = true;
while l <= initLen && notFound
if strcmp(results_graph{l}.modality, results{k}.modality)...
&& strcmp(results_graph{l}.dataset, results{k}.dataset)...
&& strcmp(results_graph{l}.participant, results{k}.participant)...
&& strcmp(results_graph{l}.wobble, results{k}.wobble)...
&& results_graph{l}.photonT==results{k}.photonT...
&& ((strcmp(results_graph{l}.modality, '2D') && results{k}.dim3D==0)...
|| (~strcmp(results_graph{l}.modality, '2D') && results{k}.dim3D==1))
notFound = false;
else
l = l + 1;
if l > initLen && length(results_graph)==initLen
for fn = fieldnames(results_graph{l-1})'
results_graph{l}.(fn{1}) = results_graph{l-1}.(fn{1});
for n = 1:numel(results_graph{l}.(fn{1}))
try
results_graph{l}.(fn{1})(n) = nan;
end
end
end
end
end
end
if strcmp(results{k}.modality,strMod{m})
fprintf(fileID,formatSpec,...
results{k}.dataset,results{k}.dataset(end-1:end),...
results{k}.modality,results{k}.wobble,...
results{k}.radTolXY,results{k}.radTolZ,...
results{k}.nloc_test_initial,...
results{k}.photonT,...
results{k}.TP,results{k}.FP,results{k}.FN,...
results{k}.Jaccard,results{k}.Fscore,results{k}.recall,results{k}.precision,...
results{k}.RMSExyz,results{k}.RMSExy,results{k}.RMSEz,...
results{k}.MADxyz,results{k}.MADxy,results{k}.MADz,results{k}.distX,...
results{k}.distY,results{k}.distZ,results{k}.corrPhoton,...
results{k}.FSC,results{k}.FRC{1},results{k}.FRC{2},results{k}.FRC{3},...
results{k}.SNR{1},results{k}.SNR{2},...
results{k}.SNR{3},results{k}.SNR{4},...
results_mol{k}.TPmol,results_mol{k}.FNmol,...
results_mol{k}.recall_mol,...
results_mol{k}.RMSExyz_mol,results_mol{k}.RMSExy_mol,results_mol{k}.RMSEz_mol,...
results_mol{k}.MADxyz_mol,results_mol{k}.MADxy_mol,results_mol{k}.MADz_mol,...
results_mol{k}.ratio_det_per_mol_ave,...
results_graph{l}.z_min_RMSE,results_graph{l}.min_RMSE,results_graph{l}.FWDM,...
results_graph{l}.z_range_FWDM(1),results_graph{l}.z_range_FWDM(2),...
results_graph{l}.FWDM_T, results_graph{l}.z_range_T_RMSE(1),...
results_graph{l}.z_range_T_RMSE(2),results_graph{l}.RMSE_thres,...
results_graph{l}.z_max_metric(1),results_graph{l}.z_max_metric(2),results_graph{l}.z_max_metric(3),...
results_graph{l}.max_metric(1),results_graph{l}.max_metric(2),results_graph{l}.max_metric(3),...
results_graph{l}.FWHM(1),results_graph{l}.FWHM(2),results_graph{l}.FWHM(3),...
results_graph{l}.z_range_FWHM(1,1),results_graph{l}.z_range_FWHM(1,2),...
results_graph{l}.z_range_FWHM(2,1),results_graph{l}.z_range_FWHM(2,2),...
results_graph{l}.z_range_FWHM(3,1),results_graph{l}.z_range_FWHM(3,2),...
results_graph{l}.FWHM_T(1),results_graph{l}.FWHM_T(2),results_graph{l}.FWHM_T(3),...
results_graph{l}.z_range_T_metric(1,1),results_graph{l}.z_range_T_metric(1,2),...
results_graph{l}.z_range_T_metric(2,1),results_graph{l}.z_range_T_metric(2,2),...
results_graph{l}.z_range_T_metric(3,1),results_graph{l}.z_range_T_metric(3,2),...
results_graph{l}.metric_thres(1),results_graph{l}.metric_thres(2),results_graph{l}.metric_thres(3),...
results_graph{l}.z_min_fitted,results_graph{l}.min_fitted,...
results_graph{l}.FWDM_fitted,results_graph{l}.z_range_FWDM_fitted(1),results_graph{l}.z_range_FWDM_fitted(2));
end
end
fclose(fileID);
end
fprintf('The public assessment results are saved in the file %s in different modality folders\n',fname);
end
function results_graph = fill_results_graph(results)
res_len = length(results);
results_graph = cell(res_len,1);
for l = 1:res_len
results_graph{l}.dim3D = results{l}.dim3D;
results_graph{l}.photonT = results{l}.photonT;
results_graph{l}.wobble = results{l}.wobble;
results_graph{l}.participant = results{l}.participant;
results_graph{l}.dataset = results{l}.dataset;
results_graph{l}.modality = results{l}.modality;
results_graph{l}.z_min_RMSE = nan;
results_graph{l}.min_RMSE = nan;
results_graph{l}.FWDM = nan;
results_graph{l}.z_range_FWDM(1) = nan;
results_graph{l}.z_range_FWDM(2) = nan;
results_graph{l}.FWDM_T = nan;
results_graph{l}.z_range_T_RMSE(1) = nan;
results_graph{l}.z_range_T_RMSE(2) = nan;
results_graph{l}.RMSE_thres = nan;
results_graph{l}.z_max_metric(1) = nan;
results_graph{l}.z_max_metric(2) = nan;
results_graph{l}.z_max_metric(3) = nan;
results_graph{l}.max_metric(1) = nan;
results_graph{l}.max_metric(2) = nan;
results_graph{l}.max_metric(3) = nan;
results_graph{l}.FWHM(1) = nan;
results_graph{l}.FWHM(2) = nan;
results_graph{l}.FWHM(3) = nan;
results_graph{l}.z_range_FWHM(1,1) = nan;
results_graph{l}.z_range_FWHM(1,2) = nan;
results_graph{l}.z_range_FWHM(2,1) = nan;
results_graph{l}.z_range_FWHM(2,2) = nan;
results_graph{l}.z_range_FWHM(3,1) = nan;
results_graph{l}.z_range_FWHM(3,2) = nan;
results_graph{l}.FWHM_T(1) = nan;
results_graph{l}.FWHM_T(2) = nan;
results_graph{l}.FWHM_T(3) = nan;
results_graph{l}.z_range_T_metric(1,1) = nan;
results_graph{l}.z_range_T_metric(1,2) = nan;
results_graph{l}.z_range_T_metric(2,1) = nan;
results_graph{l}.z_range_T_metric(2,2) = nan;
results_graph{l}.z_range_T_metric(3,1) = nan;
results_graph{l}.z_range_T_metric(3,2) = nan;
results_graph{l}.metric_thres(1) = nan;
results_graph{l}.metric_thres(2) = nan;
results_graph{l}.metric_thres(3) = nan;
results_graph{l}.z_min_fitted = nan;
results_graph{l}.min_fitted = nan;
results_graph{l}.FWDM_fitted = nan;
results_graph{l}.z_range_FWDM_fitted(1) = nan;
results_graph{l}.z_range_FWDM_fitted(2) = nan;
results_graph{l}.z_max_fitted(1) = nan;
results_graph{l}.z_max_fitted(2) = nan;
results_graph{l}.z_max_fitted(3) = nan;
results_graph{l}.max_fitted(1) = nan;
results_graph{l}.max_fitted(2) = nan;
results_graph{l}.max_fitted(3) = nan;
end
end | MATLAB |
2D | SMLM-Challenge/Challenge2016 | Assessment/Matlab/loc_metrics.m | .m | 6,566 | 210 | function [out,pairings,fig_corr] = loc_metrics(testPos, truePos, radTol, pairings, dim3D, varargin)
%EVALUATION localization assessment with radius tolerance radTol
% INSPIRED BY JAVA CODE OF LOCALIZATION AVAILABLE ON 2016 ISBI CHALLENGE WEBSITE
% Provides usual metrics such as recall, precision, etc.
% Follows Sage's definition
% positions are N molecules x 3 vectors with columns for frame, indx & indy
% in nm
% varargin : 'name', value
% 'index' : indices for param.frames, param.indx and param.indy (struct
% expected)
% Output : Metrics with max values are 1 except for accuracy, distX and distY (nm)
% pairings between reference and tested positions
% NOTE : If dim3D -> 2 tolerances (XY & Z) and rmse XYZ used for comparison
% If ~dim3D -> 1 tolerance (XY) and rmse XY used for comparison
% Written by Thanh-an Pham, 2016
param = struct;
radTolZ = inf;
for k=1:length(radTol)
if k==1
radTolXY = radTol(k);
elseif k==2 && dim3D
radTolZ = radTol(k);
end
end
out.radTolXY = radTolXY;
out.radTolZ = radTolZ;
colPhotons = 6;
out.thresPhotons = 0;
k=1;
while k <= nargin - 5
switch varargin{k}
case 'index'
param = varargin{k+1};
case 'estFluor'
out.estFluor4metrics = varargin{k+1};
case 'trueFluor'
out.trueFluor4metrics = varargin{k+1};
case 'thresPhotons'
out.thresPhotons = varargin{k+1};
case 'colPhotons'
colPhotons = varargin{k+1};
end
k = k+2;
end
nFeat = size(testPos, 2);
pairings = [pairings, nan(size(pairings,1), nFeat)];
if isempty(fieldnames(param))
param.frames = 1;
param.indx = 2;
param.indy = 3;
param.indz = 4;
end
nframes = max(truePos(:, param.frames));
A = cell(nframes,1);%REFERENCE
B = cell(nframes,1);%TEST
TPframe = zeros(nframes,1);
Na = zeros(nframes,1);
Nb = zeros(nframes,1);
RMSExy = 0;
RMSEz = 0;
RMSExyz = 0;
MADxy = 0;
MADz = 0;
MADxyz = 0;
dX = 0;
dY = 0;
dZ = 0;
iter_pair = 0;
for k=1:nframes
%fprintf('%i,',k);
A{k} = truePos(truePos(:,param.frames) == k, [param.indx,param.indy,param.indz]);%REFERENCE
B{k} = testPos(testPos(:,param.frames) == k, :);%TEST
Na(k) = size(A{k},1);
Nb(k) = size(B{k},1);
[distXYZ,distXY, distX, distY, distZ] = arrayfun(@(x,y,z) distEuc(x, y, z,...
B{k}(:,[param.indx,param.indy,param.indz])),...
A{k}(:,1), A{k}(:,2), A{k}(:,3),'UniformOutput',false);
if dim3D
distMat = distXYZ;
else
distMat = distXY;
end
distMat = reshape(cell2mat(distMat),[Nb(k),Na(k)]);
distX = reshape(cell2mat(distX),[Nb(k),Na(k)]);
distY = reshape(cell2mat(distY),[Nb(k),Na(k)]);
distZ = reshape(cell2mat(distZ),[Nb(k),Na(k)]);
distXYZ = reshape(cell2mat(distXYZ),[Nb(k),Na(k)]);
distXY = reshape(cell2mat(distXY),[Nb(k),Na(k)]);
done = isempty(distMat);
while ~done
[~, ind] = min(distMat(:));
if distXY(ind) <= radTolXY %comme dans java
if abs(distZ(ind)) <= radTolZ
[row, col] = ind2sub(size(distMat), ind);
pairings(iter_pair + col, end-nFeat + 1:end) = B{k}(row,:);
if pairings(iter_pair + col, colPhotons) > out.thresPhotons
RMSExyz = RMSExyz + distXYZ(ind)^2;
RMSExy = RMSExy + distXY(ind)^2;
RMSEz = RMSEz + distZ(ind)^2;
dX = dX + distX(ind);
dY = dY + distY(ind);
dZ = dZ + distZ(ind);
MADxyz = MADxyz + abs(distX(ind)) + abs(distY(ind)) + abs(distZ(ind));
MADxy = MADxy + abs(distX(ind)) + abs(distY(ind));
MADz = MADz + abs(distZ(ind));
TPframe(k) = TPframe(k) + 1;
end
distMat(row,:) = nan; distMat(:,col) = nan;
distZ(row,:) = nan; distZ(:,col) = nan;
distXY(row,:) = nan; distXY(:,col) = nan;
done = all(isnan(distMat(:)));
elseif min(abs(distZ(:))) > radTolZ
done = true;
else %might still have some points acceptable
distMat(ind) = nan;
distZ(ind) = nan;
distXY(ind) = nan;
end
elseif min(distXY(:)) > radTolXY
done = true;
else %might still have some points acceptable, should never be reached
distMat(ind) = nan;
distZ(ind) = nan;
distXY(ind) = nan;
end
end
iter_pair = iter_pair + Na(k);
end
if ~isfield(out,'trueFluor4metrics')
out.trueFluor4metrics = sum(Na);
end
if ~isfield(out,'estFluor4metrics')
out.estFluor4metrics = sum(Nb);
end
%Threshold on photon
ThresfluorCountGT = sum(pairings(:, colPhotons) <= out.thresPhotons);
%Remove from FP count the localizations paired with photon-thresholded GT fluors
ThresfluorCountTest = sum(pairings(:, colPhotons) <= out.thresPhotons & ~isnan(pairings(:,end)));
pairings = pairings(pairings(:, colPhotons) > out.thresPhotons,:);
TP = sum(TPframe);
FN = out.trueFluor4metrics - TP - ThresfluorCountGT;
FP = out.estFluor4metrics - TP - ThresfluorCountTest;
recall = TP/(TP + FN);
precision = TP/(TP + FP);
Fscore = 2*precision*recall/(precision + recall);
Jaccard = TP/(FN + FP + TP);
out.RMSExy = sqrt(RMSExy/TP);
out.RMSEz = sqrt(RMSEz/TP);
out.RMSExyz = sqrt(RMSExyz/TP);
out.MADxy = MADxy/TP;
out.MADz = MADz/TP;
out.MADxyz =MADxyz/TP;
out.dim3D = dim3D;
out.estFluorFrame = Nb;
out.trueFluorFrame = Na;
out.TPframe = TPframe;
out.FNframe = Nb - TPframe;
out.FPframe = Na - TPframe;
out.TP = TP;
out.FN = FN;
out.FP = FP;
out.recall = recall;
out.precision = precision;
out.Fscore = Fscore;
out.Jaccard = Jaccard*100;%percentage
out.distX = dX/TP;
out.distY = dY/TP;
out.distZ = dZ/TP;
%coeff correlation # photons
if all(isnan(pairings(:,end)))
out.corrPhoton = 0;
else
out.corrPhoton = corr(pairings(~isnan(pairings(:,end)),6),...
pairings(~isnan(pairings(:,end)),end));
end
fig_corr = figure;
scatter(pairings(~isnan(pairings(:,end)),6),...
pairings(~isnan(pairings(:,end)),end),1,'filled');hold on;
xlabel('Emitted photons - Ground truth');
ylabel('Emitted photons - Software');
id = 1:max(pairings(~isnan(pairings(:,end)),6));
plot(id, id,'black');
end
function [distXYZ, distXY, diffX, diffY, diffZ] = distEuc(x,y,z,pos)
diffX = pos(:,1) - x;
diffY = pos(:,2) - y;
diffZ = pos(:,3) - z;
distXYZ = sqrt(diffX.^2 + diffY.^2 + diffZ.^2);
distXY = sqrt(diffX.^2 + diffY.^2);
end
| MATLAB |
2D | SMLM-Challenge/Challenge2016 | Assessment/Matlab/main_PerfvsTolRadius.m | .m | 3,775 | 120 | %% Plot the performance vs radius tolerance curves
clear pos
path = '~/Dropbox/smlm/figures/';
software = 'MIATool-RMS';%'SMAP'
modality = 'AS';
dataset = 'MT1.N1.LD';
wobble = false;
photonT = true;
%File must be in the path
if wobble
fname = dir(fullfile('assessment_results',software,...
sprintf('pairings____%s____%s____%s____wobble_%s____border_450____photonT_*',...
dataset,modality,software,'beads')));
if isempty(fname)
fname = dir(fullfile('assessment_results',software,...
sprintf('pairings____%s____%s____%s____wobble_%s____border_450____photonT_*',...
dataset,modality,software,'file')));
end
if isempty(fname)
error('No file found');
end
else
fname = dir(fullfile('assessment_results',software,...
sprintf('pairings____%s____%s____%s____wobble_%s____border_450____photonT_*',...
dataset,modality,software,'no')));
end
iter = 0;
for kk = 1:length(fname)
if ~isempty(strfind(fname(kk - iter).name,'photonT_0_'))
fname(kk - iter) = [];
iter = iter + 1;
end
end
fname = fullfile('assessment_results',software,fname(1).name);
fprintf('Reading file %s\n',fname);
%% Load files
pairings = importFullPairings(fname);
pairings = pairings(:,[1:24,27:end]);
pairings.Properties.VariableNames = {'ID','X','Y','Z','Frame','Photons',...
'Channel','Frame_ON','Total','Background_Mean','Background_Stdev',...
'Signal_Mean','Signal_Stdev','Signal_Peak','Sigma_X','Sigma_Y','Sigma_Z',...
'Uncertainty','Closest_ID','Closest_Distance','Closest_Count','CNR',...
'SNR','PSNR','FrameSoft','XSoft','YSoft','ZSoft','PhotonsSoft'};
res = importPublicRes(fullfile('assessment_results',software,modality,'public.csv'));
res = res(2:end,:);
%% Calculate distance
dist2D = sqrt((pairings.X - pairings.XSoft).^2 + (pairings.Y - pairings.YSoft).^2);
if strcmp(modality,'2D')
dist = dist2D;
else
dist = dist2D + (pairings.Z - pairings.ZSoft).^2;
end
dist = sqrt(dist);
[sort_dist,ind_sort] = sort(dist);
%% Compute the metrics wrt lateral tolerance
TolRad = 0:250;
Npoints = length(TolRad);
R = height(pairings);
ind_res = strcmpi(res.Dataset,dataset) ...
& strcmpi(res.Modality,modality) ...
& xor(wobble,strcmpi(res.Wobble,'no'))...
& xor(photonT>0,res.ThresPhoton==0);
S = res.TP(ind_res) + res.FP(ind_res);
alp = 1;
TP = zeros(Npoints,1); Recall = TP; FP = TP; Precision=TP;
JAC=TP;RMSE2D =TP; Efficiency = TP;MAD2D = TP;
for kk = 1:Npoints
curr_mol = dist2D <= TolRad(kk);
TP(kk) = nnz(curr_mol);
FP(kk) = S - TP(kk);
Recall(kk) = TP(kk)/R;
Precision(kk) = TP(kk)/S;
JAC(kk) = TP(kk)/(S + R - TP(kk));
RMSE2D(kk) = sqrt(mean(dist2D(curr_mol).^2));
MAD2D(kk) = mean(abs(pairings.X(curr_mol) - pairings.XSoft(curr_mol))...
+ abs(pairings.Y(curr_mol) - pairings.YSoft(curr_mol)));
Efficiency(kk) = 100 - sqrt((100 - 100*JAC(kk))^2 + (alp*RMSE2D(kk))^2);
end
%%
siz = 2;
figure(10);
plot(TolRad,Recall,'LineWidth',siz);hold on;
plot(TolRad,Precision,'LineWidth',siz);
plot(TolRad,JAC,'LineWidth',siz);
title('Recall, Precision & Jaccard Index');
xlabel('Tolerance Radius [nm]');
ylabel('Metrics');
legend('Recall','Precision','Jaccard Index','Location','Best');
axis([0,250,0,1]);
hold off;
figure(11);
plot(TolRad,RMSE2D,'LineWidth',siz);
title('RMSE');
xlabel('Tolerance Radius [nm]');
ylabel('RMSE [nm]');
axis([0,250,0,150]);
figure(12);
plot(TolRad,Efficiency,'LineWidth',siz);hold on;
plot(TolRad,100*JAC,'LineWidth',siz);
plot(TolRad,RMSE2D,'LineWidth',siz);hold off;
title('Efficiency');
xlabel('Tolerance Radius [nm]');
ylabel('Efficiency, Jaccard Index, RMSE');
legend('Efficiency', 'Jaccard Index', 'RMSE','Location','Best');
%axis([0,250,0,150]);
%%
figure(13)
scatter3(TolRad,JAC,RMSE2D); | MATLAB |
2D | SMLM-Challenge/Challenge2016 | Assessment/Matlab/assessment_frame.m | .m | 12,706 | 299 | function perf_metrics = assessment_frame(param_input)
%ASSESSMENT Performance assessment for SMLM Challenge 2016
% INPUT
% param_input : parameters structure
% OUTPUT
% perf_metrics : structure regrouping the performance assessment results
% and Gaussian rendered of gt and res in addition
% Written by Thanh-an Pham, 2016
%% Parameters initialization
fov = param_input.fov;%nm, field of view
pix_siz = param_input.pix_siz;%nm, pixel size for rendering
radTol = param_input.radTol;%nm, XY tolerance radius (circle)
exclusion = param_input.exclusion;%nm, exclusion of results from the border
int_thres = param_input.int_thres;%percentage for thresholded intensity (wrt maximum per frame ?) or absolute value
sig = param_input.FWHM/(2*sqrt(2*log(2)));%nm, sigma for Gaussian rendering (expect the FWHM)
saveFig = param_input.saveFig;
files_path = fullfile(param_input.participant,'standard');%String, path/folder name containing the results
test_name = param_input.test_name;%String, name of the results file
splitPos = strfind(test_name,'____');
dataset_name = test_name(1:splitPos(1)-1);
modality = test_name(splitPos(1)+4:splitPos(2)-1);
participant = test_name(splitPos(2)+4:splitPos(3)-1);
gt_fname = fullfile('Ground_truth',dataset_name,'activations.csv');
doFSC = param_input.doFSC && ~strcmp(modality,'2D');
detail_fname = fullfile('Ground_truth',dataset_name, strcat(modality,...
('-Exp'*~strcmp(modality,'BP') + '-250'*strcmp(modality,'BP'))*~strcmp(modality,'DHNPC')),...
'oracle', 'activation-snr.csv');
res.res_path = fullfile(param_input.result_folder, participant);
if exist(res.res_path,'dir') && param_input.firstTime
%means a previous run (files) might exist, must rename the folder
k = 1; done = false;
while ~done
folder_name = [res.res_path,'_attempt_', num2str(k)];
if ~exist(folder_name,'dir')
movefile(res.res_path, folder_name);
done = true;
end
k = k + 1;
end
clear k
mkdir(param_input.result_folder, participant);
end
if ~exist(fullfile(res.res_path, modality),'dir')
mkdir(res.res_path, modality);
mkdir(fullfile(res.res_path, modality),'png');
mkdir(fullfile(res.res_path, modality),'data');
end
%copy converter to public folder
participant_tmp = participant;
participant_tmp(strfind(participant_tmp,'-')) = '';%filename cannot have this character
copyfile(fullfile('code','converter',sprintf('convert_%s.m', participant_tmp)),...
fullfile(res.res_path, modality));
%copy index.html to public folder
%copyfile('index.html',fullfile(res.res_path, modality));
%% Data reading
res.loc = csvread(fullfile(files_path, test_name));%participant localizations : frame,x,y,z,photons
gt = csvread(gt_fname,1,1);%activation.csv : frame,xyz,intensity (first column ignored)
pairings = dlmread(detail_fname);%activation-snr.csv
%% Assessment settings
%Check wobble setting
if param_input.wobble %boolean to deactivate wobble
fileID = fopen(fullfile(participant,'upload','wobble.txt'),'r');
res.wobble = fscanf(fileID,'%s');
switch res.wobble
case 'no'
fprintf('No wobble correction required\n');
res.wobble_file = [];
wobble_corr = [];
case 'file'
fprintf('Wobble correction loaded from uploaded file...\n');
w=1;
while w<=length(param_input.wobble_files)
if ~isempty(strfind(param_input.wobble_files(w).name,...
strcat('Wobble____',modality,'____',participant)))
wob_file = param_input.wobble_files(w).name;
w=inf;
end
w = w+1;
end
try
wobble_corr = csvread(fullfile(param_input.participant,'upload',wob_file));
catch
wobble_corr = csvread(fullfile(param_input.participant,'upload',wob_file),1,0);
end
fprintf([' ',wob_file,'\n']);
res.wobble_file = fullfile(files_path, wob_file);
case 'beads'
fprintf('Wobble correction calculated from uploaded (standardized) beads localization\n');
w=1;
while w <= length(param_input.beads_files)
if ~isempty(strfind(param_input.beads_files(w).name,...
strcat('Beads____',modality,'____',participant)))
beads_file = param_input.beads_files(w).name;
w = inf;
end
w = w+1;
end
wobble_fname = ['wobble____',modality,'____',participant,'.csv'];
zmin = -750;zmax = 750;zstep = 10;roiRadius = 500;%nm
beads_loc = csvread(fullfile(files_path, beads_file),0,0);
beads_gt = csvread(fullfile('Ground_truth','Beads','activations.csv'));
beads_gt = unique(beads_gt(:,3:4),'rows');
xnm = beads_loc(:,2); ynm = beads_loc(:,3); frame = beads_loc(:,1);
%not used, because makes it worse for ThunderSTORM
%[xnm, ynm, frame] = simBeadLocCorr(beads_loc(:,2),...
% beads_loc(:,3), beads_loc(:,1), beads_gt);%indices should be the same
wobbleCorrectSimBead(xnm,ynm,frame,beads_gt,zmin,zstep,zmax,...
roiRadius,fullfile(res.res_path,wobble_fname));
wobble_corr = csvread(fullfile(res.res_path, wobble_fname));
fprintf([' ',beads_file,'\n']);
res.wobble_file = fullfile(res.res_path,wobble_fname);
otherwise
error('Error in reading wobble.txt');
end
fclose(fileID);
if ~isempty(wobble_corr)
%copy wobble csv file to public folder
csvwrite(fullfile(res.res_path,modality,...
sprintf('Wobble____%s.csv',participant)), wobble_corr);
zdiff = arrayfun(@(x) abs(x - gt(:,4)), wobble_corr(:,end),'UniformOutput',false);
zdiff = squeeze(cat(3,zdiff{:}));
[~, ind_zdiff] = min(zdiff,[],2);
gt(:,2:3) = gt(:,2:3) + wobble_corr(ind_zdiff,1:2);
zdiff = arrayfun(@(x) abs(x - pairings(:,4)), wobble_corr(:,end),'UniformOutput',false);
zdiff = squeeze(cat(3,zdiff{:}));
[~, ind_zdiff] = min(zdiff,[],2);
pairings(:,2:3) = pairings(:,2:3) + wobble_corr(ind_zdiff,1:2);
end
else
res.wobble = 'no';
res.wobble_file = [];
end
res.nloc_gt_initial = size(gt,1);
res.nloc_test_initial = size(res.loc,1);
if saveFig
%Orthoview before border/photon exclusion
close all
save_folder = fullfile(res.res_path,'figures', 'orthoview');
if ~exist(fullfile(save_folder,'eps'),'dir')...
|| ~exist(fullfile(save_folder,'png'),'dir')...
|| ~exist(fullfile(res.res_path, 'figures', '3D'),'dir')
mkdir(save_folder,'eps');
mkdir(save_folder,'png');
mkdir(fullfile(res.res_path,'figures', '3D'),'eps');
mkdir(fullfile(res.res_path,'figures', '3D'),'png');
end
fname_orth = sprintf('%s %s %s wobble %s',participant,dataset_name,modality,res.wobble);
ortho_loc = res.loc(:,2:4);
ortho_gt = gt(:,2:4);
switch dataset_name(1:2)
case 'ER'
if strcmp(dataset_name(3),'1')
cubeArea = [2850 950 -750 param_input.ofov];%5540 2730
elseif strcmp(dataset_name(3),'2')
cubeArea = [2160 1250 -750 param_input.ofov];
end
case 'MT'
cubeArea = [param_input.oPos, param_input.ofov];
end
[Iref, Iest] =...
im_metrics(ortho_loc, ortho_gt, sig,...
pix_siz,fov/pix_siz,0,0,0,'renderOnly',true);
im3D = Iest{1};%for 3D below
h1 = dispOrthoView(fname_orth,Iest,Iref,[],...
'cube',cubeArea./pix_siz,'2D',strcmp(modality,'2D'));
%Zoomed area
ortho_loc = ortho_loc - repmat(cubeArea(1:3),[res.nloc_test_initial,1]);
ortho_gt = ortho_gt - repmat(cubeArea(1:3),[res.nloc_gt_initial,1]);
[Iref, Iest] =...
im_metrics(ortho_loc, ortho_gt, 2*sig/pix_siz*param_input.opix_siz, param_input.opix_siz,...
param_input.ofov/param_input.opix_siz,0,0,0,'renderOnly',true,'doCorr',false);
h2 = dispOrthoView([fname_orth,' zoom'], Iest, Iref,[],'2D',strcmp(modality,'2D'));
h1.InvertHardcopy = 'off';
h2.InvertHardcopy = 'off';
saveas(h1,fullfile(save_folder,'eps',[fname_orth,'.eps']),'epsc');
saveas(h1,fullfile(save_folder,'png',[fname_orth,'.png']),'png');
saveas(h1,fullfile(res.res_path,modality,'png',[fname_orth,'.png']),'png');
fname_orth = strcat(fname_orth,'_zoom');
saveas(h2,fullfile(save_folder,'eps',[fname_orth,'.eps']),'epsc');
saveas(h2,fullfile(save_folder,'png',[fname_orth,'.png']),'png');
saveas(h2,fullfile(res.res_path,modality,'png',[fname_orth,'.png']),'png');
%3D
if ~strcmp(modality,'2D')
fname_3D = sprintf('%s %s %s wobble %s',participant,dataset_name,modality,res.wobble);
fig3D = disp3D(res.loc,fname_3D,im3D,pix_siz);
fname_3D = sprintf('%s____%s____%s____wobble____%s____3D',participant,dataset_name,modality,res.wobble);
saveas(fig3D{1},fullfile(res.res_path,'figures', '3D',...
'eps',[fname_3D,'.eps']),'epsc');
saveas(fig3D{1},fullfile(res.res_path,'figures', '3D',...
'png',[fname_3D,'.png']),'png');
saveas(fig3D{2},fullfile(res.res_path,'figures', '3D',...
'eps',[fname_3D,'_noProj','.eps']),'epsc');
saveas(fig3D{2},fullfile(res.res_path, 'figures', '3D',...
'png',[fname_3D,'_noProj','.png']),'png');
saveas(fig3D{1},fullfile(res.res_path,modality,...
'png',[fname_3D,'.png']),'png');
saveas(fig3D{2},fullfile(res.res_path,modality,...
'png',[fname_3D,'_noProj','.png']),'png');
end
end
%Exclusion of activations at the border (exclusion) for gt(s) & res.loc
gt = gt(gt(:,2) > exclusion & gt(:,3) > exclusion...
& gt(:,2) < fov(1) - exclusion & gt(:,3) < fov(2) - exclusion,:);
res.nloc_gt_after_exclusion = size(gt,1);
pairings = pairings(pairings(:,2) > exclusion & pairings(:,3) > exclusion...
& pairings(:,2) < fov(1) - exclusion & pairings(:,3) < fov(2) - exclusion,:);
res.loc = res.loc(res.loc(:,2) > exclusion & res.loc(:,3) > exclusion...
& res.loc(:,2) < fov(1) - exclusion & res.loc(:,3) < fov(2) - exclusion,:);
res.nloc_test_after_exclusion = size(res.loc,1);
res.border = exclusion;%nm excluded
%Photons Threshold
if int_thres==0
res.photonTperc = 0;
res.photonT = 0;
elseif int_thres > 1 %absolute value
%gt = gt(gt(:,5) > int_thres,:);
%pairings = pairings(pairings(:,6) > int_thres,:);
res.photonT = int_thres;
else %percentage
res.photonT = floor(quantile(gt(:,5),int_thres));
res.photonTperc = int_thres;%quantile percentage
%gt = gt(gt(:,5) > res.photonT,:);
%pairings = pairings(pairings(:,6) > res.photonT,:);
end
%% Pairing & performance evaluation (localization based metrics)
[perf_metrics, pairings,fig_corr] = loc_metrics(res.loc, gt, radTol, pairings,...
param_input.dim3D,'trueFluor',res.nloc_gt_after_exclusion,...
'estFluor',res.nloc_test_after_exclusion,'thresPhotons',res.photonT);%'index'
saveas(fig_corr,fullfile(res.res_path, modality,...
'png',sprintf('photon correlation %s %s %i %s.png',dataset_name,modality,res.photonT,res.wobble)));
%% Image based metrics
[~,~,perf_metrics.SNR, perf_metrics.FRC, perf_metrics.FSC] =...
im_metrics(res.loc(:,2:4), gt(:,2:4), sig, pix_siz,...
fov/pix_siz,param_input.winLen,param_input.areaCenter,doFSC);
%copy fields res to perf_metrics'
for fn = fieldnames(res)'
perf_metrics.(fn{1}) = res.(fn{1});
end
%% Regrouping all the results (and photon correlations) and save
perf_metrics.dataset = dataset_name;
perf_metrics.participant = participant;
perf_metrics.modality = modality;
perf_metrics.gt_fname = gt_fname;
perf_metrics.test_fname = test_name;
perf_metrics.Nerrorline = str2double(test_name(strfind(test_name,'____Nerror_')+11:strfind(test_name,'____Nfluor')-1));
perf_metrics.nFeatInPairings = size(res.loc,2);
perf_metrics.pairings = pairings;
perf_metrics.winLen = param_input.winLen;
perf_metrics.areaCenter = param_input.areaCenter;
perf_metrics.fov = fov;
fname = sprintf('pairings____%s____%s____%s____wobble_%s____border_%i____photonT_%i____date_%s____dim3D_%i____nFeat_%i.csv',...
dataset_name, modality, participant,perf_metrics.wobble,...
perf_metrics.border,perf_metrics.photonT,...
date,1*perf_metrics.dim3D, perf_metrics.nFeatInPairings);
dlmwrite(fullfile(res.res_path,fname),...
pairings,'precision','%5.3f');
perf_metrics.fname_pairings = fname;
close all
end
| MATLAB |
2D | SMLM-Challenge/Challenge2016 | Assessment/Matlab/assessment_main.m | .m | 6,802 | 169 | %% ASSESSMENT PROGRAM (MAIN) NOT THE MOST RECENT (SEE ASSESSMENT_MAIN_AUTOMATIC.M)
% ASSESSMENT SCRIPT written by Thanh-an Pham (EPFL): 12-Jul-2016
% Expect standardized input files in folder 'participant_name/standard'
% converted by participant-specific converter script "convert_(participant_name).m"
%% Parameters
clear
param_input.fov = [6400, 6400, 1500];%nm, Field Of View
param_input.radTol = [250,500];%nm, (XY and Z)
param_input.pix_siz = 10;%nm, pixel size for rendering
param_input.FWHM = 20;%nm, rendering with Gaussian convolution (FWHM)
param_input.winLen = 5120;%nm, window length XY for FSC
param_input.areaCenter = [3200,3200];%nm, area center for window in FSC
param_input.exclusion = 450;%nm, border exclusion
param_input.opix_siz = 2;%nm, orthoview zoomed pixel size
param_input.oPos = [1920,1920,-750];%(X,Y,Z) = (top, left, bottom),nm for MT
param_input.ofov = [1280,1280,1500];%nm
param_input.doFSC = false;%do FSC or not
param_input.saveFig = false;%save Orthoview (& 3D) or not
param_input.result_folder = 'test_photon';
param_input.participant = 'TVSTORM';
%below overwritten in for boucles
%param_input.int_thres = 0;%percentage or absolute value
%param_input.dim3D = true;%boolean false (true) for pairing distance: rmseXY (rmseXYZ) and tolerance XY (+ Z)
%param_input.wobble = true;
%% Settings
fnames = dir([param_input.participant,filesep,'standard',filesep,'MT*']);
fnames = [fnames;dir([param_input.participant,filesep,'standard',filesep,'ER*'])];
intensity = [0,0.15,0.25,0.35,0.45];%,0.25];%photon counts below to exclude (e.g. 0.1 => 90% are kept)
dim3D = [true];
wobble = [true,false];
nSettings = length(intensity)*length(dim3D)*length(wobble);
fprintf('%i dataset(s), %i setting(s) per dataset => %i run(s)\n',length(fnames),nSettings,nSettings*length(fnames));
param_input.wobble_files = dir([param_input.participant,filesep,'upload',filesep,'Wobble*']);
param_input.beads_files = dir([param_input.participant,filesep,'standard',filesep,'Beads*']);
maxCounter = 1;%choose a divider of nSettings*length(fnames) (e.g. multiple of 2)
lenPart = nSettings*length(fnames)/maxCounter;
%% Assessment for one participant's files ---Frame & Molecule based---
param_input.firstTime = true;%for folder existence verification
results = cell(lenPart,1);
results_mol = results;
overalltimer = tic;
l = 1;counter = 1;
for int_iter = 1:length(intensity)
for dim3D_iter = 1:length(dim3D)
for wobble_iter = 1:length(wobble)
for k = 1:length(fnames)
dataset_timer = tic;
param_input.int_thres = intensity(int_iter);
param_input.dim3D = dim3D(dim3D_iter);
param_input.wobble = wobble(wobble_iter);
param_input.test_name = fnames(k).name;
results{l} = assessment_frame(param_input);
%only requires name
results_mol{l} = assessment_mol(results{l}.res_path,...
results{l}.fname_pairings);
fprintf('Time for dataset/settings %i : %1.3f s\n',(counter-1)*lenPart + l,toc(dataset_timer));
param_input.firstTime = false;
l = l + 1;
if l > lenPart && maxCounter > 1 %memory trouble ? One mat file > 700mb
save(sprintf('%s____results_part_%i.mat',param_input.participant,counter),'results','results_mol','-v7.3');
l = 1;
counter = counter + 1;
end
end
end
end
end
fprintf('Assessment done for %s in %f\n',param_input.participant,toc(overalltimer))
%% Regroup in one variable
if maxCounter > 1
results = cell(nSettings*length(fnames),1);
results_mol = results;
for k = 1:maxCounter
tmp = load(sprintf('%s____results_part_%i.mat',param_input.participant,k));
results(1+(k-1)*lenPart:k*lenPart) = tmp.results;
results_mol(1+(k-1)*lenPart:k*lenPart) = tmp.results_mol;
end
clear tmp
end
fprintf('Results loaded and regrouped\n');
%% Figures production
%uncomment only if necessary, can super slow down (due to matlab 2016)
%addpath(genpath([param_input.result_folder,filesep,param_input.participant]));
filesOI = dir([param_input.result_folder,filesep,param_input.participant,filesep,'pairings*']);
Nfiles = length(filesOI);
modalSet = [];dataSet = [];wobSet = [];
intSet = cell(2,1); intSet{1} = 0;
for ii = 1:Nfiles
sep = strfind(filesOI(ii).name,'____');
strDataset = filesOI(ii).name(sep(1)+4:sep(2)-1);
if isempty(find(strcmp(strDataset,dataSet),1))
dataSet{end+1} = strDataset;
end
strMod = filesOI(ii).name(sep(2)+4:sep(3)-1);
if isempty(find(strcmp(strMod,modalSet),1))
modalSet{end+1} = strMod;
end
strInt = str2double(filesOI(ii).name(strfind(filesOI(ii).name,'photonT_')+8:sep(7)-1));
if ~ismember(strInt,intSet{2}) && strInt~=0
intSet{2} = [intSet{2}, strInt];
end
strWob = filesOI(ii).name(strfind(filesOI(ii).name,'wobble_')+7:sep(5)-1);
if isempty(find(strcmp(strWob,wobSet),1))
wobSet{end+1} = strWob;
end
end
if isempty(intSet{2})
intSet(2) = [];
end
NphotonSettings = numel(intSet);
%only wobble on/off is shown on same graph
NelPerFig = numel(wobSet);
if mod(NelPerFig,1)~=0
error('Number of files in results incorrect');
end
input = cell(NelPerFig,1);
m = 1;
clear results_graph
for ii = 1:length(dataSet)
for jj = 1:length(modalSet)
for k = 1:NphotonSettings
ind_count = 1;
for l = 1:Nfiles
fname = filesOI(l).name;
dim3Dread = str2double(fname(strfind(fname,'____dim3D_')...
+10));
photon_t = str2double(fname(strfind(fname,'____photonT_')...
+12:strfind(fname,'____date')-1));
if ismember(photon_t, intSet{k})...
&& any(strfind(fname, dataSet{ii}))...
&& any(strfind(fname, modalSet{jj}))...
&& ((strcmp(modalSet{jj},'2D') && dim3Dread==0)...
|| (~strcmp(modalSet{jj},'2D') && dim3Dread==1))
input{ind_count} = fname;
ind_count = ind_count + 1;
end
end
results_graph{m} = assessment_graph(input, 'fov', param_input.fov,...
'RMSE',62.5,'metrics', [0.5,0.5,0.4]);%[recall, precision, jaccard]
m = m + 1;
end
end
end
results_graph = cat(2,results_graph{:});
fprintf('Figures saved and additional metrics calculated\n');
%% Save the results file (private and public)
saveResults(results, results_mol, [], param_input.result_folder);
savePublic(results, results_mol, [], param_input.result_folder);
fprintf('Results saved\n');
| MATLAB |
2D | SMLM-Challenge/Challenge2016 | Assessment/Matlab/main_load_4_fig.m | .m | 5,708 | 149 | %% MAIN FOR FIGURE WHEN MAT FILES AVAILABLE
clear
res_fold = 'assessment_results';
participants = dir(pwd);
ind2rm = false(length(participants),1);
for k=1:length(participants)
ind2rm(k) = ~participants(k).isdir...
|| ~exist(fullfile(participants(k).name,'standard'),'dir');
end
participants(ind2rm) = [];
mat_dir = 'mat_files';%folder to save mat files
intensity = [0, 0.25];%photon counts below to exclude (e.g. 0.1 => 90% are kept)
maxCounter = 2;%choose a divider of nSettings*length(fnames) (e.g. multiple of 2)
%%
%parpool(4)
for ll = 1:length(participants)
param_input = [];
param_input.fov = [6400, 6400, 1500];%nm, Field Of View
param_input.radTol = [250,500];%nm, (XY and Z)
param_input.pix_siz = 10;%nm, pixel size for rendering
param_input.FWHM = 20;%nm, rendering with Gaussian convolution (FWHM)
param_input.winLen = 5120;%nm, window length XY for FSC
param_input.areaCenter = [3200,3200];%nm, area center for window in FSC
param_input.exclusion = 450;%nm, border exclusion
param_input.opix_siz = 2;%nm, orthoview zoomed pixel size
param_input.oPos = [1920,1920,-750];%(X,Y,Z) = (top, left, bottom),nm for MT
param_input.ofov = [1280,1280,1500];%nm
param_input.doFSC = false;%do FSC or not
param_input.saveFig = false;%save Orthoview (& 3D) or not
param_input.result_folder = res_fold;
param_input.thresRMSE = 62.5;%250/4
param_input.thresMetrics = [0.25,0.5;0.25,0.5;25,5];%[0.5,0.5,0.5];
param_input.Nsamples_smooth = 5;
param_input.Alpha_smooth = 2;
param_input.participant = participants(ll).name;
%Settings
fnames = dir(fullfile(param_input.participant,'standard','MT*'));
fnames = [fnames;dir(fullfile(param_input.participant,'standard','ER*'))];
param_input.wobble_files = dir(fullfile(param_input.participant,'upload','Wobble*'));
param_input.beads_files = dir(fullfile(param_input.participant,'standard','Beads*'));
%mkdir(mat_dir);
fileID = fopen(fullfile(param_input.participant,'upload','wobble.txt'),'r');
wobble = unique([~strcmp(fscanf(fileID,'%s'),'no'),false]);
nSettings = length(intensity)*length(wobble);
fprintf('%s : %i dataset(s), %i setting(s) per dataset => %i run(s)\n',...
param_input.participant, length(fnames),nSettings,nSettings*length(fnames));
lenPart = nSettings*length(fnames)/maxCounter;
%% Regroup in one variable
if maxCounter > 1
results = cell(nSettings*length(fnames),1);
results_mol = results;
for k = 1:maxCounter
tmp = load(fullfile(mat_dir,sprintf('%s____results_part_%i.mat',param_input.participant,k)));
results(1+(k-1)*lenPart:k*lenPart) = tmp.results;
results_mol(1+(k-1)*lenPart:k*lenPart) = tmp.results_mol;
end
tmp = [];
fprintf('Results loaded and regrouped for %s\n',param_input.participant);
end
%Figures production
%addpath(fullfile(param_input.result_folder,param_input.participant));
filesOI = dir(fullfile(param_input.result_folder,param_input.participant,'pairings*'));
Nfiles = length(filesOI);
modalSet = [];dataSet = [];wobSet = [];
intSet = cell(2,1); intSet{1} = 0;
for ii = 1:Nfiles
sep = strfind(filesOI(ii).name,'____');
strDataset = filesOI(ii).name(sep(1)+4:sep(2)-1);
if isempty(find(strcmp(strDataset,dataSet),1))
dataSet{end+1} = strDataset;
end
strMod = filesOI(ii).name(sep(2)+4:sep(3)-1);
if isempty(find(strcmp(strMod,modalSet),1))
modalSet{end+1} = strMod;
end
strInt = str2double(filesOI(ii).name(strfind(filesOI(ii).name,'photonT_')+8:sep(7)-1));
if ~ismember(strInt,intSet{2}) && strInt~=0
intSet{2} = [intSet{2}, strInt];
end
strWob = filesOI(ii).name(strfind(filesOI(ii).name,'wobble_')+7:sep(5)-1);
if isempty(find(strcmp(strWob,wobSet),1))
wobSet{end+1} = strWob;
end
end
if isempty(intSet{2})
intSet(2) = [];
end
%only wobble on/off is shown on same graph
NelPerFig = numel(wobSet);
if mod(NelPerFig,1)~=0
error('Number of files in results incorrect');
end
input = cell(NelPerFig,1);
m = 1;
results_graph = cell(length(dataSet)*length(modalSet)*length(intSet),1);
for ii = 1:length(dataSet)
for jj = 1:length(modalSet)
for k = 1:length(intSet)
ind_count = 1;
for l = 1:Nfiles
fname = filesOI(l).name;
dim3Dread = str2double(fname(strfind(fname,'____dim3D_')...
+10));
photon_t = str2double(fname(strfind(fname,'____photonT_')...
+12:strfind(fname,'____date')-1));
if ismember(photon_t, intSet{k})...
&& any(strfind(fname, dataSet{ii}))...
&& any(strfind(fname, modalSet{jj}))...
&& ((strcmp(modalSet{jj},'2D') && dim3Dread==0)...
|| (~strcmp(modalSet{jj},'2D') && dim3Dread==1))
input{ind_count} = fname;
ind_count = ind_count + 1;
end
end
if ~all(cellfun(@isempty, input))
results_graph{m} = assessment_graph(input, 'fov', param_input.fov,...
'RMSE', param_input.thresRMSE,'metrics', param_input.thresMetrics,...
'Nsamples_smooth',param_input.Nsamples_smooth,...
'Alpha_smooth',param_input.Alpha_smooth);%[recall; precision; jaccard]
m = m + 1;
input = cell(NelPerFig,1);
end
end
end
end
results_graph = cat(1,results_graph{:});
fprintf('Figures saved and additional metrics calculated\n');
% Save the results file (private and public)
saveResults(results, results_mol, results_graph, res_fold);
savePublic(results, results_mol, results_graph, res_fold);
fprintf('Results saved\n');
end | MATLAB |
2D | SMLM-Challenge/Challenge2016 | Assessment/Matlab/savePublic.m | .m | 10,724 | 207 | function savePublic(results, results_mol, results_graph,res_folder)
%SAVEPUBLIC save results in public.csv
for k=1:length(results)
strMod{k} = results{k}.modality;
end
strMod = unique(strMod);
fname = 'public.csv';
if isempty(results_graph)
results_graph = fill_results_graph(results);
end
initLen = length(results_graph);
for m=1:length(strMod)
fileID = fopen(strcat(res_folder,filesep,...
results{1}.participant,filesep, strMod{m},filesep,fname),'w');
formatSpec = strcat('%s,%s,%s,%s,%f,%f,%i,%i,%i,%i,%i,',...%FN
'%f,%f,%f,%f,%f,%f,%f,%f,%f,%f,%f,%f,%f,',...%Dz
'%f,%f,%f,%f,%f,%f,%f,%f,%f,',...%SNRxy
'%f,%f,%f,%f,%f,%f,%f,%f,%f,%f,',...%Detection ratio_mol
'%f,%f,%f,%f,%f,%f,%f,%f,%f,%f,%f,%f,',...%max_z_range
'%f,%f,%f,%f,%f,%f,%f,%f,%f,%f,%f,%f,',...%stdRMSExy_onRangeZ
'%f,%f,%f,%f,%f,%f,%f,%f,%f,%f,%f,%f,',...%CVRMSExy_onRangeZ
'%f,%f,%f,%f,%f,%f,%f,%f,%f,%f,%f,%f,%f,%f,%f,%f,',...%FWHM Jaccard
'%f,%f,%f,%f,','\n');%T2 Jaccard
fprintf(fileID,strcat('Dataset,Density,',...
'Modality,','Wobble,','TolXY,','TolZ,',...
'# Fluorophores Test,','Thres Photon,',...
'TP,','FP,','FN,','Jaccard,','F-Score,','Recall,','Precision,',...
'RMSExyz,','RMSExy,','RMSEz,',...
'MADxyz,','MADxy,','MADz,',...
'Dx,','Dy,','Dz,','Corr. photons,',...
'FSC,','FRCyz,','FRCxz,','FRCxy,',...
'SNRxyz,','SNRyz,','SNRxz,','SNRxy,',...
'TP_mol,','FN_mol,','Recall_mol,','RMSExyz_mol,','RMSExy_mol,','RMSEz_mol,',...
'MADxyz_mol,','MADxy_mol,','MADz_mol,',...
'Detection ratio_mol,',...
'Min Z Recall T1,','Max Z Recall T1,',...
'Mean RMSExy Recall T1,','STD RMSExy Recall T1,',...
'Mean + STD RMSExy Recall T1,','CV RMSExy Recall T1,',...
'Mean RMSEz Recall T1,','STD RMSEz Recall T1,',...
'Mean + STD RMSEz Recall T1,','CV RMSEz Recall T1,',...
'Min Z Recall T2,','Max Z Recall T2,',...
'Mean RMSExy Recall T2,','STD RMSExy Recall T2,',...
'Mean + STD RMSExy Recall T2,','CV RMSExy Recall T2,',...
'Mean RMSEz Recall T2,','STD RMSEz Recall T2,',...
'Mean + STD RMSEz Recall T2,','CV RMSEz Recall T2,',...
'Min Z Jaccard T1,','Max Z Jaccard T1,',...
'Mean RMSExy Jaccard T1,','STD RMSExy Jaccard T1,',...
'Mean + STD RMSEz Recall T2,','CV RMSExy Jaccard T1,',...
'Mean RMSEz Jaccard T1,','STD RMSEz Jaccard T1,',...
'Mean + STD RMSEz Jaccard T1,','CV RMSEz Jaccard T1,',...
'Min Z Jaccard T2,','Max Z Jaccard T2,',...
'Mean RMSExy Jaccard T2,','STD RMSExy Jaccard T2,',...
'Mean + STD RMSExy Jaccard T2,','CV RMSExy Jaccard T2,',...
'Mean RMSEz Jaccard T2,','STD RMSEz Jaccard T2,',...
'Mean + STD RMSEz Jaccard T2,','CV RMSEz Jaccard T2,',...
'Range Z Recall T1,','Range Z Recall T2,',...
'Range Z Jaccard T1,','Range Z Jaccard T2,',...
'Max Recall,','min Z FWHM Recall,','max Z FWHM Recall,','FWHM Recall,',...
'Max Jaccard,','min Z FWHM Jaccard,','max Z FWHM Jaccard,','FWHM Jaccard,',...
'T1 Recall,','T2 Recall,','T1 Jaccard,','T2 Jaccard,','\n'));
for k=1:length(results)
l=1;
notFound = true;
while l <= initLen && notFound
if strcmp(results_graph{l}.modality, results{k}.modality)...
&& strcmp(results_graph{l}.dataset, results{k}.dataset)...
&& strcmp(results_graph{l}.participant, results{k}.participant)...
&& strcmp(results_graph{l}.wobble, results{k}.wobble)...
&& results_graph{l}.photonT==results{k}.photonT
%&& ((strcmp(results_graph{l}.modality, '2D') && results{k}.dim3D==0)...
%|| (~strcmp(results_graph{l}.modality, '2D') && results{k}.dim3D==1))
notFound = false;
else
l = l + 1;
if l > initLen && length(results_graph)==initLen
for fn = fieldnames(results_graph{l-1})'
results_graph{l}.(fn{1}) = nan(size(results_graph{l}.(fn{1})));
end
end
end
end
if strcmp(results{k}.modality,strMod{m})
fprintf(fileID,formatSpec,...
results{k}.dataset,results{k}.dataset(end-1:end),...
results{k}.modality,results{k}.wobble,...
results{k}.radTolXY,results{k}.radTolZ,...
results{k}.nloc_test_initial,...
results{k}.photonT,...
results{k}.TP,results{k}.FP,results{k}.FN,...
results{k}.Jaccard,results{k}.Fscore,results{k}.recall,results{k}.precision,...
results{k}.RMSExyz,results{k}.RMSExy,results{k}.RMSEz,...
results{k}.MADxyz,results{k}.MADxy,results{k}.MADz,results{k}.distX,...
results{k}.distY,results{k}.distZ,results{k}.corrPhoton,...
results{k}.FSC,results{k}.FRC{1},results{k}.FRC{2},results{k}.FRC{3},...
results{k}.SNR{1},results{k}.SNR{2},...
results{k}.SNR{3},results{k}.SNR{4},...
results_mol{k}.TPmol,results_mol{k}.FNmol,...
results_mol{k}.recall_mol,...
results_mol{k}.RMSExyz_mol,results_mol{k}.RMSExy_mol,results_mol{k}.RMSEz_mol,...
results_mol{k}.MADxyz_mol,results_mol{k}.MADxy_mol,results_mol{k}.MADz_mol,...
results_mol{k}.ratio_det_per_mol_ave,...
results_graph{l}.min_z_range_metric(1, 1),...
results_graph{l}.max_z_range_metric(1, 1),...
results_graph{l}.meanRMSExy_onRangeZ(1, 1),...
results_graph{l}.stdRMSExy_onRangeZ(1, 1),...
results_graph{l}.meanRMSExy_onRangeZ(1, 1)...
+results_graph{l}.stdRMSExy_onRangeZ(1, 1),...
results_graph{l}.CVRMSExy_onRangeZ(1, 1),...
results_graph{l}.meanRMSEz_onRangeZ(1, 1),...
results_graph{l}.stdRMSEz_onRangeZ(1, 1),...
results_graph{l}.meanRMSEz_onRangeZ(1, 1)...
+results_graph{l}.stdRMSEz_onRangeZ(1, 1),...
results_graph{l}.CVRMSEz_onRangeZ(1, 1),...
results_graph{l}.min_z_range_metric(1, 2),...
results_graph{l}.max_z_range_metric(1, 2),...
results_graph{l}.meanRMSExy_onRangeZ(1, 2),...
results_graph{l}.stdRMSExy_onRangeZ(1, 2),...
results_graph{l}.meanRMSExy_onRangeZ(1, 2)...
+results_graph{l}.stdRMSExy_onRangeZ(1, 2),...
results_graph{l}.CVRMSExy_onRangeZ(1, 2),...
results_graph{l}.meanRMSEz_onRangeZ(1, 2),...
results_graph{l}.stdRMSEz_onRangeZ(1, 2),...
results_graph{l}.meanRMSEz_onRangeZ(1, 2)...
+results_graph{l}.stdRMSEz_onRangeZ(1, 2),...
results_graph{l}.CVRMSEz_onRangeZ(1, 2),...
results_graph{l}.min_z_range_metric(3, 1),...
results_graph{l}.max_z_range_metric(3, 1),...
results_graph{l}.meanRMSExy_onRangeZ(3, 1),...
results_graph{l}.stdRMSExy_onRangeZ(3, 1),...
results_graph{l}.meanRMSExy_onRangeZ(3, 1)...
+results_graph{l}.stdRMSExy_onRangeZ(3, 1),...
results_graph{l}.CVRMSExy_onRangeZ(3, 1),...
results_graph{l}.meanRMSEz_onRangeZ(3, 1),...
results_graph{l}.stdRMSEz_onRangeZ(3, 1),...
results_graph{l}.meanRMSEz_onRangeZ(3, 1)...
+results_graph{l}.stdRMSEz_onRangeZ(3, 1),...
results_graph{l}.CVRMSEz_onRangeZ(3, 1),...
results_graph{l}.min_z_range_metric(3, 2),...
results_graph{l}.max_z_range_metric(3, 2),...
results_graph{l}.meanRMSExy_onRangeZ(3, 2),...
results_graph{l}.stdRMSExy_onRangeZ(3, 2),...
results_graph{l}.meanRMSExy_onRangeZ(3, 2)...
+results_graph{l}.stdRMSExy_onRangeZ(3, 2),...
results_graph{l}.CVRMSExy_onRangeZ(3, 2),...
results_graph{l}.meanRMSEz_onRangeZ(3, 2),...
results_graph{l}.stdRMSEz_onRangeZ(3, 2),...
results_graph{l}.meanRMSEz_onRangeZ(3, 2)...
+results_graph{l}.stdRMSEz_onRangeZ(3, 2),...
results_graph{l}.CVRMSEz_onRangeZ(3, 2),...
results_graph{l}.range_metric(1,1),...
results_graph{l}.range_metric(1,2),...
results_graph{l}.range_metric(3,1),...
results_graph{l}.range_metric(3,2),...
results_graph{l}.max_metric(1),...
results_graph{l}.min_z_FWHM_metric(1),...
results_graph{l}.max_z_FWHM_metric(1),...
results_graph{l}.FWHM(1),...
results_graph{l}.max_metric(3),...
results_graph{l}.min_z_FWHM_metric(3),...
results_graph{l}.max_z_FWHM_metric(3),...
results_graph{l}.FWHM(3),...
results_graph{l}.metric_thres(1,1),...
results_graph{l}.metric_thres(1,2),...
results_graph{l}.metric_thres(3,1),...
results_graph{l}.metric_thres(3,2));
end
end
fclose(fileID);
end
fprintf('The public assessment results are saved in the file %s in different modality folders\n',fname);
end
function results_graph = fill_results_graph(results)
res_len = length(results);
results_graph = cell(res_len,1);
for l = 1:res_len
results_graph{l}.dim3D = results{l}.dim3D;
results_graph{l}.photonT = results{l}.photonT;
results_graph{l}.wobble = results{l}.wobble;
results_graph{l}.participant = results{l}.participant;
results_graph{l}.dataset = results{l}.dataset;
results_graph{l}.modality = results{l}.modality;
results_graph{l}.min_z_range_metric = nan(3,2);
results_graph{l}.max_z_range_metric = nan(3,2);
results_graph{l}.meanRMSExy_onRangeZ = nan(3,2);
results_graph{l}.stdRMSExy_onRangeZ = nan(3,2);
results_graph{l}.CVRMSExy_onRangeZ = nan(3,2);
results_graph{l}.meanRMSEz_onRangeZ = nan(3,2);
results_graph{l}.stdRMSEz_onRangeZ = nan(3,2);
results_graph{l}.CVRMSEz_onRangeZ = nan(3,2);
results_graph{l}.metric_thres = nan(3,2);
results_graph{l}.range_metric = nan(3,2);
results_graph{l}.max_metric = nan(3,1);
results_graph{l}.min_z_FWHM_metric = nan(3,1);
results_graph{l}.max_z_FWHM_metric = nan(3,1);
results_graph{l}.FWHM = nan(3,1);
end
end | MATLAB |
2D | SMLM-Challenge/Challenge2016 | Assessment/Matlab/depthcolor3D.m | .m | 1,774 | 74 | function [im2D,T1,T2,T3,L] = depthcolor3D(im,colormapType,t,dim,varargin)
%DEPTHCOLOR3D Color code for depth in 3D image im
%im : 3D intensity image (e.g. 3D Gaussian rendered)
%colormapType : string indicating colormap type (e.g. jet, parula)
%t : quantile for max intensity (0 to 1). Change the scaling of color (and
% brightness)
%Optional input
% maxZ : shift the assigned color to depth
bg = 0;
siz = size(im);
Nz = siz(3);
siz = siz(~ismember(1:3,dim));
%[~,z_pos] = max(im,[],dim);
z_pos = ones(siz);
curr_im2D = zeros(siz);
L = 25;
T1 = 1;
T2 = 0.75;
T3 = 0.2;
if dim==3
for kk = 1:siz(1)
for ll = 1:siz(2)
curr_ind = find(im(kk,ll,:) > T1,1,'last');
if isempty(curr_ind)
curr_ind = find(im(kk,ll,:) > T2,1,'last');
if isempty(curr_ind)
curr_ind = find(im(kk,ll,:) > T3,1,'last');
end
end
if ~isempty(curr_ind)
z_pos(kk,ll) = curr_ind;
curr_im2D(kk,ll) = sum(im(kk,ll,max(curr_ind-L,1):min(curr_ind+L,end)));
end
end
end
elseif dim==1
z_pos = repmat(1:Nz,siz(1),1);
elseif dim==2
z_pos = repmat(1:Nz,siz(1),1);
else
warning('error in dim indication');
end
curr_im2D = squeeze(sum(im,dim));
max_int = quantile(curr_im2D(curr_im2D > 0),t);
if nargin > 4 %shift the color
maxZ = varargin{1};
z_pos = z_pos - Nz/2 + maxZ/2;
else
maxZ = Nz;
end
try
eval(sprintf('curr_color = %s(maxZ);',colormapType));
catch
fprintf('Unknown colormap... Taking Jet colormap.\n');
end
im2D = reshape(curr_color(z_pos(:),:),[siz,3]);
im2D = im2D.*repmat(curr_im2D/max_int,[1,1,3]);
im2D(repmat(curr_im2D==0,[1,1,3])) = bg;
end
| MATLAB |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.