Example #1
0
 public void run(ImageProcessor ip) {
   if (enlarge && gd.wasOKed())
     synchronized (this) {
       if (!isEnlarged) {
         enlargeCanvas();
         isEnlarged = true;
       }
     }
   if (isEnlarged) { // enlarging may have made the ImageProcessor invalid, also for the parallel
                     // threads
     int slice = pfr.getSliceNumber();
     if (imp.getStackSize() == 1) ip = imp.getProcessor();
     else ip = imp.getStack().getProcessor(slice);
   }
   ip.setInterpolationMethod(interpolationMethod);
   if (fillWithBackground) {
     Color bgc = Toolbar.getBackgroundColor();
     if (bitDepth == 8) ip.setBackgroundValue(ip.getBestIndex(bgc));
     else if (bitDepth == 24) ip.setBackgroundValue(bgc.getRGB());
   } else ip.setBackgroundValue(0);
   ip.rotate(angle);
   if (!gd.wasOKed()) drawGridLines(gridLines);
   if (isEnlarged && imp.getStackSize() == 1) {
     imp.changes = true;
     imp.updateAndDraw();
     Undo.setup(Undo.COMPOUND_FILTER_DONE, imp);
   }
 }
Example #2
0
 /**
  * Builds dialog to query users for projection parameters.
  *
  * @param start starting slice to display
  * @param stop last slice
  */
 protected GenericDialog buildControlDialog(int start, int stop) {
   GenericDialog gd = new GenericDialog("ZProjection", IJ.getInstance());
   gd.addNumericField("Start slice:", startSlice, 0 /*digits*/);
   gd.addNumericField("Stop slice:", stopSlice, 0 /*digits*/);
   gd.addChoice("Projection type", METHODS, METHODS[method]);
   if (isHyperstack && imp.getNFrames() > 1 && imp.getNSlices() > 1)
     gd.addCheckbox("All time frames", allTimeFrames);
   return gd;
 }
Example #3
0
 public int showDialog(ImagePlus imp, String command, PlugInFilterRunner pfr) {
   this.pfr = pfr;
   String macroOptions = Macro.getOptions();
   if (macroOptions != null) {
     if (macroOptions.indexOf(" interpolate") != -1)
       macroOptions.replaceAll(" interpolate", " interpolation=Bilinear");
     else if (macroOptions.indexOf(" interpolation=") == -1)
       macroOptions = macroOptions + " interpolation=None";
     Macro.setOptions(macroOptions);
   }
   gd = new GenericDialog("Rotate", IJ.getInstance());
   gd.addNumericField("Angle (degrees):", angle, (int) angle == angle ? 1 : 2);
   gd.addNumericField("Grid Lines:", gridLines, 0);
   gd.addChoice("Interpolation:", methods, methods[interpolationMethod]);
   if (bitDepth == 8 || bitDepth == 24)
     gd.addCheckbox("Fill with Background Color", fillWithBackground);
   if (canEnlarge) gd.addCheckbox("Enlarge Image to Fit Result", enlarge);
   else enlarge = false;
   gd.addPreviewCheckbox(pfr);
   gd.addDialogListener(this);
   gd.showDialog();
   drawGridLines(0);
   if (gd.wasCanceled()) {
     return DONE;
   }
   if (!enlarge) flags |= KEEP_PREVIEW; // standard filter without enlarge
   else if (imp.getStackSize() == 1) flags |= NO_CHANGES; // undoable as a "compound filter"
   return IJ.setupDialog(imp, flags);
 }
Example #4
0
 /** Quit using a separate thread, hopefully avoiding thread deadlocks. */
 public void run() {
   quitting = true;
   boolean changes = false;
   int[] wList = WindowManager.getIDList();
   if (wList != null) {
     for (int i = 0; i < wList.length; i++) {
       ImagePlus imp = WindowManager.getImage(wList[i]);
       if (imp != null && imp.changes == true) {
         changes = true;
         break;
       }
     }
   }
   Frame[] frames = WindowManager.getNonImageWindows();
   if (frames != null) {
     for (int i = 0; i < frames.length; i++) {
       if (frames[i] != null && (frames[i] instanceof Editor)) {
         if (((Editor) frames[i]).fileChanged()) {
           changes = true;
           break;
         }
       }
     }
   }
   if (windowClosed
       && !changes
       && Menus.window.getItemCount() > Menus.WINDOW_MENU_ITEMS
       && !(IJ.macroRunning() && WindowManager.getImageCount() == 0)) {
     GenericDialog gd = new GenericDialog("ImageJ", this);
     gd.addMessage("Are you sure you want to quit ImageJ?");
     gd.showDialog();
     quitting = !gd.wasCanceled();
     windowClosed = false;
   }
   if (!quitting) return;
   if (!WindowManager.closeAllWindows()) {
     quitting = false;
     return;
   }
   // IJ.log("savePreferences");
   if (applet == null) {
     saveWindowLocations();
     Prefs.savePreferences();
   }
   IJ.cleanup();
   // setVisible(false);
   // IJ.log("dispose");
   dispose();
   if (exitWhenQuitting) System.exit(0);
 }
Example #5
0
 void showDialog() {
   int width = imp.getWidth();
   int height = imp.getHeight();
   Calibration cal = imp.getCalibration();
   int places;
   if (cal.scaled()) {
     pixelWidth = cal.pixelWidth;
     pixelHeight = cal.pixelHeight;
     units = cal.getUnits();
     places = 2;
   } else {
     pixelWidth = 1.0;
     pixelHeight = 1.0;
     units = "pixels";
     places = 0;
   }
   if (areaPerPoint == 0.0)
     areaPerPoint =
         (width * cal.pixelWidth * height * cal.pixelHeight) / 81.0; // default to 9x9 grid
   ImageWindow win = imp.getWindow();
   GenericDialog gd = new GenericDialog("Grid...");
   gd.addChoice("Grid Type:", types, type);
   gd.addNumericField("Area per Point:", areaPerPoint, places, 6, units + "^2");
   gd.addChoice("Color:", colors, color);
   gd.addCheckbox("Random Offset", randomOffset);
   gd.addDialogListener(this);
   gd.showDialog();
   if (gd.wasCanceled()) showGrid(null);
 }
Example #6
0
 void interpolate() {
   Roi roi = imp.getRoi();
   if (roi == null) {
     noRoi("Interpolate");
     return;
   }
   if (roi.getType() == Roi.POINT) return;
   if (IJ.isMacro() && Macro.getOptions() == null) Macro.setOptions("interval=1");
   GenericDialog gd = new GenericDialog("Interpolate");
   gd.addNumericField("Interval:", 1.0, 1, 4, "pixel");
   gd.addCheckbox("Smooth", IJ.isMacro() ? false : smooth);
   gd.showDialog();
   if (gd.wasCanceled()) return;
   double interval = gd.getNextNumber();
   smooth = gd.getNextBoolean();
   Undo.setup(Undo.ROI, imp);
   FloatPolygon poly = roi.getInterpolatedPolygon(interval, smooth);
   int t = roi.getType();
   int type = roi.isLine() ? Roi.FREELINE : Roi.FREEROI;
   if (t == Roi.POLYGON && interval > 1.0) type = Roi.POLYGON;
   if ((t == Roi.RECTANGLE || t == Roi.OVAL || t == Roi.FREEROI) && interval >= 5.0)
     type = Roi.POLYGON;
   if ((t == Roi.LINE || t == Roi.FREELINE) && interval >= 5.0) type = Roi.POLYLINE;
   if (t == Roi.POLYLINE && interval >= 1.0) type = Roi.POLYLINE;
   ImageCanvas ic = imp.getCanvas();
   if (poly.npoints <= 150 && ic != null && ic.getMagnification() >= 12.0)
     type = roi.isLine() ? Roi.POLYLINE : Roi.POLYGON;
   Roi p = new PolygonRoi(poly, type);
   if (roi.getStroke() != null) p.setStrokeWidth(roi.getStrokeWidth());
   p.setStrokeColor(roi.getStrokeColor());
   p.setName(roi.getName());
   transferProperties(roi, p);
   imp.setRoi(p);
 }
Example #7
0
 public boolean dialogItemChanged(GenericDialog gd, AWTEvent e) {
   iterations = (int) gd.getNextNumber();
   count = (int) gd.getNextNumber();
   boolean bb = Prefs.blackBackground;
   Prefs.blackBackground = gd.getNextBoolean();
   if (Prefs.blackBackground != bb) ThresholdAdjuster.update();
   Prefs.padEdges = gd.getNextBoolean();
   EDM.setOutputType(gd.getNextChoiceIndex());
   boolean isInvalid = gd.invalidNumber();
   if (iterations < 1) {
     iterations = 1;
     isInvalid = true;
   }
   if (iterations > MAX_ITERATIONS) {
     iterations = MAX_ITERATIONS;
     isInvalid = true;
   }
   if (count < 1) {
     count = 1;
     isInvalid = true;
   }
   if (count > 8) {
     count = 8;
     isInvalid = true;
   }
   if (isInvalid) return false;
   if (imp != null) {
     operation = gd.getNextChoice();
     arg = operation.toLowerCase();
   }
   return true;
 }
 public boolean dialogItemChanged(GenericDialog gd, AWTEvent e) {
   checkc2 = gd.getNextBoolean();
   double[] params = new double[10];
   int[] fixes = new int[10];
   for (int i = 0; i < params.length; i++) {
     params[i] = gd.getNextNumber();
     if (gd.getNextBoolean()) {
       fixes[i] = 1;
     } else {
       fixes[i] = 0;
     }
   }
   gd.getNextBoolean();
   gd.getNextNumber();
   gd.getNextNumber();
   NLLSfit_v2 fitclass = new NLLSfit_v2(this, 0);
   double[] stats = new double[2];
   float[] fit = fitclass.fitdata(params, fixes, null, tempdata, null, stats, true);
   pw.updateSeries(fit, series, false);
   c2 = (float) stats[1];
   return true;
 }
