Difference between revisions of "Script Parameters"

(Parameter properties: Quote properties to be future-proof!)
m (Visibility: Set required=false for MESSAGE parameters)
 
(64 intermediate revisions by 11 users not shown)
Line 1: Line 1:
{{Scripting}}
+
{{Learn | scripting}}All scripting languages have access to a universal <code>#@parameter</code> notation for declaring inputs and outputs. This approach is preferred over the ImageJ 1.x [[Generic dialog|GenericDialog]] because it is totally agnostic of the user interface, allowing such scripts to run in a variety of contexts. As with [[Writing_ImageJ2_plugins|ImageJ2 plugins]], script parameterization is based on the [[SciJava]] [https://github.com/scijava/scijava-common/blob/scijava-common-2.40.0/src/main/java/org/scijava/plugin/Parameter.java parameter annotation]—so experience with plugin writing directly translates to scripting, and vice versa.
  
All scripting languages have access to a universal <code>@parameter</code> notation for declaring inputs and outputs. This approach is preferred to using ImageJ 1.x <code>GenericDialog</code> because it is totally agnostic of the user interface, allowing such scripts to run in a variety of contexts. As with [[Writing_ImageJ2_plugins|ImageJ2 plugins]], script parameterization is based on the [[SciJava]] [https://github.com/scijava/scijava-common/blob/scijava-common-2.40.0/src/main/java/org/scijava/plugin/Parameter.java @Parameter annotation] - so experience with plugin writing directly translates to scripting, and vice versa.  
+
{{Notice | Script parameters are a feature of [[ImageJ2]]; they will not work in plain [[ImageJ1]]. The [[Fiji]] distribution of ImageJ is built on ImageJ2, so they also work in Fiji.}}
  
 
== Basic syntax ==
 
== Basic syntax ==
  
The rules for <code>@parameter</code> use are as follows:
+
The rules for <code>#@</code> parameter use are as follows:
  
 
<ol>
 
<ol>
<li>All parameter declarations must appear in comments. Each comment line contains a single parameter declaration and nothing else.</li>
+
<li>Parameter declarations begin with <code>#@</code>. Each such line contains a single parameter declaration or script directive and nothing else.</li>
<li>Any parameters after the first non-parameter line will not be recognized.</li>
+
<li><code>#@ Type variableName</code> will declare an input of the indicated type, assigned to the specified name. (The use of a space between <code>#@</code> and <code>Type</code> is encouraged, but not required.)</li>
<li><code>@type variableName</code> will declare an input of the indicated type, assigned to the specified name.</li>
+
<li><code>#@output Type outputName</code> will declare the variable of the specified name as an output parameter with the given type. The <code>Type</code> parameter is optional, as the output will be treated as <code>Object</code> be default. (For the <code>output</code> directive and other script directives, no space is allowed between <code>#@</code> and the directive.)</li>
<li><code>@OUTPUT type outputName</code> will declare the variable of the specified name as an output parameter with the given type.</li>
 
 
</ol>
 
</ol>
  
 +
{{Testimonial
 +
| quote = zomg UIs are so easy now<br>done by lunchtime
 +
| person = {{Person|kephale}},<br>Clojure developer
 +
| gravatar = 9e4ed4484fd425f3f178bfeed4777b31
 +
| source = https://gitter.im/fiji/fiji?at=5717afbc98c544f1396cef2f
 +
| float = right
 +
}}
 
For example, if we look at the [https://github.com/scijava/scripting-jython/blob/scripting-jython-0.2.0/src/main/resources/script_templates/Python/Greeting.py Greeting.py] [[Script_Templates|template]] supplied with Fiji:
 
For example, if we look at the [https://github.com/scijava/scripting-jython/blob/scripting-jython-0.2.0/src/main/resources/script_templates/Python/Greeting.py Greeting.py] [[Script_Templates|template]] supplied with Fiji:
 +
 +
{{GitHubEmbed
 +
| org = scijava
 +
| repo = scripting-jython
 +
| path = src/main/resources/script_templates/Intro/Greeting.py
 +
}}
 +
 +
We see that an input parameter <code>name</code> of type <code>String</code> is declared. <code>@Parameters</code> are handled automatically by the framework; if we run this script when the User Interface is available (e.g. from the script editor), the <code>name</code> parameter will automatically be harvested via a pop-up dialog:
 +
 +
 +
[[File:ScriptParams.png|450px]]
 +
 +
 +
We could also run this script [[Scripting Headless|headlessly]], thanks to the general nature of <code>@parameters</code>.
 +
 +
When the script is completed, any <code>#@output</code> variables are handled by the framework, based on their type. In this case we expect the <code>greeting</code> variable to be printed, since it is a <code>string</code>.
 +
 +
== Parameter types ==
 +
 +
A list of possible data types and the corresponding widgets is provided:
 +
 +
{| style="wikitable nicetable"
 +
| '''Data type'''
 +
| '''Widget type'''
 +
| '''Available styles'''
 +
|-
 +
| | <code>boolean</code> {{!}} <code>Boolean</code>
 +
| checkbox
 +
|
 +
|-
 +
| | <code>byte</code> {{!}} <code>short</code> {{!}} <code>int</code> {{!}} <code>long</code>
 +
| numeric field
 +
| | <code>slider</code> {{!}} <code>spinner</code> {{!}} <code>scroll bar</code>
 +
|-
 +
| | <code>Byte</code> {{!}} <code>Short</code> {{!}} <code>Integer</code> {{!}} <code>Long</code>
 +
| numeric field
 +
| | <code>slider</code> {{!}} <code>spinner</code> {{!}} <code>scroll bar</code>
 +
|-
 +
| | <code>Float</code>
 +
| numeric field
 +
| | <code>slider</code> {{!}} <code>spinner</code> {{!}} <code>scroll bar</code>
 +
|-
 +
| | <code>BigInteger</code> {{!}} <code>BigDecimal</code>
 +
| numeric field
 +
| | <code>slider</code> {{!}} <code>spinner</code> {{!}} <code>scroll bar</code>
 +
|-
 +
| | <code>char</code> {{!}} <code>Character</code> {{!}} <code>String</code>
 +
| text field
 +
| | <code>text field</code> {{!}} <code>text area</code> {{!}} <code>password</code>
 +
|-
 +
| | <code>Dataset</code> {{!}} <code>ImagePlus</code>
 +
| (>=2 images) triggers a dropdown list
 +
|
 +
|-
 +
| | <code>ColorRGB</code>
 +
| color chooser
 +
|
 +
|-
 +
| | <code>Date</code>
 +
| date chooser
 +
|
 +
|-
 +
| | <code>File</code>
 +
| file chooser
 +
| | <code>open</code> {{!}} <code>save</code> {{!}} <code>file</code> {{!}}  <code>directory</code> {{!}} <code>extensions:</code>
 +
|}
 +
 +
{{Warning | <code>float</code> is also an accepted field but the decimal part is not displayed in the form compared to <code>Float</code> (mind the capital F).<br>
 +
A related [https://github.com/scijava/scijava-common/issues/302 issue] occurs with <code>int</code> and <code>double</code> when a default value is set in the code and entered in the form, the value is not properly recalled at the next run. Use <code>Integer</code> and <code>Double</code> instead.}}
 +
{{Warning | A single <code>#@ImagePlus</code> or <code>#@Dataset</code>  field will not show up in the input form, instead the current image will automatically be processed. The idea is to stick to the IJ macro language. However if 2 <code>#@ImagePlus</code> (or respectively <code>#@Dataset</code>) are present then they will be rendered as drop-down buttons.}}
 +
 +
 +
By implementing {{Javadoc | project = SciJava | package = org/scijava/widget | class = InputWidget}} it is possible to extend this list.
 +
 +
== Parameter properties ==
 +
 +
If you look at the [https://github.com/scijava/scijava-common/blob/scijava-common-2.40.0/src/main/java/org/scijava/plugin/Parameter.java @Parameter annotation], you will notice it has many properties—for example, <code>name</code> and <code>description</code>.
 +
 +
Script parameters can set these properties, following these guidelines:
 +
 +
<ol>
 +
<li>All properties are defined in a '''single parenthetical expression''' immediately following the <code>#@type</code> declaration.</li>
 +
<li>Properties are set by a [https://docs.oracle.com/javase/tutorial/java/annotations/basics.html comma-separated list of '''key=value''' pairs]</li>
 +
</ol>
 +
 +
Properties are your way to customize how an <code>#@parameter</code> should be handled by the framework.
 +
 +
=== Widget labels ===
 +
 +
Widgets are the User Interface elements shown to users to collect input information. For example, instead of just displaying "Name" to the user, we can add a custom label to the field of our <code>Greeting.py</code> script as follows:
  
 
<source lang="python">
 
<source lang="python">
# @String name
+
#@ String (label="Please enter your name") name
# @OUTPUT String greeting
+
#@output String greeting
 +
 
 +
greeting = "Hello, " + name + "!"
 +
</source>
  
# A Jython script with parameters.
+
=== Widget mouseover ===
# It is the duty of the scripting framework to harvest
+
 
# the 'name' parameter from the user, and then display
+
We can add a <code>description</code> property to provide mouse-over text for our field:
# the 'greeting' output parameter, based on its type.
+
 
 +
<source lang="python">
 +
#@ String (label="Please enter your name", description="Your name") name
 +
#@output String greeting
  
 
greeting = "Hello, " + name + "!"
 
greeting = "Hello, " + name + "!"
 
</source>
 
</source>
  
We see that an input parameter <code>name</code> of type <code>String</code> is declared. This will automatically be harvested via a pop-up dialog when the script is run.
+
=== Default values ===
  
When the script is completed, we expect to have a <code>String</code> variable named <code>greeting</code> which will be displayed as appropriate, based on the variable type.
+
Default values are also supported as parameter properties:
  
Note that if we added an extra comment to the top of our script we would break the script, as the parameters would not be harvested or displayed due to violation of the second parameter rule:
+
<source lang="python">
 +
#@ Integer (label="An integer!",value=15) someInt
 +
</source>
 +
 
 +
=== Persistence ===
 +
 
 +
Per default, variable values are persisted between runs of a script. This means that parameter values from a previous run are used as starting value. Please note that a persisted value will overwrite a defined [[#Default value|default value]].
  
 
<source lang="python">
 
<source lang="python">
# A simple python script
+
#@ Integer (label="An integer!", value=15, persist=false) someInt
# @String name
+
</source>
# @OUTPUT String greeting
+
{{Warning | Currently, "two scripts which declare the same parameter name, even with different types, will stomp each other." See [https://github.com/scijava/scijava-common/issues/193].}}
  
# A Jython script with parameters.
 
# It is the duty of the scripting framework to harvest
 
# the 'name' parameter from the user, and then display
 
# the 'greeting' output parameter, based on its type.
 
  
greeting = "Hello, " + name + "!"
+
=== Visibility ===
 +
 
 +
This property set if the parameter should be displayed, editable and/or recorded.
 +
 
 +
- NORMAL: parameter is included in the history for purposes of data provenance, and included as a parameter when recording scripts.
 +
 
 +
- TRANSIENT: parameter is excluded from the history for the purposes of data provenance, but still included as a parameter when recording scripts.
 +
 
 +
- INVISIBLE: parameter is excluded from the history for the purposes of data provenance, and also excluded as a parameter when recording scripts. This option should only be used for parameters with no effect on the final
 +
output, such as a "verbose" flag.
 +
 
 +
- MESSAGE: parameter value is intended as a message only, not editable by the user nor included as an input or output parameter. The option <code>required</code> should be set to false.
 +
 
 +
[[File:ScriptParam_MESSAGEstring.JPG|thumb]]
 +
<source lang="python">
 +
#@ String (visibility=MESSAGE, value="This is a documentation line", required=false) msg
 +
#@ Integer (label="Some integer parameter") my_int
 +
</source>
 +
 
 +
You can [https://forum.image.sc/t/multiline-messages-in-dialog-widgets/183 use HTML] to format the message string, for example:
 +
[[File:ScijavaMultilineMessage.png|thumb]]
 +
<source lang="python">
 +
#@ String (visibility=MESSAGE, value="<html>Message line 1<br/>Message line 2<p>Let's make a list<ul><li>item a</li><li>item b</li></ul></html>") docmsg
 +
#@ Integer anIntParam
 +
</source>
 +
 
 +
{{Warning | Currently if a script containing a MESSAGE string is recorded with the macro recorder and the resulting recorded code executed, a window will show up containing only the MESSAGE string This is unexpected and will be corrected in the future.}}
 +
 
 +
=== Multiple Choice ===
 +
 
 +
Any parameter can be turned into a multiple-choice selector by adding a <code>choices={...}</code> property:
 +
 
 +
<source lang="python">
 +
#@ String (label="What mythical monster would you like to unleash?", choices={"Kraken","Cyclops","Medusa","Fluffy bunny"}) monsterChoice
 +
</source>
 +
 
 +
=== Files and Folders ===
 +
 
 +
By default, a <code>#@ File</code> parameter will create a chooser for a single file. Here is an example in python:
 +
 
 +
<source lang="python">
 +
#@ File (label="Select a file") myFile
 +
 
 +
print(myFile)
 +
</source>
 +
 
 +
You can request for multiple files or folders as well. However multiple files/folders input are not yet macro-recordable.
 +
 
 +
Example in ImageJ Macro Language:
 +
 
 +
<source lang="python">
 +
#@ File[] listOfPaths (label="select files or folders", style="both")
 +
 
 +
print("There are "+listOfPaths.length+" paths selected.");
 +
 
 +
for (i=0;i<listOfPaths.length;i++) {
 +
        myFile=listOfPaths[i];
 +
        if (File.exists(myFile)) {
 +
                print(myFile + " exists.");
 +
                if (File.isDirectory(myFile)) {
 +
                        print("Is a directory");
 +
                } else {
 +
                        print("Is a file");
 +
                }
 +
        }
 +
}
 +
 
 
</source>
 
</source>
  
Keep this in mind when adding documentation to your scripts.
+
The exact same code works for the [[Macros|ImageJ1 Macro language]], too.
 +
 
 +
If you want to select files or folders exclusively, use a <code>style</code> property:
  
== Parameter properties ==
+
<source lang="python">
 +
#@ File (label="Select a file", style="file") myFile
 +
#@ File (label="Select a directory", style="directory") myDir
  
If you look at the [https://github.com/scijava/scijava-common/blob/scijava-common-2.40.0/src/main/java/org/scijava/plugin/Parameter.java @Parameter annotation], you will notice it has many properties - for example, <code>name</code> and <code>description</code>. In Java, annotations can accept [https://docs.oracle.com/javase/tutorial/java/annotations/basics.html comma-separated key=value properties]. Script parameters preserve this property syntax, with the additional requirement that all parameters are enclosed in a '''single parenthetical expression'''.
+
print(myFile)
 +
print(myDir)
 +
</source>
  
For example, instead of just displaying "Name", we can add a custom label and description to the name field of our Greeting.py script as follows:
+
You can set restrictions on accepted file types based on file extension (using a <code>style</code> property):
  
 
<source lang="python">
 
<source lang="python">
# A simple python script
+
#@ File (label="Select an image file", style="extensions:png/jpg") myImageFile
# @String name (label="Please enter your name",description="Name field")
 
# @OUTPUT String greeting
 
  
# A Jython script with parameters.
+
print(myImageFile)
# It is the duty of the scripting framework to harvest
+
</source>
# the 'name' parameter from the user, and then display
 
# the 'greeting' output parameter, based on its type.
 
  
greeting = "Hello, " + name + "!"
+
=== Styles ===
 +
 
 +
You can influence the visual style of some of the input widgets. See previous paragraph for an example for how to switch from file to folder selection. You can also switch
 +
 
 +
<source lang="python">
 +
#@ String (choices={"Option 1", "Option 2"}, style="listBox") myChoice123
 +
#@ String (choices={"Option A", "Option B"}, style="radioButtonHorizontal") myChoiceABC
 +
 
 +
print(myChoice123)
 +
print(myChoiceABC)
 
</source>
 
</source>
  
It is up to the current UI framework how to deal with these properties. By default, the <code>label</code> will change the input field label, while <code>description</code> will change the mouse-over text.
+
[[File:Input-styles.png]]
  
 
[[Category:Scripting]]
 
[[Category:Scripting]]

Latest revision as of 07:31, 7 July 2019

Learn
Topics
Introduction
Getting Started
User Guides
Tutorials
Tips and Tricks
Presentations
Plugins
Techniques
All Techniques
Colocalization
Deconvolution
Registration
Segmentation
Stitching
Tracking
Visualization
Scripting
Overview
User input
Basics of script writing
Batch processing
Script Editor
Auto Imports
Templates
Running headlessly
Comparisons
Toolbox
Multithreading in Clojure
Multithreading in JavaScript
Chess in Jython
Languages
BeanShell
Groovy
ImageJ Macro
JavaScript
Lisp (Clojure)
MATLAB
Python (Jython)
R (Renjin)
Ruby (JRuby)
Scala

All scripting languages have access to a universal #@parameter notation for declaring inputs and outputs. This approach is preferred over the ImageJ 1.x GenericDialog because it is totally agnostic of the user interface, allowing such scripts to run in a variety of contexts. As with ImageJ2 plugins, script parameterization is based on the SciJava parameter annotation—so experience with plugin writing directly translates to scripting, and vice versa.



Basic syntax

The rules for #@ parameter use are as follows:

  1. Parameter declarations begin with #@. Each such line contains a single parameter declaration or script directive and nothing else.
  2. #@ Type variableName will declare an input of the indicated type, assigned to the specified name. (The use of a space between #@ and Type is encouraged, but not required.)
  3. #@output Type outputName will declare the variable of the specified name as an output parameter with the given type. The Type parameter is optional, as the output will be treated as Object be default. (For the output directive and other script directives, no space is allowed between #@ and the directive.)
“zomg UIs are so easy now
done by lunchtime”
Kyle Harrington,
Clojure developer
[ source ]

For example, if we look at the Greeting.py template supplied with Fiji:

src/main/resources/script_templates/Intro/Greeting.py

#@ String (label="Please enter your name", description="Name field") name
#@output String greeting

# A Jython script with parameters.
# It is the duty of the scripting framework to harvest
# the 'name' parameter from the user, and then display
# the 'greeting' output parameter, based on its type.

greeting = "Hello, " + name + "!"

We see that an input parameter name of type String is declared. @Parameters are handled automatically by the framework; if we run this script when the User Interface is available (e.g. from the script editor), the name parameter will automatically be harvested via a pop-up dialog:


ScriptParams.png


We could also run this script headlessly, thanks to the general nature of @parameters.

When the script is completed, any #@output variables are handled by the framework, based on their type. In this case we expect the greeting variable to be printed, since it is a string.

Parameter types

A list of possible data types and the corresponding widgets is provided:

Data type Widget type Available styles
boolean | Boolean checkbox
byte | short | int | long numeric field slider | spinner | scroll bar
Byte | Short | Integer | Long numeric field slider | spinner | scroll bar
Float numeric field slider | spinner | scroll bar
BigInteger | BigDecimal numeric field slider | spinner | scroll bar
char | Character | String text field text field | text area | password
Dataset | ImagePlus (>=2 images) triggers a dropdown list
ColorRGB color chooser
Date date chooser
File file chooser open | save | file | directory | extensions:



By implementing InputWidget it is possible to extend this list.

Parameter properties

If you look at the @Parameter annotation, you will notice it has many properties—for example, name and description.

Script parameters can set these properties, following these guidelines:

  1. All properties are defined in a single parenthetical expression immediately following the #@type declaration.
  2. Properties are set by a comma-separated list of key=value pairs

Properties are your way to customize how an #@parameter should be handled by the framework.

Widget labels

Widgets are the User Interface elements shown to users to collect input information. For example, instead of just displaying "Name" to the user, we can add a custom label to the field of our Greeting.py script as follows:

#@ String (label="Please enter your name") name
#@output String greeting

greeting = "Hello, " + name + "!"

Widget mouseover

We can add a description property to provide mouse-over text for our field:

#@ String (label="Please enter your name", description="Your name") name
#@output String greeting

greeting = "Hello, " + name + "!"

Default values

Default values are also supported as parameter properties:

#@ Integer (label="An integer!",value=15) someInt

Persistence

Per default, variable values are persisted between runs of a script. This means that parameter values from a previous run are used as starting value. Please note that a persisted value will overwrite a defined default value.

#@ Integer (label="An integer!", value=15, persist=false) someInt



Visibility

This property set if the parameter should be displayed, editable and/or recorded.

- NORMAL: parameter is included in the history for purposes of data provenance, and included as a parameter when recording scripts.

- TRANSIENT: parameter is excluded from the history for the purposes of data provenance, but still included as a parameter when recording scripts.

- INVISIBLE: parameter is excluded from the history for the purposes of data provenance, and also excluded as a parameter when recording scripts. This option should only be used for parameters with no effect on the final output, such as a "verbose" flag.

- MESSAGE: parameter value is intended as a message only, not editable by the user nor included as an input or output parameter. The option required should be set to false.

ScriptParam MESSAGEstring.JPG
#@ String (visibility=MESSAGE, value="This is a documentation line", required=false) msg
#@ Integer (label="Some integer parameter") my_int

You can use HTML to format the message string, for example:

ScijavaMultilineMessage.png
#@ String (visibility=MESSAGE, value="<html>Message line 1<br/>Message line 2<p>Let's make a list<ul><li>item a</li><li>item b</li></ul></html>") docmsg
#@ Integer anIntParam



Multiple Choice

Any parameter can be turned into a multiple-choice selector by adding a choices={...} property:

#@ String (label="What mythical monster would you like to unleash?", choices={"Kraken","Cyclops","Medusa","Fluffy bunny"}) monsterChoice

Files and Folders

By default, a #@ File parameter will create a chooser for a single file. Here is an example in python:

#@ File (label="Select a file") myFile

print(myFile)

You can request for multiple files or folders as well. However multiple files/folders input are not yet macro-recordable.

Example in ImageJ Macro Language:

#@ File[] listOfPaths (label="select files or folders", style="both")

print("There are "+listOfPaths.length+" paths selected.");

for (i=0;i<listOfPaths.length;i++) {
        myFile=listOfPaths[i];
        if (File.exists(myFile)) {
                print(myFile + " exists.");
                if (File.isDirectory(myFile)) {
                        print("Is a directory");
                } else {
                        print("Is a file");
                }
        }
}

The exact same code works for the ImageJ1 Macro language, too.

If you want to select files or folders exclusively, use a style property:

#@ File (label="Select a file", style="file") myFile
#@ File (label="Select a directory", style="directory") myDir

print(myFile)
print(myDir)

You can set restrictions on accepted file types based on file extension (using a style property):

#@ File (label="Select an image file", style="extensions:png/jpg") myImageFile

print(myImageFile)

Styles

You can influence the visual style of some of the input widgets. See previous paragraph for an example for how to switch from file to folder selection. You can also switch

#@ String (choices={"Option 1", "Option 2"}, style="listBox") myChoice123
#@ String (choices={"Option A", "Option B"}, style="radioButtonHorizontal") myChoiceABC

print(myChoice123)
print(myChoiceABC)

Input-styles.png