Copyright: IDL Online Help 4.0.1 (c)1995 Research Systems,Inc


IDL Online Help Navigator

IDL User's Guide Table of Contents

Alphabetical List of Routines

List of Routines by Application

Language Features Quick Reference

Graphics Keywords and System Variables

IDL Graphics Devices

Release Notes

What's New in IDL version 4.0.1

What was New in IDL version 4.0

More IDL Resources

Notes for Macintosh

Notes for Unix and VMS

Notes for Windows


IDL User's Guide Table of Contents

Chapter 1.	IDL Overview

Chapter 2.	Running IDL

Chapter 3.	Constants and Variables

Chapter 4.	Expressions and Operators

Chapter 5.	Subscripts

Chapter 6.	Statements

Chapter 7.	Structures

Chapter 8.	Strings

Chapter 9.	Vector-Drawn Fonts

Chapter 10.	Defining Procedures and Functions

Chapter 11.	Programming Routines

Chapter 12.	Efficient Programming

Chapter 13.	Interactive Support

Chapter 14.	Plotting

Chapter 15.	Plotting Multi-Dimensional Arrays

Chapter 16.	Image Display Routines

Chapter 17.	Files and Input/Output

Chapter 18.	Operating System Access

Chapter 19.	Map Projections

Chapter 20.	IDL Mathematics

Chapter 21.	Widgets

Chapter 22.	Widget Builder

Chapter 23.	Scientific Data Formats

Chapter 24.	Remote Procedure Calls

Chapter 25.	Reporting Bugs


IDL Overview
1	IDL Overview

Chapter Overview

IDL is a complete computing environment for the interactive analysis and visualization of data. IDL integrates a powerful, array-oriented language with numerous mathematical analysis and graphical display techniques. Programming in IDL is a time-saving alternative to programming in FORTRAN or C—using IDL, tasks which require days or weeks of programming with traditional languages can be accomplished in hours. Users can explore data interactively using IDL commands and then create complete applications by writing IDL programs.

Advantages of IDL include:

•	IDL is a complete, structured language that can be used both interactively and to create sophisticated functions, procedures, and applications.

•	Operators and functions work on entire arrays (without using loops), simplifying interactive analysis and reducing programming time.

•	Immediate compilation and execution of IDL commands provides instant feedback and "hands-on" interaction.

•	Rapid 2D plotting, multi-dimensional plotting, volume visualization, image display, and animation allow you to observe the results of your computations immediately.

•	Many numerical and statistical analysis routines—including Numerical Recipes routines—are provided for analysis and simulation of data.

•	IDL's flexible input/output facilities allow you to read any type of custom data format. Support is also provided for common image standards (including BMP, GIF, JPEG, and XWD) and scientific data formats (CDF, HDF, and NetCDF).

•	IDL widgets can be used to quickly create multi-platform graphical user interfaces to your IDL programs.

•	IDL programs run the same across all supported platforms (Unix, VMS, Microsoft Windows, and Macintosh systems) with little or no modification. This application portability allows you to easily support a variety of computers.

•	Existing FORTRAN and C routines can be dynamically-linked into IDL to add specialized functionality. Alternatively, C and FORTRAN programs can call IDL routines as a subroutine library or display "engine".

Getting Started with IDL

If you are a new user of IDL, a good place to start your exploration of the program is the IDL Basics tutorial. It provides a broad overview of IDL's syntax and graphics features.

Contents of this Manual

This manual provides instructions for using IDL and explains the features of the language. The IDL Reference Guide documents IDL's functions, procedures, and device-specific abilities.

IDL Data Types

IDL supports byte, integer, longword integer, floating-point, double-precision, complex, double-precision-complex, and string data types. Structures that combine different data types can also be constructed. See "Constants and Variables" on page 3-1.

Operators, Functions, and Procedures

Whenever possible, operators and functions in IDL operate consistently over the full range of structures and types. Results of operators with operands of mixed structure and type are automatically converted to the type yielding the greatest precision with a structure consistent with the operands. IDL includes a full set of mathematical, relational, and boolean operators. See "Expressions and Operators" on page 4-1.

Array Operators

In addition to the conventional operators, array-oriented operators can be used to extract and insert subarrays and concatenate arrays. See "Subscripts" on page 5-1.

Statement Types and Syntax

The syntax of IDL is deliberately simple. The 12 types of IDL statements should be familiar to those with a knowledge of FORTRAN or C.

IDL provides most of the control structures associated with modern languages, notably: "IF ... THEN ... ELSE," "FOR ... DO," "WHILE," "REPEAT," and "CASE" statements. "BEGIN ... END" blocks allow compound statements. Procedures and functions allow users to create modularly structured programs.

Programs consisting of IDL statements can be written with the built-in editor or with any external text editor. The 12 statement types are listed in Table 1.1 (keywords are denoted by capital letters). See "Statements" on page 6-1.

variable = expression	Assigns the value of the expression to the variable.
IF expression THEN statementIF  expression THEN statement ELSE statement	Conditionally executes statements depending upon the value of the expression.
FOR  var = initial_expression, limit DO statementFOR var = initial_expression, limit, increment DO statement	Initializes the control variable to initial_expression, repeatedly executes the statement, and increments the control variable until it is larger than the limit expression.
WHILE expression DO statement	Repeatedly executes the statement while the value of the expression is true.
procedure_name, parameter_list	Calls a system or user-written procedure with the given parameters.
CASE expression OF expression: statement ... END	Selects one of many statements for execution depending upon the value of the expression.
GOTO, label	Transfers control to the statement with the designated label.
BEGIN statement, ..., statement END	A compound statement composed of one or more statements.
PRO  name, parameter_list	Begins the definition of a user-written procedure.
FUNCTION name, parameter_list	Begins the definition of a user-written function.
COMMON name, variable_list	Defines a group of variables to belong to a common block with global scope.
Table 1.1 IDL Statement Types and Syntax

Display of Data

Results can be plotted or displayed with a minimum of decision-making on the user's part. For example, the PLOT procedure produces an easily interpreted graph of data values versus point number, regardless of the mode or size of the data. Data are scaled, and axes are automatically labeled. More than one plot can be drawn on the same axes by using the OPLOT (overplot) procedure. One vector can be plotted against another vector by calling the plot procedure with two vector parameters—an X vector, and a Y vector.

IDL includes a vast array of data visualization tools. Multi-dimensional plotting, volume visualization, image display, mapping, and animation routines are all included.

See chapters 14, 15, 16, and 19.

Window-System Support

IDL supports the use of a window system when suitable hardware is present. IDL supports the X Windows, Microsoft Windows, and Macintosh window managers. Any combination of graphics, text, and images can be displayed in one or more windows. Windows are easily created, destroyed, displayed, and hidden with IDL. Colortables are easily set or modified. The position of the mouse cursor can also be tracked and set. See "IDL Graphics Devices" on page 3-1 of the IDL Reference Guide.

Hardcopy Graphics

In addition to on-screen displays, IDL's graphic output can be directed to a variety of hardcopy devices. PostScript and PCL output allows IDL graphics to be produced on many popular laser printers. IDL graphics can also be embedded in documents produced by systems that support the inclusion of encapsulated PostScript graphics. IDL also supports output to HP plotters and laser printers, Tektronix devices, and the Computer Graphics Metafile (CGM) format. See "IDL Graphics Devices" on page 3-1 of the IDL Reference Guide.

Input/Output

Most types of data, formatted (encoded as text) or unformatted (raw binary), can be read or written by IDL. In addition, IDL provides read and write routines for many popular image and scientific data formats. See "Files and Input/Output" on page 17-1. For information about IDL's scientific data formats see "Scientific Data Formats" on page 23-1.

Advanced Mathematics Capabilities

IDL includes an extensive set of advanced mathematics and statistics routines for performing matrix operations, correlation analysis, curve and surface fitting, gridding and interpolation, integration, solution of linear and non-linear systems, time-series analysis, and more. See "Mathematics" on page 20-1.

Graphical User Interface Tools

IDL widgets are simple graphical objects (such as sliders, buttons, and pulldown menus) that allow you to create complete graphical user interfaces. As with most other IDL code, widgets are portable across all IDL platforms. For example, an interface designed on a Macintosh will also work on X Windows and Microsoft Windows displays. Widgets can be grouped into sophisticated "compound widgets" that can be easily re-used. See "Widgets" on page 21-1.

IDL also includes the Widget Builder, an easy-to-use graphical interface design tool. See "Widget Builder" on page 22-1.

Integration with External Code

Existing C or FORTRAN code can be called from or linked into IDL. On Unix, Remote Procedure Calls (RPCs) can be used to make IDL communicate with other processes on the same machine or across a network. IDL can also be called like a subroutine library from other C, C++, or FORTRAN applications. The callable IDL kernel can be embedded in your applications, eliminating the need to write your own complex mathematics and visualization routines. See "Operating System Access" on page 18-1. For information about RPCs, see "Remote Procedure Calls" on page 24-1. For information about callable IDL, refer to the online help.


Topics in IDL Overview Chapter
IDL Overview

This chapter provides an introduction to IDL's interface and capabilities. If you are new to IDL, reading through this chapter will give you a quick overview of the language's main concepts and functionality.

Jump forward to the next chapter in the IDL User's Guide, Running IDL

Jump forward to documentation on IDL Routines


Running IDL
2	Running IDL

Chapter Overview

This chapter explains IDL special characters, executive commands, the various commands you can enter in response to the IDL prompt, how to prepare and run IDL programs, how to set up IDL to work with your terminal or workstation, and other general information about IDL. If you are using IDL for the first time, the IDL Basics tutorial provides a hands-on way to learn basic concepts in IDL.

Installation and licensing instructions for IDL can be found in the appropriate platform-specific booklet. These booklets are titled: IDL for Macintosh, IDL for Unix, IDL for VMS, and IDL for Windows.


Topics in Running IDL Chapter
Running IDL

This chapter provides an overview of how to use the IDL programming environment.

Topics Covered:

Starting IDL

Quitting IDL

Input to IDL

Matching IDL to Your Terminal/Window System

Hints on Using IDL with Selected Window Systems

Special Characters

Executive Commands

Preparing and Running Programs

Format of Program Files

Interrupting Program Execution

Aborting IDL

Issuing Operating System Commands from IDL

Batch Execution

Noninteractive IDL

Startup File

Changing the IDL Prompt

Defining Keys

Environment Parameters Used by IDL

Jump ahead to Constants and Variables

Jump back to IDL Overview


Starting IDL

To run IDL, enter idl at the operating system prompt (UNIX and VMS) or double-click on the IDL icon (Windows and Macintosh). When IDL is ready to accept a command, it prompts with the string IDL> . If IDL does not start, take the following action depending upon the operating system you are running:

♦	UNIX: Be sure that your PATH environment variable includes the directory that contains IDL. You can find other recommended settings for environment variables at the end of this chapter.

♦	VMS: See your system manager (or the IDL installation instructions) for the proper commands to include in your LOGIN.COM file.

♦	Windows: Be sure that the path listed in the "Properties" dialog for the IDL icon (this is found under the File menu in the Program Manager) accurately reflects the location of the IDL executable file idl.exe.


Quitting IDL

To quit IDL, enter the EXIT command at the IDL prompt. On versions of IDL that have graphical interfaces (e.g., IDL for Windows, IDL for Macintosh) you can also exit by selecting the "Exit" option from the File menu.


Input to IDL

Commands that are entered at the IDL prompt are usually interpreted as IDL statements to be executed. Other interpretations include executive commands that control execution and compilation of programs, shell commands, etc. Input to the IDL prompt is interpreted according to the first character of the line, as shown in Table 2.1.

First Character	Action
.	Executive command
?	Help inquiry
$	Command to be sent to operating system (UNIX, VMS, Windows)
@	Batch file initiation.
Up arrow key	Recall / edit previous command
Control-D	Under UNIX, exits IDL, closes all files, and returns to operating system.
Control-Z	Under UNIX, suspends IDL. Under VMS and Windows, exits IDL, closes all files, and returns to operating system.
All others	IDL statement
Table 2.1 Interpretation of the First Character in an IDL Command

Command Recall and Line Editing

IDL saves the last 20 command lines entered. These command lines can be recalled, edited, and re-entered. The "up arrow" key on the keypad recalls the previous command you entered to IDL. Pressing it again recalls the previous line, etc. When a command is recalled, it is displayed after the IDL prompt and can be edited and/or entered.

The line-editing abilities and the keys that activate them differ somewhat between the different operating systems. Table 2.2 lists the edit functions and the corresponding keys.

The command recall feature is enabled by setting the system variable !EDIT_INPUT to 1 (the default) and is disabled by setting it to 0.

Changing the Number of Lines Saved

You can change the number of command lines saved in the recall buffer by setting !EDIT_INPUT equal to a number other than 20. In order for the change to take effect, IDL must be able to process the assignment statement before providing a command prompt. This means that you must put the assignment statement in the IDL startup file. (See "Startup File" on page 2-22 for more information on startup files.)

Function	UNIX	VMS	Windows	Macintosh
Move cursor to start of line	Control-A		Home	Control-A, Home
Move cursor to end of line	Control-E	Control-E, Control-W	End	Control-E, End
Move cursor left one character	Left arrow	Control-D, Left arrow	Left arrow	Left arrow
Move cursor right one character	Right arrow	Control-F,Right arrow	Right arrow	Right arrow
Move cursor left one word	Control-B, (R13 on Sun Keyboard)		Control-left arrow	Control-B
Move cursor right one word	Control-F, (R15 on Sun Keyboard)		Control-right arrow	Control-F
Delete from current to start of line	Control-U	Control-U, Control-X, Control-Delete
Delete from current to end of line			Control-Delete
Delete entire line			ESC	Control-U
Delete current character	Control-X		Delete	Control-X, Right-Delete
Delete previous character	Control-H, Backspace, Delete	Backspace, Delete	Backspace	Control-H, Delete
Delete previous word	Control-W, ESC-Delete			Control-W
Move back one line in recall buffer	Control-N, Up arrow	Control-B, Up arrow	Up arrow	Control-N, Up arrow
Move forward one line in recall buffer	Down arrow	Down arrow	Down arrow	Down arrow
Redraw current line	Control-R	Control-R
Overstrike/Insert	ESC-I	Control-A
EOF if current line is empty, else EOL	Control-D
Search recall buffer for text	^-text	PF1-text		^-text
Insert the character at the current position	any character	any character	any character	any character
Table 2.2 Command Recall and Line Editing Functions

For example, placing the line

!EDIT_INPUT = 50

in your IDL startup file changes the number of lines saved in the command recall buffer to 50.


Matching IDL to Your Terminal/Window System

In order to function properly, IDL must know the type of terminal or window system you wish to use. For most UNIX and VMS workstations, the default graphics device is "X", the X Window System . For computers running Microsoft Windows, the default graphics device is "Win," and for Macintosh computers the default graphics devices is "Mac."

♦	UNIX: IDL reads the value of the environment variable IDL_DEVICE when it starts. If IDL_DEVICE is present, IDL calls the procedure SET_PLOT with this string. For example, to use IDL with Tektronix  terminals, include the following command in your  ~/.login file:

setenv IDL_DEVICE tek

♦	VMS: IDL reads the value of the logical name IDL_DEVICE when it starts. If IDL_DEVICE is present, IDL calls the procedure SET_PLOT with this string. For example, to use IDL with Tektronix terminals, include the following command in your LOGIN.COM file:

$ DEFINE IDL_DEVICE tek

♦	Windows: IDL reads the value of the environment variable IDL_DEVICE when it starts. If IDL_DEVICE is present, IDL calls the procedure SET_PLOT with this string. For example, to set IDL to generate PostScript output by default, include the following command in your AUTOEXEC.BAT file:

SET IDL_DEVICE=PS

The case of the device name string is ignored, so "x" and "X" both refer to the same device (the X Window System). If IDL_DEVICE is defined, it should contain the name of a valid IDL graphics device. See the description of SET_PLOT in the IDL Reference Guide for a complete list of device names. In addition, this manual describes the capabilities of each device and how each device interacts with IDL.


Hints on Using IDL with Selected Window Systems

The interface to window systems is described in detail in the IDL Reference Guide. This section explains briefly how to properly set up selected window systems with IDL.

X Window System

Little or no customization is required to use IDL with the X Window System. You can control the number of colors used by IDL, if and how windows are repainted, and the type of color system (visual class). See "The X Windows Device" on page 3-56 of the IDL Reference Guide.

Microsoft Windows

Little or no customization is required to use IDL with Microsoft Windows. See the IDL for Windows for details.

Macintosh

Little or no customization is required to use IDL on the Macintosh. See the IDL for Macintosh for details.


Special Characters

Table 2.3 lists characters with special interpretations and states their functions in IDL. These characters are discussed further in the descriptions below.

UNIX	VMS	Windows	Macintosh	Function
!	!	!	!	First character of system variable names
'	'	'	'	Delimit string constants or indicate part of octal or hex constant
;	;	;	;	Begin comment field
$	$	$	$	Continue current command on the next line, or issue operating system command if entered on a line by itself.
"	"	"	"	Delimit string constants or precede octal constants
.	.	.	.	Indicate constant is floating point or start executive command
&	&	&	&	Separate multiple statements on one line
:	:	:	:	End label identifiers
*	*	*	*	Array subscript range
@	@	@	@	Include file/Execute IDL batch file
?	?	?	?	Online help
Control-C	Control-C	Control-C	Command-.	Interrupt
Control-D	Control-Z	Control-Z	Command-Q	Exit
Control-\	Control-Y			Abort
Table 2.3 Special Characters

Exclamation Point (!)

The exclamation point is the first character of names of IDL system-defined variables. System variables are predefined scalar variables of a fixed type. Their purpose is to override defaults for system procedures, to return status information, and to control the action of IDL.

Apostrophe (')

The apostrophe delimits string literals and indicates part of an octal or hex constant.

Semicolon (;)

The semicolon is the first character of the optional comment field of an IDL statement. All text on a line following a semicolon is ignored by IDL. A line can consist of a comment only or both a valid statement and a comment.

Dollar Sign ($)

The dollar sign at the end of a line indicates that the current statement is continued on the following line. The dollar sign character can appear anywhere a space is legal except within a string constant or between a function name and the first open parenthesis. Any number of continuation lines are allowed.

When the $ character is entered as the first character after the IDL prompt, the rest of the line is sent to the operating system as a command. If $ is the only character present, an interactive subprocess is started. Under Unix and VMS, IDL execution suspends until the new shell process terminates. Note that in IDL for Macintosh, there must be no space between the $ character and the full path name of the application being started.

Quotation Mark (")

The quotation mark precedes octal numbers, which are always integers, and delimits string constants. Example: "100B is a byte constant equal to 64 base 10 and "Don't drink the water" is a string constant.

Period (.)

The period or decimal point indicates in a numeric constant that the number is of floating-point or double-precision type. Example: 1.0 is a floating-point number. Also, in response to the IDL prompt, the period begins an executive command. For example,

.run myfile

causes IDL to compile the file myfile.pro. If myfile.pro contains a main program, the program also will be executed. In addition, the period precedes the name of a tag when referring to a field within a structure. For example, a reference to a tag called NAME in a structure stored in the variable A is A.NAME.

Ampersand (&)

The ampersand separates multiple statements on one line. Statements can be combined until the maximum line length is reached. For example, the following line contains two statements:

  I = 1 & PRINT, 'value:', I

Colon (:)

The colon ends label identifiers. Labels can only be referenced by GOTO and ON_ERROR statements. The following line contains a statement with the label LOOP1.

  LOOP1: X = 2.5

The colon also separates the starting and ending subscripts in subscript range specifiers. For example, A(3:6) designates elements three to six of the variable A.

Asterisk (*)

The asterisk, in addition to denoting multiplication, designates an ending subscript range equal to the size of the dimension. For example, A(3:*) represents all elements of the vector A from A(3) to the last element, while B(*, 3) represents all elements of row four of matrix B.

At Sign (@)

The "at" sign is used both as an include character and to signal batch execution.

@ as an Include Character

The "at" sign at the beginning of a line causes the IDL compiler to substitute the contents of the file whose name appears after the @ for the line. If the full path name is not specified after the @ symbol, IDL searches the current directory and a list of known locations where procedures are kept.

♦	UNIX: IDL searches for the file in the list of directories (as established by the environment variable IDL_PATH) stored in the system variable !PATH.

♦	VMS: IDL searches the list of directories (but not text libraries) established by the logical name IDL_PATH and stored in the system variable !PATH for the file.

♦	Windows: IDL searches for the file in the list of directories stored in the system variable !PATH (specified in the "Preferences" dialog of the File menu).

♦	Macintosh: IDL searches for the file in the list of directories stored in the system variable !PATH (specified in the "Search Path" dialog of the Edit menu).

For example, the line

@doit

when included in a file, causes the file doit.pro to be compiled in its place. (The suffix .pro is the default for IDL program files.) When the end of the file is reached, compilation resumes at the line after the @.

@ to Signal Batch Processing

When IDL is running in interactive mode, a line beginning with the character @ is entered in response to the IDL prompt and the file is opened for batch input. See "Batch Execution" on page 2-20.

Question Mark (?)

The question mark invokes the IDL on-line help facility when entered in response to the IDL prompt. See "IDL's Online Help System" on page 13-2 for more information.

Control-C / Command-.

Typing Control-C, the interrupt character, generates an IDL keyboard interrupt. See "Interrupting Program Execution" on page 2-19.

Under VMS and Windows, Control-C is always the interrupt character. However, under UNIX, the interrupt character can be changed by the user outside of IDL. This is rarely done. So for the purposes of this manual, we assume the default convention.

On the Macintosh, the interrupt character is Command-. (Command-period).

Control-D

Under UNIX, entering Control-D as the first character causes IDL to exit back to the operating system. The EXIT procedure has the same function. If Control-D is not the first character, it simply ends the input line as if a return had been entered.

Control-D has no special meaning under VMS, Windows, or the Macintosh.

Control-Y

Under VMS, typing Control-Y, the quit character, causes IDL to be killed instantly (just like any VMS process). It is best to avoid this type of exit. See "Aborting IDL" on page 2-19. If you enter the DCL command CONTINUE immediately after aborting the IDL session, VMS will resume the session as if you had never aborted it. However, if you execute any command that causes a program to run, your IDL session will be lost.

Control-Y has no special meaning under UNIX, Windows, or the Macintosh.

Control-Z

The function of Control-Z depends on the operating system in use:

♦	UNIX: Control-Z is normally the UNIX suspend character. Typing the suspend character suspends IDL and returns you to the shell process where you can enter one or more shell commands, for example, to run a text editor. After completing the commands, type fg to return IDL to the foreground. Although the UNIX suspend character can be changed by the user outside of IDL, this is rarely done. For the purposes of this manual, we assume the default convention.

♦	VMS: Under VMS, entering Control-Z as the first character causes IDL to exit back to the operating system. The EXIT procedure has the same function. If Control-Z is not the first character, it ends the input line as if a return had been entered. This input line is executed, then IDL exits.

♦	Windows: Under Windows, entering Control-Z at any point causes IDL to exit back to Windows. The EXIT procedure has the same function.

♦	Macintosh: Control-Z has no special meaning on the Macintosh. Enter Command-Q to exit IDL.

Control-\

Control-\ is normally the UNIX quit character. Typing the quit character causes IDL to be killed instantly (just like any UNIX process). It is best to avoid this type of exit. See "Aborting IDL" on page 2-19. Although the UNIX quit character can be changed by the user, this is rarely done. For the purposes of this manual, we assume the default convention. Control-\ has no special meaning under VMS, Windows, or the Macintosh.

For additional information about these special characters and their functions, refer to subsequent sections of this chapter.


Executive Commands

IDL executive commands compile programs, continue stopped programs, and start previously compiled programs. All of these commands begin with a period and must be entered in response to the IDL prompt. Commands can be entered in either uppercase or lowercase and can be abbreviated. Under UNIX, filenames are case sensitive, while with VMS, Windows, and the Macintosh either case can be used. Note that comments (prefaced by the semicolon character in IDL code) are not allowed within executive commands. Executive commands are summarized in Table 2.4.

Command	Action
.RUN	Compiles and possibly executes text from files or keyboard
.RNEW	Erases main program variables and then .RUN
.COMPILE	Compiles text from files or keyboard without executing
.CONTINUE	Continues execution of a stopped program
.GO	Executes previously compiled main program from beginning
.OUT	Continues program execution until the current routine returns
.SKIP	Skips over the next statement and then single steps
.STEP	Executes a single statement (abbreviated as .S)
.STEPOVER	Executes a single statement if the statement does not call a routine (abbreviated as .SO)
.SIZE	Resizes the compiler's code and data areas
.TRACE	Similar to .CONTINUE, but displays each line of code before execution
Table 2.4 IDL Executive Commands

.RUN [File1, ..., Filen]

The .RUN command compiles and saves procedures, functions, and/or main programs in memory. The command can be followed by a list of files to be compiled. Filenames are separated by blanks, tabs, or commas.

If a file specification is included in the command, IDL searches for the file first in the current directory, then in the directories specified by the system variable !PATH. See "Searching for Program Files" on page 2-15 for more information on IDL's search strategy.

If no files are present, input is accepted from the keyboard until a complete program unit is entered. If a main program unit is encountered, execution of the program will begin after all files have been read if there were no errors. The values of all of the variables are retained.

Files containing IDL procedures, programs, and functions are assumed to have the file extension (suffix) .pro.

Using .RUN to Make Program Listings

The command arguments -t for terminal listing or -l filename for listing to a named file can appear after the command name and before the program filenames to produce a numbered program listing directed to the terminal or to a file. For instance, to see a listing on the screen as a result of compiling a procedure contained in a file named analyze.pro, use the following command:

.RUN -T analyze

To compile the same procedure and save the listing in a file named analyze.lis, use the following command:

.RUN -L analyze.lis analyze

In listings produced by IDL, the line number of each statement is printed at the left margin. This number is the same as that printed in IDL error statements, simplifying location of the statement causing the error.

Note that if the compiled file contains more than one procedure or function, line numbering is reset to "1" each time the end of a program segment is detected.

Each level of block nesting is indented four spaces to the right of the preceding block level to improve the legibility of the program's structure.

Examples of .RUN and .RNEW

Some examples of the .RUN and .RNEW commands are shown below.

.RUN	Accept a program from the keyboard. Retain the present variables.

.RUN myfile	Compile the file myfile.pro. If it is not found in the current directory, try to find it in the directory search path.

.RUN -T A, B, C	Compile the files a.pro, b.pro and c.pro. List the files on the terminal.

.RNEW -L myfile.lis myfile, yourfile
Erase all variables and compile the files myfile.pro and yourfile.pro. Produce a listing on myfile.lis.

.RNEW [File1, ..., Filen]

The .RNEW command compiles and saves procedures and programs in the same manner as .RUN. In addition, all variables in the main program unit, except those in common blocks, are erased. The -t and -l filename switches have the same effect as with .RUN.

.COMPILE [File1, ..., Filen]

The .COMPILE command compiles and saves procedures and programs in the same manner as .RUN. If one or more filenames are specified, the procedures and functions contained therein are compiled but not executed.

.CONTINUE

Continues execution of a program that has stopped because of an error, a stop statement, or a keyboard interrupt. IDL saves the location of the beginning of the last statement executed before an error. If it is possible to correct the error condition in the interactive mode, the offending statement can be re-executed by entering .CONTINUE. After STOP statements, .CONTINUE continues execution at the next statement. The .CONTINUE command can be abbreviated; for example, .C. Execution of a program interrupted by typing Control-C also can be resumed at the point of interruption with the .CONTINUE command.

.GO

This command starts execution at the beginning of a previously-compiled main program.

.OUT

The .OUT command continues executing statements in the current program until it returns.

.STEP [n] or .S [n]

The .STEP command executes one or more statements in the current program starting at the current position, stops, and returns control to the interactive mode. This command is useful in debugging programs. The optional argument n indicates the number of statements to execute. If n is omitted, a single statement is executed.

.STEPOVER [n] or .SO [n]

The .STEPOVER command executes one or more statements in the current program starting at the current position, stops, and returns control to the interactive mode. Unlike .STEP, if .STEPOVER executes a statement that calls another routine, the called routine runs until it ends before control returns to interactive mode. That is, a statement calling another routine is treated as a single statement.

The optional argument n indicates the number of statements to execute. If n is omitted, a single statement (or called routine) is executed.

. SKIP [n]

The .SKIP command skips one or more statements and then executes a single step. It is useful for continuing over a program statement that caused an error. If the optional argument n is present, it gives the number of statements to skip; otherwise, a single statement is skipped. Note that .SKIP does not skip into a called routine.

For example, consider the following program segment:

...... ... ...

OPENR, 1, 'missing'

READF, 1, xxx, ..., ...

... ... ...

If the OPEN statement fails because the specified file does not exist, program execution will halt with the OPEN statement as the current statement. Execution can not be resumed with the executive command .CONTINUE because it attempts to re-execute the offending OPEN statement, causing the same error. The remainder of the program can be executed by:

1.	Opening the correct file by manually typing in a valid OPEN statement.

2.	Entering .SKIP, which skips over the incorrect OPEN statement.

3.	Entering .CONTINUE, which resumes execution of the program at the READF statement.

.SIZE Code_Size, Data_Size

The .SIZE command resizes the memory area used to compile programs. The default code and data area sizes are 32,768 and 8,192 bytes, respectively. These sizes represent a compromise between an unlimited program space and conservation of memory. User procedures and functions are compiled in this large program area. After successful compilation, a new memory area of the required size is allocated to contain the newly compiled program unit.

Resizing the code and data areas erases the currently compiled main program and all main program variables. For example, to extend the code and data areas to 30,000 and 5,000 bytes, respectively, use the following statement:

.SIZE 30000 5000

Each user-defined procedure, function, and main program has its own code area that contains the compiled code and constants. Although the maximum size of these areas is set by the .SIZE command, there is virtually no limit to the number of program units. Procedures or functions that run out of code area space should be broken into multiple program units.

The data area contains information describing the user-defined variables and common blocks for each procedure, function, or main program. Note that the "data area" is not the space available for variable storage, but the space available for that program unit's symbol table.

Examples

Users are sometimes confused about the nature of the code and data areas. Note that there are separate code and data areas for each compiled function, routine, or main program. The HELP command can be used to see the current sizes of the code and data areas for the program unit in which the HELP function is called. For example, to see the sizes of the code and data areas for the main program level, enter:

HELP

at the IDL prompt.

Each compiled function and procedure has its own code and data areas. If the compiled routine does not use the full amount of code space allocated by the default code area size, the code area "shrinks" to just the size the routine needs. For example, enter and compile a simple procedure from the IDL prompt by entering:

.RUN

- PRO EXAMPLE

- PRINT, "Here are the code and data areas for this procedure:"

- HELP

- END

Call the EXAMPLE procedure from the command line to see the result:

EXAMPLE

The third line of output from the HELP procedure displays:

Code area used: 100.00% (100/100), Data area used: 2.02% (2/99)

Note that the code area for the EXAMPLE procedure is completely filled and that the total size of the code area is just 100 bytes.

.TRACE

Continues execution of a program that has stopped because of an error, a stop statement, or a keyboard interrupt. .TRACE differs from .CONTINUE in that if IDL is using a graphical user interface (IDL for Windows, IDL for Macintosh, or IDLTool) it highlights each line of code before execution. For command-line versions of IDL, .TRACE is identical to .CONTINUE.


Preparing and Running Programs

To enter a short program or procedure from the keyboard, simply type .RUN or .RNEW. When the final END statement is encountered, execution of the main program will begin if there was an END statement and if no errors were found. If you entered only functions or procedures or if the main program you entered had an error, IDL will display the IDL prompt to show that a program is not running.

Usually, any text editor can be used to prepare programs or procedures of more than a few lines. IDL for Windows and IDL for Macintosh include built-in text editors, but these need not be used if you prefer to use your own text editor or word processor. Files containing IDL programs, procedures, and functions are assumed to have the extension name .pro. Once the program has been entered into a file from a text editor, run IDL and compile one or more program files using .RUN or .RNEW.

If errors are found or changes are necessary and you cannot run your editor in a separate window, you can re-enter the editor directly from IDL. For example, for UNIX, use the following statement:

$ vi myfile.pro

For VAX/VMS, use the following statement:

$ edit/edt myfile.pro

This command causes IDL to pause and runs the text editor with the file myfile.pro. Exiting the editor returns you to IDL where you can re-compile the program. Variable values, open files, compiled procedures, etc., are retained.

Under UNIX, you also can suspend IDL to use the text editor by typing Control-Z, then re-entering IDL after editing with the shell fg command.

It should be noted that if you are running IDL in a window system environment, it is faster and more convenient to use one window for IDL and another for the text editor.

Searching for Program Files

When a file specified is with the .RUN, .RNEW, .COMPILE, or @ commands, IDL searches the current directory for filename.pro (where filename is the file specified), then for filename.sav, then for filename. If no file is found in the current directory, IDL searches in the same way in each directory specified by !PATH.

The details of how !PATH is initialized and used differ between the various operating systems, although the overall concept is the same.

♦	UNIX: !PATH is a colon-separated list of directories, similar in concept to the PATH environment variable which UNIX uses to locate commands.

!PATH is initialized from the environment variable IDL_PATH when IDL starts. Note that directories that do not contain at least one .pro or .sav file will not be included in !PATH, even if they are specified by the IDL_PATH environment variable. This initial value can be changed, as desired, once in IDL. For example, the following statement adds the directory /usr2/project/idl_files to the beginning of the search path:

!path = '/usr2/project/idl_files:' + !path

To specify a directory tree that includes all of that directory's subdirectories, use the EXPAND_PATH function as described in the IDL Reference Guide.

Each user can assign IDL_PATH to a series of directories that are searched for IDL programs, procedures, functions, and "include" files. It is convenient to set up this variable in your ~/.login file. For example,

setenv IDL_PATH ~/idl_lib:/usr/local/rsi/idl/lib

causes IDL to search for programs first in the current directory, then in your idl/lib directory, and then in the system-wide directory /usr/local/rsi/ idl/lib.

If IDL_PATH is not defined, IDL initializes !PATH to the default value +/usr/ local/rsi/idl. Note that the current directory is always searched before consulting !PATH.

♦	VMS: !PATH is a comma-separated list of directories and text libraries. Text libraries are distinguished by prepending a "@" character to their name.

!PATH is initialized from the logical name IDL_PATH when IDL starts. Note that directories that do not contain at least one .pro or .sav file will not be included in !PATH, even if they are specified by the IDL_PATH logical. This initial value can be changed once in IDL as desired. For example, the following statement adds the directory DISKA:[PROJECTLIB] to the beginning of the search path:

path = 'diska:[projectlib],' + !path

To specify a directory tree that includes all of that directory's subdirectories, use the EXPAND_PATH function as described in the IDL Reference Guide.

Each user can assign IDL_PATH to a series of directories and text libraries that are searched in order for IDL programs, procedures, functions, and "include" files. It is convenient to set up this variable in your LOGIN.COM file. For example,

DEFINE IDL_PATH "DISKA:[USER.IDLLIB],@IDL_DIR:[LIB]USERLIB.TLB"

causes IDL to search for programs first in the current directory, then in the directory DISKA:[USER.IDLLIB], and finally in the library of routines written in IDL and included in the standard IDL distribution, which is supplied as a VMS text library. Note that the current directory is always searched before consulting !PATH.

The logical IDL_PATH also can be defined as a multi-valued logical name (e.g., a search list logical). Therefore, the above example also can be written as follows:

DEFINE IDL_PATH DISKA:[USER.IDLLIB],"@IDL_DIR:[LIB]USERLIB.TLB"

IDL simply takes the various translations and concatenates them together into a comma-separated list. Note that the quotes around the second translation in this example are necessary to keep DCL from seeing the "@" character as an invitation to execute a command file.

♦	Windows: !PATH is a semicolon-separated list of directories, similar in concept to the PATH environment variable DOS uses to locate commands. !PATH is initialized from the saved IDL for Windows preferences data, or from a DOS environment variable IDL_PATH, when IDL starts. Note that directories that do not contain at least one .pro or .sav file will not be included in !PATH, even if they are specified by the preferences data or the IDL_PATH environment variable. Change the path settings by adding to or altering the list of directories in the "Path" dialog, found under the "Preferences" selection of the IDL for Windows File menu, or by changing the value of !PATH from the IDL command prompt.

To specify a directory tree that includes all of that directory's subdirectories, use the EXPAND_PATH function as described in the IDL Reference Guide. For example, the following commands create a variable containing a list of the directories under the directory C:\USER and append the list to the IDL path:

list = expand_path('+c:\user')

!path = !path + ';' + list

♦	Macintosh: !PATH is a comma-separated list of folders. !PATH is initialized from the saved IDL for Macintosh preferences data when IDL starts. Note that folders that do not contain at least one .pro or .sav file will not be included in !PATH, even if they are specified by the preferences data. Change the path settings by adding to or altering the list of directories in the "Search Path" dialog, found in the IDL for Macintosh Edit menu, or by changing the value of !PATH from the IDL command prompt.

Use the following syntax is used to specify Macintosh path locations:

•	Filenames are specified as a colon-separated list of drive names and folders.

•	Folder and file names can contain spaces and/or commas.

Thus, the file myprogram.pro, located in the folder named Programs which resides on the drive named Macintosh HD would be specified:

'Macintosh HD:Programs:myprogram.pro'

To specify a directory tree that includes all of that folder's subfolders, use the EXPAND_PATH function as described in the IDL Reference Guide. For example, the following commands create a variable containing a list of the folders in the folder Macintosh HD:USER and append the list to the IDL path:

list = expand_path('+Macintosh HD:USER:')

!path = !path + ',' + list


Format of Program Files

There are essentially four types of code units in files containing IDL statements:

Procedure

A self-contained code unit with a unique name that is called by other code units to perform a desired function. The calling code unit and the procedure communicate via passed arguments.

Function

A self-contained code unit similar to a procedure. The only difference is that a function returns a value and can therefore be used in expressions.

Main Program

A series of statements that are not preceded by a procedure or function heading. They do, however, require an END statement. Since there is no heading, it cannot be called from other routines and cannot be passed in arguments. When IDL encounters a main program as the result of a .RUN executive command, it compiles it into the special program named  $MAIN$ and immediately executes it. Afterwards, it can be executed again by using the .GO executive command.

Include File

A file to be included in other files. The statements contained in an include file are textually inserted into the including file. See "Batch Execution" on page 2-20. A file can contain any combination of functions, procedures, and/or include files. For example, a file might contain three procedures and two functions and also might be included in another file.

Examples of IDL Program Files

The form of a file containing only a main program is as follows:

First statement

Second statement

...

...

...

END

Files containing procedures and/or functions have the following form:

PRO XXX, PARAM1, PARAM2	First procedure.

First statement of procedure

Second statement

...

...

...

END	End of first procedure, implicit RETURN.

<ff>	Form feed between units is optional.

PRO YYY, PARAM1, PARM2	Second procedure.

First statement

...

...

RETURN	Return is optional in procedures.

END	End of second procedure.

First statement of main program

Second statement of main program

...

...

END	End of main program.

In a file containing procedures, the main program is optional. If no main program exists, the procedures are compiled (but not executed) and control returns to the IDL prompt.

The user should take care not to place any statements between the end of the previous program unit and the next procedure definition line. If the first statement (non-empty line) is not a procedure or function definition statement, IDL assumes a main program follows.


Interrupting Program Execution

Programs that are running can be manually stopped by typing Control-C (Command-. on the Macintosh). This action is called a keyboard interrupt. A message indicating the statement number and program unit being executed is issued on the terminal acknowledging the interrupt. The values of variables can be examined, statements can be entered from the keyboard, and variables can be changed. The program can be resumed by typing the executive command .CONTINUE to resume or .S to execute the next statement and stop.

Variable Context After Interruption

The variable context after a keyboard interrupt is that of the program unit in which the interrupt occurred. By typing the statement RETURN, the program context will revert to the next higher calling level. The RETALL command returns control to the main program level. If any doubt arises as to which program unit in which the interrupt occurred, the HELP procedure can be used to determine the program context. IDL checks after each statement to see if an interrupt has been typed. Execution does not stop until the statement that was active finishes; thus, a long time can elapse from the time the interrupt is typed to the time the program interrupts.


Aborting IDL

♦	UNIX: As with any UNIX process, IDL can be aborted by typing Control-  .This is a very abrupt exit—all variables are lost, and the state of open files will be uncertain. Thus, although it can be used to exit of IDL in an emergency, its use should be avoided.
Note: After aborting IDL by using Control-\ , you may find that your terminal is left in the wrong state. You can restore your terminal to the correct state by issuing one of the following UNIX commands:

% reset

or

% stty echo -cbreak

♦	VMS: As with any VMS program, IDL can be aborted by typing Control-Y. Aborting IDL with Control-Y should only be used as an emergency measure since all the variables are lost and some output may disappear. It is possible to resume IDL by typing the DCL command:

$ CONTINUE

However, if any DCL command that causes VMS to run a new program is issued prior to the CONTINUE command, the IDL session will be irreversibly lost.

♦	Windows and Macintosh: There is no abort character for either IDL for Windows or IDL for Macintosh.


Issuing Operating System Commands from IDL

UNIX and VMS operating system commands can be sent to a subprocess for execution by entering the command preceded by the character $ in response to the IDL prompt. Under Windows, the $ can be used to enter a DOS command at the IDL prompt.

The SPAWN procedure has the same effect and is more flexible because it can be used within an IDL program while $ can only be entered interactively. In addition, the standard output of the command can be saved in an IDL string array by SPAWN. Hence, $ can be thought of as an interactive-only abbreviation for SPAWN. Unlike $, SPAWN can also be used on the Macintosh.

IDL creates and runs a process to execute the command and waits for the command to finish before issuing another IDL prompt. All of the variables, procedures, open files, etc., are saved while the command is executing. (Under UNIX, essentially the same result is obtained using Control-Z to suspend IDL.) Output from the command issued is handled different ways under different operating systems:

♦	UNIX: Output from the command is directed to the window in which IDL is running. Other windows may be created as well.

♦	VMS: Output from the command is directed to the window in which IDL is running. Other windows may be created as well.

♦	Windows: A new MS-DOS window is opened to display the output. Note that the window is destroyed as soon as the command finishes.

♦	Macintosh: The selected Macintosh application starts up as if it had been opened from the Finder.


Batch Execution

IDL can be run in the non-interactive mode (the "batch" mode) by entering the character @ followed by the name of a file containing IDL executive commands and statements. All executive commands and IDL statements that normally come from the keyboard are read from the specified file.

Batch execution can be terminated before the end of the file, with control returning to the interactive mode without exiting IDL, by calling the STOP procedure from the batch file. Calling the EXIT procedure from the batch procedure has the usual effect of terminating IDL.

To enter batch mode from the interactive mode, enter:

@filename

at the IDL prompt. (Note that the @ symbol must be the first character on the line in order for it to be interpreted properly.) IDL reads commands from the specified file until the end of the file is reached. Batch files can be nested by simply prefacing the name of the new batch file with the @ character. As stated above, the current directory and then all directories in the !PATH system variable are searched (if the file was not found in the current directory). The filename can also include full path specifications (e.g., when the batch file resides in a directory that isn't included in !PATH).

Interpretation of Batch Statements

Each line of the batch file is interpreted exactly as if it was entered from the keyboard. In the batch mode, IDL compiles and executes each statement before reading the next statement. This differs from the interpretation of programs compiled using .RNEW or .RUN, in which all statements in a program are compiled as a single unit and then executed.

Labels are illegal in the batch mode because each statement is compiled and executed independently.

Multiline statements must be continued on the next line using the $ continuation character, because IDL terminates every interactive mode statement not ending with $ by an END statement. A common mistake is to include a multiple-line block statement in a batch file as shown below.

FOR I = 1, 10 DO BEGIN	This will not work in batch mode.

A = X(I)

...

...

ENDFOR

In the batch mode, IDL compiles and executes each line separately, causing syntax errors in the above example because no matching ENDFOR is found on the line containing the BEGIN statement when the line is compiled. The above example could be made to work by writing the block of statements as a single line using the $ (continuation) and & (multiple commands on a single line) characters.

Batch Examples

An example of an IDL executive command line that initiates batch execution follows:

@myfile

This command causes the file myfile.pro to be used for statement and command input. If this file is not in the current directory, the search path, !PATH is also searched.

 An example of the contents of a batch file follows:

.RUN proga	Run program A.

.RUN progb	Run program B.

PRINT, AVALUE, BVALUE	Print results.

CLOSE, 3	Close unit 3.

<eof>

The batch file should not contain complete program units. Complete program units should be compiled and run by using the .RUN and .RNEW commands in the batch files, as illustrated above.


Noninteractive IDL

IDL can be run entirely in the non-interactive mode by including the name of a file containing batch mode commands in the shell command used to invoke IDL. When the end of the file is reached, control reverts to the interactive mode and input is accepted from the keyboard. Call the EXIT procedure from the file to cause IDL to return to the operating system if you do not want to use IDL in the interactive mode. For example, the operating system command

idl startup

runs IDL. IDL then executes in batch mode the text in the file startup.pro and reverts to the interactive mode if a call to EXIT is not present in the file.


Startup File

The start-up file contains a series of IDL statements and is executed each time IDL is run. Common uses are to compile frequently used procedures or functions, customize default settings, load data, and perform other useful operations. It contains IDL statements that are individually compiled and executed in the same manner as batch file execution.

♦	UNIX: To make IDL execute a start-up file under UNIX, set the environment variable IDL_STARTUP to the name of the file to be executed. If IDL_STARTUP is not defined, a startup file is not executed.

♦	VMS: To make IDL execute a start-up file under VMS, assign the VMS logical name IDL_STARTUP to the name of the file to be executed. If IDL_STARTUP is not defined, a startup file is not executed.

♦	Windows: To make IDL execute a start-up file under Windows, specify the name of the startup file in the "Startup" dialog, found under "Preferences" in the IDL for Windows File menu.

♦	Macintosh: To make IDL execute a start-up file on the Macintosh, specify the name of the startup file in the "IDL Startup Settings" dialog, found under "Preferences" in the IDL for Macintosh Edit menu.

The procedure search path, !PATH, is used when searching for the file if it is not in the current directory. Startup command files are executed before the batch file present in the initial command line, if any.


Changing the IDL Prompt

The text string IDL prompts the user for input specified by the system variable !PROMPT. You can change the prompt to any string by setting this system variable to the new prompt string. For example, to make IDL ring the bell on the terminal without echoing visible text when prompting, type the following statement:

!PROMPT = '\007'

The ASCII code for the bell is 7. It does not have a printable representation, so it is specified using the octal escape sequence \007. Such sequences are described in Chapter 3. To completely eliminate the prompt, set !PROMPT to the null string:

!PROMPT = ''


Defining Keys

Function keys on the terminal can be equated to a character string using the DEFINE_KEY procedure. For example, pressing the R4 key on a Sun-style keyboard or the PF4 key on a DEC  keyboard is equivalent to the string PLOT, as shown in the following example. This ability allows frequently used strings and commands to be entered with a single key stroke. Briefly, the call to DEFINE_KEY is:

DEFINE_KEY, Key_Name, Text

where Key_Name is a string containing the name of the key to define (e.g., R1, ..., R15, and F2, ..., F9), and Text is the text to be entered when the key is depressed. The keyword parameters TERMINATE and NOECHO can be used in the call to terminate the substituted text with a new line character and/or to not echo the text when the key is depressed.

In IDL for Windows, the function keys F1 through F4, F11, and F12 are available for definition. DEFINE_KEY is not currently available in IDL for Macintosh.

Example

SETUP_KEYS

DEFINE_KEY, 'r4', 'PLOT,'	Enter the text "PLOT," when the Sun R4 function key is pressed.

DEFINE_KEY, 'pf4', 'PLOT,'	Enter the text "PLOT," when the VAX function key PF4 is pressed.

DEFINE_KEY, 'f5','ERASE',/TERM	Enter the text "ERASE" followed by a carriage return when F5 is pressed.

DEFINE_KEY, 'f6', 'WSHOW', /TERM, /NOECHO
F6 displays the current window, the text is not echoed.

A natural place to put your key definitions is in the start-up file so that the function keys are defined when IDL is initialized. The statement HELP,/KEYS displays the current definition of all the function keys.


Environment Parameters
Environment Parameters Used by IDL

Under UNIX, IDL uses environment variables to control its initial state. Under VMS, logical names are used for the same purpose. Under Windows, IDL uses either saved preference settings or DOS environment variables to control its initial state. On the Macintosh, all information about IDL's initial state is contained in the saved preference settings.

The environment parameters used by UNIX, and VMS IDL are described below. In most cases, these parameters can also be used by IDL for Windows, but it is recommended that changes be made through the "Preferences" dialogs (under the File menu) instead.

IDL_DEVICE

The initial graphics output device. If it is defined, IDL calls the SET_PLOT procedure with its contents to direct graphics output to the proper device. If IDL_DEVICE is not defined, IDL assumes that the X Window System is being used.

IDL_DIR

The directory that contains the files required by IDL. At startup, IDL uses this parameter to find the Hershey character font files, system-wide colortable definitions, etc.

♦	UNIX: If IDL_DIR is not defined, IDL assumes a default of /usr/local/rsi/idl. If IDL is installed in a different directory on your system, IDL_DIR must be properly defined before IDL can run.

♦	VMS: This rooted logical must be properly defined in order for IDL to run properly. For example, if the IDL distribution is located in DUA1:[IDL] on your system, the following DCL command will suffice:

$ DEFINE IDL_DIR DUA1:[IDL.]/TRANS = (CONCEAL, TERM)

Note that IDL_DIR must be defined using the physical device name of the disk. Most sites use logical names to refer to disks. If you wish to define IDL_DIR in terms of the disk's logical name, use the DCL F$TRNLNM lexical function to translate the name. For example, assume that the main IDL directory is DISKA:[IDL]:

$ DEFINE IDL_DIR 'F$TRNLNM(""DISKA"")'[IDL.]/trans = (conceal, term)

♦	Windows/Macintosh: This parameter is not necessary under Windows or on the Macintosh.

IDL_STARTUP

The name of a start-up procedure that is executed by IDL on initialization. If it is not defined, no start-up file is executed.

IDL_PATH

The library and procedure directory search path. This is a special-character-separated list of locations to search if the desired routine is not found in the current directory. The current directory is always searched first. Note that the separator character used is different for each operating system (":" for Unix, "," for VMS, and ";" for Windows).

At startup time, the value of IDL_PATH is expanded using the same rules as the EXPAND_PATH function. See the IDL Reference Guide for a description of EXPAND_PATH and path definition strings.

If a directory specification supplied in IDL_PATH does not have a "+" character prepended to it, it is used by IDL as is. However, if it does have a leading "+," then IDL performs the steps described in the documentation for EXPAND_PATH.

Defaults for IDL_PATH are different for each operating system:

♦	UNIX:  IDL_PATH is a colon-separated list of directories. If it is not defined, a default of +/usr/local/rsi/idl/lib is assumed. This is consistent with the default value assumed for IDL_DIR.

♦	VMS: IDL_PATH is a comma-separated list of directories and text library files. Under VMS, using a text library in favor of a directory containing .pro files is more efficient. Most of the routines written in IDL and included in standard distribution are therefore supplied in this form. If IDL_PATH is not defined, a default of +IDL_DIR:[LIB] is assumed.

♦	Windows/Macintosh: This parameter is not necessary under Windows or on the Macintosh.

Examples

For an example of typical commands to set the UNIX environment variables, see the file idl_setup in the bin subdirectory of the main IDL directory.

For an example of typical commands to set the VMS logical names, see the command file IDL_SETUP in the bin subdirectory of the main IDL directory.

Jump ahead to Constants and Variables

Jump back to IDL Overview


Constants and Variables
3	Constants and Variables

Chapter Overview

Constants and variables are the building blocks that combine with operators and functions to produce results. A constant is a value that does not change during the execution of a program. A variable is a location with a name that contains a scalar or array value. During the execution of a program or an interactive terminal session, numbers, strings, or arrays can be stored in variables and used in future computations.

The data type of a constant is determined by its syntax. In IDL there are eight basic, atomic data types, each with its own form of constant:

•	Byte: An 8-bit unsigned integer ranging in value from 0 to 255. Pixels in images are commonly represented as byte data.

•	Integer: A 16-bit signed integer ranging from −32,768 to +32,767.

•	Long: A 32-bit signed integer ranging in value from approximately minus two billion to plus two billion.

•	Floating-point: A 32-bit, single-precision, floating-point number in the range of  ±10^34 on the VAX  system, and  ±10^38 on machines supporting the Institute of Electrical and Electronics Engineers, Inc. (IEEE) standard, with approximately six or seven decimal places of significance.

•	Double-precision: A 64-bit, double-precision, floating-point number in the range of ±10^34 on the VAX system, and ±10^308 on machines supporting the IEEE standard, with approximately 14 decimal places of significance.

•	Complex: A real-imaginary pair of single-precision, floating-point numbers. Complex numbers are useful for signal processing and frequency domain filtering.

•	Double-precision complex: A real-imaginary pair of double-precision, floating-point numbers.

Note that in previous versions of IDL, the combination of a double-precision number and a complex number in an expression resulted in a single-precision complex number. Starting with this release, this combination results in a double-precision complex number.

•	String: A sequence of characters, from 0 to 32,767 characters in length, which is interpreted as text.

In addition, structures can be created that are aggregations of the eight atomic data types. The use of structures is described in further detail in Chapter 7.


Topics in Constants and Variables Chapter
Constants and Variables

This chapter provides an overview of IDL's data types.

Topics Covered:

Numeric Constants

String Constants

Variables

System Variables

Jump forward to Expressions and Operators

Jump backward to Running IDL


Numeric Constants

Integer Constants

Numeric constants of different types can be represented by a variety of forms. The syntax of integer constants is shown in the following table, where  n represents one or more digits.

Radix	Type	Form	Examples
Decimal	Byte	nB	12B, 34B
	Integer	n	12, 425
	Long	nL	12L, 94L
Hexadecimal	Byte	'n'XB	'2E'XB
	Integer	'n'X	'0F'X
	Long	'n'XL	'FF'XL
Octal	Byte	"nB	"12B
	Integer	"n	"12
		'n'O	'377'O
	Long	"nL	"12L
		'n'OL	'777777'OL
Table 3.1 Syntax of Integer Constants

Digits in hexadecimal constants can include the letters A through F for the decimal numbers 10 through 15. Also, octal constants can be written using the same style as hexadecimal constants by substituting an O for the X. The following table illustrates examples of both valid and invalid IDL constants.

Values of integer constants can range from 0 to 255 for bytes, 0 to 32,767 for integers, and 0 to 2^31 - 1 longwords. Integers with absolute values greater than 32,767 are automatically promoted to longword type. Any numeric constant can be preceded by a plus (+) or minus (-) sign.

Acceptable	Unacceptable	Reason
255B	256B	Too large, limit is 255
'123'L	'123L	Unbalanced apostrophe
"123	'03G'x	Invalid character
'27'OL	'27'L	No radix
'650'XL	650XL	No apostrophes
"124	"129	9 is an invalid octal digit
Table 3.2 Examples of Integer Constants

Floating-Point and Double-Precision Constants

Floating-point and double-precision constants can be expressed in either conventional or scientific notation. Any numeric constant that includes the decimal point is a floating-point or double-precision constant.

The syntax of floating-point and double-precision constants is shown in the following table. The notation "sx" represents the sign and magnitude of the exponent, for example,  E-2.

Form	Example
n.	102.
.n	.102
n.n	10.2
nEsx	10E5
n.Esx	10.E-3
.n Esx	.1E+12
n.nEsx	2.3E12
Table 3.3 Syntax of Floating-Point Constants

Double-precision constants are entered in the same manner, replacing the E with a D. For example, 1.0D0, 1D, and 1.D each represent a double-precision numeral 1.

Complex Constants

Complex constants contain a real and an imaginary part, both of which are single- or double-precision, floating-point numbers. The imaginary part can be omitted, in which case it is assumed to be zero. The form of a complex constant is as follows:

COMPLEX(REAL_PART, IMAGINARY_PART)

or

COMPLEX(REAL_PART)

For example, COMPLEX(1,2) is a complex constant with a real part of one, and an imaginary part of two. COMPLEX(1) is a complex constant with a real part of one and a zero imaginary component. To extract the real part of a complex expression, use the FLOAT function. The ABS function returns the magnitude of a complex expression, and the IMAGINARY function returns the imaginary part.


String Constants

A string constant consists of zero or more characters enclosed by apostrophes (') or quotes ("). The value of the constant is simply the characters appearing between the leading delimiter ('or ") and the next occurrence of the same delimiter. A double apostrophe ('') or quote ("") is considered to be the null string; a string containing no characters. An apostrophe or quote can be represented within a string by two apostrophes or quotes; e.g., 'Don''t' returns Don't. This syntax often can be avoided by using a different delimiter; e.g., "Don't" instead of 'Don''t'. The following table illustrates valid string constants.

String Value	Acceptable
Hi there	'Hi there'
Hi there	"Hi there"
Null String	''
I'm happy	"I'm happy"
I'm happy	'I"m happy'
counter	'counter'
129	'129'
Table 3.4 Examples of Valid String Constants

This next table illustrates invalid string constants. In the last entry of the table, "129" is interpreted as an illegal octal constant. This is because a quote character followed by a digit from 0 to 7 represents an octal numeric constant, not a string, and the character 9 is an illegal octal digit.

String Value	Unacceptable	Reason
Hi there	'Hi there"	Mismatched delimiters
Null String	'	Missing delimiter
I'm happy	'I'm happy'	Apostrophe in string
counter	''counter''	Double apostrophe is null string
129	"129"	Illegal octal constant
Table 3.5 Examples of Invalid String Constants

Representing Non-Printable Characters

The ASCII characters with value less than 32 or greater than 126 do not have printable representations. Such characters can be included in string constants by specifying their ASCII value as a byte argument to the STRING function. The following table gives examples of using octal or hexadecimal character notation.

Specified String	Actual Contents	Comment
STRING(27B)+'[;H'+STRING(27B)+[2J'	'<Esc>[;H<Esc>[2J'	Erase ANSI terminal
STRING(7B)	Bell	Ring the bell
STRING(8B)	Backspace	Move cursor left
Table 3.6 Specifying Non-Printable Characters

Note that ASCII characters may have different effects (or no effect) on platforms that do not support ASCII terminal commands. For example, the ASCII string 7B does not ring the bell in IDL for Windows or IDL for Macintosh.


Variables

Variables are named repositories where information is stored. A variable can contain a scalar, vector, multi-dimensional array, or structure of virtually any size. Arrays can contain elements of any of the seven basic IDL data types plus structures. Variables can be used to store images, spectra, single quantities, names, tables, etc.

Attributes of Variables

Every variable has a number of attributes that can change during the execution of a program or terminal session. Variables have both a structure and a type as described below.

Structure

A variable can contain a single value (a scalar) or a number of values of the same type (an array) or data entities of potentially differing type and size (a structure). Strings are considered as single values, and a string array contains a number of variable-length strings.

In addition, a variable can associate an array structure with a file; these variables are called associated variables. Referencing an associated variable causes data to be read from, or written to, the file. Associated variables are described in the ASSOC function description on page 17-36.

Type

A variable can have one and only one of the following types: undefined, byte, integer, longword, floating-point, double-precision floating-point, complex floating-point, double-precision complex floating-point, string, or structure.

When a variable appears on the left-hand side of an assignment statement, its attributes are copied from those of the expression on the right-hand side. For example, the statement

ABC = DEF

redefines or initializes the variable ABC with the attributes and value of variable DEF. Attributes previously assigned to the variable are destroyed. Initially, every variable has the single attribute of undefined. Attempts to use the value of an undefined variables result in an error.

Variable Names

IDL variables are named by identifiers. Each identifier must begin with a letter and can contain from 1 to 128 characters. The second and subsequent characters can be letters, digits, the underscore character, or the dollar sign. A variable name cannot contain embedded spaces, because spaces are considered to be delimiters. Characters after the first 128 are ignored. Names are case insensitive. Lowercase letters are converted to uppercase; so the variable name abc is equivalent to the name ABC.

Acceptable	Unacceptable	Reason
A	EOF	Conflicts with function name
A6	6A	Does not start with letter
INIT_STATE	_INIT	Does not start with letter
ABC$DEF	AB@	Illegal character
My_variable	ab cd	Embedded space
Table 3.7 Examples of Valid and Invalid Variable Names

Caution: A variable cannot have the same name as a function (either built-in or user defined) or a reserved word (see the list below). Giving a variable such a name results in a syntax error or in "hiding" the variable.

The following table lists all of the reserved words in IDL.

AND	BEGIN	CASE	COMMON
DO	ELSE	END	ENDCASE
ENDELSE	ENDFOR	ENDIF	ENDREP
ENDWHILE	EQ	FOR	FUNCTION
GE	GOTO	GT	IF
LE	LT	MOD	NE
NOT	OF	ON_IOERROR	OR
PRO	REPEAT	THEN	UNTIL
WHILE	XOR
Table 3.8 IDL Reserved Words


System Variables

System variables are a special class of predefined variables available to all program units. Their names always begin with the exclamation mark character (!). System variables are used to set the options for plotting, to set various internal modes, to return error status, etc.

System variables have a predefined type and structure that cannot be changed. When an expression is stored into a system variable, it is converted to the variable type, if necessary and possible. Certain system variables are read only, and their values cannot be changed. The user can define new system variables with the DEFSYSV procedure.

Constant System Variables

The following system variables contain pre-defined constants or values for use by IDL routines. System variables can be used just like other variables. For example, the command:

PRINT, ACOS(A) * !RADEG

converts a result expressed in radians to one expressed in degrees.

!DPI

A read-only variable containing the double-precision value of pi ( π).

!DTOR

A read-only variable containing the floating-point value used to convert degrees to radians (π/180 ≅  0.01745).

!MAP

An array variable containing the information needed to effect coordinate conversions between points of latitude and longitude and map coordinates. The values in this array are established by the MAP_SET procedure; the user should not change them directly.

!PI

A read-only variable containing the single-precision value of pi ( π).

!RADEG

A read-only variable containing the floating-point value used to convert radians to degrees (180/π ≅ 57.2958).

!VALUES

A read-only variable containing the IEEE single- and double-precision floating-point values Infinity and NaN (Not A Number). !VALUES is a structure variable with the following fields:

** Structure !VALUES, 4 tags, length=24:

   F_INFINITY      FLOAT          Infinity

   F_NAN           FLOAT               NaN

   D_INFINITY      DOUBLE         Infinity

   D_NAN           DOUBLE              NaN

where Infinity is the value Infinity and NaN is the value Not A Number. (For more information on these special floating-point values, see "Special Floating-Point Values" on page 11-9 of the IDL User's Guide.)

Graphics System Variables

The following system variables control various IDL graphics functions. These system variables are structures that contain many tags; detailed information can be found in Chapter 2 of the IDL Reference Guide. For example, the command

!P.TITLE = 'Cross Section'

sets the default plot title.

!D

A structure variable that contains information about the current graphics device. See "!D System Variable" on page 2-15 of the IDL Reference Guide.

!ORDER

A long-integer variable specifying the direction of image transfer, bottom up (0), or top down (1). See "Image Orientation" on page 16-3.

!P

A structure variable that contains information about the plotting system. See "!P System Variable" on page 2-17 of the IDL Reference Guide.

!X, !Y, !Z

Structure variables of type AXIS, containing information on the appearance and scaling of the three axes. See "!X, !Y, !Z System Variables" on page 2-20 of the IDL Reference Guide.

Error Handling System Variables

The following system variables are either set by IDL when an error condition occurs or used by IDL when displaying information about errors.

!ERR

A long-integer variable containing the error code of the last error message. Note that !ERR can also be changed by IDL even when error conditions are not present.

!ERROR

A long-integer variable which always contains the error code of the last error message.

!ERR_STRING

A read-only string variable containing the text of last error message.

!MSG_PREFIX

A string variable containing the prefix string used for error messages.

!SYSERROR

A long-integer variable which always contains the error code of the last system error message.

!SYSERR_STRING

A read-only string variable containing the text of last system error message.

IDL Environment System Variables

The following system variables contain information about IDL's configuration.

!DIR

A string variable containing the path to the main IDL directory.

!EDIT_INPUT

An integer variable indicating whether keyboard line editing is enabled (1) or disabled (0). By default, line editing is enabled.

!JOURNAL

A read-only long-integer variable containing the logical unit number of the file used for journal output.

!MORE

An integer variable indicating whether IDL should paginate help output sent to a tty device. Setting !MORE to zero (0) prevents IDL from paginating the output text. A non-zero value (the default) causes IDL to display output text one screen at a time.

!PATH

A string variable listing the directories IDL will search for libraries, include files, and executive commands. See "Searching for Program Files" on page 2-15.

!PROMPT

A string variable containing the text string used by IDL to prompt the user for input. The default is IDL>.

!QUIET

A long-integer variable indicating whether informational messages should be printed (0) or suppressed (nonzero). By default, !QUIET is set to zero.

!VERSION

A structure variable containing information about the version of IDL in use. The structure is defined as follows:

{!VERSION, ARCH:'', OS:'', OS_FAMILY:'', RELEASE:''}

The ARCH field reports the type of CPU. The OS field reports the name of the operating system, and the OS_FAMILY field reports the general type of operating system. The RELEASE field reports the IDL version number.

In the unlikely event that you need to differentiate between different IDL versions in your code, use !VERSION.OS_FAMILY. At present, four operating system families are supported: MacOS, unix, vms, Windows. If for some reason you need even more detail, use !VERSION.OS. Operating system names used in the OS field are: A/UX, AIX, ConvexOS, DG/UX, hp-ux, IRIX, MacOS, OSF, RISC/os, sunos, ultrix, vms, Win32.

Jump forward to Expressions and Operators

Jump backward to Running IDL


Expressions and Operators
4	Expressions and Operators

Chapter Overview

Variables and constants can be combined into expressions by using operators and functions. Expressions are constructed to specify how results are obtained. Expressions can be combined with other expressions, variables, and constants, yielding more complex expressions. In IDL, unlike FORTRAN or BASIC, expressions can be scalar- or array-valued.

There are many types of operators in IDL. In addition to the usual operators—addition, subtraction, multiplication, division, exponentiation, relations (EQ, NE, GT, etc.), and Boolean arithmetic (AND, OR, NOT, and XOR)—operators exist to find minima, maxima, select scalars and subarrays from arrays (subscripting), and to concatenate scalars and arrays to form new arrays.

Functions, which are operators in themselves, perform operations that are usually of a more complex nature than those denoted by simple operators. Functions exist in IDL for data smoothing, shifting, transforming, evaluation of transcendental functions, and other operations.

Expressions can be arguments to functions or procedures. For example, the expression SIN(A*3.14159) evaluates expression A multiplied by the value of π, then applies the trigonometric sine function. This result can be used as an operand to form a more complex expression or as an argument to yet another function (e.g., EXP(SIN(A*3.14159)) evaluates esin πa).


Topics in Expressions and Operators Chapter
Expressions and Operators

This chapter provides an overview of IDL's operators and rules for creating IDL expressions.

Topics Covered:

Operator Precedence

Type and Structure of Expressions

Type Conversion Functions

Structure of Expressions

IDL Operators

Jump forward to Subscripts

Jump backward to Constants and Variables


Operator Precedence

IDL operators are divided into the levels of algebraic precedence found in common arithmetic. Operators with higher precedence are evaluated before those with lesser precedence, and operators of equal precedence are evaluated from left to right. Operators are grouped into five classes of precedence as shown in the following table.

Priority	Operator
First (highest)	^ (exponentiation)
Second	* (multiplication)
	# and ##  (matrix multiplication)
	/(division)
	MOD (modulus)
Third	+ (addition)
	- (subtraction and negation)
	< (minimum)
	> (maximum)
	NOT (Boolean negation)
Fourth	EQ (equality)
	NE (not equal)
	LE (less than or equal)
	LT (less than)
	GE (greater than or equal)
	GT (greater than)
Fifth	AND (Boolean AND)
	OR (Boolean OR)
	XOR (Boolean exclusive OR)
Table 4.1 Operator Precedence

For example, the expression 4 + 5 * 2 yields 14 because the multiplication operator has a higher precedence than the addition operator. Parentheses can be used to override the default evaluation. For example, (4 + 5) * 2 yields 18 because the expression inside the parentheses is evaluated first. A useful rule of thumb is, "when in doubt, parenthesize." Some examples of expressions are provided below.

A	The value of variable A.

A + 1	The value of A+1.

A < 2 + 1	The smaller of A or two, plus one.

A < 2 * 3	The smaller of A and six, since * has higher precedence than <.

2 * SQRT(A)	Twice the square root of A.

A + 'Thursday'	The concatenation of the strings A and "Thursday." An error results if A is not a string.


Type and Structure of Expressions

Every entity in IDL has an associated type and structure. The eight atomic data types in decreasing order of precedence are as follows:

•	Double-precision complex floating-point

•	Complex floating-point

•	Double-precision floating-point

•	Floating-point

•	Longword integer

•	Integer

•	Byte

•	String

The structure of an expression can be either a scalar or an array. The type and structure of an expression depends on the type and structure of its operands. Unlike many other languages, the type and structure of most expressions in IDL cannot be determined until the expression is evaluated. Because of this, care must be taken when writing programs. For example, a variable can be a scalar byte variable at one point in a program while at a later point it can be set to a complex array.

IDL attempts to evaluate expressions containing operands of different types in the most accurate manner possible. The result of an operation becomes the same type as the operand with the greatest precedence or potential precision. For example, when adding a byte variable to a floating-point variable, the byte variable is first converted to floating-point, then added to the floating-point variable, yielding a floating-point result. When adding a double-precision variable to a complex variable, the result is complex because the complex type has a higher position in the hierarchy of data types.

When writing expressions with mixed types, care must be taken to obtain the desired results. For example, assume the variable A is an integer variable with a value of 5. The following expressions yield the indicated results:

A / 2 = 2	Integer division is performed. The remainder is discarded.

A / 2. = 2.5	The value of A is first converted to floating.

A / 2 + 1. = 3.	Integer division is done first because of operator precedence. Result is floating point.

A / 2. + 1 = 3.5	Division is done in floating, then the 1 is converted to floating and added.

Note that when other types are converted to complex type, the real part of the result is obtained from the original value and the imaginary part is set to zero.

When a string type appears as an operand with a numeric data type, the string is converted to the type of the numeric term. For example: '123' + 123.0 is 246.0, while '123.333' + 33 gives the result 156 because 123.333 is first converted to integer type. In the same manner, 'ABC' + 123 also causes a conversion error.


Type Conversion Functions

IDL provides a set of functions that convert an operand to a specific type. These functions are useful in many instances, such as forcing the evaluation of an expression to a certain type, outputting data in a mode compatible with other programs, etc. The conversion functions are as follows:

Function	Description
STRING	Convert to string
BYTE	Convert to byte
FIX	Convert to (16-bit) integer
LONG	Convert to longword
FLOAT	Convert to floating-point
DOUBLE	Convert to double-precision floating-point
COMPLEX	Convert to complex value
DCOMPLEX	Convert to double-precision complex value
Table 4.2 Type Conversion Functions

For example, the result of the expression FIX(A) is of short (16-bit) integer type with the same structure (scalar or array) as the variable. The variable can be of any type. These conversion functions operate on data of any structure: scalars, vectors, or arrays. If it lies outside the range of single-precision integers (-32768 to +32,767), the result is truncated silently.

Caution: Not all implementations of IDL check for overflow in type conversions. On such a system, the statement

PRINT, FIX(66000)

prints the value 464, which is [image], with no indication that an error occurred. The FINITE and CHECK_MATH functions test floating-point results for valid numbers and the accumulated math error status, respectively. See Chapter 11 for details.

The statement:

A = FLOAT(A)

is perfectly legitimate in IDL. Its effect is to force the variable A to have floating-point type.

When converting from a string argument, it is possible that the string does not contain a valid number and no conversion is possible. The default action in such cases is to print a warning message and return zero. The ON_IOERROR procedure can be used to establish a statement to be jumped to in case of such errors.

Examples	Results
FLOAT(1)	1.0
FIX(1.3 + 1.7)	3
FIX(1.3) + FIX(1.7)	2
BYTE(1.2)	1
BYTE(-1)	255b (Bytes are modulo 256)
BYTE('01ABC')	[48b, 49b, 65b, 66b, 67b]
STRING([65B, 66B, 67B])	'ABC'
FLOAT(COMPLEX(1, 2))	1.0
COMPLEX([1, 2], [4, 5])	[COMPLEX(1,4),COMPLEX(2,5)]
Table 4.3 Example Uses of Type Conversion Functions

Special cases of type conversions occur when converting between strings and byte arrays. The result of the BYTE function applied to a string or string array is a byte array containing the ASCII codes of the characters of the string. Converting a byte array with the STRING function yields a string array or scalar with one less dimension than the byte array.

Extracting Fields

When called with more than a single parameter, the BYTE, FIX, LONG, FLOAT, and DOUBLE functions create an expression of the designated type by extracting fields from the input parameter without performing type conversion. COMPLEX and DCOMPLEX can also be used to extract data, but three arguments must be provided. The result is that the original binary information in the parameter is interpreted as being of the new type. This feature is handy for extracting fields of data of one type embedded in arrays or scalars of another type. The general form of the call is as follows:

Type_Conversion_Function (Expression, Offset[,Dim1, ..., Dimn])

where

Type_Conversion_Function

The name of one of the conversion functions listed above.

Expression

An array or scalar expression of any type from which the field is to be extracted.

Offset

Starting byte offset within expression of the field to be extracted. Zero is the first byte.

Dim1, ..., Dimn

The dimensions of the result. If these dimensions are omitted, the result is a scalar. If more than two parameters appear, the third and following parameters are the dimensions of the resulting array.

For example, assume file unit 1 is open for reading on a file containing 112-byte binary records containing the fields shown below:

Bytes	Type	Name
0-7	Double	Time
8	Byte	Type
9-10	Integer	Count
11-110	Floating	20 by 5 array
111	Byte	Quality
Table 4.4 Contents of a Sample File

The following program segment reads a record into an array and extracts the fields:

A = BYTARR(112) 	Define array variable to contain record, 112 bytes.

READU, 1, A 	Read the next record.

TIME = DOUBLE(A, 0) 	Extract TIME. Offset = 0, double precision.

TYPE = BYTE(A, 8)	Extract TYPE. Starting offset is 8.

COUNT = FIX(A, 9) 	COUNT, offset = 9, integer.

DATA = FLOAT(A, 11, 20, 5)	DATA = floating array, dimensions of 20 by 5, starting offset is 11 bytes.

QUALITY = BYTE(A, 111)	Last field, single byte.


Structure of Expressions

IDL expressions can contain operands with different structures, just as they can contain operands with different types. Structure conversion is independent of type conversion. An expression will yield an array result if any of its operands is an array, as shown in the following table:

Operands	Result
Scalar : Scalar	Scalar
Array : Array	Array
Scalar : Array	Array
Array : Scalar	Array
Table 4.5 Structure of Expressions

Seven functions exist to create arrays of the seven types: BYTARR, INTARR, LONARR, FLTARR, DBLARR, COMPLEXARR, and STRARR. The dimensions of the desired array are the parameters to these functions. The result of FLTARR(5) is a floating-point array with one dimension, a vector, with five elements initialized to zero. FLTARR(50,100) is a two-dimensional array, a matrix, with 50 columns and 100 rows.

The size of an array-valued expression is equal to the smaller of its array operands. For example, adding a 50-point array to a 100-point array gives a 50-point array, the last 50 points of the larger array are ignored. Array operations are performed point-by-point, without regard to individual dimensions. An operation involving a scalar and an array always yields an array of identical dimensions. When two arrays of equal size (number of elements) but different structure are operands, the result is of the same structure as the first operand. For example:

FLTARR(4) + FLTARR(1, 4)	Yields fltarr(4).

In the above example, a row vector is added to a column vector and a row vector is obtained because the operands are the same size. This causes the result to take the structure of the first operand. Here are some examples of expressions involving arrays:

ARR + 1	An array in which each element is equal to the same element in ARR plus one. The result has the same dimensions as ARR. If ARR is byte or integer, the result is of integer type; otherwise, the result is the same type as ARR.

ARR1 + ARR2	An array obtained by summing two arrays.

(ARR < 100) * 2 	An array in which each element is set to twice the smaller of either the corresponding element of ARR or 100.

EXP(ARR/10.)	An array in which each element is equal to the exponential of the same element of ARR divided by 10.

ARR * 3./MAX(ARR)	An inefficient way of writing the following line.

ARR * (3./MAX(ARR))

In the last example, each point in ARR is multiplied by three, then divided by the largest element of ARR. The MAX function returns the largest element of its array argument. This way of writing the statement requires that each element of ARR be operated on twice. If (3./MAX(ARR)) is evaluated with one division and the result then multiplied by each point in ARR, the process requires approximately half the time.


IDL Operators

As described above, operators are used to combine terms and expressions. IDL has the following types of operators:

Parentheses

Mathematical Operators

Minimum and Maximum Operators

Matrix Multiplication

Array Concatenation

Boolean Operators

Relational Operators


Parentheses

Parentheses are used to group expressions and to enclose subscript and function parameter lists. Parentheses can be used to override the order of operator evaluation described above. Examples:

ARRAY(X, Y)	Parentheses enclose subscripts.

SIN(ANG * PI/180.)	Parentheses enclose function argument lists.

(A + 5)/B	Parentheses specify order of operator evaluation.

The right parenthesis must always close the list begun by the left parenthesis.


Mathematical Operators

There are seven basic IDL mathematics operators, described below.

Assignment

The equal sign (=) is the assignment operator. The value of the expression on the right hand side of the equal sign is stored in the variable, subscript element, or range on the left side. See "The Assignment Statement" on page 6-3. Example:

A = 32	Assign the value of 32 to A.

Addition

The positive sign (+) is the addition operator. When applied to strings, the addition operator concatenates the strings. Examples:

B = 3 + 6	Assign the value of nine to B.

B = 'John' + ' ' + 'Doe'	Assign the string value of "John Doe" to B.

Subtraction and Negation

The negative sign (-) is the subtraction operator. Also, the minus sign is used as the unary negation operator. Examples:

C = 9 - 5	Assign the value of four to C.

C = -C	Change the sign of C.

Multiplication

The asterisk (*) is the multiplication operator. Example:

C = 2*5	Store the product of 2 and 5 in variable C.

Division

The forward slash (/) is the division operator. Example:

D = 10.0/3.2	Store the result of 10.0 divided by 3.2 in variable D.

Exponentiation

The caret (^) is the exponentiation operator. A^B is equal to A raised to the B power.

•	If A is a real number and B is of integer type, repeated multiplication is applied.

•	If A is real and B is real (non-integer), the formula A^B = e^(B ln A) is evaluated.

•	If A is complex and B is real, the formula A^B = (re^(iθ))^B = r^B * (cosBθ + isinBθ) (where r is the real part of A and iθ is the imaginary part) is evaluated.

•	If B is complex, the formula A^B = e^(B ln A) is evaluated. If A is also complex, the natural logarithm is computed to be ln(A) = ln(re^(iθ)) = ln(r) + iθ (where r is the real part of A and iθ is the imaginary part).

•	A^0 is defined as 1.

Modulo

The keyword MOD is the modulo operator. I MOD J is equal to the remainder when I is divided by J. When I or J are floating point, double precision, or complex, I MOD J equals I - J * [I/J] where "[x]" is the largest integer smaller than or equal to x. Example:

A = 9 MOD 5	A is set to four.

A =(ANGLE + B) MOD (2 * !PI)	Compute angle modulo 2π.


Minimum and Maximum Operators

The IDL minimum and maximum operators return the smaller or larger of their operands, as described below. Note that negated values must be enclosed in parentheses in order for IDL to interpret them correctly.

The Minimum Operator

The "less than" sign (<) is the IDL minimum operator. The value of "A < B" is equal to the smaller of A or B. Examples:

A = 5 < 3	A is set equal to 3.

A = 5 < (-6)	A is set equal to -6.

ARR = ARR < 100	Set all points in array ARR that are larger than 100 to 100.

X = X0 < X1 < X2	Set X to the smallest of the three operands.

The Maximum Operator

The "greater than" sign (>) is the IDL maximum operator. "A > B" is equal to the larger of A or B. Examples:

C = ALOG(D > 1E - 6)	Here, > is used to avoid taking the log of zero or negative numbers.

PLOT, ARR > 0	Plot positive points only. Negative points are plotted as zero.


Matrix Multiplication

IDL has two operators used to multiply arrays and matrices.

The # Operator

The # operator computes array elements by multiplying the columns of the first array by the rows of the second array. The resulting array has the same number of columns as the first array and the same number of rows as the second array. The second array must have the same number of columns as the first array has rows.

The ## Operator

The ## operator does what is commonly referred to as matrix multiplication. It computes array elements by multiplying the rows of the first array by the columns of the second array. The resulting array has the same number of rows as the first array and the same number of columns as the second array. The second array must have the same number of rows as the first array has columns.

For an example illustrating the difference between the two, see see "Multiplying Arrays" on page 20-6 of the IDL User's Guide.


Array Concatenation

The square brackets are used as array concatenation operators. Operands enclosed in square brackets and separated by commas are concatenated to form larger arrays. The expression [A, B] is an array formed by concatenating A and B, which can be scalars or arrays, along the first dimension.

Similarly, [A, B, C] concatenates A, B, and C. The second and third dimensions can be concatenated by nesting the bracket levels; [[1, 2], [3, 4]] is a 2-element by 2-element array with the first row containing 1 and 2 and the second row containing 3 and 4. Operands must have compatible dimensions; all dimensions must be equal except the dimension that is to be concatenated, (e.g., [2, INTARR(2, 2)]) are incompatible. Examples:

C = [-1, 1, -1]	Define C as three-point vector.

C = [C, 12]	Add 12 to the end of C.

C = [12, C]	Insert 12 at the beginning of C.

PLOT, [ARR1, ARR2]	Plot ARR2 appended to ARR1.

KER = [[1,2,1], [2,4,2], [1,2,1]] 	Define a 3x3 matrix.

Note: The maximum number of operands that can appear within brackets varies across IDL implementations but is always at least 25. This number is also influenced by the .SIZE executive command. If you must create an array of more than 25 elements using the concatenation operator, use multiple statements. For example, to create an array with 70-constant elements, use the following statements:

A = [k0, k1, ..., k24]

A = [A, k25, k26, ..., k49]

A = [A, k50, k51, ..., k69]

This method is relatively inefficient and should be performed only once if possible.


Boolean Operators

There are four Boolean operators in IDL. Boolean operators return either "true" or "false" as described previously. Note that the Boolean operators do not work with string and complex arguments.

Results of relational expressions can be combined into more complex expressions using the Boolean operators AND, OR, NOT, and XOR (Exclusive OR). The action of these operators is summarized in Table 4.6.

Operator	T op T	T op F	F op F
AND	T	F	F
OR	T	T	F
XOR	F	T	F
Table 4.6 Action of Boolean Operators

When applied to bytes, integers, and longword operands, the Boolean functions operate on each binary bit. (1 AND 7) is 1, (3 OR 5) is 7, (NOT 1) is -2 (twos-complement arithmetic) and (5 XOR 12) is 9. When applied to data types that are not integers, the Boolean operators yield the following results:

The expression OP1 AND OP2 equals OP2 if OP1 is true (not zero or the null string); otherwise false is returned (zero or the null string).

The expression OP1 OR OP2 equals OP2 if OP1 is false; otherwise OP1.

Some examples of relational and Boolean expressions are as follows:

(A LE 50) AND (A GE 25)	True if A is between 25 and 50. If it is an array, then the result is an array of zeros and ones.

(A GT 50) OR (A LT 25)	True if A is less than 25 or greater than 50. This is the inverse of the first.

ARR AND 'FF'X	Adds (using the logical AND operator) the hexadecimal constant FF (255 in decimal) to the array ARR. This masks the lower 8-bits and zeros the upper bits.

AND

AND is a Boolean operator that returns "true" whenever both of its operands are true; otherwise, the result is "false." Any nonzero value is considered true. For integer, longword, and byte operands, a bitwise AND operation is performed. For operations on other types, the result is equal to the second operand if the first operand is not equal to zero or the null string; otherwise, the result is zero or the null string.

NOT

The NOT operator is the Boolean inverse and is a unary operator because it has only one operand. In other words, "NOT true" is equal to "false" and "NOT false" is equal to "true." NOT complements each bit for integer operands. For floating-point operands, the result is 1.0 if the operand is zero; otherwise, the result is zero.

OR

OR is the Boolean inclusive operator. For integer or byte operands, a bitwise inclusive OR is performed. For example, 3 OR 5 equals 7. For floating-point operands, the OR operator returns the first operand if it is non-zero, or the 2nd operand otherwise.

XOR

XOR is the Boolean "exclusive or" function. XOR is only valid for integer operands. A bit in the result is set to 1 if the corresponding bits in the operands are different; if they are equal, it is set to zero.


Relational Operators

The IDL relational operators can be used to test the relationship between two arguments. The six relational operators are described in the following table:

Operator	Purpose
EQ	Equal to
NE	Not equal to
LE	Less than or equal to
LT	Less than
GE	Greater than or equal to
GT	Greater than
Table 4.7 Relational Operators

Relational operators apply a relation to two operands and return a logical value of true or false. The resulting logical value can be used as the predicate in IF, WHILE, or REPEAT statements or can be combined using Boolean operators with other logical values to make more complex expressions. For example: 1 EQ 1 is true, and 1 GT 3 is false.

The rules for evaluating relational expressions with operands of mixed modes are the same as those given above for arithmetic expressions. For example, in the relational expression (2 EQ 2.0), the integer 2 is converted to floating point and compared to the floating point 2.0. The result of this expression is true, as represented by a byte 1.

Individual relational operators are described at the end of this chapter—see "Relational Operators" on page 4-12.

Definition of True

In IDL, the value "true" is represented by the following:

•	Any odd, nonzero value for byte, integer, and longword data types

•	Any nonzero value for single, double-precision, and the real part of a complex number (the imaginary part is ignored)

•	Any non-null string

Conversely, false is represented as anything that is not true—zero or even-valued integers; zero-valued, floating-point quantities; and the null string.

The relational operators return a value of 1 for true and 0 for false. The type of the result is always byte.

Using Relational Operators with Arrays

Relational operators can be applied to arrays, and the resulting array of ones and zeroes can be used as an operand. For example, the expression:

ARR * (ARR LE 100)

is an array equal to ARR except that all points greater than 100 have been reduced to zero. The expression (ARR LE 100) is an array that contains a 1 where the corresponding element of ARR is less than or equal to 100, and zero otherwise.

The statement:

PRINT, TOTAL(ARR GT 0)

prints the number of positive elements in the array ARR.

The six relational operators are described below:

EQ

EQ is the relational "equal to" operator. This operator returns true if its operands are equal; otherwise, it returns false. This operator always returns a byte value of 1 for true and a byte value of 0 for false.

GE

GE is the "greater than or equal to" relational operator. The GE operator returns true if the operand on the left is greater than or equal to the one on the right. One use of relational operators is to mask arrays as shown in the following statement:

A = ARRAY * (ARRAY GE 100)

This command sets A equal to ARRAY whenever the corresponding element of ARRAY is greater than or equal to 100. If the element is less than 100, the corresponding element of A is set to zero.

Strings are compared using the ASCII collating sequence: " " is less than "0" is less than "9" is less than "A" is less than "Z" is less than "a" which is less than "z".

GT

GT is the "greater than" relational operator. This operator returns true if the operand on the left is greater than the operand on the right. For example,  6 GT 5 returns true.

LE

LE is the "less-than or equal-to" relational operator. This operator returns true if the operand on the left is less than or equal to the operand on the right. For example, 4 LE 4 returns true.

LT

LT is the "less-than" relational operator. This operator returns true if the operand on the left is less than the operand on the right. For example, 3 LT 4 returns true.

NE

NE is the "not-equal-to" relational operator. This operator returns true whenever the operands are different. For example "sun" NE "fun" returns true.

Jump forward to Subscripts

Jump backward to Constants and Variables


Subscripts
5	Subscripts

Chapter Overview

Subscripts provide a means of selecting one or more elements of an array for retrieval or modification.

The values of the selected array elements are extracted when a subscripted variable reference appears in an expression. New values are stored in selected array elements, without disturbing the remaining elements, when a subscript reference appears on the left side of an assignment statement. Chapter 6, "Statements," discusses the use of the different types of assignment statements when storing into arrays.

The subscripts of an array element denote the address of the element within the array. In the simple case of a one-dimensional array, an n-element vector, elements are numbered starting at 0 with the first element, 1 for the second element, and running to n − 1, the subscript of the last element.

Arrays with multiple dimensions are addressed by specifying a subscript expression for each dimension. A two-dimensional array, a matrix with n columns and m rows, is addressed with a subscript of the form (i, j), where 0  ≤ i < n and 0  ≤ j < m. The first subscript, i, is the column index; the second subscript, j, is the row index. The syntax of a subscript reference is:

Variable_Name (Subscript_ List)

or

(Array_Expression)(Subscript_List)

The Subscript_List is simply a list of expressions, constants, or subscript ranges containing the values of one or more subscripts. Subscript expressions are separated by commas if there is more than one subscript. In addition, multiple elements are selected with subscript expressions that contain either a contiguous range of subscripts or an array of subscripts.


Topics in Subscripts Chapter
Subscripts

This chapter provides an overview of how subscripts are used to manipulate IDL arrays.

Topics Covered:

Subscript Examples

Subscript Ranges

Structure of Subarrays

Array Subscripts

Combining Array Subscripts with Others

Storing Elements with Array Subscripts

Jump forward to Statements

Jump backward to Expressions and Operators


Subscript Examples

Subscripts can be used either to retrieve the value of one or more array elements or to designate array elements to receive new values. The expression ARR(12) denotes the value of the 13-th element of ARR (because subscripts start at 0), while the statement ARR(12) = 5 stores the number 5 in the 13-th element of ARR without changing the other elements.

Elements of multidimensional arrays are specified by using one subscript for each dimension. In arrays and images, the first subscript denotes the column and the second subscript is the row. For matrices, the first subscript denotes the row and the second subscript is the column.

If A is a 2-element by 3-element array, the elements are stored in memory as follows:

A(0,0)	A(1,0)	Lowest memory address
A(0,1)	A(1,1)	. . .
A(0,2)	A(1,2)	Highest memory address
Table 5.1 Storage of IDL Array Elements in Memory

The elements are ordered in memory as: A(0,0), A(1,0), A(0,1), A(1,1), A(0,2), A(1,2), etc. Thus, IDL arrays are row major (i.e., stored by rows). This ordering is like FORTRAN. It is the opposite of the way C and Pascal handle arrays. IDL uses row major storage because it is oriented toward image processing while the other languages stress matrix computation. For a more extensive discussion of row versus column majority and how it relates to IDL mathematics routines, see "Arrays and Matrices" on page 20-4.

Images are usually displayed with row zero at the bottom of the screen, matching the display's coordinate system, although this order can be reversed by setting the system variable !ORDER to a nonzero value. Note that arrays are printed with the first row on top.

Elements of multidimensional arrays also can be specified using only one subscript, in which case the array is treated as a vector with the same number of points. In the above example, A(2) is the same element as A (0, 1), and A(5) is the same element as A (1, 2).

If an attempt is made to reference a nonexistent element of an array using a scalar subscript (a subscript that is negative or larger than the size of the dimension minus 1), an error occurs and program execution stops.

Subscripts can be any type of vector or scalar expression. If a subscript expression is not integer, a longword integer copy is made and used to evaluate the subscript.

"Extra" Dimensions

When creating arrays, IDL eliminates all "degenerate" trailing dimensions of size 1. Thus, the statements

A = INTARR(10, 1)

HELP, A

print the following:

A               INT       = Array(10)

This removal of superfluous dimensions is usually convenient, but it can cause problems when attempting to write fully general procedures and functions. Therefore, IDL allows you to specify "extra" dimensions for an array as long as the extra dimensions are all zero. For example, consider a vector defined as follows:

ARR = INDGEN(10)

The following are all valid references to the sixth element of ARR:

X = ARR(5)

X = ARR(5, 0)

X = ARR(5, 0, 0, *, 0)

Thus, the automatic removal of degenerate trailing dimensions does not cause problems for routines that attempt to access the resulting array.

Subscripting Scalars

References to scalars can be subscripted. All subscripts must be zero. For example, the following statements print the value of 5, then assign the scalar variable A a value of 6.

A = 5

PRINT, A(0)

A(0) = 6


Subscript Ranges

Subscript ranges are used to select a subarray from an array by giving the starting and ending subscripts of the subarray in each dimension. Subscript ranges can be combined with scalar and array subscripts and with other subscript ranges. Any rectangular portion of an array can be selected with subscript ranges. There are four types of subscript ranges:

•	A range of subscripts, written (e0:e1), denoting all elements whose subscripts range from the expression  e0 through e1 (e0 must not be greater than e1). For example, if the variable VEC is a 50-element vector, VEC(5:9) is a five-element vector composed of VEC(5) through VEC(9).

•	All elements from a given element to the last element of the dimension, written as (e:*). Using the above example, VEC(10:*) is a 40-element vector made from VEC(10) through VEC(49).

•	A simple subscript, (n). When used with multidimensional arrays, simple subscripts specify only elements with subscripts equal to the given subscript in that dimension.

•	All elements of a dimension, written (*). This form is used with multidimensional arrays to select all elements along the dimension. For example, if ARR is a 10-column by 12-row array, ARR(*, 11) is the last row of ARR, composed of elements [ARR(0,11), ARR(1,11), ..., ARR(9,11)], and is a 10-element row vector. Similarly, ARR(0, *) is the first column of ARR, [ARR(0,0), ARR(0,1),..., ARR(0,11)], and its dimensions are 1 column by 12 rows.

Multidimensional subarrays can be specified using any combination of the above forms. For example, ARR(*, 0:4) is made from all columns of rows 0 to 4 of ARR or a 10-column, 5-row matrix. The table below summarizes the possible forms of subscript ranges:

Form	Meaning
e	A simple subscript expression
e 0:e 1	Subscript range from e 0 to e 1
e:*	All points from element e to end
*	All points in the dimension
Table 5.2 Subscript Ranges


Structure of Subarrays

The dimensions of the extracted subarray are determined by the size in each dimension of the subscript range expression. In general, the number of dimensions is equal to the number of subscripts and subscript ranges. The size of the n-th dimension is equal to one if a simple subscript was used to specify that dimension in the subscript; otherwise, it is equal to the number of elements selected by the corresponding range expression.

Degenerate dimensions (trailing dimensions whose size is equal to one) are removed. This was illustrated in the previous example by the expression ARR(*,11) which resulted in a row vector with a single dimension because the last dimension of the result was one and was removed. On the other hand, the expression ARR(0, *) became a column vector with dimensions of (1, 12) showing that the structure of columns is preserved because the dimension with a size of one does not appear at the end.

Using the examples of VEC, a 50-element vector, and A, a 10-column by 12-row array, some typical subscript range expressions are as follows:

VEC(5:10)	Elements 5 through 10 of VEC, a six-element vector.

VEC((I - 1:I + 1)	A three-element vector.

[VEC(I - 1), VEC(I), VEC(I + 1)]

VEC(4:*)	Elements of VEC from VEC(4) to the end, a 46-element (50 - 4) vector.

A(3, *)	The fourth column of A, a 1 row by 12 column vector.

[A(3, 0), A(3, 1), ..., A(3, 11)]

A(*, 0)	The first row of A, a 10-element row vector. Note, the last dimension was removed because it was degenerate.

A(X - 1:X + 1, Y - 1:Y + 1)	The nine-point neighborhood surrounding A(X,Y), a 3 by 3 array.

A(3:5,*)	Three columns of A, a 3 by 12 subarray:

See "The Assignment Statement" on page 6-3 for a description of the process of assigning values to subarrays.


Array Subscripts

Arrays can be used as subscripts to other arrays. Each element in the array used as a subscript selects an element in the subscripted array. When used with subscript ranges, more than one element may be selected for each subscript element.

If no subscript ranges are present, the length and structure of the result is the same as that of the subscript expression. The type of the result is the same as that of the subscripted array. If only one subscript is present, all subscripts are interpreted as if the subscripted array has one dimension.

In the simple case of only one subscript, in which the subscript is an array, the process can be written as follows:

The vector V has n elements, and S has m elements. The result V(S) has the same structure and number of elements as does the subscript vector S.

If an element of the subscript array is less than or equal to zero, the first element of the subscripted variable is selected. If an element of the subscript is greater than or equal to the last subscript in the subscripted variable (N, above), the last element is selected.

Example

As an example, consider the commands:

A = [6, 5, 1, 8, 4, 3]

B = [0, 2, 4, 1]

C = A(B)

PRINT, C

that produce the following output:

6 1 4 5

The first element of C is 6 because that is the number in the 0 position of A. The second is 1 because the value in B of 2 indicates the third position in A, and so on.

As another example, assume the variable A is a 10 by 10 array. The expression A(INDGEN(10) * 11) yields a 10-element vector equal to the diagonal elements of A. The subscripts of the diagonal elements, A(0,0), A(1,1), ..., A(9, 9) are equal to 0, 11, 22, 99, when singularly subscripted. The elements of the vector INDGEN(10)*11 also are equal to 0, 11, 22, ..., 99. Applying the vector as a subscript selects the diagonal elements.

The WHERE function, which returns a vector of subscripts, can be used to select elements of an array using expressions similar to A(WHERE(A GT 0)) which results in a vector composed only of the elements of A that are greater than 0.


Combining Array Subscripts with Others

Array subscripts can be combined with subscript ranges, simple scalar subscripts and other array subscripts.

When IDL encounters a multidimensional subscript that contains one or more subscript arrays, it builds an array of subscripts by processing each subscript from left to right. The resulting array of subscripts is then applied to the variable that is to be subscripted. As with other subscript operations, trailing degenerate dimensions (those with a size of 1) are eliminated.

Subscript Ranges

When combining an array subscript with a subscript range, the result is an array of subscripts constructed by combining each element of the subscript array with each member of the subscript range. Combining an n-element array with an m-element subscript range yields an nm-element subscript. Each dimension of the result is equal to the number of elements in the corresponding subscript array or range.

For example, the expression A([1, 3, 5], 7:9) is a nine-element, 3 x 3 array composed of the following elements:

Each element of the three-element subscript array (1, 3, 5) is combined with each element of the three-element range (7, 8, 9).

Another example shows the common process of zeroing the edge elements of a two-dimensional n x m array:

A(*, [0, M-1]) = 0	Zero the first and last rows.

A([0, N - 1], *) = 0	Zero the first and last columns.

Other Subscript Arrays

When combining two subscript arrays, each element of the first array is combined with the corresponding element of the other subscript array. The two subscript arrays must have the same number of elements. The resulting subscript array has the same number of elements as its constituents. For example, the expression  A([1, 3], [5, 9]) yields the elements A(1,5) and A(3,9).

Scalars

Combining an n-element subscript range or n-element subscript array with a scalar yields an n-element result. The value of the scalar is combined with each element of the range or array. For example, the expression A([1, 3, 5], 8) yields the three-element vector composed of the elements A(1,8), A(3,8), and A(5,8). The second dimension of the result is 1 and is eliminated because it is degenerate. The expression A(8, [1, 3, 5]) is the 1 x 3-column vector A(8,1), A(8,3), and A(8,5), illustrating that leading dimensions are not eliminated.


Storing Elements with Array Subscripts

One or more values can be stored in selected elements of an array by using an array expression as a subscript for the array on the left side of an assignment statement. Values are taken from the expression on the right side of the assignment statement and stored in the elements whose subscripts are given by the array subscript. The right-hand expression can be either a scalar or array.

The subscript array is converted to longword type before use if necessary. Regardless of structure, this subscript array is interpreted as a vector. For details and examples of storing with vector subscripts, see "Assignment Statement" on page 6-3.

Examples

The statement:

A([2, 4, 6]) = 0

zeroes elements A(2), A(4), and A(6), without changing other elements of A. The statement:

A([2, 4, 6]) = [4, 16, 36]

stores 4 in A(2), 16 in A(4), and 36 in A(6).

One way to create a square n x n identity matrix is as follows:

A = FLTARR(N, N)

A(INDGEN(N) * (N + 1)) = 1.0

The expression INDGEN(N)*(N + 1) results in a vector containing the subscripts of the diagonal elements [0, N+1, 2N+2, ..., (N-1)*(N+1)]. Yet another way is to use two array subscripts. The statements:

A = FLTARR(N, N)

A(INDGEN(N), INDGEN(N)) = 1.0

create the array subscripts [(0,0), (1,1), ..., (n-1, n-1)]. The statement:

A(WHERE(A LT 0)) = -1

sets negative elements of A to -1.

The statements:

A = FLTARR(10, 10)

A(INDGEN(10) * 11) = 1

create a ten by ten identity matrix.

Jump forward to Statements

Jump backward to Expressions and Operators


Statements
6	Statements

Chapter Overview

IDL programs, procedures, and functions are composed of one or more valid statements. Most simple IDL statements can also be entered in the immediate mode in response to the IDL> prompt. The thirteen types of IDL statements are as follows:

•	Assignment

•	Block

•	Case

•	Common Block Definition

•	For

•	Forward Function Definition

•	Function Definition

•	Goto

•	If

•	Procedure Call

•	Procedure Definition

•	Repeat

•	While


Topics in Statements Chapter
Statements

This chapter provides an overview of IDL statement types.

Topics Covered:

Components of Statements

The Assignment Statement

Blocks

CASE Statement

Common Blocks

FOR Statement

Function Definition Statement

GOTO Statement

IF Statement

Procedure Call Statement

Procedure Definition Statement

REPEAT Statement

WHILE Statement

Jump forward to Structures

Jump backward to Subscripts


Components of Statements

Statements in IDL can consist of any combination of three parts:

•	A label field

•	The statement proper

•	A comment field

Spaces and tabs can appear anywhere except in the middle of an identifier or numeric constant.

Statement Labels

Labels are the destinations of GOTO statements as well as the ON_ERROR and ON_IOERROR procedures. The label field, which must appear before the statement or comment, is simply an identifier followed by a colon. A line can consist of only a label field. Label identifiers, as with variable names, consist of 1 to 15 alphanumeric characters and are case insensitive. The dollar sign ($) and underscore (_) characters can appear after the first character. Some examples of labels are as follows:

LABEL1:

LOOP_BACK: A = 12

I$QUIT: RETURN   ;Comments are allowed.

Comments

The comment field, which is ignored by IDL, begins with a semicolon and continues to the end of the line. Lines can consist of only a comment field or can be entirely blank. It is good programming practice to fully annotate programs with comments. There are no execution-time or space penalties for comments in IDL.

The following IDL statement shows a simple assignment statement with a comment field:

COUNT = 5    ;Set variable COUNT to 5. This is the comment field.


The Assignment Statement

The assignment statement stores a value in a variable. There are four forms of the assignment statement as shown in Table 6.1

Syntax	Subscript Structure	Expression Structure	Effect
Variable = Expression	None	All	Expression is stored in Variable
Variable(Subscripts) = Expression	Scalar	Scalar	Expression is stored in a single element of Variable
	Scalar	Array	Expression array is inserted in Variable array
	Array	Scalar	Expression scalar is stored in designated elements of Variable
	Array	Array	Elements of Expression are stored in designated elements of Variable
Variable(Range) =  Expression	Range	Scalar	Scalar is inserted into subarray
	Range	Array	Illegal
Table 6.1 Types of Assignment Statements

In addition, in the second and fourth cases, an array can be used as a subscript. This stores the values from the right side of the statement into elements of the variable designated by the contents of the array subscript.

The Basic Assignment Statement

The first, and most basic, form of the assignment statement is as follows:

Variable = Expression

The old value of the variable, if any, is discarded, and the value of the expression is stored in the variable. The expression on the right side can be of any type or structure.

Examples

Some examples of the basic form of the assignment statement are as follows:

MMAX = 100 * X + 2.987	Set MMAX to value.

NAME = 'Mary '	NAME becomes a scalar string variable.

ARR = FLTARR(100)	Make ARR a 100-element, floating-point array.

ARR = ARR(50:*)	Discard points 0 to 49 of ARR. It is now a 50-element array.

The Second Form of the Assignment Statement

The second type of assignment statement has the following form:

Variable(Subscripts) = Scalar_Expression

Here, a single element of the specified array is set to the value of the scalar expression. The expression can be of any type and is converted, if necessary, to the type of the variable. The variable on the left side must be either an array or a file variable. Some examples of assigning scalar expressions to subscripted variables are shown below:

DATA(100) = 1.234999	Set element 100 of DATA to value.

NAME(INDEX) = 'Joe '	Store string in an array. NAME must be a string array or an error will result.

IMAGE(X, Y) = PIXEL	Set element (X, Y) of the 2-dimensional array IMAGE to the value contained in PIXEL.

Using Array Subscripts with the Second Form of the Assignment Statement

The subscripted variable can have either a scalar or array subscript. If the subscript expression is an array, the scalar value is stored in the elements of the array whose subscripts are elements of the subscript array. For example, the statement

DATA([3, 5, 7, 9]) = 0

zeroes the four specified elements of DATA: DATA(3), DATA(5), DATA(7) and DATA(9).

The subscript array is converted to longword type if necessary before use. Elements of the subscript array that are negative, or greater than the highest subscript of the subscripted array, are clipped to the target array boundaries. Note that a common error is to use a negative scalar subscript (e.g., A(-1)). Using this type of subscript causes an error. Negative array subscripts (e.g., A([-1])) do not cause errors.

The WHERE function can be used to select array elements to be changed. For example, the statement:

DATA(WHERE(DATA LT 0)) = -1

sets all negative elements of DATA to -1 without changing the positive elements. The result of the function, WHERE(DATA LT 0), is a vector composed of the subscripts of the negative elements of DATA. Using this vector as a subscript changes only the negative elements.

The Third Form of the Assignment Statement

The third type of assignment statement is similar to the second, except the subscripts specify a range in which all elements are set to the scalar expression.

Variable(Subscript_Range) = Scalar_Expression

A subscript range specifies a beginning and ending subscript. The beginning and ending subscripts are separated by the colon character. An ending subscript equal to the size of the dimension minus one can be written as *.

For example, ARR(I:J) denotes those points in the vector ARR with subscripts between I and J inclusive. I must be less than or equal to J and greater than or equal to zero. J denotes the points in ARR from ARR(I) to the last point and must be less than the size of the dimension  ARR (I:*). Consult Chapter 5 for more details on subscript ranges.

Examples

Assuming the variable B is a 512 x 512-byte array, some examples are as follows:

B(*, I) = 1	Store 1 in every element of the i-th row.

B(J, *) = 1	Store 1 in every element of the j-th column.

B(200:220, *) = 0	Zero all the rows of columns 200 through 220 of the array B.

B(*) = 100	Store the value 100 in all the elements of array B.

The Fourth Form of the Assignment Statement

The fourth type of assignment statement is of the following form:

Variable(Subscripts) = Array

Note that this form is syntactically identical to the second type of assignment statement, but that the expression on the right-hand-side is an array instead of a scalar. This form of the assignment statement is used to insert one array into another.

The array expression on the right is inserted into the array appearing on the left side of the equal sign starting at the point designated by the subscripts.

Examples

For example, to insert the contents of an array called A into array B, starting at point B(13, 24), use the following statement:

B(13, 24) = A

If A is a 5-column by 6-row array, elements B(13:17, 24:29) are replaced by the contents of array A.

In the next example, a subarray is moved from one position to another with the statement:

B(100, 200) = B(200:300, 300:400)

A subarray of B, specifically the columns 200 to 300 and rows 300 to 400, is moved to columns 100 to 200 and rows 200 to 300, respectively.

Using Array Subscripts with the Fourth Form of the Assignment Statement

If the subscript expression applied to the variable is an array and an array appears on the right side of the statement:

Variable(Array) = Array

then elements from the right side are stored in the elements designated by the subscript vector. Only those elements of the subscripted variable whose subscripts appear in the subscript vector are changed. For example, the statement

B([ 2, 4, 6 ]) = [4, 16, 36]

is equivalent to the following series of assignment statements:

B(2) = 4

B(4) = 16

B(6) = 36

Subscript elements are interpreted as if the subscripted variable is a vector. For example, if A is a 10 x n matrix, the element A(i, j) has the subscript i+10*j. The subscript array is converted to longword type before use, if necessary.

As described previously for the second form of assignment statement, elements of the subscript array that are negative or larger than the highest subscript are clipped to the target array boundaries. Note that a common error is to use a negative scalar subscript (e.g., A(-1)). Using this type of subscript causes an error. Negative array subscripts (e.g., A([-1])) do not cause errors.

As another example, assume that the vector DATA contains data elements and that a data drop-out is denoted by a negative value. In addition, assume that there are never two or more adjacent drop-outs. The following statements replace all drop-outs with the average of the two adjacent good points:

BAD = WHERE(DATA LT 0)	Subscript vector of drop-outs.

DATA(BAD) = (DATA(BAD - 1) + DATA(BAD + 1)) / 2
Replace drop-outs with average of previous and next point.

In this example, the following actions are performed:

•	Elements of the vector BAD are set to the subscripts of the points of DATA that are drop-outs using the WHERE function. The WHERE function returns a vector containing the subscripts of the nonzero elements of its parameter, (DATA LT 0). This Boolean expression is a vector that is nonzero when the elements of DATA are negative and zero if the elements are positive.

•	The expression DATA(BAD - 1) is a vector which contains the subscripts of the points immediately preceding the drop-outs; while similarly, the expression DATA(BAD + 1) is a vector containing the subscripts of the points immediately after the drop-outs.

•	The average of these two vectors is stored in DATA(BAD), the points that originally contained drop-outs.

Associated Variables in Assignment Statements

A special case occurs when using an associated file variable in an assignment statement. For additional information regarding the ASSOC function, see its description on page 17-36. When a file variable is referenced, the last (and possibly only) subscript denotes the record number of the array within the file. This last subscript must be a simple subscript. Other subscripts and subscript ranges, except the last, have the same meaning as when used with normal array variables.

An implicit extraction of an element or subarray in a data record can also be performed. For example:

A = ASSOC(1, FLTARR(200))	Variable A associates the file open on unit 1 with  the  records of 200-element, floating-point vectors.

X = A(0:99, 2)	Then, X is set to the first 100 points of record number 2,  the third record of the file.

A(23, 16) = 12	Set the 24th point of record 16 to 12.

A(10, 12) = A(10:*, 12)+1	Increment points 10 to 199 of record 12. Points 0 to 9 of the record remain unchanged.


Blocks

A block of statements is simply a group of statements that are treated as a single statement. For example, a group of statements can be bracketed with BEGIN and END statements:

BEGIN

Statement1

...

Statementn

END

Blocks are necessary when more than one statement is the subject of a conditional or repetitive statement, as in the FOR, WHILE, and IF statements. In general, the format of a FOR statement with a block subject is as follows:

FOR Variable = Expression, Expression DO BEGIN

Statement1

Statement2

...

...

...

Statementn

ENDFOR

All the statements between the BEGIN and the END are the subject of the FOR statement. The group of statements is executed as a single statement and is called a compound statement. Blocks can be nested within other blocks.

Syntactically, a block of statements is composed of one or more statements of any type, started by a BEGIN identifier and ended by an END identifier. IDL allows the use of blocks wherever a single statement is allowed. As an example, the process of reversing an array in place might be written as follows:

FOR I = 0,(N - 1)/2 DO BEGIN
T = ARR(I)
ARR(I) = ARR(N - I - 1)
ARR(N - I - 1) = T
ENDFOR

Note that the code shown above is for illustration only. The IDL REVERSE function is much more efficient.

The three statements between the BEGIN and ENDFOR are the subject of the FOR statement, and each will be executed once during each iteration of the loop. If the statements are not enclosed in a block, only the first statement (T = ARR(I)) is executed during each iteration, and the remaining two statements are executed only once after the termination of the FOR statement.

To ensure proper nesting of compound statements (one or more different blocks), the "END" statement terminating the block can be followed by the block type as shown in Table 6.2. The compiler checks the end of each block, comparing it with the type of the enclosing statement. Any block can be terminated by the generic END, although no type checking is performed.

END Statement	Use
ENDCASE	CASE statement
ENDELSE	IF statement, ELSE clause
ENDFOR	FOR statement
ENDIF	IF statement, THEN clause
ENDREP	REPEAT statement
ENDWHILE	WHILE statement
Table 6.2 Types of END Statements

Listings produced by the IDL compiler indent each block four spaces to the right of the previous level to make the program structure easier to read.


CASE Statements
CASE Statement

The CASE statement is used to select one, and only one, statement for execution, depending upon the value of the expression following the word CASE. This expression is called the case selector expression. The general form of the CASE statement is as follows:

CASE Expression OF

Expression: Statement

...

...

...

...

Expression: Statement

ELSE: Statement

ENDCASE

Each statement that is part of a CASE statement is preceded by an expression that is compared to the value of the selector expression. If a match is found, the statement is executed and control resumes directly below the CASE statement.

The ELSE clause of the CASE statement is optional. If included, it must be the last clause in the case statement. The statement after the ELSE is executed only if none of the preceding statement expressions match. If the ELSE is not included and none of the values match, an error occurs and program execution stops.

Example

An example of the CASE statement follows:

CASE NAME OF

'Linda ': PRINT, 'sister '	If NAME is "Linda," print "sister."

'John ': PRINT, 'brother '	If NAME is "John," print "brother."

'Harry ': PRINT, 'step-brother '	If NAME is "Harry," print "step-brother".

ELSE: PRINT, 'Not a sibling.'	No matches, print "Not a sibling."

ENDCASE	End of CASE statement.

Another example shows the CASE statement with the number 1 as the selector expression of the CASE. One is equivalent to true and is matched against each of the conditionals.

CASE 1 OF

(X GT 0) AND (X LE 50): Y = 12 * X + 5

(X GT 50) AND (X LE 100): Y = 13 * X + 4

(X LE 200): BEGIN

              Y = 14 * X - 5

              Z = X + Y

            END

ELSE: PRINT, 'X has an illegal value.'

ENDCASE

In this CASE statement, only one clause is selected, and that clause is the first one whose value is equal to the value of the case selector expression. Each clause is tested in order, so it is most efficient to order the most frequently selected clauses first.


Statements
Common Blocks

Common blocks are useful when there are variables that need to be accessed by several IDL procedures or when the value of a variable within a procedure must be preserved across calls. Once a common block has been defined, any program unit referencing that common block can access variables in the block as though they were local variables. Variables in a common statement have a global scope within procedures defining the same common block. Unlike local variables, variables in common blocks are not destroyed when a procedure is exited.

There are two types of common block statements: definition statements and reference statements.

Common Block Definition Statements

The common block definition statement creates a common block with the designated name and places the variables whose names follow into that block. Variables defined in a common block can be referenced by any program unit that declares that common block. The general form of the COMMON block definition statement is as follows:

COMMON Block_Name, Variable1, Variable2, ..., Variablen

The number of variables appearing in the common block definition statement determines the size of the common block. The first program unit (main program, function, or procedure) defining the common block sets the size of the common block, which can never be expanded. Other program units can reference the common block with any number of variables up to the number originally specified. Different program units can give the variables different names, as shown in the example below.

Common blocks share the same space for all procedures. In IDL, common block variables are matched variable to variable, unlike FORTRAN, where storage locations are matched. The third variable in a given IDL common block will always be the same as the third variable in all declarations of the common block regardless of the size, type, or structure of the preceding variables.

Note that common blocks must appear before any of the variables they define are referenced in the procedure.

Variables in common blocks can be of any type and can be used in the same manner as normal variables. Variables appearing as parameters cannot be used in common blocks. There are no restrictions on the number of common blocks used, although each common block uses dynamic memory.

Example

The two procedures in the following example show how variables defined in common blocks are shared.

PRO ADD, A
COMMON SHARE1, X, Y, Z, Q, R
A = X + Y + Z + Q + R
PRINT, X, Y, Z, Q, R, A
RETURN END

PRO SUB, T
COMMON SHARE1, A, B, C, D
T = A - B - C - D
PRINT, A, B, C, D, T
RETURN
END

The variables X, Y, Z, and Q in the procedure ADD are the same as the variables A, B, C, and D, respectively, in procedure SUB. The variable R in ADD is not used in SUB. If the procedure SUB were to be compiled before the procedure ADD, an error would occur when the COMMON definition in ADD was compiled. This is because SUB has already declared the size of the common block, SHARE1, which cannot be extended.

Common Block Reference Statements

The common block reference statement duplicates the common block and variable names from a previous definition. The common block need only be defined in the first routine to be compiled that references the block.

Example

The two procedures in the following example share the common block SHARE2 and all its variables.

PRO MULT, M
COMMON SHARE2, E, F, G
M = E * F * G
PRINT, M, E, F, G
RETURN
END

PRO DIV, D
COMMON SHARE2
D = E / F
PRINT, D, E, F, G
RETURN
END

The MULT procedure uses a common block definition statement to define the block SHARE2. The DIV procedure then uses a common block reference statement to gain access to all the variables defined in SHARE2.


FOR Statement

The FOR statement is used to execute one or more statements repeatedly, while incrementing or decrementing a variable with each repetition, until a condition is met. It is analogous to the DO statement in FORTRAN.

In IDL, there are two types of FOR statements: one with an implicit increment of 1 and the other with an explicit increment. If the condition is not met the first time the FOR statement is executed, the subject statement is not executed.

FOR Statement with an Increment of One

The FOR statement with an implicit increment of one is written as follows:

FOR Variable = Expression, Expression DO Statement

The variable after the FOR is called the index variable and is set to the value of the first expression. The subject statement is executed, and the index variable is incremented by 1 until the index variable is larger than the second expression. This second expression is called the limit expression. Complex limit and increment expressions are converted to floating-point type.

Caution: The data type of the index variable is determined by the type of the initial value expression. Keep this fact in mind to avoid the following:

FOR I = 0, 50000 DO ... ...

This loop does not produce the intended result. Converting the longword constant 50,000 to a short integer yields −15,536 because of truncation. The loop is not executed. The index variable's initial value is larger than the limit variable. The loop should be written as follows:

FOR I = 0L, 50000 DO ... ...

Example—Simple FOR Statement

An example of a FOR statement is:

FOR I = 1, 4 DO PRINT, I, I^2

which produces the following output:

1    1

2    4

3    9

4   16

The index variable I is first set to an integer variable with a value of one. The call to the PRINT procedure is executed, then the index is incremented by one. This is repeated until the value of I is greater than four at which point execution continues at the statement following the FOR statement.

Example—FOR Statement with a Block Subject

The next example displays the use of a block structure (instead of a single statement) as the subject of the FOR statement. The example is a common process used for computing a count-density histogram. Note: A HISTOGRAM function is provided by IDL.

FOR K = 0, N - 1 DO BEGIN

   C = A(K)

    HIST(C) = HIST(C)+1

ENDFOR

Example—FOR Statement with Floating-Point Index and Limit Expressions

Another example is:

FOR X = 1.5, 10.5 DO S = S + SQRT(X)

where X is set to a floating-point variable and steps through the values (1.5, 2.5, ..., 10.5).

The indexing variables and expressions can be integer, longword, floating-point, or double-precision. The type of the index variable is determined by the type of the first expression after the "=" character.

Warning

Note that due to the inexact nature of IEEE floating-point numbers, using floating-point indexing can cause "infinite loops" and other problems. This problem is also manifested in both the C and FORTRAN programming languages. For example, the numbers 0.1, 0.01, 1.6, and 1.7 do not have exact representations under the IEEE standard. To see this phenomenon, enter the following IDL command:

PRINT, 0.1, 0.01, 1.6, 1.7, FORMAT='(f20.10)'

IDL prints the following approximations to the numbers we requested:

0.1000000015

0.0099999998

1.6000000238

1.7000000477

FOR Statement with Variable Increment

The format of the second type of FOR statement is as follows:

FOR Variable = Expression1, Expression2, Expression3 DO Statement

This form is used when an increment other than 1 is desired.

The first two expressions describe the range of numbers for the index variable. The third expression specifies the increment of the index variable. A negative increment allows the index variable to step downward. In this case, the first expression must have a value greater than that of the second expression. If not, an almost infinite loop will result.

Examples

The following examples demonstrate the second type of FOR statement.

FOR K = 100.0, 1.0, -1  DO ...	Decrement, K has the values 100., 99., ..., 1.

FOR LOOP = 0, 1023, 2       DO ...	Increment by 2., LOOP has the values 0., 2., 4., ..., 1022.

FOR MID = BOTTOM, TOP, (TOP - BOTTOM)/4.0 DO ...
Divide range from BOTTOM to TOP by 4.

Caution: If the value of the increment expression is zero, an infinite loop occurs. A common mistake resulting in an infinite loop is a statement similar to the following:

FOR X = 0, 1, .1 DO ....

The variable X is first defined as an integer variable because the initial value expression is an integer zero constant. Then the limit and increment expressions are converted to the type of X, integer, yielding an increment value of zero because .1 converted to integer type is 0. The correct form of the statement is:

FOR X = 0., 1, .1 DO ....

which defines X as a floating-point variable.

Operation of the FOR Statement

The FOR statement performs the following steps:

1.	The value of the first expression is evaluated and stored in the specified variable, which is called the index variable. The index variable is set to the type of this expression.

2.	The value of the second expression is evaluated, converted to the type of the index variable, and saved in a temporary location. This value is called the limit value.

3.	The value of the third expression, called the step value, is evaluated, type-converted if necessary, and stored. If omitted, a value of 1 is assumed.

4.	If the index variable is greater than the limit value (in the case of a positive step value) the FOR statement is finished and control resumes at the next statement. Similarly, in the case of a negative step value, if the index variable is less than or equal to the limit value, control resumes after the FOR statement.

5.	The statement or block following the DO is executed.

6.	The step value is added to the index variable.

7.	Steps 4, 5, and 6 are repeated until the test of Step 4 fails.


Function Definition Statement

FUNCTION Function_Name, Parameter1, Parameter2, ..., Parametern

A function is a program unit containing one or more IDL statements that returns a value. This unit executes independently of its caller. It has its own local variables and execution environment. Once a function has been defined, references to the function cause the program unit to be executed. All functions return a function value which is given as a parameter in the RETURN statement used to exit the function. Function names can be up to 128 characters long.

The general format of a function definition is as follows:

FUNCTION Name, Parameter1, ..., Parametern
Statement1
Statement2
...
...
RETURN, Expression
END

Example

For example, to define a function called AVERAGE, which returns the average value of an array, use the following statements:

FUNCTION AVERAGE, ARR
RETURN, TOTAL(ARR)/N_ELEMENTS(ARR)
END

Once the function AVERAGE has been defined, it is executed by entering the function name followed by its arguments enclosed in parentheses. Assuming the variable X contains an array, the statement,

PRINT, AVERAGE(X^2)

squares the array X, passes this result to the AVERAGE function, and prints the result. Parameters passed to functions are identified by their position or by a keyword. See "Keyword Parameters" on page 6-19. For further details about user-defined functions, see Chapter 10.

Automatic Compilation

IDL automatically compiles and executes a user-written function or procedure when it is first referenced if (1) the source code of the function is in the current working directory or in a directory in the IDL search path defined by the system variable !PATH, and (2) the name of the file containing the function is the same as the function name suffixed by .pro. Under UNIX, the .pro suffix should be in lowercase letters.

Caution: User-written functions must be defined before they are referenced, unless they meet the above conditions for automatic compilation or the function name has been reserved by using the FORWARD_FUNCTION statement described below. This restriction is necessary in order to distinguish between function calls and subscripted variable references.

Forward Function Definition

As mentioned above, ambiguities can arise between function calls and array references when a function has not yet been compiled, or there is no file with the same name as the function found in the IDL path.

For example, attempting to compile the IDL statement:

a = XYZ(1, COLOR=1)

will cause an error if the user-written function XYZ has not been compiled and the filename xyz.pro is not found in the IDL path. IDL reports a syntax error, because XYZ is interpreted as an array variable instead of a function name.

This problem can be eliminated by using the FORWARD_FUNCTION statement. This statement has the following syntax:

FORWARD_FUNCTION Name1, Name2, ..., NameN

where Name is the name of a function that has not yet been compiled. Any names declared as forward-defined functions will be interpreted as functions (instead of as variable names) for the duration of the IDL session.

For example, we can resolve the ambiguity in the previous example by adding a FORWARD_FUNCTION definition:

FORWARD_FUNCTION XYZ	Define XYZ as the name of a function that has not yet been compiled.

a = XYZ(1, COLOR=1)	IDL now understands this statement to be a function call instead of a bad variable reference.


GOTO Statement

GOTO, Label

The GOTO statement is used to transfer program control to a point in the program specified by the label. The GOTO statement is generally considered to be a poor programming practice that leads to unwieldy programs. Its use should be avoided. However, for those cases in which the use of a GOTO is appropriate, IDL does provide the GOTO statement.

Note that using a GOTO to jump into the middle of a loop results in an error.

Caution: The user must be careful in programming with GOTO statements. It is not difficult to get into a loop that will never terminate, especially if there is not an escape (or test) within the statements spanned by the GOTO.

Examples

An example of the GOTO statement follows:

GOTO, JUMP1
Statements ...
...
...
...
JUMP1: X = 2000 + Y

In the above example, the statement at label JUMP1 is executed after the GOTO statement, skipping any intermediate statements. Note that the label could also occur before the GOTO statement that refers to the label.

GOTO statements are frequently the subjects of IF statements, as seen in the statement below:

IF A NE G THEN GOTO, MISTAKE


IF Statement

IF Expression THEN Statement
IF Expression THEN Statement ELSE Statement

The IF statement is used to conditionally execute a statement or a block of statements.

The expression after the "IF" is called the condition of the IF statement. This expression (or condition) is evaluated, and if true, the statement following the "THEN" is executed. If the expression evaluates to a false value, the statement following the "ELSE" clause is executed. Control passes immediately to the next statement if the condition is false and the ELSE clause is not present.

Examples

Examples of the IF statement include the following:

IF A NE 2 THEN PRINT, 'A IS NOT TWO '
IF A EQ 1 THEN PRINT, 'A IS ONE' ELSE PRINT, 'NOT ONE '

The first example contains no ELSE clause. If the value of A is not equal to 2, "A IS NOT TWO" is printed. If A is equal to 2, the THEN clause is ignored, nothing is printed, and execution resumes at the next statement. In the second example above, the condition of the IF statement is (A EQ 1). If the value of A is equal to 1, "A IS ONE" is printed; otherwise, "NOT ONE" is printed.

Definition of True and False

The condition of the IF statement can be any scalar expression. The definition of true and false for the different data types is as follows:

•	Byte, integer, and long: odd integers are true, even integers are false.

•	Floating-Point, double-precision floating-point, and complex: non-zero values are true, zero values are false. The imaginary part of complex numbers is ignored.

•	String: any string with a nonzero length is true, null strings are false.

Example

In the following example, the logical statement for the condition is a conjunction of two conditions.

IF (LON GT -40) AND (LON LE -20) THEN ...

If both conditions (LON being larger than -40 and less than or equal to -20) are true, the statement following the THEN is executed.

Using Statement Blocks with the IF Statement

The THEN and ELSE clauses can be in the form of a block (or group of statements) with the delimiters BEGIN and END (see "Blocks" on page 6-7). To ensure proper nesting of blocks, you can use ENDIF and ENDELSE to terminate the block, instead of using the generic END. Below is an example of the use of blocks within an IF statement.

IF (I NE 0.0) THEN BEGIN
...
...
...
ENDIF ELSE BEGIN
...
...
...
ENDELSE 	End of else clause.

Nesting IF Statements

IF statements can be nested in the following manner:

IF P1 THEN S1 ELSE $
IF P2 THEN S2 ELSE $
...
...
IF PN THEN SN ELSE SX

If condition P1 is true, only statement S1 is executed; if condition P2 is true, only statement S2 is executed, etc. If none of the conditions are true, statement SX will be executed. Conditions are tested in the order they are written. The construction above is similar to the CASE statement except that the conditions are not necessarily related.


Procedure Call Statements
Procedure Call Statement

Procedure_Name, Parameter1, Parameter2, ..., Parametern

The procedure call statement invokes a system, user-written, or externally-defined procedure. The parameters that follow the procedure's name are passed to the procedure. When the called procedure finishes, control resumes at the statement following the procedure call statement. Procedure names can be up to 128 characters long.

Procedures can come from the following sources:

•	System procedures provided with IDL.

•	User-written procedures written in IDL and compiled with the .RUN command.

•	User-written procedures that are compiled automatically because they reside in directories in the search path. These procedures are compiled the first time they are used. See "Function Definition Statement" on page 6-14.

•	Procedures written in IDL, that are included with the IDL distribution, located in directories that are specified in the search path.

•	Under many operating systems, user-written system procedures coded in FORTRAN, C, or any language that follows the standard calling conventions, which have been dynamically linked with IDL using the LINKIMAGE or CALL_EXTERNAL procedures.

Examples

Some procedures can be called without any parameters. For example:

ERASE

This is a procedure call to a subroutine to erase the screen. There are no explicit inputs or outputs. Other procedures have one or more parameters. For example, the statement:

PLOT, CIRCLE

calls the PLOT procedure with the parameter CIRCLE.

Parameter Passing

Parameters passed to procedures and functions are identified by their position or by a keyword. As their name indicates, the position of positional parameters establishes the correspondence of the parameters in the call and those in the definition of the procedure or function. A keyword parameter is a parameter preceded by a keyword and "=" that identifies the parameter.

Parameters are passed by value or by reference. Parameters that consist of only a variable name are passed by reference. Expressions, constants, and system variables are passed by value. The two passing mechanisms are fundamentally different. The called procedure or function cannot return a value in a parameter that is passed by value, as the value of the parameter is evaluated and passed into the called procedure, but is not copied back to the caller. Changes made by the called procedure are passed back to the caller if the parameter is passed by reference. See "Parameter Passing Mechanism" on page 10-7.

Parameters can be of any type or structure, although some system procedures, as well as user-defined procedures, may require a particular type of parameter for a specific argument. Parameters also can be expressions which are evaluated, used in the call, and then discarded. For example:

PLOT, SIN(CIRCLE)

The sine of the array CIRCLE is computed and plotted, then the result of the computation is discarded.

Keyword Parameters

A keyword parameter is a parameter preceded by a keyword and "=" that identifies the parameter.

For example, the PLOT procedure can be manipulated to retain, rather than erase, the image on the screen, as well as to draw, using color index 12. Accomplish these tasks with either of the following calls:

PLOT, X, Y, NOERASE = 1, COLOR = 12

or

PLOT, X, Y, COL = 12, /NOERASE

The two calls produce identical code. Keywords can be abbreviated to the shortest nonambiguous string. The construct /KEYWORD is equivalent to setting the keyword parameter to the value 1. For example, /NOERASE is equivalent to NOERASE = 1. In the above examples, the parameter X is the first positional parameter because it is not preceded by a keyword. The parameter Y is the second positional parameter.

The interpretation of keyword arguments is independent of their order. The placement of keyword arguments does not affect the interpretation of positional parameters —keyword parameters can appear before, after, or in the middle of the positional parameters.

Keyword parameters offer the following advantages over positional parameters:

•	Procedures and functions can have a large number of arguments, any of which may be optional. Only those arguments that are actually used need be present in the call.

•	It is much easier to remember the names of keyword arguments than to remember the order of positional arguments.

•	Additional features can be added to existing procedures and functions without changing the meaning or interpretation of other arguments.


Procedure Definition Statement

PRO Procedure_Name, Parameter1, Parameter2, ..., Parametern

A sequence of one or more IDL statements can be given a name, compiled, and saved for future use with the procedure definition statement. Once a procedure has been successfully compiled, it can be executed using a procedure call statement interactively from the terminal, from a main program, or from another procedure or function.

The general format for the definition of a procedure is as follows:

PRO Name, Parameter1, ..., Parametern

Statement1	Statements defining procedure.

Statement2

...

...

RETURN	Done, return to caller.

END	End of procedure definition.

For more detail on defining procedures see Chapter 10.

Calling a user-written procedure that is in a directory in the IDL search path (!PATH) causes the procedure to be read from the disc, compiled, saved, and executed without interrupting program execution.


REPEAT Statement

REPEAT Subject_Statement UNTIL Condition_Expression

The REPEAT statement repetitively executes its subject statement until a condition is true. The condition is checked after the subject statement is executed. Therefore, the subject statement is always executed at least once.

Examples

Some examples of how the REPEAT statement can be used are as follows:

A = 1

REPEAT A = A * 2 UNTIL A GT B

This code finds the smallest power of 2 that is greater than B. The subject statement can also be in the form of a block:

REPEAT BEGIN	Sort array.

NOSWAP = 1	Set flag to true.

FOR I = 0, N - 2 DO IF ARR(I) GT ARR(I + 1)THEN BEGIN

NOSWAP = 0	Swapped elements, clear flag.

T = ARR(I) & ARR(I) = ARR(I + 1) & ARR(I + 1) = T

ENDIF

ENDREP UNTIL NOSWAP	Keep going until nothing is moved.

The above example sorts the elements of ARR using the inefficient bubble sort method. A more efficient way to sort elements is to use IDL's SORT function.


WHILE Statement

WHILE Expression DO Statement

WHILE statements are used to execute a statement repeatedly while a condition remains true. The WHILE statement is similar to the REPEAT statement except that the condition is checked prior to the execution of the statement.

When the WHILE statement is executed, the conditional expression is tested, and if it is true, the statement following the DO is executed. Control then returns to the beginning of the WHILE statement, where the condition is again tested. This process is repeated until the condition is no longer true, at which point the control of the program resumes at the next statement.

In the WHILE statement, the subject is never executed if the condition is initially false.

Examples

An example of a WHILE statement follows:

WHILE NOT EOF(1) DO READF, 1, A, B, C

In this example, data are read until the end-of-file is encountered.

The next example demonstrates one way to find the first point of an array greater than or equal to a selected value assuming the array is sorted into ascending order.

I = 0	Initialize index.

WHILE (ARR(I) LT X) AND (I LT N) DO I = I + 1
Increment X until a point larger than X is found or the end of the array is reached

Another way to accomplish the same thing is with the WHERE command, which is used to find the subscripts of the points where ARR(I) is greater than or equal to X.

P = WHERE(ARR GE X)	Subscripts of elements of ARR that are greater than or equal to X.

I = P(0)	Save first subscript.

Jump forward to Structures

Jump backward to Subscripts


Structures
7	Structures

Chapter Overview

IDL supports structures and arrays of structures. A structure is a collection of scalars, arrays, or other structures contained in a variable. Structures are useful for representing data in a natural form, transferring data to and from other programs, and containing a group of related items of various types. There are two types of structures; they have similar features.

Named Structures

Each distinct type of named structure is defined by a unique structure name. The first time a structure name is used, IDL creates and saves a definition of the structure which cannot be changed. Each structure definition consists of the structure's name and a definition of each field that is a member of the structure. Each instance of a named structure shares the same definition. Named structures are used when their definitions will not be changed.

Anonymous Structures

If a structure definition contains no name, an anonymous structure is created. A unique structure definition is created for each anonymous structure. Use anonymous structures when the structure, type, and/or dimensions of its components change during program execution.

Each field definition consists of a tag name and a tag definition that contains the type and structure of the data contained in the field. A field is referred to by its tag name. The tag definition is simply an expression or variable. The type, structure, and value of the tag definition serve to define the field's type, structure, and value. As with structure definitions, a field definition is fixed and cannot be changed. The contents of a field can be any type of data representable by IDL. Fields can contain scalars, arrays of the seven basic data types, and even other structures or arrays of structures.


Topics in Structures Chapter
Structures

This chapter provides an overview of IDL data structures.

Topics Covered:

Creating and Defining Structures

Structure References

Using HELP with Structures

Parameter Passing with Structures

Arrays of Structures

Structure Input/Output

Advanced Structure Usage

Jump forward to Strings

Jump backward to Statements


Creating and Defining Structures

A named structure is created by executing a structure-definition expression, which is an expression of the following form:

{Structure_Name, Tag_Name1 : Tag_Definition1, ..., Tag_Namen : Tag_Definitionn}

Anonymous structures are created in the same way, but with the structure's name omitted.

{Tag_Name1 : Tag_Definition1 , ..., Tag_Namen : Tag_Definitionn}

Anonymous structures can also be created and combined using the CREATE_STRUCT function.

Note that a given structure can contain up to 127 fields.

Tag names must be unique within a given structure, although the same tag name can be used in more than one structure. Structure names and tag names follow the rules of IDL identifiers: they must begin with a letter; following characters can be letters, digits, or the underscore or dollar sign characters; and case is ignored.

As mentioned above, each tag definition is a constant, variable, or expression whose structure defines the structure and initial value of the field. The result of the structure definition expression is an instance of the structure, with each field set equal to its tag definition.

A named structure that has already been defined can be referred to by simply enclosing the structure's name in braces, as shown below:

{Structure_Name}

The result of this expression is a structure of the designated name with all of its fields filled with zeros or null strings.

Also, when making a named structure that has already been defined, the tag names need not be present:

{Structure_Name, expression1, ..., expressionn}

All of the expressions must agree in structure with the original tag definition.

Once defined, a given named structure type cannot be changed. If a structure definition with tag names is executed and the structure already exists, each tag name and the structure of each tag field must agree with the original definition. Anonymous structures do not have this restriction because each instance has its own definition.

Example of Creating a Structure

Assume that a star catalog is to be processed. Each entry for a star contains the following information: star name, right ascension, declination, and an intensity measured each month over the last 12 months. A structure for this information is defined with the following IDL statement:

A = {STAR, NAME: '', RA: 0.0, DEC: 0.0, INTEN: FLTARR(12)}

This structure definition is the basis for all examples in this chapter. The statement above defines a structure type named STAR, which contains four fields. The tag names are NAME, RA, DEC, and INTEN. The first field, with the tag NAME, contains a scalar string as given by its tag definition. The following two fields each contain floating-point scalars. The fourth field, INTEN, contains a 12-element, floating-point array. Note that the type of the constants, 0.0, is floating point. If the constants had been written as 0, the fields RA and DEC would contain short integers.

 The same structure is created as an anonymous structure by the statement:

A ={NAME: '', RA: 0.0, DEC: 0.0, INTEN: FLTARR(12)}

or by using the CREATE_STRUCT function:

A = CREATE_STRUCT('NAME', '', 'RA', 0.0, 'DEC', 0.0, 'INTEN', FLTARR(12))


Structure References

The basic syntax of a reference to a field within a structure is as follows:

Variable_Name.Tag_Name

Variable_Name must be a variable that contains a structure. Tag_Name is the name of the field and must exist in the structure. If the field referred to by the tag name is itself a structure, the Tag_Name can optionally be followed by one or more additional tag names, as shown by the following example:

VAR.TAG1.TAG2

This nesting of structure references can be continued up to 10 levels. Each tag name, except possibly the last, must refer to a field that contains a structure.

Subscripted Structure References

A subscript specification can be appended to the variable or tag names if the variable is an array of structures or if the field referred to by the tag contains an array. Scalar fields within a structure can also be subscripted, provided the subscript is zero.

Variable_Name.Tag_Name(Subscripts)

Variable_Name(Subscripts).Tag_Name...

Variable_Name(Subscripts).Tag_Name(Subscripts)

Each subscript is applied to the variable or tag name it immediately follows. The syntax and meaning of the subscript specification is similar to simple array subscripting in that it can contain a simple subscript, array of subscripts, or a subscript range. If a variable or field containing an array is referenced without a subscript specification, all elements of the item are affected. Similarly, when a variable that contains an array of structures is referenced without a subscript but with a tag name, the designated field in all array elements is affected. The complete syntax of references to structures follows. (Optional items are enclosed in square brackets, [].)

Structure_reference:= Variable_Name[(Subscripts)].Tags

Tags:= [Tags.]Tag

Tag:= Tag_Name[(Subscripts)]

For example, all of the following are valid structure references:

A.B
A.B(N, M)
A(12).B
A(3:5).B(*, N)
A(12).B.C(X, *)

The semantics of storing into a structure field using subscript ranges is slightly different than that of simple arrays. This is because the structure of arrays in fields are fixed. See "Storing Into Array Fields" on page 7-6.

Examples of Structure References

The name of the star contained in A is referenced as A.NAME. The entire intensity array is referred to as A.INTEN, while the n-th element of A.INTEN is A.INTEN(N). The following are valid IDL statements using the STAR structure:

A = {STAR, NAME: 'SIRIUS', RA: 30., DEC: 40., INTEN:INDGEN(12)}
Store a structure of type STAR into variable A. Define the values of all fields.

A.NAME = 'BETELGEUSE' 	Set name field. Other fields remain unchanged.

PRINT, A.NAME, A.RA, A.DEC	Print name, right ascension, and declination.

Q = A.INTEN(5)	Set Q to the value of the sixth element of A.INTEN. Q will be a floating-point scalar.

A.RA = 23.21	Set RA field to 23.21.

A.INTEN = 0 	Zero all 12 elements of intensity field. Because the type and size of A.INTEN are fixed by the structure definition, the semantics of assignment statements is somewhat different than with normal variables.

B = A.INTEN(3:6)	Store fourth through seventh elements of INTEN field in variable B.

A.NAME = 12	The integer 12 is converted to string and stored in the name field because the field is defined as a string.

B = A	Copy A to B. The entire structure is copied and B contains a STAR structure.


Using HELP with Structures

Use the HELP,/STRUCTURE command to determine the type, structure, and tag name of each field in a structure. In the example above, a structure was stored into variable A. The statement,

HELP, /STRUCTURE, A

prints the following information:

** Structure STAR, 4 tags, length=40:
   NAME            STRING    'SIRIUS'
   RA              FLOAT           30.0000
   DEC             FLOAT           40.0000
   INTEN           INT       Array(12)

Using HELP with anonymous structures prints the structure's name as a unique number enclosed in angle brackets. Calling HELP with the STRUCTURE keyword and no parameters prints a list of all defined, named structure types and their tag names.


Parameter Passing with Structures

An entire structure is passed by reference by simply using the name of the variable containing the structure as a parameter. Changes to the parameter within the procedure are passed back to the calling procedure. Fields within a structure are passed by value. For example, the following statement prints the value of the structure field A.NAME:

PRINT, A.NAME

Any reference to a structure with a subscript or tag name is evaluated into an expression, hence A.NAME is an expression and is passed by value. This works as expected unless the called procedure returns information in the parameter. For example, the call

READ, A.NAME

does not read into A.NAME but interprets its parameter as a prompt string. The proper code to read into the field is as follows.

B = A.NAME	Copy type and attributes to variable.

READ, B	Read into a simple variable.

A.NAME = B	Store result into field.

Storing Into Array Fields

As mentioned previously, the semantics of storing into structure array fields is slightly different than storing into simple arrays. The main difference is that with structures, a subscript range must be used when storing an array into part of an array field. With normal arrays, when storing an array inside part of another array, use the subscript of the lower-left corner, not a range specification. Other differences occur because the size and type of a field are fixed by the original structure definition, and the normal IDL semantics of dynamic binding are not applicable. The rules for storing into array fields are as follows:

VAR.ARRAY_TAG = Scalar_Expression

All elements of VAR.TAG are set to Scalar_Expression. For example:

A.INTEN = 100	Sets all 12 elements of A.INTEN to 100.

VAR.TAG = Array_Expression

Each element of Array_Expression is copied into the array VAR.TAG. If Array_Expression contains more elements than the destination array does, an error results. If it contains fewer elements than VAR.TAG, the unmatched elements remain unchanged. For example:

A.INTEN = FINDGEN(12)	Sets A.INTEN to the 12 numbers 0, 1, 2,..., 11.

A.INTEN = [1, 2]	Sets A.INTEN(0) to 1 and A.INTEN(1) to 2. The other elements remain unchanged.

VAR.TAG(Subscript) = Scalar_Expression

The value of the scalar expression is simply copied into the designated element of the destination. If Subscript is an array of subscripts, the scalar expression is copied into the designated elements. For example:

A.INTEN(5) = 100	Sets the sixth element of A.INTEN to 100.

A.INTEN([2, 4, 6]) = 100	Sets elements 2, 4, and 6 to 100.

VAR.TAG(Subscript) = Array_Expression

Unless VAR.TAG is an array of structures, the subscript must be an array. Each element of Array_Expression is copied into the element given by the corresponding element subscript. For example:

A.INTEN([2, 4, 6]) = [5, 7, 9]	Sets elements 2, 4, and 6 to the values 5, 7, and 9 respectively.

VAR.TAG(Subscript_Range) = Scalar_Expression

The value of the scalar expression is stored into each element specified by the subscript range. For example:

A.INTEN(8:*) = 5	Sets elements 8, 9, 10, and 11 to the value 5.

VAR.TAG(Subscript_Range) = Array_Expression

Each element of the array expression is stored into the element designated by the subscript range. The number of elements in the array expression must agree with the size of the subscript range. For example:

A.INTEN(3:6) = FINDGEN(4)	Sets elements 3, 4, 5, and 6 to the numbers 0, 1, 2, and 3, respectively.


Arrays of Structures

An array of structures is simply an array in which each element is a structure of the same type. The referencing and subscripting of these arrays (also called structure arrays) follow the same rules as simple arrays.

Creating an Array of Structures

The easiest way to create an array of structures is to use the REPLICATE function. The first parameter to REPLICATE is a reference to the structure of each element. Using the example on page 7-5 (star catalog) and assuming the STAR structure has been defined, an array containing 100 elements of the structure is created with the following statement:

CAT = REPLICATE({STAR}, 100)

Alternatively, since the variable A contains an instance of the structure STAR, then

CAT = REPLICATE(A, 100)

Or, to define the structure and an array of the structure in one step, use the following statement:

CAT = REPLICATE({STAR, NAME: '', RA: 0.0, DEC: 0.0, $

INTEN: FLTARR(12)}, 100)

The concepts and combinations of subscripts, subscript arrays, subscript ranges, fields, nested structures, etc., are quite general and lead to many possibilities, only a small number of which can be explained here. In general, any structures that are similar to the examples above are allowed.

Examples of Arrays of Structures

This example uses the above definition in which the variable CAT contains a star catalog of STAR structures.

CAT.NAME = 'EMPTY'	Set the NAME field of all 100 elements to "EMPTY."

CAT(I) = {STAR, 'BETELGEUSE', 12.4, 54.2, FLTARR(12)}
Set the i-th element of CAT to the contents of the STAR structure.

CAT.RA = INDGEN(100)	Store 0.0 into CAT(0).RA, 1.0 into CAT(1).RA, ..., 99.0 into CAT(99).RA

PRINT, CAT.NAME + ','	Prints name field of all 100 elements of CAT, separated by commas (the last field has a trailing comma).

I = WHERE(CAT.NAME EQ 'SIRIUS')	Find index of star with name of SIRIUS.

Q = CAT.INTEN	Extract intensity field from each entry. Q will be a 12 by 100 floating-point array.

PLOT, CAT(5).INTEN	Plot intensity of sixth star in array CAT.

CONTOUR, CAT(5:50).INTEN(2:8)	Make a contour plot of the (7,46) floating-point array taken from months (2:8) and stars (5:50).

CAT = CAT(SORT(CAT.NAME))	Sort the array into ascending order by names. Store the result back into CAT.

MONTHLY = CAT.INTEN # REPLICATE(1,100)
Determine the monthly total intensity of all stars in array. MONTHLY is now a 12-element array.


Structure Input/Output

Structures are read and written using the formatted and unformatted input/output procedures READ, PRINT, READU, and WRITEU. Structures and arrays of structures are transferred in much the same way as simple data types, with each element of the structure transferred in order.

Formatted Input/Output with Structures

Writing a structure with PRINT or PRINTF and the default format outputs the contents of each element using the default format for the appropriate data type. The entire structure is enclosed in braces: "{}." Each array begins a new line. For example, printing the variable A, as defined in the first example in this chapter, results in the following output.

{SIRIUS 30.0000 40.0000 0 1 2 3 4 5 6 7 8 9 10 11}

When reading a structure with READ or READF and the default format, white space should separate each element. Reading string elements causes the remainder of the input line to be stored in the string element, regardless of spaces, etc. A format specification can be used with any of these procedures to override the default formats. The length of string elements is determined by the format specification (i.e, to read the next 10 characters into a string field, use an (A10) format).

Unformatted Input/Output with Structures

Reading and writing unformatted data contained in structures is a straightforward process of transferring each element, without interpretation or modification, except in the case of strings. Each IDL data type, except strings, has a fixed length expressed in bytes. This length (which is padded when using ASSOC, but not padded when using READU/WRITEU) is also the number of bytes read or written for each element.

All instances of structures contain an even number of bytes. On machines whose native C compilers force short integers to begin on an even byte boundary, IDL begins fields that are not of type byte on an even byte boundary. Thus, a "padding byte" may appear (when using ASSOC for I/O) after a byte field to cause the following non-byte-type field to begin on an even byte. A padding byte is never added before a byte or byte array field. For example, the structure:

{EXAMPLE, T1: 1B, T2: 1}

occupies four bytes on a machine where short integers must begin on an even byte boundary. When using ASSOC, a padding byte is added after field T1 to cause the integer field T2 to begin on an even-byte boundary.

Strings

Strings are exceptions to the above rules because the length of strings within structures is not fixed. For example, one instance of the {STAR} structure can contain a NAME field with a five-character name, while another instance of the same structure can contain a 20-character name. When reading into a structure field that contains a string, IDL reads the number of bytes given by the length of the string. If the string field contains a 10-character string, 10 characters are read. If the data read contains a null byte, the length of the string field is truncated, and the null and following characters are discarded. When writing fields containing strings with the unformatted procedure WRITEU, IDL writes each character of the string and does not append a terminating null byte.

String Length Issues

When reading or writing structures containing strings with READU and WRITEU, make each string in a given field the same length to be compatible with C and to be able to read the data back into IDL. You must know how many characters exist to read into a string element. One way around this problem is using the STRING function with a format specification that sets the length of all elements to some maximum number. For example, it is easy to set the length of all NAME fields in the CAT array to 20 characters by using the following statement.

CAT.NAME = STRING(CAT.NAME, FORMAT = '(A20)')

This statement will truncate names longer than 20 characters and will pad with blanks those names shorter than 20 characters. The structure or structure array then can be output in a format suitable to be read by C or FORTRAN programs. For example, to read into the CAT array from a file in which each NAME field occupies 26 bytes, use the following statements.

CAT = REPLICATE({STAR, STRING(' ', FORMAT = '(A26)'), $

FLTARR(0., 0.12)}, 100)	Make a 100-element array of {STAR} structures, storing a 26-character string in each NAME field.

READU, 1, CAT	Read the structure. As mentioned above, 26 bytes will be read for each NAME field. The presence of a null byte in the file will truncate the field to the correct number of bytes.


Advanced Structure Usage

Facilities exist to process structures in a general way using tag numbers rather than tag names. A tag can be referenced using its index, enclosed in parentheses, as follows:

Variable_Name.(Tag_Index)... ... ...

The Tag_Index ranges from zero to the number of fields minus one.

Number of Structure Tags

The function N_TAGS(Structure) returns the number of fields in a structure. To obtain the size, in bytes, of a structure call N_TAGS with the /LENGTH keyword.

Names of Structure Tags

The function TAG_NAMES(Structure) returns a string array containing the names of each tag. To return the name of the structure itself, call TAG_NAMES with the /STRUCTURE_NAME keyword.

Example

Using tag indices and the above-mentioned functions, we specify a procedure that reads into a structure from the keyboard. The procedure prompts the user with the type, structure, and tag name of each field within the structure.

PRO READ_STRUCTURE, S	A procedure to read into a structure, S, from the keyboard with prompts.

NAMES = TAG_NAMES(S)	Get the names of the tags. Loop for each field.

FOR I = 0, N_TAGS(S) - 1 DO BEGIN

A = S.(I) 	Define variable A of same type and structure as the i-th field.

HELP, S.(I) 	Use HELP to print the attributes of the field. Prompt user with tag name of this field, and then read into variable A. S.(I) = A. Store back into structure from A.

READ, 'Enter Value For Field ', NAMES(I), ': ', A

ENDFOR

END

Note, in the above procedure, the READ procedure reads into the variable A rather than S.(I) because S.(I) is an expression, not a simple variable reference. Expressions are passed by value; variables are passed by reference. The READ procedure prompts the user with parameters passed by value and reads into parameters passed by reference.

Jump forward to Strings

Jump backward to Statements


Strings
8	Strings

Chapter Overview

An IDL string is a sequence of characters from 0 to 32,767 characters in length. Strings have dynamic length (they grow or shrink to fit), and there is no need to declare the maximum length of a string prior to using it. As with any data type, string arrays can be created to hold more than a single string. In this case, the length of each individual string in the array depends only on its own length and is not affected by the lengths of the other string elements.

A Note About the Examples

In some of the examples in this chapter, it is assumed that a string array named TREES exists. TREES contains the names of seven trees, one name per element, and is created using the statement:

TREES = ['Beech', 'Birch', 'Mahogany', 'Maple', 'Oak', $

         'Pine', 'Walnut']

Executing the statement,

PRINT, '>' + TREES + '< '

results in the following output:

>Beech<  >Birch<  >Mahogany<  >Maple<  >Oak<  >Pine<  >Walnut<


Topics in Strings Chapter
Strings

This chapter provides an overview of IDL's string-handling facilities.

Topics Covered:

String Operations

Non-string and Non-scalar Arguments to String Routines

String Concatenation

Using STRING to Format Data

Byte Arguments and Strings

Case Folding

Whitespace

Finding the Length of a String

Substrings

Jump forward to Vector-Drawn Fonts

Jump backward to Structures


String Operations

IDL supports several basic string operations, as described below.

Concatenation

The addition operator, "+", can be used to concatenate strings together.

Formatting Data

The STRING function is used to format data into a string. The READS procedure can be used to read values from a string into IDL variables.

Case Folding

The STRLOWCASE function returns a copy of its string argument converted to lowercase. Similarly, the STRUPCASE function converts its argument to uppercase.

White Space Removal

The STRCOMPRESS and STRTRIM functions can be used to eliminate unwanted white space (blanks or tabs) from their string arguments.

Length

The STRLEN function returns the length of its string argument.

Substrings

The STRPOS, STRPUT, and STRMID routines locate, insert, and extract substrings from their string arguments.


Non-string and Non-scalar Arguments to String Routines

Most of the string processing routines described in this chapter expect at least one argument that is the string on which they act.

If the argument is not of type string, IDL converts it to type string using the same default formatting rules that are used by the PRINT or STRING routines. The function then operates on the converted result. Thus, the IDL statement,

PRINT, STRLEN(23)

returns the result

8

because the argument "23" is first converted to the string '     23' that happens to be a string of length 8.

If the argument is an array instead of a scalar, the function returns an array result with the same structure as the argument. Each element of the result corresponds to an element of the argument. For example, the following statements:

A = STRUPCASE(TREES)	Get an uppercase version of TREES.

HELP, A	Show that the result is also an array.

PRINT, TREES	Display the original.

PRINT, A	Display the result.

results in the output below.

A                STRING    = Array(7)
Beech Birch Mahogany Maple Oak Pine Walnut
BEECH BIRCH MAHOGANY MAPLE OAK PINE WALNUT

For more details on how individual routines handle their arguments, see the individual descriptions in the IDL Reference Guide.


String Concatenation

The addition operator is used to concatenate strings. For example, the command:

A = 'This is' + ' a concatenation example.'

PRINT, A

results in the following output:

This is a concatenation example.

The following IDL statements build a scalar string containing a comma-separated list of the names found in the TREES string array:

NAMES = TREES + [REPLICATE(',', N_ELEMENTS(TREES)-1), '']
Use REPLICATE to make an array with the correct number of commas and add it to trees.

PRINT, NAMES	Show the resulting list.

Running the above statements results in the following output:

Beech, Birch, Mahogany, Maple, Oak, Pine, Walnut


Using STRING to Format Data

The STRING function has the following form:

S = STRING(Expression1, ..., Expressionn)

It converts its parameters to characters, returning the result as a string expression. It is identical in function to the PRINT procedure, except that its output is placed into a string rather than being output to the terminal. As with PRINT, the FORMAT keyword can be used to explicitly specify the desired format. See the discussions of free format and explicitly formatted input/output on page 17-5 for details of data formatting. The STRING function is described fully in the IDL Reference Guide.

As a simple example, the following IDL statements:

A = STRING(FORMAT='("The values are:", /, (I))', INDGEN(5))
Produce a string array.

HELP, A	Show its structure.

FOR I = 0, 4 DO PRINT, A(I)	Print the result.

produces the following output:

A   STRING    = Array(6)
The values are:
     0
     1
     2
     3

Reading Data from Strings

The READS procedure performs formatted input from a string variable and writes the results into one or more output variables. This procedure differs from the READ procedure only in that the input comes from memory instead of a file.

This routine is useful when you need to examine the format of a data file before reading the information it contains. Each line of the file can be read into a string using READF. Then the components of that line can be read into variables using READS.

See the description of READS in the IDL Reference Guide for more details.


Byte Arguments and Strings

There is a close association between a string and a byte array—a string is simply an array of bytes that is treated as a series of ASCII characters. Therefore, it is convenient to be able to convert between them easily.

When STRING is called with a single argument of type byte and the FORMAT keyword is not used, STRING does not work in its normal fashion. Instead of formatting the byte data and placing it into a string, it returns a string containing the byte values from the original argument. Thus, the result has one less dimension than the original argument. A two-dimensional byte array becomes a vector of strings, and a byte vector becomes a scalar string. However, a byte scalar also becomes a string scalar. For example, the statement

PRINT, STRING([72B, 101B, 108B, 108B, 111B])

produces the output below:

Hello

This output results because the argument to STRING, as produced by the array concatenation operator, is a byte vector. Its first element is 72B which is the ASCII code for "H," the second is 101B which is an ASCII "e," and so forth. Set the PRINT keyword can be used to disable this feature and cause STRING to treat byte data in the usual way.

As discussed in Chapter 17, it is easier to read fixed-length string data from binary files into byte variables instead of string variables. Therefore, it is convenient to read the data into a byte array and use this special behavior of STRING to convert the data into string form.

Another use for this feature is to build strings that contain nonprintable characters in a way such that the character is not entered directly. This results in programs that are easier to read and that also avoid file transfer difficulties (some forms of file transfer have problems transferring nonprintable characters). For example, the following statements ring the bell:

TAB = STRING(9B)	The decimal ASCII code for the tab character is 9.

BEL = STRING(7B)	The decimal ASCII code for the bell character is 7.

PRINT, 'There is a', TAB, 'tab here.', BEL
Output a line containing a tab character and ring the terminal bell.

Due to the way in which strings are implemented in IDL, applying the STRING function to a byte array containing a null (zero) value will result in the resulting string being truncated at that position. Thus, the statement,

PRINT, STRING([65B, 66B, 0B, 67B])

produces the following output:

AB

This output is produced because the null byte in the third position of the byte array argument terminates the string and hides the last character.

It should be noted that the BYTE function, when called with a single argument of type string, performs the inverse operation to that described here, resulting in a byte array containing the same byte values as its string argument. For additional information about the BYTE function, see the discussion of type conversion functions in on page 4-4.


Case Folding

The STRLOWCASE and STRUPCASE functions are used to convert arguments to lowercase or uppercase. They have the form:

S = STRLOWCASE(String)

S = STRUPCASE(String)

where String is the string to be converted to lowercase or uppercase.

The following IDL statements generate a table of the contents of TREES showing each name in its actual case, lowercase and uppercase:

FOR I=0, 6 DO PRINT, TREES(I), STRLOWCASE(TREES(I)),$

STRUPCASE(TREES(I)), FORMAT = '(A, T15, A, T30, A)'

The resulting output from running this statement is as follows:

Beech	beech	BEECH
Birch	birch	BIRCH
Mahogany	mahogany	MAHOGANY
Maple	maple	MAPLE
Oak	oak	OAK
Pine	pine	PINE
Walnut	walnut	WALNUT
A common use for case folding occurs when writing IDL procedures that require input from the user. By folding the case of the response, it is possible to handle responses written in uppercase, lowercase, or mixed case. For example, the following IDL statements can be used to ask "yes or no" style questions:

ANSWER = ''	Create a string variable to hold the response.

READ, 'Answer yes or no:  ', ANSWER	Ask the question.

IF (STRUPCASE(ANSWER) EQ 'YES') THEN PRINT,'YES' ELSE PRINT, 'NO'
Compare the response to the expected answer.


Whitespace

The STRCOMPRESS and STRTRIM functions are used to remove unwanted white space (tabs and spaces) from a string. This can be useful when reading string data from arbitrarily formatted strings.

Removing All Whitespace

The function STRCOMPRESS returns a copy of its string argument with all white space replaced with a single space or completely removed. It has the form:

S = STRCOMPRESS(String)

where String is the string to be compressed. The default action is to replace each section of white space with a single space. Setting the REMOVE_ALL keyword causes white space to be completely eliminated. For example,

A = '   This   is  a poorly   spaced  sentence.   '
Create a string with undesirable white space. Such a string might be the result of reading user input with a READ statement.

PRINT, '>', STRCOMPRESS(A), '<'	Print the result of shrinking all white space to a single blank.

PRINT '>', STRCOMPRESS(A, /REMOVE_ALL), '<'
Print the result of removing all white space.

results in the output:

> This is a poorly spaced sentence. <
>Thisisapoorlyspacedsentence.<

Removing Leading or Trailing Blanks

The function STRTRIM returns a copy of its string argument with leading and/or trailing white space removed. It has the form:

S = STRTRIM(String[, Flag])

where String is the string to be trimmed and Flag is an integer that indicates the specific trimming to be done. If  Flag is 0 or is not present, trailing white space is removed. If it is 1, leading white space is removed. Both trailing and leading white space are removed if Flag is equal to 2. For example:

A = ' This string has leading and trailing white space  '
Create a string with unwanted leading and trailing blanks.

PRINT, '>', STRTRIM(A), '<'	Remove trailing white space.

PRINT, '>', STRTRIM(A,1), '<'	Remove leading white space.

PRINT, '>', STRTRIM(A,2), '<'	Remove both.

Executing these statements produces the output below.

>     This string has leading and trailing white space<
>This string has leading and trailing white space    <
>This string has leading and trailing white space<

Removing All Types of Whitespace

When processing string data, STRCOMPRESS and STRTRIM can be combined to remove leading and trailing white space and shrink any white space in the middle down to single spaces.

A =  'Yet   another  poorly  spaced    sentence.   '
Create a string with undesirable white space.

PRINT, '>' STRCOMPRESS(STRTRIM(A,2)),   '<'
Eliminate unwanted white space.

Executing these statements gives the result below:

>Yet another poorly spaced sentence.<


Finding the Length of a String

The STRLEN function is used to obtain the length of a string. It has the form:

L = STRLEN(String)

where String is the string for which the length is required. For example, the following statement

PRINT, STRLEN('This sentence has 31 characters')

results in the output

31

while the following IDL statement prints the lengths of all the names contained in the array TREES.

PRINT, STRLEN(TREES)

The resulting output is as follows:

 5        5        8        5        3        4        6


Substrings

IDL provides the STRPOS, STRPUT, and STRMID routines to locate, insert, and extract substrings from their string arguments.

Searching for a Substring

The STRPOS function is used to search for the first occurrence of a substring. It has the form

S = STRPOS(Object, Search_string[, Position])

where Object is the string to be searched, Search_string is the substring to search for, and Position is the character position (starting with position 0) at which the search is begun. If the optional argument Position is omitted, the search is started at the first character (character position 0). The following IDL statements count the number of times that the word "dog" appears in the string "dog cat duck rabbit dog cat dog":

ANIMALS = 'dog cat duck rabbit dog cat dog'
The search string, "dog", appears three times.

I = 0	Start searching in character position 0.

CNT = 0	Number of occurrences found.

WHILE (I NE -1) DO BEGIN	Search for an occurrence.

  I = STRPOS(ANIMALS, 'dog', I)	If one is found, count it and advance to next character position.

  IF (I NE -1) THEN BEGIN CNT = CNT + 1

    I = I + 1

  END

ENDWHILE	Print the result.

PRINT, 'Found ', cnt, "occurrences of 'dog'"

Running the above statements produces the result below.

Found         3 occurrences of 'dog'

Inserting the Contents of One String into Another

The STRPUT procedure is used to insert the contents of one string into another. It has the form,

STRPUT, Destination, Source[, Position]

where Destination is the string to be overwritten, Source is the string to be inserted, and Position is the first character position within Destination at which Source will be inserted. If the optional argument Position is omitted, the overwrite is started at the first character (character position 0). The following IDL statements use STRPOS and STRPUT to replace every occurrence of the word "dog" with the word "CAT" in the string "dog cat duck rabbit dog cat dog":

ANIMALS = 'dog cat duck rabbit dog cat dog'
The string to search, "dog", appears three times.

WHILE (((I = STRPOS(ANIMALS, 'dog'))) NE -1) DO $

STRPUT, ANIMALS, 'CAT', I	While any occurrence of "dog" exists, replace it.

PRINT, ANIMALS	Show the resulting string.

Running the above statements produces the result below.

CAT cat duck rabbit CAT cat CAT

Extracting Substrings

The STRMID function is used for extracting substrings from a larger string. It has the form:

STRMID(Expression, First_Character, Length)

where Expression is the string from which the substring will be extracted, First_Character is the starting position within Expression of the substring (the first position is position 0), and Length is the length of the substring to extract. If there are not Length characters following the position First_Character, the substring will be truncated. The following IDL statements use STRMID to print a table matching the number of each month with its three-letter abbreviation:

MONTHS = 'JANFEBMARAPRMAYJUNJULAUGSEPOCTNOVDEC'
String containing all the month names.

FOR I = 1, 12 DO PRINT, I, '      ', $

STRMID(MONTHS, (I - 1) * 3, 3)	Extract each name in turn. The equation (I-1)*3 calculates the position within MONTH for each abbreviation

The result of executing these statements is as follows:

 1      JAN

 2      FEB

 3      MAR

 4      APR

 5      MAY

 6      JUN

 7      JUL

 8      AUG

 9      SEP

10      OCT

11      NOV

12      DEC

Jump forward to Vector-Drawn Fonts

Jump backward to Structures


Vector-Drawn Fonts
9	Vector-Drawn Fonts

Chapter Overview

IDL uses two types of fonts for writing characters on the graphics device: vector-drawn fonts and hardware-generated characters. Vector-drawn fonts are internal to IDL and are drawn with lines. With hardware-generated characters, IDL simply sends the characters to the device, which displays them using built-in, character-display hardware. Vector-drawn fonts are device independent (within the limits of device resolution), while hardware-generated characters differ between devices. This chapter discusses how vector fonts are used and when to use them.

When generating characters for plots, IDL uses the fonts specified by the value of the system variable !P.FONT. The normal default for this variable is -1, which specifies that the built-in, vector-drawn fonts should be used instead of using the fonts supplied by the graphics device hardware (selected by setting !P.FONT to zero). Some of the issues involved in choosing between vector-drawn and hardware-generated fonts are explained below.

Appearance

Vector-drawn characters are of medium quality, suitable for most uses. The appearance of hardware-generated characters varies from mediocre (such as the characters found in many terminals) to publication quality (such as provided by PostScript).

Three-Dimensional Transformations

Vector plotting should always be used with three-dimensional transformations. Vector-drawn characters pass through the same transformations as the rest of the plot, yielding a better looking plot. See Chapter 15 for examples of vector-drawn characters with three-dimensional graphics.

Portability

The vector-drawn fonts work using any graphics device and look the same on every device (within the limitations of device resolution). In contrast, the appearance, size, and availability of hardware fonts varies greatly from device to device. Many, if not most, of the positioning and font changing commands recognized by the vector-drawing routines are ignored when using hardware fonts.

Cost

It takes more computer time to draw characters with line vectors and generally results in more input/output. However, this is not an important issue unless the plot contains a large number of characters or the transmission link to the device is slow.

Flexibility

Vector-drawn fonts provide a great deal of flexibility. There are many different typefaces available, as shown in the tables at the end of this chapter. In addition, such fonts can be arbitrarily scaled, rotated, and transformed.

The abilities of hardware-generated characters differ greatly between devices so it is not possible to make a blanket statement on when they should be used—the best font to use depends on the available hardware. In general, however, the vector-drawn fonts are easier to use and often provide superior results to what is available from the hardware. For producing publication-quality output, we recommend using PostScript output with hardware characters. See the IDL Reference Guide for details on the hardware-generated characters provided by the various devices supported by IDL.


Topics in Vector-Drawn Fonts Chapter
Vector-Drawn Fonts

This chapter provides an overview of IDL's device-independent vector-drawn fonts and their use.

Topics Covered:

About the Vector Fonts

Character Sets and Positioning Commands

Vector-Drawn Font Example

Font Samples

Jump forward to Defining Procedures and Functions

Jump backward to Strings


About the Vector Fonts

The vector fonts used by IDL were digitized by Dr. A.V. Hershey of the Naval Weapons Laboratory. Text strings can include embedded formatting commands that facilitate subscripting, superscripting, and equation formatting using a method similar to that developed by Grandle and Nystrom (1980). These commands are always introduced by the exclamation mark, (!). The string "!!" is used to produce an exclamation mark.

Note: The exclamation mark has no special significance for hardware-generated characters unless the ability is provided by the particular device in use. For example, the PostScript driver provides some. Therefore, you should consult the description of the device in the IDL Reference Guide before trying to use these commands with hardware characters.

All the available fonts are illustrated at the end of this chapter. The default font (Font 3, Simplex Roman) is in effect if no font changes have been made.

ISO Latin 1 Encoding

Note that the default font (Font 3, Simplex Roman) follows the ISO Latin 1 Encoding scheme and contains many international characters. The illustration of this font, found at the end of this chapter, can be used to find the octal codes for the special characters.

For example, suppose you want to display some text with an Angstrom symbol in it. Looking at the chart of font 3, we see that the Angstrom symbol has octal code 305. Non-printable characters can be represented in IDL using octal or hexadecimal notation and the STRING function, as described previously (see "Representing Non-Printable Characters" on page 3-5). So the Angstrom can be printed by inserting a STRING("305B) character in our text string as follows:

XYOUTS,.1, .5, 'Here is an Angstrom symbol: ' + STRING("305B), $
       /NORM, CHARSIZE=3

Customizing the Vector Fonts

The EFONT procedure is a widget application that allows you to edit the Hershey fonts and save the results. Use this routine to add special characters or completely new, custom fonts to the Hershey fonts.


Character Sets and Positioning Commands

The commands to change the fonts are shown in the table below. The character following the exclamation mark can be either upper or lowercase.

Font Command	Description
!3	Simplex Roman (default)
!4	Simplex Greek
!5	Duplex Roman
!6	Complex Roman
!7	Complex Greek
!8	Complex Italic
!9(!M)	Math and special characters
!10	Special characters
!11(!G)	Gothic English
!12(!W)	Simplex Script
!13	Complex Script
!14	Gothic Italian
!15	Gothic German
!16	Cyrillic
!17	Triplex Roman
!18	Triplex Italic
!20	Miscellaneous
!X	Revert to the entry font
Table 9.1 Vector-Drawn Character Sets

Positioning Commands

The positioning and other font-manipulation commands are described in Table 9.2.

PositioningCommands	Action
!A	Shift above the division line.
!B	Shift below the division line.
!C	"Carriage return," begins a new line of text. Shift back to the starting position and down one line.
!D	Shift down to the first level subscript and decrease the character size by a factor of 0.62.
!E	Shift up to the exponent level and decrease the character size by a factor of 0.44.
!I	Shift down to the index level and decrease the character size by a factor of 0.44.
!L	Shift down to the second level subscript. Decrease the character size by a factor of 0.62.
!N	Shift back to the normal level and original character size.
!R	Restore position. The current position is set from the top of the saved positions stack.
!S	Save position. The current position is saved on the top of the saved positions stack.
!U	Shift to upper subscript level. Decrease the character size by a factor of 0.62.
!X	Return to the entry font.
!!	Display the ! symbol.
Table 9.2 Vector-Drawn Positioning and Miscellaneous Commands

The figure below illustrates the relative positions and effects on character size of the level commands. In this figure, the letters "!N" are normal level and size characters.

The figure below illustrates some typical uses of the Hershey character set.

The command string is reproduced underneath the graphic output to show how to format complex equations. Remember, the case of the character that follows the "!" command character is ignored. To illustrate, the bottom integral term was formed by the following IDL procedure call:

XYOUTS, 0, .2, $

        '!MI!S!A!E!8x!R!B!Ip!N !7q!Ii!N!8U!S!E2!R!Ii!Ndx', $

        SIZE = 3, /NORMAL

The string may be broken down into the following components:

!MI

Changes to the math set and draws the integral sign, uppercase I.

!S

Saves the current position on the position stack.

!A!E!8x

Shifts above the division line and to the exponent level, switches to the Complex Italic font (Font 8), and draws the " x."

!R!B!Ip

Restores the position to the position immediately after the integral sign, shifts below the division line to the index level, and draws the " p."

!N !7q

Returns to the normal level, advances one space, shifts to the Complex Greek font (Font 7), and draws the Greek letter rho, which is designated by "q" in this set.

!Ii!N

Shifts to the index level and draws the " i " at the index level. Returns to the normal level.

!8U

Shifts to the Complex Italic font (Font 8) and outputs the upper case " U."

!S!E2

Saves the position and draws the exponent " 2."

!R!Ii

Restores the position and draws the index " i."

!N dx

Returns to the normal level and outputs " dx."


Vector-Drawn Font Example

IDL uses vector-drawn font when the value of the system variable !P.FONT is -1. This is the default condition. Initially, all characters are drawn using the Simplex Roman font (Font 3). When plotting, font changing commands may be embedded in the title strings keyword arguments (XTITLE, YTITLE, and TITLE) to select other fonts. For example, the following statement uses the Complex Roman font (Font 6) for the x-axis title:

PLOT, X, XTITLE = '!6X Axis Title'

This font remains in effect until explicitly changed. The order in which the annotations are drawn is main title, x-axis numbers, x-axis title, y-axis numbers, and y-axis title. Strings to be output also may contain embedded information selecting subscripting, superscripting, plus other features that facilitate equation formatting.

The following statements were used to produce the figure below. They serve as an example of a plot using vector-drawn characters and of equation formatting.

X = FLTARR(128)	Define an array.

X(30:40) = 1.0	Make a step function.

X = ABS(FFT(X, 1))	Take FFT and magnitude.

PLOT_IO, X(0:64), XTITLE = '!17Frequency', $

   YTITLE = '!5Power', $

   TITLE = '!18Example of Vector Drawn Plot', $

   POSITION = [.2, .2, .9, .6]	Produce a log-linear plot. Use the Triplex Roman font for the x title (!17), Duplex Roman for the y title (!5), and Triplex Italic for the main title (!18). The position keyword is used to shrink the plotting window.

SS = '!6F(s) = (2!4p)!e-1/2!n !mi!s!a!e!m$!r!b!i ' + $

     '-!m$!nF(x)e !e-i2!4p!3xs!ndx'	String to produce equation.

XYOUTS, 0.1, .75, SS, SIZE = 3, /NORMAL, /NOCLIP
Output string over plot. The NOCLIP keyword is needed because the previous plot caused the clipping region to shrink.


Font Samples

The following figure shows the Simplex Roman vector-drawn font. To view the other vector-drawn fonts, use the SHOWFONT routine, or see "Font Samples" on page 9-7 of the IDL User's Guide.

References

Hershey, A.V., (1967), Calligraphy for Computers, Technical Report No. 2101, U.S. Naval Weapons Laboratory, Dahlgren, Virginia.

Grandle, R.E. and P.A. Nystrom, (1980), A Method for usage of a large calligraphy set under RSX-11M, Proceedings of the Digital Equipment Computer Users Society, 391­395.

Jump forward to Defining Procedures and Functions

Jump backward to Strings


Defining Procedures and Functions
10	Defining Procedures and Functions

Chapter Overview

Procedures and functions are self-contained modules that break large tasks into smaller, more manageable ones. Modular programs simplify debugging and maintenance and, because they are reusable, minimize the amount of new code required for each application.

New procedures and functions can be written in IDL and called in the same manner as the system-defined procedures or functions from the keyboard or from other programs. When a procedure or function is finished, it executes a RETURN statement that returns control to its caller. Functions always returns an explicit result. A procedure is called by a procedure call statement, while a function is called by a function reference. For example, if ABC is a procedure and XYZ is a function, the following occurs:

ABC, A, 12	Call procedure ABC with two parameters.

A = XYZ(C/D)	Call function XYZ with one parameter. The result of XYZ is stored in variable A.


Topics in Defining Procedures and Functions Chapter
Defining Procedures and Functions

This chapter provides an overview of the definition and use of IDL procedures and functions.

Topics Covered:

Procedure and Function Definition Statements

Parameters

Entering Procedure Definitions

Parameter Passing Mechanism

Calling Mechanism

Jump forward to Programming Routines

Jump backward to Vector-Drawn Fonts


Procedure and Function Definition Statements

The procedure and function definition statements notify the IDL compiler that a user-written program module follows. One of these statements must be the first line in a user-written IDL routine.

The PRO statement defines an IDL procedure. Its syntax is:

PRO Procedure_Name, P1, P2, ..., Pn

The FUNCTION statement defines an IDL function. It's syntax is:

FUNCTION Function_Name, P1, P2, ..., Pn


Parameters

The variables and expressions passed to the function or procedure from its caller are parameters. Actual parameters are those appearing in the procedure call statement or the function reference. In the examples at the beginning of this section, the actual parameters in the procedure call are the variable A and the constant 12, while the actual parameter in the function call is the value of the expression (C/D).

Formal parameters are the variables declared in the procedure or function definition. The same procedure or function can be called using different actual parameters from a number of places in other program units.

Correspondence of Formal and Actual Parameters

The correspondence between the actual parameters of the caller and the formal parameters of the called procedure is established by position or by keyword.

Positional Parameters

A positional parameter, or plain argument, is a parameter without a keyword. Just as its name implies, the position of a positional parameter establishes the correspondence—the n-th formal positional parameter is matched with the n-th actual positional parameter.

Keyword Parameters

A keyword parameter, which can be either actual or formal, is an expression or variable name preceded by a keyword and an equal sign ("=") that identifies which parameter is being passed.

When calling a procedure with a keyword parameter, you can abbreviate the keyword to its shortest, unambiguous abbreviation. Keyword parameters can also be specified by the caller with the syntax /KEYWORD, which is equivalent to setting the keyword parameter to 1 (e.g.,  KEYWORD = 1). The syntax /KEYWORD is often referred to, in the rest of this documentation, as setting the keyword.

Example

A procedure is defined with a keyword parameter named TEST.

PRO XYZ, A, B, TEST = T

The caller can supply a value for the formal (keyword) parameter T with the following calls:

XYZ, TEST = A	Supply only the value of T. A and B are undefined inside the procedure.

XYZ, TE = A, Q, R	The value of A is copied to formal parameter T (note the abbreviation for TEST), Q to A, and R to B.

XYZ, Q	Variable Q is copied to formal parameter A. B and T are undefined inside the procedure.

Copying Parameters

When a procedure or function is called, the actual parameters are copied into the formal parameters of the procedure or function and the module is executed.

On exit, via a RETURN statement, the formal parameters are copied back to the actual parameters, providing they were not expressions or constants. Parameters can be inputs to the program unit; they can be outputs in which the values are set or changed by the program unit; or they can be both inputs and outputs.

When a RETURN statement is encountered in the execution of a procedure or function, control is passed back to the caller immediately after the point of the call. In functions, the parameter of the RETURN statement is the result of the function.

Number of Parameters

A procedure or a function can be called with fewer arguments than were defined in the procedure or function. For example, if a procedure is defined with 10 parameters, the user or another procedure can call the procedure with 0 to 10 parameters.

Parameters that are not used in the actual argument list are set to be undefined upon entering the procedure or function. If values are stored by the called procedure into parameters not present in the calling statement, these values are discarded when the program unit exits. The number of actual parameters in the calling list can be found by using the system function N_PARAMS. Use the N_ELEMENTS function to determine if a variable is defined.

Example

An example of an IDL function to compute the digital gradient of an image is shown in the example below. The digital gradient approximates the two-dimensional gradient of an image and emphasizes the edges.

This simple function consists of three lines corresponding to the three required components of IDL procedures and functions: the procedure or function declaration, the body of the procedure or function, and the terminating end statement.

FUNCTION GRAD, IMAGE	Define a function called GRAD. Result is ABS(dz/dx) + ABS(dz/dy).

RETURN, ABS(IMAGE - SHIFT(IMAGE, 1, 0)) + $

       ABS(IMAGE-SHIFT(IMAGE, 0, 1))	Evaluate and return the result.

END	End of function.

The function has one parameter called IMAGE. There are no local variables. Local variables are variables active only within a module (i.e., they are not parameters and are not contained in common blocks).

The result of the function is the value of the expression used as an argument to the RETURN statement. Once compiled, the function is called by referring to it in an expression. Two examples are shown below.

A = GRAD(B)	Store gradient of B in A.

TVSCL, GRAD(ABC + DEF) 	Display gradient of IMAGE sum.

Example of Keyword Parameters

A short example of a function that exchanges two columns of a 4 x 4 homogeneous, coordinate-transformation matrix is shown below. The function has one positional parameter, the coordinate-transformation matrix T. The caller can specify one of the keywords XYEXCH, XZEXCH, or YZEXCH to interchange the xy, xz, or yz axes of the matrix. The result of the function is the new coordinate transformation matrix defined below.

FUNCTION SWAP, T, XYEXCH = XY, XZEXCH = XZ, YZEXCH = YZ
Function to swap columns of T. XYEXCH swaps columns 0 and 1, XZEXCH swaps 0 and 2, and YZEXCH swaps 1 and 2.

IF KEYWORD_SET(XY) THEN S=[0,1]	Swap columns 0 and 1 if keyword XYEXCH is set.

ELSE IF KEYWORD_SET(XZ) THEN S=[0,2]	Check to see if xz is set.

ELSE IF KEYWORD_SET(YZ) THEN S=[1,2]	Check to see if yz is set.

ELSE RETURN, T 	If nothing is set, return.

R = T 	Copy matrix for result.

R(S(1), 0) = T(S(0), *)	Exchange two columns using matrix insertion operators and subscript ranges.

R(S(0), 0) = T(S(1), *)

RETURN,R	Return result.

END

Typical calls to SWAP are as follows:

Q = SWAP(!P.T, /XYEXCH)

Q = SWAP(Q, /XYEX)

Q = SWAP(INVERT(Z), YZ = 1)

Q = SWAP(Z, XYE = I EQ 0, XZE = I EQ 1, YZE = I EQ 2)

Note that keyword names can abbreviated to the shortest unambiguous string. The last example sets one of the three keywords according to the value of the variable I.

This function example uses the system function KEYWORD_SET to determine if a keyword parameter has been passed and if it is nonzero. This is similar to using the condition:

IF N_ELEMENTS(P) NE 0 THEN IF P THEN ... ...

to test if keywords that have a true/false value are both present and true.

Keyword Inheritance

Keyword inheritance allows IDL routines to pass keyword parameters not defined in their function or procedure declaration on to routines they call. This greatly simplifies writing "wrapper" routines, which are variations of a system or user-provided routine.

Usually, passing an undefined keyword to an IDL routine causes an error. However, if the routine is defined with a formal keyword parameter named "_EXTRA" (note the underscore character), pairs of unrecognized keywords and values are placed in an anonymous structure. The name of each unrecognized keyword becomes a tag name, and the keyword value becomes the tag value. Changes to this structure created by using the _EXTRA keyword do not affect variables in the calling program.

When the keyword _EXTRA appears in a procedure or function call, its argument is a structure containing additional keyword/value pairs which are inserted into the argument list. The value of _EXTRA can also be "undefined", indicating that no additional keyword parameters were passed.

Note that keyword parameters passed via the _EXTRA keyword are only passed into the called routine. They are not passed back out.

Example

The most common use of this functionality is the creation of "wrapper" routines that extend the functionality of existing routines. For example, suppose that procedure TEST is a wrapper to the PLOT command. The text of such a procedure is shown below:

PRO TEST, a, b, _EXTRA = e, COLOR = color

PLOT, a, b, COLOR = color, _EXTRA = e

END

The procedure definition:

PRO TEST, a, b, _EXTRA = e, COLOR = color

places unrecognized keywords (e.g., any keywords other than COLOR) and their values into the variable "e". If there are no unrecognized keywords, e will be undefined.

When procedure TEST is called with the following command:

TEST, x, y, COLOR=3, LINESTYLE = 4, THICK=5

variable "e", within TEST, contains an anonymous structure with the value:

{ LINESTYLE: 4, THICK: 5}

These keyword/value pairs are then be passed from TEST to the PLOT routine using the _EXTRA keyword:

PLOT, a, b, COLOR = color, _EXTRA = e

Note that keywords passed into a routine via _EXTRA override previous settings of that keyword. For example, the call:

PLOT, a, b, COLOR = color, _EXTRA = {COLOR: 12}

specifies a color index of 12 to PLOT.


Entering Procedure Definitions

Procedures and functions are compiled using the .RUN executive command. The format of this command is as follows:

.RUN File1 [, Filen, ... ]

From 1 to 10 files, each containing one or more program units, can be compiled with the .RUN command. For more information on the .RUN command, see "Executive Commands" on page 2-10.

To enter program text directly from the keyboard, simply enter .RUN at the IDL> prompt. IDL will prompt with the "-" character, indicating that it is compiling a directly entered program. As long as IDL requires more text to complete a program unit, it prompts with the "-"character. Rather than executing statements immediately after they are entered, IDL compiles the program unit as a whole.

Procedure and function definition statements cannot be entered in the single-statement mode, but must be prefaced by either .RUN or .RNEW.

The first non-empty line the IDL compiler reads determines the type of the program unit: procedure, function, or main program. If the first non-empty line is not a procedure or function definition statement, the program unit is assumed to be a main program. The name of the procedure or function is given by the identifier following the keyword PRO or FUNCTION. If a program unit with the same name is already compiled, it is replaced by the new program unit.

Note Regarding Functions

User-defined functions, with the exception of those contained in directories specified by the IDL system variable !PATH, must be compiled before the first reference to the function is compiled. This is necessary because the IDL compiler is unable to distinguish between a reference to a subscripted variable and a call to a presently undefined user function with the same name. For example, in the statement

A = XYZ(5)

it is impossible to tell by context alone if XYZ is an array or a function.

When IDL encounters references that may be either a function call or a subscripted variable, it searches the current directory, then the directories specified by !PATH, for files with names that match the unknown function or variable name. If one or more files matching the unknown name exist, IDL compiles them before attempting to evaluate the expression. If no function or variable with the given name exists, IDL displays an error message.

There are several ways to avoid this problem:

•	Compile the lowest-level functions (those that call no other functions) first, then higher-level functions, and finally procedures.

•	Place the function in a file with the same name as the function, and place that file in one of the directories specified by !PATH.

•	Use the FORWARD_FUNCTION definition statement to inform IDL that a given name refers to a function rather than a variable. See "Forward Function Definition" on page 6-15.

•	Manually compile all functions before any reference, or use RESOLVE_ROUTINE or RESOLVE_ALL to compile functions.


Parameter Passing Mechanism

Parameters are passed to IDL system and user-written procedures and functions by value or by reference. It is important that the user recognize the distinction between these two methods.

•	Expressions, constants, system variables, and subscripted variable references are passed by value.

•	Variables are passed by reference.

Parameters passed by value can only be inputs to program units. Results cannot be passed back to the caller by these parameters. Parameters passed by reference can convey information in either or both directions. For example, consider the following trivial procedure:

PRO ADD, A, B
A = A + B
RETURN
END

This procedure adds its second parameter to the first, returning the result in the first. The call

ADD, A, 4

adds 4 to A and stores the result in variable A. The first parameter is passed by reference and the second parameter, a constant, is passed by value. The call

ADD, 4, A

does nothing because a value cannot be stored in the constant 4, which was passed by value. No error message is issued. Similarly, if ARR is an array, the call

ADD, ARR(5), 4

will not achieve the desired effect (adding 4 to element ARR(5)), because subscripted variables are passed by value. The correct, though somewhat awkward, method is as follows:

TEMP = ARR(5)
ADD, TEMP, 4
ARR(5) = TEMP


Calling Mechanism

When a user-written procedure or function is called, the following actions occur:

1.	All of the actual arguments in the user-procedure call list are evaluated and saved in temporary locations.

2.	The actual parameters that were saved are substituted for the formal parameters given in the definition of the called procedure. All other variables local to the called procedure are set to undefined.

3.	The function or procedure is executed until a RETURN or RETALL statement is encountered. Procedures also can return on an END statement. The result of a user-written function is passed back to the caller by specifying it as the value of a RETURN statement. RETURN statements in procedures cannot specify a return value.

4.	All local variables in the procedure, those variables that are neither parameters nor common variables, are deleted.

5.	The new values of the parameters that were passed by reference are copied back into the corresponding variables. Actual parameters that were passed by value are deleted.

6.	Control resumes in the calling procedure after the procedure call statement or function reference.

Recursion

Recursion (i.e., a program calling itself) is supported for both procedures and functions.

Example

Here is an example of an IDL procedure that reads and plots the next vector from a file. This example illustrates using common variables to store values between calls, as local parameters are destroyed on exit. It assumes that the file containing the data is open on logical unit 1 and that the file contains a number of 512-element, floating-point vectors.

PRO NXT, RECNO	Read and plot the next record from file 1. If RECNO is specified, set the current record to its value and plot it.

COMMON NXT_COM, LASTREC	Save previous record number.

IF N_PARAMS(0) GE 1 THEN LASTREC = RECNO
Set record number if parameter is present.

IF N_ELEMENTS(LASTREC) LE 0 THEN LASTREC = 0
Define LASTREC if this is first call.

AA = ASSOC(1, FLTARR(512))	Define file structure.

PLOT, AA(LASTREC)	Read and plot record.

LASTREC = LASTREC + 1	Increment record for next time.

RETURN A	All finished.

END

Once the user has opened the file, typing NXT will read and plot the next record. Typing NXT, N will read and plot record number N.

Jump forward to Programming Routines

Jump backward to Vector-Drawn Fonts


Programming Routines
11	Programming Routines

Chapter Overview

The routines discussed in this chapter are characterized by the fact that they are useful primarily (though not exclusively) in IDL procedures and functions. They are rarely used interactively. They provide information about variables and expressions, give the programmer control over how errors are handled, and perform other useful operations.

Routines can be loosely categorized into the following groups:

•	Error-handling and checking routines such as CATCH, ON_ERROR, ON_IOERROR, FINITE, and CHECK_MATH.

•	Informational routines which return information about variables, expressions, parameters, etc. These routines are N_ELEMENTS, SIZE, N_PARAMS, KEYWORD_SET, FINITE, and CHECK_MATH. In addition, TAG_NAMES and N_TAGS, which are described on page 7-10, supply information about structure variables.

•	Program control routines such as CALL_FUNCTION, CALL_PROCEDURE, EXIT, EXECUTE, STOP, and WAIT.

•	Dynamic memory routines ("handle" routines) that create and manage IDL's handle data structures.

Different IDL platforms supply different sets of debugging tools. Consult your platform-specific documentation (i.e. IDL for Unix, IDL for Windows, etc.) for more information on the tools available on your platform.


Topics in Programming Routines Chapter
Programming Routines

This chapter provides an overview of IDL's error handling, informational, program control, and dynamic memory routines.

Topics Covered:

Error-Handling Routines

Controlling Errors Using CATCH

Controlling Errors Using ON_ERROR

Controlling Input/Output Errors

Error Signaling

Obtaining Traceback Information

Error System Variables

Math Errors

Informational Routines

Program Control Routines

Handles—Dynamic Memory Structures in IDL

Jump forward to Efficient Programming

Jump backward to Defining Procedures and Functions


Error Handling Routines
Error-Handling Routines

IDL divides possible execution errors into three categories: input/output, math, and all others. There are three main error-handling routines: CATCH, ON_ERROR, and ON_IOERROR. CATCH is a generalized mechanism for handling exceptions and errors. The ON_ERROR routine handles regular errors when an error handler established by the CATCH procedure is not present. The ON_IOERROR routine allows you to change the default way in which input/output errors are handled. The FINITE and CHECK_MATH routines provide control over math errors.

Default Error-Handling Mechanism

In the default case, whenever an error is detected by IDL during the execution of a program, program execution stops and an error message is printed. The execution context is that of the program unit (procedure, function, or main program) in which the error occurred.

Sometimes it is possible to recover from an error by manually entering statements to correct the problem. Possibilities include setting the values of variables, closing files, etc., and then entering the command .CON, which resumes execution of the program unit at the beginning of the statement that caused the error.

As an example, if an error stop occurs because an undefined variable is referenced, you can simply define the variable from the keyboard, then continue execution with .CON. Of course, this is not a permanent solution. You should still edit the program file to permanently fix the problem.

Disappearing Variables

IDL users may find that all their variables have seemingly disappeared after an error occurs inside a procedure or function. The misunderstood subtlety is that after the error occurs, IDL's context is inside the called procedure, not in the main level. All variables in procedures and functions, with the exception of parameters and common variables, are local in scope. Typing RETURN or RETALL will make the lost variables reappear.

RETALL is best suited for use when an error is detected in a procedure and it is desired to return immediately to the main program level despite nested procedure calls. RETALL issues RETURN commands until the main program level is reached.

The HELP command can be used to see the current call stack (i.e., which program unit IDL is in and which program unit called it).


Controlling Errors with CATCH
Controlling Errors Using CATCH

The CATCH procedure provides a generalized mechanism for handling any type of errors and exceptions within IDL. Calling CATCH establishes an error handler for the current procedure that intercepts all errors that can be handled by IDL, with the exception of non-fatal warnings such as math errors (e.g., floating-point underflow). The CATCH mechanism is similar to C's setjmp/longjmp facilities or C++'s catch/throw facilities.

When an error occurs, each active procedure, beginning with the offending procedure and proceeding up the call stack to the main program level, is examined for an error handler (established by a call to CATCH). If an error handler is found, control resumes at the statement after the call to CATCH. The index of the error is returned in the argument to CATCH and is also stored in the !ERROR system variable. The associated error message is stored in the !ERR_STRING system variable. If no error handlers are found, program execution stops, an error message is issued, and control reverts to the interactive mode.

Complete documentation on CATCH can be found on page 1-56 of the IDL Reference Guide.

Interaction of CATCH, ON_ERROR, and ON_IOERROR

Error handlers established by calls to CATCH supercede calls to ON_ERROR. However, calls to ON_IOERROR made in the procedure that causes an I/O error supercede any error handling mechanisms created with CATCH and the program branches to the label specified by ON_IOERROR. Figure 11.1 shows

a flow chart of how errors are handled in IDL.

Canceling an Error Handler

Call CATCH with the CANCEL keyword set to cancel a procedure's error handler. This cancellation does not effect other error handlers that may be established in other active procedures.

Generating an Exception

To generate an exception and cause control to return to the error handler, use the MESSAGE procedure. Calling MESSAGE generates an exception that sets the !ERROR system variable to -5 and the !ERR_STRING system variable to the string used as an argument to MESSAGE. See "Error Signaling" on page 11-7.

Example Using CATCH

The following procedure illustrates the use of CATCH:

PRO ABC

A = FLTARR(10)	Define variable A.

CATCH, Error_status	Establish error handler. When errors occur, the index of the error is returned in the variable Error_status. Initially, this argument is set to zero.

IF Error_status NE 0 THEN BEGIN	This statement begins the error handler.

        PRINT, 'Error index: ', Error_status

        PRINT, 'Error message:', !ERR_STRING

        A=FLTARR(12)	Handle the error by extending A.

        ENDIF

A(11)=12	Cause an error.

HELP, A	Even though an error occurs in the line above, program execution continues to this point because the event handler extended the definition of A so that the statement can be re-executed.

END

Running the ABC procedure causes IDL to produce the following output and control returns to the interactive prompt:

Error index:         -101

Error message:

Attempt to subscript A with <INT (      11)> is out of range.

A               FLOAT     = Array(12)


Controlling Errors Using ON_ERROR

The ON_ERROR procedure determines the action taken when an error is detected inside a user procedure or function and no error handlers established with the CATCH procedure are found. The possible options for error recovery are shown in Table 11.1:

Value	Action
0	Stop immediately in the context of the procedure or function that caused the error. This is the default action.
1	Return to the main program level and stop.
2	Return to the caller of the program unit that called ON_ERROR and stop.
3	Return to the program unit that called ON_ERROR and stop.
Table 11.1 Error Recovery Options

One useful option is to use ON_ERROR to cause control to be returned to the caller of a procedure in the event of an error. The statement:

ON_ERROR, 2

placed at the beginning of a procedure will have this effect. Include this statement in library procedures and other routines that will be used by others once the routines have been debugged. This form of error recovery makes debugging a routine difficult because the routine is exited as soon as an error occurs; therefore, it should be added once the code is completely tested.

Note that error handlers established by CATCH supercede calls to ON_ERROR made in the same procedure.


Controlling Input/Output Errors

The default action for handling input/output errors is to treat them exactly like regular errors and follow the error handling strategy set by ON_ERROR. You can alter this default by using the ON_IOERROR procedure to specify the label of a statement to which execution should jump if an input/output error occurs. When IDL detects an input/output error and an error-handling statement has been established, control passes directly to the given statement without stopping program execution. In this case, no error messages are printed.

Note that calls to ON_IOERROR made in the procedure that causes an I/O error supercede any error handling mechanisms created with CATCH and the program branches to the label specified by ON_IOERROR.

When writing procedures and functions that are to be used by others, it is good practice to anticipate and handle errors caused by the user. For example, the following procedure segment, which opens a file specified by the user, handles the case of a nonexistent file or read error.

FUNCTION READ_DATA, FILE_NAME	Define a function to read, and return a 100-element, floating-point array.

ON_IOERROR, BAD	Declare error label.

OPENR, UNIT, FILE NAME, /GET_LUN	Use the GET_LUN keyword to allocate a logical file unit.

A = FLTARR(100) 	Define data array.

READU, UNIT, A	Read it.

GOTO, DONE	Clean up and return.

BAD:  PRINT, !ERR_STRING	Exception label. Print the error message.

DONE: FREE_LUN, UNIT 	Close and free the input/output unit.

RETURN, A	Return the result. This will be undefined if an error occurred.

END

The important things to note in this example are that the FREE_LUN procedure is always called, even in the event of an error, and that this procedure always returns to its caller. It returns an undefined value if an error occurs, causing its caller to encounter the error.


Error Signaling

The MESSAGE procedure is used by user procedures and functions to issue errors. It has the form:

MESSAGE, Text

where Text is a scalar string that contains the text of the error message.

The MESSAGE procedure issues error and informational messages using the same mechanism employed by built-in IDL routines. By default, the message is issued as an error, the message is output, and IDL takes the action specified by the ON_ERROR procedure.

As a side effect of issuing the error, the system variables !ERR, !ERROR, and !SYSERROR are set, and the text of the error message is placed in the system variable !ERR_STRING or (!SYSERR_STRING, if the error is a system error). See "Error System Variables" on page 11-8.

As an example, assume the statement:

MESSAGE, 'Unexpected value encountered.'

is executed in a procedure named CALC. IDL would print:

% CALC: Unexpected value encountered.

and execution would halt.

The MESSAGE procedure accepts several keywords that modify its behavior. See the IDL Reference Guide for additional details.

Another use of MESSAGE involves re-signaling trapped errors. For example, the following code uses ON_IOERROR to read from a file until an error (presumably end-of-file) occurs. It then closes the file and reissues the error.

OPENR, UNIT, 'DATA.DAT', /GET_LUN	Open the data file.

ON_IOERROR, EOD	Arrange for jump to label EOD when an input/output error occurs.

WHILE 1 DO READF, UNIT, LINE	Read every line of the file.

EOD: ON_IOERROR, NULL	An error has occurred. Cancel the input/output error trap.

FREE_LUN, UNIT	Close the file.

MESSAGE, !ERR_STRING, /NONAME, /ON_IOERROR
Reissue the error. !ERR_STRING contains the appropriate text. The ON_IOERROR keyword causes it to be issued as an input/output error. Use of NONAME
prevents MESSAGE from tacking the name of the current routine to the beginning of the message string since !ERR_STRING already contains it.


Obtaining Traceback Information

It is sometimes useful for a procedure or function to obtain information about its caller(s). The HELP procedure returns, in a string array, the contents of the procedure stack when the CALLS keyword parameter is specified. The first element of the resulting array contains the module name, source filename, and line number of the current level. The second element contains the same information for the caller of the current level, and so on, back to the level of the main program.

For example, the following code fragment prints the name of its caller, followed by the source filename and line number of the call:

HELP, CALLS = A

PRINT, 'called from:', A(1);print 2nd element

This results in a message of the following form:

Called from: DIST </usr2/idl/lib/dist.pro (27)>

Programs can readily parse the traceback information to extract the source file name and line number.


Error System Variables

IDL contains a number of system variables that are updated when errors occur. These system variables are described below.

!ERROR

This system variable is used to store the error code of the last error generated by IDL. Whenever an error occurs, IDL sets this system variable to the error code (a negative integer number) of the error. If an error has not occurred in the current IDL session, this system variable contains 0. For historical reasons, there is a similar system variable called !ERR that also contains the code of the last error message. However, some older IDL routines may use !ERR for other purposes, so !ERROR should always be used in preference to !ERR.

!ERR_STRING

This system variable is used to store the error message of the last error. Whenever an error occurs, IDL sets this system variable to the error message (a scalar string) that corresponds to the error code.

!SYSERROR

This system variable is used to store the error code of the last error generated by the operating system. When an operating system error occurs, IDL sets this system variable to the OS-defined error code. This system variable is a two-element longword array.

On most operating systems, the error code is returned in the first element of the array (i.e., !SYSERROR(0)) and the second element is set to 0. Some operating systems (e.g., VMS) can return two separate error codes for some types of filesystem errors. In these cases, !SYSERROR(1) is also set to an OS-defined error code.

!SYSERR_STRING

This system variable is used to store the error message of the last error generated by the operating system. When an operating system error occurs, IDL sets this system variable to the OS-defined error message string.


Math Errors

The detection of math errors, such as division by zero, overflow, and attempting to take the logarithm of a negative number, is hardware and operating system dependent. Some systems trap more errors than other systems.

On machines that do a thorough job of detecting floating-point exceptions and integer math errors, IDL prints an error message indicating the source statement that caused the error and continues program execution. Up to eight error messages are printed.

Accumulated Math Error Status

IDL handles math errors on those machines that implement the IEEE floating-point standard, but do not properly handle exceptions by keeping an accumulated math error status. This status, which is implemented as a longword, contains a bit for each type of math error that is detected by the hardware. IDL checks and clears this indicator each time the interactive prompt is issued, and if it is nonzero, prints an error message. A typical message is as follows:

% Program caused arithmetic error: Floating divide by 0

This means that a floating division by zero occurred since the last interactive prompt.

The CHECK_MATH function, described below, allows you to check and clear this accumulated math error status when desired. It is used to control how IDL treats floating-point exceptions on machines that do not properly support them. It can also disable printing of math error messages.

Special Floating-Point Values

Machines which implement the IEEE standard for binary floating-point arithmetic have two special values for undefined results: NaN (Not A Number) and Infinity. Infinity results when a result is larger than the largest representation. NaN is the result of an undefined computation such as zero divided by zero, taking the square-root of a negative number, or the logarithm of a non-positive number. In many cases, when IDL encounters the value NaN in a data set, it treats it as "missing data." The special values NaN and Infinity are also accessible in the read-only system variable !VALUES (see "System Variables" on page 3-7). These special operands propagate throughout the evaluation process—the result of any term involving these operands is one of these two special values. For example:

PRINT, 3 * !VALUES.F_NAN	Multiply NaN by 3

IDL prints:

NaN

It is important to remember that the value NaN is literally not a number, and as such cannot be compared with a number. For example, suppose you have an array that contains the value NaN:

A = [1.0, 2.0, !VALUES.F_NAN]

PRINT, A

IDL prints:

1.00000      2.00000          NaN

If you try to select elements of this array by comparing them with a number (using the WHERE function, for example), IDL will generate an error:

PRINT, WHERE(A GT 1.0) 	Print the indices of the elements of A with a value greater than one.

IDL prints:

1

% Program caused arithmetic error: Floating illegal operand

To avoid this problem, use the FINITE function (see "FINITE" on page 1-292 of the IDL Reference Guide) to make sure arguments to be compared are in fact valid floating-point numbers:

PRINT, WHERE(FINITE(A) EQ 1)

IDL prints the indices of the finite elements of A:

0           1

To then print the indices of the elements of A that are both finite and greater than 1.0, you could use the command:

PRINT, WHERE(A(WHERE(FINITE(A) EQ 1)) GT 1.0)

IDL prints:

1

Similarly, if you wanted to find out which elements of an array were  not valid floating-point numbers, you could use a command like:

PRINT, WHERE(FINITE(A) EQ 0)	Print the indices of the elements of A that are not valid floating-point numbers.

IDL prints:

2

Note that the special value Infinity can be compared to a floating point number. Thus, if:

B = [1.0, 2.0, !VALUES.F_INFINITY]

PRINT, B

IDL prints:

1.00000      2.00000          Inf

and

PRINT, WHERE(B GT 1.0)

IDL prints:

1           2

You can also compare numbers directly with the special value Infinity:

PRINT, WHERE(B EQ !VALUES.F_INFINITY)

IDL prints:

2

Note on Math Error Traps

On most machines, if math error traps are enabled, the result of illegal arithmetical operations is undetermined. For example, a floating-point division-by-zero error may return a finite value rather than the special value Infinity. To ensure that special floating-point values are returned, use the CHECK_MATH function with the TRAP keyword set to zero to disable math error traps. See "CHECK_MATH" on page 1-94 of the IDL Reference Guide for details.

The FINITE Function

Use the FINITE function to explicitly check the validity of floating-point or double-precision operands on machines which use the IEEE floating-point standard. For example, to check the result of the EXP function for validity, use the following statement:

A = EXP(EXPRESSION)	Perform exponentiation.

IF NOT FINITE(A) THEN PRINT, 'Overflow occurred'
Print error message.

If A is an array, use the statement:

IF FINITE(A) NE N_ELEMENTS(A) THEN error

Integer Conversions

It must be stressed that when converting from floating to byte, short integer, or longword types, if overflow is important, you must explicitly check to be sure the operands are in range. Conversions to the above types from floating point, double precision, complex, and string types do not check for overflow—they simply convert the operand to longword integer and extract the low 8, 16, or 32 bits.

When run on a Sun workstation, the program:

A = 2.0 ^ 31 + 2

PRINT, LONG(A), LONG(-A), FIX(A), FIX(-A), BYTE(A), BYTE(-A)

(which creates a floating-point number 2 larger than the largest positive longword integer), prints the following:

2147483647 -2147483648 -1 0 255 0
% Program caused arithmetic error: Floating illegal operand

This result is incorrect.

Caution: No error message will appear if you attempt to convert a floating number whose absolute value is between 2^15 and 2^31 - 1 to short integer even though the result is incorrect. Similarly, converting a number in the range of 256 to 2^31- 1 from floating, complex, or double to byte type produces an incorrect result, but no error message. Furthermore, integer overflow is usually not detected. Your programs must guard explicitly against it.

CHECK_MATH Function

As mentioned above, the CHECK_MATH function allows you to test the accumulated math error status. It also is used to enable or disable traps. Each call to this function returns and clears the value of this status.

Note: CHECK_MATH does not properly maintain an accumulated error status on machines that do not implement the IEEE standard for floating-point math.

It is good programming practice to bracket segments of code which might produce an arithmetic error with calls to CHECK_MATH to properly handle ill-conditioned result. It has the form:

Result = CHECK_MATH(Print_Flag, Message_Inhibit)

If an error condition has been detected and the first optional parameter is present and nonzero, an error message is printed and program execution continues; otherwise, the routine runs silently.

If the second optional parameter, Message_Inhibit, is present and nonzero, error messages are disabled for subsequent math errors. The accumulated math error status is maintained even when error messages are disabled. When the interpreter exits back to the prompt, accumulated math error messages which have been suppressed are printed. To suppress this final message, call CHECK_MATH to clear the accumulated error status before returning to the interactive mode.

The error status is encoded as an integer, where each binary bit represents an error, as shown in Table 11.2.

Value	Condition
0	No errors detected since the last interactive prompt or call to CHECK_MATH
1	Integer divided by zero
2	Integer overflow
16	Floating point divided by zero
32	Floating-point underflow
64	Floating-point overflow
128	Floating-point operand error. An illegal operand was encountered, such as a negative operand to the SQRT or ALOG functions, or an attempt to convert to integer a number whose absolute value is greater than 2^31 - 1
Table 11.2 Math Error Status Values (note that not all machines detect all errors)

 Note that not all machines detect all errors.

Enabling and Disabling Math Traps

To enable trapping, use the following statement:

JUNK = CHECK_MATH(TRAP = 1)

To disable trapping, use the following statement:

JUNK = CHECK_MATH(TRAP = 0)

CHECK_MATH Examples

Assume that there is a critical section of code that is likely to produce an error. The following example shows how to check for errors, and if one is detected, how to repeat the code with different parameters.

JUNK = CHECK_MATH(1, 1)	Clear error status from previous operations, and print error messages if an error exists. Also, disable automatic printing of subsequent math errors.

AGAIN: ... 	Critical section goes here.

IF CHECK_MATH(0, 0) NE 0 THEN BEGIN	Did an arithmetic error occur? Also, re-enable the printing of subsequent math errors.

PRINT, 'Math error occurred in critical section.'
Input new parameters from user.

READ, 'Enter new values.',...

GOTO, AGAIN 	And retry.

ENDIF

Hardware-Dependent Math Error Handling

Sun 4 (SPARC), SunOS 4 Error Handling

Improper floating-point operations are trapped if traps are enabled, which is the default. The result of an improper operation contains garbage, not an IEEE special value as would be expected if traps are enabled. When traps are disabled, by the CHECK_MATH function, the correct special values result, but no error message occurs until the next interactive prompt is issued.

DECStation Error Handling

Integer divide by zero is always trapped. Integer overflows produce no indication of error; zero results. By default, floating-point traps are disabled. The result of an improper floating-point operation that occurs when traps are enabled is garbage. If traps are not enabled, the correct IEEE special value results.

VAX/VMS Error Handling

The VAX does not implement the IEEE floating-point standard. The special values NaN and Infinity cannot occur. The FINITE function always returns a value of 1.

Most floating-point functions check for and report overflow or illegal operands. Traps can be disabled, in which case math error messages are not immediately printed. Integer overflow is not detected, while integer divide by zero is detected.

Silicon Graphics Iris Error Handling

Error handling for the Iris is identical to that described for SunOS 4 above.


Informational Routines

The informational routines, N_ELEMENTS, SIZE, N_PARAMS, and KEYWORD_SET, are useful in procedures and functions to check if arguments are supplied. Procedures should be written to check that all required arguments are supplied and to supply reasonable default values for missing optional parameters.

KEYWORD_SET Function

The KEYWORD_SET function simply returns a 1 (true), if its parameter is defined and nonzero; otherwise, it returns zero (false). For example, assume that a procedure is written which performs and returns the result of a computation. If the keyword PLOT is present and nonzero, the procedure also plots its result as follows:

PRO XYZ, RESULT, PLOT = PLOT	Procedure definition.

...	Compute RESULT.

IF KEYWORD_SET(PLOT) THEN PLOT, RESULT
Plot result if keyword parameter is set.

END

A call to this procedure that produces a plot is shown in the following statement.

XYZ, R, /PLOT

N_PARAMS Function

The N_PARAMS function returns the number of positional arguments (not keyword arguments) present in a procedure or function call. A frequent use is to call N_PARAMS to determine if all arguments are present and if not, to supply default values for missing parameters. For example:

PRO XPRINT, XX, YY	Print values of XX and YY. If XX is omitted, print values of YY versus element number.

CASE N_PARAMS() OF 	Check number of arguments.

1: BEGIN 	Single-argument case.

Y = XX	First argument is y values.

X = INDGEN(N_ELEMENTS(Y))	Create vector of subscript indices.

END

2: BEGIN & Y = YY & X = XX & END	Two-argument case. Copy parameters to local arguments.

ELSE: MESSAGE, 'Wrong number of arguments'
Wrong number of args: print message.

ENDCASE

...	Remainder of procedure.

END

N_ELEMENTS Function

The N_ELEMENTS function returns the number of elements contained in any expression or variable. Scalars always have one element. The number of elements in arrays or vectors is equal to the product of the dimensions. The N_ELEMENTS function returns zero if its parameter is an undefined variable. The result is always a longword scalar.

For example, the following expression is equal to the mean of a numeric vector or array.

TOTAL(ARR) / N_ELEMENTS(ARR)

The N_ELEMENTS function provides a convenient method of determining if a variable is defined. The following statement sets the variable ABC to zero if it is undefined; otherwise, the variable is not changed.

IF N_ELEMENTS(ABC) EQ 0 THEN ABC = 0

N_ELEMENTS is frequently used to check for omitted plain and keyword arguments. N_PARAMS cannot be used to check for the number of keyword arguments because it returns only the number of plain arguments. An example of using N_ELEMENTS to check for a keyword parameter is as follows:

PRO ZOOM, IMAGE, FACTOR = FACTOR	Display an image with a given zoom factor. If factor is omitted, use 4.

IF N_ELEMENTS(FACTOR) EQ 0 THEN FACTOR = 4
Supply default for missing keyword parameter.

SIZE Function

The SIZE function returns a vector that contains information indicating the size and type of the parameter. The returned vector is always of longword type. The first element is equal to the number of dimensions of the parameter and is zero if the parameter is a scalar. The following elements contain the size of each dimension. After the dimension sizes, the last two elements indicate the type of the parameter and the total number of elements, respectively. The type is encoded as follows:

Type Code	Data Type
0	Undefined
1	Byte
2	Integer
3	Longword integer
4	Floating point
5	Double-precision floating
6	Complex floating
7	String
8	Structure
Table 11.3 Type Codes Returned by the SIZE Function

Examples

Assume A is an integer array with dimensions of (3,4,5). Executing the statement,

B = SIZE(A)

assigns to the variable, B, a six-element vector containing:

b0	3	Three dimensions
b1	3	First dimension
b2	4	Second dimension
b3	5	Third dimension
b4	2	Integer type
b5	60	Number of elements = 3*4*5
A code segment that checks that a variable (A) is two-dimensional and extracts the dimensions is shown below.

S = SIZE(A)	Get size vector.

IF S(0) NE 2 THEN $	Check if two dimensional.

   MESSAGE, 'Variable a is not two dimensional.'
Print error message.

NX = S(1) & NY = S(2)	Get number of columns and rows.


Program Control Routines

The program control procedures are largely self-explanatory with the exception of the EXECUTE function. CALL_FUNCTION and CALL_PROCEDURE are used to indirectly call functions and procedures whose names are contained in strings. The EXIT procedure exits the IDL session. STOP halts execution of a program or batch file and prints the values of its optional parameters. WAIT, as its name implies, pauses execution for a given amount of time specified in seconds.

EXECUTE, CALL_FUNCTION, and CALL_PROCEDURE Routines

The EXECUTE function compiles and executes one or more IDL statements contained in its string parameter during runtime.

EXECUTE is limited by two factors:

•	Calls to EXECUTE cannot be nested, so a routine called by EXECUTE cannot use EXECUTE itself.

•	The need to compile the string at runtime makes EXECUTE inefficient in terms of speed.

The CALL_FUNCTION and CALL_PROCEDURE routines provide much of the functionality of EXECUTE without imposing these limitations and should be used in preference to EXECUTE when possible.

The result of the EXECUTE function is true (1) if the string was successfully compiled and executed. If an error occurred during either phase, the result is false (0). If an error occurs, an error message is printed.

The string can have a maximum length of 131 characters. Multiple statements in the string should be separated with the "&" character. GOTO statements and labels are not allowed.

Do not use EXECUTE to create new variables inside procedures or functions. All variables used by the string that is executed should be referenced or defined when the program unit is originally compiled. New variables cannot be created after a procedure or function is compiled. Attempts to create new variables will result in the error "Program data area full."

Example

This example, taken from the routine SVDFIT, calls a function whose name is passed to SVDFIT via a keyword parameter as a string. If the keyword parameter is omitted, the function POLY is called.

FUNCTION SVDFIT,..., FUNCT=FUNCT	Function declaration.

...

IF N_ELEMENTS(FUNCT) EQ 0 THEN FUNCT = 'POLY'
Use default name, POLY, for function if not specified.

Z = EXECUTE('A = '+FUNCT+'(X,M)')	Make a string of the form "a = funct(x,m)", and execute it.

...

The above example is easily made more efficient by replacing the call to EXECUTE with the following line:

A = CALL_FUNCTION(FUNCT, X, M)


Handles - Dynamic Memory Structures in IDL
Handles—Dynamic Memory Structures in IDL

Dynamic memory structures, such as linked lists and trees, can be created in IDL using "handles" which are similar to "pointers" as found in languages such as C and Pascal. An IDL handle is a dynamically-allocated variable that is identified by a unique longword integer value known as a "handle ID". Handles can have a value, of any data type and organization, associated with them.

Because handles are dynamic, they can be used to create complex data structures. They are also global in scope, but do not suffer from the limitations of COMMON blocks. That is, handles are available to all program units at all times. (Remember, however, that IDL variables containing handle IDs are not global in scope and must be declared in a COMMON block if you want to share them between program units.)

The following routines control the creation and management of handles:

•	HANDLE_CREATE creates new handles.

•	HANDLE_FREE frees an existing handle and any of its children.

•	HANDLE_INFO returns information about a handle.

•	HANDLE_MOVE moves a handle to a new location.

•	HANDLE_VALUE sets or returns the value associated with an existing handle.

Full documentation for these routines can be found in the IDL Reference Guide.

Handle Terminology

The following terms are used to describe handles in the following documentation:

•	Handle ID: The unique longword integer identifier associated with a handle.

•	Handle value: Data of any IDL type and organization associated with a handle.

•	Top-level handle: A handle at the top of a handle hierarchy. A top-level handle can have children, but does not have a parent.

•	Parents, children, and siblings: These terms describe the relationship between handles in a handle hierarchy. When a new handle is created, it can be the start of a new handle hierarchy (a top-level handle) or it can belong to the level of a widget hierarchy below an existing handle. A handle created in this way is said to be a child of the specified parent. Parents can have any number of children. All handles that share the same parent are said to be siblings.

Creating and Destroying Handles

The HANDLE_CREATE function is used to create a new handle. Handles can be created as top-level handles, the last child of an existing handle, the first child of an existing handle, or as the next sibling of an existing handle. HANDLE_CREATE is a function that returns the handle ID (a longword integer) of the newly-created handle.

•	To create a top-level handle (i.e., a handle without a parent), call the HANDLE_CREATE function without an argument:

newhandle = HANDLE_CREATE()

•	To create a new handle that is the last child of a specified parent, call HANDLE_CREATE with an argument that specifies the handle ID of the parent:

newhandle = HANDLE_CREATE(ParentID)

•	To create a new handle that is the first child of a specified parent, call HANDLE_CREATE and set the FIRST_CHILD keyword:

newhandle = HANDLE_CREATE(ParentID, /FIRST_CHILD)

Any existing children of the parent become later siblings of the new first child.

•	To create a handle as the next sibling of an existing handle, call HANDLE_CREATE and set the SIBLING keyword:

newhandle = HANDLE_CREATE(HandleID, /SIBLING)

Any previously-created siblings of HandleID become later siblings of the new handle.

Setting and Obtaining Handle Values

Handles can have a value, of any IDL data type (e.g., integer, string, floating-point, etc.) and organization (e.g., scalar, array, structure, etc.) associated with them. This value, called the "handle value", can be set or obtained by using the HANDLE_VALUE procedure.

•	To set a handle value, call HANDLE_VALUE with two arguments and set the SET keyword. The first argument specifies the handle ID to be assigned the new value. The second argument is the new handle value. For example, the following command sets the value of handle whose ID is stored in the variable top to a 3-element, floating-point vector:

HANDLE_VALUE, top, [2.0, 4.0, 2.0], /SET

•	To return a a handle's value, call HANDLE_VALUE with two arguments. The first specifies the handle ID to get a value from. The second argument is a named variable in which the handle value is returned. For example, the following command returns the value of handle top in the variable value:

HANDLE_VALUE, top, value

Obtaining Information about Handles

The HANDLE_INFO function can be used to return handy information about a handle's validity and connections. HANDLE_INFO can be used to determine if a handle ID is valid, return the number of children a handle has, return the ID of the first child of a handle, return the ID of the parent of a handle, or return the ID of a handle's next sibling.

HANDLE_INFO accepts a single argument, the ID of the handle for which information is desired. This argument can also be an array of ID's. In this case, HANDLE_INFO returns an array of results with the same number of elements as the argument.

•	To verify that a handle ID is valid, call HANDLE_INFO without any keywords. True (1) is returned if the handle ID exists. For example, to verify that handle top exists, you could use the command:

IF HANDLE_INFO(top) THEN PRINT, 'Handle top exists!'

•	To return the number of children a handle has, call HANDLE_INFO and set the NUM_CHILDREN keyword:

children = HANDLE_INFO(top, /NUM_CHILDREN)

•	To return the ID of the first child of a handle, call HANDLE_INFO and set the FIRST_CHILD keyword:

firstchildid = HANDLE_INFO(handle, /FIRST_CHILD)

•	To return the ID of a handle's parent handle, call HANDLE_INFO and set the PARENT keyword:

parentid = HANDLE_INFO(handle, /PARENT)

•	To return the ID of the sibling handle following the specified handle, call HANDLE_INFO and set the SIBLING keyword:

nextsiblingid = HANDLE_INFO(handle, /SIBLING)

Moving Handles

The HANDLE_MOVE procedure can be used to move previously-created handles to new locations in a handle hierarchy. HANDLE_MOVE accepts two arguments. The first argument is the ID of a handle relative to which another handle will be moved (this handle is said to be "static"). The second argument is the ID of the handle to be moved. A handle can be moved such that it becomes the last child, first child, or next sibling of the static handle. HANDLE_MOVE can also be used to turn a child handle into a top-level handle.

The following examples assume that the IDs of the static and moving handles are stored in the variables static and move, respectively.

•	To make move the last child of static, call HANDLE_MOVE without any keywords:

HANDLE_MOVE, static, move

•	To make move the first child of static, call HANDLE_MOVE and set the FIRST_CHILD keyword:

HANDLE_MOVE, static, move, /FIRST_CHILD

•	To make move the sibling immediately after static, call HANDLE_MOVE and set the SIBLING keyword:

HANDLE_MOVE, static, move, /SIBLING

•	To make move a top-level handle without a parent, call HANDLE_MOVE with the first argument (the static ID) set to zero:

HANDLE_MOVE, 0, move

Example—Using Handles to Create a Linked List

The following example uses handles to create and manipulate a linked list. One procedure reads string input from the keyboard and creates a list of handles that have the strings as their values. Another procedure prints the strings, given the ID of the top-level handle. A third procedure uses a modified "bubble sort" algorithm to reorder the handles in the list so the strings are in alphabetical order.

Though the code of the example programs is shown below, you don't have to type them in. The programs can be found in the misc subdirectory of the demo subdirectory of the IDL Users' Library (the lib subdirectory of the IDL distribution).

Creating a Linked List

The following program prompts the user to enter a series of strings from the keyboard. After reading each string, it creates a new handle and assigns the string to the handles' value. Any number of strings can be entered. When the user is finished entering strings, the program can be exited by entering a period by itself at the "Enter string:" prompt. This program demonstrates the use of the HANDLE_CREATE routine.

The text of the program shown below can be found in the file readnames.pro in the misc subdirectory of the demo subdirectory of the IDL Users' Library (the lib subdirectory of the IDL distribution).

PRO readnames, top	READNAMES accepts one argument, a named variable in which to return the handle ID of the top-level handle.

newstring = ''	Initialize the input string variable.

top = HANDLE_CREATE()	Create the top-level handle.

PRINT,'Enter a list of names. Enter a period (.) to stop list entry.'
Print instructions for this program.

WHILE newstring NE "." DO BEGIN	Continue accepting input until a period is entered.

READ, newstring, PROMPT='Enter string: '
Read a new string from the keyboard.

IF newstring NE '.' THEN $	Create a child with the string as its value.

   junk = HANDLE_CREATE(top, VALUE=newstring)

ENDWHILE

END	End of READNAMES program.

Run the READNAMES program by entering the following command at the IDL prompt:

IDL> readnames, top

Type a string, press Return, and the program prompts for another string. You can enter as many strings as you want. Each time a string is entered, READNAMES creates a new child handle with that string as its value. For example, you could enter the following three strings (used in the rest of this example):

Enter a list of names.  Enter a period (.) to stop list entry.

Enter string: keith

Enter string: doogie

Enter string: juli

Enter string: .

Figure 11.2 shows one way of visualizing the linked list that we've created.

Printing the Linked List

The next program in our example accepts the ID of the top-level handle (as returned by the READNAMES program) and prints the values of all of its children (i.e., all the values in the list). This program demonstrates the use of the HANDLE_VALUE and HANDLE_INFO routines.

The text of the program shown below can be found in the file printnames.pro in the misc subdirectory of the demo subdirectory of the IDL Users' Library (the lib subdirectory of the IDL distribution).

PRO printnames, top	PRINTNAMES accepts one arugument, a top-level handle ID as returned by READNAMES. Note that the PRINTNAMES program does not need to know how many elements are in the list, nor does it need to explicitly know the handle ID's of the list elements.

handle = HANDLE_INFO(top, /FIRST_CHILD)
Retrieve the ID of the first child of the top-level handle.

WHILE handle NE 0 DO BEGIN	HANDLE_INFO returns 0 if the requested ID does not exist.

  HANDLE_VALUE, handle, name	Get the value attached to the child handle.

  PRINT, name	Print that value.

  handle=HANDLE_INFO(handle, /SIBLING)
Get ID of the next sibling.

ENDWHILE

END	End of the READNAMES program.

If we run the PRINTNAMES program with the list generated in the previous example:

IDL> printnames, top

IDL prints:

keith

doogie

juli

A Simple Sorting Routine for the Linked List

The next example program takes a list generated by READNAMES and moves the child handles so that their values are in alphabetical order. This program demonstrates the use of HANDLE_VALUE and HANDLE_INFO in conjuction with the HANDLE_MOVE routine.

The sorting algorithm used in this program is a variation on the classic "bubble sort". However, instead of starting with the last element in the list and letting lower values "rise" to the top, this example starts at the top of the list and lets higher ("heavier") values "sink" to the bottom of the list (hence the name SINKSORT). Note that this is not the most efficient sorting algorithm and is shown simply as an illustration. For real sorting applications, use IDL's SORT function.

The text of the program shown below can be found in the file sinksort.pro in the misc subdirectory of the demo subdirectory of the IDL Users' Library (the lib subdirectory of the IDL distribution).

PRO sinksort, top	SINKSORT accepts a single argument, the top-level handle of a linked list as returned by READNAMES.

swap = 1	Initialize flags.

last = 0

WHILE swap NE 0 DO BEGIN	Continue the sorting until no swaps are made. If no adjacent handles need to be swapped, the list is in alphabetical order.

  handle = HANDLE_INFO(top, /FIRST_CHILD)
Get the ID of the first child.

  handle2 = HANDLE_INFO(handle, /SIBLING)
Get the ID of the child's next sibling.

  swap = 0	Reset swap flag.

  WHILE handle2 NE last DO BEGIN	Begin comparing adjacent handles until we're at the end of the unsorted part of the list.

     HANDLE_VALUE, handle, current	Get the value of handle.

     HANDLE_VALUE, handle2, next	Get the value of handle2.

     IF current GT next THEN BEGIN	Compare the values. If current is greater than next, then handle and handle2 are out of alphabetical order and their positions must be swapped (i.e., handle sinks to a lower position in the list).

           HANDLE_MOVE, handle2, handle, /SIBLING
This command makes handle the next sibling of handle2, effectively swapping their positions with a single command.

           swap = swap + 1	A swap has been made, so increment the swap counter.

     ENDIF ELSE handle=handle2	If no swap was necessary, make handle2 the handle to be compared to others in the list and repeat the process.

     handle2 = HANDLE_INFO(handle, /SIBLING)
Get the ID of handle's next sibling.

  ENDWHILE

  last = handle	All later siblings of handle have been sorted. Update last to reflect this.

ENDWHILE

END	End of the SINKSORT program.

To run the SINKSORT routine with the list from our previous examples as input, enter:

IDL> sinksort, top

Figure 11.3

shows how our example handles get moved about by the SINKSORT algorithm. We can see the results of the sorting by calling the PRINTNAMES routine again:

IDL> printnames, top

IDL prints:

doogie

juli

keith

and we see that now the names are in alphabetical order.

Example Files—Using Handles to Create Binary Trees

Two more complicated example programs demonstrate the use of IDL handles to create and search a simple tree structure. These files, named idl_tree.pro and tree_example.pro, can be found in the misc subdirectory of the demo subdirectory of the IDL Users' Library (the lib subdirectory of the IDL distribution).

To run the tree examples, enter the following commands at the IDL prompt:

IDL> .run idl_tree idl_tree tree_example
Compile the programs. idl_tree must be compiled twice because it contains a recursive function.

IDL> tree_example	Run the tree_example.

The TREE_EXAMPLE and IDL_TREE routines create a binary tree with ten nodes whose values are structures that contain random values for two fields, "Time" and "Data". The TREE_EXAMPLE routine then prints the tree sorted by both time and data. It then searches for and deletes the nodes containing the fourth and second data values. The resulting 8-node trees are again printed in both time and data order.

A detailed explication of the TREE_EXAMPLE and IDL_TREE routines is beyond the scope of this chapter. Interested users should examine the files, starting with tree_example.pro, to see how the trees are created and searched.

References

A popular reference work that describes dynamic memory structures such as trees and linked lists is:

Aho, Alfred V., Data Structures and Algorithms, Addison-Wesley, 1983, ISBN: 0-201-00023-7

Jump forward to Efficient Programming

Jump backward to Defining Procedures and Functions


Efficient Programming
12	Efficient Programming

Chapter Overview

Knowledge of IDL's implementation and the pitfalls of virtual memory can be used to greatly improve the efficiency of IDL programs. In IDL, complicated computations can be specified at a high level. Therefore, inefficient IDL programs can suffer severe speed penalties — perhaps much more so than with most other languages.

Techniques for writing efficient programs in IDL are identical to those in other computer languages with the addition of the following simple guidelines:

•	Use array operations rather than loops wherever possible. Try to avoid loops with high repetition counts.

•	Use IDL system functions and procedures wherever possible.

•	Access array data in machine address order.

Attention also must be given to algorithm complexity and efficiency, as this is usually the greatest determinant of resources used.

Note: The results of timing various examples are given in this chapter. Many factors influence such timings; hence, time required may not be the same for your machine. All timings reported here were conducted on the same machine (a Sun 3/160 with 4M primary memory) under the same conditions. Exact times may differ from machine to machine, but the timings can be used to evaluate the relative efficiency of the examples given.


Topics in Efficient Programming Chapter
Efficient Programming

This chapter provides an overview of IDL's implementation and discusses ways to maximize the efficiency of IDL programs.

Topics Covered:

Expression Evaluation Order

Avoid IF Statements

Use Vector and Array Operations

Use IDL System Functions and Procedures

Use Constants of the Correct Type

Eliminate Invariant Expressions

Virtual Memory

IDL Implementation

Jump forward to Interactive Support

Jump backward to Programming Routines


Expression Evaluation Order

The order in which an expression is evaluated can have a significant effect on program speed. Consider the following statement, where A is an array:

B = A * 16. / MAX(A)	Scale A from 0 to 16.

This statement first multiplies every element in A by 16 and then divides each element by the value of the maximum element. The number of operations required is twice the number of elements in A. This statement took 24 seconds to execute on a 512 x 512 single-precision, floating-point array. A much faster way of computing the same result is used in the following statement:

B = A * (16./MAX(A))	Scale A from 0 to 16 using only one array operation.

or

B = 16./MAX(A) * A 	Operators of equal priority are evaluated from left to right. Only one array operation is required.

The faster method only performs one operation for each element in A, plus one scalar division. It executes in 14 seconds on the same floating-point array as above.


Avoid IF Statements

Programs with array expressions run faster than programs with scalars, loops, and IF statements. Some examples of slow and fast ways to achieve the same results follow.

Example—Summing Elements

The first example adds all positive elements of array B to array A.

FOR I = 0, (N-1) DO IF B(I) GT 0 THEN A(I) = A(I) + B(I)
Using a loop will be slow.

A = A + (B GT 0) * B	Fast way: Mask out negative elements using array operations.

A = A + (B > 0)	Faster way: Add B > 0.

When an IF statement appears in the middle of a loop with each element of an array in the conditional, the loop can often be eliminated by using logical array expressions.

Example—Using Array Operators and the WHERE Function

In the next example, each element of C is set to the square-root of A if A(I) is positive; otherwise, C(I) is set to minus the square-root of the absolute value of A(I).

FOR I=0,(N-1) DO IF A(I) LE 0 THEN $	Using an IF statement is slow.

    C(I)=-SQRT(-A(I)) ELSE C(I)=SQRT(A(I))

C = ((A GT 0) * 2-1) * SQRT(ABS(A))	Fast way.

For a 10,000-element, floating-point vector, the statement using the IF took 8.5 seconds to execute, while the version using the array operation required only 0.7 seconds.

The expression (A GT 0) has the value 1 if A(I) is positive and has the value 0 if A(I)is not. (A GT 0)* 2 - 1 is equal to +1 if A(I) is positive or -1 if A(I) is negative, accomplishing the desired result without resorting to loops or IF statements.

Another method is to use the WHERE function to determine the subscripts of the negative elements of A and negate the corresponding elements of the result.

NEGS = WHERE(A LT 0)	Get subscripts of negative elements.

C = SQRT(ABS(A)) 	Take root of absolute value.

C(NEGS) = -C(NEGS)	Negate elements in C corresponding to negative elements in A.

In this version, the same 10,000-element, floating-point array processed in 0.8 seconds.


Use Vector and Array Operators
Use Vector and Array Operations

Whenever possible, vector and array data should always be processed with IDL array operations instead of scalar operations in a loop. For example, consider the problem of inverting a 512 x 512 image. This problem arises because approximately half the available image display devices consider the origin to be the lower-left corner of the screen, while the other half recognize it as the upper-left corner.

The following example is for demonstration only. The IDL system variable !ORDER should be used to control the origin of image devices. The ORDER keyword to the TV procedure serves the same purpose.

A programmer without experience in using IDL might be tempted to write the following nested loop structure to solve this problem:

FOR I = 0, 511 DO FOR J = 0, 255 DO BEGIN

TEMP = IMAGE(I, J)	Temporarily save pixel image.

IMAGE(I, J) = IMAGE(I, 511 - J)	Exchange pixel in same column from corresponding row at bottom.

IMAGE(I, 511-J) = TEMP

ENDFOR

Executing this code required 143 seconds. A more efficient approach to this problem capitalizes on IDL's ability to process arrays as a single entity:

FOR J = 0, 255 DO BEGIN

TEMP = IMAGE(*, J)	Temporarily save current row.

IMAGE(*, J) = IMAGE(*, 511-J)	Exchange row with corresponding row at bottom.

IMAGE(*, 511-J) = TEMP

ENDFOR

Executing this revised code was 13 times faster, requiring 11 seconds. At the cost of using twice as much memory, processing can be simplified even further by using the following statements:

IMAGE2 = BYTARR(512, 512)	Get a second array to hold inverted copy.

FOR J = 0, 511 DO IMAGE2(*, J) = IMAGE(*, 511-J)
Copy the rows from the bottom up.

This version also ran in 11 seconds. Even more efficient is the single line:

IMAGE2 = IMAGE(*, 511 - INDGEN(512))

that reverses the array using subscript ranges and array-valued subscripts. This statement executed in six seconds, an almost 50 percent improvement.

Finally, using the built-in ROTATE function is quickest of all:

IMAGE = ROTATE(IMAGE, 7)

Inverting the image is equivalent to transposing it and rotating it 270 degrees clockwise. This simple statement took 0.6 seconds to execute.


Use IDL System Functions and Routines
Use IDL System Functions and Procedures

IDL supplies a number of built-in functions and procedures to perform common operations. These system-supplied functions have been carefully optimized and are almost always much faster than writing the equivalent operation in IDL with loops and subscripting.

Example

A common operation is to find the sum of the elements in an array or subarray. The TOTAL function directly and efficiently evaluates this sum at least 10 times faster than directly coding the sum.

SUM = 0. & FOR I = J, K DO SUM = SUM + ARRAY(I)
Slow way: Initialize SUM and sum each element.

SUM = TOTAL(ARRAY(J:K))	Efficient, simple way.

Using a 10,000-element, floating-point vector and summing all of its elements took four seconds with the first statement and 0.09 seconds with the second. Similar savings result when finding the minimum and maximum elements in an array (MIN and MAX functions), sorting (SORT function), finding zero or nonzero elements (WHERE function), etc.


Use Constants of the Correct Type

As explained in "Constants and Variables" on page 3-1, the syntax of a constant determines its type. Efficiency is adversely affected when the type of a constant must be converted during expression evaluation. Consider the following expression:

A + 5

If the variable A is of floating-point type, the constant 5 must be converted from short integer type to floating point each time the expression is evaluated.

The type of a constant also has an important effect in array expressions. Care must be taken to write constants of the correct type. In particular, when performing arithmetic on byte arrays with the intent of obtaining byte results, be sure to use byte constants; e.g., nB. For example, if A is a byte array, the result of the expression  A + 5B is a byte array, while A + 5 yields a 16-bit integer array.


Eliminate Invariant Expressions

Expressions whose values do not change inside a loop should be moved outside the loop. For example, in the loop:

FOR I = 0, N - 1 DO ARR(I, 2*J-1) = ...,

the expression (2*J-1) is invariant and should be evaluated only once before the loop is entered:

TEMP = 2*J-1

FOR I = 0, N-1 DO ARR(I, TEMP) = ....


Virtual Memory

The IDL programmer and user must be cognizant of the characteristics of virtual memory computer systems to avoid penalty. Virtual memory allows the computer to execute programs that require more memory than is actually present in the machine by keeping those portions of programs and data that are not being used on the disk. Although this process is transparent to the user, it greatly affects the efficiency of the program.

IDL arrays are stored in dynamically allocated memory. Although the program can address large amounts of data, only a small portion of that data actually resides in physical memory at any given moment; the remainder is stored on disk. The portion of data and program code in real physical memory is commonly called the working set.

When an attempt is made to access a datum in virtual memory not currently residing in physical memory, the operating system suspends IDL, arranges for the page of memory containing the datum to be moved into physical memory and then allows IDL to continue. This process involves deciding where the datum should go in memory, writing the current contents of the selected memory page out to the disk, and reading the page with the datum into the selected memory page. A page fault is said to occur each time this process takes place. Because the time required to read from or write to the disk is very large in relation to the physical memory access time, page faults become an important consideration.

When using IDL with large arrays, it is important to have access to sufficient physical and virtual memory. Given a suitable amount of physical memory, the parameters that regulate virtual memory require adjustment to assure best performance. These parameters are discussed below. See "Virtual Memory System Parameters" on page 12-8. If you suspect that lack of physical or virtual memory is causing problems, consult your system manager.

Access Large Arrays by Memory Order

When an array is larger than or close to the working set size (i.e., the amount of physical memory available for the process), it is preferable to access it in memory address order.

Consider the process of transposing a large array. Assume the array is a 512 x 512 byte image with a 100 kilobyte working set. The array requires 512 x 512, or approximately 250 kilobytes. Less than half of the image can be in memory at any one instant.

In the transpose operation, each row must be interchanged with the corresponding column. The first row, containing the first 512 bytes of the image, will be read into memory, if necessary, and written to the first column. Because arrays are stored in row order (the first subscript varies the fastest), one column of the image spans a range of addresses almost equal to the size of the entire image. To write the first column, 250,000 bytes of data must be read into physical memory, updated, and written back to the disk. This process must be repeated for each column, requiring the entire array be read and written almost 512 times. The time required to transpose the array using the method described above is several minutes.

The IDL TRANSPOSE function transposes large arrays by dividing them into subarrays smaller than the working set size enabling it to transpose a 512 x 512 image in less than 10 seconds.

Example

Consider the operation of the following IDL statement:

FOR X = 0, 511 DO FOR Y = 0, 511 DO ARR(X, Y) = ...

This statement requires an extremely large execution time because the entire array must be transferred between memory and the disk 512 times. The proper form of the statement is to process the points in address order by using the following statement:

FOR Y = 0, 511 DO FOR X = 0, 511 DO ARR(X, Y) = ...

This approach cuts computing time by a factor of at least 50.

Running Out of Virtual Memory

If you process images with IDL and use the vendor-supplied default system parameters (especially if you have a small system), you will encounter the error message

% Unable to allocate memory.

This error message means that IDL was unable to obtain enough virtual memory to hold all your data. Whenever you define an array, image, or vector, IDL asks the operating system for some virtual memory in which to store the data. When you reassign the variable, IDL frees the memory for re-use.

The first time you get this error, you will either have to stop what you are doing and exit IDL or delete unused variables containing images or arrays, thereby releasing enough virtual memory to continue. You can delete the memory allocation of array variables by setting the variable equal to a scalar value.

If you need to exit IDL, you first should use the SAVE procedure to save your variables in an IDL save file. Later, you will be able to recover those variables from the save file using the RESTORE procedure.

The HELP,/MEMORY command tells you how much virtual memory you have allocated. For example, a 512 x 512 complex floating array requires 8*512^2 bytes or about 2 megabytes of virtual memory because each complex element requires 8 bytes. Deleting a variable containing a 512 x 512 complex array will increase the amount of virtual memory available by this amount.

Minimizing Virtual Memory

If virtual memory is a problem, try to tailor your programming to minimize the number of images held in IDL variables. Keep in mind that IDL creates temporary arrays to evaluate expressions involving arrays. For example, when evaluating the statement

A = (B + C) * (E + F)

IDL first evaluates the expression B + C and creates a temporary array if either B or C are arrays. In the same manner, another temporary array is created if either E or F are arrays. Finally, the result is computed, the previous contents of A are deleted, and the temporary area holding the result is saved as variable A. Therefore, during the evaluation of this statement, enough virtual memory to hold two array's worth of data is required in addition to normal variable storage.

It is a good idea to delete the allocation of a variable that contains an image and that appears on the left side of an assignment statement, as shown in the following program.

FOR I = ... DO BEGIN	Loop to process an image.

...	Processing steps.

  A = 0	Delete old allocation for A.

  A = Image_Expression 	Compute image expression and store.

  ...

ENDFOR	End of loop.

The purpose of the statement A=0 is to free the old memory allocation for the variable A before computing the image expression in the next statement. Because the old value of A is going to be replaced in the next statement, it makes sense to free A's allocation first.

The TEMPORARY Function

Another way to minimize memory use when performing operations on large arrays is to use the TEMPORARY function. TEMPORARY returns the value of its argument as a temporary variable and makes the argument undefined. In this way, you avoid making a new copy of temporary results. For example, assume that A is a large array. To add 1 to each element in A, you could enter:

A = A+1

However, this statement creates a new array for the result of the addition and assigns the result to A before freeing the old allocation of A. Hence, the total storage required for the operation is twice the size of A. The statement:

A = TEMPORARY(A) + 1

requires no additional space.

Virtual Memory System Parameters

♦	UNIX: The size of the swapping area(s) determines how much virtual memory your process is allowed. To increase the amount of available virtual memory, you must either increase the size of the swap device (sometimes called the swap partition) or add additional swap areas (see your operating system documentation for details). Increasing the size of a swap partition is a time-consuming task that should be planned carefully. It requires saving the contents of the disk, reformatting the disk with the new file partition sizes, and restoring the original contents. Consult the documentation that came with your system for details. Some systems (SunOS) allow root to swap to a normal file by using the mkfile(8) command in conjunction with swapon. This is a considerably easier solution.

♦	VMS: VMS, as it comes from DEC, is not tuned for image processing. To get the best performance from IDL, you should increase the VMS SYSGEN parameters, file sizes, and AUTHORIZE quotas that restrict the virtual memory system. This discussion is on the most elementary level, and the appropriate VMS manuals should be consulted for more detail.

The first step is to determine how much virtual memory you require. For example, if you compute complex Fast Fourier Transforms (FFT) on 512 x 512 images, each complex image requires 2 megabytes. Suppose that during a typical session you need to have four images stored in variables and require enough memory for two images to hold temporary results, resulting in a total of six images or 12 megabytes. Rounding up to 16 megabytes gives a reasonable goal. The following SYSGEN parameters and quotas should be changed to increase the amount of virtual memory available.

SYSGEN Parameters

WSMAX: This parameter sets the maximum number of pages of any working set on a system-wide basis. The working set is that portion of virtual memory used by a process that is actually in physical memory. Although this is an over simplification, small working set sizes cause page faulting. Page faults waste time and potentially require disk accesses. Increasing the working set to a size of three times the size of the largest array to be processed, or at least 2,000 blocks, can cause dramatic speed improvements. Many MicroVAX  systems have from 8 to 16 megabytes of physical memory. Subtracting approximately 2 megabytes for VMS leaves the rest available to be divided up among the user processes. On many MicroVAX systems, there are only one or two users so large working sets of 3 to 7 megabytes (6,000 to 14,000 pages) can be used.

VIRTUALPAGECNT: This parameter sets the maximum number of virtual pages (512 bytes/page) that can be used by any one process.

To change the values of SYSGEN parameters, DEC recommends that you run the AUTOGEN command procedure after adding lines to set the new values of changed parameters to the end of the file SYS$SYSTEM: MODPARAMS.DAT.

System Files

The sizes of the system page and swap files (SYS$SYSTEM: PAGEFILE.SYS and SWAPFILE.SYS) must be large enough to contain the virtual memory used by all active processes. In any event, you cannot have more virtual memory than will fit in the page file. You can increase the size of these files or create secondary system files on a disk other than the system disk. If you get the error message

Page file fragmented - continuing

on the system console, your page file is too small. To increase the size of these files, use the command procedure SYS$UPDATE: SWAPFILES. Use the SYSGEN INSTALL command to activate system files created on disks other than the system disk. AUTOGEN can also be used to change the sizes of these files.

Quotas

The following quotas, all of which can be changed on a per user or system basis using the AUTHORIZE utility, affect virtual page limits and working set sizes.

Pgflquo: The page file quota for each user expressed in blocks. If you increase the size of the page file, be sure to increase the page file quotas for the users requiring more virtual memory. Be sure that the page file size is at least as large as the sum of the quotas of each active user.

WSquo: The working set quota for each user. This quota can be used to allow some users a larger working set than others. WSquo must not be larger than WSMAX.

♦	Windows, Macintosh: Consult your Windows or Macintosh system documentation for details on how to configure your system to use virtual memory.


IDL Implementation

IDL programs are compiled into a low-level abstract machine code which is interpretively executed. The dynamic nature of variables in IDL and the relative complexity of the operators precludes the use of directly executable code. Statements are only compiled once, regardless of the frequency of their execution.

The IDL interpreter emulates a simple stack machine with approximately 50 operation codes. When performing an operation, the interpreter must determine the type and structure of each operand and branch to the appropriate routine. The time required to properly dispatch each operation may be longer than the time required for the operation itself.

The characteristics of the time required for array operations is similar to that of vector computers and array processors. There is an initial set-up time, followed by rapid evaluation of the operation for each element. The time required per element is shorter in longer arrays because the cost of this initial set-up period is spread over more elements. The speed of IDL is comparable to that of optimized FORTRAN for array operations. When data are treated as scalars, IDL efficiency degrades by a factor of 30 or more.

As an example, the processes of evaluating the square root of a 10,000-element, floating-point vector and adding 2 to each element of a 512 x 512 byte image was timed using IDL scalar operations, IDL array operations, and FORTRAN yielding the times shown in the following table.

Method	Square Root Time	Addition Time
IDL with scalars and FOR statement	3.10	138
IDL with array operation	0.16	0.49
UNIX FORTRAN (optimized)	0.11	0.80
Table 12.1 Sample Timings on a Sun 3/160 Workstation.

As you can see, there is a large penalty for using scalar operations when array operations are appropriate. There is little difference in the times required by IDL array operations and FORTRAN.

Jump forward to Interactive Support

Jump backward to Programming Routines


Interactive Support
13	Interactive Support

Chapter Overview

IDL provides two kinds of help information: complete manual text on-line and status information concerning the current environment. In addition, the state of an IDL session can be saved for future use (via the SAVE and RESTORE procedures), and the commands entered in an IDL session can be logged (via the JOURNAL procedure).


Topics in Interactive Support Chapter
Interactive Support

This chapter provides an overview of IDL's facilities for on-line help, determining and saving the state of the current IDL session, and capturing interactive IDL sessions.

Topics Covered:

IDL's Online Help System

Extending IDL's Online Help System

The HELP Procedure

SAVE and RESTORE

Journaling

Jump forward to Plotting

Jump backward to Efficient Programming


IDL's Online Help System

The entire text of the IDL User's Guide and IDL Reference Guide is available on-line by entering a question mark (?) at the IDL prompt. The most current documentation on any aspect of IDL is available through this command.

After entering the ? command, a new window titled "IDL Online Help" appears. Depending upon the speed and type of your computer system, it may take a minute or two for the online help window to appear.

The IDL online help system is a searchable hypertext database. Hypertext links appear in green and can be followed by clicking on the green text with the mouse cursor.

More information about the help viewer can be found in the following sections. Note there are slight differences between the help systems on different IDL platforms.

The Help Menus

Several pulldown menus appear at the top of the IDL Online Help window. These menus are described below.

File

This menu controls help system file and printing options.

Open

Select this option to open a different help file. Since IDL's basic help system is contained in a single file named idl.hlp (located in the help subdirectory of the IDL distribution on Macintosh and Windows systems, located in the hyperhelp subdirectory of the help subdirectory on Unix and VMS), this option will not usually be needed.

Close (Macintosh only)

Select this option to close the current help file.

Print

Select this option to print the current topic or a group of topics.

Printer Setup/Page Setup

Select this option to configure IDL Online Help to work with your printer. This menu item is called "Page Setup" on the Macintosh.

Print All Topics (Macintosh only)

Select this option to print all topics in the help file. Note that since the IDL help system contains the full text of both the IDL User's Guide and the IDL Reference Guide, choosing this option will result in several thousand pages being printed.

Exit/Quit

Select this option to dismiss the online help system. This menu item is called "Quit" on the Macintosh

Edit

This menu allows you to copy text from the current topic to the clipboard or to add your own notes to a topic. On the Macintosh, the top six items ("Undo," "Cut," "Copy," "Paste," "Clear," and "Select All") function as they do in other Macintosh applications.

Copy

Select this option to copy the entire text of the current topic to a scrolling window. In this window, you can select text by dragging over it with the mouse cursor. Click the "Copy" button to copy the selected text to the system clipboard. The text can then be pasted into other windows or applications. Click "Cancel" to dismiss the Copy window.

On the Macintosh, copy topic text to a scrolling window by selecting "Copy Topic Text...". The generalized "Copy" command is only available in annotations, which are described below.

On the Macintosh you also have the option of saving a topic as a PICT file. Select "Copy Topic as Picture" to save a copy of the topic on the clipboard in PICT format.

Annotate

Select this option to add your own notes to the current topic. The Annotate window appears. Type your annotation in the window and click "OK" or "Save" to create a new annotation. A green "paper clip" icon appears at the top of the current topic. Clicking on this icon causes the saved annotation to appear. Annotations can be deleted by clicking the "Delete" button. Press "Cancel" to dismiss the Annotate window.

On Unix systems, annotations are stored in each user's home directory (as defined by the $HOME environment variable) in the file idl.hlpab. This location can be changed by setting the value of the $HHLOCAL environment variable. Annotations can be shared if users set the same $HHLOCAL directory.

On Microsoft Windows systems, annotations are stored in the WINDOWS directory in the file idl.ann.

Annotations are handled slightly differently on the Macintosh. In the upper right-hand corner of the help window is a small yellow icon designed to look like a paper sticky-note. To add your own notes, drag a copy of this icon into the topic text. You can add as many lines of annotation, in as many separate notes, as you wish.

To delete an annotation on the Macintosh, place the cursor in the note you wish to delete and either drag it off the help window or select "Delete Note" from the Edit menu.

Find (Macintosh only)

The Macintosh help viewer has a Find menu that provides full-text search capability. (This capability is provided by the Find Text button on Unix systems.) The Find menu has two options:

Global Find...

Select this option to display a "Global Find" dialog. Enter the text string you wish to search for and click "Find." The first instance of text matching your search string will be displayed in the main help window.

Global Find Again

Select this option to continue a full-text search already started.

Bookmark

This menu allows you create "bookmarks" that allow easy access to frequently-used help topics.

Define/Set Bookmark

Select this option to create a new bookmark or delete existing bookmarks. The Bookmark window appears. The name of the bookmark to be created is shown in the "Selection" or "Bookmark Name" text field. The default name the bookmark is the name of the topic as shown in the non-scrolling region of the IDL Online Help window. On the Macintosh, you have the option of defining a command-key shortcut for the bookmark as well. Change the name or define a shortcut key if you desire, then click "OK". The newly-defined bookmark becomes a menu item under the Bookmark menu. When this menu item is selected, IDL Online Help jumps to the bookmarked topic.

Under Unix and Windows, the Bookmark window also shows a list of any other bookmarks you have defined. To delete a previously-defined bookmark, click on its name in the list, then click the "Delete" button.

Click the "Cancel" button to dismiss the Bookmark window without changing the list of bookmarks.

Edit Bookmarks... (Macintosh only)

On the Macintosh, a second menu option displays a scrolling list of your bookmarks. Jump to a topic by selecting a bookmark from the list and clicking "View Topic." Delete a bookmark by clicking "Delete Bookmark." You can also changes to the name or command-key shortcut in the "Edit Bookmarks" window. Click "OK" to accept any changes you have made or "Cancel" to dismiss the window without saving changes.

How Bookmarks are Stored

On Unix systems, bookmarks are stored in each user's home directory (as defined by the $HOME environment variable) in the file idl.hlpab. This location can be changed by setting the value of the $HHLOCAL environment variable. Bookmarks can be shared is users set the same $HHLOCAL directory.

On Microsoft Windows systems, bookmarks are stored in the WINDOWS directory in the file idl.bkm.

View (Macintosh only)

The View menu allows you to toggle display of annotations on and off by selecting the "Show Notes" option, or to toggle animation effects on and off by selecting the "Animation Effects" option. The bottom of the View menu contains a list of help files that are currently open. To change to another open help file, select its name from the list.

Help

This menu can be used to access information about the help system. On the Macintosh, the help menu is at the "?" menu at the right of the menu bar.

How to Use Help/Help with QuickHelp

Select this option to jump to the topic "IDL's Online Help System" which is also found on page 13-2 of the IDL User's Guide. On the Macintosh, selecting "Help with QuickHelp" displays the Altura QuickHelp help file.

About Help

Select this option to see version and copyright information for the help viewer. On the Macintosh, this menu item is under the Apple menu.

The IDL Online Help Button Bar

Directly below the IDL Online Help menus is a group of buttons that can be used to help navigate through the help system. These buttons are described in more detail below. Note that not all features are available on all platforms.

Contents

Click this button to jump to the "IDL Online Help Navigator Page". This is the first page that appears if you start the online help system without any arguments. This top-level page allows access to the table of contents for the IDL User's Guide, alphabetical and topical lists of routines, lists of graphics keywords and system variables, and documentation for graphics devices. There are also links to release notes and more information about Research Systems products.

Back/Go Back

Click this button to jump to the previously-displayed topic. You can continue jumping backward through previously-displayed topics until you reach the first one.

History

Click this button to see a list of topics previously-visited during the current online help session. The History window appears. Double-click on a topic title in the list to jump to that topic. Click the "Cancel" button to dismiss the History window without selecting a new topic. On the Macintosh, clicking on "Clear" erases the current history list.

Find Topic/Search

Click the "Find Topic" (on Unix) or "Search" button (Microsoft Windows and Macintosh) to perform a keyword search of the IDL Online Help database. The Search window appears.

Under Unix or Microsoft Windows, enter a keyword to search for, or select one from the scrolling list. Click "Show Topics" to show the topics that are related to the search keyword. Select a topic from the list, then click "Go To" to display that topic in the IDL Online Help window.

On the Macintosh, clicking "Search" brings up the Index window. Scroll through the topics or type the first few letters of a keyword to move quickly through the list. When you have selected a topic, click "View Topic" to display the topic in the main help window without dismissing the Index window. Click "Go To Topic" to display the topic in the main help window and dismiss the Index window. Click "Done" to dismiss the Index window without changing the contents of the main help window.

The Macintosh help viewer provides another method for keyword searching as well. Underneath the button bar is a field with the label "Keyword:". Begin typing in this field and search keywords that match what you have typed so far will be displayed in gray. Press Return to jump directly to the topic containing the search keyword that is displayed. If more than one topic contains the search keyword you specify, the Index window will appear, allowing you to select the topic you wish to view.

Tips on Keyword Searching

There are over 6000 search keywords in the IDL Online Help database. These keywords are derived from the index entries in the IDL User's Guide and IDL Reference Guide. The index to the IDL documentation is multi-level. In the Online Help database, the top-level index entries are presented as keywords. Keywords are presented in all lower-case letters, even when upper-case letters are used in the index. When you select a keyword, topics associated will all the lower-level index entries for that top-level index entry are displayed in the topic list.

Note also that the Unix keyword search is case sensitive, but the Windows and Macintosh search is not.

Find Text

Click this button to perform a full text search of the IDL Online Help database. This option can be used to find all occurrences of any string in the database. This option is not available on Microsoft Windows, and is replaced by the "Find" menu on the Macintosh.

When the Find window appears, enter a string to be searched for in the "Find" text field. You can set the option of just searching in topic titles or in all of the manual text. Click the "Match Case" button to perform a case-sensitive search. Click the "Search" button to begin searching.

A "Searching" window appears that reports the number of topics found so far. Note that because the IDL Online Help database represents over 1500 pages of documentation, performing a full text search can take a number of minutes. You can stop the search by clicking the "Stop Search" button.

When the search is complete, or the search has been stopped before locating all topics, a "Topics Found" window appears. This window lists the title of each topic and the number of occurrences of the search string in that topic. To jump to a topic, double-click on it in the list. There are also buttons for sorting ("Sort") the list, moving forward ("Next") or backward ("Previous") through the list, jumping to the highlighted topic ("Go To"), or dismissing the window ("Cancel").

All Topics

Click this button to display the "All Topics" window in which every topic title in the help system is displayed. Clicking on a title displays that topic in the IDL Online Help window. Topics appear in roughly the same order as they do in the IDL documentation with topics from the IDL User's Guide shown first, followed by topics from the IDL Reference Guide.

Browse Buttons (<< and >>)

The browse buttons allow you to look at topics related to the currently-displayed topic as if you were browsing through the paper version of the manuals. Click the ">>" button to see the next topic in the sequence. Click the "<<" button to see the previous topic in the sequence. On the Macintosh, the browse buttons portray the pages of a book.

Note that the browse buttons are not active for every topic in the help system. For example, the "IDL Online Help Navigator" page is not part of a browse sequence.

There are many browse sequences defined in the help database. The topics that comprise chapters in the IDL User's Guide have been organized into separate browse sequences. Documentation for IDL routines is organized into an alphabetical browse sequence.


Extending IDL's Online Help System

Users may want to create online help for their own IDL applications, procedures, or functions. The online help system used by IDL emulates (or uses, in the case of IDL for Windows) the Microsoft Windows Help viewer on all supported platforms. Because the online help files are compiled, there is not a simple, no-cost way to include user-created help topics directly in the help system on all platforms. However, there are a number of ways to create your own online help. The techniques described below vary in complexity, cost, and level of integration with IDL's hypertext online help viewer.

Creating Hypertext Files for Use with IDL's Hypertext Help Viewer

As mentioned above, the online help system used by IDL emulates (or uses, in the case of IDL for Windows) the Microsoft Windows Help viewer on all supported platforms. It is possible to create your own hypertext help files that can be used with the viewer. The difficulty and expense involved in creating such files depends largely on the platform(s) involved.

Microsoft Windows

For Microsoft Windows systems, help files are relatively easy to create. Files must be created in the Rich Text Format (RTF) and compiled with Microsoft's help compiler. The help compiler is part of the Windows Software Developer's Kit, and is now included in several Microsoft programming products, including the Visual C++ development environment. The help compiler may also be available from the Microsoft ftp site (ftp.microsoft.com) or other Microsoft online software libraries at little or no cost.

The Windows help system is often referred to as "WinHelp". The two components are the viewer (WINHELP.EXE, found in the main WINDOWS directory of all Windows systems), and the help compiler. There are a number of third-party "help authoring systems" that simplify the creation of WinHelp compatible RTF files. Also, a number of third party books describe the WinHelp creation process—Developing Online Help for Windows, by Scott Boggan, David Farkas, and Joe Welinske, Sams Publishing, 1993, ISBN: 0-672-30230-6 is one that we have found useful.

Macintosh

For Macintosh, we use a WinHelp-compatible compiler and viewer licensed from Altura Software, Inc. called QuickHelp. This compiler uses the same RTF files as are used by the Microsoft Help compiler. Altura Software can be contacted at the following address:

Altura Software, Inc.
510 Lighthouse Avenue, Suite 5
Pacific Grove, CA 93950
Phone: 408-655-8005
Fax: 408-655-9663
AppleLink: ALTURA

Unix and VMS

For Unix and VMS, we use a compiler and viewer from Bristol Technology, Inc. called HyperHelp. Bristol makes a number of compilers that can compile source files in RTF, FrameMaker's MIF (Maker Interchange Format), SGML (Standard Generalized Markup Language), and their own simple HyperHelp Text (HHT) format. We use the MIF compiler to create hypertext help files from the same FrameMaker files that produce our hardcopy manuals.

Bristol also makes a product called Bridge that takes compiled HyperHelp files and converts them to RTF files that can be compiled with the Windows and Macintosh help compilers described above. In this way, we can create help files for all supported IDL platforms from a single source.

Bristol Technology can be contacted at the following address:

Bristol Technology, Inc.
241 Ethan Allen Highway
Ridgefield, CT 06877
Phone: 203-438-6969
Fax: 203-438-5013
Email: info@bristol.com
http://www.bristol.com

Accessing Hypertext Help Files

Once compiled, your own hypertext help files can be opened by selecting "Open" from the help viewer's File menu. In addition, the ONLINE_HELP procedure can be used in your IDL programs to display help files and control the viewer. See "ONLINE_HELP" on page 1-638 of the IDL Reference Guide.

Documentation Professional Services

It may be possible for documentation professionals from Research Systems to write and/or compile hypertext help files for IDL users on a contract basis. Contact the Research Systems sales department for details.

Creating HTML Files from User Routines

If you need a simple, low- or no-cost way to create hypertext online help for user-written routines, consider using HTML (HyperText Markup Language) files in conjunction with a WWW (World-Wide Web) browser such as Mosaic or Netscape. The MK_HTML_HELP procedure can be used to create HTML-format documentation from standard IDL documentation headers. These files can then be viewed with your web browser. See "MK_HTML_HELP" on page 1-592 of the IDL Reference Guide.

Browsers such as Mosaic and Netscape are available for most platforms supported by IDL. For information about the Mosaic viewers, send email to mosaic@ncsa.uiuc.edu. For information about the Netscape viewers, send email to info@netscape.com.

Support for IDL's Previous Help System

While the procedures and functions required to run the pre-version-4.0 IDL help system are no longer documented, they are still included in IDL. We do not recommend that new users of IDL use the system described in this section.

Users who have existing .help files in the "old" format should move them to the help subdirectory of the main IDL directory. The IDL command WIDGET_OLH can be used to display the old-style help viewer, which will show a category for each .help file found. Note that the MAN_PROC procedure is also still available, but we recommend using WIDGET_OLH to call the old-style help viewer instead.

The MK_LIBRARY_HELP procedure, which creates .help files from standard IDL documentation headers, is still included. It can be found in the file mk_library_help.pro in the lib subdirectory of the main IDL directory. Read its documentation header for instructions. New users who want similar functionality (and previous users who want HTML support) should consider using the MK_HTML_HELP procedure, described above, instead. See "MK_HTML_HELP" on page 1-592 of the IDL Reference Guide.

The DOC_LIBRARY procedure (that reads individual IDL documentation headers) is still included and documented. See "DOC_LIBRARY" on page 1-252 of the IDL Reference Guide.


The HELP Procedure

The HELP procedure gives information about many different aspects of the current IDL session. Entering

HELP

with no parameters prints an overview of the current state, including the definitions of all current variables. Calling HELP with one or more parameters displays the definitions of its parameters.

The HELP procedure also will display other information about the current session if called with a keyword parameter indicating the topic. Only one topic keyword should be specified at a time. The available topics are described below.

The Current State

When HELP is called without any plain or keyword arguments, it provides an overview of the current state. The information provided includes:

•	A traceback showing the current procedure and function nesting.

•	When IDL reads a procedure or function for the first time, it compiles it into the internal form that is executed by the IDL interpreter. Every routine has a code area where the executable code is stored and a data area where information about all locally available variables (including common block variables) resides. The amount of room used in each of these areas is reported, along with the number of local variables and parameters to the current routine.

•	A one-line description of every current variable.

Note: You can use the NAMES keyword, to specify a pattern string that contains wildcard matching characters to select which variables are to be described. An example appears below.

•	A description of all currently accessible common blocks.

•	The names of all saved procedures and functions.

As an example of a typical IDL session, the command,

HELP

might result in output similar to the following:

% At $MAIN$(0).
Code area used: 0.00% (0/8192), Data area used: 4.88% (100/2048)
# local variables: 4, # parameters: 0
B BYTE = Array(256)
G BYTE = Array(256)
I BYTE = Array(512, 512)
R BYTE = Array(256)
X (CBLK) INT = 10
Y (CBLK) INT = 11
Z (CBLK) INT = 12
Common Blocks:
CBLK(3)
Saved Procedures:
COLOR_EDIT COLOR_EDIT_BACK INTERP_COLORS READ_SRF SHOW3
Saved Functions:
AVG    BILINEAR    CORRELATE    CURVEFIT

This display gives the following information:

•	The current routine is $MAIN$, which means that we are currently at the main program level and that no called routine is executing.

•	The second line gives the information that the code area is empty (0 bytes used out of 8,192 available), and approximately 95 percent of the "data area" (which contains the symbol table) also is free (100 bytes used out of 2,048 available). Note that arrays are not stored in the data area. The code area is empty because we are currently at the main level, and no main program has been entered (using the .RUN executive command).

•	The third line gives the number of local variables and the number of parameters to the current routine.

•	The next seven lines give one-line descriptions of all locally available variables. The first four variables (B, G, I, and R) are local variables, while the other three (X, Y, and Z) are contained in the common block CBLK. Note that the one-line descriptions of scalar variables give their values, while the descriptions of arrays show their dimensions. Use the PRINT procedure to look at the contents of arrays.

•	Following the descriptions of variables is the list of available common blocks. The session depicted above has only a single common block named CBLK, which contains three variables.

•	The final information given is the names of all saved procedures and functions.

If you call HELP with arguments (but without any keyword arguments), it simply provides a one-line description of each argument. Hence, for the IDL session described above, the command,

HELP, 12.0 * 23, R, I, Z, !D

gives the output below:

<Expression> FLOAT = 276.000
R BYTE = Array(256)
I BYTE = Array(512, 512)
Z (CBLK) INT = 12
<Expression> STRUCT = -> !DEVICE

It was noted above that the one-line description of scalars gives their values, and that arrays have their dimensions given instead. The last line of this example demonstrates that for structure variables, the name of the structure definition associated with the variable is given. Use the command:

HELP, /STRUCTURES

to see the form of a structure variable. The STRUCTURES keyword is described below.

HELP, /DEVICE

The command,

HELP, /DEVICE

gives information about the current graphics device. This information is dependent on the abilities of the current device, but the name of the device is always given. Arguments to HELP are ignored when DEVICE is selected. As an example of the type of information supplied, the commands:

SET_PLOT, 'X'	Select the X Window System.

HELP, /DEVICE	Get device information.

give output similar to the following:

Available graphics_devices: CGM HP LJ NULL PCL PS REGIS TEK X Z
Current graphics device: X
   Server: X11.0, Hewlett-Packard Company, Release 4
   Display Depth, Size: 8 bits, (1280,1024)
   Visual Class: PseudoColor (3)
   Bits Per RGB: 8
   Physical Color Map Entries (Used / Total): 225 / 256
   Colormap: Shared, 225 colors. Translation table: Enabled
   Dither Method: Ordered
   Write Mask: 255 (decimal) ff (hex)
   Graphics Function: 3 (copy)
   Current Font: <default>
   Default Backing Store: Req from Server.

while the commands,

SET_PLOT, 'PS'	Select PostScript output.

HELP, /DEVICE 	Get device information.

give output similar to the following:

Available graphics_devices: CGM HP LJ NULL PCL PS REGIS TEK X Z
Current graphics device: PS
   File: <none>
   Mode: Portrait, Non-Encapsulated, EPSI Preview Disabled, Color Disabled
   Offset (X,Y): (1.905,12.7) cm., (0.75,5) in.
   Size (X,Y): (17.78,12.7) cm., (7,5) in.
   Scale Factor: 1
   Font Size: 12
   Font: Helvetica
   # bits per image pixel: 4
   Font Mapping:
    (!3) Helvetica              (!4) Helvetica-Bold
    (!5) Helvetica-Narrow       (!6) Helvetica-Narrow-BoldOblique
    (!7) Times-Roman            (!8) Times-BoldItalic
    (!9) Symbol                (!10) ZapfDingbats
   (!11) Courier               (!12) Courier-Oblique
   (!13) Palatino-Roman        (!14) Palatino-Italic
   (!15) Palatino-Bold         (!16) Palatino-BoldItalic
   (!17) AvantGarde-Book       (!18) NewCenturySchlbk-Roman
   (!19) NewCenturySchlbk-Bold (!20) <Undefined-User-Font>

HELP, /FILES

The FILES keyword provides information about file units. If no arguments are supplied, information on all open file units is displayed. If arguments are provided, they are taken to be integer file unit numbers, and information on the specified file units is given. For example, the command,

HELP, /FILES, -2, -1, 0

gives information below about the default file units:

Unit Attributes Name
-2   Write, Truncate, Tty, Reserved   <stderr>
-1   Write, Truncate, Tty, Reserved   <stdout>
 0   Read, Tty, Reserved              <stdin>

The attributes column tells about the characteristics of the file. For instance, the file connected to logical file unit 2 is called "stderr" and is the standard error file. It is opened for write access (Write), is a new file (Truncate), is a terminal (Tty), and cannot be closed by the CLOSE command (Reserved).

HELP, /KEYS

The KEYS keyword provides current function key definitions as set using DEFINE_KEY. If no arguments are supplied, information on all function keys is displayed. If arguments are provided, they must be scalar strings containing the names of function keys, and information on the specified keys is given. For example, on a Sun computer the command:

DEFINE_KEY, /TERMINATE, 'F2', 'HELP, /KEYS'

causes the F2 function key to send the string "HELP, /KEYS" every time it is pressed in response to the IDL prompt. Pressing it gives output similar to the following lines, showing how all the keys are programmed:

Pre-defined Keys:
  ^A                  <Start Of Line>
  ^B                  <Back Word>
  ^D                  <EOF If Line Empty, Line Term. Otherwise>
  ^E                  <End Of Line>
  ^F                  <Forward Word>
  ^N                  <Previous Line>
  ^R                  <Redraw>
  ^U                  <Delete To Start Of Line>
  ^W, ESC-Delete      <Delete Word>
  ^X                  <Delete Current Character>
  Backspace, Delete   <Delete Character>
  ^text             <If Line Empty, Find Last Cmd Matching Text>
Function keys:
  LEFT ARROW <\033[D> =        <Cursor Left>
  RIGHT ARROW <\033[C> =       <Cursor Right>
  UP ARROW <\033[A> =          <Previous Line>
  DOWN ARROW <\033[B> =        <Next Line>
  INSERT/OVERSTRIKE <\033i> =  <Insert/Overstrike Toggle>
  INSERT/OVERSTRIKE <\033I> =  <Insert/Overstrike Toggle>
  R10 <\033[217z> =             <Cursor Left>
  R12 <\033[219z> =             <Cursor Right>
  R8 <\033[215z> =              <Previous Line>
  R14 <\033[221z> =             <Next Line>
  R13 <\033[220z> =             <Back Word>
  R15 <\033[222z> =             <Forward Word>

HELP, /ALL_KEYS

The ALL_KEYS keyword displays the list of all keys which are programmable in IDL. This list is different from the list generated when the KEYS keyword is used in that KEYS displays only the programmable keys which currently have definitions. Refer to the section on defining keys on page 2-23 for additional information.

HELP, /MEMORY

IDL uses dynamic (heap) memory to store items such as programs and variables. The MEMORY keyword reports the amount of dynamic memory currently in use by the IDL session and the number of times dynamic memory has been allocated and deallocated. A typical response to the

HELP, /MEMORY

command might be as follows:

heap memory in use: 14572, calls to MALLOC: 64, FREE: 3

Arguments to HELP are ignored when MEMORY is selected.

HELP, NAMES

The NAMES keyword specifies a pattern string which determines which variables are to be described. This string may contain the usual wildcard matching characters, "*" and "?". For example, the command,

HELP, NAMES = 'A*'

prints the values of all variables whose name begins with an "A," while command,

HELP, NAMES = '??'

prints the values of all variables with a two-character name.

HELP, /RECALL_COMMANDS

By default, IDL saves the last 20 lines of input in a buffer from which they can be recalled for command line editing. The RECALL_COMMANDS keyword causes the HELP procedure to display the contents of this buffer. Arguments to HELP are ignored when RECALL is selected.

The number of lines saved can be changed by assigning the desired number of lines to the environment variable !Edit_input in the IDL startup file.

HELP, /ROUTINES

The ROUTINES keyword causes HELP to print a list of all compiled procedures and functions with their parameter names. Positional parameters accepted by each routine are shown in lowercase. Keyword parameters accepted by each module are shown in all caps. Arguments to HELP are ignored when ROUTINES is selected. Typical output from the command:

HELP, /ROUTINES

could be:

Compiled Procedures:
TETRIS           BELL HELP LEVEL TOP WAIT
T_DROP           DONE RANGE
T_HELP
T_INIT           wt lev BELL
T_LEFT
T_NEXT           pn
T_PLOT           flag
T_RIGHT
T_ROT
T_SCORE          r

Compiled Functions:
DIST             n m

HELP, /SOURCE_FILES

The SOURCE_FILES keyword gives information on procedures and functions written in the IDL language that have been compiled during the current IDL session. Full path names (relative to the current directory) of compiled .pro files are displayed.

For example, HELP, /SOURCE_FILES might produce output like the following:

HELP, /SOURCE
Compiled Procedures:
$MAIN$
CW_EIGHT_DRAW_BALL        cw_eightball.pro
CW_EIGHT_INIT             cw_eightball.pro
CW_EIGHT_SET              cw_eightball.pro
EIGHT                     eight.pro
EIGHT_EVENT               eight.pro
XMANAGER                  /usr/local/rsi/idl_4/lib/xmanager.pro
XUNREGISTER               /usr/local/rsi/idl_4/lib/xmanager.pro

Compiled Functions:
CW_EIGHTBALL              cw_eightball.pro
CW_EIGHT_EVENT            cw_eightball.pro
CW_EIGHT_GET              cw_eightball.pro

HELP, /STRUCTURES

The STRUCTURES keyword gives information on the structure of variables. If no arguments are provided, all currently defined structures are shown. If arguments are provided, the structure of those expressions is displayed. For example, the command,

HELP, /STRUCTURES, !D

shows the contents and structure of the system variable !D as follows:

** Structure !DEVICE, 17 tags, length=80:
   NAME          STRING   'X'
   X_SIZE        LONG          512
   Y_SIZE        LONG          385
   X_VSIZE       LONG          512
   Y_VSIZE       LONG          385
   X_CH_SIZE     LONG            6
   Y_CH_SIZE     LONG            9
   X_PX_CM       FLOAT      40.0000
   Y_PX_CM       FLOAT      40.0000
   N_COLORS      LONG          225
   TABLE_SIZE    LONG          225
   FILL_DIST     LONG            1
   WINDOW        LONG           -1
   UNIT          LONG            0
   FLAGS         LONG        65980
   ORIGIN        LONG Array(2)
   ZOOM          LONG Array(2)

It is often more convenient to use HELP, /STRUCTURES instead of PRINT to look at the contents of a structure variable because it shows the names of the fields as well as the data. For instance, the command,

PRINT, !D

gives the more cryptic output:

{ SUN   1152   900   1152   900     8    13
40.0000 40.0000   256   256    1    -1
0   508}

HELP, /SYSTEM_VARIABLES

The SYSTEM_VARIABLES keyword causes HELP to show all system variables and their values. Arguments to HELP are ignored when the SYSTEM_VARIABLES keyword is selected. The command,

HELP, /SYSTEM_VARIABLES

gives output similar to the following:

!C = 0 !D = -> !DEVICE Array(1) !DIR = '/usr/local/lib/idl'
!DPI = 3.1415927 !DTOR = 0.0174533 !EDIT_INPUT = 1
!ERR = 0 !ERROR = 0 !ERR_STRING = ''
!JOURNAL = 0 !MAP = -> !MAP Array(1) !MOUSE = -> !MOUSE Array(1)
!MSG_PREFIX = '% ' !ORDER = 0 !P = -> !PLT Array(1)
!PATH = '/usr/local/rsi/idl/lib'
!PI = 3.14159 !PROMPT = 'IDL> ' !QUIET = 0
!RADEG = 57.2958 !SYSERROR = Array(2) !SYSERR_STRING = ''
!VERSION = -> !VERSION Array(1) !X = -> !AXIS Array(1) !Y = ->
!AXIS Array(1) !Z = -> !AXIS Array(1)

HELP, /TRACEBACK

The TRACEBACK keyword displays the current nesting of procedures and functions. Arguments to HELP are ignored when TRACEBACK is selected.


SAVE and RESTORE

The SAVE and RESTORE procedures combine to provide the ability to save the state of variables, system variables, and procedures and functions to restore them at a later time. This ability to "checkpoint" a session and then recover it later can be very convenient. SAVE/RESTORE files can be used for many purposes.

Save files can be used to recover variables that are used from session to session. A startup file can be setup to execute the RESTORE command every time IDL is started. See "Startup File" on page 2-22 of the IDL User's Guide for the details of how to create one.

The state of an IDL session can be saved quickly and easily, and can be restored to the same point. This feature allows you to stop work, and later resume at a convenient time.

Data can be conveniently stored in SAVE/RESTORE files, relieving the user of the need to remember the dimensions of arrays and other details. It is very convenient to store images this way. For instance, if the three variables R, G, and B hold the color table vectors, and the variable I holds the image variable, the IDL statement,

SAVE, FILENAME = 'image.dat', R, G, B, I

will save everything required to display the image properly in a file named image.dat. At a later date, the simple command,

RESTORE, 'image.dat'

will recover the four variables from the file.

Long iterative jobs can save their partial results in SAVE/RESTORE format to guard against losing data if some unexpected event such as a machine crash should occur.

SAVE

The SAVE procedure saves variables and system variables in a file, using an efficient binary format, for later recovery by RESTORE. It has the form:

SAVE[, Var1, ..., Varn]

where Varn is the named variables to be saved. If no arguments are provided to the SAVE procedure, all variables are saved to a file named idlsave.dat.

Additionally, the following keywords can be supplied:

ALL

Set this keyword to specify that all variable-related information (common blocks, system variables, and local variables) should be saved.

COMM

Set this keyword to save all main-level common-block definitions.

FILENAME

Set this keyword equal to a scalar string that contains the name of the file into which the IDL objects should be saved. If this keyword is not specified, the file  idlsave.dat is used.

ROUTINES

Set this keyword to save all user-defined procedures and functions in a machine-independent, binary form. This feature is useful for distributing your IDL routines to other users without allowing them access to the source code for those routines. VMS IDL can save routines in either machine-dependent VMS format (the default) or machine-independent XDR format (if the XDR keyword is also set). All other versions save the routines in XDR format.

SYSTEM_VARIABLES

Set this keyword to save all system variables. Caution: Saving system variables is not recommended, as their structure may change between releases, making the SAVE/RESTORE files incompatible.

VARIABLES

Set this keyword to save all variables.

VERBOSE

Set this keyword to make IDL print an informative message for each saved object.

XDR

Set this keyword to write the save file in a portable format using XDR (external data representation). Under all operating systems except VMS, XDR is the only supported format and specifying this keyword is unnecessary. Under VMS, the default is a VAX-specific format which is more efficient to process. Use XDR under VMS to interchange data with other versions of IDL.

Caution: Under all operating systems except VMS, creating a new SAVE/RESTORE file will cause any existing file with the same name to be lost. Use the FILENAME keyword with SAVE to avoid destroying desired files.

RESTORE

The RESTORE procedure restores the objects previously saved in a SAVE/RESTORE file by the SAVE procedure. It has the form

RESTORE[, Filename]

where Filename is the name of the SAVE/RESTORE file to be used. If Filename is not supplied, the file idlsave.dat is used. In addition, the following keywords can be supplied:

FILENAME

Set this keyword equal to a scalar string that contains the name of the file from which the IDL objects should be restored. If not present, the file idlsave.dat is used. This keyword serves exactly the same purpose as the Filename argument—only one of them needs to be provided.

VERBOSE

Set this keyword to make IDL prints an informative message for each restored object.

RESTORE normally recovers all saved objects from the file. If a local or common variable from the SAVE/RESTORE file already exists, the definition from the file overrides the existing definition. If the variable does not exist, it is created. Situations in which the contents of the file are not be restored are as follows:

When attempting to restore a structure variable, the structure of the saved variable must either not exist or must agree with the existing structure definition. If the structure is already defined and does not agree, RESTORE issues an error message, skips the variable in question, and continues with the next variable in the file. This also applies to system variables. Research Systems reserves the right to change the structure of IDL system variables. Generally, there is little need to save system variables, so this restriction should not be a problem.

Read-only system variables are not restored. RESTORE quietly skips over such variables in the file unless the VERBOSE keyword is present. In this case an informative message is issued as the variable is skipped.


Journaling

Journaling provides a record of an interactive session by saving in a file all text entered from the terminal in response to a prompt. All text entered to the IDL prompt is entered directly into the file, and any text entered from the terminal in response to any other input request (such as with the READ procedure) is entered as a comment. The result is a file that contains a complete description of the IDL session.

JOURNAL has the form:

JOURNAL[, Argument]

where Argument is either a filename (if journaling is not currently in progress) or an expression to be written to the file (if journaling is active).

The first call to JOURNAL starts the logging process. If no argument is supplied, a journal file named idlsave.pro is started.

Caution: Under all operating systems except VMS, creating a new journal file will cause any existing file with the same name to be lost. Supply a filename argument to JOURNAL to avoid destroying desired files.

When journaling is not in progress, the value of the system variable !JOURNAL is zero. When the journal file is opened, the value of this system variable is set to the number of the logical file unit on which the file is opened. This allows IDL routines to check if journaling is active. You can send any arbitrary data to this file using the normal IDL output routines. In addition, calling JOURNAL with an argument while journaling is in progress results in the argument being written to the journal file as if the PRINT procedure had been used. In other words, the statement,

JOURNAL, Argument

is equivalent to

PRINTF, !JOURNAL, Argument

with one significant difference—the JOURNAL statement is not logged to the file, only its output; while the PRINTF statement will be logged to the file in addition to its output.

Journaling ends when the JOURNAL procedure is called again without an argument or when IDL is exited. The resulting file serves as a record of the interactive session that went on while journaling was active. It can be used later as an IDL batch input file to repeat the session, and it can be edited with any text editor if changes are necessary.

As an example, consider the following IDL statements:

JOURNAL, 'demo.pro'	Start journaling to file demo.pro.

PRINT, 'Enter a number:'	Prompt for input.

READ, Z	Read the user response into variable Z.

JOURNAL, '; This was inserted with JOURNAL.'
Send an IDL comment to the journal file using JOURNAL.

PRINTF, !JOURNAL, '; This was inserted with PRINTF.'
Send another comment using PRINTF.

JOURNAL	End journaling.

If these statements are executed by a user on a Sun workstation named machine, the resulting journal file demo.pro will look like the following:

; IDL Version 3.0 - The IDL of things to come (hp-ux hp9000s300)
; Journal File for keith@bill
; Working directory: /users/keith
; Date: Tue Sep 1 14:25:59 1992

PRINT, 'Enter a number:'
;Enter a number:
READ, z
; 339
; This was inserted with JOURNAL.
; This was inserted with PRINTF.
PRINTF, !JOURNAL, '; This was inserted with PRINTF.'

Note that the input data to the READ statement is shown as a comment. In addition, the statement to insert the text using JOURNAL does not appear, while the statement using PRINTF does appear.

Jump forward to Plotting

Jump backward to Efficient Programming


Plotting
14	Plotting

Chapter Overview

IDL includes several routines that can be used to display data in a variety of plot formats, including general x versus y, contour, mesh surface, and perspective plots. The routines allow users to display information in a manner that can be easily understood during data analysis.

Optional keyword parameters and system variables enable users to change certain specifications of the routines, such as scaling, style, and colors, for custom or specialized plots.

This chapter provides examples of scientific graphics in which one variable is plotted as a function of another. The routines for the display of functions of two variables, CONTOUR, SHADE_SURF, and SURFACE, are explained in detail in Chapter 15.

For a complete list of plotting routines, see the IDL HandiGuide or IDL's online help system.


Topics in Plotting Chapter
Plotting

This chapter provides an overview of IDL's tools for X-Y plotting.

Topics Covered:

Plotting Keyword Parameters

Graphics Coordinate Systems

X Versus Y Plots— PLOT and OPLOT

Annotation ­ The XYOUTS Procedure

Plotting Symbols

Polygon Filling

Tick Marks

Logarithmic Scaling

Multiple Plots on a Page

Specifying the Location of the Plot

Plotting Missing Data

Using the AXIS Procedure

The CURSOR Procedure

Jump forward to Plotting Multi-Dimensional Arrays

Jump backward to Interactive Support


Plotting Keyword Parameters

The IDL plotting procedures are designed to produce acceptable results for most applications with a minimum amount of effort. The large number of keyword parameters, described in the IDL Reference Guide, in combination with plotting and graphic system variables, allow users to customize the graphics produced by IDL. Most of these keyword parameters pertain to advanced programming. The major keyword parameters are described and illustrated by example in this chapter.

Correspondence with System Variables

Many of the keyword parameters correspond directly to fields in the system variables !P, !X, !Y, or !Z. When specifying a keyword parameter name and value in a call that value affects only the current call, the corresponding system-variable field is not changed. Changing the value of a system-variable field changes the default for that particular parameter and remains in effect until explicitly changed. The system-variables involving graphics and their corresponding keywords are detailed in the IDL Reference Guide.

Example—The COLOR Keyword Parameter

The keyword parameter COLOR corresponds to the field COLOR of the system-variable structure !P and is referenced as !P.COLOR. To set the color of a plot to color index 12, use the following statement:

PLOT, X, Y, COLOR = 12

Future plots are not affected and are drawn with color index !P.COLOR, which is normally set to the number of available colors minus one.

The interpretation of the color index varies among the devices supported by IDL. With color video displays, this index selects a color (normally a red, green, blue (RGB) triple stored in a device table). You can control the color selected by each color index with the TVLCT procedure which loads the device color tables.

Other devices have a fixed color associated with each color index. With plotters, for example, the correspondence between colors and color index is established by the order of the pens in the carousel.

To change the default color of future plots, use a statement such as:

!P.COLOR = 12

which sets the default color to color index 12. You can override this default at any time by including the COLOR keyword in the graphic routine call.


Graphics Coordinate Systems

You can specify coordinates to IDL in one of the following coordinate systems:

DATA Coordinates

This coordinate system is established by the most recent PLOT, CONTOUR, or SURFACE procedure. This system usually spans the plot window, the area bounded by the plot axes, with a range identical to the range of the plotted data. The system can have two or three dimensions and can be linear, logarithmic, or semi-logarithmic. The mechanisms of converting from one coordinate system to another are described below. See "CONVERT_COORD Function" on page 14-4.

DEVICE Coordinates

This coordinate system is the physical coordinate system of the selected plotting device. Device coordinates are integers, ranging from (0, 0) at the bottom-left corner to (Vx - 1, Vy - 1) at the upper-right corner. Vx and Vy are the number of columns and rows addressed by the device. These numbers are stored in the system variable !D as !D.X_SIZE and !D.Y_SIZE.

NORMAL Coordinates

The normalized coordinate system ranges from zero (0) to one (1) over each of the three axes.

Almost all of the IDL graphics procedures accept parameters in any of these coordinate systems. Most procedures use the data coordinate system by default. Routines beginning with the letters TV are notable exceptions. They use device coordinates by default. You can explicitly specify the coordinate system to be used by including one of the keyword parameters /DATA, /DEVICE, or /NORMAL in the call.

Two-Dimensional Coordinate Conversion

The system variables !D, !P, !X, !Y, and !Z contain the information necessary to convert from one coordinate system to another. The relevant fields of these system variables are explained below, and formulae are given for conversions to and from each coordinate system. Three-dimensional coordinates are discussed in Chapter 15.

In the following discussion, D is a data coordinate, N is a normalized coordinate, and R is a raw device coordinate.

The fields !D.X_VSIZE and !D.Y_VSIZE always contain the size of the  visible area of the currently selected display or drawing surface. Let Vx and Vy represent these two sizes.

The field !X.S is a two-element array that contains the parameters of the linear equation, converting data coordinates to normalized coordinates. !X.S(0) is the intercept, and !X.S(1) is the slope. !X.TYPE is 0 for a linear x-axis and 1 for a logarithmic x-axis. The y and z axes are handled in the same manner, using the system variables !Y and !Z.

Also, let Dx be the data coordinate, Nx the normalized coordinate, Rx the device coordinate, Vx the device X size (in device coordinates), and Xi = !X.Si (the scaling parameter).

With the above variables defined, the linear two-dimensional coordinate conversions for the x coordinate can be written as follows:

The y- and z-axis coordinates are converted in exactly the same manner, with the exception that there is no z device coordinate and that logarithmic z axes are not permitted.

CONVERT_COORD Function

The CONVERT_COORD function provides a convenient means of computing the above transformations. It can convert coordinates to and from any of the above systems. The keywords DATA, DEVICE, or NORMAL specify the input system. The output coordinate system is specified by one of the keywords TO_DATA, TO_DEVICE, or TO_NORMAL. For example, to convert the endpoints of a line from data coordinates (0, 1) to (5, 7) to device coordinates, use the following statement:

D = CONVERT_COORD([0, 5], [1, 7], /DATA, /TO_DEVICE)

On completion, the variable D is a (3, 2) vector, containing the x, y, and z coordinates of the two endpoints.


X Versus Y Plots - PLOT and OPLOT
X Versus Y Plots—PLOT and OPLOT

This section illustrates the use of the basic x versus y plotting routines, PLOT and OPLOT. PLOT produces linear-linear plots by default, and can produce linear-log, log-linear, or log-log plots with the addition of the XLOG and YLOG keywords.

Data from the U.S. Scholastic Aptitude Test (SAT), from the years 1967, 1970, and from 1975 to 1983 are used in the following simple examples.

Note: Variables defined in the following examples are used in later examples in this chapter.

The following IDL statements create and initialize the variables VERBM, VERBF, MATHM, and MATHF, which contain the verbal and math scores for males and females for the 11 observations:

VERBM=[463, 459, 437, 433, 431, 433, 431, 428, 430, 431, 430]
VERBF=[468, 461, 431, 430, 427, 425, 423, 420, 418, 421, 420]
MATHM=[514, 509, 495, 497, 497, 494, 493, 491, 492, 493, 493]
MATHF=[467, 465, 449, 446, 445, 444, 443, 443, 443, 443, 445]

A vector in which each element contains the year of the score is constructed with the following statement:

YEAR = [1967, 1970, INDGEN(9) + 1975]

The PLOT procedure, which produces an x versus y plot on a new set of axes, requires one or two parameters: a vector of y values or a vector of x values followed by a vector of y values. The first attempt at making a plot produces the figure shown below:

PLOT, YEAR, VERBM

Note: You can abort any of the higher-level procedures (e.g., PLOT, OPLOT, CONTOUR, and SURFACE) by typing Control-C.

Axis Scaling

The fluctuations in the data are hard to see because the scores range from 428 to 463, and the plot's y-axis is scaled from 0 to 500. Two factors cause this effect. By default, IDL sets the minimum y-axis value of linear plots to zero if the y data are all positive. The maximum axis value is automatically set by IDL from the maximum y data value. In addition, IDL attempts to produce from three to six tick-mark intervals that are in increments of an integer power of 10 times 2, 2.5, 5, or 10. In this example, this rounding effect causes the maximum axis value to be 500, rather than 463.

The YNOZERO keyword parameter inhibits setting the y-axis minimum to zero when given positive, nonzero data.  The figure below illustrates the data plotted using this keyword. The y-axis now ranges from 420 to 480 because IDL selected three tick-mark intervals of 20. In addition, axis titles and a main title have been added to the plot:

PLOT, YEAR, VERBM, /YNOZ, $

     TITLE='Verbal Sat, Male', XTITLE='Year', YTITLE='Score'

Multiline Titles

The graph-text positioning command !C, starts a new line of text output. Titles containing more than one line of text are easily produced by separating each line with this positioning command.

In the above example, the main title could have been displayed on two centered lines by changing the keyword parameter TITLE to the following statement:

TITLE = 'Verbal SAT!CMale'

Note: When using multiple line titles you may find that the default margins are inadequate, causing the titles to run off the page. In this case, increase the values of !X.MARGIN and/or !Y.MARGIN.

Range Keyword

The range of the x, y, or z axes can be explicitly specified with the [XYZ] RANGE keyword parameter. The argument of the keyword parameter is a two-element vector containing the minimum and maximum axis values.

As explained above, IDL attempts to produce even tick intervals, and the axis range selected by IDL may be slightly larger than that given with the RANGE keyword. To obtain the exact specified interval, set the axis style parameter to one (YSTYLE = 1).

The effect of the YNOZERO keyword is identical to that obtained by including the keyword parameter YRANGE = [MIN(Y), MAX(Y)] in the call to PLOT. You can make /YNOZERO the default in subsequent plots by setting bit 4 of !Y.STYLE to one (!Y.STYLE = 16).

The IDL Reference Guide describes the other bits in the STYLE field of the axis system variables !X, !Y, and !Z. Briefly: Other bits in the STYLE field extend the axes by providing a margin around the data, suppress the axis and its notation, and suppress the box-style axes by drawing only left and bottom axes.

For example, to constrain the x-axis to the years 1975 to 1983, the keyword parameter XRANGE = [1975, 1983] is included in the call to PLOT.  The figure below illustrates the result. Note that the x-axis actually extends from 1974 to 1984, as IDL elected to make five tick-mark intervals, each spanning two years. If, as explained above, the x-axis style is set to one, the plot will exactly span the given range. The call combining all these options is as follows:

PLOT, YEAR, VERBM, /YNOZERO, TITLE='Verbal SAT, Male', $

      XTITLE = 'Year', YTITLE = 'Score', $

      XRANGE = [1975, 1983], /XSTYLE

Note: The keyword parameter syntax /XSTYLE is synonymous with the expression XSTYLE = 1. Setting a keyword parameter to 1 is often referred to as simply setting the keyword.

Overplotting

Additional data can be added to existing plots with the OPLOT procedure. Each call to PLOT establishes the plot window (the rectangular area enclosed by the axes), the plot region (the box enclosing the plot window and its annotation), the axis types (linear or log), and the scaling. This information is saved in the system variables !P, !X, and !Y and used by subsequent calls to OPLOT.

Frequently, the color index, linestyle, or line thickness parameters are changed in each call to OPLOT to distinguish the data sets. The IDL Reference Guide contains a table describing the line style associated with each index.

 The figure below illustrates a plot showing all four data sets. Each data set except the first was plotted with a different line style and was produced by a call to OPLOT. In this example, an (11, 4) array called ALLPTS is defined and contains all the scores for the four categories using the array concatenation operator. Once this array is defined, the IDL array operators and functions can be applied to the entire data set, rather than explicitly referencing the particular score.

The plot  was produced with the following statements:

ALLPTS = [[VERBF], [VERBM], [MATHF], [MATHM]]
Make an (n, 4) array containing the four score vectors.

PLOT, YEAR, VERBF, YRANGE = [MIN(ALLPTS), MAX(ALLPTS)]
Plot first graph. Set the y-axis min and max from the min and max of all data sets. Default linestyle is 0. Note that the TITLE keywords have been omitted from this example for clarity.

FOR I = 1, 3 DO OPLOT, YEAR, ALLPTS(*, I), LINE = I
Loop for the three remaining scores, varying the linestyle.


Annotation - The XYOUTS Procedure
Annotation ­ The XYOUTS Procedure

An obvious problem with the above figure is that each line should be labeled showing what it depicts. The XYOUTS procedure is used to write graphic text at a given location. The call to XYOUTS to write a string starting at location (x, y) is as follows:

XYOUTS, X, Y, STRING

The following major keyword parameters can be included in the call (see the description of XYOUTS in the IDL Reference Guide or a complete list of keywords):

ALIGNMENT

This keyword specifies the horizontal alignment of the text in relation to the point (x, y). A value of 0.0 (the default) left-justifies the text, 0.5 centers the text, and 1.0 right- justifies the text.

COLOR

Set this keyword to the color index used to write the text.

DATA

Set this keyword parameter to indicate that the (x, y) coordinates are in data units. The data coordinate system is usually the default, so it is normally not necessary to specify this keyword.

DEVICE

Set this keyword to indicate that the (x , y) coordinates are in device coordinates.

FONT

Set this keyword to the index of the font used in writing the text. A font index of -1 selects the vector-drawn fonts, and an index of 0 selects the hardware-generated text. Different hardware-generated fonts, such as the PostScript Times-Roman, Helvetica, etc., are device dependent and are selected by the DEVICE procedure. The IDL Reference Guide describes how to access these hardware-generated fonts.

NOCLIP

This keyword controls the clipping of vectors, polygons, and vector-drawn text. By default, clipping is disabled. To enable it, include the parameter  NOCLIP = 0. The clipping rectangle is enclosed by the axes of the most recent plot unless you explicitly specify a rectangle using the CLIP keyword.

NORMAL

Set this keyword to indicate that the (x, y) coordinates are in normalized coordinates which range from 0.0 to 1.0.

ORIENTATION

Set this keyword to the desired angle, in degrees counter-clockwise, of the text baseline with respect to the horizontal.

SIZE

Set this keyword to the desired text size (normal size is 1.0).

 The figure below illustrates one method of annotating each graph with its name. The plot was produced exactly as was the above figure, except that the x-axis range was extended to the year 1990 to allow room for the titles. To accomplish this, the keyword parameter XRANGE = [1967, 1990] was added to the call to PLOT. A string vector, NAMES, containing the names of each score also is defined. The annotation was written using the following statements:

NAMES=['Female Verbal','Male Verbal','Female Math', 'Male Math']
Vector containing the score names.

N1 = N_ELEMENTS(YEAR) - 1	Index of last point.

FOR I = 0, 3 DO XYOUTS, 1984, ALLPTS(N1, I), NAMES(I)
Append the title of each graph on the right.

Font Selection

In addition, Figure 14.5 (see the print version of the IDL User's Guide for this figure) illustrates the PostScript Times-Roman font. This font was selected by first setting the default font, !P.FONT, to the hardware-font index of zero, and then calling the DEVICE procedure to set the Times-Roman font.

!P.FONT = 0

DEVICE, /TIMES

Note that because not all devices have selectable hardware fonts, default hardware fonts vary. Use of other PostScript fonts and their bold, italic, oblique, and other variants is described in the PostScript section of the IDL Reference Guide. Not all devices support different hardware-generated fonts.


Plotting Symbols

Each data point can be marked with a symbol and/or connected with lines. The value of the keyword parameter PSYM selects the marker symbol, as described in the IDL Reference Guide. For example, a value of 1 marks each data point with the plus sign, 2 is an asterisk, etc. Setting PSYM to minus the symbol number marks the points with a symbol and connects them with lines. A value of -1 marks points with a plus sign and connects them with lines. Note also that setting PSYM to a value of 10 produces histogram style plots in which a horizontal line is drawn across each x bin.

Frequently, when data points are plotted against the results of a fit or model, symbols are used to mark the data points while the model is plotted using a line.  The figure below illustrates this, fitting the male verbal scores to a quadratic function of the year. The IDL function POLY_FIT is used to calculate the quadratic. The statements used to construct this plot are as follows:

COEFF=POLY_FIT(YEAR, VERBM, 2, YFIT)	Use the function POLY_FIT to obtain a quadratic fit.

PLOT, YEAR, VERBM, /YNOZ, PSYM = 4, $

       TITLE = 'Quadratic Fit', XTITLE = 'Year', $

        YTITLE = 'SAT Score'	Plot the original data points with PSYM = 4, for diamonds.

OPLOT, YEAR, YFIT	Overplot the smooth curve using a plain line.

Defining Your Own Plotting Symbols

The USERSYM procedure allows you to define your own symbols by supplying the coordinates of the lines used to draw the symbol. The symbol you define can be drawn using lines or it can be filled using the polygon filling operator. USERSYM accepts two vector parameters: a vector of x values and a vector of y values. The coordinate system you use to define the symbol's shape is centered on each data point, and each unit is approximately the size of a character. For example, to define the simplest symbol, use a one character-wide dash centered over the data point:

USERSYM, [-.5, .5], [0, 0]

The color and line thickness used to draw the symbols are also optional keyword parameters of USERSYM. The right half of Figure 14.1 (shown only in the print version of the IDL User's Guide) illustrates the use of USERSYM to define a new symbol—a filled circle. It was produced in exactly the same manner as the example above, except with the addition of the following statements that define the marker symbol and use it:

A = FINDGEN(16) * (!PI*2/16.)	Make a vector of 16 points, A(i) = 2πi/16.

USERSYM, COS(A), SIN(A), /FILL	Define the symbol to be a unit circle with 16 points. Set the filled flag.

PLOT, YEAR, VERBM, /YNOZ, PSYM = 8, ... ...

As above, but use symbol index 8 to select user-defined symbols.

Histogram Mode

Using the keyword PSYM=10 with the PLOT routines draws graphs in the "histogram mode," connecting points with vertical and horizontal lines.  The figure below illustrates the comparison between the distribution of the IDL normally distributed random number function (RANDOMN) to the theoretical normal distribution:

It was produced by the following IDL program:

X = FINDGEN(200) / 20. - 5.	Two-hundred values ranging from −5 to 4.95.

Y = 1/SQRT(2.*!PI) * EXP(-X^2/2) * (10./200)
Theoretical normal distribution, scale so integral is one.

H = HISTOGRAM(RANDOMN(SEED, 2000), $

      BINSIZE = 0.4, MIN = -5., MAX = 5.)/2000.
Approximate normal distribution with RANDOMN, then form the histogram.

PLOT,FINDGEN(26) * 0.4 - 4.8, H, PSYM = 10
Plot the approximation using "histogram mode."

OPLOT, X, Y * 8. 	Overplot the actual distribution.


Polygon Filling

Many scientific graphs use region filling to highlight the difference between two or more curves, to illustrate boundaries, etc. The IDL POLYFILL procedure fills the interior of arbitrary polygons given a list of vertices. The interior of the polygon can be filled with a solid color or with some devices, a user-defined fill pattern contained in a rectangular array.

 The figure below illustrates a simple example of polygon filling by filling the region under the male math scores with a color index of 25 percent the maximum, then filling the region under the male verbal scores with 50 percent of the maximum index. Because the male math scores are always higher than the verbal, the graph appears as two distinct regions.

The program that produced this figure is shown below. It first draws a plot axis with no data, using the NODATA keyword. The minimum and maximum y values are directly specified with the YRANGE keyword. Because the y-axis range does not always exactly include the specified interval (see "X Versus Y Plots— PLOT and OPLOT" on page 14-5), the variable MINVAL, is set to the current y-axis minimum, !Y.CRANGE(0). Next, the upper math score region is shaded with a polygon that contains the vertices of the math scores, preceded and followed by points on the x-axis,  (YEAR(0), MINVAL), and (YEAR(n-1), MINVAL). The polygon for the verbal scores is drawn using the same method with a different color. Finally, the XYOUTS procedure is used to annotate the two regions.

PLOT, YEAR, MATHM, YRANGE = [MIN(VERBM), MAX(MATHM)], $

    /NODATA, TITLE='Male SAT Scores'	Draw axes, no data, set the range.

PXVAL = [YEAR(0), YEAR, YEAR(N1)]	Make a vector of x values for the polygon by duplicating the first and last points.

MINVAL = !Y.CRANGE(0)	Get y value along bottom x-axis.

POLYFILL, PXVAL, [MINVAL, MATHM, MINVAL], $

    COL = 0.75 * !D.N_COLORS	Make a polygon by extending the edges of the math score down to the x-axis.

POLYFILL, PXVAL, [MINVAL, VERBM, MINVAL], $

    COL = 0.50 * !D.N_COLORS	Same with verbal.

XYOUTS, 1968, 430, 'Verbal', SIZE=2	Label the polygons.

XYOUTS, 1968, 490, 'Math', SIZE=2

Bar Charts

Bar (or box) charts are used in business-style graphics and are useful in comparing a small number of measurements within a few discrete data sets. Although not designed as a tool for business graphics, IDL can produce many business-style plots with little effort.

The following example produces a box-style chart showing the four SAT scores as boxes of differing colors or shading. The commands used to draw  the figure below are shown below and annotated. First, compile a procedure called BOX, which draws a box given the coordinates of two diagonal corners:

.RUN	Put IDL in compile mode. Type the following three lines very carefully—we don't want any errors in our short program!

PRO BOX, X0, Y0, X1, Y1, color	Define a procedure that draws a box, using POLYFILL, whose corners are (X0, Y0) and (X1, Y1).

POLYFILL, [X0, X0, X1, X1], [Y0, Y1, Y1, Y0], COL = color
Call POLYFILL.

END	End the program and put IDL back into interactive mode.

As in the previous example, the PLOT procedure is used to draw the axes and to establish the scaling using the NODATA keyword. Enter the following commands at the IDL prompt:

colors = 48*INDGEN(4) + 32	Make a vector of colors for each score.

PLOT, year, mathm, YRANGE = [MIN(allpts),MAX(allpts)], $

    TITLE = 'SAT Scores', /NODATA, $

    XRANGE = [year(0), 1990]	Use PLOT to draw the axes and set the scaling. Draw no data points; explicitly set the x and y ranges.

minval = !Y.CRANGE(0)	Get the y value of the bottom x-axis.

del = 1./5.	Width of bars in data units.

Finally, create a MAIN level procedure to draw the bars. Begin by typing .RUN at the IDL prompt, and enter the following commands:

.RUN	Put IDL into compile mode. We are now creating a main-level program. Enter the following lines with care—we don't want any syntax errors!

FOR iscore = 0, 3 DO BEGIN	Loop for each score.

yannot = minval + 20 *(iscore+1)	The y value of annotation. Vertical separation is 20 data units.

XYOUTS, 1984, yannot, names(iscore)	Label for each bar.

BOX, 1984, yannot - 6, 1988, yannot - 2, colors(iscore)
Bar for annotation.

xoff = iscore * del - 2 * del	The x offset of vertical bar for each score.

FOR iyr=0, N_ELEMENTS(year)-1 DO $	Draw vertical box for each year's score.

  BOX, year(iyr) + xoff, minval, $

       year(iyr) + xoff + del, $

       allpts(iyr, iscore), $

       colors(iscore)

ENDFOR	End the FOR loop.

END	End the MAIN level procedure.

LOADCT, 39	Load a more colorful color table.

The bars are drawn on the chart as soon as the program is executed.

Note that the procedure we have entered here as a MAIN level procedure could also be compiled as a named procedure if the variables used (VERBM, NAMES, ALLPTS, etc.) were defined within the procedure rather than at the MAIN level.


Tick Marks

You have almost complete control of the number, style, placement, thickness, and annotation of the tick marks. The following plotting keyword parameters and their corresponding system variable fields affect the tick marks:

[XYZ]GRIDSTYLE

The index of the linestyle to be used for plot tickmarks and grids (i.e., when TICKLEN is set to 1.0).

[XYZ]MINOR

The number of minor-tick intervals. If set to zero, the default, IDL automatically determines the number of minor ticks in each major tick-mark interval. Setting this parameter to 1 suppresses the minor ticks, and setting it to a positive, nonzero number, n, produces n minor-tick intervals, and n-1 minor-tick marks.

[XYZ]THICK

The thickness of the x, y, or z axes and their tick marks. This parameter is set with the field THICK in the axes system variables, !X, !Y, and !Z (e.g., !X.THICK controls the x-axis thickness). There are no keyword parameters affecting the axis thickness.

XYZ[TICKFORMAT]

Set this keyword to a format string or a string containing the name of a function that returns a string to be used to format the axis tick mark labels.

See the description of this keyword on page 2-10 of the IDL Reference Guide for more information.

TICKLEN

The length of each major-tick mark, expressed as a fraction of the window size in the tick mark's direction. The default value is 0.02. A length of 1.0 produces a grid. A value of -0.02 makes tick marks that extend away from the plot. Individual axis ticks can be controlled with the [XYZ]TICKLEN keyword.

[XYZ]TICKNAME

A string array containing the annotation of each major-tick mark. If omitted or if a given string element contains the null string, IDL labels the tick mark with its value. To suppress the tick labels, supply a string array of one-character long, blank strings, i.e., REPLICATE(' ', N). (Null strings cause IDL to number the tick mark with its value.) Note that if there are n tick-mark intervals, there are n + 1 tick marks and labels.

[XYZ]TICKS

The number of major tick-mark intervals. If set to zero or omitted, IDL produces between three and six intervals.

[XYZ]TICKV

The data values of each tick mark. You can directly specify these values, producing graphs with arbitrary tick marks. If you do this, IDL scales the axis from the first tick value to the last unless you directly specify a range. As above, be sure to provide n + 1 tick values.

Example—Box Chart

 The figure below is a box chart that illustrates the direct specification of the x-axis tick values, number of ticks, and tick names. Building upon the previous program, this program shows each of the four scores for the year 1967, the first year in our data. It uses the BOX procedure from the previous example to draw a rectangle for each score. Using the data and variables from above, the following commands create the box chart:

XVAL = FINDGEN(4)/5. + .2	Tick x values, 0.2, 0.4, 0.6, 0.8.

YVAL = [VERBF(0), VERBM(0), MATHF(0), MATHM(0)]
Make a vector of scores from first year, corresponding to the name vector from above.

PLOT, XVAL, YVAL, /YNOZERO, XRANGE = [0,1], XTICKV = XVAL, $

    XTICKS = 3, XTICKNAME = NAMES, /NODATA, $

     TITLE = 'SAT Scores, 1967'	Make the axes with no data. Force x range to [0, 1], centering xval, which also contains the tick values. Force three tick intervals making four tick marks. Specify the tick names from the names vector.

FOR I = 0, 3 DO BOX, XVAL(I) - .08, !Y.CRANGE(0), $

     XVAL(I) + 0.08, YVAL(I), 128	Draw the boxes, centered over the tick marks. !Y.CRANGE(0) is the y value of the bottom x-axis.

The top two plots in  the multi-plot figure found in the "Multiple Plots on a Page" section illustrate tick-mark lengths of 1.0 for a full grid and -0.02 for tick marks extending outward. Outward extending ticks are useful in that they do not obscure the plot inside the window. The tick linestyle can be set using the [XYZ]GRIDSTYLE keyword to make dashed or dotted grids. These two plots were produced with the following code:

PRECIP=[0.5,0.7,1.2,1.8,2.5,1.6,1.9,1.5,1.2,1.0,0.8,0.6]
Define 12 monthly precipitation values.

TEMP=[30, 34, 38, 47, 57, 67, 73, 71, 63, 52, 39, 33]
Define 12 monthly average temperature.

MONTH = ['Ja', 'Fe', 'Ma', 'Ap', 'Ma', 'Ju', $

         'Ju', 'Au', 'Se', 'Oc', 'No', 'De']
Define names of months.

DAY = FINDGEN(12) * 30 + 15	Vector containing approximate day number of the middle of each month.

PLOT, DAY, PRECIP, XTICKS = 11, XTICKNAME = MONTH, $

      TICKLEN = 1.0, XTICKV = DAY, $

      TITLE = 'Average Monthly Precipitation', $

      XTITLE = 'Inches', SUBTITLE = 'Denver'
Plot, setting tick-mark length to full and setting number, position, and labels of ticks.

PLOT, DAY, PRECIP, XTICKS = 11, XTICKNAME = MONTH, $

      TICKLEN = -0.02, XTICKV = DAY, $

      TITLE = 'Average Monthly Precipitation', $

       XTITLE = 'Inches', SUBTITLE = 'Denver'
As above, setting tick-mark length for outside ticks.


Logarithmic Scaling

The XLOG, YLOG, and ZLOG keywords can be used with the PLOT routine to get any combination of linear and logarithmic axes. The OPLOT procedure uses the same scaling and transformation as did the most recent plot.  The figure below illustrates using PLOT to make a linear-log plot. It was produced with the following statements:

X = FLTARR(256)	Create data array.

X(80:120) = 1	Make a step function. Array elements 80 through 120 are set to 1.

FREQ = FINDGEN(256)	Make a filter.

FREQ = FREQ < (256-FREQ)	Make the filter symmetrical about the value x =128.

FIL = 1./(1+(FREQ/20)^2)	Second order Butterworth, cutoff frequency = 20.

PLOT, /YLOG, FREQ, ABS(FFT(X,1)), $

          XTITLE = 'Relative Frequency', YTITLE = 'Power', $

         XSTYLE = 1	Plot with a logarithmic x-axis. Use exact axis range.

OPLOT, FREQ, FIL	Plot graph.


Multiple Plots on a Page

Plots can be "ganged" on the display or page in the horizontal and/or vertical directions using the system variable field !P.MULTI. IDL sets the plot window to produce the given number of plots on each page and moves the window to a new sector at the beginning of each plot. If the page is full, it is first erased. If more than two rows or columns of plots are produced, IDL decreases the character size by a factor of 2.

!P.MULTI controls the output of multiple plots and is an integer vector in which the following applies:

!P.MULTI(0)

Contains the number of empty sectors remaining on the page. The display is erased if this field is zero when a new plot is begun.

!P.MULTI(1)

The number of plots across the page.

!P.MULTI(2)

Contains the number of plots per page in the vertical direction.

For example, to set up IDL to stack two plots vertically on each page, use the following
statement:

!P.MULTI = [0, 1, 2]

Note that the first element, !P.MULTI (0), is set to zero to cause the next plot to begin a new page. To make four plots per page with two columns and two rows, use the following statement:

!P.MULTI = [0, 2, 2]

 The figure below illustrates this format. To reset to the default of one plot per page, set the value of !P.MULTI to 0, as shown in the following statement:

!P.MULTI = 0


Specifying the Location of the Plot

The plot-data window is the region of the page or screen enclosed by the axes. The plot region is the box enclosing the plot-data window and the titles and tick annotation.  The figure below illustrates the relationship of the plot-data window, plot region, and the entire device area. These areas are determined by the following system variables and keyword parameters, in order of decreasing precedence:

POSITION

Keyword, a four-element vector (six elements for three-dimensional plots) containing the position of the axis endpoints: [x0, y0, x1, y1]. Coordinates are specified in normalized coordinates or in device coordinates if the DEVICE keyword is present.

!P.POSITION

A four-element vector in the same form as above containing the normalized coordinates of the plot-data window. !P.POSITION is ignored if x0 is equal to x1, (that is, if !P.POSITION(0) EQ !P.POSITION(2)), which is the default.

!P.REGION

Another four-element vector in the same form as above containing the normalized coordinates of the plot region, the rectangle enclosing the plot-data window and annotation. It is ignored if !P.REGION (0) is equal to !P.REGION (2).

!P.MULTI

The multiplot variable described above.

![X, Y, Z]MARGIN

The MARGIN keyword parameters specify in character units the margin between the x, y, and z axes and the screen or region borders.


Plotting Missing Data

The MAX_VALUE and MIN_VALUE keywords to PLOT can be used to create "missing data" plots wherein "bad" data values are not plotted. Data values greater than the value of the MAX_VALUE keyword or less than the value of the MIN_VALUE keyword are treated as missing and are not plotted. The following code creates a dataset with "bad" data values and plots it with and without these keywords:

A = FINDGEN(100)	Make a 100-element array where each element is set equal to its index.

A(RANDOMU(SEED, 20)*100)=400	Set 20 random point in the array equal to 400. This simulates "bad" data values above the range of the "real" data.

A(RANDOMU(SEED, 20)*100)=-10	Set 20 random point in the array equal to -10. This simulates "bad" data values below the range of the "real" data.

PLOT, A	Plot the dataset with the bad values. Looks pretty bad!

PLOT, A, MAX_VALUE=101	Plot the dataset, but don't plot any value over 101. The resulting plot looks better, but still shows spurious values.

PLOT, A, MAX_VALUE=101, MIN_VALUE=0
This time leave out both high and low spurious values. The resulting plot more accurately reflects the "real" data.

The following plotting routines allow you to set maximum and minimum values in this manner: CONTOUR, PLOT, SHADE_SURF, SURFACE.

In addition to the maximum and minimum values specified with the MAX_VALUE and MIN_VALUE keywords, these plotting routines treat the IEEE floating-point value NaN (Not A Number) as missing data automatically. (For more information on NaN, see "Special Floating-Point Values" on page 11-9 of the IDL User's Guide.)


Using the AXIS Procedure

The AXIS procedure draws and annotates an axis. It optionally saves the scaling established by the axis for use by subsequent graphics procedures. It can be used to add additional axes to plots or to draw axes at a specified position.

The AXIS procedure accepts the set of plotting keyword parameters that govern the scaling and appearance of the axes. Additionally, the keyword parameters XAXIS, YAXIS, and ZAXIS specify the orientation and position (if no position coordinates are present) of the axis. The value of these parameters are 0 for the bottom or left axis and 1 for the top or right. The tick marks and their annotation extend away from the plot window. For example, specify YAXIS = 1 to draw a y-axis on the right of the window.

The optional keyword parameter SAVE saves the data-scaling parameters established for the axis in the appropriate axis system variable, !X, !Y, or !Z. The call to AXIS is as follows:

AXIS[[, X, Y], Z], Keyword_Parameters

where X, Y, and optionally Z specify the coordinates of the axis. Any of the coordinate systems can be used by including the appropriate coordinate keyword in the call. The coordinate corresponding to the axis direction is ignored. When specifying an x-axis, the x coordinate parameter is ignored, but must be present if there is a y coordinate.

Example

The bottom left plot of  the figure below illustrates using AXIS to draw axes with a different scale, opposite the main x and y axes. The plot is produced using PLOT with the bottom and left axes annotated and scaled in units of days and degrees Fahrenheit. The XMARGIN and YMARGIN keyword parameters are specified to allow additional room around the plot window for the new axes. The keyword parameters XSTYLE = 8 and YSTYLE = 8 inhibit drawing the top and right axes.

Next, the AXIS procedure is called to draw the top, XAXIS = 1, axis, labeled in months. Eleven tick intervals with 12 tick marks are drawn. The x value of each monthly tick mark is the day of the year that is approximately the middle of the month. Tick-mark names come from the MONTH string array.

The right y-axis, YAXIS = 1, is drawn in the same manner. The new y-axis range is set by converting the original y-axis minimum and maximum values, saved by PLOT in !Y.CRANGE, from Fahrenheit to Celsius, using the formula C = 5(F-32)/9. The keyword parameter YSTYLE = 1 forces the y-axis range to match the given range exactly. The program is as follows:

PLOT, DAY, TEMP, /YNOZERO, $	Plot the data, omit right and top axes.

  SUBTITLE = 'Denver Average Temperature', $

  XTITLE = 'Day of Year', $

  YTITLE = 'Degrees Fahrenheit', $

  XSTYLE=8, YSTYLE=8, XMARGIN=[8, 8], YMARGIN=[4, 4]

AXIS, XAXIS = 1, XTICKS = 11, XTICKV = DAY, XTICKN = MONTH, $

     XTITLE='Month', XCHARSIZE = 0.7	Draw the top x-axis, supplying labels, etc. Make the characters smaller so they will fit.

AXIS, YAXIS=1, YRANGE = (!Y.CRANGE-32)*5./9., YSTYLE = 1, $

      YTITLE = 'Degrees Celsius'	Draw the right y-axis. Scale the current y-axis minimum values from Fahrenheit to Celsius and make them the new min and max values. Set YSTYLE=1 to make axis exact.

Using AXIS with Polar Plots

If the POLAR keyword parameter is set, the IDL PLOT procedure converts its coordinates from polar to cartesian coordinates when plotting. The first parameter to plot is the radius, R, and the second is expressed in radians. Polar plots are produced using the standard axis and label styles, with box axes enclosing the plot area.

The bottom right plot in  the figure below illustrates using AXIS to draw centered axes, dividing the plot window into the four quadrants centered about the origin. This method uses PLOT to plot the polar data and to establish the coordinate scaling, but suppresses the axes. Next, two calls to AXIS add the x and y axes, drawn through data coordinate (0, 0):

R = FINDGEN(100)	Make a radius vector.

THETA = R/5	Make a vector.

PLOT, R, THETA, SUBTITLE='Polar Plot', XSTY=4, YSTY=4, /POLAR
Plot the data, suppressing the axes by setting their styles to 4.

AXIS, 0, 0, XAX=0

AXIS, 0, 0, YAX=0	Draw the x and y axes through (0, 0).


The CURSOR Procedure

The CURSOR procedure reads the position of the interactive graphics cursor of the current graphics device. It enables the graphic cursor on the device, optionally waits for the user to move it and/or press a locator button to terminate the operation (or type a character if the device has no buttons), and then reports the cursor position.

Note, however, that CURSOR should not be used with draw widgets, created by the WIDGET_DRAW function. If you need to find the position of the mouse or status of mouse buttons in a draw widget, set the BUTTON_EVENTS and MOTION_EVENTS keywords to WIDGET_DRAW, then examine the events returned by your draw widget. See "WIDGET_DRAW" on page 1-999 of the IDL Reference Guide.

The CURSOR procedure is called as follows:

CURSOR, X, Y[, WAIT]

where x and y are the named variables that receive the cursor position. Normally, the position is reported in data coordinates, but the DATA, DEVICE, and NORMAL keywords can be used to explicitly specify the coordinate system. The following keyword parameters can be used to specify which actions cause CURSOR to return:

CHANGE

Wait for pointer movement or button-down state within the currently selected window.

DOWN

Wait for a button-down transition within the currently selected window.

NOWAIT

Return immediately with the current locator position and button status. If the locator is not within the currently selected window, the device coordinates are set to -1, -1.

UP

Wait for a button-up transition within the currently selected window.

WAIT

Wait for a button to be depressed within the currently selected window. If a button is already pressed, return immediately.

Note: Many devices, such as Tektronix terminals, do not have the ability to return immediately, and therefore should always be used with the WAIT keyword. In addition, not all types of waiting are available for devices that do not have the ability to sense transitions or states.

The following values can be provided for WAIT:

WAIT value	Keyword	Action
0	NOWAIT	Return immediately
1	WAIT	Return if a button is down
2	CHANGE	Return if button pressed, changed, or pointer moved
3	DOWN	Return when button-down transition is detected
4	UP	Return when button-up transition is detected
Table 14.1 CURSOR Keywords

The system variable !ERR is set to the button status or ASCII code of the key if no mouse is present. Each mouse button is assigned a bit in !ERR. Bit 0 is the leftmost button (value = 1), bit 1 is the middle button (value = 2), and bit 3 is the rightmost button (value = 4) for the typical three-button mouse.

Examples Using CURSOR

The following code creates a simple drawing program. Straight lines are connected to positions marked with the left or middle mouse buttons until the right button is pressed. Create the following main-level procedure, beginning with the .RUN command:

ERASE	Start with a blank screen.

CURSOR, X, Y, /NORMAL, /DOWN	Get the initial point in normalized coordinates.

WHILE (!ERR NE 4) DO BEGIN	Repeat until the right button is pressed.

  CURSOR, X1, Y1, /NORM, /DOWN	Get the second point.

  PLOTS,[X,X1], [Y,Y1], /NORMAL	Draw the line.

  X = X1 & Y = Y1	Make the current second point be the new first.

ENDWHILE

END

For another example, the following simple procedure can be used to label plots using the cursor to position the text:

PRO ANNOTATE, TEXT 	Text is the string to be written on the screen.

PRINT, 'Use the mouse to mark the text position:'
Ask the user to mark the position.

CURSOR, X, Y, /NORMAL, /DOWN	Get the cursor position after pressing any button.

XYOUTS, X, Y, TEXT, /NORMAL, /NOCLIP	Write the text at the specified position. The NOCLIP keyword is used to ensure that the text will appear even if it is outside the plotting region.

END

To place annotation on a device with an interactive pointer, call this procedure with the command:

ANNOTATE, "Text for label"

Next, move the pointer device (mouse, cursor, or joystick) to the desired spot, and press the locator button.

Jump forward to Plotting Multi-Dimensional Arrays

Jump backward to Interactive Support


Plotting Multi-Dimensional Arrays
15	Plotting Multi-Dimensional
Arrays

Chapter Overview

This chapter describes the facilities for drawing representations of two-dimensional arrays. The two intrinsic procedures for the display of arrays are CONTOUR and SURFACE. Procedures for displaying two-dimensional arrays in the form of images, using color or grayscale pixels, are discussed in Chapter 16, "Image Display Routines."

CONTOUR and SURFACE both use line graphics to depict the value of a two-dimensional array. As its name implies, CONTOUR draws contour plots.

SURFACE depicts the surface created by interpreting each element value as an elevation. These three-dimensional, wire-mesh surface plots can have almost any rotation about the x and z axes (the data z axis must project parallel to the device's y axis).

Three-dimensional graphics, coordinate systems, and transformations also are included in this chapter. Almost all of the information concerning coordinate systems, keyword parameters, and system variables discussed in Chapter 14 apply to CONTOUR and SURFACE as well.


Topics in Plotting Multi-D Arrays Chapter
Plotting Multi-Dimensional Arrays

This chapter provides and overview of IDL's tools for plotting representations of multi-dimensional data.

Topics Covered:

Contour Plots

Overlaying Images and Contour Plots

Additional Contour Options

The SURFACE Procedure

Three-Dimensional Graphics

Three-Dimensional Transformations with Two-Dimensional Procedures

Shaded Surfaces—The SHADE_SURF Procedure

Volume Visualization—The SHADE_VOLUME Procedure

Jump forward to Image Display Routines

Jump backward to Plotting


 Contour Plots

The CONTOUR procedure draws contour plots from data stored in a rectangular array. In its simplest form, CONTOUR makes a contour plot given a two-dimensional array of z values. In more complicated forms, CONTOUR accepts, in addition to z, arrays containing the x and y locations of each column, row, or point, plus many keyword parameters. In more sophisticated applications, the output of CONTOUR can be projected from three dimensions to two dimensions, superimposed over an image, or combined with the output of SURFACE. The call to CONTOUR is as follows:

CONTOUR, Z

This call labels the x and y axes with the subscript along each dimension. For example, when contouring a 10 x 20 array, the x-axis ranges from 0 to 9, and the y-axis ranges from 0 to 19.

You can explicitly specify the x and y locations of each cell with the following call:

CONTOUR, Z, X, Y

The x and y arrays can be either vectors or two-dimensional arrays of the same size as z. If they are vectors, the element zi,j has a coordinate location of (xi, yj). Otherwise, if the x and y arrays are two-dimensional, the element zi,j has the location (xi,j, yi,j). Thus, vectors should be used if the x location of zi,j does not depend upon j and the y location of zi,j does not depend upon i.

Dimensions must be compatible. In the one-dimensional case, x must have a dimension equal to the number of columns in z, and y must have a dimension equal to the number of rows in z. In the two- dimensional case, all three arrays must have the same dimensions.

IDL uses linear interpolation to determine the x and y locations of the contour lines that pass between grid elements. The cells must be regular in that the x and y arrays must be monotonic over rows and columns, respectively. The lines describing the quadrilateral enclosing each cell and whose vertices are (xi,j, yi,j), (xi+1,j, yi+1,j), (xi+1,j+1, yi+1,j+1), and (xi,j+1, yi,j+1) must intersect only at the four corners and the quadrilateral must not contain other nodes.

Contouring Methods

In order to provide a wide range of options, CONTOUR uses one of two contouring algorithms. The algorithm used depends on the keywords specified as follows:

Cell Drawing

The first algorithm, used by default, examines each array cell and draws all contours emanating from that cell before proceeding to the next cell. This method is efficient in terms of computer resources, but does not allow options such as contour labeling or smoothing.

Contour Following

The second method searches for each contour line, then follows the line until it reaches a boundary or closes. This method gives better looking results with dashed linestyles and allows contour labeling and bi-cubic spline interpolation, but requires more computer time. The contour following method is used if any of these keywords are specified: C_ANNOTATION, C_CHARSIZE, C_LABELS, CLOSED, FOLLOW, PATH_FILENAME, or DOWNHILL.

It should be noted that due to their differing algorithms, these two methods will often draw slightly different, yet correct contour maps for the same data. This difference is a direct result of the fact that there is often more than one valid way to draw contours and should not be a cause for concern.

Example: Maroon Bells Peaks

Digital elevation data of the Maroon Bells area, near Aspen, Colorado, are used to illustrate the CONTOUR procedure. The data set was obtained from a United States Geological Survey Digital Elevation Model tape. This data provides terrain elevation data over a 7.5-minute square (approximately 11 x 13.7 kilometers at the latitude of Maroon Bells), with 30-meter sampling.

The data are contained in a 360 x 460 array A, sampled in 30-meter square intervals, measured in Universal Transverse Mercator (UTM) coordinates. The rectangular array is not completely filled with data because the 7.5-minute square is not perfectly oriented to the UTM grid system. Missing data are represented as zeroes. Elevation measurements range from 2658 to 4241 meters or from 8720 to 13,914 feet.

The figure below is the result of applying the CONTOUR procedure to the data, using the default settings:

CONTOUR, A

A number of problems are apparent.

•	IDL selected six contour levels, by default, at (4241-0)/7-meter intervals or approximately 605 meters. The levels are 605, 1250, ..., 3635 meters, even though the range of valid data is from 2658 to 4241 meters. This is because the missing data values of 0 were considered when selecting the intervals. It is more appropriate to select levels only within the range of valid data.

•	The vertical contours along the left edge are an artifact due to contouring missing data and should not be present.

•	For most display systems and for contour intervals of approximately 200 meters, the data has too many samples in the xy direction. This "oversampling" has two adverse effects: the contours appear jagged and a large number of short vectors are produced.

•	The axes are labeled by point number, but should be in UTM coordinates.

•	It is difficult to visualize the terrain and to discern maxima from minima because each contour is drawn with the same type of line.

The above problems are readily solved using the following simple techniques:

•	Specify the contour levels directly using the LEVELS keyword parameter. Selecting contour intervals of 250 meters, at elevation levels of [2750, 3000, 3250, 3500, 3750, 4000], results in six levels.

•	Change the missing data value to a value well above the maximum valid data value, then use the MAX_VALUE keyword parameter to exclude missing points. In this example, we set missing data values to one million with the following statement:

A(WHERE(A EQ 0)) = 1.0E6

•	Use the REBIN function to decrease the sampling in x and y by a factor of 5:

B = REBIN(A, 360/5, 460/5)

This smooths the contours, because the call to REBIN averages 5^2=25 bins when resampling. The number of vectors transmitted to the display also are decreased by a factor of approximately 25. The variable B is now a 72 x 92 array.

Care is taken in the second step to ensure that the missing data are not confused with valid data after REBIN is applied. As in this example, REBIN averages bins of 5^2=25 elements, the missing data value must be set to a value of at least 25 times the maximum valid data value. After applying REBIN, any cell with a missing original data point will have a value of at least 106/25 = 40000, well over the largest valid data value of approximately 4,500.

The x and y vectors are constructed containing the UTM coordinates for each row and column. From the USGS data tape, the UTM coordinate of the lower-left corner of the array is (326,850: 4,318,500) meters. As the data spacing is 30 meters in both directions, the x and y vectors, in kilometers, are easily formed using the FINDGEN function, as shown in the example below.

Contour levels at each multiple of 500 meters (every other level) are drawn with a solid linestyle, while levels that fall between are drawn with a dotted line. In addition, the 4000-meter contour is drawn with a triple thick line, emphasizing the top contour.

The result of these improvements is shown in the figure below. It was produced with the following IDL statements.

A (WHERE (A EQ 0)) = 1E6	Set missing data points to a large value.

B = REBIN(A, 360/5, 460/5)	REBIN down to a 72 x 92 matrix.

X = 326.850 + .030 * FINDGEN(72)	Make the x and y vectors giving the position of each column and row.

Y = 4318.500 + .030 * FINDGEN(92)

CONTOUR, B, X, Y, LEVELS = 2750 + FINDGEN(6) * 250., $

  XSTYLE = 1, YSTYLE = 1, MAX_VALUE = 5000, $

  C_LINESTYLE = [1, 0], $

  C_THICK = [1, 1, 1, 1, 1, 3], $

  TITLE = 'Maroon Bells Region', $

  SUBTITLE = '250 meter contours', $

  XTITLE = 'UTM Coordinates (KM)'	Make the plot, specifying the contour levels, missing data value, linestyles, etc. Set the STYLE keywords to 1, obtaining exact axes.

The figure below illustrates the data displayed as a grayscale image. Higher elevations are white. This image demonstrates that contour plots do not always provide the best qualitative visualization of many two-dimensional data sets.


Overlaying Images and Contour Plots

Superimposing an image and its contour plot combines the best of both worlds: the image allows easy visualization and the contour lines provide a semi-quantitative display. The programs presented in the rest of this section are for advanced computing only.

A combined contour and image display, such as that discussed in this section, can be created with the IMAGE_CONT procedure. The following material is intended to illustrate the ways in which images and graphics can be combined using IDL.

The technique used to overlay plots and images depends on whether or not the device is able to represent pixels of variable size, as does PostScript, or if it has pixels of a fixed size. If the device does not have scalable pixels, the image must be resized to fit within the plotting area if it is not already of a size suitable for viewing. This leads to three separate cases that are illustrated in the following examples.

Overlaying with Scalable Pixels

Certain devices, notably PostScript, can display pixels of varying sizes. With these devices, it is easy to set the size and position of an image so that it exactly overlays the plot window. For example, the following statements were used to produce the figure below.

C = BYTSCL(A, MIN=2658, MAX=4241)	Scale the range of valid elevations into intensities.

TV, C, !X.WINDOW(0), !Y.WINDOW(0), $

  XSIZE = !X.WINDOW(1) - !X.WINDOW(0), $

   YSIZE = !Y.WINDOW(1) - !Y.WINDOW(0), /NORM
Display the image with its lower-left corner at the origin of the plot window and with its size scaled to fit the plot window.

CONTOUR, B, X, Y, LEVELS = 2750 + FINDGEN(6) * 250., $

  MAX_VALUE = 5000, XSTYLE = 1, YSTYLE = 1, /NOERASE
Write the contours over the image, being sure to use the exact axis styles so that the contours fill the plot window. Inhibit erasing.

Be sure that the position of the plot window contained in the field WINDOW in !X, !Y, and !Z is set, using CONTOUR or PLOT, before executing the above statements. Also, note that in the figure above, the aspect ratio of the image was changed to fit that of the plot window. To retain the original image aspect ratio, the plot window must be resized to an identical aspect ratio using the POSITION keyword parameter.

Overlaying with Fixed Pixels

Method 1: Scale the Image to Fit the Display

If the pixel size cannot be changed, an image of the same size as the plotting window must be created using the CONGRID function. The REBIN function also can be used to resample the original image if the plot window dimensions are an integer multiple or factor of the original image dimensions. REBIN is always faster than CONGRID. The following IDL procedure creates an image of the same size as the window, displays it, then overlays the contour plot.

PRO IMAGE_CONT, A	Procedure to scale an image to the plot window, display it, then overlay its contour plot.

PX = !X.WINDOW * !D.X_VSIZE	Get size of plot window in device pixels.

PY = !Y.WINDOW * !D.Y_VSIZE

SX = PX(1) - PX(0) + 1	Desired size of image in pixels.

SY = PY(1) - PY(0) + 1

ERASE	Erase the display.

TV, CONGRID(BYTSCL(A), SX, SY), PX(0), PY(0)
Create an SX-pixels by SY-pixels image stretched from the original. Display it with same lower-left corner coordinate as the window. Note that we apply BYTSCL before changing the size, as it is more efficient to apply CONGRID to byte images. Also, it is likely that the original image is smaller than the stretched image.

CONTOUR, A, /NOERASE, XSTYLE = 1, YSTYLE = 1
Draw the contour without first erasing the screen.

END

Method 2: Scale the Display to Fit the Image

If the image is already close to the proper display size, it is simpler and more efficient to change the plot window size to that of the image. The following procedure displays the image at the window origin, then sets the plot window to the image size, leaving its origin unchanged.

PRO IMAGE_CONT1, A	Display image at the origin of the plot window, then overlay its contour plot scaled to the same size.

PX = !X.WINDOW * !D.X_VSIZE	Get size of the plot window in device pixels.

PY = !Y.WINDOW * !D.Y_VSIZE

SZ = SIZE(A)	Size of original image.

ERASE	Clear the display.

TVSCL, A, PX(0), PY(0)	Scale and display the image at the lower-left corner of the plot window.

CONTOUR, A, /NOERASE, XSTYLE = 1, YSTYLE = 1, $

  POSITION = [PX(0), PY(0), PX(0) + SZ(1) - 1, $

   PY(0) + SZ(2) - 1], /DEVICE	Make the contour; explicitly set the plot window in device coordinates to the size of the image. Make the axes exact. Do not erase.

END

Of course, these procedures can be customized by using other keyword parameters with the CONTOUR procedure.


Additional Contour Options

In addition to the abilities of CONTOUR demonstrated above, there are several options that depend upon the use of the contour following algorithm. These options are as follows:

Labeling Contours

The C_ANNOTATION, C_CHARSIZE, and C_LABELS keywords are used to control contour labeling. Using them, possibly in conjunction with the LEVELS keyword, it is possible to specify which contours should be labeled, the size of the labels, and the actual labels that should be used.

In the following discussion, a variable named DATA is contoured. This variable contains uniformly distributed random numbers obtained using the following statements:

SEED = 20 & DATA = RANDOMU(SEED, 6, 6)

To label contours using the defaults for label size and contours to label, it is sufficient to select the FOLLOW keyword. In this case, CONTOUR labels every other contour using the default label size (three-fourths of the plot axis label size). Each contour is labeled with its value. The figure below was produced using the following statement:

CONTOUR, /FOLLOW, DATA

The C_CHARSIZE keyword is used to specify the size of the characters used for labeling in the same manner that SIZE is used to control plot axis label size. The C_LABELS keyword can be used to select the contours to be labeled. For example, suppose that we want to contour the variable DATA at 0.2, 0.5, and 0.8, and we want all three levels labeled. In addition, we wish to make each label larger, and use hardware fonts. This can be accomplished with the statement below.

CONTOUR, LEVEL=[0.2, 0.5, 0.8], C_LABELS=[1, 1, 1], $

C_CHARSIZE = 1.25, DATA, FONT = 0

The result is the plot on the left in the figure below.

Finally, it is possible to specify the text to be used for the contour labels using the C_ANNOTATION keyword, as shown in the statement below.

CONTOUR, LEVEL=[0.2, 0.5, 0.8], C_LABELS=[1, 1, 1], $

C_ANNOTATION = ["Low", "Medium", "High"], DATA, FONT=0

The result is the plot on the right in the figure below.

Smoothing Contours

The MIN_CURVE_SURF function can be used to smoothly interpolate both regularly and irregularly sampled surfaces before contouring. This function replaces the older SPLINE keyword to CONTOUR, which was inaccurate and is no longer supported. MIN_CURVE_SURF interpolates the entire surface to a relatively fine grid before drawing the contours.

See the documentation of CONTOUR in the IDL Reference Guide for an example using the MIN_CURVE_SURF function. Use IDL's online help facilities (e.g., the "?" command) to see documentation on MIN_CURVE_SURF.

The following short example shows the difference between a smoothed and an unsmoothed contour plot:

data = RANDOMU(seed, 7, 7)	Create a simple dataset.

CONTOUR, data	Plot the unsmoothed data.

CONTOUR, MIN_CURVE_SURF(data)	Plot the smoothed data.

Filling Contours

Set the FILL keyword to produce a filled contour plot. The contours are filled with solid or line-filled polygons. For solid polygons, use the C_COLOR keyword to specify the color index of the polygons for each contour level. For line fills, use C_ORIENTATION, C_SPACING, C_COLOR, C_LINESTYLE, and/or C_THICK to specify attributes for the lines.

If the current device is not a pen plotter, each polygon is erased to the background color before the fill lines are drawn, to avoid superimposing one pattern over another.

The FILL keyword replaces the use of the PATH_FILENAME keyword and POLYFILL procedure from previous versions of IDL. Setting the FILL keyword also closes any open contours before filling.

The following example illustrates various filled contour plot options.

data = RANDOMU(seed, 7, 7)	Create a simple, random dataset for contouring.

CONTOUR, data, NLEVELS=6, /FILL	Create a basic, solid-color, filled CONTOUR plot with 6 evenly-spaced levels.

CONTOUR, data, NLEVELS=6, /NOERASE	Overplot contour outlines.

Instead of solid colors, contours can be filled with lines:

ANGLES = [0, 45, -45]	Create a vector of orientations for the fill lines.

C = [70, 120, 200, 255]	Create a vector of colors to use.

CONTOUR, data, NLEVELS=10, C_ORIENT=ANGLES, C_COLORS=C
Create contours filled with lines.

CONTOUR, data, NLEVELS=10, /NOERASE	Overplot contour outlines.

There are many other controls for filled contour plots. The C_COLORS, C_LINESTYLE, C_SPACING, and C_THICK keywords can also be used to control the type of fill. For a complete description of CONTOUR, see the IDL Reference Guide.

Indicating Direction of Grade

Setting the DOWNHILL keyword creates short, perpendicular tick marks along each contour that point in the "downhill" direction. These marks make the direction of the grade readily apparent. For example:

CONTOUR, data, /DOWNHILL


The SURFACE Procedure

The SURFACE procedure draws "wire mesh" representations of functions of x and y, just as CONTOUR draws their contours. Parameters to SURFACE are similar to CONTOUR. SURFACE accepts a two-dimensional array of z (elevation) values, and optionally x and y parameters indicating the location of each z element.

Note: The grid defined by the x and y parameters must be regular, or nearly regular, or errors in hidden line removal will result. Also, the rotation must project the data z axis so that it is parallel to the drawing surface's y axis or errors in hidden line removal will result.

SURFACE projects the three-dimensional array of points into two dimensions after rotating about the z and then the x axes. Each point is connected to its neighbors by lines. Hidden lines are suppressed. The rotation about the x and z axes can be specified with keywords or a complete three-dimensional transformation matrix can be stored in the field !P.T for use by SURFACE. Details concerning the mechanics of three-dimensional projection and rotation are covered in the next section.

The following IDL code illustrates the most basic call to SURFACE. It produces a two-dimensional Gaussian function, then calls SURFACE to produce the figure below.

Z = SHIFT(DIST(40), 20, 20)	Create a 40 by 40 array in which each element is equal to the Euclidean distance from the center.

Z = EXP(-(Z/10)^2) 	Make Gaussian with a 1/e width of 10.

SURFACE, Z	Call SURFACE to display plot.

In the example above, the DIST function creates an (n, n) array in which each element is set to its Euclidean distance from the origin.

SURFACE Keyword Parameters

In addition to the standard graphics keyword parameters, the following are unique to, or have particular relevance to, SURFACE:

AX

Set this keyword to the angle of rotation of the surface, in degrees towards the viewer, about the x-axis. Default value is +30 degrees. This keyword is effective only if the keyword T3D is not set.

AZ

Set this keyword to the angle of rotation of the surface, in degrees counterclockwise when looking down the z-axis towards the origin. Default value is +30 degrees. This keyword is effective only if the keyword T3D is not set.

BOTTOM

This keyword specifies the color index used to draw the underside of the surface. If this keyword is not present, the bottom is drawn with same color index as the top.

HORIZONTAL

Set this keyword to draw only horizontal lines across the plot perpendicular to the line of sight. The default is to draw lines both across the plot and from front to back.

LOWER_ONLY

Set this keyword to draw only the lower surface.

SAVE

Set this keyword to save the three-dimensional to two-dimensional transformation used by SURFACE and specified by the AX and AZ keywords in the (4, 4) array !P.T. Use this keyword to combine the output of SURFACE with other graphic output. See the next section for details.

SKIRT

A skirt around the array at the given z value is drawn if this keyword parameter is present. The z value is expressed in data units.

UPPER_ONLY

Set this keyword to inhibit drawing the lower side of the surface.

ZAXIS

This keyword specifies the placement of the z-axis. The default is at the upper-left corner of the axis box. Setting ZAXIS to -1 inhibits drawing the z-axis; otherwise, the position of the z-axis is determined as follows: 1 = lower right, 2 = lower left, 3 = upper left, and 4 = upper right.

Example

The figure below illustrates the application of the SURFACE procedure to the Maroon Bells data used in the first section of this chapter. This figure shows the re-binned data from the previous section. As with CONTOUR, there can be too many data values obscuring the surface with too much detail and requiring more computation and drawing time. The left illustration in the figure was produced by the following statements:

C = REBIN(A > 2650, 360/5, 460/5)

SURFACE, C, X, Y, SKIRT = 2650

The first statement resizes the original data into a 72 x 92 array, as shown in the previous section, setting all data values which are less than 2650 (the lowest elevation we wish to show) to 2650.

The right illustration in the figure shows the Maroon Peaks area looking from the back row to the front row (north to the south), AZ = 210, and from a slightly steeper azimuth AX = 45. Also, only the horizontal lines are drawn because the /HORIZONTAL keyword is present in the following call:

SURFACE, C, X, Y, SKIRT = 2650, /HORIZ, AZ = 210, AX = 45

Because the axes were rotated 210 degrees about the original z-axis, the annotation is reversed and the x-axis is behind and obscured by the surface. This undesirable effect can be eliminated by reversing the data array C about its y-axis. Also, the y vector of element locations must be reversed, and the YRANGE keyword used to reverse the y-axis ordering.

SURFACE, REVERSE(C, 2), X, REVERSE(Y), SKIRT = 2650, $

  /HORIZ, AX = 45, YRANGE = [MAX(Y), MIN(Y)]
As above, but reverse the data rather than the axes.


Three-Dimensional Graphics

Points in xyz space are expressed by vectors of homogeneous coordinates. These vectors are translated, rotated, scaled, and projected onto the two-dimensional drawing surface by multiplying them by transformation matrices. The geometrical transformations used by IDL, and many other graphics packages, are taken from Chapters 7 and 8 of Foley and Van Dam (1982). The reader is urged to consult this book for a detailed description of homogeneous coordinates and transformation matrices since this section presents only an overview.

Homogeneous Coordinates

A point in homogeneous coordinates is represented as a four-element column vector of three coordinates and a scale factor w   ≠ 0. For example:

P(wx, wy, wz, w) ≡ P(x/w, y/w, z/w, 1) ≡ (x, y, z)

One advantage of this approach is that translation, which normally must be expressed as an addition, can be represented as a matrix multiplication. Another advantage is that homogeneous coordinate representations simplify perspective transformations. The notion of rows and columns used by IDL is opposite that of Foley and Van Dam (1982). In IDL, the column subscript is first, while in Foley and Van Dam (1982) the row subscript is first. This changes all row vectors to column vectors and transposes matrices.

Right-Handed Coordinate System

The coordinate system is right-handed so that when looking from a positive axis to the origin, a positive rotation is counterclockwise. As usual, the x-axis runs across the display, the y-axis is vertical, and the positive z-axis extends out from the display to the viewer. For example, a 90-degree positive rotation about the z-axis transforms the x-axis to the y-axis.

Transformation Matrices

Note: For most applications, it is not necessary to create, manipulate, or to even understand transformation matrices. The procedure T3D, explained below, implements most of the common transformations.

Transformation matrices, which post-multiply a point vector to produce a new point vector, must be (4, 4). A series of transformation matrices can be concatenated into a single matrix by multiplication. If A1, A2, and A3 are transformation matrices to be applied in order, and the matrix  A is the product of the three matrices, the following applies.

((P  • A1) • A2) • A3 ≡ P • ((A1  • A2) • A3) = P • A

IDL stores the concatenated transformation matrix in the system variable field !P.T.

Each of the operations of translation, scaling, rotation, and shearing can be represented by a transformation matrix.

Translation

The transformation matrix to translate a point by (Dx, Dy, Dz) is shown below.

Scaling

Scaling by factors of Sx, Sy, and Sz about the x, y, and z axes respectively, is represented by the matrix below.

Rotation

Rotation about the x, y, and z axes is represented respectively by the following three matrices:

T3D Procedure

The IDL procedure T3D creates and accumulates transformation matrices, storing them in the system variable field !P.T. The procedure can be used to create a transformation matrix composed of any combination of translation, scaling, rotation, perspective projection, oblique projection, and axis exchange. Transformations are applied in the order of the keyword descriptions below:

RESET

Set this keyword to reset the transformation matrix to the identity matrix to begin a new accumulation of transformations. If this keyword is not present, the current transformation matrix !P.T is post-multiplied by the new transformation. The final transformation matrix is always stored back in !P.T.

TRANSLATE

This keyword argument accepts a 3-element vector. The viewpoint is translated by the three-element vector [Tx, Ty, Tz].

SCALE

This keyword argument accepts a 3-element vector. The viewing area is scaled by factor [Sx, Sy, Sz].

ROTATE

This keyword accepts a 3-element vector. The viewing area is rotated about each axis by the amount [θx, θy, θz], in degrees.

PERSPECTIVE

A scalar (p) indicating the z distance of the center of the projection in the negative direction. Objects are projected into the xy plane, at z = 0, and the "eye" is at point (0, 0, -p).

OBLIQUE

A two-element vector, [d, α], specifying the parameters for an oblique projection. Points are projected onto the xy-plane at z = 0 as follows:

x0 = x + z(d cos α)

y0 = y + z(d sin α)

An oblique projection is a parallel projection in which the normal to the projection plane is the z-axis, and the unit vector (0, 0, 1) is projected to (d cos α, d sin α) where  α is expressed in degrees.

XYEXCH

If set, exchanges the x and y axes.

XZEXCH

If set, exchanges the x and z axes.

YZEXCH

If set, exchanges the y and z axes.

Example: The Transformation Created by SURFACE

The SURFACE procedure creates a transformation matrix from its keyword parameters AX and AZ as follows:

Starting with the identity transformation, SURFACE translates the center of the normalized cube to the origin.

SURFACE rotates 90 degrees about the x-axis to make the +z-axis of the data the +y-axis of the display. The +y data axis extends from the front of the display to the rear.

SURFACE rotates AZ degrees about the y-axis. This rotates the result counter-clockwise, as seen from above the page.

SURFACE rotates AX degrees about the x-axis, tilting the data towards the viewer.

The procedure then removes the translation applied in the first step and scales the data so that the data are still contained within the normal coordinate unit cube after transformation.

These transformations can be created using T3D as shown below. The SCALE3 procedure, documented in the IDL Reference Guide, mimics the transformation matrix created by SURFACE using the following method:

T3D, /RESET, TRANSLATE = [-.5, -.5, -.5]
Translate to move center of cube to origin.

T3D, ROTATE = [-90, AZ, 0]	Rotate 90 degrees about x-axis, so +z-axis is now +y. Then rotate AZ degrees about y-axis.

T3D, ROTATE = [AX, 0, 0]	Rotate AX about x-axis.

T3D, TRANSLATE = [0.5, 0.5, 0.5]	Restore origin.

The SCALE3 procedure, documented in the IDL Reference Guide, scales the unit cube by a fixed factor, 1/√3 to ensure that the corners of the rotated cube fit within the drawing area. If requested, it also will set the data scaling. Animations involving rotations or the SURFACE procedure should have their scaling and viewing transformation set by SCALE3 rather than the obsolete SURFR procedure, so that the scaling does not vary between frames.

Three-Dimensional Coordinate Conversion

To convert from a three-dimensional coordinate to a two-dimensional coordinate, IDL follows these steps:

•	Data coordinates are converted to three-dimensional normalized coordinates. As described in Chapter 14, to convert the x coordinate from data to normalized coordinates, use the formula Nx = X0 + X1Dx. The same process is used to convert the y and z coordinates using !Y.S and !Z.S.

•	The three-dimensional normalized coordinate, P = (Nx, Ny, Nz), whose homogeneous representation is (Nx, Ny, Nz, 1), is multiplied by the concatenated transformation matrix !P.T:

P′ = P • !P.T

•	The vector P′ is scaled by dividing by w, and the normalized two-dimensional coordinates are extracted:

N′x = P′x/P′w and N′y =  P′y/P ′w

•	The normalized xy coordinate is converted to device coordinates as described in Chapter 12.

The CONVERT_COORD function performs the above process when converting to and from coordinate systems when the T3D keyword is specified. For example, if a three-dimensional coordinate system is established, then the device coordinates of the data point (0, 1, 2) can be computed as follows:

D = CONVERT_COORD(0, 1, 2, /TO_DEVICE, /T3D, /DATA)

On completion, the three-element vector D will contain the desired device coordinates. The process of converting from three-dimensional to two-dimensional coordinates also can be written as an IDL function:

FUNCTION CVT_TO_2D, X, Y, Z	Accept a three-dimensional data coordinate, return a two-element vector containing the coordinate transformed to two-dimensional normalized coordinates using the current transformation matrix.

P = [!X.S(0) + !X.S(1) * X, !Y.S(0) + !Y.S(1) * Y, $

  !Z.S(0) + !Z.S(1) * Z, 1]	Make a homogeneous vector of normalized three-dimensional coordinates.

P = P # !P.T	Transform by !P.T.

RETURN, [P(0) / P(3), P(1) / P(3)]	Return the scaled result as a two-element, two-dimensional, xy vector.

END

Establishing a Three-Dimensional Coordinate System

Usually, scaling parameters for coordinate conversion are set up by the higher-level procedures. To set up your own three-dimensional coordinate system with a given transformation matrix and x, y, z data range, follow these steps:

•	Establish the scaling from your data coordinates to normalized coordinates—the (0,1) cube. Assuming your data are contained in the range (Xmin, Ymin, Zmin) to (Xmax, Ymax, Zmax), set the data scaling system variables as follows:

!x.s = [ -Xmin, 1 ] / (Xmax - Xmin)

!y.s = [ -Ymin, 1 ] / (Ymax - Ymin)

!z.s = [ -Zmin, 1 ] / (Zmax - Zmin)

•	Establish the transformation matrix that determines the view of the unit cube. This can be done by either calling T3D, as explained above or by directly manipulating !P.T yourself. If you wish to simply mimic the rotations provided by the SURFACE procedure, call the SCALE3 procedure (which can also be used to perform the previous step).

Example

This example draws four views of a simple house. The procedure house defines the coordinates of the front and back faces of the house. The data-to-normal coordinate scaling is set, as shown above, to a volume about 25 percent larger than that enclosing the house. The PLOTS procedure is called to draw lines describing and connecting the front and back faces. XYOUTS is called to label the front and back faces.

The main program contains four sequences of calls to T3D to establish the coordinate transformation, followed by a call to HOUSE.

PRO HOUSE	Define a procedure to draw a house.

house_x = [0, 16, 16, 8, 0, 0, 16, 16, 8, 0]
X coordinates of 10 vertices. First 5 are front face, second 5 are back face. The range is 0 to 16.

house_y = [0, 0, 10, 16, 10, 0, 0, 10, 16, 10]
The corresponding y values range from 0 to 16.

house_z = [54, 54, 54, 54, 54, 30, 30, 30, 30, 30]
The z values range from 30 to 54.

min_x = -4 & max_x = 20.	Define max and min xy values to scale. Slightly larger than data range.

!X.S = [-(-4), 1.]/(20 - (-4))	Set x data scale to range from −4 to 20.

!Y.S = !X.S	Same for y.

!Z.S = [-10, 1.]/(70 - 10)	The z range is from 10 to 70.

face = [INDGEN(5), 0]	Indices of front face.

PLOTS, house_x(face), house_y(face), house_z(face), /T3D, /DATA
Draw front face.

PLOTS, house_x(face + 5), house_y(face + 5), house_z(face + 5), $

  /T3D, /DATA	Draw back face.

FOR I = 0, 4 DO PLOTS, [house_x(i), house_x(i + 5)], $

  [house_y(i), house_y(i + 5)], [house_z(i), house_z(i + 5)], $

  /T3D, /DATA	Connecting lines from front to back.

XYOUTS, house_x(3), house_y(3), Z = house_z(3), 'Front', $

  /T3D, /DATA, SIZE = 2	Annotate front peak.

XYOUTS, house_x(8), house_y(8), Z = house_z(8), 'Back', $

  /T3D, /DATA, SIZE = 2	Annotate back.

END	End of house procedure.

The HOUSE procedure could be called from the IDL command line to produce a number of different plots. For example:

T3D, /RESET & HOUSE	Set up no rotation, scale, and draw house.

H = [0.5, 0.5, 0.5]	Create a handy constant.

T3D, /RESET, TRANS = -H, ROT = [30, 30, 0] & T3D, TR = H & HOUSE
Straight projection after rotating 30 degrees about x and y axes.

T3D, /RESET, TRANS = -H, ROT=[0, 0, 0], OBLIQUE=[.5, -45] & $

  T3D, TR = H & HOUSE	No rotation, oblique projection, z factor = 0.5, angle = 45.

T3D, /RESET, TR=-H, ROT=[-6, 6, 0], PERS=4 & T3D, TR=H & HOUSE
Rotate 6 degrees about x and y, then apply perspective.

The figure below illustrates the different transformations. The four rotations are:

•	Upper left: no rotation, plain projection

•	Upper right: oblique projection, factor = 0.5, angle = −45

•	Bottom left: rotation of 30 degrees about both the x and y axes, plain projection

•	Bottom right: rotation of -6 degrees about the x axis and +6 degrees about the y axis, and perspective projection with the eye at 4.

Rotating the House

A common procedure for visualizing three-dimensional data is to animate the data by rotating it about one or more axes. To make an animation of the house in the preceding example with the XINTERANIMATE procedure, use the following example.

sizx = 500

sizy = 500

nframes = 16

XINTERANIMATE, SET=[sizx, sizy, nframes]
Initialize animation: set frame size and number of frames.

FOR i = 0, nframes - 1 DO BEGIN $

  SCALE3, AX = 75, AZ = i * 360. / nframes & $
Rotate about the z-axis.

  ERASE & $

  HOUSE & $	Draw the house.

  SCALE3, AX = 75, AZ = i * 360. / nframes & $

  XINTERANIMATE, FRAME=i, WINDOW=!D.WINDOW & $
Save the window.

ENDFOR

XANIMATE	Show the animation.

In the above example, SCALE3 rather than SCALE3D is used to maintain the same scaling in all rotations.


Three-Dimensional Transformations with Two-Dimensional Procedures

The CONTOUR and PLOT procedures output their results using the three-dimensional coordinate transformation contained in !P.T when the keyword T3D is specified. Note that !P.T must contain a valid transformation matrix prior to using the T3D keyword.

PLOT and its variants output graphs in the xy-plane at the normal coordinate z value given by the keyword ZVALUE. If this keyword is not specified, the plot is drawn at the bottom of the unit cube at z = 0.

CONTOUR draws its axes at z = 0 and its contours at their z data value if ZVALUE is not specified. If ZVALUE is present, CONTOUR draws both the axes and contours in the xy-plane at the given z value.

Combining CONTOUR and SURFACE

It is easy to combine the results of SURFACE with the other IDL graphics procedures. The keyword parameter SAVE causes SURFACE to save the graphic transformation it used in !P.T. Then, when either CONTOUR or PLOT is called with the keyword parameter T3D, its output is transformed with the same projection. For example, the figure below illustrates combining SURFACE with CONTOUR. In essence, this is a combination of figures from 2 previous sections. Using the same variables as in the first two sections of this chapter, the figure was produced with the following statements:

SURFACE, C, X, Y, SKIRT=2650, /SAVE	Make the mesh.

CONTOUR, B, X, Y, /T3D, /NOERASE, TITLE = 'Contour Plot', $

MAX_VAL = 5000., ZVALUE = 1.0, /NOCLIP, $

LEVELS = 2750. + FINDGEN(6) * 250 	Specify T3D to align with SURFACE, at ZVALUE of 1.0. Suppress clipping as the plot is outside the normal plot window.

More Complicated Transformations

The figure below illustrates the application of three-dimensional transforms to the output of CONTOUR and PLOT. Using the two-dimensional Gaussian array z defined in "The SURFACE Procedure" on page 15-12, it draws a three-dimensional contour plot with the contours stacked above the axes in the z direction. It then plots the sum of the columns, also a Gaussian, in the xz-plane, and the sum of the rows in the yz plane. It was constructed as follows:

•	First, the SCALE3 procedure is called to establish the default three- to two-dimensional transformation used by SURFACE, as explained above. The default rotations are 30 degrees about both the x and z axes.

•	Next, a vector, POS, defining the cube containing the plot window is defined in normalized coordinates. The cube extends from 0.1 to 1.0 in the x and y directions and from 0 to 1 in the z direction. Each call to CONTOUR and PLOT must explicitly specify this window to align the plots. This is necessary because the default margins around the plot window are different in each direction.

•	CONTOUR is called to draw the stacked contours with the axes at z=0. Clipping is disabled to allow drawing outside the default plot window, which is only two-dimensional.

•	The procedure T3D is called to exchange the y and z axes. The original xyz coordinate system is now xzy.

•	PLOT is called to draw the column sums which appear in front of the contour plot. The expression Z#REPLICATE(1., Ny) creates a row vector containing the sum of each row in the two-dimensional array z. The NOERASE and NOCLIP keywords are specified to prevent erasure and clipping. This plot appears in the xz-plane because of the previous axis exchange.

•	T3D is called again to exchange the x and z axes. This makes the original xyz coordinate system, which was converted to xzy, now correspond to yzx.

•	PLOT is called to produce the column sums in the yz-plane in the same manner as the first plot. The original x-axis is drawn in the y-plane, and the y-axis is in the z-plane. One unavoidable side effect of this method is that the annotation of this plot is backwards. If the plot is transformed so the letters read correctly, the x-axis of the plot would be reversed in relation to the y-axis of the contour plot.

The IDL code used to draw the figure is as follows:

SCALE3	Set up !P.T with default SURFACE transformation.

POS=[.1, .1, 1, 1, 0, 1]	Define the three-dimensional plot window: x = 0.1 to 1, Y=0.1 to 1, and z = 0 to 1.

CONTOUR, Z, /T3D, NLEVELS=10, /NOCLIP, POSIT=POS, CHARSIZE=2	Make the stacked contours. Use 10 contour levels.

T3D, /YZEXCH	Swap y and z axes. The original xyz system is now xzy.

PLOT, Z#REPLICATE(1., NY), /NOERASE, /NOCLIP, /T3D, $

   TITLE='COLUMN SUMS', POSITION = POS, CHARSIZE = 2
Plot the column sums in front of the contour plot.

T3D, /XZEXCH	Swap x and z—original xyz is now yzx

PLOT, REPLICATE(1., NX)#Z, /NOERASE, /T3D, /NOCLIP, $

  TITLE = 'ROW SUMS', POSITION = POS, CHARSIZE = 2
Plot the row sums along the right side of the contour plot.

Combining Images with Three-Dimensional Graphics

Images are combined with three-dimensional graphics, as shown in the figure below, using the transformation techniques described above. The rectangular image must be transformed so that it fits underneath the mesh drawn by SURFACE. The general approach is as follows:

•	Use SURFACE to establish the general scaling and geometrical transformation. Draw no data, as the graphics made by SURFACE will be over-written by the transformed image.

•	For each of the four corners of the image, translate the data coordinate, which is simply the subscript of the corner, into a device coordinate. The data coordinates of the four corners of an (m, n) image are (0, 0), (m-1, 0), (0, n-1), and (m-1, n-1). Call this data coordinate system (x, y). Using a procedure or function similar to CVT_TO_2D, described on page 15-21, convert to device coordinates, which in this discussion are called (U, V).

•	The image is transformed from the original xy coordinates to a new image in UV coordinates using the POLY_2D function. POLY_2D accepts an input image and the coefficients of a polynomial in UV giving the xy coordinates in the original image. The equations for x and y are below.

X = S0,0 + S1,0U +S1,0V +S1,1UV

Y = T0,0 + T1,0U + T1,0V + T1,1UV

We solve for the four unknown S coefficients using the four equations relating the x corner coordinates to their U coordinates. The T coefficients are similarly found using the y and V coordinates. This can be done using matrix operators and inversion or more simply, with the procedure POLY_WARP.

•	The new image is a rectangle that encloses the quadrilateral described by the UV coordinates. Its size is specified in the formula below:

(MAX(U) - MIN(U) +2, MAX(V ) - MIN(V) +1)

•	POLY_2D is called to form the new image which is displayed at device coordinate (MIN(U), MIN(V)).

•	SURFACE is called once again to display the mesh surface over the image.

•	Finally, CONTOUR is called with ZVALUE set to 1.0, placing the contour above both the image and the surface.

The SHOW3 procedure performs these operations. It should be examined for details of how images and graphics can be combined.


Shaded Surfaces - The SHADE_SURF Procedure
Shaded Surfaces—The SHADE_SURF Procedure

The SHADE_SURF procedure creates a shaded representation of a surface made from regularly gridded elevation data. The shading information can be supplied as a parameter or computed using a light-source model. Displays are easily constructed depicting the surface elevation of a variable shaded as a function of itself or another variable. This procedure is similar to the SURFACE routine, but it renders the visible surface as a shaded image rather than a mesh.

Parameters are identical to those of the SURFACE procedure, described in "SURFACE Keyword Parameters" on page 15-13, with the addition of two optional keyword parameters:

SHADES

Specifies an array of the same dimensions as the z parameter which contains the shading color indices. This array should be scaled into the range of color indices, normally 0 to the maximum color index, !D.TABLE_SIZE.

IMAGE

Specifies the name of a variable into which the image created by SHADE_SURF is placed. Normally, the image is displayed on the currently selected graphics device and then discarded.

Shading Method

The shading applied to each polygon, defined by its four surrounding elevations, can be either constant over the entire cell or interpolated. Constant shading takes less time because only one shading value needs to be computed for the entire polygon. Interpolated shading gives smoother results. The Gouraud method of interpolation is used: the shade values are computed at each elevation point, coinciding with each polygon vertex. The shading is then interpolated along each edge, finally, between edges along each vertical scan line.

Light-source shading is computed using a combination of depth cueing, ambient light, and diffuse reflection, adapted from Foley and Van Dam (1982, Chapter 19):

I = Ia + dIp(L • N)

where

Ia	Term due to ambient light. All visible objects have at least this intensity, which is approximately 20 percent of the maximum intensity.

Ip(L • N)	Term due to diffuse reflection. The reflected light is proportional to the cosine of the angle between the surface normal vector N and the vector pointing to the light source, L. Ip is approximately 0.9.

d	Term for depth cueing, causing surfaces further away from the observer to appear dimmer. The normalized depth is d = (z+2)/3, ranging from zero for the most distant point to one for the closest.

Shading Parameters

Parameters affecting the method of shading interpolation, light source direction, and rejection of hidden faces are set with the SET_SHADING procedure, described in the IDL Reference Guide. Defaults are Gouraud interpolation, light-source direction [0, 0, 1], and rejection of hidden faces enabled.

See the description of SET_SHADING in the IDL Reference Guide for a more complete description of the parameters. Note that the REJECT keyword has no effect on the output of SHADE_SURF—it is used only with solids.

Examples Using SHADE_SURF

The figure below illustrates the application of SHADE_SURF, with light-source shading, to the two dimensional Gaussian, drawn as a mesh in a previous topic. This figure was produced by the following statement.

SHADE_SURF, Z

The right half of the figure shows the use of an array of shades, which in this case is simply the surface elevation scaled into the range of bytes. The output of SURFACE is superimposed over the shaded image with the statements below.

SHADE_SURF, Z, SHADES=BYTSCL(Z, TOP = !D.TABLE_SIZE)
Show Gaussian with shades created by scaling elevation into the range of bytes.

SURFACE, Z, XST = 4, YST = 4, ZST = 4, /NOERASE
Draw the mesh surface over the shaded figure. Suppress the axes.

The figure below shows the Maroon Bells data as a light-source shaded surface. It was produced by the following statement:

SHADE_SURF, A, X, Y, AZ=210, AX=45, XST=4, YST=4, ZST=4

The AX and AZ keywords specify the orientation. The axes are suppressed by the axis-style keyword parameters; as in this orientation, the axes are behind the surface.


Volume Visualization - The SHADE_VOLUME Procedure
Volume Visualization—The SHADE_VOLUME Procedure

A common problem in data visualization is how to display a constant density surface (also known as an isosurface), given a three-dimensional grid of density measurements. In medical imaging, stacking a series of two-dimensional images created by computed tomography or magnetic resonance creates a grid of density measurements that can be contoured to display the surfaces of anatomical structures. Atmospheric scientists create three-dimensional grids of water densities that can be contoured at the proper density level to show the surface of clouds. It is relatively easy to produce these surfaces using the SHADE_VOLUME procedure in conjunction with the POLYSHADE function.

SHADE_VOLUME accepts a three-dimensional grid of densities and a contour level. It outputs the set of polygons that describe the surface of the contour. The polygons are described by a (3, n) array of vertices and a polygon list array that contains the vertices belonging to each polygon. Given a volume array with dimensions of (D0, D1, D2), the resulting vertex coordinates range between 0 and D0 - 1 in x, 0 and D1 - 1 in y, and 0 and D2 - 1 in z. Keyword parameters to SHADE_VOLUME include the following:

LOW

A flag that indicates which side of the contour surface is to be viewed: 1 for the high side and 0 for the low (the default). If the contour to be viewed encloses high data values, set the LOW keyword parameter to 1.

SHADES

An array of shading values for each volume element (voxel). On completion, SHADE_VOLUME replaces this array with the interpolated shading for each vertex of the surface.

These polygons are then fed to the POLYSHADE function to produce the shaded surface representation. It must be noted that the maximum volume size and polygon complexity are limited by the amount of available memory, as these routines store the density measurements, vertex list, and polygon list in memory.

For example, the figure below produced by the following IDL code, shows the three-dimensional contour surface of the precipitating region of a thunderstorm simulated by a three-dimensional cloud model. The data were provided by the National Center for Atmospheric Research. The original data are contained in an array called clouds, a (55, 55, 32) element floating-point array. Each array element contains the amount of water contained in the corresponding volume of air.

SHADE_VOLUME, clouds, 0.1, v, p, /LOW
Create the contour surface polygons (v and p) at density 0.1, from clouds. Show the low side.

s = SIZE(clouds)	Obtain the dimensions of the volume. Variables S(1), S(2), and S(3) now contain the number of columns, rows, and slices in the volume.

SCALE3, XRANGE=[0,S(1)], YRANGE=[0,S(2)], $

  ZRANGE=[0,S(3)], AX=0, AZ=45	Use SCALE3 to establish the three-dimensional transformation matrix. Rotate 45 degrees about the z-axis.

TV, POLYSHADE(v, p, /T3D)	Render and display the polygons.

The shaded volume can be viewed from different rotations by changing the three-dimensional transformation matrix, !P.T, and calling POLYSHADE for each view. The following code will display 20 views of the volume, each separated by 18 degrees.

nframes = 20 	Define number of views.

FOR i = 0, nframes - 1 DO BEGIN

T3D, TR=[-.5, -.5, -.5], ROT=[0, 360./NFRAMES, 0]
Translate the center of the (0, 1) unit cube to (0,0) and rotate about the x-axis.

T3D, TR = [.5, .5, .5]	Translate the center back to (0.5, 0.5, 0.5).

TV, POLYSHADE(v, p, /T3D)	Show the surface.

ENDFOR

The animation rate of the above loop will not be very fast, especially with a larger number of polygons. Each image could be saved for rapid replay by writing it to a disk file. Given enough memory and/or display resources, the XINTERANIMATE procedure could be used to animate the views.

The SLICER Tool

IDL also includes an interactive volume visualization tool called SLICER. This tool can be used to view isosurfaces and slices of volume data. A short tutorial on using the SLICER can be found in IDL Basics. See "SLICER" on page 1-816 of the IDL Reference Guide.

References

Foley, J.D., and A. Van Dam (1982), Fundamentals of Interactive Computer Graphics, Addison-Wesley Publishing Co.

Jump forward to Image Display Routines

Jump backward to Plotting


Image Display Routines
16	Image Display Routines

Chapter Overview

IDL provides a powerful environment for image processing and display. The routines described in this chapter provide the interface between IDL and the image display system. This chapter describes these image display and control routines and provides examples of their use.


Topics in Image Display Routines Chapter
Image Display Routines

This chapter provides an overview of IDL's image processing and display routines.

Topics Covered:

Images

Imaging Routines

Image Display

Reading from the Display Device

Color Tables

True-Color Displays

Controlling the Device Cursor

Jump forward to Files and Input/Output

Jump backward to Plotting Multi-Dimensional Arrays


Images

An image consists of a two-dimensional array of pixels. The value of each pixel represents the intensity and/or color of that position in the scene. Images of this form are known as sampled or raster images, because they consist of a discrete grid of samples. Such images come from many different sources and are a common form of representing scientific and medical data.


Imaging Routines

The following IDL routines are used for the display and manipulation of images:

TVCRS

This procedure manipulates the image device cursor. TVCRS allows the cursor to be enabled and disabled, as well as allowing it to be positioned.

TV

This procedure displays images on the image display.

TVSCL

This procedure scales the intensity values of the image into the range of the display device, then displays the result on the image display.

TVLCT

This procedure loads a new color table into the display device.

TVRD

This function reads image pixels back from the display device.

In addition, most routines used for plotting and graphics can be used with the display of images as well. These routines are described in the chapters on plotting. For example, to overlay an image and its contour plot, the output of the CONTOUR procedure is combined with that of TV, as described in Chapter 15. The CURSOR routine, described on page 14-27, reads the position of the interactive pointing device and may also be used to determine the location of image pixels.


Image Display

The TV and TVSCL procedures display images on the screen. These procedures use the same arguments and keywords and differ only in that TVSCL scales the image into the intensity range of the display device, while TV displays the image directly. They have the form:

TV, IMAGE[, POSITION]

TV, IMAGE[, X, Y[, CHANNEL]]

TVSCL, IMAGE[, POSITION]

TVSCL, IMAGE[, X, Y[, CHANNEL]]

where

IMAGE

A vector or two-dimensional matrix to be displayed as an image. If not already of byte type, it is converted prior to use.

X, Y

If present, these arguments specify the lower-left coordinate of the displayed image.

POSITION

Position number of the image. Image positions are discussed in detail below.

CHANNEL

Some image display devices are capable of storing more than a single image or can combine three single color images to form a true color image. CHANNEL specifies the memory channel to be written. It is assumed to be zero if not specified. This parameter is ignored on display systems that have only one memory channel.

If no optional parameters are present, IMAGE is output to the display with its lower-left corner at coordinate (0, 0). The optional parameters can be used to specify the screen position of the image in a variety of ways.

Image Orientation

The screen coordinate system for image displays puts the origin, (0, 0), at the lower-left corner of the device. The upper-right corner has the coordinate (xsize - 1, ysize - 1), where xsize and ysize are the dimensions of the visible area of the display. The descriptions of the image display routines that follow assume a display size of 512 x 512, although other sizes may be used.

The system variable !ORDER controls the order in which the image is written to the screen. Images are normally output with the first row at the bottom, i.e., in bottom-to-top order, unless !ORDER is 1, in which case images are written on the screen from top to bottom. The ORDER keyword also can be specified with TV and TVSCL. It works in the same manner as !ORDER except that its effect only lasts for the duration of the single call—the default reverts to that specified by !ORDER.

An image can be displayed with any of the eight possible combinations of axis reversal and transposition by combining the display procedures with the ROTATE function.

Image Position

Image positions run from the left of the screen to the right and from the top of the screen to the bottom. If a position number is used instead of x and y, the position of the image is calculated from the dimensions of the image (using integer arithmetic) as follows:

xsize , ysize = size of display or window

xdim, ydim = dimensions of array

Nx = xsize/xdim = images across screen

x = xdimPositionmoduloNx = startingx

y = ysize - ydim (1 + Position/Nx) = startingy

For example, when displaying 128 x 128 images on a 512 x 512 display, the position numbers run from 0 to 15 as follows:

 0    1    2    3

 4    5    6    7

 8    9   10   11

12   13   14   15

Image Size

Most image devices have a fixed number of display pixels. Common sizes are 512 x 512, 1280 x 1024, and 900 x 1152 (for Sun workstations). Such pixels have a fixed size which cannot be changed. For such devices, the area written on the screen is the same size as the dimensions of the image array. One-dimensional vectors are considered row vectors. The x and y parameters specify the coordinates of the lower-left corner of the area written on the display.

There are some devices, however, that have the ability to place an image with any number of pixels into an area of arbitrary size. PostScript devices are a notable example. Such devices are said to have scalable pixels, because there is no direct connection between the number of pixels in the image and the physical space it occupies in the displayed image. When the current image device has scalable pixels, IDL sets the first bit of !D.FLAGS. The following IDL statement can be used to determine if the current device has scalable pixels:

SP = !D.FLAGS AND 1

SP will be nonzero if the device has scalable pixels. When displaying an image on a device with scalable pixels, the default uses the entire display surface for the image. The XSIZE and YSIZE keywords can be used to override this default and specify the width and height that should be used.

The XSIZE and YSIZE keywords also should be used when positioning images with the POSITION argument to TV or TVSCL. POSITION normally uses the size of the image in pixels to determine the placement of the image, but this is not possible for devices with scalable pixels. Instead, the default for such devices is to assume a single position that fills the entire available display surface. However, if XSIZE and YSIZE are specified, POSITION will use them to determine image placement.

Examples

TV, REPLICATE(100B, 512, 512)	Set all display memory to 100.

ABC = BYTARR(50, 100)	Define a 50 column by 100 row array.

TV, ABC, 300, 400	Display array ABC starting at location x = 300, y=400. Display pixels in columns 300 to 349, and rows 400 to 499 are zeroed.

TV, ABC/2, 12	Display image divided by 2 at position number 12.

TV, A, 256, 256, 2	Output image to memory channel 2, lower-left corner at (256, 256).

AA = ASSOC(1, BYTARR(64, 64))	Assume file one contains a sequence of 64 x 64 byte arrays.

FOR I = 0, 63 DO TV, AA(I), I	Display 64 images from file, from left to right and top to bottom, filling a 512 x 512 area.

Image Scaling

An image can be contrast enhanced so any subrange of pixel values are scaled to fill the entire range of displayed brightnesses using a variety of methods.

For example, if the image A contains an object superimposed on a varying background and the pixel values in the object range from a value of S to the brightest value in the image the IDL statement:

TVSCL, A > S

will use the entire range of display brightnesses to display the object. The expression A>S results in an image in which each pixel in A less than S is set to S. S becomes the new minimum intensity. The TVSCL procedure scales the new image into the available number of color-table entries before loading it into the display. Again, the image A is not changed.

Another method that is more efficient, although slightly obscure, is to use the BYTSCL function to scale the array as follows:

TV, BYTSCL(A, MIN = S, TOP = !D.TABLE_SIZE)

This method is more efficient because the value S is known and avoids scanning the array for the minimum and maximum values. Also, one less array operation is required.

If the object in A has values from 2.6 to 9.4, the statements

TVSCL, A > 2.6 < 9.4	Slow method.

TV, BYTSCL(A, MIN=2.6, MAX=9.4, TOP = !D.TABLE_SIZE)
Faster method.

will truncate the image so 2.6 is the new minimum and 9.4 is the new maximum before scaling and display.

Some examples of using the TVSCL function follow.

TVSCL, SQRT(A)	Display square root of image.

TVSCL, A - SMOOTH(A, 3)	Display unsharp masked image.

TVSCL, A + B, 12	Display scaled sum at position number 12.


Reading from the Display Device

The TVRD function reads the contents of the display device memory back into an IDL variable. One use for this capability is to build up a complex display using many IDL statements, and then read the resulting image back as a single unit for storage in a file.

The TVRD function returns the contents of the specified rectangular portion of the display subsystem's memory. The coordinate (x0, y0) is the starting coordinate of the data to be read, and Nx, Ny is the size of the rectangle in columns and rows. This results in a byte array of dimensions Nx x Ny.

A Note on Reading Data from Windows

On some systems, when backing store is provided by the window system (RETAIN=1), reading data from a window using TVRD( ) may cause unexpected results. For example, data may be improperly read from the window even when the image displayed on screen is correct. Having IDL provide the backing store (RETAIN=2) ensures that the window contents will be read properly.

The TVRD function has the form:

TVRD([X0, Y0, NX, NY[, CHANNEL]])

where

X0

Starting column of data to read.

Y0

Starting row of data to read.

NX

Number of columns to read.

NY

Number of rows to read.

CHANNEL

Memory channel to be read. It is assumed to be zero if not specified. This parameter is ignored on display systems that only have one memory channel.

If the system variable !ORDER is set to zero, then data are read from the bottom up; otherwise, data are read in the top-down direction.

Example Using TVRD

The following statement inverts the 100 x 100 area of the display starting at (200, 300):

TV, NOT TVRD(200, 300, 100, 100)	Reverse area.

Ability to Read from Display

Not all image devices are able to support reading pixels back from device memory. If the current device has this ability, IDL sets the eighth bit of !D.FLAGS. The following IDL statement can be used to determine if the current device allows reading from display memory:

TEST = !D.FLAGS AND 128

TEST will be nonzero if the device allows such operations.


Color Tables

There are numerous systems for the measuring and specification of color. Most systems are three-dimensional in nature. For a complete discussion of color systems, refer to Foley and Van Dam (1982, Chapter 17). Parts of this discussion are taken from that chapter.

Most devices capable of displaying color use the RGB (red, green, and blue) color system. Other common color systems include the Munsell, HSV (hue, saturation, and value), HLS (hue, lightness, and saturation), and CMY (cyan, magenta, and yellow) color systems. Algorithms exist to convert colors from one system to another. IDL accepts color specifications in the RGB, HLS, or HSV color systems.

The RGB color system, as implemented in IDL, uses a three-dimensional Cartesian coordinate system with the value of each color ranging from 0 to 255. Each displayable color is a point within this cube, shown in Figure 16.1 (after Foley and Van Dam). The origin, (0, 0, 0), where each color coordinate is 0, is black. The point at (255, 255, 255) is white and represents an additive mixture of the full intensity of each of the three colors. Points along the main diagonal—where the intensities of each of the three primary colors are equal —are shades of gray. The color yellow is represented by the coordinate (255, 255, 0), or a mixture of 100% red, plus 100% green, and no blue.

Typically, digital display devices represent each component of an RGB color coordinate as an n-bit integer in the range of 0 to 2^n - 1. Each displayable color is an RGB coordinate triple of n-bit numbers yielding a palette containing 2^3n total colors. Therefore, for 8-bit colors, each color coordinate can range from 0 to 255, and the total palette contains 2^24 or 16,777,216 colors.

A display with an m-bit pixel can represent 2^m colors simultaneously, given enough pixels. In the case of 8-bit colors, 24-bit pixels are required to represent all colors. The more common case is a display with 8 bits per pixel which allows the display of 2^8 = 256 colors selected from the much larger palette.

If there are not enough bits in a pixel to represent all colors, m < 2^3n, a color translation table is used to associate the value of a pixel with a color triple. This table is an array of color triples with an element for each possible pixel value. Given 8-bit pixels, a color table containing 2^8 = 256 elements is required. The color table element with an index of i specifies the color for pixels with a value of i.

To summarize, given a display with an n bit color representation and an m bit pixel, the color translation table, C, is a 2^m long array of RGB triples:

Ci  = {ri, gi, bi},   0 ≤ i < 2^m

0 ≤  ri, gi, bi < 2^n

Objects containing a value, or color index, of i are displayed with a color of Ci.

The IDL COLOR_CONVERT procedure can bo used to convert color triples to and from the RGB color system and the HLS and HSV systems.

You can display true color images on pseudo-color displays by using the COLOR_QUAN function. This function creates the "best" pseudo-color palette for displaying the true-color image and then maps the true color image to the new palette. See the IDL Reference Guide for more information on COLOR_QUAN.

Loading Color Tables

IDL maintains its own internal color table which is read and written by the TVLCT procedure. When this table is modified, it is loaded into the currently selected graphics output device. A call to this procedure has the form:

TVLCT, RED, GREEN, BLUE[, START]

where

RED, GREEN, and BLUE

Vectors containing the intensity or value of each color for each index. Standard devices have an 8-bit color representation so the color values should range from 0 to 255. These vectors can contain up to 2^m elements (usually 256), assuming the display contains m bit pixels.

START

The starting index in the color translation table into which RED, GREEN, and BLUE will be loaded. If not specified, a value of 0 is used, causing the tables to be loaded starting at the first element of the translation vectors. START can be used to change only part of the color table.

In addition, the following keyword parameters can also be present:

GET

Returns the RGB values from the internal color table into the three variables.

HLS

Indicates that the parameters specify color using the HLS color system. The plain argument parameters are in the order H-L-S. Hue is expressed in degrees, and the lightness and saturation range from 0 to 1.

HSV

Indicates that the parameters specify color using the color system. The plain argument parameters are in the order H-S-V. As above, hue is in degrees, and the saturation and value range from 0 to 1.

Examples: TVLCT

This example creates a graph with the axes drawn in white, then successively adds red, green, blue, and yellow lines. As there are five distinct colors, plus one color for the background, a six-element color table is created. Usually, color index 0 represents black (0, 0, 0). We arbitrarily choose color index 1 to be white (1, 1, 1), 2 as red (1, 0, 0), 3 as green (0, 1, 0), 4 as blue (0, 0, 1), and 5 as yellow (1, 1, 0). The display must have at least 3 bits per pixel to represent six colors simultaneously, and an 8-bit color table is assumed.

RED = [0, 1, 1, 0, 0, 1]	Specify the red component of each color.

GREEN = [0, 1, 0, 1, 0, 1]	Specify the green component of each color.

BLUE = [0, 1, 0, 0, 1, 0]	Specify the blue component of each color.

TVLCT, 255 * RED, 255 * GREEN, 255 * BLUE
Load the first six elements of the color table.

PLOT, COLOR = 1, /NODATA,...	Draw the axes in white, color index 1.

OPLOT, COLOR = 2, ...	Draw in red.

OPLOT, COLOR = 3, ...	Draw in green.

OPLOT, COLOR = 4, ...	Draw in blue.

OPLOT, COLOR = 5, ...  ...	Draw in yellow.

The INDGEN function is handy when creating larger color tables in which each color's intensity can be expressed as a function of its index:

A = INDGEN(256)	Straight line, A(I) = I.

TVLCT, A, A * 0, A * 0	Display image with a linear red scale, disable green and blue.

TVLCT, A, A, A	Display with linear black and white scale.

TVLCT, A, 2 * (A - 128) > 64, 4 * (A - 192) > 0
Warm body temperature scale. Red is linear, green starts at 128, and blue starts at 192.

Color Table Procedures

The following IDL procedures are used to manipulate color tables:

LOADCT

Load predefined color tables. LOADCT has one parameter: the index of the predefined color table to be loaded. There are 38 pre-defined color tables in the file colors1.tbl, which is supplied with IDL. To obtain a menu listing the available color tables, call LOADCT with no parameters. Standard tables are listed below.

Number	Name	Number	Name
0	Black & White Linear	19	Hue Sat Lightness 1
1	Blue/White Linear	20	Hue Sat Lightness 2
2	Green-Red-Blue-White	21	Hue Sat Value 1
3	Red Temperature	22	Hue Sat Value 2
4	Blue-Green-Red-Yellow	23	Purple-Red + Stripes
5	Standard Gamma-II	24	Beach
6	Prism	25	Mac Style
7	Red-Purple	26	Eos A
8	Green/White Linear	27	Eos B
9	Green/White Exponential	28	Hardcandy
10	Green-Pink	29	Nature
11	Blue-Red	30	Ocean
12	16 Level	31	Peppermint
13	Rainbow	32	Plasma
14	Steps	33	Blue-Red 2
15	Stern Special	34	Rainbow 2
16	Haze	35	Blue Waves
17	Blue-Pastel-Red	36	Volcano
18	Pastels	37	Waves
Table 16.1 Predefined Color Tables

XLOADCT

This procedure provides a widget interface to LOADCT. Pre-defined color tables can be loaded and manipulated using this tool. Tables can be stretched and Gamma corrected interactively using this procedure.

XPALETTE

This widget procedure allows you to create your own color tables using a set of three sliders. This procedure can interpolate the space between color indices (to create "smooth" color transitions) or edit individual colors.

PALETTE

Creates color tables with RGB bars and allows good selection and control of each color index. PALETTE can interpolate in RGB space between color indices or edit a single color index.

MODIFYCT

Saves color tables for later use by LOADCT.

HSV

Makes and loads color tables based on the HSV color system. A spiral through the single-ended HSV cone is traced. The color representation of pixel values is linearly interpolated from beginning and ending values of hue, saturation, and value.

HLS

Makes and loads color tables based on the HLS color system which is based on the Otswald color system. As with the HSV procedure, spirals are interpolated in the three-dimensional color space.

PSEUDO

Generates and loads a pseudo-color table based on the LHB (lightness, hue, and brightness) system.

STRETCH

Linearly expands the entire range of the last color table loaded to cover a given range of pixel values. STRETCH has two parameters: the pixel value to be displayed with color index 0 and the pixel value to be displayed with the maximum color index:

STRETCH, LOW, HIGH

For example, the statement,

STRETCH, 100, 150

expands the color tables so that pixels in the range of 100 to 150 fill the entire color range. To revert to a normal color table, call STRETCH with no parameters.

Note that the window-oriented procedures will not work without a window system.

Obtaining the Color Tables

All of the IDL color-table procedures maintain the current color table in a common block called COLORS, defined as follows:

COMMON COLORS, R_ORIG, G_ORIG, B_ORIG, R_CURR, G_CURR, B_CURR

The variables are integer vectors of length equal to the number of color indices. Your program can access these variables by defining the common block. The convention is that routines that modify the current color table should read it from R_ORIG, G_ORIG, and B_ORIG, then load the color table using TVLCT and leave the resulting color table in R_CURR, G_CURR, and B_CURR.

Color Tables—Switching Between Devices

Use the SET_PLOT procedure to direct the graphics output to different devices. Because devices have differing capabilities and not all are capable of representing the same number of colors, the treatment of color tables when switching devices is somewhat tricky.

After selecting a new graphics output device, SET_PLOT will perform one of the following color-table actions depending upon which keyword parameters are specified:

•	The default is to do nothing. The problem with this treatment is that the internal color tables incorrectly reflect the state of the device's color tables until TVLCT is called (usually via LOADCT).

•	If the COPY keyword parameter is set, the internal color tables are copied into the device. This is straightforward if both devices have the same number of color indices. If the new device has more colors than the old device, some color indices will be invalid. If the new device has less colors than the old, not all the colors are saved. This is the preferred method if you are displaying graphics and each color index is explicitly loaded.

•	When the INTERPOLATE keyword is set, the new device's table is loaded by interpolating the old color table to span the new number of color indices. This method works best when displaying images with continuous color ranges.


True Color Displays
True-Color Displays

IDL supports the use of some true-color displays with 24 bits per pixel. True-color displays have multiple channels. That is, they store information about each primary color component (red, green, and blue) of a pixel separately. A true-color display with n bits per memory channel can display 2^3n simultaneous colors, as opposed to the 2^n simultaneous colors available with a normal indexed (pseudo) color display. Images can be transferred to and from each individual memory channel, or to all channels simultaneously.

The X Window visuals TrueColor and DirectColor are among the true-color devices supported by IDL.

Configuration

The true-color display is configured as a single display with three channels:

Channel Number	Output
0	All colors
1	Red
2	Green
3	Blue
Table 16.2 True-Color Display Channels

Lookup Tables

Note: Not all true-color display systems have writable color lookup tables.

Each output channel, red, green, or blue, is routed through its own 8-bit deep, 256 element lookup table. The lookup tables can be used to compensate for color inaccuracies generated by the display hardware or present in the acquisition process. Initially, each lookup table is loaded with a linear ramp, mapping its input directly to its output.

As the TrueColor lookup tables are of the same size and number of elements as those on a pseudo-color display, operation of the TVLCT procedure, which loads the lookup tables, is unchanged.

Furthermore, if the same image is loaded into each channel, operation of the display mimics that of a standard 8-bit deep pseudo-color display. Most, but not all, IDL image processing procedures written for a standard color display will run on a true-color display without modification. The routines that transfer images to the display, TV and TVSCL, write the same 8-bit data to each channel (channel 0) if no channel parameter is present. The function TVRD, which reads data from the display, returns the maximum value contained in the three-color channels for each pixel if no channel parameter is present.

Color Indices

The color index specifier can range from 0 to 2^24 - 1. The system variable field !D.N_COLORS, which contains the number of colors, is set to 2^24 on a true-color display.The system variable field, !D.TABLE_SIZE, contains the number of RGB color table elements.

The low 8 bits, bits 0 to 7, of the color index are written to the red channel; bits 8 to 15 are written to the green; and bits 16 to 23 are written to the blue. For example, a given RGB, the index is R + 256(G + 256B). To create a plot with a given color (assuming linear lookup tables), use the following statement:

PLOT, X, Y, COLOR = R + 256L * (G + 256L * B)

True-Color Images

Images can be transferred to and from the display in either 8-bit or 24-bit mode. The CHANNEL keyword specifies the source or destination channel number for 8-bit images, and the TRUE keyword indicates for 24-bit images the method of channel interleaving. If neither keyword parameter is present, the 8-bit image is written to all three-color channels, yielding the same effect as if the channel parameter is specified as 0.

 For example, to transfer three 8-bit images contained in the arrays R, G, and B to their respective channels, use the following statements:

TV, R, CHANNEL = 1	Load red in channel 1.

TV, G, CHANNEL = 2	Load green in channel 2.

TV, B, CHANNEL = 3	Load blue in channel 3.

The optional position parameters can be included to write to any location in the window.

For 24-bit images, the RGB data can be interleaved by pixel, by line, or by image. Use the TRUE parameter to specify the method of interleaving. A c column by l line true-color image is dimensioned as follows:

TRUE Value	Dimensions	Interleaving
1	(3, c, l)	Pixel
2	( c, 3, l)	Line
3	( c, l, 3)	Image
Table 16.3 Values for the TRUE Keyword

For example, to write a true-color, line interleaved image contained in the variable t, with its lower- left corner at coordinate (100,200), use the following statement:

TV, T, 100, 200, TRUE = 2

Reading Images

To read from the display to an IDL variable or expression, use the TVRD function with either the CHANNEL or TRUE keyword parameters. The calling sequence for TVRD is:

Result = TVRD([X0, Y0, Nx, Ny, Channel])

where (X0, Y0) specifies the window coordinate of the lower-left corner of the rectangle to be read, and (Nx, Ny) contains the number of columns and rows to read. Note that all parameters to TVRD are optional. If no arguments are supplied, the entire area of the display device is returned.

When used without the TRUE parameter, TVRD returns an (Nx, Ny) byte image read from the indicated channel. If the channel number is not specified or is zero, the maximum RGB value of each pixel is returned, approximating the luminance.

If present and nonzero, the TRUE keyword indicates that a true-color image is to be read and specifies the index of the dimension over which color is interleaved. The result is a (3, Nx, Ny) pixel interleaved array if TRUE is 1; or an (Nx, 3, Ny) line interleaved array if TRUE is 2; or an (Nx, Ny, 3) image interleaved array if TRUE is 3.

Some examples of TVRD follow.

R = TVRD(0, 0, 512, 512, CHANNEL=1)	Read a 512 x 512 image, starting at (0, 0), from the red channel into R.

T = TVRD(0, 0, 512, 512, TRUE = 2)	Read a true-color 512 x 512, line interleaved image, starting at (0, 0) into T. The variable T is now dimensioned (512, 3, 512).

L = TVRD(0, 0, 512, 512)	Read the maximum RGB value of each pixel into L.


Controlling the Device Cursor

The TVCRS function manipulates the cursor of the image display. Normally, the cursor is disabled and is not visible. TVCRS with one argument allows the cursor to be enabled or disabled. While TVCRS with two parameters enables the cursor and places it on pixel location (x, y). TVCRS has the form

TVCRS[, ON_OFF]

TVCRS[, X, Y]

where

ON_OFF

Specifies whether the cursor should be on or off. If present and nonzero, the cursor is enabled. If ON_OFF is zero or no parameters are specified, the cursor is turned off.

X

The column to which the cursor will be set.

Y

The row to which the cursor will be set.

TVCRS also takes various keywords that affect how it positions the cursor. Notably, the keywords DATA, DEVICE, and NORMAL specify the coordinate system. For details, see the entry for TVCRS in the IDL Reference Guide.

References

Foley, J.D., and A. Van Dam (1982), Fundamentals of Interactive Computer Graphics, Addison- Wesley Publishing Company.

Jump forward to Files and Input/Output

Jump backward to Plotting Multi-Dimensional Arrays


Files and Input/Output
17	Files and Input/Output

Chapter Overview

IDL provides powerful facilities for file input and output. Few restrictions are imposed on data files by IDL, and there is no unique IDL format. This chapter describes IDL input/output methods and routines and gives examples of programs which read and write data using IDL, C, and FORTRAN.

This section provides a description for how IDL input/output works. It is intentionally brief and is intended to serve only as an introduction. Additional details are covered in the following sections. For the IDL user, perhaps the largest single difference between platforms is input/output. The majority of this chapter covers information that is required in all of the environments IDL supports. Operating system specific information is concentrated in the final sections of this chapter.


Topics in Files and I/O Chapter
Files and Input/Output

This chapter provides an overview of IDL's file manipulation and input/output facilities.

Topics Covered:

File I/O Overview

Types of Input/Output

Opening Files

Closing Files

Logical Unit Numbers (LUN's)

Free Format Input/Output

Explicitly Formatted Input/Output

Format Codes

Unformatted Input/Output

Portable Unformatted Input/Output

Associated Input/Output

Miscellaneous File Manipulation Information

UNIX-Specific Information

VMS-Specific Information

Scientific Data Formats

Support for Standard Image File Formats

Jump forward to Operating System Access

Jump backward to Image Display Routines


File I/O Overview

Before any file input or output can be performed, it is necessary to open a file. This is done using either the OPENR (Open for Reading), OPENW (Open for Writing), or OPENU (Open for Update) procedures. When a file is opened, it is associated with a Logical Unit Number, or LUN. All file input and output routines in IDL use the LUN rather than the filename, and most require that the LUN be explicitly specified. Once a file is opened, several input/output routines are available for use. Each routine fills a particular need ­ the one to use depends on the particular situation.

There are three exceptions to the need to open any file before performing input/output on it. Three files are always open ­ in fact, the user is not allowed to close them. These files are the standard input (usually the keyboard), the standard output (usually the terminal screen), and the standard error output (usually the terminal screen). These three files are associated with LUN's 0, -1, and -2, respectively. Because these files are always open, there is no need to open them prior to using them for input/output. The READ and PRINT procedures automatically use these files, so basic formatted input/output is extremely simple.

Formatted I/O

Formatted input/output converts internal data to and from characters in a file. This is useful for storing data that should be human readable or easily portable. The routines for formatted input/output are as follows:

PRINTF

Output formatted data to the specified LUN.

PRINT

Output formatted data to the standard output file (LUN -1).

READF

Read formatted data from the specified LUN.

READ

Read formatted data from the standard input file (LUN 0).

Unformatted I/O

Unformatted input/output transfers data directly to and from the file with no data conversion. It is best for images or large data sets that require high efficiency. Unformatted data files are usually more compact than their formatted counterparts. The unformatted input/output routines are as follows:

ASSOC

Map an array structure to a data file. ASSOC provides extremely efficient direct access to unformatted data and is an important IDL function to understand.

READU

Input unformatted data from the specified LUN.

WRITEU

Output unformatted data to the specified LUN.

In addition to performing input/output to an open file, there are several IDL routines that provide other capabilities:

GET_KBRD

Read single characters from the keyboard.

GET_LUN/FREE_LUN

Allocate and free unique file units.

FINDFILE

 Locate files that match a file specification.

FLUSH

Ensure all buffered data for a LUN has actually been output to the file.

POINT_LUN

Position the file pointer.

EOF

Check for the end-of-file condition.

HELP,/FILES

Print information about open files.

FSTAT

Get detailed information about any LUN.

Closing a File

Once all input/output to a given LUN is complete, it should be closed. There are three ways to close a file:

•	Use the CLOSE procedure.

•	Use the FREE_LUN procedure on a LUN that has been allocated by GET_LUN.

•	Exit IDL. IDL closes all open files when it exits.

Simple Examples

It is easy to use input/output using the default input and output files. The IDL command:

PRINT, 'Hello World.'

causes IDL to print the line:

Hello World.

on the terminal screen. This happens because PRINT formats its arguments and prints them to LUN -1, which is the standard output file. It is only slightly more complicated to use other files. The following IDL statements show how the above "Hello World" example could be sent to a file named hello.dat:

OPENW, 1, 'hello.dat'	Open LUN 1 for hello.dat with write access.

PRINTF, 1, 'Hello World.'	Do the output operation to the file.

CLOSE, 1 	Close the file.


Types of Input/Output

IDL divides input/output into two categories. These are summarized below, along with a brief discussion of advantages and disadvantages.

Unformatted

The most basic form of input/output. Unformatted input/output transfers the internal binary representation of the data directly between memory and the file.

Advantages of Unformatted I/O

Unformatted input/output is the simplest and most efficient form of input/output. It is usually the most compact way to store data.

Disadvantages of Unformatted I/O

Unformatted input/output is the least portable form of input/output. Unformatted data files can only be moved easily to and from computers that share the same internal data representation. It should be noted that XDR (eXternal Data Representation) files, described in "Portable Unformatted Input/Output" on page 17-33, can be used to produce portable binary data. It is not directly human readable, so you cannot type it out on a terminal screen or edit it with a text editor.

Formatted

Output converts the internal binary representation of the data to ASCII characters which are written to the output file. Formatted input reads characters from the input file and converts them to internal form.

Advantages of Formatted I/O

Formatted input/output is very portable. It is a simple process to move formatted data files to various computers, even computers running different operating systems, as long as they all use the ASCII character set. (ASCII is the American Standard Code for Information Interchange. It is the character set used by almost all current computers, with the notable exception of large IBM mainframes.)

Formatted files are human readable and can be typed to the terminal screen or edited with a text editor.

Disadvantages of Formatted I/O

Formatted input/output is more computationally expensive than unformatted input/output because of the need to convert between internal binary data and ASCII text. Formatted data requires more space than unformatted to represent the same information. Inaccuracies can result when converting data between text and the internal representation.

Formatted input/output is subdivided further into two categories as described below.

Free Format

With free format input/output, IDL uses default rules to format the data.

Advantages of Free Format I/O

The user is free of the chore of deciding how the data should be formatted. Free format is extremely simple and easy to use. It provides the ability to handle the majority of formatted input/output needs with a minimum of effort.

Disadvantages of Free Format I/O

The default formats used are not always exactly what is required. In this case, explicit formatting is necessary.

Explicit Format

Allows the exact format for input/output to be specified.

Advantages of Explicit I/O

Explicit formatting allows a great deal of flexibility in specifying exactly how data will be formatted. Formats are specified using a syntax that is similar to that used in FORTRAN format statements. Scientists and engineers already familiar with FORTRAN will find IDL formats easy to write. Commonly used FORTRAN format codes are supported. In addition, IDL formats have been extended to provide many of the capabilities found in the scanf () and printf () functions commonly found in the C language runtime library.

Disadvantages of Explicit I/O

Using explicitly specified formats requires the user to specify more detail—they are, therefore, more complicated to use than free format.

The type of input/output to use in a given situation is usually determined by considering the advantages and disadvantages of each method as they relate to the problem to be solved. Also, when transferring data to or from other programs or systems, the type of input/output is determined by the application. The following suggestions are intended to give a rough idea of the issues involved, though there are always exceptions:

•	Images and large data sets are usually stored and manipulated using unformatted input/output in order to minimize processing overhead. The IDL ASSOC function is often the natural way to access such data

•	Data that needs to be human readable should be written using formatted input/output.

•	Data that needs to be portable should be written using formatted input/output. Another option is to use unformatted XDR files by specifying the XDR keyword with the OPEN procedures. This is especially important if moving between computers with markedly different internal binary data formats. XDR is discussed in "Portable Unformatted Input/Output" on page 17-33.

•	Free format input/output is easier to use than explicitly formatted input/output and about as easy as unformatted input/output, so it is often a good choice for small files where there is no strong reason to prefer one method over another.


Opening Files

Before a file can be processed by IDL, it must be opened using one of the procedures described in Table 17.1. All open files are associated with a LUN (Logical Unit Number) within IDL, and all input/output routines refer to files via this number. For example, to open the file named data.dat for reading on file unit 1, use the following statement:

OPENR, 1, 'data.dat'

The OPEN procedures can be used with certain keywords to modify their normal behavior. Some keywords are generally applicable, while others only have effect under a given operating system. Some operating system specific keywords are allowed (and ignored) under other operating systems in order to facilitate writing portable routines.

Procedure	Description
OPENR	Opens an existing file for input only.
OPENW	Opens a new file for input and output. Under UNIX, Windows, and on the Macintosh, if the named file already exists, its old contents are destroyed. Under VMS, a file with the same name and a higher version number is created.
OPENU	Opens an existing file for input and output.
Table 17.1 IDL File Opening Commands

Generally Applicable Keywords to the OPEN Procedure

The following keywords are available under all operating systems:

APPEND

If present and nonzero, the file is opened with the current file pointer positioned just past the end of the file, ready for data to be appended. When used with OPENU, it is equivalent to the following IDL sequence:

OPENU, 1, 'file.dat'	Open the file.

TMP = FSTAT(1)	Get information about the file.

POINT LUN, 1, TMP.SIZE	Position the file pointer.

There is no reason to specify APPEND with OPENW because new files (as opened by OPENW) are empty—the start and end of the file are the same (position 0). Similarly, specifying it with OPENR is not useful because the file cannot be written to.

DELETE

If present, causes the file to be deleted when it is closed. This is convenient for cleaning up temporary scratch files.

ERROR

If an error occurs in the attempt to open a file, IDL normally takes the error-handling action defined by the ON_ERROR and/or ON_IOERROR procedures. However, the ERROR keyword can be used to specify a variable into which the error status code is placed. OPEN always returns to the caller without generating an error message when ERROR is present. A nonzero error status indicates that an error occurred. The error message can then be found in the system variable !ERR_STRING.

GET_LUN

If GET_LUN is present and nonzero, the GET_LUN procedure is called to set the value of UNIT before the file is opened. Thus, the two IDL statements

GET_LUN, UNIT

OPENR, UNIT, 'data.dat'

can be written as follows:

OPENR, UNIT, 'data.dat', /GET_LUN

GET_LUN is discussed in more detail later in this section.

MORE

If this keyword is set, and the specified file is a terminal, then all output to this unit will be output page-by-page in a manner similar to the UNIX more(1) command. See the description of OPEN in the IDL Reference Guide for a list of keyboard commands. Under VMS, this keyword is only allowed for stream mode files.

XDR

If this keyword is set, only unformatted input/output is allowed on the file using READU and WRITEU, and those procedures use the portable XDR binary representation. This results in binary files that are portable to different machine architectures. XDR is described in "Portable Unformatted Input/Output" on page 17-33.

UNIX-Only Keywords to OPEN

The following keyword only has effect under UNIX.

F77_UNFORMATTED

Files of unformatted data made by UNIX FORTRAN programs have a special record structure. Each logical record of data has a longword count preceding and following the data containing the number of bytes in the record. If F77_UNFORMATTED is present and nonzero, IDL properly reads and writes records using this format when performing input/output on the file. This allows IDL to exchange data with UNIX FORTRAN programs. This topic is covered in more detail in "UNIX-Specific Information" on page 17-46.

VMS-Only Keywords to OPEN

The following keywords only have effect under VMS:

BLOCK

If present and nonzero, indicates that the file should be processed using RMS block mode. In this mode, most RMS processing is bypassed and IDL reads and writes to the file in disk block units. Such files can only be accessed via unformatted input/output commands. Files created in block mode can only be accessed in block mode. Block mode files are treated as an uninterrupted stream of bytes in a manner similar to UNIX stream files.

DEFAULT

A scalar string that provides a default file specification from which missing parts of the filename argument are taken. For example, to make .LOG the default file extension when opening a new file, use the following statement:

OPENW, 'DATA', DEFAULT = '.LOG'

This statement will open the file DATA.LOG.

EXTENDSIZE

File extension is a relatively slow operation, and it is desirable to minimize the number of times it is done. In order to avoid the unacceptable performance that would result from extending a file a single block at a time, VMS extends its size by a default number of blocks in an attempt to trade a small amount of wasted disk space for better performance. The EXTENDSIZE keyword overrides the default and specifies the number of disk blocks by which the file should be extended. This keyword is often used in conjunction with the INITIALSIZE and TRUNCATE_ON_CLOSE keywords.

FIXED

Set this keyword to indicate that the file has fixed-length records.

FORTRAN

Set this keyword, when creating a new file, to specify FORTRAN-style carriage control. The first byte of each record controls the formatting.

INITIALSIZE

Specifies the initial file allocation in blocks.

KEYED

Set this keyword to specify that the file has indexed organization. Indexed files are discussed in "VMS-Specific Information" on page 17-49.

LIST

When creating a new file, this keyword specifies carriage-return carriage control. If no carriage control keyword is specified, LIST is the default. Each record is implicitly preceded by a line feed and followed by a carriage return.

NONE

When creating a new file, this keyword specifies explicit carriage control. This means that VMS does not add any carriage control information to the file, and the user must explicitly add any desired carriage control information to the data being written to the file.

PRINT

If present, the file will be sent to SYS$PRINT, the default system printer, when closed.

SEGMENTED

Specifies that the file has VMS FORTRAN-style segmented records. Segmented records are a method by which VMS FORTRAN allows logical records to exist with record sizes that exceed the maximum possible physical record sizes supported by VMS. Segmented record files are useful primarily for passing data between FORTRAN and IDL programs.

SHARED

If this keyword is set, other processes are allowed read and write access to the file in parallel with IDL. If SHARED is not specified, read-only files are opened for read sharing, and read/write files are not shared.

The SHARED keyword cannot be used with STREAM files.

Caution: It is not a good idea to allow shared write access to on-disk fixed-length record files or to files open in RMS block mode. With such files, which are processed in RMS block mode, VMS cannot perform record locking, which avoids file corruption. Therefore, it is possible for multiple writers to corrupt the contents.

STREAM

Set this keyword to open the file in stream mode using the Standard C Library (stdio).

SUBMIT

Set this keyword to submit the file to SYS$BATCH, the default system batch queue, when closed.

SUPERSEDE

If present, this keyword allows an existing file to be superseded by a new file of the same name, type, and version.

TRUNCATE_ON_CLOSE

If present, this keyword causes any unused disk space allocated to the file to be freed when the file is closed. It can be used to get rid of excess allocations caused by the EXTENDSIZE and INITIALSIZE keywords. If the SHARED keyword is present or the file is open for read-only access, TRUNCATE_ON_CLOSE has no effect.

VARIABLE

The file has variable length records. If the RECORD_SIZE argument is present, it specifies the maximum record size; otherwise, the only limit is that imposed by RMS. If no file organization is specified, variable length records are the default.


Closing Files

After work involving the file is complete, it should be closed. Closing a file removes the association between the file and its unit number, thus freeing the unit number for use with a different file. There is usually an operating-system imposed limit on the number of files a user may have open at once. Although this number is large enough that it rarely causes problems, situations can occur where a file must be closed before another file may be opened. In any event, it is good style to only keep needed files open.

A file unit can be closed by calling the CLOSE procedure. For example, to close file unit number 1, use the following statement:

CLOSE, 1

In addition, if FREE_LUN is called with a file unit number that was previously allocated by GET_LUN, it calls CLOSE before deallocating the file unit. Finally, all open files are automatically closed when IDL exits.


Logical Unit Numbers (LUN's)

IDL LUN's fall within the range −2 to 128. Some LUN's are reserved for special functions as described below.

The Standard Input, Output, and Error LUN's

The three LUN's described below have special meanings that are operating system dependent:

♦	UNIX: Logical Unit Numbers 0, -1, and -2 are tied to stdin, stdout, and stderr, respectively. This means that the normal UNIX file redirection and pipe operations work with IDL. For example, the shell command

%idl < idl.inp > idl.out &

will cause IDL to execute in the background, reading its input from the file idl.inp and writing its output to the file idl.out.

♦	VMS: Logical Unit Numbers 0, -1, and -2 are tied to SYS$INPUT, SYS$OUTPUT, and SYS$ERROR respectively. This means that the DCL DEFINE command can be used to redefine where IDL gets commands and writes its output. It also means that IDL can be used in command and batch files.

♦	Windows and Macintosh: Logical Unit Numbers 0, -1, and -2 are tied to stdin (the command line), stdout (the log window), and stderr (the log window), respectively.

These special file units are described in more detail below.

File Unit 0

This LUN represents the standard input stream, which is usually the keyboard. Therefore, the IDL statement:

READ, X

is equivalent to the following:

READF, 0, X

File Unit -1

This LUN represents the standard output stream, which is usually the terminal screen. Therefore, the IDL statement:

PRINT, X

is equivalent to the following:

PRINTF, -1, X

File Unit -2

This LUN represents the standard error stream, which is usually the terminal screen.

File Units 1­99

These are the file units for normal interactive use. When using IDL interactively, the user arbitrarily selects the file units used. The file units from 1 to 99 are available for this use.

File Units 100 ­128

These are the file units managed by the GET_LUN and FREE_LUN procedures. If an IDL procedure or function that uses files is written to explicitly use a given file unit, there is a chance that it will conflict with other routines that use the same unit. It is therefore necessary to avoid explicit file unit numbers when writing IDL procedures and functions. The GET_LUN and FREE_LUN procedures provide a standard mechanism for IDL routines to obtain unique file units. GET_LUN allocates a file unit from a pool of free units in the range 100 to 128. This unit will not be allocated again until it is released by a call to FREE_LUN. Meanwhile, it is available for the exclusive use of the program that allocated it. A typical procedure that needs a file unit might be structured as follows:

PRO DEMO

OPENR, UNIT, /GET_LUN	Get a unique file unit and open the file.

.

.	Body of program goes here.

.

FREE_LUN, UNIT 	Return file unit.

END	Since the file is still open, FREE_LUN will automatically call CLOSE.

Note: All IDL procedures and functions that open files should use GET_LUN/FREE_LUN to obtain file units. Furthermore, the file units between 100 and 128 should never be used unless previously allocated by GET_LUN.


Free Format Input/Output

Use of formatted data is most appropriate when the data must be in human readable form, such as when it is to be prepared or modified with a text editor. Formatted data also are highly portable between various computers and operating systems. IDL provides four procedures for performing formatted input/output:

PRINT

Sends output to the standard output.

PRINTF

Sends output to the specified file unit.

READ

Reads from the standard input.

READF

Reads input from the specified file unit.

In addition, the STRING function can be used to generate formatted output that is sent to a string variable instead of a file. The READS procedure can be used to read formatted input from a string variable.

The exact format of the character data may be specified to these procedures by providing a format string via the FORMAT keyword. If no format string is given, default formats for each type of data are applied. This method of formatted input/output is called free format. Free format input/output is suitable for most applications involving formatted data. It is designed to provide input/output abilities with a minimum of programming.

Free Format Input

The following rules are used by IDL to perform free format input:

1.	Input is performed on scalar variables. Array and structure variables are treated as collections of scalar variables. For example,

A = INTARR(5)

READ, A

causes IDL to read five separate values to fill each element of the variable A.

2.	If the current input line is empty and there are variables left requiring input, read another line.

3.	If the current input line is not empty but there are no variables left requiring input, the remainder of the line is ignored.

4.	Input data must be separated by commas or white space (tabs, spaces, or new lines).

5.	When reading into a variable of type string, all characters remaining in the current input line are placed into the string.

6.	When reading into numeric variables, every effort is made to convert the input into a value of the expected type. Decimal points are optional and exponential (scientific) notation is allowed. If a floating-point datum is provided for an integer variable, the value is truncated.

7.	When reading into a variable of complex type, the real and imaginary parts are separated by a comma and surrounded by parentheses. If only a single value is provided, it is taken as the real part of the variable, and the imaginary part is set to zero. For example:

A = COMPLEX(0)	Create a complex variable.

READ, A	IDL prompts for input with a colon:

:(3, 4)	The user enters "(3,4)" and A is set to COMPLEX(3, 4).

READ, A	IDL prompts for input with a colon:

:50	The user enters "50" and A is set to COMPLEX(50, 0).

Free Format Output

The following rules are used by IDL to perform free format output:

1.	The format used to output numeric data is determined by the data type. The formats used are summarized in the table below. The formats are specified in the FORTRAN-like style used by IDL for explicitly formatted input/output.

Data Type	Format
Byte	I4
Int	I8
Long	I12
Float	G13.6
Double	G16.8
Complex	'(', G13.6, ',', G13.6, ')'
String	Output full string on current line.
Table 17.2 Formats Used for Free-Format Output

2.	The current output line is filled with characters until one of the following happens:

 (a)  There is no more data to output.

 (b)  The output line is full.

 (c)  An entire row is output in the case of multidimensional arrays.

3.	When outputting a structure variable, its contents are bracketed with "{" and "}" characters.

Example: Free Format Input/Output

IDL free format input/output is extremely easy to use. The following IDL statements demonstrate how to read into a complicated structure variable and then print the results:

A = {ALLTYPES, A:0B, B:0, C:0L, D:1.0, E:1D, $

  F:COMPLEX(0), G: 'string', E:FLTARR(5)}
Create a structure named "alltypes" that contains all seven of the basic IDL data types, as well as a floating-point array.

READ, A 	Read free formatted data from the input.

: 1 2 3 4 5 (6,7) EIGHT	IDL prompts for input with a colon. We enter values for the first six numeric fields of A and the string. Notice that the complex value was specified as (6, 7). If the parentheses had been omitted, the complex field of A would have received the value COMPLEX(6, 0), and the 7 would have been input for the next field. When reading into a string variable, IDL starts from the current point in the input and continues to the end of the line. Thus, we do not enter values intended for the rest of the structure on this line.

: 9 10 11 12 13	There are still fields of A that have not received data, so IDL prompts for another line of input.

PRINT, A 	Show the result.

Executing these statements results in the following output:

{   1       2           3      4.00000       5.0000000
(      6.00000,      7.00000)  eight
      9.00000      10.0000      11.0000      12.0000     13.0000}

When producing the output, IDL uses default rules for formatting the values and attempts to place as many items as possible onto each line. Because the variable A is a structure, braces {} are placed around the output. As noted above, when IDL reads strings it continues to the end of the line. For this reason, it is usually convenient to place string variables at the end of the list of variables to be input. For example, if S is a string variable and I is an integer:

READ, S, I	Read into the string first.

: Hello World 34	IDL prompts for input. We enter a string value followed by an integer.

: 34	The entire previous line was placed into the string variable S, and I still requires input. IDL prompts for another line.


Explicitly Formatted Input/Output

The FORMAT keyword can be used with the formatted input/output routines to explicitly specify the appearance of the data. The syntax of IDL format strings is extremely similar to that used in FORTRAN. The format string specifies the format in which data is to be transferred as well as the data conversion required to achieve that format. The format specification strings supplied by the FORMAT keyword have the form:

FORMAT = '(q1f1s1f2s2 ... fnqn)'

where q, f, and s are described below.

Record Terminators

q is zero or more slash (/) record terminators. On output, each record terminator causes the output to move to a new line. On input, each record terminator causes the next line of input to be read.

Format Codes

f is a format code. Some format codes specify how data should be transferred while others control some other function related to how input/output is handled. The code f can also be a nested format specification enclosed in parentheses. This is called a group specification and has the following form:

...[n](q1f1s1f2s2 ... fnqn) ...

A group specification consists of an optional repeat count n followed by a format specification enclosed in parentheses. Use of group specifications allows more compact format specifications to be written. For example, the format specification:

FORMAT = '("Result: ", "<",I5,">", "<",I5,">")'

can be written more concisely using a group specification:

FORMAT = '("Result: ", 2("<",I5,">"))'

If the repeat count is 1 or is not given, the parentheses serve only to group format codes for use in format reversion (discussed in the next section).

Field Separators

s is a field separator. A field separator consists of one or more commas (,) and/or slash record terminators (/). The only restriction is that two commas cannot occur side-by-side.

The arguments provided in a call to a formatted input/output routine are called the argument list. The argument list specifies the data to be moved between memory and the file. All data are handled in terms of basic IDL components. Thus, an array is considered to be a collection of scalar data elements, and a structure is processed in terms of its basic components. Complex scalar values are treated as two floating-point values.

Rules for Explicitly Formatted Input/Output

IDL uses the following rules to process explicitly formatted input/output:

•	Traverse the format string from left to right, processing each record terminator and format code until an error occurs or no data is left in the argument list. The comma field separator serves no purpose except to delimit the format codes.

•	It is an error to specify an argument list with a format string that does not contain a format code that transfers data to or from the argument list because an infinite loop would result.

•	When a slash record terminator (/) is encountered, the current record is completed, and a new one is started. For output, this means that a new line is started. For input, it means that the rest of the current input record is ignored, and the next input record is read.

•	When a format code that does not transfer data to or from the argument list is encountered, process it according to its meaning. The format codes that do not transfer data to or from the argument list are summarized in Table 17.3.

Code	Action
Quoted String	On output, the contents of the string are written out. On input, quoted strings are ignored.
:	The colon format code in a format string terminates format processing if no more items remain in the argument list. It has no effect if data still remains on the list.
$	On output, if a $ format code is placed anywhere in the format string, the new line implied by the closing parenthesis of the format string is suppressed. On input, the $ format code is ignored.
nH	FORTRAN-style Hollerith string. Hollerith strings are treated exactly like quoted strings.
nX	Skips n character positions.
Tn	Tab. Sets the character position of the next item in the current record.
TLn	Tab Left. Specifies that the next character to be transferred to or from the current record is the n-th character to the left of the current position.
TRn	Tab Right. Specifies that the next character to be transferred to or from the current record is the n-th character to the right of the current position.
Table 17.3 Format Codes that do not Transfer Data

•	When a format code that transfers data to or from the argument list is encountered, it is matched up with the next datum in the argument list. The format codes that transfer data to or from the argument list are summarized in Table 17.4.

•	On input, read data from the file and format it according to the format code. If the data type of the input data does not agree with the data type of the variable that is to receive the result, do the type conversion if possible; otherwise, issue a type conversion error and stop.

•	On output, write the data according to the format code. If the data type does not agree with the format code, do the type conversion prior to doing the output if possible. If the type conversion is not possible, issue a type conversion error and stop.

Code	Action
A	Transfer character data.
D	Transfer double-precision, floating-point data.
E	Transfer floating-point data using scientific (exponential) notation.
F	Transfer floating-point data.
G	Use F or E format depending on the magnitude of the value being processed.
I	Transfer integer data.
O	Transfer octal data.
Q	Obtain the number of characters in the input record remaining to be transferred during a read operation. In an output statement, the Q format code has no effect except that the corresponding input/output list element is skipped.
Z	Transfer Hexadecimal data.
Table 17.4 Format Codes that Transfer Data

•	If the last closing parenthesis of the format string is reached and there are no data left on the argument list, then format processing terminates. If, however, there are still data to be processed on the argument list, then part or all of the format specification is reused. This process is called format reversion.

Format Reversion

In format reversion, the current record is terminated, a new one is initiated, and format control reverts to the group repeat specification whose opening parenthesis matches the next-to-last closing parenthesis of the format string. If the format does not contain a group repeat specification, format control returns to the initial opening parenthesis of the format string. For example, the IDL command:

PRINT, FORMAT = '("The values are: ", 2("<", I1, ">"))', $

  INDGEN(6)

results in the output

The values are: <0><1>

<2><3>

<4><5>

The process involved in generating this output is as follows:

1.	Output the string "The values are: ".

2.	Process the group specification and output the first two values. The end of the format specification is encountered, so end the output record. Data are remaining, so move back to the group specification
       2("<", I1, ">")
by format reversion.

3.	Repeat Step 2 until no data remain. End the output record. Format processing is complete.


Format Codes

"A" Format Code

The A format code transfers character data. The format is

[n]A[w]

where

n	is an optional repeat count (1 ≤ n ≤ 32767) specifying the number of times the format code should be processed. If n is not specified, a repeat count of one is used.

w	is an optional width (1 ≤ w ≤ 256), specifying the number of characters to be transferred. If w is not specified, the entire string is transferred. On output, if  w is greater than the length of the string, the string is right justified. On input, IDL strings have dynamic length, so w specifies the resulting length of input string variables.

For example, the IDL statement,

PRINT, FORMAT = '(A6)', '123456789'

generates the following output:

123456

":" Format Code

The colon format code terminates format processing if there are no more data remaining in the argument list. For example, the IDL statement,

PRINT, FORMAT = '(6(I1, :, ", "))', INDGEN(6)

will output the following comma-separated list of integer values:

0, 1, 2, 3, 4, 5

The use of the colon format code prevented a comma from being output following the final item in the argument list.

"$" Format Code

When IDL completes output format processing, it normally outputs a newline to terminate the output operation. However, if a "$" format code is found in the format specification, this default newline is not output. The "$" format code is only used on output; it is ignored during input formatting. The most common use for the "$" format code is in prompting for user input. For example, the IDL statements,

PRINT, FORMAT = '($, "Enter value: ")'
Prompt for input. Suppress the carriage return.

READ, VALUE 	Read the response.

will prompt for input without forcing the user's response to appear on a separate line from the prompt. Under VMS, the "$" format code does not work with files opened with carriage-return carriage control, which is the default for new files. However, it does work with explicit or FORTRAN carriage control. FORTRAN carriage control is described on page 17-46.

"F," "D," "E," and "G" Format Codes

The F, D, E, and G format codes are used to transfer floating-point values between memory and the specified file. The format is

[n]F[w.d]

[n]D[w.d]

[n]E[w.d] or [n]E[w.dEe]

[n]G[w.d] or [n]G[w.dEe]

where

n	is an optional repeat count (1 ≤ n ≤ 32767) specifying the number of times the format code should be processed. If n is not specified, a repeat count of 1 is used.

w.d	is an optional width specification (1 ≤ w ≤ 256, 1 ≤ d < w). The variable w specifies the number of characters in the external field, and d specifies the number of positions after the decimal point.

e 	is an optional width (1 ≤ e ≤ 256) specifying the width of exponent part of the field. IDL ignores this value—it is allowed for compatibility with FORTRAN.

On input, the F, D, E, and G format codes all transfer w characters from the external field and assign them as a real value to the corresponding input/output argument list datum.

The F and D format codes are used to output values using fixed-point notation. The value is rounded to d decimal positions and right-justified into an external field that is w characters wide. The value of w must be large enough to include a minus sign when necessary, at least one digit to the left of the decimal point, the decimal point, and d digits to the right of the decimal point. The code D is identical to F (except for its default values for w and d) and exists in IDL primarily for compatibility with FORTRAN.

The E format code is used for scientific (exponential) notation. The value is rounded to d decimal positions and right-justified into an external field that is w characters wide. The value of w must be large enough to include a minus sign when necessary, at least one digit to the left of the decimal point, the decimal point, d digits to the right of the decimal point, a plus or minus sign for the exponent, the character "e" or "E", and at least two characters for the exponent.

The G format code is a compromise between these choices—it uses the F output style when reasonable and E for other values.

On output, if the field provided is not wide enough, it is filled with asterisks (*) to indicate the overflow condition. If w is zero, the "natural" width for the value is used —the value is read or output using a default format without any leading or trailing whitespace, in the style of the C standard input/output library printf (3S) function. If w, d, or e are omitted, the values specified in Table 17.5 are used.

Data Type	w	d	e
Float, Complex	15	7	2
Double	25	16	2
All Other Types	25	16	2
Table 17.5 Floating Format Defaults

Note that using a value of zero for the w parameter is useful when reading tables of data in which individual elements may be of varying lengths. For example, if your data reside in tables of the following form:

26.01 92.555 344.2

101.0 6.123 99.845

23.723 200.02 141.93

setting the format to

FORMAT = '(3F0)'

ensures that the correct number of digits are read or output for each element.

Normally, the case of the format code is ignored by IDL. However, the case of the E and G format codes determines the case used to output the exponent in scientific notation. Table 17.6 gives examples of several floating-point formats and the resulting output.

Format	Internal Value	Formatted Output
F	100.0	bbbb100.0000000
F	100.0D	bbbbb100.0000000000000000
F10.0	100.0	bbbbbb100.
F10.1	100.0	bbbbb100.0
F10.4	100.0	100.0000
F2.1	100.0	**
e10.4	100.0	1.0000e+02
E10.4	100.0	1.0000E+02
g10.4	100.0	100.0
g10.4	10000000.0	1.000e+07
Table 17.6 Floating-Point Output Examples ("b" represents a blank space)

"I," "O," and "Z" Format Codes

The I, O, and Z format codes are used to transfer integer values to and from the specified file. The I format code is used to output decimal values, O is used for octal values, and Z is used for hexadecimal values. The format is as follows:

[n]I[w] or [n]I[w.m]

[n]O[w] or  [n]O[w.m]

[n]Z[w] or [n]Z[w.m]

where

n	is an optional repeat count (1 ≤ n ≤ 32767) specifying the number of times the format code should be processed. If n is not specified, a repeat count of 1 is used.

w	is an optional integer value (1 ≤ w ≤ 256) specifying the width of the field in characters. The default values used if w is omitted are specified in Table 17.7

Data Type	w
Byte, Int	7
Long, Float	12
Double	23
All Other Types	12
Table 17.7 Integer Format Defaults

If the field provided is not wide enough, it is filled with asterisks (*) to indicate the overflow condition. If w is zero, the "natural" width for the value is used —the value is read or output using a default format without any leading or trailing white space, in the style of the C standard input/output library printf (3S) function.

Note that using a value of zero for the w parameter is useful when reading tables of data in which individual elements may be of varying lengths. For example, if your data reside in tables of the following form:

26 92 344

101 6 99

23 200 141

setting the format to

FORMAT = '(3I0)'

ensures that the correct number of digits are read or output for each element.

m	On output, m specifies the minimum number of nonblank digits required (1 ≤ m ≤ 256). The field is zero-filled on the left if necessary. If m is omitted or zero, the external field is blank filled.

Normally, the case of the format code is ignored by IDL. However, the case of the Z format codes determines the case used to output the hexadecimal digits A-F. Table 17.8 gives examples of several integer formats and the resulting output.

Format	Internal Value	Formatted Output
I	3000	bbb3000
I6.5	3000	b03000
I5.6	3000	*****
I2	3000	**
O	3000	bbb5670
O6.5	3000	b05670
O5.6	3000	*****
O2	3000	**
z	3000	bbbbbb8
Z	3000	bbbbBB8
Z6.5	3000	b00bb8
Z5.6	3000	*****
Z2	3000	**
Table 17.8 Integer Output Examples ("b" represents a blank space)

"Q" Format Code

The Q format code returns the number of characters in the input record remaining to be transferred during the current read operation. It is ignored during output formatting. Format Q is useful for determining how many characters have been read on a line. For example, the following IDL statements count the number of characters in file demo.dat:

OPENR, 1, "demo.dat"	Open file for reading.

N = 0L 	Create a longword integer to keep the count.

WHILE(NOT EOF(1)) DO BEGIN	Count the characters.

  READF, 1, CUR, FORMAT = '(q)' & N = N + CUR

END

PRINT, FORMAT = '("counted", N, "characters.")'
Report the result.

CLOSE, 1	Close file.

Quoted String and "H" Format Codes

On output, any quoted strings or Hollerith constants are sent directly to the output. On input, they are ignored. For example, the IDL statement,

PRINT, FORMAT = '("Value: ", I0)', 23

results in the following output:

Value: 23

Notice the use of single quotes around the entire format string and double quotes around the quoted string inside the format. This is necessary because we are including quotes inside a quoted string. It would have been equally correct to use double quotes around the entire format string and single quotes internally. Another way to specify the string is with a Hollerith constant as follows:

PRINT, FORMAT = '(7HValue: , I0)', 23

The format for a Hollerith constant is:

nHc1c2 c3 ... cn

where

n	is the number of characters in the constant (1 ≤ n ≤ 255).

ci	is the characters that make up the constant. The number of characters must agree with the value provided for n.

"T" Format Code

The T format code specifies the absolute position in the current record. The format is

Tn

where

n	is the absolute character position within the record to which the current position should be set (1 ≤ n ≤ 32767).

T	differs from the TL, TR, and X format codes primarily in that it requires an absolute position rather than an offset from the current position. For example,

PRINT, FORMAT = '("First", 20X, "Last", T10, "Middle")'

produces the following output:

FirstbbbbMiddlebbbbbbbbbbLast

where "b" represents a blank space.

"TL" Format Code

The TL format code moves the current position in the external record to the left. The format is

TLn

where

n	is the number of characters to move left from the current position (1 ≤ n ≤ 32767). If the value of n is greater than the current position, the current position is moved to column one.

TL	is used to move backwards in the current record. It can be used on input to read the same data twice or on output to position the output nonsequentially. For example,

PRINT, FORMAT = '("First", 20X, "Last", TL15, "Middle")'

produces the following output:

FirstbbbbbbbbbMiddlebbbbbLast

where "b" represents a blank space.

"TR" and "X" Format Codes

The TR and X format codes move the current position in the record to the right. The format is

TRn

nX

where

n	is the number of characters to skip (1 ≤ n ≤ 32767). On input, n characters in the current input record will be passed over. On output, the current output position is moved n characters to the right.

The TR or X format codes can be used to leave whitespace in the output or to skip over unwanted data in the input. For example,

PRINT, FORMAT = '("First", 15X, "Last")'

or

PRINT, FORMAT = '("First", TR15, "Last")'

results in the following output:

FirstbbbbbbbbbbbbbbbLast

where "b" represents a blank space.

These two format codes differ in one way. Using the X format code at the end of an output record will not cause any characters to be written unless it is followed by another format code that causes characters to be output. The TR format code always writes characters in this situation. Thus,

PRINT, FORMAT = '("First", 15X)'

does not leave 15 blanks at the end of the line, but the following statement does:

PRINT, FORMAT = '("First", 15TR)'

Example: Reading Tables of Formatted Data

IDL explicitly formatted input/output has the power and flexibility to handle almost any kind of formatted data. A common use of explicitly formatted input/output involves reading and writing tables of data. Consider a data file containing employee data records. Each employee has a name (String, 32 columns) and the number of years they have been employed (Integer, 3 columns) on the first line. The next two lines contain each employee's monthly salary for the last twelve months. A sample file named employee.dat with this format might look like the following:

Bullwinkle                       10
   1000.0    9000.97   1100.0                        2000.0
   5000.0    3000.0    1000.12   3500.0    6000.0     900.0
Borris                           11
    400.0     500.0    1300.10    350.0     745.0    3000.0
    200.0     100.0     100.0      50.0      60.0       0.25
Natasha                          10
    950.0    1050.0    1350.0     410.0     797.0     200.36
   2600.0    2000.0    1500.0    2000.0    1000.0     400.0
Rocky                            11
   1000.0    9000.0    1100.0       0.0       0.0    2000.37
   5000.0    3000.0    1000.01   3500.0    6000.0     900.12

The following IDL statements read data with the above format and produce a summary of its contents:

OPENR, 1, 'employee.dat'	Open data file for input.

name = '' & years = 0 & salary = FLTARR(12)
Create variables to hold the name, number of years, and monthly salary.

PRINT, FORMAT='("Name", 28X, "Years", 4X, "Yearly Salary")'
Output a heading for the summary.

PRINT, '========' 	Note: The actual dashed line is longer than is shown here.

WHILE (NOT EOF(1)) DO BEGIN	Loop over each employee.

 READF, 1, $	Read the data on the next employee.

  FORMAT = '(A32,I3,2(/,6F10.2))', name, years, salary

 PRINT, FORMAT='(A32,I5,5X,F10.2)', name, years, TOTAL(salary)
Output the employee information. Use TOTAL to sum the monthly salaries to get the yearly salary.

ENDWHILE

CLOSE, 1

The output from executing these statements on employee.dat is as follows:

Name                            Years    Yearly Salary
======================================================
Bullwinkle                         10       32501.09
Borris                             11        6805.35
Natasha                            10       14257.36
Rocky                              11       32500.50

Example: Reading Records that Contain Multiple Array Elements

Frequently, data are written to files with each record containing single elements of more than one array. One example might be a file consisting of observations of altitude, pressure, temperature, and velocity with each line or record containing a value for each of the four variables. Because IDL has no equivalent of the FORTRAN implied DO list, special procedures must be used to read or write this type of file.

The first approach, which is the simplest, may be used only if all of the variables have the same data type. An array is created with as many columns as there are variables and as many rows as there are elements. The data are read into this array, the array is transposed storing each variable as a row, and each row is extracted and stored into a variable which becomes a vector. For example, the FORTRAN program which writes the data and the IDL program which reads the data are as follows:

FORTRAN Write:

DIMENSION ALT(100),PRES(100),TEMP(100),VELO(100)
OPEN (UNIT = 1, STATUS='NEW', FILE='TEST')
WRITE(1,'(4(1x,g15.5))')
     (ALT(I),PRES(I),TEMP(I),VELO(I),I=1,100)

IDL Read:

OPENR, 1, 'test'	Open file for input.

A = FLTARR(4,100)	Define variable (NVARS by NOBS).

READF, 1, A 	Read the data.

A = TRANSPOSE(A)	Transpose so that columns become rows.

ALT = A(*, 0)	Extract the variables.

PRES = A(*, 1)

TEMP = A(*, 2)

VELO = A(*, 3)

Note that this same example may be written without the implied DO list, writing all elements for each variable contiguously and simplifying matters considerably:

FORTRAN Write:

DIMENSION ALT(100),PRES(100),TEMP(100),VELO(100)
OPEN (UNIT = 1, STATUS='NEW', FILE='TEST')
WRITE (1,'(4(1x,G15.5))') ALT,PRES,TEMP,VELO

IDL Read:

ALT = FLTARR(100)	Define variables.

PRES = ALT & TEMP = ALT & VELO = ALT

OPENR, 1, 'test'

READF, 1, ALT, PRES, TEMP, VELO

A different approach must be taken when the columns contain different data types or the number of lines or records are not known. This method involves defining the arrays, defining a scalar variable to contain each datum in one record, then writing a loop to read each line into the scalars, and then storing the scalar values into each array. For example, assume that a fifth variable, the name of an observer which is of string type, is added to the variable list. The FORTRAN output routine and IDL input routine are as follows:

FORTRAN Write:

DIMENSION ALT(100),PRES(100),TEMP(100),VELO(100)
CHARACTER * 10 OBS(100)
OPEN (UNIT = 1, STATUS = 'NEW', FILE = 'TEST')
WRITE (1,'(4(1X,G15.5),2X,A)')
  (ALT(I),PRES(I),TEMP(I),VELO(I),OBS(I),I=1,100)

IDL Read:

OPENR, 1, 'test'	Access file. This example will read files containing from 1 to 200 records.

ALT = FLTARR(200)	Define vector, make it large enough for the biggest case.

PRES = ALT & TEMP = ALT & VELO = ALT	Define other vectors using the first.

OBS = STRARR(200)	Define string array.

OBSS = ''	Define scalar string.

I = 0	Initialize counter.

WHILE NOT EOF(1) DO BEGIN 	Read loop.

  READF, 1, $	Read scalars.

  FORMAT = '(4(1X, G15.5), 2X, A10)', $

    ALTS, PRESS, TEMPS, VELOS, OBSS

  ALT(I) = ALTS & PRES(I) = PRESS & TEMP(I) = TEMPS

  VELO(I) = VELOS & OBS(I) = OBSS	Store in each vector.

  IF I LT 199 THEN I = I + 1 ELSE STOP, 'Too many records'
Increment counter and check for too many records.

ENDWHILE	Done.

If desired, after the file has been read and the number of observations is known, the arrays may be truncated to the correct length using a series of statements similar to the following:

ALT = ALT(0:I-1)

The above statement represents a worst case example. Reading is greatly simplified by writing data of the same type contiguously and by knowing the size of the file. One frequently used technique is to write the number of observations into the first record so that when reading the data the size is known.

Caution: It might be tempting to implement a loop in IDL which reads the data values directly into array elements, using a statement such as the following:

FOR I = 0, 99 DO READF, 1, ALT(I), PRES(I), TEMP(I), VELO(I)

This statement is incorrect. Subscripted elements (including ranges) are temporary expressions passed as values to procedures and functions (READF in this example). Parameters passed by value do not pass results back to the caller as explained in Chapter 10. The proper approach is to read the data into scalars and assign the values to the individual array elements as follows:

A = 0. & P = 0. & T = 0. & V = 0.
FOR I = 0, 99 DO BEGIN
  READF, 1, A, P, T, V
  ALT(I) = A & PRES(I) = P & TEMP(I) = T & VELO(I) = V
ENDFOR


Unformatted Input/Output

Unformatted input/output involves the direct transfer of data between a file and memory without conversion to and from a character representation. Unformatted input/output is used when efficiency is important and portability is not an issue. It is faster and requires less space than formatted input/output. IDL provides three procedures for performing unformatted input/output:

READU

Reads unformatted data from the specified file unit.

WRITEU

Writes unformatted data to the specified file unit.

ASSOC

Maps an array structure to a logical file unit, providing efficient and convenient direct access to data.

This section discusses READU and WRITEU, while ASSOC is discussed in "Associated Input/Output" on page 17-36. The READU and WRITEU procedures provide IDL's basic unformatted input/output capabilities. They have the form:

READU, Unit, Var1, ..., Varn

WRITEU, Unit, Var1, ..., Varn

where

Unit 	The logical file unit with which the input/output operation will be performed.

Vari	One or more IDL variables (or expressions in the case of output).

The WRITEU procedure writes the contents of its arguments directly to the file, and READU reads exactly the number of bytes required by the size of its arguments. Both cases directly transfer binary data with no interpretation or formatting.

Unformatted Input/Output of String Variables

Strings are the only basic IDL data type that do not have a fixed size. A string variable has a dynamic length that is dependent only on the length of the string currently assigned to it. Thus, although it is always possible to know the length of the other types, string variables are a special case. IDL uses the following rules to determine the number of characters to transfer:

Input

Input enough bytes to fill the original length of the string. The length of the resulting string is truncated if the data contains a null byte.

Output

Output the number of bytes contained in the string. This number is the same number returned by the STRLEN function and does not include a terminating null byte.

Note that these rules imply that when reading into a string variable from a file, you must know the length of the original string so as to be able to initialize the destination string to the correct length. For example, the IDL statements,

OPENW, 1, 'temp.tmp'	Open a file.

WRITEU, 1, 'Hello World'	Write an 11-character string.

POINT_LUN, 1, 0	Rewind the file.

A = '         ' 	Prepare a nine-character string.

READU, 1, A 	Read back in the string.

PRINT, A	Show what was input.

CLOSE, 1

produce the following output, because the receiving variable A was not long enough:

Hello Wor

The only solution to this problem is to know the length of the string being input. The following IDL statements demonstrate a useful "trick" for initializing strings to a known length:

OPENW, 1, 'temp.tmp'	Open a file.

WRITEU, 1, 'Hello World'	Write an 11-character string.

POINT_LUN, 1, 0	Rewind the file.

A = STRING(REPLICATE(32B,11))	Create a string of the desired length initialized with blanks. The result of the call to REPLICATE is a byte array of 11 elements, each element initialized to 32, which is the ASCII code for a blank. Passing this byte array to STRING converts it to a scalar string containing 11 blanks.

READU, 1, A	Read in the string.

PRINT, A	Show what was input.

CLOSE, 1

This example takes advantage of the special way in which the BYTE and STRING functions convert between byte arrays and strings. See the description of the BYTE and STRING functions for additional details.

Example: Reading C-Generated Unformatted Data with IDL

The following C program produces a file containing employee records. Each record stores the first name of each employee, the number of years he has been employed, and his salary history for the last 12 months.

#include <stdio.h>

main()
{
    static struct rec {
             char name[32]; /* Employee's name */
             int years;     /* # of years with company */
             float salary[12]; /* Salary for last 12 months */
    } employees[] = {
{ {'B','u','l','l','w','i','n','k','l','e'}, 10,
      {1000.0, 9000.97, 1100.0, 0.0, 0.0, 2000.0,
   5000.0, 3000.0, 1000.12, 3500.0, 6000.0, 900.0} },{ {'B','o','r','r','i','s'}, 11,
      {400.0, 500.0, 1300.10, 350.0, 745.0, 3000.0,
   200.0, 100.0, 100.0, 50.0, 60.0, 0.25} },
{ {'N','a','t','a','s','h','a'}, 10,
      {950.0, 1050.0, 1350.0, 410.0, 797.0, 200.36,
   2600.0, 2000.0, 1500.0, 2000.0, 1000.0, 400.0} },
{ {'R','o','c','k','y'}, 11,
      {1000.0, 9000.0, 1100.0, 0.0, 0.0, 2000.37,
   5000.0, 3000.0, 1000.01, 3500.0, 6000.0, 900.12}}
};

    FILE *outfile;

    outfile = fopen("data.dat", "w");
    (void) fwrite(employees, sizeof(employees), 1, outfile);
    (void) fclose(outfile);
}

Running this program creates the file data.dat containing the employee records. The following IDL statements can be used to read and print this file:

STR32 = STRING(REPLICATE(32B, 32))	Create a string with 32 characters so that the proper number of characters will be input from the file. REPLICATE is used to create a byte array of 32 elements, each containing the ASCII code for a space (32). STRING turns this byte array into a string containing 32 blanks.

A = REPLICATE({EMPLOYEES, NAME:STR32, YEARS:0L, $

  SALARY:FLTARR(12)}, 4)	Create an array of four employee records to receive the input data.

OPENR, 1, 'data.dat'	Open the file for input.

READU, 1, A 	Read the data.

CLOSE, 1

PRINT, A	Show the results.

Executing these IDL statements produces the following output:

{ Bullwinkle          10
1000.00    9000.97    1100.00    0.00000     0.00000    2000.00
5000.00    3000.00    1000.12    3500.00    6000.00    900.000
}{ Borris             11
400.000    500.000    1300.10    350.000    745.000    3000.00
200.000    100.000    100.000    50.0000    60.0000    0.250000
}{ Natasha            10
950.000    1050.00    1350.00    410.000    797.000    200.360
2600.00    2000.00    1500.00    2000.00    1000.00    400.000
}{ Rocky              11
1000.00    9000.00    1100.00    0.00000    0.00000    2000.37
5000.00    3000.00    1000.01    3500.00    6000.00    900.120
}

Example: Reading IDL-Generated Unformatted Data with C

The following IDL program creates an unformatted data file containing a 5 x 5 array of floating-point values:

OPENW, 1, 'data.dat'	Open a file for output.

WRITEU, 1, FINDGEN(5, 5)	Write a 5 x 5 array with each element set to its one-dimensional index.

CLOSE, 1

This file can be read and printed by the following C program:

#include <stdio.h>

main()
{
    float data[5][5];
    FILE *infile; int i, j;
    infile = fopen("data.dat", "r");
    (void) fread(data, sizeof(data), 1, infile);
    (void) fclose(infile);
    for (i = 0; i < 5; i++) {
        for (j = 0; j < 5; j++)
            printf("%8.1f", data[i][j]);
            printf("\n");
    }
}

Running this program gives the following output:

     0.0     1.0     2.0     3.0     4.0
     5.0     6.0     7.0     8.0     9.0
    10.0    11.0    12.0    13.0    14.0
    15.0    16.0    17.0    18.0    19.0
    20.0    21.0    22.0    23.0    24.0

Example: Reading a Sun Rasterfile from IDL

Sun computers use rasterfiles to store scanned images. This example shows how to read such an image and display it using IDL. In the interest of keeping the example brief, a number of simplifications are made, no error checking is performed, and only 8-bit deep rasterfiles are handled. See the READ_SRF procedure (the file read_srf.pro in the lib sudirectory of the IDL distribution) for a complete example. The format used for rasterfiles is documented in the C header file /usr/include/rasterfile.h. That file provides the following information:

Each file starts with a fixed header that describes the image. This header is defined in C as follows:

struct rasterfile{
   int ras_magic; /* magic number */
   int ras_width; /* width (pixels) of image */
   int ras_height; /* height (pixels) of image */
   int ras_depth; /* depth (1, 8, or 24 bits) */
   int ras_length; /* length (bytes) of image */
   int ras_type; /* type of file */
   int ras_maptype; /* type of colormap */
   int ras_maplength; /* length(bytes) of colormap */ };

The color map, if any, follows directly after the header information. The image data follows directly after the color map.

The following IDL statements read an 8-bit deep image from the file ras.dat:

h = {rasterfile, magic:0L, width:0L, height:0L, depth: 0L,$

  length:0L, type:0L, maptype:0L, maplength:0L}
Define an IDL structure that matches the Sun-defined rasterfile structure. Note that a C integer variable on a Sun corresponds to an IDL LONG integer.

OPENR, unit, file, /GET_LUN	Open the file, allocating a file unit at the same time.

READU, unit, h	Read the header information.

IF ((h.maptype EQ 1) AND (h.maplength NE 0) ) THEN BEGIN
Is there a color map?

  maplen = h.maplength/3	Calculate length of each vector.

  r=(g=(b=BYTARR(maplen, /NOZERO)))	Create three byte vectors to hold the color map.

  READU, unit, r, g, b	Read the color map.

ENDIF

image = BYTARR(h.width, h.height, /NOZERO)
Create a byte array to hold the image.

READU, unit, image	Read the image.

FREE_LUN, unit	Free the previously-allocated Logical Unit Number and close the file.


Portable Unformatted Input/Output

Normally, unformatted input/output is not portable between different machine architectures because of differences in the way various machines represent binary data. However, it is possible to produce binary files that are portable by specifying the XDR keyword with the OPEN procedures. XDR (for eXternal Data Representation) is a scheme under which all binary data is written using a standard "canonical" representation. All machines supporting XDR understand this standard representation and have the ability to convert between it and their own internal representation.

XDR represents a compromise between the extremes of unformatted and formatted input/output:

•	It is not as efficient as purely unformatted input/output because it does involve the overhead of converting between the external and internal binary representations.

•	It is still much more efficient than formatted input/output because conversion to and from ASCII characters is much more involved than converting between binary representations.

•	It is much more portable than purely unformatted data, although it is still limited to those machines that support XDR. However, XDR is freely available and can be moved to any system.

XDR Considerations

The primary differences in the way IDL input/output procedures work with XDR files, as opposed to files opened normally are as follows:

•	To use XDR, you must specify the XDR keyword when opening the file.

•	The only input/output data transfer routines that can be used with a file opened for XDR are READU and WRITEU.

•	XDR converts between the internal and standard external binary representations for data instead of simply using the machine's internal representation.

•	Since XDR adds extra "bookkeeping" information to data stored in the file and because the binary representation used may not agree with that of the machine being used, it does not make sense to access an XDR file without using XDR.

•	OPENW and OPENU normally open files for both input and output. However, XDR files can only be opened in one direction at a time. Thus, using these procedures with the XDR keyword results in a file open for output only. OPENR works in the usual way.

•	The length of strings is saved and restored along with the string. This means that you do not have to initialize a string of the correct length before reading a string from the XDR file. (This is necessary with normal unformatted input/output and is described in "Unformatted Input/Output" on page 17-28).

•	For efficiency reasons, byte arrays are transferred as a single unit; therefore, byte variables must be initialized to the correct number of elements for the data to be input, or an error will occur. For example, given the statements,

OPENW, /XDR, 1, 'data.dat'	Open a file for XDR output.

WRITEU, 1, BINDGEN(10)	Write a 10-element byte array.

CLOSE, 1 & OPENR, /XDR, 1, 'data.dat'
Close the file and re-open it for input.

then the statement,

B = 0B & READU, 1, B	Try to read the first byte only.

results in the following error:

% READU: Error encountered reading from file unit: 1.

Instead, it is necessary to read the entire byte array back in one operation using a statement such as:

B=BYTARR(10) & READU, 1, B	Read the whole array back at once.

This restriction does not exist for other data types.

•	Under VMS, XDR is only possible with stream mode files.

IDL XDR Conventions for Programmers

IDL uses certain conventions for reading and writing XDR files. If your only use of XDR is through IDL, you do not need to be concerned about these conventions because IDL takes care of it for you. However, programmers who want to create IDL-compatible XDR files from other languages need to know the actual XDR routines used by IDL for various data types. The table below

Data Type	XDR routine
Byte	xdr_bytes()
Integer	xdr_short()
Long	xdr_long()
Float	xdr_float()
Double	xdr_double()
Complex	xdr_complex()
String	xdr_counted_string()
Table 17.9 XDR Routines Used by IDL

summarizes this information.

The routines used for type COMPLEX and STRING are not primitive XDR routines. Their definitions are as follows:

bool_t xdr_complex(xdrs, p)
     XDR *xdrs;
     struct complex { float r, i} *p;
{

  return(xdr_float(xdrs, (char *) &p->r) &&

         xdr_float(xdrs, (char *) &p->i));

}

bool_t xdr_counted_string(xdrs, p)
     XDR *xdrs;

     char **p;

{

  int input = (xdrs->x_op == XDR_DECODE);

  short length;

  /* If writing, obtain the length */
  if (!input) length = strlen(*p);

  /* Transfer the string length */
  if (!xdr_short(xdrs, (char *) &length)) return(FALSE);

  /* If reading, obtain room for the string */
  if (input)

  {
        *p = malloc((unsigned) (length + 1));
        *p[length] = '\0'; /* Null termination */
  }

  /* If the string length is nonzero, transfer it */
  return(length ? xdr_string(xdrs, p, length) : TRUE);
}

Example: Reading C-Generated XDR Data with IDL

The following C program produces a file containing different types of data using XDR. The usual error checking is omitted for the sake of brevity.

#include <stdio.h>
#include <rpc/rpc.h>
[ xdr_complex() and xdr_counted_string() included here ]

main()
{
    static struct {	/* Output data */
        unsigned char c;
        short s;
        long l;
        float f;
        double d;
        struct complex { float r, i } cmp;
        char *str;
    }
    data = {1, 2, 3, 4, 5.0, { 6.0, 7.0}, "Hello" };
    u_int c_len = sizeof(unsigned char); /* Length of a char */
    char *c_data = (char *) &data.c;     /* Addr of byte field */
    FILE *outfile;                       /* stdio stream ptr */
    XDR xdrs;                            /* XDR handle */

    /* Open stdio stream and XDR handle */
    outfile = fopen("data.dat", "w");
    xdrstdio_create(&xdrs, outfile, XDR_ENCODE);

    /* Output the data */
    (void) xdr_bytes(&xdrs, &c_data, &c_len, c_len);
    (void) xdr_short(&xdrs, (char *) &data.s);
    (void) xdr_long(&xdrs, (char *) &data.l);
    (void) xdr_float(&xdrs, (char *) &data.f);
    (void) xdr_double(&xdrs, (char *) &data.d);
    (void) xdr_complex(&xdrs, (char *) &data.cmp);
    (void) xdr_counted_string(&xdrs, &data.str);

    /* Close XDR handle and stdio stream */
    xdr_destroy(&xdrs);
    (void) fclose(outfile);
}

Running this program creates the file data.dat containing the XDR data. The following IDL statements can be used to read this file and print its contents:

DATA={S, C:0B, S:0, L:0L, F:0.0, D:0.0D, CMP:COMPLEX(0), STR: ''}
Create structure containing correct types.

OPENR, /XDR, 1, 'data.dat'	Open the file for input.

READU, 1, DATA	Read the data.

CLOSE, 1	Close the file.

PRINT, DATA	Show the results.

Executing these IDL statements produces the output:

{   1       2           3      4.00000       5.0000000
(      6.00000,      7.00000) Hello}

For further details about XDR, consult the XDR documentation for your machine. Sun users should consult their Network Programming manual.


Associated Input/Output

Unformatted data stored in files often consists of a repetitive series of arrays or structures. A common example is a series of images. IDL-associated file variables offer a convenient and efficient way to access such data.

An associated variable is a variable that maps the structure of an IDL array or structure variable onto the contents of a file. The file is treated as an array of these repeating units of data. The first array or structure in the file has an index of zero, the second has index one, and so on. Such variables do not keep data in memory like a normal variable. Instead, when an associated variable is subscripted with the index of the desired array or structure within the file, IDL performs the input/output operation required to access the data.

When their use is appropriate (the file consists of a sequence of identical arrays or structures), associated file variables offer the following advantages over READU and WRITEU for unformatted input/output:

•	Input/output occurs when an associated file variable is subscripted. Thus, it is possible to perform input/output within an expression without a separate input/output statement.

•	The size of the data set is limited primarily by the maximum size of the file containing the data instead of the maximum memory available. Data sets too large for memory can be accessed.

•	There is no need to declare the maximum number of arrays or structures contained in the file.

•	Associated variables systematize access to the data. Direct access to any element in the file is rapid and simple—there is no need to calculate offsets into the file and/or position the file pointer prior to performing the input/output operation.

•	Associated variables are the most efficient form of IDL input/output.

An associated file variable is created by assigning the result of the ASSOC function to a variable. ASSOC takes the following three parameters:

Unit

The logical file unit with which the variable is to be associated.

Array_Structure

An array or structure expression that defines the type and structure of the data in the file.
Note: Only the form of this parameter is used by ASSOC—its value is ignored.

Offset

The offset in the file to the start of the data in the file. Under UNIX, the offset is given in bytes. Under VMS, stream files and RMS (VMS) block mode files have their offset given in bytes while record-oriented files have it specified in records.

To determine the actual file position at which to start a read or write operation, IDL adds Offset to the position determined by the subscripts to the associated variable. If Offset is not specified, zero (the start of the file) is assumed. Offset is useful for dealing with data files that contain a descriptive header block followed by the actual data.

Example of Using Associated Input/Output

Assume that a file named data.dat exists, and that this file contains a series of 10 x 20 arrays of floating-point data. The following two IDL statements open the file and create an associated file variable mapped to the file:

OPENU, 1, 'data.dat'	Open the file.

A = ASSOC(1, FLTARR(10, 20, /NOZERO))	Make a file variable. Using the NOZERO keyword with FLTARR increases efficiency.

The order of these two statements is not important—it would be equally valid to call ASSOC first, and then open the file. This is because the association is between the variable and the logical file unit, not the file itself. It is also legitimate to close the file, open a new file using the same LUN, and then use the associated variable without first executing a new ASSOC. Naturally, an error occurs if the file is not open when the file variable is subscripted in an expression or if the file is open for the wrong type of access (for example, trying to assign to an associated file variable linked with a file opened for read-only access).

As a result of executing the two statements above, the variable A is now an associated file variable. Executing the statement,

HELP, A

gives the following response:

A               FLOAT     = File<data.dat> Array(10, 20)

The associated variable A maps the structure of a 10 x 20, floating-point array onto the contents of the file data.dat. Thus, the response from the HELP procedure shows it as having the structure of a two-dimensional array. An associated file variable only performs input/output to the file when it is subscripted. Thus, the following two IDL statements do not cause input/output to happen:

B = A

This assignment does not transfer data from the file to variable B because A is not subscripted. Instead, B becomes an associated file variable with the same structure, and to the same logical file unit, as A.

B = 23

This assignment does not result in the value 23 being transferred to the file because variable B (which became a file variable in the previous statement) is not subscripted. Instead, B becomes a scalar integer variable containing the value 23. It is no longer an associated file variable.

Reading Data from Associated Files

Once a variable has been associated with a file, data are read from the file whenever the associated variable appears in an expression with a subscript. The position of the array or structure read from the file is given by the value of the subscript. The following IDL statements give some examples of using file variables:

Z = A(0)	Copy the contents of the first array into normal variable Z. Z is now a 10 x 20, floating-point array.

FOR I = 1, 9 DO Z = Z + A(I)	Form the sum of the first 10 arrays (Z was initialized in the previous statement to the value of the first array. This statement adds the following nine to it.).

PLOT, A(3)	Read fourth array and plot it.

PLOT, A(5) - A(4)	Subtract array four from array five, and plot the result. The result of the subtraction is then discarded.

Subscripting Associated File Variables on Input

When the structure associated with a file variable is an array, it is possible to subscript into the array being accessed during input operations. For example, for the variable A defined above,

Z = A(0, 0, 1)

assigns the value of the first floating-point element of the second array within the file to the variable Z. The rightmost subscript is taken as the subscript into the file causing IDL to read the entire array into memory. This resulting array expression is then further subscripted by the remaining subscripts.

Note: Although this ability can be convenient, it also can be very slow because every access to an array element causes the entire array to be read from memory. Unless only one element of the array is desired, it is faster to assign the contents of the array to a normal variable by subscripting the file variable with a single subscript, then accessing the individual array elements in the normal variable.

Writing Data

When a subscripted, associated variable appears on the left side of an assignment statement, the expression on the right side is written into the file at the given array position:

A(5) = FLTARR(10, 20)	Sets sixth record to zero.

A(5) = ARR	Writes ARR into the sixth record after any necessary type conversions.

A(J) = (A(J) + A(J + 1))/2	Averages records J and J+1, and writes the result into record J.

When writing data, only a single subscript specifying the index of the affected array or structure in the file is allowed. Thus, it is not possible to index individual elements of associated arrays on output, although it is allowed for input. To update individual elements of an array within a file, assign the contents of that array to a normal array variable, modify the copy, and write the array back by assigning it to the subscripted file variable.

Files with Multiple Structures

The same file may be associated with a number of different structures. Assume a number of 128 x 128-byte images are contained on a file. The statement,

ROW = ASSOC(1, BYTARR(128))

will map the file into rows of 128 bytes each. ROW(3) is the fourth row of the first image, while ROW(128) is the first row of the second image. The statement,

IMAGE = ASSOC(1, BYTARR(128, 128))

maps the file into entire images; IMAGE(4) will be the fifth image.

Offset Parameter

The Offset parameter to ASSOC specifies the position in the file at which the first array starts. This parameter is useful when a file contains a header followed by data records. For example, if a UNIX file uses the first 1,024 bytes of the file to contain header information, followed by 512 x 512-byte images, the statement,

IMAGE = ASSOC(1, BYTARR(512, 512), 1024)

sets the variable IMAGE to access the images while skipping the header.

Under VMS, stream files and RMS block mode files have their offset given in bytes, and record-oriented files have it specified in records. Thus, the example above would have worked for VMS if the file was a stream or block mode file. Assume however, that the file has 512-byte, fixed-length records. In this case, skipping the first 1,024 bytes is equivalent to skipping the first two records:

IMAGE = ASSOC(1, BYTARR(512, 512), 2)

Efficiency

Arrays are accessed most efficiently if their length is an integer multiple of the physical block size of the disk holding the file. Common values are 512, 1,024, and 2,048 bytes. For example, on a disk with 512-byte blocks, one benchmark program required approximately one-eighth of the time required to read a 512 x 512-byte image that started and ended on a block boundary, as compared to a similar program that read an image that was not stored on even block boundaries.

Each time a subscripted, associated variable is referenced, one or more records are read from or written to the file. Therefore, if a record is to be accessed more than a few times, it is more efficient to read the entire record into a variable. After making the required changes to the in-memory variable, it can be written back to the file if necessary.

Unformatted Data from UNIX FORTRAN Programs

Unformatted data files generated by FORTRAN programs under UNIX contain an extra long word before and after each logical record in the file. ASSOC does not interpret these extra bytes but considers them to be part of the data. This is true even if the F77_UNFORMATTED keyword is specified on the OPEN statement. Therefore, ASSOC should not be used with such files. Instead, such files should be processed using READU and WRITEU. An example of using IDL to read such data is given in "Unformatted Input/Output" on page 17-28.


Miscellaneous File Manipulation Information

Locating Files

The FINDFILE function returns an array of strings containing the names of all files that match its argument string. The argument string may contain any wildcard characters understood by the command interpreter. Under VMS, this is DCL. Under UNIX, it is the Bourne shell (/bin/sh). Under Windows it is COMMAND.COM. On the Macintosh, standard Macintosh OS wildcard characters are supported. For example, to determine the number of IDL procedure files that exist in the current directory, use the following statement:

PRINT, '# IDL pro files:',N_ELEMENTS(FINDFILE('*.pro'))

Getting Help and Information

Information about currently open file units is available by using the FILES keyword with the HELP procedure. If no arguments are provided, information about all currently open user file units (units 1­128) is given. For example, the following command can be used to get information about the three special units (−2, −1, and 0):

HELP, /FILES, -2, -1, 0

This command results in output similar to the following:

Unit   Attributes              Name
-2     Write, New, Tty, Reserved     <stderr>
-1     Write, New, Tty, Reserved     <stdout>
 0     Read, Tty, Reserved         <stdin>

The FSTAT Function

The FSTAT function can be used to get more detailed information, as well as information that can be used from within an IDL program. It returns a structure expression of type FSTAT containing information about the file. For example, to get detailed information about the standard input, the command,

HELP, /STRUCTURES, FSTAT(0)

causes the following to be displayed on the screen:

** Structure FSTAT, 12 tags, length=48:

   UNIT            LONG              0

   NAME            STRING    '<stdin>'

   OPEN            BYTE         1

   ISATTY          BYTE         1

   ISAGUI          BYTE         0

   INTERACTIVE     BYTE         1

   READ            BYTE         1

   WRITE           BYTE         0

   TRANSFER_COUNT  LONG                 0

   CUR_PTR         LONG             51550

   SIZE            LONG                 0

   REC_LEN         LONG                 0

Since IDL allows keywords to be abbreviated to the shortest nonambiguous number of characters,

HELP, /ST, FSTAT(0)

also will work (and save some typing). The fields of the FSTAT structure provide the following information:

UNIT

The IDL logical unit number (LUN).

NAME

The name of the file.

OPEN

Nonzero if the file unit is open. If OPEN is zero, the remaining fields in FSTAT will not contain useful information.

ISATTY

Nonzero if the file is actually a terminal instead of a normal file. For example, if you are using an xterm window on a Unix system and you invoke FSTAT on logical unit 0 (standard input), ISATTY will be set to 1.

ISAGUI

Nonzero if the file is actually a Graphical User Interface (for example, a logical unit associated with IDLTool, IDL for Windows, or IDL for Macintosh). Thus, if you are using IDLTool and you invoke FSTAT on logical unit 0 (standard input), ISAGUI will be set to 1.

INTERACTIVE

Nonzero if either ISATTY or ISAGUI is nonzero.

READ

Nonzero if the file is open for read access.

WRITE

Nonzero if the file is open for write access.

TRANSFER_COUNT

The number of scalar IDL data items transferred in the last input/output operation on the unit. This is set by the following IDL routines: READU, WRITEU, PRINT, PRINTF, READ, and READF. TRANSFER_COUNT is useful when attempting to recover from input/output errors.

CUR_PTR

The current position of the file pointer, given in bytes from the start of the file. If the device is a terminal (ISATTY is nonzero), the value of CUR_PTR will not contain useful information.

SIZE

The current length of the file in bytes. If the device is a terminal (ISATTY is nonzero), the value of SIZE will not contain useful information.

REC_LEN

If the file is record-oriented (VMS), this field contains the record length; otherwise, it is zero.

An Example Using FSTAT

The following IDL function can be used to read single-precision, floating-point data from a stream file into a vector when the number of elements in the file is not known. It uses the FSTAT function to get the size of the file in bytes and divides by four (the size of a single-precision, floating-point value) to determine the number of values. Note that this approach will not work with VMS variable-length record files:

FUNCTION READ_DATA, file	READ_DATA reads all the floating point values from a stream file and returns the result as a floating-point vector.

OPENR, /GET_LUN, unit, file	Get a unique file unit and open the data file.

status = FSTAT(unit)	Get file status.

data = FLTARR(status.size / 4)	Make an array to hold the input data. The SIZE field of status gives the number of bytes in the file, and single-precision, floating-point values are four bytes each.

READU, unit, data	Read the data.

FREE_LUN, unit 	Deallocate the file unit. The file also will be closed.

RETURN, data	Done.

END

Assuming that a file named data.dat exists and contains 10 floating-point values, the READ_DATA function could be used as follows:

A = READ_DATA('data.dat')	Read floating-point values from data.dat.

HELP, A	Show the result.

The following output is produced:

A               FLOAT     = Array(10)

Flushing File Units

For efficiency, IDL buffers its input/output in memory. Therefore, when data are output, there is a window of time during which data are in memory and have not been actually placed into the file. Normally, this behavior is transparent to the user (except for the improved performance). The FLUSH routine exists for those rare occasions where a program needs to be certain that the data has actually been written to the file immediately. For example, use the statement,

FLUSH, 1

to flush file unit one.

Positioning File Pointers

Each open file unit has a current file pointer associated with it. This file pointer indicates the position in the file at which the next input/output operation will take place. The file position is specified as the number of bytes from the start of the file. The first position in the file is position zero. The following statement will rewind file unit 1 to its start:

POINT_LUN, 1, 0

The following sequence of statements will position it at the end of the file:

tmp = FSTAT(1)

POINT_LUN, 1, tmp.size

POINT_LUN has the following operating-system specific behavior:

♦	UNIX: the current file pointer can be positioned arbitrarily ­ moving to a position beyond the current end-of-file causes the file to grow out to that point. The gap created is filled with zeroes.

♦	VMS stream files: the current file pointer can be positioned arbitrarily ­ moving to a position beyond the current end-of-file causes the file to grow out to that point. The gap created is filled with zeroes.

♦	VMS block mode and record-oriented files: attempting to move the pointer past the current end-of-file causes an end-of-file error.

♦	VMS record-oriented files: the file pointer should only be set to record boundaries. Setting it to other positions can result in unexpected behavior.

♦	Windows: the current file pointer can be positioned arbitrarily ­ moving to a position beyond the current end-of-file causes the file to grow out to that point. Unlike UNIX, the gap created is filled with arbitrary data instead of zeroes.

♦	Macintosh: the current file pointer cannot be positioned past the end of the file.

Testing for End-Of-File

The EOF function is used to test a file unit to see if it is currently positioned at the end of the file. It returns true (1) if the end-of-file condition is true and false (0) otherwise.

Note the non-diskfile devices always return "false" and, under VMS, non-sequential files or files opened across DECnet always return "false".

For example, to read the contents of a file and print it on the screen, use the following statements:

OPENR, 1, 'demo.doc'	Open file demo.doc for reading.

LINE = ''	Create a variable of type string.

WHILE(NOT EOF(1)) DO BEGIN READF,1,LINE & PRINT,LINE & END
Read and print each line until the end of the file is encountered.

CLOSE, 1 	Done with the file.

GET_KBRD

The GET_KBRD function returns the next character available from the standard input (IDL file unit zero) as a single character string. It takes a single parameter named WAIT. If WAIT is zero, the function returns the null string if there are no characters in the terminal typeahead buffer. If it is nonzero, the function waits for a character to be typed before returning.

Under Windows, the GET_KBRD function can be used to return Windows special characters (in addition to the standard keyboard characters). To get a special character, hold down the Alt key and type the character's ANSI equivalent on the numeric keypad while GET_KBRD is waiting. Control + key combinations are not supported.

Example—Using GET_KBRD

A procedure that updates the screen and exits when the carriage return is typed might appear as follows:

PRO UPDATE, ... 	Procedure definition.

WHILE 1 DO BEGIN	Loop forever.

... 	Update screen here...

CASE GET_KBRD(0) OF	Read character, no wait.

'A': .... 	Process letter A.

'B': .... 	Process letter B.

...	Process other alternatives.

STRING("15B): RETURN	Exit on carriage return (ASCII code = 15 octal).

ELSE:	Ignore all other characters.

ENDCASE

ENDWHILE

END	End of procedure.

Using the STRING Function to Format Data

The STRING function is very similar to the PRINT and PRINTF procedures. It can be thought of as a version of PRINT that places its formatted output into a string variable instead of a file. If the output is a single line, the result is a scalar string. If the output has multiple lines, the result is a string array with each element of the array containing a single line of the output.

Example—Using STRING with Explicit Formatting

The IDL statements:

A=STRING(FORMAT='("The values are:", /, (I))', INDGEN(5))
Produce a string array.

HELP, A	Show its structure.

FOR I = 0, 5 DO PRINT, A(I)	Print out the result.

produce the following output:

A               STRING    = Array(6)
The values are:
      0
      1
      2
      3
      4

For additional details about the STRING function, see the description in the IDL Reference Guide.

Reading Data from a String Variable

The READS procedure performs formatted input from a string variable and writes the results into one or more output variables. This procedure differs from the READ procedure only in that the input comes from memory instead of a file.

This routine is useful when you need to examine the format of a data file before reading the information it contains. Each line of the file can be read into a string using READF. Then the components of that line can be read into variables using READS.

See the description of READS in the IDL Reference Guide for more details.


UNIX-Specific Information

UNIX offers only a single type of file. All files are considered to be an uninterpreted stream of bytes, and there is no such thing as record structure at the operating system level. (By convention, records of text are simply terminated by the linefeed character, which is referred to as "newline.") It is possible to move the current file pointer to any arbitrary position in the file and to begin reading or writing data at that point. This simplicity and generality form a system in which any type of file can be manipulated easily using a small set of file operations.

Reading FORTRAN-Generated Unformatted Data with IDL

The UNIX file system considers all files to be an uninterpreted stream of bytes. Standard FORTRAN I/O considers all input/output to be done in terms of logical records.

In order to reconcile the FORTRAN need for logical records with UNIX files, UNIX FORTRAN programs add a longword count before and after each logical record of data. These longwords contain an integer count giving the number of bytes in that record. Note that direct-access FORTRAN I/O does not write data in this format, but simply transfers binary data to or from the file.

The use of the F77_UNFORMATTED keyword with the OPENR statement informs IDL that the file contains unformatted data produced by a UNIX FORTRAN program. When a file is opened with this keyword, IDL interprets the longword counts properly and is able to read and write files that are compatible with FORTRAN.

Reading data from a FORTRAN file

The following UNIX FORTRAN program produces a file containing a five-column by three-row array of floating-point values with each element set to its one-dimensional subscript:

    PROGRAM ftn2idl

    INTEGER i, j

    REAL data(5, 3)

    OPEN(1, FILE="ftn2idl.dat", FORM="unformatted")

      DO 100 j = 1, 3

        DO 100 i = 1, 5

          data(i,j) = ((j - 1) * 5) + (i - 1)

          print *, data(i,j)

100 CONTINUE

    WRITE(1) data

    END

Running this program creates the file ftn2idl.dat containing the unformatted array. The following IDL statements can be used to read this file and print out its contents:

data = FLTARR(5,3)	Create an array to contain the fortran array.

OPENR, lun, 'ftn2idl.dat', /GET_LUN, /F77_UNFORMATTED
Open the fortran-generated file. The F77_UNFORMATTED keyword is necessary so that IDL will know that the file contains unformatted data produced by a UNIX FORTRAN program.

READU, lun, data	Read the data in a single input operation.

FREE_LUN, lun	Release the logical unit number and close the fortran file.

PRINT, data	Print the result.

Executing these IDL statements produces the following output:

0.00000      1.00000      2.00000      3.00000      4.00000
5.00000      6.00000      7.00000      8.00000      9.00000
10.0000      11.0000      12.0000      13.0000      14.0000

Warning: Because unformatted data produced by UNIX FORTRAN unformatted WRITE statements are interspersed with extra information before and after each logical record, it is important that the IDL program read the data in the same way that the FORTRAN program wrote it. For example, consider the following attempt to read the above data file one row at a time:

data = FLTARR(5, /NOZERO)	Create an array to contain one row of the Fortran array.

OPENR, lun, 'ftn2idl.dat', /GET_LUN, /F77_UNFORMATTED

FOR I = 0, 4 DO BEGIN	One row at a time.

READU, lun, data	Read a row of data.

PRINT, data	Print the row.

ENDFOR

FREE_LUN, lun	Close the file.

Executing these IDL statements produces the output:

0.00000      1.00000      2.00000      3.00000      4.00000

% READU: End of file encountered. Unit: 100

         File: ftn2idl.dat

% Execution halted at $MAIN$(0).

Here, IDL attempted to read the single logical record written by the FORTRAN program as if it were written in five separate records. IDL hit the end of the file after reading the first five values of the first record.

Writing data to a FORTRAN file

The following IDL statements create a five-column by three-row array of floating-point values with each element set to it's one-dimensional subscript, and writes the array to a data file suitable for reading by a FORTRAN program:

data = FINDGEN(5,3)	Create the array.

OPENW, lun, 'idl2ftn.dat', /GET_LUN, /F77_UNFORMATTED
Open a file for writing. Note that the F77_UNFORMATTED keyword is necessary to tell IDL to write the data in a format readable by a FORTRAN program.

WRITEU, lun, data	Write the data.

FREE_LUN, lun	Close the file.

The following FORTRAN program reads the data file created by IDL:

    PROGRAM idl2ftn

    INTEGER i, j

    REAL data(5, 3)

    OPEN(1, FILE="idl2ftn.dat", FORM="unformatted")

    READ(1) data

      DO 100 j = 1, 3

        DO 100 i = 1, 5

          PRINT *, data(i,j)

100 CONTINUE

    END


VMS-Specific Information

Input/output under VMS is a relatively complex topic, involving a large number of formats and options. VMS files are record-oriented, and it is necessary to take this into account when writing applications, especially those that will run under other operating systems. The VMS user faces decisions in the following areas:

Organization

A VMS file can have sequential, relative, or indexed organization. The organization controls the way in which data is placed in the file and determines the options for random access. IDL is able to read data from all three organizations and is able to create sequential or indexed files.

In addition, it is possible to bypass the organization and access a file in "block mode." In block mode, most VMS file processing is bypassed. The IDL user can access a block mode file as if it were simply a stream of uninterpreted bytes. This is very similar to stream files (although considerably more efficient).

Caution: With some file organizations, VMS intermingles housekeeping information with data. When accessing such a file in block mode, it is easy to corrupt this information and render the file unusable in its usual mode; however, block mode will always work. Avoiding such corruption is the user's responsibility.

Access

The access mode controls how data in a file are accessed. VMS supports sequential access, random access by key value (indexed files), relative record number (relative files), or relative file address (all file organizations). IDL does not support access by relative record number—files are accessed sequentially or through key value. Random access for sequential files is allowed by file address using the POINT_LUN procedure.

Record Format

VMS supports fixed-length records, variable-length records, variable length with fixed-length control field (VFC), and stream format. Of these, the fixed-length and variable-length record formats are the most useful and are fully supported by IDL.

It is possible to read the data portion of a VFC file, but not the control field. All access to stream mode files under IDL is done through the Standard C Library. It is worth noting that VMS stream files are record oriented (and therefore, fail to provide much of the flexibility of UNIX stream files) although the VMS Standard C Library (upon which IDL is implemented) does a good job of concealing this limitation. Our experience indicates that input/output using VMS stream mode files is dramatically slower than the other options and should be avoided when possible. For unformatted data, using block mode can give similar flexibility as well as high efficiency.

Byte Value	ASCII Character	Meaning
0	(null)	No carriage control—output data directly.
32	(space)	Single-space. A linefeed precedes the output data, and a carriage return follows.
48	0	Double-space. Two linefeeds precede the output data, and a carriage return follows.
49	1	Page eject. A formfeed precedes the data, and a carriage return follows.
40	+	Overprint. A carriage return follows the data, causing the next output line to overwrite the current one.
36	$	Prompt. A linefeed precedes the data, but no carriage return follows.
other		Same as ASCII space character. Single-space carriage control
Table 17.10 VMS FORTRAN Carriage Control

Record Attributes

When a record is output to the screen or printer, VMS uses its carriage control attributes to determine how to output each line. Explicit carriage control specifies that VMS should do nothing, and the user will provide the appropriate carriage control (if any) in the data. Carriage-return carriage control specifies that each line should be preceded by a line feed and followed by a carriage return. FORTRAN carriage control indicates that the first byte of each record contains a FORTRAN carriage control character. The possible values of this byte are given in Table 17.10. The default for IDL is carriage-return carriage control.

File Attributes

There are many file attributes that can be adjusted to suit various requirements. These attributes allow specifying the default name, the initial size of new files, the amount by which files are extended, whether the file is printed or sent to a batch queue when closed, file sharing between processes, etc.

How IDL Handles Records

With record-oriented files, IDL always transfers at least a single record of data. If the amount of data required exceeds a single record, more input/output occurs. For example, consider the case of a file open on unit 1 for output with 80-character records. The statement,

WRITEU, UNIT, FINDGEN(512)

requires 2,048 bytes to be output (each floating-point value takes four bytes), and thus, causes 26 records to be output. The last record will not be entirely full and is padded at the end with zeroes.

On later input, the same rule is applied in reverse —26 records are read, and the unused portion of the last one is discarded. The basic rule of input/output with record-oriented files is that the form of the input and output statements should match. For instance, the statements,

WRITEU, UNIT, A

WRITEU, UNIT, B

WRITEU, UNIT, C

generate three output records and should be later input with statements of the following form:

READU, UNIT, A

READU, UNIT, B

READU, UNIT, C

In contrast, the statement

WRITEU, UNIT, A, B, C

generates a single-output record and should be later input with the following single statement:

READU, UNIT, A, B, C

Reading FORTRAN-Generated Unformatted Data with IDL

The following VMS FORTRAN program produces a file containing a 5 x 5 array of floating-point values with each element set to its one-dimensional subscript:

     INTEGER I, J REAL DATA(5, 5)
     OPEN(1, FILE='data.dat', FORM='unformatted', status='new')
     DO 100 J = 1, 5
       DO 100 I = 1, 5
         DATA(I,J) = ((J-1) * 5) + (I-1)
 100 CONTINUE
     WRITE(1) DATA
     END

Running this program creates the file data.dat containing the unformatted data. By default, VMS FORTRAN programs create such files using segmented records, which is a scheme used by FORTRAN to write data records with lengths that exceed the actual record lengths allowed by VMS. Each segmented record is written as one or more actual VMS records. Each of the actual records has a 2-byte control field prepended that allows FORTRAN to reconstruct the original record. IDL is able to read and write segmented record files if the OPEN statement, used to access the file, includes the SEGMENTED keyword. The following IDL statements can be used to read this file and print out its contents:

OPENR, 1, 'data.dat', /SEGMENTED	Open the file. The SEGMENTED keyword is necessary so that IDL will know that the file contains VMS FORTRAN segmented records.

A = FLTARR(5, 5, /NOZERO)	Create an array to contain the array.

READU, 1, A	Read the data in a single input operation.

PRINT, A	Print the result.

Executing these IDL statements produces the following output:

      0.00000 1.00000 2.00000 3.00000 4.00000
      5.00000 6.00000 7.00000 8.00000 9.00000
      10.0000 11.0000 12.0000 13.0000 14.0000
      15.0000 16.0000 17.0000 18.0000 19.0000
      20.0000 21.0000 22.0000 23.0000 24.0000

As with all record-oriented input/output, it is important that the IDL program read the data in the same way it was written by the FORTRAN program. For example, consider the following attempt to read the above data file one row at a time:

Create an array to contain one row of the array.

OPENR, 1, 'DATA.DAT', /SEGMENTED

A = FLTARR(5, /NOZERO)

FOR I = 0, 4 DO BEGIN $	One row at a time.

READU, 1, A $	Read a row of data.

PRINT, A $	Print the row.

ENDFOR

Executing these IDL statements produces the following output:

0.00000      1.00000      2.00000      3.00000      4.00000
% End of file encountered on file unit: 1.
% Execution halted at $MAIN$(0).

This program attempted to read the single logical record written by the FORTRAN program as if it were written in five separate records and so, hit the end of the file after reading the first five values of the first record.

Indexed Files

Creating Indexed Files

Although IDL can read and write indexed files, it cannot create them. The options for creating indexed files are so numerous that they should be specified using the VMS CREATE/FDL command. FDL (File Definition Language) is the standard method for specifying VMS file attributes. The VAX/VMS File Definition Language Facility Reference Manual (1986) describes FDL in detail. It is often useful to start with the FDL description for an existing file and then modify it to suit your new application. The VMS command,

$ ANALYZE/RMS FILE/FDL file.dat

creates a file named file.fdl containing the FDL description for file.dat. The following is an example of an FDL description for an indexed file named data.dat with two keys. The first key is a 32-character string containing an employee name. The second is a 4-byte integer containing the current salary for that employee:

FILE
    NAME data.dat
    ORGANIZATION indexed
RECORD
    SIZE 36
KEY 0
    NAME "Name"
    SEG0_LENGTH 32
    SEG0_POSITION 0
    TYPE string
KEY 1
    CHANGES yes
    NAME "Salary"
    SEG0_LENGTH 4
    SEG0_POSITION 32
    TYPE bin4

Assume that this description resides in a file named data.fdl. The following IDL statement can be used to create data.dat:

SPAWN, 'create/fdl = data.fdl'

Once the file exists, it can be opened within IDL using the KEYED keyword with the OPENR or OPENU procedures.

Using Indexed Files

Given a file created using the FDL description in the previous section, the IDL statements below do four things:

•	Add some employee records to the file

•	Print the records out sorted by name

•	Give an employee a raise

•	Print the records sorted by increasing salary

IDL is able to perform both formatted and unformatted input/output with indexed files.
In this instance, unformatted access is required because the record definition contains a binary field (salary).

OPENU, UNIT, 'data.dat', /KEY, /GET_LUN
Open the previously created, empty file.

WRITEU, UNIT, STRING('Natasha', FORMAT = "(A,T33)"), 14257L
Add the first record. The STRING function is used to pad the name to 32 characters using space characters because the data must match the FDL description of the file exactly.

WRITEU, UNIT, STRING('Bullwinkle', FORMAT = "(A,T33)"), 32501L
Second record.

WRITEU, UNIT, STRING('Rocky', FORMAT = "(A,T33)"), 32500L
Third record.

WRITEU, UNIT, STRING('Borris', FORMAT = "(A,T33)"), 6805L
Fourth and last record.

READ_BY_INDEX, UNIT, 0, 'a', 'By Name:'
Print the contents of the file, sorted by name. READ_BY_INDEX is a procedure (described below) that does the actual work.

NAME = STRING(REPLICATE(32B, 32))	In preparation for giving a raise, make variables to read the current information on the employee.

SALARY = 0L

READU, UNIT, NAME, SALARY, KEY_VALUE = 'Bullwinkle'
Read the record for employee Bullwinkle.

WRITEU, UNIT, NAME, SALARY + 10000L, /REWRITE
Update Bullwinkle's record with an increased salary. The REWRITE keyword causes the last input record to be overwritten, instead of creating a new record.

READ_BY_INDEX, UNIT, 1, 0L, 'By Salary:'
Print the contents of the file, sorted by salary.

FREE_LUN, UNIT	Free the file unit, and close the file.

The procedure READ_BY_INDEX is implemented as follows:

PRO READ_BY_INDEX, UNIT, KI, KV, HEADING
Print the contents of the file sorted on the index given by KI. KV is the value the first record should be matched against. Heading is a banner comment to be printed before the file contents.

FIRST = 1 	Indicates first trip through main loop.

NAME = STRING(REPLICATE(32B, 32))	Prepare variables to read the records into.

SALARY = 0L

ON_IOERROR, EOD	The EOF function does not work with indexed files, so we will use ON_IOERROR to catch attempts to read too far.

WHILE 1 DO BEGIN 	Loop will be exited on end-of-file.

  IF (FIRST) THEN BEGIN	First iteration.

    PRINT, FORMAT='(/, a)', HEADING)	Output the heading.

    READU, UNIT, NAME, SALARY, KEY_ID = KI, KEY_MATCH = 1, $

    KEY_VALUE = KV	On first iteration, use keywords to locate the first record.

    FIRST = 0 	Indicate that first iteration has happened.

  ENDIF ELSE BEGIN
After the first iteration, use normal input statement to read sequentially.

    READU, UNIT, NAME, SALARY

  ENDELSE
Print the record.

  PRINT, FORMAT = '(4X, A, T15, I)', NAME, SALARY

ENDWHILE

EOD:	When the above loop tries to read past end-of-file, execution will be transferred here.

END

Executing the above statements gives the following output:

By Name:
    Borris                    6805
    Bullwinkle               32501
    Natasha                  14257
    Rocky                    32500
By Salary:
    Borris                    6805
    Natasha                  14257
    Rocky                    32500
    Bullwinkle               42501

Magnetic Tape

Under VMS, IDL offers procedures to directly access magnetic tapes. Data are transferred between the tape and IDL arrays without using RMS. Optionally, tapes from IBM mainframe compatible systems may be read or written with odd/even byte reversal. The routines used to access magnetic tape directly are as follows:

REWIND

Rewind a tape unit.

SKIPF

Skip records or files.

TAPRD

Read from tape.

TAPWRT

Write to tape.

WEOF

Write an end-of-file mark on tape.

To use the IDL magnetic tape procedures, you must define a logical name MTn: to be equivalent to the actual name of the tape drive you wish to use. This definition must be done before invoking IDL. You also must have the tape mounted as a foreign volume.

For example, if you wish to access the tape drive MUA0: as IDL tape unit number one, issue the following VMS commands before running IDL:

$ MOUNT/FOREIGN MUA0:

$ DEFINE MT1 MUA0:

Then, within IDL, refer to the tape as unit number one. The IDL unit number n may range from 0 to 9.

Note: These unit numbers are not the same as the LUN's used by the other input/output routines. The unit numbers used by the magnetic tape routines are completely unrelated and come from the last letter of the MT* logical name used to refer to it.

Magnetic Tape Examples

The following statements skip forward 30 records on the tape mounted on the drive with the logical name MT2: and print a message if an end-of-file was encountered.

SKIPF, 2, 30, 1	Skip forward over 30 records on unit 2.

IF !ERR NE 30 THEN PRINT, 'end-of-file hit'
Print a message if the requested number of records were not skipped.

The next example skips two files backwards and then positions the tape immediately after the second file mark encountered in reverse.

SKIPF, 0, -2 	Go backwards two files.
Position after file if two files were actually skipped.

IF !ERR EQ -2 THEN SKIPF, 0, 1

The following code segment reads a 512 x 512-byte image from the tape which is assigned the logical name MT5. It is assumed that the data are written in 2,048-byte tape blocks.

a = BYTARR(512, 512)	Define image array.

b = BYTARR(512, 4)	Define an array to hold one tape block worth of data.

FOR I = 0, 511, 4 DO BEGIN

    TAPRD, B, 5	Read next record.

    A(0, I) = B	Insert four rows starting at i-th row.

ENDFOR

Assuming the tape is actually on drive MXB2:, the mount command, which must be issued to VMS before entering IDL, is as follows:

$ MOUNT MXB2:/FOR "" MT5	This command serves to both mount the tape and define the logical name MT5 to refer to it, thus making it unit 5 within IDL.

References

Digital Equipment Corporation (1986), VAX/VMS File Definition Language Facility Reference Manual, Order Number AA-Z415B-TE, Maynard, Massachusetts.


Scientific Data Formats

IDL supports the HDF (Hierarchical Data Format), CDF (Common Data Format), and NetCDF (Network Common Data Format) self-describing, scientific data formats. Collections of built-in routines provide an interface between IDL and these formats. Documentation for specific routines can be found in Input/Output Routines. Further discussion of the various formats can be found in "Scientific Data Formats" on page 23-1 of the IDL User's Guide.


Support for Standard Image File Formats

IDL includes routines for reading and writing many standard graphics file formats. These routines and the types of files they support are listed in the table below. Documentation on these routines can be found in the online help (enter "?" at the IDL prompt).

Format	Read Routine	Write Routine	Description
BMP	READ_BMP	WRITE_BMP	Windows Bitmap ( .bmp) Format
GIF	READ_GIF	WRITE_GIF	CompuServe Graphics Interchange Format
Interfile	READ_INTERFILE	n/a	Interfile version 3.3 Format
JPEG	READ_JPEG	WRITE_JPEG	Joint Photographic Experts Group files
NRIF	n/a	WRITE_NRIF	NCAR Raster Interchange Format
PICT	READ_PICT	WRITE_PICT	Macintosh version 2 PICT files (bitmap only)
SRF	READ_SRF	WRITE_SRF	Sun Raster File
TIFF	TIFF_READ	TIFF_WRITE	8-bit or 24-bit Tagged Image File Format
X11 Bitmap	READ_X11_BITMAP	n/a	X11 Bitmap format used for reading bitmaps for IDL widget button labels
XWD	READ_XWD	n/a	X Windows Dump format
Table 17.11 IDL-Supported Graphics Standards

Jump forward to Operating System Access

Jump backward to Image Display Routines


Operating System Access
18	Operating System Access

Chapter Overview

IDL offers the ability to interface with the operating system. This ability extends IDL by allowing it to communicate with other software. Some abilities are available under all operating systems while others are operating system specific:

•	The SPAWN procedure allows you to spawn a child process to execute commands. The output generated by that command can be captured in a variable for later processing by IDL.

•	The CD procedure (along with the PUSHD, POPD, and PRINTD procedures) allows you to change the current working directory.

•	The CALL_EXTERNAL function allows you to call external functions (written in C or Fortran, for example) from your IDL programs.

•	The LINKIMAGE procedure merges routines written in other languages with IDL at runtime. Routines merged in this fashion are added to IDL's internal system routine table and are available in the same manner as IDL built-in routines.

This chapter covers the basics of IDL's interaction with any operating system, then discusses platform-specific options for the Unix, VMS, Windows, and Macintosh versions of IDL.


Topics in Operating System Access Chapter
Operating System Access

This chapter provides an overview of IDL's facilities for interacting with various computer operating systems and other software.

Topics Covered:

The SPAWN Procedure

Changing the Working Directory

The CALL_EXTERNAL Function

The LINKIMAGE Procedure

Which Operating System is Running?

Unix-Specific OS Abilities

Using CALL_EXTERNAL under Unix

Unix Compilation, Link, and Call Statements

VMS-Specific OS Abilities

Using CALL_EXTERNAL under VMS

VMS Compilation, Link, and Call Statements

Windows-Specific OS Abilities

Using CALL_EXTERNAL under Windows

Macintosh-Specific OS Abilities

Using CALL_EXTERNAL on the Macintosh

Jump forward to Map Projections

Jump backward to Files and Input/Output


The SPAWN Procedure

The SPAWN procedure spawns a child process to execute a given command. It has the form:

SPAWN[, Command[, Result]]

where

Command

A string containing the command to be issued. Command can be either a scalar or an array.

Result

If Result is not present, the output from the child process simply goes to the standard output (usually the terminal). Otherwise, the output from the child process is placed into a string array (one line of output per array element) and assigned to Result.

The SPAWN procedure is a very flexible command. It can create an interactive command interpreter process, or simply issue a single command and return. Under UNIX, in this second case, the command can either be passed to a shell for processing or be executed directly as a child process of IDL.

Interactive Use of SPAWN

If SPAWN is called without arguments, an interactive command interpreter process is started. The user can enter one or more operating system commands. While you use the command interpreter process, IDL is suspended. When you exit the child process, control returns to IDL, which resumes at the point where it left off. The IDL session remains exactly as you left it.

It should be noted that using SPAWN in this manner is equivalent to using the IDL "$" command. The difference between these two is that "$" can only be used interactively while SPAWN can be used interactively or in IDL programs.

UNIX Command Interpreter

UNIX offers many shells. The two most common are the Bourne shell ( /bin/sh) and the C shell (/bin/csh). Rather than force use of a given shell, IDL follows the UNIX convention of using the shell specified by the UNIX environment variable SHELL. If SHELL does not exist, the Bourne shell is used.

Under UNIX, the interactive form of SPAWN is provided primarily for users of the Bourne shell and for compatibility with VMS. Shells that offer process suspension (e.g., /bin/csh) offer a more convenient and efficient way to get the same effect.

The following statements demonstrate the interactive use of SPAWN on a UNIX system:

SPAWN

% date
Fri Aug 26 13:55:00 MDT 1988
% exit

VMS Command Interpreter

Under VMS, the command interpreter used is always DCL. The following statements demonstrate SPAWN under VMS:

SPAWN

$ SHOW TIME
29-JAN-1990 16:32:23
$ LOGOUT

Windows Command Interpreter

Under Windows 3.1, the command interpreter used is always COMMAND.COM; under Windows NT, CMD.EXE is used. Calling SPAWN (or $) with no arguments creates an interactive command interpreter window as a child process.

Macintosh Command Interpreter

Interactive access to the Macintosh command interpreter is not supported.

Noninteractive Use of SPAWN

If SPAWN is called with a single argument, that argument is taken as a command to be executed. In this case, IDL starts a child command interpreter process and passes the command to it. The argument should be a scalar string. The shell executes the command and exits, at which point IDL resumes operation. This form of operation is very convenient for executing single commands from IDL programs. For example, it is sometimes useful to create a temporary scratch file. SPAWN can be used as demonstrated in the following program fragment:

OPENW, UNIT, 'scratch.dat', /GET_LUN
Open the scratch file. Use the GET_LUN keyword to allocate a file unit.

...	IDL commands that use the file go here.

FREE_LUN, UNIT	Deallocate the file unit and close the file.

CASE !VERSON.OS OF

  'vms': CMD = 'DELETE'

  'windows': CMD = 'DEL'

  'MacOS': GOTO, NOTSUP

  ELSE: CMD = 'rm'

ENDCASE
Use the !VERSION system variable to determine the proper file deletion command for the current operating system. Since this operation is not supported on the Macintosh, jump to an error message.

SPAWN, CMD + 'scratch.dat'	Delete the file using SPAWN.

GOTO, DONE	Jump to the end of the procedure.

NOTSUP: PRINT, 'This operation is not supported on the Macintosh'

DONE:

END

Note that the DELETE keyword to the OPEN procedures is a more efficient way to handle this job. The above example should serve only to demonstrate use of the SPAWN procedure.

Macintosh Command Interpreter

You can specify one or more file names when invoking SPAWN on the Macintosh. Each file specified is opened by the application that created it, unless the first file name is that of an application. In this case, the application is used to open the remaining files.

Capturing Output

Under Windows and on the Macintosh, it is not possible to capture output from a spawned command to an IDL variable.

Under UNIX and VMS, by default, any output generated by a spawned command is sent to the standard output, which is usually the terminal. It is possible to capture this output in an IDL string array by calling SPAWN with a second argument. If this second argument, called Result, is present, all output from the child process is put into a string array, one line of output per array element, and is assigned to Result. For example, the following IDL statements can be used to give a simplistic count of the number of users logged onto a computer running either UNIX or VMS:

IF (!VERSION.OS EQ 'VMS') THEN CMD='SHOW USERS' ELSE CMD='who'
Use the !VERSION system variable to determine the command to use.

SPAWN, cmd, users	Issue the command, catch the result in a string array.

N = N_ELEMENTS(users)	Count how many lines of output came back. Under UNIX, this is the number of users logged in.

IF (!VERSION.OS EQ 'VMS') THEN N = N - 5
VMS outputs five extra header lines that are not actual users.

PRINT, 'There are ', N,' users logged on.'
Print the result.


Changing the Working Directory

Like every process, IDL has a current working directory. This is the default directory that is used whenever you specify a file without explicitly supplying the directory. The initial working directory is the directory you were in when you issued the command to start IDL. You can use the CD procedure to change this working directory at any point during the IDL session. This new working directory affects the current session and any child processes that you start from IDL, but it does not change the current directory of the process that started IDL. Therefore, when you exit IDL, you will find yourself back in the directory you were in when you started.

In order to change to your login directory, just provide a null argument. In addition, the CURRENT keyword can be used to obtain the current directory before any change is made. The following command saves the current directory and then changes it to your home directory:

CD, '', CURRENT = OLDDIR

Later, you can restore the current directory to its previous value with the following command:

CD, OLDDIR

Changing the Working Directory Under Unix

To change the current directory to /usr/stardata under UNIX, use the following statement:

CD, '/usr/stardata'

Changing the Working Directory Under VMS

To change the current directory to SYS$SYSDEVICE:[STARDATA] under VMS, use the following statement:

CD, 'SYS$SYSDEVICE:[STARDATA]'

Changing the Working Directory Under Windows

To change the current directory to C:\usr\stardata under Windows, use the following statement:

CD, 'c:\usr\stardata'

Changing the Working Directory on the Macintosh

To change the current folder to stardata in the usr folder on the disk drive Macintosh HD on the Macintosh, use the following statement:

CD, 'Macintosh HD:usr:stardata'

Maintaining a Directory Stack

The procedures PUSHD, POPD, and PRINTD are provided to make interactive use of cd more convenient by maintaining a stack of directories. PUSHD saves the current directory on the top of the stack and then changes it to the directory given by its argument. POPD sets the current directory to the directory at the top of the stack and removes that directory from the stack. PRINTD shows you the current entries on the stack. Using these user procedures, the example above could be written as follows:

PUSHD, ''	Change to your home directory.

...	Execute some number of statements.

POPD	Return to the original working directory.


The CALL_EXTERNAL Function

The CALL_EXTERNAL function loads and calls routines contained in shareable object libraries. IDL and the called routine share the same memory and data space. Because of this, CALL_EXTERNAL avoids the overhead of process creation of the SPAWN routine. In addition, the shareable object library is only loaded the first time it is referenced, saving overhead on succeeding calls.

CALL_EXTERNAL is much easier to use than the LINKIMAGE routine. Unlike LINKIMAGE, however, CALL_EXTERNAL does not check the type or number of parameters. Programming errors in the external routine are likely to cause IDL to crash or corrupt data.

For more information and examples, see one of the following sections:

•	"Using CALL_EXTERNAL under Unix" on page 18-12.

•	"Using CALL_EXTERNAL under VMS" on page 18-24.

•	"Using CALL_EXTERNAL under Windows" on page 18-34.

•	"Using CALL_EXTERNAL on the Macintosh" on page 18-35.

•	"CALL_EXTERNAL" on page 1-51 of the IDL Reference Guide.


The LINKIMAGE Procedure

LINKIMAGE merges routines written in other languages with IDL at run-time. Each call to LINKIMAGE defines a new system procedure or function by specifying the routine's name, the name of the file containing the code, and the entry point name. The name of your routine is added to IDL's internal system routine table, making it available in the same manner as any other IDL built-in routine. LINKIMAGE can also be used to add graphics device drivers.

Warning: This procedure is only available under VMS, Windows, and on Unix systems that support the dynamic loading of object modules. Its use requires intimate knowledge of the internals of IDL, and is not for use by the novice user. It should only be used if there is absolutely no alternative. If dynamic linking is necessary, we recommend you examine the CALL_EXTERNAL function before committing to LINKIMAGE, as it has a much simpler interface.

For more information, see "LINKIMAGE" on page 1-529 of the IDL Reference Guide.


Which Operating System is Running?

Information about the release level and platform IDL is running on is stored in the OS field of !VERSION system variable. See "!VERSION" on page 3-10.


Unix-Specific OS Abilities

Avoiding the Shell Under UNIX

As mentioned above, SPAWN usually creates a shell process and passes the command to this shell, instead of simply creating a child process to directly execute the command. This default action is taken because the shell provides useful actions such as wildcard expansion and argument processing. Although this is usually desirable, it has the drawback of being slower than necessary. It simply takes longer to start a shell. However, it is possible to avoid using the shell by using the NOSHELL keyword.

When SPAWN is called and NOSHELL is present and nonzero, the command is executed as a direct child process, avoiding the extra overhead of starting a shell. This is faster; but since there is no shell to break the command into separate arguments, the user has to do it. Every UNIX program is called with a series of arguments. When you issue a shell command, you separate the arguments with white space (blanks and tabs). The shell then breaks up the command into an array of arguments and calls the command (the first word of the command), passing it the array of arguments.

In this case, the Command argument should be a string array. The first element of the array is the name of the command to use, and the following elements contain the arguments.

For example, consider the command,

SPAWN, 'ps ax'

that uses the UNIX ps command to show running processes on the computer. To issue this command without a shell, you would write it as follows:

SPAWN, ['ps', 'ax'], /NOSHELL

Communicating With A Child Process

Using SPAWN in the above examples, the IDL process waited until the child process was finished before continuing. It is also possible to start a child process and immediately continue without waiting for it to finish. In this case, IDL attaches a bidirectional pipe to the standard input and output of the child process. This pipe appears in the IDL process as a normal logical file unit.

Once a process has been started in this way, the normal IDL input/output facilities are used to communicate with it. The ability to use a child process in this manner allows you to solve specialized problems using other languages and to take advantage of existing programs.

In order to start such a process, the UNIT keyword is used with SPAWN to specify a named variable into which the logical file unit number will be stored. Once the child process has done its work, the FREE_LUN procedure is used to close the pipe and delete the process.

When using a child process in this manner, it is important to understand the following points:

•	Closing the file unit causes the child process to be killed. Therefore, do not close the unit until the child process completes its work.

•	The EOF function always returns "False" when applied to a pipe. This means that it is not possible to use this function to know when the child process is finished. As a result, the child process must be written in such a way that the controlling IDL procedure knows how much data to send and how much is coming back.

•	A UNIX pipe is simply a buffer maintained by the operating system. It has a fixed length and can therefore become completely filled. When this happens, the operating system puts the process that is filling the pipe to sleep until the process at the other end consumes the buffered data. The use of a bidirectional pipe can lead to deadlock situations in which both processes are waiting for the other. This can happen if the parent and child processes do not synchronize their reading and writing activities.

•	Most C programs use the input/output facilities provided by the Standard C Library (stdio). In situations where IDL and the child process are carrying on a running dialog (as opposed to a single transaction), the normal buffering performed by stdio on the output file can cause communications to hang. We recommend calling the stdio setbuf() function as the first statement of the child program to eliminate such buffering.

(void) setbuf(stdout, (char *) 0);

It is important that this statement occur before any output operation is executed; otherwise, it will have no effect.

Example—Communicating with a Child Process Under Unix

The following C program (named test_pipe.c) accepts floating-point values from its standard input and returns their average on the standard output. In actual practice, such a trivial program would never be used from IDL. It is simpler and more efficient to perform the calculation within IDL. However, it does serve to illustrate the method by which significant programs can be called from IDL.

In the interest of brevity, some error checking that would normally be included in such a program has been omitted. For example, a real program would need to check the non-zero return values from fread(3) and fwrite(3) to ensure that the desired amount of data was actually transferred.

#include <stdio.h>
extern int errno; 	 /* System error number */
extern char *sys_errlist[];	 /* System error messages */
extern int sys_nerr; 	 /* Length of sys_errlist */
main()
{
     float *data, total = 0.0;
     long i, n;
     /* Make sure the output is not   buffered */
     setbuf(stdout, (char *) 0);
     /* Find out how many points */
     if (!fread(&n, sizeof(long), 1, stdin)) goto error;
     /* Get memory for the array */
     if (!(data = (float *) malloc((unsigned)
     (n * sizeof(float))))) goto error;
     /* Read the data */
     if (!fread(data, sizeof(float), n, stdin)) goto error;
     /* Calculate the average */
     for (i=0; i < n; i++) total += data[i];
     total /= (float) n;
     /* Return the answer */
     if (!fwrite(&total, sizeof(float), 1, stdout))
     goto error;
     return;
   error:
     fprintf(stderr, "test_pipe: %s\n",
     sys_errlist[errno]);
}

This program performs the following steps:

1.	Reads a long integer that tells how many data points to expect, because it is desirable to be able to average an arbitrary number of points.

2.	Obtains dynamic memory via the malloc() function, and reads the data into it.

3.	Calculates the average of the points.

4.	Returns the answer as a single floating-point value.

Since the amount of input and output for this program is explicitly known and because it reads all of its input at the beginning and writes all of its results at the end, a deadlock situation cannot occur and use of EOF is not necessary.

The following IDL statements use test_pipe to determine the average of the values 0 to 9:

SPAWN, 'test_pipe', UNIT = UNIT, /NOSHELL
Start test_pipe. The use of the NOSHELL keyword is not necessary, but speeds up the start-up process.

WRITEU, UNIT, 10L, FINDGEN(10)	Send the number of points followed by the actual data.

READU, UNIT, ANSWER	Read the answer.

PRINT, "Average = ", ANSWER	Announce the result.

FREE_LUN, UNIT	Close the pipe, delete the child process, and deallocate the logical file unit.

Executing these statements gives the result:

Average =        4.50000

This mechanism provides the UNIX IDL user a simple and efficient way to augment IDL with code written in other languages such as C or FORTRAN. It is, however, not as efficient as writing the required operation entirely in IDL. The actual cost depends primarily on the amount of data being transferred. For example, the above example can be performed entirely in using a simple statement such as the following:

PRINT, 'Average = ', TOTAL(FINDGEN(10))/10.0

In order to determine the performance difference between using a child process and doing the calculation in IDL, we ran both versions for 10, 100, 1000, 10,000, and 100,000 points on a Sun 3. The results of the example above are summarized in the figure below. These results show that the pipe transfer rate is approximately 130 KB/sec. As can be seen, the IDL calculation is always faster, but the difference is only significant when a large amount of data is transferred.

The Unix Environment

Every UNIX process has an "environment." The environment consists of "environment variables," each of which has a string value associated with it. Some environment variables always exist, such as PATH that tells the shell where to look for programs or TERM that specifies the kind of terminal being used. Others can be added by the user, usually from an interactive shell and often from the .login file that is executed when you log in.

When a process is created, it is given a copy of the environment from its parent process. IDL is no exception to this; when started, it inherits a copy of its parent's environment. The parent process to IDL is usually the interactive shell from which it was started. In turn, any child process created by IDL (such as those from the SPAWN procedure) inherits a copy of IDL's current environment.

Note: It is important to realize that environment variables are not an IDL feature; they are part of every UNIX process. Although they can serve as a form of global memory, it is best to avoid using them in that way. Instead, IDL system variables and common blocks should be used in that role. This will make your IDL code portable to non-UNIX-based IDL systems. Environment variables should be used for communicating with child processes. One example is setting the value of the SHELL environment variable prior to calling SPAWN to change the shell executed by SPAWN.

IDL provides two routines for manipulating the environment:

GETENV

The GETENV function returns the equivalence string from the environment of the IDL process. It has the form:

GETENV(Name)

where Name is the name of the environment variable for which the translation is desired. If Name does not exist in the environment, a null string is returned. For example, to determine the type of terminal being used, you can enter the IDL statement:

PRINT, 'The terminal type is:  ', GETENV('TERM')

Executing this statement on a Sun workstation give the following result:

The terminal type is: sun

SETENV

The SETENV function adds a new environment variable or changes the value of an existing environment variable in the IDL process. It has the form:

SETENV, Environment_Expression

where Environment_Expression is a scalar string containing an environment expression to be added to the environment.

For example, you can change the shell used by SPAWN by changing the value of the SHELL environment variable. An IDL statement to change to using the Bourne shell /bin/sh would be:

SETENV, 'shell=/bin/sh'


Using CALL_EXTERNAL under Unix

The CALL_EXTERNAL function loads and calls routines contained in sharable object libraries. CALL_EXTERNAL is currently supported under the following operating systems:

•	DEC Alpha/OSF1 Version 3.2

•	Hewlett-Packard HP/UX Version 9.0

•	IBM AIX Version 3.2

•	Silicon Graphics IRIX Version 5.2

•	Sun SunOS Version 4.1.3

•	Sun Solaris Version 2.3

An important advantage to calling external routines with CALL_EXTERNAL, as opposed to spawning child processes and passing parameters by pipe, is that IDL and the called routine share the same memory and data space. CALL_EXTERNAL avoids the overhead of process creation and parameter passing. In addition, the sharable object file containing the called routine is only loaded the first time it is referenced.

Calling Convention and Parameter Passing

IDL calls routines in a shareable object using the C calling convention (argc, argv). Any routines called by CALL_EXTERNAL should be defined with a prototype similar to the following:

return_type example(int argc; void *argv[])

where return_type is one of the data types which CALL_EXTERNAL may return. If this return_type is not "long," a keyword must be used in the CALL_EXTERNAL call to indicate the type of the result.

The parameter argc is the count of optional parameters in the CALL_EXTERNAL call, and  argv is an array of the parameters. Parameters are passed either by value or by reference. Parameters passed by value are copied directly into the argv array, with the exception of scalar strings, which place a pointer to a null-terminated string in argv[i]. All arrays are passed by reference. Scalar items passed by reference (the default) place a pointer to the datum in argv[i]. Strings and string arrays passed by reference place a pointer to a STRING structure in argv[i]. This structure is defined as follows:

typedef struct {
  unsigned short slen;   /* Length of string */
  short stype;  /* type of string:  (0) static, (!0)   dynamic */
  char *s;      /*  Addr of string, invalid if slen == 0.  */
} IDL_STRING;

See "CALL_EXTERNAL" on page 1-51 of the IDL Reference Guide for additional details about passing parameters by value. See the Fortran example below for a description of how to implement the (argc, argv) prototype in Fortran.

It is important to note that IDL integer variables correspond to a C short integer. For example, an integer variable could be defined in an IDL routine as follows:

IDL> A = 5          ;default type of integer, not LONG

The variable could then be passed by reference in a CALL_EXTERNAL call. The declaration and cast statement in the called C routine should be:

short *a;

a = (short *) argv[0];

The corresponding type in Fortran would be INTEGER*2.

Example: Calling a C routine

Assume you wish to add a routine that returns the sum of a floating point array, similar to the TOTAL function in IDL. The code for such a routine is contained in the listing of example.c below.

The following lines make up the example.c file:

#include <stdio.h>

float sum_array(argc, argv)

int argc;

void *argv[];

{

  float *fp, s = 0.0; int n;

  for(n = *(int *) argv[1], fp = (float *) argv[0]; n--; )

   s += *fp++;

  return(s);

}

The following statements could be used to compile the example shown above and link it to produce a shareable object library for the SunOS operating system. For more information on compiling and linking on your platform, see "Unix Compilation, Link, and Call Statements" on page 18-17.

cc -pic -fsingle -c example.c

ld -o example.so -assert pure-text example.o

Assuming the compiled routine resides in the shared library example.so, it can be called by the following IDL code. Note that in this example, an underscore character has been added to the function name (sum_array) in order to match the entry point name in the object file. The entry point name is generated by the compiler and may be different for different compilers.

X = FINDGEN(10)	Make an array.

S = CALL_EXTERNAL('example.so', $

                  '_sum_array' X, N_ELEMENTS(X), /F_VALUE)

In this example, example.so is the name of the sharable image file, _sum_array is the name of the entry point, and X and N_ELEMENTS(X) are passed to the called routine as parameters. The F_VALUE keyword specifies that the returned value is a floating-point number rather than a long integer.

Example: Calling a Fortran Routine Using a C Interface Routine

Calling Fortran is similar to calling C, with the restriction that Fortran expects all arguments to be passed by reference. This means that the address of the argument is passed rather than the argument itself.

A C interface routine can easily extract the addresses of the arguments from the argv array and pass them to the actual routine which will compute the sum. Passing the contents of each argv element by value has the same effect as converting the parameter to a normal Fortran parameter. The following code segments illustrate this. The example.c file contains the C interface routine, which would be compiled as illustrated above. The example.f file contains the Fortran routine that actually sums the array.

As in the above example, we assume that the routines are being compiled under SunOS. Note that the object name will be sum_array1_ to match the output of the SunOS Fortran compiler. The example.c file includes the following lines:

#include <stdio.h>

void sum_array(argc, argv)

int argc;

void *argv[];

{

void sum_array1_();

int *n;

float *s, *f;

f = (float *) argv[0];    /* Array pntr */

n = (int *) argv[1];      /* Get # of elements */

s = (float *) argv[2];    /* Pass back result a parameter */

sum_array1_(f, n, s);     /* Compute sum */

}

The example1.f file contains the following lines:

c This subroutine is called by SUM_ARRAY and has no

c IDL specific code.

c

SUBROUTINE sum_array1(array, n, sum)

INTEGER*4 n

REAL*4 array(n), sum

sum=0.0

DO i=1,n

sum = sum + array(i)

PRINT *, sum, array(i)

ENDDO

RETURN

END

This example is compiled, linked, and called in a manner similar to that used in the C example above. For more information on compiling and linking on your platform, see "Unix Compilation, Link, and Call Statements" on page 18-17.

When passing C null-terminated character strings into a Fortran routine, the C function should also pass in the string length. This extra parameter is added to the end of the Fortran routine call in the C function, but does not appear in the Fortran routine.

For example, in C:

char * str1= 'IDL';

char * str2= 'RSI';

int len1=3;

int len2=3;

double data, info;

/* Call a Fortran sub-routine named example1 */

example1_(str1, data, str2, info, len1, len2)

In Fortran:

SUBROUTINE EXAMPLE1(STR1, DATA, STR2, INFO)

CHARACTER*(*)STR1, STR2

DOUBLE PRECISIONDATA, INFO

Example: Calling a Fortran Routine Using a Fortran Interface Routine

Calling Fortran is similar to calling C, with the restriction that Fortran expects all arguments to be passed by reference. This means that the address of the argument is passed rather than the argument itself.

A Fortran interface routine can be written to extract the addresses of the arguments from the argv array and pass them to the actual routine which will compute the sum. Passing the contents of each argv element by value has the same effect as converting the parameter to a normal Fortran parameter.

This method uses the VMS Extensions to Fortran, %LOC and %VAL. On the IBM, the LOC function is an intrinsic operator. The syntax of the call, which differs from the Sun and HP syntax, is:

y=loc(x)

Some Fortran compilers may not support these extensions. If your compiler does not, use the method shown above for calling Fortran with a C interface routine.

The example.f file contains the following:

SUBROUTINE SUM_ARRAY(argc, argv)  !Called by IDL

INTEGER*4 argc, argv(*)           !Argc and Argv are integers

j = LOC(argc)         !Obtains the number of arguments (argc)

                      !Because argc is passed by VALUE.

cCall subroutine SUM_ARRAY1, converting the IDL parameters

cto standard FORTRAN, passed by reference arguments:

CALL SUM_ARRAY1(%VAL(argv(1)), %VAL(argv(2)), %VAL(argv(3)))

RETURN

END

cThis subroutine is called by SUM_ARRAY and has no

cIDL specific code.

c

SUBROUTINE SUM_ARRAY1(array, n, sum)

INTEGER*4 n

REAL*4 array(n), sum

sum=0.0

DO i=1,n

sum = sum + array(i)

ENDDO

RETURN

END

This example is compiled, linked, and called in a manner similar to that used in the C example above. For more information on compiling and linking on your platform, see "Unix Compilation, Link, and Call Statements" on page 18-17.

This example is compiled, linked, and called in a similar manner to the C example above. The entry point name generated by the Fortran compiler is likely to be different than that produced by the C compiler. One of the best ways to find out what name was generated is to use the Unix nm utility. See the man page for nm for details.

Further Examples

A number of example routines, along with makefiles for the various systems that support CALL_EXTERNAL, are located in the sharelib subdirectory of the examples subdirectory of the external subdirectory of the IDL distribution. To compile the examples into a shareable object and then run IDL procedures which call them, issue one of the following commands at the shell prompt:

To run the C only examples:

% make_callext_demo

To run the C wrapper to Fortran examples:

% make_callext_demo test_c2fort

To run the Fortran only examples:

% make_callext_demo test_ftn_only

To clean up the directory:

% make_callext_demo clean

The makefiles use the correct options for the standard compiler for each supported system. If you use a different compiler, you may need to change the compilation or link flags. Also, each of the IDL procedures contains logic to set the name of the entry point in the shared library. The name of the entry point in the CALL_EXTERNAL call may be incorrect if you use a different compiler.

Each makefile assumes that the location of IDL is /usr/local/lib/idl. If this is not the location of you IDL installation, edit the makefile for your system. The macro IDL=  will need to be changed to the location of you IDL distribution.


Unix Compilation, Link, and Call Statements

Each Unix system has different compilation and link statements for producing a shareable object suitable for usage with CALL_EXTERNAL. Also, the name of the entry point in the object may be different, because compilers may add leading or trailing underscores to the name of the source routine.

The following compilation and link statements may be used for the example routines above. They also show the correct flags to use for any set of C routines. Additional libraries may be added to the link lines by using the -L and -l flags, except on certain systems noted below, where the name of the library must be specified explicitly.

•	DEC Alpha/OSF1 Version 3.2

•	Hewlett-Packard HP/UX Version 9.0

•	IBM AIX Version 3.2

•	Silicon Graphics IRIX Version 5.2

•	Sun SunOS Version 4.1.3

•	Sun Solaris Version 2.3

DEC Alpha/OSF1 Version 3.2

CALL_EXTERNAL Library Loading

The location of the dynamic library can either be specified in the CALL_EXTERNAL call or in the LD_LIBRARY_PATH environment variable. For more information on the use and format of this environment variable consult the man pages for dlopen and loader.

Dynamic library files use the .so filename extension.

C Functions

Use the following to compile a C function for use by CALL_EXTERNAL:

% cc -c example.c

Use the following to load:

% ld -S -o example.so -shared example.o

No leading or trailing underscores are added to the entry name (i.e. `example').

The -S flag is used to set silent mode and suppress non-fatal compiler errors. The -shared flag produces a shared object library file.

Fortran Routines

Use the following to compile a Fortran routine for use by CALL_EXTERNAL:

% f77 -c example.f

Use the following to load:

% ld -o example.so -shared example.o -lUfor -lfor \

-lFutil -lm -lots -lc

A trailing underscore is added to the entry name (i.e. `example_').

The -shared flag is used to produce a shared object library file. The remaining flags load various Fortran libraries.

C Wrapper Functions to Fortran Routines

Use the following to compile a Fortran routine with a C wrapper:

% cc -c example.c

% cc -c example1.f

% ld -o example.so -shared example.o example1.o -lUfor \

-lfor -lFutil -lm -lots -lc

A trailing underscore is added to the Fortran entry point, so in the C routine you would call the example1 routine with example1_().

Hewlett-Packard HP/UX Version 9.0

CALL_EXTERNAL Library Loading

The location of the dynamic library must be specified in the CALL_EXTERNAL call. The dynamic loader does not use any environment variables for a library search path.

Dynamic library files use the .sl filename extension.

C Functions

Use the following to compile a C function for use by CALL_EXTERNAL:

% cc +z -c example.c

Use the following to load:

% ld -b -o example.sl example.o

On HP 9000s300 systems, a leading underscore is added to the library entry name (i.e. `_example'). Other HP systems add no leading or trailing underscores to the entry name (i.e. `example').

Compile with the +z flag to generate position independent code. Use the -b option to specify the creation of a shared library.

Fortran Routines

Use the following to compile a Fortran function for use by CALL_EXTERNAL:

% f77 +z -c example.f

Use the following to load:

% ld -o example.sl -b example.o

On HP 9000s300 systems, a leading underscore is added to the library entry name (i.e. `_example'). Other HP systems add no leading or trailing underscores to the entry name (i.e. `example').

Compile with the +z flag to generate position independent code. Use the -b option to specify the creation of a shared library.

C Wrapper Functions to Fortran Routines

Use the following to compile a Fortran routine with a C wrapper:

% cc +z -c example.c

% f77 +z -c example1.f

Use the following to load:

% ld -o example.sl -b example.o example1.f

On HP 9000s300 systems, a leading underscore is added to the library entry name (i.e. `_example'). Other HP systems add no leading or trailing underscores to the entry name (i.e. `example').

Compile with the +z flag to generate position independent code. Use the -b option to specify the creation of a shared library.

IBM AIX Version 3.2

Entry point names must be specified in an export file that defines which symbols in the object file are exported and visible outside the library.

For example, if you wanted to export the following routines:

int function1()

long function2()

double function3()

you would need an exports file that looked like this:

#!

*

function1

function2

function3

Export files use the .exp filename extension.

CALL_EXTERNAL Library Loading

The location of the dynamic library can either be specified in the CALL_EXTERNAL call or in the LIBPATH environment variable. For more information on the use and format of this environment variable consult the section 3 man page for load.

Dynamic library files use the .so filename extension.

C Functions

Use the following to compile a C function for use by CALL_EXTERNAL:

% cc -c example.c

Use the following to load:

% cc -o example.so example.o -bM:SRE -bE:example.exp -e _nostart

No leading or trailing underscores are added to the entry name (i.e. `example').

The -bM:SRE indicates that the module type of the result should be set to Shared and REusable. The -bE:filename.exp specifies the exports file to be used. The -e switch of the linking cc command (specifying the "entry point" _nostart) ensures that the entry points listed in your exports file will be used. The loadable object file is written to the file example.so. It is important to use cc to do the link, rather than ld, because cc uses the correct configuration file so that support libraries are linked. See the manual page for ld for details on using ld rather than cc.

Note: If you are using callable IDL routines (added to IDL's system tables with LINKIMAGE, for example), you will need to add the idl.export file to the linking cc command. The idl.export file is located in the external subdirectory of the IDL distribution. Note also that AIX needs to know where to look for the symbols specified in the idl.export file. Use the -L switch to specify the bin/bin.ibm subdirectory of the main IDL directory. The linking command would look something like:

% cc -o example.so example.o -bM:SRE -bE:example.exp \
  -bI:idl.export -e _nostart -L/usr/local/rsi/idl/bin/bin.ibm

Fortran Routines

Use the following to compile a Fortran function for use by CALL_EXTERNAL:

% xlf -c example.f

Use the following to load:

% xlf -o example.so example.o -bM:SRE -bE:example.exp -e _nostart

No leading or trailing underscores are added to the entry name (i.e. `example').

Fortran compilation with xlf should use the same options as C compilation, as shown above. For linking, use xlf instead of cc or ld, unless you handle the configuration manually. See the manual page for xlf for details.

C Wrapper Functions to Fortran Routines

Use the following to compile a Fortran routine with a C wrapper:

% cc -c example.c

% xlf -c example1.f

Use the following to load:

% cc -o example.so -bM:SRE example.o example1.o \

  -bE:example.exp -e _nostart -lxlf

No underscores are added to the C function entry point, so only the C function name is passed into CALL_EXTERNAL from IDL (i.e. `example').

The flags passed to the loader are the same as with C functions. The only addition is the -lxlf flag which loads the Fortran specific libraries.

Silicon Graphics IRIX Version 5.2

CALL_EXTERNAL Library Loading

The location of the dynamic library can either be specified in the CALL_EXTERNAL call or in the LD_LIBRARY_PATH environment variable. For more information on the use and format of this environment variable consult the man page for dlopen.

Dynamic library files use the .so filename extension.

C Functions

Use the following to compile a C function for use by CALL_EXTERNAL:

% cc -c -KPIC example.c

Use the following to link:

% ld -shared -o example.so example.o

No leading or trailing underscores are added to the entry name (i.e. `example').

The -KPIC flag is used to generate position-independent code. The -shared flag to the loader produces a shared object that can be dynamically loaded.

Fortran Routines

Use the following to compile a Fortran function for use by CALL_EXTERNAL:

% f77 -c -KPIC example.f

Use the following to load:

% ld -shared -o example.so example.o -lftn

A trailing underscore is added to the routine name (i.e. `example_').

The flags passed to the loader are the same as with C functions. The only addition is the -lftn flag which loads the Fortran specific libraries.

Sun SunOS Version 4.1.3

CALL_EXTERNAL Library Loading

The location of the dynamic library must be specified in the CALL_EXTERNAL call. The dynamic loader does not use the LD_LIBRARY_PATH environment variable.

Dynamic library files use the .so filename extension.

C Functions

Use the following to compile a C function for use by CALL_EXTERNAL:

% cc -pic -fsingle -c example.c

Use the following to load:

% ld -o example.so -assert pure-text example.o

No leading or trailing underscores are added to the entry name (i.e. `example').

The -pic flag is used to generate position independent code. The -fsingle flag is used to prevent the default promotion of single-precision floating-point numbers to double-precision in expressions. The -assert pure-text flag is used to guarantee that the resulting load has no relocation items in its text.

Fortran Routines

Use the following to compile a Fortran function for use by CALL_EXTERNAL:

% f77 -c -pic example.f

Use the following to load:

% ld -o example.so example.o /usr/local/lang/SC1.0/libF77.a \

/usr/local/lang/SC1.0/libm.a

A leading and trailing underscore are added to the routine name (i.e. `_example_').

Compiling and linking Fortran language routines requires the use of fewer flags than C compilation. The -fsingle flag is not applicable and should not be used. Similarly, the -assert pure-text flag should not be used when linking to additional Fortran libraries such as libF77.a and libm.a.

Fortran language libraries might be required when loading/linking the dynamic library. These libraries must be explicitly listed, as shown above; the -L and -l loader flags cannot be used. (Note that the absolute paths to these files may be different on your system.)

All Fortran functions that return single-precision floating-point values will actually return double-precision values. This will not cause errors in IDL even if the /F_VALUE keyword is specified in the CALL_EXTERNAL call.

C Wrapper Functions to Fortran Routines

Use the following to compile a Fortran routine with a C wrapper:

% cc -c -pic -fsingle example.c

% f77 -c -pic example1.f

Use the following to load:

% ld -o example.so example.o example1.o \

/usr/local/lang/SC1.0/libF77.a \

/usr/local/lang/SC1.0/libm.a

No underscores are added to the C function entry point, so only the C function name is passed into CALL_EXTERNAL from IDL (i.e. `example'). A trailing underscore is added to the Fortran routine name, so the C function should call the Fortran function using `example1_' not `example1'. Modules are compiled as outlined above.

Sun Solaris Version 2.3

CALL_EXTERNAL Library Loading

The location of the dynamic library can either be specified in the CALL_EXTERNAL call or in the LD_LIBRARY_PATH environment variable. For more information on the use and format of this environment variable consult the man page for dlopen.

Dynamic library files use the .so filename extension.

C Functions

Use the following to compile a C function for use by CALL_EXTERNAL:

% cc -G -Kpic -c example.c

Use the following to load:

% ld -G -o example.so example.o

No leading or trailing underscores are added to the entry name (i.e. `example').

The -Kpic flag is used to generate position independent code. The -G flag is used to produce a shared object rather than a dynamically linked executable.

Fortran Routines

Use the following to compile a Fortran function for use by CALL_EXTERNAL:

% f77 -c -pic example.f

Use the following to load:

% ld -G -o example.so example.o /opt/SUNWspro/SC2.0.1/libF77.a \

/opt/SUNWspro/SC2.0.1/libm.a

A leading and trailing underscore are added to the routine name (i.e. `_example_').

The -G flag is used to produce a shared object rather than a dynamically linked executable. Fortran language libraries might be required when loading/linking the dynamic library. These libraries must be explicitly listed, as shown above; the -L and -l loader flags cannot be used. (Note that the absolute paths to these files may be different on your system.)

C Wrapper Functions to Fortran Routines

Use the following to compile a Fortran routine with a C wrapper:

% cc -G -Kpic -fsingle example.c

% f77 -c -pic example1.f

Use the following to load:

% ld -G -o example.so example.o example1.o \

/opt/SUNWspro/SC2.0.1/libF77.a \

/opt/SUNWspro/SC2.0.1/libm.a

No underscores are added to the C function entry point, so only the C function name is passed into CALL_EXTERNAL from IDL (i.e. `example'). A trailing underscore is added to the Fortran routine name, so the C function should call the Fortran function using `example1_' not `example1'. Modules are compiled as outlined above.

The -G flag is used to produce a shared object rather than a dynamically linked executable. Fortran language libraries might be required when loading/linking the dynamic library. These libraries must be explicitly listed, as shown above; the -L and -l loader flags cannot be used. (Note that the absolute paths to these files may be different on your system.)


VMS-Specific OS Abilities

Manipulating Logical Names

VMS logical names are manipulated using the SETLOG, TRNLOG, and DELLOG routines.

Accessing DCL Interpreter Symbols

Digital Command Language (DCL) interpreter symbols are accessed with the SET_SYMBOL, GET_SYMBOL, and DELETE_SYMBOL routines.


Using CALL_EXTERNAL under VMS

The CALL_EXTERNAL function loads and calls routines contained in sharable images that adhere to the VMS calling standard.

Calling Convention and Parameter Passing

IDL calls routines in the sharable image object with the parameters that were passed to CALL_EXTERNAL. Unlike Unix routines that are called using the C calling convention argc and argv, VMS routines are called with a parameter list. Any routine called by CALL_EXTERNAL should be defined in the following manner:

In IDL:

status = CALL_EXTERNAL(image, 'example', p1, p2, p3, p4 )

In C:

return_type example( p1, p2, p3, p4 )

where return_type is one of the types which CALL_EXTERNAL may return. If this type is not "long", then a keyword must be used in the CALL_EXTERNAL call to indicate the type of the result.

Arrays are passed by reference. By default, scalars are passed by reference also. See "CALL_EXTERNAL" on page 1-51 of the IDL Reference Guide for additional details about passing parameters by value.

It is important to note that IDL integer variables correspond to a C short integer. For example, an integer variable could be defined in an IDL routine as follows:

IDL> A=5

The variable could then be passed by reference in a CALL_EXTERNAL call. The declaration and cast statement in the called C routine should be:

short *a;

The declaration in a called Fortran routine should be:

INTEGER*2 A

Example: Calling a C routine

Assume you wish to add a routine that returns the sum of a floating point array, similar to the TOTAL function in IDL. This routine accepts a pointer to the array (f_arr), a pointer to the number of elements (n_ele), and it passes back a floating point sum as a parameter (sum). It does not pass back a return value. Even though the return value is unused, the CALL_EXTERNAL call in IDL must be made as a function call. In this case, the return value should be assigned to a dummy value.

The following lines make up the example.c file:

#include <stdio.h>

void sum_array(f_arr, n_ele, sum)

float *f_arr;

long*n_ele;

float *sum;

{

float s;

for(s=0.0; n_ele--; ) /* Compute the sum */

s += *f_arr++;

*sum = s;

}

See "VMS Compilation, Link, and Call Statements" on page 18-30 for details on compiling and linking the code on your platform.

Assuming the compiled routine resides in the executable file example.exe, it can be called by the following IDL code.

X = FINDGEN(10)	Make an array.

SUM = 0.0	Define a variable to hold the result.

S = CALL_EXTERNAL('[path]example.exe', $

                  'example' X, N_ELEMENTS(X), SUM)

In this example, [path]example.exe is the full path name of the linked executable file, example is the name of the entry point, and X, N_ELEMENTS(X), and SUM are passed to the called routine as parameters. Note that the result is returned in the variable SUM, which must be defined as the proper data type (single-precision floating-point in this case) before calling the external routine. You may find it helpful to replace [path]example.exe with a VMS logical.

Example: Calling a Fortran Routine

Calling Fortran is similar to calling C, with the restriction that Fortran expects all arguments to be passed by reference. This means that the address of the argument is passed rather than the argument itself.

To compute the sum of a float array using Fortran you would use the following Fortran subroutine.

The example.f file contains the following:

SUBROUTINE EXAMPLE( F_ARR, N_ELE, SUM)

INTEGER*4N_ELE

REAL*4F_ARR(N_ELE)

REAL*4SUM

INTEGER I

SUM = 0.0

DO I=1, N_ELE

SUM = SUM + F_ARR(I)

END DO

RETURN

END

See "VMS Compilation, Link, and Call Statements" on page 18-30 for details on compiling and linking the code on your platform.

Example: Calling the EDT or TPU Editors

A simple example uses CALL_EXTERNAL to invoke the EDT text editor directly from IDL. The EDT editor is provided as a sharable, callable image in the file SYS$SHARE:EDTSHR.EXE. Its entry point is named EDT$EDIT. The statement

status = CALL_EXTERNAL('edtshr', 'edt$edit', 'test.pro')

calls EDT to edit the file test.pro.

Similarly, to call TPU, use the following statement:

status = CALL_EXTERNAL('tpushr', 'tpu$edit', 'test.pro', '')

TPU$EDIT requires two parameters: the file to be edited and an output file. In this case, the output file is a zero-length string denoting that the output file is the same as the input.

A procedure named EDIT is easily written to accept a filename parameter, verify that it is a scalar string, and call EDT:

PRO EDIT, file	Edit file using EDT.

IF N_ELEMENTS(file) EQ 0 THEN BEGIN	Is the parameter defined?

  BAD_PAR:  PRINT, "Usage:  EDIT, 'filename'"
Print error message.

RETURN

ENDIF

S = SIZE(file)	Validate parameter.

IF (S(0) NE 0) OR (S(1) NE 7) THEN GOTO, BAD_PAR
Is the string scalar?

STATUS = CALL_EXTERNAL('edtshr', 'edt$edit', file)
Call the editor.

END

Example: Calling a Runtime Library Function

This example presents a procedure called GETMSG that returns the error message text given a VMS error message number.

The VMS Run-Time Library routine LIB$SYS_GETMSG is used, which is documented by Digital Equipment Corporation (1988, pp. LIB408­LIB410). Briefly, parameters to LIB$SYS_GETMSG are:

LIB$SYS_GETMSG(MSG_ID, MSG_LEN, DEST_STRING, FLAGS)

where

•	MSG_ID is the message identification code, a longword passed by reference.

•	MSG_LEN is the returned message length, a longword integer passed by reference.

•	DEST_STRING is the string into which the message is placed, passed by reference to its string descriptor.

•	FLAGS is a longword integer, passed by reference, of flag bits that determine message content (default value 0).

The code of the procedure GETMSG is as follows:

FUNCTION GETMSG, msgid	Return the text to the VMS message MSGID.

len = 0L	Destination string length, initialize to longword.

msg = STRING(REPLICATE(32B, 100))	Destination string, initialize to a string containing 100 blanks.

istat = CALL_EXTERNAL('librtl', 'lib$sys_getmsg', $

        LONG(msgid), len, msg, 0L)	Call lib$sys_getmsg; flags parameter is 0.

msg = STRMID(msg, 0, len)	Truncate the string using the returned length.

RETURN, msg	Return the string.

END

This example illustrates one method of returning a string from an external routine. The function creates a 100-character, blank-filled string called MSG, which is passed by reference to its descriptor to LIB$SYS_GETMSG. The descriptor LIB$SYS_GETMSG fills the memory pointed to by this descriptor with the result, which can be up to 100-characters long, and returns the actual string length in the variable len. The call to STRMID is necessary to truncate the string MSG to the length of the returned string.

Calling a VAX FORTRAN Subroutine

This example calls a simple VAX FORTRAN function that returns the mean of a floating-point array:

MEAN = CALL_EXTERNAL(/F_VALUE, 'MY_AVG_EXE', 'MY_AVG', $

       FINDGEN(10), 10L)

The F_VALUE keyword indicates that the called function returns a single-precision, floating value.

The entry MY_AVG, inside a sharable image pointed to by the logical name MY_AVG_EXE, is called. The two parameters passed to the routine are a 10-element, floating-point vector and the element count, passed as a long integer. The FORTRAN routine, in file MY_AVG.FOR, is as follows:

REAL * 4 FUNCTION MY_AVG(V, N)

REAL*4 V(*)

MY_AVG = 0.0

DO I=1,N

  MY_AVG = MY_AVG + V(I)

END DO

MY_AVG = MY_AVG / N

RETURN

END

The VMS DCL commands to compile, link, and setup the logical name are as follows:

$ FORTRAN MY_AVG

$ LINK MY_AVG, SYS$INPUT/OPT/SHARE

UNIVERSAL = MY_AVG

$ DEFINE MY_AVG_EXE dduu:[xxx]MY_AVG.EXE

The OpenVMS DCL commands to compile, link, and setup the logical name are as follows:

$ FORTRAN MY_AVG

$ LINK MY_AVG, SYS$INPUT/OPT/SHARE

SYMBOL_VECTOR = [MY_AVG=PROCEDURE]

$ DEFINE MY_AVG_EXE dduu:[xxx]MY_AVG.EXE

Passing Parameters by Value

Scalar parameters can be passed by value or by reference. The optional VALUE keyword parameter is a byte array in which nonzero elements indicate the respective scalar parameter is to be passed by value. Parameters are passed by reference if the VALUE parameter is not present or the respective element is zero.

For example, if the above routine, MY_AVG, is written in the C language and declared as follows:

float my_avg(float *, int)

The call from IDL becomes:

MEAN = CALL_EXTERNAL(/F VALUE, VALUE = [0B,1B], $

       'MY_AVG_EXE', 'MY_AVG', FINDGEN(10), 10L)

causing the second parameter, the number of elements, to be passed by value rather than by reference.

Using CALL_EXTERNAL with FORTRAN Common Blocks

In FORTRAN language routines, common blocks are declared as writable, sharable PSECTS. This can cause the following error messages:

LIB-E-ACT: error activating image: image.exe

SYSTEM-F-NOTINSTALL: writable sharable images must be installed

%CALL_EXTERNAL: error in called routine

Place the following command in the link command file for each common block:

PSECT_ATTR = com_block_name, noshr

where com_block_name is the name of the common block in your FORTRAN routine. These lines must be added for each common block in the routines that you call using CALL_EXTERNAL.

Using CALL_EXTERNAL with C Extern Variables

In C language routines, variables declared with the extern modifier must be declared as writable, shareable images. Place the following command in the link command file for each extern declaration:

PSECT_ATTR = extern_var_name, noshr

where extern_var_name is the name of the extern variable in your C routine.

Further Examples

A number of example routines, along with makefiles, are located in the sharelib subdirectory of the examples subdirectory of the external subdirectory of the IDL distribution. To compile the examples into a shareable object and then run IDL procedures which call them, issue one of the following commands at the shell prompt:

To run the C only examples:

$ @test_c_only

To run the Fortran only examples:

$ @test_ftn_only

To delete the newly-created object and executable files from the directory:

$ @test_c_only clean

$ @test_ftn_only clean

To delete the object files and purge the newly-created executable files from the directory:

$ @test_c_only tidy

$ @test_ftn_only tidy

The makefiles use the correct options for the standard compiler for each supported system.

These files should be run in the directory that contains the C and/or Fortran code that is used in these examples. If this code is not present the examples will fail to operate. These examples also require that the logical IDL_DIR be defined and point to the location of the IDL directory.


VMS Compilation, Link, and Call Statements

Since there are now two different VMS systems in use (VAX and Alpha), the compile and link statements are slightly different on both systems. The following sections outline the Compile, link and Call statements for each of these systems.

VAX/VMS Version 5.4

CALL_EXTERNAL Library Loading

In the CALL_EXTERNAL call, the IMAGE argument only accepts the name of the sharable image file. CALL_EXTERNAL will not accept the file type, device name or directory specification strings. There are two methods to specify these file parameters:

•	Declare a VMS logical that is defined to the location of the shareable image file.

•	Use the CALL_EXTERNAL keyword DEFAULT keyword to specify the location and file name of the sharable image file.

If neither of these two methods are used, IDL will search the directory defined by the system logical SYS$SHARE for the specified image file.

C Functions

Use the following to compile a C function for use by CALL_EXTERNAL:

$ cc EXAMPLE.C /nolist

Use the following to link:

$ LINK /share EXAMPLE,-

SYS$INPUT/OPT/EXE=EXAMPLE_SHARE.EXE

SYS$SHARE:VAXCRTL/SHARE

UNIVERSAL = example

The /SHARE keyword is used to specify that the input file is a shareable image file. The /OPT switch specifies that SYS$INPUT will contain a list of linking options. The /EXE keyword is used to specify the output executable file name. The file SYS$SHARE:VAXCRTL contains symbols used by C and is a sharable file as indicated by the /SHARE keyword. All entry points (routine names) are indicated by the UNIVERSAL= statement. Each entry point in the sharable image file requires a  UNIVERSAL statement.

Fortran Routines

Use the following to compile a Fortran function for use by CALL_EXTERNAL:

$ FORTRAN EXAMPLE.FOR

Use the following to link:

$ LINK /share EXAMPLE,-

SYS$INPUT/OPT/EXE=FTN_ONLY_SHARE.EXE

UNIVERSAL = example

The options used with the LINK command are the same as used with C routines.

OpenVMS AXP Version 6.1

CALL_EXTERNAL Library Loading

In the CALL_EXTERNAL call, the IMAGE argument only accepts the name of the sharable image file. CALL_EXTERNAL will not accept the file type, device name or directory specification strings. There are two methods to specify these file parameters:

•	Declare a VMS logical that is defined to the location of the shareable image file.

•	Use the CALL_EXTERNAL keyword DEFAULT keyword to specify the location and file name of the sharable image file.

If neither of these two methods are used, IDL will search the directory defined by the system logical SYS$SHARE for the specified image file.

C Functions

Use the following to compile a C function for use by CALL_EXTERNAL:

$ cc /FLOAT=D_FLOAT EXAMPLE.C /nolist

Use the following to link:

$ LINK /share EXAMPLE, -

SYS$INPUT/OPT /EXE=EXAMPLE_SHARE.EXE

symbol_vector=(example=PROCEDURE)

The /SHARE keyword is used to specify that the input file is a shareable image file. The /OPT switch specifies that SYS$INPUT will contain a list of linking options. The /EXE keyword is used to specify the output executable file name. All entry points (routine names) are indicated by a symbol_vector=(name=PROCEDURE) statement. Each entry point in the shareable image file requires a  SYMBOL_VECTOR statement.

The /D_FLOAT in the compile statement is used to indicate that double variables us the D_floating format.

Fortran Routines

Use the following to compile a Fortran function for use by CALL_EXTERNAL:

$ FORTRAN /FLOAT=D_FLOAT EXAMPLE.FOR

Use the following to link:

$ LINK /share EXAMPLE, -

SYS$INPUT/OPT /EXE=EXAMPLE_SHARE.EXE

symbol_vector=(example=PROCEDURE)

The options used with the LINK command are the same as used with C routines.


Windows-Specific OS Abilities

Windows-Only Routines for Dynamic Data Exchange (DDE)

IDL for Windows supports DDE client capability for cold DDE links. The relevant system calls are documented below:

Result = DDE_GETSERVERS()

This function returns an array of service names for the currently-available DDE servers.

Result = DDE_GETTOPICS(server)

This function returns the topics list for the specified server. The server argument is a scalar string containing the name of the desired DDE server.

Result = DDE_GETITEMS(server)

This function returns the items list for the specified server. The server argument is a scalar string containing the name of the desired DDE server.

Result = DDE_REQUEST(server, topic, item)

This function returns the requested data in string format. The server, topic, and item arguments must be scalar strings.

DDE_EXECUTE, server, topic, command

This procedure causes the DDE server to execute the command for the specified topic. The server, topic, and command arguments must be scalar strings.

Windows-Only Routines for Hardware Ports

You can address the hardware ports of your personal computer directly using the following routines. In each case, Port is specified using the hexadecimal address of the hardware port. For example, if serial port #1 of your PC is at address 3F8, you would use the following IDL commands to read that port:

paddr = '3F8'x	Set paddr to hexadecimal value.

data = INPW(paddr)	Read data.

Result = INP(Port, [D1 . . . DN])

This function returns either one byte (if only the port number is specified) or an array (the dimensions of which are specified by D1 . . . DN) read from the specified hardware port. Port is the hardware port number. For example,

result = INP(paddr)

would read a single byte, and

result = INP(paddr, 2,4)

would read a two-element by four-element array.

Result = INPW(Port, [D1 . . . DN])

This function returns either one 16-bit word, as an integer (if only the port number is specified), or an array (the dimensions of which are specified by  D1 . . . DN) from the specified hardware port. Port is the hardware port number.

OUTP, Port, Value

This procedure writes either one byte or an array of bytes to the specified hardware port. Port is the hardware port number. Value is the byte value or array to be written.

OUTPW, Port, Value

This procedure writes either one 16-bit word or an array of words to the specified hardware port. Port is the hardware port number. Value is the integer value or array to be written.


Using CALL_EXTERNAL under Windows

You can use CALL_EXTERNAL to call your own Windows-compatible DLLs. Note that under Windows 3.1, only 32-bit win32s-compatible DLLs are supported by CALL_EXTERNAL.

There are some difficulties in creating Windows-compatible DLLs and we suggest that you obtain some additional information on this topic (such as Charles Petzold's book Programming Windows 3.1) before attempting to write one.

Calling Convention and Parameter Passing

All DLLs called with CALL_EXTERNAL must use an argc-argv calling convention. The parameters you specify in the call to CALL_EXTERNAL are translated into the argv vector.

Parameters can be passed by value or by reference. See "CALL_EXTERNAL" on page 1-51 of the IDL Reference Guide for additional details about specifying how parameters are to be passed.

DLL procedures can return long integers, floating-point integers, or strings by value. They can return any sort of information by reference.

Examples

Example DLL code, a makefile, and an IDL procedure calling the newly-created DLL are located in the sharelib subdirectory of the examples subdirectory of the external subdirectory of the IDL distribution. To compile the example into a DLL, issue the following command:

C:\RSI\IDL\EXAMPLES\SHARELIB> nmake /f makefile.win

The makefile uses the correct options for the Microsoft C compiler. If you use a different compiler, you may need to change the compilation or link flags.

To run the example code, start IDL, compile and run the file dlltst32.pro.


Macintosh-Specific OS Abilities

Note that LINKIMAGE is supported on PowerPC Macintoshes, but not on 680X0-based machines.

Applescript Support

IDL for Macintosh supports the "Do Script," "Get," and "Set" Apple Events. For example, the following AppleScripts are recognized:

tell application "IDL" to get variable "v"

tell application "IDL" to copy {1,2,3} to variable "v"

tell application "IDL" to do script "plot,v"

In addition, the IDL procedure DO_APPLE_SCRIPT allows you to provide a string (or an array of strings) to be compiled and executed by AppleScript. See "DO_APPLE_SCRIPT" on page 1-248 of the IDL Reference Guide for details.


Using CALL_EXTERNAL on the Macintosh

You can use CALL_EXTERNAL to call your own Macintosh Stand Alone Code resources or a shared library file. On 680X0 Macintoshes, CALL_EXTERNAL expects a Stand Alone Code Resource (a compiled piece of relocatable code) that is stored in a file as resource of type CUST. On PowerPC Macintoshes, CALL_EXTERNAL expects native PowerPC code stored in the data fork of a shared library file.

Calling Convention and Parameter Passing

IDL calls routines in a CUST resource or shared library using the C calling convention (argc, argv). Any routines called by CALL_EXTERNAL should be defined with a prototype similar to the following:

return_type resFunction ( int argc, void *argv[] )

where return_type is one of the data types which CALL_EXTERNAL may return. If this return_type is not "long," a keyword must be used in the CALL_EXTERNAL call to indicate the type of the result. Note that it is your responsibility to set the resource attributes of your code resource correctly. IDL locks the resource in memory before its calls your code, and restores the old state (locked or unlocked) after your code returns. If you need your code to stay locked in memory between multiple calls, you must set its lock bit in the resource file.

Returning a string value

When returning a string value, the code resource must allocate the string value in its own code space. The string will be copied into an IDL variable on return.

Global Data in Stand Alone Code

Global data can be difficult in Macintosh Stand Alone Code. Many included libraries and files declare static global data. In addition, you may need persistent (global) data inside your code resource, for example when returning a string type. The string must be stored inside the code resource and then copied into an IDL variable upon return. Many compilers offer workarounds, such as putting the data into the same segment as your code resource. They also offer workarounds for getting at the System Global Variables such as those used with Quickdraw. Consult your compiler manual on these issues.

Example: Calling a C Routine on a 680X0 Macintosh

Assume you wish to add a routine that returns the sum of an integer array, similar to the TOTAL function in IDL. The routine accepts a variable length argument list where the first parameter is the number of arguments and the second is an array of pointers to the arguments. The function then returns a long integer which is the sum of its inputs.

The example.c file contains the following:

long sumarray( int argc, void *argv[] )

{

longretval;

short*arrInd;

inti;

retval = 0L;

if ( argc == 2 ) {

/*

* IDL integer arrays are arrays of shorts so get the pointer

* to the array (arrays are always passed to CALL_EXTERNAL by

* reference

*/

arrInd = (short *)argv[0];

/*

* then just sum the array

*/

for (i = 0;i < *(int *)argv[1]; i++)

retval += *arrInd++;

}

return(retval);

} /* end of summer routine */

To link an object file suitable for loading by IDL with MPW, use the compilation and link statements shown below:

C example.c

Link example.c.o -rt CUST=0 -m sumarray -sg summer -o example

Finally to use the above example in IDL, use the commands:

IDL> testarr = INDGEN(10)

IDL> total = CALL_EXTERNAL("example", "summer", testarr, 10L)

Example: Calling a C Routine on a PowerPC Macintosh

CALL_EXTERNAL on the PowerMac expects native PowerPC code to be stored in the data fork of a shared library file. It loads the code with the routine  GetDiskFragment(), and finds the requested routine using FindSymbol(). Because of this, you may put multiple routines in the same shared library file and even share global variables amongst them. The library is only loaded once, and is freed when IDL exits.

Consult your compiler manual on how to create a shared library file. Consult the Code Fragment Manager of Inside Macintosh: PowerPC System Software to learn about GetDiskFragment() and FindSymbol().

The example routine sumarray() given above also works on the Power Macintosh. You must link the program as a shared library. In Metrowerks CodeWarrior, this is done using a popup menu in the "Project" section of the "Preferences" dialog.

The external code can then be called from IDL using the following commands:

IDL> testarr = INDGEN(10)

IDL> total = CALL_EXTERNAL("example", "sumarray", testarr, 10L)

Note that the actual routine name, rather than a resource name, is used in the call.

Jump forward to Map Projections

Jump backward to Files and Input/Output


Map Projections
19	Map Projections

Chapter Overview

The IDL mapping package contains the following procedures:

MAP_SET

This procedure establishes the coordinate conversion mechanism for mapping points on a globe's surface to points on a plane, according to one of 11 possible projections. This procedure also sets up the limits of the global region to be mapped, the center of the map, and the polar rotation. MAP_SET must be called to set up a map projection before any other mapping routines are called. See "MAP_SET" on page 1-566 of the IDL Reference Guide.

MAP_GRID

This procedure draws the graticule of parallels and meridians (grid lines) according to the specifications established by MAP_SET. See "MAP_GRID" on page 1-558 of the IDL Reference Guide.

MAP_CONTINENTS

This procedure draws continental or other boundaries over a map projection established by MAP_SET. Continents, coastlines, rivers, and political borders can be draw in either low or high resolution. See "MAP_CONTINENTS" on page 1-555 of the IDL Reference Guide.

MAP_IMAGE and MAP_PATCH

These functions return an image warped to fit the current map projection. See the IDL Reference Guide for more information. See "MAP_IMAGE" on page 1-560 of the IDL Reference Guide. See "MAP_PATCH" on page 1-563 of the IDL Reference Guide.


Topics in Map Projections Chapter
Map Projections

This chapter provides an overview of IDL's mapping package.

Topics Covered:

The MAP_SET Procedure

The MAP_GRID Procedure

The MAP_CONTINENTS Procedure

Map Projections Described

Putting Data on Maps

High-Resolution Continent Outlines

Jump forward to Mathematics

Jump backward to Operating System Access


The MAP_SET Procedure

The MAP_SET procedure establishes the axis type and coordinate conversion mechanism for mapping points on the Earth's surface, expressed in latitude and longitude, to points on a plane, according to one of 12 possible map projections. Many other keywords are available to control various graphics options. For information on all the available keywords, see "MAP_SET" on page 1-566 of the IDL Reference Guide.

The user can select the map projection, the map center, polar rotation, and geographical limits. The system variable !MAP retains the information needed to effect coordinate conversions to the plane and inversely from the projection plane to points on the earth in latitude and longitude. The user should not change the values of the fields in !MAP directly. The user can request MAP_SET to plot the graticule and continental boundaries by setting the keywords GRID and CONTINENT. The procedure has the calling sequence:

MAP_SET[, P0LAT, P0LON, ROT]

where

P0LAT

For all but Lambert's conformal conic projection with two standard parallels, P0LAT is the latitude of the point on the earth's surface to be mapped to the center of the projection plane. If the projection type is sinusoidal, P0LAT must be zero. Latitude is measured in degrees North of the equator, where -90° ≤ POLAT ≤ 90°.

If P0LAT is not set, the default value is zero. If the user has selected Lambert's conformal conic projection with two standard parallels, P0LAT should be set to the latitude in degrees of one of the parallels. If P0LAT is omitted, it is set to 20 degrees by default.

P0LON

For all but Lambert's conformal conic projection with two standard parallels, P0LON is the longitude of the point on the Earth's surface to be mapped to the center of the map projection. Longitude is measured in degrees east of the Greenwich meridian and -180° ≤ POLON ≤ 180°.

If P0LON is not set, the default value is zero.

If the user has selected Lambert's conformal conic projection with two standard parallels, P0LON should be set to the latitude in degrees of the other standard parallel. If P0LON is omitted, it is set to 60 degrees by default.

ROT

ROT is the angle through which the North direction should be rotated around the line L between the Earth's center and the point (P0LAT, P0LON). ROT is measured in degrees with the positive direction being clockwise rotated around L. ROT should satisfy -180 ≤ ROT ≤ 180.

With cylindrical maps and the Mollweide projection, ROT should not be set to precisely 180 degrees or -180 degrees.

If the center is at the North Pole, the North direction is in the direction of P0LON + 180 degrees. If the origin is at the South Pole, then North is in the direction of P0LON. The default value of ROT is zero.

MAP_SET Keywords

MAP_SET accepts many keywords that customize the appearance of the map. A few of the important ones are described below. See the description of MAP_SET in the IDL Reference Guide for descriptions of all the keywords.

CONTINENTS

Set this keyword to plot the continental boundaries.

GRID

Set this keyword to draw the grid of parallels and meridians.

LIMIT

LIMIT is a four-element vector of the form [Latmin, Lonmin, Latmax, Lonmax] that specifies the boundaries of the region to be mapped. (Latmin, Lonmin) and (Latmax, Lonmax) are the latitudes and longitudes of two points diagonal from each other on the region's boundary.


The MAP_GRID Procedure

MAP_GRID draws the graticule of parallels and meridians according to the specifications established by MAP_SET. The MAP_SET procedure should be called before MAP_GRID to establish the projection type, the center of the projection, polar rotation, and geographical limits. Latitude and/or longitude lines can be drawn in different linestyles, colors, and spacings. For information on all the available options, see "MAP_GRID" on page 1-558 of the IDL Reference Guide.


The MAP_CONTINENTS Procedure

MAP_CONTINENTS draws the projection of the continental boundaries to a resolution of 1 degree, according to the specifications established by MAP_SET. MAP_SET should be called before MAP_CONTINENTS to establish the projection type, the center of the projection, polar rotation, and geographical limits. For information on all the available options, see "MAP_CONTINENTS" on page 1-555 of the IDL Reference Guide.


Map Projections Described

In the following sections, the available projections are discussed in detail. The projections are grouped within three categories: azimuthal, cylindrical, and pseudo-cylindrical.

Note that in this text, the plane of the projection is referred to as the UV plane with horizontal axis u and vertical axis v.

Azimuthal Projections

With azimuthal projections, the UV plane is tangent to the globe. The point of tangency is projected onto the center of the plane and its latitude and longitude are P0LAT and P0LON, respectively. ROT is the angle between North and the v-axis.

Important characteristics of azimuthal maps include the fact that directions or azimuths are correct from the center of the projection to any other point, and great circles through the center are projected to straight lines on the plane.

The IDL mapping package includes the following azimuthal projections: stereographic, orthographic, gnomonic, Lambert's azimuthal equal area, satellite, and azimuthal equidistant.

The Stereographic Projection

The stereographic projection is a true perspective projection with the globe being projected onto the UV plane from the point P on the globe diametrically opposite to the point of tangency. The whole globe except P is mapped onto the UV plane. There is great distortion for regions close to P, since P maps to infinity.

The stereographic projection is the only known perspective projection that is also conformal. It is frequently used for polar maps. For example, a stereographic view of the north pole has the south pole as its point of perspective.

If the keyword LIMIT is not supplied, the determination of the region of the globe to be projected to the UV plane depends on the center C of the projection. If C is on the equator or is one of the poles, then the hemisphere centered around C is the selected region; otherwise, the region selected is the whole globe, which is not optional.

The following call to MAP_SET uses the stereographic projection to draw the hemisphere centered on the equator at longitude -105 degrees and produces an equatorial stereographic map:

MAP_SET, 0, -105, LATDEL = 20, LONDEL = 20, /GRID, /CONTINENT, $

         /STEREO, TITLE = 'Equatorial Stereographic'

The output of this call is shown in the upper-left corner

of the figure.

Since keywords LATDEL and LONDEL are set to 20, parallels and meridians are spaced 20 degrees apart. The GRID and CONTINENT keywords signal that the grid and continents should be drawn.

Orthographic Projection

The orthographic projection was known by the Egyptians and Greeks 2000 years ago. This projection looks like a globe because it is a perspective projection from infinite distance. As such, it maps one hemisphere of the globe into the UV plane. Distortions are greatest along the rim of the hemisphere where distances and land masses are compressed.

If the keyword LIMIT is not set, the region of the globe mapped to the UV plane is the hemisphere around the center of the projection. The following call is used to produce an orthographic projection:

MAP_SET, 40, LONDEL=20, /GRID, /CONTINENTS, /ORTHO, $

  TITLE = 'Oblique Orthographic'

The output of this call is shown in the accomp

anying figure.

Gnomonic Projection

The gnomonic projection (also called the Central projection) projects all great circles to straight lines. The gnomonic projection is the perspective, azimuthal projection with point of perspective at the center of the globe. Hence, with the gnomonic projection, the interior of a hemispherical region of the globe is projected to the UV plane with the rim of the hemisphere going to infinity. Except at the center, there is great distortion of shape, area, and scale.

If the user has not selected the region to be mapped through the keyword LIMIT, the default region depends on the location of the center. If the center is on the equator, then

LIMIT = [P0LAT - 60, P0LON - 60, P0LAT + 60, P0LON +60]

At the North Pole,

LIMIT = [30, -180, 90, 180]

and at the South Pole,

LIMIT = [-90, -180, -30, 180]

For other locations of the center, LIMIT is set to the whole globe. However, only part of the hemisphere around the center will be shown.

The oblique gnomonic projection shown in the lower-left corner of the figure is produced by the following statement:

MAP_SET, 40, -105, LIMIT = [20, -170, 80, -50], $

  /GRID, /CONTINENT, /GNOM, TITLE = 'Oblique Gnomonic'

This projection is centered around the point at latitude 40 degrees and longitude -105 degrees. The region on the globe that is mapped lies between -40 degrees and 80 degrees of latitude and -180 degrees and 30 degrees of longitude.

Lambert's Equal Area Projection

Lambert's equal area projection adjusts projected distances in order to preserve area. Hence, it is not a true perspective projection.

Like the stereographic projection, it maps to infinity the point P diametrically opposite the point of tangency. Note also that to preserve area, distances between points become more contracted as the points become closer to P. Lambert's equal area projection has less overall scale variation than the other azimuthal projections.

If the keyword LIMIT is not set, then the default region is identical to that for the stereographic projection. The following call produces the polar Lambert projection:

MAP_SET, 90, 0, -105, LATDEL=20, LONDEL=20, /GRID, $

  /CONTINENTS, /LAMB, TITLE = 'Polar Lambert'

Note that this map shows the Northern Hemisphere rotated counterclockwise 105 degrees.

Azimuthal Equidistant Projection

The azimuthal equidistant projection is also not a true perspective projection, because it preserves correctly the distances between the tangent point and all other points on the globe. The point P opposite the tangent point is mapped to a circle on the UV plane, and hence, the whole globe is mapped to the plane. There is infinite distortion close to the outer rim of the map, which is the circular image of P.

If the keyword LIMIT is not set, the whole globe is mapped to the UV plane. The polar azimuthal projection is created using the following statement:

MAP_SET, -90, LONDEL=20, LATDEL=20, /GRID, /CONTINENT, $

  /AZIMUTHAL, TITLE = 'Polar Azimuthal'

It is centered at the South Pole and shows the entire globe.

Satellite Projection

The satellite projection, also called the General Perspective projection, simulates a view of the globe as seen from a camera in space. If the camera faces the center of the globe, the projection is called a Vertical Perspective projection (note that the orthographic, stereographic, and gnomonic projections are special cases of this projection), otherwise the projection is called a Tilted Perspective projection.

The globe is viewed from a point in space, with the viewing plane touching the surface of the globe at the point directly beneath the satellite (the sub-satellite point). If the projection plane is perpendicular to the line connecting the point of projection and the center of the globe, a Vertical Perspective projection results. Otherwise, the projection plane is horizontally turned Γ degrees clockwise from the north, then tilted ω degrees downward from horizontal.

For the satellite projection, P0LAT and P0LON represent the latitude and longitude of the sub-satellite point. Three additional parameters, P, Omega, and Gamma (supplied as a three-element vector argument to the SAT_P keyword), are required where:

•	P is the distance of the point of perspective (camera) from the center of the globe, expressed in units of the radius of the globe.

•	Omega is the downward tilt of the camera, in degrees from the new horizontal. If both Gamma and Omega are 0, a Vertical Perspective projection results.

•	Gamma is the angle, expressed in degrees clockwise from north, of the rotation of the projection plane.

Note that since all meridians and parallels are oblique lines or arcs, the LIMIT keyword must be supplied as an eight-element vector representing four points that delineate the limits of the map. The extent of the map limits, when expressed in latitude/longitude is a complicated polygon, rather than a simple quadrilateral.

The accompanying

figure, which shows the eastern seaboard of the United States from an altitude of about 160km, above Newburgh, NY, was produced with the code shown below. The parameters for this satellite projection are:

•	Center of projection = 41.5N latitude, -74W longitude

•	P (altitude) = 1.025 = (1.0 + 160 / 6371km)

•	Gamma (rotation of projection plane) = 210 degrees

•	Omega (tilt of projection plane) = 55 degrees

•	The eight element LIMIT keyword array specifies the latitude/longitude location of points at the bottom, left, top, and right of the map respectively.

MAP_SET, /SATELLITE, SAT_P = [1.0251, 55, 210], 41.5, -74., $

      LIMIT = [39, -74, 33, -80, 40, -77, 41, -74], $

      LATDEL=1, LONDEL=1, /LABEL, LATLAB = -75, LONLAB = 39, $

      /GRID, /CONTINENTS, TITLE='Satellite / Tilted Perspective'
Set up the satellite projection.

p = CONVERT_COORD(-74.5, [40.2, 40.5], /TO_NORM)
Get North vector.

ARROW, p(0,0), p(1,0), p(0,1), p(1,1), /NORMAL
Draw North arrow.

XYOUTS, -74.5, 40.1, 'North', ALIGNMENT=0.5
Label North vector.

Hammer-Aitoff Projection

Although the Hammer-Aitoff projection is not truly azimuthal, it is included in this section because it is derived from the equatorial aspect of Lambert's equal area projection limited to a hemisphere. In this derivation, the hemisphere is represented inside an ellipse with the rest of the world in the lunes of the ellipse.

Because the Hammer-Aitoff projection produces an equal area map of the entire globe, it is useful for visual representations of geographically related statistical data and distributions. Astronomers use this projection to show the entire celestial sphere on one map in a way that accurately depicts the relative distribution of the stars in different regions of the sky.

A Hammer-Aitoff projection centered on the international dateline can be produced by the command:

MAP_SET, 0, 180, /AITOFF, /GRID, /CONTINENTS,TITLE= 'Aitoff'

Cylindrical Projections

A cylindrical projection maps the globe to a cylinder which is formed by wrapping the UV plane around the globe with the u-axis coinciding with a great circle. The parameters P0LAT, P0LON, and ROT determine the great circle that passes through the point C=(P0LAT, P0LON). In the discussions below, this great circle is sometimes referred to as EQ. ROT is the angle between North at the map's center and the v-axis (which is perpendicular to the great circle). The cylinder is cut along the line parallel to the v-axis and passing through the point diametrically opposite to C. It is then rolled out to form a plane.

Mercator's projection and the cylindrical equidistant projection are the two cylindrical projections included in IDL.

Mercator Projection

Mercator's projection is partially developed by projecting the globe onto the cylinder from the center of the globe. This is a partial explanation of the projection because vertical distances are subjected to additional transformations to achieve conformity—that is, local preservation of shape. To properly use the projection, the user should be aware that the two points on the globe 90 degrees from the central great circle (e.g., the North and South Poles in the case that the selected great circle is the equator) are mapped to infinite distances. By default, the keyword LIMIT is set to [-80, -180, 80, 180] because of the great distortions around the poles when the equator is selected.

The following call to procedure MAP_SET produces a simple Mercator projection:

MAP_SET, LATDEL=20, LONDEL=20, /GRID, /CONTINENT, $

  /MERC, TITLE = 'Mercator'

The result of this call is shown in the upper-left corner of the figure.

Note that EQ is the equator, and by default, latitudes range from -80 degrees to 80 degrees. A transverse Mercator projection, centered on the poles, is shown in the upper right corner of the figure. It is produced by the following call:

MAP_SET, 0, 0, 90, LATDEL = 20, LONDEL = 20, $

  /GRID, /CONTINENT, /MERC, TITLE = 'Transverse Mercator'

Note that the central great circle is the meridian at longitude 0 degrees.

Cylindrical Equidistant Projection

The cylindrical equidistant projection is one of the simplest projections to construct. If EQ is the equator, this projection simply lays out horizontal and vertical distances on the cylinder to coincide numerically with their measurements in latitudes and longitudes on the sphere. Hence, the equidistant cylindrical projection maps the entire globe to a rectangular region bounded by

-180 ≤ u ≤ 180

and

-90 ≤ v ≤ 90

If EQ is the equator, meridians and parallels will be equally spaced parallel lines.

The default for the keyword LIMIT is:

LIMIT = [-90, -180, 90, 180]

The following code is used to produce a simple cylindrical equidistant projection and an oblique cylindrical equidistant projection as shown in the lower half of the figure:

MAP_SET, LATDEL = 20, LONDEL = 20, $

  /GRID, /CONTINENT, /CYL, $

  TITLE = 'Simple Cylindrical Equidistant'

MAP_SET, 0, 0, 45, LONDEL = 20, LATDEL = 20, /GRID, $

  /CONTINENT, /CYL, TITLE='Oblique Cylindrical Equidistant'

Conic Projection

The conic projection in this mapping package is Lambert's conformal conic with two standard parallels. It is constructed by projecting the globe onto a cone passing through two parallels. Additional scaling achieves conformity. The pole under the cone's apex is transformed to a point, and the other pole is mapped to infinity. The scale is correct along the two standard parallels. Parallels are projected onto circles and meridians onto equally spaced straight lines.

The parameters P0LAT and P0LON denote the latitudes of the two standard parallels. ROT is the longitude of the central meridian. If both P0LAT and P0LON are not defined, then by default, the two standard parallels are at latitudes 20 degrees and 60 degrees. ROT is zero by default. If the keyword LIMIT is undefined, then the map is limited to the region of the globe lying between the two standard parallels.

The following code produces the map shown in the accompanying figure, which features North America with standard parallels at 20 degrees and 60 degrees:

MAP_SET, 20, 60, -80, LIMIT = [0, -260, 90, 100], $

  LATDEL = 20, LONDEL = 20, /GRID, /CONTINENT, /CONIC

ROT was set to -80 in order to place North America in the center of the map.

Pseudocylindrical Projections

Pseudocylindrical projections are distinguished by the fact that in their simplest form, lines of latitude are parallel straight lines and meridians are curved lines.

The sinusoidal and Mollweide pseudocylindrical projections are included in IDL.

Sinusoidal Projection

With the sinusoidal projection, the central meridian is a straight line and all other meridians are equally spaced sinusoidal curves. The scaling is true along the central meridian as well as along all parallels.

The sinusoidal projection is one of the easiest projections to construct. The formulas below from Snyder (1987) give the relationship between the latitude  φ and longitude λ of a point on the globe and its image on the UV plane.

u = λcosφ

v = φ

The parameters P0LAT and ROT of the MAP_SET procedure must be zero. If they are not, an error message results and the procedure MAP_SET will reset both of these parameters to zero and continue. By default, P0LON (the central longitude) is zero, but the user can set it to any other value between -180 and 180. If the keyword LIMIT is undefined, the entire globe is the region selected for mapping.

The following call to MAP_SET produces the sinusoidal map (top) of the whole globe centered at longitude 0 degrees and latitude 0 degrees:

MAP_SET, LATDEL = 20, LONDEL = 20, /GRID, $

  /CONTINENT, /SIN, TITLE = 'Sinusoidal Projection'

The result of this call is shown bel

ow .

Mollweide Projection

With the Mollweide projection, the central meridian is a straight line, the meridians 90 degrees from the central meridian are circular arcs and all other meridians are elliptical arcs. The Mollweide projection maps the entire globe onto an ellipse in the UV plane. The circular arcs encompass a hemisphere and the rest of the globe is contained in the lunes on either side.

If the keyword LIMIT is not set, the whole globe will be mapped to the plane. The following call to MAP_SET produces a Mollweide projection in oblique form, as illustrated below :

MAP_SET, 45, 0, 0, LATDEL = 20, LONDEL = 20, /GRID, /CONTINENT, $

  /MOLL, TITLE = 'Oblique Mollweide'

Since the center of the projection is not on the equator, parallels of latitude are not straight lines, just as they are not straight lines with an oblique Mercator or cylindrical equidistant projection.


Putting Data on Maps

The procedures PLOT, OPLOT, PLOTS, XYOUTS, and CONTOUR can be used to display and annotate geographical data on maps created by the routines MAP_SET, MAP_GRID, and MAP_CONTINENTS. The MAP_IMAGE procedure can be used to warp regularly-gridded images to map projections.

Example—Using CONTOUR with MAP_SET

The following simple example generates a random dataset and creates a CONTOUR plot over a Mollweide map projection. The resulting plot is shown below .

seed = 1L	Create a seed value for the random dataset.

data = RANDOMN(seed, 31, 31)	Create a 31 by 31 element dataset.

lat = FINDGEN(31)*6 - 90	Create an array of corresponding latitudes. The first point in the dataset corresponds to -90 degrees. The last point corresponds to 90 degrees.

lon = FINDGEN(31)*12 - 180	Similarly, create an array of longitudes. The first point in data corresponds to -180 degrees. The last point corresponds to 180 degrees.

MAP_SET, /MOLL, /GRID, /CONT	Set up a basic Mollweide projection.

CONTOUR, data, lon, lat, NLEVELS=7, /OVERPLOT, /CELL_FILL
Overplot the data as a filled CONTOUR plot with seven equally-spaced levels. The CELL_FILL keyword uses a more accurate filling algorithm than FILL.

CONTOUR, data, lon, lat, NLEVELS=7, /OVERPLOT
Overplot the contour outlines.

LOADCT, 39	Load a good colortable.

MAP_CONTINENTS, COLOR=0, MLINETHICK=2
Overplot continent outlines with thick black lines.

MAP_GRID, COLOR=0, GLINETHICK=2	Overplot a latitude/longitude grid with thick black lines.

Limitations

Once the procedure MAP_SET has established the mapping coordinate system, most plotting routines such as PLOT, PLOTS, and OPLOT will connect locations expressed in latitudes and longitudes with straight lines. However, two cautions should be noted. First, no line will be drawn if an endpoint is out of bounds. For example, if the user sets the map limits so that -100° ≤ longitude ≤ 100°, then the call:

PLOTS, [0, 101], [0, 0]

will not produce a line. Secondly, lines with length exceeding a certain value will not be drawn. The critical value depends upon the projection. Problems with drawing lines may occur when lengths exceed 75 percent of the length or width of the map. In that case, simply break the line into shorter line segments.

It is important to remember that contours of the following types are considered open contours and are ignored by the CONTOUR procedure when used with the FILL keyword:

•	Contours that wrap around boundaries in cylindrical maps

•	Contours that contain points outside the map's boundary

•	Contours that cross the boundary of the array of surface values

Using the CELL_FILL keyword instead of FILL often gives better results in these cases.


High-Resolution Continent Outlines

IDL supports two different datasets that contain continent outlines and other geographical and political boundaries. The default dataset is a low-resolution continental outline database that is automatically installed when you install IDL. The high-resolution database was adapted from the 1993 CIA World Map database by Thomas Oetli of the Swiss Meteorological Institute. The high-resolution outlines are found in an optional dataset that may not have been installed when your copy of IDL was first installed.

To access the high-resolution dataset, simply set the HIRES keyword when calling MAP_CONTINENTS with the COASTS, COUNTRIES, FILL_CONTINENTS, or RIVERS keywords. You can also get high-resolution continent boundaries by calling MAP_SET with the HIRES and CONTINENTS keywords set. For an example of using the high-resolution outlines, see "MAP_CONTINENTS" on page 1-555 of the IDL Reference Guide.

See "Notes on Filling Continental Boundaries" for information on filling continental boundaries.

Resolution of Map Databases

Data points in the CIA World Map database are approximately one kilometer apart. Note, however, that in the case of the coast and river databases, actual distances between the data points may be much smaller because of convolutions in the coastline or riverbed.

Data points in the low-resolution map database are either a subset of the high-resolution database (rivers and country boundaries) or are based on the continental map database used in previous versions of IDL (the file supmap.dat in the maps subdirectory of the resource subdirectory of the main IDL directory). Data points in the low-resolution database are approximately 10 kilometers apart.

Neither of the map databases is intended for high-precision work.

The following table compares the low-resolution and high-resolution map databases:

Feature	Low-Resolution	High-Resolution
Coastlines, islands, and lakes (including continental outlines)	Data in file supmap.dat.	Entire CIA World Map.
Continental polygons	Data extracted from supmap.dat.	Every 20th point of CIA World Map.
Rivers	Every 250th point of the CIA World Map	Entire CIA World Map.
National boundaries	Every 100th point of CIA World Map	Entire CIA World Map.
Table 19.1 Comparison of Low and High Resolution Map Datasets

References

Greenwood, David (1964), Mapping, University of Chicago Press, Chicago.

Pearson, Frederick II (1990), Map Projections: Theory and Applications, CRC Press, Inc., Boca Raton.

Snyder, John P. (1987), Map Projections—A Working Manual, U.S. Geological Survey Professional Paper 1395, U.S.Government Printing Office, Washington, D.C.

Jump forward to Mathematics

Jump backward to Operating System Access


IDL Mathematics
20	Mathematics

Chapter Overview

This chapter documents IDL's mathematics and statistics procedures and functions. These include Numerical Recipes  algorithms published in Numerical Recipes in C: The Art of Scientific Computing (Second Edition).

This chapter also includes introductory discussions of the following topics and an overview of the way IDL handles the particular problems involved:

•	Arrays and Matrices

•	Correlation Analysis

•	Curve and Surface Fitting

•	Eigenvalues and Eigenvectors

•	Gridding and Interpolation

•	Hypothesis Testing

•	Integration

•	Linear Systems

•	Nonlinear Equations

•	Optimization

•	Sparse Arrays

•	Time Series Analysis

References are provided at the end of each section for a more detailed description and understanding of the topic.

Research Systems is extremely interested in the accuracy of its algorithms. Bug reports, documentation errors and suggestions for future mathematics and statistics enhancements can be sent to Research Systems via:

Internet: math@rsinc.com

Fax: (303) 786-9909


Topics in IDL Mathematics Chapter
Mathematics

This chapter provides an overview of IDL's mathematics and statistics functionality.

Topics Covered:

IDL's Numerical Recipes Functions

Accuracy and Floating-Point Operations

Arrays and Matrices

Correlation Analysis

Curve and Surface Fitting

Eigenvalues and Eigenvectors

Gridding and Interpolation

Hypothesis Testing

Integration

Linear Systems

Nonlinear Equations

Optimization

Sparse Arrays

Time-Series Analysis

Jump forward to Widgets

Jump backward to Map Projections


IDL's Numerical Recipes Functions

IDL includes a number of routines based on algorithms published in  Numerical Recipes in C: The Art of Scientific Computing (Second Edition). Routines derived from Numerical Recipes are noted as such in the IDL Reference Guide and in the online help.

In IDL versions up to and including IDL version 3.6, mathematics functions based on Numerical Recipes algorithms required that input be in column-major format. This is no longer the case. Routines based on Numerical Recipes algorithms have been reworked and renamed, so that all IDL functions now expect input arrays to be in row-major format (composed of row vectors).

Note, however, that to maintain compatibility with IDL programs based on earlier versions, the old routines (using the older input convention) are still available. No alterations need be made to existing code as a result of this change in IDL. We recommend that all new IDL programs take advantage of the new names and input convention.


Accuracy and Floating-Point Operations

In a computer, real numbers are represented with finite precision. While in most cases it is safe to assume that the result of an arithmetical operation done on your computer is correct, it is important to remember that this finite-precision representation leads to unavoidable errors, especially when floating-point numbers, which are digital approximations to real numbers, are involved.

To understand why floating-point numbers are inherently inaccurate, consider the following:

•	Floating-point numbers must be made to fit in a space (a string of binary digits in a computer's memory register) that can only hold an integer and a scaling factor.

•	Floating-point numbers are represented by strings of a limited number of bits, but represent numbers much larger or smaller than that number of digits can be made to express.

In other words, floating-point values are finite-precision approximations of infinitely precise numbers.

Roundoff Error

When working with floating-point arithmetic, it is helpful to consider the quantity known as the machine accuracy or the floating-point accuracy of your particular computer. This is the smallest number that, when added to 1.0, produces a floating-point result that is different from 1.0.

A useful way of thinking about machine accuracy is to consider it to be the fractional accuracy to which floating-point numbers are represented. In other words, the machine accuracy roughly corresponds to a change of the least significant bit of the floating-point mantissa—precisely what can happen if a number with more significant digits than fit in the floating-point mantissa is rounded to fit the space available. Generally speaking, every floating-point arithmetic operation introduces an error at least equal to the machine accuracy into the result. This error is known as roundoff error.

Roundoff errors are cumulative. Depending on the algorithm you are using, a calculation involving n arithmetic operations might have a total roundoff error between SQRT(n) times the machine accuracy and n times the machine accuracy.

Note that the machine accuracy is not the same as the smallest floating-point number your computer can represent. To find these and other machine-dependent quantities for your own computer, see "MACHAR" on page 1-551 of the IDL Reference Guide.

Truncation Error

Another type of error is also present in some numerical algorithms.  Truncation error is the error introduced by the process of numerically approximating a continuous function by evaluating it at a finite number of discrete points. Often, accuracy can be increased (again at some cost of computation time) by increasing the number of discrete points evaluated.

For example, consider the process of calculating

Obviously, the answer becomes more accurate as n approaches infinity. When performing the actual computation, however, a cutoff value must be specified for n. Increasing n reduces truncation error at the expense of computational effort.

Several IDL routines allow you to specify cutoff values in such cases (see, for example, "INT_2D" on page 1-489 of the IDL Reference Guide). When writing your own routines in IDL, it is important to consider this trade-off between accuracy and computational time.

 Routines for Mathematical Error Assessment

Below is a brief description of IDL routines for checking math error status and machine characteristics. More detailed information is available in the IDL Reference Guide.

CHECK_MATH( )	Return and clear accumulated math error status.

FINITE( )	Returns TRUE if argument is finite.

MACHAR( )	Returns machine-specific parameters that affect floating-point arithmetic.

References

Burden, Richard L., J. Douglas Faires, and Albert C. Reynolds. Numerical Analysis. Boston: PWS Publishing, 1993. ISBN 0-534-93219-3

Stoer, J., and R. Bulirsch. Introduction to Numerical Analysis. New York: Springer-Verlag, 1980. ISBN 0-387-90420-4

Press, William H. et al. Numerical Recipes in C: The Art of Scientific Computing. Cambridge: Cambridge University Press, 1992. ISBN 0-521-43108-5


Arrays and Matrices

In a computer, a multidimensional data set can be indexed in one of two ways. It can be indexed in column-major format, which means that the linear order of the data elements proceeds from the first element in the first column through the last element in the first column before beginning on the second column, and so on. This is the format used by the C and Pascal computer languages to index data.

Alternatively, data can be indexed in row-major format, meaning that the linear order of the data elements proceeds from the first element of the first row through the last element of the first row before beginning on the second row, and so on. This is the format used by FORTRAN, and is traditionally associated with image processing, because it keeps all the elements of a single image scan line together. Because IDL's origins are in image processing, it indexes data in row-major format.

For example, a two-by-two array A that looks like this on paper:

would be indexed: A(0,0), A(1,0), A(0,1), A(1,1) in IDL.

Remembering the difference between these two indexing schemes is crucial to effective use of IDL's matrix and array functions. To specify an individual element of a column-major array, you specify the row index first, then the column index. To specify an individual element of a row-major array, you specify the column index first, then the row index. Since many numerical algorithms assume data is indexed (row, column), while IDL indexes it (column, row), it is important to keep this distinction in mind.

IDL always allocates and references data in row-major format. In order to work with data in column-major format, use IDL's TRANSPOSE function to interchange the order of the indices.

For example, suppose you have an array A of data with each element set to the value of its one-dimensional subscript, stored in a column-major array, like this:

   0   3

   1   4

   2   5

If you give this array as input to an IDL function that expects data in row-major format, IDL will calculate an answer other than the one you expect. Why? Because while you consider the second element in this array to be the number one (the second element in the column-major array), IDL considers the second element to be the number three (the second element in the row-major array).

A column-major array can then be transformed into row-major format using the TRANSPOSE function:

PRINT, TRANSPOSE(A)	Transpose the column-major array into row-major format and print.

   0   1   2

   3   4   5

Symmetric Arrays

It is possible for an array to be indistinguishable from its transpose. In this case the number of columns and rows are identical and there is a symmetry between the rows of the array and the columns of its transpose. Arrays satisfying this condition are called symmetric. When dealing with symmetric arrays the use of the TRANSPOSE function is unnecessary, since A^T = A.

Multiplying Arrays

IDL has two operators used to multiply arrays. To illustrate the difference between the two operators, consider the following two arrays:

array1 = [ [1, 2, 1], [2, -1, 2] ]

array1 is a 3 column by 2 row array.

array2 = [ [1, 3], [0, 1], [1, 1] ]

array2 is a 2 column by 3 row array.

The # Operator

The # operator computes array elements by multiplying the columns of the first array by the rows of the second array. The resulting array has the same number of columns as the first array and the same number of rows as the second array. The second array must have the same number of columns as the first array has rows.

PRINT, array1#array2	Multiply the arrays and print the result.

IDL prints:

           7          -1           7

           2          -1           2

           3           1           3

The ## Operator

The ## operator does what is commonly referred to as matrix multiplication. It computes array elements by multiplying the rows of the first array by the columns of the second array. The resulting array has the same number of rows as the first array and the same number of columns as the second array. The second array must have the same number of rows as the first array has columns.

PRINT, array1##array2	Multiply the arrays and print the result.

IDL prints:

           2           6

           4           7

Note

The # and ## operators are order specific. Note also that A # B = B ## A.


Correlation Analysis

Given two n-element sample populations, X and Y, it is possible to quantify the "degree of fit" to a linear model using the correlation coefficient. The correlation coefficient, r, is a scalar quantity in the interval [-1.0, 1.0], and is defined as the ratio of the covariance of the sample populations to the product of their standard deviations.

 or

The correlation coefficient is a direct measure of how well two sample populations vary jointly. A value of r = +1 or r = -1 indicates a perfect fit to a positive or negative linear model, respectively. A value of r close to +1 or -1 indicates a high degree of correlation and a good fit to a linear model. A value of r close to 0 indicates a poor fit to a linear model.

Examples

The following sample populations represent a perfect positive linear correlation.

X = [-8.1,  1.0, -14.3, 4.2, -10.1, 4.3, 6.3, 5.0, 15.1, -2.2]

Y = [-9.8, -0.7, -16.0, 2.5, -11.8, 2.6, 4.6, 3.3, 13.4, -3.9]

Compute the correlation coefficient of X and Y.

PRINT, CORRELATE(X, Y)

IDL prints:

1.00000

The following sample populations represent a high negative linear correlation.

X = [ 1.8, -2.7,  0.7, -0.5, -1.3, -0.9,  0.6, -1.5,  2.5,  3.0]

Y = [-4.7,  9.8, -3.7,  2.8,  5.1,  3.9, -3.6,  5.8, -7.3, -7.4]

Compute the correlation coefficient of X and Y.

PRINT, CORRELATE(X, Y)

IDL prints:

-0.979907

The following sample populations represent a poor linear correlation.

X = [-1.8,  0.1, -0.1, 1.9, 0.5,  1.1, 1.9,  0.3, -0.2, -1.0]

Y = [ 1.5, -1.0, -0.6, 1.1, 0.7, -0.7, 1.1, -0.1,  0.6, -0.1]

Compute the correlation coefficient of X and Y.

PRINT, CORRELATE(X, Y)

IDL prints:

0.0322859

Notes on Interpreting the Correlation Coefficient

When interpreting the value of the correlation coefficient, it is important to remember the following two caveats:

1.	Although a high degree of correlation (a value close to +1 or -1) indicates a good mathematical fit to a linear model, its applied interpretation may be completely nonsensical. For example, there may be a high degree of correlation between the number of scientists using IDL to study atmospheric phenomena and the consumption of alcohol in Russia, but the two events are clearly unrelated.

2.	Although a correlation coefficient close to 0 indicates a poor fit to a linear model, it does not mean that there is no correlation between the two sample populations. It is possible that the relationship between X and Y is accurately described by a nonlinear model. See "Curve and Surface Fitting" on page 20-10 for further details on fitting data to linear and nonlinear models.

Multiple Linear Models

The fundamental principles of correlation that apply to the linear model of two sample populations may be extended to the multiple-linear model. The degree of relationship between three or more sample populations may be quantified using the  multiple correlation coefficient. The degree of relationship between two sample populations when the effects of all other sample populations are removed may be quantified using the partial correlation coefficient. Both of these coefficients are scalar quantities in the interval [0.0, 1.0]. A value of +1 indicates a perfect linear relationship between populations. A value close to +1 indicates a high degree of linear relationship between populations; whereas a value close to 0 indicates a poor linear relationship between populations. (Although a value of 0 indicates no linear relationship between populations, remember that there may be a nonlinear relationship.)

Examples

Define the independent (X) and dependent (Y) data.

X = [[0.477121, 2.0, 13.0], $

     [0.477121, 5.0, 6.0], $

     [0.301030, 5.0, 9.0], $

     [0.000000, 7.0, 5.5], $

     [0.602060, 3.0, 7.0], $

     [0.698970, 2.0, 9.5], $

     [0.301030, 2.0, 17.0], $

     [0.477121, 5.0, 12.5], $

     [0.698970, 2.0, 13.5], $

     [0.000000, 3.0, 12.5], $

     [0.602060, 4.0, 13.0], $

     [0.301030, 6.0, 7.5], $

     [0.301030, 2.0, 7.5], $

     [0.698970, 3.0, 12.0], $

     [0.000000, 4.0, 14.0], $

     [0.698970, 6.0, 11.5], $

     [0.301030, 2.0, 15.0], $

     [0.602060, 6.0, 8.5], $

     [0.477121, 7.0, 14.5], $

     [0.000000, 5.0, 9.5]]

Y = [97.682, 98.424, 101.435, 102.266, 97.067, 97.397, $

     99.481, 99.613, 96.901, 100.152, 98.797, 100.796, $

     98.750, 97.991, 100.007, 98.615, 100.225, 98.388, $

     98.937, 100.617]

Compute the multiple correlation of Y on the first column of X. The result should be 0.798816.

PRINT, M_CORRELATE(X(0,*), Y)

IDL prints:

0.798816

Compute the multiple correlation of Y on the first two columns of X. The result should be 0.875872.

PRINT, M_CORRELATE(X(0:1,*), Y)

IDL prints:

0.875872

Compute the multiple correlation of Y on all columns of X. The result should be 0.877197.

PRINT, M_CORRELATE(X, Y)

IDL prints:

0.877197

Define the five sample populations.

X0 = [30, 26, 28, 33, 35, 29]

X1 = [0.29, 0.33, 0.34, 0.30, 0.30, 0.35]

X2 = [65, 60, 65, 70, 70, 60]

X3 = [2700, 2850, 2800, 3100, 2750, 3050]

Y  = [37, 33, 32, 37, 36, 33]

Compute the partial correlation of X1 and Y with the effects of X0, X2 and X3 removed.

PRINT, P_CORRELATE(X1, Y, REFORM([X0,X2,X3], 3, N_ELEMENTS(X1)))

IDL prints:

0.996017

Routines for Computing Correlations

Below is a brief description of IDL routines for computing correlations. More detailed information is available in the IDL Reference Guide.

A_CORRELATE( )	Compute the autocorrelation or autocovariance of a sample population as a function of the lag.

C_CORRELATE( )	Compute the cross-correlation or cross-covariance of a sample population as a function of the lag.

CORRELATE( )	Compute the linear correlation coefficient.

M_CORRELATE( )	Compute the multiple correlation coefficient.

P_CORRELATE( )	Compute the partial correlation coefficient.

R_CORRELATE( )	Compute the rank correlation of two populations.

References

Harnet, Donald L. Introduction to Statistical Methods. Reading, Massachusetts: Addison-Wesley, 1975. ISBN 0-201-02752-6

Neter, John., William Wasserman, and G.A. Whitmore. Applied Statistics. Newton, Massachusetts: Allyn and Bacon, 1988. ISBN 0-205-10328-6

Press, William H. et al. Numerical Recipes in C: The Art of Scientific Computing. Cambridge: Cambridge University Press, 1992. ISBN 0-521-43108-5


Curve and Surface Fitting

The problem of curve fitting may be stated as follows:

Given a tabulated set of data values {xi, yi} and the general form of a mathematical model (a function f(x) with unspecified parameters), determine the parameters of the model that minimize an error criterion. The problem of surface fitting involves tabulated data of the form {xi, yi, zi} and a function f(x, y) of two spatial dimensions.

For example, we can use the CURVEFIT routine to determine the parameters A and B of a user-supplied function f(x), such that the sums of the squares of the residuals between the tabulated data {xi, yi} and function are minimized. We will use the following function and data:

f (x) = a (1 - e^-bx)

xi = [0.25, 0.75, 1.25, 1.75, 2.25]

yi = [0.28, 0.57, 0.68, 0.74, 0.79]

First we must provide a procedure written in IDL to evaluate the function, f, and its partial derivatives with respect to the parameters a0 and a1:

PRO funct, X, A, F, PDER

  F = A(0) * (1.0 - EXP(-A(1) * X))

  IF N_PARAMS() GE 4 THEN BEGIN	If the function is called with four parameters, calculate the partial derivatives.

    pder = FLTARR(N_ELEMENTS(X), 2)

PDER's column dimension is equal to the number of elements in xi and its row dimension is equal to the number of parameters in the function f.

    pder(*, 0) = 1.0 - EXP(-A(1) * X)

Compute the partial derivatives with respect to a0 and place in the first row of PDER.

    pder(*, 1) = A(0) * x * EXP(-A(1) * X)

Compute the partial derivatives with respect to a1 and place in the second row of PDER.

  ENDIF

END

Note that the function will not calculate the partial derivatives unless it is called with four parameters. This allows the calling routine (in this case CURVEFIT) to avoid the extra computation in cases when the partial derivatives are not needed.

Next, we can use the following IDL commands to find the function's parameters:

X = [0.25, 0.75, 1.25, 1.75, 2.25]

Y = [0.28, 0.57, 0.68, 0.74, 0.79]

Define the vectors of tabulated data values.

W = 1.0 / Y	Define a vector of weights.

A = [1.0, 1.0]	Provide an initial guess of the function's
parameters.

yfit = CURVEFIT(X, Y, W, A, SIGMA_A, FUNCTION_NAME = 'funct')

Compute the parameters a0 and a1.

PRINT, A	Print the parameters, which are returned
in A.

IDL prints:

  0.787386  1.71602

Thus the nonlinear function that best fits the data is:

f (x) = 0.787386 ( 1 - e^-1.71602x )

Routines for Curve and Surface Fitting

Below is a brief description of IDL routines for curve and surface fitting. More detailed information is available in the IDL Reference Guide.

COMFIT( )	Gradient-expansion least squares fit to paired data.

CURVEFIT( )	Non-linear least squares fit to a function.

GAUSSFIT( )	Fit sum of a gaussian and a quadratic.

LADFIT( )	Least absolute deviation fit to paired data.

LINFIT( )	Minimal Chi-square fit to paired data.

POLY_FIT( )	Polynomial least squares fit.

POLYFITW( )	Weighted polynomial least squares fit.

REGRESS( )	Multiple linear regression.

SFIT( )	Determine a polynomial fit to a surface.

SVDFIT( )	General least squares fit using SVD.

References

Bevington, Philip R. Data Reduction and Error Analysis for the Physical Sciences. New York: McGraw-Hill, 1969.

Lancaster, Peter and Kestutis Salkauskas. Curve and Surface Fitting (An Introduction). San Diego: Academic Press, 1986. ISBN 0-124-36060-0


Eigenvalues and Eigenvectors

Consider a system of equations that satisfies the array-vector relationship Ax = λx, where A is an n x n array, x is an n-element vector, and λ is a scalar. A scalar λ and nonzero vector x that simultaneously satisfy this relationship are referred to as an  eigenvalue and an eigenvector of the array A, respectively. The set of all eigenvectors of the array A is then referred to as the eigenspace of A. Ideally, the eigenspace will consist of n linearly-independent eigenvectors, although this is not always the case.

IDL computes the eigenvalues and eigenvectors of a real symmetric n x n array using "Householder" transformations and the QL algorithm with implicit shifts. The eigenvalues of a real, n x n nonsymmetric array are computed from the "upper Hessenberg" form of the array using the QR algorithm. Eigenvectors are computed using inverse subspace iteration.

Although it is not practical for numerical computation, the problem of computing eigenvalues and eigenvectors can also be defined in terms of the determinant function. The eigenvalues of an n x n array A are the roots of the polynomial defined by                  det(A - λI), where I is the "identity matrix" (an array with 1s on the main diagonal and 0s elsewhere) with the same dimensions as A. By expressing eigenvalues as the roots of a polynomial, we see that they can be either real or complex. If an eigenvalue is complex, its corresponding eigenvector(s) is (are) also complex.

The following examples demonstrate how to use IDL to compute the eigenvalues and eigenvectors of real, symmetric and nonsymmetric n x n arrays. Note that it is possible to check the accuracy of the computed eigenvalues and eigenvectors by algebraically manipulating the definition given above to read Ax - λx = 0; in this case 0 denotes an n-element vector, all elements of which are zero.

Example 1: Symmetric Array with n Distinct Real Eigenvalues

To compute eigenvalues and eigenvectors of a real, symmetric, n x n array, begin with a symmetric array A. Note that the eigenvalues and eigenvectors of a real, symmetric n x n array will always be real.

A = [[ 3.0,  1.0, -4.0], $

     [ 1.0,  3.0, -4.0], $

     [-4.0, -4.0,  8.0]]

TRIRED, A, D, E	Compute the tridiagonal form of A.

Compute the eigenvalues (returned in vector D) and the eigenvectors (returned in the rows of the array A):

TRIQL, D, E, A

PRINT, D	Print eigenvalues.

IDL prints:

  2.00000  4.76837e-07  12.0000

The exact values are: [2.0, 0.0, 12.0].

PRINT, A	Print the eigenvectors, which are returned as row vectors in A.

IDL prints:

  0.707107  -0.707107   0.00000

 -0.577350  -0.577350  -0.577350

 -0.408248  -0.408248   0.816497

The exact eigenvectors are:

Example 2:	 Nonsymmetric Array with n Distinct Real and
Complex Eigenvalues

To compute the eigenvalues and eigenvectors of a real, nonsymmetric  n x n array, begin with an array A. In this example, there are n distinct eigenvalues and n linearly-independent eigenvectors.

A = [[ 1.0, 0.0,  2.0], $

     [ 0.0, 1.0, -1.0], $

     [-1.0, 1.0,  1.0]]

hes = ELMHES(A)	Reduce to upper Hessenberg format.

evals = HQR(hes)	Compute the eigenvalues.

PRINT, evals	Print the eigenvalues.

IDL prints:

(  1.00000, -1.73205)(  1.00000,  1.73205)

(  1.00000,  0.00000)

Note that the three eigenvalues are distinct, and that two are complex. Note also that complex eigenvalues of an n x n real, nonsymmetric array always occur in complex conjugate pairs.

residual = 1	Initialize a variable to contain the residual.

evecs = EIGENVEC(A, evals, /DOUBLE, RESIDUAL=residual)
Compute the eigenvectors and the residual for each eigenvalue/eigenvector pair, using double-precision arithmetic.

PRINT, evecs(*,0) 	Print the eigenvectors, which are returned as row vectors in evecs.

IDL prints:

(  0.68168704,  0.18789033)( -0.34084352, -0.093945164)

(  0.16271780, -0.59035830)

PRINT, evecs(*,1)

IDL prints:

(  0.18789033,  0.68168704)( -0.093945164, -0.34084352)

( -0.59035830,  0.16271780)

PRINT, evecs(*,2)

IDL prints:

(  0.70710678,  0.0000000)(  0.70710678,  0.0000000)

( -2.3570226e-21, 0.0000000)

We can check the accuracy of these results using the relation Ax - λx = 0. The array contained in the variable specified by the RESIDUAL keyword contains the result of this computation.

PRINT, residual

IDL prints:

( -1.2021898e-07,  1.1893681e-07)(  6.0109490e-08, -5.9468404e-08)

(  1.0300230e-07,  1.0411269e-07)

(  1.1893681e-07, -1.2021898e-07)( -5.9468404e-08,  6.0109490e-08)

(  1.0411269e-07,  1.0300230e-07)

(      0.0000000,      0.0000000)(      0.0000000,      0.0000000)

The results are all zero to within machine precision.

Example 3: Repeated Eigenvalues

To compute the eigenvalues and eigenvectors of a real, nonsymmetric  n x n array, begin with an array A. In this example, there are fewer than  n distinct eigenvalues, but n independent eigenvectors are available.

A = [[8.0, 0.0, 3.0], $

     [2.0, 2.0, 1.0], $

     [2.0, 0.0, 3.0]]

evals = HQR(ELMHES(A))	Reduce A to upper Hessenberg form and compute the eigenvalues. Note that both operations can be combined into a single command.

PRINT, evals	Print the eigenvalues.

IDL prints:

(  9.00000,  0.00000) (  2.00000,  0.00000)

(  2.00000,  0.00000)

Note that the three eigenvalues are real, but only two are distinct.

residual = 1	Initialize a variable to contain the residual.

evecs = EIGENVEC(A, evals, /DOUBLE, RESIDUAL=residual)
Compute the eigenvectors and residual, using double-precision arithmetic.

PRINT, evecs(*,0) 	Print the eigenvectors.

IDL prints:

(  0.90453403,  0.0000000)(  0.30151134,  0.0000000)

(  0.30151134,  0.0000000)

PRINT, evecs(*,1)

( -0.27907279,  0.0000000)( -0.78140380,  0.0000000)

(  0.55814557,  0.0000000)

PRINT, evecs(*,2)

( -0.27907279,  0.0000000)( -0.78140380,  0.0000000)

(  0.55814557,  0.0000000)

We can compute an independent eigenvector for the repeated eigenvalue (2.0) by perturbing it slightly, allowing the algorithm EIGENVEC to "recognize" the eigenvalue as distinct and to compute a linearly-independent eigenvector.

newresidual = 1

evecs(*,2) = EIGENVEC(A, evals(2)+1.0e-6, /DOUBLE, $

    RESIDUAL = newresidual)

PRINT, evecs(*,2)

( -0.33333333,  0.0000000)(  0.66666667,  0.0000000)

(  0.66666667,  0.0000000)

Once again, we can check the accuracy of these results by checking that each element in the residuals—for both the original eigenvectors and the "perturbed" eigenvector —is zero to within machine precision.

Example 4: The "Defective" Case

In the "defective" case, there are fewer than n distinct eigenvalues and fewer than n linearly-independent eigenvectors. Begin with an array A:

A = [[2.0, -1.0], $

     [1.0,  0.0]]

evals = HQR(ELMHES(A))	Reduce A to upper Hessenberg form and compute the eigenvalues. Note that both operations can be combined into a single command.

PRINT, evals	Print the eigenvalues.

IDL prints:

(  1.00000,  0.00000)(  1.00000,  0.00000)

Note that the two eigenvalues are real, but not distinct.

evecs = EIGENVEC(A, evals, /DOUBLE) 	Compute the eigenvectors, using double-precision arithmetic.

PRINT, evecs(*,0) 	Print the eigenvectors.

IDL prints:

(  0.70710678,  0.0000000)(  0.70710678,  0.0000000)

PRINT, evecs(*,1)

IDL prints:

(  0.70710678,  0.0000000)(  0.70710678,  0.0000000)

We attempt to compute an independent eigenvector using the method described in the previous example:

evecs(*,1) = EIGENVEC(A, evals(1)+1.0e-6, /DOUBLE)

PRINT, evecs(1,*)

IDL prints:

(  0.70710678,  0.0000000)(  0.70710678,  0.0000000)

In this example, n independent eigenvectors do not exist. This situation is termed the "defective" case and cannot be resolved analytically or numerically.

Routines for Computing Eigenvalues and Eigenvectors

Below is a brief description of IDL routines for computing eigenvalues and eigenvectors. More detailed information is available in the IDL Reference Guide.

EIGENVEC( )	Compute eigenvectors of a real, nonsymmetric array, given the array and its eigenvalues.

ELMHES( )	Reduce a real, nonsymmetric array to upper-Hessenberg form.

HQR( )	Compute the eigenvalues of an upper-Hessenberg array.

TRIQL	Compute eigenvalues and eigenvectors of a real, symmetric, tridiagonal array.

TRIRED	Use Householder's method to reduce a real, symmetric array to tridiagonal form.

 References

Press, William H. et al. Numerical Recipes in C: The Art of Scientific Computing. Cambridge: Cambridge University Press, 1992. ISBN 0-521-43108-5

Strang, Gilbert. Linear Algebra and Its Applications. San Diego: Harcourt Brace Jovanovich, 1988. ISBN 0-155-551005-3


Gridding and Interpolation

Given a set of tabulated data in

one	{xi, yi = f (xi)},

two 	{xi, yi, zi = f (xi, yi)}, or

three	{xi, yi, zi, wi = f (xi, yi, zi)}

dimensions, it is possible to calculate intermediate values of the function f using interpolation. IDL includes a variety of routines to solve this type of problem.

The determination of intermediate values is based upon an interpolating function that establishes a relationship between the tabulated data points. Different algorithms employ different types of interpolating functions suitable for different types of data trends.

Unlike curve-fitting algorithms, interpolation requires that the interpolating function be an exact fit at each of the tabulated data points. Interpolation does not use any type of error analysis and its accuracy depends upon the "behavior" of the interpolating function between successive data points. Polynomial, spline, nearest-neighbor, and kriging are among the interpolation methods used in IDL.

Gridding, a topic closely related to interpolation, is the problem of creating uniformly-spaced planar data from irregularly-spaced data. IDL handles this type of problem by constructing a Delaunay triangulation. This method is highly accurate and has great utility since many of IDL's graphics routines require uniformly-gridded data. Extrapolation, the estimation of values outside the range of tabulated data, is also possible using this method.

Routines for Gridding and Interpolation

Below is a brief description of IDL routines for gridding and interpolation. More detailed information is available in the IDL Reference Guide.

BILINEAR( )	Bilinear interpolation.

GRID3( )	Smooth fit to a set of 3D scattered nodes.

INTERPOL( )	Linear interpolation of vectors.

INTERPOLATE( )	Compute linear, bilinear, or trilinear interpolates.

KRIG2D( )	Interpolate regularly or irregularly gridded points using kriging.

MIN_CURVE_SURF( )	Interpolate regularly or irregularly gridded points using minimum curvature spline surface.

SPL_INIT( )	Establish interpolating spline for a data set (use with SPL_INTERP).

SPL_INTERP( )	Compute cubic-spline interpolated values (use with SPL_INIT).

POLAR_SURFACE( )	Interpolate a surface from polar coordinates to rectangular coordinates.

SPLINE( )	Cubic spline interpolation.

SPLINE_P 	Parametric cubic spline interpolation.

TRIANGULATE	Construct a Delaunay triangulation of a planar set of points. With TRIGRID, this procedure can interpolate irregularly-gridded data to a regular grid.

TRIGRID( )	Compute a regular grid of interpolated values.

VORONOI	Compute the Voronoi polygon of a point.

References

Lancaster, Peter and Kestutis Salkauskas. Curve and Surface Fitting (An Introduction). San Diego: Academic Press, 1986. ISBN 0-124-36060-0

Press, William H. et al. Numerical Recipes in C: The Art of Scientific Computing. Cambridge: Cambridge University Press, 1992. ISBN 0-521-43108-5


Hypothesis Testing

Hypothesis testing tests one or more sample populations for a statistical characteristic or interaction. The results of the testing process are generally used to formulate conclusions about the probability distribution(s) of the sample population(s).

Hypothesis testing involves four steps:

•	The formulation of a hypothesis.

•	The selection and collection of sample population data.

•	The application of an appropriate test.

•	The interpretation of the test results.

For example, suppose the FDA wishes to establish the effectiveness of a new drug in the treatment of a certain ailment. Researchers test the assumption that the drug is effective by administering it to a sample population and collecting data on the patients' health. Once the data are collected, an appropriate statistical test is selected and the results analyzed. If the interpretation of the test results suggests a statistically significant improvement in the patients' condition, the researchers conclude that the drug will be effective in general.

It is important to remember that a valid or successful test does not prove the proposed hypothesis. Only by disproving competing or opposing hypotheses can a given assumption's validity be statistically established.

One- and Two-sided Tests

In the above example, only the hypothesis that the drug would significantly improve the condition of the patients receiving it was tested. This type of test is called one-sided or one-tailed, because it is concerned with deviation in one direction from the norm (in this case, improvement of the patients' condition). A hypothesis designed to test the improvement or ill-effect of the trial drug on the patient group would be called  two-sided or two-tailed.

Parametric and Nonparametric Tests

Tests of hypothesis are usually classified into parametric and nonparametric methods. Parametric methods make assumptions about the underlying distribution from which sample populations are selected. Nonparametric methods make no assumptions about a sample population's distribution and are often based upon magnitude-based ranking, rather than actual measurement data. In many cases it is possible to replace a parametric test with a corresponding nonparametric test without significantly affecting the conclusion.

The following example demonstrates this by replacing the parametric T-means test with the nonparametric Wilcoxon Rank-Sum test to test the hypothesis that two sample populations have significantly different means of distribution.

Define two sample populations.

X = [257, 208, 296, 324, 240, 246, 267, 311, 324, 323, 263, $

     305, 270, 260, 251, 275, 288, 242, 304, 267]

Y = [201,  56, 185, 221, 165, 161, 182, 239, 278, 243, 197, $

     271, 214, 216, 175, 192, 208, 150, 281, 196]

Compute the T-statistic and its significance, using IDL's TM_TEST function, assuming that X and Y belong to Normal populations with the same variance.

PRINT, TM_TEST(X, Y)

IDL prints:

5.52839  2.52455e-06

The small value of the significance (2.52455e-06) indicates that X and Y have significantly different means.

Compute the Wilcoxon Rank-Sum Test, using IDL's RS_TEST function, to test the hypothesis that X and Y have the same mean of distribution.

PRINT, RS_TEST(X, Y)

IDL prints:

-4.26039  1.01924e-05

The small value of the computed probability (1.01924e-05) requires the rejection of the proposed hypothesis and the conclusion that X and Y have significantly different means of distribution.

Each of IDL's 11 parametric and nonparametric hypothesis testing functions is based upon a well-known and widely-accepted statistical test. Each of these functions returns a two-element vector containing the "statistic" on which the test is based and its significance. Examples are provided and demonstrate how the result is interpreted.

Routines for Hypothesis Testing

Below is a brief description of IDL routines for hypothesis testing. More detailed information is available in the IDL Reference Guide.

CTI_TEST( )	Construct contingency table from observed frequency data.

FV_TEST( )	Compute the F-statistic for two sample populations.

KW_TEST( )	Test the hypothesis that three or more sample populations have the same mean of distribution.

LNP_TEST( )	Compute the Lomb Normalized Periodogram of two sample populations.

MD_TEST( )	Test the hypothesis that a sample population is random.

R_CORRELATE( )	Compute the rank correlation of two sample populations.

R_TEST( )	Test the hypothesis that a binary population is random.

RS_TEST( )	Test the hypothesis that two sample populations have the same mean of distribution.

S_TEST( )	Test the hypothesis that two sample populations have the same mean of distribution.

TM_TEST( )	Compute the student's t-statistic for two sample populations.

XSQ_TEST( )	Compute the Chi-square goodness-of-fit between observed and expected frequencies.

References

Harnett, Donald H. Introduction to Statistical Methods. Reading, Massachusetts: Addison-Wesley, 1975. ISBN 0-201-02752-6

Kraft, Charles H. and Constance Van Eeden. A Nonparametric Introduction to Statistics. New York: Macmillan, 1968.

Sprent, Peter. Applied Nonparametric Statistical Methods. London: Chapman and Hall, 1989. ISBN 0-412-30600-X


Integration

Numerical methods of approximating integrals are important in many areas of pure and applied science. For a function of a single variable, f (x), it is often the case that the antiderivative F =∫f(x)dx   is unavailable using standard techniques such as trigonometric substitutions and integration-by-parts formulas. These standard techniques become increasingly unusable when integrating multivariate functions, f (x, y) and f (x, y, z). Numerically approximating the integral operator provides the only method of solution when the antiderivative is not explicitly available. IDL offers the following numerical methods for the integration of uni-, bi-, and trivariate functions:

•	Integration of a univariate function

over an open or closed interval is possible using one of several routines based on well known methods developed by Romberg and Simpson.

•	The problem of integrating over a tabulated set of data { xi, yi = f (xi) } can be solved using a highly accurate 5-point Newton-Cotes formula. This method is more accurate and efficient than using interpolation or curve-fitting to find an approximate function and then integrating.

•	Integration of a bivariate function

over a regular or irregular region in the x-y plane is possible using an iterated "Gaussian Quadrature" routine.

•	Integration of a trivariate function

over a regular or irregular region in x-y-z space is possible using an iterated "Gaussian Quadrature" routine.

Note

IDL's iterated "Gaussian Quadrature" routines, INT_2D and INT_3D, follow the dy-dx and dz-dy-dx order of evaluation, respectively. Problems not conforming to this standard must be changed as described in the following example.

Example 1: A Bivariate Function

Suppose that we wish to evaluate

The order of integration is initially described as a dx-dy region in the x-y plane. We can easily change the order to dy-dx. The integral is now of the form

The new expression can be evaluated using the INT_2D function.

To use INT_2D, we must specify the function to be integrated and expressions for the upper and lower limits of integration. First, we write an IDL function for the integrand, the function f (x, y):

FUNCTION fxy, X, Y

  RETURN, Y * COS(X^5)

END

Next, we write a function for the limits of integration of the inner integral. Note that the limits of the outer integral are specified numerically, in vector form, while the limits of the inner integral must be specified as an IDL function even if they are constants. In this case, the function is:

FUNCTION pq_limits, X

  RETURN, [0.0, X^2]

END

Now we can use the following IDL commands to print the value of the integral expressed above. First, we define a variable AB_LIMITS containing the vector of lower and upper limits of the outer integral. Next, we call INT_2D. The first argument is the name of the IDL function that represents the integrand (FXY, in this case). The second argument is the name of the variable containing the vector of limits for the outer integral (AB_LIMITS, in this case). The third argument is the name of the IDL function defining the lower and upper limits of the inside integral (PQ_LIMITS, in this case). The fourth argument (48) refers to the number of transformation points used in the computation. As a general rule, the number of transformation points used with iterated Gaussian Quadrature should increase as the integrand becomes more oscillatory or the region of integration becomes more irregular.

ab_limits = [0.0, 2.0]

PRINT, INT_2D('fxy', ab_limits, 'pq_limits', 48)

IDL prints:

0.055142668

This is the exact solution to 9 decimal accuracy.

Example 2: A Trivariate Function

Suppose that we wish to evaluate

This integral can be evaluated using the INT_3D function. As with INT_2D, we must specify the function to be integrated and expressions for the upper and lower limits of integration. Note that in this case IDL functions must be provided for the upper and lower integration limits of both inside integrals.

For the above integral, the required functions are the integrand f (x, y, z):

FUNCTION fxyz, X, Y, Z

  RETURN, Z * (X^2 + Y^2 + Z^2)^1.5

END

The limits of integration of the first inside integral:

FUNCTION pq_limits, X

  RETURN, [-SQRT(4.0 - X^2), SQRT(4.0 -X^2)]

END

The limits of integration of the second inside integral:

FUNCTION uv_limits, X, Y

  RETURN, [0.0, SQRT(4.0 - X^2 - Y^2)]

END

We can use the following IDL commands to determine the value of the above integral using 6, 10, 20 and 48 transformation points.

6 transformation points:

PRINT, INT_3D('fxyz', [-2.0, 2.0], 'pq_limits', 'uv_limits', 6)

IDL prints:

57.417720

10 transformation points:

PRINT, INT_3D('fxyz', [-2.0, 2.0], 'pq_limits', 'uv_limits', 10)

IDL prints:

57.444248

20 transformation points:

PRINT, INT_3D('fxyz', [-2.0, 2.0], 'pq_limits', 'uv_limits', 20)

IDL prints:

57.446201

48 transformation points:

PRINT, INT_3D('fxyz', [-2.0, 2.0], 'pq_limits', 'uv_limits', 48)

IDL prints:

57.446265

The exact solution to 6-decimal accuracy is 57.446267.

Routines for Integration

Below is a brief description of IDL routines for integration. More detailed information is available in the IDL Reference Guide.

INT_2D( )	Evaluate the double integral of a bivariate function f(x,y).

INT_3D( )	Evaluate the triple integral of a trivariate function f(x,y,z).

INT_TABULATED( )	Integrate a tabulated data set { xi, yi = f (xi) }.

QROMB( )	Evaluate integral over a closed interval using Romberg's method.

QROMO( )	Evaluate integral over an open interval using a modified Romberg's method.

QSIMP( )	Evaluate integral over a closed interval using Simpson's method.

References

Chapra, Steven C. and Raymond P. Canale. Numerical Methods for Engineers. New York: McGraw-Hill, 1988. ISBN 0-070-79984-9

Press, William H. et al. Numerical Recipes in C: The Art of Scientific Computing. Cambridge: Cambridge University Press, 1992. ISBN 0-521-43108-5


Linear Systems

IDL offers a variety of methods for the solution of simultaneous linear equations. In order to use these routines successfully, the user should consider both existence and uniqueness criteria and the potential difficulties in finding the solution numerically.

The solution vector x of an n by n linear system Ax = b is guaranteed to exist and to be unique if the coefficient array A is invertible. Using a simple algebraic manipulation, it is possible to formulate the solution vector x in terms of the inverse of the coefficient array A and the right-side vector b: x = A^-1b. Although this relationship provides a concise mathematical representation of the solution, it is never used in practice. Array inversion is computationally expensive (requiring a large number of floating-point operations) and prone to severe round-off errors.

An alternate way of describing the existence of a solution is to say that the system Ax = b is solvable if and only if the vector b may be expressed as a linear combination of the columns of A. This definition is important when considering the solutions of non-square (over- and under-determined) linear systems.

While the invertabiltiy of the coefficient array A may ensure that a solution exists, it does not help in determining the solution. Some systems can be solved accurately using numerical methods whereas others cannot. In order to better understand the accuracy of a numerical solution, we can classify the condition of the system it solves.

The scalar quantity known as the condition number of a linear system is a measure of a solution's sensitivity to the effects of finite-precision arithmetic. The condition number of an n x n linear system Ax = b is computed explicitly as |A||A^-1| (where | | denotes a Euclidean norm). A linear system whose condition number is small is considered well-conditioned and well suited to numerical computation. A linear system whose condition number is large is considered ill-conditioned and prone to computational errors. To some extent, the solution of an ill-conditioned system may be improved using an extended-precision data type (such as double-precision float). Other situations require an approximate solution to the system using its Singular Value Decomposition.

The following two examples show how the singular value decomposition may be used to find solutions when a linear system is over- or underdetermined.

Example 1: Overdetermined Systems

In the case of the overdetermined system (when there are more linear equations than unknowns), the vector b cannot be expressed as a linear combination of the columns of array A. (In other words, b lies outside of the subspace spanned by the columns of A.) Using IDL's SVDC procedure, it is possible to determine a projected solution of the overdetermined system (b is projected onto the subspace spanned by the columns of A and then the system is solved). This type of solution has the property of minimizing the residual error E = b - Ax in a least-squares sense.

Suppose that we wish to solve the following linear system:

The vector b does not lie in the two-dimensional subspace spanned by the columns of A (there is no linear combination of the columns of A that yield b), and therefore an exact solution is not possible.

It is possible, however, to find a solution to this system that minimizes the residual error by orthogonally projecting the vector b onto the two-dimensional subspace spanned by the columns of the array A. The projected vector is then used as the right-hand side of the system. The orthogonal projection of b onto the column space of A may be expressed with the array-vector product A(A^TA)^-1A^Tb, where A(A^TA)^-1A^T is known as the projection matrix, P.

In this example, the array-vector product Pb yields:

and we wish to solve the linear system

In many cases, the explicit calculation of the projected solution is numerically unstable, resulting in large accumulated round-off errors. For this reason it is best to use singular value decomposition to effect the orthogonal projection of the vector b onto the subspace spanned by the columns of the array A.

The following IDL commands use singular value decomposition to solve the system in a numerically stable manner. Begin with the array A:

A = [[1.0, 2.0], $

     [1.0, 3.0], $

     [0.0, 0.0]]

B = [4.0, 5.0, 6.0]	Define the right-hand side vector B.

SVDC, A, W, U, V	Compute the singular value decomposition of A.

Create a diagonal array WP of reciprocal singular values from the output vector W. To avoid overflow errors when the reciprocal values are calculated, only elements with absolute values greater than or equal to 1.0 x 10^-5 are reciprocated.

N = N_ELEMENTS(W)

WP = FLTARR(N, N)

FOR K = 0, N-1 DO $

  IF ABS(W(K)) GE 1.0e-5 THEN WP(K, K) = 1.0/W(K)

We can now express the solution to the linear system as a array-vector product. (See Section 2.6 of Numerical Recipes for a derivation of this formula.)

X = V ## WP ## TRANSPOSE(U) ## B

PRINT, X	Print the solution.

IDL Prints:

2.00000

1.00000

Example 2: Underdetermined Systems

In the case of the underdetermined system (when there are fewer linear equations than unknowns), a unique solution is not possible. Using IDL's SVDC procedure it is possible to determine the minimal norm solution. Given a vector norm, this type of solution has the property of having the minimal length of all possible solutions with respect to that norm.

Suppose that we wish to solve the following linear system.

Using elementary row operations it is possible to reduce the system to

It is now possible to express the solution x in terms of x1 and x3:

The values of x1 and x3 are completely arbitrary. Setting x1 = 0 and x3 = 0 results in one possible solution of this system:

Another possible solution is obtained using singular value decomposition and results in the minimal norm condition. The minimal norm solution for this system is:

Note that this vector also satisfies the solution x as it is expressed in terms of x1 and x3.

The following IDL commands use singular value decomposition to find the minimal norm solution. Begin with the array A:

A = [[ 1.0, 3.0, 3.0, 2.0], $

     [ 2.0, 6.0, 9.0, 5.0], $

     [-1.0, -3.0, 3.0, 0.0]]

B = [1.0, 5.0, 5.0]	Define the right-hand side vector B.

SVDC, A, W, U, V 	Compute the decomposition of A.

Create a diagonal array WP of reciprocal singular values from the output vector W. To avoid overflow errors when the reciprocal values are calculated, only elements with absolute values greater than or equal to 1.0 x 10^-5 are reciprocated.

N = N_ELEMENTS(W)

WP = FLTARR(N, N)

FOR K = 0, N-1 DO $

  IF ABS(W(K)) GE 1.0e-5 THEN WP(K, K) = 1.0/W(K)

We can now express the solution to the linear system as a array-vector product. (See Section 2.6 of Numerical Recipes for a derivation of this formula.) The solution is expressed in terms of x1 and x3 with minimal norm.

X = V ## WP ## TRANSPOSE(U) ## B

PRINT, X	Print the solution.

IDL Prints:

-0.211009

-0.633027

 0.963303

 0.110092

Example 3: Complex Linear Systems

We can use IDL's LU_COMPLEX function to compute the solution to a linear system with real and complex coefficients. Suppose we wish to solve the following linear system:

First we define the real part of the complex coefficient array:

re = [[-1, 1, 2, 3], $

      [-2, -1, 0, 3], $

      [3, 0, 0, 0], $

      [2, 1, 2, 2]]

Next, we define the imaginary part of the coefficient array:

im = [[0, -3, 0, 3], $

      [0, 3, 1, 1], $

      [0, 4, -1, -3], $

      [0, 1, 1, 1]]

A = COMPLEX(re, im)	Combine the real and imaginary parts to form a single complex coefficient array.

B = [COMPLEX(15,-2), COMPLEX(-2,-1), COMPLEX(-20,11), COMPLEX(-10,10)]
Define the right-hand side vector B.

Compute the solution using double-precision complex arithmetic.

z = LU_COMPLEX(A, B, /DOUBLE)

PRINT, TRANSPOSE(Z), FORMAT = '(f5.2, ",", f5.2, "i")'

IDL prints:

-4.00, 1.00i

 2.00, 2.00i

 0.00, 3.00i

-0.00,-1.00i

We can check the accuracy of the computed solution by computing the residual, Az-b:

PRINT, A##Z-B

IDL prints:

(      0.00000,      0.00000)

(      0.00000,      0.00000)

(      0.00000,      0.00000)

(      0.00000,      0.00000)

Routines for Solving Simultaneous Linear Equations

Below is a brief description of IDL routines for solving simultaneous linear equations. More detailed information is available in the IDL Reference Guide.

CHOLDC	Construct the Cholesky decomposition of an array.

CHOLSOL( )	Solve sets of linear equations (use with CHOLDC).

COND( )	Compute the condition number of a square array.

CRAMER( )	Solve a linear system using Cramer's rule.

DETERM( )	Compute the determinant of a square array.

GS_ITER( )	Solve a linear system using Gauss-Seidel iteration.

INVERT( )	Invert a square array.

LU_COMPLEX( )	Solve a complex linear system or invert a complex array.

LUDC	Construct the LU Decomposition of an array.

LUMPROVE( )	Iteratively improve the solution vector of a set of linear equations.

LUSOL( )	Solve sets of linear equations (use with LUDC).

NORM( )	Compute the infinity norm of a square array or the Euclidean norm of a vector.

SVDC	Construct the Singular Value Decomposition of an array.

SVSOL( )	Use back-substitution to solve a set of simultaneous linear equations (use with SVDC).

TRISOL( )	Solve a tridiagonal system of linear equations.

References

Golub, Gene H. and Van Loan, Charles F. Matrix Computations. Baltimore: Johns Hopkins University Press, 1989. ISBN 0-8018-3772-3

Kreyszig, Erwin. Advanced Engineering Mathematics. New York: Wiley & Sons, Inc., 1993. ISBN 0-471-55380-8

Press, William H. et al. Numerical Recipes in C: The Art of Scientific Computing. Cambridge: Cambridge University Press, 1992. ISBN 0-521-43108-5

Strang, Gilbert. Linear Algebra and Its Applications. San Diego: Harcourt Brace Jovanovich, 1988. ISBN 0-155-551005-3


Nonlinear Equations

The problem of finding a solution to a system of n nonlinear equations, F(x) = 0, may be stated as follows:

given F: Rn → Rn, find x* (an element of Rn) such that F(x*) = 0

For example:

x* = [0, 3] or x* = [3, 0]

Note: A solution to a system of nonlinear equations is not necessarily unique.

The most powerful and successful numerical methods for solving systems of nonlinear equations are loosely based upon a simple two-step iterative method frequently referred to as Newton's method. This method begins with an initial guess and constructs a solution by iteratively approximating the n-dimensional nonlinear system of equations with an n x n linear system of equations.

The first step formulates an n x n linear system of equations (Js = -F) where the coefficient array J is the Jacobian (the array of first partial derivatives of F), s is a solution vector, and -F is the negative of the nonlinear system of equations. Both J and -F are evaluated at the current value of the n-element vector x.

J(xk) sk = - F(xk)

The second step uses the solution sk of the linear system as a directional update to the current approximate solution xk of the nonlinear system of equations. The next approximate solution  xk+1 is a linear combination of the current approximate solution xk and the directional update sk.

xk+1 = xk + sk

The success of Newton's method relies primarily on providing an initial guess close to a solution of the nonlinear system of equations. In practice this proves to be quite difficult and severely limits the application of this simple two-step method.

IDL provides two algorithms that are designed to overcome the restriction that the initial guess be close to a solution. These algorithms implement a "line search" which checks, and if necessary modifies, the course of the algorithm at each step ensuring progress toward a solution of the nonlinear system of equations. IDL's NEWTON and BROYDEN functions are among a class of algorithms known as "quasi-Newton" methods.

The solution of an n-dimensional system of nonlinear equations, F(x) = 0, is often considered a root of that system. As a one-dimensional counterpart to NEWTON and BROYDEN, IDL provides the FX_ROOT and FZ_ROOTS functions.

Routines for Solving Nonlinear Equations

Below is a brief description of IDL routines for solving systems of nonlinear equations. More detailed information is available in the IDL Reference Guide.

BROYDEN( )	Solve sets of non-linear equations using a globally-convergent Broyden's method.

FX_ROOT( )	Compute the real and complex roots of a univariate non-linear function using Müller's method.

FZ_ROOTS( )	Compute the roots of a complex polynomial.

NEWTON( )	Solve sets of non-linear equations using a globally-convergent Newton's method.

References

Dennis, J.E. Jr. and Robert B. Schnabel. Numerical Methods for Unconstrained Optimization and Nonlinear Equations. Englewood Cliffs, NJ: Prentice-Hall, 1983. ISBN 0-136-27216-9

Press, William H. et al. Numerical Recipes in C: The Art of Scientific Computing. Cambridge: Cambridge University Press, 1992. ISBN 0-521-43108-5


Optimization

The problem of finding an unconstrained minimizer of an n-dimensional function, f, may be stated as follows:

given f: Rn → R, find x* (an element of Rn) such that f(x*) is a minimum of f.

For example:

f (x) = (x0 - 3)^4 + (x1 - 2)^2

x* = [3, 2]

In minimizing an n-dimensional function f, it is a necessary condition that the gradient at the minimizer x*, gradient f(x*), be the zero vector. Mathematically expressing this condition defines the following system of nonlinear equations.

This relation might suggest that finding a minimizer is equivalent to solving a system of linear equations based on the gradient. In most cases, however, this is not true. It is just as likely that a solution, x*, of gradient f(x)=0 be a maximizer or a local minimizer of f. Thus the gradient alone does not provide sufficient information in determining the role of x*.

IDL provides two algorithms that do sufficiently determine the global minimizer of an n-dimensional function. IDL's DFPMIN routine is among a class of algorithms known as "variable metric" methods and requires a user-supplied analytic gradient of the function to be minimized. IDL's POWELL routine implements a "direction-set" method that does not require a user-supplied analytic gradient. The utility of the POWELL routine is evident as the function to be minimized becomes more complicated and partial derivatives become more difficult to calculate.

Routines for Optimization

Below is a brief description of IDL routines for optimization. More detailed information is available in the IDL Reference Guide.

DFPMIN	Davidon-Fletcher-Powell minimization of a user supplied function.

POWELL	Powell minimization of a user supplied function.

References

Dennis, J.E. Jr. and Robert B. Schnabel. Numerical Methods for Unconstrained Optimization and Nonlinear Equations. Englewood Cliffs, NJ: Prentice-Hall, 1983. ISBN 0-136-27216-9

Press, William H. et al. Numerical Recipes in C: The Art of Scientific Computing. Cambridge: Cambridge University Press, 1992. ISBN 0-521-43108-5


Sparse Arrays

The occurrence of zero elements in a large array is both a computational and storage inconvenience. An array in which a large percentage of elements are zeros is referred to as being sparse.

Because standard linear algebra techniques are highly inefficient when dealing with sparse arrays, IDL incorporates a collection of routines designed to handle them effectively. These routines use the row-indexed sparse storage method, which stores the array in structure form, as a vector of data and a vector of indices. The length of each vector is equal to the number of diagonal elements of the array plus the number of off-diagonal elements with an absolute magnitude greater than or equal to a specified threshold value. Diagonal elements of the array are always retained even if their absolute magnitude is less than the specified threshold. Sparse array routines that handle array-vector and array-array multiplication, file input/output, and the solution of systems of simultaneous linear equations are included.

When considering using IDL's sparse array routines, remember that the computational savings gained by working in sparse storage format is at least partially offset by the need to first convert the arrays to that format. Although an absolute determination of when to use sparse format is not possible, the example below demonstrates the time savings when solving a 500 by 500 linear system in which approximately 50% of the coefficient array's elements as zeros.

Example

Note: the times shown here were recorded on a DEC 3000 Alpha workstation running OSF/1; they are shown as examples only. Your times will depend on your specific computing platform.

First, create a 500 by 500 element pseudo-random diagonally-dominant floating-point array in which approximately 50% of the elements as zeros. (In a diagonally-dominant array, the diagonal element in a given row is greater than the sum of the absolute values of the non-diagonal elements in that row.)

N = 500L

A = CEIL(RANDOMN(SEED, N, N)*10) + 0.0

Set elements with absolute magnitude greater than or equal to eight to zero.

I = WHERE(ABS(A) GE 8)

A(I) = 0.0

Set each diagonal element to the absolute sum of its row elements plus 1.0.

diag = TOTAL(ABS(A), 1)

A(INDGEN(N) * (N+1)) = diag + 1.0

Create a right-hand side vector, b, in which 40% of the elements are ones and 60% are twos.

B = [REPLICATE(1.0, 0.4*N), REPLICATE(2.0, 0.6*N)]

We now calculate a solution to this system using two different methods, measuring the time elapsed. First, we compute the solution using the iterative biconjugate gradient method and a sparse array storage format. Note that we include everything between the start and stop timer commands as a single operation, so that only computation time (as opposed to typing time) is recorded.

X = REPLICATE(1.0, N_ELEMENTS(B))
Begin with an initial guess.

start = SYSTIME(1) & $	Start the timer.

result1 = LINBCG(SPRSIN(A), B, X) & $
Solve the system.

stop = SYSTIME(1)	Stop the timer.

PRINT, 'Time for Iterative Biconjugate Gradient:', stop-start
Print the time taken, in seconds.

IDL prints:

Time for Iterative Biconjugate Gradient       1.1259040

Remember that your result will depend on your hardware configuration.

Next, we compute the solution using LU decomposition.

start = SYSTIME(1) & $	Start the timer.

LUDC, A, index & $	Compute the LU decomposition of A.

result2 = LUSOL(A, index, B) & $
Compute the solution.

stop = SYSTIME(1)	Stop the timer.

PRINT, 'Time for LU Decomposition:', stop-start
Print the time taken, in seconds.

IDL prints:

Time for LU decomposition       14.871168

Finally, we can compare the absolute error between result1 and result2. The following commands will print the indices of any elements of the two results that differ by more than 1.0 x 10^-5, or a "-1" if the two results are identical to within five decimal places.

error = ABS(result1-result2)

PRINT, WHERE(error GT 1.0e-5)

IDL prints:

-1

See the documentation for the WTN function for an example using IDL's sparse array functions with image data.

Routines for Handling Sparse Arrays

Below is a brief description of IDL routines for handling sparse arrays. More detailed information is available in the IDL Reference Guide. Note that SPRSIN must be used to convert to sparse storage format before the other routines can be used.

FULSTR( )	Restore a row-indexed sparse array to full storage format.

LINBCG( )	Solve a system of linear equations using the iterative biconjugate method.

READ_SPR( )	Read a row-indexed sparse array from a file.

SPRSAB( )	Multiply two row-indexed sparse arrays.

SPRSAX( )	Multiply a row-indexed sparse array by a vector.

SPRSIN( )	Convert an array to row-indexed sparse storage format.

WRITE_SPR	Write a row-indexed sparse array to a file.

References

Press, William H. et al. Numerical Recipes in C: The Art of Scientific Computing. Cambridge: Cambridge University Press, 1992. ISBN 0-521-43108-5


Time-Series Analysis

A time-series is a sequential collection of data observations indexed over time. In most cases, the observed data is continuous and is recorded at a discrete and finite set of equally-spaced points. An n-element time-series is denoted as x = (x(0), x(1), x(2), ... , x(n-1)), where the time-indexed distance between any two successive observations is referred to as the sampling interval.

A widely held theory assumes that a time-series is comprised of four components:

•	A "trend" or long term movement.

•	A "cyclical fluctuation" about the trend.

•	A pronounced "seasonal" effect.

•	A "residual", "irregular", or "random" effect.

Collectively, these components make the analysis of a time-series a far more challenging task than just fitting a linear or nonlinear regression model. Adjacent observations are unlikely to be independent of one another. Clusters of observations are frequently correlated with increasing strength as the time intervals between them become shorter. Often the analysis is a multi-step process involving graphical and numerical methods.

The first step in the analysis of a time-series is the transformation to stationarity. A stationary series exhibits statistical properties that are unchanged as the period of observation is moved forward or backward in time. Specifically, the mean and variance of a stationary time-series remain fixed in time. The "sample autocorrelation" function is a commonly used tool in determining the stationarity of a time-series. The autocorrelation of a time-series measures the dependence between observations as a function of their time differences or lag. A plot of the sample autocorrelation coefficients against corresponding lags can be very helpful in determining the stationarity of a time-series.

For example, suppose the IDL variable X contains time-series data:

X = [5.44, 6.38, 5.43, 5.22, 5.28, $

     5.21, 5.23, 4.33, 5.58, 6.18, $

     6.16, 6.07, 6.56, 5.93, 5.70, $

     5.36, 5.17, 5.35, 5.61, 5.83, $

     5.29, 5.58, 4.77, 5.17, 5.33]

The following IDL commands plot both the time-series data and the sample autocorrelation versus the lags.

!P.MULTI=[0,1,2]	Set the plotting window to hold two plots.

PLOT, X	Plot the data.

Compute the sample autocorrelation function for time lagged values 0 ­ 20 and plot.

lag = INDGEN(21)

result = A_CORRELATE(X, lag)

PLOT, lag, result

PLOTS, [0,20], [0,0], /DATA	Add a reference line at zero.

!P.MULTI=0	Set the plotting window back to a single plot.

The figure below shows the resulting graph.

Nonstationary components of a time-series may be eliminated in a variety of ways. Two frequently used methods are known as moving averages and forward differencing. The method of moving averages dampens fluctuations in a time-series by taking successive averages of groups of observations. Each successive overlapping sequence of k observations in the series is replaced by the mean of that sequence. The method of forward differencing replaces each time-series observation with the difference of the current observation and its adjacent observation one step forward in time. Differencing may be computed recursively to eliminate more complex nonstationary components.

Once a time-series has been transformed to stationarity, it may be modeled using an autoregressive process. An autoregressive process expresses the current observation, x(t), as a combination of past time-series values and residual white noise. The simplest case is known as a first order autoregressive model and is expressed as

x(t) = φx(t-1) + ω(t)

The coefficient φ is estimated using the time-series data. The general autoregressive model of order p is expressed as

x(t) = φ(1)x(t-1) + φ(2)x(t-2) + ... + φ(p)x(t-p) + ω(t)

Modelling a stationary time-series as a pth order autoregressive process allows the extrapolation of data for future values of time. This process is know as forecasting.

Routines for Time-Series Analysis

Below is a brief description of IDL routines for time-series analysis. More detailed information is available in the IDL Reference Guide.

A_CORRELATE( )	Compute the autocorrelation or autocovariance of a sample population.

C_CORRELATE( )	Compute the cross-correlation or cross-covariance of two sample populations.

SMOOTH( )	Smooth a time-series using a moving average.

TS_COEF( )	Compute the coefficients used in an autoregressive time-series forecasting model.

TS_DIFF( )	Compute forward differences of a time-series.

TS_FCAST( )	Compute the future values of a stationary time-series.

References

Chatfield, C. The Analysis of Time Series. London: Chapman and Hall, 1975. ISBN 0-412-31820-2

Neter, John., William Wasserman, and G.A. Whitmore. Applied Statistics. Newton, Massachusetts: Allyn and Bacon, 1988. ISBN 0-205-10328-6

Jump forward to Widgets

Jump backward to Map Projections


Widgets
21	Widgets

Chapter Overview

IDL allows the construction and manipulation of graphical user interfaces. This style of interaction offers many significant advantages over traditional command-line based systems. Widgets are simple graphical objects, such as pushbuttons or sliders, that allow user interaction via a pointing device (usually a mouse) and a keyboard.

IDL widgets are significantly easier to use than other alternatives, such as writing a C language program using the native window system directly. IDL handles much of the low-level work involved in using such toolkits. The interpretive nature of IDL makes it easy to prototype potential user interfaces. In addition to the user interface, the author of a program written in a traditional compiled language also must implement any computational and graphical code required by the program. IDL widget programs can draw on the full computational and graphical abilities of IDL to supply these components.

The style of widgets that are created depend on the windowing system supported by your host computer. Unix and VMS hosts use Motif widgets, while Microsoft Windows and Macintosh systems use their native toolkits. Although the different toolkits produce applications with a slightly different look and feel, most properly-written widget applications work on all systems without change.

IDL graphical user interfaces are constructed by combining widgets in a treelike hierarchy. Each widget has one parent widget and zero or more child widgets. There is one exception: the topmost widget (called a top-level base) is always a base widget and has no parent.

Programs that use widgets are event driven. In an event driven system, the program creates an interface and then waits for messages (events) to be sent to it from the window system. Events are generated in response to user manipulation, such as pressing a button or moving a slider. The program responds to such events by carrying out the computations requested by the user.


Topics in Widgets Chapter
Widgets

This chapter provides an overview of IDL's tools for constructing graphical user interfaces for IDL programs.

Topics Covered:

Widget Types

Examples of Widget Programming

The Widget Lifecycle

Simple Widget Example

Widget Events

Using the XMANAGER Procedure

Widget Values

Widget User Values

Compound Widgets

Managing the State of a Widget Application

Using Draw Widgets

Menus

The XREGISTERED Function

Using Timer Events

Widget Sizing

Miscellaneous Widget Information

A Larger Example

Writing a Compound Widget (CW_DICE)

Jump forward to Widget Builder

Jump backward to Mathematics


Widget Types

IDL supports the widget types listed below.

Base

A base is a widget used to hold other widgets, including other base widgets. Base widgets can optionally contain scroll bars that allow the base to be larger than the space on the screen. In this case, only part of the base is visible at any given time, and the scroll bars are used to control which part is visible. Base widgets are created by the WIDGET_BASE function.

Button

A pushbutton is activated by moving the mouse cursor over the button and pressing a mouse button. Button widgets are created by the WIDGET_BUTTON function.

Draw

Draw widgets offer a rectangular area that works like a standard IDL graphics window. Any graphical output that can be produced by IDL can be directed to one of these widgets through the WSET function. Draw widgets can optionally contain scrollbars that allow examining a graphical region larger than the area containing the widget. Draw widgets are created by the WIDGET_DRAW function.

Droplist

Droplist widgets look like regular buttons but, when selected, reveal a drop-down list of options. When a new option is selected from this list, the list disappears and the new selection becomes the new title for the droplist button. Droplist widgets are created by the WIDGET_DROPLIST function.

Label

Label widgets display static text. They are similar to single-line text widgets but are optimized for small labeling purposes. Text widgets should be used to display large amounts of text. Label widgets are created by the WIDGET_LABEL function.

List

A list widget offers the user a list of text elements from which to choose. Users can select an item by pointing with the mouse cursor and pressing a button. List widgets always have a vertical scrollbar and allow selection from a large number of items. List widgets are created by the WIDGET_LIST function.

Message

Message widgets are modal (or "blocking") dialog boxes that can display warnings, informational messages, or error messages. When a message dialog is displayed, no other widgets can be manipulated until the user dismisses the dialog by clicking on one of its buttons. Message widgets are special in that they do not really belong to widget hierarchies. Message widgets are instantly created when the WIDGET_MESSAGE function is called and block all other widget activity until dismissed. The function returns the text of the button that the user clicked.

Slider

Slider widgets are used to select or indicate a value within a range of possible values. They consist of a rectangular region that represents the possible range of values. Inside this region is a sliding pointer that displays the current value. This pointer can be manipulated by the user via the mouse or from within IDL by the WIDGET_CONTROL procedure. Slider widgets are created by the WIDGET_SLIDER function.

Text

Text widgets are used to display text and to get text input from the user. They can have one or more lines and can optionally contain scroll bars that allow viewing more text than can otherwise be displayed. Text widgets are created by the WIDGET_TEXT function.


Examples of Widget Programming

A number of simple examples of widget programming can be seen by running the IDL program EXAMPLES. A widget interface with a pulldown menu of small widget applications should appear. You can find the .pro files for these applications in the general subdirectory of the examples subdirectory of the IDL distribution.


The Widget Lifecycle

An application using widgets goes through the following cycle:

1. Construct the Widget Hierarchy

A widget hierarchy is built by combining the following widget creation functions:

WIDGET_BASE
WIDGET_BUTTON
WIDGET_DRAW
WIDGET_DROPLIST
WIDGET_LABEL
WIDGET_LIST
WIDGET_SLIDER
WIDGET_TEXT

These functions all return a "Widget ID," a long integer that uniquely identifies the newly created widget. This ID is used in creating and manipulating widgets. For instance, when creating a widget you must always supply the widget ID of its parent (except for the topmost base widget). At this point, the widgets exist only within IDL—nothing has been created or displayed on the window system. In addition to the seven basic widgets above, there are many functions and compound widgets (described later in this chapter) that can be used to easily add more sophisticated widgets to a widget hierarchy.

2. Realize the Widgets

The widget hierarchy is brought into existence using the REALIZE keyword to the WIDGET_CONTROL procedure. This causes the widgets to be created and displayed.

3. Register the Program with the XMANAGER

The program registers itself with the XMANAGER procedure and waits for events to be reported. An event is a message informing the requesting program that something of interest has happened to one of the widgets (button press, slider motion, etc.). This message is obtained by XMANAGER via the WIDGET_EVENT function and takes the form of a structure.

Each type of widget returns a different type of structure, the exact form of which is described in the documentation for the individual widget creation functions in the IDL Reference Guide. However, every event structure has the same first three elements. These are long integers named ID, TOP, and HANDLER. ID is the widget ID of the widget generating the event. TOP is the widget ID of the top-level base containing ID. HANDLER is important for event handler functions, which are discussed later in this chapter. When an event appears, XMANAGER passes it to an event-handling procedure specified by the program, and the event handler takes some appropriate action based on the event. Therefore, multiple widget applications can run simultaneously—XMANAGER dispatches the events to the appropriate routine.

4. Use WIDGET_CONTROL to Manipulate the Widgets

The IDL program can use the WIDGET_CONTROL procedure to manipulate the widgets. Possible actions include the following:

•	Obtain or change the value of a widget (see "Widget Values" on page 21-11) using the APPEND, GET_VALUE, and SET_VALUE keywords.

•	Obtain or change the value of a widget's user value (discussed in "Widget User Values" on page 21-12) using the GET_UVALUE and SET_UVALUE keywords.

•	Map and unmap widgets using the MAP keyword. Unmapped widgets are removed from the screen and become invisible, but they still exist.

•	Change a widget's sensitivity using the SENSITIVE keyword. When a widget is insensitive, it indicates the fact by changing its appearance (often by graying itself or displaying text with dashed lines) and ignores any user input. It is useful to make widgets insensitive at points where it would be inconvenient to get events from them (for example, if your program is in the wrong "mode").

•	Change the settings of toggle buttons using the SET_BUTTON keyword.

•	Push a widget hierarchy behind the other windows on the screen, or pull them in front using the SHOW keyword.

•	Display the "hourglass" cursor when the application is busy and not able to respond to user actions using the HOURGLASS keyword.

5. Use WIDGET_INFO to Obtain Information about Widgets

The program can use the WIDGET_INFO procedure to obtain information about widgets. Information is available on:

•	Existence of realized, top-level widgets on the screen.

•	The IDs of parent, child, and sibling widgets.

•	A widget's type.

•	Whether or not a given widget has been realized.

•	If a widget ID represents a currently-valid widget.

•	The type of widget toolkit being used.

•	Other, widget type specific information.

6. Destroy the Widgets

The widget hierarchy is destroyed by using the WIDGET_CONTROL procedure's DESTROY keyword. This causes all resources related to the hierarchy to be freed and removes it from the screen.

For the best performance, it is important that the program spend most of its time in the event loop of Step 3. Some widgets will not respond rapidly to user manipulation when not in this loop. Widget-based programs should wait for user-generated events, handle them as quickly as possible, and quickly return to wait for more events. Operations that are expected to be slow should indicate that fact to the user by turning on the hourglass cursor by setting the HOURGLASS keyword to WIDGET_CONTROL. This approach to computing is fundamentally different from the traditional command-based approach.


Simple Widget Example

In the following example, a menu of options is constructed by using a top-level base widget with 10 child buttons labeled 0 through 9. As soon as a button is pressed, its value is printed and the menu is destroyed.

The following commands create the top-level base with 10 child-button widgets. XMENU is a convenience function that builds a base populated with buttons. The default for the XMENU is to arrange the buttons in a column. The base widget ID is stored in BASE, and the button IDs in B.

XMENU, SINDGEN(10),BASE = base, BUTTONS = B

WIDGET_CONTROL, /REALIZE, base

event = WIDGET_EVENT(base)

PRINT, 'Pressed Button: ', WHERE(B EQ event.id)

WIDGET_CONTROL, base, /DESTROY

The resulting menu is shown in Figure 21.1. This example serves to show how simple a widget program can be. A program intended to be used in real applications would be written somewhat differently, as will become apparent in the remainder of this chapter.

The biggest problem with this example is that it calls the WIDGET_EVENT function directly, and the way in which WIDGET_EVENT is used precludes having more than a single widget application running simultaneously. Although WIDGET_EVENT is the basic event-handling routine for the IDL widget system, it is rarely called by user programs. Instead, the XMANAGER procedure should be used. XMANAGER uses WIDGET_EVENT to provide a simplified interface to widget processing while allowing multiple widget applications. This topic is discussed in detail on page 21-9.


Widget Events

The concept of events and event processing underlies every aspect of widget programming. It is important to understand how IDL handles widget events in order to use widgets effectively.

What are Widget Events?

A widget event is a message returned from the window system as the result of user interactions such as pressing a button or otherwise manipulating a widget. In response to an event, a widget program usually performs some desired action for the user (e.g., opens a file, updates a plot).

Structure of Widget Events

As events arrive, IDL saves them in a queue for the target widget. They are delivered to the IDL program by the WIDGET_EVENT function as IDL structures. Each type of widget returns a different type of structure, the exact form of which is described in the documentation for the individual widget creation functions in the IDL Reference Guide. However, every event has the same first three fields. These are long integers named ID, TOP, and HANDLER. ID is the widget ID of the widget generating the event. TOP is the widget ID of the top-level base containing ID. The meaning of HANDLER will become apparent when we discuss event routines and compound widgets, below.

Calling the WIDGET_EVENT Function

In its simplest form, the WIDGET_EVENT function is called with a widget ID (usually, the ID of a widget base) as its argument. WIDGET_EVENT checks the queue of undelivered events for that widget or any of its children. If an event is present, it is immediately dequeued and returned. If no event is available, WIDGET_EVENT blocks until one arrives and then returns it. Typically, the request is made for a top-level base, so WIDGET_EVENT returns events for any widget in that widget hierarchy (also called a widget tree).

This simple usage suffers from a major weakness. Since each call to WIDGET_EVENT is looking for events from a specified widget hierarchy, it is not possible to receive events for more than one widget hierarchy at a time. It is important to be able to run multiple widget applications (each with a separate top-level base) simultaneously. An example would be an image processing application, a colortable manipulation tool, and an on-line help reader all running together.

One solution to this problem is to call WIDGET_EVENT with an array of widget identifiers instead of a single ID. In this case, WIDGET_EVENT returns events for any widget hierarchy in the list. This solution is effective, but it still requires a complete list of all interesting top level base identifiers to be maintained, which implies that all cooperating applications need to know about each other.

The most powerful way to use WIDGET_EVENT is to call it without any arguments at all. Called this way, it will return events for any currently-realized widgets that have expressed an interest in being managed (done via the MANAGED keyword to the WIDGET_CONTROL procedure). This form of WIDGET_EVENT is especially useful when used in conjuction with widget event callback routines.

Managing Events with XMANAGER

The best way to call WIDGET_EVENT is to let the XMANANGER procedure do it for you. XMANAGER provides a more convenient interface for event processing. Most widget applications in the IDL distribution use XMANAGER to handle their events. See "Using the XMANAGER Procedure" on page 21-9.

Event Processing And Callback Routines

Previously we mentioned that when IDL receives an event, it is queued until a call to WIDGET_EVENT is made, when the event is dequeued and returned. That is a simplified description of what actually happens.

All events for a given widget are processed in the order that they are generated. The event processing performed by WIDGET_EVENT consists of the following steps, applied iteratively:

•	WIDGET_EVENT waits for an event from one of the specified widgets to arrive.

•	Starting with the widget that the event belongs to, move up the widget hierarchy looking for a widget that has an event-handling procedure or function associated with it. Such routines are associated with a widget via the EVENT_PRO and EVENT_FUNC keywords to the widget creation functions or the WIDGET_CONTROL procedure.

•	If an event-handling procedure is found, it is called with the event as its argument. The HANDLER field of the event is set to the widget ID of the widget associated with the handling procedure. When the procedure returns, WIDGET_EVENT returns to the first step above and starts searching for events. Hence, event-handling procedures are said to "swallow" events.

•	If an event-handling function is found, it is called with the event as its argument. The HANDLER field of the event is set to the widget ID of widget associated with the handling function.

When the function returns, its value is examined. If the value is not a structure, it is discarded and WIDGET_EVENT returns to the first step. This behavior allows event-handling functions to selectively act like event-handling procedures and "swallow" events.

If the returned value is a structure, it is checked to ensure that it has the standard first 3 fields: ID, TOP, and HANDLER. If not, an error is issued. Otherwise, the returned value replaces the event found in the first step and WIDGET_EVENT continues moving up the widget tree looking for another event handler routine, as described in step 2, above.

Hence, event functions are said to "rewrite" events. This ability to rewrite events is the basis of compound widgets which combine several widgets to give the appearance of a single, more complicated widget. Compound widgets are an important widget programming concept, and are discussed on page 21-12.

•	If an event reaches the top of a widget hierarchy without being swallowed by an event handler, it is returned as the value of WIDGET_EVENT.

•	If WIDGET_EVENT was called without an argument, and there are no widgets left on the screen that are being managed (as set via the MANAGED keyword to the WIDGET_CONTROL procedure) and could generate events, WIDGET_EVENT ends the search and returns an empty event (i.e., a standard widget event structure with the top three fields set to zero).


 Using the XMANAGER Procedure

As discussed above, WIDGET_EVENT provides basic widget event-handling capabilities. However, it is extremely rare for a user-written widget program to actually call WIDGET_EVENT directly. Instead, your programs should call the XMANAGER procedure, which provides a convenient, simplified interface to WIDGET_EVENT.

A widget application creates and realizes its widgets, and then calls XMANAGER. XMANAGER arranges for an event-handling procedure supplied by the application to be called when events for it arrive. The application is shielded from the details of calling WIDGET_EVENT and interacting with other widget applications that may be running simultaneously.

For these reasons, widget applications should always use XMANAGER in preference to calling WIDGET_EVENT directly. The XMNG_TMPL procedure is a template for writing widget applications that use XMANAGER.

Calling XMANAGER

XMANAGER is called with the following syntax:

XMANAGER[, Name, ID]

XMANAGER registers and keeps track of events for all registered widgets and controls the processing of tasks associated with widget applications. Its arguments are as follows:

NAME

A scalar string containing the name of the widget application that is to be managed. If this argument is omitted, XMANAGER skips the registration step and immediately attempts to manage any current widget applications that are still valid.

ID

The widget ID of the top level (base) of the widget being registered. If this argument is omitted, XMANAGER skips the registration step and immediately attempts to manage any current widget applications that are still valid.

XMANAGER Keywords

The optional keywords for XMANAGER are as follows:

EVENT_HANDLER

A string containing the name of the procedure called when an event occurs in the widget. The default event-handling routine is the name of the widget application with "_EVENT" concatenated at the end.

GROUP_LEADER

The widget ID of the group leader of the widget being registered. When specified, the death of the group leader will force the death of all widgets that were registered in that group.

JUST_REG

If set, this keyword instructs XMANAGER to simply register the new widget and return immediately without processing events.

MODAL

If set, the widget application being registered becomes the only sensitive widget and any other current widgets are made insensitive. XMANAGER dispatches events only for the modal widget application until it is destroyed.

Features Reserved to XMANAGER

To be able to work with XMANAGER, widget applications should avoid the following pitfalls. If you ignore the suggestions below, your changes will conflict with those made by XMANAGER:

•	Do not specify an event-handling function or procedure on the top level base of a widget application using the EVENT_FUNC or EVENT_PRO keywords to the widget creation functions or WIDGET_CONTROL. Instead, provide the name of the event handler routine to XMANAGER via the EVENT_HANDLER keyword.

•	Do not specify a death notification procedure on the top level base of a widget application using the KILL_NOTIFY keyword to the widget creation functions or WIDGET_CONTROL. Instead, provide the name of your "cleanup" routine to XMANAGER via the CLEANUP keyword.


Widget Values

Many widgets have values associated with them. Initial values are set using the VALUE keyword to the widget creation function. The value can be obtained and/or changed at any time using the GET_VALUE and SET_VALUE keywords to the WIDGET_CONTROL procedure. Widgets with a value are listed below:

Button

Type: Scalar string (text) or byte array (bitmap).

The value is the button label. The GET_VALUE keyword cannot be used to obtain bitmaps.

Draw

Type: Integer.

The value is the IDL window number for use with graphics routines, such as WSET. This value cannot be set or modified.

Label

Type: Scalar string.

The value is the label text.

List or Droplist

Type: Scalar string or string array.

The value represents the list elements. This value can only be set; it cannot be retrieved.

Slider

Type: Integer.

The value is the current slider position.

Text

Type: Scalar string or string array.

The value is the contents of the text widget. When setting this value, the APPEND keyword to the WIDGET_CONTROL procedure causes the new text to be appended to the old text instead of replacing it.


Widget User Values

Every widget has the potential to carry a user-specified value of any IDL data type and organization. That is, every widget contains a variable that can store arbitrary information. This value is ignored by the widget and is for the programmer's convenience only.

The initial user value is specified using the UVALUE keyword to the widget creation function. If no initial value is specified, the user value is undefined. Once the widget exists, its user value can be examined and/or changed using the GET_UVALUE and SET_UVALUE keywords to the WIDGET_CONTROL procedure. The widget user value should not be confused with the concept of widget values described above.

Simple Example Revisited

User values can be used to simplify event-handling. Without user values, you would have to compare the widget ID returned by WIDGET_EVENT with the IDs of every event-generating widget in the widget tree to determine what to do with it. The user value can be used to store information that makes this unnecessary.

Taking advantage of user values and using the XMANAGER procedure, we can rewrite the example of the previous section. Unlike our first attempt (on page 21-6), this version is able to co-exist with other widget applications simultaneously.

The first step is to write an event processing procedure:

PRO MENU_EVENT, event	 Event handler for menu.

WIDGET_CONTROL, GET_UVALUE = I, event.id
Obtain the button index within the menu.

PRINT, 'Pressed Button: ', I	Inform the user which button was pressed.

WIDGET_CONTROL, event.top, /DESTROY	Destroy the menu.

END

The following statements create the menu:

XMENU, SINDGEN(10), BASE = base	Create a menu with 10 buttons XMENU automatically fills the UVALUE of each button with it's index, so there is no need to explicitly supply the user values.

WIDGET_CONTROL, base, /REALIZE	Realize the widgets.

XMANAGER, 'MENU', base	Register the menu with XMANAGER and wait for events. XMANAGER determines that MENU_EVENT is the event handler by adding the EVENT suffix to the supplied name.


Compound Widgets

So far, only the base set of widgets provided by IDL has been described. These widget primitives can be used to construct many varied user interfaces, but complex programs written with them suffer the following drawbacks:

•	Large widget applications become difficult to maintain. As an application grows, it becomes more difficult to properly write and test. The resulting program suffers from poor organization.

•	Good ideas can be difficult to reuse. Most larger applications are constructed from smaller sub-units. For example, a color table editor might contain control panel, color selection and color-index selection sub-units. These sub-units are often complicated tools that could be used profitably in other programs. To reuse such sub-units, the programmer must understand the existing application and then transplant the interesting parts into the new program — at best a tedious and error-prone proposition.

Compound widgets solve these problems. A compound widget is a complete, self-contained, reusable widget sub-tree that behaves to a large degree just like a primitive widget. Complex widget applications written with compound widgets are much easier to maintain than the same application written without them. Using compound widgets is analogous to using subroutines and functions in programming languages.

Compound Widgets Included with IDL

A number of compound widgets are included in the IDL distribution. These can be found (along with many other routines that use the widgets) in the lib sudirectory of the IDL distribution. All compound widget filenames begin with "CW_" to make them easier to identify. Documentation for these routines can be found in the IDL Reference Guide:

CW_ANIMATE — Display an animated sequence of images.

CW_ARCBALL — Intuitively specify three-dimensional orientations.

CW_BGROUP — Create a cluster of buttons (a menu).

CW_CLR_INDEX — Display a color bar and allow the user to select a color index.

CW_COLORSEL — Display all the colors in the current colormap and allow the user to select color indices.

CW_DEFROI — Specify a region of interest within a draw widget.

CW_FIELD — A data-entry compound widget built with a label and text widget.

CW_FORM — Create simple forms with text, numeric fields, buttons, and droplists.

CW_FSLIDER — A version of the slider widget that handles floating-point values.

CW_ORIENT — Interactively adjust the three-dimensional drawing transformation.

CW_PDMENU — Create pulldown menus.

CW_RGBSLIDER — Allows adjusting color values using the RGB, CMY, HSV, and HLS color systems. Returns events containing the resulting RGB values.

CW_TMPL — Template for users wanting to write their own compound widgets.

CW_ZOOM — Display orgininal and zoomed images side-by-side.

Writing Compound Widgets

Compound widgets are written in the same way as any other widget application. They are distinguished from regular widget applications in the following ways:

•	Compound widgets usually have a base widget at the root of their hierarchies. This base contains the subwidgets that make up the cluster. From the user's point of view, this single widget is the compound widget — its children are hidden from the users view.

•	It is important that the compound widget not make use of the base's user value. This user value should be reserved for use by the caller of the compound widget in order to preserve the illusion that the compound widget works just like any of the basic widgets.

•	The root widget of the compound widget always has an event handler function associated with it via the EVENT_FUNC keyword to the widget creating function or the WIDGET_CONTROL procedure. This event handler manages events from its sub-widgets and generates events for the compound widget. By swallowing events from the widgets that comprise the compound widget and generating events that represent the compound widget, it presents the illusion that the compound widget is acting like a basic widget.

•	If the compound widget has a value that can be set, it should be assigned a value setting procedure via the PRO_SET_VALUE keyword to the widget creating function or the WIDGET_CONTROL procedure.

•	If the compound widget has a value that can be retrieved, it should be assigned a value retrieving function via the FUNC_GET_VALUE keyword to the widget creating function or the WIDGET_CONTROL procedure.

For an example of how a compound widget might be written, see the discussion on page 21-28.


Managing the State of a Widget Application

Usually, a widget application or compound widget has some information, or state, associated with it. This is a natural consequence of the fact that the application is usually divided into at least two separate routines, one that creates and realizes the application and another that handles events. These multiple routines need shared access to certain types of information such as the widget IDs of the component widgets and data being used by the application.

One obvious answer to this problem is to use a COMMON block to hold the state. However, this solution is undesirable because it prevents more than a single copy of the application from running at the same time. It is easy to imagine the chaos that would ensue if multiple instances of the same application were using the same common block without some sort of interlocking.

A better solution to this problem is to use the user value of one of the widgets to store state information for the application. Since this user value can be of any type, a structure can be used to store any number of state-related values. Using this technique, multiple instances of the same widget code can exist simultaneously.

In our previous discussions, the HANDLER field of widget event structures was described without giving any compelling reason for its existence. That is because event processing and compound widgets must be understood before the need for HANDLER becomes clear. Recall that when WIDGET_EVENT finds an event to return, it moves up the widget tree looking for an event-handling routine registered to the widgets in between its current position and the top-level base of the widget application. If such a routine is found, it is called with the event as its argument, and the HANDLER field of this event is set to the widget ID of the widget where the event routine was found. Since compound widgets have event handlers associated with their root widget, the HANDLER field gives the event handler the widget ID of the root widget. This allows the event handler for a compound widget instance to easily locate the location of its state information relative to this root.

IDL programmers are often tempted to store the state information directly in the user value of the root widget, but this is not a good idea. The user value of a compound widget is reserved for the user of the widget, just like any basic widget. Therefore, you should store the state information in the user value of one of the child widgets below the root. As a convention, the user value of the first child is often used, leading to event handlers structured as follows:

FUNCTION EVENT_FUNC, event

; Get state from the first child of the compound widget root:

child = WIDGET_INFO(event.handler, /CHILD)

WIDGET_CONTROL, child, GET_UVALUE=state, /NO_COPY

; Execute event-handling code here.

; Restore the state information before exiting routine:

WIDGET_CONTROL, child, SET_UVALUE=state, /NO_COPY

; Return result of function

RETURN, result

END

Notice the use of the NO_COPY keyword in the above example. This keyword behaves similarly to the TEMPORARY function, and prevents IDL from duplicating the memory used by the user value during the GET_UVALUE and SET_UVALUE operations. This is an important efficiency consideration if your code generates many events or the size of the state data is large.

Sometimes, an application will find that it needs to use the user value of all its child widgets for some other purpose, and there is no convenient place to keep the state information. One way to work around this problem is to interpose an extra base between the root base and the rest of the widgets:

ROOT = WIDGET_BASE(parent)

EXTRA = WIDGET_BASE(root)

In such an approach, the remaining widgets would all be children of EXTRA rather than ROOT.


Using Draw Widgets

Draw widgets are graphics windows that appear as part of a widget hierarchy instead of appearing as an independent window. Standard graphics windows are created using the WINDOW procedure, while draw widgets are created using the WIDGET_DRAW function. Once created, however, they are used in the same way. Draw widgets allow designers of IDL graphical user interfaces to take advantage of the full power of IDL graphics in their displays.

All IDL graphics windows have a window number by which they are referenced. In the case of draw widgets, this number is not assigned until the draw widget is actually realized. Therefore, it cannot be returned by WIDGET_DRAW when the widget is created. Instead, you should use the WIDGET_CONTROL procedure to retrieve the window number after the widget has been realized. Unlike normal graphics windows, creating a draw widget does not cause the current graphics window to change to the new widget. Therefore, the WSET procedure must be used explicitly. The following statements demonstrate the required steps:

base = WIDGET_BASE()	Create a base widget.

draw = WIDGET_DRAW(base, XSIZE = 256, YSIZE = 256)
Attach a 256 x 256 draw widget.

WIDGET_CONTROL, /REALIZE, base	Realize the widgets.

WIDGET_CONTROL, GET_VALUE = index, draw
Obtain the window index.

WSET, index	Set the new widget to be the current graphics window

If you attempt to get the value of a draw widget before the widget has been realized, the value -1 (which is not a valid index) is returned.

The WIDGET_DRAW function accepts the SCROLL keyword that causes scrollbars to be attached to the drawing widget. These scrollbars allow you to view a larger image than would otherwise be possible in the area occupied by the draw widget. Figure 21.2 shows the SLIDE_IMAGE procedure that uses both a regular and a scrolling draw widget.


Menus

Two different types of menus can be created with the IDL widgets—visible menus and pulldown menus. A "visible menu" is a group of buttons that is always visible. A "pulldown menu" is a single button that, when selected, reveals a group of buttons.

Visible Menus

Two basic approaches exist to create menus that are always visible. The first is to use a base widget with pushbutton children. The steps involved are as follows:

1.	Use the WIDGET_BASE function to create a base to hold the buttons. The COLUMN and ROW keywords can be used to determine the layout of the buttons. The EXCLUSIVE and NONEXCLUSIVE keywords can be used to specify that the buttons should be two state "toggle" buttons rather than the normal single state buttons.

2.	Use the WIDGET_BUTTON function to add buttons to the base created in the previous step.

A Compound Widget for Menus

Since menus are very common, the CW_BGROUP compound widget is included to provide an easier interface to menu creation. The following example uses CW_BGROUP to produce a menu of 10 buttons labeled 0­9:

base = WIDGET_BASE()	Create the top-level base.

menu = CW_BGROUP(base, /COLUMN, SINDGEN(10))
Create the menu.

WIDGET_CONTROL, base, /REALIZE	Realize the menu.

An interesting variation is to use toggle buttons instead of regular buttons. A toggle button is a button with two states: selected and unselected. A selected button indicates its status visually. This is especially useful for creating menus in which more than a single item can be selected at a given time and when an indication of each button's state would be useful. For example:

base = WIDGET_BASE()

menu = CW_BGROUP(base, /COLUMN, /NONEXCLUSIVE, SINDGEN(10))

WIDGET_CONTROL, /REALIZE, base

Yet another variation is to use toggle buttons and to specify the EXCLUSIVE keyword to CW_BGROUP. A base with exclusive behavior ensures that toggle buttons are selected one-at-a-time by automatically unsetting all buttons whenever a new button is pressed.

base = WIDGET_BASE()

menu = CW_BGROUP(base, /COLUMN, /EXCLUSIVE, SINDGEN(10))

WIDGET_CONTROL, /REALIZE, base

Figure 21.3 shows both non-exclusive and exclusive menus using the Motif toolkit.

List Widgets

The other basic approach to creating menus that remain visible is to use the list widget. The previous example would be written as follows:

base = WIDGET_BASE()	Create a base widget.

items = ['Item Zero', 'Item One', 'Item Two', $

         'Item Three', 'Item Four', 'Item Five']

list = WIDGET_LIST(base, VALUE = items, YSIZE = 5)
The list displays the elements of the array items, in a window that displays five elements at a time.

WIDGET_CONTROL, /REALIZE, base	Realize the menu.

The resulting list widget is shown in Figure 21.4.

One advantage of the list widget is that it uses scrollbars to handle many more selections than could be displayed on the screen at once. The WIDGET_LIST statement above can be rewritten to display a menu of 100 items with 10 elements visible as follows:

list = WIDGET_LIST(base, VALUE = SINDGEN(100), YSIZE = 10)

Pulldown Menus

A pulldown menu appears to be a normal button until the user pushes it. The menu then pops up to display selections. Buttons in such a pulldown menu can activate other pulldown menus to any desired depth. The method for creating a pulldown menu is as follows:

1.	The topmost element of any pulldown menu is a button, created with the MENU keyword to the WIDGET_BUTTON function.

2.	The top-level button has one or more child widget buttons attached. Each button can either be used as is, in which case pressing it causes an event to be generated, or it can be created with the MENU keyword and have child widget buttons attached to it. If it has; child widgets, pushing it causes a pulldown menu containing the child buttons to pop into view.

3.	Menu buttons can be the parent of other buttons to any desired depth.

A Compound Widget for Pulldown Menus

Since pulldown menus are frequently used, the CW_PDMENU compound widget exists to simplify this procedure. Similarly, the CW_BGROUP compound widget simplifies regular menu creation.

The following example uses CW_BGROUP to create a pulldown menu. The result is shown in Figure 21.5:

desc = REPLICATE({ flags:0, name:'' }, 6)
This array will contain the menu description from which CW_PDMENU generates the menu.

desc.flags = [ 1, 0, 1, 0, 2, 2 ]	Specifies the role of each button. The first and third buttons (value is 1) start a new sub-menu, the second and fourth buttons are plain buttons with no other role, and the last two buttons end the current sub-menu and return to the previous level.

desc.name = [ 'Operations', 'Predefined', 'Interpolate', $

  'Linear', 'Spline', 'Quit' ]	Supplies the names of each button.

base = WIDGET_BASE()	Create a base widget.

menu = CW_PDMENU(base, desc)	Create the pulldown menu.

WIDGET_CONTROL, /REALIZE, base	Make it visible.

The format of the menu description used by CW_PDMENU in the above example requires some explanation. CW_PDMENU views a menu as consisting of a series of buttons, each of which can optionally lead to a sub-menu. The description of each button consists of a structure supplying its name and a flag field that tells what kind of button it is (starts a new sub-menu, ends the current sub-menu, or a plain button within the current sub-menu). The description of the complete menu consists of an array of such structures corresponding to the flattened menu. Comparing the description used in the code above with the result shown in Figure 21.5 should help to clarify this issue.


The XREGISTERED Procedure
The XREGISTERED Function

The XMANAGER procedure does not restrict applications to only a single running copy. Indeed, it is desirable for most applications to allow multiple simultaneous instances to run. However, there are some applications that should only allow a single instance at a time, either because it makes logical sense or because a weakness in the implementation requires it. An obvious example of this is an application that uses a COMMON block to maintain its current state (see "Managing the State of a Widget Application" on page 21-14).

The XREGISTERED function can be used in such applications to ensure that only a single copy can run at a time. Place the following statement at the start of the routine:

IF XREGISTERED('routine_name') THEN RETURN

where routine_name is the name of the application.

The use of this routine is as follows:

XREGISTERED(Name)

The XREGISTERED function returns the number of copies of a widget application that are currently registered under a given name. Here, Name is a string containing the name of the widget that is looked for in the XMANAGER widget applications.

The only optional keyword for XREGISTERED is as follows:

NOSHOW

Normally, if XREGISTERED finds a current copy of the specified application, it forces that application to the front of the display. If NOSHOW is set, this action is suppressed.


Using Timer Events

In addition to the normal widget events discussed previously, IDL allows the user to make timer event requests by using the TIMER keyword to the WIDGET_CONTROL procedure. Such events are useful in many applications that are time dependent, such as animation. The syntax for making such a request is:

WIDGET_CONTROL, Widget_Id, TIMER=interval_in_seconds

Widget_Id can be the ID of any type of widget. When such a request is made, IDL generates a timer request after the requested time interval has passed. Timer events consist of a structure with only the standard three fields  — no additional information is provided.

It is up to the programmer to differentiate between a normal event and a timer event for a given widget. The usual way to solve this problem is to make timer requests for widgets that do not otherwise generate events, such as base or label widgets.

Each timer request causes a single event to be generated. To generate a steady stream of timer events, you must make a new timer request in the event handler routine each time a timer event is delivered.

Timer Event Example: XCLOCK

The following example presents a simple widget-based clock program that displays the current time in a text widget. Timer events are used at 5 second intervals to drive the updating of the text. Since the text widget used is not editable, it does not generate any standard events. This makes it a good candidate for being the target of timer events.

Here is the widget creation routine for XCLOCK:

PRO xclock

base = WIDGET_BASE(TITLE='System Time', /COLUMN)
Top-level base for xclock.

done = WIDGET_BUTTON(base, UVALUE=0, VALUE='DONE')
Used to dismiss the application. The UVALUE of 0 will be used by the event function to recognize the done button.

text = WIDGET_TEXT(base, XSIZE=30, YSIZE=1, UVALUE=1, $

  VALUE=SYSTIME(0))	Text widget used to display the current time. The UVALUE of 1 will indicate to the event function that a timer event has arrived.

WIDGET_CONTROL, base, /REALIZE	Make the application visible.

WIDGET_CONTROL, text, TIMER=5.0	Make the initial timer request for 5 seconds.

XMANAGER, 'XClock', base	Register the menu with XMANAGER and wait for events. XMANAGER determines that XCLOCK_EVENT is the event handler by adding the _EVENT suffix to the supplied name.

END

Here is the event-handling function for the above clock:

PRO xclock_event, event

WIDGET_CONTROL, event.id, GET_UVALUE=type
The UVALUE will be 0 for the done button, or 1 for a timer event.

IF(type EQ 0)THEN WIDGET_CONTROL, /DESTROY, event.top ELSE BEGIN
Done button was pressed. Kill the application.

WIDGET_CONTROL, event.id, TIMER=5.0	Request the next timer event.

WIDGET_CONTROL, event.id, SET_VALUE=SYSTIME(0)
Update the displayed time.

ENDELSE

END

This example is intentionally very simple because the intent was to demonstrate timer events with a minimum of other issues to complicate things. However, it is easy to imagine extending this example to make it more useful, by providing it with a graphical clock display and writing it as a reusable compound widget. The compound widget could even go so far as to have an alarm or a stopwatch feature that would generate events to notify the user at certain times.


Widget Sizing

This section explains how IDL widgets size themselves, widget geometry concepts, and how to explicitly size and position widgets.

Widget Geometry Terms and Concepts

Widget geometry, or the size and layout of widgets, is determined by many interrelated factors. In the following discussion, the following terms are used:

•	Geometry: The size and position of a widget.

•	Natural Size: The natural, or implicit, size of a widget is the size a widget has if no external constraints are placed on it. For example, a label widget has a natural size that is determined by the size of the text it is displaying and space for margins. These values are influenced by such things as the size of the font being displayed and characteristics of the low-level (i.e., operating-system level) widget or control used to implement the IDL widget.

•	Explicit Size: The explicit, or user-specified, size of a widget is the size set when an IDL programmer specifies one of the size keywords to an IDL widget creation function or WIDGET_CONTROL.

How Widget Geometry is Determined

IDL uses the following rules to determine the geometry of a widget:

•	The explicit size of a widget, if one is specified, takes precedence over the natural size. That is, the user-specified size is used if available.

•	If an explicit size is not specified, the natural size of the widget —at the time the widget is realized—is used. Once realized, the size of a widget does not automatically change when the value of the widget changes, unless the widget's dynamic resize property has been set. Dynamic resizing is discussed in more detail below. Note that any realized widget can be made to change its size by calling WIDGET_CONTROL with any of the sizing keywords.

•	Children of a "bulletin board" base (i.e., a base that was created without setting the COLUMN or ROW keywords) have an offset of (0,0) unless an offset is explicitly specified via the XOFFSET or YOFFSET keywords.

•	The offset keywords to children of ROW or COLUMN bases are ignored and IDL calculates the offsets lay the children out in a grid. This calculation can be influenced by setting any of the ALIGN or BASE_ALIGN keywords when the widgets are created.

Dynamic Resizing

Realized widgets, by default, do not automatically resize themselves when their values change. This is true whether the widget was created with an explicit size or the widget was allowed to size itself naturally. This behavior makes it easy to create widget layouts that don't change size too frequently or "flicker" due to small changes in a widget's natural size.

This default behavior can be changed for label, button, and droplist widgets. Set the DYNAMIC_RESIZE keyword to WIDGET_LABEL, WIDGET_BUTTON, or WIDGET_DROPLIST to make a widget that automatically resizes itself when its value changes. Note that the XSIZE and YSIZE keywords should not be used with DYNAMIC_RESIZE. Setting explicit sizing values overrides the dynamic resize property and creates a widget that will not resize itself.

Explicitly Specifying the Size and Location of Widgets

The XSIZE (and SCR_XSIZE), YSIZE (and SCR_YSIZE), XOFFSET, and YOFFSET keywords, when used with a standard base widget parent (a base created without the COLUMN or ROW keywords—also called a "bulletin board" base), allow the programmer to specify exactly how the child widgets should be positioned. Sometimes this is a very useful option. However, in general, it is best to avoid this style of programming. Although these keywords are usually honored by the toolkit, they are merely hints to the widget toolkit and might be ignored.

Explicitly specifying the size and offset makes a program inflexible and unable to run gracefully on various platforms. Often, a layout of this type will look good on one platform, but variations in screen size and how the toolkit works will cause widgets to overlap and not look good on another. The best way to handle this situation is to use nested row and column bases to hold the widgets and let the widgets arrange themselves. Such bases are created using the COLUMN and ROW keywords to the WIDGET_BASE procedure.

See the documentation for the various widget creation routines for more information about size and offset keywords.

Finding the Size of the Screen

When creating the top-level base for an application, sometimes it is useful to know the size of the screen. This information is available from the graphics driver via the GET_SCREEN_SIZE keyword to the DEVICE procedure. See "Keywords Accepted by the IDL Devices" on page 3-2 of the IDL Reference Guide for a list of drivers that support the GET_SCREEN_SIZE keyword. This keyword returns a two-element array, the first element of which is the screen width and the second the height. For example, the statements:

DEVICE, GET_SCREEN_SIZE = SCRSIZ

PRINT, 'Screen size: ', SCRSIZ(0), '(X) by ', SCRSIZ(1),'(Y)'

will generate output similar to the following:

Screen size: 1024(X) by 864(Y)

Preventing Layout Flicker

After a widget hierarchy has been realized, adding or destroying widgets in that hierarchy causes IDL to recalculate and set new geometries for every widget in the hierarchy. When a number of widgets are added or destroyed, these calculations occur between each change to the hierarchy, resulting in unpleasant screen "flashing" as the user sees a brief display of each intermediate widget configuration. This behavior can be eliminated by using the UPDATE keyword to WIDGET_CONTROL.

The top level base of every widget hierarchy has an UPDATE attribute that determines whether or not changes to the hierarchy are displayed on screen. Setting UPDATE to 0 turns off immediate updates and allows you to make a large number of changes to a widget hierarchy without updating the screen after each change. After all of your changes have been made, setting UPDATE to 1 causes the final widget configuration to be displayed on screen.

For example, consider the following program that realizes an unmapped base, then adds 200 button widgets to the previously-realized base:

b = WIDGET_BASE(/COLUMN, XSIZE=400, YSIZE=400, MAP=0)
WIDGET_CONTROL, b, /REALIZE
FOR i = 0, 200 DO button = WIDGET_BUTTON(b, VALUE=STRING(i))
WIDGET_CONTROL, b, /MAP
END

This program takes over 50 seconds to run on an HP 9000/720 workstation. If the base had been mapped, the user would see the base "flashing" as each button was added to the base. Altering the example to use the UPDATE keyword reduces the execution time to 0.7 seconds:

b = WIDGET_BASE(/COLUMN, XSIZE=400, YSIZE=400, MAP=0)
WIDGET_CONTROL, b, /REALIZE, UPDATE=0
FOR i = 0, 200 DO button = WIDGET_BUTTON(b, VALUE=STRING(i))
WIDGET_CONTROL, b, /MAP, /UPDATE
END


Miscellaneous Widget Information

Widget Application Errors

At times, widget applications may experience errors that stop the processing of widget events by XMANAGER. This is most common during the development of the application, when unexpected programming errors are likely to appear. This is evidenced by error messages as well as the return of the IDL prompt. If this occurs when other currently running widget applications are registered with XMANAGER, all widget activity comes to a halt. To return control to XMANAGER, first close the widget application via the window manager. Then, issue the following commands:

RETALL	Return to the main level.

XMANAGER	Calling XMANAGER with no parameters tells it to skip registering a new application and to simply resume event processing.

Are Widgets Available?

Widgets are implemented as an extension of the current graphics driver. If the current graphics driver supports widgets, the !D.FLAGS system variable will have the bit represented by the value 65,536 set. Therefore, the following statement can be used to test for widget availability:

IF (!D.FLAGS AND 65536) NE 0 THEN PRINT, 'Widgets are available.'

Identifying Widget Type from an Event

Given a widget event structure, often you need to know what type of widget generated it without having to match the widget ID in the event structure to all the current widgets. This information is available by specifying the STRUCTURE_NAME keyword to the TAG_NAMES function:

PRINT, 'Event structure type: ', $

       TAG_NAMES(EVENT, /STRUCTURE_NAME)

This works because each widget type generates a different event structure. The event structure generated by a given widget type is documented in the description of the widget creation function for that type.

When using this technique, be aware that although all the basic widgets use named structures for their events, many compound widgets return anonymous structures. This technique does not work well in that case because anonymous structures lack a recognizable name.

Killing Widget Hierarchies

The standard way to kill a widget hierarchy is with the statement

WIDGET_CONTROL, /DESTROY, base

where BASE is the topmost widget to be killed. Usually, IDL programs that use widgets issue this statement in their event-handling routine in response to the application "Done" button.

In addition, some window managers place a pulldown menu on the frame of the top-level base widget that allows the user to kill the entire hierarchy. Using the window manager to kill a widget hierarchy is equivalent to using the WIDGET_CONTROL procedure.

When designing widget applications, you should always include a "Done" button in the application itself, because some window managers to not provide the user with a kill option from the outer frame.

Interrupting the Event Loop

When IDL is waiting for events in the WIDGET_EVENT function, it is not available to accept commands from the IDL prompt. It is possible to interrupt the event function by pressing the Control-C interrupt character.

However, you may find that even after pressing Control-C, IDL still does not return to the interactive prompt. Simply moving the mouse cursor across the widgets will cause IDL to return to the prompt; otherwise, operating one of the widgets will do so.

This happens because when IDL is in the event function, it only checks for the interrupt between event notifications from the window system. Such events do not necessarily translate one-to-one into IDL widget events because the window system typically generates a large number of events related to the window system's operation that IDL quietly handles. Moving the mouse cursor across the widgets typically generates some of these events which gives IDL a chance to notice the interrupt and act on it.

Note: Do not interrupt the event loop by placing a STOP or EXIT command in the event-handler or in a callback routine. The presence of either command will cause the widget routine to exit with an error.

Indicating Time-Consuming Operations

In an event driven environment, it is important that the interface be highly responsive to the user's manipulations. This means that widget event handlers should be written to execute quickly and return. However, sometimes the event handler has no option but to perform an operation that is slow. In such a case, it is a good idea to give the user feedback that the system is busy. This is easily done using the HOURGLASS keyword to the WIDGET_CONTROL procedure just before the expensive operation is started:

WIDGET_CONTROL, /HOURGLASS

This command causes IDL to turn on an hourglass-shaped cursor for all IDL widgets and graphics windows. The hourglass remains active until the next event is processed, at which point the previous cursor is automatically restored.

Writing Applications that Work With All Widget Toolkits

Although IDL widgets are essentially the same on all supported hosts, there are some differences that can complicate writing applications that work well with both. The following hints should help you write such applications:

•	Avoid XSIZE, YSIZE, XOFFSET, and YOFFSET keywords. The different toolkits create widgets with slightly different sizes and layouts, so it is best to use bases that order their child widgets in rows or columns and stay away from explicit positioning. If you must use these keywords, try to isolate the affected widgets in a sub-base of the overall widget hierarchy to minimize the overall effect.

•	When using a bitmap to specify button labels, be aware that some toolkits prefer certain sizes and give sub-optimal results with others.

•	Try to place text, label, and list widgets in locations where their absolute size can vary without making the overall application look bad. The font used by the different toolkits have different physical sizes that can cause these widgets to have different proportions.

•	If all else fails, it is possible to use the value of the WIDGET_INFO function to execute special case code for each toolkit. It is, however, desirable to avoid large-scale special case programming because this makes maintenance of the finished program more difficult.

It is reasonably easy to write applications that will work in all environments without having to resort to much special case programming. It is very helpful to have a machine running each environment available so that the design can be tested on each iteratively until a suitable layout is obtained.


A Larger Example

The following principles should be followed when writing any serious widget application:

•	Use existing compound widgets when possible. In particular, use the CW_BGROUP and CW_PDMENU compound widgets to create menus. These functions are easier to use that writing the menu code directly, and your intent will be more quickly understood by others reading your code.

•	When writing new applications, decompose the problem into sub-problems and write reusable compound widgets to implement them. In this way, you will build a collection of reusable widget solutions to general problems instead of hard-to-modify, monolithic programs.

•	The many advantages of the XMANAGER procedure dictate that all widget programs should use it. There are few if any reasons to call the WIDGET_EVENT procedure directly.

•	Avoid specifying the absolute size and location of widgets whenever possible. Use row/column widget bases and let them do the work.

This example demonstrates how a slightly larger application might be written. This is a simple tool named XPCOLOR, that allows the user to change the foreground plotting color used by IDL for graphics operations. A picture of XPCOLOR is shown in Figure 21.6. The code for XPCOLOR can be found in the file xpcolor.pro in the general subdirectory of the examples subdirectory of the IDL distribution. The code is also shown below:

PRO xpcolor

COMMON COLORS, r_orig, g_orig, b_orig, r_curr, g_curr, b_curr	  This COMMON block is used by all IDL color routines by convention. It contains the current colortables as set by LOADCT and XLOADCT.

IF N_ELEMENTS(r_orig) LE 0 THEN BEGIN
The COLORS COMMON block hasn't been initialized yet, we should do it.

TVLCT, r_orig, g_orig, b_orig, /GET
Get the current color tables and fill in the COMMON.

r_curr=r_orig & b_curr=b_orig & g_curr=g_orig

ENDIF

base = WIDGET_BASE(/COLUMN, TITLE='Set Plot Color')
Top-level base for application.

b = CW_BGROUP(base, /ROW, ['Done', 'Help'], UVALUE=0)
Use the button group compound widget to create Done and Help buttons. The UVALUE of 0 will be used by the event handler to recognize the button group. The VALUE field of the event will then allow telling them apart.

draw = WIDGET_DRAW(base, XSIZE=100, YSIZE=50)
A bar shaped region at the top to show the current plotting color.

rgb = CW_RGBSLIDER(base, /DRAG, UVALUE=1)
The RGB slider compound widget is used to change the plotting color. The DRAG keyword allows intermediate RGB values to be reported when the sliders are dragged. It should be noted that RGBSLIDER uses the CW_FSLIDER compound widget, demonstrating that compound widgets can be nested to arbitrary depth. The UVALUE of 1 allows the event handler to know the event is for the RGBSLIDER.

WIDGET_CONTROL, rgb, SET_VALUE=[r_curr(!P.COLOR), $

  g_curr(!P.COLOR), b_curr(!P.COLOR)]
Set the RGB slider to the initial plotting color.

WIDGET_CONTROL,/REALIZE, base	Make the application visible.

WIDGET_CONTROL, draw, GET_VALUE=win_id
Now that the draw widget is realized, obtain it's graphics window index.

save=!D.WINDOW	Remember the current graphics window so we can restore it.

WSET, win_id	Shift graphics to our draw widget.

ERASE, COLOR=!P.COLOR	Use ERASE to set the entire draw widget to the foreground plotting color.

IF (save NE -1) THEN WSET, save	Restore the previous graphics window. A value of -1 indicates that there was no current graphics window before our draw widget was created. In that case, don't bother.

XMANAGER, 'XPCOLOR', base	Register with XMANANGER and allow it to call our event handler when events arrive.

END

The routine above creates the application widgets and performs any required initialization. The next step is to define the event-handling procedure:

PRO xpcolor_event, event

COMMON colors, r_orig, g_orig, b_orig, r_curr, g_curr, b_curr

WIDGET_CONTROL, GET_UVALUE=type, event.id
The UVALUE allows us to tell the events apart. A value of zero is the button group and 1 is the RGBSLIDER.

IF (type EQ 0) THEN BEGIN	Button Group. Either Done or Help has been pressed.

IF (event.value EQ 0) THEN WIDGET_CONTROL, /DESTROY, event.top $
Done was pressed. Kill the application.

ELSE XDISPLAYFILE, TITLE='XPcolor Help', $

  GROUP=event.top, HEIGHT=5, WIDTH=60, $

  TEXT=['This is the XPCOLOR demo program.', ...]
XDISPLAYFILE is a procedure that displays text. It is commonly used for help text. The GROUP keyword specifies that if the user kills the main application while the help is still alive, the help should also be killed. Note that the full help text is not shown here.

ENDIF ELSE BEGIN	A new RGB value has arrived.

r_curr(!P.COLOR) = event.r	Update the Red.

g_curr(!P.COLOR) = event.g	Update the Green.

b_curr(!P.COLOR) = event.b	Update the Blue.

TVLCT, event.r, event.g, event.b, !P.COLOR
Load the new plotting color.

ENDELSE

END


Writing a Compound Widget (CW_DICE)

The following example incorporates ideas from the previous sections to show how you might approach the task of writing a compound widget. The widget is called CW_DICE, and it simulates a single six-sided die. Figure 21.7 shows the appearance of XDICE, an application that uses two instances of CW_DICE. XDICE is discussed on page 21-33. cw_dice.pro can be found in the lib subdirectory of the IDL distribution. xdice.pro can be found in the general subdirectory of the examples subdirectory of the IDL distribution. You should examine these files for additional details and comments not included here.

The CW_DICE compound widget has the following features:

•	It uses a button widget. The current value of the die is displayed as a bitmap label on the button itself. When the user presses the button, the die "rolls" itself by displaying a sequence of bitmaps and then settles on a final value. An event is generated that returns this final value.

•	Timer events are used to create the rolling effect. This allows the dice to give the same appearance on machines of varying performance levels.

•	The die can be set to a specific value via the SET_VALUE keyword to the WIDGET_CONTROL procedure. If the desired value is outside of the range 1 through 6, the die is rolled as if the user had pressed the button and a final value is selected randomly. Using WIDGET_CONTROL does not cause an event to be issued. This follows the IDL convention that user actions cause events while programmatic changes do not.

•	The current value of the die can be obtained via the GET_VALUE keyword to the WIDGET_CONTROL procedure.

Almost any compound widget will have some state associated with it. The following is the state of CW_DICE:

1.	The current value.

2.	The number of times the die should "tumble" before settling on a final value.

3.	The amount of time to take between tumbles.

4.	When a roll is in progress, a count of how many tumbles are left before a final value is displayed.

5.	The bitmaps to use for the 6 possible die values.

6.	The seed to use for the random number generator.

The first four items are stored in a per-widget structure kept in one of the child widget's user values. Since the bitmaps never change, it makes sense to keep them in a COMMON block to be accessed freely by all the CW_DICE routines. It also makes sense to use a single random number seed for the entire CW_DICE class rather than one per instance to avoid the situation where multiple dice, having been created at the same time, have the same seed and thus display the same value on each roll.

It is rare that the use of a COMMON block in a compound widget makes sense. Notice, however, that we're only keeping read-only data (bitmaps) or data that can be overwritten at any time with no negative effects (random number generator seed).

Given the above decisions, it is now possible to write the CW_DICE procedure:

PRO cw_dice, parent, value, UVALUE=uvalue, $

  TUMBLE_CNT=tumble_cnt, TUMBLE_PERIOD=tumble_period
Value is an optional argument that lets the caller set the initial die value to a value between 1 and 6. UVALUE will simply be passed on to the root base of CW_DICE. The TUMBLE keywords let the user adjust the tumble count and period.

COMMON CW_DICE_BLK, seed, faces	This COMMON block holds the bitmaps and random number generator seed.

IF NOT KEYWORD_SET(tumble_cnt) THEN tumble_cnt=10
Provide defaults for the keywords.

IF (tumble_cnt lt 1) then tumble_cnt=10
Guard against a nonsensical request.

IF NOT KEYWORD_SET(tumble_period) THEN tumble_period=.05
Default tumble period in seconds.

IF (tumble_period lt 0) then tumble_period=.05

IF NOT KEYWORD_SET(uvalue) uvalue=0

ON_ERROR, 2	Return to caller if an error occurs.

faces=LONARR(192)	Generate the die face bitmaps. The actual code for this is omitted here because it doesn't add much to the example, but it can be found in the CW_DICE.PRO file.

IF(N_ELEMENTS(value) EQ 0) THEN value = FIX(6*RANDOMU(seed) + 1)
Use RANDOMU to pick the initial value of the die unless the user provided one.

state = { value:value, tumble_cnt:FIX(tumble_cnt), $

          tumble_period:tumble_period, remaining:0 }
Construct a state variable for this instance.

base = WIDGET_BASE(parent, UVALUE=uvalue, $

       EVENT_FUNC='CW_DICE_EVENT', $

       FUNC_GET_VALUE='CW_DICE_GET_VALUE', $

       PRO_SET_VALUE='CW_DICE_SET_VALUE')
Create the base widget, passing the UVALUE through for the caller. Notice that we also register an event function and GET/SET value routines which will be called by WIDGET_CONTROL on our behalf.

die = WIDGET_BUTTON(base, VALUE=faces(*, *, value-1))
Create the die, setting its bitmap to the current value.

WIDGET_CONTROL, WIDGET_INFO(base, /CHILD), $

  SET_UVALUE=state, /NO_COPY	Save the state in the first child's user value. Notice the use of the NO_COPY keyword for efficiency.

RETURN, base	The result of a compound widget is always the ID of its topmost widget.

END

The above code makes reference to two routines named CW_DICE_SET_VAL and CW_DICE_GET_VAL. By using the FUNC_GET_VALUE and PRO_SET_VALUE keywords to WIDGET_BASE, WIDGET_CONTROL can call these routines whenever the user makes a WIDGET_CONTROL SET_VALUE or GET_VALUE request:

PRO cw_dice_set_val, id, value	This is the SET_VALUE routine for CW_DICE. The number and type of the arguments is defined by WIDGET_CONTROL. Id is the widget ID of a CW_DICE, and value is the users requested value.

COMMON CW_DICE_BLK, seed, faces

stash = WIDGET_INFO(id, /CHILD)	Get the ID of the first child of the CW_DICE widget. This is where the state information is stored.

WIDGET_CONTROL, stash, GET_UVALUE=state, /NOCOPY
Get the state structure.

if (value < 1) or (value > 6) THEN BEGIN
If the value is outside the range [1,6] then roll the die as if the user pressed the button.

CW_DICE_ROLL, stash, state	CW_DICE_ROLL rolls the dice. It's a separate function because our event handler also needs to use it.

ENDIF ELSE BEGIN	If the value is in the range [1,6] then simply set the die to that value without rolling.

state.value=value

WIDGET_CONTROL, stash, SET_VALUE=faces(*,*, value-1)
Set the new bitmap on the button. We take advantage of the fact that stash must be the widget ID of the button widget, since the base only has one child.

ENDELSE

WIDGET_CONTROL, stash, SET_UVALUE=state, /NO_COPY
Restore the state in the child UVALUE.

END

FUNCTION cw_dice_get_val, id	This is the GET_VALUE routine for CW_DICE. The number and type of the arguments is defined by WIDGET_CONTROL. Id is the widget ID of a CW_DICE. The return value of this function must be the current value of the compound widget, as defined by that widget.

stash = WIDGET_INFO(id, /CHILD)	Get the ID of the first child of the CW_DICE widget. This is where the state information is stored.

WIDGET_CONTROL, stash, GET_UVALUE=state, /NO_COPY
Get the state structure.

ret = state.value	Get the current value from the state structure.

WIDGET_CONTROL, stash, SET_UVALUE=state, /NO_COPY
Restore the state in the child UVALUE.

RETURN, ret

END

CW_DICE_SET_VALUE makes reference to a procedure named CW_DICE_ROLL that does the actual dice rolling. Rolling is implemented as follows:

1.	If this is the initial call to CW_DICE_ROLL, then pick the final value that will end up being displayed and enter this into the widget's state. Hence, WIDGET_CONTROL, /GET_VALUE reports the final value instead of one of the intermediate "tumble" values no matter when it is called.

2.	If this is not the final tumble, pick a random intermediate value and display that. Then, make another timer event request for the next tumble.

3.	If this is the final tumble, use the saved final value.

4.	CW_DICE_ROLL works in cooperation with the event handler function for CW_DICE. Each timer event causes the event handler to be called and the event handler in turn calls CW_DICE_ROLL to process the next tumble.

PRO cw_dice_roll, dice, state	Roll the specified die. Dice is the widget ID of the button holding the bitmap, and state is the state as extracted from the CW_DICE UVALUE by the caller.

COMMON CW_DICE_BLK, seed, faces

IF (state.remaining EQ 0) THEN BEGIN	First time.

state.remaining = state.tumble_cnt	Set the counter for the number of tumbles remaining.

state.value = FIX(6*RANDOMU(seed)+1)	Determine final value now.

ENDIF

IF (state.remaining EQ 1) THEN BEGIN	Last time.

value = state.value	Use the previously-saved final result.

ENDIF ELSE BEGIN	Not the last time.

value = FIX(6 * RANDOMU(seed) + 1)	Generate an intermediate value.

WIDGET_CONTROL, dice, TIMER=state.tumble_period
Since this isn't the last tumble, make the next timer request.

ENDELSE

WIDGET_CONTROL, dice, SET_VALUE=faces(*,*, value-1)
Display the correct bitmap.

state.remaining = state.remaining-1	Decrement tumble counter.

END

This leads us to the event handler function:

FUNCTION cw_dice_event, event

base = event.handler	The primary use for the HANDLER field of event structures is to make finding the root of a compound widget easy.

stash = WIDGET_INFO(base, /CHILD)	Get the ID of the first child of the CW_DICE widget. This is where the state information is stored.

WIDGET_CONTROL, stash, GET_UVALUE=state, /NO_COPY
Get the state structure.

CW_DICE_ROLL, stash, state	Roll the die and display a new bitmap.

if (TAG_NAMES(event, /STRUCTURE_NAME) NE 'WIDGET_TIMER') THEN $
This event handler expects to see button press events generated from a user action as well as TIMER events from CW_DICE_ROLL. We only want to issue events for the button presses. Even though the die still has several tumbles left, we know that the final value is in the state now.

ret = { CW_DICE_EVENT, ID:base, TOP:event.top, $

  HANDLER:0L, VALUE:state.value} $	Create an event.

ELSE ret = 0	By not returning an event structure, we cause the event to be swallowed by WIDGET_EVENT.

WIDGET_CONTROL, stash, SET_UVALUE=state, /NO_COPY
Restore the state in the child UVALUE.

RETURN, ret

END

Using CW_DICE in a Widget Program

Having written a compound widget, it is natural to want to use it in a real application. We can use CW_DICE to implement an application named XDICE. XDICE displays two dice as well as a "Roll" button. Pressing either die causes it to roll individually. Pressing the "Roll" button causes both dice to roll together. A text widget at the bottom always displays the current value in textual form. XDICE is shown in Figure 21.7.

PRO xdice, GROUP=group	Providing standard keywords usually found in other widget applications is a nice finishing touch. GROUP is easy to support since we just pass it to XMANAGER.

base = WIDGET_BASE(/COLUMN, title='Pair O'' Dice')
Create the top level base that holds everything else.

bgroup = CW_BGROUP(base, ['Done', 'Roll'], /ROW, SPACE=50)
A button group compound widget is used to implement the Done and Roll buttons. The SPACE keyword simply causes the buttons to be spread out from each other.

dice = WIDGET_BASE(base, /ROW, XPAD=20)
Create a row base to hold the dice. XPAD moves the first die away from the left side of the application and helps center the dice.

d1 = CW_DICE(dice)	The first die.

d2 = CW_DICE(dice)	The second die.

WIDGET_CONTROL, d1, GET_VALUE=d1v	We need the initial dice values to set the label appropriately. We could have specified initial values for the calls to CW_DICE above, but it seems better to let them be different on each invocation.

WIDGET_CONTROL, d2, GET_VALUE=d2v

str=STRING(format='("Current Value: ",I1,", ",I1)', d1v, d2v)	  Format the initial label text.

label = WIDGET_LABEL(base, value=str)
This label is used to textually display the current dice values.

state = { bgroup:bgroup, d1:d1, d2:d2, label:label }
Information that is needed in the event handler.

WIDGET_CONTROL, base, SET_UVALUE=state, /NO_COPY, /REALIZE
Save useful information in the base UVALUE, and realize the application.

XMANAGER, 'XDICE', base, GROUP=group
Pass control to XMANAGER.

END

The following event handler is called by XMANAGER to process events for the XDICE application:

PRO xdice_event, event

WIDGET_CONTROL, event.top, GET_UVALUE=state, /NO_COPY
Recover the state.

IF (event.id EQ state.bgroup) THEN BEGIN
Either the Done or Roll button was pressed.

IF (event.value EQ 0) THEN BEGIN	The Done button.

WIDGET_CONTROL, /DESTROY, event.top	Destroy the application.

RETURN	Return now to avoid trying to update the widget label we just destroyed.

ENDIF ELSE BEGIN	The Roll button.

WIDGET_CONTROL, state.d1, SET_VALUE=-1
Roll the first die by asking for an out of range value.

WIDGET_CONTROL, state.d2, SET_VALUE=-1
Roll the second die.

ENDELSE

ENDIF

WIDGET_CONTROL, state.d1, GET_VALUE=d1v
Get value of first die.

WIDGET_CONTROL, state.d2, GET_VALUE=d2v
Get value of second die.

str = STRING(format='("Current Value: ",I1,", ",I1)', d1v, d2v)
Format the initial label text.

WIDGET_CONTROL, state.label, SET_VALUE=str
Update the label.

WIDGET_CONTROL, event.top, SET_UVALUE=state, /NO_COPY
Restore the state.

END

Jump forward to Widget Builder

Jump backward to Mathematics


Widget Builder
22	Widget Builder

Chapter Overview

The Widget Builder is an IDL widget application that allows you to rapidly prototype graphical user interfaces. Interfaces in progress can be saved and edited later. Once an interface is complete, the Widget Builder can generate the IDL code that creates that interface along with a basic widget event handler.

While even non-programmers can use the Widget Builder to explore user interface design, a knowledge of IDL widget programming is required to turn Widget Builder output into usable widget applications. For more information on learning to program with IDL widgets, see "Widgets" on page 21-1.


Topics in Widget Builder Chapter
Widget Builder

This chapter describes IDL's menu driven GUI designer.

Topics Covered:

Starting the Widget Builder

Widget Builder Menu Hierarchy

Widget Builder Tutorial

Jump forward to Scientific Data Formats

Jump backward to Widgets


Starting the Widget Builder

To start the Widget Builder, enter the following command at the IDL prompt:

WIDED

The Widget Builder is a complicated application and can take some time to compile. Once the code has been compiled, two windows appear: the Widget Builder main window (titled "Widget Builder") and a small window titled "idl". The small window is a new widget interface that consists of only a base. This preview window actually shows an example of the interface that you are currently building. Other widgets can be added to the base using the tools provided in the main Widget Builder window (Figure 22.1).

Getting Started with the Widget Builder

If you are running the Widget Builder for the first time, you should go through the tutorial that begins on page 22-21. This tutorial shows how to build and edit a simple widget interface.


Widget Builder Menu Hierarchy

The Widget Builder main window has a group of pulldown menus along its top. These menus are described below.

The following hypertext links can be used to jump to the menu items described in this section:

The File Menu

The Edit Menu

The Add Menu

The Rebuild Button

The Help Button

The File Menu

The File menu controls input to and output from the Widget Builder. This menu allows you to save and restore widget interfaces as well as generate IDL program files.

New

Select this option to start a new widget interface. If an unsaved widget interface is currently open, you are asked if you want to save it before starting a new one.

Open

Select this option to open previously-saved widget interfaces. The default extension for these files is .wid.

Save

Select this option to save the current widget interface in the Widget Builder's .wid format. These files can be restored at a later time with the "Open" option.

Create .PRO

Select this option to reveal a cascading menu of options for turning the current widget interface into IDL code. The Widget Builder writes a single file with three sections: a documentation header template, a basic event handler routine, and a widget creation routine.

Note that this option is usually used only when your prototype widget interface is complete. Then the programmer makes modifications to the resulting  .pro file to create a usable widget application, making no further use of the Widget Builder. However, by using the "Normal" option, you can allow the Widget Builder to make changes to the widget creation section of a previously-saved .pro file (while retaining your edits to the widget event handler or documentation sections of the file).

Caution: Creating a .pro file is not the same as saving a .wid file (by selecting "Save" from the File menu). A .wid file can be read back into the Widget Builder, but a .pro file cannot. Creating a .pro file from a preview does not save your work. If you quit without saving the preview as a .wid, you will not be able to read your work back into the Widget Builder.

Select "Normal" to write any changes to the widget creation routine of an existing .pro file without changing the event handler and header.

Select "Rewrite Everything" to write a new .pro file or rewrite all parts of an existing .pro file. Any changes made previously are lost.

Select "Without Header" to write a .pro file without a documentation header. Otherwise, this option behaves exactly as the "Normal" option.

Show Object Tree

Select this option to display a window that shows the a textual representation of the current widget interface. The widget tree begins with the top-level base (called MAIN). Any widgets that belong to MAIN are shown indented. Each new sub-base is shown as a new indent level. Any titles or names that you have assigned to the widgets are shown in parentheses.

Quit

Select this option to exit the Widget Builder and return control to the IDL command line. If the current widget interface has unsaved changes, you are prompted before exiting.

The Edit Menu

The options in this pulldown menu allow you to edit parts of the current widget interface.

Cut

Select this option to remove a previously-created widget from the current interface. The "Cut Widget" dialog (Figure 22.3) appears. Click on the name of the widget to be cut, then click the "Cut Child" button to remove that widget from the current widget interface. Once cut, the widget is placed on the Widget Builder's "clipboard". The clipboard can contain up to 10 widget subtrees at one time.

If the widget you want to cut resides in a sub-base of the main base, click on the name of the sub-base, then click "Show Children". The Cut Widget dialog changes to show the children of that sub-base. To return to a display of widgets in the previous base, click "Show Parent Base".

Once you have cut a widget, the "Paste Widget" dialog can be displayed by clicking "Show Paste Dialog".

Click "Done" to dismiss the Cut Widget dialog.

Note that you must click "Rebuild" on the Widget Builder main window to see your changes to the current widget preview.

Copy

Select this option to copy a previously-created widget to the Widget Builder clipboard. The "Copy Widget" dialog appears. This dialog has the same functions as the "Cut Widget" dialog described above, except that copied widgets are not removed from the current widget interface.

Paste

Select this option to paste widgets from the Widget Builder clipboard to new positions in the current widget interface. The "Paste Widgets" dialog (Figure 22.4) appears.

This dialog features two lists. The list on the left (titled "Clipboard") shows the widgets that have been cut or copied to the clipboard. The list on the right (titled "Children of...") represents the current widget tree. To paste a widget from the clipboard to a new position in the widget tree, click on the name of the widget to be pasted in the "Clipboard" list. Then click on a widget in the "Children of..." list. Click the "Paste After" button to paste the selected "Clipboard" widget into the widget tree in the position after the selected "Children of..." widget.

If the widget you want to paste after resides in a sub-base of the main base, click on the name of the sub-base in the "Children of..." list, then click "Show Children". The "Children of..." list changes to show the children of that sub-base. To return to a display of widgets in the previous base, click "Show Parent Base".

Click "Delete Widget" to delete the currently selected "Clipboard" widget from the clipboard. Click "Done" to dismiss the Paste Widgets dialog.

Note that you must click "Rebuild" on the Widget Builder main window to see your changes to the current widget preview.

Edit Child

Select this option to edit the attributes of a previously-created widget. The "Edit Widget" dialog appears.

 To edit a widget, click on its name in the list, then click on "Edit Child". The appropriate widget editing menu will appear. These menus are the same as the menus used to create widgets. See "The Add Menu" on page 22-6.

If the widget you want to edit resides in a sub-base of the main base, click on the name of the sub-base, then click "Show Children". The Edit Widget dialog changes to show the children of that sub-base. To return to a display of widgets in the previous base, click "Show Parent Base".

Click "Done" to dismiss the Edit Widget dialog.

The Add Menu

The options on this menu are used to add widgets to the current widget interface. Note that many of the options selectable from the Add menu can also be selected through the Widget Builder

"button bar"—a row of graphic-labeled buttons below the main menu. The button bar and its corresponding menu items are shown in Figure 22.6. Individual menu items are described below.

Newly-created widgets are added to the end of the current widget tree. Therefore, new widgets fill row bases in left-to-right order and column bases in top-to-bottom order. Note that after they are created, widgets can be cut, copied, and pasted to arbitrary positions in the widget tree using the options in the Edit menu.

Common Features of the Add Widget Dialogs

The Add widget dialogs are graphical interfaces to IDL's widget-creation routines (e.g., WIDGET_BASE, WIDGET_BUTTON, etc.). Since these creation routines have many common keywords, the Add widget dialogs have many common controls. These features are described below.

•	Done and Cancel: All of the Add widget dialogs have "Done" and "Cancel" buttons. Click "Done" to dismiss the dialog and add the widget to the widget tree. Note that you must click "Rebuild" to see the changes reflected in the widget preview. Click "Cancel" to dismiss the dialog without adding the widget to the widget tree.

•	Font: Any widgets that have text elements can also be assigned fonts other than the default. Note, however, that different systems (and different types of platforms) may not have access to the same fonts. If you are building interfaces that will be used on many different platforms, it is best not to specify special fonts (if a specified font is not available, the system uses the default font). To specify a special font, enter a string in the format accepted by the FONT keyword to the DEVICE routine. See "FONT" on page 3-11 of the IDL Reference Guide.

On Windows and Macintosh systems, this string has the following format:

font*modifier1*modifier2*...modifiern

where font is the full name of any display font installed in your system. For example, to set the text for a widget to 24 point Times italic, you would enter the following string in the "Font:" field:

times*24*italic

On X Windows systems, this string can be the name of any font that is displayed when the Unix xlsfonts command is invoked. X Windows Widget Builder users can also click on the "XFont" button next to the "Font:" field to invoke IDL's XFONT routine that shows the available fonts.

•	Name: All widgets created with the Add widget dialogs can be assigned a name. This name is not the title string for the widget. Instead, this is a descriptor that shows up in Widget Editor dialogs (such as the Cut, Edit, Paste, and Show Object Tree dialogs) next to the widget description (e.g., BUTTON4). In the .pro files generated by the Widget Builder, the contents of the name field become the text that is printed when an event is received for this widget. If you use the Name field, take care not to give different widgets identical names.

•	Frame Size: This field accepts an integer value that specifies the width of a frame (or border) to be put around the widget. Note that this is simply a hint to the window manager. Many systems will not display frames of different thicknesses—all you can specify is whether or not the widget has a frame. If this field is empty, the widget has no frame around it.

•	User Value: All IDL widgets can contain a user-specified value of any data type and organization. This value is not used by the widget in any way, but exists entirely for the convenience of the IDL programmer. You can enter any value in this field. When a .pro file is generated, this value becomes the initial user value for the widget (specified with the UVALUE keyword to the appropriate widget creation function). Note that this field has no function inside the Widget Builder application. If you use the User Value field, take care not to give different widgets identical User Values, or the event handler routine (in the generated .pro file) will not be able to identify the widget that caused the event.

•	X Size and Y Size: The width (X Size) and height (Y Size) of the widget (in pixels for most widgets, in characters for text widgets). Note that it is best to let most widgets size themselves.

•	X Offset and Y Offset: The horizontal (X Offset) and vertical (Y Offset) offset of the widget (in pixels) relative to its parent. Note that it is best to let most widgets position themselves.

Hide/Show Tool Bar

Select this options to toggle display of the button bar (Figure 22.6) on and off.

Base

Select this option to create a new base. The Base dialog appears. This dialog has the same controls as the Widget Builder main window, except that it only has an "Add" menu.

 This menu is used to add new widgets to the new sub-base.

For descriptions of the other controls on this dialog, see "Common Features of the Add Widget Dialogs" on page 22-7. Note that the Add Base Dialog does not have a "Cancel" button. To remove an accidentally-added base, use the "Cut" option from the Edit menu. The Base dialog is an interface to IDL's WIDGET_BASE function. See "WIDGET_BASE" on page 1-971 of the IDL Reference Guide.

Button

Select this option to create a new button with a text label. The Button dialog appears.

Features unique to this dialog are described below.

•	Button Text: This field accepts a string to be used as the button label.

For descriptions of the other controls on this dialog, see "Common Features of the Add Widget Dialogs" on page 22-7. The Button dialog is an interface to IDL's WIDGET_BUTTON function. See "WIDGET_BUTTON" on page 1-981 of the IDL Reference Guide.

Bitmap Button

Select this option to create a new button with a bitmap label. The Bitmap Button dialog appears

 This dialog is used to create black and white bitmap labels for the button. Controls unique to this dialog are described below.

•	Gridded Draw Widget: Click inside this draw widget to draw the bitmap label. Each square represents a pixel in the final bitmap. Clicking on a white square turns it black. Clicking on a black square turns it white. Hold the mouse button down to draw continuous lines. On X Windows systems, an actual-size bitmap button appears next to the draw widget.

•	Bitmap Size: Click on one of these buttons to select the size of the bitmap button. There are three choices: 16, 32, and 64 pixels square.

•	Invert: Click this button to turn all white pixels black and vice-versa.

For descriptions of the other controls on this dialog, see "Common Features of the Add Widget Dialogs" on page 22-7. The Bitmap Button dialog is an interface to IDL's WIDGET_BUTTON function. See "WIDGET_BUTTON" on page 1-981 of the IDL Reference Guide.

Button Group

Select this option to create a "button group" compound widget. Button groups can be used to create a number of buttons that share the same sub-base. They can also be used to create menus of exclusive and non-exclusive "radio" buttons. The BGROUP dialog appears. Controls unique to this dialog are described below.

•	BGROUP Widget Value: This multi-line text widget at the top of the dialog is used to enter the labels for the buttons. Each line is a separate label. Take care not to enter a "Return" after the last button label, or you will end up with an extra button with a blank label.

•	Base Type, Child Spacing, Padding: Select the type of base to be used to hold the buttons. Buttons can be organized in a row, column, or bulletin-board base. You can also select spacing between children and X and Y padding.

•	Base Type: This menu allows you to select the type of buttons in the button group. To create the default style buttons (like the "Done" and "Cancel" buttons on this dialog), select "Normal Base". To create an exclusive menu (i.e., a menu of radio buttons wherein only one button can be selected at a time), select "Exclusive". To create a non-exclusive menu (i.e., a menu of radio buttons wherein any number of buttons can be selected), select "Non-Exclusive".

•	Top Title, Left Title: Button groups can have label titles at the very top and/or on the left side of the group.

•	X Scroll Size, Y Scroll Size: Entering values in these fields makes the base that holds the buttons a scrolling base. The values represent the size of the scrollable region, in pixels.

For descriptions of the other controls on this dialog, see "Common Features of the Add Widget Dialogs" on page 22-7. The Button Group dialog is an interface to IDL's CW_BGROUP function. See "CW_BGROUP" on page 1-173 of the IDL Reference Guide.

Draw

Select this option to create a draw widget. The Draw dialog appears. Controls unique to this dialog are described below.

•	X Size, Y Size: The size of the draw widget in pixels.

•	Accept Button Events: Select this button to create a draw widget that returns button presses inside the drawing region.

•	Accept Motion Events: Select this button to create a draw widget that returns motion events inside the drawing region.

•	Backing Store: This menu provides an interface to the RETAIN keyword. Click "None" to create a draw widget without backing store. Click "Server" to request backing store from the window manager. Click "IDL" to have IDL manage backing store for the widget.

•	X Scroll Size, Y Scroll Size: Entering values in these fields creates a scrolling draw widget. The values represent the size of the scrollable region, in pixels.

For descriptions of the other controls on this dialog, see "Common Features of the Add Widget Dialogs" on page 22-7. The Draw dialog is an interface to IDL's WIDGET_DRAW function. See "WIDGET_DRAW" on page 1-999 of the IDL Reference Guide.

Field w/Label

Select this option to create an "input field" compound widget. The FIELD dialog appears. Input fields combine a text widget with a label. Controls unique to this dialog are described below:

•	FIELD Widget Value: The initial contents of the text widget.

•	Title: The text string for the label part of the input field.

•	Field Type: Input fields are "smart" in that they automatically convert input to the text widget to the appropriate type. Select from "String", "Float", "Int", and "Long" types.

•	Field Events: Use this menu to select the type of events the input field will return. By default, fields only return their value on a call to WIDGET_CONTROL, /GET_VALUE. However, you can modify this behavior by clicking "Event on <CR>" (return an event whenever Return is pressed in the text field) or "All Events" (similar to "All Events" for text widgets).

•	Field text Fixed: Click this button to make the text widget non-editable.

•	Field is Vertical: Click this button to put the label above the text widget. By default, the label is to the left of the text widget.

For descriptions of the other controls on this dialog, see "Common Features of the Add Widget Dialogs" on page 22-7. The FIELD dialog is an interface to the CW_FIELD function. See "CW_FIELD" on page 1-185 of the IDL Reference Guide.

Label

Select this option to create a new label widget. The LABEL Dialog appears. Controls unique to this dialog are described below.

•	Label Text: Enter the text string to be used as a label in this field.

For descriptions of the other controls on this dialog, see "Common Features of the Add Widget Dialogs" on page 22-7. The LABEL dialog is an interface to the WIDGET_LABEL function. See "WIDGET_LABEL" on page 1-1017 of the IDL Reference Guide.

List

Select this option to add a new list widget. The LIST Dialog appears. Controls unique to this dialog are described below.

•	List Widget Value: This multi-line text widget at the top of the dialog is used to enter the list items. Each line is a separate element in the list. Take care not to enter a "Return" after the last list item, or you will end up with an extra list element that is blank.

•	Y Size: The number of list items shown at one time.

For descriptions of the other controls on this dialog, see "Common Features of the Add Widget Dialogs" on page 22-7. The LIST Dialog is an interface to IDL's WIDGET_LIST function. See "WIDGET_LIST" on page 1-1021 of the IDL Reference Guide.

Pull Down Menu

Select this option to create a new pulldown menu. The PDMENU Dialog appears. Controls unique to this dialog are described below.

•	List of Items: The list in the upper-left corner of the dialog shows the items in the pulldown menu. When creating a new pulldown menu, this list shows the top-level menu buttons. To create the sub-menu items (the elements that are shown when the menu is pulled down), click on an item in this list and click "Edit as a SubMenu". Another PDMENU dialog is displayed. Items in the list that have sub-menu items have an asterisk (*) to the left of their names.

•	Button Value: To add a new pulldown menu item, enter the text for the pulldown item and click on "Add" or press Return.

•	Edit as a Submenu: Use this button to create new submenus in your pulldown menu. When a new pulldown menu is created, the PDMENU dialog allows you to create the top-level menu buttons. To create the sub-menu items (the options that are shown when the menu is pulled down), click on an item in the list, and click "Edit as a SubMenu". A new PDMENU dialog appears. Here you can enter the items to be shown in the pulldown list. If you click on one of these items and click "Edit as a SubMenu", yet another PDMENU dialog appears. Elements entered in this dialog would become cascading menu options of the selected pulldown menu option.

•	Delete: To delete an item from the list, click on the item name, then click the "Delete" button.

•	Add: Click on this button to put the current entry in the "Button Value" field into the list of menu items.

For descriptions of the other controls on this dialog, see "Common Features of the Add Widget Dialogs" on page 22-7. The PDMENU Dialog is an interface to the CW_PDMENU function. See "CW_PDMENU" on page 1-198 of the IDL Reference Guide..

Slider

Select this option to create a new slider widget. The SLIDER Dialog appears. Unique controls for this dialog are described below:

•	Slider Title: This field accepts a string to be used as the slider's title.

•	Minimum: An integer minimum value for the slider. The default is 0.

•	Initial: The initial value for the slider to be set to. The default is the minimum value.

•	Maximum: An integer maximum value for the slider.

•	Generate Drag Events: Click this button to make the slider return widget events while it is being repositioned.

•	Vertical Slider: Click this button to make the slider vertical. By default sliders are horizontal.

•	Suppress display of current value: Click this button to create a slider without a number field that reports the current value of the slider.

For descriptions of the other controls on this dialog, see "Common Features of the Add Widget Dialogs" on page 22-7. The SLIDER dialog is an interface to IDL's WIDGET_SLIDER function. See "WIDGET_SLIDER" on page 1-1027 of the IDL Reference Guide.

Floating Pt. Slider

Select this option to create a floating-point slider widget. The FSLID dialog appears. Controls unique to this dialog are described below.

•	Slider Title: This field accepts a string to be used as the slider's title.

•	Minimum: A floating-point minimum value for the slider. The default is 0.

•	Initial: The initial value for the slider to be set to. The default is the minimum value.

•	Maximum: A floating-point maximum value for the slider.

•	Generate Drag Events: Click this button to make the slider return widget events while it is being repositioned.

•	Vertical Slider: Click this button to make the slider vertical. By default sliders are horizontal.

•	Suppress display of current value: Click this button to create a slider without a number field that reports the current value of the slider.

For descriptions of the other controls on this dialog, see "Common Features of the Add Widget Dialogs" on page 22-7. The FSLID dialog is an interface to the CW_FSLIDER function. See "CW_FSLIDER" on page 1-194 of the IDL Reference Guide.

Text

Select this option to create a new text widget. The TEXT Dialog appears. Controls unique to this dialog are described below.

•	TEXT Widget Value: This multi-line text widget can be used to enter the initial text to be shown in the text widget.

•	Text Editable: Select this button to create an editable text widget. The EDITABLE keyword is set for this widget when a .pro file is generated.

•	Process All Events: Selecting this button causes the text widget to return a full set of text events. The ALL_EVENTS keyword is set for this widget when a .pro file is generated. Note that the ALL_EVENTS and EDITABLE keywords interact in complex ways, as described in the documentation for WIDGET_TEXT in the IDL Reference Guide.

•	No Auto-Newline: Select this button to suppress the automatic addition of newline characters when setting the value of a multi-line text widget. The NO_NEWLINE keyword is set for this widget when a .pro file is generated.

•	Add Scrollbars: Select this button to make the text widget scrollable.

For descriptions of the other controls on this dialog, see "Common Features of the Add Widget Dialogs" on page 22-7. The TEXT dialog is an interface to IDL's WIDGET_TEXT function. See "WIDGET_TEXT" on page 1-1032 of the IDL Reference Guide.

Dependent Base

Select this option to create a new, free-floating base (i.e., the base has its own frame). Caution: Dependent bases cannot be cut or copied from within the Widget Builder—be sure you want to add a dependent base before selecting this option.

The Dependent Base Dialog appears. This dialog is identical to the Add Base dialog except that it creates and modifies "dependent" bases.

The Rebuild Button

Click on the "Rebuild" button to redraw the current widget preview, reflecting any changes made since the last rebuild. This is the only way to see the effect of your changes to the current widget preview. The Widget Builder application never rebuilds the interface automatically.

When "Rebuild" is pressed, any changes made since the last time "Rebuild" was pressed are made to the preview. Note also that any open Add or Edit dialogs also influence the look of the rebuilt preview. Settings for any open Add or Edit dialogs are read by the Widget Builder and added to the preview.

The Help Button

Click this button to display information about the Widget Builder.


Widget Builder Tutorial

This brief tutorial shows how to use the Widget Builder to create a simple widget interface.

Start the Widget Builder

If you have not already done so, start the Widget Builder by entering the following command at the IDL prompt:

WIDED

After compiling, the Widget Builder main window and preview window appear.

The Main Window and Widget Preview

When first starting to use the Widget Builder, many users wonder what that little empty window is that pops up with the Widget Builder main window. That is the preview of your current widget tree. It shows the current state of the widgets as you add and/or change them. The preview is only updated when you click on the "Rebuild" button in the Widget Builder main window. This button is probably the most used button in the entire interface.

When your first start the Widget Builder, or after you have started a new widget interface by selecting "New" from the File menu, the entire preview consists of only an empty top level base widget. This little window is the widget that would be created if you entered the command:

B=WIDGET_BASE()& WIDGET_CONTROL, B, /REALIZE

at the IDL prompt.

The Widget Builder main window is used to select, configure, and edit widget elements. It controls the operation of the Widget Builder itself, and also controls the characteristics of the top-level widget base of the widget interface that you are building. Unlike the other Widget Builder dialogs, it cannot be dismissed without quitting the Widget Builder application.

A Simple Widget Interface

In the steps that follow, we'll create a simple widget interface as shown below.

Create a Title for the Top-Level Base

First, set the title for our new widget interface to "My Widget" by typing that into the "Title:" field in the Widget Builder main window.

To see the change we have just made, we must click on the "Rebuild" button.

Note that since we haven't put anything into the top-level base, part of the title will not be visible until we resize the preview window.

Add a New Sub-Base and Pulldown Menu

Now we need to add some children to the main base. First, add a new sub-base widget by selecting "Base" from the Add menu on the main window. A BASE dialog appears. Ignore this dialog for now and add a pulldown menu by selecting "Pull Down Menu" from the Add menu on the main window. A PDMENU dialog appears.

The Add/Edit Dialogs

A new dialog appears for each element you select from the Add menu. The windows are titled to give you an indication of which element you are working on at any given time. For example, when you select "Pull Down Menu", a new control panel with a title something like "PDMENU614 (Child of Top Base)" appears. This title tells you what type of widget element is being created (a PD menu), and which widget is the parent of this widget. The number, (614 in this example) is a unique identifier for the widget element and is used to distinguish between similar elements. You can change the name of any object except the Top Base by entering a string in the "Name:" field of its dialog. As you fill in information about a widget, the Widget Builder refers to that widget in a clearer way based on that information—titles, values, user values, and names, are used in preference to automatically generated numbers.

Configure the Pulldown Menu

Now let's configure the pulldown menu. Select the control panel titled "PDMENUxxx (Child of Top Base)". To add an entry to the menu, simply type the entry in the "Button Value:" field and press Return. Create three buttons in the top-level of the pulldown menu by typing:

One	Now press Return.

Tow	Press Return. Yes, I'm sure you noticed its misspelled, but play along for now!

Three	Press Return again.

Rebuild your preview (by clicking "Rebuild" on the main window) if you like. The PDMENU dialog should now look something like this:

Correct the Error

As you probably noticed earlier, the second button has a misspelled label. To correct it, click on the "Tow" entry in the list, then click the "Delete" button. Now add the correct version clicking on the "One" entry in the list, typing "Two" into the "Button Value:" field, and pressing Return or clicking on the "Add" button. The "Two" entry is added after "One". A menu entry is always added to the list immediately after the currently selected entry or at the end of the list if there is no current selection. Select "<Top of List>" to add an entry as the first item in the menu.

Add Another Level to the Pulldown Menu

The pulldown menu items we just added represent the top-level buttons of the pulldown menu. Currently, these buttons do not reveal pulldown menu lists because we haven't specified any items for them.

Let's add some pulldown items to the "Two" menu button. Select "Two" in the list and click the "Edit as a Submenu" button. A dialog titled "Submenu Two" appears. This dialog looks very similar to the PDMENU dialog that popped up when you first added a pulldown menu widget.

Fill in the submenu with the entries "Four", "Five", and "Six" by entering those names in the "Button Value:" field of this new dialog just like we did for the first three buttons in the previous dialog. Click on the "Done" button for both the submenu dialog ("Submenu Two") and the pulldown menu dialog ("PDMENUx (Child of Top Base)").

Click the "Rebuild" button to preview our progress. You can see the submenu for the "Two" button by clicking on that button in the preview.

Configuring the Sub-Base

Now let's work on the sub-base we created earlier. Find the sub-base dialog. It should have a title like "BASE2 (Child of Top Base)". If you can't find the dialog easily (or if you accidentally dismissed the dialog earlier) you can instead use the "Edit Child" option in the Edit menu of the Widget Builder main window. Select the base in the list that appears and click on the "Edit Child" button. The dialog will be re-created if it had been destroyed or will pop to the top of the display if it is hidden beneath other windows.

Note that the BASE dialog is very similar to the Widget Builder main window. Don't get them confused!

Add a Draw Widget to the Sub-Base

Go to the "Add" menu on the base dialog and select "Draw". A DRAW dialog appears. In this dialog, set the "X Size" field to 400, and the "Y Size" field to 200. Make IDL handle the backing store for the draw window by clicking on the "IDL" choice in the "Backing Store:" menu. Click on the "Done" button when you are finished.

Add a Label to the Sub-Base

Now add a label widget to the sub-base by choosing the "Label" option from the sub-base dialog's "Add" menu. A label dialog appears. Set the "Label Text:" field to "Some *Really* Great Data" and press the "Done" button. Now click "Rebuild" in the main window to update the preview. Your preview should look like this:

Finishing Touches

This is close to our goal, but not quite! In the finished interface, the widgets are arranged in columns, not rows. To make this change, click on the "Column" button in the "Base Type" sections of both the sub-base dialog and the Widget Builder main window. Click on "Rebuild".

Reposition the Label

Now things are close to being right except that the label should be  above the draw widget:

We'll need to cut the label and paste it into the proper position. Select "Cut" from the main window's Edit menu. The Cut dialog appears. You may have noticed that the label widget and draw widget seem to be missing from this list. They are not shown in this list because they are children of the sub-base that we created.

To see the children of the sub-base, click on the name of the sub-base in the Cut dialog's list. Now click on the Show Children button. The Cut dialog changes to show the children—the draw and label widgets. Click on the label in the new list, then click on "Cut Child". Click on "Done" to dismiss the Cut dialog. Though it hasn't been reflected in the preview yet, the label widget has been removed from the widget tree and placed on the Widget Builder's clipboard.

Select "Paste" from the Widget Builder's Edit menu. The Paste dialog appears.

We want to paste the label back into the sub-base, but before the draw widget. To accomplish this, click on the name of the base in the list on the right. Now click on "Show Children". The list changes to show the contents of the sub-base (currently, just the draw widget). Note that the highlight in the new list is on "<Top of List>". Now click "Paste After" and the label is pasted into the list after "<Top of List>" and before the draw widget.

The Final Rebuild

Click on "Rebuild" one last time to ensure that everything is correct. Your widget preview should look like Figure 22.20.

Save the Current Widget Tree

Now we save our work. Choose "Save" from the main window's File menu. A file saving dialog appears. Choose a file in which to save your widget tree. For example, you might want to call it great.wid. The widget tree is saved in a special format that can be read by the Widget Builder (by selecting "Open" from the file menu) at a later time.

Create an IDL Program File

You may also want the Widget Builder to write the IDL code it would take to create the widget tree. This code could then be modified to create a fully-functional application. Select "Create .PRO" from the Widget Builder's File menu. A cascading list of options appears—select "Normal". A file selection dialog appears. Create a file named great.pro. Quit the Widget Builder (by selecting "Quit" from the File menu) and try running great.pro by entering great at the IDL prompt. A running copy of the widget tree we just built should appear. Note that manipulating the widgets causes messages to be printed in the IDL log window. You can examine the contents of great.pro with a text editor to see how its event handler is turning widget events into actions in IDL.

Jump forward to Scientific Data Formats

Jump backward to Widgets


Scientific Data Formats
23	Scientific Data Formats

Chapter Overview

This chapter provides an overview the three self-describing scientific data formats supported by IDL—CDF (Common Data Format), HDF (Hierarchical Data Format), and netCDF (Network Common Data Format). These data formats are now supported on all IDL platforms. More detailed documentation for each routine can be found in the IDL Reference Guide.


Topics in Scientific Data Formats Chapter
Scientific Data Formats

This chapter describes IDL's scientific data formats.

Topics Covered:

CDF—Common Data Format

HDF—Hierarchical Data Format

NetCDF—Network Common Data Format

Jump forward to Remote Procedure Calls

Jump backward to Widget Builder


CDF - Common Data Format
CDF—Common Data Format

The Common Data Format is a file format that facilitates the storage and retrieval of multi-dimensional scientific data. The current release of IDL supports CDF version CDF2_5r6. IDL's CDF routines all begin with the prefix "CDF_". Documentation for these routines can be found in the IDL Reference Guide, beginning on page 1-59.

CDF is a product of National Space Science Data Center (NSSDC). General information about CDF, including the "frequently-asked-questions" (FAQ) list, software, and CDF's IDL library (an alternative interface between CDF and IDL) are available on the World Wide Web at:

http://nssdc.gsfc.nasa.gov/cdf/cdf_home.html

If you do not have access to the WWW you can get CDF information via ftp at:

ftp://ncgl.gsfc.nasa.gov/pub/cdf/FAQ.doc

For assistance via e-mail, send a message to the internet address:

cdfsupport@nssdca.gsfc.nasa.gov

CDF Version 2.5 Compatibility Warning

CDFs created with CDF V2.5 (the version currently used by IDL) take up less disk space than CDFs created with previous CDF distributions. The new version saves 1689 bytes per CDF file regardless of the file's contents, plus an additional savings of 128 bytes per variable. A side effect of this improvement is that V2.5 CDFs can only be read with the CDF V2.5 distribution. CDF V2.5 files are not readable by previous versions of CDF.


HDF - Hierarchical Data Format
HDF—Hierarchical Data Format

The Hierarchical Data Format (HDF) is a multi-object file format that facilitates the transfer of various types of data between machines and operating systems. HDF is a product of the National Center for Supercomputing Applications (NCSA). HDF is designed to be flexible, portable, self-describing and easily extensible for future enhancements or compatibility with other standard formats. The HDF library contains interfaces for storing and retrieving images and multi-dimensional scientific data. This version of IDL supports HDF3_3r4. IDL's HDF routines all begin with the prefix "HDF_". Documentation for these routines can be found in the IDL Reference Guide, beginning on page 1-340.

Further information about HDF can be found on the World Wide Web. The HDF "Frequently-Asked Questions" file can be found at:

http://hdf.ncsa.uiuc.edu:8001/HDF-FAQ.html

Alternately, you can send e-mail to hdfhelp@ncsa.uiuc.edu.

HDF Interfaces

There are two basic interfaces to HDF files, the single-file application interface and the multiple-file application interface. These interfaces support eight different types (or "models") of data access. The table below lists the different models and the names of the IDL routines that access those models. Each model is described in more detail after the table.

Model	IDL Routine Name Prefix
24-bit raster	HDF_DF24_
annotation data	HDF_DFAN_
palette data	HDF_DFP_
8-bit raster	HDF_DFR8_
scientific data	HDF_DFSD_
multi-file scientific data	HDF_SD_
VData	HDF_VD_
VGroup	HDF_VG_
Table 23.1 Prefixes for IDL HDF Interface Commands

Single File Application Interfaces

In this mode, access is limited to one file at a time. This interface supports the 8-bit raster, 24-bit raster, palette, scientific data, and annotation models. The interfaces are described in more detail after the table.

•	8-bit Raster Model: The HDF_DFR8_ routines access 8-bit images.

•	Palette Model: The HDF_DFP_ routines are used to work with the HDF_DFR8_ routines to manipulate palettes associated with 8-bit HDF images.

•	24-bit Raster Model: The HDF_DFR24_ routines access 24-bit images.

•	Scientific Data Models (SDs): Used to manipulate arrays of arbitrary dimension and type. Under this model, an array accompanied by a record of its data type, dimensions and descriptors is called a Scientific Dataset (SD). HDF supports two kinds of SDs—the older single-file DFSD, and the new, NetCDF based, MFSD.

To show preference to the new format, HDF and IDL refer to "MFSD" as simply "SD". IDL calls to the SD model are distinguished by the prefix HDF_SD, while calls to the DFSD are distinguished by the HDF_DFSD prefix. Unfortunately, HDF3.3r4 uses the same tags for the two different scientific data models. Therefore, caution should be used when accessing the SDs through tags. IDL routines may seem to work, but may actually read incorrect information when tags, and not the standard HDF_SD_ routines, are used.

•	Annotation Model: The annotation model is used to describe the contents of the file through such items as labels, data descriptors, and dimension scales.

•	Vdata Model: This interface allows for the creation of customized tables. Each table consists of a series of Vdata records whose values are stored in fixed length fields. As described in more detail in the Vdata example below, a Vdata can contain three kinds of identifying information: a Vdata name, Vdata Class, and multiple Vdata field names. The Vdata model is accessed through the routines that begin with the HDF_VD_ prefix.

•	Vgroup Model: A collection of one or more data objects, Vdata sets, or Vgroups is known as a Vgroup. Each Vgroup can be given a Vgroup name and Vgroup class. The Vgroup model is accessed through the routines that begin with the HDF_VG_ prefix.

Multi-File Application Interface

The HDF_SD_ routines allow operations on more than one file at a time. This multi-file interoperability is achieved through HDF's use of a modified version of the NetCDF library. IDL's interface to HDF's multi-file capability is the HDF_SD_SETEXTFILE routine.

Creating an HDF File in IDL

The following IDL commands should be used to create a new HDF file:

•	HDF_OPEN: Call this procedure first to open an HDF file. The CREATE keyword must be set if you want to create a new file instead of open an existing one.

•	HDF_DFAN_ADDFDS: Optionally, add a file description.

•	HDF_DFAN_ADDFID: Optionally, add a file annotation.

Adding Data to an HDF File

The routines used to add data to an HDF file vary based on the interface model being used.

•	To add an 8-bit image (with or without a palette), use HDF_DFR8_ADDIMAGE or DFR8_PUTIMAGE.

•	To add a palette, use HDF_DFP_ADDPAL or HDF_DFP_PUTPAL.

•	To add a 24-bit image, use HDF_DF24_ADDIMAGE or HDF_DF24_PUTIMAGE.

•	To add a Scientific Dataset, use the following commands:

HDF_DFSD_SETINFO to insert information about the data (optional). HDF_DFSD_DIMSET to set dimension information.
HDF_DFSD_ADDDATA to insert the data.

•	To add a Multi-File Scientific Dataset, use the following commands:

HDF_SD_CREATE or HDF_SD_SELECT to create an SDS or select an existing one.
HDF_SD_DIMSET to set dimension information.
HDF_SD_ATTRSET to set attribute information.
HDF_SD_SETINFO to insert optional information about the data.
HDF_SD_ADDDATA to insert the data.
HDF_SD_SETEXTFILE to move the data to an external file (optional).
HDF_SD_ENDACCESS to end access to the SDS.

•	To add a Vdata, use the following commands:

HDF_VD_ATTACH to get a Vdata identifier.
HDF_VD_SETINFO to write information about the Vdata (optional). HDF_VD_FDEFINE to prepare non-trivial fields (optional).
HDF_VD_WRITE to write the Vdata.

•	To add a Vdata to a Vgroup, use the following commands:

HDF_VG_ATTACH to get a Vgroup identifier.
HDF_VG_SETINFO to set the Vgroup name and class (optional).
HDF_VG_INSERT to add the Vdata to a Vgroup.
HDF_VG_DETACH to close the Vgroup.
HDF_CLOSE to close the file.

HDF Examples

Two example files that demonstrate the use of the HDF routines can be found in the hdf_ncdf subdirectory of the examples subdirectory of the IDL distribution. The file hdf_info.pro prints a summary of basic information about an HDF file. The file  hdf_rdwr.pro creates a new HDF file and then reads the information back from that file.

HDF Scientific Dataset ID Numbers

IDL's HDF_SD_ routines can accept two different types of ID numbers. Documentation for these routines in the IDL Reference Guide refers to these ID numbers as the SD_ID and SDS_ID arguments.

The SD_ID is the Scientific Dataset interface ID. There is only one SD_ID per HDF file. For each actual dataset used, you will also need an  SDS_ID, which is the ID for the particular dataset.

Some routines, such as HDF_SD_ATTRFIND accept either an SD_ID or an SDS_ID. In these cases, the documentation refers to the ID as an S_ID, meaning that either type of ID is accepted.

A Cautionary Note about Tags

Both the old DFSD and the new MFSD HDF interfaces use the same tags. Therefore, you must be careful when reading or writing SDs. Use only the appropriate "HDF_SD_" or "HDF_DFSD_" routines. The wrong SD interface may seem to work, but may return bad results.

 IDL and HDF Data Types

HDF and IDL support many different data types. Many of the HDF routines allow you perform a data type conversion "on the fly" by setting keywords such as FLOAT. When the data type desired is not explicitly specified, IDL uses the conversions shown in the following tables. Note that single-precision floating-point is the default data type and that the complex data type is not supported.

When writing IDL data to an HDF file, IDL data types are converted to the HDF data types shown in the following table:

IDL Data Type	HDF Data Type
BYTE	DFNT_UINT8 (IDL bytes are unsigned)
INT	DFNT_INT16
LONG	DFNT_INT32
FLOAT	DFNT_FLOAT32
DOUBLE	DFNT_DOUBLE
STRING	DFNT_CHAR
Table 23.2 Type Conversions when Writing IDL Data to an HDF File

When reading data from an HDF file, HDF data types are converted to the IDL data types shown in the following table:

HDF Data Type	IDL Data Type
DFNT_CHAR or DFNT_UCHAR	STRING
DFNT_INT8 or DFNT_UINT8	BYTE
DFNT_INT16 or DFNT_UINT16	INT
DFNT_INT32 or DFNT_UINT32	LONG
DFNT_FLOAT32 or DFNT_NONE	FLOAT
DFNT_DOUBLE	DOUBLE
Table 23.3 Type Conversions when Reading HDF Data into IDL

HDF type codes for the supported HDF data types are shown in the table below:

HDF Data Type	Type Code
DFNT_UCHAR	3
DFNT_CHAR	4
DFNT_FLOAT32	5
DFNT_DOUBLE	6
DFNT_INT8	20
DFNT_UINT8	21
DFNT_INT16	22
DFNT_UINT16	23
DFNT_INT32	24
DFNT_UINT32	25
Table 23.4 HDF Data Type Codes

Common HDF Tag Numbers

The following table lists common HDF tag numbers and their meanings.

Tag Number	Meaning
030	Version Identifier
100	File Identifier
101	File Description
102	Tag Identifier
103	Tag Description
104	Data Identifier Label
105	Data Identifier Annotation
106	Number Type
107	Machine Type
200	8-Bit Image Dimensions
201	8-Bit Palette
202	8-Bit Raster Image
203	8-Bit Image-Compressed
204	8-Bit Image-INCOMP Compressed
300	RIG Image Dimension
301	Raster Image Look Up Table (LUT)
302	Raster Image
306	Raster Image Group (RIG)
307	RIG LUT Dimension
308	RIG Matte Dimension
309	Raster Image Matte Data
310	Raster Image Color Correction
311	Raster Image Color Format
312	Raster Image Aspect Ratio
400	Composite Image Descriptor
500	XY Position
602	Vector Image - Tek4014 Stream
603	Vector Image - Tek4105 Stream
701	SD Dimension Record
702	SD Data
703	SD Scales
704	SD Labels
705	SD Units
706	SD Formats
707	SD Max/Min
708	SD Coordinates
720	SD Descriptor (NDG)
731	SD Calibration Information
732	SD Fill Value
1962	Vdata Description
1963	Vdata
1965	Vgroup
Table 23.5 Common HDF Tag Numbers


NetCDF - Network Common Data Format
NetCDF—Network Common Data Format

The network Common Data Format (netCDF) is a self-describing scientific data access interface and library developed at the Unidata Program Center in Boulder, Colorado. The netCDF interface and library use XDR (eXternal Data Representation) to make the data format machine-independent. IDL's NetCDF routines all begin with the prefix "NCDF_". Documentation for these routines can be found in the IDL Reference Guide, beginning on page 1-595.

More information about netCDF can be found on Unidata's netCDF World Wide Web home page which can be found at:

http://www.unidata.ucar.edu/packages/netcdf/

Further information and the original netCDF documentation can be obtained from Unidata at the following addresses:

UCAR Unidata Program Center
P.O. Box 3000
Boulder, Colorado, USA 80307
(303) 497-8644
email: support@unidata.ucar.edu

General notes and examples about the interface are presented below, followed by descriptions of the IDL interface routines.

NetCDF Data Modes

There are two modes associated with accessing a netCDF file: define mode and data mode. In define mode, dimensions, variables, and new attributes can be created but variable data cannot be read or written. In data mode, data can be read or written and attributes can be changed, but new dimensions, variables, and attributes cannot be created.

IDL's NCDF_CONTROL routine can be used control the mode of a netCDF file. The only time it is not necessary to set the mode with NCDF_CONTROL is when using the NCDF_CREATE procedure to create a new file. NCDF_CREATE places the new netCDF file into define mode automatically.

Attributes, Dimensions, and Variables

The three basic components of a netCDF file are described below.

Attributes

Attributes can contain auxiliary information about an entire netCDF file (global attributes) or about a single netCDF variable. Every attribute has a name, data type, and length associated with it. It is common to repeat attribute names for each variable. For example, every variable in a netCDF file might have an attribute named "Units". Note however, that variables cannot have multiple attributes with the same names.

Dimensions

Dimensions are named integers that are used to specify the size (or  dimensionality) of one or more variables. Each dimension must have a unique name, but a variable and dimension can share a name. Each netCDF file is allowed to have one boundless (or unlimited) dimension. Most often the unlimited dimension is used as a temporal variable, allowing data to be appended to an existing netCDF file. An example of this use is shown later.

Variables

Variables are multidimensional arrays of values of the same data type. Each variable has a size, type, and name associated with it. Variables can also have attributes that describe them.

Creating NetCDF Files

The following IDL commands should be used to create a new netCDF file:

•	NCDF_CREATE: Call this procedure to begin creating a new file. The new file is put into define mode.

•	NCDF_DIMDEF: Create dimensions for the file.

•	NCDF_VARDEF: Define the variables to be used in the file.

•	NCDF_ATTPUT: Optionally, use attributes to describe the data.

•	NCDF_CONTROL, /ENDEF: Call NCDF_CONTROL and set the ENDEF keyword to leave define mode and enter data mode.

•	NCDF_VARPUT: Write the appropriate data to the netCDF file.

•	NCDF_CLOSE: Close the file.

Reading NetCDF Files

The following commands should be used to read data from a netCDF file:

•	NCDF_OPEN: Open an existing netCDF file.

•	NCDF_INQUIRE: Call this function to find the format of the netCDF file.

•	NCDF_DIMINQ: Retrieve the names and sizes of dimensions in the file.

•	NCDF_VARINQ: Retrieve the names, types, and sizes of variables in the file.

•	NCDF_ATTNAME: Optionally, retrieve attribute names.

•	NCDF_ATTINQ: Optionally, retrieve the types and lengths of attributes.

•	NCDF_ATTGET: Optionally, retrieve the attributes.

•	NCDF_VARGET: Read the data from the variables.

•	NCDF_CLOSE: Close the file.

If the structure of the netCDF file is already known, the inquiry routines do not need to be called—only NCDF_OPEN, NCDF_ATTGET, NCDF_VARGET, and NCDF_CLOSE would be needed.

NetCDF Examples

Two example files that demonstrate the use of the netCDF routines can be found in the hdf_ncdf subdirectory of the examples subdirectory of the IDL distribution. The file nncdf_cat.pro prints a summary of basic information about a netCDF file. The file ncdf_rdwr.pro creates a new netCDF file and then reads the information back from that file.

A Complete Example with Unlimited Dimensions

The following example shows how to create a netCDF file, populate it with data, read data from the file, and make a simple plot from the data.The resulting graphic is shown below.

id = NCDF_CREATE('inquire.nc', /CLOBBER)
Create a new NetCDF file with the filename inquire.nc.

NCDF_CONTROL, id, /FILL	Fill the file with default values.

hours = INDGEN(5)	We'll create some time-dependant data, so here is an array of hours from 0 to 5.

data = FLTARR(5,10)	Create a 5 by 10 array to hold floating-point data.

FOR i=0,9 DO $	Generate some values.

    data(*,i) = (i+0.5) * EXP(-hours/2.) / SIN((i+1)/30.*!PI)

xid = NCDF_DIMDEF(id, 'x', 10)	Make dimensions.

zid = NCDF_DIMDEF(id, 'z', /UNLIMITED)

hid = NCDF_VARDEF(id, 'Hour', [zid], /SHORT)
Define variables.

vid = NCDF_VARDEF(id, 'Temperature', [xid,zid], /FLOAT)
Define variable.

NCDF_ATTPUT, id, vid, 'units', 'Degrees x 100 F'

NCDF_ATTPUT, id, vid, 'long_name', 'Warp Core Temperature'

NCDF_ATTPUT, id, hid, 'long_name', 'Hours Since Shutdown'

NCDF_ATTPUT, id, /GLOBAL, 'Title', 'Really important data'

NCDF_CONTROL, id, /ENDEF	Put file in data mode.

NCDF_VARPUT, id, hid, hours 	Input data.

FOR i=0,4 DO NCDF_VARPUT, id, vid, $

                  REFORM(data(i,*)), OFFSET=[0,i]
Oops! We forgot the 6th hour! This is not a problem, however, as you can dynamically expand a netCDF file if the unlimited dimension is used.

NCDF_VARPUT, id, hid, 6, OFFSET=[5]	Add the hour and data.

NCDF_VARPUT, id, vid, FINDGEN(10)*EXP(-6./2), OFFSET=[0,5]
Add the temperature.

NCDF_VARGET, id, vid, output_data	Read the data back out.

NCDF_ATTGET, id, vid, 'long_name', ztitle

NCDF_ATTGET, id, hid, 'long_name', ytitle

NCDF_ATTGET, id, vid, 'units', subtitle

!P.CHARSIZE = 2.5

!X.TITLE = 'Location'

!Y.TITLE = STRING(ytitle)	Convert from bytes to strings.

!Z.TITLE = STRING(ztitle) + '!C' + STRING(subtitle)

NCDF_CLOSE, id	Close the NetCDF file.

SHOW3, output_data	Display the data.

Type Conversion

Values are converted to the appropriate type before being written to a netCDF file. For example, in the commands below, IDL converts the string "12" to a floating-point 12.0 before writing it:

varid=NCDF_VARDEF(fileid, 'VarName', [d0,d1,d2+d3], /FLOAT)

NCDF_VARPUT, fileid, 'VarName', '12'

Specifying Attributes and Variables

Variables and attributes can be referred to either by name or by their ID numbers in most netCDF routines. For example, given the NCDF_VARDEF command shown below, the two NCDF_VARPUT commands shown after it are equivalent:

varid = NCDF_VARDEF(fileid, 'VarName', [d0,d1,d2+d3], /FLOAT)

NCDF_VARPUT, fileid, 'VarName', '12'	Reference by variable name.

NCDF_VARPUT, fileid, varid,'12'	Reference by variable ID.

String Data in NetCDF Files

Strings are stored as arrays of ASCII bytes in netCDF files. To read string data from netCDF files, use the STRING function to convert bytes back into characters. When writing an IDL string array to a variable, an extra dimension (the maximum string length) must be added to the variable definition. Both of these situations are illustrated by the following example:

string_in = REPLICATE('Test String',10,10)
Make a test string

string_in(0,0) = 'Long Test String'	Make one element longer than the others.

HELP, string_in	IDL reports:
STRING_IN    STRING  = Array(10, 10)

ncdfid = NCDF_CREATE('string.nc', /CLOBBER)
Create a new netCDF file.

xid = NCDF_DIMDEF(ncdfid, 'height', 10)
Define first dimension.

yid = NCDF_DIMDEF(ncdfid, 'width', 10)
Define second dimension.

zid = NCDF_DIMDEF(ncdfid, 'length', MAX(STRLEN(string_in)))
Find the length of the longest string and use that as the third dimension.

id = NCDF_VARDEF(ncdfid, 'strings', [zid,yid,xid], /CHAR)
Define the variable with dimensions zid, yid, xid.

NCDF_CONTROL, ncdfid, /ENDEF	Put the file into define mode.

NCDF_VARPUT, ncdfid, id, string_in	Write the string variable. The array will be stored as bytes in the file.

NCDF_VARGET, ncdfid, id, byte_out	Read the byte array back out.

NCDF_CLOSE, ncdfid	Close the file.

HELP, byte_out	IDL reports that BYTE_OUT is a (16, 10, 10) BYTE array.

PRINT, STRING(byte_out(*,0,0))	Taking the STRING of the first "row" of byte_out returns the first element of our original array, "Long Test String".

string_new = STRING(byte_out)	Convert the entire byte array back into strings.

HELP, string_new	The new string array has the same dimensions and values as our original string, string_in.

IF TOTAL(string_in NE string_new) EQ 0 THEN PRINT, 'Success!'
This statement compares the two arrays and prints "Success!" if they are equal—and they are.

Jump forward to Remote Procedure Calls

Jump backward to Widget Builder


Remote Procedure Calls
24	Remote Procedure Calls

Chapter Overview

Remote Procedure Calls (RPCs) allow one process (the client process) to have another process (the server process) execute a procedure call just as if the caller process had executed the procedure call in its own address space. Since the client and server are separate processes, they can reside on the same machine or on different machines. RPC libraries allow the creation of network applications without having to worry about underlying networking mechanisms.

IDL supports RPCs so that other applications can communicate with IDL. A library of C language routines is included to handle communication between client programs and the IDL server. Note that remote procedure calls are supported only on Unix platforms.

The current implementation allows IDL to be run as an RPC server and your own program to be run as a client. IDL commands can be sent from your application to the IDL server, where they are executed. Variable structures can be defined in the client program and then sent to the IDL server for creation as IDL variables. Similarly, the values of variables in the IDL server session can be retrieved into the client process.


Topics in Remote Procedure Calls Chapter
Remote Procedure Calls

This chapter describes IDL's remote procedure call capabilities.

Topics Covered:

Using IDL as an RPC Server

The IDL RPC Library

The varinfo_t Structure

More Variable Manipulation Macros

Notes on Variable Creation and Memory Management

RPC Examples

Jump forward to Reporting Bugs

Jump backward to Scientific Data Formats


Using IDL as an RPC Server

The IDL RPC Directory

All of the files related to using IDL's RPC capabilities are found in the rpc subdirectory of the external subdirectory of the main IDL directory. The main IDL directory is referred to here as idldir.

Running IDL in Server Mode

To use IDL as an RPC server, run IDL in server mode by using the -server command line option. This option can be invoked one of two ways:

idl -server process_id

or

idl -server=server_number process_id

where server_number is the hexadecimal server ID number (between 0x20000000 and 0x3FFFFFFF) for IDL to use. For example, to run IDL with the server ID number 0x20500000, use the command:

idl -server=20500000

If a server ID number is not supplied, IDL uses the default, IDL_DEFAULT_ID, defined in the file idldir/external/rpc/rpc_idl.h. This value is originally set to 0x2010CAFE.

The process_id argument is an optional argument that specifies the process ID of a Unix process that should be contacted when IDL has finished running in interactive mode. If the IDL rpc server is placed in interactive mode and a process ID has been supplied on the command line, IDL sends the Unix signal SIGUSR1 to the specified process. This signal allows the client program to know when it can continue to communicate with the rpc server.

Creating the IDL RPC Library

The machine that runs the client program must have its own version of the IDL RPC library. The make file for this library is contained in the directory idldir/external/rpc. If the machine that runs the client program is not licensed to run IDL, simply copy the contents of the IDL rpc directory to an appropriate location on the client machine.

To build the IDL RPC library, copy the IDL rpc directory to a new directory, change to that directory, and enter the make command:

cp -R idldir/external/rpc newrpcdir
cd newrpcdir
make

The created library is contained in the file newrpcdir/rpcidl.a. The functions contained in the library are described in "The IDL RPC Library" on page 24-3.

Linking your Client Program

Your client program must include the file idldir/external/rpc/rpc_idl.h.

You must also link the application that communicates with IDL with the IDL RPC library. For example, to compile and link a program with the IDL RPC library, you might enter:

cc -c rpcclient.c
cc -o rpcclient.o idldir/external/rpc/rpcidl.a

where rpcclient.c is the name of your program. Note that your actual command lines and flag settings may be different than the ones shown above, depending upon your C compiler. The Makefile contains details on modifications for various systems.


The IDL RPC Library

The IDL RPC library contains several C language interface functions that facilitate communication between your application and IDL. There are functions to register and unregister clients, set timeouts, get and set the value of IDL variables, send commands to the IDL server, and cause the server to exit. These functions are described below.

free_idl_variable

Calling Sequence

void free_idl_var(varinfo_t* var);

Description

This function frees all dynamic memory associated with the given variable. Attempts to free a static variable are silently ignored. (See "Notes on Variable Creation and Memory Management" on page 24-12.)

Parameters

var

The address of the varinfo_t structure that contains the information about the variable to be freed.

Return Value

None.

get_idl_variable

Calling Sequence

int get_idl_variable(CLIENT* client, char* name, varinfo_t* var,
     int typecode)

Description

Call this function to retrieve the value of an IDL variable in the IDL session referred to by client. Any scalar or array variable type can be retrieved. Variables can be retrieved only from the main program level.

Note that it is not possible to get the value of an IDL structure. To retrieve values from an IDL structure, "decompose" the structure into regular variables in IDL, then use this function to get the values of those individual variables.

It is not possible to get the value of IDL system variables directly. To retrieve the value of an IDL system variable, first copy it to a regular IDL variable. The value of the regular variable can then be retrieved with get_idl_variable. For example:

varinfo_t pt;	/* Declare variable pt */
send_idl_command(client, "X = !P.T");
get_idl_variable(client, "X", &pt, 0);

Parameters

client

A pointer to the CLIENT structure that corresponds to the desired IDL session.

name

A null terminated string that contains the name of the IDL variable to be retrieved. Only the first MAXIDLEN characters of this string are used. MAXIDLEN is defined in the file idldir/external/rpc/rpc_idl.h.

var

The address of a varinfo_t structure in which to store the returned variable information. Upon return, the Name field of the var structure contains the name of the variable as found in IDL. If the name supplied is an illegal IDL variable name, the Name field is set to <ILLEGAL_NAME>. If the variable is a structure or associated variable, the Name field is set to <BAD-VAR-TYPE>.

typecode

If you want IDL to typecast a variable (i.e., guarantee the value to be of a particular type) before it is transported, set typecode to one of the following values (defined in the file export.h):

IDL_TYP_BYTE, IDL_TYP_INT, IDL_TYP_LONG, IDL_TYP_FLOAT, IDL_TYP_DOUBLE, IDL_TYP_STRING, IDL_TYP_COMPLEX, IDL_TYP_DCOMPLEX

For example, the command:

get_idl_variable(client, "x", &xv, IDL_TYP_LONG)

guarantees that the value in x is returned as a 32-bit integer.

If typecode is 0, the variable is transferred with whatever data type it has in the server. Typecasting only affects the variables in the client ­ the server side is not affected.

Return Value

This function returns a status value that denotes the success or failure of this function as described below.

-1	Failure: bad arguments supplied (e.g., name or var is NULL).

 0	RPC mechanism failed (an error message may also be printed).

 1	Success

-2	Illegal variable name (e.g., "213xyz", "#a", "!DEVICE")

-3	Variable not transportable (e.g., the variable is a structure or associated
variable)

idl_server_interactive

Calling Sequence

int idl_server_interactive(CLIENT*client)

Description

Call this function to cause the IDL server to become an interactive IDL session. It is likely that this command will time out. Some alternative mechanism for determining when the server is finished should be implemented. See the example server.c in the idldir/examples/rpc directory.

Parameters

client

A CLIENT structure that corresponds to the desired IDL session.

Return Value

This function returns TRUE if the interactive IDL session did not time out. FALSE is returned if the session times out or otherwise fails.

kill_server

Calling Sequence

int kill_server(CLIENT*client)

Description

Call this function to kill the IDL RPC server.

Parameters

client

The pointer to a CLIENT structure registered with the server to be killed.

Return Value

This function returns TRUE if the server was successfully killed. FALSE is returned otherwise.

register_idl_client

Calling Sequence

CLIENT* register_idl_client(long server_id, char* hostname,
     struct timeval* timeout)

Description

Call this function to register your program as a client of an IDL server. Note that a program can be the client of a number of different servers at the same time and a single server can have multiple clients.

Parameters

server_id

The ID number of the IDL server that the program is to be registered with. If this value is 0, the default server ID (0x2010CAFE) is used.

hostname

The name of the machine where the IDL server is running. If this value is NULL or "", the default, localhost, is used.

timeout

A pointer to the timeout value for all communication with IDL servers. If this value is NULL or 0, the default timeout, 60 seconds, is used.

Return Value

A pointer to the new CLIENT structure is returned. This function returns NULL if it is unsuccessful.

send_idl_command

Calling Sequence

int send_idl_command(CLIENT* client, char* command);

Description

Call this function to send an IDL command to the IDL server referred to by client. The command is executed just as if it had been entered from the IDL command line.

This function cannot be used to send multi-line commands. If the first part of a multi-line command is sent, for example:

send_idl_command(client, "FOR I=1,5 DO $");

IDL spawns an interactive session and may hang. In any case, subsequent commands are not executed.

Parameters

client

A pointer to the CLIENT structure that corresponds to the desired IDL session.

command

A null-terminated string with no more than MAX_STRING_LEN characters. MAX_STRING_LEN is defined in the file idldir/external/rpc/rpc_idl.h.

Return Value

This function returns a status value that denotes success or failure as described below.

-1	RPC communication failure (an error message is also printed).

 0	Command is NULL.

 1	Success.

For all other errors, the error number is returned. This number could be passed as an argument to STRMESSAGE();.

set_idl_timeout

Calling Sequence

int set_idl_timeout(struct timeval* timeout)

Description

Call this function to replace the current timeout used by the RPC mechanism with the given timeout.

Parameters

timeout

A pointer to the new timeout value to be used. This parameter has no default.

Return Value

This function returns TRUE if the timeout was replaced. FALSE is returned if the timeout value was NULL or zero.

set_idl_variable

Calling Sequence

int set_idl_variable(CLIENT* client, varinfo_t* var);

Description

Call this function to assign a value to an IDL variable in the IDL session referred to by client. The address var points to a varinfo_t structure that contains information about the variable to be set. The "helper" functions can be used to build var. (See "The varinfo_t Structure" on page 24-9.) Any scalar or array variable type can be set. Variables can be set only in the main IDL program level.

Note that it is not possible to set the value of an IDL structure. To set values in an IDL structure, set the individual elements of the structure to scalar IDL variables, then use the send_idl_command function to create the structure in IDL.

It is not possible to set the value of IDL system variables directly. To set the value of an IDL system variable, first set the value of a regular IDL variable. The value of the regular variable can then be assigned to the system variable. For example:

set_idl_variable(client, &newvar); /* newvar describes the */
                                  /* IDL variable "NEW" */
send_idl_command(client, "!P.T = NEW");

Parameters

client

A pointer to the CLIENT structure that corresponds to the desired IDL session.

var

The address of the varinfo_t structure that contains information about the variable to be set.

Return Value

This function returns a status value that denotes the success or failure of this function as described below.

-1	Failure: bad arguments supplied (e.g., var is NULL).

 0	RPC mechanism failed (an error message is also printed).

 1	Success

set_rpc_verbosity

Calling Sequence

void set_rpc_verbosity(verbosity)

Description

This function controls the printing of error messages by RPC library routines. If verbosity is TRUE, error messages will be printed by the various RPC routines to explain what failed. If verbosity is FALSE, return codes continue to indicate success or failure, but no error messages are printed.

Parameters

verbosity

An int specifying TRUE or FALSE as explained above.

Return Value

None.

unregister_idl_client

Calling Sequence

void unregister_idl_client(CLIENT* client)

Description

Call this function to release the resources associated with the given CLIENT structure. The operating system automatically releases the resources associated with all CLIENT structures when your program exits. This function does not affect the IDL server.

Parameters

client

The pointer to the CLIENT structure to be unregistered.

Return Value

None.


The varinfo_t Structure

The varinfo_t structure is used to pass variables to and from the IDL server.

The varinfo_t structure is defined in the idldir/external/rpc/rpc_idl.h file. The structure is:

typedef struct _VARINFO {
char Name[MAXIDLEN+1];
IDL_VPTR Variable;
IDL_LONG Length;
} varinfo_t;

Variable Creation Functions

A number of functions are provided to help build varinfo_t structures. These functions are contained in the file idldir/external/rpc/helper.c.

The variable creation functions are described below. Unless otherwise noted, all of the following functions return TRUE if variable creation is successful and FALSE otherwise. When passing a varinfo_t structure pointer, if the Variable field is NULL, the variable creation functions attempt to allocate that field.

v_make_byte

Calling Sequence

int v_make_byte(varinfo_t* var_struct, char* var_name,
     unsigned value)

Description

Create an IDL byte variable with the given name and value.

v_make_complex

Calling Sequence

int v_make_complex(varinfo_t* var_struct, char* var_name,
     double real_value, double imag_value)

Description

Create an IDL complex variable.

v_make_dcomplex

Calling Sequence

int v_make_dcomplex(varinfo_t* var_struct, char* var_name,
     double real_value, double imag_value)

Description

Create an IDL double-precision complex variable.

v_make_double

Calling Sequence

int v_make_double(varinfo_t* var_struct, char* var_name,
     double value)

Description

Create an IDL double-precision, floating-point variable.

v_make_float

Calling Sequence

int v_make_float(varinfo_t* var_struct, char* var_name,
     double value)

Description

Create an IDL single-precision, floating-point variable.

v_make_int

Calling Sequence

int v_make_int(varinfo_t* var_struct, char* var_name, int value)

Description

Create an IDL (16-bit) integer variable.

v_make_long

Calling Sequence

int v_make_long(varinfo_t* var_struct, char* var_name,
     IDL_LONG value)

Description

Create an IDL long variable.

v_make_string

Calling Sequence

int v_make_string(varinfo_t* var_struct, char* name,
     char* value)

Description

Create an IDL string variable.

v_fill_array

Calling Sequence

int v_fill_array(varinfo_t* var, char* name, int type,
     int ndimension, IDL_LONG dims[], UCHAR* value,
     IDL_long length)

Description

Create an IDL array variable. The type argument should be one of the following values (defined in the file export.h):

IDL_TYP_BYTE, IDL_TYP_INT, IDL_TYP_LONG, IDL_TYP_FLOAT, IDL_TYP_DOUBLE, IDL_TYP_STRING, IDL_TYP_COMPLEX, IDL_TYP_DCOMPLEX

This function allocates var->Variable->value.arr.

If value is NULL then var->Variable->value.arr->data is allocated.

The dims[] argument should have at least ndimension valid elements.

If value is supplied but length is 0, var->Length is filled with the computed size of the array (in bytes) and value is assumed to point to at least that many bytes of memory. If value and length are supplied, length is assumed to be the size (in bytes) of the region of memory that value points to. (See "Notes on Variable Creation and Memory Management" on page 24-12.)


More Variable Manipulation Macros

The following macros can be used to get information from varinfo_t structures. Like the variable creation functions, these macros are defined in the file rpc_idl.h.

All of these macros accept a single argument v of varinfo_t type.

GetArrayData(v)

This macro returns a pointer to the array data described by the varinfo_t structure.

GetArrayDimensions(v)

This macro returns the dimensions of the array described by the varinfo_t structure. The dimensions are returned as long dimensions[].

GetArrayNumDims(v)

This macro returns the number of dimensions of the array.

GetVarByte(v)

This macro returns the value of a 1-byte, unsigned char variable.

GetVarComplex(v)

This macro returns the value (as a struct, not a pointer) of a complex variable.

GetVarDComplex(v)

This macro returns the value (as a struct, not a pointer) of a double-precision, complex variable.

GetVarDouble(v)

This macro returns the value of a double-precision, floating-point variable.

GetVarFloat(v)

This macro returns the value of a single-precision, floating point variable.

GetVarInt(v)

This macro returns the value of a 2-byte integer variable.

GetVarLong(v)

This macro returns the value of a 4-byte integer variable.

GetVarString(v)

This macro returns the value of a string variable (as a char*).

GetVarType(v)

This macro returns the type of the variable described by the varinfo_t structure. The type is returned as IDL_TYP_XXX as described under the documentation for the get_idl_variable function.

VarIsArray(v)

This macro returns non-zero if v is an array variable.


Notes on Variable Creation and Memory Management

This section contains miscellaneous notes about variable creation.

Freeing Resources

The variable creation functions (i.e., v_make_xxx) do not free resources associated with a variable before placing new information there. Your programs should free resources (if there are any) associated with the varinfo_t structure being passed.

To prevent memory leakage, memory associated with a variable is freed before new memory is allocated. You should make sure that the varinfo_t structure passed to the get_idl_variable function contains valid information or has been cleared (to zeroes) first. If an array of the same size, dimensions, and type is being read into the existing array variable, no allocation is performed and the same space is re-used. For example:

/* Assume that:
   X = FLTARR(1000, 1000)
   Y = FLTARR(1000, 1000)
   Z = LONARR(1000, 1000)	same size, different type
*/

bzero(&vinfo, sizeof(vinfo));
get_idl_variable(client, "X", &vinfo, 0); /* array allocated */
...
get_idl_variable(client, "Y", &vinfo, 0); /* memory re-used */
...
get_idl_variable(client, "Z", &vinfo, 0); /* array allocated */
free_idl_var(&vinfo);

The get_idl_variable function calls free_idl_var before doing any allocation. So, in the example above, we only needed to free Z. X and Y were freed when we re-used vinfo.

Creating a Statically-Allocated Array

It is possible to create a statically-allocated array for receiving information from the server without having the overhead of memory reallocation every time information is received.

If the Length field of the varinfo_t structure is not zero, it is assumed to be the size of the array data. The free_idl_var function will not do anything to a variable where length is non-zero. It is up to the programmer to do their own memory management if this is the case. Storing a scalar in a static variable (i.e., a variable that has a non-zero Length field) fails as does attempting to store an array that does not fit the statically-allocated array. For example:

/* X = FLTARR(10)     40 bytes of data (10*4)
   Y = LONARR(2,2,2)  32 bytes of data(2*2*2*4)
   Z = BYTARR(50)     50 bytes of data
   W = 12             scalar
*/

char       buf[40]
varinfo_t  v;
VARIABLE   var;
ARRAY      arr;

/* Build a static array. Fill in the minimum amount of */
/* information required.                              */

v.Variable    = &var;
v.Length      = 40;
var.type      = IDL_TYP_BYTE;
var.flags     = V_ARR;
var.value.arr = &arr;
arr.data      = buf;

get_idl_variable(client, "X", &v, 0);  /* ok */
get_idl_variable(client, "Y", &v, 0);  /* ok */
get_idl_variable(client, "Z", &v, 0);  /* fails — too big */
get_idl_variable(client, "W", &v, 0);  /* fails — scalar */

Allocating Space for Strings

All space for strings is assumed to be obtained via malloc(3). This fact is important only when receiving variables (using the  get_idl_variable function). For example, the following code fragment is valid:

v_make_string(&foo, "UGH", "blug");
set_idl_variable(client, &foo);

Here is an example of code that will crash your program:

v_make_string(&foo, "UGH", "blug");
set_idl_variable(me, &foo);
send_idl_command(me, "UGH='hello world'");
get_idl_variable(me, "UGH", &foo, 0);

In this case, the get_idl_variable function attempts to free the old resources before allocating new storage. Freeing the constant blug results in an error. You could achieve the desired result without an error by changing the first line to:

v_make_string(&foo, "UGH", strdup("blug"));


RPC Examples

A number of example files are included in the idldir/external/examples/rpc directory. A Makefile for these examples is also included. These short C programs demonstrate the use of the IDL RPC library.

Jump forward to Reporting Bugs

Jump backward to Scientific Data Formats


Alphabetical List of Routines

A  B C D E F G H I J K L M N O P Q R S T U V W X Z

A_CORRELATE

ABS

ACOS

ALOG

ALOG10

ANNOTATE

ARROW

ASIN

ASSOC

ATAN

AXIS

BAR_PLOT

BESELI

BESELJ

BESELY

BETA

BILINEAR

BIN_DATE

BINDGEN

BINOMIAL

BLK_CON

BOX_CURSOR

BREAKPOINT

BROYDEN

BYTARR

BYTE

BYTEORDER

BYTSCL

C_CORRELATE

CALDAT

CALENDAR

CALL_EXTERNAL

CALL_FUNCTION

CALL_PROCEDURE

CATCH

CD

CDF_ATTCREATE

CDF_ATTGET

CDF_ATTINQ

CDF_ATTNUM

CDF_ATTPUT

CDF_ATTRENAME

CDF_CLOSE

CDF_CONTROL

CDF_CREATE

CDF_DELETE

CDF_DOC

CDF_EPOCH

CDF_ERROR

CDF_EXISTS

CDF_INQUIRE

CDF_OPEN

CDF_VARCREATE

CDF_VARGET

CDF_VARGET1

CDF_VARINQ

CDF_VARNUM

CDF_VARPUT

CDF_VARRENAME

CEIL

CHEBYSHEV

CHECK_MATH

CHISQR_CVF

CHISQR_PDF

CHOLDC

CHOLSOL

CINDGEN

CIR_3PNT

CLOSE

COLOR_CONVERT

COLOR_QUAN

COMFIT

COMPLEX

COMPLEXARR

COMPLEXROUND

COND

CONGRID

CONJ

CONTOUR

CONVERT_COORD

CONVOL

COORD2TO3

CORRELATE

COS

COSH

CRAMER

CREATE_STRUCT

CREATE_VIEW

CROSSP

CT_LUMINANCE

CTI_TEST

CURSOR

CURVEFIT

CV_COORD

CW_ANIMATE

CW_ANIMATE_LOAD

CW_ANIMATE_RUN

CW_ANIMATE_GETP

CW_ARCBALL

CW_BGROUP

CW_CLR_INDEX

CW_COLORSEL

CW_DEFROI

CW_DICE

CW_FIELD

CW_FSLIDER

CW_ORIENT

CW_PDMENU

CW_RGBSLIDER

CW_TMPL

CW_ZOOM

DBLARR

DCINDGEN

DCOMPLEX

DCOMPLEXARR

DEFINE_KEY

DEFROI

DEFSYSV

DELETE_SYMBOL (VMS Only)

DELLOG (VMS Only)

DELVAR

DEMO_MODE

DERIV

DERIVSIG

DETERM

DEVICE

DFPMIN

DIGITAL_FILTER

DILATE

DINDGEN

DISP_TXT

DISSOLVE

DIST

DO_APPLE_SCRIPT

DOC_LIBRARY

DOUBLE

EFONT

EIGENVEC

ELMHES

EMPTY

EOF

ERASE

ERODE

ERRORF

ERRPLOT

EXECUTE

EXIT

EXP

EXPAND

EXPAND_PATH

EXPINT

EXTRAC

EXTRACT_SLICE

F_CVF

F_PDF

FACTORIAL

FFT

FILEPATH

FINDFILE

FINDGEN

FINITE

FIX

FLICK

FLOAT

FLOOR

FLOW3

FLTARR

FLUSH

FREE_LUN

FSTAT

FULSTR

FUNCT

FV_TEST

FX_ROOT

FZ_ROOTS

GAMMA

GAMMA_CT

GAUSS_CVF

GAUSS_PDF

GAUSS2DFIT

GAUSSFIT

GAUSSINT

GET_KBRD

GET_LUN

GET_SYMBOL (VMS Only)

GETENV

GETHELP

GRID3

GS_ITER

H_EQ_CT

H_EQ_INT

HANDLE_CREATE

HANDLE_FREE

HANDLE_INFO

HANDLE_MOVE

HANDLE_VALUE

HANNING

HDF_CLOSE

HDF_DELDD

HDF_DF24_ADDIMAGE

HDF_DF24_GETIMAGE

HDF_DF24_GETINFO

HDF_DF24_LASTREF

HDF_DF24_NIMAGES

HDF_DF24_READREF

HDF_DF24_RESTART

HDF_DFAN_ADDFDS

HDF_DFAN_ADDFID

HDF_DFAN_GETDESC

HDF_DFAN_GETFDS

HDF_DFAN_GETFID

HDF_DFAN_GETLABEL

HDF_DFAN_LABLIST

HDF_DFAN_LASTREF

HDF_DFAN_PUTDESC

HDF_DFAN_PUTLABEL

HDF_DFP_ADDPAL

HDF_DFP_GETPAL

HDF_DFP_LASTREF

HDF_DFP_NPALS

HDF_DFP_PUTPAL

HDF_DFP_READREF

HDF_DFP_RESTART

HDF_DFP_WRITEREF

HDF_DFR8_ADDIMAGE

HDF_DFR8_GETIMAGE

HDF_DFR8_GETINFO

HDF_DFR8_LASTREF

HDF_DFR8_NIMAGES

HDF_DFR8_PUTIMAGE

HDF_DFR8_READREF

HDF_DFR8_RESTART

HDF_DFR8_SETPALETTE

HDF_DFSD_ADDDATA

HDF_DFSD_DIMGET

HDF_DFSD_DIMSET

HDF_DFSD_ENDSLICE

HDF_DFSD_GETDATA

HDF_DFSD_GETINFO

HDF_DFSD_GETSLICE

HDF_DFSD_PUTSLICE

HDF_DFSD_READREF

HDF_DFSD_SETINFO

HDF_DFSD_STARTSLICE

HDF_DUPDD

HDF_EXISTS

HDF_ISHDF

HDF_NEWREF

HDF_NUMBER

HDF_OPEN

HDF_SD_ADDDATA

HDF_SD_ATTRFIND

HDF_SD_ATTRINFO

HDF_SD_ATTRSET

HDF_SD_CREATE

HDF_SD_DIMGET

HDF_SD_DIMGETID

HDF_SD_DIMSET

HDF_SD_END

HDF_SD_ENDACCESS

HDF_SD_FILEINFO

HDF_SD_GETDATA

HDF_SD_GETINFO

HDF_SD_ISCOORDVAR

HDF_SD_NAMETOINDEX

HDF_SD_REFTOINDEX

HDF_SD_SELECT

HDF_SD_SETEXTFILE

HDF_SD_SETINFO

HDF_SD_START

HDF_VD_ATTACH

HDF_VD_DEFINE

HDF_VD_DETACH

HDF_VD_FEXIST

HDF_VD_FIND

HDF_VD_GET

HDF_VD_GETID

HDF_VD_GETINFO

HDF_VD_GETNEXT

HDF_VD_INSERT

HDF_VD_ISVD

HDF_VD_ISVG

HDF_VD_LONE

HDF_VD_READ

HDF_VD_SEEK

HDF_VD_SETINFO

HDF_VD_WRITE

HDF_VG_ADDTR

HDF_VG_ATTACH

HDF_VG_DETACH

HDF_VG_GETID

HDF_VG_GETINFO

HDF_VG_GETNEXT

HDF_VG_GETTR

HDF_VG_GETTRS

HDF_VG_INQTR

HDF_VG_INSERT

HDF_VG_ISVD

HDF_VG_ISVG

HDF_VG_LONE

HDF_VG_NUMBER

HDF_VG_SETINFO

HELP

HILBERT

HIST_2D

HIST_EQUAL

HISTOGRAM

HLS

HQR

HSV

IBETA

IGAMMA

IMAGE_CONT

IMAGINARY

INDGEN

INT_2D

INT_3D

INT_TABULATED

INTARR

INTERPOL

INTERPOLATE

INVERT

IOCTL

ISHFT

JOURNAL

JULDAY

KEYWORD_SET

KRIG2D

KW_TEST

LABEL_DATE

LABEL_REGION

LADFIT

LEEFILT

LINBCG

LINDGEN

LINFIT

LINKIMAGE

LJLCT

LL_ARC_DISTANCE

LNGAMMA

LNP_TEST

LOADCT

LONARR

LONG

LU_COMPLEX

LUDC

LUMPROVE

LUSOL

M_CORRELATE

MACHAR

MAKE_ARRAY

MAP_CONTINENTS

MAP_GRID

MAP_IMAGE

MAP_PATCH

MAP_SET

MAX

MD_TEST

MEDIAN

MESH_OBJ

MESSAGE

MIN

MIN_CURVE_SURF

MK_HTML_HELP

MODIFYCT

MOMENT

MULTI

N_ELEMENTS

N_PARAMS

N_TAGS

NCDF_ATTCOPY

NCDF_ATTDEL

NCDF_ATTGET

NCDF_ATTINQ

NCDF_ATTNAME

NCDF_ATTPUT

NCDF_ATTRENAME

NCDF_CLOSE

NCDF_CONTROL

NCDF_CREATE

NCDF_DIMDEF

NCDF_DIMID

NCDF_DIMINQ

NCDF_DIMRENAME

NCDF_EXISTS

NCDF_INQUIRE

NCDF_OPEN

NCDF_VARDEF

NCDF_VARGET

NCDF_VARGET1

NCDF_VARID

NCDF_VARINQ

NCDF_VARPUT

NCDF_VARRENAME

NEWTON

NORM

ON_ERROR

ON_IOERROR

ONLINE_HELP

OPEN

OPLOT

OPLOTERR

P_CORRELATE

PICKFILE

PLOT

PLOT_3DBOX

PLOT_FIELD

PLOTERR

PLOTS

PNT_LINE

POINT_LUN

POLAR_CONTOUR

POLAR_SURFACE

POLY

POLY_2D

POLY_AREA

POLY_FIT

POLYFILL

POLYFILLV

POLYFITW

POLYSHADE

POLYWARP

POPD

POWELL

PRIMES

PRINT

PRINTD

PROFILE

PROFILES

PROJECT_VOL

PS_SHOW_FONTS

PSAFM

PSEUDO

PUSHD

QROMB

QROMO

QSIMP

R_CORRELATE

R_TEST

RANDOMN

RANDOMU

RANKS

RDPIX

READ

READ_BMP

READ_GIF

READ_INTERFILE

READ_JPEG

READ_PICT

READ_PPM

READ_SPR

READ_SRF

READ_SYLK

READ_WAVE

READ_X11_BITMAP

READ_XWD

READS

READU

REBIN

RECON3

REDUCE_COLORS

REFORM

REGRESS

REPLICATE

RESOLVE_ALL

RESOLVE_ROUTINE

RESTORE

REVERSE

REWIND (VMS Only)

RIEMANN

RK4

ROBERTS

ROT

ROTATE

ROUND

RS_TEST

RSTRPOS

S_TEST

SAVE

SCALE3

SCALE3D

SEARCH2D

SEARCH3D

SET_PLOT

SET_SHADING

SET_SYMBOL (VMS Only)

SETENV (Unix and Windows Only)

SETLOG (VMS Only)

SETUP_KEYS

SFIT

SHADE_SURF

SHADE_SURF_IRR

SHADE_VOLUME

SHIFT

SHOW3

SHOWFONT

SIN

SINDGEN

SINH

SIZE

SKIPF (VMS Only)

SLICER

SLIDE_IMAGE

SMOOTH

SOBEL

SORT

SPAWN

SPH_4PNT

SPH_SCAT

SPL_INIT

SPL_INTERP

SPLINE

SPLINE_P

SPRSAB

SPRSAX

SPRSIN

SQRT

STOP

STR_SEP

STRARR

STRCOMPRESS

STRETCH

STRING

STRLEN

STRLOWCASE

STRMESSAGE

STRMID

STRPOS

STRPUT

STRTRIM

STRUPCASE

SURFACE

SURFR

SVDC

SVDFIT

SVSOL

SWAP_ENDIAN

SYSTIME

T_CVF

T_PDF

T3D

TAG_NAMES

TAN

TANH

TAPRD (VMS Only)

TAPWRT (VMS Only)

TEK_COLOR

TEMPORARY

THIN

THREED

TIFF_DUMP

TIFF_READ

TIFF_WRITE

TIME_TEST

TM_TEST

TOTAL

TRANSPOSE

TRI_SURF

TRIANGULATE

TRIGRID

TRIQL

TRIRED

TRISOL

TRNLOG (VMS Only)

TS_COEF

TS_DIFF

TS_FCAST

TV

TVCRS

TVLCT

TVRD

TVSCL

UNIQ

USERSYM

VEL

VELOVECT

VERT_T3D

VOIGT

VORONOI

VOXEL_PROJ

WAIT

WARP_TRI

WDELETE

WEOF (VMS Only)

WF_DRAW

WHERE

WIDED

WIDGET_BASE

WIDGET_BUTTON

WIDGET_CONTROL

WIDGET_DRAW

WIDGET_DROPLIST

WIDGET_EVENT

WIDGET_INFO

WIDGET_LABEL

WIDGET_LIST

WIDGET_MESSAGE

WIDGET_SLIDER

WIDGET_TEXT

WINDOW

WRITE_BMP

WRITE_GIF

WRITE_JPEG

WRITE_NRIF

WRITE_PICT

WRITE_PPM

WRITE_SPR

WRITE_SRF

WRITE_SYLK

WRITE_WAVE

WRITEU

WSET

WSHOW

WTN

XBM_EDIT

XDISPLAYFILE

XFONT

XINTERANIMATE

XLOADCT

XMANAGER

XMNG_TMPL

XMTOOL

XPALETTE

XREGISTERED

XSQ_TEST

XSURFACE

XVAREDIT

XYOUTS

ZOOM

ZOOM_24


A Routines
A

All A B C D E F G H I J K L M N O P Q R S T U V W X Z

A_CORRELATE

ABS

ACOS

ALOG

ALOG10

ANNOTATE

ARROW

ASIN

ASSOC

ATAN

AXIS


B Routines
B

All A B C D E F G H I J K L M N O P Q R S T U V W X Z

BAR_PLOT

BESELI

BESELJ

BESELY

BETA

BILINEAR

BIN_DATE

BINDGEN

BINOMIAL

BLK_CON

BOX_CURSOR

BREAKPOINT

BROYDEN

BYTARR

BYTE

BYTEORDER

BYTSCL


C Routines
C

All A B C D E F G H I J K L M N O P Q R S T U V W X Z

C_CORRELATE

CALDAT

CALENDAR

CALL_EXTERNAL

CALL_FUNCTION

CALL_PROCEDURE

CATCH

CD

CDF_ATTCREATE

CDF_ATTGET

CDF_ATTINQ

CDF_ATTNUM

CDF_ATTPUT

CDF_ATTRENAME

CDF_CLOSE

CDF_CONTROL

CDF_CREATE

CDF_DELETE

CDF_DOC

CDF_EPOCH

CDF_ERROR

CDF_EXISTS

CDF_INQUIRE

CDF_OPEN

CDF_VARCREATE

CDF_VARGET

CDF_VARGET1

CDF_VARINQ

CDF_VARNUM

CDF_VARPUT

CDF_VARRENAME

CEIL

CHEBYSHEV

CHECK_MATH

CHISQR_CVF

CHISQR_PDF

CHOLDC

CHOLSOL

CINDGEN

CIR_3PNT

CLOSE

COLOR_CONVERT

COLOR_QUAN

COMFIT

COMPLEX

COMPLEXARR

COMPLEXROUND

COND

CONGRID

CONJ

CONTOUR

CONVERT_COORD

CONVOL

COORD2TO3

CORRELATE

COS

COSH

CRAMER

CREATE_STRUCT

CREATE_VIEW

CROSSP

CT_LUMINANCE

CTI_TEST

CURSOR

CURVEFIT

CV_COORD

CW_ANIMATE

CW_ANIMATE_LOAD

CW_ANIMATE_RUN

CW_ANIMATE_GETP

CW_ARCBALL

CW_BGROUP

CW_CLR_INDEX

CW_COLORSEL

CW_DEFROI

CW_DICE

CW_FIELD

CW_FSLIDER

CW_ORIENT

CW_PDMENU

CW_RGBSLIDER

CW_TMPL

CW_ZOOM


D Routines
D

All A B C D E F G H I J K L M N O P Q R S T U V W X Z

DBLARR

DCINDGEN

DCOMPLEX

DCOMPLEXARR

DEFINE_KEY

DEFROI

DEFSYSV

DELETE_SYMBOL (VMS Only)

DELLOG (VMS Only)

DELVAR

DEMO_MODE

DERIV

DERIVSIG

DETERM

DEVICE

DFPMIN

DIGITAL_FILTER

DILATE

DINDGEN

DISP_TXT

DISSOLVE

DIST

DO_APPLE_SCRIPT

DOC_LIBRARY

DOUBLE


E Routines
E

All A B C D E F G H I J K L M N O P Q R S T U V W X Z

EFONT

EIGENVEC

ELMHES

EMPTY

EOF

ERASE

ERODE

ERRORF

ERRPLOT

EXECUTE

EXIT

EXP

EXPAND

EXPAND_PATH

EXPINT

EXTRAC

EXTRACT_SLICE


F Routines
F

All A B C D E F G H I J K L M N O P Q R S T U V W X Z

F_CVF

F_PDF

FACTORIAL

FFT

FILEPATH

FINDFILE

FINDGEN

FINITE

FIX

FLICK

FLOAT

FLOOR

FLOW3

FLTARR

FLUSH

FREE_LUN

FSTAT

FULSTR

FUNCT

FV_TEST

FX_ROOT

FZ_ROOTS


G Routines
G

All A B C D E F G H I J K L M N O P Q R S T U V W X Z

GAMMA

GAMMA_CT

GAUSS_CVF

GAUSS_PDF

GAUSS2DFIT

GAUSSFIT

GAUSSINT

GET_KBRD

GET_LUN

GET_SYMBOL (VMS Only)

GETENV

GETHELP

GRID3

GS_ITER


H Routines
H

All A B C D E F G H I J K L M N O P Q R S T U V W X Z

H_EQ_CT

H_EQ_INT

HANDLE_CREATE

HANDLE_FREE

HANDLE_INFO

HANDLE_MOVE

HANDLE_VALUE

HANNING

HDF_CLOSE

HDF_DELDD

HDF_DF24_ADDIMAGE

HDF_DF24_GETIMAGE

HDF_DF24_GETINFO

HDF_DF24_LASTREF

HDF_DF24_NIMAGES

HDF_DF24_READREF

HDF_DF24_RESTART

HDF_DFAN_ADDFDS

HDF_DFAN_ADDFID

HDF_DFAN_GETDESC

HDF_DFAN_GETFDS

HDF_DFAN_GETFID

HDF_DFAN_GETLABEL

HDF_DFAN_LABLIST

HDF_DFAN_LASTREF

HDF_DFAN_PUTDESC

HDF_DFAN_PUTLABEL

HDF_DFP_ADDPAL

HDF_DFP_GETPAL

HDF_DFP_LASTREF

HDF_DFP_NPALS

HDF_DFP_PUTPAL

HDF_DFP_READREF

HDF_DFP_RESTART

HDF_DFP_WRITEREF

HDF_DFR8_ADDIMAGE

HDF_DFR8_GETIMAGE

HDF_DFR8_GETINFO

HDF_DFR8_LASTREF

HDF_DFR8_NIMAGES

HDF_DFR8_PUTIMAGE

HDF_DFR8_READREF

HDF_DFR8_RESTART

HDF_DFR8_SETPALETTE

HDF_DFSD_ADDDATA

HDF_DFSD_DIMGET

HDF_DFSD_DIMSET

HDF_DFSD_ENDSLICE

HDF_DFSD_GETDATA

HDF_DFSD_GETINFO

HDF_DFSD_GETSLICE

HDF_DFSD_PUTSLICE

HDF_DFSD_READREF

HDF_DFSD_SETINFO

HDF_DFSD_STARTSLICE

HDF_DUPDD

HDF_EXISTS

HDF_ISHDF

HDF_NEWREF

HDF_NUMBER

HDF_OPEN

HDF_SD_ADDDATA

HDF_SD_ATTRFIND

HDF_SD_ATTRINFO

HDF_SD_ATTRSET

HDF_SD_CREATE

HDF_SD_DIMGET

HDF_SD_DIMGETID

HDF_SD_DIMSET

HDF_SD_END

HDF_SD_ENDACCESS

HDF_SD_FILEINFO

HDF_SD_GETDATA

HDF_SD_GETINFO

HDF_SD_ISCOORDVAR

HDF_SD_NAMETOINDEX

HDF_SD_REFTOINDEX

HDF_SD_SELECT

HDF_SD_SETEXTFILE

HDF_SD_SETINFO

HDF_SD_START

HDF_VD_ATTACH

HDF_VD_DEFINE

HDF_VD_DETACH

HDF_VD_FEXIST

HDF_VD_FIND

HDF_VD_GET

HDF_VD_GETID

HDF_VD_GETINFO

HDF_VD_GETNEXT

HDF_VD_INSERT

HDF_VD_ISVD

HDF_VD_ISVG

HDF_VD_LONE

HDF_VD_READ

HDF_VD_SEEK

HDF_VD_SETINFO

HDF_VD_WRITE

HDF_VG_ADDTR

HDF_VG_ATTACH

HDF_VG_DETACH

HDF_VG_GETID

HDF_VG_GETINFO

HDF_VG_GETNEXT

HDF_VG_GETTR

HDF_VG_GETTRS

HDF_VG_INQTR

HDF_VG_INSERT

HDF_VG_ISVD

HDF_VG_ISVG

HDF_VG_LONE

HDF_VG_NUMBER

HDF_VG_SETINFO

HELP

HILBERT

HIST_2D

HIST_EQUAL

HISTOGRAM

HLS

HQR

HSV


I Routines
I

All A B C D E F G H I J K L M N O P Q R S T U V W X Z

IBETA

IGAMMA

IMAGE_CONT

IMAGINARY

INDGEN

INT_2D

INT_3D

INT_TABULATED

INTARR

INTERPOL

INTERPOLATE

INVERT

IOCTL

ISHFT


J Routines
J

All A B C D E F G H I J K L M N O P Q R S T U V W X Z

JOURNAL

JULDAY


K Routines
K

All A B C D E F G H I J K L M N O P Q R S T U V W X Z

KEYWORD_SET

KRIG2D

KW_TEST


L Routines
L

All A B C D E F G H I J K L M N O P Q R S T U V W X Z

LABEL_DATE

LABEL_REGION

LADFIT

LEEFILT

LINBCG

LINDGEN

LINFIT

LINKIMAGE

LJLCT

LL_ARC_DISTANCE

LNGAMMA

LNP_TEST

LOADCT

LONARR

LONG

LU_COMPLEX

LUDC

LUMPROVE

LUSOL


M Routines
M

All A B C D E F G H I J K L M N O P Q R S T U V W X Z

M_CORRELATE

MACHAR

MAKE_ARRAY

MAP_CONTINENTS

MAP_GRID

MAP_IMAGE

MAP_PATCH

MAP_SET

MAX

MD_TEST

MEDIAN

MESH_OBJ

MESSAGE

MIN

MIN_CURVE_SURF

MK_HTML_HELP

MODIFYCT

MOMENT

MULTI


N Routines
N

All A B C D E F G H I J K L M N O P Q R S T U V W X Z

N_ELEMENTS

N_PARAMS

N_TAGS

NCDF_ATTCOPY

NCDF_ATTDEL

NCDF_ATTGET

NCDF_ATTINQ

NCDF_ATTNAME

NCDF_ATTPUT

NCDF_ATTRENAME

NCDF_CLOSE

NCDF_CONTROL

NCDF_CREATE

NCDF_DIMDEF

NCDF_DIMID

NCDF_DIMINQ

NCDF_DIMRENAME

NCDF_EXISTS

NCDF_INQUIRE

NCDF_OPEN

NCDF_VARDEF

NCDF_VARGET

NCDF_VARGET1

NCDF_VARID

NCDF_VARINQ

NCDF_VARPUT

NCDF_VARRENAME

NEWTON

NORM


O Routines
O

All A B C D E F G H I J K L M N O P Q R S T U V W X Z

ON_ERROR

ON_IOERROR

ONLINE_HELP

OPEN

OPLOT

OPLOTERR


P Routines
P

All A B C D E F G H I J K L M N O P Q R S T U V W X Z

P_CORRELATE

PICKFILE

PLOT

PLOT_3DBOX

PLOT_FIELD

PLOTERR

PLOTS

PNT_LINE

POINT_LUN

POLAR_CONTOUR

POLAR_SURFACE

POLY

POLY_2D

POLY_AREA

POLY_FIT

POLYFILL

POLYFILLV

POLYFITW

POLYSHADE

POLYWARP

POPD

POWELL

PRIMES

PRINT

PRINTD

PROFILE

PROFILES

PROJECT_VOL

PS_SHOW_FONTS

PSAFM

PSEUDO

PUSHD


Q Routines
Q

All A B C D E F G H I J K L M N O P Q R S T U V W X Z

QROMB

QROMO

QSIMP


R Routines
R

All A B C D E F G H I J K L M N O P Q R S T U V W X Z

R_CORRELATE

R_TEST

RANDOMN

RANDOMU

RANKS

RDPIX

READ

READ_BMP

READ_GIF

READ_INTERFILE

READ_JPEG

READ_PICT

READ_PPM

READ_SPR

READ_SRF

READ_SYLK

READ_WAVE

READ_X11_BITMAP

READ_XWD

READS

READU

REBIN

RECON3

REDUCE_COLORS

REFORM

REGRESS

REPLICATE

RESOLVE_ALL

RESOLVE_ROUTINE

RESTORE

REVERSE

REWIND (VMS Only)

RIEMANN

RK4

ROBERTS

ROT

ROTATE

ROUND

RS_TEST

RSTRPOS


S Routines
S

All A B C D E F G H I J K L M N O P Q R S T U V W X Z

S_TEST

SAVE

SCALE3

SCALE3D

SEARCH2D

SEARCH3D

SET_PLOT

SET_SHADING

SET_SYMBOL (VMS Only)

SETENV (Unix and Windows Only)

SETLOG (VMS Only)

SETUP_KEYS

SFIT

SHADE_SURF

SHADE_SURF_IRR

SHADE_VOLUME

SHIFT

SHOW3

SHOWFONT

SIN

SINDGEN

SINH

SIZE

SKIPF (VMS Only)

SLICER

SLIDE_IMAGE

SMOOTH

SOBEL

SORT

SPAWN

SPH_4PNT

SPH_SCAT

SPL_INIT

SPL_INTERP

SPLINE

SPLINE_P

SPRSAB

SPRSAX

SPRSIN

SQRT

STOP

STR_SEP

STRARR

STRCOMPRESS

STRETCH

STRING

STRLEN

STRLOWCASE

STRMESSAGE

STRMID

STRPOS

STRPUT

STRTRIM

STRUPCASE

SURFACE

SURFR

SVDC

SVDFIT

SVSOL

SWAP_ENDIAN

SYSTIME


T Routines
T

All A B C D E F G H I J K L M N O P Q R S T U V W X Z

T_CVF

T_PDF

T3D

TAG_NAMES

TAN

TANH

TAPRD (VMS Only)

TAPWRT (VMS Only)

TEK_COLOR

TEMPORARY

THIN

THREED

TIFF_DUMP

TIFF_READ

TIFF_WRITE

TIME_TEST

TM_TEST

TOTAL

TRANSPOSE

TRI_SURF

TRIANGULATE

TRIGRID

TRIQL

TRIRED

TRISOL

TRNLOG (VMS Only)

TS_COEF

TS_DIFF

TS_FCAST

TV

TVCRS

TVLCT

TVRD

TVSCL


U Routines
U

All A B C D E F G H I J K L M N O P Q R S T U V W X Z

UNIQ

USERSYM


V Routines
V

All A B C D E F G H I J K L M N O P Q R S T U V W X Z

VEL

VELOVECT

VERT_T3D

VOIGT

VORONOI

VOXEL_PROJ


W Routines
W

All A B C D E F G H I J K L M N O P Q R S T U V W X Z

WAIT

WARP_TRI

WDELETE

WEOF (VMS Only)

WF_DRAW

WHERE

WIDED

WIDGET_BASE

WIDGET_BUTTON

WIDGET_CONTROL

WIDGET_DRAW

WIDGET_DROPLIST

WIDGET_EVENT

WIDGET_INFO

WIDGET_LABEL

WIDGET_LIST

WIDGET_MESSAGE

WIDGET_SLIDER

WIDGET_TEXT

WINDOW

WRITE_BMP

WRITE_GIF

WRITE_JPEG

WRITE_NRIF

WRITE_PICT

WRITE_PPM

WRITE_SPR

WRITE_SRF

WRITE_SYLK

WRITE_WAVE

WRITEU

WSET

WSHOW

WTN


X Routines
X

All A B C D E F G H I J K L M N O P Q R S T U V W X Z

XBM_EDIT

XDISPLAYFILE

XFONT

XINTERANIMATE

XLOADCT

XMANAGER

XMNG_TMPL

XMTOOL

XPALETTE

XREGISTERED

XSQ_TEST

XSURFACE

XVAREDIT

XYOUTS


Z Routines
Z

All A B C D E F G H I J K L M N O P Q R S T U V W X Z

ZOOM

ZOOM_24


Routines by Application
List of Routines by Application

Animation Routines

Array Creation Routines

Array and Image Processing Routines

Font Manipulation Routines

General Graphics Routines

Graphics, Color Table Manipulation Routines

Help Routines

Image Display Routines

Input/Output Routines

Mapping Routines

Mathematics Routines

Operating System Access Routines

Plotting Routines, Two-Dimensional and General

Plotting Routines, Multi-Dimensional

Programming and IDL Control Routines

Saving and Restoring a Session Routines

String Processing Routines

Type Conversion Routines

Widget Routines

Widget Routines, Compound

Window Routines


Language Features Quick Reference

Executive Commands

Special Characters

Statements

Operators

Subscripts

System Variables

Graphics Devices

Graphics Keywords


Executive Commands Quick Reference
Executive Commands

.COMPILE [File1, ..., Filen]	Compile programs without running.

.CONTINUE	Continue execution of a stopped program.

.GO	Execute previously-compiled main program.

.OUT	Continue execution until the current routine returns.

.RNEW [File1, ..., Filen]	Erase main program variables and then .RUN.

.RUN [File1, ..., Filen]	Compile and execute IDl commands from files or keyboard.

.SIZE Code_Size, Data_Size	Resize the compiler's code and data areas.

. SKIP [n]	Skip over the next statement (or n statements) and single step.

.STEP [n] or .S [n]	Execute one or n statements from the current position.

.STEPOVER [n] or .SO [n]	Execute a single statement if the statement doesn't call a routine.

.TRACE	Similar to .CONTINUE, but displays each line of code before execution.


Special Characters Quick Reference
Special Characters

Exclamation Point (!)	First character of system variable names.

Apostrophe (')	Delimit strings or indicate octal or hex.

Semicolon (;)	First character of comment field.

Dollar Sign ($)	Continuation character (at end of line) or spawn operating system command (at start of line).

Quotation Mark (")	String delimiter or indicate octal number.

Period (.)	First character of executive commands. Also indicates floating-point numbers.

Ampersand (&)	Separates multiple commands on a single line.

Colon (:)	Ends label identifiers. Also separates start and end subscript ranges.

Asterisk (*)	Designates an ending subscript range equal to the size of the dimension. Also the multiplication operator.

At Sign (@)	Execute batch file. Also include character.

Question Mark (?)	Invoke online help facility.


Statements Quick Reference
Statements

variable = expression	The Assignment Statement

BEGIN	Blocks

    statements

END

CASE expression OF	CASE Statement

    expression: statement

...

    expression: statement

    ENDCASE

COMMON Name, var1, ..., varn	Common Blocks

FOR var = init, limit, incr DO state	FOR Statement

FUNCTION Name, arg1, ..., argn	Function Definition Statement

GOTO, label	GOTO Statement

IF expr THEN statement	IF Statement

IF expr THEN state1 ELSE state2

PROCEDURE_NAME, arg1, ..., argn	Procedure Call Statement

PRO Name, arg1, ..., argn	Procedure Definition Statement

REPEAT statement UNTIL expr	REPEAT Statement

WHILE expression DO statement	WHILE Statement


Operators Quick Reference
Operators

()	Parentheses group expressions, enclose subscripts, etc.

=	Assignment

+	Addition

-	Subtraction and Negation

*	Multiplication

/	Division

^	Exponentiation

MOD	Modulo

<	The Minimum Operator

>	The Maximum Operator

# and ##	Matrix Multiplication

[ ]	Array Concatenation

Boolean Operators

AND	Boolean AND.

NOT	Boolean complement.

OR	Boolean OR.

XOR	Boolean exclusive OR.

Relational Operators

EQ	Equal to.

GE	Greater than or equal to.

GT	Greater than.

LE	Less than or equal to.

LT	Less than.

NE	Not equal to.


Subscripts Quick Reference
Subscripts

Vector(i)	The ith element of a vector.

Array(i, j)	The element stored at the ith column, jth row of an array.

Vector(i:j)	Elements i through j of a vector.

Vector(i:*)	Elements from i through the end of a vector.

Array(i, *)	The ith column of a two-dimensional array.

Array(*, j)	The jth row of a two-dimensional array.

Array(i:j, m:n)	The subarray of columns i though j, rows m through n.

Array(Array2)	The elements of Array whose subscripts are the values of Array2.

(Array_Expression)(i)	The ith element of an array-valued expression.


Animation Routines

CW_ANIMATE	Compound widget for animation.

CW_ANIMATE_LOAD	Load images into CW_ANIMATE.

CW_ANIMATE_GETP	Get pixmap IDs used by CW_ANIMATE.

CW_ANIMATE_RUN	Display images loaded into CW_ANIMATE.

FLICK	Flicker display between two images.

XINTERANIMATE	Display animations. Easy interface to CW_ANIMATE.


Array Creation Routines

BINDGEN	Return a byte array with each element set to its subscript.

BYTARR	Create a byte vector or array.

CINDGEN	Return a complex array with each element set to its subscript.

COMPLEXARR	Return a complex, single-precision, floating-point vector or array.

DBLARR	Return a double-precision array.

DCINDGEN	Return a double-precision, complex array with each element set to its subscript.

DCOMPLEXARR	Return a double-precision, complex vector or array.

DINDGEN	Return a double-precision array with each element set to its subscript.

FINDGEN	Return a floating-point array with each element set to its subscript.

FLTARR	Return a floating-point vector or array.

INDGEN	Return an integer array with each element set to its subscript.

INTARR	Return an integer vector or array.

LINDGEN	Return a longword integer array with each element set to its subscript.

LONARR	Return a longword integer vector or array.

MAKE_ARRAY	General purpose array creation.

REPLICATE	Form array of given dimensions filled with a value.

SINDGEN	Return a string array with each element set to its subscript.

STRARR	Return a string vector or array.


Array and Image Processing Routines

CONGRID	Resample image to any dimensions.

DEFROI	Define graphical region-of-interest.

DIGITAL_FILTER	Calculate coefficients of a non-recursive digital filter.

DILATE	Morphologic dilation operator.

ERODE	Morphologic erosion operator.

EXPAND	Magnify an image.

EXTRAC	Return subarray of input array. Note that array operators (e.g., * and :) should usually be used instead.

HILBERT	Construct a Hilbert matrix.

HIST_EQUAL	Histogram equalize an image.

HISTOGRAM	Compute density function of array.

INTERPOL	Linear interpolation for vectors.

INTERPOLATE	Return an array of interpolates.

INVERT	Compute inverse of a square array.

KRIG2D	Interpolate points using kriging.

LABEL_REGION	Label regions (blobs) of a bi-level image.

LEEFILT	Lee filter for images.

MAX	Return the maximum element of an array.

MEDIAN	Median function and filter.

MIN	Return the minimum element of an array.

POLY_2D	Polynomial image warping.

POLYWARP	Determine coefficients for polynomial image warping.

RDPIX	Interactively read and display image pixel values.

REBIN	Resample array by integer multiples.

REFORM	Change array dimensions without changing contents.

REVERSE	Reverse vectors or arrays.

ROBERTS	Roberts edge enhancement.

ROT	Rotate array by any amount.

ROTATE	Rotate array by multiples of 90 degrees and/or transpose.

SEARCH2D	Find "objects" or regions of similar data within an image.

SEARCH3D	Find "objects" or regions of similar data within a volume.

SHIFT	Shift array elements.

SIZE	Return array size and type information.

SMOOTH	Smooth with a boxcar average.

SOBEL	Sobel edge enhancement.

SORT	Sort array contents and return vector of indices.

THIN	Obtain the "skeleton" of a bi-level image.

TOTAL	Sum array elements.

TRANSPOSE	Transpose array.

UNIQ	Return subscripts of unique array elements.

WARP_TRI	Warp an image using control points.

WHERE	Return subscripts of non-zero array elements.

XVAREDIT	Widget-based editor for arrays.


Font Manipulation Routines

EFONT	Interactive vector font editor and display tool.

PS_SHOW_FONTS	Display all PostScript fonts that IDL knows about.

PSAFM	Convert Adobe Font Metric files to IDL format.

SHOWFONT	Display an IDL vector font.

XFONT	Modal widget application for selecting and viewing X Windows fonts.


General Graphics Routines

ANNOTATE	Interactive drawing and annotation tool.

ARROW	Draw a line with an arrow head.

BOX_CURSOR	Variable size box cursor for windows.

CURSOR	Read interactive graphics cursor.

DEVICE	Access to device-specific functions.

DISP_TXT	Display text strings with many font and style options.

EMPTY	Empty the graphics output buffer.

ERASE	Erase screen of current graphics device.

SET_PLOT	Specify IDL graphics device.

XYOUTS	Display text on selected graphics device.


Graphics, Color Table Manipulation Routines

COLOR_CONVERT	Convert color triples to and from RGB, HLS, HSV.

COLOR_QUAN	Convert true-color (24-bit) images to pseudo-color (8-bit).

CT_LUMINANCE	Calculate luminance of color in COLORS common block.

GAMMA_CT	Gamma correction for color tables.

H_EQ_CT	Histogram equalize the color tables for an image or region of the display.

H_EQ_INT	Interactively histogram-equalize the color tables of an image or region of the display.

HLS	Hue, Lightness, Saturation color system color tables.

HSV	Hue, Saturation, Value color system color tables.

LJLCT	Load standard color tables for DEC LJ250 printer.

LOADCT	Load built-in IDL color tables.

MODIFYCT	Save modified color tables in the IDL color table file.

MULTI	Replicate current color table to enhance contrast.

PSEUDO	Lightness, Hue, Brightness color system color tables.

REDUCE_COLORS	Reduce number of colors used by an image by eliminating unused pixel values.

STRETCH	Linear color table contrast enhancement.

TEK_COLOR	Load special color table based on Tektronix printer.

TVLCT	Load display color tables.

XLOADCT	Interactively select and adjust color tables.

XPALETTE	Interactively create and edit color tables.


Help Routines

?	Display IDL's Online Help System.

DOC_LIBRARY	Retrieve text documentation headers from user routines.

GETHELP	Return output from HELP as a string.

HELP	Print information about current IDL session.

MK_HTML_HELP	Convert text documentation headers to HTML hypertext files.

ONLINE_HELP	Invoke online help viewer from programs.


Image Display Routines

DISSOLVE	Digital "dissolve" effect for images.

SLIDE_IMAGE	Create scrolling graphics window.

TV	Display an image.

TVCRS	Manipulate image display cursor.

TVLCT	Load display color tables.

TVRD	Read image from window into variable.

TVSCL	Scale and display an image.

ZOOM	Zoom portions of the display.

ZOOM_24	ZOOM for true-color (24-bit) display.


Input/Output Routines

ASSOC	Associate a file with an array structure.

CDF Routines	Jump to list of CDF routines.

CLOSE	Close files.

EOF	Test for end-of-file.

FILEPATH	Return full filepath to use in opening a file in the IDL distribution.

FINDFILE	Find files matching a given specification.

FLUSH	Flush file unit buffers.

FREE_LUN	Deallocate file units.

FSTAT	Return information about a file unit.

GET_KBRD	Get one input character.

GET_LUN	Reserve a logical unit number (file unit).

HDF Routines	Jump to list of HDF routines.

IOCTL	Perform special functions on Unix files.

NetCDF Routines	Jump to list of NetCDF routines.

OPEN	Open files for reading, updating, or writing.

POINT_LUN	Obtain or set position of the file pointer.

PRINT	Write formatted output to screen or file.

READ	Read formatted input form keyboard or file.

READ_BMP	Read Microsoft Windows Bitmap files.

READ_GIF	Read GIF files.

READ_INTERFILE	Read Interfile (version 3.3) files.

READ_JPEG	Read JPEG files.

READ_PICT	Read Macintosh PICT bitmap files.

READ_PPM	Read PBMPLUS files.

READ_SPR	Read a row-indexed sparse matrix from a file.

READ_SRF	Read Sun Raster Format files.

READ_SYLK	Read Symbolic Link format spreadsheet files.

READ_WAVE	Read Wavefront Advanced Visualizer files.

READ_X11_BITMAP	Read X11 bitmap files.

READ_XWD	Read X Windows Dump files.

READS	Read formatted input from a string variable.

READU	Read unformatted input from a file.

REWIND (VMS Only)	Rewind magnetic tape.

SKIPF (VMS Only)	Skip record or files on tape.

TAPRD (VMS Only)	Read next record from tape.

TAPWRT (VMS Only)	Write data to tape.

TIFF_DUMP	TIFF debugging utility.

TIFF_READ	Read TIFF files.

TIFF_WRITE	Write TIFF files.

WEOF (VMS Only)	Write end-of-file mark to tape.

WRITE_BMP	Write Microsoft Window Bitmap files.

WRITE_GIF	Write GIF files.

WRITE_JPEG	Write JPEG files.

WRITE_NRIF	Write NCAR Raster Interchange Format files.

WRITE_PICT	Write Macintosh PICT bitmap files.

WRITE_PPM	Write PBMPLUS files.

WRITE_SPR	Write a row-indexed sparse matrix to a file.

WRITE_SRF	Write Sun Raster files.

WRITE_SYLK	Write Symbolic Link spreadsheet files.

WRITE_WAVE	Write Wavefront Advanced Visualizer files.

WRITEU	Write unformatted output to a file.


CDF Routines

CDF_ATTCREATE	Create new variable for CDF file.

CDF_ATTGET	Read an attribute from a CDF.

CDF_ATTINQ	Read information about an attribute.

CDF_ATTNUM	Return an attribute's number.

CDF_ATTPUT	Write an attribute entry to a CDF.

CDF_ATTRENAME	Rename an existing attribute.

CDF_CLOSE	Close a CDF file.

CDF_CONTROL	Obtain or set information for a CDF.

CDF_CREATE	Create a new CDF file.

CDF_DELETE	Delete a CDF file.

CDF_DOC	Retrieve documentation about a CDF.

CDF_EPOCH	Compute or break down epoch values.

CDF_ERROR	Return a string explaining a status code.

CDF_EXISTS	Returns True if CDF interface is available.

CDF_INQUIRE	Return global information about a CDF.

CDF_OPEN	Open an existing CDF file.

CDF_VARCREATE	Create a new CDF variable.

CDF_VARGET	Read multiple values from a CDF variable.

CDF_VARGET1	Read one value from a CDF variable.

CDF_VARINQ	Return a structure with information about a variable.

CDF_VARNUM	Return variable number of variable name.

CDF_VARPUT	Write a value to a variable.

CDF_VARRENAME	Rename an existing variable.


HDF Routines

HDF_CLOSE	Close an HDF file.

HDF_DELDD	Delete a tag or reference from an HDF file.

HDF_DF24_ADDIMAGE	Write a 24-bit image to an HDF file.

HDF_DF24_GETIMAGE	Read a 24-bit image from an HDF file.

HDF_DF24_GETINFO	Retrieve information about current 24-bit image.

HDF_DF24_LASTREF	Return reference number of most recent 24-bit image.

HDF_DF24_NIMAGES	Return number of 24-bit images in an HDF.

HDF_DF24_READREF	Set the reference number of the next 24-bit image to be read.

HDF_DF24_RESTART	Reset 24-bit image reading to the first image.

HDF_DFAN_ADDFDS	Add a file description to an HDF.

HDF_DFAN_ADDFID	Add an HDF file annotation.

HDF_DFAN_GETDESC	Read description for a tag and reference number.

HDF_DFAN_GETFDS	Retrieve the next available file description.

HDF_DFAN_GETFID	Read the next available file annotation.

HDF_DFAN_GETLABEL	Read the label for a tag reference number.

HDF_DFAN_LABLIST	Retrieve reference numbers and labels for a tag.

HDF_DFAN_LASTREF	Return the reference number of the most recently read or written annotation.

HDF_DFAN_PUTDESC	Write a description for an HDF tag and reference number.

HDF_DFAN_PUTLABEL	Write a label for a tag and reference number.

HDF_DFP_ADDPAL	Append a palette to an HDF file.

HDF_DFP_GETPAL	Read the next available palette.

HDF_DFP_LASTREF	Return the reference number of the most recently read or written palette.

HDF_DFP_NPALS	Return the number of palettes in an HDF file.

HDF_DFP_PUTPAL	Write a palette to an HDF file.

HDF_DFP_READREF	Set the reference number for the next palette to be read.

HDF_DFP_RESTART	Reset reading to the first palette in the HDF file.

HDF_DFP_WRITEREF	Set the reference number for the next palette to be written.

HDF_DFR8_ADDIMAGE	Append an 8-bit image to an HDF file.

HDF_DFR8_GETIMAGE	Read an image from an HDF file.

HDF_DFR8_GETINFO	Retrieve information about the current 8-bit image.

HDF_DFR8_LASTREF	Return the reference nubmer of the most recently read or written 8-bit image.

HDF_DFR8_NIMAGES	Return the nubmer of 8-bit images in an HDF file.

HDF_DFR8_PUTIMAGE	Write an 8-bit image to an HDF file.

HDF_DFR8_READREF	Set the reference number of the next image to be read.

HDF_DFR8_RESTART	Reset 8-bit image reading to the first image in the HDF file.

HDF_DFR8_SETPALETTE	Set the default palette for subsequent images.

HDF_DFSD_ADDDATA	Write data to an HDF file.

HDF_DFSD_DIMGET	Retrieve information about a dimension.

HDF_DFSD_DIMSET	Set dimension information.

HDF_DFSD_ENDSLICE	Finish writing a data slice.

HDF_DFSD_GETDATA	Read data from an HDF file.

HDF_DFSD_GETINFO	Retrieve information about the current HDF file.

HDF_DFSD_GETSLICE	Read a slice from an HDF.

HDF_DFSD_PUTSLICE	Write a data slice to an HDF.

HDF_DFSD_READREF	Set the reference number of the next HDF file to be read.

HDF_DFSD_SETINFO	Set dimension and data type information for an HDF file.

HDF_DFSD_STARTSLICE	Prepare file for writing a data slice.

HDF_DUPDD	Generate new references to existing data in an HDF.

HDF_EXISTS	Returns True if HDF interface is available.

HDF_ISHDF	Returns True if the file is an HDF file.

HDF_NEWREF	Return the next available reference number for an HDF.

HDF_NUMBER	Return the number of tags or references.

HDF_OPEN	Open or create an HDF file.

HDF_SD_ADDDATA	Write a hyperslab of values to an SD dataset.

HDF_SD_ATTRFIND	Locate the index of an attribute given its name.

HDF_SD_ATTRINFO	Retrieve information about an SD attribute.

HDF_SD_ATTRSET	Write attributes to an open HDF SD dataset.

HDF_SD_CREATE	Create and define a Scientific Dataset.

HDF_SD_DIMGET	Retrieve SD dimension information.

HDF_SD_DIMGETID	Retrieve a dimension ID given an SDS_ID and dimension number.

HDF_SD_DIMSET	Set the scale and data strings for an SD dimension.

HDF_SD_END	Close the SD interface to an HDF file.

HDF_SD_ENDACCESS	Close an SD dataset interface.

HDF_SD_FILEINFO	Retrieve number of datasets and global attributes.

HDF_SD_GETDATA	Retrieve a hyperslab of values from an SD dataset.

HDF_SD_GETINFO	Retrieve information about an SD dataset.

HDF_SD_ISCOORDVAR	Returns True if an SDS_ID represents a NetCDF coordinate variable.

HDF_SD_NAMETOINDEX	Retrieve an SD dataset index given its name and ID.

HDF_SD_REFTOINDEX	Retrieve an SD dataset index given its reference number and ID.

HDF_SD_SELECT	Return an SD dataset ID given the current interface ID.

HDF_SD_SETEXTFILE	Move data from a dataset into an external file.

HDF_SD_SETINFO	Set information about an SD dataset.

HDF_SD_START	Open or create an HDF file and initialize the SD interface.

HDF_VD_ATTACH	Access a VData in an HDF file.

HDF_VD_DEFINE	Add a new field for a VData in an HDF file.

HDF_VD_DETACH	Close access to a VData.

HDF_VD_FEXIST	Returns True if the specified field exists.

HDF_VD_FIND	Retrieves the reference number of a VData given its name.

HDF_VD_GET	Retrieve general information about a VData.

HDF_VD_GETID	Retrieve the reference number for the next VData.

HDF_VD_GETINFO	Retrieve information about fields in a VData.

HDF_VD_GETNEXT	Return the reference nubmer of the next object in a VData.

HDF_VD_INSERT	Add a VData to the contents of a VGroup.

HDF_VD_ISVD	Returns True if the specified object is a VData.

HDF_VD_ISVG	Returns True if the specified object is a VGroup.

HDF_VD_LONE	Return all VDatas that are not found in another VData.

HDF_VD_READ	Read data from a VData.

HDF_VD_SEEK	Move the read pointer within a VData to specified record number.

HDF_VD_SETINFO	Set general information about a VData.

HDF_VD_WRITE	Write data into a VData.

HDF_VG_ADDTR	Add a tag and reference to a VGroup.

HDF_VG_ATTACH	Open a VGroup in and HDF file for reading or writing.

HDF_VG_DETACH	Close access to a VGroup.

HDF_VG_GETID	Return the VGroup ID of the next VGroup.

HDF_VG_GETINFO	Retrieve general information about a VGroup.

HDF_VG_GETNEXT	Return the reference number of the next object in a VGroup.

HDF_VG_GETTR	Return a tag/reference pair within a VGroup.

HDF_VG_GETTRS	Return all tag/reference pairs within a VGroup.

HDF_VG_INQTR	Returns True if a tag/reference pair belongs to the specified VGroup.

HDF_VG_INSERT	Add a VGroup to the contents of a VGroup.

HDF_VG_ISVD	Returns True if the specified object is a VData.

HDF_VG_ISVG	Returns True if the specified object is a VGroup.

HDF_VG_LONE	Retrieve the IDs of all VGroups that are not contained in another VGroup.

HDF_VG_NUMBER	Retrieve the number of objects in a VGroup.

HDF_VG_SETINFO	Set the name and class of a VGroup.


NetCDF Routines

NCDF_ATTCOPY	Copy an attribute from one netCDF file to another.

NCDF_ATTDEL	Delete an attribute from a netCDF file.

NCDF_ATTGET	Retrieve the value of an attribute in a netCDF file.

NCDF_ATTINQ	Retrieve information about a netCDF attribute.

NCDF_ATTNAME	Retrieve the name of an attribute given its ID.

NCDF_ATTPUT	Create an attribute in a netCDF file.

NCDF_ATTRENAME	Rename a netCDF attribute.

NCDF_CLOSE	Close a netCDF file.

NCDF_CONTROL	Perform miscellaneous netCDF operations.

NCDF_CREATE	Create a new netCDF file.

NCDF_DIMDEF	Define a netCDF dimension.

NCDF_DIMID	Retrieve the ID of a netCDF dimension.

NCDF_DIMINQ	Retrieve the name and size of a netCDF dimension.

NCDF_DIMRENAME	Rename an existing netCDF dimension.

NCDF_EXISTS	Returns True if the netCDF interface is available.

NCDF_INQUIRE	Retrieve information about a netCDF file.

NCDF_OPEN	Open a netCDF file.

NCDF_VARDEF	Add a new variable to a netCDF file.

NCDF_VARGET	Read a hyperslab of values from a netCDF variable.

NCDF_VARGET1	Retrieve one element from a netCDF variable.

NCDF_VARID	Retrieve the ID of a netCDF variable.

NCDF_VARINQ	Return information about a netCDF variable.

NCDF_VARPUT	Write a hyperslab of values to a netCDF variable.

NCDF_VARRENAME	Rename a netCDF variable.


Mapping Routines

MAP_CONTINENTS	Draw continent boundaries, countries, rivers, etc. over map projection established by MAP_SET.

MAP_GRID	Draw parallels and meridians over map projection.

MAP_IMAGE	Return an image warped to the current map projection.

MAP_PATCH	Return an image warped to the current map projection.

MAP_SET	Establish map projection type and limits.


Mathematics Routines

Alphabetical List of Mathematics Routines

Correlation Analysis Routines

Curve and Surface Fitting Routines

Differential Equations Routines

Eigenvalue and Eigenvector Routines

Gridding and Interpolation Routines

Hypothesis Testing Routines

Integration Routines

Linear Systems Routines

Miscellaneous Math Routines

Multivariate Analysis Routines

Nonlinear Equations Routines

Optimization Routines

Probability Routines

Sparse Array Routines

Special Math Functions

Statistical Tools Routines

Time-Series Analysis Routines

Transcendental Functions

Transforms Routines


Correlation Analysis Routines

A_CORRELATE	Compute autocorrelation.

C_CORRELATE	Compute cross correlation.

CORRELATE	Compute linear Pearson correlation.

M_CORRELATE	Compute multiple correlation.

P_CORRELATE	Compute partial correlation.

R_CORRELATE	Compute rank correlation.


Curve and Surface Fitting Routines

COMFIT	Fit using gradient-expansion least-squares method.

CURVEFIT	Fit using non-linear least squares method.

GAUSS2DFIT	Fit a 2D elliptical gaussian to rectilinearly-gridded data.

GAUSSFIT	Fit sum of a gaussian and a quadratic.

LADFIT	Fit using least absolute deviation method.

LINFIT	Fit using Chi-square error statistic.

MIN_CURVE_SURF	Interpolate points with a minimum curvature splice surface. Useful with CONTOUR.

POLY_FIT	Fit using polynomial least squares method.

POLYFITW	Fit using weighted polynomial least squares method.

REGRESS	Perform multiple linear regression fit.

SFIT	Perform polynomial fit to a surface.

SVDFIT	Least squares fit using SVD method.


Differential Equations Routines

DERIV	Differentiation using 3-point Lagrangian interpolation.

DERIVSIG	Compute standard deviation of a derivative as found by DERIV.

RK4	Solve differential equations using fourth-order Runge-Kutta method.


Eigenvalue and Eigenvector Routines

EIGENVEC	Compute eigenvectors.

ELMHES	Reduce nonsymmetric array to upper Hessenberg form.

HQR	Return eigenvalues of an upper Hessenberg array.

TRIQL	Compute eigenvectors and eigenvalues of a tridiagonal array.

TRIRED	Reduce a real, symmetric array to tridiagonal form.


Gridding and Interpolation Routines

BILINEAR	Bilinear interpolation.

GRID3	Fit a smooth function to set of 3D scattered nodes.

INTERPOL	Linear interpolation for vectors.

INTERPOLATE	Return an array of interpolates.

KRIG2D	Interpolate points using kriging.

MIN_CURVE_SURF	Interpolate points with a minimum curvature splice surface. Useful with CONTOUR.

POLAR_SURFACE	Interpolate a surface from polar coordinates to rectangular coordinates.

SPH_SCAT	Perform spherical gridding.

SPL_INIT	Establish type of interpolating spline.

SPL_INTERP	Cubic spline interpolation (Numerical Recipes).

SPLINE	Cubic spline interpolation.

SPLINE_P	Parametric cubic spline interpolation.

TRIANGULATE	Construct Delaunay triangulation.

TRIGRID	Interpolate irregularly-gridded data to regular grid.

VORONOI	Compute Voronoi polygons given Delaunay triangulation.


Hypothesis Testing Routines

CTI_TEST	Chi-square test.

FV_TEST	F-variance test.

KW_TEST	Kruskal-Wallis H-test.

LNP_TEST	Lomb Normalized Periodogram test.

MD_TEST	Median Delta test.

R_CORRELATE	Compute rank correlation.

R_TEST	Runs test for randomness.

RS_TEST	Wilcoxon Rank-Sum test.

S_TEST	Sign test.

TM_TEST	T-means test.

XSQ_TEST	Chi-square goodness-of-fit test.


Integration Routines

INT_2D	Compute double-integral of bivariate function.

INT_3D	Compute triple integral of trivariate function.

INT_TABULATED	Integrate a tabulated set of data.

QROMB	Evaluate integral over a closed interval.

QROMO	Evaluate integral over an open interval.

QSIMP	Evaluate integral using Simpson's rule.


Linear Systems Routines

CHOLDC	Construct Cholesky decomposition of a matrix.

CHOLSOL	Solve sets of linear equations (use with CHOLDC).

COND	Compute condition number of a square matrix.

CRAMER	Solve system of linear equations using Cramer's rule.

CROSSP	Vector cross product.

DETERM	Determinant of a square matrix/

GS_ITER	Solve linear system using Gauss-Seidel iteration.

INVERT	Compute inverse of a square array.

LINBCG	Solve set of linear equations using iterative biconjugate gradient method. Used with SPRSIN.

LU_COMPLEX	Solve complex linear system using LU decomposition.

LUDC	LU decomposition.

LUMPROVE	Use LU decomposition to improve approximate solution.

LUSOL	Use with LUDC to solve linear equations with LU decomposition.

NORM	Compute Euclidean norm of a vector or infinity norm of a matrix.

SVDC	Compute singular value decomposition of an array.

SVSOL	Use back-substitution to solve linear equations.

TRISOL	Solve tridiagonal systems of linear equations.


Miscellaneous Math Routines

ABS	Absolute value.

CEIL	Return closest integer great than or equal to argument.

CIR_3PNT	Return radius and center of a circle, given 3 points.

COMPLEXROUND	Round a complex array.

COND	Compute condition number of a square matrix.

CONJ	Complex conjugate.

DETERM	Determinant of a square matrix.

DIST	Create an array where each element is set to its Euclidean distance from the origin.

EXP	Natural exponential.

FINITE	Return True if number is finite.

FLOOR	Return closest integer less than or equal to argument.

IMAGINARY	Return imaginary part of complex value.

ISHFT	Integer bit shift.

LEEFILT	Lee filter.

LL_ARC_DISTANCE	Return longitude and latitude of a point, given its arc distance and azimuth.

PNT_LINE	Return perpendicular distance between a point and a line.

POLY	Evaluate polynomials.

ROBERTS	Roberts edge enhancement.

ROUND	Return integer closest to argument.

SOBEL	Sobel edge enhancement.

SPH_4PNT	Return the center and radius of a sphere, given 4 points.

TOTAL	Sum array elements.

VOIGT	Calculate the intensity of a Voigt profile.


Multivariate Analysis Routines

CTI_TEST	Chi-square test.

KW_TEST	Kruskal-Wallis H-test.

M_CORRELATE	Compute multiple correlation.

P_CORRELATE	Compute partial correlation.


Nonlinear Equations Routines

BROYDEN	Solve nonlinear equations using Broyden's method.

FX_ROOT	Compute real and complex roots of a univariate nonlinear function.

FZ_ROOTS	Find roots of complex polynomial using Laguerre's method.

NEWTON	Solve nonlinear equations using Newton's method.


Optimization Routines

DFPMIN	Minimize a function using Davidon-Fletcher-Powell method.

POWELL	Minimize a function using the Powell method.


Probability Functions and Inverses
Probability Routines

BINOMIAL	Compute binomial distribution function.

CHISQR_CVF	Compute cutoff value in Chi-square distribution.

CHISQR_PDF	Compute Chi-square distribution function.

F_CVF	Compute cutoff values for F distribution.

F_PDF	Compute F distribution function.

GAUSS_CVF	Compute cutoff value for Gaussian distribution.

GAUSS_PDF	Compute Gaussian distribution function.

T_CVF	Compute cutoff value for Student's t distribution.

T_PDF	Compute Student's t distribution function.


Sparse Array Routines

FULSTR	Restore a sparse matrix to full storage mode.

LINBCG	Solve set of linear equations using iterative biconjugate gradient method. Used with SPRSIN.

SPRSAB	Matrix multiplication for sparse matrices.

SPRSAX	Multiply sparse matrix by vector.

SPRSIN	Convert a matrix to row-index sparse matrix.

READ_SPR	Read a row-indexed sparse matrix from a file.

WRITE_SPR	Write a row-indexed sparse matrix to a file.


Special Math Functions

BESELI	Evaluate I Bessel function.

BESELJ	Evaluate J Bessel function.

BESELY	Evaluate Y Bessel function.

BETA	Evaluate beta function.

ERRORF	Evaluate error function.

EXPINT	Evaluate exponential integral.

GAMMA	Evaluate gamma function.

IBETA	Evaluate incomplete beta function.

IGAMMA	Evaluate incomplete gamma function.

LNGAMMA	Evaluate logarithm of gamma function.


Statistical Fitting Routines

COMFIT	Fit using gradient-expansion least-squares method.

CURVEFIT	Nonlinear least-squares fit to a function.

LADFIT	Fit using least absolute deviation method.

LINFIT	Fit using Chi-square error statistic.

REGRESS	Perform multiple linear regression fit.

SVDFIT	Least squares fit using SVD method.


Statistical Tools Routines

FACTORIAL	Factorial.

HIST_2D	Return histogram of two variables.

HISTOGRAM	Compute density function of array.

MAX	Return the maximum element of an array.

MEDIAN	Median function and filter.

MIN	Return the minimum element of an array.

MOMENT	Compute mean, variance, skewness, and kurtosis.

PRIMES	Compute prime numbers.

RANDOMN	Return normally-distributed random numbers.

RANDOMU	Return uniformly-distributed random numbers.

RANKS	Compute magnitude-based ranks.

SORT	Sort array in ascending order.

TOTAL	Sum array elements.


Time-Series Analysis Routines

A_CORRELATE	Compute autocorrelation.

C_CORRELATE	Compute cross correlation.

SMOOTH	Smooth with a boxcar average.

TS_COEF	Compute coefficients for autoregressive time-series.

TS_DIFF	Compute forward differences of a time series.

TS_FCAST	Compute future values of a stationary time-series.


Transcendental Functions

ACOS	Arc-cosine.

ALOG	Natural logarithm.

ALOG10	Base 10 logarithm.

ASIN	Arc-sin.

ATAN	Arc-tangent.

COS	Cosine.

COSH	Hyperbolic cosine.

EXP	Natural exponential.

SIN	Sine.

SINH	Hyperbolic sine.

TAN	Tangent.

TANH	Hyperbolic tangent.


Transforms Routines

BLK_CON	Convolve an input signal with an impulse-response sequence.

CHEBYSHEV	Forward and reverse Chebyshev polynomial expansion.

CONVOL	Convolve two vectors or arrays.

FFT	Fast Fourier Transform.

WTN	Wavelet transform.


Alphabetical List of Mathematics Routines

A_CORRELATE

ABS

ACOS

ALOG

ALOG10

ASIN

ATAN

BESELI

BESELJ

BESELY

BETA

BILINEAR

BINOMIAL

BLK_CON

BROYDEN

C_CORRELATE

CEIL

CHEBYSHEV

CHECK_MATH

CHISQR_CVF

CHISQR_PDF

CHOLDC

CHOLSOL

CIR_3PNT

COMFIT

COMPLEXROUND

COND

CONJ

CONVOL

CORRELATE

COS

COSH

CRAMER

CROSSP

CTI_TEST

CURVEFIT

DERIV

DERIVSIG

DETERM

DFPMIN

DIST

EIGENVEC

ELMHES

ERRORF

EXP

EXPINT

F_CVF

F_PDF

FACTORIAL

FFT

FINITE

FLOOR

FULSTR

FUNCT

FV_TEST

FX_ROOT

FZ_ROOTS

GAMMA

GAUSS_CVF

GAUSS_PDF

GAUSSFIT

GAUSSINT

GS_ITER

HANNING

HIST_2D

HISTOGRAM

HQR

IBETA

IGAMMA

IMAGINARY

INT_2D

INT_3D

INT_TABULATED

INTERPOL

INTERPOLATE

INVERT

ISHFT

KRIG2D

KW_TEST

LADFIT

LINBCG

LINFIT

LL_ARC_DISTANCE

LNGAMMA

LNP_TEST

LU_COMPLEX

LUDC

LUMPROVE

LUSOL

M_CORRELATE

MACHAR

MAX

MD_TEST

MEDIAN

MIN

MIN_CURVE_SURF

MOMENT

NEWTON

NORM

P_CORRELATE

PNT_LINE

POLAR_SURFACE

POLY

POLY_AREA

POLY_FIT

POLYFITW

POWELL

PRIMES

QROMB

QROMO

QSIMP

R_CORRELATE

R_TEST

RANDOMN

RANDOMU

RANKS

READ_SPR

REGRESS

RIEMANN

RK4

ROUND

RS_TEST

S_TEST

SFIT

SIN

SINH

SPH_4PNT

SPL_INIT

SPL_INTERP

SPLINE

SPLINE_P

SPRSAB

SPRSAX

SPRSIN

SQRT

SVDC

SVDFIT

SVSOL

T_CVF

T_PDF

TAN

TANH

TM_TEST

TOTAL

TRI_SURF

TRIANGULATE

TRIGRID

TRIQL

TRIRED

TRISOL

TS_COEF

TS_DIFF

TS_FCAST

VOIGT

VORONOI

WRITE_SPR

WTN

XSQ_TEST


Operating System Access Routines

CALL_EXTERNAL	Call an external entry in a sharable image.

CD	Change or get current working directory.

DELETE_SYMBOL (VMS Only)	Delete a DCL interpreter symbol.

DELLOG (VMS Only)	Delete a VMS logical name.

DO_APPLE_SCRIPT	Compile and execute AppleScript code.

GET_SYMBOL (VMS Only)	Return a VMS DCL interpreter symbol.

GETENV	Return value of an environment variable.

LINKIMAGE	Add a procedure or function from a VMS sharable image or Unix dynamically-linked object.

POPD	Remove the top directory on the working directory stack maintained by PUSHD/POPD.

PRINTD	Display the contents of the working directory stack maintained by PUSHD/POPD.

PUSHD	Push a directory onto the working directory stack maintained by PUSHD/POPD.

SET_SYMBOL (VMS Only)	Define a VMS DCL interpreter symbol.

SETENV (Unix and Windows Only)	Add or change an environment variable.

SETLOG (VMS Only)	Define a VMS logical name.

SPAWN	Spawn a child process for access to the operating system.

TRNLOG (VMS Only)	Search VMS logical name tables.


Plotting Routines, Two-Dimensional and General

AXIS	Draw an axis.

BAR_PLOT	Draw business style bar charts.

CONTOUR	Draw contour plots.

CONVERT_COORD	Transform coordinates.

COORD2TO3	Return 3D data coordinates given normalized screen coordinates.

CV_COORD	Convert 2D and 3D coordinates between coordinate systems.

ERRPLOT	Overplot error bars.

IMAGE_CONT	Overlay an image and its contour plot.

LABEL_DATE	A function to label axes with dates. Use with [XYZ]TICKFORMAT keyword.

MIN_CURVE_SURF	Interpolate points with a minimum curvature splice surface. Useful with CONTOUR.

OPLOT	Overplot dataset on existing axes.

OPLOTERR	Overplot data points with error bars.

PLOT	Plot vector arguments as X versus Y graphs.

PLOT_3DBOX	Three-dimensional box plot with projections.

PLOT_FIELD	Plot two-dimensional fields using arrows.

PLOTERR	Plot data with error bars.

PLOTS	Plot vectors and points.

POLAR_CONTOUR	Draw contour plot in polar coordinates.

POLYFILL	Fill polygons.

POLYFILLV	Return subscripts of pixels inside a polygon.

PROFILE	Extract a profile from an image.

PROFILES	Interactively examine image profiles.

SHADE_SURF	Create a shaded surface representation of gridded data.

SHADE_SURF_IRR	Create shaded surface from irregularly-gridded data.

SHOW3	Display array as an image, contour, and mesh surface simultaneously.

SURFACE	Plot array as a wireframe mesh surface.

THREED	Plot 2D array using pseudo-3D technique.

TRIANGULATE	Construct Delaunay triangulation.

TRIGRID	Interpolate irregularly-gridded data to regular grid.

USERSYM	Define a new plotting symbol.

VEL	Draw vector flow (field) plot with streamlines.

VELOVECT	Draw vector flow (field) plot.

WF_DRAW	Draw weather fronts with smoothing.

XYOUTS	Draw text on the current graphics device.

XSURFACE	Widget interface to SURFACE and SHADE_SURF.


Plotting Routines, Multi-Dimensional

CREATE_VIEW	Set up 3D transformations.

EXTRACT_SLICE	Return a 2D planar slice extracted from a volume.

FLOW3	Draw lines representing 3D flow/velocity field.

GRID3	Create a regularly-gridded 3D dataset forma set of scattered 3D nodes.

MESH_OBJ	Generate polygon mesh for various simple objects.

POLYSHADE	Create a shaded surface representation from a set of polygons.

PROJECT_VOL	Return a translucent rendering of a volume projected onto a plane.

RECON3	Reconstruct a 3D representation of an object from 2D images.

SCALE3	Set up axis ranges and viewing angles for 3D plots.

SCALE3D	Scale 3D unit cube into the viewing area.

SET_SHADING	Set light source shading parameters.

SHADE_VOLUME	Contour a volume to produce vertex and polygon lists that can be displayed using POLYSHADE.

SLICER	Interactive volume visualization tool.

SURFR	Duplicate rotation, translation, and scaling of SURFACE.

T3D	Perform various 3D transformations.

VERT_T3D	Transform a 3D array by a 4 x 4 transformation matrix.

VOXEL_PROJ	Visualize volumes using voxel technique.


Programming and IDL Control Routines

BIN_DATE	Convert ASCII date/time to binary.

BREAKPOINT	Set and clear program breakpoints.

BYTEORDER	Convert short and long integer between host and network byte order.

CALDAT	Convert Julian date to month, day, year.

CALENDAR	Display a calendar for a given month or year.

CALL_FUNCTION	Indirectly call an IDL function.

CALL_PROCEDURE	Indirectly call an IDL procedure.

CATCH	Intercept error messages, process, them, and continue program execution.

CREATE_STRUCT	Create and concatenate structures.

CW_TMPL	Template for creating compound widgets.

DEFINE_KEY	Define a function key.

DEFSYSV	Define a new system variable.

DELVAR	Delete a variable from the main level.

DEMO_MODE	Returns True if IDL is in demo mode.

EXECUTE	Compile and execute the contents of a string.

EXIT	Exit IDL and return to the operating system.

EXPAND_PATH	Expand path definition string into a full pathname for use with !PATH.

HANDLE_CREATE	Create a new handle (pointer).

HANDLE_FREE	Free a handle, its dynamic memory, and children.

HANDLE_INFO	Return information about a handle.

HANDLE_MOVE	Move a handle to a new location.

HANDLE_VALUE	Return or set the value of a handle.

JULDAY	Calculate the Julian Day Number from month, day, and year.

KEYWORD_SET	Returns True if its argument is defined and non-zero.

MESSAGE	Issue error and informational messages.

N_ELEMENTS	Return number of elements in expression.

N_PARAMS	Return number of non-keyword parameters

N_TAGS	Return number of tags in a structure.

ON_ERROR	Designate error recovery method.

ON_IOERROR	Declare I/O error exception handler.

PICKFILE	Interactively select a file.

RESOLVE_ALL	Resolve all uncompiled routine names.

RESOLVE_ROUTINE	Resolve an uncompiled routine.

SETUP_KEYS	Setup function keys for use with IDL.

STOP	Stop the execution of a running program or batch file.

SWAP_ENDIAN	Reverse the byte ordering of scalars, arrays, or structures.

SYSTIME	Return current system time.

TAG_NAMES	Return names of tags in a structure.

TEMPORARY	Return a temporary copy of a variable, setting the original to "undefined".

TIME_TEST	Speed benchmarks for IDL.

WAIT	Delay program execution.

XBM_EDIT	Bitmap editor for IDL widget bitmaps.

XDISPLAYFILE	Display text file using scrolling text widget.

XMANAGER	Event loop manager for IDL widgets.

XMNG_TMPL	Template for creating widget programs.

XMTOOL	View widgets currently being managed by XMANAGER.

XREGISTERED	Return registration status of a given widget.


Saving and Restoring a Session Routines

JOURNAL	Log IDL commands to a file.

RESTORE	Restore contents of an IDL SAVE file.

SAVE	Save IDL objects in a file for later use.


String Processing Routines

RSTRPOS	Find last occurrence of a search string.

STR_SEP	Divide a string into pieces marked by a separator string.

STRCOMPRESS	Remove whitespace from a string.

STRLEN	Return the length of a string.

STRLOWCASE	Convert all characters to lower case.

STRMESSAGE	Return the text of an error number.

STRMID	Extract a substring from a string.

STRPOS	Search for a substring within a string.

STRPUT	Insert the contents of one string into another.

STRTRIM	Remove leading or trailing blanks from a string.

STRUPCASE	Convert all characters to upper case.


Type Conversion Routines

BYTE	Convert argument to byte type.

BYTSCL	Scale argument into the range of bytes.

COMPLEX	Convert argument to complex type.

DCOMPLEX	Convert argument to double-precision complex type.

DOUBLE	Convert argument to double-precision type.

FIX	Convert argument to integer type.

FLOAT	Convert argument to floating-point type.

LONG	Convert argument to longword integer type.

STRING	Convert argument to string type.


Widget Routines

WIDED	Interactive graphical user interface creator.

WIDGET_BASE	Create base widgets.

WIDGET_BUTTON	Create button widgets.

WIDGET_CONTROL	Realize, manage, and destroy widgets.

WIDGET_DRAW	Create drawable widgets.

WIDGET_DROPLIST	Create droplist widgets.

WIDGET_EVENT	Return events for widget hierarchies.

WIDGET_INFO	Return information about widgets.

WIDGET_LABEL	Create label widgets.

WIDGET_LIST	Create list widgets.

WIDGET_MESSAGE	Create modal message widgets.

WIDGET_SLIDER	Create slider widgets.

WIDGET_TEXT	Create text widgets.


Widget Routines, Compound

CW_ANIMATE	Compound widget for animation.

CW_ANIMATE_LOAD	Load images into CW_ANIMATE.

CW_ANIMATE_GETP	Get pixmap IDs used by CW_ANIMATE.

CW_ANIMATE_RUN	Display images loaded into CW_ANIMATE.

CW_ARCBALL	3D orientation selector using "arcball" method.

CW_BGROUP	Create button groups for use as menus.

CW_CLR_INDEX	Select a color index from a colorbar.

CW_COLORSEL	Color selection compound widget.

CW_DEFROI	Compound widget for defining regions-of-interest.

CW_DICE	Six-sided die widget.

CW_FIELD	Create labeled data entry fields.

CW_FSLIDER	Create floating-point slider widgets.

CW_ORIENT	Interactively adjust the 3D transformation matrix.

CW_PDMENU	Create pulldown menus.

CW_RGBSLIDER	Widget for adjusting red, green, blue color values.

CW_ZOOM	Compound widget for displaying zoomed images.


Window Routines

WDELETE	Delete IDL graphics windows.

WINDOW	Create a graphics window.

WSET	Set the current window.

WSHOW	Expose or hide a window.


System Variables Quick Reference
System Variables

Constant System Variables

!DPI	Double-precision pi (π).

!DTOR	Degrees to radians, π/180 ≅ 0.01745.

!MAP	Read-only system variable used by MAP_SET.

!PI	Single-precision pi (π).

!RADEG	Radians to degrees, 180/π ≅ 57.2958.

!VALUES	Single- and double-precision NaN and Infinity values.

Graphics System Variables

!D	Information about current graphics device.

!ORDER	Direction of image transfer: 0=bottom up, 1=top down.

!P	Information for plotting procedures.

!X, !Y, !Z	Axis structures for X, Y, and Z axes.

Error Handling System Variables

!ERR	Used internally by IDL to monitor error conditions.

!ERROR	Code of last error message.

!ERR_STRING	Text of last error message.

!MSG_PREFIX	Prefix string for error messages.

!SYSERROR	Error code of the last system error message.

!SYSERR_STRING	Text of the last system error message.

IDL Environment System Variables

!DIR	Location of the main IDL directory.

!EDIT_INPUT	Enables/disables keyboard line editing.

!JOURNAL	Logical unit number of journal output, or 0.

!MORE	Set to 0 to prevent paginating help text.

!PATH	Search path for IDL routines.

!PROMPT	String to be used for IDL prompt.

!QUIET	Suppresses informational messages if set to non-zero.

!VERSION	Type, architecture, and version of IDL.


Graphics Devices Quick Reference
Graphics Devices

CGM	The CGM Device

HP	The HP-GL Device

LJ	The LJ Device

MAC	The Macintosh Display Device

NULL	The Null Display Device

PCL	The PCL Device

PS	The PostScript Device

REGIS	The Regis Terminal Device

TEK	The Tektronix Device

WIN	The Microsoft Windows Device

X	The X Windows Device

Z	The Z-Buffer Device


Graphics Keywords Quick Reference
Graphics Keywords

BACKGROUND	Background color index when erasing.

CHANNEL	Channel index or mask for multi-channel displays.

CHARSIZE	Overall character size.

[XYZ]CHARSIZE	Character size for axes.

CHARTHICK	Overall thickness for vector fonts.

CLIP	Coordinates of clipping window.

COLOR	Color index for data, text, line, or polygon fill.

DATA	Set to plot in data coordinates.

DEVICE	Set to plot in device coordinates.

FONT	Text font index: -1 for vector, 0 for hardware fonts.

[XYZ]GRIDSTYLE	Index of linestyle to be used for tickmarks and grids.

LINESTYLE	LInestyle used to connect data points.

[XYZ]MARGIN	Margin of plot window in character units.

[XYZ]MINOR	number of minor tick marks.

NOCLIP	Set to disable clipping of plot.

NODATA	Set to plot only axes, titles, and annotation w/o data.

NOERASE	Set to inhibit erasing before new plot.

NORMAL	Set to plot in normal coordinates.

ORIENTATION	Angle (in degrees counter-clockwise) for text.

POSITION	Position of plot window.

PSYM	Use plotting symbols to plot data points.

[XYZ]RANGE	Axis range.

[XYZ]STYLE	Axis type.

SUBTITLE	String for subtitle.

SYMSIZE	Size of PSYM plotting symbols.

T3D	Set to use 3D transformation store in !P.T.

THICK	Overall line thickness.

[XYZ]THICK	Thickness of axis and tickmark lines.

[XYZ]TICKFORMAT	Allows advanced formatting of tick labels.

TICKLEN	Length of tickmarks in normal coordinates. 1.0 produces a grid. Negative values extend outside window.

[XYZ]TICKLEN	Tickmark lengths for individual axes.

[XYZ]TICKNAME	String array of up to 30 labels for tickmark annotation.

[XYZ]TICKS	Number of major tick intervals for axes.

[XYZ]TICKV	Array of up to 30 elements for tick mark values.

[XYZ]TICK_GET	Variable in which to return values of tick marks.

TITLE	String for plot title.

[XYZ]TITLE	String for specified axis title.

ZVALUE	The Z coordinate for a 2D plot in 3D space.

Z	Z coordinate if Z argument not specified in 3D plot call.


IDL Routines
1	IDL Routines

This chapter describes IDL's built-in functions and procedures. Conventions used in this chapter are described below.

How to Use this Chapter

All of IDL's routines are documented alphabetically in this chapter. A description of each routine follows its name. Beneath the general description of the routine are a number of sections that describe the calling sequence for the routine, its arguments (if any), its keywords (if any), and an example of using the routine. These sections are described below.

Routines written in the IDL language are noted as such, and the location of the .pro file within the IDL distribution is specified. You may wish to inspect the IDL source code for some of these routines to gain further insight into their inner workings.

Calling Sequence

The "Calling Sequence" section shows the proper syntax for calling the function or procedure.

Procedures

IDL procedures have the calling sequence:

PROCEDURE_NAME, Argument [, Optional_Arguments]

where PROCEDURE_NAME is the name of the procedure, Argument is a required parameter, and Optional_Argument is an optional parameter to the procedure. Note that the square brackets around optional arguments are not used in the actual call to the procedure, they are simply used to denote the optional nature of the arguments within this document.

Functions

IDL functions have the calling sequence:

Result = FUNCTION_NAME(Argument [, Optional_Arguments])

where Result is the returned value of the function, FUNCTION_NAME is the name of the function, Argument is a required parameter, and Optional_Argument is an optional parameter. Note that the square brackets around optional arguments are not used in the actual call to the function, they are simply used to denote the optional nature of the arguments within this document. Note also that all arguments and keyword arguments to functions should be supplied within the parentheses that follow the function's name.

Functions do not always have to be used in assignment statements (i.e., A=SIN(10.2)), they can be used just like any other IDL expression. For example, you could print the result of SIN(10.2) by entering the command:

PRINT, SIN(10.2)

Arguments

The "Arguments" section describes each valid argument to the routine. Note that these arguments are positional parameters that must be supplied in the order indicated by the routine's calling sequence.

Named Variables

Often, arguments that contain values upon return from the function or procedure ("output arguments") are described as accepting "named variables". A named variable is simply a valid IDL variable name. This variable does not need to be defined before being used as an output argument. Note, however that when an argument calls for a named variable, only a named variable can be used—sending an expression causes an error.

Keywords

The "Keywords" section describes each valid keyword argument to the routine. Note that keyword arguments are formal parameters that can be supplied in any order.

Keyword arguments are supplied to IDL routines by including the keyword name followed by an equal sign ("=") and the value to which the keyword should be set. For example, to produce a plot with diamond-shaped plotting symbols, the PSYM keyword should be set to 4 as follows:

PLOT, FINDGEN(10), PSYM=4

Note also that keywords can be abbreviated to their shortest unique length. For example, the XSTYLE keyword can be abbreviated to XST.

Setting Keywords

When the documentation for a keyword says something similar to, "Set this keyword to enable logarithmic plotting," the keyword is simply a switch that turns an option on and off. Usually, setting such keywords equal to 1 causes the option to be turned on. Explicitly setting the keyword to zero (or not including the keyword) turns the option off.

There is a "shortcut" that can be used to set a keyword equal to 1 without the usual syntax (i.e., KEYWORD=1). To "set" a keyword, simply preface it with a slash character ("/"). For example, to plot a wire mesh surface with a skirt around it, set the SKIRT keyword to the SURFACE routine as follows:

SURFACE, DIST(10), /SKIRT

Named Variables

Often, keywords that contain values upon return from the function or procedure ("output arguments") are described as accepting "named variables". A named variable is simply a valid IDL variable name. This variable does not need to be defined before being used with the keyword. Note, however that when a keyword calls for a named variable, only a named variable can be used—sending an expression causes an error.

For example, the WIDGET_CONTROL procedure can return the user values of widgets in a named variable using the GET_UVALUE keyword. To return the user value for a widget ID (contained in the variable mywidget) in the variable userval, you would use the command:

WIDGET_CONTROL, mywidget, GET_UVALUE = userval

Upon return from the procedure, userval contains the user value. Note that userval did not have to be defined before the call to WIDGET_CONTROL.

Examples

Most routines include a short example that demonstrates how the function or procedure is used. Most of the examples are just one or two lines of IDL code that can be entered at the IDL prompt. Others are code fragments or routines designed to serve as examples for you own programs.

See Also

The names of related routines are listed in this section.


A_CORRELATE

The A_CORRELATE function computes the autocorrelation Px(L) or autocovariance Rx(L) of a sample population X as a function of the lag L.

where x  is the mean of the sample population x = (x0, x1, x2, ... , xN-1).

This routine is written in the IDL language. Its source code can be found in the file a_correlate.pro in the lib subdirectory of the IDL distribution.

Calling Sequence

Result = A_CORRELATE(X, Lag)

Arguments

X

An n-element integer, single-, or double-precision floating-point vector.

Lag

An n-element integer vector in the interval [-(n-2), (n-2)], specifying the signed distances between indexed elements of X.

Keywords

COVARIANCE

Set this keyword to compute the sample autocovariance rather than the sample autocorrelation.

Example

Define an n-element sample population.

X = [3.73, 3.67, 3.77, 3.83, 4.67, 5.87, 6.70, 6.97, 6.40, 5.57]

Compute the autocorrelation of X for LAG = -3, 0, 1, 3, 4, 8

lag = [-3, 0, 1, 3, 4, 8]

result = A_CORRELATE(X, lag)

PRINT, result

IDL prints:

-0.0303311  1.00000  0.784758  -0.0303311  -0.350930  -0.112325

See Also

CORRELATE, C_CORRELATE, M_CORRELATE, P_CORRELATE, R_CORRELATE


ABS

The ABS function returns the absolute value of its argument.

Calling Sequence

Result = ABS(X)

Arguments

X

The value for which the absolute value is desired. If  X is of complex type, ABS returns the magnitude of the complex number:

SQRT(Real^2 + Imaginary^2)

If X is of complex type, the result is returned as single-precision, floating-point type. For all other types, the result has the same type as X. If X is an array, the result has the same structure, with each element containing the absolute value of the corresponding element of X.

Example

To print the absolute value of -25, enter:

PRINT, ABS(-25)

IDL prints:

25


ACOS

The ACOS function returns the angle, expressed in radians, whose cosine is X (i.e., the arc-cosine). The range of ACOS is between 0 and π.

Calling Sequence

Result = ACOS(X)

Arguments

X

The cosine of the desired angle in the range (-1 ≤ X ≤ 1). If X is double-precision floating, the result of ACOS is also double-precision. X cannot be complex. All other types are converted to single-precision floating-point and yield floating-point results. If X  is an array, the result has the same structure, with each element containing the arc-cosine of the corresponding element of X.

Example

To find the arc-cosine of 0.707 and store the result in the variable B, enter:

B = ACOS(0.707)

See Also

COS


ALOG

The ALOG function returns the natural logarithm of X. The result has the same structure as X.

Calling Sequence

Result = ALOG(X)

Arguments

X

The value for which the natural log is desired. The result of ALOG is double-precision floating if X is double-precision, and complex if X is complex. All other types are converted to single-precision floating-point and yield floating-point results. When applied to complex numbers, the definition of the ALOG function is:

ALOG (x) = COMPLEX(log |x|, atan x)

Example

To print the natural logarithm of 5, enter:

PRINT, ALOG(5)

IDL prints:

1.60944

See Also

ALOG10


ALOG10

The ALOG10 function returns the logarithm to the base 10 of X. This function operates in the same manner as the ALOG function.

Calling Sequence

Result = ALOG10(X)

Arguments

X

The value for which the base 10 log is desired.

Example

To find the base 10 logarithm of 5 and store the result in the variable L, enter:

L = ALOG10(5)

See Also

ALOG


ANNOTATE

The ANNOTATE procedure starts an IDL widget program that allows you to interactively annotate images and plots with text and drawings. Drawing objects include lines, arrows, polygons, rectangles, circles, and ellipses. Annotation files can be saved and restored, and annotated displays can be written to TIFF, GIF, or PostScript files. The Annotation widget will work on any IDL graphics window or draw widget.

This routine is written in the IDL language. Its source code can be found in the file annotate.pro in the lib subdirectory of the IDL distribution.

Using the Annotation Widget

Before calling the Annotation widget, plot or display your data in an IDL graphics window or draw widget. Unless you specify otherwise (using the DRAWABLE or WINDOW keywords), annotations will be made in the current graphics window.

For information on using the Annotation widget, click on the widget's "Help" button.

Calling Sequence

ANNOTATE

Arguments

This procedure has no required arguments.

Keywords

COLOR_INDICES

An array of color indices from which the user can choose colors. For example, to allow the user to choose 10 colors, spread evenly over the available indices, set the keyword as follows:

COLOR_INDICES = INDGEN(10) * (!D.N_COLORS-1) / 9

If neither TEK_COLORS or COLOR_INDICES are specified, the default is to load 10 colors, evenly distributed over those available.

DRAWABLE

The widget ID of the draw widget for the annotations. Do not set both DRAWABLE and WINDOW. If neither WINDOW or DRAWABLE are specified, the current window is used.

LOAD_FILE

The name of an annotation format file to load after initialization.

TEK_COLORS

Set this keyword and the Tektronix color table is loaded starting at color index TEK_COLORS(0), with TEK_COLORS(1) color indices. The Tektronix color table contains up to 32 distinct colors suitable for graphics. If neither TEK_COLORS or COLOR_INDICES are specified, the default is to load 10 colors, evenly distributed over those available.

WINDOW

The window index number of the window to receive the annotations. Do not set both DRAWABLE and WINDOW. If neither WINDOW or DRAWABLE are specified, the current window is used.

Example

TVSCL, HANNING(300,200)	Output an image in the current window.

ANNOTATE	Annotate it.

See Also

DISP_TXT, PLOTS, XYOUTS


ARROW

The ARROW procedure draws one or more vectors with arrow heads.

This routine is written in the IDL language. Its source code can be found in the file arrow.pro in the lib subdirectory of the IDL distribution.

Calling Sequence

ARROW, X0, Y0, X1, Y1

Arguments

X0, Y0

Arrays or scalars containing the coordinates of the tail end of the vector or vectors. Coordinates are in DEVICE coordinates unless otherwise specified.

X1,Y1

Arrays or scalars containing the coordinates of the arrowhead end of the vector or vectors. X1 and Y1 must have the save number of elements as X0 and Y0.

Keywords

DATA

Set this keyword if vector coordinates are DATA coordinates.

NORMALIZED

Set this keyword if vector coordinates are NORMALIZED coordinates.

HSIZE

Use this keyword to set the length of the lines used to draw the arrowhead. The default is 1/64th the width of the display (!D.X_SIZE / 64.). If the HSIZE is positive, the value is assumed to be in device coordinate units. If HSIZE is negative, the arrowhead length is set to the vector length * ABS(HSIZE). The lines are separated by 60 degrees to make the arrowhead.

COLOR

The color of the arrow. The default is the highest color index.

HTHICK

The thickness of the arrowheads. The default is 1.0.

SOLID

Set this keyword to make a solid arrow, using polygon fills, looks better for thick arrows.

THICK

The thickness of the body. The default is 1.0.

Examples

Draw an arrow from (100,150) to (300,350) in DEVICE units.

ARROW, 100, 150, 300, 350

Draw a sine wave with arrows from the line Y = 0 to SIN(X/4).

X = FINDGEN(50)

Y = SIN(x/4)

PLOT, X, Y

ARROW, X, REPLICATE(0,50), X, Y, /DATA

See Also

ANNOTATE, PLOTS, VELOVECT


ASIN

The ASIN function returns the angle, expressed in radians, whose sine is X (i.e., the arc-sine). The range of ASIN is between -π/2 and  π/2. Rules for the type and structure of the result are the same as those given for the ACOS function.

Calling Sequence

Result = ASIN(X)

Arguments

X

The sine of the desired angle, -1 ≤ X ≤ 1.

Example

To print the arc-sine of 0.707, enter:

PRINT, ASIN(0.707)

IDL prints:

0.785247

See Also

SIN


ASSOC

The ASSOC function associates an array structure with a file. It provides a basic method of random access input/output in IDL. An associated variable, which stores this association, is created by assigning the result of ASSOC to a variable. This variable provides a means of mapping a file into vectors or arrays of a specified type and size.

Calling Sequence

Result = ASSOC(Unit, Array_Structure [, Offset])

Arguments

Unit

The IDL file unit to associate with Array_Structure.

Array_Structure

An expression of the data type and structure to be associated with Unit are taken from Array_Structure. The actual value of Array_Structure is not used.

Offset

The offset in the file to the start of the data in the file. For stream files, and RMS (VMS) block mode files, this offset is given in bytes. For RMS record-oriented files, the offset is specified in records. Offset is useful for dealing with data files that contain a descriptive header block followed by the actual data.

Example

Suppose that the file images.dat holds 5 images as 256-element by 256-element arrays of bytes. Open the file for reading and create an associated variable by entering:

OPENR, 1, 'images.dat'	Open the file as file unit 1.

A = ASSOC(1, BYTARR(256, 256))	Make an associated variable.

Now A(0) corresponds to the first image in the file, A(1) is the second element, etc. To display the first image in the file, you could enter:

TV, A(0)

The data for the first image is read and then displayed. Note that the data associated with A(0) is not held in memory. It is read in every time there is a reference to A(0). To store the image in the memory-resident array B, you could enter:

B = A(0)

See Also

OPEN, READU


ATAN

The ATAN function returns the angle, expressed in radians, whose tangent is X (i.e., the arc-tangent). If two parameters are supplied, the angle whose tangent is equal to Y/X is returned. The range of ATAN is between -π/2 and π/2 for the single argument case, and between -π and π if two arguments are given.

Calling Sequence

Result = ATAN(X)

or

Result = ATAN(Y, X)

Arguments

X

The tangent of the desired angle.

Y

An optional argument. If this argument is supplied, ATAN returns the angle whose tangent is equal to Y/X. If both arguments are zero, the result is undefined.

Examples

To find the arc-tangent of 0.707 and store the result in the variable B, enter:

B = ATAN(0.707)

The following code defines a function that converts Cartesian coordinates to polar coordinates. It returns "r" and "theta" given an "x" and "y" position:

FUNCTION TO_POLAR, X, Y	Define function TO_POLAR that accepts X and Y as arguments.

RETURN, [SQRT(X^2 + Y^2), ATAN(Y, X)
Return the distance and angle as a two-element array.

END	End of function.

See Also

TAN


AXIS

The AXIS procedure draws an axis of the specified type and scale at a given position. The new scale is saved for use by subsequent overplots if the SAVE keyword parameter is set. The keyword parameters XAXIS, YAXIS, and ZAXIS specify the type of axis to be drawn, and its position.

Calling Sequence

AXIS  [[[, X], Y], Z]

Arguments

X, Y, and Z

Scalars giving the starting coordinates of the new axis. If no coordinates are specified, the axis is drawn in its default position as given by the [XYZ]AXIS keyword. When drawing an X axis, the X coordinate is ignored, similarly the Y and Z parameters are ignored when drawing their respective axes (i.e., new axes will always point in the correct direction).

Keywords

SAVE

Set this keyword to indicate that the scaling to and from data coordinates established by the call to AXIS is to be saved in the appropriate axis system variable, !X, !Y, or !Z. If this keyword is not present, the scaling is not changed.

XAXIS

Set this keyword to draw an X axis. If the X parameter is not present, setting XAXIS equal to 0 draws an axis under the plot window with the tick marks pointing up, and setting XAXIS equal to one draws an axis above the plot window with the tick marks pointing down. If the X parameter is present, the X axis is positioned accordingly, and setting XAXIS equal to 0 or 1 causes the tick marks to point up or down, respectively.

YAXIS

Set this keyword to draw a Y axis. If the Y parameter is not present, setting YAXIS equal to 0 draws an axis on the left side of the plot window with the tick marks pointing right, and setting YAXIS equal to one draws an axis on the right side of the plot window with the tick marks pointing left. If the Y parameter is present, the Y axis is positioned accordingly, and setting YAXIS equal to 0 or 1 causes the tick marks to point right or left, respectively.

ZAXIS

Set this keyword to draw a Z axis. If the Z parameter is not present, setting ZAXIS has the following meanings:

•	0 = lower (front) right, with tickmarks pointing left

•	1 = lower (front) left, with tickmarks pointing right

•	2 = upper (back) left, with tickmarks pointing right

•	3 = upper (back) right, with tickmarks pointing left

If the Z parameter is present, the Z axis is positioned accordingly, and setting ZAXIS equal to 0 or 1 causes the tick marks to point left or right, respectively.

Note that AXIS uses the 3D plotting transformation stored in the system variable field !P.T.

XLOG

Set this keyword to specify a logarithmic X axis

YNOZERO

Set this keyword to inhibit setting the minimum Y axis value to zero when the Y data are all positive and non-zero, and no explicit minimum Y value is specified (using YRANGE, or !Y.RANGE). By default, the Y axis spans the range of 0 to the maximum value of Y, in the case of positive Y data. Set bit 4 in !Y.STYLE to make this option the default.

YLOG

Set this keyword to specify a logarithmic Y axis.

Graphics Keywords Accepted

See Chapter 2, "Graphics Keywords and System Variables", for the description of graphics and plotting keywords not listed above. CHARSIZE CHARTHICK  COLOR DATA DEVICE FONT NODATA NOERASE NORMAL SUBTITLE  T3D TICKLEN  [XYZ]CHARSIZE [XYZ]GRIDSTYLE [XYZ]MARGIN [XYZ]MINOR [XYZ]RANGE [XYZ]STYLE [XYZ]THICK [XYZ]TICKFORMAT [XYZ]TICKLEN [XYZ]TICKNAME [XYZ]TICKS [XYZ]TICKV [XYZ]TICK_GET [XYZ]TITLE ZVALUE.

Example

The following example shows how the AXIS procedure can be used with normal or polar plots to draw axes through the origin, dividing the plot window into four quadrants:

PLOT, /POLAR, XSTYLE=4, YSTYLE=4, TITLE='Polar Plot', r, theta
Make the plot, polar in this example, and suppress the X and Y axes using the XSTYLE and YSTYLE keywords.

AXIS,0,0,XAX=0,/DATA 	Draw an X axis, through data Y coordinate of 0. Because the XAXIS keyword parameter has a value of 0, the tick marks point down.

AXIS,0,0,0,YAX=0,/DATA	Similarly, draw the Y axis through data X = 0. The tick marks point left.

See Also

LABEL_DATE, PLOT


BAR_PLOT

The BAR_PLOT procedure creates a bar graph.

This routine is written in the IDL language. Its source code can be found in the file bar_plot.pro in the lib subdirectory of the IDL distribution.

Calling Sequence

BAR_PLOT, Values

Arguments

Values

A vector containing the values to be represented by the bars. Each element in Values corresponds to a single bar in the output.

Keywords

BACKGROUND

A scalar that specifies the color index to be used for the background color. By default, the normal IDL background color is used.

BARNAMES

A string array, containing one string label per bar. If the bars are vertical, the labels are placed beneath them. If horizontal (rotated) bars are specified, the labels are placed to the left of the bars.

BAROFFSET

A scalar that specifies the offset to be applied to the first bar, in units of "nominal bar width". This keyword allows, for example, different groups of bars to be overplotted on the same graph. If not specified, the default offset is equal to BARSPACE.

BARSPACE

A scalar that specifies, in units of "nominal bar width", the spacing between bars. For example, if BARSPACE is 1.0, then all bars will have one bar-width of space between them. If not specified, the bars are spaced apart by 20% of the bar width.

BARWIDTH

A floating-point value that specifies the width of the bars in units of "nominal bar width". The nominal bar width is computed so that all the bars (and the space between them, set by default to 20% of the width of the bars) will fill the available space (optionally controlled with the BASERANGE keyword).

BASELINES

A vector, the same size as Values, that contains the base value associated with each bar. If not specified, a base value of zero is used for all bars.

BASERANGE

A floating-point scalar in the range 0.0 to 1.0, that determines the fraction of the total available plotting area (in the direction perpendicular to the bars) to be used. If not specified, the full available area is used.

COLORS

A vector, the same size as Values, containing the color index to be used for each bar. If not specified, the colors are selected based on spacing the color indices as widely as possible within the range of available colors (specified by !D.N_COLORS).

OUTLINE

If set, this keyword specifies that an outline should be drawn around each bar.

OVERPLOT

If set, this keyword specifies that the bar plot should be overplotted on an existing graph.

ROTATE

If set, this keyword indicates that horizontal rather than vertical bars should be drawn. The bases of horizontal bars are on the left, "Y" axis and the bars extend to the right.

TITLE

A string containing the main title to for the bar plot.

XTITLE

A string containing the title for the X axis.

YTITLE

A string containing the title for the Y axis.

Example

By using the overplotting capability, it is relatively easy to create stacked bar charts, or different groups of bars on the same graph.

For example, if ARRAY is a two-dimensional array of 5 columns and 8 rows, it is natural to make a plot with 5 bars, each of which is a "stacked" composite of 8 sections. First, create a 2D COLORS array, equal in size to ARRAY, that has identical color index values across each row to ensure that the same item is represented by the same color in all bars.

array = INDGEN(5,8)

colors = INTARR(5,8)

FOR I = 0, 7 DO colors(*,I)=(20*I)+20

With ARRAYS and COLORS defined, the following code fragment illustrates the creation of stacked bars (note that the number of rows and columns is arbitrary):

!Y.RANGE = [0, MAX(array)]	Scale range to accommodate the total bar lengths.

nrows = N_ELEMENTS(array(0,*))

base = INTARR(nrows)

FOR I = 0, nrows-1 DO BEGIN

  BAR_PLOT, array(*,I), COLORS=colors(*,I), BASELINES=base, $

    BARWIDTH=0.75, BARSPACE=0.25, OVER=(I GT 0)

  base = array(*,I)

ENDFOR

To plot each row of ARRAY as a clustered group of bars within the same graph, use the BASERANGE keyword to restrict the available plotting region for each set of bars. The sample code fragment below illustrates this method:

ncols = N_ELEMENTS(array(*,0))

FOR I = 0, nrows-1 DO $

  BAR_PLOT, array(*,I), COLORS=colors(*,I), BARWIDTH=0.8, $

    BARSPACE=0.2, BAROFFSET=I*(1.5*ncols), $

    OVER=(I GT 0), BASERANGE=0.19

where NCOLS is the number of columns in ARRAY. (In this example, each group uses the same set of colors, but this could easily be changed.)

See Also

PLOT, PSYM Graphics Keyword


BESELI

The BESELI function returns the I Bessel function of order N for the argument X. If X is double-precision, the result is double precision, otherwise the argument is converted to floating-point and the result is floating-point.

Calling Sequence

Result = BESELI(X, N)

Arguments

X

The expression for which the I Bessel function is required. The result will have the same dimensions as X.

N

The order of the I Bessel function to calculate. N must be an integer greater than or equal to 0.

See Also

BESELJ, BESELY


BESELJ

The BESELJ function returns the J Bessel function of order N for the argument X. If X is double-precision, the result is double precision, otherwise the argument is converted to floating-point and the result is floating-point. BESELJ uses the j0(3M), j1(3M), and jn(3M) functions from the standard C math library.

Calling Sequence

Result = BESELJ(X, N)

Arguments

X

The expression for which the J Bessel function is required. The result has the same dimensions as X.

N

The order of the J Bessel function to calculate. N must be an integer greater than or equal to 0.

See Also

BESELI, BESELY


BESELY

The BESELY function returns the Y Bessel function of order N for the argument X. If X is double-precision, the result is double precision, otherwise the argument is converted to floating-point and the result is floating-point. BESELY uses the y0(3M), y1(3M), and yn(3M) functions from the standard C math library.

Calling Sequence

Result = BESELY(X, N)

Arguments

X

The expression for which the Y Bessel function is required. X must be greater than 0. The result has the same dimensions as X.

N

The order of the Y Bessel function to calculate. N must be an integer greater than or equal to 0.

See Also

BESELI, BESELJ


BETA

The BETA function returns the value of the beta function B(Z, W).

BETA is based on the routine beta described in section 6.1 of Numerical Recipes in C: The Art of Scientific Computing (Second Edition), published by Cambridge University Press, and is used by permission.

Calling Sequence

Result = BETA(Z, W)

Arguments

Z, W

The point at which the beta function is to be evaluated. Z and  W can be scalar or array.

Keywords

DOUBLE

Set this keyword to force the computation to be done in double-precision arithmetic.

Example

To evaluate the beta function at the point (1.0, 1.1) and print the result:

PRINT, BETA(1.0, 1.1)

IDL prints:

0.909091

The exact solution is:

((1.00 * .95135077) / (1.10 * .95135077)) = 0.909091.

See Also

GAMMA, IBETA,  IGAMMA, LNGAMMA


BILINEAR

The BILINEAR function uses a bilinear interpolation algorithm to compute the value of a data array at each of a set of subscript values. The function returns a two-dimensional, floating-point interpolated array.

This routine is written in the IDL language. Its source code can be found in the file bilinear.pro in the lib subdirectory of the IDL distribution.

Calling Sequence

Result = BILINEAR(P, IX, JY)

Arguments

P

A two-dimensional data array.

IX and JY

Arrays containing the X and Y "virtual subscripts" of P to interpolate values for.

IX and JY can be either of the following:

•	One-dimensional, n-element floating-point arrays of subscripts to look up in P. One-dimensional arrays will be converted to two-dimensional arrays in such a way that IX contains n identical rows and JY contains n identical columns.

•	Two-dimensional, n-element floating-point arrays that uniquely specify the X subscripts (the IX array) and the Y subscripts (the JY array) of the points to be computed from the input array P.

In either case, IX must satisfy the expressions

0 <= MIN(IX) < N0  and 0 < MAX(IX) <= N0

where N0 is the total number of columns in the array  P. JY must satisfy the expressions

0 <= MIN(JY) < M0  and 0 < MAX(JY) <= M0

where M0 is the total number of rows in the array P.

It is better to use two-dimensional arrays for IX and JY because the algorithm is somewhat faster. If IX and JY are specified as one-dimensional, the returned two-dimensional arrays IX and JY can be re-used on subsequent calls to take advantage of the faster 2D algorithm.

Example

Create a 3 x 3 floating point array P:

P = FINDGEN(3,3)

Suppose we wish to find the value of a point half way between the first and second elements of the first row of P. Create the subscript arrays IX and JY:

IX = 0.5	Define the X subscript.

JY = 0.0	Define the Y subscript.

Z = BILINEAR(P, IX, JY)	Interpolate.

PRINT, Z	Print the value at the point IX,JY within P.

IDL prints:

0.500000

Suppose we wish to find the values of a 2 x 2 array of points in P. Create the subscript arrays IX and JY:

IX = [[0.5, 1.9], [1.1, 2.2]]	Define the X subscripts.

JY = [[0.1, 0.9], [1.2, 1.8]]	Define the Y subscripts.

Z = BILINEAR(P, IX, JY)	Interpolate.

PRINT, Z	Print the array of values.

IDL prints:

0.800000    4.60000

4.70000     7.40000

See Also

INTERPOL, INTERPOLATE, KRIG2D


BIN_DATE

The BIN_DATE function converts a standard form ASCII date/time string to a binary string. The function returns a six-element integer array where:

•	Element 0 is the year (e.g., 1994)

•	Element 1 is the month (1-12)

•	Element 2 is the day (1-31)

•	Element 3 is the hour (0-23)

•	Element 4 is minutes (0-59)

•	Element 5 is seconds (0-59)

This routine is written in the IDL language. Its source code can be found in the file bin_date.pro  in the lib subdirectory of the IDL distribution.

Calling Sequence

Result = BIN_DATE(Ascii_Time)

Arguments

Ascii_Time

A string containing the date/time to convert in standard ASCII format. If this argument is omitted, the current date/time is used. Standard form is a 24 character string:

DOW MON DD HH:MM:SS YYYY

where DOW is the day of the week, MON is the month, DD is the day of month, HH:MM:SS is the time in hours, minutes, second, YYYY is the year.

See Also

CALDAT, JULDAY, SYSTIME


BINDGEN

The BINDGEN function returns a byte array with the specified dimensions. Each element of the array is set to the value of its one-dimensional subscript.

Calling Sequence

Result = BINDGEN(D1, ...,Dn)

Arguments

Di

The dimensions of the result. The dimension parameters can be any scalar expression. Up to eight dimensions can be specified.

Example

To create a four-element by four-element byte array, and store the result in the variable A, enter:

A = BINDGEN(4,4)

Each element in A holds the value of its one-dimensional subscript. That is, if you enter the command:

PRINT, A

IDL prints the result:

   0   1   2   3

   4   5   6   7

   8   9  10  11

  12  13  14  15

See Also

CINDGEN, DCINDGEN, DINDGEN, FINDGEN, INDGEN, LINDGEN, SINDGEN


BINOMIAL

The BINOMIAL function computes the probability that in a cumulative binomial (Bernouli) distribution, a random variable X is greater than or equal to a user-specified value V, given N independent performances and a probability of occurrence or success P in a single performance.

This routine is written in the IDL language. Its source code can be found in the file binomial.pro in the lib subdirectory of the IDL distribution.

Calling Sequence

Result = BINOMIAL(V, N, P)

Arguments

V

A non-negative integer specifying the minimum number of times the event occurs in N independent performances.

N

A non-negative integer specifying the number of performances. If the number of performances exceeds 25, the Gaussian distribution is used to approximate the cumulative binomial distribution.

P

A non-negative single- or double-precision floating-point scalar, in the interval [0.0, 1.0], that specifies the probability of occurrence or success of a single independent performance.

Examples

Compute the probability of obtaining at least two 6s in rolling a die four times. The result should be 0.131944.

result = binomial(2, 4, 1.0/6.0)

Compute the probability of obtaining exactly two 6s in rolling a die four times. The result should be 0.115741.

result = binomial(2, 4, 1./6.) - binomial(3, 4, 1./6.)

Compute the probability of obtaining three or fewer 6s in rolling a die four times. The result should be 0.999228.

result = (binomial(0, 4, 1./6.) - binomial(1, 4, 1./6.)) + $

(binomial(1, 4, 1./6.) - binomial(2, 4, 1./6.)) + $

(binomial(2, 4, 1./6.) - binomial(3, 4, 1./6.)) + $

(binomial(3, 4, 1./6.) - binomial(4, 4, 1./6.))

See Also

CHISQR_PDF, F_PDF, GAUSS_PDF, T_PDF


BLK_CON

The BLK_CON function computes a "fast convolution" of a digital signal and an impulse-response sequence. It returns the filtered signal.

This routine is written in the IDL language. Its source code can be found in the file blk_con.pro in the lib subdirectory of the IDL distribution.

Calling Sequence

Result = BLK_CON(Filter, Signal)

Arguments

Filter

A P-element floating-point vector containing the impulse-response sequence of the digital filter.

Signal

An n-element floating-point vector containing the discrete signal samples.

Keywords

B_LENGTH

A scalar specifying the block length of the subdivided signal segments. If this parameter is not specified, a near-optimal value is chosen by the algorithm based upon the length P of the impulse-response sequence. If P is a value less than 11 or greater than 377, then B_LENGTH must be specified.

B_LENGTH must be greater than the filter length, P, and less than the number of signal samples.

Example

Create a filter of length P = 32:

filter = REPLICATE(1.0,32)	Set all points to 1.0

filter(2*INDGEN(16)) = 0.5	Set even points to 0.5

Create a sampled signal with random noise:

signal = SIN((FINDGEN(1000)/35.0)^2.5)

noise = (RANDOMU(SEED,1000)-.5)/2.

signal = signal + noise

 Convolve the filter and signal using block convolution:

result = BLK_CON(filter, signal)

See Also

CONVOL


BOX_CURSOR

The BOX_CURSOR procedure emulates the operation of a variable-sized box cursor (also known as a "marquee" selector).

This routine is written in the IDL language. Its source code can be found in the file box_cursor.pro in the lib subdirectory of the IDL distribution.

Using BOX_CURSOR

Once the box cursor has been realized, hold down the left mouse button to move the box by dragging. Hold down the middle mouse button to resize the box by dragging. (The corner nearest the initial mouse position is moved.) Press the right mouse button to exit the procedure and return the current box parameters.

Calling Sequence

BOX_CURSOR, [ X0, Y0, NX, NY ]

Arguments

X0, Y0

Named variables that will contain the coordinates of the lower left corner of the box cursor.

NX, NY

Named variables that will contain the width and height of the cursor, in pixels.

Keywords

INIT

If this keyword is set, the arguments X0, Y0, NX, and NY contain the initial position and size of the box.

FIXED_SIZE

If this keyword is set, NX and NY contain the initial size of the box. This size may not be changed by the user.

MESSAGE

If this keyword is set, IDL prints a message describing operation of the cursor.

See Also

CURSOR, CURSOR_CROSSHAIR keyword, CURSOR_IMAGE keyword, CURSOR_STANDARD keyword, CURSOR_XY keyword


BREAKPOINT

The BREAKPOINT procedure allows you to insert and remove breakpoints in programs for debugging. A breakpoint causes program execution to stop after the designated statement is executed. Breakpoints are specified using the source file name and line number. You can insert breakpoints in programs without editing the source file. Use the command:

HELP, /BREAKPOINT

to display the breakpoint table which gives the index, module and source file locations of each breakpoint.

Calling Sequence

BREAKPOINT [, File], Index

Arguments

File

An optional string argument that contains the name of the source file. Note that if File is not in the current directory, the full path name must be specified even if File is in one of the directories specified by !PATH.

Index

The line number at which to clear or set a breakpoint.

Keywords

AFTER

Set this keyword equal to an integer n. Execution will stop only after the nth time the breakpoint is hit. For example:

BREAKPOINT, /SET, 'test.pro', 8, AFTER=3

sets a breakpoint at the eighth line of the file test.pro, but only stops execution after the breakpoint has been encountered three times.

CLEAR

Set this keyword to remove a breakpoint. The breakpoint to be removed is specified either by index, or by the source file and line number. Use command HELP, /BREAKPOINT to display the indices of existing breakpoints. For example:

BREAKPOINT, /CLEAR, 3	Clear breakpoint with an index of 3.

BREAKPOINT, /CLEAR, 'test.pro',8
Clear the breakpoint corresponding to the statement in the file test.pro, line number 8.

ONCE

Set this keyword to make the breakpoint temporary. If ONCE is set, the breakpoint is cleared as soon as it is hit. For example:

BREAKPOINT, /SET, 'file.pro', 12, AFTER=3, /ONCE

sets a breakpoint at line 12 of file.pro. Execution stops when line 12 is encountered the third time, and the breakpoint is automatically cleared.

SET

Set this keyword to set a breakpoint at the designated source file line. If this keyword is set, the first input parameter, File must be a string expression that contains the name of the source file. The second input parameter must be an integer that represents the source line number.

For example, to set a breakpoint at line 23 in the source file xyz.pro, enter:

BREAKPOINT, /SET, 'xyz.pro', 23

See Also

"Executive Commands" on page 2-10 of the IDL User's Guide.


BROYDEN

The BROYDEN function solves a system of n nonlinear equations in n dimensions using a globally-convergent Broyden's method. The result is an n-element vector containing the solution.

BROYDEN is based on the routine broydn described in section 9.7 of Numerical Recipes in C: The Art of Scientific Computing (Second Edition), published by Cambridge University Press, and is used by permission.

Calling Sequence

Result = BROYDEN(X, Vecfunc)

Arguments

X

An n-element vector containing an initial guess at the solution of the system.

Vecfunc

A scalar string specifying the name of a user-supplied IDL function that defines the system of non-linear equations. This function must accept a vector argument X and return a vector result.

For example, suppose we wish to solve the following system:

3x  ­ cos(yz) ­ 1/2 = 0

x^2 ­ 81(y + 0.1)^2 + sinz + 1.06 = 0

e^-xy + 20z + (10π ­ 3)/3 = 0

To represent this system, we define an IDL function named BROYFUNC:

FUNCTION broyfunc, X

  RETURN, [3.0 * X(0) - COS(X(1)*X(2)) - 0.5,$

  X(0)^2 - 81.0*(X(1) + 0.1)^2 + SIN(X(2)) + 1.06,$

  EXP(-X(0)*X(1)) + 20.0 * X(2) + (10.0*!PI - 3.0)/3.0]

END

Keywords

CHECK

BROYDEN calls an internal function named fmin() to determine whether the routine has converged to a local rather than a global minimum (see Numerical Recipes, section 9.7). Use the CHECK keyword to specify a named variable which will be set to 1 if the routine has converged to a local minimum or to 0 if not. If the routine does converge to a local minimum, try restarting from a different initial guess to obtain the global minimum.

DOUBLE

Set this keyword to force the computation to be done in double-precision arithmetic.

ITMAX

Use this keyword to specify the maximum allowed number of iterations. The default is 200.

STEPMAX

Use this keyword to specify the scaled maximum step length allowed in line searches. The default value is 100.0.

TOLF

Set the convergence criterion on the function values. The default value is 1.0 x 10^-4.

TOLMIN

Set the criterion for deciding whether spurious convergence to a minimum of the function fmin() has occurred. The default value is 1.0 x 10^-6.

TOLX

Set the convergence criterion on X. The default value is 1.0 x 10^-7.

Example

We can use BROYDEN to solve the non-linear system of equations defined by the BROYFUNC function above:

X = [-1.0, 1.0, 2.0]	Provide an initial guess as the algorithm's starting point.

result = BROYDEN(X, 'BROYFUNC')	Compute the solution.

PRINT, result	Print the result.

IDL prints:

   0.500000  -1.10731e-07  -0.523599

The exact solution (to eight-decimal accuracy) is [0.5, 0.0, -0.52359877].

See Also

FX_ROOT, NEWTON, FZ_ROOTS


BYTARR

The BYTARR function returns a byte vector or array.

Calling Sequence

Result = BYTARR(D1, ..., Dn)

Arguments

Di

The dimensions of the result. The dimension parameters can be any scalar expression. Up to eight dimensions can be specified.

Keywords

NOZERO

Normally, BYTARR sets every element of the result to zero. If the NOZERO keyword is set, this zeroing is not performed (array elements contain random values) and BYTARR executes faster.

Example

To create B as a 3 by 3 by 5 byte array where each element is set to zero, enter:

B = BYTARR(3, 3, 5)

See Also

COMPLEXARR, DBLARR, FLTARR, INTARR, LONARR, MAKE_ARRAY, STRARR


BYTE

The BYTE function returns a result equal to Expression converted to byte type. If Expression is a string, each string is converted to a byte vector of the same length as the string. Each element of the vector is the character code of the corresponding character in the string. The BYTE function can also be used to extract data from Expression and place it in a byte scalar or array without modification, if more than one parameter is present. See the description in Chapter 4 of the IDL User's Guide for details.

Calling Sequence

Result = BYTE(Expression[, Offset [, Dim1, ..., Dimn]])

Arguments

Expression

The expression to be converted to type byte.

Offset

The byte offset from the beginning of Expression. Specifying this argument allows fields of data extracted from Expression to be treated as byte data without conversion.

Di

When extracting fields of data, the Di arguments specify the dimensions of the result. The dimension parameters can be any scalar expression. Up to eight dimensions can be specified. If no dimension arguments are given, the result is taken to be scalar.

Example

If the variable A contains the floating-point value 10.0, it can be converted to byte type and saved in the variable B by entering:

B = BYTE(A)

See Also

COMPLEX, DCOMPLEX, DOUBLE, FIX, FLOAT, LONG, STRING


BYTEORDER

The BYTEORDER procedure converts integers between host and network byte ordering or floating-point values between the native format and XDR (IEEE) format. This routine can also be used to swap the order of bytes within both short and long integers. If the type of byte swapping is not specified via one of the keywords below, bytes within short integers are swapped (even and odd bytes are interchanged).

The size of the parameter, in bytes, must be evenly divisible by two for short integer swaps, and by four for long integer swaps. BYTEORDER operates on both scalars and arrays. The parameter must be a variable, not an expression or constant, and may not contain strings. The contents of Variable are overwritten by the result.

Network byte ordering is "big endian". That is, multiple byte integers are stored in memory beginning with the most significant byte.

Calling Sequence

BYTEORDER, Variable1, ..., Variablen

Arguments

Variablen

A named variable (not an expression or constant) that contains the data to be converted. The contents of Variable are overwritten by the new values.

Keywords

DTOXDR

Set this keyword to convert native double-precision to XDR (IEEE) format. VAX users should see the cautionary note below.

FTOXDR

Set this keyword to convert native single-precision to XDR (IEEE) format. VAX users should see the cautionary note below.

HTONL

Set this keyword to perform host to network conversion, longwords.

HTONS

Set this keyword to perform host to network conversion, short integers.

LSWAP

Set this keyword to perform a longword swap. Swap the order of the bytes within each longword. For example, the four bytes within a longword are changed from (B0, B1, B2, B3), to (B3, B2, B1, B0).

NTOHL

Set this keyword to perform network to host conversion, longwords.

NTOHS

Set this keyword to perform network to host conversion, short integers.

SSWAP

Set this keyword to perform a short word swap. Swap the bytes within short integers. The even and odd numbered bytes are interchanged. This is the default action, if no other keyword is set.

XDRTOD

Set this keyword to convert XDR (IEEE) format to native double-precision floating-point. VAX users should see the cautionary note below.

XDRTOF

Set this keyword to convert XDR (IEEE) format to native single-precision floating-point. VAX users should see the cautionary note below.

VAX Warning

Do not attempt to interpret an XDR format floating-point number as a native floating number on a VAX. They are two entirely different things. VAXen generate an illegal instruction trap when the CPU encounters illegal floating-point values. Under VAX/VMS, the illegal value is automatically replaced with zero and execution continues. Some of the bit patterns resulting from conversion to XDR format are illegal VAX floating values. The resulting interactions can be confusing.

For example, the following series of statements work as expected:

a = 1.0

BYTEORDER, a, /FTOXDR

BYTEORDER, a, /XDRTOF

PRINT, a

IDL prints:

1.0

However, the following on a VMS system produces an error because of an attempt to interpret an XDR floating point number as a native floating point number:

a = 1.0

BYTEORDER, a, /FTOXDR

PRINT, a

IDL prints:

0

BYTEORDER, a, /XDRTOF

PRINT, a

IDL prints:

0

The illegal floating value is replaced by zero, resulting in the wrong answer. On an Ultrix system, IDL would have crashed. This problem can be avoided in two ways:

•	Avoid any operation that would result in the data in the XDR format variable having its data explicitly interpreted as floating point data. This is why the first example above worked.

•	Keep the binary data in an integer array. For instance:

a = LONG(1.0, 0, 1)

BYTEORDER, a, /FTOXDR

PRINT, a

32831

BYTEORDER, a, /XDRTOF

PRINT, FLOAT(a, 0, 1)

1.0

See Also

SWAP_ENDIAN


BYTSCL

The BYTSCL function scales all values of Array that lie in the range (Min ≤ x ≤ Max) into the range (0 ≤ x  ≤ Top). The returned result has the same structure as the original parameter and is of byte type.

Calling Sequence

Result = BYTSCL(Array)

Arguments

Array

The array to be scaled and converted to bytes.

Keywords

MAX

The maximum value of Array to be considered. If MAX is not provided, Array is searched for its maximum value. All values greater or equal to MAX are set equal to TOP in the result.

MIN

The minimum value of Array to be considered. If MIN is not provided, Array is searched for its minimum value. All values less than or equal to MIN are set equal to 0 in the result.

NAN

Set this keyword to cause the routine to check for occurrences of the IEEE floating-point value NaN in the input data. Elements with the value NaN are treated as missing data. (See  "Special Floating-Point Values" on page 11-9 of the IDL User's Guide for more information on IEEE floating-point values.)

TOP

The maximum value of the scaled result. If TOP is not specified, 255 is used. Note that the minimum value of the scaled result is always 0.

Example

BYTSCL is often used to scale images into the appropriate range for 8-bit displays. As an example, enter the following commands:

IM = DIST(200)	Create a simple image array.

TV, IM	Display the array as an image.

Now scale the image into the full range of bytes (0 to 255) and re-display it by entering:

IM = BYTSCL(IM)	Byte scale the image and store the result in the same variable.

TV, IM	Display the new image.

See Also

BYTE, TVSCL


C_CORRELATE

The C_CORRELATE function computes the cross correlation Pxy(L ) or cross covariance Rxy(L) of two sample populations X and Y as a function of the lag L.

where x  andy  are the means of the sample populations x = (x0, x1, x2, ... , xN-1) and y = (y0, y1, y2, ... , yN-1), respectively.

This routine is written in the IDL language. Its source code can be found in the file c_correlate.pro in the lib subdirectory of the IDL distribution.

Calling Sequence

Result = C_CORRELATE(X, Y, Lag)

Arguments

X

An n-element integer, single-, or double-precision floating-point vector.

Y

An n-element integer, single-, or double-precision floating-point vector.

Lag

A scalar or n-element integer vector in the interval [-(n-2), (n-2)], specifying the signed distances between indexed elements of X.

Keywords

COVARIANCE

Set this keyword to compute the sample cross covariance rather than the sample cross correlation.

Example

Define two n-element sample populations.

X = [3.73, 3.67, 3.77, 3.83, 4.67, 5.87, 6.70, 6.97, 6.40, 5.57]

Y = [2.31, 2.76, 3.02, 3.13, 3.72, 3.88, 3.97, 4.39, 4.34, 3.95]

Compute the cross correlation of X and Y for LAG = -5, 0, 1, 5, 6, 7

lag = [-5, 0, 1, 5, 6, 7]

result = C_CORRELATE(X, Y, lag)

PRINT, result

IDL prints:

-0.448655  0.915846  0.628814  -0.393466  -0.350169  -0.282198

See Also

A_CORRELATE, CORRELATE, M_CORRELATE, P_CORRELATE, R_CORRELATE


CALDAT

The CALDAT procedure computes the month, day and year corresponding to a given Julian date. The inverse of this procedure is JULDAY.

This routine is written in the IDL language. Its source code can be found in the file caldat.pro in the lib subdirectory of the IDL distribution.

Calling Sequence

CALDAT, Julian, Month, Day, Year

Arguments

Julian

A longword integer that specifies the Julian Day Number (which begins at noon) to be converted to a calendar date.

Month

A named variable that, on output, contains the number of the desired month (1 = January, ..., 12 = December).

Day

A named variable that, on output, contains the number of day of the month (1-31).

Year

A named variable that, on output, contains the number of the desired year (e.g., 1994).

Example

CALDAT, 2449587, D, M, Y	Find date corresponding to Julian day 2449587.

PRINT, D, M, Y	IDL prints: 8 22 1994. The Julian day corresponds to August 22, 1994.

See Also

BIN_DATE, JULDAY, SYSTIME


CALENDAR

The CALENDAR procedure displays a calendar for a month or an entire year on the current plotting device. This IDL routine imitates the Unix cal command.

This routine is written in the IDL language. Its source code can be found in the file calendar.pro in the lib subdirectory of the IDL distribution.

Calling Sequence

CALENDAR [[, Month] , Year]

Arguments

Month

The number of the month for which a calendar is desired (1 is January, 2 is February, ..., 12 is December). If called without arguments, CALENDAR draws a calendar for the current month.

Year

The number of the year for which a calendar should be drawn. If YEAR is provided without MONTH, a calendar for the entire year is drawn. If called without arguments, CALENDAR draws a calendar for the current month.

Example

CALENDAR, 5, 1995	Display a calendar for May, 1995.

See Also

SYSTIME


CALL_EXTERNAL

The CALL_EXTERNAL function calls a function in an external sharable object and returns a scalar value. Parameters can be passed by reference (the default) or by value. See Chapter 18 of the IDL User's Guide for examples.

CALL_EXTERNAL is supported on VMS systems, some Unix systems (including some versions of SunOS, HPUX and AIX), under Microsoft Windows, and on the Macintosh.

This function requires no interface routines and is much simpler and easier to use than the LINKIMAGE procedure. However, CALL_EXTERNAL performs no checking of the type and number of parameters. Programming errors are likely to cause IDL to crash or to corrupt your data.

♦	UNIX: Only available on systems that support dynamic linking. Routines written in other languages that adhere to the C (argc, argv) calling convention, and linked as a sharable object library can be dynamically added and called from IDL.

♦	VMS: Routines written in any language that adheres to the VMS calling convention may be easily called using the CALL_EXTERNAL function.

♦	Windows: Windows-compatible DLLs that adhere to the C (argc, argv) calling convention can be called from IDL. Note that only 32-bit, win32s DLLs are supported under Windows 3.1.

♦	Macintosh: Stand Alone Code resources of resource type CUST (680X0-based machines) or sharable libraries (PowerPC machines) can be called from IDL.

The result of the CALL_EXTERNAL function is the scalar returned by the external function. By default, this is a longword scalar integer, unless the D_VALUE, F_VALUE, or S_VALUE keywords are specified, indicating that the function returns a double, single floating point, or string value respectively.

Calling Sequence

Result = CALL_EXTERNAL(Image, Entry [, P0, ..., PN-1])

Arguments

Image

The name of the file, which must be a sharable image (VMS), sharable object library (Unix), DLL (Windows), CUST resource or shared library (Macintosh) which contains the routine to be called.

♦	UNIX: This argument is a pathname which specifies the sharable object file to be loaded.

♦	VMS: This argument may contain only the file name. File type, and device/directory specification strings are not allowed. If the sharable image file is not in SYS$SHARE, a logical name or the DEFAULT file name keyword parameter must be used to direct LIB$FIND_IMAGE_SYMBOL to locate the correct file.

♦	Windows: This argument is a pathname which specifies the DLL to be loaded.

♦	Macintosh: This argument is a pathname to the file which includes the CUST resource or shared library to be loaded.

Entry

The entry point of the procedure or function.

♦	UNIX, VMS: A string containing the name of the universal symbol which is the entry point of the procedure or function.

♦	Windows: A string containing the name of the exported DLL procedure.

♦	Macintosh: A string containing the name of the CUST resource (680X0 machines) or routine name (PowerPC machines).

P0, ..., PN-1

The parameters to be passed to the external routine. The passing mechanism is by either reference or value, according to the setting of the VALUE keyword.

String Parameters
 Under Unix, VMS, and the Macintosh OS, strings passed by reference pass the address of their descriptor. Strings passed by value pass the address of the null-terminated string. String arrays are passed via a pointer to an array of string descriptors.

Under Windows, string parameters are always passed via a pointer to the string or array of strings. Note that the VALUE keyword has no effect for string parameters.

The definition of a string descriptor, as written in C, is:

typedef struct {

    unsigned short length;

    short reserved;

    char *s;

} STRING;

Warning: Do not change the contents of the string or its descriptor.

Non-string Parameters
Non-string scalars and arrays, and all structures, are passed by reference unless the VALUE keyword parameter is used to indicate a scalar is to be passed by value. Care must be taken to ensure that the type, structure, and passing mechanism of the parameters passed to the external routine match what it expects.

♦	UNIX, Windows, Macintosh: Routines are called with an argc argument count, and an argv[] array of arguments or pointers to arguments. Parameters passed by value and addresses of parameters passed by reference are placed in the argv[] array. A typical C function prototype is:

int xxx(int argc, void *argv[])

♦	VMS: Routines are called with N arguments. In Fortran, a typical routine is declared:

INTEGER *4 FUNCTION XXX(P1, P2, ..., PN)

Keywords

ALL_VALUE (Windows Only)

Set this keyword to indicate that all parameters are passed by value.

DEFAULT (VMS Only)

A string containing the default device, directory, file name, and file type information for the file that contains the sharable image. This optional keyword parameter must be used if the sharable image is not in SYS$SHARE or no logical name exists that corresponds to the Image argument.

D_VALUE (UNIX, VMS, Macintosh)

If set, this keyword indicates that the called function returns a double-precision floating value.

F_VALUE (UNIX, VMS, Macintosh)

If set, this keyword indicates that the called function returns a single-precision floating value.

S_VALUE (All Platforms)

If set, this keyword indicates that the called function returns a pointer to a null-terminated string.

VALUE (UNIX, VMS, Windows)

A byte array, with as many elements as there are optional parameters, indicating the method of parameter passing. Arrays are always passed by reference. If parameter P is a scalar, P is passed by reference if VALUE(i) is 0; and by value if it is non-zero. Passing a scalar string parameter by value passes the address of the first byte of the null-terminated string. Your routine must not alter the contents of such a string.

Note that under Windows, this keyword is ignored for string parameters.

Example

See Chapter 18 of the IDL User's Guide for examples using CALL_EXTERNAL.

See Also

LINKIMAGE


CALL_FUNCTION

CALL_FUNCTION calls the IDL function specified by the string Name, passing any additional parameters as its arguments. The result of the called function is passed back as the result of this routine.

Although not as flexible as the EXECUTE function, CALL_FUNCTION is much faster. Therefore, CALL_FUNCTION should be used in preference to EXECUTE whenever possible.

Calling Sequence

Result = CALL_FUNCTION(Name [, P1, ..., Pn])

Arguments

Name

A string containing the name of the function to be called. This argument can be a variable, which allows the called function to be determined at runtime.

Pi

The arguments to be passed to the function given by Name. These arguments are the positional and keyword arguments documented for the called function, and are passed to the called function exactly as if it had been called directly.

Example

The following command indirectly calls the IDL function SQRT (the square root function) with an argument of 4 and stores the result in the variable R:

R = CALL FUNCTION('SQRT', 4)

See Also

CALL_PROCEDURE, EXECUTE


CALL_PROCEDURE

CALL_PROCEDURE calls the procedure specified by Name, passing any additional parameters as its arguments.

Although not as flexible as the EXECUTE function, CALL_PROCEDURE is much faster. Therefore, CALL_PROCEDURE should be used in preference to EXECUTE whenever possible.

Calling Sequence

CALL_PROCEDURE, Name [, P1, ..., Pn]

Arguments

Name

A string containing the name of the procedure do be called. This argument can be a variable, which allows the called procedure to be determined at runtime.

Pi

The arguments to be passed to the procedure given by Name. These arguments are the positional and keyword arguments documented for the called procedure, and are passed to the called procedure exactly as if it had been called directly.

Example

The following example shows how to call the PLOT procedure indirectly with a number of arguments. First, create a dataset for plotting by entering:

B = FINDGEN(100)

Call PLOT indirectly to create a polar plot by entering:

CALL_PROCEDURE, 'PLOT', B, B, /POLAR

A "spiral" plot should appear.

See Also

CALL_FUNCTION, EXECUTE


CATCH

The CATCH procedure provides a generalized mechanism for the handling of exceptions and errors within IDL. Calling CATCH establishes an error handler for the current procedure that intercepts all errors that can be handled by IDL, excluding non-fatal warnings such as math errors.

When an error occurs, each active procedure, beginning with the offending procedure and proceeding up the call stack to the main program level, is examined for an error handler. If an error handler is found, control resumes at the statement after the call to CATCH. The index of the error is returned in the argument to CATCH. The !ERROR (or !SYSERROR) and !ERR_STRING (or !SYSERR_STRING) system variables are also set. If no error handlers are found, program execution stops, an error message is issued, and control reverts to the interactive mode. A call to ON_IOERROR in the procedure that causes an I/O error supersedes CATCH, and takes the branch to the label defined by ON_IOERROR.

This mechanism is similar, but not identical to, the setjmp/longjmp facilities in C and the catch/throw facilities in C++.

Error handling is discussed in more detail in Chapter 11 of the IDL User's Guide.

Calling Sequence

CATCH, Variable

Arguments

Variable

A named variable in which the error index is returned. When an error handler is established by a call to CATCH, Variable is set to zero. If an error occurs, Variable is set to the error index, and control is transferred to the statement after the call to CATCH.

Keywords

CANCEL

Set this keyword to cancel the error handler for the current procedure. This cancellation does not affect other error handlers that may be established in other active procedures.

Example

The following procedure illustrates the use of CATCH:

PRO ABC

A = FLTARR(10)	Define variable A.

CATCH, Error_status	Establish error handler. When errors occur, the index of the error is returned in the variable Error_status.

IF Error_status NE 0 THEN BEGIN	This statement begins the error handler.

        PRINT, 'Error index: ', Error_status

        PRINT, 'Error message:', !ERR_STRING

        A=FLTARR(12)	Handle the error by extending A.

        ENDIF

A(11)=12	Cause an error.

HELP, A	Even though an error occurs in the line above, program execution continues to this point because the event handler extended the definition of A so that the statement can be re-executed.

END

Running the ABC procedure causes IDL to produce the following output and control returns to the interactive prompt:

Error index:         -101

Error message:

Attempt to subscript A with <INT (      11)> is out of range.

A               FLOAT     = Array(12)

See Also

ON_ERROR, ON_IOERROR, See "Error-Handling Routines" on page 11-2 of the IDL User's Guide.


CD

The CD procedure is used to set and/or change the current working directory. This routine changes the working directory for the IDL session and any child processes started from IDL during that session after the directory change is made. Under Unix, CD does not affect the working directory of the process that started IDL. The PUSHD, POPD, and PRINTD procedures provide a convenient interface to CD.

Calling Sequence

CD [, Directory]

Arguments

Directory

A scalar string specifying the path of the new working directory. If Directory is specified as a null string, the working directory is changed to the user's home directory. If this argument is not specified, the working directory is not changed.

Keywords

CURRENT

If CURRENT is present, it specifies a named variable into which the current working directory is stored as a scalar string. The returned directory is the working directory before the directory is changed. Thus, you can obtain the current working directory and change it in a single statement:

CD, new_dir, CURRENT=old_dir

Example

Under Unix, to change the working directory to the "data" subdirectory of the current directory, enter:

CD, 'data'

Under VMS, you could use:

CD, '[.data]'

See Also

PUSHD, POPD


CDF_ATTCREATE

The CDF_ATTCREATE function creates a new attribute in the specified Common Data Format file. If successful, the attribute ID is returned.

Calling Sequence

Result = CDF_ATTCREATE(Id, Attribute_Name)

Arguments

Id

The CDF ID of the file for which a new attribute is created, returned from a previous call to CDF_OPEN or CDF_CREATE.

Attribute_Name

A string containing the name of the attribute to be created.

Keywords

GLOBAL_SCOPE

Set this keyword to make the scope of the attribute global. This is the default.

VARIABLE_SCOPE

Set this keyword to indicate that the attribute's scope is per variable.

Example

id = CDF_OPEN('test')

xx = CDF_ATTCREATE(id, 'Attribute-1', /GLOBAL_SCOPE)

CDF_ATTRENAME, id, 'Attribute-1', 'My Favorite Attribute'

PRINT, CDF_ATTNUM(id, 'My Favorite Attribute')


CDF_ATTGET

The CDF_ATTGET procedure reads an attribute entry from a Common Data Format file.

Calling Sequence

CDF_ATTGET, Id, Attribute, EntryNum, Value

Arguments

Id

The CDF ID, returned from a previous call to CDF_OPEN or CDF_CREATE.

Attribute

A string containing the name of the attribute or the attribute number to be written.

EntryNum

The entry number. If the attribute is global in scope, this has meaning only to the application. If the attribute is variable in scope, this is either the name or number of the variable the attribute is to be associated with.

Value

A named variable in which the value of the attribute is returned.

Keywords

ZVARIABLE

If EntryNum is a variable ID (as opposed to a variable name) and the variable is a zVariable, set this flag to indicate that the variable ID is a zVariable ID. The default is to assume that EntryNum is an rVariable ID. Note: the attribute must have a scope of VARIABLE_SCOPE.

Example

CDF_ATTGET, id, 'Att2', 'Var2', x

PRINT, x


CDF_ATTINQ

The CDF_ATTINQ procedure obtains information about a specified attribute in a Common Data Format file.

Calling Sequence

CDF_ATTINQ, Id, Attribute, Name, Scope, MaxEntry, MaxZEntry

Arguments

Id

The CDF ID of the file containing the desired attribute, returned from a previous call to CDF_OPEN or CDF_CREATE.

Attribute

Either a string containing the name of the attribute or the attribute number to be inquired.

Name

A named variable in which the name of the attribute is returned.

Scope

A named variable in which a string, describing the scope of the attribute, is returned. This string will have one of the following values: "GLOBAL_SCOPE", "VARIABLE_SCOPE", "GLOBAL_SCOPE_ASSUMED", or "VARIABLE_SCOPE_ASSUMED".

MaxEntry

A named variable in which the maximum rVariable entry number for this attribute is returned.

MaxZEntry

A named variable in which the maximum zVariable entry number for this attribute is returned.

Example

cdfid= CDF_OPEN('/cdrom/ozone.8.20.92')

CDF_ATTINQ, cdfid, 0, name, scope, maxentry, maxzentry

PRINT, name, scope, maxentry, maxzentry


CDF_ATTNUM

The CDF_ATTNUM function returns the attribute number associated with a particular attribute in a Common Data Format file.

Calling Sequence

Result = CDF_ATTNUM(Id, Attribute_Name)

Arguments

Id

The CDF ID for the file that contains the desired attribute, returned from a previous call to CDF_OPEN or CDF_CREATE.

Attribute_Name

A string containing the name of the attribute.


CDF_ATTPUT

The CDF_ATTPUT procedure writes an attribute entry to a Common Data Format file. If the specified entry already exists, it is overwritten.

Calling Sequence

CDF_ATTPUT, Id, Attribute, EntryNum, Value

Arguments

Id

The CDF ID, returned from a previous call to CDF_OPEN or CDF_CREATE.

Attribute

A string containing the name of the attribute or the attribute number to be written.

EntryNum

The entry number. If the attribute is global in scope, this argument has meaning only to the application. If the attribute is variable in scope, this is either the name or number of the variable the attribute is to be associated with.

Value

The value(s) to be written.

Keywords

ZVARIABLE

If EntryNum is a variable ID (as opposed to a variable name) and the variable is a zVariable, set this flag to indicate that the variable ID is a zVariable ID. The default is to assume that EntryNum is an rVariable ID. Note: the attribute must have a scope of VARIABLE_SCOPE.

Example

Id= CDF_CREATE('foo',/VAX,/ROW_MAJOR) ; no dimensions

dummy= CDF_VARCREATE(id, 'Var1', /CDF_INT4, /REC_VARY)

v2= CDF_VARCREATE(id, 'Var2', /CDF_FLOAT, /REC_NOVARY)

dummy= CDF_ATTCREATE(id, 'Title', /VARIABLE)

dummy= CDF_ATTCREATE(id, 'Att2', /VARIABLE)

CDF_ATTPUT, id, 'Title', 'Var1', 'Temperature at surface'

CDF_ATTPUT, id, 'Title', v2, 'Time of recording'

CDF_ATTPUT, id, 'Att2', 'Var2', FINDGEN(10)


CDF_ATTRENAME

The CDF_ATTRENAME procedure is used to rename an existing attribute in a Common Data Format file.

Calling Sequence

CDF_ATTRENAME, Id, OldAttr, NewName

Arguments

Id

The CDF ID of the file containing the desired attribute, returned from a previous call to CDF_OPEN or CDF_CREATE.

OldAttr

A string containing the current name of the attribute or the attribute number to be renamed.

NewName

A string containing the new name for the attribute.


CDF_CLOSE

The CDF_CLOSE procedure closes the specified Common Data Format file. The CDF's data buffers are flushed, all of the CDF's open files are closed, and the CDF identifier is freed. You must use CDF_CLOSE to close a CDF to guarantee that all modifications you have made are actually written to disk.

Calling Sequence

CDF_CLOSE, Id

Arguments

Id

The CDF ID of the file to be closed, returned from a previous call to CDF_OPEN or CDF_CREATE.


CDF_CONTROL

The CDF_CONTROL procedure allows you to obtain or set information for a Common Data Format file, its variables, or its attributes.

Calling Sequence

CDF_CONTROL, Id

Arguments

Id

The CDF ID of the file being changed or queried, as retuned from a previous call to CDF_OPEN or CDF_CREATE.

Keywords

ATTRIBUTE

Makes the attribute specified the current attribute. Either an attribute name or an attribute number may be specified.

GET_ATTR_INFO

Set this keyword to a named variable which will contain information about the current attribute. Information is returned in the form of a structure with the following tags:

{ NUMGENTRIES:0L, NUMRENTRIES:0L, NUMZENTRIES:0L,

  MAXGENTRY:0L, MAXRENTRY:0L, MAXZENTRY:0L }

The first three tags contain the number of globals, rVariables, and zVariables associated with the attribute. MAXGENTRY contains the highest index used, and the last two tags contain the highest variable ids used that were used when setting the attribute's value.

Note that an attribute must be set before GET_ATTR_INFO can be used. For example:

CDF_CONTROL, id, ATTRIBUTE='ATT1', GET_ATTR_INFO=X

GET_COPYRIGHT

Set this keyword to a named variable which will contain the copyright notice of the CDF library now being used (as opposed to the library that was used to write the current CDF).

GET_FILENAME

Set this keyword to a named variable which will contain the pathname of the current CDF.

GET_NUMATTRS

Set this keyword to a named variable which will contain a two-element array of longs. The first value will contain the number of attributes with global scope, the second value will contain the number of attributes with variable scope. NOTE: attributes with GLOBAL_SCOPE_ASSUMED scope will be included in the global scope count and attributes with VARIABLE_SCOPE_ASSUMED will be included in the count of attributes with variable scope.

GET_VAR_INFO

Set this keyword to a named variable that will contain information about the current variable. Information is returned in the form of a structure with the following tags:

{ EXTENDRECS:0L, MAXREC:0L, PADVALUE:<as appropriate> }

The EXTENDRECS field will contain the number of records by which the current variable will be extended whenever a new record needs to be added. See Section 2.7.5 of the CDF User's Guide for more details.

The MAXREC field will contain the maximum record number for the current variable. For variables with a record variance of NOVARY this will be at most zero. A value of -1 indicates that no records have been written.

The PADVALUE field will contain the value being used to fill locations that are not explicitly filled by the user. See Section 2.7.12 of the CDF User's Guide for more details.

For example:

CDF_CONTROL, id, VARIABLE='VAR1', GET_VAR_INFO=X

SET_EXTENDRECS

Set this keyword equal to the number of additional physical records that should be added to the current variable whenever it needs to be extended.

SET_INITIALRECS

Set this keyword equal to the number of records that should be initially written to the current variable. Note that this keyword should be set before writing any data to the variable.

SET_PADVALUE

Set this keyword equal to the pad value for the current variable.

VARIABLE

Set this keyword to a name or index to set the current variable. For example,

CDF_CONTROL, id, VAR='MyData', SET_INITIALRECS=20

specifies that the variable MyData should have 20 records written to it initially.

Note that if VARIABLE is set to the index of a zVariable, the ZVARIABLE keyword should also be set.

ZVARIABLE

Set this keyword to TRUE if the current variable is a zVariable and is referred to by index. For example:

CDF_CONTROL, id, VARIABLE=0, /ZVARIABLE, GET_VAR_INFO=V


CDF_CREATE

The CDF_CREATE function creates a new Common Data Format file with the given filename and dimensions. If successful, this function returns the CDF ID for the new file.

Calling Sequence

Result = CDF_CREATE(Filename, [Dimensions])

Arguments

Filename

A scalar string containing the name of the file to be created. Note that if the desired filename has a .cdf ending, you can omit the extension and specify just the first part of the filename. For example, specifying "mydata" would open the file mydata.cdf.

Dimensions

A vector of values specifying size of each dimensions. If no dimensions are specified, then the file will contain a single scalar per record (i.e., a 0-dimensional CDF).

Keywords

COL_MAJOR

Set this keyword to specify column major (IDL-like) array ordering for variable storage.

HOST_ENCODING

Set this keyword to indicate that the file will use native data representation.

HP_ENCODING

Set this keyword to indicate HP data representation.

IBMRS_ENCODING

Set this keyword to indicate IBM RS/6000 series data representation.

MIPSEB_ENCODING

Set this keyword to indicate MIPSEB data representation (Silicon Graphics Iris and Power series).

MIPSEL_ENCODING

Set this keyword to indicate MIPSEL data representation (DECstation).

NETWORK_ENCODING

Set this keyword to indicate that the file will use network-transportable data representation (XDR). This is the default encoding.

ROW_MAJOR

Set this keyword to specify row major (C-like) array ordering for variable storage. This is the default.

SINGLE_FILE

Set this keyword to cause all CDF information (control information, attribute entry data, variable data, etc.) to be written to a single file. The default is to use the MULTI_FILE format where a separate file is created for each variable. See section 2.3.3 ("Performance") of the CDF User's Guide (version 2.3.0) for more information.

SUN_ENCODING

Set this keyword to indicate SUN data representation.

VAX_ENCODING

Set this keyword to indicate VAX data representation.


CDF_DELETE

The CDF_DELETE procedure deletes the specified Common Data Format file. Files deleted include the original .cdf file and the .v0, .v1, etc. files if they exist.

Calling Sequence

CDF_DELETE, Id

Arguments

Id

The CDF ID of the file to be deleted, returned from a previous call to CDF_OPEN or CDF_CREATE.


CDF_DOC

The CDF_DOC procedure retrieves general documentation information about a Common Data Format file.

Calling Sequence

CDF_DOC, Id, Version, Release, Copyright

Arguments

Id

A CDF ID, returned from a previous call to CDF_OPEN or CDF_CREATE.

Version

A named variable in which the version number of the CDF library that created the CDF is returned.

Release

A named variable in which the release number of the CDF library that created the CDF is returned.

Copyright

A named variable in which the copyright notice of the CDF library that created the CDF is returned.

Example

CDF_DOC,id,v,r,c

PRINT,'CDF Version',v,' Release',r

PRINT,c


CDF_EPOCH

The CDF_EPOCH procedure computes or breaks down CDF_EPOCH values in a Common Data Format file. When computing an epoch, any missing value is considered to be set to zero.

Calling Sequence

CDF_EPOCH, Epoch, Year [, Month, Day, Hour, Minute, Second, Milli]

Arguments

Epoch

The Epoch value to be broken down, or a named variable into which the computed epoch will be placed.

Year

The year (e.g., 1992) or a named variable.

Month

The month (1-12) or a named variable.

Day

The day (1-31) or a named variable.

Hour

The hour (0-23) or a named variable.

Minute

The minute (0-59) or a named variable.

Second

The second (0-59) or a named variable.

Milli

The millisecond (0-999) or a named variable.

Keywords

BREAKDOWN_EPOCH

If this keyword is set, Epoch is a value which will broken down and the resulting Year, Month, Day, etc. are returned in the remaining parameters which must be named variables.

COMPUTE_EPOCH

If this keyword is set, Epoch is a named variable into which the epoch is placed and the other parameters are values which will be used to compute the epoch.

Example

CDF_EPOCH, MergeDate, 1992, 9, 20, 3, /COMPUTE_EPOCH

CDF_EPOCH, 4.7107656e13, yr, mo, dy, hr, mn, sc, milli, /BREAK


CDF_ERROR

The CDF_ERROR function returns a string containing a short explanation of a given status code returned from a Common Data Format file.

Calling Sequence

Result = CDF_ERROR(Status)

Arguments

Status

The status code to be explained.


CDF_EXISTS

The CDF_EXISTS function returns true if the Common Data Format (CDF) scientific data format library is supported on the current IDL platform.

This routine is written in the IDL language. Its source code can be found in the file cdf_exists.pro in the lib subdirectory of the IDL distribution.

Calling Sequence

Result = CDF_EXISTS()

Example

The following IDL command prints an error message if the CDF library is not available:

IF CDF_EXISTS() EQ 0 THEN PRINT, 'CDF not supported.'


CDF_INQUIRE

The CDF_INQUIRE function returns global information about the Common Data Format file. This information is returned in a structure of the form:

{ NDIMS:0L, ENCODING:"", MAJORITY:"", MAXREC:0L, $

  NVARS:0L, NZVARS:0L, NATTS:0L, DIM:LONARR(NDIMS) }

The tags of this structure are described below.

Calling Sequence

Result = CDF_INQUIRE(Id)

Arguments

Id

A CDF ID, returned from a previous call to CDF_OPEN or CDF_CREATE.

 Explanation of the Structure Tags

NDIMS

The longword integer specifying the number of dimensions in the CDF.

ENCODING

A string describing the type of encoding used in the CDF file. For example, 'NETWORK_ENCODING' or 'VAX_ENCODING'.

MAJORITY

A string describing the majority used in the CDF file. For example, 'ROW_MAJOR'.

MAXREC

A longword integer specifying the highest record number written.

NVARS

A longword integer specifying the number of rVariables (regular variables) in the CDF.

NZVARS

A longword integer specifying the number of zVariables in the CDF.

NATTS

A longword integer specifying the number of attributes in the CDF.

DIM

A vector where each element contains the corresponding dimension size. For 0-dimensional CDF's, this argument contains a single element (a zero).


CDF_OPEN

The CDF_OPEN function opens an existing Common Data Format file. If successful, the CDF ID for the file is returned.

Calling Sequence

Result = CDF_OPEN(Filename)

Arguments

Filename

A scalar string containing the name of the file to be created. Note that if the desired filename has a .cdf ending, you can omit the extension and specify just the first part of the filename. For example, specifying "mydata" would open the file mydata.cdf.


CDF_VARCREATE

The CDF_VARCREATE function creates a new variable in a Common Data Format file.

Calling Sequence

Result = CDF_VARCREATE(Id, Name [, DimVary])

Arguments

Id

The CDF ID, returned from a previous call to CDF_OPEN or CDF_CREATE.

Name

A string containing the name of the variable to be created.

DimVary

A one-dimensional array containing one element per CDF dimension. If the element is non-zero or the string 'VARY', the variable will have variance in that dimension. If the element is zero or the string 'NOVARY' then the variable will have no variance with that dimension. If the variable is zero-dimensional, this argument may be omitted.

Keywords

You must specify the type variable being created. This is done by setting one of the following keywords:

•	CDF_BYTE	•	CDF_INT4

•	CDF_CHAR	•	CDF_REAL4

•	CDF_DOUBLE	•	CDF_REAL8

•	CDF_EPOCH	•	CDF_UCHAR

•	CDF_FLOAT	•	CDF_UINT1

•	CDF_INT1	•	CDF_UINT2

•	CDF_INT2	•	CDF_UINT4

If no type is specified, CDF_FLOAT is assumed.

Although all CDF variable types are supported within the file, IDL has full support only for the following CDF data types: CDF_DOUBLE, CDF_EPOCH, CDF_FLOAT, CDF_INT2, CDF_INT4, CDF_REAL4, CDF_REAL8, and CDF_UCHAR.

DIMENSIONS

Set this keyword to create a new zVariable with the specified dimensions. For example:

id = CDF_CREATE("cdffile.cdf", [100] )

zid = CDF_VARCREATE(id, "Zvar", [1,1,1], DIM=[10,20,30])

NUMELEM

The number of elements of the data type at each variable value. This keyword only has meaning for string data types (CDF_CHAR, CDF_UCHAR). This is the number of characters in the string. The default is 1.

REC_NOVARY

If this keyword is set, all records will contain the same information.

REC_VARY

If this keyword is set, all records will contain unique data. This is the default.

ZVARIABLE

A variable is assumed to be a zVariable if its dimensions are specified by the DIMENSIONS keyword. Set this keyword to create a zero-dimensional zVariable.

For example:

id = CDF_CREATE("cdffile.cdf", [100] )

zid = CDF_VARCREATE(id, "Zvar", /ZVARIABLE)

Example

Id= CDF_CREATE('mycdf',[100,100],/NETWORK_ENCODING)

VarId = CDF_VARCREATE(Id, 'Temp', ['VARY', 'NOVARY'], $

        /REC_NOVARY, /CDF_EPOCH)

VarId2 = CDF_VARCREATE(Id, 'Pressure', [1,0], $

         NUMELEM=10, /CDF_UCHAR)


CDF_VARGET

The CDF_VARGET procedure reads multiple values from a Common Data Format file variable. By default, all elements of a record are read. If INTERVAL, and/or OFFSET are specified but no COUNT is specified, CDF_VARGET attempts to get as many elements of each record as possible.

Calling Sequence

CDF_VARGET, Id, Variable, Value

Arguments

Id

The CDF ID, returned from a previous call to CDF_OPEN or CDF_CREATE

Variable

A string containing the name of the variable or the variable number being read.

Value

A named variable in which the values of the variable are returned.

Keywords

COUNT

An optional vector containing the counts to be used in reading Value. The default is to read all elements in each record, taking into account INTERVAL and OFFSET.

INTERVAL

A vector specifying the interval between values in each dimension. The default value is 1 for each dimension.

OFFSET

A vector specifying the array indices within the specified record(s) at which to begin writing. OFFSET is a 1-dimensional array containing one element per CDF dimension. The default value is zero for each dimension.

REC_COUNT

The number of records to read. The default is 1.

REC_INTERVAL

The interval between records when reading multiple records. The default value is 1.

REC_START

The record number at which to start reading. The default is 0.

ZVARIABLE

If Variable is a variable ID (as opposed to a variable name) and the variable is a zVariable, set this flag to indicate that the variable ID is a zVariable ID. The default is to assume that Variable is an rVariable ID.

Example

If V1 is a 100-element by 100-element array, the command:

CDF_VARGET, id, 'V1', X, OFFSET=[50,50], INTERVAL=[2,2]

returns X as a 25-element by 25-element array, containing V1([50, 52, ..., 98], [50, 52, ..., 98]).


CDF_VARGET1

The CDF_VARGET1 procedure reads one value from a Common Data Format file variable.

Calling Sequence

CDF_VARGET1, Id, Variable, Value

Arguments

Id

The CDF ID, returned from a previous call to CDF_OPEN or CDF_CREATE.

Variable

A string containing the name of the variable or the variable number to be read.

Value

A named variable in which the value of the variable is returned.

Keywords

OFFSET

A vector specifying the array indices within the specified record(s) at which to begin reading. OFFSET is a 1-dimensional array containing one element per CDF dimension. The default value is 0 for each dimension.

REC_START

The record number at which to start reading. The default is 0.

ZVARIABLE

If Variable is a variable ID (as opposed to a variable name) and the variable is a zVariable, set this flag to indicate that the variable ID is a zVariable ID. The default is to assume that Variable is an rVariable ID.


CDF_VARINQ

The CDF_VARINQ function returns a structure containing information about the specified variable in a Common Data Format file. This structure has the form:

{ IS_ZVAR:0, NAME:"", DATATYPE:"", NUMELEM:0L, $

  RECVAR:"", DIMVAR:BYTARR(...) [, DIM:LONARR(...)]}

Note: the DIM field is included in the structure only if IS_ZVAR is one. This structure's tags are explained below.

Calling Sequence

Result = CDF_VARINQ(Id, Variable)

Arguments

Id

The CDF ID, returned from a previous call to CDF_OPEN or CDF_CREATE.

Variable

A string containing the name of the variable or the variable number being inquired.

Keywords

ZVARIABLE

If Variable is a variable ID (as opposed to a variable name) and the variable is a zVariable, set this flag to indicate that the variable ID is a zVariable ID. The default is to assume that Variable is an rVariable ID.

Explanation of the Structure Tags

IS_ZVAR

This field will contain a 1 if the variable is a zVariable or a 0 if it is an rVariable.

NAME

The name of the variable.

DATATYPE

A string describing the data type of the variable. The string has the form 'CDF_XXX' where XXX is FLOAT, DOUBLE, EPOCH, UCHAR, etc.

NUMELEM

The number of elements of the data type at each variable value. This is always 1 except in the case of string type variables (CDF_CHAR, CDF_UCHAR).

RECVAR

A string describing the record variance of the variable. This is either the string 'VARY' or 'NOVARY'.

DIMVAR

An array of bytes. The value of each element is zero if there is no variance with that dimension and one if there is variance. For zero-dimensional CDFs, DIMVAR will have one element whose value is zero.

DIM

An array of longs. The value of each element corresponds to the dimension of the variable. This field is only included in the structure if the variable is a zVariable.


CDF_VARNUM

The CDF_VARNUM function returns the variable number associated with a given variable name in a Common Data Format file.

Calling Sequence

Result = CDF_VARNUM(Id, VarName [, IsZVar])

Arguments

Id

The CDF ID, returned from a previous call to CDF_OPEN or CDF_CREATE.

VarName

A string containing the name of the variable.

IsZVar

A named variable into which CDF_VARNUM will place a 1 to indicate that the referenced variable is a zVariable or a 0 to indicate that it is an rVariable.


CDF_VARPUT

The CDF_VARPUT procedure writes a value to a variable in a Common Data Format file. This function provides equivalent functionality to the C routines CDFvarPut and CDFvarHyperPut.

Calling Sequence

CDF_VARPUT, Id, Variable, Value

Arguments

Id

The CDF ID, returned from a previous call to CDF_OPEN or CDF_CREATE.

Variable

A string containing the name of the variable or the variable number being written.

Value

The value to write. If the value has 1 more dimension than the CDF, multiple records will be written.

Keywords

COUNT

An optional vector containing the counts to be used in writing Value. Note that counts do not have to match the dimensions of Value. The default count is to use the dimensions of Value.

INTERVAL

A vector specifying the interval between values in each dimension. The default value is 1 in each dimension.

OFFSET

A vector specifying the array indices within the specified record(s) at which to begin writing. OFFSET is a 1-dimensional array containing one element per CDF dimension. The default value is zero in each dimension.

REC_INTERVAL

The interval between records being written when writing multiple records. The default value is 1.

REC_START

The record number at which to start writing. The default is 0.

ZVARIABLE

If Variable is a variable ID (as opposed to a variable name) and the variable is a zVariable, set this flag to indicate that the variable ID is a zVariable ID. The default is to assume that Variable is an rVariable ID.

Examples

id= CDF_CREATE('mycdf', [5,10], /NETWORK_ENCODING, /ROW_MAJOR)

varid= CDF_VARCREATE(id, 'V1', [1,1], /CDF_FLOAT, /REC_VARY)

To write the value 42.0 into record 12, third row, fourth column:

CDF_VARPUT, id, varid, 42, REC_START=12, OFFSET=[2,3]

To write 3 records, skipping every other record, starting at record 2, writing every other entry of each record. Note that in this example we write 25 values into each record written:

CDF_VARPUT, id, varid, FINDGEN(5,5,3), INTERVAL=[2,1], $

            REC_INTERVAL=2, REC_START=2


CDF_VARRENAME

The CDF_VARRENAME procedure renames an existing variable in a Common Data Format file.

Calling Sequence

CDF_VARRENAME, Id, OldVariable, NewName

Arguments

Id

The CDF ID, returned from a previous call to CDF_OPEN or CDF_CREATE.

OldVariable

A string containing the current name of the variable or the variable number to be renamed.

NewName

A string containing the new name for the variable.

Keywords

ZVARIABLE

If OldVariable is a variable ID (as opposed to a variable name) and the variable is a zVariable, set this flag to indicate that the variable ID is a zVariable ID. The default is to assume that OldVariable is an rVariable ID.

Example

CDF_VARRENAME, id, 0, /Zvar, 'Z1'	Change first zVariable name to Z1

CDF_VARRENAME, id, 0, 'R1'	Change first rVariable name to R1


CEIL

The CEIL function returns the closest integer greater than or equal to its argument. This value is returned as a longword integer with the same structure as the input argument.

Calling Sequence

Result = CEIL(X)

Arguments

X

The value for which the ceiling function is to be evaluated. This value can be single- or double-precision, real or complex floating-point. CEIL returns a longword integer with the same structure as X.

Example

To print the ceiling function of 5.1, enter:

PRINT, CEIL(5.1)

IDL prints:

6

See Also

COMPLEXROUND, FLOOR, ROUND


CHEBYSHEV

The CHEBYSHEV function returns the forward or reverse Chebyshev polynomial expansion of a set of data. Note: Results from this function are subject to roundoff error given discontinuous data.

This routine is written in the IDL language. Its source code can be found in the file chebyshev.pro in the lib subdirectory of the IDL distribution.

Calling Sequence

Result = CHEBYSHEV(D, N)

Arguments

D

A vector containing the values at the zeros of Chebyshev polynomial.

N

A flag that, if set to -1, returns a set of Chebyshev polynomials. If set to +1, the original data is returned.

See Also

FFT, WTN


CHECK_MATH

The CHECK_MATH function returns and clears the accumulated math error status. If the optional parameter  Print_Flag is non-zero then an error message indicating the accumulated math errors is printed, otherwise the routine produces no messages. The result of this function is 0 if no math errors have occurred since the last call or issuance of the interactive prompt. Each type of error is encoded as a bit, as described in the table below.

Value	Condition
0	No errors detected since the last interactive prompt or call to CHECK_MATH
1	Integer divided by zero
2	Integer overflow
16	Floating-point divided by zero
32	Floating-point underflow
64	Floating-point overflow
128	Floating-point operand error. An illegal operand was encountered, such as a negative operand to the SQRT or ALOG functions, or an attempt to convert to integer a number whose absolute value is greater than 2^31 - 1
Table 1.1 Math Error Status Values (note that not all machines detect all errors)

Calling Sequence

Result = CHECK_MATH([Print_Flag, Message_Inhibit])

Arguments

Print_Flag

If this argument is present and non-zero, an error message is printed if any accumulated math errors exist. If this argument is omitted or zero, CHECK_MATH executes silently.

Message_Inhibit

This optional parameter disables or enables the printing of math error exception error messages when they are detected. By default, these messages are enabled. Set Message_Inhibit to 1 to inhibit, and 0 to re-enable. When the interpreter exits to the interactive mode, error messages are printed for accumulated math errors that were suppressed but not cleared.

Keywords

TRAP

Set this parameter to a non-zero value to enable floating-point traps (the default). Set this keyword to a zero value to disable traps.

The first 8 floating-point error exceptions issue error messages. Subsequent errors are silent.

The accumulated floating-point error status is printed when IDL returns to the interactive mode if a floating-point error occurred that was not logged.

If TRAP is set to 0, no error messages are printed excepting the final, accumulated error status.

Trap handling is machine dependent. Some machines will not operate properly with traps enabled, others do not allow disabling traps. For example, on the Sun 386i traps may not be enabled.

Note that on most machines, if traps are enabled, the result of an illegal operation is indeterminate. To get proper IEEE floating-point special values as results, traps must be disabled. For example, on a Sun workstation with math traps enabled, the following command generates a floating-point error, but an indeterminate result:

junk = check_math(trap=1)	Turn on traps.

a = 1./0.

IDL prints:

% Program caused arithmetic error: Floating divide by 0

PRINT, a

IDL prints:

5.04467e-41	This result should be Infinity.

junk = check_math(trap=0)	Turn off traps.

a = 1./0.

IDL prints:

% Program caused arithmetic error: Floating divide by 0

PRINT, a

IDL prints:

Inf 	This works as expected.

Examples

To simply check and clear the accumulated math error status using all the defaults, enter:

PRINT, CHECK_MATH()

The following code fragment would print the names of errors that have occurred:

ERRS = ['Divide by 0', 'Underflow', 'Overflow', $

        'Illegal Operand']	Create a string array of error names.

J = CHECK_MATH()	Get math error status.

FOR I = 4, 7 DO IF ISHFT(J, -I) AND 1 THEN $

    PRINT, ERRS(I-4), ' Occurred'	Check to see if an error occurred and print the corresponding error message.

See Also

FINITE, MACHAR, and "!VALUES" on page 3-8 of the  IDL User's Guide.


CHISQR_CVF

The CHISQR_CVF function computes the cutoff value V in a Chi-square distribution with Df degrees of freedom such that the probability that a random variable X is greater than V is equal to a user-supplied probability P.

This routine is written in the IDL language. Its source code can be found in the file chisqr_cvf.pro in the lib subdirectory of the IDL distribution.

Calling Sequence

Result = CHISQR_CVF(P, Df)

Arguments

P

A non-negative single- or double-precision floating-point scalar, in the interval [0.0, 1.0], that specifies the probability of occurrence or success.

Df

A positive integer, single- or double-precision floating-point scalar that specifies the number of degrees of freedom of the Chi-square distribution.

Example

Use the following command to compute the cutoff value in a Chi-square distribution with three degrees of freedom such that the probability that a random variable X is greater than the cutoff value is 0.100. The result should be 6.25139.

PRINT, CHISQR_CVF(0.100, 3)

IDL prints:

6.25139

See Also

CHISQR_PDF, F_CVF, GAUSS_CVF, T_CVF


CHISQR_PDF

The CHISQR_PDF function computes the probability P that, in a Chi-square distribution with Df degrees of freedom, a random variable X is less than or equal to a user-specified cutoff value V.

This routine is written in the IDL language. Its source code can be found in the file chisqr_pdf.pro in the lib subdirectory of the IDL distribution.

Calling Sequence

Result = CHISQR_PDF(V, Df)

Arguments

V

An integer, single-, or double-precision floating-point scalar that specifies the cutoff value.

Df

A positive integer, single- or double-precision floating-point scalar that specifies the number of degrees of freedom of the Chi-square distribution.

Examples

Use the following command to compute the probability that a random variable X, from the Chi-square distribution with three degrees of freedom, is less than or equal to 6.25. The result should be 0.899939.

result = CHISQR_PDF(6.25, 3)

PRINT, result

IDL prints:

0.899939

Compute the probability that a random variable X from the Chi-square distribution with three degrees of freedom, is greater than 6.25. The result should be 0.100061.

PRINT, 1 - chisqr_pdf(6.25, 3)

IDL prints:

0.100061

See Also

BINOMIAL, CHISQR_CVF, F_PDF, GAUSS_PDF, T_PDF


CHOLDC

Given a positive-definite symmetric n by n array A, the CHOLDC procedure constructs its Cholesky decomposition A = LL^T, where L is a lower triangular array and L^T is the transpose of L.

CHOLDC is based on the routine choldc described in section 2.9 of Numerical Recipes in C: The Art of Scientific Computing (Second Edition), published by Cambridge University Press, and is used by permission.

Calling Sequence

CHOLDC, A, P

Arguments

A

An n by n array. On input, only the upper triangle of A need be given. On output, L is returned in the lower triangle of A, except for the diagonal elements, which are returned in the vector P.

P

An n-element vector containing the diagonal elements of L.

Keywords

DOUBLE

Set this keyword to force the computation to be done in double-precision arithmetic.

Example

See the description of CHOLSOL for an example using this function.

See Also

CHOLSOL


CHOLSOL

The CHOLSOL function returns an n-element vector containing the solution to the set of linear equations Ax = b, where A  is the positive-definite symmetric array returned by the CHOLDC procedure.

CHOLSOL is based on the routine cholsl described in section 2.9 of Numerical Recipes in C: The Art of Scientific Computing (Second Edition), published by Cambridge University Press, and is used by permission.

Calling Sequence

result = CHOLSOL(A, P, B)

Arguments

A

An n by n positive-definite symmetric array, as output by CHOLDC. Only the lower triangle of A is accessed.

P

The diagonal elements of the Cholesky factor L, as computed by CHOLDC.

B

An n-element vector containing the right-hand side of the equation.

Keywords

DOUBLE

Set this keyword to force the computation to be done in double-precision arithmetic.

Example

To solve a positive-definite symmetric system Ax = b:

A = [[ 6.0, 15.0, 55.0], $	Define the coefficient array.

     [15.0, 55.0, 225.0], $

     [55.0, 225.0, 979.0]]

B = [9.5, 50.0, 237.0]	Define the right-hand side vector B.

CHOLDC, A, P	Compute Cholesky decomposition of A.

PRINT, CHOLSOL(A, P, B)	Compute and print the solution.

IDL prints:

  -0.499998  -1.00000  0.500000

The exact solution vector is [-0.5, -1.0, 0.5].

See Also

CRAMER, GS_ITER, LU_COMPLEX, CHOLDC, LUSOL, SVSOL, TRISOL


CINDGEN

The CINDGEN function returns a complex, single-precision, floating-point array with the specified dimensions. Each element of the array has its real part set to the value of its one-dimensional subscript. The imaginary part is set to zero.

Calling Sequence

Result = CINDGEN(D1, ..., Dn)

Arguments

Di

The dimensions of the result. The dimension parameters can be any scalar expression. Up to eight dimensions can be specified.

Example

To create C, a 4-element vector of complex values with the real parts set to the value of their subscripts, enter:

C = CINDGEN(4)

See Also

BINDGEN, DCINDGEN, DINDGEN, FINDGEN, INDGEN, LINDGEN, SINDGEN


CIR_3PNT

The CIR_3PNT procedure returns the radius and center of a circle, given 3 points on the circle. This is analogous to finding the circumradius and circumcircle of a triangle; the center of the circumcircle is the point at which the three perpendicular bisectors of the triangle formed by the points meet.

This routine is written in the IDL language. Its source code can be found in the file cir_3pnt.pro in the lib subdirectory of the IDL distribution.

Calling Sequence

CIR_3PNT, X, Y, R, X0, Y0

Arguments

X

A three-element vector containing the X-coordinates of the points.

Y

A three-element vector containing the Y-coordinates of the points.

R

A named variable that will contain the radius of the circle. The procedure returns 0.0 if the points are co-linear.

X0

A named variable that will contain the X-coordinate of the center of the circle. The procedure returns 0.0 if the points are co-linear.

Y0

A named variable that will contain the Y-coordinate of the center of the circle. The procedure returns 0.0 if the points are co-linear.

Example

X = [1.0, 2.0, 3.0]

Y = [1.0, 2.0, 1.0]

CIR_3PNT, X, Y, R, X0, Y0

PRINT, 'The radius is: ', R

PRINT, 'The center of the circle is at: ', X0, Y0

See Also

PNT_LINE, SPH_4PNT


CLOSE

The CLOSE procedure closes the file units specified as arguments. All open files are also closed when IDL exits.

Calling Sequence

CLOSE [,Unit1, ..., Unitn]

Arguments

Uniti

The IDL file units to close.

Keywords

ALL

Set this keyword to close all open file units. In addition, any file units that were allocated via GET_LUN are freed.

FILE

Set this keyword to close all file units from 1 to 99. File units greater than 99, which are associated with the GET_LUN and FREE_LUN procedures, are not affected.

Example

If file units 1 and 3 are open, they can both be closed at the same time by entering the command:

CLOSE, 1, 3

See Also

OPEN


COLOR_CONVERT

The COLOR_CONVERT procedure converts colors to and from the RGB (Red Green Blue), HLS (Hue Lightness Saturation), and HSV (Hue Saturation Value) color systems. A keyword parameter indicates the type of conversion to be performed (one of the keywords must be specified). The first three parameters contain the input color triple(s) which may be scalars or arrays of the same size. The result is returned in the last three parameters, O0, O1, and O2. RGB values are bytes in the range 0 to 255.

Hue is measured in degrees, from 0 to 360. Saturation, Lightness, and Value are floating-point numbers in the range 0 to 1. A Hue of 0 degrees is the color red. Green is 120 degrees. Blue is 240 degrees. A reference containing a discussion of the various color systems is: Foley and Van Dam, Fundamentals of Interactive Computer Graphics, Addison-Wesley Publishing Co., 1982.

Calling Sequence

COLOR_CONVERT, I0, I1, I2, O0, O1, O2

Arguments

I0, I1, I2

The input color triple(s). These arguments may be either scalars or arrays of the same length.

O0, O1, O2

The variables to receive the result. Their structure is copied from the input parameters.

Keywords

HLS_RGB

Set this keyword to convert from HLS to RGB.

HSV_RGB

Set this keyword to convert from HSV to RGB.

RGB_HLS

Set this keyword to convert from RGB to HLS.

RGB_HSV

Set this keyword to convert from RGB to HSV.

Example

The command:

COLOR_CONVERT, 255, 255, 0, h, s, v, /RGB_HSV

converts the RGB color triple (255, 255, 0), which is the color yellow at full intensity and saturation, to the HSV system. The resulting hue in the variable h is 60.0 degrees. The saturation and value, s and v, are set to 1.0.

See Also

HLS, HSV


COLOR_QUAN

The COLOR_QUAN function quantizes a true-color image and returns a pseudo-color image and palette to display the image on standard pseudo-color displays. The output image and palette can have from 2 to 256 colors.

COLOR_QUAN solves the general problem of accurately displaying decomposed, true-color images, that contain a palette of up to 2^24 colors, on pseudo-color displays that can only display 256 (or fewer) simultaneous colors.

One of two color quantization methods can be used:

•	Method 1 is a statistical method that attempts to find the N colors that most accurately represent the original color distribution. This algorithm uses a variation of the Median Cut Algorithm, described in "Color Image Quantization for Frame Buffer Display", from Computer Graphics, Volume 16, Number 3 (July, 1982), Page 297. It repeatedly subdivides the color space into smaller and smaller rectangular boxes, until the requested number of colors are obtained.

The original colors are then mapped to the nearest output color, and the original image is resampled to the new palette with optional Floyd-Steinberg color dithering. The resulting pseudo-color image and palette are usually a good approximation of the original image.

The number of colors in the output palette defaults to the number of colors supported by the currently-selected graphics output device. The number of colors can also be specified by the COLOR keyword parameter.

•	Method 2, selected by setting the keyword parameter CUBE, divides the three-dimensional color space into equal-volume cubes. Each color axis is divided into CUBE segments, resulting in CUBE^3 volumes. The original input image is sampled to this color space using Floyd-Steinberg dithering, which distributes the quantization error to adjacent pixels.

The CUBE method has the advantage that the color tables it produces are independent of the input image, so that multiple quantized images can be viewed simultaneously. The statistical method usually provides a better-looking result and a smaller global error.

COLOR_QUAN can use the same color mapping for a series of images. See the descriptions of the GET_TRANSLATION, MAP_ALL, and TRANSLATION keywords, below.

Calling Sequence

Result = COLOR_QUAN(Image_R, Image_G, Image_B, R, G, B)

or

Result = COLOR_QUAN( Image, Dim, R, G, B)

Note that the input image parameter can be passed as either three, separate color-component arrays (Image_R, Image_G, Image_B) or as a three-dimensional array containing all three components, Image, and a scalar,  Dim, indicating the dimension over which the colors are interleaved.

Arguments

Image_R, Image_G, Image_B

Arrays containing the red, green, and blue components of the decomposed true-color image. For best results, the input image(s) should be scaled to the range of 0 to 255.

Image

A three-dimensional array containing all three components of the true-color image.

Dim

A scalar that indicates the method of color interleaving in the Image parameter. A value of 1 indicates interleaving by pixel (3, n, m), 2 indicates interleaving by row (n, 3, m), and 3 indicates interleaving by image (n, m, 3).

R, G, B

Three output byte arrays containing the red, green, and blue components of the output palette.

Keywords

COLORS

The number of colors in the output palette. This value must at least 2 and not greater than 256. The default is the number of colors supported by the current graphics output device.

CUBE

If this keyword is set, the color space is divided into CUBE^3 volumes, to which the input image is quantized. This result is always Floyd-Steinberg dithered. The value of CUBE can range from 2 to 6; providing from 2^3 = 8, to 6^3 = 216 output colors. If this keyword is set, the COLORS, DITHER, and ERROR keywords are ignored.

DITHER

Set this keyword to dither the output image. Dithering can improve the appearance of the output image, especially when using relatively few colors.

ERROR

Set this optional keyword to a named variable. A measure of the quantization error is returned. This error is proportional to the square of the Euclidean distance, in RGB space, between corresponding colors in the original and output images.

GET_TRANSLATION

Set this keyword to a named variable in which the mapping between the original RGB triples (in the true-color image) and the resulting pseudo-color indices is returned as a vector. Do not use this keyword if CUBE is set.

MAP_ALL

Set this keyword to establish a mapping for all possible RGB triples into pseudo-color indices. Set this keyword only if GET_TRANSLATION is also present. Note that mapping all possible colors requires more compute time and slightly degrades the quality of the resultant color matching.

TRANSLATION

Set this keyword to a vector of translation indices obtained by a previous call to COLOR_QUAN using the GET_TRANSLATION keyword. The resulting image is quantized using this vector.

Example

The following code segment reads a true-color, row interleaved, image from a disk file, and displays it on the current graphics display, using a palette of 128 colors:

OPENR, unit, 'XXX.DAT', /GET_LUN	Open an input file.

a = BYTARR(512, 3, 480)	Dimensions of the input image.

READU, unit, a	Read the image.

FREE LUN, unit	Close the file.

TV, COLOR_QUAN(a, 2, r, g, b, COLORS=128)	Show the quantized image. The 2 indicates that the colors are interleaved by row.

TVLCT, r, g, b	Load the new palette.

To quantize the image into 216 equal-volume color cubes, replace the call to COLOR_QUAN with the following:

TV, COLOR_QUAN(a, 2, r, g, b, CUBE=6)

See Also

PSEUDO


COMFIT

The COMFIT function fits the paired data {xi, yi} to one of six common types of approximating models using a gradient-expansion least-squares method. The result is a vector containing the model parameters.

This routine is written in the IDL language. Its source code can be found in the file comfit.pro in the lib subdirectory of the IDL distribution.

Calling Sequence

Result = COMFIT(X, Y, A0)

Arguments

X

An n-element integer, single-, or double-precision floating-point vector.

Y

An n-element integer, single-, or double-precision floating-point vector.

A0

A vector of initial estimates for each model parameter. The length of this vector depends upon the type of model selected.

Keywords

EXPONENTIAL

Set this keyword to compute the parameters of the exponential model.

GEOMETRIC

Set this keyword to compute the parameters of the geometric model.

GOMPERTZ

Set this keyword to compute the parameters of the Gompertz model.

HYPERBOLIC

Set this keyword to compute the parameters of the hyperbolic model.

LOGISTIC

Set this keyword to compute the parameters of the logistic model.

LOGSQUARE

Set this keyword to compute the parameters of the logsquare model.

SIGMA

Set this keyword to a named variable that will contain a vector of standard deviations for the computed model parameters.

WEIGHTS

An n-element vector of weights. If the WEIGHTS vector is not specified, an n-element vector of 1.0s is used.

YFIT

Set this keyword to a named variable that will contain an n-element vector of y-data corresponding to the computed model parameters.

Example

Define two n-element vectors of paired data.

X = [ 2.27, 15.01, 34.74, 36.01, 43.65, 50.02, 53.84, 58.30, $

     62.12, 64.66, 71.66, 79.94, 85.67, 114.95]

Y = [ 5.16, 22.63, 34.36, 34.92, 37.98, 40.22, 41.46, 42.81, $

     43.91, 44.62, 46.44, 48.43, 49.70, 55.31]

Define a 3-element vector of initial estimates for the logsquare model.

A0 = [1.5, 1.5, 1.5]

Compute the model parameters of the logsquare model, A(0), A(1), & A(2).

result = COMFIT(X, Y, A0, /LOGSQUARE)

The result should be the 3-element vector: [1.42494, 7.21900, 9.18794].

See Also

CURVEFIT, LADFIT, LINFIT,


COMPLEX

The COMPLEX function returns complex scalars or arrays given one or two scalars or arrays. If only one parameter is supplied, the imaginary part of the result is zero, otherwise it is set to the value of the Imaginary parameter. Parameters are first converted to single-precision floating-point. If either or both of the parameters are arrays, the result is an array, following the same rules as standard IDL operators. If three parameters are supplied, COMPLEX extracts fields of data from Expression.

Calling Sequence

Result = COMPLEX(Real [, Imaginary])

or

Result = COMPLEX(Expression, Offset, Dim1 [, ..., Dimn])

Arguments

Real

Scalar or array to be used as the real part of the complex result.

Imaginary

Scalar or array to be used as the imaginary part of the complex result.

Expression

The expression from which data is to be extracted.

Offset

Offset from beginning of the Expression data area. Specifying this argument allows fields of data extracted from Expression to be treated as complex data. See the description in Chapter 4 of the IDL User's Guide for details.

Di

When extracting fields of data, the Di arguments specify the dimensions of the result. The dimension parameters can be any scalar expression. Up to eight dimensions can be specified. If no dimension arguments are given, the result is taken to be scalar.

When converting from a string argument, it is possible that the string does not contain a valid floating-point value and no conversion is possible. The default action in such cases is to print a warning message and return 0. The ON_IOERROR procedure can be used to establish a statement to be jumped to in case of such errors.

Example

Create a complex array from two integer arrays by entering the following commands:

A = [1,2,3]	Create the first integer array.

B = [4,5,6]	Create the second integer array.

C = COMPLEX(A, B)	Make A the real parts and B the imaginary parts of the new complex array.

PRINT, C	See how the two arrays were combined.

IDL prints:

( 1.00000, 4.00000)( 2.00000, 5.00000)

( 3.00000, 6.00000)

See Also

BYTE, CONJ,  DCOMPLEX, DOUBLE, FIX, FLOAT, LONG, STRING


COMPLEXARR

The COMPLEXARR function returns a complex, single-precision, floating-point vector or array.

Calling Sequence

Result = COMPLEXARR(D1, ..., Dn)

Arguments

Di

The dimensions of the result. The dimension parameters may be any scalar expression. Up to eight dimensions can be specified.

Keywords

NOZERO

Normally, COMPLEXARR sets every element of the result to zero. If the NOZERO keyword is set, this zeroing is not performed, and COMPLEXARR executes faster.

Example

To create an empty, 5-element by 5-element, complex array C, enter:

C = COMPLEXARR(5, 5)

See Also

DBLARR, DCOMPLEXARR, FLTARR, INTARR, LONARR, MAKE_ARRAY, STRARR


COMPLEXROUND

The COMPLEXROUND function rounds real and imaginary components of a complex array and returns the resulting array.

This routine is written in the IDL language. Its source code can be found in the file complexround.pro in the lib subdirectory of the IDL distribution.

Calling Sequence

Result = COMPLEXROUND(Input)

Arguments

Input

The complex array to be rounded.

Example

X = [COMPLEX(1.245, 3.88), COMPLEX(9.1, 0.3345)]

PRINT, COMPLEXROUND(X)

IDL prints:

(   1.00000,   4.00000)(   9.00000,   0.00000)

See Also

ROUND


COND

The COND function returns the condition number of an n by n real or complex array A by explicitly computing NORM(A)·NORM(A^-1). If A is real and A^-1 is invalid (due to the singularity of A or floating-point errors in the INVERT function), COND returns -1. If A  is complex and A^-1 is invalid (due to the singularity of A), calling COND results in floating-point errors.

This routine is written in the IDL language. Its source code can be found in the file cond.pro in the lib subdirectory of the IDL distribution.

Calling Sequence

Result = COND(A)

Arguments

A

An n by n real or complex array.

Keywords

DOUBLE

Set this keyword to force the computation to be done in double-precision arithmetic.

Example

Define a complex array A:

A = [[COMPLEX(1, 0), COMPLEX(2,-2), COMPLEX(-3, 1)], $

     [COMPLEX(1,-2), COMPLEX(2, 2), COMPLEX(1, 0)], $

     [COMPLEX(1, 1), COMPLEX(0, 1), COMPLEX(1, 5)]]

Compute the condition number of the array using internal double-precision arithmetic.

PRINT, COND(A, /DOUBLE)

IDL prints:

5.93773

See Also

DETERM, INVERT


CONGRID

The CONGRID function shrinks or expands the size of an array by an arbitrary amount. CONGRID is similar to REBIN in that it can resize a one, two, or three dimensional array, but where REBIN requires that the new array size must be an integer multiple of the original size, CONGRID will resize an array to any arbitrary size. (REBIN is somewhat faster, however.) REBIN averages multiple points when shrinking an array, while CONGRID just resamples the array.

The returned array has the same number of dimensions as the original array and is of the same data type.

This routine is written in the IDL language. Its source code can be found in the file congrid.pro in the lib subdirectory of the IDL distribution.

Calling Sequence

Result = CONGRID(Array, X, Y, Z)

Arguments

Array

A 1-, 2-, or 3-dimensional array to resize. Array can be any type except string or structure.

X

The new X-dimension of the resized array. X must be an integer or a long integer, and must be greater than or equal to 2.

Y

The new Y-dimension of the resized array. If the original array has only 1 dimension, Y is ignored. If the original array has 2 or 3 dimensions Y MUST be present.

Z

The new Z-dimension of the resized array. If the original array has only 1 or 2 dimensions, Z is ignored. If the original array has 3 dimensions then Z MUST be present.

Keywords

CUBIC

Set this keyword to force CONGRID to use cubic convolution interpolation on a 1- or 2-dimensional array. When the input array is 1- or 2-dimensional, the default is to employ nearest-neighbor sampling. This keyword has no effect when used with 3-dimensional arrays.

INTERP

Set this keyword to force CONGRID to use linear interpolation when resizing a 1- or 2-dimensional array. CONGRID automatically uses linear interpolation if the input array is 3-dimensional. When the input array is 1- or 2-dimensional, the default is to employ nearest-neighbor sampling.

MINUS_ONE

Set this keyword to prevent CONGRID from extrapolating one row or column beyond the bounds of the input array. For example, if the input array has the dimensions (i, j) and the output array has the dimensions (x, y), then by default the array is resampled by a factor of (i/x) in the X direction and (j/y) in the Y direction. If MINUS_ONE is set, the array will be resampled by the factors (i-1)/(x-1) and (j-1)/(y-1).

Example

Given  vol is a 3-D array with the dimensions (80, 100, 57), resize it to be a (90, 90, 80) array

vol = CONGRID(vol, 90, 90, 80)

See Also

REBIN


CONJ

The CONJ function returns the complex conjugate of X. The complex conjugate of the real-imaginary pair (x, y) is (x, -y). If X is not complex, a complex-valued copy of X is used.

Calling Sequence

Result = CONJ(X)

Arguments

X

The value for which the complex conjugate is desired. If X is an array, the result has the same structure, with each element containing the complex conjugate of the corresponding element of X.

Example

Print the conjugate of the complex pair (4.0, 5.0) by entering:

PRINT, CONJ(COMPLEX(4.0, 5.0))

IDL prints:

( 4.00000, -5.00000)

See Also

CINDGEN, COMPLEX, COMPLEXARR, DCINDGEN, DCOMPLEX, DCOMPLEXARR


CONTOUR

The CONTOUR procedure draws a contour plot from data stored in a rectangular array. Both line contours and filled contour plots can be created. Note that outline and fill contours cannot be drawn at the same time. To create a contour plot with both filled contours and outlines, first create the filled contour plot, then add the outline contours by calling CONTOUR a second time with the OVERPLOT keyword.

Contours can be smoothed by using the MIN_CURVE_SURF function on the contour data before contouring.

Using various keywords, described below, it is possible to specify contour levels, labeling, colors, line styles, and other options. CONTOUR can draw contours using one of two different methods:

•	The first algorithm, used by default, examines each array cell and draws all contours emanating from that cell before proceeding to the next cell. This method is efficient in terms of computer resources but does not allow contour labeling.

•	The second method searches for each contour line and then follows the line until it reaches a boundary or closes. This method gives better looking results with dashed line styles, and allows contour labeling, but requires more computer time. It is used if any of the following keywords are specified: C_ANNOTATION, C_CHARSIZE, C_LABELS, FOLLOW, PATH, FILENAME, or DOWNHILL.

Although these two methods both draw correct contour maps, differences in their algorithms can cause small differences in the resulting graphs. Note that the resulting contour plots are  both correct—there can be more than one correct way to interpret contours.

Smoothing Contours

The MIN_CURVE_SURF function can be used to smoothly interpolate both regularly and irregularly sampled surfaces before contouring. This function replaces the older SPLINE keyword to CONTOUR, which was inaccurate and is no longer supported. MIN_CURVE_SURF interpolates the entire surface to a relatively fine grid before drawing the contours.

Calling Sequence

CONTOUR, Z [, X, Y]

Arguments

Z

A two-dimensional array containing the values that make up the contour surface. If arguments  X and Y are provided, the contour is plotted as a function of the (X, Y) locations specified by their contents. Otherwise, the contour is generated as a function of the two-dimensional array index of each element of Z.

This argument is converted to single-precision floating-point before plotting. Plots created with CONTOUR are limited to the range and precision of single-precision floating-point values.

X

A vector or two-dimensional array specifying the X coordinates for the contour surface. If X is a vector, each element of X specifies the X coordinate for a column of Z (e.g., X(0) specifies the X coordinate for Z(0,*)). If X is a two-dimensional array, each element of X specifies the X coordinate of the corresponding point in Z (i.e., Xij specifies the X coordinate for Zij).

Y

A vector or two-dimensional array specifying the Y coordinates for the contour surface. If Y a vector, each element of Y specifies the Y coordinate for a row of Z (e.g., Y(0) specifies the Y coordinate for Z(*,0)). If Y is a two-dimensional array, each element of Y specifies the Y coordinate of the corresponding point in Z (Yij specifies the Y coordinate for Zij).

Keywords

C_ANNOTATION

The label to be drawn on each contour. Usually, contours are labeled with their value. This parameter, a vector of strings, allows any text to be specified. The first label is used for the first contour drawn, and so forth. If the LEVELS keyword is specified, the elements of C_ANNOTATION correspond directly to the levels specified, otherwise, they correspond to the default levels chosen by the CONTOUR procedure. If there are more contour levels than elements in C_ANNOTATION, the remaining levels are labeled with their values.

Use of this keyword implies use of the FOLLOW keyword.

Example

To produce a contour plot with three levels labeled "low", "medium", and "high":

CONTOUR, Z, LEVELS = [0.0, 0.5, 1.0], $

  C_ANNOTATION = ['low', 'medium', 'high']

C_CHARSIZE

The size of the characters used to annotate contour labels. Normally, contour labels are drawn at 3/4 of the size used for the axis labels (specified by the CHARSIZE keyword or !P.CHARSIZE system variable. This keyword allows the contour label size to be specified directly. Use of this keyword implies use of the FOLLOW keyword.

C_COLORS

The color index used to draw each contour. This parameter is a vector, converted to integer type if necessary. If there are more contour levels than elements in C_COLORS, the elements of the color vector are cyclically repeated.

Example

If C_COLORS contains three elements, and there are seven contour levels to be drawn, the colors c0, c1, c2, c0, c1, c2, c0 will be used for the seven levels. To call CONTOUR and set the colors to [100,150,200], use the command:

CONTOUR, Z, C_COLORS = [100,150,200]

C_LABELS

Specifies which contour levels should be labeled. By default, every other contour level is labeled. C_LABELS allows you to override this default and explicitly specify the levels to label. This parameter is a vector, converted to integer type if necessary. If the LEVELS keyword is specified, the elements of C_LABELS correspond directly to the levels specified, otherwise, they correspond to the default levels chosen by the CONTOUR procedure. Setting an element of the vector to zero causes that contour label to not be labeled. A nonzero value forces labeling.

Use of this keyword implies use of the FOLLOW keyword.

Example

To produce a contour plot with four levels where all but the third level is labeled:

CONTOUR, Z, LEVELS = [0.0, 0.25, 0.75, 1.0], $

  C_LABELS = [1, 1, 0, 1]

C_LINESTYLE

The line style used to draw each contour. As with C_COLORS, C_LINESTYLE is a vector of line style indices. If there are more contour levels than line styles, the line styles are cyclically repeated. See Table 2.1 on  page 2-6 of the IDL Reference Guide for a list of available styles.

Note: The cell drawing contouring algorithm draws all the contours in each cell, rather than following contours. Since an entire contour is not drawn as a single operation, the appearance of the more complicated linestyles will suffer. Use of the contour following method (selected with the FOLLOW keyword) will give better looking results in such cases.

Example

To produce a contour plot, with the contour levels directly specified in a vector V, with all negative contours drawn with dotted lines, and with positive levels in solid lines:

CONTOUR, Z, LEVELS = V, C_LINESTYLE = (V LT 0.0)

C_ORIENTATION

If the FILL keyword is set, this keyword can be set to the angle, in degrees counterclockwise from the horizontal, of the lines used to fill contours. If neither C_ORIENTATION or C_SPACING are specified, the contours are solid filled.

C_SPACING

If the FILL keyword is set, this keyword can be used to control the distance, in centimeters, between the lines used to fill the contours.

C_THICK

The line used to draw each contour level. As with C_COLORS, C_THICK is a vector of line thickness values, although the values are floating point. If there are more contours than thickness elements, elements are repeated. If omitted, the overall line thickness specified by the THICK keyword parameter or !P.THICK is used for all contours.

CELL_FILL

Set this keyword to produce a filled contour plot using a "cell filling" algorithm. Use this keyword instead of FILL when you have a contour plot with missing data or contours that extend off the edge of the contour plot. CELL_FILL is less efficient than FILL because it makes one or more polygons for each data cell. It also gives poor results when used with patterned (line) fills, because each cell is assigned its own pattern. Otherwise, this keyword operates identically to the FILL keyword, described below.

CLOSED

Set this keyword to close contours that intersect the plot boundaries. After a contour hits a boundary, it is follows the plot boundary until it connects with its other boundary intersection.

DOWNHILL

Set this keyword to label each contour with short, perpendicular tick marks that point in the "downhill" direction, making the direction of the grade readily apparent. If this keyword is set, the contour following method is used in drawing the contours.

Note that this keyword is ignored if the TRIANGULATION keyword is set.

FILL

Set this keyword to produce a filled contour plot. The contours are filled with solid or line-filled polygons. For solid polygons, use the C_COLOR keyword to specify the color index of the polygons for each contour level. For line fills, use C_ORIENTATION, C_SPACING, C_COLOR, C_LINESTYLE, and/or C_THICK to specify attributes for the lines.

If the current device is not a pen plotter, each polygon is erased to the background color before the fill lines are drawn, to avoid superimposing one pattern over another.

Contours that are not closed can not be filled because their interior and exterior are undefined. Contours created from data sets with missing data may not be closed; many map projections can also produce contours that are not closed. Filled contours should not be used in these cases.

FOLLOW

Set this keyword to force the CONTOUR procedure to use the line-following method instead of the cell-drawing method. CONTOUR can draw contours using one of two different methods:

•	The first algorithm, used by default, examines each array cell and draws all contours emanating from that cell before proceeding to the next cell. This method is efficient in terms of computer resources but does not allow contour labeling.

•	The second method searches for each contour line and then follows the line until it reaches a boundary or closes. This method gives better looking results with dashed line styles, and allows contour labeling, but requires more computer time. It is used if any of the following keywords is specified: C_ANNOTATION, C_CHARSIZE, C_LABELS, DOWNHILL, FOLLOW, or PATH_FILENAME.

Although these two methods both draw correct contour maps, differences in their algorithms can cause small differences in the resulting graph.

Note that this keyword is ignored if the TRIANGULATION keyword is set.

LEVELS

Specifies a vector containing the contour levels drawn by the CONTOUR procedure. A contour is drawn at each level in LEVELS.

Example

To draw a contour plot with levels at 1, 100, 1000, and 10000:

CONTOUR, Z, LEVELS = [1, 100, 1000, 10000]

To draw a contour plot with levels at 50, 60, ..., 90, 100:

CONTOUR, Z, LEVELS = FINDGEN(6) * 10 + 50

MAX_VALUE

Data points with values equal to or above this value are ignored (i.e., treated as missing data) when contouring. Cells containing one or more corners with values above MAX_VALUE will have no contours drawn through them. Note that the IEEE floating-point value NaN is also treated as missing data. (See "Special Floating-Point Values" on page 11-9 of the IDL User's Guide for more information on IEEE floating-point values.)

MIN_VALUE

Data points with values less than this value are ignored (i.e., treated as missing data) when contouring. Cells containing one or more corners with values below MIN_VALUE will have no contours drawn through them. Note that the IEEE floating-point value NaN is also treated as missing data. (See "Special Floating-Point Values" on page 11-9 of the IDL User's Guide for more information on IEEE floating-point values.)

NLEVELS

The number of equally spaced contour levels that are produced by CONTOUR. If the LEVELS parameter, which explicitly specifies the value of the contour levels, is present this keyword has no effect. If neither parameter is present, approximately six levels are drawn. NLEVELS should be an integer between 1 and 29.

OVERPLOT

Set this keyword to make CONTOUR "overplot". That is, the current graphics screen is not erased, no axes are drawn and the previously established scaling remains in effect. You must explicitly specify the values of the contour levels when using this option, unless geographic mapping coordinates are in effect.

PATH_FILENAME

Specifies the name of a file to contain the contour positions. If PATH_FILENAME is present, CONTOUR does not draw the contours, but rather, opens the specified file and writes the positions, in normalized coordinates, into it. The file consists of a series of logical records containing binary data. Each record is preceded with a header structure defining the contour as follows:

{CONTOUR_HEADER, TYPE:0B, HIGH:0B, LEVEL:0, $

 NUM:0L, VALUE:0.0}

The fields are:

•	TYPE: A byte that is zero if the contour is open, and one if it is closed.

•	HIGH: A byte that is 1 if the contour is closed and above its surroundings, and is 0 if the contour is below. This field is meaningless if the contour is not closed.

•	LEVEL: A short integer with value greater or equal to zero (It is an index into the LEVELS array).

•	NUM: The longword number of data points in the contour.

•	VALUE: The contour value. This is a single precision floating point value.

Following the header in each record are NUM X-coordinate values followed by NUM Y-coordinate values, expressed in normalized coordinates.

Use of this keyword implies use of the FOLLOW keyword.

PATH_INFO

Set this keyword to a named variable that will return path information for the contours. This information can be used, along with data stored in a variable named by the PATH_XY keyword, to trace closed contours. If PATH_INFO is present, CONTOUR does not draw the contours, but rather records the path information in an array of structures of the following type:

{CONTOUR_PATH_STRUCTURE, TYPE:0B, HIGH_LOW:0B, $

 LEVEL:0, N:0L, OFFSET:0L, VALUE:0.0}

The fields are:

•	TYPE: A byte that is zero if the contour is open, and one if it is closed. In the present implementation, all contours are closed.

•	HIGH_LOW: A byte that is 1 if the contour is above its surroundings, and is 0 if the contour is below.

•	LEVEL: A short integer indicating the index of the contour level, from zero to the number of levels minus one.

•	N: A long integer indicating the number of XY pairs in the contour's path.

•	OFFSET: A long integer that is the offset into the array defined by PATH_XY, representing the first XY coordinate for this contour.

•	VALUE: The contour value. This is a single precision floating point value.

See the examples section below for an example using the PATH_INFO and PATH_XY keywords to return contour path information.

PATH_XY

Set this keyword to a named variable that returns the normalized coordinates of the closed paths of the contours. This information can be used, along with data stored in a variable named by the PATH_INFO keyword, to trace closed contours. If PATH_XY is present, CONTOUR does not draw the contours, but rather records the normalized path coordinates in the named array.

See the examples section below for an example using the PATH_INFO and PATH_XY keywords to return contour path information.

TRIANGULATION

Set this keyword to a variable that contains an array of triangles returned from the TRIANGULATE procedure. Providing triangulation data allows you to contour irregularly gridded data directly, without gridding.

Note that if TRIANGULATION is set, the cell-drawing method is used even if the FOLLOW keyword is set, because each triangular cell is contoured individually. Note also that the DOWNHILL keyword is ignored if TRIANGULATION is set.

XLOG

Set this keyword to specify a logarithmic X axis.

YLOG

Set this keyword to specify a logarithmic Y axis.

ZAXIS

Set this keyword to draw a Z axis for the CONTOUR plot. CONTOUR draws no Z axis by default. This keyword is of use only if a three-dimensional transformation is established.

Graphics Keywords Accepted

See Chapter 2, "Graphics Keywords and System Variables", for the description of graphics and plotting keywords not listed above. BACKGROUND CHARSIZE  CHARTHICK CLIP COLOR DATA DEVICE FONT NOCLIP NODATA NOERASE NORMAL POSITION SUBTITLE T3D THICK  TICKLEN TITLE [XYZ]CHARSIZE [XYZ]GRIDSTYLE [XYZ]MARGIN [XYZ]MINOR [XYZ]RANGE [XYZ]STYLE [XYZ]THICK [XYZ]TICKFORMAT [XYZ]TICKLEN [XYZ]TICKNAME [XYZ]TICKS [XYZ]TICKV [XYZ]TICK_GET [XYZ]TITLE ZVALUE.

Examples

To create a contour plot with 10 contour levels where every other contour is labeled:

Z = DIST(100)	Create a simple dataset to plot.

CONTOUR, Z, NLEVELS=10, /FOLLOW, TITLE='Simple Contour Plot'
Draw the plot.

The following commands describe a more complicated example that shows the use of polygon filling and smoothing.

First, create a surface to contour:

A = RANDOMU(seed, 5, 6)	Create a 2D array of random numbers.

B = MIN_CURVE_SURF(A)	Smooth the dataset before contouring.

Draw solid-filled contours:

TEK_COLOR	Load discrete colors for contours.

CONTOUR, B, /FILL, NLEVELS=5, C_COLOR=INDGEN(5)+2
Draw filled contours.

CONTOUR, B, NLEVELS=5, /DOWNHILL, /OVERPLOT
Overplot the contour lines with tickmarks.

Draw line-filled contours:

CONTOUR, B, C_ORIENTATION=[0, 22, 45]

CONTOUR, B, /OVERPLOT	Overplot the contours.

The following program saves the closed path information of a set of contours and plots the result:

PRO path

A = RANDOMU(seed, 8, 10)	Create a 2D array of random numbers.

B = MIN_CURVE_SURF(A)	Smooth the dataset before contouring.

CONTOUR, B, PATH_XY=xy, PATH_INFO=info
Compute contour paths.

FOR I = 0, (N_ELEMENTS(info) - 1 ) DO BEGIN

S = [INDGEN(info(I).N), 0]

PLOTS, xy(*,INFO(I).OFFSET + S ), /NORM
Plot the closed paths.

ENDFOR

END

To contour irregularly-gridded data without having to call TRIGRID, first use the TRIANGULATE procedure to get the Delaunay triangulation of your data, then pass the triangulation array to CONTOUR:

TRIANGULATE, X, Y, tri	Get triangulation.

CONTOUR, Z, X, Y, TRIANGULATION = tri
Draw the contours.

See Also

IMAGE_CONT, SHADE_SURF, SHOW3, SURFACE


CONVERT_COORD

The CONVERT_COORD function transforms one or more sets of coordinates to and from the coordinate systems supported by IDL. The result of the function is a (3, n) vector containing the (x, y, z) components of the n output coordinates.

The input coordinates  X and, optionally, Y and/or Z can be given in data, device, or normalized form by using the DATA, DEVICE, or NORMAL keywords. The default input coordinate system is DATA. The keywords TO_DATA, TO_DEVICE, and TO_NORMAL specify the output coordinate system.

If the input points are in 3D data coordinates, be sure to set the T3D keyword.

Calling Sequence

Result = CONVERT_COORD(, X [, Y [, Z]])

Arguments

X

A vector or scalar argument providing the X components of the input coordinates. If only one argument is specified, X must be an array of either two or three vectors (i.e., (2,*) or (3,*)). In this special case, X(0,*) is taken as the X values, X(1,*) is taken as the Y values, and, if present, X(2,*) is taken as the Z values.

Y

An optional argument providing the Y input coordinate(s).

Z

An optional argument providing the Z input coordinate(s).

Keywords

DATA

Set this keyword if the input coordinates are in data space (the default).

DEVICE

Set this keyword if the input coordinates are in device space.

NORMAL

Set this keyword if the input coordinates are in normalized space.

T3D

Set this keyword if the 3D transformation !P.T is to be applied.

TO_DATA

Set this keyword if the output coordinates are to be in data space.

TO_DEVICE

Set this keyword if the output coordinates are to be in device space.

TO_NORMAL

Set this keyword if the output coordinates are to be in normalized space.

Example

Convert, using the currently established viewing transformation, 11 points along the parametric line x = t, y = 2t, z = t^2, along the interval [0, 1] from data coordinates to device coordinates:

X = FINDGEN(11)/10.	Make a vector of X values.

D = CONVERT_COORD(X, 2*X, X^2, /T3D, /TO_DEVICE)
Convert the coordinates. D will be an (3,11) element array.

See Also

CV_COORD


CONVOL

The CONVOL function convolves an array with a kernel, and returns the result. Convolution is a general process that can be used for various types of smoothing, signal processing, shifting, differentiation, edge detection, etc. The CENTER keyword controls the alignment of the kernel with the array and the ordering of the kernel elements. If CENTER is explicitly set to 0, convolution is performed in the strict mathematical sense, otherwise the kernel is centered over each data point.

Assume R = CONVOL(A, K, S), where A is an n-element vector, K is an m-element vector (m < n), and S is the scale factor. If the CENTER keyword is omitted or set to 1:

If CENTER is explicitly set to 0:

In the two-dimensional, zero CENTER case where A is an m by n-element array, and K is the l by l element kernel; the result R is an m by n-element array:

The centered case is similar, except the t-i and u-j subscripts are replaced by t+i-l/2 and u+j-l/2.

Calling Sequence

Result = CONVOL(Array, Kernel [, Scale_Factor])

Arguments

Array

An array of any basic type except string. The result of CONVOL has the same type and dimensions as Array.

If the Array parameter is of byte type, the result is clipped to the range of 0 to 255. Negative results are set to 0, and values greater than 255 are set to 255.

Kernel

An array of any type except string. If the type of Kernel is not the same as Array, a copy of Kernel is made and converted to the appropriate type before use. The size of the kernel dimensions must be smaller than those of Array.

Scale_Factor

A scale factor, for use with integer and byte type data only, that is divided into each resulting value. This argument allows the use of fractional kernel values and avoids overflow with byte arguments. If omitted, 1.0 is used.

Keywords

CENTER

Set or omit this keyword to center the kernel over each array point. If CENTER is explicitly set to zero, the CONVOL function works in the conventional mathematical sense. In many signal and image processing applications, it is useful to center a symmetric kernel over the data, thereby aligning the result with the original array.

EDGE_WRAP

Set this keyword to make CONVOL compute the values of elements at the edge of Array by "wrapping" the subscripts of Array at the edge. For example, if CENTER is set to zero:

where na is the number of elements in Array.

If neither EDGE_WRAP nor EDGE_TRUNCATE is set, CONVOL sets the values of elements at the edges of Array to zero.

EDGE_TRUNCATE

Set this keyword to make CONVOL compute the values of elements at the edge of Array by repeating the subscripts of Array at the edge. For example, if CENTER is set to zero:

where na is the number of elements in Array.

If neither EDGE_WRAP nor EDGE_TRUNCATE is set, CONVOL sets the values of elements at the edges of Array to zero.

Example

Convolve a vector of random noise and a one-dimensional triangular kernel and plot the result. Create a simple vector as the original dataset and plot it by entering:

A = RANDOMN(SEED, 100) & PLOT, A

Create a simple kernel by entering:

K = [1, 2, 3, 2, 1]

Convolve the two and overplot the result by entering:

OPLOT, CONVOL(A, K, TOTAL(K))

See Also

BLK_CON


COORD2TO3

The COORD2TO3 function returns a three-element vector containing 3D data coordinates given the normalized X and Y screen coordinates and one of the three data coordinates. Note: A valid 3D transform must exist in !P.T or be specified by the PTI keyword. The axis scaling variables, !X.S, !Y.S and !Z.S must be valid.

This routine is written in the IDL language. Its source code can be found in the file coord2to3.pro in the lib subdirectory of the IDL distribution.

Calling Sequence

Result = COORD2TO3(Mx, My, Dim, D0 [, PTI])

Arguments

Mx, My

The normalized X and Y screen coordinates.

Dim

A parameter used to specify which data coordinate is fixed. Use 0 for a fixed X data coordinate, 1 for a fixed Y data coordinate, or 2 for a fixed Z data coordinate.

D0

The value of the fixed data coordinate.

PTI

The inverse of !P.T. If this parameter is not supplied, or set to 0, COORD2TO3 computes the inverse. If this routine is to be used in a loop, the caller should supply PTI for highest efficiency.

Example

To return the data coordinates of the mouse, fixing the data Z value at 10, enter the commands:

CREATE_VIEW	Make sure a transformation matrix exists.

CURSOR, X, Y, /NORM	Get the normalized mouse coords.

PRINT, COORD2TO3(X, Y, 2, 10.0)	Print the 3D coordinates.

See Also

CONVERT_COORD, CREATE_VIEW, CV_COORD, SCALE3, T3D


CORRELATE

The CORRELATE function computes the linear Pearson correlation coefficient of two n-element vectors or the correlation matrix of an m x n array. Alternatively, this function computes the covariance of two n-element vectors or the covariance matrix of an m x n array.

This routine is written in the IDL language. Its source code can be found in the file correlate.pro in the lib subdirectory of the IDL distribution.

Calling Sequence

Result = CORRELATE(X [,Y])

Arguments

X

An n-element vector or an m x n array. X can be integer, single-, or double-precision floating-point.

Y

An n-element integer, single-, or double-precision floating-point vector. If X is an m x n array, Y should not be supplied.

Keywords

COVARIANCE

Set this keyword to compute the sample covariance rather than the correlation coefficient.

Examples

Define the n-element data vectors.

X = [65, 63, 67, 64, 68, 62, 70, 66, 68, 67, 69, 71]

Y = [68, 66, 68, 65, 69, 66, 68, 65, 71, 67, 68, 70]

Compute the linear Pearson correlation coefficient of x and y. The result should be 0.702652:

PRINT, CORRELATE(X, Y)

IDL prints:

0.702652

Compute the covariance of x and y. The result should be 3.66667.

PRINT, CORRELATE(X, Y, /COVARIANCE)

IDL prints:

3.66667

Define an array with x and y as its columns.

A = TRANSPOSE([[X],[Y]])

Compute the correlation matrix.

PRINT, CORRELATE(A)

IDL prints:

  1.00000    0.702652

  0.702652   1.00000

See Also

A_CORRELATE, C_CORRELATE, M_CORRELATE, P_CORRELATE, R_CORRELATE


COS

The periodic function COS returns the trigonometric cosine of X.

Calling Sequence

Result = COS(X)

Arguments

X

The angle for which the cosine is desired, specified in radians. If X is double-precision floating or complex, the result is of the same type. All other types are converted to single-precision floating-point and yield floating-point results. When applied to complex numbers:

COS(x ) = COMPLEX(cos I cosh R , -sin R sinh (-I))

where R and I are the real and imaginary parts of x.

If X  is an array, the result has the same structure, with each element containing the cosine of the corresponding element of X.

Example

Find the cosine of 0.5 radians and print the result by entering:

PRINT, COS(.5)

IDL prints:

0.877583

See Also

ACOS, COSH


COSH

The COSH function returns the hyperbolic cosine of X.

Calling Sequence

Result = COSH(X)

Arguments

X

The value for which the hyperbolic cosine is desired, specified in radians. If X is double-precision floating, the result is also double- precision. Complex values are not allowed. All other types are converted to single-precision floating-point and yield floating-point results. COSH is defined as:

COSH(u ) = (e^u + e^-u) / 2

If X  is an array, the result has the same structure, with each element containing the hyperbolic cosine of the corresponding element of X.

Example

Find the hyperbolic cosine of 0.5 radians and print the result by entering:

PRINT, COSH(.5)

IDL prints:

1.12763

See Also

ACOS, COS


CRAMER

The CRAMER function solves an n by n linear system of equations using Cramer's rule.

This routine is written in the IDL language. Its source code can be found in the file cramer.pro in the lib subdirectory of the IDL distribution.

Calling Sequence

       Result = CRAMER(A, B)

Arguments

A

An n by n single- or double-precision floating-point array.

B

An n-element single- or double-precision floating-point vector.

 Keywords

DOUBLE

Set this keyword to force the computation to be done in double-precision arithmetic.

ZERO

Use this keyword to set the value of the floating-point zero. A floating-point zero on the main diagonal of a triangular array results in a zero determinant. A zero determinant results in a "Singular matrix" error and stops the execution of CRAMER. For single-precision inputs, the default value is 1.0 x 10^-6. For double-precision inputs, the default value is 1.0 x 10^-12.

Example

Define an array A and right-hand side vector B.

A = [[ 2.0,  1.0,  1.0], $

     [ 4.0, -6.0,  0.0], $

     [-2.0,  7.0,  2.0]]

B = [3.0, 10.0, -5.0]

PRINT, CRAMER(A,B)	Compute the solution and print.

IDL prints:

1.00000     -1.00000      2.00000

See Also

GS_ITER, LU_COMPLEX, CHOLSOL, LUSOL, SVSOL, TRISOL


CREATE_STRUCT

The CREATE_STRUCT function creates a structure given pairs of tag names and values. CREATE_STRUCT can also be used to concatenate structures.

Calling Sequence

Result = CREATE_STRUCT(Tags, Values)

Arguments

Tags

The structure tag names. Tag names may be specified either as scalar strings or string arrays. If scalar strings are specified, values alternate with tag names. If a string array is provided, values must still be specified individually. Tag names must be enclosed in quotes.

Note that structures can contain a maximum of 127 fields.

Values

The value of each field of the structure must be provided.

Keywords

Name

Use this keyword to create a named structure using the specified string as the structure name.

Examples

To create the anonymous structure { A: 1, B: `xxx'} in the variable P, use the following command:

p = CREATE_STRUCT('A', 1, 'B', 'xxx')

To add the fields "FIRST" and "LAST" to the structure, do the following:

p = CREATE_STRUCT('FIRST', 0, p, 'LAST', 3)

The resulting structure contains { FIRST: 0, A: 1, B: 'xxx', LAST: 3}.

Finally, the statement:

p = CREATE_STRUCT(name='list', ['A','B','C'], 1, 2, 3)

creates the structure { LIST, A: 1, B: 2, C: 3}.

See Also

See "Creating and Defining Structures" on page 7-2 of the IDL User's Guide.


CREATE_VIEW

The CREATE_VIEW procedure sets the various system variables required to define a coordinate system and a 3D view. This procedure builds the system viewing matrix (!P.T) in such a way that the correct aspect ratio of the data is maintained even if the display window is not square. CREATE_VIEW also sets the "Data" to "Normal" coordinate conversion factors (!X.S, !Y.S, and !Z.S) so that center of the unit cube will be located at the center of the display window.

CREATE_VIEW sets the following IDL system variables:

!P.T, !P.T3D, !P.Position, !P.Clip, !P.Region !X.S, !X.Style, !X.Range, !X.Margin !Y.S, !Y.Style, !Y.Range, !Y.Margin, !Z.S, !Z.Style, !Z.Range, !Z.Margin.

This routine is written in the IDL language. Its source code can be found in the file create_view.pro in the lib subdirectory of the IDL distribution.

Calling Sequence

CREATE_VIEW

Arguments

This procedure has no required arguments.

Keywords

AX

A floating-point value specifying the orientation (X rotation) of the view. The default is (0.0).

AY

A floating-point value specifying the orientation (Y rotation) of the view. The default is (0.0).

AZ

A floating-point value specifying the orientation (Z rotation) of the view. The default is (0.0).

PERSP

A floating-point value specifying the perspective projection distance. A value of (0.0) indicates an isometric projection (NO perspective). The default is (0.0).

RADIANS

Set this keyword if AX, AY, and AZ are specified in radians. The default is degrees.

WINX

A long integer specifying the X size, in pixels, of the window that the view is being set up for. The default is (640).

WINY

A long integer specifying the Y size, in pixels, of the window that the view is being set up for. The default is (512).

XMAX

A scalar specifying the maximum data value on the X axis. The default is (1.0).

XMIN

A scalar specifying the minimum data value on the X axis. The default is (0.0).

YMAX

A scalar specifying the maximum data value on the Y axis. The default is (1.0).

YMIN

A scalar specifying the minimum data value on the Y axis. The default is (0.0).

ZFAC

Set this keyword to a floating-point value to expand or contract the view in the Z dimension. The default is (1.0).

ZMAX

A scalar specifying the maximum data value on the Z axis. The default is (1.0).

ZMIN

A scalar specifying the minimum data value on the Z axis. The default is (0.0).

ZOOM

A floating-point number or 3-element vector specifying the view zoom factor. If zoom is a single value then the view will be zoomed equally in all 3 dimensions. If zoom is a 3-element vector then the view will be scaled zoom(0) in X, zoom(1) in Y, and zoom(2) in Z. The default is (1.0).

Example

Set up a view to display an iso-surface from volumetric data. First, create some data:

vol = FLTARR(40, 50, 30)

vol(3:36, 3:46, 3:26) = RANDOMU(S, 34, 44, 24)

FOR I = 0, 10 DO vol = SMOOTH(vol, 3)

Generate the iso-surface.

SHADE_VOLUME, vol, 0.2, polygon_list, vertex_list, /LOW

Set up the view. Note that the subscripts into the Vol array range from 0 to 39 in X, 0 to 49 in Y, and 0 to 29 in Z. As such, the 3-D coordinates of the iso-surface (vertex_list) may have the same range. Set XMIN, YMIN, and ZMIN to zero (the default), and set XMAX=39, YMAX=49, and ZMAX=29.

WINDOW, XSIZE = 600, YSIZE = 400

CREATE_VIEW, XMAX = 39, YMAX = 49, ZMAX = 29, $

  AX = (-60.0), AZ = (30.0), WINX = 600, WINY = 400, $

  ZOOM = (0.7), PERSP = (1.0)

Display the iso-surface in the specified view.

img = POLYSHADE(polygon_list, vertex_list, /DATA, /T3D)

TVSCL, img

See Also

SCALE3, T3D


CROSSP

The CROSSP function returns a floating-point vector that is the vector (or cross) product of two 3-element vectors, V1 and V2.

Calling Sequence

Result = CROSSP(V1, V2)

Arguments

V1, V2

Three-element vectors.

See Also

"Matrix Multiplication" on page 4-10 of the IDL User's Guide.


CT_LUMINANCE

The CT_LUMINANCE function calculates the luminance of colors. The function returns an array containing the luminance values of the specified colors. If the R, G, and B parameters are not specified, or if R is of integer, byte or long type, the result is a longword array with the same number of elements as the input arguments. Otherwise, the result is a floating-point array with the same number of elements as the input arguments.

This routine is written in the IDL language. Its source code can be found in the file ct_luminance.pro in the lib subdirectory of the IDL distribution.

Calling Sequence

Result = CT_LUMINANCE([R, G, B])

Arguments

R

An array representing the red color table. If omitted, the color values from either the COLORS common block, or the current color table are used.

G

An array representing the green color table. This parameter is optional.

B

An array representing the blue color table. This parameter is optional.

Keywords

BRIGHT

Set this keyword to a named variable in which the array index of the brightest color is returned.

DARK

Set this keyword to a named variable in which the array index of the darkest color is returned.

READ_TABLES

Set this keyword, and don't specify the R, G, and B arguments, to read colors directly from the current colortable (using TVLCT, /GET) instead of using the COLORS common block.

See Also

GAMMA_CT, STRETCH


CTI_TEST

The CTI_TEST function constructs a "contingency table" from an array of observed frequencies and tests the hypothesis that the rows and columns are independent using an extension of the chi-square goodness-of-fit test. The result is a two-element vector containing the chi-square test statistic X2 and the one-tailed probability of obtaining a value of X2 or greater.

This routine is written in the IDL language. Its source code can be found in the file cti_test.pro in the lib subdirectory of the IDL distribution.

Calling Sequence

Result = CTI_TEST(Obfreq)

Arguments

Obfreq

An m x n array containing observed frequencies. Obfreq can contain either integer, single-, double-precision floating-point values.

Keywords

COEFF

Set this keyword to a named variable that will contain the Coefficient of Contingency. The Coefficient of Contingency is a non-negative scalar, in the interval [0.0, 1.0], which measures the degree of dependence within a contingency table. The larger the value of COEFF, the greater the degree of dependence.

CORRECTED

Set this keyword to use the "Yate's Correction for Continuity" when computing the Chi-squared test statistic, X2. The Yate's correction always decreases the magnitude of X2. In general, this keyword should be set for small sample sizes.

CRAMV

Set this keyword to a named variable that will contain Cramer's V. Cramer's V is a non-negative scalar, in the interval [0.0, 1.0], which measures the degree of dependence within a contingency table.

DF

Set this keyword to a named variable that will contain the number of degrees of freedom used to compute the probability of obtaining the value of the Chi-squared test statistic or greater. DF = (n - 1) * (m - 1) where m and n are the number of columns and rows of the contingency table, respectively.

EXFREQ

Set this keyword to a named variable that will contain an array of m-columns and n-rows containing expected frequencies. The elements of this array are often referred to as the "cells" of the expected frequencies. The expected frequency of each cell is computed as the product of row and column marginal frequencies divided by the overall total of observed frequencies.

RESIDUAL

Set this keyword to a named variable that will contain an array of m-columns and n-rows containing signed differences between corresponding cells of observed frequencies and expected frequencies.

Example

Define a 5-column and 4-row array of observed frequencies.

obfreq = [[748, 821, 786, 720, 672], $

          [ 74,  60,  51,  66,  50], $

          [ 31,  25,  22,  16,  15], $

          [  9,  10,   6,   5,   7]]

Test the hypothesis that the rows and columns of "obfreq" contain independent data at the 0.05 significance level.

result = CTI_TEST(obfreq, COEFF = coeff)

The result should be the two-element vector [14.3953, 0.276181].

The computed value of 0.276181 indicates that there is no reason to reject the proposed hypothesis at the 0.05 significance level. The Coefficient of Contingency returned in the parameter "coeff" (coeff = 0.0584860) also indicates the lack of dependence between the rows and columns of the observed frequencies. Setting the CORRECTED keyword returns the two-element vector [12.0032, 0.445420] and (coeff = 0.0534213) resulting in the same conclusion of independence.

See Also

CORRELATE, M_CORRELATE, XSQ_TEST


CURSOR

The CURSOR procedure is used to read the position of the interactive graphics cursor from the current graphics device. Note that not all graphics devices have interactive cursors. CURSOR enables the graphic cursor on the device and optionally waits for the operator to position it. On devices that have a mouse, CURSOR normally waits until a mouse button is pressed (or already down). If no mouse buttons are present, CURSOR waits for a key on the keyboard to be pressed.

The system variable !ERR is set to the button status, or ASCII code of the key, if no mouse is present. Each mouse button is assigned a bit in !ERR, bit 0 is the left most button, bit 1 the next, etc.

Using CURSOR with Draw Widgets

Note that the CURSOR procedure is only for use with IDL graphics windows. It should not be used with draw widgets. To obtain the cursor position and button state information from a draw widget, examine the X, Y, PRESS, and RELEASE fields in the structures returned by the draw widget in response to cursor events.

Using CURSOR with the TEK Device

Note that for the CURSOR procedure to work properly with Tektronix terminals, you may need to execute the command, DEVICE, GIN_CHARS=6.

Calling Sequence

CURSOR, X, Y [, Wait]

Arguments

X

A named variable to receive the cursor's current column position.

Y

A named variable to receive the cursor's current row position.

Wait

An integer that specifies the conditions under which CURSOR returns. This parameter can be used interchangeably with the keyword parameters listed below that specify the type of wait. The default value is 1. The table below describes each type of wait.

Note that not all modes of waiting work with all display devices.

Wait Value	Corresponding Keyword	Action
0	NOWAIT	Return immediately.
1	WAIT	Return if a button is down.
2	CHANGE	Return if a button is pressed, released, or the pointer is moved.
3	DOWN	Return when a button down transition is detected.
4	UP	Return when a button up transition is detected.
Table 1.2 Values for CURSOR Wait Parameter

Keywords

CHANGE

Set this keyword to wait for pointer movement or button transition within the currently selected window.

DATA

Set this keyword to return X and Y in data coordinates.

DOWN

Set this keyword to wait for a button down transition within the currently selected window.

DEVICE

Set this keyword to return X and Y in device coordinates.

NORMAL

Set this keyword to return X and Y in normalized coordinates.

NOWAIT

Set this keyword to read the pointer position and button status and return immediately. If the pointer is not within the currently selected window, the device coordinates -1, -1 are returned.

UP

Set this keyword to wait for a button up transition within the current window.

WAIT

Set this keyword to wait for a button to be depressed within the currently selected window. If a button is already pressed, return immediately.

Example

Activate the graphics cursor, select a point in the graphics window, and return the position of the cursor in device coordinates. Enter:

CURSOR, X, Y, /DEVICE

Move the cursor over the graphics window and press the mouse button. The position of the cursor in device coordinates is stored in the variables X and Y. To label the location, enter:

XYOUTS, X, Y, 'X marks the spot.', /DEVICE

See Also

RDPIX, TVCRS,  CURSOR_CROSSHAIR (and other CURSOR_ keywords), WIDGET_DRAW


CURVEFIT

The CURVEFIT function uses a gradient-expansion algorithm to compute a non-linear least squares fit to a user-supplied function with an arbitrary number of parameters. The user-supplied function may be any non-linear function where the partial derivatives are known or can be approximated. Iterations are performed until the chi square changes by 0.1% or less, or until 20 iterations have been performed.

This routine is written in the IDL language. Its source code can be found in the file curvefit.pro in the lib subdirectory of the IDL distribution.

Calling Sequence

Result = CURVEFIT(X, Y, W, A [, Sigmaa])

Arguments

X

An n-element vector of independent variables.

Y

A vector of dependent variables, the same length as X.

W

A vector of weights, the same length as X. For no weighting, specify Wi = 1.0. For instrumental weighting, specify Wi = 1.0/Yi, etc.

A

A vector with as many elements as the number of terms in the user-supplied function, containing the initial estimate for each parameter. If A is double-precision, calculations are performed in double-precision arithmetic, otherwise they are performed in single-precision arithmetic.

Sigmaa

A named variable that will contain a vector of standard deviations for the elements of A.

Keywords

CHI2

Set this keyword equal to a named variable that will contain the value of chi-squared.

FUNCTION_NAME

Use this keyword to specify the name of the function to fit. If this keyword is omitted, CURVEFIT assumes that the IDL procedure FUNCT is to be used. FUNCT evaluates the sum of a Gaussian and a second-order polynomial.

The function to be fit must be written as an IDL procedure and compiled prior to calling CURVEFIT. The procedure must accept values of X (the independent variable), and A (the fitted function's initial parameter values). It must return values for F (the function's value at  X), and optionally PDER (a 2D array of partial derivatives).

See the Example section below for an example function.

ITER

Set this keyword equal to a named variable that will contain the actual number of iterations performed.

ITMAX

Set this keyword to specify the maximum number of iterations. The default value is 20.

NODERIVATIVE

If this keyword is set, the routine specified by the FUNCTION_NAME keyword will not be requested to provide partial derivatives. The partial derivatives will be estimated by CURVEFIT using forward differences. If analytical derivatives are available they should always be used.

TOL

Use this keyword to specify the desired convergence tolerance. The routine returns when the relative decrease in chi-squared is less than TOL in one interation. The default value is 1.0 x 10^-3.

Example

Fit a function of the form F(x) = a * exp(b*x) + c to sample pairs contained in arrays X and Y. The partial derivatives are easily computed symbolically:

df/da = exp(b*x)

df/db = a * x * exp(b*x)

df/dc = 1.0

First, define a procedure to return F(x) and the partial derivatives, given X. Note that A is an array containing the values a, b, and c.

PRO gfunct, X, A, F, pder

  bx = EXP(A(1) * X)

  F = A(0) * bx + A(2)

  IF N_PARAMS() GE 4 THEN $	If the procedure is called with four parameters, calculate the partial derivatives.

    pder= [[bx], [A(0) * X * bx], [replicate(1.0, N_ELEMENTS(X))]]

END

Compute the fit to the function we have just defined. First, define the independent and dependent variables:

X = FLOAT(INDGEN(10))

Y = [12.0, 11.0, 10.2, 9.4, 8.7, 8.1, 7.5, 6.9, 6.5, 6.1]

W = 1.0/Y	Define a vector of weights.

A = [10.0,-0.1,2.0]	Provide an initial guess of the function's parameters.

yfit = CURVEFIT(X, Y, W, A, SIGMAA, FUNCTION_NAME='gfunct')
Compute the parameters.

PRINT, 'Function parameters: ', A	Print the parameters returned in A.

IDL prints:

Function parameters:       9.91120    -0.100883      2.07773

Thus, the function that best fits the data is:

F(x) = 9.91120 * exp(-0.100883x) +  2.07773

See Also

GAUSSFIT, POLY_FIT, POLYFITW, REGRESS, SFIT, SVDFIT


CV_COORD

The CV_COORD function converts 2D and 3D coordinates between the rectangular, polar, cylindrical, and spherical coordinate systems.

If the value passed to the "FROM_" keyword is double precision, then all calculations are performed in double precision and the returned value is double precision. Otherwise, single precision is used. If none of the "FROM_" keywords are specified, 0 is returned. If none of the "TO_" keywords are specified, the input coordinates are returned.

This routine is written in the IDL language. Its source code can be found in the file cv_coord.pro in the lib subdirectory of the IDL distribution.

Calling Sequence

Result = CV_COORD()

Arguments

This function has no required arguments. All data is passed in via keywords.

Keywords

DEGREES

If set, then the input and output coordinates are in degrees (where applicable). Otherwise, the angles are in radians.

FROM_CYLIN

A vector of the form [angle, radius, z], or a (3, n) array of cylindrical coordinates to convert.

FROM_POLAR

A vector of the form [angle, radius], or a (2, n) array of polar coordinates to convert.

FROM_RECT

A vector of the form [x, y] or [ x, y, z], or a (2, n) or (3, n) array containing rectangular coordinates to convert.

FROM_SPHERE

A vector of the form [longitude, latitude, radius], or a (3, n) array of spherical coordinates to convert.

TO_CYLIN

If set, cylindrical coordinates are returned in a vector of the form [angle, radius, z], or a (3, n) array.

TO_POLAR

If set, polar coordinates are returned in a vector of the form [angle, radius], or a (2, n) array.

TO_RECT

If set, rectangular coordinates are returned in a vector of the form [x, y] or [x,  y, z], or a (2, n) or (3, n) array.

TO_SPHERE

If set, spherical coordinates are returned in a vector of the form [longitude, latitude, radius], or a (3, n) array.

Examples

Convert from spherical to cylindrical coordinates:

sph_coord = [[45.0, -60.0, 10.0], [0.0, 0.0, 0.0]]

rect_coord = CV_COORD(FROM_SPHERE=sph_coord, /TO_CYLIN, /DEGREES)

Convert from rectangular to polar coordinates:

rect_coord = [10.0, 10.0]

polar_coord = CV_COORD(FROM_RECT=rect_coord, /TO_POLAR)

See Also

CONVERT_COORD, COORD2TO3, CREATE_VIEW, SCALE3, T3D


CW_ANIMATE

The CW_ANIMATE function creates a compound widget that displays an animated sequence of images using off-screen windows knows as pixmaps. The speed and direction of the display can be adjusted using the widget interface.

CW_ANIMATE provides the graphical interface used by the XINTERANIMATE procedure, which is the preferred routine for displaying animation sequences in most situations. Use this widget instead of XINTERANIMATE when you need to run multiple instances of the animation widget simultaneously. Note that if more than one animation widget is running, they will have to share resources and will display images more slowly than a single instance of the widget.

The returned value of this function is the widget ID of the newly-created animation widget.

This routine is written in the IDL language. Its source code can be found in the file cw_animate.pro in the lib subdirectory of the IDL distribution.

Using CW_ANIMATE

Unlike XINTERANIMATE, using the CW_ANIMATE widget requires calls to two separate procedures, CW_ANIMATE_LOAD and CW_ANIMATE_RUN, to load the images to be animated and to run the animation. Alternatively, you can supply a vector of pre-existing pixmap window IDs, eliminating the need to use CW_ANIMATE_LOAD. The vector of pixmaps is commonly obtained from a call to CW_ANIMATE_GETP applied to a previous animation widget. Once the images are loaded, they are displayed by copying the images from the pixmap or buffer to the visible draw widget.

See the documentation for CW_ANIMATE_LOAD, CW_ANIMATE_RUN, and CW_ANIMATE_GETP for more information.

The only event returned by CW_ANIMATE indicates that the user has clicked on the "End Animation" button. The parent application should use this as a signal to kill the animation widget via WIDGET_CONTROL. When the widget is destroyed, the pixmaps used in the animation are destroyed as well, unless they were saved by a call to CW_ANIMATE_GETP.

See the animation widget's help file (available by clicking the "Help" button on the widget) for more information about the widget's controls.

Calling Sequence

Result = CW_ANIMATE(Parent, Sizex, Sizey, Nframes)

Arguments

Parent

The widget ID of the parent widget.

Sizex

The width of the displayed image, in pixels.

Sizey

The height of the displayed image, in pixels

Nframes

The number of frames in the animation sequence.

Keywords

NO_KILL

Set this keyword to omit the "End Animation" button from the animation widget.

OPEN_FUNC

Set this keyword equal to a scalar string specifying the name of a user-written function that loads animation data. If a function is specified, an "Open ..." button is added to the animation widget.

For an example showing the format and use of an animation-loading function, see the file animate.pro in the general subdirectory of the examples subdirectory of the IDL distribution.

PIXMAPS

Use this keyword to provide the animation widget with a vector of pre-existing pixmap (off screen window) IDs. This vector is usually obtained from a call to CW_ANIMATE_GETP applied to a previous animation widget.

TRACK

Set this keyword to cause the frame slider to track the frame number of the currently-displayed frame.

UVALUE

The "user value" to be assigned to the widget.

Widget Events Returned by the CW_ANIMATE Widget

The only event returned by this widget indicates that the user has pressed the DONE button. The parent application should use this as a signal to kill the animation widget via WIDGET_CONTROL.

Example

Assume the following event handler procedure exists:

PRO EHANDLER, EV

WIDGET_CONTROL, /DESTROY, EV.TOP

end

(If you wish to create this event handler starting from the IDL command prompt, remember to begin with the .RUN command.)

Enter the following commands to open the file ABNORM.DAT (a series of images of a human heart) and load the images it contains into an array H.

OPENR, 1, FILEPATH('abnorm.dat', SUBDIR = 'images')

H = BYTARR(64, 64, 16)

READU, 1, H

CLOSE, 1

H = REBIN(H, 128, 128, 16)

Create an instance of the animation widget and load the frames. Note that because the animation widget is realized before the call to CW_ANIMATE_LOAD, the frames are displayed as they are loaded. This provides the user with an indication of how things are progressing.

base = WIDGET_BASE(TITLE = 'Animation Widget')

animate = CW_ANIMATE(base, 128, 128, 16)

WIDGET_CONTROL, /REALIZE, base

FOR I=0,15 DO CW_ANIMATE_LOAD, animate, FRAME=I, IMAGE=H(*,*,I)

Save the pixmap window IDs for future use:

CW_ANIMATE_GETP, animate, pixmap_vect

Start the animation:

CW_ANIMATE_RUN, animate

XMANAGER, 'CW_ANIMATE Demo', base, EVENT_HANDLER = 'EHANDLER'

Pressing the "End Animation" button kills the application.

See Also

CW_ANIMATE_LOAD, CW_ANIMATE_RUN, CW_ANIMATE_GETP, XINTERANIMATE


CW_ANIMATE_GETP

The CW_ANIMATE_GETP procedure gets a copy of the vector of pixmap window IDs being used by a CW_ANIMATE animation widget. If this routine is called, CW_ANIMATE does not destroy the pixmaps when it is destroyed. You can then provide the pixmaps to a later instance of CW_ANIMATE to re-use them, skipping the pixmap creation and rendering step (CW_ANIMATE_LOAD).

CW_ANIMATE provides the graphical interface used by the XINTERANIMATE procedure, which is the preferred routine for displaying animation sequences in most situations. Use this widget instead of XINTERANIMATE when you need to run multiple instances of the animation widget simultaneously. Note that if more than one animation widget is running, they will have to share resources and will display images more slowly than a single instance of the widget.

This routine is written in the IDL language. Its source code can be found in the file cw_animate.pro in the lib subdirectory of the IDL distribution.

Calling Sequence

CW_ANIMATE_GETP, Widget, Pixmaps

Arguments

Widget

The widget ID of the animation widget (created with CW_ANIMATE) that contains the pixmaps.

Pixmaps

A named variable that will contain a vector of the window IDs of the pixmap windows.

Keywords

KILL_ANYWAY

Set this keyword to ensure that the pixmaps are destroyed anyway when CW_ANIMATE exits, despite the fact that CW_ANIMATE_GETP has been called.

Example

See the documentation for CW_ANIMATE for an example using this procedure.

See Also

CW_ANIMATE, CW_ANIMATE_LOAD, CW_ANIMATE_RUN, XINTERANIMATE


CW_ANIMATE_LOAD

The CW_ANIMATE_LOAD procedure creates an array of pixmaps which are loaded into a CW_ANIMATE compound widget.

CW_ANIMATE provides the graphical interface used by the XINTERANIMATE procedure, which is the preferred routine for displaying animation sequences in most situations. Use this widget instead of XINTERANIMATE when you need to run multiple instances of the animation widget simultaneously. Note that if more than one animation widget is running, they will have to share resources and will display images more slowly than a single instance of the widget.

This routine is written in the IDL language. Its source code can be found in the file cw_animate.pro in the lib subdirectory of the IDL distribution.

Calling Sequence

CW_ANIMATE_LOAD, Widget

Arguments

Widget

The widget ID of the animation widget (created with CW_ANIMATE) into which the image should be loaded.

Keywords

CYCLE

Set this keyword to cause the animation to cycle. Normally, frames are displayed going either forward or backward. If CYCLE is set, the animation reverses direction after the last frame in either direction is displayed.

FRAME

The frame number to be loaded. This is a value between 0 and NFRAMES. If not supplied, frame 0 is loaded.

IMAGE

The image to be loaded.

ORDER

Set this keyword to display images from the top down instead of the default bottom up. This keyword is only used when loading images with the IMAGE keyword.

WINDOW

When this keyword is specified, an image is copied from an existing window to the animation pixmap. Under some windowing systems, this technique is much faster than reading from the display and then loading with the IMAGE keyword.

The value of this parameter is either an IDL window number (in which case the entire window is copied), or a vector containing the window index and the rectangular bounds of the area to be copied. For example:

WINDOW = [Window_Number, X0, Y0, Sx, Sy]

XOFFSET

The horizontal offset, in pixels from the left of the frame, of the image in the destination window.

YOFFSET

The vertical offset, in pixels from the bottom of the frame, of the image in the destination window.

Example

See the documentation for CW_ANIMATE for an example using this procedure. Note that if the widget is realized before calls to CW_ANIMATE_LOAD, the frames are displayed as they are loaded. This provides the user with an indication of how things are progressing.

See Also

CW_ANIMATE, CW_ANIMATE_GETP, CW_ANIMATE_RUN, XINTERANIMATE


CW_ANIMATE_RUN

The CW_ANIMATE_RUN procedure displays a series of images that have been loaded into a CW_ANIMATE compound widget by a call to CW_ANIMATE_LOAD.

CW_ANIMATE provides the graphical interface used by the XINTERANIMATE procedure, which is the preferred routine for displaying animation sequences in most situations. Use this widget instead of XINTERANIMATE when you need to run multiple instances of the animation widget simultaneously. Note that if more than one animation widget is running, they will have to share resources and will display images more slowly than a single instance of the widget.

This routine is written in the IDL language. Its source code can be found in the file cw_animate.pro in the lib subdirectory of the IDL distribution.

Calling Sequence

CW_ANIMATE_RUN, Widget [, Rate]

Arguments

Widget

The widget ID of the animation widget (created with CW_ANIMATE) that will display the animation.

Rate

A value between 0 and 100 that represents the speed of the animation as a percentage of the maximum display rate. The fastest animation has a value of 100 and the slowest has a value of 0. The default animation rate is 100.

The animation rate can also be adjusted after the animation has begun by changing the value of the "Animation Speed" slider.

Keywords

NFRAMES

Set this keyword equal to the number of frames to animate. This number must be less than or equal to the Nframes argument to CW_ANIMATE.

STOP

If this keyword is set, the animation is stopped.

Example

See the documentation for CW_ANIMATE for an example using this procedure.

See Also

CW_ANIMATE, CW_ANIMATE_GETP, CW_ANIMATE_LOAD, XINTERANIMATE


CW_ARCBALL

The CW_ARCBALL function creates a compound widget for intuitively specifying three-dimensional orientations.

The user drags a simulated track-ball with the mouse to interactively obtain arbitrary rotations. Sequences of rotations may be cascaded. The rotations may be unconstrained (about any axis), constrained to the view X, Y, or Z axes, or constrained to the object's X, Y, or Z axis.

This widget is based on "ARCBALL: A User Interface for Specifying Three-Dimensional Orientation Using a Mouse," by Ken Shoemake, Computer Graphics Laboratory, University of Pennsylvania, Philadelphia, PA 19104.

This widget can generate any rotation about any axis. Note, however, that not all rotations are compatible with the IDL SURFACE procedure, which is restricted to rotations that project the object Z axis parallel to the view Y axis.

The returned value of this function is the widget ID of the newly-created ARCBALL widget.

This routine is written in the IDL language. Its source code can be found in the file cw_arcball.pro in the lib subdirectory of the IDL distribution.

Using CW_ARCBALL

Use the command:

WIDGET_CONTROL, id, GET_VALUE = matrix

to return the current 3x3 rotation matrix in the variable matrix.

You can set the arcball to new rotation matrix using the command:

WIDGET_CONTROL, id, SET_VALUE = matrix

after the widget is initially realized.

Calling Sequence

Result = CW_ARCBALL(Parent)

Arguments

Parent

The widget ID of the parent widget.

Keywords

COLORS

A 6-element array containing the color indices to be used.

•	Colors(0) = view axis color,

•	Colors(1) = object axis color,

•	Colors(2) = XZ plane +Y side (body top) color,

•	Colors(3) = YZ plane (fin) color,

•	Colors(4) = XZ plane -Y side (body bottom),

•	Colors(5) = background color.

The default value is  [1,7,2,3,7,0], which yields good colors with the TEK_COLOR table. (white, yellow, red, green, yellow, black).

FRAME

Set this keyword to draw a frame around the widget.

LABEL

Set this keyword to a string containing the widget's label.

RETAIN

Set this keyword to zero, one, or two to specify how backing store should be handled for the draw widget. RETAIN=0 specifies no backing store. RETAIN=1 requests that the server or window system provide backing store. RETAIN=2 specifies that IDL provide backing store directly. See "Backing Store" on page 3-27 of the IDL Reference Guide for details.

SIZE

The size of the square drawable area containing the arcball, in pixels. The default is 192.

UPDATE

Set this keyword to cause the widget will send an event each time the mouse button is released after a drag operation. By default, events are only sent when the "Update" button is pressed.

UVALUE

The "user value" to be assigned to the widget.

VALUE

Set this keyword to a 3 x 3 array that will be the initial value for the rotation matrix. VALUE must be a valid rotation matrix (no translation or perspective) where TRANSPOSE(VALUE) = INVERSE(VALUE). This can be the upper-left corner of !P.T after executing the command

T3D, /RESET, ROTATE = [x,y,z].

The default is the identity matrix.

Widget Events Returned by the CW_ARCBALL Widget

Arcball widgets generate event structures with the following definition:

event = {ID:0L, TOP:0L, HANDLER:0L, VALUE:fltarr(3,3) }

The VALUE field contains the 3 x 3 array representing the new rotation matrix.

Example

See the procedure ARCBALL_TEST, contained in the cw_arcball.pro file. To test CW_ARCBALL, enter the following commands:

.RUN cw_arcball

ARCBALL_TEST

See Also

CREATE_VIEW, SCALE3, T3D


CW_BGROUP

The CW_BGROUP function creates a widget base of buttons. It handles the details of creating the proper base (standard, exclusive, or non-exclusive) and filling in the desired buttons. Events for the individual buttons are handled transparently, and a CW_BGROUP event returned. This event can return any one of the following:

•	the index of the button within the base,

•	the widget ID of the button,

•	the name of the button,

•	an arbitrary value taken from an array of user values.

Only buttons with textual names are handled by this widget. Bitmaps are not understood.

The returned value of this function is the widget ID of the newly-created button group widget.

This routine is written in the IDL language. Its source code can be found in the file cw_bgroup.pro in the lib subdirectory of the IDL distribution.

Using CW_BGROUP

To get or set the value of a CW_BGROUP, use the GET_VALUE and SET_VALUE keywords to WIDGET_CONTROL. The values for different types of CW_BGROUP widgets is shown in the table below:

Type	Value
normal	None
exclusive	Index of currently set button
non-exclusive	Vector indicating the position of each button (1-set, 0-unset)
Table 1.3 Widget Values of Different Button Groups.

Calling Sequence

Result = CW_BGROUP(Parent, Names)

Arguments

Parent

The widget ID of the parent widget.

Names

A string array, one string per button, giving the name of each button.

Keywords

BUTTON_UVALUE

An array of user values to be associated with each button and returned in the event structure.

COLUMN

Buttons will be arranged in the number of columns specified by this keyword.

EVENT_FUNCT

A string containing the name of a function to be called by the WIDGET_EVENT function when an event arrives from a widget in the widget hierarchy rooted at the newly-created widget. This function is called with the return value structure whenever a button is pressed, and follows the conventions for user-written event functions.

EXCLUSIVE

Set this keyword to cause buttons to be placed in an exclusive base, in which only one button can be selected at a time.

FONT

The name of the font to be used for the button titles. This name should be an X Windows font for Unix X displays, or a True Type or PostScript font name for Macintosh/Windows systems. The format of this string is the same as that described for the FONT keyword to the DEVICE command. "FONT" on page 3-11of the IDL Reference Guide. If this keyword is omitted, the default font is used.

FRAME

Specifies the width of the frame to be drawn around the base.

IDS

A named variable in which the button IDs will be stored, as a longword vector.

LABEL_LEFT

Creates a text label to the left of the buttons.

LABEL_TOP

Creates a text label above the buttons.

MAP

Set this keyword to cause the base to be mapped when the widget is realized (the default).

NONEXCLUSIVE

Set this keyword to cause buttons to be placed in an non-exclusive base, in which any number of buttons can be selected at once.

NO_RELEASE

If set, button release events will not be returned.

RETURN_ID

Set this keyword and the VALUE field of returned events will be the widget ID of the button.

RETURN_INDEX

Set this keyword and the VALUE field of returned events will be the zero-based index of the button within the base. THIS IS THE DEFAULT.

RETURN_NAME

Set this keyword and the VALUE field of returned events will be the name of the button within the base.

ROW

Buttons will be arranged in the number of rows specified by this keyword.

SCROLL

If set, the base will include scroll bars to allow viewing a large base through a smaller viewport.

SET_VALUE

The initial value of the buttons. This is equivalent to the later statement:

WIDGET_CONTROL, widget, SET_VALUE = value

SPACE

The space, in pixels, to be left around the edges of a row or column major base. This keyword is ignored if EXCLUSIVE or NONEXCLUSIVE are specified.

UVALUE

The "user value" to be assigned to the widget.

XOFFSET

The X offset of the widget relative to its parent.

XPAD

The horizontal space, in pixels, between children of a row or column major base. This keyword is ignored if EXCLUSIVE or NONEXCLUSIVE are specified.

XSIZE

The width of the base.

X_SCROLL_SIZE

The width of the viewport if SCROLL is specified.

YOFFSET

The Y offset of the widget relative to its parent.

YPAD

The vertical space, in pixels, between children of a row or column major base. This keyword is ignored if EXCLUSIVE or NONEXCLUSIVE are specified.

YSIZE

The height of the base.

Y_SCROLL_SIZE

The height of the viewport if SCROLL is specified.

Widget Events Returned by the CW_BGROUP Widget

Button Group widgets generates event structures with the following definition:

event = {ID:0L, TOP:0L, HANDLER:0L, SELECT:0, VALUE:0 }

The SELECT field is passed through from the button event. VALUE is either the INDEX, ID, NAME, or BUTTON_UVALUE of the button, depending on how the widget was created.

See Also

CW_PDMENU, WIDGET_BUTTON


CW_CLR_INDEX

The CW_CLR_INDEX function creates a compound widget for the selection of a color index. A horizontal color bar is displayed. Clicking on the bar sets the color index.

The returned value of this function is the widget ID of the newly-created color index widget.

This routine is written in the IDL language. Its source code can be found in the file cw_clr_index.pro in the lib subdirectory of the IDL distribution.

Using CW_CLR_INDEX

To get or set the value of a CW_CLR_INDEX, use the GET_VALUE and SET_VALUE keywords to WIDGET_CONTROL. The value of a CW_CLR_INDEX widget is the index of the color selected.

Calling Sequence

Result = CW_CLR_INDEX(Parent)

Arguments

Parent

The widget ID of the parent widget.

Keywords

COLOR_VALUES

A vector of color indices containing the colors to be displayed in the color bar. If omitted, NCOLORS and START_COLOR specify the range of color indices.

EVENT_FUNCT

A string containing the name of a function to be called by the WIDGET_EVENT function when an event arrives from a widget in the widget hierarchy rooted at the newly-created widget. This function is called with the return value structure whenever a button is pressed, and follows the conventions for user-written event functions.

FRAME

If set, a frame will be drawn around the widget.

LABEL

A text label that appears to the left of the color bar.

NCOLORS

The number of colors to place in the color bar. The default is !D.N_COLORS.

START_COLOR

The starting color index, placed at the left of the bar.

UVALUE

The "user value" to be assigned to the widget.

XSIZE

The width of the color bar in pixels. The default is 192.

YSIZE

The height of the color bar in pixels. The default is 12.

Widget Events Returned by the CW_CLR_INDEX Widget

This widget generates event structures with the following definition:

Event = {CW_COLOR_INDEX, ID: base, TOP: ev.top, HANDLER: 0L, VALUE:c}

The VALUE field is the color index selected.

See Also

CW_COLORSEL, XLOADCT, XPALETTE


CW_COLORSEL

The CW_COLORSEL function creates a compound widget that displays all the colors in the current colormap in a 16 x 16 (320 x 320 pixels) grid. To select a color index, the user moves the mouse pointer over the desired color square and presses any mouse button. Alternatively, the color index can be selected by moving one of the three sliders provided around the grid.

The returned value of this function is the widget ID of the newly-created color index widget.

This routine is written in the IDL language. Its source code can be found in the file cw_colorsel.pro in the lib subdirectory of the IDL distribution.

Using CW_COLORSEL

The command:

WIDGET_CONTROL, SET_VALUE = -1

informs the widget to initialize itself and redraw. It should be called when any of the following happen:

•	the widget is realized,

•	the widget needs redrawing,

•	the brightest or darkest color has changed.

To set the current color index, use the command:

WIDGET_CONTROL, SET_VALUE = index

To retrieve the current color index and store it in the variable var , use the command:

WIDGET_CONTROL, GET_VALUE = var

Calling Sequence

Result = CW_COLORSEL(Parent)

Arguments

Parent

The widget ID of the parent widget.

Keywords

FRAME

If set, a frame is drawn around the widget.

UVALUE

The "user value" to be assigned to the widget.

XOFFSET

The X offset position

YOFFSET

The Y offset position

Widget Events Returned by the CW_COLORSEL Widget

This widget generates event structures with the following definition:

Event = {COLORSEL_EVENT, ID: base, TOP: ev.top, HANDLER: 0L, VALUE:c}

The VALUE field is the color index selected.

See Also

CW_CLR_INDEX, XLOADCT, XPALETTE


CW_DEFROI

The CW_DEFROI function creates a compound widget that allows the user to define a region of interest within a widget draw window. Note: This is a modal widget. No other widget applications will be responsive while this widget is in use.

The returned value of this function is an array of subscripts defining the region. If no region is defined, the scalar -1 is returned.

This routine is written in the IDL language. Its source code can be found in the file cw_defroi.pro in the lib subdirectory of the IDL distribution.

Calling Sequence

Result = CW_DEFROI(Draw)

Arguments

Draw

The widget ID of draw window in which to draw the region. Note that the draw window must have both BUTTON and MOTION events enabled (see "WIDGET_DRAW" on page 1-999 for more information).

Keywords

IMAGE_SIZE

The size of the underlying array, expressed as a two element vector: [columns, rows]. Default is the size of the draw window divided by the value of ZOOM.

OFFSET

The offset of lower left corner of image within the draw window. Default = [0,0].

ORDER

Set this keyword to return inverted subscripts, as if the array were output from top to bottom.

RESTORE

Set this keyword to restore the draw window to its previous appearance on exit. Otherwise, the regions remain on the drawable.

ZOOM

If the image array was expanded (using REBIN, for example) specify this two element vector containing the expansion factor in X and Y. Default = [1,1]. Both elements of ZOOM must be integers.

Widget Events Returned by the CW_DEFROI Widget

Region definition widgets do not return an event structure.

Example

The following two procedures create a region-of-interest widget and its event handler. Create a file containing the program code using a text editor and compile using the .RUN command, or type .RUN at the IDL prompt and enter the lines interactively.

First, create the event handler:

PRO test_event, ev

COMMON T, draw, dbutt, done, image
The common block holds variables that are shared between the routine and its event handler.

IF ev.id EQ dbutt THEN BEGIN	Define what happens when you click the "Draw ROI" button.

    Q = CW_DEFROI(draw)	The ROI definition will be stored in the variable Q.

    HELP, Q	Show the size of the ROI definition array.

    image2 = image	Duplicate the original image.

    image2(Q)=!P.COLOR-1	Set the points in the ROI array Q equal to a single color value.

    WIDGET_CONTROL, draw, GET_VALUE=W
Get the window ID of the draw widget.

    WSET, W	Set the draw widget as the current graphics window.

    TV, image2	Load the image plus the ROI into the draw widget.

ENDIF

IF ev.id EQ done THEN WIDGET_CONTROL, ev.top, /DESTROY
Define what happens when you click the "Done" button.

END

Next, create a draw widget that can call CW_DEFROI. Note that you must specify both button events and motion events when creating the draw widget, if it is to be use with CW_DEFROI.

PRO test

COMMON T, draw, dbutt, done, image

base = WIDGET_BASE(/COLUMN)	Create a base to hold the draw widget and buttons.

draw = WIDGET_DRAW(base, XSIZE=256, YSIZE=256, /BUTTON, /MOTION)
Create a draw widget that will return both button and motion events.

dbutt = WIDGET_BUTTON(base, VALUE='Draw ROI')

done = WIDGET_BUTTON(base, VALUE='Done')

WIDGET_CONTROL, base, /REALIZE

WIDGET_CONTROL, draw, GET_VALUE=W	Get the widget ID of the draw widget.

WSET, W	Set the draw widget as the current graphics window.

image = BYTSCL(SIN(DIST(256)))	Create an original image.

TV, image	Display the image in the draw widget.

XMANAGER, "test", base	Start XMANAGER.

END

See Also

DEFROI


CW_DICE

The CW_DICE function creates a compound widget that implements a single die. The widget uses a button with a bitmap label. If the user presses the button, the die tumbles for a moment, then the new value is displayed and an event is issued.

The primary purpose of this compound widget is to serve as a full example of a realistic compound widget for the IDL User's Guide.

The returned value of this function is the widget ID of the newly-created die widget.

This routine is written in the IDL language. Its source code can be found in the file cw_dice.pro in the lib subdirectory of the IDL distribution.

Using CW_DICE

To get or set the value of a CW_DICE widget, use the GET_VALUE and SET_VALUE keywords to WIDGET_CONTROL. The value of a CW_DICE widget is an integer in the range [1,6].

If a value outside the range [1,6] is specified by the SET_VALUE keyword, the die tumbles to a new value as if the user had pressed the button, but no event is issued.

Calling Sequence

Result = CW_DICE(Parent)

Arguments

Parent

The widget ID of the parent widget.

Keywords

TUMBLE_CNT

The widget simulates the tumbling of a dice by changing the bitmap on the dice several times before settling down to a final value. The number of "tumbles" is specified by the TUMBLE_CNT keyword. The default is 10.

TUMBLE_PERIOD

The amount of time in seconds between each tumble of the dice. The default is .05 seconds.

UVALUE

The "user value" to be assigned to the widget.

Widget Events Returned by the CW_DICE Widget

This widget generates event structures with the following definition:

Event = {CW_DICE_EVENT, ID: base, TOP: ev.top, HANDLER: 0L, VALUE:0}

The VALUE field is the value of the die face. Such events are only sent when the user presses the dice button.

Example

See "Using CW_DICE in a Widget Program" on page 21-33 of the IDL User's Guide  for an example using CW_DICE.


CW_FIELD

The CW_FIELD function creates a widget data entry field. The field consists of a label and a text widget. CW_FIELD can create string, integer, or floating-point fields. The default is an editable string field.

The returned value of this function is the widget ID of the newly-created field widget.

This routine is written in the IDL language. Its source code can be found in the file cw_field.pro in the lib subdirectory of the IDL distribution.

Calling Sequence

Result = CW_FIELD(Parent)

Arguments

Parent

The widget ID of the parent widget.

Keywords

ALL_EVENTS

Like RETURN_EVENTS but return an event whenever the contents of a text field have changed.

COLUMN

Set this keyword to center the label above the text field. The default is to position the label to the left of the text field.

FIELDFONT

A string containing the name of the font to use for the TEXT part of the field.

FLOATING

Set this keyword to have the field accept only floating-point values. Any number or string entered is converted to its floating-point equivalent.

FONT

A string containing the name of the font to use for the TITLE of the field. This name should be an X Windows font for Unix and VMS X displays, or a True Type or PostScript font name for Macintosh/Windows systems. The format of this string is the same as that described for the FONT keyword to the DEVICE command. "FONT" on page 3-11of the IDL Reference Guide. If this keyword is omitted, the default font is used.

FRAME

The width, in pixels, of a frame to be drawn around the entire field cluster. The default is no frame.

INTEGER

Set this keyword to have the field accept only integer values. Any number or string entered is converted to its integer equivalent (using FIX). For example, if 12.5 is entered in this type of field, it is converted to 12.

LONG

Set this keyword to have the field accept only long integer values. Any number or string entered is converted to its long integer equivalent (using LONG).

NOEDIT

Normally, the value in the text field can be edited. Set this keyword to make the field non-editable.

RETURN_EVENTS

Set this keyword to make CW_FIELD return an event when a carriage return is pressed in a text field. The default is not to return events. Note that the value of the text field is always returned when the command

WIDGET_CONTROL, field, GET_VALUE = X

is used.

ROW

Set this keyword to position the label to the left of the text field. This is the default.

STRING

Set this keyword to have the field accept only string values. Numbers entered in the field are converted to their string equivalents. This is the default.

TITLE

A string containing the text to be used as the label for the field. The default is "Input Field".

UVALUE

The "user value" to be assigned to the widget.

VALUE

The initial value in the text widget. This value is automatically converted to the type set by the STRING, INTEGER, and FLOATING keywords described below.

XSIZE

An explicit horizontal size (in characters) for the text input area. The default is to let the window manager size the widget. Using the XSIZE keyword is not recommended.

YSIZE

An explicit vertical size (in lines) for the text input area. The default is 1.

Widget Events Returned by the CW_FIELD Widget

This widget generates event structures with the following definition:

event = { ID:0L, TOP:0L, HANDLER: 0L, VALUE:'', TYPE:0 , UPDATE:0}

The VALUE field is the value of the field. TYPE specifies the type of data contained in the field and can be any of the following: 0=string, 1=floating-point, 2=integer, 3=long integer (the value of TYPE is determined by setting one of the STRING, FLOAT, INTETER, or LONG keywords). UPDATE contains a zero if the field has not been altered or a one if it has.

Example

The code below creates a main base with a field cluster attached to it. The cluster accepts string input, has the title "Name", and has a frame around it:

base = WIDGET_BASE()

field = CW_FIELD(base, TITLE = "Name", /FRAME)

WIDGET_CONTROL, base, /REALIZE

See Also

WIDGET_LABEL, WIDGET_TEXT


CW_FORM

The CW_FORM function is a compound widget that simplifies creating small forms which contain text, numeric fields, buttons, lists, and droplists. Event handling is also simplified.

If the argument Parent is present, the returned value of this function is the widget ID of the newly-created form widget. If Parent is omitted, the form is realized as a modal, top-level widget and the returned value of the function is a structure containing the value of each field in the form when the user finishes.

This routine is written in the IDL language. Its source code can be found in the file cw_form.pro in the lib subdirectory of the IDL distribution.

Using CW_FORM

The form has a value that is a structure with a tag/value pair for each field in the form. Use the command

WIDGET_CONTROL, id, GET_VALUE=v

to read the current value of the form. To set the value of one or more tags, use the command

WIDGET_CONTROL, id, SET_VALUE={ Tag:value, ..., Tag:value}

Calling Sequence

Result = CW_FORM([Parent,] Desc)

Arguments

Parent

The widget ID of the parent widget. Omit this argument to created a modal, top-level widget.

Desc

A string array describing the form. Each element of the string array contains two or more comma-delimited fields. Each string has the following format:

'Depth, Item, Initial value, Keywords'

Use the backslash character ("\") to escape commas that appear within fields. To include the backslash character, escape it with another backslash.

The fields are defined as follows:

Depth

A digit defining the level at which the element will be placed on the form. Nesting is used primarily for layout, with row or column bases.

This field must contain the digit 0, 1, or 2, with the following effects:

•	A "0" continues the current nesting level.

•	A "1" begins a new level under the current level.

•	A "2" denotes the last element at the current level.

Item

A label defining the type of element to be placed in the form. Item must be one of the following: BASE, BUTTON, DROPLIST, FLOAT, INTEGER, LABEL, LIST, or TEXT.

BASEs and LABELs do not return a value in the widget value structure. The other items return the following value types:

•	BUTTON
An integer or integer array. For single buttons, the value is 1 if the button is set, or 0 if it is not set. For exclusive button groups, the value is the index of the currently set button. For non-exclusive button groups, the value is an array containing an element for each button. Array elements are set to 1 if the corresponding button is set, or 0 if it is not set.

•	DROPLIST
An integer. The value set in the widget value structure is the zero-based index of the item is selected.

•	FLOAT
A floating-point value. The value set in the widget value structure is the floating-point value of the field.

•	INTEGER
An integer. The value set in the widget value structure is the integer value of the field.

•	LIST
An integer. The value set in the widget value structure is the zero-based index of the item is selected.

•	TEXT
A string. The value set in the widget value structure is the string value of the field.

Initial value

The initial value of the field. The Initial value field is left empty for BASEs.

For BUTTON, DROPLIST, and LIST items, the value field contains one or more item names, separated by the | character. Strings do not need to be enclosed in quotes. For example, the following line defines an exclusive button group with buttons labeled "one," "two," and "three."

'0, BUTTON, one|two|three, EXCLUSIVE'

For FLOAT, INTEGER, LABEL, and TEXT items, the value field contains the initial value of the field.

Keywords

The Keyword field contains one of the following keywords or keyword=value pairs. Keywords are used to specify optional attributes or options. Any number of Keyword fields may be included in the description string.

Note that preceding keywords with a "/" character has no effect. Simply including a keyword in the Keyword field enables that option.

•	CENTER
Specifies alignment of LABEL items.

•	COLUMN
If present, specifies column layout in BASES or for BUTTON groups.

•	EXCLUSIVE
If present, makes an exclusive set of BUTTONs. The default is nonexclusive.

•	FONT=font name
If present, the font for the item is specified. font name should be an X Windows font for X displays, or a True Type or PostScript font name for Macintosh/Windows systems. The format of this string is the same as that described for the FONT keyword to the DEVICE command. "FONT" on page 3-11of the IDL Reference Guide. If this keyword is omitted, the default font is used.

•	EVENT=function
Specifies the name of a user-written event function that is called whenever the element is changed. The event function is called with the widget event structure as a parameter. It may return an event structure or zero to indicate that no further event processing is desired.

•	FRAME
If present, a frame is drawn around the item. Valid only for BASEs.

•	LABEL_LEFT=label
Place a label to the left of the item. This keyword is valid with BUTTON, DROPLIST, FLOAT, INTEGER and TEXT items.

•	LABEL_TOP=label
Place a label above the item. This keyword is valid with BUTTON, DROPLIST, FLOAT, INTEGER and TEXT items.

•	LEFT
Specifies alignment of LABEL items.

•	QUIT
If the form widget is created as a top-level, modal widget, when the user activates an item defined with this keyword, the form is destroyed and its widget value returned in the widget value structure of CW_FORM. For non-modal form widgets, events generated by changing this item have their QUIT field set to 1.

•	RIGHT
Specifies alignment of LABEL items.

•	ROW
If present, specifies row layout in BASES or for BUTTON groups.

•	SET_VALUE=value
Sets the initial value of BUTTON groups. If the button group is exclusive, value should be the zero-based index of the button to be set.

•	TAG=name
The tag name of this element in the widget's value structure. If not specified, the tag name is TAGnnn, where nnn is the zero-based index of the item in the Desc array.

•	WIDTH=n
Specifies the width, in characters, of a TEXT, INTEGER, or FLOAT item.

Keywords

COLUMN

Set this keyword to make the orientation of the form vertical. If COLUMN is not set, the form is laid out in a horizontal row.

IDS

Set this keyword equal to a named variable into which the widget id of each widget corresponding to an element in the Desc array is stored.

TITLE

Set this keyword equal to a scalar string containing the title of the top level base. TITLE is not used if the form widget has a parent widget.

UVALUE

Set this keyword equal to the user value associated with the form widget.

Widget Events Returned by the CW_FORM Widget

This widget generates event structures each time the value of the form is changed. The event structure has the following definition:

Event = { ID:0L, TOP:0L, HANDLER:0L, TAG:'', VALUE:0, QUIT:0}

The ID field is the widget ID of the CW_FORM widget. The TOP field is the widget ID of the top-level widget. The TAG field contains the tag name of the field that changed. The VALUE field contains the new value of the changed field. The QUIT field contains a zero if the quit flag is not set, or one if it is set.

Example

Define a form with a label, by two vertical button groups (one non-exclusive and the other exclusive), a text field, an integer field, and "OK" and "Done" buttons. If either the "OK" or "Done" buttons are pressed, the form is exited.

Begin by defining a string array describing the form:

desc = [ $

'0, LABEL, Centered Label, CENTER', $

'1, BASE,, ROW, FRAME', $

'0, BUTTON, B1|B2|B3, LABEL_TOP=Nonexclusive:, $

    COLUMN, TAG=bg1', $

'2, BUTTON, E1|E2|E2, EXCLUSIVE,LABEL_TOP=Exclusive:, $

    COLUMN,TAG=bg2', $

'0, TEXT, , LABEL_LEFT=Enter File name:, WIDTH=12, $

    TAG=fname', $

'0, INTEGER, 0, LABEL_LEFT=File size:, WIDTH=6, TAG=fsize', $

'1, BASE,, ROW', $

'0, BUTTON, OK, QUIT,FONT=*helvetica-medium-r-*-180-*, $

    TAG=OK', $

'2, BUTTON, Cancel, QUIT']

To use the form as a modal widget:

a = CW_FORM(desc, /COLUMN)

WIDGET_CONTROL, a, /REALIZE

When the form is exited, (when the user presses the OK or Cancel buttons), a structure is returned as the function's value. We can examine the structure by entering:

HELP, /STRUCTURE, a

IDL displays the following:

BG1    INT       Array(3)	Set buttons = 1, unset = 0.

BG2    INT              1	Second button of exclusive button group was set.

FNAME  STRING  'test.dat'	Value of the text field.

FSIZE  LONG           120	Value of the integer field.

OK     LONG             1	This button was pressed.

TAG8   LONG             0	This button wasn't pressed.

Note that if the "Cancel" button is pressed, the "OK" field is set to 0.

To use CW_FORM inside another widget:

a = WIDGET_BASE(TITLE='Testing')

b = CW_FORM(a, desc, /COLUMN)

WIDGET_CONTROL, a, /REALIZE

XMANAGER, 'Test', a

The event handling procedure (in this example, called TEST_EVENT), may use the TAG field of the event structure to determine which field changed and perform any data validation or special actions required. It can also get and set the value of the widget by calling WIDGET_CONTROL.


CW_FSLIDER

The CW_FSLIDER function creates a slider that select floating-point values.

The returned value of this function is the widget ID of the newly-created slider widget.

This routine is written in the IDL language. Its source code can be found in the file cw_fslider.pro in the lib subdirectory of the IDL distribution.

Using CW_FSLIDER

To get or set the value of a CW_FSLIDER widget, use the GET_VALUE and SET_VALUE keywords to WIDGET_CONTROL.

Calling Sequence

Result = CW_FSLIDER(Parent)

Arguments

Parent

The widget ID of the parent widget.

Keywords

DRAG

Set this keyword to zero if events should only be generated when the mouse is released. If DRAG is non-zero, events will be generated continuously when the slider is adjusted. Note: On slow systems, /DRAG performance can be inadequate. The default is DRAG = 0.

EDIT

Set this keyword to make the slider label be editable. The default is EDIT = 0.

FORMAT

Provides the format in which the slider value is displayed. This should be a format as accepted by the STRING procedure. The default FORMAT is '(G13.6)'

FRAME

Set this keyword to have a frame drawn around the widget. The default is FRAME = 0.

MAXIMUM

The maximum value of the slider. The default is MAXIMUM = 100.

MINIMUM

The minimum value of the slider. The default is MINIMUM = 0.

SUPPRESS_VALUE

If true, the current slider value is not displayed. The default is SUPPRESS_VALUE = 0.

TITLE

The title of slider.

UVALUE

The "user value" to be assigned to the widget.

VALUE

The initial value of the slider

VERTICAL

If set, the slider will be oriented vertically. The default is horizontal.

XSIZE

For horizontal sliders, sets the length.

YSIZE

For vertical sliders, sets the height.

Widget Events Returned by the CW_FSLIDER Widget

This widget generates event structures with the following definition:

Event = { ID:0L, TOP:0L, HANDLER:0L, VALUE:0.0, DRAG:0}

The VALUE field is the floating-point value selected by the slider. The DRAG field reports on whether events are generated continuously (when the DRAG keyword is set) or only when the mouse button is released (the default).

See Also

WIDGET_SLIDER


CW_ORIENT

The CW_ORIENT function creates a compound widget that provides a means to interactively adjust the three-dimensional drawing transformation and resets the !P.T system variable field to reflect the changed orientation.

The returned value of this function is the widget ID of the newly-created orientation-adjustment widget.

This routine is written in the IDL language. Its source code can be found in the file cw_orient.pro in the lib subdirectory of the IDL distribution.

Calling Sequence

Result = CW_ORIENT(Parent)

Arguments

Parent

The widget ID of the parent widget.

Keywords

AX

The initial rotation in the X direction. The default is 30 degrees.

AZ

The initial rotation in the Z direction. The default is 30 degrees.

FRAME

Set this keyword to draw a frame around the widget.

TITLE

The title of the widget.

UVALUE

The "user value" to be assigned to the widget.

XSIZE

Determines the width of the widget. The default is 100.

YSIZE

Determines the height of the widget. The default is 100.

Widget Events Returned by the CW_ORIENT Widget

CW_ORIENT only returns events when the three dimensional drawing transformation has been altered. The !P.T system variable field is automatically updated to reflect the new orientation.

See Also

CW_ARCBALL, T3D


CW_PDMENU

The CW_PDMENU function simplifies creating widget pulldown menus. It has a simpler interface than the XPDMENU procedure, which it replaces. Events for the individual buttons are handled transparently, and a CW_PDMENU event returned. This event can return any one of the following:

•	the Index of the button within the base,

•	the widget ID of the button,

•	the name of the button.

•	the fully qualified name of the button. This allows different sub-menus to contain buttons with the same name in an unambiguous way.

Only buttons with textual names are handled by this widget. Bitmaps are not understood.

The returned value of this function is the widget ID of the newly-created pulldown menu widget.

This routine is written in the IDL language. Its source code can be found in the file cw_pdmenu.pro in the lib subdirectory of the IDL distribution.

Calling Sequence

Result = CW_PDMENU(Parent, Desc)

Arguments

Parent

The widget ID of the parent widget.

Desc

An array of structures, each of which has the following definition:

{CW_PDMENU_S, flags:0, name:'' }

The name tag gives the name of button. The flags field is a bitmask that controls how the button is interpreted:

Value	Meaning
0	This button is neither the beginning nor the end of a pulldown level.
1	This button is the root of a sub-pulldown menu. The sub-buttons start with the next button.
2	This button is the last button at the current pulldown level. The next button belongs to the same level as the current parent button.
3	This button is the root of a sub-pulldown menu, but it is also the last entry of the current level.
Table 1.4 Button Flag Bit Meanings.

Keywords

DELIMITER

The character used to separate the parts of a fully qualified name in returned events. The default is to use the `.' character.

FONT

The name of the font to be used for the button titles. This name should be an X Windows font for Unix and VMS X displays, or a True Type or PostScript font name for Macintosh/Windows systems. The format of this string is the same as that described for the FONT keyword to the DEVICE command. "FONT" on page 3-11of the IDL Reference Guide. If this keyword is omitted, the default font is used.

IDS

A named variable in which the button IDs will be stored as a longword vector.

RETURN_ID

Set this keyword and the VALUE field of returned events will be the widget ID of the button.

RETURN_INDEX

Set this keyword and the VALUE field of returned events will be the zero-based index of the button within the base. THIS IS THE DEFAULT.

RETURN_NAME

Set this keyword and the VALUE field of returned events will be the name of the selected button.

RETURN_FULL_NAME

Set this keyword and the VALUE field of returned events will be the fully qualified name of the selected button. This means that the names of all the buttons from the topmost button of the pulldown menu to the selected one are concatenated with the delimiter specified by the DELIMITER keyword. For example, if the top button was named COLORS, the second level button was named BLUE, and the selected button was named LIGHT, the returned value would be

COLORS.BLUE.LIGHT

This allows different submenus to have buttons with the same name (e.g., COLORS.RED.LIGHT).

UVALUE

The "user value" to be assigned to the widget.

XOFFSET

The X offset of the widget relative to its parent.

YOFFSET

The Y offset of the widget relative to its parent.

Widget Events Returned by the CW_PDMENU Widget

This widget generates event structures with the following definition:

event = { ID:0L, TOP:0L, HANDLER:0L, VALUE:0 }

VALUE is either the INDEX, ID, NAME, or FULL_NAME of the button, depending on how the widget was created.

Example

The following is the description of a menu bar with two buttons, "Colors" and "Quit". Colors is a pulldown containing the colors "Red", "Green", Blue", "Cyan", and "Magenta". Blue is a sub-pulldown containing "Light", "Medium", "Dark", "Navy", and "Royal":

The following small program can be used with the above description to create the specified menu:

PRO PD_EXAMPLE

Make sure CW_PDMENU_S is defined:

junk = {CW_PDMENU_S, flags:0, name:'' }

Define the menu:

desc = [ { CW_PDMENU_S, 1, 'Colors' }, $

         { CW_PDMENU_S, 0, 'Red' }, $

         { CW_PDMENU_S, 0, 'Green' }, $

         { CW_PDMENU_S, 1, 'Blue' }, $

         { CW_PDMENU_S, 0, 'Light' }, $

         { CW_PDMENU_S, 0, 'Medium' }, $

         { CW_PDMENU_S, 0, 'Dark' }, $

         { CW_PDMENU_S, 0, 'Navy' }, $

         { CW_PDMENU_S, 2, 'Royal' }, $

         { CW_PDMENU_S, 0, 'Cyan' }, $

         { CW_PDMENU_S, 2, 'Magenta' }, $

         { CW_PDMENU_S, 2, 'Quit' } ]

Create the widget:

base = WIDGET_BASE()

menu = CW_PDMENU(base, desc, /RETURN_FULL_NAME)

WIDGET_CONTROL, /REALIZE, base

Provide a simple event handler:

REPEAT BEGIN

ev = WIDGET_EVENT(base)

PRINT, ev.value

END UNTIL ev.value EQ 'Quit'

WIDGET_CONTROL, /DESTROY, base

END

END

See Also

CW_BGROUP, WIDGET_DROPLIST


CW_RGBSLIDER

The CW_RGBSLIDER function creates a compound widget that provides three sliders for adjusting color values. The RGB, CMY, HSV, and HLS color systems can all be used. No matter which color system is in use, the resulting color is always supplied in RGB, which is the base system for IDL.

The returned value of this function is the widget ID of the newly-created color adjustment widget.

This routine is written in the IDL language. Its source code can be found in the file cw_rgbslider.pro in the lib subdirectory of the IDL distribution.

Using CW_RGBSLIDER

The CW_RGBSLIDER widget consists of a pulldown menu which allows the user to change between the supported color systems, and three color adjustment sliders, allowing the user to select a new color value.

Calling Sequence

Result = CW_RGBSLIDER(Parent)

Arguments

Parent

The widget ID of the parent widget.

Keywords

CMY

If set, the initial color system used is CMY.

COLOR_INDEX

If set, display a small rectangle with the selected color, using the given index. The color is updated as the values are changed.

DRAG

Set this keyword and events will be generated continuously when the sliders are adjusted. If not set, events will only be generated when the mouse button is released. Note: On slow systems, /DRAG performance can be inadequate. The default is DRAG = 0.

FRAME

If set, a frame will be drawn around the widget. The default is FRAME = 0.

HSV

If set, the initial color system used is HSV.

HLS

If set, the initial color system used is HLS.

LENGTH

The length of the sliders. The default = 256.

RGB

If set, the initial color system used is RGB. This is the default.

UVALUE

The "user value" to be assigned to the widget.

VERTICAL

If set, the sliders will be oriented vertically. The default is VERTICAL = 0.

Widget Events Returned by the CW_RGBSLIDER Widget

This widget generates event structures with the following definition:

event = {ID:0L, TOP:0L, HANDLER:0L, R:0B, G:0B, B:0B }

The `R', `G', and `B' fields contain the Red, Green and Blue components of the selected color. Note that CW_RGBSLIDER reports back the Red, Green, and Blue values no matter which color system is selected.

See Also

CW_CLR_INDEX, XLOADCT, XPALETTE


CW_TMPL

The CW_TMPL procedure is a template for compound widgets that use the XMANAGER. Use this template instead of writing your compound widgets from "scratch". This template can be found in the file cw_tmpl.pro in the lib subdirectory of the IDL distribution.

Calling Sequence

Result = CW_TMPL(Parent)

Arguments

Parent

The widget ID of the parent widget of the new compound widget.

Keywords

UVALUE

A user-specified value for the compound widget.

See Also

XMNG_TMPL


CW_ZOOM

The CW_ZOOM function creates a compound widget that displays two images: an original image in one window and a portion of the original image in another. The user can select the center of the zoom region, the zoom scale, the interpolation style, and the method of indicating the zoom center.

The returned value of this function is the widget ID of the newly-created zoom widget.

This routine is written in the IDL language. Its source code can be found in the file cw_zoom.pro in the lib subdirectory of the IDL distribution.

Using CW_ZOOM

The value of the CW_ZOOM widget is the original, un-zoomed image to be displayed (a two-dimensional array). To change the contents of the CW_ZOOM widget, use the command:

WIDGET_CONTROL, id, SET_VALUE = array

where id is the widget ID of the CW_ZOOM widget and  array is the image array. The value of CW_ZOOM cannot be set until the widget has been realized. Note that the size of the original window, set with the XSIZE and YSIZE keywords to CW_ZOOM, must be the size of the input array.

To return the current zoomed image as displayed by CW_ZOOM in the variable array , use the command:

WIDGET_CONTROL, id, GET_VALUE = array

Calling Sequence

Result = CW_ZOOM(Parent)

Arguments

Parent

The widget ID of the parent widget.

Keywords

FRAME

If set, a frame will be drawn around the widget. The default is FRAME = 0.

MAX

The maximum zoom scale, which must be greater than or equal to 1. The default is 20.

MIN

The minimum zoom scale, which must be greater than or equal to 1. The default is 1.

RETAIN

Set this keyword to zero, one, or two to specify how backing store should be handled for both windows. RETAIN=0 specifies no backing store. RETAIN=1 requests that the server or window system provide backing store. RETAIN=2 specifies that IDL provide backing store directly. See "Backing Store" on page 3-27 of the IDL Reference Guide for details.

SAMPLE

Set to zero for bilinear interpolation, or to a non-zero value for nearest neighbor interpolation. Bilinear interpolation gives higher quality results, but requires more time. The default is 0.

SCALE

The initial integer scale factor to use for the zoomed image. The default is SCALE = 4. The scale must be greater than or equal to 1.

TRACK

Set this keyword and events will be generated continuously as the cursor is moved across the original image. If not set, events will only be generated when the mouse button is released. Note: On slow systems, /TRACK performance can be inadequate. The default is 0.

UVALUE

The "user value" to be assigned to the widget.

XSIZE

The width of the window (in pixels) for the original image. The default is XSIZE = 500. Note that XSIZE must be set to the width of the original image array for the image to display properly.

X_SCROLL_SIZE

The width of the visible part of the original image. This may be smaller than the actual width controlled by the XSIZE keyword. The default is 0, for no scroll bar.

X_ZSIZE

The width of the window for the zoomed image. The default is 250.

YSIZE

The height of the window (in pixels) for the original image. The default is 500. Note that YSIZE must be set to the height of the original image array for the image to display properly.

Y_SCROLL_SIZE

The height of the visible part of the original image. This may be smaller than the actual height controlled by the YSIZE keyword. The default is 0, for no scroll bar.

Y_ZSIZE

The height of the window for the zoomed image. The default is 250.

Widget Events Returned by the CW_ZOOM Widget

When the "Report Zoom to Parent" button is pressed, this widget generates event structures with the following definition:

event = {ZOOM_EVENT, ID:0L, TOP:0L, HANDLER:0L, $

         XSIZE:0L, YSIZE:0L, X0:0L, Y0:0L, X1:0L, Y1:0L }

The XSIZE and YSIZE fields contain the dimensions of the zoomed image. The X0 and Y0 fields contain the coordinates of the lower left corner of the original image, and the X1 and Y1 fields contain the coordinates of the upper right corner of the original image.

Example

The following code samples illustrate a use of the CW_ZOOM widget.

First, create an event-handler. Note that clicking on the widget's "Zoom" button displays IDL's help output on the console.

PRO widzoom_event, event

WIDGET_CONTROL, event.id, GET_UVALUE=uvalue

CASE uvalue OF

   'ZOOM': HELP, /STRUCT, event

   'DONE': WIDGET_CONTROL, event.top, /DESTROY

ENDCASE

END

Next, create the widget program:

PRO widzoom

OPENR, lun, FILEPATH('people.dat', SUBDIR='images'), /GET_LUN

image=BYTARR(192,192)

READU, lun, image

FREE_LUN, lun

sz = SIZE(image)

base=WIDGET_BASE(/COLUMN)

zoom=CW_ZOOM(base, XSIZE=sz(1), YSIZE=sz(2), UVALUE='ZOOM')

done=WIDGET_BUTTON(base, VALUE='Done', UVALUE='DONE')

WIDGET_CONTROL, base, /REALIZE

WIDGET_CONTROL, zoom, SET_VALUE=image

XMANAGER, 'widzoom', base

END

Once you have entered these programs, type "widzoom" at the IDL command prompt to run the widget application.

See Also

ZOOM, ZOOM_24


DBLARR

The DBLARR function returns a double-precision, floating-point vector or array.

Calling Sequence

Result = DBLARR(D1, ..., Dn)

Arguments

Di

The dimensions of the result. The dimension parameters can be any scalar expression. Up to eight dimensions can be specified.

Keywords

NOZERO

Normally, DBLARR sets every element of the result to zero. If NOZERO is set, this zeroing is not performed and DBLARR executes faster.

Example

To create D, an 3-element by 3-element, double-precision, floating-point array with every element set to 0.0, enter:

D = DBLARR(3, 3)

See Also

COMPLEXARR, DCOMPLEXARR, FLTARR, INTARR, LONARR, MAKE_ARRAY, STRARR


DCINDGEN

The DCINDGEN function returns a complex, double-precision, floating-point array with the specified dimensions. Each element of the array has its real part set to the value of its one-dimensional subscript. The imaginary part is set to zero.

Calling Sequence

Result = DCINDGEN(D1, ..., Dn)

Arguments

Di

The dimensions of the result. The dimension parameters can be any scalar expression. Up to eight dimensions can be specified.

Example

To create DC, a 4-element vector of complex values with the real parts set to the value of their subscripts, enter:

DC = DCINDGEN(4)

See Also

BINDGEN, CINDGEN, DINDGEN, FINDGEN, INDGEN, LINDGEN, SINDGEN


DCOMPLEX

The DCOMPLEX function returns double-precision complex scalars or arrays given one or two scalars or arrays. If only one parameter is supplied, the imaginary part of the result is zero, otherwise it is set to the value of the Imaginary parameter. Parameters are first converted to double-precision floating-point. If either or both of the parameters are arrays, the result is an array, following the same rules as standard IDL operators. If three parameters are supplied, DCOMPLEX extracts fields of data from Expression.

Calling Sequence

Result = DCOMPLEX(Real [, Imaginary])

or

Result = DCOMPLEX(Expression, Offset, Dim1 [, ..., Dimn])

Arguments

Real

Scalar or array to be used as the real part of the complex result.

Imaginary

Scalar or array to be used as the imaginary part of the complex result.

Expression

The expression from which data is to be extracted.

Offset

Offset from beginning of the Expression data area. Specifying this argument allows fields of data extracted from Expression to be treated as complex data. See the description in Chapter 4 of the IDL User's Guide for details.

Di

When extracting fields of data, the Di arguments specify the dimensions of the result. The dimension parameters can be any scalar expression. Up to eight dimensions can be specified. If no dimension arguments are given, the result is taken to be scalar.

When converting from a string argument, it is possible that the string does not contain a valid floating-point value and no conversion is possible. The default action in such cases is to print a warning message and return 0. The ON_IOERROR procedure can be used to establish a statement to be jumped to in case of such errors.

Example

Create a complex array from two integer arrays by entering the following commands:

A = [1,2,3]	Create the first integer array.

B = [4,5,6]	Create the second integer array.

C = DCOMPLEX(A, B)	Make A the real parts and B the imaginary parts of the new complex array.

PRINT, C	See how the two arrays were combined.

IDL prints:

( 1.0000000, 4.0000000)( 2.0000000, 5.0000000)

( 3.0000000, 6.0000000)

See Also

BYTE, CONJ,  COMPLEX, DOUBLE, FIX, FLOAT, LONG, STRING


DCOMPLEXARR

The DCOMPLEXARR function returns a complex, double-precision, floating-point vector or array.

Calling Sequence

Result = DCOMPLEXARR(D1, ..., Dn)

Arguments

Di

The dimensions of the result. The dimension parameters may be any scalar expression. Up to eight dimensions can be specified.

Keywords

NOZERO

Normally, DCOMPLEXARR sets every element of the result to zero. If the NOZERO keyword is set, this zeroing is not performed, and DCOMPLEXARR executes faster.

Example

To create an empty, 5-element by 5-element, complex array DC, enter:

DC = DCOMPLEXARR(5, 5)

See Also

COMPLEXARR, DBLARR, FLTARR, INTARR, LONARR, MAKE_ARRAY, STRARR


DEFINE_KEY

The DEFINE_KEY procedure programs the keyboard function Key with the string  Value, or with one of the actions specified by the available keywords.

Calling Sequence

DEFINE_KEY, Key [, Value]

Arguments

Key

A scalar string containing the name of a function key to be programmed. IDL maintains an internal list of function key names and the escape sequences they send.

♦	UNIX: Under Unix, if Key is not already on IDL's internal list, you must use the ESCAPE keyword to specify the escape sequence, otherwise, Key alone will suffice. The available function keys and the escape sequences they send vary from keyboard to keyboard. The SETUP_KEYS procedure should be used once at the beginning of the session to enter the keys for the current keyboard. Table 1.5 describes the standard key definitions.

Editing Key	Function
Control-A	Move cursor to start of line
Control-B	Move cursor left one word
Control-D	EOF if current line is empty, EOL otherwise
Control-E	Move to end of line
Control-F	Move cursor right one word
Control-K	Erase from the cursor to the end of the line
Control-N	Move back one line in the recall buffer
Control-R	Retype current line
Control-U	Delete from current position to start of line
Control-W	Delete previous word
Control-X	Delete current character
Backspace, Delete	Delete previous character
ESC-I	Overstrike/insert toggle
ESC-Delete	Delete previous word
Up Arrow	Move back one line in the recall buffer
Down Arrow	Move forward one line in the recall buffer
Left Arrow	Move left one character
Right Arrow	Move right one character
R13	Move cursor left one word (Sun keyboards)
R15	Move cursor right one word (Sun keyboards)
^text	Recall the first line containing text. If text is blank, recall the previous line
Other Characters	Insert character at the current cursor position
Table 1.5 Unix Line Editing Keys

♦	VMS: Under VMS, the key names are those defined by the Screen Management utility (SMG). Table 1.6 describes some of these keys. For a complete description, refer to the VMS RTL Screen Management (SMG$) Manual.

Key Name	Description
DELETE
PF1	Recall most recent command that matches supplied string.
PF2 —PF4	Top row of keypad.
KP0 —KP9	Keypad keys 0 through 9
ENTER	Keypad ENTER key
MINUS	Keypad "-" key
COMMA	Keypad "," key
PERIOD	Keypad "." key
FIND	Editing keypad FIND key
INSERT_HERE	Editing keypad INSERT HERE key
REMOVE	Editing keypad REMOVE key
SELECT	Editing keypad SELECT key
PREV_SCREEN	Editing keypad PREV_SCREEN key
NEXT_SCREEN	Editing keypad NEXT_SCREEN key
Table 1.6 VMS Line Editing Keys

♦	Windows: Under Windows, function keys F1 through F4, F11, and F12 can be customized.

♦	Macintosh: DEFINE_KEY does not currently work with IDL for Macintosh.

Value

The scalar string that will be printed (as if it had been typed manually at the keyboard) when Key is pressed. If Value is not present, and no function is specified for the key with one of the keywords, the key is cleared so that nothing happens when it is pressed.

Keywords

MATCH_PREVIOUS

Set this keyword to program Key to prompt the user for a string, and then search the saved command buffer for the most recently issued command that contains that string. If a match is found, the matching command becomes the current command, otherwise the last command entered is used. Under Unix, the default match key is the up caret "^" key when pressed in column 1. Under VMS, the default match key is PF1.

NOECHO

Set this keyword to enter the Value assigned to Key when pressed, without echoing the string to the screen. This feature is useful for defining keys that perform such actions as erasing the screen. If NOECHO is set, TERMINATE is also assumed to be set.

TERMINATE

If this keyword is set, and Value is present, pressing Key terminates the current input operation after its assigned value is entered. Essentially, an implicit carriage return is added to the end of Value.

Unix Keywords

BACK_CHARACTER

Set this keyword to program Key to move the current cursor position left one character.

BACK_WORD

Set this keyword to program Key to move the current cursor position left one word.

DELETE_CHARACTER

Set this keyword to program Key to delete the character to the left of the cursor.

DELETE_CURRENT

Set this keyword to program Key to delete the character directly underneath the cursor.

DELETE_EOL

Set this keyword to program Key to delete from the cursor position to the end of the line.

DELETE_LINE

Set this keyword to program Key to delete all characters to the left of the cursor.

DELETE_WORD

Set this keyword to programs Key to delete the word to the left of the cursor.

END_OF_LINE

Set this keyword to program Key to move the cursor to the end of the line.

ENTER_LINE

Set this keyword to program Key to enter the current line (i.e., the action normally performed by the "Return" key).

ESCAPE

A scalar string that specifies the escape sequence that corresponds to Key. See the discussion below for further details.

FORWARD_CHARACTER

Set this keyword to program Key to move the current cursor position right one character.

FORWARD_WORD

Set this keyword to program Key to move the current cursor position right one word.

INSERT_OVERSTRIKE_TOGGLE

Set this keyword to program Key to toggle between "insert" and "overstrike" mode. When characters are typed into the middle of a line, insert mode causes the trailing characters to be moved to the right to make room for the new ones. Overstrike mode causes the new characters to overwrite the existing ones.

NEXT_LINE

Set this keyword to program Key to move forward one command in the saved command buffer and make that command the current one.

PREVIOUS_LINE

Set this keyword to program Key to move back one command in the saved command buffer and make that command the current one.

RECALL

Set this keyword to program Key to prompt the user for a command number. The saved command corresponding to the entered number becomes the current command. In order to view the currently saved commands and the number currently associated with each, enter the IDL command:

HELP, /RECALL COMMANDS

The RECALL operation remembers the last command number entered, and if the user simply presses return, it recalls the command currently associated with that saved number. Since the number associated with a given command increases by one each time a new command is saved, this feature can be used to quickly replay a sequence of commands. For example

IDL> PRINT, 1

1

IDL> PRINT, 2

2

IDL> HELP, /RECALL_COMMANDS

Recall buffer length: 20

1               PRINT, 2

2               PRINT, 1

IDL>	User presses key tied to RECALL.

Recall Line #: 2	Line 2 is requested.

IDL> PRINT, 1	Saved command 2 is recalled.

1

Recall Line #: 	User presses return.

IDL> PRINT, 2	Saved command 2 is recalled again.

2

REDRAW

Set this keyword to program Key to retype the current line.

START_OF_LINE

Set this keyword to program Key to move the cursor to the start of the line.

Defining New Function Keys

Under VMS, IDL uses the SMG screen management package, which ensures that IDL command editing behaves in the standard VMS way. Hence, it is not possible to use a key SMG does not understand.

Under Unix, IDL can handle arbitrary function keys. When adding a definition for a function key that is not built into IDL's default list of recognized keys, you must use the ESCAPE keyword to specify the escape sequence it sends. For example, to add a function key named "HELP" which sends the escape sequence <Escape>[28~, use the command:

DEFINE_KEY, 'HELP', ESCAPE = '\033[28~'

This command adds the HELP key to the list of keys understood by IDL. Since only the key name and escape sequence were specified, pressing the HELP key will do nothing. The Value argument, or one of the keywords provided to specify command line editing functions, could have been included in the above statement to program it with an action.

Once a key is defined using the ESCAPE keyword, it is contained in the internal list of function keys. It can then be subsequently redefined without specifying the escape sequence.

It is convenient to include commonly used key definitions in a startup file, so that they will always be available. See "Startup File" on page 2-22 of the IDL User's Guide.

Usually, the SETUP_KEYS procedure is used to define the function keys found on the keyboard, so it is not necessary to specify the ESCAPE keyword. For example, to program key "F2" on a Sun keyboard to redraw the current line:

SETUP_KEYS

DEFINE_KEY, 'F2', /REDRAW

See Also

GET_KBRD


DEFROI

The DEFROI function defines an irregular region of interest of an image using the image display system and the cursor and mouse. The result is a vector of subscripts of the pixels inside the region. Note: the lowest bit in which the write mask is enabled is changed.

DEFROI only works for interactive, pixel oriented devices with a cursor and an exclusive or writing mode. Regions may have at most 1000 vertices.

This routine is written in the IDL language. Its source code can be found in the file defroi.pro in the lib subdirectory of the IDL distribution.

Using DEFROI

After calling DEFROI, click in the image with the left mouse button to mark points on the boundary of the region of interest. The points are connected in sequence. Alternatively, press and hold the left mouse button and drag to draw a curved region. Click the middle mouse button to erase points. The most recently-placed point is erased first. Click the right mouse button to close the region. The function returns after the region has been closed.

Calling Sequence

Result = DEFROI(Sx, Sy [, Xverts, Yverts])

Arguments

Sx, Sy

Integers specifying the horizontal and vertical size of image, in pixels.

Xverts, Yverts

Named vectors that will contain the vertices of the enclosed region.

Keywords

NOREGION

Set this keyword to inhibit the return of the pixel subscripts.

NOFILL

Set this keyword to inhibit filling of the defined region on completion.

RESTORE

Set this keyword to restore the display to its original state upon completion.

X0, Y0

Set these keywords equal to the coordinates of the lower left corner of the displayed image (in device coordinates). If omitted, the default value (0,0) is used.

ZOOM

Set this keyword equal to the zoom factor. If not specified, a value of 1 is assumed.

Example

TVSCL, DIST(200,200)	Create an image.

X = DEFROI(200, 200)	Call DEFROI. The cursor becomes active in the graphics window. Define a region and click the right mouse button.

PRINT, X	Print subscripts of points included in the defined region.

See Also

CW_DEFROI


DEFSYSV

The DEFSYSV procedure creates a new system variable called Name initialized to Value.

Calling Sequence

DEFSYSV, Name, Value [, Read_Only]

Arguments

Name

A scalar string containing the name of the system variable to be created. All system variable names must begin with the character `!'.

Value

An expression from which the type, structure, and initial value of the new system variable is taken. Value can be a scalar, array, or structure.

Read_Only

If the  Read_Only argument is present and nonzero, the value of the newly-created system variable cannot be changed (i.e., the system variable is read-only, like the !PI system variable). Otherwise, the value of the new system variable can be modified.

Keywords

EXISTS

Set this keyword to a named variable that returns 1 if the system variable specified by  Name exists. If this keyword is specified, Value can be omitted. For example, the following commands could be used to check that the system variable XYZ exists:

DEFSYSV, '!XYZ', EXISTS = i

IF i EQ 1 THEN PRINT, '!XYZ exists' ELSE $

          PRINT, '!XYZ does not exist'

Example

To create a new, floating-point, scalar system variable called !NEWVAR with an initial value of 2.0, enter:

DEFSYSV, '!NEWVAR', 2.0

See Also

See "System Variables" on page 3-7 of the IDL User's Guide.


DELETE_SYMBOL
DELETE_SYMBOL (VMS Only)

The DELETE_SYMBOL procedure deletes a DCL (Digital Command Language) interpreter symbol for the current process.

Calling Sequence

DELETE_SYMBOL, Name

Arguments

Name

A scalar string containing the name of the symbol to be deleted.

Keywords

TYPE

Indicates the table from which Name will be deleted. Set TYPE to 1 to specify the local symbol table. Set TYPE to 2 to specify the global symbol table. The default is to search the local table.

See Also

DELLOG (VMS Only), SET_SYMBOL (VMS Only), SETLOG (VMS Only)


DELLOG
DELLOG (VMS Only)

The DELLOG procedure deletes a VMS logical name.

Calling Sequence

DELLOG, Lognam

Arguments

Lognam

A scalar string containing the name of the logical to be deleted.

Keywords

TABLE

A scalar string giving the name of the logical table from which to delete Lognam. If TABLE is not specified, LNM$PROCESS_TABLE is used.

See Also

DELETE_SYMBOL (VMS Only), SET_SYMBOL (VMS Only), SETLOG (VMS Only)


DELVAR

The DELVAR procedure deletes variables from the main IDL program level. DELVAR frees any memory used by the variable and removes it from the main program's symbol table. The following restrictions apply:

•	DELVAR can only be called from the main program level.

•	Each time DELVAR is called, the main program is erased. Variables that are not deleted remain unchanged.

Calling Sequence

DELVAR,  V1, ..., Vn

Arguments

Vi

One or more named variables to be deleted.

Example

Suppose that the variable Q is defined at the main program level. Q can be deleted by entering:

DELVAR, Q

See Also

TEMPORARY


DEMO_MODE

The DEMO_MODE function returns True if IDL is running in the timed demo mode (i.e., a license manager is not running). Calling this function causes a FLUSH, -1 command to be issued.

This routine is written in the IDL language. Its source code can be found in the file demo_mode.pro in the lib subdirectory of the IDL distribution.

Calling Sequence

Result = DEMO_MODE()


DERIV

The DERIV function performs numerical differentiation using 3-point, Lagrangian interpolation and returns the derivative.

Calling Sequence

Result = DERIV([X,] Y)

Arguments

X

The variable to differentiate with respect to. If omitted, unit spacing for Y (i.e., Xi = i) is assumed.

Y

The variable to be differentiated.

Example

X = [ 0.1, 0.3, 0.4, 0.7, 0.9]

Y = [ 1.2, 2.3, 3.2, 4.4, 6.6]

PRINT, DERIV(Y)

IDL prints:

1.20000   1.00000   1.05000   1.70000   2.70000

PRINT, DERIV(X,Y)

IDL prints:

8.00000   6.66667   5.25000   6.80000   10.800

See Also

DERIVSIG


DERIVSIG

The DERIVSIG function computes the standard deviation of a derivative as found by the DERIV function, using the input variables of DERIV and the standard deviations of those input variables.

Calling Sequence

Result = DERIVSIG([X, Y, Sigx,] Sigy)

Arguments

X

The variable to differentiate with respect to. If omitted, unit spacing for Y (i.e., Xi = i) is assumed.

Y

The variable to be differentiated. Omit if X is omitted.

Sigx

The standard deviation of X (either vector or constant). Use "0.0" if the abscissa is exact; omit if X is omitted.

Sigy

The standard deviation of Y. Sigy must be a vector if the other arguments are omitted, but may be either a vector or a constant if X, Y, and  Sigx are supplied.

See Also

DERIV


DETERM

The DETERM function computes the determinant of an n by n array. LU decomposition is used to represent the input array in triangular form. The determinant is then computed as the product of diagonal elements of the triangular form. Row interchanges are tracked during the LU decomposition to ensure the correct sign.

This routine is written in the IDL language. Its source code can be found in the file determ.pro in the lib subdirectory of the IDL distribution.

Calling Sequence

       Result = DETERM(A)

Arguments

A

An n by n single- or double-precision floating-point array.

Keywords

CHECK

Set this keyword to check A for singularity. The determinant of a singular array is returned as zero if this keyword is set. Run-time errors may result if A is singular and this keyword is not set.

DOUBLE

Set this keyword to force the computation to be done in double-precision arithmetic.

ZERO

Use this keyword to set the absolute value of the floating-point zero. A floating-point zero on the main diagonal of a triangular array results in a zero determinant. For single-precision inputs, the default value is 1.0 x 10^-6. For double-precision inputs, the default value is 1.0 x 10^-12. Setting this keyword to a value less than the default may improve the precision of the result.

Example

Define an array A:

A = [[ 2.0,  1.0,  1.0], $

     [ 4.0, -6.0,  0.0], $

     [-2.0,  7.0,  2.0]]

PRINT, DETERM(A)	Compute the determinant.

IDL prints:

-16.0000

See Also

COND, INVERT


DEVICE

The DEVICE procedure provides device-dependent control over the current graphics device (as set by the SET_PLOT routine). The IDL graphics procedures and functions are device-independent. That is, IDL presents the user with a consistent interface to all devices. However, most devices have extra abilities that are not directly available through this interface. DEVICE is used to access and control such abilities. It is used by specifying various keywords that differ from device to device.

See Chapter 3, "IDL Graphics Devices" for a description of the keywords available for each graphics device.

Calling Sequence

DEVICE

Keywords

See "Keywords Accepted by the IDL Devices" on page 3-2.

Example

The following example retains the name of the current graphics device, sets plotting to the PostScript device, makes a PostScript file, then resets plotting to the original device:

mydevice = !D.NAME	The NAME field of the !D system variable contains the name of the current plotting device.

SET_PLOT, 'PS'	Set plotting to PostScript.

DEVICE, FILENAME='myfile.ps', /LANDSCAPE
Use DEVICE to set some PostScript device options.

PLOT, FINDGEN(10)	Make a simple plot to the PostScript file.

DEVICE, /CLOSE	DEVICE closes the PostScript file.

SET_PLOT, mydevice	Return plotting to the original device.

See Also

SET_PLOT


DFPMIN

The DFPMIN procedure minimizes a user-written function Func using the Broyden-Fletcher-Goldfarb-Shanno variant of the Davidon-Fletcher-Powell method, using its gradient as calculated by a user-written function Dfunc and an n-element starting-point vector X.

DFPMIN is based on the routine dfpmin described in section 10.7 of Numerical Recipes in C: The Art of Scientific Computing (Second Edition), published by Cambridge University Press, and is used by permission.

Calling Sequence

DFPMIN, X, Gtol, Fmin, Func, Dfunc

Arguments

X

On input, X is an n-element vector specifying the starting point. On output, it is replaced with the location of the minimum.

Gtol

An input value specifying the convergence requirement on zeroing the gradient.

Fmin

On output, Fmin contains the value at the minimum-point X of the user-supplied function specified by Func.

Func

A scalar string specifying the name of a user-supplied IDL function to be minimized. This function must accept a vector argument X and return a scalar result.

For example, suppose we wish to find the minimum value of the function

y = (x0 ­ 3)^4 + (x1 ­ 2)^2

To evaluate this expression, we define an IDL function named MINIMUM:

FUNCTION minimum, X

  RETURN, (X(0) - 3.0)^4 + (X(1) - 2.0)^2

END

Dfunc

A scalar string specifying the name of a user-supplied IDL function that calculates the gradient of the function specified by Func. This function must accept a vector argument X and return a vector result.

For example, the gradient of the above function is defined by the partial derivatives:

dy/dx0 = 4( x0 ­ 3)^3

dy/dx1 = 2( x1 ­ 2)

We can write a function GRAD to express these relationships in the IDL language:

FUNCTION grad, X

  RETURN, [4.0*(X(0) - 3.0)^3, 2.0*(X(1) - 2.0)]

END

Keywords

DOUBLE

Set this keyword to force the computation to be done in double-precision arithmetic.

EPS

Use this keyword to specify a number close to the machine precision. For single-precision calculations, the default value is 3.0 x 10^-8. For double-precision calculations, the default value is 3.0 x 10^-16.

ITER

Use this keyword to specify a named variable which returns the number of iterations performed.

ITMAX

Use this keyword to specify the maximum number of iterations allowed. The default value is 200.

STEPMAX

Use this keyword to specify the scaled maximum step length allowed in line searches. The default value is 100.0

TOLX

Use this keyword to specify the convergence criterion on X values. The default value is 4 x EPS.

Example

To minimize the function MINIMUM (shown above):

X = [1.0, 1.0]	Make an initial guess (the algorithm's
starting point).

Gtol = 1.0e-7	Set the convergence requirement on the
gradient.

DFPMIN, X, Gtol, Fmin, 'minimum', 'grad'

Find the minimizing value.

PRINT, X	Print the minimizing value.

IDL prints:

  3.00175  2.00000

See Also

POWELL


DIGITAL_FILTER

The DIGITAL_FILTER function returns the coefficients of a non-recursive, digital filter for evenly spaced data points. Frequencies are expressed in terms of the Nyquist frequency, 1/2T, where T is the time between data samples. Highpass, lowpass, bandpass and bandstop filters may be constructed with this function. The resulting vector of coefficients has (2 x Nterms + 1) elements.

This routine is written in the IDL language. Its source code can be found in the file digital_filter.pro in the lib subdirectory of the IDL distribution.

Calling Sequence

Result = DIGITAL_FILTER(Flow, Fhigh, A, Nterms)

Arguments

Flow

The lower frequency of the filter as a fraction of the Nyquist frequency

Fhigh

The upper frequency of the filter as a fraction of the Nyquist frequency.

The following conditions are necessary for various types of filters:

•	No Filtering:	Flow = 0, Fhigh = 1

•	Low Pass:	Flow = 0, 0 < Fhigh < 1

•	High Pass:	0 < Flow < 1, Fhigh =1

•	Band Pass:	0 < Flow < Fhigh < 1

•	Band Stop:	0 < Fhigh < Flow < 1

A

The size of Gibbs phenomenon wiggles in -db. 50 is a good choice.

Nterms

The number of terms in the filter formula. The order of filter.

Example

Coeff = DIGITAL_FILTER(Flow, Fhigh, A, Nterms)	To get coefficients.

Followed by:

Yout = CONVOL(Yin, Coeff)	To apply the filter.

See Also

CONVOL, LEEFILT, MEDIAN, SMOOTH


DILATE

The DILATE function implements the morphologic dilation operator on both binary and grayscale images.

Mathematical morphology is a method of processing digital images on the basis of shape. A discussion of this topic is beyond the scope of this manual. A suggested reference is: Haralick, Sternberg, and Zhuang, "Image Analysis Using Mathematical Morphology," IEEE Transactions on Pattern Analysis and Machine Intelligence, Vol. PAMI-9, No. 4, July, 1987, pp. 532-550. Much of this discussion is taken from that article.

Briefly, the DILATE function returns the dilation of Image by the structuring element Structure. This operator is commonly known as "fill", "expand", or "grow." It can be used to fill "holes" of a size equal to or smaller than the structuring element.

Used with binary images, where each pixel is either 1 or 0, dilation is similar to convolution. Over each pixel of the image, the origin of the structuring element is overlaid. If the image pixel is nonzero, each pixel of the structuring element is added to the result using the "or" operator.

Letting A ⊕ B represent the dilation of an image A by structuring element B, dilation can be defined as:

where (A)b represents the translation of A by  b. Intuitively, for each nonzero element bi,j of B, A is translated by i,j and summed into C  using the "or" operator. For example:

In this example, the origin of the structuring element is at (0,0).

Used with grayscale images, which are always converted to byte type, the DILATE function is accomplished by taking the maximum of a set of sums. It can be used to conveniently implement the neighborhood maximum operator with the shape of the neighborhood given by the structuring element.

Openings and Closings

The opening of image B by structuring element K is defined as (B ⊗ K) ⊕ K. The closing of image B by K is defined as (B ⊕ K) ⊗ K where the "o times" symbol represents the erosion operator implemented by the IDL ERODE function.

As stated by Haralick  et al, the result of iteratively applied dilations and erosions is an elimination of specific image detail smaller than the structuring element without the global geometric distortion of unsuppressed features. For example, opening an image with a disk structuring element smooths the contour, breaks narrow isthmuses, and eliminates small islands and sharp peaks or capes.

Closing an image with a disk structuring element smooths the contours, fuses narrow breaks and long thin gulfs, eliminates small holes, and fills gaps on the contours."

Calling Sequence

Result = DILATE(Image, Structure [, X0, Y0])

Arguments

Image

A one-, two-, or three-dimensional array upon which the dilation is to be performed. If the parameter is not of byte type, a temporary byte copy is obtained. If neither of the keywords GRAY or VALUES is present, the image is treated as a binary image with all nonzero pixels considered as 1.

Structure

A one-, two-, or three-dimensional array that represents the structuring element. Elements are interpreted as binary: values are either zero or nonzero. This argument must have the same number of dimensions as Image.

X0, Y0

Optional parameters specifying the row and column coordinate of the structuring element's origin. If omitted, the origin is set to the center, ([Nx/2], [Ny/2]), where Nx and Ny are the dimensions of the structuring element array. The origin need not be within the structuring element.

Keywords

GRAY

Set this keyword to perform grayscale, rather than binary, dilation. The nonzero elements of the Structure parameter determine the shape of the structuring element (neighborhood). If VALUES is not present, all elements of the structuring element are 0, yielding the neighborhood maximum operator.

VALUES

An array with the same dimensions as Structure providing the values of the structuring element. The presence of this parameter implies grayscale dilation. Each pixel of the result is the maximum of the sum of the corresponding elements of VALUE overlaid with Image.

Example

The following example thresholds a gray scale image at the value of 100, producing a binary image. The result is then "opened" with a 3 pixel by 3 pixel square shape operator, using the DILATE and ERODE operators. The effect is to remove holes, islands, and peninsula smaller than the shape operator:

B = A GE 100	Threshold and make binary image.

S = REPLICATE(1, 3, 3)	Create the shape operator.

C = DILATE(ERODE(B, S), S)	"Opening" operator.

TVSCL, C	Show the result.

See Also

ERODE


DINDGEN

The DINDGEN function returns a double-precision, floating-point array with the specified dimensions. Each element of the array is set to the value of its one-dimensional subscript.

Calling Sequence

Result = DINDGEN(D1, ..., Dn)

Arguments

Di

The dimensions of the result. The dimension parameters may be any scalar expression. Up to eight dimensions may be specified.

Example

To create D, a 100-element, double-precision, floating-point array with each element set to the value of its subscript, enter:

D = DINDGEN(100)

See Also

BINDGEN, CINDGEN, DCINDGEN, FINDGEN, INDGEN, LINDGEN, SINDGEN


DISP_TXT

The DISP_TEXT procedure displays text strings in the current IDL window. The text strings may contain control sequences which define what font, color, and position to use when drawing the text. All text is drawn in device coordinates and 3D transformations have no effect.

Note: An IDL graphics window must exist before calling DISP_TXT.

This routine is written in the IDL language. Its source code can be found in the file disp_txt.pro in the lib subdirectory of the IDL distribution.

Calling Sequence

DISP_TXT, Strings, Fonts, Yspace

Arguments

Strings

A string or string array containing the text to display in the current IDL window. The string(s) may contain control sequences which specify what font, color, and position to use when drawing the text. Control sequences are enclosed in single open quotes. (The single open quote character looks like this: ` and often shares a key with the tilde character: ~.) Control sequences consist of one or more commands separated by commas. Commands start with one of the following upper or lower case characters:

F	-	Specify a new font to use

C 	-	Specify a new color to use

J 	-	Specify a new justification (alignment). 0.0 specifies left justification, 0.5 specifies center justification, and 1.0 specifies right justification.

X 	-	Specify a new absolute X position (in pixels)

Y 	-	Specify a new absolute Y position (in pixels)

H 	-	Shift horizontally a relative amount (in pixels)

V 	-	Shift vertically a relative amount (in pixels)

Here is an example of a text string with an imbedded control sequence to change to font #2, color #255, justification 0.5 (center), and absolute Y position 100:

ABCDEF`F2,C255,J0.5,Y100`GHIJKL

The actual fonts to use are specified by the Fonts argument (see below).

Care must be taken when specifying any justification other than 0.0 (left justify) or the strings may overlap. A good rule of thumb is if center justification (0.5) or right justification (1.0) is desired, then put the control commands before or after a block of text, but not in the middle of it.

One line of text is output for each non-null element in Strings. If an element in Strings is null or contains only a control sequence, then no new line is output. To output a blank line, use a space character on a line by itself.

Fonts

A string or string array containing the font(s) to use. When a command of the form Fn is encountered while processing the text, the nth element of Fonts is passed to the DEVICE, FONT= command. Using the above example, when the command "F2" is processed, the font is set by automatically issuing the command:

DEVICE, FONT=Fonts(2)

If the specified font number is less than zero, or greater than or equal to the number of elements in Fonts, then Fonts(0) is used.

Fonts may be specified using wildcards, and may have an optional field that specifies what style of vector drawn font to use if the specified hardware font does not exist. The optional field is separated from the actual font string by a "|" character. (The optional field is always stripped off before passing the string to the DEVICE, FONT= command.) An example of a Fonts array is as follows:

*helvetica-bold*--12*|10!5 vector|20!3 *helvetica-bold*--24*

This example array specifies the following:

•	Use 12 point helvetica bold hardware font for font F0. If no matching font exists on the current system then use vector font style #5 (duplex roman), and size the font so that it is 10 pixels high. (For a list of the IDL vector drawn fonts, see Chapter 9 of the IDL User's Guide.)

•	Since there is no such thing as a hardware font called "vector," use a software (vector drawn) font for font F1. Draw this font 20 pixels high and use font style #3 (simplex roman).

•	Use 24 point helvetica bold hardware font for font F2. If no matching font exists on the current system then use the most recently specified vector drawn font (since there is no optional field specified for this font). On some Unix systems, it is possible to list the available hardware fonts by using the Unix command xlsfonts.

When running under Microsoft Windows or on the Macintosh, fonts are specified in a slightly different manner. For example, a Helvetica italic 24-point font could be specified by the font definition:

HELVETICA*ITALIC*24

For best results, use a scalable font.

Yspace

The spacing, in pixels, between the baseline of each line of text. If Yspace is negative then the baseline of each line of text will be Yspace pixels above the previous line. Otherwise, each line is placed Yspace pixels below the previous line.

Keywords

COLORS

Normally, color indices can be specified directly in Strings. If COLORS is specified, however, it acts as a translation table to modify the actual color index of the text. For example, when the following string is drawn:

`C13`ABCDEF

It will be drawn in color index 13 if COLORS is not specified. If COLORS is specified then "ABCDEF" will be drawn in color index COLORS(13).

If COLORS is specified and the color number is less than zero, COLORS(0) is used. If the color number is greater than or equal to the number of elements in COLORS then COLORS(n-1) is used (where n is the number of elements in COLORS).

DEF_COLOR

The color index to use when no color is specified in Strings. The default is (!D.N_COLORS - 1L).

DEF_FONT

The font to use when no font has been specified in Strings. DEF_FONT is specified just like the fonts in Fonts (except that no optional field should be used). If no font is specified in Strings and DEF_FONT is not supplied, the default hardware font is used. If no hardware font is available, use a vector drawn font as the default.

DEF_SIZE

The default height (in pixels) of the vector drawn font. The default is !D.Y_CH_SIZE.

DEF_STYLE

The default style (such as !3, !4, etc.) of the vector drawn font. The default is `!3' (simplex roman).

W_ERASE

The color index to erase the window with before drawing the text. If W_ERASE is less than zero then the window will not be erased first (this is the default).

XSTART

The X location (in pixels) at which to start drawing the text. The default is to start near the left edge of the current window (unless the default justification is Center or Right, in which case the default starting X location is set accordingly).

YSTART

The Y location (in pixels) at which to start drawing the text. The default is to start near the top edge of the current window. (Unless Yspace is negative, in which case the default is to start near the bottom edge of the current window).

Example

Display a text screen using DISP_TXT. First, create some strings:

strings = STRARR(4)

strings(0) = '0000000000000'

strings(1) = '`F1,C200`'

strings(2) = 'ABC`X200,V-100`DEF`F0`GHIJKL`C155`abc'

strings(3) = '`C255,F1`ABCDEF`F2`GHIJKL'

Specify the fonts:

fonts = STRARR(3)

fonts(0) = '*helvetica-bold*--24*|20!5'

fonts(1) = 'vector|15!6'

fonts(2) = '8x13|11!3'

Create a window and display the text:

WINDOW, 0

DISP_TXT, strings, fonts, 28, Def_Font='12x24'

See Also

ANNOTATE, XYOUTS


DISSOLVE

The DISSOLVE procedure provides a digital "dissolve" effect for images. The routine copies pixels from the image (arranged into square tiles) to the display in pseudo-random order.

This routine is written in the IDL language. Its source code can be found in the file dissolve.pro in the lib subdirectory of the IDL distribution.

Calling Sequence

DISSOLVE, Image

Arguments

Image

The image to be displayed. It is assumed that the image is already scaled. Byte-valued images display most rapidly.

Keywords

DELAY

The wait between displaying tiles. The default is 0.01 second.

ORDER

The Image display order: 0 = bottom up (the default), 1 = top-down.

SIZ

Size of square tile. The default is 32 x 32 pixels.

X0, Y0

The X and Y offsets of the lower-left corner of the image on screen, in pixels.

Example

DISSOLVE, DIST(200), SIZ=16	Display an image using 16 x 16 pixel tiles.

See Also

ERASE, TV


DIST

The DIST function creates a rectangular array in which the value of each element is proportional to its frequency. This array may be used for a variety of purposes, including frequency-domain filtering and making pretty pictures.

This routine is written in the IDL language. Its source code can be found in the file dist.pro in the lib subdirectory of the IDL distribution.

Calling Sequence

Result = DIST(N [, M])

Arguments

N

The number of columns in the resulting array.

M

The number of rows in the resulting array. If M is omitted, the resulting array will be N by N.

Example

TVSCL, DIST(100)	Display the results of DIST as an image.

See Also

FFT


DO_APPLE_SCRIPT

The DO_APPLE_SCRIPT procedure compiles and executes an AppleScript script, possibly returning a result. DO_APPLE_SCRIPT is only available in IDL for Macintosh.

Calling Sequence

DO_APPLE_SCRIPT, Script

Arguments

Script

A string or array of strings to be compiled and executed by AppleScript.

Keywords

AS_STRING

Set this keyword to cause the result to be returned as a decompiled string. Decompiled strings have the same format as the "The Result" window of Apple's Script Editor.

RESULT

Set this keyword equal to a named variable that will contain the results of the script.

Example

Suppose you wish to retrieve a range of cell data from a Microsoft Excel spreadsheet. The following AppleScript script and command retrieve the first through fifth rows of the first two columns of a spreadsheet titled "Worksheet 1", storing the result in the IDL variable A:

script = [ 'tell application "Microsoft Excel"', $

           'get Value of Range "R1C1:R5C2" of Worksheet 1', $

           'end tell' ]

DO_APPLE_SCRIPT, script, RESULT = a

Similarly, the following lines would copy the contents of the IDL variable A to a range within the spreadsheet:

A = [ 1, 2, 3, 4, 5 ]

script = [ 'tell application "IDL" to copy variable "A"', $

           'into aVariable', $

           'tell application "Excel" to copy aVariable to', $

           'value of range "R1C1:R5C1" of worksheet 1' ]

DO_APPLE_SCRIPT, script

See Also

"Macintosh-Specific OS Abilities" on page 18-35 of the IDL User's Guide.


DOC_LIBRARY

The DOC_LIBRARY procedure extracts documentation headers from one or more IDL programs (procedures or functions). This command provides a standard interface to the operating-system specific DL_DOS, DL_UNIX, and DL_VMS procedures.

The documentation header of the .pro file in question must have the following format:

•	The first line of the documentation block contains only the characters ;+, starting in column 1.

•	The last line of the documentation block contains only the characters ;-, starting in column 1.

•	All other lines in the documentation block contain a ; in column 1.

The file template.pro in the general subdirectory of the examples subdirectory of the IDL distribution contains a template for creating your own documentation headers.

This routine is supplied for users to view online documentation from their own IDL programs. Though it could be used to view documentation headers from the lib subdirectory of the IDL distribution, we do not recommend doing so. The documentation headers on the files in the lib directory are used for historical purposes—most do not contain the most current or accurate documentation for those routines. The most current documentation for IDL's built-in and library routines is found in IDL's online help system (enter ? at the IDL prompt).

This routine is written in the IDL language. Its source code can be found in the file doc_library.pro in the lib subdirectory of the IDL distribution.

Calling Sequence

DOC_LIBRARY [, Name]

Arguments

Name

A string containing the name of the IDL routine in question. Under Windows or Unix, Name can be "*" to get information on all routines.

Keywords (All Platforms)

PRINT

Set this keyword to send the output of DOC_LIBRARY to the default printer. Under Unix, if PRINT is a string, it is interpreted as a shell command used for output with the documentation from DOC_LIBRARY providing standard input (i.e., PRINT="cat > junk").

Unix Keywords

DIRECTORY

A string containing the name of the directory to search. If omitted, the current directory and !PATH are used.

MULTI

Set this keyword to allow printing of more than one file if the requested module exists in more than one directory.

VMS Keywords

FILE

If this keyword is set, the output is left in the file userlib.doc, in the current directory.

PATH

A string that describes an optional directory/library search path. This keyword uses the same format and semantics as !PATH. If omitted, !PATH is used.

OUTPUTS

If this keyword is set, documentation is sent to the standard output unless the PRINT keyword is set.

Example

To view the documentation header for the library function DIST, enter:

DOC_LIBRARY, 'DIST'

See Also

MK_HTML_HELP


DOUBLE

The DOUBLE function returns a result equal to Expression converted to double-precision floating-point.

Calling Sequence

Result = DOUBLE(Expression[, Offset [, Dim1, ..., Dimn]])

Arguments

Expression

The expression to be converted to double-precision floating-point.

Offset

Offset from beginning of the Expression data area. Specifying this argument allows fields of data extracted from Expression to be treated as double-precision floating-point data. See the description in Chapter 4 of the IDL User's Guide for details.

Di

When extracting fields of data, the Di arguments specify the dimensions of the result. The dimension parameters can be any scalar expression. Up to eight dimensions can be specified. If no dimension arguments are given, the result is taken to be scalar.

When converting from a string argument, it is possible that the string does not contain a valid floating-point value and no conversion is possible. The default action in such cases is to print a warning message and return 0. The ON_IOERROR procedure can be used to establish a statement to be jumped to in case of such errors.

Example

Suppose that A contains the integer value 45. A double-precision, floating-point version of A can be stored in B by entering:

B = DOUBLE(A)

See Also

BYTE, COMPLEX, DCOMPLEX, FIX, FLOAT, LONG, STRING


EFONT

The EFONT procedure provides a simple widget-based vector font editor and display. Use this procedure to read and/or modify a local copy of the file hersh1.chr, located in the main IDL directory, which contains the vector fonts used by IDL in plotting. This is a very rudimentary editor. Click the "Help" button on the EFONT main menu for more information.

This routine is written in the IDL language. Its source code can be found in the file efont.pro in the lib subdirectory of the IDL distribution.

Calling Sequence

EFONT, Init_Font

Arguments

Init_Font

The initial font index, from 3 to 29. The default is 3.

Keyword

GROUP

The widget ID of the widget that calls EFONT. If GROUP is set, the death of the caller results in the death of EFONT.

See Also

SHOWFONT, XFONT


EIGENVEC

The EIGENVEC function computes the eigenvectors of an n by n  real, non-symmetric array using Inverse Subspace Iteration. The result is a complex array with a column dimension equal to n and a row dimension equal to the number of eigenvalues. Use ELMHES and HQR to find the eigenvalues of an n by n real, nonsymmetric array.

This routine is written in the IDL language. Its source code can be found in the file eigenvec.pro in the lib subdirectory of the IDL distribution.

Calling Sequence

Result = EIGENVEC(A, Eval)

Arguments

A

An n by n nonsymmetric, single- or double-precision floating-point array.

EVAL

An n-element complex vector of eigenvalues.

Keywords

DOUBLE

Set this keyword to force the computation to be done in double-precision arithmetic.

ITMAX

The maximum number of iterations allowed in the computation of each eigenvector. The default value is 4.

RESIDUAL

Use this keyword to specify a named variable that will contain the residuals for each eigenvalue/eigenvector (λ/x) pair. The residual is based on the definition Ax - λx = 0 and is an array of the same size and type as that returned by the function. The rows of this array correspond to the residuals for each eigenvalue/eigenvector pair.

Note:  This keyword must be initialized to a non-zero value before calling EIGENVEC if the residuals are desired.

Example

Define an n by n real, nonsymmetric array.

A = [[1.0, -2.0, -4.0,  1.0], $

     [0.0, -2.0,  3.0,  4.0], $

     [2.0, -6.0, -1.0,  4.0], $

     [3.0, -3.0,  1.0, -2.0]]

Compute the eigenvalues of A using double-precision complex arithmetic and print the result:

eval = HQR(ELMHES(A), /DOUBLE)

PRINT, eval

IDL prints:

(  0.26366255, -6.1925899)(  0.26366255, 6.1925899)

(  -4.9384492,  0.0000000)(  0.41112406, 0.0000000)

Compute the eigenvectors of A. The eigenvectors are returned in the rows of the resulting array.

residual = 1	Note that the RESIDUAL array must be initialized to a nonzero value.

evec = EIGENVEC(A, eval, RESIDUAL = residual)

Print the eigenvectors.

PRINT, evec(*,0), evec(*,1), evec(*,2), evec(*,3)

IDL prints:

( 0.0076733129,  -0.42912489)(  0.40651652,  0.32973069)

(   0.54537624,  -0.28856257)(  0.33149359, -0.22632585)

(  -0.42145884, -0.081113711)(  0.23867007,  0.46584824)

(  -0.39497143,   0.47402647)( -0.28990600,  0.27760747)

(  -0.54965842,    0.0000000)( -0.18401243,   0.0000000)

(  -0.58124548,    0.0000000)(  0.57111192,   0.0000000)

(   0.79297048,    0.0000000)(  0.50289130,   0.0000000)

( -0.049618509,    0.0000000)(  0.34034720,   0.0000000)

You can check the accuracy of each eigenvalue/eigenvector (λ/x) pair by printing the residual array. All residual values should be floating-point zeros.

See Also

ELMHES, HQR,  TRIQL, TRIRED


ELMHES

The ELMHES function reduces a real, nonsymmetric n by n array A to upper Hessenberg form. The result is an upper Hessenberg array with eigenvalues that are identical to those of the original array A. The Hessenberg array is stored in elements ( j, i) with i ≤ j + 1. Elements with i > j + 1 are to be thought of as zero, but are returned with random values.

ELMHES is based on the routine elmhes described in section 11.5 of Numerical Recipes in C: The Art of Scientific Computing (Second Edition), published by Cambridge University Press, and is used by permission.

Calling Sequence

Result = ELMHES(A)

Arguments

A

An n by n real, nonsymmetric array.

Keywords

DOUBLE

Set this keyword to force the computation to be done in double-precision arithmetic.

COLUMN

Set this keyword if the input array A is in column-major format (composed of column vectors) rather than in row-major format (composed of row vectors).

NO_BALANCE

Set this keyword to disable balancing. By default, a balancing algorithm is applied to  A. Balancing a nonsymmetric array is recommended to reduce the sensitivity of eigenvalues to rounding errors.

Example

See the description of HQR for an example using this function.

See Also

EIGENVEC, HQR,  TRIQL, TRIRED


EMPTY

The EMPTY procedure causes all buffered output for the current graphics device to be written. IDL uses buffered output on many display devices for reasons of efficiency. This buffering leads to rare occasions where a program needs to be certain that data are not waiting in a buffer, but have actually been output. EMPTY is a low-level graphics routine. IDL graphics routines generally handle flushing of buffered data transparently to the user, so the need for EMPTY is very rare.

Calling Sequence

EMPTY

See Also

FLUSH


EOF

The EOF function tests the specified file unit for the end-of-file condition. If the file pointer is positioned at the end of the file, EOF returns true (1), otherwise false (0) is returned.

Note that the EOF function cannot be used with files opened with the NOSTDIO keyword to the OPEN routines. Many of the devices commonly used with NOSTDIO signal their end-of-file by returning a zero transfer count to the I/O operation that encounters the end-of-file.

Calling Sequence

Result = EOF(Unit)

Arguments

Unit

The file unit to test for end-of-file.

Using EOF with VMS Files

Under VMS, the EOF function does not work with files accessed via DECNET or that do not have sequential organization (i.e., relative or indexed). The EOF procedure cannot be used with such files as it will always return "false". Instead, use the ON_IOERROR procedure to detect when the end-of-file occurs.

Examples

If file unit number 1 is open, the end-of-file condition can be checked by examining the value of the expression EOF(1). For example, the following IDL code reads and prints a text file:

OPENR, 1, 'test.lis'	Open the file test.lis.

A = ''	Define a string variable.

WHILE NOT EOF(1) DO BEGIN	Loop until EOF is found.

    READF, 1, A	Read a line of text.

    PRINT, 	Print the line.

    ENDWHILE

CLOSE, 1	Close the file.

See Also

POINT_LUN


ERASE

The ERASE procedure erases the screen of the currently selected graphics device (or starts a new page if the device is a printer). The device is reset to alphanumeric mode if it has such a mode (e.g., Tektronix terminals).

Calling Sequence

ERASE  [, Background_Color]

Arguments

Background_Color

The color index for the screen to be erased to. If this argument is omitted ERASE resets the screen to the default background color (normally 0), stored in the system variable !P.BACKGROUND. Providing a value for Background_Color overrides the default.

Warning: Not all devices support this feature.

Keywords

CHANNEL

The channel or channel mask for the erase operation. This parameter has meaning only when used with devices that support true-color or multiple-display channels. The default value is !P.CHANNEL.

COLOR

Specifies the background color. Using this keyword is analogous to using the Background_Color argument.

Example

TV, DIST(255)	Display a simple image in the current window.

ERASE	Erase the image from the window.

See Also

SET_PLOT, WINDOW, WSET


ERODE

The ERODE function implements the erosion operator on binary and grayscale images and vectors.

See the description of the DILATE function for background on morphological operators. Erosion is the dual of dilation. It does to the background what dilation does to the foreground.

Briefly, the ERODE function returns the erosion of Image by the structuring element Structure. This operator is commonly known as "shrink" or "reduce". It can be used to remove islands smaller than the structuring element.

Over each pixel of the image, the origin of the structuring element is overlaid. If each nonzero element of the structuring element is contained in the image, the output pixel is set to one. Letting A ⊗ B represent the erosion of an image A by structuring element B, erosion can be defined as:

where (A)-b represents the translation of A by  b. The structuring element B can be visualized as a probe that slides across image A, testing the spatial nature of A at each point. If B translated by i,j can be contained in A (by placing the origin of B at i,j), then i,j belongs to the erosion of A by B . For example:

In this example, the origin of the structuring element is at (0, 0).

Used with grayscale images, which are always converted to byte type, the ERODE function is accomplished by taking the minimum of a set of differences. It can be used to conveniently implement the neighborhood minimum operator with the shape of the neighborhood given by the structuring element.

Calling Sequence

Result = ERODE(Image, Structure [, X0, Y0])

Arguments

Image

A one-, two-, or three-dimensional array upon which the erosion is to be performed. If this parameter is not of byte type, a temporary byte copy is obtained. If neither of the keywords GRAY or VALUES is present, the image is treated as a binary image with all nonzero pixels considered as 1.

Structure

A one-, two-, or three-dimensional array to be used as the structuring element. The elements are interpreted as binary values—either zero or nonzero. The structuring element must have the same number of dimensions as Image.

X0, Y0

Optional parameters specifying the row and column coordinate of the structuring element's origin. If omitted, the origin is set to the center, ([Nx/2], [Ny/2]), where Nx and Ny are the dimensions of the structuring element array. The origin need not be within the structuring element.

Keywords

GRAY

Set this keyword to perform grayscale, rather than binary, erosion. Nonzero elements of the Structure parameter determine the shape of the structuring element (neighborhood). If VALUES is not present, all elements of the structuring element are 0, yielding the neighborhood minimum operator.

VALUES

An array of the same dimensions as Structure providing the values of the structuring element. The presence of this keyword implies grayscale erosion. Each pixel of the result is the minimum of Image less the corresponding elements of VALUE.

Example

The following example thresholds a gray scale image at the value of 100, producing a binary image. The result is then "opened" with a 3 pixel by 3 pixel square shape operator, using the ERODE and DILATE operators. The effect is to remove holes, islands, and peninsula smaller than the shape operator:

B = A GE 100	Threshold and make binary image.

S = REPLICATE(1, 3, 3)	Create the shape operator.

C = DILATE(ERODE(B, S), S)	"Opening" operator.

TVSCL, C	Show the result.

See Also

DILATE


ERRORF

The ERRORF function returns the value of the error function:

The result is a double-precision if the argument is double-precision. If the argument is floating-point, the result is floating-point. The result always has the same structure as X. The ERRORF function does not work with complex arguments.

Calling Sequence

Result = ERRORF(X)

Arguments

X

The expression for which the error function is to be evaluated.

Example

To find the error function of 0.4 and print the result, enter:

PRINT, ERRORF(0.4)

IDL prints:

0.428392

See Also

GAMMA, IGAMMA, EXPINT


ERRPLOT

The ERRPLOT procedure plots error bars over a previously drawn plot.

This routine is written in the IDL language. Its source code can be found in the file errplot.pro in the lib subdirectory of the IDL distribution.

Calling Sequence

ERRPLOT, [ X, ] Low, High

Arguments

X

A vector containing the abscissa values at which the error bars are to be plotted. X only needs to be provided if the abscissa values are not the same as the index numbers of the plotted points.

Low

A vector of lower estimates, equal to data - error.

High

A vector of upper estimates, equal to data + error.

Keywords

WIDTH

The width of the error bars. The default is 1% of plot width.

Examples

To plot symmetrical error bars where Y is a vector of data values and ERR is a symmetrical error estimate, enter:

PLOT, Y	Plot data.

ERRPLOT, Y-ERR, Y+ERR	Overplot error bars.

If error estimates are non-symmetrical, provide actual error estimates in the upper and lower arguments.

PLOT,Y 	Plot data.

ERRPLOT, upper, lower	Provide custom upper and lower bounds.

To plot versus a vector of abscissas:

PLOT, X, Y	Plot data (X versus Y).

ERRPLOT, X, Y-ERR, Y+ERR	Overplot error estimates.

See Also

OPLOTERR, PLOT,  PLOTERR


EXECUTE

The EXECUTE function compiles and executes one or more IDL statements contained in a string at run-time. It also returns true (1) if the string was successfully compiled and executed. If an error occurs during either phase, the result is false (0).

Like the CALL_PROCEDURE and CALL_FUNCTION routines, calls to EXECUTE can be nested. However, compiling the string at run-time is inefficient. CALL_FUNCTION and CALL_PROCEDURE provide much of the functionality of EXECUTE without imposing this limitation, and should be used instead of EXECUTE whenever possible.

Calling Sequence

Result = EXECUTE(String)

Arguments

String

A string containing the command(s) to be compiled and executed.

Warning

Do not use EXECUTE to create new variables inside procedures or functions. All variables used by the string that is executed should be referenced or defined when the program unit is originally compiled. New variables cannot be created after a procedure or function is compiled. Attempts to create new variables result in the error " Program data area full".

Example

Create a string that holds a valid IDL command by entering:

com = 'PLOT, [0,1]'

Execute the contents of the string by entering:

R = EXECUTE(com)

A plot should appear. You can confirm that the string was successfully compiled and executed by checking that the value of R is 1.

See Also

CALL_FUNCTION, CALL_PROCEDURE


EXIT

The EXIT procedure quits IDL and exits back to the operating system. All buffers are flushed and open files are closed. The values of all variables that were not saved are lost.

Calling Sequence

EXIT

Keywords

NO_CONFIRM

Set this keyword to suppress any confirmation dialog that would otherwise be displayed in a GUI version of IDL such as IDLtool.

STATUS

Set this keyword equal to an exit status code that will be returned when IDL exits. For example, on a Unix system using the Bourne shell:

$ idl	Start IDL

IDL> exit, status=45	Exit, specifying exit status 45

$ echo $?	Display last exit status code

45

See Also

CLOSE, FLUSH,  STOP, WAIT


EXP

The EXP function returns the natural exponential function of Expression.

Calling Sequence

Result = EXP(Expression)

Arguments

Expression

The expression to be evaluated. If Expression is double-precision floating or complex, the result is of the same type. All other types are converted to single-precision floating-point and yield floating-point results. The definition of the exponential function for complex arguments is:

EXP(x ) = COMPLEX(eR cos I, eR sin I)

where:

R = real part of x, and I = imaginary part of x. If Expression is an array, the result has the same structure, with each element containing the result for the corresponding element of Expression .

Example

Plot a Gaussian with a 1/e width of 10 and a center of 50 by entering:

PLOT, EXP(-(FINDGEN(100)/10. - 5.0)^2)

See Also

ALOG


EXPAND

The EXPAND procedure shrinks or expands a two-dimensional array, using bilinear interpolation. It is similar to the CONGRID and REBIN routines.

This routine is written in the IDL language. Its source code can be found in the file expand.pro in the lib subdirectory of the IDL distribution.

Calling Sequence

EXPAND, A, Nx, Ny, Result

Arguments

A

A two-dimensional array to be magnified.

Nx

Desired size of the X dimension, in pixels.

Ny

Desired size of the Y dimension, in pixels.

Result

A named variable that will contain the magnified array.

Keywords

MAXVAL

Set this keyword equal to the largest good value. Elements greater than this value are set equal to the value of the FILLVAL keyword.

FILLVAL

Set this keyword equal to the value to use when elements larger than MAXVAL are encountered. The default is -1.

See Also

CONGRID, REBIN


EXPAND_PATH

The EXPAND_PATH function is used to expand a simple path-definition string into a full path name for use with the !PATH system variable.

As explained in Chapter 2 of the IDL User's Guide, the search path is maintained in the IDL system variable:

•	!PATH is a list of locations where IDL searches for currently undefined procedures and functions.

The Path Definition String

EXPAND_PATH accepts a single argument, a scalar string that contains a simple path-definition string, that the function expands into a list of directories that can be assigned to !PATH. This string uses the same format as the IDL_PATH environment variable (Unix, Windows) or logical name (VMS). This format is also used in the path preferences dialog (Windows, Macintosh).

The path-definition string is a scalar string containing a list of directories (and in the case of VMS, text library files that are prefixed with the "@" character), separated by a special character (":" for Unix and Macintosh, "," for VMS, and ";" for Windows). Prepending a "+" character to a directory name causes all of its subdirectories to be searched.

If a directory specified in the string does not have a "+" character prepended to it, it is copied to the output string verbatim. However, if it does have a leading "+" then EXPAND_PATH performs the following steps, searching each subdirectory of the specified directory recursively for other subdirectories. All directories found that contain at least one file of the desired type are added to the search path.

♦	UNIX: The directory name is expanded to remove wildcards (~ and *). This avoids overhead IDL would otherwise incur as it searches for library routines. It is discarded from the search path if any of the following is true:

•	It is not a directory.

•	The directory it names does not exist or cannot be accessed.

•	The directory does not contain any .pro or .sav files.

♦	VMS: The directory name is discarded from the search path if any of the following is true:

•	It is not a directory.

•	The directory it names does not exist or cannot be accessed.

•	The directory does not contain any .PRO or .SAV files).

In addition, any text library (.TLB) files are added to the result.

♦	Windows: The directory name is expanded to remove wildcards (*). This avoids overhead IDL would otherwise incur as it searches for library routines. It is discarded from the search path if any of the following is true:

•	It is not a directory.

•	The directory it names does not exist or cannot be accessed.

•	The directory does not contain any .PRO or .SAV files.

♦	Macintosh: The folder name is expanded to remove wildcards (*). This avoids overhead IDL would otherwise incur as it searches for library routines. It is discarded from the search path if any of the following is true:

•	It is not a folder.

•	The folder it names does not exist or cannot be accessed.

•	The folder does not contain any .pro or .sav files.

Calling Sequence

Result = EXPAND_PATH(String)

Arguments

String

A scalar string containing the path-definition string to be expanded. See "The Path Definition String," above, for details.

Keywords

ARRAY

Set this keyword to return the result as a string array with each element containing one path segment. In this case, there is no need for a separator character and none is supplied. Normally, the result is a string array with the various path segments separated with the correct special delimiter character for the current operating system.

COUNT

Set this keyword to a named variable which returns the number of path segments contained in the result.

Example

Under the Unix operating system, the default value of !PATH is specified as "+/usr/local/rsi/idl/lib", unless this default is changed by setting the IDL_PATH environment variable. When IDL starts, one of the first things it does is to run this default value through the EXPAND_PATH function to obtain the actual value for the !PATH system variable. The following statement shows how this expansion might look (assuming that your IDL is installed in /usr/local/rsi/idl):

PRINT, EXPAND_PATH('+/usr/local/rsi/idl/lib')

IDL prints:

/usr/local/rsi/idl/lib

See Also

"Searching for Program Files" on page 2-15, "Environment Parameters Used by IDL" on page 2-24, and "IDL Environment System Variables" on page 3-9, all in the IDL User's Guide.


EXPINT

The EXPINT function returns the value of the exponential integral En(x).

EXPINT is based on the routine expint described in section 6.3 of Numerical Recipes in C: The Art of Scientific Computing (Second Edition), published by Cambridge University Press, and is used by permission.

Calling Sequence

Result = EXPINT(N, X)

Arguments

N

An integer specifying the order of En(x). N can be either a scalar or an array.

X

The value at which En(x) is evaluated. X can be either a scalar or an array.

Note: If an array is specified for both N and X, then EXPINT evaluates En(x) for each Ni and Xi. If either N  or X is a scalar and the other an array, the scalar is paired with each array element in turn.

Keywords

DOUBLE

Set this keyword to force the computation to be done in double-precision arithmetic.

ITMAX

An input integer specifying the maximum allowed number of iterations. The default value is 100.

EPS

Use this keyword to specify a number close to the desired relative error. For single-precision calculations, the default value is 1.0 x 10^-7. For double-precision calculations, the default value is 1.0 x 10^-14.

Example

To compute the value of the exponential integral at the following X values:

X = [1.00, 1.05, 1.27, 1.34, 1.38, 1.50]

Define the parametric X values.

result = EXPINT(1, X)	Compute the exponential integral of order 1.

PRINT, result	Print the result.

IDL prints:

  0.219384 0.201873 0.141911 0.127354 0.119803 0.100020

This is the exact solution vector to six-decimal accuracy.

See Also

ERRORF


EXTRAC

The EXTRAC function returns as its result any rectangular sub-matrix or portion of the parameter array. Note that it is usually more efficient to use the array subscript ranges (the ":" operator; see "Subscript Ranges" on page 5-4 of the IDL User's Guide) to perform such operations. The main advantage to EXTRAC is that, when parts of the specified subsection lie outside the bounds of the array, zeros are entered into these outlying elements.

EXTRAC was originally a built-in system procedure in the PDP-11 version of IDL, and was retained in that form in the original VAX/VMS IDL for compatibility. Most applications of the EXTRAC function are more concisely written using subscript ranges (e.g., X(10:15)). EXTRAC has been rewritten as a library function that provides the same interface as the previous versions.

Note: If you know that the subarray will never lie beyond the edges of the array, it is more efficient to use array subscript ranges (the ":" operator) to extract the data instead of EXTRAC.

This routine is written in the IDL language. Its source code can be found in the file extrac.pro in the lib subdirectory of the IDL distribution.

Calling Sequence

Result = EXTRAC(Array, C1, C2, ..., Cn, S1, S2, ..., Sn)

Arguments

Array

The array from which the subarray will be copied.

Ci

The starting subscript in Array for the subarray. There should be one Ci for each dimension of Array. These arguments must be integers.

Si

The size of each dimension. The result will have dimensions of (S1,  S2, ..., Sn). There should be one Si for each dimension of Array. These arguments must be non-negative.

Examples

Extracting elements from a vector:

A = FINDGEN(1000)	Create a 1000 element floating-point vector with each element set to the value of its subscript.

B = EXTRAC(A, 200, 300)	Extract 300 points starting at A(200) and extending to A(499).

In the next example, the first 49 points extracted—B(0) to B(49)—lie outside the bounds of the vector and are set to 0. B(50) is gets the value of  A(0), B(51) gets the value of A(1)which is 1. Enter:

A = FINDGEN(1000)	Create a 1000 element vector.

B = EXTRAC(A, -50, 100)	Extract 50 elements, 49 of which lie outside the bounds of A.

The following commands illustrate the use of EXTRAC with multi-dimensional arrays. Enter:

A = INTARR(64,64)	Make a 64 by 64 array.

B = EXTRAC(A, 20, 30, 32, 32)	Extract a 32 by 32 portion starting at A(20,30).

As suggested in the discussion above, a better way to perform the same operation as the previous line is:

B = A(20:51, 30:61)	Use the array subscript operator instead of EXTRAC.

Extract the 20th column and 32nd row of A:

B = EXTRAC(A, 19, 0, 1, 64)	Extract 20th column of A.

B = EXTRAC(A, 0, 31, 64, 1)	Extract 32nd row of A.

Take a 32 BY 32 matrix from A starting at A(40,50):

B = EXTRAC(A, 40, 50, 32, 32)	Note that those points beyond the boundaries of A are set to 0.

See Also

See "Subscript Ranges" on page 5-4 of the IDL User's Guide.


EXTRACT_SLICE

This EXTRACT_SLICE function returns a two-dimensional planar slice extracted from 3D volumetric data. The slicing plane can be oriented at any angle and pass through any desired location in the volume.

This routine is written in the IDL language. Its source code can be found in the file extract_slice.pro in the lib subdirectory of the IDL distribution.

Calling Sequence

Result = EXTRACT_SLICE(Vol, Xsize, Ysize, Xcenter, Ycenter, Zcenter, Xrot, Yrot, Zrot)

Arguments

Vol

The volume of data to slice. This argument is a three-dimensional array of any type except string or structure. The planar slice returned by EXTRACT_SLICE has the same data type as  Vol.

Xsize

The desired X size (dimension 0) of the returned slice. To preserve the correct aspect ratio of the data, Xsize should equal Ysize. For optimal results, set Xsize and Ysize to be greater than or equal to the largest of the three dimensions of Vol.

Ysize

The desired Ysize (dimension 1) of the returned slice. To preserve the correct aspect ratio of the data, Ysize should equal Xsize. For optimal results, set Xsize and Ysize to be greater than or equal to the largest of the three dimensions of Vol.

Xcenter

The X coordinate (index) of the point within the volume that the slicing plane passes through. The center of the slicing plane passes through Vol at the coordinate (Xcenter, YCenter, Zcenter).

Ycenter

The Y coordinate (index) of the point within the volume that the slicing plane passes through. The center of the slicing plane passes through Vol at the coordinate (Xcenter, YCenter, Zcenter).

Zcenter

The Z coordinate (index) of the point within the volume that the slicing plane passes through. The center of the slicing plane passes through Vol at the coordinate (Xcenter, YCenter, Zcenter).

Xrot

The X-axis rotation of the slicing plane, in degrees. Before transformation, the slicing plane is parallel to the X-Y plane. The slicing plane transformations are performed in the following order:

•	Rotate Z_rot degrees about the Z axis.

•	Rotate Y_rot degrees about the Y axis.

•	Rotate X_rot degrees about the X axis.

•	Translate the center of the plane to Xcenter, Ycenter, Zcenter.

Yrot

The Y-axis rotation of the slicing plane, in degrees.

Zrot

The orientation Z-axis rotation of the slicing plane, in degrees.

Keywords

RADIANS

Set this keyword to indicate that Xrot, Yrot, and Zrot are in radians. The default is degrees.

OUT_VAL

Set this keyword to a value that will be assigned to elements of the returned slice that lie outside of the original volume.

SAMPLE

Set this keyword to perform nearest neighbor sampling when computing the returned slice. The default is to use bilinear interpolation. A small reduction in execution time results when SAMPLE is set and the OUT_VAL keyword is not used.

Example

Display an oblique slice through volumetric data:

vol = RANDOMU(s, 40, 40, 40)	Create some data.

FOR i=0, 10 DO vol = SMOOTH(vol, 3) Smooth the data.

vol = BYTSCL(vol(3:37, 3:37, 3:37))
Scale the smoothed part into the range of bytes

slice = EXTRACT_SLICE(vol, 40, 40, 17, 17, 17, 30.0, 30.0, $

        0.0, OUT_VAL=0B)	Extract a slice.

TVSCL, REBIN(slice, 400, 400)	Display the 2D slice as a magnified image.

See Also

SLICER


F_CVF

The F_CVF function computes the cutoff value V in an F distribution with Dfn and Dfd degrees of freedom such that the probability that a random variable X is greater than V is equal to a user-supplied probability P.

This routine is written in the IDL language. Its source code can be found in the file f_cvf.pro in the lib subdirectory of the IDL distribution.

Calling Sequence

Result = F_CVF(P, Dfn, Dfd)

Arguments

P

A non-negative single- or double-precision floating-point scalar, in the interval [0.0, 1.0], that specifies the probability of occurrence or success.

Dfn

A positive integer, single- or double-precision floating-point scalar that specifies the number of degrees of freedom of the F distribution numerator.

Dfd

A positive integer, single- or double-precision floating-point scalar that specifies the number of degrees of freedom of the F distribution denominator.

Example

Use the following command to compute the cutoff value in an F distribution with ten degrees of freedom in the numerator and six degrees of freedom in the denominator such that the probability that a random variable X is greater than the cutoff value is 0.01. The result should be 7.87413.

PRINT, F_CVF(0.01, 10, 6)

IDL prints:

7.87413

See Also

CHISQR_CVF, F_PDF, GAUSS_CVF, T_CVF


F_PDF

The F_PDF function computes the probability P that, in an F distribution with Dfn and Dfd degrees of freedom, a random variable X is less than or equal to a user-specified cutoff value V.

This routine is written in the IDL language. Its source code can be found in the file f_pdf.pro in the lib subdirectory of the IDL distribution.

Calling Sequence

Result = F_PDF(V, Dfn, Dfd)

Arguments

V

An integer, single-, or double-precision floating-point scalar that specifies the cutoff value.

Dfn

A positive integer, single- or double-precision floating-point scalar that specifies the number of degrees of freedom of the F distribution numerator.

Dfd

A positive integer, single- or double-precision floating-point scalar that specifies the number of degrees of freedom of the F distribution denominator.

Example

Use the following command to compute the probability that a random variable X, from the F distribution with five degrees of freedom in the numerator and 24 degrees of freedom in the denominator, is less than or equal to 3.90. The result should be 0.990059.

PRINT, F_PDF(3.90, 5, 24

IDL prints:

0.990059

See Also

BINOMIAL, CHISQR_PDF, F_CVF, GAUSS_PDF, T_PDF


FACTORIAL

The FACTORIAL function computes the factorial N! as the double-precision product, (N) ⋅ (N-1) ⋅ (N-2) ⋅ ... ⋅ 3 ⋅ 2 ⋅ 1.

This routine is written in the IDL language. Its source code can be found in the file factorial.pro in the lib subdirectory of the IDL distribution.

Calling Sequence

Result = FACTORIAL(N)

Arguments

N

A non-negative integer or long integer.

Note:  large values of N will cause floating-point overflow errors. The maximum size of N varies with machine architecture. On machines that support the IEEE standard for floating-point arithmetic, the maximum value of N is 170. See MACHAR for a discussion of machine-specific parameters affecting floating-point arithmetic.

Keywords

STIRLING

Set this keyword to use Stirling's asymptotic formula to approximate N!:

where e is the base of the natural logarithm.

Example

Compute 20!.

PRINT, FACTORIAL(20)

IDL prints:

2.4329020e+18

See Also

BINOMIAL, TOTAL


FFT

The FFT function returns a result equal to the complex, discrete Fourier transform of Array. The result of this function is a single- or double-precision complex array.

The discrete Fourier transform, F(u), of an N-element, one-dimensional function, f(x), is defined as:

And the inverse transform, (Direction > 0), is defined as:

If the keyword OVERWRITE is set, the transform is performed in-place, and the result overwrites the original contents of the array.

The result returned by FFT is a complex array that has the same dimensions as the input array. The output array is ordered in the same manner as almost all discrete Fourier transforms. Element 0 contains the zero frequency component, F0. F1 contains the smallest non-zero positive frequency, which is equal to 1/(NT) where N is the number of elements in the respective dimension and T is the sampling interval. F2 corresponds to a frequency of 2/(NT). FN/2 contains the component corresponding to the Nyquist frequency, 1/(2T), which is the highest frequency that can be sampled.

Negative frequencies are stored in reverse order from FN-1, FN-2, ..., FN/2+1, corresponding to frequencies of -1/NT, -2/NT, and -(N/2 - 1)/NT, respectively.

Calling Sequence

Result = FFT(Array [, Direction])

Arguments

Array

The array to which the Fast Fourier Transform should be applied. If Array is not of complex type, it is converted to complex type. The dimensions of the result are identical to those of Array. The size of each dimension may be any integer value and does not necessarily have to be an integer power of 2, although powers of 2 are certainly the most efficient.

Direction

Direction is a scalar indicating the direction of the transform, which is negative by convention for the forward transform, and positive for the inverse transform. If Direction is not specified, the forward transform is performed.

A normalization factor of 1/N, where N is the number of points, is applied during the forward transform.

Note: When transforming from a real vector to complex and back, it is slightly faster to set Direction to 1 in the real to complex FFT.

Note also that the value of Direction is ignored if the INVERSE keyword is set.

Keywords

DOUBLE

Set this keyword to a value other than zero to force the computation to be done in double-precision arithmetic, and to give a result of double-precision complex type. If DOUBLE is set equal to zero, computation is done in single-precision arithmetic and the result is single-precision complex. If DOUBLE is not specified, the data type of the result will match the data type of Array.

INVERSE

Set this keyword to perform an inverse transform. Setting this keyword is equivalent to setting the Direction argument to a positive value. Note, however, that setting INVERSE results in an inverse transform even if Direction is specified as negative.

OVERWRITE

If this keyword is set, and the Array parameter is a variable of complex type, the transform is done "in-place". The result overwrites the previous contents of the variable. For example, to perform a forward, in-place FFT on the variable a:

a = FFT(a, -1, /OVERWRITE)

Running Time

For a one-dimensional FFT, running time is roughly proportional to the total number of points in Array times the sum of its prime factors. Let N be the total number of elements in Array, and decompose N into its prime factors:

Running time is proportional to:

where T3 ~ 4T2. For example, the running time of a 263 point FFT is approximately 10 times longer than that of a 264 point FFT, even though there are fewer points. The sum of the prime factors of 263 is 264 (1 + 263), while the sum of the prime factors of 264 is 20 (2 + 2 + 2 + 3 + 11).

Example

Display the log of the power spectrum of a 100-element index array by entering:

PLOT, /YLOG, ABS(FFT(FINDGEN(100), -1))

As a more complex example, display the power spectrum of a 100-element vector sampled at a rate of 0.1 seconds per point. Show the 0 frequency component at the center of the plot and label the abscissa with frequency:

N =100	Define the number of points.

T = 0.1	Define the interval.

N21 = N/2 + 1	Midpoint+1 is the most negative frequency subscript.

F = INDGEN(N)	The array of subscripts.

F(N21) = N21 -N + FINDGEN(N21-2)	Insert negative frequencies in elements F(N/2 +1), ..., F(N-1).

F = F/(N*T)	Compute T0 frequency.

PLOT, /YLOG, SHIFT(F, -N21), SHIFT(ABS(FFT(Y, -1)), -N21)
Shift so that the most negative frequency is plotted first.

See Also

HILBERT


FILEPATH

The FILEPATH function returns the fully-qualified path to a file found in the IDL distribution. Operating system dependencies are taken into consideration. This routine is used by Research Systems to make the library routines portable.

This routine is written in the IDL language. Its source code can be found in the file filepath.pro in the lib subdirectory of the IDL distribution.

Calling Sequence

Result = FILEPATH(Filename)

Arguments

Filename

A string containing the name of the file to be found. The file should be specified in all lowercase characters. No device or directory information should be included.

Keywords

ROOT_DIR

A string containing the name of the directory from which the resulting path should be based. If not present, the value of !DIR is used. This keyword is ignored if TERMINAL or TMP are specified.

SUBDIRECTORY

The name of the subdirectory in which the file should be found. If this keyword is omitted, the main IDL directory is used. This variable can be either a scalar string or a string array with the name of each level of subdirectory depth represented as an element of the array.

For example, to get a path to the file filepath.pro in IDL's lib subdirectory, enter:

path = FILEPATH('filepath.pro',SUBDIR=['lib'])

TERMINAL

Set this keyword to return the filename of the user's terminal.

TMP

Set this keyword to indicate that the specified file is a scratch file. Return a path to the proper place for temporary files under the current operating system.

Example

Open the IDL distribution file people.dat, found in the images subdirectory:

OPENR, 1, FILEPATH('people.dat', SUBDIRECTORY='images')

See Also

FINDFILE


FINDFILE

The FINDFILE function returns a string array containing the names of all files matching File_Specification.

All matched filenames are returned in a string array, one file name per array element. If no files exist with names matching the File_Specification a null scalar string is returned instead of a string array.

Note: Under VMS, FINDFILE returns the full path specification for any file it finds. On all other platforms, FINDFILE returns only the local filename in the directory specified by File_Specification.

Calling Sequence

Result = FINDFILE(File_Specification)

Arguments

File_Specification

A scalar string used to find files. The string can contain any valid command-interpreter wildcard characters. If File_Specification is omitted, the names of all files in the current directory are returned.

Keywords

COUNT

A named variable into which the number of files found is placed. If no files are found, a value of 0 is returned.

Example

To print the names of all the Unix files with "dat" extensions, use the command:

PRINT, FINDFILE('*.dat')

See Also

FILEPATH


FINDGEN

The FINDGEN function returns a single-precision, floating-point array with the specified dimensions. Each element of the array is set to the value of its one-dimensional subscript.

Calling Sequence

Result = FINDGEN(D1, ..., Dn)

Arguments

Di

The dimensions of the result. The dimension parameters can be any scalar expression. Up to eight dimensions can be specified.

Example

To create F, a 6-element vector of single-precision, floating-point values where each element is set to the value of its subscript, enter:

F = FINDGEN(6)

The value of F(0) is 0.0, F(1) is 1.0, et cetera.

See Also

BINDGEN, CINDGEN, DCINDGEN, DINDGEN, INDGEN, LINDGEN, SINDGEN


FINITE

The FINITE function returns 1 (True) if its argument is finite. If the argument is infinite or not a defined number (NaN), 0 (False) is returned. (See "Special Floating-Point Values" on page 11-9 of the IDL User's Guide for more information.) The result is a byte expression of the same structure as the argument X.

Note: This function always returns 1 on machines that do not implement the IEEE floating-point standard, such as the VAX.

Calling Sequence

Result = FINITE(X)

Arguments

X

A floating-point, double-precision, or complex scalar or array expression. Strings are first converted to floating-point. This function is meaningless for byte, integer, or longword arguments.

Example

To find out if the logarithm of 5.0 is finite, enter:

PRINT, FINITE(ALOG(5.0))

IDL prints "1" because the argument is finite.

See Also

CHECK_MATH, MACHAR, and "!VALUES" on page 3-8 of the IDL User's Guide.


FIX

The FIX function returns a result equal to Expression converted to integer type.

Calling Sequence

Result = FIX(Expression [, Offset [, Dim1, ..., Dimn]])

Arguments

Expression

The expression to be converted to integer.

Offset

Offset from beginning of the Expression data area. Specifying this argument allows fields of data extracted from Expression to be treated as integer data. See the description in Chapter 4 of the IDL User's Guide for details.

Dimi

When extracting fields of data, the Di arguments specify the dimensions of the result. The dimension parameters can be any scalar expression. Up to eight dimensions can be specified. If no dimension arguments are given, the result is taken to be scalar.

When converting from a string argument, it is possible that the string does not contain a valid integer and no conversion is possible. The default action in such cases is to print a warning message and return 0. The ON_IOERROR procedure can be used to establish a statement to be jumped to in case of such errors.

Example

Convert the floating-point array [2.2, 3.0, 4.5] to integer type and store the new array in the variable I by entering:

I = FIX([2.2, 3.0, 4.5])

See Also

BYTE, COMPLEX, DCOMPLEX, DOUBLE, FLOAT, LONG, STRING


FLICK

The FLICK procedure causes the display to flicker between two output images at a given rate.

This routine is written in the IDL language. Its source code can be found in the file flick.pro in the lib subdirectory of the IDL distribution.

Calling Sequence

FLICK, A, B [, Rate]

Arguments

A

Byte image number 1, scaled from 0 to 255.

B

Byte image number 2, scaled from 0 to 255.

Rate

The flicker rate. The default is 1.0 sec/frame

See Also

CW_ANIMATE, XINTERANIMATE


FLOAT

The FLOAT function returns a result equal to Expression converted to single-precision floating-point.

Calling Sequence

Result = FLOAT(Expression [, Offset [, Dim1, ..., Dimn]])

Arguments

Expression

The expression to be converted to single-precision floating-point.

Offset

Offset from beginning of the Expression data area. Specifying this argument allows fields of data extracted from Expression to be treated as single precision floating point data. See the description in Chapter 4 of the IDL User's Guide for details.

Di

When extracting fields of data, the Di arguments specify the dimensions of the result. The dimension parameters can be any scalar expression. Up to eight dimensions can be specified. If no dimension arguments are given, the result is taken to be scalar.

When converting from a string argument, it is possible that the string does not contain a valid floating-point value and no conversion is possible. The default action in such cases is to print a warning message and return 0. The ON_IOERROR procedure can be used to establish a statement to be jumped to in case of such errors.

Example

If A contains the integer value 6, it can be converted to floating-point and stored in the variable B by entering:

B = FLOAT(A)

See Also

BYTE, COMPLEX, DCOMPLEX, DOUBLE, FIX, LONG, STRING


FLOOR

The FLOOR function returns the closest integer less than or equal to its argument. This value is returned as a longword integer with the same structure as the input argument..

Calling Sequence

Result = FLOOR(X)

Arguments

X

The value for which the FLOOR function is to be evaluated. This value can be single- or double-precision, real or complex floating-point. FLOOR returns a longword integer with the same structure as X.

Example

To print the floor function of 5.9, enter:

PRINT, FLOOR(5.9)

IDL prints:

5

See Also

CEIL, COMPLEXROUND, ROUND


FLOW3

The FLOW3 procedure draws lines representing a 3D flow/velocity field. Note that the 3D scaling system must be in place before calling FLOW3. This procedure works best with Z buffer output device.

This routine is written in the IDL language. Its source code can be found in the file flow3.pro in the lib subdirectory of the IDL distribution.

Calling Sequence

FLOW3, Vx, Vy, Vz

Arguments

Vx, Vy, Vz

3D arrays containing X, Y, and Z components of the field.

Keywords

ARROWSIZE

Size of arrowheads (default = 0.05).

BLOB

Set this keyword to draw a blob at the beginning of each flow line and suppress the arrows.

LEN

Length of each step used to follow flow lines (default = 2.0). Expressed in units of largest field vector (i.e., the length of the longest step is set to len times the grid spacing.

NSTEPS

Number of steps used to follow the flow lines (default = largest dimension of Vx / 5).

NVECS

Number of random flow lines to draw (default = 200). Only used if Sx, Sy, Sz are not present.

SX, SY, SZ

Optional vectors containing the starting coordinates of the flow lines. If omitted random starting points are chosen.

Example

Create a set of random three-dimensional arrays to represent the field:

vx = RANDOMU(seed, 5, 5, 5)

vy = RANDOMU(seed, 5, 5, 5)

vz = RANDOMU(seed, 5, 5, 5)

Set up the 3D scaling system:

SCALE3, xr=[0,4], yr=[0,4], zr = [0,4]

Plot the vector field:

FLOW3, vx, vy, vz

See Also

VEL, VELOVECT


FLTARR

The FLTARR function returns a single-precision, floating-point vector or array.

Calling Sequence

Result = FLTARR(D1, ..., Dn)

Arguments

Di

The dimensions of the result. The dimension parameters can be any scalar expression. Up to eight dimensions can be specified.

Keywords

NOZERO

Normally, FLTARR sets every element of the result to zero. Set this keyword to inhibit zeroing of the array elements and cause FLTARR to execute faster.

Example

Create F, a 3-element by 3-element floating-point array with each element set to 0.0 by entering:

F = FLTARR(3, 3)

See Also

BYTARR, COMPLEXARR, DBLARR, DCOMPLEXARR, INTARR, LONARR, MAKE_ARRAY, STRARR


FLUSH

The FLUSH procedure causes all buffered output on the specified file units to be written. IDL uses buffered output for reasons of efficiency. This buffering leads to rare occasions where a program needs to be certain that output data are not waiting in a buffer, but have actually been output.

Calling Sequence

FLUSH, Unit1, ..., Unitn

Arguments

Uniti

The file units (logical unit numbers) to flush.

See Also

CLOSE, EMPTY, EXIT


FREE_LUN

The FREE_LUN procedure deallocates previously-allocated file units. This routine is usually used with file units allocated with GET_LUN, but it will also close any other specified file unit. If the specified file units are open, they are closed prior to the deallocation.

Calling Sequence

FREE_LUN, Unit1, ..., Unitn

Arguments

Uniti

The IDL file units (logical unit numbers) to deallocate.

Example

See the example for the GET_LUN procedure.

See Also

CLOSE, GET_LUN


FSTAT

The FSTAT function returns a structure expression of type FSTAT containing status information about a specified file unit. The contents of this structure are documented in Chapter 17 of the IDL User's Guide on page 17-41.

Calling Sequence

Result = FSTAT(Unit)

Arguments

Unit

The file unit about which information is required. This parameter can be an integer or an associated variable, in which case information about the variable's associated file is returned.

Fields of the FSTAT Structure

The following descriptions are of fields in the structure returned by the FSTAT function. They are not keywords to FSTAT.

UNIT

The IDL logical unit number (LUN).

NAME

The name of the file.

OPEN

Nonzero if the file unit is open. If OPEN is zero, the remaining fields in FSTAT will not contain useful information.

ISATTY

Nonzero if the file is actually a terminal instead of a normal file. For example, if you are using an xterm window on a Unix system and you invoke FSTAT on logical unit 0 (standard input), ISATTY will be set to 1.

ISAGUI

Nonzero if the file is actually a Graphical User Interface (for example, a logical unit associated with IDLTool, IDL for Windows, or IDL for Macintosh). Thus, if you are using IDLTool and you invoke FSTAT on logical unit 0 (standard input), ISAGUI will be set to 1.

INTERACTIVE

Nonzero if either ISATTY or ISAGUI is nonzero.

READ

Nonzero if the file is open for read access.

WRITE

Nonzero if the file is open for write access.

TRANSFER_COUNT

The number of scalar IDL data items transferred in the last input/output operation on the unit. This is set by the following IDL routines: READU, WRITEU, PRINT, PRINTF, READ, and READF. TRANSFER_COUNT is useful when attempting to recover from input/output errors.

CUR_PTR

The current position of the file pointer, given in bytes from the start of the file. If the device is a terminal (ISATTY is nonzero), the value of CUR_PTR will not contain useful information.

SIZE

The current length of the file in bytes. If the device is a terminal (ISATTY is nonzero), the value of SIZE will not contain useful information.

REC_LEN

If the file is record-oriented (VMS), this field contains the record length; otherwise, it is zero.

Examples

If file unit number 1 is open, the FSTAT information on that unit can be seen by entering:

PRINT, FSTAT(1)

Specific information can be obtained by referring to single fields within the structure returned by FSTAT. The following code prints the name and length of the file open on unit 1:

A = FSTAT(1)	Put FSTAT information in variable A.

PRINT, 'File: ', A.NAME, ' is ', A.SIZE, ' bytes long.'
Print the name and size fields.

See Also

ASSOC, OPEN


FULSTR

The FULSTR restores a row-indexed sparse array to full storage mode. If the sparse array was created with the SPRSIN function using the THRESH keyword, any values in the original array that were below the specified threshold are replaced with zeros.

Calling Sequence

Result = FULSTR(A)

Arguments

A

A row-indexed sparse array created by the SPRSIN function.

Example

Suppose we have converted an array to sparse storage format with the following commands:

A = [[ 5.0, -0.2, 0.1], $

     [ 3.0, -2.0, 0.3], $

     [ 4.0, -1.0, 0.0]]

sparse = SPRSIN(A, THRESH=0.5)
Convert to sparse storage mode. All elements of the array A that have absolute values less than THRESH are set to zero.

The variable SPARSE now contains a representation of the array A in structure form. To restore the array from the sparse-format structure, type:

result = FULSTR(sparse)	Restore the array.

PRINT, result	Print the result.

IDL prints:

      5.00000      0.00000      0.00000

      3.00000     -2.00000      0.00000

      4.00000     -1.00000      0.00000

Note that the elements with an absolute value less than the specified threshold have been set to zero.

See Also

LINBCG, SPRSAB, SPRSAX, SPRSIN, READ_SPR, WRITE_SPR


FUNCT

The FUNCT procedure evaluates the sum of a Gaussian and a 2nd-order polynomial and optionally returns the value of its partial derivatives. Normally, this function is used by CURVEFIT to fit the sum of a line and a varying background to actual data.

This routine is written in the IDL language. Its source code can be found in the file funct.pro in the lib subdirectory of the IDL distribution.

Calling Sequence

FUNCT, X, A, F [, Pder]

Arguments

X

A vector of values for the independent variable.

A

A vector of coefficients for the equations:

F = A0 ⋅ EXP(-Z^2/2) + A3 + A4 x + A5x^2

Z = (x - A1)/A2

F

A named variable that will contain the value of the function at each Xi.

Pder

A named variable that will contain an array of the size (N_ELEMENTS(X),6) that contains the partial derivatives. Pder(i,j) represents the derivative at the ith point with respect to jth parameter.

See Also

CURVEFIT


FV_TEST

The FV_TEST function computes the F-statistic and the probability that two sample populations X and Y have significantly different variances. X and Y may be of different lengths. The result is a two-element vector containing the F-statistic and its significance. The significance is a value in the interval [0.0, 1.0]; a small value (0.05 or 0.01) indicates that X and Y have significantly different variances. This type of test is often referred to as the F-variance test.

The F-statistic formula for sample populations x and y with meansx andy is defined as:

where x  = (x0, x1, x2, ..., xN-1) and y = (y0, y 1, y2 ..., yM-1)

This routine is written in the IDL language. Its source code can be found in the file fv_test.pro in the lib subdirectory of the IDL distribution.

Calling Sequence

Result = FV_TEST(X, Y)

Arguments

X

An n-element integer, single- or double-precision floating-point vector.

Y

An m-element integer, single- or double-precision floating-point vector.

Example

Define two n-element sample populations.

X = [257, 208, 296, 324, 240, 246, 267, 311, 324, 323, 263, $

     305, 270, 260, 251, 275, 288, 242, 304, 267]

Y = [201,  56, 185, 221, 165, 161, 182, 239, 278, 243, 197, $

     271, 214, 216, 175, 192, 208, 150, 281, 196]

Compute the F-statistic (of X and Y) and its significance.

PRINT, FV_TEST(X, Y)

IDL prints:

2.48578    0.0540116

The result indicates that X and Y have significantly different variances.

See Also

KW_TEST, MOMENT, RS_TEST, S_TEST, TM_TEST


FX_ROOT

The FX_ROOT function computes real and complex roots of a univariate nonlinear function using an optimal Müller's method.

This routine is written in the IDL language. Its source code can be found in the file fx_root.pro in the lib subdirectory of the IDL distribution.

Calling Sequence

Result = FX_ROOT(X, Func)

Arguments

X

A 3-element real or complex initial guess vector. Real initial guesses may result in real or complex roots. Complex initial guesses will result in complex roots.

Func

A scalar string specifying the name of a user-supplied IDL function that defines the univariate nonlinear function. This function must accept the vector argument X.

For example, suppose we wish to find a root of the following function:

We write a function FUNC to express the function in the IDL language:

FUNCTION func, X

  RETURN, EXP(SIN(X)^2 + COS(X)^2 - 1) - 1

END

Keywords

DOUBLE

Set this keyword to force the computation to be done in double-precision arithmetic.

ITMAX

The maximum allowed number of iterations. The default is 100.

STOP

Use this keyword to specify the stopping criterion used to judge the accuracy of a computed root r(k). Setting STOP = 0 (the default) checks whether the absolute value of the difference between two successively-computed roots, | r(k) - r(k+1) | is less than the stopping tolerance TOL. Setting STOP = 1 checks whether the absolute value of the function FUNC at the current root, | FUNC(r(k)) |, is less than TOL.

TOL

Use this keyword to specify the stopping error tolerance. The default is 1.0 x 10-4.

Example

To find the roots of the function FUNC defined above, first define a real 3-element initial guess vector:

x = [0.0, -!pi/2, !pi]

Compute a root of the function using double-precision arithmetic.

root = FX_ROOT(X, 'FUNC', /DOUBLE)

Check the accuracy of the computed root.

PRINT, EXP(SIN(ROOT)^2 + COS(ROOT)^2 - 1) - 1

IDL prints:

0.0000000

We can also define a complex 3-element initial guess vector:

X = [COMPLEX(-!PI/3, 0), COMPLEX(0, !PI), COMPLEX(0, -!PI/6)]

root = FX_ROOT(x, 'FUNC')	Compute the root of the function.

Check the accuracy of the computed complex root.

PRINT, EXP(SIN(ROOT)^2 + COS(ROOT)^2 - 1) - 1

IDL prints:

(      0.00000,      0.00000)

See Also

BROYDEN, NEWTON, FZ_ROOTS


FZ_ROOTS

The FZ_ROOTS function is used to find the roots of an m-degree complex polynomial, using Laguerre's method. The result is an m-element complex vector.

FZ_ROOTS is based on the routine zroots described in section 9.5 of Numerical Recipes in C: The Art of Scientific Computing (Second Edition), published by Cambridge University Press, and is used by permission.

Calling Sequence

Result = FZ_ROOTS(C)

Arguments

C

A vector of length m+1 containing the coefficients of the polynomial, in ascending order (see example). The type can be real or complex.

Keywords

DOUBLE

Set this keyword to force the computation to be done in double-precision arithmetic.

EPS

The desired fractional accuracy. The default value is 2.0 x 10^-6.

NO_POLISH

Set this keyword to suppress the usual polishing of the roots by Laguerre's method.

Examples

Example 1: Real coefficients yielding real roots.

P (x) = 6x^3 - 7 x^2 - 9x - 2 (The exact roots are -1/2, -1/3, 2.0)

coeffs = [-2.0, -9.0, -7.0, 6.0]

roots = FZ_ROOTS(coeffs)

PRINT, roots

( -0.500000, 0.00000)( -0.333333, 0.00000)( 2.00000, 0.00000)

Example 2: Real coefficients yielding complex roots.

P (x) = x^4 + 3x^2 + 2

The exact roots are:

coeffs = [2.0, 0.0, 3.0, 0.0, 1.0]

roots = FZ_ROOTS(coeffs)

PRINT, roots

(0.00000, -1.41421)(0.00000, 1.41421)

(0.00000, -1.00000)(0.00000, 1.00000)

Example 3: Real and complex coefficients yielding real and complex roots.

P  (x) = x^3 + (­4 ­ i4)x^2 +s (­3 + i4)x + (18 +  i24)

(The exact roots are ­2.0, 3.0, (3.0 + i4.0))

coeffs = [COMPLEX(18,24), COMPLEX(-3,4), COMPLEX(-4,-4), 1.0]

roots = FZ_ROOTS(coeffs)

PRINT, roots

( -2.00000, 0.00000) ( 3.00000, 0.00000) ( 3.00000, 4.00000)

See Also

FX_ROOT, BROYDEN, NEWTON, POLY


GAMMA

The GAMMA function returns the gamma function of X. The domain of the function is 0 < X < 34.5.

The gamma function is defined as:

If X is double-precision, the result is double-precision, otherwise the argument is converted to floating-point and the result is floating-point.

Use the LNGAMMA function to obtain the natural logarithm of the gamma function when there is a possibility of overflow.

Calling Sequence

Result = GAMMA(X)

Arguments

X

The expression for which the gamma function will be evaluated.

Example

Plot the gamma function over the range 0.01 to 1.0 with a step size of 100 by entering:

X = FINDGEN(99)/100. + 0.01

PLOT, X, GAMMA(X)

See Also

BETA, IBETA,  IGAMMA, LNGAMMA


GAMMA_CT

The GAMMA_CT procedure applies gamma correction to a color table.

This routine is written in the IDL language. Its source code can be found in the file gamma_ct.pro in the lib subdirectory of the IDL distribution.

Calling Sequence

GAMMA_CT, Gamma

Arguments

Gamma

The value of gamma correction. A value of 1.0 indicates a linear ramp (i.e., no gamma correction). Higher values of Gamma give more contrast. Values less than 1.0 yield lower contrast.

Keywords

CURRENT

Set this keyword to apply correction from the "current" color table (i.e., the values R_CURR, G_CURR, and B_CURR in the COLORS common block). Otherwise, correction is applied from the "original" color table (i.e., the values R_ORIG, G_ORIG, and B_ORIG in the COLORS common block). The gamma corrected color table is always saved in the "current" table (R_CURR, G_CURR, B_CURR) and the new table is loaded.

INTENSITY

Set this keyword to correct the individual intensities of each color in the colortable. Otherwise, the colors are shifted according to the gamma function.

See Also

PSEUDO, STRETCH, XLOADCT


GAUSS_CVF

The GAUSS_CVF function computes the cutoff value V in a standard Gaussian (normal) distribution with a mean of 0.0 and a variance of 1.0 such that the probability that a random variable X is greater than V is equal to a user-supplied probability P.

This routine is written in the IDL language. Its source code can be found in the file gauss_cvf.pro in the lib subdirectory of the IDL distribution.

Calling Sequence

Result = GAUSS_CVF(P)

Arguments

P

A non-negative single- or double-precision floating-point scalar, in the interval [0.0, 1.0], that specifies the probability of occurrence or success.

Example

Use the following command to compute the cutoff value in a Gaussian distribution such that the probability that a random variable X is greater than the cutoff value is 0.025. The result should be 1.95997.

PRINT, GAUSS_CVF(0.025)

IDL prints:

1.95997

See Also

CHISQR_CVF, F_CVF, GAUSS_PDF, T_CVF


GAUSS_PDF

The GAUSS_PDF function computes the probability P that, in a standard Gaussian (normal) distribution with a mean of 0.0 and a variance of 1.0, a random variable X is less than or equal to a user-specified cutoff value V.

This routine is written in the IDL language. Its source code can be found in the file gauss_pdf.pro in the lib subdirectory of the IDL distribution.

Calling Sequence

Result = GAUSS_PDF(V)

Arguments

V

An integer, single-, or double-precision floating-point scalar that specifies the cutoff value.

Examples

Compute the probability that a random variable X, from the standard Gaussian (normal) distribution, is less than or equal to 2.44. The result should be 0.992656.

result = GAUSS_PDF(2.44)

Compute the probability that a random variable X, from the standard Gaussian (normal) distribution, is less than or equal to 10.0 and greater than or equal to 2.0. The result should be 0.0227501.

result = GAUSS_PDF(10.0) - GAUSS_PDF(2.0)

Compute the probability that a random variable X, from the Gaussian (Normal) distribution with a mean of 0.8 and a variance of 4.0, is less than or equal to 2.44. The result should be 0.793892.

result = GAUSS_PDF( (2.44 - 0.80)/SQRT(4.0) )

See Also

BINOMIAL, CHISQR_PDF, F_PDF, GAUSS_CVF, T_PDF


GAUSS2DFIT

The GAUSS2DFIT function fits a two-dimensional, elliptical Gaussian equation to rectilinearly gridded data.

Z = F(x, y)

where:

F(x, y) = A0 + A1*EXP(-U/2)

And the elliptical function is:

U  = (x'/a)^2 + (y'/b)^2

The parameters of the ellipse U are:

Axis lengths are 2 a and 2b, in the unrotated X and Y axes, respectively.
Center is at (h, k).
Rotation of T radians from the X axis, in the clockwise direction.

The rotated coordinate system is defined as:

x'  = (x - h) * cos(T) - (y - k) * sin(T)      (i.e., rotate by T about (h, k ))

y' = (x - h) * sin(T) + (y - k) * cos(T)

The rotation is optional, and can be forced to 0, making the major and minor axes of the ellipse parallel to the X and Y axes.

Coefficients of the computed fit are returned in argument A.

Procedure Used and Other Notes

The peak/valley is found by first smoothing Z and then finding the maximum or minimum, respectively. GAUSSFIT is then applied to the row and column running through the peak/valley to estimate the parameters of the Gaussian in X and Y. Finally, CURVEFIT is used to fit the 2D Gaussian to the data.

Be sure that the 2D array to be fit contains the entire Peak/Valley out to at least 5 to 8 half-widths, or the curve-fitter may not converge.

This computationally-intensive routine takes approximately 4 seconds for a 128 by 128-element array on a Sun SPARC LX. The time required is roughly proportional to the number of elements in  Z.

This routine is written in the IDL language. Its source code can be found in the file gauss2dfit.pro in the lib subdirectory of the IDL distribution.

Calling Sequence

Result = GAUSS2DFIT(Z, A [,X, Y])

Arguments

Z

The dependent variable. Z should be a two-dimensional array with dimensions (N(x), N(y)). Gridding in the array must be rectilinear.

A

A named variable in which the coefficients of the fit are returned. A is returned as a seven element vector the coefficients of the fitted function. The meanings of the seven elements in relation to the discussion above is:

•	A(0) = A0 = constant term

•	A(1) = A1 = scale factor

•	A(2) = a = width of Gaussian in the X direction

•	A(3) = b = width of Gaussian in the Y direction

•	A(4) = h = center X location

•	A(5) = k = center Y location.

•	A(6) = T = Theta, the rotation of the ellipse from the X axis in radians, counter-clockwise.

X

An optional vector with Nx elements that contains the X values of Z (i.e., X(i) is the X value for Z(i,j). If this argument is omitted, a regular grid in X is assumed, and the X location of Z(i,j) = i.

Y

An optional vector with Ny elements that contains the Y values of Z (i.e., Y(j) is the Y value for Z(i,j). If this argument is omitted, a regular grid in Y is assumed, and the Y location of Z(i,j) = j.

Keywords

NEGATIVE

Set this keyword to indicate that the Gaussian to be fitted is a valley (such as an absorption line). By default, a peak is fit.

TILT

Set this keyword to allow the orientation of the major and minor axes of the ellipse to be unrestricted. The default is that the axes of the ellipse must be parallel to the X and Y axes. Therefore, in the default case, A(6) is always returned as 0.

Example

This example creates a 2D gaussian, adds random noise and then applies GAUSS2DFIT.

nx = 128 & ny = 100	Define array dimensions.

A = [ 5., 10., nx/6., ny/10., nx/2., .6*ny]
Define input function parameters.

X = FINDGEN(nx) # REPLICATE(1.0, ny)

Y = REPLICATE(1.0, nx) # FINDGEN(ny)
Create X and Y arrays.

U = ((X-A(4))/A(2))^2 + ((Y-A(5))/A(3))^2
Create an ellipse.

Z = A(0) + A(1) * EXP(-U/2)	Create gaussian Z.

Z = Z + RANDOMN(seed, nx, ny)	Add random noise, SD = 1.

yfit = GAUSS2DFIT(Z, B)	Fit the function, no rotation.

PRINT, 'Should be: ', STRING(A, FORMAT='(6f10.4)')

PRINT, 'Is: ', STRING(B(0:5), FORMAT='(6f10.4)')
Report results.


GAUSSFIT

The GAUSSFIT function computes a non-linear least-squares fit to a function f (x) with from three to six unknown parameters. f (x) is a linear combination of a Gaussian and a quadratic; the number of terms is controlled by the keyword parameter NTERMS.

This routine is written in the IDL language. Its source code can be found in the file gaussfit.pro in the lib subdirectory of the IDL distribution.

Calling Sequence

Result = GAUSSFIT(X, Y [, A])

Arguments

X

An n-element vector of independent variables.

Y

A vector of dependent variables, the same length as X.

A

A named variable that will contain the coefficients A of the fit.

Keywords

NTERMS

Set this keyword to an integer value between three and six to specify the function to be used for the fit. The values correspond to the functions shown below. In all cases:

z = (x ­ A1) / A2

•	NTERMS=6

f (x) = A0 ⋅ EXP(-z^2/2) + A3 + A4x + A5x^2

NTERMS=6 is the default setting. Here, A0 is the height of the Gaussian, A1 is the center of the Gaussian, A2 is the width of the Gaussian, A3 is the constant term, A4 is the linear term, and A5 is the quadratic term.

•	NTERMS=5

f (x) = A0 ⋅ EXP(-z^2/2) + A3 + A4x

•	NTERMS=4

f (x) = A0 ⋅ EXP(-z^2/2) + A3

•	NTERMS=3

f (x) = A0 ⋅ EXP(-z^2/2)

Example

X = FINDGEN(13)/5 - 1.2	Define the independent variables.

Y = [0.0, 0.1, 0.2, 0.5, 0.8, 0.9, $

     0.99, 0.9, 0.8, 0.5, 0.2, 0.1, 0.0]
Define the dependent variables.

yfit = GAUSSFIT(X, Y, A)	Fit the data to the default function, storing coefficients in A.

PRINT, A	Print the coefficients.

IDL prints:

2.2562526     -1.2658522e-07  0.70335141  -1.2561733

2.0321091e-07  0.51353000

We can compare original and fitted data by plotting one on top of the other:

LOADCT, 30	Load an appropriate color table.

PLOT, X, Y	Plot the original data.

OPLOT, X, yfit, COLOR = 100	Overplot the fitted data in a different color.

See Also

CURVEFIT, POLY_FIT, POLYFITW, REGRESS, SFIT, SVDFIT


GAUSSINT

The GAUSSINT function evaluates the integral of the Gaussian probability function and returns the result.

The Gaussian integral is defined as:

If X is double-precision, the result is double-precision, otherwise the argument is converted to floating-point and the result is floating-point. The result has the same structure as the input argument, X.

Calling Sequence

Result = GAUSSINT(X)

Arguments

X

The expression for which the Gaussian integral is to be evaluated.

Example

Plot the Gaussian probability function over the range -5 to 5 with a step size of 0.1by entering:

X = FINDGEN(101)/10. - 5.

PLOT, X, GAUSSINT(X)

See Also

GAUSS_CVF, GAUSS_PDF


GET_KBRD

The GET_KBRD function returns the next character available from the standard input (IDL file unit 0) as a one-character string.

Calling Sequence

Result = GET_KBRD(Wait)

Arguments

Wait

If Wait is zero, GET_KBRD returns the null string if there are no characters in the terminal type-ahead buffer. If it is nonzero, the function waits for a character to be typed before returning.

Examples

To wait for keyboard input and store one character in the variable R, enter:

R = GET_KBRD(1)

Press any key to return to the IDL prompt. To see the character that was typed, enter:

PRINT, R

The following code fragment reads one character at a time and echoes that character's numeric code. It quits when a "q" is entered:

REPEAT BEGIN

  A = GET_KBRD(1)

  PRINT, BYTE(A)

ENDREP UNTIL A EQ 'q'

See Also

READ


GET_LUN

The GET_LUN procedure allocates a file unit from a pool of free units. Instead of writing routines to assume the use of certain file units, IDL functions and procedures should use GET_LUN to reserve unit numbers in order to avoid conflicts with other routines. Use FREE_LUN to free the file units when finished.

Calling Sequence

GET_LUN, Unit

Arguments

Unit

The named variable into which GET_LUN should place the file unit number. Unit  is converted into a longword integer in the process. The file unit number obtained is in the range 100 to 128.

Example

Instead of explicitly specifying a file unit number that may already be used, use GET_LUN to obtain a free one and store the result in the variable U by entering:

GET_LUN, U

Now U can be used in opening a file, for Example

OPENR, U, 'file.dat'

Once the data from "file.dat" has been read, the file can be closed and the file unit can be freed with the command:

FREE_LUN, U

Note also that OPENR has a GET_LUN keyword that allows you to simultaneously obtain a free file unit and open a file. The following command performs the same tasks as the first two commands above:

OPENR, U, 'file.dat', /GET_LUN

See Also

FREE_LUN, OPEN


GET_SYMBOL
GET_SYMBOL (VMS Only)

The GET_SYMBOL function returns the value of a VMS DCL (Digital Command Language) interpreter symbol as a scalar string. If the symbol is undefined, the null string is returned.

Calling Sequence

Result = GET_SYMBOL(Name)

Arguments

Name

A scalar string containing the name of the symbol to be translated.

Keywords

TYPE

The table from which Name is translated. Set TYPE to 1 to specify the local symbol table. A value of 2 specifies the global symbol table. The default is to search the local table.

See Also

GETENV


GETENV

The GETENV function returns the equivalence string for Name from the environment of the IDL process. If Name does not exist in the environment, a null string is returned.

Calling Sequence

Result = GETENV(Name)

Arguments

Name

The scalar string for which an equivalence string from the environment is desired.

Environment Variables Under VMS

VMS does not directly support the concept of environment variables. Instead, it is emulated (by using the standard C getenv() function) as described below, enabling you to use GETENV portably between Unix and VMS:

•	If Name is one of HOME, TERM, PATH, or USER, an appropriate response is generated. This mimics the most common Unix environment variables.

•	An attempt is made to translate Name as a logical name. All four logical name tables are searched in the standard order.

•	An attempt is made to translate Name as a command-language interpreter symbol.

Example

To print the name of the current Unix shell, enter the command:

PRINT, 'The current shell is: ', GETENV('SHELL')

See Also

GET_SYMBOL (VMS Only), SETENV (Unix and Windows Only)


GETHELP

The GETHELP function returns information on variables defined at the program level from which GETHELP is called. The function builds a string array that contains information that follows the format used by the IDL HELP command.

When called without an argument, GETHELP returns a string array that normally contains variable data that is in the same format as used by the IDL HELP procedure. The variables in this list are those defined for the routine (or program level) that called GETHELP. If there are no variables defined, or the specified variable does not exist, GETHELP returns a null string. Other information can be obtained by setting keywords.

This routine is written in the IDL language. Its source code can be found in the file gethelp.pro in the lib subdirectory of the IDL distribution.

Calling Sequence

Result = GETHELP([Variable])

Arguments

Variable

A scalar string that contains the name of the variable from which to get information. If this argument is omitted, GETHELP returns an array of strings where each element contains information on a separate variable, one element for each defined variable.

Keywords

FULLSTRING

Normally a string that is longer than 45 chars is truncated and followed by "..." just like the HELP command. Setting this keyword will cause the full string to be returned.

FUNCTIONS

Setting this keyword will cause the function to return all current IDL compiled functions.

ONELINE

If a variable name is greater than 15 characters it is usually returned as 2 two elements of the output array (Variable name in 1st element, variable info in the 2nd element). Setting this keyword will put all the information in one string, separating the name and data with a space.

PROCEDURES

Setting this keyword will cause the function to return all current IDL compiled procedures.

SYS_PROCS

Setting this keyword will cause the function to return the names of all IDL system (built-in) procedures.

SYS_FUNCS

Setting this keyword will cause the function to return the names of all IDL system (built-in) functions.

Example

To obtain a listing in a help "format" of the variables contained in the current routine you would make the following call:

HelpData = GetHelp()

The variable HelpData would be a string array containing the requested information.

See Also

HELP


GRID3

The GRID3 function fits a smooth function to a set of 3D scattered nodes (xi, yi, zi) with associated data values (fi). The function can be sampled over a set of user-specified points, or over an arbitrary 3D grid which can then be viewed using the SLICER procedure.

GRID3 uses the method described in Renka, R. J., "Multivariate Interpolation of Large Sets of Scattered Data," ACM Transactions on Mathematical Software, Vol. 14, No. 2, June 1988, Pages 139-148, which has been referred to as the Modified Shepard's Method. The function described by this method has the advantages of being equal to the values of fi, at each (xi, yi, zi), and being smooth (having continuous first partial derivatives).

If no optional or keyword parameters are supplied, GRID3 produces a regularly-sampled volume with dimensions of (25, 25, 25), made up of single-precision, floating-point values, enclosing the original data points.

Calling Sequence

Result = GRID3(X, Y, Z, F, Gx, Gy, Gz)

Arguments

X, Y, Z and F

Arrays containing the locations of the data points, and the value of the variable to be interpolated at that point. X, Y, Z, and F must have the same number of elements (with a minimum of 10 elements per array) and are converted to floating-point if necessary.

Note:  For the greatest possible accuracy, the arrays X, Y, and Z should be scaled to fit in the range [0,1].

Gx, Gy, and Gz

Optional arrays containing the locations within the volume to be sampled (if the GRID keyword is not set), or the locations along each axis of the sampling grid (if the GRID keyword is set). If these parameters are supplied, the keywords DELTA, NGRID, and START are ignored.

If the keyword GRID is not set, the result has the same number of elements as Gx, Gy, and Gz. The ith element of the result contains the value of the interpolate at (Gxi,  Gyi, Gzi). The result has the same dimensions as Gx.

If the GRID keyword is set, the result of GRID3 is a three-dimensional, single-precision, floating-point array with dimensions of (Nx, Ny, Nz), where Nx, Ny, and Nz are the number of elements in Gx, Gy, and Gz, respectively.

Keywords

DELTA

Set this keyword to a three-element vector or a scalar that specifies the grid spacing in the X, Y, and Z dimensions. The default spacing produces NGRID samples within the range of each axis.

DTOL

The tolerance for detecting an ill-conditioned system of equations. The default value is 0.01, which is appropriate for small ranges of X, Y , and Z. For large ranges of X, Y, or Z, it may be necessary to decrease the value of DTOL. If you receive the error message "GRID3: Ill-conditioned matrix or all nodes co-planar," try decreasing the value of DTOL.

GRID

This keyword specifies the interpretation of Gx, Gy, and Gz. The default value for GRID is zero if Gx, Gy, and  Gz are supplied, otherwise a regularly-gridded volume is produced.

NGRID

The number of samples along each axis. NGRID can be set to a scalar, in which case each axis has the same number of samples, or to a three-element array containing the number of samples for each axis. The default value for NGRID is 25.

START

A three-element array that specifies the starting value for each grid. The default value for START is the minimum value in the respective X, Y, and Z array.

Examples

Produce a set random points within the (0,1) unit cube and simulate a function:

N = 300	Number of irregular samples.

X = RANDOMU(SEED, N)	Generate random values between 0 and 1.

Y = RANDOMU(SEED, N)

Z = RANDOMU(SEED, N)

F = (X-.5)^2 + (Y-.5)^2 + Z	The function to simulate.

Return a cube with 25 equal-interval samples along each axis:

Result = GRID3(X, Y, Z, F)

Return a cube with 11 elements along each dimension, which samples each axis at (0, 0.1, ..., 1.0):

Result = GRID3(X, Y, Z, F, START=[0., 0., 0], $

               DELTA=0.1, NGRID=10)

The same result is produced by the statements:

S = FINDGEN(11) / 10.	Create sample values

Result = GRID3(X, Y, Z, F, S, S, S, /GRID)

See Also

SLICER


GS_ITER

The GS_ITER function solves an n by n linear system of equations using Gauss-Seidel iteration with over- and under-relaxation to enhance convergence.

Note that the equations must be entered in diagonally dominant form to guarantee convergence. A system is diagonally dominant if the diagonal element in a given row is greater than the sum of the absolute values of the non-diagonal elements in that row.

This routine is written in the IDL language. Its source code can be found in the file gs_iter.pro in the lib subdirectory of the IDL distribution.

Calling Sequence

Result = GS_ITER(A, B)

Arguments

A

An n by n integer, single-, or double-precision floating-point array. On output, A is divided by its diagonal elements. Integer input values are converted to single-precision floating-point values.

B

A vector containing the right-hand side of the linear system Ax=b. On output, B is divided by the diagonal elements of A.

Keywords

CHECK

Set this keyword to check the array A for diagonal dominance. If A is not in diagonally dominant form, GS_ITER reports the fact but continues processing on the chance that the algorithm may converge.

LAMBDA

A scalar value in the range: [0.0, 2.0]. This value determines the amount of relaxation. Relaxation is a weighting technique used to enhance convergence.

•	If LAMBDA = 1.0, no weighting is used. This is the default.

•	If 0.0 ≤ LAMBDA < 1.0, convergence improves in oscillatory and non-convergent systems.

•	If 1.0 < LAMBDA ≤ 2.0, convergence improves in systems already known to converge.

MAX_ITER

The maximum allowed number of iterations. The default value is 30.

X_0

An n-element vector that provides the algorithm's starting point. The default is [1.0, 1.0, ... , 1.0].

TOL

The relative error tolerance between current and past iterates calculated as:  ( (current-past)/current ). The default is 1.0 x 10-4.

Example

Define an array A:

A = [[ 1.0,  7.0, -4.0], $

     [ 4.0, -4.0,  9.0], $

     [12.0, -1.0,  3.0]]

B = [12.0, 2.0, -9.0]	Define the right-hand side vector B.

RESULT = GS_ITER(A, B, /CHECK)	Compute the solution to the system.

IDL prints:

Input matrix is not in Diagonally Dominant form.

Algorithm may not converge.

% GS_ITER: Algorithm failed to converge within given parameters.

Since the A represents a system of linear equations, we can reorder it into diagonally dominant form by rearranging the rows:

A = [[12.0, -1.0,  3.0], $

     [ 1.0,  7.0, -4.0], $

     [ 4.0, -4.0,  9.0]]

Make corresponding changes in the ordering of B.

B = [-9.0, 12.0, 2.0]

RESULT = GS_ITER(A, B, /CHECK)	Compute the solution to the system.

IDL prints:

-0.999982      2.99988      1.99994

See Also

CRAMER, LU_COMPLEX, CHOLSOL, LUSOL, SVSOL, TRISOL


H_EQ_CT

The H_EQ_CT function histogram-equalizes the color tables for an image or a region of the display. A pixel-distribution histogram is obtained, the cumulative integral is taken and scaled, and the result is applied to the current color table.

This routine is written in the IDL language. Its source code can be found in the file h_eq_ct.pro in the lib subdirectory of the IDL distribution.

Calling Sequence

H_EQ_CT [, Image]

Arguments

Image

A two-dimensional byte array representing the image whose histogram is to be used in determining the new color tables. If this value is omitted, the user is prompted to mark the diagonal corners of a region of the display. If Image is specified, it is assumed that the image is loaded into the current IDL window.  Image must be scaled the same way as the image loaded to the display.

See Also

H_EQ_INT


H_EQ_INT

The H_EQ_INT function interactively histogram-equalizes the color tables of an image or a region of the display. By moving the cursor across the screen, the amount of histogram-equalization can be varied.

Either the image parameter or a region of the display marked by the user is used to obtain a pixel-distribution histogram. The cumulative integral is taken and scaled and the result is applied to the current color tables.

This routine is written in the IDL language. Its source code can be found in the file h_eq_int.pro in the lib subdirectory of the IDL distribution.

Using the H_EQ_INT Interface

A window is created and the histogram equalization function is plotted. A linear ramp is overplotted. Move the cursor from left to right to vary the amount of histogram equalization applied to the color tables from 0 to 100%. Press the right mouse button to exit.

Calling Sequence

H_EQ_INT [, Image]

Arguments

Image

A two-dimensional byte array representing the image whose histogram is to be used in determining the new color tables. If this value is omitted, the user is prompted to mark the diagonal corners of a region of the display. If Image is specified, it is assumed that the image is loaded into the current IDL window.  Image must be scaled the same way as the image loaded to the display.

See Also

H_EQ_CT


HANDLE_CREATE

The HANDLE_CREATE function creates a new handle. A "handle" is a dynamically-allocated variable that is identified by a unique integer value known as a "handle ID". Handles can have a value, of any IDL data type and organization, associated with them.This function returns the handle ID of the newly-created handle.

Because handles are dynamic, they can be used to create complex data structures. They are also global in scope, but do not suffer from the limitations of COMMON blocks. That is, handles are available to all program units at all times. (Remember, however, that IDL variables containing handle IDs are not global in scope and must be declared in a COMMON block if you want to share them between program units.)

Handle Terminology

The following terms are used to describe handles in the documentation for this function and other handle-related routines:

•	Handle ID: The unique integer identifier associated with a handle.

•	Handle value: Data of any IDL type and organization associated with a handle.

•	Top-level handle: A handle at the top of a handle hierarchy. A top-level handle can have children, but does not have a parent.

•	Parents, children, and siblings: These terms describe the relationship between handles in a handle hierarchy. When a new handle is created, it can be the start of a new handle hierarchy (a top-level handle) or it can belong to the level of a widget hierarchy below an existing handle. A handle created in this way is said to be a child of the specified parent. Parents can have any number of children. All handles that share the same parent are said to be siblings.

Calling Sequence

Result = HANDLE_CREATE([ID])

Arguments

ID

If this argument is present, it specifies the handle ID relative to which the new handle is created. Normally, the new handle becomes the last child of the parent handle specified by ID. However, this behavior can be changed by setting the FIRST_CHILD or SIBLING keywords.

Omit this argument to create a new top-level handle without a parent.

Keywords

FIRST_CHILD

Set this keyword to create the new handle as the first child of the handle specified by ID. Any existing children of ID become later siblings of the new first child (i.e., the existing first child becomes the second child, the second child becomes the third child, etc.).

NO_COPY

Usually, when the VALUE keyword is used, the source variable memory is copied to the handle value. If the NO_COPY keyword is set, the value data is taken away  from the source variable and attached directly to the destination. This feature can be used to move data very efficiently. However, it has the side effect of causing the source variable to become undefined.

SIBLING

Set this keyword to create the new handle as the sibling handle immediately following ID. Any other siblings currently following ID become later siblings of the new handle. Note that you cannot create a handle that is a sibling of a top-level handle.

VALUE

The value to be assigned to the handle.

Every handle can contain a user-specified value of any data type and organization. This value is not used by the handle in any way, but exists entirely for the convenience of the IDL programmer. Use this keyword to set the handle value when the handle is first created.

If the VALUE keyword is not specified, the handle's initial value is undefined.

Handle values can be retrieved using the HANDLE_VALUE procedure.

Examples

The following commands create a top-level handle with 3 child handles. Each handle is assigned a different string value:

top = HANDLE_CREATE()	Create top-level handle without an initial handle value.

first = HANDLE_CREATE(top, VALUE='First child')
Create first child of the top-level handle.

second = HANDLE_CREATE(top, VALUE='Second child')
Create second child of the top-level handle.

third = HANDLE_CREATE(first, VALUE='Another child', /SIBLING)
Create a new sibling between first and second. This handle is also a child of the top-level handle.

See Also

HANDLE_FREE, HANDLE_INFO, HANDLE_MOVE, HANDLE_VALUE


HANDLE_FREE

The HANDLE_FREE procedure frees an existing handle, along with any dynamic memory currently being used by its value. Any child handles associated with ID are also freed.

Calling Sequence

HANDLE_FREE, ID

Arguments

ID

The ID of the handle to be freed. Once the handle is freed, further use of it is invalid and causes an error to be issued.

Examples

To free all memory associated with the top-level handle top, and all its children, use the command:

HANDLE_FREE, top

See Also

HANDLE_CREATE, HANDLE_INFO, HANDLE_MOVE, HANDLE_VALUE


HANDLE_INFO

The HANDLE_INFO function returns information about handle validity and connectivity. By default, it returns True if the specified handle ID is valid. Keywords can be set to return other types of information.

Calling Sequence

Result = HANDLE_INFO(ID)

Arguments

ID

The ID of the handle for which information is desired. This argument can be scalar or array an array of IDs. The result of HANDLE_INFO has the same structure as ID, and each element gives the desired information for the corresponding element of ID.

Keywords

FIRST_CHILD

Set this keyword to return the handle ID of the first child of the specified handle. If the handle has no children, 0 is returned.

NUM_CHILDREN

Set this keyword to return the number of children related to ID.

PARENT

Set this keyword to return the handle ID of the parent of the specified handle. If the specified handle is a top-level handle (i.e., it has no parent), 0 is returned.

SIBLING

Set this keyword to return the handle ID of the sibling handle following ID. If ID has no later siblings, or if  ID is a top-level handle, 0 is returned.

VALID_ID

Set this keyword to return 1 if ID represents a currently valid handle. Otherwise, zero is returned. This is the default action for HANDLE_INFO if no other keywords are specified.

Examples

The following commands demonstrate a number of different uses of HANDLE_INFO:

IF HANDLE_INFO(handle1) THEN PRINT, 'Valid handle.'
Print a message if handle1 is a valid handle ID.

handle = HANDLE_INFO(top, /FIRST_CHILD)
Retrieve the handle ID of the first child of top.

next= HANDLE_INFO(handle1, /SIBLING)
Retrieve the handle ID of the next sibling of handle1.

See Also

HANDLE_CREATE, HANDLE_FREE, HANDLE_MOVE, HANDLE_VALUE


HANDLE_MOVE

The HANDLE_MOVE procedure moves a handle (specified by Move_ID) to a new location. This new position is specified relative to Static_ID.

Calling Sequence

HANDLE_MOVE, Static_ID, Move_ID

Arguments

Static_ID

The handle ID relative to which the handle specified by Move_ID is moved. By default, Move_ID becomes the last child of Static_ID. This behavior can be changed by specifying one of the keywords described below.

If Static_ID is set to 0, Move_ID becomes a top level handle without any parent. Static_ID cannot be a child of Move_ID.

Move_ID

The ID of the handle to be moved.

Keywords

FIRST_CHILD

Set this keyword to make Move_ID the first child of Static_ID. Any existing children of Static_ID become later siblings of the new first child (i.e., the existing first child becomes the second child, the second child becomes the third child, etc.).

SIBLING

Set this keyword to make Move_ID the sibling handle immediately following Static_ID. Any siblings currently following Static_ID become later siblings of the new handle. Note that you cannot move a handle such that is becomes a sibling of a top-level handle.

Example

top = HANDLE_CREATE()	Create top-level handle.

child1 = HANDLE_CREATE(top)	Create first child of top.

child2 = HANDLE_CREATE(top)	Create second child of top.

HANDLE_MOVE, top, child1	Move the first child to be the last child of top.

See Also

HANDLE_CREATE, HANDLE_FREE, HANDLE_INFO, HANDLE_VALUE


HANDLE_VALUE

The HANDLE_VALUE procedure returns or sets the value of an existing handle.

Calling Sequence

HANDLE_VALUE, ID, Value

Arguments

ID

A valid handle ID.

Value

When using HANDLE_VALUE to return an existing handle value (the default), Value is a named variable in which the value is returned.

When using HANDLE_VALUE to set a handle value, Value is the new value. Note that handle values can have any IDL data type and organization.

Keywords

NO_COPY

By default, HANDLE_VALUE works by making a second copy of the source data. Although this technique is fine for small data, it can have a significant memory cost when the data being copied is large.

If the NO_COPY keyword is set, HANDLE_VALUE works differently. Rather than copy the source data, it takes the data away from the source and attaches it directly to the destination. This feature can be used to move data very efficiently. However, it has the side effect of causing the source variable to become undefined. On a retrieve operation, the handle value becomes undefined. On a set operation, the variable passed as Value becomes undefined.

SET

Set this keyword to assign Value as the new handle value. The default is to retrieve the current handle value.

Examples

The following commands demonstrate the two different uses of HANDLE_VALUE:

HANDLE_VALUE, handle1, current	Retrieve the value of handle1 into the variable current.

HANDLE_VALUE,handle1,[2,3],/SET	Set the value of handle1 to a 2-element integer vector.

See Also

HANDLE_CREATE, HANDLE_FREE, HANDLE_INFO, HANDLE_MOVE


HANNING

The HANNING function is used to create a "window" for Fourier Transform filtering. It can be used to create both Hanning and Hamming windows.

This routine is written in the IDL language. Its source code can be found in the file hanning.pro in the lib subdirectory of the IDL distribution.

Calling Sequence

Result = HANNING(N1 [, N2])

Arguments

N1

The number of columns in the resulting array.

N2

The number of rows in the resulting array.

Keywords

ALPHA

Set this keyword equal to the width parameter of a generalized Hamming window. ALPHA must be in the range of 0.5 to 1.0. If ALPHA = 0.5 (the default) the function is called a "Hanning" window. If ALPHA = 0.54, the result is called a "Hamming" window.

See Also

FFT


HDF_CLOSE

The HDF_CLOSE procedure closes the Hierarchical Data Format file associated with the given file handle.

Calling Sequence

HDF_CLOSE, Filehandle

Arguments

Filehandle

The HDF file handle returned from a previous call to HDF_OPEN.

See Also

HDF_OPEN


HDF_DELDD

The HDF_DELDD procedure deletes a tag or reference from the list of data descriptors in a Hierarchical Data Format file.

Calling Sequence

HDF_DELDD, FileHandle, Tag, Ref

Arguments

Filehandle

The HDF file handle returned from a previous call to HDF_OPEN.

Tag

The data descriptor tag to delete.

Ref

The data descriptor reference number to delete.


HDF_DF24_ADDIMAGE

The HDF_DF24_ADDIMAGE procedure writes a 24-bit raster image to a Hierarchical Data Format file. The interlace is set automatically based upon the dimensions of the image being written: ARR(3, Width, Height) for pixel interlace, ARR(Width, 3, Height) for scan-line interlace, and ARR(Width, Height, 3) for scan-plane interlace.

Note: HDF_DF24_ADDIMAGE chooses an interlace based upon the location of the `3'-sized dimension. For 3x3xN, 3xNx3 and Nx3x3 images, if the first `3' encountered is supposed to be a width or height, HDF_DF24_ADDIMAGE will choose the `wrong' interlace. However, as long as one reads in the image using the same interlace, the image will be read correctly anyway. Avoid writing 24-bit-deep raster images with a width or height of 3 pixels.

Note also that JPEG compression has not been implemented.

Calling Sequence

HDF_DF24_ADDIMAGE, Filename, Image

Arguments

Filename

A scalar string containing the name of the file to be written.

Image

A 3-dimensional array of values representing the 3 planes (Red, Green, and Blue) of the 24-bit image. One of the dimensions must be 3 (e.g., a 3 x 100 x 100 array).

Keywords

IMCOMP

Set this keyword to store the image using imcomp data reduction.

RLE

Set this keyword to store the image using run length encoding.


HDF_DF24_GETIMAGE

The HDF_DF24_GETIMAGE procedure reads a 24-bit raster image from a Hierarchical Data Format file. The default is to use the same format for reading as that used in writing the image. Note: it is slower to read an image in a different interlace than the one the image was originally written with.

Calling Sequence

HDF_DF24_GETIMAGE, Filename, Image

Arguments

Filename

A scalar string containing the name of the file to be read.

Image

A named variable in which the image data is returned.

Keywords

LINE

Set this keyword to force the image to be read with scan-line interlace.

PIXEL

Set this keyword to force the image to be read with pixel interlace.

PLANE

Set this keyword to force the image to be read with scan-plane interlace.


HDF_DF24_GETINFO

The HDF_DF24_GETINFO procedure retrieves information about the current 24-bit HDF image.

Calling Sequence

HDF_DF24_GETINFO, Filename, Width, Height, Interlace

Arguments

Filename

A string containing the name of the file to be read.

Width

A named variable in which the width of the image is returned.

Height

A named variable in which the height of the image is returned.

Interlace

A named variable in which the interface method is returned. The returned value is 0 for pixel interlacing, 1 for scan-line interlacing, and 2 for scan-plane interlacing.

Example

h = HDF_OPEN('myhdf.hdf')	Open the file myhdf.hdf.

HDF_DF24_GETINFO, 'myhdf.hdf', width, height, interlace
Return information about the 24-bit image.

HELP, width, height, interlace	Print information about the returned variables. If the image were 536 pixels wide, 412 pixels high, and scan-line interlaced, IDL would print:
WIDTH LONG = 536
HEIGHT LONG = 412
INTERLACE LONG = 1

HDF_CLOSE('myhdf.hdf')	Close the HDF file.

See Also

HDF_DF24_GETIMAGE, HDF_DF24_NIMAGES, HDF_DF24_READREF, HDF_DF24_RESTART


HDF_DF24_LASTREF

The HDF_DF24_LASTREF function returns the reference number of the most recently read or written 24-bit image in an HDF file.

Calling Sequence

Result = HDF_DF24_LASTREF()

Example

h=HDF_OPEN('myhdf.hdf')	Open an HDF file.

PRINT, HDF_DF24_LASTREF()	IDL prints 0, meaning that the call was successful, but no reference number was available.

a = BINDGEN(3,100,100)	Create a 3D array, representing a 24-bit image.

HDF_DF24_ADDIMAGE, 'myhdf.hdf', a	Write the 24-bit image to the file.

PRINT, HDF_DF24_LASTREF()	IDL prints a reference number for the last operation (for example, 2). Note the reference number is not simply a 1-based "image number"—the reference number could easily be "2" or "3", etc.

HDF_DF24_ADDIMAGE, 'myhdf.hdf', a	Write another image to the file.

PRINT, HDF_DF24_LASTREF()	Print the last reference number.

PRINT, HDF_DF24_NIMAGES('myhdf.hdf')
IDL prints "2" because we've written two images to the file.

HDF_CLOSE, h	Close the file.

See Also

HDF_DF24_ADDIMAGE, HDF_DF24_GETIMAGE, HDF_DF24_GETINFO, HDF_DF24_NIMAGES, HDF_DF24_READREF, HDF_DF24_RESTART, HDF_DFR8_LASTREF


HDF_DF24_NIMAGES

The HDF_DF24_NIMAGES function returns the number of 24-bit images in an HDF file. A -1 is returned if the specified file is invalid or damaged.

Calling Sequence

Result = HDF_DF24_NIMAGES(Filename)

Arguments

Filename

A string containing the name of the file to be searched.

Example

h = HDF_OPEN('myhdf.hdf')	Open an HDF file.

number = HDF_DF24_NIMAGES('myhdf.hdf')
Return the number of 24-bit images in the file.

HELP, number	Print information about the returned value. If there were five images in the file, IDL would print:
NUMBER LONG = 5

HDF_CLOSE, h	Close the HDF File.

See Also

HDF_DF24_GETIMAGE, HDF_DF24_GETINFO, HDF_DF24_READREF, HDF_DF24_RESTART, HDF_DFR8_NIMAGES


HDF_DF24_READREF

The HDF_DF24_READREF procedure sets the reference number of the image in a Hierarchical Data Format file to be read by the next call to HDF_DF24_GETIMAGE.

Calling Sequence

HDF_DF24_READREF, Filename, Refno

Arguments

Filename

A scalar string containing the name of the file to be read.

Refno

The reference number for a 24-bit raster image.


HDF_DF24_RESTART

The HDF_DF24_RESTART procedure causes the next call to HDF_DF24_GETIMAGE to read the first 24-bit image in the Hierarchical Data Format file.

Calling Sequence

HDF_DF24_RESTART


HDF_DFAN_ADDFDS

The HDF_DFAN_ADDFDS procedure adds a file description to a Hierarchical Data Format file.

Calling Sequence

HDF_DFAN_ADDFDS, Filename, Description

Arguments

Filename

A scalar string containing the name of the file to be written.

Description

A string or a array of bytes containing the information to be written.


HDF_DFAN_ADDFID

The HDF_DFAN_ADDFID procedure adds a file annotation to a Hierarchical Data Format file. A file can have multiple annotations added.

Calling Sequence

HDF_DFAN_ADDFID, Filename, Label

Arguments

Filename

A scalar string containing the name of the file to be written.

Label

A string containing the annotation string.


HDF_DFAN_GETDESC

The HDF_DFAN_GETDESC procedure reads the description for the given tag and reference number in a Hierarchical Data Format file.

Calling Sequence

HDF_DFAN_GETDESC, Filename, Tag, Ref, Description

Arguments

Filename

A scalar string containing the name of the file to be read.

Tag

The tag number.

Ref

The reference number.

Description

A named variable in which the description is returned as a vector of bytes.


HDF_DFAN_GETFDS

The HDF_DFAN_GETFDS procedure reads the next available file description from an HDF file.

Calling Sequence

HDF_DFAN_GETFDS, Filename, Description

Arguments

Filename

A string containing the name of the file to be read.

Description

A named variable in which the description is returned. By default, this description is returned as a null-terminated vector of bytes but this behavior can be changed with the NONULL and STRING keywords.

Keywords

NONULL

Set this keyword to prevent the NULL byte from being appended Description .

STRING

Set this keyword to return Description as a string instead of a vector of bytes. This keyword can be used in conjunction with NONULL.

Example

fid = HDF_OPEN('test.hdf', /ALL)	Create an HDF file.

fds = 'TEST FILE DESCRIPTION'	Create a string to be used as the file description.

HDF_DFAN_ADDFDS, 'test.hdf', fds	Write the description.

HDF_DFAN_GETFDS, 'test.hdf', out	Read the description back.

HELP, fds, out, STRING(out_fd)	Print information about the variables. IDL prints the following 3 lines:

FDS STRING = 'TEST FILE DESCRIPTION'
The original description string.

OUT BYTE = Array(22)	The description string as returned by HDF_DFAN_GETFDS is an array of bytes.

<Expression> STRING = 'TEST FILE DESCRIPTION'
Using the STRING function on that array of bytes turns it back into a readable string.

PRINT, out	Print the byte values in the output variable. Note the 0 at the end. This string is null-terminated. IDL prints:

84 69 83 84 32 70 73 76 69 32 68 69 83 67 82 73 80 84 73 79 78 0

HDF_DFAN_GETFDS, 'test.hdf', out_nonull, /NONULL
This command would return the string as a byte array without a null-terminating byte.

HDF_DFAN_GETFDS, 'test.hdf', out_string, /STRING
This command would return the description string as a scalar string.

HDF_CLOSE, fid	Close the file.

See Also

HDF_DFAN_ADDFDS


HDF_DFAN_GETFID

The HDF_DFAN_GETFID procedure reads the next available file annotation from a Hierarchical Data Format file.

Calling Sequence

HDF_DFAN_GETFID, Filename, Label

Arguments

Filename

A scalar string containing the name of the file to be read.

Label

A named variable in which the annotation is returned as a string.

Keywords

FIRST

Set this keyword to read the first annotation in the file. Otherwise, the next available annotation is read (which may be the first annotation).


HDF_DFAN_GETLABEL

The HDF_DFAN_GETLABEL procedure reads the label for the given tag reference number in a Hierarchical Data Format file.

Calling Sequence

HDF_DFAN_GETLABEL, Filename, Tag, Ref, Label

Arguments

Filename

A scalar string that contains the name of the file to be read.

Tag

The tag number.

Ref

The reference number.

Label

A named variable in which the label is returned as a null-terminated (but see the NONULL keyword, below) string.

Keywords

NONULL

Set this keyword to prevent the null byte from being appended to the returned label string.

Example

fid = HDF_OPEN('test.hdf',/ ALL)

label = 'TEST LABEL'

tag=105	The annotation tag.

ref=2	Choose a reference number.

HDF_DFAN_PUTLABEL, 'test.hdf', tag, ref, label
Write the label.

HDF_DFAN_GETLABEL, 'test.hdf', tag, ref, outl
Read the label back.

HDF_DFAN_GETLABEL, 'test.hdf', tag, ref, outln, /NONULL
Read the label back without NULL termination.

HELP, label, outl, outln	They all look the same...

LABEL           STRING    = 'TEST LABEL'

OUTL            STRING    = 'TEST LABEL'

OUTLN           STRING    = 'TEST LABEL'

HELP, STRLEN(label), STRLEN(outl), STRLEN(outln)
...but they are not. IDL prints:
LONG      =           10
LONG      =           11
LONG      =           10

PRINT, BYTE(label), BYTE(outl), BYTE(outln)
Note outl has a NULL termination. IDL prints:
84  69  83  84  32  76  65  66  69  76
84  69  83  84  32  76  65  66  69  76   0
84  69  83  84  32  76  65  66  69  76

HDF_CLOSE, fid	Close the file.

See Also

HDF_DFAN_PUTDESC, HDF_DFAN_GETDESC, HDF_DFAN_PUTLABEL


HDF_DFAN_LABLIST

The HDF_DFAN_LABLIST function retrieves a list of the reference numbers and the corresponding labels for a given tag in a Hierarchical Data Format file. If successful, the number of entries found is returned.

Calling Sequence

Result = HDF_DFAN_LABLIST(Filename, Tag, Reflist, Labellist)

Arguments

Filename

A scalar string containing the name of the file to be read.

Tag

The tag number.

Reflist

A named variable in which an array of reference numbers associated with the given tag is returned.

Labellist

A named variable in which an array of labels is returned.

Keywords

LISTSIZE

Set the maximum size of the Reflist and Labellist returned. The default is to read all references present, or 20 if the inquiry to obtain the number of references fails.

MAXLABEL

Use this keyword to override the default label length of 16.

STARTPOS

Use this keyword to set the default starting position.


HDF_DFAN_LASTREF

The HDF_DFAN_LASTREF function returns the reference number of the most recently read or written annotation in a Hierarchical Data Format file.

Calling Sequence

Result = HDF_DFAN_LASTREF()


HDF_DFAN_PUTDESC

The HDF_DFAN_PUTDESC procedure writes a description for the given tag and reference number in a Hierarchical Data Format file.

Calling Sequence

HDF_DFAN_PUTDESC, Filename, Tag, Ref, Description

Arguments

Filename

A scalar string containing the name of the file to be written.

Tag

The tag number.

Ref

The reference number.

Description

A string or array of bytes containing the information to be written.

Bugs

Attempting to overwrite an existing description with a longer one fails.

Overwriting an existing description with a shorter description succeeds, but the description length is unchanged and garbage characters are left at the end of the description).


HDF_DFAN_PUTLABEL

The HDF_DFAN_PUTLABEL procedure writes a label for the given tag and reference number in a Hierarchical Data Format file.

Calling Sequence

HDF_DFAN_PUTLABEL, Filename, Tag, Ref, Label

Arguments

Filename

A scalar string containing the name of the file to be written.

Tag

The tag number.

Ref

The reference number.

Label

A string containing the description to write.

Bugs

Attempting to rewrite a label fails. For example:

HDF_DFAN_PUTLABEL, 't', tag, ref, 'XXXX'	Make label "XXXX".

HDF_DFAN_PUTLABEL, 't', tag, ref, 'YY'	Label now 'YY'

DELFILE, 't'	Remove the file.

HDF_DFAN_PUTLABEL, 't', tag, ref, 'XXXX'	Operation fails.


HDF_DFP_ADDPAL

The HDF_DFP_ADDPAL procedure appends a palette to a Hierarchical Data Format file.

Calling Sequence

HDF_DFP_ADDPAL, Filename, Palette

Arguments

Filename

A scalar string containing the name of the file to be written.

Palette

A vector or array containing palette data.


HDF_DFP_GETPAL

The HDF_DFP_GETPAL procedure reads the next available palette from a Hierarchical Data Format file.

Calling Sequence

HDF_DFP_GETPAL, Filename, Palette

Arguments

Filename

A scalar string containing the name of the file to be read.

Palette

A named variable in which the palette data is returned.


HDF_DFP_LASTREF

The HDF_DFP_LASTREF function returns the reference number of the most recently read or written palette in a Hierarchical Data Format file.

Calling Sequence

Result = HDF_DFP_LASTREF()


HDF_DFP_NPALS

The HDF_DFP_NPALS function returns the number of palettes present in a Hierarchical Data Format file. This number includes palettes associated with RIS8 (8-bit raster) images.

Calling Sequence

Result = HDF_DFP_NPALS(Filename)

Arguments

Filename

A scalar string containing the name of the desired HDF file.


HDF_DFP_PUTPAL

The HDF_DFP_PUTPAL procedure writes a palette to a Hierarchical Data Format file. Keywords can be used to write the palette at a specific location in the file. If no keywords are specified, all existing palettes in the data file are erased and the specified palette replaces them.

Calling Sequence

HDF_DFP_PUTPAL, Filename, Palette

Arguments

Filename

A scalar string containing the name of the file to be written.

Palette

A vector or array containing palette data.

Keywords

APPEND

Append the palette to the file (creating it if necessary)

OVERWRITE

Set this keyword to overwriting the previous palette with the one specified by Palette.


HDF_DFP_READREF

The HDF_DFP_READREF procedure sets the reference number of the palette in a Hierarchical Data Format file to be read by the next call to HDF_DFP_GETPAL.

Calling Sequence

HDF_DFP_READREF, Filename, Refno

Arguments

Filename

A scalar string containing the name of the file to be read.

Refno

The reference number of a palette.


HDF_DFP_RESTART

The HDF_DFP_RESTART procedure causes the next call to HDF_DFR8_GETPAL to read from the first palette in a Hierarchical Data Format file.

Calling Sequence

HDF_DFP_RESTART


HDF_DFP_WRITEREF

The HDF_DFP_WRITEREF procedure sets the reference number for the next palette to be written to a Hierarchical Data Format file. Normally, the HDF library automatically chooses a reference number for the palette. This procedure allows you to override that choice.

Calling Sequence

HDF_DFP_WRITEREF, Filename, Refno

Arguments

Filename

A scalar string containing the name of the file to be read.

Refno

The new reference number.


HDF_DFR8_ADDIMAGE

The HDF_DFR8_ADDIMAGE procedure appends an 8-bit raster image to the specified Hierarchical Data Format file. Note that JPEG compression has not been implemented.

Calling Sequence

HDF_DFR8_ADDIMAGE, Filename, Image

Arguments

Filename

A scalar string containing the name of the file to be written.

Image

A two-dimensional array containing the image data. If this array is not byte-type data, it is converted to bytes before writing.

Keywords

IMCOMP

Set this keyword to store the image using imcomp data reduction.

PALETTE

Set this keyword to a vector or array containing valid palette data.

RLE

Set this keyword to store the image using run length encoding.

Example

Assuming that we start with a file, new.hdf, with no 8-bit raster images, images could be appended and overwritten, with the following commands:

HDF_DFR8_ADDIMAGE,'new.hdf',Image1	Write the first image to the file.

HDF_DFR8_ADDIMAGE,'new.hdf',Image2	Append 2nd image.

HDF_DFR8_ADDIMAGE,'new.hdf',Image3	Append 3rd image.

HDF_DFR8_PUTIMAGE,'new.hdf',Image4	Use HDF_DFR8_PUTIMAGE to erase all previous images and write a new image at the first position in the file.

HDF_DFR8_ADDIMAGE,'new.hdf',Image5	Append 2nd image.


HDF_DFR8_GETIMAGE

The HDF_DFR8_GETIMAGE procedure retrieves an image and optionally, its palette, from a Hierarchical Data Format file.

Calling Sequence

HDF_DFR8_GETIMAGE, Filename, Image [, Palette]

Arguments

Filename

A scalar string containing the name of the file to be read.

Image

A named variable in which the image is returned.

Palette

A named variable in which the palette is returned as a 3-element by 256-element byte array. If the image does not have an associated palette, this variable is returned as 0.


HDF_DFR8_GETINFO

The HDF_DFR8_GETINFO procedure retrieves information about the current 8-bit HDF image.

Calling Sequence

HDF_DFR8_GETINFO, Filename, Width, Height, Has_Palette

Arguments

Filename

A string containing the name of the file to be read.

Width

A named variable in which the width of the image is returned.

Height

A named variable in which the height of the image is returned.

Has_Palette

A named variable in which 1 is returned if a palette is present. Otherwise, 0 is returned.

Example

h = HDF_OPEN('myhdf.hdf')	Open the file myhdf.hdf.

HDF_DFR8_GETINFO, 'myhdf.hdf', width, height, has_palette
Retrieve information about an image.

HELP, width, height, has_palette	Print information about the returned variables. IDL prints:
WIDTH LONG = 536
HEIGHT LONG = 412
HAS_PALETTE LONG = 1

HDF_CLOSE('myhdf.hdf')	Close the HDF file.

See Also

HDF_DFR8_GETIMAGE, HDF_DFR8_NIMAGES, HDF_DFR8_READREF, HDF_DFR8_RESTART


HDF_DFR8_LASTREF

The HDF_DFR8_LASTREF function returns the reference number of the most recently read or written 8-bit image in a Hierarchical Data Format file.

Calling Sequence

Result = HDF_DFR8_LASTREF()

Example

h = HDF_OPEN('myhdf.hdf')	Open an hdf file.

PRINT, HDF_DFR8_LASTREF()	IDL prints "0", meaning that the call was successful, but no reference number was available.

a = BINDGEN(100,100)	Create a 2D array representing an 8-bit image.

HDF_DFR8_ADDIMAGE, 'myhdf.hdf', a	Write the image to the file.

PRINT, HDF_DFR8_LASTREF()	IDL prints the reference number for the last 8-bit image operation (for example, "2"). Note the reference number is not simply a 1-based `image number'—it could easily be "2" or "3" for the first operation on the file.

HDF_DFR8_ADDIMAGE, 'myhdf.hdf', a	Add another image.

PRINT, HDF_DFR8_NIMAGES('myhdf.hdf')
IDL prints "2", because we've put two 8-bit images in the file.

HDF_CLOSE, h	Close the file.

See Also

HDF_DFR8_ADDIMAGE, HDF_DFR8_GETIMAGE, HDF_DFR8_GETINFO, HDF_DFR8_LASTREF, HDF_DFR8_NIMAGES, HDF_DFR8_READREF, HDF_DFR8_RESTART


HDF_DFR8_NIMAGES

The HDF_DFR8_NIMAGES function returns the number of 8-bit images in the specified Hierarchical Data Format file. A -1 is returned if the specified file is invalid or damaged.

Calling Sequence

Result = HDF_DFR8_NIMAGES(Filename)

Arguments

Filename

A string containing the name of the file to be read.

Example

h = HDF_OPEN('myhdf.hdf')	Open the file myfile.hdf.

number = HDF_DFR8_NIMAGES('myhdf.hdf')
Retrieve the number of 8-bit images in the file into the variable  number.

HDF_CLOSE, h	Close the file.

See Also

HDF_DFR8_GETIMAGE, HDF_DFR8_GETINFO, HDF_DFR8_READREF HDF_DFR8_RESTART


HDF_DFR8_PUTIMAGE

The HDF_DFR8_PUTIMAGE procedure writes an 8-bit raster image as the first image in a Hierarchical Data Format file. If there are images in the file, this procedure erases all other 8-bit and 24-bit images and writes Image as the first image in the file.

Calling Sequence

HDF_DFR8_PUTIMAGE, Filename, Image

Arguments

Filename

A scalar string containing the name of the file to be written.

Image

A two-dimensional array containing the image data. If this array is not byte-type data, it is converted to bytes before writing.

Keywords

IMCOMP

Set this keyword to store the image using imcomp data reduction.

PALETTE

A vector or array containing valid palette data. Note that the single command:

HDF_DFR8_PUTIMAGE, 'foo.hdf', Image, PALETTE=MyPal

gives the same result as the 2 commands:

HDF_DFR8_SETPALETTE, MyPal

HDF_DFR8_PUTIMAGE, 'foo.hdf', Image

RLE

Set this keyword to store the image using run length encoding.


HDF_DFR8_READREF

The HDF_DFR8_READREF procedure sets the reference number of the image to be read from a Hierarchical Data Format file by the next call to HDF_DFR8_GETIMAGE.

Calling Sequence

HDF_DFR8_READREF, Filename, Refno

Arguments

Filename

A scalar string containing the name of the file to be read.

Refno

A reference number for an 8-bit raster image.


HDF_DFR8_RESTART

The HDF_DFR8_RESTART procedure causes the next call to HDF_DFR8_GETIMAGE to read from the first image in the Hierarchical Data Format file.

Calling Sequence

HDF_DFR8_RESTART


HDF_DFR8_SETPALETTE

The HDF_DFR8_SETPALETTE procedure sets the default palette to be used for subsequent images in a Hierarchical Data Format file.

Calling Sequence

HDF_DFR8_SETPALETTE, Palette

Arguments

Palette

A 768-element byte array of palette data. This array be a vector (e.g., BYTARR(768)) or a two-dimensional array (e.g., BYTARR(3, 256)).


HDF_DFSD_ADDDATA

The HDF_DFSD_ADDDATA procedure writes data, as well as all other information set via calls to HDF_DFSD_SETINFO and HDF_DFSD_DIMSET, to a Hierarchical Data Format file.

The Data  array must have the same dimensions as the array in the file. The new SDS is appended to the file, unless the OVERWRITE keyword is set.

Calling Sequence

HDF_DFSD_ADDDATA, Filename, Data

Arguments

Filename

A scalar string containing the name of the file to be written.

Data

An expression (typically an array) containing the data to write.

Keywords

OVERWRITE

Set this keyword to write Data as the first, and only, SDS in the file. All previously-written scientific data sets in the file are removed.

SET_DIM

Set this keyword to make the dimension information for the HDF file based upon the dimensions of Data. This flag should be used if HDF_DFSD_SETINFO, DIMS=... has not been called or if the dimensions of Data do not match those previously set by a call to HDF_DFSD_SETINFO or HDF_DFSD_PUT.

SET_TYPE

Set this keyword to make the data type of the current SDS based on the data type of Data.


HDF_DFSD_DIMGET

The HDF_DFSD_DIMGET procedure retrieves information about the specified dimension number of the current Hierarchical Data Format file.

Calling Sequence

HDF_DFSD_DIMGET, Dimension

Arguments

Dimension

The dimension number [0, 1, 2, ...] to get information about.

Keywords

FORMAT

Set this keyword to return the dimension format string.

LABEL

Set this keyword to return the dimension label string.

SCALE

Use this keyword to return scale information about the dimension. Set this keyword to a vector of values of the same type as the data.

UNIT

Set this keyword to return the dimension unit string.


HDF_DFSD_DIMSET

The HDF_DFSD_DIMSET procedure sets the label, unit, format, or scale of dimensions in a Hierarchical Data Format file. Note that the label, unit, and format of a dataset must be set simultaneously.

Calling Sequence

HDF_DFSD_DIMSET, Dimension

Arguments

Dimension

The dimension number that the label, unit, format or scale apply to.

Keywords

FORMAT

A string for the dimension format. This string should be a standard IDL formatting string.

LABEL

A string for the dimension label.

SCALE

A vector of values used to set the dimension scale.

UNIT

A string for the dimension units.

Example

Suppose that a stored dataset is a 20 by 100 by 50 element floating-point array of values representing water content within the volume of a cloud. Assume further that each element in the 100-element dimension (the "Y" dimension) was sampled at 1/10 mile increments. Appropriate labeling, formatting, unit, and scaling information for the Y dimension can be set with the following command:

HDF_DFSD_DIMSET, 1, LABEL = 'Y Position', FORMAT = 'F8.2', $

             UNIT = 'Miles', SCALE = 0.1*FINDGEN(100)


HDF_DFSD_ENDSLICE

The HDF_DFSD_ENDSLICE procedure ends a sequence of calls started by HDF_DFSD_STARTSLICE by closing the internal slice interface and syncronizing the file.

Calling Sequence

HDF_DFSD_ENDSLICE

Example

See the example in the documentation for HDF_DFSD_STARTSLICE.

See Also

HDF_DFSD_GETINFO, HDF_DFSD_GETSLICE, HDF_DFSD_PUTSLICE, HDF_DFSD_SETINFO, HDF_DFSD_STARTSLICE


HDF_DFSD_GETDATA

The HDF_DFSD_GETDATA procedure reads data from a Hierarchical Data Format file.

Calling Sequence

HDF_DFSD_GETDATA, Filename, Data

Arguments

Filename

A scalar string containing the name of the file to be read.

Data

A named variable in which the data is returned.

Keywords

GET_DIMS

Set this keyword to get dimension information for reading the data. This keyword should only be used if one has not called HDF_DFSD_GETINFO with the DIMS keyword

GET_TYPE

Set this keyword to get the data type for the current SDS.


HDF_DFSD_GETINFO

The HDF_DFSD_GETINFO procedure retrieves information about the current Hierarchical Data Format file.

Note that calling HDF_DFSD_GETINFO with the DIMS or TYPE keywords may alter which dataset is current. See "Reading an Entire Scientific Dataset" and "Getting Other Information About SDSs" in the NCSA HDF Calling Interfaces and Utilities documentation.

Note that reading a label, unit, format, or coordinate system string that has more than 256 characters can have unpredictable results.

Calling Sequence

HDF_DFSD_GETINFO, Filename

Arguments

Filename

A scalar string containing the name of the file to be read. A filename is only needed to determine SDS dimensions and/or the number of SDSs in a file.

Keywords

CALDATA

Set this keyword to a named variable which will contain the calibration data associated with an SDS data set. The data will be returned in a structure of the form:

{ CAL: 0d, CAL_ERR: 0d, OFFSET: 0d, $

  OFFSET_ERR: 0d,NUM_TYPE: 0L }

COORDSYS

Set this keyword to return the data coordinate system description string.

DIMS

Set this keyword to a named variable in which the dimensions of the current SDS are returned in a longword array.

FORMAT

Set this keyword to return the data format description string.

LABEL

Set this keyword to return the data label description string.

LASTREF

Set this keyword to return the last reference number written or read for an SDS.

NSDS

Set this keyword to return the number of SDSs in the file.

RANGE

Set this keyword to return the valid max/min values for the current SDS.

TYPE

Set this keyword to a named variable which returns a string describing the type of the current SDS (e.g., 'BYTE', 'FLOAT' , etc.).

UNIT

Set this keyword to return the data unit description string.

Example

The following commands read an SDS, including information about its dimensions but not its annotations:

HDF_DFSD_GETINFO, filename, DIMS=d, TYPE=t, RANGE=r, $

              LABEL=l, UNIT=u, FORMAT=f, COORDSYS=c

...

FOR i = 0, N_ELEMENTS(d)-1 DO BEGIN

HDF_DFSD_DIMGET, i, LABEL=dl, UNIT=du, FORMAT=df, SCALE=ds

...

ENDFOR

HDF_DFSD_GETDATA, filename, data


HDF_DFSD_GETSLICE

The HDF_DFSD_GETSLICE procedure reads a slice of data from the current Hierarchical Data Format file.

Note: Before calling HDF_DFSD_GETSLICE, call HDF_DFSD_GETINFO with the DIMS and TYPE keywords to get the dimensions and type of the next data slice. Failure to get the dimensions and type will cause the HDF interface to attempt to read the data incorrectly, and may cause unexpected results.

Calling Sequence

HDF_DFSD_GETSLICE, Filename, Data

Arguments

Filename

A scalar string containing the name of the file to be read.

Data

A named variable in which the data, read from the SDS, is returned.

Keywords

COUNT

An optional vector containing the counts to be used in reading Value. The default is to read all elements in each record taking the value of OFFSET into account.

OFFSET

A vector specifying the array indices within the specified record at which to begin reading. OFFSET is a 1-dimensional array containing one element per HDF dimension. The default value is zero for each dimension.

Example

See the example in the documentation for HDF_DFSD_STARTSLICE.

See Also

HDF_DFSD_ENDSLICE, HDF_DFSD_GETINFO, HDF_DFSD_PUTSLICE, HDF_DFSD_SETINFO, HDF_DFSD_STARTSLICE


HDF_DFSD_PUTSLICE

The HDF_DFSD_PUTSLICE procedure writes a data slice to the current Hierarchical Data Format file.

Note: Before calling HDF_DFSD_PUTSLIDCE, call HDF_DFSD_SETINFO to set the dimensions and attributes of the slice and HDF_DFSD_STARTSLICE to initialize the slice interface.

Calling Sequence

HDF_DFSD_PUTSLICE, Data

Arguments

Data

An array containing the data to write. Dimensions used to write the data are taken from the dimensions of Data, unless the COUNT keyword is used.

Keywords

COUNT

An optional vector containing the counts to be used in writing Data. The counts do have to match the dimensions (number or sizes), but the count cannot describe more elements than exist.

Example

See the example in the documentation for HDF_DFSD_STARTSLICE.

See Also

HDF_DFSD_ENDSLICE, HDF_DFSD_GETINFO, HDF_DFSD_GETSLICE, HDF_DFSD_SETINFO, HDF_DFSD_STARTSLICE


HDF_DFSD_READREF

The HDF_DFSD_READREF procedure specifies the reference number of the Hierarchical Data Format file to be read by the next call to HDF_DFSD_GETINFO or HDF_DFSD_GETDATA.

Calling Sequence

HDF_DFSD_READREF, Filename, Refno

Arguments

Filename

A scalar string containing the name of the file to be read.

Refno

The reference number of the desired SDS.


HDF_DFSD_SETINFO

The HDF_DFSD_SETINFO procedure controls information associated with a Hierarchical Data Format file. Because of the manner in which the underlying HDF library was written, it is necessary to set the dimensions and data type of a scientific data set the first time that HDF_DFSD_SETINFO is called.

This procedure has many options, controlled by keywords. The order in which the keywords are specified is unimportant as the routine insures the order of operation for any given call to it. CLEAR and RESTART requests are performed first, followed by type and dimension setting, followed by length setting, followed by the remaining keyword requests.

If you are not writing any ancillary information, you can call HDF_DFSD_ADDDATA with the SET_TYPE and/or SET_DIMS keywords.

Data string lengths should be set before, or at the same time as, writing the corresponding data string. For example:

HDF_DFSD_SETINFO, LEN_FORMAT=10, FORMAT='12.3F'

or

HDF_DFSD_SETINFO, LEN_FORMAT=10

HDF_DFSD_SETINFO, FORMAT='12.3F'

Due to the underlying C routines, it is necessary to set all four data strings at the same time, or the unspecified strings are treated as `' (null strings). For example:

HDF_DFSD_SETINFO, LABEL = 'hi'

HDF_DFSD_SETINFO, UNIT = 'ergs'

is the same as:

HDF_DFSD_SETINFO, LABEL='hi', UNIT='', FORMAT='', COORDSYS=''

HDF_DFSD_SETINFO, LABEL='', UNIT='ergs', FORMAT='', COORDSYS=''

Calling Sequence

HDF_DFSD_SETINFO

Arguments

None.

Keywords

BYTE

Set this keyword to make the SDS data type DFNT_UINT8 (1-byte unsigned integer).

CALDATA

Set this keyword to a structure containing calibration information. The structure should contain five tags, the first four of which are double-precision floating-point, and fifth of which should be long integer. For example:

caldata = { Cal:	1.0d $	Calibration factor.

            Cal_Err:	0.1d $	Calibration error.

            Offset:	2.5d $	Uncalibrated offset.

            Offset_Err:	0.1d $	Uncalibrated offset error.

            Num_Type:	5L   $	Number type of uncalibrated

}	data.

Some typical values for the Num_Type field include:

For byte data:

3L     (DFNT_UCHAR8)

21L    (DFNT_UINT8)

For integer data:

22L    (DNFT_INT16)

For long-integer data:

24L    (DFNT_INT32)

For floating-point data:

5L     (DFNT_FLOAT32)

6L     (DFNT_FLOAT64)

There are other types, but they are not native to IDL. They can be found in the hdf.h header file for the HDF library.

CLEAR

Set this keyword to reset all possible set values to their default value.

COORDSYS

A string for the data coordinate system description.

DIMS

Set this keyword to a vector of dimensions to be used in writing the next SDS. For example:

HDF_DFSD_SETINFO, DIMS = [10, 20, 30]

DOUBLE

Set this keyword to make the SDS data type DFNT_FLOAT64 (8-byte floating point).

FLOAT

Set this keyword to make the SDS data type DFNT_FLOAT32 (4-byte floating point).

FORMAT

A string for the data format description.

INT

Set this keyword to make the SDS data type DFNT_INT16 (2-byte signed integer).

LABEL

A string for the data label description.

LEN_LABEL

The label string length (default is 255).

LEN_UNIT

The unit string length (default is 255).

LEN_FORMAT

The format string length (default is 255).

LEN_COORDSYS

The format coordinate system string length (default is 255).

LONG

Set this keyword to make the SDS data type DFNT_INT32 (4-byte signed integer).

RANGE

The minimum and maximum range, represented as a 2-element vector of the same data type as the data to be written. The first element is the maximum, the second is the minimum. For example:

HDF_DFSD_SETINFO, RANGE = [10,0]

RESTART

Set this keyword to make the get (HDF_DFSD_GETSLICE) routine read from the first SDS in the file.

UNIT

A string for the data unit description.

Example

Write a 100x50 array of longs:

data = LONARR(100, 50)

HDF_DFSD_SETINFO, /CLEAR, /LONG, DIMS=[100,50], $

              RANGE=[MAX(data), MIN(data)], $

              LABEL='pressure', UNIT='pascals', $

              FORMAT='F10.0'


HDF_DFSD_STARTSLICE

The HDF_DFSD_STARTSLICE procedure prepares the system to write a slice of data to a Hierarchical Data Format file. HDF_DFSD_SETINFO must be called before HDF_DFSD_STARTSLICE to set the dimensions and attributes of the slice.

This procedure must be called before calling HDF_DFSD_PUTSLICE, and must be terminated with a call to HDF_DFSD_ENDSLICE.

Calling Sequence

HDF_DFSD_STARTSLICE, Filename

Arguments

Filename

A scalar string containing the name of the file to be written.

Example

fid=HDF_OPEN('test.hdf',/ALL)	Open an HDF file.

Create two datasets:

slicedata1=FINDGEN(5,10,15)

slicedata2=DINDGEN(4,5)

Use HDF_DFSD_SETINFO to set the dimensions, then add the first slice:

HDF_DFSD_SETINFO,LABEL='label1', DIMS=[5,10,15], /FLOAT

HDF_DFSD_STARTSLICE,'test.hdf'

HDF_DFSD_PUTSLICE, slicedata1

HDF_DFSD_ENDSLICE

Repeat the process for the second slice:

HDF_DFSD_SETINFO, LABEL='label2', DIMS=[4,5], /DOUBLE

HDF_DFSD_STARTSLICE,'test.hdf'

HDF_DFSD_PUTSLICE, slicedata2

HDF_DFSD_ENDSLICE

HDF_DFSD_SETINFO, /RESTART

Use HDF_DFSD_GETINFO to advance slices and set slice attributes, then get the slices:

HDF_DFSD_GETINFO, name, DIMS=dims, TYPE=type

HDF_DFSD_GETSLICE, out1

HDF_DFSD_GETINFO, name, DIMS=dims, TYPE=type

HDF_DFSD_GETSLICE, out2

Close the HDF file:

HDF_CLOSE('test.hdf')

Check the first slice to see if everything worked:

IF TOTAL(out1 EQ slicedata1) EQ N_ELEMENTS(out1) THEN $

    PRINT, 'SLICE 1 WRITTEN/READ CORRECTLY' ELSE $

    PRINT, 'SLICE 1 WRITTEN/READ INCORRECTLY'

IDL prints:

SLICE 1 WRITTEN/READ CORRECTLY

Check the second slice to see if everything worked:

IF TOTAL(out2 EQ slicedata2) EQ N_ELEMENTS(out2) THEN $

    PRINT, 'SLICE 2 WRITTEN/READ CORRECTLY' ELSE $

    PRINT, 'SLICE 2 WRITTEN/READ INCORRECTLY'

IDL prints:

SLICE 2 WRITTEN/READ CORRECTLY

See Also

HDF_DFSD_ENDSLICE, HDF_DFSD_GETINFO, HDF_DFSD_GETSLICE, HDF_DFSD_PUTSLICE, HDF_DFSD_SETINFO


HDF_DUPDD

The HDF_DUPDD procedure generates new references to existing data in a Hierarchical Data Format file.

Calling Sequence

HDF_DUPDD, FileHandle, NewTag, NewRef, OldTag, OldRef

Arguments

Filehandle

The HDF file handle returned from a previous call to HDF_OPEN.

NewTag

An integer tag for new data descriptor.

NewRef

An integer reference number for the new data descriptor.

OldTag

The integer tag of data descriptor to duplicate.

OldRef

The reference number of data descriptor to duplicate.


HDF_EXISTS

The HDF_EXISTS function returns True if the Hierarchical Data Format (HDF) scientific data format library is supported on the current IDL platform.

This routine is written in the IDL language. Its source code can be found in the file hdf_exists.pro in the lib subdirectory of the IDL distribution.

Calling Sequence

Result = HDF_EXISTS()

Example

The following IDL command prints an error message if the HDF library is not available:

IF HDF_EXISTS() EQ 0 THEN PRINT, 'HDF not supported.'


HDF_ISHDF

The HDF_ISHDF function returns true if the file is a Hierarchical Data Format file.

Calling Sequence

Result = HDF_ISHDF(Filename)

Arguments

Filename

A scalar string containing the name of the file to be tested.


HDF_NEWREF

The HDF_NEWREF function returns the next available reference number for a Hierarchical Data Format file.

Calling Sequence

Result = HDF_NEWREF(Filehandle)

Arguments

Filehandle

The HDF file handle returned from a previous call to HDF_OPEN.


HDF_NUMBER

The HDF_NUMBER function returns the number of tags in a Hierarchical Data Format file or the number of references associated with a given tag.

Calling Sequence

Result = HDF_NUMBER(Filehandle)

Arguments

Filehandle

The HDF file handle returned from a previous call to HDF_OPEN.

Keywords

TAG

Set this keyword to an integer tag number or the string '*'. If this keyword is set to a tag number, HDF_NUMBER returns the number of references associated with the given tag. If this keyword is set to the string '*', or is not specified, HDF_NUMBER returns the total number of tags in the HDF file.


HDF_OPEN

The HDF_OPEN function opens or creates a Hierarchical Data Format file for reading and/or writing. If successful, a non-zero file handle (a longword integer) is returned. Longword zero is returned on failure.

Note that any combination of the READ, WRITE and CREATE keywords is valid.

Calling Sequence

Result = HDF_OPEN(Filename)

Arguments

Filename

A scalar string containing the name of the file to be opened.

 Keywords

ALL

Set this keyword to create a new HDF file with read and write access. Setting this keyword is equivalent to:

HDF_OPEN(filename, /READ, /WRITE, /CREATE)

CREATE

Set this keyword to create a new HDF file.

NUM_DD

Use this keyword to override the machine default for the number of data descriptors to be allocated per DD block. For example:

H = HDF_OPEN('foo.hdf',/CREATE,/WRITE, NUM_DD=100)

RDWR

Set this keyword to open file with both read and write access. Setting this keyword is equivalent to:

HDF_OPEN(filename, /READ, /WRITE)

READ

Set this keyword to open the file with read access.

WRITE

Set this keyword to open the file with write access.


HDF_SD_ADDDATA

The HDF_SD_ADDDATA procedure writes a hyperslab of values to an SD dataset. By default, the output data is transposed. This transposition puts the data in column order, which is more efficient in HDF than row order (which is more efficient in IDL). To write the data without transposing, set the NOREVERSE keyword. The OFFSET, COUNT, and STRIDE keywords are similarly affected by the NOREVERSE keyword.

Calling Sequence

HDF_SD_ADDDATA, SDS_ID, Data

Arguments

SDS_ID

An SD dataset ID as returned by HDF_SE_SELECT or HDF_SD_CREATE.

Data

The data to be written.

Keywords

COUNT

Set this keyword to a vector of counts (i.e., the number of items) to be written in each dimension. The default is to write all available data. Use caution when using this keyword. See the second example, below.

NOREVERSE

Set this keyword to prevent HDF_SD_ADDATA's transposition of Data into column order.

START

Set this keyword to a vector that contains the starting position for the data. The default position is [0, 0, ..., 0].

STRIDE

Set this keyword to a vector that contains the strides, or sampling intervals, between accessed values of the NetCDF variable. The default stride vector is that for a contiguous write: [0, 0, ..., 0].

Example

The following example writes a 230-element by 230-element byte image to an SD dataset, then reads it back as a 70 by 70 image starting at (40, 20), sampling every other Y pixel and every third X pixel:

start = [40, 20]	Set the start vector.

count = [70, 70]	Set the count vector.

stride = [2, 3]	Set the stride vector.

image = DIST(230, 230)	Create the image.

TV, image	Display the image.

sd_id = HDF_SD_START('image.hdf', /CREATE)
Create a new HDF file in SD mode.

sds_id = HDF_SD_CREATE(sd_id, 'image', [230, 230], /BYTE)
Define a new SD dataset.

HDF_SD_ADDDATA, sds_id, image	Write the image into the dataset.

HDF_SD_GETDATA, sds_id, full	Retrieve the full image.

HDF_SD_GETDATA, sds_id, small, COUNT=count, $

     START=start, STRIDE=stride	Retrieve the sub-sampled image.

HELP, full, small	Print information about the images. IDL prints:
FULL   BYTE = Array(230, 230)
SMALL  BYTE = Array(70, 70)

ERASE	Erase the window.

TV, full	Display the full image.

TV, small	Display the sub-sampled image.

Continuing with our example, suppose we want to write the center 100 by 100 pixels of the image to the file. You might be tempted to try:

HDF_SD_ADDATA, sds_id, image, START=[65, 65], COUNT=[100,100]
This command will not work.

Instead, you must create a separate variable of the correct size containing only the pixels we want to write:

mini = image(65:164, 65:164)	Create a new image that is a subset of the original.

HDF_SD_ADDATA, sds_id, mini, START=[65, 65], COUNT=[100,100]
This is the correct way to add the data.

HDF_SD_ENDACCESS, sds_id	End SD access.

HDF_SD_END, sd_id	Close the file.


HDF_SD_ATTRFIND

The HDF_SD_ATTRFIND function locates the index of an HDF attribute given its name. The attribute can be global or from a specific dataset. If an attribute is located, its index is returned. Otherwise, -1 is returned. Once an attribute's index is known, the HDF_SD_ATTRINFO function can be used to read that attribute.

Calling Sequence

Result = HDF_SD_ATTRFIND(S_ID, Name)

Arguments

S_ID

An SD interface ID as returned by HDF_SD_START (i.e., a global attribute's "SD_ID"), or HDF_SD_SELECT/HDF_SD_CREATE (i.e., a dataset's "SDS_ID").

Name

A string containing the name of the attribute whose index is to be returned.

Example

sd_id = HDF_SD_START('demo.hdf')	Open an HDF file and start the SD interface.

gindex = HDF_SD_ATTRFIND(sd_id, 'TITLE')
Find "TITLE", a global attribute.

sds_id = HDF_SD_SELECT(sd_id, 1)	Get the ID for the first dataset.

HDF_SD_ATTRINFO,sd_id,gindex, NAME=name, TYPE=type, COUNT=count
Read attribute info.

HELP, type, count, name	Print info about the returned variables. IDL prints:
TYPE STRING = 'STRING'
COUNT LONG = 8
NAME STRING = 'TITLE'

dindex = HDF_SD_ATTRFIND(sds_id, 'LOCATION')
Find the "LOCATION" dataset attribute.

HDF_SD_ATTRINFO,sds_id,dindex,NAME=name,TYPE=type,COUNT=count
Read attribute info.

See Also

HDF_SD_ATTRINFO, HDF_SD_ATTRSET, HDF_SD_SELECT

HDF_SD_SELECT, HDF_SD_ATTRINFO, HDF_SD_ATTRSET


HDF_SD_ATTRINFO

The HDF_SD_ATTRINFO procedure reads or retrieves information about an SD attribute. The attribute can be global or from a specific dataset. If an attribute is not present, an error message is printed.

Calling Sequence

HDF_SD_ATTRINFO, S_ID, Attr_Index

Arguments

S_ID

An SD interface ID as returned by HDF_SD_START (i.e., a global attribute's "SD_ID"), or HDF_SD_SELECT/HDF_SD_CREATE (i.e., a dataset's "SDS_ID").

Attr_Index

The attribute index, usually obtained by calling HDF_SD_ATTRFIND or HDF_SD_NAMETOINDEX .

Keywords

COUNT

Set this keyword to a named variable in which the total number of values in the specified attribute is returned.

DATA

Set this keyword to a named variable in which the attribute data is returned.

NAME

Set this keyword to a named variable in which the name of the attribute is returned.

TYPE

Set this keyword to a named variable in which the datatype of the attribute is returned as a string. Possible values are "

Example

sd_id = HDF_SD_START('demo.hdf')	Open an HDF file and start the SD interface.

gindex = HDF_SD_ATTRFIND(sd_id, 'TITLE')
Find a global attribute

HDF_SD_ATTRINFO, sd_id, gindex, NAME=n, TYPE=t, COUNT=c, DATA=d
Retrieve attribute info.

HELP, n, t, c	Print information about the returned variables. IDL prints:
N STRING = 'TITLE'
T STRING = 'STRING'
C LONG = 17
D STRING = '5th Ave Surf Shop'

sds_id = HDF_SD_SELECT(sd_id, 0)	Return the SD dataset ID for the first dataset (index 0).

dindex = HDF_SD_ATTRFIND(sds_id, 'LOCATION')
Find a dataset attribute.

HDF_SD_ATTRINFO,SDS_ID, dindex, NAME=n, TYPE=t, COUNT=c, DATA=d
Retrieve attribute info.

HELP, n, t, c, d	Print information about the new returned variables. IDL prints:
N STRING = 'LOCATION'
T STRING = 'STRING'
C LONG = 15
D STRING = 'MELBOURNE BEACH'

See Also

HDF_SD_ATTRFIND, HDF_SD_ATTRSET, HDF_SD_CREATE, HDF_SD_SELECT, HDF_SD_START


HDF_SD_ATTSET
HDF_SD_ATTRSET

The HDF_SD_ATTRSET procedure writes attributes to an open HDF SD dataset. If no data type is specified, the data type is taken from the Values argument.

Calling Sequence

HDF_SD_ATTRSET, S_ID, Attr_Name, Values

Arguments

S_ID

An SD interface ID as returned by HDF_SD_START (i.e., a global attribute's "SD_ID"), or HDF_SD_SELECT/HDF_SD_CREATE (i.e., a dataset's "SDS_ID").

Attr_Name

A string containing the name of the attribute to be written.

Values

The attribute values to be written.

Keywords

BYTE

Set this keyword to indicate that the attribute is composed of bytes.

DOUBLE

Set this keyword to indicate that the attribute is composed of double-precision floating-point values.

FLOAT

Set this keyword to indicate that the attribute is composed of single-precision floating-point values.

INT

Set this keyword to indicate that the attribute is composed of 2-byte integers. Setting this keyword is the same as setting the SHORT keyword.

LONG

Set this keyword to indicate that the attribute is composed of longword integers.

SHORT

Set this keyword to indicate that the attribute is composed of 2-byte integers. Setting this keyword is the same as setting the INT keyword.

Example

fid = HDF_OPEN('demo.hdf', /ALL)	Create a new HDF file.

sd_id = HDF_SD_START('demo.hdf', /RDWR)
Start the SD interface.

HDF_SD_ATTRSET, sd_id, 'TITLE', 'MY TITLE GLOBAL', 16
Create a global attribute.

HDF_SD_ATTRSET, sd_id, 'RANGE', [-99.88,55544.2], /DOUBLE
Create another global attribute.

SDS_ID = HDF_SD_CREATE(sd_id, 'var1', [10,20], /FLOAT)
Create a dataset.

HDF_SD_ATTRSET, SDS_ID, 'TITLE', 'MY TITLE SD_ID', 15
Add a dataset attribute.

index=HDF_SD_ATTRFIND(sd_id, 'RANGE')
Find the recently-created RANGE attribute.

HDF_SD_ATTRINFO,sd_id,index,NAME=atn,COUNT=atc,TYPE=att,DATA=d
Retrieve data from RANGE.

HELP, atn, atc, att	Print information about the returned variables. IDL prints:
ATN STRING = 'RANGE'
ATC LONG = 2
ATT STRING = 'DOUBLE'

PRINT, d, FORMAT='(F8.2,x,F8.2)'	Print the data returned in variable d with the given format. IDL prints:
-99.88 55544.20

HDF_SD_ENDACCESS, sds_id	End access to the HDF file.

HDF_SD_END, sd_id

HDF_CLOSE, fid

See Also

HDF_SD_ATTRFIND, HDF_SD_ATTRINFO, HDF_SD_CREATE, HDF_SD_SELECT


HDF_SD_CREATE

The HDF_SD_CREATE function creates and defines a Scientific Dataset (SD) for an HDF file. Keywords can be set to specify the data type. If no keywords are present a floating-point dataset is created. The returned value of this function is the SDS ID of the newly-created dataset.

Calling Sequence

Result = HDF_SD_CREATE(SD_ID, Name, Dims)

Arguments

SD_ID

An SD ID as returned by HDF_SD_START.

Name

A string containing the name of the variable to be created.

Dims

A 1-based vector specifying the dimensions of the variable. If an UNLIMITED dimension is desired, set the last vector element to zero or a negative number.

Keywords

BYTE

Set this keyword to indicate that the dataset is composed of bytes.

DOUBLE

Set this keyword to indicate that the dataset is composed of double-precision floating-point values.

FLOAT

Set this keyword to indicate that the dataset is composed of single-precision floating-point values.

INT

Set this keyword to indicate that the dataset is composed of 2-byte integers. Setting this keyword is the same as setting the SHORT keyword.

LONG

Set this keyword to indicate that the dataset is composed of longword integers.

SHORT

Set this keyword to indicate that the dataset is composed of 2-byte integers. Setting this keyword is the same as setting the INT keyword.

Example

sd_id = HDF_SD_START('test.hdf', /CREATE)
Create a new HDF file.

sds_id = HDF_SD_CREATE(sd_id, 'var1', [9,40,0], /SHORT)
Create an dataset that includes an unlimited dimension.

The example for HDF_SD_ATTRSET also demonstrates the use of this routine.

See Also

HDF_OPEN, HDF_SD_ENDACCESS, HDF_SD_SELECT


HDF_SD_DIMGET

The HDF_SD_DIMGET function retrieves information about an SD dataset dimension.

Calling Sequence

Result = HDF_SD_DIMGET(Dim_ID)

Arguments

Dim_ID

A dimension ID as returned by HDF_SD _DIMGETID.

Keywords

COUNT

Set this keyword to return the dimension size.

FORMAT

Set this keyword to return the dimension format description string.

LABEL

Set this keyword to return the dimension label description string.

NAME

Set this keyword to return the dimension name.

NATTR

Set this keyword to return the number of attributes for the dimension.

SCALE

Set this keyword to return the scale of the dimension.

TYPE

Set this keyword to return a string describing the data's type (i.e., `BYTE').

UNIT

Set this keyword to return the dimension unit description string.

Example

For an example using this routine, see the example for HDF_SD_DIMSET.

See Also

HDF_SD_CREATE, HDF_SD_DIMGETID, HDF_SD_DIMSET, HDF_SD_SELECT


HDF_SD_DIMGETID

The HDF_SD_DIMGETID function returns a dimension ID given a dataset's "SDS_ID" and a dimension number.

Calling Sequence

Result = HDF_SD_DIMGETID(SDS_ID, Dimension_Number)

Arguments

SDS_ID

An SD dataset ID as returned by HDF_SD _SELECT or HDF_SD_CREATE.

Dimension_Number

A zero-based dimension number. The dimension number must be greater than or equal to 0 and less than the maximum dimension number, or rank.

Example

For an example illustrating this routine, see the documentation for HDF_SD_DIMSET.

See Also

HDF_SD_CREATE, HDF_SD_DIMGET, HDF_SD_DIMSET, HDF_SD_SELECT


HDF_SD_DIMSET

The HDF_SD_DIMSET function sets the scale and data strings for an SD dimension.

Calling Sequence

HDF_SD_DIMSET, Dim_ID

Arguments

Dim_ID

A dimension ID as returned by HDF_SD _DIMGETID.

Keywords

FORMAT

A string for the dimension format.

LABEL

A string for the dimension label.

NAME

A string for the dimension name.

SCALE

A vector containing the dimension scale values.

UNIT

A string for the dimension unit.

Example

sd_id = HDF_SD_START('myhdf.hdf', /RDWR)
Initialize the SD interface.

sds_id = HDF_SD_CREATE(sd_id, 'var1', [10,20,0], /LONG)
Create 3 dimensions.

dim_id=HDF_SD_DIMGETID(sds_id,0)	Select the first dimension.

HDF_SD_DIMSET, dim_id, NAME='d1', LABEL='l1', $

               FORMAT='f1', UNIT='u1', SCALE=FINDGEN(10)
Set the data strings and scale for the first dimension.

HDF_SD_DIMGET, dim_id, NAME=d1, LABEL=l1, FORMAT=f1, $

           UNIT=u1, SCALE=sc, COUNT=cnt, NATTR=natt, TYPE=type
Retrieve the information.

HELP, d1, l1, f1, u1, sc, cnt, natt, type
Print information about the returned variables. IDL prints:
D1 STRING = 'd1'
L1 STRING = 'l1'
F1 STRING = 'f1'
U1 STRING = 'u1'
SC FLOAT = Array(10)
CNT LONG = 10
NATT LONG = 3
TYPE STRING = 'FLOAT'

HDF_SD_ENDACCESS,sds_id	Close the SD interface.

HDF_SD_END, sd_id

See Also

HDF_SD_CREATE, HDF_SD_DIMGET, HDF_SD_DIMGETID, HDF_SD_SELECT


HDF_SD_END

The HDF_SD_END function closes the SD interface to an HDF file. Failure to close the file without a call to HDF_SD_END results in the loss of any changed or added SD data. Therefore, HDF_SD_END calls should always be paired with calls to HDF_SD_START. Before HDF_SD_END is called, all access to SD datasets should be terminated with calls to HDF_SD_ENDACCESS.

Calling Sequence

HDF_SD_END, SD_ID

Arguments

SD_ID

An SD interface ID as returned by HDF _SD_START.

Example

sd_id = HDF_SD_START('test.hdf', /CREATE)
Open a new HDF file.

...	Various commands could now be used to access SD data in the HDF file.

HDF_SD_ENDACESS, sds_id_1	When done with datasets, access should be ended with calls to HDF_SD_ENDACCESS.

HDF_SD_END, sd_id	When done with an HDF file, it should be closed.

Another example can be seen in the documentation for HDF_SD_ATTRSET.

See Also

HDF_CLOSE, HDF_OPEN, HDF_SD_ENDACCESS, HDF_SD_START


HDF_SD_ENDACCESS

The HDF_SD_ENDACCESS function closes an SD dataset interface. Failure to close the interface can result in the loss of any changed or added SD data. This routine should be called once for each call to HDF_SD_START or HDF_SD_CREATE. After all SD dataset interfaces are closed, the HDF file can safely be closed with HDF_SD_END.

Calling Sequence

HDF_SD_ENDACCESS, SD_ID

Arguments

SDS_ID

An SD dataset ID as returned by HDF_SD_SELECT, or HDF_SD_CREATE.

Example

sd_id = HDF_SD_START('test.hdf', /CREATE)
Open a new HDF file.

sds_id_1 = HDF_SD_SELECT(sd_id,0)	Access the HDF file.

HDF_SD_ENDACCESS, sds_id_1	End access to any SD IDs.

HDF_SD_END, sd_id	Close the HDF file.

For Also, see the example in HDF_SD_ATTRSET.

See Also

HDF_CLOSE, HDF_OPEN, HDF_SD_CREATE, HDF_SD_ENDACCESS, HDF_SD_START


HDF_SD_FILEINFO

The HDF_SD_FILEINFO procedure retrieves the number of datasets and global attributes in an HDF file.

Calling Sequence

HDF_SD_FILEINFO, SD_ID, Datasets, Attributes

Arguments

SD_ID

An SD interface ID as returned by HDF_SD_START.

Datasets

A named variable in which the total number of SD-type objects (i.e., the number of datasets + the number of dimensions) in the file is returned.

Attributes

A named variable in which the number of global attributes in the file is returned.

Example

sd_id = HDF_SD_START('demo.hdf', /CREATE)
Start the SD interface.

HDF_SD_ATTRSET,sd_id, 'TITLE', 'MYTITLE'
Set a global attribute.

HDF_SD_ATTRSET,sd_id, 'TITLE2', 'MYTITLE2'
Set another one.

sds_id = HDF_SD_CREATE(sd_id, 'var1', [10,3])
Create a dataset.

HDF_SD_FILEINFO, sd_id, datasets, attributes
Retrieve info about the dataset.

HELP, datasets, attributes	Print information about the returned variables. IDL prints:
DATASETS LONG = 1
ATTRIBUTES LONG = 2

HDF_SD_ENDACCESS, sds_id	End SD access.

HDF_SD_END, sd_id	Close the SD interface.

See Also

HDF_SD_ATTRFIND, HDF_SD_ATTRINFO, HDF_SD_START


HDF_SD_GETDATA

The HDF_SD_GETDATA procedure retrieves a hyperslab of values from an SD dataset. By default, the retrieved data is transposed from HDF's column order format into IDL's row order which is more efficient in IDL. To retrieve the dataset without this transposition, set the NOREVERSE keyword.

Calling Sequence

HDF_SD_GETDATA, SDS_ID, Data

Arguments

SDS_ID

An SD dataset ID as returned by HDF_SD _SELECT or HDF_SD_CREATE.

Data

A named variable in which the values are returned.

Keywords

COUNT

Set this keyword to a vector containing the counts, or number of items, to be read. The default is to read all available data.

NOREVERSE

Set the keyword to retrieve the data without transposing the data from column to row order.

START

Set this keyword to a vector containing the starting position for the read. The default start position is [0, 0, ..., 0].

STRIDE

Set this keyword to a vector containing the strides, or sampling intervals, between accessed values of the HDF variable. The default stride vector is that for a contiguous read: [0, 0, ..., 0].

Example

For an example using this routine, see the documentation for HDF_SD_ADDDATA

See Also

HDF_SD_ADDDATA, HDF_SD_GETINFO


HDF_SD_GETINFO

The HDF_SD_GETINFO procedure retrieves information about an SD dataset.

Caution:  Reading a label, unit, format, or coordinate system string that has more than 256 characters can have unpredictable results.

Calling Sequence

HDF_SD_GETINFO, SDS_ID

Arguments

SDS_ID

An SD dataset ID as returned by HDF_SD _SELECT or HDF_SD_CREATE.

Keywords

CALDATA

Set this keyword to a named variable in which the calibration data associated with the SD dataset is returned. The data is returned in a structure of the form:

{CAL: 0D, CAL_ERR: 0D, OFFSET: 0D, OFFSET_ERR: 0D, NUM_TYPE: 0L}

For more information about calibration data, see the documentation for HDF_SD_SETINFO.

COORDSYS

Set this keyword to a named variable in which the coordinate system description string is returned.

DIMS

Set this keyword to a named variable in which the dimensions of the SD dataset are returned. For efficiency, these dimensions are returned in reverse order from their HDF format unless the NOREVERSE keyword is also set.

FILL

Set this keyword to a named variable in which the fill value of the SD dataset is returned.

FORMAT

Set this keyword to a named variable in which the format description string is returned.

LABEL

Set this keyword to a named variable in which the label description string is returned.

NATTS

Set this keyword to a named variable in which the number of "NetCDF-style" attributes for the SD dataset is returned.

NDIMS

Set this keyword to a named variable in which the number of dimensions in the dataset is returned.

NOREVERSE

Set this keyword in conjunction with DIMS to return the variable dimensions in non-reversed form. By default, IDL reverses data and dimensions from the HDF format to improve efficiency.

RANGE

Set this keyword to a named variable in which the maximum and minimum of the current SD dataset is returned as a two-element vector.

TYPE

Set this keyword to a named variable in which the type of the SD dataset is returned as a scalar string (e.g., "BYTE").

UNIT

Set this keyword to a named variable in which the unit description string is returned.

Example

For an example using this routine, see the documentation for HDF_SD_SETINFO.

See Also

HDF_OPEN, HDF_SD_END, HDF_SD_SETINFO, HDF_SD_START


HDF_SD_ISCOORDVAR

The HDF_SD_ISCOORDVAR function returns True (1) if the supplied dataset ID represents a NetCDF "coordinate" variable. Otherwise, False (0) is returned.

Calling Sequence

Result = HDF_SD_ISCOORDVAR(SDS_ID)

Arguments

SDS_ID

An SD dataset ID as returned by HDF_SD _SELECT or HDF_SD_CREATE.


HDF_SD_NAMETOINDEX

The HDF_SD_NAMETOINDEX function returns an SD dataset index given its name and SD interface ID. An error message is printed if the dataset cannot be located. The returned index can be used by HDF_SD_SELECT to access an SD dataset.

Calling Sequence

Result = HDF_SD_NAMETOINDEX(SD_ID, SDS_Name)

Arguments

SD_ID

An SD interface ID as returned by HDF_SD_START.

SDS_Name

A string containing the name of the SD dataset be located.

Example

sd_id = HDF_SD_START('demo.hdf')	Start the SD interface.

index = HDF_SD_NAMETOINDEX(sd_id, 'variable_2')
Return the index of the `variable_2' dataset.

sds_id=HDF_SD_SELECT(sd_id,index)	Access the dataset.

HDF_SD_ENDACCESS, sds_id	End access.

HDF_SD_END, sd_id

See Also

HDF_SD_REFTOINDEX, HDF_SD_SELECT, HDF_SD_START


HDF_SD_REFTOINDEX

The HDF_SD_REFTOINDEX function returns a scientific dataset's index given its reference number and SD interface ID.

Calling Sequence

Result = HDF_SD_REFTOINDEX(SD_ID, Refno)

Arguments

SD_ID

An SD interface ID as returned by HDF_SD_START.

Refno

The SD reference number for the desired dataset.

Example

sd_id = HDF_SDSTART('demo.hdf')	Initialize the SD interface.

refno = 66	Define the reference number for which we want to search.

index = HDF_SD_REFTOINDEX(sd_id, refno)
Return the index number.

sds_id = HDF_SD_SELECT(sd_id, index)
Now the dataset can be accessed.

HDF_SD_ENDACCESS,SDS_ID	End access.

HDF_SD_END, sd_id

See Also

HDF_SD_IDTOREF, HDF_SD_NAMETOREF


HDF_SD_SELECT

The HDF_SD_SELECT function returns an SD dataset ID given the current SD interface ID, and the zero-based SD dataset index.

HDF_SD_FILEINFO can be used to determine the number of SD datasets in an HDF file, HDF_SD_REFTOINDEX can be used to find the index from its SD dataset ID, and HDF_SD_NAMETOINDEX can be used to find the index from its name.

Calling Sequence

Result = HDF_SD_SELECT(SD_ID, Number)

Arguments

SD_ID

A SD interface ID as returned from HDF _SD_START.

Number

A zero-based SD dataset index.

Example

sd_id = HDF_SD_START('test.hdf')	Open an HDF file.

sds_id_1=HDF_SD_SELECT(sd_id, 0)	Access the first SD in the HDF file.

HDF_SD_ENDACCESS, sds_id_1	End access to any SD ids.

HDF_SD_END, sd_id	Close the file.

See Also

HDF_SD_CREATE, HDF_SD_END, HDF_SD_ENDACCESS, HDF_SD_NAMETOINDEX, HDF_SD_REFTOINDEX, HDF_SD_SELECT, HDF_SD_START


HDF_SD_SETEXTFILE

The HDF_SD_SETEXTFILE procedure moves data values from a dataset into an external file. Only the data is moved, all other information remains in the original file. This routine can only be used with HDF version 3.3 files, not on older HDF files or NetCDF files. Data can only be moved once, and the user must keep track of the external file(s). The OFFSET keyword allows writing to an arbitrary location in the external file.

As shown in the example, when adding data to an external file SD, you must first use HDF_SD_ENDACCESS to sync the file, then reacquire the SDS ID with HDF_SD_SELECT before using HDF_SD_SETEXTFILE.

Calling Sequence

HDF_SD_SETEXTFILE, SDS_ID, Filename

Arguments

SDS_ID

An SD dataset ID as returned by HDF_SD_SELECT.

Filename

The name of the external file to be written.

Keywords

OFFSET

Set this keyword to a number of bytes from the beginning of the external file at which data writing should begin. Exercise extreme caution when using this keyword with existing files.

Example

sd_id = HDF_SD_START('ext_main.hdf', /CREATE)
Create an HDF file.

sds_id = HDF_SD_CREATE(sd_id, 'float_findgen', [3,5], /FLOAT)
Add an SD.

HDF_SD_ADDDATA, sds_id, FINDGEN(3,5)
Put some data into the SD.

HDF_SD_ENDACCESS,sds_id	Call HDF_SD_ENDACCESS to sync the file.

sds_id = HDF_SD_SELECT(sd_id, 0)	Reacquire the SDS_ID.

HDF_SD_SETEXTFILE, sds_id, 'findgen.hdf'
Move data to an external file named findgen.hdf.

HDF_SD_GETDATA, sds_id, fout	Retrieve data from the external file into the variable fout.

PRINT, fout	Print the contents of fout. As we would expect, IDL prints:
0.00000 1.00000 2.00000
3.00000 4.00000 5.00000
6.00000 7.00000 8.00000
9.00000 10.0000 11.0000
12.0000 13.0000 14.0000

HDF_SD_ENDACCESS, sds_id	Sync and close the files.

HDF_SD_END, sd_id

See Also

HDF_SD_END, HDF_SD_ENDACCESS, HDF_SD_SELECT, HDF_SD_START


HDF_SD_SETINFO

The HDF_SD_SETINFO procedure sets information about an SD dataset.

Caution:  Setting a label, unit, format, or coordinate system string that has more than 256 characters can have unpredictable results.

Calling Sequence

HDF_SD_SETINFO, SDS_ID

Arguments

SDS_ID

An SD dataset ID as returned by HDF_SD _SELECT or HDF_SD_CREATE.

Keywords

FILL

Set this keyword to the fill value of the SD dataset.

FORMAT

Set this keyword to a string to be used as the SD dataset format.

LABEL

Set this keyword to a string to be used as the SD dataset label.

RANGE

Set this keyword to a two dimensional array that contains the minimum and maximum values of the SD dataset.

UNIT

Set this keyword to a string to be used as the SD dataset units.

COORDSYS

Set this keyword to a string to be used as the SD dataset coordinate system.

CALDATA

Set this keyword to a structure that contains the calibration data. This structure must contain five tags as shown below. The first four tags are of double-precision floating-point type. The fifth tag should be a long integer that specifies the HDF number type. The structure should have the following form:

CALDATA={ Cal: 0.0D $	Calibration Factor

      Cal_Err: 0.0D $	Calibration Error

       Offset: 0.0D $	Uncalibrated Offset

       Offset_Err: 0.0D $	Uncalibrated Offset Error

       Num_Type: 0L }	Number Type of Uncalibrated Data

The relationship between HDF and IDL number types is illustrated by the following table:

HDF Number Type	IDL Data Type
3L	STRING
21L	BYTE
22L	INTEGER
24L	LONG INTEGER
5L	FLOATING-POINT
6L	DOUBLE-PRECISION
Table 1.7 Relationship Between HDF and IDL Number Types

The relationship between the calibrated data (CD) and the uncalibrated data (CD) is given by the equation:

CD = Cal * (UD - Offset)	Cal and Offset are the values of the Cal and Offset structure fields described above.

Example

sd_id = HDF_SD_START('demo.hdf', /RDWR)
Open an HDF file.

sds_id = HDF_SD_CREATE(sd_id, 'variable1', [10, 20], /DOUBLE)
Define a new dataset for the file.

CAL={Cal:1.0D, Cal_Err:0.1D, Offset:2.5D, Offset_Err:0.1D, $

     Num_Type:6L}	Create a calibration data structure.

HDF_SD_SETINFO, sds_id, LABEL='label1', unit='unit1', $

                format='format1', coordsys='coord1', $

                FILL=999.991, RANGE=[99.99,-78], caldata=CAL
Set information about the dataset.

HDF_SD_GETINFO, sds_id, LABEL=l, UNIT=u, FORMAT=f, $

                COORDSYS=c, FILL=fill, RANGE=r, CALDATA=cd, $

                NDIMS=ndims, DIMS=dims, TYPE=ty
Retrieve the information.

HELP, l, u, f, c, fill, r, cd, ndims, dims, ty
Print information about the returned variables. IDL prints:
L STRING = `label1'
U STRING = `unit1'
F STRING = `format1'
C STRING = `coord1'
FILL DOUBLE = 999.99103
R DOUBLE = Array(2)
CD STRUCT = -> < Anonymous > Array(1)
NDIMS LONG = 2
DIMS LONG = Array(2)
TY STRING = `DOUBLE'

PRINT, r	Print the range. IDL prints:
-78.000000 99.989998

PRINT, cd	Print the calibration data. IDL prints:
{ 1.0000000 0.10000000 2.5000000 0.10000000 6}

PRINT, dims	Print the dimensions. IDL prints:
10 20

HDF_SD_ENDACCESS, sds_id	Close the SD interface.

HDF_SD_END, sd_id

See Also

HDF_SD_END, HDF_SD_ENDACCESS, HDF_SD_GETINFO, HDF_SD_START


HDF_SD_START

The HDF_SD_START function opens or creates an HDF file and initializes the SD interface. The returned value of this function is the SD ID of the HDF file. If no keywords are present, the file is opened in read-only mode.

Note that every file opened with HDF_SD_START should eventually be closed with a call to HDF_SD_END.

Calling Sequence

Result = HDF_SD_START(Filename)

Arguments

Filename

A scalar string containing the name of the file to be opened or created. HDF_SD_START can open the following file types: XDR-based NetCDF files, "old-style" DFSD files, or "new-style" SD files. New files are created as "new-style" SD files.

Keywords

READ

Set this keyword to open the SD interface in read-only mode. If no keywords are specified, this is the default behavior.

RDWR

Set this keyword to open the SD interface in read and write mode. Setting this keyword is the same as setting the ALL keyword.

CREATE

Set this keyword to create a new SD file.

Example

sd_id = HDF_SD_START('test.hdf', /CREATE)
Open a new HDF file. The file is ready to be accessed.

HDF_SD_END, sd_id	When finished with the file, close it with a call to HDF_SD_END.

For a more complicated example, see the documentation for HDF_SD_ATTRSET.

See Also

HDF_CLOSE, HDF_OPEN, HDF_SD_ATTRFIND, HDF_SD_ATTRINFO, HDF_SD_ATTRSET, HDF_SD_CREATE, HDF_SD_END, HDF_SD_FILEINFO, HDF_SD_NAMETOINDEX, HDF_SD_REFTOINDEX, HDF_SD_SELECT, HDF_SD_SETEXTFILE


HDF_VD_ATTACH

The HDF_VD_ATTACH function accesses a VData with the given Id in a Hierarchical Data Format file. If successful, a handle for that VData is returned, otherwise 0 is returned.

If VDataId is set to -1, a new VData is created. If neither the READ nor WRITE keyword is specified, the VData is opened for reading.

Calling Sequence

Result = HDF_VD_ATTACH(Filehandle, VDataId)

Arguments

Filehandle

The HDF file handle returned from a previous call to HDF_OPEN.

VDataId

The VData reference number, usually obtained by HDF_VD_GETID or HDF_VD_LONE. Set this argument to -1 to create a new VData.

Keywords

READ

Set this keyword to open the VData for reading.

WRITE

Set this keyword to open the VData for writing.


HDF_VD_DETACH

The HDF_VD_DETACH procedure is called when done accessing a VData in a Hierarchical Data Format file. This routine must be called for every VData attached for writing before closing the HDF file to insure that VSET information is properly updated.

Calling Sequence

HDF_VD_DETACH, VData

Arguments

VData

The VData handle returned by a previous call to HDF_VD_ATTACH.


HDF_VD_FDEFINE

The HDF_VD_FDEFINE procedure adds a new field specification for a VData in a Hierarchical Data Format file. HDF_VD_FDEFINE can only be used for a new VData.

Calling Sequence

HDF_VD_FDEFINE, VData, Fieldname

Arguments

VData

The VData handle returned by a previous call to HDF_VD_ATTACH.

Fieldname

A string containing the new field name.

Keywords

BYTE

Set this keyword to indicate that the field will contain 8-bit unsigned integer data.

DOUBLE

Set this keyword to indicate that the field will contain 64-bit floating point data.

FLOAT

Set this keyword to indicate that the field will contain 32-bit floating point data.

INT

Set this keyword to indicate that the field will contain 16-bit integer data.

LONG

Set this keyword to indicate that the field will contain 32-bit integer data.

ORDER

This keyword specifies the number of distinct components in the new field. Compound variables have an order greater than 1. The default order is 1.

Example

HDF_VD_FDEFINE, vid, 'VEL', /DOUBLE, ORDER=3


HDF_VD_FEXIST

The HDF_VD_FEXIST function returns true if all the fields specified in Fieldname exist in the specified Hierarchical Data Format file.

Calling Sequence

Result = HDF_VD_FEXIST(VData, Fieldnames)

Arguments

VData

The VData handle returned by a previous call to HDF_VD_ATTACH.

Fieldnames

A string containing a comma-separated list of fields to test. For example 'VEL' or 'PZ,PY,PX'.


HDF_VD_FIND

The HDF_VD_FIND function returns the reference number of a VData with the specified name in a Hierarchical Data Format file. A 0 is returned if an error occurs or a VData of the given name does not exist.

Calling Sequence

Result = HDF_VD_FIND(Filehandle, Name)

Arguments

Filehandle

The HDF file handle returned from a previous call to HDF_OPEN.

Name

A string containing the name of the VData to be found.


HDF_VD_GET

The HDF_VD_GET procedure is a general VData inquiry routine. Set the various keywords to named variables to return information about a VData in a Hierarchical Data Format file.

Calling Sequence

HDF_VD_GET, VData

Arguments

VData

A VData handle returned by HDF_VD_ATTACH.

Keywords

CLASS

Set this keyword to a named variable in which the class name of the VData is returned as a string.

COUNT

Set this keyword to a named variable in which a long, containing the number of records in the VData, is returned.

FIELDS

Set this keyword to a named variable in which a comma-separated string of fields in the VData is returned (e.g., 'PX,PY,PZ')

INTERLACE

Set this keyword to a named variable in which a string, containing either 'FULL_INTERLACE' or 'NO_INTERLACE', is returned.

NAME

Set this keyword to a named variable in which a string, containing the name of the VData, is returned.

NFIELDS

Set this keyword to a named variable in which a long, containing the number of fields in the VDATA, is returned. For example, the VData containing the fields "PX,PY,PZ", has an NFIELDS of 3.

REF

Set this keyword to a named variable in which the reference number of the VData is returned.

SIZE

Set this keyword to a named variable in which a long, containing the local size of a record of VData, is returned.

TAG

Set this keyword to a named variable in which the tag number of the VData is returned.

Example

HDF_VD_GET, vdat, CLASS=c, COUNT=co, FIELDS=f, NAME=n, SIZE=s

See Also

HDF_VD_GETINFO, HDF_VG_GETINFO


HDF_VD_GETID

The HDF_VD_GETID function returns the VData reference number for the next VData in a Hierarchical Data Format file after the specified VDataId.

Set VDataId to -1 to return the first VData ID in the file.

Calling Sequence

Result = HDF_VD_GETID(Filehandle, VDataId)

Arguments

Filehandle

The HDF file handle returned by a previous call to HDF_OPEN.

VDataID

The VData reference number, generally obtained by HDF_VD_GETID or HDF_VD_LONE. Set this argument to -1 to return the first VData in the file.


HDF_VD_GETINFO

The HDF_VD_GETINFO procedure is a general VData inquiry routine. Set the various keywords to named variables to return information about each field of a VData in a Hierarchical Data Format file.

Calling Sequence

HDF_VD_GETINFO, VData, Index

Arguments

VData

The VData handle returned by a previous call to HDF_VD_ATTACH.

Index

A zero-based index specifying which field or the name of the field within the VData to inquire about. For example:

HDF_VD_GETINFO, Vdat, 'VEL', ORDER=order

Keywords

NAME

Set this keyword to a named variable in which the name of the field is returned as a string.

ORDER

Set this keyword to a named variable in which the order of the field is returned.

SIZE

Set this keyword to a named variable in which the size of a data value for the specified field in the VData is returned.

TYPE

Set this keyword to a named variable in which the type of the field is returned. One of the following strings is returned: 'BYTE', 'INT', 'LONG', 'FLOAT', 'DOUBLE'.

Example

HDF_VD_GET,Vdat,NFIELDS=n

FOR index=0,n-1 DO BEGIN

HDF_VD_GETINFO,Vdat,i,NAME=n,TYPE=t,ORDER=o

PRINT,i,':',n,'TYPE=',t,'ORDER=',o

ENDFOR


HDF_VD_GETNEXT

The HDF_VD_GETNEXT function returns the reference number of the next object inside a VData in a Hierarchical Data Format file. If Id is -1, the first item in the VData is returned, otherwise Id should be set to a reference number previously returned by HDF_VD_GETNEXT. HDF_VD_GETNEXT returns -1 if there was an error or there are no more objects after the one specified by  Id.

Calling Sequence

Result = HDF_VD_GETNEXT(VData, Id)

Arguments

VData

The VData handle returned by a previous call to HDF_VD_ATTACH.

Id

A VGroup or VData reference number obtained by a previous call to HDF_VG_GETNEXT or HDF_VD_GETNEXT. Alternatively, this value can be set to -1 to return the first item in the VData.


HDF_VD_INSERT

The HDF_VD_INSERT procedure adds a VData or VGroup to the contents of a VGroup in a Hierarchical Data Format file.

Calling Sequence

HDF_VD_INSERT, VGroup, VData

Arguments

VGroup

The VGroup handle returned by a previous call to HDF_VG_ATTACH.

VData

The VData (or VGroup) handle returned by HDF_VD_ATTACH (HDF_VG_ATTACH).


HDF_VD_ISVD

The HDF_VD_ISVD function returns True (1) if the object associated with Id is a VData in a Hierarchical Data Format file.

Calling Sequence

Result = HDF_VD_ISVD(VGroup, Id)

Arguments

VGroup

The VGroup handle returned by a previous call to HDF_VG_ATTACH.

Id

The VGroup or VData reference number obtained by a previous call to HDF_VG_GETNEXT or HDF_VD_GETNEXT.

Example

Vid = HDF_VD_GETNEXT(Vgrp, -1)

PRINT, HDF_VD_ISVD(VGrp, Vid)


HDF_VD_ISVG

The HDF_VD_ISVG function returns True (1) if the object associated with Id is a VGroup in a Hierarchical Data Format file.

Calling Sequence

Result = HDF_VG_ISVG(VGroup, Id)

Arguments

VGroup

The VGroup handle returned by a previous call to HDF_VG_ATTACH.

Id

The VGroup or VData reference number obtained by a previous call to HDF_VG_GETNEXT.

Example

Vid = HDF_VD_GETNEXT(Vgrp, -1)

PRINT, HDF_VD_ISVG(VGrp, Vid)


HDF_VD_LONE

The HDF_VD_LONE function returns an array containing all VDatas in a Hierarchical Data Format file that are not contained in another VData. If there are no lone VDatas, HDF_VD_LONE returns -1.

Calling Sequence

Result = HDF_VD_LONE(Filehandle)

Arguments

Filehandle

The HDF file handle returned from a previous call to HDF_OPEN.

Keywords

MAXSIZE

The maximum number of groups to be returned (the default is to return all known lone VDatas). For example, to return only the first 12 groups:

X = HDF_VD_LONE(fid, MAX=12)

Example

X = HDF_VD_LONE(fid)

IF N_ELEMENTS(X) EQ 0 THEN $

PRINT, 'No Lone VDatas' ELSE PRINT, 'Lone VDatas:', X


HDF_VD_READ

The HDF_VD_READ function reads data from a VData in a Hierarchical Data Format file. This function returns the number of records successfully read from the VData.

The default is to use FULL_INTERLACE and to read all fields in all records. The user can override the defaults with keywords. If multiple fields with different data types are read, all of the data is read into a byte array. The data must then be explicitly converted back into the correct type(s) using various IDL type conversion routines. For example:

nread = HDF_VD_READ(vdat, x, NREC=1, FIELDS="FLT,LNG")

floatvalue = FLOAT(x, 0)

longvalue = LONG(x, 4)

Calling Sequence

Result = HDF_VD_READ(VData, Data)

Arguments

VData

The VData handle returned by a previous call to HDF_VD_ATTACH.

Data

A named variable in which the data is returned.

Keywords

FIELDS

A string containing a comma-separated list of fields to be read. Normally HDF_VD_READ will read all fields in the VData.

FULL_INTERLACE

Set this keyword to use full interlace when reading (the default).

NO_INTERLACE

Set this keyword to use no interlace when reading.

NRECORDS

The number of records to read. By default, HDF_VD_READ reads all records from a VData.

Examples

Typical read:

NREC = HDF_VD_READ(Vdat, X)

Read one field:

NREC = HDF_VD_READ(Vdat, X, FIELDS='VEL')

Read a record:

NREC = HDF_VD_READ(Vdat, X, NRECORDS=1)


HDF_VD_SEEK

The HDF_VD_SEEK procedure moves the read pointer within the specified VData in a Hierarchical Data Format file to a specific record number. Note that the record number is zero-based.

Calling Sequence

HDF_VD_SEEK, VData, Record

Arguments

VData

A VData handle returned by HDF_VD_ATTACH.

Record

The zero-based record number to seek.


HDF_VD_SETINFO

The HDF_VD_SETINFO procedure specifies general information about a VData in a Hierarchical Data Format file. Keywords can be used to establish the name, class, and interlace for the specified VData.

Calling Sequence

HDF_VD_SETINFO, VData

Arguments

VData

The VData handle returned by a previous call to HDF_VD_ATTACH.

Keywords

CLASS

A string that sets the class name for the VData.

FULL_INTERLACE

Set this keyword to store data in the file with full interlace (i.e., sequentially by record).

NAME

A string that sets the name of the VData.

NO_INTERLACE

Set this keyword to store data in the file with no interlace (i.e., sequentially by field).

Example

HDF_VD_SETINFO, Vdat, NAME='My Favorite Data', /FULL


HDF_VD_WRITE

The HDF_VD_WRITE procedure stores data in a VData in a Hierarchical Data Format file.

There are many restrictions on writing data to a VData. When writing multiple fields of varying types, only limited error checking is possible. When writing a series of fields all with the same type, data is converted to that type before writing. For example:

Vdat = HDF_VD_ATTACH(Fid, -1, /WRITE)

Data = INDGEN(10)	Create a 10 integer vector.

HDF_VD_WRITE, Vdat, 'PX', Data	Data converted to FLOAT before write.

It is possible to write less data than exists in Data by using the NRECORDS keyword. For example, the following command writes 5 records, instead of the 10 implied by the size of the data (VEL is assumed to be of type FLOAT, order=3):

HDF_VD_WRITE, Vdat, 'VEL', FINDGEN(3,10),NREC=5

VEL now contains [ [ 0.0, 1.0, 2.0 ], ..., [ 12.0, 13.0, 14.0] ]

HDF_VD_WRITE will not allow a user to specify more records than exist. For example, the following command fails:

HDF_VD_WRITE, Vdat, 'VEL', [1,2,3], NREC=1000

Bugs

Data can not be appended. Attempts to append data may make future attempts to read data fail. Data can not be overwritten.

Calling Sequence

HDF_VD_WRITE, VData, Fields, Data

Arguments

VData

The VData handle returned by a previous call to HDF_VD_ATTACH.

Fields

A string containing a comma-separated list of the fields to be written.

Data

The data to be written to the specified VData.

Keywords

FULL_INTERLACE

Set this keyword to use full interlace when writing (the default).

NO_INTERLACE

Set this keyword to use no interlace when writing.

NRECORDS

The number of records to written. By default, HDF_VD_WRITE writes all records from a VData.

Restrictions

It is not possible to write IDL structures directly to a VData (because of possible internal padding depending upon fields/machine architecture, etc.). The user must put the data into a byte array before using HDF_VD_WRITE.

When writing a series of fields all with the same type, the low order dimension of Data must match the sum of the orders of the fields. For example:

HDF_VD_WRITE, Vdat, 'PX,PY', FLTARR(3,10)

fails. PX and PY are both order 1 (total 2) and the array's low order dimension is 3.


HDF_VG_ADDTR

The HDF_VG_ADDTR procedure adds a tag and reference to the specified VGroup in a Hierarchical Data Format file.

Calling Sequence

HDF_VG_ADDTR, VGroup, Tag, Ref

Arguments

VGroup

The VGroup handle returned by a previous call to HDF_VG_ATTACH.

Tag

The tag to be written.

Ref

The reference number to be written.


HDF_VG_ATTACH

The HDF_VG_ATTACH procedure attaches (opens) a VGroup in a Hierarchical Data Format file for reading or writing. If successful, a handle for that group is returned. If it fails, 0 is returned.

If VGroupId is set to -1, a new VGroup is created. If neither the READ nor WRITE keywords are set, the VGroup is opened for reading.

Calling Sequence

Result = HDF_VG_ATTACH(Filehandle, VGroupId)

Arguments

Filehandle

The HDF file handle returned from a previous call to HDF_OPEN.

VGroupId

The VGroup reference number, generally obtained by HDF_VG_GETID or HDF_VG_LONE.

Keywords

READ

Set this keyword to open the VGroup for reading.

WRITE

Set this keyword to open the VGroup for writing.


HDF_VG_DETACH

The HDF_VG_DETACH procedure should be called when you are finished accessing a VGroup in a Hierarchical Data Format file. This routine must be called for every VGroup attached for writing before closing the HDF file in order to insure that VSET information is properly updated.

Calling Sequence

HDF_VG_DETACH, VGroup

Arguments

VGroup

The VGroup handle returned by a previous call to HDF_VG_ATTACH.


HDF_VG_GETID

The HDF_VG_GETID function returns the VGroup ID for the next VGroup after the specified VGroupId in a Hierarchical Data Format file. Use a VGroupId of -1 to get the first VGroup in the file.

Calling Sequence

Result = HDF_VG_GETID(Filehandle, VGroupId)

Arguments

Filehandle

The HDF file handle returned from a previous call to HDF_OPEN.

VGroupID

The VGroup reference number, generally obtained by HDF_VG_GETID or HDF_VG_LONE.


HDF_VG_GETINFO

The HDF_VG_GETINFO procedure is a general VGroup inquiry routine. Set the various keywords to named variables to return information about different aspects of a  VGroup in a Hierarchical Data Format file.

Calling Sequence

HDF_VG_GETINFO, VGroup

Arguments

VGroup

The VGroup handle returned by a previous call to HDF_VG_ATTACH.

Keywords

CLASS

Set this keyword to a named variable in which the class of the VGroup is returned as a string.

NAME

Set this keyword to a named variable in which the name of the VGroup is returned as a string.

NENTRIES

Set this keyword to a named variable in which the number of objects inside the VGroup is returned as a long integer.

Example

HDF_VG_GETINFO, Vgrp, CLASS=c, NAME=nm, NENTRIES=n

PRINT, c, nm, n


HDF_VG_GETNEXT

The HDF_VG_GETNEXT function returns the reference number of the next object inside a VGroup in a Hierarchical Data Format file. If Id is -1, the first item in the VGroup is returned, otherwise Id should be set to a reference number previously returned by HDF_VG_GETNEXT. HDF_VG_GETNEXT returns -1 if there was an error or there are no more objects after the one specified by  Id.

Calling Sequence

Result = HDF_VG_GETNEXT(VGroup, Id)

Arguments

VGroup

The VGroup handle returned by a previous call to HDF_VG_ATTACH.

Id

A VGroup or VData reference number obtained by a previous call to HDF_VG_GETNEXT. Alternatively, this value can be set to -1 to return the first item in the VGroup.


HDF_VG_GETTR

The HDF_VG_GETTR procedure returns the tag/reference pair at the specified position within a VGroup in a Hierarchical Data Format file.

Calling Sequence

HDF_VG_GETTR, VGroup, Index, Tags, Refs

Arguments

VGroup

The VGroup handle returned by a previous call to HDF_VG_ATTACH.

Index

The position within VGroup.

Tags

A named variable in which the tag numbers are returned.

Refs

A named variable in which the reference numbers are returned.


HDF_VG_GETTRS

The HDF_VG_GETTRS procedure returns the tag/reference pairs of the Hierarchical Data Format file objects belonging to the specified VGroup.

Calling Sequence

HDF_VG_GETTRS, VGroup, Tags, Refs

Arguments

VGroup

The VGroup handle returned by a previous call to HDF_VG_ATTACH.

Tags

A named variable in which the tag numbers are returned.

Refs

A named variable in which the reference numbers are returned.

Keywords

MAXSIZE

The maximum number of tags and references to be returned. The default is to return all tags and references in VGroup.


HDF_VG_INQTR

The HDF_VG_INQTR function returns true if the specified tag and reference pair is linked to the specified  VGroup in a Hierarchical Data Format file.

Calling Sequence

Result = HDF_VG_INQTR(VGroup, Tag, Ref)

Arguments

VGroup

The VGroup handle returned by a previous call to HDF_VG_ATTACH.

Tag

The tag number.

Ref

The reference number.


HDF_VG_INSERT

The HDF_VG_INSERT procedure adds a VData or VGroup to the contents of a VGroup in a Hierarchical Data Format file.

Calling Sequence

HDF_VG_INSERT, VGroup, VData

Arguments

VGroup

The VGroup handle returned by a previous call to HDF_VG_ATTACH.

VData

The VData (or VGroup) handle returned by HDF_VD_ATTACH (HDF_VG_ATTACH).


HDF_VG_ISVD

The HDF_VG_ISVD function returns true if the object associated with Id is a  VData in a Hierarchical Data Format file.

Calling Sequence

Result = HDF_VG_ISVD(VGroup, Id)

Arguments

VGroup

The VGroup handle returned by a previous call to HDF_VG_ATTACH.

Id

The VGroup or VData reference number obtained by a previous call to HDF_VG_GETNEXT.

Example

Vid = HDF_VG_GETNEXT(Vgrp, -1)

PRINT, HDF_VG_ISVD(VGrp, Vid)


HDF_VG_ISVG

The HDF_VG_ISVG function returns true if the object associated the Id is a VGroup in a Hierarchical Data Format file.

Calling Sequence

Result = HDF_VG_ISVG(VGroup, Id)

Arguments

VGroup

The VGroup handle returned by a previous call to HDF_VG_ATTACH.

Id

The VGroup or VData reference number obtained by a previous call to HDF_VG_GETNEXT.

Example

Vid = HDF_VG_GETNEXT(Vgrp, -1)

PRINT, HDF_VG_ISVG(VGrp, Vid)


HDF_VG_LONE

The HDF_VG_LONE function returns an array containing the IDs of all VGroups in a Hierarchical Data Format file that are not contained in another VGroup. If there are no lone VGroups, HDF_VG_LONE returns -1.

Calling Sequence

Result = HDF_VG_LONE(Filehandle)

Arguments

Filehandle

The HDF file handle returned by a previous call to HDF_OPEN.

Keywords

MAXSIZE

The maximum number of groups to return (the default is to return all lone VGroups). For example, to return no more than 12 VGroups, use the command:

X = HDF_VG_LONE(fid, MAX=12)

Example

X=HDF_VG_LONE(fid)

IF X(0) EQ-1 THEN $

   PRINT, "No Lone VGroups" ELSE PRINT, "Lone VGroups:", X


HDF_VG_NUMBER

The HDF_VG_NUMBER function returns the number of Hierarchical Data Format file objects in the specified  VGroup.

Calling Sequence

Result = HDF_VG_NUMBER(VGroup)

Arguments

VGroup

The VGroup handle returned by a previous call to HDF_VG_ATTACH.


HDF_VG_SETINFO

The HDF_VG_SETINFO procedure sets the name and class of a VGroup.

Calling Sequence

HDF_VG_SETINFO, VGroup

Arguments

VGroup

The VGroup handle as returned by HDF_VG _ATTACH.

Keywords

CLASSNAME

A string containing the class name for the VGroup.

NAME

A string containing the name for the VGroup.

Example

fid = HDF_OPEN('demo.hdf',/RDWR)	Open an HDF file.

vgid = HDF_VG_ATTACH(fid, -1, /WRITE)
Add a new VGroup.

HDF_VG_SETINFO, vgid, NAME='My Name', CLASS='My VGroup Class'
Set the name and class for the VGroup.

Now retrieve and show the information

HDF_VG_GETINFO, vgid, NAME=outname, CLASS=outclass
Retrieve the name and class information from the file.

HELP, outname, outclass	Print information about the returned variables. IDL prints:
OUTNAME STRING = 'My Name'
OUTCLASS STRING = 'My VGroup Class'

HDF_VG_DETACH, vgid	End VGroup access.

HDF_CLOSE, fid	Close the HDF file.

See Also

HDF_VG_GETINFO


HELP

The HELP procedure gives the user information on many aspects of the current IDL session. The specific area for which help is desired is selected by specifying the appropriate keyword. If no arguments or keywords are specified, the default is to show the current nesting of procedures and functions, all current variables at the current program level, and open files. Only one keyword can be specified at a time.

Calling Sequence

HELP,  Expression1, ..., Expressionn

Arguments

Expressioni

The arguments are interpreted differently depending on the keyword selected. If no keyword is selected, HELP displays basic information for its parameters. For example, to see the type and structure of the variable A, enter:

HELP, A

Keywords

Note that the use of some of the following keywords causes any arguments to HELP to be ignored and HELP provides other types of information instead. If the description of the keyword does not explicitly mention the arguments, the arguments are ignored.

ALL_KEYS

Set this keyword to show current function-key definitions as set by DEFINE_KEY. If no arguments are supplied, information on all function keys is displayed. If arguments are provided, they must be scalar strings containing the names of function keys, and information on the specified keys is given.

BREAKPOINTS

Set this keyword to display the breakpoint table which shows the program module and location for each breakpoint.

CALLS

Set this keyword to a named variable in which to store the procedure call stack. Each string element contains the name of the program module, source file name, and line number. Array element zero contains the information about the caller of HELP, element one contains information about its caller, etc. This keyword is useful for programs that require traceback information.

DEVICE

Set this keyword to show information about the currently selected graphics device.

FILES

Set this keyword to display information about file units. If no arguments are supplied in the call to HELP, information on all open file units (except the special units 0, -1, and -2) is displayed. If arguments are provided, they are taken to be integer file unit numbers, and information on the specified file units is given.

KEYS

Set this keyword to show current function key definitions as set by DEFINE_ KEY, for those function keys that are currently programmed to perform a function. Under Unix, this keyword is different from ALL_KEYS because that keyword displays every key, no matter what its current programming. Under VMS, the two keywords mean the same thing. If no arguments are supplied, information on all function keys is displayed. If arguments are provided, they must be scalar strings containing the names of function keys, and information on the specified keys is given.

 MEMORY

Set this keyword to see a report on the amount of dynamic memory currently in use by the IDL session, and the number of times dynamic memory has been allocated and deallocated.

NAMES

A string of the names of variables whose values are to be printed. This string, which must be enclosed in quotes, can contain the standard wildcard matching characters, "*" and "?". For example, to print only the values of variables beginning with "A", use the command HELP, NAME='a*'. Similarly, HELP, NAME='?', prints the values of all variables with a single-character name.

RECALL_COMMANDS

Set this keyword to display the saved commands in the command input buffer.

ROUTINES

Set this keyword to show a list of all compiled procedures and functions with their parameter names. Keyword parameters accepted by each module are shown enclosed in quotation marks.

SOURCE_FILES

Set this keyword to display information on procedures and functions written in the IDL language that have been compiled during the current IDL session. Full path names (relative to the current directory) of compiled .pro files are displayed.

STRUCTURES

Set this keyword to display information on structure-type variables. If no arguments are provided, all currently-defined structures are shown. If arguments are provided, the structure definition for those expressions is displayed.

SYSTEM_VARIABLES

Set this keyword to display information on all system variables. Arguments are ignored.

TRACEBACK

Set this keyword to display the current nesting of procedures and functions.

Example

To see general information on the current IDL session, enter:

HELP

To see information on the structure definition of the system variable !D, enter:

HELP, !D, /STRUCTURES

See Also

"Interactive Support" on page 13-1 of the IDL User's Guide.


HILBERT

The HILBERT function returns a series that has all periodic terms phase-shifted by 90 degrees. The output is a complex-valued vector with the same size as the input vector. This transform has the interesting property that the correlation between a series and its own Hilbert transform is mathematically zero.

HILBERT generates the fast Fourier transform using the FFT function, and shifts the first half of the transform products by +90 degrees and the second half by -90 degrees. The constant elements in the transform are not changed. Angle shifting is accomplished by multiplying or dividing by the complex number, i = (0.0000, 1.0000). The shifted vector is then submitted to FFT for transformation back to the "time" domain and the output is divided by the number elements in the vector to correct for multiplication effect peculiar to the FFT algorithm.

Note: Because HILBERT uses FFT, it exhibits the same side effects with respect to input arguments as that function.

This routine is written in the IDL language. Its source code can be found in the file hilbert.pro in the lib subdirectory of the IDL distribution.

Calling Sequence

Result = HILBERT(X [, D])

Arguments

X

An n-element floating-point or complex-valued vector.

D

A flag for rotation direction. Set D = +1 for a positive rotation (the default). Set D = -1 for a negative rotation.

See Also

FFT


HIST_2D

The HIST_2D function returns the two dimensional density function (histogram) of two variables, a longword array of dimensions (MAX(V1)+1, MAX(V2)+1). Result(i,j) is equal to the number of simultaneous occurrences of V1 = i and V2 = j at the specified element.

This routine is written in the IDL language. Its source code can be found in the file hist_2d.pro in the lib subdirectory of the IDL distribution.

Calling Sequence

Result = HIST_2D(V1, V2)

Arguments

V1, V2

Arrays containing the variables. V1 and V2 must be of byte, integer, or longword type, and must contain no negative elements.

Example

Return the 2D histogram of two byte images:

R = HIST_2D(image1, image2)

Return the 2D histogram made from two floating point images with range of -1 to +1, and with 100 bins:

R = HIST_2D(LONG((F1+1) * 50), LONG((F2+1) * 50))

See Also

H_EQ_CT, H_EQ_INT, HIST_EQUAL, HISTOGRAM


HIST_EQUAL

The HIST_EQUAL function returns a histogram-equalized byte array. The HISTOGRAM function is used to obtain the density distribution of the input array. The histogram is integrated to obtain the cumulative density-probability function and finally the lookup function is used to transform to the output image.

The resulting array is always of byte type and is scaled from 0 to the value set by the TOP keyword.

Note: Floating-point arrays should not have small ranges, (e.g., less than around 255) unless a binsize is specified.

This routine is written in the IDL language. Its source code can be found in the file hist_equal.pro in the lib subdirectory of the IDL distribution.

Calling Sequence

Result = HIST_EQUAL(A)

Arguments

A

The array to be histogram-equalized.

Keywords

MINV

The minimum value to consider. If this keyword is omitted, zero is used. Input elements less than or equal to MINV are output as zero. MINV should be greater than or equal to 0.

MAXV

The maximum value to consider. If this keyword is omitted, the maximum element is used. Input elements greater than or equal to MAXV are output as 255.

BINSIZE

Size of bin to use. If this keyword is omitted, the value 1 is used. This parameter is ignored for byte type data.

TOP

The maximum value to scale the output array. If this keyword is omitted, 255 is used.

Example

Create a sample image using the DIST function and display it by entering:

image = DIST(100)

TV, image

Create a histogram-equalized version of the byte array, image, and display the new version. Use a minimum input value of 10, a maximum input value of 200, and limit the top value of the output array to 220. Enter:

new = HIST_EQUAL(image, MINV = 10, MAXV = 200, TOP = 220)

TV, new

See Also

H_EQ_CT, H_EQ_INT, HIST_2D, HISTOGRAM


HISTOGRAM

The HISTOGRAM function returns a longword vector equal to the density function of Array. In the simplest case, the density function, at subscript i, is the number of Array elements in the argument with a value of i.

Let Fi = the value of element i, 0 ≤ i < n. Let Hv = result of histogram function, a longword vector. The definition of the histogram function becomes:

Warning: There may not always be enough virtual memory available to find the density functions of arrays that contain a large number of bins.

For bivariate probability distributions, use the HIST_2D function.

HISTOGRAM can optionally return an array containing a list of the original array subscripts that contributed to each histogram bin. This list, commonly called the reverse (or backwards) index list, efficiently determines which array elements are accumulated in a set of histogram bins. A typical application of the reverse index list is reverse histogram or scatter plot interrogation—a histogram bin or 2D scatter plot location is marked with the cursor and the original data items within that bin are highlighted.

Calling Sequence

Result = HISTOGRAM(Array)

Arguments

Array

The vector or array for which the density function is to be computed.

Keywords

BINSIZE

The size of the bin to use. If this keyword is not specified, a bin size of 1 is used.

INPUT

Set this keyword to a named variable that contains an array to be added to the output of HISTOGRAM. The density function of Array is added to the existing contents of INPUT and returned as the result. The array is converted to longword type if necessary and must have at least as many elements as are required to form the histogram.

Multiple histograms can be efficiently accumulated by specifying partial sums via this keyword.

MAX

MAX is the maximum value to consider. If this keyword is not specified, Array  is searched for its largest value.

MIN

MIN is the minimum value to consider. If this keyword is not specified, and Array is of type byte, 0 is used. If this keyword is not specified and  Array is not of byte type, Array is searched for its smallest value.

NAN

Set this keyword to cause the routine to check for occurrences of the IEEE floating-point value NaN in the input data. Elements with the value NaN are treated as missing data. (See  "Special Floating-Point Values" on page 11-9 of the IDL User's Guide for more information on IEEE floating-point values.)

OMAX

A named variable that, upon exit, contains the maximum data value used in constructing the histogram.

OMIN

A named variable that, upon exit, contains the minimum data value used in constructing the histogram.

REVERSE_INDICES

Set this keyword to a named variable in which the list of reverse indices is returned. This list is returned as a longword vector whose number of elements is the sum of the number of elements in the histogram, N, and the number of array elements included in the histogram, plus one.

The subscripts of the original array elements falling in the ith bin, 0 ≤ i < N, are given by the expression: R(R(i) : R(i+1)-1), where R is the reverse index list. If R(i) is equal to R(i+1), no elements are present in the ith bin.

For example, make a take the histogram of array A:

H = HISTOGRAM(A, REVERSE_INDICES = R)

Set all elements of A that are in the ith bin of H to 0 with the command:

IF R(i) NE R(i+1) THEN A(R(R(I) : R(i+1)-1)) = 0

which is usually more efficient than the commands:

bini = WHERE(A EQ i, count)

IF count NE 0 THEN A(bini) = 0

Examples

Create a simple, two-dimensional dataset with the DIST function by entering:

D = DIST(200)

Plot the histogram of D with a bin size of 1 and the default minimum and maximum by entering:

PLOT, HISTOGRAM(D)

To plot a histogram considering only those values from 10 to 50 using a bin size of 4, enter:

PLOT, HISTOGRAM(D, MIN = 10, MAX = 50, BINSIZE = 4)

The HISTOGRAM function can also be used to increment the elements of one vector whose subscripts are contained in another vector. To increment those elements of vector A indicated by vector B, use the command:

A = HISTOGRAM(B, INPUT=A, MIN=0, MAX=N_ELEMENTS(A)-1)

This method works for duplicate subscripts, whereas the statement:

A(B) = A(B)+1

adds never adds more than 1 to any element, even if that element is duplicated in vector B. For example, the following commands:

A = LONARR(5)

B = [2,2,3]

PRINT, HISTOGRAM(B, INPUT=A, MIN=0, MAX=4)

prints:

   0  0  2  1  0

while the commands:

A = LONARR(5)

A(B) = A(B)+1

PRINT, A

gives the result:

   0  0  1  1  0

See Also

H_EQ_CT, H_EQ_INT, HIST_2D, HIST_EQUAL


HLS

The HLS procedure creates a color table based on the HLS (Hue, Lightness, Saturation) color system.

Using the input parameters, a spiral through the double-ended HLS cone is traced. Points along the cone are converted from HLS to RGB. The current colortable (and the COLORS common block) contains the new colortable on exit.

This routine is written in the IDL language. Its source code can be found in the file hls.pro in the lib subdirectory of the IDL distribution.

Calling Sequence

HLS, Litlo, Lithi, Satlo, Sathi, Hue, Loops [, Colr]

Arguments

Litlo

Starting lightness, from 0 to 100%.

Lithi

Ending lightness, from 0 to 100%.

Satlo

Starting saturation, from 0 to 100%.

Sathi

Ending saturation, from 0 to 100%.

Hue

Starting Hue, from 0 to 360 degrees. Red = 0 degs, green = 120, blue = 240.

Loops

The number of loops through the color spiral. This parameter does not have to be an integer. A negative value causes the loops to traverse the spiral in the opposite direction.

Colr

An optional (256,3) integer array in which the new R, G, and B values are returned. Red = Colr(*,0), green = Colr(*,1), blue = Colr(*,2).

See Also

COLOR_CONVERT, HSV, PSEUDO


HQR

The HQR function returns all eigenvalues of an upper Hessenberg array. Using the output produced by the ELMHES function, this function finds all eigenvalues of the original real, nonsymmetric array. The result is an n-element complex vector.

HQR is based on the routine hqr described in section 11.6 of Numerical Recipes in C: The Art of Scientific Computing (Second Edition), published by Cambridge University Press, and is used by permission.

Calling Sequence

Result = HQR(A)

Arguments

A

An n by n upper Hessenberg array. Typically, A would be an array resulting from an application of ELMHES.

Keywords

DOUBLE

Set this keyword to force the computation to be done in double-precision arithmetic.

COLUMN

Set this keyword if the input array A is in column-major format (composed of column vectors) rather than in row-major format (composed of row vectors).

Example

To compute the eigenvalues of a real, non-symmetric unbalanced array, first define the array A:

A = [[ 1.0, 2.0, 0.0, 0.0, 0.0], $

     [-2.0, 3.0, 0.0, 0.0, 0.0], $

     [ 3.0, 4.0, 50.0, 0.0, 0.0], $

     [-4.0, 5.0, -60.0, 7.0, 0.0], $

     [-5.0, 6.0, -70.0, 8.0, -9.0]]

hes = ELMHES(A)	Compute the upper Hessenberg form of the array.

evals = HQR(hes)	Compute the eigenvalues.

Sort the eigenvalues into ascending order based on their real components:

evals = evals(SORT(FLOAT(evals)))

PRINT, evals	Print the result.

IDL prints:

  ( -9.00000, 0.00000)( 2.00000, -1.73205)

  (  2.00000, 1.73205)( 7.00000,  0.00000)

  ( 50.0000,  0.00000)

This is the exact solution vector to five-decimal accuracy.

See Also

EIGENVEC, ELMHES, TRIQL, TRIRED


HSV

The HSV procedure creates a color table based on the HSV (Hue, Saturation, and Value) color system.

Using the input parameters, a spiral through the single-ended HSV cone is traced. Points along the cone are converted from HLS to RGB. The current colortable (and the COLORS common block) contains the new colortable on exit.

This routine is written in the IDL language. Its source code can be found in the file hsv.pro in the lib subdirectory of the IDL distribution.

Calling Sequence

HLS, Vlo, Vhi, Satlo, Sathi, Hue, Loops [, Colr]

Arguments

Vlo

Starting value, from 0 to 100%.

Vhi

Ending value, from 0 to 100%.

Satlo

Starting saturation, from 0 to 100%.

Sathi

Ending saturation, from 0 to 100%.

Hue

Starting Hue, from 0 to 360 degrees. Red = 0 degs, green = 120, blue = 240.

Loops

The number of loops through the color spiral. This parameter does not have to be an integer. A negative value causes the loops to traverse the spiral in the opposite direction.

Colr

An optional (256,3) integer array in which the new R, G, and B values are returned. Red = Colr(*,0), green = Colr(*,1), blue = Colr(*,2).

See Also

COLOR_CONVERT, HLS, PSEUDO


IBETA

The IBETA function computes the incomplete beta function.

This routine is written in the IDL language. Its source code can be found in the file ibeta.pro in the lib subdirectory of the IDL distribution.

Calling Sequence

Result = IBETA(A, B, X)

Arguments

A

A positive integer, single-, or double-precision floating-point scalar that specifies the parametric exponent of the integrand.

B

A positive integer, single-, or double-precision floating-point scalar that specifies the parametric exponent of the integrand.

X

An integer, single-, or double-precision floating-point scalar, in the interval [0, 1], that specifies the upper limit of integration.

Example

Compute the incomplete beta function for the corresponding elements of A, B, and X.

Define an array of parametric exponents.

A = [0.5, 0.5, 1.0, 5.0, 10.0, 20.0]

B = [0.5, 0.5, 0.5, 5.0, 5.0, 10.0]

Define the upper limits of integration.

X = [0.01, 0.1, 0.1, 0.5, 1.0, 0.8]

Allocate an array to store the results.

result = FLTARR(N_ELEMENTS(A))

Compute the incomplete beta functions. Note that the result for each element in the input arrays must be computed individually.

FOR K = 0, N_ELEMENTS(A)-1 DO $

  result(K) = IBETA(A(K), B(K), X(K))

PRINT, result

IDL prints:

[0.0637686, 0.204833, 0.0513167, 0.500000, 1.00000, 0.950736]

See Also

BETA, GAMMA,  IGAMMA, LNGAMMA


IGAMMA

The IGAMMA function computes the incomplete gamma function.

IGAMMA uses either a power series representation or a continued fractions method. If X is less than or equal to A+1, a power series representation is used. If X is greater than A+1, a continued fractions method is used.

This routine is written in the IDL language. Its source code can be found in the file igamma.pro in the lib subdirectory of the IDL distribution.

Calling Sequence

Result = IGAMMA(A, X)

Arguments

A

A positive integer, single-, or double-precision floating-point scalar that specifies the parametric exponent of the integrand.

X

An integer, single-, or double-precision floating-point scalar that specifies the upper limit of integration.

Keywords

METHOD

Set this keyword to a named variable that will contain the method used to compute the incomplete gamma function. A value of 0 indicates that a power series representation was used. A value of 1 indicates that a continued fractions method was used.

Example

Compute the incomplete gamma function for the corresponding elements of A and X.

Define an array of parametric exponents.

A = [0.10, 0.50, 1.00, 1.10, 6.00, 26.00]

Define the upper limits of integration.

X = [0.0316228, 0.0707107, 5.00000, 1.04881, 2.44949, 25.4951]

Allocate an array to store the results.

result = FLTARR(N_ELEMENTS(A))

Compute the incomplete gamma functions. Note that the result for each element in the input arrays must be computed individually.

FOR K = 0, N_ELEMENTS(A)-1 DO $

result(K) = IGAMMA(A(K), X(K))

PRINT, result

IDL prints:

[0.742026, 0.293128, 0.993262, 0.607646, 0.0387318, 0.486387]

See Also

BETA, GAMMA,  IBETA, LNGAMMA


IMAGE_CONT

The IMAGE_CONT procedure overlays an image with a contour plot.

This routine is written in the IDL language. Its source code can be found in the file image_cont.pro in the lib subdirectory of the IDL distribution.

Calling Sequence

IMAGE_CONT, A

Arguments

A

The two-dimensional array to display and overlay.

Keywords

ASPECT

Set this keyword to retain the image's aspect ratio. Square pixels are assumed. If WINDOW_SCALE is set, the aspect ratio is automatically retained.

INTERP

If this keyword is set, bilinear interpolation is used if the image is resized.

WINDOW_SCALE

Set this keyword to scale the window size to the image size. Otherwise, the image size is scaled to the window size. This keyword is ignored when outputting to devices with scalable pixels (e.g., PostScript).

Example

A = BYTSCL(DIST(356))	Create an image to display.

IMAGE_CONT, A, /WINDOW	Display image and overplot contour lines.

See Also

CONTOUR, TV


IMAGINARY

The IMAGINARY function returns the imaginary part of its complex-valued argument. If the complex-valued argument is double-precision, the result will be double-precision, otherwise the result will be single-precision floating-point.

Calling Sequence

Result = IMAGINARY(Complex_Expression)

Arguments

Complex_Expression

The complex-valued expression for which the imaginary part is desired.

Example

Create an array of complex values by entering:

C = COMPLEX([1,2,3],[4,5,6])

Print just the imaginary parts of each element in C by entering:

PRINT, IMAGINARY(C)

IDL prints:

 4.00000 5.00000 6.00000

See Also

COMPLEX, DCOMPLEX


INDGEN

The INDGEN function returns an integer array with the specified dimensions. Each element of the array is set to the value of its one-dimensional subscript.

Calling Sequence

Result = INDGEN(D1, ..., Dn)

Arguments

Di

The dimensions of the result. The dimension parameters can be any scalar expression. Up to eight dimensions can be specified.

Example

Create I, a 5-element vector of integer values with each element set to the value of its subscript by entering:

I = INDGEN(5)

See Also

BINDGEN, CINDGEN, DCINDGEN, DINDGEN, FINDGEN, LINDGEN, SINDGEN


INT_2D

The INT_2D function computes the double integral of a bivariate function using iterated Gaussian quadrature. The algorithm's transformation data is provided in tabulated form with 15 decimal accuracy.

This routine is written in the IDL language. Its source code can be found in the file int_2d.pro in the lib subdirectory of the IDL distribution.

Calling Sequence

Result = INT_2D(Fxy, AB_Limits, PQ_Limits, Pts)

Arguments

Fxy

A scalar string specifying the name of a user-supplied IDL function that defines the bivariate function to be integrated. The function must accept X and Y and return a scalar result.

For example, if we wish to integrate the following function:

We define a function FXY to express this relationship in the IDL language:

FUNCTION fxy, X, Y

  RETURN, EXP(-X^2. -Y^2.)

END

AB_Limits

A two-element vector containing the lower (A) and upper (B) limits of integration with respect to the variable x.

PQ_Limits

A scalar string specifying the name of a user-supplied IDL function that defines the lower (P(x)) and upper (Q(x)) limits of integration with respect to the variable y. The function must accept x and return a two-element vector result.

For example, we might write the following IDL function to represent the limits of integration with respect to y:

FUNCTION PQ_limits, X

  RETURN, [-SQRT(16.0 - X^2), SQRT(16.0 - X^2)]

END

Pts

The number of transformation points used in the computation. Possible values are: 6, 10, 20, 48, or 96.

Keywords

DOUBLE

Set this keyword to force the computation to be done in double-precision arithmetic.

Example

Compute the double integral of the bivariate function

Using the function and limits defined above, integrate with 10, 20, 48, and 96 point formulas (using double-precision arithmetic):

PRINT, INT_2D('Fxy', [-4.0, 4.0], 'PQ_Limits', 10, /DOUBLE)

PRINT, INT_2D('Fxy', [-4.0, 4.0], 'PQ_Limits', 20, /DOUBLE)

PRINT, INT_2D('Fxy', [-4.0, 4.0], 'PQ_Limits', 48, /DOUBLE)

PRINT, INT_2D('Fxy', [-4.0, 4.0], 'PQ_Limits', 96, /DOUBLE)

INT_2D with 10 transformation points yields:	3.1208432

INT_2D with 20 transformation points yields:	3.1415923

INT_2D with 48 transformation points yields: 	3.1415923

INT_2D with 96transformation points yields: 	3.1415923

The exact solution (7 decimal accuracy) is:	3.1415923

See Also

INT_3D, INT_TABULATED, QROMB, QROMO, QSIMP


INT_3D

The INT_3D function computes the triple integral of a trivariate function using iterated Gaussian quadrature. The algorithm's transformation data is provided in tabulated form with 15 decimal accuracy.

This routine is written in the IDL language. Its source code can be found in the file int_3d.pro in the lib subdirectory of the IDL distribution.

Calling Sequence

Result = INT_3D(Fxyz, AB_Limits, PQ_Limits, UV_Limits, Pts)

Arguments

Fxyz

A scalar string specifying the name of a user-supplied IDL function that defines the trivariate function to be integrated. The function must accept X, Y, and Z, and return a scalar result.

For example, if we wish to integrate the following function:

We define a function FXY to express this relationship in the IDL language:

FUNCTION fxyz, X, Y, Z

  RETURN, z*(x^2+y^2+z^2)^1.5

END

AB_Limits

A two-element vector containing the lower (A) and upper (B) limits of integration with respect to the variable x.

PQ_Limits

A scalar string specifying the name of a user-supplied IDL function that defines the lower (P(x)) and upper (Q(x)) limits of integration with respect to the variable y. The function must accept x and return a two-element vector result.

For example, we might write the following IDL function to represent the limits of integration with respect to y:

FUNCTION PQ_limits, X

  RETURN, [-SQRT(4.0 - X^2), SQRT(4.0 - X^2)]

END

UV_Limits

A scalar string specifying the name of a user-supplied IDL function that defines the lower (U(x,y)) and upper (V(x,y)) limits of integration with respect to the variable z. The function must accept x and y and return a two-element vector result.

For example, we might write the following IDL function to represent the limits of integration with respect to z:

FUNCTION UV_limits, X, Y

  RETURN, [0, SQRT(4.0 - X^2 - Y^2)]

END

Pts

The number of transformation points used in the computation. Possible values are: 6, 10, 20, 48, or 96.

Keywords

DOUBLE

Set this keyword to force the computation to be done in double-precision arithmetic.

Example

Compute the triple integral of the trivariate function

Using the functions and limits defined above, integrate with 10, 20, 48, and 96 point formulas (using double-precision arithmetic):

PRINT, INT_3D('Fxyz', [-2.0, 2.0], 'PQ_Limits', 'UV_Limits', 10, /D)

PRINT, INT_3D('Fxyz', [-2.0, 2.0], 'PQ_Limits', 'UV_Limits', 20, /D)

PRINT, INT_3D('Fxyz', [-2.0, 2.0], 'PQ_Limits', 'UV_Limits', 48, /D)

PRINT, INT_3D('Fxyz', [-2.0, 2.0], 'PQ_Limits', 'UV_Limits', 96, /D)

INT_3D with 10 transformation points yields:	57.444248

INT_3D with 20 transformation points yields:	57.446201

INT_3D with 48 transformation points yields:	57.446265

INT_3D with 96transformation points yields:	57.446266

The exact solution (6 decimal accuracy) is:	57.446267

See Also

INT_2D, INT_TABULATED, QROMB, QROMO, QSIMP


INT_TABULATED

The INT_TABULATED function integrates a tabulated set of data { xi , fi } on the closed interval [MIN(x) , MAX(x)], using a five-point Newton-Cotes integration formula. Note: data that are highly oscillatory require a sufficient number of samples for an accurate integral approximation.

This routine is written in the IDL language. Its source code can be found in the file int_tabulated.pro in the lib subdirectory of the IDL distribution.

Calling Sequence

Result = INT_TABULATED(X, F)

Arguments

X

The tabulated single- or double-precision floating-point x-value data. Data may be irregularly gridded and in random order. (If the data is randomly ordered, set the SORT keyword.)

F

The tabulated single- or double-precision floating-point f-value data. Upon input to the function, xi and fi must have corresponding indices for all values of i. If x is reordered, f is also reordered.

Keywords

SORT

Set this keyword to sort the tabulated x-value data into ascending order. If SORT is set, both x and f values are sorted.

Example

Define 11 x-values on the closed interval [0.0 , 0.8]:

X = [0.0, .12, .22, .32, .36, .40, .44, .54, .64, .70, .80]

Define 11 f-values corresponding to xi :

F = [0.200000, 1.30973, 1.30524, 1.74339, 2.07490, 2.45600, $

     2.84299, 3.50730, 3.18194, 2.36302, 0.231964]

result = INT_TABULATED(X, F)	Integrate.

In this example, the f-values are generated from a known function

f = 0.2 + 25x ­ 200x ^2 + 675x^3 ­ 900x^4 + 400x^5

which allows the determination of an exact solution. A comparison of methods yields the following results:

The Multiple Application Trapezoid Method yields:	1.5648

The Multiple Application Simpson's Method yields:	1.6036

INT_TABULATED yields:	1.6271

The exact solution (4 decimal accuracy) is: 	1.6405

See Also

INT_2D, INT_3D, QROMB, QROMO, QSIMP


INTARR

The INTARR function returns an integer vector or array.

Calling Sequence

Result = INTARR(D1, ..., Dn)

Arguments

Di

The dimensions of the result. The dimension parameters can be any scalar expression. Up to eight dimensions can be specified.

Keywords

NOZERO

Normally, INTARR sets every element of the result to zero. If NOZERO is nonzero, this zeroing is not performed and INTARR executes faster.

Example

Create I, a 3-element by 3-element integer array with each element set to 0 by entering:

I = INTARR(3, 3)

See Also

BYTARR, COMPLEXARR, DBLARR, DCOMPLEXARR, FLTARR, LONARR, MAKE_ARRAY, STRARR


INTERPOL

The INTERPOL function performs linear interpolation on vectors with a regular or irregular grid. The result is a single- or double-precision floating-point vector, or a complex vector if the input vector is complex.

This routine is written in the IDL language. Its source code can be found in the file interpol.pro in the lib subdirectory of the IDL distribution.

Calling Sequence

Result = INTERPOL(V, N)	For regular grids.

Result = INTERPOL(V, X, U)	For irregular grids.

Arguments

V

An input vector of any type except string.

N

The number of points in the result when both input and output grids are regular. The output grid abscissa values equal FLOAT(i)/N_ELEMENTS(V), for i = 0, N-1.

X

The absicissae values for V, in the irregularly-gridded case.  X must have the same number of elements as V, and the values must be monotonically ascending or descending.

U

The absicissae values for the result. The result will have the same number of elements as  U. U does not need to be monotonic.

Example

Create a floating-point vector of 61 elements in the range [-3, 3].

X = FINDGEN(61)/10 - 3

V = SIN(X)	Evaluate V(x) at each point.

U = [-2.50, -2.25, -1.85, -1.55, -1.20, -0.85, -0.50, -0.10, $

   0.30, 0.40, 0.75, 0.85, 1.05, 1.45, 1.85, 2.00, 2.25, 2.75 ]
Define X-values where interpolates are desired.

result = INTERPOL(V, X, U)	Interpolate.

PLOT, X, V	Plot the function.

OPLOT, U, result	Plot the interpolated values.

See Also

BILINEAR, INTERPOLATE, KRIG2D


INTERPOLATE

The INTERPOLATE function returns an array of linear, bilinear or trilinear interpolates, depending on the dimensions of the input array P. Linear interpolates are returned in the one-dimensional case, bilinear in the two-dimensional case and trilinear interpolates in the three-dimensional case. The returned array has the same type as P and its dimensions depend on those of the location parameters X, Y, and Z, as explained below.

Interpolates outside the bounds of P can be set to a user-specified value by using the MISSING keyword.

Calling Sequence

Result = INTERPOLATE(P, X [, Y [, Z]])

Arguments

P

The array of data values. P must be a one-, two-, or three-dimensional array of numeric type.

X, Y, Z

Arrays of numeric type containing the locations for which interpolates are desired. For linear interpolation (P is a vector), the result has the same dimensions as X. The i-th element of the result is  P interpolated at location Xi. The Y and Z parameters should be omitted.

For bilinear interpolation Z should not be present.

If the keyword GRID is not set, all location arrays must have the same number of elements. See the description of the GRID keyword below for more details on how interpolates are computed from P and these arrays.

Keywords

CUBIC

Set this keyword to use the cubic convolution interpolation method.

Cubic convolution is an interpolation method that closely approximates the theoretically optimum sinc interpolation function using cubic polynomials. According to sampling theory, details of which are beyond the scope of this document, if the original signal, f , is a band-limited signal, with no frequency component larger than  ω0, and f is sampled with spacing less than or equal to 1/(2ω0), then f can be reconstructed by convolving with a sinc function: sinc( x) = sin(πx) / (πx).

In the one-dimensional case, four neighboring points are used, while in the two-dimensional case 16 points are used. Note that cubic convolution interpolation is significantly slower than bilinear interpolation.

For further details see Rifman, S.S. and McKinnon, D.M., "Evaluation of Digital Correction Techniques for ERTS Images—Final Report", Report 20634-6003-TU-00, TRW Systems, Redondo Beach, CA, July 1974.

GRID

The GRID keyword controls how the location arrays specify where interpolates are desired. This keyword has no effect in the case of linear interpolation.

If GRID is not set: The location arrays, X,  Y, and, if present, Z must have the same number of elements. The result has the same structure and number of elements as X.

In the case of bilinear interpolation, the result is obtained as follows: Let l = Xi  and k = Yi . Element i of the result is computed by interpolating between P(l, k), P(l+1, k), P(l,  k+1), and P(l+1, k+1). to obtain the estimated value at (Xi, Yi). Trilinear interpolation is a direct extension of the above.

If GRID is set: Let Nx be the number of elements in X, let Ny be the number of elements in Y, and Nz be the number of elements in Z. The result has dimensions (Nx, Ny) for bilinear interpolation, and (Nx, Ny, Nz) for trilinear interpolation. For bilinear interpolation, element (i,j) of the result contains the value of P interpolated at position (Xi, Yi). For trilinear interpolation, element (i, j, k) of the result is P interpolated at (Xi, Yi, Zi).

MISSING

The value to return for elements outside the bounds of P. If this keyword is not specified, locations less than zero or greater than the largest corresponding subscript of P are set to the nearest element of P.

Examples

The example below computes bilinear interpolates with the keyword GRID set:

p = FINDGEN(4,4)

PRINT, INTERPOLATE(p, [.5, 1.5, 2.5], [.5, 1.5, 2.5], /GRID)

and prints the 3 by 3 array:

   2.50000   3.50000   4.50000

   6.50000   7.50000   8.50000

   10.5000   11.5000   12.5000

corresponding to the locations:

(.5,.5), (1.5, .5), (2.5, .5),
(.5,1.5), (1.5, 1.5), (2.5, 1.5),
(.5,2.5), (1.5, 2.5), (2.5, 2.5)

Another example computes interpolates, with GRID not set and a parameter outside the bounds of P:

PRINT, INTERPOLATE(p, [.5, 1.5, 2.5, 3.1], [.5, 1.5, 2.5, 2])

prints the result:

   2.50000   7.50000   12.5000   11.0000

corresponding to the locations (.5,.5), (1.5, 1.5), (2.5, 2.5) and (3.1, 2.0). Note that the last location is outside the bounds of P and is set from the value of the last column. The following command uses the MISSING keyword to set such values to -1:

PRINT, INTERPOLATE(p, [.5, 1.5, 2.5, 3.1], [.5, 1.5, 2.5, 2], $

       MISSING = -1)

and gives the result:

   2.50000   7.50000   12.5000   -1.00000

See Also

BILINEAR, INTERPOL, KRIG2D


INVERT

The INVERT function uses the Gaussian elimination method to compute the inverse of a square array. The result is a single- or double-precision floating-point array. Errors from singular or near-singular arrays are accumulated in the optional Status.

Calling Sequence

Result = INVERT(Array [, Status])

Arguments

Array

The array to be inverted. Array must have two dimensions of equal size (i.e., a square array) and can be of any type except string. Note that the resulting array will be composed of single- or double-precision floating-point values, depending on whether the DOUBLE keyword is set.

Status

A named variable to receive the status of the operation. Possible status values are: 0 for successful completion, 1 for a singular array (which indicates that the inversion is invalid), and 2 which is a warning that a small pivot element was used and that significant accuracy was probably lost.

Keywords

DOUBLE

Set this keyword to force the computation to be done in double-precision arithmetic.

Example

Begin with an array A:

A = [[ 5.0, -1.0, 3.0], $

     [ 2.0,  0.0, 1.0], $

     [ 3.0,  2.0, 1.0]]

result = INVERT(A)	Invert.

We can check the accuracy of the inversion by multiplying the inverted array by the original array. The result should be a 3 x 3 identity array.

PRINT, result # A

IDL prints:

      1.00000      0.00000      0.00000

      0.00000      1.00000      0.00000

      0.00000  9.53674e-07      1.00000

See Also

COND, DETERM,  INVERT, REVERSE, ROTATE, TRANSPOSE


IOCTL

The IOCTL function provides a thin wrapper over the Unix ioctl(2) system call. IOTCL performs special functions on the specified file. The set of functions actually available depends on your version of Unix and the type of file (tty, tape, disk file, etc.) referred to.

To use IOCTL, read the C programmer's documentation describing the ioctl(2) function for the desired device and convert all constants and data to their IDL equivalents.

The value returned by the system ioctl function is returned as the value of the IDL IOCTL function.

Calling Sequence

Result = IOCTL(File_Unit [, Request, Arg])

Arguments

File_Unit

The IDL logical file unit (LUN) for the open file on which the ioctl request is made.

Request

A longword integer that specifies the ioctl request code. These codes are usually contained in C language header files provided by the operating system, and are not generally portable between Unix versions. If one of the "MT" keywords is used, this argument can be omitted.

Arg

A named variable through which data if passed to and from ioctl. IOCTL requests usually request data from the system or supply the system with information. The user must make  Arg the correct type and size. Errors in typing or sizing Arg can corrupt the IDL address space and/or make IDL crash. If one of the MT keywords is used, this argument can be omitted.

Keywords

Note that the keyword below that start with "MT" can be used to issue commonly used magnetic tape ioctl() calls. When these keywords are used, the Request and Arg arguments are ignored and an be omitted. Magnetic tape operations not available via these keywords can still be executed by supplying the appropriate Request and Arg values. When issuing magnetic tape IOCTL calls, be aware that different devices have different rules for which ioctl calls are allowed, and when. The documentation for your computer system explains those rules.

BY_VALUE

If this keyword is set, Arg is converted to a scalar longword and this longword is passed by value. Normally, Arg is passed to ioctl by reference (i.e., by address).

MT_OFFLINE

Set this keyword to rewind and unload a tape.

MT_REWIND

Set this keyword to rewind a tape.

MT_SKIP_FILE

Use this keyword to skip files on a tape. A positive value skips forward that number of files. A negative value skips backward.

MT_SKIP_RECORD

Use this keyword to skip records on tape. A positive value skips forward that number of files. A negative value skips backward.

MT_WEOF

Set this keyword to write an end of file ("tape mark") on the tape at the current location.

SUPPRESS_ERROR

Set this keyword to log errors quietly and cause a value of -1 to be returned. The default is for IDL to notice any failures associated with the use of ioctl and issue the appropriate IDL error and halt execution.

Example

The following example prints the size of the terminal being used by the current IDL session. It is known to work under SunOS 4.1.2. Changes may be necessary for other operating systems or even other versions of SunOS.

winsize = { row:0, col:0, xpixel:0, ypixel:0 }
Variable to receive result. This structure is described in Section 4 of the SunOS manual pages under termios(4).

TIOCGWINSZ = 1074295912L	The request code for obtaining the tty size, as determined by reading the termios(4) documentation, and reading the system include files in the /usr/include/sys directory.

ret = ioctl(-1, TIOCGWINSZ, winsize)
Make the information request. -1 is the IDL logical file unit for the standard output.

print,winsize.row, winsize.col, $

      format='("TTY has ", I0," rows and ", I0," columns.")'
Output the results.

The following points should be noted in this example:

•	Even though we only want the number of rows and columns, we must include all the fields required by the TIOCGWINSIZ ioctl in the winsize variable (as documented in the termio(4) manual page). Not providing a large enough result buffer would cause IDL's memory to be corrupted.

•	The value of TIOCGWINSZ was determined by examining the system header files provided in the /usr/include/sys directory. Such values are not always portable between major operating system releases.

See Also

OPEN


ISHFT

The ISHFT function performs the bit shift operation on bytes, integers and longwords. If P2 is positive, P1 is left shifted P2 bit positions with 0 bits filling vacated positions. If P2 is negative, P1 is right shifted with 0 bits filling vacated positions.

Calling Sequence

Result = ISHFT(P1, P2)

Arguments

P1

The scalar or array to be shifted.

P2

The scalar or array containing the number of bit positions and direction of the shift.

Example

Bit shift each element of the integer array [1, 2, 3, 4, 5] three bits to the left and store the result in B by entering:

B = ISHFT([1,2,3,4,5], 3)

The resulting array B is [8, 16, 24, 32, 40].

See Also

SHIFT


JOURNAL

The JOURNAL procedure provides a record of an interactive session by saving, in a file, all text entered from the terminal in response to the IDL prompt. The first call to JOURNAL starts the logging process. The read-only system variable !JOURNAL is set to the file unit used. To stop saving commands and close the file, call JOURNAL with no parameters. If logging is in effect and JOURNAL is called with a parameter, the parameter is simply written to the journal file.

Calling Sequence

JOURNAL [, Arg]

Arguments

Arg

A string containing the name of the journal file to be opened or text to be written to an open journal file. If Arg is not supplied, and a journal file is not already open, the file idlsave.pro is used. Once journaling is enabled, a call to JOURNAL with Arg supplied causes Arg to be written into the journal file. Calling JOURNAL without Arg while journaling is in progress closes the journal file and ends the logging process.

Example

To begin journaling to the file myjournal.pro, enter:

JOURNAL, 'myjournal.pro'

Any commands entered at the IDL prompt are recorded in the file until IDL is exited or the JOURNAL command is entered without an argument.

See Also

RESTORE, SAVE


JULDAY

The JULDAY function calculates the Julian Day Number for a given month, day, and year. This is the inverse of the CALDAT procedure. JULDAY returns the Julian Day Number (which begins at noon) of the specified calendar date.

This routine is written in the IDL language. Its source code can be found in the file julday.pro in the lib subdirectory of the IDL distribution.

Calling Sequence

Result = JULDAY(Month, Day, Year)

Arguments

Month

Number of the desired month (1 = January, ..., 12 = December).

Day

Number of day of the month.

Year

Number of the desired year.

See Also

BIN_DATE, CALDAT, SYSTIME


KEYWORD_SET

The KEYWORD_SET function returns a nonzero value if Expression is defined and nonzero or an array, otherwise zero is returned. This function is especially useful in user-written procedures and functions that process keywords that are interpreted as being either true (keyword is present and nonzero) or false (keyword was not used, or was set to zero).

Calling Sequence

Result = KEYWORD_SET(Expression)

Arguments

Expression

The expression to be tested. Expression is usually a named variable.

Example

Suppose that you are writing an IDL procedure that has the following procedure definition line:

PRO myproc, KEYW1 = keyw1, KEYW2 = keyw2

The following command could be used to execute a set of commands only if the keyword KEYW1 is set (i.e., it is present and nonzero):

IF KEYWORD_SET(keyw1) THEN BEGIN

The commands to be executed only if KEYW1 is set would follow.

See Also

N_PARAMS


KRIG2D

The KRIG2D function interpolates a regularly- or irregularly-gridded set of points z = f  (x, y) using kriging. It returns a two dimensional floating-point array containing the interpolated surface, sampled at the grid points.

The parameters of the data model ­ the range, nugget, and sill ­ are highly dependent upon the degree and type of spatial variation of your data, and should be determined statistically. Experimentation, or preferably rigorous analysis, is required.

For n data points, a system of n+1 simultaneous equations are solved for the coefficients of the surface. For any interpolation point, the interpolated value is:

f (x,y) = Sum ( wi ⋅ C(xi,yi, x, y) )

The following formulas are used to model the variogram functions:

d(i,j) = the distance from point i to point j.

V = the variance of the samples.

C(i,j) = the covariance of sample i with sample j.

C(x0,y0,x1,y1) = the covariance of point (x0,y0) with point (x1, y1).

Exponential covariance:

C(d) = C1 ⋅ EXP(­3d/A)   if d ≠ 0

C(d) = C1 + C0                  if d = 0

Spherical covariance:

C(d) = (1.0 ­ 1.5d/A + 0.5(d/A)^3)       if d < A

C(d) = C1 + C0                                    if d = 0

C(d) = 0                                                  if d > A

Note: the accuracy of this function is limited by the single-precision floating-point accuracy of the machine.

This routine is written in the IDL language. Its source code can be found in the file krig2d.pro in the lib subdirectory of the IDL distribution.

Calling Sequence

Result = KRIG2D(Z [, X, Y])

Arguments

Z, X, Y

Arrays containing the Z, X, and  Y coordinates of the data points on the surface. Points need not be regularly gridded. For regularly gridded input data, X  and Y are not used: the grid spacing is specified via the XGRID and YGRID (or XVALUES and YVALUES) keywords, and Z must be a two dimensional array. For irregular grids, all three parameters must be present and have the same number of elements.

Keywords

Model Parameters:

EXPONENTIAL

Set this keyword to a two- or three-element vector of model parameters to use an exponential semivariogram model. The model parameters (A, CO, and C1) are explained below.

SPHERICAL

Set this keyword to a two- or three-element vector of model parameters to use a spherical semivariogram model. The model parameters (A, CO, and C1) are explained below.

A

The range. At distances beyond A, the semivariogram or covariance remains essentially constant.

C0

The nugget, which provides a discontinuity at the origin.

C1

If specified, C1 is the covariance value for a zero distance, and the variance of the random sample z variable. If only a two element vector is supplied, C1 is set to the sample variance. (C0 + C1) = the sill , which is the variogram value for very large distances.

Input Grid Description:

REGULAR

If set, the Z parameter is a two dimensional array of dimensions (n,m), containing measurements over a regular grid. If any of XGRID, YGRID, XVALUES, or YVALUES are specified, REGULAR is implied. REGULAR is also implied if there is only one parameter, Z. If REGULAR is set, and no grid specifications are present, the grid is set to (0, 1, 2, ...).

XGRID

A two-element array, [xstart, xspacing], defining the input grid in the x direction. Do not specify both XGRID and XVALUES.

XVALUES

An n-element array defining the x locations of Z(i,j). Do not specify both XGRID and XVALUES.

YGRID

A two-element array, [ystart, yspacing], defining the input grid in the y direction. Do not specify both YGRID and YVALUES.

YVALUES

An n-element array defining the y locations of Z(i,j). Do not specify both YGRID and YVALUES.

Output Grid Description:

GS

The output grid spacing. If present, GS must be a two-element vector [xs, ys], where xs is the horizontal spacing between grid points and ys is the vertical spacing. The default is based on the extents of x and y . If the grid starts at x value xmin and ends at xmax, then the default horizontal spacing is (xmax - xmin )/(NX-1). ys is computed in the same way. The default grid size, if neither NX or NY are specified, is 26 by 26.

BOUNDS

If present, BOUNDS must be a four-element array containing the grid limits in x and y of the output grid: [xmin, ymin, xmax, ymax]. If not specified, the grid limits are set to the extent of x and y.

NX

The output grid size in the x direction. NX need not be specified if the size can be inferred from GS and BOUNDS. The default value is 26.

NY

The output grid size in the y direction. NY need not be specified if the size can be inferred from GS and BOUNDS. The default value is 26.

Examples

Make a random set of points that lie on a Gaussian:

N = 15	Number of random points.

X = RANDOMU(seed, N)

Y = RANDOMU(seed, N)

Z = EXP(-2 * ((X-.5)^2 + (Y-.5)^2))	The Gaussian.

Get a 26 by 26 grid over the rectangle bounding x and y:

E = [ 0.25, 0.0]	Range is 0.25 and nugget is 0. These numbers are dependent on your data model.

R = KRIG2D(Z, X, Y, EXPON = E)	Get the surface.

Alternatively, get a surface over the unit square, with spacing of 0.05:

R = KRIG2D(Z, X, Y, EXPON=E, GS=[0.05, 0.05], BOUNDS=[0,0,1,1])

See Also

BILINEAR, INTERPOLATE


KW_TEST

The KW_TEST function tests the hypothesis that three or more sample populations have the same mean of distribution against the hypothesis that they differ. The populations may be of equal or unequal lengths. The result is a two-element vector containing the test statistic H and the one-tailed probability of obtaining a value of H or greater from a Chi-square distribution.

This test is an extension of the Rank Sum Test implemented in the RS_TEST function. When each sample population contains at least five observations, the H test statistic is approximated very well by a Chi-square distribution with DF degrees of freedom. The hypothesis that three of more sample populations have the same mean of distribution is rejected if two or more populations differ with statistical significance. This type of test is often referred to as the Kruskal-Wallis H-Test.

The test statistic H is defined as follows:

where Ni  is the number of observations in the ith sample population, NT is the total number of observations in all sample populations, and Ri is the overall rank sum of the ith sample population.

This routine is written in the IDL language. Its source code can be found in the file kw_test.pro in the lib subdirectory of the IDL distribution.

Calling Sequence

Result = KW_TEST(X)

Arguments

X

An integer, single-, or double-precision floating-point array of m-columns (with m ≥ 3) and n-rows. The columns of this two dimensional array correspond to the sample populations.

If the sample populations are of unequal length, any columns of X that are shorter than the longest column must be "filled in" by appending a user-specified missing data value. This method requires the use of the MISSING keyword. See the  Example section below for an example of this case.

Keywords

DF

Use this keyword to specify a named variable that will contain the number of degrees of freedom used to compute the probability of obtaining a value of H or greater from the corresponding Chi-square distribution

MISSING

Set this keyword equal to a non-zero numeric value that has been appended to some columns of X to make them all a common length of n.

Example

Test the hypothesis that three sample populations have the same mean of distribution against the hypothesis that they differ at the 0.05 significance level. Assume we have the following sample populations:

sp0 = [24.0, 16.7, 22.8, 19.8, 18.9]

sp1 = [23.2, 19.8, 18.1, 17.6, 20.2, 17.8]

sp2 = [18.2, 19.1, 17.3, 17.3, 19.7, 18.9, 18.8, 19.3]

Since the sample populations are of unequal lengths, a missing value must be appended to sp0 and sp1. In this example the missing value is -1.0 and the 3-column, 8-row input array X is defined as:

X = [[24.0, 23.2, 18.2], $

     [16.7, 19.8, 19.1], $

     [22.8, 18.1, 17.3], $

     [19.8, 17.6, 17.3], $

     [18.9, 20.2, 19.7], $

     [-1.0, 17.8, 18.9], $

     [-1.0, -1.0, 18.8], $

     [-1.0, -1.0, 19.3]]

PRINT, KW_TEST(X, MISSING = -1)

IDL prints:

[1.65862, 0.436351]

The computed probability (0.436351) is greater than the 0.05 significance level and therefore we do not reject the hypothesis that the three sample populations sp0, sp1, and sp2 have the same mean of distribution.

See Also

FV_TEST, RS_TEST, S_TEST, TM_TEST


LABEL_DATE

The LABEL_DATE function can be used, in conjunction with the [XYZ]TICKFORMAT keyword to IDL plotting routines, to easily label axes with dates.

This routine is written in the IDL language. Its source code can be found in the file label_date.pro in the lib subdirectory of the IDL distribution.

Calling Sequence

Result = LABEL_DATE(DATE_FORMAT = String)

PLOT, x, y, XTICKFORMAT = 'LABEL_DATE'

Arguments

LABEL_DATE has no explicit inputs. When called from the plotting routines, the input parameters are (Axis, Index, Value)

Keywords

DATE_FORMAT

Set this keyword to a format string that can contain any of the following variables:

•	%M for month (3 character abbreviations)

•	%N for month (2 digit abbreviations)

•	%D for day of month

•	%Y for 4 digit year

•	%Z for last two digits of year

•	%% to represent the % character

•	Any vector font positioning and font change commands

•	Other characters are passed directly through

For example, '%M %D, %Y' results in labels of the form DEC 11, 1993. '%M %2Y' yields DEC 93. '%D-%M' yields 11-DEC. '%D/%N/%Y' yields 11/12/1993. '%M!C%Y' yields DEC on the top line, 1993 on the bottom (!C is the newline graphics command).

MONTHS

A twelve element string array that contains the names to be used for months. If omitted, three-letter abbreviations are used (i.e., Jan, Feb, ..., Dec).

Example

The following commands create a sample plot that has a date axis from Jan 1, 1993 to July 12, 1994:

start_date = JULDAY(1, 1, 1993)

end_date = JULDAY(7, 12, 1994)

dummy = LABEL_DATE(DATE_FORMAT = '%N/%D')
Simple mm/dd

x = FINDGEN(end_date+1 - start_date) + start_date
Time axis

PLOT, x, sqrt(x), XTICKFORMAT = 'LABEL_DATE', XSTYLE=1
Plot with X axis style set to exact.

See Also

[XYZ]TICKFORMAT keyword


LABEL_REGION

The LABEL_REGION function consecutively labels all of the regions, or blobs, of a bi-level image with a unique region index. This process is sometimes called "blob coloring". A region is a set of non-zero pixels, each of which are a horizontal or vertical neighbor of one or more pixels within the same region.

The argument for LABEL_REGION is a two-dimensional bi-level integer type array—only zero and non-zero values are considered. The result of the function is a two-dimensional integer array of the same dimensions with each pixel containing its region index. A region index of zero indicates that the original pixel was zero and belongs to no region. Output values range from 0 to the number of regions.

Statistics on each of the regions may be easily calculated using the HISTOGRAM function as shown in the examples below.

Calling Sequence

Result = LABEL_REGION(Image)

Arguments

Image

The two-dimensional image to be labeled. Image is converted to integer type if necessary. Pixels at the edges of Image are considered to be zero.

Example

Count the number of distinct regions within an image, and their population:

b = LABEL_REGION(image)	Get blob indices.

h = HISTOGRAM(b)	Get population of each blob.

FOR i=0, N_ELEMENTS(h)-1 DO PRINT 'Region ',i, $

    ', Population = ', h(i)

Note that region 0 is the set of zero pixels that are not within a region.

As above, but also print the average value and standard deviation of each region:

b = LABEL_REGION(image)	Get blob indices.

h = HISTOGRAM(b, REVERSE_INDICES=r)
Get population and members of each blob.

FOR i=0, N_ELEMENTS(h)-1 DO BEGIN	Each region

p = r(r(i):r(i+1)-1)	Find subscripts of members of region i.

q = image(p)	Pixels of region i

PRINT 'Region ', i, $

', Population = ', h(i), $

', Standard Deviation = ', STDEV(q, mean), $

', Mean = ', mean

ENDFOR

See Also

ANNOTATE, DEFROI, HISTOGRAM


LADFIT

The LADFIT function fits the paired data {xi, yi} to the linear model, y = A + Bx, using a "robust" least absolute deviation method. The result is a two-element vector containing the model parameters, A and B.

This routine is written in the IDL language. Its source code can be found in the file ladfit.pro in the lib subdirectory of the IDL distribution.

Calling Sequence

Result = LADFIT(X, Y)

Arguments

X

An n-element integer, single-, or double-precision floating-point vector.

Y

An n-element integer, single-, or double-precision floating-point vector.

Keywords

ABSDEV

Set this keyword to a named variable that will contain the mean absolute deviation for each data-point in the y-direction.

Example

Define two n-element vectors of paired data.

X = [-3.20, 4.49, -1.66, 0.64, -2.43, -0.89, -0.12, 1.41, $

      2.95, 2.18, 3.72, 5.26]

Y = [-7.14, -1.30, -4.26, -1.90, -6.19, -3.98, -2.87, -1.66, $

     -0.78, -2.61, 0.31, 1.74]

Compute the model parameters, A and B.

PRINT, LADFIT(X, Y)

IDL prints:

[-3.15191, 0.930440]

The figure below displays a two-dimensional distribution that is fitted to the model y = a + bx, using a minimized Chi-square error criterion (left) and a "robust" least absolute deviation technique (right). The use of the Chi-square error statistic can result in a poor fit due to an undesired sensitivity to outlying data.

See Also

COMFIT, CURVEFIT, LINFIT


LEEFILT

The LEEFILT function performs the Lee filter algorithm on an image array using a box of size 2N+1. This function can also be used on vectors. The Lee technique smooths additive image noise by generating statistics in a local neighborhood and comparing them to the expected values.

This routine is written in the IDL language. Its source code can be found in the file leefilt.pro in the lib subdirectory of the IDL distribution.

Calling Sequence

Result = LEEFILT(A [, N, Sig])

Arguments

A

The input image array or one-dimensional vector.

N

The size of the filter box is 2N+1. The default value is 5.

Sig

Estimate of the standard deviation. The default is 5. If Sig is negative, IDL interactively prompts for a value of sigma, and displays the resulting image using TVSCL. To end this cycle, enter a value of 0 (zero) for sigma.

See Also

DIGITAL_FILTER, MEDIAN, SMOOTH, VOIGT


LINBCG

The LINBCG function is used in conjunction with SPRSIN to solve a set of n linear equations with n unknowns using the iterative biconjugate gradient method. The result is an n-element vector.

LINBCG is based on the routine linbcg described in section 2.7 of Numerical Recipes in C: The Art of Scientific Computing (Second Edition), published by Cambridge University Press, and is used by permission.

Note: Numerical Recipes recommends using double-precision arithmetic to perform this computation.

Calling Sequence

Result = LINBCG(A, B, X)

Arguments

A

A row-indexed sparse array created by the SPRSIN function.

B

An n-element vector containing the right-hand side of the linear system Ax=b.

X

An n-element vector containing the initial solution of the linear system.

Keywords

DOUBLE

Set this keyword to force the computation to be done in double-precision arithmetic.

ITOL

Use this keyword to specify which convergence test should be used. Set ITOL to one of the following:

1.	Iteration stops when A ⋅ x - b/b is less than the value specified by TOL.

2.	Iteration stops when Ã^-1 ⋅ (A ⋅ x - b)/Ã^-1 ⋅ b (where Ã is a "preconditioning" matrix close to A) is less than the value specified by TOL.

3.	The routine uses its own estimate of error in x. Iteration stops when the magnitude of the error divided by the magnitude of x is less than the value specified by TOL. This is the default setting.

4.	The same as 3, except that the routine uses the largest (in absolute value) component of the error and the largest component of x rather than the vector magnitudes.

TOL

Use this keyword to specify the desired convergence tolerance. For single-precision calculations, the default value is 1.0 x 10^-7. For double-precision values, the default is 1.0 x 10^-14.

ITER

Use this keyword to specify an output variable that will be set to the number of iterations performed.

ITMAX

The maximum allowed number of iterations. The default is n^2.

Example

Begin with an array A:

A = [[ 5.0,  0.0, 0.0,  1.0, -2.0], $

     [ 3.0, -2.0, 0.0,  1.0,  0.0], $

     [ 4.0, -1.0, 0.0,  2.0,  0.0], $

     [ 0.0,  3.0, 3.0,  1.0,  0.0], $

     [-2.0,  0.0, 0.0, -1.0,  2.0]]

B = [7.0, 1.0, 3.0, 3.0, -4.0]	Define a right-hand side vector B.

X = REPLICATE(1.0, N_ELEMENTS(B))	Start with an initial guess at the solution.

result = LINBCG(SPRSIN(A), B, X)
Solve the linear system Ax=b.

PRINT, result	Print the result.

IDL prints:

   1.00000   1.00000  -5.53459e-08   3.02525e-07  -1.00000

The exact solution is [1, 1, 0, 0, -1].

See Also

FULSTR, SPRSAB, SPRSAX, SPRSIN, READ_SPR, WRITE_SPR


LINDGEN

The LINDGEN function returns a longword integer array with the specified dimensions. Each element of the array is set to the value of its one-dimensional subscript.

Calling Sequence

Result = LINDGEN(D1, ..., Dn)

Arguments

Di

The dimensions of the result. The dimension parameters can be any scalar expression. Up to eight dimensions can be specified.

Example

To create L, a 10-element by 10-element longword array where each element is set to the value of its one-dimensional subscript, enter:

L = LINDGEN(10, 10)

See Also

BINDGEN, CINDGEN, DCINDGEN, DINDGEN, FINDGEN, INDGEN, SINDGEN


LINFIT

The LINFIT function fits the paired data {xi, yi} to the linear model, y = A + Bx, by minimizing the Chi-square error statistic. The result is a two-element vector containing the model parameters, A and B.

This routine is written in the IDL language. Its source code can be found in the file linfit.pro in the lib subdirectory of the IDL distribution.

Calling Sequence

Result = LINFIT(X, Y)

Arguments

X

An n-element integer, single-, or double-precision floating-point vector.

Y

An n-element integer, single-, or double-precision floating-point vector.

Keywords

CHISQR

Set this keyword to a named variable that will contain the Chi-square error statistic as the sum of squared errors between yi and A + Bxi. If individual standard deviations are supplied, then the Chi-square error statistic is computed as the sum of squared errors divided by the standard deviations.

PROB

Set this keyword to a named variable that will contain the probability that the computed fit would have a value of CHISQR or greater. If PROB is greater than 0.1, the model parameters are "believable". If PROB is less than 0.1, the accuracy of the model parameters is questionable.

SDEV

An n-element integer, single-, or double-precision floating-point vector that specifies the individual standard deviations for {xi , yi}.

SIG_AB

Set this keyword to a named variable that will contain a two-element vector of probable uncertainties for the model parameters A and B, respectively.

Example

Define two n-element vectors of paired data.

X = [-3.20, 4.49, -1.66, 0.64, -2.43, -0.89, -0.12, 1.41, $

      2.95, 2.18, 3.72, 5.26]

Y = [-7.14, -1.30, -4.26, -1.90, -6.19, -3.98, -2.87, -1.66, $

     -0.78, -2.61, 0.31, 1.74]

Define an n-element vector of standard deviations with a constant value of 0.85

sdev = REPLICATE(0.85, N_ELEMENTS(X))

Compute the model parameters, A and B.

PRINT, LINFIT(X, Y, SDEV=sdev)

IDL prints:

[-3.44596, 0.867329]

See Also

COMFIT, CURVEFIT, LADFIT


LINKIMAGE

LINKIMAGE merges routines written in other languages with IDL at run-time. Each call to LINKIMAGE defines a new system procedure or function by specifying the routine's name, the name of the file containing the code, and the entry point name. The name of your routine is added to IDL's internal system routine table, making it available in the same manner as any other IDL built-in routine. LINKIMAGE can also be used to add graphics device drivers.

Warning: This procedure is only available under VMS, Windows, on Unix systems that support the dynamic loading of object modules, and on PowerPC Macintoshes. Its use requires intimate knowledge of the internals of IDL, and is not for use by the novice user. It should only be used if there is absolutely no alternative. If dynamic linking is necessary, we recommend you examine the CALL_EXTERNAL function before committing to LINKIMAGE, as it has a much simpler interface.

Under VMS, the LIB$FIND_IMAGE_SYMBOL run-time library routine is used to activate your sharable image and merge it into the IDL address space. To understand this process better, or in the event of problems, it is a good idea to read the description of LIB$FIND_IMAGE_SYMBOL in the VMS Run Time Library Reference Manual.

Under Unix, LINKIMAGE uses the interface to the dynamic linker: dlopen() for Sun, shl_load() for HP-UX, and load() for AIX.

Under Windows, LINKIMAGE uses LoadLibrary() to load a 32-bit DLL..

On the PowerPC Macintosh, LINKIMAGE uses the Code Fragment Manager routines GetDiskFragment( ) and FindSymbol( ) to load shared libraries.

Note: Modules must be merged via LINKIMAGE before other procedures and functions that call them are compiled, or the compilation of those routines will fail.

Calling Sequence

LINKIMAGE, Name, Image [, Type [, Entry]]

Arguments

Name

A string containing the IDL name of the function, procedure or device routine which is to be merged. When loading a device driver, Name contains the name of the global ("universal" for VMS) DEVICE_DEF structure in the driver. Upon successful loading of the routine, a new procedure or function with the given name will exist, or the new device driver will be loaded.

Image

A string that holds the name of the file containing the code to be dynamically linked.

Under VMS, the specified file must be a sharable image, and this argument can contain only the file name. The device/directory, and file type parts of the specification are not included. If the sharable image file is not in SYS$SHARE, a logical name that translates to the full specification can be used, or the DEFAULT keyword can be used to specify the additional information.

Under Unix this argument contains the full path specification of the dynamically loaded object file. See the Unix documentation on sharable libraries and dynamic linking for details.

On the Macintosh, this argument contains the full path specification of the shared library.

Type

An optional scalar integer parameter that contains 0 for a procedure, 1 for a function, and 2 for a device driver. The keyword parameters DEVICE and FUNCT can also be used to indicate the type of routine being merged. The default value is 0, for procedure.

Entry

An optional string that contains the name of the symbol which is the entry point of the procedure or function. If this parameter is not present, the entry name is the value of the parameter Name. Under VMS, the symbol must be declared to be a universal symbol when the sharable image is linked. See the documentation of the VMS LINK command for additional details. With some compilers or operating systems this name may require the addition of leading or trailing characters. For example, many Unix C compilers add a leading underscore to the beginning of a function name, and many Unix FORTRAN compilers add a trailing underscore.

Keywords

DEVICE

Set this keyword to indicate that the module being loaded contains a device driver.

FUNCT

Set this keyword to indicate that the module being loaded contains a function.

KEYWORDS

Set this keyword to indicate that the procedure or function being loaded accepts keyword parameters.

MAX_ARGS

An optional parameter containing the maximum number of non-keyword arguments the procedure or function accepts. If this parameter is not present, the maximum number of parameters is not checked when the routine is called.

MIN_ARGS

An optional parameter containing the minimum number of non-keyword arguments accepted by the procedure or function.

VMS Keywords

DEFAULT

A string containing the default device, directory, filename, and file type information for the file that contains the sharable image. This optional keyword parameter must be used if the sharable image is not in SYS$SHARE and a logical name is not used as the value of the Image argument.

Examples

To add a procedure called MY_PROC, whose entry symbol is also named MY_PROC, and whose file is pointed to by the logical name MY_PROC_EXE:

LINKIMAGE, 'MY_PROC', 'MY_PROC_EXE'

Under VMS, to add a device driver contained in the file DRA0:[SMITH]XXDRIV.EXE:

LINKIMAGE, 'XX_DEV', 'XXDRIV', $

           /DEVICE, DEFAULT='DRA0:[SMITH].EXE'

The global symbol XX_DEV, which contains the device definition structure, must be defined as universal within the sharable image.

Why Not Support LINKIMAGE under all Operating Systems?

One of the most common questions we are asked by Unix users is, "Why is LINKIMAGE only available on some platforms?" The answer is that these systems provide direct support for such operations in the form of the LIB$FIND_IMAGE_SYMBOL Run-Time Library function (VMS), dlopen(3) (SunOS), etc. Many systems do not provide such support. Although it is possible, with some programming, to support dynamic linking under Unix, such schemes suffer various problems:

•	Generally, the details of such linking differ between hardware platforms as well as individual releases of the operating system, resulting in a confusing situation which is difficult, if not impossible, to support.

•	We have encountered a few systems in which dynamic linking was not feasible.

•	Often, other desirable features must be disabled. For example, on one system, we discovered that dynamic linking causes the operating system to refuse to share text (read-only code) segments between processes.

•	Since such methods are unsupported by the operating system vendor, it is possible that the vendor could make changes that would make dynamic linking fail. This possibility makes supporting such a feature risky.

Many systems are making progress in this area, and we expect that dynamic linking will eventually be supported on such systems. As the necessary features become available, RSI will take advantage of them to bring LINKIMAGE to all of our users.

See Also

CALL_EXTERNAL, Operating System Access as described in Chapter 18 of the IDL User's Guide, Remote Procedure Calls as described in Chapter 24 of the IDL User's Guide, SPAWN


LJLCT

The LJLCT procedure loads standard color tables for LJ-250/252 printer. The color tables are modified on ly if the device is currently set to "LJ".

The default color maps used are for the 90 dpi color palette. There are only 8 colors available at 180 dpi.

If the current device is `LJ', the !D.N_COLORS system variable is used to determine how many bit planes are in use (1 to 4). The standard color map for that number of planes is loaded. These maps are described in Chapter 7 of the LJ250/LJ252 Companion Color Printer Programmer Reference Manual, Table 7-5. That manual gives the values scaled from 1 to 100, LJLCT scales them from 0 to 255.

This routine is written in the IDL language. Its source code can be found in the file ljlct.pro in the lib subdirectory of the IDL distribution.

Calling Sequence

LJLCT

Example

SET_PLOT, 'LJ'	Set plotting to the LJ device.

LJLCT	Load the LJ color tables.

See Also

SET_PLOT


LL_ARC_DISTANCE

The LL_ARC_DISTANCE function returns a two-element vector containing the longitude and latitude [lon, lat] of a point a given arc distance (-π ≤ Arc_Dist ≤ π), and azimuth (Az), from a specified location Lon_lat0. Values are in radians unless the keyword DEGREES is set.

This routine is written in the IDL language. Its source code can be found in the file ll_arc_distance.pro in the lib subdirectory of the IDL distribution.

Calling Sequence

Result = LL_ARC_DISTANCE(Lon_lat0, Arc_Dist, Az)

Arguments

Lon_lat0

A 2-element vector containing the longitude and latitude of the starting point. Values are assumed to be in radians unless the keyword DEGREES is set.

Arc_Dist

The arc distance from Lon_lat0. The value must be between - π and +π. To express distances in arc units, divide by the radius of the globe expressed in the original units. For example, if the radius of the earth is 6371 km, divide the distance in km by 6371 to obtain the arc distance.

Az

The azimuth from Lon_lat0. The value is assumed to be in radians unless the keyword DEGREES is set.

Keywords

DEGREES

Set this keyword to express all measurements and results in degrees.

Example

Lon_lat0 = [1.0, 2.0]	Initial point specified in radians

Arc_Dist = 2.0	Arc distance in radians

Az = 1.0	Azimuth in radians

Result = LL_ARC_DISTANCE(Lon_lat0, Arc_Dist, Az)

PRINT, Result

IDL prints:

2.91415 -0.622234

See Also

MAP_SET


LNGAMMA

The LNGAMMA function returns the logarithm of the gamma function of X. This function is undefined for negative integers. If the argument is double-precision, the result is double-precision. Otherwise, this function yields floating-point results.

Calling Sequence

Result = LNGAMMA(X)

Arguments

X

The expression for which the logarithm of the gamma function will be evaluated.

Example

To find the logarithm of the gamma function of 0.5 and store the result in variable A, enter:

A = LNGAMMA(0.5)

See Also

BETA, GAMMA,  IBETA, IGAMMA


LNP_TEST

The LNP_TEST function computes the Lomb Normalized Periodogram of two sample populations X and Y and tests the hypothesis that the populations represent a significant periodic signal against the hypothesis that they represent random noise. The result is a two-element vector containing the maximum peak in the Lomb Normalized Periodogram and its significance. The significance is a value in the interval [0.0, 1.0]; a small value indicates that a significant periodic signal is present.

LNP_TEST is based on the routine fasper described in section 13.8 of Numerical Recipes in C: The Art of Scientific Computing (Second Edition), published by Cambridge University Press, and is used by permission.

Calling Sequence

Result = LNP_TEST(X, Y)

Arguments

X

An n-element integer, single-, or double-precision floating-point vector containing equally or unequally spaced time samples.

Y

An n-element integer, single-, or double-precision floating-point vector containing amplitudes corresponding to Xi.

Keywords

HIFAC

Use this keyword to specify the scale factor of the average Nyquist frequency. The default value is 1.

JMAX

Use this keyword to specify a named variable that will contain the index of the maximum peak in the Lomb Normalized Periodogram.

OFAC

Use this keyword to specify the oversampling factor. The default value is 4.

WK1

Use this keyword to specify a named variable that will contain a vector of increasing linear frequencies.

WK2

Use this keyword to specify a named variable that will contain a vector of values from the Lomb Normalized Periodogram corresponding to the frequencies in WK1.

Example

Define two n-element sample populations.

X = [ 1.0,  2.0,  5.0,  7.0,  8.0,  9.0, $

     10.0, 11.0, 12.0, 13.0, 14.0, 15.0, $

     16.0, 17.0, 18.0, 19.0, 20.0, 22.0, $

     23.0, 24.0, 25.0, 26.0, 27.0, 28.0]

Y = [ 0.69502, -0.70425,  0.20632,  0.77206, -2.08339,  0.97806, $

      1.77324,  2.34086,  0.91354,  2.04189,  0.53560, -2.05348, $

     -0.76308, -0.84501, -0.06507, -0.12260,  1.83075,  1.41403, $

     -0.26438, -0.48142, -0.50929,  0.01942, -1.29268,  0.29697]

Test the hypothesis that X and Y represent a significant periodic signal against the hypothesis that they represent random noise.

result = LNP_TEST(X, Y, WK1 = wk1, WK2 = wk2, JMAX = jmax)

PRINT, result

IDL prints:

4.69296     0.198157

The small value of the significance represents the possibility of a significant periodic signal. A larger number of samples for X and Y would produce a more conclusive result. WK1 and WK2 are both 48-element vectors containing linear frequencies and corresponding Lomb values, respectively. JMAX is the indexed location of the maximum Lomb value in WK2.

See Also

CTI_TEST, FV_TEST, KW_TEST, MD_TEST, R_TEST, RS_TEST, S_TEST, TM_TEST, XSQ_TEST


LOADCT

The LOADCT procedure loads one of 41 predefined IDL color tables. These color tables are defined in the file colors1.tbl (located in the main IDL directory) unless the FILE keyword is specified. The selected colortable is loaded into the COLORS common block as both the "current" and "original" colortable. If the current device has fewer than 256 colors, the color table data is interpolated to cover the number of colors in the device.

This routine is written in the IDL language. Its source code can be found in the file loadct.pro in the lib subdirectory of the IDL distribution.

Calling Sequence

LOADCT  [, Table]

Arguments

Table

The number of the pre-defined color table to load, from 0 to 40. If this value is omitted, a menu of the available tables is printed and the user is prompted to enter a table number.

Keywords

BOTTOM

The first color index to use. LOADCT will use color indices from BOTTOM to BOTTOM+NCOLORS-1. The default is BOTTOM=0.

FILE

Set this keyword to the name of a colortable file to be used instead of the file colors1.tbl in the IDL directory. The MODIFYCT procedure (page 1-588) can be used to create and modify colortable files.

GET_NAMES

Set this keyword to a named variable in which the names of the color tables are returned as a string array. No changes are made to the color table.

NCOLORS

The number of colors to use. The default is all available colors (this number is stored in the system variable !D.TABLE_SIZE).

SILENT

If this keyword is set, the Color Table message is suppressed.

See Also

MODIFYCT, XLOADCT


LONARR

The LONARR function returns a longword integer vector or array.

Calling Sequence

Result = LONARR(D1, ..., Dn)

Arguments

Di

The dimensions of the result. The dimension parameters can be any scalar expression. Up to eight dimensions can be specified.

Keywords

NOZERO

Normally, LONARR sets every element of the result to zero. If NOZERO is set, this zeroing is not performed and LONARR executes faster.

Example

To create L, a 100-element, longword vector with each element set to 0, enter:

L = LONARR(100)

See Also

BYTARR, COMPLEXARR, DBLARR, DCOMPLEXARR, FLTARR, INTARR, MAKE_ARRAY, STRARR


LONG

The LONG function returns a result equal to Expression converted to longword integer type.

Calling Sequence

Result = LONG(Expression[, Offset [, Dim1, ..., Dimn]])

Arguments

Expression

The expression to be converted to longword integer.

Offset

Offset from beginning of the Expression data area. Specifying this argument allows fields of data extracted from Expression to be treated as longword integer data. See the description in Chapter 4 of the IDL User's Guide for details.

Di

When extracting fields of data, the Di arguments specify the dimensions of the result. The dimension parameters can be any scalar expression. Up to eight dimensions can be specified. If no dimension arguments are given, the result is taken to be scalar.

When converting from a string argument, it is possible that the string does not contain a valid longword integer and no conversion is possible. The default action in such cases is to print a warning message and return 0. The ON_IOERROR procedure can be used to establish a statement to be jumped to in case of such errors.

Example

If A contains the floating-point value 32000.0, it can converted to a longword integer and stored in the variable B by entering:

B = LONG(A)

See Also

BYTE, COMPLEX, DCOMPLEX, DOUBLE, FIX, FLOAT, STRING


LU_COMPLEX

The LU_COMPLEX function solves an n by n complex linear system Az = b using LU decomposition. The result is an n-element complex vector z. Alternatively, LU_COMPLEX computes the generalized inverse of an n by n complex array. The result is an n by n complex array.

This routine is written in the IDL language. Its source code can be found in the file lu_complex.pro in the lib subdirectory of the IDL distribution.

Calling Sequence

Result = LU_COMPLEX(A, B)

Arguments

A

An n by n complex array.

B

An n-element right-hand side vector (real or complex).

Keywords

DOUBLE

Set this keyword to force the computation to be done in double-precision arithmetic.

INVERSE

Set this keyword to compute the generalized inverse of A. If INVERSE is specified, the input argument B is ignored.

SPARSE

Set this keyword to convert the input array to row-indexed sparse storage format. Computations are done using the iterative biconjugate gradient method. This keyword is effective only when solving complex linear systems. This keyword has no effect when calculating the generalized inverse.

Example

Define a complex array A and right-side vector B :

A = [[COMPLEX(1, 0), COMPLEX(2,-2), COMPLEX(-3,1)], $

     [COMPLEX(1,-2), COMPLEX(2, 2), COMPLEX(1, 0)], $

     [COMPLEX(1, 1), COMPLEX(0, 1), COMPLEX(1, 5)]]

B =  [COMPLEX(1, 1), COMPLEX(3,-2), COMPLEX(1,-2)]

Solve the complex linear system Az = b.

Z = LU_COMPLEX(A, B)

PRINT, Z

IDL prints:

(     0.552267,      1.22818)(    -0.290371,    -0.600974)

(    -0.629824,    -0.340952)

Compute the inverse of the complex array A by supplying a scalar for B (in this example -1).

inv = LU_COMPLEX(A, B, /INVERSE)

PRINT, inv

IDL prints:

(     0.261521,   -0.0303485)(    0.0138629,     0.329337)

(    -0.102660,    -0.168602)

(     0.102660,     0.168602)(    0.0340952,    -0.162982)

(     0.125890,   -0.0633196)

(   -0.0689397,    0.0108655)(   -0.0666916,   -0.0438366)

(    0.0614462,    -0.161858)

See Also

CRAMER, GS_ITER, CHOLSOL, LUSOL, SVSOL, TRISOL, and "Sparse Arrays" on page 20-35 of the IDL User's Guide.


LUDC

The LUDC procedure replaces an n by n array,  A, with the LU decomposition of a row-wise permutation of itself.

LUDC is based on the routine ludcmp described in section 2.3 of Numerical Recipes in C: The Art of Scientific Computing (Second Edition), published by Cambridge University Press, and is used by permission.

Calling Sequence

LUDC,  A, Index

Arguments

A

An n by n array of any type except string. Upon output, A is replaced with its LU decomposition.

Index

An output vector that records the row permutations which occurred as a result of partial pivoting.

Keywords

COLUMN

Set this keyword if the input array A is in column-major format (composed of column vectors) rather than in row-major format (composed of row vectors).

DOUBLE

Set this keyword to force the computation to be done in double-precision arithmetic.

INTERCHANGES

An output variable that is set to positive 1 if the number of row interchanges was even, or to negative 1 if the number of interchanges was odd.

Example

See the description of LUSOL for an example using this function.

See Also

LUSOL


LUMPROVE

The LUMPROVE function uses LU decomposition to iteratively improve an approximate solution X of a set of n linear equations in n unknowns Ax = b. The result is a vector, whose type and length are identical to X, containing the improved solution.

LUMPROVE is based on the routine mprove described in section 2.5 of Numerical Recipes in C: The Art of Scientific Computing (Second Edition), published by Cambridge University Press, and is used by permission.

Calling Sequence

Result = LUMPROVE(A, Alud, Index, B, X)

Arguments

A

The n by n coefficient array of the linear system Ax = b.

Alud

The n by n LU decomposition of  A created by the LUDC procedure.

Index

An input vector, created by the LUDC procedure, containing a record of the row permutations which occurred as a result of partial pivoting.

B

An n-element vector containing the right-hand side of the linear system
 Ax = b.

X

An n-element vector containing the approximate solution of the linear system
Ax = b.

Keywords

COLUMN

Set this keyword if the input array A is in column-major format (composed of column vectors) rather than in row-major format (composed of row vectors).

DOUBLE

Set this keyword to force the computation to be done in double-precision arithmetic.

Example

Use LUMPROVE to improve an approximate solution X to the linear system Ax = B:

A = [[ 2.0,  1.0,  1.0], $	Create coefficient array A.

     [ 4.0, -6.0,  0.0], $

     [-2.0,  7.0,  2.0]]

alud = A	Create a duplicate of A.

B = [3.0, -8.0, 10.0]	Define the right-hand side vector B.

X = [.89, 1.78, -0.88]	Begin with an estimated solution X.

LUDC, alud, INDEX	Decompose the duplicate of A.

result = LUMPROVE(A, alud, INDEX, B, X)

Compute an improved solution.

PRINT, result	Print it.

IDL prints:

 1.00000 2.00000 -1.00000

This is the exact solution vector.

See Also

GS_ITER, LUDC


LUSOL

The LUSOL function is used in conjunction with the LUDC procedure to solve a set of n linear equations in n unknowns Ax = b. The parameter A is input not as the original array, but as its LU decomposition, created by the routine LUDC. The result is an n-element vector whose type is identical to A.

LUSOL is based on the routine lubksb described in section 2.3 of Numerical Recipes in C: The Art of Scientific Computing (Second Edition), published by Cambridge University Press, and is used by permission.

Calling Sequence

Result = LUSOL(A, Index, B)

Arguments

A

The n by n LU decomposition of an array created by the LUDC procedure.

Index

An input vector, created by the LUDC procedure, containing a record of the row permutations which occurred as a result of partial pivoting.

B

An n-element vector containing the right-hand side of the linear system
 Ax = b.

Keywords

COLUMN

Set this keyword if the input array A is in column-major format (composed of column vectors) rather than in row-major format (composed of row vectors).

DOUBLE

Set this keyword to force the computation to be done in double-precision arithmetic.

Example

To solve the linear system Ax = b using LU decomposition and back substitution:

A = [[ 2.0,  1.0,  1.0], $	Define array A.

     [ 4.0, -6.0,  0.0], $

     [-2.0,  7.0,  2.0]]

B = [3.0, -8.0, 10.0]	Define right-hand side vector B.

LUDC, A, INDEX	Decompose A.

result = LUSOL(A, INDEX, B)	Compute the solution using back
substitution.

PRINT, result	Print the result.

IDL prints:

  1.00000  2.00000 -1.00000

This is the exact solution vector.

See Also

CHOLSOL, CRAMER, GS_ITER, LU_COMPLEX, LUDC, SVSOL, TRISOL


M_CORRELATE

The M_CORRELATE function computes the multiple correlation coefficient of a dependent variable and two or more independent variables.

This routine is written in the IDL language. Its source code can be found in the file m_correlate.pro in the lib subdirectory of the IDL distribution.

Calling Sequence

Result = M_CORRELATE(X, Y)

Arguments

X

An integer, single-, or double-precision floating-point array of m-columns and n-rows that specifies the independent variable data. The columns of this two dimensional array correspond to the n-element vectors of independent variable data.

Y

An n-element integer, single-, or double-precision floating-point vector that specifies the dependent variable data.

Example

Define the independent (X) and dependent (Y) data.

X = [[0.477121, 2.0, 13.0], $

     [0.477121, 5.0, 6.0], $

     [0.301030, 5.0, 9.0], $

     [0.000000, 7.0, 5.5], $

     [0.602060, 3.0, 7.0], $

     [0.698970, 2.0, 9.5], $

     [0.301030, 2.0, 17.0], $

     [0.477121, 5.0, 12.5], $

     [0.698970, 2.0, 13.5], $

     [0.000000, 3.0, 12.5], $

     [0.602060, 4.0, 13.0], $

     [0.301030, 6.0, 7.5], $

     [0.301030, 2.0, 7.5], $

     [0.698970, 3.0, 12.0], $

     [0.000000, 4.0, 14.0], $

     [0.698970, 6.0, 11.5], $

     [0.301030, 2.0, 15.0], $

     [0.602060, 6.0, 8.5], $

     [0.477121, 7.0, 14.5], $

     [0.000000, 5.0, 9.5]]

Y = [97.682, 98.424, 101.435, 102.266, 97.067, 97.397, $

     99.481, 99.613, 96.901, 100.152, 98.797, 100.796, $

     98.750, 97.991, 100.007, 98.615, 100.225, 98.388, $

     98.937, 100.617]

Compute the multiple correlation of Y on the first column of X. The result should be 0.798816.

PRINT, M_CORRELATE(X(0,*), Y)

IDL prints:

0.798816

Compute the multiple correlation of Y on the first two columns of X. The result should be 0.875872.

PRINT, M_CORRELATE(X(0:1,*), Y)

IDL prints:

0.875872

Compute the multiple correlation of Y on all columns of X. The result should be 0.877197.

PRINT, M_CORRELATE(X, Y)

IDL prints:

0.877197

See Also

A_CORRELATE, CORRELATE, C_CORRELATE, P_CORRELATE, R_CORRELATE


MACHAR

The MACHAR function determines and returns machine-specific parameters affecting floating-point arithmetic. Information is returned in the form of a structure with the following fields:

Field Name	Description
IBETA	The radix in which numbers are represented. A longword integer.
IT	The number of base-IBETA digits in the floating-point mantissa M. A longword integer.
IRND	A code in the range 0 ­ 5 giving information on what type of rounding is done and how underflow is handled. A longword integer.
NGRD	The number of "guard digits" used when truncating the product of two mantissas. A longword integer.
MACHEP	The exponent of the smallest power of IBETA that, added to 1.0, gives something different from 1.0. A longword integer.
NEGEP	The exponent of the smallest power of IBETA that, subtracted from 1.0, gives something different from 1.0. A longword integer.
IEXP	The number of bits in the exponent. A longword integer.
MINEXP	The smallest value of IBETA consistent with there being no leading zeros in the mantissa. A longword integer.
MAXEXP	The smallest positive value of IBETA that causes overflow. A longword integer.
EPS	The floating-point number IBETA^MACHEP, loosely referred to as the "floating-point precision."
EPSNEG	The floating-point number IBETA^NEGEP, which is another way of determining floating-point precision.
XMIN	The floating-point number IBETA^MINEXP, generally the smallest usable floating-point value.
XMAX	The largest usable floating-point value, defined as the number (1-EPSNEG)xIBETA^MAXEXP
MACHAR is based on the routine machar described in section 20.1 of Numerical Recipes in C: The Art of Scientific Computing (Second Edition), published by Cambridge University Press, and is used by permission. See that section for more details on and sample values of the various parameters returned.

Calling Sequence

Result = MACHAR()

Keywords

DOUBLE

The information returned is normally for single-precision floating-point arithmetic. Specify DOUBLE to see double-precision information.

See Also

CHECK_MATH and "!VALUES" on page 3-8 of the IDL User's Guide.


MAKE_ARRAY

The MAKE_ARRAY function returns an array of the specified type, dimensions, and initialization. This function enables you to dynamically create an array whose characteristics are not known until run time.

Calling Sequence

Result = MAKE_ARRAY([D1, ..., Dn])

Arguments

Di

The dimensions of the result. The dimension parameters can be any scalar expression. Up to eight dimensions can be specified.

Keywords

BYTE

Set this keyword to create a byte array.

COMPLEX

Set this keyword to create a complex, single-precision, floating-point array.

DCOMPLEX

Set this keyword to create a complex, double-precision, floating-point array.

DIMENSION

A vector of 1 to 8 elements specifying the dimensions of the result.

DOUBLE

Set this keyword to create a double-precision, floating-point array.

FLOAT

Set this keyword to create a single-precision, floating-point array.

INDEX

Set this keyword to initialize the array with each element set to the value of its one-dimensional subscript.

INT

Set this keyword to create an integer array.

LONG

Set this keyword to create a longword integer array.

NOZERO

Set this keyword to prevent the initialization of the array. Normally, each element of the resulting array is set to zero.

SIZE

A size vector specifying the type and dimensions of the result. The format of a size vector is given in the description of the SIZE function.

STRING

Set this keyword to create a string array.

TYPE

The type code to set the type of the result. See the description of the SIZE function for a list of IDL type codes.

VALUE

The value to initialize each element of the resulting array. VALUE can be a scalar of any type including structure types. The result type is taken from VALUE unless one of the other keywords that specify a type is also set. In that case, VALUE is converted to the type specified by the other keyword prior to initializing the resulting array.

Example

To create M, a 3-element by 4-element, integer array with each element set to the value 5, enter:

M = MAKE_ARRAY(3, 4, /INTEGER, VALUE = 5)

See Also

BYTARR, COMPLEXARR, DBLARR, DCOMPLEXARR, FLTARR, INTARR, LONARR, REPLICATE, STRARR


MAP_CONTINENTS

The MAP_CONTINENTS procedure draws continental boundaries, filled continents, political boundaries, coastlines, and/or rivers, over an existing map projection established by MAP_SET. Outlines can be drawn in low or high-resolution (if the optional high-resolution CIA World Map database is installed). If MAP_CONTINENTS is called without any keywords, it draws low-resolution, unfilled continent outlines.

MAP_SET must be called before MAP_CONTINENTS to establish the projection type, the center of the projection, polar rotation and geographic limits.

Calling Sequence

MAP_CONTINENTS

Keywords

COASTS

Set this keyword to draw coastlines, islands, and lakes instead of the default continent outlines. Note that if you are using the low-resolution map database (if the HIRES keyword is not set), many islands are drawn even when COASTS is not set. If you are using the high-resolution map database (if the HIRES keyword is set), no islands are drawn unless COASTS is set.

COLOR

The color index of the lines being drawn.

COUNTRIES

Set this keyword to draw political boundaries as of 1993.

FILL_CONTINENTS

Set this keyword to 1 to fill continent boundaries with a solid color. The color is set by the COLOR keyword. Set this keyword to 2 to fill continent boundaries with a line fill. For line filling, the COLOR, MLINESTYLE, MLINETHICK, ORIENTATION, and SPACING keywords can be used to control the type of line fill.

See "Notes on Filling Continental Boundaries" for information on known problems with the continent-filling algorithm.

HIRES

Set this keyword to use high-resolution map data instead of the default low-resolution data. This option is only available if you have installed the optional high-resolution map datasets. If the high-resolution data is not available, a warning is printed and the low-resolution data is used instead.

This keyword can be used in conjunction with the COASTS, COUNTRIES, FILL_CONTINENTS, RIVERS, and POLYGONS keywords.

MLINESTYLE

The line style of the boundaries being drawn. The default is solid lines. Valid linestyles are shown in the table below:

Index	Linestyle
0	Solid
1	Dotted
2	Dashed
3	Dash Dot
4	Dash Dot Dot Dot
5	Long Dashes
Table 1.8 IDL Linestyles

MLINETHICK

The thickness of the boundary or fill lines. The default thickness is 1.

ORIENTATION

Set this keyword to the counterclockwise angle in degrees from horizontal that the line fill should be drawn. The default is 0. This keyword only has effect if the FILL_CONTINENTS keyword is set to 2.

RIVERS

Set this keyword to draw rivers.

SPACING

Set this keyword to the spacing, in centimeters, for a line fill. This keyword only has effect if the FILL_CONTINENTS keyword is set to 2. The default is 0.5 centimeters.

USA

Set this keyword to draw borders for each state in the United States in addition to continental boundaries.

Example

The following example demonstrates the use of the high-resolution map outlines to embellish a map projection:

LOADCT, 12	Load an appropriate colortable.

WINDOW, /FREE, COLORS=16	Create a new window for the map. We've allocated only 16 colors for this window.

black = 0*16 & white = 15*16	Match color indices to colors we want to use.

red = 10*16 & lt_green=3*16

lt_blue = 5*16 & dk_blue=6*16

ERASE, lt_blue	Erase the background to light blue.

MAP_SET, -10, 100, 23, /ORTHO, /ISO, /GRID, /HORIZON, $

    COLOR=black, /NOERASE	Set up an orthographic projection with black gridlines.

MAP_CONTINENTS, /FILL_CONTINENTS, COLOR=white
Fill the continent boundaries with solid white.

MAP_CONTINENTS, /COASTS, COLOR=black, MLINETHICK=0.5
Overplot coastline data.

MAP_CONTINENTS, /RIVERS, COLOR=dk_blue, MLINETHICK=0.5
Add rivers, in dark blue.

MAP_CONTINENTS, /COUNTRIES, COLOR=red, MLINETHICK=1.5
Show national borders.

See Also

MAP_GRID, MAP_IMAGE, MAP_PATCH, MAP_SET


MAP_GRID

The MAP_GRID procedure draws the graticule of parallels and meridians, according to the specifications established by MAP_SET. MAP_SET must be called before MAP_GRID to establish the projection type, the center of the projection, polar rotation and geographical limits.

Calling Sequence

MAP_GRID

Keywords

CHARSIZE

The size of the characters used for the labels. The default is 1.

COLOR

The color index for the grid lines.

LABEL

Set this keyword to label the parallels and meridians with their corresponding latitudes and longitudes.

LATALIGN

This keyword controls the alignment of the text baseline for latitude labels. A value of 0.0 left justifies the label, 1.0 right justifies it, and 0.5 centers it.

LATDEL

The spacing in degrees between parallels of latitude in the grid. The default is the 10 or (Maximum Latitude - Minimum Latitude)/10.0, whichever is smallest.

LATLAB

The longitude at which to place latitude labels. The default is the center longitude on the map.

LONALIGN

This keyword controls the alignment of the text baseline for longitude labels. A value of 0.0 left justifies the label, 1.0 right justifies it, and 0.5 centers it.

LONDEL

The spacing in degrees between meridians of longitude. The default is 10 or (Maximum Latitude - Minimum Latitude)/10.0, whichever is smallest.

LONLAB

The latitude at which to place longitude labels. The default is the center latitude on the map.

GLINESTYLE

If set, the line style used to draw the grid of parallels and meridians. See the IDL User's Guide for options. The default is dotted.

GLINETHICK

The thickness of the grid lines. Default is 1.

See Also

MAP_CONTINENTS, MAP_IMAGE, MAP_PATCH, MAP_SET


MAP_IMAGE

The MAP_IMAGE function returns an image (or other dataset) warped to fit the current map projection (specified by the system variable !MAP). The MAP_SET procedure should be called prior to calling MAP_IMAGE.

This function provides an easy method for displaying geographical data as an image on any map that encloses a mathematically convex region (i.e., any two points on the map can be joined by a straight line that lies completely within the map boundary).

Calling Sequence

Result = MAP_IMAGE(Image [, Startx, Starty [, Xsize, Ysize]])

Arguments

Image

A two-dimensional array containing the image to be overlaid on the map.

Startx

A named variable that, upon return, contains the X coordinate position where the left edge of the image should be placed on the screen.

Starty

A named variable that, upon return, contains the Y coordinate position where the left edge of the image should be placed on the screen.

Xsize

A named variable that, upon return, contains the width of the image expressed in graphic coordinate units. If the current graphics device uses scalable pixels, the values of  Xsize and Ysize should be passed to the TV procedure.

Ysize

A named variable that, upon return, contains the height of the image expressed in graphic coordinate units. If the current graphics device uses scalable pixels, the values of  Xsize and Ysize should be passed to the TV procedure.

Keywords

LATMIN

The latitude corresponding to the first row of Image. The default is -90 degrees. Note also that -90° ≤ LATMIN < LATMAX ≤ 90°.

LATMAX

The latitude corresponding to the last row of Image. The default value is 90 degrees. Note also that -90° ≤ LATMIN < LATMAX ≤ 90°.

LONMIN

The longitude corresponding to the first column of Image. The default is -180 degrees. Note also that -180° ≤ LONMIN < LONMAX ≤ 180°.

LONMAX

The longitude corresponding to the last column of Image. The default is 180 degrees. Note also that -180° ≤ LONMIN < LONMAX ≤ 180°.

BILINEAR

Set this flag to use bilinear interpolation to soften edges in the returned image.

COMPRESS

This keyword, the interpolation compression flag, controls the accuracy of the results from MAP_IMAGE. The default is 4 for output devices with fixed pixel sizes. Setting this keyword to a higher number saves time while lower numbers produce more accurate results. Setting this keyword to 1 solves the inverse map transformation for every pixel of the output image.

WHOLE_MAP

Set this keyword to defeat the code that determines the extent of the image on the map. Some projections are so complex (especially the SATELLITE) that it is difficult to find where the image goes on the map. Setting this keyword computes the entire map, at the cost of more time. For images that cover the entire map, setting this keyword produces no penalty.

SCALE

Set this keyword to the pixel/graphics scale factor for devices with scalable pixels (e.g., PostScript). The default is 0.02 pixels/graphic coordinate. This setting yields an approximate output image size of 350 x 250. Make this number larger for more resolution (and larger PostScript files and images), or smaller for faster, smaller, and less accurate images.

MAX_VALUE

Data points with values equal to or greater than this value will be treated as missing data, and will be set to the value specified by the MISSING keyword.

MIN_VALUE

Data points with values equal to or less than this value will be treated as missing data, and will be set to the value specified by the MISSING keyword.

MISSING

The pixel value to set areas outside the valid map coordinates. If this keyword is omitted, areas outside the map are set to 255 (white) if the current graphics device is PostScript, otherwise they are set to 0.

Example

The following lines of code set up an orthographic map projection and warp a simple image to it.

IMAGE = BYTSCL(SIN(DIST(400)/10))	Create a simple image to be warped.

TV, IMAGE	Display the image so we can see what it looks like before warping.

MAP_SET, 45, /ORTHO, TITLE="Orthographic Projection with Image"
Set up an orthographic projection.

newimage = MAP_IMAGE(image, startx, starty, /BILIN)
Return an image, warped to the entire map projection, in the variable newimage. Bilinear interpolation is also turned on.

TV, newimage, startx, starty	Display the warped image on the map at the proper position.

MAP_GRID	Draw gridlines over the map and image.

MAP_CONTINENTS	Draw continent outlines.

See Also

MAP_CONTINENTS, MAP_GRID, MAP_PATCH, MAP_SET


MAP_PATCH

The MAP_PATCH function returns an image (or other dataset) warped to fit the current map projection (specified by the system variable !MAP). Mapping coordinates should be setup via a call to MAP_SET before using MAP_PATCH.

MAP_PATCH uses a technique different from the one MAP_IMAGE uses to perform the warping. For some applications, MAP_PATCH may give better results than MAP_IMAGE because it works in image (graphic) space rather than in object (data) space. Each rectangular cell is divided by a diagonal into two triangles. MAP_PATCH then uses TRIGRID to interpolate the image array into latitude/longitude space.

This routine is written in the IDL language. Its source code can be found in the file map_patch.pro in the lib subdirectory of the IDL distribution.

Calling Sequence

Result = MAP_PATCH(Image_Orig [, Lons, Lats])

Arguments

Image_Orig

A two-dimensional array that contains the data to be overlaid on the map. Rows and columns must be arranged in increasing longitude and latitude order. Also, the corner points of each cell must be contiguous. This means that the seam of a map must lie on a cell boundary, not in its interior, splitting the cell.

Lons

An optional vector that contains the longitude value for each column in Image_Orig. This vector must have the same number of elements as Image_Orig has columns (i.e., longitude(Image_Orig (i, j) = Lons(i)).

This argument can be omitted if the longitudes are equally-spaced and the beginning and ending longitudes are specified with the LON0 and LON1 keywords.

Lats

An optional vector that contains the latitude value for each row in Image_Orig . This vector must have the same number of elements as Image_Orig has rows (i.e., latitude(Image_Orig(i, j) = Lats( j)).

This argument can be omitted if the latitudes are equally-spaced and the beginning and ending latitudes are specified with the LAT0 and LAT1 keywords.

Keywords

LAT0

The latitude of the first column of data. The default is -90.

LAT1

The latitude of the last column of data. The default is +90.

LON0

The longitude of the first row of data. The default is -180.

LON1

The longitude of the last row of data. The default is 180 - (360/Number-of-Rows)

MISSING

Set this keyword to a value to be used for areas outside the valid map coordinates (i.e., the "background color"). If the current plotting device is PostScript, the default is 255 (white). Otherwise, the default is 0 (usually black).

MAX_VALUE

The largest data value to be warped. Values in Image_Orig greater than this value are considered missing. Pixels in the output image that correspond to these missing values are set to the value specified by the MISSING keyword.

TRIANGULATE

Set this keyword to convert the input data to device space and triangulate them. This keyword must be specified if the connectivity of the data points is not rectangular and monotonic in device space.

XSIZE

Set this keyword to a named variable in which the width of the output image is returned, in graphic coordinate units. If the current graphics device has scalable pixels (e.g., PostScript), the values returned by XSIZE and YSIZE should be passed to the TV procedure.

XSTART

Set this keyword to a named variable in which the X coordinate where the left edge of the image should be placed on the screen is returned.

YSIZE

Set this keyword to a named variable in which the height of the output image is returned, in graphic coordinate units. If the current graphics device has scalable pixels (e.g., PostScript), the values returned by XSIZE and YSIZE should be passed to the TV procedure.

YSTART

Set this keyword to a named variable in which the Y coordinate where the bottom edge of the image should be placed on the screen is returned.

Example

image = BYTSCL(SIN(DIST(400)/10))	Create a simple image to be warped.

TV, image	Display the image so we can see what it looks like before warping.

MAP_SET, 45, /ORTHO, TITLE="Orthographic Projection with Image"
Set up an orthographic projection.

newimage = MAP_PATCH(image, XSTART=X, YSTART=Y)
Return an image, warped to the entire map projection (the default area to warp), in the variable newimage. Correct positions in which to display the image are returned in the x and y variables.

TV, newimage, X, Y	Display the warped image on the map at the proper position.

MAP_GRID	Draw gridlines over the map and image.

MAP_CONTINENTS	Draw continent outlines.

See Also

MAP_CONTINENTS, MAP_GRID, MAP_IMAGE, MAP_SET


MAP_SET

The MAP_SET procedure establishes the axis type and coordinate conversion mechanism for mapping points on the earth's surface, expressed in latitude and longitude, to points on a plane, according to one of several possible map projections.

The type of map projection, the map center, polar rotation and geographical limits can all be customized. The system variable !MAP retains the information needed to effect coordinate conversions to the plane and, inversely, from the projection plane to points on the earth in latitude and longitude. Users should not change the values of the fields in !MAP directly.

MAP_SET can also be made to plot the grid of latitude and longitude lines and continental boundaries by setting the keywords GRID and CONTINENT. Many other types of boundaries can be overplotted on maps using the MAP_CONTINENTS procedure.

Calling Sequence

MAP_SET [, P0lat, P0lon, Rot]

Arguments

P0lat

For all but Lambert's conformal conic projection with two standard parallels, P0lat is the latitude of the point on the earth's surface to be mapped to the center of the projection plane. If the projection type is sinusoidal, P0lat must be 0.

Latitude is measured in degrees North of the equator and P0lat must be in the range: -90° ≤ P0lat ≤ 90°.

If P0lat is not set, the default value is 0.

For Lambert's conformal conic projection with two standard parallels (i.e., the CONIC keyword is set), P0lat should be set to the latitude in degrees of one of the parallels. If either P0lat or P0lon  is omitted, P0lat is 20° by default.

P0lon

For all but Lambert's conformal conic projection with two standard parallels, P0lon is the longitude of the point on the earth's surface to be mapped to the center of the map projection.

Longitude is measured in degrees east of the Greenwich meridian and P0lon must be in the range: -180 ° ≤ P0lon ≤ 180°.

If P0lon is not set, the default value is zero.

For Lambert's conformal conic projection with two standard parallels (i.e, the CONIC keyword is set), P0lon should be set to the latitude in degrees of the other standard parallel. If either P0lon or P0lat  is omitted, P0lon is set to 60°.

Rot

Rot is the angle through which the North direction should be rotated around the line L between the earth's center and the point (P0lat, P0lon). Rot is measured in degrees with the positive direction being clockwise rotation around line L. Rot can have values from -180° to 180°.

For cylindrical maps and the Mollweide projection, Rot should not be set to precisely 180 or -180.

If the center of the map is at the North pole, North is in the direction P0lon + 180°. If the origin is at the South pole, North is in the direction P0lon.

The default value of  Rot is 0 degrees.

Keywords —Projection Types

AITOFF

Set this keyword to select the Hammer-Aitoff equal area projection.

AZIMUTHAL

Set this keyword to select the azimuthal equidistant projection.

CONIC

Set this keyword to select Lambert's conformal conic projection with two standard parallels.

CYLINDRICAL

Set this keyword to select the cylindrical equidistant projection. Cylindrical is the default map projection.

GNOMIC

Set this keyword to select the gnomonic projection.

LAMBERT

Set this keyword to select Lambert's equal area projection.

MERCATOR

Set this keyword to select the Mercator projection.

MOLLWEIDE

Set this keyword to select the Mollweide projection.

ORTHOGRAPHIC

Set this keyword to select the orthographic projection.

SATELLITE

Set this keyword to select the satellite projection.

For the satellite projection, P0LAT and P0LON represent the latitude and longitude of the sub-satellite point. Three additional parameters, P,  Omega, and Gamma (supplied as a three-element vector argument to the SAT_P keyword), are also required.

Note that since all meridians and parallels are oblique lines or arcs, the LIMIT keyword must be supplied as an eight-element vector representing four points that delineate the limits of the map. The extent of the map limits, when expressed in latitude/longitude is a complicated polygon, rather than a simple quadrilateral.

SAT_P

A three-element vector containing three parameters, P, Omega, and Gamma, that must be supplied when using the SATELLITE projection where:

•	P is the distance of the point of perspective (camera) from the center of the globe, expressed in units of the radius of the globe.

•	Omega is the downward tilt of the camera, in degrees from the new horizontal. If both Gamma and Omega are 0, a Vertical Perspective projection results.

•	Gamma is the angle, expressed in degrees clockwise from north, of the rotation of the projection plane.

SINUSOIDAL

Set this keyword to select the sinusoidal projection.

STEREOGRAPHIC

Set this keyword to select the stereographic projection.

Keywords—Map Characteristics

ADVANCE

Set this keyword to advance to the next frame when the screen is set to display multiple plots. Otherwise the entire screen is erased.

CHARSIZE

The size of the characters used for the labels. The default is 1.

COLOR

The color index of the map border in the plotting window.

CONTINENTS

Set this keyword to plot the continental boundaries. Note that if you are using the low-resolution map database (if the HIRES keyword is not set), outlines for continents, islands, and lakes are drawn when the CONTINENTS keyword is set. If you are using the high-resolution map database (if the HIRES keyword is set), only continental outlines are drawn when the CONTINENTS keyword is set. To draw islands and lakes when using the high-resolution map database, use the COASTS keyword to the MAP_CONTINENTS procedure.

CON_COLOR

The color index for continent outlines if CONTINENTS is set.

GLINESTYLE

The line style index used to draw the grid of parallels and meridians. See the IDL User's Guide for options. The default is dotted.

GLINETHICK

The thickness of the gridlines drawn if the GRID keyword is set. The default is 1.

GRID

Set this keyword to draw the grid of parallels and meridians.

HIRES

Set this keyword to use the high-resolution continent outlines when drawing continents. This keyword only has effect if the CONTINENTS keyword is also set.

HORIZON

Set this keyword to draw a horizon line, when the projection in use permits. The HORIZON keyword has no effect with the CYLINDRICAL, GNOMIC, or MERCATOR projections.

ISOTROPIC

Set this keyword to produce a map that has the same scale in the X and Y directions.

LABEL

Set this keyword to label the parallels and meridians with their corresponding latitudes and longitudes.

LATALIGN

The alignment of the text baseline for latitude labels. A value of 0.0 left justifies the label, 1.0 right justifies it, and 0.5 centers it.

LATLAB

The longitude at which to place latitude labels. The default is the center longitude of the map.

LATDEL

The spacing in degrees between parallels of latitude drawn by the procedure MAP_GRID. The default is 10 or (Latmax - Latmin )/10.0, whichever is smallest.

LIMIT

A four- or eight-element vector that specifies the limits of the map.

As a four-element vector, LIMIT has the form [Latmin, Lonmin , Latmax, Lonmax] that specifies the boundaries of the region to be mapped. (Latmin, Lonmin) and (Latmax, Lonmax) are the latitudes and longitudes of two points diagonal from each other on the region's boundary.

Latmin  must be less than Latmax and Lonmin must be less than Lonmax.

To plot the desired region of the globe, it may be necessary for Lonmin to be less than -180 or Lonmax to exceed 180. For example, if the center of the map is at (0, -45) and the user wants to map a region 150° in longitude on either side of the center, then Lonmin should be set to -195 and Lonmax to 105.

As an eight-element vector, LIMIT has the form: [Lat0, Lon0, Lat1, Lon1, Lat2, Lon2, Lat3, Lon3]. These four latitude/longitude pairs describe, respectively, four points on the left, top, right, and bottom edges of the map extent.

LONALIGN

The alignment of the text baseline for longitude labels. A value of 0.0 left justifies the label, 1.0 right justifies it, and 0.5 centers it.

LONDEL

The spacing in degrees between meridians of longitude drawn by the procedure MAP_GRID. The default is 10 or (Lonmax - Lonmin)/10.0, whichever is smaller.

LONLAB

The latitude at which to place longitude labels. The default is the center latitude of the map.

MLINESTYLE

The line style index used for continental boundaries. Linestyles are described in the table below. The default is 0 for solid.

Index	Linestyle
0	Solid
1	Dotted
2	Dashed
3	Dash Dot
4	Dash Dot Dot Dot
5	Long Dashes
Table 1.9 IDL Linestyles

MLINETHICK

The line thickness used for continental boundaries. The default is 2.

NOBORDER

Set this keyword to not draw a border around the map.

NOERASE

Set this keyword to have MAP_SET not erase the current plot window. The default is to erase before drawing the map.

TITLE

A string containing the main title for the map. The title appears centered above the map window.

USA

Set this keyword to draw borders for each state in the United States.

WHOLE_MAP

Set this keyword to defeat the code that determines the extent of the image on the map. Some projections are so complex (especially the SATELLITE) that it is difficult to find where the image goes on the map. Setting this keyword computes the entire map, at the cost of more time. For images that cover the entire map, setting this keyword produces no penalty.

XMARGIN

A two-element vector that specifies the vertical margin between the map and screen border in character units.

YMARGIN

A two-element vector that specifies in the horizontal margin between the map and screen border in character units.

Graphics Keywords Accepted

See Chapter 2, "Graphics Keywords and System Variables", for the description of graphics and plotting keywords not listed above. POSITION T3D ZVALUE.

See Also

MAP_CONTINENTS, MAP_GRID, MAP_IMAGE


MAX

The MAX function returns the value of the largest element of Array. The type of the result is the same as the type of Array.

Calling Sequence

Result = MAX(Array [, Max_Subscript])

Arguments

Array

The array to be searched.

Max_Subscript

A named variable that, if supplied, is converted to a long integer containing the one-dimensional subscript of the maximum element. Otherwise, the system variable !C is set to the one-dimensional subscript of the maximum element.

Keywords

MIN

A named variable to receive the value of the minimum array element. If you need to find both the minimum and maximum array values, use this keyword to avoid scanning the array twice with separate calls to MAX and MIN.

NAN

Set this keyword to cause the routine to check for occurrences of the IEEE floating-point value NaN in the input data. Elements with the value NaN are treated as missing data. (See  "Special Floating-Point Values" on page 11-9 of the IDL User's Guide for more information on IEEE floating-point values.)

Example

Create a simple two-dimensional array by entering:

D = DIST(100)

Print the maximum value in array D and its linear subscript by entering:

PRINT, MAX(D, I), I

IDL prints:

   70.7107   5050

To convert I to a two-dimensional subscript, use the commands:

IX = I MOD 100

IY = I/100

PRINT, IX, IY

The maximum value of D is at location (50, 50) in the original array.

See Also

MIN


MD_TEST

The MD_TEST function tests the hypothesis that a sample population is random against the hypothesis that it is not random. The result is a two-element vector containing the nearly-normal test statistic Z and the one-tailed probability of obtaining a value of Z or greater. This test is often referred to as the Median Delta Test.

This routine is written in the IDL language. Its source code can be found in the file md_test.pro in the lib subdirectory of the IDL distribution.

Calling Sequence

Result = MD_TEST(X)

Arguments

X

An n-element integer, single- or double-precision floating-point vector.

Keywords

ABOVE

Use this keyword to specify a named variable that will contain the number of sample population values greater than the median of X.

BELOW

Use this keyword to specify a named variable that will contain the number of sample population values less than the median of X.

MDC

Use this keyword to specify a named variable that will contain the number of Median Delta Clusters (sequential values of X above and below the median).

Example

Define a sample population.

X = [ 2.00,  0.90, -1.44, -0.88, -0.24,  0.83, -0.84, -0.74, $

      0.99, -0.82, -0.59, -1.88, -1.96,  0.77, -1.89, -0.56, $

     -0.62, -0.36, -1.01, -1.36]

Test the hypothesis that X represents a random population against the hypothesis that it does not represent a random population at the 0.05 significance level.

result = MD_TEST(X, MDC = mdc)

PRINT, result

IDL prints:

0.722745    0.234918

The computed probability (0.234918) is greater than the 0.05 significance level and therefore we do not reject the hypothesis that X represents a random population.

See Also

CTI_TEST, FV_TEST, KW_TEST, LNP_TEST, R_TEST, RS_TEST, S_TEST, TM_TEST, XSQ_TEST


MEDIAN

The MEDIAN function returns the median value of Array or applies a one- or two-dimensional median filter of the specified width to Array and returns the result. Median smoothing replaces each point with the median of the one- or two-dimensional neighborhood of a given width. It is similar to smoothing with a boxcar or average filter but does not blur edges larger than the neighborhood.

In addition, median filtering is effective in removing "salt and pepper" noise, (isolated high or low values). The scalar median is simply the middle value, which should not be confused with the average value (e.g., the median of the array [1,10,4] is 4, while the average is 5.)

Calling Sequence

Result = MEDIAN(Array [, Width])

Arguments

Array

The array to be processed. If Width is also supplied, and Array is of byte type, the result is of byte type. All other types are converted to single-precision floating-point, and the result is floating-point. Array can have only one or two dimensions.

If Width is not given, Array can have any valid number of dimensions. The array is converted to single-precision floating-point, and the median value is returned as a floating-point value.

Width

The size of the one or two-dimensional neighborhood to be used for the median filter. The neighborhood has the same number of dimensions as Array.

Example

Create a simple image and display it by entering:

D = SIN(DIST(200)^0.8) & TVSCL, D

Display D median filtered with a width of 9 by entering:

TVSCL, MEDIAN(D, 9)

See Also

DIGITAL_FILTER, LEEFILT, MOMENT, SMOOTH


MESH_OBJ

The MESH_OBJ procedure generates a polygon mesh (vertex list and polygon list) that represent the desired primitive object. The available primitive objects are: triangulated surface, rectangular surface, polar surface, cylindrical surface, spherical surface, surface of extrusion, surface of revolution, and ruled surface.

This routine is written in the IDL language. Its source code can be found in the file mesh_obj.pro in the lib subdirectory of the IDL distribution.

Calling Sequence

MESH_OBJ, Type, Vertex_List, Polygon_List, Array1 [, Array2]

Arguments

Type

An integer which specifies what type of object to create. The various surface types are described in the table below.

Type	Surface Type
0	Triangulated
1	Rectangular
2	Polar
3	Cylindrical
4	Spherical
5	Extrusion
6	Revolution
7	Ruled
Other values	None
Table 1.10 Surface Types

Vertex_List

A named variable that will contain the mesh vertices. Vertex_List has the same format as the lists returned by the SHADE_VOLUME procedure.

Polygon_List

A named variable that will contain the mesh indexes. Polygon_List has the same format as the lists returned by the SHADE_VOLUME procedure.

Array1

An array whose use depends on the type of object being created. The table below describes the differences.

Surface Type	Array1  Type
Triangulated	A (3, n) array containing random [ x, y, z] points to build a triangulated surface from. The resulting polygon mesh will have n vertices. When shading a triangulated mesh, the shading array should have (n) elements.
Rectangular	A two dimensional (n, m) array containing z  values. The resulting polygon mesh will have n x m vertices. When shading a rectangular mesh, the shading array should have (n, m) elements.
Polar	A two dimensional (n, m) array containing z  values. The resulting polygon mesh will have n x m vertices. The n dimension of the array is mapped to the polar angle, and the m  dimension is mapped to the polar radius. When shading a polar mesh, the shading array should have (n, m) elements.
Cylindrical	A two dimensional (n, m) array containing radius values. The resulting polygon mesh will have n x m vertices. The n dimension of the array is mapped to the polar angle, and the m dimension is mapped to the Z axis. When shading a cylindrical mesh, the shading array should have (n, m) elements.
Spherical	A two dimensional (n, m) array containing radius values. The resulting polygon mesh will have n x m vertices. The n dimension of the array is mapped to the longitude (0.0 to 360.0 degrees), and the m dimension is mapped to the latitude (-90.0 to +90.0 degrees). When shading a spherical mesh, the shading array should have (n, m) elements.
Extrusion	A (3, n) array of connected 3D points which define the shape to extrude. The resulting polygon mesh will have n x (steps+1) vertices (where steps is the number of "segments" in the extrusion). (See the P1 keyword). If the order of the elements in Array1 is reversed, then the polygon facing is reversed. When shading an extrusion mesh, the shading array should have (n, steps+1) elements.
Revolution	A (3, n) array of connected 3D points which define the shape to revolve. The resulting polygon mesh will have n x ((steps>3)+1) vertices (where steps is the number of "steps" in the revolution). (See the P1 keyword). If the order of the elements in Array1 is reversed, then the polygon facing is reversed. When shading a revolution mesh, the shading array should have (n, (steps>3)+1) elements.
Ruled	A (3,  n) array of connected 3D points which define the shape of the first ruled vector. The optional (3, m) Array2 parameter defines the shape of the second ruled vector. The resulting polygon mesh will have (n > m)*(steps+1) vertices (where steps is the number of intermediate "steps"). (See the P1 keyword). When shading a ruled mesh, the shading array should have (n > m, steps+1) elements.
Array2

If the object type is 7 (Ruled Surface) then Array2 is a (3,  m) array containing the 3D points which define the second ruled vector. If Array2 has fewer elements than Array1 then Array2 is processed with CONGRID to give it the same number of elements as Array1. If Array1 has fewer elements than Array2 then Array1 is processed with CONGRID to give it the same number of elements as Array2. Array2 must be supplied if the object type is 7. Otherwise, Array2 is ignored.

Keywords

DEGREES

If set, then the input parameters are in degrees (where applicable). Otherwise, the angles are in radians.

P1 - P5

The meaning of the keywords P1 through P5 vary depending upon the object type. The table below describes the differences.

Surface Type	Keywords
Triangulated	P1 through P5 are ignored.
Rectangular	If Array1 is an (n, m) array, and if P1 has n elements, then the values contained in P1 are the X coordinates for each column of vertices. Otherwise, FINDGEN(n) is used for the X coordinates. If P2 has m elements, then the values contained in P2 are the Y coordinates for each row of vertices. Otherwise, FINDGEN(m) is used for the Y coordinates. The polygon facing is reversed if the order of either P1 or P2 (but not both) is reversed. P3, P4, and P5 are ignored.
Polar	P1 specifies the polar angle of the first column of Array1 (the default is 0). P2 specifies the polar angle of the last column of Array1 (the default is 2*PI). If P2 is less than P1 then the polygon facing is reversed. P3 specifies the radius of the first row of Array1 (the default is 0). P4 specifies the radius of the last row of Array1 (the default is m-1). If P4 is less than P3 then the polygon facing is reversed. P5 is ignored.
Cylindrical	P1 specifies the polar angle of the first column of Array1 (the default is 0). P2 specifies the polar angle of the last column of Array1 (the default is 2*PI). If P2 is less than P1 then the polygon facing is reversed. P3 specifies the Z coordinate of the first row of Array1 (the default is 0). P4 specifies the Z coordinate of the last row of Array1 (the default is m-1). If P4 is less than P3 then the polygon facing is reversed. P5 is ignored.
Spherical	P1 specifies the longitude of the first column of Array1 (the default is 0). P2 specifies the longitude of the last column of Array1 (the default is 2*PI). IF P2 is less than P1 then the polygon facing is reversed. P3 specifies the latitude of the first row of Array1  (the default is -PI/2). P4 specifies the latitude of the last row of Array1 (the default is +PI/2). If P4 is less than P3 then the polygon facing is reversed. P5 is ignored.
Extrusion	P1 specifies the number of steps in the extrusion (the default is 1). P2 is a three element vector specifying the direction (and length) of the extrusion (the default is [0, 0, 1]). P3, P4, and P5 are ignored.
Revolution	P1 specifies the number of "facets" in the revolution (the default is 3). If P1 is less than 3 then 3 is used. P2 is a three element vector specifying a point that the rotation vector passes through (the default is [0, 0, 0]). P3 is a three element vector specifying the direction of the rotation vector (the default is [0, 0, 1]). P4 specifies the starting angle for the revolution (the default is 0). P5 specifies the ending angle for the revolution (the default is 2*PI). If P5 is less than P4 then the polygon facing is reversed.
Ruled	P1 specifies the number of "steps" in the ruling (the default is 1). P2, P3, P4, and P5 are ignored.
Examples

Create a 48x64 cylinder with a constant radius of 0.25.

MESH_OBJ, 3, Vertex_List, Polygon_List, $

  Replicate(0.25, 48, 64), P4=0.5

Transform the vertices.

T3D, /RESET

T3D, ROTATE=[0.0, 30.0, 0.0]

T3D, ROTATE=[0.0, 0.0, 40.0]

T3D, TRANSLATE=[0.25, 0.25, 0.25]

VERTEX_LIST = VERT_T3D(Vertex_List)

Create the window and view.

WINDOW, 0, XSIZE=512, YSIZE=512

CREATE_VIEW, WINX=512, WINY=512

Render the mesh.

SET_SHADING, LIGHT=[-0.5, 0.5, 2.0], REJECT=0

TVSCL, POLYSHADE(Vertex_List, Polygon_List, /NORMAL)

Create a cone (surface of revolution).

MESH_OBJ, 6, Vertex_List, Polygon_List, $

  [[0.75, 0.0, 0.25], [0.5, 0.0, 0.75]], $

  P1=16, P2=[0.5, 0.0, 0.0]

Create the window and view.

WINDOW, 0, XSIZE=512, YSIZE=512

CREATE_VIEW, WINX=512, WINY=512, AX=30.0, AY=(140.0), ZOOM=0.5

Render the mesh.

SET_SHADING, LIGHT=[-0.5, 0.5, 2.0], REJECT=0

TVSCL, POLYSHADE(Vertex_List, Polygon_List, /DATA, /T3D)

See Also

CREATE_VIEW, POLYSHADE, SET_SHADING, VERT_T3D


MESSAGE

The MESSAGE procedure issues error and informational messages using the same mechanism employed by built-in IDL routines. By default, the message is issued as an error, the message is output, and IDL takes the action specified by the ON_ERROR procedure. As a side-effect of issuing the error, the system variables !ERR and !ERROR are set and the text of the error message is placed in the system variable !ERR_STRING.

Calling Sequence

MESSAGE, Text

Arguments

Text

The text of the message to be issued.

Keywords

CONTINUE

Set this keyword to return after issuing the error instead of taking the action specified by ON_ERROR. Use this option when it is desirable to report an error and then continue processing.

INFORMATIONAL

Set this keyword to issue informational text instead of an error. In this case, !ERR, !ERROR, and !ERR_STRING are not set. The !QUIET system variable controls the printing of informational messages.

IOERROR

Set this keyword to indicates that the error occurred while performing I/O. The action specified by the ON_IOERROR procedure is executed instead of ON_ERROR.

NONAME

Set this keyword to suppress printing of the issuing routine's name at the beginning of the error message.

NOPREFIX

Usually, the message includes the message prefix string (as specified by the !MSG_PREFIX system variable) at the beginning. Set this keyword to omit the prefix.

NOPRINT

Set this keyword to prevent the message from printing to the screen and cause the other actions to proceed quietly. The error system variables are updated as usual.

TRACEBACK

Set this keyword to produce the error message followed by a traceback message that gives the location at which MESSAGE was called.

Example

As an example, assume the statement:

message, 'Unexpected value encountered.'

is executed in a procedure named CALC. If an error occurs, the following message would be printed:

% CALC: Unexpected value encountered.

and execution would halt.

See Also

CATCH, ON_ERROR, ON_IOERROR, STRMESSAGE


MIN

The MIN function returns the value of the smallest element of Array. The type of the result is the same as that of Array.

Calling Sequence

Result = MIN(Array [, Min_Subscript])

Arguments

Array

The array to be searched.

Min_Subscript

A named variable that, if supplied, is converted to a long integer containing the one-dimensional subscript of the minimum element. Otherwise, the system variable !C is set to the one-dimensional subscript of the minimum element.

Keywords

MAX

The name of a variable to receive the value of the maximum array element. If you need to find both the minimum and maximum array values, use this keyword to avoid scanning the array twice with separate calls to MAX and MIN.

NAN

Set this keyword to cause the routine to check for occurrences of the IEEE floating-point value NaN in the input data. Elements with the value NaN are treated as missing data. (See  "Special Floating-Point Values" on page 11-9 of the IDL User's Guide for more information on IEEE floating-point values.)

Example

Create a simple two-dimensional array by entering:

D = DIST(100)

Find the minimum value in array D and print the result by entering:

PRINT, MIN(D)

See Also

MAX


MIN_CURVE_SURF

The MIN_CURVE_SURF function interpolates a regularly- or irregularly-gridded set of points with either a minimum curvature surface or a thin-plate-spline surface. It returns a two-dimensional floating-point array containing the interpolated surface, sampled at the grid points.

A minimum curvature spline surface is fitted to the data points described by x, y, and z. The basis function is:

C (x0, x1,  y0, y1) = d^2 log(d^k)

where d is the distance between (x0, y0), (x1, y1) and k = 1 for minimum curvature surface or k = 2 for Thin Plate Splines. For n data points, a system of n+3 simultaneous equations are solved for the coefficients of the surface. For any interpolation point, the interpolated value is:

f (x, y) =  b0 + b1x  + b2y + Sum(ai ⋅ C (xi, x, yi, y))

Note: the accuracy of this function is limited by the single-precision floating-point accuracy of the machine.

This routine is written in the IDL language. Its source code can be found in the file min_curve_surf.pro in the lib subdirectory of the IDL distribution.

Calling Sequence

Result = MIN_CURVE_SURF(Z [, X, Y])

Arguments

Z, X, Y

Arrays containing the Z, X, and  Y coordinates of the data points on the surface. Points need not be regularly gridded. For regularly gridded input data, X  and Y are not used: the grid spacing is specified via the XGRID and YGRID (or XVALUES and YVALUES) keywords, and Z must be a two dimensional array. For irregular grids, all three parameters must be present and have the same number of elements.

Keywords

TPS

Set this keyword to use the thin-plate-spline method. The default is to use the minimum curvature surface method.

Input Grid Description:

REGULAR

If set, the Z parameter is a two-dimensional array of dimensions (n,m), containing measurements over a regular grid. If any of XGRID, YGRID, XVALUES, or YVALUES are specified, REGULAR is implied. REGULAR is also implied if there is only one parameter, Z. If REGULAR is set, and no grid specifications are present, the grid is set to (0, 1, 2, ...).

XGRID

A two-element array, [xstart, xspacing], defining the input grid in the x direction. Do not specify both XGRID and XVALUES.

XVALUES

An n-element array defining the x locations of Z(i,j). Do not specify both XGRID and XVALUES.

YGRID

A two-element array, [ystart, yspacing], defining the input grid in the y direction. Do not specify both YGRID and YVALUES.

YVALUES

An n-element array defining the y locations of Z(i,j). Do not specify both YGRID and YVALUES.

Output Grid Description:

GS

The output grid spacing. If present, GS must be a two-element vector [xs, ys], where xs is the horizontal spacing between grid points and ys is the vertical spacing. The default is based on the extents of x and y . If the grid starts at x value xmin and ends at xmax, then the default horizontal spacing is (xmax - xmin )/(NX-1). ys is computed in the same way. The default grid size, if neither NX or NY are specified, is 26 by 26.

BOUNDS

If present, BOUNDS must be a four-element array containing the grid limits in x and y of the output grid: [xmin, ymin, xmax, ymax]. If not specified, the grid limits are set to the extent of x and y.

NX

The output grid size in the x direction. NX need not be specified if the size can be inferred from GS and BOUNDS. The default value is 26.

NY

The output grid size in the y direction. NY need not be specified if the size can be inferred from GS and BOUNDS. The default value is 26.

XOUT

Use the XOUT keyword to specify a vector containing the output grid x values. If this parameter is supplied, GS, BOUNDS, and NX are ignored for the x output grid. XOUT allows you to specify irregularly-spaced output grids.

YOUT

Use the YOUT keyword to specify a vector containing the output grid y values. If this parameter is supplied, GS, BOUNDS, and NY are ignored for the y output grid. YOUT allows you to specify irregularly-spaced output grids.

XPOUT/YPOUT

Use the XPOUT and YPOUT keywords to specify arrays that contain the x and y values for the output points. If these keywords are used, the output grid need not be regular, and all other output grid parameters are ignored. XPOUT and YPOUT must have the same number of points, which is also the number of points returned in the result.

Example

Make a random set of points that lie on a Gaussian:

N = 15	Number of random points.

X = RANDOMU(seed, N)

Y = RANDOMU(seed, N)

Z = EXP(-2 * ((X-.5)^2 + (Y-.5)^2))	The Gaussian.

Use a 26 by 26 grid over the rectangle bounding x and y:

R = MIN_CURVE_SURF(Z, X, Y)	Get the surface.

Alternatively, get a surface over the unit square, with spacing of 0.05:

R = MIN_CURVE_SURF(Z, X, Y, GS=[0.05, 0.05], BOUNDS=[0,0,1,1])

Alternatively, get a 10 by 10 surface over the rectangle bounding x and y:

R = MIN_CURVE_SURF(Z, X, Y, NX=10, NY=10)

See Also

CONTOUR, TRI_SURF


MK_HTML_HELP

The MK_HTML_HELP procedure, given a list of IDL procedure filenames (.pro files), VMS text library filenames (.TLB files), or the names of directories containing such files, generates a file in HTML (HyperText Markup Language) format that contains documentation for those routines that contain standard IDL documentation headers. The resulting file can then be viewed with a "World Wide Web" browser such as Mosaic or Netscape.

MK_HTML_HELP procedure makes single HTML file that starts with a list of the routines documented in the file. The names of routines in that list are hypertext links to the documentation for those routines. The documentation for each routine is simply the text of the documentation header copied from the corresponding .pro file—no reformatting is performed.

The documentation headers of the .pro files in question must have the following format:

•	The first line of the documentation block contains only the characters ;+, starting in column 1.

•	The last line of the documentation block contains only the characters ;-, starting in column 1.

•	All other lines in the documentation block contain a ; in column 1.

•	If a line containing the string "NAME:" exists in the documentation block, the contents of the following line are used as the name of the routine being described. If the NAME: field is not present, the name of the source file is used as the routine name.

The file template.pro in the general subdirectory of the examples subdirectory of the IDL distribution contains a template for creating your own documentation headers.

This routine is supplied for users to make online documentation from their own IDL programs. Although it could be used to create an HTML documentation file from the lib subdirectory of the IDL distribution, we do not recommend doing so. The documentation headers on the files in the lib directory are used for historical purposes—most do not contain the most current or accurate documentation for those routines. The most current documentation for IDL's built-in and library routines is found in IDL's online help system (enter ? at the IDL prompt).

This routine is written in the IDL language. Its source code can be found in the file mk_html_help.pro in the lib subdirectory of the IDL distribution.

Calling Sequence

MK_HTML_HELP, Sources, Filename

Arguments

Sources

A string array containing the names of IDL procedure files (.pro files), VMS text libraries (.TLB files), or directories containing such files. The Sources array may contain both individual file and directory names. Each IDL procedure file must have the file extension .pro, and each VMS text library must include the file extension .TLB. Elements of the Sources array that do not have either of these extensions are assumed to be directories.

A string containing the name of a directory or VMS text library that contains .pro files. If Source is a VMS text library, it must include the file extension .TLB, otherwise MK_HTML_HELP will not recognize Source as a VMS text library.

All .pro files found in Sources are searched for documentation headers. (Note: more than one documentation block may exist in a single input file.) The documentation headers are extracted and saved in HTML format in the file specified by Filename.

Filename

A string containing the name of the output file to be generated. HTML files are usually saved in files named with a .html or .htm extension.

Keywords

STRICT

Set this keyword to force MK_HTML_HELP to adhere strictly to the HTML format by scanning the documentation blocks for HTML reserved characters and replacing them in the output file with the appropriate HTML syntax. HTML reserved characters include < , > , & , and ". By default, this keyword is set to zero to allow for faster processing of the input files.

TITLE

A string that supples the name to be used as the title of the HTML document. The default is "Extended IDL Help".

VERBOSE

Set this keyword to display informational messages as MK_HTML_HELP generates the HTML file. Normally, MK_HTML_HELP works silently.

Example

To generate an HTML help file named myhelp.html from the .pro files in the directory /usr/home/dave/myroutines, use the command:

MK_HTML_HELP, '/usr/home/dave/myroutines', 'myhelp.html'

To generate an HTML help file for all routines in a given directory whose file names contain the word "plot", use the following commands:

plotfiles=FINDFILE('/usr/home/dave/myroutines/*plot*.pro')

MK_HTML_HELP, plotfiles, 'myplot.html'

See Also

DOC_LIBRARY


MODIFYCT

The MODIFYCT procedure updates the distribution color table file colors1.tbl, located in the colors subdirectory of the resource subdirectory of the main IDL directory, or a user-designated file with a new, or modified, colortable.

This routine is written in the IDL language. Its source code can be found in the file modifyct.pro in the lib subdirectory of the IDL distribution.

Calling Sequence

MODIFYCT, Itab, Name, R, G, B

Arguments

Itab

The index of the table to be updated, numbered from 0 to 255. If the specified entry is greater than the next available location in the table, the entry will be added to the table in the available location rather than the index specified by Itab. On return, Itab contains the index for the location that was modified or extended. The modified table can be then be loaded with the IDL command: LOADCT, Itab.

Name

A string, up to 32 characters long, that contains the name for the new color table.

R

A 256-element vector that contains the values for the red colortable.

G

A 256-element vector that contains the values for the green colortable.

B

A 256-element vector that contains the values for the blue colortable.

Keywords

FILE

Set this keyword to the name of a colortable file to be modified instead of the file colors1.tbl in the IDL directory.

See Also

LOADCT, XLOADCT


MOMENT

The MOMENT function computes the mean, variance, skewness, and kurtosis of a sample population X.

When x  = (x0, x1, x2, ..., xn-1), the various moments are defined as follows:

This routine is written in the IDL language. Its source code can be found in the file moment.pro in the lib subdirectory of the IDL distribution.

Calling Sequence

Result = MOMENT(X)

Arguments

X

An n-element integer, single-, or double-precision floating-point vector.

Keywords

MDEV

Set this keyword to a named variable that will contain the mean absolute deviation of X.

SDEV

Set this keyword to a named variable that will contain the standard deviation of X.

Example

Define an n-element sample population.

X = [65, 63, 67, 64, 68, 62, 70, 66, 68, 67, 69, 71, 66, 65, 70]

Compute the mean, variance, skewness and kurtosis.

result = MOMENT(X)

PRINT, 'Mean: ', result(0) & PRINT, 'Variance: ', result(1) & $

  PRINT, 'Skewness: ', result(2) & PRINT, 'Kurtosis: ', result(3)

IDL prints:

Mean:       66.7333

Variance:    7.06667

Skewness:   -0.0942851

Kurtosis:   -1.18258

See Also

HISTOGRAM, MAX,  MEDIAN, MIN


MULTI

The MULTI procedure expands the current color table to "wrap around" some number of times.

This routine is written in the IDL language. Its source code can be found in the file multi.pro in the lib subdirectory of the IDL distribution.

Calling Sequence

MULTI, N

Arguments

N

The number of times the color table will wrap. This parameter does not have to be an integer.

Example

Display an image, load color table 1, and make that color table "wrap around" 3 times. Enter:

TVSCL, DIST(256) 	Display a simple image.

LOADCT, 1 	Load color table 1.

MULTI, 3	See how the new color table affects the image.

See Also

STRETCH, XLOADCT


N_ELEMENTS

The N_ELEMENTS function returns the number of elements contained in an expression or variable.

Calling Sequence

Result = N_ELEMENTS(Expression)

Arguments

Expression

The expression for which the number of elements is to be returned. Scalar expressions always have one element. The number of elements in an array is equal to the product of its dimensions. If Expression is an undefined variable, N_ELEMENTS returns zero.

Examples

Create an integer array, I by entering:

I = INTARR(4, 5, 3, 6)

Find the number of elements in I and print the result by entering:

PRINT, N_ELEMENTS(I)

To test if the variable Q is defined and, if not, set its value to 1, use the command:

IF N_ELEMENTS(Q) EQ 0 THEN Q=1

See Also

N_TAGS


N_PARAMS

The N_PARAMS function returns the number of non-keyword parameters used in calling an IDL procedure or function. This function is only useful within IDL procedures or functions. User-written procedures and functions can use N_PARAMS to determine if they were called with optional parameters.

Calling Sequence

Result = N_PARAMS()

Arguments

None. This function always returns the number of parameters that were used in calling the procedure or function from which N_PARAMS is called.

See Also

KEYWORD_SET


N_TAGS

The N_TAGS function returns the number of structure tags contained in a structure expression. It optionally returns the size, in bytes, of the structure.

Calling Sequence

Result = N_TAGS(Expression)

Arguments

Expression

The expression for which the number of structure tags is to be returned. Expressions that are not of structure type are considered to have no tags. N_TAGS does not search for tags recursively, so if Expression is a structure containing nested structures, only the number of tags in the outermost structure are counted.

Keywords

LENGTH

Set this keyword to return the length of the structure, in bytes.

Note: the length of a structure is machine dependent. The length of a given structure will vary depending upon the host machine. IDL to pads and aligns structures in a manner consistent with the host machine's C compiler.

Example

Find the number of tags in the system variable !P and print the result by entering:

PRINT, N_TAGS(!P)

Find the length of !P, in bytes:

PRINT, N_TAGS(!P, /LENGTH)

See Also

N_ELEMENTS, Chapter 7 of the IDL User's Guide


NCDF_ATTCOPY

The NCDF_ATTCOPY function copies an attribute from one netCDF file to another. Note that Incdf and Outcdf can be the same netCDF ID.

Calling Sequence

Result = NCDF_ATTCOPY(Incdf, [Invar,] Name, Outcdf, [Outvar])

Arguments

Incdf

The netCDF ID, returned from a previous call to NCDF_OPEN or NCDF_CREATE.

Invar

The netCDF variable ID to be read, returned from a previous call to NCDF_VARDEF or NCDF_VARID, or the name of the variable. If the IN_GLOBAL keyword is set, this argument must be omitted.

Name

A scalar string containing the name of the attribute to be copied.

Outcdf

The netCDF ID of a netCDF file opened for writing, returned from a previous call to NCDF_OPEN or NCDF_CREATE.

Outvar

The netCDF variable ID to be written, returned from a previous call to NCDF_VARDEF or NCDF_VARID, or the name of the variable. If the OUT_GLOBAL keyword is set, this argument must be omitted.

Keywords

IN_GLOBAL

Set this keyword to read a global attribute.

OUT_GLOBAL

Set this keyword to create a global attribute.


NCDF_ATTDEL

The NCDF_ATTDEL procedure deletes an attribute from a netCDF file.

Calling Sequence

NCDF_ATTDEL, Cdfid, [Varid,] Name

Arguments

Cdfid

The netCDF ID, returned from a previous call to NCDF_OPEN or NCDF_CREATE.

Varid

The netCDF variable ID, returned from a previous call to NCDF_VARDEF or NCDF_VARID, or the name of the variable.

Name

A scalar string containing the name of the attribute to be deleted.

Keywords

GLOBAL

Set this keyword to delete a global variable.

Example

id = NCDF_OPEN('test.nc', /WRITE)	 Open file test.nc for writing.

NCDF_ATTDEL, id, 'TITLE', /GLOBAL	 Delete global attribute TITLE from the file.

NCDF_CLOSE, id	 Close the file.

See Also

NCDF_ATTNAME, NCDF_ATTPUT


NCDF_ATTGET

The NCDF_ATTGET procedure retrieves the value of an attribute from a netCDF file.

Calling Sequence

NCDF_ATTGET, Cdfid, [Varid,] Name, Value

Arguments

Cdfid

The netCDF ID, returned from a previous call to NCDF_OPEN or NCDF_CREATE.

Varid

The netCDF variable ID, returned from a previous call to NCDF_VARDEF or NCDF_VARID, or the name of the variable. If the GLOBAL keyword is used, this argument must be omitted.

Name

A scalar string containing the attribute name.

Value

A named variable in which the attribute's value is returned. NCDF_ATTGET sets Value's size and data type appropriately.

Keywords

GLOBAL

Set this keyword to retrieve the value of a global attribute.

Example

For an example using this routine, see the documentation for NCDF_ATTINQ.

See Also

NCDF_ATTINQ, NCDF_ATTNAME, NCDF_ATTPUT


NCDF_ATTINQ

The NCDF_ATTINQ function returns a structure that contains information about a netCDF attribute. This structure, described below, has the form:

{ DATATYPE:'', LENGTH=0L }

Calling Sequence

Result = NCDF_ATTINQ(Cdfid [,Varid], Name)

Arguments

Cdfid

The netCDF ID, returned from a previous call to NCDF_OPEN or NCDF_CREATE.

Varid

The netCDF variable ID, returned from a previous call to NCDF_VARDEF or NCDF_VARID, or the name of the variable. If the GLOBAL keyword is set, this argument must be omitted.

Name

A scalar string containing the name of the attribute for which information is to be returned.

Keywords

GLOBAL

Set this keyword to inquire about a global variable. If this keyword is set, the Varid argument must be omitted.

Explanation of the Structure Tags

DataType

A string describing the data type of the variable. The string will be one of the following: `BYTE', `CHAR', `INT', `LONG', `FLOAT', or `DOUBLE'.

Length

The number of values stored in the attribute. If the attribute is a string, the number of values indicates one more character than the string length to include the terminating null character. This is the NetCDF convention, as demonstrated in the example below.

Example

id = NCDF_CREATE('test.nc', /CLOBBER)
Open a new netCDF file.

NCDF_ATTPUT, id, /GLOBAL, 'TITLE', 'MY TITLE'
Insert a global attribute.

NCDF_CONTROL, id, /ENDEF	Put the file into data mode.

name = NCDF_ATTNAME(id, /GLOBAL, 0)	 Get the attribute's name

result = NCDF_ATTINQ(id, /GLOBAL, name)
Inquire about the attribute.

PRINT, result.datatype	Print one field of the returned structure. IDL prints: BYTE. This shows that netCDF stores strings as arrays of bytes (ASCII).

PRINT, result.length	Print the other field. IDL prints: 9. Note that this number includes that the length of the attribute is 8 characters plus 1 extra for the null termination character.

NCDF_ATTGET, id, /GLOBAL, name, output
Read the attribute's value.

HELP, output	IDL prints: OUTPUT BYTE = Array(9)

PRINT, output	IDL prints: 77 89 32 84 73 84 76 69 0. These are the byte values of the array of ASCII text.

PRINT, STRING(output)	IDL prints: MY TITLE. We used the STRING function to convert the byte values back into a readable string.

NCDF_CLOSE, id	Close the netCDF file.

See Also

NCDF_ATTDEL, NCDF_ATTGET, NCDF_ATTNAME, NCDF_ATTPUT


NCDF_ATTNAME

The NCDF_ATTNAME function returns the name of an attribute in a netCDF file given its ID. The NULL string ("") is returned if there is no such attribute.

Calling Sequence

Result = NCDF_ATTNAME(Cdfid, [Varid,] Attnum)

Arguments

Cdfid

The netCDF ID, returned from a previous call to NCDF_OPEN or NCDF_CREATE.

Varid

The netCDF variable ID, returned from a previous call to NCDF_VARDEF or NCDF_VARID, or the name of the variable. If the GLOBAL keyword is set, this argument must be omitted.

Attnum

An expression containing the number of the desired attribute. The attributes for each variable are numbered from 0 to the number-of-attributes minus 1. Note that the number of attributes can be found using NCDF_VARINQ or NCDF_INQUIRE (to find the number of global variables).

Keywords

GLOBAL

Set this keyword to return the name of one of the global attributes.


NCDF_ATTPUT

The NCDF_ATTPUT procedure creates an attribute in a netCDF file. If the attribute is new, or if the space required to store the attribute is greater than before, the netCDF file must be in define mode.

Calling Sequence

NCDF_ATTPUT, Cdfid, [Varid,] Name, Value

Arguments

Cdfid

The netCDF ID, returned from a previous call to NCDF_OPEN or NCDF_CREATE.

Varid

The netCDF variable ID, returned from a previous call to NCDF_VARDEF or NCDF_VARID, or the name of the variable. If the GLOBAL keyword is set, this argument must be omitted.

Name

A scalar string containing the attribute name.

Value

An expression containing the data to be written. Although this procedure checks that there are a sufficient number of bytes of data, the data type is not checked or altered.

Keywords

GLOBAL

Set this keyword to create a global attribute.

LENGTH

Use this keyword to override the default length (the whole value). Set this keyword to a value less than or equal to the number of elements in Value. For example:

ATTR_ID = NCDF_ATTPUT(CDFID, VARID, 'Attr1', $

          INDGEN(10), LENGTH=5

writes Attr1 as [0,1,2,3,4].

The following keywords specify a non-default data type for the variable. By default, NCDF_ATTPUT chooses one based upon the type of data. If a data type flag is specified, the data supplied in Value is converted to that data type before being written to the file. Only one of these keywords can be used in a single call to NCDF_ATTPUT.

BYTE

Set this keyword to indicate that the data is composed of bytes.

CHAR

Set this keyword to indicate that the data is composed of bytes (assumed to be ASCII).

DOUBLE

Set this keyword to indicate that the data is composed of 8-byte floating point numbers (doubles).

FLOAT

Set this keyword to indicate that the data is composed of 4-byte floating point numbers (floats).

LONG

Set this keyword to indicate that the data is composed of 4-byte integers (longs).

SHORT

Set this keyword to indicate that the data is composed of 2-byte integers.

Example

NCDF_ATTPUT, cdfid, /GLOBAL, "Title", "My Favorite Data File"

NCDF_ATTPUT, cdfid, "data", "scale_factor", 12.5D"


NCDF_ATTRENAME

The NCDF_ATTRENAME procedure renames an attribute in a netCDF file.

Calling Sequence

NCDF_ATTRENAME, Cdfid, [Varid,] Oldname, Newname

Arguments

Cdfid

The netCDF ID, returned from a previous call to NCDF_OPEN or NCDF_CREATE.

Varid

The netCDF variable ID, returned from a previous call to NCDF_VARDEF or NCDF_VARID, or the name of the variable. If the GLOBAL keyword is set, this argument must be omitted.

OldName

A scalar string containing the attribute's current name.

NewName

A scalar string containing the attribute's new name.

Keywords

GLOBAL

Set this keyword to rename a global attribute.


NCDF_CLOSE

The NCDF_CLOSE procedure closes an open netCDF file. If a writable netCDF file is not closed before exiting IDL, the disk copy of the netCDF file may not reflect recent data changes or new definitions.

Calling Sequence

NCDF_CLOSE, Cdfid

Arguments

Cdfid

The netCDF ID of the file to be closed, returned from a previous call to NCDF_OPEN or NCDF_CREATE.


NCDF_CONTROL

The NCDF_CONTROL procedure performs miscellaneous netCDF operations.

Different options are controlled by keywords. Only one keyword can be specified in any call to NCDF_CONTROL, unless the OLDFILL keyword is specified.

Calling Sequence

NCDF_CONTROL, Cdfid

Arguments

Cdfid

The netCDF ID, returned from a previous call to NCDF_OPEN or NCDF_CREATE.

Keywords

ABORT

Set this keyword to close a netCDF file that is not in define mode. If the file is being created and is still in define mode, the file is deleted. If define mode was entered by a call to NCDF_CONTROL with the REDEF keyword, the netCDF file is restored to its state before definition mode was entered, and the file is closed.

ENDEF

Set this keyword to takes an open netCDF file out of define mode (and into data mode).

FILL

Set this keyword so that data in the netCDF file is pre-filled with default fill values. The default values (which cannot be changed) are:

Data Type	Fill Value
BYTE	0
CHAR	0
SHORT	-32767
LONG	-2147483647
FLOAT	9.96921E+36
DOUBLE	9.96921E+36
Table 1.11 Default Fill Values for netCDF Files

NOFILL

Set this keyword so that data in the netCDF file is not pre-filled. This option saves time when it is certain that variable values will be written before a read is attempted.

NOVERBOSE

Set this keyword to suppress the printing of netCDF error messages. Cdfid  is required but not used.

OLDFILL

This keyword specifies a named variable in which the previous fill value is returned. This keyword can only be used in combination with the FILL or NOFILL keywords. For example:

NCDF_CONTROL, id, FILL=1, OLDFILL=previous_fill

REDEF

Set this keyword to put an open netCDF file into define mode.

SYNC

Set this keyword to update the disk copy of a netCDF file that is open for writing. The netCDF file must be in data mode. A netCDF file in define mode will be updated only when NCDF_CONTROL is called with the ENDEF keyword.

VERBOSE

Set this keyword to cause netCDF error messages to be printed. Cdfid is required but not used. For example:

NCDF_CONTROL, 0, /VERBOSE

is a valid command even if 0 is not a valid NetCDF file ID.

Example

See the examples under NCDF_ATTINQ and NCDF_VARPUT.

See Also

NCDF_CLOSE, NCDF_CREATE, NCDF_OPEN


NCDF_CREATE

The NCDF_CREATE function creates a new netCDF file. If successful, the netCDF ID for the file is returned. The newly-created netCDF file is automatically placed into define mode. If you do not have write permission to create the specified Filename, NCDF_CREATE returns an error message instead of a netCDF file ID.

Calling Sequence

Result = NCDF_CREATE(Filename)

Arguments

Filename

A scalar string containing the name of the file to be created

Keywords

CLOBBER

Set this keyword to erase the existing file (if the file already exists) before saving the new version.

NOCLOBBER

Set this keyword to create a new netCDF file only if the specified file does not already exist. This is the default.

Example

id = NCDF_CREATE('test.nc',/CLOBBER)
Open a new NetCDF File and destroy test.nc if it already exists.

id2 = NCDF_CREATE('test.nc', /NOCLOBBER)
This attempt to create a new version of the file test.nc produces the following error because the NOCLOBBER keyword was set.

IDL prints:

nccreate: filename "test.nc": File exists

% NCDF_CREATE: Operation failed

% Execution halted at $MAIN$   (NCDF_CREATE).

See Also

NCDF_CLOSE, NCDF_CONTROL, NCDF_OPEN


NCDF_DIMDEF

The NCDF_DIMDEF function defines a dimension in a netCDF file given its name and size. If successful, the dimension ID is returned.

Calling Sequence

Result = NCDF_DIMDEF(Cdfid, DimName, Size)

Arguments

Cdfid

The netCDF ID, returned from a previous call to NCDF_OPEN or NCDF_CREATE.

DimName

A scalar string containing the name of the dimension being defined.

Size

The size of the dimension. Size can be any scalar expression. If the UNLIMITED keyword is used, the Size parameter should be omitted.

Keywords

UNLIMITED

Set this keyword to create a dimension of unlimited size. Note that only one dimension in a netCDF file can be unlimited.


NCDF_DIMID

The NCDF_DIMID function returns the ID of a netCDF dimension, given the name of the dimension. This function returns -1 if the dimension does not exist.

Calling Sequence

Result = NCDF_DIMID(Cdfid, DimName)

Arguments

Cdfid

The netCDF ID, returned from a previous call to NCDF_OPEN or NCDF_CREATE.

DimName

A scalar string containing the dimension name.


NCDF_DIMINQ

The NCDF_DIMINQ procedure retrieves the name and size of a dimension in a netCDF file, given its ID. The size for the unlimited dimension, if any, is the maximum value used so far in writing data for that dimension.

Calling Sequence

NCDF_DIMINQ, Cdfid, Dimid, Name, Size

Arguments

Cdfid

The netCDF ID, returned from a previous call to NCDF_OPEN or NCDF_CREATE.

Dimid

The netCDF dimension ID, returned from a previous call to NCDF_DIMID or NCDF_DIMDEF or the name of the dimension.

Name

A named variable in which the dimension name is returned (a scalar string).

Size

A named variable in which the size of the dimension is returned (a scalar longword integer)


NCDF_DIMRENAME

The NCDF_DIMRENAME procedure renames an existing dimension in a netCDF file which has been opened for writing. If the new name is longer than the old name, the netCDF file must be in define mode. You cannot rename one dimension to have the same name as another dimension.

Calling Sequence

NCDF_DIMRENAME, Cdfid, Dimid, NewName

Arguments

Cdfid

The netCDF ID, returned from a previous call to NCDF_OPEN or NCDF_CREATE.

Dimid

The netCDF dimension ID, returned from a previous call to NCDF_DIMID or NCDF_DIMDEF, or the name of the dimension.

NewName

A scalar string containing the new name for the dimension.


NCDF_EXISTS

The NCDF_EXISTS function returns true if the Network Common Data Format (netCDF) scientific data format library is supported on the current IDL platform.

This routine is written in the IDL language. Its source code can be found in the file ncdf_exists.pro in the lib subdirectory of the IDL distribution.

Calling Sequence

Result = NCDF_EXISTS()

Example

The following IDL command prints an error message if the NetCDF library is not available:

IF NCDF_EXISTS() EQ 0 THEN PRINT, 'NCDF not supported.'


NCDF_INQUIRE

The NCDF_INQUIRE function returns a structure that contains information about an open netCDF file. This structure of the form:

{ NDIMS:0L, NVARS:0L, NGATTS:0L, RECDIM:0L }

The structure tags are described below.

Calling Sequence

Result = NCDF_INQUIRE(Cdfid)

Arguments

Cdfid

The netCDF ID, returned from a previous call to NCDF_OPEN or NCDF_CREATE.

Explanation of the Structure Tags

Ndims

The number of dimensions defined for this netCDF file.

Nvars

The number of variables defined for this netCDF file.

Ngatts

The number of global attributes defined for this netCDF file.

RecDim

The ID of the unlimited dimension, if there is one, for this netCDF file. If there is no unlimited dimension, RecDim is set to -1.


NCDF_OPEN

The NCDF_OPEN function opens an existing netCDF file. If successful, the netCDF ID for the file is returned.

Calling Sequence

Result = NCDF_OPEN(Filename)

Arguments

Filename

A scalar string containing the name of the file to be opened.

Keywords

NOWRITE

Set this keyword to open an existing netCDF file as read only. This is the default.

WRITE

Set this keyword to open an existing netCDF file for both writing and reading.


NCDF_VARDEF

The NCDF_VARDEF function adds a new variable to an open netCDF file in define mode. If successful, the variable ID is returned.

Calling Sequence

Result = NCDF_VARDEF(Cdfid, Name [, Dim])

Arguments

Cdfid

The netCDF ID, returned from a previous call to NCDF_OPEN or NCDF_CREATE.

Name

A scalar string containing the variable name.

Dim

An optional vector containing the dimension IDs corresponding to the variable dimensions. If the ID of the unlimited dimension is included, it must be the rightmost element in the array. If Dim is omitted, the variable is assumed to be a scalar.

Keywords

The following keywords specify the data type for the variable. Only one of these keywords can be used. If no data type keyword is specified, FLOAT is used by default.

BYTE

Set this keyword to indicate that the data is composed of bytes.

CHAR

Set this keyword to indicate that the data is composed of bytes (assumed to be ASCII).

DOUBLE

Set this keyword to indicate that the data is composed of double-precision floating-point numbers.

FLOAT

Set this keyword to indicate that the data is composed of floating-point numbers.

LONG

Set this keyword to indicate that the data is composed of longword integers.

SHORT

Set this keyword to indicate that the data is composed of 2-byte integers.


NCDF_VARGET

The NCDF_VARGET procedure retrieves a hyperslab of values from a netCDF variable. The netCDF file must be in data mode to use this procedure.

Calling Sequence

NCDF_VARGET, Cdfid, Varid, Value

Arguments

Cdfid

The netCDF ID, returned from a previous call to NCDF_OPEN or NCDF_CREATE.

Varid

The netCDF variable ID, returned from a previous call to NCDF_VARDEF or NCDF_VARID, or the name of the variable.

Value

A named variable in which the values are returned. NCDF_VARGET sets Value 's size and data type as appropriate.

Keywords

COUNT

An optional vector containing the counts to be used in reading Value. The default count vector is that for a single read, [1, 1, ...], as in NCDF_VARGET1.

OFFSET

An optional vector containing the starting position for the read. The default start position is [0, 0, ...].

STRIDE

An optional vector containing the strides, or sampling intervals, between accessed values of the netCDF variable. The default stride vector is that for a contiguous read, [1, 1, ...].

Example

Suppose that a 230 by 230 image is saved in the netCDF file dave.nc. The following commands extract both the full image and a 70x70 sub-image starting at [80,20] sampling every other X pixel and every third Y pixel:

offset = [80, 20]	A variable that contains the offset for the sub-image.

count = [70, 70]	The dimensions of the sub-image.

stride = [2, 3]	Create a variable to be used as a value for the STRIDE keyword. Every other X element and every third Y element will be sampled.

id = NCDF_OPEN('dave.nc')	Open the NetCDF file.

image = NCDF_VARID(id, 'image')	Get the variable ID for the image.

NCDF_VARGET, id, image, fullimage	Get the full image.

NCDF_VARGET, id, image, subimage, $

             COUNT=count, STRIDE=stride, OFFSET=offset
Extract the sub-sampled image.

NCDF_CLOSE, id	Close the NetCDF file.

See Also

NCDF_VARGET1, NCDF_VARID, NCDF_VARINQ, NCDF_VARPUT


NCDF_VARGET1

The NCDF_VARGET1 procedure retrieves one element from a netCDF variable. The netCDF file must be in data mode to use this procedure.

Calling Sequence

NCDF_VARGET1, Cdfid, Varid, Value

Arguments

Cdfid

The netCDF ID, returned from a previous call to NCDF_OPEN or NCDF_CREATE.

Varid

The netCDF variable ID, returned from a previous call to NCDF_VARDEF or NCDF_VARID, or the name of the variable.

Value

A named variable in which the value of the variable is returned. NCDF_VARGET1 sets Value's size and data type as appropriate.

Keywords

OFFSET

An optional vector containing the starting position of the read. The default starting position is [0, 0, ...].

Example

Suppose that the file dave.nc contains an image saved with the netCDF variable name "dave". The following commands extract the value of a single pixel from the image:

offset = [180,190]	The location of the single element (pixel) whose value we will retrieve.

id = NCDF_OPEN('dave.nc')	Open the netCDF file.

varid = NCDF_VARID(id, 'dave')	Get the variable ID for variable "dave".

NCDF_VARGET, id, varid, single_pixel, OFFSET=offset
Extract the element and return the value in the variable single_pixel.

NCDF_CLOSE, id	Close the netCDF file.

See Also

NCDF_VARGET, NCDF_VARID, NCDF_VARINQ, NCDF_VARPUT


NCDF_VARID

The NCDF_VARID function returns the ID of a netCDF variable. This function returns -1 if the variable does not exist.

Calling Sequence

Result = NCDF_VARID(Cdfid, Name)

Arguments

Cdfid

The netCDF ID, returned from a previous call to NCDF_OPEN or NCDF_CREATE.

Name

A scalar string containing the variable name.


NCDF_VARINQ

The NCDF_VARINQ function returns a structure that contains information about a netCDF variable, given its ID. This structure has the form:

{ NAME:"", DATATYPE:"", NDIMS:0L, NATTS:0L, DIM:LONARR(NDIMS) }

This structure is described below.

Calling Sequence

Result = NCDF_VARINQ(Cdfid, Varid)

Arguments

Cdfid

The netCDF ID, returned from a previous call to NCDF_OPEN or NCDF_CREATE.

Varid

The netCDF variable ID, returned from a previous call to NCDF_VARDEF or NCDF_VARID, or the name of the variable.

Explanation of the Structure Tags

Name

The name of the variable.

DataType

A string describing the data type of the variable. The string will be one of the following: 'BYTE', 'CHAR',  'INT', 'LONG', 'FLOAT', or 'DOUBLE'.

Ndims

The number of dimensions.

Natts

The number of attributes assigned to this variable.

Dim

A vector of the dimension IDs for the variable dimensions.


NCDF_VARPUT

The NCDF_VARPUT procedure writes a hyperslab of values to a netCDF variable. The netCDF file must be in  data mode to use this procedure.

Calling Sequence

NCDF_VARPUT, Cdfid, Varid, Value

Arguments

Cdfid

The netCDF ID, returned from a previous call to NCDF_OPEN or NCDF_CREATE.

Varid

The netCDF variable ID, returned from a previous call to NCDF_VARDEF or NCDF_VARID, or the name of the variable.

Value

Data values to be written to the netCDF file. If the data type of Value does not match that of the netCDF variable, it is converted to the correct data type before writing. Value must have a dimensionality less than or equal to that of the variable being written.

Keywords

COUNT

An optional vector containing the counts to be used in writing Value. Note that counts do not have to match the dimensions of Value. The default count vector is the dimensionality of Value.

OFFSET

An optional vector containing the starting position to write. The default start position is [0, 0, ...].

STRIDE

An optional vector containing the strides, or writing intervals, between written values of the netCDF variable. The default stride vector is that for a contiguous write, [1, 1, ...].

Example

Suppose that you wish to create a 100x100 byte (0 & 1) checker board. In this case:

offset_even = [0,0] & offset_odd = [1,1]
Create offsets for even and odd rows.

count = [50,50] & stride = [2,2]	Create count and stride values.

black = BYTARR(50,50) > 1B	Make the "black" spaces of the checker board.

id = NCDF_CREATE('checker.nc', /CLOBBER)
Create the netCDF file.

NCDF_CONTROL, id, /FILL	Fill the file with BYTE zeros.

xid = NCDF_DIMDEF(id, 'x', 100)	Define the X dimension.

yid = NCDF_DIMDEF(id, 'y', 100)	Define the Y dimension.

vid = NCDF_VARDEF(id, 'board', [yid, xid], /BYTE)
Define a variable with the name "board".

NCDF_CONTROL, id, /ENDEF	Put the file into data mode.

NCDF_VARPUT, id, vid, black, $

             COUNT=count, STRIDE=stride, OFFSET=offset_even

NCDF_VARPUT, id, vid, black, $

             COUNT=count, STRIDE=stride, OFFSET=offset_odd

NCDF_VARGET, id, vid, output	Get the full image.

WINDOW, XSIZE=100, YSIZE=100	Create a window for displaying the image.

TVSCL, output	Display the image.

stride = [2,3]	Make stride larger than possible.

NCDF_VARPUT, id, vid, black, $

             COUNT=count, STRIDE=stride, OFFSET=offset_odd
As an experiment, attempt to write to an array larger than the one we previously allocated with NCDF_VARDEF.

IDL prints:

% NCDF_VARPUT: Requested write is larger than the available data area.
You will need to change the OFFSET/COUNT/STRIDE, or redefine the variable dimensions.
You attempted to access 150 elements in a 100 array.

NCDF_CLOSE, id	Close the netCDF file.

See Also

NCDF_VARGET, NCDF_VARGET1, NCDF_VARID, NCDF_VARINQ


NCDF_VARRENAME

The NCDF_VARRENAME procedure renames a netCDF variable.

Calling Sequence

NCDF_VARRENAME, Cdfid, Varid, Name

Arguments

Cdfid

The netCDF ID, returned from a previous call to NCDF_OPEN or NCDF_CREATE.

Varid

The netCDF variable ID, returned from a previous call to NCDF_VARDEF or NCDF_VARID, or the name of the variable.

Name

A scalar string containing the new name for the variable.


NEWTON

The NEWTON function returns an n-element vector containing the solution to a system of n non-linear equations in n dimensions using a globally-convergent Newton's method.

NEWTON is based on the routine newt described in section 9.7 of Numerical Recipes in C: The Art of Scientific Computing (Second Edition), published by Cambridge University Press, and is used by permission.

Calling Sequence

Result = NEWTON(X, Vecfunc)

Arguments

X

An n-element initial guess vector.

Vecfunc

A scalar string specifying the name of a user-supplied IDL function that defines the system of non-linear equations. This function must accept an n-element vector argument X and return an n-element vector result.

For example, suppose the non-linear system is defined by the following equations:

y0 = x0 + x1 ­ 3,     y1 = x0^2 +  x1^2 ­ 9

We write a function NEWTFUNC to express these relationships in the IDL language:

FUNCTION newtfunc, X

  RETURN, [X(0) + X(1) -3.0, X(0)^2 + X(1)^2 - 9.0]

END

Keywords

CHECK

NEWTON calls an internal function named fmin() to determine whether the routine has converged to a local minimum rather than to a global minimum (see Numerical Recipes, section 9.7). Use the CHECK keyword to specify a named variable which will be set to 1 if the routine has converged to a local minimum or to 0 if it has not. If the routine does converge to a local minimum, try restarting from a different initial guess to obtain the global minimum.

DOUBLE

Set this keyword to force the computation to be done in double-precision arithmetic.

ITMAX

The maximum allowed number of iterations. The default value is 200.

STEPMAX

The scaled maximum step length allowed in line search. The default value is 100.0.

TOLF

Set the convergence criterion on the function values. The default value is 1.0 x 10^-4.

TOLMIN

Set the criterion for deciding whether spurious convergence to a minimum of the function fmin() has occurred. The default value is 1.0 x 10^-6.

TOLX

Set the convergence criterion on X. The default value is 1.0 x 10^-7.

Example

Use NEWTON to solve an n-dimensional system of n non-linear equations. Systems of non-linear equations may have multiple solutions; starting the algorithms with different initial guesses enables detection of different solutions.

X = [1.0, 5.0]	Provide an initial guess as the algorithm's starting point.

result = NEWTON(X, 'newtfunc')	Compute the solution.

PRINT, result	Print the result.

IDL prints:

 -0.000346127 3.00000

X = [1.0, -1.0]	Try a different starting point.

result = NEWTON(X,'newtfunc')	Compute the solution.

PRINT, result	Print the result.

IDL prints:

  2.99999 8.37117e-05

See Also

FX_ROOT, BROYDEN, FZ_ROOTS


NORM

The NORM function computes the Euclidean norm of a vector. Alternatively, NORM computes the Infinity norm of an array.

This routine is written in the IDL language. Its source code can be found in the file norm.pro in the lib subdirectory of the IDL distribution.

Calling Sequence

Result = NORM(A)

Arguments

A

A can be either of the following:

•	An n-element real or complex vector, if NORM is being used to compute the Euclidean norm of a vector.

•	An m by n real or complex array, if NORM is being used to compute the Infinity norm of an array.

Keywords

DOUBLE

Set this keyword to force the computation to be done in double-precision arithmetic.

Examples

Define an  n-element complex vector A:

A = [COMPLEX(1, 0), COMPLEX(2,-2), COMPLEX(-3,1)]

PRINT, NORM(A)	Compute the Euclidean norm of A and print.

IDL prints:

4.35890

Define an m by n complex array A:

B = [[COMPLEX(1, 0), COMPLEX(2,-2), COMPLEX(-3,1)], $

     [COMPLEX(1,-2), COMPLEX(2, 2), COMPLEX(1, 0)]]

PRINT, NORM(B, /DOUBLE)	Compute the Infinity norm of B and print.

IDL prints:

6.9907048

See Also

COND


ON_ERROR

The ON_ERROR procedure determines the action taken when an error is detected inside an IDL user procedure or function.

Calling Sequence

ON_ERROR, N

Arguments

N

An integer that specifies the action to take. Valid values for N are:

•	0: Stop at the statement in the procedure that caused the error, the default action.

•	1: Return all the way back to the main program level.

•	2: Return to the caller of the program unit that established the ON_ERROR condition.

•	3: Return to the program unit that established the ON_ERROR condition.

See Also

CATCH, MESSAGE, ON_IOERROR, See "Error-Handling Routines" on page 11-2 of the IDL User's Guide.


ON_IOERROR

The ON_IOERROR procedure specifies a statement to be jumped to if an I/O error occurs in the current procedure. Normally, when an I/O error occurs, an error message is printed and program execution is stopped. If ON_IOERROR is called and an I/O related error later occurs in the same procedure activation, control is transferred to the designated statement with the error code stored in the system variables !ERR and !ERROR. The text of the error message is contained in the system variable !ERR_STRING.

The effect of ON_IOERROR can be canceled by using the label "NULL" in the call.

Calling Sequence

ON_IOERROR, Label

Example

The following code segment reads an integer from the keyboard. If an invalid number is entered, the program re-prompts.

i = 0	Number to read

valid = 0	Valid flag

WHILE valid EQ 0 DO BEGIN

   ON_IOERROR, bad_num

   READ, 'Enter Number: ', i

   VALID = 1	If we get here, i is good.

bad_num: IF NOT valid THEN $

         PRINT, 'You entered an invalid number.'

ENDWHILE

END

See Also

CATCH, MESSAGE, ON_ERROR, See "Error-Handling Routines" on page 11-2 of the IDL User's Guide.


ONLINE_HELP

The ONLINE_HELP procedure invokes the hypertext help viewer. If called with no arguments, it simply starts the help viewer with the default IDL help file displayed. Optionally, a different book, a keyword search string, or a context number can be specified. Note that this procedure is intended for use in user-written routines. To invoke IDL's online help from the command line, it is much simpler to use the ? command.

Calling Sequence

ONLINE_HELP [, Topic]

Arguments

Topic

An optional string that contains text to be searched for using the viewer's "keyword search" (not full-text search) facility. If this argument is omitted, the specified or default book is displayed at its beginning.

If the CONTEXT keyword is set, this argument should be an integer value (not a string) that represents the context number of the help topic to be displayed.

Keywords

BOOK

Set this keyword to a string containing the name of the online help "book" to be displayed. If this keyword is omitted, the default IDL help file is displayed. Any file specified by this keyword must be in the appropriate format for the viewer being invoked (e.g., on Windows, the file must be a Windows .hlp help file; on Unix, it must be a HyperHelp .hlp file).

By default, this string should be the name of a file found in the default location for IDL's online help files (i.e., wherever the file idl.hlp is installed), without a path or file extension. However, if the FULL_PATH keyword is set, this string should be a complete path and filename to the online help file you wish to display.

CONTEXT

Set this keyword to indicate that the Topic argument is an integer value that represents the context number of the help topic to be displayed. This keyword is intended for use with user-compiled help files that contain topics that have been mapped to specific context numbers when they were compiled (using the [MAP] section of the help project file). Specifying a non-existant context number causes the first topic of the requested help file to be displayed.

The help files shipped with IDL do not contain explicit context number mappings. Therefore, the context numbers of specific topics are undocumented, unknown, and subject to change between releases of the help system.

FULL_PATH

Set this keyword to indicate that the string specified by the BOOK keyword is the full path to the file, rather than the default "shorthand" file specification, as described above.

QUIT

Set this keyword to close the online help viewer.

Example

Use the following command to launch the online help viewer and perform a keyword search on the subject "handle":

ONLINE_HELP, 'handle'

To open a help file named adg.hlp, located in the default help file directory, use the command:

ONLINE_HELP, BOOK='adg.hlp'

To open a help file named myhelp.hlp, located in a directory named /usr/home/keith, use the command:

ONLINE_HELP, BOOK='/usr/home/keith/myfile.hlp', /FULL_PATH

To open the myhelp.hlp file from the previous example and display the topic corresponding to context number 100, use the command:

ONLINE_HELP, 100, /CONTEXT, $

             BOOK='/usr/home/keith/myfile.hlp', /FULL_PATH

See Also

MK_HTML_HELP, Chapter 13 of the IDL User's Guide


OPEN

The three OPEN procedures open a specified file for input and/or output.

•	OPENR (OPEN Read) opens an existing file for input only.

•	OPENW (OPEN Write) opens a new file for input and output. When creating a new file under VMS, a new file with the same name and a higher version number is created. Under other operating systems, if the file exists, it is truncated and its old contents are destroyed.

•	OPENU (OPEN Update) opens an existing file for input and output.

Calling Sequence

There are three forms of the OPEN procedure:

OPENR, Unit, File [, Record_Length]

OPENW,  Unit, File [, Record_Length]

OPENU,  Unit, File [, Record_Length]

Arguments

Unit

The unit number to be associated with the opened file.

File

A string containing the name of the file to be opened. Note the following platform-specific behaviors:

•	Under Unix, the filename can contain any wildcard characters recognized by the shell specified by the SHELL environment variable. However, it is faster not to use wildcards because IDL doesn't use the shell to expand file names unless it has to. No wildcard characters are allowed under VMS.

•	Under VMS, filenames that do not have a file extension are assumed to have the .DAT extension. No such processing of file names occurs under Unix.

Record_Length

The Record_Length argument has meaning only under VMS. It specifies the file record size in bytes. This argument is required when creating new, fixed-length files, and is optional when opening existing files. If this argument is present when creating variable-length record files, it specifies the maximum allowed record size. If this argument is present and no file organization keyword is specified, fixed-length records are implied.

Due to limitations in RMS (the VMS Record Management System), the length of records must always be an even number of bytes. Odd record lengths are therefore automatically rounded up to the nearest even boundary.

Keywords

Note: Platform-specific keywords are listed at the end of this section.

APPEND

Set this keyword to open the file with the file pointer at the end of the file, ready for data to be appended. Normally, the file is opened with the file pointer at the beginning of the file. Under Unix, use of APPEND prevents OPENW from truncating existing file contents.

BUFSIZE

Set this keyword to a value greater than 512 to specify the size of the I/O buffer (in bytes) used when reading and writing files. Setting BUFSIZE=1 (or any other value less than 512) sets the buffer to the default size, which is platform-specific. Set BUFSIZE=0 to disable I/O buffering.

Note that the buffer size is only changable when reading and writing stream files. Under Unix, the NOSTDIO keyword must not be set. Also not that the system stdio may choose to ignore the buffer size setting.

DELETE

Set this keyword to delete the file when it is closed.

Caution:  Setting the DELETE keyword causes the file to be deleted even if it was opened for read-only access. In addition, once a file is opened with this keyword, there is no way to cancel its operation.

ERROR

A named variable to place the error status in. If an error occurs in the attempt to open File, IDL normally takes the error handling action defined by the ON_ERROR and/or ON_IOERROR procedures. OPEN always returns to the caller without generating an error message when ERROR is present. A nonzero error status indicates that an error occurred. The error message can then be found in the system variable !ERR_STRING.

For example, statements similar to the following can be used to detect errors:

OPENR, 1, 'demo.dat', ERROR = err
Try to open the file demo.dat.

IF (err NE 0) then PRINTF, -2, !ERR_STRING
If err is nonzero, something happened. Print the error message to the standard error file (logical unit -2).

GET_LUN

Set this keyword to use the GET_LUN procedure to set the value of Unit  before the file is opened. Instead of using the two statements:

GET_LUN, Unit

OPENR, Unit, 'data.dat'

you can use the single statement:

OPENR, Unit, 'data.dat', /GET LUN

MORE

If MORE is set, and the specified File is a terminal, then all output to this unit is formatted in a manner similar to the Unix more(1) command and sent to the standard output stream. Output pauses at the bottom of each screen, at which point the user can press one of the following keys:

•	Space: Display the next page of text.

•	Return: Display the next line of text.

•	`q' or `Q': Suppress all remaining output.

•	`h' or `H': Display this list of options.

For example, the following statements show how to output a file named text.dat to the terminal:

OPENR, inunit, 'text.dat', /GET_LUN
Open the text file.

OPENW, outunit, '/dev/tty', /GET_LUN, /MORE
Open the terminal as a file.

line = '' & READF, inunit, line
Read the first line.

WHILE NOT EOF(inunit) DO BEGIN
While there is text left, output it.

   PRINTF, outunit, line

   READF, inunit, line

ENDWHILE

FREE_LUN, inunit & FREE_LUN, outunit
Close the files and deallocate the units.

WIDTH

The desired output width. When using the defaults for formatted output, IDL uses the following rules to determine where to break lines:

•	If the output file is a terminal, the terminal width is used. Under VMS, if the file has fixed-length records or a maximum record length, the record length is used.

•	Otherwise, a default of 80 columns is used.

The WIDTH keyword allows the user to override this default.

XDR

Set this keyword to open the file for unformatted XDR (eXternal Data Representation) I/O via the READU and WRITEU procedures. Use XDR to make binary data portable between different machine architectures by reading and writing all data in a standard format. When a file is open for XDR access, the only I/O data transfer procedures that can be used with it are READU and WRITEU.

Under VMS, the XDR keyword can only be used with stream files.

Macintosh-Only Keywords

MACCREATOR

Use this keyword to specify a four-character scalar string identifying the Macintosh file creator code of the file being created. For example, set

MACCREATOR = 'MSWD'

to create a file with the creator code MSWD. The default creator code is MIDL.

MACTYPE

Use this keyword to specify a four-character scalar string identifying the Macintosh file type of the file being created. For example, set

MACTYPE = 'PICT'

to create a file of type PICT. The default file type is TEXT.

Unix-Only Keywords

F77_UNFORMATTED

Unformatted variable-length record files produced by Unix FORTRAN programs contain extra information along with the data in order to allow the data to be properly recovered. This method is necessary because FORTRAN input/output is based on record-oriented files, while Unix files are simple byte streams that do not impose any record structure. Set the F77_UNFORMATTED keyword to read and write this extra information in the same manner as f77(1), so that data to be processed by both IDL and FORTRAN.

NOSTDIO

Set this keyword to disable all use of the standard Unix I/O for the file, in favor of direct calls to the operating system. This allows direct access to devices, such as tape drives, that are difficult or impossible to use effectively through the standard I/O. Using this keyword has the following implications:

•	No formatted or associated (ASSOC) I/O is allowed on the file. Only READU and WRITEU are allowed.

•	Normally, attempting to read more data than is available from a file causes the unfilled space to be set to zero and an error to be issued. This does not happen with files opened with NOSTDIO. When using NOSTDIO, the programmer must check the transfer count, either via the TRANSFER_COUNT keywords to READU and WRITEU, or the FSTAT function.

•	The EOF and POINT_LUN functions cannot be used with a file opened with NOSTDIO.

•	Each call to READU or WRITEU maps directly to Unix read(2) and write(2) system calls. The programmer must read the Unix system documentation for these calls and documentation on the target device to determine if there are any special rules for I/O to that device. For example, the size of data that can be transferred to many cartridge tape drives is often forced to be a multiple of 512 bytes.

VMS-Only Keywords

BLOCK

Set this keyword to process the file using RMS block mode. In this mode, most RMS processing is bypassed and IDL reads and writes to the file in disk block units. Such files can only be accessed via unformatted I/O commands. Block mode files are treated as an uninterpreted stream of bytes in a manner similar to Unix stream files.

For best performance, by default IDL uses RMS block mode for fixed length record files. However, when the SHARED keyword is present, IDL uses standard RMS mode. Do not specify both BLOCK and SHARED.

This keyword is ignored when used with stream files.

Note: With some controller/disk combinations, RMS does not allow transfer of an odd number of bytes.

DEFAULT

A scalar string that provides a default file specification from which missing parts of the File argument are taken. For example, to make .LOG be the default file extension when opening a new file, use the command:

OPENW, 'DATA', DEFAULT='.LOG'

This statement will open the file DATA.LOG.

EXTENDSIZE

File extension is a relatively slow operation, and it is desirable to minimize the number of times it is done. In order to avoid the unacceptable performance that would result from extending a file a single block at a time, VMS extends its size by a default number of blocks in an attempt to trade a small amount of wasted disk space for better performance. The EXTENDSIZE keyword overrides the default, and specifies the number of disk blocks by which the file should be extended. This keyword is often used in conjunction with the INITIALSIZE and TRUNCATE_ON_CLOSE keywords.

FIXED

Set this keyword to indicate that the file has fixed-length records. The Record_Length argument is required when opening new, fixed-length files.

FORTRAN

Set this keyword to use FORTRAN-style carriage control when creating a new file.

INITIALSIZE

The initial size of the file allocation in blocks. This keyword is often used in conjunction with the EXTENDSIZE and TRUNCATE_ON_CLOSE keywords.

KEYED

Set this keyword to indicate that the file has indexed organization.

LIST

Set this keyword to specify carriage-return carriage control when creating a new file. If no carriage-control keyword is specified, LIST is the default.

NONE

Set this keyword to specify explicit carriage control when creating a new file. When using explicit carriage control, VMS does not add any carriage control information to the file, and the user must explicitly add any desired carriage control to the data being written to the file.

PRINT

Set this keyword to send the file to SYS$PRINT, the default system printer, when it is closed.

SEGMENTED

Set this keyword to indicate that the file has VMS FORTRAN-style segmented records. Segmented records are a method by which FORTRAN allows logical records to exist with record sizes that exceed the maximum possible physical record sizes supported by VMS. Segmented record files are useful primarily for passing data between FORTRAN and IDL programs.

SHARED

Set this keyword to allow other processes read and write access to the file in parallel with IDL. If SHARED is not set, read-only files are opened for read sharing and read/write files are not shared.

Caution: It is not a good idea to allow shared write access to files open in RMS block mode. In block mode, VMS cannot perform the usual record locking that prevents file corruption. It is therefore possible for multiple writers to corrupt a block mode file. This warning also applies to fixed-length record disk files, which are also processed in block mode. When using SHARED, do not specify either BLOCK or UDF_BLOCK.

STREAM

Set this keyword to open the file in stream mode.

SUBMIT

Set this keyword to submit the file to SYS$BATCH, the default system batch queue, when it is closed.

SUPERSEDE

Set this keyword to allow an existing file to be superseded by a new file of the same name, type, and version.

TRUNCATE_ON_CLOSE

Set this keyword to free any unused disk space allocated to the file when the file is closed. This keyword can be used to get rid of excess allocations caused by the EXTENDSIZE and INITIALSIZE keywords. If the SHARED keyword is set, or the file is open for read-only access, TRUNCATE_ON_CLOSE has no effect.

UDF_BLOCK

Set this keyword to create a file similar to those created with the BLOCK keyword except that new files are created with the RMS undefined record type. Files created in this way can only be accessed by IDL in block mode, and cannot be processed by many VMS utilities. Do not specify both UDF_BLOCK and SHARED.

VARIABLE

Set this keyword to indicate that the file has variable-length records. If the Record_Length argument is present, it specifies the maximum record size. Otherwise, the only limit is that imposed by RMS (32767 bytes). If no file organization is specified, variable-length records are the default.

Example

The following example opens the IDL distribution file people.dat and reads an image from that file:

OPENR, 1, FILEPATH('people.dat', SUBDIR = 'images')
Open "people.dat" on file unit number 1. The FILEPATH function is used to return the full path name to this distribution file.

image=BYTARR(192, 192, /NOZERO)	Define a variable into which the image will be read.

READU, 1, image	Read the data.

TV, image	Display the image.

See Also

CLOSE, GET_LUN, POINT_LUN, PRINT, READ, READU, WRITEU


OPLOT

The OPLOT procedure plots vector data over a previously-drawn plot. It differs from PLOT only in that it does not generate a new axis. Instead, it uses the scaling established by the most recent call to PLOT and simply overlays a plot of the data on the existing axis.

Calling Sequence

OPLOT, [X,] Y

Arguments

X

A vector argument. If X is not specified, Y is plotted as a function of point number (starting at zero). If both arguments are provided, Y is plotted as a function of X.

This argument is converted to single-precision floating-point before plotting. Plots created with OPLOT are limited to the range and precision of single-precision floating-point values.

Y

The ordinate data to be plotted. This argument is converted to single-precision floating-point before plotting.

Keywords

MAX_VALUE

The maximum value to be plotted. If this keyword is present, data values greater than the value of MAX_VALUE are treated as missing and are not plotted. Note that the IEEE floating-point value NaN is also treated as missing data. (See "Special Floating-Point Values" on page 11-9 of the IDL User's Guide for more information on IEEE floating-point values.)

MIN_VALUE

The minimum value to be plotted. If this keyword is present, data values less than the value of MIN_VALUE are treated as missing and are not plotted. Note that the IEEE floating-point value NaN is also treated as missing data. (See "Special Floating-Point Values" on page 11-9 of the IDL User's Guide for more information on IEEE floating-point values.)

NSUM

The presence of this keyword indicates the number of data points to average when plotting. If NSUM is larger than 1, every group of NSUM points is averaged to produce one plotted point. If there are m data points, then m/NSUM points are displayed. On logarithmic axes a geometric average is performed.

It is convenient to use NSUM when there is an extremely large number of data points to plot because it plots fewer points, the graph is less cluttered, and it is quicker.

POLAR

Set this keyword to produce polar plots. The X and Y vector parameters, both of which must be present, are first converted from polar to Cartesian coordinates. The first parameter is the radius, and the second is, expressed in radians. For example, to make a polar plot, use the command:

OPLOT, /POLAR, R, THETA

THICK

Controls the thickness of the lines connecting the points. A thickness of 1.0 is normal, 2.0 is double wide, etc.

Graphics Keywords Accepted

See Chapter 2, "Graphics Keywords and System Variables", for the description of graphics and plotting keywords not listed above. CLIP COLOR LINESTYLE NOCLIP PSYM SUBTITLE SYMSIZE T3D ZVALUE.

Example

Create a simple dataset by entering:

D = SIN(FINDGEN(100)/EXP(FINDGEN(100)/50))

Create an X-Y plot of vector D by entering:

PLOT, D

Overplot the sine of D as a thick, dashed line by entering:

OPLOT, SIN(D), LINESTYLE = 5, THICK = 2

See Also

OPLOTERR, PLOT


OPLOTERR

The OPLOTERR procedure plots error bars over a previously drawn plot. A plot of X versus Y with error bars drawn from Y - Err to Y + Err is written to the output device over any plot already there.

This routine is written in the IDL language. Its source code can be found in the file oploterr.pro in the lib subdirectory of the IDL distribution.

Calling Sequence

OPLOTERR, [ X ,] Y , Err [, Psym ]

Arguments

X

An optional array of X values. The procedure checks whether or not the third parameter passed is a vector to decide if X was passed. If X is not passed, then INDGEN(Y) is assumed for the X values.

Y

The array of Y values. Y cannot be of type string.

Err

The array of error bar values.

PSYM

The plotting symbol to use (default = +7).

See Also

ERRPLOT, OPLOT, PLOTERR


P_CORRELATE

The P_CORRELATE function computes the partial correlation coefficient of a dependent variable and one particular independent variable when the effects of all other variables involved are removed.

This routine is written in the IDL language. Its source code can be found in the file P_correlate.pro in the lib subdirectory of the IDL distribution.

Calling Sequence

Result = P_CORRELATE(X, Y, C)

Arguments

X

An n-element integer, single-, or double-precision floating-point vector that specifies the independent variable data.

Y

An n-element integer, single-, or double-precision floating-point vector that specifies the dependent variable data.

C

An integer, single-, or double-precision floating-point array that specifies the independent variable data whose effects are to be removed. The columns of this two-dimensional array correspond to the n-element vectors of independent variable data.

Examples

Define three sample populations:

X0 = [64, 71, 53, 67, 55, 58, 77, 57, 56, 51, 76, 68]

X1 = [57, 59, 49, 62, 51, 50, 55, 48, 52, 42, 61, 57]

X2 = [ 8, 10, 6, 11, 8, 7, 10, 9, 10, 6, 12, 9]

Compute the partial correlation of X0 and X1  with the effects of X2 removed. The result should be 0.533469.

result = P_CORRELATE(X0, X1, REFORM(X2, 1, N_ELEMENTS(X2)))

See Also

A_CORRELATE, CORRELATE, C_CORRELATE, M_CORRELATE, R_CORRELATE


PICKFILE

The PICKFILE function allows the user to interactively pick a file. A file selection tool with a graphical user interface is displayed. Files can be selected from the current directory or other directories. On Macintosh and Windows platforms, the built-in file selection dialogs are called. Under other windowing systems, an IDL widget interface is used. PICKFILE does not recognize symbolic links to other files in UNIX.

PICKFILE returns a string that contains the name of the selected file. If no file is selected, PICKFILE returns a null string.

This routine is written in the IDL language. Its source code can be found in the file pickfile.pro in the lib subdirectory of the IDL distribution.

Calling Sequence

Result = PICKFILE()

Keywords

FILE

Set this keyword to a scalar string that contains the name of the initial file selection. This keyword is useful for specifying a default filename.

GET_PATH

Set this keyword to a named variable in which the path of the selection is returned.

GROUP

The widget ID of the widget that calls PICKFILE. When this ID is specified, a death of the caller results in the death of the PICKFILE widget application.

READ

Set this keyword to make the title of the PICKFILE window "Select File to Read".

WRITE

Set this keyword to make the title of the PICKFILE window "Select File to Write".

PATH

Set this keyword to a string that contains the initial path from which to select files. If this keyword is not set, the current working directory is used.

FILTER

A string value for filtering the files in the file list. This keyword is used to reduce the number of files to choose from. The user can modify the filter unless the FIX_FILTER keyword is set. Example filter values could be '*.pro' or '*.dat'.

FIX_FILTER

When this keyword is set, only files that satisfy the filter can be selected. The user has no ability to modify the filter and the filter is not shown.

TITLE

Set this keyword to a scalar string to be used for the window title. If it is not specified, the default title is "Select File".

NOCONFIRM

Set this keyword to return immediately upon selection of a file. The default behavior is to display the selection and then return the file when the user clicks the "OK" button.

MUST_EXIST

Set this keyword to allow only files that already exist to be selected.

Example

Create a PICKFILE widget that lets users select only files with the extensions `pro' and `dat'. Use the `Select File to Read' title and store the name of the selected file in the variable F. Enter:

F = PICKFILE(/READ, FILTER = '*.pro *.dat')

See Also

FILEPATH


PLOT

The PLOT procedure draws graphs of vector arguments. If one parameter is used, the vector parameter is plotted on the ordinate versus the point number on the abscissa. To plot one vector as a function of another, use two parameters. PLOT can also be used to create polar plots by setting the POLAR keyword.

Calling Sequence

PLOT,  [X,] Y

Arguments

X

A vector argument. If X is not specified, Y is plotted as a function of point number (starting at zero). If both arguments are provided, Y is plotted as a function of X.

This argument is converted to single-precision floating-point before plotting. Plots created with PLOT are limited to the range and precision of single-precision floating-point values.

Y

The ordinate data to be plotted. This argument is converted to single-precision floating-point before plotting.

Keywords

MAX_VALUE

The maximum value to be plotted. If this keyword is present, data values greater than the value of MAX_VALUE are treated as missing and are not plotted. Note that the IEEE floating-point value NaN is also treated as missing data. (See "Special Floating-Point Values" on page 11-9 of the IDL User's Guide for more information on IEEE floating-point values.)

MIN_VALUE

The minimum value to be plotted. If this keyword is present, data values less than the value of MIN_VALUE are treated as missing and are not plotted. Note that the IEEE floating-point value NaN is also treated as missing data. (See "Special Floating-Point Values" on page 11-9 of the IDL User's Guide for more information on IEEE floating-point values.)

NSUM

The presence of this keyword indicates the number of data points to average when plotting. If NSUM is larger than 1, every group of NSUM points is averaged to produce one plotted point. If there are m data points, then m/NSUM points are displayed. On logarithmic axes a geometric average is performed.

It is convenient to use NSUM when there is an extremely large number of data points to plot because it plots fewer points, the graph is less cluttered, and it is quicker.

POLAR

Set this keyword to produce polar plots. The X and Y vector parameters, both of which must be present, are first converted from polar to Cartesian coordinates. The first parameter is the radius, and the second is, expressed in radians. For example, to make a polar plot, you would use a command such as:

PLOT, /POLAR, R, THETA

THICK

Controls the thickness of the lines connecting the points. A thickness of 1.0 is normal, 2 is double wide, etc.

XLOG

Set this keyword to specify a logarithmic X axis, producing a log-linear plot. Set both XLOG and YLOG to produce a log-log plot. Note that logarithmic axes that have ranges of less than a decade are not labeled.

YNOZERO

Set this keyword to inhibit setting the minimum Y axis value to zero when the Y data are all positive and nonzero, and no explicit minimum Y value is specified (using YRANGE, or !Y.RANGE). By default, the Y axis spans the range of 0 to the maximum value of Y, in the case of positive Y data. Set bit 4 in !Y.STYLE to make this option the default.

YLOG

Set this keyword to specify a logarithmic Y axis, producing a linear-log plot. Set both XLOG and YLOG to produce a log-log plot. Note that logarithmic axes that have ranges of less than a decade are not labeled.

ZLOG

Set this keyword to specify a logarithmic Z axis. Note that logarithmic axes that have ranges of less than a decade are not labeled.

Graphics Keywords Accepted

See Chapter 2, "Graphics Keywords and System Variables", for the description of graphics and plotting keywords not listed above. BACKGROUND CHARSIZE  CHARTHICK CLIP COLOR DATA DEVICE FONT LINESTYLE NOCLIP NODATA NOERASE NORMAL POSITION PSYM SUBTITLE SYMSIZE T3D THICK  TICKLEN TITLE [XYZ]CHARSIZE  [XYZ]GRIDSTYLE [XYZ]MARGIN [XYZ]MINOR [XYZ]RANGE [XYZ]STYLE [XYZ]THICK [XYZ]TICKFORMAT [XYZ]TICKLEN [XYZ]TICKNAME [XYZ]TICKS [XYZ]TICKV [XYZ]TICK_GET [XYZ]TITLE ZVALUE.

Example

The PLOT procedure has many keywords that allow you to create a vast variety of plots. Here are a few simple examples using the PLOT command. Create a simple dataset by entering:

D = FINDGEN(100)

To create a simple plot with the title "Simple Plot", enter:

PLOT, D, TITLE = 'Simple Plot'

Plot one argument versus another by entering:

PLOT, SIN(D/3), COS(D/6)

Create a polar plot with the command:

PLOT, D, D, /POLAR, TITLE = 'Polar Plot'

Use plotting symbols instead of connecting lines by including the PSYM keyword. Also, label the X and Y axes with the command:

PLOT, SIN(D/10), PSYM=4, XTITLE='X Axis', YTITLE='Y Axis'

See Also

OPLOT, PLOTS


PLOT_3DBOX

The PLOT_3DBOX procedure plots a function of two variables (e.g., Z=f(X, Y)) inside a 3D box. Optionally, the data can be projected onto the "walls" surrounding the plot area.

Calling Sequence

PLOT_3DBOX, X, Y, Z

Arguments

X

A vector (i.e., a one-dimensional array) of X coordinates.

Y

A vector of Y coordinates.

Z

A vector of Z coordinates. Z(i) is a function of X(i) and Y(i).

Keywords

BACKGROUND

Set this keyword to a color index to be used as the background color for the plot. If the SOLID_WALLS keyword is set, this keyword controls the color of the grid and plotted data.

COLOR

Set this keyword to a color index to be used for the grid and plotted data. If the SOLID_WALLS keyword is set, this keyword controls the color of the box walls.

GRIDSTYLE

Set this keyword to the linestyle index for the type of line to be used when drawing the gridlines. Linestyles are described in the table below:

Index	Linestyle
0	Solid
1	Dotted
2	Dashed
3	Dash Dot
4	Dash Dot Dot Dot
5	Long Dashes
Table 1.12 IDL Linestyles

LINESTYLE

Set this keyword to the linestyle index to be used for plotting the data. See the table above for a list of linestyles.

PSYM

Set this keyword to an plotting symbol index to be used in plotting the data. For more information, see "PSYM" on page 2-19.

SOLID_WALLS

Set this keyword to cause the boundary "walls" of the plot to be filled with the color index specified by the COLOR keyword.

SUBTITLE

Set this keyword to a string containing the subtitle for the plot.

TITLE

Set this keyword to a string containing the main title for the plot.

XTITLE

Set this keyword to a string containing the label for the X axis.

XY_PLANE

Set this keyword to plot the X and Y values on the Z=0 axis plane.

XYSTYLE

Set this keyword to the linestyle used to draw the XY plane plot. See the table above for a list of linestyles.

XZ_PLANE

Set this keyword to plot the Y and Z values on the Y=MAX(Y) axis plane.

XZSTYLE

Set this keyword to the linestyle used to draw the XZ plane plot. See the table above for a list of linestyles.

YTITLE

Set this keyword to a string containing the label for the Y axis.

YZ_PLANE

Set this keyword to plot the Y and Z values on the X=MAX(X) axis plane.

YZSTYLE

Set this keyword to the linestyle used to draw the YZ plane plot. See the table above for a list of linestyles.

ZTITLE

Set this keyword to a string containing the label for the Z axis.

SURFACE Keywords

In addition to the keywords described above, all other keywords accepted by the SURFACE procedure are accepted by PLOT_3DBOX. See "SURFACE" on page 1-869.

Example

X = REPLICATE(5., 10.)	Create some data to be plotted.

X1 = COS(FINDGEN(36)*10.*!DTOR)*2.+5.

X = [X, X1, X]

Y = FINDGEN(56)

Z = REPLICATE(5., 10)

Z1 = SIN(FINDGEN(36)*10.*!DTOR)*2.+5.

Z = [Z, Z1, Z]

PLOT_3DBOX, X, Y, Z, /XY_PLANE, /YZ_PLANE, /XZ_PLANE, $

         /SOLID_WALLS, GRIDSTYLE=1, XYSTYLE=3, XZSTYLE=4, $

         YZSTYLE=5, AZ=40, TITLE='Example Plot Box', $

         XTITLE='X Coordinate', YTITLE='Y Coodinate', $

         ZTITLE='Z Coordinate', SUBTITLE='Sub Title', $

         /YSTYLE, ZRANGE=[0,10], XRANGE=[0,10], $

         PSYM=-4, CHARSIZE=1.6	Create the box plot with data projected on all of the walls. The PSYM value of -4 plots the data as diamonds connected by lines.

See Also

PLOTS, SURFACE


PLOT_FIELD

The PLOT_FIELD procedure plots a 2D field. N random points are picked, and from each point a path is traced along the field. The length of the path is proportional to the field vector magnitude.

This routine is written in the IDL language. Its source code can be found in the file plot_field.pro in the lib subdirectory of the IDL distribution.

Calling Sequence

PLOT_FIELD, U, V

Arguments

U

A 2D array giving the field vector at each point in the U(X) direction.

V

A 2D array giving the field vector at each point in the V(Y) direction.

Keywords

ASPECT

The aspect ratio of the plot (i.e., the ratio of the X size to Y size). The default is 1.0.

LENGTH

The length of the longest field vector expressed as a fraction of the plotting area. The default is 0.1.

N

The number of arrows to draw. The default is 200.

TITLE

The title of plot. The default is "Velocity Field".

Example

X = FINDGEN(20, 20)	Create array X.

Y = FINDGEN(20, 20)*3	Create array Y.

PLOT_FIELD, X, Y	Create plot.

See Also

FLOW3, VEL, VELOVECT


PLOTERR

The PLOTERR procedure plots individual data points with error bars.

This routine is written in the IDL language. Its source code can be found in the file ploterr.pro in the lib subdirectory of the IDL distribution.

Calling Sequence

PLOTERR, [ X ,] Y , Err

Arguments

X

An optional array of X values. The procedure checks the number of arguments passed to decide if X was passed. If X is not passed, then INDGEN(Y) is assumed for the X values.

Y

The array of Y values. Y cannot be of type string.

Err

The array of error-bar values.

Keywords

ITYPE

The type of plot to be produced. The possible types are:

•	0	X Linear - Y Linear (default)

•	1	X Linear - Y Log

•	2	X Log - Y Linear

•	3	X Log - Y Log

PSYM

The plotting symbol to use. The default is +7.

See Also

ERRPLOT, OPLOTERR, PLOT


PLOTS

The PLOTS procedure plots vectors or points on the current graphics device in either two or three dimensions. The coordinates can be given in data, device, or normalized form using the DATA (the default), DEVICE, or NORMAL keywords.

The COLOR keyword can be set to a scalar or vector value. If it is set to a vector value, the line segment connecting (Xi, Yi) to (Xi+1, Yi+1) is drawn with a color index of COLORi+1. In this case, COLOR must have the same number of elements as X and Y.

Calling Sequence

PLOTS, X [, Y [, Z]]

Arguments

X

A vector or scalar argument providing the X components of the points to be connected. If only one argument is specified, X must be an array of either two or three vectors (i.e., (2,*) or (3,*)). In this special case, X(0,*) is taken as the X values, X(1,*) is taken as the Y values, and X(2,*) is taken as the Z values.

Y

An optional argument providing the Y coordinate(s) of the points to be connected.

Z

An optional argument providing the Z coordinates of the points to be connected. If Z is not provided, X and Y are used to draw lines in two dimensions.

Z has no effect if the keyword T3D is not specified and the system variable !P.T3D= 0.

Keywords

CONTINUE

Set this keyword to continue drawing a line from the last point of the most recent call to PLOTS. For example:

PLOTS, 0, 0	Position at (0,0).

PLOTS, 1, 1, /CONTINUE	Draws vector from (0,0) to (1,1).

PLOTS, [2,3], [2,3], /CONTINUE
Draws two vectors from (1,1) to (2,2) to (3,3).

Graphics Keywords Accepted

See Chapter 2, "Graphics Keywords and System Variables", for the description of graphics and plotting keywords not listed above. CLIP COLOR DATA DEVICE LINESTYLE NOCLIP NODATA NOERASE NORMAL PSYM SYMSIZE T3D THICK Z.

Examples

Draw a line from (100, 200) to (600, 700), in device coordinates, using color index 12:

PLOTS, [100,600], [200,700], COLOR=12, /DEVICE

Draw a polyline where the line color is proportional to the ordinate that ends each line segment. First create datasets X and Y by entering:

X = SIN(FINDGEN(100)) & Y = COS(FINDGEN(100))

Now plot X and Y in normalized coordinates with colors as described above:

PLOTS, X, Y, COLOR = BYTSCL(Y, TOP=!D.N COLORS-1), /NORMAL

Load a good colortable to better show the result. Enter:

LOADCT, 13

Draw 3D vectors over an established SURFACE plot:

SURFACE, DIST(5), /SAVE	The SAVE keyword tells IDL to save the 3D transformation established by SURFACE.

PLOTS, [0,3], [0,3], [0,3], /T3D	Draw a line between (0,0,0) and (3,3,3). The T3D keyword makes PLOTS use the previously established 3D transformation.

PLOTS, [3,3], [0,3], [0,3], /T3D	Draw a line between (3,0,0) and (3,3,3).

PLOTS, [0,3], [3,3], [0,3], /T3D	Draw a line between (0,3,0) and (3,3,3).

See Also

ANNOTATE, XYOUTS


PNT_LINE

The PNT_LINE function returns the perpendicular distance between a point P0 and a line between points L0 and L1. This function is limited by the machine accuracy of single precision floating point.

This routine is written in the IDL language. Its source code can be found in the file pnt_line.pro in the lib subdirectory of the IDL distribution.

Calling Sequence

Result = PNT_LINE(P0, L0, L1 [, Pl])

Arguments

P0

The location of the point. P0 may have 2 to n  elements, for n dimensions.

L0

One end-point of the line. L0 must have same number of elements as P0.

L1

The other end-point of the line. L1 must have the same number of elements as L0.

Pl

A named variable that will contain the location of the point on the line between L0 and L1 that is closest to P0. Pl is not necessarily in the interval (L0, L1).

Keywords

INTERVAL

If set, and if the point on the line between L0 and L1 that is closest to P0 is not within the interval (L0, L1), PNT_LINE will return the distance from P0 to the closer of the two endpoints L0 and L1.

Example

To print the distance between the point (2,3) and the line from (-3,3) to (5,12), and also the location of the point on the line closest to (2,3), enter the following command:

PRINT, PNT_LINE([2,3], [-3,3], [5,12], Pl), Pl

IDL prints:

3.73705    -0.793104      5.48276

See Also

CIR_3PNT, SPH_4PNT


POINT_LUN

The POINT_LUN procedure sets or obtains the current position of the file pointer for the specified file.

Note that POINT_LUN cannot be used with files opened with the NOSTDIO keyword to the OPEN routines. Depending upon the device in question, the IOCTL function might be used instead for files of this type.

Calling Sequence

POINT_LUN, Unit, Position

Arguments

Unit

The file unit for the file in question. If Unit is positive, POINT_LUN sets the file position to the position given by Position. If negative, POINT_LUN gets the current file position and assigns it to the variable given by Position. Note that POINT_LUN cannot be used with the 3 standard file units (0, -1, and -2).

Position

If Unit is positive, Position gives the byte offset into the file at which the file pointer should be set (hence, to rewind the file to the beginning, specify 0). If Unit is negative, Position must be a named variable into which the current file position will be stored.

Under VMS, be careful to move the file pointer only to record boundaries. It is always safe to move to a file position that was previously obtained via POINT_LUN or the FSTAT function. Files with indexed organization can only be positioned to the beginning of the file.

Example

To move the file pointer 2048 bytes into the file associated with file unit number 1, enter:

POINT_LUN, 1, 2048

To find the position of the file pointer in the file associated with file unit 2 and store that position in the variable pos, enter:

POINT_LUN, -2, pos

See Also

GET_LUN, OPEN


POLAR_CONTOUR

The POLAR_CONTOUR procedure draws a contour plot from data in polar coordinates. Data can be regularly- or irregularly-gridded. All of the keyword options supported by CONTOUR are available to POLAR_CONTOUR.

This routine is written in the IDL language. Its source code can be found in the file polar_contour.pro in the lib subdirectory of the IDL distribution.

Calling Sequence

POLAR_CONTOUR, Z, Theta, R

Arguments

Z

The data values to be contoured. If the data is regularly gridded, Z must have the dimensions (N_ELEMENTS(Theta), N_ELEMENTS(R).

Theta

A vector of angles in radians. For regularly-gridded data, Theta must have the same number of elements as the first dimension of Z. For a scattered grid, Theta must have the same number of elements as Z.

R

A vector of radius values. For regularly-gridded data, R must have the same number of elements as the second dimension of Z. For a scattered grid, R must have the same number of elements as Z.

Keywords

POLAR_CONTOUR accepts and keywords that are accepted by the CONTOUR routine. See "CONTOUR" on page 1-122. In addition, there is one unique keyword:

SHOW_TRIANGULATION

Set this keyword to a color index to be used in overplotting the triangulation between datapoints.

Example

The first example uses POLAR_CONTOUR with regularly-gridded data:

nr = 12	The number of radii.

nt = 18	The number of Thetas.

r = FINDGEN(nr)/(nr-1)	Create a vector of radii.

theta = 2*!PI * FINDGEN(nt)/(nt-1)
Create a vector of Thetas.

z = COS(theta*3) # (r-0.5)^2	Create some data values to be contoured.

POLAR_CONTOUR, z, theta, r, /FILL, c_color=[2, 3, 4, 5]
Create the polar contour plot.

See Also

CONTOUR


POLAR_SURFACE

The POLAR_SURFACE function interpolates a surface from polar coordinates (R, Theta, Z) to rectangular coordinates (X, Y, Z). The function returns a two-dimensional array of the same type as Z.

This routine is written in the IDL language. Its source code can be found in the file polar_surface.pro in the lib subdirectory of the IDL distribution.

Calling Sequence

Result = POLAR_SURFACE(Z, R, Theta)

Arguments

Z

An array containing the surface value at each point. If the data are regularly gridded in R and Theta, Z is a two dimensional array, where Zi,j has a radius of Ri and an azimuth of Thetaj. If the data are irregularly-gridded, Ri and Thetai contain the radius and azimuth of each Zi.

R

The radius. If the data are regularly gridded in R and Theta, Zi,j has a radius of Ri. If the data are irregularly-gridded, R must have the same number of elements as Z, and contains the radius of each point.

Theta

The azimuth, in radians. If the data are regularly gridded in R and Theta, Zi,j has an azimuth of Thetaj. If the data are irregularly-gridded, Theta must have the same number of elements as Z, and contains the azimuth of each point.

Keywords

GRID

Set this keyword to indicate that Z is regularly gridded in  R and Theta.

SPACING

A two element vector containing the desired grid spacing of the resulting array in x and y. If omitted, the grid will be approximately 51 by 51.

BOUNDS

A four element vector, [x0, y0,  x1, y1], containing the limits of the xy grid of the resulting array. If omitted, the extent of input data sets the limits of the grid.

QUINTIC

Set this keyword to use quintic interpolation, which is slower but smoother than the default linear interpolation.

MISSING

Use this keyword to specify a value to use for areas within the grid but not within the convex hull of the data points. The default is 0.0.

Example

R = FINDGEN(50) / 50.0	The radius.

THETA = FINDGEN(50) * (2 * !PI / 50.0)
Theta.

Z = R # SIN(THETA)	Make a function (tilted circle).

SURFACE, POLAR_SURFACE(Z, R, THETA, /GRID)
Show it.

See Also

POLAR Keyword (to PLOT)


POLY

The POLY function evaluates a polynomial function of a variable. The result is equal to:

C0 + C1x + C2x^2 + ...

This routine is written in the IDL language. Its source code can be found in the file poly.pro in the lib subdirectory of the IDL distribution.

Calling Sequence

Result = POLY(X, C)

Arguments

X

The variable. This value can be a scalar, vector or array.

C

The vector of polynomial coefficients. The degree of the polynomial is N_ELEMENTS(C) - 1.

See Also

FZ_ROOTS


POLY_2D

The POLY_2D function performs polynomial warping of images. This function performs a geometrical transformation in which the resulting array is defined by:

g (x, y) =  f (x', y ') = f [a ( x, y), b  (x, y)]

where g(x, y) represents the pixel in the output image at coordinate (x, y), and f (x', y') is the pixel at (x', y') in the input image that is used to derive g(x, y). The functions a (x, y) and b (x, y) are polynomials in x and y of degree  N, whose coefficients are given by P and Q, and specify the spatial transformation:

Either the nearest neighbor or bilinear interpolation methods can be selected.

Calling Sequence

Result = POLY_2D(Array, P, Q [, Interp [, Dimx, Dimy]])

Arguments

Array

A two-dimensional array of any basic type except string. The result has the same type as Array.

P and Q

P and Q are arrays containing the polynomial coefficients. Each array must contain (N+1)^2 elements (where N is the degree of the polynomial). For example, for a linear transformation, P and Q  contain four elements and can be a 2 by 2 array or a 4-element vector. Pi,j contains the coefficient used to determine  x', and is the weight of the term x^jy^i. The POLYWARP procedure can be used to fit (x', y') as a function of (x, y)  and determines the coefficient arrays P and Q.

Interp

Set this argument to a 1to perform bilinear interpolation. Set this argument to 2 to perform cubic convolution interpolation (as described under the CUBIC keyword, below). Otherwise, the nearest neighbor method is used. For the linear case, (N=1), bilinear interpolation requires approximately twice as much time as does the nearest neighbor method.

Dimx

If present, Dimx specifies the number of columns in the output. If omitted, the output has the same number of columns as Array.

Dimy

If present, Dimy specifies the number of rows in the output. If omitted, the output has the same number of rows as Array.

Keywords

CUBIC

Set this keyword to use the cubic convolution interpolation method. Note that cubic convolution interpolation works only with one- and two-dimensional arrays.

Cubic convolution is an interpolation method that closely approximates the theoretically optimum sinc interpolation function using cubic polynomials. According to sampling theory, details of which are beyond the scope of this document, if the original signal, f , is a band-limited signal, with no frequency component larger than  ω0, and f is sampled with spacing less than or equal to 1/2ω0, then f can be reconstructed by convolving with a sinc function: sinc (x) = sin (πx) / (πx).

In the one-dimensional case, four neighboring points are used, while in the two-dimensional case 16 points are used. Note that cubic convolution interpolation is significantly slower than bilinear interpolation.

For further details see Rifman, S.S. and McKinnon, D.M., "Evaluation of Digital Correction Techniques for ERTS Images—Final Report", Report 20634-6003-TU-00, TRW Systems, Redondo Beach, CA, July 1974.

MISSING

Specifies the output value for points whose x', y' is outside the bounds of Array. If MISSING is not specified, the resulting output value is extrapolated from the nearest pixel of Array.

Example

Some simple linear (degree one) transformations are:

P0,0	P1,0	P0,1	P1,1	Q0,0	Q1,0	Q0,1	Q1,1	Effect
0	0	1	0	0	1	0	0	Identity
0	0	0.5	0	0	1	0	0	Stretch X by a factor of 2
0	0	1	0	0	2.0	0	0	Shrink Y by a factor of 2
z	0	1	0	0	1	0	0	Shift left by z pixels
0	1	0	0	0	0	1	0	Transpose
Table 1.13 Simple Transformations for Use with POLY_2D

POLY_2D is often used in conjunction with the POLYWARP procedure to warp images. Create and display a simple image by entering:

A = BYTSCL(SIN(DIST(250)), TOP=!D.TABLE_SIZE) & TV, A

Set up the arrays of original points to be warped by entering:

XO = [61, 62, 143, 133]

YO = [89, 34, 38, 105]

Set up the arrays of points to be fit by entering:

XI = [24, 35, 102, 92]

YI = [81, 24, 25, 92]

Use POLYWARP to generate the P and Q inputs to POLY_2D by entering:

POLYWARP, XI, YI, XO, YO, 1, P, Q

To perform an image warping based on P and Q, enter:

B = POLY_2D(A, P, Q)

Display the new image by entering:

TV, B, 250, 250

Images can also be warped over irregularly gridded control points using the WARP_TRI procedure.

See Also

POLYWARP


POLY_AREA

The POLY_AREA function returns the area of a polygon given the coordinates of its vertices. This value is always positive.

It is assumed that the polygon has n vertices with n sides and the edges connect the vertices in the order:

[(x1,y1), (x2,y2), ... , (xn,yn), (x1,y1)]

such that the last vertex is connected to the first vertex.

This routine is written in the IDL language. Its source code can be found in the file poly_area.pro in the lib subdirectory of the IDL distribution.

Calling Sequence

Result = POLY_AREA(X, Y)

Arguments

X

An n-element vector of X coordinate locations for the vertices.

Y

An n-element vector of Y coordinate locations for the vertices.

Example

See Also

DEFROI, POLYFILLV


POLY_FIT

The POLY_FIT function performs a least-square polynomial fit with optional error estimates and returns a vector of coefficients with a length of NDegree+1.

The POLY_FIT routine uses matrix inversion. A newer version of this routine, SVDFIT, uses Singular Value Decomposition. The SVD technique is more flexible, but slower. Another version of this routine, POLYFITW, performs a weighted least square fit.

This routine is written in the IDL language. Its source code can be found in the file poly_fit.pro in the lib subdirectory of the IDL distribution.

Calling Sequence

Result = POLY_FIT(X, Y, NDegree [,Yfit, Yband, Sigma, A] )

Arguments

X

An n-element vector of independent variables.

Y

A vector of independent variables, the same length as X.

NDegree

The degree of the polynomial to fit.

Yfit

A named variable that will contain the vector of calculated Y values. These values have an error of plus or minus Yband.

Yband

A named variable that will contain the error estimate for each point.

Sigma

A named variable that will contain the standard deviation in Y units.

A

A named variable that will contain the correlation matrix of the coefficients.

Example

In this example, we use X and Y data corresponding to the known polynomial f (x) = 0.25 - x + x^2. Using POLY_FIT to compute a second degree polynomial fit returns the exact coefficients (to within machine accuracy).

X = [0.0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0]
Define an 11-element vector of independent variable data.

Y = [0.25, 0.16, 0.09, 0.04, 0.01, 0.00, 0.01, 0.04, 0.09, 0.16, 0.25]
Define an 11-element vector of dependent variable data.

result = POLY_FIT(X, Y, 2)	Compute the second degree polynomial fit to the data.

PRINT, result	Print the coefficients.

IDL prints:

 0.24999996

-0.99999974

 0.99999975

See Also

CURVEFIT, GAUSSFIT, POLYFITW, REGRESS, SFIT, SVDFIT


POLYFILL

The POLYFILL procedure fills the interior of a region of the display enclosed by an arbitrary two or three-dimensional polygon. The available filling methods are: solid fill, hardware-dependent fill pattern, parallel lines, or a pattern contained in an array. Not all methods are available on every hardware output device.

The polygon is defined by a list of connected vertices stored in X, Y, and Z. The coordinates can be given in data, device, or normalized form using the DATA, DEVICE, or NORMAL keywords.

Line-fill method: Filling using parallel lines is device-independent and works on all devices that can draw lines. Crosshatching can be simulated by performing multiple fills with different orientations. The spacing, linestyle, orientation, and thickness of the filling lines can be specified using the corresponding keyword parameters. The LINE_FILL keyword selects this filling style, but is not required if either the ORIENTATION or SPACING parameters are present.

Solid fill method: Most, but not all, devices can fill with a solid color. Solid fill is performed using the line-fill method for devices that don't have this hardware capability. Method specifying keyword parameters are not required for solid filling.

Patterned fill: The method of patterned filling and the usage of various fill patterns is hardware dependent. The fill pattern array can be explicitly specified with the PATTERN keyword parameter for some output devices. If this parameter is omitted, the polygon is filled with the hardware-dependent pattern index specified by the FILL_PATTERN keyword.

Calling Sequence

POLYFILL, X [, Y [, Z]]

Arguments

X

A vector argument providing the X coordinates of the points to be connected. The vector must contain at least three elements. If only one argument is specified, X  must be an array of either two or three vectors (i.e., (2,*) or (3,*)). In this special case, the vector X(0,*) specifies the X values, X(1,*) specifies Y, and X(2,*) contain the Z values.

Y

A vector argument providing the Y coordinates of the points to be connected. Y must contain at least three elements.

Z

An optional vector argument providing the Z coordinates of the points to be connected. If Z is not provided, X and Y are used to draw lines in two dimensions. Z must contain at least three elements. Z has no effect if the keyword T3D is not specified and the system variable !P.T3D= 0.

Keywords

FILL_PATTERN

The hardware dependent fill pattern index for the POLYFILL procedure. If omitted or set to 0, a solid fill results.

IMAGE_COORD

(Z-Buffer output only) A 2 by N array containing the fill pattern array subscripts of each of the N polygon vertices.Use this keyword in conjunction with the PATTERN keyword to warp images over 2D and 3D polygons.

IMAGE_INTERP

(Z-Buffer output only) Specifies the method of sampling the PATTERN array when the IMAGE_COORDINATES keyword is present. The default method is to use nearest-neighbor sampling. Bilinear interpolation sampling is performed if IMAGE_INTERPOLATE is set.

LINE_FILL

Set this keyword to indicate that polygons are to be filled with parallel lines, rather than using solid or patterned filling methods.When using the line-drawing method of filling, the thickness, linestyle, orientation, and spacing of the lines may be specified with keywords.

PATTERN

A rectangular array of pixels giving the fill pattern. If this keyword parameter is omitted, POLYFILL fills the area with a solid color. The pattern array may be of any size; if it is smaller than the filled area the pattern array is cyclically repeated.

Note:  When the display device selected is PostScript (PS), POLYFILL can only fill with solid colors. The PATTERN keyword works with all other display devices.

For example, to fill the current plot window with a grid of dots, enter the following commands:

PAT = BYTARR(10,10)	Define pattern array as 10 by 10.

PAT(5,5) = 255	Set center pixel to bright.

POLYFILL, !X.WINDOW([0,1,1,0]), $

          !Y.WINDOW([0,0,1,1]), /NORM, PAT = PAT

Fill the rectangle defined by the four corners of the window with the pattern.

SPACING

The spacing, in centimeters, between the parallel lines used to fill polygons.

TRANSPARENT

(Z-Buffer output only) specifies the minimum pixel value to draw in conjunction with the PATTERN and IMAGE_COORDINATES keywords. Pixels less than this value are not drawn and the Z-buffer is not updated.

Graphics Keywords Accepted

See Chapter 2, "Graphics Keywords and System Variables", for the description of graphics and plotting keywords not listed above. CLIP COLOR DATA DEVICE LINESTYLE NOCLIP NORMAL ORIENTATION T3D THICK  Z.

Z-Buffer-Specific Keywords

Certain keyword parameters are only active when the Z-buffer is the currently selected graphics device: IMAGE_COORD, IMAGE_INTERP, TRANSPARENT and COLOR. These parameters allow images to be warped over 2D or 3D polygons, and the output of shaded polygons. For examples, see "The Z-Buffer Device" on page 3-62.

For shaded polygons, the COLOR keyword can specify an array that contains the color index at each vertex. Color indices are linearly interpolated between vertices. If COLOR contains a scalar, the entire polygon is drawn with the given color index, just as with the other graphics output devices.

Images can be warped over polygons by passing in the image with the PATTERN parameter, and a (2, N) array containing the image space coordinates that correspond to each of the N vertices with the IMAGE_COORDINATES keyword.

The IMAGE_INTERPOLATE keyword indicates that bilinear interpolation is to be used, rather than the default nearest-neighbor sampling. Pixels less than the value of TRANSPARENT are not drawn, simulating transparency.

Example

Fill a rectangular polygon that has the vertices (30,30), (100, 30), (100, 100), and (30, 100) in device coordinates. Create the vectors of X and Y values by entering:

X = [30, 100, 100, 30] & Y = [30, 30, 100, 100]

Fill the polygon with color index 175 by entering:

POLYFILL, X, Y, COLOR = 175, /DEVICE

See Also

POLYFILLV


POLYFILLV

The POLYFILLV function returns a vector containing the one-dimensional subscripts of the array elements contained inside a polygon defined by vectors X and Y.

If no points are contained within the polygon, a -1 is returned and an informational message is printed. The X and Y parameters are vectors that contain the subscripts of the vertices that define the polygon in the coordinate system of the two-dimensional Sx by Sy array. The Sx and Sy parameters define the number of columns and rows in the array enclosing the polygon. At least three points must be specified, and all points should lie within the limits: 0 ≤ Xi < Sx and 0 ≤ Yi < Sy ∀i.

As with the POLYFILL procedure, the polygon is defined by connecting each point with its successor and the last point with the first. This function is useful for defining, analyzing, and displaying regions of interest within a two-dimensional array.

The scan line coordinate system defined by Rogers in Procedural Elements for Computer Graphics , McGraw-Hill, 1985, page 71, is used. In this system, the scan lines are considered to pass through the center of each row of pixels. Pixels are activated if the center of the pixel is to the right of the intersection of the scan line and the polygon edge within the interval.

Calling Sequence

Result = POLYFILLV(X, Y, Sx, Sy [, Run_Length])

Arguments

X

A vector containing the X subscripts of the vertices that define the polygon.

Y

A vector containing the Y subscripts of the vertices that define the polygon.

Sx

The number of columns in the array surrounding the polygon.

Sy

The number of rows in the array surrounding the polygon.

Run_Length

Set this optional parameter to a nonzero value to make POLYFILLV return a vector of run lengths, rather than subscripts. For large polygons, a considerable savings in space results. When run-length encoded, each element with an even subscript result contains the length of the run, and the following element contains the starting index of the run.

Example

To determine the mean and standard deviation of the elements within a triangular region defined by the vertices at pixel coordinates (100, 100), (200, 300), and (300, 100), inside a 512 by 512 array called DATA, enter the commands:

P = DATA(POLYFILLV([100,200,300], [100,300,100], 512, 512))
Get the subscripts of the elements inside the triangle.

STD = STDEV(P,MEAN)	Use the STDEV function to obtain the mean and standard deviation of the selected elements.

See Also

POLYFILL


POLYFITW

The POLYFITW function performs a weighted least-square polynomial fit with optional error estimates and returns a vector of coefficients with a length of NDegree+1.

The POLYFITW routine uses matrix inversion. A newer version of this routine, SVDFIT, uses Singular Value Decomposition. The SVD technique is more flexible, but slower. Another version of this routine, POLY_FIT, performs a least square fit without weighting.

This routine is written in the IDL language. Its source code can be found in the file polyfitw.pro in the lib subdirectory of the IDL distribution.

Calling Sequence

Result = POLYFITW(X, Y, W, NDegree [,Yfit, Yband, Sigma, A] )

Arguments

X

An n-element vector of independent variables.

Y

A vector of independent variables, the same length as X.

W

A vector of weights, the same length as X and Y.

NDegree

The degree of the polynomial to fit.

Yfit

A named variable that will contain the vector of calculated Y values. These values have an error of plus or minus Yband.

Yband

A named variable that will contain the error estimate for each point.

Sigma

A named variable that will contain the standard deviation in Y units.

A

A named variable that will contain the correlation matrix of the coefficients.

See Also

CURVEFIT, GAUSSFIT, POLY_FIT, REGRESS, SFIT, SVDFIT


POLYSHADE

The POLYSHADE function returns a shaded-surface representation of one or more solids described by a set of polygons. This function accepts, as arguments, an array of three-dimensional vertices and a list of the indices of the vertices that describe each polygon. Output is a two-dimensional byte array containing the shaded image unless the current graphics output device is the Z-buffer. If the current output device is the Z-buffer, the results are merged with the Z-buffer's contents and the function result contains a dummy value.

Shading values are determined from one of three sources: a light source model, a user-specified array containing vertex shade values, or a user-specified array containing polygon shade values.

The shaded surface is constructed using the scan line algorithm. The default shading model is a combination of diffuse reflection and depth cueing. With this shading model, polygons are shaded using either constant shading, in which each polygon is given a constant intensity, or with Gouraud shading where the intensity is computed at each vertex and then interpolated over the polygon. Use the SET_SHADING procedure to control the direction of the light source and other shading parameters.

User-specified shading arrays allow "4-dimensional" displays that consist of a surface defined by a set of polygons, shaded with values from another variable.

Calling Sequence

Result = POLYSHADE(Vertices, Polygons)

or

Result = POLYSHADE( X, Y, Z, Polygons)

Arguments

Vertices

A (3,  n) array containing the X, Y, and Z coordinates of each vertex. Coordinates can be in either data or normalized coordinates, depending on which keywords are present.

X, Y, Z

The X, Y, and Z coordinates of each vertex can, alternatively, be specified as three array expressions of the same dimensions.

Polygons

An integer or longword array containing the indices of the vertices for each polygon. The vertices of each polygon should be listed in counterclockwise order when observed from outside the surface. The vertex description of each polygon is a vector of the form: [n, i0, i1, ..., in-1].

 and the array Polygons is the concatenation of the lists of each polygon. For example, to render a pyramid consisting of four triangles, Polygons would contain 16 elements, made by concatenating four, four-element vectors of the form [3, V0, V1, V2]. V0, V1, and V2 are the indices of the vertices describing each triangle.

Keywords

DATA

Set this keyword to indicate that the vertex coordinates are in data units, the default coordinate system.

NORMAL

Set this keyword to indicate that coordinates are in normalized units, within the three dimensional (0,1) cube.

POLY_SHADES

An array expression, with the same number of elements as there are polygons defined in the Polygons array, containing the color index used to render each polygon. No interpolation is performed all pixels within a given polygon have the same shade value. For most displays, this parameter should be scaled into the range of bytes.

SHADES

An array expression, with the same number of elements as Vertices, containing the color index at each vertex. The shading of each pixel is interpolated from the surrounding SHADE values. For most displays, this parameter should be scaled into the range of bytes.

T3D

Set this keyword to use the three-dimensional to two-dimensional transformation contained in the homogeneous 4 by 4 matrix !P.T. Note that if T3D is set, !P.T must contain a valid transformation matrix. The SURFACE, SCALE3, and T3D procedures (and others) can all be used to set up transformations.

TOP

The maximum shading value when light source shading is in effect. The default value is one less than the number of colors available in the currently selected graphics device.

XSIZE

The number of columns in the output image array. If this parameter is omitted, the number of columns is equal to the X size of the currently selected display device.

Warning: The size parameters should be explicitly specified when the current graphics device is PostScript or any other high-resolution device. Making the output image the default full device size is likely to cause an insufficient memory error.

YSIZE

The number of rows in the output image array. If this parameter is omitted, the number of rows is equal to the Y resolution of the currently selected display device.

Example

POLYSHADE is often used in conjunction with SHADE_VOLUME for volume visualization. The following example creates a spherical volume dataset and renders an isosurface from that dataset:

SPHERE = FLTARR(20, 20, 20)	Create an empty, 3D array.

FOR X=0,19 DO FOR Y=0,19 DO FOR Z=0,19 DO $

       SPHERE(X, Y, Z) = SQRT((X-10)^2 + (Y-10)^2 + (Z-10)^2)

Create the spherical dataset.

SHADE_VOLUME, SPHERE, 8, V, P	Find the vertices and polygons for a density level of 8.

SCALE3, XRANGE=[0,20], YRANGE=[0,20], ZRANGE=[0,20]
Set up an appropriate 3D transformation so we can see the sphere. This step is very important.

image = POLYSHADE(V, P, /T3D)	Render the image. Note that the T3D keyword has been set so that the previously-established 3D transformation is used.

TV, image	Display the image.

See Also

PROJECT_VOL, RECON3, SET_SHADING, SHADE_SURF, SHADE_VOLUME, VOXEL_PROJ


POLYWARP

The POLYWARP procedure performs polynomial spatial warping.

Using least squares estimation, POLYWARP determines the coefficients Kx(i,j) and Ky(i,j ) of the polynomial functions:

Kx and Ky can be used as inputs P and Q to the built-in function POLY_2D. This coordinate transformation may be then used to map from  Xo, Yo coordinates into Xi, Yi coordinates.

This routine is written in the IDL language. Its source code can be found in the file polywarp.pro in the lib subdirectory of the IDL distribution.

Calling Sequence

POLYWARP, Xi, Yi, Xo, Yo, Degree, Kx, Ky

Arguments

Xi, Yi

Vectors of X and Y coordinates to be fit as a function of Xo and Yo.

Xo, Yo

Vectors of X and Y independent coordinates. These vectors must have the same number of elements as  Xi and Yi.

Degree

The degree of the fit. The number of coordinate pairs must be greater than or equal to (Degree+1)^2.

Kx

A named variable that will contain the array of coefficients for Xi as a function of (Xo, Yo). This parameter is returned as a (Degree+1) by (Degree+1) element array.

Ky

A named variable that will contain the array of coefficients for Yi. This parameter is returned as a (Degree+1) by (Degree+1) element array.

Example

The following example shows how to display an image and warp it using the POLYWARP and POLY_2D routines.

Create and display the original image by entering:

A = BYTSCL(SIN(DIST(250)))

TVSCL, A

Now set up the Xi's and Yi's. Enter:

XI = [24, 35, 102, 92]

YI = [81, 24, 25, 92]

Enter the Xo's and Yo's:

XO = [61, 62, 143, 133]

YO = [89, 34, 38, 105]

Run POLYWARP to obtain a Kx and Ky:

POLYWARP, XI, YI, XO, YO, 1, KX, KY

Create a warped image based on Kx and Ky with POLY_2D:

B = POLY_2D(A, KX, KY)

Display the new image:

TV, B

See Also

POLY_2D, WARP_TRI


POPD

The POPD procedure changes the current working directory to the directory saved on the top of the directory stack maintained by the PUSHD and POPD procedures. This top entry is then removed from the stack.

Attempting to pop a directory when the stack is empty causes a warning message to be printed. The current directory is not changed in this case. The common block DIR_STACK is used to store the directory stack.

This routine is written in the IDL language. Its source code can be found in the file popd.pro in the lib subdirectory of the IDL distribution.

Calling Sequence

POPD

See Also

CD, PRINTD, PUSHD


POWELL

The POWELL procedure minimizes a user-written function Func of n variables using the Powell method. POWELL does not require a user-supplied analytic gradient.

POWELL is based on the routine powell described in section 10.5 of Numerical Recipes in C: The Art of Scientific Computing (Second Edition), published by Cambridge University Press, and is used by permission.

Calling Sequence

POWELL, P, Xi, Ftol, Fmin, Func

Arguments

P

On input, P is an n-element vector specifying the starting point. On output, it is replaced with the location of the minimum.

Xi

On input, Xi is an initial n by  n element array whose columns contain the initial set of directions (usually the n unit vectors). On output, it is replaced with the then-current directions.

Ftol

An input value specifying the fractional tolerance in the function value. Failure to decrease by more than Ftol in one iteration signals completeness. For single-precision computations, a value of 1.0 x 10^-4 is recommended; for double-precision computations, a value of 1.0 x 10^-8 is recommended.

Fmin

On output, Fmin contains the value at the minimum-point P of the user-supplied function specified by Func.

Func

A scalar string specifying the name of a user-supplied IDL function to be minimized. This function must accept a vector argument X and return a scalar result.

For example, suppose we wish to minimize the function

f (x,y) = (x + 2y) EXP(­x^2 ­  y^2)

To evaluate this expression, we define an IDL function named POWFUNC:

FUNCTION powfunc, X

  RETURN, (X(0) + 2.0*X(1)) * EXP(-X(0)^2 -X(1)^2)

END

Keywords

DOUBLE

Set this keyword to force the computation to be done in double-precision arithmetic.

ITER

Use this keyword to specify an output variable that will be set to the number of iterations performed.

ITMAX

Use this keyword to specify the maximum allowed number of iterations. The default is 200.

Example

We can use POWELL to minimize the function POWFUNC given above.

ftol = 1.0e-4 	Define the fractional tolerance.

P = [.5d, -.25d]	Define the starting point.

xi = TRANSPOSE([[1.0, 0.0],[0.0, 1.0]])
Define the starting directional vectors in column format.

POWELL, P, xi, ftol, fmin, 'powfunc'
Minimize the function.

PRINT, P	Print the solution point.

IDL prints:

     -0.31622777     -0.63245552

The exact solution point is [-0.31622777, -0.63245553].

PRINT, fmin	Print the value at the solution point.

IDL prints:

     -0.95900918

The exact minimum function value is -0.95900918.

See Also

DFPMIN


PRIMES

The PRIMES function computes the first K prime numbers. The result is a K-element long integer vector.

This routine is written in the IDL language. Its source code can be found in the file primes.pro in the lib subdirectory of the IDL distribution.

Calling Sequence

Result = PRIMES(K)

Arguments

K

An integer or long integer scalar that specifies the number of primes to be computed.

Example

Compute the first 25 prime numbers.

PRINT, PRIMES(25)

IDL prints:

 2     3     5     7    11    13

17    19    23    29    31    37

41    43    47    53    59    61

67    71    73    79    83    89

97


PRINT

The two PRINT procedures perform formatted output. PRINT performs output to the standard output stream (IDL file unit -1), while PRINTF requires a file unit to be explicitly specified.

Calling Sequence

PRINT, Expr1, ..., Exprn

or

PRINTF, Unit, Expr1, ..., Exprn

Arguments

Unit

For PRINTF, Unit specifies the file unit to which the output is sent.

Expri

The expressions to be output.

Keywords

FORMAT

If FORMAT is not specified, IDL uses its default rules for formatting the output. FORMAT allows the format of the output to be specified in precise detail, using a FORTRAN-style specification. See "Explicitly Formatted Input/Output" on page 17-15 of the IDL User's Guide.

VMS Keywords

REWRITE

When writing data to a file with indexed organization, set the REWRITE keyword to specify that the data should update the contents of the most recently input record instead of creating a new record.

Format Compatibility

If the FORMAT keyword is not present and PRINT is called with more than one argument, and the first argument is a scalar string starting with the characters "$(", this initial argument is taken to be the format specification, just as if it had been specified via the FORMAT keyword. This feature is maintained for compatibility with version 1 of VMS IDL.

Example

To print the string "IDL is fun." enter the command:

PRINT, 'IDL is fun.'

To print the same message to the open file associated with file unit number 2, use the command:

PRINTF, 2, 'IDL is fun.'

See Also

ANNOTATE, MESSAGE, WRITEU, XYOUTS


PRINTD

The PRINTD procedure prints the contents of the directory stack maintained by the PUSHD and POPD procedures. The contents of the directory stack are listed on the default output device. The common block DIR_STACK is used to store the directory stack.

This routine is written in the IDL language. Its source code can be found in the file printd.pro in the lib subdirectory of the IDL distribution.

Calling Sequence

PRINTD

See Also

CD, POPD, PUSHD


PROFILE

The PROFILE function extracts a profile from an image and returns a floating-point vector containing the values of the image along the profile line marked by the user.

This routine is written in the IDL language. Its source code can be found in the file profile.pro in the lib subdirectory of the IDL distribution.

Using PROFILE

To mark a profile line after calling PROFILE, click in the image with the left mouse button to mark the beginning and ending points. The pixel coordinates of the selected points are displayed in the IDL command log.

Calling Sequence

Result = PROFILE(Image [, XX, YY])

Arguments

Image

The data array representing the image. This array can be of any type except complex.

XX

A named variable that will contain the X coordinates of the points along the selected profile.

YY

A named variable that will contain the Y coordinates of the points along the selected profile.

Keywords

NONMARK

Set this keyword to inhibit marking the image with the profile line.

XSTART

The starting X location of the lower-left corner of Image. If this keyword is not specified, 0 is assumed.

YSTART

The starting Y location of the lower-left corner of Image. If this keyword is not specified, 0 is assumed.

Example

Display an image, select a profile and plot that profile in a new window.

Create and display an image by entering:

A = BYTSCL(DIST(256))

TV, A

Extract a profile from the image. Enter the following command and mark two points on the image with the mouse:

R = PROFILE(A)

Create a new plotting window and plot the profile by entering:

WINDOW, /FREE

PLOT, R

The PROFILES procedure is an interactive version of this routine.

See Also

PROFILES


PROFILES

The PROFILES procedure interactively draws row or column profiles of an image in a separate window. A new window is created and the mouse location in the original window is used to plot profiles in the new window.

This routine is written in the IDL language. Its source code can be found in the file profiles.pro in the lib subdirectory of the IDL distribution.

Using PROFILES

Move the mouse within the original image interactively creates profile plots in the newly-created profile window. Pressing the left mouse button toggles between row and column profiles. The right mouse button exits

Calling Sequence

PROFILES, Image

Arguments

Image

The variable that represents the image displayed in current window. This data need not be scaled into bytes. The profile graphs are made from this array, even if it is not currently displayed.

Keywords

ORDER

Set this keyword to 1 for images written top down or 0 for bottom up. Default is the current value of !ORDER.

SX

Starting X position of the image in the window. If this keyword is omitted, 0 is assumed.

SY

Starting Y position of the image in the window. If this keyword is omitted, 0 is assumed.

WSIZE

The size of the PROFILES window as a fraction or multiple of 640 by 512.

Example

Create and display an image and use the PROFILES routine on it.

Create and display an image by entering:

A = BYTSCL(DIST(256))

TV, A

Run the PROFILES routine by entering:

PROFILES, A, WSIZE = .5

A 320 x 256 pixel PROFILES window should appear. Move the cursor over the original image to see the profile at the cursor position. Press the left mouse button to toggle between row and column profiles. Press the right mouse button (with the cursor over the original image) to exit the routine.

See Also

PROFILE


PROJECT_VOL

The PROJECT_VOL function returns a two-dimensional image that is the projection of a 3D volume of data onto a plane (similar to an X-ray). The returned image is a translucent rendering of the volume (the highest data values within the volume show up as the brightest regions in the returned image). Depth queuing and opacity may be used to affect the image. The volume is projected using a 4x4 matrix, so any type of projection may be used including perspective. Typically the system viewing matrix (!P.T) is used as the 4x4 matrix.

Note that the VOXEL_PROJ procedure performs many of the same functions as this routine, and is faster.

This routine is written in the IDL language. Its source code can be found in the file project_vol.pro in the lib subdirectory of the IDL distribution.

Calling Sequence

Return = PROJECT_VOL(Vol, X_Sample, Y_Sample, Z_Sample)

Arguments

Vol

A 3D array of any type except string or structure containing the three dimensional volume of data to project.

X_Sample

A long integer specifying the number of rays to project along the X dimension of the image. The returned image will have the dimensions X_sample by Y_sample.

Y_Sample

A long integer specifying the number of rays to project along the Y dimension of the image. To preserve the correct aspect ratio of the data, Y_sample should equal X_sample.

Z_Sample

A long integer specifying the number of samples to take along each ray. Higher values for X_sample, Y_sample, and Z_sample increase the image resolution as well as execution time.

Keywords

DEPTH_Q

Set this keyword to indicate that the image should be created using depth queuing. The depth queuing should be a single floating-point value between 0.0 and 1.0. This value specifies the brightness of the farthest regions of the volume relative to the closest regions of the volume. A value of 0.0 will cause the back side of the volume to be completely blacked out, while a value of 1.0 indicates that the back side will show up just as bright as the front side. The default is 1.0 (indicating no depth queuing).

OPAQUE

A 3D array of any type except string or structure, with the same size and dimensions as Vol. This array specifies the opacity of each cell in the volume. OPAQUE values of 0 allow all light to pass through. OPAQUE values are cumulative. For example, if a ray emanates from a data value of 50, and then passes through 10 opaque cells (each with a data value of 0 and an opacity value of 5) then that ray would be completely blocked out (the cell with the data value of 50 would be invisible on the returned image). The default is no opacity.

TRANS

A 4x4 floating-point array to use as the transformation matrix when projecting the volume. The default is to use the system viewing matrix (!P.T).

Example

Use the T3D routine to set up a viewing projection and render a volume of data using PROJECT_VOL. First, create some data:

vol = RANDOMU(S, 40, 40, 40)

FOR I=0, 10 DO vol = SMOOTH(vol, 3)

vol = BYTSCL(vol(3:37, 3:37, 3:37))

opaque = RANDOMU(S, 40, 40, 40)

FOR I=0, 10 DO opaque = SMOOTH(opaque, 3)

opaque = BYTSCL(opaque(3:37, 3:37, 3:37), TOP=25B)

Set up the view:

T3D, /RESET

T3D, TRANSLATE=[-0.5, -0.5, -0.5]

T3D, SCALE=[0.7, 0.7, 0.7]

T3D, ROTATE=[30, -30, 60]

T3D, TRANSLATE=[0.5, 0.5, 0.5]

Generate and display the image:

img = PROJECT_VOL(vol, 64, 64, 64, DEPTH_Q=0.7, $

  OPAQUE=opaque, TRANS=(!P.T))

TVSCL, img

See Also

POLYSHADE, VOXEL_PROJ


PS_SHOW_FONTS

The PS_SHOW_FONTS procedure displays all the PostScript fonts that IDL knows about, with both the StandardAdobe and ISOLatin1 encodings. Each display takes a separate page, and each character in each font is shown with its character index.

A PostScript file is produced, one page per font/mapping combination. The output file contains almost 70 pages of output. A PostScript previewer is recommended rather than sending it to a printer.

This routine is written in the IDL language. Its source code can be found in the file ps_show_fonts.pro in the lib subdirectory of the IDL distribution.

Calling Sequence

PS_SHOW_FONTS

Keywords

NOLATIN

Set this keyword to prevent output of ISOLatin1 encodings.

See Also

PSAFM


PSAFM

The PSAFM procedure takes an Abobe Font Metrics file as input and generates a new AFM file in the format that IDL likes. This new file differs from the original in the following ways:

•	Information not used by IDL is removed.

•	AFM files with the AdobeStandardEncoding are supplemented with an ISOLatin1Encoding.

This routine is written in the IDL language. Its source code can be found in the file psafm.pro in the lib subdirectory of the IDL distribution.

Calling Sequence

PSAFM,  Input_Filename, Output_Filename

Arguments

Input_Filename

A string that contains the name of existing AFM file from Adobe.

Output_Filename

A string that specifies the name of new IDL-format AFM file to be created.

See Also

PS_SHOW_FONTS


PSEUDO

The PSEUDO procedure creates a pseudo-color table based on the LHB (Lightness, Hue, and Brightness) system and loads it.

The pseudo-color mapping used is generated by first translating from the LHB coordinate system to the LAB coordinate system, finding N colors spread out along a helix that spans this LAB space (supposedly a near maximal entropy mapping for the eye, given a particular N) and remapping back into the RGB (Red, Green, and Blue) colorspace. The result is loaded as the current colortable.

This routine is written in the IDL language. Its source code can be found in the file pseudo.pro in the lib subdirectory of the IDL distribution.

Calling Sequence

PSEUDO, Litlo, Lithi, Satlo, Sathi, Hue, Loops [, Colr]

Arguments

Litlo

Starting lightness, from 0 to 100%.

Lithi

Ending lightness, from 0 to 100%.

Satlo

Starting saturation, from 0 to 100%.

Sathi

Ending saturation, from 0 to 100%.

Hue

Starting hue, in degrees, from 0 to 360.

Loops

The number of loops of hue to make in the color helix. This value can range from 0 to around 3 to 5 and need not be an integer.

Colr

An optional (256,3) integer array in which the new R, G, and B values are returned. Red = Colr(*,0), green = Colr(*,1), blue = Colr(*,2).

See Also

COLOR_CONVERT, COLOR_QUAN


PUSHD

The PUSHD procedure pushes a directory onto the top of the directory stack maintained by the PUSHD and POPD procedures. The name of the current directory is pushed onto the directory stack. This directory becomes the next directory used by POPD. IDL changes directories to the one specified by the Dir argument. The common block DIR_STACK is used to store the directory stack.

This routine is written in the IDL language. Its source code can be found in the file pushd.pro in the lib subdirectory of the IDL distribution.

Calling Sequence

PUSHD, Dir

Arguments

Dir

A string containing the name of the directory to change to. The current directory is pushed onto the top of the directory stack.

See Also

CD, POPD, PRINTD


QROMB

The QROMB function evaluates the integral of a function over the closed interval [A, B] using Romberg integration. The result will have the same structure as the smaller of A and B, and the resulting type will be single- or double-precision floating, depending on the input types.

QROMB is based on the routine qromb described in section 4.3 of Numerical Recipes in C: The Art of Scientific Computing (Second Edition), published by Cambridge University Press, and is used by permission.

Calling Sequence

Result = QROMB(Func, A, B)

Arguments

Func

A scalar string specifying the name of a user-supplied IDL function to be integrated. This function must accept a single scalar argument X and return a scalar result. It must be defined over the closed interval [A, B].

For example, if we wish to integrate the cubic polynomial

y = x^3 + (x ­ 1)^2 + 3

we define a function CUBIC to express this relationship in the IDL language:

FUNCTION cubic, X

  RETURN, X^3 + (X - 1.0)^2 + 3.0

END

A

The lower limit of the integration. A can be either a scalar or an array.

B

The upper limit of the integration. B can be either a scalar or an array.

Note: If arrays are specified for A and B, then QROMB integrates the user-supplied function over the interval [Ai, Bi] for each i. If either A or B is a scalar and the other an array, the scalar is paired with each array element in turn.

Keywords

DOUBLE

Set this keyword to force the computation to be done in double-precision arithmetic.

EPS

The desired fractional accuracy. For single-precision calculations, the default value is 1.0 x 10^-6. For double-precision calculations, the default value is 1.0 x 10^-12.

JMAX

2^(JMAX-1) is the maximum allowed number of steps. If this keyword is not specified, a default of 20 is used.

K

Integration is performed by Romberg's method of order 2K. If not specified, the default is K=5. (K=2 is Simpson's rule).

Example

To integrate the CUBIC function (listed above) over the interval [0, 3] and print the result:

PRINT, QROMB('cubic', 0.0, 3.0)

IDL prints:

 32.2500

This is the exact solution.

See Also

INT_2D, INT_3D, INT_TABULATED, QROMO, QSIMP


QROMO

The QROMO function evaluates the integral of a function over the open interval (A, B) using a modified Romberg's method.

QROMO is based on the routine qromo described in section 4.4 of Numerical Recipes in C: The Art of Scientific Computing (Second Edition), published by Cambridge University Press, and is used by permission.

Calling Sequence

Result = QROMO(Func, A [, B])

Arguments

Func

A scalar string specifying the name of a user-supplied IDL function to be integrated. This function must accept a single scalar argument X and return a scalar result. It must be defined over the open interval (A, B).

For example, if we wish to integrate the fourth-order polynomial

y = 1 / x^4

we define a function HYPER to express this relationship in the IDL language:

FUNCTION hyper, X

  RETURN, 1.0 / X^4

END

A

The lower limit of the integration. A can be either a scalar or an array.

 B

The upper limit of the integration. B can be either a scalar or an array. If the MIDEXP keyword is specified, B is assumed to be infinite, and should not be supplied by the user.

Note: If arrays are specified for A and B, then QROMO integrates the user-supplied function over the interval [Ai, Bi] for each i. If either A or B is a scalar and the other an array, the scalar is paired with each array element in turn.

Keywords

DOUBLE

Set this keyword to force the computation to be done in double-precision arithmetic.

EPS

The fractional accuracy desired, as determined by the extrapolation error estimate. For single-precision calculations, the default value is 1.0 x 10^-6. For double-precision calculations, the default value is 1.0 x 10^-12.

JMAX

Set to specify the maximum allowed number of mid quadrature points to be 3^(JMAX-1). The default value is 14.

K

Integration is performed by Romberg's method of order 2K. If not specified, the default is K=5.

MIDEXP

Use the midexp() function (see Numerical Recipes, section 4.4) as the integrating function. If the MIDEXP keyword is specified, argument B is assumed to be infinite, and should not be supplied by the user.

MIDINF

Use the midinf() function (see Numerical Recipes, section 4.4) as the integrating function.

MIDPNT

Use the midpnt() function (see Numerical Recipes, section 4.4) as the integrating function. This is the default if no other integrating function keyword is specified.

MIDSQL

Use the midsql() function (see Numerical Recipes, section 4.4) as the integrating function.

MIDSQU

Use the midsqu() function (see Numerical Recipes, section 4.4) as the integrating function.

Example

To integrate the HYPER function (listed above) over the open interval (2, •) and print the result:

PRINT, QROMO('hyper', 2.0, /MIDEXP)

Note that when using the /MIDEXP keyword, the upper integration limit is assumed to be infinity and is not supplied.

IDL prints:

 0.0412050

See Also

INT_2D, INT_3D, INT_TABULATED, QROMB, QSIMP


QSIMP

The QSIMP function performs numerical integration of a function over the closed interval [A, B] using Simpson's rule. The result will have the same structure as the smaller of A and B, and the resulting type will be single- or double-precision floating, depending on the input types.

QSIMP is based on the routine qsimp described in section 4.2 of Numerical Recipes in C: The Art of Scientific Computing (Second Edition), published by Cambridge University Press, and is used by permission.

Calling Sequence

Result = QSIMP(Func, A, B)

Arguments

Func

A scalar string specifying the name of a user-supplied IDL function to be integrated. This function must accept a single scalar argument X and return a scalar result. It must be defined over the closed interval [A, B].

For example, if we wish to integrate the fourth-order polynomial

y = (x^4 ­ 2x^2) sin(x)

we define a function SIMPSON to express this relationship in the IDL language:

FUNCTION simpson, X

  RETURN, (X^4 - 2.0 * X^2) * SIN(X)

END

A

The lower limit of the integration. A can be either a scalar or an array.

B

The upper limit of the integration. B can be either a scalar or an array.

Note: If arrays are specified for A and B, then QSIMP integrates the user-supplied function over the interval [Ai, Bi] for each i. If either A or B is a scalar and the other an array, the scalar is paired with each array element in turn.

Keywords

DOUBLE

Set this keyword to force the computation to be done in double-precision arithmetic.

EPS

The desired fractional accuracy. For single-precision calculations, the default value is 1.0 x 10^-6. For double-precision calculations, the default value is 1.0 x 10^-12.

JMAX

2^(JMAX-1) is the maximum allowed number of steps. If not specified, a default of 20 is used.

Example

To integrate the SIMPSON function (listed above) over the interval [0, π/2] and print the result:

A = 0.0	Define lower limit of integration.

B = !PI/2.0	Define upper limit of integration.

PRINT, QSIMP('simpson', A, B)

IDL prints:

 -0.479158

The exact solution can be found using the integration-by-parts formula:

FB = 4.*B*(B^2-7.)*SIN(B) - (B^4-14.*B^2+28.)*COS(B)

FA = 4.*A*(A^2-7.)*SIN(A) - (A^4-14.*A^2+28.)*COS(A)

exact = FB - FA

PRINT, exact

IDL prints:

 -0.479156

See Also

INT_2D, INT_3D, INT_TABULATED, QROMB, QROMO


R_CORRELATE

The R_CORRELATE function computes Spearman's (rho) or Kendalls's (tau) rank correlation of two sample populations  X and Y. The result is a two-element vector containing the rank correlation coefficient and the two-sided significance of its deviation from zero. The significance is a value in the interval [0.0, 1.0]; a small value indicates a significant correlation.

where Rxi and Ryi are the magnitude-based ranks among X and Y, respectively. Elements of identical magnitude are ranked using a rank equal to the mean of the ranks that would otherwise be assigned.

This routine is written in the IDL language. Its source code can be found in the file r_correlate.pro in the lib subdirectory of the IDL distribution.

Calling Sequence

Result = R_CORRELATE(X, Y)

Arguments

X

An n-element integer, single-, or double-precision floating-point vector.

Y

An n-element integer, single-, or double-precision floating-point vector.

Keywords

D

Set this keyword to a named variable that will contain the sum-squared difference of ranks. If the KENDALL keyword is set, this parameter is returned as zero.

KENDALL

Set this keyword to compute Kendalls's (tau) rank correlation. By default, Spearman's (rho) rank correlation is computed.

PROBD

Set this keyword to a named variable that will contain the two-sided significance level of ZD. If the KENDALL keyword is set, this parameter is returned as zero.

ZD

Set this keyword to a named variable that will contain the number of standard deviations by which D deviates from its null-hypothesis expected value. If the KENDALL keyword is set, this parameter is returned as zero.

Example

Define two n-element sample populations.

X = [257, 208, 296, 324, 240, 246, 267, 311, 324, 323, 263, $

     305, 270, 260, 251, 275, 288, 242, 304, 267]

Y = [201, 56, 185, 221, 165, 161, 182, 239, 278, 243, 197, $

     271, 214, 216, 175, 192, 208, 150, 281, 196]

Compute Spearman's (rho) rank correlation of X and Y.

result = R_CORRELATE(X, Y)

PRINT, result

IDL prints:

[0.835967, 4.42899e-06]

Compute Kendalls's (tau) rank correlation of X and Y.

result = R_CORRELATE(X, Y, /KENDALL)

PRINT, result

IDL prints:

[0.624347 0.000118732]

See Also

A_CORRELATE, CORRELATE, C_CORRELATE, M_CORRELATE, P_CORRELATE


R_TEST

The R_TEST function tests the hypothesis that a binary population (a sequence of 1s and 0s) represents a "random sampling". The result is a two-element vector containing the nearly-normal test statistic Z and the one-tailed probability of obtaining a value of Z or greater. This test is based on the "theory of runs" and is often referred to as the "Runs Test for Randomness."

This routine is written in the IDL language. Its source code can be found in the file r_test.pro in the lib subdirectory of the IDL distribution.

Calling Sequence

Result = R_TEST(X)

Arguments

X

An n-element integer, single-, or double-precision floating-point vector. Elements not equal to 0 or 1 are removed and the length of X is correspondingly reduced.

Keywords

N0

Set this keyword to a named variable that will contain the number of 0s in X.

N1

Set this keyword to a named variable that will contain the number of 1s in X.

R

Set this keyword to a named variable that will contain the number of runs (clusters of 0s and 1s) in X.

Example

Define a binary population.

X = [0, 1, 1, 0, 1, 0, 0, 0, 1, 0, 0, 1, 1, 0, 1, 0, 1, 0, 0, $

     1, 0, 1, 1, 0, 1, 0, 0, 1, 0, 1]

Test the hypothesis that X represents a random sampling against the hypothesis that it does not represent a random sampling at the 0.05 significance level.

result = R_TEST(X, R = r, N0 = n0, N1 = n1)

PRINT, result

IDL prints:

[2.26487, 0.0117604]

Print the values of the keyword parameters:

PRINT, 'Runs: ', r & PRINT, 'Zeros: ', n0 & PRINT, 'Ones: ', n1

Runs:     22

Zeros:    16

Ones:     14

The computed probability (0.0117604) is less than the 0.05 significance level and therefore we reject the hypothesis that X represents a random sampling. The results show that there are too many runs, indicating a non-random cyclical pattern.

See Also

CTI_TEST, FV_TEST, KW_TEST, LNP_TEST, MD_TEST, RS_TEST, S_TEST, TM_TEST, XSQ_TEST


RANDOMN

The RANDOMN function returns one or more normally-distributed, floating-point, pseudo-random numbers with a mean of zero and a standard deviation of one.

RANDOMN uses the Box-Muller method for generating normally-distributed random numbers.

Calling Sequence

Result = RANDOMN(Seed [, D1, ..., Dn])

Arguments

Seed

A named variable containing the seed value for random number generation. Seed is updated by RANDOMN once for each random number generated. The initial value of Seed should be set to different values in order to obtain different random sequences. If the named variable Seed  is undefined, it is derived from the system clock.

Di

The dimensions of the result. The dimension parameters can be any scalar expression. Up to eight dimensions can be specified. If no dimensions are specified, RANDOMN returns a scalar result

Examples

Create a 10-element by 10-element array of normally-distributed, random numbers by entering:

R = RANDOMN(seed, 10, 10)

Since seed is undefined, the system time is used to initialize the random number generator. Print the resulting values by entering:

PRINT, R

Note that some of the values are negative. Use the RANDOMU function to generate uniformly-distributed, positive values.

A more interesting example plots the probability function of 2000 numbers returned by RANDOMN. Enter:

PLOT, HISTOGRAM(RANDOMN(SEED, 2000), BINSIZE=0.1)

See Also

RANDOMU


RANDOMU

The RANDOMU function returns one or more uniformly-distributed, floating-point, pseudo-random numbers in the range 0 ≤ Y < 1.0.

The random number generator is taken from: "Random Number Generators: Good Ones are Hard to Find", Park and Miller, Communications of the ACM, Oct 1988, Vol 31, No. 10, p. 1192.

Calling Sequence

Result = RANDOMU(Seed [, D1, ..., Dn])

Arguments

Seed

A named variable containing the seed value for random number generation. Seed is updated by RANDOMU once for each random number generated. The initial value of Seed should be set to different values in order to obtain different random sequences. If Seed is undefined, it is derived from the system clock.

Di

The dimensions of the result. The dimension parameters can be any scalar expression. Up to eight dimensions can be specified. If no dimensions are specified, RANDOMU returns a scalar result

Example

This example simulates rolling two dice 10,000 times and plots the distribution of the total using RANDOMU. Enter:

PLOT, HISTOGRAM(FIX(6 * RANDOMU(S, 10000)) + $

  FIX(6 * RANDOMU(S, 10000)) + 2)

In the above statement, the expression RANDOMU(S, 10000) is a 10,000-element, floating-point array of random numbers greater than or equal to 0 and less than 1. Multiplying this array by 6 converts the range to 0 ≤ Y < 6.

Applying the FIX function yields a 10,000-point integer vector with values from 0 to 5, one less than the numbers on one die. This computation is done twice, once for each die, then 2 is added to obtain a vector from 2 to 12, the total of two dice.

The HISTOGRAM function makes a vector in which each element contains the number of occurrences of dice rolls whose total is equal to the subscript of the element. Finally, this vector is plotted by the PLOT procedure.

See Also

RANDOMN


RANKS

The RANKS function computes the magnitude-based ranks of a sample population X. Elements of identical magnitude "ties" are ranked according to the mean of the ranks that would otherwise be assigned. The result is a vector of ranks equal in length to X.

This routine is written in the IDL language. Its source code can be found in the file ranks.pro in the lib subdirectory of the IDL distribution.

Calling Sequence

Result = RANKS(X)

Arguments

X

An n-element integer, single-, or double-precision floating-point vector. The elements of this vector must be in ascending order based on their magnitude.

Example

Define an n-element sample population.

X = [-0.8, 0.1, -2.3, -0.6, 0.2, 1.1, -0.3, 0.6, -0.2, 1.1, $

     -0.7, -0.2, 0.6, 0.4, -0.1, 1.1, -0.3, 0.3, -1.3, 1.1]

Allocate a two-column, n-row array to store the results.

array = FLTARR(2, N_ELEMENTS(X))

Sort the sample population and store in the 0th column of ARRAY.

array(0, *) = X(SORT(X))

Compute the ranks of the sorted sample population and store in the 1st column of ARRAY.

array(1, *) = RANKS(X(SORT(X)))

Display the sorted sample population and corresponding ranks with a two-decimal format.

PRINT, array, FORMAT = '(2(5x, f5.2))'

IDL prints:

-2.30      1.00

-1.30      2.00

-0.80      3.00

-0.70      4.00

-0.60      5.00

-0.30      6.50

-0.30      6.50

-0.20      8.50

-0.20      8.50

-0.10     10.00

 0.10     11.00

 0.20     12.00

 0.30     13.00

 0.40     14.00

 0.60     15.50

 0.60     15.50

 1.10     18.50

 1.10     18.50

 1.10     18.50

 1.10     18.50

See Also

R_CORRELATE


RDPIX

The RDPIX procedure interactively displays the X position, Y position, and pixel value at the cursor.

This routine is written in the IDL language. Its source code can be found in the file rdpix.pro in the lib subdirectory of the IDL distribution.

Using RDPIX

RDPIX displays a stream of X, Y, and pixel values when the mouse cursor is moved over a graphics window. Press the left or center mouse button to create a new line of output. Press the right mouse button to exit the procedure.

Calling Sequence

RDPIX, Image [, X0, Y0]

Arguments

Image

The array that contains the image being displayed. This array may be of any type. Rather reading pixel values from the display, they are taken from this parameter, avoiding scaling difficulties.

X0, Y0

The location of the lower-left corner of the image area on screen. If these parameters are not supplied, they are assumed to be zero.

Example

See Also

CURSOR, TVRD


READ

The READ procedures perform formatted input into variables.

READ performs input from the standard input stream (IDL file unit 0), while READF requires a file unit to be explicitly specified.

Calling Sequence

READ,  [Prompt,] Var1, ..., Varn

or

READF, [Prompt,] Unit, Var1, ..., Varn

Arguments

Prompt

Note that the PROMPT keyword should be used instead of the Prompt argument for compatibility with window-based versions of IDL.

A string or explicit expression (i.e, not a named variable) to be used as a prompt. This argument should not be included if the FORMAT keyword is specified. Also, if this argument begins with the characters "$(", it is taken to be a format specification as described below under "Format Compatibility".

Using the Prompt argument does not work well with IDL for Windows and IDL for Macintosh. The desired prompt string is written to the log window instead of the command input window. To create custom prompts compatible with these versions of IDL, use the PROMPT keyword, described below.

Unit

For READF, Unit specifies the file unit from which the input is taken.

Vari

The named variables to receive the input.

Keywords

FORMAT

If FORMAT is not specified, IDL uses its default rules for formatting the input. FORMAT allows the format of the input to be specified in precise detail, using a FORTRAN-style specification. See "Explicitly Formatted Input/Output" on page 17-15 of the IDL User's Guide.

PROMPT

Set this keyword to a scalar string to be used as a customized prompt for the READ command. If the PROMPT keyword or Prompt argument is not supplied, IDL uses a colon followed by a space (": ") as the input prompt.

VMS Keywords

Note also that the obsolete VMS-only routine READ_KEY has been replaced by the keywords below.

KEY_ID

The index key to be used (primary = 0, first alternate key = 1, etc...) when accessing data from a file with indexed organization. If this keyword is omitted, the primary key is used.

KEY_MATCH

The relation to be used when matching the supplied key with key field values (EQ = 0, GE = 1, GT = 2) when accessing data from a file with indexed organization. If this keyword is omitted, the equality relation (0) is used.

KEY_VALUE

The value of a key to be found when accessing data from a file with indexed organization. This value must match the key definition that is determined when the file was created in terms of type and size—no conversions are performed. If this keyword is omitted, the next sequential record is used.

Format Compatibility

If the FORMAT keyword is not present and READ is called with more than one argument, and the first argument is a scalar string starting with the characters "$(", this initial argument is taken to be the format specification, just as if it had been specified via the FORMAT keyword. This feature is maintained for compatibility with version 1 of VMS IDL.

Example

To read a string value into the variable B from the keyboard, enter:

B = ''	Define B as a string before reading.

READ, B, PROMPT='Enter Name: '	Read input from the terminal.

To read formatted data from the previously-opened file associated with logical unit number 7 into variable C, use the command:

READF, 7, C

See Also

READS, READU,  WRITEU


READ_BMP

The READ_BMP function reads a Microsoft Windows Version 3 device independent bitmap file (.BMP) and returns a byte array containing the image. Dimensions are taken from the BITMAPINFOHEADER of the file. In the case of 4-bit or 8-bit images, the dimensions of the resulting array are (biWidth, biHeight).

For 24-bit images, the dimensions are (3, biWidth, biHeight). Color interleaving is blue, green, red; i.e., Result(0,i,j) = blue, Result(1,i,j) = green, etc.

READ_BMP does not handle 1-bit-deep images or compressed images, and is not fast for 4-bit images. The algorithm works best on images where the number of bytes in each scan-line is evenly divisible by 4.

This routine is written in the IDL language. Its source code can be found in the file read_bmp.pro in the lib subdirectory of the IDL distribution.

Calling Sequence

Result = READ_BMP(File [, R, G, B [, Ihdr]])

Arguments

File

A scalar string specifying the full path name of the bitmap file to read.

R, G, B

Named variables that will contain the color tables from the file. There 16 elements each for 4 bit images, 256 elements each for 8 bit images. Color tables are not defined or used for 24 bit images.

Ihdr

A named variable that will contain a structure holding the BITMAPINFOHEADER from the file. Tag names are as defined in the MS Windows Programmer's Reference Manual, Chapter 7.

Example

To open, read, and display the BMP file named foo.bmp in the current directory and store the color vectors in the variables R, G, and B, enter:

TV, READ_BMP('foo.bmp', R, G, B)	Read and display an image

TVLCT, R, G, B	Load its colors

See Also

WRITE_BMP


READ_GIF

The READ_GIF procedure reads the contents of a GIF format image file and returns the image and color table vectors (if present) in the form of IDL variables.

Note that although the GIF format allows files to contain multiple images, READ_GIF only reads in the first image in a file. Only 8-bit images are supported, and local colormaps are not supported.

This routine is written in the IDL language. Its source code can be found in the file read_gif.pro in the lib subdirectory of the IDL distribution.

Calling Sequence

READ_GIF, File, Image [, R, G, B]

Arguments

File

A scalar string specifying the full path name of the rasterfile file to read.

Image

A named variable that will contain the image (a 2D byte array).

R, G, B

Named variables that will contain the Red, Green, and Blue color vectors, if the rasterfile contains colormaps.

Example

To open and read the GIF image file named foo.gif in the current directory, store the image in the variable image1, and store the color vectors in the variables R, G, and B, enter:

READ_GIF, 'foo.gif', image1, R, G, B

To load the new color table and display the image, enter:

TVLCT, R, G, B

TV, image1

See Also

WRITE_GIF


READ_INTERFILE

The READ_INTERFILE procedure reads image data stored in Interfile (v3.3) format and returns a 3D array.

Note: this is a simplistic reader. READ_INTERFILE can only read a series of images if all images have the same height and width. It does not get additional keyword information beyond what is needed to read the image data. If any problems occur when reading the file, READ_INTERFILE prints a message and stops.

If the data is stored on a bigendian machine and read on a littleendian machine (or vice versa) the order of bytes in each pixel element may be reversed, requiring a call to BYTEORDER

This routine is written in the IDL language. Its source code can be found in the file read_interfile.pro in the lib subdirectory of the IDL distribution.

Calling Sequence

READ_INTERFILE, File, Data

Arguments

File

A scalar string containing the name of the Interfile to read. Note: if the Interfile has a header file and a data file, this should be the name of the header file (also called the administrative file).

Data

A named variable that will contain a 3D array of data as read from the file. Assumed to be a series of 2D images.

Example

READ_INTERFILE, '0_11.hdr', X


READ_JPEG

The READ_JPEG procedure reads JPEG (Joint Photographic Experts Group) format compressed images from files or memory. JPEG is a standardized compression method for full-color and gray-scale images. This procedure reads JFIF format files (often called "JPEG" files), including those produced by WRITE_JPEG.

READ_JPEG can optionally quantize true-color images contained in files to a pseudo-color palette with a specified number of colors, and with optional color dithering.

This procedure is based in part on the work of the "Independent JPEG Group". For a brief explanation of JPEG, consult the description of the WRITE_JPEG procedure (page 1-1044).

Calling Sequence

READ_JPEG, [Filename,] Image [,Colortable]

Arguments

Filename

A string containing the name of the JFIF format (JPEG) file to be read. If this parameter is not present, the UNIT and/or the BUFFER keywords must be specified.

Image

A named variable to receive the image.

Colortable

A named variable to receive the colormap, when reading a true-color image that is to be quantized. On completion, this variable contains a byte array with dimensions (COLORS, 3).

Keywords

BUFFER

Set this keyword to a named variable that is used for a buffer. A buffer variable need only be supplied when reading multiple images per file. Initialize the buffer variable to empty by setting it to 0. Example:

buff = 0	Initialize buffer.

OPENR, 1, 'images.jpg', /STREAM

FOR i=1, nimages DO BEGIN	Process each image.

READ_JPEG, UNIT=1, BUFFER=buff, a	Read next image.

TV, a	Display the image.

ENDFOR

CLOSE, 1	Done.

COLORS

If the image file contains a true-color image which must be displayed on an 8-bit display, set COLORS to the desired number of colors to be quantized. COLORS can be set to a value from 8 to 256. The DITHER and TWO_PASS_QUANTIZE keywords affect the method, speed, and quality of the color quantization. These keywords have no effect if the file contains a grayscale image.

DITHER

Set this keyword to use dithering with color quantization (i.e., if the COLORS keyword is in use). Dithering is a method that distributes the color quantization error to surrounding pixels, to achieve higher-quality results.

ORDER

JPEG/JFIF images are normally written in top-to-bottom order. If the image is to be stored into the Image array in the standard IDL order (from bottom-to-top) set ORDER to 0. This is the default. If the image array is to be top-to-bottom order, ORDER must be set to 1.

TRUE

Use this keyword to specify the index of the dimension for color interleaving when reading a true-color image. The default is 1, for pixel interleaving, (3,m,n). A value of 2 indicates line interleaving (m,3,n), and 3 indicates band interleaving, (m,n,3).

TWO_PASS_QUANTIZE

Set this keyword to use a two-pass color quantization method when quantization is in effect (i.e., the COLORS keyword is in use). This method requires more memory and time, but produces superior results to the default one-pass quantization method.

UNIT

This keyword can be used to designate the logical unit number of an already open JFIF file, allowing the reading of multiple images per file or the embedding of JFIF images in other data files.

When using this keyword, Filename should not be specified.

READ_JPEG buffers its input data. To read multiple images per file, use the BUFFER keyword. When using VMS, open the file with the /STREAM keyword.

Examples

Read and display a JPEG grayscale image:

READ_JPEG, 'test.jpg', a	Read the image.

TV, a	Display the image.

Read and display a JPEG true-color image on a true-color display:

READ_JPEG, 'test.jpg', a, TRUE=1	Read the image.

TV, a, TRUE=1	Display the image returned with pixel interleaving (i.e., with dimensions 3, m, n).

Read and display a JPEG true-color image on an 8-bit pseudo-color display:

READ_JPEG, 'test.jpg', a, ctable, COLORS=!D.N_COLORS-1
Read the image, setting the number of colors to be quantized to the maximum number of available colors. Note that we could have also included the TWO_PASS_QUANTIZE and DITHER keywords to improve the image's appearance.

TV, a	Display the image.

TVLCT, ctable	Load the quantized colortable.

See Also

WRITE_JPEG


READ_PICT

The READ_PICT procedure reads the contents of a PICT (version 2) format image file and returns the image and color table vectors (if present) in the form of IDL variables. The PICT format is used by Apple Macintosh computers.

This routine is written in the IDL language. Its source code can be found in the file read_pict.pro in the lib subdirectory of the IDL distribution.

Calling Sequence

READ_PICT, File, Image [, R, G, B]

Arguments

File

A scalar string containing the name of the PICT file to read.

Image

A named variable that will contain the 2D image read from File.

R, G, B

Named variables that will contain the Red, Green, and Blue color vectors read from the PICT file.

Example

To open and read the PICT image file named foo.pict in the current directory, store the image in the variable image1, and store the color vectors in the variables R, G, and B, enter:

READ_PICT, 'foo.pict', image1, R, G, B

To load the new color table and display the image, enter:

TVLCT, R, G, B

TV, image1

See Also

WRITE_PICT


READ_PPM

The READ_PPM procedure reads the contents of a PGM (gray scale) or PPM (portable pixmap for color) format image file and returns the image in the form of a 2D byte array (for grayscale images) or a (3, n, m) byte array (for true-color images).

Files to be read should adhere to the PGM/PPM standard. The following file types are supported: P2 (graymap ASCII), P5 (graymap RAWBITS), P3 (true-color ASCII pixmaps), and P6 (true-color RAWBITS pixmaps). Maximum pixel values are limited to 255. Images are always stored with the top row first.

PPM/PGM format is supported by the PBMPLUS toolkit for converting various image formats to and from portable formats, and by the Netpbm package.

This routine is written in the IDL language. Its source code can be found in the file read_ppm.pro in the lib subdirectory of the IDL distribution.

Calling Sequence

READ_PPM, File, Image

Arguments

File

A scalar string specifying the full path name of the PGM or PPM file to read.

Image

A named variable that will contain the image. For grayscale images, Image is a 2D byte array. For true-color images, Image is a (3, n, m) byte array.

Keywords

MAXVAL

A named variable that will contain the maximum pixel value.

Example

To open and read the PGM image file named "foo.pgm" in the current directory and store the image in the variable IMAGE1:

READ_PPM, "foo.pgm", IMAGE1

See Also

WRITE_PPM


READ_SPR

The READ_SPR function reads a row-indexed sparse array from a specified file and returns the array as the result. Row-indexed sparse arrays are created using the SPRSIN function and written to a file using the WRITE_SPR function.

This routine is written in the IDL language. Its source code can be found in the file read_spr.pro in the lib subdirectory of the IDL distribution.

Calling Sequence

Result = READ_SPR(Filename)

Arguments

Filename

A scalar string specifying the name of the file containing a row-indexed sparse array.

Example

Suppose we have already saved a row-indexed sparse array to a file named sprs.as, as described in the documentation for the WRITE_SPR routine. To read the sparse array from the file and store it in a variable sprs, use the following command:

sprs = READ_SPR('sprs.as')

See Also

FULSTR, LINBCG, SPRSAB, SPRSAX, SPRSIN, WRITE_SPR


READ_SRF

The READ_SRF procedure reads the contents of a Sun rasterfile and returns the image and color table vectors (if present) in the form of IDL variables.

READ_SRF only handles 1-, 8-, 24-, and 32-bit rasterfiles of type RT_OLD and RT_STANDARD. See the file /usr/include/rasterfile.h for the structure of Sun rasterfiles.

This routine is written in the IDL language. Its source code can be found in the file read_srf.pro in the lib subdirectory of the IDL distribution.

Calling Sequence

READ_SRF, File, Image [, R, G, B]

Arguments

File

A scalar string containing the name of the rasterfile to read.

Image

A named variable that will contain the 2D byte array (image).

R, G, B

Named variables that will contain the Red, Green, and Blue color vectors, if the rasterfile contains colormaps.

Example

To open and read the Sun rasterfile named sun.srf in the current directory, store the image in the variable image1, and store the color vectors in the variables R, G, and B, enter:

READ_SRF, 'sun.srf', image1, R, G, B

To load the new color table and display the image, enter:

TVLCT, R, G, B

TV, image1

See Also

WRITE_SRF


READ_SYLK

The READ_SYLK function reads the contents of a SYLK (Symbolic Link) format spreadsheet data file and returns the contents of the file, or of a cell data range, in an IDL variable. READ_SYLK returns either a vector of structures or a 2D array containing the spreadsheet cell data.

By default, READ_SYLK returns a vector of structures, each of which contains the data from one row of the table being read. In this case, the individual fields in the structures have the tag names "Col0", "Col1", ..., "Coln". If the COLMAJOR keyword is specified, each of the structures returned contains data from one column of the table, and the tag names are "Row0", "Row1", ..., "Rown".

Note: This routine reads only numeric and string SYLK data. It ignores all spreadsheet and cell formatting information (cell width, text justification, font type, date, time, and monetary notations, etc). Note also that the data in a given cell range must be of the same data type (all integers, for example) in order for the read operation to succeed. See the example below for further information.

This routine is written in the IDL language. Its source code can be found in the file read_sylk.pro in the lib subdirectory of the IDL distribution.

Calling Sequence

Result = READ_SYLK(File)

Arguments

File

A scalar string specifying the full path name of the SYLK file to read.

Keywords

ARRAY

Set this keyword to return an IDL array rather than a vector of structures. Note that all the data in the cell range specified must be of the same data type to successfully return an array.

COLMAJOR

Set this keyword to create a vector of structures each containing data from a single column of the table being read. If you are creating an array rather than a vector of structures (the ARRAY keyword is set), setting COLMAJOR has the same effect as transposing the resulting array.

This keyword should be set when importing spreadsheet data which has column major organization (data stored in columns rather than rows).

NCOLS

Set this keyword to the number of spreadsheet columns to read. If not specified, all of the cell columns found in the file are read.

NROWS

Set this keyword to the number of spreadsheet rows to read. If not specified, all of the cell rows found in the file are read.

STARTCOL

Set this keyword to the first column of spreadsheet cells to read. If not specified, the read operation begins with the first column found in the file (column 0).

STARTROW

Set this keyword to the first row of spreadsheet cells to read. If not specified, the read operation begins with the first row of cells found in the file (row 0).

USEDOUBLES

Set this keyword to read any floating-point cell data as double-precision rather than the default single-precision.

USELONGS

Set this keyword to read any integer cell data as long integer type rather than the default integer type.

Examples

Suppose the following spreadsheet table, with the upper left cell (value = "Index") at location (0, 0), has been saved as the SYLK file "file.slk":

Index  Name  Gender  Platform

1      Beth  F       Unix

2      Kirk  M       VMS

3      Mark  M       Windows

4      Dave  M       Macintosh

Note that the data format of the title row (string,  string, string, string) is inconsistent with the following four rows (int, string, string, string) in the table. Because of this, it is impossible to read all of the table into a single IDL variable. The following two commands, however, will read all of the data:

title = READ_SYLK("file.slk", NROWS = 1)

table = READ_SYLK("file.slk", STARTROW = 1)

PRINT, title	Display the top row of the table.

IDL prints:

{ Index Name Gender Platform}

PRINT, table

IDL prints:

{ 1 Beth F Unix}{ 2 Kirk M VMS}{ 3 Mark M Windows}{ 4 Dave
M Macintosh}

To retrieve only the "Name" column:

names = READ_SYLK("file.slk", /ARRAY, STARTROW = 1, $
STARTCOL = 1, NCOLS = 1)

PRINT, names

IDL prints:

Beth Kirk Mark Dave

To retrieve the "Name" column in column format:

namescol = READ_SYLK("file.slk", /ARRAY, /COLMAJOR, $
STARTROW = 1, STARTCOL = 1, NCOLS = 1)

PRINT, namescol

IDL prints:

Beth

Kirk

Mark

Dave

See Also

WRITE_SYLK


READ_WAVE

The READ_WAVE procedure reads a .wave or .bwave file created by the Wavefront Advanced Data Visualizer into an series of IDL variables.

Note: READ_WAVE only preserves the structure of the variables if they are regularly gridded.

This routine is written in the IDL language. Its source code can be found in the file read_wave.pro in the lib subdirectory of the IDL distribution.

Calling Sequence

READ_WAVE, File, Variables, Names, Dimensions

Arguments

File

A scalar string containing the name of the Wavefront file to read.

Variables

A named variable that will contain a block of the variables contained in the wavefront file. Since each variable in a wavefront file can have more than one field (for instance, a vector variable has 3 fields), the fields of each variable make up the major index into the variable block. For instance, if a Wavefront file had one scalar variable and one vector variable, the scalar would be extracted as follows:

vector_scalar = variables(0,*,*,*)

and the vector variable would be extracted as follows:

vector_variable = variables(1:3,*,*,*)

To find the dimensions of the returned variable, see the description of the Dimensions argument.

Names

A named variable that will contain the string names of each variable contained in the file.

Dimensions

A named variable that will contain a long array describing how many fields in the large returned variable block each variable occupies. In the above example of one scalar variable followed by a vector variable, the dimension variable would be [1,3].

This indicates that the first field of the returned variable block would be the scalar variable and the following 3 fields would comprise the vector variable.

Keywords

MESHNAMES

Set this keyword to a named variable that will contain the name of the mesh used in the Wavefront file for each variable.

See Also

WRITE_WAVE


READ_X11_BITMAP

The READ_X11_BITMAP procedure reads bitmaps stored in the X Windows X11 format. The X Windows bitmap program produces a C header file containing the definition of a bitmap produced by that program. This procedure reads such a file and creates an IDL byte array containing the bitmap. It is used primarily to read bitmaps to be used as IDL widget button labels.

This routine is written in the IDL language. Its source code can be found in the file read_x11_bitmap.pro in the lib subdirectory of the IDL distribution.

Calling Sequence

READ_X11_BITMAP, File, Bitmap [, X, Y]

Arguments

File

A scalar string containing the name of the file containing the bitmap.

Bitmap

A named variable that will contain the bitmap. This variable is returned as a byte array.

X

A named variable that will contain the width of the bitmap.

Y

A named variable that will contain the height of the bitmap.

Keywords

EXPAND_TO_BYTES

Set this keyword to instruct READ_X11_BITMAP to return a 2D array which has one bit per byte (0 for a 0 bit), (255 for a 1 bit) instead.

Example

To open and read the X11 bitmap file named my.x11 in the current directory, store the bitmap in the variable bitmap1, and the width and height in the variables X and Y, enter:

READ_X11_BITMAP, 'my.x11', bitmap1, X, Y

To display the new bitmap, enter:

READ_X11_BITMAP, 'my.x11', image, /EXPAND_TO_BYTES

TV, image, /ORDER

See Also

READ_XWD


READ_XWD

The READ_XWD function reads the contents of a file created by the xwd (X Windows Dump) command and returns the image and color table vectors in the form of IDL variables. READ_XWD returns a 2D byte array containing the image. If the file cannot be open or read, the return value is zero.

Note: this function is intended to be used only on files containing 8-bit pixmaps created with xwd version 6 or later.

This routine is written in the IDL language. Its source code can be found in the file read_xwd.pro in the lib subdirectory of the IDL distribution.

Calling Sequence

Result = READ_XWD(File [, R, G, B])

Arguments

File

A scalar string containing the name of the XWD file to read.

R, G, B

Named variables that will contain the Red, Green, and Blue color vectors, if the XWD file contains color tables.

Example

To open and read the X Windows Dump file named my.xwd in the current directory, store the image in the variable image1, and store the color vectors in the variables, R, G, and B, enter:

image1 = READ_XWD('my.xwd', R, G, B)

To load the new color table and display the image, enter:

TVLCT, R, G, B

TV, image1

See Also

READ_X11_BITMAP


READS

The READS procedure performs formatted input from a string variable and writes the results into one or more output variables. This procedure differs from the READ procedure only in that the input comes from memory instead of a file.

This routine is useful when you need to examine the format of a data file before reading the information it contains. Each line of the file can be read into a string using READF. Then the components of that line can be read into variables using READS.

Calling Sequence

READS, Input, Var1, ..., Varn

Arguments

Input

The string variable from which the input is taken. If the supplied argument is not a string, it is automatically converted. The argument can be scalar or array. If Input is an array, the individual string elements are treated as successive lines of input.

Vari

The named variables to receive the input.

Keywords

FORMAT

If FORMAT is not specified, IDL uses its default rules for formatting the input. FORMAT allows the format of the input to be specified in precise detail, using a FORTRAN-style specification. See "Explicitly Formatted Input/Output" on page 17-15 of the IDL User's Guide.

See Also

READ, READU


READU

The READU procedure reads unformatted binary data from a file into IDL variables. READU transfers data directly with no processing of any kind performed on the data.

Calling Sequence

READU, Unit, Var1, ..., Varn

Arguments

Unit

The IDL file unit from which input is taken.

Vari

Named variables to receive the data. For non-string variables, the number of bytes required for Var are read. When READU is used with a variable of type string, IDL reads exactly the number of bytes contained in the existing string. For example, to read a 5-character string, enter:

temp = '12345'

READU, unit, temp

Unix Keywords

TRANSFER_COUNT

Set this keyword to a named variable in which to return the number of elements transferred by the input operation. Note that the number of elements is not the same as the number of bytes (except in the case where the data type being transferred is bytes). For example, transferring 256 floating-point numbers yields a transfer count of 256, not 1024 (the number of bytes transferred).

This keyword is useful with files opened with the NOSTDIO keyword to the OPEN routines. Normally, attempting to read more data than is available from a file causes the unfilled space to be zeroed and an error to be issued. This does not happen with files opened with the NOSTDIO keyword. Instead, the programmer must keep track of the transfer count.

VMS Keywords

Note that the obsolete VMS routines FORRD, and FORRD_KEY have been replaced by the READU command used with the following keywords.

KEY_ID

The index key to be used (primary = 0, first alternate key = 1, etc...) when accessing data from a file with indexed organization. If this keyword is omitted, the primary key is used.

KEY_MATCH

The relation to be used when matching the supplied key with key field values (EQ = 0, GE = 1, GT = 2) when accessing data from a file with indexed organization. If this keyword is omitted, the equality relation (0) is used.

KEY_VALUE

The value of a key to be found when accessing data from a file with indexed organization. This value must match the key definition that is determined when the file was created in terms of type and size—no conversions are performed. If this keyword is omitted, the previous key value is used.

Example

The following commands can be used to open the IDL distribution file people.dat and read an image from that file:

OPENR, 1, FILEPATH('people.dat', SUBDIR='images')
Open the file for reading as file unit 1.

B = BYTARR(192, 192)	The image we want to read is a 192 by 192 byte array, so make B that size.

READU, 1, B	Read the data into B.

CLOSE, 1	Close the file.

TV, B	Display the image.

See Also

READ, READS,  WRITEU


REBIN

The REBIN function resizes a vector or array to dimensions given by the parameters Di. The supplied dimensions must be integral multiples or factors of the original dimension. The expansion or compression of each dimension is independent of the others, so that each dimension can be expanded or compressed by a different value.

If the dimensions of the desired result are not integer multiples of the original dimensions, use the CONGRID function.

Calling Sequence

Result = REBIN(Array, D1, ..., Dn)

Arguments

Array

The array to be resampled. Array can be of any basic type except complex or string.

Di

The dimensions of the resulting resampled array. These dimensions must be integer multiples or factors of the corresponding original dimensions.

Keywords

SAMPLE

Normally, REBIN uses bilinear interpolation when magnifying and neighborhood averaging when minifying. Set the SAMPLE keyword to use nearest neighbor sampling for both magnification and minification. Bilinear interpolation gives higher quality results but requires more time.

Rules Used by REBIN

Assume the original vector X has n elements and the result is to have m elements.

Let f = n/m, the ratio of the size of the original vector, X to the size of the result. 1/f must be an integer if n < m (expansion). f must be an integer if compressing, (n > m). The various resizing options can be described as:

•	Expansion, n < m, SAMPLE = 0: Y(i) = F(X, f ⋅ i)       i = 0, 1, ... , m-1

The linear interpolation function, F(X, p) that interpolates X at location p, is defined as:

•	Expansion, n < m, SAMPLE = 1:

•	Compression, n > m, SAMPLE = 0:

•	Compression, n > m, SAMPLE = 1:

•	No change, n = m: Yi = Xi

Endpoint Effects When Expanding

When expanding an array, REBIN interpolates, it never extrapolates. Each of the n-1 intervals in the n-element input array produces m/n interpolates in the m-element output array. The last m/n points of the result are obtained by duplicating element n-1 of the input array because their interpolates would lie outside the input array.

For example

A = [0, 10, 20, 30]	A four point vector.

B = REBIN(A, 12)	Expand by a factor of 3.

PRINT, B

0 3 6 10 13 16 20 23 26 30 30 30

Note that the last element is repeated three times. If this effect is undesirable, use the INTERPOLATE function. For example, to produce 12 equally spaced interpolates from the interval 0 to 3:

B = INTERPOLATE(A, 3./11. * FINDGEN(12))

PRINT, B

0 2 5 8 10 13 16 19 21 24 27 30

Here, the sampling ratio is (n - 1)/(m - 1).

Example

Create and display a simple image by entering:

D = SIN(DIST(50)/4) & TVSCL, D

Resize the image to be 5 times its original size and display the result by entering:

D = REBIN(D, 250, 250) & TVSCL, D

See Also

CONGRID


RECON3

The RECON3 function can reconstruct a three-dimensional data array from two or more images (or projections) of an object. For example, if you placed a dark object in front of a white background and then photographed it three times (each time rotating the object a known amount) then these three images could be used with RECON3 to approximate a 3D volumetric representation of the object. RECON3 also works with translucent projections of an object. RECON3 returns a 3D byte array.

This routine is written in the IDL language. Its source code can be found in the file recon3.pro in the lib subdirectory of the IDL distribution.

Using RECON3

Images used in reconstruction should show strong light/dark contrast between the object and the background. If the images contain low (dark) values where the object is and high (bright) values where the object isn't, the MODE keyword should be set to +1 and the returned volume will have low values where the object is, and high values where the object isn't. If the images contain high (bright) values where the object is and low (dark) values where the object isn't, the MODE keyword should be set to -1 and the returned volume will have high values where the object is, and low values where the object isn't.

In general, the object must be CONVEX for a good reconstruction to be possible. Concave regions are not easily reconstructed. An empty coffee cup, for example, would be reconstructed as if it were full.

The more images the better. Images from many different angles will improve the quality of the reconstruction. It is also important to supply images that are parallel and perpendicular to any axes of symmetry. Using the coffee cup as an example, at least one image should be looking through the opening in the handle. Telephoto images are also better for reconstruction purposes than wide angle images.

Calling Sequence

Result = RECON3(Images, Obj_Rot, Obj_Pos, Focal, Dist, $
                               Vol_Pos, Img_Ref, Img_Mag, Vol_Size)

Arguments

Images

A 3D array containing the images to use to reconstruct the volume. Execution time increases linearly with more images. Images must be an 8-bit (byte) array with dimensions (x, y, n) where x is the horizontal image dimension, y is the vertical image dimension, and n is the number of images. Note that n must be at least 2.

Obj_Rot

A 3 x  n floating-point array specifying the amount the object is rotated to make it appear as it does in each image. The object is first rotated about the X axis, then about the Y axis, and finally about the Z axis (with the object's reference point at the origin). Obj_Rot(0, *) is the X rotation for each image, Obj_Rot(1, *) is the Y rotation, and Obj_Rot(2, *) is the Z rotation.

Obj_Pos

A 3 x  n floating-point array specifying the position of the object's reference point relative to the camera lens. The camera lens is located at the coordinate origin and points in the negative Z direction (the view up vector points in the positive Y direction). Obj_Pos should be expressed in this coordinate system. Obj_Pos(0, *) is the X position for each image, Obj_Pos(1, *) is the Y position, and Obj_Pos(2, *) is the Z position. All the values in Obj_Pos(2, *) should be less than zero. Note that the values for  Obj_Pos, Focal, Dist, and Vol_Pos should all be expressed in the same units (mm, cm, m, in, ft, etc.).

Focal

An n-element floating-point array specifying the focal length of the lens for each image. Focal may be set to zero to indicate a parallel image projection (infinite focal length).

Dist

An n-element floating-point array specifying the distance from the camera lens to the image plane (film) for each image. Dist should be greater than Focal.

Vol_Pos

A 3 x 2 floating-point array specifying the two opposite corners of a cube that surrounds the object. Vol_Pos should be expressed in the object's coordinate system relative to the object's reference point. Vol_Pos(*, 0) specifies one corner and Vol_Pos(*, 1) specifies the opposite corner.

Img_Ref

A 2 x  n integer or floating-point array that specifies the pixel location at which the object's reference point appears in each of the images.  Img_Ref(0, *) is the X coordinate for each image and  Img_Ref(1, *) is the Y coordinate.

Img_Mag

A 2 x  n integer or floating-point array that specifies the magnification factor for each image. This number is actually the length (in pixels) that a test object would appear in an image if it were n units long and n units distant from the camera lens. Img_Mag(0, *) is the X dimension (in pixels) of a test object for each image, and Img_Mag(1, *) is the Y dimension. All elements in Img_Mag should be greater than or equal to 1.

Vol_Size

A 3-element integer or floating-point array that specifies the size of the 3D byte array to return. Execution time (and resolution) increases exponentially with larger values for  Vol_Size. Vol_Size(0) specifies the X dimension of the volume, Vol_Size(1) specifies the Y dimension, and Vol_Size(2) specifies the Z dimension.

Keywords

MISSING

Set this keyword equal to a byte value for cells in the 3D volume that do not map to any of the supplied images. The value of MISSING is passed to the INTERPOLATE function. The default value is zero.

MODE

Set this keyword to a value less than zero to define each cell in the 3D volume as the  minimum of the corresponding pixels in the images. Set MODE to a value greater than zero to define each cell in the 3D volume as the maximum of the corresponding pixels in the images. If MODE is set equal to zero then each cell in the 3D volume is defined as the average of the corresponding pixels in the images.

MODE should usually be set to -1 when the images contain a bright object in front of a dark background or to +1 when the images contain a dark object in front of a light background. Setting MODE=0 (the default) requires more memory since the volume array must temporarily be kept as an integer array instead of a byte array.

Example

Assumptions for this example:

•	The object's major axis is parallel to the Z axis.

•	The object's reference point is at its center.

•	The camera lens is pointed directly at this reference point.

•	The reference point is 5000 mm in front of the camera lens.

•	The focal length of the camera lens is 200 mm.

If the camera is focused on the reference point, then the distance from the lens to the camera's image plane must be

dist = (d * f) / (d - f) = (5000 * 200) / (5000 - 200) = (1000000 / 4800) = 208.333 mm

The object is roughly 600 mm wide and 600 mm high. The reference point appears in the exact center of each image.

If the object is 600 mm high and 5000 mm distant from the camera lens, then the object image height must be

hi = (h * f) / (d - f) = (600 * 200) / (5000 - 200) = (120000 / 4800) = 25.0 mm

The object image appears 200 pixels high so the final magnification factor is

img_mag = (200 / 25) = 8.0

From these assumptions, we can set up the following reconstruction. First, define the variables:

imgx = 256

imgy = 256

frames = 3

images = BYTARR(imgx, imgy, frames)

obj_rot = Fltarr(3, frames)

obj_pos = Fltarr(3, frames)

focal = Fltarr(frames)

dist = Fltarr(frames)

vol_pos = Fltarr(3, 2)

img_ref = Fltarr(2, frames)

img_mag = Fltarr(2, frames)

vol_size = [40, 40, 40]

The object is 5000 mm directly in front of the camera:

obj_pos(0, *) = 0.0

obj_pos(1, *) = 0.0

obj_pos(2, *) = -5000.0

The focal length of the lens is constant for all the images.

focal(*) = 200.0

The distance from the lens to the image plane is also constant.

dist(*) = 208.333

The cube surrounding the object is 600 mm x 600 mm.

vol_pos(*, 0) = [-300.0, -300.0, -300.0]

vol_pos(*, 1) = [ 300.0, 300.0, 300.0]

The image reference point appears at the center of all the images.

img_ref(0, *) = imgx / 2

img_ref(1, *) = imgy / 2

The image magnification factor is constant for all images. (The images haven't been cropped or resized).

img_mag(*,*) = 8.0

Only the object rotation changes from one image to the next. Note that the object is rotated about the X axis first, then Y, and then Z. Create some fake images for this example.

images(30:160, 20:230, 0) = 255

images(110:180, 160:180, 0) = 180

obj_rot(*, 0) = [-90.0, 0.0, 0.0]

images(70:140, 100:130, 1) = 255

obj_rot(*, 1) = [-70.0, 75.0, 0.0]

images(10:140, 70:170, 2) = 255

images(80:90, 170:240, 2) = 150

obj_rot(*, 2) = [-130.0, 215.0, 0.0]

Reconstruct the volume.

vol = RECON3(images, obj_rot, obj_pos, focal, dist, $

  vol_pos, img_ref, img_mag, vol_size, Missing=255B, Mode=(-1))

Display the volume.

shade_volume, vol, 8, v, p

scale3, xrange=[0,40], yrange=[0,40], zrange=[0,40]

image = polyshade(v, p, /t3d, xs=400, ys=400)

tvscl, image

See Also

POLYSHADE, SHADE_VOLUME, VOXEL_PROJ


REDUCE_COLORS

The REDUCE_COLORS procedure reduces the number of colors used in an image by eliminating pixel values without members.

The pixel distribution histogram is obtained and the WHERE function is used to find bins with non-zero values. Next, a lookup table is made where table(old_pixel_value) contains new_pixel_value, and then applied to the image.

This routine is written in the IDL language. Its source code can be found in the file reduce_colors.pro in the lib subdirectory of the IDL distribution.

Calling Sequence:

REDUCE_COLORS, Image, Values

Arguments

Image

On input, a variable that contains the original image array. On output, this variable contains the color-reduced image array, writing over the original.

Values

A named variable that, on output, contains a vector of non-zero pixel values. If Image contains pixel values from 0 to M, Values  will be an M+1 element vector containing the mapping from the old values to the new. Values(i) contains the new color index of old pixel index i.

Example

To reduce the number of colors and display an image with the original color tables R, G, B enter the commands:

REDUCE_COLORS, image, v

TVLCT, R(V), G(V), B(V)

See Also

COLOR_QUAN


REFORM

The REFORM function changes the dimensions of an array without changing the total number of elements. If no dimensions are specified, REFORM returns a copy of Array with all leading dimensions of size 1 removed. If dimensions are specified, the result is given those dimensions. Only the dimensions of Array are changed—the actual data remains unmodified.

Calling Sequence

Result = REFORM(Array, D1, ..., Dn)

Arguments

Array

The array to have its dimensions modified.

Di

The dimensions of the result. The Di arguments can be either a single array containing the new dimensions or a sequence of scalar dimensions. Array must have the same number of elements as specified by the product of the new dimensions.

Keywords

OVERWRITE

Set this keyword to cause the specified dimensions to overwrite the present dimensions of the Array parameter. No data are copied, only the internal array descriptor is changed. The result of the function, in this case, is the Array parameter with its newly-modified dimensions. For example, to change the dimensions of the variable a, without moving data, enter:

a = REFORM(a, n1, n2, /OVERWRITE)

Example

REFORM can be used to remove "degenerate" leading dimensions of size one. Such dimensions can appear when a subarray is extracted from an array with more dimensions. For example

a = INTARR(10,10,10)	a is a 3-dimensional array.

b = a(5,*,*)	Extract a "slice" from a.

HELP, b, REFORM(b)	Use HELP to show what REFORM does.

Executing the above statements produces the output:

B            INT = Array(1, 10, 10)

<Expression> INT = Array(10, 10)

The statements:

b = REFORM(a,200,5)

b = REFORM(a,[200,5])

have identical effect. They create a new array, b, with dimensions of (200, 5), from a.

See Also

REVERSE, ROT,  ROTATE, TRANSPOSE


REGRESS

The REGRESS function performs a multiple linear regression fit and returns an Nterm-element column vector of coefficients.

REGRESS fits the function:

yi  = a0 + a0 x0, i + a 1x1, i + ... + aNterms-1xNterms-1,  i

This routine is written in the IDL language. Its source code can be found in the file regress.pro in the lib subdirectory of the IDL distribution.

Calling Sequence

Result = REGRESS(X, Y, W [, Yfit, A0, Sigma, Ftest, R, Rmul, Chisq])

Arguments

X

An Nterms by Npoints array of independent variable data, where Nterms is the number of coefficients (independent variables) and Npoints is the number of samples.

Y

An Npoints-element vector of dependent variable points.

W

And Npoints-element vector of weights for each equation. For instrumental weighting, set Wi = 1.0/standard_deviation(Yi)^2. For statistical weighting, Wi = 1.0/Yi. For no weighting, set W i = 1.0, and set the RELATIVE_WEIGHT keyword.

Yfit

A named variable that will contain an Npoints-elements vector of calculated values of Y.

A0

A named variable that will contain the constant term.

Sigma

A named variable that will contain the vector of standard deviations for coefficients.

Ftest

A named variable that will contain the value of F for test of fit.

R

A named variable that will contain the vector of linear correlation coefficients.

Rmul

A named variable that will contain the multiple linear correlation coefficient.

Chisq

A named variable that will contain a reduced, weighted chi-squared.

Keywords

RELATIVE_WEIGHT

If this keyword is set, the input weights (the W vector) are assumed to be relative values, and not based on known uncertainties in the Y  vector. Set this keyword in the case of no weighting.

Example

Create an Nterms = 2 by Npoints = 6 array of independent variable data:

X = [[0.0, 0.0], $

     [2.0, 1.0], $

     [2.5, 2.0], $

     [1.0, 3.0], $

     [4.0, 6.0], $

     [7.0, 2.0]]

Create an Npoints-element vector of dependent variable data:

Y = [5.0, 10.0, 9.0, 0.0, 3.0, 27.0]

Create an Npoints-element vector of uniform weights:

W = REPLICATE(1.0, N_ELEMENTS(Y))

Compute the fit using multiple linear regression:

result = REGRESS(X, Y, W, yfit, A0, /relative_weight)

Print the coefficients of the regression model:

PRINT, A0, result(0), result(1)

IDL prints:

      5.00000      4.00000     -3.00000

See Also

CURVEFIT, GAUSSFIT, POLY_FIT, POLYFITW, SFIT, SVDFIT


REPLICATE

The REPLICATE function returns an array with the given dimensions, filled with the scalar value specified as the first parameter.

Calling Sequence

Result = REPLICATE(Value, D1 [, ..., Dn])

Arguments

Value

The scalar value with which to fill the resulting array. The type of the result is the same as that of Value. Value can be of any scalar type, including scalar structures.

Di

The dimensions of the result.

Example

Create D, a 5-element by 5-element array with every element set to the string "IDL" by entering:

D = REPLICATE('IDL', 5, 5)

REPLICATE can also be used to create arrays of structures. For example, the following command creates a structure named "emp" that contains a string name field and a long integer employee ID field:

employee = {emp, NAME:' ', ID:0L}

To create a 10-element array of this structure, enter:

emps = REPLICATE(employee, 10)

See Also

MAKE_ARRAY


RESOLVE_ALL

The RESOLVE_ALL procedure iteratively resolves (by compiling) any uncompiled user-written or library procedures or functions that are called in any already-compiled procedure or function. The process ends when there are no unresolved routines left to compile. If an unresolved procedure or function is not in the IDL search path, this routine exits with an error, and no additional routines are compiled.

RESOLVE_ALL is useful when preparing SAVE/RESTORE files containing all the IDL routines required for an application.

Note: RESOLVE_ALL does not resolve procedures or functions that are called via CALL_PROCEDURE, CALL_FUNCTION, or EXECUTE.

This routine is written in the IDL language. Its source code can be found in the file resolve_all.pro in the lib subdirectory of the IDL distribution.

Calling Sequence

RESOLVE_ALL

Keywords

QUIET

Set this keyword to suppress informational messages.

See Also

RESOLVE_ROUTINE, .COMPILE in "Executive Commands" on page 2-10 of the IDL User's Guide.


RESOLVE_ROUTINE

The RESOLVE_ROUTINE procedure compiles user-written or library procedures or functions, given their names. Routines are compiled even if they are already defined. This procedure is similar to the .COMPILE executive command, but can be invoked within procedures and functions.

Calling Sequence

RESOLVE_ROUTINE, Name

Arguments

Name

A scalar string or string array containing the name or names of the procedures to compile. If  Name contains functions rather than procedures, set the IS_FUNCTION keyword.

Keywords

IS_FUNCTION

Set this keyword to compile functions rather than procedures.

See Also

RESOLVE_ALL, .COMPILE in "Executive Commands" on page 2-10 of the IDL User's Guide.


RESTORE

The RESTORE procedure restores the IDL objects saved in a file by the SAVE procedure. If RESTORE is used in an IDL procedure (i.e., at any level other than the main program level), any variables that are to be restored must be defined prior to the call to RESTORE.

Calling Sequence

RESTORE [, Filename]

Arguments

Filename

A scalar string that contains the name of the file from which the IDL objects should be restored. If not present, the file idlsave.dat is used.

Keywords

FILENAME

The name of the file from which the IDL objects should be restored. If not present, the file idlsave.dat is used. This keyword serves exactly the same purpose as the Filename argument —only one of them needs to be provided.

VERBOSE

Set this keyword to have IDL print an informative message for each restored object.

Example

Suppose that you have saved all the variables from a previous IDL session with the command:

SAVE, /VARIABLES, FILENAME = 'session1.sav'

The variables in the file session1.sav can be restored by entering:

RESTORE, 'session1.sav'

See Also

JOURNAL, SAVE


REVERSE

The REVERSE function reverses the order of rows or columns in a one-, two-, or three-dimensional array.

This routine is written in the IDL language. Its source code can be found in the file reverse.pro in the lib subdirectory of the IDL distribution.

Calling Sequence

Result = REVERSE(Array [, Subscript_Index])

Arguments

Array

The array containing the original data.

Subscript_Index

If this parameter is omitted or 1, the first subscript is reversed (i.e., columns are reversed). Set this parameter to 2 to reverse rows. Set this parameter to 3 to reverse around the third dimension of the array. This argument must be present if Array is three dimensional.

Example

Reverse the order of an array where each element is set to the value of its subscript:

A = [[0,1,2],[3,4,5],[6,7,8]]	Create an array.

PRINT, A	Print the array.

IDL prints:

0       1       2

3       4       5

6       7       8

PRINT, REVERSE(A)	Reverse the columns of A.

IDL prints:

2       1       0

5       4       3

8       7       6

PRINT, REVERSE(A, 2)	Reverse the rows of A.

IDL prints:

6       7       8

3       4       5

0       1       2

See Also

INVERT, REFORM, ROT, ROTATE, SHIFT, TRANSPOSE


REWIND
REWIND (VMS Only)

The REWIND procedure rewinds the tape on the designated IDL tape unit. See the description of the magnetic tape routines in Chapter 17 of the IDL User's Guide.

Calling Sequence

REWIND, Unit

Arguments

Unit

The magnetic tape unit to rewind. Unit must be a number between 0 and 9, and should not be confused with standard file Logical Unit Numbers (LUNs).

See Also

SKIPF (VMS Only), TAPRD (VMS Only)


RIEMANN

The RIEMANN procedure computes the "Riemann sum" (or its inverse) which helps implement the backprojection operator used to reconstruct the cross-section of an object, given projections through the object from multiple directions. This technique is widely used in medical imaging in the fields of computed x-ray tomography, MRI imaging, Positron Emission Tomography (PET), and also has applications in other areas such as seismology and astronomy. The inverse Riemann sum, which evaluates the projections given a slice through an object, is also a discrete approximation to the Radon transform.

Given a matrix A(m,n), which will contain the reconstructed slice; a vector P, containing the ray sums for a given view; and an angle Theta measured in radians from the vertical: the Riemann sum "backprojects" the vector P into A. For each element of A, the value of the closest element of P is summed, leaving the result in A. Bilinear interpolation is an option. All operations are performed in single-precision floating point.

In the reverse operation, the ray sums contained in the view vector, P, are computed given the original slice, A, and Theta. This is sometimes called "front projection".

The Riemann sum can be written:

Sum from i = 0 to M-1 of A(r ⋅ cos( i ⋅ Δ  ­ θ), i ⋅ Δ)

which is the sum of the data along lines through an image with an angle of theta from the vertical.

Calling Sequence

RIEMANN, P, A, Theta

Arguments

P

A k-element floating-point projection vector (or matrix if the ROW keyword is specified). For backprojection (when the BACKPROJECT keyword is set), P contains the ray sums for a single view. For the inverse operation, P should contain zeros on input and will contain the ray sums for the view on output.

A

An m by n floating-point image matrix. For backprojection, A contains the accumulated results. For the inverse operation, A contains the original image. Typically, k should be larger than SQRT(m^2 + n^2), which is the diagonal size of A.

Theta

The angle of the ray sums from the vertical.

Keywords

BACKPROJECT

Set this keyword to perform backprojection in which P is summed into A. If this keyword is not set, the inverse operation occurs and the ray sums are accumulated into P.

BILINEAR

Set this keyword to use bilinear interpolation rather than the default nearest neighbor sampling. Results are more accurate but slower when bilinear interpolation is used.

CENTER

Set this keyword equal to a floating-point number specifying the center of the projection. The default value for CENTER is one-half the number of elements of P.

COR

Set this keyword equal to a two-element floating-point vector specifying the center of rotation in the array A. The default value is [m/2., n/2.], where A is an m by n array.

D

Use this keyword to specify the spacing between elements of P, expressed in the same units as the spacing between elements of A . The default is 1.0.

ROW

Set this keyword to specify the P vector as a given row within a matrix, so that the sinogram array can be used directly without having to extract or insert each row. In this case, P must be an array with a first dimension equal to k, and the value of ROW must be in the range of 0 to the number of vectors of length k in P, minus one.

Example

This example forms a synthetic image in A, computes Nviews equally spaced views, and stores the stacked projections (commonly called the "sinogram") in a matrix PP. It then backprojects the projections into the matrix B, forming the reconstructed slice. In practical use, the projections are convolved with a filter before being backprojected.

N = 100L	Define number of columns in A.

M = 100L	Define number of rows in A.

nviews = 100	Number of views.

K = CEIL(SQRT(N^2 + M^2))	The length of the longest projection. If filtered backprojection is used, 1/2 the length of the convolution kernel must also be added.

A = FLTARR(N, M)	Form original slice.

A(N/2:N/2+5, M/2:M/2+5) = 1.0	Simulate a square object.

pp = FLTARR(K, nviews)	Make array for sinogram.

FOR I=0, NVIEWS-1 DO RIEMANN, pp, A, I * !PI/nviews, ROW=i
Compute each view.

TVSCL, pp	Show sinogram.

B = FLTARR(N,M)	Initial reconstructed image.

FOR I=0, nviews-1 DO $	Do the backprojection for each view.

  RIEMANN, pp, B, I * !PI/nviews, /BACKPROJECT, ROW=i

TVSCL, B	Show reconstructed array.

See Also

VOXEL_PROJ


RK4

The RK4 function uses the fourth-order Runge-Kutta method to advance a solution to a system of ordinary differential equations one time-step H, given values for the variables Y and their derivatives Dydx  known at X.

RK4 is based on the routine rk4 described in section 16.1 of Numerical Recipes in C: The Art of Scientific Computing (Second Edition), published by Cambridge University Press, and is used by permission.

Calling Sequence

Result = RK4(Y, Dydx, X, H, Derivs)

Arguments

Y

A vector of values for Y at X

Dydx

A vector of derivatives for Y at X.

X

A scalar value for the initial condition.

H

A scalar value giving interval length or step size.

Derivs

A scalar string specifying the name of a user-supplied IDL function that calculates the values of the derivatives Dydx at X. This function must accept two arguments: A scalar floating value X , and one n-element vector Y. It must return an n-element vector result.

For example, suppose the values of the derivatives are defined by the following relations:

dy 0 / dx = ­0.5y0,        dy1 / dx = 4.0 ­ 0.3y1 ­ 0.1y0

We can write a function DIFFERENTIAL to express these relationships in the IDL language:

FUNCTION differential, X, Y

  RETURN, [-0.5 * Y(0), 4.0 - 0.3 * Y(1) - 0.1 * Y(0)]

END

Keywords

DOUBLE

Set this keyword to force the computation to be done in double-precision arithmetic.

Example

To integrate the example system of differential equations for one time step, H:

H = 0.5	Define the step size.

X = 0.0	Define an initial X value.

Y = [4.0, 6.0]	Define initial Y values.

dydx = DIFFERENTIAL(X,Y)	Calculate the initial derivative values.

result = RK4(Y, dydx, X, H, 'differential')

Integrate over the interval (0, 0.5).

PRINT, result	Print the result.

IDL prints:

 3.11523  6.85767

This is the exact solution vector to five-decimal precision.

See Also

BROYDEN, NEWTON


ROBERTS

The ROBERTS function returns an approximation to the Roberts edge enhancement operator for images: Ga(j,k) = Fj, k ­ Fj + 1, k + 1 + Fj, k + 1 ­ Fj + 1, k

which is a simple, two-dimensional differencing method for edge-sharpening and isolation. The result of this function is a two-dimensional array of integer type, with the same dimensions as Image.

Calling Sequence

Result = ROBERTS(Image)

Arguments

Image

The two-dimensional array containing the image to which edge enhancement is applied.

Example

If the variable IM contains a two-dimensional image array, a Roberts sharpened version of IM can be displayed with the command:

TVSCL, ROBERTS(IM)

See Also

SOBEL


ROT

The ROT function rotates an image by an arbitrary amount. At the same time, it can magnify, demagnify, and/or translate an image. Note that if you want to rotate an array by a multiple of 90 degrees, you should use the ROTATE function for faster results.

This routine is written in the IDL language. Its source code can be found in the file rot.pro in the lib subdirectory of the IDL distribution.

Calling Sequence

Result = ROT(A, Angle, [Mag, X0, Y0])

Arguments

A

The image array to be rotated. This array can be of any type, but must have two dimensions. The output image has the same dimensions and data type of the input image.

ANGLE

Angle of rotation in degrees clockwise.

MAG

An optional magnification factor. A value of 1.0 results in no change. A value greater than one performs magnification and a value less than one performs demagnification.

X0

X subscript for the center of rotation. If omitted, X0 equals the number of columns in the image divided by 2.

Y0

Y subscript for the center of rotation. If omitted, Y0 equals the number of rows in the image divided by 2.

Keywords

INTERP

Set this keyword to use bilinear interpolation. The default is to use nearest neighbor sampling.

CUBIC

Set this keyword to use "cubic convolution" interpolation, a more accurate, but more time-consuming, form of interpolation.

MISSING

Set this keyword to a value to be substituted for pixels in the output image that map outside the input image.

PIVOT

Set this keyword to cause the image to pivot around the point (X0, Y0) so that this point maps into the same point in the output image. By default, the point (X0, Y0 ) in the input image is mapped into the center of the output image.

Example

A = BYTSCL(DIST(256))	Create a byte image.

TV, A	Display it.

B = ROT(A, 33, 1.5, /INTERP)	Rotate the image 33 degrees, magnify it 15 times, and use bilinear interpolation to make the output look nice.

TV, B	Display the rotated image.

See Also

ROTATE


ROTATE

The ROTATE function returns a rotated and/or transposed copy of Array. ROTATE can only rotate arrays in multiples of 90 degrees. To rotate by amounts other than multiples of 90 degrees, use the ROT function. Note, however, that ROTATE is more efficient.

ROTATE can also be used to reverse the order of elements in vectors. For example, to reverse the order of elements in the vector X, use the expression ROTATE(X,2). If X = [0,1,2,3] then ROTATE(X,2)yields the resulting array, [3,2,1,0].

Transposition is performed before rotation. Rotations are viewed with the first row at the top.

Calling Sequence

Result = ROTATE(Array, Direction)

Arguments

Array

The array to be rotated. Array can have only one or two dimensions. The result has the same type as Array. The dimensions of the result are the same as those of Array if Direction is equal to 0 or 2. The dimensions are transposed if the direction is 4 or greater.

Direction

Direction specifies the operation to be performed as follows:

Direction	Transpose?	Rotation Counterclockwise	X1	Y1
0	No	None	X0	Y0
1	No	90°	-Y0	X0
2	No	180°	-X0	-Y0
3	No	270°	Y0	-X0
4	Yes	None	Y0	X0
5	Yes	90°	-X0	Y0
6	Yes	180°	-Y0	-X0
7	Yes	270°	X0	-Y0
Table 1.14 Rotation Directions

In the table above, (X0, Y0) are the original subscripts, and (X1, Y1) are the subscripts of the resulting array. The notation -Y0 indicates a reversal of the Y axis, Y1 = Ny - Y0 - 1. Direction is taken modulo 8, so a rotation of -1 is the same as 7, 9 is the same as 1, etc.

Example

Create and display a wedge image by entering:

F = REPLICATE(1, 256) # FINDGEN(256) & TVSCL, F

To display the image rotated 90 degrees counterclockwise, enter:

TVSCL, ROTATE(F, 1)

See Also

ROT, TRANSPOSE


ROUND

The ROUND function returns the integer closest to its argument. This value is returned as a longword integer with the same structure as the input argument.

Calling Sequence

Result = ROUND(X)

Arguments

X

The value for which the ROUND function is to be evaluated. This value can be single- or double-precision, real or complex floating-point. ROUND returns a longword integer with the same structure as X. Note that only the real part of a complex argument is rounded and returned.

Example

To print the rounded values of a 2-element vector, enter:

PRINT, ROUND([5.1, 5.9])

IDL prints:

     5      6

See Also

CEIL, COMPLEXROUND, FLOOR


RS_TEST

The RS_TEST function tests the hypothesis that two sample populations X and Y have the same mean of distribution against the hypothesis that they differ. X and Y may be of different lengths. The result is a two-element vector containing the nearly-normal test statistic Z and the one-tailed probability of obtaining a value of Z or greater. This type of test is often referred to as the "Wilcoxon Rank-Sum Test" or the "Mann-Whitney U-Test."

The Mann-Whitney statistics for X and Y are defined as follows:

where Nx  and Ny are the number of elements in  X and Y, respectively, and Wx and Wy are the rank sums for X and Y, respectively. The test statistic Z, which closely follows a normal distribution for sample sizes exceeding 10 elements, is defined as follows:

This routine is written in the IDL language. Its source code can be found in the file rs_test.pro in the lib subdirectory of the IDL distribution.

Calling Sequence

Result = RS_TEST(X, Y)

Arguments

X

An n-element integer, single-, or double-precision floating-point vector.

Y

An m-element integer, single-, or double-precision floating-point vector.

Keywords

UX

Set this keyword to a named variable that will contain the Mann-Whitney statistic for X.

UY

Set this keyword to a named variable that will contain the Mann-Whitney statistic for Y.

Example

Define two sample populations.

X = [-14, 3, 1, -16, -21, 7, -7, -13, -22, -17, -14, -8, $

       7, -18, -13, -9, -22, -25, -24, -18, -13, -13, -18, -5]

Y = [-18, -9, -16, -14, -3, -9, -16, 10, -11, -3, -13, $

     -21, -2, -11, -16, -12, -13, -6, -9, -7, -11, -9]

Test the hypothesis that two sample populations, {xi, yi}, have the same mean of distribution against the hypothesis that they differ at the 0.05 significance level.

PRINT, RS_TEST(X, Y, UX = ux, UY = uy)

IDL prints:

[1.45134, 0.0733429]

Print the Mann-Whitney statistics:

PRINT, 'Mann-Whitney Statistics: Ux = ', ux, ', Uy = ', uy

IDL prints:

Mann-Whitney Statistics: Ux = 330.000, Uy = 198.000

The computed probability (0.0733429) is greater than the 0.05 significance level and therefore we do not reject the hypothesis that X and Y have the same mean of distribution.

See Also

FV_TEST, KW_TEST, S_TEST, TM_TEST


RSTRPOS

The RSTRPOS function finds the last occurrence of a substring within an object string (the STRPOS function finds the first occurrence of a substring). If the substring is found in the expression, RSTRPOS returns the character position of the match, otherwise it returns -1.

This routine is written in the IDL language. Its source code can be found in the file rstrpos.pro in the lib subdirectory of the IDL distribution.

Calling Sequence

Result = RSTRPOS(Expression, Search_String [, Pos])

Arguments

Expression

The expression string in which to search for the substring.

Search_String

The substring to be searched for within Expression.

Pos

The character position before which the search is begun. If Pos is omitted, the search begins at the last character of Expression .

Example

exp = 'Holy smokes, Batman!'	Define the expression.

pos = RSTRPOS(exp, 'smokes')	Find the position of a substring.

PRINT, pos	Print the substring's position. IDL prints 5, so substring begins at position 5 (the sixth character).

See Also

STRPOS


S_TEST

The S_TEST function tests the hypothesis that two sample populations X and Y have the same mean of distribution against the hypothesis that they differ. The result is a two-element vector containing the maximum number of signed differences between corresponding pairs of xi and  yi and its one-tailed significance. This type of test is often referred to as the "Sign Test."

This routine is written in the IDL language. Its source code can be found in the file s_test.pro in the lib subdirectory of the IDL distribution.

Calling Sequence

Result = S_TEST(X, Y)

Arguments

X

An n-element integer, single-, or double-precision floating-point vector.

Y

An n-element integer, single-, or double-precision floating-point vector.

Keywords

ZDIFF

Set this keyword to a named variable that will contain the number of differences between corresponding pairs of xi and yi resulting in zero. Paired data resulting in a difference of zero are excluded from the ranking and the sample size is correspondingly reduced.

Example

Define two n-element sample populations.

X = [47, 56, 54, 49, 36, 48, 51, 38, 61, 49, 56, 52]

Y = [71, 63, 45, 64, 50, 55, 42, 46, 53, 57, 75, 60]

Test the hypothesis that the two sample populations have the same mean of distribution against the hypothesis that they differ at the 0.05 significance level.

PRINT, S_TEST(X, Y, ZDIFF = zdiff)

IDL prints:

[9.00000, 0.0729981]

The computed probability (0.0729981) is greater than the 0.05 significance level and therefore we do not reject the hypothesis that X and Y have the same mean of distribution.

See Also

FV_TEST, KW_TEST, MD_TEST, RS_TEST, TM_TEST


SAVE

The SAVE procedure saves variables and system variables in a file for later recovery by RESTORE.

Calling Sequence

SAVE  [, Var1, ..., Varn]

Arguments

Varn

Optional named variables that are to be saved.

Keywords

ALL

Set this keyword to save all aspects of the current IDL session (common blocks, system variables, and local variables).

COMM

Set this keyword to save all main level common block definitions. Note that setting this keyword does not cause the contents of the common block to be saved unless the VARIABLES keyword is also set.

FILENAME

A string containing the name of the file into which the IDL objects should be saved. If this keyword is not specified, the file idlsave.dat is used.

ROUTINES

Set this keyword to save user defined procedures and functions in a machine independent, binary form. If parameters are present, they must be strings containing the names of the procedures and/or functions to be saved. If no parameters are present, all compiled routines are saved. If you are using VMS, see the XDR keyword below. Warning: save files containing routines are not guaranteed to be compatible between successive versions of IDL.

SYSTEM_VARIABLES

Set this keyword to save the current state of all system variables.

Caution: Saving system variables is not recommended, as the structure may change between releases, making the SAVE/RESTORE files incompatible.

VARIABLES

Set this keyword to save all variables in the current program unit. This option is the default.

VERBOSE

Set this keyword to print an informative message for each saved object.

XDR

Set this keyword to save the file in a portable format using XDR (eXternal Data Representation). Under operating systems other than VMS, XDR is the only supported format, and this keyword is unnecessary. Under VMS, the default is a VAX-specific format which is more efficient to process. Use XDR under VMS to interchange data with other versions of IDL.

Example

Save the status of all currently-defined variables in the file variables1.dat by entering:

SAVE, /VARIABLES, FILENAME = 'variables1.dat'

The variables can be restored with the RESTORE procedure. Save the user procedures MYPROC and MYFUN:

SAVE, /ROUTINES, 'MYPROC', 'MYFUN'

See Also

JOURNAL, RESOLVE_ALL, RESTORE


SCALE3

The SCALE3 procedure sets up transformation and scaling parameters for basic 3D viewing. This procedure is similar to SURFR and SCALE3D, except that the data ranges must be specified and the scaling does not vary with rotation. Results are stored in the system variables !P.T, !X.S, !Y.S, and !Z.S.

This routine is written in the IDL language. Its source code can be found in the file scale3.pro in the lib subdirectory of the IDL distribution.

Calling Sequence

SCALE3

Keywords

XRANGE

A two-element vector containing the minimum and maximum X values. If omitted, the X-axis scaling remains unchanged.

YRANGE

A two-element vector containing the minimum and maximum Y values. If omitted, the Y-axis scaling remains unchanged.

ZRANGE

A two-element vector containing the minimum and maximum Z values. If omitted, the Z-axis scaling remains unchanged.

AX

Angle of rotation about the X axis. The default is 30 degrees.

AZ

Angle of rotation about the Z axis. The default is 30 degrees.

Example

Set up a 3D transformation where the data range is 0 to 20 for each of the 3 axes and the viewing area is rotated 20 degrees about the X axis and 55 degrees about the Z axis:

SCALE3, XRANGE=[0, 20], YRANGE=[0, 20], ZRANGE=[0, 20], $

        AX=20, AZ=55

See Also

SCALE3D, SURFR, T3D


SCALE3D

The SCALE3D procedure scales the 3D unit cube (a cube with the length of each side equal to 1) into the viewing area. Eight data points are created at the vertices of the 3D unit cube. The vertices are then transformed by the value of the system variable !P.T. The system is translated to bring the minimum (x,y,z) point to the origin, and then scaled to make each coordinate's maximum value equal to 1. The !P.T system variable is modified as a result.

This routine is written in the IDL language. Its source code can be found in the file scale3D.pro in the lib subdirectory of the IDL distribution.

Calling Sequence

SCALE3D

See Also

SCALE3, SURFR, T3D


SEARCH2D

The SEARCH2D function finds "objects" or regions of similar data values within a two-dimensional array. Given a starting location and a range of values to search for, SEARCH2D finds all the cells within the array that are within the specified range and have some path of connectivity through these cells to the starting location. In addition to searching for cells within a global range of data values, SEARCH2D can also search for adjacent cells whose values deviate from their neighbors within specified tolerances.

SEARCH2D returns a longword array that contains a list of the array subscripts that define the located object or region. The original X and Y indices of the array subscripts returned by SEARCH2D can be found with the following IDL code:

index_y = Result / (SIZE(Array))(1)

index_x = Result - (index_y * (SIZE(Array))(1))

where Result is the array returned by SEARCH2D and Array is the original input array. The object within Array can be subscripted as Array(Region) or Array(index_x, index_y).

This routine is written in the IDL language. Its source code can be found in the file search2d.pro in the lib subdirectory of the IDL distribution.

Calling Sequence

Result = SEARCH2D(Array, Xpos, Ypos, Min_Val, Max_Val)

Arguments

Array

A two-dimensional array, of any data type, to be searched.

Xpos

The X coordinate (dimension 0 of Array) of the starting location.

Ypos

The Y coordinate (dimension 1 of Array) of the starting location.

Min_Val

The minimum data value for which to search. All array subscripts of all cells that are connected to the starting cell, and have a value between Min_Val and Max_Val (inclusive) are returned.

Max_Val

The maximum data value for which to search.

Keywords

DECREASE

This keyword and the INCREASE keyword allow you to compensate for changing intensities of data values within an object. An edge-enhanced copy of Array is made and compared to the orginal array if this keyword is set. When DECREASE or INCREASE is set, any adjacent cells are found if their corresponding data values in the edge enhanced array are greater than DECREASE and less than INCREASE. In any case, the adjacent cells will never be selected if their data values are not between Min_Val and Max_Val. The default for this keyword is 0.0 if INCREASE is specified.

INCREASE

This keyword and the DECREASE keyword allow you to compensate for changing intensities of data values within an object. An edge-enhanced copy of Array is made and compared to the orginal array if this keyword is set. When DECREASE or INCREASE is set, any adjacent cells are found if their corresponding data values in the edge enhanced array are greater than DECREASE and less than INCREASE. In any case, the adjacent cells will never be selected if their data values are not between Min_Val and Max_Val. The default for this keyword is 0.0 if DECREASE is specified.

LPF_BAND

Set this keyword to an integer value of 3 or greater to perform low-pass filtering on the edge-enhanced array. The value of LPF_BAND is used as the width of the smoothing window. This keyword is only effective when the DECREASE or INCREASE keywords are also specified. The default is no smoothing.

DIAGONAL

Set this keyword to cause SEARCH2D to find cells meeting the search criteria whose surrounding squares share a common corner. Normally, cells are considered adjacent only when squares surrounding the cells share a common edge. Setting this option requires more memory and execution time.

Example

Find all the indices corresponding to an object in an image:

img = FLTARR(512, 512) 	Create an image with different valued regions.

img(3:503, 9:488) = 0.7

img(37:455, 18:438) = 0.5

img(144:388, 90:400) = 0.7

img(200:301, 1:255) = 1.0

img(155:193, 333:387) = 0.3

TVSCL, img	Display the image.

region = SEARCH2D(img, 175, 300, 0.6, 0.8, /DIAGONAL)
Search for an object starting at (175, 300) whose data values are between (0.6) and (0.8).

img = BYTSCL(img, TOP=127B)	Scale the background cells into the range 0 to 127.

img(Region) = 255B	Highlight the object region by setting it to 255.

TVSCL, img	Display the array with the highlighted object in it.

See Also

SEARCH3D


SEARCH3D

The SEARCH3D function finds "objects" or regions of similar data values within a 3D array of data. Given a starting location and a range of values to search for, SEARCH3D finds all the cells within the volume that are within the specified range of values and have some path of connectivity through these cells to the starting location. In addition to searching for cells within a global range of data values, SEARCH3D can also search for adjacent cells whose values deviate from their neighbors within specified tolerances.

SEARCH3D returns a longword array that contains a list of the array subscripts that define the selected object or region. The original X and Y indices of the array subscripts returned by SEARCH3D can be found with the following IDL code:

S = SIZE(Array)

index_z = Result / (S(1) * S(2))

index_y = (Result - (index_z * S(1) * S(2))) / S(1)

index_x = (Result - (index_z * S(1) * S(2))) - (index_y * S(1))

where Result is the array returned by SEARCH3D and Array is the original input volume. The object within Array can be subscripted as Array(Region) or Array(index_x, index_y, index_z).

This routine is written in the IDL language. Its source code can be found in the file search3d.pro in the lib subdirectory of the IDL distribution.

Calling Sequence

Result = SEARCH3D(Array, Xpos, Ypos, Zpos, Min_Val, Max_Val)

Arguments

Array

The three-dimensional array, of any data type except string, to be searched.

Xpos

The X coordinate (dimension 0 or Array) of the starting location.

Ypos

The Y coordinate (dimension 1 of Array) of the starting location.

Zpos

The Z coordinate (dimension 2 of Array) of the starting location.

Min_Val

The minimum data value for which to search. All array subscripts of all the cells that are connected to the starting cell, and have a value between Min_Val  and Max_Val (inclusive) are returned.

Max_Val

The maximum data value for which to search.

Keywords

DECREASE

This keyword and the INCREASE keyword allow you to compensate for changing intensities of data values within an object. An edge-enhanced copy of Array is made and compared to the orginal array if this keyword is set. When DECREASE or INCREASE is set, any adjacent cells are found if their corresponding data values in the edge enhanced array are greater than DECREASE and less than INCREASE. In any case, the adjacent cells will never be selected if their data values are not between Min_Val and Max_Val. The default for this keyword is 0.0 if INCREASE is specified.

INCREASE

This keyword and the DECREASE keyword allow you to compensate for changing intensities of data values within an object. An edge-enhanced copy of Array is made and compared to the orginal array if this keyword is set. When DECREASE or INCREASE is set, any adjacent cells are found if their corresponding data values in the edge enhanced array are greater than DECREASE and less than INCREASE. In any case, the adjacent cells will never be selected if their data values are not between Min_Val and Max_Val. The default for this keyword is 0.0 if DECREASE is specified.

LPF_BAND

Set this keyword to an integer value of 3 or greater to perform low-pass filtering on the edge-enhanced array. The value of LPF_BAND is used as the width of the smoothing window. This keyword is only effective when the DECREASE or INCREASE keywords are also specified. The default is no smoothing.

DIAGONAL

Set this keyword to cause SEARCH3D to find cells meeting the search criteria whose surrounding cubes share a common corner or edge. Normally, cells are considered adjacent only when cubes surrounding the cells share a common edge. Setting this option requires more memory and execution time.

Example

Find all the indices corresponding to an object contained in a 3D array:

vol = RANDOMU(s, 40, 40, 40)	Create some data.

vol(3:13, 1:15, 17:33) = 1.3

vol(15:25, 5:25, 15:25) = 0.2

vol(5:30,17:38,7:28) = 1.3

vol(9:23, 16:27, 7:33) = 1.5

region = SEARCH3D(vol, 6, 22, 16, 1.2, 1.4, /DIAGONAL)
Search for an object starting at (6, 22, 16) whose data values are between (1.2) and (1.4).

vol = BYTSCL(vol, TOP=127B)	Scale the background cells into the range 0 to 127.

vol(Region) = 255B	Highlight the object region by setting it to 255.

WINDOW, 0, XSIZE=640, YSIZE=512, RETAIN=2

CREATE_VIEW, XMAX=39, YMAX=39, ZMAX=39, AX=(-30), AZ=30, ZOOM=0.8
Set up a 3-D view.

TVSCL, PROJECT_VOL(vol, 64, 64, 40, DEPTH_Q=0.4)
Display the volume with the highlighted object in it.

See Also

SEARCH2D


SET_PLOT

The SET_PLOT procedure sets the output device used by the IDL graphics procedures. Keyword parameters control how the color tables are transferred to the newly selected graphics device. SET_PLOT performs the following actions:

•	It sets the read-only system variable !D to reflect the configuration of the new device.

•	It sets the default color !P.COLOR to the maximum color index minus one or, in the case of devices with white backgrounds, such as PostScript, to 0 (black).

•	If the COPY keyword is set, the device color tables are copied directly from IDL's internal color tables. If the new device's color tables contain more indices than those of the old device, the new device's tables are not completely filled.

•	If the INTERPOLATE keyword is set, the internal color tables are interpolated to fill the range of the new device.

•	It sets the clipping rectangle to the entire device surface.

Warnings: After calling SET_PLOT to change graphics devices, the scaling contained in the axis structures !X, !Y, and !Z is invalid. Any routines that rely on data coordinates should not be called until a new data coordinate system has been established. Be careful when switching devices as the number of color indices frequently differs between devices. When in doubt, reload the color table of the new device explicitly. See "Color Tables" on page 16-7 of the IDL User's Guide.

Calling Sequence

SET_PLOT, Device

Arguments

Device

A scalar string containing the name of the device to use. The case of Device is ignored by IDL. See Table 3.1 on page 3-1 of the IDL Reference Guide for a list of device names.

Keywords

COPY

Set this keyword to copy the device's color table from the internal color table, preserving the current color mapping. The default is not to load the color table upon selection.

Warning: Unless this keyword is set, IDL's internal color tables will incorrectly reflect the state of the device's color tables until they are reloaded by TVLCT or the LOADCT procedure. Assuming that the previously-selected device's color table contains  M elements, and the new device's color table contains  N elements, then the minimum of M and N elements are loaded.

INTERPOLATE

Set this keyword to indicate that the current contents of the internal color table should be interpolated to cover the range of the newly-selected device. Otherwise, the internal color tables are not changed.

Example

Change the IDL graphics device to PostScript by entering:

SET_PLOT, 'PS'

After changing the plotting device, all graphics commands are sent to that device until changed again by another use of the SET_PLOT routine.

See Also

DEVICE


SET_SHADING

The SET_SHADING procedure modifies the light source shading parameters that affect the output of SHADE_SURF and POLYSHADE. Parameters can be changed to control the light-source direction, shading method, and the rejection of hidden surfaces. SET_SHADING first resets the shading parameters to their default values. The parameter values specified in the call then overwrite the default values. To reset all parameters to their default values, simply call this procedure with no parameters.

Calling Sequence

SET_SHADING

Arguments

None.

Keywords

GOURAUD

This keyword controls the method of shading the surface polygons by the POLYSHADE procedure. The SHADE_SURF procedure always uses the Gouraud method. Set this keyword to a nonzero value (the default), to use Gouraud shading. Set this keyword to zero to shade each polygon with a constant intensity.

Gouraud shading interpolates intensities from each vertex along each edge. Then, when scan converting the polygons, the shading is interpolated along each scan line from the edge intensities. Gouraud shading is slower than constant shading but usually results in a more realistic appearance.

LIGHT

A three-element vector that specifies the direction of the light source. The default light source vector is [0,0,1], with the light rays parallel to the Z axis.

REJECT

Set this keyword (the default) to reject polygons as being hidden if their vertices are ordered in a clockwise direction as seen by the viewer. This keyword should always be set when rendering enclosed solids whose original vertex lists are in counterclockwise order. When rendering surfaces that are not closed or are not in counterclockwise order this keyword can be set to zero although shading anomalies at boundaries between visible and hidden surfaces may occur.

VALUES

A two-element array that specifies the range of pixel values (color indices) to use. The first element is the color index for the darkest pixel. The second element is the color index for the brightest pixel. For example, to render a shaded surface with the darkest shade set to pixel value 100 and the brightest value set to 150, use the commands:

SET_SHADING, VALUES=[100, 150]

SHADE_SURF, dataset

Example

Change the light source so that the light rays are parallel to the X axis:

SET_SHADING, LIGHT = [1, 0, 0]

See Also

POLYSHADE, SHADE_SURF


SET_SYMBOL
SET_SYMBOL (VMS Only)

The SET_SYMBOL procedure defines a DCL (Digital Command Language) interpreter symbol for the current process.

Calling Sequence

SET_SYMBOL, Name, Value

Arguments

Name

A scalar string containing the name of the symbol to be defined.

Value

A scalar string containing the value with which Name is defined.

Keywords

TYPE

Indicates the table into which Name will be defined. Setting TYPE to 1 specifies the local symbol table, while a value of 2 specifies the global symbol table. The default is the local table.

See Also

DELLOG (VMS Only), DELETE_SYMBOL (VMS Only), SETLOG (VMS Only)


SETENV
SETENV (Unix and Windows Only)

The SETENV procedure adds or changes an environment string in the process environment.

Calling Sequence

SETENV, Environment_Expression

Arguments

Environment_Expression

A scalar string containing an environment expression to be added to the environment.

Example

Change the current shell variable by entering:

SETENV,'SHELL=/bin/sh'

See Also

GETENV


SETLOG
SETLOG (VMS Only)

The SETLOG procedure defines a logical name.

Calling Sequence

SETLOG, Lognam, Value

Arguments

Lognam

A scalar string containing the name of the logical to be defined.

Value

A string containing the value to which the logical will be set. If Value  is a string array, Lognam is defined as a multi-valued logical where each element of Value defines one of the equivalence strings.

Keywords

CONCEALED

If this keyword is set, RMS (VMS Record Management Services) interprets the equivalence name as a device name.

CONFINE

If this keyword is set, the logical name is not copied from the IDL process to its spawned subprocesses.

NO_ALIAS

If this keyword is set, the logical name cannot be duplicated in the same logical table at an outer access mode. If another logical name with the same name already exists at an outer access mode, it is deleted. See the VMS System Services Manual for additional information on logical names and access modes.

TABLE

A scalar string containing the name of the logical table into which Lognam will be entered. If TABLE is not specified, LNM$PROCESS_TABLE is used.

TERMINAL

If this keyword is set, when attempting to translate the logical, further iterative logical name translation on the equivalence name is not to be performed.

See Also

DELETE_SYMBOL (VMS Only), DELLOG (VMS Only), SET_SYMBOL (VMS Only)


SETUP_KEYS

The SETUP_KEYS procedure sets function keys for use with IDL.

SETUP_KEYS uses DEFINE_KEY (called via modular procedures) to enter the keys for known keyboards (Sun3, DEC VT200, HP, Mips, PSTERM, SGI). The new mappings for the keys can be viewed using the command HELP, /KEYS.

For the HP keyboard, the upper right-hand group of four keys (at the same height as the function keys) are called "BLANK1" through "BLANK4", since they have no written labels. Keys defined to have labels beginning with a capital "K" belong to the numeric keypad group. For example, "K9" refers to keypad key "9".

Although the HP 9000 series 300 can create both xterm and hpterm windows, IDL supports only user-definable key definitions in xterm windows—hpterm windows use non-standard escape sequences which IDL does not attempt to handle.

This routine is written in the IDL language. Its source code can be found in the file setup_keys.pro in the lib subdirectory of the IDL distribution.

Calling Sequence

SETUP_KEYS

Keywords

NOTE: If no keyword is specified, SETUP_KEYS uses !VERSION to determine the type of machine running IDL. It assumes that the keyboard involved is of the same type (this assumption is correct).

EIGHTBIT

Set this keyword to use the 8-bit versions of the escape codes (instead of the default 7-bit) when establishing VT200 function key definitions.

SUN

Set this keyword to establish function key definitions for a Sun3 keyboard.

VT200

Set this keyword to establish function key definitions for a DEC VT200 keyboard.

HP9000

Set this keyword to establish function key definitions for an HP 9000 series 300 keyboard. Although the HP 9000 series 300 supports both xterm and hpterm windows, IDL supports only user-definable key definitions in xterm windows— hpterm windows use non-standard escape sequences which IDL does not attempt to handle.

MIPS

Set this keyword to establish function key definitions for a Mips RS series keyboard.

PSTERM

Set this keyword to establish function key definitions for PSTERMS such as those found on the Sun SPARC workstations.

SGI

Set this keyword to establish function key definitions for SGI keyboards.

APP_KEYPAD

Set this keyword to define escape sequences for the group of keys in the numeric keypad, enabling these keys to be programmed within IDL.

NUM_KEYPAD

Set this keyword to disable programmability of the numeric keypad.

See Also

DEFINE_KEY


SFIT

The SFIT function determines a polynomial fit to a surface and returns a fitted array. The function fitted is:

This routine is written in the IDL language. Its source code can be found in the file sfit.pro in the lib subdirectory of the IDL distribution.

Calling Sequence

Result = SFIT(Data, Degree)

Arguments

Data

The two-dimensional array of data to fit. The sizes of the dimensions may be unequal.

Degree

The maximum degree of fit (in one dimension).

Keywords

KX

Set this keyword to a named variable that will contain the array of coefficients for a polynomial function of x and y to fit data. This parameter is returned as a Degree+1 by Degree+1 array.

Example

Create a grid from zero to six radians in the X and Y directions:

X = (FINDGEN(61)/10) # REPLICATE(1,61)

Y = TRANSPOSE(X)

Evaluate a function at each point:

F = -SIN(2*X) + COS(Y/2)

Compute a sixth-degree polynomial fit to the function data:

result = SFIT(F, 6)

Display the

 original function on the left and the fitted function on the right, using identical axis scaling:

WINDOW, XSIZE = 800, YSIZE = 400

!P.MULTI = [0, 2, 1]	Set up side-by-side plots.

!P.BACKGROUND = 255	Set background color to white.

!P.COLOR = 0	Set plot color to black.

SURFACE, F, X, Y, ZRANGE = [-3, 3], ZSTYLE = 1

SURFACE, result, X, Y

See Also

CURVEFIT, GAUSSFIT, POLY_FIT, POLYFITW, REGRESS, SVDFIT


SHADE_SURF

The SHADE_SURF procedure creates a shaded-surface representation of a regular or nearly-regular gridded surface with shading from either a light source model or from a user-specified array of intensities. This procedure and its parameters are similar to SURFACE. Given a regular or near-regular grid of elevations it produces a shaded-surface representation of the data with hidden surfaces removed.

The SET_SHADING procedure can be used to control the direction of the light source and other shading parameters.

If the graphics output device has scalable pixels (e.g., PostScript), the output image is scaled so that its largest dimension is less than or equal to 512 (unless the PIXELS keyword is set to some other value). This default resolution may not be high enough for some datasets. If your output looks jagged or "stair-stepped", try specifying a larger value with the PIXELS keyword.

When outputting to a device that prints black on a white background, (e.g., PostScript), pixels that contain the background color index of 0 are set to white.

Restrictions

If the  (X, Y) grid is not regular or nearly regular, errors in hidden line removal will occur. If the T3D keyword is set, the 3D to 2D transformation matrix contained in !P.T must project the Z axis to a line parallel to the device Y axis, or errors will occur. The SHADE_SURF_IRR procedure can be used to render many datasets that do not meet these requirements. Irregularly-gridded data can also be made interpolated to a regular grid using the TRIGRID and TRIANGULATE routines.

Calling Sequence

SHADE_SURF, Z [, X, Y]

Arguments

Z

A two-dimensional array that contains the values that make up the surface. For details, see "SURFACE" on page 1-869.

This argument is converted to single-precision floating-point before plotting. Plots created with SHADE_SURF are limited to the range and precision of single-precision floating-point values.

X

An optional vector or two-dimensional array that specifies the X coordinates of the grid. For details, see "SURFACE" on page 1-869.

Y

An optional vector or two-dimensional array that specifies the Y coordinates of each elevation.

Keywords

AX

This keyword specifies the angle of rotation, about the X axis, in degrees towards the viewer. This keyword is effective only if !P.T3D and the T3D keyword are not set. If !P.T3D is set, the three-dimensional to two-dimensional transformation used by SURFACE is contained in the 4 by 4 array !P.T.

The surface represented by the two-dimensional array is first rotated, AZ (see below) degrees about the Z axis, then by AX degrees about the X axis, tilting the surface towards the viewer (AX > 0), or away from the viewer.

The AX and AZ keyword parameters default to +30 degrees if omitted.

The three-dimensional to two-dimensional transformation represented by AX and AZ, can be saved in !P.T by including the SAVE keyword.

AZ

This keyword specifies the counterclockwise angle of rotation about the Z axis. This keyword is effective only if !P.T3D is not set. The order of rotation is AZ first, then AX.

IMAGE

A named variable into which an image containing the shaded surface is stored. If this keyword is omitted, the image is displayed but not saved.

MAX_VALUE

The maximum value to be plotted. If this keyword is present, data values greater than the value of MAX_VALUE are treated as missing and are not plotted. Note that the IEEE floating-point value NaN is also treated as missing data. (See "Special Floating-Point Values" on page 11-9 of the IDL User's Guide for more information on IEEE floating-point values.)

MIN_VALUE

The minimum value to be plotted. If this keyword is present, data values less than the value of MIN_VALUE are treated as missing and are not plotted. Note that the IEEE floating-point value NaN is also treated as missing data. (See "Special Floating-Point Values" on page 11-9 of the IDL User's Guide for more information on IEEE floating-point values.)

PIXELS

Set this keyword to a scalar value that specifies the maximum size of the image dimensions, in pixels. PIXELS only applies when the output device uses scalable pixels (e.g., the PostScript device). Use this keyword to increase the resolution of the output image if the default looks jagged or "stair-stepped".

SAVE

Set this keyword to save the 3D to 2D transformation matrix established by SHADE_SURF in the system variable field !P.T. Use this keyword when combining the output of SHADE_SURF with the output of other routines in the same plot.

SHADES

An array expression, of the same dimensions as Z, that contains the color index at each point. The shading of each pixel is interpolated from the surrounding SHADE values. If this parameter is omitted, light-source shading is used. For most displays, this parameter should be scaled into the range of bytes.

XLOG

Set this keyword to specify a logarithmic X axis.

YLOG

Set this keyword to specify a logarithmic Y axis.

Graphics Keywords Accepted

See Chapter 2, "Graphics Keywords and System Variables", for the description of graphics and plotting keywords not listed above. CHARSIZE CHARTHICK  CLIP COLOR DATA DEVICE FONT NOCLIP NODATA NOERASE NORMAL POSITION  SUBTITLE T3D  THICK TICKLEN TITLE [XYZ]CHARSIZE [XYZ]GRIDSTYLE [XYZ]MARGIN [XYZ]MINOR [XYZ]RANGE [XYZ]STYLE [XYZ]THICK [XYZ]TICKFORMAT [XYZ]TICKLEN [XYZ]TICKNAME [XYZ]TICKS [XYZ]TICKV [XYZ]TICK_GET [XYZ]TITLE ZVALUE.

Example

Create a simple dataset by entering:

D = DIST(40)

Display the dataset as a light-source shaded surface by entering:

SHADE_SURF, D, TITLE = 'Shaded Surface'

Instead of light-source shading, an array of the same size as the elevation dataset can be used to color the surface. This technique creates four-dimensional displays. Create an array of shades to use by entering the command:

S = SIN(D)

Now create a new shaded surface that uses the array of shading values instead of the light source. Enter:

SHADE_SURF, D, SHADES = BYTSCL(S)

Note that the BYTSCL function is used to scale S into the range of bytes.

See Also

POLYSHADE, SET_SHADING, SHADE_VOLUME, SURFACE


SHADE_SURF_IRR

The SHADE_SURF_IRR procedure creates a shaded surface representation of an irregularly gridded elevation dataset.

The data must be representable as an array of quadrilaterals. This routine should be used when the (X, Y, Z) arrays are too irregular to be drawn by SHADE_SURF, but are still semi-regular.

This routine is written in the IDL language. Its source code can be found in the file shade_surf_irr.pro in the lib subdirectory of the IDL distribution.

Calling Sequence

SHADE_SURF_IRR, Z, X, Y

Arguments

Z

An n x m array of elevations.

X

An n x m array containing the X location of each Z value.

Y

An n x m array containing the Y location of each Z value.

Note:  The grid described by X and Y must consist of quadrilaterals, must be semi-regular, and must be in "clockwise" order. Clockwise ordering means that:

x(i,j) <= x(i+1, j)	for all j

and

y(i,j) <= y(i, j+1)	for all i

Keywords

AX

The angle of rotation about the X axis. The default is 30 degrees.

AZ

The angle of rotation about the Z axis. The default is 30 degrees.

IMAGE

Set this keyword to a named variable that will contain the resulting shaded surface image. The variable is returned as a byte array of the same size as the currently selected graphics device.

PLIST

Set this keyword to a named variable that will contain the polygon list on return. This feature is useful when you want to make a number of images from the same set of vertices and polygons.

Example

The following example creates a semi-regular data set in the proper format at displays the resulting irregular surface.

z = DIST(10,10)*100.0	Create some elevation data.

x = FLTARR(10,10) & y = FLTARR(10,10)
Create arrays to hold X and Y data.

FOR i = 0,9 do x(0:9,i) = FINDGEN(10)

FOR j = 0,9 DO y(j,0:9) = FINDGEN(10)
Ensure that X and Y arrays are in "clockwise" order.

x = x + RANDOMU(seed,10,10)*0.49

y = y + RANDOMU(seed,10,10)*0.49	Make X and Y arrays irregular.

SHADE_SURF_IRR, z, x, y	Display the irregular surface.

See Also

SHADE_SURF, TRIGRID


SHADE_VOLUME

Given a 3D volume and a contour value, SHADE_VOLUME produces a list of vertices and polygons describing the contour surface. This surface can then be displayed as a shaded surface by the POLYSHADE procedure. Shading is obtained from either a single light-source model or from user-specified values.

SHADE_VOLUME computes the polygons that describe a three dimensional contour surface. Each volume element (voxel) is visited to find the polygons formed by the intersections of the contour surface and the voxel edges. The method used by SHADE VOLUME is that of Klemp, McIrvin and Boyd, 1990: "PolyPaint—A Three-Dimensional Rendering Package," American Meteorology Society Proceedings, Sixth International Conference on Interactive Information and Processing Systems. This method is similar to the marching cubes algorithm described by Lorenson and Cline, 1987: "Marching Cubes: A High Resolution 3D Surface Construction Algorithm," Computer Graphics 21, 163-169.

This routine is limited to processing datasets that will fit in memory.

Calling Sequence

SHADE_VOLUME, Volume, Value, Vertex, Poly

Arguments

Volume

A three-dimensional array that contains the dataset to be contoured. If the Volume array is dimensioned (D0, D1, D2), the resulting vertex coordinates range between 0 and D0-1 in X, 0 and D1-1 in Y, and 0 and D2-1 in Z.

Value

The scalar contour value. This value specifies the constant-density surface (also called an isosurface) to be rendered.

Vertex

The name of a variable to receive the vertex array. On output, this variable is set to a (3, n) floating-point array, suitable for input to POLYSHADE.

Poly

A named variable to receive the polygon list, an m-element, longword array. This list describes the vertices of each polygon and is suitable for input to POLYSHADE.

Keywords

LOW

Set this keyword to display the low side of the contour surface (i.e., the contour surfaces enclose high data values). If this keyword is omitted or is 0, the high side of the contour surface is displayed and the contour encloses low data values. If this parameter is incorrectly specified, errors in shading will result.

SHADES

An optional array, converted to byte type before use, that contains the user-specified shading color index for each voxel. This array must have the same dimensions as Volume. On exit, this array is replaced by another array, that contains the shading value for each vertex, contained in Vertex.

VERBOSE

Set this keyword to print a message indicating the number of polygons and vertices that are produced.

XRANGE

An optional two-element vector that contains the limits, over the first dimension, of the sub-volume to be considered.

YRANGE

An optional two-element vector that contains the limits, over the second dimension, of the sub-volume to be considered.

ZRANGE

An optional two-element vector containing the limits, over the third dimension, of the sub-volume to be considered.

Example

The following procedure shades a volume passed as a parameter. It uses the SCALE3 procedure to establish the viewing transformation. It then calls SHADE_VOLUME to produce the vertex and polygon lists, and POLYSHADE to draw the contour surface.

Pro SHOWVOLUME, vol, thresh, LOW = low
Display the contour surface of a volume.

s = SIZE(vol)	Get the dimensions of the volume.

IF s(0) NE 3 THEN ... ...	Error, must be a 3D array.

SCALE3, XRANGE=[0, S(1)], YRANGE=[0, S(2)], ZRANGE=[0, S(3)]

Use SCALE3 to establish the 3D transformation and coordinate ranges.

IF N_ELEMENTS(low) EQ 0 THEN low = 0
Default = view high side of contour surface.

SHADE_VOLUME, vol, thresh, v, p, LOW = low
Produce vertices and polygons.

TV, POLYSHADE(v,p,/T3D)	Produce image of surface and display.

END

See Also

POLYSHADE, SHADE_SURF


SHIFT

The SHIFT function shifts elements of vectors or arrays along any dimension by any number of elements. The result is a vector or array of the same structure and type as Array. Positive shifts are to the right while left shifts are expressed as a negative number. All shifts are circular.

Elements shifted off one end wrap around and are shifted onto the other end. In the case of vectors the action of SHIFT can be expressed:

Result(i + s) modulation = Arrayi  for  (0 ≤ 1 < n)

where s is the amount of the shift, and n is the number of elements in the array.

Calling Sequence

Result = SHIFT(Array, S1, ..., Sn)

Arguments

Array

The array to be shifted.

Si

The shift parameters. For arrays of more than one dimension, the parameter Sn specifies the shift applied to the nth dimension. S1 specifies the shift along the first dimension and so on. If only one shift parameter is present and the parameter is an array, the array is treated as a vector (i.e., the array is treated as having one-dimensional subscripts).

A shift specification of 0 means that no shift is to be performed along that dimension.

Example

The following example demonstrates using SHIFT with a vector. Create a 5- element, integer vector by entering:

A = INDGEN(5)

Print the original vector, the vector shifted one position to the right, and the vector shifted one position to the left:

PRINT, A, SHIFT(A, 1), SHIFT(A, -1)

Executing these statements gives the result:

  0   1   2   3   4

  4   0   1   2   3

  1   2   3   4   0

Notice how elements of the vector that shift off the end wrap around to the other end. This "wrap around" occurs when shifting arrays of any dimension.

See Also

ISHFT


SHOW3

The SHOW3 procedure combines an image, a surface plot of the image data, and a contour plot of the images data in a single tri-level display.

This routine is written in the IDL language. Its source code can be found in the file show3.pro in the lib subdirectory of the IDL distribution.

Calling Sequence

SHOW3, Image

Arguments

Image

The two-dimensional array to display.

Keywords

INTERP

Set this keyword to use bilinear interpolation on the pixel display. This technique is slightly slower, but for small images, it makes a better display.

SSCALE

Reduction scale for surface. The default is 1. If this keyword is set to a value other than 1, the array size is reduced by this factor for the surface display. That is, the number of points used to draw the wire-mesh surface is reduced. If the array dimensions are not an integral multiple of SSCALE, the image is reduced to the next smaller multiple.

Example

Z = DIST(30)	Create a simple dataset.

SHOW3, Z	Display Z as a SHOW3 graph.

See Also

CONTOUR, SURFACE


SHOWFONT

The SHOWFONT procedure displays a vector-drawn font (from the file hersh1.chr, located in the main IDL directory) on the current graphics device.

This routine is written in the IDL language. Its source code can be found in the file showfont.pro in the lib subdirectory of the IDL distribution.

Calling Sequence

SHOWFONT, Font, Name

Arguments

Font

The index number of the font (may range from 3 to 29) in the file hersh1.chr.

Name

A string that contains the text of a title to appear at the top of the font display.

Keywords

ENCAPSULATED

Set this keyword, if the current graphics device is "PS", to make encapsulated PostScript output.

Example

To create a display of Font 3 for PostScript:

SET_PLOT, 'PS'	Set output to PostScript.

SHOWFONT, 3, 'Simplex Roman'	Display font 3.

DEVICE, /CLOSE	Close the new PS file (saved by default as idl.ps).

See Also

EFONT, PS_SHOW_FONTS


SIN

The periodic function SIN returns the trigonometric sine of X.

Calling Sequence

Result = SIN(X)

Arguments

X

The angle for which the sine is desired, specified in radians. If X is double-precision floating or complex, the result is of the same type. All other types are converted to single-precision floating-point and yield floating-point results. When applied to complex numbers:

sin x = COMPLEX(sin R cosh I, cos R sinh I)

where R and I are the real and imaginary parts of x.

If input argument X is an array, the result has the same structure, with each element containing the sine of the corresponding element of X .

Examples

To find the sine of 0.5 radians and print the result, enter:

PRINT, SIN(0.5)

The following example plots the SIN function between 0 and 2π with 100 intervals:

X = 2*!PI/100 * FINDGEN(100)

PLOT, X, SIN(X)

Note: !PI is a read-only system variable that contains the single-precision value for π.

See Also

ASIN, SINH


SINDGEN

The SINDGEN function returns a string array with the specified dimensions. Each element of the array is set to the string representation of the value of its one-dimensional subscript, using IDL's default formatting rules.

Calling Sequence

Result = SINDGEN(D1, ..., Dn)

Arguments

Di

The dimensions of the result. The dimension parameters can be any scalar expression. Up to eight dimensions can be specified.

Example

To create S, a six-element string vector with each element set to the string value of its subscript, enter:

S = SINDGEN(6)

See Also

BINDGEN, CINDGEN, DCINDGEN, DINDGEN, FINDGEN, INDGEN, LINDGEN


SINH

The SINH function returns the hyperbolic sine of X.

Calling Sequence

Result = SINH(X)

Arguments

X

The angle for which the hyperbolic sine is desired, specified in radians. If X is double-precision floating-point, the result is also double-precision. Complex values are not allowed. All other types are converted to single-precision floating-point and yield floating-point results. SINH is defined as:

sinh x = (e^u - e^-u) / 2

If X is an array, the result has the same structure, with each element containing the hyperbolic sine of the corresponding element of X .

Examples

To find the hyperbolic sine of each element in the array [.5, .2, .4] and print the result, enter:

PRINT, SINH([.5, .2, .4])

To plot the SINH function between 0 and 2π with 100 intervals, enter:

X = 2*!PI/100 * FINDGEN(100)

PLOT, X, SINH(X)

Note: !PI is a read-only system variable that contains the single-precision value of π.

See Also

ASIN, SIN


SIZE

The SIZE function returns a vector that contains size and type information for its argument.

The returned vector is always of longword type. The first element is equal to the number of dimensions of Expression. This value is zero if Expression is scalar or undefined. The next elements contain the size of each dimension, one element per dimension (none if Expression is scalar or undefined). After the dimension sizes, the last two elements contain the type code (zero if undefined) and the number of elements in Expression, respectively. The type code is described in the table below.

Type Code	Data Type
0	Undefined
1	Byte
2	Integer
3	Longword integer
4	Floating point
5	Double-precision floating
6	Complex floating
7	String
8	Structure
9	Double-precision complex
Table 1.15 IDL Type Codes

Calling Sequence

Result = SIZE(Expression)

Arguments

Expression

The expression for which size information is requested.

Example

Print the size information for a 10 by 20 floating-point array by entering:

PRINT, SIZE(FINDGEN(10, 20))

IDL prints:

   2   10   20   4   200

IDL shows that the array has 2 dimensions, equal to 10 and 20, a type code of 4, and 200 elements total.


SKIPF
SKIPF (VMS Only)

The SKIPF procedure skips records or files on the designated magnetic tape unit. If two parameters are supplied, files are skipped. If three parameters are present, individual records are skipped.

The number of files or records actually skipped is stored in the system variable !ERR. Note that when skipping records, the operation terminates immediately when the end of a file is encountered. See the description of the magnetic tape routines in Chapter 17 of the IDL User's Guide.

Calling Sequence

SKIPF, Unit, Files

or

SKIPF, Unit, Records, R

Arguments

Unit

The magnetic tape unit to rewind. Unit must be a number between 0 and 9, and should not be confused with the standard file Logical Unit Numbers (LUNs).

Files

The number of files to be skipped. Skipping is in the forward direction if the second parameter is positive, otherwise files are skipped backwards.

Records

The number of records to be skipped. Skipping is in the forward direction if the second parameter is positive, otherwise records are skipped backwards.

R

If this argument is present, records are skipped, otherwise files are skipped. The value of R is never examined. Its presence serves only to indicate that records are to be skipped.


SLICER

The IDL SLICER is a widget-based application to show 3D volume slices and isosurfaces. On exit, the Z-buffer contains the most recent image generated by the SLICER. The image may be redisplayed on a different device by reading the Z-buffer contents plus the current color table. Note that the volume data must fit in memory.

This routine is written in the IDL language. Its source code can be found in the file slicer.pro in the lib subdirectory of the IDL distribution.

Using the SLICER

Data is passed to the SLICER via the common block VOLUME_DATA. Note that the variable used to contain the volume data must be defined as part of the common block before the volume data is read into the variable. (See the Example section, below.)

The SLICER has the following modes:

•	Slices: Displays or removes orthogonal or oblique slices through the data volume.

•	Block: Displays the surfaces of a selected block inside the volume.

•	Cutout: Cuts blocks from previously drawn objects.

•	Isosurface: Draws an isosurface contour.

•	Probe: Displays the position and value of objects using the mouse.

•	Colors: Manipulates the color tables and contrast.

•	Rotations: Sets the orientation of the display.

•	Journal: Records or plays back files of SLICER commands.

See the SLICER's help file (available by clicking the "Help" button on the SLICER widget) for more information about drawing slices and images.

Calling Sequence

COMMON VOLUME_DATA, A

A = your_volume_data

SLICER

Arguments

A

A 3D array containing volume data. Note that the variable A must be included in the common block VOLUME_DATA before being equated with the volume data. A is not an explicit argument to SLICER.

Keywords

CMD_FILE

Set this keyword to a string that contains the name of a file containing SLICER commands to execute as described under SLICER Commands, below. The file should contain one command per line.

Command files can be created interactively, using the SLICER's "Journal" feature.

COMMAND

Set this keyword equal to a 1 x n string array containing commands to be executed by the SLICER before entering interactive mode. Available commands are described under SLICER Commands, below.

Note that commands passed to the SLICER with the COMMAND keyword must be in a 1 x n array, rather than in an n-element vector. String arrays can be easily specified in the proper format using the TRANSPOSE command. For example, the following passes three commands to the slicer:

com=TRANSPOSE(['COLOR 5', 'TRANS 1 20', 'ISO 17 1'])

SLICER, COMMAND=com

DETACHED

Set this keyword to put the drawable in a separate window. This can be useful when working with large images.

GROUP

Set this keyword to the widget ID of the widget that calls SLICER. When GROUP is specified, a command to destroy the calling widget also destroys the SLICER.

RANGE

Set this keyword to a two-element array containing minimum and maximum data values of interest. If RANGE is omitted, the data is scanned for the minimum and maximum values.

RESOLUTION

Set this keyword to a two-element vector specifying the width and height of the drawing window. The default is 55% by 44% of the screen width.

SLICER Commands

The slicer accepts a number of commands that replicate the action of controls in the graphical user interface. These commands can be specified at the IDL command line using either CMD_FILE keyword or the COMMAND keyword. Files of SLICER commands can also be created and played back from within the SLICER, using the "Journal" feature.

Commands, in this context, are strings that include a command identifier and (in some cases) one or more numeric parameters separated by blanks. The following are the available SLICER commands, with parameters.

COLOR Table_Index Low High Shading

Set the color tables. Table_Index is the pre-defined color table number (see "LOADCT" on page 1-539), or -1 to retain the present table. Low is the contrast minimum, High is the contrast maximum, and Shading is the differential shading, all expressed in percent. For example, the following command picks color table number 2, sets the minimum contrast to 10%, the maximum contrast to 90%, and the differential shading to 50%:

COLOR 2 10 90 50

CUBE Mode Cut_Ovr Interp X0 Y0 Z0 X1 Y1 Z1

Defines the volume used for "Block" and "Cutout" operations. Set Mode=1 for Block mode or Mode=2 for Cutout mode. Set Cut_Ovr=0 to mimic selecting the "Cut Into" button or Cut_Ovr=1 to mimic selecting the "Cut Over" button. (Note that these buttons have no effect in Block mode. See the SLICER's online help for further explanation of Cut Into and Cut Over.)

Set Interp=1 for bilinear interpolation sampling or Interp=0 for nearest neighbor sampling.

X0,Y0,Z0 are the coordinates of the lower corner of the volume, and X1,Y1,Z1 are the coordinates of the upper corner. For example:

CUBE 1 0 1 20 0 56 60 75 42

selects Block mode, the "Cut Into" button, bilinear interpolation and defines the volume's corners at (20, 0, 56) and (60, 75, 42).

ERASE

Erases the display. Mimics clicking on the "Erase" button.

ISO Threshold Hi_Lo

Draws an iso-surface. Threshold is the isosurface threshold value. Set Hi_Lo equal to 1 to view the low side, or equal to 0 to view the high side.

ORI X_Axis Y_Axis Z_axis X_Rev Y_Rev Z_Rev X_Rot Z_Rot Asp

Sets the orientation for the SLICER display, mimicking the action of the "Orientation" button. Set X_Axis, Y_Axis, and Z_Axis to 0, 1, or 2, where 0 represents the data X axis, 1 the data Y axis, and 2 the data Z axis. Set X_Rev, Y_Rev, and Z_Rev to 0 for normal orientation or to 1 for reversed. Set X_Rot and Z_Rot to the desired rotations of the X and Z axes, in degrees (30 is the default). Set Asp to the desired Z axis aspect ratio with respect to X and Y. For example, to interchange the X and Z axes and reverse the Y use the string:

ORI 2 1 0 0 1 0 30 30 1

SLICE Axis Value Interp Expose 0

Draws an orthogonal slice. Set Axis to 0 to draw a slice parallel to the X axis, to 1 for the Y axis, or to 2 for the Z axis. Set Value to the pixel value of the slice. Set Interp=1 for bilinear interpolation sampling or Interp=0 for nearest neighbor sampling. Set Expose=1 to cut out of an existing image (mimicking the "Expose" button) or set Expose=0 to draw the slice on top of the current display (mimicking the "Draw" button). The final zero indicates that the slice is orthogonal rather than oblique. For example, the following command draws an orthogonal slice parallel to the X axis, at the pixel value 31, using bilinear interpolation.

SLICE 0 31 1 0 0

SLICE Azimuth Elev Interp Expose 1 X0 Y0 Z0

Draws an oblique slice. The oblique plane crosses the XY plane at angle Azimuth, with an elevation of Elev. Set  Interp=1 for bilinear interpolation sampling or Interp=0 for nearest neighbor sampling. Set Expose=1 to cut out of an existing image (mimicking the "Expose" button) or set Expose=0 to draw the slice on top of the current display (mimicking the "Draw" button). The one indicates that the slice is oblique rather than orthogonal. The plane passes through the point (X0, Y0, Z0). For example, the following command exposes an oblique slice with an azimuth of 42 and an elevation of 24, using bilinear interpolation. The plane passes through the point (52, 57, 39).

SLICE 42 24 1 1 1 52 57 39

TRANS On_Off Threshold

Turns transparency on or off and sets the transparency threshold value. Set On_Off=1 to turn transparency on, On_Off=0 to turn transparency off. Threshold is expressed in percent of data range (0 = minimum data value, 100 = maximum data value). For example, this command turns transparency on and sets the threshold at 20 percent:

TRANS 1 20

UNDO

Undoes the previous operation.

WAIT Secs

Causes the SLICER to pause for the specified time, in seconds.

Example

Data is transferred to the SLICER via the VOLUME_DATA common block instead of as an argument. This technique is used because volume datasets can be very large and the duplication that occurs when passing values as arguments is a waste of memory.

Suppose that you want to read some data from the file head.dat, which is included in the IDL demos directory, into IDL for use in the SLICER. Note that if you did not install the demo files when installing IDL, head.dat will not be available.

First, define a variable that contains the path to the head.dat file. This path will be different depending on the platform you are using. On a Unix or VMS system, define the subdirectory as follows:

subdir=['..', 'idl_demo_4', 'data']

On a Windows system, use:

subdir=['..', 'idldemo4', 'data']

On a Macintosh, use:

subdir=['..', 'idl 4.0 demos', 'data']

Before you read the data, establish the VOLUME_DATA common block with the following command:

COMMON VOLUME_DATA, VOL

The VOLUME_DATA common block has just one variable in it. (The variable can have any name; here, we're using the name VOL.) Now read the data from the file into VOL. For example:

OPENR, UNIT, /GET, FILEPATH('head.dat', SUBDIRECTORY=subdir)

VOL = BYTARR(80, 100, 57, /NOZERO)

READU, UNIT, VOL

CLOSE, UNIT

Now you can run the SLICER widget application by entering:

SLICER

The data stored in VOL is the data being worked on by the SLICER.

To obtain the image in the slicer window after slicer is finished:

SET_PLOT, 'Z'	Use the Z buffer graphics device.

A = TVRD()	Read the image.

See Also

GRID3, EXTRACT_SLICE, SHADE_VOLUME


SLIDE_IMAGE

The SLIDE_IMAGE procedure creates a scrolling graphics window for examining large images. By default, 2 draw widgets are used. The draw widget on the left shows a reduced version of the complete image, while the draw widget on the right displays the actual image with scrollbars that allow sliding the visible window.

This routine is written in the IDL language. Its source code can be found in the file slide_image.pro in the lib subdirectory of the IDL distribution.

Calling Sequence

SLIDE_IMAGE [, Image]

Arguments

Image

A 2D image array to be displayed. If this argument is not specified, no image is displayed. The FULL_WINDOW and SCROLL_WINDOW keywords can be used to obtain the window numbers of the two draw widgets so they can be drawn into at a later time.

Keywords

CONGRID

Normally, the image is processed with the CONGRID procedure before it is written to the fully visible window on the left. Specifying CONGIRD=0 will force the image to be drawn as is.

FULL_WINDOW

Set this keyword to a named variable that will contain the IDL window number of the fully visible window. This window number can be used with the WSET procedure to draw to the scrolling window at a later point.

GROUP

Set this keyword to the widget ID of the widget that calls SLIDE_IMAGE. If set, the death of the caller results in the death of SLIDE_IMAGE.

ORDER

This keyword is passed directly to the TV procedure to control the order in which the images are drawn. Usually, images are drawn from the bottom up. Set this keyword to a non-zero value to draw images from the top down.

REGISTER

Set this keyword to create a "Done" button for SLIDE_IMAGE and register the widgets with the XMANAGER procedure.

The basic widgets used in this procedure do not generate widget events, so it is not necessary to process events in an event loop. The default is therefore to simply create the widgets and return. Hence, when REGISTER is not set, SLIDE_IMAGE can be displayed and the user can still type commands at the IDL command prompt.

RETAIN

This keyword is passed directly to the WIDGET_DRAW function. Set RETAIN to zero, one, or two to specify how backing store should be handled for the window. RETAIN=0 specifies no backing store. RETAIN=1 requests that the server or window system provide backing store. RETAIN=2 specifies that IDL provide backing store directly. See "Backing Store" on page 3-27 of the IDL Reference Guide for details.

SLIDE_WINDOW

Set this keyword to a named variable that will contain the IDL window number of the sliding window. This window number can be used with the WSET procedure to draw to the scrolling window at a later time.

TITLE

Set this keyword to the title to be used for the SLIDE_IMAGE widget. If this keyword is not specified, "Slide Image" is used.

TOP_ID

Set this keyword to a named variable that will contain the top widget ID of the SLIDE_IMAGE hierarchy. This ID can be used to kill the hierarchy as shown below:

SLIDE_IMAGE, TOP_ID=base, ...

WIDGET_CONTROL, /DESTROY, base

XSIZE

Set this keyword to the maximum width of the image that can be displayed by the scrolling window. This keyword should not be confused with the visible size of the image, controlled by the XVISIBLE keyword. If XSIZE is not specified, the width of Image is used. If Image is not specified, 256 is used.

XVISIBLE

Set this keyword to the width of the viewport on the scrolling window. If this keyword is not specified, 256 is used.

YSIZE

Set this keyword to the maximum height of the image that can be displayed by the scrolling window. This keyword should not be confused with the visible size of the image, controlled by the YVISIBLE keyword. If YSIZE is not present the height of Image is used. If Image is not specified, 256 is used.

YVISIBLE

Set this keyword to the height of the viewport on the scrolling window. If this keyword is not present, 256 is used.

Example

Open an image from the IDL distribution and load it into SLIDE_IMAGE:

A = BYTARR(768,512)	Create a variable to hold the image.

OPENR, 1, FILEPATH('nyny.dat', SUBDIR='images')

READU, 1, A

CLOSE, 1

A = BYTSCL(A)	Scale the image into byte range of the display.

SLIDE_IMAGE, A	Display the image.

See Also

TV, TVSCL, WIDGET_DRAW, WINDOW


SMOOTH

The SMOOTH function returns a copy of Array smoothed with a boxcar average of the specified width. The result has the same type and dimensions as Array. The algorithm used by SMOOTH is:

where N  is the number of elements in A.

Calling Sequence

Result = SMOOTH(Array, Width)

Arguments

Array

The array to be smoothed. Array can have any number of dimensions.

Width

The width of the smoothing window. Width should be an odd number, smaller than the smallest dimension of Array. If Width is an even number, one plus the given value of Width is used. The value of Width does not affect the running time of SMOOTH to a great extent.

Keywords

EDGE_TRUNCATE

Set this keyword to apply the smoothing function to all points. If the neighborhood around a point includes a point outside the array, the nearest edge point is used to compute the smoothed result. If EDGE_TRUNCATE is not set, the end points are copied from the original array to the result with no smoothing.

For example, when smoothing an n-element vector with a three point wide smoothing window, the first point of the result R(0) is equal to A(0) if EDGE_TRUNCATE is not set, but is equal to (A(0)+A(0)+A(1))/3 if the keyword is set. In the same manner, point R(n-1) is set to A(n-1) if EDGE_TRUNCATE is not set, or to (A(n-2)+A(n-1)+A(n-1))/3 if it is.

Points not within a distance of Width/2 from an edge are not affected by this keyword.

NAN

Set this keyword to cause the routine to check for occurrences of the IEEE floating-point value NaN in the input data. Elements with the value NaN are treated as missing data. (See  "Special Floating-Point Values" on page 11-9 of the IDL User's Guide for more information on IEEE floating-point values.)

Example

Create and display a simple image by entering:

D = SIN(DIST(256)/3) & TVSCL, D

Now display the same dataset smoothed with a width of 9 by entering:

TVSCL, SMOOTH(D, 9), 256, 256

See Also

DIGITAL_FILTER, LEEFILT, MEDIAN


SOBEL

The SOBEL function implements an approximation of the 3 by 3, nonlinear edge-enhancement operator:

Where the pixels surrounding the neighborhood of the pixel F(j, k) are numbered as follows:

The result of this function is a two-dimensional array of short integer type, with the same dimensions as Image. Large original data values cause overflow if the absolute value of the result is larger than 32768.

It should be noted that the previous description is not the true definition of the Sobel function, defined as:

but a fast approximation.

Calling Sequence

Result = SOBEL(Image)

Arguments

Image

The two-dimensional array containing the image to which edge enhancement will be applied.

Example

If the variable IM contains an image, a Sobel edge-enhanced version can be displayed with the command:

TVSCL, SOBEL(IM)

See Also

ROBERTS


SORT

The SORT function returns a vector of subscripts that allow access to the elements of Array in ascending order. The result is always a vector of longword type with the same number of elements as Array.

Calling Sequence

Result = SORT(Array)

Arguments

Array

The array to be sorted. Array can be any basic type of vector or array. String arrays are sorted using the ASCII collating sequence. Complex arrays are sorted by their magnitude.

Example

To illustrate, assume the vector A contains the elements [4, 3, 7, 1, 2]. Then:

SORT(A) = [3, 4, 1, 0, 2]

because:

A(3) < A(4) < A(1) < A(0) < A(2)

To see the elements of A in sorted order use the expression enter:

PRINT, A(SORT(A))

which prints:

     1     2     3     4     7

To obtain the elements in descending order enter:

PRINT, A(REVERSE(SORT(A)))

which prints:

     7     4     3     2     1

See Also

UNIQ, WHERE


SPAWN

The SPAWN procedure spawns a child process to execute a command or series of commands. Under Unix, the shell used (if any) is obtained from the SHELL environment variable. Under VMS, the DCL command language interpreter is used. Under Windows, a DOS window or Command Shell is opened. On the Macintosh, SPAWN opens specified files or applications.

Calling Sequence

SPAWN  [, Command(s) [, Result]]

Arguments

Command

A string containing the command(s) to be executed.

If Command is not present, SPAWN starts an interactive command interpreter process. Under Unix, the default shell is used. IDL execution suspends until the new shell process terminates. Under Unix, shells that handle process suspension (e.g., /bin/csh) offer a more efficient way to get the same effect.

Command must be of type string. Under VMS, it is restricted to being a scalar. Under Unix, it can be a string array—each element is passed to the child process as a separate argument.If the first file

On the Macintosh, Command must consist of the names of files to be opened. Multiple filenames can be entered. If the first filename is an application, it is used to open the remaining files. Otherwise, each file is opened by the application that owns it. IDL execution resumes when the files have been opened.

Result

A named variable in which to place the output from the child process. Each line of output becomes a single array element. If Result is not present, the output from the child shell process goes to the standard output.

On the Macintosh, Result has no effect.

Keywords

COUNT

If Result is present and this keyword is also specified, COUNT specifies a named variable into which the number of lines of output is placed. This value gives the number of elements placed into Result.

PID

A named variable into which the Process IDentification number of the child process is stored.

Macintosh Keywords

MACCREATOR

Use this keyword to specify a four-character scalar string containing the Macintosh file creator code of the application to be used to open the specified files. In no files were specified, the application is launched without any files.

Unix Keywords

NOSHELL

Set this keyword to specify that Command should execute directly as a child process without an intervening shell process. In this case, Command should be specified as a string array in which the first element is the name of the command to execute and the following arguments are the arguments to be passed to the command (C programmers will recognize this as these are the elements of the argv argument that Unix passes to the child process main function). Since no shell is present, wildcard characters are not expanded, and other tasks normally performed by the shell do not occur. NOSHELL is useful when performing many SPAWNed operations from a program and speed is a primary concern.

NOTTYRESET

Some Unix systems drop characters when the tty mode is switched between normal and raw modes. IDL switches between these modes when reading command input and when using the GET_KBRD function. On such systems, IDL avoids losing characters by delaying the switch back to normal mode until it is truly needed. This method has the benefit of avoiding the large number of mode changes that would otherwise be necessary. Routines that cause output to be sent to the standard output (e.g., I/O operations, user interaction and SPAWN) ensure that the tty is in its normal mode before performing their operations.

If the NOTTYRESET keyword is set, SPAWN does not switch the tty back to normal mode before launching the child process assuming instead that the child will not send output to the tty. Use this keyword to avoid characters being dropped in a loop of the form:

WHILE (GET_KBRD(0) NE 'q') SPAWN, command

This keyword has no effect on systems that don't suffer from dropped characters.

SH

Set this keyword to force the use of the /bin/sh shell. Usually, the shell used is determined by the SHELL environment variable.

UNIT

If UNIT is present, SPAWN creates a child process in the usual manner, but instead of waiting for the specified command to finish, it attaches a bidirectional pipe between the child process and IDL. From the IDL session, the pipe appears as a logical file unit. The other end of the pipe is attached to the child process standard input and output. The UNIT keyword specifies a named variable into which the number of the file unit is stored.

Once the child process is started, the IDL session can communicate with it through the usual input/output facilities. After the child process has done its task, the CLOSE procedure can be used to kill the process and close the pipe. Since SPAWN uses GET_LUN to allocate the file unit, FREE_LUN should be used to free the unit.

If UNIT is present, Command must be present, and Result is not allowed.

VMS Keywords

NOCLISYM

If this keyword is set, the spawned subprocess does not inherit command language interpreter symbols from its parent process. You can specify this keyword to prevent commands redefined by symbol assignments from affecting the spawned commands, or to speed process startup.

NOLOGNAM

If this keyword is set, the spawned subprocess does not inherit process logical names from its parent process. You can specify this keyword to prevent commands redefined by logical name assignments from affecting the spawned commands, or to speed process startup.

NOTIFY

If this keyword is set, a message is broadcast to SYS$OUTPUT when the child process completes or aborts. NOTIFY should be set in conjunction with the NOWAIT keyword.

NOWAIT

If this keyword is set, the IDL process continues executing in parallel with the subprocess. Normally, the IDL process hibernates until the subprocess completes.

Example

To simply spawn a process from within IDL enter the command:

SPAWN

To execute the UNIX ls command and return to the IDL prompt, enter:

SPAWN, 'ls'

To execute the UNIX ls command and store the result in the IDL string variable listing, enter:

SPAWN, 'ls', listing

See Also

See "Dollar Sign ($)" on page 2-7 of the IDL User's Guide.


SPH_4PNT

Given four 3-dimensional points, the SPH_4PNT procedure returns the center and radius necessary to define the unique sphere passing through those points.

This routine is written in the IDL language. Its source code can be found in the file sph_4pnt.pro in the lib subdirectory of the IDL distribution.

Calling Sequence

SPH_4PNT, X, Y, Z, Xc, Yc, Zc, R

Arguments

X, Y, Z

4-element floating-point or double-precision vectors containing the X, Y, and Z coordinates of the points.

Xc, Yc, Zc

Named variables that will contain the sphere's center X, Y, and Z coordinates.

R

A named variable that will contain the sphere's radius.

Example

Find the center and radius of the unique sphere passing through the points: (1, 1, 0), (2, 1, 2), (1, 0, 3), (1, 0, 1)

Define the floating-point vectors containing the x, y and z coordinates of the points.

X = [1, 2, 1, 1] + 0.0

Y = [1, 1, 0, 0] + 0.0

Z = [0, 2, 3, 1] + 0.0

Compute the sphere's center and radius.

SPH_4PNT, X, Y, Z, Xc, Yc, Zc, R

Print the results.

PRINT, Xc, Yc, Zc, R

IDL prints:

-0.500000      2.00000      2.00000      2.69258

See Also

CIR_3PNT, PNT_LINE


SPH_SCAT

The SPH_SCAT function performs spherical gridding. Scattered samples on the surface of a sphere are interpolated to a regular grid. This routine is a convenient interface to the spherical gridding and interpolation provided by TRIANGULATE and TRIGRID. The returned value of the function is a regularly-interpolated grid.

This routine is written in the IDL language. Its source code can be found in the file sph_scat.pro in the lib subdirectory of the IDL distribution.

Calling Sequence

Result = SPH_SCAT(Lon, Lat, F)

Arguments

Lon

A vector of sample longitudes, in degrees. Note that Lon, Lat, and F must all have the same number of points.

Lat

A vector of sample latitudes, in degrees.

F

A vector of data values which are functions of Lon and Lat. Fi represents a value at (Loni, Lati).

Keywords

BOUNDS

Set this keyword to a four-element vector containing the grid limits in longitude and latitude of the output grid. The four elements are: [Lonmin, Latmin, Lonmax, Latmax]. If this keyword is not set, the grid limits are set to the extent of Lon and Lat. Note that, to cover all longitudes, you must explicitly specify the values for the BOUNDS keyword.

BOUT

Set this keyword to a named variable that, on return, contains a four-element vector (similar to BOUNDS) that describes the actual extent of the regular grid.

GOUT

Set this keyword to a named variable that, on return, contains a two-element vector (similar to GS) that describes the actual grid spacing.

GS

Set this keyword to a two-element vector that specifies the spacing between grid points in longitude (the first element) and latitude (the second element).

If this keyword is not set, the default value is based on the extents of Lon and Lat. The default longitude spacing is (Lonmax - Lonmin)/(NX-1). The default latitude spacing is (Latmax - Latmin)/(NY-1). If NX and NY are not set, the default grid size of 26 by 26 is used for NX and NY.

NX

The output grid size in the longitude direction. The default value is 26. Note that NX need not be specified if the size can be inferred from GS and BOUNDS.

NY

The output grid size in the latitude direction. The default value is 26. Note that NY need not be specified if the size can be inferred from GS and BOUNDS.

Example

lon = RANDOMU(seed, 50) * 360. -180.
Create some random longitude points.

lat = RANDOMU(seed, 50) * 180. -90.
Create some random latitude points.

z = SIN(lat*!DTOR)	Make a function to fit.

c = COS(lat*!DTOR)

x = COS(lon*!DTOR) * c

y = SIN(lon*!DTOR) * c

f = SIN(x+y) * SIN(x*z)	The finished dependent variable.

r = SPH_SCAT(lon, lat, f, BOUNDS=[0, -90, 350, 85], GS=[10,5])
Interpolate the data and return the result in variable r.

See Also

TRIANGULATE, TRIGRID


SPL_INIT

The SPL_INIT function is called to establish the type of interpolating spline for a tabulated set of functional values Xi, Yi =  F(Xi). SPL_INIT returns the values of the 2nd derivative of the interpolating function at the points Xi.

It is important to realize that SPL_INIT should be called only once to process an entire tabulated function in arrays X and Y. Once this has been done, values of the interpolated function for any value of X can be obtained by calls (as many as desired) to the separate function SPL_INTERP.

SPL_INIT is based on the routine spline described in section 3.3 of Numerical Recipes in C: The Art of Scientific Computing (Second Edition), published by Cambridge University Press, and is used by permission.

Calling Sequence

Result = SPL_INIT(X, Y)

Arguments

X

An n-element input vector that specifies the tabulate points in ascending order.

Y

An n-element input vector that specifies the values of the tabulated function F(Xi) corresponding to Xi.

Keywords

DOUBLE

Set this keyword to force the computation to be done in double-precision arithmetic.

YP0 / YPN_1

The first derivative of the interpolating function at the points X0 and Xn-1, respectively. If YP0 or YPN_1 are omitted, the second derivative at the corresponding boundary is set to zero, resulting in a "natural spline."

Example

See the description of SPL_INTERP for an example using this function.

See Also

SPL_INTERP, SPLINE, SPLINE_P


SPL_INTERP

Given the arrays X and Y, which tabulate a function (with the X(i) in ascending order), and given the array Y2, which is the output from SPL_INIT, and given an input value of X2, the SPL_INTERP function returns a cubic-spline interpolated value for the given value of XI. The result has the same structure as X2, and is either single- or double-precision floating, based on the input type.

SPL_INTERP is based on the routine splint described in section 3.3 of Numerical Recipes in C: The Art of Scientific Computing (Second Edition), published by Cambridge University Press, and is used by permission.

Calling Sequence

Result = SPL_INTERP(X, Y, Y2, X2)

Arguments

X

An input array that specifies the tabulated points in ascending order.

Y

An input array that specifies the values of the tabulate function corresponding to Xi.

Y2

The output from SPL_INIT for the specified X and Y .

X2

The input value for which an interpolated value is desired. X can be scalar or an array of values. The result of SPL_INIT will have the same structure.

Keywords

DOUBLE

Set this keyword to force the computation to be done in double-precision arithmetic.

Example

To create a spline interpolation over a tabulated set of data, [Xi, Yi], first create the tabulated data. In this example,  Xi will be in the range [0.0, 2π] and Yi in the range [sin(0.0), sin(2π)].

X = (FINDGEN(21)/20.0) * 2.0 * !PI

Y = SIN(X)

Y2 = SPL_INIT(X, Y)	Calculate interpolating cubic spline.

Next define the X values P at which we desire interpolated Y values:

X2= FINDGEN(11)/11.0 * !PI

Finally, calculate the interpolated Y values corresponding to X2(i) and print:

result = SPL_INTERP(X, Y, Y2, X2)

PRINT, result

IDL prints:

 0.00000  0.281733  0.540638  0.755739  0.909613  0.989796

 0.989796  0.909613  0.755739  0.540638  0.281733

The exact solution vector is sin(X2).

To interpolate a line in the XY plane, see SPLINE_P.

See Also

SPL_INIT, SPLINE, SPLINE_P


SPLINE

The SPLINE function performs cubic spline interpolation.

This routine is written in the IDL language. Its source code can be found in the file spline.pro in the lib subdirectory of the IDL distribution.

Calling Sequence

Result = SPLINE(X, Y, T [, Sigma])

Arguments

X

The abscissa vector. Values must be monotonically increasing.

Y

The vector of ordinate values corresponding to X.

T

The vector of abscissa values for which the ordinate is desired. The values of T must be monotonically increasing.

Sigma

The amount of "tension" that is applied to the curve. The default value is 1.0. If sigma is close to 0, (e.g., .01), then effectively there is a cubic spline fit. If sigma is large, (e.g., greater than 10), then the fit will be like a polynomial interpolation.

Example

The commands below show a typical use of SPLINE:

X = [2.,3.,4.]	X values of original function

Y = (X-3)^2	Make a quadratic

T = FINDGEN(20)/10.+2	Values for interpolated points

Z = SPLINE(X,Y,T)	Do the interpolation

See Also

SPL_INIT, SPLINE_P


SPLINE_P

The SPLINE_P procedure performs parametric cubic spline interpolation with relaxed or clamped end conditions.

This routine is both more general and faster than the SPLINE function. One call to SPLINE_P is equivalent to two calls to SPLINE, as both the X and Y are interpolated with splines. It is suited for interpolating between randomly placed points, and the abscissa values need not be monotonic. In addition, the end conditions may be optionally specified via tangents.

This routine is written in the IDL language. Its source code can be found in the file spline_p.pro in the lib subdirectory of the IDL distribution.

Calling Sequence

SPLINE_P, X, Y, Xr, Yr

Arguments

X

The abscissa vector. X should be floating-point or double-precision.

Y

The vector of ordinate values corresponding to X. Y should be floating-point or double-precision.

Neither X or Y need be monotonic.

Xr

A named variable that will contain the abscissa values of the interpolated function.

Yr

A named variable that will contain the ordinate values of the interpolated function.

Keywords

INTERVAL

Set this keyword equal to the desired interval in XY space between interpolants. If omitted, approximately 8 interpolants per XY segment will result.

TAN0

The tangent to the spline curve at X(0), Y(0). If omitted, the tangent is calculated to make the curvature of the result zero at the beginning. TAN0 is a two element vector, containing the X and Y components of the tangent.

TAN1

The tangent to the spline curve at X(n-1), Y(n-1). If omitted, the tangent is calculated to make the curvature of the result zero at the end. TAN1 is a two element vector, containing the X and Y components of the tangent.

Example

The commands below show a typical use of SPLINE_P:

X = [0.,1,0,-1,0]	Abscissas for square with a vertical diagonal

Y = [0.,1,2,1,0]	Ordinates

SPLINE_P, X, Y, XR, YR	Interpolate with relaxed end conditions

PLOT, XR, YR	Show it

As above, but with setting both the beginning and end tangents:

SPLINE_P, X, Y, XR, YR, TAN0=[1,0], TAN1=[1,0]

This yields approximately 32 interpolants.

As above, but with setting the interval to 0.05, making more interpolants, closer together:

SPLINE_P, X, Y, XR, YR, TAN0=[1,0], TAN1=[1,0], INTERVAL=0.05

This yields 116 interpolants and looks close to a circle.

See Also

SPL_INIT, SPLINE


SPRSAB

The SPRSAB function performs matrix multiplication on two row-indexed sparse arrays created by SPRSIN. The routine computes all components of the matrix products, but only stores those values whose absolute magnitude exceeds the threshold value. The result is a row-indexed sparse array.

SPRSAB is based on the routine sprstm described in section 2.7 of Numerical Recipes in C: The Art of Scientific Computing (Second Edition), published by Cambridge University Press, and is used by permission. The difference between the two routines is that SPRSAB performs the matrix multiplication A.B rather than A.B^T.

Calling Sequence

Result = SPRSAB(A, B)

Arguments

A, B

Row-indexed sparse arrays created by the SPRSIN function.

Keywords

DOUBLE

Set this keyword to force the computation to be done in double-precision arithmetic.

THRESH

Use this keyword to set the criterion for deciding the absolute magnitude of the elements to be retained in sparse storage mode. For single-precision calculations, the default value is 1.0 x 10^-7. For double-precision calculations, the default is 1.0 x 10^-14.

Example

Begin by creating two arrays:

A = [[ 5.0,  0.0, 0.0,  1.0], $

     [ 3.0, -2.0, 0.0,  1.0], $

     [ 4.0, -1.0, 0.0,  2.0], $

     [ 0.0,  3.0, 3.0,  1.0]]

B = [[ 1.0,  2.0, 3.0,  1.0], $

     [ 3.0, -3.0, 0.0,  1.0], $

     [-1.0,  3.0, 1.0,  2.0], $

     [ 0.0,  3.0, 3.0,  1.0]]

sparse = SPRSAB(SPRSIN(A), SPRSIN(B))
Convert the arrays to sparse array format before multiplying. The variable SPARSE holds the result in sparse array form.

result = FULSTR(sparse)	Restore the sparse array structure to full storage mode.

PRINT, result	Print the result.

IDL prints:

      5.00000      13.0000      18.0000      6.00000

     -3.00000      15.0000      12.0000      2.00000

      1.00000      17.0000      18.0000      5.00000

      6.00000      3.00000      6.00000      10.0000

We can check this result by multiplying the original arrays:

exact = B # A

PRINT, exact

IDL prints:

      5.00000      13.0000      18.0000      6.00000

     -3.00000      15.0000      12.0000      2.00000

      1.00000      17.0000      18.0000      5.00000

      6.00000      3.00000      6.00000      10.0000

See Also

FULSTR, LINBCG, SPRSAX, SPRSIN, READ_SPR, WRITE_SPR


SPRSAX

The SPRSAX function takes a row-indexed sparse array created by the SPRSIN function and multiplies it by an  n-element vector to its right. The result is a n-element vector.

SPRSAX is based on the routine sprsax described in section 2.7 of Numerical Recipes in C: The Art of Scientific Computing (Second Edition), published by Cambridge University Press, and is used by permission.

Calling Sequence

Result = SPRSAX(A, X)

Arguments

A

A row-indexed sparse array created by the SPRSIN function.

X

An n-element right hand vector.

Keywords

DOUBLE

Set this keyword to force the computation to be done in double-precision arithmetic.

Example

Begin by creating an array A:

A = [[ 5.0,  0.0, 0.0], $

     [ 3.0, -2.0, 0.0], $

     [ 4.0, -1.0, 0.0]]

X = [1.0, 2.0, -1.0]	Define the right-hand vector.

result = SPRSAX(SPRSIN(A),X)
Convert to sparse format, then multiply by X.

PRINT, result	Print the result.

IDL prints:

      5.00000     -1.00000      2.00000

See Also

FULSTR, LINBCG, SPRSAB, SPRSIN, READ_SPR, WRITE_SPR


SPRSIN

The SPRSIN function converts an array into a row-index sparse storage mode, retaining only elements with an absolute magnitude greater than or equal to the specified threshold.

The result is a row-indexed sparse array contained in structure form. The structure consists of two linear sparse storage vectors: SA, a vector of array values, and IJA, a vector of subscripts to the SA vector. The length of these vectors is equal to the number of diagonal elements of the array, plus the number of off-diagonal elements with an absolute magnitude greater that or equal to the threshold value. Diagonal elements of the array are always retained even if their absolute magnitude is less than the specified threshold.

SPRSIN is based on the routine sprsin described in section 2.7 of Numerical Recipes in C: The Art of Scientific Computing (Second Edition), published by Cambridge University Press, and is used by permission.

Calling Sequence

Result = SPRSIN(A)

Arguments

A

An n by n array of any type except string or complex.

Keywords

COLUMN

Set this keyword if the input array A is in column-major format (composed of column vectors) rather than in row-major format (composed of row vectors).

DOUBLE

Set this keyword to convert the sparse array to double-precision.

THRESH

Use this keyword to set the criterion for deciding the absolute magnitude of the elements to be retained in sparse storage mode. For single-precision calculations, the default value is 1.0 x 10^-7. For double-precision values, the default is 1.0 x 10^-14.

Example

Suppose we wish to convert the following array to sparse storage format:

A = [[ 5.0, -0.2, 0.1], $

     [ 3.0, -2.0, 0.3], $

     [ 4.0, -1.0, 0.0]]

sparse = SPRSIN(A, THRESH = 0.5)	Convert to sparse storage mode. All elements of the array A that have absolute values less than THRESH are set to zero.

The variable SPARSE now contains a representation of A in structure form. See the description of FULSTR for an example that restores such a structure to full storage mode.

See Also

FULSTR, LINBCG, SPRSAB, SPRSAX, READ_SPR, WRITE_SPR


SQRT

The SQRT function returns the square root of X.

Calling Sequence

Result = SQRT(X)

Arguments

X

The value for which the square root is desired. If X is double-precision floating-point or complex, the result is of the same type. All other types are converted to single-precision floating-point and yield floating-point results. When applied to complex numbers, z = x +iy:

The ambiguous sign is taken to be the same as the sign of y. The result has the same structure as X.

Example

To find the square root of 145 and store the result in variable S, enter:

S = SQRT(145)

See Also

See "Exponentiation" on page 4-9 of the IDL User's Guide.


STOP

The STOP procedure stops the execution of a running program or batch file. Control reverts to the interactive mode.

Calling Sequence

STOP  [, Expr1, ..., Exprn]

Arguments

Expri

One or more expressions whose value is printed. If no parameters are present, a brief message describing where the STOP was encountered is printed.

Example

Suppose that you want to stop the execution of a procedure and print the values of the variables A, B, C and NUM. At the appropriate location in your procedure include the command:

STOP, A, B, C, NUM

To continue execution of the procedure (if possible) enter the IDL executive command:

.CONT

See Also

BREAKPOINT, EXIT, WAIT


STR_SEP

The STR_SEP function divides a string into pieces as designated by a separator string. STR_SEP returns a string array where each element is a separated piece of the original string.

This routine is written in the IDL language. Its source code can be found in the file str_sep.pro in the lib subdirectory of the IDL distribution.

Calling Sequence

Result = STR_SEP(String, Separator)

Arguments

String

The string to be separated.

Separator

The separator string.

Example

str = 'Keith.is.a.cool.dude!'	Create a string.

parts = STR_SEP(str, '.')	Separate the parts between the periods.

HELP, parts	IDL prints:
PARTS   STRING = Array(5)
Confirming that the string has been broken up into 5 elements.

PRINT, parts(3)	IDL prints:
cool

See Also

STRMID, STRPOS


STRARR

The STRARR function returns a string array containing zero-length strings.

Calling Sequence

Result = STRARR(D1, ..., Dn)

Arguments

Di

The dimensions of the result. The dimension parameters can be any scalar expression. Up to eight dimensions can be specified.

Example

To create S, a 20-element string vector, enter:

S = STRARR(20)

See Also

BYTARR, COMPLEXARR, DBLARR, DCOMPLEXARR, FLTARR, INTARR, LONARR, MAKE_ARRAY


STRCOMPRESS

The STRCOMPRESS function returns a copy of String with all whitespace (blanks and tabs) compressed to a single space or completely removed.

Calling Sequence

Result = STRCOMPRESS(String)

Arguments

String

The string to be compressed. If not of type string, it is converted using IDL's default formatting rules. If String is an array, the result is an array with the same structure—each element contains a compressed copy of the corresponding element of String .

Keywords

REMOVE_ALL

Set this keyword to remove all whitespace. Normally, all whitespace is compressed to a single space.

Example

Create a string variable S by entering:

S = 'This is a string with spaces in it.'

Now print S with all of the whitespace removed by entering:

PRINT, STRCOMPRESS(S, /REMOVE_ALL)

IDL prints:

Thisisastringwithspacesinit.

See Also

STRTRIM


STRETCH

The STRETCH procedure stretches the image display color tables so the full range runs from one color index to another. The modified colortable is loaded, but the COLORS common block is not changed. The original colortable can be restored by calling STRETCH with no arguments. A colortable must be loaded before STRETCH can be called.

This routine is written in the IDL language. Its source code can be found in the file reduce_colors.pro in the lib subdirectory of the IDL distribution.

Calling Sequence

STRETCH [, Low, High [, Gamma]]

Arguments

Low

The lowest pixel value to use. If this parameter is omitted, 0 is assumed. Appropriate values range from 0 to the number of available colors-1. If no parameters are supplied, the original color tables are restored.

High

The highest pixel value to use. If this parameter is omitted, the number of colors-1 is assumed. Appropriate values range from 0 to the number of available colors-1.

Gamma

An optional Gamma correction factor. If this value is omitted, 1.0 is assumed. Gamma correction works by raising the color indices to the Gamma power, assuming they are scaled into the range 0 to 1.

Keywords

CHOP

Set this keyword to set color indices above the upper threshold to color index 0. Normally, values above the upper threshold are set to the maximum color index.

Example

Load the STD GAMMA-II color table by entering:

LOADCT, 5

Create and display and image by entering:

TVSCL, DIST(300)

Now adjust the color table with STRETCH. Make the entire color table fit in the range 0 to 70 by entering:

STRETCH, 0, 70

Notice that pixel values above 70 are now colored white. Restore the original color table by entering:

STRETCH

See Also

GAMMA_CT, H_EQ_CT, MULTI, XLOADCT


STRING

The STRING function returns its arguments converted to string type. It is similar to the PRINT procedure, except that its output is placed in a string rather than being output to the terminal. The case in which a single expression of type byte is specified without the FORMAT keyword is special—see the discussion of STRING below, and in Chapter 17 and Chapter 8 of the IDL User's Guide for details.

Calling Sequence

Result = STRING(Expression1, ..., Expressionn)

Arguments

Expressionn

The expressions to be converted to string type.

Keywords

FORMAT

A format string to be used in formatting the expressions. See "Explicitly Formatted Input/Output" on page 17-15 of the IDL User's Guide. Note that formatted output from STRING is limited to a maximum of 1024 lines.

PRINT

Set this keyword to specify that any special case processing should be ignored and that STRING should behave exactly as the PRINT procedure would.

Differences Between STRING and PRINT

The behavior of STRING differs from the behavior of the PRINT procedure in the following ways (unless the PRINT keyword is set):

•	When called with a single non-byte argument and no format specification, STRING returns a result that has the same dimensions as the original argument. For example, the statement:

HELP, STRING(INDGEN(5))

gives the result:

<Expression> STRING = Array(5)

while:

HELP, STRING(INDGEN(5), /PRINT)

results in:

<Expression> STRING =' 0 1 2 3 4'

•	If called with a single argument of byte type and the FORMAT keyword is not used, STRING simply stores the unmodified values of each byte element in the result. This result is a string containing the byte values from the original argument. Thus, the result has one less dimension than the original argument. For example, a 2-dimensional byte array becomes a vector of strings, a byte vector becomes a scalar string. However, a byte scalar also becomes a string scalar. For example, the statement:

PRINT, STRING([72B, 101B, 108B, 108B, 111B])

produces the output:

Hello

because the argument to STRING, is a byte vector. Its first element is a 72B which is the ASCII code for "H", the second is 101B which is an ASCII "e", and so forth.

•	If both the FORMAT and PRINT keywords are not present and STRING is called with more than one argument, and the last argument is a scalar string starting with the characters "$(" or "(", this final argument is taken to be the format specification, just as if it had been specified via the FORMAT keyword. This feature is maintained for compatibility with version 1 of VMS IDL.

Example

To convert the contents of variable A to string type and store the result in the variable B, enter:

B = STRING(A)

See Also

BYTE, COMPLEX, DCOMPLEX, DOUBLE, FIX, FLOAT, LONG, PRINT


STRLEN

The STRLEN function returns the length of its string-type argument. If the argument is not a string, it is first converted to string type.

Calling Sequence

Result = STRLEN(Expression)

Arguments

Expression

The expression for which the string length is desired. If this parameter is not a string, it is converted using IDL's default formatting rules in order to determine the length. The result is an integer. If Expression is an array, the result is an integer array with the same structure, where each element contains the length of the corresponding Expression element.

Example

To find the length of the string "IDL is fun" and print the result, enter:

PRINT, STRLEN('IDL is fun')

IDL prints:

   10


STRLOWCASE

The STRLOWCASE function returns a copy of String converted to lowercase characters. Only uppercase characters are modified—lowercase and non-alphabetic characters are copied without change.

Calling Sequence

Result = STRLOWCASE(String)

Arguments

String

The string to be converted. If this argument is not a string, it is converted using IDL's default formatting rules. If String is an array, the result is an array with the same structure—each element contains a lower case copy of the corresponding element of String.

Example

To convert the string "IDL is fun" to all lowercase characters and print the result, enter:

PRINT, STRLOWCASE('IDL is fun')

IDL prints:

idl is fun

See Also

STRUPCASE


STRMESSAGE

The STRMESSAGE function returns the text of the error message specified by Errno. This function is especially useful in conjunction with the !ERROR system variable which always contains the error number of the last error. The !ERR_STRING system variable contains the text of the last error message.

Calling Sequence

Result = STRMESSAGE(Errno)

Arguments

Errno

The error number for which the message text is desired. Programs must not make the assumption that certain error numbers are always related to certain error messages the actual correspondence changes over time as IDL is modified.

Example

Print the error message associated with error number 4 by entering:

PRINT, STRMESSAGE(4)

See Also

MESSAGE


STRMID

The STRMID function extracts a substring from a string expression. The result of the function is a string of  Length characters taken from Expression , starting at character position First_Character.

Calling Sequence

Result = STRMID(Expression, First_Character, Length)

Arguments

Expression

The expression from which the substring is to be extracted. If this argument is not a string, it is converted using IDL's default formatting rules. If Expression is an array, the result is an array with the same structure, where each element contains the substring of the corresponding Expression element.

First_Character

The starting position within Expression at which the substring starts. The first character position is 0.

Length

The length of the substring. If there are not enough characters left in the main string to obtain  Length characters, the substring is truncated.

Example

If the variable B contains the string "IDL is fun", the substring "is" can be extracted and stored in the variable C with the command:

C = STRMID(B, 4, 2)

See Also

RSTRPOS, STRPOS, STRPUT, STRTRIM


STRPOS

The STRPOS function finds the first occurrence of a substring within an object string. If Search_String occurs in Expression, STRPOS returns the character position of the match, otherwise it returns -1.

Calling Sequence

Result = STRPOS(Expression, Search String [, Pos])

Arguments

Expression

The expression in which to search for the substring. If this argument is not a string, it is converted using IDL's default formatting rules. If Expression is an array, the result is an array with the same structure, where each element contains the position of the substring within the corresponding element Expression. If Expression is the null string, STRPOS returns the value -1.

Search_String

The substring to be searched for within Expression. If this argument is not a string, it is converted using IDL's default formatting rules. If Search_String is the null string, STRPOS returns the smaller of Pos or one less than the length of Expression.

Pos

The character position at which the search is begun. If Pos is omitted, the search begins at the first character (character position 0). If Pos is less than zero, zero is used for the starting position.

Example

Find the position of the string "fun" within the string "IDL is fun" and print the result by entering:

PRINT, STRPOS('IDL is fun', 'fun')

IDL prints:

   7

See Also

RSTRPOS, STRMID, STRPUT, STRTRIM


STRPUT

The STRPUT procedure inserts the contents of one string into another. The source string, Source , is inserted into the destination string, Destination , starting at the given position, Position. Characters in Destination before the starting position and after the starting position plus the length of Source remain unchanged. The length of the destination string is not changed. If the insertion extends past the end of the destination, it is clipped at the end.

Calling Sequence

STRPUT, Destination, Source [, Position]

Arguments

Destination

The named string variable into which Source is inserted. Destination must be a named variable of type string. If it is an array, Source is inserted into every element of the array.

Source

A scalar string to be inserted into Destination. If this argument is not a string, it is converted using IDL's default formatting rules.

Position

The character position at which the insertion is begun. If Position is omitted, the insertion begins at the first character (character position 0). If Position is less than zero, zero is used for the initial position.

Examples

If the variable A contains the string "IBM is fun", the substring "IBM" can be overwritten with the string "IDL" by entering:

STRPUT, A, 'IDL', 0

The following commands demonstrate the clipping of output that extends past the end of the destination string:

STRPUT, A, 'FUNNY', 7

PRINT, A

IDL prints:

IDL is FUN

See Also

STRMID, STRPOS, STRTRIM


STRTRIM

The STRTRIM function returns a copy of String with leading and/or trailing blanks removed.

Calling Sequence

Result = STRTRIM(String, [Flag])

Arguments

String

The string to have leading and/or trailing blanks removed. If this argument is not a string, it is converted using IDL's default formatting rules. If it is an array, the result is an array with the same structure where each element contains a trimmed copy of the corresponding element of String.

Flag

A value that controls the action of STRTRIM. If Flag is zero or not present, trailing blanks are removed. Leading blanks are removed if it is equal to 1. Both are removed if it is equal to 2.

Example

Converting variables to string type often results in undesirable leading blanks. For example, the following command converts the integer 56 to string type:

C = STRING(56)

Entering the command:

HELP, C

IDL prints:

C         STRING = '      56'

which shows that there are six leading spaces before the characters 5 and 6. To remove these leading blanks, enter the command:

C = STRTRIM(C, 1)

To confirm that the blanks were removed, enter:

HELP, C

IDL prints:

C         STRING = '56'

See Also

STR_SEP, STRMID, STRPOS, STRPUT


STRUPCASE

The STRUPCASE function returns a copy of String converted to upper case. Only lowercase characters are modified—uppercase and non-alphabetic characters are copied without change.

Calling Sequence

Result = STRUPCASE(String)

Arguments

String

The string to be converted. If this argument is not a string, it is converted using IDL's default formatting rules. If it is an array, the result is an array with the same structure where each element contains an uppercase copy of the corresponding element of  String.

Example

To print an uppercase version of the string "IDL is fun", enter:

PRINT, STRUPCASE('IDL is fun')

IDL prints:

IDL IS FUN

See Also

STRLOWCASE


SURFACE

The SURFACE procedure draws a wire-mesh representation of a two-dimensional array projected into two dimensions, with hidden lines removed.

Restrictions

If the  (X, Y) grid is not regular or nearly regular, errors in hidden line removal occur. The TRIGRID and TRIANGULATE routines can be used to interpolate irregularly-gridded data points to a regular grid before plotting.

If the T3D keyword is set, the 3D to 2D transformation matrix contained in !P.T must project the Z axis to a line parallel to the device Y axis, or errors will occur.

The surface lines may blend together when drawing large arrays, especially on low or medium resolution displays. Use the REBIN or CONGRID procedure to resample the array to a lower resolution before plotting.

Calling Sequence

SURFACE, Z [, X, Y]

Arguments

Z

The two-dimensional array to be displayed. If X and Y are provided, the surface is plotted as a function of the (X, Y) locations specified by their contents. Otherwise, the surface is generated as a function of the array index of each element of Z.

This argument is converted to single-precision floating-point before plotting. Plots created with SURFACE are limited to the range and precision of single-precision floating-point values.

X

A vector or two-dimensional array specifying the X coordinates of the grid. If this argument is a vector, each element of X specifies the X coordinate for a column of Z (e.g., X(0) specifies the X coordinate for Z(0,*)). If X is a two-dimensional array, each element of X specifies the X coordinate of the corresponding point in Z (Xij specifies the X coordinate for Zij).

This argument is converted to single-precision floating-point before plotting.

Y

A vector or two-dimensional array specifying the Y coordinates of the grid. If this argument is a vector, each element of Y specifies the Y coordinate for a row of Z (e.g., Y(0) specifies the Y coordinate for Z(*,0)). If Y is a two-dimensional array, each element of Y specifies the Y coordinate of the corresponding point in Z (Yij specifies the Y coordinate for Zij).

This argument is converted to single-precision floating-point before plotting.

Keywords

AX

This keyword specifies the angle of rotation, about the X axis, in degrees towards the viewer. This keyword is effective only if !P.T3D is not set. If !P.T3D is set, the three-dimensional to two-dimensional transformation used by SURFACE is taken from the 4 by 4 array !P.T.

The surface represented by the two-dimensional array is first rotated, AZ (see below) degrees about the Z axis, then by AX degrees about the X axis, tilting the surface towards the viewer (AX > 0), or away from the viewer.

The AX and AZ keyword parameters default to +30 degrees if omitted and !P.T3D is 0.

The three-dimensional to two-dimensional transformation represented by AX and AZ, can be saved in !P.T by including the SAVE keyword.

AZ

This keyword specifies the counterclockwise angle of rotation about the Z axis. This keyword is effective only if !P.T3D is not set. The order of rotation is AZ first, then AX.

BOTTOM

The color index used to draw the bottom surface. If not specified, the bottom is drawn with the same color as the top.

HORIZONTAL

A keyword flag which if set causes SURFACE to only draw lines across the plot perpendicular to the line of sight. The default is for SURFACE to draw both across the plot and from front to back.

LEGO

Set this keyword to produce stacked histogram-style plots. Each data value is rendered as a box covering the XY extent of the cell and with a height proportional to the Z value.

If the X and Y arguments are specified, only  Nx-1 columns and Ny-1 rows are drawn. (Note that this means that the last row and column of array data are not displayed.) The rectangular area covered by Z(i, j) is given by X(i), X(i+1), Y(j), and Y(j+1).

LOWER_ONLY

Set this keyword to draw only the lower surface of the object. By default, both surfaces are drawn.

MAX_VALUE

The maximum value to be plotted. If this keyword is present, data values greater than the value of MAX_VALUE are treated as missing and are not plotted. Note that the IEEE floating-point value NaN is also treated as missing data. (See "Special Floating-Point Values" on page 11-9 of the IDL User's Guide for more information on IEEE floating-point values.)

MIN_VALUE

The minimum value to be plotted. If this keyword is present, data values less than the value of MIN_VALUE are treated as missing and are not plotted. Note that the IEEE floating-point value NaN is also treated as missing data. (See "Special Floating-Point Values" on page 11-9 of the IDL User's Guide for more information on IEEE floating-point values.)

SAVE

Set this keyword to save the 3D to 2D transformation matrix established by SURFACE in the system variable field !P.T. Use this keyword when combining the output of SURFACE with additional output from other routines in the same plot.

When used with AXIS, the SAVE keyword parameter saves the scaling parameters established by the call in the appropriate axis system variable, !X, !Y, or !Z. This causes subsequent overplots to be scaled to the new axis.

Example

To display a two-dimensional array using SURFACE, and to then superimpose contours over the surface (this example assumes that !P.T3D is zero, its default value.), enter the following commands:

SURFACE, Z, /SAVE	Make a surface plot and save the transformation.

CONTOUR, Z, /NOERASE, /T3D	Make contours, don't erase, use the 3D to 2D transform placed in !P.T by SURFACE.

To display a surface and to then display a flat contour plot, registered above the surface:

SURFACE, Z, /SAVE	Make the surface, save transform.

CONTOUR, Z, /NOERASE, /T3D, ZVALUE=1.0
Now display a flat contour plot, at the maximum Z value (normalized coordinates). You can display the contour plot below the surface with by using a ZVALUE of 0.0.

SHADES

This keyword allows user-specified coloring of the mesh surfaces. Set this keyword to an array that specifies the color index of the lines emanating from each data point toward the top and right.

SKIRT

This keyword represents a Z-value at which to draw a skirt around the array. The Z value is expressed in data units. The default is no skirt.

If the skirt is drawn, each point on the four edges of the surface is connected to a point on the skirt which has the given Z value, and the same X and Y values as the edge point. In addition, each point on the skirt is connected to its neighbor.

UPPER_ONLY

Set this keyword to draw only the upper surface of the object. By default, both surfaces are drawn.

XLOG

Set this keyword to specify a logarithmic X axis.

YLOG

Set this keyword to specify a logarithmic Yaxis.

ZAXIS

This keyword specifies the placement of the Z axis for the SURFACE plot.

By default, SURFACE draws the Z axis at the upper left corner of the axis box. To suppress the Z axis, use ZAXIS=-1 in the call. The position of the Z axis is determined from the value of ZAXIS as follows: 1 = lower right, 2 = lower left, 3 = upper left, and 4 = upper right.

Graphics Keywords Accepted

See Chapter 2, "Graphics Keywords and System Variables", for the description of graphics and plotting keywords not listed above. BACKGROUND CHARSIZE  CHARTHICK CLIP COLOR DATA DEVICE FONT LINESTYLE NOCLIP NODATA NOERASE NORMAL POSITION SUBTITLE  T3D THICK TICKLEN TITLE [XYZ]CHARSIZE [XYZ]GRIDSTYLE [XYZ]MARGIN [XYZ]MINOR [XYZ]RANGE [XYZ]STYLE [XYZ]THICK [XYZ]TICKFORMAT [XYZ]TICKLEN [XYZ]TICKNAME [XYZ]TICKS [XYZ]TICKV [XYZ]TICK_GET [XYZ]TITLE ZVALUE.

Example

Create a simple dataset to display by entering:

D = DIST(30)

Plot a simple wire-mesh surface representation of D by entering:

SURFACE, D

Create a wire-mesh plot of D with a title and a "skirt" around the edges of the dataset at Z=0 by entering:

SURFACE, D, SKIRT=0.0, TITLE = 'Surface Plot', CHARSIZE = 2

See Also

CONTOUR, SHADE_SURF


SURFR

The SURFR procedure sets up 3D transformations. This procedure duplicates the rotation, translation, and scaling features of the SURFACE routine, but does not display any data. The resulting transformations are stored in the !P.T system variable.

This routine is written in the IDL language. Its source code can be found in the file surfr.pro in the lib subdirectory of the IDL distribution.

Calling Sequence

SURFR

Keywords

AX

Angle of rotation about the X axis. The default is 30 degrees.

AZ

Angle of rotation about the Z axis. The default is 30 degrees.

See Also

SCALE3, SCALE3D, T3D


SVDC

The SVDC procedure computes the Singular Value Decomposition (SVD) of a square (n by n) or non-square (n by m) array as the product of orthogonal and diagonal arrays. SVD is a very powerful tool for the solution of linear systems, and is often used when a solution cannot be determined by other numerical algorithms.

The SVD of an (m by n) non-square array A is computed as the product of an (m by n) column orthogonal array U, an (n by n) diagonal array SV, composed of the singular values, and the transpose of an (n by n) orthogonal array V: A = U  SV  V^T

SVDC is based on the routine svdcmp described in section 2.6 of Numerical Recipes in C: The Art of Scientific Computing (Second Edition), published by Cambridge University Press, and is used by permission.

Calling Sequence

SVDC,  A, W, U, V

Arguments

A

The square (n by n) or non-square (n by m) single- or double-precision floating-point array to decompose.

W

On output, W is an n-element output vector containing the "singular values."

U

On output, U is an n-column,  m-row orthogonal array used in the decomposition of  A.

V

On output, V is an n-column,  n-row orthogonal array used in the decomposition of  A.

Keywords

COLUMN

Set this keyword if the input array A is in column-major format (composed of column vectors) rather than in row-major format (composed of row vectors).

DOUBLE

Set this keyword to force the computation to be done in double-precision arithmetic.

Example

To find the singular values of an array A:

A = [[1.0, 2.0, -1.0, 2.5], $	Define the array A.

     [1.5, 3.3, -0.5, 2.0], $

     [3.1, 0.7,  2.2, 0.0], $

     [0.0, 0.3, -2.0, 5.3], $

     [2.1, 1.0,  4.3, 2.2], $

     [0.0, 5.5,  3.8, 0.2]]

SVDC, A, W, U, V	Compute the Singular Value Decomposition.

PRINT, W	Print the singular values.

IDL prints:

8.81973      2.65502      4.30598      6.84484

To verify the decomposition, use the relationship A = U ## SV ## TRANSPOSE(V), where SV is a diagonal array created from the output vector W.

sv = FLTARR(4, 4)

FOR K = 0, 3 DO sv(K,K) = W(K)

result = U ## sv ## TRANSPOSE(V)

PRINT, result

IDL prints:

      1.00000      2.00000     -1.00000      2.50000

      1.50000      3.30000    -0.500001      2.00000

      3.10000     0.700000      2.20000      0.00000

  2.23517e-08     0.300000     -2.00000      5.30000

      2.10000     0.999999      4.30000      2.20000

 -3.91155e-07      5.50000      3.80000     0.200000

This is the input array, to within machine precision.

See Also

CHOLDC, LUDC,  SVSOL

See "Linear Systems" on page 20-25 of the IDL User's Guide.


SVDFIT

The SVDFIT function performs a general least squares fit with optional error estimates and returns a vector of coefficients. Either a user-supplied function written in the IDL language or a built-in polynomial can be used to fit the data.

This routine is written in the IDL language. Its source code can be found in the file svdfit.pro in the lib subdirectory of the IDL distribution.

Calling Sequence

Result = SVDFIT(X, Y, M)

Arguments

X

An n-element vector of independent variables.

Y

A vector of dependent variables, the same length as X.

M

The number of coefficients in the fitting function. For polynomials, M is equal to the degree of the polynomial + 1.

Keywords

Weight

Set this keyword equal to a vector of weights for Yi. This vector should be the same length as X and Y. The error for each term is weighted by WEIGHTi when computing the fit. Frequently, WEIGHTi = 1.0/Sigmai, where Sigma is the measurement error or standard deviation of Yi. If WEIGHT is not specified, WEIGHTi is assumed to be 1.0.

Funct

Set this keyword equal to a string containing the name of a user-supplied IDL basis function with M coefficients. If this keyword is omitted, polynomials are used.

NOTE: In order for the following optional keyword output parameters to be returned, they must be defined before calling SVDFIT. The value or structure used in the definition is not important. For example:

yf = 1	Define output variable yf.

C = SVDFIT(X, Y, M, YFIT = yf)
Do SVD, fitted Y vector is now returned in variable yf.

YFIT

Set this keyword equal to a pre-defined named variable that will contain the vector of calculated Y values.

CHISQ

Set this keyword equal to a pre-defined named variable that will contain the sum of squared errors multiplied by weights if weights are specified.

COVAR

Set this keyword equal to a pre-defined named variable that will contain the covariance matrix of the coefficients.

VARIANCE

Set this keyword equal to a pre-defined named variable that will contain the Sigma squared in estimate of each coefficient M.

SINGULAR

Set this keyword equal to a pre-defined named variable that will contain the number of singular values returned. This value should be 0. If not, the basis functions do not accurately characterize the data.

Example

See the documentation for the POLY_FIT routine for an example using this function.

See Also

CURVEFIT, GAUSSFIT, POLY_FIT, POLYFITW, REGRESS, SFIT


SVSOL

The SVSOL function uses "back-substitution" to solve a set of simultaneous linear equations Ax = b , given the U, W, and V arrays returned by the SVDC procedure. None of the input arguments are modified, making it possible to call SVSOL multiple times with different right hand vectors, B.

SVSOL is based on the routine svbksb described in section 2.6 of Numerical Recipes in C: The Art of Scientific Computing (Second Edition), published by Cambridge University Press, and is used by permission.

Calling Sequence

Result = SVSOL(U, W, V, B)

Arguments

U

An n-column, m-row orthogonal array used in the decomposition of A. Normally, U is returned from the SVDC procedure.

W

An n-element vector containing "singular values." Normally,  W is returned from the SVDC procedure. Small values (close to machine floating-point precision) should be set to zero prior to calling SVSOL.

V

An n-column, n-row orthogonal array used in the decomposition of A. Normally, V is returned from the SVDC procedure.

B

An m-element vector containing the right hand side of the linear system Ax = b.

Keywords

COLUMN

Set this keyword if the input arrays U and V  are in column-major format (composed of column vectors) rather than in row-major format (composed of row vectors).

DOUBLE

Set this keyword to force the computation to be done in double-precision arithmetic.

Example

To solve the linear system Ax = b using Singular-value decomposition and back substitution, begin with an array A which serves as the coefficient array:

A = [[1.0, 2.0, -1.0, 2.5], $	Define the array A.

     [1.5, 3.3, -0.5, 2.0], $

     [3.1, 0.7,  2.2, 0.0], $

     [0.0, 0.3, -2.0, 5.3], $

     [2.1, 1.0,  4.3, 2.2], $

     [0.0, 5.5,  3.8, 0.2]]

B = [0.0, 1.0, 5.3, -2.0, 6.3, 3.8]
Define the right-hand side vector B.

SVDC, A, W, U, V	Decompose A.

PRINT, SVSOL(U, W, V, B)	Compute the solution and print the result.

IDL prints:

1.00095   0.00881170     0.984176   -0.0100954

This is the correct solution.

See Also

CRAMER, GS_ITER, LU_COMPLEX, CHOLSOL, LUSOL, SVDC, TRISOL


SWAP_ENDIAN

The SWAP_ENDIAN function reverses the byte ordering of arbitrary scalars, arrays or structures. It can make "big endian" number "little endian" and vice-versa. Note that the BYTEORDER procedure can be used to reverse the byte ordering of scalars and arrays (SWAP_ENDIAN also allows structures).

SWAP_ENDIAN returns values of the same type and structure as the input value, with the pertinent bytes reversed.

This routine is written in the IDL language. Its source code can be found in the file swap_endian.pro in the lib subdirectory of the IDL distribution.

Calling Sequence

Result = SWAP_ENDIAN(Variable)

Arguments

Variable

The named variable—scalar, array, or structure—to be swapped.

Example

A = SWAP_ENDIAN(A)	Reverse the byte order of A

See Also

BYTEORDER


SYSTIME

The SYSTIME function returns the current system time as either a string that contains the current day, date and time, or as the number of seconds elapsed since January 1, 1970.

Calling Sequence

Result = SYSTIME(Arg)

Arguments

Arg

If Arg is present and nonzero, the number of seconds elapsed since January 1, 1970 is returned as a double-precision, floating-point value.

Otherwise, a scalar string containing the current date/time in standard 24-character system format is returned. This format is:

DOW MON DD HH:MM:SS YEAR

where DOW is the day of the week, MON is the month, DD is the day of the month, HH is the hour, MM is the minute, SS is the second, and YEAR is the year.

Examples

Print the day of the week by entering:

PRINT, STRMID(SYSTIME(0), 0, 3)

The following code fragment could be used to determine the time required by a 16,384 point FFT:

T = SYSTIME(1)

A = FFT(FINDGEN(16384), -1)

PRINT, SYSTIME(1) - T, ' Seconds'

See Also

CALDAT, CALENDAR, JULDAY


T_CVF

The T_CVF function computes the cutoff value V in a Student's t distribution with Df degrees of freedom such that the probability that a random variable X is greater than V is equal to a user-supplied probability P.

This routine is written in the IDL language. Its source code can be found in the file T_cvf.pro in the lib subdirectory of the IDL distribution.

Calling Sequence

Result = T_CVF(P, Df)

Arguments

P

A non-negative single- or double-precision floating-point scalar, in the interval [0.0, 1.0], that specifies the probability of occurrence or success.

Df

A positive integer, single- or double-precision floating-point scalar that specifies the number of degrees of freedom of the Student's t distribution.

Example

Use the following command to compute the cutoff value in a Student's t distribution with five degrees of freedom such that the probability that a random variable X is greater than the cutoff value is 0.025. The result should be 2.57058.

result = T_CVF(0.025, 5)

PRINT, result

IDL prints:

2.57058

See Also

CHISQR_CVF, F_CVF, GAUSS_CVF, T_PDF


T_PDF

The T_PDF function computes the probability P that, in a Student's t distribution with Df degrees of freedom, a random variable X is less than or equal to a user-specified cutoff value V.

This routine is written in the IDL language. Its source code can be found in the file t_pdf.pro in the lib subdirectory of the IDL distribution.

Calling Sequence

Result = T_PDF(V, Df)

Arguments

V

An integer, single-, or double-precision floating-point scalar that specifies the cutoff value.

Df

A positive integer, single- or double-precision floating-point scalar that specifies the number of degrees of freedom of the Student's t distribution.

Example

Use the following command to compute the probability that a random variable X, from the Student's t distribution with 15 degrees of freedom, is less than or equal to 0.691. The result should be 0.749940.

result = T_PDF(0.691, 15)

PRINT, result

IDL prints:

0.749940

See Also

BINOMIAL, CHISQR_PDF, F_PDF, GAUSS_PDF, T_CVF


T3D

The T3D procedure implements three-dimensional transforms.

This routine accumulates one or more sequences of translation, scaling, rotation, perspective, and oblique transformations and stores the result in !P.T, the 3D transformation system variable. All the IDL graphic routines use this (4,4) matrix for output. Note that !P.T3D is not set, so for the transformations to have effect you must set !P.T3D = 1 (or set the T3D keyword in subsequent calls to graphics routines).

This procedure is based on that of Foley & Van Dam, Fundamentals of Interactive Computer Graphics, Chapter 8, "Viewing in Three Dimensions". The matrix notation is reversed from the normal IDL sense, i.e., here, the first subscript is the column, the second is the row, in order to conform with this reference.

A right-handed system is used. Positive rotations are counterclockwise when looking from a positive axis position towards the origin.

This routine is written in the IDL language. Its source code can be found in the file t3d.pro in the lib subdirectory of the IDL distribution.

Restrictions

This routine implements general rotations about the three axes. The routines SURFACE and SHADE_SURF may only be used in conjunction with T3D rotations that project the Z axis in 3 dimensions to a line parallel to the Y axis in 2 dimensions.

Calling Sequence

T3D

Keywords

Any, all, or none of the following keywords can be present in a call to T3D. The order of the input parameters does not matter.

The transformation specified by each keyword is performed in the order of their descriptions below (e.g., if both TRANSLATE and SCALE are specified, the translation is done first):

OBLIQUE

A two-element vector of oblique projection parameters. Points are projected onto the XY plane at Z=0 as follows:

x' = x + z(d * COS(a))

y' = y + z(d * SIN(a))

where OBLIQUE(0) = d and OBLIQUE(1) = a.

PERSPECTIVE

Perspective transformation. This parameter is a scalar (p) that indicates the Z distance of the center of the projection. Objects are projected into the XY plane at Z=0, and the "eye" is at point (0,0,p).

RESET

Set this keyword to reset the transformation to the default identity matrix.

ROTATE

A three-element vector of the rotations, in DEGREES, about the X, Y, and Z axes. Rotations are performed in the order of X, Y, and then Z.

SCALE

A three-element vector of scale factors for the X, Y, and Z axes.

TRANSLATE

A three-element vector of the translations in the X, Y, and Z directions.

XYEXCH

Set this keyword to exchange the X and Y axes.

XZEXCH

Set this keyword to exchange the X and Z axes.

YZEXCH

Set this keyword to exchange the Y and Z axes.

Examples

To reset the transformation, rotate 30 degs about the X axis and do perspective transformation with the center of the projection at Z = -1, X=0, and Y=0, enter:

T3D, /RESET, ROT = [ 30,0,0], PERS = 1.

Transformations may be cascaded, for example:

T3D, /RESET, TRANS = [-.5,-.5,0], ROT = [0,0,45]

T3D, TRANS = [.5,.5,0]

The first command resets, translates the point (.5,.5,0) to the center of the viewport, then rotates 45 degrees counterclockwise about the Z axis. The second call to T3D moves the origin back to the center of the viewport.

See Also

SCALE3, SCALE3D, SURFR


TAG_NAMES

The TAG_NAMES function returns a string array containing the names of the tags in a structure expression. It can also be used to determine the expression's structure name (if the structure has a name).

Calling Sequence

Result = TAG_NAMES(Expression)

Arguments

Expression

The structure expression for which the tag names are returned. This argument must be of structure type. TAG_NAMES does not search for tags recursively, so if Expression  is a structure containing nested structures, only the names of tags in the outermost structure are returned.

Keywords

STRUCTURE_NAME

Set this keyword to return a scalar string that contains the name of the structure instead of the names of the tags in the structure. If the structure is "anonymous", a null string is returned.

Example

Print the names of the tags in the system variable !P by entering:

PRINT, TAG_NAMES(!P)

IDL prints:

BACKGROUND CHARSIZE CHARTHICK CLIP COLOR FONT LINESTYLE MULTI

NOCLIP NOERASE NSUM POSITION PSYM REGION SUBTITLE SYMSIZE T

T3D THICK TITLE TICKLEN CHANNEL

Print the name of the structure in the system variable !P:

PRINT, TAG_NAMES(!P, /STRUCTURE_NAME)

IDL prints:

!PLT

See Also

CREATE_STRUCT


TAN

The TAN function returns the tangent of X.

Calling Sequence

Result = TAN(X)

Arguments

X

The angle for which the tangent is desired, specified in radians. If X is double-precision floating-point, the result is of the same type. Complex values are not allowed. All other types are converted to single-precision floating-point and yield floating-point results. If X is an array, the result has the same structure, with each element containing the tangent of the corresponding element of X.

Examples

Find the tangent of 0.5 radians and store the result in the variable T by entering:

T = TAN(0.5)

See Also

TAN, TANH


TANH

The TANH function returns the hyperbolic tangent of X.

Calling Sequence

Result = TANH(X)

Arguments

X

The value for which the hyperbolic tangent is desired, specified in radians. If X is double-precision floating-point, the result is also double-precision. Complex values are not allowed. All other types are converted to single-precision floating-point and yield floating-point results. TANH is defined as:

If X  is an array, the result has the same structure, with each element containing the hyperbolic tangent of the corresponding element of X .

Example

Find the hyperbolic tangent of 1 radian and print the result by entering:

PRINT, TANH(1)

Plot the hyperbolic tangent from -5 to +5 with an increment of 0.1 by entering:

PLOT, TANH(FINDGEN(101)/10. - 5)

See Also

ATAN, TAN


TAPRD
TAPRD (VMS Only)

The TAPRD procedure reads the next record on the selected tape unit into the specified array. No data or format conversion, with the exception of optional byte reversal, is performed. The array must be defined with the desired type and dimensions. If the read is successful, the system variable !ERR is set to the number of bytes read. See the description of the magnetic tape routines in Chapter 17 of the IDL User's Guide.

Calling Sequence

TAPRD, Array, Unit [, Byte_Reverse]

Arguments

Unit

The magnetic tape unit to read. This argument must be a number between 0 and 9, and should not be confused with standard file Logical Unit Numbers (LUN's).

Array

A named variable into which the data is read. If Array is larger than the tape record, the extra elements of the array are not changed. If the array is shorter than the tape record, a data overrun error occurs. The length of Array and the records on the tape can range from 14 bytes to 65,235 bytes.

Byte_Reverse

If this parameter is present, the even and odd numbered bytes are swapped after reading, regardless of the type of data or variables. This enables reading tapes containing short integers that were written on machines with different byte ordering. You can also use the BYTORDER routine to re-order different data types.

See Also

TAPWRT (VMS Only)


TAPWRT
TAPWRT (VMS Only)

The TAPWRT procedure writes data from the Array parameter to the selected tape unit. One physical record containing the same number of bytes as the array is written each time TAPWRT is called. The parameters and usage are identical to those in the TAPRD procedure with the exception that here the Array parameter can be an expression. Consult the TAPRD procedure for details. See the description of the magnetic tape routines in Chapter 17 of the IDL User's Guide.

Calling Sequence

TAPWRT, Array, Unit [, Byte_Reverse]

Arguments

Unit

The magnetic tape unit to write. This argument must be a number between 0 and 9, and should not be confused with standard file Logical Unit Numbers (LUNs).

Array

The expression representing the data to be output. The length of Array and the records on the tape can range from 14 bytes to 65,235 bytes.

Byte_Reverse

If this parameter is present, the even and odd numbered bytes are swapped on output, regardless of the type of data or variables. This enables writing tapes that are compatible with other machines.

See Also

TAPRD (VMS Only)


TEK_COLOR

The TEK_COLOR procedure loads a 32-color colortable similar to the default Tektronix 4115 colortable. This colortable is useful because of its distinct colors.

By default, this palette consists of 32 colors. The first 9 colors are: Index 0=black, 1=white, 2=red, 3=green, 4=blue, 5=cyan, 6=magenta, 8=orange.

Calling Sequence

TEK_COLOR [, Start_Index, Colors]

Arguments

Start_Index

An optional starting index for the palette. The default is 0. If this argument is included, the colors are loaded into the current colortable starting at the specified index.

Colors

The number of colors to load. The default is 32, which is also the maximum.

See Also

LOADCT, XLOADCT


TEMPORARY

The TEMPORARY function returns a temporary copy of a variable, and sets the original variable to "undefined". This function can be used to conserve memory when performing operations on large arrays, as it avoids making a new copy of results that are only temporary. In general, the TEMPORARY routine can be used to advantage whenever a variable containing an array on the left hand side of an assignment statement is also referenced on the right hand side.

Calling Sequence

Result = TEMPORARY(Variable)

Arguments

Variable

The variable to be referenced and deleted.

Example

Assume the variable a is a large array. The statement:

A = A + 1

creates a new array for the result of the addition, places the sum into the new array, assigns it to a, and then frees the old allocation of a. Total storage required is twice the size of a. The statement:

A = TEMPORARY(A) + 1

requires no additional space.

See Also

DELVAR


THIN

The THIN function returns the "skeleton" of a bi-level image. The skeleton of an object in an image is a set of lines that reflect the shape of the object. The set of skeletal pixels can be considered to be the medial axis of the object. For a much more extensive discussion of skeletons and thinning algorithms, see Algorithms for Graphics and Image Processing, Theo Pavlidis, Computer Science Press, 1982. The THIN function is adapted from Algorithm 9.1 (the classical thinning algorithm).

On input, the bi-level image is a rectangular array in which pixels that compose the object have a nonzero value. All other pixels are zero. The result is a byte type image in which skeletal pixels are set to 2 and all other pixels are zero.

Calling Sequence

Result = THIN(Image)

Arguments

Image

The two-dimensional image (array) to be thinned.

Example

The following commands display the "thinned" edges of a Sobel filtered image:

OPENR, 1, FILEPATH('people.dat', SUBDIR='images')
Open a file for reading.

A = BYTARR(192, 192)	Create a byte array in which to store the image.

READU, 1, A	Read first 192 by 192 image.

CLOSE, 1	Close the file.

TV, A, 0	Display the image.

TVSCL, THIN(SOBEL(A) GT 75), 1	Apply the Sobel filter, threshold the image at value 75, and display the thinned edges.

See Also

ROBERTS, SOBEL


THREED

The THREED procedure plots a 2D array as a pseudo 3D plot. The orientation of the data is fixed.

This routine is written in the IDL language. Its source code can be found in the file threed.pro in the lib subdirectory of the IDL distribution.

Calling Sequence

THREED, A [, Sp]

Arguments

A

The two-dimensional array to plot.

Sp

The spacing between plot lines. If Sp is omitted, the spacing is set to: (MAX(A)-MIN(A))/ROWS. If Sp is negative, hidden lines are not removed.

Keywords

TITLE

Set this keyword to the main plot title.

XTITLE

Set this keyword to the X axis title.

YTITLE

Set this keyword to the Y axis title.

Example

A = -SHIFT(DIST(30), 15, 15)	Create a 2D dataset.

THREED, A	Make a THREED plot.

SURFACE, A	Compare to SURFACE.

See Also

SURFACE


TIFF_DUMP

The TIFF_DUMP procedure dumps the Image File Directories of a TIFF file directly to the terminal screen. Each TIFF Image File Directory entry is printed. This procedure is used mainly for debugging.

Note that not all of the tags have names encoded. In particular, Facsimile, Document Storage and Retrieval, and most no-longer-recommended fields are not encoded.

This routine is written in the IDL language. Its source code can be found in the file tiff_dump.pro in the lib subdirectory of the IDL distribution.

Calling Sequence

TIFF_DUMP, File

Arguments

File

A scalar string containing the name of file to read.

See Also

TIFF_READ, TIFF_WRITE


TIFF_READ

The TIFF_READ function reads 8-bit or 24-bit images in TIFF format files (classes G, P, and R) and returns the image and color table vectors in the form of IDL variables. Only one image per file is read. TIFF_READ returns a byte array containing the image data. The dimensions of the result are the same as defined in the TIFF file (Columns, Rows).

For TIFF images that are RGB interleaved by pixel, the output dimensions are (3, Columns, Rows ).

For TIFF images that are RGB interleaved by image, TIFF_READ returns the integer value zero, sets the variable defined by the PLANARCONFIG keyword to 2, and returns three separate images in the variables defined by the R, G, and B arguments.

This routine is written in the IDL language. Its source code can be found in the file tiff_read.pro in the lib subdirectory of the IDL distribution.

Calling Sequence

Result = TIFF_READ(File [, R, G, B])

Arguments

File

A scalar string containing the name of file to read.

R, G, B

Named variables that will contain the Red, Green, and Blue color vectors extracted from TIFF Class P, Palette Color images. For TIFF images that are RGB interleaved by image (when the variable specified by the PLANARCONFIG keyword is returned as 2) the R, G, and B variables each hold an image with the dimensions (Columns, Rows).

Keywords

ORDER

Set this keyword to a named variable that will contain the order parameter from the TIFF File. This parameter is returned as 0 for images written bottom to top, and 1 for images written top to bottom. If the Orientation parameter does not appear in the TIFF file, an order of 1 is returned.

PLANARCONFIG

Set this keyword to a named variable that will contain the interleave parameter from the TIFF file. This parameter is returned as 1 for TIFF files that are GrayScale, Palette, or RGB color interleaved by pixel, or as 2 for RGB color TIFF files interleaved by image.

Example

Read the file my.tif in the current directory into the variable image, and save the color tables in the variables, R, G, and B by entering:

image = TIFF_READ('my.tif', R, G, B)

To view the image, load the new color table and display the image by entering:

TVLCT, R, G, B

TV, image

See Also

TIFF_WRITE


TIFF_WRITE

The TIFF_WRITE procedure writes 8- or 24-bit images to a TIFF file. Files are written in a single strip, or in three strips when the PLANARCONFIG keyword is set to 2.

This routine is written in the IDL language. Its source code can be found in the file tiff_write.pro in the lib subdirectory of the IDL distribution.

Calling Sequence

TIFF_WRITE, File, Array [, Orientation]

Arguments

File

A scalar string containing the name of file to create.

Array

The image data to be written. If not already a byte array, it is made a byte array. Array may be either an (n, m) array for Grayscale or Palette classes, or a (3, n, m) array for RGB full color, interleaved by image. If the PLANARCONFIG keyword is set to 2 then the Array parameter is ignored (and may be omitted).

Orientation

This parameter should be 0 if the image is stored from bottom-to-top (the default). For images stored from top-to-bottom, this parameter should be 1.

Warning: not all TIFF readers are capable of reversing the scan line order. If in doubt, first convert the image to top-to-bottom order (use the REVERSE function), and set Orientation to 1.

Keywords

RED, GREEN, BLUE

If you are writing a Class P, Palette color image, set these keywords equal to the color table vectors, scaled from 0 to 255.

If you are writing an image that is RGB interleaved by image (i.e., if the PLANARCONFIG keyword is set to 2), set these keywords to the names of the variables containing the 3 color component image.

PLANARCONFIG

Set this keyword equal to 2 if writing an RGB image that is contained in three separate images (color planes). The three images must be stored in the variables specified by the RED, GREEN, and BLUE keywords. Otherwise, omit this parameter (or set it to 1).

XRESOL

The horizontal resolution, in pixels per inch. The default is 100.

YRESOL

The vertical resolution, in pixels per inch. The default is 100.

Examples

Four types of TIFF files can be written:

TIFF Class G, Grayscale.

The variable array contains the 8-bit image array. A value of 0 is black, 255 is white. The Red, Green, and Blue keywords are omitted.

TIFF_WRITE, 'a.tif', array

TIFF Class P, Palette Color.

The variable array contains the 8-bit image array. The keyword parameters RED, GREEN, and BLUE contain the color tables, which can have up to 256 elements, scaled from 0 to 255.

TIFF_WRITE, 'a.tif', array, RED = r, GREEN = g, BLUE = b

TIFF Class R, RGB Full Color, color interleaved by pixel.

The variable array contains the byte data, and is dimensioned ( 3, cols, rows).

TIFF_WRITE, 'a.tif', array

TIFF Class R, RGB Full Color, color interleaved by image.

Input is three separate images, provided in the keyword parameters RED, GREEN, and BLUE. The input argument Array is ignored. The keyword PLANARCONFIG must be set to 2 in this case.

TIFF_WRITE, 'a.tif', RED = r, GREEN = g, BLUE = b, PLAN = 2

See Also

TIFF_READ


TIME_TEST

The TIME_TEST procedure is a general-purpose IDL benchmark program that performs approximately 20 common operations and prints the time required.

This routine is written in the IDL language. Its source code can be found in the file time_test.pro in the lib subdirectory of the IDL distribution. This file also contains the procedure GRAPHICS_TIMES, used to time graphical operations.

Calling Sequence

TIME_TEST [, Filename]

Arguments

Filename

An optional string that contains the name of output file for the results of the time test.

Sample Timings

Table 1.16 shows sample timings for various platforms. We make no claim that these times are a fair or accurate measure of computer performance. In particular, different versions of IDL were used. Graphics performance varies greatly, depending largely on the window system, or lack of thereof. The chart shows the total computational time for the test and geometric average time (as reported by TIME_TEST) followed by the total graphics time and geometric average (as reported by GRAPHICS_TIMES).

Machine	Total Comp. Time	Geo. Avg.	Total Graph Time	Geo. Avg.
MicroVAX II, VMS 5.1, 16MB	637	14.4	39.9	6.57
MicroVAX II, Ultrix 3.0, 16MB	616	13.9	58.1	8.27
Sun 3/110, SunOS 4.0, 12MB	391	8.19	32.0	7.81
Sun 3/80, 12MB, 24-bit color	282	6.03	89.3	21.7
PC 386 25MHz, 80387, MS-DOS, 4MB	276	6.9	29.5	5.94
Mips R2030, RISC/os 4.1, 8MB	246	3.67	14.6	2.62
VAXStation 3100, VMS 5.1, 16MB	235	5.13	24.3	3.71
HP 9000, Model 375, ?? ??	163	4.14	20.8	3.37
DecStation 3100, UWS 2.1, 16MB	150	4.00	17.6	3.23
486 33mhz Intel, MS Windows, 8MB	70	1.81	12.9	3.00
Sun 4/65, SunOS 4.1, 16MB	66	1.81	7.0	1.64
Silicon Graphics 4D/25, ??	51	1.38	19.4	2.44
Sun 4/50 IPX, 16MB	40	1.03	7.7	8.80
IBM 6000 Model 325 24MB	40	0.87	5.8	1.21
HP 9000 / 720 48 MB	20	0.52	5.0	0.70
SGI Indigo XS4000, 32MB	20	0.46	2.1	0.44
SGI Indigo2, 150Mhz, 32MB	16	0.32	2.4	0.51
DEC Alpha 3000/500, 224MB	13	0.30	2.3	0.43
Table 1.16 Sample Results from TIME_TEST and GRAPHICS_TEST

Example

TIME_TEST	Run the computational tests.

GRAPHICS_TIMES	Run the graphics tests. Note that TIME_TEST must be compiled before GRAPHICS_TIMES will run.

See Also

SYSTIME


TM_TEST

The TM_TEST function computes the Student's t-statistic and the probability that two sample populations X and Y have significantly different means. X and Y may be of different lengths. The result is a two-element vector containing the T-statistic and its significance. The significance is a value in the interval [0.0, 1.0]; a small value (0.05 or 0.01) indicates that X and Y have significantly different means. The default assumption is that the data is drawn from populations with the same true variance. This type of test is often referred to as the t-means test.

The T-statistic for sample populations x and y with meansx andy is defined as:

where x  = (x0, x1, x2, ..., xN-1) and y = (y0, y 1, y2 ..., yM-1)

This routine is written in the IDL language. Its source code can be found in the file tm_test.pro in the lib subdirectory of the IDL distribution.

Calling Sequence

Result = TM_TEST(X, Y)

Arguments

X

An n-element integer, single-, or double-precision floating-point vector.

Y

An m-element integer, single-, or double-precision floating-point vector. If the PAIRED keyword is set, X and Y must have the same number of elements.

Keywords

PAIRED

If this keyword is set, X and Y are assumed to be paired samples and must have the same number of elements.

UNEQUAL

If this keyword is set, X and Y are assumed to be from populations with unequal variances.

Example

Define two n-element sample populations.

X = [257, 208, 296, 324, 240, 246, 267, 311, 324, 323, 263, $

     305, 270, 260, 251, 275, 288, 242, 304, 267]

Y = [201, 56, 185, 221, 165, 161, 182, 239, 278, 243, 197, $

     271, 214, 216, 175, 192, 208, 150, 281, 196]

Compute the Student's t-statistic and its significance assuming that X and Y belong to populations with the same true variance.

PRINT, TM_TEST(X, Y)

IDL prints:

5.52839  2.52455e-06

The result indicates that X and Y have significantly different means.

See Also

FV_TEST, KW_TEST, RS_TEST, S_TEST


TOTAL

The TOTAL function returns the sum of the elements of Array. The sum of the array elements over a given dimension is returned if the Dimension argument is present.

Calling Sequence

Result = TOTAL(Array [, Dimension])

Arguments

Array

The array to be summed. This array can be of any basic type except string. If Array is double-precision floating-point, complex, or double-precision complex, the result is of the same type. Otherwise, the result is single-precision floating-point.

Dimension

The dimension over which to sum, starting at one. If this argument is not present or zero, the scalar sum of all the array elements is returned. If this argument is present, the result is an array with one less dimension than Array. For example, if the dimensions of Array are N1, N2, N3, and Dimension is 2, the dimensions of the result are (N1, N3), and element (i,j) of the result contains the sum:

Keywords

DOUBLE

Set this keyword to perform the summation in double-precision floating-point.

NAN

Set this keyword to cause the routine to check for occurrences of the IEEE floating-point value NaN in the input data. Elements with the value NaN are treated as missing data. (See  "Special Floating-Point Values" on page 11-9 of the IDL User's Guide for more information on IEEE floating-point values.)

Example

Sum the elements of the array [20, 10, 5, 5, 3] and print the result by entering:

PRINT, TOTAL([20, 10, 5, 5, 3])

IDL prints:

   43.0000

When a multi-dimensional array is used, the results are different, as shown in the following example. Create a five-element by five-element array filled with floating-point values by entering:

A = FINDGEN(5,5)

Display the sums of each of the rows in A by entering:

PRINT, TOTAL(A, 1)

IDL prints:

   10.0000   35.0000   60.0000   85.0000   110.000

Display the sums of each of the columns in A by entering:

PRINT, TOTAL(A, 2)

IDL prints:

   50.0000   55.0000   60.0000   65.0000   70.0000

See Also

FACTORIAL


TRANSPOSE

The TRANSPOSE function returns the transpose of Array. If an optional permutation vector is provided, the dimensions of Array are rearranged as well.

Calling Sequence

Result = TRANSPOSE(Array [, P])

Arguments

Array

The array to be transposed.

P

A vector specifying how the dimensions of Array will be permuted. The elements of P correspond to the dimensions of Array; the ith dimension of the output array is dimension P(i) of the input array. Each element of the vector P must be unique. Dimensions start at zero and can not be repeated.

If P  is not present, the order of the indices of Array is reversed.

Example

Print a simple array and its transpose by entering:

PRINT, INDGEN(3,3)

PRINT, TRANSPOSE(INDGEN(3,3))

IDL prints the original array:

  0  1  2

  3  4  5

  6  7  8

and its transpose:

  0  3  6

  1  4  7

  2  5  8

To see how a multi-dimensional transposition works, first create a three-dimensional array A:

A = INDGEN(2, 3, 4)

Take the transpose, reversing the order of the indices:

B = TRANSPOSE(A)

Now re-order the dimensions of A, so that the second dimension becomes the first, the third becomes the second, and the first becomes the third:

C = TRANSPOSE(A, [1, 2, 0])

Now view the sizes of the three arrays:

HELP, A, B, C

IDL prints:

A   INT  = Array(2, 3, 4)	The original array.

B   INT  = Array(4, 3, 2)	Original array with indices reversed.

C   INT  = Array(3, 4, 2)	Original array with indices re-ordered.

See Also

REFORM, ROT,  ROTATE, REVERSE


TRI_SURF

The TRI_SURF function interpolates a regularly- or irregularly-gridded set of points with a smooth quintic surface. The result is s a two-dimensional floating-point array containing the interpolated surface, sampled at the grid points.

TRI_SURF is similar to MIN_CURVE_SURF but the surface fitted is a smooth surface, not a minimum curvature surface. TRI_SURF has the advantage of being much more efficient for larger numbers of points.

This routine is written in the IDL language. Its source code can be found in the file tri_surf.pro in the lib subdirectory of the IDL distribution.

Calling Sequence

Result = TRI_SURF(Z [, X, Y])

Arguments

X, Y, Z

arrays containing the X, Y, and Z coordinates of the data points on the surface. Points need not be regularly gridded. For regularly gridded input data, X and Y are not used: the grid spacing is specified via the XGRID and YGRID (or XVALUES and YVALUES) keywords, and Z must be a two dimensional array. For irregular grids, all three parameters must be present and have the same number of elements.

Keywords

EXTRAPOLATE

Set this keyword to cause TRI_SURF to extrapolate the surface to points outside the convex hull of input points. This keyword has no effect if the input points are regularly gridded.

MISSING

Set this keyword equal to the value to which points outside the convex hull of input points should be set. The default is 0. This keyword has no effect if the input points are regularly gridded.

Input grid description:

REGULAR

If set, the Z parameter is a two-dimensional array of dimensions (n,m), containing measurements over a regular grid. If any of XGRID, YGRID, XVALUES, or YVALUES are specified, REGULAR is implied. REGULAR is also implied if there is only one parameter, Z. If REGULAR is set, and no grid specifications are present, the grid is set to (0, 1, 2, ...).

XGRID

A two-element array, [xstart, xspacing], defining the input grid in the x direction. Do not specify both XGRID and XVALUES.

XVALUES

An n-element array defining the x locations of Z(i,j). Do not specify both XGRID and XVALUES.

YGRID

A two-element array, [ystart, yspacing], defining the input grid in the y direction. Do not specify both YGRID and YVALUES.

YVALUES

An n-element array defining the y locations of Z(i,j). Do not specify both YGRID and YVALUES.

Output grid description:

Note: The output grid must enclose the convex hull of the input points.

GS

The output grid spacing. If present, GS must be a two-element vector [xs, ys], where xs is the horizontal spacing between grid points and ys is the vertical spacing. The default is based on the extents of x and y . If the grid starts at x value xmin and ends at xmax, then the default horizontal spacing is (xmax - xmin )/(NX-1). YS is computed in the same way. The default grid size, if neither NX or NY are specified, is 26 by 26.

BOUNDS

If present, BOUNDS must be a four-element array containing the grid limits in x and y of the output grid: [xmin, ymin, xmax, ymax]. If not specified, the grid limits are set to the extent of x and y.

NX

The output grid size in the x direction. NX need not be specified if the size can be inferred from GS and BOUNDS. The default value is 26.

NY

The output grid size in the y direction. NY need not be specified if the size can be inferred from GS and BOUNDS. The default value is 26.

Examples

Example 1: Irregularly gridded cases

Make a random set of points that lie on a Gaussian:

N = 15	Number of random points

X = RANDOMU(seed, N)

Y = RANDOMU(seed, N)

Z = EXP(-2 * ((X-.5)^2 + (Y-.5)^2))	The Gaussian

Use a 26 by 26 grid over the rectangle bounding x and y:

R = TRI_SURF(Z, X, Y)	Get the surface

Alternatively, get a surface over the unit square, with spacing of 0.05:

R = TRI_SURF(z, x, y, GS=[0.05, 0.05], BOUNDS=[0,0,1,1])

Alternatively, get a 10 by 10 surface over the rectangle bounding x and y:

R = TRI_SURF(z, x, y, NX=10, NY=10)

Example 2: Regularly gridded cases

z = randomu(seed, 5, 6)	Make some random data

CONTOUR, TRI_SURF(z, /REGULAR)	Interpolate to a 26 x 26 grid

See Also

CONTOUR, MIN_CURVE_SURF


TRIANGULATE

The TRIANGULATE procedure constructs a Delaunay triangulation of a planar set of points. Delaunay triangulations are very useful for the interpolation, analysis, and visual display of irregularly-gridded data. In most applications, after the irregularly gridded data points have been triangulated, the function TRIGRID is invoked to interpolate surface values to a regular grid.

Since Delaunay triangulations have the property that the circumcircle of any triangle in the triangulation contains no other vertices in its interior, interpolated values are only computed from nearby points.

TRIANGULATE can, optionally, return the adjacency list that describes, for each node, the adjacent nodes in the Delaunay triangulation. With this list, the Voronoi polygon (the polygon described by the set of points which are closer to that node than to any other node) can be computed for each node. This polygon contains the area influenced by its associated node. Tiling of the region in this manner is also called Dirichlet, Wigner-Seithz, or Thiessen tessellation.

The grid returned by the TRIGRID function can be input to various routines such as SURFACE, TV, and CONTOUR. See the description of TRIGRID for an example.

TRIANGULATE and TRIDGRID can also be used to perform gridding and interpolation over the surface of a sphere. The interpolation is C1 continuous, meaning that the result is continuous over both the function value and its first derivative. This feature is ideal for interpolating an irregularly-sampled dataset over part or all of the surface of the earth (or other planets). Extrapolation outside the convex hull of sample points is also supported. To perform spherical gridding, you must include the FVALUE and SPHERE keywords described below. The spherical gridding technique used in IDL is based on the paper "Interpolation of Data on the Surface of a Sphere", R. Renka, Oak Ridge National Laboratory Report ORNL/CSD-108, 1982.

Calling Sequence

TRIANGULATE, X, Y, Triangles [, B]

Arguments

X

An array that contains the X coordinates of the points to be triangulated.

Y

An array that contains the Y coordinates of the points to be triangulated. Parameters X and Y must have the same number of elements.

Triangles

A named variable that, on exit, contains the list of triangles in the Delaunay triangulation of the points specified by X and Y. Triangles is a longword array dimensioned (3, Number-of-Triangles), where Triangles(0, i), Triangles(1, i), and Triangles(2, i) contain the indices of the vertices of the i-th triangle (i.e., X(Tr(*, i)) and Y(Triangles(*, i)) are the X and Y coordinates of the vertices of the i-th triangle).

B

An optional, named variable that, upon return, contains a list of the indices of the boundary points in counterclockwise order.

Keywords

CONNECTIVITY

Set this keyword to a named variable in which the adjacency list for each of the N nodes (xy point) is returned. The list has the following form:

Each element i, i ≤ 0 < N , contains the starting index of the connectivity list for node i within the list array. To obtain the adjacency list for node i, extract the list elements from LIST(i) to LIST( i+1)-1.

The adjacency list is ordered in the counter-clockwise direction. The first item on the list of boundary nodes is the subscript of the node itself. For interior nodes, the list contains the subscripts of the adjacent nodes in counter-clockwise order.

For example, the call:

TRIANGULATE, X, Y, CONNECTIVITY = LIST

returns the adjacency list in the variable LIST. The subscripts of the nodes adjacent to X(i) and Y(i) are contained in the array:

LIST(LIST(i) : LIST(i+1)-1)

DEGREES

Set this keyword to indicate that the X and Y arguments contain longitude and latitude coordinates specified in degrees. This keyword is only effective if the SPHERE keyword is also set. If DEGREES is not set, X and Y are assumed to be specified in radians when a spherical triangulation is performed.

FVALUE

Set this keyword to a named variable that contains sample values for each longitude/latitude point in a spherical triangulation. On output, the elements of FVALUE are rearranged to correspond to the new ordering of X and  Y (as described in the SPHERE keyword, below). This reordered array can be passed to TRIGRID to complete the interpolation.

REPEATS

Set this keyword to a named variable to return a (2, n) list of the indices of duplicated points. That is, for each i,

X(REPEATS(0,i)) = X(REPEATS(1,i))

and

Y(REPEATS(0,i)) = Y(REPEATS(1,i))

SPHERE

Set this keyword to a named variable in which the results from a spherical triangulation are returned. This result is a structure that can be passed to TRIGRID to perform spherical gridding. The structure contains the 3D Cartesian locations sample points and the adjacency list that describes the triangulation.

When spherical triangulation is performed, X and Y are interpreted as longitude and latitude, in either degrees or radians (see the DEGREE keyword, above). Also, the order of the elements within the X and Y parameters is rearranged (see the FVALUE keyword, above).

Example

For a examples using the TRIANGULATE routine, see the TRIGRID function.

See Also

SPH_SCAT, TRIGRID


TRIGRID

Given data points defined by the parameters X, Y, and Z and a triangulation of the planar set of points determined by X and Y, the TRIGRID function returns a regular grid of interpolated Z values. Linear or smooth quintic polynomial interpolation can be selected. Extrapolation for gridpoints outside of the triangulation area is also an option. The resulting grid is a two-dimensional array of the same data type as Z, with user-specified bounds and spacing. An input triangulation can be constructed using the procedure TRIANGULATE. Together, the TRIANGULATE procedure and the TRIGRID function constitute IDL's solution to the problem of irregularly-gridded data, including spherical gridding.

Calling Sequence

Result = TRIGRID(X, Y, Z, Triangles [, GS, Limits])

or, for spherical gridding:

Result = TRIGRID(F [, GS, Limits], SPHERE=S)

Arguments

X, Y, Z

Input arrays of X, Y, and Z coordinates of data points. Integer, long, double-precision and floating-point values are allowed. In addition, Z can be a complex array. All three arrays must have the same number of elements.

F

When performing a spherical gridding, this argument should be the named variable that contains the rearranged sample values that were returned by TRIANGULATE's FVALUE keyword.

Triangles

A longword array of the form output by TRIANGULATE. That is, Triangles has the dimensions (3, Number-of-Triangles) and, for each i, Triangles(0,i), Triangles(1,i), and Triangles(2,i) are the indices of the vertices of the i-th triangle.

GS

If present, GS should be a two-element vector [XS, YS], where XS is the horizontal spacing between grid points and YS is the vertical spacing. The default is based on the extents of X and Y. If the grid starts at X value x0 and ends at x1,then the horizontal spacing is

(X1- X0)/50

The default for YS is computed in the same way. Since the default grid spacing divides each axis into 50 intervals and produces 51 samples, TRIGRID returns a grid with dimensions (51, 51).

For spherical gridding, GS is assumed to be specified in radians, unless the DEGREES keyword is set.

Limits

If present, Limits should be a four-element vector [x0, y0, x1, y1], where x0 and y0 are the lower X and Y grid limits, and x1 and y1 are the upper limits. The default for Limits is:

[MIN(X), MIN(Y), MAX(X), MAX(Y)]

Keywords

DEGREES

For a spherical gridding, set this keyword to indicate that the grid spacing (the GS argument) is specified in degrees rather than radians.

EXTRAPOLATE

This keyword sets the quintic interpolation mode. TRIGRID extrapolates to grid points outside the triangulation if this keyword is assigned to the array of boundary node indices returned by the optional parameter B of the TRIANGULATE procedure. The extrapolation is not smooth, but should give acceptable results in most cases.

INPUT

Set this keyword to a named variable (which must be an array of the appropriate size to hold the output from TRIGRID) in which the results of the gridding are returned. This keyword is provided to make it easy and memory-efficient to perform multiple calls to TRIGRID. The interpolates within each triangle overwrite the array and the array is not initialized.

MAX_VALUE

Set this keyword to a value that represents the maximum Z value to be gridded. Data larger than this value are treated as missing data and are not gridded.

MIN_VALUE

Set this keyword to a value that represents the minimum Z value to be gridded. Data smaller than this value are treated as missing data and are not gridded.

MISSING

The Z value to be used for grid points that lie outside the triangles in Triangles. The default is 0.

QUINTIC

If QUINTIC is set, smooth interpolation is performed using Akima's quintic polynomials from "A Method of Bivariate Interpolation and Smooth Surface Fitting for Irregularly Distributed Data Points" in ACM Transactions on Mathematical Software, 4, 148-159. The default method is linear interpolation.

Derivatives are estimated by Renka's global method in "A Triangle-Based C1 Interpolation Method" in Rocky Mountain Journal of Mathematics, vol. 14, no. 1, 1984.

QUINTIC is not available for complex data values.

SPHERE

For a spherical gridding, set this keyword to the named variable that contains the results of the spherical triangulation returned by TRIANGULATE's SPHERE keyword.

Example

The first example creates and displays a 50 point random normal distribution. The random points are then triangulated, with the triangulation displayed. Next, the interpolated surface is computed and displayed using linear and quintic interpolation. Finally, the smooth extrapolated surface is generated and shown.

x = RANDOMN(seed, 50)	Make 50 normal XY points.

y = RANDOMN(seed, 50)

z = EXP(-(x^2 + y^2))	Make the Gaussian.

PLOT, x, y, psym=1	Show points.

TRIANGULATE, x, y, tr, b	Obtain triangulation.

FOR i=0, N_ELEMENTS(tr)/3-1 DO BEGIN
Show the triangles.

  t = [tr(*,i), tr(0,i)]	Subscripts of vertices [0,1,2,0].

  PLOTS, x(t), y(t)	Connect triangles.

ENDFOR

SURFACE, TRIGRID(x, y, z, tr)	Show linear surface.

SURFACE, TRIGRID(x, y, z, tr, /QUINTIC)
Show smooth quintic surface.

SURFACE, TRIGRID(x, y, z, tr, EXTRA = b)
Show smooth extrapolated surface.

The next example shows how to perform spherical gridding:

lon = RANDOMU(seed, 50) * 360. - 180.
Create some random longitude points.

lat = RANDOMU(seed, 50) * 180. - 90.
Create some random latitude points.

f = SIN(lon * !DTOR)^2 * COS(lat * !DTOR)
Make a fake function value to be passed to FVALUE. The system variable !DTOR contains the conversion value for degrees to radians.

TRIANGULATE, lon, lat, tr, SPHERE=s, FVALUE=f, /DEGREES
Perform a spherical triangulation.

r=TRIGRID(f, SPHERE=s, [2.,2.], [-180.,-90.,178.,90.], /DEGREES
Perform a spherical triangulation using the values returned from TRIANGULATE. The result, r, is a 180 by 91 element array.

See Also

SPH_SCAT, TRIANGULATE


TRIQL

The TRIQL procedure uses the QL algorithm with implicit shifts to determine the eigenvalues and eigenvectors of a real, symmetric, tridiagonal array. The routine TRIRED can be used to reduce a real, symmetric array to the tridiagonal form suitable for input to this procedure.

TRIQL is based on the routine tqli described in section 11.3 of Numerical Recipes in C: The Art of Scientific Computing (Second Edition), published by Cambridge University Press, and is used by permission.

Calling Sequence

TRIQL, D, E, A

Arguments

D

On input, this argument should be an n-element vector containing the diagonal elements of the array being analyzed. On output, D contains the eigenvalues.

E

An n-element vector containing the off-diagonal elements of the array. E0 is arbitrary. On output, this parameter is destroyed.

A

A named variable that returns the n eigenvectors.

If the eigenvectors of a tridiagonal array are desired, A should be input as an identity array. If the eigenvectors of an array that has been reduced by TRIRED are desired, A is input as the array Q  output by TRIRED.

Keywords

DOUBLE

Set this keyword to force the computation to be done in double-precision arithmetic.

Example

To compute eigenvalues and eigenvectors of a real, symmetric, tridiagonal array, begin with an array A representing a symmetric array.

A = [[ 3.0,  1.0, -4.0], $

     [ 1.0,  3.0, -4.0], $

     [-4.0, -4.0,  8.0]]

TRIRED, A, D, E	Compute the tridiagonal form of A.

Compute the eigenvalues (returned in vector D) and the eigenvectors (returned in the rows of the array A):

TRIQL, D, E, A

PRINT, D	Print eigenvalues.

IDL prints:

  2.00000  4.76837e-7  12.0000

The exact values are:

  [2.0, 0.0, 12.0]

PRINT, A	Print eigenvectors.

IDL prints:

  0.707107  -0.707107   0.00000

 -0.577350  -0.577350  -0.577350

 -0.408248  -0.408248   0.816497

The exact eigenvectors are:

 [ 1.0/sqrt(2.0), -1.0/sqrt(2.0), 0.0/sqrt(2.0)],

 [-1.0/sqrt(3.0), -1.0/sqrt(3.0), -1.0/sqrt(3.0)],

 [-1.0/sqrt(6.0), -1.0/sqrt(6.0), 2.0/sqrt(6.0)

See Also

EIGENVEC, ELMHES, HQR, TRIRED


TRIRED

The TRIRED procedure uses Householder's method to reduce a real, symmetric array to tridiagonal form.

TRIRED is based on the routine tred2 described in section 11.2 of Numerical Recipes in C: The Art of Scientific Computing (Second Edition), published by Cambridge University Press, and is used by permission.

Calling Sequence

TRIRED, A, D, E

Arguments

A

An n by n real, symmetric array that is replaced, on exit, by the orthogonal array Q effecting the transformation. The routine TRIQL can use this result to find the eigenvectors of the array A.

D

An n-element output vector containing the diagonal elements of the tridiagonal array.

E

An n-element output vector containing the off-diagonal elements.

Keywords

DOUBLE

Set this keyword to force the computation to be done in double-precision arithmetic.

Example

See the description of TRIQL for an example using this function.

See Also

EIGENVEC, ELMHES, HQR, TRIQL, TRIRED


TRISOL

The TRISOL function solves tridiagonal systems of linear equations that have the form: A^TU = R

Note: because IDL subscripts are in column-row order, the equation above is written A^TU = R rather than AU = R. The result U is a vector of length n whose type is identical to A.

TRISOL is based on the routine tridag described in section 2.4 of Numerical Recipes in C: The Art of Scientific Computing (Second Edition), published by Cambridge University Press, and is used by permission.

Calling Sequence

Result = TRISOL(A, B, C, R)

Arguments

A

A vector of length n containing the n-1 sub-diagonal elements of A^T. The first element of A, A0, is ignored.

B

An n-element vector containing the main diagonal elements of A^T.

C

An n-element vector containing the n-1 super-diagonal elements of A^T. The last element of C,  Cn-1, is ignored.

R

An n-element vector containing the right hand side of the linear system
 A^TU = R.

Keywords

DOUBLE

Set this keyword to force the computation to be done in double-precision arithmetic.

Example

To solve a tridiagonal linear system, begin with an array representing a real tridiagonal linear system. (Note that only three vectors need be specified; there is no need to enter the entire array shown.)

  [-4.0,  1.0,  0.0,  0.0]

  [ 2.0, -4.0,  1.0,  0.0]

  [ 0.0,  2.0, -4.0,  1.0]

  [ 0.0,  0.0,  2.0, -4.0]

Define a vector A containing the sub-diagonal elements with a leading 0.0 element:

A = [0.0, 2.0, 2.0, 2.0]

Define B containing the main diagonal elements:

B = [-4.0, -4.0, -4.0, -4.0]

Define C containing the super-diagonal elements with a trailing 0.0 element:

C = [1.0, 1.0, 1.0, 0.0]

Define the right-hand side vector:

R = [6.0, -8.0, -5.0, 8.0]

Compute the solution and print:

result = TRISOL(A, B, C, R)

PRINT, result

IDL prints:

  -1.00000  2.00000  2.00000  -1.00000

The exact solution vector is [-1.0, 2.0, 2.0, -1.0].

See Also

CRAMER, GS_ITER, LU_COMPLEX, CHOLSOL, LUSOL, SVSOL, TRISOL


TRNLOG
TRNLOG (VMS Only)

The TRNLOG function searches the VMS logical name tables for a specified logical name and returns the equivalence string(s) in an IDL variable. TRNLOG also returns the VMS status code associated with the translation as a longword value. As with all VMS status codes, success is indicated by an odd value (least significant bit is set) and failure by an even value.

Calling Sequence

Result = TRNLOG(Lognam, Value)

Arguments

Lognam

A scalar string containing the name of the logical to be translated.

Value

A named variable into which the equivalence string is placed. If Lognam has more than one equivalence string, the first one is used. The FULL_TRANSLATION keyword can be used to obtain all equivalence strings.

Keywords

ACMODE

The access mode to be used in the translation. The possible access modes are:

Mode	Value
Kernal	0
Executive	1
Supervisor	2
User	3
Table 1.17 TRNLOG Access Modes

When you specify the ACMODE keyword, all names at access modes less privileged than the specified mode are ignored. If you do not specify ACMODE, the translation proceeds without regard to access mode. However, the search proceeds from the outermost (User) to the innermost (Kernal) mode. Thus, if two logical names with the same name but different access modes exist in the same table, the name with the outermost access mode is used.

FULL_TRANSLATION

Set this keyword to obtain the full set of equivalence strings for Lognam . By default, when translating a multivalued logical name, Value only receives the first equivalence string as a scalar value. When this keyword is set, Value instead returns a string array. Each element of this array contains one of the equivalence strings. For example, under recent versions of VMS, the SYS$SYSROOT logical can have multiple values. To see these values from within IDL, enter:

ret = TRNLOG('SYS$SYSROOT', trans, /FULL, /ISSUE_ERROR)
Translate the logical.

PRINT, trans	View the equivalence strings.

ISSUE_ERROR

Set this keyword to issue an error message if the translation fails. Normally, no error is issued and the user must examine the return value to determine if the operation failed.

RESULT_ACMODE

If present, this keyword specifies a named variable in which to place the access mode of the translated logical. The access modes are summarized above.

RESULT_TABLE

If present, this keyword specifies a named variable. The name of the logical table containing the translated logical is placed in this variable as a scalar string.

TABLE

A scalar string giving the name of the logical table in which to search for Lognam. If TABLE is not specified, the standard VMS logical tables are searched until a match is found, starting with LNM$PROCESS_TABLE and ending with LNM$SYSTEM_TABLE.


TS_COEF

The TS_COEF function computes the coefficients φ1, φ2, ... , φP used in a Pth order autoregressive time-series forecasting model. The result is a P-element vector whose type is identical to X.

This routine is written in the IDL language. Its source code can be found in the file ts_coef.pro in the lib subdirectory of the IDL distribution.

Calling Sequence

Result = TS_COEF(X, P)

Arguments

X

An n-element single- or double-precision floating-point vector containing time-series samples.

P

An integer or long integer scalar that specifies the number of coefficients to be computed.

Keywords

MSE

Use this keyword to specify a named variable that will contain the mean square error of the Pth order autoregressive model.

Example

Define an n-element vector of time-series samples.

X = [6.63, 6.59, 6.46, 6.49, 6.45, 6.41, 6.38, 6.26, 6.09, 5.99, $

     5.92, 5.93, 5.83, 5.82, 5.95, 5.91, 5.81, 5.64, 5.51, 5.31, $

     5.36, 5.17, 5.07, 4.97, 5.00, 5.01, 4.85, 4.79, 4.73, 4.76]

Compute the coefficients of a 5th order autoregressive model.

result = TS_COEF(X, 5)

PRINT, result

IDL prints:

1.30168    -0.111783    -0.224527     0.267629    -0.233363

See Also

TS_FCAST


TS_DIFF

The TS_DIFF function recursively computes the forward differences of an n-element time-series k times. The result is an n-element differenced time-series with its last k elements as zeros.

This routine is written in the IDL language. Its source code can be found in the file ts_diff.pro in the lib subdirectory of the IDL distribution.

Calling Sequence

Result = TS_DIFF(X, K)

Arguments

X

An n-element integer, single- or double-precision floating-point vector containing time-series samples.

K

A positive integer or long integer scalar that specifies the number of times X is to be differenced. K must be in the interval [1, N_ELEMENTS(X) - 1].

Example

Define an n-element vector of time-series samples:

X = [389, 345, 303, 362, 412, 356, 325, 375, $

     410, 350, 310, 388, 399, 362, 325, 382, $

     399, 382, 318, 385, 437, 357, 310, 391]

Compute the second forward differences of X and print:

PRINT, TS_DIFF(X, 2)

IDL prints:

  2  101   -9 -106   25   81  -15  -95   20

118  -67  -48    0   94  -40  -34  -47  131

-15 -132   33  128    0    0

See Also

SMOOTH, TS_FCAST


TS_FCAST

The TS_FCAST function computes future values of a stationary time-series using a Pth order autoregressive model. The result is an N_future-element vector whose type is identical to X.

A Pth order autoregressive model relates a forecasted value xt of the time series X = [x0, x1, x2, ... , xt-1], as a linear combination of P past values.

The coefficients φ1, φ2, ... , φP are calculated such that they minimize the uncorrelated random error terms, wt.

This routine is written in the IDL language. Its source code can be found in the file ts_fcast.pro in the lib subdirectory of the IDL distribution.

Calling Sequence

Result = TS_FCAST(X, P, N_future)

Arguments

X

An n-element single- or double-precision floating-point vector containing time-series samples.

P

An integer or long integer scalar that specifies the number of past time-series values to be used in the forecast. In general, a larger number of values results in a more accurate forecast.

N_future

An integer or long integer scalar that specifies the number of future values to be computed.

Example

Define an n-element vector of time-series samples:

X = [6.63, 6.59, 6.46, 6.49, 6.45, 6.41, 6.38, 6.26, 6.09, 5.99, $

     5.92, 5.93, 5.83, 5.82, 5.95, 5.91, 5.81, 5.64, 5.51, 5.31, $

     5.36, 5.17, 5.07, 4.97, 5.00, 5.01, 4.85, 4.79, 4.73, 4.76]

Compute the five future values of the time-series using ten past values.

PRINT, TS_FCAST(X, 10, 5)

IDL prints:

4.65870      4.58380      4.50030      4.48828      4.46971

See Also

A_CORRELATE, COMFIT, CURVEFIT, TS_COEF


TV

The TV procedure displays images on the image display without scaling the intensity. To display an image with scaling, use the TVSCL procedure.

Note that while TV does not scale the intensity of an image, it does convert the input image data to byte type. Values outside the range [0,255] are "wrapped" during the conversion. In addition, for displays with less than 256 colors, elements of the input image with values between !D.TABLE_SIZE and 255 will be displayed using the color index !D.TABLE_SIZE-1.

Calling Sequence

TV,  Image [, Position]

or

TV, Image [, X, Y [, Channel]]

Arguments

Image

A vector or two-dimensional array to be displayed as an image. If this argument is not already of byte type, it is converted prior to use.

X, Y

If X and Y are present, they specify the lower-left coordinate of the displayed image, relative to the lower-left corner of the screen.

Position

An integer specifying the position for Image within the graphics window. Image positions run from the top left of the screen to the bottom right. If a position number is used instead of X and Y , the position of the image is calculated from the dimensions of the image as follows (integer arithmetic is used):

For example, when displaying 128 by 128 images on a 512 by 512 display, the position numbers run from 0 to 15 as follows:

0	1	2	3
4	5	6	7
8	9	10	11
12	13	14	15
Channel

The memory channel to be written. It is assumed to be zero if not specified. This parameter is ignored on display systems that have only one memory channel. When using a "decomposed" display system, the red channel is 1, the green channel is 2, and the blue channel is 3. Channel 0 indicates all channels.

Keywords

CENTIMETERS

Set this keyword to indicate that the X, Y, Xsize, Ysize, and Z arguments are given in centimeters from the origin. This system is useful when dealing with devices, such as PostScript printers, that do not provide a direct relationship between image pixels and the size of the resulting image.

CHANNEL

The memory channel to be written. The effect of this keyword parameter is identical to the  Channel positional parameter. Either one can be used.

DATA

Set this keyword to indicate that all position and size values are given in data coordinates. This system is useful when drawing an image over an existing plot, since the plot establishes the data scaling.

DEVICE

Set this keyword to indicate that all position and size values are given in device coordinates (the default).

INCHES

Set this keyword to indicate that all position and size values are given in inches from the origin. This system is useful when dealing with devices, such as PostScript printers, that do not provide a direct relationship between image pixels and the size of the resulting image.

NORMAL

Set this keyword to indicate that all position and size values are given in normalized coordinates in the range 0 to 1.0, inclusive. This system is useful when it is desired to position the image in a device-independent manner.

ORDER

If specified, ORDER overrides the current setting of the !ORDER system variable for the current image only. If set, the image is drawn from the top down instead of the normal bottom up.

T3D

Set this keyword to use the generalized transformation matrix stored in !P.T. If not present, the user-supplied coordinates are simply scaled to screen coordinates. For a description of !P.T and how it is used, see the description of the SAVE keyword to the SURFACE procedure (page 1-869).

TRUE

Set this keyword to a nonzero value to indicate that a true-color image is to be displayed. The value assigned to TRUE specifies the index of the dimension over which color is interleaved. The image parameter must have three dimensions, one of which must be equal to three. For example, set TRUE to 1 to display an image that is pixel interleaved and has dimensions of (3, m, n). Specify 2 for row-interleaved images, of size (m, 3, n ), and 3 for band-interleaved images of the form (m, n, 3).

Use this keyword to write 24-bit images to the PostScript device. See page 3-42 for an example.

WORDS

Set this keyword to indicate that words (short integers) instead of 8-bit bytes are to be transferred to the device. This keyword is valid only when using devices that can transfer 16-bit pixels. The normal transfer uses 8-bit pixels. If this keyword is set, the Image parameter is converted to short integer type, if necessary, and then written to the display.

XSIZE

The width of the resulting image. On devices with scalable pixel size (such as PostScript), if XSIZE is specified the image will be scaled to fit the specified width. If neither XSIZE nor YSIZE is specified, the image will be scaled to fill the plotting area, while preserving the image's aspect ratio. This keyword is ignored by pixel-based devices that are unable to change the size of their pixels.

YSIZE

The height of the resulting image. On devices with scalable pixel size (such as PostScript), if YSIZE is specified the image will be scaled to fit the specified height. If neither XSIZE nor YSIZE is specified, the image will be scaled to fill the plotting area, while preserving the image's aspect ratio. This keyword is ignored by pixel-based devices that are unable to change the size of their pixels.

Z

The Z position for the image. The value of Z is used only if the three-dimensional transformation made active via the T3D keyword.

Example

Create and display a simple image by entering:

D = BYTSCL(DIST(256)) & TV, D

Erase the screen by entering:

ERASE

Use the position parameter to display a number of images in the same window. Display the image in the upper left corner by entering:

TV, D, 0

Display another copy of the image in the next position by entering:

TV, D, 1

See Also

ERASE, SLIDE_IMAGE, TVRD, TVSCL, WIDGET_DRAW, WINDOW


TVCRS

The TVCRS procedure manipulates the display device cursor. The initial state of the cursor is device dependent. Call TVCRS with one argument to enable or disable the cursor. Call TVCRS with two parameters to enable the cursor and place it on pixel location (X, Y).

Calling Sequence

TVCRS  [, ON_OFF]

or

TVCRS [, X, Y]

Arguments

ON_OFF

This argument specifies whether the cursor should be on or off. If this argument is present and nonzero, the cursor is enabled. If ON_OFF is zero or no parameters are specified, the cursor is turned off.

X

The column to which the cursor is set.

Y

The row to which the cursor is set.

Keywords

CENTIMETERS

Set this keyword to cause X and Y to be interpreted as centimeters, based on the current device resolution.

INCHES

Set this keyword to cause X and Y to be interpreted as inches, based on the current device resolution.

HIDE_CURSOR

By default, disabling the cursor works differently for window systems than for other devices. For window systems, the cursor is restored to the standard cursor used for non-IDL windows (and remains visible), while for other devices it is completely blanked out. If the HIDE keyword is set, disabling the cursor causes it to always be blanked out.

Graphics Keywords Accepted

See Chapter 2, "Graphics Keywords and System Variables", for the description of graphics and plotting keywords not listed above. DATA DEVICE NORMAL T3D Z.

Example

To enable the graphics cursor and position it at device coordinate (100, 100), enter:

TVCRS, 100, 100

To position the cursor at data coordinate (0.5, 3.2), enter:

TVCRS, 0.5, 3.2, /DATA

See Also

CURSOR, RDPIX


TVLCT

The TVLCT procedure loads the display color translation tables from the specified variables. Although IDL uses the RGB color system internally, color tables can be specified to TVLCT using any of the following color systems: RGB (Red, Green, Blue), HLS (Hue, Lightness, Saturation), and HSV (Hue, Saturation, Value). The type and meaning of each argument is dependent upon the color system selected, as described below. Color arguments can be either scalar or vector expressions. If no color-system keywords are present, the RGB color system is used. See Chapter 16 of the IDL User's Guide for a more complete explanation of color systems.

Calling Sequence

TVLCT, V1, V2, V3 [, Start]

or

TVLCT, V [, Start]

Arguments

TVLCT will accept either three n-element vectors (V1, V2, and V3 ) or a single n by 3 array (V) as an argument. If an array V is specified, V(*,0) is the same as V1 , V(*,1) is the same as V2, and V(*,2) is the same as V3. In the description below we assume that three vectors V1, V2, and V3  are specified.

The V1 , V2, and V3 arguments have different meanings depending upon which color system they represent.

R, G, B Color System

The parameters V1, V2, and V3 contain the Red, Green, and Blue values respectively. Values are interpreted as integers in the range 0 (lowest intensity) to 255 (highest intensity). The parameters can be scalars or vectors of up to 256 elements. By default, the three arguments are assumed to be R, G, and B values.

H, L, S Color System

Parameters V1, V2, and V3 contain the Hue, Lightness, and Saturation values respectively. All parameters are floating-point. Hue is expressed in degrees and is reduced modulo 360. V2 (lightness) and V3 (saturation) can range from 0 to 1.0. Set the HLS keyword to have the arguments interpreted this way.

H, S, V Color System

Parameters V1, V2, and V3 contain values for Hue, Saturation, and Value (similar to intensity). All parameters are floating-point. Hue is in degrees. The Saturation and Value can range from 0 to 1.0. Set the HSV keyword to have the arguments interpreted this way.

Start

An integer value that specifies the starting point in the color translation table into which the color intensities are loaded. If this argument is not specified, a value of zero is used, causing the tables to be loaded starting at the first element of the translation tables.

Keywords

GET

Set this keyword to return the RGB values from the internal color tables into the V1, V2, and V3  parameters. For example, the statements:

TVLCT, H, S, V, /HSV

TVLCT, R, G, B, /GET

load a color table based in the HSV system, and then read the equivalent RGB values into the variables R, G, and B.

HLS

Set this keyword to indicate that the parameters specify color using the HLS color system.

HSV

Set this keyword to indicate that the parameters specify color using the HSV color system.

Example

Create a set of R, G, and B colormap vectors by entering the following commands:

R = BYTSCL(SIN(FINDGEN(256)))

G = BYTSCL(COS(FINDGEN(256)))

B = BINDGEN(256)

Load these vectors into the color table by entering:

TVLCT, R, G, B

Display an image to see the effect of the new color table:

TVSCL, DIST(400)

See Also

LOADCT, XLOADCT, XPALETTE


TVRD

The TVRD function returns the contents of the specified rectangular portion of the current graphics window or device. (X0, Y0) is the coordinate of the lower left corner of the area to be read and Nx, Ny is the size of the rectangle in columns and rows. The result is a byte array of dimensions Nx by Ny. All parameters are optional. If no arguments are supplied, the entire display device area is read.

Important Note about TVRD and Backing Store

On some systems, when backing store is provided by the window system (the RETAIN keyword to DEVICE or WINDOW is set to 1), reading data from a window using TVRD may cause unexpected results. For example, data may be improperly read from the window even when the image displayed on screen is correct. Having IDL provide the backing store (set the RETAIN keyword to 2) ensures that the window contents will be read properly. More detailed notes about TVRD and the X Window system can be found below in "Unexpected Results Using TVRD with X Windows" on page 1-953.

Calling Sequence

Result = TVRD([X0 [, Y0 [, Nx [, Ny [, Channel]]]]])

Arguments

X0

The starting column of data to read. The default is 0.

Y0

The starting row of data to read. The default is 0.

Nx

The number of columns to read. The default is the width of the display device or window less X0.

Ny

The number of rows to read. The default is the height of the display device or window less  Y0.

Channel

The memory channel to be read. If not specified, this argument is assumed to be zero. This parameter is ignored on display systems that have only one memory channel.

Keywords

CHANNEL

The memory channel to be read. This keyword parameter is identical to the Channel positional parameter.

Note: if the display is a 24-bit display, and both the CHANNEL and TRUE parameters are absent, the maximum RGB value in each pixel is returned.

ORDER

Set this keyword to override the current setting of the !ORDER system variable for the current image only. If set, it causes the image to be read from the top down instead of the normal bottom up.

TRUE

If this keyword is present, it indicates that a true-color image is to be read, if the display is capable. The value assigned to TRUE specifies the index of the dimension over which color is interleaved. The result is an (3, Nx, Ny) pixel-interleaved array if TRUE is 1; or an (Nx , 3, Ny) line-interleaved array if TRUE is 2; or an (Nx, Ny, 3) image-interleaved array if TRUE is 3.

WORDS

Set this keyword to indicate that words are to be transferred from the device. This keyword is valid only when using devices that can transfer 16-bit pixels. The normal transfer uses 8-bit pixels. If this keyword is set, the function result is an integer array.

Unexpected Results Using TVRD with X Windows

When using TVRD with the X Windows graphics device, there are two unexpected behaviors that can be confusing to users:

•	When reading from a window that is obscured by another window (i.e., the target window has another window "on top" or "in front" of it), TVRD may return the contents of the window in front as part of the image contained in the target window.

•	When reading from an iconified window, the X server may return a stream of "BadMatch" protocol events.

IDL uses the Xlib function XGetSubImage() to implement TVRD. The following quote is from the documentation for XGetSubImage() found in The X Window System by Robert W. Scheifler and James Gettys, Second Edition, page 174. It explains the reasons for the behaviors described above:

"If the drawable is a window, the window must be viewable, and it must be the case that if there were no... overlapping windows, the specified rectangle of the window would be fully visible on the screen, ... or a BadMatch error results. If the window has backing-store, then the backing-store contents are returned for regions of the window that are obscured... If the window does not have backing-store, the returned contents of such obscured regions are undefined."

Hence, the first behavior is caused by attempting to use TVRD on an obscured window that does not have backing store provided by the X server. The result in this case is undefined, meaning that the different servers can produce entirely different results. Many servers simply return the image of the obscuring window.

The second behavior is caused by attempting to read from a non-viewable (i.e., unmapped) window. Although IDL could refuse to allow TVRD to work with unmapped windows, some X servers return valid and useful results. Therefore, TVRD is allowed to attempt to read from unmapped windows.

Both of these behavior problems can be solved by using one of the following methods:

•	Always make sure that your target window is mapped and is not obscured before using TVRD on it. The following IDL command can be used:

WSHOW, Window_Index, ICONIC=0

•	Make IDL provide backing store (rather than the window system) by setting the RETAIN keyword to DEVICE or WINDOW equal to 2.

For a full description of backing store, see "Backing Store" on page 3-27. Note that under X Windows, backing store is a request that may or may not be honored by the X server. Many servers will honor backing store for 8-bit visuals but ignore them for 24-bit visuals because they require three times as much memory.

Example

To read the entire contents of the current display device into the variable T, enter:

T = TVRD()

See Also

RDPIX, TV, WINDOW


TVSCL

The TVSCL procedure scales the intensity values of Image into the range of the image display and outputs the data to the image display at the specified location. The array is scaled so the minimum data value becomes 0 and the maximum value becomes the maximum number of available colors (held in the system variable !D.TABLE_SIZE) as follows:

Output = !D.TABLE_SIZE (Data ­ Datamin) / (Datamax ­ Datamin)

where the maximum and minimum are found by scanning the array. The parameters and keywords of the TVSCL procedure are identical to those accepted by the TV procedure. For additional information about each parameter, consult the description of TV.

Calling Sequence

TVSCL, Image [, Position]

or

TVSCL, Image [, X, Y [, Channel]]

Arguments

Image

A two-dimensional array to be displayed as an image. If this argument is not already of byte type, it is converted prior to use.

X, Y

If X and Y are present, they specify the lower left coordinate of the displayed image.

Position

Image position. See the discussion of the TV procedure for a full description.

Channel

The memory channel to be written. This argument is assumed to be zero if not specified. This parameter is ignored on display systems that have only one memory channel.

Keywords

See the description of the TV procedure for a list and description of accepted keyword parameters.

Example

Display a floating-point array as an image using the TV command. Enter:

TV, DIST(200)

Note that the image is not easily visible because the values in the array have not been scaled into the full range of display values. Now display the image with the TVSCL command by entering:

TVSCL, DIST(200)

Notice how much brighter the image appears.

See Also

ERASE, SLIDE_IMAGE, TV, WIDGET_DRAW, WINDOW


UNIQ

The UNIQ function returns the subscripts of the unique elements in an array. Note that repeated elements must be adjacent in order to be found. This routine is intended to be used with the SORT function. See the examples below. This function was inspired by the Unix uniq(1) command.

UNIQ returns an array of indices into the original array. The following expression is a copy of the sorted array with duplicate adjacent elements removed:

Array(UNIQ(Array))

This routine is written in the IDL language. Its source code can be found in the file uniq.pro in the lib subdirectory of the IDL distribution.

Calling Sequence

Result = UNIQ(Array [, Index])

Arguments

Array

The array to be scanned. For UNIQ to work properly, the array must be sorted into monotonic order unless the optional parameter Idx is supplied.

Index

This optional parameter is an array of indices into Array that order the elements into monotonic order. That is, the expression:

Array(Index)

yields an array in which the elements of Array are rearranged into monotonic order. If the array is not already in monotonic order, use the command:

UNIQ(Array, SORT(Array))

Examples

Find the unique elements of an unsorted array:

array = [1, 2, 1, 2, 3, 4, 5, 6, 6, 5]
Create an array with duplicate elements.

b = array(UNIQ(array, SORT(array)))
Variable B holds an array containing the sorted, unique values in array.

PRINT, b	IDL prints: 1 2 3 4 5 6.

See Also

SORT, WHERE


USERSYM

The USERSYM procedure is used to define the plotting symbol that marks points when the plotting symbol is set to plus or minus 8. Symbols can be drawn with vectors or can be filled. Symbols can be of any size and can have up to 50 vertices. See "Defining Your Own Plotting Symbols" on page 14-12 of the IDL User's Guide.

Calling Sequence

USERSYM, X [, Y]

Arguments

X, Y

The X and/or Y parameters define the vertices of the symbol as offsets from the data point in units of approximately the size of a character. In the case of a vector drawn symbol, the symbol is formed by connecting the vertices in order. If only one argument is specified, it must be a (2, N) array of vertices, with element (0, i) containing the X coordinate of the vertex, and element (1,  i) containing the Y. If both arguments are provided,  X contains only the X coordinates.

Keywords

COLOR

The color used to draw the symbols, or used to fill the polygon. The default color is the same as the line color.

FILL

Set this keyword to fill the polygon defined by the vertices. If FILL is not set, lines are drawn connecting the vertices.

THICK

The thickness of the lines used in drawing the symbol. The default thickness is 1.0.

Example

Make a large, diamond-shaped plotting symbol. Define the vectors of X values by entering:

X = [-6, 0, 6, 0, -6]

Define the vectors of Y values by entering:

Y = [0, 6, 0, -6, 0]

Now call USERSYM to create the new plotting symbol 8. Enter:

USERSYM, X, Y

Generate a simple plot to test the plotting symbol by entering:

PLOT, FINDGEN(20), PSYM = 8

See Also

PLOT, XYOUTS


VEL

The VEL procedure draws a velocity (flow) field with arrows following the field proportional in length to the field strength. Arrows are composed of a number of small segments that follow the streamlines.

This routine is written in the IDL language. Its source code can be found in the file vel.pro in the lib subdirectory of the IDL distribution.

Calling Sequence

VEL,  U, V

Arguments

U

The X component at each point of the vector field. U must be a 2D array.

V

The Y component at each point of the vector field. V must have the same dimensions as U.

Keywords

NVECS

The number of vectors (arrows) to draw. If this keyword is omitted, 200 vectors are drawn.

XMAX

X axis size as a fraction of Y axis size. The default is 1.0. This argument is ignored when !P.MULTI is set.

LENGTH

The length of each arrow line segment expressed as a fraction of the longest vector divided by the number of steps. The default is 0.1.

NSTEPS

The number of shoots or line segments for each arrow. The default is 10.

TITLE

A string containing the title for the plot.

Example

X = DIST(20)	Create a vector of X values.

Y = SIN(X)*100	Create a vector of Y values.

VEL, X, Y	Plot the vector field.

See Also

FLOW3, PLOT_FIELD, VELOVECT


VELOVECT

The VELOVECT procedure produces a two-dimensional velocity field plot. A directed arrow is drawn at each point showing the direction and magnitude of the field.

This routine is written in the IDL language. Its source code can be found in the file velovect.pro in the lib subdirectory of the IDL distribution.

Calling Sequence

VELOVECT, U, V [, X, Y]

Arguments

U

The X component of the two-dimensional field. U must be a two-dimensional array.

V

The Y component of the two dimensional field. V must have the same dimensions as U.

X

Optional abcissae values. X must be a vector with a length equal to the first dimension of U and V.

Y

Optional ordinate values. Y must be a vector with a length equal to the first dimension of U and V.

Keywords

Note: Keywords not described here are passed directly to the PLOT procedure and may be used to set options such as TITLE, POSITION, NOERASE, etc.

COLOR

Set this keyword equal to the color index used for the plot.

DOTS

Set this keyword to 1 to place a dot at each missing point. Set this keyword to 0 or omit it to draw nothing for missing points. Has effect only if MISSING is specified.

LENGTH

Set this keyword equal to the length factor. The default of 1.0 makes the longest (U,V) vector the length of a cell.

MISSING

Set this keyword equal to the missing data value. Vectors with a length greater than MISSING are ignored.

PLOT Keywords

In addition to the keywords described above, all other keywords accepted by the PLOT procedure are accepted by VELOVECT. See "PLOT" on page 1-654.

Example

U = RANDOMN(S, 20, 20)	Create some random data.

V = RANDOMN(S, 20, 20)

VELOVECT, U, V	Plot the vector field.

VELOVECT, U, V, MISSING=18, /DOTS	Plot the field, using dots to represent vectors with values greater than 18.

VELOVECT, U, V, MISSING=18, /DOTS, XTITLE='Random Vectors'
Plot with a title. Note that the XTITLE keyword is passed directly to the PLOT procedure.

See Also

FLOW3, PLOT,  PLOT_FIELD, VEL


VERT_T3D

The VERT_T3D function transforms a 3D array by a 4x4 transformation matrix and returns the transformed array. The 3D points are typically an array of polygon vertices that were generated by SHADE_VOLUME or MESH_OBJ.

This routine is written in the IDL language. Its source code can be found in the file vert_t3d.pro in the lib subdirectory of the IDL distribution.

Calling Sequence

Result = VERT_T3D(Vertex_List)

Arguments

Vertex_List

A 3 x  n array of 3D coordinates to transform.

Keywords

MATRIX

The 4x4 transformation matrix to use. The default is to use the system viewing matrix (!P.T).

NO_COPY

Normally, a copy of Vertex_list is transformed and the original Vertex_list is preserved. If NO_COPY is set, however, then the original Vertex_List will be undefined after the call to VERT_T3D. Using the NO_COPY requires less memory.

NO_DIVIDE

Normally, when a [x, y, z, 1] vector is transformed by a 4x4 matrix, the final homogeneous coordinates are obtained by dividing the x, y, and z components of the result vector by the fourth element in the result vector. Setting the NO_DIVIDE keyword will prevent VERT_T3D from performing this division. In some cases (usually when a perspective transformation is involved) the fourth element in the result vector can be very close to (or equal to) zero.

SAVE_DIVIDE

Set this keyword to a named variable that will hold receive the fourth element of the transformed vector(s). If Vertex_list is a vector then SAVE_DIVIDE is a scalar. If Vertex_list is an array then SAVE_DIVIDE is an array of n elements. This keyword only has effect when the NO_DIVIDE keyword is set.

Example

Transform four points representing a square in the x-y plane by first translating +2.0 in the positive X direction, and then rotating 60.0 degrees about the Y axis.

points = [[0.0, 0.0, 0.0], [1.0, 0.0, 0.0], $

          [1.0, 1.0, 0.0], [0.0, 1.0, 0.0]]

T3D, /RESET

T3D, TRANSLATE=[2.0, 0.0, 0.0]

T3D, ROTATE=[0.0, 60.0, 0.0]

points = VERT_T3D(points)

See Also

T3D


VOIGT

The VOIGT function returns the intensity of an atomic absorption line profile (also known as a VOIGT profile) based on the Voigt damping parameter a and the frequency offset u, in units of the Doppler width. The result is always floating-point and has the same structure as the arguments. Note that a and u should not both be vectors.

The returned line profile φ(a, u) is defined as:

where H  is the classical Voigt function:

The Doppler width ΔvD (assuming no turbulence), is defined as:

where ν 0 is the line center frequency. The dimensionless frequency offset  u and the damping parameter a are determined by:

Here, Γ  is the transition rate:

where γ  is the spontaneous decay rate, and νcol is the atomic collision rate. See Radiative Processes in Astrophysics by G. B. Rybicki and A. P. Lightman (1979) p 291 for more information. The algorithm is from Armstrong, JQSRT 7, 85. (1967).

Calling Sequence

Result = VOIGT(A, U)

Arguments

A

The Voigt damping parameter.

U

The dimensionless frequency offset in Doppler widths.

See Also

LEEFILT, ROBERTS, SOBEL


VORONOI

The VORONOI procedure computes the Voronoi polygon of a point within an irregular grid of points, given the Delaunay triangulation. The Voronoi polygon of a point contains the region closer to that point than to any other point.

For interior points, the polygon is constructed by connecting the midpoints of the lines connecting the point with its Delaunay neighbors. Polygons are traversed in a counterclockwise direction.

For exterior points, the set is described by the midpoints of the connecting lines, plus the circumcenters of the two triangles that connect the point to the two adjacent exterior points.

This routine is written in the IDL language. Its source code can be found in the file voronoi.pro in the lib subdirectory of the IDL distribution.

Calling Sequence

VORONOI, X, Y, I0, C, Xp, Yp

Arguments

X

An array containing the X locations of the points.

Y

An array containing the Y locations of the points.

I0

An array containing the indices of the points.

C

A connectivity list from the Delaunay triangulation. This list is produced with the CONNECTIVITY keyword of the TRIANGULATE procedure.

Xp, Yp

Named variables that will contain the X and Y vertices of Voronoi polygon.

Example

To draw the Voronoi polygons of each point of an irregular grid:

X = RANDOMU(seed, N)	Create a random grid of N points

Y = RANDOMU(seed, N)

TRIANGULATE, X, Y, tr, CONN=C	Triangulate it

FOR I=0, N-1 DO BEGIN

VORONOI, X, Y, I, C, Xp, Yp	Get the ith polygon

POLYFILL, Xp, Yp, COLOR = (I MOD 10) + 2	Draw it

ENDFOR

See Also

TRIANGULATE


VOXEL_PROJ

The VOXEL_PROJ function generates visualizations of volumetric data by computing 2D projections of a colored, semi-transparent volume. Parallel rays from any given direction are cast through the volume, onto the viewing plane. User-selected colors and opacities can be assigned to arbitrary data ranges, simulating the appearance of the materials contained within the volume.

The VOXEL_PROJ function can be combined with the Z-buffer to render volume data over objects. Cutting planes can also be specified to view selected portions of the volume. Other options include: selectable resolution to allow quick "preview" renderings, and average and maximum projections.

VOXEL_PROJ renders volumes using an algorithm similar to the one described by Drebin, Carpenter, and Hanrahan, in "Volume Rendering", Computer Graphics, Volume 22, Number 4, August 1988, pp. 125-134, but without the surface extraction and enhancement step.

Voxel rendering can be quite time consuming. The time required to render a volume is proportional to the viewing area's size, in pixels, times the thickness of the volume cube in the viewing direction, divided by the product of the user-specified X, Y, and Z steps.

Calling Sequence

Result = VOXEL_PROJ(V [, RGBO])

Arguments

V

A three-dimensional array containing the volume to be rendered. This array is converted to byte type if necessary.

RGBO

This optional parameter is used to specify the look-up tables that indicate the color and opacity of each voxel value. This argument can be one of the following types:

•	A (256, 4) byte array for true-color rendering. This array represents 256 sets of red, green, blue, and opacity (RGBO) components for each voxel value, scaled into the range of bytes (0 to 255). The R, G, and B components should already be scaled by the opacity. For example, if a voxel value of 100 contains a material that is red, and 35% opaque, the RGBO values should be, respectively: [89, 0, 0, 89] because 255 * 0.35 = 89. If more than one material is present, the RGBO arrays contain the sum of the individual RGBO arrays. The content and shape of the RGBO curves is highly dependent upon the volume data and experimentation is often required to obtain the best display.

•	A (256, 2) byte array for volumes with only one material or monochrome rendering. This array represents 256 sets of pixel values and their corresponding opacities for each voxel value.

•	If this argument is omitted, the average projection method, or maximum intensity method (if the MAXIMUM_INTENSITY keyword is set) is used.

Keywords

BACKGROUND

A one- or three-element array containing the background color indices. The default is (0,0,0), yielding a black background with most color tables.

CUTTING_PLANE

A floating-point array specifying the coefficients of additional cutting planes. The array has dimensions of (4, N), where N is the number of additional cutting planes from 1 to 6. Cutting planes are constraints in the form of:

C(0) * X + C(1) * Y + C(2) * Z + D > 0

The X, Y, and Z coordinates are specified in voxel coordinates. For example, to specify a cutting plane that excludes all voxels with an X value greater than 10:

CUTTING_PLANE = [-1.0, 0, 0, 10.], for the constraint: -X + 10 > 0.

INTERPOLATE

Set this keyword to use tri-linear interpolation to determine the data value for each step on a ray. Otherwise, the nearest-neighbor method is used. Setting this keyword improves the quality of images produced, especially when the volume has low resolution in relation to the size of the viewing plane, at the cost of more computing time.

MAXIMUM_INTENSITY

Set this keyword to make the value of each pixel in the viewing plane the maximum data value along the corresponding ray. The RGBO argument is ignored if present.

STEP

Set this keyword to a three-element vector, [Sx, Sy, Sz], that controls the resolution of the resulting projection. The first two elements contain the step size in the X and Y view plane, in pixels. The third element is the sampling step size in the Z direction, given in voxels. Sx and Sy must be integers equal to or greater than one, while Sz can contain a fractional part. If Sx or Sy are greater than one, the values of intermediate pixels in the output image are linearly interpolated. Higher step sizes require less time because fewer rays are cast, at the expense of lower resolution in the output image.

XSIZE

The width, in pixels, of the output image. If this keyword is omitted, the output image is as wide as the currently-selected output device.

YSIZE

The height, in pixels, of the output image. If this keyword is omitted, the output image is as tall as the currently selected output device.

ZBUFFER

An integer array, with the same width and height as the output image, that contains the depth portion of the Z-buffer. Include this parameter to combine the previously-read contents of a Z-buffer with a voxel rendering. See the third example, below, for details.

ZPIXELS

A byte array, with the same width and height as the output image, that contains the image portion of the Z-buffer. Include this parameter to combine the contents of a Z-buffer with a voxel rendering. See the third example, below, for details.

Examples

In the following example, assume that variable V contains a volume of data, with dimensions Vx by Vy by Vz. The volume contains two materials, muscle tissue represented by a voxel range of 50 to 70, that we want to render with red color, and an opacity of 20; and bone tissue represented by a voxel range of 220-255, that we want to render with white color, and an opacity of 50:

rgbo = BYTARR(256,4)	Create the opacity vector.

rgbo(50:70, [0,3]) = 20	Red and opacity for muscle.

rgbo(220:255, *) = 50	White and opacity for bone.

Although it is common to use trapezoidal or Gaussian functions when forming the RGBO arrays, this example uses rectangular functions for simplicity.

SCALE3, XRANGE=[0, Vx-1], YRANGE=[0, Vy-1], ZRANGE=[0, Vz-1]
Set up the axis scaling and default rotation.

C = VOXEL_PROJ(V, rgbo)	Compute projected image.

TV, COLOR_QUAN(C, 3, R, G, B)	Convert from 24-bit to 8-bit image and display.

TVLCT, R, G, B	Load quantized color tables.

This example required approximately 27 seconds on a typical workstation to compute the view in a 640- by 512-pixel viewing window. Adding the keyword STEP=[2,2,1] in the call to VOXEL_PROJ decreased the computing time to about 8 seconds, at the expense of slightly poorer resolution.

When viewing a volume with only one constituent, the RGBO array should contain only an intensity/opacity value pair. To illustrate, if in the above example, only muscle was of interest we create the RGBO argument as follows:

rgbo = BYTARR(256,2)	Create an empty 256 x 2 array.

rgbo(50:70, *) = 20	Intensity and opacity for muscle

SCALE3, XRANGE=[0, Vx-1], YRANGE=[0, Vy-1], ZRANGE=[0, Vz-1]

TV, VOXEL_PROJ(V, rgbo)	Compute and display the projected image.

C = (FINDGEN(256)/255.) # [255., 0., 0]
Create color table array for red.

TVLCT, C(*,0), C(*,1), C(*,2)	Load colors.

The following example demonstrates combining a volume with the contents of the Z-buffer:

SET_PLOT, 'Z'	Set plotting to Z-buffer.

DEVICE, /Z_BUFFER	Turn on Z buffering.

SCALE3, XRANGE=[0, Vx-1], YRANGE=[0, Vy-1], ZRANGE=[0, Vz-1]
Set scaling.

POLYFILL, [0, Vx-1, Vx-1, 0], [0, 0, Vy-1, Vy-1], Vz/2., /T3D
Draw a polygon at z equal to half the depth

zpix = TVRD()	Read pixel values from the Z-buffer.

zbuff = TVRD(/WORDS,/CHAN)	Read depth values from the Z-buffer.

SET_PLOT, 'X'
Back to display window

C = VOXEL_PROJ(V, rgbo, ZPIX=zpix, ZBUFF=zbuff)
Compute the voxel projection and use the ZPIXELS and ZBUFFER keywords to combine the volume with the previously-read contents of the Z-buffer.

TV, COLOR_QUAN(C, 3, R, G, B)	Convert from 24-bit to 8-bit image and display.

TVLCT, R, G, B	Load the quantized color tables.

See Also

RECON3, POLYSHADE, PROJECT_VOL, SHADE_VOLUME


WAIT

The WAIT procedure suspends execution of an IDL program for a specified period. Note that because of other activity on the system, the duration of program suspension may be longer than requested.

Calling Sequence

WAIT,  Seconds

Arguments

Seconds

The duration of the wait, specified in seconds. This parameter can be a floating-point value to specify a fractional number of seconds.

Example

To make an IDL program suspend execution for about five and one half seconds, use the command:

WAIT, 5.5

See Also

EXIT, STOP


WARP_TRI

The WARP_TRI function returns an image array with a specified geometric correction applied. Images are warped using control (tie) points such that locations (Xi, Yi) are shifted to (Xo, Yo).

The irregular grid defined by (Xo, Yo) is triangulated using TRIANGULATE. Then the surfaces defined by (Xo, Yo, Xi) and (Xo, Yo, Yi) are interpolated using TRIGRID to get the locations in the input image of each pixel in the output image. Finally, INTERPOLATE is called to obtain the result. Linear interpolation is used by default. Smooth quintic interpolation is used if the QUINTIC keyword is set.

This routine is written in the IDL language. Its source code can be found in the file warp_tri.pro in the lib subdirectory of the IDL distribution.

Calling Sequence

Result = WARP_TRI(Xo, Yo, Xi, Yi, Image)

Arguments

Xo, Yo

Vectors containing the locations of the control (tie) points in the output image.

Xi, Yi

Vectors containing the location of the control (tie) points in the input image. Xi and Yi must be the same length as Xo and Yo.

Image

The image to be warped. May be any type of data.

Keywords

OUTPUT_SIZE

Set this keyword equal to a 2-element vector containing the size of the output image. If omitted, the output image is the same size as Image.

QUINTIC

Set this keyword to use smooth quintic interpolation. Quintic interpolation is slower but the derivatives are continuous across triangles, giving a more pleasing result than the default linear interpolation.

EXTRAPOLATE

Set this keyword to extrapolate outside the convex hull of the tie points. Setting this keyword implies the use of QUINTIC interpolation.

See Also

INTERPOLATE, TRIANGULATE, TRIGRID


WDELETE

The WDELETE procedure deletes IDL windows.

Calling Sequence

WDELETE [, Window_Index [, ...]]

Arguments

Window_Index

A list of one or more window indices to delete. If this argument is not specified, the current window (as specified by the system variable !D.WINDOW) is deleted. If the window being deleted is not the active window, the value of !D.WINDOW remains unchanged. If the window being deleted is the active window, !D.WINDOW is set to the highest numbered window index or to -1 if no windows remain open.

If this window index is the widget ID of a draw widget, that widget is deleted.

Example

Create IDL graphics window number 5 by entering:

WINDOW, 5

Delete window 5 by entering:

WDELETE, 5

See Also

WINDOW, WSET,  WSHOW


WEOF
WEOF (VMS Only)

The WEOF procedure writes an end of file mark, sometimes called a tape mark, on the designated tape unit at the current position. The tape must be mounted as a foreign volume. See "VMS-Specific Information" on page 17-49 of the IDL User's Guide.

Calling Sequence

WEOF,  Unit

Arguments

Unit

The magnetic tape unit on which the end of file mark is written. This argument must be a number between 0 and 9, and should not be confused with standard file Logical Unit Numbers (LUNs).

See Also

TAPWRT (VMS Only)


WF_DRAW

The WF_DRAW procedure draws weather fronts of various types using parametric spline interpolation to smooth the lines. WF_DRAW uses the POLYFILL routine to make the annotations on the front lines.

This routine is written in the IDL language. Its source code can be found in the file wf_draw.pro in the lib subdirectory of the IDL distribution.

Calling Sequence

WF_DRAW, X, Y

Arguments

X, Y

Vectors of abcissae and ordinates defining the front to be drawn.

Keywords

COLD

Set this keyword to draw a cold front. The default is a plain line with  no annotations. A cold front can also be specified by setting the keyword FRONT_TYPE = 1.

COLOR

Use this keyword to specify the color to use. The default = !P.COLOR.

CONVERGENCE

Set this keyword to draw a convergence line. A convergence line can also be specified by setting the keyword FRONT_TYPE = 5.

DATA

Set this keyword if X and Y are specified in data coordinates.

DEVICE

Set this keyword if X and Y are specified in device coordinates.

FRONT_TYPE

Set this keyword equal to the numeric index of type of front to draw. Front type indices are as follows: COLD=1, WARM=2, OCCLUDED=3, STATIONARY=4, CONVERGENCE = 5. Not required if plain line is desired or if an  explicit front type keyword is specified.

INTERVAL

Use this keyword to specify the spline interpolation interval, in normalized units. The default = 0.01. Larger values give coarser approximations to curves, smaller values make more  interpolated points.

NORM

Set this keyword if X and Y are specified in normalized coordinates. This is the default.

OCCLUDED

Set this keyword to draw an occluded front. An occluded front can also be specified by setting the keyword FRONT_TYPE = 3.

PSYM

Set this keyword a standard PSYM value to draw a marker on each actual (X, Y) data point. See "PSYM" on page 2-8 for a list of the symbol types.

STATIONARY

Set this keyword to draw a stationary front. A stationary front can also be specified by setting the keyword FRONT_TYPE = 4.

SYM_HT

Use this keyword to specify the height of front symbols, in normalized units.  The default = 0.02.

SYM_LEN

Use this keyword to specify the length and spacing factor for front symbols, in normalized units. The default = 0.15.

THICK

Use this keyword to specify the line thickness. The default = 1.0.

WARM

Set this keyword to draw a warm front. A warm front can also be specified by setting the keyword FRONT_TYPE = 2.

Example

Draw a front given 3 points:

WF_DRAW, [40, 20, 40], [30, 40, 25], /COLD

See Also

ANNOTATE, XYOUTS


WHERE

The WHERE function returns a longword vector that contains the one-dimensional subscripts of the nonzero elements of Array_Expression. The length of the resulting vector is equal to the number of nonzero elements in the parameter. Frequently the result of WHERE is used as a vector subscript to select elements of an array using given criteria. If all elements of Array_Expression are zero the result of WHERE is a scalar integer with the value -1.

Note that the system variable !ERR is set to the number of nonzero elements. This effect is for compatibility with previous versions of IDL and should not be used in new code. Use the COUNT argument to return this value instead.

Calling Sequence

Result = WHERE(Array_Expression [, Count])

Arguments

Array_Expression

The array to be searched. This argument can be of any basic type except string. Both the real and imaginary parts of a complex number must be zero for the number to be considered zero.

Count

A named variable that, on exit, is set to the number of nonzero elements found in Array_Expression. This value is returned as a longword integer.

When WHERE Returns -1

If all the elements of Array_Expression are zero, WHERE returns a scalar integer with a value of -1. Attempting to use this result as an index into another array results in a "subscripts out of bounds" error. In situations where this is possible, code similar to the following can be used to avoid errors:

index = WHERE(array, count)	Use Count to get the number of nonzero elements.

IF count NE 0 THEN result = array(index)
Only subscript the array if it's safe.

Example

Create a 100-element, floating-point array where each element is set to the value of its subscript by entering:

array = FINDGEN(100)

To find the subscripts of all the elements in the array that have values greater than 20, enter:

B = WHERE(array GT 20, count)

To see how many elements meeting the search criteria were found, enter:

PRINT, count

To see the subscripts of the found elements, enter:

PRINT, B

To make an array containing the values of array referred to by B, enter:

values = array(B)

See Also

UNIQ


WIDED

The WIDED procedure invokes IDL's graphical user interface designer, known as the Widget Builder. Complete documentation for the Widget Builder can be found in Chapter 22 of the IDL User's Guide.

Calling Sequence

WIDED


WIDGET_BASE

The WIDGET_BASE function is used to create base widgets. Base widgets serve as containers for other widgets.

The returned value of this function is the widget ID of the newly-created base.

Calling Sequence

Result = WIDGET_BASE([Parent])

Arguments

Parent

The widget ID of the parent widget. To create a top-level base, omit the Parent argument.

Keywords

ALIGN_BOTTOM

Set this keyword to align the new widget with the bottom of its parent base. To take effect, the parent must be a ROW base.

ALIGN_CENTER

Set this keyword to align the new widget with the center of its parent base. To take effect, the parent must be a ROW or COLUMN base. In ROW bases, the new widget will be vertically centered. In COLUMN bases, the new widget will be horizontally centered.

ALIGN_LEFT

Set this keyword to align the new widget with the left side of its parent base. To take effect, the parent must be a COLUMN base.

ALIGN_RIGHT

Set this keyword to align the new widget with the right side of its parent base. To take effect, the parent must be a COLUMN base.

ALIGN_TOP

Set this keyword to align the new widget with the top bottom of its parent base. To take effect, the parent must be a ROW base.

BASE_ALIGN_BOTTOM

Set this keyword to make all children of the new base align themselves with the bottom of the base by default. To take effect, you must also set the ROW keyword for the new base. The default can be overridden for individual child widgets by setting a different ALIGN_XXX keyword when the child widget is created.

BASE_ALIGN_CENTER

Set this keyword to make all children of the new base align themselves with the center of the base by default. To take effect, you must also set the COLUMN or ROW keyword for the new base. The default can be overridden for individual child widgets by setting a different ALIGN_XXX keyword when the child widget is created. In ROW bases, child widgets will be vertically centered. In COLUMN bases, child widgets will be horizontally centered.

BASE_ALIGN_LEFT

Set this keyword to make all children of the new base align themselves with the left side of the base by default. To take effect, you must also set the COLUMN keyword for the new base. The default can be overridden for individual child widgets by setting a different ALIGN_XXX keyword when the child widget is created.

BASE_ALIGN_RIGHT

Set this keyword to make all children of the new base align themselves with the right side of the base by default. To take effect, you must also set the COLUMN keyword for the new base. The default can be overridden for individual child widgets by setting a different ALIGN_XXX keyword when the child widget is created.

BASE_ALIGN_TOP

Set this keyword to make all children of the new base align themselves with the top of the base by default. To take effect, you must also set the ROW keyword for the new base. The default can be overridden for individual child widgets by setting a different ALIGN_XXX keyword when the child widget is created.

COLUMN

If this keyword is included, the base lays out its children in columns. The value of this keyword specifies the number of columns to be used. When one column is filled, a new one is started.

Note that the standard base widget does not impose any placement constraints on its child widgets. However, laying out widgets using the XSIZE, YSIZE, XOFFSET, and YOFFSET keywords can be both tedious and error-prone. Also, if you want your widget application to display properly on different platforms, you should use the COLUMN and ROW keywords to influence child widget layouts instead of explicitly formatting your interfaces.

EVENT_FUNC

A string containing the name of a function to be called by the WIDGET_EVENT function when an event arrives from a widget in the widget hierarchy rooted at the newly-created widget.

EVENT_PRO

A string containing the name of a procedure to be called by the WIDGET_EVENT function when an event arrives from a widget in the widget hierarchy rooted at the newly-created widget.

EXCLUSIVE

Set this keyword to specify that the base can have only button-widget children and that only one button can be set at a time. These buttons, unlike normal button widgets, have two states—set and unset.

When one exclusive button is pressed, any other exclusive buttons (in the same base) that are currently set are automatically released. Hence, only one button can ever be set at one time.

This keyword can be used to create exclusive button menus. See the CW_BGROUP and CW_PDMENU functions for high-level menu-creation utilities.

FRAME

The value of this keyword specifies the width of a frame (in pixels) to be drawn around the borders of the widget. Note that this keyword is only a hint to the toolkit, and may be ignored in some instances.

FUNC_GET_VALUE

A string containing the name of a function to be called when the GET_VALUE keyword to the WIDGET_CONTROL procedure is called for this widget. Using this technique allows you to change the value that should be returned for a widget. Compound widgets use this ability to define their values transparently to the user.

GROUP_LEADER

The widget ID of an existing widget that serves as "group leader" for the newly-created widget. When a group leader is killed, for any reason, all widgets in the group are also destroyed.

A given widget can be in more than one group. The WIDGET_CONTROL procedure can be used to add additional group associations to a widget. It is not possible to remove a widget from an existing group.

KILL_NOTIFY

Set this keyword to a string that contains the name of a procedure to be called automatically when the specified widget dies. Each widget is allowed a single such "callback" procedure. It can be removed by setting the routine to the null string (''). Note that the procedure specified is used only if you are not using the XMANAGER procedure to manage your widgets.

The callback routine is called with the widget identifier as its only argument. At that point, the widget identifier can only be used with the WIDGET_CONTROL procedure to get or set the user value. All other requests that require a widget ID are disallowed for the target widget. The callback is not issued until the WIDGET_EVENT function is called.

If you use the XMANAGER procedure to manage your widgets, the value of this keyword is overwritten. Use the  CLEANUP keyword to XMANAGER to specify a procedure to be called when a managed widget dies.

MAP

Once a widget hierarchy has been realized, it can be mapped (visible) or unmapped (invisible). This keyword specifies the initial map state for the given base and its descendants. Specifying a non-zero value indicates that the base should be mapped when realized (the default). A zero value indicates that the base should be unmapped initially.

After the base is realized, its map state can be altered using the MAP keyword to the WIDGET_CONTROL procedure.

MBAR

Set this keyword to a named variable to cause a menubar to be placed at the top of the base (the base must be a top-level base). The menubar is itself a special kind of base widget that can only have buttons as children. Upon return, the named variable contains the widget ID of the new menubar base. This widget ID can then be used to fill the menubar with pulldown menus. For example, the following widget creation commands first create a base with a menubar, then populate the menubar with a simple pulldown menu (CW_PDMENU could also have been used to construct the pulldown menu):

base = WIDGET_BASE(TITLE = 'Example', MBAR=bar)

file_menu = WIDGET_BUTTON(bar, VALUE='File', /MENU)

file_bttn1=WIDGET_BUTTON(file_menu, VALUE='Item 1',$

                        UVALUE='FILE1')

file_bttn2=WIDGET_BUTTON(file_menu, VALUE='Item 2',$

                        UVALUE='FILE2')

Note that to set X Window System resources for menubars created with this keyword, you must use the RNAME_MBAR keyword rather than the RESOURCE_NAME keyword.

NO_COPY

Usually, when the SET_UVALUE, GET_UVALUE, or SEND_EVENT keywords are used, the source variable memory is copied. When the NO_COPY keyword is set, the source variable dynamic memory is used by the destination, without copying. This feature can be used by compound widgets to obtain state information from a UVALUE without all the memory copying that would otherwise occur.

NONEXCLUSIVE

Set this keyword to specify that the base can only have button widget children. These buttons, unlike normal button widgets, have two states—set and unset.

Non-exclusive bases allow any number of the toggle buttons to be set at one time.

NOTIFY_REALIZE

Set this keyword to a string that contains the name of a procedure to be called automatically when the specified widget is realized. This callback occurs just once (because widgets are realized only once). Each widget is allowed a single such "callback" procedure. It can be removed by setting the routine to the null string (''). The callback routine is called with the widget ID as its only argument.

PRO_SET_VALUE

A string containing the name of a procedure to be called when the SET_VALUE keyword to the WIDGET_CONTROL procedure is called for this widget. Using this technique allows you to designate a routine that sets the value for a widget. Compound widgets use this ability to define their values transparently to the user.

 RESOURCE_NAME

A string containing an X Window System resource name to be applied to the widget. Once defined, this name can be used in the user's .Xdefaults file to customize widget resources not directly supported via the IDL widget routines. This keyword is accepted by all widget creation routines. This keyword only works with the "X" device and is ignored on platforms that do not use the X Window System (i.e., IDL for Windows, IDL for Macintosh).

RESOURCE_NAME allows unrestricted access to the underlying Motif widgets within the following limitations:

•	Users must have the appropriate resources defined in their .Xdefaults or application default resource file, or IDL will not see the definitions and they will not take effect.

•	Motif resources are documented in the OSF/Motif Programmer's Reference Manual. To use them with RESOURCE_NAME, the IDL programmer must determine the type of widget being used by IDL, and then look up the resources that apply to them. Hence, RESOURCE_NAME requires some programmer-level familiarity with Motif.

•	Only resources that are not set within IDL can be modified using this mechanism. Although it is not an error to set resources also set by IDL, the IDL settings will silently override user settings. Research Systems does not document the resources used by IDL since the actual resources used may differ from release to release as the IDL widgets evolve. Therefore, you should set only those resources that are obviously not being set by IDL. Among the resources that are not being set by IDL are those that control colors, menu mnemonics, and accelerator keys.

Example of Using RESOURCE_NAME

The sample code below produces a pulldown menu named "Menu" with 2 entries named "Item 1" and "Item 2".

Using the RESOURCE_NAME keyword in conjunction with X resource definitions, we can alter "Item 1" in several ways not possible through the standard IDL widgets interface. We'll give Item 1 a red background color. We'll also assign "I" as the keyboard mnemonic. Note that Motif automatically underlines the "I" in the title to indicate this. We'll also select Meta-F4 as the keyboard accelerator for selecting "Item 1". If Meta-F4 is pressed while the pointer is anywhere over this application, the effect will be as if the menu was pulled down and "Item 1" was selected with the mouse.

PRO test_event, ev	Simple event handler.

HELP, /STRUCTURE, ev

END

PRO test	Simple widget creation routine.

a = WIDGET_BASE(RESOURCE_NAME = 'test')
The base gets the resource name "test".

b = WIDGET_BUTTON(a, VALUE='Menu', /MENU)

c = WIDGET_BUTTON(b, VALUE='Item 1', $

                  RESOURCE_NAME='item1')
Assign the Item 1 button the resource name "item1".

c = WIDGET_BUTTON(b, VALUE='Item 2')

WIDGET_CONTROL, /REALIZE, a

XMANAGER, 'test', a

END

Note that we gave the overall application the resource name "test", and the "Item 1" button the resource name "item1". Now we can use these names in the following  .Xdefaults file entries:

Idl*test*item1*mnemonic: I

Idl*test*item1*accelerator: Meta<Key>F4

Idl*test*item1*acceleratorText: Meta-F4

Idl*test*item1*background: red

RNAME_MBAR

A string containing an X Window System resource name to be applied to the menubar created by the MBAR keyword. This keyword is identical to the RESOURCE_NAME keyword except that the resource it specifies applies only to the menubar.

ROW

If this keyword is included, the base lays out its children in rows. The value of this keyword specifies the number of rows to be used. When one row is filled, a new one is started.

This keyword is similar to the COLUMN keyword described above.

SCR_XSIZE

Set this keyword to the desired "screen" width of the widget, in pixels. In many cases, setting this keyword is the same as setting the XSIZE keyword.

SCR_YSIZE

Set this keyword to the desired "screen" height of the widget, in pixels. In many cases, setting this keyword is the same as setting the YSIZE keyword.

SCROLL

Set this keyword to give the widget scroll bars that allow viewing portions of the widget contents that are not currently on the screen.

SPACE

The space, in pixels, between children of a row or column major base. This keyword is ignored if either the EXCLUSIVE or NONEXCLUSIVE keyword is present.

TITLE

A string containing the title to be used for the widget. Base widgets use the title only if they are top-level widgets.

Note that if the widget base is not wide enough to contain the specified title, the title may appear truncated. If you must be able to see the full title, you have several alternatives:

•	Rearrange the widgets in the base so that the base becomes naturally wide enough. This is the best solution.

•	Don't worry about this issue. If the user needs to see the entire label, they can resize the window using the mouse.

•	Create the base without using the COLUMN or ROW keywords. Instead, use the XSIZE keyword to explicitly set a usable width. This is an undesirable solution that can lead to strange-looking widget layouts.

TLB_FRAME_ATTR

Set this keyword to one of the values shown in the table below to suppress certain aspects of a top-level base's window frame. Note that this keyword applies only to top-level bases and that these settings are merely hints to the window system and may be ignored by some window managers. Valid settings are:

Value	Meaning
1	Base cannot be resized, minimized, or maximized.
2	Suppress display of system menu.
4	Suppress title bar.
8	Base cannot be closed.
16	Base cannot be moved.
Table 1.18 Valid Values for TLB_FRAME_ATTR Keyword

Note that this keyword is set bitwise, so multiple effects can be set by adding values together. For example, to make a base that has no title bar (setting 4) and cannot be moved (setting 16), set the TLB_FRAME_ATTR keyword to 4+16 , or 20.

TLB_KILL_REQUEST_EVENTS

Set this keyword, usable only with top-level bases, to send the top-level base a WIDGET_KILL_REQUEST event if a user tries to destroy the widget using the window manager (by default, widgets are simply destroyed). WIDGET_KILL_REQUEST events are widget event structures that return the standard ID, TOP, and HANDLER fields. These event structures are defined as:

{ WIDGET_KILL_REQUEST, ID:0L, TOP:0L, HANDLER:0L }

A call to TAG_NAMES with the STRUCTURE_NAME keyword set can be used to differentiate a WIDGET_KILL_REQUEST event from other types of widget events. For example:

IF TAG_NAMES(event, /STRUCTURE_NAME) EQ $

   'WIDGET_KILL_REQUEST' THEN ...

Use this keyword to perform complex actions before allowing a widget application to exit. Note that widgets that have this keyword set are responsible for killing themselves after receiving a WIDGET_KILL_REQUEST event—they cannot be destroyed using the usual window system controls.

TLB_SIZE_EVENTS

Set this keyword, when creating a top-level base, to make that base return an event when the base is resized by the user. See the "Events" section below for more information.

TRACKING_EVENTS

Set this keyword to cause widget tracking events to be issued for the widget whenever the mouse pointer enters or leaves the region covered by that widget. Widget tracking events are returned as structures with the following definition:

{ WIDGET_TRACKING, ID:0L, TOP:0L, HANDLER:0L, ENTER:0 }

ID, TOP, and HANDLER are the standard fields found in every widget event. ENTER is 1 if the tracking event is an entry event, and 0 if it is an exit event.

UVALUE

The "user value" to be assigned to the widget.

Each widget can contain a user-specified value of any data type and organization. This value is not used by the widget in any way, but exists entirely for the convenience of the IDL programmer. This keyword allows you to set this value when the widget is first created.

If UVALUE is not present, the widget's initial user value is undefined.

The user value for a widget can be accessed and modified at any time by using the GET_UVALUE and SET_UVALUE keywords to the WIDGET_CONTROL procedure.

XOFFSET

The horizontal offset of the widget (in pixels) relative to its parent.

Specifying an offset relative to a row or column major base widget does not work because those widgets enforce their own layout policies. This keyword is primarily of use relative to a plain base widget. Note that it is best to avoid using this style of widget layout.

XPAD

The horizontal space, in pixels, between child widgets and the edges of a row or column major base. This keyword is ignored if either the EXCLUSIVE or NONEXCLUSIVE keyword is present.

XSIZE

The width of the widget (in pixels for most widgets, in characters for text widgets).

Most widgets attempt to size themselves to fit the situation. However, if the desired effect is not produced, use this keyword to override it. This keyword is only a "hint" to the toolkit and may be ignored in some situations.

X_SCROLL_SIZE

The XSIZE keyword always specifies the width of a widget. When the SCROLL keyword is specified, this size is not necessarily the same as the width of the visible area. The X_SCROLL_SIZE keyword allows you to set the width of the scrolling viewport independently of the actual width of the widget.

Use of the X_SCROLL_SIZE keyword implies SCROLL.

YOFFSET

The vertical offset of the widget (in pixels) relative to its parent. This offset is specified relative to the upper left corner of the parent widget.

Specifying an offset relative to a row or column major base widget does not work because those widgets enforce their own layout policies. This keyword is primarily of use relative to a plain base widget. Note that it is best to avoid using this style of widget layout.

YPAD

The vertical space, in pixels, between child widgets and the edges of a row or column major base. This keyword is ignored if either the EXCLUSIVE or NONEXCLUSIVE keyword is present.

YSIZE

The height of the widget (in pixels for most widgets, in characters for text widgets, in number of visible items for list widgets).

Most widgets attempt to size themselves to fit the situation. However, if the desired effect is not produced, use this keyword to override it. This keyword is only a "hint" to the toolkit and may be ignored in some situations.

Y_SCROLL_SIZE

The YSIZE keyword always specifies the height of a widget. When the SCROLL keyword is specified, this size is not necessarily the same as the height of the visible area. The Y_SCROLL_SIZE keyword allows you to set the height of the scrolling viewport independently of the actual height of the widget.

Use of the Y_SCROLL_SIZE keyword implies SCROLL.

Exclusive And Non-Exclusive Bases

If the EXCLUSIVE or NONEXCLUSIVE keywords are specified, the base only allows button widget children.

Positioning Children Of Row And Column Bases

When the ROW or COLUMN keywords are specified, the base decides how to lay out its children, and any XOFFSET and YOFFSET keywords specified for such children are ignored.

Positioning Top-Level Bases

When locating a new top level window, some window managers ignore the program's positioning requests and either choose a position or allow the user to choose. In such cases, the XOFFSET and YOFFSET keywords to WIDGET_BASE will not have an effect. The window manager may provide a way to disable this positioning style. The Motif window manager (mwm) can be told to honor positioning requests by placing the lines:

Mwm*clientAutoPlace: False

Mwm*interactivePlacement: False

in your .Xdefaults file.

Events

Top-level widget bases return the following event structure only when they are resized by the user and the base was created with the TLB_SIZE_EVENTS keyword set:

{ WIDGET_BASE, ID:0L, TOP:0L, HANDLER:0L, X:0, Y:0 }

ID is the widget ID of the base generating the event. TOP is the widget ID of the top level widget containing ID. HANDLER contains the widget ID of the widget associated with the handler routine. The X and Y fields return the new width of the base, not including any frame provided by the window manager.

See Also

"Widgets" on page 21-1 of the IDL User's Guide.


WIDGET_BUTTON

The WIDGET_BUTTON function creates button widgets.

The returned value of this function is the widget ID of the newly-created button.

Calling Sequence

Result = WIDGET_BUTTON(Parent)

Arguments

Parent

The widget ID of the parent for the new button widget.

Keywords

ALIGN_CENTER

Set this keyword to center justify the button's text label.

ALIGN_LEFT

Set this keyword to left justify the button's text label.

ALIGN_RIGHT

Set this keyword to right justify the button's text label.

DYNAMIC_RESIZE

Set this keyword to create a widget that resizes itself to fit its new value whenever its value is changed. Note that this keyword does not take effect when used with the SCR_XSIZE, SCR_YSIZE, XSIZE, or YSIZE keywords. If one of these keywords is also set, the widget will be sized as specified by the sizing keyword and will never resize itself dynamically.

This keyword is ignored by IDL for Windows and IDL for Macintosh.

EVENT_FUNC

A string containing the name of a function to be called by the WIDGET_EVENT function when an event arrives from a widget in the widget hierarchy rooted at the newly-created widget.

EVENT_PRO

A string containing the name of a procedure to be called by the WIDGET_EVENT function when an event arrives from a widget in the widget hierarchy rooted at the newly-created widget.

FONT

The name of the font to be used by the widget. This name should be an X Windows font for X displays, or a True Type or PostScript font name for Macintosh/Windows systems. The format of this string is the same as that described for the FONT keyword to the DEVICE command. "FONT" on page 3-11of the IDL Reference Guide. If this keyword is omitted, the default font is used.

FRAME

The value of this keyword specifies the width of a frame (in pixels) to be drawn around the borders of the widget. Note that this keyword is only a "hint" to the toolkit, and may be ignored in some instances.

FUNC_GET_VALUE

A string containing the name of a function to be called when the GET_VALUE keyword to the WIDGET_CONTROL procedure is called for this widget. Using this technique allows you to change the value that should be returned for a widget. Compound widgets use this ability to define their values transparently to the user.

GROUP_LEADER

The widget ID of an existing widget that serves as "group leader" for the newly-created widget. When a group leader is killed, for any reason, all widgets in the group are also destroyed.

A given widget can be in more than one group. The WIDGET_CONTROL procedure can be used to add additional group associations to a widget. It is not possible to remove a widget from an existing group.

HELP

Set this keyword to tell the widget toolkit that this button is a "help" button for a menubar and should be given that appearance. For example, Motif specifies that the help menubar item is displayed on the far right of the menubar. This keyword is ignored in all other contexts and may be ignored by window managers (including that for the Macintosh) that have no such special appearance defined.

KILL_NOTIFY

Set this keyword to a string that contains the name of a procedure to be called automatically when the specified widget dies. Each widget is allowed a single such "callback" procedure. It can be removed by setting the routine to the null string (''). Note that the procedure specified is used only if you are not using the XMANAGER procedure to manage your widgets.

The callback routine is called with the widget identifier as its only argument. At that point, the widget identifier can only be used with the WIDGET_CONTROL procedure to get or set the user value. All other requests that require a widget ID are disallowed for the target widget. The callback is not issued until the WIDGET_EVENT function is called.

If you use the XMANAGER procedure to manage your widgets, the value of this keyword is overwritten. Use the  CLEANUP keyword to XMANAGER to specify a procedure to be called when a managed widget dies.

MENU

The presence of this keyword indicates that the button will be used to activate a pull-down menu. Such buttons can have button children that are then placed into a pull-down menu.

Under Motif, if the value specified for MENU is greater than 1, the button label is enclosed in a box to indicate that this button is a pull-down menu. See the CW_PDMENU function for a high-level pull-down menu creation utility.

NO_COPY

Usually, when the SET_UVALUE, GET_UVALUE, or SEND_EVENT keywords are used, the source variable memory is copied. When the NO_COPY keyword is set, the source variable dynamic memory is used by the destination, without copying. This feature can be used by compound widgets to obtain state information from a UVALUE without all the memory copying that would otherwise occur.

NO_RELEASE

Set this keyword to make exclusive and non-exclusive buttons generate only select events (that is, they only generate an event when they are first pressed—no event is generated when they are released). This keyword has no effect on regular buttons.

NOTIFY_REALIZE

Set this keyword to a string that contains the name of a procedure to be called automatically when the specified widget is realized. This callback occurs just once (because widgets are realized only once). Each widget is allowed a single such "callback" procedure. It can be removed by setting the routine to the null string (''). The callback routine is called with the widget ID as its only argument.

PRO_SET_VALUE

A string containing the name of a procedure to be called when the SET_VALUE keyword to the WIDGET_CONTROL procedure is called for this widget. Using this technique allows you to designate a routine that sets the value for a widget. Compound widgets use this ability to define their values transparently to the user.

RESOURCE_NAME

A string containing an X Window System resource name to be applied to the widget. See "RESOURCE_NAME" on page 1-975 for a complete discussion of this keyword.

SCR_XSIZE

Set this keyword to the desired "screen" width of the widget, in pixels. In many cases, setting this keyword is the same as setting the XSIZE keyword.

SCR_YSIZE

Set this keyword to the desired "screen" height of the widget, in pixels. In many cases, setting this keyword is the same as setting the YSIZE keyword.

SEPARATOR

Set this keyword to tell the widget toolkit that this button is part of a pulldown menu pane and that a separator line should be added directly above this entry. This keyword is ignored in all other contexts.

TRACKING_EVENTS

Set this keyword to cause widget tracking events to be issued for the widget whenever the mouse pointer enters or leaves the region covered by that widget. For the structure of tracking events, see "TRACKING_EVENTS" on page 1-978 in the documentation for WIDGET_BASE.

UVALUE

The "user value" to be assigned to the widget.

Each widget can contain a user-specified value of any data type and organization. This value is not used by the widget in any way, but exists entirely for the convenience of the IDL programmer. This keyword allows you to set this value when the widget is first created.

If UVALUE is not present, the widget's initial user value is undefined.

VALUE

The initial value setting of the widget. The value of a widget button is the label for that button. This label can be a string or a bitmap as described below under "Bitmap Button Labels".

X_BITMAP_EXTRA

When creating a bitmap button that is not of a "byte-aligned" size (i.e., a dimension is not a multiple of 8), this keyword specifies how many bits of the supplied bitmap must be ignored (within the end byte). For example, to create a 10 by 8 bitmap, you need to supply a 2 by 8 array of bytes and ignore the bottom 6 bits. Therefore, you would specify X_BITMAP_EXTRA = 6.

XOFFSET

The horizontal offset of the widget (in pixels) relative to its parent.

Specifying an offset relative to a row or column major base widget does not work because those widgets enforce their own layout policies. This keyword is primarily of use relative to a plain base widget. Note that it is best to avoid using this style of widget programming.

XSIZE

The width of the widget (in pixels for most widgets, in characters for text widgets).

Most widgets attempt to size themselves to fit the situation. However, if the desired effect is not produced, use this keyword to override it. This keyword is only a "hint" to the toolkit and may be ignored in some situations.

YOFFSET

The vertical offset of the widget (in pixels) relative to its parent. This offset is specified relative to the upper left corner of the parent widget.

Specifying an offset relative to a row or column major base widget does not work because those widgets enforce their own layout policies. This keyword is primarily of use relative to a plain base widget. Note that it is best to avoid using this style of widget programming.

YSIZE

The height of the widget (in pixels for most widgets, in characters for text widgets, in number of visible items for list widgets).

Most widgets attempt to size themselves to fit the situation. However, if the desired effect is not produced, use this keyword to override it. This keyword is only a "hint" to the toolkit and may be ignored in some situations.

Exclusive And Non-Exclusive Bases

Buttons placed into exclusive or non-exclusive bases (created via the EXCLUSIVE or NONEXCLUSIVE keywords to WIDGET_BASE procedure) are created as two-state "toggle" buttons, which are controlled by such bases.

Events Returned by Button Widgets

Pressing the mouse button while the mouse cursor is over a button widget causes the widget to generate an event. The event structure returned by the WIDGET_EVENT function is defined by the following statement:

{WIDGET_BUTTON, ID:0L, TOP:0L, HANDLER:0L, SELECT:0}

ID is the widget id of the button generating the event. TOP is the widget ID of the top level widget containing ID. HANDLER contains the widget ID of the widget associated with the handler routine. SELECT is set to 1 if the button was set, and 0 if released. Normal buttons do not generate events when released, so SELECT will always be 1. However, toggle buttons (created by parenting a button to an exclusive or non-exclusive base) return separate events for the set and release actions.

Bitmap Button Labels

In addition to using a text string as the label of a button (set via the VALUE keyword), a button can have a bitmap label. This ability allows buttons to contain a graphic symbol. The bitmap is specified as a 2-dimensional byte array via the VALUE keyword. Appropriate bitmaps can be produced in 2 ways:

•	Create a bitmap using an external bitmap editor, and read it into an IDL byte array using the appropriate procedure (READ_X11_BITMAP, READ_BMP, READ_PICT, etc.).

•	Create a bitmap using the XBM_EDIT procedure. This procedure offers several alternatives for the form of the final bitmap.

Although IDL places no restriction on the size of bitmap allowed, the various toolkits may prefer certain sizes.

See Also

CW_BGROUP, CW_PDMENU


WIDGET_CONTROL

The WIDGET_CONTROL procedure is used to realize, manage, and destroy widget hierarchies. It is often used to change the default behavior or appearance of previously-realized widgets.

Calling Sequence

WIDGET_CONTROL [, Widget_ID]

Arguments

Widget_ID

The widget ID of the widget to be manipulated. This argument can be omitted when used with the RESET keyword, but is required for all other operations.

Keywords

ALL_TEXT_EVENTS

Along with the EDITABLE keyword, ALL_TEXT_EVENTS controls the type of events generated by the text widget. Set the ALL_TEXT_EVENTS keyword to cause the full set of events to be generated. If ALL_TEXT_EVENTS is not set, setting EDITABLE causes only end-of-line events to be generated. If EDITABLE is not set, all events are suppressed. See Table 1.19 for additional details. Note that the equivalent keyword in the WIDGET_TEXT creation routine is called ALL_EVENTS.

Keywords	Effects
ALL_TEXT_EVENTS	EDITABLE	Input changes widget contents?	Type of events generated.
Not set	Not set	No	None
Not set	Set	Yes	End-of-line insertion
Set	Not set	No	All events
Set	Set	Yes	All events
Table 1.19 Effects of using the ALL_TEXT_EVENTS and EDITABLE keywords.

APPEND

When using the SET_VALUE keyword to set the contents of a text widget (as created with the WIDGET_TEXT procedure), setting this keyword indicates that the supplied text should be appended to the existing contents of the text widget rather than replace it.

BAD_ID

If Widget_ID is not a valid widget identifier, this WIDGET_CONTROL normally issues an error and causes program execution to stop. However, if BAD_ID is present and specifies a named variable, the invalid ID is stored into the variable, and this routine quietly returns. If no error occurs, a zero is stored.

CLEAR_EVENTS

If set, any events generated by the widget hierarchy rooted at Widget_ID which have arrived but have not been processed (via the WIDGET_EVENT procedure) are discarded.

DEFAULT_FONT

A string containing the name of the default font to be used.

If the font to be used for a given widget is not explicitly specified (via the FONT keyword to the widget creation function), a default supplied by the window system or server is used. Use this keyword to change the default.

DELAY_DESTROY

Normally, when the user destroys a widget hierarchy using the window manager, it is immediately removed. This can cause problems for applications that use the background task facility provided by the XMANAGER procedure if the hierarchy is destroyed while a background task is using it.

If DELAY_DESTROY is set, attempts to destroy the hierarchy are delayed until the next attempt to obtain an event for it. Setting DELAY_DESTROY to zero restores the default behavior.

XMANAGER uses this keyword automatically when managing background tasks. It is not expected that applications will need to use it directly.

DESTROY

Set this keyword to destroy the widget and any child widgets in its hierarchy. Any further attempts to use the IDs for these widgets will cause an error.

DRAW_BUTTON_EVENTS

Set this keyword to enable button press events for draw widgets. Setting a zero value disables such events.

DRAW_MOTION_EVENTS

Set this keyword to enable motion events for draw widgets. Setting a zero value disables such events.

DRAW_VIEWPORT_EVENTS

Set this keyword to enable viewport motion events for draw widgets. Setting a zero value disables such events.

DRAW_XSIZE

Set this keyword to an integer that specifies the new horizontal size for the graphics region of a draw widget. For non-scrollable draw widgets, setting this keyword is the same as setting SCR_XSIZE or XSIZE. However, for scrolling draw widgets DRAW_XSIZE is the only way to change the width of the drawable area (XSIZE sets the viewport size).

DRAW_YSIZE

Set this keyword to an integer that specifies the new vertical size for the graphics region of a draw widget. For non-scrollable draw widgets, setting this keyword is the same as setting SCR_YSIZE or YSIZE. However, for scrolling draw widgets DRAW_YSIZE is the only way to change the height of the drawable area (YSIZE sets the viewport size).

DYNAMIC_RESIZE

Set this keyword to activate (if set to 1) or deactivate (if set to 0) dynamic resizing of the specified WIDGET_BUTTON, WIDGET_LABEL, or WIDGET_DROPLIST widget (see the documentation for the DYNAMIC_RESIZE keyword to those procedures for more information about dynamic widget resizing).

Note:  Dynamic resizing does not work the same way on all platforms.

EDITABLE

Set this keyword to allow direct user editing of the contents of a text widget. Normally, the text in text widgets is read-only. See Table 1.19 for a description of how EDITABLE interacts with ALL_TEXT_EVENTS.

EVENT_FUNC

A string containing the name of a function to be called by the WIDGET_EVENT function when an event arrives from a widget in the widget hierarchy given by Widget_ID.

This keyword overwrites any event routine supplied by previous uses of the EVENT_FUNC or EVENT_PRO keywords. To specify no event routine, set this keyword to a null string ('').

EVENT_PRO

A string containing the name of a procedure to be called by the WIDGET_EVENT function when an event arrives from a widget in the widget hierarchy given by Widget_ID.

This keyword overwrites any event routine supplied by previous uses of the EVENT_FUNC or EVENT_PRO keywords. To specify no event routine, set this keyword to a null string ('').

FUNC_GET_VALUE

A string containing the name of a function to be called when the GET_VALUE keyword to the WIDGET_CONTROL procedure is called for this widget. Using this technique allows you to change the value that should be returned for a widget. Compound widgets use this ability to define their values transparently to the user.

GET_DRAW_VIEW

Specifies a named variable which will be assigned the current position of a draw widget viewport. The position is returned as a 2-element integer array giving the X and Y position relative to the lower left corner of the graphics area.

GET_UVALUE

Set this keyword to a named variable to contain the current user value of the widget.

Each widget can contain a user set value of any data type and organization. This value is not used by the widget in any way, and exists entirely for the convenience of the IDL programmer. This keyword allows you to obtain the current user value.

The user value of a widget can be set with the SET_UVALUE keyword to this routine, or with the UVALUE keyword to the routine that created it.

To improve the efficiency of the data transfer, consider using the NO_COPY keyword (described below) with GET_UVALUE.

GET_VALUE

Set this keyword to a named variable to contain the current value of the widget. The type of value returned depends on the widget type:

•	Button: If the button label is text, it is returned as a string. Attempts to obtain the value of a button with a bitmap label is an error.

•	Draw: The IDL window ID for the drawing area is returned. This ID is used with procedures such as WSET, WSHOW, etc., to direct graphics to the widget. The window ID is assigned to drawing area widgets at the time they are realized. If the widget has not yet been realized, a value of -1 is returned.

•	Label: The label text is returned as a string.

•	Slider: The current value of the slider is returned as an integer.

•	Text: The current contents of the text widget are returned as a string array. If the USE_TEXT_SELECT keyword is also specified, only the contents of the current selection are returned.

•	Widget types not listed above do not return a value. Attempting to retrieve the value of such a widget causes an error.

The value of a widget can be set with the SET_VALUE keyword to this routine, or with the VALUE keyword to the routine that created it.

GROUP_LEADER

The widget ID of an existing widget that serves as "group leader" for the newly-created widget. When a group leader is killed, for any reason, all widgets in the group are also destroyed.

A given widget can be in more than one group. The WIDGET_CONTROL procedure can be used to add additional group associations to a widget. It is not possible to remove a widget from an existing group.

HOURGLASS

Set this keyword to turn on an "hourglass-shaped" cursor for all IDL widgets and graphics windows. The hourglass remains in place until the WIDGET_EVENT function attempts to process the next event. Then the previous cursor is reinstated. If an application starts a time-intensive calculation inside an event-handling routine, the hourglass cursor should be used to indicate that the system is not currently responding to events.

ICONIFY

Set this keyword to a non-zero value to cause the specified widget to become iconified. Set this keyword to zero to open an iconified widget.

INPUT_FOCUS

If Widget_ID is a text widget, you can set this keyword to cause the widget to receive the keyboard focus. If Widget_ID is a button widget, set this keyword to position the mouse pointer over the button (on Motif), or set the focus to the button so that it can be "pushed" with the spacebar (on Windows). You cannot set the input focus to a button in IDL for Macintosh. If  Widget_ID is a draw widget, set this keyword to give it the focus in IDL for Macintosh; this allows you to print from the draw widget. This keyword has no effect for other widget types.

KILL_NOTIFY

Set this keyword to a string that contains the name of a procedure to be called automatically when the specified widget dies. Each widget is allowed a single such "callback" procedure. It can be removed by setting the routine to the null string (''). Note that the procedure specified is used only if you are not using the XMANAGER procedure to manage your widgets.

Use this keyword to change or remove a previously-specified callback procedure for Widget_ID. A previously-defined callback can be removed by setting this keyword to the null string ('').

The callback routine is called with the widget identifier as its only argument. At that point, the widget identifier can only be used with the WIDGET_CONTROL procedure to get or set the user value. All other requests that require a widget ID are disallowed for the target widget. The callback is not issued until the WIDGET_EVENT function is called.

If you use the XMANAGER procedure to manage your widgets, the value of this keyword is overwritten. Use the  CLEANUP keyword to XMANAGER to specify a procedure to be called when a managed widget dies.

MANAGED

This keyword is used by the XMANAGER procedure to mark those widgets that it is currently managing. User applications should not use this keyword directly.

MAP

Set this keyword to zero to unmap the widget hierarchy rooted at the widget specified by Widget_ID. The hierarchy disappears from the screen, but still exists.

The mapping operation applies only to base widgets. If the specified widget is not a base, IDL searches upward in the widget hierarchy until it finds the closest base widget. The map operation is applied to that base.

Set MAP to a nonzero value to re-map the widget hierarchy and make it visible. Normally, the widget is automatically mapped when it is realized, so use of the MAP keyword is not required.

NO_COPY

Usually, when the SET_UVALUE, GET_UVALUE, or SEND_EVENT keywords are used, the source variable memory is copied. When the NO_COPY keyword is set, the source variable dynamic memory is used by the destination, without copying. This feature can be used by compound widgets to obtain state information from a UVALUE without all the memory copying that would otherwise occur.

Note that when the NO_COPY keyword is set, data is taken away from the source and attached directly to the destination. This feature can be used to move data very efficiently. However, it has the side effect of causing the source variable to become undefined.

NO_NEWLINE

When setting the value of a multi-line text widget, newline characters are automatically appended to the end of each line of text. The NO_NEWLINE keyword suppresses this action.

NOTIFY_REALIZE

Set this keyword to a string that contains the name of a procedure to be called automatically when the specified widget is realized. This callback occurs just once (because widgets are realized only once). Each widget is allowed a single such "callback" procedure. A previously-set callback routine can be removed by setting this keyword to the null string (''). The callback routine is called with the widget ID as its only argument.

PRO_SET_VALUE

A string containing the name of a procedure to be called when the SET_VALUE keyword to the WIDGET_CONTROL procedure is called for this widget. Using this technique allows you to designate a routine that sets the value for a widget. Compound widgets use this ability to define their values transparently to the user.

REALIZE

If set, the widget hierarchy is realized. Until the realization step, the widget hierarchy exists only within IDL. Realization is the step of actually creating the widgets on the screen (and mapping them if necessary).

When a previously-realized widget gets a new child widget, the new child is automatically realized.

RESET

Set the RESET keyword to destroy every currently active widget. Obviously, this keyword should be used with caution.

WIDGET_CONTROL, continued


WIDGET_CONTROL, continued

Keywords, continued

SCR_XSIZE

Set this keyword to an integer value that represents the widget's new horizontal size, in pixels. Attempting to change the size of a widget that is part of a menubar or pulldown menu causes an error. Note that, in many cases, setting this keyword is equivalent to setting the XSIZE keyword. However, this keyword is useful for resizing text, list, and scrolling widgets.

SCR_YSIZE

Set this keyword to an integer value that represents the widget's new vertical size, in pixels. Attempting to change the size of a widget that is part of a menubar or pulldown menu causes an error. Note that, in many cases, setting this keyword is equivalent to setting the YSIZE keyword. However, this keyword is useful for resizing text, list, and scrolling widgets.

SEND_EVENT

Set this keyword to a structure containing a valid widget event to be sent to the specified widget. The value of SEND_EVENT must be a structure and the first three fields must be ID, TOP, and HANDLER (all of LONG type). Additional fields can be of any type.

To improve the efficiency of the data transfer, consider using the NO_COPY keyword with SEND_EVENT.

SENSITIVE

When a widget is sensitive, it has normal appearance and can receive user input. For instance, a sensitive button widget can be activated by moving the mouse cursor over it and pressing a mouse button. When a widget is insensitive, it indicates the fact by changing its appearance, and ignores any input directed at it. If SENSITIVE is zero, the widget hierarchy becomes insensitive. If nonzero, it becomes sensitive.

Sensitivity can be used to control when a user is allowed to manipulate a widget. It should be noted that some widgets do not change their appearance when they are made insensitive, and simply cease generating events.

SET_BUTTON

This keyword allows changing the current state of toggle buttons. If zero, every toggle button in the hierarchy specified by Widget_ID is set to the unselected state. If nonzero, the action depends on the type of base holding the buttons. Normally, all buttons are selected. However, exclusive bases may or may not allow more than a single button to be selected in this manner, depending on the toolkit implementation.

SET_DRAW_VIEW

A scrollable draw widget provides a large graphics area which is viewed through a smaller viewport. This keyword allows changing the current position of the viewport. The desired position is specified as a 2-element integer array giving the X and Y position (in pixels) relative to the lower left corner of the graphics area. For example, to position the viewport to the lower left corner of the image:

WIDGET_CONTROL, widget, SET_DRAW_VIEW=[0, 0]

SET_DROPLIST_SELECT

Set this keyword to an integer that specifies the droplist element to be current (i.e., the element that is displayed on the droplist button). Positions start at zero. If the specified element is outside the possible range, no new selection is set.

SET_LIST_SELECT

Set this keyword to an integer that specifies the list element to be highlighted. The previous selection (if there is a selection) is cleared. Positions start at zero. If the specified element is outside the possible range, no new selection in set.

If the selected position is not currently on the screen, the list widget automatically move the current scrolling viewport to make it visible. The resulting topmost visible element is toolkit specific. If you wish to ensure a certain element is at the top of the list, use the SET_LIST_TOP keyword (described below) to explicitly set the viewport.

SET_LIST_TOP

Set this keyword to an integer that specifies the element of the list widget to the positioned at the top of the scrolling list. If the specified element is outside the range of list elements, nothing happens.

SET_SLIDER_MAX

Set this keyword to a new maximum value for the specified slider widget.

SET_SLIDER_MIN

Set this keyword to a new minimum value for the specified slider widget.

SET_TEXT_SELECT

Use this keyword to clear any current selection in the specified text widget, and either set a new selection, or simply set the text insertion point. To set a selection, specify a two-element integer array containing the starting position and the length of the selection. For example, to set a selection covering characters 3 though 23:

WIDGET_CONTROL, SET_TEXT_SELECT=[3, 23]

To move the text insertion point without setting a selection, omit the second element, or set it to zero.

 SET_TEXT_TOP_LINE

Set this keyword to the zero-based line number of the line to be positioned on the topmost visible line in the text widget's viewport. No horizontal scrolling is performed. Note that this is a line number, not a character offset.

SET_UVALUE

Each widget can contain a user-set value. This value is not used by IDL in any way, and exists entirely for the convenience of the IDL programmer. This keyword allows you to set this value.

To improve the efficiency of the data transfer, consider using the NO_COPY keyword with SET_UVALUE.

SET_VALUE

Sets the value of the specified widget. The meaning of the value differs between widget types:

•	Button: The label to be used for the button. This value can be either a scalar string, or a 2D byte array containing a bitmap.

•	Label: The text to be displayed by the label widget.

•	List: Set the selections for the list widget (string or string array).

•	Slider: Sets the current position of the slider (integer).

•	Text: Set the text to be displayed. If the APPEND keyword is also specified, the text is appended to the current contents instead of instead of completely replacing it (string or string array). If the USE_TEXT_SELECT keyword is specified, the new string replaces only the currently-selected text in the text widget.

•	Widget types not listed above do not allow the setting of a value. Attempting to set the value of such a widget causes an error.

The value of a widget can also be set with the VALUE keyword to the routine that created it.

SHOW

Controls the visibility of a widget hierarchy. If set to zero, the hierarchy containing Widget_ID is pushed behind any other windows on the screen. If nonzero, the hierarchy is pulled in front.

TIMER

If this keyword is present, a WIDGET_TIMER event is generated. Set this keyword to a floating-point value that represents the number of seconds before the timer event arrives. Note that this event is identical to any other widget event except that it contains only the 3 standard event tags. These event structures are defined as:

{ WIDGET_TIMER, ID:0L, TOP:0L, HANDLER:0L }

It is left to the caller to tell the difference between standard widget events and timer events. The standard way to do this is to use a widget that doesn't normally generate events (e.g., a base or label). Alternately, the TAG_NAMES function can be called with the STRUCTURE_NAME keyword to differentiate a WIDGET_TIMER event from other types of events. For example:

IF TAG_NAMES(event, /STRUCTURE_NAME) EQ $

   'WIDGET_TIMER' THEN ...

Using the TIMER keyword is more efficient than the background task functionality found in the XMANAGER procedure because it doesn't "poll" like the original background task code. Research Systems will eventually eliminate the background task functionality from XMANAGER. We encourage all users to modify their code to use the TIMER keyword instead.

TLB_GET_OFFSET

Set this keyword to a named variable in which the offset of the top-level base of the specified widget is returned. The offset is measured in device coordinates relative to the upper-left corner of the screen. This offset value does not include the size of the enclosing frame (which is provided by the window manager).

TLB_GET_SIZE

Set this keyword to a named variable in which the size of the top-level base of the specified widget is returned. The size is returned as a two-element vector that contains the horizontal and vertical size of the base in device coordinates.

TLB_KILL_REQUEST_EVENTS

Use this keyword to set or clear kill request events for the specified top-level base. For more information on these events see "TLB_KILL_REQUEST_EVENTS" on page 1-989.

TLB_SET_TITLE

Set this keyword to a scalar string to change the title of the specified top-level base after it has been created.

TLB_SET_XOFFSET

Use this keyword to set the horizontal position of the top level base of the specified widget. The offset is measured from the upper-left corner of the screen to the upper-left corner of the base, in device coordinates.

TLB_SET_YOFFSET

Use this keyword to set the vertical position of the top level base of the specified widget. The offset is measured from the upper-left corner of the screen to the upper-left corner of the base, in device coordinates.

TRACKING_EVENTS

Set this keyword to a non-zero value to enable tracking events for the widget specified by Widget_ID. Set the keyword to 0 to disable tracking events for the specified widget. For a description of tracking events, see "TRACKING_EVENTS" on page 1-978.

 UPDATE

Use this keyword to enable (if set to 1) or disable (if set to 0) screen updates for the widget hierarchy to which the specified widget belongs. This keyword is useful for preventing unwanted intermediate screen updates when changing the values of many widgets at once or when adding several widgets to a previously-realized widget hierarchy. When first realized, widget hierarchies are set to update.

Note: the UPDATE keyword is ignored on platforms that do not use Motif widgets (IDL for Windows and IDL for Macintosh, for example).

USE_TEXT_SELECT

Set this keyword to modify the behavior of the GET_VALUE and SET_VALUE keywords. If USE_TEXT_SELECT is set, GET_VALUE and SET_VALUE apply only to the current text selection. Normally, these keywords apply to the entire contents of a text widget.

X_BITMAP_EXTRA

When the value of a button widget is a bitmap, the usual width is taken to be 8 times the number of columns in the source byte array. This keyword can be used to indicate the number of bits in the last byte of each row that should be ignored. The value can range between 0 and 7.

XOFFSET

Set this keyword to an integer value that specifies the widget's new horizontal offset, in pixels. Attempting to change the offset of a widget that is the child of a ROW or COLUMN base or a widget that is part of a menubar or pulldown menu causes an error.

XSIZE

Set this keyword to an integer value that represents the widget's new horizontal size —in pixels for most widgets, but in characters for text or list widgets. For most non-scrollable widgets, this size is the same as the "screen size" that can be set using the SCR_XSIZE keyword. For scrollable widgets (e.g., scrolling bases and scrolling draw widgets), this keyword adjusts the viewport size. Use the DRAW_XSIZE keyword to change the width of the drawing area in scrolling draw widgets. Attempting to resize a widget that is part of a menubar or pulldown menu causes an error.

YOFFSET

Set this keyword to an integer value that specifies the widget's new vertical offset, in pixels. Attempting to change the offset of a widget that is the child of a ROW or COLUMN base or a widget that is part of a menubar or pulldown menu causes an error.

YSIZE

Set this keyword to an integer value that represents the widget's new vertical size —in pixels for most widgets, but in characters for text or list widgets. For most non-scrollable widgets, this size is the same as the "screen size" that can be set using the SCR_YSIZE keyword. For scrollable widgets (e.g., scrolling bases and scrolling draw widgets), this keyword adjusts the viewport size. Use the DRAW_YSIZE keyword to change the height of the drawing area in scrolling draw widgets. Attempting to resize a widget that is part of a menubar or pulldown menu causes an error.

See Also

"Widgets" on page 21-1 of the IDL User's Guide.


WIDGET_DRAW

The WIDGET_DRAW function is used to create draw widgets. Draw widgets are rectangular areas that IDL treats as standard graphics windows. Any graphical output that can be produced by IDL can be directed to a draw widget. Draw widgets can have optional scroll bars to allow viewing a larger graphics area than could otherwise be displayed in the widget's visible area.

The returned value of this function is the widget ID of the newly-created draw widget.

Note: On some systems, when backing store is provided by the window system (RETAIN=1), reading data from a window using TVRD( ) may cause unexpected results. For example, data may be improperly read from the window even when the image displayed on screen is correct. Having IDL provide the backing store (RETAIN=2) ensures that the window contents will be read properly.

Calling Sequence

Result = WIDGET_DRAW(Parent)

Arguments

Parent

The widget ID of the parent widget of the new draw widget.

Keywords

BUTTON_EVENTS

Set this keyword to make the draw widget generate event when the mouse buttons are pressed or released (and the mouse pointer is in the draw widget).

Normally, draw widgets do not generate events.

COLORS

The maximum number of color table indices to be used. This parameter has effect only if it is supplied when the first IDL graphics window is created.

If COLORS is not specified when the first window is created, all or most of the available color indices are allocated, depending upon the window system in use.

To use monochrome windows on a color display, set COLORS equal to 2 when creating the first window. One color table is maintained for all IDL windows. A negative value for COLORS specifies that all but the given number of colors from the shared color table should be used.

EVENT_FUNC

A string containing the name of a function to be called by the WIDGET_EVENT function when an event arrives from a widget in the widget hierarchy rooted at the newly-created widget.

EVENT_PRO

A string containing the name of a procedure to be called by the WIDGET_EVENT function when an event arrives from a widget in the widget hierarchy rooted at the newly-created widget.

FRAME

The value of this keyword specifies the width of a frame (in pixels) to be drawn around the borders of the widget. Note that this keyword is only a hint to the toolkit, and may be ignored in some instances.

FUNC_GET_VALUE

A string containing the name of a function to be called when the GET_VALUE keyword to the WIDGET_CONTROL procedure is called for this widget. Using this technique allows you to change the value that should be returned for a widget. Compound widgets use this ability to define their values transparently to the user.

GROUP_LEADER

The widget ID of an existing widget that serves as "group leader" for the newly-created widget. When a group leader is killed, for any reason, all widgets in the group are also destroyed.

A given widget can be in more than one group. The WIDGET_CONTROL procedure can be used to add additional group associations to a widget. It is not possible to remove a widget from an existing group.

KILL_NOTIFY

Set this keyword to a string that contains the name of a procedure to be called automatically when the specified widget dies. Each widget is allowed a single such "callback" procedure. It can be removed by setting the routine to the null string (''). Note that the procedure specified is used only if you are not using the XMANAGER procedure to manage your widgets.

The callback routine is called with the widget identifier as its only argument. At that point, the widget identifier can only be used with the WIDGET_CONTROL procedure to get or set the user value. All other requests that require a widget ID are disallowed for the target widget. The callback is not issued until the WIDGET_EVENT function is called.

If you use the XMANAGER procedure to manage your widgets, the value of this keyword is overwritten. Use the  CLEANUP keyword to XMANAGER to specify a procedure to be called when a managed widget dies.

MOTION_EVENTS

Set this keyword to make the draw widget generate events when the mouse cursor moves across the widget. Normally, draw widgets do not generate events.

Draw widgets that return motion events can generate a large number of events that can result in poor performance on slower machines.

Note that it is possible to generate motion events with coordinates outside the draw widget. If you position the mouse cursor inside the draw widget, press the mouse button, and drag the cursor out of the draw widget, the X and Y fields of the widget event will specify coordinates outside the draw widget.

NO_COPY

Usually, when the SET_UVALUE, GET_UVALUE, or SEND_EVENT keywords are used, the source variable memory is copied. When the NO_COPY keyword is set, the source variable dynamic memory is used by the destination, without copying. This feature can be used by compound widgets to obtain state information from a UVALUE without all the memory copying that would otherwise occur.

NOTIFY_REALIZE

Set this keyword to a string that contains the name of a procedure to be called automatically when the specified widget is realized. This callback occurs just once (because widgets are realized only once). Each widget is allowed a single such "callback" procedure. It can be removed by setting the routine to the null string (''). The callback routine is called with the widget ID as its only argument.

PRO_SET_VALUE

A string containing the name of a procedure to be called when the SET_VALUE keyword to the WIDGET_CONTROL procedure is called for this widget. Using this technique allows you to designate a routine that sets the value for a widget. Compound widgets use this ability to define their values transparently to the user.

RESOURCE_NAME

A string containing an X Window System resource name to be applied to the widget. See "RESOURCE_NAME" on page 1-975 for a complete discussion of this keyword.

RETAIN

Set this keyword to zero, one, or two to specify how backing store should be handled for the draw widget. RETAIN=0 specifies no backing store. RETAIN=1 requests that the server or window system provide backing store. RETAIN=2 specifies that IDL provide backing store directly. See "Backing Store" on page 3-27 of the IDL Reference Guide for details.

SCR_XSIZE

Set this keyword to the desired "screen" width of the widget, in pixels. In many cases, setting this keyword is the same as setting the XSIZE keyword.

SCR_YSIZE

Set this keyword to the desired "screen" height of the widget, in pixels. In many cases, setting this keyword is the same as setting the YSIZE keyword.

SCROLL

Set this keyword to give the draw widget scroll bars that allow viewing portions of the widget contents that are not currently on the screen.

TRACKING_EVENTS

Set this keyword to cause widget tracking events to be issued for the widget whenever the mouse pointer enters or leaves the region covered by that widget. For the structure of tracking events, see "TRACKING_EVENTS" on page 1-978 in the documentation for WIDGET_BASE.

UVALUE

The "user value" to be assigned to the widget.

Each widget can contain a user-specified value of any data type and organization. This value is not used by the widget in any way, but exists entirely for the convenience of the IDL programmer. This keyword allows you to set this value when the widget is first created.

If UVALUE is not present, the widget's initial user value is undefined.

VALUE

The initial value setting of the widget. The value of a draw widget is the IDL window number for use with graphics routines, such as WSET. This value cannot be set or modified by the user.

To obtain the window number for a newly-created draw widget, use the GET_VALUE keyword to WIDGET_CONTROL after the draw widget has been realized. Draw widgets do not have a window number assigned to them until they are realized. For example, to return the window number of a draw widget in the variable win_num, use the command:

WIDGET_CONTROL, my_drawwidget, GET_VALUE = win_num

where my_drawwidget is the widget ID of the desired draw widget.

VIEWPORT_EVENTS

Set this keyword to enable viewport motion events for draw widgets.

XOFFSET

The horizontal offset of the widget (in pixels) relative to its parent.

Specifying an offset relative to a row or column major base widget does not work because those widgets enforce their own layout policies. This keyword is primarily of use relative to a plain base widget. Note that it is best to avoid using this style of widget layout.

XSIZE

The width of the widget (in pixels for most widgets, in characters for text widgets).

Most widgets attempt to size themselves to fit the situation. However, if the desired effect is not produced, use this keyword to override it. This keyword is only a "hint" to the toolkit and may be ignored in some situations.

X_SCROLL_SIZE

The XSIZE keyword always specifies the width of a widget. When the SCROLL keyword is specified, this size is not necessarily the same as the width of the visible area. The X_SCROLL_SIZE keyword allows you to set the width of the scrolling viewport independently of the actual width of the widget.

Use of the X_SCROLL_SIZE keyword implies SCROLL.

YOFFSET

The vertical offset of the widget (in pixels) relative to its parent. This offset is specified relative to the upper left corner of the parent widget.

Specifying an offset relative to a row or column major base widget does not work because those widgets enforce their own layout policies. This keyword is primarily of use relative to a plain base widget. Note that it is best to avoid using this style of widget layout.

YSIZE

The height of the widget (in pixels for most widgets, in characters for text widgets, in number of visible items for list widgets).

Most widgets attempt to size themselves to fit the situation. However, if the desired effect is not produced, use this keyword to override it. This keyword is only a hint to the toolkit and may be ignored in some situations.

Y_SCROLL_SIZE

The YSIZE keyword always specifies the height of a widget. When the SCROLL keyword is specified, this size is not necessarily the same as the height of the visible area. The Y_SCROLL_SIZE keyword allows you to set the height of the scrolling viewport independently of the actual height of the widget.

Use of the Y_SCROLL_SIZE keyword implies SCROLL.

Widget Events Returned by Draw Widgets

By default, draw widgets do not generate events. If the BUTTON_EVENTS keyword is set when the widget is created, pressing or releasing any mouse button while the mouse cursor is over the draw widget causes events to be generated. Specifying the MOTION_EVENTS keyword causes events to be generated continuously as the mouse cursor moves across the draw widget.

The event structure returned by the WIDGET_EVENT function is defined by the following statement:

{WIDGET_DRAW, ID:0L, TOP:0L, HANDLER:0L, TYPE: 0, X:0, Y:0, PRESS:0B, RELEASE:0B}

ID, TOP, and HANDLER are the three standard fields found in every widget event. TYPE returns a value that describes the type of draw widget interaction that generated an event. The values for TYPE are shown in the table below.

Value	Meaning
0	Button Press
1	Button Release
2	Motion
3	Viewport Moved (Scrollbars)
Table 1.20 Values for the TYPE field.

The X and Y fields give the device coordinates at which the event occurred, measured from the lower left corner of the drawing area. PRESS and RELEASE are bitmasks in which the least significant bit represents the leftmost mouse button. The corresponding bit of PRESS is set when a mouse button is pressed, and in RELEASE when the button is released. If the event is a motion event, both PRESS and RELEASE are zero.

Note that the CURSOR procedure is only for use with IDL graphics windows. It should not be used with draw widgets. To obtain the cursor position and button state information from a draw widget, examine the X, Y, PRESS, and RELEASE fields in the structures returned by the draw widget in response to cursor events.

Backing Store

Draw widgets with scroll bars rely on backing store to repaint the visible area of the window as it is moved. Their performance is best on systems that provide backing store. However, if your system does not automatically provide backing store, you can make IDL supply it with the statement:

DEVICE, RETAIN=2

or by using the RETAIN keyword to WIDGET_DRAW.

See Also

SLIDE_IMAGE, WINDOW


WIDGET_DROPLIST

The WIDGET_DROPLIST function creates "droplist" widgets. A droplist widget is a button with a label that, when selected, reveals a list of options from which to choose. When the user selects a new option from the list, the list disappears and the button title displays the currently-selected option. This action generates an event containing the index of the selected item, which ranges from 0 to the number of elements in the list minus one, and updates the label on the push-button.

The returned value of this function is the widget ID of the newly-created droplist widget.

Calling Sequence

Result = WIDGET_DROPLIST(Parent)

Arguments

Parent

The widget ID of the parent widget for the new droplist widget.

Keywords

DYNAMIC_RESIZE

Set this keyword to create a widget that resizes itself to fit its new value whenever its value is changed. Note that this keyword does not take effect when used with the SCR_XSIZE, SCR_YSIZE, XSIZE, or YSIZE keywords. If one of these keywords is also set, the widget will be sized as specified by the sizing keyword and will never resize itself dynamically.

This keyword is ignored by IDL for Windows and IDL for Macintosh.

EVENT_FUNC

A string containing the name of a function to be called by the WIDGET_EVENT function when an event arrives from a widget in the widget hierarchy rooted at the newly-created widget.

EVENT_PRO

A string containing the name of a procedure to be called by the WIDGET_EVENT function when an event arrives from a widget in the widget hierarchy rooted at the newly-created widget.

FRAME

The value of this keyword specifies the width of a frame (in pixels) to be drawn around the borders of the widget. Note that this keyword is only a hint to the toolkit, and may be ignored in some instances.

FUNC_GET_VALUE

A string containing the name of a function to be called when the GET_VALUE keyword to the WIDGET_CONTROL procedure is called for this widget. Using this technique allows you to change the value that should be returned for a widget. Compound widgets use this ability to define their values transparently to the user.

GROUP_LEADER

The widget ID of an existing widget that serves as "group leader" for the newly-created widget. When a group leader is killed, for any reason, all widgets in the group are also destroyed.

A given widget can be in more than one group. The WIDGET_CONTROL procedure can be used to add additional group associations to a widget. It is not possible to remove a widget from an existing group.

KILL_NOTIFY

Set this keyword to a string that contains the name of a procedure to be called automatically when the specified widget dies. Each widget is allowed a single such "callback" procedure. It can be removed by setting the routine to the null string (''). Note that the procedure specified is used only if you are not using the XMANAGER procedure to manage your widgets.

The callback routine is called with the widget identifier as its only argument. At that point, the widget identifier can only be used with the WIDGET_CONTROL procedure to get or set the user value. All other requests that require a widget ID are disallowed for the target widget. The callback is not issued until the WIDGET_EVENT function is called.

If you use the XMANAGER procedure to manage your widgets, the value of this keyword is overwritten. Use the  CLEANUP keyword to XMANAGER to specify a procedure to be called when a managed widget dies.

NO_COPY

Usually, when the SET_UVALUE, GET_UVALUE, or SEND_EVENT keywords are used, the source variable memory is copied. When the NO_COPY keyword is set, the source variable dynamic memory is used by the destination, without copying. This feature can be used by compound widgets to obtain state information from a UVALUE without all the memory copying that would otherwise occur.

NOTIFY_REALIZE

Set this keyword to a string that contains the name of a procedure to be called automatically when the specified widget is realized. This callback occurs just once (because widgets are realized only once). Each widget is allowed a single such "callback" procedure. It can be removed by setting the routine to the null string (''). The callback routine is called with the widget ID as its only argument.

PRO_SET_VALUE

A string containing the name of a procedure to be called when the SET_VALUE keyword to the WIDGET_CONTROL procedure is called for this widget. Using this technique allows you to designate a routine that sets the value for a widget. Compound widgets use this ability to define their values transparently to the user.

RESOURCE_NAME

A string containing an X Window System resource name to be applied to the widget. See "RESOURCE_NAME" on page 1-975 for a complete discussion of this keyword.

SCR_XSIZE

Set this keyword to the desired "screen" width of the widget, in pixels. In many cases, setting this keyword is the same as setting the XSIZE keyword.

SCR_YSIZE

Set this keyword to the desired "screen" height of the widget, in pixels. In many cases, setting this keyword is the same as setting the YSIZE keyword.

TRACKING_EVENTS

Set this keyword to cause widget tracking events to be issued for the widget whenever the mouse pointer enters or leaves the region covered by that widget. For the structure of tracking events, see "TRACKING_EVENTS" on page 1-978 in the documentation for WIDGET_BASE.

UVALUE

The "user value" to be assigned to the widget.

Each widget can contain a user-specified value of any data type and organization. This value is not used by the widget in any way, but exists entirely for the convenience of the IDL programmer. This keyword allows you to set this value when the widget is first created.

If UVALUE is not present, the widget's initial user value is undefined.

VALUE

The initial value setting of the widget. The value of a droplist widget is a scalar string or array of strings that contains the text of the list items—one list item per array element. List widgets are sized based on the length (in characters) of the longest item specified in the array of values for the VALUE keyword.

XOFFSET

The horizontal offset of the widget (in pixels) relative to its parent.

Specifying an offset relative to a row or column major base widget does not work because those widgets enforce their own layout policies. This keyword is primarily of use relative to a plain base widget. Note that it is best to avoid using this style of widget programming.

XSIZE

The desired width of the droplist widget area, in pixels. Most widgets attempt to size themselves to fit the situation. However, if the desired effect is not produced, use this keyword to override it. This keyword does not control the size of the droplist button or of the dropped list. Instead, it controls the size "around" the droplist button and, as such, is not particularly useful.

YOFFSET

The vertical offset of the widget (in pixels) relative to its parent. This offset is specified relative to the upper left corner of the parent widget.

Specifying an offset relative to a row or column major base widget does not work because those widgets enforce their own layout policies. This keyword is primarily of use relative to a plain base widget. Note that it is best to avoid using this style of widget programming.

YSIZE

The desired height of the widget, in pixels. Most widgets attempt to size themselves to fit the situation. However, if the desired effect is not produced, use this keyword to override it. This keyword does not control the size of the droplist button or of the dropped list. Instead, it controls the size "around" the droplist button and, as such, is not particularly useful.

TITLE

Set this keyword to a string to be used as the title for the droplist widget.

Widget Events Returned by Droplist Widgets

Pressing the mouse button while the mouse cursor is over an element of a droplist widget causes the widget to change the label on the droplist button and to generate an event. The appearance of any previously selected element is restored to normal at the same time. The event structure returned by the WIDGET_EVENT function is defined by the following statement:

{ WIDGET_DROPLIST, ID:0L, TOP:0L, HANDLER:0L, INDEX:0L }

The first three fields are the standard fields found in every widget event. INDEX returns the index of the selected item. This can be used to index the array of names originally used to set the widget's value.

See Also

CW_PDMENU, WIDGET_BUTTON, WIDGET_LIST


WIDGET_EVENT

The WIDGET_EVENT function returns events for the widget hierarchy rooted at Widget_ID. Widgets communicate information by generating events. Events are generated when a button is pressed, a slider position is changed, and so forth.

Note: Widget applications should use the XMANAGER procedure in preference to calling WIDGET_EVENT directly. See "Widget Events" on page 21-6 of the IDL User's Guide.

Calling Sequence

Result = WIDGET_EVENT([Widget_ID])

Arguments

Widget_ID

Widget_ID specifies the widget hierarchy for which events are desired. The first available event for the specified widget or any of its children is returned. If this argument is not specified, WIDGET_EVENT processes events for all existing widgets.

Widget_ID can also be an array of widget identifiers, in which case all of the specified widget hierarchies are searched.

Note: Attempting to obtain events for a widget hierarchy which is not producing events will hang IDL, unless the NOWAIT keyword is used.

Keywords

BAD_ID

If one of the values supplied via Widget_ID is not a valid widget identifier, this function normally issues an error and causes program execution to stop. However, if BAD_ID is present and specifies a named variable, the invalid ID is stored into the variable, and this routine quietly returns. If no error occurs, a zero is stored.

This keyword can be used to handle the situation in which IDL is waiting within WIDGET_EVENT when the user kills the widget hierarchy.

This keyword has meaning only if Widget_ID is explicitly specified.

NOWAIT

When no events are currently available for the specified widget hierarchy, WIDGET_EVENT normally waits until one is available and then returns it. However, if NOWAIT is set and no events are present, it immediately returns. In this case, the ID field of the returned structure will be zero.

SAVE_HOURGLASS

Set this keyword to prevent the hourglass cursor from being cleared by WIDGET_EVENT. This keyword can be of use if a program has to poll a widget periodically during a long computation.

YIELD_TO_TTY

Unless the NOWAIT keyword is specified, WIDGET_EVENT does not return until the asked for event is available. If the user should enter a line of input from the keyboard, it cannot be processed until WIDGET_EVENT returns. If the YIELD_TO_TTY keyword is specified and the user enters a line of input, WIDGET_EVENT returns immediately. In this case, the ID field of the returned structure will be zero.

Note: This keyword is supported under Unix only, and there are no plans to extend it to other operating systems. Do not use it if you intend to use non-Unix systems.

Event Processing

All events for a given widget are processed in the order that they are generated. The event processing performed by WIDGET_EVENT consists of the following steps:

•	Wait for an event from one of the specified widgets to arrive.

•	Starting with the widget that the event belongs to, move up the widget hierarchy looking for a widget that has an event handling procedure or function associated with it. Such routines are associated with a widget via the EVENT_PRO and EVENT_FUNC keywords to the widget creation functions or the WIDGET_CONTROL procedure.

•	If an event handling procedure is found, it is called with the widget ID as its argument. When the procedure returns, WIDGET_EVENT returns to the first step. Hence, event procedures are said to "swallow" events.

•	If an event handling function is found, it is called with the widget ID as its argument. When the function returns, its value is examined. If the value is a non-structure, it is discarded and WIDGET_EVENT returns to the first step.

This behavior allows event functions to selectively act like event procedures and swallow events. If the returned value is a structure, it is checked to ensure that it has the standard first 3 fields: ID, TOP, and HANDLER. If not an error is issued. Otherwise the value replaces the event found in the first step and WIDGET_EVENT returns to the second step.

Hence, event functions are said to "rewrite" events. This ability to rewrite events is the basis of the "compound widget" in which several widgets are combined to give the appearance of a single, more complicated widget.

•	If an event reaches the top of a widget hierarchy without being swallowed by an event handler, it is returned as the value of WIDGET_EVENT.

Events

A widget event is returned in a structure. The exact contents of this structure vary depending upon the type of widget involved. The first three elements of this structure, however, are always the same. Any other elements vary from widget type to type. The three fixed elements are:

ID

The widget ID of the widget that generated the event.

TOP

The widget ID of the top level base for the widget hierarchy containing ID .

HANDLER

When an event is passed as the argument to an event handling procedure or function, as discussed in the previous section, this field contains the identifier of the widget associated with the handler routine. When an event is returned from WIDGET_EVENT, this value is always zero to indicate that no handler routine was found.

See Also

XMANAGER


WIDGET_INFO

The WIDGET_INFO function is used to obtain information about the widget subsystem and individual widgets. The specific area for which information is desired is selected by setting the appropriate keyword.

Calling Sequence

Result = WIDGET_INFO([Widget_ID])

Arguments

Widget_ID

Usually this argument should be the widget ID of the widget for which information is desired. If the ACTIVE or VERSION keywords are specified, this argument is not required.

Widget_ID can also be an array of widget identifiers, in which case the result is an array with the same structure in which information on all the specified widgets is returned.

Keywords

ACTIVE

Set this keyword to return 1 if there is at least one realized, managed, top-level widget on the screen. Otherwise, 0 is returned.

CHILD

Set this keyword to return the widget ID of the first child of the widget specified by  Widget_ID. If the widget has no children, 0 is returned.

DRAW_BUTTON_EVENTS

Set this keyword to return 1 if Widget_ID is a draw widget with the BUTTON_EVENTS attribute set. Otherwise, 0 is returned.

DRAW_MOTION_EVENTS

Set this keyword to return 1 if Widget_ID is a draw widget with the MOTION_EVENTS attribute set. Otherwise, 0 is returned.

DRAW_VIEWPORT_EVENTS

Set this keyword to return 1 if Widget_ID is a draw widget with the VIEWPORT_EVENTS attribute set. Otherwise, 0 is returned.

DROPLIST_NUMBER

Set this keyword to return the number of elements currently contained in the specified droplist widget.

DROPLIST_SELECT

Set this keyword to return the zero-based number of the currently-selected element (i.e., the currently-displayed element) in the specified droplist widget.

DYNAMIC_RESIZE

Set this keyword to return 1 if the widget specified by Widget_ID is a button, droplist, or label widget that has had its DYNAMIC_RESIZE attribute set. Otherwise, 0 is returned.

EVENT_FUNC

Set this keyword to return a string containing the name of the event handler function associated with Widget_ID. A null string is returned if no event handler function exists.

EVENT_PRO

Set this keyword to return a string containing the name of the event handler procedure associated with Widget_ID. A null string is returned if no event handler procedure exists.

GEOMETRY

Set this keyword to return a WIDGET_GEOMETRY structure that describes the offset and size information for the widget specified by Widget_ID. This structure has the following definition:

{ WIDGET_GEOMETRY, XOFFSET:0, YOFFSET:0, XSIZE:0, YSIZE:0, SCR_XSIZE:0, SCR_YSIZE:0, DRAW_XSIZE:0, DRAW_YSIZE:0, MARGIN:0, XPAD:0, YPAD:0, SPACE:0 }

With the exception of MARGIN, all of the structure's fields correspond to the keywords of the same name to the various widget routines. MARGIN is the width of any frame added to the widget, in pixels. Therefore, the actual width of any widget is:

SCR_XSIZE + (2* MARGIN)

The actual height of any widget is:

SCR_YSIZE + (2 * MARGIN)

LIST_NUMBER

Set this keyword to return the number of elements currently contained in the specified list widget.

LIST_NUM_VISIBLE

Set this keyword to return the number of elements that can be visible in the scrolling viewport of the specified list widget. Note that this value can be larger than the total number of elements actually in the list.

LIST_SELECT

Set this keyword to return the number of the currently-selected (highlighted) element in the specified list widget. Note that this offset is zero-based. If no element is currently selected, -1 is returned.

LIST_TOP

Set this keyword to return the zero-based offset of the topmost element currently visible in the specified list widget.

NAME

Set this keyword to return the widget type name of the widget specified by Widget_ID. The returned value will be one of the following strings: "BASE", "BUTTON", "DRAW", "DROPLIST", "LABEL", "LIST", "SLIDER", or "TEXT". Set the TYPE keyword to return the widget's type code.

PARENT

Set this keyword to return the widget ID of the parent of the widget specified by Widget_ID. If the widget is a top-level base (i.e., it has no parent), 0 is returned.

REALIZED

Set this keyword to return 1 if the widget specified by Widget_ID has been realized. If the widget has not been realized, 0 is returned.

SIBLING

Set this keyword to return the widget ID of the first sibling of the widget specified by Widget_ID. If the widget is the last sibling in the chain, 0 is returned.

SLIDER_MIN_MAX

Set this keyword to return the current minimum and maximum values of the specified slider as a two-element integer array. Element 0 is the minimum value and element 1 is the maximum value.

 TEXT_ALL_EVENTS

Set this keyword to return 1 if Widget_ID is a text widget with the ALL_EVENTS attribute set. Otherwise, 0 is returned.

TEXT_EDITABLE

Set this keyword to return 1 if Widget_ID is a text widget that allows user editing of its contents. Otherwise, 0 is returned.

TEXT_NUMBER

Set this keyword to return the number of characters currently contained in the specified text widget.

TEXT_OFFSET_TO_XY

Use this keyword to translate a text widget character offset into column and line form. The value of this keyword should be set to the character offset (an integer) to be translated. WIDGET_INFO returns a two-element integer array giving the column (element 0) and line (element 1) corresponding to the offset. If the offset specified is out of range, the array [-1,-1] is returned.

TEXT_SELECT

Set this keyword to return the character starting and ending character offsets of the selected (highlighted) text in the specified text widget. WIDGET_INFO returns a two-element integer array containing the starting (element 0) and ending (element 1) positions of the current selection as offsets from the start (position 0).

TEXT_XY_TO_OFFSET

Use this keyword to translate a text widget position given in line and column form into a character offset. The value of this keyword should be set to a two-element integer array specifying the column (element 0) and line (element 1) position. WIDGET_INFO returns the character offset (as a longword integer) corresponding to the position. If the position specified is out of range, -1 is returned.

TEXT_TOP_LINE

Set this keyword to return the zero-based line number of the line currently at the top of a text widget's display viewport. Note that this value is different from the zero-based character offset of the characters in the line. The character offset can be calculated from the line offset via the TEXT_XY_TO_OFFSET keyword.

TLB_KILL_REQUEST_EVENTS

Set this keyword to return 1 if the top-level base of the widget specified by Widget_ID is set to return kill request events. Otherwise, 0 is returned.

TRACKING_EVENTS

Set his keyword to return the tracking events status for the widget specified by Widget_ID. WIDGET_INFO returns 1 if tracking events are currently enabled for the widget. Otherwise, 0 is returned.

TYPE

Set this keyword to return the type code of the specified Widget_ID. Possible values are given below. Note that you can set the NAME keyword to return string names instead.

Value	Type
0	Base
1	Button
2	Slider
3	Text
4	Draw
5	Label
6	List
8	Droplist
Table 1.21 Widget Type Codes

UPDATE

Set this keyword to return 1 if the widget hierarchy that contains Widget_ID is set to display updates. Otherwise, 0 is returned. See "UPDATE" on page 1-1009.

VALID_ID

Set this keyword to return 1 if Widget_ID represents a currently-valid widget. Otherwise, 0 is returned.

VERSION

Set this keyword to return a structure that gives information about the widget implementation. This structure has the following definition:

{ WIDGET_VERSION, STYLE:'', TOOLKIT:'', RELEASE:'' }

 STYLE is the style of widget toolkit used. TOOLKIT is the implementation of the toolkit. RELEASE is the version level of the toolkit. This field can be used to distinguish between different releases of a given toolkit, such as Motif 1.0 and Motif 1.1.

See Also

"Widgets" on page 21-1 of the IDL User's Guide.


WIDGET_LABEL

The WIDGET_LABEL function is used to create label widgets.

The returned value of this function is the widget ID of the newly-created label widget.

Calling Sequence

Result = WIDGET_LABEL(Parent)

Arguments

Parent

The widget ID of the parent widget for the new label widget.

Keywords

ALIGN_CENTER

Set this keyword to center justify the label text.

ALIGN_LEFT

Set this keyword to left justify the label text.

ALIGN_RIGHT

Set this keyword to right justify the label text.

DYNAMIC_RESIZE

Set this keyword to create a widget that resizes itself to fit its new value whenever its value is changed. Note that this keyword cannot be used with the SCR_XSIZE, SCR_YSIZE, XSIZE, or YSIZE keywords. If one of these keywords is also set, the widget will be sized as specified by the sizing keyword and will never resize itself dynamically.

This keyword is ignored by IDL for Windows.

FONT

The name of the font to be used by the widget. This name should be an X Windows font for X displays, or a True Type or PostScript font name for Macintosh/Windows systems. The format of this string is the same as that described for the FONT keyword to the DEVICE command. "FONT" on page 3-11of the IDL Reference Guide. If this keyword is omitted, the default font is used.

FRAME

The value of this keyword specifies the width of a frame (in pixels) to be drawn around the borders of the widget. Note that this keyword is only a "hint" to the toolkit, and may be ignored in some instances.

FUNC_GET_VALUE

A string containing the name of a function to be called when the GET_VALUE keyword to the WIDGET_CONTROL procedure is called for this widget. Using this technique allows you to change the value that should be returned for a widget. Compound widgets use this ability to define their values transparently to the user.

GROUP_LEADER

The widget ID of an existing widget that serves as "group leader" for the newly-created widget. When a group leader is killed, for any reason, all widgets in the group are also destroyed.

A given widget can be in more than one group. The WIDGET_CONTROL procedure can be used to add additional group associations to a widget. It is not possible to remove a widget from an existing group.

KILL_NOTIFY

Set this keyword to a string that contains the name of a procedure to be called automatically when the specified widget dies. Each widget is allowed a single such "callback" procedure. It can be removed by setting the routine to the null string (''). Note that the procedure specified is used only if you are not using the XMANAGER procedure to manage your widgets.

The callback routine is called with the widget identifier as its only argument. At that point, the widget identifier can only be used with the WIDGET_CONTROL procedure to get or set the user value. All other requests that require a widget ID are disallowed for the target widget. The callback is not issued until the WIDGET_EVENT function is called.

If you use the XMANAGER procedure to manage your widgets, the value of this keyword is overwritten. Use the  CLEANUP keyword to XMANAGER to specify a procedure to be called when a managed widget dies.

NO_COPY

Usually, when the SET_UVALUE, GET_UVALUE, or SEND_EVENT keywords are used, the source variable memory is copied. When the NO_COPY keyword is set, the source variable dynamic memory is used by the destination, without copying. This feature can be used by compound widgets to obtain state information from a UVALUE without all the memory copying that would otherwise occur.

NOTIFY_REALIZE

Set this keyword to a string that contains the name of a procedure to be called automatically when the specified widget is realized. This callback occurs just once (because widgets are realized only once). Each widget is allowed a single such "callback" procedure. It can be removed by setting the routine to the null string (''). The callback routine is called with the widget ID as its only argument.

PRO_SET_VALUE

A string containing the name of a procedure to be called when the SET_VALUE keyword to the WIDGET_CONTROL procedure is called for this widget. Using this technique allows you to designate a routine that sets the value for a widget. Compound widgets use this ability to define their values transparently to the user.

RESOURCE_NAME

A string containing an X Window System resource name to be applied to the widget. See "RESOURCE_NAME" on page 1-975 for a complete discussion of this keyword.

SCR_XSIZE

Set this keyword to the desired "screen" width of the widget, in pixels. In many cases, setting this keyword is the same as setting the XSIZE keyword.

SCR_YSIZE

Set this keyword to the desired "screen" height of the widget, in pixels. In many cases, setting this keyword is the same as setting the YSIZE keyword.

TRACKING_EVENTS

Set this keyword to cause widget tracking events to be issued for the widget whenever the mouse pointer enters or leaves the region covered by that widget. For the structure of tracking events, see "TRACKING_EVENTS" on page 1-978 in the documentation for WIDGET_BASE.

UVALUE

The "user value" to be assigned to the widget.

Each widget can contain a user-specified value of any data type and organization. This value is not used by the widget in any way, but exists entirely for the convenience of the IDL programmer. This keyword allows you to set this value when the widget is first created.

If UVALUE is not present, the widget's initial user value is undefined.

VALUE

The initial value setting of the widget. The value of a widget label is a string containing the text for the label.

XOFFSET

The horizontal offset of the widget (in pixels) relative to its parent.

Specifying an offset relative to a row or column major base widget does not work because those widgets enforce their own layout policies. This keyword is primarily of use relative to a plain base widget. Note that it is best to avoid using this style of widget programming.

XSIZE

The width of the widget (in pixels for most widgets, in characters for text widgets). Note that label widgets are sized in pixels.

Most widgets attempt to size themselves to fit the situation. However, if the desired effect is not produced, use this keyword to override it. This keyword is only a "hint" to the toolkit and may be ignored in some situations.

YOFFSET

The vertical offset of the widget (in pixels) relative to its parent. This offset is specified relative to the upper left corner of the parent widget.

Specifying an offset relative to a row or column major base widget does not work because those widgets enforce their own layout policies. This keyword is primarily of use relative to a plain base widget. Note that it is best to avoid using this style of widget programming.

YSIZE

The height of the widget (in pixels for most widgets, in characters for text widgets, in number of visible items for list widgets). Note that label widgets are sized in pixels.

Most widgets attempt to size themselves to fit the situation. However, if the desired effect is not produced, use this keyword to override it. This keyword is only a "hint" to the toolkit and may be ignored in some situations.

Widget Events Returned by Label Widgets

Label widgets do not return an event structure.

See Also

CW_FIELD, WIDGET_TEXT


WIDGET_LIST

The WIDGET_LIST function is used to create list widgets. A list widget offers the user a list of text elements from which to choose. The user can select an item by pointing at it with the mouse cursor and pressing a button. This action generates an event containing the index of the selected item, which ranges from 0 to the number of elements in the list minus one.

The returned value of this function is the widget ID of the newly-created list widget.

Calling Sequence

Result = WIDGET_LIST(Parent)

Arguments

Parent

The widget ID of the parent widget for the new list widget.

Keywords

EVENT_FUNC

A string containing the name of a function to be called by the WIDGET_EVENT function when an event arrives from a widget in the widget hierarchy rooted at the newly-created widget.

EVENT_PRO

A string containing the name of a procedure to be called by the WIDGET_EVENT function when an event arrives from a widget in the widget hierarchy rooted at the newly-created widget.

FONT

The name of the font to be used by the widget. This name should be an X Windows font for X displays, or a True Type or PostScript font name for Macintosh/Windows systems. The format of this string is the same as that described for the FONT keyword to the DEVICE command. "FONT" on page 3-11of the IDL Reference Guide. If this keyword is omitted, the default font is used.

FRAME

The value of this keyword specifies the width of a frame (in pixels) to be drawn around the borders of the widget. Note that this keyword is only a "hint" to the toolkit, and may be ignored in some instances.

FUNC_GET_VALUE

A string containing the name of a function to be called when the GET_VALUE keyword to the WIDGET_CONTROL procedure is called for this widget. Using this technique allows you to change the value that should be returned for a widget. Compound widgets use this ability to define their values transparently to the user.

GROUP_LEADER

The widget ID of an existing widget that serves as "group leader" for the newly-created widget. When a group leader is killed, for any reason, all widgets in the group are also destroyed.

A given widget can be in more than one group. The WIDGET_CONTROL procedure can be used to add additional group associations to a widget. It is not possible to remove a widget from an existing group.

KILL_NOTIFY

Set this keyword to a string that contains the name of a procedure to be called automatically when the specified widget dies. Each widget is allowed a single such "callback" procedure. It can be removed by setting the routine to the null string (''). Note that the procedure specified is used only if you are not using the XMANAGER procedure to manage your widgets.

The callback routine is called with the widget identifier as its only argument. At that point, the widget identifier can only be used with the WIDGET_CONTROL procedure to get or set the user value. All other requests that require a widget ID are disallowed for the target widget. The callback is not issued until the WIDGET_EVENT function is called.

If you use the XMANAGER procedure to manage your widgets, the value of this keyword is overwritten. Use the  CLEANUP keyword to XMANAGER to specify a procedure to be called when a managed widget dies.

NO_COPY

Usually, when the SET_UVALUE, GET_UVALUE, or SEND_EVENT keywords are used, the source variable memory is copied. When the NO_COPY keyword is set, the source variable dynamic memory is used by the destination, without copying. This feature can be used by compound widgets to obtain state information from a UVALUE without all the memory copying that would otherwise occur.

NOTIFY_REALIZE

Set this keyword to a string that contains the name of a procedure to be called automatically when the specified widget is realized. This callback occurs just once (because widgets are realized only once). Each widget is allowed a single such "callback" procedure. It can be removed by setting the routine to the null string (''). The callback routine is called with the widget ID as its only argument.

PRO_SET_VALUE

A string containing the name of a procedure to be called when the SET_VALUE keyword to the WIDGET_CONTROL procedure is called for this widget. Using this technique allows you to designate a routine that sets the value for a widget. Compound widgets use this ability to define their values transparently to the user.

RESOURCE_NAME

A string containing an X Window System resource name to be applied to the widget. See "RESOURCE_NAME" on page 1-975 for a complete discussion of this keyword.

SCR_XSIZE

Set this keyword to the desired "screen" width of the widget, in pixels. In many cases, setting this keyword is the same as setting the XSIZE keyword.

SCR_YSIZE

Set this keyword to the desired "screen" height of the widget, in pixels. In many cases, setting this keyword is the same as setting the YSIZE keyword.

TRACKING_EVENTS

Set this keyword to cause widget tracking events to be issued for the widget whenever the mouse pointer enters or leaves the region covered by that widget. For the structure of tracking events, see "TRACKING_EVENTS" on page 1-978 in the documentation for WIDGET_BASE.

UVALUE

The "user value" to be assigned to the widget.

Each widget can contain a user-specified value of any data type and organization. This value is not used by the widget in any way, but exists entirely for the convenience of the IDL programmer. This keyword allows you to set this value when the widget is first created.

If UVALUE is not present, the widget's initial user value is undefined.

VALUE

The initial value setting of the widget. The value of a list widget is a scalar string or array of strings that contains the text of the list items—one list item per array element. List widgets are sized based on the length (in characters) of the longest item specified in the array of values for the VALUE keyword.

Note that the value of a list widget can only be set. It cannot be retrieved using WIDGET_CONTROL.

XOFFSET

The horizontal offset of the widget (in pixels) relative to its parent.

Specifying an offset relative to a row or column major base widget does not work because those widgets enforce their own layout policies. This keyword is primarily of use relative to a plain base widget. Note that it is best to avoid using this style of widget programming.

XSIZE

The desired width of the widget, in characters. Most widgets attempt to size themselves to fit the situation. However, if the desired effect is not produced, use this keyword to override it. Note that the final size of the widget may be adjusted to include space for scrollbars (which are not always visible), so your widget may be slightly larger than specified.

YOFFSET

The vertical offset of the widget (in pixels) relative to its parent. This offset is specified relative to the upper left corner of the parent widget.

Specifying an offset relative to a row or column major base widget does not work because those widgets enforce their own layout policies. This keyword is primarily of use relative to a plain base widget. Note that it is best to avoid using this style of widget programming.

YSIZE

The desired height of the widget, in number of list items visible. Most widgets attempt to size themselves to fit the situation. However, if the desired effect is not produced, use this keyword to override it. Note that the final size of the widget may be adjusted to include space for scrollbars (which are not always visible), so your widget may be slightly larger than specified.

Widget Events Returned by List Widgets

Pressing the mouse button while the mouse cursor is over an element of a list widget causes the widget to highlight the appearance of that element and to generate an event. The appearance of any previously selected element is restored to normal at the same time. The event structure returned by the WIDGET_EVENT function is defined by the following statement:

{ WIDGET_LIST, ID:0L, TOP:0L, HANDLER:0L, INDEX:0L , CLICKS:0L}

The first three fields are the standard fields found in every widget event. INDEX returns the index of the selected item. This index can be used to subscript the array of names originally used to set the widget's value. The CLICKS field returns either 1 or 2, depending upon how the list item was selected. If the list item is double-clicked, CLICKS is set to 2.

See Also

CW_BGROUP, WIDGET_DROPLIST


WIDGET_MESSAGE

The WIDGET_MESSAGE function creates a modal (blocking) dialog box that can be used to display information for the user. The dialog must be dismissed, by clicking on one of its option buttons, before execution of the widget program can continue.

This function differs from the normal widgets in a number of ways. The WIDGET_MESSAGE dialog does not exist as part of a widget tree, has no children, does not exist in an unrealized state, and generates no events. Instead, the dialog is displayed whenever this function is called. While the WIDGET_MESSAGE dialog is displayed, other widget activity is limited because the dialog is modal. The function does not return to its caller until the user selects one of the dialog's buttons. Once a button has been selected, the dialog disappears.

WIDGET_MESSAGE returns a string containing the text of the label that the user selected.

There are four basic dialogs that can be displayed. The default type is "Warning". Other types can be selected by setting one of the keywords described below. Each dialog type displays different buttons. Additionally any dialog can be made to show a "Cancel" button by setting the CANCEL keyword. The four types of dialogs are described in the table below:

Dialog Type	Default Buttons
Error	OK
Warning	OK
Question	Yes, No
Information	OK
Table 1.22 Types of WIDGET_MESSAGE Dialogs

Calling Sequence

Result = WIDGET_MESSAGE(Message_Text)

Arguments

Message_Text

A scalar string or string array that contains the text of the message to be displayed. If this argument is set to an array of strings, each array element is displayed as a separate line of text.

Keywords

CANCEL

Set this keyword to add a "Cancel" button to the dialog.

DEFAULT_CANCEL

Set this keyword to make the "Cancel" button the default selection for the dialog. The default selection is the button that is selected when the user presses the default keystroke (usually Space or Return depending on the platform). Setting DEFAULT_CANCEL implies that the CANCEL keyword is also set.

DEFAULT_NO

Set this keyword to make the "No" button the default selection for "Question" dialogs. Normally, the default is "Yes".

DIALOG_PARENT

Set this keyword to the widget ID of the widget over which the message dialog should be positioned. When displayed, the WIDGET_MESSAGE dialog will be positioned over the specified parent widget. (Note: In IDL for Windows the message dialog is centered on the screen rather than positioned over the parent widget.) Dialogs are usually related to a non-dialog widget tree. The ID of the widget in that tree to which the dialog is most closely related should be specified.

This keyword is ignored by IDL for Macintosh.

ERROR

Set this keyword to create an "Error" dialog. The default dialog type is "Warning".

INFORMATION

Set this keyword to create an "Information" dialog. The default dialog type is "Warning".

QUESTION

Set this keyword to create a "Question" dialog. The default dialog type is "Warning".

RESOURCE_NAME

A string containing an X Window System resource name to be applied to the dialog. See "RESOURCE_NAME" on page 1-975 for a complete discussion of this keyword.

TITLE

Set this keyword to a scalar string that contains the text of a title to be displayed in the dialog frame. If this keyword is not specified, the dialog has the dialog type as its title as shown in Table 1.22.

This keyword is ignored by IDL for Macintosh.

See Also

XMANAGER (MODAL keyword), XDISPLAYFILE


WIDGET_SLIDER

The WIDGET_SLIDER function is used to create slider widgets. Slider widgets are used to indicate an integer value from a range of possible values. They consist of a rectangular region which represents the possible range of values. Inside this region is a sliding pointer that displays the current value. This pointer can be manipulated by the user via the mouse, or from within IDL via the WIDGET_CONTROL procedure.

The returned value of this function is the widget ID of the newly-created slider widget.

Calling Sequence

Result = WIDGET_SLIDER(Parent)

Arguments

Parent

The widget ID of the parent for the new slider widget.

Keywords

DRAG

Set this keyword to cause events to be generated continuously while the slider is being dragged by the user. Normally, slider widgets generate position events only when the slider comes to rest at its final position and the mouse button is released.

When a slider widget is set to return drag events, a large number of events can be generated. On slower machines, poor performance can result. Therefore, this option should only be used when detailed or truly interactive control is required.

EVENT_FUNC

A string containing the name of a function to be called by the WIDGET_EVENT function when an event arrives from a widget in the widget hierarchy rooted at the newly-created widget.

EVENT_PRO

A string containing the name of a procedure to be called by the WIDGET_EVENT function when an event arrives from a widget in the widget hierarchy rooted at the newly-created widget.

FONT

The name of the font to be used by the widget. This name should be an X Windows font for X displays, or a True Type or PostScript font name for Macintosh/Windows systems. The format of this string is the same as that described for the FONT keyword to the DEVICE command. "FONT" on page 3-11of the IDL Reference Guide. If this keyword is omitted, the default font is used.

FRAME

The value of this keyword specifies the width of a frame (in pixels) to be drawn around the borders of the widget. Note that this keyword is only a "hint" to the toolkit, and may be ignored in some instances.

FUNC_GET_VALUE

A string containing the name of a function to be called when the GET_VALUE keyword to the WIDGET_CONTROL procedure is called for this widget. Using this technique allows you to change the value that should be returned for a widget. Compound widgets use this ability to define their values transparently to the user.

GROUP_LEADER

The widget ID of an existing widget that serves as "group leader" for the newly-created widget. When a group leader is killed, for any reason, all widgets in the group are also destroyed.

A given widget can be in more than one group. The WIDGET_CONTROL procedure can be used to add additional group associations to a widget. It is not possible to remove a widget from an existing group.

KILL_NOTIFY

Set this keyword to a string that contains the name of a procedure to be called automatically when the specified widget dies. Each widget is allowed a single such "callback" procedure. It can be removed by setting the routine to the null string (''). Note that the procedure specified is used only if you are not using the XMANAGER procedure to manage your widgets.

The callback routine is called with the widget identifier as its only argument. At that point, the widget identifier can only be used with the WIDGET_CONTROL procedure to get or set the user value. All other requests that require a widget ID are disallowed for the target widget. The callback is not issued until the WIDGET_EVENT function is called.

If you use the XMANAGER procedure to manage your widgets, the value of this keyword is overwritten. Use the  CLEANUP keyword to XMANAGER to specify a procedure to be called when a managed widget dies.

MAXIMUM

The maximum value of the range encompassed by the slider. If this keyword is not supplied, a default of 100 is used.

MINIMUM

The minimum value of the range encompassed by the slider. If this keyword is not supplied, a default of 0 is used.

NO_COPY

Usually, when the SET_UVALUE, GET_UVALUE, or SEND_EVENT keywords are used, the source variable memory is copied. When the NO_COPY keyword is set, the source variable dynamic memory is used by the destination, without copying. This feature can be used by compound widgets to obtain state information from a UVALUE without all the memory copying that would otherwise occur.

NOTIFY_REALIZE

Set this keyword to a string that contains the name of a procedure to be called automatically when the specified widget is realized. This callback occurs just once (because widgets are realized only once). Each widget is allowed a single such "callback" procedure. It can be removed by setting the routine to the null string (''). The callback routine is called with the widget ID as its only argument.

PRO_SET_VALUE

A string containing the name of a procedure to be called when the SET_VALUE keyword to the WIDGET_CONTROL procedure is called for this widget. Using this technique allows you to designate a routine that sets the value for a widget. Compound widgets use this ability to define their values transparently to the user.

RESOURCE_NAME

A string containing an X Window System resource name to be applied to the widget. See"RESOURCE_NAME" on page 1-975 for a complete discussion of this keyword.

SCR_XSIZE

Set this keyword to the desired "screen" width of the widget, in pixels. In many cases, setting this keyword is the same as setting the XSIZE keyword.

SCR_YSIZE

Set this keyword to the desired "screen" height of the widget, in pixels. In many cases, setting this keyword is the same as setting the YSIZE keyword.

SCROLL

Under the Motif window manager, the value provided for SCROLL specifies how many units the scroll bar should move when the user clicks the left mouse button inside the slider area, but not on the slider itself. This keyword has no effect under other window systems.

SUPPRESS_VALUE

Set this keyword to inhibit the display of the current slider value.

Sliders work only with integer units. This keyword can be used to suppress the actual value of a slider so that a program can present the user with a slider that seems to work in other units (such as floating-point) or with a non-linear scale.

TRACKING_EVENTS

Set this keyword to cause widget tracking events to be issued for the widget whenever the mouse pointer enters or leaves the region covered by that widget. For the structure of tracking events, see "TRACKING_EVENTS" on page 1-978 in the documentation for WIDGET_BASE.

UVALUE

The "user value" to be assigned to the widget.

Each widget can contain a user-specified value of any data type and organization. This value is not used by the widget in any way, but exists entirely for the convenience of the IDL programmer. This keyword allows you to set this value when the widget is first created.

If UVALUE is not present, the widget's initial user value is undefined.

VALUE

The initial value setting of the widget. The value of a widget slider is the current position of the slider.

TITLE

A string containing the title to be used for the slider widget.

VERTICAL

Set this keyword to crate a vertical slider. If this keyword is omitted, the slider is horizontal.

XOFFSET

The horizontal offset of the widget (in pixels) relative to its parent.

Specifying an offset relative to a row or column major base widget does not work because those widgets enforce their own layout policies. This keyword is primarily of use relative to a plain base widget. Note that it is best to avoid using this style of widget programming.

XSIZE

The width of the widget (in pixels for most widgets, in characters for text widgets).

Most widgets attempt to size themselves to fit the situation. However, if the desired effect is not produced, use this keyword to override it. This keyword is only a "hint" to the toolkit and may be ignored in some situations.

YOFFSET

The vertical offset of the widget (in pixels) relative to its parent. This offset is specified relative to the upper left corner of the parent widget.

Specifying an offset relative to a row or column major base widget does not work because those widgets enforce their own layout policies. This keyword is primarily of use relative to a plain base widget. Note that it is best to avoid using this style of widget programming.

YSIZE

The height of the widget (in pixels for most widgets, in characters for text widgets, in number of visible items for list widgets).

Most widgets attempt to size themselves to fit the situation. However, if the desired effect is not produced, use this keyword to override it. This keyword is only a "hint" to the toolkit and may be ignored in some situations.

Slider Widget Events

Slider widgets generate events when the mouse is used to change their value. The event structure returned by the WIDGET_EVENT function is defined by the following statement:

{ WIDGET_SLIDER, ID:0L, TOP:0L, HANDLER:0L, VALUE:0L, DRAG:0}

ID is the widget ID of the button generating the event. TOP is the widget ID of the top level widget containing ID. HANDLER contains the widget ID of the widget associated with the handler routine. VALUE returns the new value of the slider. DRAG returns integer 1 if the slider event was generated as part of a drag operation, or zero if the event was generated when the user had finished positioning the slider. Note that the slider widget only generates events during the drag operation if the DRAG keyword is set. When the DRAG keyword is set, the DRAG field can be used to avoid computationally expensive operations until the user releases the slider.

Known Implementation Problems

Under Motif 1.0, vertical sliders with a title organized in row bases get horizontally truncated and the slider doesn't show (the title does). Use the XSIZE keyword to work around this.

See Also

CW_FSLIDER


WIDGET_TEXT

The WIDGET_TEXT function creates text widgets. Text widgets display text and optionally get textual input from the user. They can have 1 or more lines, and can optionally contain scroll bars to allow viewing more text than can otherwise be displayed on the screen.

The returned value of this function is the widget ID of the newly-created text widget.

Calling Sequence

Result = WIDGET_TEXT(Parent)

Arguments

Parent

The widget ID of the parent widget for the new text widget.

Keywords

ALL_EVENTS

Along with the EDITABLE keyword, ALL_EVENTS controls the type of events generated by the text widget. Set the ALL_EVENTS keyword to cause the full set of events to be generated. If ALL_EVENTS is not set, setting EDITABLE causes only end-of-line events to be generated. If EDITABLE is not set, all events are suppressed. See Table 1.23 for additional details.

Keywords	Effects
ALL_EVENTS	EDITABLE	Input changes widget contents?	Type of events generated.
Not set	Not set	No	None
Not set	Set	Yes	End-of-line insertion
Set	Not set	No	All events
Set	Set	Yes	All events
Table 1.23 Effects of using the ALL_EVENTS and EDITABLE keywords.

EDITABLE

Set this keyword to allow direct user editing of the text widget contents. Normally, the text in text widgets is read-only. See Table 1.23 for a description of how EDITABLE interacts with the ALL_EVENTS keyword.

EVENT_FUNC

A string containing the name of a function to be called by the WIDGET_EVENT function when an event arrives from a widget in the widget hierarchy rooted at the newly-created widget.

EVENT_PRO

A string containing the name of a procedure to be called by the WIDGET_EVENT function when an event arrives from a widget in the widget hierarchy rooted at the newly-created widget.

FONT

The name of the font to be used by the widget. This name should be an X Windows font for X displays, or a True Type or PostScript font name for Macintosh/Windows systems. The format of this string is the same as that described for the FONT keyword to the DEVICE command. "FONT" on page 3-11of the IDL Reference Guide. If this keyword is omitted, the default font is used.

FRAME

The value of this keyword specifies the width of a frame (in pixels) to be drawn around the borders of the widget. Note that this keyword is only a "hint" to the toolkit, and may be ignored in some instances.

FUNC_GET_VALUE

A string containing the name of a function to be called when the GET_VALUE keyword to the WIDGET_CONTROL procedure is called for this widget. Using this technique allows you to change the value that should be returned for a widget. Compound widgets use this ability to define their values transparently to the user.

GROUP_LEADER

The widget ID of an existing widget that serves as "group leader" for the newly-created widget. When a group leader is killed, for any reason, all widgets in the group are also destroyed.

A given widget can be in more than one group. The WIDGET_CONTROL procedure can be used to add additional group associations to a widget. It is not possible to remove a widget from an existing group.

KILL_NOTIFY

Set this keyword to a string that contains the name of a procedure to be called automatically when the specified widget dies. Each widget is allowed a single such "callback" procedure. It can be removed by setting the routine to the null string (''). Note that the procedure specified is used only if you are not using the XMANAGER procedure to manage your widgets.

The callback routine is called with the widget identifier as its only argument. At that point, the widget identifier can only be used with the WIDGET_CONTROL procedure to get or set the user value. All other requests that require a widget ID are disallowed for the target widget. The callback is not issued until the WIDGET_EVENT function is called.

If you use the XMANAGER procedure to manage your widgets, the value of this keyword is overwritten. Use the  CLEANUP keyword to XMANAGER to specify a procedure to be called when a managed widget dies.

NO_COPY

Usually, when the SET_UVALUE, GET_UVALUE, or SEND_EVENT keywords are used, the source variable memory is copied. When the NO_COPY keyword is set, the source variable dynamic memory is used by the destination, without copying. This feature can be used by compound widgets to obtain state information from a UVALUE without all the memory copying that would otherwise occur.

NO_NEWLINE

Normally, when setting the value of a multi-line text widget, newline characters are automatically appended to the end of each line of text. Set this keyword to suppress this action.

NOTIFY_REALIZE

Set this keyword to a string that contains the name of a procedure to be called automatically when the specified widget is realized. This callback occurs just once (because widgets are realized only once). Each widget is allowed a single such "callback" procedure. It can be removed by setting the routine to the null string (''). The callback routine is called with the widget ID as its only argument.

PRO_SET_VALUE

A string containing the name of a procedure to be called when the SET_VALUE keyword to the WIDGET_CONTROL procedure is called for this widget. Using this technique allows you to designate a routine that sets the value for a widget. Compound widgets use this ability to define their values transparently to the user.

RESOURCE_NAME

A string containing an X Window System resource name to be applied to the widget. See "RESOURCE_NAME" on page 1-975 for a complete discussion of this keyword.

SCR_XSIZE

Set this keyword to the desired "screen" width of the widget, in pixels. In many cases, setting this keyword is the same as setting the XSIZE keyword.

SCR_YSIZE

Set this keyword to the desired "screen" height of the widget, in pixels. In many cases, setting this keyword is the same as setting the YSIZE keyword.

SCROLL

Set this keyword to give the widget scroll bars that allow viewing portions of the widget contents that are not currently on the screen.

TRACKING_EVENTS

Set this keyword to cause widget tracking events to be issued for the widget whenever the mouse pointer enters or leaves the region covered by that widget. For the structure of tracking events, see "TRACKING_EVENTS" on page 1-978 in the documentation for WIDGET_BASE.

UVALUE

The "user value" to be assigned to the widget.

Each widget can contain a user-specified value of any data type and organization. This value is not used by the widget in any way, but exists entirely for the convenience of the IDL programmer. This keyword allows you to set this value when the widget is first created.

If UVALUE is not present, the widget's initial user value is undefined.

VALUE

The initial value setting of the widget. The value of a text widget is the current text displayed by the widget.

WRAP

Set this keyword to indicate that scrolling or multi-line text widgets should automatically break lines between words to keep the text from extending past the right edge of the text display area.

XOFFSET

The horizontal offset of the widget (in pixels) relative to its parent.

Specifying an offset relative to a row or column major base widget does not work because those widgets enforce their own layout policies. This keyword is primarily of use relative to a plain base widget. Note that it is best to avoid using this style of widget programming.

XSIZE

The width of the widget (in pixels for most widgets, in characters for text widgets).

Most widgets attempt to size themselves to fit the situation. However, if the desired effect is not produced, use this keyword to override it. This keyword is only a "hint" to the toolkit and may be ignored in some situations.

YOFFSET

The vertical offset of the widget (in pixels) relative to its parent. This offset is specified relative to the upper left corner of the parent widget.

Specifying an offset relative to a row or column major base widget does not work because those widgets enforce their own layout policies. This keyword is primarily of use relative to a plain base widget. Note that it is best to avoid using this style of widget programming.

YSIZE

The height of the widget (in pixels for most widgets, in characters for text widgets, in number of visible items for list widgets).

Most widgets attempt to size themselves to fit the situation. However, if the desired effect is not produced, use this keyword to override it. This keyword is only a "hint" to the toolkit and may be ignored in some situations.

Text Widget Events

 There are several variations of the text widget event structure depending on the specific event being reported. All of these structures contain the standard three fields (ID, TOP, and HANDLER) as well as an integer TYPE field that indicates which type of structure has been returned. Programs should always check the type field before referencing fields that are not present in all text event structures. The different text widget event structures are described below.

Insert Single Character (TYPE = 0)

This is the type of structure returned when characters are typed into a text widget by a user.

{ WIDGET_TEXT_CH, ID:0L, TOP:0L, HANDLER:0L, TYPE:0, OFFSET:0L, CH:0B }

OFFSET is the insertion position that will result after the character is inserted. CH is the ASCII value of the character.

Insert Multiple Characters (TYPE = 1)

This is the type of structure returned when multiple characters are pasted into a text widget by the window system.

{ WIDGET_TEXT_STR, ID:0L, TOP:0L, HANDLER:0L, TYPE:1, OFFSET:0L, STR:'' }

OFFSET is the insertion position that will result after the text is inserted. STR is the string to be inserted.

Delete Text (TYPE = 2)

This is the type of structure returned when any amount of text is deleted from a text widget.

{ WIDGET_TEXT_DEL, ID:0L, TOP:0L, HANDLER:0L, TYPE:2, OFFSET:0L, LENGTH:0L }

OFFSET is the (zero-based) character position of the first character to be deleted. It is also the insertion position that will result when the character is inserted. LENGTH gives the number of characters involved.

Selection (TYPE = 3)

This is the type of structure returned when an area of text is selected (highlighted) by the user.

{ WIDGET_TEXT_SEL, ID:0L, TOP:0L, HANDLER:0L, TYPE:3, OFFSET:0L, LENGTH:0L }

The event announces a change in the insertion point. OFFSET is the (zero-based) character position of the first character to be selected. LENGTH gives the number of characters involved. A LENGTH of zero indicates that the widget has lost its previous selection, and the new insertion position is given by OFFSET.

Note that text insertion, text deletion, or any change in the current insertion point causes any current selection to be lost. In such cases, the loss of selection is implied by the text event reporting the insert/delete/movement and a separate zero length selection event is not sent.

See Also

CW_FIELD, XDISPLAYFILE


WINDOW

The WINDOW procedure creates a window for the display of graphics or text. It is only necessary to use WINDOW if more than one simultaneous window or a special size window is desired because a window is created automatically the first time any display procedure attempts to access the window system. The newly-created window becomes the current window, and the system variable !D.WINDOW is set to that window's window index. (See the description of the  WSET procedure for a discussion of the current IDL window.)

The behavior of WINDOW varies slightly depending on the window system in effect. See the discussion of IDL graphics devices in Chapter 3, "IDL Graphics Devices" for additional details.

Calling Sequence

WINDOW [, Window_Index]

Arguments

Window_Index

The window index for the newly-created window. A window index is an integer value between 0 and 31 that is used to refer to the window. If this parameter is omitted, window index 0 is used. If the value of Window_Index specifies an existing window, the existing window is deleted and a new one is created. If you need to create more than 32 windows, use the FREE keyword described below.

Keywords

COLORS

The maximum number of color table indices to be used when drawing. This parameter has effect only if supplied when the first window is created. If COLORS is not present when the first window is created, all or most of the available color indices are allocated depending upon the window system in use.

To use monochrome windows on a color display use COLORS = 2, when creating the first window. One color table is maintained for all windows. A negative value for COLORS specifies that all but the given number of colors from the shared color table should be allocated.

FREE

Set this keyword to create a window using the smallest unused window index above 32. If this keyword is present, the Window_Index argument can be omitted. The default position of the new window is opposite that of the current window. Using the FREE keyword allows the creation of a large number of windows. The system variable !D.WINDOW is set to the index of the newly-created window.

PIXMAP

If the current graphics device is the X Window system, setting the PIXMAP keyword specifies that the window being created is actually an invisible portion of the display memory called a pixmap.

RETAIN

Set this keyword to zero, one, or two to specify how backing store should be handled for the window. RETAIN=0 specifies no backing store. RETAIN=1 requests that the server or window system provide backing store. RETAIN=2 specifies that IDL provide backing store directly. See "Backing Store" on page 3-27 of the IDL Reference Guide for details.

TITLE

A scalar string that contains the window's label. If not specified, the window is given a label of the form "IDL n", where n is the index number of the window. For example, to create a window with the label "IDL Graphics", enter:

WINDOW, TITLE='IDL Graphics'

XPOS

The X position of the lower left corner of the window, specified in device coordinates. If no position is specified, the position of the window is determined from the value of Window Index using the following rules:

•	Window 0 is placed in the upper right hand corner.

•	Even numbered windows are placed on the top half of the screen and odd numbered windows are placed on the bottom half.

•	Windows 0,1,4,5,8, and 9 are placed on the right side of the screen and windows 2,3,6, and 7 are placed on the left.

YPOS

The Y position of the lower left window corner, specified in device coordinates. See the description of XPOS for details.

XSIZE

The width of the window in pixels.

YSIZE

The height of the window in pixels.

Example

Create graphics window number 0 with a size of 400 by 400 pixels and a title that reads "Square Window" by entering:

WINDOW, 0, XSIZE=400, YSIZE=400, TITLE='Square Window'

See Also

WDELETE, WSET,  WSHOW


WRITE_BMP

The WRITE_BMP procedure writes an image and its color table vectors to a Microsoft Windows Version 3 device independent bitmap file (.BMP).

WRITE_BMP does not handle 1-bit-deep images or compressed images, and is not fast for 4-bit images. The algorithm works best on images where the number of bytes in each scan-line is evenly divisible by 4.

This routine is written in the IDL language. Its source code can be found in the file write_bmp.pro in the lib subdirectory of the IDL distribution.

Calling Sequence

WRITE_BMP, File, Image [, R, G, B]

Arguments

File

A scalar string containing the full path name of the bitmap file to write.

Image

The array to write into the new bitmap file. The array should be scaled into a range of bytes for 8- and 24-bit deep images. Scale to 0-15 for 4 bit deep images. If the image has 3 dimensions and the first dimension is 3, a 24 bit deep bitmap file is created. Note: for 24-bit images, color interleaving is blue, green, red: Image(0,i,j) = blue, Image(1,i,j) = green, etc.

R, G, B

Color tables. If omitted, the colors loaded in the COLORS common block are used.

Keywords

FOUR_BITS

Set this keyword to write as a 4-bit device independent bitmap. If omitted or zero, an 8-bit deep bitmap is written.

IHDR

Set this keyword to a BITMAPINFOHEADER structure containing the file header fields that are not obtained from the image itself. The fields in this structure that can be set are: bi{XY}PelsPerMeter, biClrUsed , and biClrImportant.

HEADER_DEFINE

If this keyword is set, WRITE_BMP returns an empty BITMAPINFOHEADER structure, containing zeros. No other actions are performed. This structure may be then modified with the pertinent fields and passed in via the IHDR keyword parameter. See the Microsoft Windows Programmers Reference Guide for a description of each field in the structure.

Note: this parameter must be defined before the call. For example:

H = 0

WRITE_BMP, HEADER_DEFINE = H

Examples

The following command captures the contents of the current IDL graphics window and saves it to a Microsoft Windows Bitmap file with the name test.bmp:

WRITE_BMP, 'test.bmp', TVRD()

The following commands scale an image to 0-15, and then write a 4-bit BMP file, using a grayscale color table:

r = BYTSCL(INDGEN(16))	Create a ramp from 0 to 255

WRITE_BMP, 'test.bmp', BYTSCL(Image, MAX=15), r, r, r, /FOUR

See Also

READ_BMP


WRITE_GIF

The WRITE_GIF procedure writes an image and its color table vectors to a Graphics Interchange Format (GIF) file.

WRITE_GIF produces 8-bit GIF files of the standard type: non-interlaced, global colormap, one image per file, with no local colormap.

This routine is written in the IDL language. Its source code can be found in the file write_gif.pro in the lib subdirectory of the IDL distribution.

Calling Sequence

WRITE_GIF, File, Image [, R, G, B]

Arguments

File

A scalar string containing the full path name of the GIF file to write.

Image

The array to write into the new GIF file.

R, G, B

The Red, Green, and Blue color vectors to be written with to the GIF file. If R, G, B values are not provided, the last color table established using LOADCT is saved, and the table is padded to 256 entries. If no color table has been established, WRITE_GIF calls LOADCT to load the grayscale entry (table 0).

Example

The following command captures the contents of the current IDL graphics window and saves it to a GIF file named test.gif:

WRITE_GIF, 'test.gif', TVRD()

See Also

READ_GIF, WRITE_JPEG


WRITE_JPEG

The WRITE_JPEG procedure writes compressed images to files. JPEG (Joint Photographic Experts Group) is a standardized compression method for full-color and gray-scale images. This procedure is based in part on the work of the "Independent JPEG Group".

As the Independent JPEG Group states, JPEG is intended for "real-world" scenes (such as digitized photographs). Line art, such as drawings or IDL plots, and other "unrealistic" images are not its strong suit. Note also that JPEG is a "lossy" compression scheme. That is, the output image is not identical to the input image. Hence you must not use JPEG if you have to have identical output bits. However, on typical images of real-world scenes, very good compression levels can be obtained with no visible change, and amazingly high compression levels are possible if you can tolerate a low-quality image. You can trade off output image quality against compressed file size by adjusting a compression parameter. Files are encoded in JFIF, the JPEG File Interchange Format (however, such files are usually simply called "JPEG" files).

If you need to store images in a compressed format that is not lossy, consider using the WRITE_GIF procedure. This procedure writes 8-bit (256 color) images in the Graphics Interchange Format. To store 8-bit or 24-bit images without compression, consider using the WRITE_BMP (for Microsoft Bitmap format files) or TIFF_WRITE (to write Tagged Image Format Files) procedures.

For a short technical introduction to the JPEG compression algorithm, see: Wallace, Gregory K. "The JPEG Still Picture Compression Standard", Communications of the ACM, April 1991 (vol. 34, no. 4), pp. 30-44.

To read JPEG files, use the READ_JPEG procedure (page 1-722).

Calling Sequence

WRITE_JPEG, [Filename,] Image

Arguments

Filename

A string containing the name of file to be written in JFIF (JPEG) format. If this parameter is not present, the UNIT keyword must be specified.

Image

A byte array of either two or three dimensions, containing the image to be written. Grayscale images must have two dimensions. True-color images must have three dimensions with the index of the dimension that contains the color specified with the TRUE keyword.

Keywords

ORDER

JPEG/JFIF images are normally written in top-to-bottom order. If the image array is in the standard IDL order (i.e., from bottom-to-top) set ORDER to 0, its default value. If the image array is in top-to-bottom order, ORDER must be set to 1.

QUALITY

This keyword specifies the quality index, in the range of 0 ("terrible") to 100 ("excellent") for the JPEG file. The default value is 75, to obtain "very good" quality. Lower values of QUALITY produce higher compression ratios and smaller files.

TRUE

This keyword specifies the index, starting at 1, of the dimension over which the color is interleaved. For example, for an image that is pixel interleaved and has dimensions of (3, m, n), set TRUE to 1. Specify 2 for row-interleaved images (m, 3, n); and 3 for band-interleaved images (m, n, 3).

UNIT

This keyword designates the logical unit number of an already open file to receive the output, allowing multiple JFIF images per file or the embedding of JFIF images in other data files. If this keyword is used, Filename should not be specified. When using VMS, open the file with the /STREAM keyword.

Examples

Write the image contained in the array A, using JPEG compression with a quality index of 25. The image is stored in bottom-to-top order:

WRITE_JPEG, 'test.dat', a, QUALITY=25

Write a true-color image to a JPEG file. The image is contained in the band-interleaved array A with dimensions (m,n,3). Assume it is stored in top-to-bottom order:

WRITE_JPEG, 'test1.dat', a, TRUE=3, /ORDER

See Also

READ_JPEG, WRITE_GIF


WRITE_NRIF

The WRITE_NRIF procedure writes an image and its color table vectors to an NCAR Raster Interchange Format (NRIF) rasterfile.

WRITE_NRIF only writes 8- or 24-bit deep rasterfiles of types "Indexed Color" (8-bit) and "Direct Color integrated" (24-bit). The color map is included only for 8-bit files.

See the document "NCAR Raster Interchange Format and TAGS Raster Reference Manual," available from the Scientific Computing Division, National Center for Atmospheric Research, Boulder, CO, 80307-3000, for information on the structure of NRIF files.

This routine is written in the IDL language. Its source code can be found in the file write_nrif.pro in the lib subdirectory of the IDL distribution.

Calling Sequence

WRITE_NRIF, File, Image, [R, G, B]

Arguments

File

A scalar string containing the full path name of the NRIF file to write.

Image

The byte array to be written to the NRIF file. If Image has the dimensions (n,m), an 8-bit NRIF file with color tables is created. If Image has the dimensions (3,n,m), a 24-bit NRIF file is created, where each byte triple represents the red, green, and blue intensities at (n,m) on a scale from 0 to 255. The NRIF image will be rendered from bottom to top, in accordance with IDL standards.

R, G, B

The Red, Green, and Blue color vectors to be used as a color table with 8-bit images. If color vectors are supplied, they are included in the output (8-bit images only). If R, G, B  values are not provided, the last color table established using LOADCT is included. If no color table has been established, WRITE_NRIF calls LOADCT to load the grayscale entry (table 0).

Note: WRITE_NRIF does not recognize color vectors loaded directly using TVLCT, so if a custom color table is desired and it is not convenient to use XPALETTE, include the R, G, and B vectors that were used to create the color table.


WRITE_PICT

The WRITE_PICT procedure writes and image and its color table vectors to a PICT (version 2) format image file. The PICT format is used by Apple Macintosh computers.

Note: WRITE_PICT only works with 8-bit displays

This routine is written in the IDL language. Its source code can be found in the file write_pict.pro in the lib subdirectory of the IDL distribution.

Calling Sequence

WRITE_PICT, File [, Image, R, G, B]

Arguments

File

A scalar string containing the full path name of the PICT file to write.

Image

The byte array to be written to the PICT file. If Image is omitted, the entire current graphics window is read into an array and written to the PICT file.

R, G, B

The Red, Green, and Blue color vectors to be written to the PICT file. If R, G, B values are not provided, the last color table established using LOADCT is included. If no color table has been established, WRITE_PICT calls LOADCT to load the grayscale entry (table 0).

Example

Create a pseudo screen dump from the current window:

WRITE_PICT, 'test.pict', TVRD()

See Also

READ_PICT


WRITE_PPM

The WRITE_PPM procedure writes an image to a PPM (true-color) or PGM (gray scale) file.

Note: WRITE_PPM only writes 8-bit deep PGM/PPM files of the standard type. Images should be ordered so that the first row is the top row.

PPM/PGM format is supported by the PBMPLUS toolkit for converting various image formats to and from portable formats, and by the Netpbm package.

This routine is written in the IDL language. Its source code can be found in the file write_ppm.pro in the lib subdirectory of the IDL distribution.

Calling Sequence

WRITE_PPM, File, Image

Arguments

File

A scalar string specifying the full path name of the PPM or PGM file to write.

Image

The 2D (gray scale) or 3D (true-color) array to be written to a file.

Keywords

ASCII

Set this keyword to force WRITE_PPM to use formatted ASCII input/output to write the image data. The default is to use the far more efficient binary input/output (RAWBITS) format.

Example

Suppose you have a grayscale image array stored in the IDL variable image. To write this image to a PGM file, use the following command:

WRITE_PPM, 'file.pgm', image

See Also

READ_PPM


WRITE_SPR

The WRITE_SPR procedure writes a row-indexed sparse array structure to a specified file. Row-indexed sparse arrays are created using the SPRSIN function.

Calling Sequence

WRITE_SPR, AS, Filename

Arguments

AS

A row-indexed sparse array created by SPRSIN.

Filename

The name of the file that will contain AS.

Example

A = [[3.,0., 1., 0., 0.],$	Create an array.

     [0.,4., 0., 0., 0.],$

     [0.,7., 5., 9., 0.],$

     [0.,0., 0., 0., 2.],$

     [0.,0., 0., 6., 5.]]

A = SPRSIN(A)	Convert it to sparse storage format.

WRITE_SPR, A, 'sprs.as'	Store it in the file sprs.as

See Also

FULSTR, LINBCG, SPRSAB, SPRSAX, SPRSIN, READ_SPR


WRITE_SRF

The WRITE_SRF procedure writes an image and its color table vectors to a Sun Raster File (SRF).

WRITE_SRF only writes 32-, 24-, and 8-bit-deep rasterfiles of type RT_STANDARD. Use the UNIX command rasfilter8to1 to convert these files to 1-bit deep files. See the file /usr/include/rasterfile.h for the structure of Sun rasterfiles.

This routine is written in the IDL language. Its source code can be found in the file write_srf.pro in the lib subdirectory of the IDL distribution.

Calling Sequence

WRITE_SRF, File [, Image, R, G, B]

Arguments

File

A scalar string containing the full path name of the SRF to write.

Image

The array to be written to the SRF. If Image has dimensions (3, n,m), a 24-bit SRF is written. If Image  is omitted, the entire current graphics window is read into an array and written to the SRF file. Image should be of byte type, and in top to bottom scan line order.

R, G, B

The Red, Green, and Blue color vectors to be written to the file. If R, G, B values are not provided, the last color table established using LOADCT is included. If no color table has been established, WRITE_PICT calls LOADCT to load the grayscale entry (table 0).

Keywords

ORDER

Set this keyword to write the image from the top down instead of from the bottom up. This setting is only necessary when writing a file from the current IDL graphics window; it is ignored when writing a file from a data array passed as a parameter.

WRITE_32

Set this keyword to write a 32-bit file. If the input image is a true color image, dimensioned (3,n,m), it is normally written as a 24-bit raster file.

Example

Create a pseudo screen dump from the current window:

WRITE_SRF, 'test.srf', TVRD()

See Also

READ_SRF


WRITE_SYLK

The WRITE_SYLK function writes the contents of an IDL variable to a SYLK (Symbolic Link) format spreadsheet data file. The function returns TRUE if the write operation was successful.

Note: This routine writes only numeric and string SYLK data. It cannot handle spreadsheet and cell formatting information (cell width, text justification, font type, date, time, monetary notations, etc.). A given SYLK data file cannot be appended with data blocks through subsequent calls.

This routine is written in the IDL language. Its source code can be found in the file write_sylk.pro in the lib subdirectory of the IDL distribution.

Calling Sequence

Result = WRITE_SYLK(File, Data)

Arguments

File

A scalar string specifying the full path name of the SYLK file to write.

Data

A scalar, vector, or 2D array to be written to File.

Keywords

STARTCOL

Set this keyword to the first column of spreadsheet cells to write. If not specified, the write operation begins with the first column found in the file (column 0).

STARTROW

Set this keyword to the first row of spreadsheet cells to write. If not specified, the write operation begins with the first row of cells found in the file (row 0).

Example

Suppose you wish to write the contents of a 2 by 2 floating-point array, data, to a SYLK data file called "bar.slk" such that the matrix would appear with it's upper left data at the cell in the 10th row and the 20th column. Use the following command:

status = WRITE_SYLK("bar.slk", data, STARTROW = 9, STARTCOL = 19)

The IDL variable status will contain the value 1 if the operation was successful.

See Also

READ_SYLK


WRITE_WAVE

The WRITE_WAVE procedure writes a three dimensional IDL array to a .wave or  .bwave file for use with the Wavefront Advanced Data Visualizer. Note that this routine only writes one scalar field for each Wavefront file that it creates.

This routine is written in the IDL language. Its source code can be found in the file write_wave.pro in the lib subdirectory of the IDL distribution.

Calling Sequence

WRITE_WAVE, File, Array

Arguments

File

A scalar string containing the full path name of the Wavefront file to write.

Array

A 3D array to be written to the file.

Keywords

BIN

Set this keyword to create a binary file. By default, text files are created.

DATANAME

Set this keyword to the name of the data inside of the Wavefront file. If not specified, the name used is "idldata".

MESHNAME

Set this keyword to the name of the mesh used in the Wavefront file. If not specified, the name used is "idlmesh".

NOMESHDEF

Set this keyword to omit the mesh definition from the Wavefront file.

VECTOR

Set this keyword to write the variable as a vector.

See Also

READ_WAVE


WRITEU

The WRITEU procedure writes unformatted binary data from an expression into a file. This procedure performs a direct transfer with no processing of any kind being done to the data.

Calling Sequence

WRITEU, Unit, Expr1 ..., Exprn

Arguments

Unit

The IDL file unit to which the output is sent.

Expri

The expressions to be output. For non-string variables, the number of bytes implied by the data type is output. When WRITEU is used with a variable of type string, IDL outputs exactly the number of bytes contained in the existing string.

Unix Keywords

TRANSFER_COUNT

Set this keyword to a named variable in which to return the number of elements transferred by the output operation. Note that the number of elements is not the same as the number of bytes (except in the case where the data type being transferred is bytes). For example, transferring 256 floating-point numbers yields a transfer count of 256, not 1024 (the number of bytes transferred).

This keyword is useful with files opened with the NOSTDIO keyword to the OPEN routines. Normally, writing more data than an output device will accept causes an error. Files opened with the NOSTDIO keyword will not generate such an error. Instead, the programmer must keep track of the transfer count to judge the success or failure of a WRITEU operation.

VMS Keywords

Note that the obsolete FORWRT routine has been replaced by WRITEU.

REWRITE

When writing data to a file with indexed organization, setting the REWRITE keyword specifies that the data should update the contents of the most recently input record instead of creating a new record.

Example

Create some data to store in a file by entering:

D = BYTSCL(DIST(200))

Open a new file for writing as IDL file unit number 1 by entering:

OPENW, 1, 'newfile'

To write the data in D to the file, enter:

WRITEU, 1, D

Close file unit 1 by entering:

CLOSE, 1

See Also

OPEN, READU


WSET

The WSET procedure selects the current window. Most IDL graphics routines do not explicitly require the IDL window to be specified. Instead, they use the window known as the current window. The window index number of the current window is contained in the read-only system variable !D.WINDOW. WSET only works with devices that have windowing systems.

Calling Sequence

WSET  [, Window_Index]

Arguments

Window_Index

This argument specifies the window index of the window to be made current. If this argument is not specified, a default of 0 is used.

Example

Create IDL windows 1 and 2 by entering:

WINDOW, 1 & WINDOW, 2

Set the current window to window 1 and display an image by entering:

WSET, 1 & TVSCL, DIST(100)

Set the current window to window 2 and display an image by entering:

WSET, 2 & TVSCL, DIST(100)

See Also

WDELETE, WINDOW, WSHOW


WSHOW

The WSHOW procedure exposes or hides the designated window.

Calling Sequence

WSHOW  [, Window_Index [, Show]]

Arguments

Window_Index

The window index of the window to be hidden or exposed. If this argument is not specified, the current window is assumed. If this index is the widget ID of a draw widget, the widget base associated with that drawable is brought to the front of the screen.

Show

Set Show to 0 to hide the window. Omit this argument or set it to 1 to expose the window.

Keywords

ICONIC

Set this keyword to iconify the window. Set ICONIC to 0 to de-iconify the window.

Under windowing systems, iconification is the task of the window manager, and client applications such as IDL have no direct control over it. The ICONIC keyword serves as a hint to the window manager, which is free to iconify the window or ignore the request as it sees fit.

Example

To bring IDL window number 0 to the front, enter:

WSHOW, 0

See Also

WDELETE, WINDOW, WSET


WTN

The WTN function returns a multi-dimensional discrete wavelet transform of the input array A. The transform is based on a Daubechies wavelet filter.

WTN is based on the routine wtn described in section 13.10 of Numerical Recipes in C: The Art of Scientific Computing (Second Edition), published by Cambridge University Press, and is used by permission.

Calling Sequence

Result = WTN(A, Coef)

Arguments

A

The input vector or array. The dimensions of A must all be powers of 2.

Coef

An integer that specifies the number of wavelet filter coefficients. The allowed values are 4, 12, or 20. When Coef is 4, the daub4()  function (see Numerical Recipes, section 13.10) is used. When Coef is 12 or 20, pwt() is called, preceded by pwtset() (see Numerical Recipes, section 13.10).

Keywords

COLUMN

Set this keyword if the input array A is in column-major format (composed of column vectors) rather than in row-major format (composed of row vectors).

DOUBLE

Set this keyword to force the computation to be done in double-precision arithmetic.

INVERSE

If the INVERSE keyword is set, the inverse transform is computed. By default, WTN performs the forward wavelet transform.

OVERWRITE

Set the OVERWRITE keyword to perform the transform "in place." The result overwrites the original contents of the array.

Example

This example demonstrates the use of IDL's discrete wavelet transform and sparse array storage format to compress and store an 8-bit gray-scale digital image. First, an image selected from the people.dat data file is transformed into its wavelet representation and written to a separate data file using the WRITEU procedure.

Next, the transformed image is converted, using the SPRSIN function, to row-indexed sparse storage format retaining only elements with an absolute magnitude greater than or equal to a specified threshold. The sparse image is written to a data file using the WRITE_SPR procedure.

Finally, the transformed image is reconstructed from the storage file and displayed alongside the original.

Begin by choosing the number of wavelet coefficients to use and a threshold value:

coeffs = 12 & thres = 10.0

Open the people.dat data file, read an image using associated variables, and close the file.

OPENR, 1, FILEPATH('people.dat', SUBDIR = 'images')

images = assoc(1, bytarr(192, 192))

image_1 = images(0)

close, 1

Expand the image to the nearest power of two using cubic convolution, and transform the image into its wavelet representation using the WTN function.

pwr = 256

image_1 = CONGRID(image_1, pwr, pwr, /CUBIC)

wtn_image = WTN(image_1, coeffs)

Write the image to a file using the WRITEU procedure and check the size of the file (in bytes) using the FSTAT function.

OPENW, 1, 'original.dat'

WRITEU, 1, wtn_image

status = FSTAT(1)

CLOSE, 1

PRINT, 'The size of the file is ', status.size, ' bytes.'

IDL prints:

The size of the file is       262144 bytes.

Now, we convert the wavelet representation of the image to a row-indexed sparse storage format using the SPRSIN function, write the data to a file using the WRITE_SPR procedure, and check the size of the "compressed" file.

sprs_image = SPRSIN(wtn_image, THRES = thres)

WRITE_SPR, sprs_image, 'sparse.dat'

OPENR, 1, 'sparse.dat'

status = FSTAT(1)

CLOSE, 1

PRINT, 'The size of the file is ', status.size, ' bytes.'

IDL prints:

The size of the file is        69600 bytes.

Determine the number of elements (as a percentage of total elements) whose absolute magnitude is less than the specified threshold. These elements are not retained in the row-indexed sparse storage format.

PRINT, 100.*N_ELEMENTS(WHERE(ABS(wtn_image) LT thres, $

    count)) / N_ELEMENTS(image_1)

IDL prints:

87.0331

This means the sparse array contains only 13% of the elements contained in the original array. Next, read the row-indexed sparse data back from the file sparse.dat using the READ_SPR function and reconstruct the image from the non-zero data using the FULSTR function.

sprs_image = READ_SPR('sparse.dat')

wtn_image = FULSTR(sprs_image)

Apply the inverse wavelet transform to the image.

image_2 = WTN(wtn_image, COEFFS, /INVERSE)

Calculate and print the amount of data used in reconstruction of the image.

PRINT, 'The image on the right is reconstructed from:', $

    100.0 - (100.* count/N_ELEMENTS(image_1)),$

    '% of original image data.'

IDL prints:

The image on the right is reconstructed from:

12.9669% of original image data.

Finally, display the original and reconstructed images side by side.

WINDOW, 1, XSIZE = pwr*2, YSIZE = pwr, $

    TITLE = 'Wavelet Image Compression and File I/O'

TV, image_1, 0, 0

TV, image_2, pwr - 1, 0

Sample Image

The

 image on the left is the original 256 by 256 image. The image on the right was compressed by the above process and was reconstructed from 13% of the original data. The size of the compressed image's data file is 26.6% of the size of the original image's data file. Note that due to limitations in the printing process, differences between the images may not be as evident as they would be on a high-resolution printer or monitor.

See Also

FFT


XBM_EDIT

The XBM_EDIT procedure allows users to create and edit icons for use with IDL widgets as bitmap labels for widget buttons.

The icons created with XBM_EDIT can be saved in two different file formats. IDL "array definition files" are text files that can be inserted into IDL programs. "Bitmap array files" are data files that can be read into IDL programs. Bitmap array files should be used temporarily until the final icon design is determined and then they can be saved as IDL array definitions for inclusion in the final widget code. This routine does not check the file types of the files being read and assumes that they are of the correct size and type for reading. XBM_EDIT maintains its state in a common block so it is restricted to one working copy at a time.

This routine is written in the IDL language. Its source code can be found in the file xbm_edit.pro in the lib subdirectory of the IDL distribution.

Calling Sequence

XBM_EDIT

Keywords

FILENAME

Set this keyword to a scalar string that contains the filename to be used for the new icon. If this argument is not specified, the name "idl.bm" is used. The filename can be changed in XBM_EDIT by editing the "Filename" field before selecting a file option.

GROUP

The widget ID of the widget that calls XBM_EDIT. When this ID is specified, the death of the caller results in the death of XBM_EDIT.

XSIZE

The number of pixels across the bitmap is in the horizontal direction. The default value is 16 pixels.

YSIZE

The number of pixels across the bitmap is in the vertical direction. The default value is 16 pixels.

See Also

WIDGET_BUTTON


XDISPLAYFILE

The XDISPLAYFILE procedure displays an ASCII text file using a widget interface.

This routine is written in the IDL language. Its source code can be found in the file xdisplayfile.pro in the lib subdirectory of the IDL distribution.

Calling Sequence

XDISPLAYFILE, Filename

Arguments

Filename

A scalar string that contains the filename of the file to display. Filename  can include a path to that file.

Keywords

FONT

A string containing the name of the font to use. This name should be an X Windows font for X displays, or a True Type or PostScript font name for Macintosh/Windows systems. The format of this string is the same as that described for the FONT keyword to the DEVICE command. "FONT" on page 3-11of the IDL Reference Guide. If this keyword is omitted, the default font is used.

GROUP

The widget ID of the widget that calls XDISPLAYFILE. If this keyword is specified, the death of the group leader results in the death of XDISPLAYFILE.

HEIGHT

The number of text lines that the widget should display at one time. If this keyword is not specified, 24 lines is the default.

TEXT

A string or string array to be displayed in the widget instead of the contents of a file. If this keyword is present, the Filename input argument is ignored (but is still required). String arrays are displayed one element per line.

TITLE

A string to use as the widget title rather than the file name or "XDisplayFile".

WIDTH

The width of the widget display in characters. If this keyword is not specified, 80 characters is the default.

See Also

PRINT, XYOUTS


XFONT

The XFONT function creates a modal widget for selecting and viewing an X Windows font. The function returns a string containing the name of the last selected font. If no font is selected, or the "Cancel" button is clicked, a null string

Calling XFONT resets the current X Windows font.

This routine is written in the IDL language. Its source code can be found in the file xfont.pro in the lib subdirectory of the IDL distribution.

Calling Sequence

Result = XFONT()

Keywords

GROUP

The widget ID of the widget that calls XFONT. When this ID is specified, the death of the caller results in the death  of XFONT.

PRESERVE

Set this keyword to make XFONT save the server font directory in common  blocks so that subsequent calls to XFONT start-up much  faster. If this keyword is not set, the common block is cleaned.

See Also

EFONT, SHOWFONT


XINTERANIMATE

The XINTERANIMATE procedure displays an animated sequence of images using off-screen pixmaps or memory buffers. The speed and direction of the display can be adjusted using the widget interface.

Note: Only a single copy of XINTERANIMATE can run at a time. If you need to run multiple instances of the animation widget concurrently, use the CW_ANIMATE compound widget.

This routine is written in the IDL language. Its source code can be found in the file xinteranimate.pro in the lib subdirectory of the IDL distribution.

Using XINTERANIMATE

Displaying an animated series of images using XINTERANIMATE requires at least three calls to the routine: one to initialize the animation widget, one to load images, and one to display the images. When initialized using the SET keyword, XINTERANIMATE creates an approximately square pixmap or memory buffer, large enough to contain the requested number of frames of the requested size. Images are loaded using the IMAGE and FRAME keywords. Finally, images are displayed by copying them from the pixmap or memory buffer to the visible draw widget.

Calling Sequence

XINTERANIMATE [, Rate]

Arguments

Rate

A value between 0 and 100 that represents the speed of the animation as a percentage of the maximum display rate. The fastest animation is with a value of 100 and the slowest is with a value of 0. The default animation rate is 100. The animation must be initialized using the SET keyword before calling XINTERANIMATE with a rate value.

Keywords —Initialization

The following keywords are used to initialize the animation display. The SET keyword must be provided. Other keywords described in this section are optional; note that they work only when SET is specified.

SET

Set this keyword to a three-element vector [Sizex, Sizey, Nframes] to initialize XINTERANIMATE. Sizex and Sizey represent the width and height of the images to be displayed, in pixels. Nframes is the number of frames in the animation sequence. Note that Nframes must be at least 2 frames.

CYCLE

Normally, frames are displayed going either forward or backwards. If the CYCLE keyword is set, the animation reverses direction after the last frame in either direction is displayed.

SHOWLOAD

Set this keyword to display each frame and update the frame slider as frames are loaded.

TRACK

Set this keyword to cause the frame slider to track the current frame when the animation is in progress. The default is not to track.

TITLE

Use this keyword to specify a string to be used as the title of the animation widget. If TITLE is not specified, the title is set to "XInterAnimate."

Keywords —Loading Images

The following keywords are used to load images into the animation display. They have no effect when initializing or running animations.

FRAME

Use this keyword to specify the frame number when loading frames. FRAME must be set to a number in the range 0 to Nframes-1.

IMAGE

Use this keyword to specify a single image to be loaded at the animation position specified by the FRAME keyword. (FRAME must also be specified.)

ORDER

Set this keyword to display images from the top down instead of the default bottom up.

WINDOW

When this keyword is specified, an image is copied from an existing window to the animation pixmap or memory buffer. (When using some windowing systems, using this keyword is much faster than reading from the display and then calling XINTERANIMATE with a 2D array.)

The value of this parameter is either an IDL window number (in which case the entire window is copied), or a vector containing the window index and the rectangular bounds of the area to be copied. For example:

WINDOW = [Window_Number, X0, Y0, Sx, Sy]

Keywords—Running Animations

The following keywords are used to when running the animation. They have no effect when initializing the animation or loading images.

CLOSE

Set this keyword to delete the offscreen pixmaps or buffers and the animation widget itself. This also takes place automatically when the user presses the "Done With Animation" button or closes the window with the window manager.

GROUP

Set this keyword to the widget ID of the widget that calls XINTERANIMATE. When GROUP is specified, the death of the calling widget results in the death of XINTERANIMATE.

KEEP_PIXMAPS

If this keyword is set, XINTERANIMATE will not destroy the animation pixmaps or buffers when it is killed. Calling XINTERANIMATE again without going through the SET and LOAD steps will play the same animation without the overhead of creating the pixmaps.

XOFFSET

Use this keyword to specify the horizontal offset, in pixels from the left of the frame, of the image in the destination window.

YOFFSET

Use this keyword to specify the vertical offset, in pixels from the bottom of the frame, of the image in the destination window.

Example

Enter the following commands to open the file ABNORM.DAT (a series of images of a human heart) and animate the images it contains using XINTERANIMATE. For a more detailed example of using XINTERANIMATE, see the example in the "Using IDL Widgets" chapter of IDL Basics.

Read the images into the variable H by entering:

OPENR, 1, FILEPATH('abnorm.dat', SUBDIR = 'images')

H = BYTARR(64, 64, 16)

READU, 1, H

CLOSE, 1

H = REBIN(H, 128, 128, 16)

Initialize XINTERANIMATE with the command:

XINTERANIMATE, SET=[128, 128, 16], /SHOWLOAD

Load the images into XINTERANIMATE:

FOR I=0,15 DO XINTERANIMATE, FRAME = I, IMAGE = H(*,*,I)

Play the animation by entering:

XINTERANIMATE, /KEEP_PIXMAPS

Note that since the KEEP_PIXMAPS keyword was supplied, the same animation can be replayed (after the animation widget has been destroyed) with the single command:

XINTERANIMATE

See Also

CW_ANIMATE


XLOADCT

The XLOADCT procedure provides a graphical widget interface to the LOADCT procedure. XLOADCT displays the current colortable and shows a list of available predefined color tables. Clicking on the name of a color table causes the color table to be loaded. Many other options, such as Gamma correction, stretching, and transfer functions can also be applied to the colortable.

This routine is written in the IDL language. Its source code can be found in the file xloadct.pro in the lib subdirectory of the IDL distribution.

Calling Sequence

XLOADCT

Keywords

FILE

If this keyword is set, the file by the given name is used instead of the file colors1.tbl in the IDL directory.

BOTTOM

The first color index to use. XLOADCT will use color indices from BOTTOM to BOTTOM+NCOLORS-1. The default is BOTTOM=0.

GROUP

The widget ID of the widget that calls XLOADCT. When this ID is specified, a death of the caller results in a death of XLOADCT.

NCOLORS

The number of colors to use. Use color indices from 0 to the smaller of !D.TABLE_SIZE-1 and NCOLORS-1. The default is all available colors (!D.TABLE_SIZE).

PICK_ONE

Normally, XLOADCT remains running until the user presses the "QUIT" button. Set the PICK_ONE keyword to suppress the "QUIT" button and exit XLOADCT after a single colortable selection has been made.

SILENT

Normally, no informational message is printed when a color map is loaded. If this keyword is set to zero, the message is printed.

USE_CURRENT

Set this keyword to use the current color tables, regardless of the contents of the COLORS common block.

See Also

LOADCT, XPALETTE


XMANAGER

The XMANAGER procedure provides the main event loop and management for widgets created using IDL. Calling XMANAGER "registers" a widget program with the XMANAGER event handler. XMANAGER takes control of event processing and locks out the IDL prompt until all widgets have been destroyed.

This routine is written in the IDL language. Its source code can be found in the file xmanager.pro in the lib subdirectory of the IDL distribution.

Calling Sequence

XMANAGER [, Name, ID]

Arguments

Name

A string that contains the name of the routine that creates the widget (i.e., the name of the widget creation routine that is calling XMANAGER).

ID

The widget ID of the new widget's top-level base.

Keywords

BACKGROUND

This keyword is obsolete and is included in XMANAGER for compatibility with existing code only. Its functionality has been replaced by the TIMER keyword to the WIDGET_CONTROL procedure.

A string that contains the name of a background task procedure to be called when the event loop is idle.

CLEANUP

Set this keyword to a string that contains the name of the routine to be called when the widget dies. If not specified, no routine is called. The cleanup routine must accept one parameter which is the widget ID of the dying widget.

EVENT_HANDLER

Set this keyword to a string that contains the name of a routine to be called when a widget event occurs in the widget program being registered. If this keyword is not supplied, XMANAGER tries to process the event by calling the routine name with "_event" appended. See the example below for a more detailed explanation.

GROUP_LEADER

The widget ID of the group leader for the widget being processed. When the leader dies either by the users actions or some other routine, all widgets that have that leader will also die.

For example, a widget that views a help file for a demo widget would have that demo widget as its leader. When the help widget is registered, it sets the keyword GROUP_LEADER to the widget ID of the demo widget. If the demo widget were destroyed, the help widget led by it would be killed by the XMANAGER.

JUST_REG

Set this keyword to indicate that XMANAGER should just register the widget but not start processing events. This keyword is useful when you want to register a group of related top-level widgets before beginning processing.

MODAL

When this keyword is set, the widget that is being registered traps all events and desensitizes all the other widgets. It is useful when input from the user is necessary to continue (i.e., "blocking" dialog boxes). Once the modal widget dies, the others are resensitized and the normal event processing continues.

Warning

Although this routine is written in the IDL language, it may change in the future in its internal implementation. For future upgradability, it is best not to modify or even worry about what this routine does internally.

Example

The following code creates a widget named EXAMPLE that is just a base widget with a "Done" button and registers it with the XMANAGER. Widgets being registered with the Xmanager must provide at least two routines. The first routine creates the widget and registers it with the manager and the second routine processes the events that occur within that widget. Optionally, a third routine can is used for the processing of background tasks while awaiting input. An example widget is supplied below that uses only two routines. A number of other "Simple Widget Examples", can be viewed by entering WEXMASTER at the IDL prompt. These simple programs demonstrate many aspects of widget programming.

The following lines of code would be saved in a single file, named example.pro:

PRO example_event, ev	Begin the event handler routine for the EXAMPLE widget.

WIDGET_CONTROL, ev.id, GET_UVALUE = uv
The uservalue is retrieved from a widget when an event occurs.

if (uv eq 'DONE') THEN WIDGET_CONTROL, ev.top, /DESTROY
 If the event occurred in the Done button, kill the widget example.

END	End of the event handler part.

PRO example	This is the routine that creates the widget and registers it with the XMANAGER.

base = WIDGET_BASE(TITLE='Example')
Create the top-level base for the widget.

done = WIDGET_BUTTON(base, TITLE = 'Done', UVALUE = 'DONE')
Create the Done button and set its uservalue to "DONE".

WIDGET_CONTROL, base, /REALIZE	Realize the widget (i.e., display it on screen).

XMANAGER, 'example', base	Register the widget with the XMANAGER.

END	End of the widget creation part.

First the event handler routine is listed. The handler routine has the same name as the main routine with the characters "_event" added. If you would like to use another event handler name, you would need to pass its name to XMANAGER using the EVENT_HANDLER keyword.

Notice that the event routine is listed before the main routine. This is because the compiler will not compile the event routine if it was below the main routine. This is only needed if both routines reside in the same file and the file name is the same as the main routine name with the .pro extension added.

See Also

XMTOOL, XREGISTERED, Chapter 21 of the IDL User's Guide


XMNG_TMPL

The XMNG_TMPL procedure is a template for widgets that use the XMANAGER. Use this template instead of writing your widget applications from "scratch". This template can be found in the file  xmng_tmpl.pro in the lib subdirectory of the IDL distribution.

The documentation header should be altered to reflect the actual implementation of the XMNG_TMPL widget. Use a global search and replace to replace the word XMNG_TMPL with the name of the routine you would like to use. All the comments with a "***" in front of them should be read, decided upon and removed from the final copy of your new widget routine.

Calling Sequence

XMNG_TMPL

Keywords

GROUP

The widget ID of the widget that calls XMNG_TMPL. When this ID is specified, the death of the caller results in the death of XMNG_TMPL.

See Also

CW_TMPL


XMTOOL

The XMTOOL procedure displays a tool for viewing widgets currently being managed by the XMANAGER. Only one instance of the XMTOOL can run at one time.

This routine is written in the IDL language. Its source code can be found in the file xmtool.pro in the lib subdirectory of the IDL distribution.

Calling Sequence

XMTOOL

Keywords

GROUP

The widget ID of the widget that calls XMTOOL. If the calling widget is destroyed, the XMTOOL is also destroyed.

See Also

XLOADCT


XPALETTE

The XPALETTE procedure displays a widget interface that allows interactive creation and modification of colortables using the RGB, CMY, HSV, or HLS color systems. Single colors can be defined or multiple color indices between two endpoints can be interpolated.

This routine is written in the IDL language. Its source code can be found in the file xpalette.pro in the lib subdirectory of the IDL distribution.

Calling Sequence

XPALETTE

Keywords

GROUP

The widget ID of the widget that calls XPALETTE. When this ID is specified, a death of the caller results in a death of XPALETTE.

Using the XPALETTE Interface

Calling XPALETTE causes a graphical interface to appear. The elements of this interface are described below.

Plots on Left Side of Interface: Three plots show the current red, green, and blue vectors.

Status Region: The center of the XPALETTE widget is a status region containing:

•	The total number of colors.

•	The current color index. XPALETTE allows changing one color at a time. This color is known as the "current color" and is indicated in the color spectrum display with a special marker.

•	The current mark index. The mark is used to remember a color index. Click the "Set Mark Button" to make the current color index the mark index.

•	A sample of the current color. The special marker used in the color spectrum display prevents the user from seeing the color of the current index, but it is visible here.

Control Panel: A panel of 8 buttons control common XPALETTE functions:

•	Done: Click this button to exit XPALETTE. The new color tables are saved in the COLORS common block and loaded to the display.

•	Predefined: Click this button to start XLOADCT, allowing selection of one of the predefined color tables. Note that when you change the color map via XLOADCT, XPALETTE is not always able to keep its display accurate. This problem can be overcome by pressing the XPALETTE "Redraw" button after changing the colortable via XLOADCT.

•	Help: Click this button to display help information.

•	Redraw: Click this button to redraws the display using the current state of the color map.

•	Set Mark: Click this button to set the value of the mark index to the current color index.

•	Switch Mark: Click this button to exchange the mark and the current index.

•	Copy Current: Click this button to make every color lying between the current index and the mark index (inclusive) the same color as the current color.

•	Interpolate: Click this button to smoothly interpolate colors between the current index and the mark index.

Color System Control: This section of the interface allows you to select the color system used to modify individual colors. The "Select Color System" pulldown menu lets you select from four different systems—RGB, CMY, HSV, and HLS. Depending upon the current system, 3 sliders below the pulldown menu allow you to alter the current color.

Right Side Color Spectrum Display: A display on the right side of the XPALETTE interface shows the current color map as a series of squares. Color index 0 is at the upper left. The color index increases monotonically by rows going left to right and top to bottom. The current color index is indicated by a special marker symbol. There are 4 ways to change the current color:

•	Click on any square in the color map display.

•	Use the "By Index" slider to move to the desired color index.

•	Use the "Row" Slider to move the marker vertically.

•	Use the "Column" Slider to move the marker horizontally.

A Note about the Colors Used in the Interface

XPALETTE uses two colors from the current color table as drawing foreground and background colors. These are used for the RGB plots on the left, and the current index marker on the right. This means that if the user set these two colors to the same value, the XPALETTE display could become unreadable (like writing on black paper with black ink). XPALETTE minimizes this possibility by noting changes to the color map and always using the brightest available color for the foreground color and the darkest for the background. Thus, the only way to make XPALETTE's display unreadable is to set the entire color map to a single color, which is highly unlikely. The only side effect of this policy is that you may notice XPALETTE redrawing the entire display after you've modified the current color. This simply means that the change has made XPALETTE pick new drawing colors.

See Also

LOADCT, MODIFYCT, XLOADCT


XREGISTERED

The XREGISTERED function returns True if the widget named as its argument is currently registered with the XMANAGER as an exclusive widget. Otherwise the routine returns false.

If the named widget is registered, XREGISTERED returns the number of instances of that name in the list maintained by XMANAGER. The registered widget is brought to the front of the desktop unless the NOSHOW keyword is set.

This routine is written in the IDL language. Its source code can be found in the file xregistered.pro in the lib subdirectory of the IDL distribution.

Calling Sequence

Result = XREGISTERED(Name)

Arguments

Name

A string containing the name of the widget in question.

Keywords

NOSHOW

If the widget in question is registered, it is brought to the front of all the other windows by default. Set this keyword to keep the widget from being brought to the front.

Example

Suppose that you have a widget program that registers itself with the XMANAGER with the command:

XMANAGER, 'mywidget', base

You could limit this widget to one instantiation by adding the following line as the first line (after the procedure definition statement) of the widget creation routine:

IF XREGISTERED('mywidget') THEN RETURN

See Also

XMANAGER


XSQ_TEST

The XSQ_TEST function computes the Chi-square goodness-of-fit test between observed frequencies and the expected frequencies of a theoretical distribution. The result is a two-element vector containing the Chi-square test statistic X2 and the one-tailed probability of obtaining a value of X2 or greater.

Expected frequencies of magnitude less than 5 are combined with adjacent elements resulting in a reduction of cells used to formulate the chi-squared test statistic. If the observed frequencies differ significantly from the expected frequencies, the Chi-square test statistic will be large and the fit is poor. This situation requires the rejection of the hypothesis that the given observed frequencies are an accurate approximation to the expected frequency distribution.

This routine is written in the IDL language. Its source code can be found in the file xsq_test.pro in the lib subdirectory of the IDL distribution.

Calling Sequence

Result = XSQ_TEST(Obfreq, Exfreq)

Arguments

Obfreq

An n-element integer, single-, or double-precision floating-point vector containing observed frequencies.

Exfreq

An n-element integer, single-, or double-precision floating-point vector containing expected frequencies.

Keywords

EXCELL

Set this keyword to a named variable that will contain a vector of expected frequencies used to formulate the Chi-square test statistic. If each of the expected frequencies contained in Exfreq, has a magnitude of 5 or greater, then this vector is identical to Exfreq. If Exfreq contains elements of magnitude less than 5, adjacent expected frequencies are combined. The identical combinations are performed on the corresponding elements of Obfreq.

OBCELL

Set this keyword to a named variable that will contain a vector of observed frequencies used to formulate the Chi-square test statistic. The elements of this vector are often referred to as the "cells" of the observed frequencies. The length of this vector is determined by the length of EXCELL described below.

RESIDUAL

Set this keyword to a named variable that will contain a vector of signed differences between corresponding cells of observed frequencies and expected frequencies.

RESIDUAL(i) = OBCELL(i) - EXCELL(i).

The length of this vector is determined by the length of EXCELL described above.

Example

Define the vectors of observed and expected frequencies.

obfreq = [2, 1, 4, 15, 10, 5, 3]

exfreq = [0.5, 2.1, 5.9, 10.3, 10.7, 7.0, 3.5]

Test the hypothesis that the given observed frequencies are an accurate approximation to the expected frequency distribution.

result = XSQ_TEST(obfreq, exfreq)

PRINT, result

IDL prints:

3.05040     0.383920

Since the vector of expected frequencies contains elements of magnitude less than 5, adjacent expected frequencies are combined resulting in fewer cells. The identical combinations are performed on the corresponding elements of observed frequencies. The computed value of 0.383920 indicates that there is no reason to reject the proposed hypothesis at the 0.05 significance level.

See Also

CTI_TEST


XSURFACE

The XSURFACE procedure provides a graphical interface to the SURFACE and SHADE_SURF commands. Different controls are provided to change the viewing angle and other plot parameters. The command used to generate the resulting surface plot is shown in a text window. Note that this procedure does not accept SURFACE or SHADE_SURF keywords.

This routine is written in the IDL language. Its source code can be found in the file xsurface.pro in the lib subdirectory of the IDL distribution.

Calling Sequence

XSURFACE, Data

Arguments

Data

The two-dimensional array to display as a wire-mesh or shaded surface.

Keywords

GROUP

Set this keyword to the widget ID of the widget that calls XSURFACE. When GROUP is specified, the death of the calling widget results in the death of XSURFACE.

Example

z = DIST(30)	Make a 2D array.

XSURFACE, z	Call XSURFACE. The XSURFACE widget appears.

See Also

SHADE_SURF, SURFACE


XVAREDIT

The XVAREDIT procedure is a widget-based editor for any IDL variable. If the variable is exceedingly large such as a giant structure or huge array, the editor will not fit on the screen and may not be able to create enough widget components to edit the whole variable. Use the input fields to change desired values of the variable or array. Click "Accept" to write the new values into the variable. Click "Cancel" to exit XVAREDIT without saving changes.

This routine is written in the IDL language. Its source code can be found in the file xvaredit.pro in the lib subdirectory of the IDL distribution.

Calling Sequence

XVAREDIT, Var

Arguments

Var

The variable to be edited. On output, this variable contains the edited value if the user selects the "Accept" button, or the original value if the user selects the "Cancel" button.

Keywords

NAME

The NAME of the variable.  This keyword is overwritten with the structure name if the variable is a structure.

GROUP

The widget ID of the widget that calls XVAREDIT.  When this ID is specified, a death of the caller results in a death of XVAREDIT.


XYOUTS

The XYOUTS procedure draws text on the currently-selected graphics device starting at the designated coordinate.

Arguments X, Y, and String can be any combination of scalars or arrays. If the arguments are arrays, multiple strings are output.

If the optional X and Y arguments are omitted, the text is positioned at the end of the most recently output text string.

Important keywords that control the appearance and positioning of the text include: ALIGNMENT, the justification of the text; CHARSIZE, the size of the text; FONT, chooses between vector drawn and hardware fonts; COLOR, the color of the text; and ORIENTATION, the angle between the baseline of the text and the horizontal. With hardware fonts, most of the text attributes, (e.g., size and orientation), are predetermined and not changeable.

Note: specify the Z coordinate with the Z keyword when positioning text in three dimensions.

Calling Sequence

XYOUTS, [X, Y,] String

Arguments

X, Y

The horizontal and vertical coordinates used to position the string(s). X and Y are normally interpreted in data coordinates. The DEVICE and NORMAL keywords can be used to specify the coordinate units.

X and Y can be arrays of positions if String is an array.

String

The string(s) to be output. This argument can be a scalar string or an array of strings. If this argument is not a string, it is converted prior to use using the default formatting rules.

If String is an array, X, Y, and the COLOR keyword can also be arrays so that each string can have a separate location and color.

Keywords

ALIGNMENT

Specifies the alignment of the text baseline. An alignment of 0.0 (the default) aligns the left edge of the text baseline with the given (x, y ) coordinate. An alignment of 1.0 right-justifies the text, while 0.5 results in text centered over the point (x, y).

CHARSIZE

The overall character size for the annotation. A CHARSIZE of 1.0 is normal. Setting CHARSIZE = -1 suppresses output of the text string.

CHARTHICK

The line thickness of the vector drawn font characters.This keyword has no effect when used with the hardware drawn fonts. The default value is 1.0.

TEXT_AXES

This keyword specifies the plane of vector drawn text when three-dimensional plotting is enabled. By default, text is drawn in the plane of the XY axes. The horizontal text direction is in the X plane, and the vertical text direction is in the Y plane. Values for this keyword can range from 0 to 5, with the following effects: 0 for XY, 1 for XZ, 2 for YZ, 3 for YX, 4 for ZX, and 5 for ZY. The notation ZY means that the horizontal direction of the text lies in the Z plane, and the vertical direction of the text is drawn in the Y plane.

WIDTH

Set this keyword to a named variable in which to return the width of the text string, in normalized coordinate units.

Graphics Keywords Accepted

See Chapter 2, "Graphics Keywords and System Variables", for the description of graphics and plotting keywords not listed above. CLIP COLOR DATA DEVICE FONT NOCLIP NORMAL ORIENTATION T3D Z.

Example

Print the string "This is text" at device coordinate position (100,100) by entering:

XYOUTS, 100, 100, 'This is text', /DEVICE

Print an array of strings with each element of the array printed at a different location. Use larger text than in the previous example. Enter:

XYOUTS, [0, 200, 250], [200, 50, 100], ['This', 'is', 'text'], CHARSIZE = 3, /DEVICE

See Also

ANNOTATE, DISP_TXT, PRINT


ZOOM

The ZOOM procedure displays part of an image from the current window enlarged in a new ("zoom") window. The cursor is used to mark the center of the zoom area, and different zoom factors can be specified interactively.

Note: ZOOM only works with color systems.

This routine is written in the IDL language. Its source code can be found in the file zoom.pro in the lib subdirectory of the IDL distribution.

Using ZOOM

After calling ZOOM, place the mouse cursor over an image in an IDL graphics window. Click the left mouse button to display a magnified version of the image in a new window. The zoomed image is centered around the pixel selected in the original window. Click the middle mouse button to display a menu of zoom factors. Click the right mouse button to exit the procedure.

Calling Sequence

ZOOM

Keywords

CONTINUOUS

Set this keyword to make the zoom window track the mouse without requiring the user to press the left mouse button. This feature only works well on fast computers.

FACT

Use this keyword to specify the zoom factor, which must be an integer. The default zoom factor is 4.

INTERP

Set this keyword to use bilinear interpolation. The default is to use pixel replication.

KEEP

Set this keyword to keep the zoom window after exiting the procedure.

NEW_WINDOW

Normally, if ZOOM is called with KEEP and then called again, it will use the same window to display the new zoomed image. Set the NEW_WINDOW keyword to force ZOOM to create a new window for this purpose.

XSIZE

Use this keyword to specify the X size of the zoom window. The default is 512.

YSIZE

Use this keyword to specify the Y size of the zoom window. The default is 512.

ZOOM_WINDOW

Set this keyword to a named variable that will contain the index of the zoom window. KEEP must also be set. If KEEP is not set, ZOOM_WINDOW will contain the integer -1.

See Also

CW_ZOOM, ZOOM_24


ZOOM_24

The ZOOM_24 procedure displays part of a 24-bit color image from the current window expanded in a new ("zoom") window, and provides information about cursor location and color values in an auxiliary ("data") window. The cursor is used to mark the center of the zoom area, and different zoom factors can be specified interactively.

Note: ZOOM only works on 24-bit color systems.

This routine is written in the IDL language. Its source code can be found in the file zoom_24.pro in the lib subdirectory of the IDL distribution.

Using ZOOM_24

After calling ZOOM_24, windows titled "Zoomed Image" (the zoom window) and "Pixel Values" (the data window) appear on the screen. Place the mouse cursor over a 24-bit color image in an IDL graphics window and click the left mouse button to display a magnified version of the image in the zoom window. The zoomed image is centered around the pixel selected in the original window. Move the mouse cursor in the zoom window to determine the coordinates (in the original image) and color values of individual pixels.

With the cursor located in the zoom window, click the right mouse button to return to selection mode, which allows you to either choose a new zoom center, change the zoom factor, or exit the procedure. Move the cursor to the original image and click the middle mouse button to display a menu of zoom factors, or click the right mouse button to exit the procedure.

Calling Sequence

ZOOM_24

Keywords

FACT

Use this keyword to specify the zoom factor, which must be an integer. The default zoom factor is 4.

RIGHT

Set this keyword to position the zoom and data windows to the right of the original window.

XSIZE

Use this keyword to specify the X size of the zoom window. The default is 512.

YSIZE

Use this keyword to specify the Y size of the zoom window. The default is 512.

See Also

CW_ZOOM, ZOOM


Graphics Keyword and System Variables Introduction
2	Graphics Keywords and
System Variables

This chapter contains descriptions of common keywords to IDL's graphics and plotting routines. It also describes the system variables used to control IDL graphics output. It has two main sections:

•	"Graphics Keywords" on page 2-2.

•	"System Variables for Graphics" on page 2-15.


Graphics Keywords

Graphics Keywords A-R

Graphics Keywords S-Z

The graphics routines, CURSOR, ERASE, PLOTS, POLYFILL, TV (and TVSCL), TVCRS, TVRD, and XYOUTS, and the plotting procedures, AXIS, CONTOUR, PLOT, OPLOT, SHADE_SURF, and SURFACE, accept a number of common keywords. Therefore, instead of describing each keyword along with the description of each routine, this section contains a brief summary of each graphics keyword. Routine-specific keywords are documented in the description of the routine in Chapter 1, "IDL Routines".

The graphics keywords are described below. Click on a keyword in the scrolling list at left. The name of the keyword appears followed by a list of routines that accept that keyword. Keywords that have a direct correspondence to fields in a system variable (usually !P) are also indicated.

The keywords that control the plot axes are prefixed with the character `X', `Y', or `Z' depending on the axis in question. These keywords correspond to fields in the axis system variables: !X, !Y, and !Z, and are described in more detail in "System Variables for Graphics" on page 2-15. The axis keywords are shown in the form [XYZ]NAME. For example, [XYZ]CHARSIZE refers to the three keywords XCHARSIZE, YCHARSIZE, and ZCHARSIZE, which control the size of the characters annotating the three axes. The system variable fields that control this are !X.CHARSIZE, !Y.CHARSIZE, and !Z.CHARSIZE.

BACKGROUND

Accepted by:  CONTOUR, PLOT, SURFACE. System variable equivalent: !P.BACKGROUND.

The background color index to which the screen is set when erasing. Not all devices support erasing the background to a color index.

Example

To produce a black plot with a white background on a color display:

PLOT, Y, BACKGROUND = 255, COLOR = 0

CHANNEL

Accepted by: ERASE, TV, TVRD. System variable equivalent: !P.CHANNEL.

This keyword specifies the memory channel for the operation. This parameter is ignored on display systems that have only one memory channel. When using a "decomposed" display system, the red channel is 1, the green channel is 2, and the blue channel is 3. Channel 0 indicates all channels. If omitted, !P.CHANNEL contains the default channel value.

Note that CONTOUR, PLOT, SHADE_SURF, and SURFACE also accept the CHANNEL keyword, but simply pass it to ERASE.

CHARSIZE

Accepted by: AXIS, CONTOUR, PLOT, SHADE_SURF, SURFACE, XYOUTS. System variable equivalent: !P.CHARSIZE.

The overall character size for the annotation. A CHARSIZE of 1.0 is normal. The size of the annotation on the axes may be set, relative to CHARSIZE, with xCHARSIZE, where x is X, Y, or Z. The main title is written with a character size of 1.25 times this parameter.

[XYZ]CHARSIZE

Accepted by: AXIS, CONTOUR, PLOT, SHADE_SURF, SURFACE. System variable equivalent: !P.CHARSIZE.

The size of the characters used to annotate the axis and its title. This field is a scale factor applied to the global scale factor set by !P.CHARSIZE or the keyword CHARSIZE.

CHARTHICK

Accepted by: AXIS, CONTOUR, PLOT, SHADE_SURF, SURFACE, XYOUTS. System variable equivalent: !P.CHARTHICK.

The line thickness of the vector drawn font characters.This keyword has no effect when used with the hardware drawn fonts. The default value is 1.0.

CLIP

Accepted by: AXIS, CONTOUR, OPLOT, PLOT, PLOTS, POLYFILL, SHADE_SURF, SURFACE, XYOUTS. System variable equivalent: !P.CLIP.

The coordinates of a rectangle used to clip the graphics output. The rectangle is specified as a vector of the form [X0, Y0,  X1, Y1], giving coordinates of the lower left and upper right corners, respectively. The default clipping rectangle is the plot window, the area enclosed within the axes of the most recent plot. Coordinates are specified in data units unless an overriding coordinate unit specification keyword is present (i.e., NORMAL or DEVICE).

Note: the default is not to clip the output of PLOTS and XYOUTS. To enable clipping include the keyword parameter NOCLIP = 0. With PLOTS, POLYFILL, and XYOUTS, this keyword controls the clipping of vectors and vector-drawn text.

Example

To draw a vector using normalized coordinates with its contents clipped within a rectangle covering the upper left quadrant of the display:

PLOTS, X, Y, CLIP=[0.,.5,.5,1.0], /NORM, NOCLIP=0

COLOR

Accepted by: AXIS, CONTOUR, ERASE, OPLOT, PLOT, PLOTS, POLYFILL, SHADE_SURF, SURFACE, XYOUTS. System variable equivalent: !P.COLOR.

The color index of the data, text, line, or solid polygon fill to be drawn. If this keyword is omitted, !P.COLOR specifies the color index.

When used with the PLOTS, POLYFILL, or XYOUTS procedure, this keyword parameter can be set to a vector to specify multiple color indices.

Gouraud shading of polygons is performed with the Z-buffer graphics output device and POLYFILL procedure when COLOR contains an array of color indices, one for each vertex.

DATA

Accepted by: AXIS, CONTOUR, CURSOR, PLOT, PLOTS, POLYFILL, SHADE_SURF, SURFACE, TV, TVCRS, XYOUTS.

Set this keyword to indicate that the coordinates are in data coordinates. The default coordinate system is DATA if no other coordinate-system specifications are present.

DEVICE

AXIS, CONTOUR, CURSOR, PLOT, PLOTS, POLYFILL, SHADE_SURF, SURFACE, TV, TVCRS, XYOUTS.

Set this keyword to indicates that coordinates are expressed in device coordinates.

Example

The following code displays an image contained in the variable A and then draws a contour plot of pixels (100:499, 100:399) over the correct section of the image:

TV,A	Display the image.

CONTOUR, A(100:499, 100:399), $

         POS = [100,100, 499,399], /DEVICE, $

         /NOERASE, XSTYLE=1, YSTYLE=1
Draw the contour plot, specify the coordinates of the plot, in device coordinates, do not erase, set the X and Y axis styles to EXACT.

Note that in the above example, the keyword specification /DEVICE  is equivalent to DEVICE = 1.

FONT

Accepted by: AXIS, CONTOUR, PLOT, SHADE_SURF, SURFACE, XYOUTS. System variable equivalent: !P.FONT.

An integer that specifies the graphics text font index. Font number -1 selects the Hershey character fonts which are drawn using vectors. Font 0 uses the hardware font of the output device.

The Hershey fonts are selected by command strings beginning with the exclamation mark character within the graphic text string. See Chapter 9 of the IDL User's Guide for a complete description of the vector-drawn fonts.

When using three-dimensional transformations, always use the vector drawn fonts, as the hardware fonts are not properly projected from three to two dimensions.

[XYZ]GRIDSTYLE

Accepted by: AXIS, CONTOUR, PLOT, SHADE_SURF, SURFACE

The index of the linestyle to be used for plot tickmarks and grids (i.e., when [XYZ]TICKLEN is set to 1.0). See Table 2.1 for a list of linestyles.

Graphics Keywords, continued


Graphics Keywords, continued

Graphics Keywords A-R

Graphics Keywords S-Z

LINESTYLE

Accepted by:  OPLOT, PLOT, PLOTS, SURFACE. System variable equivalent: !P.LINESTYLE.

This keyword indicates the line style used to draw lines for PLOTS. For PLOT, OPLOT, and SURFACE, it indicates the line style of the lines used to connect the data points. This keyword should be set to the appropriate index for the desired linestyle as deleted in the following table.

Index	Linestyle
0	Solid
1	Dotted
2	Dashed
3	Dash Dot
4	Dash Dot Dot Dot
5	Long Dashes
Table 2.1 IDL Linestyles

[XYZ]MARGIN

Accepted by:  AXIS, CONTOUR, PLOT, SHADE_SURF, SURFACE. System variable equivalent: ![XYZ].MARGIN.

A 2-element array specifying the margin on the left (bottom) and right (top) sides of the plot window, in units of character size. Default margins are 10 and 3 for the X axis, and 4 and 2 for the Y axis.

[XYZ]MINOR

Accepted by:  AXIS, CONTOUR, PLOT, SHADE_SURF, SURFACE. System variable equivalent: ![XYZ].MINOR.

The number of minor tick marks.

NOCLIP

Accepted by:  AXIS, CONTOUR, OPLOT, PLOT, PLOTS, POLYFILL, SHADE_SURF, SURFACE, XYOUTS. System variable equivalent: !P.NOCLIP.

Set this keyword to suppress clipping of the plot. By default, the plot is clipped within the plotting window.

Note: the default value is clipping disabled for PLOTS, POLYFILL, and XYOUTS. For all other routines, the default is to enable clipping.

With PLOTS, POLYFILL, and XYOUTS, this keyword controls the clipping of vectors and vector-drawn text. The default is to disable clipping, so to enable clipping include the parameter NOCLIP = 0. To explicitly enable clipping set this parameter to one.

NODATA

Accepted by:  AXIS, CONTOUR, PLOT, SHADE_SURF, SURFACE.

If this keyword is set, only the axes, titles, and annotation are drawn. No data points are plotted.

Example

To draw an empty set of axes between some given values:

PLOT, [XMIN, XMAX],[YMIN, YMAX], /NODATA

NOERASE

Accepted by: AXIS, CONTOUR, PLOT, SHADE_SURF, SURFACE. System variable equivalent: !P.NOERASE.

Specifies that the screen or page is not to be erased. By default, the screen is erased, or a new page is begun, before a plot is produced.

NORMAL

Accepted by: AXIS, CONTOUR, CURSOR, PLOT, PLOTS, POLYFILL, SHADE_SURF, SURFACE, TV, TVCRS, XYOUTS.

Set this keyword to indicate that the clipping and/or positioning coordinates are in the normalized coordinate system, and range from 0.0 to 1.0.

ORIENTATION

Accepted by: POLYFILL, XYOUTS.

Specifies the counterclockwise angle in degrees from horizontal of the text baseline and the lines used to fill polygons.When used with the POLYFILL procedure, this keyword forces the "linestyle" type of fill, rather than solid or patterned fill.

POSITION

Accepted by: CONTOUR, MAP_SET, PLOT, SHADE_SURF, SURFACE. System variable equivalent: !P.POSITION.

Allows direct specification of the plot window. POSITION is a 4-element vector giving, in order, the coordinates [(X0, Y0), (X1, Y1)], of the lower left and upper right corners of the data window. Coordinates are expressed in normalized units ranging from 0.0 to 1.0, unless the keyword /DEVICE is present, in which case they are in actual device units.

When setting the position of the window, be sure to allow space for the annotation, which resides outside the window. IDL outputs the message "% Warning: Plot truncated." if the plot region is larger than the screen or page size. The plot region is the rectangle enclosing the plot window and the annotation.

When plotting in three dimensions, the POSITION keyword is a 6-element vector with the first four elements describing, as above, the XY position, and with the last two elements giving the minimum and maximum Z coordinates. The Z specification is always in normalized coordinate units.

When making more than one plot per page it is more convenient to set !P.MULTI than to manipulate the position of the plot directly with the POSITION keyword.

Example

The following statement produces a contour plot with data plotted in only the upper left quarter of the screen:

CONTOUR, Z, POS=[0., 0.5, 0.5, 1.0]

Because no space on the left or top edges was allowed for the axes or their annotation, the above described warning message results.

PSYM

Accepted by: OPLOT, PLOT, PLOTS. System variable equivalent: !P.PSYM.

The symbol used to mark each data point. Normally, PSYM is 0, data points are connected by lines, and no symbols are drawn to mark the points. Set this keyword, or the system variable !P.PSYM, to the symbol index as shown in the table below to mark data points with symbols. The keyword SYMSIZE is used to set the size of the symbols.

PSYM Value	Plotting Symbol
1	Plus sign (+)
2	Asterisk (*)
3	Period (.)
4	Diamond
5	Triangle
6	Square
7	X
8	User-defined. See  USERSYM procedure.
9	Undefined
10	Histogram mode. Horizontal and vertical lines connect the plotted points, as opposed to the normal method of connecting points with straight lines.
Table 2.2 Values for the PSYM Keyword

Negative values of PSYM cause the symbol designated by PSYM to be plotted at each point with solid lines connecting the symbols. For example, a value of -5 plots triangles at each data point and connects the points with lines.

Example

The following IDL code plots an array using points, and then overplots the smoothed array, connecting the points with lines:

PLOT, A, PSYM=3 	Plot using points.

OPLOT, SMOOTH(A,7)	Overplot smoothed data.

[XYZ]RANGE

Accepted by: AXIS, CONTOUR, PLOT, SHADE_SURF, SURFACE. System variable equivalent: ![XYZ].RANGE.

The desired data range of the axis, a 2-element vector. The first element is the axis minimum, and the second is the maximum. IDL will frequently round this range. This override can be defeated using the [XYZ]STYLE keywords.

[XYZ]STYLE

Accepted by: AXIS, CONTOUR, PLOT, SHADE_SURF, SURFACE. System variable equivalent: ![XYZ].STYLE.

This keyword allows specification of axis options such as rounding of tick values and selection of a box axis. Each option is described in the table below.

Value	Description
1	Force exact axis range.
2	Extend axis range.
4	Suppress entire axis
8	Suppress box style axis (i.e., draw axis on only one side of plot)
16	Inhibit setting the Y axis minimum value to 0 (Y axis only)
Table 2.3 Values for the XSTYLE Keyword

Note that this keyword is set bitwise, so multiple effects can be set by adding values together. For example, to make an X axis that is both exact (value 1) and suppresses the box style (setting 8), set the XAXIS keyword to 1+8, or 9.

SUBTITLE

Accepted by: AXIS, CONTOUR, PLOT, SHADE_SURF, SURFACE. System variable equivalent: !P.SUBTITLE.

A text string to be used as a subtitle for the plot. Subtitles appear below the X axis.

SYMSIZE

Accepted by: OPLOT, PLOT, PLOTS.

Specifies the size of the symbols drawn when PSYM is set. The default size of 1.0 produces symbols approximately the same size as a character.

T3D

Accepted by: AXIS, CONTOUR, MAP_SET, OPLOT, PLOT, PLOTS, POLYFILL, SHADE_SURF, SURFACE, TV, TVCRS, XYOUTS. System variable equivalent: !P.T3D.

Set this keyword to indicate that the generalized transformation matrix in !P.T is to be used. If not present, the user-supplied coordinates are simply scaled to screen coordinates. See the examples in the description of the SAVE keyword.

Note: Since T3D uses the transformation matrix in !P.T, it is important that !P.T contain a valid transformation matrix. This can be achieved in several ways:

•	Use the SAVE keyword to save the transformation matrix from an earlier graphics operation.

•	Establish a transformation matrix using the T3D, SURFR, or, SCALE3 procedures.

•	Set the value of !P.T directly.

THICK

Accepted by:  AXIS, OPLOT, PLOT, PLOTS, POLYFILL, SHADE_SURF, SURFACE. System variable equivalent: !P.THICK.

Indicates the line thickness. THICK overrides the setting of !P.THICK.

[XYZ]THICK

Accepted by:  AXIS, CONTOUR, PLOT, SHADE_SURF, SURFACE. System variable equivalent: ![XYZ].THICK.

This keyword controls the thickness of the lines forming the axis and tick marks. A value of 1.0 is the default.

[XYZ]TICKFORMAT

Accepted by:  AXIS, CONTOUR, PLOT, SHADE_SURF, SURFACE. System variable equivalent: ![XYZ].TICKFORMAT.

Set this keyword to a format string or a string containing the name of a function that returns a string to be used to format the axis tick mark labels.

If the argument to the TICKFORMAT keyword does not begin with the an open parenthesis, "(", the string is interpreted as the name of a function. The function is called with three parameters: Axis, Index, and Value where:

•	Axis is the axis number: 0 for X axis, 1 for Y axis, 2 for Z axis.

•	Index is the tick mark index which starts at 0.

•	Value is the default tick mark value (a floating-point number).

Used with the LABEL_DATE function, this keyword can easily create axes with date labels. See "LABEL_DATE" on page 1-517.

Example: Using Format Strings for Tick Labels

For example, to display the X axis tick values using a format of F6.2 (six characters, with 2 places after the decimal point), use the XTICKFORMAT keyword as follows:

PLOT, X, Y, XTICKFORMAT='(F6.2)'

To display the Y tick values using the "dollars and cents" format $dddd.dd, use:

PLOT, X, Y, YTICKFORMAT='("$", F7.2)'

Example: Using a Function to Return Tick Labels

For more complicated tick label formatting, labels can be created by a user-specified function that returns a string. For example, to annotate ticks along a time axis with the format HH:MM:SS, you could use the following function:

FUNCTION YTICKS, axis, index, value

hour = long(value)/3600

minute = long(value-3600 * hour) / 60

sec = value mod 60

RETURN, STRING(hour, minute, sec, $

        FORMAT="(i2.2, ':', i2.2, ':', i2.2)")

END

Then use the call:

PLOT, T, YTICKFORMAT='YTICKS'

TICKLEN

Accepted by: AXIS, CONTOUR, PLOT, SHADE_SURF, SURFACE. System variable equivalent: !P.TICKLEN.

Controls the length of the axis tick marks, expressed as a fraction of the window size. The default value is 0.02. TICKLEN of 1.0 produces a grid, while a negative TICKLEN makes tick marks that extend outside the window, rather than inwards.

Example

To produce outward-going tick marks of the normal length:

PLOT, X, Y, TICKLEN = -0.02

To provide a new default tick length, set !P.TICKLEN.

[XYZ]TICKLEN

Accepted by: AXIS, CONTOUR, PLOT, SHADE_SURF, SURFACE. System variable equivalent: ![XYZ].TICKLEN.

This keyword controls the lengths of tick marks (expressed in normal coordinates) for the individual axes. This keyword, if nonzero, overrides the global tick length specified in !P.TICKLEN, and/or the TICKLEN keyword parameter, which is expressed in terms of the window size.

[XYZ]TICKNAME

Accepted by: AXIS, CONTOUR, PLOT, SHADE_SURF, SURFACE. System variable equivalent: ![XYZ].TICKNAME.

A string array of up to 30 elements that controls the annotation of each tick mark.

[XYZ]TICKS

Accepted by: AXIS, CONTOUR, PLOT, SHADE_SURF, SURFACE. System variable equivalent: ![XYZ].TICKS.

The number of major tick intervals to draw for the axis. If this keyword is omitted, IDL selects from three to six tick intervals. Setting this field to  n, where n > 1, produces exactly n tick intervals, and n +1 tick marks. Setting this field equal to 1 suppresses tick marks.

[XYZ]TICKV

Accepted by: AXIS, CONTOUR, PLOT, SHADE_SURF, SURFACE. System variable equivalent: ![XYZ].TICKV.

The data values for each tick mark, an array of up to 30 elements. Note: to specify the number of ticks and their values exactly, set [XYZ]TICKS = n and [XYZ]TICKV = n + 1, where n > 1.

[XYZ]TICK_GET

Accepted by: AXIS, CONTOUR, PLOT, SHADE_SURF, SURFACE.

A named variable in which to return the values of the tick marks for the designated axis. The result is a floating-point array with the same number of elements as ticks.

Example

To retrieve in the variable V the values of the tick marks selected by IDL for the Y axis:

PLOT, X, Y, YTICK_GET = V

TITLE

Accepted by: AXIS, CONTOUR, PLOT, SHADE_SURF, SURFACE. System variable equivalent: !P.TITLE.

Produces a main title centered above the plot window. The text size of this main title is larger than the other text by a factor of 1.25. For example:

PLOT, X, Y, TITLE = 'Final Results'

[XYZ]TITLE

Accepted by: AXIS, CONTOUR, PLOT, SHADE_SURF, SURFACE. System variable equivalent: ![XYZ].TITLE.

A string that contains a title for the specified axis.

ZVALUE

Accepted by: AXIS, CONTOUR, MAP_SET, OPLOT, PLOT, SHADE_SURF, SURFACE.

Sets the Z coordinate, in normalized coordinates in the range of 0 to 1, of the axis and data output from PLOT, OPLOT, and CONTOUR.

This keyword has effect only if !P.T3D is set and the three-dimensional to two- dimensional transformation is stored in !P.T. If ZVALUE is not specified, CONTOUR will output each contour at its Z coordinate, and the axes and title at a Z coordinate of 0.0.

Z

Accepted by: PLOTS, POLYFILL, TV, TVCRS, XYOUTS.

Provides the Z coordinate if a Z parameter is not present in the call. This is of use only if the three-dimensional transformation is in effect (i.e., the T3D keyword is not set).


Alphabetical List of Graphics Keywords (A-R)
Graphics Keywords A-R

BACKGROUND

CHANNEL

CHARSIZE

[XYZ]CHARSIZE

CHARTHICK

CLIP

COLOR

DATA

DEVICE

FONT

[XYZ]GRIDSTYLE

LINESTYLE

[XYZ]MARGIN

[XYZ]MINOR

NOCLIP

NODATA

NOERASE

NORMAL

ORIENTATION

POSITION

PSYM

[XYZ]RANGE


Alphabetical List of Graphics Keywords (S-Z)
Graphics Keywords S-Z

[XYZ]STYLE

SUBTITLE

SYMSIZE

T3D

THICK

[XYZ]THICK

[XYZ]TICKFORMAT

TICKLEN

[XYZ]TICKLEN

[XYZ]TICKNAME

[XYZ]TICKS

[XYZ]TICKV

[XYZ]TICK_GET

TITLE

[XYZ]TITLE

ZVALUE

Z


System Variables for Graphics

List of Graphics System Variables

Many of the functions of the graphics keywords described in "Graphics Keywords" on page 2-2 are also controlled by the system variables !P, !X, !Y, and !Z.

You can change the default style of plots, fonts, etc., by setting the corresponding field in the appropriate system variable. Also, some effects that persist longer than one call are controlled only by system variables. The field !P.MULTI is one example.

The system variables that control IDL graphics are described below.


!C System Variable

The cursor system variable. Currently, the only function of this system variable is to contain the subscript of the largest or smallest element found by the MAX and MIN functions. That information is better obtained through the optional output arguments to those routines. !C is included only for compatibility with old versions of IDL.


!D System Variable

This system variable is a structure that contains information about the current graphics output device. Fields, in alphabetical order, are:

FILL_DIST

The line interval, in device coordinates, required to obtain a solid fill.

FLAGS

A longword of flags that provide information about the current device. Each bit is a flag encoded as shown in Table 2.4, below.

Bit	Value	Function
0	1	Device has scalable pixel size (e.g., PostScript).
1	2	Device can output text at an arbitrary angle using hardware.
2	4	Device can control line thickness with hardware.
3	8	Device can display images.
4	16	Device supports color.
5	32	Device supports polygon filling with hardware.
6	64	Device hardware characters are monospace.
7	128	Device can read pixels (i.e., it supports TVRD).
8	256	Device supports windows.
9	512	Device prints black on a white background (e.g., printers are plotters).
10	1024	Device has no hardware characters.
11	2048	Device does line-fill style polygon filling in hardware.
12	4096	Device understands Hershey style formatting commands.
13	8192	Device is a pen plotter.
14	16384	Device can transfer 16-bit pixels.
15	32768	Device supports Kanji characters.
16	65536	Device supports widgets.
17	131072	Device has Z-buffer.
Table 2.4 !D.FLAGS Bit Definitions

N_COLORS

The number of simultaneously-available colors. In the case of devices with windows, this field is set after the window system is initialized. For a monochrome system, !D.N_COLORS is 2, and for color systems it is normally between 16 and 256.

NAME

A string containing the name of the device.

ORIGIN

A two-element integer array containing the current pan/scroll offset. An offset of (0, 0) is normal. Positive offsets shift the display memory to the right and upwards. This field has relevance only with devices with hardware pan and scroll abilities.

TABLE_SIZE

The number of color table indices. Devices without color tables have this field set to 0.

UNIT

The logical number of the file open for output by the current graphics device. This field only has meaning for devices that write to a file if the file is accessible to the user from IDL, and is 0 if no file is open.

For example, the PostScript driver fills this field with the unit number of the file open for PostScript output. In the case of Tektronix output to a file, !D.UNIT may be set to either + or - the logical unit number.

WINDOW

The index of the currently open window. This field is set to -1 if no window is currently open. This field is used only with devices that support windows.

X_CH_SIZE, Y_CH_SIZE

The normal width and height of a character in device units.

X_PX_CM, Y_PX_CM

The approximate number of pixels per centimeter in the X and Y directions.

X_SIZE, Y_SIZE

The total display size in the X and Y directions in device units.

X_VSIZE, Y_VSIZE

The size of the visible area of the display. This area can be smaller than the total size fields.

ZOOM

This field contains the current X and Y zoom factors for the display. This field has relevance only with devices equipped with hardware zoom. A zoom factor of [1, 1] is normal.


!ORDER System Variable

Controls the direction of image transfers when using the TV, TVSCL, and TVRD procedures. If !ORDER is 0, images are transferred from bottom to top, i.e. the row with a 0 subscript is written on the bottom. Setting !ORDER to 1, transfers images from top to bottom.


!P System Variable

The main plotting system variable structure. All fields, except !P.MULTI, have a directly corresponding keyword parameter in the plot procedures: PLOT, OPLOT, CONTOUR, and SURFACE. Fields, in alphabetical order, are:

BACKGROUND

The background color index. When erasing the screen or page, all pixels are set to this color. The default value is 0. Not all devices support this feature.

CHANNEL

The default source or destination channel. This field has meaning only on graphics devices that contain multiple display channels, and is device dependent. It may contain either a channel mask or index.

CHARSIZE

The overall character size of all annotation. 1.0 is normal size.

CHARTHICK

The thickness of the lines used to draw the characters when using the vector drawn fonts. This field has no effect on the appearance of characters drawn with the hardware fonts. Normal thickness is 1.0.

CLIP

The device coordinates of the clipping window, a 6-element vector of the form [(x0, y0, z0), (x1, y1, z1)], specifying two opposite corners of the volume to be displayed. In the case of two-dimensional displays, the Z coordinates can be omitted. Normally, this is set to the plot window.

COLOR

The default color index.

FONT

The index of the graphics text font. Font -1 is the Hershey vector drawn font, font 0 is the hardware-drawn font.

LINESTYLE

The default style of the lines used to connect points. A line style index of 0 yields a solid line. See Table 2.1, "IDL Linestyles," on page 6 of this chapter for a description of the linestyles.

MULTI

!P.MULTI allows making multiple plots on a page or screen. It is a 5-element integer array defined as follows:

!P.MULTI(0) contains the number of plots remaining on the page. If !P.MULTI(0) is less than or equal to 0, the page is cleared, the next plot is placed in the upper left hand corner, and !P.MULTI(0) is reset to the number of plots per page.

!P.MULTI(1) is the number of plot columns per page. If this value is less than or equal to 0, one is assumed. If more than two plots are ganged in either the X or Y direction, the character size is halved.

!P.MULTI(2) is the number of rows of plots per page. If this value is less than or equal to 0, one is assumed.

!P.MULTI(3) contains the number of plots stacked in the Z dimension.

!P.MULTI(4) is 0 to make plots from left to right (column major), and top to bottom, and is 1 to make plots from top to bottom, left to right (row major).

Example

To gang two plots across the page:

!P.MULTI = [0, 2, 0, 0, 0]

PLOT, X0, Y0 	Make left plot.

PLOT, X1, Y1 	Right plot.

To gang two plots vertically:

!P.MULTI = [0, 0, 2, 0, 0]

PLOT, X0, Y0 	Make top plot.

PLOT, X1, Y1 	Bottom plot.

To make four plots per page, two across and two up and down:

!P.MULTI = [0, 2, 2, 0, 0]

and then call plot four times.

To reset !P.MULTI back to the normal one plot per page:

!P.MULTI = 0

NOCLIP

A field, which if set, inhibits the clipping of the graphic vectors and vector-drawn text. By default, most routines, with the exception of PLOTS and XYOUTS, clip within the plotting window.

NOERASE

Set this field to a non-zero value to inhibit erasing the screen before plotting.

NSUM

The number of adjacent points to average to obtain a plotted point.

POSITION

Specifies the normalized coordinates of the rectangular plot window. This is a four element floating point vector x0, y0, x1, y1, where ( x0, y0) is the origin, and (x1, y1) is the upper right corner.

!P.POSITION determines the plotting window if x0 does not equal x1, and the POSITION keyword is not present. If set, it overrides the effect of the MARGIN and !P.MULTI variables and keywords.

PSYM

The default plotting symbol index. Each point drawn by PLOT, PLOTS, and OPLOT is marked with a symbol if this field is non-zero. The possible symbols are given in Table 2.2.

REGION

A four element vector that specifies the normalized coordinates of the rectangle enclosing the plot region, which includes the plot data window and its surrounding annotation area. It is in the same form as !P.POSITION, x0, y0, x1, y1, where (x0, y0) is the origin, and (x1, y1) is the upper right corner. It is ignored if !P.REGION(0) is equal to !P.REGION(2).

SUBTITLE

The plot subtitle, placed under the X axis label.

T

Contains the homogeneous 4 by 4 transformation matrix.

T3D

Enables the three-dimensional to two-dimensional transformation contained in the homogeneous 4 by 4 matrix !P.T. Note that if T3D is set, !P.T must contain a valid transformation matrix.

THICK

The thickness of the lines connecting points. 1.0 is normal.

TITLE

The main plot title.

TICKLEN

The length of the tick marks, expressed as a fraction of the plot size (from 0.0 to 1.0). The default is 0.02. A value of 0.5 makes a grid. Negative values make the tick marks point outward.


!X, !Y, !Z System Variables

The system variables !X, !Y, and !Z, are structures of type AXIS, that affect the appearance and scaling of the three axes. The fields for !X, !Y, and !Z have identical fields with identical meanings and usage. In addition, almost all fields have corresponding keyword parameters, with identical function, but with temporary effect. For example, to suppress the minor tick marks on the X axis using the !X system variable, you could use the command:

!X.MINOR = -1

To suppress the tick marks for just one call to plot, you could use the command:

PLOT, X, Y, XMINOR = -1

The name of the keyword parameter is simply the name of the system variable field, prefixed with the letter X, Y, or Z.

The fields for these system variables, in alphabetical order are:

CHARSIZE

The size of the characters used to annotate the axis and its title. This field is a scale factor applied to the global scale factor. For example, setting !P.CHARSIZE to 2.0, and !X.CHARSIZE to 0.5 results in a character size of 1.0 for the X axis.

CRANGE

The output axis range. Setting this variable has no effect; set !X.RANGE to change the range. !X.CRANGE(0) always contains the minimum axis value, and !X.CRANGE(1) contains the maximum axis value of the last plot before extending the axes.

GRIDSTYLE

The index of the linestyle to be used for tick marks and grids. See Table 2.1 for a list of linestyles.

MARGIN

A 2-element array specifying the margin on the left (bottom) and right (top) sides of the plot window, in units of character size. The plot window is the rectangular area that contains the plot data, i.e. the area enclosed by the axes.

The default values for !X.MARGIN are [10, 3] yielding a 10-character wide left margin and a 3-character wide right margin. The values for !Y.MARGIN are [4, 2], for a 4-character high bottom margin and a 2-character high top margin.

When calculating the size and position of the plot window, IDL first determines the plot region, the area enclosing the window plus the axis annotation and titles. It then subtracts the appropriate margin from each side, obtaining the window.

Setting !P.POSITION, or specification of the POSITION parameter overrides the effect of this field.

MINOR

The number of minor tick marks. If !X.MINOR is 0, the default, the number of minor ticks is automatically determined from the tick mark increment. You can force a given number of minor ticks by setting this field to the desired number. To suppress minor tick marks, set !X.MINOR to -1.

OMARGIN

A 2-element array specifying the "outer" margin on the left (bottom) and right (top) sides of a multi-plot window, in units of character size. A multi-plot window is created by setting the !P.MULTI system variable field. OMARGIN controls the amount of space around the entire plot area, including individual plot margins set with !X.MARGIN and !Y.MARGIN.

The default values for !X.OMARGIN and !Y.OMARGIN are [0, 0].

When calculating the size and position of the individual plots, IDL first determines the plot region, the area enclosing the window plus the axis annotation and titles. It then subtracts the appropriate margin from each side, obtaining the window.

Setting !P.POSITION, or specification of the POSITION parameter overrides the effect of this field.

RANGE

The input axis range, a 2-element vector. The first element is the axis minimum, and the second is the maximum. Set this field, or use the corresponding keyword parameter, to specify the data range to plot. If axis end point rounding is selected (see STYLE above), the final axis range may not be equal to this input range. The field !X.CRANGE contains the axis range used for the plot before extending the axes. Set both elements equal to 0 for automatic axis ranges:

!X.RANGE = 0

Example

To force the X axis to run from 5.5 to 8.3:

!X.RANGE = [5.5, 8.3]

PLOT, X, Y

Alternatively, by using keywords:

PLOT, X, Y, XRANGE=[5.5, 8.3]

Note that even though the range was set to (5.5, 8.3), the resulting plot has a range of (5.5, 8.5), because axis rounding is the default.

REGION

Contains the normalized coordinates of the region. This field is similar to WINDOW, in that it is set by the graphics procedures and is a 2-element floating point array. To change the default plotting region, set !P.REGION.

S

The scaling factors for converting between data coordinates and normalized coordinates (a 2-element array). The formula for conversion from data (Xd) to normalized (Xn) coordinates is Xn = S1Xd + S0

If logarithmic scaling is in effect, substitute log10(Xd) for Xd.

The CONVERT_COORD function can be used to convert between coordinate systems. The user should save and restore these fields when switching between windows or devices with different sizes and/or scaling.

STYLE

The style of the axis encoded as bits in a longword. The axis style can be set to exact, extended, none, or no box using this field. See Table 2.5 for details.

Bit	Value	Function
0	1	Exact. By default, the end points of the axis are rounded in order to obtain even tick increments. Setting this bit inhibits rounding, making the axis fit the data range exactly.
1	2	Extend. If this bit is set, the axes are extended by 5% in each direction, leaving a border around the data.
2	4	None. If this bit is set, the axis and its annotation are not drawn.
3	8	No box. Normally, PLOT and CONTOUR draw a box-style axis with the data window surrounded by axes.
4	16	Inhibits setting the Y axis minimum value to zero when the data are all greater than 0. The keyword YNOZERO sets this bit temporarily.
Table 2.5 Axis Style Bit Values

Note that this system variable field is set bitwise, so multiple effects can be set by adding values together. For example, to make an X axis that is both exact (value 1) and suppresses the box style (setting 8), set the !X.STYLE system variable to 1+8 , or 9.

Example

To set the Y axis style to exact using the !Y system variable:

!Y.STYLE = 1

or by using a keyword parameter:

PLOT, X, Y, YSTYLE = 1

THICK

The thickness of the axis line. 1.0 is normal.

TICKFORMAT

Set this field to a format string or a string containing the name of a function that returns a string to be used to format the axis tick mark labels.

See the [XYZ]TICKFORMAT keyword description on page 2-10 for more information.

TICKLEN

The lengths of tick marks (expressed in normal coordinates) for the individual axes.

TICKNAME

The annotation for each tick. A string array of up to 30 elements. Setting elements of this array allows direct specification of the tick label. If this element contains a null string, the default value, IDL annotates the thick with its numeric value. Setting the element to a 1-blank string suppresses the tick annotation.

Example

To produce a plot with an abscissa labeled with the days of the week:

!X.TICKNAME = ['SUN', 'MON', 'TUE', 'WED', $

               'THU', 'FRI', 'SAT']
Set up X axis tick labels.

!X.TICKS = 6	Use six tick intervals, requiring seven tick labels.

PLOT, Y	Plot the data, this assumes that Y contains 7 elements.

The same plot can be produced, using keyword parameters, with:

PLOT, Y, XTICKN = ['SUN', 'MON', 'TUE', 'WED',$

      'THU', 'FRI', 'SAT'], XTICKS = 6
Set fields, as above, only temporarily.

TICKS

The number of major tick intervals to draw for the axis. If !X.TICKS is set to 0, the default, IDL will select from three to six tick intervals. Setting this field to n, where n > 1, produces exactly n tick intervals, and n +1 tick marks. Setting this field equal to 1 suppresses tick marks.

TICKV

An array of up to 30 elements containing the data values for each tick mark. You can directly specify the location of each tick by setting !X.TICKS to the number of tick marks (the number of intervals plus 1) and storing the data values of the tick marks in !X.TICKV. If, as is true by default, !X.TICKV(0) is equal to !X.TICKV(1), IDL automatically determines the value of the tick marks.

TITLE

A string containing the axis title.

TYPE

The type of axis, 0 for linear, 1 for logarithmic.

WINDOW

Contains the normalized coordinates of the axis end points, the plot data window. This field is set by PLOT, CONTOUR, SHADE_SURF, and SURFACE. Changing its value has no effect. A 2-element floating point array. To change the default plotting window, set !P.POSITION. The keyword parameter POSITION sets the plot data window on a per call basis.


List of Graphics System Variables
Graphics System Variables

!C System Variable

!D System Variable

!ORDER System Variable

!P System Variable

!X, !Y, !Z System Variables


Table of IDL Devices
3	IDL Graphics Devices

IDL supports graphic output to the devices described in the table below. Each of these devices is described in a section of this chapter. The SET_PLOT procedure can be used to select the graphic device to which IDL directs its output. Click on a page number for more information on that device.

You can also go to a list of Keywords Accepted by the IDL Devices.

Device Name	Page	Description
CGM	31	Computer Graphics Metafile
HP	32	Hewlett-Packard Graphics Language (HP-GL)
LJ	33	Digital Equipment LJ250 (VMS Only)
MAC	36	Macintosh display
NULL	36	No graphics output
PCL	36	Hewlett-Packard Printer Control Language (PCL)
PS	37	PostScript
REGIS	52	Regis graphics protocol (DEC systems only)
TEK	53	Tektronix compatible terminal
WIN	54	Microsoft Windows
X	55	X Window System
Z	61	Z-buffer pseudo device
Table 3.1 IDL Graphics Output Devices

The DEVICE procedure controls the graphic device-specific functions. An attempt has been made to isolate all device-specific functions in this procedure.

DEVICE controls the graphics device currently selected by SET_PLOT. When using DEVICE, it is important to make sure that the current graphics device is the one you intend to use. This is because most of the devices have different keywords —you will most likely get a ``Keyword ... ... not allowed in call to: Device'' error if you call DEVICE when the wrong device is selected.


Table of DEVICE Keywords
Keywords Accepted by the IDL Devices

The following table indicates which keywords are accepted by the DEVICE procedure. Note that the NULL device is not listed as it accepts no keywords. Click on a keyword to see detailed information about that keyword. Click on a device name to go to detailed information about that device.

AVANTGARDE (PS)

AVERAGE_LINES (REGIS)

BINARY (CGM)

BITS_PER_PIXEL (PS)

BKMAN (PS)

BOLD (PS)

BOOK (PS)

BYPASS_TRANSLATION (MAC, WIN, X)

CLOSE (Z)

CLOSE_FILE (CGM, HP, LJ, PCL, PS, REGIS, TEK)

COLOR (PCL, PS)

COLORS (CGM, TEK)

COMMAND_INPUT_ANCHOR (WIN)

COMMAND_INPUT_VISIBLE (WIN)

COPY (MAC, WIN, X)

COURIER (PS)

CURSOR_CROSSHAIR (WIN, X)

CURSOR_IMAGE (X)

CURSOR_MASK (X)

CURSOR_ORIGINAL (MAC, WIN, X)

CURSOR_STANDARD (MAC, WIN, X)

CURSOR_XY (X)

DECOMPOSED (MAC, WIN, X)

DEMI (PS)

DEPTH (LJ)

DIRECT_COLOR (X)

EJECT (HP)

ENCAPSULATED (PS)

ENCODING (CGM)

FILENAME (CGM, HP, LJ, PCL, PS, REGIS, TEK)

FLOYD (LJ, MAC, PCL, X)

FONT (MAC, WIN, X)

FONT_INDEX (PS)

FONT_SIZE (PS)

GET_CURRENT_FONT (MAC, WIN, X)

GET_FONTNAMES (MAC, WIN, X)

GET_FONTNUM (MAC, WIN, X)

GET_GRAPHICS_FUNCTION (MAC, WIN, X, Z)

GET_SCREEN_SIZE (MAC, WIN, X)

GET_WINDOW_POSITION (MAC, WIN, X)

GET_WRITE_MASK (X, Z)

GIN_CHARS (TEK)

HELVETICA (PS)

INCHES (HP, LJ, PCL, PS)

ISOLATIN1 (PS)

ITALIC (PS)

LANDSCAPE (HP, LJ, PCL, PS)

LIGHT (PS)

MAIN_WINDOW_SIZE (WIN)

MEDIUM (PS)

NARROW (PS)

NCAR (CGM)

OBLIQUE (PS)

OPEN_EDIT_WINDOW (WIN)

OPTIMIZE (PCL)

ORDERED (LJ, MAC, PCL, X)

OUTPUT (HP, PS)

PALATINO (PS)

PIXELS (LJ, PCL)

PLOT_TO (REGIS, TEK)

PLOTTER_ON_OFF (HP)

POLYFILL (HP)

PORTRAIT (HP, LJ, PCL, PS)

PREVIEW (PS)

PRINT_FILE (WIN)

PSEUDO_COLOR (MAC, X)

RESET_STRING (TEK)

RESOLUTION (LJ, PCL)

RETAIN (MAC, WIN, X)

SCALE_FACTOR (PS)

SCHOOLBOOK (PS)

SET_CHARACTER_SIZE (CGM, HP, LJ, MAC, PCL, PS, REGIS, TEK, WIN, X, Z)

SET_COLORMAP (PCL)

SET_COLORS (Z)

SET_GRAPHICS_FUNCTION (MAC, WIN, X, Z)

SET_RESOLUTION (Z)

SET_STRING (TEK)

SET_TRANSLATION (X)

SET_WRITE_MASK (X, Z)

STATIC_COLOR (X)

STATIC_GRAY (X)

SYMBOL (PS)

TEK4014 (TEK)

TEK4100 (TEK)

TEXT (CGM)

THRESHOLD (LJ, MAC, PCL, X)

TIMES (PS)

TRANSLATION (MAC, WIN, X)

TRUE_COLOR (MAC, X)

TTY (REGIS, TEK)

USER_FONT (PS)

VT240, VT241 (REGIS)

VT340, VT341 (REGIS)

WINDOW_STATE (WIN, X)

XOFFSET (HP, LJ, PCL, PS)

XON_XOFF (HP)

XSIZE (HP, LJ, PCL, PS)

YOFFSET (HP, LJ, PCL, PS)

YSIZE (HP, LJ, PCL, PS)

ZAPFCHANCERY (PS)

ZAPFDINGBATS (PS)

Z_BUFFERING (Z)


Keywords to DEVICE - A through C
Keywords for the DEVICE Procedure—A through C

Keywords accepted by the DEVICE command are described below.

AVANTGARDE

Set this keyword to select the ITC Avant Garde PostScript font.

AVERAGE_LINES

Controls the method of writing images to the VT240. If this keyword is set, (default setting), even and odd pairs of image lines are averaged and written to a single line. If clear, each image line is written to the screen. See the discussion below. This keyword has no effect when using a VT300 series terminal.

BINARY

Set this keyword to set the encoding type for the CGM output file to binary.

BITS_PER_PIXEL

IDL is capable of producing PostScript images with 1, 2, 4, or 8 bits per pixel. Using more bits per pixel gives higher resolution at the cost of generating larger files. BITS_PER_PIXEL is used to specify the number of bits to use. If you do not specify a value of 1, 2, 4, or 8, IDL selects the closest one.

It should be noted that many laser printers, including the original Apple Laserwriter are capable of only 32 different shades of gray (which can be represented by 5 bits). Thus, specifying 8 bits per pixel does not give 256 apparent shades of grey as might be expected, only 32, at a cost of sending twice the number of bits to the printer. Often, 4 bits (16 levels of gray) will give acceptable results with a large savings in file size.

BKMAN

Set this keyword to select the ITC Bookman PostScript font.

BOLD

Set this keyword to specify that the bold version of the current PostScript font should be used.

BOOK

Set this keyword to specify that the book version of the current PostScript font should be used.

BYPASS_TRANSLATION

Set this keyword to bypass the translation tables, allowing direct specification of color indices. See "Color Translation" on page 3-58. Pixel values read via the TVRD function are not translated if this keyword is set, and the result contains the byte value of the actual pixel values present in the display.

By default, the translation tables are used with shared and static color tables. When using displays with private color tables, the translation tables are bypassed.

This keyword is accepted by the WIN device (for compatibility with the X device), but has no effect when set.

CLOSE

Set this keyword to deallocate the memory used by the Z-buffer. The Z-buffer device is reinitialized if subsequent graphics operations are directed to the device.

CLOSE_FILE

Set this keyword to have IDL output any buffered commands and close the current graphics file.

Caution: Under operating systems other than VMS, if you close the output file and then cause IDL to produce more output (e.g., by executing a new PLOT command), IDL will open the file again, causing the contents of the recently closed file to be lost. To avoid this, use the FILENAME keyword to specify a different file name or use SET_PLOT to disable the graphics driver, or be sure to print the closed output file before creating more output.

See the discussion of printing output files in "Printing Graphics Output Files" on page 3-28.

COLOR

Set this keyword to enable color PCL or PostScript output. See "The PCL Device" on page 3-36 or "The PostScript Device" on page 3-37.

COLORS

This keyword specifies the maximum number of colors and the size of the color table used for output. The value of the system variable fields !D.N_COLORS and !D.TABLE_SIZE are set to this value and !P.COLOR is set to one less than this value.

For Tektronix Terminals Only

This keyword sets the number of colors supported by a 4100 series terminal. For example, if your terminal has 4-bit planes, the number of colors is 24 = 16:

DEVICE, COLORS = 16

Valid values of this parameter are: 2, 4, 8, 16, or 64; other values will cause problems. Some Tektronix terminals will not operate properly if this parameter does not exactly match the number of colors available in the terminal hardware.

This parameter sets the field !D.N_COLORS, which affects the loading of color tables, the scaling used by the TVSCL procedure, and the number of bits output by the TV procedure to the terminal. It also changes the default color, !P.COLOR to the number of colors minus one.

COMMAND_INPUT_ANCHOR

Set this keyword to 0 to un-anchor (tear off) the IDL for Windows command input window. Set this keyword to 1 to anchor the command input window.

COMMAND_INPUT_VISIBLE

Set this keyword to 1 to show the IDL for Windows command input window. Set this keyword to 0 to hide the command input window.

COPY

Use this keyword to copy a rectangular area of pixels from one region of a window to another. COPY should be set a six or seven element array: [Xs, Ys, Nx, Ny, Xd, Yd, W], where: (Xs, Ys) is the lower left corner of the source rectangle, (Nx, Ny) are the number of columns and rows in the rectangle, and (Xd, Yd) is the coordinate of the destination rectangle. Optionally, W is the index of the window from which the pixels should be copied to the current window. If it is not supplied, the current window is used as both the source and destination.

COURIER

Set this keyword to select the Courier PostScript font.

CURSOR_CROSSHAIR

Set this keyword to selects the crosshair cursor type. This is the IDL default.

CURSOR_IMAGE

Specifies the cursor pattern. The value of this keyword must be a 16-line by 16-column bitmap, contained in a 16-element short integer vector. The offset from the upper left pixel to the point that is considered the "hot spot" can be provided via the CURSOR_XY keyword.

CURSOR_MASK

When the CURSOR_IMAGE keyword is used to specify a cursor bitmap, the CURSOR_MASK keyword can be used to simultaneously specify the mask that should be used. In the mask, bits that are set indicate bits in the CURSOR_IMAGE that should be seen and bits that are not set are "masked out".

By default, the CURSOR_IMAGE bitmap is used for both the image and the mask. This can cause the cursor to be invisible on a black background (because only black pixels are allowed to be displayed).

CURSOR_ORIGINAL

Set this keyword to select the window system's default cursor. Under X Windows, it is the cursor in use by the root window when IDL starts. For the Macintosh and Microsoft Windows devices, it is the arrow pointer.

CURSOR_STANDARD

This keyword can be used to change the appearance of the cursor in IDL graphics windows.

For X Windows

This keyword selects one of the predefined cursors provided by the X Window system. The available cursors shapes are defined in the file cursorfonts.h  in the directory /usr/include/X11 (Unix), or DECW$INCLUDE: (VMS). In order to use one of these cursors, you select the number of the cursor and provide it as the value of the CURSOR_STANDARD keyword. For example, the file gives the value of XC_CROSS as being 30. In order to make that the current cursor, use the statement:

DEVICE, CURSOR_STANDARD=30

For Microsoft Windows

The table below shows the values for CURSOR_STANDARD that result in different cursor shapes. For example, to change the cursor to an "I-beam" when the cursor is in an IDL graphics window, use the command:

DEVICE, CURSOR_STANDARD = 32513

Cursor Shape	Value
Arrow	32512
I-Beam	32513
Hourglass	32514
Black Crosshair	32515
Up Arrow	32516
Size	32640
Icon	32641
Size NW-SE	32642
Size NE-SW	32643
Size E-W	32644
Size N-S	32645
Table 3.2 Values for the WIN device CURSOR_STANDARD keyword

For Macintosh

Setting the CURSOR_STANDARD keyword changes the cursor to a crosshair in IDL graphics windows.

CURSOR_XY

A two element integer vector giving the (X, Y) pixel offset of the cursor "hot spot", the point which is considered to be the mouse position, from the upper left corner of the cursor image. This parameter is only applicable if CURSOR_IMAGE is provided. The cursor image is displayed top-down—the first row is displayed at the top.


Keywords to DEVICE - D through F
Keywords for the DEVICE Procedure—D through F

DECOMPOSED

This keyword is used to control the way in which graphics color index values are interpreted when using displays with decomposed color (TrueColor or DirectColor visuals). This keyword has no effect with other types of visuals.

Set this keyword to 1 to cause color indices to be interpreted as 3, 8-bit color indices where the least-significant 8 bits contain the red value, the next 8 bits contain the green value, and the most-significant 8 bits contain the blue value. This is the way IDL has always interpreted pixels when using visual classes with decomposed color.

Set this keyword to 0 to cause the least-significant 8 bits of the color index value to be interpreted as a PseudoColor index. This setting allows users with DirectColor and TrueColor displays to use IDL programs written for standard, PseudoColor displays without modification.

In older versions of IDL, color index values higher than !D.N_COLORS-1 were clipped to !D.N_COLORS-1 in the higher level graphics routines. In some cases, this clipping caused the exclusive-OR graphics mode to malfunction with raster displays. This clipping has been removed. Programs that incorrectly specified color indices higher than !D.N_COLORS-1 will now probably exhibit different behavior.

DEMI

Set this keyword to specify that the demi version of the current PostScript font should be used.

DEPTH

The DEPTH keyword specifies the number of significant bits in a pixel. The LJ250 can support between 1 and 4 significant bits (known also as planes). The number of available colors is related to the number of significant planes by the equation:

Colors = 2#planes

Therefore, the LJ250 can support 2, 4, 8, or 16 separate colors on a single page of output. The default is to use a single plane, producing monochrome output.

Since IDL is based around 8-bit pixels, it is necessary to define which bits in a 8-bit pixel are used by the LJ250 driver, and which are ignored. When using a depth of 1 (monochrome), dithering techniques are used to render images. In this case, all 8 bits are used. If more than a single plane is used, the least significant n bits of a 8-bit pixel are used, where n is the selected depth. For example, using a depth of 4, pixel values of 15, 31, and 47 are all considered to have the value 15 because all three values have the same binary representation in their 4 least significant digits.

When the depth is changed, the standard color map given in Table 7-5 of the LJ250/LJ252 Companion Color Printer Programmer Reference Manual is automatically loaded. Therefore, color maps should be loaded with TVLCT after changing the depth.

DIRECT_COLOR

Set this keyword to select the DirectColor visual. The value of the keyword represents the number of bits per pixel. This keyword has effect only if no windows have been created. Visual classes are discussed in more detail in "X Windows Visuals" on page 3-55.

EJECT

In order to perform an erase operation on a plotter, it is necessary to remove the current sheet of paper and load a fresh sheet. The ability of various plotters to do this varies, so the EJECT keyword allows you to specify what should be done. The table below describes the possible values.

Value	Meaning
0	Do nothing. Note that this is likely to cause one page to plot over the previous one, so you should limit yourself to one page of output per file. This is the default.
1	Use the sheet feeder to load the next page.
2	Put the plotter off-line at the beginning of each page after the first.
Table 3.3 Values for the HP-GL Eject Keyword

Many HP-GL plotters lack a sheet feeder, and require the user to load the next page manually. Therefore, the default action is for IDL to not issue any page eject instructions. In this case, you must restrict yourself to generating only a single plot at a time. If your plotter has a sheet feeder, you will want to issue the command:

DEVICE, /EJECT

to tell IDL that it should use the sheet feeder instead of placing the plotter off-line.

If your plotter does not have a sheet feeder, but it does understand the HP-GL NR command, use the command:

DEVICE, EJECT=2

to place the plotter off-line at the start of every plot except the first one. This causes the plotter to wait between plots for the user to replace the paper. When the user puts the plotter back on-line, the graphics commands for the new page are executed by the plotter. Consult the programming manual for your plotter to determine if this instruction is provided.

ENCAPSULATED

Set this keyword to create an encapsulated PostScript file, suitable for importing into another document (e.g., a LaTeX or FrameMaker document).

Normally, IDL assumes that its PostScript-generated output will be sent directly to a printer. It therefore includes PostScript commands to position the plot on the page and to eject the page from the printer. These commands are undesirable if the output is going to be inserted into the middle of another PostScript document. If ENCAPSULATED is present and non-zero, IDL does not generate these commands.

IDL follows the standard PostScript convention for encapsulated files. It assumes the standard PostScript scaling is in effect (72 points per inch), In addition, it declares the size, or bounding box of the plotting region at the top of the output file. This size is determined when the output file is opened (when the first graphics command is given), by multiplying the size of the plotting region (as specified with the XSIZE and YSIZE keywords) by the current scale factor (as specified by the SCALE_FACTOR keyword).

Changing the size of the plotting region or scale factor once graphics have been output will not be reflected in the declared bounding box, and will confuse programs that attempt to import the resulting graphics. Therefore, when generating encapsulated PostScript, do not change the plot region size or scaling factor once any graphics commands have been issued. If you need to change these parameters, use the FILENAME keyword to start a new file.

ENCODING

Set this keyword to set the CGM encoding type for the output file. Valid values are: 1 (binary encoding, the default), 2 (text encoding), and 3 (NCAR binary encoding). The encoding type can only be changed when there is no CGM file open.

FILENAME

Normally, all generated output is sent to a file named idl.xxx where xxx is the lowercase name of the device shown in Table 3.1. The FILENAME keyword can be used to change these defaults. If FILENAME is specified:

1. If the file is already open (as happens if plotting commands have been directed to the file since the call to SET_PLOT), then the file is completed and closed as if CLOSE_FILE had been specified.

2. The specified file is opened for subsequent graphics output.

HP-GL Only

Under Unix, if you wish to send HP-GL output directly to a plotter without generating an intermediate file, you should specify the device special file for the plotter as the argument to FILENAME. For example, if your plotter is connected to a serial input/output port known on your system as /dev/ttya, you would issue the command:

DEVICE, FILENAME='/dev/ttya'

All subsequent HP-GL output is sent directly to the plotter connected to serial port /dev/ttya.

FLOYD

Set this keyword to select the Floyd-Steinberg method of dithering. This algorithm distributes the error, due to displaying intermediate shades in either black or white, to surrounding pixels. This method generally gives the most pleasing results but requires the most computer time.

FONT

Set this keyword to a scalar string specifying the name of the font used when the hardware font is selected. Note that hardware fonts cannot be rotated, scaled, or projected, and that the "!" commands accepted for vector fonts for subscripts and superscripts may not work. When generating three-dimensional plots, it is best to use the vector-drawn characters because IDL can draw them in perspective with the rest of the plot.

The GET_FONTNAMES keyword, described below, can be used to retrieve a list of available fonts.

X Windows Only

Usually, the window system provides a directory of font files that can be used by all applications. List the contents of that directory to find the fonts available on your system. The size of the font selected also affects the size of vector drawn text. X Windows users can use the xlsfonts command to list available X Windows fonts.

On some machines, fonts are kept in subdirectories of /usr/lib/X11/fonts.

For example, to select the font 8X13:

DEVICE, FONT = '8X13'

Unix X Window System users can use the xlsfonts Unix command to see a list of fonts supported by their systems or the GET_FONTNAMES keyword described below.

Microsoft Windows Only

The FONT keyword should be set to a string with the following form:

DEVICE, FONT="font*modifier1*modifier2*...modifiern"

where the asterisk (*) acts as a delimiter between the font's name (font ) and any modifiers. The string is not case sensitive. Modifiers are simply "keywords" that change aspects of the selected font. Valid modifiers are:

•	For font weight: THIN, LIGHT, BOLD, HEAVY

•	For font quality: DRAFT, PROOF

•	For font pitch: FIXED, VARIABLE

•	For font angle: ITALIC

•	For strikeout text: STRIKEOUT

•	For underlined text: UNDERLINE

•	For font size: Any number is interpreted as the font height in pixels.

For example, if you have Garamond installed as one of your Windows fonts, you could select 24-pixel cell height Garamond italic as the font to use in plotting. The following commands tell IDL to use hardware fonts, change the font, and then make a simple plot:

IDL> !P.FONT = 0

IDL> DEVICE, FONT = "GARAMOND*ITALIC*24"

IDL> PLOT, FINDGEN(10), TITLE = "IDL Plot"

This feature is compatible with TrueType and Adobe Type Manager (and, possibly, other type scaling programs for Windows). If you have TrueType or ATM installed, the TrueType or PostScript outline fonts are used so that text looks good at any size.

Seeing the Installed Windows Fonts

To see a list of fonts that you have installed under Microsoft Windows, open the "Control Panel" icon, located in the "Main" program group. The control panel menu appears. Double click on the "Fonts" icon to see a scrolling list of installed windows fonts.

Note that if you have a type scaling program such as Adobe Type Manager installed, there my be fonts installed that do not show up under the Windows control panel. For example, Adobe Type Manger has its own control panel icon that, when opened, displays a scrolling list of installed PostScript outline fonts.

Macintosh Only

The FONT keyword should be set to a string with the following form:

DEVICE, FONT="font*modifier1*modifier2*...modifiern"

where the asterisk (*) acts as a delimiter between the font's name (font ) and any modifiers. The string is not case sensitive. Modifiers are simply "keywords" that change aspects of the selected font. Valid modifiers are:

•	For font weight: BOLD

•	For font angle: ITALIC

•	For font width: CONDENSED, EXTENDED

•	For outlined text: OUTLINE, SHADOW

•	For underlined text: UNDERLINE

•	For font size: Any number is interpreted as the font size, in points.

For example, if you have Garamond installed, you could select 24-point Garamond italic as the font to use in plotting. The following commands tell IDL to use hardware fonts, change the font, and then make a simple plot:

IDL> !P.FONT = 0

IDL> DEVICE, FONT = "GARAMOND*ITALIC*24"

IDL> PLOT, FINDGEN(10), TITLE = "IDL Plot"

FONT_INDEX

An integer representing the font index to be mapped to the current PostScript font.

Normally the font specification keywords (AVANTGARDE, etc.) take effect immediately to change the current font. The FONT_INDEX keyword alters this behavior. The current font is not changed. Instead, the specified font is mapped to the specified font index. This mapping can then be used within text strings to change the font in the middle of the string. See "Using PostScript Fonts" on page 3-38.

FONT_SIZE

The default height used for displayed text. FONT_SIZE is given in points (a common typesetting unit of measure). The default size is 12 point text.


Keywords to DEVICE - G through I
Keywords for the DEVICE Procedure—G through I

GET_CURRENT_FONT

Set this keyword to a named variable in which the name of the current font is returned as a scalar string. A null string is returned if the Windows font is the default font.

GET_FONTNAMES

Set this keyword to a named variable in which a string array containing the names of available fonts is returned. If no fonts are found, a null scalar string is returned. This keyword must be used in conjunction with the FONT keyword. Set the FONT keyword to a scalar string containing the name of the desired font or a wildcard.

GET_FONTNUM

Set this keyword to a named variable in which the number of fonts available to your installation is returned. This keyword must be used in conjunction with the FONT keyword. Set the FONT keyword to a scalar string containing the name of the desired font or a wildcard.

GET_GRAPHICS_FUNCTION

Set this keyword to a named variable that returns the value of the current graphics function (which is set with the SET_GRAPHICS_FUNCTION keyword). This can be used to remember the current graphics function, change it temporarily, and then restore it. See the SET_GRAPHICS_FUNCTION keyword for an example.

GET_SCREEN_SIZE

Set this keyword to a named variable in which to return a two-word array that contains the width and height of the server's screen, in pixels.

GET_WINDOW_POSITION

Set this keyword to a named variable that returns a two-element array containing the (X,Y) position of the lower left corner of the current window on the screen. The origin is also in the lower left corner of the screen.

GET_WRITE_MASK

Specifies the name of a variable to receive the current value of the write mask.

GIN_CHARS

The number of characters IDL is to read when accepting a GIN (Graphics INput) report. The default is 5. If your terminal is configured to send a carriage return at the end of each GIN report, set this parameter to 6. If the number of GIN characters is too large, the IDL CURSOR procedure will not respond until two or more keys are struck. If it is too small, the extra characters sent by the terminal will appear as input to the next IDL prompt.

HELVETICA

Set this keyword to select the Helvetica PostScript font.

INCHES

Normally, the XOFFSET, XSIZE, YOFFSET, and YSIZE keywords are specified in centimeters. However, if INCHES is present and non-zero, they are taken to be in inches instead.

ISOLATIN1

Set this keyword to use Adobe ISO Latin 1 font encoding with any font that supports such coding. Use of this keyword allows access to many commonly-used foreign characters.

ITALIC

Set this keyword to specify that the italic version of the current PostScript font should be used.


Keywords to DEVICE - J through M
Keywords for the DEVICE Procedure—J through M

LANDSCAPE

IDL normally generates plots with portrait orientation (the abscissa is along the short dimension of the page). If the LANDSCAPE keyword is set, landscape orientation (abscissa along the long dimension of the page) is used instead. Note that explicitly setting LANDSCAPE=0 is the same as setting the PORTRAIT keyword.

LIGHT

Set this keyword to specify that the light version of the current PostScript font should be used.

MAIN_WINDOW_SIZE

This keyword can be used to resize the IDL for Windows main window. To iconize the main window, set this keyword to 0. To maximize the window, set this keyword to 2. To restore the main IDL window to its original size, set this keyword to 1.

MEDIUM

Set this keyword to specify that the medium version of the current PostScript font should be used.


Keywords to DEVICE - N through P
Keywords for the DEVICE Procedure—N through P

NARROW

Set this keyword to specify that the narrow version of the current PostScript font should be used.

NCAR

Set this keyword to set the encoding type for the CGM output file to NCAR binary.

The NCAR Binary Encoding

The NCAR binary encoding is used exclusively by the NCAR graphics package. Version 3.01 of NCAR View (ctrans, ictrans, and cgm2ncgm) does not correctly handle the following graphic elements:

•	Cell arrays (raster images) with an odd number of pixels in the X dimension. Solution: specify an even number of pixels for the X dimension or make the image one column wider and fill with zeros.

•	Raster images drawn in top down order. Solution: invert the image prior to using TV or TVSCL and do not use the /ORDER keyword. For example:

TV, image	Draw image bottom to top.

TV, ROTATE(image, 7)	Draw image top to bottom.

OBLIQUE

Set this keyword to specify that the oblique version of the current PostScript font should be used.

OPEN_EDIT_WINDOW

Set this keyword to open a new IDL for Windows edit window (as if File-New Edit Window had been selected from the menu bar). If set to a value other than 1, the "open" common dialog box is presented (as if File-Open File had been selected from the menu bar). This dialog can be used to select a program file for editing.

OPTIMIZE

It is desirable, though not always possible, to compress the size of the PCL output file. Such optimization reduces the size of the output file, and improves I/O speed to the printer. There are three levels of optimization:

•	0. No optimization is performed. This is the default because it will work with any PCL device. However, users of devices which can support optimization should use one of the other optimization levels.

•	1. Optimization is performed using PCL optimization primitives. This gives the best output compression and printing speed. Unfortunately, not all PCL devices support it. On those that can't, the result will be garbage printed on the page.

Consult the programmers manual for your printer to determine it supports the required escape sequences. The required sequences are: <ESC>*b0M (select full graphics mode), <ESC>*b1M (select compacted graphics mode 1), and <ESC>*b2M (select compacted graphics mode 2). The HP LaserJet II does not support this optimization level. The DeskJet PLUS does.

•	2. IDL attempts to optimize the output by explicitly moving the left margin and then outputting non-blank sections of the page. This is primarily intended for use with the LaserJet II, which does not support optimization level 1. Note: This optimization can be very slow on some devices (such as the DeskJet PLUS). On such devices, it is best to avoid this optimization level.

ORDERED

Set this keyword to select the ordered dither method. This introduces a pseudo-random error into the display by using a 4 by 4 "dither" matrix, yielding 16 apparent intensities. This is the default method.

Macintosh Only

This keyword is identical to the THRESHOLD keyword.

OUTPUT

Specifies a scalar string that is sent directly to the graphics output file without any processing, allowing the user to send arbitrary commands to the file. Since IDL does not examine the string, it is the user's responsibility to ensure that the string is correct for the target device.

PALATINO

Set this keyword to select the Palatino PostScript font.

PIXELS

Normally, the XOFFSET, XSIZE, YOFFSET, and YSIZE keywords are specified in centimeters. However, if the PIXELS keyword is set, they are taken to be in pixels instead. Note that the selected resolution will determine how large a region is actually written on the page.

PLOTTER_ON_OFF

There are some configurations in which a HP-GL plotter is connected between the computer and a terminal. In this mode (known as eavesdrop mode), the plotter ignores everything it is sent and passes it through to the terminal—the plotter is logically off. This state continues until an escape sequence is sent that turns the plotter logically on. At this point the plotter interprets and executes all input as HP-GL commands. Another escape sequence is sent at the end of the HP-GL commands to return the plotter to the logically off state.

Most configurations do not use eavesdrop mode, and the plotter is always logically on. However, if you are using this style of connection, you must use PLOTTER_ON_OFF to instruct IDL to generate the necessary on/off commands. If present and non-zero, PLOTTER_ON_OFF causes each output page to be bracketed by device control commands that turn the plotter logically on and off. Specifying a value of zero stops the issuing of such commands. You should only use this keyword before any output has been generated.

PLOT_TO

Directs the Tektronix graphic output that would normally go to the user's terminal to the specified I/O unit. The logical unit specified should be open with write access to a device or file. Graphic output may be saved in files for later playback, redirected to other terminals, or to devices that can accept Textronix graphic commands.

Do not use the interactive graphics cursor when graphic output is not directed to your terminal.

To direct the graphic data to both the terminal and the file, set the unit to the negative of the actual unit number. Alternatively, you can use the TTY keyword, described below.

If the specified unit number is zero then Tektronix output to the file is stopped.

POLYFILL

Some plotters (e.g., HP7550A) can perform polygon filling in hardware, while others (e.g., HP7475) cannot. IDL therefore assumes that the plotter cannot, and generates all polygon operations in software using line drawing. Specifying a non-zero value for the POLYFILL keyword causes IDL to use the hardware polygon filling. Setting it to zero reverts to software filling.

Different implementations of HP-GL plotters may have different limits for the number of vertices that can be specified for a polygon region before the plotter runs out of internal memory. Since this limit can vary, the HP-GL driver cannot check for calls to POLYFILL that specify too many points. Therefore, it is possible for the user to produce HP-GL output that causes an error when sent to the plotter. To avoid this situation, minimize the number of points used. On the HP7550A, the limit is about 127 points. If you do generate output that exceeds the limit imposed by your plotter, you will have to break that polygon filling operation into multiple smaller operations.

PORTRAIT

Set the PORTRAIT keyword to generate plots using portrait orientation. Portrait orientation is the default. Note that explicitly setting PORTRAIT=0 is the same as setting the LANDSCAPE keyword.

PREVIEW

Set this keyword to add a "device independent screen preview" to the PostScript output file, in encapsulated PostScript interchange format (EPSI). Use this keyword only with encapsulated output. Many, but certainly not all, desktop publishing and word processing programs will display this screen preview when the file is imported into a document. The preview is only a crude approximation and does not include all elements of the final PostScript output. This feature is not available under VMS.

PRINT_FILE

Set this keyword to the name of a file (e.g., PostScript or PCL) to be sent to the currently-selected Windows printer. IDL performs no type checking on this file before sending it to the printer. Therefore, if you have a PostScript printer selected and you send a file that contains no valid PostScript information, you'll simply get text output.

To send the file MYFILE.PS to the currently-selected Windows printer, enter:

DEVICE, PRINT_FILE='MYFILE.PS'

PSEUDO_COLOR

If this keyword is present, the PseudoColor visual is used. The value of the keyword represents the number of bits per pixel to be used. This keyword has effect only if no windows have been created. Visual classes are discussed in more detail in "X Windows Visuals" on page 3-55.

Macintosh Only

Setting this keyword causes all screen manipulations to be done in 8-bit mode. The value of the keyword is ignored, as is the current bit-depth of the monitor.


Keywords to DEVICE - R through T
Keywords for the DEVICE Procedure—R through T

RESET_STRING

The string used to place the terminal back into the normal interactive mode after drawing graphics. Use this parameter, in conjunction with the SET_STRING keyword, to control the mode switching of your terminal.

For example, the GraphON 200 series terminals require the string <ESC>2 to activate the alphanumeric window after drawing graphics. The call to set this is:

DEVICE, RESET = string(27b) + '2'

If the 4100 series mode switch is set, using the keyword TEK4100, the default mode resetting string is <ESC>%!1, which selects the ANSI code mode.

RESOLUTION

PCL Only

The resolution at which the PCL printer will work. PCL supports resolutions of 75, 100, 150, and 300 dots per inch. The default is 300 dpi. Lower resolution gives smaller output files, while higher resolution gives superior quality.

LJ250 Only

The resolution at which the LJ printer will work. LJ supports resolutions of 90 and 180 dots per inch. The default is 180 dpi. Lower resolution gives smaller output files and a larger selection of colors, while higher resolution gives superior quality.

RETAIN

Use this keyword to specify the default method used for backing store when creating new windows. This is the method used when the RETAIN keyword is not specified with the WINDOW procedure. Backing store is discussed in more detail under "Backing Store" on page 3-27. The possible values for this keyword are summarized in Table 3.5. If RETAIN is not used to specify the default method, method 1 (server-supplied backing store) is used.

Microsoft Windows Only

The initial value of this parameter can be set by selecting File-Preferences from the menu bar. See "Backing Store" on page 3-27.

A Note on Reading Data from Windows

On some systems, when backing store is provided by the window system (RETAIN=1), reading data from a window using TVRD may cause unexpected results. For example, data may be improperly read from the window even when the image displayed on screen is correct. Having IDL provide the backing store (RETAIN=2) ensures that the window contents will be read properly. These types of problems are described in more detail in the documentation for TVRD. See "Unexpected Results Using TVRD with X Windows" on page 1-948.

SCALE_FACTOR

Specifies a scale factor applied to the entire plot. The default value is 1.0, allowing output to appear at its normal size. SCALE_FACTOR is used to magnify or shrink the resulting output.

SCHOOLBOOK

Set this keyword to select the New Century Schoolbook PostScript font.

SET_CHARACTER_SIZE

The standard size and vertical spacing of vector-drawn fonts can be changed by specifying this keyword with a two-element vector. The first element specifies the new character width and thus the height of the characters (because vector-drawn fonts have a fixed aspect ratio). The second element specifies the vertical distance between lines. The default produces a character that is approximately 8 pixels wide, with 12 pixels between lines.

SET_COLORMAP

Set this keyword to a 14,739 (= 3 ⋅ 17^3) element byte vector containing the RGB-to-printer color translation table for a color PCL printer. The default table is for an HP Deskjet 500C printer.

The translation table is divided into red, green, and blue planes of 4913 (=17^3) elements each. For a given RGB triple, the offset into each plane is calculated as follows:

Offset = (Red/16)*289 + (Green/16)*17 + (Blue/16)

Thus, if the RGB triple is [16,32,160], the offset into each plane is 333. The printer will use the value at element 332 of the translation table as the red value, the value at element 5245 (=4913+332) as the green value, and the value at element 10158 (=9826+332) as the blue value.

SET_COLORS

Sets the number of pixel values, !D.N_COLORS and !D.TABLE_SIZE. This value is used by a number of IDL routines to determine the scaling of pixel data and the default drawing index. Allowable values range from 2 to 256, and the default value is 256. Use this parameter to make the Z-buffer device compatible with devices with fewer than 256 colors indices.

SET_GRAPHICS_FUNCTION

Most window systems allow applications to specify the graphics function. This is a logical function which specifies how the source pixel values generated by a graphics operation are combined with the pixel values already present on the screen. The complete list of possible values is given in Table 3.4. The default graphics function is GXcopy, which causes new pixels to completely overwrite any previous pixels.

Logical Function	Code	Definition
GXclear	0	0
GXand	1	source AND destination
GXandReverse	2	source AND (NOT destination)
GXcopy	3	source
GXandInverted	4	(NOT source) AND destination
GXnoop	5	destination
GXxor	6	source XOR destination
GXor	7	source OR destination
GXnor	8	(NOT source) AND (NOT destination)
GXequiv	9	(NOT source) XOR destination
GXinvert	10	(NOT destination)
GXorReverse	11	source OR (NOT destination)
GXcopyInverted	12	(NOT source)
GXorInverted	13	(NOT source) OR destination
GXnand	14	(NOT source) OR (NOT destination)
GXset	15	1
Table 3.4 Graphic Function Codes

 Not all functions are available on all window systems.

For example, the following code segment inverts the bottom bit in the rectangle defined by its diagonal corners (x0, y0) and (x1, y1):

DEVICE, GET_GRAPHICS = oldg, SET_GRAPHICS = 6
Set graphics function to exclusive or (GXor), save the old function.

POLYFILL, [[x0,y0], [x0,y1], [x1,y1], [x1,y0]], $

          /DEVICE, COLOR=1	Use POLYFILL to select the area to be inverted, the source pixel value is 1.

DEVICE, SET_GRAPH=oldg	Restore the previous graphics function.

SET_RESOLUTION

Set this keyword to a two-element vector that specifies the width and height of the Z-buffers. The default size is 640 by 480. If this size is not the same as the existing buffers, the current buffers are destroyed and the device is reinitialized.

SET_STRING

The string used to place the terminal into the graphics mode from the normal interactive terminal mode. If the 4100 series mode switch is set, using the keyword TEK4100, the default graphic mode setting string is <ESC>%!0, which selects the Tektronix code mode.

SET_TRANSLATION

This keyword can be used to allow multiple, simultaneous IDL sessions to use the same colors from a shared colormap. Use this keyword before the X connection is established (i.e., before a window is created), IDL will use the shared color map without allocating any additional colors, and will not load a grayscale ramp as is usually done when the X server starts up. The following example shows two cooperating IDL processes sharing the same colormap:

Execute the following commands in the first IDL session:

WINDOW, GET_X_ID = a

DEVICE, SET_TRANSLATION = t

OPENW, 1, 'junk.dat'

WRITEU, 1, a, !D.N_COLORS, t(0:!D.N_COLORS-1)

CLOSE, 1

LOADCT, 3

Execute the following commands in the second IDL session:

OPENR, 1, 'junk.dat'

a=0L

n=0L

READU,1, a, n

t = BYTARR(n)

READU, 1, t

CLOSE, 1

DEVICE, SET_TRANSLATION = t

WINDOW, COLORS=n, SET_X_ID=a

TV, DIST(256)

SET_WRITE_MASK

Sets the write mask to the specified value. For an n-bit system, the write mask can range from 0 to 2n-1.

STATIC_COLOR

Use this keyword to select the X Windows StaticColor visual. The value of the keyword represents the number of bits per pixel to be used. This keyword has effect only if no windows have been created. Visual classes are discussed in more detail in "X Windows Visuals" on page 3-55.

STATIC_GRAY

Use this keyword to select the X Windows StaticGray visual. The value of the keyword represents the number of bits per pixel to be used. This keyword has effect only if no windows have been created. Visual classes are discussed in more detail in "X Windows Visuals" on page 3-55.

SYMBOL

Set this keyword to select the Symbol PostScript font.

TEK4014

Set this keyword to specify that coordinates are to be output with full 12-bit resolution. If this keyword is not present or is zero, 10-bit coordinates are output. Normally, IDL sends 10-bit coordinates. 12-bit coordinates are compatible with most terminals, even those without the full resolution, but require more characters to send.

Notes: the 4014 and the 4100 modes can be used together. The coordinate system IDL uses for the Tektronix is 0 to 4095 in the X direction and 0 to 3120 in the Y direction, even when not in the 4014 mode. In the 10-bit case the internal coordinates are divided by 4 prior to output.

TEK4100

Set this keyword to indicate that the terminal is a 4100 or 4200 series terminal. The use of color, ANSI and Tektronix mode switching, hardware line styles, and pixel output with the TV procedure is supported with these terminals. Also, text is output differently.

TEXT

Set this keyword to set the encoding type for the CGM output file to text.

THRESHOLD

Set this keyword to select the threshold algorithm— the simplest dithering method. The value of this keyword is the threshold to be used. This algorithm simply compares each pixel against the given threshold, usually 128. If the pixel equals or exceeds the threshold the display pixel is set to white, otherwise it is black.

Macintosh Only

Set this keyword to use the Macintosh's default thresholding. Values greater than one cause the keyword to be set but are otherwise ignored.

TIMES

Set this keyword to select the Times-Roman PostScript font.

TRANSLATION

As discussed in "Shared Colormaps" on page 3-57, using the shared colormap (normally recommended) causes IDL to translate between IDL color indices (which always start with zero and are contiguous) and the pixel values actually present in the display. The TRANSLATION keyword specifies the name of a variable to receive the translation vector. To read the translation table, use the command:

DEVICE, TRANSLATION=TRANSARR

where TRANSARR is a named variable into which the translation array is stored. The result is a 256-element byte vector. Element zero of the vector contains the pixel value allocated for the first color in the IDL colormap, and so forth.

Microsoft Windows Only

This keyword is accepted by the WIN device, for compatibility with the X Windows driver, but simply returns a 256-element vector where each element has the value of its subscript (0 to 255).

TRUE_COLOR

Use this keyword to select TrueColor visuals. The value of the keyword represents the number of bits per pixel to be used. This keyword has effect only if no windows have been created. Visual classes are discussed in more detail in "X Windows Visuals" on page 3-55.

Macintosh Only

Setting this keyword causes all screen manipulations to be done in 24-bit mode. The value of the keyword is ignored, as is the current bit-depth of the monitor.

TTY

Set this keyword to specify that output should be sent to the terminal at the same time that it is being sent to a file due to the FILENAME or PLOT_TO keywords. A zero value causes output to go only to the file. If no output file is in use, this keyword has no effect.


Keywords to DEVICE - U through Z
Keywords for the DEVICE Procedure—U through Z

USER_FONT

A scalar string containing the name of a PostScript font to be used. The font name given must be specified exactly as the PostScript interpreter expects it, with the correct case and spelling. USER_FONT provides a way of using fonts that are not known to IDL.

VT240, VT241

Set this keyword to configure the REGIS device for VT240 series terminals.

VT340, VT341

Set this keyword to configure the REGIS device for VT340 series terminals.

WINDOW_STATE

Set this keyword to a named variable that returns an array containing one element for each possible window. Array element i contains a 1 if window i is open, otherwise it contains a 0.

XOFFSET

Specifies the X position, on the page, of the lower left corner of output generated by IDL. XOFFSET is specified in centimeters, unless INCHES is specified. See "Positioning Graphics Output" on page 3-30.

PostScript Only

SCALE does not affect the value of XOFFSET.

XON_XOFF

If present and non-zero, XON_XOFF causes each output page to start with device control commands that instruct the plotter to obey xon/xoff (^S/^Q) style flow control. Specifying a value of zero stops the issuing of such commands. You should only use this keyword before any output has been generated.

Such handshaking is the default. To turn it off, use the command

DEVICE, XON_XOFF=0

Often, it is not necessary to tell the plotter to obey flow control because the printing facilities on the system handle such details for you, but it is usually harmless.

XSIZE

Specifies the width of output generated by IDL. XSIZE is specified in centimeters, unless INCHES is specified.

PostScript Only

SCALE modifies the value of XSIZE. Hence, the following statement:

DEVICE,/INCHES,XSIZE=7.0,SCALE_FACTOR=0.5

results in a real width of 3.5 inches.

YOFFSET

Specifies the Y position, on the page, of the lower left corner of output generated by IDL. YOFFSET is specified in centimeters, unless INCHES is specified. See "Positioning Graphics Output" on page 3-30.

Note: The corner of the page from which the Y offset is measured (lower or upper left) differs on various devices. Read the device specific information in the following sections to determine how this is handled for your device.

PostScript Only

SCALE does not affect the value of YOFFSET.

YSIZE

Specifies the height of output generated by IDL. YSIZE is specified in centimeters, unless INCHES is specified.

PostScript Only

SCALE modifies the value of YSIZE. Hence, the following statement:

DEVICE,/INCHES,YSIZE=5.0,SCALE_FACTOR=0.5

results in a real width of 2.5 inches.

LJ250 Only

Changing the size, depth, or orientation of the output causes the current page to be sent to the file. The effect is identical to calling the ERASE procedure.

ZAPFCHANCERY

Set this keyword to select the ITC Zapf Chancery PostScript font.

ZAPFDINGBATS

Set this keyword to select the ITC Zapf Dingbats PostScript font.

Z_BUFFERING

This keyword enables and disables the Z-buffering. If this keyword is specified with a zero value, the driver operates as a standard 2D device, the Z-buffering is disabled, and the Z-buffer (if any) is deallocated. Setting this keyword to one (the default value), enables the Z-buffering.

To disable Z-buffering enter:

DEVICE, Z_BUFFERING = 0


Window Systems

The different window systems supported by IDL have many features in common. This section describes those features. See the individual descriptions of each system later in this chapter for additional information about each one.

IDL utilizes the window system by creating and using one or more largely independent windows, each of which can be used for the display of graphics and/or images. One color map table is shared among all these windows. Multiple windows can be active simultaneously. Windows are referenced using their index which is a non-negative integer.

"Dithering" or halftoning techniques are used to display images with multiple shades of gray on monochrome displays—displays that can only display white or black. This topic is discussed in "Image Display On Monochrome Devices" on page 3-28.

Graphic and image output is always directed to the current window. When a window system is selected as the current IDL graphics device, the index number of the current window is found in the !D.WINDOW system variable. This variable contains -1 if no window is open or selected. The WSET procedure is used to change the current window. WSHOW hides, displays, and iconifies windows. WDELETE deletes a window.

The WINDOW procedure creates a new window with a given index. If a window already exists with the same index, it is first deleted. The size, position, title, and number of colors, may also be specified. If you access the display before creating the first window, IDL automatically creates a window with an index number of 0 and with the default attributes.

Backing Store

One of the features that distinguishes various window systems is how they handle the issue of backing store. When part of a window that was previously not visible is exposed, there are two basic approaches that a window system can take. Some keep track of the current contents of all windows and automatically repair any damage to their visible regions (retained windows). This saved information is known as the backing store. Others simply report the damage to the program that created the window and leave repairing the visible region to the program (non-retained windows).

Value	Description
0	No backing store.
1	Request the server or window system to perform backing store.
2	Make IDL perform backing store.
Table 3.5 Allowed Values for the RETAIN Keyword

There are convincing arguments for and against both approaches. It is generally more convenient for IDL if the window system handles this problem automatically, but this often comes at a performance penalty. The actual cost of retained windows varies between systems and depends partially on the application.

The X Window system does not by default keep track of window contents. Therefore, when a window on the display is obscured by another window, the contents of its obscured portion is lost. Re-exposing the window causes the X server to fill the missing data with the default background color for that window, and request the application to redraw the missing data. Applications can request a backing store for their windows, but servers are not required to provide it. Many X servers do not provide backing store, and even those that do cannot necessarily provide it for all requesting windows. Therefore, requesting backing store from the server might help, but there is no certainty.

The IDL window system drivers allow you to control the issue of backing store using the RETAIN keyword to the DEVICE and WINDOW procedures. Using it with DEVICE allows you to set the default action for all windows, while using it with WINDOW lets you override the default for the new window. The possible values for this keyword are summarized in Table 3.5, and are described below:

•	Setting the RETAIN keyword to 0 specifies that no backing store is kept. In this case, exposing a previously obscured window leaves the missing portion of the window blank. Although this behavior can be inconvenient, it usually has the highest performance because there is no need to keep a copy of the window contents.

•	Setting the RETAIN keyword to 1 causes IDL to request that a backing store be maintained. If the window system decides to accept the request, it will automatically repair the missing portions when the window is exposed. X Windows may or may not provide backing store when requested, depending on the capabilities of the server and the resources available to it.

•	Setting the RETAIN keyword to 2 specifies that IDL should keep a backing store for the window itself, and repair any window damage when the window system requests it. This option exists for X Windows. In this case, a pixmap (off-screen display memory) the same size as the window is created at the same time the window is created, and all graphics operations sent to the window are also sent to the pixmap. When the server requests IDL to repair freshly exposed windows, this pixmap is used to fill in the missing contents. Pixmaps are a precious resource in the X server, so backing pixmaps should only be requested for windows with contents that must absolutely be preserved.

If the type of backing store to use is not explicitly specified using the RETAIN keyword, IDL assumes option 1 and requests the window system to keep a backing store.

A Note on Reading Data from Windows

On some systems, when backing store is provided by the window system (RETAIN=1), reading data from a window using TVRD may cause unexpected results. For example, data may be improperly read from the window even when the image displayed on screen is correct. Having IDL provide the backing store (RETAIN=2) ensures that the window contents will be read properly. These types of problems are described in more detail in the documentation for TVRD. See "Unexpected Results Using TVRD with X Windows" on page 1-948.

Image Display On Monochrome Devices

Images are automatically dithered when sent to some monochrome devices. Dithering is a technique which increases the number of apparent brightness levels at the expense of spatial resolution. Images with 256 gray levels are displayed on a display with only two colors, black and white, using halftoning techniques. PostScript handles dithering directly. IDL supports dithering for other devices if their DEVICE procedures accept the FLOYD, ORDERED, or THRESHOLD keywords.


Printing Graphics Output Files

For printer and plotter devices (e.g., PCL, PostScript, and HP-GL), IDL creates a file containing output commands. This file can be sent to the printer via the normal methods provided by the local operating system. When attempting to output the file before exiting IDL, the user must be sure that the graphics output file is complete. For example, the following IDL commands (executed under Unix) will not produce the desired result:

SET_PLOT,'PS'

PLOT,x,y

SPAWN,'lpr idl.ps'

These commands fail because the attempt to print the file is premature—the file is still open within IDL and is not yet complete.

The following lines of code are an IDL procedure called OUTPUT_PLOT which closes the current graphics file and sends it to the printer. This routine assumes that the graphics output file is named idl.xxx, where xxx represents the name of the graphics driver. For example, PostScript output file is assumed to be idl.ps. It also assumes that the graphics output to be printed is from the current graphics device, as selected with SET_PLOT.

Pro OUTPUT_PLOT, New_file	Close the current graphics file, and print it. If the New_file parameter is present, rename the file to the given name so it won't be overwritten.

DEVICE,/CLOSE	Close current graphics file.

file = 'idl.' + STRLOWCASE(!D.NAME)	Build the default output file name by using the idl name for the current device (!D.NAME).

cmd = 'lpr ' + file	Build shell commands to send file to the printer. You will probably have to change this command in accordance with local usage.

IF N_ELEMENTS(New_file) GT 0 THEN $

  cmd = cmd + '; mv' + file + ' ' + New_file
Concatenate rename command if new file specified.

SPAWN, cmd	Issue shell commands to print/rename file.

END

The call to DEVICE causes IDL to finish the file and close it, which makes it available for printing.

Setting Up The Printer

In order for IDL generated output files to work properly with printers and plotters, it is necessary for the device to be configured properly. This usually involves configuring both the device hardware and the operating system printing software. When setting up your system, keep the following points in mind:

•	The device and computer must use some form of flow control to prevent the computer from sending data faster than the printing device can handle it. The most common form of flow control is known as XON/XOFF, and involves the sending of Control-S (off) and Control-Q (on) characters from the device to the printer to manage the flow of data.

Many printers have a large buffer into which they store incoming data they haven't yet processed. This reduces the need to invoke flow control. When testing your configuration to ensure flow control is actually enabled, you must be sure to print a document long enough to fill any such buffer, or flow control may never occur, giving a false impression that the setup is correct. A common source of problems stem from attempting to print long IDL generated output files without proper flow control.

•	Some devices (such as PCL) require an eight-bit data path, while others (such as PostScript) do not. For devices that do, it is important to ensure that the printer port and system printing software provide such a connection.

If you are having problems printing on a PostScript printer, the ehandler.ps file provided in the ps subdirectory of the fonts subdirectory of the resource subdirectory of the IDL distribution can help you to debug your problem. Sending this file to your PostScript Printer causes it to print any subsequent errors it encounters on a sheet of paper and eject it. The effect of this file lasts until the printer is reset.

Setting Up Printers Under Unix

Printers are configured in the /etc/printcap file. This file describes to the system which printers are connected to it, the characteristics of each printer, and how the printer port should be configured. Managing the printcap file is usually discussed in the system management documentation supplied with the system by the manufacturer.

Setting Up Printers Under VMS

Printer queue configuration under VMS is a large topic. However, it is often sufficient to set the printer port up properly using the DCL_SET_TERMINAL command, and set up a printer queue using the standard printer form. Users can send eight-bit data to such a printer using the DCL PRINT/PASSALL command (On very small systems, it is even possible to dispense with the printer queue entirely and simply use the COPY command to send data to the printer port directly).

However, much more sophisticated arrangements are possible including the definition of specialized printer forms, placing printers on the local area network for use by more than one machine, and so forth. For information on these topics, refer to the relevant VMS documentation.

Positioning Graphics Output

The difference between the XOFFSET and YOFFSET keywords to the DEVICE procedure, and the higher level plot positioning keywords and system variables (discussed in Chapter 14 of the IDL User's Guide and Chapter 2 of this manual) can lead to confusion. A common misunderstanding is to attempt to use the DEVICE procedure "offset" and "size" keywords multiple times in an attempt to produce multiple plots on a single output page.

The DEVICE keywords are intended to specify the size and position of the entire output area on the page, not to move the plotting region for multiple plots. The driver does not monitor their values continuously, but only when initializing a new page or ejecting the current one.

The proper way to produce multiple plots is to use the high level positioning abilities. The !P.MULTI, !P.POSITION, and !P.REGION system variables can be used to position individual plots on the page. The plotting routines also accept the POSITION, MARGIN and REGION keywords.

Image Background Color

Graphical output that is displayed with a black background on a monitor frequently look better if the background is changed to white when printed on white paper. This is easily done with the statement:

a(WHERE(a EQ 0B)) = 255B


The CGM Device

The CGM, Computer Graphics Metafile, standard describes a device independent file format used for the exchange of graphic information. The IDL CGM driver produces CGM files encoded in one of three methods: Text, Binary or NCAR Binary. To direct graphics output to a CGM file, issue the command:

SET_PLOT,'CGM'

This causes IDL to use the CGM driver for producing graphical output. Once the CGM driver is selected, the DEVICE procedure controls its actions, as described below. Typing HELP, /DEVICE displays the current state of the CGM driver. The CGM driver defaults to the binary encoding using 256 colors.

Abilities and Limitations

This section describes details specific to IDL's CGM implementation:

•	IDL uses the CGM default integer encoding for graphic primitives. Coordinate values range from 0 to 32767. It is advisable to use the values stored in !D.X_SIZE and !D.Y_SIZE instead of assuming a fixed coordinate range.

•	Color information is output with a resolution of 8 bits (color indices and intensity values range from 0 to 255).

•	The definition of background color in the CGM standard is somewhat ambiguous. According to the standard, color index 0 and the background color are the same. Because background color is specified in the metafile as a color value (RGB triple), not an index, it is possible to have the background color not correspond with the color value of index 0.

•	The CGM BACKGROUND_COLOUR attribute is explicitly set by IDL only during an erase operation: changing the value of the color map at index 0 does not cause IDL to generate a BACKGROUND_COLOUR attribute until the next ERASE occurs. An ERASE command sets the background color to the value in the color map at index 0. The command ERASE, INDEX (where INDEX is not 0) generates the message "Value of background color is out of allowed range." For consistent results, modify the color table before any graphics are output.

•	The CGM standard uses scalable (variable size) pixels for raster images. By default, the TV and TVSCL procedures output images, regardless of size, using the entire graphics output area. To output an image smaller than the graphics output area, specify the XSIZE and YSIZE keywords with the TV and TVSCL procedures. For example:

SET_PLOT, 'CGM'	Select the CGM driver.

X = DIST(64)	Create a 64 x 64 element array

TVSCL, X	Display the image (fills entire screen)

ERASE	Now display 4 images on the screen.

XS = !D.X_SIZE / 2	Size of each image, X dimension.

YS = !D.Y_SIZE / 2	Size of each image, Y dimension.

TVSCL, X, 0, XSIZE=XS, YSIZE=YS	Upper left.

TVSCL, X, 1, XSIZE=XS, YSIZE=YS	Upper right.

TVSCL, X, 2, XSIZE=XS, YSIZE=YS	Lower left.

TVSCL, X, 3, XSIZE=XS, YSIZE=YS	Lower right.


The HP-GL Device

HP-GL (Hewlett-Packard Graphics Language) is a plotter control language used to produce graphics on a wide family of pen plotters. To use HP-GL as the current graphics device, issue the IDL command:

SET_PLOT,'HP'

This causes IDL to use HP-GL for producing graphical output. Once the HP-GL driver is enabled via SET_PLOT, the DEVICE procedure is used to control its actions, as described below. The default settings for the HP-GL driver are shown in Table 3.6. Use the statement:

HELP, /DEVICE

to view the current state of the HP-GL driver.

Feature	Value
File	idl.hp
Orientation	Portrait
Erase	No action
Polygon filling	Software
Turn plotter logically on/off	No
Specify xon/xoff flow control	Yes
Horizontal offset	3/4 in.
Vertical offset	5 in.
Width	7 in.
Height	5 in.
Table 3.6 Default HP-GL Driver Settings

Abilities And Limitations

IDL is able to produce a wide variety of graphical output using HP-GL. The following is a list of what is and is not supported:

•	All types of vector graphics can be generated, including line plots, contours, surfaces, etc.

•	HP-GL plotters can draw lines in different colors selected from the pen carousel. It should be noted that color tables are not used with HP-GL. Instead, each color index refers directly to one of the pens in the carousel.

•	Some HP-GL plotters can do polygon filling in hardware. Others can rely on the software polygon filling provided by IDL.

•	It is possible to generate graphics using the hardware generated text characters, although such characters do not give much improvement over the standard vector fonts. To use hardware characters, set the !P.FONT system variable to zero, or set the FONT keyword to the plotting routines to zero.

•	Since HP-GL is designed to drive pen plotters, it does not support the output of raster images. Therefore the TV and TVSCL procedures do not work with HP-GL.

•	Since pen plotters are not interactive devices, they cannot support such operations as cursors and windows.

HP-GL Linestyles

The LINESTYLE graphics keyword allows specifying any of 6 linestyles. These linestyles are documented in Chapter 2. HP-GL does not support all of these linestyles, and styles 3 and 4 differ from the definition in Chapter 2. The following table summarizes the differences:

Index	Normal Line Style	HP-GL Line Style
0	Solid	same
1	Dotted	same
2	Dashed	same
3	Dash Dot	Relative size of dash and dot are different.
4	Dash Dot Dot Dot	Dash Dot Dot
5	Long Dashes	same
Table 3.7 Linestyles for the HP-GL Device


The LJ Device

The LJ250 and LJ252 are color printers sold by Digital Equipment Corporation (DEC). To direct graphics output to a picture description file compatible with these printers, issue the command:

SET_PLOT, 'LJ'

This causes IDL to use the LJ driver for producing graphical output. To actually print the generated graphics, send the file to the printer using the normal printing facilities supplied by the operating system. Once the LJ driver is enabled via SET_PLOT, the DEVICE procedure is used to control its actions, as described below. The default settings for the LJ driver are given in Table 3.8. Use the HELP, /DEVICE command to view the current font, file, and other options currently set for LJ output.

Feature	Value
File	idl.lj
Mode	Portrait
Dither method	Floyd-Steinberg
Resolution	180 dpi
Number of planes	1 (monochrome)
Horizontal offset	1/2 in.
Vertical offset	1 in.
Width	7 in.
Height	5 in.
Table 3.8 Default LJ Driver Settings

LJ Driver Strengths

The LJ250 produces color graphics at a low cost. It is capable of producing good quality monochrome output, and is also good at color vector graphics and simple color imaging using a small number of predefined solid colors.

LJ Driver Limitations

The LJ250 is intended to be used as a low cost printer for business color graphics. Although it can be used to print color images, it is limited in its ability to produce satisfactory images of the sort commonly encountered in science and engineering. These limitations make it a poor choice for such work.

•	Although color is specified via the usual RGB triples using the TVLCT procedure, the LJ250 is only capable of generating a fixed set of colors. The number of possible colors depends on the resolution in use. When producing 180 dpi graphics, only the colors given in the table below are possible. In 90 dpi mode, 256 colors are available.

Color	Red Value	Green Value	Blue Value
Black	10	10	10
Yellow	227	212	33
Magenta	135	13	64
Cyan	5	56	163
Red	135	20	36
Green	8	66	56
Blue	10	10	74
White	229	224	217
Table 3.9 LJ250 Colors Available at 180 dpi

If a color is specified that the printer cannot produce, it substitutes the closest color it can. However, the results of such substitutions can give unexpected results. The fixed set of possible colors means that the LOADCT procedure is of limited use with the LJ250. It also means that it is difficult to produce satisfactory grayscale images.

•	The number of simultaneous colors possible on an output page is limited. Although images are specified in 8-bit bytes, the number of significant bits used ranges from 1 to 4 (as specified via the DEPTH keyword to the DEVICE procedure), allowing from 2 to 16 colors. Coupled with the above limitation on the colors that are possible, it is difficult to produce high quality image output.

LJ Suggestions

The following suggestions are intended to help you get the most out of the LJ250, taking its limitations into account:

•	Use monochrome output when possible. This results in considerably smaller output files, and provides most of the abilities the LJ250 handles well. When producing monochrome output, the LJ250 driver dithers images. This can often produce more satisfying gray scale output than possible using the printer in color mode.

•	Table 3.9 gives the RGB values to use when specifying colors at 180 dpi. To make more colors available, use 90 dpi resolution. The RGB values for the possible colors at 90 dpi are given in Table 7-6 of the LJ250/LJ252 Companion Color Printer Programmer Reference Manual. You can cause the printer to display the complete 256 color palette as follows: With the power off, press and hold the READY and DEC/PCL switches while momentarily pressing the power switch. Wait approximately 2 seconds and release the READY and DEC/PCL switches. The printer will take a few minutes to print all 256 colors. The complete display fits on a single page.

Use the table in the programmers manual with this display to select the colors to use. Note that the RGB values in the programmers manual are scaled from 1 to 100, while IDL scales such values from 0 to 255. Therefore, multiply the values obtained from the manual by 2.55 to properly scale them for use within IDL.

•	Unlike most devices, IDL does not initialize the LJ250 color map to a gray scale ramp because the printer cannot produce a satisfactory gray scale image. Instead, the default palettes given in Table 7-5 of the LJ250/LJ252 Companion Color Printer Programmer Reference Manual are used. If you modify the color map, the LJLCT procedure can be used to reset the color table to these defaults. LJLCT examines the !D.N_COLORS system variable to determine the number of output planes in use, and then loads the appropriate default color map.

•	When producing images, stick to images with small amounts of detail and large sections of uniform color. Complicated images do not reproduce well on this printer.


The Macintosh Display Device

The Macintosh version of IDL uses the "MAC" device by default. This device is similar to the X Windows device described starting on page 3-55. The "MAC" device is only available in IDL for Macintosh.

To set plotting to the Macintosh device, use the command:

SET_PLOT, 'MAC'


The Null Display Device

To suppress graphics output entirely, use the null device:

SET_PLOT, 'NULL'


The PCL Device

PCL (Printer Control Language) is used by Hewlett-Packard laser and ink jet printers to produce graphics output. To direct graphics output to a PCL file, issue the command:

SET_PLOT,'PCL'

This causes IDL to use the PCL driver for producing graphical output. Once the PCL driver is enabled via SET_PLOT, the DEVICE procedure is used to control its actions, as described below. The default settings for the PCL driver are given in Table 3.10. Note: Unlike monitors where white is the most visible color, PCL writes black on white paper. Setting the output color index to 0, the default when PCL output is selected, writes in black. A color index of 255 writes white which is invisible on white paper.

Feature	Value
File	idl.pcl
Mode	Portrait
Optimization level	0 (None)
Dither method	Floyd-Steinberg
Resolution	300 dpi
Horizontal offset	1/2 in.
Vertical offset	1 in.
Width	7 in.
Height	5 in.
Table 3.10 Default PCL Driver Settings

Color tables are not used with PCL unless the color mode has been enabled using the COLOR keyword to the DEVICE procedure. For images, color dithering produces realistic color image output even though PCL printers only produce eight output colors. See the SET_COLORMAP keyword for further details. For vector graphics, only eight colors are supported—no line dithering is implemented. Any RGB component that is not zero is treated as 255. The correct RGB definitions for each color are shown in Table 3.11. Use the HELP, /DEVICE command to view the current options for PCL output.

Color	Red Value	Green Value	Blue Value
Red	255	0	0
Green	0	255	0
Blue	0	0	255
Cyan	0	255	255
Magenta	255	0	255
Yellow	255	255	0
Black	0	0	0
White	255	255	255
Table 3.11 PCL RGB Color Definitions


The PostScript Device

PostScript is a programming language designed to convey a description of a page containing text and graphics. Many laser printers and high-resolution, high-quality photo typesetters support PostScript. Color output or direct color separations can be produced with color PostScript. To direct graphics output to a PostScript file, issue the command:

SET_PLOT, 'PS'

This causes IDL to use the PostScript driver for producing graphical output. Once the PostScript driver is enabled via SET_PLOT, the DEVICE procedure is used to control its actions, as described below. The default settings are given in Table 3.12.

Feature	Value
File	idl.ps
Mode	Portrait, non-encapsulated, no color
Horizontal offset	3/4 in.
Vertical offset	5 in.
Width	7 in.
Height	5 in.
Scale factor	1.0
Font size	12 points
Font	Helvetica
# Bits / Image Pixel	4
Table 3.12 Default PostScript Driver Settings

Note: Unlike monitors where white is the most visible color, PostScript writes black on white paper. Setting the output color index to 0, the default when PostScript output is selected, writes black. A color index of 255 writes white which is invisible on white paper. Color tables are not used with PostScript unless the color mode has been enabled using the DEVICE procedure. See "Color Images" on page 3-41.

To obtain adequate resolution, the device coordinate system used for PostScript output is expressed in units of 0.001 centimeter (i.e., 1000 pixels/cm).

Use the HELP, /DEVICE call to view the current font, file, and other options set for PostScript output.

Using PostScript Fonts

Normally, IDL uses vector-drawn characters for annotating plots (!P.FONT is -1). These characters are of good quality and are extremely flexible. However, if this flexibility is not required, higher quality characters are available via PostScript fonts. In order to get IDL to use the PostScript fonts, do one of the following:

•	Set !P.FONT to 0, making hardware fonts the default.

or

•	Use the FONT keyword with the plotting and graphics procedures to specify font 0.

The default PostScript font is 12 point Helvetica. To change this font, use the DEVICE procedure with the font selection keywords described in Table 3.13.

PostScript Font	DEVICE Keywords
Courier	/COURIER
Courier Bold	/COURIER, /BOLD
Courier Oblique	/COURIER, /OBLIQUE
Courier Bold Oblique	/COURIER, /BOLD, /OBLIQUE
Helvetica	/HELVETICA
Helvetica Bold	/HELVETICA, /BOLD
Helvetica Oblique	/HELVETICA, /OBLIQUE
Helvetica Bold Oblique	/HELVETICA, /BOLD, /OBLIQUE
Helvetica Narrow	/HELVETICA, /NARROW
Helvetica Narrow Bold	/HELVETICA, /NARROW, /BOLD
Helvetica Narrow Oblique	/HELVETICA, /NARROW, /OBLIQUE
Helvetica Narrow Bold Oblique	/HELVETICA, /NARROW, /BOLD, /OBLIQUE
ITC Avant Garde Gothic Book	/AVANTGARDE, /BOOK
ITC Avant Garde Gothic Book Oblique	/AVANTGARDE, /BOOK, /OBLIQUE
ITC Avant Garde Gothic Demi	/AVANTGARDE, /DEMI
ITC Avant Garde Gothic Demi Oblique	/AVANTGARDE, /DEMI, /OBLIQUE
ITC Bookman Demi	/BKMAN, /DEMI
ITC Bookman Demi Italic	/BKMAN, /DEMI, /ITALIC
ITC Bookman Light	/BKMAN, /LIGHT
ITC Bookman Light Italic	/BKMAN, /LIGHT, /ITALIC
ITC Zapf Chancery Medium Italic	/ZAPFCHANCERY, /MEDIUM, /ITALIC
ITC Zapf Dingbats	/ZAPFDINGBATS
New Century Schoolbook	/SCHOOLBOOK
New Century Schoolbook Bold	/SCHOOLBOOK, /BOLD
New Century Schoolbook Italic	/SCHOOLBOOK, /ITALIC
New Century Schoolbook Bold Italic	/SCHOOLBOOK, /BOLD, /ITALIC
Palatino	/PALATINO
Palatino Bold	/PALATINO, /BOLD
Palatino Italic	/PALATINO, /ITALIC
Palatino Bold Italic	/PALATINO, /BOLD, /ITALIC
Symbol	/SYMBOL
Times	/TIMES
Times Bold	/TIMES, /BOLD
Times Italic	/TIMES, /ITALIC
Times Bold Italic	/TIMES, /ITALIC, /BOLD
Table 3.13 The Standard 35 PostScript Fonts

 Any of the "standard 35" PostScript fonts can be selected in this manner.

Note that when generating three-dimensional plots, it is best to use the vector-drawn characters because IDL can draw them in perspective with the rest of the plot. When using PostScript fonts, commands may be inserted into the text in order to specify positioning and font changes in mid-text. These commands are described in Table 3.14

Command	Action
!A	Shift above division line.
!B	Shift below the division line.
!C	Start a new line of text below the current line.
!D	Shift down to the first level subscript and decrease the character size by a factor of 0.62.
!E	Shift up to the exponent level and decrease the character size by a factor of 0.44.
!I	Shift down to the index level and decrease the character size by a factor of 0.44.
!L	Shift down to the second level subscript. Decrease the character size by a factor of 0.62.
!M	Select the PostScript Symbol font.
!MX	Insert a bullet character (•).
!N	Shift back to the normal level and original character size.
!R	Restore position. The current position is set from the top of the save positions stack.
!S	Save position. The current position is saved on the top of the save positions stack.
!U	Shift to upper subscript level. Decrease the character size by a factor of 0.62.
!W	Same as !12.
!X	Return to the entry font.
!!	Display the ! symbol.
!3 - !20	Change to the font specified by the given font number.
Table 3.14 PostScript Text Commands

. They are similar to the commands provided for the standard vector-drawn characters described in Chapter 9 of the IDL User's Guide. The examples given there apply to PostScript text as well.

The in-text commands for changing fonts consist of a leading "!" character followed by a number between 3 and 20. These numbers are related to a PostScript font by use of a "font mapping table" maintained by the PostScript driver. The current font mapping can be displayed by using the command:

HELP, /DEVICE

which gives information on the current state of the graphics device. The information related to font mapping will look similar to:

 Font Mapping:

 (!3) Helvetica (!4) Helvetica-Bold

 (!5) Helvetica-Narrow (!6) Helvetica-Narrow-BoldOblique

 (!7) Times-Roman (!8) Times-BoldItalic

 (!9) Symbol (!10) ZapfDingbats

 (!11) Courier (!12) Courier-Oblique

 (!13) Palatino-Roman (!14) Palatino-Italic

 (!15) Palatino-Bold (!16) Palatino-BoldItalic

 (!17) AvantGarde-Book (!18) NewCenturySchlbk-Roman

 (!19) NewCenturySchlbk-Bold (!20) <Undefined-User-Font>

For example, the following statement produces a large Greek letter alpha in the center of the page:

XYOUTS, .5, .5, /NORMAL, "!9a", FONT=0, SIZE=5.0

The "!9" changes to the PostScript Symbol font. The following "a" is then interpreted in that font as an alpha. To determine the relationship between ASCII characters and their PostScript font equivalents, consult the PostScript Language Reference Manual. The font mapping table can be changed by using the FONT_INDEX keyword to the DEVICE procedure. For example, the statement:

DEVICE, /PALATINO, /BOLD, /ITALIC

immediately changes the current font to the PostScript PalatinoBoldItalic font. If the FONT_INDEX keyword is present, the current font is not changed. Instead, the specified font map entry is changed to the specified font. This mapping can then be used later to change fonts in mid-text. For example, the following statements map PalatinoBoldItalic to font index 4, and then outputs text using that font and the Symbol font:

DEVICE, /PALATINO, /BOLD, /ITALIC, FONT_INDEX=4
Map the font selected by !4 to be PalatinoBoldItalic.

XYOUTS, .3, .5, /NORMAL, "!4Alpha: !9a", FONT=0, SIZE=5.0
Output "Alpha :" in PalatinoBoldItalic followed by an Alpha character.

NOTE: It is important to realize that although the PostScript driver provides abilities similar to the vector drawn fonts described in Chapter 9 of the IDL User's Guide, the actual fonts are different. The font names and the characters in various positions differ markedly between them.

Color PostScript

If you have a color PostScript device you can enable the use of color with the statement:

DEVICE, /COLOR

Enabling color also enables the color tables. Text and graphic color indices are translated to RGB by dividing the red, green and blue color table values by 255. As with most display devices, color indices range from 0 to 255. Zero is normally black and white is normally represented by an index of 255. For example, to create and load a color table with four elements, black, red, green and blue:

TVLCT, [0,255,0,0], [0,0,255,0], [0,0,0,255]

Drawing text or graphics with a color index of 0 results in black, 1 in red, 2 in green, and 3 in blue.

Color Images

As with black and white PostScript, images may be output with 1, 2, 4, or 8 bits, yielding 1, 2, 16, or 256 possible colors. In addition, images are either pseudo-color or true-color. A pseudo-color image is a two dimensional image, each pixel of which is used to index the color table, thereby obtaining an RGB value for each possible pixel value. Pseudo-color images are similar to those displayed using the workstation monitor.

Note: in the case of pseudo-color images of fewer than 8 bits, the number of columns in the image should be an exact multiple of the number of pixels per byte (i.e., when displaying 4 bit images the number of columns should be even, and 2 bit images should have a column size that is a multiple of 4). If the image column size is not an exact multiple, extra pixels with a value of 255 are output at the end of each row. This causes no problems if the color white is loaded into the last color table entry, otherwise a stripe of the last (index number 255) color is drawn to the right of the image.

True-Color Images

A true-color image consists of an array with three dimensions, one of which has a size of three, containing the three color components. It may be considered as three two dimensional images, one each for the red, green and blue components. For example a true-color n by m element image can be ordered in three ways: pixel interleaved (3,  n, m), row interleaved (n, 3, m), or image interleaved (n, m, 3). By convention the first color is always red, the second green, and the last is blue.

True-color images are also routed through the color tables. The red color table array contains the intensity translation table for the red image, and so forth. Assuming that the color tables have been loaded with the vectors R, G, and B, a pixel with a color value of (r, g, b) is displayed with a color of (Rr, Gg, Bb). As with other devices, a color table value of 255 represents maximum intensity, while 0 indicates an absence of the color. To pass the RGB pixel values without change, load the red, green and blue color tables with a ramp with a slope of 1.0:

TVLCT, INDGEN(256), INDGEN(256), INDGEN(256)

or with the LOADCT procedure:

LOADCT, 0	Load standard black/white table.

Use the TRUE keyword to the TV and TVSCL procedures to indicate that the image is a true-color image and to specify the dimension over which color is interleaved. A value of 1 specifies pixel interleaving, 2 is row interleaving, and 3 is image interleaving. The following example writes a 24-bit image, interleaved over the 3rd dimension, to a PostScript file:

SET_PLOT, 'PS'

;Set the PostScript device to *8* bits per color, not 24:

DEVICE, FILE='24bit.ps', /COLOR, BITS=8

TV, [[[r]], [[g]], [[b]]], TRUE=3

DEVICE, /CLOSE

Image Background Color

Images that are displayed with a black background on a monitor frequently look better if the background is changed to white when displayed with PostScript. This is easily done with the statement:

a(WHERE(a EQ 0B)) = 255B

PostScript Positioning

Using the XOFFSET and YOFFSET Keywords

Often, IDL users are confused by the use of the XOFFSET and YOFFSET keywords to the PostScript DEVICE routine. These keywords control the position of IDL plots on the page. XOFFSET specifies the "X" position of the lower left corner of the output generated by IDL. This offset is always taken relative to the lower left-hand corner of the page when viewed in portrait orientation. YOFFSET specifies the "Y" position of the lower left corner of the output generated by IDL. This offset is also taken relative to the lower left-hand corner of the page when viewed in portrait orientation.

Figure 3.1 shows how the XOFFSET and YOFFSET keywords are interpreted. The page on the left shows an IDL plot printed in "portrait" orientation. Note that the X and Y offsets work just as we expect them to—increasing the XOFFSET moves the plot to the right and increasing the YOFFSET moves the plot up the page. The page on the right shows an IDL plot printed in "landscape" orientation. Here, the X and Y offsets are still taken relative to the same points even though the orientation of the plot has changed. This happens because IDL moves the origin of the plot before rotating the PostScript coordinate system 270 degrees clockwise for the landscape plot.

Note also that the XOFFSET and YOFFSET keywords have no effect when you generate ENCAPSULATED PostScript output.

Encapsulated PostScript Output

Another form of PostScript output is Encapsulated PostScript. This is the format used to import PostScript files into page layout and desktop publishing programs. An Encapsulated PostScript (EPS) file is similar to a regular PostScript file except that it contains only one page of PostScript output contained in a "bounding box" that is used to tell other programs about the size and aspect ratio of the encapsulated image.

Most of the time, output from IDL to an EPS file is properly scaled into the EPS bounding box because commands such as PLOT take full advantage of the plotting area made available to them. Sometimes, however, the default bounding box is inappropriate for the image being displayed.

As an example, suppose you have an image that is narrow and tall that, when TV'ed to an IDL window, fills only a small portion of the plotting window. Similarly, when output to an EPS file, this image will only fill a small portion of the bounding box. When the resulting EPS file is brought into a desktop publishing program, it becomes very hard to properly scale the image since the aspect ratio of the bounding box bears no relation to the aspect ratio of the image itself.

To solve this problem, use the XSIZE and YSIZE keywords to the DEVICE procedure to make the bounding box just large enough to contain the image. Since IDL uses a resolution of 1000 dots per centimeter with the PostScript device, the correct XSIZE and YSIZE (in centimeters) can be computed as:

•	XSIZE = Width of image in pixels/1000.0 pixels per cm

•	YSIZE = Height of image in pixels/1000.0 pixels per cm

The following IDL procedure demonstrates this technique. This procedure reads an X Windows Dump file and writes it back out as a properly-sized, 8-bit-color Encapsulated PostScript file:

PRO XWDTOEPS, filename

array = READ_XWD(filename, r, g, b)
Read the XWD file. Pixel intensity information is stored in the variable `array'. Values to reconstruct the color table are stored in `r', `g', and `b'.

TVLCT, r,g,b	Reconstruct the color table.

TV, array	Display the image in an IDL window.

s = SIZE(array)	Find the size of the picture. The width of the picture (in pixels) is stored in s(1). The height of the picture is stored in s(2):

fl = STRLEN(filename)	Take the `xwd' (for X Windows Dump) extension off of the old filename and replace it with `eps'.

filename = STRMID(filename, 0, fl-4)

filename = filename + '.eps'

PRINT, 'Making file: ', filename

PRINT, s

SET_PLOT, 'ps'	Set the plotting device to PostScript.

DEVICE, /ENCAPSUL, BITS_PER_PIXEL=8, /COLOR, $

        FILENAME=filename, XSIZE=S(1)/1000., $

        YSIZE=S(2)/1000.	Use the DEVICE procedure to make the output encapsulated, 8 bits, color, and only as wide and high as it needs to be to contain the XWD image:

TV, array	Write the image to the file.

DEVICE, /CLOSE	Close the file.

SET_PLOT, 'x'	Return plotting to X Windows.

END

Multiple Plots on the Same Page

To put multiple plots on the same PostScript page, use the !P.MULTI system variable (described in more detail on page 2-17). !P.MULTI is a 5-element integer array that controls the number of rows and columns of plots to make on a page or in a graphics window.

The first element of !P.MULTI is a counter that reports how many plots remain on the page. The second element of !P.MULTI is the number of columns per page. The third element is the number of rows per page.

For example, the following lines of code create a PostScript file,  multi.ps, with 6 different plots arranged as 2 columns and 3 rows:

SET_PLOT, 'PS'	Set plotting to PostScript.

DEVICE, FILENAME='multi.ps'	Set the filename.

!P.MULTI = [0, 2, 3]	Make IDL's plotting area hold 2 columns and 3 rows of plots.

A = FINDGEN(10)	Create a simple dataset.

PLOT, A	Make 6 different plots.

PLOT, SIN(A)

PLOT, COS(A)

PLOT, TAN(A)

PLOT, TANH(A)

PLOT, SINH(A)

DEVICE, /CLOSE	Close the file.

!P.MULTI = 0	Reset plotting to 1 plot per page.

The resulting file produces a set of plots as shown below.

Importing IDL Plots into Other Documents

This section shows how to generate IDL PostScript graphics so that they can be inserted into other documents. It also provides several examples of how the PostScript graphics device is used. Simply omit the ENCAPSULATED keyword from the calls to DEVICE if you wish to produce plots that can be printed directly. The figure below is an encapsulated PostScript file suitable for inclusion in other documents. It was produced with the following IDL statements:

SET_PLOT, 'PS'	Select the PostScript driver.

DEVICE, /ENCAPSULATED, FILENAME = 'pic1.ps'
Note use of ENCAPSULATED keyword.

x = FINDGEN(200)

PLOT, 10000 * SIN(x/5) / EXP(x/100), $

    LINESTYLE = 2, TITLE = 'IDL PostScript Plot', $

    XTITLE = 'Point Number', YTITLE='Y Axis Title', $

    FONT = 0	Plot the sine wave.

OPLOT, 10000 * COS(x/5) / EXP(x/100), LINESTYLE = 4
Add the cosine.

XYOUTS, 100, -6000, 'Sine', FONT = 0
Annotate the plot.

OPLOT, [120, 180], [-6000, -6000], LINESTYLE = 2

XYOUTS, 100, -8000, 'Cosine', FONT = 0

OPLOT, [120, 180], [-8000, -8000], LINESTYLE = 4

Note the use of the ENCAPSULATED keyword in the call to DEVICE. The figure below is a more complicated plot. It demonstrates some of the three-dimensional plotting capabilities of IDL. It was produced with the following IDL statements:

SET_PLOT, 'PS'	Select the PostScript driver.

DEVICE, /ENCAPSULATED, FILENAME = 'pic2.ps'
Note use of ENCAPSULATED keyword.

OPENR, 1, !DIR+'/images/abnorm.dat'
Access the data.

aa = ASSOC(1, BYTARR(64, 64))

a = SMOOTH(aa(0), 3)	Get a smoothed version.

SURFACE, a, /SAVE, ZAXIS = 1, XSTYLE = 1, YSTYLE = 1
Generate the surface.

CONTOUR, a, /T3D, /NOERASE, ZVALUE = 1, $

         XSTYLE = 1, YSTYLE = 1, C_LINESTYLE = [0,1,2], $

         TITLE = 'IDL PostScript Plot'
Add the contour.

CLOSE, 1

The figure below illustrates polygon filling. It was produced with the following IDL statements:

SET_PLOT, 'PS'

DEVICE, /ENCAPSULATED, FILENAME = 'pic3.ps'

x = FINDGEN(200)

a = 10000 * sin(x / 5) / exp(x / 100)
Upper sine wave.

PLOT, a, /NODATA, TITLE = 'IDL PostScript Plot', $

      XTITLE='Point Number', YTITLE='Y Axis Title', $

      FONT = 0	Make the axes and titles.

C = [X, ROTATE(X, 2)]	Vector of X vertices for polygon filling. Note that the ROTATE(V,2) function call returns the vector V in reverse order.

D = [A, ROTATE(A-2000, 2)]	Vector of Y vertices for polygon filling.

POLYFILL, C, D, COLOR=192	Fill the region using an intensity of about 75% white.

The figure below illustrates IDL PostScript images. In this case, the same image is reproduced four times. In each case, a different number of bits are used per image pixel. It was produced with the following IDL statements:

SET_PLOT, 'PS'

DEVICE, /ENCAPSULATED, FILENAME = 'pic4.ps'

OPENR, 1, FILEPATH('people.dat', SUBDIR='images')
Open image file.

a = BYTARR(192, 192, /NOZERO)
Variable to hold image.

READU, 1, a	Input the image.

CLOSE, 1	Done with the file.

A(0,0) = BYTSCL(INDGEN(192))#REPLICATE(1,16)
Add a color table ramp to the bottom of the image.

FOR i = 0,3 DO BEGIN	Output the image four times.

DEVICE, BITS_PER_PIXEL=2^i	Use 1, 2, 4, and 8 bits per pixel.

TV, a, i, XSIZE=2.5, YSIZE=2.5, /INCHES
Output using TV with position numbers 0, 1, 2, and 3.

ENDFOR


The Regis Terminal Device

IDL provides Regis graphics output for the DEC VT240, VT330, and VT340 series of terminals. To output graphics to such terminals, issue the IDL command:

SET_PLOT, 'REGIS'

This causes IDL to use the Regis driver for producing graphical output.

Defaults for Regis Devices

The default setting for Regis output is: VT340, 16 colors, 4 bits per pixel.

Regis Limitations

•	Four colors are available with VT240 and VT241 terminals, sixteen colors are available with the VT330 and VT340.

•	Thick lines are emulated by filling polygons. There may be a difference in linestyle appearance between thick and normal lines.

•	Image output is slow and is of poor quality, especially on the VT240 series. The VT240 is only able to write pixels on even numbered screen lines. IDL offers two methods of writing images to the 240:

•	Even and odd pairs of rows are averaged and written to the screen. An n, m image will occupy n columns and m screen rows. If this method is selected, graphics and image coordinates coincide. This method is the default (AVERAGE_LINES = 1). Routines that rely on a uniform graphics and image coordinate system, such as SHADE_SURF, work only in this mode.

•	Each line of the image is written to the screen, displaying every image pixel. An n, m image occupies 2m lines on the screen. (AVERAGE_LINES = 0). Graphics and image coordinates coincide only at the lower left corner of the image.

•	Pixel values cannot be read back from the terminal, rendering the TVRD function inoperable.


The SunView Device

The SunView device is no longer supported. Note that the paper documentation for IDL version 4.0 does not reflect this fact.


The Tektronix Device

The Tektronix 4000 (4010, 4014, etc.), 4100 and 4200 series of graphics terminals (and the multitude of terminals and microcomputers that emulate them) are among the most common graphics devices available. To use IDL graphics with such terminals, issue the command:

SET_PLOT,'TEK'

This causes IDL to use the Tektronix driver for producing graphical output. Once the Tektronix driver is enabled via SET_PLOT, the DEVICE procedure is used to control its actions, and to configure IDL for the specific features of your terminal. If you never call the DEVICE procedure, IDL assumes a plain vanilla Tektronix 4000 series compatible terminal. The 4200 series is upwardly compatible with the 4100 series; all references to the 4100 series also include the 4200 series. To set up IDL for use with a 4100 series compatible terminal with n colors, enter the following commands:

SET_PLOT, 'TEK'

DEVICE, /TEK4100, COLORS = n

The number of colors should be set to 2B where B is the number of bit planes in your terminal. If you use a Tektronix compatible terminal that requires calling the DEVICE procedure for configuration, you should probably create and use a start-up procedure the calls the DEVICE procedure, as described in Chapter 2. Because of the tremendous variation among the requirements and abilities of these terminals, it is crucial that you configure IDL properly for your terminal. In particular, the mode switching character sequences, set by the keyword parameters SET_STRING and RESET_STRING must be set correctly.

The DEVICE Procedure For Tektronix Terminals

The default setting for Tektronix output is: 10-bit coordinates, 4000 series terminals, and no use of color. The DEVICE keywords can be used to modify these defaults.

Tektronix Limitations

The line drawing procedures work with all models. Line style and color capabilities vary greatly among terminal models and/or emulation programs.

Color and the display of images (albeit very slowly and frequently of a poor quality because of the small number of colors) is usable only with 4100 series terminals. Hardware polygon fill and thick lines do not work with the 4000 series.

The image coordinate system does not match the graphics coordinate system. The graphics coordinates range from 0 to 3071 in Y, and from 0 to 4095 in X. Image coordinates vary according to terminal model. A typical range is from 0 to 479 in Y, and 0 to 639 in X. Because of this, the SHADE_SURF procedure does not work with Tektronix terminals.

Warning: Not all 4100 series terminals are capable of displaying images—the Tektronix pixel operations option is required. Many terminal emulators do not emulate this option. The Tektronix commands used to output images are: RU, begin pixel operations, RS, set pixel viewport, and RP, raster write. If your terminal or emulator does not accept these commands, you will not be able to display images.

The Tektronix graphics protocol does not allow the specification of line thickness. Lines with a thickness more than 1.0 are drawn using polygon filling in the case of 4100 series terminals. With 4000 series terminals, thick lines are emulated by drawing multiple thin lines. This scheme will produce artifacts on some Tektronix emulating devices because of differing resolutions, normal line thicknesses and inexact coordinate conversions.

Tektronix Device Limitations

Usage of Tektronix and Tektronix-compatible terminals with IDL has the following limitations:

•	Image coordinates do not match the coordinates used by the rest of the graphic procedures. This is because no two models of Tektronix terminals are compatible. The graphics procedures utilize the default coordinate system of 1024 by 780, or 4096 by 3120 in the 12-bit mode. The size of the pixel memory and coordinate system vary widely between models. The Position parameter of the TV and TVSCL procedures does not work.

•	The cursor can not be positioned from the computer meaning that the TVCRS procedure cannot be used with the Tektronix driver.

•	Pixel values may not be read back from the terminal, rendering the TVRD function inoperable.


The Microsoft Windows Device

The Microsoft Windows version of IDL uses the "WIN" device by default. This device is similar to the X Windows device described below (starting on page 3-55). The "WIN" device is only available in IDL for Windows.

To set plotting to the Microsoft Windows device, use the command:

SET_PLOT, 'WIN'


The X Windows Device

X Windows is a network-based windowing system developed by MIT's project Athena. IDL uses the X System (often referred to simply as "X"), to provide an environment in which the user can create one or more independent windows, each of which can be used for the display of graphics and/or images.

In the X system, there are two basic cooperating processes: clients and servers. A server consists of a display, keyboard, and pointer (such as a mouse) as well as the software that controls them. Client processes (such as IDL) display graphics and text on the screen of a server by sending X protocol requests across the network to the server. Although in the most common case, the server and client reside on the same machine, this network based design allows much more elaborate configurations.

To use X Windows as the current graphics device, issue the IDL command:

SET_PLOT, 'X'

This causes IDL to use the X Window System for producing graphical output. Once the X driver is enabled via SET_PLOT, the DEVICE procedure is used to control its actions, as described below.

Use the statement:

HELP, /DEVICE

to view the current state of the X Windows driver.

X Windows Visuals

Visuals specify how the hardware deals with color. The X Window server (your display) may provide colors or only gray scale (black and white), or both. The color tables may be changeable from within IDL (read-write), or may be fixed (read-only). The value of each pixel value may be mapped to any color (Un-decomposed Colormap), or certain bits of each pixel are dedicated to the red, green, and blue primary colors (Decomposed Colormap).

There are six X Windows visual classes—read-write and read-only visuals for three types of displays: Gray Scale, Pseudo Color, and Decomposed Color. The names of the visuals are shown in Table 3.15.

Visual Name	Writable	Description
StaticGray	no	Gray scale
GrayScale	yes	Gray scale
StaticColor	no	Undecomposed color
PseudoColor	yes	Undecomposed color
TrueColor	no	Decomposed color
DirectColor	yes	Decomposed color
Table 3.15 X Windows Visual Classes

IDL supports all six types of visuals, although not at all possible depths. Unix X Window System users can use the command xdpyinfo to determine which visuals are supported by their systems.

Each X Window server has a default visual class. Many servers may provide multiple visual classes. For example, a server with display hardware that supports an 8-bit-deep, un-decomposed, writable color map (PseudoColor), may also easily provide StaticColor, StaticGray, and GrayScale visuals.

You can select the visual used by IDL using the DEVICE procedure before a window is created, or by including the resource idl.gr_visual in your X defaults file, as explained in "Setting the X Window Defaults" on page 3-61.

How IDL Selects a Visual Class

When opening the display, IDL asks the display for the following visuals, in order, until a supported visual class is found:

 DirectColor, 24-bit

TrueColor, 24-bit

PseudoColor, 8-bit, then 4-bit

StaticColor, 8-bit, then 4-bit

GrayScale, any depth

StaticGray, any depth

You can override this behavior by using the DEVICE routine to specify the desired visual class and depth before you create a window. For example, if you are using a display that supports both the DirectColor, 24-bit-deep visual, and an 8-bit-deep PseudoColor visual, IDL will select the 24-bit-deep DirectColor visual. To instead use PseudoColor, issue the following command before creating a window:

DEVICE, PSEUDO_COLOR = 8

The colormap/visual class combination is chosen when IDL first connects with the X Window server. Note that if you connect with the X server by creating a window or using the DEVICE keyword to the HELP procedure, the visual class will be set; it then cannot be changed until IDL is restarted. If you wish to use a visual class other than the default, be sure to set it with a call to the DEVICE procedure before creating windows or otherwise connecting with the X Window server.

Windows are created in two ways:

1. Using the WINDOW procedure. WINDOW allows you to explicitly control many aspects of how the window is created.

2. If no windows exist and a graphics operation requiring a window is executed, IDL implicitly creates window 0 with the default characteristics.

Once the visual class is selected, all subsequently-created windows share the same class and colormap. The number of simultaneous colors available is stored in the system variable !D.N_COLORS. The visual class and number of colors, once initialized, cannot be changed without first exiting IDL.

How IDL Obtains a Colormap

IDL chooses the type of colormap in the following manner:

•	By default, the shared colormap is used whenever possible (i.e., whenever IDL is using the default visual for the system). All available colors from the shared colormap are allocated for use by IDL. This is what happens when no window currently exists and a graphics operation causes IDL to implicitly create one.

•	If the number of colors to use is explicitly specified using the COLORS keyword with the WINDOW procedure, IDL attempts to allocate the number of colors specified from the shared colormap using the default visual of the screen. If there aren't enough colors available, a private colormap with that number of colors is used instead.

•	Specifying a negative value for the COLORS keyword to the WINDOW procedure causes IDL to attempt to use the shared colormap, allocating all but the specified number of colors. For example:

WINDOW, COLORS = -8

allocates all but 8 of the currently available colors. This allows other applications that might need their own colors to run in tandem with IDL.

•	If a visual type and depth is specified, via the DEVICE procedure, which does not match the default visual of the screen, a new, private, colormap is created.

Using Color Under X

Colormaps define the mapping from color index to screen color. Two attributes of colormaps are important to the IDL user: they may be private or shared; and they may be static or writable. These different types of colormaps are described below.

Shared Colormaps

The window manager creates a colormap when it is started. This is known as the default colormap, and can be shared by most applications using the display. When each application requires a colormap entry (i.e., a mapping from a color index to a color), it allocates one from this shared table. Advantages and disadvantages of shared colormaps include:

•	Using the shared colormap ensures that all applications share the available colors without conflict. A given application will not change a color that is allocated to a different application. In the case of IDL it means that IDL can change the colors it has allocated without changing the colors in use by the window manager or other applications.

•	The window system interface routines must translate between the actual and allocated pixel values, significantly slowing the transfer of images.

•	The shared colormap might not have enough colors available to perform the desired operations with IDL.

•	The number of available colors in the shared colormap depends on the window manager in use and the demands of other applications. Thus, the number of available colors can vary.

•	The allocated colors in a shared colormap do not generally start at zero and they are not necessarily contiguous. This makes it difficult to use the write mask for certain operations.

Private Colormaps

An application can create its own private color map. Most hardware can only display a single colormap at a time, so these private colormaps are called virtual color maps, and only one at a time is actually in use and visible. When the window manager gives the color focus to a window with a private colormap, the X window system loads its virtual colormap into the hardware colormap.

•	Every color index supported by the hardware is available to IDL, improving the quality of images.

•	Allocated colors always start at zero and are contiguous. This simplifies using the write mask.

•	No translation between internal pixel values and the values required by the server is required, making the transfer of images more efficient.

•	When the IDL colormap is loaded, other applications are displayed using the wrong colors. Furthermore, colors from the shared colormap are usually allocated from the lower end of the map first. These are the colors allocated by the window manager for such things as window borders, the color of text, and so forth. Since most IDL colormaps have very dark colors in the lower entries, the end effect with the IDL colormap loaded is that the non-IDL portions of the screen go blank.

Static Colormaps

As mentioned above, the contents of static colormaps are determined outside of IDL and cannot be changed. When using a static colormap, the TVLCT procedure simulates writable colormaps by finding the closest RGB color entry in the colormap to the requested color. The colormap translation table is then set to map IDL color indices to those of the closest colors in the colormap.

The colors present in the colormap may, and probably will, not match the requested colors exactly. For example, with a typical static color map, loading the IDL standard color table number 0, which consists of 256 intensities of gray, results in only 8 or 16 distinct intensities.

With static colormaps, loading a new color table does not affect the appearance of previously written objects. The internal translation tables are modified, which only affects objects that are subsequently written.

Color Translation

As mentioned above, colors from the shared colormap do not necessarily start from index zero, and are not necessarily contiguous. IDL preserves the illusion of a zero based contiguous colormap by maintaining a translation table between user color indices, which range from 0 to !D.TABLE_SIZE, and the actual pixel values allocated from the X server. Normally, the user need not be concerned with this translation table, but it is available using the statement:

DEVICE, TRANSLATION=T

This statement stores the current translation table, a 256 element byte vector, in the variable T. Element zero of the vector contains the value pixel allocated for the zeroth color in the IDL colormap, and so forth. In the case of a private colormap, each element of the translation vector contains it's own index value, because private colormaps start at zero and are contiguous.

The translation table may be bypassed, allowing direct access to the display's color indices, by setting the BYPASS_TRANSLATION keyword in the DEVICE procedure.

DEVICE, /BYPASS_TRANSLATION

Translation can be reestablished by setting the keyword to zero:

DEVICE, BYPASS_TRANSLATION=0

When a private or static (read-only) color table is initialized, the bypass flag is cleared. It is set when initializing a shared color table.

Using Pixmaps

X Windows can direct graphics to windows or pixmaps. Windows are the usual windows that appear on the screen and contain graphics. Pixmaps are invisible graphics memory contained in the server. Drawing to a window produces a viewable result, while drawing to a pixmap simply updates the pixmap memory.

Pixmaps are useful because it is possible to write graphics to a pixmap and then copy the contents of the pixmap to a window where it can be viewed. Furthermore, this copy operation is very fast because it happens entirely within the server. Provided enough pixmap memory is available, this technique works very well for animating a series of images by placing the images into pixmap memory and then sequentially copying them to a visible window.

To create a pixmap, use the PIXMAP keyword with the WINDOW procedure. For example, to create a square pixmap with 128 pixels per side as IDL window 1, use the command:

WINDOW, 1, /PIXMAP, XSIZE=128, YSIZE=128

Once they are created, pixmaps are treated just like normal windows, although some operations (WSHOW for instance) don't do anything useful when applied to a pixmap.

The following procedure shows how animation can be done using pixmap memory. It uses a series of 15 heart images taken from the file abnorm.dat. This file is supplied with all IDL distributions in the data subdirectory of the images examples of the main IDL directory. It creates a pixmap and writes the heart images to it. It then uses the COPY keyword of the DEVICE procedure to copy the images to a visible window. Pressing any key causes the display process to halt:

PRO animate_heart	Animate heart series.

OPENR, u, FILEPATH('abnorm.dat', SUBDIR='images'), $

       /GET_LUN	Open the file containing the images.

frame = ASSOC(u, BYTARR(64,64))
Associate a file variable with the file. Each heart image is 64x64 pixels.

WINDOW, pixwin, /PIXMAP, XSIZE = 512, YSIZE = 512, /FREE
Window pixwin is a pixmap which is 4 images tall and 4 images wide. The images will be placed in this pixmap.

FOR i=0, 15-1 DO TV, REBIN(SMOOTH(frame(i),3), 128, 128),i
Write each image to the pixmap. SMOOTH is used to improve the appearance of each image and REBIN is used to enlarge/shrink each image to the final display size.

FREE_LUN, u	Close the image file and free the file unit.

WINDOW, win, XSIZE = 128, YSIZE=128, TITLE='Heart', /FREE
Window win is a visible window. It will be used to display the animated heart cycle.

i = 0L	Current frame number.

WHILE GET_KBRD(0) EQ '' DO BEGIN
Display frames until any key is pressed.

x = (i mod 4) * 128 & y = 384 - (i/4) * 128
Compute x and y locations of pixmap image's lower left corner.

DEVICE, COPY = [x, y, 128, 128, 0, 0, pixwin]
Copy the next image from the pixmap to the visible window.

i = (i + 1) MOD 15	Keep track of total frame count.

ENDWHILE

END

Animation sequences with more and/or larger images can be made. See the documentation for the XANIMATE procedure, which is a more generalized embodiment of the above procedure.

Note: Some X Windows servers will refuse to create a pixmap that is larger than the physical screen in either dimension.

Setting the X Window Defaults

You can set the initial default value of the following parameters by setting resources in the file .Xdefaults (Unix), or DECW$SM_GENERAL.DAT (VMS) in your home directory as follows:

Resource Name	Description
idl.colors	The number of colors used by IDL.
idl.gr_depth	The depth, in bits, of the visual used by IDL.
idl.retain	The default setting for the retain parameter: 0=none, 1= by server, 2=by IDL.
idl.gr_visual	The type of visual: StaticGray, GrayScale, StaticColor, PseudoColor, TrueColor, or DirectColor.
idl.olh_text_width	The width for the online help window.
idl.olh_text_height	The height for the online help window.
Table 3.16 IDL/ X Window Defaults

For example, to set the default visual to PseudoColor, and to allocate 100 colors, insert the following lines in your defaults file:

idl.gr_visual: PseudoColor

idl.colors: 100


The Z-Buffer Device

The IDL Z-buffer device is a pseudo device that draws 2D or 3D graphics in a buffer contained in memory. This driver implements the classic Z buffer algorithm for hidden surface removal. Although primarily used for 3D graphics, the Z-buffer driver can be used to create 2D objects in a frame buffer in memory. The resolution of this device can be set by the user.

All of the IDL plotting and graphics routines work with the Z-buffer device driver. In addition, the POLYFILL procedure has a few keyword parameters, allowing Gouraud shading and warping images over 3D polygons, that are only effective when used with the Z-buffer.

When used for 3D graphics, two buffers are present: an 8-bit-deep frame buffer that contains the picture; and a 16-bit-deep Z-buffer of the same resolution, containing the z-value of the visible surface of each pixel. The Z-buffer is initialized to the depth at the back of the viewing volume. When objects are drawn, the z-value of each pixel is compared with the value at the same location in the Z-buffer, and if the z-value is greater (closer to the viewer), the new pixel is written in the frame buffer and the Z-buffer is updated with the new z-value.

The Z-buffer device is a "pseudo device" in that drawing commands update buffers in memory rather than sending commands to a physical device or file. The TVRD function reads the contents of either buffer to an IDL array. This array may then be further processed, written to a file, or output to a raster-based graphics output device.

The Z-buffer driver can be used for 2D graphics by disabling the depth computations.

To use the Z-buffer as the current graphics device, issue the IDL command:

SET_PLOT,'Z'

Once the Z-buffer driver is enabled the DEVICE procedure is used to control its actions, as described below.

Use the statement:

HELP, /DEVICE

to view the current state of the Z-buffer driver and the amount of memory used for the buffers.

Reading and Writing Buffers

The contents of both buffers are directly accessed by the TV and TVRD routines. The frame buffer that contains the picture is 8 bits deep and is accessed as channel 0. The Z depth buffer contains 16 bit integers and is accessed as channel 1. Always use CHANNEL=1 and set the keyword WORDS when reading or writing the depth buffer.

The normal procedure is to set the graphics device to "Z", draw the objects, read the frame buffer, and then select another graphics device and write the image. For example, to create an image with the Z-buffer driver and then display it on an X-Window display:

SET_PLOT,'Z'	Select Z-buffer device.

... ... ...	Write objects to the frame buffer using normal graphics routines, e.g. PLOT, SURFACE, POLYFILL.

a=TVRD()	Read back the entire frame buffer.

SET_PLOT,'X'	Select X Windows.

TV, a	Display the contents of the frame buffer.

To read the depth values in the Z-buffer, use the command:

a = TVRD(CHANNEL=1, /WORDS)

To write the depth values, use the command:

TV, a, /WORDS, CHANNEL=1

The TV, TVSCL, and TVRD routines write or read pixels directly to a rectangular area of the designated buffer without affecting the other buffer.

Z-Axis Scaling

The values in the depth buffer are short integers, scaled from -32765 to +32765, corresponding to normalized Z-coordinate values of 0.0 to 1.0.

Polyfill Procedure

The following POLYFILL keywords are active only with the Z-buffer device: IMAGE_COORDINATES, IMAGE_INTERPOLATE, and TRANSPARENT. These parameters allow images, specified via the PATTERN keyword, to be warped over 2D and 3D polygons.

The IMAGE_COORDINATES keyword contains a 2 by N array containing the image space coordinates that correspond to each of the N vertices of the polygon. The IMAGE_INTERPOLATE keyword indicates that bilinear interpolation is to be used, rather than the default nearest neighbor sampling. Pixels less than the value of TRANSPARENT are not drawn, simulating transparency. For Gouraud shading of polygons, the COLOR keyword can contain an array specifying the color index for each polygon vertex.

Examples Using the Z-Buffer

This example forms a Bessel function, draws its shaded surface and overlays its contour, using the Z-buffer as shown in the figure below. The final output is directed to PostScript.

SET_PLOT, 'Z'	Select the Z-buffer.

n = 50	Size of array for Bessel.

a = BESELJ(SHIFT(DIST(n), n/2, n/2)/2, 0)
Make the Bessel function.

SHADE_SURF, a, /SAVE, COLOR=1, BACKGROUND=255
Draw the surface, label axes in black, background in white.

nlev = 8	Number of contour levels.

CONTOUR, a, /OVERPLOT, ZVALUE=.6, /T3D, $

         LEVELS=FINDGEN(nlev)*1.5/nlev-.5, COLOR=1
Make the Contour at normalized Z=.6.

b=TVRD()	Read image.

SET_PLOT, 'PS'	Select PostScript output.

TV, b	Output the image.

DEVICE, /CLOSE	Close the new PostScript file.

The following example warps an image to a cube as shown in the figure below. The lower two quadrants of the image are warped to the front two faces of the cube. The upper-right quadrant is warped to the top face of the cube. The image is held in the array a, with dimensions nx by ny.

SET_PLOT, 'Z'	Select the Z-buffer.

ERASE, 255	Make a white background for final output to PostScript.

SCALE3, XRANGE=[0,1], YRANGE=[0,1], ZRANGE=[0,1]
Establish 3D scaling as (0,1) cube.

verts = [[0,0,0], [1,0,0], [1,1,0], [0,1,0], $

        [0,0,1], [1,0,1], [1,1,1], [0,1,1]]
Define vertices of cube. Vertices 0-3 are bottom, 4-7 are top.

POLYFILL, verts(*, [3,0,4,7]), /T3D, PATTERN=a, $

     IMAGE_COORD=[[0,0], [nx/2,0], [nx/2,ny/2], [0,ny/2]]
Fill lower left face.

POLYFILL, verts(*, [0,1,5,4]), /T3D, PATTERN=a, $

          IMAGE_COORD=[[nx/2,0], [nx-1,0], $

          [nx-1,ny/2], [nx/2,ny/2]]
Lower right face.

POLYFILL, verts(*, [4,5,6,7]), /T3D, PATTERN=a, $

          IMAGE_COORD = [[nx/2,ny/2], [nx-1,ny/2], $

          [nx-1,ny-1], [nx/2,ny-1]]
Top face.

PLOTS, verts(*, [0,4]), /T3D, COLOR=0
Draw edges of cube in black.

PLOTS, verts(*, [4,5,6,7,4]), /T3D, COLOR=0
Edges of top face.

The image is then output to PostScript as in the previous example.


Reporting Bugs
4	Reporting Bugs

Chapter Overview

We strive to make IDL as reliable and bug free as possible. However, no program with the size and complexity of IDL is perfect, and bugs do surface. When you encounter a problem with IDL, the manner in which you report it has a large bearing on how well and quickly we can fix it. This appendix is intended to help you report the bug in a way that will help us correct the problem rapidly.


Topics in Reporting Bugs Chapter
Reporting Bugs

This chapter includes information on reporting IDL bugs to Research Systems, Inc.

Topics Covered:

Background Information

Double Check

Describing The Problem

Reproducibility

Simplify the Problem

Bugs with Dynamic Loading

Sending Data with Your Bug Report

Contact Us

Jump backward to Remote Procedure Calls

Jump to IDL Routines


Background Information

When a bug is reported and verified, we correct it in a later release. Sometimes, a bug only occurs when running on a certain machine, operating system, or graphics device. For these reasons, we need to know the following facts when you report a bug:

•	Your IDL site number.

•	The version of IDL you are running.

•	The type of machine it is running on.

•	The operating system version it is running under.

•	The type and version of your windowing system.

•	The graphics device, if the problem involves graphics.

The site number is assigned by us when you purchase IDL. The IDL version, site number, and type of machine are printed when IDL is started. For example:

IDL. Version 3.0 - (hp-ux hp9000s300).
Copyright 1989-1992, Research Systems, Inc.
All rights reserved. Unauthorized reproduction prohibited.
Site: 177.
Licensed for use by: ACME Datawhack Corp.

is the startup announcement from IDL version 3.0 under HP-UX on a Hewlett-Packard 9000 series 300 machine at site number 177.

Under Unix, the version of the operating system can usually be found in the file /etc/motd. It is also printed when the machine boots. In any event, your system administrator should know.

Under VMS, the DCL statement:

write sys$output f$getsyi("version")

will give you the operating system version.


Double Check

Before reporting a bug, you should always ask yourself "Is it really a bug?". Sometimes, it is a simple matter of misinterpreting what is supposed to happen. Double check with the manual or a local expert.

If you cannot determine what should happen in a given situation by consulting the reference manual, the manual needs to be improved on that topic. Please let us know if you feel that the manual was vague or unclear on a subject.

It is often obvious whether something is a bug or not. If IDL crashes, it is a genuine bug. If however, it draws a plot differently than you would expect or desire, it might be a bug, but it is certainly less obvious. Another question to ask is whether the problem lies within IDL, or with the system running IDL. Is your system properly configured with enough virtual memory and sufficient operating system quotas? Does the system seem stable and is everything else working normally?


Describing The Problem

When describing the problem, it is important to use precise language. Vague terms like "crashes", "blows up", and "fails" are open to many interpretations. Does it really crash IDL and leave you looking at an operating system prompt? This would be our interpretation of "crash". Perhaps, however, it just issues an unexpected error message and gives another prompt. What is really meant by a term like "fails"?

It is also important to separate concrete facts from conjecture about underlying causes. For example, a statement such as "IDL dumps core when allocating dynamic memory." is not nearly as useful as one like "IDL dumps core when I execute the following statements. I think it might be trying to get dynamic memory". The second version tells us exactly what happened. The opinion about what was going on when the problem surfaced is also useful to us, but it helps to have it clearly labeled as such.


Reproducibility

Intermittent bugs are by far the hardest kind to fix. In general, if we can't make it happen on our machine, we can't fix it. It is therefore far more likely that we can help you if you can tell us a sequence of IDL statements that cause the problem to happen. Naturally, there are degrees of reproducibility. Situations where a certain sequence of statements causes the bug 1 time in 3 tries are fairly likely to be fixable. Situations where the bug happens once every few months and no one is sure what triggered it are almost hopeless.


Simplify the Problem

When reporting a bug, it is important to give us the shortest possible series of IDL statements that cause it. The longer and more intricate an example, the less likely it is that we can help. Sometimes a single statement triggers the bug. Often though, the problem surfaces when writing a larger system of inter-related procedures and functions. Such a situation must be simplified before we can tackle it. Take the following steps to simplify your problem:

•	Copy the procedure and function files that are involved to a scratch second copy. Never modify your only copy!

•	Eliminate everything that is not involved in demonstrating the bug. Don't do this all at once. Instead, do it in a series of slow careful steps. Between each step, stop and run IDL on the result to ensure that the bug still appears.

•	If a simplification causes the bug to disappear, restore the statements involved and look for other things to eliminate.

•	If the problem does not involve file Input/Output, strive to eliminate all file I/O statements. Use IDL routines to generate a dummy data set, rather than including your own data. If your bug report does not involve I/O, it will be much easier for us to reproduce. If you have to provide us with a copy of your data, things become more complicated.

On the other hand, if the bug involves file Input/Output, attempt to determine if the problem only happens with a certain file, or with any data. If you are running under VMS, check the file organization using the DCL DIRECTORY/FULL command, and include this information in your report.

The end result of such simplification should be a small number of IDL statements that demonstrate the problem.


Bugs with Dynamic Loading

Under some operating systems, the CALL_EXTERNAL and LINKIMAGE system routines allow you to dynamically load routines written in other languages into IDL. This is a very powerful technique for extending IDL, but it is considerably more difficult than simply writing IDL statements. At this level, the programmer is underneath the user level shell of IDL and is not protected from small programming errors that can corrupt data, give incorrect results, or even crash IDL. In such situations, the burden of proving that a bug is within IDL and not the dynamically loaded code is entirely the programmer's.

Although it is certainly true that a bug in this situation can be within IDL, it is very important that you exhaust all other possibilities before reporting a bug. If you decide that you need to report a bug, the comments above on simplifying things are even more important than usual. If you send us a small example that tickles the bug, we can respond quickly with a correction or advice. Otherwise, we may not even know where to begin.


Sending Data with Your Bug Report

If the statements required to reproduce the bug are more than a few lines or require data files, we will need you to send them to us on magnetic media or via email. Call us for details.


Contact Us

To report a bug, contact us at the following addresses.

Mail

Research Systems, Inc.
2995 Wilderness Place, Suite 203
Boulder, Colorado 80301

Telephone

(303) 786-9900 (Voice)
(303) 786-9909 (Fax)
(303) 786-9930 ext. 320 (IDL technical support direct line)

Electronic Mail

support@rsinc.com

Jump backward to Remote Procedure Calls

Jump to IDL Routines


What's New in IDL version 4.0.1

Click on a topic or use the browse buttons to read about new features in IDL version 4.0.1.

Platforms Supported in this Release
New and Modified Routines in IDL 4.0.1
A Note about Widget Sizing
 Online Help Changes
 Callable IDL
IDL for Windows Changes
Bugs Fixed in this Release


Platforms Supported in this Release

IDL supports the following OS versions (including later versions):

•	Digital Equipment Corporation VAX VMS 5.5-2 with Motif 1.2. IDL is no longer available for VMS 5.1. Note: IDL installed on VMS versions between 5.5-2 and 6.0 needs the DEC C Run Time Components kit installed before IDl will run properly. See "Important Note for VAX IDL Installers" in the README.TXT file.

•	Risc Ultrix 4.4 with Motif 1.2. This is the final release of IDL for Ultrix.

•	Alpha AXP VMS Version 6.1

•	OSF/1 Version 3.2

•	IBM RS/6000 AIX Version 3.2

•	Sun Solaris Version 2.3

•	SunOS Version 4.1.3

•	Silicon Graphics Inc. IRIX Version 5.2

•	Hewlett Packard Corporation HP/UX Version 9.01

•	Linux: IDL for Linux was built under Linux 1.2.8 using Slackware version 2.2. We also ship a statically compiled version that should work with older kernels.

•	Intel x86 Microsoft Windows NT Version 3.5, Microsoft Windows Version 3.1

•	Apple Macintosh and PowerMacintosh MacOS System 7.0.1 or higher

•	Convex: IDL is no longer available for Convex computers.

Note also that all OpenLook support has been removed from IDL's X-Windows code. It is no longer possible for us to support Sun's OpenLook.


New and Modified Routines in IDL 4.0.1

Widget Features

New TLB_KILL_REQUEST_EVENTS keyword to WIDGET_BASE, WIDGET_CONTROL, WIDGET_INFO. Use this keyword to send an event when the user attempts to kill the widget.

New DYNAMIC_RESIZE keyword to  WIDGET_CONTROL, WIDGET_BUTTON, WIDGET_DROPLIST, WIDGET_INFO, WIDGET_LABEL. Controls sizing behavior for some widgets. In this release, only Motif and Macintosh widgets support this keyword. Windows widgets accept the keywords, but may not act on them.

New UPDATE keyword to WIDGET_CONTROL, WIDGET_INFO. Use this keyword to control screen updates when making changes to previously-realized widgets. In this release, only Motif widgets obey this keyword. Windows and Macintosh widgets accept the keywords, but may not act on them.

Online Help Features

New MK_HTML_HELP routine for creating HTML help files from user routines.

New user-level routine for invoking hypertext help viewer, ONLINE_HELP.

Mapping Features

In addition to a number of map-related bug fixes, some modifications have been made to the files that contain the low- and high-resolution map databases. Changes include:

•	The largest 104 of 256 islands off of western Canada are now included in the high-resolution map database. These islands are the ones that contain more than 40 points in the CIA World Database.

•	Removed a number of spurious triangles in the areas of Micronesia and Antarctica. The Antarctic triangles were the result of inconsistently including the winter ice shelves.

•	Small gaps in the U.S./Canada and U.S./Mexico borders have been fixed in both the low- and high-resolution map databases.

Files in the distribution that have changed as a result are:

resource/maps/high/phigh.ndx
resource/maps/high/phigh.dat
resource/maps/high/bhigh.ndx
resource/maps/high/bhigh.dat
resource/maps/low/plow.ndx
resource/maps/low/plow.dat
resource/maps/low/blow.ndx
resource/maps/low/blow.dat
resource/maps/low/blow.dat


Widget Sizing
A Note about Widget Sizing

Some users of previous versions of IDL have been confused by changes made to the behavior of widgets in IDL version 4.0. This release note addresses their concerns, explains widget sizing in detail, and describes new IDL 4.0.1 widget functionality that can improve the performance of widget applications. The following information is also duplicated in a new section of the Widgets chapter of the IDL User's Guide, "Widget Sizing".

Widget Geometry Terms and Concepts

Widget geometry, or the size and layout of widgets, is determined by many interrelated factors. In the following discussion, the following terms are used:

•	Geometry: The size and position of a widget.

•	Natural Size: The natural, or implicit, size of a widget is the size a widget has if no external constraints are placed on it. For example, a label widget has a natural size that is determined by the size of the text it is displaying and space for margins. These values are influenced by such things as the size of the font being displayed and characteristics of the low-level (i.e., operating-system level) widget or control used to implement the IDL widget.

•	Explicit Size: The explicit, or user-specified, size of a widget is the size set when an IDL programmer specifies one of the size keywords to an IDL widget creation function or WIDGET_CONTROL.

How Widget Geometry is Determined

IDL uses the following rules to determine the geometry of a widget:

•	The explicit size of a widget, if one is specified, takes precedence over the natural size. That is, the user-specified size is used if available.

•	If an explicit size is not specified, the natural size of the widget —at the time the widget is realized—is used. Once realized, the size of a widget does not automatically change when the value of the widget changes, unless the widget's dynamic resize property has been set. Dynamic resizing is discussed in more detail below. Note that any realized widget can be made to change its size by calling WIDGET_CONTROL with any of the sizing keywords.

•	Children of a "bulletin board" base (i.e., a base that was created without setting the COLUMN or ROW keywords) have an offset of (0,0) unless an offset is explicitly specified via the XOFFSET or YOFFSET keywords.

•	The offset keywords to children of ROW or COLUMN bases are ignored and IDL calculates the offsets lay the children out in a grid. This calculation can be influenced by setting any of the ALIGN or BASE_ALIGN keywords when the widgets are created.

Dynamic Resizing

In IDL 4.0.1, realized widgets, by default, do not automatically resize themselves when their values change. This is true whether the widget was created with an explicit size or the widget was allowed to size itself naturally. This behavior makes it easy to create widget layouts that don't change size too frequently or "flicker" due to small changes in a widget's natural size.

This default behavior can be changed for label, button, and droplist widgets. Set the DYNAMIC_RESIZE keyword to WIDGET_LABEL, WIDGET_BUTTON, or WIDGET_DROPLIST to make a widget that automatically resizes itself when its value changes. Note that the XSIZE and YSIZE keywords should not be used with DYNAMIC_RESIZE. Setting explicit sizing values overrides the dynamic resize property and creates a widget that will not resize itself.

Preventing Layout Flicker

After a widget hierarchy has been realized, adding or destroying widgets in that hierarchy causes IDL to recalculate and set new geometries for every widget in the hierarchy. When a number of widgets are added or destroyed, these calculations occur between each change to the hierarchy, resulting in unpleasant screen "flashing" as the user sees a brief display of each intermediate widget configuration. This behavior can be eliminated by using the UPDATE keyword to WIDGET_CONTROL.

The top level base of every widget hierarchy has an UPDATE attribute that determines whether or not changes to the hierarchy are displayed on screen. Setting UPDATE to 0 turns off immediate updates and allows you to make a large number of changes to a widget hierarchy without updating the screen after each change. After all of your changes have been made, setting UPDATE to 1 causes the final widget configuration to be displayed on screen.

For example, consider the following program that realizes an unmapped base, then adds 200 button widgets to the previously-realized base:

b = WIDGET_BASE(/COLUMN, XSIZE=400, YSIZE=400, MAP=0)
WIDGET_CONTROL, b, /REALIZE
FOR i = 0, 200 DO button = WIDGET_BUTTON(b, VALUE=STRING(i))
WIDGET_CONTROL, b, /MAP
END

This program takes over 50 seconds to run on an HP 9000/720 workstation. If the base had been mapped, the user would see the base "flashing" as each button was added to the base. Altering the example to use the UPDATE keyword reduces the execution time to 0.7 seconds:

b = WIDGET_BASE(/COLUMN, XSIZE=400, YSIZE=400, MAP=0)
WIDGET_CONTROL, b, /REALIZE, UPDATE=0
FOR i = 0, 200 DO button = WIDGET_BUTTON(b, VALUE=STRING(i))
WIDGET_CONTROL, b, /MAP, /UPDATE
END


Online Help Changes

New Viewer for Unix/VMS Platforms

IDL 4.0.1 for Unix and VMS contains a new version of the hypertext help viewer. This viewer is much faster than the previous version and fixes a number of display problems. It also has new, easier-to-use printer setup features. Information about the printer setup features can be seen by selecting "Printer Help" from the viewer's File menu when the IDL help file is displayed. Use the "Back" or "History" button to return to topics in the IDL help file. On some platforms, the HyperHelp viewer does not have the "Printer Help" option available. In these cases, use the "Open" option from the File menu to open the hoh.hlp file, then click the "Configuring a Printer" link.

Because of extensive changes to the Unix/VMS viewer in this release, those platforms also include Bristol Technology's own viewer documentation, in the file hoh.hlp, found in the help/hyperhelp subdirectory. This help file is accessible by selecting "Viewer Help" from the viewer's Help menu when the IDL help file is displayed. Use the "Back" or "History" button to return to topics in the IDL help file. On some platforms, the HyperHelp viewer does not have the "Viewer Help" option available. In these cases, use the "Open" option from the File menu to open the hoh.hlp file.

New Online Help File

A new IDL online help file (idl.hlp) is shipped with this version of IDL. It contains documentation for features new to IDL 4.0.1 and a number of corrections and modifications. Note that since some new topics have been added to the help system, existing bookmarks and annotations may be in the wrong locations when used with this new idl.hlp file. See the topic, "IDL's Online Help System" for more information about the hypertext help viewers.

Note that new hardcopy versions of the IDL manuals are not available for the 4.0.1 release.

Extending IDL's Online Help System

A number of users expressed confusion about changes to IDL's online help system in version 4.0. A new section in the "Interactive Support" chapter of the IDL User's Guide describes various ways to create online help for user-written routines. It also describes how to use the previous IDL help system with legacy  .help files. See the topic, "Extending IDL's Online Help System".

DOC_LIBRARY Errata

The IDL documentation header template, known as lib_template.pro in previous versions of IDL, had both its name and location changed in IDL version 4.0. Unfortunately, the information in the version 4 hardcopy manuals is incorrect. The  correct name and location for this file is: template.pro located in the general subdirectory of the examples subdirectory of the IDL distribution. The information has been corrected in this version of the online help.


Callable IDL

IDL can be called from other applications using Windows DLL, Macintosh AppleScript, or Unix Sharable Object Library techniques. Note that while using AppleScript to interact with IDL is relatively straightforward, calling the IDL libraries under Windows or Unix requires extensive knowledge of both IDL and the operating system.

If you have installed the "External Linking Support" option, a hypertext help file for the Advanced Development Guide, named adg.hlp, can be found in the help/hyperhelp subdirectory (for Unix and VMS platforms) or the help subdirectory (for Windows and Macintosh) of the IDL distribution. To view this file, select "Open" from the help viewer's File menu and select the adg.hlp file. Use the "Back" or "History" buttons to return to topics in the IDL help file.

For availability of a hardcopy version of the Advanced Development Guide, contact Research Systems or your IDL distributor.

Alternatives to Calling the IDL Libraries

In many cases, external code can be integrated with IDL without the need to call the IDL libraries directly. One of the following options may suit your application.

•	On the Macintosh, the only way to call IDL from an external application is via AppleScript. For more information on using AppleScript to interact with IDL, see "DO_APPLE_SCRIPT" on page 1-248 of the IDL Reference Guide.

•	Under Unix, IDL can be configured as a server for remote procedure calls. For information, see "Remote Procedure Calls" on page 24-1 of the IDL User's Guide. Using IDL as an RPC server may alleviate the need to call the IDL libraries directly.

•	IDL supports calls from IDL to external programs. For information about calling external programs from within IDL, see "CALL_EXTERNAL" on page 1-51 of the IDL Reference Guide. CALL_EXTERNAL is available on all platforms.

•	On computers that support dynamic linking of object modules, IDL can link routines written in other languages directly into IDL's internal symbol table. For information, see "LINKIMAGE" on page 1-529 of the IDL Reference Guide.


IDL for Windows Changes

SPAWN

Under Windows (but not under Windows NT), the SPAWN command calls a PIF file named idlspawn.pif so that spawned programs "block" instead of immediately returning to IDL for Windows. This file is installed automatically in the WINDOWS directory. You can change any options you wish in idlspawn.pif file, with the exception of the Program Filename ( COMMAND.COM) and the Window Title (IDL Spawned Process).


Bugs Fixed in this Release

The file  README.TXT, found in the main IDL directory (idl_4), contains a list of bugs fixed in this version of IDL.


What's New in IDL version 4.0
What was New in IDL version 4.0

Click on a topic or use the browse buttons to read about new features in IDL version 4.0.

Changes to IDL Directory Tree
IDL Documentation Changes
IDL Language Enhancements
Miscellaneous New Features
New Keywords to Existing Routines
 Widget Enhancements
 Mathematics Improvements
IDL Statistics Library Revisions
IDL for Macintosh Enhancements
IDL for Windows Enhancements


Changes to IDL Directory Tree

New Library File Directory Structure

All IDL library routines written in IDL (previously known as the IDL Users' Library) are now documented in the IDL Reference Guide. Also, the .pro files for those routines can all be found in a single directory, the lib subdirectory of the main IDL directory.

Library routines that are outdated and no longer supported can be found in the obsolete  subdirectory of lib. Any routines found in this directory are unsupported by Research Systems and will not be changed or enhanced. Research Systems does not guarantee that any of these routines will be included with future releases of IDL. In most cases, obsolete routines have been replaced by superior, supported routines. However, if you need any of the obsolete routines for compatibility with existing code, we suggest that you keep copies of the necessary routines in your own library directories (i.e., directories that are not part of the IDL directory tree).

Examples and Demos

A number of IDL examples have been removed from XDEMO (and DEMO) and are now accessible via their own IDL command—EXAMPLES. Source code for these examples can be found in the general subdirectory of the examples subdirectory of the main IDL directory.


IDL Documentation Changes

New Manual Format

The main IDL documentation set now consists of the IDL User's Guide, a two-volume IDL Reference Guide, IDL Basics, and Callable IDL documentation. Narrative information is found in the IDL User's Guide (which now includes information from the old IDL Mathematics Guide, Scientific Data Formats, Statistics Library Addendum, and Remote Procedure Calls books). Library routines written in IDL (including the new statistics library) are now fully documented in the IDL Reference Guide as well as in the online help.

Hypertext Help

The complete text of the IDL User's Guide and IDL Reference Guide is available online. Enter a question mark (?) at the IDL command line or select the "Help" option from the Help menu to display this new online help system. Note that the system may take a few minutes to start on Unix systems, depending upon the speed of your machine and load on the system. Jump to more information about IDL's Online Help System.


IDL Language Enhancements

Forward Declaration of Function Names

IDL programmers can now use "forward declaration" of function names. The FORWARD_FUNCTION statement can be used to define function names before those functions are actually called, so that they won't be interpreted as variable names. Jump to more information about  Forward Function Definition.

Callable IDL

Callable IDL lets you call IDL from other applications using Windows DLL, Macintosh AppleScript, or Unix Sharable Object Library techniques.

Improved Debugging Support

IDL now allows debugging of callback routines such as widget event handlers. New debugging features include:

•	Setting the ONCE keyword to BREAKPOINT creates a breakpoint that is automatically cleared when hit.

•	Setting BREAKPOINT,AFTER=n creates a breakpoint that fires only after being hit n times.

•	New executive commands for debugging: .COMPILE [File1, ..., Filen], .OUT, .STEPOVER [n] or .SO [n], and .TRACE.

These features are also available interactively from the built-in IDL debugger/editors.

Double-Precision Complex Data Type

A new double-precision, complex data type has been added to IDL. The new type is called DCOMPLEX. Data types are described in more detail in Constants and Variables. Three new routines can be used to create DCOMPLEX variables and arrays: DCINDGEN, DCOMPLEX, and DCOMPLEXARR. MAKE_ARRAY also supports the DCOMPLEX type. The COMPLEXROUND, COND, CONJ, FX_ROOT, IMAGINARY, and NORM routines now accept and return the DCOMPLEX data type. Other routines that work with DCOMPLEX data include FFT, FZ_ROOTS, and HQR. In general, all IDL operators and routines work with the DCOMPLEX type to varying degrees.


Miscellaneous New Features

Contour Plots from Polar Data

POLAR_CONTOUR produces a contour plot from data in polar coordinates. Both regular and irregular polar grids are supported.

High-Resolution Map Database

A high-resolution map database can optionally be installed when you install IDL. THe HIRES keyword to MAP_CONTINENTS and MAP_SET provides access to this high-resolution outline set.

Image Warping to Maps

MAP_PATCH warps a set of regularly gridded data to a map using image space interpolation. This routine is similar to MAP_IMAGE, which operates in object space.

Compile Routines using Procedure Calls

The RESOLVE_ALL procedure allows you to compile all uncompiled routines that are called in any already-compiled procedures or functions. The  RESOLVE_ROUTINE procedure can be used compile procedures or functions from inside another procedure.

Import/Export SYLK Spreadsheet Files

The READ_SYLK and WRITE_SYLK routines allow IDL to import and export generic spreadsheet and database tab-delimited data files in the SYLK format. This format can also be used with databases and spreadsheets such as Lotus 123, Excel, Quatro Pro, DBASE, and FoxPro.

Scientific Data Formats

IDL now supports CDF version 2.5, NetCDF version 2.3.2, and HDF version 3.3r4. Many new Scientific Data Format routines have also been added. Jump to lists of CDF Routines, HDF Routines, or NetCDF Routines.

Spherical Gridding

IDL now supports gridding and interpolation over the surface of a sphere. A new library function, SPH_SCAT, encapsulates the process into a single call. TRIANGULATE and TRIGRID accept new keywords that enable spherical gridding. This feature is not present in Ultrix versions of IDL.

3D Box Plot

The PLOT_3DBOX procedure creates a 3D line plot with projections of the data onto the "walls" of the plot.


New Keywords to Existing Routines

CONTOUR supports a number of new keywords: Setting CELL_FILL fills each cell on an individual basis, often resulting in better filled contour results. The PATH_INFO, and PATH_XY keywords can be used to capture path information for the contours. The TRIANGULATION keyword can be used to contour irregularly-gridded data without calling TRIGRID.

CONVOL has new EDGE_WRAP and EDGE_TRUNCATE keywords for controlling the way in which edge points are handled.

DILATE and ERODE now work with arrays from one to three dimensions.

FFT accepts the new INVERSE keyword. Setting this keyword is equivalent to setting the Direction argument to 1.

MAP_CONTINENTS has new keywords for new features included in both the standard and high-resolution map databases: COASTS, COUNTRIES, and RIVERS. Setting the new HIRES keyword enables the high-resolution map database. Setting FILL_CONTINENTS produces filled continent outlines. Fill characteristics can be controlled with COLOR, SPACING, and ORIENTATION keywords.

MAP_SET now accepts the ISOTROPIC keyword for making maps that have the same scale in X and Y directions. It also accepts the HIRES keyword for enabling the high-resolution map database.

PLOT accepts new XLOG, YLOG, and ZLOG keywords for plotting with logarithmic AXES. Setting these keywords is synonymous with setting the now-obsolete [XYZ]TYPE keyword. This keyword also makes the PLOT_IO, PLOT_OI, and PLOT_OO routines obsolete. Calling these routines still works, but they are now undocumented. In addition, the XLOG, YLOG, and ZLOG routines work with AXIS, CONTOUR, SHADE_SURF, and SURFACE, but the keywords are currently only documented in the online help.

RANDOMN now uses the Box-Muller method which provides a better approximation to the normal distribution at the tails of the distribution. The new method is also more than five times faster than the previous method.

RIEMANN has CENTER keyword for specifying the center of rotation of the image.

SMOOTH has the new EDGE_TRUNCTATE keyword for decreasing artifacts near edges.

TRIANGULATE and TRIGRID accept the new DEGREES, FVALUE, and SPHERE keywords for performing spherical gridding.

TRIGRID has two new keywords for missing data, MAX_VALUE and MIN_VALUE. Another new keyword, INPUT, allows multiple calls to TRIGRID.


Widget Enhancements

New Widget Routines

The WIDGET_DROPLIST function creates droplist widgets (buttons that reveal pulldown menus).

The WIDGET_MESSAGE function creates modal message dialogs.

New Keywords to Existing Widget Routines

New ALIGN_LEFT, ALIGN_CENTER, and ALIGN_RIGHT alignment keywords for WIDGET_BUTTON and WIDGET_LABEL allow justification of text.

HELP and SEPARATOR keywords to  WIDGET_BUTTON for controlling the appearance of buttons on menubars and in pulldown menus.

WRAP keyword to WIDGET_TEXT enables text wrapping in multi-line or scrolling text widgets.

The following keywords have been added to all widget creation routines: TRACKING_EVENTS causes WIDGET_TRACKING events to be issued for the widget whenever the mouse pointer enters or leaves the region covered by that widget. SCR_XSIZE and SCR_YSIZE set the size of widgets in pixels.

New keywords to WIDGET_CONTROL: TRACKING_EVENTS, SCR_XSIZE, SCR_YSIZE, XSIZE/YSIZE/XOFFSET/YOFFSET can be used to control all widget types, DRAW_XSIZE, DRAW_YSIZE, and SET_DROPLIST_SELECT.

New keywords to WIDGET_INFO: GEOMETRY, NAME, TRACKING_EVENTS, DROPLIST_NUMBER, DROPLIST_SELECT


Mathematics Improvements

Double-Precision Complex Data Type

A new double-precision, complex data type has been added to IDL. The new type is called DCOMPLEX. Data types are described in more detail in Constants and Variables. Three new routines can be used to create DCOMPLEX variables and arrays: DCINDGEN, DCOMPLEX, and DCOMPLEXARR. MAKE_ARRAY also supports the DCOMPLEX type. The COMPLEXROUND, COND, CONJ, FX_ROOT, IMAGINARY, and NORM routines now accept and return the DCOMPLEX data type. Other routines that work with DCOMPLEX data include FFT, FZ_ROOTS, and HQR. In general, all IDL operators and routines work with the DCOMPLEX type to varying degrees.

Matrix Multiplication Operator

A second matrix-multiplication operator, ##, has been added to IDL. This operator performs a matrix multiply of two row vectors. The other matrix-multiply operator, #, performs a matrix multiply of two column vectors. Jump to more information about Matrix Multiplication.

Missing Data Support

The MIN_VALUE keyword to ignore data less than a given value has been added to: PLOT, OPLOT, CONTOUR, SURFACE, and SHADE_SURFACE procedures.These routines also automatically treat the IEEE floating-point value NaN (not-a-number) as missing data.

Additionally, a new NAN keyword to the MIN, MAX, TOTAL, BYTSCL, and SMOOTH routines can be set to indicate that the IEEE floating-point value NaN indicates missing data.

The FINITE function now checks for missing values.

A new system variable, !VALUES has been added to make the IEEE floating-point values Infinity and NaN accessible to the IDL programmer.  !VALUES contains the following single- and double-precision fields: F_INFINITY, F_NAN, D_INFINITY, and D_NAN.

Numerical Recipes Enhancements and Modifications

All routines previously prefixed with NR_ have been renamed. Jump to a list of Mathematics Routines, including the new statistics routines.

Note that the old routine names still work, but are undocumented. Also, some Numerical Recipes routines previously required that input arrays be in column-major format, rather than row-major (as many mathematicians expect). These routines have been modified to accept column-major arrays. The modified routines can be made to accept column-major data by simply setting the COLUMN keyword.

For example, the routine NR_ELMHES has been renamed to ELMHES. ELMHES accepts row-major input by default and column-major input (the default for NR_ELMHES) can be forced by setting the COLUMN keyword. In short:

NR_ELMHES, ... is the same as ELMHES, ..., /COLUMN

The list below shows the mathematics routines that have been renamed as well as those that now accept row-major input by default (a * indicates new row-major input format):

Old Name	New Name
NR_BETA	BETA
NR_BROYDN	BROYDEN
NR_CHOLDC	CHOLDC
NR_CHOLSL	CHOLSOL
NR_DFPMIN	DFPMIN
NR_ELMHES	ELMHES *
NR_EXPINT	EXPINT
NR_FULSTR	FULSTR
NR_HQR	HQR *
NR_INVERT	INVERT
NR_LINBCG	LINBCG
NR_LUBKSB	LUSOL *
NR_LUDCMP	LUDC *
NR_MACHAR	MACHAR
NR_MPROVE	LUMPROVE *
NR_NEWT	NEWTON
NR_POWELL	POWELL
NR_QROMB	QROMB
NR_QROMO	QROMO
NR_QSIMP	QSIMP
NR_RK4	RK4
NR_SPLINE	SPL_INT
NR_SPLINT	SPL_INTERP
NR_SPRSAB	SPRSAB
NR_SPRSAX	SPRSAX
NR_SPRSIN	SPRSIN *
NR_SVBKSB	SVSOL *
NR_SVD	SVDC *
NR_TQLI	TRIQL
NR_TRED2	TRIRED
NR_TRIDAG	TRISOL
NR_WTN	WTN *
NR_ZROOTS	FZ_ROOTS
BLK_CON now supports long indexing into vectors and minor changes in the use of intermediate variables reduced memory allocation in certain instances.

DETERM has a new keyword, CHECK, to check for singular arrays.

EIGENVEC computes eigenvectors of a nonsymmetric array. It replaces EIGEN_II which has been moved to the obsolete and is no longer supported.

INT_2D now handles 96 point transformation data and a new keyword, DOUBLE. A nested FOR loop was replaced with vector operations resulting in 200% - 400% faster execution.

INT_3D now handles 96 point transformation data and a new keyword, DOUBLE. A nested FOR loop was replaced with vector operations resulting in 200% - 800% faster execution.

LNP_TEST is a new Numerical Recipe routine that computes the Lomb Normalized Periodogram of two sample populations. This routine replaces the undocumented and untested version of NR_FASPER which has been eliminated from the IDL distribution.

LU_COMPLEX now supports sparse complex arrays, double-precision complex inputs, and the INVERSE keyword. Internal memory allocation requirements have been reduced resulting in a faster, more efficient algorithm.


IDL Statistics Library Revisions

The IDL statistics library has been replaced. Some routines were revised to make them more robust or efficient. There are also many entirely new routines that provide new statistics functionality. Jump to a list of Mathematics Routines, including the new statistics routines.

All of the replaced statistics library functions have been moved to the obsolete directory.


IDL for Macintosh Enhancements

There are many changes specific to IDL for Macintosh, including:

•	Power Macintosh native version

•	New graphics driver that supports: 1-2-4-bit monochrome, 16-24-bit color, all monitor depths (with optional dithering when screen depth < IDL depth).

•	The MAC DEVICE has been enhanced to accept the following keywords: FLOYD, THRESHOLD, TRUE_COLOR, PSEUDO_COLOR=8, DECOMPOSED, SET_WRITE_MASK, GET_WRITE_MASK, TRANSLATION.

•	Improved debugging support in editor window: visual feedback showing breakpoints, current execution line, or point of a syntax error; Debug Menu Set/Clear Breakpoint; Set Complex Breakpoint; Clear All Breakpoints. See the IDL for Macintosh book for more information.

•	Improved editor window: Undo; standard Mac search options.

•	Widget improvements: slider drag events; 3D look with better choice of default fonts; fixes to widget sizing; "smart" top-level base scrollbars.

•	AppleScript support: allows scripting of required AppleEvents; "Do Script" apple event handling; allows running of scripts generated in IDL with DO_APPLE_SCRIPT procedure

•	Separate Command input and Log windows.


IDL for Windows Enhancements

There are many new editing and debugging capabilities added to the IDL for Windows interface. There is a new editor that is much more reliable than in previous versions. New editor features include:

•	User-configurable "chroma-coded" text—IDL commands appear in one color, keywords in a second color, variables in a third, comments in a fourth, etc.

•	New search and replace.

•	Go to Line dialog.

•	8 megabyte file capacity on Windows, 2 gigabytes on Windows NT.

Added better support for 16- and 24-bit color.

There are many other changes to the IDL for Windows interface. See the IDL for Windows book for more information.


More IDL Resources

Contacting Research Systems

Research Systems Internet Resources

IDL Training

ENVI

Visible Human CD


Contacting Research Systems

Address

Research Systems, Inc.

2995 Wilderness Place

Boulder, CO 80301

Phone

303 786 9900

303 786 9930 ext. 320 (Technical support)

Fax

303 786 9909

Email

Sales inquiries: info@rsinc.com

Technical support: support@rsinc.com

Training information: training@rsinc.com


Research Systems Internet Resources

Research Systems FTP Site

Research Systems maintains an ftp site that features demo versions of our products, information from our newsletter, and user-contributed library routines. Use ftp to connect to:

ftp.rsinc.com

Log on as anonymous and give your email address as your password.

Research Systems World Wide Web Pages

There are a number of WWW sites of interest to IDL users. Use Mosaic, Netscape, or other web browser to access these sites. Research Systems maintains a page containing basic information about IDL, an IDL gallery, and links to other IDL-related pages at:

http://sslab.colorado.edu:2222/projects/IDL/idl_ssl_home.html

IDL Newsgroup

The Usenet newsgroup comp.lang.idl-pvwave is dedicated to the discussion of IDL. Users post questions and answers and share information about their own IDL projects. Note that many Research Systems employees read this newsgroup, but do not usually post messages to the group. Bug reports and technical support questions should be sent to Research Systems via phone or email. See "Contacting Research Systems".


IDL Training

Research Systems offers both standard and customized training courses for everyone from the person just starting to use IDL or ENVI to the person building large IDL applications in the commercial marketplace. Our courses are small, informal, and highly interactive. Whether you visit us in our intimate training facility in Boulder, Colorado or we come to your site, you are guaranteed to learn the specific skills you need to make your job easier. If you want to spend more time doing your work and less time learning the nuances of a new language, plan to attend one of the IDL or ENVI courses offered below.

When and Where are IDL and ENVI Courses Offered?

IDL and ENVI courses are taught on a rotating basis every month at our training facility in Boulder, Colorado. In addition, 6-8 regional training classes are offered every year at various locations in the United States, Europe, and Australia.

On-site training courses are scheduled frequently at customer sites and are usually not open to the public, although occasionally sponsoring organizations welcome the opportunity to share the cost of the course with outside users. Please let us know if you are interested in attending courses somewhere other than in Boulder, as these opportunities are usually not advertised unless we know you are interested in them.

How to Contact the IDL and ENVI Training Department

To contact us for the latest training schedule, a detailed course outline, and/or the cost of a training course, please call or send e-mail to:

IDL and ENVI Training Department

Research Systems, Inc.

2995 Wilderness Place, Suite 203

Boulder, CO 80301

Phone: 303-786-9900 (ask for "training")

Fax: 303-786-9909

E-Mail: training@rsinc.com

IDL and ENVI Course Descriptions

Learning IDL

This three-day course is specifically designed for those of you who want a quick overview of IDL's basic capabilities. We will emphasize the specific IDL commands you will need to interactively read, analyze, and display your data in formats ranging from line, surface, and contour plots to sophisticated data animations. There are no prerequisites for this course. It is designed for the beginning IDL user or for those whose programming skills are rusty.

Introduction to IDL Programming

This five-day course is our most comprehensive introduction to IDL functionality. You will learn to read, analyze, and display your data in a variety of ways. You will also learn to use the IDL language to create your own IDL programs, including IDL programs with graphical user interfaces for point-and-click operation. You must have at least six months of IDL experience or be a proficient programmer in some other programming language to attend this course.

IDL Application Development

This five-day course is an advanced IDL programming course specifically designed for the user who is creating larger IDL programs. We emphasize writing IDL programs with graphical user interfaces, linking IDL programs to other software, and writing IDL programs that are portable and easy to maintain across several IDL platforms. The prerequisite for this course is at least one year of IDL programming experience or completion of the Introduction to IDL Programming course.

Learning ENVI

This three-day course is an introduction to ENVI, the "Environment for Visualizing Images". ENVI is specifically designed to visualize and analyze multi- or hyperspectral data collected from various airborne or satellite remote se9nsing instruments. This class introduces you to ENVI's capabilities with respect to such topics as image classification and registration, image spectral and spatial filtering, band math and image statistics, and using the built-in ENVI spectral libraries. An optional one-day Introduction to IDL course is always offered at the end of each Learning ENVI course for those who wish to know more about extending ENVI's capabilities with IDL.

Custom IDL and ENVI Courses

Customized IDL or ENVI courses are arranged on an ad hoc basis through the Research Systems Training Department to meet your company's specific training needs. These courses last from one to five days and can be taught at our training facility or at your site. Topics are ordinarily selected from our standard course material, but our experienced instructors are also available to help you with everything from program design to program implementation.

IDL and ENVI Course Manuals

Many of the people who have taken our courses have told us that the course manuals were outstanding and a great help in learning IDL and ENVI. For this reason, we are offering our training course manuals to people who cannot attend a course. Manuals are updated frequently and are always in limited supply. Contact us at the phone number or e-mail address above for availability and price information.


ENVI

ENVI is an advanced, full-featured remote sensing image processing application. It combines a robust suite of image processing functions with state-of-the-art radar and spectral analysis routines, giving you a powerful tool that can be used from desktop PCs, Macintoshes, or Unix workstations.

ENVI's open file architecture allows you to read and analyze virtually any image type and share the data with others. Its intuitive graphical user interface gets new users get up and running fast, and experienced users can easily customize the interface to suit specialized analysis requirements.

Custom image processing routines can be rapidly created and run in ENVI using IDL, Research Systems' comprehensive data analysis and visualization toolkit. With ENVI, you get the unique combination of advanced image processing, an intuitive graphical interface, and flexible extensibility.


Visible Human CD

The world's first digital human body reference

Research Systems' Visible Human CD is the world's first complete digital reference of photographic images for exploring male human anatomy. With the click of a mouse, the Visible Human CD gives you ready access to more than 7,800 axial, coronal, and sagittal slices of a human male. For efficient storage and retrieval, the image slices are compressed to fit on a single CD-ROM!

Explore the Visible Human using custom Navigator built in IDL

Research Systems' easy-to-use Navigator lets you concurrently display multiple slices in any orientation or modality. For comparison and analysis, click on a region of interest in a slice and view corresponding cross-sections in additional windows. Set bookmarks to keep track of notable images, create powerful animations, and easily annotate images for presentation.

Export Visible Human slices using TIFF, PICT, GIF, PostScript, EPS, or BMP formats to IDL or other image processing packages for manipulation or output.

Data provided by the National Library of Medicine's Visible Human Project


Notes for Unix
Notes for Unix and VMS

Please see the file README.TXT in the idl_4 subdirectory of your IDL installation directory for notes that were too late to include in this section.

Changing Unix and VMS Online Help Defaults

Serious OpenWindows Bug in SunOS 4.1.3 and 4.1.4

LD_LIBRARY_PATH on Sun Platforms

Ultrix XDR SAVE/RESTORE Files and Double-precision Data

Using IDL 4.0.1 under AIX 4.1

Using IDL 4.0.1 for Unix with Research Systems' Visible Human CD-ROM

Notes on Filling Continental Boundaries


Notes for Windows

Please see the file readme.wri in the idl40 subdirectory of your IDL installation directory for notes that were too late to include in this section. Double-click on the "Read Me" icon in your IDL program group to launch Microsoft Write to read this file.

Long Filenames not Supported in IDL for Windows

Problems with ATI Graphics Cards

System Languages other than English

LINKIMAGE Supported under Windows 3.1

File Handles under Windows 3.1

Hardware Port Routines under Windows NT

Setting Environment Variables under Windows NT

Using IDL in a Multiuser Windows NT Environment

Notes on Filling Continental Boundaries


Notes for Macintosh

Please see the file Read Me in your IDL installation folder for notes that were too late to include in this section.

Running IDL on a PowerBook 160 or PowerBook 180

Printing Images from IDL for Macintosh

Font/Display Problems with Online Help

Notes on Filling Continental Boundaries


Changing Unix Online Help Defaults
Changing Unix and VMS Online Help Defaults

You can change the appearance and behavior of many aspects of the IDL Online Help viewer for Unix and VMS. We have chosen defaults that are appropriate for most platforms. However, due to differences in screen size, available fonts, or other X default settings, you may want to change the appearance of the viewer.

Changes can be made by altering the HyperHelp X resources. The file that contains the default settings is rsidir/idl_4/resource/X11/lib/app-defaults/HyperHelp. Altering the X resources in this file will make changes for all IDL help users on your system. To change defaults for a single user, copy individual X resources from the HyperHelp file and put them in the user's own .Xdefaults file.

See the notes in the  rsidir/idl_4/resource/X11/lib/app-defaults/HyperHelp  file for information on the effects of each X resource.


Serious OpenWindows Bug in SunOS 4.1.3 and 4.1.4"
Serious OpenWindows Bug in SunOS 4.1.3 and 4.1.4

The standard OpenWindows server shipped by Sun with SunOS 4.1.3 and 4.1.4 has a known bug that causes it to sometimes hang when the user activates pulldown menus in Motif applications such as IDL. When this happens, the only way to recover is to log in remotely and kill the program or reboot the system. This is not an IDL specific problem—it is common to all applications built with Motif 1.2. The problem happens even though the Motif used by IDL for SunOS is the Sun-sanctioned IXI Premier Motif sold by Sun Express. Furthermore, there is no fully reliable client-side fix that we can apply to IDL to avoid activating this bug in the server.

There are several solutions to this problem:

•	Avoid IDL programs that use pulldown menus. This essentially limits you to non-widget applications, and is not recommended.

•	Install MIT X11R5 or X11R6 and use it in preference to OpenWindows. Many third party vendors sell inexpensive precompiled versions for SunOS that are easy to install. This is probably the best answer for those who anticipate staying with SunOS 4.1.x for a long period.

•	Upgrade your operating system to Solaris 2.3 or later, which comes with an MIT-based X server that does not have this problem.

•	Obtain the proper patch for your system from Sun and apply it to your system.

•	Replace the xnews server on your system with the patched version that we supply as part of this IDL distribution. We obtained this server from the Sun-supported FTP site at sunsite.unc.edu, and have verified on our systems that it solves the hanging problem.

This patched server is provided as an easy way to get up and running with IDL. We provide this patch "as is" with no guarantee of suitability or fitness. Please direct any problems or questions about the server to Sun Microsystems.

Follow the instructions below to install the patched xnews server that we have supplied:

•	Install IDL following the standard instructions.

•	Log in as root. Ensure that the OpenWindows environment is not running. If openwindows is NOT found on your system via the path /usr/openwin, define the environment variable OPENWINHOME to point at its location. For example:

% setenv OPENWINHOME /bigdisk/openwin

If openwindows is located in /usr/openwin, this step is not necessary.

•	Change directories to the IDL directory. Here, we assume IDL is installed in /usr/local/rsi/idl_4. Adjust these commands as necessary to reflect your installation:

% cd /usr/local/rsi/idl_4

•	Run the patch_sun_xnews script supplied in the bin directory of the IDL distribution:

% bin/patch_sun_xnews

This script saves your existing server under a different name and copies the new version into the correct place.


LD_LIBRARY_PATH on Sun Platforms

Some users have had difficulties with the xinstall IDL installer or IDL widget applications on Sun platforms. These problems are caused by the directory /lib being defined in their LD_LIBRARY_PATH environment variable. For example, if /lib is in LD_LIBRARY_PATH, a call to the IDL widget function PICKFILE generates the following error:

dlopen: stub interception failed
IOT trap

Removing /lib from LD_LIBRARY_PATH solves this problem. There is no reason for the directory /lib to be defined in LD_LIBRARY_PATH. However, it should also not cause problems. We believe this problem is caused by a bug in the SunOS dynamic linking system. Another workaround is to specify the directory /usr/lib instead of just /lib in LD_LIBRARY_PATH.


Ultrix XDR Files and Double-precision Data
Ultrix XDR SAVE/RESTORE Files and Double-precision Data

IDL uses XDR for Save/Restore files, and for files opened with the XDR keyword to OPENR, OPENW, and OPENU. IDL 4.0 has a bug that affects users of DEC Ultrix Risc (DecStations). All XDR output of double-precision floating-point data written by that version of IDL has its least and most significant longwords reversed. This presents no problem as long as such files are only used on these machines. However, XDR files with double-precision data cannot be moved between these machines and others without the need to correct the data.

IDL 4.0.1 handles such data in the correct order, and is compatible with IDL 3.6.1.

The file mipseb_dblfixup.pro, found in the lib/obsolete subdirectory of the IDL distribution, contains an IDL program that can be used to repair any double-precision floating-point data affected by this problem.


Using IDL 4.0.1 under AIX 4.1

While IDL 4.0.1 for AIX was compiled under AIX version 3.2, you can run it under AIX version 4.1 by installing the AIX version 3.2 compatibility libraries. These libraries are found on the AIX version 4.1 installation media.

Using LINKIMAGE under AIX 4.1

If you are compiling external code to be linked with IDL 4.0.1 (using LINKIMAGE, for example) under AIX version 4.1, you will need to substitute the -bnoentry compiler switch for the -e _nostart switch shown in "IBM AIX Version 3.2" on page 18-19 of the IDL User's Guide. For example, the compiler command:

% cc -o example.so example.o -bM:SRE -bE:example.exp -e _nostart

which works under AIX 3.2, should be replaced by:

% cc -o example.so example.o -bM:SRE -bE:example.exp -bnoentry

under AIX 4.1.


Using IDL 4.0.1 with Research Systems' Visible Human CD-ROM
Using IDL 4.0.1 for Unix with Research Systems' Visible Human CD-ROM

Follow the instructions in this release note if you are having problems running the Visible Human CD-ROM after updating your IDL installation to version 4.0.1.

If you have both the Visible Human installed on your system and IDL 4.0.1 installed on your Unix system in the default IDL directory (/usr/local/rsi/idl_4), you need to update the IDL 4.0 executables used by the Visible Human for Visible Human to run properly.

We have included a simple patch program in the IDL 4.0.1 distribution that performs this update for you.

For the technically minded, an explanation of the problem solved by this patch follows: In IDL 4.0.1, IDL's sharable libraries have been restructured. The main program for IDL is no longer included in the sharable libraries; instead, it is found in a file called main.o. By default, the Visible Human attempts to load the IDL sharable libraries from the /usr/local/rsi/idl_4 directory if this directory exists. If /usr/local/rsi/idl_4 contains IDL 4.0.1, instead of IDL 4.0, the Visible Human is unable to locate the IDL main program. The patch we provide upgrades the Visible Human application to IDL 4.0.1, so the correct libraries are loaded if /usr/local/rsi/idl_4 is present.

Applying the Visible Human Patch

Follow the instructions in this section to apply the update patch for Visible Human.

The patch program will overwrite the IDL binaries contained in all of the /usr/local/rsi/human_1/bin/bin.os_version directories. If you want to keep a backup copy of these files, make a copy of these directories before applying the patch or simply keep your Visible Human version 1.0 CD.

If the Visible Human application is installed in a location other than the default location (/usr/local/rsi), the HUMAN_DIR environment variable may need to be defined to point to the actual location before you can execute the patch script. HUMAN_DIR can be defined by issuing the following command, where install_dir is the directory in which you installed the Visible Human:

setenv HUMAN_DIR install_dir/human_1

Enter the following command to start the patch program. Because /usr/local/rsi is a public directory, you may need root or similar permissions before running the patch script:

/bin/sh /usr/local/rsi/idl_4/bin/human_patch

Executing the Visible Human Application from CD-ROM

If you have IDL 4.0.1 installed in the /usr/local/rsi/idl_4 directory, but want to execute the Visible Human application directly from the CD, the idl_4 directory found in /usr/local/rsi must be temporarily changed to a new name.

Move the idl_4 directory by executing the following commands. You may need  root permissions to perform these operations:

cd /usr/local/rsi
mv idl_4 idl_4_save

The Visible Human can now be executed from the CD-ROM. When you are finished with Visible Human, IDL 4.0.1 can be restored to its previous location with the commands:

cd /usr/local/rsi
mv idl_4_save idl_4


Long Filenames not Supported in IDL for Windows

Filenames of files read and written with IDL can be a maximum of eight characters long with a three-character file extension, and cannot contain spaces.

Under Windows 3.1, DOS truncates filenames longer than eight characters. If you plan to transfer files from operating systems that support longer filenames, be sure that all files that you transfer are unique in the first eight letters.

Under Windows NT, long filenames may exist, but IDL read and write operations on these files will not succeed. If you transfer files from operating systems that support long filenames, be sure to rename them using the 8.3 convention before attempting to read from or write to them using IDL.

While the names of IDL library files have been truncated to eight characters, the names of the actual routines remain unchanged.


Problems with ATI Graphics Cards

Using IDL version 4.0 on systems with ATI graphics cards and outdated ATI software may cause unpredictable behavior. If you have an ATI graphics card, make sure you are using version 1.4 or later of the ATI Desktop software, and version 3.0 or later of the ATI Flexdesk software.

Contact your hardware vendor for details on getting the updated ATI software.


System Languages other than English

Using IDL 4.0 with your Windows system language set to something other than "English (American)" can cause unpredictable behavior.

To set the system language, choose open the Control Panel (in the Main Program group) and double-click on the "International" icon. Select "English (American)" from the "Language" pulldown menu and click "OK".


LINKIMAGE under Windows 3.1
LINKIMAGE Supported under Windows 3.1

The LINKIMAGE procedure now functions under Windows 3.1. Note, however, that LINKIMAGE loads a 32-bit win32s DLL. 16-bit DLLs are not supported.


File Handles under Windows 3.1

Under Windows 3.1, we recommend that you set the FILES= environment variable to a value of at least 60. This will help avoid running out of file handles when running IDL alongside other Windows applications.

To set the environment variable, use a text editor to open the file config.sys. Change the line that begins with FILES= to read  FILES=60. You will need to restart your computer for this change to take effect.

If you get an "Out of File Handles" error message while running IDL, increase the value of this environment variable again.


Hardware Port Routines under Windows NT

Under Windows NT, it is not possible for an application to address hardware ports directly. Accordingly, the IDL routines INP(), INPW(), OUTP, and OUTPW will generate a privileged instruction exception under Windows NT.


Setting Environment Variables under Windows NT

Under Windows NT, the SETENV procedure can be used to set Windows NT environment variables. Note, however, that variables set using SETENV are available only to IDL's process. Variables set using SETENV cannot be referenced or modified outside IDL.

The IDL function GETENV() can read both IDL-only environment variables (set with SETENV) and environment variables set before IDL was started.


Using IDL in a Multiuser Windows NT Environment

The IDL Installation program appends IDL's home directory to the PATH environment variable of the user who is installing IDL. If users with other accounts on the NT workstation wish to use IDL, do one of the following:

•	Add IDL's home directory to each user's individual PATH environment variable.

or

•	Add IDL's home directory to the shared system PATH environment variable.

To modify either PATH environment variable, open the Control Panel and double-click on the "System" icon. Select the PATH variable from either the "System Environment Variables" list or the "User Environment Variables" list, as appropriate, and add IDL's home directory to the value. Click "Set." By default, IDL's is installed in the directory \rsi\idl40 on the drive that contains the windows directory.

Note that only processes begun after environment variables are set inherit those new values. This means you must restart IDL after changing your path.


Running IDL on a PowerBook 160 or 180
Running IDL on a PowerBook 160 or PowerBook 180

To run IDL on a PowerBook 160 or PowerBook 180 you must install the file PrBk 160/180 ADB Patch from the folder For PowerBook 160/180 Users on your installation disk. To install the file, drag it onto your System Folder and restart your PowerBook.

The patch file is supplied by Apple Computer. It fixes a problem with the Apple Desktop Bus on PowerBook models 160 and 180.


Printing Images from IDL for Macintosh

When using the "Print" option from the File menu, to print an IDL image directly to your printer, be aware that some printer drivers always print colortable index zero as white. "Inverted" looking images can sometimes result. This is a problem with older versions of the LaserWriter printer driver from Apple. We suggest using LaserWriter driver version 8.3, available from Apple's ftp site (ftp.support.apple.com) to fix this problem.


Font/Display Problems with Online Help

If you are experiencing problems viewing the online
help, such as strange-looking fonts, or text that
is cut off by the edges of the viewer window,
your system is probably missing certain fonts that
the help viewer needs to run properly.

Make sure your system has the following fonts
installed:

Times-12
Symbol-12
Courier-12
Helvetica-12, 14, and 18

Note that the text of this release note has
intentionally short lines so that users
affected by this problem can read the
solution.


Notes on Filling Continental Boundaries

There are a number of known problems with the algorithm used by the FILL_CONTINENTS keyword to MAP_CONTINENTS. While many map projections are drawn properly, there are some instances where continent boundaries may be filled incorrectly. This section details situations in which the problems are most likely to occur.

Note also that the clipping algorithm for the continental polygons is computationally intensive, and can be slow. Use the low-resolution data when testing map projections, then switch to high resolution when producing a final map.

Polygons that Intersect the Horizon

Concave polygons that intersect the horizon may not be filled correctly. For example, suppose you had a projection in which the horizon ran though Florida, across the Gulf of Mexico, and through the Yucatan. Depending on the projection, the Gulf of Mexico might be treated as a continent and filled.

Projections Centered on the North or South Pole

If the outer border of the map lies inside a continent, the outside of the continent may be filled instead of the inside. For example, if the projection is centered on the North pole and the outer border of the map lies within Antarctica, the outside of Antarctica may be filled rather than the inside.

Plotting on a PostScript Device

Some PostScript devices may not be able to handle the large number of polygon vertices generated by the continent-filling routines.

Displaying Portions of the Globe

Continents may not be properly clipped when the entire globe is not displayed.

Gnomic and Conic Projections

Filled continents may not be confined to the plotting window due to the lack of a properly-defined horizon.

Sinusoidal Projection

Due to the granularity of the map database, a portion of Antarctica is not filled.

Molleweide Projection

Continental polygons may be drawn above the Earth's surface.

Satellite Projection

May produce unsatisfactory results when the viewing position is less than one Earth-radius above the surface (when the parameter P is less than two).


IDL Online Help

Contents

 IDL Online Help Navigator

 IDL User's Guide Table of Contents

 IDL Overview

 Topics in IDL Overview Chapter

 Running IDL

 Topics in Running IDL Chapter

 Starting IDL

 Quitting IDL

 Input to IDL

 Matching IDL to Your Terminal/Window System

 Hints on Using IDL with Selected Window Systems

 Special Characters

 Executive Commands

 Preparing and Running Programs

 Format of Program Files

 Interrupting Program Execution

 Aborting IDL

 Issuing Operating System Commands from IDL

 Batch Execution

 Noninteractive IDL

 Startup File

 Changing the IDL Prompt

 Defining Keys

 Environment Parameters

 Constants and Variables

 Topics in Constants and Variables Chapter

 Numeric Constants

 String Constants

 Variables

 System Variables

 Expressions and Operators

 Topics in Expressions and Operators Chapter

 Operator Precedence

 Type and Structure of Expressions

 Type Conversion Functions

 Structure of Expressions

 IDL Operators

 Parentheses

 Mathematical Operators

 Minimum and Maximum Operators

 Matrix Multiplication

 Array Concatenation

 Boolean Operators

 Relational Operators

 Subscripts

 Topics in Subscripts Chapter

 Subscript Examples

 Subscript Ranges

 Structure of Subarrays

 Array Subscripts

 Combining Array Subscripts with Others

 Storing Elements with Array Subscripts

 Statements

 Topics in Statements Chapter

 Components of Statements

 The Assignment Statement

 Blocks

 CASE Statements

 Statements

 FOR Statement

 Function Definition Statement

 GOTO Statement

 IF Statement

 Procedure Call Statements

 Procedure Definition Statement

 REPEAT Statement

 WHILE statement

 Structures

 Topics in Structures Chapter

 Creating and Defining Structures

 Structure References

 Using HELP with Structures

 Parameter Passing with Structures

 Arrays of Structures

 Structure Input/Output

 Advanced Structure Usage

 Strings

 Topics in Strings Chapter

 String Operations

 Non-string and Non-scalar Arguments to String Routines

 String Concatenation

 Using STRING to Format Data

 Byte Arguments and Strings

 Case Folding

 Whitespace

 Finding the Length of a String

 Substrings

 Vector-Drawn Fonts

 Topics in Vector-Drawn Fonts Chapter

 About the Vector Fonts

 Character Sets and Positioning Commands

 Vector-Drawn Font Example

 Font Samples

 Defining Procedures and Functions

 Topics in Defining Procedures and Functions Chapter

 Procedure and Function Definition Statements

 Parameters

 Entering Procedure Definitions

 Parameter Passing Mechanism

 Calling Mechanism

 Programming Routines

 Topics in Programming Routines Chapter

 Error Handling Routines

 Controlling Errors with CATCH

 Controlling Errors Using ON_ERROR

 Controlling Input/Output Errors

 Error Signaling

 Obtaining Traceback Information

 Error System Variables

 Math Errors

 Informational Routines

 Program Control Routines

 Handles - Dynamic Memory Structures in IDL

 Efficient Programming

 Topics in Efficient Programming Chapter

 Expression Evaluation Order

 Avoid IF Statements

 Use Vector and Array Operators

 Use IDL System Functions and Routines

 Use Constants of the Correct Type

 Eliminate Invariant Expressions

 Virtual Memory

 IDL Implementation

 Interactive Support

 Topics in Interactive Support Chapter

 IDL's Online Help System

 Extending IDL's Online Help System

 The HELP Procedure

 SAVE and RESTORE

 Journaling

 Plotting

 Topics in Plotting Chapter

 Plotting Keyword Parameters

 Graphics Coordinate Systems

 X Versus Y Plots - PLOT and OPLOT

 Annotation - The XYOUTS Procedure

 Plotting Symbols

 Polygon Filling

 Tick Marks

 Logarithmic Scaling

 Multiple Plots on a Page

 Specifying the Location of the Plot

 Plotting Missing Data

 Using the AXIS Procedure

 The CURSOR Procedure

 Plotting Multi-Dimensional Arrays

 Topics in Plotting Multi-D Arrays Chapter

 Contour Plots

 Overlaying Images and Contour Plots

 Additional Contour Options

 The SURFACE Procedure

 Three-Dimensional Graphics

 Three-Dimensional Transformations with Two-Dimensional Procedures

 Shaded Surfaces - The SHADE_SURF Procedure

 Volume Visualization - The SHADE_VOLUME Procedure

 Image Display Routines

 Topics in Image Display Routines Chapter

 Images

 Imaging Routines

 Image Display

 Reading from the Display Device

 Color Tables

 True Color Displays

 Controlling the Device Cursor

 Files and Input/Output

 Topics in Files and I/O Chapter

 File I/O Overview

 Types of Input/Output

 Opening Files

 Closing Files

 Logical Unit Numbers (LUN's)

 Free Format Input/Output

 Explicitly Formatted Input/Output

 Format Codes

 Unformatted Input/Output

 Portable Unformatted Input/Output

 Associated Input/Output

 Miscellaneous File Manipulation Information

 Unix-Specific Information

 VMS-Specific Information

 Scientific Data Formats

 Support for Standard Image File Formats

 Operating System Access

 Topics in Operating System Access Chapter

 The SPAWN Procedure

 Changing the Working Directory

 The CALL_EXTERNAL Function

 The LINKIMAGE Procedure

 Which Operating System is Running?

 Unix-Specific OS Abilities

 Using CALL_EXTERNAL under UNIX

 Unix Compilation, Link, and Call Statements

 VMS-Specific OS Abilities

 Using CALL_EXTERNAL under VMS

 VMS Compilation, Link, and Call Statements

 Windows-Specific OS Abilities

 Using CALL_EXTERNAL under Windows

 Macintosh-Specific OS Abilities

 Using CALL_EXTERNAL on the Macintosh

 Map Projections

 Topics in Map Projections Chapter

 The MAP_SET Procedure

 The MAP_GRID Procedure

 The MAP_CONTINENTS Procedure

 Map Projections Described

 Putting Data on Maps

 High-Resolution Continent Outlines

 IDL Mathematics

 Topics in IDL Mathematics Chapter

 IDL's Numerical Recipes Functions

 Accuracy and  Floating-Point Operations

 Arrays and Matrices

 Correlation Analysis

 Curve and Surface Fitting

 Eigenvalues and Eigenvectors

 Gridding and Interpolation

 Hypothesis Testing

 Integration

 Linear Systems

 Nonlinear Equations

 Optimization

 Sparse Arrays

 Time-Series Analysis

 Widgets

 Topics in Widgets Chapter

 Widget Types

 Examples of Widget Programming

 The Widget Lifecycle

 Simple Widget Example

 Widget Events

 Using the XMANAGER Procedure

 Widget Values

 Widget User Values

 Compound Widgets

 Managing the State of a Widget Application

 Using Draw Widgets

 Menus

 The XREGISTERED Procedure

 Using Timer Events

 Widget Sizing

 Miscellaneous Widget Information

 A Larger Example

 Writing a Compound Widget (CW_DICE)

 Widget Builder

 Topics in Widget Builder Chapter

 Starting the Widget Builder

 Widget Builder Menu Hierarchy

 Widget Builder Tutorial

 Scientific Data Formats

 Topics in Scientific Data Formats Chapter

 CDF - Common Data Format

 HDF - Hierarchical Data Format

 NetCDF - Network Common Data Format

 Remote Procedure Calls

 Topics in Remote Procedure Calls Chapter

 Using IDL as an RPC Server

 The IDL RPC Library

 The Varinfo_t Structure

 More Variable Manipulation Macros

 Notes on Variable Creation and Memory Management

 RPC Examples

 Alphabetical List of Routines

 A Routines

 B Routines

 C Routines

 D Routines

 E Routines

 F Routines

 G Routines

 H Routines

 I Routines

 J Routines

 K Routines

 L Routines

 M Routines

 N Routines

 O Routines

 P Routines

 Q Routines

 R Routines

 S Routines

 T Routines

 U Routines

 V Routines

 W Routines

 X Routines

 Z Routines

 Routines by Application

 Language Features Quick Reference

 Executive Commands Quick Reference

 Special Characters Quick Reference

 Statements Quick Reference

 Operators Quick Reference

 Subscripts Quick Reference

 Animation Routines

 Array Creation Routines

 Array and Image Processing Routines

 Font Manipulation Routines

 General Graphics Routines

 Graphics, Color Table Manipulation Routines

 Help Routines

 Image Display Routines

 Input/Output Routines

 CDF Routines

 HDF Routines

 NetCDF Routines

 Mapping Routines

 Mathematics Routines

 Correlation Analysis Routines

 Curve and Surface Fitting Routines

 Differential Equations Routines

 Eigenvalue and Eigenvector Routines

 Gridding and Interpolation Routines

 Hypothesis Testing Routines

 Integration Routines

 Linear Systems Routines

 Miscellaneous Math Routines

 Multivariate Analysis Routines

 Nonlinear Equations Routines

 Optimization Routines

 Probability Functions and Inverses

 Sparse Array Routines

 Special Math Functions

 Statistical Fitting Routines

 Statistical Tools Routines

 Time-Series Analysis Routines

 Transcendental Functions

 Transforms Routines

 Alphabetical List of Mathematics Routines

 Operating System Access Routines

 Plotting Routines, Two-Dimensional and General

 Plotting Routines, Multi-Dimensional

 Programming and IDL Control Routines

 Saving and Restoring a Session Routines

 String Processing Routines

 Type Conversion Routines

 Widget Routines

 Widget Routines, Compound

 Window Routines

 System Variables Quick Reference

 Graphics Devices Quick Reference

 Graphics Keywords Quick Reference

 IDL Routines

 A_CORRELATE

 ABS

 ACOS

 ALOG

 ALOG10

 ANNOTATE

 ARROW

 ASIN

 ASSOC

 ATAN

 AXIS

 BAR_PLOT

 BESELI

 BESELJ

 BESELY

 BETA

 BILINEAR

 BIN_DATE

 BINDGEN

 BINOMIAL

 BLK_CON

 BOX_CURSOR

 BREAKPOINT

 BROYDEN

 BYTARR

 BYTE

 BYTEORDER

 BYTSCL

 C_CORRELATE

 CALDAT

 CALENDAR

 CALL_EXTERNAL

 CALL_FUNCTION

 CALL_PROCEDURE

 CATCH

 CD

 CDF_ATTCREATE

 CDF_ATTGET

 CDF_ATTINQ

 CDF_ATTNUM

 CDF_ATTPUT

 CDF_ATTRENAME

 CDF_CLOSE

 CDF_CONTROL

 CDF_CREATE

 CDF_DELETE

 CDF_DOC

 CDF_EPOCH

 CDF_ERROR

 CDF_EXISTS

 CDF_INQUIRE

 CDF_OPEN

 CDF_VARCREATE

 CDF_VARGET

 CDF_VARGET1

 CDF_VARINQ

 CDF_VARNUM

 CDF_VARPUT

 CDF_VARRENAME

 CEIL

 CHEBYSHEV

 CHECK_MATH

 CHISQR_CVF

 CHISQR_PDF

 CHOLDC

 CHOLSOL

 CINDGEN

 CIR_3PNT

 CLOSE

 COLOR_CONVERT

 COLOR_QUAN

 COMFIT

 COMPLEX

 COMPLEXARR

 COMPLEXROUND

 COND

 CONGRID

 CONJ

 CONTOUR

 CONVERT_COORD

 CONVOL

 COORD2TO3

 CORRELATE

 COS

 COSH

 CRAMER

 CREATE_STRUCT

 CREATE_VIEW

 CROSSP

 CT_LUMINANCE

 CTI_TEST

 CURSOR

 CURVEFIT

 CV_COORD

 CW_ANIMATE

 CW_ANIMATE_GETP

 CW_ANIMATE_LOAD

 CW_ANIMATE_RUN

 CW_ARCBALL

 CW_BGROUP

 CW_CLR_INDEX

 CW_COLORSEL

 CW_DEFROI

 CW_DICE

 CW_FIELD

 CW_FORM

 CW_FSLIDER

 CW_ORIENT

 CW_PDMENU

 CW_RGBSLIDER

 CW_TMPL

 CW_ZOOM

 DBLARR

 DCINDGEN

 DCOMPLEX

 DCOMPLEXARR

 DEFINE_KEY

 DEFROI

 DEFSYSV

 DELETE_SYMBOL

 DELLOG

 DELVAR

 DEMO_MODE

 DERIV

 DERIVSIG

 DETERM

 DEVICE

 DFPMIN

 DIGITAL_FILTER

 DILATE

 DINDGEN

 DISP_TXT

 DISSOLVE

 DIST

 DO_APPLE_SCRIPT

 DOC_LIBRARY

 DOUBLE

 EFONT

 EIGENVEC

 ELMHES

 EMPTY

 EOF

 ERASE

 ERODE

 ERRORF

 ERRPLOT

 EXECUTE

 EXIT

 EXP

 EXPAND

 EXPAND_PATH

 EXPINT

 EXTRAC

 EXTRACT_SLICE

 F_CVF

 F_PDF

 FACTORIAL

 FFT

 FILEPATH

 FINDFILE

 FINDGEN

 FINITE

 FIX

 FLICK

 FLOAT

 FLOOR

 FLOW3

 FLTARR

 FLUSH

 FREE_LUN

 FSTAT

 FULSTR

 FUNCT

 FV_TEST

 FX_ROOT

 FZ_ROOTS

 GAMMA

 GAMMA_CT

 GAUSS_CVF

 GAUSS_PDF

 GAUSS2DFIT

 GAUSSFIT

 GAUSSINT

 GET_KBRD

 GET_LUN

 GET_SYMBOL

 GETENV

 GETHELP

 GRID3

 GS_ITER

 H_EQ_CT

 H_EQ_INT

 HANDLE_CREATE

 HANDLE_FREE

 HANDLE_INFO

 HANDLE_MOVE

 HANDLE_VALUE

 HANNING

 HDF_CLOSE

 HDF_DELDD

 HDF_DF24_ADDIMAGE

 HDF_DF24_GETIMAGE

 HDF_DF24_GETINFO

 HDF_DF24_LASTREF

 HDF_DF24_NIMAGES

 HDF_DF24_READREF

 HDF_DF24_RESTART

 HDF_DFAN_ADDFDS

 HDF_DFAN_ADDFID

 HDF_DFAN_GETDESC

 HDF_DFAN_GETFDS

 HDF_DFAN_GETFID

 HDF_DFAN_GETLABEL

 HDF_DFAN_LABLIST

 HDF_DFAN_LASTREF

 HDF_DFAN_PUTDESC

 HDF_DFAN_PUTLABEL

 HDF_DFP_ADDPAL

 HDF_DFP_GETPAL

 HDF_DFP_LASTREF

 HDF_DFP_NPALS

 HDF_DFP_PUTPAL

 HDF_DFP_READREF

 HDF_DFP_RESTART

 HDF_DFP_WRITEREF

 HDF_DFR8_ADDIMAGE

 HDF_DFR8_GETIMAGE

 HDF_DFR8_GETINFO

 HDF_DFR8_LASTREF

 HDF_DFR8_NIMAGES

 HDF_DFR8_PUTIMAGE

 HDF_DFR8_READREF

 HDF_DFR8_RESTART

 HDF_DFR8_SETPALETTE

 HDF_DFSD_ADDDATA

 HDF_DFSD_DIMGET

 HDF_DFSD_DIMSET

 HDF_DFSD_ENDSLICE

 HDF_DFSD_GETDATA

 HDF_DFSD_GETINFO

 HDF_DFSD_GETSLICE

 HDF_DFSD_PUTSLICE

 HDF_DFSD_READREF

 HDF_DFSD_SETINFO

 HDF_DFSD_STARTSLICE

 HDF_DUPDD

 HDF_EXISTS

 HDF_ISHDF

 HDF_NEWREF

 HDF_NUMBER

 HDF_OPEN

 HDF_SD_ADDDATA

 HDF_SD_ATTRFIND

 HDF_SD_ATTRINFO

 HDF_SD_ATTSET

 HDF_SD_CREATE

 HDF_SD_DIMGET

 HDF_SD_DIMGETID

 HDF_SD_DIMSET

 HDF_SD_END

 HDF_SD_ENDACCESS

 HDF_SD_FILEINFO

 HDF_SD_GETDATA

 HDF_SD_GETINFO

 HDF_SD_ISCOORDVAR

 HDF_SD_NAMETOINDEX

 HDF_SD_REFTOINDEX

 HDF_SD_SELECT

 HDF_SD_SETEXTFILE

 HDF_SD_SETINFO

 HDF_SD_START

 HDF_VD_ATTACH

 HDF_VD_DETACH

 HDF_VD_FDEFINE

 HDF_VD_FEXIST

 HDF_VD_FIND

 HDF_VD_GET

 HDF_VD_GETID

 HDF_VD_GETINFO

 HDF_VD_GETNEXT

 HDF_VD_INSERT

 HDF_VD_ISVD

 HDF_VD_ISVG

 HDF_VD_LONE

 HDF_VD_READ

 HDF_VD_SEEK

 HDF_VD_SETINFO

 HDF_VD_WRITE

 HDF_VG_ADDTR

 HDF_VG_ATTACH

 HDF_VG_DETACH

 HDF_VG_GETID

 HDF_VG_GETINFO

 HDF_VG_GETNEXT

 HDF_VG_GETTR

 HDF_VG_GETTRS

 HDF_VG_INQTR

 HDF_VG_INSERT

 HDF_VG_ISVD

 HDF_VG_ISVG

 HDF_VG_LONE

 HDF_VG_NUMBER

 HDF_VG_SETINFO

 HELP

 HILBERT

 HIST_2D

 HIST_EQUAL

 HISTOGRAM

 HLS

 HQR

 HSV

 IBETA

 IGAMMA

 IMAGE_CONT

 IMAGINARY

 INDGEN

 INT_2D

 INT_3D

 INT_TABULATED

 INTARR

 INTERPOL

 INTERPOLATE

 INVERT

 IOCTL

 ISHFT

 JOURNAL

 JULDAY

 KEYWORD_SET

 KRIG2D

 KW_TEST

 LABEL_DATE

 LABEL_REGION

 LADFIT

 LEEFILT

 LINBCG

 LINDGEN

 LINFIT

 LINKIMAGE

 LJLCT

 LL_ARC_DISTANCE

 LNGAMMA

 LNP_TEST

 LOADCT

 LONARR

 LONG

 LU_COMPLEX

 LUDC

 LUMPROVE

 LUSOL

 M_CORRELATE

 MACHAR

 MAKE_ARRAY

 MAP_CONTINENTS

 MAP_GRID

 MAP_IMAGE

 MAP_PATCH

 MAP_SET

 MAX

 MD_TEST

 MEDIAN

 MESH_OBJ

 MESSAGE

 MIN

 MIN_CURVE_SURF

 MK_HTML_HELP

 MODIFYCT

 MOMENT

 MULTI

 N_ELEMENTS

 N_PARAMS

 N_TAGS

 NCDF_ATTCOPY

 NCDF_ATTDEL

 NCDF_ATTGET

 NCDF_ATTINQ

 NCDF_ATTNAME

 NCDF_ATTPUT

 NCDF_ATTRENAME

 NCDF_CLOSE

 NCDF_CONTROL

 NCDF_CREATE

 NCDF_DIMDEF

 NCDF_DIMID

 NCDF_DIMINQ

 NCDF_DIMRENAME

 NCDF_EXISTS

 NCDF_INQUIRE

 NCDF_OPEN

 NCDF_VARDEF

 NCDF_VARGET

 NCDF_VARGET1

 NCDF_VARID

 NCDF_VARINQ

 NCDF_VARPUT

 NCDF_VARRENAME

 NEWTON

 NORM

 ON_ERROR

 ON_IOERROR

 ONLINE_HELP

 OPEN

 OPLOT

 OPLOTERR

 P_CORRELATE

 PICKFILE

 PLOT

 PLOT_3DBOX

 PLOT_FIELD

 PLOTERR

 PLOTS

 PNT_LINE

 POINT_LUN

 POLAR_CONTOUR

 POLAR_SURFACE

 POLY

 POLY_2D

 POLY_AREA

 POLY_FIT

 POLYFILL

 POLYFILLV

 POLYFITW

 POLYSHADE

 POLYWARP

 POPD

 POWELL

 PRIMES

 PRINT

 PRINTD

 PROFILE

 PROFILES

 PROJECT_VOL

 PS_SHOW_FONTS

 PSAFM

 PSEUDO

 PUSHD

 QROMB

 QROMO

 QSIMP

 R_CORRELATE

 R_TEST

 RANDOMN

 RANDOMU

 RANKS

 RDPIX

 READ

 READ_BMP

 READ_GIF

 READ_INTERFILE

 READ_JPEG

 READ_PICT

 READ_PPM

 READ_SPR

 READ_SRF

 READ_SYLK

 READ_WAVE

 READ_X11_BITMAP

 READ_XWD

 READS

 READU

 REBIN

 RECON3

 REDUCE_COLORS

 REFORM

 REGRESS

 REPLICATE

 RESOLVE_ALL

 RESOLVE_ROUTINE

 RESTORE

 REVERSE

 REWIND

 RIEMANN

 RK4

 ROBERTS

 ROT

 ROTATE

 ROUND

 RS_TEST

 RSTRPOS

 S_TEST

 SAVE

 SCALE3

 SCALE3D

 SEARCH2D

 SEARCH3D

 SET_PLOT

 SET_SHADING

 SET_SYMBOL

 SETENV

 SETLOG

 SETUP_KEYS

 SFIT

 SHADE_SURF

 SHADE_SURF_IRR

 SHADE_VOLUME

 SHIFT

 SHOW3

 SHOWFONT

 SIN

 SINDGEN

 SINH

 SIZE

 SKIPF

 SLICER

 SLIDE_IMAGE

 SMOOTH

 SOBEL

 SORT

 SPAWN

 SPH_4PNT

 SPH_SCAT

 SPL_INIT

 SPL_INTERP

 SPLINE

 SPLINE_P

 SPRSAB

 SPRSAX

 SPRSIN

 SQRT

 STOP

 STR_SEP

 STRARR

 STRCOMPRESS

 STRETCH

 STRING

 STRLEN

 STRLOWCASE

 STRMESSAGE

 STRMID

 STRPOS

 STRPUT

 STRTRIM

 STRUPCASE

 SURFACE

 SURFR

 SVDC

 SVDFIT

 SVSOL

 SWAP_ENDIAN

 SYSTIME

 T_CVF

 T_PDF

 T3D

 TAG_NAMES

 TAN

 TANH

 TAPRD

 TAPWRT

 TEK_COLOR

 TEMPORARY

 THIN

 THREED

 TIFF_DUMP

 TIFF_READ

 TIFF_WRITE

 TIME_TEST

 TM_TEST

 TOTAL

 TRANSPOSE

 TRI_SURF

 TRIANGULATE

 TRIGRID

 TRIQL

 TRIRED

 TRISOL

 TRNLOG

 TS_COEF

 TS_DIFF

 TS_FCAST

 TV

 TVCRS

 TVLCT

 TVRD

 TVSCL

 UNIQ

 USERSYM

 VEL

 VELOVECT

 VERT_T3D

 VOIGT

 VORONOI

 VOXEL_PROJ

 WAIT

 WARP_TRI

 WDELETE

 WEOF

 WF_DRAW

 WHERE

 WIDED

 WIDGET_BASE

 WIDGET_BUTTON

 WIDGET_CONTROL

 WIDGET_CONTROL, continued

 WIDGET_DRAW

 WIDGET_DROPLIST

 WIDGET_EVENT

 WIDGET_INFO

 WIDGET_LABEL

 WIDGET_LIST

 WIDGET_MESSAGE

 WIDGET_SLIDER

 WIDGET_TEXT

 WINDOW

 WRITE_BMP

 WRITE_GIF

 WRITE_JPEG

 WRITE_NRIF

 WRITE_PICT

 WRITE_PPM

 WRITE_SPR

 WRITE_SRF

 WRITE_SYLK

 WRITE_WAVE

 WRITEU

 WSET

 WSHOW

 WTN

 XBM_EDIT

 XDISPLAYFILE

 XFONT

 XINTERANIMATE

 XLOADCT

 XMANAGER

 XMNG_TMPL

 XMTOOL

 XPALETTE

 XREGISTERED

 XSQ_TEST

 XSURFACE

 XVAREDIT

 XYOUTS

 ZOOM

 ZOOM_24

 Graphics Keyword and System Variables Introduction

 Graphics Keywords

 Graphics Keywords, continued

 Alphabetical List of Graphics Keywords (A-R)

 Alphabetical List of Graphics Keywords (S-Z)

 System Variables for Graphics

 !C System Variable

 !D System Variable

 !ORDER System Variable

 !P System Variable

 !X, !Y, !Z System Variables

 List of Graphics System Variables

 Table of IDL Devices

 Table of DEVICE Keywords

 Keywords to DEVICE - A through C

 Keywords to DEVICE - D through F

 Keywords to DEVICE - G through I

 Keywords to DEVICE - J through M

 Keywords to DEVICE - N through P

 Keywords to DEVICE - R through T

 Keywords to DEVICE - U through Z

 Window Systems

 Printing Graphics Output Files

 The CGM Device

 The HP-GL Device

 The LJ Device

 The Macintosh Display Device

 The Null Display Device

 The PCL Device

 The PostScript Device

 The Regis Terminal Device

 The SunView Device

 The Tektronix Device

 The Microsoft Windows Device

 The X Windows Device

 The Z-Buffer Device

 Reporting Bugs

 Topics in Reporting Bugs Chapter

 Background Information

 Double Check

 Describing the Problem

 Reproducibility

 Simplify the Problem

 Bugs with Dynamic Loading

 Sending Data with Your Bug Report

 Contact Us

 What's New in IDL version 4.0.1

 Platforms Supported in this Release

 New and Modified Routines in IDL 4.0.1

 Widget Sizing

 Online Help Changes

 Callable IDL

 IDL for Windows Changes

 Bugs Fixed in this Release

 What's New in IDL version 4.0

 Changes to IDL Directory Tree

 IDL Documentation Changes

 IDL Language Enhancements

 Miscellaneous New Features

 New Keywords to Existing Routines

 Widget Enhancements

 Mathematics Improvements

 IDL Statistics Library Revisions

 IDL for Macintosh Enhancements

 IDL for Windows Enhancements

 More IDL Resources

 Contacting Research Systems

 Research Systems Internet Resources

 IDL Training

 ENVI

 Visible Human CD

 Notes for Unix

 Notes for Windows

 Notes for Macintosh

 Changing Unix Online Help Defaults

 Serious OpenWindows Bug in SunOS 4.1.3 and 4.1.4"

 LD_LIBRARY_PATH on Sun Platforms

 Ultrix XDR Files and Double-precision Data

 Using IDL 4.0.1 under AIX 4.1

 Using IDL 4.0.1 with Research Systems' Visible Human CD-ROM

 Long Filenames not Supported in IDL for Windows

 Problems with ATI Graphics Cards

 System Languages other than English

 LINKIMAGE under Windows 3.1

 File Handles under Windows 3.1

 Hardware Port Routines under Windows NT

 Setting Environment Variables under Windows NT

 Using IDL in a Multiuser Windows NT Environment

 Running IDL on a PowerBook 160 or 180

 Printing Images from IDL for Macintosh

 Font/Display Problems with Online Help

 Notes on Filling Continental Boundaries