Script commands

The script processor is case-insensitive; you can enter commands as ALLCAPS or alllowercase, but for readability it is helpful to use MixedCase as in the table. Completing a command by typing tab or ` will convert it to MixedCase.  Parameters to the individual commands are abbreviated as follows:

When there are multiple optional entries, there needs to be an entry for every one up to the last one that you want to enter.  If there are several entries within one set of brackets, they must all be entered if any of them are desired.  For example, 'RealignToNavItem #R [#C] [#S #N #Z]' must have at least one entry, and can have 2 or 5, such as 'RealignToNavItem 0', ' RealignToNavItem 0 1', or 'RealignToNavItem 0 0 0.3 2 0'.

Frequently used non-numeric parameters used in SerialEM scripting are:

Commands starting with 'Report...' will assign output to one or more variable names listed after the command (omitting the '$'), except where the table notes otherwise.  For other commands, the table explicitly states when they accept variable names.  Arithmetic expressions can be used after virtually all commands starting with 'Set' and with the commands listed in Commands Allowing Arithmetic Expressions for Arguments.

Some commands will call functions that may not be supported by the FEI scripting adapter or JEOL scripting interface on your scope.  In either case, the program will crash if it calls a function that does not exist in the scripting interface.  (Neither of these interfaces has a version number that could be used to prevent this.)  For a JEOL, the version of TemExt.dll that provides the interface may be new enough to have the function, but the call will fail with an error if it is not supported by the microscope software/hardware.

All commands not available from Python are marked as 'Not from Python'.


Script Control Commands
     Flow Control Commands
     Variable and Array Commands
     Other Script Operation Control Commands
     Functions Available Only from Python
Camera Commands
     Camera Control
     Acquisition Commands
     Parameter Commands
     Continuous Mode Control
     Frame Saving and Alignment
     Hardware Specific Camera Commands
     Other Camera Commands
Buffer and File Commands
     Buffer and Image Commands
     Directory and Miscellaneous Commands
     Image File Commands
     Text File Commands
     Autodoc/.mdoc File Commands
Microscope and Filter Commands
     Stage-Related Commands
     Focus-Related Commands
     Magnification-Related Commands
     Beam-Related Commands
     Image Shift-Related Commands
     Miscellaneous Scope Commands
     Energy Filter Commands
     Autoloader, Refrigerant, and Vacuum Commands
     Piezo Drive Commands
Higher Level Operations and Tasks
     Autoalign-Related Commands
     Autofocus/Autotuning-Related Commands
     Low Dose Commands
     Task-Related Commands
Navigator
     Navigator Window and List Commands
     Item and Group Commands
     Item Generating Commands
     Alignment and Shift Commands
     Acquisition Control Commands
Miscellaneous Commands
     Time-Related Commands
     Scale Matrix Commands
     Other Commands
Commands Allowing Arithmetic Expressions for Arguments

Script Control Commands

Flow Control Commands
Repeat Place at end of script to repeat it. 
Not from Python.
Loop # [var] Loops the given # of times until EndLoop; optionally set var with index.  A loop count less than or equal to 0 is allowed and will cause the loop to be skipped.  If a script relying on this is liable to run on earlier versions, it should include the line 'Require zeroloop'. 
Not from Python.
DoLoop var #S #E [#I] Loops from #S to #E, inclusive, assigning the loop index to var.  The optional #I can be entered to set the increment, which is 1 by default.  If the starting index is already past the ending one, the loop will be skipped.  Integer values should be entered; non-integer values will be truncated to integers. 
Not from Python.
EndLoop Marks the end of a loop. 
Not from Python.
DoScript #
DoMacro #
Switches to given script #./ 
Not from Python.
CallScript # [arg1 arg2 ...]
CallMacro # [arg1 arg2 ...]
Calls other script by # and returns.  The # can be -1 to use the script number found by a previous 'FindScriptByName'.  A regular SerialEM script may call a Python script provided that the top-level script was not Python.  When doing so, optional arguments can be added and will be placed into a list of strings named 'SEMargStrings' in the Python script.
Callable from Python with the number of a regular SerialEM script, but with no optional arguments.
FindScriptByName text Finds the number of the script whose name is text and stores its number internally so that it can be used in a following 'CallScript -1'.  Names are case-sensitive and must match exactly, including spaces.
Not from Python.  Command added in 3.8.0, 5/4/21
Call text Calls other script by name. Names are case-sensitive and must match exactly, including spaces.  A regular SerialEM script may call a Python script provided that the top-level script was not Python.
Callable from Python with the name of a regular SerialEM script.
CallStringArray var [#E] Places the array of strings in var into an 'extra' script and runs it.  Extra scripts are temporary and available only until a script ends.  Up to 5 extra scripts can be defined; they are added sequentially to positions numbered 1 to 5.  The optional #E can be entered to place a script into a previously used position or the next unused position.  If the script depends on other temporary scripts, they can be loaded first with 'StringArrayToScript'. 
Callable from Python if the string array contains a regular SerialEM script and the Python script was not called from a regular script.
Function name [#N] [#S] [args] Defines a function with the given name (without embedded spaces).  The optional #N indicates the number of numeric arguments and #S is non-zero to indicate that a string argument occurs after the numeric ones.  Optional variable names can be provided for the arguments.  Functions must be placed at the ends of scripts. 
Not from Python.
EndFunction Required ending to a function definition. 
Not from Python.
CallFunction name [args] Calls the function with the given name and supplies arguments for the function to receive.  If the name could occur in more than one script, it must be qualified with a script number or name, i.e. '5::GoodFunc' or 'Func Script::GoodFunc'.  The variable functionName is defined with the name. 
Callable from Python with the name of a regular script function as its first, string argument.  The order of arguments is changed from what is used in a regular script: the first optional argument is the string argument that the function may allow, and then up to 17 numeric arguments can be passed.  If a function takes no string argument, you can just use an empty string.  For example:
        retVals = CallFunction('My Functions::Cycle Defocus', '', 1., 10)
PythonScript [arg1 arg2 ...] Allows a Python script to be embedded in a regular script and run at that point.   Optional arguments can be added and will be placed into a list of strings named 'SEMargStrings' in the Python script.  This is equivalent to having the Python text by itself in a different script and calling it with 'CallScript'.
Not from Python.  Command added in 3.8.0, 5/4/21
EndPythonScript This line must occur at the end of an embedded Python script started with 'PythonScript'. 
Not from Python.
If expression Starts a block that is executed conditionally on the value of 'expression'. 
Not from Python.
Endif Ends a block started with 'If'. 
Not from Python.
Elseif expression Inside of an If/Endif block, starts a block that is executed conditionally on the value of 'expression' if the expressions in the starting 'If' statement and any preceding 'Elseif' statements were not true. 
Not from Python.
Else Inside of an If/Endif block, starts a block that is executed if the expression after the 'If' and any preceding 'Elseif' commands is false. 
Not from Python.
Break Stops execution of the innermost Loop containing this statement.  Not from Python.
KeyBreak [key] If the user presses 'B', or the key given by the optional key entry, the script breaks out of the innermost Loop containing this statement.  key should be a letter or number; the test for the key is case-insensitive.
Callable from Python.
Continue Skips the rest of the current iteration of the innermost Loop containing this statement. 
Not from Python.
SkipTo label Skips forward to the line starting with the given label, where the label has a colon (:) at the end of it and is the only item on the line.  The colon is not included in the label in the 'SkipTo' statement. 
Not from Python.
Try Starts a block within which an error will result in the script jumping to the line after the following 'Catch' statement instead of a message box appearing.  See Error Handling and TRY - CATCH - ENDTRY Blocks.  
Not from Python.
Catch Starts the block of commands that are run only when an error occurs or 'Throw' statement is used inside the 'Try' portion of the block. 
Not from Python.
EndTry Ends the block of commands run upon error. 
Not from Python.
Throw [text] Jumps to the 'Catch' section of the 'Try' block containing this statement, adding the optional text to the message given in the log about the jump.  
Not from Python.
OnStopCallFunc name Calls the function with the given name when the script is stopped by the user pressing STOP or by an error in a script operation or in an external routine.  The function must not take any arguments, and it should not call other functions or scripts (such calls will be skipped).  The function will be called only once, even if there is an error or STOP while it is running.  The script will be aborted (not left in a resumable state) when the end of the function is reached.  
Not from Python.
Return [r1] [r2] [r3] [r4] r[5] [r6] Without executing to the end of the current script, returns to calling script or ends execution if this is the top-level script.  As of SerialEM 3.9, 4.28.21, up to 6 return values can be placed in reportedValue1 to reportValue6 with optional arguments r1 to r6  If any such arguments are included, existing reported values will be cleared; otherwise they will be preserved.  If there is any chance that a script relying on this feature will be run on an earlier version, include the line 'require 203' in the script.
Callable from Python with the same functionality, except that existing reported values are always cleared.  The returned arguments must all be strings.
Exit [text] Ends execution unconditionally and prints the optional text to the log. 
Callable from Python: From a Python script, there are two optional arguments, an integer then a string; i.e., it is called as Exit([exc], [text]).  In a script run from SerialEM, exc should be 0 when exiting from normal code or positive when exiting from a Python exception; the default is 0.  In a script run from an externally started Python, the default is 1 to keep the script from raising a SEMexited exception.  You can call with a 0 if you want to catch this exception.
Variable and Array Commands
CompareStrings var text Compares the strings in the given variable var (without a $) and in the text on the rest of the line.  Sets reportedValue1 to 0 if the strings are equal, a negative number if the variable is alphabetically before the text, and a positive number if it is after.
CompareNoCase var text Like CompareStrings except that upper/lower case differences are ignored in the comparison.
StripEndingDigits var1 var2 Removes any digits from the end of the variable var1 and assigns it to the variable var2 (both named without a $).  The digits are converted to a number and assigned to reportedValue1.
ListVars Lists all variables and their values in the log window, including reported values, persistent variables, and loop indices.
ListPersistentVars Lists all variables defined as persistent and their values in the log window.
ClearPersistentVars Removes all persistent variables defined with ':='
MakeVarPersistent var [#] Changes a regular variable to persistent, or if a 0 is entered for #, makes a persistent variable non-persistent.
IsVariableDefined var Reports whether a variable is defined, placing a 1 in reportedValue1 if it is and a 0 if it is not.  Follow with the variable name without a $.  Value can be assigned to a variable at end of command.
LocalVar var [var] ... Creates the listed variables as variables local to the current script or function.  They will not be accessible outside this script or function and will become undefined when returning from the script or function.  Not from Python.
LocalLoopIndexes Makes loop indexes local; this means that a called function or script cannot access the index value in the caller and is free to reuse the variable name as a loop index or other variable.  If this feature is used, this command should be near the start of any script that may be started independently.  Once the feature is invoked, it cannot be turned off. 
Not from Python.
NewArray var #T #E Creates a new variable with the name var, making it persistent or local if #T is 1 or -1, respectively, or a regular variable if #T is 0.  The array is initialized with #E zeros. 
Not from Python.
New2DArray var [#T] [#R #E] Creates a 2D array variable with the name var, making it persistent or local if #T is 1 or -1, respectively, or a regular variable if #T is 0.  If the optional #R and #E are given, the array is initialized with #R rows of #E zeros each, where both must be positive. 
Not from Python.
AppendToArray var item Appends one item or an array or items either to a 1D variable, which may already be an array or not, or to a row of a 2D array, specified with var[row], or as a new row of a 2D array, specified without a subscript.  As with setting a variable, if there are multiple items on the line not specified as an array, only the first item will be added, whereas if there the multiple items are enclosed in '{ }', all items will be added to the array. 
Not from Python.
TruncateArray var # Truncates the given array variable var to # elements; # must be positive. For a 1D array,  the values is truncated to # elements; for a row of a 2D array,  specified by var[row], the row of values is truncated; for a 2D array given without a subscript, the number of rows is truncated to #
Not from Python.
ArrayStatistics var For the set of values in the given array variable, computes and reports the total number of values, the minimum, the maximum, the mean, the standard deviation and the median.  For a 2D array, the statistics can be of the whole array, or of one row if the variable is given with a row subscript. Values can be assigned to variables at end of command.
LinearFitToVars var1 var2 [var3] Computes a linear least-squares fit between values in 2 or 3 array variables.  With two variables, fits to the equation  v2 = slope * v1 + intercept and reports the number of values, slope, intercept, and correlation coefficient 'ro'.  With three variables, fits to the equation v3 = a1 * v1 + a2 * v2 + c and reports the number of values, a1, a2, and c.  All variables must have the same number of values.
StringArrayToScript var [#E] Loads the array of strings in var into an 'extra' or regular script.  Use this command to make functions in an extra script available, such as to another extra script.  Extra scripts are added sequentially to positions numbered 1 to 5.  A positive value #E can be entered to place a script into a previously used position or the next unused position.  A negative value (-1 to -20) can be used to replace the script in one of the regular script positions that are editable and saved to settings. 
Not from Python.
Other Script Operation Control Commands
ScriptName text
MacroName text
Names the script to the given text, which can include spaces.  The variable scriptName is defined with either this name, or "Script #n" if no name has been defined, when the script is started running.  Not called as a function from Python, but can be present as a comment.
LongName text A longer name to appear in the Run submenu of the Script menu; if this name is not defined, the regular name defined by ScriptName or MacroName appears there.  The variable longName is defined with this name when a script is started running. Not called as a function from Python, but can be present as a comment.
ReadOnlyUnlessAdmin Prevents changing the script in the script editor from this command to the end of the script, unless Administrator mode is turned on in the Calibration menu.  Place the command at the beginning of script to make the whole script read-only. Not called as a function from Python, but can be present as a comment.
Delay # [units] Waits for given amount of time. The optional units can be 'msec', 'sec', or 'min'. If no units are given, a # <= 60 is taken to be seconds, and a # > 60 is taken to be milliseconds
WaitForMidnight [#B] [#A] [#H #M] If the current time is between #B (default 5) minutes before and #A (default 5) minutes after midnight, or an alternative time specified by the optional entries #H (the hour from 0 to 23) and #M (the minute from 0 to 59), the script will wait until #A minutes after midnight or the given time.
Echo [text] Prints the text to the log window, or a blank line if there is no text.  Variables are substituted but arithmetic expressions are not evaluated.  Multiple spaces between words are preserved, as well as extra spaces before the text.
EchoEval [text] Prints the text to the log window after substituting variables and evaluating arithmetic expressions.  Multiple spaces between words will be lost.  Not from Python.
EchoNoLineEnd text Prints the text to the log window after substituting variables and evaluating arithmetic expressions, without adding a line ending, so more text can be written to the line.  Multiple spaces between words will be lost.
EchoReplaceLine [text] Removes existing text from the log back to the last line ending, if there is any such text, then prints the optional text to the log after substituting variables and evaluating arithmetic expressions, without adding a line ending.  This command can be used repeatedly to update the text on a line, such as with a status output.
EchoNoVarSub [text] Prints the text verbatim to the log window including initial extra spaces, or a blank line if there is no text, without substituting variables. 
Not from Python.  Command added in 4.9, 1/8/21.
Pause [text] Opens message box with optional text plus question of whether to proceed with script.  Is not suppressed by NoMessageBoxOnError.
YesNoBox text Opens a Yes-No message box with the given text, which should be a question that can be answered with yes or no. Sets reportedValue1 to 1 or 0 for a yes or no answer.  If NoMessageBoxOnError is set, no box appears, the text is printed to the log, and reportedValue1 is 0.
OKBox text Opens a message box with the given text and just an OK button.  The box is not suppressed by NoMessageBoxOnError.
EnterOneNumber text Opens a dialog box for the user to enter one floating point number, with the given text as the prompt.  Sets reportedValue1 to the entered value.
EnterDefaultedNumber #V #D text Opens a dialog box for the user to enter one floating point or integer value.  Follow with the default value #V to show in the box, the number of decimal places #D to show for a float entry or -1 for an integer entry, and the prompt text on the rest of the line.  Sets reportedValue1 to the entered value.
EnterString var text Opens a dialog box for the user to enter a string of text, with the given text as the prompt, and assigns it to the given variable var (without a $).
ThreeChoiceBox header choice1 choice2 [choice3] buttons Opens a dialog box to allow the user to choose between two or three options.  Follow with 4 or 5 variable names.  Put initial text to appear at the top of the box in variable header, descriptions of the two or three choices in variables choice1, choice2, and the optional choice3, and button labels as an array of strings in buttons.  These names are arbitrary.  Use an array of strings to have multiple lines of text for the header or descriptions.  Use a line with just 'header @=' to make a variable for omitting the header text.  The number of the choice (1, 2, or 3) is placed in reportedValue1.  See Three Choice Box in Advanced Examples.  Command added in 3.9, 3/5/21.
ParseQuotedStrings [#] Allows strings that may have spaces to be enclosed in single quotes (e.g., 'text string') and treated as a single entity in cases where it would be broken up at the spaces.  Follow with a 0 to turn off such parsing.  The best use of this feature would be for making an array of strings in a single statement that encloses the entries with braces.  It also allows a string to be assigned to a variable without using '@='.  
Not from Python.
FlashDisplay [#T] [#D] [rgb] Flashes between a uniformly colored screen and normal image display several times.  The first optional entry, #T, sets the number of times to flash (default 4) and the second optional entry, #D, sets the duration of each state in seconds (default 0.3).  Total duration may not exceed 6 seconds. The third optional entry, rgb, sets the color of the flashing screen in hexadecimal (RRGGBB) notation, e.g. FF5500 is orange.
Verbose # Turns echoing of each script line on or off for # 1 or 0
SuppressReports [#] Disables printing of reports and other script output, and just assigns the values to report variables.  Including 0 for the optional # reenables printing.
SuspendNavRedraw [#] Disables updating of the table list box in the Navigator window and redrawing of the image window when Navigator items are changed, to speed up scripting changes of multiple items.  Updating is reenabled and done when this command is given again with 0 for the optional # or when the script ends.  Command added in 3.9, 9/23/20.
DeferLogUpdates [#] Makes output to the log window be held in a buffer and added to the window periodically, to speed up repetitive printing to log.  The buffering ends when this command is given again with 0 for the optional # or when the script ends.  Command added in 3.9, 9/23/20.
ErrorsToLog [#] Makes most script error messages be duplicated in the log window.  Follow with a 0 to turn off the feature again.
NoMessageBoxOnError [#] Outputs an error message to the log instead of opening a message box.  The script stops, but if it is being run from Navigator Acquire at Items, the Navigator is able to go to the next item.  Follow with 0 to turn the feature off again.
GetFileInWatchedDir pattern Looks for a file matching the given pattern, where pattern can be a directory followed by a filename including '*' to match multiple names.  If just a directory is entered, the program appends a '*'.  If a file is found, it returns 1 in reportedValue1 and the filename in reportedValue2; otherwise it returns 0 and 'none'.  A file is ignored if a file with the same name plus '.lock' is found as well.  Thus, if there is a risk that a file might not all be present when SerialEM first sees it, the program creating the file should create the '.lock' file (which can be empty), then create and finish writing to the file to be found, then remove the '.lock' file.  The file will need to be removed to avoid finding it again on the next call.
IsFFTWindowOpen Reports whether the FFT window is open; the value can be assigned to a variable after the command.  Command added in 3.9, 2/6/21.
RunScriptInWatchedDir pattern Looks for a file matching the given pattern, like 'GetFileInWatchedDir', and reads the file, places its contents in an extra script position, removes the file, and runs that script.  It sets reportedValue1 and 2 just as for 'GetFileInWatchedDir'.  As for 'GetFileInWatchedDir', a '.lock' file can be used to avoid the risk that the file is not complete when SerialEM sees it.
Require feature [feature] ...
Require script_version_number
This command tests whether scripting features used in the script are available in this version of SerialEM.  Earlier versions will not generate an error when some newer features are used, so including this command is the only way to test whether the script will run correctly.  Initially these features were specified by name, but this was silly and the command now takes a scripting version number, which is unrelated to the program version number.  You can enter either the latest feature name or the version number that your script needs. The available features, in order of addition, were: 1) 'variable1', which includes two capabilities: assigning reported values directly to variables listed after a command, and assigning function arguments directly to variables listed on the 'Function' line.  2) 'arrays', which is the ability to define a variable with an indexable array of values.  3) 'keepcase', which means that case will be preserved when assigning text to a variable.  4) 'zeroloop', which means that a non-positive loop count is allowed.  5) 'evalargs', which means that arithmetic expressions will be evaluated in arguments to some commands.  6) Scripting version 201, which means commands can be continued onto multiple lines with backslash.  7) Scripting version 202, which means that limited arithmetic can be done in array subscripts (without spaces) and that arithmetic clauses can start with a minus sign. 
Not from Python.  8) Scripting version 203, in which the 'Return' command can return values from a function or script.
IsVersionAtLeast #V [#D] Tests whether the program version is at least the version specified with #V, and also if its build date is at least that specified by the optional #D.  The version should be 5 digits: the initial version number (currently 3) times 10000, plus the major release version times 100, plus the minor version (.e.g, 3.6.3 is 30603).  The build date should have the format yyyymmdd, e.g., 'Sep 12 2017'; is specified as 20170912.  Sets reportedValue1 to 1 if the version is high enough, 0 if not.
SkipIfVersionLessThan #V [#D] Skips the command on the next line if the program version is earlier than the version specified with #V, or if the build date is earlier than the optional entry #D.  The format of these entries is as just described.  The next line will be skipped unconditionally when checking the script before execution.  Thus, loop and conditional control statements cannot be on that line.  This command is intended to provide a way to place a newer command into a script and allow it to be runnable on older versions.
Test expression Evaluates a conditional expression (just as would be used for an IF statement) or a single number or variable value and stores whether the test passed (i.e., if the expression is true or if the number is non-zero) internally, as well as storing a 1 for success or 0 for failure in reportedValue1 and a variable TestResult.  
Not from Python.
PauseIfFailed [text] If the last 'Test' command failed, this command opens a message box with the optional text plus the question of whether to proceed with the script, even if NoMessageBoxOnError is set. 
Not from Python.
AbortIfFailed [text] If the last 'Test' command failed, this command opens a message box with the optional text (unless NoMessageBoxOnError; is set) and aborts the script.  Not from Python.
Functions Available Only from Python
SetVariable(var, value) Sets variable var within SerialEM scripting with value, which must be a string.  A one-dimensional array variable can be passed by separating each value with newlines ('\n', written as '|\n' within SerialEM).  The Python wrapper function 'listToSEMarray' can be used to convert a list with numeric and/or string values to a newline-separated string.  Variable names are stored as upper case within SerialEM, so all variable specifications are case-insensitive.
SetPersistentVar(var, value) Like SetVariable, but sets it as a persistent variable.
SetFloatVariable(var, value [, #P]) Sets variable var within SerialEM scripting with value, which must be numeric, and sets it as a persistent variable if the optional #P is non-zero.
GetVariable(var) Returns the value of a variable var as string or floating point value, depending on whether the variable was designated as numeric when it was stored  The Python wrapper function 'SEMarrayToFloats' can be used to create a list of float values from the return value if the variable contains either a single numeric value or an array of numeric values
bufferImage(buf) Constructs an instance of the 'bufferImage' type that has an image pointer and other essential information about the image in buffer buf, which is a non-numeric string and can specify an FFT buffer.  This type instance can provide the image to other classes via the Python 'Buffer Protocol'.  The image may have padding (i.e., not be strictly contiguous) and a request that does not permit striding between lines could generate an exception.  Not available below Python 3.4.
PutImageInBuffer(image, buf [,#X, #Y, base, #B, #C]) Places an image that provides the 'Buffer Protocol' for array access into buffer buf.  If buf is 'A' then buffers are rolled as when making a new processed image. Optional arguments are: #X and #Y with the X and Y size of the image (this seems to be required for an image from numpy); base with the letter of a buffer to use as the basis for various buffer parameters (the default is the buffer where the image is being placed); #B with a value of additional binning (default 1); #C with a 'capture flag' to define how the image is labeled in the buffer status window (the default is -1 for 'Processed').
ConnectToSEM([#P, IP]) When running Python externally to control SerialEM, this function can be used optionally as the first call to SerialEM to define an alternative port in #P (the default is 48888) or an alternative IP address in IP (the default is '127.0.0.1'). If you use a different port, it must be specified in a property entry 'SocketServerPort 8'.

Camera Commands

Camera Control
SelectCamera # Makes the given camera be the active camera, where the # is the position of the camera in the ActiveCameraList property or Camera setup dialog, numbered from 1.  Will switch in and out of EFTEM mode or STEM mode if appropriate.
RetractCamera Retracts all retractable cameras
CameraProperties [#C] [#M] Reports unbinned size in X and Y, RotationAndFlip property, size of detector pixel in microns, and unbinned pixel size of the current camera, or of the active camera whose number is given by the optional #C, numbered from 1. The unbinned pixel size is for the current magnification, or for the magnification index given by the optional #M.
SetDivideBy2 # Turns division by 2 for the current camera on or off if # is 1 or 0, respectively.
ArePostActionsEnabled Reports whether post-exposure actions are allowed for the current camera for all shots, and for Record shots specifically, and sets reportedValue1 and reportedValue2 to 1 if so, 0 if not.  For Falcon and DE cameras, post-actions are allowed only when frames are being aligned in SerialEM.  The values can be assigned to a variable after the command.
ReportCountScaling Reports two values of current camera: either the scaling being applied to counting/super-resolution mode images returned from a K2 camera, or the 'CountsPerElectron' property; and whether division by 2 is on.
Acquisition Commands
V or View Acquires image with 'View' parameters
F or Focus Acquires image with 'Focus' parameters
T or Trial Acquires image with 'Trial' parameters
R or Record Acquire image with 'Record' parameters
L or Preview Acquires image with 'Preview' parameters
M or Montage Acquires montage
Search Acquires image with 'Search' parameters, or with 'View' parameters if the option is set to use those for Search.
PreCookMontage #D [#P] [#C] [#S] If montaging is enabled with stage movement, lowers the screen to expose the specimen, then moves the stage to each piece position and waits there for the number of seconds indicated by #D, if the number is positive.  If #D is negative or #P is entered, it skips pieces within each column, with an interval given by the #P or the negative of #D: 2 will stop at every second piece, 3 at every third, etc.  For convenience, 1 is equivalent to a large interval and will make it stop only at the bottom and top of each column.  Set #C non-zero to skip columns partially or 0 not to: in every other column, the stage will be moved only to the first and last piece and to any piece that does not have an adjacent piece in the columns on both sides.  This entry will make no difference if you use 1 or a very large number for the skip interval.  Set #S with a stage movement speed factor or 0 for normal speed.  If setting a speed factor crashes SerialEM or FEI-SEMserver, see notes under TiltDuringRecord.
Parameter Commands
The following 'Set...' commands change values in one of the camera parameter sets.  The set entry can be specified as either V, F, T, R, P, S, M or 0, 1, 2, 3, 4, 5, 6 for View, Focus, Trial, Record, Preview, Search, and Mont-Map, respectively.  Parameters will be restored whenever the script ends or stops or when a different camera is selected.  However, if the script is suspended, any changed parameters will be set again when the script resumes.
SetExposure set #E [#D] Sets exposure and, optionally, drift settling for set  to the given values #E and #D.   If #D is omitted, the existing drift settling will be unchanged. 
SetBinning set #B Sets binning for set to #B.
SetCameraArea set #L #R #T #B
SetCameraArea set area
Sets the acquisition area for set.  Follow the set with either 4 numbers #L #R #T #B for the unbinned left, right, top, and bottom coordinates (the same kind of numbers as in the camera setup dialog) or with area set to 'F', 'H', 'Q', 'WH' or 'WQ' for full, half, quarter, wide half, or wide quarter.  Values will be adjusted for a legal area. 
SetCenteredSize set #B #X #Y Sets set for acquisition from a centered area.  Follow set with 3 numbers: the binning #B, the binned size in X, and the binned size in Y. 
SetContinuous set # Sets the acquisition mode for set for continuous if # is non-zero, or single-frame if # is 0.
SetSTEMDetectors set #D [#D] [#D] ... Sets the STEM detectors for each available channel of set.  Follow set with a detector number #D for each channel, numbered from 0, or -1 to select no detector for that channel.  At least one actual detector must be specified.
SetProcessing set #P Sets processing for set to the given value #P, which should be 0 for unprocessed, 1 for dark-subtracted, or 2 for gain-normalized.
SetK2ReadMode set #M  Sets the processing mode for set to the given value.  For a K2 or DE camera, #M should be 0 for linear, 1 for counting, or 2 for super-resolution mode.  For a Falcon or K3 camera, #M would be 0 for linear or 1 for counting mode.
SetFrameTime set #F Sets the frame time in set for a K2/K3 or generic frame-saving camera to the given number #FreportedValue1 is set to the actual frame time after constraints are applied.
ChangeFrameAndExposure set #F Changes the frame time and exposure time in set for a K2/K3 or generic frame-saving camera by the given factor #F, maintaining the same number of frames.  reportedValue1 and reportedValue1 are set to the actual frame time and exposure time after constraints are applied.  Command added in 3.9, 2/9/21.
SetDoseFracParams set #D [#S] [#A] [#M] [#C]  Sets dose fractionation parameters for set; follow with up to 5 numbers: #D non-zero for dose-fractionation mode on K2/K3; #S non-zero to save frames (not just for K2/K3); #A non-zero to align frames; #M 0 to align in DM, 1 to align in plugin, or 2 to save a command file for alignframes; #C non-zero to combine frames into sums.
RestoreCameraSet [set] Restores one or all camera parameter set(s) modified with the 'Set' commands above.  If set is omitted, all modified sets will be restored.
KeepCameraSetChanges [set] Retains changes in one or all modified camera parameter sets when script ends.  Use this after making all the changes with the 'Set' commands that you wish to retain.  If set is omitted, all modified sets will be retained.  'RestoreCameraSet' cannot be used on a set that has been retained.  Subsequent changes by the 'Set' commands will be restored on script end or by 'RestoreCameraSet',  unless this command is given again.
Continuous Mode Control
StopContinuous Stops continuous acquisition if it is running.
ReportContinuous Returns -1 if continuous acquisition is not running, or the camera parameter set number being used if it is running, numbered from 0.
UseContinuousFrames # If # is non-zero, the script keeps executing commands (such as stage movement and alignment) even when the camera is acquiring in continuous mode.  Use 0 to return to normal operation, in which the script will wait for continuous acquisition to be ended by the user.
WaitForNextFrame [#S] [#A] After starting a continuous acquisition, this command waits until the next image becomes available in buffer A.  The program will wait until the exposure time has elapsed so that the image is likely to be taken after completion of previous operations, unless the command 'StartFrameWaitTime -1' is used first.  For the next script command, the image will be available in buffers A and B, but for commands after that, buffer B should be accessed instead because the copy in A may be overwritten with a new continuous frame by then.   The 'UseContinuousFrames 1' command must be used before the acquisition is started.  If the optional #S is given, that number of frames will be aligned with the Framealign module and summed, or averaged if the optional #A is non-zero.  Use averaging if the sum may exceed 32767 (for signed images) or 65535.  Essential frame alignment parameters are controlled by several properties; the default is for alignment to a cumulative sum, which is somewhat faster than pairwise alignments and should be adequate for high-contrast frames.
StartFrameWaitTimer [#] With no optional value #, sets the time from which the next 'WaitForNextFrame' will require an exposure time to elapse.  Without this command, the program will wait the full exposure time after the 'WaitNextFrameCommand'. If this command is given with no value just after getting a frame, and operations are done before waiting for the next frame, the next frame may be obtained sooner.  However, if the command is followed by a negative value, then the program will not wait for the exposure time to elapse but just return the next distinct frame.  Use this command with # set to -1 before WaitForNextFrame to get every successive frame if possible, such as after starting a continuous tilt.
SetLiveSettleFraction # Sets the fraction of the usual settling time to apply in continuous mode after image shift or stage movement.  By default, no settling is applied in continuous mode (i.e., the fraction is 0), but some settling may be needed when a script or other operation is using continuous frames.  The fraction is reset to zero when continuous mode ends.
Frame Saving and Alignment
ReportNumFramesSaved Reports the number of frames saved, or being saved, in the last acquisition that saved frames.
ReportFrameAliParams Reports six values for the frame alignment parameter set selected to be used for Record images: the binning or target size for alignment, whether to keep precision for gain-normalized images when doing early returns or GPU frame alignment, the strategy (0 to 3, corresponding to the radio buttons in the Frame Alignment dialog), the number of frames to align all pairs among, the number of iterations to refine (negative if refinement off), and the group size (negative if using groups is off).
SetFrameAliParams #B [#K]
    [#S] [#A] [#R] [#G]
In the frame alignment parameter set selected to be used for Record images, sets the binning to #B if #B is 1-16 or the target size to #B otherwise, and optionally sets whether to keep precision during early returns or GPU frame alignment if #K is 1, the strategy from #S (0, 1, or 2 for pairwise alignment using specified, half, or all frames; 3 for cumulative alignment), the number of frames for all pairs from #A, the number of refinement iterations from the absolute value of #R and to do refinement if #R is positive, and the group size from absolute value of #G and the whether to use groups if #G is positive. 
ReportFrameAli2 Reports more values for frame alignment: whether GPU use is selected, and for the Record parameter set: truncation limit (negative if truncation is off), whether to use hybrid shifts, and the three filter radii.
SetFrameAli2 #G [#T] [#H]
    [#R1] [#R2] [#R3]
Sets whether to use GPU for frame alignment (#G 0 or 1) and, in the frame alignment parameters for Record, optionally sets truncation limit from the absolute value of #T and to truncate if #T is positive, whether to use hybrid shifts if #H is 1, primary filter radius from #R1, and second and third filter radii from #R2 and #R3 or 0 for either if #R1 is present and #R2 or #R3 is not.
SkipFrameAliParamCheck [#] Disables the checking of whether the selected frame alignment parameter set fits the constraints for use selected in the Frame Alignment dialog.  This can be used when modifying frame alignment parameters or Record parameters to avoid an annoying message before every shot.  The optional value of 0 can be supplied to re-enable the checking.
EarlyReturnNextShot #N [#D] Returns as early as possible from the next acquisition, which must involve either aligning or saving dose-fractionation frames from a K2/K3 camera.  Follow with the number of frames #N to be summed in the returned image, 0 to return without any summed image, or -1 to return with the full sum.  The optional #D should be 1 to make a deferred full sum when not aligning in the plugin; this sum is always made when aligning in the plugin for an ordinary acquisition.  Single-shot and dose-fractionation images can be requested without delay in the script.  The single-shot images will be taken as soon as possible (after the frame stack has been accessed).  Another dose-fractionation shot will be delayed until saving is finished for the current shot.  When a frame tilt series is to be taken, a non-zero value of #D triggers the making of separate deferred sums for each tilt angle.  In this case, the Record parameters can specify just saving, just aligning, or both operations.
GetDeferredSum Acquires the deferred full sum that was saved as a result of 'EarlyReturnNextShot', or the next deferred tilt sum available from a frame tilt series.
SetFolderForFrames dir Sets the folder for saving frames from the current camera to dir.  A simple directory name without path separators is required for DE cameras and FEI cameras run with Advanced Scripting.  For other cameras, an absolute path is required, either a network path starting with two slashes or one starting with a drive letter.  Command added in 3.9, 9/12/20.
FrameThresholdNextShot #T [#S] [#E] [#D] Skips saving frames whose mean value is below the given threshold #T in the next shot  from a K2/K3 camera.  The mean value used for comparison with the threshold will be the value that the frame would have after saving, thus a scaled electron count value when taking normalized frames or actual electron counts otherwise (even if aligning also).  The first and last frame will be saved regardless.  The plugin will write a list of frames actually saved, numbered from 0, named as the root of the frame stack name and '_saved.txt'.   The SEMCCD plugin must be dated 12/18/19 or later.  If a command file is being saved for aligning in IMOD, and this command includes the optional #S and #E, these values will be used for the entry to the PartialFrameThreshold option to Alignframes, which takes thresholds for skipping the frames at the start and end of a tilt.  These relative thresholds are between 0 and 1, where 0 sets no threshold.  If #E is omitted, #S will be used for both values.  If the optional #D is added, the frame threshold will be adjusted dynamically on each tilt angle after the first to this fraction of the mean or median value of the frames above threshold on the nearest previous tilt angle.
QueueFrameTiltSeries #S #I #N [#D] [#O] [#W] [#F] [#X #Y] Sets up a tilt series with discrete tilts and other uniform changes to occur during the next shot, provided frames are saved.  Follow with starting angle (#S), increment (#I) and number of tilt steps (#N), plus optional entries #D for the initial delay before starting the starts, #O for the time the beam should be unblanked, #W for time to wait between tilting and unblanking, #F for a change in focus per step, #X and #Y for a change in image shift values for each step.  Image shift values are in microns in 'specimen' coordinates, i.e. with the X axis along the tilt axis, and they will be converted to image shift units at the Record magnification if in Low Dose mode, or at the current magnification if not.  All times are in seconds.  A frame stack mdoc file with tilt angle and dose information is written by the SEMCCD plugin regardless of whether the option for one is turned on.
FrameSeriesFromVar var #F [#D] Sets up a tilt series with all steps specified in the given array variable var, which should contain 1 to 6 values per step of the series, with the values for one step followed by those for the next step, etc.  #F is the sum of 1 if there are tilt angles, 2 if there are shutter open times, 4 if there are  wait times or intervals between steps, 8 if there are changes in defocus from the current value, and 16 if there are image shift changes from the current value.  In the latter case there would be values for X and Y in microns in  'specimen' coordinates, i.e. with the X axis along the tilt axis.  The shifts will be converted to image shift units at the Record magnification if in Low Dose mode, or at the current magnification if not.  The values must be present in the order just listed.  If there are tilt angles, then the third parameter #D (wait times or intervals) is a delay between the end of the tilt and the opening of the shutter, if any.  If there are no tilt angles because continuous tilt is being used, then this item sets the total interval between steps of the series.  #D is an optional initial delay before the first step.  All times are in seconds.  If there are discrete tilts, a frame stack mdoc file with tilt angle and dose information is written.
SetFrameSeriesParams #B [#S] [#X #Y] [#G] [#D] Sets optional parameters for frame tilt series.  Set #B non-zero to use backlash for all tilt steps not in the same direction as the first one, 0 otherwise. Set optional entries: #S with a tilting speed factor or 0 for normal speed; #X and #Y for X and Y stage coordinates to restore after the tilt, or values greater than 9000 for no stage restoration if further entries follow; #G for the minimum gap between frames above threshold for recognizing a new tilt angle when specifying a dynamic threshold with 'FrameThresholdNextShot' or getting back deferred tilt sums with 'EarlyReturnNextShot'; and #D for the number of initial frames to drop when getting simple deferred tilt sums.  The default gap size is 2 frames below threshold and this value should be entered when dropping frames unless a different gap is desired.  The default is not to drop any frames from simple sums; frames are never dropped when getting aligned sums.  For CryoARM, speed factors of 100 - 105 will select pre-set speeds of 10, 2, 1, 0.5, 0.25, and 0.1 degrees/sec.  If setting a speed factor crashes SerialEM or FEI-SEMserver, see notes under TiltDuringRecord.
WriteFrameSeriesAngles file Writes the actual tilt angles from the last frame tilt series to the given file, one per line.
ReportFrameTiltSum Reports: 0 if there is a tilt sum or 1 of there is not, the tilt angle or 0 if there is no tilt sum, the tilt index (numbered from 0), the number of frames in the sum, and the starting and ending frame number after getting a deferred tilt sum from a frame tilt series.
ModifyFrameTSShifts #I #X #Y Changes the image shift values to be imposed for each future step in the same tilt direction after aligning a deferred sum from a frame tilt series to the one at the adjacent previous tilt angle.  #I specifies the tilt index obtained from 'ReportTiltSumProperties', and #X and #Y are relative image shift values needed to align this tilt sum with the previous one with a command such as 'AlignTo B 1' that aligns without imposing an image shift. There are two ways to get these values: 1) Use 'ReportISforBufferShift' then 'ClearAlignment 1' to remove the alignment shifts from the image each time, and use the values from 'ReportISforBufferShift' directly; or 2) Keep track of the last IS values from 'ReportISforBufferShift', subtract them each time from the new IS values, and use those differences for #X and #Y.
ReplaceFrameTSShifts varX varY Changes the entire array of image shift values to be imposed in a frame tilt series with a new set of values (i.e., refined predictions) in the two array variables given by varX and varY.  As of SerialEM 3.8.8, these shifts should be in 'specimen' coordinates just like the original shifts.  Both arrays must have the same size as the original number of tilt angles.  Untested
ReplaceFrameTSFocus var Changes the entire array of focus values to be imposed in a frame tilt series with a new set of values (i.e., refined predictions) in the array variable var,which must have the same size as the original number of tilt angles.  Untested.
AlignWholeTSOnly [#] Allows a whole tilt series taken from a K2/K3, Falcon, or DE camera through the script to be aligned with one command file in IMOD, just as when using the tilt series controller.  Specifically, no command files will be written for individual Record images taken after the command is given, and a single command file to align all frame stacks in the series is written at the end with the 'WriteComForTSAlign' command.  The command has no effect unless frame alignment in IMOD is selected in the Record parameter set and 'Align only whole tilt series' is selected in the Frame Alignment Parameters dialog.  If these conditions are satisfied, there must already be a current image file with an associated .mdoc file.  The optional # can be 0 to turn this mode of operation off.  Sets reportedValue1 to 1 or 0 depending on whether this operating mode was switched to or not.
Hardware Specific Camera Commands
ReportK2FileParams Reports values selected in the Frame File Options dialog: 0 for MRC, 1 for TIFF LZW, or 2 for TIFF ZIP; sum of 1 to pack unnormalized data at all, plus 2 to pack counting mode to bytes; 1 to save MRC files in 4-bit mode 101; 1 to save normalized data times 100; 1 to skip rotation and flip of frames; 1 for one file per frame.
SetK2FileParams #T [#P] [#M] [#N] [#R] [#O] Sets values to control K2/K3 frame file saving.  Follow with up to 6 values: #T 0 for MRC, 1 for TIFF LZW, or 2 for TIFF ZIP; #P as the sum of 1 to pack unnormalized data at all, plus 2 to pack counting mode to bytes; #M non-zero to save MRC files in 4-bit mode 101; #N non-zero to save normalized data times 100; #R non-zero to skip rotation and flip of frames; #O non-zero for one file per frame.
ReportK3CDSmode Reports 1 if CDS mode is on for a K3 camera acquisitions, 0 if not.
SetK3CDSmode #O [#P] Sets the CDS mode option for K3 camera acquisitions on if #O is non-zero, off otherwise.  The existing value is restored at the end of the script unless #P as entered with a non-zero value to make it permanent.
DeferStackingNextShot Disables stacking Falcon intermediate frames after the next exposure.  To stack frames from multiple exposures into one stack, use this command before each exposure except the last one.
OpenDECameraCover Opens the protection cover of the Direct Electron camera for the remainder of the script, if it is the current camera.  Without this command, the cover will be opened and closed for each exposure except during tasks.
SetDECamFrameRate # Sets the frame rate of the current camera if it is a DE camera; follow with the new rate in frames per second, which must be positive and less than the maximum frame rate.  The user's original frame rate is placed into reportedValue1 and is restored when the script ends.
NewDEserverDarkRef #P #H Acquires a dark reference in the DE server if the known interval since the last reference for processing mode #P is longer than #H in hours. #P must be 0 for linear mode or 1 for counting mode.  Parameters for the reference are those specified in the Direct Electron Server Reference Maker Dialog for the given mode.  If #H is 0, the reference is done unconditionally; if #H is negative (-1), the command simply records the current time as the time of the last reference.
UpdateHWDarkRef # Updates the K2 hardware dark reference if the known interval since the last update is longer than # in hours.  If # is 0, the update is done unconditionally; if # is negative (-1), it simply records the current time as the time of the last update.  In order for the time interval to be kept track of between runs of the program, the property IgnoreShortTermCals must not be set. This command is available on a K3 with GMS 3.31 or higher.
Other Camera Commands
OppositeFocus In low dose mode, acquires Focus image from area on opposite side of Record from the defined Focus area.  Opposite areas are not available if Balance Shifts is turned on.
OppositeTrial In low dose mode, acquires Trial image from area on opposite side of Record from the defined Trial area.
AcquireToMatchBuffer buf Acquires an image whose size matches that of the image in the given buffer, with camera parameters matching those used to acquire that image.  The image will be cropped after acquisition if necessary.  The camera parameters will be based on the parameter set used for buffer's image, with the exposure time and binning taken from values stored in the buffer.  In Low Dose mode, the image will be acquire from the corresponding Low Dose area.
StepFocusNextShot # # [# #] Does one or two focus changes during the next exposure.  Follow with 2 or 4 numbers: the time in seconds from start of the exposure to the first focus change, the first focus change in microns, the time from start of the exposure to the second focus change if any, and the second focus change relative to the starting focus, not relative to the focus after the first change.  The command will have no effect if the exposure time is less than the time to the  first change, and the second change will not be done if the time for it is greater than the exposure time. This command is enabled for Gatan, Falcon, and Tietz cameras.
SmoothFocusNextShot # # Changes focus linearly through next exposure.  Follow with 2 numbers, the starting and ending defocus relative to the current focus.  This command is enabled for Gatan, Falcon, and Tietz cameras.
RecordAndTiltUp [#R] [#X #Y] Starts a Record acquisition and tilts the stage up by the current increment after the exposure is expected to be done.  Post-exposure actions must be allowed for the current camera, at least for current Record parameters, but need not be not enabled by the user in the Camera menu.  If optional #R is non-zero, then the program will restore the stage X and Y positions after tilting, either to the position before starting or to #X, #Y if they are entered.
RecordAndTiltDown [#R] [#X #Y] Like 'RecordAndTiltUp', but tilts the stage down by the current increment.
RecordAndTiltTo #T [#B] [#R] [#X #Y] Like 'RecordAndTiltUp', but tilts the stage to the given angle #T.  If an optional non-zero backlash is entered in #B, the stage will tilt first to #T +/- #B, then back to #T. Prior to 5/23/19, #T + #B was used and the sign of #B had to be set to correct the backlash for the desired direction; after then, the program sets the sign properly and a positive value can always be entered.
TiltDuringRecord #A #D [#S] Starts a Record acquisition and starts the stage tilting to angle #A after the delay #D in milliseconds.  On FEI scopes with recent enough versions of FEI scripting, or JEOL scopes with recent versions of TemExt.dll, #S can be added with a speed multiplier (< 1 for slower, > 1 for faster).  For CryoARM, speed factors of 100 - 105 will select pre-set speeds of 10, 2, 1, 0.5, 0.25, and 0.1 degrees/sec.  On FEI scopes this command will freeze the user interface and prevent scope updates while the stage is tilting. If the command crashes SerialEM or FEI-SEMserver with a speed multiplier but runs OK without one, it means that the FEI scripting version is too old to support the speed command. In that case, define an environment variable SEM_USE_TOMMONIKER with the value of 1 on the microscope computer to use an alternate interface.
SetDoseAdjustmentFactor # Sets a factor for adjusting the exposure dose and frame doses stored in an .mdoc file for an image.  Set to 0 to eliminate the adjustment; the factor will be reset to 0 when the script ends.  Command added in 3.9, 2/12/21.

Buffer and File Commands

In all commands including a buffer to operate on, the buffer can be specified with either the buffer letter or the corresponding number, where A corresponds to 1.

Buffer and Image Commands
Copy buf1 buf2 Copies from buf1 to buf2 (e.g., Copy C A), where buf1 can be in the FFT window.
Show buf Displays the given buffer (e.g., Show C)
ReportCurrentBuffer Returns the letter of the buffer currently open in the main window in reportedValue1 and 0 or 1 in reportedValue2 indicating if the buffer contains an image or not. FFT windows or image windows other than the main window are ignored. Command added in 3.9, 7/8/21.
CropImage buf #X0 #X1 #Y0 #Y1 Crops out a subarea of the given buffer, which can be in the FFT window, from #X0 to #X1 in X and from #Y0 to #Y1 in Y. Coordinates are numbered from 0 to size - 1 in each dimension and 0 in Y is at the top.
CropCenterToSize buf #X #Y Crops out a centered subarea of size #X by #Y from the given buffer, which can be in the FFT window.
ReduceImage buf # Reduces the image in the given buffer by the factor #, which must be greater than 1 but need not be an integer.  buf may be in the FFT window.  Antialiased reduction (with a Lanczos 2 filter) is used instead of binning.
Rotate90CW buf Rotates the image in the given buffer by 90 degrees clockwise. The result is placed into buffer A.
Rotate90CCW buf Rotates the image in the given buffer by 90 degrees counterclockwise. The result is placed into buffer A.
FFT buf [#B] Takes the FFT of the image in the given buffer, optionally applying the binning given in #B.  The FFT will appear in buffer A, or in the side-by-side FFT window if that option is on.
FilterImage buf sig1 rad1 rad2 sig2 [obuf] Applies a filter in Fourier space to the image in the given buffer, which can be in the FFT window.  The filter is the product of two separate filters, one controlled by sig1 (sigma1) and the other by rad2 (radius2) and sig2 (sigma2).  Sigma1 provides low-frequency filtering with an inverted Gaussian rising from 0 to 1 with that sigma, and starting at either 0 frequency or the frequency specified by |rad1| (radius1) if it is negative.  Radius2 and sigma2 provide high-frequency filtering with a Gaussian that falls past radius2 with that sigma.  If radius1 is positive, a Gaussian with the same sigma falls off to the left of radius1.  If sigma1 is negative, it provides a band-pass filter peaking at 1.414 * |sigma1|.  See Filterplot in IMOD for a complete description and ability to graph any filter.  The units are reciprocal pixels (0 to 0.5 along an axis).  The floating point output is placed into buffer A, and top buffers are rolled, unless the optional obuf is added specifying a different buffer, which can be buf.  Command added in 3.9, 9/12/20.
AddImages buf1 buf2 [obuf] Adds the two images in buffers buf1 and buf2  The floating point output is placed into buffer A, and top buffers are rolled, unless the optional obuf is added specifying a different buffer, which can be buf1 or buf2.  Command added in 3.9, 11/11/20.
SubtractImages buf1 buf2 [obuf] Like 'AddImages', except that buf2 is subtracted from buf1. Command added in 3.9, 11/11/20.
MultiplyImages buf1 buf2 [obuf] Like 'AddImages', except that buf2 is multiplied by buf1 Command added in 3.9, 11/11/20.
DivideImages buf1 buf2 [obuf] Like 'AddImages', except that buf1 is divided by buf2, with 0 in the output at pixels where buf2 is zero. Command added in 3.9, 11/11/20.
ScaleImage buf #S #A [obuf] [#K] Scales the image in buffer buf by multiplying by #S then adding #Abuf may be in the FFT window.  The output is placed into buffer A, and top buffers are rolled, unless the optional obuf is added specifying a different buffer, which can be buf unless that is in the FFT window.  The resulting image is floating point unless the optional #K is non-zero to keep the existing image type.  Command added in 3.9, 11/11/20.
ImageProperties [buf] Reports size in X and Y, binning, exposure, pixel size, and parameter set used for the image in buffer A or in the buffer indicated by buf, which can be in the FFT window.  It also sets the variable imageTickTime with the time that the image finished being acquired, in seconds since the program started.   Values can be assigned to variables after a buffer letter/number.
ImageLowDoseSet [buf] Reports the parameter set that an image was taken with and whether it was taken in Low Dose mode, for the image in buffer A or in the buffer indicated by buf.  For one of the 5 standard parameter sets, it will report the set name.  For a montage image, it will report Record.  For a tracking image, it will report View if the mag matches that of View in Low Dose; if the mag matches Record in Low Dose, it will report Record or Preview depending on which has an closest exposure time closest to that of the image.   Values can be assigned to variables after a buffer letter/number.
ReportMeanCounts [buf] [#] Reports the mean counts of the A buffer, or of the buffer indicated by buf; add a 1 as # to get unbinned counts per second instead, or add a 2 as # to get a report of mean, standard deviation, minimum and maximum.  No optional assignment to variables.
ElectronStats [buf] Reports the min, max, mean, and SD of the A buffer, or of the buffer indicated by buf, scaled to electrons, and also reports the electrons per unbinned pixel per second.  The camera must have a defined counts per electron. Values recorded in electron counting mode will be linearized if possible (corrected for decreasing counting efficiency at higher dose rates).   Values can be assigned to variables after a buffer letter/number.
RawElectronStats [buf] Reports the same items as 'ElectronStats' without linearizing them for loss in counting mode.  Values can be assigned to variables after a buffer letter/number.
SubareaMean #X0 #X1 #Y0 #Y1 Reports the mean counts in a subarea of the A buffer from #X0 to #X1 in X and from #Y0 to #Y1 in Y. Coordinates are numbered from 0 to size - 1 in each dimension and 0 in Y is at the top.  Value can be assigned to variable at end of command.
CircularSubareaMean #X #Y #R Reports the mean counts in a circular subarea of the A buffer defined by center point #X,#Y and radius #R. Value can be assigned to variable at end of command.
QuadrantMeans [#N] [#F1] [#F2] Reports means of strips along quadrant boundaries. Optional entries are #N for the number of pixels between strip and boundary (default 2), #F1 for the strip width as a fraction of quadrant extent (default 0.1), and #F2 for the fraction of quadrant extent to trim off the length of the strip (default 0.1). Output is labeled by quadrant number (1 to 4) and 'h' for horizontal strips or 'v' for vertical strips.
CheckForBadStripe [buf] [#H] Checks for sharp transitions between columns or rows in an image and for whether they occur at expected positions for a bad channel of data from a K2 or K3 camera.  Analyzes the image in buffer A, or the buffer indicated by buf.  It uses the RotationAndFlip property of the camera, if it can be identified, to determine if vertical or horizontal stripes should be sought, unless the option #H is entered with 1 for horizontal or 0 for vertical stripes.  Reports the number of significant transitions found and the number of those that are within a few pixels of the expected boundaries between channels for a K2 or K3 camera.  The latter would be a more reliable number to use if there is a risk of very straight grid bars in the field.
CtfFind buf #M #N [#F] [#B] [#P0] [#P9] [#S] [#A] Determines defocus and astigmatism by fitting to Thon rings in an FFT of the image in the given buffer.  Follow the buffer letter/number with the minimum (#M) and maximum (#N) defocus for the search (in microns, underfocus negative), and with these optional entries:
  #F non-zero to do a 1-D initial search instead of a slower 2D one
  #B between 128 and 640 to set the box size for the amplitude spectrum to analyze, or zero to use the default (256)
  #P0 alone to set the additional phase shift, in degrees, or 0 (or 0 0) to use the phase shift set in the Set Phase Plate Shift menu item
  #P0 and #P9 to set the minimum and maximum phase shift for a search that includes phase shift; the range must be less than 90 degrees.  Such a search may be slow.
  #S nonzero to set the phase shift search step, or 0 to use the default (5.7 degrees)
  #A non-zero to fix astigmatism at zero.
See Do Ctffind On Click and Set Ctffind Options for more details on these options.
After successful fitting, the command will set reportedValue1-6 with mean defocus and astigmatism (difference between maximum and minimum defocus) in microns (underfocus negative), astigmatism angle in degrees, additional phase shift in degrees, fitting score, and resolution in Angstroms to which Thon rings fit.
Directory and Miscellaneous Commands
SetDirectory dir Changes the working directory to dir, which can contain spaces.  The working directory is the location where script commands will access files when the names given to commands do not include a path, but it is not the directory where file choosers will open unless the 'OpenChooserInCurrentDir' command is used.
ReportDirectory Reports the current working directory, which is where a file will be created if it is opened from a script command without a full path.
UserSetDirectory [prompt] Opens a directory chooser dialog to allow user to select or make a directory, and change the working directory to it.  If the optional prompt string is not supplied, the dialog title is 'Choose a new current working directory'.  The chosen directory is stored in reportedValue1.  This is the directory where script commands will access files when given a name with a path. but file choosers will not open there unless the 'OpenChooserInCurrentDir' command is used.
OpenChooserInCurrentDir Makes the next file chooser dialog open in the current working directory.  If the user selects a different directory in the chooser, the next file chooser will open in that directory, just as if this command was not given, although the location will be kept track of by the program rather than by the operating system.  Command added in 3.9,0, 11/29/20
MakeDirectory dir Creates the directory dir if it does not already exist.  dir can contain spaces.  The parent directory must already exist.
MakeDateTimeDir Creates a directory named by the date and time (e.g., Aug15_12.23.15) under the current directory and change to this as the new working directory.
DoesFileExist file Reports if file exists in the current working directory if the name includes no path, or at the indicated path if it includes a path.  file can be a directory.  Command added in 3.9, 11/8/20.
AllowFileOverwrite # Allows 'OpenNewFile', 'OpenNewMontage', and 'OpenTextFile ID W...' to overwrite an existing file if # is 1, or disallow it again if # is 0.
RemoveFile file Removes the given file unconditionally, prints a warning if it cannot be removed.
WriteComForTSAlign Writes the command file for aliging a whole tilt series if this mode of operation was selected with the AlignWholeTSOnly command; otherwise it has no effect. The tilt series file with associated .mdoc must still be the current open file.
SaveLogOpenNew [newFile] Closes the log window and opens a new one.  If a log file has been saved, the log is automatically saved to it before closing.  If there is no log file and the log has new contents since program startup, the program will ask the user whether to save to log first; if the user cancels, the script is aborted.  If a filename (newFile) is added, the new log will be saved with that name.  Variables will be substituted before using the name. An extension in this name will be stripped off before adding '.log', so if you want to preserve extensions or other text after a period, add '.log' to the end of the name.  If the file already exists, a number will be added to get a unique new name.
CloseLogOpenNew [#] Closes the log window and opens a new one.  If a log file has been saved, the log is automatically saved to it before closing.  If there is no log file and the log has new contents since program startup, the program will ask the user whether to save to log first unless a non-zero value is entered for the optional #, in which case the contents of the log are discarded. If the user cancels the query, the script is aborted.
SaveLog [#O newFile] Saves the log to a file.  If no optional entries are made, it will be saved to the current file if there is one; otherwise the user will be asked for a filename in which to save.  If a filename newFile is entered on this command, the log will be saved to a new file with that name.  Variables will be substituted before using the name. An extension in this name will be stripped off before adding '.log', so if you want to preserve extensions or other text after a period, add '.log' to the end of the name.  Enter a non-zero value for #O to overwrite the file if it already exists, or zero to have a number added to get a unique new name.
SaveCalibrations Saves the calibrations to a file. The name of the calibrations file is printed in the log window; execution of this command requires Administrator mode to be enabled in the Calibrations menu.
ListCalibrations Print tables with image shift, stage shift, focus, astigmatism via CTF, beam shift, beam intensity and spot intensity calibrations to the log window for diagnostic purposes. Command added in 3.9, 7/8/21.
Image File Commands
S or Save [buf] [#F] Saves image in A or in buf to current open file, or to the given file number #F
SetNewFileType #T [#S] Enter #T as 0 to open files as MRC, or 1 to open files as a TIFF series described in an image autodoc file. The optional second value #S sets whether to open montaged files as MRC or as a TIFF series, but only if the property MontageAutodocOptions is set.
OpenNewFile file Opens a file with the given name, which can contain spaces. The file properties dialog will be bypassed. Since the current working directory can be unpredictable, depending on whether the user has opened a file with the file chooser, it is advisable either to specify an absolute path for the filename, use a 'SetDirectory' with an absolute path, or use a filename in a variable set by 'ChooserForNewFile'.  The same advice applies for the following commands that open files as well.
OpenNewMontage #X #Y file Opens a file with the given name for montaging, with the number of frames in X and Y given by #X and #Y. If either #X or #Y is 0, the number of frames will be taken from the last montage that was open. The file properties and montage setup dialogs will be bypassed, and some properties like overlap and whether to do a stage montage will be taken from the last montage that was open. If no montage has been opened through the dialogs, some parameter settings with  SetMontageParams will work, some will crash the program.
SetMontageParams #S [#OX #OY #FX #FY #N #B] Sets up to 7 montage parameters after a montage file has been opened; enter a value or -1 to leave the parameter unchanged. The entries are: #S 1 to use stage movement or 0 not to; #OX overlap in X; #OY overlap in Y; #FX frame size in X; #FY frame size in Y, #N 1 to skip correlations or 0 not to; #B a binning.  The frame sizes, overlaps, and binnings cannot validly be changed after acquiring into the file.
SetupWaffleMontage #B file Opens a montage file or adjust the current file's properties so that it will hold an image of the cross-line (waffle) replica grating with at least #B blocks in X and Y at the current magnification. Follow with the minimum # of blocks and the name of the file to be opened if necessary.  If montaging is not needed, no changes are made.  If there is an existing montage that is adequate, its properties will be adjusted to work at the current mag.  If a new montage is needed, it will close the current file if it is a montage and open a new one with the given name.  Variables will be substituted, so the name can contain the mag index, for example. It sets reportedValue1 to 1 or 0 depending on whether montaging is needed or not.
ReportNumMontagePieces Reports the number of pieces that will be acquired for a montage if one is currently open, or 1 if not.
SaveToOtherFile buf typ cmp file Saves one image in the given buffer buf, which can be in the FFT window, to the file with the given name and closes the file.  typ specifies the type of file and can be MRC, HDF, TIF, TIFF, JPG, JPEG, CUR, or -1 (case insensitive), where CUR or -1 means use the current file type for the File menu entry Save Single/Save to Other.  If that type is a series of TIFF files, a single TIFF will be written with the given name instead.  cmp specifies the compression for a TIFF file and can be NONE,  LZW, ZIP, JPG, JPEG, CUR, or -1 (case insensitive), where CUR or -1 means use the current compression for Save Single/Save to Other.  If JPG or JPEG is entered for 'typ', a true JPEG file will be written, not a JPEG-compressed TIFF, and the compression entry does not matter (but must be present before the filename file).
SnapshotToFile #S #T feat typ cmp file Takes a snapshot of the image display in the current active buffer and saves it to the file with the given name and closes the file.  #S sets the amount of image scaling relative to the display with a value of 1 or greater, or 0 or less to take the whole image at 1:1 zoom.  #T sets the scaling of text labels and line thicknesses with a value of 1 or more, or 0 or less to use the same scaling as for the image.  Set feat non-zero to skip feature drawing, with the sum of 1 to skip some features, 2 to skip Navigator items, and 4 to skip the scale bar.  typ specifies the type of file and can be TIF, TIFF, JPG, JPEG, CUR, or -1 (case insensitive), where CUR or -1 means use the current file type selected in the Image Snapshots dialogcmp specifies the compression for a TIFF file and can be NONE,  LZW, ZIP, JPG, JPEG, CUR, or -1 (case insensitive), where CUR or -1 means use the current compression in the Image Snapshots dialog.  If JPG or JPEG is entered for 'typ', a true JPEG file will be written, not a JPEG-compressed TIFF, and the compression entry does not matter (but must be present before the filename file).
EnterNameOpenFile [prompt] Gets a filename through a dialog with a simple text box and open it as a new file.  If the optional prompt string is not supplied, the prompt is 'Enter name for new file:'.
ChooserForNewFile # var Opens a file chooser for the user to specify a new file; # should be 0 for an MRC file or non-zero for an .idoc file, and var must be the name of a variable to which the full filename will be assigned.  Since the user will confirm the replacement of a file, the command also allows 'OpenNewFile' and 'OpenNewMontage' to overwrite an existing file.
OpenFrameSumFile suffix Opens a file whose name starts with the last name used for saving frames from a K2/K3, DE, or Falcon camera, and ends with the suffix string given in the command.  The string can contain spaces and variables.
OpenOldFile file Opens an existing MRC, HDF, or .idoc file with the given name, which can contain spaces.
UserOpenOldFile Opens a file chooser for a user to open an existing MRC, HDF or .idoc file and opens the file, just like the Open Old item in the File menu. The script is suspended if the user cancels or pick a file that cannot be opened.  Command added in 3.9, 2/6/21.
ReadFile # [buf] Reads the given section # (numbered from 0) from the current open file into the standard Read buffer, or into the buffer indicated by the optional buf
ReadOtherFile # buf file Reads the given section # (numbered from 0) from a file into the given buffer buf and leaves the file closed; buf can be a buffer letter/number or -1 to use the standard Read buffer; end with filename.  This command can read from a TIFF file, which cannot be opened otherwise.
RetryReadOtherFile # Sets the number of times to retry if there is an error in ReadOtherFile, with a 2-second wait between trials.
CloseFile [e] Closes the current file. Enter optional 'e' to stop script if no file is open.
ReportFileNumber Reports the number of the currently selected file, numbered from 1, or -1 if there is no file open.
SwitchToFile # Makes the given file number, numbered from 1, be the current open file.
ReportFileZsize Reports the number of frames in currently open file
ReportCurrentFilename [#] Reports the full path and filename of the current open file and sets it into reportedValue1; or if the optional # is entered with a 1, sets the root of the filename including the path in reportedValue1, the extension (including the dot) in reportedValue2, the path only in reportedValue3, and the rest of the rootname in reportedValue4.  No optional assignment to variable.
ReportLastFrameFile Reports the full path and filename of the last frame file saved from a K2/K3, DE, or Falcon camera and sets it into reportedValue1.
ReportFrameBaseName Reports the base name if one is included in frame file names; sets reportedValue1 to 1 if it is included and 0 if not, and sets reportedValue2 to the base name if it is included or 'none' if it is not.
Text File Commands
ReadTextFile var file Reads the entire contents of the given text file, breaks it up by spaces or tabs, and stores the words or numbers as an array in the variable var.  All lines will be read and combined into the one variable.  The file will be closed after reading.
ReadStringsFromFile var file Reads the entire contents of the given text file as a whole string per line, and stores the lines as an array in the variable var.
Read2DTextFile var file Reads the entire contents of the given text file, breaks it up by spaces or tabs, and stores the words or numbers of each line as a separate row of a 2D array in the variable var.  The file will be closed after reading.
     The following commands allow multiple files to be opened for either reading or writing (not both) and accessed one line at a time.  Each file is referred to by an arbitrary one-word identifier (ID) that immediately follows the command; the ID is case-insensitive.
OpenTextFile ID mode #K file Opens a file with the given ID in the given mode, closing it when the script ends if #K is 0 or keeping it open if #K is non-zero.  The mode can be:
   R or r to open for reading, giving an error if the file does not exist;
   T or t to try to open for reading, setting reportedValue1 to 1 if the file exists or 0 if it does not;
   W or w to open for writing, giving an error if the file exists unless 'AllowFileOverwrite 1' has been used;
   O or o to open for writing, overwriting an existing file if any;
   A or a to open for appending (writing at the end), giving an error if the file does not exist.
The same file cannot be opened under two different ID's.  The 'T' mode can be used to avoid a script error and also can be used in a loop to wait for a file to appear from an external source.
WriteLineToFile ID [line] Writes the remainder of the text on the script line (after variable substitution) to the file with the given ID.  The comment character '#' can be included and text after it will be written.  Omit text to write a blank line.
ReadLineToArray ID var Reads the next line of the file with the given ID, breaks it into words, and sets up an array variable var with each word as an element.  '#' is treated as the start of comment and the rest of the line is discarded. Blank lines and lines starting with '#' will be skipped.  Parts of the line enclosed in single quotes will be treated as single strings if the 'ParseQuotedStrings' command has been given.  Reaching the end of the file does not give a script error; instead, reportedValue1 is set to 1 when a line is read or 0 if nothing was read.  This command could be used in a loop to wait for a file to be added to by external source.
ReadLineToString ID var Works like 'ReadLineToArray ', but the line is stored in the variable exactly as it is in the file, including a line starting with '#'.  Blank lines will still be skipped.
FlushTextFile ID Flushes the output added to the file with the given ID to disk.
CloseTextFile ID Closes the file with the given ID.
IsTextFileOpen ID [file] Sets reportedValue1 to 1 if there is an open file with the given ID, or with the given optional name, and to 0 otherwise.  The ID can be nonsense when testing with a filename (file).
Autodoc/.mdoc File Commands
AddToAutodoc key value Adds a key-value pair to the last section of the autodoc associated with the current open image file, if any.  The next word after the command is the key, and the remainder of the text on the line is taken as the value.  Variables are substituted before using the text.  After one or more additions to a section of the autodoc, a WriteAutodoc command must be used to save the values before closing the file or saving another image to it.  If no images have been written yet, the entry will be added to the global section.
WriteAutodoc Writes the autodoc associated with the current open image file.  Use this command once after adding one or more values to a section of the autodoc.
OpenFrameMdoc filename Opens an '.mdoc' file with the given filename for information about image acquisitions that save frames, the same as using the Open .mdoc for Frames command.  An error is generated if such a file is already open.
CloseFrameMdoc [#] Closes the '.mdoc' file for acquisitions that save frames, if one is open. If the optional # is non-zero, an error is generated if no file is open.
AddToFrameMdoc key value Adds a key-value pair to the last section of the autodoc opened with the Open .mdoc for Frames or 'OpenFrameMdoc' command.  This works just like AddToAutodoc, but the WriteFrameMdoc command must be used instead after adding values.
WriteFrameMdoc Writes the frame autodoc file; use this command after adding one or more values to a section.
ReportFrameMdocOpen Reports whether a frame .mdoc file is open; sets reportedValue1 to 1 if so.
DeferWritingFrameMdoc Prevents the program from appending a new section to the frame .mdoc file after frames are acquired.  If you use this command before starting the acquisition, add values after acquisition with 'AddToFrameMdoc ', and finish with 'WriteFrameMdoc', the new section with your additions can be appended to the file rather than rewriting the whole file.
StartNextFrameStackMdoc key value Adds a key-value pair to the global section of the .mdoc file written with each frame stack when the option for such a file is selected in the Frame File Options dialog, after clearing out any previous entries in the global section.  This command and the next must be given before acquiring.
AddToNextFrameStackMdoc key value Adds a key-value pair to the global section of the frame stack .mdoc file while retaining previous entries there.

Microscope and Filter Control Commands

Stage-Related Commands
U or TiltUp [#R] [#X #Y] Tilts up by preset increment.  If optional #R is non-zero, then the program will restore the stage X and Y positions after tilting, either to the position before starting or to #X, #Y if they are entered.
D or TiltDown  [#R] [#X #Y] Like TiltUp, but tilts down by preset increment
TiltTo #A  [#R] [#X #Y] Like TiltUp, but tilts to given angle #A
TiltBy #A  [#R] [#X #Y] Like TiltUp, but changes tilt by the given amount #A
BackgroundTilt #A [#S] Starts tilting stage in the background; images can be taken and scripts can run during the tilt.  Follow with #A, the angle to tilt to, and optionally with #S, a speed factor for FEI or JEOL scopes that support this (< 1 for slower than normal tilting).  For CryoARM, speed factors of 100 - 105 will select pre-set speeds of 10, 2, 1, 0.5, 0.25, and 0.1 degrees/sec.  On FEI scopes, background stage movement requires the property 'BackgroundSocketToFEI' set to 1 so that the fourth socket for background stage operations is opened when the program starts. If the command crashes SerialEM or FEI-SEMserver, see notes under TiltDuringRecord.
ReportTiltAngle Reports current tilt angle
MoveStage #X #Y [#Z] Moves stage by micron increments in X, Y, Z (#Z optional)
MoveStageTo #X #Y [#Z] Moves stage to given position in microns. #Z is optional and Z will not be changed if it is omitted.
StageShiftByPixels #X #Y Moves the stage by the given number of unbinned pixels in X and Y on the current camera.
MoveStageWithSpeed #X #Y #S Moves the stage by micron increments in X and/or Y with a speed factor #S.  On FEI scopes, this may work only with one axis set to 0 using standard scripting, but should work for moving both axes when going through the Tommoniker interface.  If the command crashes SerialEM or FEI-SEMserver, see notes under TiltDuringRecord.
ReportStageXYZ Reports current stage position
ReportStageBusy Reports if the stage is busy and set reportedValue1 to 1 if so, 0 if not.
TestRelaxingStage #X #Y [#B] [#R] Moves stage by the micron increments in X and Y with backlash correction and a small relaxation in the opposite direction from the backlash correction.  The optional #B can be set with the backlash amount, otherwise the value of the property 'StageMontageBacklash' will be used.  The optional #R can be set with the relaxation amount in microns; otherwise the value of the property 'StageRelaxation' will be used (default 0.025).  The backlash movement will be opposite to the stage movement unless #B is negative.  To assess the value of relaxation, a measurement of the time it takes for drift to settle should be done after this command.
RelaxStage [#R] If the stage is in a known backlash state, moves the stage in the opposite direction from its last movement by the amount given by the optional #R, or the StageRelaxation property (0.025 by default).  A message is printed if the stage backlash state is not known.
ReportStageBAxis Reports the B axis value of the stage in degrees, if such an item exists.
SetStageBAxis # Sets the stage B axis to the given value in degrees.
Focus-Related Commands
ChangeFocus # Changes defocus by the given value in microns
SetDefocus # Sets the defocus to the given value in microns
SetAbsoluteFocus # Sets focus to an absolute (standardized) value as reported earlier by ReportAbsoluteFocus or ReportFocus
SetStandardFocus # Same as 'SetAbsoluteFocus', which is preferred to avoid confusion with the calibrated standard or eucentric focus value
SetObjFocus # Calls SetObjFocus on JEOL with the given #, an integer increment, and reports change in focus
SetDiffractionFocus # Sets diffraction focus to the given #
ReportDefocus Reports current defocus readout in microns
ReportAbsoluteFocus Reports an absolute (standardized) value for the current focus setting
ReportFocus Same as 'ReportAbsoluteFocus', which is a better description of the operation
SetEucentricFocus If in low mag, sets to the standard focus for the current mag or nearest LM mag if one has been set; otherwise on FEI it assumes standard focus is 0 and on JEOL it stops with an error.  If not in LM, sets to the standard focus for the nearest nonLM mag if one has been set or stops with an an error if none were set.  On FEI scopes, it issues a warning if it is using a calibrated value from a different mag.
CalEucentricFocus Stores the current standardized focus value as the standard focus for the current mag, just as the Calibrate menu item Standard Focus does.
SaveFocus Saves the current focus; the focus will be restored to this value either by RestoreFocus or when the script stops or exits.  The script will not be resumable if it stops.
RestoreFocus Restores the focus value when SaveFocus was run.  After this is run, the focus will not be restored again when the script ends.
ResetDefocus Sets the defocus readout to 0, just as Reset Defocus in Focus menu does.
Magnification-Related Commands
SetMag #M [#D] Sets the mag to an actual mag value in #M.  In STEM mode, set the optional #D non-zero to set STEM mag directly to the given value, without trying to find it in the mag table.
SetMagIndex # Sets the magnification index to the given value
ChangeMag # Changes mag by given number of mag steps, positive to increase mag index and negative to decrease it.  If the property 'UseInvertedMagRange' is set, positive and negative increase or decrease the mag rather than the mag index in the inverted range.
ReportMag Reports the current mag; also sets reportedValue2 to 1 if low mag mode, 0 if not
ReportMagIndex Reports the current mag index; also sets reportedValue2 to 1 if low mag mode, 0 if not
ReportCameraLength Reports the camera length in meters, or 0 if not in diffraction mode.
SetCamLenIndex # Sets the camera length index to the given number; on an FEI scope, values higher than 30 set the index to (# - 30) in LAD mode
SetMagAndIntensity # Sets the mag to the actual film mag value and change the beam to maintain the same brightness. Two values are reported: the initial percent C2 value and the remaining factor of intensity change needed if it was not possible to change the intensity by the full amount needed. The C2 value should be used to restore intensity when the mag is restored. The remaining intensity change could be applied to the exposure time if necessary. The script will stop if there is an error in the intensity change.
ChangeMagAndIntensity # Changes mag by the given number of mag steps and change the beam to maintain the same brightness. Behaves same as SetMagAndIntensity, and steps in the same way as ChangeMag.
IncMagIfFoundPixel # Increases or decreases mag by one step if the pixel size has been found at the current mag with the Find Pixel Size routine, depending on whether # is positive or negative.  Sets reportedValue1 to 1 if the mag is changed, 0 otherwise.
Beam-Related Commands
SetSpotSize # Sets the spot size to the given number
ReportSpotSize Reports the current spot size
SetPercentC2 # Sets the C2/C3 lens strength to the given percentage, or illuminated area on Titan to given value in microns.
IncPercentC2 # Changes the C2/C3 lens strength percentage or illuminated area in microns by the given amount
ReportPercentC2 Reports the percent C2/C3 (on an FEI scope, this number matches the value in MUI) and the fractional lens strength.  On a Titan, if illuminated area is being used for intensity, this reports the illuminated area value.
ReportCrossoverPercentC2 Reports the percent C2/C3 and the fractional lens strength of the crossover at the current spot size and probe mode as calibrated. If illuminated area is being used for intensity, this reports the illuminated area value at crossover.
ReportIlluminatedArea Reports the illuminated area on a Titan in the units that are used internally, which are microns times 0.01.
SetIlluminatedArea # Sets the illuminated area on a Titan to the given value, expressed in microns times 0.01.
ReportImageDistanceOffset Reports the offset of the distance from the condenser plane to the image plane on a Titan in the units from the scope. Older versions of the scripting software do not have this function, and with them, this command will crash SerialEM or FEI-SEMserver.
SetImageDistanceOffset # Sets the offset of the distance from the condenser plane to the image plane on a Titan; the allowed range is +/- 0.02. Older versions of the scripting software do not have this function, and with them, this command will crash SerialEM or FEI-SEMserver.
SetIntensityForMean # Adjusts beam intensity to yield the given number of counts in a Record image, based on counts in the tilt-foreshortened area of the image in A. In Low Dose mode, this operates only on Record images and will change the intensity only of the Record area.
SetExposureForMean #M [#K] Adjusts Record exposure time to yield the given number of counts #M, based on counts in the tilt-foreshortened area of the image in A, which must be a Record image in Low Dose mode.  For a K2/K3 camera taking dose-fractionated images, a non-zero value can be given for the optional #K to modify frame time so as to keep the same number of frames.
SetIntensityByLastTilt Adjusts beam intensity by the change in cosine of the tilt angle from the last tilt change. In low dose mode, this changes the intensity only of the Record area.
ChangeIntensityBy # Changes beam intensity by the given factor using calibrations. In low dose mode this changes the intensity of the current area.
SetDoseRate # Changes the beam intensity to set the dose rate at the camera to the given value in electrons per unbinned pixel per second beam intensity, based on the image in buffer A. This command is the same as running Set Dose Rate in the Tasks menu. In low dose mode it changes the intensity of the current area.
SetAlpha # Sets alpha value on JEOL.
ReportAlpha Reports alpha value on JEOL.
SetBeamShift #X #Y Sets the beam shift to the given values (nominal micron units)
ReportBeamShift Reports the beam shift in nominal micron units
MoveBeamByMicrons #X #Y Moves the beam by the given number of microns in X and Y.
MoveBeamByFieldFraction #X #Y Moves the beam by the given fractions of the current camera field of view in X and Y; e.g. 0.5,0.5 would move the center of the beam from the center of the field to the upper right corner.
SetBeamTilt #X #Y Sets the beam tilt to the given values (milliradians or % of full scale)
ReportBeamTilt Reports the beam tilt in milliradians for FEI, % of full-scale value for JEOL
SetImageBeamTilt #X #Y Sets the image-beam tilt on an FEI scope to the given values in milliradians.  The FEI scripting documentation cautions against using both this kind of beam tilt and the dark field tilt.  Command added in 3.8, 5/23/21.
ReportImageBeamTilt Reports the image beam tilt in milliradians on an FEI scope.  Command added in 3.8, 5/23/21.
SetProbeMode #|mode Sets the mode to microprobe or nanoprobe on an FEI scope.  Follow with 0 or 'nano' for nanoprobe, or 1 or 'micro' for microprobe.
SaveBeamTilt Saves the current X and Y beam tilt (specifically for the current probe mode on an FEI scope).  It will be restored to these values either by RestoreBeamTilt or when the script stops or exits.  The script will not be resumable if it stops.
RestoreBeamTilt Restores the beam tilt saved when SaveBeamTilt was run or another command saved the beam tilt (AdjustBeamTiltForIS or several ImageShift commands).  After this is run, the beam tilt will not be restored again when the script ends.  For an FEI scope, it is restored for the current probe mode provided that a value was saved in that mode.
ReportProbeMode Reports whether an FEI scope is in nanoprobe or microprobe mode; sets reportedValue1 to 0 or 1, respectively.
Image Shift-Related Commands
SetImageShift #X #Y [#D] [#A] Sets the image shift to the given values (image shift units).  The values correspond to the ones give by ReportImageShift, which are adjusted for tilt axis offset, image shift offset, and low dose area shift.  Add the optional #D to impose a settling time before the next camera image equal to #D times the normal settling time (i.e., 1 for regular settling).  Add the optional #A to use the Coma vs. Image Shift calibration to adjust beam tilt and objective stigmation for the incremental change in image shift from its current value. With that option, the command saves the current beam tilt, if it has not been saved before in the script, and it will be automatically restored when the script exits.  The stigmator settings will also be saved and restored.
ImageShiftByPixels #X #Y [#D] [#A] Changes image shift by given # of unbinned pixels in camera X and Y; optional #D and #A provide settling time and beam-tilt adjustment for the image shift as just described.
ImageShiftByUnits #X #Y  [#D] [#A] Changes image shift by given # of IS units in X & Y; optional #D and #A provide settling time and beam-tilt adjustment for the image shift as just described.
ImageShiftByMicrons #X #Y [#D] [#A] Changes image shift by given distance on specimen (X is tilt axis); optional #D and #A provide settling time and beam-tilt adjustment for the image shift as just described.
ImageShiftByStageDiff #X #Y [#D] [#A] Changes image shift by the equivalent of the given stage shift in X and Y; optional #D and #A provide settling time and beam-tilt adjustment for the image shift as just described.
ReportImageShift Reports the image shift in IS units, adjusted for tilt axis offset, image shift offset, and low dose area shift; if image shift is calibrated, also report the equivalent shift in unbinned pixels on the current camera at the current magnification, and the amount the stage would need to be moved to compensate for resetting this image shift.  Positive values of the camera shift will result from an image shift imposed by dragging an image to the upper right.
ReportSpecimenShift Reports the image shift, as just described, in the "specimen" coordinates used internally by the program, which are coordinates in microns with X along the tilt axis.
Miscellaneous Scope Commands
SetObjectiveStigmator #X #Y Sets the objective lens stigmator to the given values (between -1 and 1)
ReportObjectiveStigmator Reports the X and Y values of the objective stigmator, between -1 and 1
SetBeamBlank # Blanks beam if # is 1, unblank if # is 0
NormalizeLenses # Normalizes selected lenses on an FEI or Hitachi scope; # is the sum of 1 for projector, 2 for objective, 4 for condenser lenses
NormalizeAllLenses [#] Normalizes all lenses, or in a lens group, on an FEI scope.  With # 0 or not present, it normalizes all lenses in one call.  Otherwise, # can be the sum of 1 to normalize the illumination group (which includes condenser, minicondenser, and objective lenses) and 2 to normalize the projection group (which includes objective and projector lenses) in a separate call.
ReportColumnOrGunValve Reports 0 or 1 if column/gun valve is closed or open on FEG scopes, or if filament on JEOL is clearly off or on.  Reports -1 if the filament current is inconsistent with the beam switch state.
SetColumnOrGunValve # Closes column/gun valve on FEG scope or turn off filament on JEOL if # is 0; open valve or turn on filament if # is 1.
ReportFilamentCurrent Reports the filament current on a non-FEG JEOL scope.  The value is between 0 and 100 unless the property 'FilamentCurrentScale' is set with a scaling other than 100.
SetFilamentCurrent # Sets the filament current on a non-FEG JEOL to #, in the same units as  'ReportFilamentCurrent'.
ReportFEGEmissionState Reports whether the FEG emission is on (non-zero) or off (0), on JEOL's only.  Command added in 3.9, 5/10/21.
SetFEGEmissionState # Turns the FEG emission off (for a 0 value) or one (for a non-zero value), on JEOL's only.  This should be used only for a cold FEG.  Command added in 3.9, 5/10/21.
ScreenUp Raises the main screen
ScreenDown Lowers the main screen
ReportScreen Reports if screen is up or down; reportedValue1 is set to 0 or 1, respectively.
ReportScreenCurrent Reports the unsmoothed screen current in nA.
ReportLens name For a Hitachi or JEOL scope, reports the lens value by its abbreviated name.  For JEOL, allowed names are 'CL1', 'CL2', 'OM2', 'IL1', 'IL2', 'IL3', 'PL1', 'PL2', 'PL3', 'PL4', 'FLf', 'FLc', 'FLcomp1', 'FLcomp2'. Value cannot be assigned to a variable at end of command
ReportDeflector name For a Hitachi scope, reports the X and Y values of deflector specified by its abbreviated name.
SetFreeLensControl #L #S On a JEOL with scripting support for free lens control, turns free lens control for the lens given by #L off if #S is 0 and on otherwise.   Lens numbers are: 0: CL1,  2: CL3,  6: OL Coarse,  7: OL Fine,  8: OM,  I0: IL1,  11: IL2,  12: IL3, 13: IL4,  14: PL1,  15 or 16: PL2,  19: FL Coarse,  20: FL Fine,  21: FL Ratio
SetLensWithFLC #L #V [#R] Using free lens control, sets the lens given by #L (see SetFreeLensControl) to the value #V between 0 and 1 if the optional #R is 0 or absent, or changes it by #V if #R is non-zero.  This command probably turns on FLC for that lens.
ReportLensFLCStatus #L For the lens given by #L (see SetFreeLensControl), reports whether free lens control is on and the value for the lens.
RemoveAperture # Removes the aperture whose index is the given # (JEOL only).  If the property JeolHasExtraApertures is not set, 1 and 2 are the condenser and objective apertures, others are 3:HCA, 4:SAA, 5:ENTA, 6:EDS.  If that property is set (e.g., for CryoARM), indexes are 0:CL1, 1:CL2, 2:OL(OL Upper), 3:HC(OL Lower), 4:SA, 5:ENT, 6:HX, 7:BF, 8:AUX1, 9:AUX2, 10:AUX3, 11:AUX4.  The size and position of the aperture will be recorded before it is removed.
ReInsertAperture # Replaces the aperture whose index is the given # after it has been removed with 'RemoveAperture' (JEOL only).  The aperture of the stored size will be inserted and it will be set to the stored position.
PhasePlateToNextPos Moves phase plate to next position.  Works on JEOL and FEI scopes, but for FEI scopes it requires server version 6.13 and a license for advanced scripting.
ReportPhasePlatePos Reports the current phase plate position number, numbered from 1 (FEI scopes only)
ReportVacuumGauge name Reports the status and pressure reading from a vacuum gauge identified by the given name.  For FEI scopes, name is of the style accepted in the WatchGauge property; status values are 0 for undefined, 1 for underflow, 2 for overflow, 3 for invalid, and 4 for valid; pressure is in pascals.  For JEOL scopes, the command requires a relatively recent version of TemExt; names can be Pir0 to Pir9 or Pen0 to Pen9; status values are 0 for not ready, 1 for low, 2 for high, and 3 for ready; and pressure values are between 0 and 1 (the value returned by the scope is divided by 4095).
ReportHighVoltage Reports the current value of the high tension in kV.
ManualFilmExposure # Sets film exposure time in seconds for manual exposures; enter 0 for automatic exposure (the default)
ExposeFilm Takes a film exposure
SpecialExposeFilm #D [#P] [#N] Exposes film with special handling: #D specifies a delay in seconds after loading the plate; #P specifies a pre-exposure of the specimen before exposing the plate, in seconds. #N suppresses dimming of the screen if it is nonzero. This command command does not raise the screen if it is down. It requires the adaexp server to be installed.
SetupScopeMessage #B [#T] [text] Sets properties for a message box to be shown on an FEI microscope computer with the next command.  #B specifies the type of buttons: 0 for OK, 1 for OK - Cancel, 2 for Yes - No, 3 for Yes - No - Cancel.  The optional #T sets the time interval between message box displays, or 0 to display it unconditionally or -1 just to set the time of display to the current time.  The optional rest of the line (text) specifies the text inside the message.  If you just want to specify an interval, enter ' 0 interval'; if you just want to specify text for a box to be displayed unconditionally, enter '0 0 text'.
ShowMessageOnScope title Opens a message box on an FEI microscope computer with the given title, which can include spaces.  The box is displayed with the "long operation" mechanism described below, so it is possible to have it displayed only after an interval has elapsed.  If SetupScopeMessage was not used, the default is for a box with an OK button, opened unconditionally, with the text "SerialEM message".  When the command is finished, reportedValue1 is set with 1 if the box was displayed or 0 if it was not, and reportedValue2 is set with the reply from the box: 2 for Yes or OK, 1 for No, 0 for Cancel, or -1 for an error.
ReportXLensDeflector #D Reports the X and Y values of a deflector associated with the X lens, where #D should be 1 for shift, 2 for tilt, 3 for stigmators.  To use X lens commands, the adatl module must be registered and the environment variable SEM_USE_ADATL must be set to any value on the microscope, and XL mode must be turned on in the microscope interface.
SetXLensDeflector #D #X #Y Sets the X and Y values of an X lens deflector, where #D is 1 for shift, 2 for tilt, 3 for stigmator.
ReportXLensFocus Reports the focus setting of the X lens.
SetXLensFocus # Sets the focus setting of the X lens.
Energy Filter Commands
SetSlitWidth # Sets energy filter slit width in eV
SetSlitIn [#] Inserts the slit; or if # is entered, inserts if 1 or retracts if 0
SetEnergyLoss # Sets the energy loss to the #
ChangeEnergyLoss # Changes the energy loss by the #
ReportEnergyFilter Reports the slit width, energy loss, and whether the slit is in or out (the latter is placed in reportedValue3 as a 1 or 0)
SetJeolGIF # Calls JEOL function to set GIF mode on (if # is nonzero) or off.
ReportJeolGIF Calls JEOL function to get whether GIF mode is on.
Autoloader, Refrigerant, and Vacuum Commands
LoadCartridge # Loads the cartridge from the given slot # (numbered from 1) if there is an FEI autoloader. This command starts a long operation.
UnloadCartridge If there is an FEI autoloader, unloads the cartridge. This command starts a long operation
ReportSlotStatus # Reports the status of the cartridge slot given by # (numbered from 1) if there is an FEI autoloader.  Status is -1 for an error, 0 for empty, and 1 for occupied.
AreDewarsFilling Reports whether any of the dewars in a temperature control system on an FEI scope are busy filling, or whether a SimpleOrigin system is busy filling (reportedValue1 is set to 0 or 1).   Also reports if tanks are being refilled on a JEOL if the interface exists for determining that (reportedValue1 is set to 1 for stage tank plus 2 for transfer tank).  Value can be assigned to a variable at end of command.
DewarsRemainingTime Reports the time remaining until next automatic dewar filling on an FEI scope or -1 if none is scheduled.  Alternatively, with a SimpleOrigin filling system, reports the seconds left until the next filling or -1 if there are no remaining refills.  Value can be assigned to a variable at end of command.
RefrigerantLevel # Reports the refrigerant level of the dewar given by # on an FEI scope: 1 for autoloader, 2 for column, 3 for liquid helium.   Value can be assigned to a variable at end of command.
SimpleOriginStatus Reports the number of remaining refills, the minutes until the next refill (or a negative value if there are no refills left) and whether filling is underway for a SimpleOrigin system.  Values can be assigned to variables at end of command.  Command added in 3.9, 6/16/21.
IsPVPRunning Reports whether the PVP is running on an FEI scope.  Value can be assigned to a variable at end of command.
IsFEGFlashingAdvised # Reports whether flashing of a cold FEG is advisable on an FEI scope, where # should be 0 for a low-temperature flash and non-zero for a high-temperature flash.  Value can be assigned to a variable at end of command  Command added in 3.9, 6/12/21.
NextFEGFlashHighTemp [#] Sets the next FEG flashing done with 'LongOperation FF' on an FEI scope to be high-temperature, unless the option # is 0.  A call for a high-temperature flash will fail unless it is advisable, so test with' IsFEGFlashingAdvised 1' first.  Command added in 3.9, 6/12/21.
LongOperation op # [op #...] Starts one or more time-consuming operations: op can be Buffer cycle ('Bu'), Refill refrigerant on FEI ('Re'), Inventory cassettes ('In'), Loader buffer cycle ('Lo'), Unload cartridge ('Un'), Dark reference update for K2 (or K3 with GMS 3.31+) ('Da'), Refill Stage tank ('RS') or Refill Transfer tank ('RT') on JEOL, or Flash FEG ('FF') on JEOL or FEI.  Operations are identified by the first two letters of whatever full word you use (case insensitive).  Each operation except Inventory and Unload cartridge must be followed by an interval in hours (#).  If # is > 0, the operation is done only if the time since the last such operation is greater than #; if # is 0, the operation is done unconditionally; if # is -1, it simply records the current time as the time of the last operation; if # is < -1, it reports the time in hours since the last operation and places it into one of the reportedValue variables.   The scope operations will occur sequentially and be started in  the order that they are listed. The dark reference update will be done simultaneously with scope operations.  If an error occurs in a scope operation, other operations will be finished and the error reported at the end.  Errors other than in refilling refrigerant will cause the script to stop.  The user interface should not hang during long operations, and users will be asked to confirm that they want to kill the operation threads if they press STOP or try to exit the program.  The consequences of killing these threads are uncertain.  If a tank refilling on a JEOL is included in the operations, a STOP will just stop all filling.  In order for time intervals to be kept track of between runs of the program, the property IgnoreShortTermCals must not be set.
Piezo Drive Commands
SelectPiezo #U #Z Selects a piezo drive for reports or movements, follow with the plugin number #U (numbered from 0, enter 0 if there is only one plugin controlling piezos) and the piezo number #Z (numbered from 0).
ReportPiezoXY Reports the X and Y position of the currently selected piezo, if there is a piezo plugin loaded, or of the piezos on a JEOL stage if not.
ReportPiezoZ Reports the Z position, or the position of the only axis for a single-axis piezo, of the currently selected piezo
MovePiezoXY #X #Y [#R] Sets the X and Y position to #X, #Y for the currently selected piezo, if a piezo plugin is loaded, or for the piezos on a JEOL stage if not. If #R is non-zero, moves the piezo by #X, #Y.
MovePiezoZ #Z [#R] Sets the Z position, or position of a single-axis piezo, to #Z for the currently selected piezo, or if #R is non-zero, moves the piezo by #Z

Higher Level Operations and Tasks

Autoalign-Related Commands
A or Autoalign Aligns buffer A to autoalign buffer.  The script is suspended if there is an error such as memory allocation or mismatched binnings, but if a maximum shift limit has been set with 'LimitNextAutoAlign' and there are no eligible peaks with that distance, it will set reportedValue1 to -1 instead of 0 rather than stopping the script.
AlignTo buf [#N] [#T] Aligns buffer A to given buffer buf (e.g. B or 2). Optionally, enter 1 for #N to avoid changing microscope image shift, and 1 for #T to prevent trimming of dark borders.  Behaves like 'Autoalign' on errors.
ClearAlignment [#N] Clears the alignment shift of the image in buffer A.  Optionally, enter 1 for #N to avoid changing microscope image shift.
LimitNextAutoAlign # Sets a limit in microns to the amount of shift allowed in the next autoalign. If there are no correlation peaks within that limit, no shift will be imposed.
AlignWithRotation buf #C #R Finds the best alignment between buffer A and buffer buf including a rotation; #C sets the center angle for the rotation search and #R sets the total angular range of the search.  reportedValue1-3 are set with the rotation angle and the X and Y shift (after rotation), in the binned pixels of the image.  Values can be assigned to variables after command.
ConicalAlignTo buf #R [#S] Aligns buffer A to the given buffer buf assuming a specimen rotation given by #R. Optionally, enter 1 for #S to show the cross-correlation.   Behaves like 'Autoalign' on errors.
ReportAlignTrimming Reports the sum of left and right borders and the sum of top and bottom borders in the last autoalign for the image in A and for the reference image.  The numbers are in pixels of the respective images before the additional binning applied for correlation, and will thus differ from the binned values reported by the autoalign routine.
ReportAlignShift Reports the X and Y alignment shift of the current image in A in unbinned pixels on image, in nanometers along the image shift axes, and in nanometers on the specimen, where the tilt axis is along X.
ReportISforBufferShift Reports the image shift that corresponds to the shift stored and displayed for the current image in A, in image shift units.  These values are the same as the ones that would be imposed on the scope typically when introducing such a shift, such as by autoaligning or dragging the image with the right mouse.
ReportShiftDiffFrom # Reports the difference between the alignment shift of the current image and the given value # in microns, as percentage of the value; the cumulative sum of differences in microns, and the total sum of shifts in microns. For monitoring variability in successive stage movements.
ReportAccumShift Reports sum of shifts given by ReportAlignShift or ReportShiftDiffFrom
ResetAccumShift Resets the sum of shifts given by ReportAlignShift or ReportShiftDiffFrom to 0
Autofocus/Autotuning-Related Commands
G or Autofocus [#M] [#A] Runs the Autofocus routine; set #M to -2 to measure shift and drift, -1 to just measure defocus without changing, or 1 for normal autofocus that changes focus to target; set optional #A to 1 or 2 to focus with the View area in Low Dose mode, 3 or 4 to focus with the Search area, or -1 to focus with the Record area. With  '-1 1' or '-1 3', the measured defocus is that of the View or Search area, i.e., not adjusted for View or Search defocus offset; with '-1 2' or '-1 4' the measured defocus is adjusted for the offset to give an estimate of defocus in the Record area.
IncTargetDefocus # Changes the defocus target by #
SetTargetDefocus # Sets the defocus target to #
ReportAutofocusOffset Reports the current value of the defocus offset used for autofocusing
SetAutofocusOffset # Sets the defocus offset for autofocusing to the given #.  The first time it is set, the current value is saved, and it will be restored automatically when the script ends.
BeamTiltDirection # Sets beam tilt direction for autofocusing to # (a value from 0 to 3)
OppositeAutofocus [#] In low dose mode, runs autofocus in area on opposite side of Record from the defined Focus area; if optional # is -1, just measure defocus without changing.  Not available if 'Balance Shifts' is on.
FocusChangeLimits # # Sets limits on the focus change during autofocus runs for the remainder of the script; follow with a negative and a positive number for the limits in microns.  When an autofocus run exceeds a limit, it will abort and return to the starting defocus.  Enter with '0 0' to cancel these limits.
AbsoluteFocusLimits # # Sets limits on the absolute focus reached during autofocus runs.  Follow with a lower and a upper limit as given by ReportAbsoluteFocus, or '0 0' to cancel these limits.  Autofocus will abort when a limit is exceeded.  These values will override the absolute limits that can be specified through the Focus menu, but a '0 0' will not prevent those limits from being applied.
ReportFocusDrift Reports the drift estimate from the last autofocus, if available
ReportAutofocus Reports measured defocus from last autofocus, or whether it failed.  The defocus is placed into reportedValue1 and a failure code in reportedValue2 (1 for inconsistent focus, 2 for absolute limits exceeded, 3 for focus change limits exceeded, or -1 for other error).
ReportTargetDefocus Reports the defocus target
FixAstigmatismByCTF [#M] [#L]  [#S] Measures astigmatism by CTF fitting, outputs the stigmation change to the log, and corrects for those values (or just measures, if the optional #M is nonzero).  Image shift is set to 0 unless the optional #L is non-zero.  Set optional #S non-zero to suppress the message box on errors that occur after starting to take images.
FixComaByCtf  [#M] [#L] [#F]  [#S] Measures beam-tilt misalignment by CTF fitting, outputs beam tilt change needed to the log, and corrects for it (or just measures, if the optional #M is nonzero).  Image shift is set to 0 unless the optional #L is non-zero.  The user setting for whether to do a full array of images is used unless optional #F is 0 for 5 images or > 0 for a full array. Set optional #S non-zero to suppress the message box on errors that occur after starting to take images.
CorrectAstigmatism [#] Measures astigmatism by beam-tilt-induced displacements (BTID), outputs the stigmator values to the log, and corrects for those values (or do not correct, if the optional # is -1)
CorrectComa [#] Measures beam-tilt misalignment by beam-tilt-induced displacements (BTID), outputs the estimated beam tilt to the log, and corrects to bring beam tilt to zero. If the optional # is -1, it will simply measure the misalignment once and report it without correcting it.  If the # is 1, it will do another iteration of estimating beam tilt and average the result with the previous iterations.
ReportStigmatorNeeded Reports the needed stigmator change in X and Y that was measured only, but not imposed, after running 'FixAstigmatismByCTF 1' or 'CorrectAstigmatism 1'.  The last run of either astigmatism routine must be by one of these commands; otherwise it will return 0 and 0.
ReportComaTiltNeeded Reports the needed change in X and Y beam tilt that was measured only, but not imposed, after running 'FixComaByCTF 1'.  If the last run of the coma routine applied rather than just measured the tilt, it will return 0 and 0.
ZemlinTableau #T [#S] [#C] Makes an array of 8 FFTs of beam-tilted images around a central FFT without beam tilt.  The first value #T specifies the beam tilt to use, in milliradians on an FEI scope or percent of full scale on other scopes.  The optional entry #S sets the cropped size of each FFT in the array (default 340) and #C sets the number of pixels to crop (default 170).  See Beam-Tilted FFT Array for other details.
ReportComaVsISmatrix Reports the matrix computed from the Coma vs. Image Shift calibration.  The 4 values are xpx, xpy, ypx, and ypy, where the change in beam tilt for a given image shift (in IS units) is given by
  BTx = ISx * xpx + ISy * xpy
  BTy = ISx * ypx + ISy * ypy
AdjustBeamTiltforIS  Adjusts beam tilt to compensate for the current image shift (as displayed in the Scope Status panel), provided that the Coma vs. Image Shift calibration has been done.  This command saves the current beam tilt, if it has not been saved before in the script, and it will be automatically restored when the script exits.  Astigmatism will also be adjusted if that calibration includes an astigmatism estimate, unless the property 'SkipAstigAdjustmentForIS' is set.
CBAstigComa #T #C #A [#L] [#S] FOR TESTING: Runs the routine for astigmatism and coma by CTF fitting.  Set #T 0 for astigmatism, 1 for coma with 5 images, 2 for coma with full array; #C 0/1 to measure/calibrate; #A 0 to apply a measurement, 1 to just measure, 2 to measure from images in the buffers; #L non-zero to leave image shift as it is; #S non-zero to suppress the message box on errors that occur after starting to take images.
Low Dose Commands
GoToLowDoseArea area Switches to the low dose area given by area, which must be one of V, F, T, R, or S. This will not work if the screen is down.
SetLowDoseMode # Turns low dose mode on for # nonzero or off for # 0; the previous state of low dose is saved in reportedValue1 as a 0 or 1.  This value can be assigned to a variable at the end of the command.
ReportLowDose Reports whether low dose is on or not and the current area, if it is defined.  The number of the area (0 for V, etc.) is placed in reportedValue2.
UpdateLowDoseParams area [#K] Activates continuous update of the area given by area; whenever necessary to reflect changes made by the script to any of the parameters that are recorded when 'Continuous update' is on the Low Dose panel.  Specifically, the area is updated to the current parameters if it is the current area when this command is given (thus recording changes made before this entry), and also updated thereafter whenever one of the commands are used to change a relevant parameter.  Set the optional #K non-zero to keep the parameter changes when the script ends; otherwise the parameters saved when this command is first given will be restored on script end.  A must be one of V, F, T, R, or S.
SetLDAddedBeamButton [#] Turns the 'Set' button in the Low Dose panel for recording additional beam shift on, or turns it off if the optional # is 0.  The original state of the button will be restored on script end.
RestoreLowDoseParams [area] Restores parameters saved for the given area when 'UpdateLowDoseParams' was entered for this area.  Omit area to restore parameters for all areas, including ones marked to be kept when the script ends.
SetLDContinuousUpdate # Turns "Continuous update" in the Low Dose panel on if # is non-zero or off if # is 0.  Continuous update is not active while any script is running.  If it is on, microscope parameter changes will have no effect on Low Dose settings during a script, but when the script ends, changes will update the current Low Dose area.
ReportAxisPosition area Reports the axis position in microns and the rotation of the inter-area axis, for the given area: F (Focus) or T (Trial). The offset from center of the camera acquisition subarea is also reported in unbinned pixels (in left-handed camera coordinates).
SetAxisPosition area #D [#R] Modifies the axis position, and optionally the rotation of the inter-area axis, for the Focus and/or Trial area.  Follow with 'F' or 'T' to specify the area (both will be changed if Focus and Trial settings are being kept identical); with #D, the distance in microns; and optionally with #R, a rotation angle.  If an angle is set, the option to apply the angle will be turned on in the Low Dose control panel.  Low dose mode must be on to use this command.
CurrentSettingsToLDArea area Sets the parameters for low dose area given by area, which must be one of V, F, T, R, or S, from the current microscope settings.  It must be run while not in low dose mode and after adjusting to scope state to the desired settings for the area.  It clears out the parameters for the area, enters low dose mode, and goes to the area so that it is assigned the current state.
Task-Related Commands
ResetImageShift [#B] [#R] Resets image shift and move stage to compensate.  Follow with a 1 or 2 for the optional #B to move the stage so as to retain or impose backlash, even if the user has not selected the option to do so in the Image Alignment & Focus control panel.  With a value of 2, it will relax from the stage movement by the amount given in the optional #R, or by the value of the StageRelaxation property (0.025 by default).
ResetShiftIfAbove # Resets image shift and realign image if image shift is greater than the given # in microns
Eucentricity [#] Refines eucentricity, or if optional # is entered, do rough eucentricity only (1), refine only (2), both steps (3), or refine and realign (6)
ReportLastAxisOffset Reports the total lateral offset of the tilt axis estimated from the last Refine Eucentricity run; aborts the script if no offset is available.
SetTiltAxisOffset # Sets the lateral offset of the tilt axis to #.  Command added in 3.9, 11/10/20.
WalkUpTo # Tilts up to given angle in steps and track image position
ReverseTilt [#] Works out backlash and realign image after reversing tilt direction; enter optional 1 or -1 to specify a specific direction for further tilts
RefineZLP [#] Reports time of day and run Refine Zero Loss Peak procedure.  If the optional # is entered with an interval in minutes, the procedure is not run if the time since the last run is less than that interval.
AutocenterBeam [#] Starts the Beam Autocenter routine.  The optional # sets a maximum beam shift in microns; the beam will not be moved if the shift determined from the circle fit to the beam edges exceeds this value.
CookSpecimen Runs the Specimen Cooker routine
WaitForDose #D [#R] Starts accumulating dose and wait until it reaches the given #D in electrons per square Angstrom. Enter the optional #R to set how many times it reports progress while waiting (default is 10). Be sure that the screen is down and, if in low dose, that the beam is unblanked.
CenterBeamFromImage [#C] [#M] Centers beam using the existing image in the active buffer by detecting the edges of the beam, or from the centroid of the image intensities if #C is nonzero. In the latter case the beam should be completely within the camera field.  The optional #M sets a maximum beam shift in microns; the beam will not be moved if the shift determined from the circle fit to the beam edges exceeds this value.  Sets reportedValue1 to -1 if no beam edges are detected, 5 if there is a failure fitting edges to a circle, 6 if beam was not moved because the radius was too high, and 7 if the beam was not moved because the fitting error was too high.
MeasureBeamSize [buf] Measures the beam diameter by detecting its edges in the image in buffer A, or in the buffer given by the optional buf.  The value is reported in microns.
BacklashAdjust Runs the routine to adjust for backlash by taking an image, applying the current montaging backlash, and aligning a new image to the original image.
DriftWaitTask [#R] [unit] [#M] [#I] [#G] [type] [#C] [#E] [#B] Runs the Wait for Drift task using parameters set in the Wait for Drift Setup dialog if there are no optional entries.  Any optional entry that is not zero overrides the parameter set in the dialog; enter a 0 to use the dialog setting for any parameter.  The parameters are: #R for target drift rate; unit 'nm' or 'A'; #M for maximum time to wait in sec; #I for interval over which drift is measured in sec; #G 1 to generate an error when maximum time reached or -1 not to; type for type of measurement (T for Trial, F for Focus, A for within autofocus runs, or 0 for dialog setting); #C to correct drift with image shift; #E for Trial exposure, #B for Trial binning.
GetWaitTaskDrift Places the final drift measurement from the last Wait for Drift task into reportedValue1 and a non-zero number if the task failed in reportedValue2. Values can be assigned to variables after command.
ConditionPhasePlate [#] Runs the routine to condition a phase plate using parameters set in the Phase Plate Conditioning Setup dialog.   If the optional # is non-zero, it will move to the next phase plate position first, provided this is supported by scripting on the microscope.
MultipleRecords [#N] [#C] [#O] [#D] [#S] [#E] [#F] [#B] [#H] [#R2] [#N2] [#O2] Acquires multiple Record images around the periphery of a hole and/or in multiple holes, using image shift to move to each off-center position.  The parameters set in the Multiple Record Setup dialog control the operation of this task, but any subset of them can be overridden by entering optional parameters here.  The value in the dialog is used if -9 is entered for the corresponding parameter here, or if the optional entries end before the given parameter.  The parameters are:
1) #N for number of shots around the center
2) #C -1 or 1 for a shot in the center before or after the off-center shots
3) #O for the distance from center of the off-center shots, in microns
4) #D for the extra delay after the image shift, in seconds
5) #S 1 to save a Record image at each position or 0 not to
6) #E 1 or 2 to use early return for a K2/K3 camera after the last shot or after all shots
7) #F for the number of frames in the early returned image (or -1 for all, 0 for none)
8) #B 1 to adjust beam tilt to compensate for image shift or 0 not to
9) #H the sum of 1 to do shots around a center (within a hole) and 2 to do shots in multiple holes or specified positions.  (In addition, the sum in #H can include 4 for testing image locations or 8 for testing the coma correction.)
10) #R2 greater than 0 to do a second ring of positions
11) #N2 with the number of positions in the second ring
12) #O2 for the distance from center of the second ring
For example, 'MultipleRecords -9 -9 -9 4. 1' will use an extra delay of 4 seconds and save Records, but take all other parameters from the dialog.  When the operation starts successfully, ReportedValue1 is set to the total number of Record images to be taken.
TestNextMultiShot # Sets a variable so that the next MultipleRecords command will test image location by acquiring a Record or montage at each location (if # is 1) or by measuring coma at each location (if # is 2).  See Testing Image Location and Coma Adjustment for details on this testing.
StageToLastMultiHole Moves the stage to the center of the last hole position acquired with MultipleRecords.  This command can be used to position over a hole for occasional post-acquisition tasks when using a hole pattern centered on the support film.  There is no backlash correction.
ImageShiftToLastMultiHole Changes image shift by the offset to the last hole position acquired with MultipleRecords.  This command combined with 'ResetImageShift' will be more accurate than 'StageToLastMultiHole' if backlash correction is needed and enabled in the Image Alignment & Focus control panel.
RotateMultiShotPattern #A [#C] Rotates the hole positions in the pattern set up in the Multiple Record Setup dialog by angle #A.  Set optional #C non-zero to rotate the custom pattern instead of the regular one.  Generates an error if the selected pattern is not defined or the needed transformation is not available.
CalibrateImageShift [#] Calibrates image shift at the current mag. Do the calibration from scratch if the optional # is nonzero.
ShiftCalSkipLensNorm [#] Keeps projector lens normalization from being done before the next image or stage shift calibration provided that normalization was last done at the current magnification.  Set the optional # to 0 to NOT skip normalization.
FindPixelSize Runs the routine to find the pixel size in an image of a cross-line grating.
QuickFlyback set #E Runs the camera timing calibration routine in quick flyback mode for an FEI STEM camera, where 'set' specifies the camera parameter set and must be V, F, T, R, or P, and #E is the exposure time to use.  The routine will not ask for confirmation before saving the resulting flyback time and startup delay in the master list of flyback times.
ShiftImageForDrift #X #Y #U Applys image shift during the next exposure to compensate for a drift in X and Y given by #X and #Y; #U should be 0 if the drift is in unbinned pixels/sec and 1 if it is in nm/sec

Navigator

Navigator Window and List Commands
ReportIfNavOpen Reports whether the Navigator is open; sets reportedValue1 to 1 if it is open and 2 if there is a Navigator file defined 2.  Virtually all of the commands described in this section will generate an error if the Navigator is not open.
OpenNavigator [name] Opens the Navigator window, which must not already be open.  If the optional name is entered, this file is set as the Navigator file to save to.   Command added in 3.9, 11/26/20.
CloseNavigator Closes the Navigator window, which must be open.  If there are unsaved changes and the Autosave Nav File option is not on, the user will be asked whether to save.   Command added in 3.9, 11/26/20.
SaveNavigator [name] If the optional name is not present, saves the Navigator data to the current file or opens a file chooser for saving if a file is not yet defined.  If a name is entered, it saves to this file instead.
ReadNavFile name Reads in the Navigator file with the given name, opening the Navigator if necessary.  If there are unsaved changes in the Navigator, the user is asked whether to save those first as usual.  A cancel from that, or an error opening, reading, or processing the file will generate an error message.
MergeNavFile name Merges the Navigator file with the given name into the current items in the Navigator, which must be open.  An error opening, reading, or processing the file will generate an error message.
ReportNavFile [#] Reports the name of current Navigator file or generates an error if the Navigator is not open with a file defined.  Sets the full name into reportedValue1; or if the optional # is entered with a 1, sets the root of the filename including the path in reportedValue1, the extension (including the dot) in reportedValue2, the path only in reportedValue3, and the rest of the rootname in reportedValue4.  No optional assignment to variable.
ReportNumTableItems Reports the number of items in the Navigator table.
NavIndexWithLabel text Reports the index in the Navigator table of the item whose label is the given text, or 0 if there is none.  Sets reportedValue1 with the index.  The string can contain spaces and the comparison is not case-sensitive.
NavIndexWithNote text Reports the Navigator index of the item whose note is the given text, otherwise just like ItemIndexWithLabel.
NavIndexItemDrawnOn # Reports the Navigator index of the map that the specified item was drawn on, or 0 if it was not drawn on a map.  For #, enter 0 for the current item or the item being acquired; an index greater than 0 for the item with that index in the table; or a value less than 0 to count back from the end of the table, where -1 is the last item.
SetNavRegistration # Sets the current registration of the Navigator window to the given number.  No item registration values are changed.
Item and Group Commands
MoveToNavItem [#] Moves the stage to a Navigator item; if no # is entered, move to the current Navigator item or to the item that this script is being run on, otherwise move to the item whose index in the table is # (numbered from 1)
UpdateItemZ Assigns current stage Z value to the current Navigator item, or item that this script is being run on.
UpdateGroupZ [#] Assigns current stage Z value to the whole group of either the current Navigator item, the item that this script is being run on, or the next item to be acquired if the optional [#] is non-zero.  The item must have a non-zero group ID.  Acquisition must be running to assign to the next group.  If the group would show up on more than one line with 'Collapse groups' on, items on all lines will be updated, unlike with the 'Update Z' button.
LoadNavMap [buf] Loads the current Navigator item, or the item this script is being run on, if it is a map.  If the optional buf is entered, loads to that buffer instead of the read buffer.
LoadOtherMap # [buf] Loads the Navigator item whose index in the table is #, if it is a map; or if # is negative, loads the item that many items from the end of the table, i.e., -1 loads on the last item.  If the optional buf is entered, loads to that buffer instead of the read buffer.
ReportNavItem Reports the index, stage X, Y, Z, label, and note string for the current Navigator item, or the item this script is being run on. The index and stage coordinates are placed in reportedValue variables as usual, and the item type is placed in reportedValue5; (0 for point, 1 for polygon, 2 for map). In addition, these named variables are set:
  navLabel and navNote are set with the label and note strings,
  navIndex and navIntLabel are set with integer values of the item index (numbered from 1) and of the label (up to any non-numeric characters),
  navRegis is set with the item's registration value,
  navColor is set with the item's color (a value from 0 to 5),
  navNumHoles is set with the number of holes that would be acquired by 'MultipleRecords' with current parameters, or 0 if the item is not marked for Acquire.
  navAcqIndex is set with the number of items already acquired plus 1 If the Navigator is currently acquiring at items.  Any of these variables can then be used to make filenames, and the latter three can be used in arithmetic and IF statements.
ReportOtherItem # Reports similarly on the Navigator item whose index in the table is #, numbered from 1; or if # is negative, reports on item that many items from the end of the table, i.e., -1 reports on the last item.
ReportNextNavAcqItem Reports similarly on the next Navigator item to be acquired.  The Navigator must be acquiring.  If the last item is being acquired, navIndex is set to -1, and reportedValue1 and 2 are set to -1 and 0.
ReportGroupStatus For the current Navigator item or the item this script is being run on, reports a code for whether the item is first to be acquired in a group: -1 if Navigator not acquiring, 0 if not in a group, 1 if first to be acquired in a group, 2 if later in the group. If the group would show up on more than one line with 'Collapse groups' on, a value of 1 is returned for the first item to be acquired in each subgroup.  It also reports the group ID of the item  (ID is 0 for an item not in a group), the total number in the group, and the number in the group still marked for acquisition.
ReportItemImageCoords [#I] [buf] Reports the pixel coordinates of navigator item #I on the image in buffer buf. If no #I is specified, the current item is used, negative numbers are items counted from the end of the list. If no buffer buf is specified, the image in buffer A is used. The X and Y coordinates are returned in reportedValue1 and 2, reportedValue3 is set to 0 if item #I is outside the buffer or to -1 if the transformation can not be completed.
ChangeItemRegistration #I #R Changes the registration number of the Navigator item with table index #I to #R.  This works just like the Navigator menu entry Change Registration: the registration number must be in the legal range, the item cannot be a registration point, and you cannot change an item between imported and regular registrations.
ChangeItemColor #I #C Changes the color index of the Navigator item with table index #I to #C, which must be between 0 and 5. (0 = red; 1 = green; 2 = blue; 3 = yellow; 4 = magenta; 5 = no realign)
ChangeItemDraw #I [#D] Changes if the Navigator item with table index #I is drawn or not. If no #D is specified, the option is toggled, if #D is 0, drawing is disabled, any other numeric values for #D enable drawing. Command added in 3.9, 7/8/21.
ChangeItemLabel #I text Changes the label of the Navigator item with table index #I to the given text.  The text is limited to 16 characters; items with labels longer than 10 characters will not display their properties in the right columns in the table.
ChangeItemNote #I [text] Changes the note of the Navigator item with table index #I to the given text or deletes the note if text is not specified.
SetMapAcquireState # Sets the state with which the specified map item was acquired.  For #, enter 0 for the current item or the item being acquired; an index greater than 0 for the item with that index in the table; or a value less than 0 to count back from the end of the table, where -1 is the last item.
RestoreState Restores the state if one has been saved with either with 'SetMapAcquireState' or the Imaging States dialog.
SkipPiecesOutsideItem #I Sets the current montage to skip pieces outside the Navigator item whose position in the table is #I (numbered from 1). If #I is 0, uses the current item. If #I is < 0, disables the skipping of pieces.
NavItemFileToOpen # Reports the name of the file set to be opened for the specified Navigator item.  Sets reportedValue1 to the filename or to 0 if there is none.  For #, enter 0 for the current item; an index greater than 0 for the item with that index in the table; or a value less than 0 to count back from the end of the table, where -1 is the last item.  The command will not work for the item being acquired, as the stored name is cleared out when the file is opened.
ItemForSuperCoord # Sets the item number that Navigator supplies supermontage coordinates from when a montage image is acquired. Sets the number to 0 to restore Navigator to using coordinates from the item currently being acquired.
SetItemTargetDefocus #I #D Sets the target defocus to #D for the Navigator item specified by #I (positive for table index, 0 for current or acquired item, or negative for index from end).  The item must be marked for acquisition or a tilt series.  The target is not restored after acquisition, so the target would then apply for the next single image acquisition but be superceded by the value in the parameters for the next tilt series.   If this command is used in a script run before the main action, the target will apply in a script or tilt series but not to an autofocus done by the Navigator before the main action.  Items with this value set will have a line including 'F targ' and the target in the listing produced by the Navigator menu item List Files/Series/States.   When TS Params is pressed for an item with this set, the target defocus that shows in setup dialog will be the one in the parameter set, which may apply to many tilt series, and not this set value.  The label after the target will be um* to indicate that it is being overridden.
SetItemSeriesAngles #I #S #E [#B] Sets the starting and ending tilt series angles to #S and #E and optionally sets the bidirectional starting angle to #B for the Navigator item specified by #I (positive for table index, 0 for current or acquired item, or negative for index from end).  The item must be marked for tilt series acquisition.  The command can be used in a script run before the tilt series.  In the listing produced by the Navigator menu item List Files/Series/States, the tilt series angles specified by this command will be shown, with a '*' to indicate the override.   When TS Params is pressed for an item with angles set, the angles that appear in setup dialog will be the ones in the parameter set, which may apply to many tilt series, and not these set values.  There will be a * after the text box to indicate that they are being overridden.  Command added in 3.9, 9/16/20
SetNavItemUserValue #I #V [text] Sets an arbitrary value for a Navigator item specified by #I (positive for table index, 0 for current or acquired item, or negative for index from end).  Up to 8 user values are currently allowed, with a number from 1 to 8 specified by #V (numbers do not have to be used sequentially).  The text on the rest of the line is assigned as the value after variable substitution but not arithmetic; text can be omitted to clear out a value.  Command added in 3.9, 9/16/20
ReportItemUserValue #I #V Reports an arbitrary value set for the Navigator item specified by #I (positive for table index, 0 for current or acquired item, or negative for index from end), or 'none' if no value is set.  Sets reportedValue1 with the text value.
Item Generating Commands
NewMap [#N text] Makes the current image or montage a new Navigator map.  If an optional #N is entered, text after that replaces, or is added to, the standard note for a map.  text replaces the standard note if #N is 0, is added before it if #N is < 0, or is added after it if #N > 0.  Places the index of the new map in reportedValue1.
MakeAnchorMap Calls the routine to make an anchor map and does the same tests and operations as when run from the button in the dialog, including saving the current image and making it a map if it is not already.
FindHoles [buf] Runs the Hole Finder routine on the image in the current buffer, or in the buffer optionally specified by buf, using all of the parameters set in the Hole Finder dialog.  That dialog need not be open, but the Navigator must be.
MakeNavPointsAtHoles [#A] [#L] [#U] [#S] [#B] Makes positions found by the Hole Finder into Navigator points, using the various thresholds for exclusion set in the Hole Finder dialog.  That dialog need not be open, but the Navigator must be.  Optionally, #A may be entered with 0 to 2 to specify the arrangement of points (0 for zigzag, 1 for away from focus, 2 for divided into groups, or -1 to use the layout set in the dialog); #L and #U may be entered to set alternative lower and/or upper mean thresholds for excluding points (enter -999999 for #L or #U to use the dialog setting); #S may be entered to set the SD cutoff (or -1 to use the dialog value); and #B may be entered to set the cutoff for the percentage of black pixels.
ClearHoleFinder Removes the display of points found by the Hole Finder and frees its memory.
CombineHolesToMulti #S Combines a set of Navigator points marked for acquisition into a subset suitable for acquisition of a rectangular array with 'MultipleRecords', using the parameters set in the Multiple Record Setup dialog. See the   Multiple Hole Combiner dialog for details and restrictions.  Neither of those two dialogs need to be open, but the Navigator must be.   Set #S to 0 to select points on the currently displayed image, 1 to select points within the current polygon, or 2 to select points in the same group as the current point.
UndoHoleCombining Removes the multi-shot acquisition points created by the last hole-combining operation (through script command or dialog) and restores the individual points to the Navigator table.  All of the multi-shot points must still exist.
Alignment and Shift Commands
RealignToNavItem #R [#C] [#S #N #Z] Realigns to the current Navigator item, or to the item that this script is being run on. For #R, enter 1 to restore the microscope state to the current state after the procedure, or 0 not to.  For optional #C, enter 1 to use continuous acquisition mode and end it at end of procedure, or 2 to leave it running if possible. The three optional entries #S, #N, #Z control the resetting of image shift at the end of the procedure when aligning a single map at one magnification.  It will reset image shift and move the stage to compensate, realigning with a new image up to #N times and if the starting shift is more than the criterion #S.  Enter 0 or 1 for #Z to end with nonzero or zero image shift, respectively, i.e. with the image realigned or with a final image shift reset and stage movement.  This procedure occurs only if realignment is to a single map.  All three values must be entered if any are, plus a value for #C.  An entry of 0 for #N and 1 for #Z will make it move the stage to the target position and skip the regular realignment there.
RealignToOtherItem #I #R [#C] [#S #N #Z] Realigns to the Navigator item whose index in the table is #I, numbered from 1. For #R, enter 1 to restore the microscope state to the current state after the procedure, or 0 not to.  For optional #C, enter 1 to use continuous acquisition mode and end it at end of procedure, or 2 to leave it running if possible.  Entries for #S, #N, and #Z control image shift reset when aligning to a single map, as decribed for 'RealignToNavItem'.
RealignToMapDrawnOn #I #R Centers on the specified item by first realigning to the map that the item was drawn on, then using image shift to center on the marked item.  The specified item must have been drawn on a higher-magnification map that can be aligned to in two rounds using some lower mignification map, such as an anchor map. For #I, enter 0 for the current item or the item being acquired; an index greater than 0 for the item with that index in the table; or a value less than 0 to count back from the end of the table, where -1 is the last item. For #R, enter 1 to restore the microscope state to the current state after the procedure, or 0 not to.
GetRealignToItemError Gets the total stage error in X and Y and the second move error in X and Y from the last Realign to Item and assigns them to reportedValue1-4 and to optional variables included after the command.
ForceCenterRealign Makes Realign to Item align to the map center instead of skipping the first round because it was aligned to recently.
ShiftItemsByAlignment Shifts items at the current registration by the alignment shift of the image in buffer A. If rerun on the same image, it applies the change in shift between the current and previous run.
ShiftItemsByCurrentDiff # Shifts items at the current registration by the difference between the current stage position and the recorded position of the current Navigator item or the item that this script is being run on.  The shift is done only if the difference is less than the # in microns.
ShiftItemsByMicrons #X #Y [#R] Shifts items at the current registration, or at the registration given by the optional #R, by the amount in microns in #X and #Y.  Each component of the shift must be less than 100 microns.
AlignAndTransformItems #C #R [#L] Performs the image alignment and Navigator item transformation that can be done interactively in the Align with Rotation dialog.  The same conditions apply here as in that dialog: there must be either a single-frame image in buffer A or a montage overview in buffer B at the current registration, and a map in the buffer for read-in images at a different registration.  #C sets the center angle of the rotational search, and #R sets the total angular range to be searched.  Set the optional #L to a limit for an acceptable rotation angle; above this, items will not be transformed.  After finding the alignment, items at the registration of the map will be transformed to the current registration.
Acquisition Control Commands
ReportNumNavAcquire Reports the number of Navigator items marked for Acquire and marked for Tilt Series as two values; returns each as -1 if Navigator is not open.
ReportNumHoleAcquire [#M] [#S] [#E] Reports the total number of hole positions that would be acquired at and the number of Navigator items moved to by acquiring with 'MultipleRecords', based on current Multiple Record parameters and the number of hole positions specified for individual items.  If the optional #M is set with a minimum number of holes, the totals will omit any items that have fewer than that number of hole position remaining after excluding some holes in the pattern.  If the optional #S and #E are set with starting and ending item numbers in the Navigator table (numbered from 1), totals will include only items within those limits.  Each value is returned as -1 if Navigator is not open.  Command added in 3.9, 2/14/21.
ReportItemAcquire [#] Reports the Acquire state of the Navigator item whose index in the table is #, numbered from 1; or if # is negative, reports on item that many items from the end of the table (i.e., -1 reports on the last item), or if 0 or no # is specified, reports on the current item.  No optional assignment to variable.
SetItemAcquire [#I] [#A] Enables or disables Acquire for a Navigator item: if #A is 0, Acquire is disabled, if this parameter is not specified or nonzero, Acquire becomes enabled.  The item index is specified by #I with a positive or negative number (as in ReportItemAcquire); if 0 or no #I is specified the current item is changed.  Acquire may not be turned for an item marked for a tilt series.  If this command is used from within a running acquisition, the item must not be within the range from the current acquisition point to the end of the range being acquired.  The end of the range is the original end of the Navigator table when acquisition was started, or the end of the subset if one is being acquired.
SkipAcquiringNavItem Tells the Navigator to skip the current item and move on to the next.  This command has an effect only when included in a script being run as a preliminary action before the main action.  The item will still be marked for Acquire.
SkipAcquiringGroup [#I] Tells the Navigator to skip points whose group ID match either the group ID of the current acquire item, or the optional #I entered with the command.  The items will still be marked for Acquire.  The Navigator must be acquiring at points.
SkipMoveInNavAcquire [#] Tells the Navigator to enable skipping the initial stage move for each following item to be acquired.  This command is allowed only when the Navigator is already acquiring at items.  It does not affect the user's selection in the Acquire at Items dialog for whether to skip this stage move.  Thus a script that is going to use Realign to Item on each point can skip the stage move and there is no need for the user to make this selection.
StartNavAcquireAtEnd Starts the Navigator Acquire at Items operation after the script ends successfully, using the parameters last defined in the Navigator Acquire dialog.  The command cannot be used when Navigator is already acquiring or a tilt series is running.
SuffixForExtraFile suffix [suffix] [suffix] [...] Sets one or more suffixes so that the Acquire at Items routine will open the corresponding number of extra files whenever it opens a regular file for output. Follow with the suffices, separated by spaces (and thus a suffix cannot contain a space). The name of each extra file will be the root of the regular filename, plus the suffix, followed by the extension of the regular filename.  The extra files will be opened before the regular file.  They will be closed when the regular file is closed (at the end of acquisition or before opening a new file).

Miscellaneous Commands

Time-Related Commands
ReportClock Reports seconds elapsed since last ResetClock command
ResetClock Resets the time reported by ReportClock to 0
ReportMinuteTime Reports an absolute time in minutes, a large integer. The difference between two such values will give an elapsed time in minutes.  If a variable name is included after the command, the value will automatically be assigned to a persistent variable so that it is available across multiple runs of the script.
SetCustomTime name [#M] Stores an absolute time in minutes in a 'custom time' with the given name.  The current time is stored, or the time given by the optional #M.  Custom times are stored in the short-term calibration file, like the times since the last long operations of various kinds.  They can be used to perform actions periodically during Navigator acquisitions.  Entries older than 20000 minutes will be removed when the file is read on program startup.
ReportCustomInterval name [#M] Reports the time elapsed, in minutes, from the custom time with the given name to either the current time or the absolute time in minutes given by optional #M.  If a time with that name has not be set, an interval of 40000 is returned.   No optional assignment to variable.
ReportTickTime Reports the time in seconds since the program started, like the times that prefix program debug output. The difference between two such values will give an elapsed time in seconds with nominal millisecond precision, as long as the program has been running for fewer than 50 days. If a variable name is included after the command, the value will automatically be assigned to a persistent variable so that it is available across multiple runs of the script.
ElapsedTickTime #S Reports the time in seconds since the tick time given in #S, which should be a variable assigned with the result from 'ReportTickTime'.  This command should be used to measure intervals between tick times if there is any chance that the program will run for more than 50 days.  The value can be assigned to a variable at the end of the command.
ReportDateTime Reports a numeric date in the form YYYYMMDD and a time to the minute in the form HHMM.
ProgramTimeStamps [#] Prints the program version and build date, plus the current date and time, or the date and time of program startup if the optional # is nonzero.
Scale Matrix Commands These commands output the 4 elements of the various scale matrices used to convert between 4 different kinds of positional coordinates:
  camera coordinates in right-handed unbinned pixels;
  'specimen' coordinates in microns, a right-handed rectilinear system with the X axis along the tilt axis;
  IS (image shift or projector shift) coordinates in their basic units;
  stage coordinates in microns.  They report 4 values that specify an amount of change in a coordinate being scaled to per unit of change in a coordinate being scaled from, namely X per X, X per Y, Y per X, and Y per Y in that order.  The coordinate transformation is
Xout = Xin * XperX + Yin * XperY
Yout = Xin * YperX + Yin * YperY
All commands return a matrix for the current camera where relevant, and all require an entry #M for the magnification index, or 0 to use the current index.  Variables to assign to can be entered after that.
ISToCameraMatrix #M Converts from image shift or projector shift to camera coordinates
CameraToISMatrix #M Converts from camera to image shift or projector shift coordinates
CameraToStageMatrix #M Converts from camera to stage coordinates
StageToCameraMatrix #M Converts from stage to camera coordinates.
ISToSpecimenMatrix #M Converts from image shift or projector shift to specimen coordinates.
SpecimenToISMatrix #M Converts from specimen to image shift or projector shift coordinates.
SpecimenToCameraMatrix #M Converts from specimen to camera  coordinates.
CameraToSpecimenMatrix #M Converts from camera to specimen  coordinates.
ISToStageMatrix #M Converts from image shift or projector shift to stage  coordinates.
StageToISMatrix #M Converts from stage  to image shift or projector shift coordinates.
SpecimenToStageMatrix #M Converts from specimen to stage coordinates.  The matrix should have two terms near 0 and two terms near +/-1.
StageToSpecimenMatrix #M Converts from stage to specimen coordinates.
Other Commands
CircleFromPoints #X1 #Y1 #X2 #Y2 #X3 #Y3 Reports the X and Y center coordinate and the radius in microns for the circle through three points whose coordinates are given on the line as #X1:#Y1 #X2:#Y2 #X3:#Y3.  Values can be assigned to variables at end of command.
SetCameraPLAOffset Sets or refines a PLA offset between two cameras on a JEOL scope using PLA for image shift.  To use:
Take an image with the camera to be aligned to (e.g., an on-axis camera).
Center a feature and take a new image.
Switch to the other camera (e.g., an off-axis camera).
Use right mouse-shifting, or set the marker point and use the To Marker button or Shift P hot key to center the feature with image shift only.
Run this command.  It will report the existing and new offsets.
Iterate if desired for a more accurate result.  If aligning more than two cameras, use one camera as a reference for aligning each of the others to.  Command added in 3.9, 12/23/20.
Plugin name func [args] Calls the function func in the plugin named name with appropriate list of arguments for that function.  Arguments (args) are entered as items separated by spaces, except that a string argument at the end may consist of multiple words.  The return value of the function is reported and placed into reportedValue1.
ListPluginCalls Lists the names of script-callable functions in all loaded plugins along with the arguments that they expect, in parentheses.  For each argument, there should be one item provided on the command line calling the function, with all items separated by spaces as usual.  Two exceptions to this are: a string argument at the end can include spaces; an argument listed as [out]double is a returned value, assigned to reportedValue2 or higher.
MailSubject text Sets subject line for an email message (default is 'Message from SerialEM script'). text can include variables to be substituted.
SendEmail text Sends an email containing the given text, which can include variables to be substituted. An SMTP server and address to send from must be defined in the properties file, and recipient(s) must be defined using 'Set Email Address' in the Tilt Series Menu.
ErrorBoxSendEmail text Sends an email containing the given text if the script stops with a message box; the text can have variables to be substituted.  Requirements are the same as for 'SendEmail'.  If the message box occurs during Navigator Acquire at Items and the user has selected to send emails there, two emails will be sent, thus allowing more specific information from the one specified here.
RunInShell command Runs the given command with the system command processor.  It appears that any command that will run in a Command Prompt window can be run.  Thus commands can include: '|' to pipe from one program to another; '&' to run successive programs unconditionally; '&&' or '||' to run successive programs conditionally; '> outfile' to redirect standard output to a file, '2> errfile' to redirect standard error output to a file, or '> outfile 2>&1' to redirect both to one file.  Single arguments like filenames that contain spaces should be enclosed in double quotes.  The exit status of the command will be placed in reportedValue1; if it is -1, this indicates an error in before running the command, and reportedValue2 will be set with the following values: 1 if argument list too big, 2 or 3 if command interpreter cannot be found or is not executable, 4 for insufficient memory or other memory problem, 5 for unidentified error.  In any case, a non-zero exit status will not be considered a script error, and you need to test for failure explicitly. These error codes are not very helpful - it seems that the exit status is 1 if the command cannot be found or cannot be started, so if you want to pass information back with the exit status, you cannot use a 1, and might want to use a value besides 1 for failure of the operation to distinguish it from failure to run the command.   If STOP is used while the command is running, the script will stop and the thread that is running the command will be killed, but the command will keep running.
CreateProcess command Starts the program given by command without waiting for it to finish, using the argument list defined previously with the 'NextProcessArgs' command.  See The Tools Menu and Running External Commands for a description of the rules governing this command.
NextProcessArgs arg [arg] [...] Sets arguments for the next process run with 'CreateProcess' or 'RunExternalTool'.  The argument list can contain script variables that are substituted, as well as several keywords that are replaced with path entries.  See The Tools Menu and Running External Commands for a description of these keywords and the rules governing the arguments entry. The arguments are used up by running the process and must be defined with this command each time a process is run.
RunExternalTool #N|name Runs an external tool shown in the Tools menu, where #N is either the number of the tool in the Tools menu, numbered from 1, or name is the full name of the tool in the menu. If arguments were set with 'NextProcessArgs', they will be included when running the command.
ExternalToolArgPlace # Specifies whether arguments set with 'NextProcessArgs' should be placed before (-1 for #) or after (1 for #) the arguments defined for an external tool in the properties file, or replace the defined arguments (0 for #).  The default is 0 and a setting is retained for the duration of the script.
ReportProperty name [var] Reports the value of one program property given by name.  The command can be used with nearly all of the general (non-camera-specific) properties that contain just a single numeric entry and can be set by name in SerialEMproperties.txt.  Follow with the full name of the property (case insensitive) and with an optional variable name var for the value. An error will result if the name does not match one of the properties that can be reported.  The list of available properties in the development version of SerialEM is in http://bio3d.colorado.edu/ftp/SerialEM/Scripts/ScriptableProperties.txt
SetProperty name value Sets the value of one program property.  This works just like 'ReportProperty'.  Follow with the full name of the property (case insensitive) and with its new value
ReportUserSetting name [var] Reports the value of one user setting, using the name for it in SerialEMsettings.txt.  The command can be used with nearly all of the general (non-camera-specific) settings that contain just a single numeric entry.  Follow with the full name of the setting (case insensitive) and with an optional variable name var for the value.  An error will result if the name does not match one of the settings that can be set.  The list of available settings in the development version of SerialEM is in http://bio3d.colorado.edu/ftp/SerialEM/Scripts/ScriptableSettings.txt
SetUserSetting name val [#K] Sets the value of one user setting.  This works just like 'ReportUserSetting'.  Follow with the name of the setting and its value val.  The original value is automatically restored when the script stops unless the optional entry #K is non-zero to keep the setting.  If the script is suspended, the new value will be set again when it is resumed.  Multiple changes in the same setting can be done; the original value or last kept new value will be restored when the script stops, and the latest new value will be set on resume.
ReportEnvironVar name Reports whether the environment variable given by name exists in reportedValue1 and its value in reportedValue2 if so or 'none' if not.  The name must be a single word without spaces.  Command added in 4.9, 1/8/21.
ReportSettingsFile Reports the name of the current settings file and the name of the current script package file, or "None" if scripts were loaded from settings.  Command added in 4.9, 1/8/21.
ListAllCalibrations Lists IS vectors, stage vectors, beam calibrations and focus and tuning calibrations just as could be done from the menus.  IS vectors are listed using calibrated pixel sizes.  Command added in 4.9, 1/8/21.

Commands Allowing Arithmetic Expressions for Arguments

In addition to the commands starting with 'Set', these commands allow arithmetic arguments:
AbsoluteFocusLimits
BackgroundTilt
BeamTiltDirection
ChangeEnergyLoss
ChangeFocus
ChangeIntensityBy
ChangeItemRegistration
ChangeMag
ChangeMagAndIntensity
CircleFromPoints
CropImage
CtfFind
Delay
EarlyReturnNextShot
EchoEval
EchoNoLineEnd
EchoReplaceLine
ElapsedTickTime
ExposeFilm
FocusChangeLimits
FrameThresholdNextShot
ImageShiftByMicrons
ImageShiftByPixels
ImageShiftByUnits
IncPercentC2
IncTargetDefocus
LongOperation
ManualFilmExposure
ModifyFrameTSShifts
MoveBeamByFieldFraction
MoveBeamByMicrons
MovePiezoXY
MovePiezoZ
MoveStage
MoveStageTo
MoveStageWithSpeed
MultipleRecords
PreCookMontage
QuickFlyback
RecordAndTiltTo
ReduceImage
RelaxStage
ResetShiftIfAbove
SetSlitIn
ShiftItemsByMicrons
SmoothFocusNextShot
SpecialExposeFilm
StageShiftByPixels
StepFocusNextShot
SubareaMean
TestRelaxingStage
TestSTEMshift
TiltBy
TiltDuringRecord
TiltTo
UpdateHWDarkRef
WaitForDose
WaitForMidnight
WalkUpTo
ZemlinTableau