liveDriftCorrectionGUI.java Source code

Java tutorial

Introduction

Here is the source code for liveDriftCorrectionGUI.java

Source

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

import ij.IJ;
import jaolho.data.lma.LMA;
import ij.ImagePlus;
import ij.WindowManager;
import ij.gui.ImageWindow;
import ij.gui.Roi;
import ij.measure.Measurements;
import ij.plugin.frame.RoiManager;
import ij.process.ImageProcessor;
import ij.process.ImageStatistics;
import java.awt.Rectangle;
import java.util.logging.Level;
import java.util.logging.Logger;
import mmcorej.CMMCore;
import org.micromanager.MMStudioMainFrame;
import org.micromanager.api.ScriptInterface;
import org.micromanager.utils.ReportingUtils;
import java.math.BigDecimal;
import java.util.concurrent.atomic.AtomicBoolean;
import mmcorej.DeviceType;
import static org.apache.commons.math.util.MathUtils.round;

/**
 *
 * @author dell
 */
public class liveDriftCorrectionGUI extends javax.swing.JFrame {

    // we are a singleton with only one window
    //public staticScriptInterface app_;
    private final CMMCore core_;
    private MMStudioMainFrame studio_;
    private final String XSTAGE = "PIXStage";
    private final String YSTAGE = "PIYStage";
    private final String ZSTAGE = "PIZStage";
    private final String XYSTAGE = "PIXYStage";
    private double pixelSizeUm_ = 0.16;
    private final ScriptInterface app_;
    private String LOCKINGSTATUS = "OFF";
    public static final String SIMPLE_ACQ = "Snap/Live Window";
    private final double ROISIZE = 12.0;
    AtomicBoolean stopRequested_ = new AtomicBoolean(false);
    AtomicBoolean isRunning_ = new AtomicBoolean(false);
    private double MAX_MOVE_TOLER;
    private double DAMPING;
    private boolean USEFITTING;

