PDL/Graphics/PGPLOT/Window.pm untested

filter: Statementstmt 0.0% 0 / 2175 Branchbran 0.0% 0 / 1188 Conditioncond 0.0% 0 / 415 MC/DCmcdc 0.0% 0 / 244 Subroutinesub 0.0% 0 / 105 Podpod 0.0% 0 / 88 totaltotal 0.0% 0 / 4215 CC 594 SCAR 63.6
CC
594
Cov
0%
initenv
3192.0
lines
1560.0
errb
992.0
CRAP 576.3
1 package PDL::Graphics::PGPLOT::Window;
2 use strict;
3 use warnings;
4 require Exporter;
5  
6 use PDL::Core qw/:Func :Internal/; # Grab the Core names
7 use PDL::Basic;
8 use PDL::Ufunc;
9 use PDL::Primitive;
10 use PDL::Types;
11 use PDL::Options;
12 use PDL::Graphics::State;
13 use PDL::Graphics::PGPLOTOptions qw(default_options);
14 use PDL::Slices;
15 use PGPLOT;
16  
17 require DynaLoader;
18  
19 our @ISA = qw( Exporter );
20 our @EXPORT = qw( pgwin );
21  
22 $PDL::Graphics::PGPLOT::RECORDING = 0; # By default recording is off..
23  
24 =head1 NAME
25  
26 PDL::Graphics::PGPLOT::Window - A OO interface to PGPLOT windows
27  
28 =head1 SYNOPSIS
29  
30 pdl> use PDL::Graphics::PGPLOT::Window
31 pdl> $win = pgwin(Device => '/xs');
32 pdl> $x = pdl [1..100]
33 pdl> $y = sqrt($x)
34 pdl> $win->line($y)
35 pdl> $win->hold()
36 pdl> $c = sin($x/10)*2 + 4
37 pdl> $win->line($c)
38  
39 In the following documentation the commands are not shown in their OO
40 versions. This is for historical reasons and should not cause too much
41 trouble.
42  
43 =head1 DESCRIPTION
44  
45 This package offers a OO interface to the PGPLOT plotting package. This
46 is intended to replace the traditional interface in
47 L<PDL::Graphics::PGPLOT>
48 and contains interfaces to a large number of PGPLOT routines. Below the
49 usage examples for each function tend to be given in the non-OO version for
50 historical reasons. This will slowly be changed, but in the meantime refer
51 to the section on OO-interface below to see how to convert the usage
52 information below to OO usage (it is totally trivial).
53  
54 PDL::Graphics::PGPLOT::Window is an interface to the PGPLOT graphical
55 libraries. It currently supports PGPLOT-5.2 and PGPLOT-5.2-cd2. The
56 -cd2 version includes RGB output and anti-aliasing.
57  
58 High-level plotting commands:
59  
60 imag - Display an image (uses pgimag/pggray/pgrgbi as appropriate)
61 fits_imag - Display a FITS image in scientific coordinates
62 cont - Display image as contour map
63 fits_cont - Display a FITS image in scientific coordinates as a contour map
64 vect - Display 2 images as a vector field
65 fits_vect - Display 2 FITS images in sci. coordinates as a vector field
66 ctab - Load an image colour table
67 ctab_info - Get information about currently loaded colour table
68 line - Plot vector as connected points
69 tline - Plot a collection of vectors as lines
70 lines - Plot a polyline, multicolor vector [broadcastable]
71 points - Plot vector as points
72 tpoints - Plot a collection of vectors as points [broadcastable]
73 errb - Plot error bars
74 bin - Plot vector as histogram (e.g. bin(hist($data)) )
75 hi2d - Plot image as 2d histogram (not very good IMHO...)
76 tcircle - Plot vectors as circles [broadcastable]
77 label_axes - Print axis titles
78 legend - Create a legend with different texts, linestyles etc.
79  
80 Low-level plotting commands:
81  
82 arrow - Draw an arrow
83 poly - Draw a polygon
84 rectangle - Draw a rectangle
85 text - Write text in the plot area
86 cursor - Interactively read cursor positions.
87 circle - Draw a circle
88 ellipse - Draw an ellipse.
89  
90 Device manipulation commands:
91  
92 new - Construct a new output device
93 pgwin - Exported hook to new()
94 close - Close a PGPLOT output device.
95 hold - Hold current plot window range - allows overlays etc.
96 release - Release back to freshly autoscaling for each command.
97 held - Indicates whether the current window is held.
98 focus - Set focus to the given device.
99 erase - Erase the current window (or panel).
100 options - Get the options set for the present output device.
101 id - The ID for the device.
102 device - The device type.
103 name - The window name.
104  
105 Notes: C<$transform> for image/cont etc. is used in the same way as the
106 C<TR()> array in the underlying PGPLOT FORTRAN routine but is, fortunately,
107 zero-offset. The L<transform()|/transform> routine can be used to create this ndarray.
108  
109 For completeness: The transformation array connect the pixel index to a
110 world coordinate such that:
111  
112 X = tr[0] + tr[1]*i + tr[2]*j
113 Y = tr[3] + tr[4]*i + tr[5]*j
114  
115 =head2 Variable passing and extensions
116  
117 In general variables are passed to the pgplot routines by using
118 C<get_dataref>
119 to get the reference to the values. Before passing to pgplot routines
120 however, the data are checked to see if they are in accordance with the
121 format (typically dimensionality) required by the PGPLOT routines.
122 This is done using the routine C<checkarg> (internal to PGPLOT). This routine
123 checks the dimensionality of the input data. If there are superfluous
124 dimensions of size 1 they will be trimmed away until the dimensionality
125 is correct. Example:
126  
127 Assume an ndarray with dimensions (1,100,1,1) is passed to C<line>, which
128 expects its inputs to be vectors. C<checkarg> will then return an ndarray
129 with dimensions (100). If instead the same ndarray was passed to C<imag>,
130 which requires 2D ndarrays as output, C<checkarg> would return an ndarray
131 with dimensionality (100, 1) (Dimensions are removed from the I<start>)
132  
133 Thus, if you want to provide support for another PGPLOT function, the
134 structure currently look like this (there are plans to use the Options
135 package to simplify the options parsing):
136  
137 # Extract the hash(es) on the commandline
138 ($arg, $opt)=_extract_hash(@_);
139 <Check the number of input parameters>
140 <deal with $arg>
141 checkarg($x, 3); # For a hypothetical 3D routine.
142 catch_signals {
143 ...
144 pgcube($n, $x->get_dataref);
145 };
146 1;
147  
148 (the catch_signals block prevents problems with the perl-PGPLOT
149 interface if the user hits Ctrl-C during an operation).
150  
151 =head2 Setting options
152  
153 All routines in this package take a hash with options as an optional
154 input. This options hash can be used to set parameters for the
155 subsequent plotting without going via the PGPLOT commands.
156  
157 This is implemented such that the plotting settings (such as line width,
158 line style etc.) are affected only for that plot, any global changes made,
159 say, with C<pgslw()> are preserved. Some modifications apply when using
160 the OO interface, see below.
161  
162 =head2 Alphabetical listing of standard options
163  
164 The following options are always parsed. Whether they have any importance
165 depend on the routine invoked - e.g. line style is irrelevant for C<imag>,
166 or the C<justify> option is irrelevant if the display is on 'hold'.
167 This is indicated in the help text for the commands below.
168  
169 The options are not case sensitive and will match for unique substrings,
170 but this is not encouraged as obscure options might invalidate what
171 you thought was a unique substring.
172  
173 In the listing below examples are given of each option. The actual
174 option can then be used in a plot command by specifying it as an argument
175 to the function wanted (it can be placed anywhere in the command list).
176  
177 E.g:
178  
179 $opt={COLOR=>2};
180 line $x, $y, $opt; # This will plot a line with red color
181  
182 If you are plotting to a hardcopy device then a number of
183 options use a different name:
184  
185 HardLW instead of LineWidth
186 HardCH instead of CharSize
187 HardFont instead of Font
188  
189 HardAxisColour instead of AxisColour
190 HardColour instead of Colour
191  
192 [although I'm not sure when HardColour is actually used]
193  
194 =over 4
195  
196 =item align
197  
198 If C<pix> is set, then images and plots are not stretched to fill the plot
199 area. the C<align> string tells how to align them within the available
200 area. 'L' and 'R' shove the plot against the left and right edges,
201 respectively; 'B' and 'T' shove the plot against the bottom and top
202 edges. The default is to center the image. e.g. 'BL' puts the image
203 on the bottom left corner, while 'CT' centers the image horizontally
204 while placing it at the top of the available plot area. This defaults
205 to 'BT' for non-justified images, to 'CC' for justified images.
206  
207 =item arrow
208  
209 This options allows you to set the arrow shape, and optionally size for
210 arrows for the vect routine. The arrow shape is specified as a hash
211 with the key FS to set fill style, ANGLE to set the opening angle of
212 the arrow head, VENT to set how much of the arrow head is cut out and
213 SIZE to set the arrowsize.
214  
215 The following
216  
217 $opt = {ARROW => {FS=>1, ANGLE=>60, VENT=>0.3, SIZE=>5}};
218  
219 will make a broad arrow of five times the normal size.
220  
221 Alternatively the arrow can be specified as a set of numbers
222 corresponding to an extension to the syntax for pgsah. The equivalent to
223 the above is
224  
225 $opt = {ARROW => pdl([1, 60, 0.3, 5})};
226  
227 For the latter the arguments must be in the given order, and if any are
228 not given the default values of 1, 45, 0.3 and 1.0 respectively will
229 be used.
230  
231 =item arrowsize
232  
233 The arrowsize can be specified separately using this option to the
234 options hash. It is useful if an arrowstyle has been set up and one
235 wants to plot the same arrow with several sizes. Please note that it is
236 B<not> possible to set arrowsize and character size in the same call to
237 a plotting function. This should not be a problem in most cases.
238  
239 $opt = {ARROWSIZE => 2.5};
240  
241 =item axis
242  
243 Set the axis value (see L</env>). If you pass in a scalar you set the
244 axis for the whole plot. You can also pass in an array ref for finer
245 control of the axes.
246  
247 If you set the option to a scalar value, you get one of a few standard layouts.
248 You can specify them by name or by number:
249  
250 EMPTY (-2) draw no box, axes or labels
251 BOX (-1) draw box only
252 NORMAL (0) draw box and label it with coordinates
253 AXES (1) same as NORMAL, but also draw (X=0,Y=0) axes
254 GRID (2) same as AXES, but also draw grid lines
255 LOGX (10) draw box and label X-axis logarithmically
256 LOGY (20) draw box and label Y-axis logarithmically
257 LOGXY (30) draw box and label both axes logarithmically
258  
259 When using logarithmic axes (C<LOGX>, C<LOGY> and C<LOGXY>) you normally
260 need to log the data yourself, e.g.
261  
262 line $x->log10, $y, {axis=>'LOGX'};
263  
264 For your convenience you can put PDL::Graphics::PGPLOT into
265 autolog mode. In this mode a call to C<line> or C<points>
266 will log the data for you and you can pass in the unmodified
267 data, e.g.
268  
269 autolog(1); # enable automatic logarithm calculation
270 line $x, $y, {axis=>'LOGX'}; # automatically displays logged x data
271  
272 You can use the function interface to enable autologging:
273  
274 autolog(1);
275  
276 or use it with a window reference (mode switching on a per window basis)
277  
278 $win->autolog(1);
279  
280 C<autolog> without arguments returns the current autolog setting (0=off,
281 1=on).
282  
283 If you set the C<AXIS> option to an array ref, then you can specify the
284 box/axis options separately for the horizontal (ordinate; X
285 coordinate; 0th element) and vertical (abscissa; Y coordinate; 1st element))
286 axes. Each element of the array ref should contain a PGPLOT format string.
287 Presence or absence of specific characters flags particular options. For
288 normal numeric labels, the options are:
289  
290 A : draw axis for this dimension.
291 B : draw bottom (X) or left (Y) edge of frame.
292 C : draw top (X) or right (Y) edge of frame.
293 G : draw Grid of vertical (X) or horizontal (Y) lines.
294 I : Invert ticks: draw them outside the plot rather than inside.
295 L : Label the axis Logarithmically.
296 P : Extend ("Project") major tick marks outside the box.
297 M : Numeric labels go in the alternate place above (X) or to the
298 right (Y) of the viewport.
299 N : Numeric labels go in the usual location below (X) or to the
300 left (Y) of the viewport
301 T : Draw major tick marks at the major coordinate interval.
302 S : Draw minor tick marks (subticks).
303 V : Orient numeric labels Vertically. Only applicable to Y.
304 (The default is to write them parallel to the axis.)
305 1 : Force decimal labelling, instead of automatic choice
306 2 : Force exponential labeling, instead of automatic.
307  
308 If you don't specify any axis value at all, the default is ['BCNST','BCNST']
309 for plots and ['BCINST','BCINST'] for images. (These list ref elements are
310 handed on directly to the low-level PGPLOT routines).
311  
312 In addition, you can specify that your axis labels should be printed
313 as days, hours, minutes, and seconds (ideal for julian dates and delta-t,
314 or for angular quantities). You do that by setting additional character
315 flags on the affected axis:
316  
317 X : Use HH MM SS.S time labeling rather than conventional numeric
318 labels. The ordinate is in secsonds. Hours roll over at 24.
319 Y : Like 'X' but the hour field runs past 24 if necessary.
320 Z : Like 'X' but with a days field too (only shown where nonzero).
321 H : Label the numbers with superscript d, h, m, and s symbols.
322 D : Label the numbers with superscript o, ', and '' symbols.
323 F : Omit first (lowest/leftmost) label; useful for tight layouts.
324 O : Omit leading zeroes in numbers under 10 (e.g. " 3h 3m 1.2s"
325 rather than "03h 03m 01.2s").
326  
327 For example, to plot a numeric quantity versus Julian day of the year
328 in a standard boxed plot with tick marks, you can use ["BNCSTZHO","BCNST"].
329  
330 =item border
331  
332 Normally the limits are
333 chosen so that the plot just fits; with this option you can increase
334 (or decrease) the limits by either a relative
335 (ie a fraction of the original axis width) or an absolute amount.
336 Either specify a hash array, where the keys are C<TYPE> (set to
337 'relative' or 'absolute') and C<VALUE> (the amount to change the limits
338 by), or set to 1, which is equivalent to
339  
340 BORDER => { TYPE => 'rel', VALUE => 0.05 }
341  
342 =item charsize
343  
344 Set the character/symbol size as a multiple of the standard size.
345  
346 $opt = {CHARSIZE => 1.5}
347  
348 The HardCH option should be used if you are plotting to a hardcopy device.
349  
350 =item colour (or color)
351  
352 Set the colour to be used for the subsequent plotting. This can be
353 specified as a number, and the most used colours can also be specified
354 with name, according to the following table (note that this only works for
355 the default colour map):
356  
357 0 - WHITE 1 - BLACK 2 - RED 3 - GREEN 4 - BLUE
358 5 - CYAN 6 - MAGENTA 7 - YELLOW 8 - ORANGE 14 - DARKGRAY
359 16 - LIGHTGRAY
360  
361 However there is a much more flexible mechanism to deal with colour.
362 The colour can be set as a 3 or 4 element anonymous array (or ndarray)
363 which gives the RGB colours. If the array has four elements the first
364 element is taken to be the colour index to change. For normal work you
365 might want to simply use a 3 element array with R, G and B values and
366 let the package deal with the details. The R,G and B values go from 0
367 to 1.
368  
369 In addition the package will also try to interpret non-recognised
370 colour names using the default X11 lookup table, normally using the
371 C<rgb.txt> that came with PGPLOT.
372  
373 For more details on the handling of colour it is best that the user
374 consults the PGPLOT documentation. Further details on the handling of
375 colour can be found in the documentation for the internal routine
376 L</_set_colour>.
377  
378 The HardColour option should be used if you are plotting to a hardcopy device
379 [this may be untrue?].
380  
381 =item diraxis
382  
383 This sets the direction of the axes of a plot or image, when you don't explicitly
384 set them with the XRange and YRange options. It's particularly useful when
385 you want (for example) to put long wavelengths (larger numbers) on the left
386 hand side of your plot, or when you want to plot an image in (RA,dec)
387 coordinates.
388  
389 You can use either a scalar or a two-element perl array. If you set it to
390 0 (the default) then PDL will guess which direction you want to go. If you
391 set it to a positive number, the axis will always increase to the right. If
392 you set it to a negative number, the axis will always increase to the left.
393  
394 For example, [0,0] is the default, which is usually right. [1,1] tells
395 PGPLOT to always increase the axis values up and to the right. For a
396 plot of intensity (y-axis) versus wavelength (x-axis) you could say
397 [-1,1].
398  
399 This option is really only useful if you want to allow autoranging but
400 need to set the direction that the axis goes. If you use the ranging
401 options (C<XRange> and C<YRange>), you can change the direction by changing
402 the order of the maximum and minimum values. That direction will
403 override C<DirAxis>.
404  
405 =item filltype
406  
407 Set the fill type to be used by L</poly>, L</circle>,
408 L</ellipse>, and L</rectangle>
409 The fill can either be specified using numbers or name, according to the
410 following table, where the recognised name is shown in capitals - it is
411 case-insensitive, but the whole name must be specified.
412  
413 1 - SOLID
414 2 - OUTLINE
415 3 - HATCHED
416 4 - CROSS_HATCHED
417  
418 $opt = {FILLTYPE => 'SOLID'};
419  
420 (see below for an example of hatched fill)
421  
422 =item font
423  
424 Set the character font. This can either be specified as a number following
425 the PGPLOT numbering or name as follows (name in capitals):
426  
427 1 - NORMAL
428 2 - ROMAN
429 3 - ITALIC
430 4 - SCRIPT
431  
432 (Note that in a string, the font can be changed using the escape sequences
433 C<\fn>, C<\fr>, C<\fi> and C<\fs> respectively)
434  
435 $opt = {FONT => 'ROMAN'};
436  
437 gives the same result as
438  
439 $opt = {FONT => 2};
440  
441 The HardFont option should be used if you are plotting to a hardcopy device.
442  
443 =item hatching
444  
445 Set the hatching to be used if either fillstyle 3 or 4 is selected
446 (see above) The specification is similar to the one for specifying
447 arrows. The arguments for the hatching is either given using a hash
448 with the key ANGLE to set the angle that the hatch lines will make
449 with the horizontal, SEPARATION to set the spacing of the hatch lines
450 in units of 1% of C<min(height, width)> of the view surface, and PHASE to
451 set the offset the hatching. Alternatively this can be specified as a
452 1x3 ndarray C<$hatch=pdl[$angle, $sep, $phase]>.
453  
454 $opt = {FILLTYPE => 'HATCHED',
455 HATCHING => {ANGLE=>30, SEPARATION=>4}};
456  
457 Can also be specified as
458  
459 $opt = {FILL=> 'HATCHED', HATCH => pdl [30,4,0.0]};
460  
461 For another example of hatching, see L</poly>.
462  
463 =item justify
464  
465 If C<justify> is set true, then the plot axes are shrunk to fit
466 the plot or image and it specifies the aspect ratio of pixel
467 coordinates in the plot or image. Setting justify=>1 will
468 produce a correct-aspect-ratio, shrink-wrapped image or plot;
469 setting justify=>0.5 will do the same thing but with a short and
470 fat plot. The difference between C<justify> and C<pix> is that
471 C<pix> does not affect the shape of the axes themselves.
472  
473 =item linestyle
474  
475 Set the line style. This can either be specified as a number following
476 the PGPLOT numbering:
477  
478 1 - SOLID line
479 2 - DASHED
480 3 - DOT-DASH-dot-dash
481 4 - DOTTED
482 5 - DASH-DOT-DOT-dot
483  
484 or using name (as given in capitals above).
485 Thus the following two specifications both specify the line to be dotted:
486  
487 $opt = {LINESTYLE => 4};
488 $varopt = {LINESTYLE => 'DOTTED'};
489  
490 The names are not case sensitive, but the full name is required.
491  
492 =item linewidth
493  
494 Set the line width. It is specified as a integer multiple of 0.13 mm.
495  
496 $opt = {LINEWIDTH => 10}; # A rather fat line
497  
498 The HardLW option should be used if you are plotting to a hardcopy device.
499  
500 =item pitch
501  
502 Sets the number of data pixels per inch on the output device.
503 You can set the C<unit> (see below) to change this to any other
504 PGPLOT unit (millimeters, pixels, etc.). Pitch is device independent,
505 so an image should appear exactly the same size (e.g. C<Pitch=E<gt>100>
506 is 100 dpi) regardless of output device.
507  
508 =item pix
509  
510 Sets the pixel aspect ratio height/width. The height is adjusted
511 to the correct ratio, while maintaining any otherwise-set pitch or scale
512 in the horizontal direction. Larger numbers yield tall, skinny pixels;
513 smaller numbers yield short, fat pixels.
514  
515 =item scale
516  
517 Sets the number of output display pixels per data pixel. You can set
518 the C<unit> (see below) to change this to number of PGPLOT units
519 (inches, millimeters, etc.) per data pixel. C<scale> is deprecated,
520 as it is not device-independent; but it does come in handy for quick
521 work on digital displays, where aliasing might otherwise interfere
522 with image interpretation. For example, C<scale=E<gt>1> displays
523 images at their native resolution.
524  
525 =item Panel
526  
527 It is possible to define multiple plot ``panels'' with in a single
528 window (see the L<NXPanel and NYPanel options in the
529 constructor|/new>). You can explicitly set
530 in which panel most plotting commands occur, by passing either a
531 scalar or an array ref into the C<Panel> option. There is also a
532 L<panel|PDL::Graphics::PGPLOT/panel> method, but its use is deprecated
533 because of a wart with the PGPLOT interface.
534  
535 =item plotting & imaging range
536  
537 Explicitly set the plot range in x and y. X-range and Y-range are set
538 separately via the aptly named options C<XRange> and C<YRange>. If omitted
539 PGPLOT selects appropriate defaults (minimum and maximum of the data range
540 in general). These options are ignored if the window is on hold.
541  
542 line $x, $y, {xr => [0,5]}; # y-range uses default
543 line $x, $y, {XRange => [0,5], YRange => [-1,3]}; # fully specified range
544 imag $im, {XRange => [30,50], YRange=>[-10,30]};
545 fits_imag $im, {XRange=>[-2,2], YRange=>[0,1]};
546  
547 Imaging requires some thought if you don't want to lose a pixel off
548 the edge of the image. Pixels are value-centered (they are centered
549 on the coordinate whose value they represent), so the appropriate
550 range to plot the entirety of a 100x100 pixel image is C<[-0.5,99.5]> on
551 each axis.
552  
553 =back
554  
555 =head1 OBJECT-ORIENTED INTERFACE
556  
557 This section will briefly describe how the PDL::Graphics::PGPLOT::Window
558 package can be used in an object-oriented (OO) approach and what the
559 advantages of this would be. We will start with the latter
560  
561 =over
562  
563 =item Multiple windows.
564  
565 For the common user it is probably most interesting to use the OO interface
566 when handling several open devices at the same time. If you have one
567 variable for each plot device it is easier to distribute commands to the
568 right device at the right time. This is the angle we will take in the rest
569 of this description.
570  
571 =item Coding and abstraction
572  
573 At a more fundamental level it is desirable to approach a situation where
574 it is possible to have a generic plotting interface which gives access
575 to several plotting libraries, much as PGPLOT gives access to different
576 output devices. Thus in such a hypothetical package one would say:
577  
578 my $win1 = Graphics::new('PGPLOT', {Device => '/xs'});
579 my $win2 = Graphics::new('gnuplot', {Background => 'Gray'};
580  
581 From a more practical point of view such abstraction also comes in
582 handy when you write a large program package and you do not want to import
583 routines nilly-willy in which case an OO approach with method calls is a
584 lot cleaner.
585  
586 The pgwin exported constructor, arguably, breaks this philosophy; hopefully
587 it will ``wither away'' when other compatible modules are available.
588  
589 =back
590  
591 Anyway, enough philosophizing, let us get down to Earth and give some
592 examples of the use of OO PGPLOT. As an example we will take Odd (which
593 happens to be a common Norwegian name) who is monitoring the birth of
594 rabbits in O'Fib-o-nachy's farm (alternatively they can of course be
595 monitoring processes or do something entirely different). Odd wants the
596 user to be able to monitor both the birth rates and accumulated number
597 of rabbits and the spatial distribution of the births. Since these are
598 logically different they choose to have two windows open:
599  
600 $rate_win = PDL::Graphics::PGPLOT::Window->new(Device => '/xw',
601 Aspect => 1, WindowWidth => 5, NXPanel => 2);
602  
603 $area_win = PDL::Graphics::PGPLOT::Window->new(Device => '/xw',
604 Aspect => 1, WindowWidth => 5);
605  
606 See the documentation for L</new> below for a full overview of the
607 options you can pass to the constructor.
608  
609 Next, Odd wants to create plotting areas for subsequent plots and maybe
610 show the expected theoretical trends
611  
612 $rate_win->env(0, 10, 0, 1000, {XTitle => 'Days', YTitle => '#Rabbits'});
613 $rate_win->env(0, 10, 0, 100, {Xtitle=>'Days', Ytitle => 'Rabbits/day'});
614  
615 $area_win->env(0, 1, 0, 1, {XTitle => 'Km', Ytitle => 'Km'});
616 # And theoretical prediction.
617 $rate_win->line(sequence(10), fibonacci(10), {Panel => [1, 1]});
618  
619 That is basically it. The commands should automatically focus the relevant
620 window. Due to the limitations of PGPLOT this might however lead you to
621 plot in the wrong panel... The package tries to be smart and do this
622 correctly, but might get it wrong at times.
623  
624 =head1 STATE and RECORDING
625  
626 A new addition to the graphics interface is the ability to record plot
627 commands. This can be useful when you create a nice-looking plot on the
628 screen that you want to re-create on paper for instance. Or if you want
629 to redo it with slightly changed variables for instance. This is still
630 under development and views on the interface are welcome.
631  
632 The functionality is somewhat detached from the plotting functions
633 described below so I will discuss them and their use here.
634  
635 Recording is off by default. To turn it on when you create a new
636 device you can set the C<Recording> option to true, or you can set
637 the C<$PDL::Graphics::PGPLOT::RECORDING> variable to 1. I recommend doing the
638 latter in your C<.perldlrc> file at least since you will often have use
639 for recording in the perldl or pdl2 script.
640  
641 =head2 Use of recording
642  
643 The recording is meant to help you recreate a plot with new data or
644 to a different device. The most typical situation is that you have
645 created a beautiful plot on screen and want to have a Postscript file
646 with it. In the dreary old world you needed to go back and execute all
647 commands manually, but with this wonderful new contraption, the recorder,
648 you can just replay your commands:
649  
650 dev '/xs', {Recording => 1}
651 $x = sequence(10)
652 line $x, $x**2, {Linestyle => 'Dashed'}
653 $s = retrieve_state() # Get the current tape out of the recorder.
654 dev '/cps'
655 replay $s
656  
657 This should result in a C<pgplot.ps> file with a parabola drawn with a
658 dashed line. Note the command C<retrieve_state> which retrieves the current
659 state of the recorder and return an object (of type PDL::Graphics::State)
660 that is used to replay commands later.
661  
662 =head2 Controlling the recording
663  
664 Like any self-respecting recorder you can turn the recorder on and off
665 using the C<turn_on_recording> and C<turn_off_recording> respectively.
666 Likewise you can clear the state using the C<clear_state> command.
667  
668 $w=PDL::Graphics::PGPLOT::Window->new(Device => '/xs');
669 $w->turn_on_recording;
670 $x=sequence(10); $y=$x*$x;
671 $w->line($x, $y);
672 $w->turn_off_recording;
673 $w->line($y, $x);
674 $w->turn_on_recording;
675 $w->line($x, $y*$x);
676 $state = $w->retrieve_state();
677  
678 We can then replay C<$state> and get a parabola and a cubic plot.
679  
680 $w->replay($state);
681  
682 =head2 Tips and Gotchas!
683  
684 The data are stored in the state object as references to the real
685 data. This leads to one good and one potentially bad consequence:
686  
687 =over
688  
689 =item The good is that you can create the plot and then subsequently
690 redo the same plot using a different set of data. This is best explained
691 by an example. Let us first create a simple gradient image and get
692 a copy of the recording:
693  
694 $im = sequence(10,10)
695 imag $im
696 $s=retrieve_state
697  
698 Now this was a rather dull plot, and in reality we wanted to show an
699 image using C<rvals>. Instead of re-creating the plot (which of course
700 here would be the simplest option) we just change C<$im>:
701  
702 $im -= sequence(10,10)
703 $im += rvals(10,10)
704  
705 Now replay the commands
706  
707 replay $s
708  
709 And hey presto! A totally different plot. Note however the trickery
710 required to avoid losing reference to C<$im>
711  
712 =item This takes us immediately to the major problem with the recording
713 though. Memory leakage! Since the recording keeps references to the data
714 it can keep data from being freed (zero reference count) when you expect
715 it to be. For instance, in this example, we lose totally track of the
716 original $im variable, but since there is a reference to it in the state
717 it will not be freed
718  
719 $im = sequence(1000,1000)
720 imag $im
721 $s = retrieve_state
722 $im = rvals(10,10)
723  
724 Thus after the execution of these commands we still have a reference to
725 a 1000x1000 array which takes up a lot of memory...
726  
727 The solution is to call C<clear> on the state variable:
728  
729 $s->clear()
730  
731 (This is done automatically if the variable goes out of scope). I forsee
732 this problem to most acute when working on the C<perldl> or C<pdl2>
733 command line, but since this is exactly where the recording is most useful
734 the best advice is just to be careful and call clear on state variables.
735  
736 If you are working with scripts and use large images for instance I would
737 instead recommend that you do not turn on recording unless you need it.
738  
739 =back
740  
741  
742 =head1 FUNCTIONS
743  
744 A more detailed listing of the functions and their usage follows. For
745 all functions we specify which options take effect and what other options
746 exist for the given function. The function descriptions below are all
747 given for the non-OO usage for historical reasons, but since the conversion
748 to an OO method is trivial there is no major need for concern. Whenever you
749 see a function example of the form
750  
751 Usage: a_simple_function($x, $y, $z [, $opt]);
752  
753 and you wish to use the OO version, just let your mind read the above line
754 as:
755  
756 Usage: $win->a_simple_function($x, $y, $z [, $opt]);
757  
758 where C<$win> is a PDL::Graphics::PGPLOT::Window object. That is all.
759  
760  
761 =head2 Window control functions.
762  
763 =head2 pgwin
764  
765 =for ref
766  
767 Exported constructor for PGPLOT object/device/plot window.
768  
769 =for usage
770  
771 Usage: pgwin($opt);
772 Usage: pgwin($option=>$value,...);
773 Usage: pgwin($device);
774  
775 Parameters are passed on to new() and can either be specified by hash
776 reference or as a list.
777  
778 See the documentation fo PDL::Graphics::PGPLOT::Window::new for details.
779  
780 Because pgwin is a convenience function, you can specify the device by
781 passing in a single non-ref parameter. For even further convenience, you
782 can even omit the '/' in the device specifier, so these two lines
783 deliver the same result:
784  
785 $win = pgwin(gif);
786 $win = PDL::Graphics::PGPLOT::Window->new({Dev=>'/gif'});
787  
788 =head2 new
789  
790 =for ref
791  
792 Constructor for PGPLOT object/device/plot window.
793  
794 =for usage
795  
796 Usage: PDL::Graphics::PGPLOT::Window->new($opt);
797 Usage: PDL::Graphics::PGPLOT::Window->new($option=>$value,...);
798  
799 Options to new() can either be specified via a reference to a hash
800  
801 $win = PDL::Graphics::PGPLOT::Window->new({Dev=>'/xserve',ny=>2});
802  
803 or directly, as an array
804  
805 # NOTE: no more {} !
806 $win = PDL::Graphics::PGPLOT::Window->new(Dev=>'/xserve',ny=>2);
807  
808 The following lists the recognised options:
809  
810 =over
811  
812 =item AspectRatio
813  
814 The aspect ratio of the image, in the sense vertical/horizontal.
815 See the discussion on size setting.
816  
817 =item Device
818  
819 The type of device to use. The syntax of this is the one used by PGPLOT.
820  
821 =item Hold
822  
823 Hold the plot window so that subsequent plots can plot over existing plots.
824 This can be adjusted with the C<hold()> and C<release()> methods.
825  
826 =item NXPanel
827  
828 The number of panels in the X-direction
829  
830 =item NYPanel
831  
832 The number of panels in the Y-direction
833  
834 =item Size
835  
836 Yet another way to identify the plot window size -- this takes a scalar
837 or an array ref containing one, two, or three numbers. One number gives
838 you a square window. Two gives you a rectangular window C<(X,Y)>. Three
839 lets you specify the unit compactly (e.g. C<< [<X>,<Y>,1] >> for inches,
840 C<< [<X>,<Y>,2] >> for mm) but is deprecated in favor of using the
841 C<Unit> option.
842 See the discussion on size setting.
843  
844 =item Unit
845  
846 The unit to use for size setting. PGPLOT accepts inch, mm, or pixel.
847 The default unit is inches for historical reasons, but you can choose
848 millimeters or (God forbid) pixels as well. String or numeric
849 specifications are OK (0=normalized, 1=inches, 2=mm, 3=pixels).
850 Normalized units make no sense here and are not accepted. Ideally
851 someone will one day hook this into the CPAN units parser so you can
852 specify window size in rods or attoparsecs.
853  
854 =item WindowName
855  
856 The name to give to the window. No particular use is made of this at present.
857 It would be great if it was possible to change the title of the window frame.
858  
859 =item WindowWidth
860  
861 The width of the window in inches (or the specified Unit). See the
862 discussion on size setting.
863  
864 =item WindowXSize and WindowYSize
865  
866 The width and height of the window in inches (or the specified Unit). See
867 the discussion on size setting.
868  
869 =back
870  
871 An important point to note is that the default values of most options can be
872 specified by passing these to the constructor. All general options (common to
873 several functions) can be adjusted in such a way, but function specific
874 options can not be set in this way (this is a design limitation which is
875 unlikely to be changed).
876  
877 Thus the following call will set up a window where the default axis colour
878 will be yellow and where plot lines normally have red colour and dashed
879 linestyle.
880  
881 $win = PDL::Graphics::PGPLOT::Window->new(Device => '/xs',
882 AxisColour => 'Yellow', Colour => 'Red', LineStyle => 'Dashed');
883  
884  
885 Size setting: There are a gazillion ways to set window size, in
886 keeping with TIMTOWTDI. In general you can get away with passing any
887 unique combination of an C<< <X> >> size, a C<< <Y> >>size,
888 and/or an aspect ratio.
889 In increasing order of precedence, the options are: (C<Units>,
890 C<AspectRatio>, C<WindowWidth>, C<< Window<X,Y>Size >>, C<Size>).
891  
892 So if you specify an AspectRatio *and* an X and a Y coordinate, the
893 AspectRatio is ignored. Likewise, if you specify Units and a
894 three-component Size, the Units option is ignored in favor of the
895 numeric unit in the Size.
896  
897 If you don't specify enough information to set the size of the window,
898 you get the default pane size and shape for that device.
899  
900 =head2 close
901  
902 =for ref
903  
904 Close a plot window
905  
906 =for usage
907  
908 Usage: $win->close()
909  
910 Close the current window. This does not necessarily mean that the
911 window is removed from your screen, but it does ensure that the
912 device is closed. E.g., on X Windows with C</XSERVE>, the window won't
913 get closed, but it will with C</XWINDOW>.
914  
915 A message will be printed to STDOUT giving the name of the
916 file created if the plot was made to a hardcopy device and
917 C<$PDL::verbose> is true.
918  
919 =head2 held
920  
921 =for ref
922  
923 Check if a window is on hold
924  
925 =for usage
926  
927 $is_held = $win->held();
928  
929 Function to check whether the window is held or not.
930  
931  
932 =head2 hold
933  
934 =for ref
935  
936 Hold the present window.
937  
938 =for usage
939  
940 Usage: $win->hold()
941  
942 Holds the present window so that subsequent plot commands overplots.
943  
944  
945 =head2 panel
946  
947 =for ref
948  
949 Switch to a different panel
950  
951 =for usage
952  
953 $win->panel(<num>);
954  
955 Move to a different panel on the plotting surface. Note that you will need
956 to erase it manually if that is what you require.
957  
958 This routine currently does something you probably don't want, and hence is
959 deprecated for most use: if you say
960  
961 $win->panel(1);
962 $win->imag($image);
963  
964 then $image will actually be displayed in panel B<2>. That's because
965 the main plotting routines such as line and imag all advance the panel
966 when necessary. Instead, it's better to use the Panel option within
967 plotting commands, if you want to set the panel explicitly.
968  
969 =head2 release
970  
971 =for ref
972  
973 Release a plot window.
974  
975 =for usage
976  
977 $win->release()
978  
979 Release a plot window so that subsequent plot commands move to the next
980 panel or erase the plot and create a new plot.
981  
982 =head2 erase
983  
984 =for ref
985  
986 Erase plot
987  
988 =for usage
989  
990 $win->erase($opt);
991  
992 Erase a plot area. This accepts the option C<Panel> or alternatively a number
993 or array reference which makes it possible to specify the panel to erase when
994 working with several panels.
995  
996 =head2 Plotting functions
997  
998 =head2 env
999  
1000 =for ref
1001  
1002 Define a plot window, and put graphics on 'hold'
1003  
1004 =for usage
1005  
1006 $win->env( $xmin, $xmax, $ymin, $ymax, [$justify, $axis] );
1007 $win->env( $xmin, $xmax, $ymin, $ymax, [$options] );
1008  
1009 C<$xmin>, C<$xmax>, C<$ymin>, C<$ymax> are the plot boundaries.
1010 C<$justify> is a boolean value (default is B<0>);
1011 if true the axes scales will be the same (see C<justify>).
1012 C<$axis> describes how the axes should be drawn (see
1013 C<axis>) and defaults to B<0>.
1014  
1015 If the second form is used, $justify and $axis can be set in the options
1016 hash, for example:
1017  
1018 $win->env( 0, 100, 0, 50, {JUSTIFY => 1, AXIS => 'GRID',
1019 CHARSIZE => 0.7} );
1020  
1021 In addition the following options can also be set for C<env>:
1022  
1023 =over
1024  
1025 =item PlotPosition
1026  
1027 The position of the plot on the page relative to the view surface in
1028 normalised coordinates as an anonymous array. The array should contain
1029 the lower and upper X-limits and then the lower and upper Y-limits. To
1030 place two plots above each other with no space between them you could do
1031  
1032 $win->env(0, 1, 0, 1, {PlotPosition => [0.1, 0.5, 0.1, 0.5]});
1033 $win->env(5, 9, 0, 8, {PlotPosition => [0.1, 0.5, 0.5, 0.9]});
1034  
1035 =item Axis, Justify, Border
1036  
1037 See the description of general options for these options.
1038  
1039 =item AxisColour
1040  
1041 Set the colour of the coordinate axes.
1042  
1043 =item XTitle, YTitle, Title, Font, CharSize
1044  
1045 Axes titles and the font and size to print them.
1046  
1047 =back
1048  
1049 =head2 label_axes
1050  
1051 =for ref
1052  
1053 Label plot axes
1054  
1055 =for usage
1056  
1057 $win->label_axes(<xtitle>, <ytitle>, <plot title>, $options);
1058  
1059 Draw labels for each axis on a plot.
1060  
1061 =head2 imag
1062  
1063 =for ref
1064  
1065 Display an image (uses C<pgimag()>/C<pggray()> as appropriate)
1066  
1067 =for usage
1068  
1069 $win->imag ( $image, [$min, $max, $transform], [$opt] )
1070  
1071 NOTES
1072  
1073 C<$transform> for image/cont etc. is used in the same way as the
1074 C<TR()> array in the underlying PGPLOT FORTRAN routine but is,
1075 fortunately, zero-offset. The L<transform()|/transform> routine can be used to
1076 create this ndarray.
1077  
1078 If C<$image> is two-dimensional, you get a grey or pseudocolor image
1079 using the scalar values at each X,Y point. If C<$image> is
1080 three-dimensional and the third dimension has order 3, then it is
1081 treated as an RGB true-color image via L</rgbi>.
1082  
1083 There are several options related to scaling. By default, the image
1084 is scaled to fit the PGPLOT default viewport on the screen. Scaling,
1085 aspect ratio preservation, and 1:1 pixel mapping are available. (1:1
1086 pixel mapping is useful for avoiding display artifacts, but it's not
1087 recommended for final output as it's not device-independent.)
1088  
1089 Here's an additional complication: the "pixel" stuff refers not
1090 (necessarily) to normal image pixels, but rather to I<transformed>
1091 image pixels. That is to say, if you feed in a transform matrix
1092 via the C<TRANSFORM> option, the C<PIX>, C<SCALE>,
1093 etc. options all refer to the
1094 transformed coordinates and not physical image pixels. That is a Good
1095 Thing because it, e.g., lets you specify plate scales of your output
1096 plots directly! See fits_imag for an example application. If you
1097 do not feed in a transform matrix, then the identity matrix is applied
1098 so that the scaling options refer to original data pixels.
1099  
1100 To draw a colour bar (or wedge), either use the C<DrawWedge> option,
1101 or the C<draw_wedge()> routine (once the image has been drawn).
1102  
1103 Options recognised:
1104  
1105 =over 3
1106  
1107 =item ITF
1108  
1109 the image transfer function applied to the pixel values.
1110 It may be one of 'LINEAR', 'LOG', 'SQRT' (lower case is
1111 acceptable). It defaults to 'LINEAR'.
1112  
1113 =item MIN
1114  
1115 Sets the minimum value to be used for calculation of the
1116 color-table stretch.
1117  
1118 =item MAX
1119  
1120 Sets the maximum value for the same.
1121  
1122 =item RANGE
1123  
1124 A more compact way to specify MIN and MAX, as a list:
1125 you can say "Range=>[0,10]" to scale the color table for
1126 brightness values between 0 and 10 in the image data.
1127  
1128 =item CRANGE
1129  
1130 Image values between MIN and MAX are scaled to an
1131 interval in normalized color domain space, on the
1132 interval [0,1], before lookup in the window's color
1133 table. CRANGE lets you use only a part of the color
1134 table by specifying your own range -- e.g. if you
1135 say "CRange=>[0.25,0.75]" then only the middle half
1136 of the pseudocolor space will be used. (See the
1137 writeup on ctab().)
1138  
1139 =item TRANSFORM
1140  
1141 The PGPLOT transform 'matrix' as a 6x1 vector for display
1142  
1143 =item DrawWedge
1144  
1145 set to 1 to draw a colour bar (default is 0)
1146  
1147 =item Wedge
1148  
1149 see the draw_wedge() routine
1150  
1151 =back
1152  
1153 The following standard options influence this command:
1154  
1155 AXIS, BORDER, JUSTIFY, SCALE, PIX, PITCH, ALIGN, XRANGE, YRANGE
1156  
1157 =for example
1158  
1159 To see an image with maximum size in the current window, but square
1160 pixels, say:
1161 $win->imag( $x, { PIX=>1 } );
1162 An alternative approach is to try:
1163 $win->imag( $x, { JUSTIFY=>1 } );
1164 To see the same image, scaled 1:1 with device pixels, say:
1165 $win->imag( $x, { SCALE=>1 } );
1166 To see an image made on a device with 1:2 pixel aspect ratio, with
1167 X pixels the same as original image pixels, say
1168 $win->imag( $x, { PIX=>0.5, SCALE=>2 } );
1169 To display an image at 100 dpi on any device, say:
1170 $win->imag( $x, { PITCH=>100 } );
1171 To display an image with 100 micron pixels, say:
1172 $win->imag( $x, { PITCH=>10, UNIT=>'mm' } );
1173  
1174 =head2 imag1
1175  
1176 =for ref
1177  
1178 Display an image with correct aspect ratio
1179  
1180 =for usage
1181  
1182 $win->imag1 ( $image, [$min, $max, $transform], [$opt] )
1183  
1184 This is syntactic sugar for
1185  
1186 $win->imag( { PIX=>1, ALIGN=>'CC' } );
1187  
1188 =head2 rgbi
1189  
1190 =for ref
1191  
1192 Display an RGB color image
1193  
1194 The calling sequence is exactly like L</imag>, except that the input
1195 image must have three dimensions: C<N x M x 3>. The last dimension is the
1196 (R,G,B) color value. This routine requires B<pgplot 5.3devel> or later.
1197 Calling rgbi explicitly is not necessary, as calling image with an
1198 appropriately dimensioned RGB triplet makes it fall through to rgbi.
1199  
1200 =head2 fits_imag
1201  
1202 =for ref
1203  
1204 Display a FITS image with correct axes
1205  
1206 =for usage
1207  
1208 $win->fits_imag( image, [$min, $max], [$opt] );
1209  
1210 NOTES
1211  
1212 =over 3
1213  
1214 =item Titles:
1215  
1216 Currently fits_imag also generates titles for you by default and appends the
1217 FITS header scientific units if they're present. So if you say
1218  
1219 $pdl->hdr->{CTYPE1} = "Flamziness";
1220 $pdl->hdr->{CUNIT1} = "milliBleems";
1221 $win->fits_imag($pdl);
1222  
1223 then you get an X title of "Flamziness (milliBleems)". But you can (of course)
1224 override that by specifying the XTitle and YTitle switches:
1225  
1226 $win->fits_imag($pdl,{Xtitle=>"Arbitrary"});
1227  
1228 will give you "Arbitrary" as an X axis title, regardless of what's in the
1229 header.
1230  
1231 =item Scaling and aspect ratio:
1232  
1233 If CUNIT1 and CUNIT2 (or, if they're missing, CTYPE1 and CTYPE2)
1234 agree, then the default pixel aspect ratio is 1 (in scientific units,
1235 NOT in original pixels). If they don't agree (as for a spectrum)
1236 then the default pixel aspect ratio is adjusted automatically to
1237 match the plot viewport and other options you've specified.
1238  
1239 You can override the image scaling using the SCALE, PIX, or PITCH
1240 options just as with L<the imag() method|/imag> -- but
1241 those parameters refer to the scientific coordinate system rather than
1242 to the pixel coordinate system (e.g. C<PITCH=E<gt>100> means "100 scientific units
1243 per inch", and C<SCALE=E<gt>1> means "1 scientific unit per device pixel"). See
1244 L<the imag() writeup|/imag> for more info on these
1245 options.
1246  
1247 The default value of the C<ALIGN> option is 'CC' -- centering the image
1248 both vertically and horizontally.
1249  
1250 =item Axis direction:
1251  
1252 By default, fits_imag tries to guess which direction your axes are meant
1253 to go (left-to-right or right-to-left) using the CDELT keywords:
1254 if C<< CDELT >>
1255 is negative, then rather than reflecting the image fits_imag will plot the
1256 X axis so that the highest values are on the left.
1257  
1258 This is the most convenient behavior for folks who use calibrated
1259 (RA,DEC) images, but it is technically incorrect. To force the direction,
1260 use the DirAxis option. Setting
1261 C<< DirAxis=>1 >> (abbreviated C<< di=>1 >>)
1262 will force the scientific axes to increase to the right, reversing the image
1263 as necessary.
1264  
1265 =item Color wedge:
1266  
1267 By default fits_imag draws a color wedge on the right; you can explicitly
1268 set the C<DrawWedge> option to 0 to avoid this. Use the C<WTitle> option
1269 to set the wedge title.
1270  
1271  
1272 =item Alternate WCS coordinates:
1273  
1274 The default behaviour is to use the primary/default WCS information
1275 in the FITS header (i.e. the C<CRVAL1>,C<CRPIX1>,... keywords). The
1276 Greisen et al. standard (L<http://fits.cv.nrao.edu/documents/wcs/wcs.html>)
1277 allows alternative/additional mappings to be included in a header; these
1278 are denoted by the letters C<A> to C<Z>. If you know that your image contains
1279 such a mapping then you can use the C<WCS> option to select the appropriate
1280 letter. For example, if you had read in a Chandra image created by the CIAO
1281 software package then you can display the image in the C<physical>
1282 coordinate system by saying:
1283  
1284 $win->fits_imag( $pdl, { wcs => 'p' } );
1285  
1286 The identity transform is used if you select a mapping for which there is
1287 no information in the header.
1288 Please note that this support is B<experimental> and is not guaranteed
1289 to work correctly; please see the documentation for the L</_FITS_tr>
1290 routine for more information.
1291  
1292 =back
1293  
1294  
1295  
1296 =head2 fits_rgbi
1297  
1298 =for ref
1299  
1300 Display an RGB FITS image with correct axes
1301  
1302 =for usage
1303  
1304 $win->fits_rgbi( image, [$min,$max], [$opt] );
1305  
1306 Works exactly like L</fits_imag>, but the image must be in
1307 (X,Y,RGB) form. Only the first two axes of the FITS header are examined.
1308  
1309 =head2 fits_cont
1310  
1311 =for ref
1312  
1313 Draw contours of an image, labelling the axes using the WCS information
1314 in the FITS header of the image.
1315  
1316 =for usage
1317  
1318 $win->fits_cont( image, [$contours, $transform, $misval], [$opt] )
1319  
1320 Does the same thing for the L</cont> routine that
1321 L</fits_imag> does for the L</imag> routines.
1322  
1323 =head2 draw_wedge
1324  
1325 =for ref
1326  
1327 Add a wedge (colour bar) to an image.
1328  
1329 =for usage
1330  
1331 $win->draw_wedge( [$opt] )
1332  
1333 Adds a wedge - shows the mapping between colour and value for a pixel - to
1334 the current image. This can also be achieved by setting C<DrawWedge> to 1
1335 when calling the C<imag> routine.
1336  
1337 The colour and font size are the same as used to draw the image axes
1338 (although this will probably fail if you did it yourself). To control the size
1339 and location of the wedge, use the C<Wedge> option, giving it a hash reference
1340 containing any of the following:
1341  
1342 =over 4
1343  
1344 =item Side
1345  
1346 Which side of the image to draw the wedge: can be one of 'B', 'L', 'T', or
1347 'R'. Default is B<'R'>.
1348  
1349 =item Displacement
1350  
1351 How far from the edge of the image should the wedge be drawn, in units of character
1352 size. To draw within the image use a negative value. Default is B<1.5>.
1353  
1354 =item Width
1355  
1356 How wide should the wedge be, in units of character size. Default is B<2>.
1357  
1358 =item Label
1359  
1360 A text label to be added to the wedge. If set, it is probably worth
1361 increasing the C<Width> value by about 1 to keep the text readable.
1362 Default is B<''>. This is equivalent to the C<WTitle> option to
1363 L</imag>, L</fits_imag>, and similar methods.
1364  
1365 =item ForeGround (synonym Fg)
1366  
1367 The pixel value corresponding to the "maximum" colour. If C<undef>, uses the
1368 value used by C<imag> (recommended choice). Default is C<undef>.
1369  
1370 =item BackGround (synonym Bg)
1371  
1372 The pixel value corresponding to the "minimum" colour. If C<undef>, uses the
1373 value used by C<imag> (recommended choice). Default is C<undef>.
1374  
1375 =back
1376  
1377 =for example
1378  
1379 $x = rvals(50,50);
1380 $win = PDL::Graphics::PGPLOT::Window->new();
1381 $win->imag( $x, { Justify => 1, ITF => 'sqrt' } );
1382 $win->draw_wedge( { Wedge => { Width => 4, Label => 'foo' } } );
1383 # although the following might be more sensible
1384 $win->imag( $x, { Justify => 1, ITF => 'sqrt', DrawWedge => 1,
1385 Wedge => { Width => 4, Label => 'foo'} } );
1386  
1387 =head2 ctab
1388  
1389 =for ref
1390  
1391 Load an image colour table.
1392  
1393 Usage:
1394  
1395 =for usage
1396  
1397 ctab ( $name, [$contrast, $brightness] ) # Builtin col table
1398 ctab ( $ctab, [$contrast, $brightness] ) # $ctab is Nx4 array
1399 ctab ( $levels, $red, $green, $blue, [$contrast, $brightness] )
1400 ctab ( '', $contrast, $brightness ) # use last color table
1401  
1402 Note: See L<PDL::Graphics::LUT> for access to a large
1403 number of colour tables.
1404  
1405 Notionally, all non-RGB images and vectors have their colors looked up
1406 in the window's color table. Colors in images and such are scaled to
1407 a normalized pseudocolor domain on the line segment [0,1]; the color
1408 table is a piecewise linear function that maps this one-dimensional
1409 scale to the three-dimensional normalized RGB color space [0,1]^3.
1410  
1411 You can specify specific indexed colors by appropriate use of the
1412 (levels,red,green,blue) syntax -- but that is deprecated, since the actual
1413 available number of colors can change depending on the output device.
1414 (Someone needs to write a specific hardware-dependent lookup table interface).
1415  
1416 See also L</imag> for a description of how to use only part of the
1417 color table for a particular image.
1418  
1419 =head2 ctab_info
1420  
1421 =for ref
1422  
1423 Return information about the currently loaded color table
1424  
1425 =head2 autolog
1426  
1427 =for ref
1428  
1429 Turn on automatic logarithmic scaling in C<line> and C<points>
1430  
1431 =for usage
1432  
1433 Usage: autolog([0|1]);
1434  
1435 Setting the argument to 1 turns on automatic log scaling and setting it to
1436 zero turns it off again. The function can be used in both the object
1437 oriented and standard interface. To learn more, see the documentation for
1438 the L<axis option|/axis>.
1439  
1440 =for example
1441  
1442 my $win = PDL::Graphics::PGPLOT::Window->new(dev=>'/xserve');
1443 my $x=sequence(10);
1444 my $y=$x*$x+1;
1445  
1446 $win->autolog(1);
1447 $win->line($x,$y, {Axis => 'LogY'});
1448  
1449  
1450 =head2 line
1451  
1452 =for ref
1453  
1454 Plot vector as connected points
1455  
1456 If the 'MISSING' option is specified, those points in the C<$y> vector
1457 which are equal to the MISSING value are not plotted, but are skipped
1458 over. This allows one to quickly draw multiple lines with one call to
1459 C<line>, for example to draw coastlines for maps.
1460  
1461 =for usage
1462  
1463 Usage: line ( [$x,] $y, [$opt] )
1464  
1465 The following standard options influence this command:
1466  
1467 AXIS, BORDER, COLO(U)R, LINESTYLE, LINEWIDTH, MISSING,
1468 JUSTIFY, SCALE, PITCH, PIX, ALIGN
1469  
1470 =for example
1471  
1472 $x = sequence(10)/10.;
1473 $y = sin($x)**2;
1474 # Draw a red dot-dashed line
1475 line $x, $y, {COLOR => 'RED', LINESTYLE=>3};
1476  
1477 =head2 lines
1478  
1479 =for ref
1480  
1481 Plot a list of vectors as discrete sets of connected points
1482  
1483 This works much like L</line>, but for discrete sets of connected
1484 points. There are two ways to break lines: you can pass in x/y coordinates
1485 just like in L</line>, but with an additional C<pen> ndarray that
1486 indicates whether the pen is up or down on the line segment following
1487 each point (so you set it to zero at the end of each line segment you
1488 want to draw); or you can pass in an array ref containing a list
1489 of single polylines to draw.
1490  
1491 Happily, there's extra meaning packed into the C<pen> ndarray: it
1492 multiplies the COLO(U)R that you set, so if you feed in boolean
1493 values you get what you expect -- but you can also feed in integer
1494 or floating-point values to get multicolored lines.
1495  
1496 Furthermore, the sign bit of C<pen> can be used to draw hairline segments:
1497 if C<pen> is negative, then the segment is drawn as though it were
1498 positive but with LineWidth and HardLW set to 1 (the minimum).
1499  
1500 Equally happily, even if you are using the array ref mechanism
1501 to break your polylines you can feed in an array ref of C<pen> values to
1502 take advantage of the color functionality or further dice your polylines.
1503  
1504 Note that, unlike L</line>, C<lines> has no no specify-$y-only
1505 calling path. That's because C<lines> is intended more for line art than for
1506 plotting, so you always have to specify both $x and $y.
1507  
1508 Infinite or bad values are ignored -- that is to say, if your vector
1509 contains a non-finite point, that point breaks the vector just as if you
1510 set pen=0 for both that point and the point before it.
1511  
1512 =for usage
1513  
1514 Usage: $w->lines( $x, $y, [$pen], [$opt] );
1515 $w->lines( $xy, [$pen], [$opt] );
1516 $w->lines( \@xvects, \@yvects, [\@pen], [$opt] );
1517 $w->lines( \@xyvects, [\@pen], [$opt] );
1518  
1519 The following standard options influence this command:
1520 AXIS, BORDER, COLO(U)R, LINESTYLE, LINEWIDTH, MISSING,
1521 JUSTIFY, SCALE, PITCH, PIX, ALIGN
1522  
1523 CAVEAT:
1524  
1525 Setting C<pen> elements to 0 prevents drawing altogether, so you
1526 can't use that to draw in the background color.
1527  
1528 =head2 points
1529  
1530 =for ref
1531  
1532 Plot vector as points
1533  
1534 =for usage
1535  
1536 Usage: points ( [$x,] $y, [$symbol(s)], [$opt] )
1537  
1538 Options recognised:
1539  
1540 SYMBOL - Either an ndarray with the same dimensions as $x, containing
1541 the symbol associated to each point or a number specifying
1542 the symbol to use for every point, or a name specifying the
1543 symbol to use according to the following (recognised name in
1544 capital letters):
1545 0 - SQUARE 1 - DOT 2 - PLUS 3 - ASTERISK
1546 4 - CIRCLE 5 - CROSS 7 - TRIANGLE 8 - EARTH
1547 9 - SUN 11 - DIAMOND 12- STAR
1548 PLOTLINE - If this is >0 a line will be drawn through the points.
1549  
1550 The following standard options influence this command:
1551  
1552 AXIS, BORDER, CHARSIZE, COLOUR, LINESTYLE, LINEWIDTH,
1553 JUSTIFY, SCALE, PIX, PITCH, ALIGN
1554  
1555 C<SymbolSize> allows adjusting the symbol size, it defaults to CharSize.
1556  
1557 The C<ColorValues> option allows one to plot XYZ data with the
1558 Z axis mapped to a color value. For example:
1559  
1560 use PDL::Graphics::LUT;
1561 ctab(lut_data('idl5')); # set up color palette to 'idl5'
1562 points ($x, $y, {ColorValues => $z});
1563  
1564 =for example
1565  
1566 $y = sequence(10)**2+random(10);
1567 # Plot blue stars with a solid line through:
1568 points $y, {PLOTLINE => 1, COLOUR => BLUE, symbol => STAR}; # case insensitive
1569  
1570 =head2 errb
1571  
1572 =for ref
1573  
1574 Plot error bars (using C<pgerrb()>)
1575  
1576 Usage:
1577  
1578 =for usage
1579  
1580 errb ( $y, $yerrors, [$opt] )
1581 errb ( $x, $y, $yerrors, [$opt] )
1582 errb ( $x, $y, $xerrors, $yerrors, [$opt] )
1583 errb ( $x, $y, $xloerr, $xhierr, $yloerr, $yhierr, [$opt])
1584  
1585 Any of the error bar parameters may be C<undef> to omit those error bars.
1586  
1587 Options recognised:
1588  
1589 TERM - Length of terminals in multiples of the default length
1590 SYMBOL - Plot the datapoints using the symbol value given, either
1591 as name or number - see documentation for 'points'
1592  
1593 The following standard options influence this command:
1594  
1595 AXIS, BORDER, CHARSIZE, COLOUR, LINESTYLE, LINEWIDTH,
1596 JUSTIFY, SCALE, PIX, PITCH, ALIGN
1597  
1598 =for example
1599  
1600 $y = sequence(10)**2+random(10);
1601 $sigma=0.5*sqrt($y);
1602 errb $y, $sigma, {COLOUR => RED, SYMBOL => 18};
1603  
1604 # plot X bars only
1605 errb( $x, $y, $xerrors, undef );
1606  
1607 # plot negative going bars only
1608 errb( $x, $y, $xloerr, undef, $yloerr, undef );
1609  
1610  
1611 =head2 cont
1612  
1613 =for ref
1614  
1615 Display image as contour map
1616  
1617 =for usage
1618  
1619 Usage: cont ( $image, [$contours, $transform, $misval], [$opt] )
1620  
1621 Notes: C<$transform> for image/cont etc. is used in the same way as the
1622 C<TR()> array in the underlying PGPLOT FORTRAN routine but is,
1623 fortunately, zero-offset. The L<transform()|/transform> routine can be used to
1624 create this ndarray.
1625  
1626 Options recognised:
1627  
1628 CONTOURS - A ndarray with the contour levels
1629 FOLLOW - Follow the contour lines around (uses pgcont rather than
1630 pgcons) If this is set >0 the chosen linestyle will be
1631 ignored and solid line used for the positive contours
1632 and dashed line for the negative contours.
1633 LABELS - An array of strings with labels for each contour
1634 LABELCOLOUR - The colour of labels if different from the draw colour
1635 This will not interfere with the setting of draw colour
1636 using the colour keyword.
1637 MISSING - The value to ignore for contouring
1638 NCONTOURS - The number of contours wanted for automatical creation,
1639 overridden by CONTOURS
1640 TRANSFORM - The pixel-to-world coordinate transform vector
1641  
1642 The following standard options influence this command:
1643  
1644 AXIS, BORDER, COLOUR, LINESTYLE, LINEWIDTH,
1645 JUSTIFY, SCALE, PIX, PITCH, ALIGN
1646  
1647 =for example
1648  
1649 $x=sequence(10,10);
1650 $ncont = 4;
1651 $labels= ['COLD', 'COLDER', 'FREEZING', 'NORWAY']
1652 # This will give four blue contour lines labelled in red.
1653 cont $x, {NCONT => $ncont, LABELS => $labels, LABELCOLOR => RED,
1654 COLOR => BLUE}
1655  
1656 =head2 bin
1657  
1658 =for ref
1659  
1660 Plot vector as histogram (e.g. C<bin(hist($data))>)
1661  
1662 =for usage
1663  
1664 Usage: bin ( [$x,] $data )
1665  
1666 Options recognised:
1667  
1668 CENTRE - (default=1) if true, the x values denote the centre of the
1669 bin otherwise they give the lower-edge (in x) of the bin
1670 CENTER - as CENTRE
1671  
1672 The following standard options influence this command:
1673  
1674 AXIS, BORDER, COLOUR, JUSTIFY, LINESTYLE, LINEWIDTH
1675  
1676 =head2 hi2d
1677  
1678 =for ref
1679  
1680 Plot image as 2d histogram (not very good IMHO...)
1681  
1682 =for usage
1683  
1684 Usage: hi2d ( $image, [$x, $ioff, $bias], [$opt] )
1685  
1686 Options recognised:
1687  
1688 IOFFSET - The offset for each array slice. >0 slants to the right
1689 <0 to the left.
1690 BIAS - The bias to shift each array slice up by.
1691  
1692 The following standard options influence this command:
1693  
1694 AXIS, BORDER, JUSTIFY, SCALE, PIX, PITCH, ALIGN
1695  
1696 Note that meddling with the C<ioffset> and C<bias> often will require you to
1697 change the default plot range somewhat. It is also worth noting that if
1698 you have TriD working you will probably be better off using
1699 L<mesh3d|PDL::Graphics::TriD/mesh3d> or
1700 a similar command - see the L<PDL::Graphics::TriD>
1701 module.
1702  
1703 =for example
1704  
1705 $r=sequence(100)/50-1.0;
1706 $y=exp(-$r**2)*transpose(exp(-$r**2))
1707 hi2d $y, {IOFF => 1.5, BIAS => 0.07};
1708  
1709 =head2 arrow
1710  
1711 =for ref
1712  
1713 Plot an arrow
1714  
1715 =for usage
1716  
1717 Usage: arrow($x1, $y1, $x2, $y2, [, $opt]);
1718  
1719 Plot an arrow from C<$x1, $y1> to C<$x2, $y2>. The arrow shape can be
1720 set using the option C<Arrow>. See the documentation for general options
1721 for details about this option (and the example below):
1722  
1723 =for example
1724  
1725 Example:
1726  
1727 arrow(0, 1, 1, 2, {Arrow => {FS => 1, Angle => 1, Vent => 0.3, Size => 5}});
1728  
1729 which draws a broad, large arrow from (0, 1) to (1, 2).
1730  
1731 =head2 rect
1732  
1733 =for ref
1734  
1735 Draw a non-rotated rectangle
1736  
1737 Usage: rect ( $x1, $x2, $y1, $y2 )
1738  
1739 Options recognised:
1740  
1741 The following standard options influence this command:
1742  
1743 AXIS, BORDER, COLOUR, FILLTYPE, HATCHING, LINESTYLE, LINEWIDTH
1744 JUSTIFY, SCALE, PIX, PITCH, ALIGN
1745  
1746 =head2 poly
1747  
1748 =for ref
1749  
1750 Draw a polygon
1751  
1752 =for usage
1753  
1754 Usage: poly ( $x, $y )
1755  
1756 Options recognised:
1757  
1758 The following standard options influence this command:
1759  
1760 AXIS, BORDER, COLOUR, FILLTYPE, HATCHING, LINESTYLE, LINEWIDTH
1761 JUSTIFY, SCALE, PIX, PITCH, ALIGN
1762  
1763 =for example
1764  
1765 # Fill with hatching in two different colours
1766 $x=sequence(10)/10;
1767 # First fill with cyan hatching
1768 poly $x, $x**2, {COLOR=>5, FILL=>3};
1769 hold;
1770 # Then do it over again with the hatching offset in phase:
1771 poly $x, $x**2, {COLOR=>6, FILL=>3, HATCH=>{PHASE=>0.5}};
1772 release;
1773  
1774 =head2 circle
1775  
1776 =for ref
1777  
1778 Plot a circle on the display using the fill setting.
1779  
1780 =for usage
1781  
1782 Usage: circle($x, $y, $radius [, $opt]);
1783  
1784 All arguments can alternatively be given in the options hash using the
1785 following options:
1786  
1787 =over
1788  
1789 =item XCenter and YCenter
1790  
1791 The position of the center of the circle
1792  
1793 =item Radius
1794  
1795 The radius of the circle.
1796  
1797 =back
1798  
1799 =head2 ellipse
1800  
1801 =for ref
1802  
1803 Plot an ellipse, optionally using fill style.
1804  
1805 =for usage
1806  
1807 Usage: ellipse($x, $y, $smaj, $smin, $theta [, $opt]);
1808  
1809 All arguments can alternatively be given in the options hash using the
1810 following options (for historical reasons the names MajorAxis and MinorAxis have
1811 been preserved though they really refer to the semi-axes):
1812  
1813 =over
1814  
1815 =item MajorAxis
1816  
1817 The semi-major axis of the ellipse - this must be defined or C<$smaj> must be given.
1818  
1819 =item MinorAxis
1820  
1821 The semi-minor axis, like C<MajorAxis> this is required or C<$smin> must be given.
1822  
1823 =item Theta (synonym Angle)
1824  
1825 The orientation of the ellipse - defaults to 0.0. This is given in
1826 radians.
1827  
1828 =item XCenter and YCenter
1829  
1830 The coordinates of the center of the ellipse. These must be specified or
1831 C<$x> and C<$y> must be given.
1832  
1833 =item NPoints
1834  
1835 The number of points used to draw the ellipse. This defaults to 100 and
1836 might need changing in the case of very large ellipses.
1837  
1838 =back
1839  
1840 The routine also recognises the same standard options as
1841 accepted by L</poly>.
1842  
1843 =head2 rectangle
1844  
1845 =for ref
1846  
1847 Draw a rectangle.
1848  
1849 =for usage
1850  
1851 Usage: rectangle($xcenter, $ycenter, $xside, $yside, [, $angle, $opt]);
1852  
1853 This routine draws a rectangle with the chosen fill style. Internally
1854 it calls L</poly> which is somewhat slower than C<pgrect> but which
1855 allows for rotated rectangles as well. The routine recognises the same
1856 options as C<poly> and in addition the following:
1857  
1858 =over
1859  
1860 =item XCenter and YCenter
1861  
1862 The position of the center of the rectangle. XCentre and YCentre are
1863 valid synonyms.
1864  
1865 =item XSide and YSide
1866  
1867 The length of the X and Y sides. If only one is specified the
1868 shape is taken to be square with that as the side-length, alternatively
1869 the user can set Side
1870  
1871 =item Side
1872  
1873 The length of the sides of the rectangle (in this case a square) - syntactic
1874 sugar for setting XSide and YSide identical. This is overridden by XSide
1875 or YSide if any of those are set.
1876  
1877 =item Angle (synonym Theta)
1878  
1879 The angle at which the rectangle is to be drawn. This defaults to 0.0 and
1880 is given in radians.
1881  
1882  
1883 =back
1884  
1885  
1886 =head2 vect
1887  
1888 =for ref
1889  
1890 Display 2 images as a vector field
1891  
1892 =for usage
1893  
1894 Usage: vect ( $w, $x, $y, [$scale, $pos, $transform, $misval], { opt } );
1895 $w->vect($x,$y,[$scale,$pos,$transform,$misval], { opt });
1896  
1897 Notes: C<$transform> for image/cont etc. is used in the same way as the
1898 C<TR()> array in the underlying PGPLOT FORTRAN routine but is,
1899 fortunately, zero-offset. The L<transform()|/transform> routine can be used to
1900 create this ndarray.
1901  
1902 This routine will plot a vector field. C<$x> is the horizontal component
1903 and C<$y> the vertical component. The scale factor converts between
1904 vector length units and scientific positional units. You can set the
1905 scale, position, etc. either by passing in parameters in the normal parameter
1906 list or by passing in options.
1907  
1908 Options recognised:
1909  
1910 SCALE - Set the scale factor for vector lengths.
1911 POS - Set the position of vectors.
1912 <0 - vector head at coordinate
1913 >0 - vector base at coordinate
1914 =0 - vector centered on the coordinate
1915 TRANSFORM - The pixel-to-world coordinate transform vector
1916 MISSING - Elements with this value are ignored.
1917  
1918 The following standard options influence this command:
1919  
1920 ARROW, ARROWSIZE, AXIS, BORDER, CHARSIZE, COLOUR,
1921 LINESTYLE, LINEWIDTH,
1922  
1923 =for example
1924  
1925 $x=rvals(11,11,{Centre=>[5,5]});
1926 $y=rvals(11,11,{Centre=>[0,0]});
1927 vect $x, $y, {COLOR=>YELLOW, ARROWSIZE=>0.5, LINESTYLE=>dashed};
1928  
1929 =head2 fits_vect
1930  
1931 =for ref
1932  
1933 Display a pair of 2-D ndarrays as vectors, with FITS header interpretation
1934  
1935 =for usage
1936  
1937 Usage: fits_vect ($x, $y, [$scale, $pos, $transform, $misval] )
1938  
1939 C<fits_vect> is to L</vect> as L</fits_imag> is to L</imag>.
1940  
1941 =head2 transform
1942  
1943 =for ref
1944  
1945 Create transform array for contour and image plotting
1946  
1947 =for usage
1948  
1949 $win->transform([$xdim,$ydim], $options);
1950  
1951 (For information on coordinate transforms, try L<PDL::Transform>.)
1952 This function creates a transform array in the format required by the image
1953 and contouring routines. You must call it with the dimensions of your image
1954 as arguments or pass these as an anonymous hash - see the example below.
1955  
1956 =over
1957  
1958 =item Angle
1959  
1960 The rotation angle of the transform, in radians. Positive numbers rotate the
1961 image clockwise on the screen.
1962  
1963 =item ImageDimensions
1964  
1965 The dimensions of the image the transform is required for. The dimensions
1966 should be passed as a reference to an array.
1967  
1968 =item Pixinc
1969  
1970 The increment in output coordinate per pixel.
1971  
1972 =item ImageCenter (or ImageCentre)
1973  
1974 The centre of the image as an anonymous array B<or> as a scalar, in
1975 scientific coordinates. In the latter case the x and y value for the
1976 center will be set equal to this scalar. This is particularly useful
1977 in the common case when the center is (0, 0). (ImageCenter overrides
1978 RefPos if both are specified).
1979  
1980 =item RefPos (or ReferencePosition)
1981  
1982 If you wish to set a pixel other than the image centre to a given
1983 value, use this option. It should be supplied with a reference to an array
1984 containing 2 2-element array references, e.g.
1985  
1986 RefPos => [ [ $xpix, $ypix ], [ $xplot, $yplot ] ]
1987  
1988 This will label pixel C<($xpix,$ypix)> as being at position
1989 C<($xplot,$yplot)>. For example
1990  
1991 RefPos => [ [100,74], [ 0, 0 ] ]
1992  
1993 sets the scientific coordinate origin to be at the center of the (100,74)
1994 pixel coordinate. The pixel coordinates are pixel-centered, and start counting
1995 from 0 (as all good pixel coordinates should).
1996  
1997 =back
1998  
1999 Example:
2000  
2001 $im = rvals(100, 100);
2002 $w = PDL::Graphics::PGPLOT::Window->new(Device => '/xs');
2003 $t = $w->transform(dims($im), {ImageCenter => 0, Pixinc => 5});
2004 $w->imag($im, {Transform => $t});
2005  
2006 =cut
2007  
2008 {
2009 use strict;
2010 my $transform_options = undef;
2011  
2012 sub transform {
2013 # Compute the transform array needed in contour and image plotting
2014 my $self = shift;
2015  
2016 if (!defined($transform_options)) {
2017 $transform_options =
2018 $self->{PlotOptions}->extend({Angle => undef,
2019 ImageDims => undef,
2020 Pixinc => undef,
2021 ImageCenter => undef,
2022 RefPos => undef
2023 });
2024 $transform_options->synonyms({
2025 ImageDimensions => 'ImageDims',
2026 ImageCentre => 'ImageCenter',
2027 ReferencePosition => 'RefPos',
2028 });
2029 }
2030  
2031 # parse the input
2032 my ($in, $opt)=_extract_hash(@_);
2033 my ($x_pix, $y_pix)= @$in;
2034  
2035 # handle options
2036 $opt = {} if !defined($opt);
2037 my ($o, $u_opt) = $self->_parse_options($transform_options, $opt);
2038 $self->_standard_options_parser($u_opt);
2039  
2040 my ($angle, $x_pixinc, $y_pixinc, $xref_pix, $yref_pix, $xref_wrld, $yref_wrld);
2041 if (defined($o->{Angle})) {
2042 $angle = $o->{Angle};
2043 }
2044 else {
2045 $angle = 0;
2046 }
2047  
2048 if (defined($o->{Pixinc})) {
2049 if (ref($o->{Pixinc}) eq 'ARRAY') {
2050 ($x_pixinc, $y_pixinc) = @{$o->{Pixinc}};
2051 }
2052 else {
2053 $x_pixinc = $y_pixinc = $o->{Pixinc};
2054 }
2055 }
2056 else {
2057 $x_pixinc = $y_pixinc = 1;
2058 }
2059  
2060 if ( defined $o->{ImageDims} ) {
2061 if ( ref($o->{ImageDims}) eq 'ARRAY' ) {
2062 ($x_pix, $y_pix) = @{$o->{ImageDims}};
2063 }
2064 else {
2065 barf "Image dimensions must be given as an array reference!";
2066 }
2067 }
2068  
2069 # The user has to pass the dimensions of the image somehow, so this
2070 # is a good point to check whether they have done so.
2071 unless (defined($x_pix) && defined($y_pix)) {
2072 barf "You must pass the image dimensions to the transform routine\n";
2073 }
2074  
2075 # The RefPos option gives more flexibility than
2076 # ImageCentre, since ImageCentre => [ a, b ] is the same
2077 # as PosReference => [ [(nx-1)/2,(ny-1/2)], [a,b] ].
2078 # We use ImageCentre in preference to PosReference
2079 #
2080 if (defined $o->{ImageCenter}) {
2081 print "transform() ignoring RefPos as seen ImageCentre\n"
2082 if defined $o->{RefPos} and $PDL::verbose;
2083 my $ic = $o->{ImageCenter};
2084 if (ref($ic) eq 'ARRAY') {
2085 ($xref_wrld, $yref_wrld) = @{$ic};
2086 }
2087 else {
2088 $xref_wrld = $yref_wrld = $ic;
2089 }
2090  
2091 $xref_pix = ($x_pix - 1)/2;
2092 $yref_pix = ($y_pix - 1)/2;
2093  
2094 }
2095 elsif ( defined $o->{RefPos} ) {
2096 my $aref = $o->{RefPos};
2097 barf "RefPos option must be sent an array reference.\n"
2098 unless ref($aref) eq 'ARRAY';
2099 barf "RefPos must be a 2-element array reference\n"
2100 unless $#$aref == 1;
2101 my $pixref = $aref->[0];
2102 my $wrldref = $aref->[1];
2103 barf "Elements of RefPos must be 2-element array references\n"
2104 unless $#$pixref == 1 and $#$wrldref == 1;
2105  
2106 ($xref_pix, $yref_pix) = @{$pixref};
2107 ($xref_wrld, $yref_wrld) = @{$wrldref};
2108 }
2109 else {
2110 $xref_wrld = $yref_wrld = 0;
2111 $xref_pix = ($x_pix - 1)/2;
2112 $yref_pix = ($y_pix - 1)/2;
2113 }
2114  
2115 # The elements of the transform ndarray,
2116 # here labelled t0 to t5, relate to the
2117 # following maxtix equation:
2118 #
2119 # world = zp + matrix * pixel
2120 #
2121 # world - the position of the point in the world,
2122 # ie plot, coordinate system
2123 # pixel - the position of the point in pixel
2124 # coordinates (bottom-left is 0,0 pixel)
2125 # zp - (t0)
2126 # (t3)
2127 # matrix - (t1 t2)
2128 # (t4 t5)
2129 #
2130 my $ca = cos( $angle );
2131 my $sa = sin( $angle );
2132 my $t1 = $x_pixinc * $ca;
2133 my $t2 = $y_pixinc * $sa;
2134 my $t4 = -$x_pixinc * $sa;
2135 my $t5 = $y_pixinc * $ca;
2136  
2137 return pdl(
2138 $xref_wrld - $t1 * $xref_pix - $t2 * $yref_pix,
2139 $t1, $t2,
2140 $yref_wrld - $t4 * $xref_pix - $t5 * $yref_pix,
2141 $t4, $t5
2142 );
2143 }
2144 }
2145  
2146 =head2 tline
2147  
2148 =for ref
2149  
2150 Broadcasted line plotting
2151  
2152 =for usage
2153  
2154 $win->tline($x, $y, $options);
2155  
2156 This is a broadcasted interface to C<line>. This is convenient if you have
2157 a 2D array and want to plot out every line in one go. The routine will
2158 apply any options you apply in a "reasonable" way. In the sense that it
2159 will loop over the options wrapping over if there are less options than
2160 lines.
2161  
2162 Example:
2163  
2164 $h={Colour => ['Red', '1', 4], Linestyle => ['Solid' ,'Dashed']};
2165 $tx=zeroes(100,5)->xlinvals(-5,5);
2166 $ty = $tx + $tx->yvals;
2167 $win->tline($tx, $ty, $h);
2168  
2169 =cut
2170  
2171 # A "broadcasted" line - I cannot come up with a more elegant way of doing
2172 # this without re-coding bits of broadcast_over but it might very well be
2173 # that you may :)
2174 my $line_options = undef;
2175 sub tline {
2176 my $self = shift;
2177 my ($in, $opt)=_extract_hash(@_);
2178 $self->_add_to_state(\&tline, $in, $opt);
2179 $opt={} if !defined($opt);
2180  
2181 barf 'Usage tline ([$x], $y, [, $options])' if $#$in < 0 || $#$in > 2;
2182 my ($x, $y)=@$in;
2183 if (!defined($line_options)) {
2184 $line_options=$self->{PlotOptions}->extend({Missing => undef});
2185 }
2186  
2187 if ($#$in==0) {
2188 $y = $x; $x = $y->xvals();
2189 }
2190  
2191 catch_signals {
2192 # This is very very kludgy, but it was the best way I could find..
2193 my $o = _broadcast_options($y->getdim(1), $opt);
2194 # We need to keep track of the current status of hold or not since
2195 # the tline function automatically enforces a hold to allow for overplots.
2196 my $tmp_hold = $self->held();
2197 unless ( $self->held() ) {
2198 my ($o, $u_opt) = $self->_parse_options($line_options,$opt);
2199 $self->_check_move_or_erase($o->{Panel}, $o->{Erase});
2200  
2201 # use Data::Dumper;
2202 # print Dumper $o;
2203 # print Dumper $u_opt;
2204  
2205 my ($ymin, $ymax, $xmin, $xmax);
2206 # Make sure the missing value is used as the min or max value
2207 if (defined $o->{Missing} ) {
2208 ($ymin, $ymax)=ref $o->{YRange} eq 'ARRAY' ?
2209 @{$o->{YRange}} : minmax($y->where($y != $o->{Missing}));
2210 ($xmin, $xmax)=ref $o->{XRange} eq 'ARRAY' ?
2211 @{$o->{XRange}} : minmax($x->where($x != $o->{Missing}));
2212 } else {
2213 ($ymin, $ymax)=ref $o->{YRange} eq 'ARRAY' ? @{$o->{YRange}} :
2214 minmax($y);
2215 ($xmin, $xmax)=ref $o->{XRange} eq 'ARRAY' ? @{$o->{XRange}} :
2216 minmax($x);
2217 }
2218 if ($xmin == $xmax) { $xmin -= 0.5; $xmax += 0.5; }
2219 if ($ymin == $ymax) { $ymin -= 0.5; $ymax += 0.5; }
2220 # use Data::Dumper;
2221 # print "tline options: ", Dumper($opt), "\n";
2222 $self->initenv( $xmin, $xmax, $ymin, $ymax, $opt);
2223 $self->hold; # we hold for the duration of the broadcasted plot
2224 }
2225 _tline($x, $y, PDL->sequence($y->getdim(1)), $self, $o);
2226 $self->release unless $tmp_hold;
2227 };
2228 }
2229 PDL::broadcast_define('_tline(a(n);b(n);ind()), NOtherPars => 2',
2230 PDL::over {
2231 my ($x, $y, $ind, $self, $opt)=@_;
2232 # use Data::Dumper;
2233 # print Dumper $opt->[$ind->at(0)];
2234 $self->line($x, $y,$opt->[$ind->at(0)] || {}); #
2235 });
2236  
2237 =head2 tpoints
2238  
2239 =for ref
2240  
2241 A broadcasted interface to points
2242  
2243 =for usage
2244  
2245 Usage: tpoints($x, $y, $options);
2246  
2247 This is a broadcasted interface to C<points>. This is convenient if you have
2248 a 2D array and want to plot out every line in one go. The routine will
2249 apply any options you apply in a "reasonable" way. In the sense that it
2250 will loop over the options wrapping over if there are less options than
2251 lines.
2252  
2253 Example:
2254  
2255 $h={Colour => ['Red', '1', 4], Linestyle => ['Solid' ,'Dashed']};
2256 $tx=zeroes(100,5)->xlinvals(-5,5);
2257 $ty = $tx + $tx->yvals;
2258 tpoints($tx, $ty, $h);
2259  
2260 =cut
2261  
2262 # A "broadcasted" point - I cannot come up with a more elegant way of doing
2263 # this without re-coding bits of broadcast_over but it might very well be
2264 # that you may :)
2265 my $points_options = undef;
2266 sub tpoints {
2267 my $self = shift;
2268 my ($in, $opt)=_extract_hash(@_);
2269 $self->_add_to_state(\&tpoints, $in, $opt);
2270 $opt={} if !defined($opt);
2271  
2272 barf 'Usage tpoints ([$x], $y, [, $options])' if $#$in < 0 || $#$in > 2;
2273 my ($x, $y)=@$in;
2274  
2275 if ($#$in==0) {
2276 $y = $x; $x = $y->xvals();
2277 }
2278  
2279 # This is very very cludgy, but it was the best way I could find..
2280 my $o = _broadcast_options($y->getdim(1), $opt);
2281 # We need to keep track of the current status of hold or not since
2282 # the tline function automatically enforces a hold to allow for overplots.
2283 my $tmp_hold = $self->held();
2284 unless ( $self->held() ) {
2285 if (!defined($points_options)) {
2286 $points_options = $self->{PlotOptions}->extend({PlotLine => 0});
2287 }
2288 my ($o, $u_opt) = $self->_parse_options($points_options,$opt);
2289 $self->_check_move_or_erase($o->{Panel}, $o->{Erase});
2290  
2291 # use Data::Dumper;
2292 # print Dumper $o;
2293 # print Dumper $u_opt;
2294  
2295 my ($ymin, $ymax, $xmin, $xmax);
2296 # Make sure the missing value is used as the min or max value
2297 if (defined $o->{Missing} ) {
2298 ($ymin, $ymax)=ref $o->{YRange} eq 'ARRAY' ?
2299 @{$o->{YRange}} : minmax($y->where($y != $o->{Missing}));
2300 ($xmin, $xmax)=ref $o->{XRange} eq 'ARRAY' ?
2301 @{$o->{XRange}} : minmax($x->where($x != $o->{Missing}));
2302 } else {
2303 ($ymin, $ymax)=ref $o->{YRange} eq 'ARRAY' ? @{$o->{YRange}} :
2304 minmax($y);
2305 ($xmin, $xmax)=ref $o->{XRange} eq 'ARRAY' ? @{$o->{XRange}} :
2306 minmax($x);
2307 }
2308 if ($xmin == $xmax) { $xmin -= 0.5; $xmax += 0.5; }
2309 if ($ymin == $ymax) { $ymin -= 0.5; $ymax += 0.5; }
2310 $self->initenv( $xmin, $xmax, $ymin, $ymax, $opt);
2311 $self->hold; # we hold for the duration of the broadcasted plot
2312 }
2313 _tpoints($x, $y, PDL->sequence($y->getdim(1)), $self, $o);
2314 $self->release unless $tmp_hold;
2315 }
2316 PDL::broadcast_define('_tpoints(a(n);b(n);ind()), NOtherPars => 2',
2317 PDL::over {
2318 my ($x, $y, $ind, $self, $opt)=@_;
2319 $self->points($x, $y, $opt->[$ind->at(0)] || {});
2320 });
2321  
2322 =head2 tcircle
2323  
2324 =for ref
2325  
2326 A broadcasted interface to circle
2327  
2328 =for usage
2329  
2330 Usage: tcircle($x, $y, $r, $options);
2331  
2332 This is a broadcasted interface to C<circle>. This is convenient if you have
2333 a list of circle centers and radii and want to draw every circle in one go.
2334 The routine will apply any options you apply in a "reasonable" way,
2335 in the sense that it will loop over the options wrapping over if there are less
2336 options than circles.
2337  
2338 Example:
2339  
2340 $x=sequence(5);
2341 $y=random(5);
2342 $r=sequence(5)/10 + 0.1;
2343 $h={justify => 1,Color => ['red','green','blue'], filltype => ['solid','outline','hatched','cross_hatched']};
2344 tcircle($x, $y, $r, $h);
2345  
2346 Note that C<$x> and C<$y> must be the same size (>1D is OK, though meaningless as far as C<tcircle> is concerned). C<$r> can be the same size as C<$x> OR a 1-element ndarray OR a single perl scalar.
2347  
2348 =cut
2349  
2350 my $circle_options = undef;
2351 sub tcircle {
2352 my $self = shift;
2353 my ($in, $opt)=_extract_hash(@_);
2354 $self->_add_to_state(\&tcircle,$in,$opt);
2355 $opt = {} if !defined($opt);
2356  
2357 barf 'Usage tcircle ($x,$y,$r,[$options])'
2358 if $#$in < 0 || $#$in > 3;
2359  
2360 my ($x, $y, $radius)=@$in;
2361 $x=$x->flat;$y=$y->flat;$radius=$radius->flat;
2362  
2363 if (!defined($circle_options)){
2364 $circle_options=$self->{PlotOptions}->extend({Missing => undef});
2365 }
2366  
2367 my $o = _broadcast_options($x->nelem,$opt);
2368 my $tmp_hold = $self->held();
2369  
2370 unless ( $self->held() ) {
2371 my ($o,$u_opt) = $self->_parse_options($circle_options,$opt);
2372 $self->_check_move_or_erase($o->{Panel},$o->{Erase});
2373  
2374 my ($ymin, $ymax, $xmin, $xmax);
2375  
2376 if ( defined $o->{Missing} ) {
2377 ($ymin, $ymax)=ref $o->{YRange} eq 'ARRAY' ?
2378 @{$o->{YRange}} : minmax($y->where($y != $o->{Missing}));
2379 ($xmin, $xmax)=ref $o->{XRange} eq 'ARRAY' ?
2380 @{$o->{XRange}} : minmax($x->where($x != $o->{Missing}));
2381 } else {
2382 ($ymin, $ymax)=ref $o->{YRange} eq 'ARRAY' ? @{$o->{YRange}} :
2383 (min($y-$radius),max($y+$radius));
2384 ($xmin, $xmax)=ref $o->{XRange} eq 'ARRAY' ? @{$o->{XRange}} :
2385 (min($x-$radius),max($x+$radius));
2386 }
2387 if ($xmin == $xmax) { $xmin-=0.5; $xmax +=0.5; }
2388 if ($ymin == $ymax) { $ymin-=0.5; $ymax +=0.5; }
2389  
2390 $self->initenv( $xmin, $xmax, $ymin, $ymax, $opt);
2391 $self->hold;
2392 }
2393  
2394 _tcircle($x,$y,$radius,PDL->sequence($x->nelem),$self,$o);
2395 $self->release unless $tmp_hold;
2396 }
2397 PDL::broadcast_define '_tcircle(a();b();c();ind()), NOtherPars => 2', sub {
2398 my ($x,$y,$r,$ind,$self,$opt)=@_;
2399 $self->circle($x,$y,$r,$opt->[$ind->at(0)] || {} );
2400 };
2401  
2402 =head2 Text routines
2403  
2404 =head2 text
2405  
2406 =for ref
2407  
2408 Write text in a plot window at a specified position.
2409  
2410 =for usage
2411  
2412 Usage: text ($text, $x, $y [, $opt])
2413  
2414 Options recognised:
2415  
2416 =over
2417  
2418 =item C<ANGLE>
2419  
2420 The angle in degrees between the baseline of the text and
2421 the horisontal (increasing counter-clockwise). This defaults to 0.
2422  
2423 =item C<JUSTIFICATION>
2424  
2425 The justification of the text relative to the position specified. It
2426 defaults to 0.0 which gives left-justified text. A value of 0.5 gives
2427 centered text and a value of 1.0 gives right-justified text.
2428  
2429 =item C<XPos>, C<YPos>, C<Text>
2430  
2431 These gives alternative ways to specify the text and position.
2432  
2433 =item C<BackgroundColour>
2434  
2435 This sets the background colour for the text in case an opaque background
2436 is desired. You can also use the synonyms C<Bg> and C<BackgroundColor>.
2437  
2438 =back
2439  
2440 The following standard options influence this command:
2441  
2442 COLOUR, CHARSIZE
2443  
2444 =for example
2445  
2446 line sequence(10), sequence(10)**2;
2447 text 'A parabola', 3, 9, {Justification => 1, Angle=>atan2(6,1)};
2448  
2449  
2450 =head2 legend
2451  
2452 =for ref
2453  
2454 Add a legend to a plot
2455  
2456 =for usage
2457  
2458 Usage: legend($text, $x, $y, [, $width], $opt]);
2459  
2460 This function adds a legend to an existing plot. The action is primarily
2461 controlled by information in the options hash, and the basic idea is that
2462 C<$x> and C<$y> determines the upper left hand corner of the box in which
2463 the legend goes. If the width is specified either as an argument or as
2464 an option in the option hash this is used to determine the optimal character
2465 size to fit the text into part of this width (defaults to 0.5 - see the
2466 description of C<TextFraction> below). The rest of the width is filled out with
2467 either lines or symbols according to the content of the C<LineStyle>,
2468 C<Symbol>, C<Colour> and C<LineWidth> options.
2469  
2470 The local options recognised are as follows:
2471  
2472 =over
2473  
2474 =item C<Text>
2475  
2476 An anonymous array of annotations, can also be specified directly.
2477  
2478 =item C<XPos> and C<YPos>
2479  
2480 The X and Y position of the upper left-hand corner of the text.
2481  
2482 =item C<Width> and C<Height>
2483  
2484 The width and/or height of each line (including symbol/line). This is
2485 used to determine the character size. If any of these are set to 'Automatic'
2486 the current character size will be used.
2487  
2488 =item C<TextFraction>
2489  
2490 The text and the symbol/line is set inside a box. C<TextFraction>
2491 determines how much of this box should be devoted to text. This
2492 defaults to 0.5. You can also use C<Fraction> as a synonym to this.
2493  
2494 =item C<TextShift>
2495  
2496 This option allows for fine control of the spacing between the text and the
2497 start of the line/symbol. It is given in fractions of the total width of the
2498 legend box. The default value is 0.1.
2499  
2500 =item C<VertSpace> or C<VSpace>
2501  
2502 By default the text lines are separated by one character height (in the sense that
2503 if the separation were 0 then they would lie on top of each other). The
2504 C<VertSpace> option allows you to increase (or decrease) this gap in units of
2505 the character height; a value of 0.5 would add half a character height to the
2506 gap between lines, and -0.5 would remove the same distance.
2507 The default value is 0.
2508  
2509 =item C<BackgroundColour>
2510  
2511 This sets the background colour for the text in case an opaque background
2512 is desired. You can also use the synonyms C<Bg> and C<BackgroundColor>.
2513  
2514  
2515 =back
2516  
2517 =for example
2518  
2519 line $x, $y, {Color => 'Red', LineStyle => 'Solid'};
2520 line $x2, $y2, {Color => 'Blue', 'LineStyle' => 'Dashed', LineWidth => 10};
2521  
2522 legend ['A red line', 'A blue line'], 5, 5,
2523 {LineStyle => ['Solid', 'Dashed'], Colour => ['Red', 'Blue']
2524 LineWidth => [undef, 10]}; # undef gives default.
2525  
2526  
2527 =head2 Cursor routines
2528  
2529 =head2 cursor
2530  
2531 =for ref
2532  
2533 Interactively read cursor positions.
2534  
2535 =for usage
2536  
2537 Usage: ($x, $y, $ch, $xref, $yref) = cursor($opt)
2538  
2539 This routine has no standard input parameters, but the type of cursor
2540 can be set by setting the option C<Type> as a key in the anonymous hash
2541 C<$opt>. The first three return values from the function are always
2542 defined and gives the position selected by the user and the character
2543 pressed.
2544  
2545 Depending on the cursor type selected the last two arguments might also
2546 be defined and these give a reference position. For instance if the cursor
2547 is selected to be C<Rectangle> then the reference position gives one of
2548 the corners of the rectangle and C<$x> and C<$y> the diagonally opposite
2549 one.
2550  
2551 Options recognised:
2552  
2553 =over
2554  
2555 =item XRef, YRef
2556  
2557 The reference position to be used
2558  
2559 =item Type
2560  
2561 The type of cursor. This can be selected using a number between 0 and 7 as
2562 in PGPLOT, or alternatively you can specify these as, C<Default> (0),
2563 C<RadialLine> (1), C<Rectangle> (2), C<TwoHorizontalLines> (3),
2564 C<TwoVerticalLines> (4), C<HorizontalLine> (5), C<VerticalLine> (6)
2565 and C<CrossHair> (7) respectively. The default cursor is just the normal
2566 mouse cursor.
2567  
2568 For the C<RadialLine> you I<must> specify the reference point, whereas for
2569 the C<Two(Vertical|Horizontal)Lines> cursor the X or Y reference point,
2570 respectively, must be specified.
2571  
2572 =back
2573  
2574 =for example
2575  
2576 To select a region on a plot, use the rectangle cursor:
2577  
2578 ($x, $y, $ch, $xref, $yref) = cursor({Type => 'Rectangle'});
2579 poly pdl($x, $xref, $xref, $x, $x), pdl($y, $y, $yref, $yref, $y);
2580  
2581 To select a region of the X-axis:
2582  
2583 ($x1, $y1, $ch) = cursor({Type => 'VerticalLine'});
2584 ($x2, $y2, $ch) = cursor({Type => 'TwoVerticalLines', XRef => $x1});
2585  
2586  
2587 =head1 Internal routines
2588  
2589 =cut
2590  
2591 ####
2592 # Helper routines to handle signal avoidance:
2593 # cpgplot doesn't take well to being interrupted, so we mask out INT
2594 # signals during most of the routines. But we do want to handle
2595 # those INTs, so we need a handler that marks 'em.
2596 #
2597 # You call catch_signals with the block to be executed. INT and __DIE__ signals
2598 # are sent to the signal_catcher, and released, not necessarily in
2599 # the order they occurred, by release_signals.
2600 #
2601 # The mechanism is a little over-powered for what we need -- but, hey,
2602 # if you want to defer any other signal you can simply add it to the
2603 # list in catch_signals.
2604 #
2605 # Don't try to parse arguments within catch_signals -- the omitted-() call
2606 # is extra fast but doesn't set @_!
2607 #
2608 # --CED 9-Aug-2002
2609 ####
2610  
2611 =head2 catch_signals
2612  
2613 To prevent pgplot from doing a fandango on core, we have to block interrupts
2614 during PGPLOT calls. Specifically, INT needs to get caught. These internal
2615 routines provide a mechanism for that.
2616  
2617 You simply bracket any PGPLOT calls with C<catch_signals>:
2618  
2619 catch_signals {
2620 ...
2621 pgcube($n, $x->get_dataref);
2622 };
2623  
2624 and the signal_catcher will queue up any
2625 signals (like INT -- the control-C interrupt) until the
2626 end of the block.
2627  
2628 =cut
2629  
2630 my %sig_log;
2631 my %sig_handlers;
2632 my $sig_nest = 0;
2633  
2634 sub signal_catcher {
2635 my($sig) = shift;
2636  
2637 if($sig eq '__DIE__') {
2638 return unless defined $^S; # Don't do anything during parsing of an eval
2639 $sig_nest = 1; # Unwrap all nests when dying
2640 &release_signals;
2641 &{$SIG{__DIE__}}($sig) if defined($SIG{__DIE__});
2642 return;
2643 }
2644  
2645 # Print message if debugging is on or on multiple INT signals
2646 if($PDL::debug || ($sig_log{$sig} && ($sig eq 'INT'))) {
2647 if($sig_log{$sig}==1) {
2648 warn "PDL::Graphics::PGPLOT: deferred $sig for PGPLOT; one more aborts operation\n";
2649 } else {
2650 warn "PDL::Graphics::PGPLOT: deferred $sig signal for PGPLOT operation (l=$sig_nest)\n"
2651 }
2652 }
2653  
2654 # Handle multiple INT signals (user pressing ^C a bunch)
2655 if(defined($sig_log{$sig}) && ($sig_log{$sig}>1) && ($sig eq 'INT')) {
2656 warn "Aborting PGPLOT operation".($PDL::debug ? " (may mess up future PGPLOT commands)\n" : "\n");
2657 $sig_nest = 1;
2658 &release_signals ;
2659 }
2660 else {
2661 $sig_log{$sig}++;
2662 }
2663 }
2664  
2665 sub catch_signals (&) {
2666 my ($block) = @_;
2667 my(@sigs) = ('INT');
2668 local($_, $@);
2669 if($sig_nest == 0) {
2670 foreach (@sigs) {
2671 next if ($SIG{$_}//'') ne 'DEFAULT' and ($SIG{$_}//0) == \&signal_catcher;
2672 $sig_handlers{$_}=$SIG{$_};
2673 $SIG{$_}=\&signal_catcher;
2674 }
2675 }
2676 $sig_nest++; # Keep track of nested calls.
2677 eval { $block->() };
2678 &release_signals;
2679 die $@ if $@;
2680 }
2681  
2682 sub release_signals {
2683 local($_);
2684 $sig_nest-- if($sig_nest > 0);
2685 return if($sig_nest > 0);
2686 # restore original handlers
2687 foreach $_(keys %sig_handlers) {
2688 no warnings; # allow assignment even if sig_handlers{$_} is undef
2689 $SIG{$_}=$sig_handlers{$_};
2690 delete $sig_handlers{$_};
2691 }
2692 # release signals
2693 foreach $_(keys %sig_log) {
2694 next unless $sig_log{$_};
2695 $sig_log{$_} = 0;
2696 kill $_,$$;
2697 }
2698 }
2699  
2700 #
2701 # Note: Here the general and window creation specific options are read in
2702 # from PGPLOTOptions. The $GeneralOptions variable is most importantly
2703 # used in the new() routine to set the general options for the window.
2704 #
2705 # These are somewhat confusingly named perhaps. The WindowOptions are the
2706 # options that affect window creation and setup such as width, shape etc.
2707 # The GeneralOptions are options that affect all function calls in the package
2708 # (or at least most) since it affects the default colour, character size etc.
2709 # The problematic aspect here is the treatment of hardcopy settings. For
2710 # historical reasons these are set in the WindowOptions variable but they
2711 # should affect settings in the GeneralOptions variable...
2712 # Ideally this should be re-coded, but to save some time I have instead opted
2713 # for a patchy solution where they are specially treated in the new_window
2714 # routine.
2715 #
2716 # Added 28/9/01 JB
2717 # Delay the intialization of the window options so that it is possible
2718 # to set the defaults in the .perldlrc file
2719 my ($GeneralOptions, $WindowOptions) = (undef, undef);
2720  
2721  
2722 my $PREVIOUS_DEVICE = undef;
2723 my $PI = 4*atan2(1,1);
2724 my $PREVIOUS_ENV = undef;
2725  
2726 my $AUTOLOG = 0;
2727  
2728  
2729 sub autolog {
2730 my $class = shift;
2731 my $ret;
2732 if (ref $class) {
2733 $ret = $class->{Autolog} || $AUTOLOG;
2734 $class->{Autolog} = shift if @_ > 0;
2735 } else {
2736 $ret = $AUTOLOG;
2737 $AUTOLOG = shift if @_ > 0;
2738 }
2739 return $ret;
2740 }
2741  
2742 sub checklog {
2743 my ($self,$x,$y) = @_;
2744 $x = $x->log10->float if defined $x && $self->autolog && $self->{Logx};
2745 $y = $y->log10->float if defined $y && $self->autolog && $self->{Logy};
2746 # print STDERR "Logx: ",$self->{Logx},"\n";
2747 # print STDERR "Logy: ",$self->{Logy},"\n";
2748 return ($x,$y);
2749 }
2750  
2751 sub pgwin {
2752 my(@a) = @_;
2753 # Since this is a convenience function, be convenient. If only
2754 # one parameter is passed in, assume that it's a device.
2755 if(!$#a && !(ref $a[0])){
2756 $a[0] = "/$a[0]" unless($a[0] =~ m:/:);
2757 unshift(@a,'Dev')
2758 }
2759  
2760 # If two parameters are passed in, and the second one is a hash,
2761 # then the first one is a device.
2762 if(scalar(@a) == 2 && ref $a[1] eq 'HASH') {
2763 $a[0] = "/$a[0]" unless($a[0] =~ m:/:);
2764 $a[1]->{Dev} = $a[0];
2765 @a = %{$a[1]};
2766 }
2767  
2768 # Furthermore, if an odd number of parameters are passed in,
2769 # then the first one is a device and the rest is intended to
2770 # be a parameters hash...
2771 if(scalar(@a) % 2) {
2772 $a[0] = "/$a[0]" unless($a[0] =~ m/:/);
2773 unshift(@a,'Dev');
2774 }
2775  
2776 return PDL::Graphics::PGPLOT::Window->new(@a);
2777 }
2778  
2779 my $dev;
2780 sub new {
2781 my $type = shift;
2782  
2783 # Set the default options!
2784 ($GeneralOptions, $WindowOptions) = default_options();
2785 # Turn off warnings for missing options...
2786 $GeneralOptions->warnonmissing(0);
2787 $WindowOptions->warnonmissing(0);
2788  
2789 # options are either given in a hash reference, or as a list
2790 # (which is converted to a hash reference to make the code easier)
2791 my $u_opt = ref($_[0]) eq "HASH" ? shift : { @_ };
2792  
2793 my $opt = $WindowOptions->options($u_opt);
2794 $WindowOptions->full_options(0);
2795 my $user_options = $WindowOptions->current();
2796 $WindowOptions->full_options(1);
2797  
2798 # If the user set DEVICE then that overrides anything else...
2799 if (exists $user_options->{Device}) {
2800 $dev = $opt->{Device}
2801 } elsif (!defined($dev) || $dev eq "") {
2802 $dev = $PREVIOUS_DEVICE || $opt->{Device};
2803 }
2804 $PREVIOUS_DEVICE = $dev;
2805  
2806 my $this_opt = PDL::Options->new($opt);
2807 my $t=$WindowOptions->translation();
2808 $this_opt->translation($t);
2809 my $s=$WindowOptions->synonyms();
2810 $this_opt->synonyms($s);
2811 $this_opt->warnonmissing(0);
2812  
2813 # This is the setup for the plot options - which also can
2814 # be set on a per-window basis by the user.
2815 my $popt = $GeneralOptions->options($u_opt);
2816 my $this_plotopt = PDL::Options->new($popt);
2817 $t = $GeneralOptions->translation();
2818 $this_plotopt->translation($t);
2819 $s = $GeneralOptions->synonyms();
2820 $this_plotopt->synonyms($s);
2821 $this_plotopt->warnonmissing(0);
2822  
2823 my $self = {
2824 'Options' => $this_opt,
2825 'PlotOptions' => $this_plotopt,
2826 'Hold' => $opt->{Hold} || 0,
2827 'Name' => $opt->{WindowName} || '',
2828 'ID' => undef,
2829 'AspectRatio' => $opt->{AspectRatio},
2830 'WindowWidth' => $opt->{WindowWidth},
2831 'NX' => $opt->{NXPanel} || 1,
2832 'NY' => $opt->{NYPanel} || 1,
2833 'Device' => $opt->{Device} || $dev,
2834 'CurrentPanel' => 0,
2835 '_env_options' => undef,
2836 'State' => undef,
2837 'Recording' => $opt->{Recording} || $PDL::Graphics::PGPLOT::RECORDING,
2838 'CTAB' => undef, # The default colour table
2839 };
2840  
2841 if (defined($self->{Options})) {
2842 # Turn off warnings about missing options
2843 $self->{Options}->warnonmissing(0);
2844 }
2845  
2846 bless $self, ref($type) || $type;
2847  
2848 $self->_open_new_window($opt);
2849 # This weird setup is required to create the object.
2850  
2851 # We always have to create a state variable to avoid undefined errors.
2852 $self->{State}=PDL::Graphics::State->new();
2853  
2854 return $self;
2855 }
2856  
2857 #
2858 # Graphics windows should be closed when they go out of scope.
2859 # Thanks to Doug Burke for pointing this out.
2860 #
2861 sub DESTROY {
2862  
2863 my $self=shift;
2864  
2865 $self->close() unless !defined($self->{ID});
2866 }
2867  
2868 =head2 _open_new_window
2869  
2870 Open a new window. This sets the window ID, which is the one used when
2871 accessing a window later using C<pgslct>. It also sets the window name
2872 to something easily remembered if it has not been set before.
2873  
2874 =cut
2875  
2876 sub _open_new_window {
2877 my $self = shift;
2878 my(@parameters) = @_;
2879  
2880 my $window_nr;
2881 catch_signals {
2882 $window_nr = pgopen($self->{Device});
2883 };
2884 barf("Opening new window (pgopen) failed: $window_nr\n")
2885 if ($window_nr < 0);
2886  
2887 $self->{ID} = $window_nr;
2888 $self->{Name} = "Window$window_nr" if $self->{Name} eq "";
2889  
2890 $self->_setup_window(@parameters);
2891 }
2892  
2893  
2894 =head2 _setup_window
2895  
2896 This routine sets up a new window with its shape and size. This is
2897 also where the size options are actually parsed. These are then
2898 forgotten (well, they are stored in $self->{Options}) and the
2899 corresponding aspect ratio and window width is stored. See the
2900 discussion under new() for the logic.
2901  
2902 Finally the subpanels are set up using C<pgsubp> and colours and linewidth
2903 are adjusted according to whether we have a hardcopy device or not.
2904  
2905 =cut
2906  
2907 # bit: 2=>height; 1=>width; 0=>aspect
2908 my $DefaultWindowWidth = 6;
2909 my $DefaultWindowAspect=0.618;
2910  
2911 # These are thunks to handle regularizing window values in _setup_window.
2912 # Index is binary by validity of value. 0 = undefined (or 0), 1 = ok.
2913 # Bit 0 = aspect, bit 1 = width, bit 2 = height. Arguments in the same order.
2914 # Return value is ($aspect, $height).
2915 #
2916 # If nothing is defined we try to grab the latest values from PGPLOT itself.
2917 my @__setup_subs = (
2918 sub { my($vs_x1,$vs_x2,$vs_y1,$vs_y2); # 0 (000)
2919 catch_signals {
2920 pgqvsz(1,$vs_x1,$vs_x2,$vs_y1,$vs_y2);
2921 };
2922 my($w) = ($vs_x2 - $vs_x1) || $DefaultWindowWidth;
2923 return ( ((($vs_y2 - $vs_y1) / $w) || $DefaultWindowAspect),
2924 $w
2925 );
2926 },
2927 sub { ($_[0], $DefaultWindowWidth / ($_[0]<1 ? 1 : $_[0])); },# 1 (001)
2928 sub { ($DefaultWindowAspect, $_[1]); }, # 2 (010)
2929 sub { @_; }, # 3 (011)
2930 sub { ($DefaultWindowAspect, $_[2] / $_[0]); }, # 4 (100)
2931 sub { ($_[0], $_[2] / $_[0]) }, # 5 (101)
2932 sub { ($_[2] / $_[1], $_[1]) }, # 6 (110)
2933 sub { ($_[2] / $_[1], $_[1] ) } # use W and H; ignore Aspect # 7 (111)
2934 );
2935  
2936 sub _setup_window {
2937 my $self = shift;
2938 my $opt = shift;
2939 # Get options as hash or as list
2940 if(ref $opt ne 'HASH') {
2941 $opt = {$opt,@_};
2942 }
2943  
2944 my $unit = _parse_unit($opt->{Unit}) || 1;
2945 my $aspect = $opt->{AspectRatio};
2946 my $width = $opt->{WindowXSize} || $opt->{WindowWidth};
2947 my $height = $opt->{WindowYSize};
2948  
2949 if(defined $opt->{Size}) {
2950 if(ref $opt->{Size} eq 'ARRAY') {
2951 $width = $opt->{Size}->[0];
2952 $height = $opt->{Size}->[1] || $width;
2953 $unit = _parse_unit($opt->{Size}->[2]) if defined($opt->{Size}->[2]);
2954 } elsif(!(ref $opt->{Size})) {
2955 $width = $height = $opt->{Size};
2956 } else {
2957 warn("Size must be a scalar or an array ref if specified! Ignoring...\n");
2958 }
2959 }
2960  
2961 my $subindex = ($aspect ? 1 : 0) +
2962 ($width ? 2 : 0) +
2963 ($height ? 4 : 0);
2964 @$self{qw(AspectRatio WindowWidth)} = ($aspect,$width) =
2965 $__setup_subs[$subindex]->($aspect,$width,$height);
2966  
2967 # PGPLOT seems not to include full unit support in (e.g.) the pgpap
2968 # command -- so check here and convert mm->inches if necessary.
2969 # This is a real kludge that should be replaced with Real Units Conversion
2970 # at a future date.
2971 #
2972 catch_signals {
2973 if($unit==2) { # mm -> inches
2974 $width /= 25.4;
2975 $height /= 25.4;
2976 } elsif($unit==3) { # pixels -> inches. Warning, not device independent!
2977 # What a kludge -- get window width in both pixels
2978 # and inches to figure out the scaling factor for
2979 # pgpap (which requires inches).
2980 my($x0,$x1,$y0,$y1);
2981 pgqvp(3,$x0,$x1,$y0,$y1);
2982 my($pixwidth) = $x1 - $x0;
2983 pgqvp(1,$x0,$x1,$y0,$y1);
2984 my($inwidth) = $x1 - $x0;
2985 my($pixperinch) = $pixwidth / $inwidth;
2986 $width /= $pixperinch;
2987 $height /= $pixperinch;
2988 } elsif($unit ==0 || $unit > 3) {
2989 warn("Invalid unit specification for window size; defaulting to inches.\n");
2990 }
2991  
2992 # OK, we got a decent size. Now call pgpap to set the size in the
2993 # device, and (for interactive devices!) pgpag to get the size we
2994 # want -- otherwise the window just hangs around looking lame at the
2995 # default size instead of the size the user asked for. We also have
2996 # to turn PGASK off so the user doesn't get asked to hit "return".
2997 # Afterwards, we turn it back on because that's the default state.
2998 # (although it is set to 0 again pretty soon)
2999 #
3000 pgqinf('HARDCOPY',my $hcopy,my $len);
3001 pgpap($width, $aspect);
3002 if($hcopy eq 'NO') {
3003 pgask(0);
3004 pgpage();
3005 pgask(1);
3006 }
3007  
3008 # Now do the sub-division into panels.
3009 my $nx = $self->{NX};
3010 my $ny = $self->{NY};
3011 if ($nx < 0) {
3012 warn "We do not support the alternative numbering of panels of PGPLOT!\n";
3013 $nx = abs($nx);
3014 $self->{NX}=abs($self->{NX});
3015 }
3016 pgsubp($nx, $ny);
3017  
3018 # Setup the colours
3019 my $o = $self->{Options}->current();
3020 pgask(0);
3021 if ($hcopy eq "YES") {
3022 # This has changed to set the defaults instead.
3023 pgslw($o->{HardLW});
3024 pgsch($o->{HardCH});
3025 pgscf($o->{HardFont});
3026 # To change defaults you first need to read them out and then
3027 # adjust them and set them again
3028 my $temp_wo = $self->{PlotOptions}->defaults();
3029 $temp_wo->{Font}= $o->{HardFont};
3030 $temp_wo->{CharSize}= $o->{HardCH};
3031 $temp_wo->{LineWidth}= $o->{HardLW};
3032 $temp_wo->{Colour}= $o->{HardColour};
3033 $self->{PlotOptions}->defaults($temp_wo);
3034 my $temp_o=$self->{Options}->defaults();
3035 $temp_o->{AxisColour}=$o->{HardAxisColour};
3036 $temp_o->{CharSize}=$o->{HardCH};
3037 $self->{Options}->defaults($temp_o);
3038 } else {
3039 # Set the global properties as for the hardcopy device.
3040 pgsch($o->{CharSize});
3041 my $wo = $self->{PlotOptions}->defaults();
3042 pgscf($wo->{Font});
3043 pgslw($wo->{LineWidth});
3044 }
3045  
3046 my $wo = $self->{PlotOptions}->defaults();
3047 $self->_set_colour($wo->{Colour});
3048 pgask(0);
3049 };
3050 }
3051  
3052 sub _set_defaults { # Set up defaults
3053  
3054 # Now check if this is a hardcopy device, in which case we
3055 # set a variety of properties differently.
3056 my $self = shift;
3057  
3058 }
3059  
3060  
3061  
3062  
3063 =head2 _status
3064  
3065 This routine checks PGPLOT's status for the window. It returns OPEN if
3066 the window is open and CLOSED if it is closed. (Windows can be closed
3067 but still exist).
3068  
3069 =cut
3070  
3071 sub _status {
3072 my $self=shift;
3073 $self->focus();
3074 my ($state, $len);
3075 catch_signals {
3076 pgqinf('STATE',$state,$len);
3077 };
3078 return $state;
3079 }
3080  
3081 =head2 _reopen
3082  
3083 This functions reopens a window. Since this is an internal function it does
3084 not have a lot of error-checking. Make sure the device is closed I<before>
3085 calling this routine.
3086  
3087 There is an unfortunate problem which pops up viz. that the window name
3088 cannot be changed at this point since we are offering that to the rest of
3089 the world. That might be sensible, but it means that the window name will
3090 not reflect the id of the window - use C<id()> for that (this is also why
3091 we do not call C<open_new_window> )
3092  
3093 =cut
3094  
3095 sub _reopen {
3096 my @parameters = @_;
3097 my $self = shift;
3098  
3099 my $window_nr;
3100 catch_signals {
3101 $window_nr = pgopen($self->{Device});
3102 };
3103  
3104 barf("Opening new window (pgopen) failed: $window_nr\n")
3105 if ($window_nr < 0);
3106  
3107 $self->{ID} = $window_nr;
3108  
3109 $self->_setup_window(@parameters);
3110 }
3111  
3112  
3113 =head2 _advance_panel
3114  
3115 This routine advances one plot panel, updating the CurrentPanel as well.
3116 If the advance will proceed past the page the page will be erased. Also
3117 note that when you advance one panel the hold value will be changed.
3118  
3119 =cut
3120  
3121 sub _advance_panel {
3122 my $self = shift;
3123  
3124 my $new_panel = $self->{CurrentPanel}+1;
3125 if ($new_panel > ($self->{NX}*$self->{NY})) {
3126 # We are at the end of the page..
3127 $new_panel = 1;
3128 $self->clear_state();
3129 catch_signals {
3130 pgpage();
3131 };
3132 }
3133  
3134  
3135 $self->panel($new_panel);
3136 if ($self->held()) {
3137 $self->{Hold}=0;
3138 print "Graphic released (panel move)\n" if $PDL::verbose;
3139 }
3140 }
3141  
3142  
3143 =head2 _check_move_or_erase
3144  
3145 This routine is a utility routine which checks if we need to move panel,
3146 and if so will do this. It also checks if it is necessary to advance panels,
3147 and whether they need to be erased.
3148  
3149 =cut
3150  
3151 sub _check_move_or_erase {
3152 my $self=shift;
3153 my ($panel, $erase)=@_;
3154  
3155 catch_signals {
3156 my $sid; pgqid($sid);
3157 # Only perform a pgslct if necessary.
3158 pgslct($self->{ID}) unless $sid == $self->{ID};
3159 };
3160  
3161 if (defined($panel)) {
3162 $self->panel($panel);
3163 } elsif (!$self->held()) {
3164 # If no hold has been set.
3165 $self->_advance_panel();
3166 }
3167  
3168 $self->erase() if $erase;
3169 }
3170  
3171  
3172 =head2 _broadcast_options
3173  
3174 This function is a cludgy utility function that expands an options hash
3175 to an array of hashes looping over options. This is mainly of use for
3176 "broadcasted" interfaces to standard plotting routines.
3177  
3178 =cut
3179  
3180  
3181 sub _broadcast_options {
3182 my ($n, $h) = @_;
3183  
3184 # Loop over each option.
3185 my @hashes=(); # One for each option.
3186 my @keys = keys %$h;
3187 foreach my $k (@keys) {
3188 my @vals=();
3189 my $v=$h->{$k};
3190 $v = [$v] if ref($v) ne 'ARRAY';
3191 while ($#vals+1 < $n) {
3192 splice(@vals, @vals, 0, @$v);
3193 }
3194 for (my $i=0; $i<$n; $i++) {
3195 $hashes[$i]->{$k}=$vals[$i];
3196 }
3197 }
3198 return \@hashes;
3199 }
3200  
3201 ############################
3202 # Replay related functions #
3203 ############################
3204  
3205 my $DEBUGSTATE = 0;
3206  
3207 sub debug_state {
3208 $DEBUGSTATE = !$DEBUGSTATE;
3209 }
3210  
3211 sub replay {
3212 my $self = shift;
3213 my $state = shift || $self->{State};
3214 die "A state object must be defined to play back commands!\n"
3215 if !defined $state;
3216  
3217 my @list = $state->get();
3218  
3219  
3220 if ($#list < 0) {
3221 # If there are no commands, then the user might have forgotten to
3222 # turn on recording, let us remind them
3223  
3224 warn "Replaying an empty state - did you turn on recording?\n";
3225 print "Hint: Put PDL::Graphics::PGPLOT::RECORDING=1 in your .perldlrc file\n"
3226 }
3227  
3228 catch_signals {
3229 foreach my $arg (@list) {
3230 my ($command, $commandname, $arg, $opt)=@$arg;
3231 &$command($self, @$arg, $opt);
3232 }
3233 };
3234 }
3235  
3236  
3237 sub clear_state {
3238 my $self = shift;
3239 print "Clearing state!\n" if $DEBUGSTATE;
3240 $self->{State}->clear() if(defined($self) && defined($self->{State}));
3241 }
3242  
3243 sub turn_off_recording {
3244 my $self=shift;
3245 # Turning off does _NOT_ clear the state at the moment!
3246 $self->{Recording} =0;
3247 print "Turning off state!\n" if $DEBUGSTATE;
3248 }
3249 sub turn_on_recording {
3250 my $self=shift;
3251 # Previous calls are not recorded of course..
3252 print "Turning on state!\n" if $DEBUGSTATE;
3253 $self->{Recording} = 1;
3254 $self->{State}=PDL::Graphics::State->new() unless defined($self->{State});
3255 }
3256  
3257 sub _add_to_state {
3258 my $self=shift;
3259 my ($func, $arg, $opt)=@_;
3260 my ($pkg, $fname, $line, $funcname, $hasargs, $wantarray,
3261 $evaltext, $isrequire, $hints, $bitmask)=caller(1);
3262 # We only add if recording has been turned on.
3263 print "Adding to state ! $func, $arg, $opt\n" if $DEBUGSTATE;
3264 print "State = ".$self->{State}."\n" if $DEBUGSTATE;
3265 $self->{State}->add($func, $funcname, $arg, $opt) if $self->{Recording};
3266 }
3267  
3268 sub retrieve_state {
3269 my $self=shift;
3270 my $state_copy = $self->{State}->copy();
3271 print "Retriving state!\n" if $DEBUGSTATE;
3272 return $state_copy;
3273 }
3274  
3275  
3276 #####################################
3277 # Window related "public" routines. #
3278 #####################################
3279  
3280 sub close {
3281 my $self=shift;
3282 # let the user know that we've created a file
3283 if ( $self->_status() eq 'OPEN' ) {
3284 my @info = $self->info( 'HARDCOPY', 'FILE' );
3285 print "Created: $info[1]\n" if $info[0] eq 'YES' and $PDL::verbose;
3286 pgclos();
3287 }
3288 $self->{ID}=undef;
3289 $self->clear_state();
3290 }
3291  
3292 =head2 options
3293  
3294 Access the options used when I<originally> opening the window. At the moment
3295 this is not updated when the window is changed later.
3296  
3297 =cut
3298  
3299 sub options {
3300 return $_[0]->{Options};
3301 }
3302  
3303 =head2 id
3304  
3305 Access the window ID that PGPLOT uses for the present window.
3306  
3307 =cut
3308  
3309 sub id {
3310 return $_[0]->{ID};
3311 }
3312  
3313 =head2 device
3314  
3315 This function returns the device type of the present window.
3316  
3317 =cut
3318  
3319 sub device {
3320 return $_[0]->{Device};
3321 }
3322  
3323 =head2 name
3324  
3325 Accessor to set and examine the name of a window.
3326  
3327 =cut
3328  
3329 sub name {
3330 my $self=shift;
3331 if ($#_>=0) {
3332 $self->{Name}=$_[0];
3333 }
3334 return $self->{Name};
3335 }
3336  
3337 =head2 focus
3338  
3339 Set focus for subsequent PGPLOT commands to this window.
3340  
3341 =cut
3342  
3343 sub focus {
3344 my $self=shift;
3345 return if !defined($self->{ID});
3346  
3347 catch_signals {
3348 my $sid; pgqid($sid);
3349 # Only perform a pgslct if necessary.
3350 pgslct($self->{ID}) unless $sid == $self->{ID};
3351 };
3352 }
3353  
3354  
3355 sub hold {
3356 my $self=shift;
3357 $self->{Hold}=1;
3358 $self->_add_to_state(\&hold);
3359 return $self->{Hold};
3360 }
3361  
3362  
3363 sub release {
3364 my $self=shift;
3365 $self->{Hold}=0;
3366 $self->_add_to_state(\&release);
3367 return $self->{Hold};
3368 }
3369  
3370  
3371 sub held {
3372 my $self = shift;
3373 return $self->{Hold};
3374 }
3375  
3376  
3377  
3378  
3379 =head2 info
3380  
3381 =for ref
3382  
3383 Get general information about the PGPLOT environment.
3384  
3385 =for usage
3386  
3387 @ans = $self->info( @item );
3388  
3389 The valid values of C<@item> are as below, where case is not
3390 important:
3391  
3392 VERSION - What PGPLOT version is in use.
3393 STATE - The status of the output device, this is returns 'OPEN'.
3394 if the device is open and 'CLOSED' otherwise.
3395 USER - The username of the owner of the spawning program.
3396 NOW - The current date and time in the format
3397 'dd-MMM-yyyy hh:mm'. Most people are likely to use Perl
3398 functions instead.
3399 DEVICE * - The current PGPLOT device or file, see also device().
3400 FILE * - The filename for the current device.
3401 TYPE * - And the device type for the current device.
3402 DEV/TYPE * - This combines DEVICE and TYPE in a form that can be used
3403 as input to new.
3404 HARDCOPY * - This is flag which is set to 'YES' if the current device is
3405 a hardcopy device and 'NO' otherwise.
3406 TERMINAL * - This flag is set to 'YES' if the current device is the
3407 user's terminal and 'NO' otherwise.
3408 CURSOR * - A flag ('YES' or 'NO') to inform whether the current device
3409 has a cursor.
3410  
3411 Those items marced with a C<*> only return a valid answer if
3412 the window is open. A question mark (C<?>) is returned
3413 if the item is not recognised or the information is not available.
3414  
3415 =cut
3416  
3417 #'
3418  
3419 sub info {
3420 my $self = shift;
3421 my @inq = wantarray ? @_ : $_[0];
3422  
3423 $self->focus();
3424 my @ans;
3425 catch_signals {
3426 foreach my $inq ( @inq ) {
3427 my ( $state, $len );
3428 pgqinf( uc($inq), $state, $len );
3429 push @ans, $state;
3430 }
3431 };
3432 return wantarray() ? @ans : $ans[0];
3433 } # info()
3434  
3435 sub panel {
3436  
3437 my $self = shift;
3438  
3439 $self->focus();
3440 my ($xpos, $ypos);
3441 if ($#_ == 1) {
3442 # We have gotten $x and $y..
3443 ($xpos, $ypos)=@_;
3444 } elsif ($#_ == 0 && ref($_[0]) eq 'ARRAY' ) {
3445 ($xpos, $ypos)=@{$_[0]};
3446 } elsif ($#_ == 0) {
3447 # We have been given a single number... This can be converted
3448 # to a X&Y position with a bit of calculation. The code is taken
3449 # from one2nd.
3450 barf("panel: Panel numbering starts at 1, not 0\n")
3451 if($_[0]<=0);
3452  
3453 my $i=$_[0]-1; # Offset code is 0-based (of course)
3454 $xpos = $i % $self->{NX};
3455 $i = long($i/$self->{NX});
3456 $ypos=$i % $self->{NY};
3457 $xpos++; $ypos++; # Because PGPLOT starts at 1..
3458 } else {
3459 barf <<'EOD';
3460 Usage: panel($xpos, $ypos); or
3461 panel([$xpos, $ypos]); or
3462 panel($index);
3463 EOD
3464 }
3465  
3466 # We do not subtract 1 from X because we would need to add it again to
3467 # have a 1-offset numbering scheme.
3468 $self->{CurrentPanel} = ($ypos-1)*$self->{NX}+($xpos);
3469 $self->_add_to_state(\&panel, $xpos, $ypos);
3470 catch_signals {
3471 pgpanl($xpos, $ypos);
3472 };
3473 }
3474  
3475  
3476 {
3477 # To save space and time..
3478 my $erase_options = undef;
3479 sub erase {
3480 my $self = shift;
3481  
3482 # Parse options
3483 my $u_opt = shift;
3484 if (defined($u_opt) && ref($u_opt) eq 'HASH') {
3485 $erase_options = PDL::Options->new({Panel => undef}) if
3486 !defined($erase_options);
3487 my $o = $erase_options->options($u_opt);
3488 # Change panel if requested
3489 $self->panel($o->{Panel}) if defined($o->{Panel});
3490 } elsif (defined($u_opt)) {
3491 # The user has passed a number of reference to array..
3492 $self->panel($u_opt);
3493 }
3494  
3495 $self->focus();
3496 # What should I do with the state here????
3497 catch_signals {
3498 pgeras();
3499 };
3500 $self->_add_to_state(\&erase, [], $u_opt);
3501 # Remove hold.
3502 $self->{Hold}=0;
3503 }
3504 }
3505  
3506  
3507 ##
3508 ## Utility functions
3509 ##
3510  
3511 =head2 _extract_hash
3512  
3513 This routine takes and array and returns the first hash reference found as
3514 well as those elements that are I<not> hashes. Note the latter point because
3515 all other references to hashes in the array will be lost.
3516  
3517 =cut
3518  
3519 sub _extract_hash {
3520 my @opt=@_;
3521 #
3522 # Given a list, returns a list of hash references and all the rest.
3523 #
3524 my $count=0;
3525 my $hashes=[];
3526 foreach (@opt) {
3527 push @$hashes, splice(@opt, $count, 1) if ref($_) eq 'HASH';
3528 $count++
3529 }
3530 return (\@opt, $$hashes[0]);
3531 }
3532  
3533 =head2 _parse_unit
3534  
3535 Convert a unit string or number into a PGPLOT-certified length unit
3536 specification, or return undef if it won't go.
3537  
3538 =cut
3539  
3540 my @__unit_match = (
3541 qr/^((\s*0)|(n(orm(al(ized)?)?)?))\s*$/i,
3542 qr/^((\s*1)|(i(n(ch(es)?)?)?))\s*$/i,
3543 qr/^((\s*2)|(m(m|(illimeter))?s?))\s*$/i,
3544 qr/^((\s*3)|(p(ix(el)?)?s?))\s*$/i
3545 );
3546  
3547 sub _parse_unit {
3548 # I'm assuming returning undef when $u is undefined is a good thing to do (DJB; 06/28/02)
3549 my $u = shift || return undef;
3550 # print "parse_unit: got '$u'\n";
3551 for my $i (0..$#__unit_match) {
3552 return $i if($u =~ m/$__unit_match[$i]/);
3553 }
3554 return undef;
3555 }
3556  
3557 =head2 _parse_options
3558  
3559 This is a convenience routine for parsing a set of options. It returns
3560 both the full set of options and those that the user has set.
3561  
3562 =cut
3563  
3564 sub _parse_options {
3565  
3566 my $self=shift;
3567 my ($opt, $oin)=@_;
3568  
3569 ## Should do something sensible if $opt is no options object f.i.
3570 if (defined($oin) && ref($oin) ne 'HASH') {
3571 my ($package, $file, $line, $sub)=caller(1);
3572 barf "_parse_options called by $sub with non-hash options element!";
3573 } elsif (!defined($oin)) {
3574 my ($package, $file, $line, $sub)=caller(1);
3575 warn "_parse_options called by $sub without an options hash! - continuing\n";
3576 $oin = {};
3577 }
3578 my $o=$opt->options($oin);
3579 $opt->full_options(0);
3580 my $uo=$opt->current();
3581 $opt->full_options(1);
3582  
3583 $opt->clear_current();
3584  
3585 return ($o, $uo);
3586  
3587 }
3588  
3589  
3590 ################################################################
3591 #
3592 # GRAPHICS FUNCTIONS below!
3593 #
3594 ################################################################
3595  
3596 ############ Local functions #################
3597  
3598 =head2 _save_status
3599  
3600 Saves the PGPLOT state so that changes to settings can be made and then
3601 the present state restored by C<_restore_status>.
3602  
3603 =cut
3604  
3605 sub _save_status {
3606 my $self=shift;
3607 catch_signals {
3608 pgsave;
3609 } if $self->_status() eq 'OPEN';
3610 }
3611  
3612 =head2 _restore_status
3613  
3614 Restore the PGPLOT state. See L</_save_status>.
3615  
3616 =cut
3617  
3618 sub _restore_status {
3619 my $self=shift;
3620 catch_signals {
3621 pgunsa;
3622 } if $self->_status() eq 'OPEN';
3623 }
3624  
3625  
3626  
3627 =head2 _checkarg
3628  
3629 This routine checks and optionally alters the arguments given to it.
3630  
3631 =cut
3632  
3633 sub _checkarg { # Check/alter arguments utility
3634 my $self = shift;
3635 my ($arg,$dims,$type,$nobarf) = @_;
3636 $type = $PDL_F unless defined $type;
3637  
3638 # nobarf added so the end-user can choose whether to die or not..x
3639 $nobarf = 0 unless defined($nobarf);
3640 my $ok = 1;
3641  
3642 $arg = topdl($arg); # Make into a pdl
3643 $arg = convert($arg,$type) if $arg->get_datatype != $type;
3644 if (($arg->getndims > $dims)) {
3645 # Get the dimensions, find out which are == 1. If it helps
3646 # chuck these off and return trimmed ndarray.
3647 my $n=nelem(which(pdl($arg->dims)==1));
3648 if (($arg->getndims-$n) > $dims) {
3649 $ok = 0;
3650 barf "Data is >".$dims."D" unless $nobarf;
3651 } else {
3652 my $count=0; my $qq;
3653 my $s=join ',',
3654 map {if ($_ == 1 && $count<$arg->getndims-$dims) {$qq='(0)'; $count++}
3655 else {
3656 $qq= '';
3657 }
3658 ; $qq} $arg->dims;
3659 $arg=$arg->slice($s);
3660 }
3661 }
3662 $_[0] = $arg if $ok; # Alter
3663  
3664 return $ok;
3665 }
3666  
3667 # a hack to store information in the object.
3668 # Currently only used by imag() for storing information
3669 # useful to draw_wedge().
3670 #
3671 # This routine needs changing:
3672 # . store values using PDL::Options, so you can update rather than overwrite
3673 # . associate the information with a particular window/panel/whatever
3674 # . clear information when plot erased (correct for current use by imag(),
3675 # but maybe not in more general cases?)
3676 #
3677 # The API is liable to change: you have been warned (Doug Burke)
3678 #
3679 sub _store {
3680 my $self = shift;
3681 barf 'Usage: _store( $self, $name, $item )' unless $#_ == 1;
3682  
3683 my $name = shift;
3684 my $object = shift;
3685  
3686 # create storage space, if needed
3687 $self->{_horrible_storage_space} = {}
3688 unless defined $self->{_horrible_storage_space};
3689  
3690 # store data
3691 $self->{_horrible_storage_space}{$name} = $object;
3692  
3693  
3694 } # sub: _store()
3695  
3696 # retrieve information from storage space
3697 # - same caveats as with _store()
3698 #
3699 sub _retrieve {
3700 my $self = shift;
3701 barf 'Usage: _retrieve( $self, $name )' unless $#_ == 0;
3702  
3703 my $name = shift;
3704  
3705 barf "Internal error: no storage space in object"
3706 unless exists $self->{_horrible_storage_space};
3707  
3708 if ( exists $self->{_horrible_storage_space}{$name} ) {
3709 return $self->{_horrible_storage_space}{$name};
3710 } else {
3711 return undef;
3712 }
3713  
3714 } # sub: _retrieve()
3715  
3716 ##################
3717 # Options parser #
3718 ##################
3719  
3720  
3721  
3722 =head2 _set_colour
3723  
3724 This is an internal routine that encapsulates all the nastiness of
3725 setting colours depending on the different PGPLOT colour models (although
3726 HLS is not supported).
3727  
3728 The routine works in the following way:
3729  
3730 =over 8
3731  
3732 =item *
3733  
3734 At initialisation of the plot device the work colour index is set
3735 to 16. The work index is the index the routine will modify unless the
3736 user has specified something else.
3737  
3738 =item *
3739  
3740 The routine should be used after standard interpretation and synonym
3741 matching has been used. So if the colour is given as input is an integer
3742 that colour index is used.
3743  
3744 =item *
3745  
3746 If the colour is a reference the routine checks whether it is an
3747 C<ARRAY> or a C<PDL> reference. If it is not an error message is given.
3748 If it is a C<PDL> reference it will be converted to an array ref.
3749  
3750 =item *
3751  
3752 If the array has four elements the first element is interpreted
3753 as the colour index to modify and this overrules the setting for the
3754 work index used internally. Otherwise the work index is used and incremented
3755 until the maximum number of colours for the output device is reached
3756 (as indicated by C<pgqcol>). Should you wish to change that you need
3757 to read the PGPLOT documentation - it is somewhat device dependent.
3758  
3759 =item *
3760  
3761 When the array has been recognised the R,G and B colours of the
3762 user-set index or work index is set using the C<pgscr> command and we
3763 are finished.
3764  
3765 =item *
3766  
3767 If the input colour instead is a string we try to set the colour
3768 using the PGPLOT routine C<pgscrn> with no other error-checking. This
3769 should be ok, as that routine returns a rather sensible error-message.
3770  
3771 =back
3772  
3773 =cut
3774  
3775 {
3776 my $work_ci = 16;
3777  
3778 sub _set_colour {
3779 my $self = shift;
3780 my ($col, $is_textbg) = @_;
3781 $is_textbg = 0 if !defined($is_textbg);
3782  
3783 catch_signals {
3784 # The colour index to use for user changes.
3785 # This is increased until the max of the colour map.
3786 # I don't know if this can change, but let's not take any
3787 # chances.
3788 my ($min_col, $max_col);
3789 pgqcol($min_col, $max_col);
3790  
3791 #
3792 # Extended treatment of colours - added 2/10/01 JB.
3793 #
3794 if (ref($col)) {
3795 if ((ref($col) eq 'PDL') or (ref($col) eq 'ARRAY')) {
3796 my @colvals = (ref($col) eq 'PDL' ? list($col) : @{$col});
3797 my ($red, $green, $blue)=@colvals;
3798 my $index = $work_ci;
3799 if ($#colvals == 3) {
3800 # This is a situation where the first element is interpreted
3801 # as a PGPLOT colour index, otherwise we will use our own
3802 # strategy to step through indices.
3803 ($index, $red, $green, $blue)=@colvals;
3804 } else {
3805 $work_ci += 1;
3806 # NB this does not work on devices with < 16 colours.
3807 $work_ci = 16 if $work_ci > $max_col;
3808 }
3809 pgscr($index, $red, $green, $blue);
3810  
3811 if ($is_textbg) {
3812 pgstbg($index);
3813 } else {
3814 pgsci($index);
3815 }
3816 } else {
3817 warn "The colour option must be a number, string, array or PDL!\n";
3818 }
3819 } else {
3820 # Now check if this is a name that could be recognised by pgscrn.
3821 # To simplify the logic we first check if $col is a digit.
3822 if ($col =~ m/^\s*\d+\s*$/) {
3823 if ($is_textbg) {
3824 pgstbg($col);
3825 } else {
3826 pgsci($col);
3827 }
3828 } else {
3829 #
3830 # Ok, we either have an untranslated colour name or something
3831 # bogus - let PGPLOT deal with that!
3832 #
3833 my $ier;
3834 pgscrn($work_ci, $col, $ier);
3835 if ($is_textbg) {
3836 pgstbg($work_ci);
3837 } else {
3838 pgsci($work_ci);
3839 }
3840 $work_ci += 1;
3841 # NB this does not work on devices with < 16 colours.
3842 $work_ci = 16 if $work_ci > $max_col;
3843 }
3844 }
3845 };
3846 }
3847 }
3848  
3849  
3850 =head2 _standard_options_parser
3851  
3852 This internal routine is the default routine for parsing options. This
3853 routine deals with a subset of options that most routines will accept.
3854  
3855 =cut
3856  
3857 sub _standard_options_parser {
3858 #
3859 # Parse the options and act on the values set.
3860 #
3861 my $self=shift;
3862 my ($o)=@_;
3863 #
3864 # The input hash has to contain the options _set by the user_
3865 #
3866 $self->_set_colour($o->{Colour}) if (exists($o->{Colour}));
3867 catch_signals {
3868 pgsls($o->{LineStyle}) if exists($o->{LineStyle});
3869 pgslw($o->{LineWidth}) if exists($o->{LineWidth});
3870 pgscf($o->{Font}) if exists($o->{Font});
3871 pgsch($o->{CharSize}) if exists($o->{CharSize});
3872 pgsfs($o->{Fill}) if exists($o->{Fill});
3873 # pgsch($o->{ArrowSize}) if exists($o->{ArrowSize});
3874 # Two new options..
3875  
3876  
3877 my $wo = $self->{PlotOptions}->defaults(); # Window defaults - for some routines below
3878  
3879 # We just need special treatment of the Arrow and Hatch options,
3880 # and they are complex for historical reasons...
3881  
3882 if (exists($o->{Arrow})) {
3883 #
3884 # Set the arrow. The size can be set either independently
3885 # using ARROWSIZE or in the hash
3886 #
3887 # Note the use of $wo to get the true default values here!
3888 my ($fs, $angle, $vent)=($wo->{Arrow}{FS}, $wo->{Arrow}{Angle},
3889 $wo->{Arrow}{Vent});
3890 my $arrowsize = $o->{CharSize}; # Default to the character size..
3891 if (ref($o->{Arrow}) eq 'HASH') {
3892 while (my ($var, $value)=each %{$o->{Arrow}}) {
3893 # options are FS, ANGLE, VENT, SIZE
3894 # but SIZE may be ARROWSIZE [see ../PGPLOTOptions.pm]
3895 $fs=$value if $var =~ m/^F/i;
3896 $vent=$value if $var =~ m/^V/i;
3897 $angle=$value if $var =~ m/^AN/i;
3898 # not sure about how correct this is, but it stops 'use of undefined'
3899 # variable (for $angle) in pgsah() call below
3900 $arrowsize=$value if $var =~ m/^S/i or $var =~ m/^AR/i;
3901 }
3902 } else {
3903 $fs=$o->{Arrow}[0] if defined $o->{Arrow}[0];
3904 $angle=$o->{Arrow}[1] if defined $o->{Arrow}[1];
3905 $vent=$o->{Arrow}[2] if defined $o->{Arrow}[2];
3906 $arrowsize=$o->{Arrow}[3] if defined $o->{Arrow}[3];
3907 }
3908 pgsch($arrowsize) if defined($arrowsize);
3909 pgsah($fs, $angle, $vent);
3910 }
3911  
3912 if (exists($o->{Hatch})) {
3913 my $val = $o->{Hatch};
3914 if (!defined($val) || lc($val) eq 'default') {
3915 pgshs(); # Default values are either specified by HATCH=>undef or HATCH=>'default'
3916 } else {
3917 #
3918 # Can either be specified as numbers or as a hash...
3919 #
3920 # Note the use of $wo to get the true default values!!
3921 #
3922 my ($angle, $separation, $phase)=
3923 ($wo->{Hatch}{Angle}, $wo->{Hatch}{Separation}, $wo->{Hatch}{Phase});
3924  
3925 if (ref($val) eq 'HASH') {
3926 while (my ($var, $value) = each %{$val}) {
3927 $angle=$value if $var =~ m/^A/i;
3928 $separation=$value if $var =~ m/^S/i;
3929 $phase=$value if $var =~ m/^P/i;
3930 }
3931 } else {
3932 $angle=$$val[0] if defined($$val[0]);
3933 $separation=$$val[1] if defined($$val[1]);
3934 $phase=$$val[2] if defined($$val[2]);
3935 }
3936 if ($separation==0) {
3937 warn "The separation of hatch lines cannot be zero, the default of".
3938 $wo->{Hatch}{Separation} . " is used!\n";
3939 $separation=$wo->{Hatch}{Separation};
3940 }
3941 pgshs($angle,$separation, $phase);
3942 }
3943 }
3944 };
3945 }
3946  
3947 # initenv( $xmin, $xmax, $ymin, $ymax, $just, $axis )
3948 # initenv( $xmin, $xmax, $ymin, $ymax, $just )
3949 # initenv( $xmin, $xmax, $ymin, $ymax, \%opt )
3950 #
3951 # \%opt can be supplied but not be defined
3952 # we parse the JUSTIFY, AXIS, and BORDER options here,
3953 # rather than have a multitude of checks below
3954 #
3955  
3956  
3957 sub initenv{
3958 my $self = shift; # Default box
3959  
3960 # We must check the status of the object, and if not ready it must
3961 # be re-opened...
3962 $self->_status();
3963  
3964 my ($in, $u_opt)=_extract_hash(@_);
3965  
3966 my ($xmin, $xmax, $ymin, $ymax, $just, $axis)=@$in;
3967 $u_opt={} unless defined($u_opt);
3968  
3969 ##############################
3970 # If the user specifies $just or $axis these values will
3971 # override any options given.
3972 $u_opt->{Justify} = $just if defined($just);
3973 $u_opt->{Axis} = $axis if defined($axis);
3974  
3975 ##############################
3976 # Now parse the input options.
3977 my $o = $self->{Options}->options($u_opt); # Merge in user options...
3978 if ($self->autolog) {
3979 # Bug fix JB, 03/03/05 - logging noisy/failed when running with -w or strict.
3980 # Hence the extra check on the content of Axis
3981 if (ref($o->{Axis}) eq 'ARRAY') {
3982 $self->{Logx} = ($o->{Axis}[0] =~ /L/) ? 1 : 0;
3983 $self->{Logy} = ($o->{Axis}[1] =~ /L/) ? 1 : 0;
3984 } elsif (ref($o->{Axis})) {
3985 barf "The axis option must be an array ref or a scalar!\n";
3986 } else {
3987 $self->{Logx} = ($o->{Axis} == 10 || $o->{Axis} == 30) ? 1 : 0; #/BCLNST/) ? 1 : 0;
3988 $self->{Logy} = ($o->{Axis} == 20 || $o->{Axis} == 30) ? 1 : 0; #/BCLNST/) ? 1 : 0;
3989 }
3990  
3991 ($xmin,$xmax) = map {
3992 barf "plot boundaries not positive in logx-mode" if $_ <= 0;
3993 log($_)/log(10) } ($xmin,$xmax)
3994 if $self->{Logx};
3995 ($ymin,$ymax) = map {
3996 barf "plot boundaries not positive in logy-mode" if $_ <= 0;
3997 log($_)/log(10) } ($ymin,$ymax)
3998 if $self->{Logy};
3999 }
4000  
4001 # DJB 2003/12/01 - added some error checking for user errors like
4002 # setting xmin==xmax. yeah, should really check abs(x1-x2)<tolerance ;)
4003 #
4004 barf "x axis has min==max" if $xmin == $xmax;
4005 barf "y axis has min==max" if $ymin == $ymax;
4006  
4007 $self->focus(), return 1 if $self->held;
4008 catch_signals {
4009 ##########
4010 # Save current colour and set the axis colours
4011 my ($col);
4012 pgqci($col);
4013 $self->_set_colour($o->{AxisColour});
4014 # Save current font size and set the axis character size.
4015 my ($chsz);
4016 pgqch($chsz);
4017 pgsch($o->{CharSize});
4018  
4019 if (ref($o->{Border}) eq 'HASH' || $o->{Border} != 0) {
4020 my $type = "REL";
4021 my $delta = 0.05;
4022 if ( ref($o->{Border}) eq "HASH" ) {
4023 while (my ($bkey, $bval) = each %{$o->{Border}}) {
4024 $bkey = uc($bkey);
4025 if ($bkey =~ m/^TYP/) {
4026 $type = uc $bval;
4027 } elsif ($bkey =~ m/^VAL/) {
4028 $delta = $bval;
4029 }
4030 } # while: (bkey,bval)
4031 } # if: ref($val) eq "HASH"
4032  
4033 if ( $type =~ m/^REL/ ) {
4034 my $sep = ( $xmax - $xmin ) * $delta;
4035 $xmin -= $sep; $xmax += $sep;
4036 $sep = ( $ymax - $ymin ) * $delta;
4037 $ymin -= $sep; $ymax += $sep;
4038 } elsif ( $type =~ m/^ABS/ ) {
4039 $xmin -= $delta; $xmax += $delta;
4040 $ymin -= $delta; $ymax += $delta;
4041 } else {
4042 print "Warning: unknown BORDER/TYPE option '$type'.\n";
4043 }
4044 }
4045  
4046 ##############################
4047 # pgpage doesn't behave quite right in the multi-panel case. Hence,
4048 # we call erase if there are multiple panels and pgpage if there is only
4049 # one.
4050 if (defined($o->{Erase}) && $o->{Erase}) {
4051 if ($self->{NX}*$self->{NY} > 1) {
4052 pgeras();
4053 $self->clear_state(); # Added to deal with new pages.
4054 } else {
4055 $self->clear_state(); # Added to deal with new pages.
4056 pgpage();
4057 }
4058 }
4059  
4060 ##########
4061 # Set up the viewport, and get its size in physical screen units.
4062 # This has to be done before the PIX/SCALE/PITCH stuff below in order
4063 # to make sure we can get physical dimensions of the viewport for scaling,
4064 # even though the JUSTIFY stuff redefines the viewport later.
4065 #
4066 if (!defined($o->{PlotPosition}) || $o->{PlotPosition} eq 'Default') {
4067 # Set standard viewport
4068 pgvstd();
4069 } else {
4070 barf "The PlotPosition must be given as an array reference!" unless
4071 ref($o->{PlotPosition}) eq 'ARRAY';
4072 my ($x0, $x1, $y0, $y1)=@{$o->{PlotPosition}};
4073 print "pgsvp($x0,$x1,$y0,$y1);\n" if($PDL::Graphics::PGPLOT::debug);
4074 pgsvp ($x0, $x1, $y0, $y1);
4075 }
4076  
4077 ##############################
4078 # Parse out scaling options. The defaults for each value change
4079 # based on the others (e.g. specifying "SCALE" and no unit
4080 # gives pixels; but specifying "PITCH" and no unit gives dpi).
4081 #
4082 my($pix,$pitch,$unit);
4083  
4084 ($pix,$pitch,$unit) = (1,1.0/$o->{'Scale'},3)
4085 if($o->{'Scale'});
4086  
4087 ($pix,$pitch,$unit) = (1,$o->{'Pitch'},1)
4088 if($o->{'Pitch'});
4089  
4090 if(defined $o->{'Unit'}) {
4091 $unit = _parse_unit($o->{'Unit'});
4092 barf("Unknown unit '$o->{'Unit'}'\n")
4093 unless(defined $unit);
4094 }
4095  
4096 $unit = 1 unless defined($unit); # Default to inch (any phys. unit will do)
4097  
4098 ##############################
4099 # Get size of viewport in physical screen units
4100 my ($x0,$x1,$y0,$y1);
4101 pgqvp($unit,$x0,$x1,$y0,$y1);
4102  
4103 # Pixel aspect ratio is always overridden by the pix option
4104 $pix = $o->{'Justify'} if $o->{'Justify'}; # Only override if nonzero!
4105 $pix = $o->{'Pix'} if defined $o->{'Pix'}; # Override if set.
4106  
4107 ###
4108 # Figure out the stretched pitch, if it isn't set.
4109 #
4110 my $have_pitch_and_pix = (defined($pix) & defined($pitch));
4111  
4112 unless(defined $pitch) {
4113 my $p = pdl( ($xmax-$xmin) / ($x1-$x0),
4114 ($ymax-$ymin) / ($y1-$y0) * (defined($pix)?$pix:0));
4115 $pitch = $p->abs->max;
4116 }
4117  
4118 $pix = abs(($y1 - $y0) / ($ymax - $ymin)) * $pitch
4119 unless defined($pix);
4120  
4121 ##########
4122 # Figure out the actual data coordinate corners of the screen, and/or
4123 # tweak the screen to match the data coordinate corners. This is important
4124 # because the PIX/SCALE/PITCH options set the scaling explicitly, and
4125 # the JUSTIFY option requires changing the viewport.
4126 #
4127  
4128 if($o->{Justify}) {
4129 ##########
4130 # Justify case
4131  
4132 ###
4133 # Work out the boundaries of the data in viewport space, given the
4134 # pitch and requested pixel aspect ratio. This is complicated a
4135 # little by the need to specify the viewport in surface normalized
4136 # coordinates: we have to retrieve surface normalized coords to tweak.
4137  
4138 my($ox0,$ox1,$oy0,$oy1);
4139 pgqvp(0,$ox0,$ox1,$oy0,$oy1); # Get surface normalized dims of current vp
4140  
4141 my($wxs, $wys) = ( ($ox1-$ox0) / ($x1-$x0) , ($oy1-$oy0) / ($y1-$y0) );
4142  
4143 local($_) = $o->{Align} || "CC";
4144 my($wx0,$wx1,$wy0,$wy1);
4145  
4146 my($xrange) = abs(($xmax-$xmin) * $wxs / $pitch );
4147 ($wx0,$wx1) =
4148 (m/L/i) ? ( $ox0, $ox0 + $xrange ) :
4149 (m/R/i) ? ( $ox1 - $xrange, $ox1 ) :
4150 (0.5 * ( $ox0 + $ox1 - $xrange ), 0.5 * ( $ox0 + $ox1 + $xrange ));
4151  
4152 my($yrange) = abs(($ymax-$ymin) * $wys * $pix / $pitch );
4153 ($wy0,$wy1) =
4154 (m/B/i) ? ( $oy0, $oy0 + $yrange ) :
4155 (m/T/i) ? ( $oy1 - $yrange, $oy1 ) :
4156 (0.5 * ( $oy0 + $oy1 - $yrange ), 0.5 * ( $oy0 + $oy1 + $yrange ));
4157  
4158 pgsvp(minmax(pdl($wx0,$wx1)),minmax(pdl($wy0,$wy1)));
4159  
4160 pgswin($xmin,$xmax,$ymin,$ymax);
4161  
4162 } elsif($have_pitch_and_pix) {
4163  
4164 ##########
4165 # Non-justify case with specified pitch and pixel aspect.
4166  
4167 my($xx0,$xx1,$yy0,$yy1); # These get the final data coords
4168  
4169 ###
4170 # Work out the boundaries of the viewport in data space, given the
4171 # pitch and requested pixel aspect ratio.
4172 local($_) = $o->{Align} || "BL";
4173  
4174 ($xx0,$xx1) =
4175 (m/L/i) ? ($xmin, $xmin+($x1-$x0)*$pitch) :
4176 (m/R/i) ? ($xmax-($x1-$x0)*$pitch, $xmax) :
4177 (0.5*($xmin+$xmax - ($x1-$x0)*$pitch),
4178 0.5*($xmin+$xmax + ($x1-$x0)*$pitch));
4179  
4180 ($yy0,$yy1) =
4181 (m/B/i) ? ($ymin, $ymin+($y1-$y0)*$pitch/$pix) :
4182 (m/T/i) ? ($ymax-($y1-$y0)*$pitch/$pix, $ymax) :
4183 (0.5*($ymin+$ymax - ($y1-$y0)*$pitch/$pix),
4184 0.5*($ymin+$ymax + ($y1-$y0)*$pitch/$pix));
4185  
4186 #
4187 # Sort out the direction that each axis runs...
4188 #
4189 my ( $dax, $day );
4190 unless(defined $o->{DirAxis}) {
4191 ($dax,$day) = (0,0);
4192 } elsif( ! ref $o->{DirAxis} ) {
4193 $dax=$day=$o->{DirAxis};
4194 } elsif( ref $o->{DirAxis} eq 'ARRAY' ) {
4195 ($dax,$day) = @{$o->{DirAxis}};
4196 } else {
4197 barf "DirAxis option must be a scalar or array\n";
4198 }
4199  
4200 ##print "dax=$dax; day=$day\n";
4201 ( $xx0, $xx1 ) = ( $xx1, $xx0 )
4202 if ( ( $dax==0 and ($xmin-$xmax)*($xx0-$xx1)<0 )
4203 or ( $dax < 0 )
4204 );
4205  
4206 ( $yy0, $yy1 ) = ( $yy1, $yy0 )
4207 if ( ( $day==0 and ($ymin-$ymax)*($yy0-$yy1)<0 )
4208 or ( $day < 0 )
4209 );
4210  
4211 pgswin($xx0, $xx1, $yy0, $yy1);
4212  
4213 } else {
4214 ###
4215 # Simplest case -- just do what the user originally said.
4216 #
4217 pgswin($xmin,$xmax,$ymin,$ymax);
4218  
4219 }
4220  
4221 if (ref($o->{Axis}) eq 'ARRAY') {
4222 print "found array ref axis option...\n" if($PDL::Graphics::PGPLOT::debug);
4223 pgtbox($o->{Axis}[0], 0.0, 0, $o->{Axis}[1], 0.0, 0);
4224 } else {
4225 pgtbox($o->{Axis}, 0.0, 0, $o->{Axis}, 0.0, 0);
4226 }
4227  
4228 $self->_set_env_options($xmin, $xmax, $ymin, $ymax, $o);
4229 $self->label_axes($u_opt->{XTitle}, $u_opt->{YTitle}, $u_opt->{Title},
4230 $u_opt);
4231  
4232 # restore settings
4233 $self->_set_colour($col);
4234 pgsch($chsz);
4235 };
4236 1;
4237 }
4238  
4239 # This is a tidy little routine to set the env options and update the global
4240 # variable.
4241 sub _set_env_options {
4242 my $self=shift;
4243 my @opt=@_;
4244  
4245 $self->{_env_options} = [@opt];
4246 $PREVIOUS_ENV = [@opt];
4247 }
4248  
4249 sub redraw_axes {
4250 my $self = shift;
4251 my $o;
4252 if (defined($self->{_env_options})) {
4253 # Use the previous settings for the plot box.
4254 my $e = $self->{_env_options};
4255 $o=$$e[4];
4256 } else {
4257 $o=$self->{Options}->defaults();
4258 }
4259 catch_signals {
4260 my $col;
4261 pgqci($col);
4262 $self->_set_colour($o->{AxisColour});
4263 my $chsz;
4264 pgqch($chsz);
4265 pgsch($o->{CharSize});
4266 my $axval = $o->{Axis}; # Using the last for this window...
4267 $axval = 0 unless defined $axval; # safety check
4268 unless ( $self->{Hold} ) {
4269 if ( ref($axval) ) {
4270 pgtbox($$axval[0],0,0,$$axval[1],0,0);
4271 } else {
4272 pgtbox($axval,0,0,$axval,0,0);
4273 }
4274 }
4275 $self->_set_colour($col);
4276 pgsch($chsz);
4277 };
4278 $self->_add_to_state(\&redraw_axes);
4279 }
4280  
4281  
4282 =head2 _image_xyrange
4283  
4284 Given a PGPLOT tr matrix and an image size, calculate the
4285 data world coordinates over which the image ranges. This is
4286 used in L</imag> and L</cont>. It keeps track of the
4287 required half-pixel offset to display images properly -- eg
4288 feeding in no tr matrix at all, nx=20, and ny=20 will
4289 will return (-0.5,19.5,-0.5,19.5). It also checks the options
4290 hash for XRange/YRange specifications and, if they are present, it
4291 overrides the appropriate output with the exact ranges in those fields.
4292  
4293 =cut
4294  
4295 sub _image_xyrange {
4296 my($tr,$nx,$ny,$opt) = @_;
4297  
4298 # Set identity $tr if no $tr is passed in. This looks funny
4299 # because it's designed for use with evil Fortran coordinates.
4300 if(!defined($tr)) {
4301 $tr = float [-1,1,0,-1,0,1];
4302 }
4303  
4304  
4305 ##############################
4306 ## Because the transform is an inhomogeneous scale-and-rotate,
4307 ## the limiting points are always the corners of the original
4308 ## physical data plane after transformation. We just transform
4309 ## the four corners of the data (in evil homogeneous FORTRAN
4310 ## origin-at-1 coordinates) and find the minimum and maximum
4311 ## X and Y values of 'em all.
4312  
4313 my @xvals;
4314 if(ref $opt eq 'HASH' and defined $opt->{XRange}) {
4315 die "_image_xyrange: if XRange is specified it must be an array ref\n"
4316 if(ref $opt->{XRange} ne 'ARRAY');
4317 @xvals = @{$opt->{XRange}};
4318 } else {
4319 @xvals = ($tr->slice('0:2')*pdl[
4320 [1, 0.5, 0.5],
4321 [1, 0.5, $nx+0.5],
4322 [1, $nx+0.5, 0.5],
4323 [1, $nx+0.5, $nx+0.5]
4324 ])->sumover->minmax;
4325 }
4326  
4327 my @yvals;
4328 if(ref $opt eq 'HASH' and defined $opt->{YRange}) {
4329 die "_image_xyrange: if YRange is specified it must be an array ref\n"
4330 if(ref $opt->{YRange} ne 'ARRAY');
4331 @yvals = @{$opt->{YRange}};
4332 } else {
4333 @yvals = ($tr->slice('3:5')*pdl[
4334 [1, 0.5, 0.5],
4335 [1, 0.5, $ny+0.5],
4336 [1, $ny+0.5, 0.5],
4337 [1, $ny+0.5, $ny+0.5]
4338 ])->sumover->minmax;
4339 }
4340  
4341 if ( $tr->at(1) < 0 ) { @xvals = ( $xvals[1], $xvals[0] ); }
4342 if ( $tr->at(5) < 0 ) { @yvals = ( $yvals[1], $yvals[0] ); }
4343  
4344 return (@xvals,@yvals);
4345 }
4346  
4347  
4348 =head2 _FITS_tr
4349  
4350 Given a FITS image, return the PGPLOT transformation matrix to convert
4351 pixel coordinates to scientific coordinates. Used by
4352 L</fits_imag>, L</fits_rgbi>, and
4353 L</fits_cont>, but may come in handy for other methods.
4354  
4355 =for example
4356  
4357 my $tr = _FITS_tr( $win, $img );
4358 my $tr = _FITS_tr( $win, $img, $opts );
4359  
4360 The return value (C<$tr> in the examples above) is the same as
4361 returned by the L<transform()|/transform> routine, with values
4362 set up to convert the pixel to scientific coordinate values for the
4363 two-dimensional image C<$img>. The C<$opts> argument is optional
4364 and should be a HASH reference; currently it only understands
4365 one key (any others are ignored):
4366  
4367 WCS => undef (default), "", or "A" to "Z"
4368  
4369 Both the key name and value are case insensitive. If left as C<undef>
4370 or C<""> then the primary coordinate mapping from the header is used, otherwise
4371 use the additional WCS mapping given by the appropriate letter.
4372 We make B<no> checks that the given mapping is available; the routine
4373 falls back to the unit mapping if the specified system is not available.
4374  
4375 The WCS option has only been tested on images from the Chandra X-ray satellite
4376 (L<http://chandra.harvard.edu/>) created by the CIAO software
4377 package (L<http://cxc.harvard.edu/ciao/>), for which you should
4378 set C<WCS =E<gt> "P"> to use the C<PHYSICAL> coordinate system.
4379  
4380 See L<http://fits.cv.nrao.edu/documents/wcs/wcs.html> for further
4381 information on the Representation of World Coordinate Systems in FITS.
4382  
4383 =cut
4384  
4385 {
4386 my $_FITS_tr_opt = undef;
4387  
4388 sub _FITS_tr {
4389 my $pane = shift;
4390 my $pdl = shift;
4391 my $opts = shift || {};
4392  
4393 $_FITS_tr_opt = PDL::Options->new( { WCS => undef } )
4394 unless defined $_FITS_tr_opt;
4395 my $user_opts = $_FITS_tr_opt->options( $opts );
4396  
4397 # Can either be sent an ndarray or a hash reference for the header
4398 # information
4399 #
4400 my $isapdl = UNIVERSAL::isa($pdl,'PDL');
4401 my $hdr = $isapdl ? $pdl->hdr() : $pdl->hdr;
4402  
4403 print STDERR
4404 "Warning: null FITS header in _FITS_tr (do you need to set hdrcpy?)\n"
4405 unless (scalar(keys %$hdr) || (!$PDL::debug));
4406  
4407 my ( $cdelt1, $cpix1, $cval1, $n1 );
4408 my ( $cdelt2, $cpix2, $cval2, $n2 );
4409 my $angle;
4410  
4411 # what WCS system to use? Not sure how well we are following the
4412 # Greisen et al proposal/standard here.
4413 #
4414 my $id = "";
4415 if ( defined $$user_opts{WCS} ) {
4416 $id = uc( $$user_opts{WCS} );
4417 die "WCS option must either be 'undef' or A-Z, not $id\n"
4418 unless $id =~ /^[A-Z]?$/;
4419 }
4420 print "Using the WCS '$id' mapping (if it exists)\n"
4421 if $PDL::verbose and $id ne "";
4422  
4423 {
4424 # don't complain about missing fields in fits headers
4425 no warnings;
4426  
4427 if ( $isapdl ) {
4428 ( $n1, $n2 ) = $pdl->dims;
4429 } else {
4430 $n1 = $hdr->{NAXIS1};
4431 $n2 = $hdr->{NAXIS2};
4432 }
4433  
4434 $cdelt1 = $hdr->{"CDELT1$id"} || 1.0;
4435 $cpix1 = $hdr->{"CRPIX1$id"} || 1;
4436 $cval1 = $hdr->{"CRVAL1$id"} || 0.0;
4437  
4438 $cdelt2 = $hdr->{"CDELT2$id"} || 1.0;
4439 $cpix2 = $hdr->{"CRPIX2$id"} || 1;
4440 $cval2 = $hdr->{"CRVAL2$id"} || 0.0;
4441  
4442 # changed Jan 14 2004 DJB - previously used CROTA
4443 # keyword but that is not in the WCS standard
4444 # - I hope this doesn't break things
4445 # -- This broke a few things because CROTA is a pseudostandard
4446 # in the solar physics community. I added a fallback to
4447 # CROTA in case CROTA2 doesn't exist. --CED
4448 # 13-Apr-2010: changed sign of CROTA2 to match update to PDL::Transform in 2.4.3 --CED
4449 $angle = - ( (defined $hdr->{"CROTA2$id"}) ? $hdr->{"CROTA2$id"} :
4450 (defined $hdr->{"CROTA"}) ? $hdr->{"CROTA"} : 0) *
4451 3.14159265358979323846264338/180;
4452  
4453 } # no warnings;
4454  
4455 #
4456 # Here's what we would do if PGPLOT worked as advertised...
4457 #
4458 return transform( $pane, {
4459 ImageDimensions => [ $n1, $n2 ],
4460 Angle => $angle,
4461 Pixinc => [ $cdelt1, $cdelt2 ],
4462 RefPos => [ [$cpix1-1, $cpix2-1], [$cval1,$cval2] ]
4463 } );
4464 #
4465 # Here's a failed attempt to compensate for the PGPLOT-induced jitter
4466 # (look closely at the "demo transform" rotating screens and you'll
4467 # see a small movement...)
4468 #
4469 # $offset = sqrt(0.5)* max abs cos ( $angle + pdl(-1,1)*0.25*3.14159 );
4470 # return transform( $pane, {
4471 # ImageDimensions => [ $n1, $n2 ],
4472 # Angle => $angle,
4473 # Pixinc => [ $cdelt1, $cdelt2 ],
4474 # RefPos => [ [$cpix1-1-$offset, $cpix2-1-$offset], [$cval1,$cval2] ]
4475 # } );
4476  
4477  
4478 } # sub: _FITS_tr
4479  
4480 } # "closure" around _FITS_tr
4481  
4482 my $label_params = [
4483 [2.0, 3.2, 2.2], # default
4484 [1.0, 2.7, 2.2], # tightened
4485 ];
4486 sub label_axes {
4487 # print "label_axes: got ",join(",",@_),"\n";
4488 my $self = shift;
4489 my ($in, $opt)=_extract_hash(@_);
4490  
4491 # :STATE RELATED:
4492 # THIS WILL PROBABLY NOT WORK as label_axes can be called both by
4493 # the user directly and by env... Let's see.
4494 $self->_add_to_state(\&label_axes, $in, $opt);
4495  
4496 barf 'Usage: label_axes( [$xtitle, $ytitle, $title], [$opt])' if $#$in > 3;
4497  
4498 my ($xtitle, $ytitle, $title)=@$in;
4499  
4500 $opt = {} if !defined($opt); # For safety.
4501  
4502 # Now the titles are set per plot so we use the general options to
4503 # parse the options (if they were set per window we would use
4504 # $self->{Options}
4505 my ($o, $u_opt) = $self->_parse_options($self->{PlotOptions}, $opt);
4506  
4507 # Added 25/8/01 JB to check whether label_axes is called before env..
4508 # This is not fool-proof though... And it will give a warning if the
4509 # user creates their env box outside of this package.
4510 warn "label_axes called before env - weird results might occur!\n" unless
4511 defined($self->{_env_options});
4512  
4513 $self->_save_status();
4514 $self->_standard_options_parser($u_opt);
4515 $o->{Title}=$title if defined($title);
4516 $o->{XTitle}=$xtitle if defined($xtitle);
4517 $o->{YTitle}=$ytitle if defined($ytitle);
4518  
4519 # what width do we use?
4520 # - things are somewhat confused since we have
4521 # LineWidth and TextWidth (a recent addition)
4522 # and LineWidth is set by _setup_window() - so
4523 # _standard_options_parser() uses it - but
4524 # TextWidth isn't.
4525 #
4526 # so for now we over-ride the _standard_options_parser
4527 # setting if TextWidth exists
4528 # [DJB 2002 Aug 08]
4529 catch_signals {
4530 my $old_lw;
4531 if ( defined($o->{TextWidth}) ) {
4532 pgqlw($old_lw);
4533 pgslw($o->{TextWidth});
4534 }
4535  
4536 # pglab by default goes too far from the plot! If NYPanels > 1
4537 # then the bottom label of a higher plot tends to squash the plot
4538 # title for the plot below it. To remedy this problem I've
4539 # replaced the pglab call with a set of calls to pgmtxt, cribbed
4540 # from the pglab.f file. The parameters are shrunk inward if NYPanel > 1
4541 # or if the option "TightLabels" is set. You can also explicitly set
4542 # it to 0 to get the original broken behavior. [CED 2002 Aug 29]
4543  
4544 my($p) = $label_params->[ ( ($self->{NY} > 1 && !defined $o->{TightLabels})
4545 || $o->{TightLabels}
4546 ) ? 1 : 0 ];
4547 my($sz);
4548 pgqch($sz);
4549  
4550 pgbbuf(); # Begin a buffered batch output to the device
4551 pgsch($sz * ( $o->{TitleSize} || 1 ));
4552 # The 'T' offset is computed so that the original
4553 # vertical center is maintained.
4554 pgmtxt('T', ($p->[0]+0.5)/( $o->{TitleSize} || 1 ) - 0.5 , 0.5, 0.5, $o->{Title});
4555  
4556 pgebuf(); # Flush the buffer to avoid a pgplot bug that produced
4557 pgbbuf(); # doubled titles for some devices (notably the ppm device).
4558  
4559 pgsch($sz);
4560 pgmtxt('B', $p->[1], 0.5, 0.5, $o->{XTitle});
4561 pgmtxt('L', $p->[2], 0.5, 0.5, $o->{YTitle});
4562 pgebuf();
4563  
4564 # pglab($o->{XTitle}, $o->{YTitle}, $o->{Title});
4565  
4566  
4567 pgslw($old_lw) if defined $old_lw;
4568 };
4569 $self->_restore_status;
4570 }
4571  
4572  
4573 ############ Exported functions #################
4574  
4575 # Open/reopen the graphics device
4576  
4577 ################ Supports two new options::
4578 ## NewWindow and WindowName
4579  
4580  
4581 sub CtoF77coords{ # convert a transform array from zero-offset to unit-offset images
4582 my $self = shift;
4583 my $tr = pdl(shift); # Copy
4584 set($tr, 0, at($tr,0)-at($tr,1)-at($tr,2));
4585 set($tr, 3, at($tr,3)-at($tr,4)-at($tr,5));
4586 return $tr;
4587 }
4588  
4589  
4590  
4591 # set the envelope for plots and put auto-axes on hold
4592  
4593 sub env {
4594 my $self=shift;
4595  
4596 # Inserted 28/2/01 - JB to avoid having to call release whenever
4597 # you want to move to the next panel after using env.
4598 $self->release() if $self->held();
4599 # The following is necessary to advance the panel if wanted...
4600 my ($in, $opt)=_extract_hash(@_);
4601 $opt = {} if !defined($opt);
4602 my $o = $self->{PlotOptions}->options($opt);
4603  
4604 #
4605 # Inserted 06/08/01 - JB to be able to determine whether the user has
4606 # specified a particular PlotPosition in which case we do _not_ call
4607 # _check_move_or_erase...
4608 #
4609 my $o2 = $self->{Options}->options($opt);
4610 if (!defined($o2->{PlotPosition}) || $o2->{PlotPosition} eq 'Default') {
4611 $self->_check_move_or_erase($o->{Panel}, $o->{Erase});
4612 }
4613  
4614 barf 'Usage: env ( $xmin, $xmax, $ymin, $ymax, [$just, $axis, $opt] )'
4615 if ($#_==-1 && !defined($self->{_env_options}) && !defined($PREVIOUS_ENV)) ||
4616 ($#_>=0 && $#_<=2) || $#_>6;
4617 my(@args);
4618  
4619 # Set the args. The logic here was extended 13/8 by JB to use the
4620 # previous setting of the plot env variables regardless of device
4621 # if the current device does not have a setting for env etc.
4622 if ($#_ == -1) {
4623 if (@{$self->{_env_options}}) {
4624 @args = @{$self->{_env_options}};
4625 } elsif (defined($PREVIOUS_ENV)) {
4626 @args = @{$PREVIOUS_ENV};
4627 } else {
4628 @args = ();
4629 }
4630 } else {
4631 @args = @_;
4632 }
4633 $self->initenv( @args );
4634 ## The adding to state has to take place here to avoid being cleared
4635 ## buy the call to initenv...
4636 $self->_add_to_state(\&env, $in, $opt);
4637 $self->hold();
4638  
4639  
4640 1;
4641 }
4642  
4643 # Plot a histogram with pgbin()
4644  
4645 {
4646 my $bin_options = undef;
4647  
4648  
4649 sub bin {
4650 my $self = shift;
4651 if (!defined($bin_options)) {
4652 $bin_options = $self->{PlotOptions}->extend({Centre => 1});
4653 $bin_options->add_synonym({Center => 'Centre'});
4654 }
4655 my ($in, $opt)=_extract_hash(@_);
4656 $self->_add_to_state(\&bin, $in, $opt);
4657  
4658 barf 'Usage: bin ( [$x,] $data, [$options] )' if $#$in<0 || $#$in>2;
4659 my ($x, $data)=@$in;
4660  
4661 $self->_checkarg($x,1);
4662  
4663 my $n = nelem($x);
4664 if ($#$in==1) {
4665 $self->_checkarg($data,1); barf '$x and $y must be same size' if $n!=nelem($data);
4666 } else {
4667 $data = $x; $x = float(sequence($n));
4668 }
4669  
4670 # Parse options
4671 $opt={} unless defined($opt);
4672 my ($o, $u_opt) = $self->_parse_options($bin_options,$opt);
4673  
4674 $self->_check_move_or_erase($o->{Panel}, $o->{Erase});
4675 unless ( $self->held() ) {
4676 my ($xmin, $xmax)=ref $o->{XRange} eq 'ARRAY' ?
4677 @{$o->{XRange}} : minmax($x);
4678 my ($ymin, $ymax)=ref $o->{YRange} eq 'ARRAY' ?
4679 @{$o->{YRange}} : minmax($data);
4680 if ($xmin == $xmax) { $xmin -= 0.5; $xmax += 0.5; }
4681 if ($ymin == $ymax) { $ymin -= 0.5; $ymax += 0.5; }
4682 $self->initenv( $xmin, $xmax, $ymin, $ymax, $opt );
4683 }
4684 $self->_save_status();
4685  
4686 my $centre = $o->{Centre};
4687  
4688 # For the standard parser we only want the options that the user set!
4689 # $bin_options->full_options(0);
4690 # my $u_opt = $bin_options->current();
4691 # $bin_options->full_options(1);
4692  
4693 # Let's also parse the options if any.
4694 $self->_standard_options_parser($u_opt);
4695 catch_signals {
4696 pgbin($n, $x->get_dataref, $data->get_dataref, $centre);
4697 };
4698 $self->_restore_status();
4699 1;
4700 }
4701 }
4702  
4703 # display a contour map of an image using pgconb()
4704 {
4705 my $cont_options = undef;
4706 sub cont {
4707 my $self=shift;
4708 if (!defined($cont_options)) {
4709 $cont_options = $self->{PlotOptions}->extend({Contours => undef,
4710 Follow => 0,
4711 Labels => undef,
4712 LabelColour => undef,
4713 Missing => undef,
4714 NContours => undef,
4715 FillContours => undef});
4716 my $t = {
4717 LabelColour => {
4718 'White' => 0, 'Black' => 1, 'Red' => 2,
4719 'Green' => 3, 'Blue' => 4, 'Cyan' => 5,
4720 'Magenta' => 6, 'Yellow' => 7, 'Orange' => 8,
4721 'DarkGray' => 14, 'DarkGrey' => 14,
4722 'LightGray' => 15, 'LightGrey' => 15
4723 }
4724 };
4725 $cont_options->add_translation($t);
4726 }
4727  
4728  
4729 my ($in, $opt)=_extract_hash(@_);
4730 $self->_add_to_state(\&cont, $in, $opt);
4731  
4732 barf 'Usage: cont ( $image, %options )' if $#$in<0;
4733  
4734 # Parse input
4735 my ($image, $contours, $tr, $misval) = @$in;
4736 $self->_checkarg($image,2);
4737 my($nx,$ny) = $image->dims;
4738 my ($ncont)=9; # The number of contours by default
4739  
4740 # First save the present status
4741 $self->_save_status();
4742  
4743  
4744 # Then parse the common options
4745 #
4746 # These will be all options.
4747 $opt = {} if !defined($opt);
4748 my ($o, $u_opt) = $self->_parse_options($cont_options, $opt);
4749 $self->_check_move_or_erase($o->{Panel}, $o->{Erase});
4750  
4751 $self->_standard_options_parser($u_opt);
4752 my ($labelcolour);
4753 catch_signals {
4754 pgqci($labelcolour); # Default let the labels have the chosen colour.
4755  
4756 my ($labels, $fillcontours, $angle);
4757 my $usepgcont = 0;
4758  
4759 $contours = $o->{Contours} if defined($o->{Contours});
4760 $ncont = $o->{NContours} if defined($o->{NContours});
4761 $misval = $o->{Missing} if defined($o->{Missing});
4762 $tr = $o->{Transform} if defined($o->{Transform});
4763 $labelcolour = $o->{LabelColour} if defined($o->{LabelColour});
4764 $labels = $o->{Labels} if defined($o->{Labels});
4765 $usepgcont = $o->{Follow} if defined($o->{Follow});
4766 $fillcontours = $o->{FillContours} if defined($o->{FillContours});
4767  
4768 if (defined($tr)) {
4769 $self->_checkarg($tr,1);
4770 barf '$transform incorrect' if nelem($tr)!=6;
4771 } else {
4772 $tr = float [0,1,0, 0,0,1];
4773 }
4774  
4775 $tr = $self->CtoF77coords($tr);
4776  
4777 if (!$self->held()) {
4778 $self->initenv( _image_xyrange($tr,$nx,$ny,$o), $o );
4779 }
4780  
4781 if (!defined($contours)) {
4782 my($minim, $maxim)=minmax($image);
4783 $contours = xlinvals(zeroes($ncont), $minim, $maxim)
4784 }
4785 else {
4786 $ncont = nelem($contours);
4787 }
4788  
4789 $self->_checkarg($contours,1);
4790  
4791 print "Contouring $nx x $ny image from ",min($contours), " to ",
4792 max($contours), " in ",nelem($contours)," steps\n" if $PDL::verbose;
4793  
4794 if (defined($fillcontours)) {
4795 pgbbuf();
4796 if (ref $fillcontours ne 'PDL') {
4797 $fillcontours = zeroes($ncont - 1)->xlinvals(0,1)->dummy(0,3);
4798 } elsif ($fillcontours->getndims == 1) {
4799 $fillcontours = $fillcontours->dummy(0,3);
4800 } elsif (($fillcontours->getdim(1) != $ncont - 1) ||
4801 ($fillcontours->getdim(0) != 3)) {
4802 barf "Argh, wrong dims in filled contours!";
4803 }
4804 my ($cr, $cg, $cb, $i);
4805 pgqcr(16, $cr, $cg, $cb); # Save color index 16
4806 # Loop over filled contours (perhaps should be done in PP for speed)
4807 # Do not shade negative and 0-levels
4808 for ($i = 0; $i < ($ncont - 1); $i++) {
4809 pgscr(16, list $fillcontours->slice(":,$i"));
4810 pgsci(16);
4811 pgconf($image->get_dataref, $nx, $ny,
4812 1, $nx, 1, $ny,
4813 list($contours->slice("$i:(".($i+1))), $tr->get_dataref);
4814 }
4815 pgscr(16, $cr, $cg, $cb); # Restore color index 16
4816 pgebuf();
4817 } elsif (defined($misval)) {
4818 pgconb( $image->get_dataref, $nx,$ny,1,$nx,1,$ny,
4819 $contours->get_dataref,
4820 nelem($contours), $tr->get_dataref, $misval);
4821 } elsif (abs($usepgcont) == 1) {
4822 pgcont( $image->get_dataref, $nx,$ny,1,$nx,1,$ny,
4823 $contours->get_dataref,
4824 $usepgcont*nelem($contours), $tr->get_dataref);
4825 } else {
4826 pgcons( $image->get_dataref, $nx,$ny,1,$nx,1,$ny,
4827 $contours->get_dataref, nelem($contours), $tr->get_dataref);
4828 }
4829  
4830 # Finally label the contours.
4831 if (defined($labels) && $#$labels+1==nelem($contours)) {
4832  
4833 my $label=undef;
4834 my $count=0;
4835 my $minint=long($nx/10)+1; # At least stretch a tenth of the array
4836 my $intval=long($nx/3)+1; #
4837  
4838 my $dum;
4839 pgqci($dum);
4840 $self->_set_colour($labelcolour);
4841 foreach $label (@{$labels}) {
4842 pgconl( $image->get_dataref, $nx,$ny,1,$nx,1,$ny,
4843 $contours->slice("($count)"),
4844 $tr->get_dataref, $label, $intval, $minint);
4845 $count++;
4846 }
4847 $self->_set_colour($dum);
4848 } elsif (defined($labels)) {
4849 #
4850 # We must have had the wrong number of labels
4851 #
4852 warn <<EOD
4853 You must specify the same number of labels as contours.
4854 Labelling has been ignored.
4855 EOD
4856 }
4857 };
4858  
4859 # Restore attributes
4860 $self->redraw_axes unless $self->held(); # Redraw box
4861 $self->_restore_status();
4862  
4863 1;
4864 }
4865 }
4866  
4867 # Plot errors with pgerrb()
4868  
4869 {
4870  
4871 my $errb_options = undef;
4872  
4873 sub errb {
4874 my $self = shift;
4875 if (!defined($errb_options)) {
4876 $errb_options = $self->{PlotOptions}->extend({Term => 1});
4877 $errb_options->add_synonym({Terminator => 'Term'});
4878 }
4879 my ($in, $opt)=_extract_hash(@_);
4880 $self->_add_to_state(\&bin, $in, $opt);
4881  
4882 $opt = {} if !defined($opt);
4883  
4884 barf <<'EOD' if @$in==0 || @$in==1 || @$in > 7;
4885 Usage: $w-> errb ( $y, $yerrors [, $options] )
4886 $w-> errb ( $x, $y, $yerrors [, $options] )
4887 $w-> errb ( $x, $y, $xerrors, $yerrors [, $options])
4888 $w-> errb ( $x, $y, $xloerr, $xhierr, $yloerr, $yhierr [, $options])
4889 EOD
4890  
4891 my @t=@$in;
4892 my $n;
4893  
4894 # it's possible the user slipped in undefs as the data position.
4895 # that's illegal and won't be caught in next loop
4896 barf "Must specify data position"
4897 if ! defined $t[0] || ( @t > 2 && ! defined $t[1] );
4898  
4899 # loop over input data; skip undefined values, as they are
4900 # used to flag missing error bars. all data should have the
4901 # same dims as the first ndarray.
4902 for ( my $i = 0 ; $i < @t ; $i++ )
4903 {
4904 next if ! defined $t[$i];
4905  
4906 $self->_checkarg($t[$i], 1);
4907  
4908 $n = nelem($t[$i]) if $i == 0;
4909 barf "Args must have same size" if nelem($t[$i]) != $n;
4910 }
4911  
4912 my $x = @t < 3 ? float(sequence($n)) : shift @t;
4913 my $y = shift @t;
4914  
4915 # store data in a hash to automate operations
4916 my %d;
4917 $d{x}{data} = $x;
4918 $d{y}{data} = $y;
4919  
4920 ( $d{y}{err} ) = @t if @t == 1;
4921 ( $d{x}{err}, $d{y}{err} ) = @t if @t == 2;
4922 ( $d{x}{loerr}, $d{x}{hierr},
4923 $d{y}{loerr}, $d{y}{hierr} ) = @t if @t == 4;
4924  
4925 my ($o, $u_opt) = $self->_parse_options($errb_options, $opt);
4926 $self->_check_move_or_erase($o->{Panel}, $o->{Erase});
4927 unless( $self->held() ) {
4928 # Allow for the error bars
4929 my ( $xmin, $xmax, $ymin, $ymax );
4930  
4931  
4932 # Bug fix, JB 03/03/05 - user input ranges were not considered.
4933 my @axes_to_do = ();
4934  
4935 if (ref($o->{XRange})) {
4936 ($d{'x'}{min}, $d{'x'}{max})=@{$o->{XRange}};
4937 if ($d{'x'}{xmin} == $d{'x'}{max}) { $d{'x'}{min} -= 0.5; $d{'x'}{max} += 0.5; }
4938 } else {
4939 push @axes_to_do, 'x';
4940 }
4941 if (ref($o->{YRange})) {
4942 ($d{'y'}{min}, $d{'y'}{max})=@{$o->{YRange}};
4943 if ($d{'y'}{xmin} == $d{'y'}{max}) { $d{'y'}{min} -= 0.5; $d{'y'}{max} += 0.5; }
4944 } else {
4945 push @axes_to_do, 'y';
4946 }
4947  
4948  
4949 # loop over the axes to calculate plot limits
4950 for my $ax (@axes_to_do)
4951 {
4952 my $axis = $d{$ax};
4953 my $range = uc $ax . 'range';
4954  
4955 # user may have specified range limits already; pull them in
4956 ($axis->{min},$axis->{max}) = @{$o->{$range}}
4957 if ref $o->{$range} eq 'ARRAY';
4958  
4959 # skip if user specified range limits
4960 unless ( exists $axis->{min} )
4961 {
4962 my ( $min, $max );
4963  
4964 # symmetric error bars
4965 if ( defined $axis->{err} )
4966 {
4967 $min = min( $axis->{data} - $axis->{err} );
4968 $max = max( $axis->{data} + $axis->{err} );
4969 }
4970  
4971 # assymetric error bars
4972 else
4973 {
4974 # lo error bar specified
4975 if ( defined $axis->{loerr} )
4976 {
4977 $min = min( $axis->{data} - $axis->{loerr} );
4978 }
4979  
4980 # hi error bar specified
4981 if ( defined $axis->{hierr} )
4982 {
4983 $max = max( $axis->{data} + $axis->{hierr} );
4984 }
4985 }
4986  
4987 # handle the case where there is no error bar.
4988 $min = $axis->{data}->min unless defined $min;
4989 $max = $axis->{data}->max unless defined $max;
4990  
4991 # default range for infinitesimal data range
4992 if ($min == $max) { $min -= 0.5; $max += 0.5; }
4993  
4994 $axis->{min} = $min;
4995 $axis->{max} = $max;
4996 }
4997 }
4998  
4999 $self->initenv( $d{x}{min}, $d{x}{max}, $d{y}{min}, $d{y}{max}, $opt );
5000 }
5001  
5002 $self->_save_status();
5003 # Let us parse the options if any.
5004  
5005 my $term=$o->{Term};
5006 my $symbol;
5007 my $plot_points=0; # We won't normally plot the points
5008  
5009 if (defined($u_opt->{Symbol})) {
5010 $symbol = $u_opt->{Symbol};
5011 $plot_points=1;
5012 }
5013  
5014 # Parse other standard options.
5015 $self->_standard_options_parser($u_opt);
5016  
5017 # map our combination of errors onto pgerrb's DIR parameter. note that
5018 # DIR(Y) = DIR(X) + 1 for similar error bar configurations
5019 $d{x}{dir} = 0;
5020 $d{y}{dir} = 1;
5021  
5022 catch_signals {
5023 # loop over axes, plotting the appropriate error bars
5024 for my $axis ( $d{x}, $d{y} )
5025 {
5026 my $dir = $axis->{dir};
5027  
5028 # symmetric error bars
5029 if ( defined $axis->{err} )
5030 {
5031 pgerrb(5 + $dir, $n, $x->get_dataref, $y->get_dataref,
5032 $axis->{err}->get_dataref,$term);
5033 }
5034  
5035 # assymetric error bars
5036 else
5037 {
5038 if ( defined $axis->{hierr} )
5039 {
5040 pgerrb(1 + $dir, $n, $x->get_dataref, $y->get_dataref,
5041 $axis->{hierr}->get_dataref,$term);
5042 }
5043  
5044 if ( defined $axis->{loerr} )
5045 {
5046 pgerrb(3 + $dir, $n, $x->get_dataref, $y->get_dataref,
5047 $axis->{loerr}->get_dataref,$term);
5048 }
5049  
5050 }
5051 }
5052  
5053 if ($plot_points) {
5054 if (exists($opt->{SymbolSize})) { # Set symbol size (2001.10.22 kwi)
5055 pgsch($opt->{SymbolSize});
5056 }
5057 $symbol=long($symbol);
5058 my $ns=nelem($symbol);
5059 pgpnts($n, $x->get_dataref, $y->get_dataref, $symbol->get_dataref, $ns)
5060 }
5061 };
5062 $self->_restore_status();
5063 1;
5064 }
5065 }
5066  
5067 # Plot a line with pgline()
5068  
5069 {
5070 my $line_options = undef;
5071  
5072 #
5073 # lines: CED 17-Dec-2002
5074 #
5075 sub lines {
5076 my $self = shift;
5077  
5078 if(!defined($line_options)) {
5079 $line_options = $self->{PlotOptions}->extend({Missing=>undef});
5080 }
5081 my($in,$opt) = _extract_hash(@_);
5082  
5083 # Parse out the options and figure out which syntax is being used
5084 # This is a pain to look at but the computer does it behind your back so
5085 # what do you care? --CED
5086 my($x,$y,$p);
5087  
5088 if(@$in == 3) {
5089 barf "lines: inconsistent array refs in \$x,\$y,\$p call\n"
5090 if((ref $in->[0] eq 'ARRAY') ^ (ref $in->[1] eq 'ARRAY'));
5091  
5092 ($x,$y) = (ref $in->[0] eq 'ARRAY') ?
5093 ($in->[0],$in->[1]) : ([$in->[0]],[$in->[1]]);
5094  
5095 $p = (ref $in->[2] eq 'ARRAY') ? $in->[2] : [$in->[2]];
5096 }
5097 elsif(@$in == 2) { # $xy, $p or $x,$y (no-$p)
5098 my($c) = (ref $in->[0] eq 'ARRAY') ? $in->[0] : [$in->[0]];
5099 my($d) = (ref $in->[1] eq 'ARRAY') ? $in->[1] : [$in->[1]];
5100  
5101 barf " lines: \$xy must be an ndarray\n"
5102 unless(UNIVERSAL::isa($c->[0],'PDL'));
5103  
5104 if( ( ref $in->[0] ne ref $in->[1] ) ||
5105 ( ! UNIVERSAL::isa($d->[0],'PDL') ) ||
5106 ( $c->[0]->ndims > $d->[0]->ndims )
5107 ) { # $xy, $p case -- split $xy into $x and $y.
5108  
5109 foreach $_(@$c){
5110 push(@$x,$_->slice("(0)"));
5111 push(@$y,$_->slice("(1)"));
5112 }
5113 $p = $d;
5114  
5115 } else { # $x,$y,(omitted $p) case -- make default $p.
5116 $x = $c;
5117 $y = $d;
5118 $p = [1];
5119 }
5120 }
5121  
5122 elsif(@$in == 1) { # $xyp or $xy,(omitted $p) case
5123 my($c) = (ref $in->[0] eq 'ARRAY') ? $in->[0] : [$in->[0]];
5124  
5125 foreach $_(@$c) {
5126 push(@$x,$_->slice("(0)"));
5127 push(@$y,$_->slice("(1)"));
5128 push(@$p, ($_->dim(0) >= 3) ? $_->slice("(2)") : 1);
5129 }
5130 }
5131  
5132 else {
5133 barf " lines: ".scalar(@$in)." is not a valid number of args\n";
5134 }
5135  
5136 barf "lines: x and y lists have different numbers of elements"
5137 if($#$x != $#$y);
5138  
5139 ##############################
5140 # Now $x, $y, and $p all have array refs containing their respective
5141 # vectors. Set up pgplot (copy-and-pasted from line; this is probably
5142 # the Wrong thing to do -- we probably ought to call line directly).
5143 #
5144 $opt = {} unless defined($opt);
5145 my($o,$u_opt) = $self->_parse_options($line_options,$opt);
5146  
5147 barf "lines: \$o->\{Missing\} must be an array ref if specified\n" if (defined $o->{Missing} && ref $o->{Missing} ne 'ARRAY');
5148  
5149 $self->_check_move_or_erase($o->{Panel},$o->{Erase});
5150  
5151 my $held = $self->held();
5152 unless ($held) {
5153 my($ymin,$ymax,$xmin,$xmax) = (
5154 zeroes(scalar(@$y)),
5155 zeroes(scalar(@$y)),
5156 zeroes(scalar(@$y)),
5157 zeroes(scalar(@$y))
5158 );
5159 my $thunk = sub {
5160 my($range) = shift;
5161 my($vals,$missing,$min,$max,$pp) = @_;
5162 if(ref $range eq 'ARRAY') {
5163 $min .= $range->[0];
5164 $max .= $range->[1];
5165 return;
5166 }
5167 my($mask) = (isfinite $vals);
5168 $mask &= ($vals != $missing) if(defined $missing);
5169 $mask->slice("1:-1") &= long(($pp->slice("0:-2") != 0) | ($pp->slice("1:-1") != 0));
5170 my($c,$d) = minmax(where($vals,$mask));
5171 $min .= $c;
5172 $max .= $d;
5173 };
5174  
5175 for my $i(0..$#$x) {
5176 my($pp) = $#$p ? $p->[$i] : $p->[0]; # allow scalar pen in array case
5177 $pp = pdl($pp) unless UNIVERSAL::isa($pp,'PDL');
5178 my $miss = defined $o->{Missing} ? $o->{Missing}->[$i] : undef;
5179 &$thunk($u_opt->{XRange},$x->[$i],$miss,$xmin->slice("($i)"),$xmax->slice("($i)"),$pp);
5180 &$thunk($u_opt->{YRange},$y->[$i],$miss,$ymin->slice("($i)"),$ymax->slice("($i)"),$pp);
5181 }
5182  
5183 $xmin = $xmin->min;
5184 $xmax = $xmax->max;
5185 $ymin = $ymin->min;
5186 $ymax = $ymax->max;
5187  
5188 if($xmin==$xmax) { $xmin -= 0.5; $xmax += 0.5; }
5189 if($ymin==$ymax) { $ymin -= 0.5; $ymax += 0.5; }
5190  
5191 print "lines: xmin=$xmin; xmax=$xmax; ymin=$ymin; ymax=$ymax\n"
5192 if($PDL::verbose);
5193 $self->initenv($xmin,$xmax,$ymin,$ymax,$opt);
5194 }
5195  
5196 $self->_save_status();
5197 $self->_standard_options_parser($u_opt);
5198  
5199 catch_signals {
5200 my($lw); # Save the normal line width
5201 pgqlw($lw);
5202 my($hh) = 0; # Indicates local window hold
5203  
5204 # Loop over everything in the list
5205 for my $i(0..$#$x) {
5206 my($xx,$yy) = ($x->[$i],$y->[$i]);
5207 next if($xx->nelem < 2);
5208  
5209 my($pp) = $#$p ? $p->[$i] : $p->[0]; # allow scalar pen in array case
5210 my($miss) = defined $o->{Missing} ? $o->{Missing}->[$i] : undef;
5211 my($n) = $xx->nelem;
5212  
5213 $pp = pdl($pp) unless UNIVERSAL::isa($pp,'PDL');
5214  
5215 $pp = zeroes($xx)+$pp
5216 if($pp->nelem == 1);
5217  
5218 $pp = $pp->copy; # Make a duplicate to scribble on
5219 $pp->slice("0:-2") *= ($xx->slice("0:-2") + $xx->slice("1:-1"))->isfinite;
5220 $pp->slice("0:-2") *= ($yy->slice("0:-2") + $yy->slice("1:-1"))->isfinite;
5221  
5222 my($pn,$pval) = rle($pp);
5223 my($pos,$run,$rl) = (0,0,0);
5224  
5225  
5226 # Within each list element loop over runs of pen value
5227 while(($run<$pn->nelem) && ($rl = $pn->at($run))) { # assignment
5228 my($pv);
5229 if($pv = $pval->at($run)) { # (assignment) Skip runs with pen value=0
5230 my $top = $pos+$rl; $top-- if($top == $xx->dim(0));
5231 my $x0 = float $xx->slice("$pos:$top");
5232 my $y0 = float $yy->slice("$pos:$top");
5233  
5234 $self->_set_colour(abs($pv)*(defined $o->{Colour} ? $o->{Colour}:1));
5235  
5236 ($x0,$y0) = $self->checklog($x0,$y0) if $self->autolog;
5237  
5238 if($pv > 0) {
5239 pgslw($lw);
5240 } else {
5241 pgslw(1);
5242 }
5243  
5244 if(defined($miss)) {
5245 my $mpt = $miss->slice("$pos:$top");
5246 pggapline($x0->nelem,$mpt,$x0->get_dataref, $y0->get_dataref);
5247 } else {
5248 pgline($x0->nelem,$x0->get_dataref,$y0->get_dataref,);
5249 }
5250  
5251 $self->hold() unless $hh++;
5252 }
5253  
5254 $pos += $rl;
5255 $run++;
5256 } # end of within-ndarray polyline loop
5257 } # end of array ref loop
5258 pgslw($lw); # undo incredible shrinking line width$
5259 };
5260 $self->release() unless($held);
5261 $self->_restore_status();
5262 $self->_add_to_state(\&lines,$in,$opt);
5263 1;
5264 }
5265  
5266 sub line {
5267 my $self = shift;
5268 if (!defined($line_options)) {
5269 $line_options=$self->{PlotOptions}->extend({Missing => undef});
5270 }
5271 my ($in, $opt)=_extract_hash(@_);
5272  
5273 barf 'Usage: line ( [$x,] $y, [$options] )' if $#$in<0 || $#$in>2;
5274 my($x,$y) = @$in;
5275 $self->_checkarg($x,1);
5276 my $n = nelem($x);
5277  
5278 my ($is_1D, $is_2D);
5279 if ($#$in==1) {
5280 $is_1D = $self->_checkarg($y,1,undef,1);
5281 if (!$is_1D) {
5282 $is_2D = $self->_checkarg($y,2,undef,1);
5283 barf '$y must be 1D (or 2D for broadcasting!)'."\n" if !$is_2D;
5284  
5285 # Ok, let us use the broadcasting possibility.
5286 $self->tline(@$in, $opt);
5287  
5288 &release_signals;
5289 return;
5290 } else {
5291 barf '$x and $y must be same size' if $n!=nelem($y);
5292 }
5293 } else {
5294 $y = $x; $x = float(sequence($n));
5295 }
5296  
5297 # Let us parse the options if any.
5298 $opt = {} if !defined($opt);
5299 my ($o, $u_opt) = $self->_parse_options($line_options, $opt);
5300 $self->_check_move_or_erase($o->{Panel}, $o->{Erase});
5301  
5302 unless ( $self->held() ) {
5303  
5304 # Make sure the missing value is used as the min or max value.
5305 # Also, do autoscaling but avoid infinities.
5306 my ($ymin, $ymax, $xmin, $xmax);
5307  
5308 # Thunk for finding max and min X and Y ranges
5309 my($thunk) = sub {
5310 my($range) = shift; return @{$range} if(ref $range eq 'ARRAY');
5311 my($vals, $missing) = @_;
5312 my($mask) = (isfinite $vals);
5313 $mask &= ($vals != $missing) if(defined $missing);
5314 minmax(where($vals,$mask));
5315 };
5316  
5317 ($xmin,$xmax) = &$thunk($o->{XRange},$x,$o->{Missing});
5318 ($ymin,$ymax) = &$thunk($o->{YRange},$y,$o->{Missing});
5319  
5320 if ($xmin == $xmax) { $xmin -= 0.5; $xmax += 0.5; }
5321 if ($ymin == $ymax) { $ymin -= 0.5; $ymax += 0.5; }
5322 print("line: xmin=$xmin; xmax=$xmax; ymin=$ymin; ymax=$ymax\n")
5323 if($PDL::verbose);
5324 $self->initenv( $xmin, $xmax, $ymin, $ymax, $opt);
5325 }
5326 $self->_save_status();
5327 $self->_standard_options_parser($u_opt);
5328  
5329 # take logs if we are in autolog mode and axis option indicates logs
5330 ($x,$y) = $self->checklog($x,$y) if $self->autolog;
5331  
5332 # If there is a missing value specified, use pggapline
5333 # to break the line around missing values.
5334 catch_signals {
5335 if (defined $o->{Missing}) {
5336 pggapline ($n, $o->{Missing}, $x->get_dataref, $y->get_dataref);
5337 } else {
5338 pgline($n, $x->get_dataref, $y->get_dataref);
5339 }
5340 };
5341 $self->_restore_status();
5342 $self->_add_to_state(\&line, $in, $opt);
5343 1;
5344 }
5345 }
5346 # Plot points with pgpnts()
5347  
5348  
5349  
5350 sub arrow {
5351  
5352 my $self = shift;
5353  
5354 my ($in, $opt)=_extract_hash(@_);
5355 $opt = {} if !defined($opt);
5356  
5357 barf 'Usage: arrow($x1, $y1, $x2, $y2 [, $options])' if $#$in != 3;
5358  
5359 my ($x1, $y1, $x2, $y2)=@$in;
5360  
5361 my ($o, $u_opt) = $self->_parse_options($self->{PlotOptions}, $opt);
5362 $self->_check_move_or_erase($o->{Panel}, $o->{Erase});
5363 unless ($self->held()) {
5364 $self->initenv($x1, $x2, $y1, $y2, $opt);
5365 }
5366  
5367 $self->_save_status();
5368 $self->_standard_options_parser($u_opt);
5369 catch_signals {
5370 pgarro($x1, $y1, $x2, $y2);
5371 };
5372 $self->_restore_status();
5373 $self->_add_to_state(\&arrow, $in, $opt);
5374 }
5375  
5376  
5377  
5378 {
5379 my $points_options = undef;
5380  
5381 sub points {
5382  
5383 my $self = shift;
5384 if (!defined($points_options)) {
5385 $points_options = $self->{PlotOptions}->extend({PlotLine => 0});
5386 }
5387 my ($in, $opt)=_extract_hash(@_);
5388 barf 'Usage: points ( [$x,] $y, $sym, [$options] )' if $#$in<0 || $#$in>2;
5389 my ($x, $y, $sym)=@$in;
5390 $self->_checkarg($x,1);
5391 my $n=nelem($x);
5392  
5393 my ($is_1D, $is_2D);
5394 if ($#$in>=1) {
5395 $is_1D = $self->_checkarg($y,1,undef,1);
5396 if (!$is_1D) {
5397 $is_2D = $self->_checkarg($y,2,undef,1);
5398 barf '$y must be 1D (or 2D for broadcasting!)'."\n" if !$is_2D;
5399  
5400 # Ok, let us use the broadcasting possibility.
5401 $self->tpoints(@$in, $opt);
5402 return;
5403  
5404 } else {
5405 barf '$x and $y must be same size' if $n!=nelem($y);
5406 }
5407 } else {
5408 $y = $x; $x = float(sequence($n));
5409 }
5410  
5411 # Let us parse the options if any.
5412 $opt = {} if !defined($opt);
5413 my ($o, $u_opt) = $self->_parse_options($points_options, $opt);
5414 $self->_check_move_or_erase($o->{Panel}, $o->{Erase});
5415  
5416 #
5417 # Save some time for large datasets.
5418 #
5419 unless ( $self->held() ) {
5420 my ($xmin, $xmax)=ref $o->{XRange} eq 'ARRAY' ?
5421 @{$o->{XRange}} : minmax($x);
5422 my ($ymin, $ymax)=ref $o->{YRange} eq 'ARRAY' ?
5423 @{$o->{YRange}} : minmax($y);
5424 if ($xmin == $xmax) { $xmin -= 0.5; $xmax += 0.5; }
5425 if ($ymin == $ymax) { $ymin -= 0.5; $ymax += 0.5; }
5426 $self->initenv( $xmin, $xmax, $ymin, $ymax, $opt );
5427 }
5428 $self->_save_status();
5429 $self->_standard_options_parser($u_opt);
5430  
5431 # take logs if we are in autolog mode and axis option indicates logs
5432 ($x,$y) = $self->checklog($x,$y) if $self->autolog;
5433  
5434 catch_signals {
5435 if (exists($opt->{SymbolSize})) { # Set symbol size (2001.10.22 kwi)
5436 pgsch($opt->{SymbolSize});
5437 }
5438 if (exists($opt->{ColorValues})) {
5439 my $sym ||= $o->{Symbol} || 0;
5440 my $z = $opt->{ColorValues};
5441 $self->_checkarg($z,1); # make sure this is a float PDL
5442 pgcolorpnts($n, $x->get_dataref, $y->get_dataref, $z->get_dataref, $sym);
5443 } else {
5444 # Set symbol if specified in the options hash.
5445 ## $sym ||= $o->{Symbol};
5446 $sym = $o->{Symbol} unless defined $sym;
5447 $self->_checkarg($sym,1); my $ns = nelem($sym); $sym = long($sym);
5448 pgpnts($n, $x->get_dataref, $y->get_dataref, $sym->get_dataref, $ns);
5449 }
5450 #
5451 # Sometimes you would like to plot a line through the points straight
5452 # away.
5453 pgline($n, $x->get_dataref, $y->get_dataref) if $o->{PlotLine}>0;
5454 };
5455  
5456 $self->_restore_status();
5457 $self->_add_to_state(\&points, $in, $opt);
5458 1;
5459 }
5460 }
5461  
5462 # add a "wedge" to the image
5463 # - since this can be called from imag() as well as by the user,
5464 # we make all parameters defined as options
5465 #
5466 # Wedge => {
5467 # Side => one of B L T R,
5468 # Displacement => default = 2,
5469 # Width => default = 3,
5470 # Fg/Bg => default, values used by imag()
5471 # Label => default ''
5472 # }
5473 #
5474 # - uses horrible _store()/_retrieve() routines, which need to
5475 # know (but don't) about changing window focus/erasing/...
5476 #
5477 # Want to be able to specify a title (optional)
5478 # - also, by default want to use the axes colour/size, but want to be able to
5479 # over-ride this
5480 #
5481 # initial version by Doug Burke (11/20/00 ish)
5482  
5483 {
5484 my $wedge_options = undef;
5485  
5486 sub draw_wedge {
5487 my $self = shift;
5488 if ( !defined($wedge_options) ) {
5489 $wedge_options =
5490 $self->{PlotOptions}->extend({
5491 Side => 'R',
5492 Displacement => 1.5,
5493 Width =>3.0,
5494 WTitle => undef,
5495 Label => undef,
5496 ForeGround => undef,
5497 BackGround => undef,
5498 });
5499 $wedge_options->synonyms({ Fg => 'ForeGround', Bg => 'BackGround' });
5500 }
5501  
5502 my ( $in, $opt ) = _extract_hash(@_);
5503 $opt = {} unless defined($opt);
5504 barf 'Usage: $win->draw_wedge( [$options] )'
5505 unless $#$in == -1;
5506  
5507 # check imag has been called, and get information
5508 # - this is HORRIBLE
5509 my $iref = $self->_retrieve( 'imag' );
5510 barf 'draw_wedge() can only be called after a call to imag()'
5511 unless defined $iref;
5512  
5513 # Let us parse the options if any.
5514 # - not convinced I know what I'm doing
5515 my $o;
5516 if ( defined $opt->{Wedge} ) {
5517 $o = $wedge_options->options( $opt->{Wedge} );
5518 } else {
5519 $o = $wedge_options->current();
5520 }
5521 $o->{ForeGround} = $$iref{max} unless defined( $o->{ForeGround} );
5522 $o->{BackGround} = $$iref{min} unless defined( $o->{BackGround} );
5523  
5524 # do we really want this?
5525 # - (03/15/01 DJB) removed since I assume that draw_wedge()
5526 # will be called before the focus has been changed.
5527 # Not ideal, but I don't think the current implementation will
5528 # handle such cases anyway (ie getting the correct min/max values
5529 # for the wedge).
5530 # $self->_check_move_or_erase($o->{Panel}, $o->{Erase});
5531  
5532 # get the options used to draw the axes
5533 # note: use the window object, not the options hash, though we
5534 # probably could/should do that
5535 my $wo = $self->{_env_options}[4];
5536  
5537 # Save current status
5538 $self->_save_status();
5539  
5540 # we use the colour/size of the axes here
5541 $self->_set_colour($wo->{AxisColour});
5542 catch_signals {
5543 pgsch($wo->{CharSize});
5544 # draw the wedge
5545 my $side = $o->{Side} . $$iref{routine};
5546 pgwedg( $side, $o->{Displacement}, $o->{Width}, $o->{BackGround}, $o->{ForeGround}, $o->{Label} || $o->{WTitle} || '' );
5547 };
5548 # restore character colour & size before returning
5549 $self->_restore_status();
5550 $self->_add_to_state(\&draw_wedge, $in, $opt);
5551 1;
5552 } # sub: draw_wedge()
5553 }
5554  
5555 ######################################################################
5556 #
5557 # imag and related functions
5558 #
5559 # display an image using pgimag()/pggray()/pgrgbi() as appropriate.
5560 #
5561 # The longish routine '_imag' handles the meat and potatoes of the setup,
5562 # but hands off the final plot to the PGPLOT routines pgimag() or pgrgbi().
5563 # It expects a ref to the appropriate function to be passed in. The
5564 # userland methods 'imag' and 'rgbi' are just trampolines that call _imag
5565 # with the appropriate function ref.
5566 #
5567 # This gets pretty sticky for fits_imag, which is itself a trampoline for
5568 # _fits_foo -- so if you call fits_imag, it trampolines into fits_foo, which
5569 # does setup and then bounces into imag, which in turn hands off control
5570 # to pgimag. What a mess -- but at least it seems to work OK. For now.
5571 # -- CED 20-Jan-2002
5572 #
5573 {
5574 # The ITF is in the general options - since other functions might want
5575 # it too.
5576 #
5577 # There is some repetitiveness in the code, but this is to allow the
5578 # user to set global defaults when opening a new window.
5579 #
5580 #
5581 #
5582  
5583 my $im_options = undef;
5584 sub _imag {
5585 my $self = shift;
5586  
5587 if (!defined($im_options)) {
5588 $im_options = $self->{PlotOptions}->extend({
5589 Min => undef,
5590 Max => undef,
5591 Range => undef,
5592 CRange => undef,
5593 DrawWedge => 0,
5594 Wedge => undef,
5595 Justify => undef,
5596 Transform => undef
5597 });
5598 }
5599  
5600 ##############################
5601 # Unwrap first two arguments: the PGPLOT call and the
5602 # dimensions of the image variable (2 or 3 depending
5603 # on whether this is called by imag or rgbi)
5604 my $pgcall = shift;
5605 my $image_dims = shift;
5606  
5607 ##############################
5608 # Pull out the rest of the arg list, and parse the options (if any).
5609 my ($in, $opt)=_extract_hash(@_);
5610  
5611 $opt = {} if !defined($opt);
5612 my ($o, $u_opt) = $self->_parse_options($im_options, $opt);
5613  
5614 ##########
5615 # Default to putting tick marks outside the box, so that you don't
5616 # scrozzle images.
5617  
5618 $o->{Axis} = 'BCINST'
5619 unless (defined($opt->{Axis}) || ($o->{Axis} ne 'BCNST'));
5620  
5621 $self->_add_to_state(\&imag, $in, $opt);
5622 barf 'Usage: (imag|rgbi) ( $image, [$min, $max, $transform] )' if $#$in<0 || $#$in>3;
5623  
5624 my ($image,$min,$max,$tr) = @$in;
5625 my ($cmin, $cmax) = (0,1);
5626  
5627 ## Make sure the image has the right number of dims...
5628 $self->_checkarg($image,$image_dims);
5629  
5630 my($nx,$ny) = $image->dims;
5631 $nx = 1 unless($nx);
5632 $ny = 1 unless($ny);
5633  
5634 my $itf = 0;
5635  
5636 $tr = $u_opt->{Transform} if exists($u_opt->{Transform});
5637 $min = $u_opt->{Min} if exists($u_opt->{Min});
5638 $max = $u_opt->{Max} if exists($u_opt->{Max});
5639  
5640 # Check on ITF value hardcoded in.
5641 $itf = $u_opt->{ITF} if exists($u_opt->{ITF});
5642 barf ( "illegal ITF value `$itf'") if $itf > 2 || $itf < 0;
5643  
5644 ## Option checker thunk gets defined only on first run-through.
5645 our $checker = sub {
5646 my($name,$opt,$min,$max) = @_;
5647 delete $opt->{$name} unless(defined $opt->{$name});
5648 return unless exists($opt->{$name});
5649 barf("$name option must be an array ref if specified.\n")
5650 if( ref ($opt->{$name}) ne 'ARRAY' );
5651 ($$min,$$max) = @{$opt->{$name}} if defined($min);
5652 } unless(defined $checker);
5653  
5654 &$checker("Range", $u_opt, \$min, \$max);
5655 &$checker("CRange", $u_opt, \$cmin, \$cmax);
5656 &$checker("XRange", $u_opt);
5657 &$checker("YRange", $u_opt);
5658  
5659 $min = min($image) unless defined $min;
5660 $max = max($image) unless defined $max;
5661  
5662 if (defined($tr)) {
5663 $self->_checkarg($tr,1);
5664 barf '$transform incorrect' if nelem($tr)!=6;
5665 } else {
5666 $tr = float [0,1,0, 0,0,1];
5667 }
5668 $tr = $self->CtoF77coords($tr);
5669  
5670 $self->_check_move_or_erase($o->{Panel}, $o->{Erase});
5671  
5672 $self->initenv( _image_xyrange($tr,$nx,$ny,$o), $o );
5673  
5674 catch_signals {
5675 pgsitf( $itf );
5676 my ($i1, $i2);
5677  
5678 pgqcir($i1, $i2); # Default color range
5679  
5680 my($c1,$c2);
5681 $c1 = int($i1 + ($i2-$i1) * $cmin + 0.5);
5682 $c2 = int($i1 + ($i2-$i1) * $cmax + 0.5);
5683  
5684 print "Displaying $nx x $ny image from $min to $max, using ".($c2-$c1+1)." colors ($c1-$c2)...\n" if $PDL::verbose;
5685  
5686  
5687 # Disable PS pggray output because the driver is busted in pgplot-2.3
5688 # (haven't tested later versions). pgimag seems to work OK for that
5689 # output tho'.
5690 if ($c2-$c1<16 || $self->{Device} =~ /^v?ps$/i) {
5691 print STDERR "_imag: Under 16 colors available; reverting to pggray\n"
5692 if($PDL::debug || $PDL::verbose);
5693 pggray( $image->get_dataref,
5694 $nx,$ny,1,$nx,1,$ny, $min, $max,
5695 $tr->get_dataref);
5696 $self->_store( imag => { routine => "G", min => $min, max => $max } );
5697 } else {
5698 $self->ctab('Grey') unless $self->_ctab_set(); # Start with grey
5699  
5700 pgscir($c1,$c2);
5701  
5702 &$pgcall( $image->get_dataref,
5703 $nx,$ny,1,$nx,1,$ny, $min, $max,
5704 $tr->get_dataref);
5705  
5706 pgscir($i1,$i2);
5707  
5708 $self->_store( imag => { routine => "I", min => $min, max => $max } );
5709 }
5710 };
5711  
5712 # draw the wedge, if requested
5713 if ( $u_opt->{DrawWedge} ) {
5714 my $hflag = $self->held();
5715 $self->hold();
5716 $self->draw_wedge( $u_opt );
5717 $self->release() unless $hflag;
5718 }
5719 $self->redraw_axes($u_opt) unless $self->held();
5720 1;
5721 } # sub: imag()
5722 }
5723  
5724 ######################################################################
5725 # Here are the `top-level' imaging routines -- they call _imag to get
5726 # the job done.
5727  
5728  
5729 ##########
5730 # image - the basic image plotter
5731  
5732 sub imag {
5733 my $me = shift;
5734 my $im = shift;
5735 my @a = @_;
5736  
5737 if(UNIVERSAL::isa($im,'PDL') && ($im->ndims == 3) && ($im->dim(2)==3)) {
5738 rgbi($me,$im,@a);
5739 return;
5740 }
5741  
5742 _imag($me,\&pgimag,2,$im,@a);
5743 }
5744  
5745  
5746 ##########
5747 # imag1 - Plot an image with Justify = 1
5748  
5749 sub imag1 {
5750 my $self = shift;
5751 my ($in,$opt)=_extract_hash(@_);
5752  
5753 my $im_options = $self->{PlotOptions}->extend({
5754 Min => undef,
5755 Max => undef,
5756 DrawWedge => 0,
5757 Wedge => undef,
5758 XTitle => undef,
5759 YTitle => undef,
5760 Title => undef,
5761 Justify => 1
5762 });
5763  
5764 # Let us parse the options if any.
5765 $opt = {} if !defined($opt);
5766 my ($o, $u_opt) = $self->_parse_options($im_options, $opt);
5767  
5768 barf 'Usage: imag1 ( $image, [$min, $max, $transform] )' if $#$in<0 || $#$in>3;
5769 $o->{Pix} = 1 unless defined($o->{Pix});
5770 $self->imag (@$in,$o);
5771 # This is not added to the state, because the imag command does that.
5772 }
5773  
5774  
5775 ##########
5776 # rgbi - Plot an image with 3 color planes
5777  
5778 sub rgbi {
5779 unless($PGPLOT::RGB_OK) {
5780 print STDERR "PGPLOT rgbi called, but RGB support is not present. Using grayscale instead.\n";
5781 my $me = shift;
5782 my $in = shift;
5783 my $in2;
5784  
5785 if($in->dim(0)==3 && $in->dim(1)>3 && $in->dim(2)>3) {
5786 $in2 = $in->sumover;
5787 } else {
5788 $in2 = $in->mv(2,0)->sumover;
5789 }
5790 my @a = @_;
5791 return _imag($me,\&pgimag,2,$in2,@a);
5792 }
5793  
5794 barf("rgbi: RGB-enabled PGPLOT is not present\n")
5795 unless($PGPLOT::RGB_OK);
5796  
5797 my $me = shift;
5798 my @a = @_;
5799 my($in,$opt) = _extract_hash(@_);
5800 my($image) = shift @$in;
5801 if(UNIVERSAL::isa($image,'PDL')) {
5802 my @dims = $image->dims;
5803 if($dims[0] == 3 && $dims[1] > 3 && $dims[2] > 3) {
5804 print "rgbi: Hmmm... Found (rgb,X,Y) [deprecated] rather than (X,Y,rgb) [approved]."
5805 if($PDL::debug || $PDL::verbose);
5806 $image = $image->mv(0,2);
5807 }
5808 }
5809 $opt->{DrawWedge} = 0;
5810  
5811 # Get rid of nan elements...
5812 my $im2;
5813 my $m = !(isfinite $image);
5814 if(zcheck($m)) {
5815 $im2 = $image;
5816 } else {
5817 $im2 = $image->copy;
5818 $im2->range(scalar(whichND $m)) .= 0;
5819 }
5820  
5821 _imag($me,\&pgrgbi,3,$im2,@$in,$opt);
5822 }
5823  
5824  
5825 ######################################################################
5826 # Here are the FITS subroutines
5827 #
5828 # They all use _fits_foo as a ``pre-call'' to set up the appropriate
5829 # image transformations and plot command.
5830 #
5831 # by fits_imag, fits_rgbi, and fits_cont.
5832 #
5833 {
5834 my $f_im_options = undef;
5835  
5836 sub _fits_foo {
5837 my $pane = shift;
5838 my ($in,$opt_in) = _extract_hash(@_);
5839 my ($pdl,@rest) = @$in;
5840  
5841 $opt_in = {} unless defined($opt_in);
5842  
5843 unless ( defined($f_im_options) ) {
5844 $f_im_options = $pane->{PlotOptions}->extend({
5845 Contours=>undef,
5846 Follow=>0,
5847 Labels=>undef,
5848 LabelColour=>undef,
5849 Missing=>undef,
5850 NContours=>undef,
5851 FillContours=>undef,
5852 Min => undef,
5853 Max => undef,
5854 DrawWedge => 0,
5855 Wedge => undef,
5856 XRange=>undef,
5857 YRange=>undef,
5858 XTitle => undef,
5859 YTitle => undef,
5860 Title => undef,
5861 CharSize=>undef,
5862 CharThick=>undef,
5863 HardCH=>undef,
5864 HardLW=>undef,
5865 TextThick=>undef,
5866 WCS => undef,
5867 });
5868 }
5869  
5870 my($opt,$u_opt) = $pane->_parse_options($f_im_options,$opt_in);
5871 my $hdr = $pdl->gethdr();
5872  
5873 # What WCS system are we using?
5874 # we could check that the WCS is valid here but we delegate it
5875 # to the _FITS_tr() routine.
5876 my %opt2 = %$u_opt; # copy options
5877 my $wcs = delete $opt2{WCS} || "";
5878 $opt2{Transform} = _FITS_tr($pane,$pdl,{WCS => $wcs});
5879 delete @opt2{ grep /title/i, keys %opt2 };
5880 $opt2{Align} //= 'CC';
5881 $opt2{DrawWedge} //= 1;
5882  
5883 # I am assuming here that CUNIT1<A-Z> is a valid keyword for
5884 # 'alternative' WCS mappings (DJB)
5885 $opt2{Pix}=1.0
5886 if( (!defined($opt2{Justify}) || !$opt2{Justify}) &&
5887 (!defined($opt2{Pix})) &&
5888 ( $hdr->{"CUNIT1$wcs"} ?
5889 ($hdr->{"CUNIT1$wcs"} eq $hdr->{"CUNIT2$wcs"}) :
5890 ($hdr->{"CTYPE1$wcs"} eq $hdr->{"CTYPE2$wcs"})
5891 )
5892 );
5893  
5894 ([$pdl, @rest, \%opt2], [
5895 $opt->{XTitle} || _mkaxis(@$hdr{"CTYPE1$wcs","CUNIT1$wcs"}),
5896 $opt->{YTitle} || _mkaxis(@$hdr{"CTYPE2$wcs","CUNIT2$wcs"}),
5897 $opt->{Title}, $opt
5898 ]);
5899 } # sub: _fits_foo()
5900  
5901 my @fits_templates = ("(arbitrary units)","%u","%t","%t (%u)");
5902 sub _mkaxis {
5903 my ($typ,$unit) = @_;
5904 my $s = $fits_templates[2 * defined($typ) + (defined $unit && $unit !~ m/^\s+$/)];
5905 $s =~ s/%u/$unit/;
5906 $s =~ s/%t/$typ/;
5907 $s;
5908 }
5909  
5910 sub fits_imag {
5911 my $self = shift;
5912 my ($main_args, $label_args) = _fits_foo($self,@_);
5913 $self->imag(@$main_args);
5914 $self->label_axes(@$label_args);
5915 }
5916  
5917 sub fits_rgbi {
5918 my $self = shift;
5919 my ($main_args, $label_args) = _fits_foo($self,@_);
5920 $self->rgbi(@$main_args);
5921 $self->label_axes(@$label_args);
5922 }
5923  
5924 sub fits_cont {
5925 my $self = shift;
5926 my ($main_args, $label_args) = _fits_foo($self,@_);
5927 $self->cont(@$main_args);
5928 $self->label_axes(@$label_args);
5929 }
5930  
5931 sub fits_vect {
5932 my($self) = shift;
5933 my ($main_args, $label_args) = _fits_foo($self,@_);
5934 $self->vect(@$main_args);
5935 $self->label_axes(@$label_args);
5936 }
5937  
5938 } # closure around _fits_foo and fits_XXXX routines
5939  
5940 # Load a colour table using pgctab()
5941  
5942 #
5943 # Modified 7/4/02 JB - having the last colour table as a variable in here
5944 # did not work. So it is now moved to the $self hash.
5945 {
5946 # This routine doesn't really have any options at the moment, but
5947 # it uses the following standard variables
5948 my %CTAB = ();
5949 $CTAB{Grey} = [ pdl([0,1],[0,1],[0,1],[0,1]) ];
5950 $CTAB{Igrey} = [ pdl([0,1],[1,0],[1,0],[1,0]) ];
5951 $CTAB{Fire} = [ pdl([0,0.33,0.66,1],[0,1,1,1],[0,0,1,1],[0,0,0,1]) ];
5952 $CTAB{Gray} = $CTAB{Grey}; # Alias
5953 $CTAB{Igray} = $CTAB{Igrey}; # Alias
5954  
5955 # It would be easy to add options though..
5956 sub _ctab_set {
5957 my $self = shift;
5958 return defined($self->{CTAB});
5959 }
5960  
5961 sub ctab {
5962 my $self = shift;
5963 my ($in, $opt)=_extract_hash(@_);
5964  
5965  
5966 # No arguments -- print list of tables
5967 if (scalar(@$in) == 0) {
5968 print "Available 'standard' color tables are:\n",join(",",sort keys %CTAB)
5969 ,"\n";
5970 return;
5971 }
5972 # No arguments -- print list of tables
5973 if (scalar(@$in) == 0) {
5974 print "Available 'standard' color tables are:\n",join(",",sort keys %CTAB)
5975 ,"\n";
5976 return;
5977 }
5978  
5979 # First indirect arg list through %CTAB
5980 my(@arg) = @$in;
5981  
5982 my($ctab, $levels, $red, $green, $blue, $contrast, $brightness, @t, $n);
5983  
5984 if ($#arg>=0 && !ref($arg[0])) { # First arg is a name not an object
5985 # if first arg is undef or empty string, means use last CTAB.
5986 # preload with Grey if no prior CTAB
5987 $arg[0] = 'Grey' unless $arg[0] || $self->{CTAB};
5988  
5989 # now check if we're using the last one specified
5990 if ( ! $arg[0] ) {
5991 shift @arg;
5992 unshift @arg, @{$self->{CTAB}->{ctab}};
5993 $brightness = $self->{CTAB}->{brightness};
5994 $contrast = $self->{CTAB}->{contrast};
5995 } else {
5996 my $name = ucfirst(lc(shift @arg)); # My convention is $CTAB{Grey} etc...
5997 barf "$name is not a standard colour table" unless defined $CTAB{$name};
5998 unshift @arg, @{$CTAB{$name}};
5999 }
6000 }
6001  
6002  
6003 if ($#arg<0 || $#arg>5) {
6004 my @std = keys %CTAB;
6005 barf <<"EOD";
6006 Usage: ctab ( \$name, [\$contrast, $\brightness] ) # Builtin col table
6007 [Builtins: @std]
6008 ctab ( \$ctab, [\$contrast, \$brightness] ) # $ctab is Nx4 array
6009 ctab ( \$levels, \$red, \$green, \$blue, [\$contrast, \$brightness] )
6010 EOD
6011 }
6012  
6013  
6014 if ($#arg<3) {
6015 ($ctab, $contrast, $brightness) = @arg;
6016 @t = $ctab->dims; barf 'Must be a Nx4 array' if $#t != 1 || $t[1] != 4;
6017 $n = $t[0];
6018 $ctab = float($ctab) if $ctab->get_datatype != $PDL_F;
6019 my $nn = $n-1;
6020 $levels = $ctab->slice("0:$nn,0:0");
6021 $red = $ctab->slice("0:$nn,1:1");
6022 $green = $ctab->slice("0:$nn,2:2");
6023 $blue = $ctab->slice("0:$nn,3:3");
6024 } else {
6025 ($levels, $red, $green, $blue, $contrast, $brightness) = @arg;
6026 $self->_checkarg($levels,1); $n = nelem($levels);
6027 for ($red,$green,$blue) {
6028 $self->_checkarg($_,1); barf 'Arguments must have same size' unless nelem($_) == $n;
6029 }
6030 }
6031  
6032 # Now load it
6033  
6034 $contrast = 1 unless defined $contrast;
6035 $brightness = 0.5 unless defined $brightness;
6036  
6037 focus( $self );
6038  
6039 catch_signals {
6040 pgctab( $levels->get_dataref, $red->get_dataref, $green->get_dataref,
6041 $blue->get_dataref, $n, $contrast, $brightness );
6042 };
6043 $self->{CTAB} = { ctab => [ $levels, $red, $green, $blue ],
6044 brightness => $brightness,
6045 contrast => $contrast
6046 }; # Loaded
6047 $self->_add_to_state(\&ctab, $in, $opt);
6048 1;
6049 }
6050  
6051 # get information on last CTAB load
6052 sub ctab_info {
6053 my $self = shift;
6054 my ($in, $opt)=_extract_hash(@_);
6055 barf 'Usage: ctab_info( )' if $#$in> -1;
6056  
6057 return () unless $self->{CTAB};
6058 return @{$self->{CTAB}}{qw(ctab contrast brightness)};
6059 }
6060 }
6061  
6062 # display an image using pghi2d()
6063  
6064 {
6065  
6066 my $hi2d_options = undef;
6067  
6068 sub hi2d {
6069 my $self = shift;
6070 if (!defined($hi2d_options)) {
6071 $hi2d_options = $self->{PlotOptions}->extend({
6072 Ioff => undef,
6073 Bias => undef
6074 });
6075 }
6076 my ($in, $opt)=_extract_hash(@_);
6077 $opt = {} if !defined($opt);
6078  
6079 barf 'Usage: hi2d ( $image, [$x, $ioff, $bias] [, $options] )' if $#$in<0 || $#$in>3;
6080 my ($image, $x, $ioff, $bias) = @$in;
6081 $self->_checkarg($image,2);
6082 my($nx,$ny) = $image->dims;
6083  
6084 # Let us parse the options if any.
6085 my ($o, $u_opt) = $self->_parse_options($hi2d_options, $opt);
6086 $self->_check_move_or_erase($o->{Panel}, $o->{Erase});
6087  
6088 if (defined($x)) {
6089 $self->_checkarg($x,1);
6090 barf '$x incorrect' if nelem($x)!=$nx;
6091 } else {
6092 $x = float(sequence($nx));
6093 }
6094  
6095 # Parse for options input instead of calling convention
6096 $ioff = $o->{Ioff} || 1 unless defined($ioff);
6097 $bias = $o->{Bias} if defined($o->{Bias});
6098  
6099 $bias = 5*max($image)/$ny unless defined $bias;
6100 my $work = float(zeroes($nx));
6101  
6102 $self->_save_status();
6103 $self->_standard_options_parser($u_opt);
6104  
6105 $self->initenv( 0 ,2*($nx-1), 0, 10*max($image), $opt ) unless $self->held();
6106  
6107 catch_signals {
6108 pghi2d($image->get_dataref, $nx, $ny, 1,$nx,1,$ny, $x->get_dataref, $ioff,
6109 $bias, 1, $work->get_dataref);
6110 };
6111  
6112 $self->_restore_status();
6113 $self->_add_to_state(\&hi2d, $in, $opt);
6114 1;
6115 }
6116 }
6117  
6118 # Plot a rectangle with pgrect()
6119 sub rect {
6120 my $self = shift;
6121 my ($in, $opt)=_extract_hash(@_);
6122 barf 'Usage: rect ( $x1, $x2, $y1, $y2 [, $options] )' if( $#$in<0 || $#$in>3);
6123 my($x1,$x2,$y1,$y2) = @$in;
6124 $self->_checkarg($x1,1);
6125 $self->_checkarg($x2,1);
6126 $self->_checkarg($y1,1);
6127 $self->_checkarg($y2,1);
6128 my ($o, $u_opt) = $self->_parse_options($self->{PlotOptions}, ($opt || {}));
6129 $self->_check_move_or_erase($o->{Panel}, $o->{Erase});
6130  
6131 unless ( $self->held() ) {
6132 my ($xmin, $xmax)=ref $o->{XRange} eq 'ARRAY' ?
6133 @{$o->{XRange}} : minmax(pdl($x1->at(0),$x2->at(0)));
6134 my ($ymin, $ymax)=ref $o->{YRange} eq 'ARRAY' ?
6135 @{$o->{YRange}} : minmax(pdl($y1->at(0),$y2->at(0)));
6136 if ($xmin == $xmax) { $xmin -= 0.5; $xmax += 0.5; }
6137 if ($ymin == $ymax) { $ymin -= 0.5; $ymax += 0.5; }
6138 $self->initenv( $xmin, $xmax, $ymin, $ymax, $opt );
6139 }
6140  
6141 $self->_save_status();
6142 $self->_standard_options_parser($u_opt);
6143  
6144 catch_signals {
6145 pgrect($x1, $x2, $y1, $y2);
6146 };
6147 $self->_restore_status();
6148 $self->_add_to_state(\&poly, $in, $opt);
6149  
6150 1;
6151 }
6152  
6153  
6154  
6155 # Plot a polygon with pgpoly()
6156  
6157 sub poly {
6158 my $self = shift;
6159 my ($in, $opt)=_extract_hash(@_);
6160 barf 'Usage: poly ( $x, $y [, $options] )' if $#$in<0 || $#$in>2;
6161 my($x,$y) = @$in;
6162 $self->_checkarg($x,1);
6163 $self->_checkarg($y,1);
6164 my ($o, $u_opt) = $self->_parse_options($self->{PlotOptions}, $opt);
6165 $self->_check_move_or_erase($o->{Panel}, $o->{Erase});
6166  
6167 unless ( $self->held() ) {
6168 my ($xmin, $xmax)=ref $o->{XRange} eq 'ARRAY' ?
6169 @{$o->{XRange}} : minmax($x);
6170 my ($ymin, $ymax)=ref $o->{YRange} eq 'ARRAY' ?
6171 @{$o->{YRange}} : minmax($y);
6172 if ($xmin == $xmax) { $xmin -= 0.5; $xmax += 0.5; }
6173 if ($ymin == $ymax) { $ymin -= 0.5; $ymax += 0.5; }
6174 $self->initenv( $xmin, $xmax, $ymin, $ymax, $opt );
6175 }
6176  
6177 $self->_save_status();
6178 $self->_standard_options_parser($u_opt);
6179 my $n = nelem($x);
6180 catch_signals {
6181 pgpoly($n, $x->get_dataref, $y->get_dataref);
6182 };
6183 $self->_restore_status();
6184 $self->_add_to_state(\&poly, $in, $opt);
6185 1;
6186 }
6187  
6188 # Plot a circle using pgcirc
6189  
6190  
6191  
6192  
6193 {
6194 my $circle_options = undef;
6195  
6196 sub circle {
6197 my $self = shift;
6198 if (!defined($circle_options)) {
6199 $circle_options = $self->{PlotOptions}->extend({Radius => undef,
6200 XCenter => undef,
6201 YCenter => undef});
6202 }
6203 my ($in, $opt)=_extract_hash(@_);
6204 $opt = {} if !defined($opt);
6205 my ($x, $y, $radius)=@$in;
6206  
6207 my ($o, $u_opt) = $self->_parse_options($circle_options, $opt);
6208 $o->{XCenter}=$x if defined($x);
6209 $o->{YCenter}=$y if defined($y);
6210 $o->{Radius} = $radius if defined($radius);
6211  
6212 $self->_check_move_or_erase($o->{Panel}, $o->{Erase});
6213  
6214 ##DAL added this to properly set environment
6215 unless ( $self->held() ) {
6216 my ($xmin, $xmax)=ref $o->{XRange} eq 'ARRAY' ?
6217 @{$o->{XRange}} : ($x-$radius,$x+$radius);
6218 my ($ymin, $ymax)=ref $o->{YRange} eq 'ARRAY' ?
6219 @{$o->{YRange}} : ($y-$radius,$y+$radius);
6220 $self->initenv( $xmin, $xmax, $ymin, $ymax, $opt );
6221 }
6222 ##end DAL addition
6223  
6224 $self->_save_status();
6225 $self->_standard_options_parser($u_opt);
6226 catch_signals {
6227 pgcirc($o->{XCenter}, $o->{YCenter}, $o->{Radius});
6228 };
6229 $self->_restore_status();
6230 $self->_add_to_state(\&circle, $in, $opt);
6231 }
6232 }
6233  
6234 # Plot an ellipse using poly.
6235  
6236 {
6237 my $ell_options = undef;
6238  
6239 sub ellipse {
6240 my $self = shift;
6241 if (!defined($ell_options)) {
6242 $ell_options = $self->{PlotOptions}->extend({
6243 MajorAxis=>undef,
6244 MinorAxis=>undef,
6245 Theta => 0.0,
6246 XCenter => undef,
6247 YCenter => undef,
6248 NPoints => 100
6249 });
6250 $ell_options->synonyms({Angle => 'Theta'});
6251 }
6252 my ($in, $opt)=_extract_hash(@_);
6253 $opt = {} unless defined $opt;
6254 my ($x, $y, $c, $d, $theta)=@$in;
6255  
6256 my $o = $ell_options->options($opt);
6257 $o->{XCenter}=$x if defined($x);
6258 $o->{YCenter}=$y if defined($y);
6259 $o->{MajorAxis} = $c if defined($c);
6260 $o->{MinorAxis} = $d if defined($d);
6261 $o->{Theta}=$theta if defined($theta);
6262  
6263 if (!defined($o->{MajorAxis}) || !defined($o->{MinorAxis}) || !defined($o->{XCenter})
6264 || !defined($o->{YCenter})) {
6265 barf "The major and minor axis and the center coordinates must be given!";
6266 }
6267  
6268 $self->_check_move_or_erase($o->{Panel}, $o->{Erase});
6269  
6270 my $t = 2*$PI*sequence($o->{NPoints})/($o->{NPoints}-1);
6271 my ($xtmp, $ytmp) = ($o->{MajorAxis}*cos($t), $o->{MinorAxis}*sin($t));
6272  
6273 # Rotate the ellipse and shift it.
6274 my ($costheta, $sintheta)=(cos($o->{Theta}), sin($o->{Theta}));
6275 $x = $o->{XCenter}+$xtmp*$costheta-$ytmp*$sintheta;
6276 $y = $o->{YCenter}+$xtmp*$sintheta+$ytmp*$costheta;
6277  
6278 $self->_add_to_state(\&ellipse, $in, $opt);
6279 # Now turn off recording so we don't get this one twice..
6280 $self->turn_off_recording();
6281 $self->poly($x, $y, $opt);
6282 $self->turn_on_recording();
6283 }
6284 }
6285  
6286 {
6287 my $rect_opt = undef;
6288 sub rectangle {
6289 my $self = shift;
6290 my $usage='Usage: rectangle($xcenter, $ycenter, $xside, $yside, [, $angle, $opt])';
6291 if (!defined($rect_opt)) {
6292 # No need to use $self->{PlotOptions} here since we
6293 # pass control to poly below.
6294 $rect_opt = PDL::Options->new({XCenter => undef, YCenter => undef,
6295 XSide => undef, YSide => undef,
6296 Angle => 0, Side => undef});
6297 $rect_opt->synonyms({XCentre => 'XCenter', YCentre => 'YCenter',
6298 Theta => 'Angle'});
6299 $rect_opt->warnonmissing(0);
6300 }
6301 my ($in, $opt)=_extract_hash(@_);
6302 $opt={} if !defined($opt);
6303 my ($xc, $yc, $xside, $yside, $angle)=@$in;
6304 my $o=$rect_opt->options($opt);
6305  
6306 $o->{XCenter}=$xc if defined($xc);
6307 $o->{YCenter}=$yc if defined($yc);
6308 $o->{XSide}=$xside if defined($xside);
6309 $o->{YSide}=$yside if defined($yside);
6310 $o->{Angle}=$angle if defined($angle);
6311  
6312 ##
6313 # Now do some error checking and checks for squares.
6314 ##
6315 if (defined($o->{XSide}) || defined($o->{YSide})) {
6316 # At least one of these are set - let us ignore Side.
6317 $o->{XSide}=$o->{YSide} if !defined($o->{XSide});
6318 $o->{YSide}=$o->{XSide} if !defined($o->{YSide});
6319 } elsif (defined($o->{Side})) {
6320 $o->{XSide}=$o->{Side};
6321 $o->{YSide}=$o->{Side};
6322 } else {
6323 print "$usage\n";
6324 barf 'The sides of the rectangle must be specified!';
6325 }
6326  
6327 unless (defined($o->{XCenter}) && defined($o->{YCenter})) {
6328 print "$usage\n";
6329 barf 'The center of the rectangle must be specified!';
6330 }
6331  
6332 $self->_check_move_or_erase($o->{Panel}, $o->{Erase});
6333  
6334 # Ok if we got this far it is about time to do something useful,
6335 # namely construct the ndarray that contains the sides of the rectangle.
6336  
6337 # We make it first parallell to the coordinate axes around origo
6338 # and rotate it subsequently (ala the ellipse routine above).
6339 my ($dx, $dy)=(0.5*$o->{XSide}, 0.5*$o->{YSide});
6340 my $xtmp = pdl(-$dx, $dx, $dx, -$dx, -$dx);
6341 my $ytmp = pdl(-$dy, -$dy, $dy, $dy, -$dy);
6342  
6343 my ($costheta, $sintheta)=(cos($o->{Angle}), sin($o->{Angle}));
6344 my $x = $o->{XCenter}+$xtmp*$costheta-$ytmp*$sintheta;
6345 my $y = $o->{YCenter}+$xtmp*$sintheta+$ytmp*$costheta;
6346  
6347 $self->_add_to_state(\&rectangle, $in, $opt);
6348 # Turn off recording temporarily.
6349 $self->turn_off_recording();
6350 $self->poly($x, $y, $opt);
6351 $self->turn_on_recording();
6352 }
6353 }
6354  
6355  
6356 # display a vector map of 2 images using pgvect()
6357  
6358 {
6359 my $vect_options = undef;
6360  
6361 sub vect {
6362 my $self = shift;
6363 if (!defined($vect_options)) {
6364 $vect_options = $self->{PlotOptions}->extend({
6365 Scale => 0,
6366 Position => 0,
6367 Missing => undef
6368 });
6369 $vect_options->add_synonym({Pos => 'Position'});
6370 }
6371 my ($in, $opt)=_extract_hash(@_);
6372 barf 'Usage: vect ( $x, $y, [$scale, $pos, $transform, $misval] )' if $#$in<1 || $#$in>5;
6373 my ($x, $y, $scale, $pos, $tr, $misval) = @$in;
6374 $self->_checkarg($x,2); $self->_checkarg($y,2);
6375 my($nx,$ny) = $x->dims;
6376 my($n1,$n2) = $y->dims;
6377 barf 'Dimensions of $x and $y must be the same' unless $n1==$nx && $n2==$ny;
6378  
6379 my ($o, $u_opt) = $self->_parse_options($vect_options, $opt);
6380 $self->_check_move_or_erase($o->{Panel}, $o->{Erase});
6381  
6382 # Parse for options input instead of calling convention
6383 $scale = $o->{Scale} if exists($u_opt->{Scale});
6384 $pos = $o->{Position} if exists($u_opt->{Scale});
6385 $tr = $o->{Transform} if exists($u_opt->{Transform});
6386 $misval = $o->{Missing} if exists($u_opt->{Missing});
6387 #What if there's no Missing option supplied and one of the input ndarrays
6388 #contain zero? Then that location will have no arrow, instead of a
6389 #horizontal or vertical line. So define $misval, but make it meaningless:
6390 $misval = 1 + $x->glue(0,$y)->flat->maximum unless defined $misval; #DAL added 02-Jan-2006
6391  
6392 $scale = 0 unless defined $scale;
6393 $pos = 0 unless defined $pos;
6394  
6395 if (defined($tr)) {
6396 $self->_checkarg($tr,1);
6397 barf '$transform incorrect' if nelem($tr)!=6;
6398 } else {
6399 $tr = float [0,1,0, 0,0,1];
6400 }
6401 $tr = $self->CtoF77coords($tr);
6402  
6403 $self->initenv( 0, $nx-1, 0, $ny-1, $opt ) unless $self->held();
6404 print "Vectoring $nx x $ny images ...\n" if $PDL::verbose;
6405  
6406 $self->_save_status();
6407 $self->_standard_options_parser($u_opt); # For arrowtype and arrowhead
6408 catch_signals {
6409 pgvect( $x->get_dataref, $y->get_dataref, $nx,$ny,1,$nx,1,$ny, $scale,
6410 $pos, $tr->get_dataref, $misval);
6411 };
6412 $self->_restore_status();
6413 $self->_add_to_state(\&vect, $in, $opt);
6414 1;
6415 }
6416 }
6417  
6418 # ############ Text routines #############
6419  
6420  
6421  
6422 {
6423 # Do not create this object unless necessary.
6424 my $text_options = undef;
6425  
6426 sub text {
6427 my $self = shift;
6428  
6429 if (!defined($text_options)) {
6430 # This is the first time this routine is called so we
6431 # have to initialise the options object.
6432 $text_options = $self->{PlotOptions}->extend({
6433 Angle => 0.0,
6434 Justification => 0.0,
6435 Text => '',
6436 XPos => undef,
6437 YPos => undef
6438 });
6439 $text_options->add_synonym({Justify => 'Justification'});
6440 $text_options->add_synonym({Bg => 'BackgroundColour'});
6441 }
6442  
6443 # Extract the options hash and separate it from the other input
6444 my ($in, $opt)=_extract_hash(@_);
6445 $opt = {} if !defined($opt);
6446 barf 'Usage: text ($text, $x, $y, [,$opt])' if
6447 (!defined($opt) && $#$in < 2) || ($#$in > 3) || ($#$in < 0);
6448 my ($text, $x, $y)=@$in;
6449  
6450 # Next - parse options
6451 my ($o, $u_opt) = $self->_parse_options($text_options, $opt);
6452  
6453 # Check for change of panel or request to erase the panel
6454 # (Commented out by CED 21-Jun-2002, because this seems
6455 # to erase too much -- e.g. it's hard to scribble on a line plot!)
6456 # $self->_check_move_or_erase($o->{Panel}, $o->{Erase});
6457 # Parse standard options such as colour
6458  
6459 $self->_save_status();
6460  
6461 $self->_standard_options_parser($u_opt);
6462  
6463 # Finally do what the routine needs to do.
6464 $o->{Text}=$text if defined($text);
6465 $o->{XPos}=$x if defined($x);
6466 $o->{YPos}=$y if defined($y);
6467 barf "text: You must specify the X-position!\n" if !defined($o->{XPos});
6468 barf "text: You must specify the Y-position!\n" if !defined($o->{YPos});
6469  
6470 # Added support for different background colours..
6471 # 2/10/01 JB - To avoid -w noise we use a reg-exp..
6472  
6473 if ($o->{BackgroundColour} !~ m/^-\d+$/) {
6474 $self->_set_colour($o->{BackgroundColour}, 1);
6475 }
6476  
6477 # what width do we use?
6478 # - things are somewhat confused since we have
6479 # LineWidth and TextWidth (a recent addition)
6480 # and LineWidth is set by _setup_window() - so
6481 # _standard_options_parser() uses it - but
6482 # TextWidth isn't.
6483 #
6484 # so for now we over-ride the _standard_options_parser
6485 # setting if TextWidth exists
6486 # [DJB 2002 Aug 08]
6487 my $old_lw;
6488 catch_signals {
6489 if ( defined($o->{TextWidth}) ) {
6490 pgqlw($old_lw);
6491 pgslw($o->{TextWidth});
6492 }
6493 my $old_bg;
6494 pgptxt($o->{XPos}, $o->{YPos}, $o->{Angle}, $o->{Justification},
6495 $o->{Text});
6496 pgslw($old_lw) if defined $old_lw;
6497 };
6498 $self->_restore_status();
6499 $self->_add_to_state(\&text, $in, $opt);
6500 1;
6501 }
6502 }
6503  
6504  
6505  
6506 {
6507 my $legend_options = undef;
6508  
6509 sub legend {
6510  
6511 my $self = shift;
6512 if (!defined($legend_options)) {
6513 $legend_options = $self->{PlotOptions}->extend({
6514 Text => undef,
6515 XPos => undef,
6516 YPos => undef,
6517 Width => 'Automatic',
6518 Height => 'Automatic',
6519 TextFraction => 0.5,
6520 TextShift => 0.1,
6521 VertSpace => 0
6522 });
6523 # should this be synonyms() or add_synonym() ? DJB 09 Apr 03
6524 $legend_options->add_synonym({
6525 VSpace => 'VertSpace',
6526 Fraction => 'TextFraction',
6527 Bg => 'BackgroundColour',
6528 });
6529 }
6530 my ($in, $opt)=_extract_hash(@_);
6531 $opt = {} if !defined($opt);
6532 my ($o, $u_opt) = $self->_parse_options($legend_options, $opt);
6533  
6534 #
6535 # In this function there are several options that we do not want
6536 # parsed by the standard options parsers so we deal with these
6537 # here - we translate the linestyles, symbols and colours below
6538 #
6539 my %myopt;
6540 foreach my $optname ( qw( LineStyle LineWidth Colour Symbol ) ) {
6541 my $tmp = $u_opt->{$optname};
6542 $myopt{lc($optname)} = ref($tmp) eq "ARRAY" ? $tmp : [$tmp];
6543 delete $u_opt->{$optname};
6544 }
6545  
6546 my ($text, $x, $y, $width)=@$in;
6547 $o->{Text} = $text if defined($text);
6548 $o->{XPos} = $x if defined($x);
6549 $o->{YPos} = $y if defined($y);
6550 $o->{Width} = $width if defined($width);
6551  
6552 # We could keep accessing $o but this is more succint.
6553 # [In the following we want to deal with an array of text.]
6554 $text = $o->{Text};
6555 $text = [$text] unless ref($text) eq 'ARRAY';
6556 my $n_lines = $#$text+1;
6557  
6558 if (!defined($o->{XPos}) || !defined($o->{YPos}) || !defined($o->{Text})) {
6559 barf 'Usage: legend $text, $x, $y [,$width, $opt] (styles are given in $opt)';
6560 }
6561  
6562 $self->_save_status();
6563  
6564 $self->_standard_options_parser($u_opt); # Set font, charsize, colour etc.
6565  
6566 # Ok, introductory stuff has been done, lets get down to the gritty
6567 # details. First let us save the current character size.
6568 catch_signals {
6569 pgqch(my $chsz);
6570  
6571 ## Now, set the background colour of the text before getting further.
6572 ## Added 2/10/01 - JB - test as a regexp to avoid -w noise.
6573 if ($o->{BackgroundColour} !~ m/^-?\d+$/) {
6574 # Do this unless a negative integer..
6575 $self->_set_colour($o->{BackgroundColour}, 1);
6576 }
6577  
6578 # The size of the legend can be specified by giving the width or the
6579 # height so to calculate the required text size we need to find the
6580 # minimum required (since text in PGPLOT cannot have variable width
6581 # and height.
6582 # Get the window size.
6583 pgqwin( my $xmin, my $xmax, my $ymin, my $ymax );
6584  
6585 # note: VertSpace is assumed to be a scalar
6586 my $vfactor = 1.0 + $o->{VertSpace};
6587  
6588 my $required_charsize=$chsz*9000;
6589  
6590 if ($o->{Width} eq 'Automatic' && $o->{Height} eq 'Automatic') {
6591 # Ok - we just continue with the given character size.
6592 $required_charsize = $chsz;
6593 # We still need to calculate the width and height of the legend
6594 # though. Fixed 20/3/01
6595  
6596 my $t_width = -1; # Very short text...
6597 my $t_height = -1; # And very low
6598 foreach my $t (@$text) {
6599 # Find the bounding box of left-justified text
6600 pgqtxt($xmin, $ymin, 0.0, 0.0, $t, my $xbox, my $ybox);
6601 my $dx = $$xbox[2] - $$xbox[0];
6602 my $dy = $$ybox[2] - $$ybox[0];
6603 $t_width = $dx if $dx > $t_width;
6604 $t_height = $dy if $dy > $t_height;
6605 }
6606  
6607 $o->{Width} = $t_width/$o->{TextFraction};
6608 # we include an optional vspace (which is given as a fraction of the
6609 # height of a line)
6610 $o->{Height} = $t_height*$vfactor*$n_lines; # The height of all lines..
6611 } else {
6612 # We have some constraint on the size.
6613 my ($win_width, $win_height)=($xmax-$xmin, $ymax-$ymin);
6614  
6615 # If either the width or the height is set to automatic we set
6616 # the width/height here to be 2 times the width/height of the
6617 # plot window - thus ensuring not too large a text size should the
6618 # user have done something stupid, but still large enough to
6619 # detect an error.
6620 $o->{Width} = 2*$win_width/$o->{TextFraction} if $o->{Width} eq 'Automatic';
6621 $o->{Height} = 2*$win_height if $o->{Height} eq 'Automatic';
6622  
6623 foreach my $t (@$text) {
6624 # Find the bounding box of left-justified text
6625 pgqtxt($xmin, $ymin, 0.0, 0.0, $t, my $xbox, my $ybox);
6626 my $dx = $$xbox[2] - $$xbox[0];
6627 my $dy = $$ybox[2] - $$ybox[0];
6628  
6629 # Find what charactersize is required to fit the height
6630 # (accounting for vspace) or fraction*width:
6631 my $t_width = $o->{TextFraction}*$o->{Width}/$dx;
6632 my $t_height = $o->{Height}/$vfactor/$n_lines/$dy; # XXX is $vfactor==(1+VertSpace) correct?
6633  
6634 my $t_chsz = ($t_width < $t_height ? $t_width*$chsz : $t_height*$chsz);
6635  
6636 $required_charsize = $t_chsz if $t_chsz < $required_charsize;
6637  
6638 pgsch($required_charsize*$chsz); # Since we measured relative to $chsz
6639 }
6640 }
6641  
6642 #
6643 # Ok, $required_charsize should now contain the optimal size for the
6644 # text. The next step is to create the legend. We can set linestyle,
6645 # linewidth, colour and symbol for each of these texts.
6646 #
6647 my ($xpos, $ypos) = ($o->{XPos}, $o->{YPos});
6648 my ($xstart, $xend)=($o->{XPos}+$o->{TextFraction}*$o->{Width}+
6649 $o->{TextShift}*$o->{Width}, $o->{XPos}+$o->{Width});
6650 my $xmid = 0.5 * ($xstart + $xend);
6651  
6652 # step size in y
6653 my $ystep = $o->{Height} / $n_lines;
6654  
6655 # store current settings
6656 pgqci(my $col);
6657 pgqls(my $ls);
6658 pgqlw(my $lw);
6659  
6660 foreach (my $i=0; $i<$n_lines; $i++) {
6661 $self->text($text->[$i], $xpos, $ypos);
6662 # Since the parsing of options does not go down array references
6663 # we need to create a temporary PDL::Options object here to do the
6664 # parsing..
6665 my $t_o = $self->{PlotOptions}->options({
6666 Symbol => $myopt{symbol}[$i],
6667 LineStyle => $myopt{linestyle}[$i],
6668 LineWidth => $myopt{linewidth}[$i],
6669 Colour => $myopt{colour}[$i],
6670 });
6671  
6672 $self->_set_colour($t_o->{Colour}) if defined($myopt{colour}[$i]);
6673  
6674 # Use the following to get the lines/symbols centered on the
6675 # text.
6676 pgqtxt($xpos, $ypos, 0.0, 0.0, $text->[$i], my $xbox, my $ybox);
6677 my $ymid = 0.5 * ($$ybox[2] + $$ybox[0]);
6678  
6679 if (defined($myopt{symbol}[$i])) {
6680 pgpt(1, $xmid, $ymid, $t_o->{Symbol});
6681  
6682 } else {
6683 pgsls($t_o->{LineStyle}) if defined $myopt{linestyle}[$i];
6684 pgslw($t_o->{LineWidth}) if defined $myopt{linewidth}[$i];
6685 pgline(2, [$xstart, $xend], [$ymid, $ymid]);
6686 }
6687  
6688 # reset colour, line style & width after each line
6689 $self->_set_colour($col);
6690 pgsls($ls);
6691 pgslw($lw);
6692  
6693 $ypos -= $ystep;
6694 }
6695 };
6696 $self->_restore_status();
6697 $self->_add_to_state(\&legend, $in, $opt);
6698 }
6699 }
6700  
6701  
6702  
6703  
6704  
6705 ############## Cursor routine ##################
6706  
6707  
6708  
6709 {
6710 my $cursor_options = undef;
6711 sub cursor {
6712  
6713 my $self = shift;
6714 # Let us check if this is a hardcopy device, in which case we will return
6715 # with a warning and undefined values.
6716 my ($hcopy, $len);
6717 pgask(0);
6718 pgqinf("HARDCOPY",$hcopy,$len);
6719 if ($hcopy eq 'YES') {
6720 warn "cursor called on a hardcopy device - returning!\n";
6721 return (undef, undef, undef, undef, undef);
6722 }
6723  
6724 if (!defined($cursor_options)) {
6725 $cursor_options = PDL::Options->new(
6726 {
6727 'XRef' => undef,
6728 'YRef' => undef,
6729 'Type' => 0
6730 });
6731 $cursor_options->translation({Type=>{
6732 'Default' => 0,
6733 'RadialLine' => 1,
6734 'Rectangle' => 2,
6735 'TwoHorizontalLines' => 3,
6736 'TwoVerticalLines' => 4,
6737 'HorizontalLine' => 5,
6738 'VerticalLine' => 6,
6739 'CrossHair' => 7
6740 }});
6741 }
6742  
6743 my ($opt)=@_;
6744  
6745 $opt = {} unless defined($opt);
6746 my $place_cursor=1; # Since X&Y might be uninitialised.
6747 my $o = $cursor_options->options($opt);
6748  
6749 my ($x, $y, $ch);
6750  
6751 # The window needs to be focussed before using the cursor commands.
6752 # Added 08/08/01 by JB after bug report from Brad Holden.
6753 $self->focus();
6754  
6755 catch_signals {
6756 if ($o->{Type} eq 'Rectangle' && !defined($o->{XRef})) {
6757 #
6758 # We use pgcurs to get a first position.
6759 #
6760 print "Please select a corner of the rectangle\n";
6761 pgcurs($x, $y, $ch);
6762 $o->{XRef}=$x;
6763 $o->{YRef}=$y;
6764 }
6765  
6766 if ($o->{Type} > 7 || $o->{Type} < 0) {
6767 print "Unknown type of cursor $$o{Type} - using Default\n";
6768 $o->{Type}=0;
6769 }
6770 my ($xmin, $xmax, $ymax, $ymin);
6771 pgqwin($xmin, $xmax, $ymin, $ymax);
6772  
6773 $x = $o->{XRef} if defined($o->{XRef});
6774 $y = $o->{YRef} if defined($o->{YRef});
6775  
6776 $x = 0.5*($xmin+$xmax) if !defined($x);
6777 $y = 0.5*($ymin+$ymax) if !defined($y);
6778  
6779 my ($got_xref, $got_yref)=(defined($o->{XRef}), defined($o->{YRef}));
6780 if (!$got_xref || !$got_yref) {
6781 # There is a little bit of gritty error-checking
6782 # for the users convenience here.
6783 if ($o->{Type}==1 || $o->{Type}==2) {
6784 barf "When specifying $$o{Type} as cursor you must specify the reference point";
6785 } elsif ($o->{Type}==3 && !$got_yref) {
6786 barf "When specifying two horizontal lines you must specify the Y-reference";
6787 } elsif ($o->{Type}==4 && !$got_xref ) {
6788 barf "When specifying two vertical lines you must specify the X-reference";
6789 }
6790  
6791 # Ok so we have some valid combination of type and reference point.
6792 $o->{XRef}=$xmin if !$got_xref;
6793 $o->{YRef}=$ymin if !$got_yref;
6794  
6795 }
6796  
6797  
6798 $ch = ''; # To silence -w
6799 my $istat = pgband($o->{Type}, $place_cursor, $o->{XRef},
6800 $o->{YRef}, $x, $y, $ch);
6801 };
6802  
6803 $self->_add_to_state(\&cursor, [], $opt);
6804 return ($x, $y, $ch, $o->{XRef}, $o->{YRef});
6805  
6806 }
6807 }
6808  
6809  
6810 =head1 INTERNAL
6811  
6812 The coding tries to follow reasonable standards, so that all functions
6813 starting with an underscore should be considered as internal and should
6814 not be called from outside the package. In addition most routines have
6815 a set of options. These are encapsulated and are not accessible outside
6816 the routine. This is to avoid collisions between different variables.
6817  
6818  
6819 =head1 AUTHOR
6820  
6821 Karl Glazebrook [kgb@aaoepp.aao.gov.au] modified by Jarle Brinchmann
6822 (jarle@astro.ox.ac.uk) who is also responsible for the OO interface,
6823 docs mangled by Tuomas J. Lukka (lukka@fas.harvard.edu) and
6824 Christian Soeller (c.soeller@auckland.ac.nz). Further contributions and
6825 bugfixes from Kaj Wiik, Doug Burke, Craig DeForest, and many others.
6826  
6827 All rights reserved. There is no warranty. You are allowed
6828 to redistribute this software / documentation under certain
6829 conditions. For details, see the file COPYING in the PDL
6830 distribution. If this file is separated from the PDL distribution,
6831 the copyright notice should be included in the file.
6832  
6833 =cut
6834  
6835 1;