Example #9
0
 public boolean dialogItemChanged(GenericDialog gd, AWTEvent e) {
   angle = gd.getNextNumber();
   // only check for invalid input to "angle", don't care about gridLines
   if (gd.invalidNumber()) {
     if (gd.wasOKed()) IJ.error("Angle is invalid.");
     return false;
   }
   gridLines = (int) gd.getNextNumber();
   interpolationMethod = gd.getNextChoiceIndex();
   if (bitDepth == 8 || bitDepth == 24) fillWithBackground = gd.getNextBoolean();
   if (canEnlarge) enlarge = gd.getNextBoolean();
   return true;
 }
Example #10
0
 void addSelection() {
   ImagePlus imp = IJ.getImage();
   String macroOptions = Macro.getOptions();
   if (macroOptions != null && IJ.macroRunning() && macroOptions.indexOf("remove") != -1) {
     imp.setOverlay(null);
     return;
   }
   Roi roi = imp.getRoi();
   if (roi == null && imp.getOverlay() != null) {
     GenericDialog gd = new GenericDialog("No Selection");
     gd.addMessage("\"Overlay>Add\" requires a selection.");
     gd.setInsets(15, 40, 0);
     gd.addCheckbox("Remove existing overlay", false);
     gd.showDialog();
     if (gd.wasCanceled()) return;
     if (gd.getNextBoolean()) imp.setOverlay(null);
     return;
   }
   if (roi == null) {
     IJ.error("This command requires a selection.");
     return;
   }
   roi = (Roi) roi.clone();
   if (roi.getStrokeColor() == null) roi.setStrokeColor(Toolbar.getForegroundColor());
   int width = Line.getWidth();
   Rectangle bounds = roi.getBounds();
   boolean tooWide = width > Math.max(bounds.width, bounds.height) / 3.0;
   if (roi.getStroke() == null && width > 1 && !tooWide) roi.setStrokeWidth(Line.getWidth());
   Overlay overlay = imp.getOverlay();
   if (overlay != null && overlay.size() > 0 && !roi.isDrawingTool()) {
     Roi roi2 = overlay.get(overlay.size() - 1);
     if (roi.getStroke() == null) roi.setStrokeWidth(roi2.getStrokeWidth());
     if (roi.getFillColor() == null) roi.setFillColor(roi2.getFillColor());
   }
   boolean points = roi instanceof PointRoi && ((PolygonRoi) roi).getNCoordinates() > 1;
   if (points) roi.setStrokeColor(Color.red);
   if (!IJ.altKeyDown() && !(roi instanceof Arrow)) {
     RoiProperties rp = new RoiProperties("Add to Overlay", roi);
     if (!rp.showDialog()) return;
   }
   String name = roi.getName();
   boolean newOverlay = name != null && name.equals("new-overlay");
   if (overlay == null || newOverlay) overlay = new Overlay();
   overlay.add(roi);
   imp.setOverlay(overlay);
   overlay2 = overlay;
   if (points || (roi instanceof ImageRoi) || (roi instanceof Arrow)) imp.killRoi();
   Undo.setup(Undo.OVERLAY_ADDITION, imp);
 }
Example #11
0
 public boolean showDialog(ImageStack stack) {
   hyperstack = imp.isHyperStack();
   boolean showCheckbox = false;
   if (hyperstack && imp.getNSlices() > 1 && imp.getNFrames() > 1) showCheckbox = true;
   else if (hyperstack && imp.getNSlices() > 1) reduceSlices = true;
   int n = stack.getSize();
   GenericDialog gd = new GenericDialog("Reduce Size");
   gd.addNumericField("Reduction Factor:", factor, 0);
   if (showCheckbox) gd.addCheckbox("Reduce in Z-Dimension", false);
   gd.showDialog();
   if (gd.wasCanceled()) return false;
   factor = (int) gd.getNextNumber();
   if (showCheckbox) reduceSlices = gd.getNextBoolean();
   return true;
 }
Example #12
0
 void checkForCalibrationConflict(ImagePlus imp, Calibration cal) {
   Calibration gcal = imp.getGlobalCalibration();
   if (gcal == null || !showConflictMessage || IJ.isMacro()) return;
   if (cal.pixelWidth == gcal.pixelWidth && cal.getUnit().equals(gcal.getUnit())) return;
   GenericDialog gd = new GenericDialog(imp.getTitle());
   gd.addMessage("The calibration of this image conflicts\nwith the current global calibration.");
   gd.addCheckbox("Disable_Global Calibration", true);
   gd.addCheckbox("Disable_these Messages", false);
   gd.showDialog();
   if (gd.wasCanceled()) return;
   boolean disable = gd.getNextBoolean();
   if (disable) {
     imp.setGlobalCalibration(null);
     imp.setCalibration(cal);
     WindowManager.repaintImageWindows();
   }
   boolean dontShow = gd.getNextBoolean();
   if (dontShow) showConflictMessage = false;
 }
Example #13
0
 // Conversion Options
 void conversions() {
   double[] weights = ColorProcessor.getWeightingFactors();
   boolean weighted = !(weights[0] == 1d / 3d && weights[1] == 1d / 3d && weights[2] == 1d / 3d);
   // boolean weighted = !(Math.abs(weights[0]-1d/3d)<0.0001 && Math.abs(weights[1]-1d/3d)<0.0001
   // && Math.abs(weights[2]-1d/3d)<0.0001);
   GenericDialog gd = new GenericDialog("Conversion Options");
   gd.addCheckbox("Scale when converting", ImageConverter.getDoScaling());
   String prompt = "Weighted RGB conversions";
   if (weighted)
     prompt +=
         " (" + IJ.d2s(weights[0]) + "," + IJ.d2s(weights[1]) + "," + IJ.d2s(weights[2]) + ")";
   gd.addCheckbox(prompt, weighted);
   gd.showDialog();
   if (gd.wasCanceled()) return;
   ImageConverter.setDoScaling(gd.getNextBoolean());
   Prefs.weightedColor = gd.getNextBoolean();
   if (!Prefs.weightedColor) ColorProcessor.setWeightingFactors(1d / 3d, 1d / 3d, 1d / 3d);
   else if (Prefs.weightedColor && !weighted)
     ColorProcessor.setWeightingFactors(0.299, 0.587, 0.114);
   return;
 }
 public double[][] get_constraints(double[] params) {
   // here we populate the constraints
   GenericDialog gd = new GenericDialog("Constraints");
   for (int i = 0; i < 10; i++) {
     if (constraints == null) {
       gd.addNumericField("P" + (i + 1) + "_upper", params[i], 5, 10, null);
       gd.addNumericField("P" + (i + 1) + "_lower", params[i], 5, 10, null);
     } else {
       gd.addNumericField("P" + (i + 1) + "_upper", constraints[1][i], 5, 10, null);
       gd.addNumericField("P" + (i + 1) + "_lower", constraints[0][i], 5, 10, null);
     }
   }
   gd.showDialog();
   if (gd.wasCanceled()) {
     return null;
   }
   double[][] constraints = new double[2][10];
   for (int i = 0; i < 10; i++) {
     constraints[1][i] = gd.getNextNumber();
     constraints[0][i] = gd.getNextNumber();
   }
   return constraints;
 }
Example #15
0
  public boolean dialogItemChanged(GenericDialog gd, AWTEvent e) {
    int width = imp.getWidth();
    int height = imp.getHeight();
    type = gd.getNextChoice();
    areaPerPoint = gd.getNextNumber();
    color = gd.getNextChoice();
    randomOffset = gd.getNextBoolean();

    double minArea = (width * height) / 50000.0;
    if (type.equals(types[1]) && minArea < 144.0) minArea = 144.0;
    else if (minArea < 16) minArea = 16.0;
    if (areaPerPoint / (pixelWidth * pixelHeight) < minArea) {
      String err = "\"Area per Point\" too small";
      if (gd.wasOKed()) IJ.error("Grid", err);
      else IJ.showStatus(err);
      return true;
    }
    double tileSize = Math.sqrt(areaPerPoint);
    tileWidth = tileSize / pixelWidth;
    tileHeight = tileSize / pixelHeight;
    if (randomOffset) {
      xstart = (int) (random.nextDouble() * tileWidth);
      ystart = (int) (random.nextDouble() * tileHeight);
    } else {
      xstart = (int) (tileWidth / 2.0 + 0.5);
      ystart = (int) (tileHeight / 2.0 + 0.5);
    }
    linesV = (int) ((width - xstart) / tileWidth) + 1;
    linesH = (int) ((height - ystart) / tileHeight) + 1;
    if (gd.invalidNumber()) return true;
    if (type.equals(types[0])) drawLines();
    else if (type.equals(types[1])) drawCrosses();
    else if (type.equals(types[2])) drawPoints();
    else showGrid(null);
    return true;
  }