    /**
     * Creates new form liveDriftCorrectionGUI
     */
    public liveDriftCorrectionGUI(CMMCore core, ScriptInterface app) {
        app_ = app;
        core_ = core;
        studio_ = MMStudioMainFrame.getInstance();
        initComponents();
        pixelSizeUm_ = Double.valueOf(PixelSizeEdit.getText());
        MAX_MOVE_TOLER = Double.valueOf(MaxMoveToler.getText());
        DAMPING = Double.valueOf(Damping.getText());
        setVisible(true);
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        jTabbedPane6 = new javax.swing.JTabbedPane();
        jButton2 = new javax.swing.JButton();
        xStageInc1 = new javax.swing.JButton();
        jPanel2 = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        PixelSizeEdit = new javax.swing.JTextField();
        jLabel2 = new javax.swing.JLabel();
        MaxMoveToler = new javax.swing.JTextField();
        reverseX = new javax.swing.JRadioButton();
        reverseY = new javax.swing.JRadioButton();
        reverseZ = new javax.swing.JRadioButton();
        jLabel6 = new javax.swing.JLabel();
        Damping = new javax.swing.JTextField();
        swapXY = new javax.swing.JRadioButton();
        jPanel3 = new javax.swing.JPanel();
        jLabel7 = new javax.swing.JLabel();
        yStageInc = new javax.swing.JButton();
        yStageDec = new javax.swing.JButton();
        xStageInc = new javax.swing.JButton();
        xStageDec = new javax.swing.JButton();
        zStageInc = new javax.swing.JButton();
        zStageDec = new javax.swing.JButton();
        jLabel8 = new javax.swing.JLabel();
        jLabel9 = new javax.swing.JLabel();
        stageStepSize = new javax.swing.JTextField();
        jLabel3 = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();
        jPanel4 = new javax.swing.JPanel();
        AddRoiButton = new javax.swing.JButton();
        getPositionOneFrame = new javax.swing.JButton();
        LockButton = new javax.swing.JToggleButton();
        offLineButton = new javax.swing.JButton();
        jLabel5 = new javax.swing.JLabel();

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(jPanel1Layout
                .createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING).addGap(0, 100, Short.MAX_VALUE));
        jPanel1Layout.setVerticalGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGap(0, 100, Short.MAX_VALUE));

        jButton2.setText("jButton2");

        xStageInc1.setFont(new java.awt.Font("", 0, 20)); // NOI18N
        xStageInc1.setText("");
        xStageInc1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                xStageInc1ActionPerformed(evt);
            }
        });

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setBackground(new java.awt.Color(0, 51, 51));

        jPanel2.setBackground(new java.awt.Color(51, 255, 204));

        jLabel1.setText("Pixel Size (um): ");

        PixelSizeEdit.setHorizontalAlignment(javax.swing.JTextField.CENTER);
        PixelSizeEdit.setText("0.16");
        PixelSizeEdit.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                PixelSizeEditActionPerformed(evt);
            }
        });

        jLabel2.setText("Max_Move Toler.(um):");

        MaxMoveToler.setHorizontalAlignment(javax.swing.JTextField.CENTER);
        MaxMoveToler.setText("0.3");
        MaxMoveToler.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                MaxMoveTolerActionPerformed(evt);
            }
        });

        reverseX.setText("reverseX");

        reverseY.setText("reverseY");

        reverseZ.setText("reverseZ");

        jLabel6.setText("Damping Coefficient:");

        Damping.setHorizontalAlignment(javax.swing.JTextField.CENTER);
        Damping.setText("10");
        Damping.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                DampingActionPerformed(evt);
            }
        });

        swapXY.setSelected(true);
        swapXY.setText("swapXY");
        swapXY.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                swapXYActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout
                .setHorizontalGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addGroup(jPanel2Layout.createSequentialGroup().addContainerGap().addGroup(jPanel2Layout
                                .createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                                .addGroup(jPanel2Layout.createSequentialGroup().addGroup(jPanel2Layout
                                        .createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                                        .addComponent(jLabel2, javax.swing.GroupLayout.DEFAULT_SIZE,
                                                javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                        .addComponent(jLabel1, javax.swing.GroupLayout.DEFAULT_SIZE,
                                                javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                        .addGroup(jPanel2Layout
                                                .createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING,
                                                        false)
                                                .addComponent(PixelSizeEdit, javax.swing.GroupLayout.DEFAULT_SIZE,
                                                        42, Short.MAX_VALUE)
                                                .addComponent(MaxMoveToler)))
                                .addGroup(jPanel2Layout.createSequentialGroup().addComponent(jLabel6)
                                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                        .addComponent(Damping)))
                                .addGap(18, 18, 18)
                                .addGroup(
                                        jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                                .addComponent(reverseX, javax.swing.GroupLayout.DEFAULT_SIZE,
                                                        javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                                .addComponent(swapXY, javax.swing.GroupLayout.DEFAULT_SIZE,
                                                        javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                                .addGap(10, 10, 10)
                                .addComponent(reverseY, javax.swing.GroupLayout.DEFAULT_SIZE,
                                        javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                .addGap(10, 10, 10).addComponent(reverseZ, javax.swing.GroupLayout.DEFAULT_SIZE,
                                        javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                .addGap(33, 33, 33)));
        jPanel2Layout.setVerticalGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(jPanel2Layout.createSequentialGroup().addContainerGap().addGroup(jPanel2Layout
                        .createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE).addComponent(jLabel1)
                        .addComponent(PixelSizeEdit, javax.swing.GroupLayout.PREFERRED_SIZE,
                                javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addComponent(reverseX).addComponent(reverseY).addComponent(reverseZ))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                                .addComponent(jLabel2)
                                .addComponent(MaxMoveToler, javax.swing.GroupLayout.PREFERRED_SIZE,
                                        javax.swing.GroupLayout.DEFAULT_SIZE,
                                        javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addComponent(swapXY))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                                .addComponent(jLabel6).addComponent(Damping, javax.swing.GroupLayout.PREFERRED_SIZE,
                                        javax.swing.GroupLayout.DEFAULT_SIZE,
                                        javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addContainerGap(29, Short.MAX_VALUE)));

        jPanel3.setBackground(new java.awt.Color(153, 153, 255));

        jLabel7.setText("X-Y");

        yStageInc.setText("");
        yStageInc.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                yStageIncActionPerformed(evt);
            }
        });

        yStageDec.setText("");
        yStageDec.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                yStageDecActionPerformed(evt);
            }
        });

        xStageInc.setFont(new java.awt.Font("", 0, 20)); // NOI18N
        xStageInc.setText("");
        xStageInc.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                xStageIncActionPerformed(evt);
            }
        });

        xStageDec.setText("?");
        xStageDec.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                xStageDecActionPerformed(evt);
            }
        });

        zStageInc.setText("");
        zStageInc.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                zStageIncActionPerformed(evt);
            }
        });

        zStageDec.setText("");
        zStageDec.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                zStageDecActionPerformed(evt);
            }
        });

        jLabel8.setText("Z");

        jLabel9.setText("StepSize(um)");

        stageStepSize.setText("0.1");
        stageStepSize.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                stageStepSizeActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3);
        jPanel3.setLayout(jPanel3Layout);
        jPanel3Layout.setHorizontalGroup(jPanel3Layout
                .createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(jPanel3Layout.createSequentialGroup().addComponent(jLabel7).addGap(33, 33, 33)
                        .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.CENTER)
                                .addComponent(yStageInc, javax.swing.GroupLayout.PREFERRED_SIZE, 57,
                                        javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addComponent(yStageDec, javax.swing.GroupLayout.PREFERRED_SIZE, 57,
                                        javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addGap(78, 78, 78).addComponent(jLabel8).addGap(18, 18, 18)
                        .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                .addComponent(zStageDec)
                                .addGroup(jPanel3Layout.createSequentialGroup().addComponent(zStageInc)
                                        .addGap(30, 30, 30).addComponent(jLabel9)
                                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                        .addComponent(stageStepSize, javax.swing.GroupLayout.PREFERRED_SIZE, 41,
                                                javax.swing.GroupLayout.PREFERRED_SIZE)))
                        .addGap(0, 52, Short.MAX_VALUE))
                .addGroup(jPanel3Layout.createSequentialGroup().addContainerGap().addComponent(xStageDec)
                        .addGap(49, 49, 49).addComponent(xStageInc)
                        .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)));
        jPanel3Layout.setVerticalGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(jPanel3Layout.createSequentialGroup()
                        .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                .addComponent(jLabel7)
                                .addGroup(jPanel3Layout.createSequentialGroup().addContainerGap()
                                        .addComponent(yStageInc))
                                .addComponent(jLabel8))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                .addComponent(xStageDec).addComponent(xStageInc,
                                        javax.swing.GroupLayout.PREFERRED_SIZE, 24,
                                        javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                                .addComponent(yStageDec).addComponent(zStageDec))
                        .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addGroup(jPanel3Layout.createSequentialGroup().addContainerGap().addGroup(jPanel3Layout
                        .createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE).addComponent(zStageInc)
                        .addComponent(jLabel9).addComponent(stageStepSize, javax.swing.GroupLayout.PREFERRED_SIZE,
                                javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addGap(0, 0, Short.MAX_VALUE)));

        jLabel3.setText("TEST STAGE");

        jLabel4.setText("SET PARAMETERS");

        jPanel4.setBackground(new java.awt.Color(153, 153, 0));

        AddRoiButton.setText("Add Roi");
        AddRoiButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                AddRoiButtonActionPerformed(evt);
            }
        });

        getPositionOneFrame.setText("Get Position");
        getPositionOneFrame.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                getPositionOneFrameActionPerformed(evt);
            }
        });

        LockButton.setText("LockOff");
        LockButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                LockButtonActionPerformed(evt);
            }
        });

        offLineButton.setText("Off Line");
        offLineButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                offLineButtonActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel4Layout = new javax.swing.GroupLayout(jPanel4);
        jPanel4.setLayout(jPanel4Layout);
        jPanel4Layout
                .setHorizontalGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addGroup(jPanel4Layout.createSequentialGroup().addComponent(AddRoiButton)
                                .addGap(10, 10, 10).addComponent(getPositionOneFrame)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                .addComponent(LockButton)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                .addComponent(offLineButton).addGap(0, 0, Short.MAX_VALUE)));
        jPanel4Layout.setVerticalGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(jPanel4Layout.createSequentialGroup().addContainerGap()
                        .addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                                .addComponent(AddRoiButton).addComponent(getPositionOneFrame)
                                .addComponent(LockButton).addComponent(offLineButton))
                        .addContainerGap(38, Short.MAX_VALUE)));

        jLabel5.setText("Drift Correction");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup().addContainerGap()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                .addComponent(jPanel3, javax.swing.GroupLayout.DEFAULT_SIZE,
                                        javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                .addComponent(jPanel4, javax.swing.GroupLayout.DEFAULT_SIZE,
                                        javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                .addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE,
                                        javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                        .addGap(10, 10, 10))
                .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                .addGroup(
                                        layout.createSequentialGroup().addGap(204, 204, 204).addComponent(jLabel5))
                                .addGroup(javax.swing.GroupLayout.Alignment.TRAILING,
                                        layout.createSequentialGroup().addContainerGap().addComponent(jLabel4)
                                                .addGap(7, 7, 7)))
                        .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addGroup(javax.swing.GroupLayout.Alignment.TRAILING,
                        layout.createSequentialGroup()
                                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                .addComponent(jLabel3).addGap(214, 214, 214)));
        layout.setVerticalGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup().addGap(14, 14, 14).addComponent(jLabel5)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jPanel4, javax.swing.GroupLayout.PREFERRED_SIZE,
                                javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED).addComponent(jLabel4)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE,
                                javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED).addComponent(jLabel3)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jPanel3, javax.swing.GroupLayout.PREFERRED_SIZE,
                                javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)));

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void getPositionOneFrameActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_getPositionOneFrameActionPerformed
        ReportingUtils.logMessage("Preview Begin ");
        // TODO add your handling code here:
        float[][] imgData;
        double[] InitParam = { 10000, 4.5, 2, 4.5, 2, 100 };
        // Detect desired ROI in Snap/Live Window
        ImagePlus implus = null;
        ImageWindow win = app_.getSnapLiveWin();
        if (win != null) {
            implus = win.getImagePlus();
        }
        if (implus == null) {
            IJ.log("First snap an image and select ROI to be tracked.");
            return;
        }
        imgData = implus.getProcessor().getFloatArray();
        // get Rois
        Roi[] rois_ = RoiManager.getInstance().getRoisAsArray();
        for (Roi iRois : rois_) {
            LMA lma;
            lma = fitRois(imgData, iRois, InitParam);
            System.out.println("iterations: " + lma.iterationCount);
            System.out.println("chi2: " + lma.chi2 + ",\n" + "param0: " + lma.parameters[0] + ",\n" + "param1: "
                    + lma.parameters[1] + ",\n" + "param2: " + lma.parameters[2] + ",\n" + "param3: "
                    + lma.parameters[3] + ",\n" + "param4: " + lma.parameters[4] + ",\n" + "param5: "
                    + lma.parameters[5]);
        }

    }//GEN-LAST:event_getPositionOneFrameActionPerformed

    private void offLineButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_offLineButtonActionPerformed
        // Initialize parameters     
        final ImagePlus imgPlus;
        LMA lma;
        double[] InitParam = { 10000, 4.5, 2, 4.5, 2, 100 };

        imgPlus = IJ.getImage();
        //Multi Rois
        //Roi[] rois_ = RoiManager.getInstance().getRoisAsArray();

        //Single Roi
        RoiManager RM = RoiManager.getInstance();
        Roi[] rois_ = RM.getSelectedRoisAsArray();
        ReportingUtils.logMessage(String.valueOf(imgPlus.getStackSize()));
        for (int nSlice = 0; nSlice < imgPlus.getStackSize(); nSlice++) {
            imgPlus.setPosition(nSlice + 1);
            imgPlus.setSlice(nSlice + 1);
            for (Roi roi : rois_) {
                imgPlus.setRoi(roi);
                ImageStatistics stats = imgPlus.getStatistics(Measurements.MIN_MAX + Measurements.CENTER_OF_MASS);
                double xPosCoM = stats.xCenterOfMass - roi.getXBase();
                double yPosCoM = stats.yCenterOfMass - roi.getYBase();
                int index = RM.getRoiIndex(roi);
                lma = fitRois(imgPlus.getProcessor().getFloatArray(), roi, InitParam);
                double xPosFit = lma.parameters[1];
                double yPosFit = lma.parameters[3];
                IJ.log("Centroid Postion at Frame: " + String.valueOf(nSlice) + ", Roi " + String.valueOf(index)
                        + ":\n");
                IJ.log("Using Fitting:");
                IJ.log(Double.toString(round(xPosFit, 2, BigDecimal.ROUND_CEILING)) + ", "
                        + Double.toString(round(yPosFit, 2, BigDecimal.ROUND_CEILING)) + ":\n");
                IJ.log("Other parameters: " + Double.toString(round(lma.parameters[0], 2, BigDecimal.ROUND_CEILING))
                        + ", " + Double.toString(round(lma.parameters[2], 2, BigDecimal.ROUND_CEILING)) + ", "
                        + Double.toString(round(lma.parameters[4], 2, BigDecimal.ROUND_CEILING)) + ", "
                        + Double.toString(round(lma.parameters[5], 2, BigDecimal.ROUND_CEILING)) + "\n");
                IJ.log("Using CoM:");
                IJ.log(Double.toString(xPosCoM) + ", " + Double.toString(yPosCoM));
            }

        }

    }//GEN-LAST:event_offLineButtonActionPerformed

    private void LockButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_LockButtonActionPerformed

        try {
            boolean running = isCalibrating();
            if (running) {
                stopCalibration();
                LockButton.setText("Lock Off");
            } else {
                runDriftCorrection();
                LockButton.setText("Lock On");
            }
        } catch (Exception e) {
            ReportingUtils.showError(e);
        }

    }//GEN-LAST:event_LockButtonActionPerformed

    public void runDriftCorrection() {

        if (!isRunning_.get()) {
            stopRequested_.set(false);
            Thread th;
            th = new Thread("Drift Correction thread") {
                @Override
                public void run() {
                    try {
                        isRunning_.set(true);
                        LockButton.setText("Lock On");
                        ImagePlus liveImage;
                        LMA lma;
                        double[] InitParam = { 10000, 4.5, 2.0, 4.5, 2.0, 100 };
                        int NTimePoint = 0;
                        double initXPosition = 0;
                        double initYPosition = 0;
                        double xPosFit, yPosFit;//Position of Fitting
                        double xPosCoM, yPosCoM;//Position of Center of Mass
                        double xPosFinal, yPosFinal;//
                        double PIXELSIZE = Double.parseDouble(PixelSizeEdit.getText());
                        boolean revX = reverseX.isSelected();
                        boolean revY = reverseY.isSelected();
                        boolean swapXYFlag = swapXY.isSelected();
                        IJ.log("Pixel Size:" + String.valueOf(PIXELSIZE));
                        IJ.log("Axis X " + (revX ? "IS" : "IS NOT") + " reversed");
                        IJ.log("Axis Y " + (revY ? "IS" : "IS NOT") + " reversed");
                        //double[] stagePositionX = {0.0};
                        //double[] stagePositionY = {0.0};
                        //Single Roi
                        Roi[] rois_ = RoiManager.getInstance().getSelectedRoisAsArray();
                        ImageWindow liveWindow = studio_.getSnapLiveWin();
                        liveImage = liveWindow.getImagePlus();
                        liveImage.setRoi(rois_[0]);
                        while (LockButton.isSelected()) {
                            NTimePoint = NTimePoint + 1;
                            // Lock beads position on the live mode;
                            liveImage = liveWindow.getImagePlus();
                            ImageStatistics stats = liveImage
                                    .getStatistics(Measurements.MIN_MAX + Measurements.CENTER_OF_MASS);
                            xPosCoM = stats.xCenterOfMass - rois_[0].getXBase();
                            yPosCoM = stats.yCenterOfMass - rois_[0].getYBase();

                            //liveImage = WindowManager.getCurrentImage();
                            try {
                                lma = fitRois(liveImage.getProcessor().getFloatArray(), rois_[0], InitParam);
                                xPosFit = lma.parameters[1];
                                yPosFit = lma.parameters[3];
                                //Rectangle bound = rois_[0].getBounds();
                                if (NTimePoint == 1) {
                                    xPosFinal = (Math.sqrt(
                                            Math.pow(xPosFit - xPosCoM, 2) + Math.pow(yPosFit - yPosCoM, 2))) < 1
                                                    ? xPosFit
                                                    : xPosCoM;
                                    yPosFinal = (Math.sqrt(
                                            Math.pow(xPosFit - xPosCoM, 2) + Math.pow(yPosFit - yPosCoM, 2))) < 1
                                                    ? yPosFit
                                                    : yPosCoM;
                                    initXPosition = xPosFinal;
                                    initYPosition = yPosFinal;
                                    IJ.log("Initialize X/YPosition");
                                    IJ.log(String.valueOf(initXPosition) + ";" + String.valueOf(initYPosition));
                                    // Set renewed fitting parameters
                                    InitParam[0] = stats.max;
                                    InitParam[1] = xPosFinal;
                                    InitParam[3] = yPosFinal;
                                    InitParam[5] = stats.min;
                                    IJ.log("Initialize Fitting Parameters:");
                                    IJ.log("MAX_MIN:" + String.valueOf(stats.max) + ","
                                            + String.valueOf(stats.min));
                                    IJ.log("Center_of_Mass:" + String.valueOf(xPosFinal) + ","
                                            + String.valueOf(yPosFinal));
                                } else {
                                    USEFITTING = (Math.sqrt(
                                            Math.pow(xPosFit - xPosCoM, 2) + Math.pow(yPosFit - yPosCoM, 2))) < 1;
                                    if (USEFITTING) {
                                        IJ.log("Fitting is good");
                                    } else {
                                        IJ.log("Fitting does not work using CoM instead");
                                    }
                                    xPosFinal = USEFITTING ? xPosFit : xPosCoM;
                                    yPosFinal = USEFITTING ? yPosFit : yPosCoM;
                                    double deltaX = xPosFinal - initXPosition;
                                    double deltaY = yPosFinal - initYPosition;
                                    double deltaXUM = revX ? deltaX * PIXELSIZE / DAMPING
                                            : -deltaX * PIXELSIZE / DAMPING;
                                    double deltaYUM = revY ? deltaY * PIXELSIZE / DAMPING
                                            : -deltaY * PIXELSIZE / DAMPING;
                                    try {
                                        if (Math.abs(deltaXUM) < MAX_MOVE_TOLER
                                                && Math.abs(deltaYUM) < MAX_MOVE_TOLER) {
                                            IJ.log("Ready to move at Frame " + String.valueOf(NTimePoint) + ":\n");
                                            IJ.log(Double.toString(deltaXUM) + ", " + Double.toString(deltaYUM));
                                            if (!swapXYFlag) {
                                                core_.setRelativePosition(XSTAGE, deltaXUM);
                                                core_.setRelativePosition(YSTAGE, deltaYUM);
                                            } else {
                                                core_.setRelativePosition(YSTAGE, deltaXUM);
                                                core_.setRelativePosition(XSTAGE, deltaYUM);
                                            }
                                            core_.waitForDeviceType(DeviceType.StageDevice);

                                        } else {
                                            IJ.log("Out of Movestep Range");
                                        }

                                    } catch (Exception ex) {
                                        Logger.getLogger(liveDriftCorrectionGUI.class.getName()).log(Level.SEVERE,
                                                null, ex);
                                    }
                                }
                            } catch (Exception ex) {
                                IJ.log("Fit Error !!");
                            }
                        }
                    } catch (Exception e) {
                        ReportingUtils.showError(e);
                    } finally {
                        isRunning_.set(false);
                        stopRequested_.set(false);
                    }
                }
            };
            th.start();
        }

    }

    private void PixelSizeEditActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_PixelSizeEditActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_PixelSizeEditActionPerformed

    private void AddRoiButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_AddRoiButtonActionPerformed
        // Define a point ROI by hand -> automaticlly calculate the center -> define Rectangle ROI
        Roi proi = WindowManager.getCurrentImage().getRoi(); // point roi
        RoiManager RM = RoiManager.getInstance();
        if (RM == null) {
            IJ.run("ROI Manager...");
            RM = RoiManager.getInstance();
        }
        ReportingUtils.logMessage("ROI Type: " + String.valueOf(proi.getType()));
        if (proi.getType() == 10) { // point Roi
            Roi recRoi = new Roi(proi.getXBase() - Math.round(ROISIZE / 2),
                    proi.getYBase() - Math.round(ROISIZE / 2), ROISIZE, ROISIZE);
            RM.addRoi(recRoi);
            RM.runCommand("Show All");
        }
    }//GEN-LAST:event_AddRoiButtonActionPerformed

    private void MaxMoveTolerActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_MaxMoveTolerActionPerformed
        MAX_MOVE_TOLER = Double.valueOf(MaxMoveToler.getText());
        IJ.log("Reset MAX_MOVE_TOLER to " + String.valueOf(MAX_MOVE_TOLER));
    }//GEN-LAST:event_MaxMoveTolerActionPerformed

    private void DampingActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_DampingActionPerformed
        DAMPING = Double.valueOf(Damping.getText());
        IJ.log("Reset MAX_MOVE_TOLER to " + String.valueOf(DAMPING));
    }//GEN-LAST:event_DampingActionPerformed

    private void swapXYActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_swapXYActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_swapXYActionPerformed

    private void xStageInc1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_xStageInc1ActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_xStageInc1ActionPerformed

    private void xStageIncActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_xStageIncActionPerformed
        MoveStage("xstage", "inc");
    }//GEN-LAST:event_xStageIncActionPerformed

    private void stageStepSizeActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_stageStepSizeActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_stageStepSizeActionPerformed

    private void yStageIncActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_yStageIncActionPerformed
        // TODO add your handling code here:
        MoveStage("ystage", "inc");
    }//GEN-LAST:event_yStageIncActionPerformed

    private void yStageDecActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_yStageDecActionPerformed
        // TODO add your handling code here:
        MoveStage("ystage", "dec");
    }//GEN-LAST:event_yStageDecActionPerformed

    private void xStageDecActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_xStageDecActionPerformed
        // TODO add your handling code here:
        MoveStage("xstage", "dec");
    }//GEN-LAST:event_xStageDecActionPerformed

    private void zStageIncActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_zStageIncActionPerformed
        // TODO add your handling code here:
        MoveStage("zstage", "inc");
    }//GEN-LAST:event_zStageIncActionPerformed

    private void zStageDecActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_zStageDecActionPerformed
        // TODO add your handling code here:
        MoveStage("zstage", "dec");
    }//GEN-LAST:event_zStageDecActionPerformed

    private void MoveStage(String stage, String direction) {
        double MOVESTEP = Double.valueOf(stageStepSize.getText());
        MOVESTEP = ("inc".equals(direction)) ? MOVESTEP : -MOVESTEP;
        boolean swapXYFlag = swapXY.isSelected();
        IJ.log(stage);
        switch (stage) {
        case "xstage":
            boolean revX = reverseX.isSelected();
            MOVESTEP = (revX) ? MOVESTEP : -MOVESTEP;
            try {
                if (!swapXYFlag) {
                    core_.setRelativePosition(XSTAGE, MOVESTEP);
                    IJ.log("Stage" + XSTAGE + ":" + Double.toString(MOVESTEP));
                    IJ.log("Stage Position:" + Double.toString(core_.getPosition(XSTAGE)));
                } else {
                    core_.setRelativePosition(YSTAGE, MOVESTEP);
                    IJ.log("Stage" + YSTAGE + ":" + Double.toString(MOVESTEP));
                    IJ.log("Stage Position:" + Double.toString(core_.getPosition(YSTAGE)));
                }
            } catch (Exception ex) {
                Logger.getLogger(liveDriftCorrectionGUI.class.getName()).log(Level.SEVERE, null, ex);
            }
            break;
        case "ystage":
            boolean revY = reverseY.isSelected();
            MOVESTEP = (revY) ? MOVESTEP : -MOVESTEP;
            try {
                if (!swapXYFlag) {
                    core_.setRelativePosition(YSTAGE, MOVESTEP);
                    IJ.log("Stage" + YSTAGE + ":" + Double.toString(MOVESTEP));
                    IJ.log("Stage Position:" + Double.toString(core_.getPosition(YSTAGE)));
                } else {
                    core_.setRelativePosition(XSTAGE, MOVESTEP);
                    IJ.log("Stage" + XSTAGE + ":" + Double.toString(MOVESTEP));
                    IJ.log("Stage Position:" + Double.toString(core_.getPosition(XSTAGE)));
                }
            } catch (Exception ex) {
                Logger.getLogger(liveDriftCorrectionGUI.class.getName()).log(Level.SEVERE, null, ex);
            }
            break;
        case "zstage":
            try {
                core_.setRelativePosition(ZSTAGE, MOVESTEP);
                IJ.log("Stage" + ZSTAGE + ":" + Double.toString(MOVESTEP));
                IJ.log("Stage Position:" + Double.toString(core_.getPosition(ZSTAGE)));
            } catch (Exception ex) {
                Logger.getLogger(liveDriftCorrectionGUI.class.getName()).log(Level.SEVERE, null, ex);
            }
            break;
        }

    }

    private LMA fitRois(float[][] imgData, Roi iRois, double[] InitParam) {
        Rectangle rec_ = iRois.getBounds();
        double[][] img;
        img = new double[(int) rec_.getWidth()][(int) rec_.getHeight()];
        for (int iCol = (int) rec_.getX(); iCol < rec_.getX() + rec_.getWidth(); iCol++) {
            for (int iRow = (int) rec_.getY(); iRow < rec_.getY() + rec_.getHeight(); iRow++) {
                int cX = iCol - (int) rec_.getX();
                int cY = iRow - (int) rec_.getY();
                //ReportingUtils.showMessage(Float.toString(imgData[iCol][iRow]));
                img[cX][cY] = (double) imgData[iCol][iRow];
            }
        }
        double[][] InitConbineData;
        InitConbineData = LM2DGaussFit.GenerateDataPoint((int) rec_.getWidth(), (int) rec_.getHeight(), img);
        LMA lma = new LMA(new LM2DGaussFit.LM2DGaussFunction(), InitParam, InitConbineData);
        lma.maxIterations = 100;
        lma.fit();
        return lma;
    }

    public boolean isCalibrating() {
        return isRunning_.get();
    }

    public void stopCalibration() {
        stopRequested_.set(true);
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton AddRoiButton;
    private javax.swing.JTextField Damping;
    private javax.swing.JToggleButton LockButton;
    private javax.swing.JTextField MaxMoveToler;
    private javax.swing.JTextField PixelSizeEdit;
    private javax.swing.JButton getPositionOneFrame;
    private javax.swing.JButton jButton2;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JLabel jLabel7;
    private javax.swing.JLabel jLabel8;
    private javax.swing.JLabel jLabel9;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JPanel jPanel3;
    private javax.swing.JPanel jPanel4;
    private javax.swing.JTabbedPane jTabbedPane6;
    private javax.swing.JButton offLineButton;
    private javax.swing.JRadioButton reverseX;
    private javax.swing.JRadioButton reverseY;
    private javax.swing.JRadioButton reverseZ;
    private javax.swing.JTextField stageStepSize;
    private javax.swing.JRadioButton swapXY;
    private javax.swing.JButton xStageDec;
    private javax.swing.JButton xStageInc;
    private javax.swing.JButton xStageInc1;
    private javax.swing.JButton yStageDec;
    private javax.swing.JButton yStageInc;
    private javax.swing.JButton zStageDec;
    private javax.swing.JButton zStageInc;
    // End of variables declaration//GEN-END:variables
}