String n(double n) {
   String s;
   if (Math.round(n) == n) s = ResultsTable.d2s(n, 0);
   else s = ResultsTable.d2s(n, Analyzer.getPrecision());
   return "\t" + s;
 }
 public boolean get_errors(double[] params, int[] fixes) {
   GenericDialog gd = new GenericDialog("Error Options");
   String[] methods = {"Support Plane", "Monte Carlo"};
   gd.addChoice("Method", methods, methods[0]);
   float conf = 0.67f;
   gd.addNumericField("SP_Confidence Limit (%)", (int) (conf * 100.0f), 5, 10, null);
   String[] labels = {"P1", "P2", "P3", "P4", "P5", "P6", "P7", "P8", "P9", "P10"};
   gd.addChoice("SP_Parameter", labels, labels[0]);
   double spacing = 0.01;
   gd.addNumericField("SP_Chi^2_plot_spacing (% of value)?", spacing * 100.0, 2, 10, null);
   int ntrials = 100;
   gd.addNumericField("MC_#_Trials", ntrials, 0);
   gd.showDialog();
   if (gd.wasCanceled()) {
     return false;
   }
   int methodindex = gd.getNextChoiceIndex();
   conf = 0.01f * (float) gd.getNextNumber();
   int paramindex = gd.getNextChoiceIndex();
   spacing = 0.01 * gd.getNextNumber();
   ntrials = (int) gd.getNextNumber();
   if (methodindex == 0) {
     support_plane_errors_v2 erclass = new support_plane_errors_v2(this, 0.0001, 50, false, 0.1);
     int errindex = paramindex;
     int nfit = 0;
     for (int i = 0; i < labels.length; i++) {
       if (fixes[i] == 0) {
         nfit++;
       }
     }
     int npts = tempdata.length;
     int dofnum = npts - (nfit - 1) - 1;
     int dofden = npts - nfit - 1;
     double flim = (new jdist()).FLimit(dofnum, dofden, (double) conf);
     IJ.log("FLimit = " + (float) flim);
     if (flim == Double.NaN && flim < 1.0) {
       IJ.showMessage("Invalid Limiting F Value");
       return false;
     }
     double truespacing = Math.abs(params[errindex] * spacing);
     double[][] c2plot =
         erclass.geterrors(
             params, fixes, constraints, tempdata, weights, flim, truespacing, errindex);
     IJ.log("upper limit = " + c2plot[1][0] + " lower limit = " + c2plot[0][0]);
     IJ.log(
         "upper error = "
             + (c2plot[1][0] - params[errindex])
             + " lower error = "
             + (params[errindex] - c2plot[0][0]));
     int templength = c2plot[0].length;
     float[][] c2plotf = new float[2][templength - 1];
     for (int i = 0; i < (templength - 1); i++) {
       c2plotf[0][i] = (float) c2plot[0][i + 1];
       c2plotf[1][i] = (float) c2plot[1][i + 1];
     }
     new PlotWindow4("c2 plot", labels[errindex], "Chi^2", c2plotf[0], c2plotf[1]).draw();
   } else {
     StringBuffer sb = new StringBuffer();
     sb.append("Trial\t");
     for (int i = 0; i < labels.length; i++) {
       if (fixes[i] == 0) sb.append(labels[i] + "\t");
     }
     sb.append("chi^2");
     tw = new TextWindow("Monte Carlo Results", sb.toString(), "", 400, 400);
     redirect = true;
     monte_carlo_errors_v2 erclass = new monte_carlo_errors_v2(this, 0.0001, 50, false, 0.1);
     double[][] errors = erclass.geterrors(params, fixes, constraints, tempdata, weights, ntrials);
     sb = new StringBuffer();
     sb.append("StDev\t");
     for (int i = 0; i < errors.length; i++) {
       float[] ferr = new float[errors[0].length];
       for (int j = 0; j < ferr.length; j++) ferr[j] = (float) errors[i][j];
       float stdev = jstatistics.getstatistic("StDev", ferr, null);
       sb.append("" + stdev);
       if (i < (errors.length - 1)) sb.append("\t");
     }
     tw.append(sb.toString());
     redirect = false;
   }
   return true;
 }
  /**
   * Performs particle analysis on the specified ImagePlus and ImageProcessor. Returns false if
   * there is an error.
   */
  public boolean analyze(ImagePlus imp, ImageProcessor ip) {
    if (this.imp == null) this.imp = imp;
    showResults = (options & SHOW_RESULTS) != 0;
    excludeEdgeParticles = (options & EXCLUDE_EDGE_PARTICLES) != 0;
    resetCounter = (options & CLEAR_WORKSHEET) != 0;
    showProgress = (options & SHOW_PROGRESS) != 0;
    floodFill = (options & INCLUDE_HOLES) == 0;
    recordStarts = (options & RECORD_STARTS) != 0;
    addToManager = (options & ADD_TO_MANAGER) != 0;
    displaySummary = (options & DISPLAY_SUMMARY) != 0;
    inSituShow = (options & IN_SITU_SHOW) != 0;
    outputImage = null;
    ip.snapshot();
    ip.setProgressBar(null);
    if (Analyzer.isRedirectImage()) {
      redirectImp = Analyzer.getRedirectImage(imp);
      if (redirectImp == null) return false;
      int depth = redirectImp.getStackSize();
      if (depth > 1 && depth == imp.getStackSize()) {
        ImageStack redirectStack = redirectImp.getStack();
        redirectIP = redirectStack.getProcessor(imp.getCurrentSlice());
      } else redirectIP = redirectImp.getProcessor();
    } else if (imp.getType() == ImagePlus.COLOR_RGB) {
      ImagePlus original = (ImagePlus) imp.getProperty("OriginalImage");
      if (original != null
          && original.getWidth() == imp.getWidth()
          && original.getHeight() == imp.getHeight()) {
        redirectImp = original;
        redirectIP = original.getProcessor();
      }
    }
    if (!setThresholdLevels(imp, ip)) return false;
    width = ip.getWidth();
    height = ip.getHeight();
    if (!(showChoice == NOTHING || showChoice == OVERLAY_OUTLINES || showChoice == OVERLAY_MASKS)) {
      blackBackground = Prefs.blackBackground && inSituShow;
      if (slice == 1) outlines = new ImageStack(width, height);
      if (showChoice == ROI_MASKS) drawIP = new ShortProcessor(width, height);
      else drawIP = new ByteProcessor(width, height);
      drawIP.setLineWidth(lineWidth);
      if (showChoice == ROI_MASKS) {
      } // Place holder for now...
      else if (showChoice == MASKS && !blackBackground) drawIP.invertLut();
      else if (showChoice == OUTLINES) {
        if (!inSituShow) {
          if (customLut == null) makeCustomLut();
          drawIP.setColorModel(customLut);
        }
        drawIP.setFont(new Font("SansSerif", Font.PLAIN, fontSize));
        if (fontSize > 12 && inSituShow) drawIP.setAntialiasedText(true);
      }
      outlines.addSlice(null, drawIP);

      if (showChoice == ROI_MASKS || blackBackground) {
        drawIP.setColor(Color.black);
        drawIP.fill();
        drawIP.setColor(Color.white);
      } else {
        drawIP.setColor(Color.white);
        drawIP.fill();
        drawIP.setColor(Color.black);
      }
    }
    calibration = redirectImp != null ? redirectImp.getCalibration() : imp.getCalibration();

    if (rt == null) {
      rt = Analyzer.getResultsTable();
      analyzer = new Analyzer(imp);
    } else analyzer = new Analyzer(imp, measurements, rt);
    if (resetCounter && slice == 1) {
      if (!Analyzer.resetCounter()) return false;
    }
    beginningCount = Analyzer.getCounter();

    byte[] pixels = null;
    if (ip instanceof ByteProcessor) pixels = (byte[]) ip.getPixels();
    if (r == null) {
      r = ip.getRoi();
      mask = ip.getMask();
      if (displaySummary) {
        if (mask != null) totalArea = ImageStatistics.getStatistics(ip, AREA, calibration).area;
        else totalArea = r.width * calibration.pixelWidth * r.height * calibration.pixelHeight;
      }
    }
    minX = r.x;
    maxX = r.x + r.width;
    minY = r.y;
    maxY = r.y + r.height;
    if (r.width < width || r.height < height || mask != null) {
      if (!eraseOutsideRoi(ip, r, mask)) return false;
    }
    int offset;
    double value;
    int inc = Math.max(r.height / 25, 1);
    int mi = 0;
    ImageWindow win = imp.getWindow();
    if (win != null) win.running = true;
    if (measurements == 0) measurements = Analyzer.getMeasurements();
    if (showChoice == ELLIPSES) measurements |= ELLIPSE;
    measurements &= ~LIMIT; // ignore "Limit to Threshold"
    roiNeedsImage =
        (measurements & PERIMETER) != 0
            || (measurements & SHAPE_DESCRIPTORS) != 0
            || (measurements & FERET) != 0;
    particleCount = 0;
    wand = new Wand(ip);
    pf = new PolygonFiller();
    if (floodFill) {
      ImageProcessor ipf = ip.duplicate();
      ipf.setValue(fillColor);
      ff = new FloodFiller(ipf);
    }
    roiType = Wand.allPoints() ? Roi.FREEROI : Roi.TRACED_ROI;

    for (int y = r.y; y < (r.y + r.height); y++) {
      offset = y * width;
      for (int x = r.x; x < (r.x + r.width); x++) {
        if (pixels != null) value = pixels[offset + x] & 255;
        else if (imageType == SHORT) value = ip.getPixel(x, y);
        else value = ip.getPixelValue(x, y);
        if (value >= level1 && value <= level2) analyzeParticle(x, y, imp, ip);
      }
      if (showProgress && ((y % inc) == 0)) IJ.showProgress((double) (y - r.y) / r.height);
      if (win != null) canceled = !win.running;
      if (canceled) {
        Macro.abort();
        break;
      }
    }
    if (showProgress) IJ.showProgress(1.0);
    if (showResults) rt.updateResults();
    imp.killRoi();
    ip.resetRoi();
    ip.reset();
    if (displaySummary && IJ.getInstance() != null) updateSliceSummary();
    if (addToManager && roiManager != null) roiManager.setEditMode(imp, true);
    maxParticleCount = (particleCount > maxParticleCount) ? particleCount : maxParticleCount;
    totalCount += particleCount;
    if (!canceled) showResults();
    return true;
  }