Example #16
0
 private void makeBand(ImagePlus imp) {
   Roi roi = imp.getRoi();
   if (roi == null) {
     noRoi("Make Band");
     return;
   }
   if (!roi.isArea()) {
     IJ.error("Make Band", "Area selection required");
     return;
   }
   Calibration cal = imp.getCalibration();
   double pixels = bandSize;
   double size = pixels * cal.pixelWidth;
   int decimalPlaces = 0;
   if ((int) size != size) decimalPlaces = 2;
   GenericDialog gd = new GenericDialog("Make Band");
   gd.addNumericField("Band Size:", size, decimalPlaces, 4, cal.getUnits());
   gd.showDialog();
   if (gd.wasCanceled()) return;
   size = gd.getNextNumber();
   if (Double.isNaN(size)) {
     IJ.error("Make Band", "invalid number");
     return;
   }
   int n = (int) Math.round(size / cal.pixelWidth);
   if (n > 255) {
     IJ.error("Make Band", "Cannot make bands wider that 255 pixels");
     return;
   }
   int width = imp.getWidth();
   int height = imp.getHeight();
   Rectangle r = roi.getBounds();
   ImageProcessor ip = roi.getMask();
   if (ip == null) {
     ip = new ByteProcessor(r.width, r.height);
     ip.invert();
   }
   ImageProcessor mask = new ByteProcessor(width, height);
   mask.insert(ip, r.x, r.y);
   ImagePlus edm = new ImagePlus("mask", mask);
   boolean saveBlackBackground = Prefs.blackBackground;
   Prefs.blackBackground = false;
   IJ.run(edm, "Distance Map", "");
   Prefs.blackBackground = saveBlackBackground;
   ip = edm.getProcessor();
   ip.setThreshold(0, n, ImageProcessor.NO_LUT_UPDATE);
   int xx = -1, yy = -1;
   for (int x = r.x; x < r.x + r.width; x++) {
     for (int y = r.y; y < r.y + r.height; y++) {
       if (ip.getPixel(x, y) < n) {
         xx = x;
         yy = y;
         break;
       }
     }
     if (xx >= 0 || yy >= 0) break;
   }
   int count = IJ.doWand(edm, xx, yy, 0, null);
   if (count <= 0) {
     IJ.error("Make Band", "Unable to make band");
     return;
   }
   ShapeRoi roi2 = new ShapeRoi(edm.getRoi());
   if (!(roi instanceof ShapeRoi)) roi = new ShapeRoi(roi);
   ShapeRoi roi1 = (ShapeRoi) roi;
   roi2 = roi2.not(roi1);
   imp.setRoi(roi2);
   bandSize = n;
 }
Example #17
0
  void addImage() {
    ImagePlus imp = IJ.getImage();
    int[] wList = WindowManager.getIDList();
    if (wList == null || wList.length < 2) {
      IJ.error("Add Image...", "The command requires at least two open images.");
      return;
    }
    String[] titles = new String[wList.length];
    for (int i = 0; i < wList.length; i++) {
      ImagePlus imp2 = WindowManager.getImage(wList[i]);
      titles[i] = imp2 != null ? imp2.getTitle() : "";
    }
    int x = 0, y = 0;
    Roi roi = imp.getRoi();
    if (roi != null && roi.isArea()) {
      Rectangle r = roi.getBounds();
      x = r.x;
      y = r.y;
    }
    int index = 0;
    if (wList.length == 2) {
      ImagePlus i1 = WindowManager.getImage(wList[0]);
      ImagePlus i2 = WindowManager.getImage(wList[1]);
      if (i2.getWidth() < i1.getWidth() && i2.getHeight() < i1.getHeight()) index = 1;
    } else if (imp.getID() == wList[0]) index = 1;

    GenericDialog gd = new GenericDialog("Add Image...");
    gd.addChoice("Image to add:", titles, titles[index]);
    gd.addNumericField("X location:", x, 0);
    gd.addNumericField("Y location:", y, 0);
    gd.addNumericField("Opacity (0-100%):", 100, 0);
    gd.addCheckbox("Create image selection", createImageRoi);
    gd.showDialog();
    if (gd.wasCanceled()) return;
    index = gd.getNextChoiceIndex();
    x = (int) gd.getNextNumber();
    y = (int) gd.getNextNumber();
    double opacity = gd.getNextNumber() / 100.0;
    createImageRoi = gd.getNextBoolean();
    ImagePlus overlay = WindowManager.getImage(wList[index]);
    if (wList.length == 2) {
      ImagePlus i1 = WindowManager.getImage(wList[0]);
      ImagePlus i2 = WindowManager.getImage(wList[1]);
      if (i2.getWidth() < i1.getWidth() && i2.getHeight() < i1.getHeight()) {
        imp = i1;
        overlay = i2;
      }
    }
    if (overlay == imp) {
      IJ.error(
          "Add Image...", "Image to be added cannot be the same as\n\"" + imp.getTitle() + "\".");
      return;
    }
    if (overlay.getWidth() > imp.getWidth() && overlay.getHeight() > imp.getHeight()) {
      IJ.error(
          "Add Image...", "Image to be added cannnot be larger than\n\"" + imp.getTitle() + "\".");
      return;
    }
    if (createImageRoi && x == 0 && y == 0) {
      x = imp.getWidth() / 2 - overlay.getWidth() / 2;
      y = imp.getHeight() / 2 - overlay.getHeight() / 2;
    }
    roi = new ImageRoi(x, y, overlay.getProcessor());
    roi.setName(overlay.getShortTitle());
    if (opacity != 1.0) ((ImageRoi) roi).setOpacity(opacity);
    if (createImageRoi) imp.setRoi(roi);
    else {
      Overlay overlayList = imp.getOverlay();
      if (overlayList == null) overlayList = new Overlay();
      overlayList.add(roi);
      imp.setOverlay(overlayList);
      overlay2 = overlayList;
      Undo.setup(Undo.OVERLAY_ADDITION, imp);
    }
  }
  /** Displays a modal options dialog. */
  public boolean showDialog() {
    Calibration cal = imp != null ? imp.getCalibration() : (new Calibration());
    double unitSquared = cal.pixelWidth * cal.pixelHeight;
    if (pixelUnits) unitSquared = 1.0;
    if (Macro.getOptions() != null) {
      boolean oldMacro = updateMacroOptions();
      if (oldMacro) unitSquared = 1.0;
      staticMinSize = 0.0;
      staticMaxSize = DEFAULT_MAX_SIZE;
      staticMinCircularity = 0.0;
      staticMaxCircularity = 1.0;
      staticShowChoice = NOTHING;
    }
    GenericDialog gd = new GenericDialog("Analyze Particles");
    minSize = staticMinSize;
    maxSize = staticMaxSize;
    minCircularity = staticMinCircularity;
    maxCircularity = staticMaxCircularity;
    showChoice = staticShowChoice;
    if (maxSize == 999999) maxSize = DEFAULT_MAX_SIZE;
    options = staticOptions;
    String unit = cal.getUnit();
    boolean scaled = cal.scaled();
    if (unit.equals("inch")) {
      unit = "pixel";
      unitSquared = 1.0;
      scaled = false;
      pixelUnits = true;
    }
    String units = unit + "^2";
    int places = 0;
    double cmin = minSize * unitSquared;
    if ((int) cmin != cmin) places = 2;
    double cmax = maxSize * unitSquared;
    if ((int) cmax != cmax && cmax != DEFAULT_MAX_SIZE) places = 2;
    String minStr = ResultsTable.d2s(cmin, places);
    if (minStr.indexOf("-") != -1) {
      for (int i = places; i <= 6; i++) {
        minStr = ResultsTable.d2s(cmin, i);
        if (minStr.indexOf("-") == -1) break;
      }
    }
    String maxStr = ResultsTable.d2s(cmax, places);
    if (maxStr.indexOf("-") != -1) {
      for (int i = places; i <= 6; i++) {
        maxStr = ResultsTable.d2s(cmax, i);
        if (maxStr.indexOf("-") == -1) break;
      }
    }
    if (scaled) gd.setInsets(5, 0, 0);
    gd.addStringField("Size (" + units + "):", minStr + "-" + maxStr, 12);
    if (scaled) {
      gd.setInsets(0, 40, 5);
      gd.addCheckbox("Pixel units", pixelUnits);
    }
    gd.addStringField("Circularity:", IJ.d2s(minCircularity) + "-" + IJ.d2s(maxCircularity), 12);
    gd.addChoice("Show:", showStrings, showStrings[showChoice]);
    String[] labels = new String[8];
    boolean[] states = new boolean[8];
    labels[0] = "Display results";
    states[0] = (options & SHOW_RESULTS) != 0;
    labels[1] = "Exclude on edges";
    states[1] = (options & EXCLUDE_EDGE_PARTICLES) != 0;
    labels[2] = "Clear results";
    states[2] = (options & CLEAR_WORKSHEET) != 0;
    labels[3] = "Include holes";
    states[3] = (options & INCLUDE_HOLES) != 0;
    labels[4] = "Summarize";
    states[4] = (options & DISPLAY_SUMMARY) != 0;
    labels[5] = "Record starts";
    states[5] = (options & RECORD_STARTS) != 0;
    labels[6] = "Add to Manager";
    states[6] = (options & ADD_TO_MANAGER) != 0;
    labels[7] = "In_situ Show";
    states[7] = (options & IN_SITU_SHOW) != 0;
    gd.addCheckboxGroup(4, 2, labels, states);
    gd.addHelp(IJ.URL + "/docs/menus/analyze.html#ap");
    gd.showDialog();
    if (gd.wasCanceled()) return false;

    String size = gd.getNextString(); // min-max size
    if (scaled) pixelUnits = gd.getNextBoolean();
    if (pixelUnits) unitSquared = 1.0;
    else unitSquared = cal.pixelWidth * cal.pixelHeight;
    String[] minAndMax = Tools.split(size, " -");
    double mins = gd.parseDouble(minAndMax[0]);
    double maxs = minAndMax.length == 2 ? gd.parseDouble(minAndMax[1]) : Double.NaN;
    minSize = Double.isNaN(mins) ? DEFAULT_MIN_SIZE : mins / unitSquared;
    maxSize = Double.isNaN(maxs) ? DEFAULT_MAX_SIZE : maxs / unitSquared;
    if (minSize < DEFAULT_MIN_SIZE) minSize = DEFAULT_MIN_SIZE;
    if (maxSize < minSize) maxSize = DEFAULT_MAX_SIZE;
    staticMinSize = minSize;
    staticMaxSize = maxSize;

    minAndMax = Tools.split(gd.getNextString(), " -"); // min-max circularity
    double minc = gd.parseDouble(minAndMax[0]);
    double maxc = minAndMax.length == 2 ? gd.parseDouble(minAndMax[1]) : Double.NaN;
    minCircularity = Double.isNaN(minc) ? 0.0 : minc;
    maxCircularity = Double.isNaN(maxc) ? 1.0 : maxc;
    if (minCircularity < 0.0 || minCircularity > 1.0) minCircularity = 0.0;
    if (maxCircularity < minCircularity || maxCircularity > 1.0) maxCircularity = 1.0;
    if (minCircularity == 1.0 && maxCircularity == 1.0) minCircularity = 0.0;
    staticMinCircularity = minCircularity;
    staticMaxCircularity = maxCircularity;

    if (gd.invalidNumber()) {
      IJ.error("Bins invalid.");
      canceled = true;
      return false;
    }
    showChoice = gd.getNextChoiceIndex();
    staticShowChoice = showChoice;
    if (gd.getNextBoolean()) options |= SHOW_RESULTS;
    else options &= ~SHOW_RESULTS;
    if (gd.getNextBoolean()) options |= EXCLUDE_EDGE_PARTICLES;
    else options &= ~EXCLUDE_EDGE_PARTICLES;
    if (gd.getNextBoolean()) options |= CLEAR_WORKSHEET;
    else options &= ~CLEAR_WORKSHEET;
    if (gd.getNextBoolean()) options |= INCLUDE_HOLES;
    else options &= ~INCLUDE_HOLES;
    if (gd.getNextBoolean()) options |= DISPLAY_SUMMARY;
    else options &= ~DISPLAY_SUMMARY;
    if (gd.getNextBoolean()) options |= RECORD_STARTS;
    else options &= ~RECORD_STARTS;
    if (gd.getNextBoolean()) options |= ADD_TO_MANAGER;
    else options &= ~ADD_TO_MANAGER;
    if (gd.getNextBoolean()) options |= IN_SITU_SHOW;
    else options &= ~IN_SITU_SHOW;
    staticOptions = options;
    options |= SHOW_PROGRESS;
    if ((options & DISPLAY_SUMMARY) != 0)
      Analyzer.setMeasurements(Analyzer.getMeasurements() | AREA);
    return true;
  }
