blib/lib/PDL/Graphics/PGPLOT/Window.pm

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