Using IDL: IDL Version 5.4 September, 2000 Edition
Using IDL: IDL Version 5.4 September, 2000 Edition
Using IDL 3
4
Chapter 3:
The IDL for Windows Interface ............................................................ 63
The Main IDL Window ................................................................................................... 64
IDLDE Windows ............................................................................................................. 67
The Menu Items ............................................................................................................... 69
Keyboard Shortcuts ......................................................................................................... 84
Customizing IDL ............................................................................................................. 86
Windows IDL Differences ............................................................................................... 98
Chapter 4:
The IDL for Motif Interface ................................................................. 101
The Main IDL Window ................................................................................................. 103
IDLDE Windows ........................................................................................................... 106
The Menu Items ............................................................................................................. 107
Keyboard Shortcuts ....................................................................................................... 121
Using Preferences to Customize IDLDE ....................................................................... 123
Using Resources to Customize IDL .............................................................................. 135
Command Line Options ................................................................................................. 137
Modifying the Control Panel ......................................................................................... 142
Action Routines ............................................................................................................. 145
Modifying the Macros Menu ......................................................................................... 152
CDE File Manager Support ........................................................................................... 153
Chapter 5:
The IDL for Macintosh Interface ........................................................ 155
The Main IDL Windows ................................................................................................ 156
IDL Document Windows ............................................................................................... 159
The Menus ..................................................................................................................... 163
Chapter 7:
Reading and Writing Images ............................................................. 215
List of Commands .......................................................................................................... 216
Accessing Image Files Using Dialogs ........................................................................... 219
Accessing General Image File Formats ......................................................................... 223
Accessing Specific Image File Formats ......................................................................... 224
Accessing Files Using Dialogs ...................................................................................... 226
Accessing Files With Compound Widgets .................................................................... 228
Chapter 8:
Reading and Writing ASCII Data ....................................................... 231
Overview ........................................................................................................................ 232
Reading an ASCII Data File .......................................................................................... 233
Advanced File Input/Output .......................................................................................... 237
Chapter 9:
Reading and Writing Binary Data ...................................................... 239
Overview ........................................................................................................................ 240
Reading a Binary Data File ............................................................................................ 241
Advanced File Input/Output .......................................................................................... 245
Chapter 11:
Direct Graphics Plotting ..................................................................... 253
Overview ........................................................................................................................ 254
Plotting Keyword Parameters ........................................................................................ 255
Direct Graphics Coordinate Systems ............................................................................. 256
Annotation – The XYOUTS Procedure ......................................................................... 265
Plotting Symbols ............................................................................................................ 267
Polygon Filling .............................................................................................................. 271
Tick Marks ..................................................................................................................... 275
Logarithmic Scaling ....................................................................................................... 278
Multiple Plots on a Page ................................................................................................ 280
Specifying the Location of the Plot ............................................................................... 282
Plotting Missing Data .................................................................................................... 284
Date/Time Plotting ......................................................................................................... 285
Using the AXIS Procedure ............................................................................................ 296
Using the CURSOR Procedure ...................................................................................... 300
Chapter 12:
Plotting Multi-Dimensional Arrays .................................................... 303
Overview ........................................................................................................................ 304
Contour Plots ................................................................................................................. 305
Overlaying Images and Contour Plots ........................................................................... 312
Additional Contour Options .......................................................................................... 316
The SURFACE Procedure ............................................................................................. 320
Three-Dimensional Graphics ......................................................................................... 323
Three-Dimensional Transformations ............................................................................. 333
Shaded Surfaces ............................................................................................................. 339
Volume Visualization .................................................................................................... 342
References ...................................................................................................................... 346
Chapter 13:
Map Projections .................................................................................. 347
Overview ........................................................................................................................ 348
The MAP_SET Procedure ............................................................................................. 349
The MAP_GRID Procedure .......................................................................................... 351
Chapter 14:
Image Display Routines ..................................................................... 379
Overview ........................................................................................................................ 380
Images ............................................................................................................................ 381
Imaging Routines ........................................................................................................... 382
Image Display ................................................................................................................ 383
Reading from the Display Device .................................................................................. 387
Color Tables ................................................................................................................... 389
TrueColor Displays ........................................................................................................ 396
Controlling the Device Cursor ....................................................................................... 400
References ...................................................................................................................... 401
Chapter 15:
Signal Processing ............................................................................... 403
Overview ........................................................................................................................ 404
Digital Signals ................................................................................................................ 405
Signal Analysis Transforms ........................................................................................... 408
The Fourier Transform ................................................................................................... 409
Interpreting FFT Results ................................................................................................ 410
Displaying FFT Results ................................................................................................. 411
Using Windows .............................................................................................................. 416
Aliasing .......................................................................................................................... 420
FFT Algorithm Details ................................................................................................... 421
The Hilbert Transform ................................................................................................... 422
The Wavelet Transform ................................................................................................. 424
Convolution ................................................................................................................... 425
Correlation and Covariance ........................................................................................... 426
Chapter 16:
Mathematics ........................................................................................ 441
IDL’s Numerical Recipes Functions ............................................................................. 443
Accuracy & Floating-Point Operations ......................................................................... 444
Arrays and Matrices ....................................................................................................... 446
Correlation Analysis ...................................................................................................... 450
Curve and Surface Fitting .............................................................................................. 454
Eigenvalues and Eigenvectors ....................................................................................... 457
Gridding and Interpolation ............................................................................................ 463
Hypothesis Testing ........................................................................................................ 465
Integration ...................................................................................................................... 468
Linear Systems ............................................................................................................... 473
Nonlinear Equations ...................................................................................................... 480
Optimization .................................................................................................................. 482
Sparse Arrays ................................................................................................................. 484
Time-Series Analysis ..................................................................................................... 487
Multivariate Analysis ..................................................................................................... 490
References ...................................................................................................................... 496
Chapter 18:
The Graphics Object Hierarchy ......................................................... 523
Overview ........................................................................................................................ 524
Scenes ............................................................................................................................ 525
Viewgroups .................................................................................................................... 526
Views ............................................................................................................................. 527
Models ............................................................................................................................ 528
Atomic Graphic Objects ................................................................................................ 529
Attribute and Helper Objects ......................................................................................... 530
The Rendering Process .................................................................................................. 531
Simple Plot Example ..................................................................................................... 533
Chapter 19:
Transformations .................................................................................. 535
Overview ........................................................................................................................ 536
Viewport ........................................................................................................................ 537
Projection ....................................................................................................................... 539
Eye Position ................................................................................................................... 541
View Volume ................................................................................................................. 543
Model Transformations .................................................................................................. 546
Coordinate Conversion .................................................................................................. 549
A Simple Example ......................................................................................................... 552
Virtual Trackball and 3D Transformations .................................................................... 555
Chapter 20:
Working with Color ............................................................................. 557
Overview ........................................................................................................................ 558
Color and Digital Data ................................................................................................... 559
Indexed Color Model ..................................................................................................... 560
Chapter 21:
Using Attributes and Helpers ............................................................ 569
Overview ........................................................................................................................ 570
Font Objects ................................................................................................................... 571
Palette Objects ............................................................................................................... 574
Pattern Objects ............................................................................................................... 575
Symbol Objects .............................................................................................................. 577
Tessellator Objects ......................................................................................................... 581
Chapter 22:
Working with Axes and Text .............................................................. 583
Overview ........................................................................................................................ 584
Axis Objects ................................................................................................................... 585
Text Objects ................................................................................................................... 603
Chapter 23:
Working with Plots and Graphs ......................................................... 607
Contour Objects ............................................................................................................. 608
Polygon Objects ............................................................................................................. 610
Polyline Objects ............................................................................................................. 615
Plot Objects .................................................................................................................... 616
Legend Objects .............................................................................................................. 620
A Plotting Routine ......................................................................................................... 623
Chapter 24:
Working with Surfaces ....................................................................... 627
Surface Objects .............................................................................................................. 628
Light Objects ................................................................................................................. 633
An Interactive Surface Example .................................................................................... 636
Chapter 25:
Working with Images .......................................................................... 639
Image Objects ................................................................................................................ 640
Colorbar Objects ............................................................................................................ 644
Saving an Image to a File ............................................................................................... 646
Chapter 26:
Working with Volumes ........................................................................ 649
Volume Objects ............................................................................................................. 650
Volume Object Attributes .............................................................................................. 652
Chapter 27:
Selecting Objects ................................................................................ 657
Selection and Data Picking ............................................................................................ 658
Selection ......................................................................................................................... 659
A Selection Example ...................................................................................................... 661
Data Picking ................................................................................................................... 662
A Data Picking Example ................................................................................................ 663
Chapter 28:
Using Destination Objects ................................................................. 665
Overview ........................................................................................................................ 666
Window Objects ............................................................................................................. 667
Using Window Objects .................................................................................................. 670
Instancing ....................................................................................................................... 672
Buffer Objects ................................................................................................................ 674
Clipboard Objects .......................................................................................................... 675
Printer Objects ............................................................................................................... 676
VRML Objects ............................................................................................................... 679
Chapter 29:
Subclassing from Object Graphics ................................................... 681
Creating Composite Classes or Subclasses .................................................................... 682
Chapter 30:
Performance Tuning Object Graphics ............................................... 685
Overview ........................................................................................................................ 686
Polygon Mesh Optimization .......................................................................................... 687
Overview
This chapter includes information about IDL, the IDL documentation set, and how to contact
Research Systems Technical Support. The following topics are covered in this chapter:
Using IDL 13
14 Chapter 1: Overview
About IDL
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. You 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.
• Support for OpenGL-based hardware accelerated graphics.
• 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 provided for
• common image standards: BMP, GEO TIFF, Interfile, JPEG, PICT, PNG,
PPM, SRF, TIFF, X11 Bitmap, and XWD.
• scientific data formats: CDF, HDF, and NetCDF.
• other data formats: ASCII, Binary, DICOM, DXF, WAV, and XDR.
• 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.
Typographical Conventions
The following typographical conventions are used throughout the IDL documentation
set:
• UPPER CASE type
IDL functions and procedures, and their keywords are displayed in UPPER
CASE type. For example, the calling sequence for an IDL procedure looks like
this:
CONTOUR, Z [, X, Y]
• Italic type
Arguments to IDL procedures and functions — data or variables you must
provide — are displayed in italic type. In the above example, Z, X, and Y are all
arguments.
• Square brackets ( [ ] )
Square brackets used in calling sequences indicate that the enclosed arguments
are optional. Do not type the brackets. In the above CONTOUR example, X
and Y are optional arguments. Square brackets are also used to specify array
elements.
• Courier type
In examples or program listings, things that you must enter at the command
line or in a file are displayed in courier type. Results or data that IDL displays
on your computer screen are shown in courier bold type. An example might
direct you to enter the following at the IDL command prompt:
array = INDGEN(5)
PRINT, array
Reporting Problems
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.
Bugs which are reported and verified in one release are corrected as soon as possible.
The relnotes.txt file accompanying each release includes information about new
features in that release, bug fixes, and known problems which may be of help.
This section is intended to help you report problems in a way which helps us to
address the problem rapidly.
Background Information
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 installation 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 installation number is assigned by us when you purchase IDL. The IDL version,
site number, and type of machine are printed in the output window when IDL is
started.
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 this information.
Under VMS, the DCL statement:
write sys$output f$getsyi("version")
On the Macintosh, select About this Macintosh from the apple menu.
Double Check
Before reporting a problem, 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?
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 nearly impossible to identify and correct.
Contact Us
To report a problem, contact us at the following addresses.
Mail
Research Systems, Inc.
4990 Pearl East Circle
Boulder, CO 80301
Telephone
(303) 786-9900
(303) 786-9909 (Fax)
(303) 413-3920 (IDL Technical Support direct line)
Electronic Mail
support@ResearchSystems.com
Running IDL
Using IDL 23
24 Chapter 2: Running IDL
Starting IDL
To run IDL under UNIX or VMS in command-line mode, enter idl at the operating
system prompt. To run the IDL Development Environment graphical user interface,
enter idlde at the UNIX prompt, or idl/de at the VMS prompt. To run IDL under
Windows or the Macintosh OS, double-click on the IDL icon. For a description of the
IDL graphical user interface, see Chapter 4, “The IDL for Motif Interface”, Chapter
3, “The IDL for Windows Interface”, or Chapter 5, “The IDL for Macintosh
Interface”.
Note
To start the IDLDE by double-clicking on a .pro file in the CDE File Manager on
HP-UX, Solaris, or Tru64 UNIX, you must ensure that the IDLDE is setup to
support the CDE File Manager. See “CDE File Manager Support” on page 153.
When IDL is ready to accept a command, it displays the IDL> prompt. 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 in Windows NT
3.51, or by right-clicking on the IDL shortcut icon in Windows 95 and
Windows NT 4.0) accurately reflects the location of the IDL executable file
idlde.exe.
Note
IDL will import preferences from IDL 5.1 or later versions.
Note
It is not necessary to explicitly import macros from previous releases of IDL on
UNIX, VMS, or Macintosh platforms. IDL preferences and macros are
automatically imported on these platforms.
If you do not want to import preferences and user-defined macros, select No and IDL
will start. If you want to import from a previous release, select Yes. The new Import
IDL Preferences dialog displays.
This dialog displays the paths to the previous IDL installations on your machine in
the drop-down list box. Select the path to the previous release of IDL from which to
import preferences and user-defined macros. If you want to import any user-defined
macros from this installation as well, select the Import Macros check box. Click
OK. The preferences and user-defined macros are imported and then IDL will start.
Note
If you chose not to import user-defined macros or if you want to import macros
from several previous installations, you can select Macros→Import, and select the
previous release from which to import the macros.
Start IDL with a runtime license. The file argument should be an IDL .sav file.
If no file is specified, IDL attempts to run a file named runtime.sav. If you are
interested in developing IDL runtime applications, please contact your
Research Systems sales representative.
-queue
For users of counted floating licenses, setting this command switch causes IDL
to wait for an available license before beginning an IDL task such as batch
processing.
-w
Start IDL with the graphical user interface. This is the same as entering idlde at
the command prompt.
-autow
Start IDL with the graphical user interface if possible, otherwise start IDL in
command-line mode.
-32
Start IDL in 32-bit mode, otherwise IDL starts in 64-bit mode by default for
those platforms that support 64-bit. If you have not installed the 64-bit version,
the 32-bit version will automatically be started. If you have not installed the
32-bit version, this flag will not work.
-nw
Run IDL in command-line mode no matter what. Note that specifying idlde -
nw at the command line will start IDL in command line mode.
See Chapter 4, “The IDL for Motif Interface” for additional command line
options for the graphical user interface.
VMS
• The VMS version of IDL accepts the following command line qualifiers:
/RUNTIME=file
Start IDL with a runtime license. The file argument should be an IDL .sav file.
If no file is specified, IDL attempts to run a file named runtime.sav. If you are
interested in developing IDL runtime applications, please contact your
Research Systems sales representative.
/QUEUE
For users of counted floating licenses, setting this startup command switch
causes IDL to wait for an available license before beginning an IDL task such
as batch processing.
/DE
Start IDL with the graphical user interface (same as /DE). If the NO prefix is
included, IDL starts in command-line mode.
/[NO]AUTOWINDOW
Start IDL with the graphical user interface if possible, otherwise start IDL in
command-line mode. If the NO prefix is included, IDL starts in command-line
mode.
/ARRAY_MEMORY
-queue
For users of counted floating licenses, setting this command switch causes IDL
to wait for an available license before beginning an IDL task such as batch
processing. To set this switch, change the shortcut properties of the IDL 5.4
desktop icon so that the target line reads:
C:\RSI-Directory\bin\bin.x86\idlde.exe -queue
where RSI-Directory is the directory where you have installed IDL.
Macintosh
• The Macintosh version of IDL does not accept command-line switches.
Quitting IDL
To quit IDL, do one of the following:
• Enter the EXIT command at the IDL command prompt.
• If you are running the IDL Development Environment (IDLDE), you can exit
by selecting the Exit option from the File menu.
• Type Alt+F4 (Windows) or Command+Q (Macintosh)
Note
On Windows, using the IDL_DLM_PATH environment variable is the only way to
specify the path to DLMs.
IDL_HELP_PATH
Set this environment variable equal to the path to the directory or directories
containing IDL help files. Setting this value is the same as setting the value of the
IDL system variable !HELP_PATH. For information on expanding
IDL_HELP_PATH, see “Path Expansion” on page 33.
IDL_PATH
Set this environment variable equal to the path to the directory or directories
containing IDL library (.pro and .sav) files. Setting this value is the same as setting the
value of the IDL system variable !PATH. For information on expanding IDL_PATH,
see “Path Expansion” on page 33.
IDL_STARTUP
Set this environment variable equal to the path to an IDL batch file that contains a
series of IDL statements which are executed each time IDL is run. See “Startup File”
on page 58 for further details.
IDL_TMPDIR
IDL, and code written in the IDL language, sometimes need to create temporary files.
The location where these files should be created is highly system-dependent, and
local user conventions are often different from standard practice. By default, IDL
selects a reasonable location based on operating system and vendor conventions. Set
the IDL_TMPDIR environment variable to override this choice and explicitly specify
the location for temporary files.
The GETENV system function handles IDL_TMPDIR as a special case, and can be
used by code written in IDL to obtain the temporary file location. See GETENV in
the IDL Reference Guide for more information.
TERM
As with any X Windows program, IDL uses the standard UNIX environment variable
TERM to determine the type of terminal in use when IDL is in command-line mode.
LM_LICENSE_FILE
IDL’s FlexLM-based license manager uses the value of this environment variable to
determine where to search for valid license files. Consult the license manager
documentation for details.
The choice of qualifier or logical depends on the application. Values specified via the
ARRAY_MEMORY qualifier take precedence over those specified by the logical
name. Neither are required; IDL will provide defaults. The ability to set these values
is provided for those with a deep understanding of VMS memory management and
special requirements that the defaults don’t satisfy.
Path Expansion
The IDL_PATH, IDL_DLM_PATH, and IDL_HELP_PATH environment variables
support two special notations that cause IDL to expand the variables when they are
translated at startup time. These notations simplify the setting of these variables:
• Using “+” — When IDL translates the IDL_PATH, IDL_DLM_PATH, or
IDL_HELP_PATH environment variables, it looks for a leading + on each
directory, and if it is present, IDL searches the directory and all of its
subdirectories for files of the appropriate type for the path. Any directory
containing such files is added to the path. For more information, see
EXPAND_PATH in the IDL Reference Guide.
• Using “<IDL_DEFAULT>” — When IDL gets the value of the IDL_PATH,
IDL_DLM_PATH, and IDL_HELP_PATH environment variables, it replaces
any instances of the string <IDL_DEFAULT> with the default value IDL would
have assumed for the environment variable if it were not defined. Hence, to
pre-pend your directory to IDL’s default location in !DLM_PATH (under
UNIX):
% setenv IDL_DLM_PATH "/your/path/here:<IDL_DEFAULT>"
This substitution allows you to set up your paths without having to hard-code
IDL’s defaults into your startup scripts.
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 the
following table.
Note
You can change the number of lines to be recalled in the IDLDE Preferences. Select
File → Preferences... and adjust the number under the General option.
The line-editing abilities and the keys that activate them differ somewhat between the
different operating systems. The table below lists the edit functions and the
corresponding keys.
Move forward one Down arrow Down Down arrow Down arrow
line in recall buffer arrow
Redraw current line Ctrl+R Ctrl+R
Overstrike/Insert ESC-I Ctrl+A
EOF if current line Ctrl+D
is empty, else EOL
Search recall buffer At Xterm PF1, then ^ , then input
for text command input text at text in dialog
line: use ^ , prompt box
then input
text at
prompt.
At IDLDE
command
line: NA.
Insert the character any any any character any character
at the current character character
Executive
Commands
position
The command recall feature is enabled by setting the system variable !EDIT_INPUT
to a non-zero value (the default is 1) and is disabled by setting it to 0. See
“!EDIT_INPUT” in Appendix D of the IDL Reference Guide for details.
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 one. (in the IDL Development
Environment, you can set this value in the Preferences dialog as well.) 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 58 for more information
on startup files.)
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.
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 the
table below. See the IDL Reference Guide for in-depth descriptions of these
commands.
Command Action
.COMPILE Compiles text from files or keyboard without
executing
.CONTINUE Continues execution of a stopped program
.EDIT Opens files in editor windows of the IDLDE
(Windows and Motif only)
.FULL_RESET_SESSION Does everything .RESET_SESSION does, plus
additional reset tasks such as unloading sharable
libraries
.GO Executes previously compiled main program from
beginning
.OUT Continues program execution until the current
routine returns
.RESET_SESSION Resets much of the state of an IDL session without
requiring the user to exit and restart the IDL
session
.RETURN Continues execution until encountering a
RETURN statement
Command Action
.RNEW Erases main program variables and then executes
.RUN
.RUN Compiles and possibly executes text from files or
keyboard
.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)
.TRACE Similar to .CONTINUE, but displays each line of
code before execution
Note
With Xprinter 3.3.1 (UNIX) the config file is called .xprinterDefaults, however on
VMS, it is still called .xpdefaults.
Button Description
Apply Writes current configuration information to your default
printer information file $HOME/.Xpdefaults.
Save Writes current configuration information to your default
printer information file $HOME/.Xpdefaults.
Reset Reloads default configuration from $HOME/.Xpdefaults.
Cancel Closes dialog and cancels all configuration changes.
Options Displays the options dialog box that lets you select an
alternate printer setup. This button is disabled if output is
configured to be sent to a file instead of a printer.
Install Displays the installation dialog box that allows you to add or
remove printer devices and printer ports from the
$HOME/.Xpdefaults file.
Option Description
Output Format: Specify whether to send output to a file or a printer. If you
choose Printer Specific, you can send output to any printer
type/port combination configured in your $HOME/.Xpdefaults
file. If the port is FILE: (as in the example here), Xprinter
creates an output file for the specified printer type. If you
choose Generic (File Only), print output is sent to an
Encapsulated PostScript or generic PCL file.
Printer: This field appears only if you select Output Format: Printer
Specific. It specifies the name of the default printer type/port
to which to send print output. Click the Options button to
specify a different printer type/port combination.
File Name: This field appears only if you choose Output Format: Generic
(File Only). Type the name of the print file you wish to create.
To pipe print output to a command, enter a ! character as the
first character and then specify the command to which to send
output. For example, to send output to the lp command, enter
the following:
!lp -d ps
EPSF This field only appears if you select Output Format: File.
PCL4 Click this button to display a list of output file types and select
the desired type. Available types are EPSF (Encapsulated
PCL5 PostScript), PCL4, and PCL5.
Orientation Specify portrait or landscape.
Scale To increase the size of the output, specify a value greater than
1.00. To reduce the size, specify a value less than 1.00. For
example, a value of 2.00 would double the size of the output;
a value of 0.50 would reduce it by half.
Copies Specify the number of copies to print.
To set additional options, such as selecting a different printer or changing the page
size, click the Options button. The Options dialog appears.
Option Description
Printer Name Use this field to change the Printer on the Setup dialog. Click
the down arrow to display a list of configured printers.
Resolution Specify printer resolution with this field. Values vary
depending on printer.
Page Size Specify paper size with this field. Values vary depending on
printer.
Paper tray Specify paper tray with this field. Values vary depending on
printer.
Duplex Specify duplex options (if the selected printer supports duplex
printing). Valid values include None (no duplex printing),
Duplex Tumble (flips over the short edge), and Duplex No
Tumble (flips over the long edge). If the selected printer does
not support duplexing, this field is disabled.
Type the port definition in the Edit Port edit box. Port definitions have the following
format:
port=print_command
The print_command is the command for sending output to the printer port. If you
were to have two printers named ORION and SIRIUS for example, the definitions
would appear as follows:
ORION=rsh bandit "lp -d ps"
SIRIUS=rsh bandit "lp -d ps -T pcl5"
Both printers here are connected to the system bandit, so the print command is a
remote shell command executed on bandit. ORION is a PostScript printer, so the
command lp -d ps is executed on bandit to print to ORION. SIRIUS though is a PCL5
printer, so the print command executed on bandit to print to SIRIUS is lp -d ps -T pcl5.
• Click Add/Replace and the new port is now included in the list of current port
definitions.
• Repeat the above step for each printer to which you wish to send output.
Note
To create a printer port for each available queue on hp700 systems, click the
Spooler button on the Ports dialog. This command creates a default printer port for
each available printer queue returned by the lpstat -a command.
• Select the desired port in the Current Port Definitions list box and click Add
Selected. The new printer is now included in the list of currently installed
printers.
For this Printer Name, FILE: is the port name. To send output to a printer instead of a
file, you first must define a port for each printer to which you wish to direct output.
Port entries in the [ports] section have this format:
port=print_command
The print_command is the command for sending output to the printer port. For
instance, if you have two printers (ORION and SIRIUS), your [ports] section may
appear as follows:
[ports]
ORION=rsh bandit "lp -d ps"
SIRIUS=rsh bandit "lp -d ps -T pcl5"
In the above, both printers are connected to the system bandit, so the print command
is a remote shell command executed on bandit. ORION is a PostScript printer, so the
command lp -d ps is executed on bandit to print to ORION. SIRIUS, though, is a
PCL5 printer, and thus the print command executed on bandit to print to SIRIUS is lp
-d ps -T pcl5.
If a printer is connected to your local system, you will need to add an entry for that
printer as well. For the local printer, your entry should be like the following:
[ports]
ORION=rsh bandit "lp -d ps"
SIRIUS=rsh bandit "lp -d ps -T pcl15"
LOCAL=lp -d ps
Your printer port can be any name you choose except FILE:, which is the only
reserved port name. It causes Xprinter to create a print file formatted specifically for
the specified printer type.
An entry must be created in the [ports] section for every printer to which you wish to
be able to print.
Note
There must be a space between the PPD_file and driver and a comma between the
driver and the port. The following table describes each part of this entry.
Field Description
alias The alias is a descriptive name used to identify the printer. It
can be anything you choose. The alias is the name which
appears in the Printer Setup dialog (such as HP LaserJet III SI
PostScript).
PPD_file The PPD_file is the name of the printer description (PPD) file
used by the printer, without a .PPD extension. Search in the
directory $XPHOME/xprinter/ppds/ to find the PPD file for
your printer.
driver The driver is the type of driver your printer uses. Value values
are PostScript, PCL4, and PCL5.
port The port is the printer port as listed in the [ports] section of
the .Xpdefaults file (ORION, SIRIUS, and LOCAL in the
example [ports] section).
First, be sure to choose an alias for each printer. In order to make it simpler to
identify the printer from the Printer Setup dialog you wish to use, you may use the
following aliases:
HP LaserJet PS
HP LasterJet PCL
QMS PS
It is important to note that if you utilize the Printer Setup dialog to associate ports and
PPD files, you cannot specify a printer alias. You must instead choose an alias from
the predefined listing that appears in the Printer Devices list box in the Add Printer
dialog. The corresponding PPD file is already associated with the printer aliases in
this list box.
Now, identify the PPD file associated with each of these printers. In the
$XPHOME/xprinter/ppds/filename.map file, you can find a PPD file for the printer on
port ORION (hp3si523.ppd)a PPD file for the printer on port LOCAL (q2200523.ppd),
and a PPD file for the printer on port SIRIUS (hp4m.ppd).
Thus the [devices] section of the .Xpdefaults file would be as follows:
[devices]
HP LaserJet PS=HP3SI523 PostScript,ORION
HP LaserJet PCL=HP4M PCL,SIRIUS
QMS PS=Q2200523 PostScript,LOCAL
After these entries have been added to your .Xpdefaults file, the following printer
choices are available from the Printer Setup dialog:
HP LaserJet PS on ORION
HP LaserJet PCL on SIRIUS
QMS PS on LOCAL
Simply provide the same information that you used in the [devices] section. Only the
format of the entry is different; there is a comma between the PPD_file and the driver
instead of a space.
For example, suppose you wish the default printer to be the printer at port ORION.
The [windows] section would appear as follows:
[windows]
device=HP3SI523,PostScript,ORION
[ports]
ORION=rsh bandit "lp -d ps"
SIRIUS=rsh bandit "lp -d ps -T pcl5"
LOCAL=lp -d ps
[devices]
HP LaserJet PS=HP3SI523 PostScript,ORION
HP LaserJet PCL=HP4M PCL,SIRIUS
QMS PS=Q2200523 PostScript,LOCAL
Since no PPD file is listed (NULL), the default on the Printer Setup dialog is to print
generic PostScript to a file. You may specify the filename and change the type of
output to PCL on the Printer Setup dialog.
Specifying Printer-Specific Options
You may include a section that lists the default printer-specific options for each
printer defined in the devices section. The options available vary between differing
printers, but typical options include number of copies, page size, paper tray, and
orientation. An example follows of a printer-specific section for a default printer in
the example .Xpdefaults file:
[HP3SI523,PostScript]
Scale=0.80
Copies=1
PaperTray=Lower
PageSize=Letter
Orientation=Portrait
DPI=300
Printing Graphics
Beginning with IDL version 5.0, IDL interacts with a system-level printer manager to
allow printing of both IDL Direct Graphics and IDL Object Graphics. On Windows
and Macintosh platforms, IDL uses the operating system’s built-in printing facilities;
on UNIX and VMS platforms, IDL uses the Xprinter print manager from Bristol
Technology.
Use the DIALOG_PRINTERSETUP and DIALOG_PRINTJOB functions to
configure your system printer and control individual print jobs from within IDL.
Note
IDL does not support tiling or printing multi-page documents.
example, a file might contain three procedures and two functions and also might be
included in another file.
See Chapter 9, “Introduction to IDL Programming” in the Building IDL Applications
manual for more information on creating programs in IDL.
Warning
If the current directory contains a subdirectory with the same name as filename, IDL
will consider the file to have been found and stop searching. To avoid this problem,
specify the extension (.pro or .sav, usually) when entering the run, compile, or batch
file command.
The details of how !PATH is initialized and used differ between the various operating
systems, although the overall concept is the same. See “!PATH” in Appendix D of
the IDL Reference Guide for more information.
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.
Aborting IDL
If you find it necessary to abort IDL rather than exiting cleanly using the EXIT
command, do one of the following:
• UNIX: As with any UNIX process, IDL can be aborted by typing Ctrl+\.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 Ctrl+\, 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:
• VMS: As with any VMS program, IDL can be aborted by typing Ctrl+Y.
Aborting IDL with Ctrl+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.
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).
IDL only searches the !PATH directories for .sav and .pro files. There are two ways to
get IDL to execute your batch/include file:
• Add the directory with your batch file to !PATH, and make sure it has a .pro
extension (e.g. "mybatch.pro")
• Make the directory with your batch files the working directory, either by
launching IDL from there, or using the CD routine
The only way to execute a simple ASCII batch/include file that does not have a .pro
extension is if it is in the working directory, or if you supply the full path
specification.
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.
; This will not work in batch mode.
FOR I = 1, 10 DO BEGIN
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:
@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 program A:
. RUN proga
; Run program B:
. RUN progb
; Print results:
PRINT, AVALUE, BVALUE
; Close unit 3:
CLOSE, 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.
Startup File
The startup file is an IDL batch file that contains a series of IDL statements which are
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 startup 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 startup 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 startup 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 startup 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.
Non-Interactive IDL
Under UNIX and VMS, 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. 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.
Note
If you want IDL to display anything to a window in non-interactive mode, IDL
requires that a valid DISPLAY environment variable be set. This means that you
must be logged into a machine to which IDL has access, and that the DISPLAY
environment variable be set to that machine. This is only a requirement when
displaying to screen device. To avoid this requirement, you could use another
device such as the Z buffer or PostScript device.
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'
Note
Save files that contain IDL procedures, functions, and programs are not always
portable between different versions of IDL. In this case, you will need to recompile
and then save the files in the current version of IDL.
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]
Warning
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,
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:
;Start journaling to file demo.pro:
JOURNAL, 'demo.pro'
;Prompt for input:
PRINT, 'Enter a number:'
;Read the user response into variable Z:
READ, Z
;Send an IDL comment to the journal file using JOURNAL:
JOURNAL, '; This was inserted with JOURNAL.'
;Send another comment using PRINTF:
PRINTF, !JOURNAL, '; This was inserted with PRINTF.'
;End journaling:
JOURNAL
If these statements are executed by a user named Doug on a Sun workstation named
quixote, the resulting journal file demo.pro will look like the following:
; IDL Version 5.3 (sunos sparc)
; Journal File for doug@quixote
; Working directory: /home/doug/IDL
; Date: Mon Sept 9 14:38:24 1999
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.
Using IDL 63
64 Chapter 3: The IDL for Windows Interface
Menu Bar
Tool Bar
Projects Window
Multiple
Document
Panel
Output Log
Variable Watch
Window
Command
Input Line
Status Bar
Docking/Undocking
Four sections of the IDLDE can be moved within and unanchored from the main
IDLDE window: the Tool Bar, Output Log, Variable Watch Window, and
Command Input Line. Click on the border and drag the left mouse button. You will
notice the outline of the section you have chosen moving with your mouse. When you
are satisfied with a location, let go of the mouse button to dock the window. If you
move this outline so that it overlaps an edge of the window space being used by the
IDLDE, the section will be docked to the nearest available side of the main IDLDE
window. The Tool Bar, Output Log, Variable Watch Window, and Command
Input Line will remain between the Menu Bar and the Status Bar when docked.
They can be docked in any order against an edge. If the outline doesn’t overlap an
edge, the section will float on the desktop. If you hold down the [Ctrl] key, the
sections will float on the desktop instead of docking to the nearest available side of
the IDLDE.
Menu Bar
The menu bar, located at the top of the main IDL window, has features which enable
you to control various IDLDE features. When you select an option from a menu item
in the IDLDE, the Status Bar displays a brief description.
Tool Bars
You can choose any combination of three tool bars: Standard, Run & Debug, and
Macros. To change the toolbars displayed, use the Windows menu to access the
Toolbar pulldown menu and select or de-select any combination of the three
toolbars. In addition, when you open a GUIBuilder window, its associated toolbar is
displayed.
When you position the mouse pointer over a Toolbar button, the Status Bar displays
a brief description. If you click on a Toolbar button which represents an IDL
command, the IDL command issued is displayed in the Output Log.
Project Window
IDL Project Window allows you to manage, compile, run, and create distributions of
all the files needed to develop an IDL application. All of your application files can be
organized for ease of access, and to be easier to export to other developers,
colleagues, or users. For further information on the Projects Window, refer to Chapter
13, “Creating IDL Projects” in Building IDL Applications.
Output Log
Output from IDL is displayed in the Output Log window, which appears by default
when IDLDE is first started. The Output Log area can be sized by moving the
separator attached to the top of the Output Log. You can hide/display the Output Log
by clicking the Output Log toggle item in the Windows menu, by pressing
[Ctrl+L], or by changing the Layout tab from Preferences in the File Menu. If you
click the right mouse button while positioned over the Output Log, a popup menu
appears allowing you to move to a specified error. Clear the contents of the Output
Log, or copy selected contents.
Status Bar
When you position the mouse pointer over a Toolbar button or select an option from
a menu in IDLDE, the Status Bar displays a brief description. The Status Bar can
be made invisible by clicking the Status Bar toggle item in the Windows menu or by
changing the Layout tab from Preferences in the File menu.
IDLDE Windows
Three types of windows can be created within the IDLDE: IDL Editor windows, IDL
GUIBuilder windows, and IDL Graphics windows.
When you minimize a GUIBuilder window, a Windows title bar with the name of the
file appears in the Multiple Document Panel.
For information about the IDL GUIBuilder, see Chapter 21, “Using the
IDL GUIBuilder” in Building IDL Applications.
Warning
If the backing store is not set when a window is iconized, it will not be refreshed
upon return. For more information about setting the backing store for graphics
windows, see “Graphics Preferences” on page 90.
File Menu
The File menu accesses and manipulates files.
New
From this option you can select Editor [Ctrl+N], GUI, or Project. If you select
Editor, a new IDL Editor window is opened. If you select GUI, a new IDL
GUIBuilder file is opened. If you select Project, the New Project dialog displays.
Each window is titled Untitledn or UntitledPrcn until saved with another name, n
being the numerical order of the new window opened.
For information about the IDL GUIBuilder, see Chapter 21, “Using the
IDL GUIBuilder” in Building IDL Applications.
Open... [CTRL+O]
Select this option to open a text file or a GUIBuilder *.prc portable resource file for
editing. The Open dialog appears. Select the file you want to open and click Open.
You can select a continuous range of files by holding down the Shift key after
selecting the first file. You can also select multiple separated files by selecting each
file while holding down the Control key. A new IDL Editor window is created to
contain each text file.
You can also open text files from the Command Input Line. To open text files, enter
the following at the IDL prompt:
.EDIT file1 [file2 ... filen]
where file is the name of the text file you want to open. If the path is not specified in
the Path Preferences from the File menu, you must enter the full path for file. See
.EDIT in the IDL Reference Guide for more information.
Close
Select this option to close the currently-selected IDL Editor window. If you have
made changes in an IDL Editor window, you are asked if you want to save the
changes before closing the window.
Open Project...
Select this option to open a new IDL Project. The Open dialog appears. Select the
project you want to open and click Open.
Save Project
Select this option to save the current IDL Project. If the Project has not yet been
saved, you are prompted for a filename with the Save As dialog.
Save Project As...
Select this option to save the current IDL Project to a specified filename. The Save
As dialog appears.
Close Project
Select this option to close the current IDL Project. If you have made changes in to the
project, you are asked if you want to save the changes before closing the window.
Save [Ctrl+S]
Select this option to save the contents of an IDL Editor window. If the file has not yet
been saved, you are prompted for a filename with the Save As dialog.
Note
Changes made to a previously-compiled routine are not available to IDL until that
routine is re-compiled. Executing the routine without first saving and re-compiling
simply re-runs the previously-compiled version, without incorporating recent
changes.
Select the Compile option in the Run menu to return to the main program level and
re-compile the routine. Select Compile from Memory in the Run menu to save
and compile recent changes to a temporary file.
Save As...
Select this option to save the contents of an IDL Editor window to a specified
filename. The Save As dialog appears.
Revert to Saved
Select this option to reload the last saved version of the document.
Warning
Unsaved changes are lost without warning.
Generate .pro
Select this option to generate source code files from GUIBuilder interface definitions.
When you generate code for the first time, all options open the Save As dialog so that
you can select a location and specify a filename. The following are generated:
• The widget definition code to a *.pro file.
• The event-handler callback code to a *_eventcb.pro file.
For information about the IDL GUIBuilder generated code, see “Generating Files” in
Chapter 21 in Building IDL Applications.
Print... [CTRL+P]
Select this option to print the contents of the currently-selected window to the
currently-active printer. The Print dialog appears. Use the Printers icon in the
Microsoft Windows Control Panel (found in the Main program group) to change the
currently-selected printer.
Print Setup...
Select this option to change the printer and printing options.
Recent Files
Select this option to view or open recently opened or created files. This menu item
lists the last ten opened or created files, and it includes both text and GUIBuilder
files. To open a file on this list, select it.
Recent Projects
Select this option to view or open recently opened project files.
Preferences...
Select this option to display a dialog box containing seven tab selections with which
you can customize your interaction with the IDLDE environment. The seven
categories are: General, Layout, Graphics, Editor, Startup, Fonts and Path. For more
information about the Preferences, see “Customizing IDL” on page 86.
Tab Description
General This tab allows you to specify how the IDLDE begins and
ends, to control the number of lines in the recall buffer and the
Output Log, and to designate how the files should be opened
and read.
Layout This tab allows you to specify the location and size of the
main window on the screen. You can also designate which
components of the IDLDE will be visible.
Graphics This tab allows you to set the layout of the graphics window
and to specify the backing store.
Editor This tab allows you to customize the built-in IDL editor and
also offers several compiling options.
Startup This tab allows you to specify the main directory, the working
directory, and the startup file.
Fonts This tab allows you to specify different fonts, styles, and sizes
for the Editor, Command Input Line and Output Log.
Path This tab allows you to specify the IDL Files Search Path.
Your entries are appended to the system variable !PATH.
Exit Select this option to exit IDL for Windows. All IDL Editor
windows are closed before exiting. If text in an Editor
window has changed, you are prompted to save it before
exiting.
Exit [CTRL+Q]
Select this option to exit IDL.
Edit Menu
Undo [CTRL+Z]
Select this option to undo previous editing actions. Multiple undo operations are
supported; the first reverses the most recent operation, the next reverses the second
most recent operation, etc. If the most recent action is irreversible, this option will not
be accessible.
Redo [CTRL+Y]
Select this option to redo previously undone editing actions. Multiple redo operations
are supported; the first redo reverses the most recent undo, etc.
Cut [CTRL+X]
Select this option to remove currently-selected text from an IDL Editor window or
the Command Input Line to the Windows clipboard.
Copy [CTRL+C]
Select this option to copy the currently-selected text in an IDL Editor window,
Output Log window, or Command Input Line to the clipboard. Copy also allows you
to copy graphics from an IDL graphics window or draw widget to the clipboard.
Paste [CTRL+V]
Select this option to paste the contents of the Windows clipboard at the current
insertion point. The insertion point can only be placed in an IDL Editor window.
Delete [DEL]
Select this option to delete the currently-selected text. The deleted text is not placed
on the clipboard.
Select All
Use this option to highlight the entire contents of an IDL Editor window.
Clear All [CTRL+DEL]
Use this option to clear the entire contents of an IDL Editor window.
Clear Log
Use this option to clear the entire contents of the Output Log.
Properties
Select this option to open the GUIBuilder Properties dialog, which you can use to set
the attribute and event properties for a widget.
For information on the Properties dialog, see “Using the Properties Dialog” in
Chapter 21 in Building IDL Applications.
Menu
Select this option to open the GUIBuilder Menu Editor, which you can use to define
menus for top-level base widgets and button widgets.
For information on the Menu Editor, see “Using the Menu Editor” in Chapter 21 in
Building IDL Applications.
Search Menu
Find... [CTRL+F]
Select this option to find text in an IDL Editor window or windows. The Search
dialog appears.
Enter the text to find in the field marked Search for: or choose an entry from the
pulldown list of recent search terms. To replace the found text with new text, check
the Replace with checkbox. Enter the replacement text in the field or choose an entry
from the pulldown list of recent replacement terms.
Click Find next to highlight the search text in your file. Click Replace to replace the
selected text.
Check the Case sensitive checkbox to match the case of the text you enter. Check
Whole words only to match only entire words (the default is to match sub-strings).
To replace all instances of the search text, check the Replace all checkbox and click
Replace. Select Forward from cursor or Backward from cursor to specify the
direction in which you would like to begin the search, or Entire file to search from
the beginning of the file.
By default, the search will take place in the currently-selected window. Choose a
different file or All Windows from the pulldown list marked Search in file to search
other windows.
Find Again [F3]
Select this option to repeat the previous Find.
Find Selection [CTRL+E]
Select this option to find the next occurrence of the selected text in an IDL Editor
window.
Replace... [CTRL+H]
Select this option to find text in an IDL Editor window and replace it with new text.
The Replace dialog box appears. The Replace dialog has the same controls as the
Search dialog, described above in the Find item. By default, the Replace with
checkbox is checked.
Replace Again [SHIFT+F3]
Select this option to repeat the previous Replace.
Go To Line... [CTRL+G]
Select this option to jump directly to the specified line number in an IDL Editor
window. The Go To Line dialog appears.
Go To Definition [CTRL+D]
Use this option to go to and mark with a current line indicator (blue arrow) the
procedure or function call of the item next to which the cursor is positioned. The item
must be either user-defined or a procedure or function written in IDL, and must have
been compiled during the current IDLDE session.
Run Menu
Run Menu items are enabled when an IDL program is loaded into an IDL Editor
window and compiled. If you click the right mouse button while positioned over an
editor window, a popup menu appears allowing you to quickly access several of the
most convenient commands. The popup menu changes to display common debugging
commands if IDL is running a program. See Chapter 18, “Debugging an IDL
Program” in Building IDL Applications for more information.
Compile filename.pro [CTRL+F5]
Select this option to compile a .pro file. The currently-selected file is only recognized
as an IDL procedure or function if suffixed with .pro. Selecting this option is the
same as entering .COMPILE at the Command Input Line, with the appropriate Editor
window selected in the Multiple Document Panel.
You can also compile files from the Command Input Line. Enter the following at the
IDL prompt:
.COMPILE file1 [file2 ... filen]
where file is the name of the file you want to open. IDL opens your files in editor
windows and compiles the procedures and functions contained therein. If the path is
not specified in the Path Preferences from the File menu, you must enter the full
path for file.
See .COMPILE in the IDL Reference Guide for a more detailed explanation.
Warning
In order for the Run option to reflect the correct procedure name in the Run menu,
the .pro filename must be the same as the main procedure name. For example, the
file named squish.pro must include:
pro squish
Resolve Dependencies
Select this option to iteratively compile all un-compiled IDL routines that are
referenced in any open and compiled files. Selecting this option is the same as
entering RESOLVE_ALL, /QUIET at the Command Input Line. The QUIET keyword
suppresses informational messages. See RESOLVE_ALL in the IDL Reference
Guide for a more detailed explanation.
Profile
Select this option to access the Profile dialog. The IDL Code Profiler allows you to
analyze the performance of your applications. You can identify which modules are
used most frequently, and which modules take up the greatest amount of time.For
more information about the IDL Code Profiler, see “The IDL Code Profiler” in
Chapter 14 of Building IDL Applications.
Note
This option is not available if a blocking widget is currently active.
Break [CTRL+BREAK]
Select this option to interrupt program execution. IDL inserts a marker to the left of
the line at which program execution was interrupted.
Stop [CTRL+R]
Select this option to stop program execution and return to the main program level.
Selecting this item is the same as entering the following at the Command Input
Line:
RETALL
WIDGET_CONTROL,/RESET
CLOSE, /ALL
HEAP_GC, /VERBOSE
entering .STEP at the IDL Command Input Line. See .STEP in the IDL Reference
Guide for a more detailed explanation.
Step Over [F10]
Select this option to execute a single statement in the current program. The current-
line indicator advances one statement. If the statement which is stepped over calls
another IDL procedure or function, statements from that procedure or function are
executed to the end without interactive capability. Selecting this item is the same as
entering .STEPOVER at the IDL Command Input Line. See .STEPOVER in the IDL
Reference Guide for a more detailed explanation.
Step Out [CTRL+F8]
Select this option to continue processing until the current program returns. Selecting
this item is the same as entering .OUT at the IDL Command Input Line. See .OUT in
the IDL Reference Guide for a more detailed explanation.
Trace...
Select this option to access the Trace Execution dialog. You can modify the interval
between successive .STEP or .STEPOVER commands, depending on whether Step
into routines or Step over routines is checked. The current-line indicator points to
program lines as they are executed. Selecting this item at full speed is the same as
entering .TRACE at the IDL command prompt. See .TRACE in the IDL Reference
Guide for a more detailed explanation.
Run to Cursor [F7]
Select this option to execute statements in the current program up to the line where
the cursor is positioned. Selecting this item is the same as setting a one-time
breakpoint at a specific line. See BREAKPOINT in the IDL Reference Guide for a
more detailed explanation.
Run to Return [CTRL+F7]
Select this option to execute statements in the current procedure or function up to the
line where the return is positioned. Selecting this item is the same as setting a one-
time breakpoint at a specific line. See .RETURN in the IDL Reference Guide for a
more detailed explanation.
Set Breakpoint [F9]
Select this option to set a breakpoint on the current line.
See Chapter 18, “Debugging an IDL Program” in Building IDL Applications for a
more detailed explanation.
Disable Breakpoint
Select this option to access disable a breakpoint in the current line.
See Chapter 18, “Debugging an IDL Program” in Building IDL Applications for a
more detailed explanation.
Edit Breakpoint...
Select this option to access the Edit Breakpoint dialog.
See Chapter 18, “Debugging an IDL Program” in Building IDL Applications for a
more detailed explanation.
Up Stack [CTRL+Up]
Select this option to move up the call stack by one.
Down Stack [CTRL+Down]
Select this option to move down the call stack by one.
List Call Stack
Select this option to display the current nesting of procedures and functions.
Selecting this item is the same as entering HELP, /TRACEBACK at the IDL Command
Input Line. See HELP in the IDL Reference Guide for a more detailed explanation.
Project Menu
For more information on the following menu items, see Chapter 13, “Creating IDL
Projects” in Building IDL Applications.
Add/Remove Files...
Select this option to add or remove files from the current project.
Groups...
Selecting this option displays the Project Groups dialog from which you can create
a new group or rename, remove, move up or down, or set to filter specific file types
for the default groups within an IDL Project.
Options...
Select this option to change the options for a project. The Project Options dialog is
displayed.
Compile
Select this option to compile files in a project. You can choose either All Files to
compile all the source files in a project or Modified Files to compile only the files
that have been modified since the last compile.
Build
Select this option to build your project.
Run
Select this option to run the application defined by your project.
Export
Select this option to export your project.
Macros Menu
Edit...
Select this item to access the Edit Macros dialog. Macros which have already been
defined are listed in the Macros: field. To edit a macro, click on the macro to access
its characteristics and click OK when your adjustments are complete.
To add a macro, click Add..., which will access the Add Macro dialog. Enter the
name of the new macro in the given field and click OK. Enter the IDL command to
be executed by the new macro in the IDL Command: field. Enter the menu item
name, the full path to the toolbar bitmap file, the tooltip text, and the status bar text in
the appropriate fields. Select the accelerator by specifying the key in the Key: field
and then optionally clicking on any combination of Ctrl, Alt and Shift.
Note
Bitmap files for toolbar buttons must be 16 pixels by 16 pixels, and must contain
256 colors or fewer.
To remove a macro, click Remove. To change the position of a macro in the Macro
menu and on the Macro Toolbar, click on the macro to highlight it and click on
either Move Up or Move Down.
Import...
Use this menu selection to display the Import Macros dialog box. Use this dialog to
select the previous IDL installation from which you want macros to be imported.
Print Var
Select this option to print the selected variable. Selecting this item is the same as
entering PRINT, x at the IDL Command Input Line, where x is the selected variable.
Help On Var
Select this option to list attributes of the selected variable. Selecting this item is the
same as entering HELP, x, /STRUCTURE at the IDL Command Input Line, where x is
the selected variable.
Import Image
Select this option to import an image file into IDL. For more information, see “Using
Macros to Import Image Files” on page 193.
Import ASCII
Select this option to import an ASCII file into IDL. For more information, see “Using
Macros to Import ASCII Files” on page 197.
Import Binary
Select this option to import a binary file into IDL. For more information, see “Using
Macros to Import Binary Files” on page 203.
Import HDF
Select this option to import an HDF file into IDL. For more information, see “Using
Macros to Import HDF Files” on page 210.
Demo
Select this option to access IDL’s Demo application.
Window Menu
Next [F6]
Select this option to shift IDL’s focus to the next numbered editor window.
Previous [SHIFT+F6]
Select this option to shift IDL’s focus to the previous numbered editor window.
Cascade
Select this option to cascade all the IDL Editor windows within the main window.
Tile Horizontally
Select this option to tile all the IDL Editor windows on top of one another within the
main window.
Tile Vertically
Select this option to tile all the IDL Editor windows side-by-side within the main
window.
Arrange Icons
Select this option to arrange all minimized Editor or Graphics windows.
Close All
Select this option to close all IDL Editor windows. If the text within an IDL Editor
window has changed, you are asked if you want to save the file before closing.
Command Input [CTRL+I]
If this menu item has a check mark by it, the IDL Command Input Line is visible in
the main IDL window. If this item does not have a check mark next to it, the IDL
command input line is not visible. Click on this menu item to toggle between the two
states.
Output Log [CTRL+L]
If this menu item has a check mark by it, the Output Log is visible in the main IDL
window. If this item does not have a check mark next to it, the Multiple Document
Panel is maximized in the main IDL window. Click on this menu item to toggle
between the two states.
Variable Watch [CTRL+A]
If this menu item has a check mark by it, the Variable Watch Window is visible in
the main IDL window. If this item does not have a check mark net to it, the Variable
Watch Window is not visible. Click on this menu item to toggle between the two
states.
Project
If this menu item has a check mark by it, the Project Window is visible in the main
IDL window. If this item does not have a check mark net to it, the Project Window
is not visible. Click on this menu item to toggle between the two states.
Toolbars
Select this option to access a pulldown menu with the three Windows toolbars:
Standard, Run & Debug, and Macros. If a toolbar has a check mark by it, it is
visible below the Menu bar items.
Status Bar
If this menu item has a check mark by it, the Status bar is visible at the very bottom
of the Main IDL window.
Numbered Windows
The numbered menu items at the bottom of the Window menu display open files.
Select any of these menu items to make that window the current window.
Help Menu
Contents...[CTRL+F1]
Select this menu item to display the IDL Online Help Viewer.
Find Topic... [F1]
Select this menu item to display the Search dialog for IDL Online Help.
Help on the IDL Dev Env...
Select this menu item to display this chapter of Using IDL.
Help on the IDL Language...
Select this menu item to display information on the IDL language.
Help on Help...
Select this menu item to learn about how to use Help.
About IDL...
Select this option to display information on the IDL version in use.
Keyboard Shortcuts
Most of the menu options can be accessed from the keyboard instead of clicking on
the menus. The following table lists all of the available keyboard equivalents. Note
that these equivalents are also shown to the right of each menu item in the menus
themselves.
Keyboard
Function
Shortcut
Ctrl+A Toggle Variable Watch Window
Ctrl+C Copy selection to clipboard
Ctrl+D Go to definition
Ctrl+E Find highlighted selection
Ctrl+F Start Find dialog
Ctrl+G Start Go To Line dialog
Ctrl+H Start Replace dialog
Ctrl+I Toggle Command Input Line
Ctrl+L Toggle Output Log
Ctrl+N Open new file
Ctrl+O Open file
Ctrl+P Print currently-active file
Ctrl+Q Exit IDL
Ctrl+R Stop the IDL environment
Ctrl+S Save currently-active file
Ctrl+V Paste selection from clipboard at
insertion point
Ctrl+X Cut selection to clipboard
Ctrl+Y Redo last undo
Ctrl+Z Undo previous editing action
Keyboard
Function
Shortcut
Ctrl+Break Interrupt execution
Ctrl+Del Clear current Editor window
Ctrl+F1 Start Contents of Online Help
Ctrl+F5 Compile currently-selected file
Ctrl+F7 Execute file to return
Ctrl+F8 Continue processing until program
returns: .OUT
Ctrl+Up arrow Move up call stack
Ctrl+Down arrow Move down call stack
Delete Delete selection
F1 Start Find Topic in Online Help
F3 Repeat last Find entry
F5 Run / Continue stopped program:
.CONTINUE
F6‘ Display next-numbered Editor window
F7 Execute file to cursor
F8 Execute a single statement: .STEP
F9 Toggle breakpoint
F10 Execute a single statement:
.STEPOVER
Shift+F3 Repeat last Replace entry
Shift+F5 Execute currently-selected file
Shift+F6 Display previously-numbered Editor
window
Customizing IDL
Various defaults for IDL can be customized using the IDL Preferences dialog box.
Select Preferences from the IDL File menu to display a cascading list of preferences.
The IDLDE Preferences dialog box contains seven tab selections with which you
can customize your interaction with the IDLDE environment. The seven categories
are: General, Layout, Graphics, Editor, Startup, Fonts, and Path.
Click Reset to restore the settings to the values from the start of the current IDL
session.
General Preferences
The General tab in the Preferences dialog box allows you to specify how the IDLDE
begins and ends, to control the number of lines in the recall buffer and the Output
Log, and to designate how the files should be opened and read.
Program
You can specify how IDL handles starting up and exiting. Click on the following
checkboxes to apply or disable the options:
• Show Splash Screen — Select this option to show IDL’s splash screen on
startup.
• Save Settings on Exit — Select this option to save all the preferences settings
from the current IDL session to be applied to future IDL sessions.
• Confirm Exit
• Users share preferences and macros — Only someone with administrator
rights can toggle this preference. If this checkbox is selected, all users are able
to use and edit the same set of preferences and macros. If a user changes a
preference or macro, it will change for all users. If this checkbox is not
checked, each user has his own set, and will not be able to affect other users’
preferences and macros. If this checkbox is grayed out, the current user does
not have administrator rights.
button while positioned over the Command Input Line to display your entries
up to the limit specified by the recall buffer. The default is 20.
• Number of lines to display in the log
This field controls the minimum number of lines retained by the Output Log
window. The default is 1000 lines.
• Number of log lines to delete at limit
This field controls the number of lines to delete at a time until the limit is
reached again. The default is 100.
Files
You can change the way in which IDL handles opening files. Click on the following
checkboxes to apply or disable the options:
• Change Directory on Open
Select this checkbox to change the working directory upon opening a file to the
opened file’s directory.
• Open Files Read Only
• Clip long filenames
Select this checkbox to truncate filenames so that they conform to the
Windows 8.3 filename format. By default, a file is opened without changing
the filename. See !WARN in the IDL Reference Guide for more information.
Layout Preferences
Main window
By default the size of the window is 1/4 of the screen size (i.e., 1/2 the screen width
and 1/2 the screen height). The window is positioned such that the lower-left corner
of the window is at the lower-left corner of the screen. Click on Default Layout to
use these settings.
To change the layout, click on Specify Layout, which allows you to adjust the
positioning of the window with the Left and Top fields and to adjust the size of the
window with the Width and Height fields.
• Left
The horizontal location of the upper-left corner of the main IDL window (in
pixels) relative to the left side of the screen. The default is 0.
• Top
The vertical location of the upper-left corner of the main IDL window (in
pixels) relative to the top of the screen. The default is 1/2 the screen height.
• Width
The width of the main IDL window in pixels. The default is 1/2 the screen
width. The value in this entry reflects the current width of the main IDL
window.
• Height
The height of the main IDL window in pixels. The default is 1/2 the screen
height. The value in this entry reflects the current height of the main IDL
window.
Click on Remember Layout to apply the settings to future IDL sessions.
Show Window
By default, all the listed options are checked, signifying that they are all visible in the
IDLDE main window. Click on the checkboxes to show or hide the sections.
For more information about the above window sections, see “The Main IDL
Window” on page 64.
Graphics Preferences
This tab allows you to control the layout and size of the open Graphics windows in
the Main Document Panel and also to control the backing store applied to all
Graphics windows.
Window layout
All open Graphics windows can be arranged in either a tiled or cascading fashion.
• Tile
The Tile option arranges all Graphics windows on the desktop side-by-side,
without any overlap.
• Cascade
The Cascade option arranges all Graphics windows on the desktop so that they
overlap.
• Width
This field specifies the width of IDL graphics windows, in pixels. The default
is 1/2 of the total screen width.
• Height
This field specifies the height of IDL graphics windows, in pixels. The default
is 1/2 of the total screen height.
• Use 1/4 the screen size
Click this check box to use the default Height and Width values of 1/2 of the
height and 1/2 of the width of your display.
• Always On Top
Click this check box to specify that graphics windows created in IDL remain
on top of the IDLDE window. If the check box is deselected, the graphics
windows are hidden behind the IDLDE window when it has the focus.
Backing Store
When backing store is enabled, a copy of each Graphics window is kept in memory.
The copy of the window is used to refresh the window when it has been covered and
uncovered. IDL’s performance increases for no backing store, since the amount of
memory required to save files can affect the speed at which IDL will run.
See “Backing Store” in Appendix B of the IDL Reference Guide for more
information.
• None (direct-draw), RETAIN = 0
This option does not keep a copy of the window, allowing the highest
performance in terms of speed.
• System buffered, RETAIN = 1
This option requests the backing store from the Windows server. This option is
the default.
• Bitmap buffered, RETAIN = 2
This option specifies to have IDL maintain the backing store.
Editor Preferences
This tab allows you to control the appearance and performance of the built-in IDL
Editor, and also to set the way in which IDL compiles files.
For more information, see “Using the IDL Editor” in Chapter 9 of Building IDL
Applications.
Startup Preferences
This tab allows you to control the location of the main IDL directory and any startup
file to be run.
IDL Main Directory
This field shows where the main IDL directory is located. The default is the location
you specified when you installed IDL. There is no reason to change this entry. The
location of the home IDL directory is shown primarily for informational purposes.
Click Browse next to the Home directory: field to access the Select Directory
dialog.
Working Directory
This field allows you to set the initial working directory for future IDL sessions. The
General Preferences tab contains an option, described in “Change Directory on
Open” on page 88, which also affects the Working Directory.
Startup file
Use this field to specify the name of an IDL batch file to be executed automatically
each time IDL is run. The startup file specifies the startup path for the next session of
the IDLDE. Your entries are appended to the system variable !PATH. Click Browse
next to the Startup file: field to access the Select File dialog.
For example, to execute the commands in a batch file named MYBATCH.PRO,
located in the C:\DATA directory, use:
C:\DATA\MYBATCH.PRO
Note
Startup files are executed one statement at a time. It is not possible to define
program modules (procedures, functions, or main-level programs) in the startup
file.
Fonts Preferences
This tab allows you to specify individual font descriptions for the Editor window, the
Command Input Line and the Output Log.
Path Preferences
This tab allows you to control where IDL looks for procedures, functions, and help
files.
Search Path
This field tells IDL where to look for procedures and functions. The search path
specifies a list of directories to search.
• Subdirectory checkboxes
To specify a directory tree that includes all of that directory’s subdirectories,
add a check to the box in front of the entry. Clicking on a checked box, thereby
un-checking it, specifies that the subdirectories of the directory will not be
searched.
• Add
To add a path to the Search Path, click on Add to start the Select Directory
dialog. The new path is inserted before a selected path. If none of the paths are
selected, the new path is appended to the end of the list.
• Remove
Click on Remove to delete the selected path.
• Expand
Click on Expand to list a selected path’s subdirectories directly beneath the
path. The expanded path is then un-selected and any newly listed
subdirectories are selected so you can cancel the expansion by immediately
clicking “Remove”. The initial path and any expanded subdirectories are
automatically unchecked to prevent subdirectory searching.
• Move Up and Move Down
You can move the selected path up or down through the list by clicking on
Move Up or Move Down. You can scroll through the list by pressing the up
and down arrows on your keyboard after selecting one of the paths.
The default path is the IDL directory and all of its subdirectories. See
“Executing Program Files” in Chapter 2 for more information.
Message-of-the-Day File
A message-of-the-day file can be used to display the contents of an ASCII text file
each time IDL is run. To create a message-of the-day file for IDL for Windows,
simply name the desired text file MOTD.TXT or WIN32.TXT and place it in the MOTD
subdirectory of the HELP subdirectory of the main IDL directory.
Note
The MOTD file is simply an ASCII text file—not an IDL program or batch file. To
execute a series of IDL commands, select a startup file as described in “Startup
File” in Chapter 2.
If you don’t wish to see the message-of-the-day file each time you start IDL, simply
remove or rename the WIN32.TXT or MOTD.TXT file.
Note
EGA (Enhanced Graphics Adapter) cards provide only 16 colors no matter what
resolution they support.
File Manipulation
Filenames
Under Windows 95/98 and Windows NT, long filenames are supported by IDL.
Names can be up to 255 characters long including extensions. Names can contain any
uppercase or lowercase characters (including spaces) except those shown above.
Windows 95/98 and Windows NT preserve the case of filenames, but the names are
not case sensitive (that is, FileName is the same as filename).
While the names of IDL Library files have been truncated to 8 characters, the names
of the actual routines remain unchanged.
Save/Restore Files
SAVE/RESTORE files generated with the Windows version of IDL are saved in the
XDR format. This format allows data files saved under UNIX, VMS, Windows, and
MacOS systems to be easily exchanged.
Positioning File Pointers
Under Windows, the current file pointer can be positioned arbitrarily. Moving the file
pointer to a position beyond the current end-of-file causes the file to grow out to that
point. Under Windows, the file is padded with arbitrary data.
IDL for UNIX and VMS platforms can be used with one of two different interfaces.
Starting IDL with the command idl begins a traditional IDL session using a simple tty
(text) command line interface. If you are running the X Window system, however,
IDL can also be started with the command idlde (or idl/de under VMS), which invokes
a convenient multiple-document interface called the IDL Development Environment
(IDLDE). This chapter describes the IDLDE.
See “Starting IDL” on page 24 and “Environment Variables Used by IDL” on
page 30 for details on running IDL with its command-line interface.
Using IDL
Chapter 4: The IDL for Motif Interface 103
Menu Bar
Tool Bars
Control Panel
Buttons
Project
Window
Multiple
Document
Window
Output Log
Variable Watch
Window
Command Input
Line
Status Bar
Figure 4-1: The Main IDL Window
Menu Bar
The menu bar, located at the top of the main IDLDE window, is used to control
various IDLDE features.
Tool Bars
You can choose any combination of three tool bars: Standard, Run & Debug, and
Macros. To change the toolbars displayed, use the Window menu to access the
Toolbar pulldown menu and select or de-select any combination of the three
toolbars. In addition, when you open a GUIBuilder window, its associated toolbar is
displayed.
When you position the mouse pointer over a Toolbar button, the Status Bar displays
a brief description. If you click on a Toolbar button which represents an IDL
command, the IDL command issued is displayed in the Output Log.
Project Window
IDL Project Window allows you to manage, compile, run, and create distributions of
all the files needed to develop an IDL application. All of your application files can be
organized for ease of access, and to be easier to export to other developers,
colleagues, or users. The Project Window can be made invisible by selecting
Window–>Configure–>Hide Project. For further information on the Projects
Window, refer to Building IDL Applications.
Output Log
Output from IDL is displayed in the Output Log window, which appears by default
when IDLDE is first started. The Output Log area can be sized by moving the sash
located above the Output Log scroll bar and can be made invisible (as can the
Command Input Line) by selecting Window–>Configure–>Hide Log. If you click
the right mouse button while positioned over the Output Log, a popup menu appears
allowing you to move to a specified error or clear the contents of the Output Log.
Status Bar
When you position the mouse pointer over a Control Panel button or select an
option from a menu item in IDLDE, the Status Bar displays a brief description. The
Status Bar can be made invisible by selecting Window–>Configure–>Hide Status.
IDLDE Windows
Two types of windows can be created and manipulated with IDLDE: IDL Editor, and
IDL Graphics windows.
Warning
If a window is iconized, it will not be refreshed upon return if system or IDL
backing store is not enabled.
File Menu
New [CTRL+N]
Select this option to create a new, empty IDL Editor window. Each window is titled
Untitled until saved. This option is also accessible by clicking the New Document
button from the Toolbar (first button).
Open [CTRL+O]
Select this option to open a text file for editing. The Open dialog appears. Use the
filter to search a specific directory. To open a file, either double-click on the file you
want to open or type the file name in the Selection field and click OK. If the
Multiple Windows option is in effect, a new IDL Editor window is created outside
the main window to contain each text file. If the Single Window option is in effect,
the new file is displayed and all others are listed in the Window menu.
You can also open files from the Command Input Line. Enter the following at the
IDL prompt:
.EDIT file1 [file2 ... filen]
where file is the name of the file you want to open. If the path is not specified in the
Paths Preference from the File menu, you must enter the full path for file. See
.EDIT in the IDL Reference Guide for more information.
Close
Select this option to close the currently-selected IDL Editor window. If you have
made changes in an IDL Editor window, you are asked if you want to save the
changes before closing the window.
Open Project...
Select this option to open a new IDL Project. The Open dialog appears. Select the
project you want to open and click Open.
Save Project
Select this option to save the current IDL Project. If the Project has not yet been
saved, you are prompted for a filename with the Save As dialog.
Save Project As...
Select this option to save the current IDL Project to a specified filename. The Save
As dialog appears.
Close Project
Select this option to close the current IDL Project. If you have made changes in to the
project, you are asked if you want to save the changes before closing the window.
Save [CTRL+S]
Select this option to save the contents of an IDL Editor window. If the file has not yet
been saved, you are prompted for a filename with the Save As dialog.
Note
Changes made to a previously-compiled routine are not available to IDL until that
routine is re-compiled. Executing the routine without saving and re-compiling
simply re-runs the previously-compiled version, without incorporating recent
changes.
Select Run–>Compile to return to the main program level and re-compile the
routine. Select Run–>Compile from Memory to compile the last-saved version of
the file without saving or implementing recent changes.
Warning
Unsaved changes are lost without warning.
Print... [CTRL+P]
Select this option to print the contents of the currently-selected window to the
currently-active printer. The Print dialog appears.
Print Setup
Select this option to change the printer and printing options. The Printer Setup dialog
appears. For further information on Printer Setup, see “Setting Up a Printer in IDL”
on page 40.
Recent Files
Select this option to view or open recently opened or created files. This menu item
lists the last ten opened or created files. To open a file on this list, select it.
To change the maximum number of files displayed from ten to another number,
modify the idlde.numRecentFiles resource in your resource file called .idlde, which is
located in your home directory.
Recent Projects
Select this option to view or open recently opened project files.
Preferences
Select this option to display a dialog box containing five tab selections with which
you can customize your interaction with the IDLDE environment.
Tab Description
General This tab allows you to set the look of the IDLDE interface.
Layout This tab allows you to specify the location and size of the
main window on the screen. You can also designate the
appearance of the IDLDE’s components.
Graphics This tab allows you to specify graphics window dimensions
and also to select how to handle IDL’s backing store.
Edit This tab allows you to specify how to compile files in IDL.
Startup This tab allows you to specify IDL’s main directory, working
directory, and the startup file. The startup file specifies the
startup path of IDLDE for the next session. It is also possible
to disable the use of the startup file.
Fonts This tab allows you to specify the fonts used in document
windows.
Tab Description
Paths This tab allows you to specify the IDL Files Search Path.
Your entries are appended to the system variable !PATH.
Exit [CTRL+Q]
Select this option to exit IDLDE. All IDL Editor windows are closed before exiting.
If text in an Editor window has changed, you are asked if you want to save it before
exiting.
Edit Menu
Undo [ALT+Z]
Select this option to undo previous editing actions. Multiple undo operations are
supported; the first reverses the most recent operation, the next reverses the second
most recent operation, etc. If the most recent action is irreversible, this option will not
be accessible.
Redo [ALT+Y]
Select this option to redo previously undone editing actions. Multiple redo operations
are supported; the first reverses the most recent undo, etc.
Cut [ALT+X]
Select this option to remove currently-selected text from an IDL Editor window to
the Motif clipboard.
Copy [ALT+C]
Select this option to copy currently-selected text from an IDL Editor window to the
Motif clipboard.
Paste [ALT+V]
Select this option to paste the contents of the Motif clipboard at the current insertion
point. The insertion point can only be placed in an IDL Editor window.
Delete [DEL]
Select this option to delete the currently-selected text. The deleted text is not placed
on the clipboard.
Select All
Use this option to select all of the text in an IDL Editor window. The entire contents
of the window are highlighted.
Clear All
Use this option to erase all of the contents in the current IDL Editor window.
Clear Log [CTRL+Y]
Use this option to erase the contents of the Output Log window.
Search Menu
Find... [ALT+F]
Select this option to find text in the currently-active IDL Editor window. The
Find/Replace dialog appears. The attributes available for the Find dialog are
described below:
• Find: — Enter text to search for in this field.
• Case Sensitive or Non-sensitive — Specify if the search should reflect the
case of the text entered in the Find field.
• Search Forward or Backward — Specify the direction in which you would
like to begin the search.
• Start at: Top, Current or Bottom — Specify where to begin the search. For
Top and Bottom, the Search automatically moves Forward or Backward,
respectively. After a word is found, the Search begins at Current.
• Whole words only: — Select this check box so that the search applies only to
the entire designated word, instead of finding the word within other words as a
sub-string.
• Files: — You can specify an open file in which to search or that all open files
be searched. By default, the search will take place in the currently-selected
window. You can also create a Tear-off from the pulldown menu (click on the
dashed line at the top), which remains open as long as the Find/Replace dialog
is open.
To replace text, use the Replace dialog [Alt+R].
Find Again [ALT+G]
Select this option to repeat the most recent text search.
Run Menu
Run Menu items are enabled when an IDL program is loaded into an IDL Editor
window. If you click the right mouse button while positioned over an editor window,
a popup menu appears allowing you to quickly access several of the most convenient
commands. The popup menu changes to display common debugging commands if
IDL is running a program. See Chapter 18, “Debugging an IDL Program” in Building
IDL Applications for more detailed information.
where file is the name of the file you want to open. IDL opens your files in Editor
windows and compiles the procedures and functions contained therein. If the path is
not specified in the Paths Preference from the File menu, you must enter the full
path for file.
See .COMPILE in the IDL Reference Guide for more detail.
Compile from Memory filename.pro [CTRL+F6]
Select this option to save and compile changes to the current editor window without
affecting the last-saved version of the file. The temporary file created allows you to
experiment without committing changes to the permanent file. Selecting this option is
the same as entering .COMPILE -f at the Command Input Line. See .COMPILE in the
IDL Reference Guide for a more detailed explanation.
Compile All
Select this option to compile all currently open *.pro files.
Run filename [F5]
Select this option to execute the file, filename, contained in the currently active Editor
window. Selecting this option is the same as entering the procedure name at the
Command Input Line or using the .GO executive command at the Command Input
Line. If the file is interrupted while running, selecting this option resumes execution;
it is the same as entering .CONTINUE at the Command Input Line. For more
information, see .CONTINUE and .GO in the IDL Reference Guide.
Note
In order for the Run option to reflect the correct procedure name in the Run menu,
the .pro filename must be the same as the main procedure name. For example, the
file named squish.pro must include: pro squish.
entering .STEP at the IDL Command Input Line. See .STEP in the IDL Reference
Guide for a more detailed explanation.
Step Over [F10]
Select this option to execute a single statement in the current program. The current
line indicator advances one statement. If the statement being stepped over calls
another IDL procedure or function, statements from that procedure or function are
executed to the end without interactive capability. Selecting this item is the same as
entering .STEPOVER at the IDL Command Input Line. See .STEPOVER in the IDL
Reference Guide for a more detailed explanation.
Step Out [CTRL+F8]
Select this option to continue processing until the current program returns. Selecting
this item is the same as entering .OUT at the IDL Command Input Line. See .OUT
in the IDL Reference Guide for a more detailed explanation.
Trace ...
Select this option to access the Trace dialog. You can modify the interval between
successive .STEP or .STEPOVER commands, depending on whether the Step Over
option is enabled. The current-line indicator points to program lines as they are
executed. Selecting this item at full speed is the same as entering .TRACE at the IDL
command prompt. See .TRACE in the IDL Reference Guide for a more detailed
explanation.
Run to Cursor [F7]
Select this option to execute statements in the current program up to the line where
the cursor is positioned. Selecting this item is the same as setting a one-time
breakpoint at a specific line. See BREAKPOINT in the IDL Reference Guide for a
more detailed explanation.
Run to Return [CTRL+F7]
Select this option to execute statements in the current procedure or function up to the
line where the return is positioned. Selecting this item is the same as setting a one-
time breakpoint at a specific line. See .RETURN in the IDL Reference Guide for a
more detailed explanation.
Set Breakpoint [F9]
Select this option to set a breakpoint on the current line. Selecting this item is the
same as entering the following at the IDL Command Input Line:
BREAKPOINT, ['file',] index
where ’file’ is the file in which to set a breakpoint, and index designates the line
number at which the breakpoint is set.
See BREAKPOINT in the IDL Reference Guide for a more detailed explanation.
Disable Breakpoint
Select this option to access disable a breakpoint in the current line.
See “Debugging an IDL Program” in Chapter 18 of Building IDL Applications for a
more detailed explanation.
Edit Breakpoint
Select this option to access the Edit Breakpoint dialog to set a complex breakpoint.
Complex breakpoints may function only once, or may function only after being hit a
specified number of times. Selecting this item is the same as setting the AFTER and
ONCE keywords for the BREAKPOINT procedure at the IDL Command Input Line.
Enter the source file in which to set a breakpoint in the File field. The default field is
the one in which the cursor is positioned. Click File..., at the bottom of the dialog, to
search through available directories. Enter the line number at which to place the
breakpoint in the Line field. The default is the line at which the cursor is currently
positioned. You can specify how many times the line must be hit in order to interrupt
execution. Click Once to interrupt execution after encountering the line for the first
time or click Break After and enter the number of hits after which execution should
be interrupted into the given field. Click on Condition to specify an expression that
will be evaluated each time the breakpoint is encountered. If and when the condition
is true, program execution is interrupted.
See BREAKPOINT in the IDL Reference Guide for a more detailed explanation.
Up Stack [CTRL+Up]
Select this option to move up the call stack by one.
Down Stack [CTRL+Down]
Select this option to move down the current call stack by one.
List Call Stack
Select this option to display the current nesting of procedures and functions.
Selecting this item is the same as entering HELP, /TRACEBACK at the IDL
Command Input Line. See HELP in the IDL Reference Guide for a more detailed
explanation.
Project Menu
For more information on the following menu items, see Chapter 13, “Creating IDL
Projects” in Building IDL Applications.
Add/Remove Files...
Select this option to add or remove files from the current project.
Remove Selected
Selecting this option removes the currently selected file from your IDL Project.
Move To
Selecting this option moves the currently selected file to the group you specify in
your IDL Project.
Groups...
Selecting this option displays the Project Groups dialog from which you can create
a new group or rename, remove, move up or down, or set to filter specific file types
for the default groups within an IDL Project.
Options...
Select this option to change the options for a project. The Project Options dialog
displays.
Compile
Select this option to compile files in a project. You can choose either All Files to
compile all the source files in a project or Modified Files to compile only the files
that have been modified since the last compile.
Build
Select this option to build your project.
Run
Select this option to run the application defined by your project.
Export
Select this option to export your project.
Macros Menu
Macros allow you to access frequently used IDL commands from a menu. You can
add your own macros to the macros menu by editing your .idlde resource file. See
“Modifying the Macros Menu” on page 152 for more information. The following
macros are installed by default. (UNIX syntax is shown; similar macros are installed
under OpenVMS.)
Edit...
Select this option to access the Edit Macros dialog. The Edit Macros dialog is a
convenient GUI with which you can modify existing macros or create new ones. The
macros can be applied as either a menu item or a toolbar button. Click on a menu or
toolbar macro to view its attributes. You can specify different attributes for a macro,
some of which are required. You can also rearrange the order of the menu or toolbar
macros with the up and down arrows located at the bottom of the Macro Attributes
section.
Print Var
Select this option to print the selected variable. Selecting this item is the same as
entering PRINT, x at the IDL Command Input Line, where x is the selected variable.
Help On Var
Select this option to list attributes of the selected variable. Selecting this item is the
same as entering HELP, x, /STRUCTURES at the IDL Command Input Line, where x
is the selected variable.
Import Image
Select this option to import an image file into IDL. For more information, see “Using
Macros to Import Image Files” on page 193.
Import Ascii
Select this option to import an ASCII file into IDL. For more information, see “Using
Macros to Import ASCII Files” on page 197.
Import Binary
Select this option to import a binary file into IDL. For more information, see “Using
Macros to Import Binary Files” on page 203.
Import HDF
Select this option to import an HDF file into IDL. For more information, see “Using
Macros to Import HDF Files” on page 210.
IDL Demo
Select this option to start the IDL Demo application.
Window Menu
Read Only
Select this option to enable or disable editing of the currently selected window. A
filled square next to the item indicates Read-Only status.
Next [F11]
Select this option to shift IDL’s focus to the next numbered editor window.
Previous [ALT+F11]
Select this option to shift IDL’s focus to the previous numbered editor window.
Cascade
Select this option to arrange all open windows in a staggered, overlapping fashion.
Tile
Select this option to arrange all open windows in a non-overlapping fashion.
Close All
Select this option to close all open files. If a file has not yet been saved, you are
prompted to save the changes.
Configure
Select this option to access a pulldown menu which alters the appearance of the
IDLDE. Select each toggle option to hide or show each component. For more
information about each component, see “The Main IDL Window” on page 103.
• Hide Control (Show Control)
• Hide View (Show View)
• Hide Log (Show Log)
• Hide Variable Watch (Show Variable Watch)
Help Menu
Help on IDL...
Select this option to display the IDL Online Help Viewer.
Find Topic...
Select this option to access the Search dialog for IDL Online Help.
Help on IDE...
Select this option to display this chapter of Using IDL.
Help on Help
Select this option to learn about how to use Help.
About IDL
Select this option to display information on the IDL version in use.
Keyboard Shortcuts
Many of the menu options can be accessed from the keyboard as well as by selecting
from the menus. The following table below lists all of the available keyboard
equivalents. Note that these equivalents are also shown to the right of each menu item
in the menus themselves.
Note
It is important to understand the distinctions in application that occur throughout the
Preferences Dialog, as described in the table below.
Button Effect
OK Changes are applied to the current session and the Preferences
dialog is dismissed.
Apply Changes are applied to the current session but not saved. The
Preferences dialog remains visible.
Save Changes are applied to the current session and saved. If the option
has an asterisk next to it, you must save and restart the IDLDE for
the change to take effect.
Cancel Any unapplied changes are ignored and the Preferences dialog is
dismissed.
General Preferences
Program
You can specify how IDL handles starting up and exiting. Click on the following
check boxes to apply or disable the options:
• Show Splash Screen — Select this option to show IDL’s splash screen on
startup. IDL must be restarted for this option to take effect.
• Save Preferences on Exit — Select this option to save all the settings—as
specified in the seven Preference tabs—from the current IDL session to be
applied to future IDL sessions.
• Confirm Exit
Log and Command Window
The performance of IDL can depend upon the number of saved lines. The amount of
memory required for greater numbers of saved lines can affect the speed at which
IDL will run. Click in the field next to each description and enter your adjusted value.
• Lines to Save — This field controls the minimum number of lines retained by
the Output Log window. The default is 500 lines. IDL must be restarted for
this option to take effect.
• Delete on limit — This field controls the number of lines to delete at a time
until the limit is reached again. The default is 125. IDL must be restarted for
this option to take effect.
• Lines saved in the recall buffer: — This field controls the maximum number
of lines saved in the recall buffer. There are three ways to access the contents
of the recall buffer, all of which are limited by this field. After locating the
cursor in the Command Input Line, you can press your up arrow key to scroll
through your last entries.You can also enter HELP, /RECALL in the Command
Input Line or click on your right mouse button while positioned over the
Command Input Line to display your entries up to the limit specified by the
recall buffer. The default is 20.
Files
You can specify how files are opened within the IDLDE:
• Change Directory on Open — Click on this check box to change the working
directory to the directory of the most recently opened file.
• Open Files Read Only — Click on this check box to open files so that they
are not writable.
Layout Preferences
This tab allows you to control the look of the main IDL window.
Main window
By default the size of the window is 1/4 of the screen size (i.e., 1/2 the screen width
and 1/2 the screen height). The window is positioned such that the upper-left corner
of the window is at the upper-left corner of the screen. Click on Default to use these
settings.
To change the layout, click on Specify, which allows you to adjust the positioning of
the window with the Left and Top fields and to adjust the size of the window with
the Width and Height fields.
• Left — The horizontal location of the upper-left corner of the main IDL
window (in pixels) relative to the left side of the screen. The default is 75.
• Top — The vertical location of the upper-left corner of the main IDL window
(in pixels) relative to the top of the screen. The default is 25.
• Width — The width of the main IDL window in pixels. The default is 1/2 the
screen width. The value in this entry reflects the current width of the main IDL
window.
• Height — The height of the main IDL window in pixels. The default is 1/2 the
screen height. The value in this entry reflects the current height of the main
IDL window.
Click Remember to apply the settings to future IDL sessions. This option—as
indicated by the asterisk before Main Window— is unavailable until IDL has been
restarted.
Windows
These options are also contained in the Window menu of the IDLDE. The difference
between the Windows section of the Layout Preferences and the Window menu is
that any changes to the Preferences are applies to future IDL sessions.
• Editor Layout — Click on Multiple to display open Editor windows
separately from the main IDLDE window. The Editor Layout is listed as
Multiple Windows/Single Window in the Window menu.
• Hide — Click on any of the sections of the IDLDE window to hide them from
view. If the check box is marked, the section is hidden. By default, none of the
sections are hidden. The Hide options are found in the pulldown menu
accessed with the Configure option from the Window menu.
• Separate — Click on the available sections to separate them from the main
IDLDE window. If the check box is marked, the section can be found on the
desktop in a separate window. If you dismiss a window, the Hide option for
that section, as described above, is enabled. To view a dismissed window, un-
hide it and click OK or Apply.
Note
If the Multiple Windows option is enabled, the choice to hide or view the Editor
windows is not available.
Control Panel
You can specify how you would like to display the Control Panel buttons:
• Hide Tools — Click on any of the available toolbars: Standard,
Run&Debug, and User to change their visibility. If a box is checked (it will
appear darker), the toolbar with which it is associated is hidden on the main
IDLDE window.
• Number of Rows — Enter the number of rows to use in displaying any visible
toolbars. You can select from 1 to 3 rows. If the window has been separated, as
Graphics Preferences
Windows Size
This section of the Graphics Preferences tab allows you to specify the appearance of
an IDL graphics window.
• Default Width — The width of IDL graphics windows, in pixels. The default
is 1/4 of the total screen width.
• Default Height — The height of IDL graphics windows, in pixels. The default
is 1/4 of the total screen height.
• Use 1/4 the screen size — If this box is checked, the Graphics windows are set
to 1/2 the screen size in both width and height. If this box is unchecked, the
Graphics windows are sized according to content.
Backing Store
When backing store is enabled, a copy of each Graphics window is kept in memory.
The copy of the window is used to refresh the window when it has been covered and
uncovered. IDL’s performance increases for no backing store, since the amount of
memory required to save files can affect the speed at which IDL will run.
See “Backing Store” in Appendix B of the IDL Reference Guide for more
information.
• None, RETAIN = 0
Click None to disable backing store. This option does not keep a copy of the
window, allowing the highest performance in terms of speed.
• System, RETAIN = 1
Click this option to request backing store from the server.
• Pixmap, RETAIN = 2
Click this option (the default) to have IDL maintain backing store. Most users
should keep this value set to 2.
Graphics Attributes
• Size of TrueType Font Cache (in glyphs) — Enter the number of TrueType
characters whose triangulation information will be saved. Saving the
triangulation information for TrueType characters means that IDL will not
have to calculate the polygons to draw the next time a character of the same
font and size is rendered. Larger values will use more memory but can increase
drawing speed if multiple fonts are used. The default is 256.
• Object Graphics Renderer — Select either Hardware Rendering
(OpenGL) or Software Rendering. See Chapter 28, “Window Objects” for
information about the differences between the two rendering systems.
Edit Preferences
This tab allows you to set the way in which IDL compiles files. By default, IDLDE
asks if you would like to save changes. You can also set IDLDE to make a backup
copy of the source file.
Startup Preferences
This tab allows you to specify the location of a file to be run when IDLDE starts.
Select IDL Main Dir ...
Click on this button to start the Select IDL Main Dir dialog, which shows you where
the main IDL directory is located. The default is the location you specified when you
installed IDL. There is no reason to change this entry. The location of the home IDL
directory is shown primarily for informational purposes. You must restart IDL for
any changes to take effect.
Select Working Directory
Click on this button to start the Select Working Directory dialog. You can specify
the initial working directory for future IDL sessions. The General Preferences tab
contains a “Change Directory on Open” option, described under “Files” on page 125,
which also affects the working directory.
Select Startup File
Click on this button to start the Select Startup File dialog. You can specify the name
of an IDL batch file to be executed automatically each time IDL is run. For example,
to execute the commands in a batch file named MYBATCH.PRO, located in the
/home/user directory, use:
/home/user/MYBATCH.PRO
Disable the use of the startup file by selecting the Don’t Use Startup File button.
Warning
Startup files are executed one statement at a time. It is not possible to define
program modules, (procedures, functions, or main-level programs) in the startup
file. See “Startup File” on page 58 for more information.
Font Preferences
This tab allows you to control which fonts are to be used for the main IDL window.
Click on any of the following buttons to specify the relevant font:
• Default — dialog boxes
• Menubar — menu items
• Control — the Control Panel
• Edit — editor windows
• Log — the Output Log
• Command — the Command Input Line
Path Preferences
This tab allows you to control where IDL looks for procedures and functions. Entries
into the IDL Files Search Path are appended to the system variable !PATH.
Note
You must restart IDLDE for changes to take effect.
pressing the up and down arrows on your keyboard after either selecting or
outlining one of the paths.
• Insert... — To add a path to the IDL Files Search Path list, click on Insert...
to start the Select Path dialog. The new path is inserted before the first
selected path. If none of the paths are selected, the new path is appended to the
end of the list.
• Remove — Click on Remove to delete the selected path.
• Expand — Click on Expand to list a selected path’s subdirectories directly
beneath the path. The expanded path is then deselected and any subdirectories
are selected so you can cancel the expansion by immediately clicking Remove.
The initial path and any expanded subdirectories are automatically unchecked
to prevent subdirectory searching.
See “Executing Program Files” in Chapter 2 for more information.
Reserving Colors
When IDL starts, it attempts to secure entries in the shared system color map for use
when drawing graphics. If the entry Idl.colors exists in the Idl resource file, IDL will
attempt to allocate the number of colors specified from the shared colormap. If for
some reason it cannot allocate the requested number of colors from the shared
colormap, IDL will create a private colormap. Using a private colormap ensures that
IDL has the number of colormap entries necessary, but can lead to colormap flashing
when the cursor or window focus moves between IDL and other applications.
One way to avoid creating a private colormap for IDL is to set the Idl.colors resource
equal to a negative number. This causes IDL to try to use the shared colormap,
allocating all but the specified number of colors. For example:
Idl.colors = -10
instructs IDL to allocate all but 10 of the currently available colors for its use. Thus,
if there are a total of 220 colors not yet reserved by other applications (such as the
windowing system), IDL will allocate 210 colors from the shared colormap.
The IDLDE application itself uses between 10-15 colors. On startup, the IDLDE will
attempt to use colors in the shared colormap, but will reserve colors for itself if
appropriate matching colors in the shared colormap are not found. As a result,
running IDL with the IDLDE may use more colors than running IDL with the tty
(plain command line) interface.
If you experience colormap flashing when using the IDLDE, but not when you use
the plain tty interface, try adjusting the number of colors used by the IDLDE
interactively, using the -colors startup flag. For example,
idlde -colors -15
starts the IDLDE and allocates all but 15 of the currently available colors. When you
find an appropriate number of colors to reserve, you can set the idlde.colors resource
in the Idl resource file or in your personal .idlde file accordingly.
If specified, IDL attempts to allocate n colors specified from the shared colormap. If
there aren’t enough colors available, a private colormap with n colors is used instead.
Specifying a negative value for the colors flag causes IDL to attempt to use the
shared colormap, allocating all but the specified number of colors. For example:
idlde -colors -15
allocates all but 15 of the currently available colors for the IDLDE. This allows other
applications that might need their own colors to run in tandem with IDL.
The related resource is idlde.colors.
-nocommand
/NOCOMMAND
Hides the Output Log window and Command Input Line at startup. The related
resource is Idl*idlde*hideCommand: True.
-command
/COMMAND
Displays Log window and Command Input window at startup. The related resource is
Idl*idlde*hideCommand: False.
-nocontrol
/NOCONTROL
Hides the Control panel buttons at startup. The related resource is
Idl*idlde*hideControl: True.
-control
/CONTROL
Displays the Control Panel buttons at startup. The related resource is
Idl*idlde*hideControl: False.
-nolog
/NOLOG
Hides the Output Log at startup. The related resource is
Idl*idlde*hideLog: True.
-log
/LOG
Displays the Output Log at startup. The related resource is
Idl*idlde*hideLog: False.
-nostartup
/NOSTARTUP
Does not execute startup file on startup (including IDL_STARTUP). The related
resource is Idl*idlde.noStartupFile: True.
-startup
/STARTUP
Executes startup file on startup (including IDL_STARTUP). The related resource is
Idl*idlde.noStartupFile: False.
-startupfile "file"
/STARTUPFILE="file"
Executes file at startup (overrides IDL_STARTUP environment variable). If
startupfile is not specified, the environment variable IDL_STARTUP is used as the
startup file (if defined). The related resource is Idl*idlde.startupFile: file where file is
the full path name of the startup file.
-nostatus
/NOSTATUS
Hides the Status Bar at startup. The related resource is
Idl*idlde*hideStatus: True.
-status
/STATUS
Displays the Status Bar at startup. The related resource is Idl*idlde*hideStatus: False.
-path "path"
/PATH="path"
Append path to the IDL path (defined using IDL_PATH environment variable). The
related resource is Idl*idlde.path: path where path is the full path to be appended.
-quiet
/QUIET
Inhibits display of the IDL startup announcement and message of the day (motd) file.
-readonly
/READONLY
Opens files as read-only. The related resource is Idl*idlde.readOnly: True.
-readwrite
/READWRITE
Open files as read-writeable. The related resource is
Idl*idlde.readOnly: False.
-single
/SINGLE
Displays files in a single window, which is a child of the main IDLDE window. The
related resource is Idl*idlde*multiWindowEdit: False.
-multi
/MULTI
Displays files in multiple windows, each one in a separate main level window. The
related resource is Idl*idlde*multiWindowEdit: True.
-view
/VIEW
Displays the Multiple Document Panel in single window mode at startup. The related
resource is Idl*idlde*hideView: False.
-noview
/NOVIEW
Hides the Multiple Document Panel at startup. The related resource is
Idl*idlde*hideView: True.
-title "Title"
/TITLE="Title"
Use Title as the title of the main IDLDE window. The related resource is idlde.title.
/VAX_FLOAT
This option is available only in IDL for VMS. Set this qualifier to change the default
value of the VAX_FLOAT keyword of the CALL_EXTERNAL and OPEN
procedures to be TRUE. Starting IDL with this qualifier allows old code that is
written to assume IDL reads and writes VAX format floating-point numbers to
continue reading and writing that format without requiring changes to the IDL code.
There are three caveats:
1. Internally, IDL is still using IEEE floating-point numbers.
2. This option should be used as a transitional aid prior to converting the code to
work with IEEE math. It is not a good long term strategy to use IDL in this
mode.
Note
You should read the warnings on this topic found in the OPEN and
CALL_EXTERNAL routines in the IDL Reference Guide.
3. The bitmap must be defined in the resource file (Idl, .idlde), for example:
idlde*control*mybutton*labelPixmap: mybutton
Examples
• To add a button called Reset All to the Control Panel with color pixmap
stored in the file resetall.xpm located in your home directory add the following
resources to your .idlde:
Idl*idlde*control*idlButtonsUser: resetall
Idl*idlde*control*resetall*labelPixmap: resetall.xpm
Idl*idlde*control*resetall*labelString: Reset All
Idl*idlde*control*resetall*idlCommand:\
RETALL & WIDGET_CONTROL,/RESET
Idl*idlde*control*resetall*statusString:\
Stop execution of the current code and return to\
the main programming level
• To specify a pixmap located in particular directory, specify the full file path of
the pixmap file, for example:
Idl*idlde*control*resetall*labelPixmap:\
/home/user/bitmaps/resetall.xpm
• To create two rows of the Control Panel from the default of one row, set the
numColumns resource to 2:
Idl*idlde*control*numColumns: 2
• To use label (text) buttons in the Control Panel set labelType to XmSTRING.
To use icon (graphics) buttons set labelType to XmPIXMAP.
Idl*idlde*control*labelType: XmPIXMAP
% Symbol Substitution
%S The text of the current selection.
% Symbol Substitution
%F or %P The filename associated with the current
IDL Editor.
%N The base name of the filename (without
path and suffix).
%B The base name of the filename (without
path, but with a suffix)
%L The line number with the current insertion
point.
%% Inserts “%”.
Action Routines
Most Motif widgets supply action routines which can be bound to events (such as
keypress events). Action routines provided by IDL can be used to define commands
for Control Panel buttons or menu items by using the idlAction resource.
The following action routines can be used in the same manner as the IDL commands
specified in an idlCommand resource. The syntax to add an action routine to a control
panel button is:
Idl*idlde*control*button name*idlAction: action
where button name is the name of the button and action is the name of the action
routine.
IdlBreakpoint
Use IdlBreakpoint to control the placement of breakpoints. If no parameter is
specified, the breakpoint is set on the current line. At least one of the arguments from
Table 4-4 must be set:
Argument Action
SET Set a breakpoint on the current line.
CLEAR Clear the breakpoint on the current line.
TOGGLE Toggle (SET or CLEAR) the state of the
breakpoint on the current line.
COMPLEX Display breakpoint dialog to set a complex
breakpoint.
LIST List all currently set breakpoints
IdlClearLog
Use IdlClearLog to erase the contents of the Output Log.
IdlClearView
Use IdlClearView to clear the contents of the currently-active file in the Multiple
Document Panel.
IdlCommandHide
Use IdlCommandHide to hide or expose the Command Area, which includes the
Command Input Line and the Output Log. One of the following arguments must be
set: Show, Hide, or Toggle.
IdlCompile
Use IdlCompile to compile the file in the currently-active editor window. One of the
arguments from the following table must be set:
Argument Action
FILE Compiles the currently-active
file.
TEMPORARY Compiles the currently-active
file into a temporary file
RESOLVE Resolves all referenced and
uncompiled IDL routines
IdlControlHide
Use IdlControlHide to hide or expose the Control Panel. One of the following
arguments must be set: Show, Hide, or Toggle.
IdlEdit
Use IdlEdit to manipulate the contents of the currently-selected editor window. One
of the arguments from the following table must be set:
Argument Action
UNDO Undo previous editing action.
REDO Redo previously undone
action.
CUT Remove currently-selected
text to Motif clipboard.
Argument Action
COPY Copy currently-selected text
to Motif clipboard.
PASTE Paste contents of Motif
clipboard at current insertion
point.
SELECTALL Select all of the text in the
currently-selected editor
window.
GOTODEF Display the definition of the
currently-selected procedure
or function.
GOTOLINE Move directly to the specified
line number.
IdlEditMacros
Use IdlEditMacros to display the Edit Macros dialog.
IdlExit
Use IdlExit to cause IDLDE to act as though the EXIT command has been entered.
Note that this is usually tied to a menu accelerator (Ctrl-Q in this case), so this routine
is rarely called directly.
IdlFile
Use IdlFile to manipulate the currently-selected editor window. One of the arguments
in the following table must be set:
Argument Action
NEW Creates a new editor window.
OPEN Opens an existing file.
Argument Action
SAVE Saves the contents of the
currently-selected editor
window.
PRINT Prints the contents of the
currently-selected editor
window.
IdlFileReadOnly
Use IdlFileReadOnly to specify the read/write status of the currently-active editor
window. One of the arguments from the following table must be set:
Argument Action
READONLY Disable editing of the
currently-selected editor
window.
READWRITE Enables editing of the
currently-selected window.
IdlFunctionKey
Use IdlFunctionKey to allow entry of an IDL command into the input command
stream. It is typically used to tie IDL commands to function keys. For example:
<Key>F5:IdlFunctionKey("print, 'F5 pressed'")\n
IdlInterrupt
Use IdlInterrupt to cause IDLDE to receive an interrupt. Note that this is usually tied
to Ctrl-C as a menu accelerator.
IdlListStack
Use IdlListStack to display the current nesting of procedures and functions (calling
stack).
IdlLogHide
Use IdlLogHide to hide or expose the Output Log. One of the following arguments
must be set: Show, Hide, or Toggle.
IdlRecallCommand
Use IdlRecallCommand to recalls previously entered commands into the command
widget. Either the BACK or the FORWARD argument must be specified to indicate
the direction of the recall. For example:
<Key>osfUp:IdlRecallCommand(BACK)\n
IdlReset
Use IdlReset to reset the IDL environment.
IdlRun
Use IdlRun to execute the currently-active file.
IdlSearch
Use IdlSearch to call the Find dialog for a search of the current Multiple Document
Panel. One of the optional arguments from the following table may be used:
Argument Action
FIND Displays a search dialog (default).
FINDAGAIN Finds the next occurrence of the
specified string.
FINDSELECTION Finds next occurrence of the current
selection.
ENTERSELECTION Enters the current selection as the
search string in the Find dialog.
REPLACE Replaces the search string, with a
specified replacement string.
REPLACEFIND Finds the next occurrence of the search
string, and replaces it with the specified
replacement string.
IdlStatusHide
Use IdlStatusHide to hide or expose the Status Bar. One of the following arguments
must be set: Show, Hide, or Toggle.
IdlStep
Use IdlStep to control statement execution for debugging. At least one of the
arguments from the following table must be set.
Argument Action
INTO Executes a single statement in the current
program. If nested procedures or functions are
encountered, they are also executed in single-
statement mode.
OVER Executes a single statement in the current
program. If nested procedures or functions are
encountered, they are run until completion,
whereupon interactive control returns.
OUT Continues execution until current routine
returns.
SKIP Skips one statement and executes following
statement.
CONTINUE Continues execution of an interrupted program.
TOCURSOR Executes file until encountering the cursor.
TORETURN Executes file until encountering the return.
IdlTrace
Use IdlTrace to display a dialog box to control program tracing.
IdlViewHide
Use IdlViewHide to hide or expose the Multiple Document Panel. One of the
following arguments must be set: Show, Hide, or Toggle.
IdlWindows
Use IdlWindows to manipulate the state of the Editor windows. One of the arguments
from the following table must be set:
Argument Action
CASCADE Arrange open windows in a
staggered, overlapping
fashion.
TILE Arrange all windows in a
non-overlapping fashion.
MULTI Open windows outside the
IDLDE interface.
SINGLE Display the most recent
window on the Multiple
Document Panel.
Example
To add the menu item File in Big Vi to the Macros menu add the following resources
to .idlde:
;Define a new menu item:
Idl*idlde*menubar*macrosMenu*macrosListUser: bigViXterm
;Assign text to the defined menu item:
Idl*idlde*menubar*macrosMenu*bigViXterm*labelString:\
File in Big Vi
;Define a procedure to call up the vi editor:
Idl*idlde*menubar*macrosMenu*bigViXterm*idlCommand:\
SPAWN,'xterm -geometry 80x50 -e vi -c %L %F &
;Assign text for the status string:
Idl*idlde*menubar*macrosMenu*bigViXterm*statusString:\
Run vi in the Big Xterm window
3. In the Idl.dt file, verify that the path to theRSI_Dir/bin directory in the
ACTION Idl section is correct for the local machine. For example, if IDL is
located in the /usr/local/rsi/ directory, the ACTION Idl section should look like
this:
ACTION Idl
{
LABEL Idl
TYPE COMMAND
EXEC_STRING /bin/sh -c ‘. /usr/local/rsi/idl_setup.ksh;idl -c -e %Arg_1%’
ICON Dtactn
WINDOW_TYPE NO_STDIO
DESCRIPTION Start Idl Development Environment
}
Output Log
The Output Log window displays output from IDL and echoes commands input to
IDL. Only one Output Log window can exist at a time.
Project Window
The IDL Project Window allows you to manage, compile, run, and create
distributions of all the files needed to develop an IDL application. All of your
application files can be organized for ease of access, and to be easier to export to
.STEPOVER, then Step In which calls .STEP, and the fourth button is Continue
which calls .CONTINUE.
Debug Windows
When IDL encounters a program error or breakpoint, and if the debugger is turned on
by selecting File–>Preferences–>General and marking the Use Debugger check
box (see “Use Debugger” on page 176), the IDL Editor window containing the
routine in question is brought to the front. If the file containing the error is not already
open, a new Editor window is opened to contain it. A current-line indicator is placed
at the line at which the breakpoint or error occurred. You can use standard Macintosh
editing commands to edit and save the program file.
Error Window
When IDL encounters a program error during compilation, the Error Window will
display and show all of the errors encountered. Clicking on the error displays the line
of the program that contains the error in the IDL Editor window.
The Menus
Six menus (File, Edit, Search, Run, Project, Macros, Window, and Help) allow
you to control the operation of IDL for Macintosh. These menus are described below.
Note that many menu items have Command-key equivalents displayed to the right of
the menu option.
File Menu
New
Select this option to create a new, empty IDL Editor window.
New Project...
IDL Project Window allows you to manage, compile, run, and create distributions of
all the files needed to develop an IDL application. All of your application files can be
organized for ease of access, and to be easier to export to other developers,
colleagues, or users. For further information on the Projects Window, refer to
Building IDL Applications.
Open
Select this option to open a text file or project file for editing. The standard File
Selection dialog box appears. Select the file you want to open and click OK. A new
IDL Editor window is created to display the text file.
Open Selection
Select this option to use whatever text is selected as an argument to the Open
command. If the selected text is not the name of a file in the current folder or a valid
path, no file is opened.
Open Recent
Select this option to view or open recently opened or created files. This menu item
lists the last ten opened or created files, and it includes two sections for text and IDL
Project files. To open a file on this list, simply select it from the drop list.
Close / Hide
Select this option to close the currently-selected IDL window. If you have made
changes in the window, you are prompted to save the changes before closing it. If the
currently-selected window is the Output Log, this options changes to Hide Output
Log. If the currently-selected window is the Variable Watch Window, this option
changes to Hide Variable Watch Window. You can re-display a hidden window by
selecting Output Log or Variable Watch from the Window menu.
Hold down the Close option and hit the Command key to close down all open Editor
windows with a single command.
Save
Select this option to save the contents of an IDL Editor window. If the window is
untitled, you are prompted for a filename for the new file. If the window is already
associated with a filename, the contents of the window are saved over the old file.
Hold down the Save option and hit the Command key to save all open Editor
windows with a single command.
Note
Changes made to a previously-compiled program or function are not noticed by the
IDL session until that file is re-compiled. Calling the routine simply re-runs the
currently-compiled version. Select the Compile option under the Run menu to re-
compile the routine before running the newly saved program.
Save As...
Select this option to save the contents of an IDL Editor window to a specified
filename. A file selection dialog box appears.
Revert to Saved
Select this option to discard any changes made in the current window and restore the
last saved version of the file.
Page Setup...
Select this option to define page orientation and other print characteristics for the
currently-selected window.
Print
Select this option to print the contents of the currently-selected IDL window, text
widget, or graphics widget to the currently-active printer.
Preferences
Select this menu item to display a cascading menu of preference options: General,
Graphics, Edit, Startup, Path, Syntax Coloring, Preferences Sets, and Projects.
See “Customizing IDL” on page 175 for more information.
Working Folder...
Select this option to modify the current folder for reading and writing files. Note that
the current folder is searched first when IDL looks for program files.
Quit
Select this option to exit IDL for Macintosh. All IDL Editor windows are closed
before exiting. If text in an Editor window has changed, you are asked if you want to
save it before exiting.
Edit Menu
Undo
Select this option to undo the most recent editing action. If the most recent action is
not undo-able, this option will be shown as Can’t Undo.
Cut
Select this option to cut the currently-selected text from an IDL Editor window or the
IDL Command Input line and place it on the clipboard.
Copy
Select this option to copy the currently-selected text in an IDL Editor window,
Output Log window, or Command Input to the clipboard. Copy also allows you to
copy graphics from an IDL graphics window or draw widget to the clipboard.
Paste
Select this option to paste the contents of the clipboard at the current insertion point.
You can paste into the IDL Command Input and IDL Editor windows, but not the
Output Log window.
Clear
Select this option to delete the currently-selected text. The deleted text is not placed
on the clipboard.
Select All
Use this option to select all of the text in an IDL Editor or Output Log window. The
entire contents of the window are highlighted.
Shift Left
Select this menu item to shift the selected text one tab stop to the left.
Shift Right
Select this menu item to shift the selected text one tab stop to the right.
Comment Line
Select this menu item to insert a semi-colon at the beginning of the line with the
cursor in it. You can also select multiple lines to be commented out by highlighting
them and using this menu item.
Uncomment Line
Select this menu item to remove a semi-colon from the beginning of the line with the
cursor in it. You can also select multiple lines to be uncommented by highlighting
them and using this menu item.
Search Menu
Find...
Select this menu item to search for a text string in the currently-selected IDL Editor
window, Output Log window, or text widget.
Find Again
Select this option to repeat the most recent text search.
Find Selection
Select this menu item to search for occurrences of the currently-selected text in the
currently-selected window.
Enter Selection
Select this menu item to enter the currently-selected text into the Find dialog as the
search string. For example, you can enter the selection and then select Find Again to
find the next occurrence.
Replace...
Select this menu item to search for a text string in the currently-selected IDL Editor
window or text widget and replace it with another text string you specify.
Replace & Find Again
Select this option to repeat the most recent search and replace operation.
Go To Routine Definition
Select this menu item to find and display the definition of the selected IDL library or
user-written routine. The routine must already be compiled.
Go To Line...
Select this option to specify a line on which to locate the cursor in the currently-
selected IDL Editor window or text widget.
You can also use the line number button box at the bottom left of an IDL Editor
window, which displays the number of the line on which the cursor is located. To
relocate the cursor on another line, click in the box and specify the line number in the
Go To Line field.
Run Menu
Run menu items are enabled when an IDL program is loaded into an IDL Editor
window and compiled. See Chapter 18, “Debugging an IDL Program” in Building
IDL Applications for more detailed information.
Note
You must have the Use Debugger option in the IDL General Preferences dialog
checked for the Debug menu to appear.
Compile
Select this option to compile the current editor window from memory. The currently-
selected file is only recognized as an IDL procedure or function if suffixed with
.pro. Selecting this option is the same as entering .COMPILE at the Command
Input line, with the appropriate Editor window selected. See .COMPILE in the IDL
Reference Guide for a more detailed explanation.
Compile from Memory
Select this option to save and compile changes to the current editor window without
affecting the last-saved version of the file. The temporary file created allows you to
experiment without committing changes to the permanent file. Selecting this option is
the same as entering .COMPILE -f at the Command Input Line. See .COMPILE in
the IDL Reference Guide for a more detailed explanation.
Compile All
Select this option to compile all currently open *.pro files.
Run
Select this option to execute the file contained in the currently-active Editor window.
Selecting this option is the same as entering the procedure name at the Command
Input line.
Resolve Dependencies
Select this option to iteratively compile all uncompiled IDL routines that are
referenced in any open and compiled files. Selecting this option is the same as
entering RESOLVE_ALL, /QUIET at the Command Input line. The QUIET keyword
suppresses informational messages. See RESOLVE_ALL in the IDL Reference
Guide for a more detailed explanation.
Profile...
Select this option to start the IDL Code Profiler, which helps you analyze the
performance of your applications. See “The IDL Code Profiler” in Chapter 14 of
Building IDL Applications for more information about the Profiler.
Continue
Select this option to continue a stopped program or start a main-level program from
the beginning. Selecting this option is the same as entering .CONTINUE at the
Command Input line. See .CONTINUE in the IDL Reference Guide for a more
detailed explanation.
Break
Select this option to interrupt program execution. IDL inserts a marker to the left of
the line at which program execution was interrupted.
Clear IDL
Select this option to stop program execution and return to the main program level.
Selecting this item is the same as entering the following at the Command Input line:
RETALL
WIDGET_CONTROL,/RESET
CLOSE, /ALL
HEAP_GC, /VERBOSE
Reset IDL
Select this option to completely reset the IDL session. This option executes
.RESET_SESSION. See the IDL Reference Guide for more information.
Step Over
Select this option to execute a single statement in the current program. The current-
line indicator advances one statement. If the statement which is stepped over calls
another IDL procedure or function, statements from that procedure or function are
executed to the end without interactive capability. Selecting this item is the same as
entering .STEPOVER at the IDL Command Input Line. See .STEPOVER in the IDL
Reference Guide for a more detailed explanation.
Step Into
Select this option to execute a single statement in the current program. The current-
line indicator advances one statement. If the statement which is stepped into calls
another IDL procedure or function, statements from that procedure or function are
executed in order by successive Step commands. Selecting this item is the same as
entering .STEP at the IDL Command Input line. See .STEP in the IDL Reference
Guide for a more detailed explanation.
Step Out
Select this option to continue processing until the current program returns. Selecting
this item is the same as entering .OUT at the IDL Command Input line. See .OUT in
the IDL Reference Guide for a more detailed explanation.
Trace
Select this option to point to program lines as they are executed. Selecting this item is
the same as entering .TRACE at the IDL command prompt. See .TRACE in the IDL
Reference Guide for a more detailed explanation.
Run to Cursor
Select this option to execute statements in the current program up to the line where
the cursor is positioned. Selecting this item is the same as setting a one-time
breakpoint at a specific line. See BREAKPOINT in the IDL Reference Guide for a
more detailed explanation.
Run to Return
Select this option to execute statements in the current procedure or function up to the
line where the return is positioned. Selecting this item is the same as setting a one-
time breakpoint at a specific line. See .RETURN in the IDL Reference Guide for a
more detailed explanation.
Set Breakpoint
Select this option to set a breakpoint on the current line. Selecting this item is the
same as entering the following at the IDL Command Input line:
BREAKPOINT, ['File',] Index
where File is the file to set a breakpoint within, and Index designates the line
number at which the breakpoint is set.
See BREAKPOINT in the IDL Reference Guide for a more detailed explanation.
Disable Breakpoint
Select this option to access disable a breakpoint in the current line.
See Chapter 18, “Debugging an IDL Program” in Building IDL Applications for a
more detailed explanation.
Edit Breakpoints ...
Select this option to access the Edit Breakpoint dialog to set a complex breakpoint.
Complex breakpoints may function only once, or may function only after being hit a
specified number of times. Selecting this item is the same as setting the AFTER and
ONCE keywords for the BREAKPOINT procedure at the IDL Command Input line.
Enter the source file in which to set a breakpoint in the File: field. The default file is
the one in which the cursor is positioned. Click Choose File ... to search through
available directories. Enter the line number at which to place the breakpoint in the
Line: field. The default is the line at which the cursor is currently positioned. You
can also specify how many times the line must be hit in order to interrupt execution.
Click One-Time Breakpoint to interrupt execution after encountering the line for
the first time or click Break After: and enter the number of hits after which
execution should be interrupted into the given field.
See BREAKPOINT in the IDL Reference Guide for a more detailed explanation.
Clear All Breakpoints
Select this option to clear all breakpoints.
List Breakpoints
Select this option to list all breakpoints currently set, in all compiled programs.
Selecting this item is the same as entering HELP, /BREAKPOINTS at the IDL
Command Input line.
List Call Stack
Select this option to display the current nesting of procedures and functions.
Selecting this item is the same as entering HELP, /TRACEBACK at the IDL
Command Input line. See HELP in the IDL Reference Guide for a more detailed
explanation.
Project Menu
For more information on the following menu items, see Chapter 13, “Creating IDL
Projects” in the Building IDL Applications.
Add Window
Select this menu item to add the current file in the Editor window to the current
project.
Add Files...
Selecting this option brings up the Add Files To Project dialog box from which you
can select files to add to the current project.
Remove Selected Items
When an item in the Project window has been selected, it may be removed from the
project by using this option from the Project menu.
Project Options...
Select this option to change the options for a project. The Project Options dialog
displays.
Project Groups...
Selecting this option displays the Project Groups dialog from which you can create
a new group or rename, remove, move up or down, or set to filter specific file types
for the default groups within an IDL Project.
Compile Modified Files
Select this option to compile only the files that have been modified since the last
compile.
Macros Menu
Edit Macros...
Select this item to access the Edit Macros dialog. Macros which have already been
defined are listed in the Macros: field. To edit a macro, click on the macro to access
its characteristics and click SAVE when your adjustments are complete.
Import Image
Select this option to import an image file into IDL. For more information, see “Using
Macros to Import Image Files” on page 193.
Import Ascii
Select this option to import an ASCII file into IDL. For more information, see “Using
Macros to Import ASCII Files” on page 197.
Import Binary
Select this option to import a binary file into IDL. For more information, see “Using
Macros to Import Binary Files” on page 203.
Import HDF
Select this option to import an HDF file into IDL. For more information, see “Using
Macros to Import HDF Files” on page 210.
Demo
Select this option to access IDL’s Demo application.
Window Menu
Stagger
Select this option to stagger all the Output Log and IDL Editor windows on the
desktop.
Tile
Select this option to tile all the Output Log and IDL Editor windows side-by-side on
the desktop.
Command Input Anchored
Select this option to anchor or unanchor the Command Input window pane. If the
window is anchored, a check will appear next to this menu item.
Command Input
Select this menu item to give the Command Input window the input focus.
Output Log
Select this menu item to bring the Output Log to the front.
Variable Watch
Select this option to give the Variable Watch Window the input focus.
Macro Editor
Select this option to bring the Macro Editor to the front.
Profile
Select this option to bring the Profile dialog to the front. See “The IDL Code
Profiler” in Chapter 14 of Building IDL Applications for more information about the
Profiler.
Profile Results
Select this option to bring the Profile Report dialog to the front. See “The IDL Code
Profiler” in Chapter 14 of Building IDL Applications for more information about the
Profiler.
Breakpoints
Select this option to bring the Edit Breakpoint window to the front.
Error Window
Select this option to bring the Error Window to the front.
Open Editor Windows
If any files and/or projects are currently open, they are listed at the bottom of the
Window menu. Select any of these menu items to make that window the current
window and give it the input focus.
Help Menu
The Help menu is located at the far right of the menu bar.
About Balloon Help...
IDL for Macintosh supports balloon help. Select this menu item to learn more about
balloon help.
Show Balloons
Select Show Balloons to activate help balloons. This menu item changes to Hide
Balloons when balloons are enabled.
IDL Online Help
Select this menu item to display the IDL Online Help Viewer.
Help on Selection
Select this menu item to display the help topic in IDL Online Help for the highlighted
item The Index dialog appears if the topic is ambiguous or does not exist.
Customizing IDL
Various defaults for IDL can be customized using the IDL Preferences dialog box.
Select Preferences from the IDL File menu to display a cascading list of preferences.
Select an item from the list to display a Preferences dialog box. Enter new values
and click on OK to use the preferences in the current IDL session. Select the Save
Settings on Exit option (a checkmark appears by the item the next time you select
Preferences) to save the preferences for use with future IDL sessions.
General Preferences
Note
To set the text formats for the current window only, select Format from the Edit
Preferences option.
Use Debugger
If this box is checked, the Debug menu appears in the menu bar and the IDL for
Macintosh debugger automatically opens an edit window containing the program
module in question when an error occurs in an IDL program.
Ask to Save Files on Compile
If this box is checked, a query dialog box appears when you try to compile your
program asking if you want to save your file before compiling.
Confirm Quit
If selected, this brings up a Confirm Quit? dialog box before exiting IDL. The
dialog must be accepted before the IDL session can quit.
Change this field to None to disable backing store. Set this field to Pixmap (the
default) to have IDL maintain backing store.
See “Backing Store” in Appendix B of the IDL Reference Guide for more
information.
Startup Depth
This popup menu allows you to specify the color pixel depth you wish to work in,
regardless of the actual depth of your monitor. All operations (saving, printing,
copying to the clipboard, etc.) will be carried out in the depth you select, even if your
monitor does not support that depth.
For example, if you wish to work with 24-bit images but your computer only supports
8-bit video, select 24-bit from the Startup Depth menu. (If you do not select Dither
to Lower Depth Screens, images will not be displayed properly on your monitor.)
Similarly, if you wish to use 8-bit, pseudo-color video even though your machine
supports 24-bit TrueColor, choose 8-bit. Select the screen depth to match the pixel
depth IDL works with to your monitor.
Note
This setting takes effect when IDL is restarted.
Note
Because of Apple’s implementation, there are some current limitations to hardware
rendering with Apple drivers. For example, back-face culling and hidden line
removal will not be performed, and there is no Apple support for hardware
rendering in 8-bit. IDL code will support these operations as these limitations are
addressed by Apple.
If your system is set up with multiple monitors, you can also choose to Accelerate
All Monitors.
Note
All monitors must be capable of Hardware Acceleration.
You can also select IDL Software Rendering. See “Window Objects” in Chapter 28
for information about the differences between the two rendering systems.
Hardware Font
Click on this button to bring up the Graphics Hardware Font dialog, which allows
you to specify the font, font size, and style to be used when hardware fonts are
specified for use in IDL graphics windows.
Note
The !P.FONT system variable field must be set equal to zero to use hardware fonts
rather than the default vector fonts.
Edit Preferences
Startup Settings
These preferences control the location of the IDL Home Folder and the IDL Startup
File.
Select IDL Main Dir...
The IDL Main Dir is the folder in which IDL was installed. It only needs to be
changed if the executable is moved somewhere else (e.g., to a special applications
folder). Clicking on this button displays a dialog for selecting the folder. The IDL
main directory is displayed below.
Select Startup File
Click this button to specify the name of an IDL batch file to be executed
automatically each time IDL is run. The startup file is displayed below.
Note
Startup files are executed one statement at a time. It is not possible to define
program modules, (procedures, functions, or main-level programs) in the startup
file.
Path Specifications
This dialog specifies where IDL will look for procedures and functions. To specify a
folder that includes all of that folder’s subfolders, select the entry in the list and click
the Search Subfolders button. A + will be shown in front of the path, indicating that
the folder is to be searched recursively. To change the path specification list, click on
either Add or Remove.
The default path is the IDL folder and all of its subfolders.
Syntax Coloring
This dialog specifies if IDL should use syntax coloring within open editor windows
and in the Command Input line. To change the color associated with a context word,
click on the color box next to each type of word. To disable syntax coloring
altogether, un-check the Use Syntax Coloring check box. To disable syntax coloring
only within the Command Input line, un-check the Use Syntax Coloring on
Command Line check box.
Message-of-the-Day File
A message-of-the-day file can be used to display the contents of an ASCII text file
each time IDL is run. To create a message-of the-day file for IDL for Macintosh,
simply name the desired text file MOTD.txt or MacOS.txt and place it in the motd
folder in the help folder in the main IDL folder. Note that the MOTD file is simply an
ASCII text file – not an IDL program or batch file. To execute a series of IDL
commands, select a startup file as described under “Startup Settings” on page 182.
If you don’t wish to see the message-of-the-day file each time you start IDL, simply
remove or rename the MacOS.txt or MOTD.txt file.
Specifying Paths
Many IDL commands accept a partially- or fully-qualified filename (i.e., a filename
and the directory path to that file) as an argument. However, the Macintosh uses a
graphical representation of file folders instead of a directory tree. To solve this
problem, the following syntax is used to specify the location of files and folders:
• Partially- or fully-qualified filenames are specified as a colon-separated list of
drive names and folders.
• Folder and file names can contain spaces and/or commas.
For example, the string to specify the fully-qualified filename of the file
myprogram.pro, located in the folder named Programs which resides on the drive
named Macintosh HD would be:
'Macintosh HD:Programs:myprogram.pro'
Note
The IDL routine DIALOG_PICKFILE does not change the current directory.
File Manipulation
Compiling Programs
Because Macintosh filenames allow spaces, the .RUN, .RNEW, and .COMPILE
executive commands cannot be used to compile multiple programs with a single
command.
For example, on most IDL platforms, the following line compiles three IDL program
files named test, demo, and program:
IDL> .RUN test demo program
However, since Macintosh filenames can have spaces in them, the filenames shown
above would be interpreted as a single filename. In IDL for Macintosh, you can only
specify one filename per .RUN command. For example:
IDL> .RUN Macintosh HD:Programs:test
Save/Restore Files
SAVE/RESTORE files generated with the Macintosh version of IDL are saved in the
XDR format. This format allows data files saved under UNIX, VMS, Macintosh and
DOS systems to be easily exchanged.
Logical Unit Numbers
The three special file units, 0, –1, and –2, are tied to stdin (the Command Input
line), stdout (the Output Log) and stderr (the Output Log), respectively.
Positioning File Pointers
Under Macintosh, the current file pointer cannot be positioned past the end of the file.
Note
The type code is always four characters long, so the BIN type code includes an
ASCII space character at the end.
Overview
IDL contains macros to ease the importing of data into IDL. This chapter introduces
these macros and describes how to import image, ASCII, binary, and Scientific Data
Format (SDF) files. These macros are available through the Macros menu and also
through new IDL Tool Bar buttons.
Figure 6-1: Importing Data Macros Menu (Left) and Tool Bar Buttons (Right)
You can now see a preview of this image as well as other information about
the file in the lower section of the Select Image File dialog. You can change
the preview to Color, Grayscale, or No Preview. If the image file had more
than one actual image, you can see them using the arrow buttons to scroll
through the images. You can only read in one image of a multi-image file. The
image in the preview is the image that will be read.
3. Click Open.
4. The file has been opened into a structure variable named MUSCLE_IMAGE.
Images opened with the Import Image File macro are stored in structure variables
which are named filename_IMAGE where filename is the name of the file you
opened without the extension.
Note
IDL variables must begin with a letter, and may contain only letters, digits, the
underscore character, or the dollar sign. If the first character of filename is not a
letter, the prefix “var” is added to the variable name. Any spaces within filename
are converted to underscores. Any other illegal characters within filename are
removed.
So, the file we just opened (muscle.jpg) is now in the structure variable named
MUSCLE_IMAGE. The file is a structure with the following fields:
• IMAGE — The actual image array.
• R — The red color table vectors.
• G — The green color table vectors.
• B — The blue color table vectors.
• QUERY — Contains information about the image.
• CHANNELS — The number of channels in the image.
• HAS_PALETTE — Specifies if the palette is present. 1 if the palette is
present, else 0. If your image is n-by-m the palette is usually present and
the R, G, and B color table vectors mentioned above will contain values. If
your image is 3-by-n-by-m, the palette will not be present and the R,G, and
B color table vectors will not contain any values.
• IMAGE_INDEX — The index of the image of the file. The default is 0,
the first image in the file. If there are multiple images in the file that you
read, this will be the number (or index) of the image.
• NUM_IMAGES — The number of images in the original file.
• PIXEL_TYPE — The IDL Type Code of the image pixel format. Valid
types are:
You can specify which part of the structure variable you want to access by using the
following syntax:
variable_name.element_name[.element_name]
For example, if you want to view the image, enter the following:
TV, MUSCLE_IMAGE.IMAGE
IDL prints:
JPEG
3. In the Define Data Type/Range dialog, you specify information about your
file. The first few lines of the file are displayed to help you find the
information you need to specify.
First, select the type of field which best describes your data. You can either
choose Fixed Width which specifies that the data is aligned in columns, or
Delimited which specifies that the data is separated by commas, whitespace,
etc. In this example, the data is delimited by commas so we’ll select the
Delimited radio button.
Next, enter a character or string that is used to comment lines within the file in
the Comment String to Ignore: field. In this example, if we read the first few
lines of this file, it defines the % character as the comment character. Enter the
% sign in the Comment String to Ignore: field.
Next, enter the line number in which the data starts in the Data Starts at Line:
field. In this example, the data starts on line 6 so we’ll enter that value in the
field.
Click Next.
4. In the Define Delimiter/Fields dialog, we’ll specify the information about the
actual data in the file.
First, we’ll enter the number of columns or fields in the Number of Fields Per
Line: field. In this example, there are 7 fields.
Next, we’ll enter the how the data is delimited. You can choose White Space,
Comma, Colon, Semicolon, Tab, or Other. If you specify Other, you must
then enter the characters in the field. In this example, we’ll select Comma
since the data is delimited by commas.
Click Next.
5. In the Field Specification dialog, we’ll enter information about the contents of
each column or field in the data.
First, select the first field in the data in the box in the upper left of the dialog.
Enter the name of the field in the Name field and the type of data represented
in the Type field. In this example we’ll specify Longitude and Floating for
the fields. Continue naming all the fields in the data using this procedure. In
this example, we’ll use Latitude – Floating; Elevation – Long; Temperature –
Long; DewPoint – Long; WindSpeed – Long; WindDir – Long for the other
field pairs.
You can also group some or all of the fields into one field by using the Group
or Group All buttons. In this example, there is no need to group any of the
fields.
Next, select the value to assign missing data. You can select the IEEE standard
for NaN or a custom value. In this example, we’ll choose IEEE NaN.
6. Click Finish.
ASCII files opened with the Import ASCII File macro are stored in structure
variables which are named filename_ASCII where filename is the name of the file
you opened without the extension.
Note
IDL variables must begin with a letter, and may contain only letters, digits, the
underscore character, or the dollar sign. If the first character of filename is not a
letter, the prefix “var” is added to the variable name. Any spaces within filename
are converted to underscores. Any other illegal characters within filename are
removed.
So, the file we just opened (ascii.txt) is now in the structure variable named
ASCII_ASCII. The variable is a structure with each field name being an element of
the structure.
The structure can be viewed in the Variable Watch Window.
You can specify which part of the structure variable you want to access by using the
following syntax:
variable_name.element_name
For example, if you want to view the Longitude field, enter the following:
Print, ASCII_ASCII.LONGITUDE
IDL prints:
-156.950 -116.967 -104.255 -114.522 -106.942
-94.7500 -73.6063 -117.176 -116.093 -106.372
-93.2237 -109.635 -76.0225 -93.1535 -118.721
Note
The Import Binary File macro is intended for use in loading raw binary data from
files into IDL. Such data is comprised of bits that are meaningful — as integers or
floating-point numbers for example — with no special processing (except possibly
byte-order swapping) required. Commercial spreadsheet or word processing files,
for example, are binary but they are not raw in the above sense, and thus are not
good candidates for use with this macro.
Also note that the Import Binary File macro is intended for use in loading data
from files the contents of which you have some knowledge about. To effectively
read data with this macro, you must be able to supply literal values or expressions
that specify the type and location of the data in the file you wish to read.
3. In the Binary Template dialog box, specify information about your file.
First, enter the name of the template you are going to create in the Template
name: field. For this example, “marbellstemplate” is used.
Next, select the byte order in the file in the File’s byte ordering: pull-down
menu. The choices are:
• Native — The type of storage method that is native to the machine you are
currently running. Little Endian for Intel microprocessor-based machines
and Big Endian for Motorola microprocessor-based machines. No byte
swapping will be performed.
• Little Endian — A method of storing numbers so that the least significant
byte appears first in the number. For example, given the hexadecimal
number A02B, the little endian method specifies the number to be stored
as 2BA0. Specify this if the original file was created on a machine that
uses an Intel microprocessor.
• Big Endian — A method of storing numbers so that the most significant
byte appears first in the number. For example, given the hexadecimal
number A02B, the big endian method specifies the number to be stored as
A02B. Specify this if the original file was created on a machine that uses a
Motorola microprocessor.
The file surface.dat was created on a machine that uses an Intel
microprocessor. For this example, select Little Endian for the byte order.
4. Now we are ready to enter the field values for the file. You can have multiple
fields within a binary file. Click the New Field... button in the lower-left
corner of the Binary Template dialog box.
In the New Field dialog (shown at the end of these example steps), enter the
name of the field in the Field name: text box. In this example, enter “A” as the
field name.
Next, you need to specify where in the file to start reading. The options are:
• Offset — Specifies the byte offset or where to begin reading the file. This
is always a decimal integer unless the Allow an expression for the offset
checkbox is checked. The > symbol specifies to offset forward from a byte
position, the < symbol specifies to offset backward from a byte position.
• From beginning of file — Specifies to start reading this field starting with
the first byte of the file plus any Offset specified.
• From initial position in file/From end of previous field — This field
changes depending upon if this is the first field or any other field besides
the first. If this is the first field you are defining, this option specifies to
read from the beginning of the file plus any Offset specified. If this is not
the first field, this option changes to From end of previous field and
specifies to begin reading the field where the previous field ended plus any
Offset specified.
• Allow an expression for the Offset — If this is checked, you can enter
any valid IDL expression in the Offset field. You can use any previously
defined field in the expression.
In this example, since this is the first field in the file and we don’t have any
header information in the file, specify From the beginning of file without any
offset.
Next, select whether or not you want this field to be returned to IDL when a
file is read. For example, you may have a section of your binary file that
contains header information. If you create a field for this section, you do not
want it returned to IDL. In this case, you would not select Returned in the
result. You must specify at least one field to be returned to IDL. In this
example, we want to return the field we’re creating so we’ll check the box in
the upper-right corner marked Returned in the result.
Next, you need to specify whether or not you want to verify any of the data you
are returning in the Verified equal to field. This field is only available if the
field is a scalar. This can be any valid IDL expression that evaluates to a scalar.
For this example, we won’t verify any of the data.
Next, you need to specify the type of data that is in this field. In this example,
the data is integer type data so select the Integer (16 bits) at the Type pull-
down menu. The valid values for Type are:
• Byte (unsigned 8-bits)
• Integer (16-bits)
• Long (32-bits)
• Long64 (64 bits)
• Float (32 bits)
• Double-Precision (64-bits)
• Unsigned Integer (16 bits)
• Unsigned Long (32-bits)
• Unsigned Long64 (64-bits)
• Complex (real-imaginary pair of floats)
• Double-Precision Complex (pair of doubles)
Next, specify the number of dimensions contained in the data in the Number
of dimensions: pull-down menu. This will activate a corresponding number of
boxes in the dimensions section of the dialog. In this example, the data is two-
dimensional.
Finally, enter the size of each dimension in the field. If you select the Allow
expressions for dimension sizes check box, you enter any valid IDL
expression that returns the size of the dimension. You can also choose to
reverse the order of the data by selecting the Reverse check box for each
dimension. This can be useful when image data is returned in the reverse order
and appears upside down. In this example, the data is contained in a 350-by-
450 array, so enter 350 for the size of the 1st dimension and 450 for the size of
the 2nd dimension in the text fields marked Size:.
Click OK.
5. You can now see the information that you entered in the Binary Template
dialog. If you need to enter more fields, select the New Field button. Repeat
the steps until you have entered all the fields in the binary file.
In this example, there is only one field. Click OK.
Binary files opened with the Import Binary File macro are stored in structure
variables which are named filename_BINARY where filename is the name of the file
you opened without the extension.
Note
IDL variables must begin with a letter, and may contain only letters, digits, the
underscore character, or the dollar sign. If the first character of filename is not a
letter, the prefix “var” is added to the variable name. Any spaces within filename
are converted to underscores. Any other illegal characters within filename are
removed.
So, the file we just opened (surface.dat) is now in the structure variable named
SURFACE_BINARY. The variable is a structure with each field name being an
element of the structure.
The structure can be viewed in the Variable Watch Window.
You can specify which part of the structure variable you want to access by using the
following syntax:
variable_name.element_name
For example, display the image by entering:
TVSCL, SURFACE_BINARY.A
Next, select the type of data you want to import. The following tables describe
the options available for the two display choices from the pull-down menu.
Once you have selected the type of data, information is displayed that shows
the different elements of data available in the file you are opening. For
example, if it is an image file, you will see the names of the images displayed.
Select the item to import.
If you have selected an image, 2D data set, or 3-by-n-by-m data set from the
pull-down menu, you can click on the Preview button to view the image. If
you have selected a data item that can be plotted in two dimensions, click on
the Preview button to view a 2D plot of the data (the default); or click on the
Preview Surface radio button to display a surface plot; click on the Preview
Contour radio button to display a contour plot; or click on the Preview Show3
radio button for an image, surface, and contour display. You can also select the
Fit to Window check box to fit the image to the window.
Next, if you want the data or metadata item you are previewing to be imported
into IDL, select the Read check box to extract the current data or metadata
item from the HDF file.
Next, specify a name for the extracted data or metadata item.
Note
The Read check box must be selected for the item to be extracted. Default names
are generated for all data items, but may be changed at any time by the user.
4. Continue selecting to read and name the data or metadata items you want to
import into IDL.
5. Click OK.
HDF, NETCDF, or HDF-EOS files read with the Import Binary File macro are
stored in structure variables which are named filename_DF where filename is the
name of the file you opened without the extension.
Note
IDL variables must begin with a letter, and may contain only letters, digits, the
underscore character, or the dollar sign. If the first character of filename is not a
letter, the prefix “var” is added to the variable name. Any spaces within filename
are converted to underscores. Any other illegal characters within filename are
removed.
The variable is a structure with each data or metadata name being an element of the
structure. You can specify which part of the structure variable you want to access by
using the following syntax:
variable_name.data_name
For example, if you imported two data elements out of a file named hydrogen.hdf and
you named the elements IMAGE1 and IMAGE2, you could access each individual
data element using the following:
HYDROGEN_DF.IMAGE1
HYDROGEN_DF.IMAGE2
If you wanted to view IMAGE1, you would enter:
TV, HYDTROGEN_DF.IMAGE1
For more information on IDL support of HDF and other scientific data formats, see
the Scientific Data Formats manual.
List of Commands
The following routines are used for reading and writing image data. These IDL
routines provide access to specialized functionality in the case of more specific
applications.
Images (Generalized)
Button Function
Open Opens the selected image file.
Cancel Cancels the current image selection.
Arrow Keys Pages through multiple images in the file.
Button Function
Save Saves the image file.
Cancel Cancels the save function.
Options Brings up a dialog box of image format save options.
Tag Definition
CHANNELS Long
DIMENSIONS One-dimensional long array
FILENAME Scalar string
HAS_PALETTE Integer
IMAGE_INDEX Long
NUM_IMAGES Long
PIXEL_TYPE Integer
TYPE Scalar string
QUERY_BMP QUERY_PNG
QUERY_DICOM QUERY_PPM
QUERY_JPEG QUERY_SRF
QUERY_PICT QUERY_TIFF
READ_* Routines
IDL includes a number of routines for reading standard graphics file formats.These
routines read the image file format and returns the image and color table vectors (if
present). The following is a list of the current READ_ routines:
READ_BMP READ_PNG
READ_DICOM READ_PPM
READ_JPEG READ_SRF
READ_PICT READ_TIFF
WRITE_* Routines
IDL has added a consistent set of write routines to the existing IDL image file format
functions to allow users to write an image and its color table vectors to a file of a
specified type. The following is a list of the current WRITE_ routines:
WRITE_BMP WRITE_PNG
WRITE_DICOM WRITE_PPM
WRITE_JPEG WRITE_SRF
WRITE_PICT WRITE_TIFF
Directory Selection
The DIRECTORY keyword allows the user to select a directory rather than a file
name with the DIALOG_PICKFILE function. See DIALOG_PICKFILE in the IDL
Reference Guide for details.
Result = DIALOG_PICKFILE( )
Result = DIALOG_PICKFILE(/MULTIPLE_FILES)
CASE event.DONE OF
0: BEGIN
state.file = event.VALUE
WIDGET_CONTROL, event.top, SET_UVALUE=state, /NO_COPY
END
1: BEGIN
IF (state.file NE '') THEN BEGIN
img = READ_IMAGE(state.file)
TV, img
ENDIF
WIDGET_CONTROL, event.top, SET_UVALUE=state, /NO_COPY
END
2: WIDGET_CONTROL, event.top, /DESTROY
ENDCASE
END
PRO image_opener
END
Overview
IDL recognizes two types of ASCII data files: free format files, and explicit format
files. A free format file uses commas or tabs and spaces to distinguish each element
in the file. An explicit format file distinguishes elements according to the commands
specified in a format statement.
This command assigns the description of the data to a variable named template. IDL
will display a dialog box which prompts the user to select a file.
Note
If a filename is specified in the parentheses after the ASCII_TEMPLATE function,
this screen will not appear.
Once a file has been selected, IDL displays the first of three pages of the
ASCII_TEMPLATE dialog.
The first page displays a representative sample of lines from the data file with their
numbers on the left. Select the field type that best describes the data. Click the Next
button on the bottom-right corner of the screen to move to the next page.
The second page displays the number of fields per line which is listed as three and the
white space is selected for the data delimiter. Click the Next button on the bottom
right corner of the screen to move to the next page.
The third page displays the columns in the data set which can be named and their data
type specified. Name the fields by typing in the name text at the upper right of the
form. Click the Finish button on the bottom-right corner of the screen.
The result is an IDL structure variable that describes the data in the file and can be
used as input to the READ_ASCII command.
Overview
Binary data or binary data files are more compact than ASCII data files and are
frequently used for large data files. Binary data files are stored as one long stream of
bytes in a file.
An absolute offset specifies a fixed location (in bytes) from the beginning of the file
(or the initial file position for an externally opened file).
A relative offset specifies a position relative to the current file position pointer after
the previous field (if any) is read. Relative offsets are shown in the
BINARY_TEMPLATE user interface with a preceding > or < character, to indicate a
positive (>) or negative (<) byte offset.
The following example creates a template for a binary file using the
BINARY_TEMPLATE function. The following command invokes the binary
template dialog.
Result = BINARY_TEMPLATE (filename)
The binary template dialog box appears and a template for reading a binary file has
now been generated. In the Template Name field, enter the name of the new
template.
Note
The template name is optional, this field can be left blank.
Fields are read in the order in which they are listed in the main dialog for
BINARY_TEMPLATE with offsets being added to the current file position pointer
before each field is read. Offsets may be specified via expressions or literals. The
user checks a checkbox to allow the input of expressions, if an expression is needed.
Literals are unsigned decimal integers. Expressions can be any legal IDL syntax. If
the user desires to enter a hex value, they can do so by entering it as an expression.
Also, an expression may use any previously read field as a variable in an IDL
expression.
The Type of each Template-specified field is selected from a droplist or specified via
an expression which yields an IDL type code (the type code is also generated via an
expression which can be a function of any previously read fields). The droplist offers
the following IDL types: byte, integer, long, float, double, complex, dcomplex, uint,
ulong, long64 and ulong64. Strings are read as an array of bytes for later conversion
to type STRING.
The number of dimensions of a field can be set via a droplist of values 0 (scalar) to 8
(which is the maximum number of dimensions that an IDL variable can have.)
Alternately, the size of each dimension can be an expression, which would allow the
dimensions of a field to be determined at file-read time.
Any of the first three dimensions of array data can also be specified to be reversed in
order. A Verify field can be any valid IDL expression. Only scalar fields can be
verified. This template can be saved to disk for later access, used to guide
READ_BINARY or passed back to BINARY_TEMPLATE for further editing.
The field name can be any name the user chooses. It does not have to be the template
name. The Number of Dimensions is a pull-down menu. In the two boxes marked
Size, enter the size of the array. Specify the type of data in the Type field.
Fields can define themselves in terms of other fields using IDL expressions. Fields
need not be returned to the user at READ_BINARY time, but can be used to define
other fields. Scalar fields can also be labeled as Verify. All comparisons in a
verification are based on equality. If a sample data file is given in the call to
BINARY_TEMPLATE, verified fields are read from the sample data file and
checked against their specified verify value. When READ_BINARY is called with a
template specifying that fields be verified, READ_BINARY reports an error if a
verification fails.
Templates must have at least one field marked yes for return from READ_BINARY.
The value for a Verify field can be entered as an expression in IDL syntax, including
hex literal values or expressions involving previously defined fields.
Result = READ_BINARY('surface.dat', TEMPLATE=template)
Graphics
Overview
Beginning with IDL version 5.0, IDL supports two distinct graphics modes: Direct
Graphics and Object Graphics. Direct Graphics rely on the concept of a current
graphics device; IDL commands like PLOT or SURFACE create images directly on
the current graphics device. Object Graphics use an object-oriented programmers’
interface to create graphic objects, which must then be drawn, explicitly, to a
destination of the programmer’s choosing.
Direct Graphics
Plotting
The following topics are covered in this 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 “Plotting
Multi-Dimensional Arrays” in Chapter 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.
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 257.
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.
Coordinate
Linear Logarithmic
Conversion
Data to normal Nx = X0 + X1 Dx N x = X 0 + X 1 log D x
Data to device Rx = Vx ( X0 + X1 Dx ) R x = V x ( X 0 + X 1 log D x )
Normal to device Rx = Nx Vx Rx = Nx Vx
Normal to data Dx = ( Nx – X0 ) ⁄ X1 D x = 10 ( Nx – X0 ) ⁄ X1
Device to data D x = ( R x ⁄ V x – X 0 ) ⁄ X 1 D x = 10 ( Rx ⁄ Vx – X0 ) ⁄ X1
Device to normal Nx = Rx ⁄ Vx Nx = Rx ⁄ Vx
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
If you prefer not to enter the data by hand, run the batch file plot01 with the
following command at the IDL prompt:
@plot01
See “Running the Example Code” on page 254 if IDL does not find the batch file.
The following IDL commands create a plot of the population of Sockeye salmon, by
year:
PLOT, YEAR, SOCKEYE, $
TITLE='Sockeye Population', XTITLE='Year', $
YTITLE='Fish (thousands)'
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. Note that the three titles, defined by the keywords TITLE, XTITLE, and
YTITLE, are optional.
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 470, and IDL creates tick-mark
intervals of 10.
;Define variables:
@plot01
PLOT, YEAR, SOCKEYE, /YNOZERO, $
TITLE='Sockeye Population', XTITLE='Year', $
YTITLE='Fish (thousands)'
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 = 'Sockeye!CPopulation'
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, set the [XY]MARGIN
keywords or increase the values of !X.MARGIN 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).
See STYLE in the IDL Reference Guide for details on 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 following
figure 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:
; Define variables:
@plot01
PLOT, YEAR, SOCKEYE, /YNOZERO, $
TITLE='Sockeye Population', XTITLE = 'Year', $
YTITLE = 'Fish (thousands)', 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, line style, 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 sample.
First, we define an n-by-4 array containing all four sample vectors. (This array is also
defined by the plot01 batch file.)
ALLPTS = [[COHO], [SOCKEYE], [HUMPBACK], [CHINOOK]]
The plot in the preceding figure was produced with the following statements:
Using IDL Direct Graphics Coordinate Systems
264 Chapter 11: Direct Graphics Plotting
; Define variables:
@plot01
; Plot first graph. Set the y-axis min and max
; from the min and max of all data sets. Default linestyle is 0.
PLOT, YEAR, COHO, YRANGE = [MIN(ALLPTS), MAX(ALLPTS)], $
TITLE='Salmon Populations', XTITLE = 'Year', $
YTITLE = 'Fish (thousands)', XRANGE = [1975, 1983], $
/XSTYLE
; Loop for the three remaining scores, varying the linestyle:
FOR I = 1, 3 DO OPLOT, YEAR, ALLPTS[*, I], LINE = I
See XYOUTS in the IDL Reference Guide for a complete list of keywords available
when adding graphic text to a plot.
The next figure illustrates one method of annotating each graph with its name. The
plot was produced exactly as was the previous 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 sample population also is
defined.
First, we define an array containing names for each of the lines plotted. (This array is
also defined by the plot01 batch file.)
NAMES=['Coho','Sockeye','Humpback','Chinook']
Font Selection
The previous figure also illustrates the use of a PostScript font (Times-Roman, in this
case) for the titles and annotations. Note that PostScript fonts can only be used when
the current graphics devices is set to PostScript.
This font was selected by first setting the default font, controlled by the system
variable !P.FONT, to the hardware-font index of zero, and then calling the DEVICE
procedure to set the Times-Roman font. To recreate the plot using this font on your
system, inspect the batch file plot02, located in the examples/doc subdirectory of
the IDL distribution. Note that running this batch files creates a PostScript file named
plot.ps in your current working directory. See “Running the Example Code” on
page 254 if IDL does not find the batch file.
Warning
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 Appendix H, “Fonts” in the IDL Reference Guide.
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 Sockeye population values to a quadratic function of
the year. The IDL function POLY_FIT is used to calculate the quadratic.
Alternatively, you can run the following batch file to create the plot:
@plot03
See “Running the Example Code” on page 254 if IDL does not find the batch file.
The color and line thickness used to draw the symbols are also optional keyword
parameters of USERSYM. The following code illustrates the use of USERSYM to
define a new symbol—a filled circle:
; Make a vector of 16 points, A[i] = 2pi/16:
A = FINDGEN(17) * (!PI*2/16.)
; Define the symbol to be a unit circle with 16 points,
; and set the filled flag:
USERSYM, COS(A), SIN(A), /FILL
Using the variables defined in the above example, we then create the plot, specifying
8 (user-defined) for the PSYM keyword to PLOT:
PLOT, YEAR, SOCKEYE, /YNOZERO, PSYM = 8, $
TITLE = 'Quadratic Fit', XTITLE = 'Year', $
YTITLE = 'Sockeye Population'
; Overplot the smooth curve using a plain line:
OPLOT, YEAR, YFIT
Histogram Mode
Using the keyword PSYM=10 with the PLOT routines draws graphs in the histogram
mode, connecting points with vertical and horizontal lines. This next figure illustrates
the comparison between the distribution of the IDL normally distributed random
number function (RANDOMN) to the theoretical normal 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 Chinook population graph with a color index of 25 percent the maximum,
then filling the region under the Sockeye population graph with 50 percent of the
maximum index. Because the Chinook populations are always higher than the
Sockeye populations, 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 258), the variable MINVAL, is set to the current y-axis minimum,
!Y.CRANGE[0]. Next, the upper Chinook population region is shaded with a
polygon that contains the vertices of the Chinook samples, preceded and followed by
points on the x-axis, (YEAR[0], MINVAL), and (YEAR[n-1], MINVAL). The polygon
for the Sockeye samples is drawn using the same method with a different color.
Finally, the XYOUTS procedure is used to annotate the two regions.
Enter the following IDL commands to create the plot:
; Define variables:
@plot01
; Draw axes, no data, set the range:
PLOT, YEAR, CHINOOK, YRANGE = [MIN(SOCKEYE), MAX(CHINOOK)], $
/NODATA, TITLE='Sockeye and Chinook Populations', $
XTITLE='Year', YTITLE='Fish (thousands)'
; Make a vector of x values for the polygon by duplicating
; the first and last points:
PXVAL = [YEAR[0], YEAR, YEAR[N1]]
;Get y value along bottom x-axis:
MINVAL = !Y.CRANGE[0]
; Make a polygon by extending the edges down to the x-axis:
POLYFILL, PXVAL, [MINVAL, CHINOOK, MINVAL], $
COL = 0.75 * !D.N_COLORS
; Same with second polygon.
POLYFILL, PXVAL, [MINVAL, SOCKEYE, MINVAL], $
COL = 0.50 * !D.N_COLORS
; Label the polygons:
XYOUTS, 1968, 430, 'SOCKEYE', SIZE=2
XYOUTS, 1968, 490, 'CHINOOK', SIZE=2
Alternatively, you can run the following batch file to create the plot:
@plot04
See “Running the Example Code” on page 254 if IDL does not find the batch file.
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 salmon
populations as boxes of differing colors or shading. The commands used to draw the
next figure are shown below with annotation. You do not need to type these
commands in yourself; they are collected in the files plot05.pro, which contains
the two procedures, and plot06, which contains the found in the examples/doc
subdirectory of the IDL distribution.
First, we define a procedure called BOX, which draws a box given the coordinates of
two diagonal corners:
; Define a procedure that draws a box, using POLYFILL,
; whose corners are (X0, Y0) and (X1, Y1):
PRO BOX, X0, Y0, X1, Y1, color
; Call POLYFILL:
POLYFILL, [X0, X0, X1, X1], [Y0, Y1, Y1, Y0], COL = color
END
Enter the following at the IDL prompt to compile these two procedures from the IDL
distribution:
.run plot5.pro
To create the bar graph on your screen, enter the following commands.
; Load a color table:
LOADCT, 39
As in the previous example, the PLOT procedure is used to draw the axes and to
establish the scaling using the NODATA keyword.
PLOT, year, CHINOOK, YRANGE = [MIN(allpts),MAX(allpts)], $
TITLE = 'Salmon Populations', /NODATA, $
XRANGE = [year[0], 1990]
; Get the y value of the bottom x-axis:
minval = !Y.CRANGE[0]
; Create the bar chart:
BARGRAPH, minval
Alternatively, you can run the following batch file to create the plot:
@plot06
See “Running the Example Code” on page 254 if IDL does not find the batch file.
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 line style to be used for plot tick marks and grids (i.e., when
TICKLEN is set to 1.0). See [XYZ]GRIDSTYLE in the IDL Reference Guide for
more information.
[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. See
[XYZ]MINOR in the IDL Reference Guide for more information.
[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.
See [XYZ]THICK in the IDL Reference Guide for more information.
[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
[XYZ]TICKFORMAT in 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. See TICKLEN in the IDL
Reference Guide for more information.
[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 force IDL to number the tick mark with its
value. See [XYZ]TICKNAME in the IDL Reference Guide for more information.
Note
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. See [XYZ]TICKS in the IDL Reference Guide for
more information.
[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. See [XYZ]TICKV in the IDL Reference Guide for more
information.
Using the data and variables from above, the following commands create the box
chart:
Enter the following command at the IDL prompt to compile the BOX and BARGRAPH
procedures (discussed in the previous example) from the IDL distribution:
.run plot05.pro
Alternatively, you can run the following batch file to create the plot:
@plot07
See “Running the Example Code” on page 254 if IDL does not find the batch file.
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 illustrates using PLOT to make a linear-log plot. It was produced with the
following statements:
; Create data array:
X = FLTARR(256)
; Make a step function. Array elements 80 through 120 are set to 1:
X[80:120] = 1
; Make a filter:
FREQ = FINDGEN(256)
; Make the filter symmetrical about the value x = 128:
FREQ = FREQ < (256-FREQ)
; Second order Butterworth, cutoff frequency = 20.
FIL = 1./(1+(FREQ/20)^2)
; Plot with a logarithmic x-axis. Use exact axis range:
PLOT, /YLOG, FREQ, ABS(FFT(X,1)), $
XTITLE = 'Relative Frequency', YTITLE = 'Power', $
XSTYLE = 1
; Plot graph:
OPLOT, FREQ, FIL
Alternatively, you can run the following batch file to create the plot:
@plot08
See “Running the Example Code” on page 254 if IDL does not find the batch file.
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]
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
Figure 11-13: Multiple Plots Per Page, Various Tick Marks, and Multiple Axes
This figure shows four plots in a single window. For details, inspect the batch file
plot09 in the examples/doc subdirectory of the IDL distribution. Note the
following features of the plots in the figure:
1. The plot in the upper left has grid-style tick marks. This is accomplished by
setting the TICKLEN keyword equal to 1.0
2. The plot in the upper right has outward-facing tick marks. This is
accomplished by setting the TICKLEN keyword to a negative value.
3. The plot in the lower left corner has different axes on left and right, top and
bottom. This is accomplished by drawing the top and right axes separately,
using the AXIS procedure.
4. The plot in the lower right uses no default axes at all. The centered axes are
drawn with calls to the AXIS procedure.
Figure 11-14: The Plot-Data Window, Plot Region, and Device Area
Relationship
The figure 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
The POSITION keyword is accepted by the CONTOUR, MAP_SET, PLOT,
SHADE_SURF, and SURFACE routines. Its value is 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
!P.POSITION is the system variable equivalent of the POSITION keyword. Its value
is 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
The !P.REGION system variable is 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
!P.MULTI controls the number of plots per page. It is described in “Multiple Plots on
a Page” on page 280.
[XYZ]MARGIN
The [XYZ]MARGIN keywords are accepted by the AXIS, CONTOUR, PLOT,
SHADE_SURF, and SURFACE routines. The value of each of these keywords is a 2-
element array specifying the margin on the left and right sides (XMARGIN) or the
top and bottom (YMARGIN) 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. The ZMARGIN
keyword is present for consistency and is currently ignored.
![XYZ]MARGIN
![XYZ]MARGIN are the system variable equivalents of the [XYZ]MARGIN
keywords.
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” in Building IDL Applications.)
Date/Time Plotting
Dates and times are among the many types of information that numerical data can
represent. IDL provides a number of routines that offer specialized support for
generating, analyzing, and displaying date- and time- based data (herein referred to as
date/time data).
Julian Dates and Times
Within IDL, dates and times are typically stored as Julian dates. A Julian date is
defined to be the number of days elapsed since noon on January 1, 4713 BCE.
Following the astronomical convention, a Julian day is defined to start at 12pm
(noon). The following table shows a few examples of calendar dates and their
corresponding Julian dates.
Julian dates can also include fractional portions of a day, thereby incorporating hours,
minutes, and seconds. If the day fraction is included in a Julian date, it is represented
as a double-precision floating point value. The day fraction is computed as follows:
One advantage of using Julian dates to represent dates and times is that a given
date/time can be stored within a single variable (rather than storing the year, month,
day, hour, minute, and second information in six different variables). Because each
Julian date is simply a number, IDL’s numerical routines can be applied to Julian
dates just as for any other type of number.
Note
Julian values must be in the range -1095 to 1827933925, which corresponds to
calendar dates 1 Jan 4716 B.C.E. and 31 Dec 5000000, respectively.
; Convert to seconds:
PRINT, precision*86400d0
where the UNIT keyword is set to 'Months' to increment by month and the START
keyword is set to the Julian date form of March 1, 2000.
The results of the above call to TIMEGEN can be output using either of the following
methods:
1. Using the CALDAT routine to convert the Julian dates to calendar dates:
CALDAT, date_time, month, day, year
FOR i = 0, (N_ELEMENTS(date_time) - 1) DO PRINT, $
month[i], day[i], year[i], $
FORMAT = '(i2.2, "/", i2.2, "/", i4)'
The TIMEGEN routine contains several keywords to provide specific date/time data
generation. For more information, see the TIMEGEN in the IDL Reference Guide.
Normally, this type of data would be imported into IDL from a data file. However,
this section is designed specifically to show how to display date/time data, not how to
import data from a file; therefore, the data for this example is created with the above
IDL commands.
Before displaying this one-dimensional data with the PLOT routine, the format of the
date/time values is specified through the LABEL_DATE routine as follows
date_label = LABEL_DATE(DATE_FORMAT = ['%I:%S'])
The XTICKUNITS keyword is set to note the tick labels contain date/time data. The
XTICKINTERVAL keyword is set to place the major tick marks at every five second
interval. These keyword settings produce the following results:
The above display shows the progression of the date/time variable, but it does not
include all of the date/time data we generated with the TIMEGEN routine. This data
also includes hour, month, day, and year information. IDL can display this
information with additional levels to the date/time axis. You can control the number
of levels to draw and the units used at each level with the XTICKUNITS keyword.
You can specify the formatting for these levels by changing the DATE_FORMAT
keyword setting to the LABEL_DATE routine:
date_label = LABEL_DATE(DATE_FORMAT = $
['%I:%S', '%H', '%D %M, %Y'])
The POSITION keyword is set to allow the resulting display to contain all three
levels and the title of the date/time axis. The XTICKFORMAT is now set to a string
array containing an element for each level of the axis. The XTICKUNITS keyword is
set to note the unit of each level. These keyword settings produce the following
results:
Notice the three levels of the X-axis. These levels are arranged as specified by the
previous call to the LABEL_DATE routine.
Since the final contour display will be filled, we should define a color table:
DEVICE, DECOMPOSED = 0
LOADCT, 5
The call to the DEVICE command with the DECOMPOSED keyword set to zero
allows color tables to be used on TrueColor displays, which may be the default
setting on some systems. The call to the LOADCT routine loads the Standard
Gamma-II (number 5) color table, which is a part of IDL's libraries.
As with the one-dimensional case, the format of the date/time values is specified
through the LABEL_DATE routine as follows
date_label = LABEL_DATE(DATE_FORMAT = $
['%I:%S', '%H', '%D %M, %Y'])
As in the plot example, the POSITION keyword is set to allow the resulting display
to contain all three levels and the title of the date/time axis. The YTICKUNITS
keyword is set to note the unit of each level. And the YTICKINTERVAL keyword is
set to place the major tick marks at every five second interval.
This example also contains the YTICKLAYOUT keyword. By default, this keyword
is set to 0, which provides the date/time layout shown in the plot example. In this
example, YTICKLAYOUT is set to 2, which rotates and boxes the tick labels to
provide the following results:
Usually, keywords are used more frequently than system variables, but system
variables are better when trying to establish a consistent display style. For example,
we could have established a date/time axis style with these system variables before
producing our previous displays:
; Establishing an axis style.
!X.TICKFORMAT = ['LABEL_DATE', 'LABEL_DATE', 'LABEL_DATE']
!X.TICKUNITS = ['Time', 'Hour', 'Day']
!X.TICKINTERVAL = 5
!X.TICKLAYOUT = 2
; Displaying data.
PLOT, date_time, displacement, /XSTYLE, $
TITLE = 'Measured Signal', $
XTITLE = 'Time (seconds)', $
YTITLE = 'Displacement (inches)', $
POSITION = [0.2, 0.7, 0.9, 0.9]
CONTOUR, temperature, date_time, angle, /FILL, $
LEVELS = BYTSCL(INDGEN(8)), /XSTYLE, /YSTYLE, $
C_COLORS = BYTSCL(INDGEN(8)), /NOERASE, $
TITLE = 'Measured Temperature (degrees Celsius)', $
XTITLE = 'Angle (degrees)', $
YTITLE = 'Time (seconds)', $
POSITION = [0.2, 0.25, 0.9, 0.45]
CONTOUR, temperature, date_time, angle, /OVERPLOT, $
LEVELS = BYTSCL(INDGEN(8))
!X.TICKLAYOUT = 0
!X.TICKINTERVAL = 0
!X.TICKUNITS = ''
!X.TICKFORMAT = ''
Notice these system variables are set to their default values after the two displays are
shown. When using system variables instead of keywords, remember to reset the
system variables back to their default values. The above example produces the
following results:
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.
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 the data, omit right and top axes:
PLOT, DAY, TEMP, /YNOZERO, $
SUBTITLE = 'Denver Average Temperature', $
XTITLE = 'Day of Year', $
YTITLE = 'Degrees Fahrenheit', $
XSTYLE=8, YSTYLE=8, XMARGIN=[8, 8], YMARGIN=[4, 4]
; Draw the top x-axis, supplying labels, etc.
; Make the characters smaller so they will fit:
AXIS, XAXIS=1, XTICKS=11, XTICKV=DAY, XTICKN=MONTH, $
XTITLE='Month', XCHARSIZE = 0.7
; 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.
AXIS, YAXIS=1, YRANGE = (!Y.CRANGE-32)*5./9., YSTYLE = 1, $
YTITLE = 'Degrees Celsius'
The code above is included in the batch file plot09 in the examples/doc
subdirectory of the IDL distribution.
The code above is included in the batch file plot09 in the examples/doc
subdirectory of the IDL distribution.
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.
See CURSOR in the IDL Reference Guide for details.
When CURSOR returns, the button field of the system variable !MOUSE is set to
the button status. Each mouse button is assigned a bit in the button field. 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. See !MOUSE in the
IDL Reference Guide for details.
The second simple procedure can be used to label plots using the cursor to position
the text:
;Text is the string to be written on the screen:
PRO LABEL, TEXT
; Ask the user to mark the position:
PRINT, 'Use the mouse to mark the text position:'
; Get the cursor position after pressing any button:
CURSOR, X, Y, /NORMAL, /DOWN
; 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.
XYOUTS, X, Y, TEXT, /NORMAL, /NOCLIP
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. Consider how you might augment the LABEL procedure to
allow you to specify the size and font of the annotation text.
Plotting Multi-
Dimensional Arrays
The following topics are covered in this 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 14, “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 11, “Direct
Graphics Plotting”, apply to CONTOUR and SURFACE as well.
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 basic
call to CONTOUR is as follows:
CONTOUR, Z
where Z is a two-dimensional array. This call labels the x- and y-axes with the
subscript along each dimension. For example, when contouring a 10 × 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 as follows:
CONTOUR, Z, X, Y
where 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.
See CONTOUR in the IDL Reference Guide for a complete list of CONTOUR’s
parameters and keywords.
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, and is one of the
two following methods.
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.
Note
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.
The Maroon Bells data is used in a number of examples in this chapter, and is
included in an IDL SAVE file called marbells.dat in the examples/data
subdirectory of the IDL distribution. To restore the save file, issue the following
commands at the IDL prompt (change the path separator characters as necessary for
your platform):
CD, !DIR+'/examples/data'
RESTORE, 'marbells.dat'
The batch file cntour01, located in the examples/doc subdirectory of the IDL
distribution, restores this data and defines several variables used in the examples in
this chapter.
This command creates an IDL variable named elev that contains the 360 x 460
integer array.
The figure below is the result of applying the CONTOUR procedure to the data,
using the default settings:
CONTOUR, elev
Note
32767 is the maximum allowable 16-bit integer.
This smooths the contours, because the call to REBIN averages 52=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 × 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 52=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.
If you prefer not to enter the code by hand, run the batch file cntour02 with the
following command at the IDL prompt:
@cntour02
See “Running the Example Code” on page 304 if IDL does not find the batch file.
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.
Note
In order to do this successfully, you must establish the size of the plot window
before scaling the image. This means that you must make a call to CONTOUR
before displaying the image, to set the window size, and another call to CONTOUR
after displaying the image, to draw the contour lines on top of the image data.
Inspect the batch file cntour03 located in the examples/doc subdirectory of the
IDL distribution to see how the figure was created. Note that 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.
If you prefer not to enter the code by hand, run the batch file cntour04 with the
following command at the IDL prompt:
@cntour04
See “Running the Example Code” on page 304 if IDL does not find the batch file.
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.
; Restore variables:
@cntour01
; Set missing data points to a large value:
elev (WHERE (elev EQ 0)) = 1E6
; REBIN down to a 72 x 92 matrix.
new = REBIN(elev, 360/5, 460/5)
; Scale image intensities.
image = BYTSCL(elev, MIN=2658, MAX=4241)
; Get size of plot window in device pixels.
PX = !X.WINDOW * !D.X_VSIZE
PY = !Y.WINDOW * !D.Y_VSIZE
; Get the size of the image.
SZ = SIZE(image)
; Display the image with its lower-left corner
; at the origin of the plot window.
TVSCL, image, PX[0], PY[0]
; Write the contours over the image, being sure to use
; the exact axis styles so that the contours fill the plot
; window. Inhibit erasing.
CONTOUR, new, X, Y, XSTYLE = 1, YSTYLE = 1, $
POSITION = [PX[0], PY[0], PX[0]+SZ[1]-1, PY[0]+SZ[2]-1], $
LEVELS = 2750 + FINDGEN(6) * 250., MAX_VALUE = 5000, $
TITLE = 'Maroon Bells Region', $
SUBTITLE = '250 meter contours', $
XTITLE = 'UTM Coordinates (KM)', /NOERASE, /DEVICE
If you prefer not to enter the code by hand, run the batch file cntour05 with the
following command at the IDL prompt:
@cntour05
See “Running the Example Code” on page 304 if IDL does not find the batch file.
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
statement:
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 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
Figure 12-6: Label Size and Levels Specified (left), Explicitly Specified Labels
(right)
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 CONTOUR in the IDL Reference Guide for an example using the
MIN_CURVE_SURF function. See also MIN_CURVE_SURF in the IDL Reference
Guide for further details.
The following short example shows the difference between a smoothed and an
unsmoothed contour plot:
;Create a simple dataset:
data = RANDOMU(seed, 7, 7)
;Plot the unsmoothed data:
CONTOUR, data
;Plot the smoothed data:
CONTOUR, MIN_CURVE_SURF(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.
; Create a simple, random dataset for contouring:
data = RANDOMU(seed, 7, 7)
; Create a basic, solid-color, filled CONTOUR plot
; with 6 evenly-spaced levels.
CONTOUR, data, NLEVELS=6, /FILL
; Overplot contour outlines:
CONTOUR, data, NLEVELS=6, /NOERASE
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 more information see CONTOUR in the IDL Reference Guide.
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.
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.
Example
The figures below illustrate the application of the SURFACE procedure to the
Maroon Bells data used in the first section of this chapter. As with CONTOUR, it is
often useful to reduce the number of individual data values, so that the surface is not
obscured by excessive detail.
The left illustration in the figure above was produced by the following statements:
; Restore variables.
@cntour01
; Resize the original data into a 72 x 92 array, setting
; all data values which are less than 2650 (the lowest
; elevation we wish to show) to 2650.
surf = REBIN(elev > 2650, 360/5, 460/5)
Alternatively, run the batch file surf01 with the following command at the IDL
prompt:
@surf01
See “Running the Example Code” on page 304 if IDL does not find the batch file.
The right illustration in the figure shows the Maroon Peaks area looking from the
back row to the front row (north to the south) of the Maroon Peaks area. This
perspective on the data is created by setting the angle of rotation around the z-axis to
210 degrees (setting AZ = 210), and increasing the azimuth from the default 30
degrees to 45 (setting AX = 45). Also, only the horizontal lines are drawn because the
/HORIZONTAL keyword is present in the following call:
SURFACE, surf, X, Y, SKIRT = 2650, /HORIZ, AZ = 210, AX = 45
Because the axes are 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 minimum and maximum values of the X and Y
ranges used when drawing the surface:
; As above, but reverse the data rather than the axes:
SURFACE, surf, X, Y, SKIRT = 2650, /HORIZONTAL, AX = 45, $
YRANGE = [MAX(Y), MIN(Y)], XRANGE=[MAX(X), MIN(X)]
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.
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.
Translation
The transformation matrix to translate a point by (Dx, Dy, Dz) is shown below.
1 0 0 Dx
0 1 0 Dy
0 0 1 Dz
0 0 0 1
Scaling
Scaling by factors of Sx, Sy, and Sz about the x-, y-, and z-axes respectively, is
represented by the matrix below.
Sx 0 0 0
0 Sy 0 0
0 0 Sz 0
0 0 0 1
Rotation
Rotation about the x-, y-, and z-axes is represented respectively by the following three
matrices:
1 0 0 0
0 cos θ x – sin θ x 0
Rx =
0 sin θ x cos θ x 0
0 0 0 1
cos θ y 0 sin θ y 0
Ry = 0 1 0 0
– sin θ y 0 cos θ y 0
0 0 0 1
cos θ z – sin θ z 0 0
Rz = sin θ z cos θ z 0 0
0 0 1 0
0 0 0 1
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.
The SCALE3 procedure, scales the unit cube by a fixed factor, 1/SQRT(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.
• 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 commands shown after the definition of the HOUSE procedure contain four
sequences of calls to T3D to establish the coordinate transformation, each followed
by a call to HOUSE. If you prefer not to enter the IDL code by hand, run the batch
file showhaus with the following command at the IDL prompt:
@showhaus
See “Running the Example Code” on page 304 if IDL does not find the batch file.
PRO HOUSE
; X coordinates of 10 vertices. First 5 are front face,
; second 5 are back face. The range is 0 to 16.
house_x = [0, 16, 16, 8, 0, 0, 16, 16, 8, 0]
; The corresponding y values range from 0 to 16.
house_y = [0, 0, 10, 16, 10, 0, 0, 10, 16, 10]
;The z values range from 30 to 54.
house_z = [54, 54, 54, 54, 54, 30, 30, 30, 30, 30]
; Define max and min xy values to scale.
The HOUSE procedure could be called from the IDL command line to produce a
number of different plots. For example:
; Set up no rotation, scale, and draw house.
T3D, /RESET & HOUSE
; Create a handy constant.
H = [0.5, 0.5, 0.5]
; Straight projection after rotating 30 degrees about x and y axes.
T3D, /RESET, TRANS = -H, ROT = [30, 30, 0] & $
T3D, TR = H & HOUSE
; No rotation, oblique projection, z factor = 0.5, angle = 45.
T3D, /RESET, TRANS = -H, ROT=[0, 0, 0], OBLIQUE=[.5, -45] & $
T3D, TR = H & HOUSE
; Rotate 6 degrees about x and y, then apply perspective.
T3D, /RESET, TR=-H, ROT=[-6, 6, 0], PERS=4 & $
T3D, TR=H & HOUSE
The figure 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.
In the above example, SCALE3 rather than SCALE3D is used to maintain the same
scaling in all rotations. If you prefer not to enter the IDL code by hand, run the batch
file animhaus with the following command at the IDL prompt:
@animhaus
See “Running the Example Code” on page 304 if IDL does not find the batch file.
Three-Dimensional Transformations
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.
Using the same variables as in the earlier sections of this chapter, the figure was
produced with the following statements:
; Restore variables.
@cntour01
; Resize the original data into a 72 x 92 array,
; setting all data values which are less than
; 2650 (the lowest elevation we wish to show) to 2650.
surf = REBIN(elev > 2650, 360/5, 460/5)
; Make the mesh.
SURFACE, surf, X, Y, SKIRT=2650, /SAVE
; Specify T3D to align with SURFACE, at ZVALUE of 1.0.
; Suppress clipping as the plot is outside the normal plot window.
CONTOUR, surf, X, Y, /T3D, /NOERASE, TITLE = 'Contour Plot', $
MAX_VAL = 5000., ZVALUE = 1.0, /NOCLIP, $
LEVELS = 2750. + FINDGEN(6) * 250
• 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:
; Create the Z variable:
Z = SHIFT(DIST(40), 20, 20)
Z = EXP(-(Z/10)^2)
; NX and NY are the X and Y dimensions of the Z array:
NX = (SIZE(Z))(1)
NY = (SIZE(Z))(2)
; Set up !P.T with default SURFACE transformation.
SCALE3
; Define the three-dimensional plot
; window: x = 0.1 to 1, Y=0.1 to 1, and z = 0 to 1.
POS=[.1, .1, 1, 1, 0, 1]
If you prefer not to enter the IDL code by hand, run the batch file cntour06 with the
following command at the IDL prompt:
@cntour06
See “Running the Example Code” on page 304 if IDL does not find the batch file.
Figure 12-12: Using SHOW3 to Overlay an Image, Surface Mesh, and Contour
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 (see “Three-Dimensional Coordinate
Conversion” on page 328) convert to device coordinates, which in this
discussion are called (U, V).
Shaded Surfaces
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. See SHADE_SURF in
the IDL Reference Guide for details.
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. 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
The REJECT keyword has no effect on the output of SHADE_SURF—it is used
only with solids.
The right half of the following 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.
; Show Gaussian with shades created by scaling
; elevation into the range of bytes.
SHADE_SURF, Z, SHADES=BYTSCL(Z, TOP = !D.TABLE_SIZE)
; Draw the mesh surface over the shaded figure.
; Suppress the axes:
SURFACE, Z, XST = 4, YST = 4, ZST = 4, /NOERASE
The next figure shows the Maroon Bells data as a light-source shaded surface (this
data is also shown in the right half of Figure 12-8). It was produced by the following
statements:
; Restore variables.
@cntour01
SHADE_SURF, elev, 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
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 indicating 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,
as in the “Cloud Example” data, 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.
Cloud Example
This next figure, 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.
; Restore the data:
RESTORE, FILEPATH('clouds3d.dat', SUBDIR=['examples','data'])
; Create the contour surface polygons (v and p)
; at density 0.1, from clouds. Show the low side:
SHADE_VOLUME, clouds, 0.1, v, p, /LOW
; Obtain the dimensions of the volume.
; Variables S[1], S[2], and S[3] now contain
If you prefer not to enter the IDL code by hand, run the batch file clouds with the
following command at the IDL prompt:
@clouds
See “Running the Example Code” on page 304 if IDL does not find the batch file.
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 displays 20 views of the volume, each separated by 18 degrees.
; Define number of views:
nframes = 20
FOR i = 0, nframes - 1 DO BEGIN & $
; Translate the center of the (0, 1) unit cube
; to (0,0) and rotate about the x-axis:
T3D, TR=[-.5, -.5, -.5], ROT=[0, 360./NFRAMES, 0] & $
; Translate the center back to (0.5, 0.5, 0.5):
T3D, TR = [.5, .5, .5] & $
; Show the surface:
TV, POLYSHADE(v, p, /T3D) & $
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.
XVOLUME
XVOLUME, implemented using IDL Object Graphics, is a utility for viewing and
interactively manipulating volumes and isosurfaces. The utility provides a graphical
interface for manipulating the volume orientation, adjusting the color table and
opacity, viewing image planes and contours, and adjusting the color, opacity, and
threshold value of an isosurface. See XVOLUME in the IDL Reference Guide for
more information.
References
Foley, J.D., and A. Van Dam (1982), Fundamentals of Interactive Computer
Graphics, Addison-Wesley Publishing Co.
Map Projections
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 16 possible projections.
This procedure also sets up the clipping parameters of the 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 in the IDL
Reference Guide for more information.
MAP_GRID
This procedure draws the graticule of parallels and meridians (grid lines) according
to the specifications established by MAP_SET. See MAP_GRID in the IDL
Reference Guide for more information.
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. Continents may also be filled with solid colors.
See MAP_CONTINENTS in the IDL Reference Guide for more information.
MAP_IMAGE and MAP_PATCH
These functions return an image warped to fit the current map projection. See
MAP_IMAGE and MAP_PATCH in the IDL Reference Guide for more information.
Example Graphics
The examples in this chapter are all written to take advantage of IDL Direct Graphics.
MAP_SET Keywords
MAP_SET accepts many keywords that customize the projection attributes of the
map. A few of the important ones are described below. See 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.
ISOTROPIC
Set this keyword to produce a map that has the same scale in the X and Y directions.
LIMIT
Set this keyword to a four- or eight-element vector. The four-element vector, [Latmin,
Lonmin, Latmax, Lonmax], specifies the boundaries of a simple 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. For more complex regions or
projections, the eight-element vector, [Lat0, Lon0, Lat1, Lon1, Lat2, Lon2, Lat3, Lon3]
specifies four points located, respectively, on the left, top, right and bottom edges of
the map.
SCALE
Set this keyword to construct an isotropic map with the given scale, set to the ratio of
1:scale. If SCALE is not specified, the map is fit to the window. The typical scale for
global maps is in the ratio of between 1:100 million and 1:200 million. For
continents, the typical scale is in the ratio of approximately 1:50 million. For
example, SCALE=100E6 sets the scale at the center of the map to 1:100 million,
which is in the same ratio as 1 inch to 1578 miles (1 cm to 1000 km).
Warning
For proper rendering, splitting, and clipping, polygons must be traversed in counter-
clockwise order when observed from outside the sphere. If this requirement is not
met, the exterior, instead of the interior, of the polygons may be filled. Also, vectors
connecting the points spanning the singular line for cylindrical projections will be
drawn in the wrong direction if polygons are not traversed in the correct order.
Splitting
The splitting stage is used for cylindrical and pseudo-cylindrical projections. The
singular line, one half of a great circle line, is located opposite the center of the
projection; points on this line appear on both edges of the map. The singular line is
the intersection of the surface of the sphere with a plane passing through the center of
projection, one of the poles of projections, and the center of the sphere.
3D Clipping
Map graphics are clipped to one side of an arbitrary clipping plane in one or more
clipping stages. For example, to draw a hemisphere centered on a given point, the
clipping plane passes through the center of the sphere and has a normal vector that
coincides with the given point.
Projection
In the projection stage, a point expressed in latitude and longitude is transformed to a
point on the mapping plane.
Rectangular Clipping
After the map graphics have been projected onto the mapping plane, a conventional
rectangular clipping stage ensures that the graphics are properly bounded and closed
in the rectangular display area.
Note
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:
orthographic, stereographic, gnomonic, azimuthal equidistant, Aitoff, Lambert’s
azimuthal equal area, Hammer-Aitoff, and satellite.
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.
The following statements are used to produce an orthographic projection centered
over Eastern Spain at a scale of 70 million to 1:
MAP_SET, /ORTHOGRAPHIC, 40, 0, SCALE=70e6, /CONTINENTS, $
/GRID, LONDEL=15, LATDEL=15, $
TITLE = 'Oblique Orthographic'
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.
The following statement uses the stereographic projection to draw the hemisphere
centered on the equator at longitude –105 degrees and produces an equatorial
stereographic map:
MAP_SET, /STEREO, 0, -105, /ISOTROPIC, $
/GRID, LATDEL = 20, LONDEL = 20, /HORIZON, /CONTINENT, $
TITLE = 'Equatorial Stereographic'
Since the LATDEL and LONDEL keywords 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.
Gnomonic Projection
The gnomonic projection (also called Central or Gnomic) 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. The default clipping region for the gnomonic
projection is a circle with a radius of 60 degrees at the center of projection.
MAP_SET, /GNOMIC, 40, -105, LIMIT = [20, -130, 70, -70], $
/ISOTROPIC, /GRID, /CONTINENT, $
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 20 degrees and 70
degrees of latitude and –130 degrees and –70 degrees of longitude.
The output of these statements is shown in the following figure:
Aitoff Projection
The Aitoff projection modifies the equatorial aspect of one hemisphere of the
azimuthal equidistant projection, described above. Lines parallel to the equator are
stretched horizontally and meridian values are doubled, thereby displaying the world
as an ellipse with axes in a 2:1 ratio. Both the equator and the central meridian are
represented at true scale; however, distances measured between the point of tangency
and any other point on the map are no longer true to scale.
An Aitoff projection centered on the international dateline can be produced by the
command:
MAP_SET, 0, 180, /Aitoff, /GRID, /CONTINENTS, /ISOTROPIC, $
TITLE= 'Aitoff Projection'
Note
This map shows the Northern Hemisphere rotated counterclockwise 105 degrees,
filling the continents with a solid color
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 the same way Aitoff’s projection is derived
from the equatorial aspect of the azimuthal equidistant projection). 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, /HAMMER, /GRID, /CONTINENTS, /ISOTROPIC, $
/HORIZON, TITLE= 'Hammer-Aitoff Projection'
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
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 map in 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 that follows.
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.
The cylindrical projections in IDL include: Mercator, Transverse Mercator,
cylindrical equidistant, Miller, Lambert’s conformal conic, and Alber’s equal-area
conic.
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 statement produces a simple Mercator projection:
MAP_SET, /MERCATOR, 0, 0, /ISOTROPIC, $
/GRID, /CONTINENTS, $
TITLE = 'Simple Mercator'
The result of this statement is shown in the upper-left corner of the following figure.
The Clarke 1866 ellipsoid is used for the default, but its parameters can be altered
with the ELLIPSOID keyword.
When the eccentricity of the Earth is not important, global scale Transverse Mercator
projections can be easily created using the Mercator projection with the
CENTRAL_AZIMUTH keyword set to 90 degrees, and setting Rot to rotate the map
90 degrees. For example, to create the Transverse Mercator map showing North and
South America, with a central meridian of –90 degrees West and centered on the
Equator, shown in the upper-right corner of the figure in the “Mercator Projection”
section. It is produced by the following statement:
MAP_SET, /MERCATOR, 0, -75, 90, CENTRAL_AZIMUTH=90, $
/ISOTROPIC, LIMIT= [32,-130, 70,-86, -5,-34, -58, -67], $
/GRID, LATDEL=15, LONDEL=15, /CONTINENTS, $
TITLE = 'Transverse Mercator'
–180 ≤ u ≤ 180
and
–90 ≤ v ≤ 90
If EQ is the equator, meridians and parallels will be equally spaced parallel lines.
The following code is used to produce a simple cylindrical equidistant projection and
an oblique cylindrical equidistant projection as shown in the lower-left and lower-
right sections of the figure under the “Mercator Projection” heading:
Conic Projection
The Lambert’s conformal conic with two standard parallels 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 STANDARD_PARALLELS keyword specifies the latitudes of one
or two standard parallels.
The following statement produces the map shown in the accompanying figure, which
features North America with standard parallels at 20 degrees and 60 degrees:
MAP_SET, /CONIC, 40, -80, STANDARD_PARALLELS=[20,60], $
/ISOTROPIC, LIMIT=[0, -260, 90, 100], $
/GRID, LATDEL=15, LONDEL=20, /CONTINENT, $
TITLE= 'Lambert’s Conic'
Figure 13-10: Lambert’s Conformal Conic with Standard Parallels at 20° and 60°
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.
Robinson Cylindrical
This pseudocylindrical projection was designed by Arthur Robinson in 1963 for
Rand McNally. It is suitable for World maps and is a compromise to best fulfill a
number of conflicting requirements, including an uninterrupted format, minimal
shearing, minimal apparent area-scale distortion for major continents, and simplicity.
It was designed to make the world look right. Since its introduction, it has been
adopted by the National Geographic Society for many of their world maps.
Each individual parallel is equally divided by the meridians. The poles are
represented by lines rather than points to avoid compressing the northern land
masses.
Note
The central meridian should always be 0 degrees longitude to retain the correct
balance of shapes, sizes, and relative positions.
The next statement produces the Robinson projection shown in the lower-left corner
of the figure which follows.
MAP_SET, /ROBINSON, 0, 0, /ISOTROPIC, /GRID, $
/HORIZON, E_CONTINENTS={FILL:1}, TITLE='Robinson'
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 statements produces the sinusoidal map of the whole globe centered at
longitude 0 degrees and latitude 0 degrees:
MAP_SET, /SINUSOIDAL, /ISOTROPIC, $
/CONTINENTS, TITLE='Sinusoidal'
MAP_GRID, LONDEL=20, /HORIZON
The result of these statements is shown in the upper-left corner of the following
figure.
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 statement produces a Mollweide projection in oblique form, as illustrated
in the upper-right corner of the previous figure:
MAP_SET, /MOLLWEIDE, 45, 0, /ISOTROPIC, $
/GRID, LATDEL=20, LONDEL=20, $
/HORIZON, E_CONTINENTS={FILL:1}, $
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.
Limitations
Filling contours or polygons over maps that cover more than a hemisphere will
produce incorrect results. This is because of the ambiguity between polygons that
enclose an area, and those that enclose the entire surface of the sphere outside the
area; and because of the ambiguity of determining the clockwise-ness of polygons on
a sphere that cover more than a hemisphere.
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.
Image Display
Routines
The following topics are found in this 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.
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 Chapter 11, “Direct Graphics
Plotting” and Chapter 14, “Image Display Routines”. For example, to overlay an
image and its contour plot, the output of the CONTOUR procedure is combined with
that of TV. The CURSOR routine, described in “Using the CURSOR Procedure” on
page 300, 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]]
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 × 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 × 128 images on a 512 × 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 × 512, 1280 × 1024, and 900 × 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
; Set all display memory to 100:
TV, REPLICATE(100B, 512, 512)
; Define a 50 column by 100 row array:
ABC = BYTARR(50, 100)
; 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, 300, 400
; Display image divided by 2 at position number 12:
TV, ABC/2, 12
; Output image to memory channel 2, lower-left
; corner at (256, 256).
TV, A, 256, 256, 2
; Assume file one contains a sequence of 64 × 64 byte arrays:
AA = ASSOC(1, BYTARR(64, 64))
; Display 64 images from file, from left to right and
; top to bottom, filling a 512 × 512 area:
FOR I = 0, 63 DO TV, AA[I], I
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.
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. Thus, 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
;Slow method.
TVSCL, A > 2.6 < 9.4
;Faster method.
TV, BYTSCL(A, MIN=2.6, MAX=9.4, TOP = !D.TABLE_SIZE)
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.
;Display square root of image:
TVSCL, SQRT(A)
;Display unsharp masked image:
TVSCL, A - SMOOTH(A, 3)
;Display scaled sum at position number 12:
TVSCL, A + B, 12
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
The following statement inverts the 100 × 100 area of the display starting at
(200, 300):
;Reverse area:
TV, NOT TVRD(200, 300, 100, 100)
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 14-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 2n –1. Each displayable color is an
RGB coordinate triple of n-bit numbers yielding a palette containing 23n total colors.
Therefore, for 8-bit colors, each color coordinate can range from 0 to 255, and the
total palette contains 224 or 16,777,216 colors.
A display with an m-bit pixel can represent 2m 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
28 = 256 colors selected from the much larger palette.
If there are not enough bits in a pixel to represent all colors, m < 23n, 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 28 = 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 2m long array of RGB triples:
Figure 14-1: RGB Color Cube. (Note: grays are on the main diagonal.)
Example
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.
;Specify the red component of each color:
RED = [0, 1, 1, 0, 0, 1]
;Specify the green component of each color:
GREEN = [0, 1, 0, 1, 0, 1]
;Specify the blue component of each color:
BLUE = [0, 1, 0, 0, 1, 0]
;Load the first six elements of the color table:
TVLCT, 255 * RED, 255 * GREEN, 255 * BLUE
;Draw the axes in white, color index 1:
PLOT, COLOR = 1, /NODATA,...
;Draw in red:
OPLOT, COLOR = 2, ...
;Draw in green:
OPLOT, COLOR = 3, ...
;Draw in blue.
OPLOT, COLOR = 4, ...
;Draw in yellow:
OPLOT, COLOR = 5, ... ...
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:
; Straight line, A[I] = I:
A = INDGEN(256)
; Display image with a linear red scale, disable green and blue:
TVLCT, A, A * 0, A * 0
; Display with linear black and white scale:
TVLCT, A, A, A
; Warm body temperature scale. Red is linear,
; green starts at 128, and blue starts at 192:
TVLCT, A, 2 * (A - 128) > 64, 4 * (A - 192) > 0
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.
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
Example
; Expand the color tables so that pixels in
; the range of 100 to 150 fill the entire color range:
STRETCH, 100, 150
Note
The window-oriented procedures will not work without a window system.
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.
TrueColor Displays
IDL supports the use of some TrueColor displays with 24 bits per pixel. TrueColor
displays have multiple channels. That is, they store information about each primary
color component (red, green, and blue) of a pixel separately. A TrueColor display
with n bits per memory channel can display 23n simultaneous colors, as opposed to
the 2n 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 TrueColor devices
supported by IDL.
Configuration
The TrueColor display is configured as a single display with three channels:
Channel
Output
Number
0 All colors
1 Red
2 Green
3 Blue
Lookup Tables
Warning
Not all TrueColor 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
TrueColor 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 224–1. The system variable field
!D.N_COLORS, which contains the number of colors, is set to 224 on a TrueColor
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)
TrueColor Images
Images can be transferred to and from the display in either 8-bit or 24-bit mode. The
CHANNEL parameter 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:
;Load red in channel 1:
TV, R, 0, 0, 1
;Load green in channel 2:
TV, G, 0, 0, 2
;Load blue in channel 3:
TV, B, 0, 0, 3
The position parameters (0, 0 above) can be altered 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
TrueColor image is dimensioned as follows:
For example, to write a TrueColor, 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 parameter or TRUE keyword parameter. 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 TrueColor 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.
References
Foley, J.D., and A. Van Dam (1982), Fundamentals of Interactive Computer
Graphics, Addison-Wesley Publishing Company.
Signal Processing
Overview
A signal, by definition, contains information. Any signal obtained from a physical
process also contains noise. It is often difficult or impossible to make sense of the
information contained in a digital signal by looking at it in its raw form—that is, as a
sequence of real values at discrete points in time. Signal analysis transforms offer
natural, meaningful, alternate representations of the information contained in a
signal.
This chapter describes IDL’s digital signal processing tools. Most of the procedures
and functions mentioned here work in two or more dimensions. For simplicity, only
one dimensional signals are used in the examples.
Digital Signals
A one-dimensional digital signal is a sequence of data, represented as a vector in an
array-oriented language like IDL. The term digital actually describes two different
properties:
1. The signal is defined only at discrete points in time as a result of sampling, or
because the instrument which measured the signal is inherently discrete-time
in nature. Usually, the time interval between measurements is constant.
2. The signal can take on only discrete values.
In this discussion, we assume that the signal is sampled at a time interval. The
concepts and techniques presented here apply equally well to any type of signal—the
independent variable may represent time, space, or any abstract quantity.
The following IDL commands create a simulated digital signal u(k), sampled at an
interval delt. This simulated signal will be used in examples throughout this
chapter. The simulated signal contains 1024 time samples, with a sampling interval
of 0.02 seconds. The signal contains a DC component and components at 2.8, 6.5,
and 11.0 cycles per second.
Enter the following commands at the IDL prompt to create the simulated signal:
N = 1024
delt = 0.02
u = -0.3 $
+ 1.0 * SIN(2 * !PI * 2.8 * delt * FINDGEN(N)) $
+ 1.0 * SIN(2 * !PI * 6.25 * delt * FINDGEN(N)) $
+ 1.0 * SIN(2 * !PI * 11.0 * delt * FINDGEN(N))
Alternately, you can run the following batch file to create the signal:
@sigprc01
See “Running the Example Code” on page 404 if IDL does not find the batch file.
Because the signal is digital, the conventional way to display it is with a histogram (or
step) plot. To create a histogram plot, set the PSYM keyword to the PLOT routine
equal to 10. A section of the example signal u(k) is plotted in the figure below.
Note
When the number of sampled data points is large, the steps in the histogram plot are
too small to see. In such cases you should not plot in histogram mode.
Enter the following commands at the IDL prompt to create the plot:
; Compute time data sequence u.
@sigprc01
; Vector of discrete times:
t = delt * FINDGEN(N)
; Beginning of plot time range:
t1 = 1.0
; End of plot time range:
t2 = 2.0
PLOT, t+delt/2, u, PSYM=10, XRANGE=[t1,t2], $
XTITLE='time in seconds', YTITLE='amplitude', $
TITLE='Portion of Sampled Time Signal u(k)'
Alternately, you can run the following batch file to create the plot:
@sigprc02
See “Running the Example Code” on page 404 if IDL does not find the batch file.
N–1
∑ u(k)exp [ – j2πmk ⁄ N ]
1
v(m) = ----
N
k=0
N–1
u(k) = ∑ v(m)exp [ j2πmk ⁄ N ]
m=0
IDL implements the Fast Fourier Transform in the FFT function. You can find details
on using IDL’s FFT function in the following sections and in FFT in the IDL
Reference Guide.
m
f ( m ) = -------
Nδ
The frequencies for which the FFT of a sampled signal are defined are sometimes
called frequency bins, which refers to the histogram-like nature of a discrete
spectrum. The width of each frequency bin is 1/(N*δ).
Due to the complex exponential in the definition of the DFT, the spectrum has a
cyclic dependence on the frequency index m. That is:
v ( m + pN ) = v ( m )
Enter the following commands at the IDL prompt to create the plot:
;Compute time sequence data:
@sigprc01
; Compute spectrum v:
V = FFT(U)
M = (INDGEN(N)-(N/2-1))
; Frequencies corresponding to m in cycles/second:
F = M / (N*delt)
; Set up for two plots in window:
!P.MULTI = [0, 1, 2]
PLOT, F, FLOAT(SHIFT(V,N/2-1)), $
YTITLE='real part of spectrum', $
XTITLE='Frequency in cycles / second', $
XRANGE=[-1,1]/(2*delt), XSTYLE=1, $
TITLE='Spectrum of u(k)'
PLOT, F, IMAGINARY(SHIFT(V,N/2-1)), $
YTITLE='imaginary part of spectrum', $
XTITLE='Frequency in cycles / second', $
XRANGE=[-1,1]/(2*delt), XSTYLE=1
!P.MULTI = 0
Alternately, you can run the following batch file to create the plot:
@sigprc03
See “Running the Example Code” on page 404 if IDL does not find the batch file.
IDL’s FFT function always returns a single- or double-precision complex array with
the same dimensions as the input argument. In the case of a forward FFT performed
on a one-dimensional vector of N real values, the result is an N-element vector of
complex quantities, which takes 2N real values to represent. It would seem that there
is twice as much information in the spectral data as there is in the time sequence data.
This is not the case. For a real valued time sequence, half of the information in the
frequency sequence is redundant. Specifically:
; 1 redundant value:
IMAGINARY(v(0)) = 0.0
; 1 redundant value:
IMAGINARY(v(N/2)) = 0.0
and
; for m=1 to N/2-1, N-2 redundant values:
v(N-m) = CONJ(v(m))
frequency. This vector of positive frequencies is generated in IDL with the following
command:
; f = [0.0, 1.0/(N*delt), ... , 1.0/(2.0*delt)]
F = FINDGEN(N/2+1)/(N*delt)
Enter the following commands at the IDL prompt to create the plot:
Alternately, you can run the following batch file to create the plot:
@sigprc04
See “Running the Example Code” on page 404 if IDL does not find the batch file.
Using a logarithmic scale for the frequency axis has the advantage of spreading out
the lower frequencies, while higher frequencies are crowded together. Note that the
spectrum at zero frequency (DC) is lost completely on a semi-logarithmic plot.
The previous figure shows the strong frequency components at 2.8, 6.25, and 11.0
cycles/second as peaks in the magnitude plot, and as discontinuities in the phase plot.
The magnitude peak at 6.25 cycles/second is a narrow spike, as would be expected
from the pure sine wave component at that frequency in the time data sequence. The
peaks at 2.8 and 11.0 cycles/second are more spread out, due to an effect known as
smearing or leakage. This effect is a direct result of the definition of the DFT and is
not due to any inaccuracy in the FFT. Smearing is reduced by increasing the length of
the time sequence, or by choosing a sample size which includes an integral number of
cycles of the frequency component of interest. There are an integral number of cycles
of the 6.25 cycles/second component in the time sequence used for this example,
which is why the peak at that frequency is sharper.
The apparent discontinuity in the phase plot at around 7.45 cycles/second is an
anomaly known as phase wrapping. It is a result of resolving the phase from the real
and imaginary parts of the spectrum with the arctangent function (ATAN), which
returns principal values between –180 and +180 degrees.
Power Spectrum
Finally, for many applications, the phase information is not useful. For these, it is
often customary to plot the power spectrum, which is the square of the magnitude of
the complex spectrum. The resulting plot is shown in the figure below.
Enter the following commands at the IDL prompt to create the plot:
; Compute time sequence data.
@sigprc01
; Compute spectrum v:
V = FFT(U)
; F = [0.0, 1.0/(N*delt), ... , 1.0/(2.0*delt)]:
F = FINDGEN(N/2+1) / (N*delt)
; Create log-log plot of power spectrum:
PLOT, F, ABS(V(0:N/2))^2, YTITLE='Power Spectrum of u(k)', $
/YLOG, XTITLE='Frequency in cycles / second', /XLOG, $
XRANGE=[1.0,1.0/(2.0*delt)], XSTYLE=1
Alternately, you can run the following batch file to create the plot:
@sigprc05
See “Running the Example Code” on page 404 if IDL does not find the batch file.
Using Windows
The smearing or leakage effect mentioned previously is a direct consequence of the
definition of the Discrete Fourier Transform and of the fact that a finite time sample
of a signal often does not include an integral number of some of the frequency
components in the signal. The effect of this truncation can be reduced by increasing
the length of the time sequence or by employing a windowing algorithm. IDL’s
HANNING function computes two windows which are widely used in signal
processing: the Hanning window and the Hamming window.
Hanning Window
The Hanning window is defined as:
The resulting vector is multiplied element-by-element with the sampled signal vector
before applying the FFT. For example, the following IDL command computes the
Hanning window and then applies the FFT function:
v_n = FFT(HANNING(N)*U)
The power spectrum of the Hanning windowed signal shows the mitigation of the
truncation effect (see the figure below).
Figure 15-5: Power spectrum of the sample signal after applying a Hanning
window.
Enter the following commands at the IDL prompt to create the plot:
; Compute time sequence data:
@sigprc01
; F = [0.0, 1.0/(N*delt), ... , 1.0/(2.0*delt)]:
F = FINDGEN(N/2+1) / (N*delt)
v_n = FFT(HANNING(N)*U)
;Create a log-log plot of power spectrum:
PLOT, F, ABS(v_n(0:N/2))^2, YTITLE='Power Spectrum', $
/YLOG, YRANGE=[1.0e-8,1.0], YSTYLE=1, YMARGIN=[4,4], $
XTITLE='Frequency in cycles / second', /XLOG, $
XRANGE=[1.0,1.0/(2.0*delt)], XSTYLE=1, $
TITLE=’Power Spectrum of u(k) with Hanning Window ' $
+'(solid)!Cand without Window (dashed)'
; Overplot without window:
OPLOT, F, ABS((FFT(U))(0:N/2))^2, LINESTYLE=2
Alternately, you can run the following batch file to create the plot:
@sigprc06
See “Running the Example Code” on page 404 if IDL does not find the batch file.
Hamming Window
The Hamming window is defined as:
The resulting vector is multiplied element-by-element with the sampled signal vector
before applying the FFT. For example, the following IDL command computes the
Hamming window and then applies the FFT function:
v_m = FFT(HANNING(N, ALPHA=0.56)*U)
The power spectrum of the Hamming windowed signal shows the mitigation of the
truncation effect (see the figure below).
Figure 15-6: Power spectrum of the sample signal after applying a Hamming
window.
Enter the following commands at the IDL prompt to create the plot:
; Compute time sequence data.
@sigprc01
; F = [0.0, 1.0/(N*delt), ... , 1.0/(2.0*delt)]:
F = FINDGEN(N/2+1) / (N*delt)
v_m = FFT(HANNING(N, ALPHA=0.54)*U)
; Create log-log plot of power spectrum:
PLOT, F, ABS(v_m(0:N/2))^2, YTITLE='Power Spectrum', $
/YLOG, YRANGE=[1.0e-8,1.0], YSTYLE=1, YMARGIN=[4,4], $
XTITLE='Frequency in cycles / second', $
Alternately, you can run the following batch file to create the plot:
@sigprc07
See “Running the Example Code” on page 404 if IDL does not find the batch file.
Aliasing
Aliasing is a well known phenomenon in sampled data analysis. It occurs when the
signal being sampled has components at frequencies higher than the Nyquist
frequency, which is equal to half the sampling frequency. Aliasing is a consequence
of the fact that after sampling, every periodic signal at a frequency greater than the
Nyquist frequency looks exactly like some other periodic signal at a frequency less
than the Nyquist frequency.
For example, suppose we add a 30 cycle per second periodic component to our
sampled data sequence u(t). The power spectrum of the augmented signal is shown in
the figure below.
Figure 15-7: Power spectrum of the sample signal after adding a 30 cycles per
second component.
Because the frequency of the new component is above the Nyquist frequency of 25
cycles per second (25 = 1/(2*delt)), the power spectrum shows the contribution of the
new component as an alias at 20 cycles per second.
To prevent aliasing, frequency components of a signal above the Nyquist frequency
must be removed before sampling.
You can run the following batch file to create the plot:
@sigprc08
See “Running the Example Code” on page 404 if IDL does not find the batch file.
r̂ ( t ) = r ( t ) – jH ( r ( t ) )
The following example plots the complex analytic signal of a periodic time signal
with a slowly varying amplitude.
Enter the following commands at the IDL prompt to create the plot:
; Number of time samples in data set:
N = 1024
; Sampling interval in seconds:
delt = 0.02
; Vector of discrete times:
T = delt * FINDGEN(N)
f1 = 5.0 / ((n-1)*delt)
f2 = 0.5 / ((n-1)*delt)
R = SIN(2*!PI*f1*T) * SIN(2*!PI*f2*T)
PLOT_3DBOX, T, R, -FLOAT(HILBERT(R)), $
AX=40, AZ=15, XTICKS=5, XCHARSIZE=2, $
XTITLE = 'time in seconds', YTICKS=2, YCHARSIZE=2, $
YTITLE = 'real', YMARGIN=[4,8], ZTICKS=2, ZCHARSIZE=2, $
ZTITLE = 'imaginary'
XYOUTS, 0.5, 0.95, /NORMAL, ALIGNMENT=0.5, SIZE=1.5, $
'Ana;lytic Signal for r(t) Using Hilbert Transform'
Alternately, you can run the following batch file to create the plot:
@sigprc09
See “Running the Example Code” on page 404 if IDL does not find the batch file.
Convolution
Discrete convolution in digital signal processing is used (among other things) to
smooth sampled signals using a weighted moving average. It also has many
applications outside of signal processing.
IDL has two functions for doing discrete convolution: BLK_CON and CONVOL.
BLK_CON takes advantage of the fact that the convolution of two signals is the
Inverse Fourier transform of the product of the Fourier transforms of the two signals.
BLK_CON is faster than CONVOL, but not as flexible. Among the many
applications for discrete convolution is the implementation of digital filters. See the
example in the “Finite Impulse Response (FIR) Filters” on page 428.
Digital Filtering
Digital filters can be implemented on a computer to remove unwanted frequency
components (noise) from a sampled signal. Two broad classes of filters are Finite
Impulse Response (FIR) or Moving Average (MA) filters, and Infinite Impulse
Response (IIR) or AutoRegressive Moving Average (ARMA) filters. Both of these
classes of filters are described below.
Enter the following commands at the IDL prompt to create the plot:
; Sampling period in seconds:
delt = 0.02
; Frequencies above f_low will be passed:
f_low = 15.
; Frequencies below f_high will be passed:
f_high = 7.
; Ripple amplitude will be less than -50 dB:
a_ripple = 50.
; The order of the filter:
nterms = 40
; Compute the impulse response = the filter coefficients:
bs_ir_k = DIGITAL_FILTER(f_low*2*delt, f_high*2*delt, $
a_ripple, nterms)
; The frequency response of the filter is the FFT of its
; impulse response:
nfilt = N_ELEMENTS(bs_ir_k)
; where nfilt = number of points in impulse response.
; Scale frequency response by number of points:
bs_fr_k = FFT(bs_ir_k) * nfilt
; Create a log plot of magnitude in decibels:
f_filt = FINDGEN(nfilt/2+1) / (nfilt*delt)
; Magnitude of bandstop filter transfer function:
mag = ABS(bs_fr_k(0:nfilt/2))
PLOT, f_filt, 20*ALOG10(mag), YTITLE='Magnitude in dB', $
XTITLE='Frequency in cycles / second', /XLOG, $
XRANGE=[1.0,1.0/(2.0*delt)], XSTYLE=1, $
TITLE='Frequency Response for Bandstop!CFIR Filter (Kaiser)'
Alternately, you can run the following batch file to create the plot:
@sigprc10
See “Running the Example Code” on page 404 if IDL does not find the batch file.
Other FIR filters can be designed based on the Hanning and Hamming windows (see
“Using Windows” on page 416), or any other user-defined window function. The
design procedure is simple:
1. Compute the impulse response of an ideal filter using the inverse FFT
2. Apply a window to the impulse response. The modified impulse response
defines the FIR filter.
The figure below shows the plot using the same sampling period and frequency
cutoffs as above, and the corresponding ideal filter is constructed in the frequency
domain using the Hanning window.
Enter the following commands at the IDL prompt to create the plot:
; Sampling period in seconds:
delt = 0.02
; Frequencies above f_low will be passed:
f_low = 15.
; Frequencies below f_high will be passed:
f_high = 7.
; The length of the filter:
nfilt = 81
f_filt = FINDGEN(nfilt/2+1) / (nfilt*delt)
; Pass frequencies greater than f_low and less than f_high:
ideal_fr = (f_filt GT f_low) OR (f_filt LT F_high)
; Convert from byte to floating point:
ideal_fr = FLOAT(ideal_fr)
; Replicate to obtain values for negative frequencies:
ideal_fr = [ideal_fr, REVERSE(ideal_fr[1:*])]
; Now use an inverse FFT to get the impulse response
; of the ideal filter:
ideal_ir = FLOAT(FFT(ideal_fr, /INVERSE))
; Ideal_fr is an even function, so the result is real.
; Scale by the # of points:
ideal_ir = ideal_ir / nfilt
; Shift it before applying the window:
ideal_ir = SHIFT(ideal_ir, nfilt/2)
Alternately, you can run the following batch file to create the plot:
@sigprc11
See “Running the Example Code” on page 404 if IDL does not find the batch file.
The frequency response of the filtered signal shows that the frequency component at
11.0 cycles / second has been filtered out, while the frequency components at 2.8 and
6.25 cycles / second, as well as the DC component, have been passed by the filter.
Enter the following commands at the IDL prompt to create the plot:
; Compute time data sequence u:
@sigprc01
; Compute the Kaiser filter coefficients
; with the sampling period in seconds:
delt = 0.02
Alternately, you can run the following batch file to create the plot:
@sigprc12
See “Running the Example Code” on page 404 if IDL does not find the batch file.
f0
----- -+s
2
y(s) 2π
---------- = --------------------------------------------
u(s) f0
1 + 2s ----- - +s
2
2π
where s is the Laplace transform variable. Then the continuous transfer function is
converted to the equivalent discrete transfer function using one of several techniques.
One of these is the bilinear (Tustin) transform, where
(2/δ)*(z-1)/(z+1)
is substituted for the Laplace transform variable s. In this expression, z is the unit
delay operator.
For the notch filter above, the bilinear transformation yields the following discrete
transfer function:
2 2
1-------------
+c
- – 2cz + -------------- z
1+c 2
y(z) 2 2
---------- = -------------------------------------------------------------
u(z) 2
( c – 2cz + z )
2
delt = 0.02
; Notch frequency in cycles per second:
f0 = 6.5
c = (1.0-!PI*F0*delt) / (1.0+!PI*F0*delt)
b = [(1+c^2)/2, -2*c, (1+c^2)/2]
a = [ c^2, -2*c, 1]
Alternately, you can run the following batch file to compute the coefficients:
@sigprc13
See “Running the Example Code” on page 404 if IDL does not find the batch file.
IIR Filter Implementation
Since an Infinite Impulse Response filter contains feedback loops, its output at every
time step depends on previous outputs, and the filter must be implemented
recursively with difference equations. The discrete transfer function
nb
b 0 + b 1 z + … + b nb z
- u ( z )
y ( z ) = ------------------------------------------------------
a 0 + a 1 z + … + a na z nb
( b 0 u ( k – nb ) + b 1 u ( k – nb + 1 ) + … + b nb u ( k ) – a 0 y ( k – na ) – a 1 y ( k – na + 1 ) – … – a na – 1 y ( k – 1 ) )
y ( k ) = ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
a na
An IIR filter is stable if the absolute values of the roots of the denominator of the
discrete transfer function a(z) are all less than one. The impulse response of a stable
IIR filter approaches zero as the time index k approaches infinity. The frequency
response function of a stable IIR filter is the Discrete Fourier Transform of the filter’s
impulse response.
The figure below plots the impulse and frequency response functions of the notch
filter defined above using recursive difference equations.
Enter the following commands at the IDL prompt to create the plot:
; Load the coefficients for the notch filter:
@sigprc13
; Degree of denominator polynomial:
na = N_ELEMENTS(A)-1
; Degree of numerator polynomial:
nb = N_ELEMENTS(B)-1
N = 1024L
; Create an impulse U:
U = FLTARR(N)
U[0] = FLOAT(N)
Y = FLTARR(N)
Y[0] = B[2]*U[0] / A[na]
; Recursively compute the filtered signal:
FOR K = 1, N-1 DO $
Y(K) = ( TOTAL( B[nb-K>0:nb]*U[K-nb>0:K]) $
- TOTAL( A[na-K>0:na-1]*Y[K-na>0:K-1] ) ) / A[na]
; Compute spectrum V:
V = FFT(Y)
Note
Because the impulse response approaches zero, IDL may warn of floating-point
underflow errors. This is an expected consequence of the digital implementation of
an Infinite Impulse Response filter.
Alternately, you can run the following batch file to create the plot:
@sigprc14
See “Running the Example Code” on page 404 if IDL does not find the batch file.
The same code could be used to filter any input sequence u(k).
Routine Description
A_CORRELATE Computes autocorrelation.
BLK_CON Convolves input signal with impulse-response sequence.
C_CORRELATE Computes cross correlation.
CONVOL Convolves two vectors or arrays.
CORRELATE Computes the linear Pearson correlation.
DIGITAL_FILTER Calculates coefficients of a non-recursive, digital filter.
FFT Returns the Fast Fourier Transform of an array.
HANNING Creates Hanning and Hamming windows.
HILBERT Constructs a Hilbert transform.
INTERPOL Performs linear interpolation on vectors.
M_CORRELATE Computes multiple correlation coefficient.
MEDIAN Returns the median value of an array or applies a median
filter.
P_CORRELATE Computes partial correlation coefficient.
R_CORRELATE Computes rank correlation.
SAVGOL Returns coefficients of Savitzky-Golay smoothing filter.
SMOOTH Smooths with a boxcar average.
TS_COEF Computes the coefficients for autoregressive time-series.
TS_DIFF Computes the forward differences of a time-series.
TS_FCAST Computes future or past values of a stationary time-series.
TS_SMOOTH Computes moving averages of a time-series.
WTN Returns wavelet transform of the input array.
References
Bracewell, Ronald N., The Fourier Transform and Its Applications, New York:
McGraw-Hill, 1978. ISBN 0-07-007013-X
Chen, Chi-Tsong, One-Dimensional Digital Signal Processing, New York: Marcel
Dekker, Inc., 1979. ISBN 0-8247-6877-9
Jackson, Leland B., Digital Filters and Signal Processing, Boston: Kluwer Academic
Publishers, 1986. ISBN 0-89838-174-6
Mayeda, Wataru, Digital Signal Processing, Englewood Cliffs, NJ: Prentice-Hall,
Inc., 1993. ISBN 0-13-211301-5
Morgera, Salvatore D. and Krishna, Hari, Digital Signal Processing: Applications to
Communications and Algebraic Coding Theories, Boston: Academic Press, 1989.
ISBN 0-12-506995-2
Oppenheim, Alan V. and Schafer, Ronald W., Discrete-time signal processing,
Englewood Cliffs, NJ: Prentice-Hall, 1989. ISBN 0-13-216292-X
Peled, Abraham and Liu, Bede, Digital Signal Processing, New York: John Wiley &
Sons, Inc., 1976. ISBN 0-471-01941-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
Proakis, John G. and Manolakis, Dimitris G., Digital Signal Processing: Principles,
Algorithms, and Applications, New York: Macmillan Publishing Company, 1992.
ISBN 0-02-396815-X
Rabiner, Lawrence R. and Gold, Bernard, Theory and application of digital signal
processing, Englewood Cliffs, NJ: Prentice-Hall, 1975. ISBN 0-139-14101-4
Strang, Gilbert and Nguyen, Truong, Wavelets and Filter Banks, Wellesley, MA:
Wellesley-Cambridge Press, 1996. ISBN 0-961-40887-1
Mathematics
Using IDL
Chapter 16: Mathematics 443
Note
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.
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 in 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
x2 x3 xn
e x = 1 + x + ----- + ----- + … + -----
2! 3! n!
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 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.
Note
Many computer languages, such as C, Pascal, and Visual Basic, index
2-dimensional arrays in (row, column) order. IDL indexes arrays in (column, row)
order.
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 a column-major array), IDL considers the second element to be the
number three (the second element in a row-major array).
;Transpose the column-major array into row-major format and print:
PRINT, TRANSPOSE(A)
IDL prints:
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 AT = A.
Multiplying Arrays
IDL has two operators used to multiply arrays. To illustrate the difference between
the two operators, consider the following two arrays:
;A 3-column by 2-row array:
array1 = [ [1, 2, 1], [2, -1, 2] ]
;A 2-column by 3-row array:
array2 = [ [1, 3], [0, 1], [1, 1] ]
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.
1 3
array1 = 1 2 1 , array2 = 0 1
2 –1 2
1 1
IDL prints:
7 -1 7
2 -1 2
3 1 3
Tip
If one or both of the arrays are also transposed, such as TRANSPOSE(A) # B, it is
more efficient to use the MATRIX_MULTIPLY function, which does the transpose
simultaneously with the multiplication.
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 example, consider the arrays defined above:
1 3
array1 = 1 2 1 , array2 = 0 1
2 –1 2
1 1
IDL prints:
2 6
4 7
Multiplying Vectors
When using the # and ## operators to multiply vectors, note the following:
• For A # B, where A and B are vectors, IDL performs A # TRANSPOSE(B). In
this case, C = A # B is a matrix with Cij = Ai Bj. Mathematically, this is
equivalent to the outer product, usually denoted by A ⊗ B.
• For A ## B, where A and B are vectors, IDL performs TRANSPOSE(A) ## B.
In this case, C = A ## B is a matrix with Cij = Bi Aj.
• To compute the dot product, usually denoted by A ⋅ B, use
TRANSPOSE(A) # B.
Notes on the # and ## Operators
Note the following with regard to the array multiplication operators:
• The # and ## operators are order specific.
• 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.
covariance of X and Y
r = ---------------------------------------------------------------------------------------------------------------------------
( standard deviation of X ) ( standard deviation of Y )
or
N–1 N–1 N–1
x y
------------- ∑ x i – ∑ ----k- y i – ∑ ----k-
1
i = 0
N–1 N N
k=0 k=0
r = ------------------------------------------------------------------------------------------------------------------------------------------
N–1 N–1 2 N–1 N–1 2
xk yk
------------- ∑ x i – ∑ ----- ------------- ∑ y i – ∑ -----
1 1
N–1
i=0 k=0
N N–1
i=0 k=0
N
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.
Correlation Example
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
IDL prints:
-0.979907
IDL prints:
0.0322859
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
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
Note
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:
;Define the vectors of tabulated:
X = [0.25, 0.75, 1.25, 1.75, 2.25]
;data values:
Y = [0.28, 0.57, 0.68, 0.74, 0.79]
;Define a vector of weights:
W = 1.0 / Y
;Provide an initial guess of the function’s parameters:
A = [1.0, 1.0]
;Compute the parameters a0 and a1:
yfit = CURVEFIT(X, Y, W, A, SIGMA_A, FUNCTION_NAME = 'funct')
;Print the parameters, which are returned in A:
PRINT, 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 )
Note
The eigenvalues and eigenvectors of a real, symmetric n-by-n array are real
numbers.
IDL prints:
2.00000 4.76837e-07 12.0000
IDL prints:
0.707107 -0.707107 0.00000
-0.577350 -0.577350 -0.577350
-0.408248 -0.408248 0.816497
1 ⁄ 2 –1 ⁄ 2 0
–1 ⁄ 3 –1 ⁄ 3 –1 ⁄ 3
–1 ⁄ 6 –1 ⁄ 6 2⁄ 6
evals = HQR(hes)
; Print the eigenvalues:
PRINT, evals
IDL prints:
( 1.00000, -1.73205)( 1.00000, 1.73205)
( 1.00000, 0.00000)
Note
The three eigenvalues are distinct, and that two are complex. Note also that
complex eigenvalues of an n-by-n real, nonsymmetric array always occur in
complex conjugate pairs.
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)
Repeated Eigenvalues
Example
To compute the eigenvalues and eigenvectors of a real, nonsymmetric n-by-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]]
; Reduce A to upper Hessenberg form and compute the eigenvalues.
; Note that both operations can be combined into a single command.
evals = HQR(ELMHES(A))
; Print the eigenvalues:
PRINT, evals
IDL prints:
( 9.00000, 0.00000) ( 2.00000, 0.00000)
( 2.00000, 0.00000)
Note
The three eigenvalues are real, but only two are distinct.
IDL prints:
( 0.90453403, 0.0000000)( 0.30151134, 0.0000000)
( 0.30151134, 0.0000000)
PRINT, evecs[*,1]
IDL prints:
( -0.27907279, 0.0000000)( -0.78140380, 0.0000000)
( 0.55814557, 0.0000000)
PRINT, evecs[*,2]
IDL prints:
( -0.27907279, 0.0000000)( -0.78140380, 0.0000000)
( 0.55814557, 0.0000000)
IDL prints:
( -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.
IDL prints:
( 1.00000, 0.00000)( 1.00000, 0.00000)
Note
The two eigenvalues are real, but not distinct.
IDL prints:
IDL prints:
( 0.70710678, 0.0000000)( 0.70710678, 0.0000000)
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.
Routine Description
BILINEAR Computes array using bilinear interpolation.
GRID_TPS Uses thin plate splines to interpolate a set of values over
a regular 2D grid, from irregularly sampled data values.
Routine Description
GRID3 Creates a regularly-gridded 3D dataset from a set of
scattered 3D nodes.
INTERPOL Performs linear interpolation on vectors.
INTERPOLATE Returns an array of interpolates.
KRIG2D Interpolates set of points using kriging.
MIN_CURVE_SURF Interpolates points with a minimum curvature surface or
a thin-plate-spline surface. Useful with CONTOUR.
POLAR_SURFACE Interpolates a surface from polar coordinates to
rectangular coordinates.
SPH_SCAT Performs spherical gridding.
SPL_INIT Establishes the type of interpolating spline.
SPL_INTERP Performs cubic spline interpolation (Numerical
Recipes).
SPLINE Performs cubic spline interpolation.
SPLINE_P Performs parametric cubic spline interpolation.
TRI_SURF Interpolates gridded set of points with a smooth quintic
surface.
TRIANGULATE Constructs Delaunay triangulation of a planar set of
points.
TRIGRID Interpolates irregularly-gridded data to a regular grid
from a triangulation.
VALUE_LOCATE Finds the intervals within a given monotonic vector that
brackets a given set of one or more search values.
VORONOI Computes Voronoi polygon given Delaunay
triangulation.
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 distributions of the sample populations.
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.
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.
Routine Description
CTI_TEST Performs chi-square goodness-of-fit test.
FV_TEST Performs the F-variance test.
KW_TEST Performs Kruskal-Wallis H-test.
LNP_TEST Computes the Lomb Normalized Periodogram.
MD_TEST Performs the Median Delta test.
R_TEST Runs test for randomness.
RS_TEST Performs the Wilcoxon Rank-Sum test.
S_TEST Performs the Sign test.
TM_TEST Performs t-means test.
XSQ_TEST Computes Chi-square goodness-of-fit test.
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.
x=b
I = ∫x = a f ( x ) dx
• 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.
x = b y = q(x)
I = ∫x = a ∫y = p( x ) f ( x, y ) dy dx
• Integration of a trivariate function over a regular or irregular region in x-y-z
space is possible using an iterated Gaussian Quadrature routine.
x = b y = q ( x ) z = v ( x, y )
I = ∫x = a ∫y = p( x ) ∫z = u( x, y ) f ( x, y, z ) dz dy dx
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.
A Bivariate Function
Example
Suppose that we wish to evaluate
y=4 x=2
∫y = 0 ∫x =
5
y ⋅ cos ( x ) dx dy
y
The order of integration is initially described as a dx-dy region in the x-y plane. Using
the diagram below, you can easily change the integration order to dy-dx.
Y
x = y
( 2, 4 )
dy
dx
x = 2 X
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
A Trivariate Function
Example
Suppose that we wish to evaluate
2 3⁄2
x=2 2 2
4 – x – y2
∫x = –2 ∫y = – ∫
y= 4–x z= 2 2
z(x + y + z ) dz dy dx
2
4–x z = 0
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
We can use the following IDL commands to determine the value of the above integral
using 6, 10, 20 and 48 transformation points.
For 6 transformation points:
PRINT, INT_3D('fxyz', [-2.0, 2.0], $
'pq_limits', 'uv_limits', 6)
IDL prints:
57.417720
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
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 invertibility 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-by-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.
Overdetermined Systems
Example
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:
column 2
Pb
column 1
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(ATA)-1ATb, where A(ATA)-1AT is
known as the projection matrix, P.
4.0
5.0
0.0
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 × 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 the solution:
PRINT, X
IDL Prints:
2.00000
1.00000
Underdetermined Systems
Example
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.
x0
1.0 3.0 3.0 2.0 x 1.0
1
2.0 6.0 9.0 5.0 = 5.0
x2
– 1.0 – 3.0 3.0 0.0 5.0
x3
x0
1.0 3.0 3.0 2.0 x 1.0
1
0.0 0.0 3.0 1.0 = 3.0
x2
0.0 0.0 0.0 0.0 0.0
x3
– 2 – 3x 1 – x 3
x1
x =
1 – x3 ⁄ 3
x3
– 2.0
x = 0.0
1.0
0.0
– 0.211009
x = – 0.633027
0.963303
0.110092
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]]
; Define the right-hand side vector B:
B = [1.0, 5.0, 5.0]
; Compute the decomposition of A:
SVDC, A, W, U, V
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 × 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 the solution:
PRINT, X
IDL Prints:
-0.211009
-0.633027
0.963303
0.110092
– 1 + 0i 1 – 3i 2 + 0i 3 + 3i z0 15 – 2i
– 2 + 0i – 1 + 3i – 0 + 1i 3 + 1i z1 – 2 – 1i
=
3 + 0i 0 + 4i 0 – 1i – 0 – 3i z2 – 20 + 11i
2 + 0i 1 + 1i 2 + 1i 2 + 1i z3 – 10 + 10i
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)
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:
x0 + x1 – 3
F(x) =
2 2
x0 + x1 – 9
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-by-n linear system of equations.
The first step formulates an n-by-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.
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*, ∇f(x*), be the zero vector. Mathematically expressing
this condition defines the following system of nonlinear equations.
∂f ( x )
-------------
∂x 0
0
∂f ( x )
-------------
∂x 1 = 0
…
…
0
∂f ( x )
---------------
∂x n – 1
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 ∇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.
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 1 plus 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.
Diagonally-Dominant Array
Example
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 = RANDOMN(SEED, N, N)*10
; 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
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.
;Begin with an initial guess:
X = REPLICATE(1.0, N_ELEMENTS(B))
;Start the timer:
start = SYSTIME(1) & $
;Solve the system:
result1 = LINBCG(SPRSIN(A), B, X) & $
;Stop the timer.
stop = SYSTIME(1)
;Print the time taken, in seconds:
PRINT, 'Time for Iterative Biconjugate Gradient:', stop-start
IDL prints:
Time for Iterative Biconjugate Gradient 1.1259040
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 × 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.
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.
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 = (x0, x1, x2, ... ,
xn–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 stationary series.
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.
Compute the sample autocorrelation function for time lagged values 0 – 20 and plot.
lag = INDGEN(21)
result = A_CORRELATE(X, lag)
PLOT, lag, result
;Add a reference line at zero:
PLOTS, [0,20], [0,0], /DATA
;Set the plotting window back to a single plot:
!P.MULTI=0
Figure 16-3: The top graph plots time-series data. The bottom graph plots the
autocorrelation of that data versus the lag. Because the time-series has a
significant autocorrelation up to a lag of seven, it must be considered non-
stationary.
Multivariate Analysis
IDL provides a number of tools for analyzing multivariate data. These tools are
broadly grouped into two categories: Cluster Analysis and Principal Components
Analysis.
Cluster Analysis
Cluster Analysis attempts to construct a sensible and informative classification of an
initially unclassified sample population using a set of common variables for each
individual. The clusters are constructed so as to group samples with the similar
features, based upon a set of variables. The samples (contained in the rows of an
input array) are each assigned a cluster number based upon the values of their
corresponding variables (contained in the columns of an input array).
In computing a cluster analysis, a predetermined number of cluster centers are
formed and then each sample is assigned to the unique cluster which minimizes a
distance criterion based upon the variables of the data. Given an m-column, n-row
array, IDL’s CLUST_WTS and CLUSTER functions compute n cluster centers and n
clusters, respectively. Conceivably, some clusters will contain multiple samples while
other clusters will contain none. The choice of clusters is arbitrary; in general,
however, the user will want to specify a number less than the default (the number of
rows in the input array). The cluster number (the number that identifies the cluster
group) assigned to a particular sample or group of samples is not necessarily unique.
It is possible that not all variables play an equal role in the classification process. In
this situation, greater or lesser importance may be given to each variable using the
VARIABLE_WTS keyword to the CLUST_WTS function. The default behavior is to
assume all variables contained in the data array are of equal importance.
Under certain circumstances, a classification of variables may be desired. The
CLUST_WTS and CLUSTER functions provide this functionality by first
transposing the m-column, n-row input array using the TRANSPOSE function and
then interchanging the roles of variables and samples.
Example of Cluster Analysis
Define an array with 5 variables (columns) and 9 samples (rows):
array = [[ 99, 79, 63, 87, 249 ], $
[ 67, 41, 36, 51, 114 ], $
[ 67, 41, 36, 51, 114 ], $
[ 94, 191, 160, 173, 124 ], $
[ 42, 108, 37, 51, 41 ], $
IDL prints:
1 99 79 63 87 249
3 67 41 36 51 114
3 67 41 36 51 114
0 94 191 160 173 124
2 42 108 37 51 41
3 67 41 36 51 114
0 94 191 160 173 124
1 99 79 63 87 249
3 67 41 36 51 114
Samples 0 and 7 contain identical data and are assigned to cluster #1. Samples 1, 2, 5,
and 8 contain identical data and are assigned to cluster #3. Samples 3 and 6 contain
identical data and are assigned to cluster #0. Sample 4 is unique and is assigned to
cluster #2.
If this example is run several times, each time computing new cluster weights, it is
possible that the cluster number assigned to each grouping of samples may change.
matrix. If the variables of the multivariate data are measured in widely differing units
(large variations in magnitude), it is usually best to use the sample correlation matrix
in computing the principal components; this is the default method used in IDL’s
PCOMP function.
Another alternative is to standardize the variables of the multivariate data prior to
computing principal components. Standardizing the variables essentially makes them
all equally important by creating new variables that each have a mean of zero and a
variance of one. Proceeding in this way allows the principal components to be
computed from the sample covariance matrix. IDL’s PCOMP function includes
COVARIANCE and STANDARDIZE keywords to provide this functionality.
For example, suppose that we wish to restate the following data using its principal
components. There are three variables, each consisting of five samples.
The derived variables {z1, z2, z3} are then computed as follows:
The variables that will contain the values returned by the COEFFICIENTS,
EIGENVALUES, and VARIANCES keywords to the PCOMP routine must be
initialized as nonzero values prior to calling PCOMP.
coef = 1 & eval = 1 & var = 1
; Compute the derived variables based upon
; the principal components.
result = PCOMP(data, COEFFICIENTS = coef, $
EIGENVALUES = eval, VARIANCES = var)
; Display the array of derived variables:
PRINT, result, FORMAT = '(4(f5.1, 2x))'
IDL prints:
81.4 15.5 -5.5 0.5
102.7 11.1 -4.1 0.6
109.9 20.3 -6.2 0.5
110.5 13.8 -6.3 0.6
81.8 17.1 -4.9 0.6
104.8 6.2 -5.4 0.6
121.3 8.1 -5.2 0.6
111.3 12.6 -4.0 0.6
97.0 6.4 -4.4 0.6
102.5 7.8 -6.1 0.6
118.5 11.2 -5.3 0.6
118.9 9.1 -4.7 0.6
81.5 8.8 -6.3 0.6
88.0 13.4 -3.9 0.6
74.3 7.5 -4.8 0.6
113.4 12.0 -5.1 0.6
109.7 7.7 -5.6 0.6
117.5 5.5 -5.7 0.6
91.4 12.0 -6.1 0.6
102.5 10.6 -4.9 0.6
IDL prints:
0.712422
0.250319
0.0370950
0.000164269
Display the percentage of variance for the first two derived variables; the first two
columns of the resulting array above.
PRINT, TOTAL(var[0:1])
IDL prints:
0.962741
This indicates that the first two derived variables (the first two columns of the
resulting array) account for 96.3% of the total variance of the original data, and thus
could be used to summarize the original data.
References
Accuracy and Floating Point Operations
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
Correlation Analysis
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
Hypothesis Testing
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
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
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
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
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
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
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
Multivariate Analysis
Jackson, Barbara Bund. Multivariate Data Analysis. Homewood, Illinois: R.D. Irwin,
1983. ISBN 0-256-02848-6
Everitt, Brian S. Cluster Analysis. New York: Halsted Press, 1993. ISBN 0-470-
22043-0
Kachigan, Sam Kash. Multivariate Statistical Analysis. New York: Radius Press,
1991. ISBN 0-942154-91-6
Object Graphics
This chapter discusses the difference between IDL Direct Graphics and IDL Object Graphics, and
provides an overview of the IDL Object Graphics classes.
Overview
The IDL Object Graphics system is a collection of pre-defined object classes, each of
which is designed to encapsulate a particular visual representation. Actions (such as
the modification of attributes, or data picking) may be performed on instances of
these object classes by calling corresponding pre-defined methods. These objects are
designed for building complex three-dimensional data visualizations.
For example, the IDLgrAxis object provides an encapsulation of all of the
components associated with a graphical representation of an axis. One of the actions
that can be performed on an axis is retrieving the current value of one or more of its
attributes (such as its color, tick values, or data range). This action may be performed
via the IDLgrAxis::GetProperty method. A complete listing of the types of objects
included in the Object Graphics system are described beginning in “Overview of
Object Graphics Classes” on page 508.
Object Graphics should be thought of as a collection of building blocks. In order to
display something on the screen, the user selects the appropriate set of blocks and
puts them together so that as a group they provide a visual result. In this respect,
Object Graphics are quite different than Direct Graphics. A single line of code is
unlikely to produce a complete visualization. Furthermore, a basic understanding of
the IDL object system is required (for instance, how to create an object, how to call a
method, how to destroy an object, etc.). Because of the level at which these objects
are presented, Object Graphics are aimed at application programmers rather than
command line users.
Object Graphics do not interact in any way with the system variables (such as !P, !X,
!Y, and !Z). Each graphic object is intended to encapsulate all of the information
required to fully describe itself. Reliance on external structures is not condoned. The
advantage of this approach is that once an object is created, it will always behave in
the same way even if the system state is modified by another program, or if the object
is moved to another user’s IDL session, where the system state may have been
customized in a different way than the state in which the object was originally
defined.
Object Graphics are designed for building interactive three-dimensional visualization
applications. Direct manipulation tools (such as the Trackball object) are provided to
aid the application developer. Selection and data picking are also built in, so the
developer can spend less time working out data projection issues and more time
focusing on domain specific data analysis and visualization features.
Over time, Research Systems, Inc., will continue to build higher-level applications
with these objects, applications that are suitable for users who prefer not to become
programmers to interact with their data. The LIVE_tools are good examples of
currently available applications built using Object Graphics. For more information,
see LIVE_Tools in the IDL Reference Guide.
Additional examples based on Object Graphics can be found in the IDL demo.
By themselves, a window and a single view are not particularly enlightening, but you
will find that these two types of objects are utilized by all Object Graphics
applications. To change an attribute of an object, you do not have to create a new
instance of that object. Instead, use the SetProperty method on the original object to
modify the value of the attribute.
For example, to change the color of the view to gray:
;Set the color property of the view:
OView->SetProperty, COLOR=[60,60,60]
;Redraw:
OWindow->Draw, oView
If more than one view is to be drawn to the destination, then an additional object is
required:
• A scene object - a container of views
For example:
; Create a scene and add our original view to it:
OScene = OBJ_NEW(’IDLgrScene’)
oScene->Add, oView
; Modify our original view so that it covers
; the upper left quadrant of the window.
OView->SetProperty, LOCATION=[0.0,0.5], DIMENSIONS=[0.5,0.5], $
UNITS=3
; Create and add a second red view that covers
; the right half of the window.
OView2 = OBJ_NEW(’IDLgrView’, LOCATION=[0.5,0.0], $
DIMENSIONS=[0.5,1.0], UNITS=3,COLOR=[255,0,0])
OScene->Add, oView2
; Now draw the scene, rather than the view, to the window:
OWindow->Draw, oScene
In the examples so far, the views have been empty canvases. For data visualization
applications, these views will need some graphical content. To draw visual
representations within the views, two additional types of objects are required:
• A model object - a transformation node
• An atomic graphic object - a graphical representation of data (such as an axis,
plot line, or surface mesh). For more information, see “Atomic Graphic
Objects” on page 512.
For example, to include a text label within a view:
; Create a model and add it to the original view:
oModel = OBJ_NEW('IDLgrModel')
oView->Add, oModel
; Create a text object and add it to the model:
oText = OBJ_NEW('IDLgrText','Hello World',ALIGNMENT=0.5)
oModel->Add, oText
; Redraw the scene:
OWindow->Draw, oScene
Notice that the scene, views, model, and text are all combined together into a self-
contained hierarchy. It is the overall hierarchy that is drawn to the destination object.
The transformation associated with the model can be modified to impact the text it
contains. For example:
; Rotate by 90 degrees about the Z-axis:
oModel->Rotate, [0,0,1], 90
; Redraw:
OWindow->Draw, oScene
When the objects are no longer required, they need to be destroyed. Destination
objects must be destroyed separately, but the graphic hierarchies can be destroyed in
full by simply destroying the root of the hierarchy. For example:
OBJ_DESTROY, oWindow
OBJ_DESTROY, oScene
In this example, the destruction of the scene will cause the destruction of all of its
children (including the views, model, and text).
Note
These category names are purely descriptive; for example, structure objects contain
the IDLgrModel, IDLgrScene, and IDLgrView classes, but no class named
structure. There is one exception to this rule: the container objects category which
includes the IDL_Container class.
This chapter does not describe the relationships between object classes. See Chapter
18, “The Graphics Object Hierarchy” for a discussion of the object tree.
Naming Conventions
In general, object classes shipped with IDL have names of the form:
IDLxxYyyy
where xx represents the broad functional grouping (gr for graphics objects, db for
database objects, and an for analysis, for example). Yyyy is the class name itself
(such as Axis or Surface). Object classes that are useful in more than one
functional context (container objects, for example) omit the functional grouping code
entirely (IDL_Container). All object classes shipped with IDL are prepended with the
letters IDL—we strongly suggest that you do not use this prefix when writing your
own object classes, as we will continue to add new object classes using this
convention.
The typographical convention used to describe IDL objects is slightly different from
that used for non-object functions and procedures. Whereas non-object procedures
are presented in upper case letters, object classes and methods use mixed case. For
example, we refer to the PLOT routine, but to the IDLgrPlot object. Method names
are also presented in mixed case (IDLgrAxis::GetProperty).
Common Methods
In addition to their own specific methods, all object classes shipped with IDL except
for the IDL_Container class have four methods in common: Cleanup, Init,
GetProperty, and SetProperty. The Cleanup and Init methods are life-cycle methods,
and cannot be called directly except within a subclass’ Cleanup or Init method. (See
“The Object Lifecycle” in Chapter 20 of the Building IDL Applications manual.) The
GetProperty and SetProperty methods allow you to inspect (get) or change (set) the
various properties associated with a given object. Properties associated with graphics
objects include things like color, location, line style, or data.
Container Objects
IDL’s container object, realized in the IDL_Container class, provides a way to group
disparate IDL objects into single object. Container objects provide a convenient way
to move or destroy groups of objects; when a container is destroyed, its Cleanup
method automatically calls the Cleanup methods of all the objects in the container
and destroys them as well.
See IDL_Container for details.
Structure Objects
Structure objects create a hierarchy of graphic objects—an object tree. Structure
objects also contain the information necessary to transform graphics objects in space.
Building an object tree allows you to manipulate groups of graphic objects easily by
transforming a single IDLgrModel object to which members of the group belong.
(See Chapter 18, “The Graphics Object Hierarchy” for a discussion of the object
tree.)
Model
Objects of the IDLgrModel class serve as containers for individual graphic objects
(plot lines, axes, text, etc.) and for other model objects. Model objects include a
three-dimensional transformation matrix that describes how the model and all of its
components are positioned in space. Altering the model’s transformation matrix
changes the position and orientation of any objects the model contains. If a model
object contains another model object, the contained model is positioned according to
both its own transformation matrix and that of its container.
See IDLgrModel in the IDL Reference Guide for further details.
View
Objects of the IDLgrView class serve as containers for model objects. A view object
can be supplied as the argument to a Draw method.
See IDLgrView in the IDL Reference Guide for further details.
Viewgroup
Objects of the IDLgrViewgroup class serve as containers for views. A viewgroup
object can be supplied as the argument to a Draw method.
See IDLgrViewgroup in the IDL Reference Guide for further details.
Scene
Objects of the IDLgrScene class serve as containers for view and view group objects.
A scene object can be supplied as the argument to a Draw method.
See IDLgrScene in the IDL Reference Guide for further details.
Axis
Objects of the IDLgrAxis class are individual axes. One axis object is required for
each axis line to be rendered.
See IDLgrAxis in the IDL Reference Guide for further details.
Contour
Objects of the IDLgrContour class are lines representing contour information plotted
from user data.
See IDLgrContour in the IDL Reference Guide for further details.
Image
Objects of the IDLgrImage class are two-dimensional arrays of data with an
associated mapping of the data values to pixel values.
See IDLgrImage in the IDL Reference Guide for further details.
Light
Objects of the IDLgrLight class are light sources by which atomic graphic objects are
illuminated. Light objects are not actually rendered, but are included as graphics
atoms (meaning they must be contained in a model object) so that they can be
positioned and transformed along with the graphic objects they illuminate. If no light
object is included in a particular view, default lighting is supplied.
See IDLgrLight in the IDL Reference Guide for further details.
Plot
Objects of the IDLgrPlot class are individual plot lines, created from a user-supplied
vector of dependent data values (and, optionally, a vector of independent data
values). Plot objects do not include axes.
Polygon
Objects of the IDLgrPolygon class are individual polygons, created from a user-
supplied array of data values.
See IDLgrPolygon in the IDL Reference Guide for further details.
Polyline
Objects of the IDLgrPolyline class are individual polylines, created from a user-
supplied array of data points. Locations of the data points supplied are connected by a
single line.
See IDLgrPolyline in the IDL Reference Guide for further details.
Surface
Objects of the IDLgrSurface class are individual three-dimensional surfaces, created
from a user-supplied array of data values.
See IDLgrSurface in the IDL Reference Guide for further details.
Text
Objects of the IDLgrText class are text strings that can be positioned within the
rendering area.
See IDLgrText in the IDL Reference Guide for further details.
Volume
Objects of the IDLgrVolume class map a three-dimensional array of data values to a
three-dimensional array of voxel colors, which, when drawn, are projected to two
dimensions.
See IDLgrVolume in the IDL Reference Guide for further details.
Composite Objects
A composite object is an encapsulation of a group of other objects that together
provide a commonly useful graphical representation.
Colorbar
Objects of the IDLgrColorbar class are annotations that provide information about
the data values associated with colors used in a visualization.
See IDLgrColorbar in the IDL Reference Guide for further details.
Legend
Objects of the IDLgrLegend class are annotations that provide information about the
meaning of individual data items or lines in a visualization.
See IDLgrLegend in the IDL Reference Guide for further details.
Attribute Objects
Attribute objects are used when rendering graphic objects, but exist outside the
hierarchy of Model-View-Scene objects that are actually rendered.
Font
Objects of the IDLgrFont class define the typeface, size, weight, and style of text
used when rendering a text object.
See IDLgrFont in the IDL Reference Guide for further details.
Palette
Objects of the IDLgrPalette class define a color lookup table that maps indices to red,
green, and blue values.
See IDLgrPalette in the IDL Reference Guide for further details.
Pattern
Objects of the IDLgrPattern class defines which pixels are filled and which are left
blank when a graphic object is filled.
See IDLgrPattern in the IDL Reference Guide for further details.
Symbol
Objects of the IDLgrSymbol class define graphical element that can be used when
plotting data.
See IDLgrSymbol in the IDL Reference Guide for further details.
Helper Objects
Helper objects alter data in useful ways or provide other services. They exist outside
the hierarchy of Model-View-Scene objects that are actually rendered.
Tessellator
Objects of the IDLgrTessellator class convert a simple concave polygon (or a simple
polygon with holes) into a number of simple convex polygons (general triangles).
Tessellation is useful because IDL’s polygon object handles only convex polygons.
See IDLgrTessellator in the IDL Reference Guide for further details.
TrackBall
Objects of the TrackBall class provide a simple interface to allow the user to translate
and rotate three-dimensional Object Graphics hierarchies displayed in an IDL
WIDGET_DRAW window using the mouse.
See TrackBall in the IDL Reference Guide for further details.
Destination Objects
Destination objects are objects on which object trees can be rendered (displayed on a
screen or printed on a printer).
Buffer
Objects of the IDLgrBuffer class represent an off-screen, in-memory data area that
may serve as a graphics source or destination.
See IDLgrBuffer in the IDL Reference Guide for further details.
Clipboard
Objects of the IDLgrClipboard class send Object Graphics to the operating system’s
native clipboard in bitmap format.
See IDLgrClipboard in the IDL Reference Guide for further details.
Printer
Objects of the IDLgrPrinter class represent a hardcopy graphics destination. By
default, printer objects represent the default system printer; you can use the IDL
routines DIALOG_PRINTJOB and DIALOG_PRINTERSETUP to change the
printer associated with a printer object.
See IDLgrPrinter in the IDL Reference Guide for further details.
VRML
Objects of the IDLgrVRML class allow you to save the contents of an Object
Graphics hierarchy as a VRML 2.0 format file.
See IDLgrVRML in the IDL Reference Guide for further details.
Window
Objects of the IDLgrWindow class represent an on-screen area on a display device in
which graphic objects can be rendered.
See IDLgrWindow in the IDL Reference Guide for further details.
Properties of Objects
IDL’s graphics objects have a number of associated properties—things like color, line
style, size, etc. Properties are set or changed via keywords to the object’s Init method
(specified when the object is created) or to the object’s SetProperty method. If you
are familiar with IDL Direct Graphics, many of the keywords used by IDL Object
Graphics will be familiar to you. Note, however, that unlike IDL Direct Graphics, the
IDL Object Graphics system allows you to change the value of an object’s properties
without re-creating the entire object. (Objects must be redrawn, however, with a call
to the destination object’s Draw method, for the changes to become visible.)
Remember that in most cases, an object’s Init method cannot be called directly.
Arguments to OBJ_NEW are passed directly to the Init method when the object is
created.
Note
Not all keywords available when the object is being initialized are necessarily
available via the SetProperty method. Keywords available when using an object’s
SetProperty method are noted with the word Set in parentheses after the keyword
name in the list of keywords to the object’s Init method.
This returns the value of the COLOR property in the IDL variable plotcolor.
You can retrieve the values of all of the properties associated with a graphics object
by using the ALL keyword to the object’s GetProperty method. The following
statement:
myPlot -> GetProperty, ALL=allprops
returns an anonymous structure in the variable allprops; the structure contains the
values of all of the retrievable properties of the object.
Note
Not all keywords available when the object is being initialized are necessarily
available via the GetProperty method. Keywords available when using an object’s
GetProperty method are noted with the word Get in parentheses after the keyword
name in the list of keywords to the object’s Init method.)
Overview
In this chapter we will discuss the organization of a group of graphics objects into a
hierarchy or tree. A graphics tree may have any number of branches, each of which in
turn may have any number of sub-branches, etc.
For example, a graphics object tree with four graphics atoms might be contained in
three separate model objects, which are in turn contained in two distinct view objects,
both of which are contained in one scene object. In this example (shown in the figure
below), the scene object is the root of the graphics tree.
Scenes
A scene, or instance of the IDLgrScene class, is the root-level object of most graphics
trees. Instances of the IDLgrScene class have Add and Remove methods, which
allow you to include or remove IDLgrView or IDLgrViewgroup objects in a scene. A
scene object is one of the possible arguments for a destination object’s Draw method.
It is not necessary to create a scene object if your graphics tree contains only one
view object; in that case, the view can serve as the root of the tree.
Viewgroups
A viewgroup, or instance of the IDLgrViewgroup class, is a simple container object,
similar to the Scene object. The Viewgroup differs from the Scene in two ways:
1. It will not cause an erase to occur on a destination when the destination
object’s Draw method is called.
2. It can contain objects which do not have Draw methods.
Viewgroups are designed to be placed within a scene, and therefor do not typically
serve as the root-level object of a graphics tree. Instances of the IDLgrViewgroup
class have Add and Remove methods, which allow you to include or remove objects
in a viewgroup.
Views
A view, or instance of the IDLgrView class, can also serve as the root-level object of
a graphics tree. Instances of the IDLgrView class have Add and Remove methods,
which allow you to include or remove IDLgrModel objects in a view. A view object
is one of the possible arguments for a destination object’s Draw method.
Every graphics tree must contain at least one view object. Often, it is convenient to
divide the objects being rendered into separate views, which are then contained by a
viewgroup or scene object.
Models
A model, or instance of the IDLgrModel class, is a container for atomic graphic
objects or for other model objects. The model object incorporates a transformation
matrix (see Chapter 19, “Transformations” for an in-depth discussion of
transformation matrices) that applies to all of the graphics atoms and model objects it
contains. In addition to Add and Remove methods, the model object has methods to
Rotate, Scale, and Translate the model and its contents.
To draw the view (and its contents) to the window, the Draw method of the window is
called with the view as its argument:
oWindow->Draw, oView
The window’s Draw method will perform any window-specific drawing setup, then
ask the view to draw itself. The view will then perform view-specific drawing (for
example, clearing a rectangular area to a color), then calls the Draw method for each
of its children (in this case, there is only one child, a model). The model’s Draw
method will push its transformation matrix on a stack, then step through each of its
children (in the order in which they were added) and ask them to draw themselves. In
this example, oXAxis will be asked to draw itself first; then oYAxis will be asked to
draw itself. Once each of the model’s children is drawn, the transformation matrix
associated with the model is popped off of the stack.
Thus, for each object in the hierarchy, drawing essentially consists of three steps:
• Perform setup drawing for this object.
• Step through list of contained children and ask them to draw themselves.
• Perform an follow-up drawing actions before returning control to parent.
The order in which objects are added to the hierarchy will have an impact on when
the objects are drawn. Drawing order can be changed by using the Move method of a
scene, viewgroup, view, or model to change the position of a specific object within
the hierarchy.
The first time a graphic atom (such as an axis, plot line, or text) is drawn to a given
destination, a device-specific encapsulation of its visual representation is created and
stored as a cache. Subsequent draws of this graphic atom to the same destination can
then be drawn very efficiently. The cache is destroyed only when necessary (for
example, when the data associated with the graphic atom changes). Graphic attribute
changes (such as color changes) typically do not cause cache destruction. To gain
maximum benefit from the caches, modification of atomic graphic properties should
be kept to bare minimum.
To destroy the window and remove the objects created from memory, use the
following commands:
OBJ_DESTROY, window
; Destroying the view object destroys all
; of the objects contained in the view:
OBJ_DESTROY, view
Transformations
Overview
Unlike IDL Direct Graphics, the IDL Object Graphics system does not automatically
position and size the objects to be rendered. It is up to you, as a programmer, to
properly define how your graphic elements will be positioned when rendered.
There are three aspects to this transformation from a generic depiction of your data to
a representation that can be rendered to an output device (a graphics destination
object, such as a window or printer) with the perspective, size, and location you want.
Viewport
The first aspect is the view of the graphics objects to be rendered: the size of the
viewing area (the viewport), the type of projection used, the position of the viewer’s
eye as it looks at the graphics objects, and the particular view volume in three-
dimensional space that will be rendered to the viewing area. These elements of the
view of your graphics objects are, appropriately, controlled by properties of the
IDLgrView object being rendered.
Location
The second aspect of the transformation is the location and position of your graphics
objects with respect to the viewing area. Graphics objects can be translated, rotated,
or scaled by setting the appropriate properties of the IDLgrModel object that contains
them.
Note
The viewport and location of an object are independent: It is possible, for example,
to translate a graphic object so that it is no longer within the viewing area that is
rendered in a window or on a printer.
Viewport
One of the first steps in determining how graphics objects will appear when rendered
on a graphics destination object is to select the location and dimensions of the
rectangular area—the viewport—on the destination in which the rendering will be
displayed. Set the location and dimensions of the viewport using the LOCATION and
DIMENSIONS keywords to the IDLgrView::Init method when creating the view
object (or after creation using the SetProperty method). For example, the following
statement creates a view object with a viewport that is 300 pixels by 200 pixels, with
its lower left corner located 100 pixels up from the bottom and 100 pixels to the right
of the left edge of the destination object:
myView = OBJ_NEW('IDLgrView', LOCATION=[100,100], $
DIMENSIONS=[300,200])
Both the LOCATION and DIMENSIONS properties of the view object honor the
value of the UNITS property, which specifies the type of units in which
measurements are made. (Pixels are the default units, so no specification of the
UNITS keyword was necessary in the above example.)
The viewport of an existing view can be changed using the SetProperty method:
changes the location of the viewport to have its lower left corner at (0, 0) and a size of
200 pixels by 200 pixels.
Note
The eye is positioned in only one dimension (along the z-axis) and always points in
the –z direction.
Projection
When three-dimensional graphics are displayed on a flat computer screen or printed
on paper, they must be projected onto the viewing plane. A projection is a way of
converting positions in 3D space into locations in the 2D viewing plane. IDL
supports two types of projections—parallel and perspective—for each view.
Parallel Projections
A parallel projection projects objects in 3D space onto the 2D viewing plane along
parallel rays. The figure below shows a parallel projection; note that two objects that
are the same size but at different locations still appear to be the same size when
projected onto the viewplane.
View objects use a parallel projection by default. To explicitly set a view object to use
a parallel projection, set the PROJECTION keyword to the IDLgrView::Init method
equal to 1 (or use the SetProperty method to set the projection for an exiting view
object):
myView -> SetProperty, PROJECTION = 1
Perspective Projections
A perspective projection projects objects in 3D space onto the 2D viewing plane
along rays that converge at the eye position. The figure below shows a perspective
projection; note that objects that are farther from the eye appear smaller when
projected onto the viewplane.
Set the PROJECTION keyword to the IDLgrView::Init method equal to 2 (or use the
SetProperty method to set the projection for an exiting view object) to use a
perspective projection:
myView -> SetProperty, PROJECTION = 2
Eye Position
The eye position is the position along the z-axis from which a set of objects contained
in a view object are seen. Use the EYE keyword to the IDLgrView::Init method to
specify the distance from the eye position to the viewing plane (or use the
SetProperty method to alter the eye position of an existing view object). The eye
position must be a z value larger than the z value of the near clipping plane (see “Near
and Far Clipping Planes” on page 543) or zero, which ever is greater. That is, the eye
must always be located at a positive z value, and must be outside the volume bounded
by the near and far clipping planes.
For example, the following moves the eye position to z = 5:
myView -> SetProperty, EYE=5
The eye is always positioned directly in front of the center of the viewplane rectangle.
That is, if the VIEWPLANE_RECT property is set equal to [–1, –1, 2, 2], the eye will
be located at X=0, Y=0.
Changing the position of the eye has no affect when you are using a parallel
projection. Changing the eye position when you are using a perspective projection
has a somewhat counter-intuitive affect: moving the eye closer to the near clipping
plane causes objects in the volume being rendered to appear smaller rather than
larger. To understand why this should be true, consider the following diagram.
Figure 19-4: Moving the eye closer to the viewplane causes objects to appear
smaller.
In a perspective projection, rays from the graphic objects in the view volume
converge at the eye position. When the eye is close to the viewing plane, the
projected rays cross the viewing plane (where rendering actually occurs) in a
relatively small area. When the eye moves farther from the viewing plane, the
projected rays become more nearly parallel and occupy a larger area on the viewing
plane when rendered.
View Volume
The view volume defines the three-dimensional volume in space that, once projected,
is to fit within the viewport. There are two parts to the view volume: the viewplane
rectangle and the near and far clipping planes.
Viewplane Rectangle
The viewplane rectangle defines the bounds in the X and Y directions that will be
mapped into the viewport. Objects (or portions of objects) that lie outside the
viewplane rectangle will not be rendered. The viewplane rectangle is always located
at Z=0.
Use the VIEWPLANE_RECT keyword to the IDLgrView::Init method (or use the
SetProperty method if you have already created the view object) to set the location
and extent of the viewplane rectangle. Set the keyword equal to a four-element
floating-point vector; the first two elements specify the X and Y location of the lower
left corner of the rectangle, and the second two elements specify the width and
height. The default rectangle is located at (-1.0, -1.0) and is two units wide and two
units high ([–1.0, –1.0, 2.0, 2.0]). For example, the following command changes the
viewplane rectangle to be located at (0.0, 0.0) and to be one unit square:
myView -> SetProperty, VIEWPLANE_RECT = [0.0, 0.0, 1.0, 1.0]
Figure 19-5: Near and Far Clipping Planes. Object 2 is not rendered, because it
does not lie between the near and far clipping planes.
Model Transformations
An IDLgrModel object is a container for any graphics atoms that are to be rotated,
translated, or scaled. Each IDLgrModel object has a transformation property (set via
the TRANSFORM keyword to the IDLgrModel::Init or SetProperty method), which
is a 4 x 4 floating-point matrix. For a general discussion of transformation matrices
and three-dimensional graphics, see “Three-Dimensional Graphics” in Chapter 12.
Note
A model object’s transformation matrix is akin to the transformation matrix used by
IDL Direct Graphics and stored in the !P.T system variable field. Transformation
matrices associated with model object do not use the value of !P.T, however, and
are not affected by the T3D procedure used in Direct Graphics.
You can change the transformation matrix of a model object directly, using the
TRANSFORM keyword to the IDLgrModel::Init or SetProperty method:
myModel = OBJ_NEW('IDLgrModel', TRANSFORM = tmatrix)
where tmatrix is a 4-by-4 transformation matrix. Alternatively, you can use the
Translate, Rotate, and Scale methods to the IDLgrModel object to alter the model’s
transformation matrix.
Translation
The IDLgrModel::Translate method takes three arguments specifying the amount to
translate the model object and its contents in the X, Y, and Z directions. For example,
to translate a model and its contents by 1 unit in the X-direction, you could use the
following statements:
dx = 1 & dy = 0 & dz = 0
myModel -> Translate, dx, dy, dz
How does this affect the transformation matrix? Notice that we could change the
transformation matrix in an identical way using the following statements:
; Define translation values:
dx = 1 & dy = 0 & dz = 0
; Get existing transformation matrix:
myModel -> GetProperty, TRANSFORM = oldT
; Provide a transformation matrix that performs the translation:
transT = [[1.0, 0.0, 0.0, dx], $
[0.0, 1.0, 0.0, dy], $
[0.0, 0.0, 1.0, dz], $
[0.0, 0.0, 0.0, 1.0]]
; Multiply the existing transformation matrix by
; the matrix that performs the translation:
newT = oldT # transT
; Apply the new transformation matrix to the model object:
myModel -> SetProperty, TRANSFORM = newT
Rotation
The IDLgrModel::Rotate method takes two arguments specifying the axis about
which to rotate and the number of degrees to rotate the model object and its contents.
For example, to rotate a model and its contents by 90 degrees around the y-axis, you
could use the following statements:
axis = [0,1,0] & angle = 90
myModel -> Rotate, axis, angle
How does this affect the transformation matrix? Notice that we could change the
transformation matrix in an identical way using the following statements:
; Define rotation values:
axis = [0,1,0] & angle = 90
; Get existing transformation matrix:
myModel -> GetProperty, TRANSFORM = oldT
; Define sine and cosine of angle:
cosa = COS(!DTOR*angle)
sina = SIN(!DTOR*angle)
; Provide a transformation matrix that performs the rotation:
rotT = [[cosa, 0.0, sina, 0.0], $
[0.0, 1.0, 0.0, 0.0], $
[-sina, 0.0, cosa, 0.0], $
[0.0, 0.0, 0.0, 1.0]]
; Multiply the existing transformation matrix
; by the matrix that performs the rotation.
newT = oldT # rotT
Scaling
The IDLgrModel::Scale method takes three arguments specifying the amount to scale
the model object and its contents in the x, y, and z directions. For example, to scale a
model and its contents by 2 units in the y direction, you could use the following
statements:
sx = 1 & sy = 2 & sz = 1
myModel -> Scale, sx, sy, sz
How does this affect the transformation matrix? Notice that we could change the
transformation matrix in an identical way using the following statements:
; Define scaling values:
sx = 1 & sy = 2 & sz = 1
; Get existing transformation matrix:
myModel -> GetProperty, TRANSFORM = oldT
; Provide a transformation matrix that performs the scaling:
scaleT = [[sx, 0.0, 0.0, 0.0], $
[0.0, sy, 0.0, 0.0], $
[0.0, 0.0, sz, 0.0], $
[0.0, 0.0, 0.0, 1.0]]
; Multiply the existing transformation matrix
; by the matrix that performs the scaling.
newT = oldT # scaleT
; Apply the new transformation matrix to the model object:
myModel -> SetProperty, TRANSFORM = newT
Combining Transformations
Note that model transformations are cumulative. That is, a model object contained in
another model is subject to both its own transformation and to that of its container.
All transformation matrices that apply to a given model object are multiplied together
when the object is rendered. For example, consider a model that contains another
model:
model1 = OBJ_NEW('IDLgrModel', TRANSFORM = trans1)
model2 = OBJ_NEW('IDLgrModel', TRANSFORM = trans2)
model2 -> Add, model1
The model1 object is now subject to both its own transformation matrix (trans1) and
to that of its container (trans2). The result is that when model1 is rendered, it will be
rendered with a transformation matrix = trans1 # trans2.
Coordinate Conversion
Most transformations are handled by the transformation matrix of a model object. For
convenience, however, graphic atoms may also have a simplified transformation
applied to them. Coordinate transformations applied to individual graphic atoms
allow you to change only the translation (position) and scale; this is useful when
converting from one coordinate system to another. For example, you may build your
view object using normalized coordinates, so that values range between zero and one.
If you create a graphic object—a surface object, say—based on the range of data
values, you would need to convert your surface object (built with a data coordinate
system) to match the view object (built with a normal coordinate system). To do this,
use the [XYZ]COORD_CONV keywords to the graphic object in question. The
[XYZ]COORD_CONV keywords take as their argument a two-element vector that
specifies the translation and scale factor for each dimension.
For example, suppose you have a surface object whose data is specified in a range
from [0, 0, zMin] to [xMax, yMax, zMax]. If you wanted to work with this surface as
if it were in a normalized [–1, –1, –1] to [1, 1, 1] space, you could use the following
coordinate conversions:
; Create some data:
myZdata = DIST(60)
; Use the IDL SIZE command to determine
; the size of each dimension of myZdata:
sz = SIZE(myZdata)
; Create a scale factor for the X dimension:
xs = 2.0/(sz[1]-1)
; Create a scale factor for the Y dimension:
ys = 2.0/(sz[2]-1)
; Create a scale factor for the Z dimension:
zs = 2.0/MAX(myZdata)
If you define a function like this in your code, you can then call it whenever you need
to scale your data ranges into normalized coordinates. The following statements
create a plot object from the variable data, retrieve the values of the X and Y ranges
for the plot, and the use the XYCOORD_CONV keywords to the SetProperty method
and the NORM_COORD function to set the coordinate conversion.
plot = OBJ_NEW('IDLgrPlot', data)
plot -> GetProperty, XRANGE=xr, YRANGE=yr
plot -> SetProperty, XCOORD_CONV=NORM_COORD(xr), $
YCOORD_CONV=NORM_COORD(yr)
A Simple Example
The following example steps through the process of creating a surface object and all
of the supporting objects necessary to display it.
Note
You do not need to enter the example code yourself. The example code shown here
is duplicated in the procedure file test_surface.pro, located in the
examples/visual subdirectory of the IDL distribution. You can run the example
procedure by entering TEST_SURFACE at the IDL command prompt.
When creating this procedure, we allow the user to specify keywords that will return
object references to the view, model, surface, and window objects. This allows us to
manipulate the objects directly from the IDL command line after the procedure has
been run.
PRO test_surface, VIEW=oView, MODEL=oModel, $
SURFACE=oSurface, WINDOW=oWindow
END
Play with the example to learn how object transformations work and interact. Try the
following commands at the IDL prompt to observe what they do:
First, compile test_surface.pro:
.RUN test_surface.pro
Now, execute the procedure. The variables you supply via the SURFACE, MODEL,
VIEW, and WINDOW keyword will contain object references you can manipulate
from the command line:
test_surface, VIEW=myview, MODEL=mymodel, $
SURFACE=mysurf, WINDOW=mywin
This will create a window object and display the surface. Now try the following to
translate the object to the right:
mymodel -> Translate, 0.2, 0, 0
The model transformation changes as soon as you issue this command. The window
object, however, will not be updated to reflect the new position until you issue a
Draw command:
mywin -> Draw, myview
Overview
Color is often an integral part of the process of visualizing a dataset. The IDL Object
Graphics system allows you to use color in a number of different ways; this chapter
explains how to specify color when using Object Graphics and how IDL interacts
with the destination devices on which graphics are finally displayed.
Note
For some X11 display situations, IDL may not be able to support a color index
model destination object in object graphics. We do, however, guarantee that an
RGB color model destination will be available for all display situations.
Note
You can specify the color of any graphic object using either a color index or red,
green, and blue (RGB) value, regardless of the color model used by the destination
object or the physical destination device. See “Using Color” on page 564 for
details.
Specify a palette object by setting the PALETTE property equal to an object of the
IDLgrPalette class:
myWindow -> SetProperty, PALETTE=myPalette
If you do not specify a palette object for a destination object that uses the Indexed
color model, a grayscale ramp palette is loaded automatically.
When you assign a color index to an object that is drawn on the destination device,
the color index is used to look up an RGB value in the specified palette. When you
assign an RGB value to an object that is drawn on the destination device, the nearest
match within the destination object’s palette is found and used to represent that color.
Palettes
Objects of the IDLgrPalette class are used to create color lookup tables. The
following statements create a palette object that reverses a standard grayscale ramp
palette:
rval = (gval = (bval = REVERSE(INDGEN(256))))
myPalette = OBJ_NEW('IDLgrPalette', rval, gval, bval)
or
myImage -> SetProperty, PALETTE=myPalette
Note
Palettes associated with graphic atoms are only used when the destination object
uses an RGB color model; if the destination object uses an indexed color model, the
destination object’s palette is always used.
See “IDLgrPalette” in Appendix A of the IDL Reference Guide for details on creating
palette objects.
Using Color
The color of a graphic object is specified by the COLOR property of that object. You
can set the color of an object either when the object is created or afterwards. For
example, the following statement creates a view object and sets its color value to the
RGB triple [60, 60, 60] (a dark gray).
myView = OBJ_NEW('IDLgrView', COLOR = [60, 60, 60])
The following statement changes the color value of an existing axis object to the
color value specified for entry 100 in the color palette associated with the axis object.
myAxis -> SetProperty, COLOR=100
Remember that color palettes associated with individual graphic atoms are only used
when the destination object uses an RGB color model.
• If the physical device uses an RGB color model, the RGB triple retrieved is
passed directly to the device.
If an RGB Triple is Specified
• If the physical device uses an Indexed color model, the RGB triple is mapped
to the index of the nearest match in the device’s color lookup table.
• If the physical device uses an RGB color model, the RGB triple is passed
directly to the device.
Overview
Attribute objects are not rendered directly, but are used to determine how graphic
objects will be rendered. There are four attribute object classes: IDLgrFont,
IDLgrPalette, IDLgrPattern, and IDLgrSymbol.
Helper objects perform operations on object instance data. There are two helper
object classes: IDLgrTessellator and Trackball. For additional information the
trackball object, see “Virtual Trackball and 3D Transformations” on page 555.
Font Objects
Font objects allow you to specify the type style and size used when rendering objects
of the IDLgrText class. You can use either TrueType outline fonts or IDL’s built-in
Hershey vector fonts.
Fonts used by font objects are specified in a string constant constructed from a font
name and one or more optional modifiers. The font name is the name by which your
computer system knows the font (Times for the Times Roman font, for example).
Modifiers specify the weight, angle, and other attributes of the font (Bold specifies a
weight, italic an angle). The font name string looks like this:
'fontname*weight*angle*other_modifiers'
where other_modifiers can be any other font property supported by a given font, such
as a slant. For example, the font name string for Helvetica bold italic is:
'helvetica*bold*italic'
While the font name must come first in the font name string, the order in which the
modifiers are specified is not important.
IDL’s default font is 12 point Helvetica regular.
See “IDLgrFont” in Appendix A of the IDL Reference Guide for details on creating
font objects.
Outline Fonts
IDL provides five TrueType outline fonts for use in font objects: Courier, Helvetica,
Monospace Symbol, Symbol, and Times. Your system may support additional
TrueType fonts —use them in the same way as those supplied by IDL.
The five TrueType fonts provided by IDL support the following modifiers:
Font Modifier
Courier bold, italic
Helvetica bold, italic
Monospace Symbol none
Symbol none
Times bold, italic
Hershey Fonts
IDL supplies a set of vector fonts designed by Dr. A.J. Hershey. See Appendix H,
“Fonts” in the IDL Reference Guide for information on Hershey fonts.
You can use Hershey fonts when creating font objects by specifying a fontname of
the form Hershey*fontnum to the IDLgrFont::Init method.
To create a font object using a Hershey font, omit the font name string and specify the
Hershey font’s index number with the HERSHEY keyword to the IDLgrFont::Init
method. The following statement creates a font object using the Duplex Roman
Hershey font, with a size of 14 points:
myHersheyFont = OBJ_NEW('IDLgrFont', 'hershey*5', SIZE=14)
or
myText -> SetProperty, FONT=myHersheyFont
If no font object is specified, IDL uses the Helvetica font with a size of 12 points.
See “Text Objects” on page 603 for details on creating Text objects.
Palette Objects
Objects of the IDLgrPalette class are used to create color lookup tables. Color lookup
tables assign individual numerical values to color values; this allows you to specify
the color of a graphic object with a single number (a color index) rather than
explicitly providing the red, green, and blue color values (an RGB triple). Palettes are
most useful when you want data values to correspond to color values—that is, if you
want a data value of 200, for example, to always correspond to a single color. This
correspondence is one of the main uses of the Indexed Color Model. See “Indexed
Color Model” in Chapter 20 for additional discussion of indexed color and its uses.
See “IDLgrPalette” in Appendix A of the IDL Reference Guide for details on creating
palette objects.
or
myImage -> SetProperty, PALETTE=myPalette
Note
Palettes associated with graphic atoms are only used when the destination object
uses an RGB color model; if the destination object uses an Indexed color model, the
destination object’s palette is always used. See “How IDL Interprets Color Values”
in Chapter 20 for details.
Pattern Objects
Objects of the IDLgrPattern class are used to fill objects of the IDLgrPolygon class.
Pattern objects can create a solid fill (the default), a line fill (with control over the
orientation, spacing, and thickness of the lines used), or a pattern fill (using a byte
pattern you specify). Pattern objects do not have a color of their own; patterns take
their color from the COLOR property of the polygon they fill.
The following statement creates a pattern object with lines ten pixels apart, 5 pixels
wide, at an angle of 30 degrees:
myPattern = OBJ_NEW('IDLgrPattern', 1, SPACING=10, THICK=5, $
ORIENTATION=30)
To create a pattern fill, specify a 32-by-4 byte array via the PATTERN property of
the pattern object. The byte array you specify will be tiled over the area of the
polygon to be filled. For example, the following statements create a pattern fill with a
random speckle. The first statement creates a 32-by-4 byte array with random values
ranging between 0 and 255. The second statement creates the pattern object.
pattern = BYTE(RANDOMN(seed, 32, 4)*255)
myPattern = OBJ_NEW('IDLgrPattern', 2, PATTERN=pattern)
The following statements create a triangle and fills it with the random speckle
pattern:
pattern = BYTE(RANDOMN(seed, 32, 4)*255)
Symbol Objects
Objects of the IDLgrSymbol class are used to display individual data points, either in
an IDLgrPlot object or an IDLgrPolyline object. You can create symbol objects that
display one of seven pre-defined symbols, any atomic graphic object, or any model
object.
Note that we create the pentagon to fit in the plane between –1 and 1 in both the X
and Y directions. We could also have created the pentagon to fit in a unit square and
then scaled it to fit the domain between –1 and 1.
For example:
pentagon=OBJ_NEW('IDLgrPolygon', [0.1,0.5,0.9,0.7,0.3], $
[0.6,0.9,0.6,0.1,0.1], COLOR=[0,0,255])
symModel = OBJ_NEW('IDLgrModel')
symModel -> Add, pentagon
symModel -> Scale, 2, 2, 1
symModel -> Translate, -1, -1, 0
mySymbol = OBJ_NEW('IDLgrSymbol', symModel)
Note
We create the symbol object to use the model object rather than the polygon object.
Using a model object as a symbol allows you to apply transformations to the
symbol even after it has been created.
Setting Size
By default, symbols extend one unit to each side of the data point they represent. Set
the SIZE property of the symbol object to a two-element vector that describes the
scaling factor in X and Y to apply to the symbol to change the size of the symbols that
are rendered. For example, to scale a symbol so that it extends one tenth of a unit to
each side of the data point, use the statement:
mySymbol -> SetProperty, SIZE=[0.1, 0.1]
Setting Color
If you are using a pre-defined symbol, you can set its color using the COLOR
property of the symbol object. If you are using a graphic object as a symbol, the
symbol’s color is determined by the color of the graphic object and the setting of the
COLOR property of the symbol object itself is ignored. For example, the following
statements create a symbol object that uses a red triangle:
mySymbol = OBJ_NEW('IDLgrSymbol', 5, COLOR=[255,0,0])
Suppose you wish to create a symbol object using the pentagon we created above.
Suppose also that you wish to be able to use the pentagon code in more than one
instance, and would like to be able to make changes to the pentagon object’s color,
size, and orientation. You might create a procedure like the following to define a
pentagon object contained in a model object, and return the object references.
Note
You do not need to enter the example code yourself. The example code shown here
is duplicated in the procedure file penta.pro, located in the examples/visual
subdirectory of the IDL distribution.
Once you have compiled the penta procedure, call it with the SYMBOL and MODEL
keywords set equal to named variables that will contain the object references of the
model and polygon objects:
PENTA, SYMBOL=sym, MODEL=symmodel
Now, create a plot object using the pentagon as the plot symbol:
myPlot = OBJ_NEW('IDLgrPlot', FINDGEN(10), SYMBOL=mySymbol)
Note that the plotting symbols are larger than you might wish. Try making them
smaller:
mySymbol -> SetProperty, SIZE=[0.2,0.2]
myWindow -> Draw, myView
Or, create the following procedure to spin the pentagons around the z-axis (enter
.RUN at the command prompt, followed by these statements):
PRO SPIN, model, view, window, steps
FOR i = 0, steps do begin
model -> Rotate, [0,0,1], 10
window -> Draw, view
END
END
After compiling the SPIN procedure, call it from the command line and watch the
pentagons spin:
SPIN, symmodel, myView, myWindow, 100
While it is unlikely that you will wish to create spinning plot symbols, this example
demonstrates one of the key advantages of IDL Object Graphics over IDL Direct
Graphics—once created, graphics objects can be easily manipulated in a variety of
ways without the need to recreate the entire graph or image after each change.
Tessellator Objects
The IDLgrTessellator class is a helper class that converts a simple concave polygon
(or a simple polygon with holes) into a number of simple convex polygons (general
triangles). A polygon is simple if it includes no duplicate vertices, if the edges
intersect only at vertices, and exactly two edges meet at any vertex.
Tessellation is useful because the IDLgrPolygon object accepts only convex
polygons. Using the IDLgrTessellator object, you can convert a concave polygon into
a group of convex polygons.
Overview
In IDL Object Graphics, axes and titles are not automatically included when plot or
surface objects are created. Instead, you create axis and text objects and place them in
the object hierarchy to annotate your plots and graphs.
Axis Objects
Axis objects provide a visual notation of data values in two- and three-dimensional
plots and graphs. Each axis is represented by an individual axis object; that is, if you
have a plot in X and Y, you will need to create an x-axis object and a y-axis object.
Note
Axis objects do not take their range values from data values or other objects, as you
might expect if you are familiar with IDL Direct Graphics. Instead, axis objects
have a default range of 0.0 to 1.0; you must explicitly set the range of values
covered by the axis object using the RANGE property.
The various keywords to the Init method allow you to control the number of major
and minor ticks, the tick length and direction, the data range, and other attributes. For
example, to create an x-axis object whose data range is between –5 and 5, with the
tick marks below the axis line, use the following command:
xaxis = OBJ_NEW('IDLgrAxis', 0, RANGE=[-5.0, 5.0], TICKDIR=1)
See “IDLgrAxis” in Appendix A of the IDL Reference Guide for details on creating
axis objects.
Next, we retrieve the data range from the plot object and set the x- and y-axis objects’
RANGE properly so that the axes will match the data when displayed:
myplot -> GetProperty, XRANGE=xr, YRANGE=yr
xaxis -> SetProperty, RANGE=xr
yaxis -> SetProperty, RANGE=yr
By default, major tickmarks are 0.2 data units in length. Since the data range in this
example is 0 to 99, we set the tick length to 2% of the data range instead:
xtl = 0.02 * (xr[1] - xr[0])
ytl = 0.02 * (yr[1] - yr[0])
xaxis -> SetProperty, TICKLEN=xtl
yaxis -> SetProperty, TICKLEN=ytl
Create model and view objects to contain the object tree, and a window object to
display it:
mymodel = OBJ_NEW('IDLgrModel')
myview = OBJ_NEW('IDLgrView')
mywindow = OBJ_NEW('IDLgrWindow')
mymodel -> Add, myplot
mymodel -> Add, xaxis
mymodel -> Add, yaxis
myview -> Add, mymodel
Use the SET_VIEW procedure to add an appropriate viewplane rectangle to the view
object. (See “Finding an Appropriate View Volume” on page 544 for information on
SET_VIEW).
SET_VIEW, myview, mywindow
Logarithmic Axes
Creating a plot of logarithmic data requires that you create a logarithmic axis as well.
The following example first creates a linear plot, then takes a logarithm of the same
data and creates a log-linear plot.
The example code below is included in a procedure file named obj_logaxis.pro,
located in the examples/visual subdirectory of the IDL distribution. You can run
the example code by entering obj_logaxis at the IDL prompt. You can also
examine the .pro file itself for examples of some of the topics discussed in this
section.
;Create a window and a view.
PRO obj_logaxis
oWindow = OBJ_NEW('IDLgrWindow')
oView->Add, oModel
;Scale and translate the model so the plot fits within the view:
oModel->Scale, 1.0/xRange, 1.0/yRange, 1.0
oModel->Translate, -(xMin/xRange), -(yMin/yRange), 0.0
oWindow->Draw, oView
READ, val, PROMPT='Press <Return> to quit.'
OBJ_DESTROY, oView
OBJ_DESTROY, oWindow
OBJ_DESTROY, oXTitle
OBJ_DESTROY, oYTitle
END
Date/Time Axes
Dates and times are among the many types of information that numerical data can
represent. IDL provides a number of routines that offer specialized support for
generating, analyzing, and displaying date- and time- based data (herein referred to as
date/time data).
Julian Dates and Times
Within IDL, dates and times are typically stored as Julian dates. A Julian date is
defined to be the number of days elapsed since noon on January 1, 4713 BCE.
Following the astronomical convention, a Julian day is defined to start at 12pm
(noon). The following table shows a few examples of calendar dates and their
corresponding Julian dates.
Julian dates can also include fractional portions of a day, thereby incorporating hours,
minutes, and seconds. If the day fraction is included in a Julian date, it is represented
as a double-precision floating point value. The day fraction is computed as follows:
One advantage of using Julian dates to represent dates and times is that a given
date/time can be stored within a single variable (rather than storing the year, month,
day, hour, minute, and second information in six different variables). Because each
Julian date is simply a number, IDL’s numerical routines can be applied to Julian
dates just as for any other type of number.
Note
Julian values must be in the range -1095 to 1827933925, which corresponds to
calendar dates 1 Jan 4716 B.C.E. and 31 Dec 5000000, respectively.
; Convert to seconds
PRINT, precision*86400d0
where the UNIT keyword is set to 'Months' to increment by month and the START
keyword is set to the Julian date form of March 1, 2000.
The results of the above call to TIMEGEN can be output using either of the following
methods:
1. Using the CALDAT routine to convert the Julian dates to calendar dates:
CALDAT, date_time, month, day, year
FOR i = 0, (N_ELEMENTS(date_time) - 1) DO PRINT, $
month[i], day[i], year[i], $
FORMAT = '(i2.2, "/", i2.2, "/", i4)'
The TIMEGEN routine contains several keywords to provide specific date/time data
generation. For more information, see the TIMEGEN in the IDL Reference Guide.
Displaying Date/Time Data on an Axis in Object Graphics
You can display date/time data on plots, contours, and surfaces through the tick
settings of the date/time axis. Date/time data can be displayed on any axis (x, y or z).
The date/time data is stored as Julian dates, but the LABEL_DATE routine and axis
keywords allow you to display this data as calendar dates. The following examples
show how to display one-dimensional and two-dimensional date/time data.
Displaying Date/Time Data on a Plot Display
Date/time data usually comes from measuring data values at specific times. For
example, the displacement (in inches) of an object might be recorded at every second
for 37 seconds after the initial recording of 59 minutes and 30 seconds after 2 o'clock
pm (14 hundred hours) on the 30th day of March in the year 2000 as follows
number_samples = 37
date_time = TIMEGEN(number_samples, UNITS = 'Seconds', $
START = JULDAY(3, 30, 2000, 14, 59, 30))
displacement = SIN(10.*!DTOR*FINDGEN(number_samples))
Normally, this type of data would be imported into IDL from a data file. However,
this section is designed specifically to show how to display date/time data, not how to
import data from a file; therefore, the data for this example is created with the above
IDL commands.
Before displaying this one-dimensional data with the IDLgrPlot object, the format of
the date/time values is specified through the LABEL_DATE routine:
date_label = LABEL_DATE(DATE_FORMAT = ['%I:%S'])
The oPlotModel object will contain the IDLgrPlot and IDLgrAxis objects. The
oPlotView object contains the oPlotModel object with the DOUBLE keyword. The
DOUBLE keyword is set for the oPlotView and oPlot objects because the date/time
data is made up of double-precision floating-point values.
Although the date/time part of the data will actually be contained and displayed
through the IDLgrAxis object, the oPlot object is created first to provide a display
region for the axes:
oPlot -> GetProperty, XRANGE = xr, YRANGE = yr
xs = NORM_COORD(xr)
Now the oPlotView object, which contains all of these objects, can be viewed in the
oPlotWindow object:
oPlotWindow -> Draw, oPlotView
The Draw method to the oPlotWindow object produces the following results:
The above display shows the progression of the date/time variable, but it does not
include all of the date/time data we generated with the TIMEGEN routine. This data
also includes hour, month, day, and year information. IDL can display this
information with additional levels to the date/time axis. You can control the number
of levels to draw and the units used at each level with the TICKUNITS keyword. You
can specify the formatting for these levels by changing the DATE_FORMAT
keyword setting to the LABEL_DATE routine:
date_label = LABEL_DATE(DATE_FORMAT = $
['%I:%S', '%H', '%D %M, %Y'])
Besides the above change to the LABEL_DATE routine, we must also change the
settings of the IDLgrAxis properties to specify a multiple level axis:
oPlotXAxis -> SetProperty, $
TICKFORMAT = ['LABEL_DATE', 'LABEL_DATE', 'LABEL_DATE'], $
TICKUNITS = ['Time', 'Hour', 'Day']
The TICKFORMAT is now set to a string array containing an element for each level
of the axis. The TICKUNITS keyword is set to note the unit of each level. These
property settings produce the following results:
Notice the three levels of the X-axis. These levels are arranged as specified by the
previous call to the LABEL_DATE routine.
To maintain IDL’s memory, the object references for oPlotView, oTextXAxis, and
oTextYAxis should be destroyed. Therefore, after the display is drawn, the
OBJ_DESTROY routine should be called:
OBJ_DESTROY, [oPlotView, oTextXAxis, oTextYAxis]
The display will remain until closed, but the object references are now freed from
IDL’s memory.
Displaying Date/Time Data on a Contour Display
Another possible example may be the surface temperature (in degrees Celsius) of
each degree of a single circle on a sphere recorded at every second for 37 seconds
Using IDL Axis Objects
598 Chapter 22: Working with Axes and Text
after the initial recording of 59 minutes and 30 seconds after 2 o’clock pm (14
hundred hours) on the 30th day of March in the year 2000:
number_samples = 37
date_time = TIMEGEN(number_samples, UNITS = 'Seconds', $
START = JULDAY(3, 30, 2000, 14, 59, 30))
angle = 10.*FINDGEN(number_samples)
temperature = BYTSCL(SIN(10.*!DTOR* $
FINDGEN(number_samples)) # COS(!DTOR*angle))
As with the one-dimensional case, the format of the date/time values is specified
through the LABEL_DATE routine as follows:
date_label = LABEL_DATE(DATE_FORMAT = $
['%I:%S', '%H', '%D %M, %Y'])
The oContourModel object will contain the IDLgrContour and IDLgrAxis objects.
The oContourView object contains the oContourModel with the DOUBLE keyword.
The DOUBLE and DOUBLE_GEOM keywords are set for the oContourView and
The oContourLines object is created to display contour lines over the filled contours.
Note these lines have a GEOMZ difference of 0.001 from the filled contours. This
difference is provided to display the lines over the filled contours and not in the same
view plane. The NORM_COORD routine is used to create a normalized (0 to 1)
display coordinate system. This coordinate system will also apply to the IDLgrAxis
objects:
; X-axis title.
oTextXAxis = OBJ_NEW('IDLgrText', 'Angle (degrees)')
; X-axis.
oContourXAxis = OBJ_NEW('IDLgrAxis', 0, /EXACT, RANGE = xr, $
XCOORD_CONV = xs, YCOORD_CONV = ys, TITLE = oTextXAxis, $
LOCATION = [xr[0], yr[0], zr[0] + 0.001], TICKDIR = 0, $
TICKLEN = (0.02*(yr[1] - yr[0])))
; Y-axis title.
oTextYAxis = OBJ_NEW('IDLgrText', 'Time (seconds)')
; Y-axis (date/time axis).
oContourYAxis = OBJ_NEW('IDLgrAxis', 1, /EXACT, RANGE = yr, $
XCOORD_CONV = xs, YCOORD_CONV = ys, TITLE = oTextYAxis, $
LOCATION = [xr[0], yr[0], zr[0] + 0.001], TICKDIR = 0, $
TICKLEN = (0.02*(xr[1] - xr[0])), $
TICKFORMAT = ['LABEL_DATE', 'LABEL_DATE', 'LABEL_DATE'], $
TICKUNITS = ['Time', 'Hour', 'Day'], $
TICKLAYOUT = 2)
oContourText = OBJ_NEW('IDLgrText', $
'Measured Temperature (degrees Celsius)', $
LOCATIONS = [(xr[0] + xr[1])/2., $
(yr[1] + (0.02*(yr[0] + yr[1])))], $
XCOORD_CONV = xs, YCOORD_CONV = ys, $
ALIGNMENT = 0.5)
in the call to the LABEL_DATE routine. This example also contains the
TICKLAYOUT keyword. By default, this keyword is set to 0, which provides the
date/time layout shown in the plot example. In this example, TICKLAYOUT is set to
2, which rotates and boxes the tick labels.
These objects are now added to the oContourModel object and this model is added to
the oContourView object:
oContourModel -> Add, oContour
oContourModel -> Add, oContourLines
oContourModel -> Add, oContourXAxis
oContourModel -> Add, oContourYAxis
oContourModel -> Add, oContourText
oContourView -> Add, oContourModel
Now the oContourView object, which contains all of these objects, can be viewed in
the oContourWindow object:
oContourWindow -> Draw, oContourView
Notice the three levels of the Y-axis. These levels are arranged as specified by the
previous call to the LABEL_DATE routine.
To maintain IDL's memory, the object references for oContourView, oContourPalette,
oTextXAxis, and oTextYAxis should be destroyed. Therefore, after the display is
drawn, the OBJ_DESTROY routine should be called:
The display will remain until closed, but the object references are now freed from
IDL's memory.
Note
Titles and tickmark text inherit the color specified for the IDLgrAxis object itself,
even if the COLOR property is specified for the IDLgrText object specified, unless
the USE_TEXT_COLOR property for the axis is nonzero.
By default, major tick marks are labelled with the data values. You can supply a set
of tickmark text values by setting the TICKTEXT property equal to either a single
instance of an IDLgrText object containing a vector of text strings or to a vector of
IDLgrText objects, each of which contains a single text string.
Note
Make sure that you have the same number of tick label strings as there are major
tick marks for the axis.
EX_REVERSE_PLOT.PRO at the IDL command line. You can view the source for this
example, EX_REVERSE_PLOT.PRO, in the examples/visual directory.
Text Objects
Text objects contain string values that are drawn to the destination object at a location
you specify. You have control over the font used (via an IDLgrFont object), the angle
of the text baseline, and the vertical direction of the text.
or
mytextarr = OBJ_NEW('IDLgrText', $
['First String', 'Second String', 'Third String'])
See “IDLgrText” in Appendix A of the IDL Reference Guide for details on creating
text objects.
The text is drawn at the specified location, with the baseline parallel to the x-axis.
Location and Alignment
Specifying a location via the LOCATION property picks a point in space where the
text object will be placed. By default, text objects are aligned with their lower left
edge located at the point specified by the LOCATION property.
You can change the horizontal position of the text object with respect to the point
specified by LOCATION by changing the ALIGNMENT property to a floating-point
value between 0.0 and 1.0. The default value (0.0) aligns and left-justifies text at the
location specified. Setting ALIGNMENT to 1.0 right-justifies the text; setting it to
0.5 centers the text above the point specified. The vertical position with respect to
location can also be set using the VERTICAL_ALIGNMENT property. The default
value (0.0) bottom-justifies the text at the given location. A vertical alignment of 1.0
top-justifies the text.
3D Text and Text “On the Glass”
Text objects, like all graphics atoms, are located and oriented in three-dimensional
space. (We often ignore the third dimension when making simple plots and graphs—
in these cases we simply use the default z value of zero.) With text objects, however,
there is an option to project text on the glass.
Projecting text on the glass ensures that it is displayed as if it were in flat, two-
dimensional space no matter what its true orientation in three-dimensional space may
be. In cases where text objects may be rotated at arbitrary angles, projecting on the
glass ensures that the text will be readable.
To project text on the glass, set the ONGLASS property of the text object to a value
other than zero.
Baseline
The text baseline can be altered from its default orientation (parallel to the x-axis) by
setting the text object’s BASELINE property to a two- or three-element array. The
new baseline will be oriented parallel to a line drawn between the origin and the
coordinates specified. For example, the following statement makes the text baseline
parallel to a line drawn between the points [0, 0] and [1, 2]:
The following statement makes the baseline parallel to a line drawn between the
origin and a point located at [2, 1, 3]:
mytext -> SetProperty, BASELINE=[2,1,3]
Notice that the orientation of the baseline is only an orientation; changing value of
the BASELINE property does not change the location of the text object.
Upward Direction
In addition to the baseline orientation, you can control the upward direction of the
text object. (The upward direction is the direction defined by a vector pointing from
the origin to the point specified.) The upward direction defines the plane on which
text is drawn; by specifying a baseline and an upward direction, you define the plane.
Note
The upward direction does not specify a slant angle. That is, even if you specify a
direction that is not perpendicular to the baseline for the upward direction, the text
will still be perpendicular to the baseline. All that matters is the plane defined by the
baseline and upward direction.
For example, in the default situation, the baseline is oriented parallel to the x-axis,
and the upward direction is parallel to the y-axis, pointing in the positive y direction.
Warning
If the baseline and upward direction are coincident—that is, if they do not define a
plane on which to draw the text—IDL generates an error message.
Fonts
The type style and size of the characters displayed in a text object are controlled by
the FONT property. Set the FONT property equal to the object reference of an
IDLgrFont object to use that font’s properties for the text object. If no font object is
specified, IDL uses the default font (12 point Helvetica regular).
Font objects are discussed in “Font Objects” on page 571.
A Text Example
An example procedure named rot_text.pro is included in the
examples/visual subdirectory of the IDL distribution. This file creates a simple
text string, rotates it around the y- and z-axes using the BASELINE and UPDIR
properties, and displays several different fonts.
You can run the example code by entering rot_text at the IDL prompt. You can
also examine the .pro file itself for examples of some of the topics discussed in this
section.
Contour Objects
Contour objects create a set of contour lines from data stored in a rectangular array or
in a set of unstructured points. Contour objects can consist either of lines or of filled
regions.
Note
In order to display the contour as on the plane (rather than as a three-dimensional
image), you must set the PLANAR property of the contour object equal to one and
explicitly set the GEOMZ property equal to zero.
mywindow = OBJ_NEW('IDLgrWindow')
myview = OBJ_NEW('IDLgrView', VIEWPLANE_RECT=[0,0,19,19])
mymodel = OBJ_NEW('IDLgrModel')
data = DIST(20)
mycontour = OBJ_NEW('IDLgrContour', data, COLOR=[100,150,200], $
C_LINESTYLE=[0,2,4], /PLANAR, GEOMZ=0, C_VALUE=INDGEN(20))
A more complex example using a contour object is shown in the contour demo. To
start the demos, type demo at the IDL command prompt. Both the terrain elevation
and vehicle tire data sets are displayed using the contour object.
Polygon Objects
Polygon objects represent one or more filled polygons that share a given set of
vertices and rendering attributes. All polygons must be simple (the edges of the
polygon should not intersect) and convex (the shape of the polygon should not have
any indentations). Concave polygons can be converted into convex polygons using
the helper object IDLgrTessellator. See “Tessellator Objects” on page 581 for more
on tessellator objects.
Set the STYLE property equal to 1 (one) to render the vertices and lines connecting
them. The following statement draws the polygon’s outline in green:
mypolygon -> SetProperty, STYLE=1, COLOR=[0,255,0,]
The default setting for the STYLE property is 2, which produces a filled polygon.
The following statement draws the filled polygon in red:
mypolygon -> SetProperty, STYLE=2, COLOR=[255,0,0]
Vertex Colors
You can supply a vector of vertex colors via the VERT_COLORS property. The
colors in the vector will be applied to each vertex in turn. If there are more vertices
than colors supplied for the VERT_COLORS property, IDL will cycle through the
colors. For example, the following statements color each vertex and connecting line
one of four colors:
vcolors =[[0,100,200],[200,150,200],[150,200,250],[250,0,100]]
mypolygon -> SetProperty, STYLE=1, VERT_COLORS=vcolors
Fill Patterns
As demonstrated in “Pattern Objects” on page 575, you can fill a polygon with a
pattern contained in an IDLgrPattern object. Set the FILL_PATTERN property equal
to the object reference of the pattern object. If you have created a pattern object called
mypattern, the following statement uses that pattern as the polygon’s fill pattern:
mypolygon -> SetProperty, STYLE=2, FILL_PATTERN=mypattern
Shading
IDL provides two types of shading for filled objects. In Flat shading, the color of the
first vertex in each polygon is used to define the color for the entire polygon. The
polygon color has a constant intensity. In Gouraud shading, the colors along each line
are interpolated between vertex colors, and then along scanlines from each of the
edge intensities.
Set the SHADING property of the polygon object equal to 0 (zero) to use flat shading
(this is the default), or equal to 1 (one) to use Gouraud shading. In the above example
using vertex colors, adding the following statement:
mypolygon -> SetProperty, STYLE=2, SHADING=1
creates a polygon fill in which the color values are interpolated between the vertex
colors.
Texture Mapping
You can map an image onto a polygon object by specifying an IDLgrImage object to
the TEXTURE_MAP property. The TEXTURE_COORD property defines how
individual data points within the image data are mapped to the polygon’s vertices.
Note that you must specify both TEXTURE_MAP and TEXTURE_COORD to
enable texture mapping.
0 1 2 3
4 5 6 7
8 9 10 11
For example, to use a quad strip optimization for the polygons shown above, the
connectivity for the vertices should be as follows:
verts = [v0, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10 ,v11]
oPoly = OBJ_NEW(IDLgrPolygon, verts, $
POLYGON=[4, 0, 1, 5, 4, $
4, 1, 2 ,6, 5, $
4, 2, 3, 7, 6, $
4, 4, 5, 9, 8, $
4, 5, 6, 10, 9, $
4, 6, 7, 11, 10])
Triangle Fans
A triangle fan is a set of connected triangles that all share a common vertex. To take
advantage of accelerated triangle fans, the connectivity should be set up so that the
first vertex in every triangle is the common vertex, and the second vertex is the same
as the last vertex of the previous triangle, as shown below.
2 3 4 0 2 4
1 0 5 1 3 5
Figure 23-4: Triangle Fan Mesh (left) and Triangle Strip Mesh (right)
For example, to use a triangle fan optimization for the polygons shown in the left side
of the figure, the connectivity for the vertices should be as follows:
verts = [v0, v1, v2, v3, v4, v5]
oPoly = OBJ_NEW(IDLgrPolygon, verts, $
POLYGON=[3, 0, 1, 2, $
3, 0, 2, 3, $
3, 0, 3, 4, $
3, 0, 4, 5])
Triangle Strips
A triangle strip is a set of connected triangles, each of which share two vertices with
the previous triangle. To take advantage of accelerated triangle strips, the
connectivity should be set up so that the first two vertices in every triangle must have
been in the previous triangle and ordered in the same direction (counter-clockwise or
clockwise) and the final vertex must be new, as shown in the right side of the
previous figure.
For example, to use the triangle strip optimization for the polygons shown in the
right-hand figure, the connectivity for the vertices should be as follows:
verts = [v0, v1, v2, v3, v4, v5]
oPoly = OBJ_NEW(IDLgrPolygon, verts, $
POLYGON=[3, 0, 1, 2, $
3, 2, 1, 3, $
3, 2, 3, 4, $
3, 4, 3, 5])
No limits are imposed on the number of meshes or types of meshes within any given
polygon object. A single POLYGON keyword value might contain any combination
of quad strips, triangle strips, triangle fans, or non-specialized polygons.
As the length of the strips or fans grows, and as the percentage of vertex connections
that are optimized by the rules described above increases, the performance upgrade
becomes more perceptible. The optimizations are a result of minimizing the time
required to perform vertex transforms. If the drawing of the polygons are otherwise
limited by fill-rate (as might occur on some systems if texture-mapping is being
applied, for instance), these optimizations may not be of significant benefit. In any
case, performance will not be hindered in any way by utilizing these specialized
meshes, so it is suggested that they be applied whenever possible.
Note
The IDLgrSurface object always takes advantage of the quad mesh optimization
automatically without programmer intervention.
Normal Computations
For IDLgrPolygon objects, normal vectors are computed by default at each vertex by
averaging the normals of the polygons that share that vertex. These normals are then
used to compute illumination intensities across the surface of the polygon.
Computing default normals is a computationally expensive operation. Each time the
polygon is drawn, this computation will be repeated if the polygon has changed
significantly enough to warrant a new internal cache (for example, if the
connectivity, vertices, shading, or style have changed). In some cases, the normals do
not actually change as other modifications are made. In these cases, the expense of
default normal computation can be bypassed if the user provides the normals
explicitly (via the NORMALS keyword). The provided normals will be reused every
time the polygon is drawn (without further computation) until they are replaced
explicitly by the user. See COMPUTE_MESH_NORMALS in the IDL Reference
Guide for more information.
Polyline Objects
Polyline objects lines connect a series of points in two- or three-dimensional space.
Plot Objects
Plot objects maps a set of abscissa values to a set of ordinate values and creates a
polyline connecting the points. Note that plot objects do not automatically create axes
for the plot lines they create.
The following statements plot the same data versus a series of primes:
datay = [2,9,4,4,6,2,8]
datax = [0,1,2,5,7,11,13]
myplot = OBJ_NEW('IDLgrPlot', datax, datay)
See “IDLgrPlot” in Appendix A in the IDL Reference Guide for details on creating
plot objects.
Averaging Points
Use the NSUM property of the plot object to average the values of a group of data
points before plotting. If there are m data points, m/NSUM data points are plotted.
For example, the following statement causes IDL to average pairs of data points
when plotting the line for the histogram plot:
myplot2 -> SetProperty, NSUM=2
mywindow -> Draw, myview
Polar Plots
To create a polar plot, provide a vector of radius values, a vector of theta values, and
set the POLAR property to a nonzero value. The following example creates a simple
polar plot:
mywindow = OBJ_NEW('IDLgrWindow')
myview = OBJ_NEW('IDLgrView', VIEWPLANE_RECT=[-100,-100,200,200])
mymodel = OBJ_NEW('IDLgrModel')
r = FINDGEN(100)
theta = r/5
mypolarplot = OBJ_NEW('IDLgrPlot', r, theta, /POLAR)
myview -> Add, mymodel
mymodel -> Add, mypolarplot
mywindow -> Draw, myview
Legend Objects
Legend objects provide a simple interface for displaying legends. The legend itself
consists of a (filled and/or framed) box around one or more legend items (arranged in
a single column) and an optional title string. Each legend item consists of a glyph
patch positioned to the left of a text string. The glyph patch is drawn in a square
which is a fraction of the legend label font height.
There should be one element of the ITEM_TYPE array per element in the input array
or ITEM_NAME array.
Use the ITEM_LINESTYLE and ITEM_THICK properties to define the style and
thickness of lines used as legend items. These arrays are ignored for elements that are
not lines. Use the ITEM_COLOR property to specify the color of each legend
element independently.
Use the ITEM_OBJECT property to specify that a graphic object be used as an
annotation.
Dimensions
Until the legend is drawn to the destination object, the [XYZ]RANGE properties will
be zero. Because you must know the size of the legend object in order to scale it
properly for your window, you must use the ComputeDimensions method on the
legend object to get the data dimensions of the legend prior to a draw operation.
The following example builds and displays a three-element legend.
; Create a window, view, and model:
mywindow = OBJ_NEW('IDLgrWindow')
myview = OBJ_NEW('IDLgrView')
mymodel = OBJ_NEW('IDLgrModel')
myview -> Add, mymodel
; Create the legend with two items:
itemNameArr = ['Original Data', 'Histogram Plot', $
'Boxcar-filtered (Width=5)']
mytitle = OBJ_NEW('IDLgrText', 'Plot Legend')
mysymbol = OBJ_NEW('IDLgrSymbol', 5, SIZE=[0.3, 0.3])
myLegend = OBJ_NEW('IDLgrLegend', itemNameArr, TITLE=mytitle, $
BORDER_GAP=0.8, GAP=0.5, $
ITEM_TYPE=[0,1], ITEM_LINESTYLE=[0,4,2], $
ITEM_OBJECT=[mysymbol, OBJ_NEW(), OBJ_NEW()]$
GLYPH_WIDTH=2.0, /SHOW_OUTLINE)
; Add the legend to the model:
mymodel -> Add, mylegend
; Center the legend in the window.
; Note that you must use the ComputeDimensions method
; to get the dimensions of the legend.
dims = mylegend->ComputeDimensions(mywindow)
mymodel->Translate, -(dims[0]/2.), -(dims[1]/2.), 0
; Draw the legend:
mywindow->Draw, myview
A Plotting Routine
This section develops a plotting routine that uses many of the object graphics features
discussed here and in previous chapters. The code for this example is contained in the
file obj_plot.pro, located in the examples/visual subdirectory of the IDL
distribution.
The OBJ_PLOT routine will create a window object, and display within it a view of a
single model object, which will contain a plot object, x- and y-axis objects, and an x-
axis title object. It will use the Times Roman font for the axis title.
In creating the procedure, we allow the user to specify the data to be plotted, and we
define keyword variables which can return the object references for the view, model,
window, axis, and plot objects. This allows the user to manipulate the object tree after
it has been created. We also specify the _EXTRA keyword, which allows the user to
include other keyword parameters in the call. OBJ_PLOT itself passes any extra
keyword parameters only to the plot object, but a more complex program could pass
keyword parameters to any of the objects created. The following lines begin the
procedure.
Note
See “A Function for Coordinate Conversion” on page 550 for a discussion of the
NORM_COORD function used in this example. Also, SET_VIEW is discussed in
“Finding an Appropriate View Volume” on page 544. (The files set_view.pro
and norm_coord.pro are included in the examples/visual/utility
subdirectory of the IDL distribution. NORM_COORD is also defined in the
obj_plot.pro file.)
; Add a title to the X-axis, using the font object defined above:
xtext = OBJ_NEW('IDLgrText', 'X Title', FONT=myfont)
myxaxis -> SetProperty, TITLE=xtext
Now, the OBJ_PLOT routine can be called with only the data parameter, if you
choose. For example, the statement
OBJ_PLOT, FINDGEN(10)
creates and displays the object hierarchy with a simple plot line. However, if you do
not retrieve the window, view, and other object references via the keywords, there is
no way you can interactively modify the plot. A better way to call OBJ_PLOT would
be:
OBJ_PLOT, FINDGEN(10), WINDOW=win, VIEW=view, PLOT=plot,
CONTAINER=cont
This statement creates the same object hierarchy, but returns the object references for
the window, view, and plot objects in named variables. Having access the object
references allows you to do things like change the color of the plot:
plot -> SetProperty, COLOR=[255,255,255]
window -> Draw, view
Note that when using the OBJ_DESTROY procedure, any object added to the
specified object (using the Add method) are also destroyed, recursively. We use a
container object to collect all of the objects, including attribute objects and text object
that are not explicitly added to the object tree, which allows you to destroy the entire
collection with a single call to OBJ_DESTROY.
• Provide a way to set properties of the axis and text objects when calling
obj_plot.
Working with
Surfaces
This chapter describes the use of surface and light objects. The following topics are covered in this
chapter:
Surface Objects
Surface objects create a representation of functions of two variables. Surfaces are
presented as three-dimensional objects in three-dimensional space, and thus are good
candidates for interactive rotation, and scaling. Examples in this chapter discuss
interactive manipulation of surface objects.
Similarly, if xdata and ydata are either 40-element vectors or 40x40 element arrays
specifying the X and Y values which, when evaluated by some function, result in the
zdata array, you would create the surface object with the following statement:
mysurf = OBJ_NEW('IDLgrSurface', zdata, xdata, ydata)
The following statement draws the surface as a solid lego-type surface in green:
mysurf -> SetProperty, STYLE=6, COLOR=[0,255,0]
Vertex Colors
You can supply a vector of vertex colors via the VERT_COLORS property. The
colors in the vector will be applied to each vertex in turn. If there are more vertices
than colors supplied for the VERT_COLORS property, IDL will cycle through the
colors. For example, the following statements color each vertex and connecting line
one of four colors:
vcolors =[[0,100,200],[200,150,200],[150,200,250],[250,0,100]]
mysurf -> SetProperty, STYLE=1, VERT_COLORS=vcolors
Shading
IDL provides two types of shading for surfaces. In Flat shading, the color of the first
vertex in the surface is used to define the color for the entire surface. The color has a
constant intensity. In Gouraud shading, the colors along each line are interpolated
between vertex colors, and then along scanlines from each of the edge intensities.
Note
By default, only ambient lighting is provided for surfaces. If you do not supply a
light source for your object hierarchy, solid surface objects will appear flat with
either Flat or Gouraud shading. See “Light Objects” on page 633 for details on
creating and using light objects.
Set the SHADING property of the surface object equal to 0 (zero) to use flat shading
(this is the default), or equal to 1 (one) to use Gouraud shading. In the above example
using vertex colors, adding the following statement:
mysurf -> SetProperty, STYLE=2, SHADING=1
creates a surface in which the color values are interpolated between the vertex colors.
Skirts
You can draw a skirt around the bottom edge of your surface object by setting the
SHOW_SKIRT property of the surface object to 1. The skirt extends from the edge of
the surface to a Z value specified by the SKIRT property. For example, the following
statements draw the surface in wire mesh mode, with a skirt extending from the
bottom of the surface to the value z = 0.1:
mysurf -> SetProperty, STYLE=1, /SHOW_SKIRT, SKIRT=0.1
Warning
Hidden line removal can be time-consuming.
Texture Mapping
You can map an image onto a surface object by specifying an IDLgrImage object
to the TEXTURE_MAP property. The TEXTURE_COORD property defines how
individual data points within the image data are mapped to the surface’s vertices. If
the TEXTURE_COORD property is not specified, the surface object will map the
texture onto the entire data space (the region between 0.0 and 1.0 in normalized
coordinates).
Light Objects
Objects of the IDLgrLight class represent sources of illumination for graphic objects.
Although light objects are not rendered themselves, they are part of the model tree
and thus can be transformed along with the graphic objects they illuminate.
If no light sources are specified for a given model, a default ambient light source is
supplied. This allows you to display many objects without explicitly creating a light
source. The use of only ambient light becomes problematic, however, when solid
surfaces and other objects constructed from polygons are displayed. With only
ambient lighting, all solid surfaces appear flat—in fact, they appear to be single two-
dimensional polygons rather than objects in three-dimensional space.
Note
Graphic objects do not automatically cast shadows onto other objects.
There are four types of light objects available. Set the TYPE property of the light
object to one of the following integer values:
• 0 = Ambient light. An ambient light is a universal light source, which has no
direction or position. An ambient light illuminates every surface in the scene
equally, which means that no edges are made visible by contrast. Ambient
lights control the overall brightness and color of the entire scene. If no value is
specified for the TYPE property, an ambient light is created.
• 1 = Positional light. A positional light supplies divergent light rays, and will
make the edges of surfaces visible by contrast if properly positioned. A
positional light source can be located anywhere in the scene.
• 2 = Directional light. A directional light supplies parallel light rays. The effect
is that of a positional light source located at an infinite distance from scene.
• 3 = Spot light. A spot light illuminates only a specific area defined by the
light’s position, direction, and the cone angle, or angle which the spotlight
covers.
See “IDLgrLight” in Appendix A in the IDL Reference Guide for details on creating
light objects.
Note
The SET_VIEW function is discussed in “Finding an Appropriate View Volume”
on page 544.
Begin by creating some data, the surface object, and supporting objects:
zdata = DIST(40)
mywindow = OBJ_NEW('IDLgrWindow')
myview = OBJ_NEW('IDLgrView')
mymodel = OBJ_NEW('IDLgrMODEL')
mysurf = OBJ_NEW('IDLgrSurface', zdata, STYLE=2)
Once the surface object is drawn, we see that there is no definition or apparent three-
dimensional shape to the surface. If we add a positional light one unit in the Z
direction above the XY origin, however, details appear:
mylight = OBJ_NEW('IDLgrLight', TYPE=1, LOCATION=[0,0,1])
mymodel -> Add, mylight
mywindow -> Draw, myview
We can continue to alter the lighting characteristics by changing the properties of the
existing light or by adding more light objects. (You can have up to eight lights in a
given view object.) We can change the color:
mylight -> SetProperty, COLOR=[200,0,200]
mywindow -> Draw, myview
Working with
Images
The following topics are covered in this chapter:
Image Objects
An object of the IDLgrImage class (see IDLgrImage in the IDL Reference Guide)
represents a two-dimensional array of pixel values, rendered on the plane z = 0.
Image objects can have a single channel (one value per pixel—greyscale or color
indexed), two channels (greyscale and Alpha), three channels (Red, Green, and
Blue), or four channels (Red, Green, Blue, and Alpha). The Alpha channel, if present,
determines the transparency of the pixel.
Image objects that have more than one channel can be interleaved either by pixel, by
line, or by image. That is, if the image has three channels, width m and height n, the
image array can be organized 3-by-m-by-n (pixel interleaving), m-by-3-by-n (line, or
scanline interleaving), or m-by-n-by-3 (image, or planar interleaving).
For example, the following statements read a JPEG file located in the IDL
distribution and create an image object from the RGB image. First, locate the
rose.jpg file and read the image data into the variable image:
file = FILEPATH('rose.jpg', SUBDIR=['examples', 'data'])
READ_JPEG, file, image
;Create the objects:
mywindow = OBJ_NEW('IDLgrWindow', DIMENSIONS=[227,149])
myview = OBJ_NEW('IDLgrView', VIEW=[0,0,227,149])
mymodel = OBJ_NEW('IDLgrModel')
myimage = OBJ_NEW('IDLgrImage', image, INTERLEAVE=0)
;Organize the object hierarchy:
myview -> Add, mymodel
mymodel -> Add, myimage
;Draw to the window:
mywindow -> Draw, myview
See IDLgrImage in the IDL Reference Guide for details on creating image objects.
Note
IDLgrImage does not treat NaN data as missing. If the image data includes NaNs, it
is recommended that the BYTSCL function (in the IDL Reference Guide) be used
to appropriately handle those values. For example:
oImage->SetProperty, DATA = BYTSCL(myData, /NaN, MIN=0, MAX=255)
one of the functions listed below for each of the source and destination objects. The
values of the blending function (Vsrc and Vdst) are used in the following equation
where Cd is the initial color of a pixel on the destination device (the background
color), Ci is the color of the pixel in the image, and Cd' is the resulting color of the
pixel.
Setting src and dst in the BLEND_FUNCTION vector to the following values
determine how each term in the equation is calculated:
Interleaving
Set the INTERLEAVE property of the image object to 0 (zero) to indicate that the
image is interleaved by pixel, to 1 (one) to indicated that the image is interleaved by
line, or to 2 to indicate that the image is interleaved by image, or plane. For example,
the following statement changes the image object to use line interleaving:
myimage -> SetProperty, INTERLEAVE=1
Palettes
If your image array contains indexed color data (that is, if it is an m-by-n array), you
can specify a palette object to control the conversion between the image data and the
palette used by an RGB-mode destination object. (See “Using Color” on page 564 for
a discussion of the interaction between indexed color objects and RGB color
destinations.) Set the PALETTE property of the image object equal to an instance of
an IDLgrPalette object:
myimage -> SetProperty, PALETTE = mypalette
To specify that an image be drawn in greyscale mode rather than through an existing
color palette, set the GREYSCALE property equal to 1 (one). The GREYSCALE
property is only used if the image data is a single channel (an m-by-n array).
Note
A 2-by-m-by-n array is considered to be a greyscale image with an Alpha channel.
An image containing indexed color data cannot have an alpha channel.
Colorbar Objects
The IDLgrColorbar object consists of a color-ramp with an optional framing box and
annotation axis. The object can be horizontal or vertical.
See IDLgrColorbar in the IDL Reference Guide for details on creating colorbar
objects. See the next section for a more detailed explanation of the elements of the
legend.
; the window size vertically. Show the axis values (using the
; default axis annotations) and draw an outline around the bar.
mytitle = OBJ_NEW('IDLgrText', 'My Colorbar')
barDims = [0.1, 0.4]
redValues = BINDGEN(256)
greenValues = redValues
blueValues = REVERSE(redValues)
mycolorbar = OBJ_NEW('IDLgrColorbar', redValues, $
greenValues, blueValues, TITLE=mytitle, $
DIMENSIONS=barDims, /SHOW_AXIS, /SHOW_OUTLINE)
mymodel -> Add, mycolorbar
; Center the colorbar in the window.
; Note that you must use the ComputeDimensions method to
; get the dimensions of the colorbar.
barPlusTextDims = mycolorbar -> ComputeDimensions(mywindow)
mymodel -> Translate, -barDims[0]+(barPlusTextDims[0]/2.), $
-barDims[1]+(barPlusTextDims[1]/2.), 0
; Draw the colorbar:
mywindow -> Draw, myview
ENDFOR
; Save the MPEG file:
myMPEG -> Save
Note
Note that imagearray can contain either IDLgrImage objects or simple two-
dimensional image arrays. All of the arrays or image objects must have the same
dimensions.
See IDLgrMPEG in the IDL Reference Guide for details on creating MPEG objects.
Working with
Volumes
This chapter describes the process of creating and displaying volume objects. The following topics
are covered in this chapter:
Volume Objects
A volume object contains a three dimensional data array of voxel values and a set of
rendering attributes. The voxel array is mapped to colors and opacity values through
a set of lookup tables in the volume object. Several rendering methods are provided
to draw the volume to a destination.
The volume contains a shaded prism along with two brighter cubes (one located
within the prism).
See IDLgrVolume in the IDL Reference Guide for details on creating volume objects.
Note
You do not need to enter the example code in this chapter yourself. The example
code shown here is duplicated in the procedure file obj_vol.pro, located in the
examples/visual subdirectory of the IDL distribution. You can run the example
procedure by entering OBJ_VOL at the IDL command prompt. The procedure file
stops after each operation (roughly corresponding to each section below) and
requests that you press return before continuing.
ZCOORD_CONV=cc
; Create a window and view tree:
mywindow = OBJ_NEW('IDLgrWindow', DIMENSIONS=[200,200])
myview = OBJ_NEW('IDLgrView',VIEWPLANE_RECT=[-1,-1,2,2], $
ZCLIP=[2.0,-2.0], COLOR=[50,50,50])
mymodel = OBJ_NEW('IDLgrModel')
myview -> Add, mymodel
mymodel -> Add, myvolume
; Rotate the volume a little and draw it:
mymodel -> rotate, [1,1,1], 45
mywindow -> Draw, myview
Opacity
The opacity table controls the transparency of a given voxel value. Manipulation of
the opacity table is critical to improving the quality of a rendering. The following
example makes the prism transparent and the cubes opaque, allowing the cube within
the prism to be seen, by setting the OPACITY_TABLE0 array to low values for the
prism and high values for the cubes.
opac = BYTARR(256)
opac[0:127] = BINDGEN(128)/8
;Voxel value of one cube:
opac[255] = 255
;Voxel value of the other cube:
opac[128] = 255
myvolume -> SetProperty, OPACITY_TABLE0=opac
mywindow -> Draw, myview
Color
Each voxel value can be assigned an individual color as well. This color mapping can
be changed by changing the RGB_TABLE0 property. To further highlight the cubes,
we change their colors to blue and red, using the following statements:
rgb = bytarr(256,3)
;Grayscale ramp for the prism:
rgb[0:127,0] = bindgen(128)
rgb[0:127,1] = bindgen(128)
rgb[0:127,2] = bindgen(128)
;One cube is red:
rgb[128,*] = [255,0,0]
;One cube is blue:
rgb[255,*] = [0,0,255]
myvolume -> SetProperty, RGB_TABLE0=rgb
mywindow -> Draw, myview
Lighting
Adding lights enhances the edges of volumes. Gradients within the volume are used
to approximate a surface normal for each voxel, and the lights in the current view are
then applied. The gradient shading is enabled by setting the LIGHTING_MODEL
property equal to one. The ambient volume color is selected by setting the
AMBIENT property of the volume object to a color value. Setting the TWO_SIDED
property allows both sides of a voxel to be lighted. An example of this using a light
source follows:
myvolume->SetProperty, AMBIENT=[100,100,100], LIGHTING_MODEL=1, $
TWO_SIDED=1
lmodel = OBJ_NEW('IDLgrModel')
myview -> Add, lmodel
light = OBJ_NEW('IDLgrLight', TYPE=2, LOCATION=[0,0,1], $
COLOR=[255,255,255])
lmodel -> Add, light
mywindow -> Draw, myview
; Disable lighting:
myvolume -> SetProperty, LIGHTING_MODEL=0
Note
Only DIRECTIONAL light sources are honored by the volume object. Because
normals must be computed for all voxels in a lighted view, enabling light sources
increases the rendering time.
Compositing
The volume object supports a number of methods for blending the projected voxels
together to form an image. By default, Alpha blending is used. (In Alpha blending,
each voxel occludes voxels behind it according to the opacity of the voxel in front).
Another common compositing technique is the maximum intensity projection (MIP).
Set the volume object to use MIP compositing by setting the
COMPOSITE_FUNCTION property equal to one. See IDLgrVolume::Init in the IDL
Reference Guide for other options.
myvolume -> SetProperty, COMPOSITE_FUNCTION=1
mywindow -> Draw, myview
ZBuffering
When combining a volume with other geometry in the Object Graphics system,
volume objects should in general be drawn last to ensure they intersect the other
(solid) objects properly. To increase rendering speed, the intersection operation is
disabled by default. To enable the intersection calculations, set the ZBUFFER
property of the volume object equal to one.
myvolume -> SetProperty, ZBUFFER=1
Additionally, volume objects allow for control over the rendering of invisible
(opacity equals zero) voxels. By default, the zbuffer will be updated for such voxels
(even though no change is made in the image color). This writing to the zbuffer by
transparent voxels be disabled by setting the ZERO_OPACITY_SKIP property.
myvolume -> SetProperty, ZERO_OPACITY_SKIP=1
Note
In volumes with large numbers of voxels with their opacity set to zero, enabling
ZERO_OPACITY_SKIP can improve rendering performance.
Interpolation
By default, when rendering a volume object, values between the voxels are estimated
using nearest neighbor sampling. When higher quality rendering is desired, trilinear
interpolation can be selected instead by setting the INTERPOLATE property equal to
one.
myvolume -> SetProperty, INTERPOLATE=1
Note
Trilinear interpolation will cause the rendering to take considerably longer than
nearest neighbor interpolation.
Rendering speed
Rendering speed can be improved by reducing the quality of the rendering. Use the
RENDER_STEP property to control this speed/quality trade-off. The value of the
RENDER_STEP property specifies a step size in the screen dimensions which is
used to skip voxels during the rendering process. Larger values yield faster rendering
times, but lower final image quality. For example, to render only half as many voxels
in the screen Z dimension, use the following statement:
myvolume -> SetProperty, RENDER_STEP=[1,1,2]
A more complex example using a volume object is shown in the volume visualization
demo. To start the demos, type demo at the IDL command prompt.
Selecting Objects
This chapter will describe the IDL Object Graphics selection and direct manipulation features. The
following topics are covered in this chapter:
Selection
With object graphics, the process of selection is very similar to drawing, except that
nothing is displayed on the screen, and information about which objects were
selected is returned to the user. Selection is performed via the Select method of an
IDLgrWindow object.
Three types of objects may be selected: view objects, model objects, and graphic
atoms. For a given scene that contains more than one view, you can use the Select
method to determine which view is selected at a given location. Likewise, for a given
view, you can use the Select method to determine which models and/or graphical
atoms within that view are selected.
An object is considered to be selected if its graphical rendering falls within a box
centered on a given location. The dimensions of the box are set via the
DIMENSIONS keyword to the Select method. Both the location argument and
dimensions keyword values are measured in units specified via the UNITS keyword.
The Select method returns a vector of objects, sorted in depth order (nearest to the
eye is first), that meet the criteria of having been selected at the given location. If no
objects are selected at the given location, the Select method returns –1.
See IDLgrWindow::Select in the IDL Reference Guide for a detailed description of
the Select method.
Selecting Views
To determine which of a set of views within a given scene are selected at a given
location, call the Select method on an IDLgrWindow object with an instance of an
IDLgrScene object as its first argument, and the location at which the selection is to
occur as its second argument:
myLoc = [myMouseEvent.x, myMouseEvent.y]
mySelectedViews = myWindow -> Select(myScene, myLoc)
Note
If a model within the view is set as a selection target, the model object, rather than
its contained graphic atoms, is returned in the vector of selected objects.
Selecting Models
In some cases, a group of graphic atoms may be considered subcomponents of the
model in which they are contained. As a result, you may want to know when a model
object (rather than one or more of its atomic parts) has been selected. To enable
selection of a model (rather than its graphic atoms), the model object must be marked
as a selection target.
To mark a model as being a selection target, set the SELECT_TARGET property of
the model object to a nonzero value.
myWindow = OBJ_NEW('IDLgrWindow')
myView = OBJ_NEW('IDLgrView')
myModel = OBJ_NEW('IDLgrModel')
myView -> Add, myModel
myModel -> SetProperty, /SELECT_TARGET
myAxis = OBJ_NEW('IDLgrAxis', 0)
myModel -> Add, myAxis
myWindow -> Draw, myView
In the above example, if a selection at location [myX, myY] would normally select the
axis object, the returned value of the Select method will be the object reference to
myModel rather than the object reference to myAxis.
A Selection Example
An example procedure named sel_obj.pro is included in the examples/visual
subdirectory of the IDL distribution. This file creates two views, places models
within the views, and provides an interface to let you choose between selecting
models or graphic atoms. A mouse click in one of the views will update a label that
identifies the current selections.
Data Picking
To get the data value that corresponds to a particular window location, use the
PickData method of an IDLgrWindow object. Note that you must draw the view to
the window before calling the PickData method.
myLoc = [myMouseEvent.x, myMouseEvent.y]
result = myWindow -> PickData(myView, myModel, myLoc, returnedXYZ)
The PickData method returns a value that is 0 (zero) if the pick hit the background of
the view, 1 (one) if the pick hit the one of the graphic atoms in the view, or –1 if an
error occurred (for instance, if the pick location lies outside of the given view).
The data value at the pick is returned in the returnedXYZ argument. This value
represents the mapping of the window location to the data space of the model.
Using Destination
Objects
The following topics are covered in this chapter:
Overview
Once a graphic object tree has been created, it can be displayed, or drawn, to a
physical destination device (such as a computer screen or printer), to a memory
location (such as a buffer or the operating system clipboard), or to a particular file
format (such as a VRML file). Destination objects represent the final locations to
which object graphics are drawn, and provide methods that allow you to control the
properties of the physical device, memory buffer, or file format.
Each destination object includes a GetFontnames method, which returns the list of
available fonts that can be used in IDLgrFont objects. This method will only return
the names of the available TrueType fonts. Hershey fonts will not be returned as they
are fixed—see Appendix H, “Fonts” in the IDL Reference Guide for more
information.
There are five destination objects:
1. buffers (IDLgrBuffer objects),
2. clipboards (IDLgrClipboard objects),
3. printers (IDLgrPrinter objects)
4. VRML files (IDLgrVRML objects), and
5. windows (IDLgrWindow objects).
Of the five destination objects, Window objects are the most common and most often
used, and will be addressed first.
Window Objects
Objects of the IDLgrWindow class represent a rectangular area on a computer screen
into which graphics hierarchies can be rendered. Window objects can be either stand-
alone windows on the screen or drawable areas in an IDL draw widget.
Once the draw widget has been realized, you can then retrieve the object reference to
the draw widget’s window object using the WIDGET_CONTROL procedure:
WIDGET_CONTROL, drawwid, GET_VALUE=myWindow
Color Model
By default, window objects use the RGB color model. To create a window that uses
the Indexed color model, set the COLOR_MODEL property of the window object
equal to 1 (one) when creating the window:
myWindow = OBJ_NEW('IDLgrWindow', COLOR_MODEL=1)
You cannot change the color model used by a window after it has been created.
See Chapter 20, “Working with Color” for a discussion of the two color models.
Note
IDL may not be able to provide hardware rendering in all situations and on
particular platforms. The Macintosh and many Unix platforms do not support
hardware rendering and will always use the software rendering system. In cases
where hardware rendering is not available, the setting of the RENDERER property
(and the IDL Development Environment preference) will be quietly ignored.
and the setting of the RENDERER property. Currently, the smallest maximum
drawable area on any IDL platform is 1280-by-1024 pixels; the limit on your system
may be larger.
or
myWindow -> Draw, myScene
All objects contained within the view or scene object will be drawn to the window.
Erasing a Window
To erase the contents of a window, call the IDLgrWindow::Erase method. You can
optionally supply a color to use to clear the window. By default, the window is erased
to white.
For example, to erase the window to black:
myWindow -> Erase, COLOR=[0,0,0]
To hide a window, call the IDLgrWindow::Show method with a zero value as the
argument:
myWindow -> Show, 0
Iconifying a Window
To iconify a window, call the IDLgrWindow::Iconify method with a nonzero value as
its argument:
myWindow -> Iconify, 1
ARROW CROSSHAIR
ICON IBEAM
MOVE ORIGINAL
SIZE_NE SIZE_NW
SIZE_SE SIZE_SW
SIZE_NS SIZE_EW
UP_ARROW
The ORIGINAL cursor sets the cursor to the window system’s default cursor.
See IDLgrWindow::SetCurrentCursor in the IDL Reference Guide for details on
cursor values.
Saving/Restoring Windows
When an instance of an IDLgrWindow object is restored via the RESTORE
procedure), it is not immediately displayed on the screen. It will be displayed as soon
as one of its methods (Draw, Erase, Iconify, etc.) is called.
Instancing
For interactive graphics, where views are drawn repeatedly over time, it is often the
case that one small part of the view is changing continuously, but the other objects in
the view remain static. In such a case, it may be more efficient to take a snapshot of
the unchanged portion of the view and display the snapshot for each draw instead of
re-rendering each of the unchanging objects from scratch. The objects that are
changing are rendered as usual. This process is called instancing. It is to your
advantage to use instancing only in cases where displaying the snapshot image is
faster than rendering each of the objects that remain unchanged.
The following example shows how a typical instancing loop would be set up. First,
hide the objects in the view that will be changing. In this example, we assume that the
objects that change continuously are contained by a single model object, with the
object reference myChangingModel. We set the HIDE property for this model to
remove it from the rendered view.
myChangingModel -> SetProperty, HIDE=1
Buffer Objects
Objects of the IDLgrBuffer class represent a memory buffer into which graphics
hierarchies can be rendered. Object trees can be drawn to instances of the
IDLgrBuffer object and the resulting image can be retrieved from the buffer using the
Read() method. The off-screen representation avoids dithering artifacts by providing
a full-resolution buffer for objects using either the RGB or Color Index color models.
Clipboard Objects
Objects of the IDLgrClipboard class will send Object Graphics output to the
operating system native clipboard in bitmap format. The format of bitmaps sent to the
clipboard is operating system dependent: output is stored as a PICT image on the
Macintosh, as a device-independent bitmap under Windows, and as an Encapsulated
PostScript (EPS) image under Unix and VMS.
Printer Objects
Objects of the IDLgrPrinter class represent a physical printer onto which graphics
hierarchies can be rendered.
This creates an object that maintains information about the printer. By default, this
information pertains to the default printer installed for your system. To select a
different printer or setup attributes of the printer, use the printer dialogs described in
the next section.
See IDLgrPrinter in the IDL Reference Guide for details on creating printer objects.
Color Model
By default, printer objects use the RGB color model. To create a printer that uses the
Indexed color model, set the COLOR_MODEL property of the printer object equal to
1 (one) when creating the printer:
myWindow = OBJ_NEW('IDLgrPrinter', COLOR_MODEL=1)
You cannot change the color model used by a printer after it has been created.
See Chapter 20, “Working with Color” for a discussion of the two color models.
Printer Dialogs
IDL includes two functions useful for controlling printers and printjobs.
DIALOG_PRINTERSETUP
Call the DIALOG_PRINTERSETUP function with the object reference of a printer
object as its argument to open an operating system native dialog for setting the
applicable properties of a particular printer. DIALOG_PRINTERSETUP returns a
nonzero value if the user pressed the OK button in the dialog, or zero otherwise.
result = DIALOG_PRINTERSETUP(myPrinter)
DIALOG_PRINTJOB
Call the DIALOG_PRINTJOB function with the object reference of a printer object
as its argument to open an operating system native dialog to initiate a printing job.
DIALOG_PRINTJOB returns a nonzero value if the user pressed the OK button in
the dialog, or zero otherwise.
result = DIALOG_PRINTJOB(myPrinter)
Drawing to a Printer
To draw a graphics tree to a printer, call the IDLgrPrinter::Draw method. The
argument must be either an IDLgrView object or an IDLgrScene object.
myPrinter -> Draw, myView
or
myPrinter -> Draw, myScene
All objects contained within the scene or view will be drawn to the printer.
Note
The scene or view to be drawn may be the same as the scene or view being
displayed in one or more windows.
Note
The IDLgrPrinter::Draw method has keywords that allow you to send the image as
a bitmap or vector format. For more information, see IDLgrPrinter::Draw in the
IDL Reference Guide.
VRML Objects
Objects of the IDLgrVRML class allow you to save the contents of an Object
Graphics hierarchy into a VRML 2.0 format file. The graphics tree can only contain a
single view due to limitations in the VRML specification. The resulting VRML file is
interactive and allows you to explore the geometry interactively using a VRML
browser.
This creates an object that will convert object hierarchies rendered to it into VRML
format files.
See IDLgrVRML in the IDL Reference Guide for details on creating and using
VRML objects.
Subclassing from
Object Graphics
This chapter describes the creation of composite classes or subclasses in Object Graphics. The
following topic is covered in this chapter:
You may also find that you want to customize one or more of the classes available in
Object Graphics. For instance, you may want to create a specialized image object that
can handle 16-bit palettes. An example of this is provided in
idlexpalimage_ _define.pro in the examples/visual/utility
subdirectory of the IDL distribution.
Performance Tuning
Object Graphics
The following topics are covered in this chapter:
Overview
The Object Graphics subsystem is designed to provide a rich set of graphical
functionality that can be displayed in reasonable time. This section offers suggestions
on how to utilize the object graphics in such a way as to take full advantage of
performance enhancement benefits.
Quad Strips
A quad strip is a connected set of four-sided polygons (see “Polygon Mesh
Optimization” in Chapter 23). To take advantage of accelerated quad strips, the
connectivity should be set up so that the first and last vertex for one quad are the
same as the second and third of the previous quad.
0 1 2 3
4 5 6 7
8 9 10 11
For example, to use a quad strip optimization for the polygons in the figure above, the
connectivity for the vertices should be as follows:
verts = [v0, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10 ,v11]
oPoly = OBJ_NEW('IDLgrPolygon', verts, $
POLYGON=[4, 0, 1, 5, 4, $
4, 1, 2 ,6, 5, $
4, 2, 3, 7, 6, $
4, 4, 5, 9, 8, $
4, 5, 6, 10, 9, $
4, 6, 7, 11, 10])
Triangle Fans
A triangle fan mesh is a set of connected triangles that all share a common vertex. To
take advantage of accelerated triangle fans, the connectivity should be set up so that
the first vertex in every triangle is the common vertex, and the second vertex is the
same as the last vertex of the previous triangle.
For example, to use a triangle fan optimization for the polygons in the left-hand
figure below, the connectivity for the vertices should be as follows:
verts = [v0, v1, v2, v3, v4, v5]
oPoly = OBJ_NEW('IDLgrPolygon', verts, $
POLYGON=[3, 0, 1, 2, $
3, 0, 2, 3, $
3, 0, 3, 4, $
3, 0, 4, 5])
2 3 4 0 2 4
1 0 5 1 3 5
Figure 30-2: Triangle Fan Mesh (left) and Triangle Strip Mesh (right)
Triangle Strips
A triangle strip mesh is a set of connected triangles, each of which share two vertices
with the previous triangle. To take advantage of accelerated triangle strips, the
connectivity should be set up so that the first two vertices in every triangle must have
been in the previous triangle and ordered in the same direction (counter-clockwise or
clockwise) and the final vertex must be new.
For example, to use the triangle strip optimization for the polygons in the right-hand
figure above, the connectivity for the vertices should be as follows:
verts = [v0, v1, v2, v3, v4, v5]
oPoly = OBJ_NEW('IDLgrPolygon', verts, $
POLYGON=[3, 0, 1, 2, $
3, 2, 1, 3, $
3, 2, 3, 4, $
3, 4, 3, 5])
No limits are imposed on the number of meshes or types of meshes within any given
polygon object. A single POLYGON keyword value might contain any combination
of quad strips, triangle strips, triangle fans, or non-specialized polygons.
As the length of the strips or fans grows, and as the percentage of vertex connections
that are optimized by the rules described above increases, the performance upgrade
becomes more perceptible. The optimizations are a result of minimizing the time
required to perform vertex transforms. If the drawing of the polygons are otherwise
limited by fill-rate (as might occur on some systems if texture-mapping is being
applied, for instance), these optimizations may not be of significant benefit. In any
case, performance will not be hindered in any way by utilizing these specialized
meshes, so it is suggested that they be applied whenever possible.
Note
The IDLgrSurface object always takes advantage of the quad mesh optimization
automatically without programmer intervention.
Normal Computations
For IDLgrPolygon objects, normal vectors are computed by default at each vertex by
averaging the normals of the polygons that share that vertex. These normals are then
used to compute illumination intensities across the surface of the polygon.
Computing default normals is a computationally expensive operation. Each time the
polygon is drawn, this computation will be repeated if the polygon has changed
significantly enough to warrant a new internal cache (for example, if the connectivity,
vertices, shading, or style have changed). In some cases, the normals do not actually
change as other modifications are made. In these cases, the expense of default normal
computation can be bypassed if the user provides the normals explicitly (via the
NORMALS keyword). These normals can be computed by using the
COMPUTE_MESH_NORMALS routine in the IDL Reference Guide. The resulting
normals, if passed in via the NORMALS keyword of the IDLgrPolygon object, will
be reused every time the polygon is drawn (without further computation) until they
are replaced explicitly by the user.
Back-face Culling
For polygonal meshes that describe a closed shape (for example, a sphere), it is often
wasteful to spend any time rendering the polygons whose normal vector faces away
from the eye because it is known that the polygons whose normals face toward the
eye will obscure those back-facing polygons. Therefore, for efficiency, it may be
beneficial to employ back-face culling, which is simply the process of choosing to
skip the rasterization of any polygons whose normal vector faces away from the eye.
On an IDLgrPolygon object, set the REJECT property to a value of 1 to enable
back-face culling.
Lighting
Lighting computations are generally set up to compute the light intensity based on the
normal vector for the polygon. If the polygon normal faces away from the eye, the
lighting model will likely determine that the light intensity for that polygon is zero.
When the polygonal mesh being rendered is a closed surface, this is not a problem
because the back-facing polygons will always be obscured. However, when the
polygon mesh represents an open shape (for which back-facing polygons may be
visible), the dark appearance of these polygons may hinder the user’s perception of
the overall shape. In such a case, two-sided lighting can be useful. Two-sided lighting
is the process of reversing the normals for all back-facing polygons before computing
the light intensities for that polygon.
In IDL’s Object Graphics, two-sided lighting is enabled by default. When the
additional lighting calculation is not required, one-sided lighting can be used to
improve rendering performance. On an IDLgrModel object, set the LIGHTING
property to a value of 1 to enable one-sided lighting.
IDL_DEVICE, 30 files
IDL_DIR, 30 filenames
IDL_DLM_PATH, 30 Macintosh platform, 186
IDL_HELP_PATH, 31 Windows platform, 98
IDL_PATH, 31 Message-of-the-Day
IDL_STARTUP, 31, 58 Macintosh platform, 184
IDL_TMPDIR, 31 Windows platform, 97
LM_LICENSE_FILE, 32 MPEG, 646
PATH, 24 pointer position
path expansion, 33 Windows platform, 99
TERM, 32 restoring
UNIX platform, 31 Windows platform, 99
used by IDL, 30 saving
VMS logical names, 32 Windows platform, 99
equal-area map projection, 370 saving images, 646
erasing a window object, 670 specifying search path
error Macintosh platform, 183
floating-point, 444 Motif platform, 133
mathematical error assessment, 445 Windows platform, 95
rounding, 444 filling contours, 318
truncation, 445 filling polygons, 271, 611
error handling on Macintosh, 188 filters
executive commands, 38 autoregressive moving average, 427
exiting IDL, 29 bandpass, 428
expose events, 691 bandstop, 428
exposing window objects, 670 boxcar, 432
eye position, 541 digital, 427
FIR, 427
highpass, 428
F IIR filter, 427
Kaiser’s window, 428
far clipping plane, 543
lowpass, 428
Fast Fourier transform, 409
moving average, 427
implementation, 421
notch, 434
FFT, 409, 416
rectangular, 432
Cooley-Tukey algorithm, 421
finding text
implementation, 421
IDLDE
file selection
Windows platform, 74
using compound widgets, 228
Macintosh platform, 166
using dialogs, 226
Motif platform, 111
finite Windows, 68
impulse response filters, 427 coordinate systems, 256, 323
FIR filter, 427 data picking, 658
fixed pixels, 314 device independent graphics, 252, 505
flashing color maps, 136 devices, 251
floating-point accuracy, 444 devices for Direct Graphics, 504
font object, 515, 571 driver information (Windows), 98
FONT property of text objects, 606 IDLDE windows
fonts backing store for Windows, 91
default, 571, 606 changing Windows preferences, 90
hardware, 266 layout in Windows platform, 90
Hershey, 572 OS clipboard support
selecting, 266 Windows, 68
specifying modes, 250, 504
Macintosh platform, 176, 180 object-oriented, 252, 505
Motif platform, 132 selecting, 658
Windows platform, 95 two-dimensional arrays, 304
TrueType, 571 graphics hierarchy, 524
type size, 606 graphics object tree, 524
type style, 606 graphics windows
Fourier transform backing store for Macintosh, 178
discrete, 409 backing store for Motif, 129
Fourier transforms changing Macintosh preferences, 178
fast, 409 layout in Motif platform, 106
frequency plot leakage, 414 layout on Macintosh platform, 178
frequency plot smearing, 414 layout on Motif platform, 128
frequency response function, 435 OS clipboard support on Macintosh, 162
graphs, 607
graticule, 351
G gridding
data extrapolation, 463
Gaussian
Delaunay triangulation, 463
iterated quadrature, 468
drawing meridians, 350
Gauss-Krueger map projection, 367
routines, 463
general perspective map projection, 362
uniformly-spaced planar data, 463
gnomic map projection, 358
gridding plots, 275
gnomonic map projection, 358
Gouraud shading, 339
grade, 319
graphics
H
atoms, 512, 529 Hammer-Aitoff map projection, 361
clipboard support Hamming window, 418