Example #19
0
  public void run(String arg) {
    GenericDialog gd = new GenericDialog("Options");
    double sfreq = 20000.0;
    gd.addNumericField("Sampling Frequency?", sfreq, 1, 10, null);
    String[] psfchoice = {"3D Gaussian", "Gaus-Lorentz^2", "2D Gaussian"};
    gd.addChoice("PSF Type?", psfchoice, psfchoice[0]);
    String[] filetypechoice = {
      "Confocor 3 raw", "Short binary trajectory", "PlotWindow trajectory", "Ascii Text File"
    };
    gd.addChoice("File Type?", filetypechoice, filetypechoice[0]);
    boolean ch2green = true;
    gd.addCheckbox("Ch2 is green?", ch2green);
    gd.showDialog();
    if (gd.wasCanceled()) {
      return;
    }
    sfreq = gd.getNextNumber();
    int psfflag = gd.getNextChoiceIndex();
    int fileflag = gd.getNextChoiceIndex();
    ch2green = gd.getNextBoolean();
    int nfiles = 0;
    Object[] histograms = null;
    int xmax = 0;
    int ymax = 0;
    String[] names = null;
    if (fileflag < 2) {
      jdataio ioclass = new jdataio();
      File[] filearray = ioclass.openfiles(OpenDialog.getDefaultDirectory(), IJ.getInstance());
      if (filearray.length == 0) {
        return;
      }
      String dir = filearray[0].getAbsolutePath();
      int sepindex = dir.lastIndexOf(File.separator);
      String newdir = dir.substring(0, sepindex + 1);
      OpenDialog.setDefaultDirectory(newdir);
      nfiles = filearray.length / 2;
      if (nfiles > 25) {
        nfiles = 25;
      }
      histograms = new Object[nfiles];
      names = organize_c3_files(filearray);
      for (int i = 0; i < nfiles; i++) {
        try {
          int length1 = (int) (((double) filearray[2 * i].length() - 128.0) / 4.0);
          int length2 = (int) (((double) filearray[2 * i + 1].length() - 128.0) / 4.0);
          int length3 = (int) (((double) filearray[2 * i].length()) / 2.0);
          int length4 = (int) (((double) filearray[2 * i + 1].length()) / 2.0);
          InputStream instream = new BufferedInputStream(new FileInputStream(filearray[2 * i]));
          InputStream instream2 =
              new BufferedInputStream(new FileInputStream(filearray[2 * i + 1]));
          if (fileflag == 0) {
            int[] pmdata = new int[length1];
            int[] pmdata2 = new int[length2];
            if (!ioclass.skipstreambytes(instream, 128)) {
              showioerror();
              instream.close();
              return;
            }
            if (!ioclass.skipstreambytes(instream2, 128)) {
              showioerror();
              instream2.close();
              return;
            }
            if (!ioclass.readintelintfile(instream, length1, pmdata)) {
              showioerror();
              instream.close();
              return;
            }
            if (!ioclass.readintelintfile(instream2, length2, pmdata2)) {
              showioerror();
              instream2.close();
              return;
            }
            if (ch2green) {
              histograms[i] = (new pmodeconvert()).pm2pch(pmdata2, pmdata, sfreq, 20000000);
            } else {
              histograms[i] = (new pmodeconvert()).pm2pch(pmdata, pmdata2, sfreq, 20000000);
            }
          } else {
            float[] tmdata = new float[length3];
            float[] tmdata2 = new float[length4];
            if (!ioclass.readintelshortfile(instream, length3, tmdata)) {
              showioerror();
              instream.close();
              return;
            }
            if (!ioclass.readintelshortfile(instream2, length4, tmdata2)) {
              showioerror();
              instream2.close();
              return;
            }
            if (ch2green) {
              histograms[i] = (new pmodeconvert()).create_2Dhistogram(tmdata2, tmdata);
            } else {
              histograms[i] = (new pmodeconvert()).create_2Dhistogram(tmdata, tmdata2);
            }
          }
          if (((float[][]) histograms[i]).length > xmax) {
            xmax = ((float[][]) histograms[i]).length;
          }
          if (((float[][]) histograms[i])[0].length > ymax) {
            ymax = ((float[][]) histograms[i])[0].length;
          }
          instream.close();
          instream2.close();
        } catch (IOException e) {
          showioerror();
          return;
        }
      }
    } else {
      if (fileflag == 2) {
        ImageWindow iw = WindowManager.getCurrentWindow();
        float[][] trajectories = (float[][]) jutils.runPW4VoidMethod(iw, "getYValues");
        float[][] tempxvals = (float[][]) jutils.runPW4VoidMethod(iw, "getXValues");
        sfreq = 1.0 / ((double) tempxvals[0][1]);
        nfiles = trajectories.length / 2;
        if (nfiles > 25) {
          nfiles = 25;
        }
        names = new String[nfiles + 1];
        names[nfiles] = "avg";
        histograms = new Object[nfiles];
        for (int i = 0; i < nfiles; i++) {
          names[i] = "trajectory " + (i + 1);
          if (ch2green) {
            histograms[i] =
                (new pmodeconvert())
                    .create_2Dhistogram(trajectories[2 * i + 1], trajectories[2 * i]);
          } else {
            histograms[i] =
                (new pmodeconvert())
                    .create_2Dhistogram(trajectories[2 * i], trajectories[2 * i + 1]);
          }
          if (((float[][]) histograms[i]).length > xmax) {
            xmax = ((float[][]) histograms[i]).length;
          }
          if (((float[][]) histograms[i])[0].length > ymax) {
            ymax = ((float[][]) histograms[i])[0].length;
          }
        }
      } else {
        // here we read tab delimited lines from files
        jdataio ioclass = new jdataio();
        File[] filearray = ioclass.openfiles(OpenDialog.getDefaultDirectory(), IJ.getInstance());
        if (filearray.length == 0) {
          return;
        }
        String dir = filearray[0].getAbsolutePath();
        int sepindex = dir.lastIndexOf(File.separator);
        String newdir = dir.substring(0, sepindex + 1);
        OpenDialog.setDefaultDirectory(newdir);
        nfiles = filearray.length;
        if (nfiles > 25) {
          nfiles = 25;
        }
        histograms = new Object[nfiles];
        names = new String[nfiles + 1];
        names[nfiles] = "avg";
        for (int i = 0; i < nfiles; i++) {
          try {
            names[i] = filearray[i].getName();
            BufferedReader d = new BufferedReader(new FileReader(filearray[i]));
            String[] lines = new String[256];
            int counter = 0;
            do {
              lines[counter] = d.readLine();
              counter++;
            } while ((lines[counter - 1] != null && lines[counter - 1] != "") && counter < 256);
            int numcolumns = 0;
            for (int j = 0; j < counter - 1; j++) {
              int temp = getncolumns(lines[j]);
              if (temp > numcolumns) {
                numcolumns = temp;
              }
            }
            float[][] temphist2 = null;
            if (ch2green) {
              temphist2 = new float[numcolumns][counter - 1];
            } else {
              temphist2 = new float[counter - 1][numcolumns];
            }
            for (int k = 0; k < counter - 1; k++) {
              float[] temp = tab_delim2float(lines[k]);
              for (int j = 0; j < numcolumns; j++) {
                if (ch2green) {
                  temphist2[j][k] = temp[j];
                } else {
                  temphist2[k][j] = temp[j];
                }
              }
            }
            histograms[i] = temphist2;
            d.close();
          } catch (IOException e) {
            showioerror();
            return;
          }
        }
        for (int i = 0; i < nfiles; i++) {
          if (((float[][]) histograms[i]).length > xmax) {
            xmax = ((float[][]) histograms[i]).length;
          }
          if (((float[][]) histograms[i])[0].length > ymax) {
            ymax = ((float[][]) histograms[i])[0].length;
          }
        }
      }
    }
    // note that here x is green and y is red
    float[][][] pch = new float[nfiles][xmax][ymax];
    for (int i = 0; i < nfiles; i++) {
      for (int j = 0; j < ((float[][]) histograms[i]).length; j++) {
        for (int k = 0; k < ((float[][]) histograms[i])[j].length; k++) {
          pch[i][j][k] = ((float[][]) histograms[i])[j][k];
        }
      }
    }

    final PCH2DFitWindow cw = new PCH2DFitWindow();
    cw.init(names, pch, psfflag);

    final Frame f = new Frame("PCH 2D Analysis");
    f.setLocation(10, 10);
    f.addWindowListener(
        new WindowAdapter() {
          public void windowClosing(WindowEvent e) {
            f.dispose();
          }
        });

    f.add(cw);
    f.pack();
    f.setResizable(false);
    Insets ins = f.getInsets();
    cw.totalSize.height = PCH2DFitWindow.H + ins.bottom + ins.top + 65;
    cw.totalSize.width = PCH2DFitWindow.WR + ins.left + ins.right;
    f.setSize(cw.totalSize);
    f.setVisible(true);
    cw.requestFocus();
  }
