Greetings Michael,

Thanks to your help, I got it working...

Concerning the impetus of getting this method to work at this time;
eliminating the error/debug window upon an error: There is a method
interpreter.setIgnoreErrors(true) that does just that, even though no
exceptions or wasError()==true upon error, getErrorMessage() only returned
a String upon an error.

Concerning the need for "function dummy() {}": With or without it there
are no errors when the offset is 0, although without it the variables are
all 0 after the run(0) call. So with it I do not need to calculate the
correct(?) offset. Note: I guessed that "new
Tokenizer().tokenize(preamble).macroCount();" should calculate the
correct(?) offset for me, albeit it always returns zero.

Concerning setting arrays: The attached implementation works. I have
included two methods for Interpreter that should allow (s|g)etting of
arrays; at least double arrays.

Thanks again,

Fred

PS: Sometimes physicists are the best computer scientists...



   public static ImagePlus macro(String macro, ImagePlus ... imps) {
      String code = "var x, y, z, f, w, h, a, d, v, va, ";
      String[] vna = new String[imps.length];
      Arrays.setAll(vna, i -> "v"+i);
      code += String.join(",",vna)+";\n";
      code += "function dummy() {}\n";
      int offset = new Tokenizer().tokenize(code).macroCount();
//offset=29 -6;
      IJ.log("======= preamble("+offset+") ======\n"+code);
      if (imps.length == 1) code += "va=newArray(1);va[0]="+vna[0]+";\n";
                       else code +=
"va=newArray("+String.join(",",vna)+");\n";
      code += macro;
      IJ.log("======= code ======\n"+code);

      Interpreter interpreter = new Interpreter();
      interpreter.setIgnoreErrors(true);
      try { interpreter.run(code, null); } catch (Exception e) {
IJ.log("Interpreter throw(ed) an exception.");   throw(e); }
      if (interpreter.wasError())                              {
IJ.log("Interpreter.wasError() returned true."); return null; }
      String em = interpreter.getErrorMessage();
      if (em != null)                                          {
IJ.log("errorMessage="+em); return null; }

      IJ.log("======= running =======");
//      for(String str : interpreter.getVariables())
  //       IJ.log(str);
      int e = 0, en = 10;
      ImagePlus resimp = imps[0].duplicate();
      resimp.setTitle(imps[0].getTitle()+" macro results");
      resimp.setProp("macro",macro);
      resimp.setProp("sources",String.join(";",imps2titles(imps)));
      int nx = resimp.getWidth(),  xc = nx/2;
      int ny = resimp.getHeight(), yc = ny/2;
      int nf = resimp.getNFrames();
      int ns = resimp.getNSlices();
      float[][] rfa = new float[nx][ny];
      for(int f=0; f<nf; f++)
         for(int s=0; s<ns; s++) {
            float[][][] fa = new float[imps.length][][];
            for(int i=0; i<imps.length; i++)
               fa[i] =
imps[i].getStack().getProcessor(imps[i].getStackIndex(1,s+1,f+1)).getFloatArray();
            int si = resimp.getStackIndex(1,s+1,f+1);
            ImageProcessor ip = resimp.getStack().getProcessor(si);
            for(int x=0; x<nx; x++)
               for(int y=0; y<ny; y++) try {
                  interpreter.setVariable("f",f+1);
                  interpreter.setVariable("z",s+1);
                  interpreter.setVariable("x",x);
                  interpreter.setVariable("y",y);
                  interpreter.setVariable("w",nx);
                  interpreter.setVariable("h",ny);
                  interpreter.setVariable("a",Math.atan2(y-yc, x-xc));
                  interpreter.setVariable("d",Math.hypot(y-yc,x-xc));
                  interpreter.setVariable("v",fa[0][x][y]);
                  for(int i=0; i<imps.length; i++)
                     interpreter.setVariable("v"+i,fa[i][x][y]);
if (f==0 && s==0 && x==1 && y==1) {
   for(String str : interpreter.getVariableNames())
      IJ.log(str+" = "+interpreter.getVariable(str));
      IJ.log("errorMessage="+interpreter.getErrorMessage());
   }
                  interpreter.run(offset);
                  if (interpreter.wasError() && e<en)
                     IJ.log("macro error "+(++e)+"
at("+(f+1)+","+(s+1)+","+x+","+y+")
"+interpreter.getErrorMessage());
                  em = interpreter.getErrorMessage();
                  if (em != null) { IJ.log("errorMessage="+em); return
null; }
if (f==0 && s==0 && x==1 && y==1) {
   for(String str : interpreter.getVariableNames())
      IJ.log(str+" = "+interpreter.getVariable(str));
      IJ.log("errorMessage="+interpreter.getErrorMessage());
   }
                  rfa[x][y] = (float)interpreter.getVariable("v");
                  } catch(Exception ex) {IJ.log("Exception "+ex);
throw(ex); }
            ip.setFloatArray(rfa);
            resimp.getStack().setProcessor(ip,si);
            }
      return resimp;
      }



// Interpreter.java
   public void setArray(String name, double ... arr) {
      for(int i=0; i<=topOfStack; i++) {
         if (pgm.table[stack[i].symTableIndex].str.equals(name)) {
            stack[i].setArray(new Variable(arr));
            stack[i].setArraySize(arr.length);
            return;
            }
      }

   public double[] getArray(String name) {
      for(int i=0; i<=topOfStack; i++) {
         if (pgm.table[stack[i].symTableIndex].str.equals(name)) {
            Variable[] varr = stack[i].getArray();
            double[] arr = new double[stack[i].getArraySize()];
            Arrays.setAll(arr, i -> varr[i].getValue();
            return arr;
            }
      return Double.NaN;
      }


On Thu, July 2, 2026 2:58 pm, Michael Schmid wrote:
> Hi Fred,
>
> concerning the details of the Macro interpreter, I must admit that I am
> a physicist and I have always looked up with awe to computer scientists
> who can do things like writing an interpreter or compiler.
> When using the Interpreter, I simply look at Wayne's examples and try to
> copy them.
> Another example is Process>Math>Macro,
>
> https://github.com/imagej/ImageJ/blob/master/ij/plugin/filter/ImageMath.java#L230
>
> If "in unison" means multi-threaded, I fear that this is not possible. I
> have the impression that there are many places that rely on only one
> instance of the Interpreter being active at a time.
>
> I have never tried to understand the reason for the "function dummy()
> {}\n". Maybe it is meant to avoid running beyond the variable
> definitions in the initial call interpreter.run(code, null)
>
> Concerning the offset: One simply has to count the tokens in the
> "preamble", i.e., in the code before the one that actually does the
> work. Every keyword, variable or function name, comma, semicolon,
> operator or bracket is one token. Whitespace is not a token.
> In the CurveFitter, we have
> "var x, a, b, c, d, e, f; function dummy() {}"
> These are 21 tokens. So you need an offset of 21 to start the
> interpreter at the code position following this preamble.
> If the number of variables is not always the same, you can't have a
> fixed offset but you have to adjust the offset according to how many
> variables you define. In a list like this, each additional variable
> would result in two additional tokens, the name and the comma.
>
> As I understand it, you should define all input variables for your macro
> with "var" in the preamble as above.
>
> After the initial call to interpreter.run(code, null), you can supply
> variable values with interpreter.setVariable and run
> interpreter.run(offset) for each set of variables that you like.
> Use interp.getVariable to get the results(s).
> I think that this way of doing it is meant to reuse the interpreter
> without the overhead of tokenizing, for better performance.
>
> Concerning
>  > I did not find a way to generate a Program:
> Looking at the Interpreter code, it seems that one can generate a
> program with
>    Tokenizer tokenizer = new Tokenizer();
>    Program program = tokenizer.tokenize(macroCodeString);
> I have never tried using this.
>
>  > I assume that the (g|s)etVariable does not work with arrays.
> Yes, one needs some workaround. Your way of having variables v0, v1,
> v2,... looks reasonable, but you also need to define them in the
> preamble with var v0, v1, ...
>
> hth,
>
> Michael
> ________________________________________________________________
> On 02.07.26 20:46, Fred Damen wrote:
>> Greetings Michael,
>>
>> In an attempt to implement the ability to run the equivalent of
>> Process/Math/Marco... on multiple images in unison, I am trying to
>> borrow
>> code indirectly from CurveFitter. The problem is I do not know how to
>> determine the offset passed to Interpreter.run(int offset). Could you
>> explain how to determine this offset?
>>
>> A few other questions...
>> a) is the "function dummy() {}\n" needed in the beginning of the macro?
>> if
>> so, why? Does this somehow separate variable definitions from executable
>> code?
>>
>> b) I assume that the Interpreter.run(macro, argument) is called to
>> compile
>> the macro into a Program that is somehow stored in the Interpreter
>> object.
>> So, can the Interpreter.run(offset) be called multiple times with
>> different Interpreter.(g|s)etVariable calls? Or does the String macro
>> need
>> to be recompiled each time?
>>
>> c) I noticed a Interpreter.run(Program, offset) method, albeit, I did
>> not
>> find a way to generate a Program. Is this an avenue I should explore, or
>> ignore?
>>
>> d) I assume that the (g|s)etVariable does not work with arrays. Is there
>> a
>> better way to pass an array than what I have attempted?
>>
>> Thanks in advance,
>>
>> Fred
>>
>> code: in case I did not explain the questions well...
>>
>>     public static ImagePlus macro(String macro, ImagePlus ... imps) {
>>        String code = "var x, y, ";
>>        String[] vna = new String[imps.length];
>>        Array.setAll(vna, i -> "v"+i);
>>        code += String.join(",",vna)+";\n";
>>        code += "va=newArray("+String.join(",",vna)+");"\n;
>>        code += macro;
>>        IJ.log("======= code ======\n"+code);
>>
>>        Interpreter interpreter = new Interpreter();
>>        try { interpreter.run(code, null); } catch (Exception e) {
>> status("Interpreter throw(ed) an exception.");   throw(e); }
>>        if (interpreter.wasError())                              {
>> status("Interpreter.wasError() returned true."); return null; }
>>
>>        int e = 0, en = 10;
>>        ImagePlus resimp = imps[0].duplicate();
>>        resimp.setTitle(imps[0].getTitle()+" macro results");
>>        float[][] rfa = new float[nx][ny];
>>        for(int f=0; f<nf; f++)
>>           for(int s=0; s<ns; s++) {
>>              float[][][] fa = new float[imps.length][][];
>>              Arrays.setAll(fa, i ->
>> imps[i].getStack().getProcessor(imps[i].getStackIndex(1,s+1,f+1).getFloatArray());
>>              for(int x=0; x<nx; x++)
>>                 for(int y, y<ny; y++) try {
>>                    interpreter.setVariable("f",f+1);
>>                    interpreter.setVariable("s",s+1);
>>                    interpreter.setVariable("x",x);
>>                    interpreter.setVariable("y",y);
>>                    interpreter.setVariable("v",fa[0][x][y]);
>>                    for(int i=0; i<imps.length; i++)
>>                       interpreter.setVariable("v"+i,fa[i][x][y];
>>                    macro.run(39); // 21);
>>                    if (interpreter.wasError() && e<en)
>>                       IJ.log("macro error "+(++e)+"
>> at("+(f+1)+","+"(s+1)+","+x+","+y+")
>> "+interpreter.getErrorMessage());
>>                    rfa[x][y] = (float)macro.getVariable("v");
>>                    } catch(Exception e) {IJ.log("Exception "+e);
>> throw(e); }
>>              
>> resimp.getStack().getProcessor(resimp.getStackIndex(1,s+1,f+1)).setFloatArray(rfa);
>>              }
>>        return resimp;
>>        }
>>
>> On Tue, June 30, 2026 4:08 pm, Fred Damen wrote:
>>> Greetings Michael,
>>>
>>> I am on 1.54p, so an upgrade is in order. This will lower the
>>> aggravation
>>> level dramatically.
>>>
>>> Thanks for the suggestions for running a macro, albeit I need to run
>>> the
>>> equivalent of Process/Math/Macro...
>>>
>>> Thanks for the info,
>>>
>>> Fred
>>>
>>> On Mon, June 29, 2026 11:07 am, Michael Schmid wrote:
>>>> Hi Fred,
>>>>
>>>> which version of ImageJ are you using?
>>>>
>>>> There was a change in 1.54s13 that should avoid deadlocks with
>>>> NonBlockingGenericDialogs.
>>>>
>>>> Anyhow, to run a macro from a Java plugin, I would propose
>>>>     String result = IJ.runMacro(String macro);
>>>> or
>>>>     String result = IJ.runMacro(String macro, String arg);
>>>>
>>>> According to the documantation, the result String is "[aborted]" in
>>>> case
>>>> of an error. See
>>>>     https://github.com/imagej/ImageJ/blob/master/ij/IJ.java#L153
>>>>
>>>>
>>>> Michael
>>>> ________________________________________________________________
>>>> On 28.06.26 22:52, Fred Damen wrote:
>>>>> Greetings,
>>>>>
>>>>> I write / run a plugin that needs to run a macro, that is generated,
>>>>> on
>>>>> a
>>>>> ImagePlus:
>>>>> String macro = ...
>>>>> IJ.run(tmpimp, "Macro...", "code=[ "+macro+" ] stack");
>>>>>
>>>>> The problem is if there is a error in the macro a
>>>>> NonblockingGenericDialog
>>>>> is called and then ImageJ locks up hard; ... cancel and restart.
>>>>>
>>>>> Is there a way to run a macro on an image from a plugin and if there
>>>>> is
>>>>> an
>>>>> error to throw an exception instead of invoking a dialog???
>>>>>
>>>>> Thanks in advance,
>>>>>
>>>>> Fred
>>>>>
>>>>> PS: the code snipit that was considered an error was a variable
>>>>> subtracting a negative constant: v--1
>>>>>
>>>>> PSS: a side note: leave the "code=" off the arguments and the
>>>>> Macro...
>>>>> call is silently ignored.
>>>>>
>>>>> --
>>>>> ImageJ mailing list: http://imagej.nih.gov/ij/list.html
>>>>
>>>> --
>>>> ImageJ mailing list: http://imagej.nih.gov/ij/list.html
>>>>
>>>
>>> --
>>> ImageJ mailing list: http://imagej.nih.gov/ij/list.html
>>>
>>
>> --
>> ImageJ mailing list: http://imagej.nih.gov/ij/list.html
>
> --
> ImageJ mailing list: http://imagej.nih.gov/ij/list.html
>

--
ImageJ mailing list: http://imagej.nih.gov/ij/list.html

Reply via email to