/**
   * This method is required if the AlgorithmPerformed interface is implemented. It is called by the
   * algorithms when it has completed or failed to to complete, so that the dialog can be display
   * the result image and/or clean up.
   *
   * @param algorithm Algorithm that caused the event.
   */
  public void algorithmPerformed(AlgorithmBase algorithm) {

    if (algorithm instanceof AlgorithmNonlocalMeansFilter) {
      image.clearMask();

      if ((nlMeansFilterAlgo.isCompleted() == true) && (resultImage != null)) {

        updateFileInfo(image, resultImage);
        resultImage.clearMask();

        // The algorithm has completed and produced a new image to be displayed.
        try {
          new ViewJFrameImage(resultImage, null, new Dimension(610, 200));
        } catch (OutOfMemoryError error) {
          MipavUtil.displayError("Out of memory: unable to open new frame");
        }
      } else if (resultImage == null) {

        // These next lines set the titles in all frames where the source image is displayed to
        // image name so as to indicate that the image is now unlocked!
        // The image frames are enabled and then registed to the userinterface.
        Vector<ViewImageUpdateInterface> imageFrames = image.getImageFrameVector();

        for (int i = 0; i < imageFrames.size(); i++) {
          ((Frame) (imageFrames.elementAt(i))).setTitle(titles[i]);
          ((Frame) (imageFrames.elementAt(i))).setEnabled(true);

          if (((Frame) (imageFrames.elementAt(i))) != parentFrame) {
            userInterface.registerFrame((Frame) (imageFrames.elementAt(i)));
          }
        }

        if (parentFrame != null) {
          userInterface.registerFrame(parentFrame);
        }

        image.notifyImageDisplayListeners(null, true);
      } else if (resultImage != null) {

        // algorithm failed but result image still has garbage
        resultImage.disposeLocal(); // clean up memory
        resultImage = null;
      }
    }

    if (algorithm.isCompleted()) {
      insertScriptLine();
    }
    // save the completion status for later
    setComplete(algorithm.isCompleted());

    nlMeansFilterAlgo.finalize();
    nlMeansFilterAlgo = null;
    dispose();
  }
 /**
  * Creates a new JDialogNonlocalMeansFilter object.
  *
  * @param theParentFrame Parent frame.
  * @param im Source image.
  */
 public JDialogNonlocalMeansFilter(Frame theParentFrame, ModelImage im) {
   super(theParentFrame, false);
   image = im;
   userInterface = ViewUserInterface.getReference();
   init();
   setVisible(true);
 }
  /** {@inheritDoc} */
  protected void setGUIFromParams() {
    image = scriptParameters.retrieveInputImage();
    userInterface = ViewUserInterface.getReference();
    parentFrame = image.getParentFrame();

    if (scriptParameters.doOutputNewImage()) {
      setDisplayLocNew();
    } else {
      setDisplayLocReplace();
    }

    searchWindowSide = scriptParameters.getParams().getInt("search_window_side");
    similarityWindowSide = scriptParameters.getParams().getInt("similarity_window_side");
    noiseStandardDeviation = scriptParameters.getParams().getFloat("noise_standard_deviation");
    degreeOfFiltering = scriptParameters.getParams().getFloat("degree_of_filtering");
    doRician = scriptParameters.getParams().getBoolean("do_rician");
    image25D = scriptParameters.doProcess3DAs25D();
  }
  /** {@inheritDoc} */
  protected void setGUIFromParams() {
    image = scriptParameters.retrieveInputImage(1);

    userInterface = ViewUserInterface.getReference();
    parentFrame = image.getParentFrame();

    if (scriptParameters.doOutputNewImage()) {
      setDisplayLocNew();
    } else {

      // replace processing not supported..
      // setDisplayLocReplace();
      setDisplayLocNew();
    }

    subXDim = scriptParameters.getParams().getInt("sub_x_dim");
    subYDim = scriptParameters.getParams().getInt("sub_y_dim");
    numberOfImagesInMosaic = scriptParameters.getParams().getInt("number_of_images_in_mosaic");
  }
  /** Starts the program. */
  public void runAlgorithm() {
    int i, j, k;

    if (srcImage == null) {
      displayError("Source Image is null");
      finalize();

      return;
    }

    if (threadStopped) {
      finalize();

      return;
    }

    trueVOIs = srcImage.getVOIs();
    nTrueVOIs = trueVOIs.size();
    testVOIs = testImage.getVOIs();
    nTestVOIs = testVOIs.size();
    length = srcImage.getExtents()[0];

    for (i = 1; i < srcImage.getNDims(); i++) {
      length *= srcImage.getExtents()[i];
    }

    testLength = testImage.getExtents()[0];

    for (i = 1; i < testImage.getNDims(); i++) {
      testLength *= testImage.getExtents()[i];
    }

    if (length != testLength) {
      MipavUtil.displayError(
          srcImage.getImageName()
              + " and "
              + testImage.getImageName()
              + " are unequal in dimensions");
      setCompleted(false);

      return;
    }

    trueMask = new short[length];
    testMask = new short[length];
    ViewUserInterface.getReference().setGlobalDataText(srcImage.getImageName() + " = true\n");
    ViewUserInterface.getReference().setGlobalDataText(testImage.getImageName() + " = test\n");

    for (i = 0; i < nTrueVOIs; i++) {

      if ((trueVOIs.VOIAt(i).getCurveType() == VOI.CONTOUR)
          || (trueVOIs.VOIAt(i).getCurveType() == VOI.POLYLINE)) {
        trueID = trueVOIs.VOIAt(i).getID();

        for (j = 0; j < nTestVOIs; j++) {
          testID = testVOIs.VOIAt(j).getID();

          if (trueID == testID) {

            for (k = 0; k < length; k++) {
              trueMask[k] = -1;
              testMask[k] = -1;
            }

            trueMask = srcImage.generateVOIMask(trueMask, i);
            testMask = testImage.generateVOIMask(testMask, j);
            absoluteTrue = 0;
            trueFound = 0;
            falseNegative = 0;
            falsePositive = 0;

            for (k = 0; k < length; k++) {

              if (trueMask[k] == trueID) {
                absoluteTrue++;

                if (testMask[k] == trueID) {
                  trueFound++;
                } else {
                  falseNegative++;
                }
              } // if (trueMask[k] == trueID)
              else { // trueMask[k] != trueID

                if (testMask[k] == trueID) {
                  falsePositive++;
                }
              } // else trueMask[k] != trueID
            } // for (k = 0; k < length; k++)

            ViewUserInterface.getReference()
                .setGlobalDataText(
                    "Statistics for VOIs with ID = " + String.valueOf(trueID) + "\n");
            fnvf = (float) falseNegative / (float) absoluteTrue;
            ViewUserInterface.getReference()
                .setGlobalDataText(
                    "     False negative volume fraction = " + String.valueOf(fnvf) + "\n");
            fpvf = (float) falsePositive / (float) absoluteTrue;
            ViewUserInterface.getReference()
                .setGlobalDataText(
                    "     False positive volume fraction = " + String.valueOf(fpvf) + "\n");
            tpvf = (float) trueFound / (float) absoluteTrue;
            ViewUserInterface.getReference()
                .setGlobalDataText(
                    "     True Positive volume fraction = " + String.valueOf(tpvf) + "\n\n");
          } // if (trueID == testID)
        } // for (j = 0; j < nTestVOIs; j++)
      } // if ((trueVOIs.VOIAt(i).getCurveType() == VOI.CONTOUR)
    } // for (i = 0; i < nTrueVOIs; i++)

    setCompleted(true);
  }
  /**
   * Once all the necessary variables are set, call the Nonlocal Means filter algorithm based on
   * what type of image this is and whether or not there is a separate destination image.
   */
  protected void callAlgorithm() {
    String name = makeImageName(image.getImageName(), "_NonlocalMeans");
    int[] destExtents;

    if (image.getNDims() == 2) { // source image is 2D
      destExtents = new int[2];
      destExtents[0] = image.getExtents()[0]; // X dim
      destExtents[1] = image.getExtents()[1]; // Y dim
    } else {
      destExtents = new int[3];
      destExtents[0] = image.getExtents()[0];
      destExtents[1] = image.getExtents()[1];
      destExtents[2] = image.getExtents()[2];
    }

    if (displayLoc == NEW) {

      try {

        // Make result image of float type
        if (image.isColorImage()) {
          resultImage = new ModelImage(ModelImage.ARGB, destExtents, name);
        } else {
          resultImage = new ModelImage(ModelImage.FLOAT, destExtents, name);
        }

        // resultImage = (ModelImage)image.clone();
        // resultImage.setImageName(name);
        // Make algorithm
        nlMeansFilterAlgo =
            new AlgorithmNonlocalMeansFilter(
                resultImage,
                image,
                searchWindowSide,
                similarityWindowSide,
                noiseStandardDeviation,
                degreeOfFiltering,
                doRician,
                image25D);

        // This is very important. Adding this object as a listener allows the algorithm to
        // notify this object when it has completed of failed. See algorithm performed event.
        // This is made possible by implementing AlgorithmedPerformed interface
        nlMeansFilterAlgo.addListener(this);
        createProgressBar(image.getImageName(), nlMeansFilterAlgo);

        // Hide dialog
        setVisible(false);

        if (isRunInSeparateThread()) {

          // Start the thread as a low priority because we wish to still have user interface work
          // fast
          if (nlMeansFilterAlgo.startMethod(Thread.MIN_PRIORITY) == false) {
            MipavUtil.displayError("A thread is already running on this object");
          }
        } else {
          nlMeansFilterAlgo.run();
        }
      } catch (OutOfMemoryError x) {
        MipavUtil.displayError("Dialog Nonlocal Means Filter: unable to allocate enough memory");

        if (resultImage != null) {
          resultImage.disposeLocal(); // Clean up memory of result image
          resultImage = null;
        }

        return;
      }
    } else {

      try {

        // No need to make new image space because the user has choosen to replace the source image
        // Make the algorithm class
        nlMeansFilterAlgo =
            new AlgorithmNonlocalMeansFilter(
                null,
                image,
                searchWindowSide,
                similarityWindowSide,
                noiseStandardDeviation,
                degreeOfFiltering,
                doRician,
                image25D);

        // This is very important. Adding this object as a listener allows the algorithm to
        // notify this object when it has completed of failed. See algorithm performed event.
        // This is made possible by implementing AlgorithmedPerformed interface
        nlMeansFilterAlgo.addListener(this);
        createProgressBar(image.getImageName(), nlMeansFilterAlgo);

        // Hide the dialog since the algorithm is about to run.
        setVisible(false);

        // These next lines set the titles in all frames where the source image is displayed to
        // "locked - " image name so as to indicate that the image is now read/write locked!
        // The image frames are disabled and then unregisted from the userinterface until the
        // algorithm has completed.
        Vector<ViewImageUpdateInterface> imageFrames = image.getImageFrameVector();
        titles = new String[imageFrames.size()];

        for (int i = 0; i < imageFrames.size(); i++) {
          titles[i] = ((Frame) (imageFrames.elementAt(i))).getTitle();
          ((Frame) (imageFrames.elementAt(i))).setTitle("Locked: " + titles[i]);
          ((Frame) (imageFrames.elementAt(i))).setEnabled(false);
          userInterface.unregisterFrame((Frame) (imageFrames.elementAt(i)));
        }

        if (isRunInSeparateThread()) {

          // Start the thread as a low priority because we wish to still have user interface work
          // fast
          if (nlMeansFilterAlgo.startMethod(Thread.MIN_PRIORITY) == false) {
            MipavUtil.displayError("A thread is already running on this object");
          }
        } else {
          nlMeansFilterAlgo.run();
        }
      } catch (OutOfMemoryError x) {
        MipavUtil.displayError("Dialog Nonlocal Means Filter: unable to allocate enough memory");

        return;
      }
    }
  }
 /**
  * Creates new Mosaic To Slices dialog.
  *
  * @param theParentFrame Parent frame.
  * @param im Source image.
  */
 public JDialogMosaicToSlices(Frame theParentFrame, ModelImage im) {
   super(theParentFrame, false);
   image = im;
   userInterface = ViewUserInterface.getReference();
   init();
 }
  /**
   * Once all the necessary variables are set, call the Concat algorithm based on what type of image
   * this is and whether or not there is a separate destination image.
   */
  protected void callAlgorithm() {
    int destExtents[] = new int[3];
    ModelImage destImage = null;

    destExtents[0] = subXDim;
    destExtents[1] = subYDim;
    destExtents[2] = numberOfImagesInMosaic;

    destImage =
        new ModelImage(
            image.getType(), destExtents, makeImageName(image.getImageName(), "_mosaic_to_slices"));

    try {

      // Make algorithm
      mathAlgo = new AlgorithmMosaicToSlices(image, destImage);

      // This is very important. Adding this object as a listener allows the algorithm to
      // notify this object when it has completed of failed. See algorithm performed event.
      // This is made possible by implementing AlgorithmedPerformed interface
      mathAlgo.addListener(this);

      createProgressBar(image.getImageName(), mathAlgo);

      // Hide dialog
      setVisible(false);

      if (displayLoc == REPLACE) {

        // These next lines set the titles in all frames where the source image is displayed to
        // "locked - " image name so as to indicate that the image is now read/write locked!
        // The image frames are disabled and then unregisted from the userinterface until the
        // algorithm has completed.
        Vector<ViewImageUpdateInterface> imageFrames = image.getImageFrameVector();
        titles = new String[imageFrames.size()];

        for (int i = 0; i < imageFrames.size(); i++) {
          titles[i] = ((Frame) (imageFrames.elementAt(i))).getTitle();
          ((Frame) (imageFrames.elementAt(i))).setTitle("Locked: " + titles[i]);
          ((Frame) (imageFrames.elementAt(i))).setEnabled(false);
          userInterface.unregisterFrame((Frame) (imageFrames.elementAt(i)));
        }
      }

      if (isRunInSeparateThread()) {

        // Start the thread as a low priority because we wish to still have user interface work
        // fast.
        if (mathAlgo.startMethod(Thread.MIN_PRIORITY) == false) {
          MipavUtil.displayError("A thread is already running on this object");
        }

      } else {

        mathAlgo.run();
      }
    } catch (OutOfMemoryError x) {
      System.gc();
      MipavUtil.displayError("Dialog Concatenation: unable to allocate enough memory");

      return;
    }
  }
  /**
   * This method is required if the AlgorithmPerformed interface is implemented. It is called by the
   * algorithms when it has completed or failed to to complete, so that the dialog can be display
   * the result image and/or clean up.
   *
   * @param algorithm Algorithm that caused the event.
   */
  public void algorithmPerformed(AlgorithmBase algorithm) {
    ViewJFrameImage imageFrame = null;

    if (algorithm instanceof AlgorithmMosaicToSlices) {

      if ((mathAlgo.isCompleted() == true) && (mathAlgo.getResultImage() != null)) {

        // The algorithm has completed and produced a new image to be displayed.
        if (displayLoc == NEW) {

          try {
            resultImage = mathAlgo.getResultImage();

            new ViewJFrameImage(resultImage, null, new Dimension(610, 200));
          } catch (OutOfMemoryError error) {
            System.gc();
            MipavUtil.displayError("Out of memory: unable to open new frame");
          }
        } else {

          // These next lines set the titles in all frames where the source image is displayed to
          // image name so as to indicate that the image is now unlocked!
          // The image frames are enabled and then registed to the userinterface.
          resultImage = mathAlgo.getResultImage();

          Vector<ViewImageUpdateInterface> imageFrames = image.getImageFrameVector();

          for (int i = 0; i < imageFrames.size(); i++) {
            ((Frame) (imageFrames.elementAt(i))).setTitle(titles[i]);
            ((Frame) (imageFrames.elementAt(i))).setEnabled(true);

            if ((((Frame) (imageFrames.elementAt(i))) != parentFrame) && (parentFrame != null)) {
              userInterface.registerFrame((Frame) (imageFrames.elementAt(i)));
            }
          }

          Point pt;

          if (parentFrame != null) {
            pt = ((ViewJFrameBase) parentFrame).getLocation();
          } else {
            pt =
                new Point(
                    Toolkit.getDefaultToolkit().getScreenSize().width / 2,
                    Toolkit.getDefaultToolkit().getScreenSize().height / 2);
          }

          imageFrame = new ViewJFrameImage(resultImage, null, new Dimension(pt.x, pt.y));

          if (parentFrame != null) {
            ((ViewJFrameBase) parentFrame).close();
          } else {
            ((ViewJFrameBase) image.getParentFrame()).close();
          }

          // Not so sure about this.
          if (image.getLightBoxFrame() != null) {

            try {
              pt = image.getLightBoxFrame().getLocation();
              image.getLightBoxFrame().close();
              new ViewJFrameLightBox(
                  imageFrame,
                  "LightBox",
                  resultImage,
                  imageFrame.getComponentImage().getLUTa(),
                  imageFrame.getComponentImage().getImageB(),
                  imageFrame.getComponentImage().getLUTb(),
                  imageFrame.getComponentImage().getResolutionX(),
                  imageFrame.getComponentImage().getResolutionY(),
                  new Dimension(pt.x, pt.y),
                  imageFrame.getControls(),
                  imageFrame.getVOIManager());
            } catch (OutOfMemoryError error) {
              MipavUtil.displayError("Out of memory: unable to open new frame");
            }
          }
        }
      } else if (resultImage == null) {

        // These next lines set the titles in all frames where the source image is displayed to
        // image name so as to indicate that the image is now unlocked!
        // The image frames are enabled and then registered to the userinterface.
        /*Vector imageFrames = imageA.getImageFrameVector();

        for (int i = 0; i < imageFrames.size(); i++) {
            ((Frame) (imageFrames.elementAt(i))).setTitle(titles[i]);
            ((Frame) (imageFrames.elementAt(i))).setEnabled(true);

            if (((Frame) (imageFrames.elementAt(i))) != parentFrame) {
                userInterface.registerFrame((Frame) (imageFrames.elementAt(i)));

            }
        }*/

        if (parentFrame != null) {
          userInterface.registerFrame(parentFrame);
        }

        image.notifyImageDisplayListeners(null, true);
      } else if (resultImage != null) {

        // algorithm failed but result image still has garbage
        resultImage.disposeLocal(); // clean up memory
        System.gc();
      }
    }

    if (algorithm.isCompleted()) {
      insertScriptLine();
    }

    mathAlgo.finalize();
    mathAlgo = null;
    dispose();
  }