Example #20
0
  private void geterrors() {
    GenericDialog gd = new GenericDialog("Options");
    float conf = 0.67f;
    gd.addNumericField("Confidence Limit", (int) (conf * 100.0f), 5, 10, null);
    gd.addChoice("Error Parameter", paramsnames, paramsnames[0]);
    double spacing = 0.01;
    gd.addNumericField("Chi^2 plot spacing (% of value)?", spacing * 100.0, 2, 10, null);
    boolean globalerror = false;
    gd.addCheckbox("Global Fit Error?", globalerror);
    int dataset = 0;
    gd.addNumericField("Data Set (for Global Error)", dataset, 0);
    gd.showDialog();
    if (gd.wasCanceled()) {
      return;
    }
    conf = 0.01f * (float) gd.getNextNumber();
    int paramindex = (int) gd.getNextChoiceIndex();
    spacing = 0.01 * gd.getNextNumber();
    globalerror = gd.getNextBoolean();
    dataset = (int) gd.getNextNumber();

    if (globalerror) {
      support_plane_errors erclass = new support_plane_errors(this, 0.0001, 50, true, 0.1);
      int[] erindeces = {paramindex, dataset};
      // need to set up all the matrices
      int nsel = 0;
      int nparams = 11;
      for (int i = 0; i < ncurves; i++) {
        if (include[i]) {
          nsel++;
        }
      }
      double[][] params = new double[nsel][nparams];
      String[][] tempformulas = new String[nsel][nparams];
      double[][][] constraints = new double[2][nsel][nparams];
      int[][] vflmatrix = new int[nsel][nparams];

      float[][] tempdata = new float[nsel][xpts * ypts];
      float[][] tempweights = new float[nsel][xpts * ypts];

      int nfit = 0;
      int counter = 0;
      for (int i = 0; i < ncurves; i++) {
        if (include[i]) {
          for (int j = 0; j < nparams; j++) {
            params[counter][j] = globalparams[i][j];
            tempformulas[counter][j] = globalformulas[i][j];
            constraints[0][counter][j] = globalconstraints[0][i][j];
            constraints[1][counter][j] = globalconstraints[1][i][j];
            vflmatrix[counter][j] = globalvflmatrix[i][j];
            if (vflmatrix[counter][j] == 0 || (j == 0 && vflmatrix[counter][j] == 2)) {
              nfit++;
            }
          }
          for (int j = 0; j < xpts; j++) {
            for (int k = 0; k < ypts; k++) {
              tempdata[counter][j + k * xpts] = (float) ((double) pch[i][j][k] / (double) nmeas[i]);
              tempweights[counter][j + k * xpts] = weights[i][j][k];
            }
          }
          counter++;
        }
      }
      int dofnum = xpts * ypts * nsel - (nfit - 1) - 1;
      int dofden = xpts * ypts * nsel - nfit - 1;
      // double flim=FLimit(dofnum,dofden,(double)conf);
      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;
      }
      double truespacing = Math.abs(params[erindeces[1]][erindeces[0]] * spacing);
      double[][] c2plot =
          erclass.geterrorsglobal(
              params,
              vflmatrix,
              tempformulas,
              paramsnames,
              constraints,
              tempdata,
              tempweights,
              flim,
              truespacing,
              erindeces);
      IJ.log("upper limit = " + c2plot[1][0] + " lower limit = " + 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",
              paramsnames[paramindex] + "[" + dataset + "]",
              "Chi^2",
              c2plotf[0],
              c2plotf[1])
          .draw();
    } else {
      support_plane_errors erclass = new support_plane_errors(this, 0.0001, 50, false, 0.1);
      int errindex = paramindex;

      float[] tempdata = new float[xpts * ypts];
      float[] tempweights = new float[xpts * ypts];
      for (int i = 0; i < xpts; i++) {
        for (int j = 0; j < ypts; j++) {
          tempdata[i + j * xpts] = (float) ((double) avg[i][j] / (double) nmeas[ncurves]);
          tempweights[i + j * xpts] = avgweights[i][j];
        }
      }

      int nfit = 0;
      for (int i = 0; i < 7; i++) {
        if (avgfixes[i] == 0) {
          nfit++;
        }
      }
      int dofnum = xpts * ypts - (nfit - 1) - 1;
      int dofden = xpts * ypts - 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;
      }
      double truespacing = Math.abs(avgparams[errindex] * spacing);
      double[][] c2plot =
          erclass.geterrors(
              avgparams,
              avgfixes,
              avgconstraints,
              tempdata,
              tempweights,
              flim,
              truespacing,
              errindex);
      IJ.log("upper limit = " + c2plot[1][0] + " lower limit = " + 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", paramsnames[errindex], "Chi^2", c2plotf[0], c2plotf[1]).draw();
    }
  }
 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;
 }
Example #22
0
  // Miscellaneous Options
  void miscOptions() {
    String key = IJ.isMacintosh() ? "command" : "control";
    GenericDialog gd = new GenericDialog("Miscellaneous Options", IJ.getInstance());
    gd.addStringField("Divide by zero value:", "" + FloatBlitter.divideByZeroValue, 10);
    gd.addCheckbox("Use pointer cursor", Prefs.usePointerCursor);
    gd.addCheckbox("Hide \"Process Stack?\" dialog", IJ.hideProcessStackDialog);
    gd.addCheckbox("Require " + key + " key for shortcuts", Prefs.requireControlKey);
    gd.addCheckbox("Move isolated plugins to Misc. menu", Prefs.moveToMisc);
    if (!IJ.isMacOSX()) gd.addCheckbox("Run single instance listener", Prefs.runSocketListener);
    gd.addCheckbox("Enhanced line tool", Prefs.enhancedLineTool);
    gd.addCheckbox("Reverse CZT order of \">\" and \"<\"", Prefs.reverseNextPreviousOrder);
    gd.addCheckbox("Debug mode", IJ.debugMode);
    gd.addHelp(IJ.URL + "/docs/menus/edit.html#misc");
    gd.showDialog();
    if (gd.wasCanceled()) return;

    String divValue = gd.getNextString();
    if (divValue.equalsIgnoreCase("infinity") || divValue.equalsIgnoreCase("infinite"))
      FloatBlitter.divideByZeroValue = Float.POSITIVE_INFINITY;
    else if (divValue.equalsIgnoreCase("NaN")) FloatBlitter.divideByZeroValue = Float.NaN;
    else if (divValue.equalsIgnoreCase("max")) FloatBlitter.divideByZeroValue = Float.MAX_VALUE;
    else {
      Float f;
      try {
        f = new Float(divValue);
      } catch (NumberFormatException e) {
        f = null;
      }
      if (f != null) FloatBlitter.divideByZeroValue = f.floatValue();
    }
    IJ.register(FloatBlitter.class);

    Prefs.usePointerCursor = gd.getNextBoolean();
    IJ.hideProcessStackDialog = gd.getNextBoolean();
    Prefs.requireControlKey = gd.getNextBoolean();
    Prefs.moveToMisc = gd.getNextBoolean();
    if (!IJ.isMacOSX()) Prefs.runSocketListener = gd.getNextBoolean();
    Prefs.enhancedLineTool = gd.getNextBoolean();
    Prefs.reverseNextPreviousOrder = gd.getNextBoolean();
    IJ.setDebugMode(gd.getNextBoolean());
  }
Example #23
0
 // DICOM options
 void dicom() {
   GenericDialog gd = new GenericDialog("DICOM Options");
   gd.addCheckbox("Open as 32-bit float", Prefs.openDicomsAsFloat);
   // gd.addCheckbox("Calculate voxel depth", Prefs.calculateDicomVoxelDepth);
   gd.addMessage("Orthogonal Views");
   gd.setInsets(5, 40, 0);
   gd.addCheckbox("Rotate YZ", Prefs.rotateYZ);
   gd.setInsets(0, 40, 0);
   gd.addCheckbox("Flip XZ", Prefs.flipXZ);
   gd.showDialog();
   if (gd.wasCanceled()) return;
   Prefs.openDicomsAsFloat = gd.getNextBoolean();
   // Prefs.calculateDicomVoxelDepth = gd.getNextBoolean();
   Prefs.rotateYZ = gd.getNextBoolean();
   Prefs.flipXZ = gd.getNextBoolean();
 }
Example #24
0
	public void run(String arg) {

  int[] wList = WindowManager.getIDList();
        if (wList==null) {
            IJ.error("No images are open.");
            return;
        }
	double kernel=3;
	double kernelsum = 0;
	double kernelvarsum =0;
	double kernalvar = 0;
	double sigmawidth = 2;
	int kernelindex, minpixnumber;
	String[] kernelsize =  { "3�,"5�, "7�, "9�};

	GenericDialog gd = new GenericDialog("Sigma Filter");
	gd.addChoice("Kernel size", kernelsize, kernelsize[0]);
	gd.addNumericField("Sigma width",sigmawidth , 2);
	gd.addNumericField("Minimum number of pixels", 1, 0);

	gd.addCheckbox("Keep source:",true);
	gd.addCheckbox("Do all stack:",true);
	gd.addCheckbox("Modified Lee's FIlter:",true);
	       	
	gd.showDialog();
       	if (gd.wasCanceled()) return ;
	kernelindex =  gd.getNextChoiceIndex();
          	sigmawidth = gd.getNextNumber();
          	minpixnumber = ((int)gd.getNextNumber());
          	boolean keep = gd.getNextBoolean();
	boolean doallstack = gd.getNextBoolean();
	boolean modified = gd.getNextBoolean();
	if (kernelindex==0) kernel = 3;
	if (kernelindex==1) kernel = 5;
	if (kernelindex==2) kernel = 7;
	if (kernelindex==3) kernel = 9;
    	long start = System.currentTimeMillis();
	
if (minpixnumber> (kernel*kernel)){
	      IJ.showMessage("Sigma filter", "There must be more pixels in the kernel than+\n" + "the minimum number to be included");
            return;
        }
	double v, midintensity;
	int   x, y, ix, iy;
	double sum = 0;
	double backupsum =0;
	int count = 0;
	int n = 0;
	if (keep) {IJ.run("Select All"); IJ.run("Duplicate...", "title='Sigma filtered' duplicate");}

	int radius = (int)(kernel-1)/2;
	ImagePlus imp = WindowManager.getCurrentImage();
	ImageStack stack1 = imp.getStack();
	int width = imp.getWidth();
	int height = imp.getHeight();
	int nslices = stack1.getSize();
	int cslice = imp.getCurrentSlice();
	double status = width*height*nslices;
	
	ImageProcessor  ip = imp.getProcessor();
	int sstart = 1;
	if (!doallstack) {sstart = cslice; nslices=sstart;status = status/nslices;};

 for (int i=sstart; i<=nslices; i++) {
                imp.setSlice(i);
                    
for (x=radius;x<width+radius;x++)	{
		for (y=radius;y<height+radius;y++)	{
			
			midintensity = ip.getPixelValue(x,y);
			count = 0;
			sum = 0;
			kernelsum =0;
			kernalvar =0;
			kernelvarsum =0;
			backupsum = 0;

		//calculate mean of kernel value
			for (ix=0;ix<kernel;ix++)	{
					for (iy=0;iy<kernel;iy++)	{
							v = ip.getPixelValue(x+ix-radius,y+iy-radius);
							kernelsum = kernelsum+v;
								}
						}
			double sigmacalcmean = (kernelsum/(kernel*kernel));

		//calculate variance of kernel
			for (ix=0;ix<kernel;ix++)	{
					for (iy=0;iy<kernel;iy++)	{
							v = ip.getPixelValue(x+ix-radius,y+iy-radius);
							kernalvar = (v-sigmacalcmean)*(v-sigmacalcmean);
							kernelvarsum = kernelvarsum + kernalvar;
								}
						}
			//double variance = kernelvarsum/kernel;
			double sigmacalcvar = kernelvarsum/((kernel*kernel)-1);

			//calcuate sigma range = sqrt(variance/(mean^2)) � sigmawidth
			double sigmarange  = sigmawidth*(Math.sqrt((sigmacalcvar) /(sigmacalcmean*sigmacalcmean)));
			//calulate sigma top value and bottom value
			double sigmatop = midintensity*(1+sigmarange);
			double sigmabottom = midintensity*(1-sigmarange);
			//calculate mean of values that differ are in sigma range.
			for (ix=0;ix<kernel;ix++)	{
					for (iy=0;iy<kernel;iy++)	{
							v = ip.getPixelValue(x+ix-radius,y+iy-radius);
							if ((v>=sigmabottom)&&(v<=sigmatop)){
								sum = sum+v;
								count = count+1;   }
								backupsum = v+ backupsum;
										}		
						}
//if there are too few pixels in the kernal that are within sigma range, the 
//mean of the entire kernal is taken. My modification of Lee's filter is to exclude the central value 
//from the calculation of the mean as I assume it to be spuriously high or low 
			if (!(count>(minpixnumber)))
				{sum = (backupsum-midintensity);
				count = (int)((kernel*kernel)-1);
				if (!modified)
					{sum = (backupsum);
					count  = (int)(kernel*kernel);}
				}
			
			double val =  (sum/count);
			ip.putPixelValue(x,y, val);
			n = n+1;
	double percentage = (((double)n/status)*100);
			 IJ.showStatus(IJ.d2s(percentage,0) +"% done");		
			
}

	//		IJ.showProgress(i, status);
					}}
			imp.updateAndDraw();
 			IJ.showStatus(IJ.d2s((System.currentTimeMillis()-start)/1000.0, 2)+" seconds");        }      
  private boolean showDialog() {
    String[] types = {"RAW", "JPEG", "ZLIB"};
    GenericDialog gd = new GenericDialog("Generate Bricks");
    gd.addChoice("FileType", types, filetype);
    gd.addNumericField("JPEG quality", jpeg_quality, 0);
    gd.addNumericField("Max file size (MB)", bdsizelimit, 0);

    int[] wlist = WindowManager.getIDList();
    if (wlist == null) return false;

    String[] titles = new String[wlist.length];
    for (int i = 0; i < wlist.length; i++) titles[i] = "";

    int tnum = 0;
    for (int i = 0; i < wlist.length; i++) {
      ImagePlus imp = WindowManager.getImage(wlist[i]);
      if (imp != null) {
        titles[tnum] = imp.getTitle();
        tnum++;
      }
    }
    gd.addChoice("Source image: ", titles, titles[0]);

    gd.showDialog();
    if (gd.wasCanceled()) return false;

    filetype = types[gd.getNextChoiceIndex()];
    jpeg_quality = (int) gd.getNextNumber();
    if (jpeg_quality > 100) jpeg_quality = 100;
    if (jpeg_quality < 0) jpeg_quality = 0;
    bdsizelimit = (int) gd.getNextNumber();

    int id = gd.getNextChoiceIndex();
    lvImgTitle = new ArrayList<String>();
    lvImgTitle.add(titles[id]);

    Prefs.set("filetype.string", filetype);
    Prefs.set("jpeg_quality.int", jpeg_quality);
    Prefs.set("bdsizelimit.int", bdsizelimit);

    return true;
  }
  public void run(String arg) {
    GenericDialog gd = new GenericDialog("Options");
    gd.addCheckbox("Acceptor_First", true);
    gd.showDialog();
    if (gd.wasCanceled()) return;
    boolean a1 = gd.getNextBoolean();
    int asp = 0;
    int dsp = 1;
    int aop = 2;
    int dop = 3;
    int atp = 4;
    int dtp = 5;
    if (!a1) {
      asp = 1;
      dsp = 0;
      aop = 3;
      dop = 2;
      atp = 5;
      dtp = 4;
    }
    ImageWindow iw = WindowManager.getCurrentWindow();
    float[][] xvals = (float[][]) jutils.runPW4VoidMethod(iw, "getXValues");
    float[][] yvals = (float[][]) jutils.runPW4VoidMethod(iw, "getYValues");
    int[] npts = (int[]) jutils.runPW4VoidMethod(iw, "getNpts");
    int maxpts = (int) jstatistics.getstatistic("Max", npts, null);
    int nsets = npts.length / 6;
    float[][] rtxvals = new float[nsets][maxpts];
    float[][] rtavals = new float[nsets][maxpts];
    float[][] rtdvals = new float[nsets][maxpts];
    int[] rtnpts = new int[nsets];
    int fretlength = 10;
    float[][] stfretvals = new float[nsets][fretlength];
    float[][] offfretvals = new float[nsets][fretlength];
    TextWindow tw = jutils.selectTable("DNA Damage FRET");
    if (tw == null)
      tw =
          new TextWindow(
              "DNA Damage FRET",
              "title\tacceptor\tdonor\testripe\teoff\tmaxart\tmaxdrt",
              "",
              400,
              200);
    // note that st stands for stripe and off is for areas off the damage stripe
    for (int i = 0; i < npts.length / 6; i++) {
      int len = npts[i * 6];
      int damageindex = findbleach(yvals[i * 6 + dsp], len);
      int fretindex = findbleach(yvals[i * 6 + atp], len);
      IJ.log("set " + i + " damage pos = " + damageindex + " , fret pos = " + fretindex);
      int predamagestart = damageindex - 4;
      int prefretstart = fretindex - 5;
      float staccpredam = getavg(yvals[i * 6 + asp], len, predamagestart, damageindex - 1);
      float stdonpredam = getavg(yvals[i * 6 + dsp], len, predamagestart, damageindex - 1);
      float nucaccpredam = getavg(yvals[i * 6 + atp], len, predamagestart, damageindex - 1);
      float nucdonpredam = getavg(yvals[i * 6 + dtp], len, predamagestart, damageindex - 1);
      float stdonprefret = getavg(yvals[i * 6 + dsp], len, prefretstart, fretindex - 2);
      float stdonafret = getavg(yvals[i * 6 + dsp], len, fretindex, fretindex + 3);
      float offdonprefret = getavg(yvals[i * 6 + dop], len, prefretstart, fretindex - 2);
      float offdonafret = getavg(yvals[i * 6 + dop], len, fretindex, fretindex + 3);
      float estripe = 1.0f - stdonprefret / stdonafret;
      float eoff = 1.0f - offdonprefret / offdonafret;
      rtnpts[i] = len;
      for (int j = 0; j < len; j++) {
        rtxvals[i][j] = j - damageindex - 1;
        rtavals[i][j] =
            (yvals[i * 6 + asp][j] / staccpredam) / (yvals[i * 6 + atp][j] / nucaccpredam);
        rtdvals[i][j] =
            (yvals[i * 6 + dsp][j] / stdonpredam) / (yvals[i * 6 + dtp][j] / nucdonpredam);
      }
      float[] smart = (float[]) algutils.get_subarray(rtavals[i], 0, fretindex);
      float[] smdrt = (float[]) algutils.get_subarray(rtdvals[i], 0, fretindex);
      jsmooth.blur1D(smart, 2.0f);
      jsmooth.blur1D(smdrt, 2.0f);
      float maxart = 0.0f;
      float maxdrt = 0.0f;
      for (int j = 0; j < fretindex - 2; j++) {
        if (smart[j] > maxart) maxart = smart[j];
        if (smdrt[j] > maxdrt) maxdrt = smdrt[j];
      }

      stfretvals[i] = getregion(yvals[i * 6 + dsp], len, prefretstart, fretlength);
      offfretvals[i] = getregion(yvals[i * 6 + dop], len, prefretstart, fretlength);
      tw.append(
          iw.getTitle()
              + "-"
              + (i + 1)
              + "\t"
              + staccpredam
              + "\t"
              + stdonpredam
              + "\t"
              + estripe
              + "\t"
              + eoff
              + "\t"
              + maxart
              + "\t"
              + maxdrt);
    }
    new PlotWindow4("Stripe_FRET_profiles", "time", "intensity", stfretvals, null).draw();
    new PlotWindow4("OffStripe_FRET_profiles", "time", "intensity", offfretvals, null).draw();
    new PlotWindow4("Acc_Rt_profiles", "time", "intensity", rtxvals, rtavals, rtnpts).draw();
    new PlotWindow4("Don_Rt_profiles", "time", "intensity", rtxvals, rtdvals, rtnpts).draw();
  }
Example #27
0
 public void run(String arg) {
   Frame[] niframes = WindowManager.getNonImageWindows();
   String[] titles = new String[niframes.length + 1];
   for (int i = 0; i < niframes.length; i++) {
     titles[i] = niframes[i].getTitle();
   }
   titles[niframes.length] = "Clipboard";
   GenericDialog gd = new GenericDialog("Windows");
   boolean importfile = false;
   gd.addCheckbox("Import from file?", importfile);
   gd.addChoice("Windows", titles, titles[0]);
   boolean hasxvals = false;
   gd.addCheckbox("X Vals Column?", hasxvals);
   boolean multix = false;
   gd.addCheckbox("Multi_X_Columns?", multix);
   boolean skipendzeros = false;
   gd.addCheckbox("Skip_end_zeros?", skipendzeros);
   String[] delimiters = {"Tab", "Comma", "Space"};
   gd.addChoice("Delimiter", delimiters, delimiters[0]);
   gd.showDialog();
   if (gd.wasCanceled()) {
     return;
   }
   importfile = gd.getNextBoolean();
   int index = gd.getNextChoiceIndex();
   hasxvals = gd.getNextBoolean();
   multix = gd.getNextBoolean();
   skipendzeros = gd.getNextBoolean();
   int delimindex = gd.getNextChoiceIndex();
   if (multix) hasxvals = true;
   String textdata = "";
   if (importfile) {
     OpenDialog od = new OpenDialog("Open File", "", ".txt");
     String directory = od.getDirectory();
     String name = od.getFileName();
     if (name == null) {
       return;
     }
     try {
       File infile = new File(directory + name);
       BufferedReader b = new BufferedReader(new FileReader(infile));
       textdata = (new jdataio()).readstringfile(b);
       b.close();
     } catch (IOException e) {
       return;
     }
   } else {
     if (index == niframes.length) {
       // here we get the data from the clipboard
       Transferable t = Toolkit.getDefaultToolkit().getSystemClipboard().getContents(null);
       try {
         if (t != null && t.isDataFlavorSupported(DataFlavor.stringFlavor)) {
           textdata = (String) t.getTransferData(DataFlavor.stringFlavor);
         }
       } catch (UnsupportedFlavorException e) {
       } catch (IOException e) {
       }
       if (textdata.equals("")) {
         IJ.error("Error copying from clipboard.");
         return;
       }
     } else {
       if (niframes[index] instanceof Editor) {
         Editor tw = (Editor) niframes[index];
         textdata = tw.getText();
       } else {
         if (niframes[index] instanceof TextWindow) {
           TextWindow tw = (TextWindow) niframes[index];
           textdata = tw.getTextPanel().getText();
         } else {
           IJ.showMessage("Not a valid text window");
           return;
         }
       }
     }
   }
   if (textdata == null) {
     IJ.showMessage("Error in Obtaining String");
     return;
   }
   if (textdata.indexOf("\r") >= 0) {
     textdata = textdata.replace('\r', '\n');
   }
   char[] delims = {'\t', ',', ' '};
   delimit_string ds = new delimit_string(delims[delimindex]);
   String[] rows = ds.getrows(textdata);
   int lines = rows.length;
   int columns = ds.getnumcolumns(rows[0]);
   int ycolumns = columns;
   if (hasxvals) {
     if (multix) {
       ycolumns /= 2;
     } else {
       ycolumns--;
     }
   }
   if (multix) {
     float[][] ydata = new float[ycolumns][lines];
     float[][] xdata = new float[ycolumns][lines];
     for (int i = 0; i < lines; i++) {
       float[] temp = ds.delim2float(rows[i], columns);
       for (int j = 0; j < ycolumns; j++) {
         ydata[j][i] = temp[2 * j + 1];
         xdata[j][i] = temp[2 * j];
       }
     }
     int[] npts = new int[ycolumns];
     for (int i = 0; i < ycolumns; i++) {
       npts[i] = lines;
     }
     if (skipendzeros) {
       for (int i = 0; i < ycolumns; i++) {
         int counter = lines - 1;
         while ((xdata[i][counter] == 0.0f || Float.isNaN(xdata[i][counter])) && counter > 0) {
           xdata[i][counter] = 0.0f;
           ydata[i][counter] = 0.0f;
           npts[i]--;
           counter--;
         }
       }
     }
     (new PlotWindow4("Text Plot", "x", "y", xdata, ydata, npts)).draw();
   } else {
     float[][] tempydata = new float[ycolumns][lines];
     float[] tempxdata = new float[lines];
     float[][] xdata = null;
     float[][] ydata = null;
     int startcolumn = 0;
     if (hasxvals) startcolumn = 1;
     for (int i = 0; i < lines; i++) {
       float[] temp = ds.delim2float(rows[i], columns);
       if (hasxvals) {
         tempxdata[i] = temp[0];
       } else {
         tempxdata[i] = (float) (i + 1);
       }
       for (int j = 0; j < ycolumns; j++) {
         tempydata[j][i] = temp[j + startcolumn];
       }
     }
     int[] npts = new int[ycolumns];
     npts[0] = lines;
     if (skipendzeros) {
       int maxpts = 0;
       for (int i = 0; i < ycolumns; i++) {
         int counter = lines - 1;
         npts[i] = lines;
         while ((tempydata[i][counter] == 0.0f || Float.isNaN(tempydata[i][counter]))
             && counter > 0) {
           npts[i]--;
           counter--;
         }
         if (npts[i] > maxpts) maxpts = npts[i];
         IJ.log("" + npts[i]);
       }
       ydata = new float[ycolumns][maxpts];
       xdata = new float[ycolumns][maxpts];
       for (int i = 0; i < ycolumns; i++) {
         // npts[i]=npts[0];
         System.arraycopy(tempxdata, 0, xdata[i], 0, npts[i]);
         System.arraycopy(tempydata[i], 0, ydata[i], 0, npts[i]);
       }
     } else {
       ydata = tempydata;
       xdata = new float[ycolumns][];
       for (int i = 0; i < ycolumns; i++) {
         npts[i] = npts[0];
         xdata[i] = tempxdata.clone();
       }
     }
     (new PlotWindow4("Text Plot", "x", "y", xdata, ydata, npts)).draw();
   }
 }
Example #28
0
  // Input/Output options
  void io() {
    GenericDialog gd = new GenericDialog("I/O Options");
    gd.addNumericField("JPEG quality (0-100):", FileSaver.getJpegQuality(), 0, 3, "");
    gd.addNumericField("GIF and PNG transparent index:", Prefs.getTransparentIndex(), 0, 3, "");
    gd.addStringField(
        "File extension for tables (.txt, .xls or .csv):", Prefs.get("options.ext", ".csv"), 4);
    gd.addCheckbox("Use JFileChooser to open/save", Prefs.useJFileChooser);
    if (!IJ.isMacOSX())
      gd.addCheckbox("Use_file chooser to import sequences", Prefs.useFileChooser);
    gd.addCheckbox("Save TIFF and raw in Intel byte order", Prefs.intelByteOrder);
    gd.addCheckbox("Skip dialog when opening .raw files", Prefs.skipRawDialog);

    gd.setInsets(15, 20, 0);
    gd.addMessage("Results Table Options");
    gd.setInsets(3, 40, 0);
    gd.addCheckbox("Copy_column headers", Prefs.copyColumnHeaders);
    gd.setInsets(0, 40, 0);
    gd.addCheckbox("Copy_row numbers", !Prefs.noRowNumbers);
    gd.setInsets(0, 40, 0);
    gd.addCheckbox("Save_column headers", !Prefs.dontSaveHeaders);
    gd.setInsets(0, 40, 0);
    gd.addCheckbox("Save_row numbers", !Prefs.dontSaveRowNumbers);

    gd.showDialog();
    if (gd.wasCanceled()) return;
    int quality = (int) gd.getNextNumber();
    if (quality < 0) quality = 0;
    if (quality > 100) quality = 100;
    FileSaver.setJpegQuality(quality);
    int transparentIndex = (int) gd.getNextNumber();
    Prefs.setTransparentIndex(transparentIndex);
    String extension = gd.getNextString();
    if (!extension.startsWith(".")) extension = "." + extension;
    Prefs.set("options.ext", extension);
    Prefs.useJFileChooser = gd.getNextBoolean();
    if (!IJ.isMacOSX()) Prefs.useFileChooser = gd.getNextBoolean();
    Prefs.intelByteOrder = gd.getNextBoolean();
    Prefs.skipRawDialog = gd.getNextBoolean();
    Prefs.copyColumnHeaders = gd.getNextBoolean();
    Prefs.noRowNumbers = !gd.getNextBoolean();
    Prefs.dontSaveHeaders = !gd.getNextBoolean();
    Prefs.dontSaveRowNumbers = !gd.getNextBoolean();
    return;
  }
 boolean init_functions() {
   GenericDialog gd = new GenericDialog("Fitting Options");
   gd.addStringField("Extra Definitions", exdef, 50);
   gd.addCheckbox("Weight Using Plot Errors", false);
   gd.addStringField("Weighting Equation (y is for data)", weightfunction, 50);
   gd.addStringField("Fit_Equation", function, 50);
   gd.showDialog();
   if (gd.wasCanceled()) {
     return false;
   }
   exdef = gd.getNextString();
   boolean errweights = gd.getNextBoolean();
   weightfunction = gd.getNextString();
   function = gd.getNextString();
   // first initialize the weights
   weights = new float[tempdata.length];
   if (errweights
       || weightfunction.equals("")
       || weightfunction == null
       || weightfunction == "1.0") {
     if (errweights) {
       for (int i = 0; i < tempdata.length; i++) weights[i] = 1.0f / (errs[i] * errs[i]);
     } else {
       for (int i = 0; i < tempdata.length; i++) weights[i] = 1.0f;
     }
   } else {
     for (int i = 0; i < tempdata.length; i++) {
       String script =
           "y =" + tempdata[i] + "; " + "x =" + tempx[i] + "; " + "retval=" + weightfunction + ";";
       Double temp = new Double(0.0);
       try {
         temp = (Double) engine.eval(script);
       } catch (Exception e) {
         IJ.log(e.getMessage());
       }
       if (!(temp.isInfinite() || temp.isNaN())) {
         weights[i] = temp.floatValue();
       }
     }
   }
   // now compile the function script
   try {
     String script1 = exdef + "; retval=" + function + ";";
     cs = ce.compile(script1);
   } catch (Exception e) {
     IJ.log(e.toString());
     return false;
   }
   return true;
 }
 boolean showoptions(double[] params, int[] fixes) {
   // GenericDialog gd=new NonBlockingGenericDialog("Options");
   GenericDialog gd = new GenericDialog("Options");
   gd.addCheckbox("Check Chi Squared", checkc2);
   for (int i = 0; i < 10; i++) {
     gd.addNumericField("P" + (i + 1), params[i], 5, 10, null);
     gd.addCheckbox("Fix?", (fixes[i] == 1));
   }
   gd.addCheckbox("Get_Errors", false);
   gd.addCheckbox("Set_Constraints", false);
   gd.addNumericField("Iterations", iterations, 0, 10, null);
   gd.addNumericField("chi squared", c2, 5, 10, null);
   gd.addDialogListener(this);
   gd.showDialog();
   if (gd.wasCanceled()) {
     return false;
   }
   checkc2 = gd.getNextBoolean();
   for (int i = 0; i < 10; i++) {
     params[i] = gd.getNextNumber();
     if (gd.getNextBoolean()) {
       fixes[i] = 1;
     } else {
       fixes[i] = 0;
     }
   }
   boolean geterrors = gd.getNextBoolean();
   boolean setconstraints = gd.getNextBoolean();
   for (int i = 0; i < 10; i++) {
     if (function.indexOf("P" + (i + 1)) < 0) {
       fixes[i] = 1;
     }
   }
   if (geterrors) {
     if (!get_errors(params, fixes)) {
       return false;
     }
   }
   if (setconstraints) constraints = get_constraints(params);
   return true;
 }