blib/lib/PDL/Graphics/Prima/PlotType.pm untested

filter: Statementstmt 0.0% 0 / 697 Branchbran 0.0% 0 / 266 Conditioncond 0.0% 0 / 71 MC/DCmcdc n/a Subroutinesub 0.0% 0 / 107 Podpod 0.0% 0 / 75 totaltotal 0.0% 0 / 1216 CC 134 SCAR 43.2
CC
134
Cov
0%
initialize
380.0
compute_collated_min_max_for
342.0
parse_position
90.0
CRAP 75.4
1 use strict;
2 use warnings;
3 use PDL::NiceSlice;
4  
5 # Note: The base class is defined near the bottom of the file because I wanted
6 # to write the documentation for creating new derived classes in the same space
7 # as where I wrote the code for the base class.
8  
9 =head1 NAME
10  
11 PDL::Graphics::Prima::PlotType - a collection of plot types
12  
13 =head1 SYNOPSIS
14  
15 use PDL;
16 use PDL::Graphics::Prima::Simple -sequential;
17 my $x = sequence(100)/10;
18 my $y = sin($x);
19
20 # A lines+diamonds plot
21 plot(
22 -data => ds::Pair(
23 $x,
24 $y,
25 plotTypes => [
26 ppair::Lines,
27 ppair::Diamonds,
28 ],
29 ),
30 );
31
32 # Dandelions:
33 $x = random(10);
34 $y = random(10) + 0.5;
35 plot(
36 -data => ds::Pair(
37 $x,
38 $y,
39 plotTypes => [
40 ppair::Spikes(colors => cl::Green, lineWidths => 2),
41 ppair::Asterisks(N_points => 11, colors => cl::White),
42 ],
43 ),
44 backColor => cl::LightBlue,
45 color => cl::White,
46 );
47
48  
49 =head1 DESCRIPTION
50  
51 This module provides a number of basic plot types that you can use in a
52 PDL::Graphics::Prima plot. As far as PDL::Graphics::Prima is concerned, there
53 are different kinds of data that you might want to visualize, each with their
54 own distinct plot types. The three kinds of basic data sets, as described in
55 L<PDL::Graphics::Prima::DataSet>, are Sets, Pairs, and Grids. Here, I will
56 discuss the different plot types that you can apply to each of these sorts of
57 data.
58  
59 Just as you can specify properties for C<DataSet>s, you can also specify properties
60 for individual <PlotType>s. XXX working here - discuss PlotType-wide properties
61 (singular) and threaded (plural) properties, and ensure that they are handled
62 as documented.
63  
64 # Specify the color for each blob:
65 ppair::Blobs(colors => $my_colors)
66
67 # Specify different line widths for each column in the histogram:
68 ppair::Histogram(lineWidths => $the_widths)
69  
70 =cut
71  
72 ###############################################################################
73 # Pair-based Plot Types #
74 ###############################################################################
75  
76 package PDL::Graphics::Prima::PlotType::Pair;
77 use base 'PDL::Graphics::Prima::PlotType';
78  
79 # A function that gets the data and performs the real-to-pixel conversion:
80 sub get_data_as_pixels {
81 my ($self, $ratio) = @_;
82 my ($xs, $ys) = $self->get_data;
83
84 return ($self->widget->x->reals_to_pixels($xs, $ratio)
85 , $self->widget->y->reals_to_pixels($ys, $ratio));
86 }
87  
88 =head2 Pairs
89  
90 Many plots are based on plotting x/y pairs
91  
92 working here
93  
94 of data or lines, or perhaps shaded
95 areas. If you think of your data as a function of a single variable, like a
96 time series, you will likely use these plot types to visualize your data.
97  
98 =over
99  
100 =cut
101  
102 ###################################################
103 # PDL::Graphics::Prima::PlotType::Pair::Lines #
104 ###################################################
105  
106 =item ppair::Lines
107  
108 =for ref
109  
110 ppair::Lines( [thread_like => STRING,] options )
111  
112 Draws the x/y data as lines, connecting each pair of points with a line
113 segment. The behavior of the line drawing depends on what kind of threading
114 you want. You can specify that the threading behave like lines:
115  
116 ppair::Lines(thread_like => 'lines', ...)
117  
118 which is the default, or like points:
119  
120 ppair::Lines(thread_like => 'points', ...)
121  
122 Threading like lines does not play well with the many point-based plotTypes.
123 For all of those plotTypes, you can specify one property per point (like
124 C<colors> and C<lineWidths>), but doing so could lead to thread index
125 mismatch and an error in C<collate_min_max_wrt_many>:
126  
127 Index mismatch in collate_min_max_wrt_many ...
128  
129 So, if you want a line with continually changing thicknesses, or continually
130 changing colors, you should specify that it thread like C<points>.
131  
132 However, threading like points has one major drawback, which is that it does
133 not properly handle line styles. For example, if you wanted a dashed curve,
134 you would specify
135  
136 ppair::Lines(..., linePattern => lp::Dash)
137  
138 When you thread like points, each line segment is treated as a seperate line.
139 That mis-applies your dashing style. For large datasets (more than a million
140 points), another problem with point-like threading is that it uses more
141 memory and CPU to perform the drawing.
142  
143 =cut
144  
145 package PDL::Graphics::Prima::PlotType::Pair::Lines;
146 our @ISA = qw(PDL::Graphics::Prima::PlotType::Pair);
147  
148 # Install the short name constructor:
149 sub ppair::Lines {
150 PDL::Graphics::Prima::PlotType::Pair::Lines->new(@_);
151 }
152  
153 # Handle the 'thread_over' property.
154 sub initialize {
155 my $self = shift;
156  
157 # Call the superclass initialization:
158 $self->SUPER::initialize(@_);
159
160 $self->{thread_like} = 'lines' unless defined $self->{thread_like};
161 $self->{thread_like} = lc $self->{thread_like};
162
163 # Make sure it's a valid option:
164 croak("thread_like should either be lines or points")
165 unless $self->{thread_like} =~ /^(lines|points)$/;
166 }
167  
168 # Collation needs some work, since the threading doesn't work quite right
169 # out-of-the-box. The line data is polyline data and it must be reduced
170 # first.
171 sub compute_collated_min_max_for {
172 my ($self, $axis_name, $pixel_extent) = @_;
173 # Get the list of properties for which we need to look for bad values:
174 my @prop_list = $self->{thread_like} eq 'lines' ? @PDL::Drawing::Prima::polylines_props
175 : @PDL::Drawing::Prima::lines_props;
176 my %properties = $self->generate_properties(@prop_list);
177
178 # Extract the line widths, against which we'll collate:
179 my $lineWidths = $properties{lineWidths};
180 $lineWidths = $self->widget->lineWidth unless defined $lineWidths;
181 delete $properties{lineWidths};
182 # get the rest of the piddles, all of which are associated with plural
183 # endings:
184 my @prop_piddles;
185 while(my ($k, $v) = each %properties) {
186 push @prop_piddles, $v if $k =~ /s$/;
187 }
188
189 # Get the data:
190 my ($xs, $ys) = $self->get_data;
191 my ($min_x, $min_y, $max_x, $max_y) = PDL::minmaxforpair($xs, $ys);
192
193 # working here - now that minmaxforpair does not return infs, make sure
194 # this works
195 my ($min_to_check, $max_to_check) = ($min_x, $max_x);
196 ($min_to_check, $max_to_check) = ($min_y, $max_y) if $axis_name eq 'y';
197
198 # Collate the min and the max:
199 return PDL::collate_min_max_wrt_many($min_to_check, $lineWidths,
200 $max_to_check, $lineWidths, $pixel_extent, @prop_piddles);
201 }
202  
203 sub draw {
204 my ($self, $canvas, $ratio) = @_;
205
206 # Assemble the various properties from the plot-type object and the dataset
207 my @prop_list = $self->{thread_like} eq 'lines' ? @PDL::Drawing::Prima::polylines_props
208 : @PDL::Drawing::Prima::lines_props;
209 my %properties = $self->generate_properties(@prop_list);
210  
211 # Retrieve the data from the dataset:
212 my ($xs, $ys) = $self->get_data_as_pixels($ratio);
213
214 if ($self->{thread_like} eq 'points') {
215 # Draw from the points to their half-way points:
216 my $left_xs = $xs->copy;
217 my $right_xs = $xs->copy;
218 $right_xs(0:-2) .= $left_xs(1:-1) .= ($xs(1:-1) + $xs(0:-2)) / 2;
219
220 my $left_ys = $ys->copy;
221 my $right_ys = $ys->copy;
222 $right_ys(0:-2) .= $left_ys(1:-1) .= ($ys(1:-1) + $ys(0:-2)) / 2;
223 $canvas->pdl_lines($left_xs, $left_ys, $right_xs, $right_ys, %properties);
224 }
225 else {
226 # Draw the lines as single curves:
227 $canvas->pdl_polylines($xs, $ys, %properties);
228 }
229 }
230  
231 ####################################################
232 # PDL::Graphics::Prima::PlotType::Pair::Trendlines #
233 ####################################################
234  
235 =item ppair::Trendlines
236  
237 =for ref
238  
239 ppair::Trendlines( [thread_like => STRING,] [weights => PDL,]
240 [along_dim => INTEGER,] options )
241  
242 Draws linear fits to the x/y data as lines. This is a descendent of
243 C<ppair::Lines>, so you can specify the style of threading you want employed.
244 You can also specify the weights that you want used for your fitting. The
245 default is equal weights.
246  
247 If you are using multidimensional data, the fit is performed along the first
248 dimension by default. However, if you need to perform the fit along some
249 other dimension, you can specify that with the C<along_dim> key.
250  
251 =cut
252  
253 package PDL::Graphics::Prima::PlotType::Pair::TrendLines;
254 our @ISA = qw(PDL::Graphics::Prima::PlotType::Pair::Lines);
255 use strict;
256 use warnings;
257 use PDL;
258  
259 # Install the short name constructor:
260 sub ppair::TrendLines {
261 PDL::Graphics::Prima::PlotType::Pair::TrendLines->new(@_);
262 }
263  
264 # Allow the user to specify fit weights:
265 sub initialize {
266 my $self = shift;
267  
268 # Call the superclass initialization:
269 $self->SUPER::initialize(@_);
270
271 $self->{weights} = 1 unless defined $self->{weights};
272
273 }
274  
275 sub get_data {
276 my $self = shift;
277
278 # Retrieve the data from the dataset:
279 my ($xs, $ys) = $self->dataset->get_data;
280 my $weights = $self->{weights};
281
282 # Recompute the $ys as the fit values:
283 # working here - this seems to be erroneous and it blows up when
284 # S_x is close to zero
285 my $S = sumover($xs->ones/$weights);
286 my $S_x = sumover($xs/$weights);
287 my $S_y = sumover($ys/$weights);
288 my $S_xx = sumover($xs*$xs/$weights);
289 my $S_xy = sumover($xs*$ys/$weights);
290 my $slope = ($S_xy * $S - $S_x * $S_y) / ($S_xx * $S - $S_x * $S_x);
291 my $y0 = ($S_xy - $slope * $S_xx) / $S_x;
292
293 # Store these values in case the user wants to retrieve them
294 # (I need to create a method for this, and a means for getting at the
295 # plotType object)
296 $self->{slope} = $slope;
297 $self->{intercept} = $y0;
298
299 # make a new set of ys that are the linear fits:
300 $ys = $y0 + $slope * $xs;
301
302 return ($xs, $ys);
303 }
304  
305 ################################################
306 # PDL::Graphics::Prima::PlotType::Pair::Spikes #
307 ################################################
308 # working here - get rid of the class-specific padding; if anything, such
309 # padding should be part of the general class, not this specific one
310  
311 =item ppair::Spikes
312  
313 =for ref
314  
315 ppair::Spikes( [x_baseline | y_baseline => PDL], options )
316  
317 Draws x/y data as a collection of vertical or horizontal lines. In the default
318 behavior, for each (x, y) data point, it draws a line from (x, 0) to (x, y). You
319 can change the baseline by specifying either the C<y_baseline> or C<x_baseline>
320 key. For example, if you specify C<< y_baseline => 5 >>, this will draw lines
321 starting from (x, 5) instead of (x, 0). Specifying C<< x_baseline => -2 >> will
322 lead to horizontal lines instead of vertical lines, drawn from (-2, y) to
323 (x, y). Finally, if you specify the undefined value, as
324 C<< x_baseline => undef >> or C<< x_baseline => undef >>, the baseline will be
325 taken as the minimum of the dataset's x or y data, respectively.
326  
327 =cut
328  
329 package PDL::Graphics::Prima::PlotType::Pair::Spikes;
330 our @ISA = qw(PDL::Graphics::Prima::PlotType::Pair);
331  
332 # Install the short name constructor:
333 sub ppair::Spikes {
334 PDL::Graphics::Prima::PlotType::Pair::Spikes->new(@_);
335 }
336  
337 # Set padding options:
338 sub initialize {
339 my $self = shift;
340  
341 # Call the superclass initialization:
342 $self->SUPER::initialize(@_);
343  
344 # Should move this to the base class, perhaps
345 # # Specify the various default padding options and validate supplied values:
346 # foreach my $pad_name (map $_.'_padding', qw(left right bottom top)) {
347 # if (exists $self->{$pad_name}) {
348 # croak("$pad_name must be a positive integer")
349 # unless $self->{$pad_name} =~ /^\d+$/ and $self->{$pad_name} > 0;
350 # }
351 # else {
352 # $self->{$pad_name} = 10;
353 # }
354 # }
355
356 # Ensure that a baseline exists:
357 if (not exists $self->{x_baseline} and not exists $self->{y_baseline}) {
358 $self->{y_baseline} = 0;
359 }
360 elsif(exists $self->{x_baseline} and exists $self->{y_baseline}) {
361 croak("You can only specify an x_baseline or a y_baseline, not both");
362 }
363 foreach (qw(x_baseline y_baseline)) {
364 # Make sure they supplied a defined value:
365 croak("You must supply a numeric value for the baseline")
366 if exists $self->{$_} and not defined $self->{$_};
367 # Ensure that value is numeric:
368 $self->{$_} = $self->{$_} + 0 if exists $self->{$_};
369 }
370 }
371  
372 # The collation code needs to be written:
373 sub compute_collated_min_max_for {
374 my ($self, $axis_name, $pixel_extent) = @_;
375
376 # Get the list of properties for which we need to look for bad values:
377 my %properties
378 = $self->generate_properties(@PDL::Drawing::Prima::lines_props);
379
380 # Get the data:
381 my ($to_check, $extra) = my ($xs, $ys) = $self->dataset->get_data;
382 ($to_check, $extra) = ($ys, $xs) if $axis_name eq 'y';
383
384 # get the rest of the piddles, which are associated with plural keys
385 my @prop_piddles;
386 while(my ($k, $v) = each %properties) {
387 push @prop_piddles, $v if $k =~ /s$/;
388 }
389 push @prop_piddles, $extra;
390
391 # The min/max depend on whether the baseline we're using has the same
392 # name as the axis we're using, or not. If the baseline has the same
393 # name as the axis of interest, then the spikes are drawn in the
394 # direction of the axis and the needed padding is 1. If the baseline is
395 # in the other axis, then the pixel extent is the line width.
396 my $baseline_name = $axis_name . '_baseline';
397 if (exists $self->{$baseline_name}) {
398 # Collate the min and the max:
399 my ($min, $max) = PDL::collate_min_max_wrt_many($to_check, 1,
400 $to_check, 1, $pixel_extent, @prop_piddles);
401
402 # make sure that the minima are less than or equal to zero:
403 my $baseline = $self->{$baseline_name};
404 my $good_min = $min->where($min->isgood);
405 $good_min->where($good_min > $baseline) .= $baseline
406 if($good_min->nelem > 0);
407 my $good_max = $max->where($max->isgood);
408 $good_max->where($good_max < $baseline) .= $baseline
409 if($good_max->nelem > 0);
410
411 return ($min, $max);
412 }
413 else {
414 # Extract the line widths, against which we'll collate:
415 my $lineWidths = $properties{lineWidths};
416 $lineWidths = $self->widget->lineWidth unless defined $lineWidths;
417 delete $properties{lineWidths};
418
419 # Collate and return the min and the max:
420 return PDL::collate_min_max_wrt_many($to_check, $lineWidths,
421 $to_check, $lineWidths, $pixel_extent, @prop_piddles);
422 }
423 }
424  
425 # Here is the method for drawing spikes:
426 sub draw {
427 my ($self, $canvas, $ratio) = @_;
428
429 # Assemble the various properties from the plot-type object and the dataset
430 my %properties = $self->generate_properties(@PDL::Drawing::Prima::lines_props);
431  
432 # Retrieve the data from the dataset:
433 my $widget = $self->widget;
434 my ($xs, $ys) = $self->dataset->get_data_as_pixels($ratio);
435
436 # Draw the lines, either horizontal or vertical, based on the given baseline
437 if (exists $self->{y_baseline}) {
438 my $baseline = $ys->zeroes;
439 if (defined $self->{y_baseline}) {
440 $baseline = $widget->y->reals_to_pixels($baseline + $self->{y_baseline}, $ratio);
441 }
442 else {
443 # working here - make threadable?
444 $baseline .= $ys->min;
445 }
446 # Draw the lines:
447 $canvas->pdl_lines($xs, $ys, $xs, $baseline, %properties);
448 }
449 else {
450 my $baseline = $xs->zeroes;
451 if (defined $self->{x_baseline}) {
452 $baseline = $widget->x->reals_to_pixels($baseline + $self->{x_baseline}, $ratio);
453 }
454 else {
455 # working here - make threadable?
456 $baseline .= $xs->min;
457 }
458 # Draw the lines:
459 $canvas->pdl_lines($xs, $ys, $baseline, $ys, %properties);
460 }
461 }
462  
463  
464  
465 ###############################################
466 # PDL::Graphics::Prima::PlotType::Pair::Blobs #
467 ###############################################
468  
469 =item ppair::Blobs
470  
471 =for ref
472  
473 ppair::Blobs( [radius => PDL], [xRadius => PDL],
474 [yRadius => PDL], options )
475  
476 Lets you draw filled ellipses with per-point x- and y- pixel radii. If you
477 specify the key C<radius>, it draws filled circles with the given radius. The
478 more specific keys C<xRadius> and C<yRadius> override the C<radius> key.
479  
480 =cut
481  
482 package PDL::Graphics::Prima::PlotType::Pair::Blobs;
483 our @ISA = qw(PDL::Graphics::Prima::PlotType::Pair);
484  
485 use PDL::Core ':Internal';
486 use Carp 'croak';
487 use PDL;
488  
489 # Install the short name constructor:
490 sub ppair::Blobs {
491 PDL::Graphics::Prima::PlotType::Pair::Blobs->new(@_);
492 }
493  
494 # The blobs initializer defaults to a radius of 3 pixels
495 sub initialize {
496 my $self = shift;
497 $self->SUPER::initialize(@_);
498
499 # They could have passed an xradius, a yradius, or a radius.
500 # if this is defined... use it
501 my $x_radius = defined $self->{xRadius} ? $self->{xRadius}
502 : defined $self->{radius} ? $self->{radius}
503 : pdl(3);
504 my $y_radius = defined $self->{yRadius} ? $self->{yRadius}
505 : defined $self->{radius} ? $self->{radius}
506 : pdl(3);
507  
508 # Oh, if only I could assume 5.10 :-(
509 # my $x_radius = $self->{xRadius} // $self->{radius} // pdl(3);
510 # my $y_radius = $self->{yRadius} // $self->{radius} // pdl(3);
511
512 # make sure the radii are piddles and croak if something goes wrong:
513 eval {
514 $x_radius = topdl($x_radius);
515 $y_radius = topdl($y_radius);
516 1;
517 } or croak('Radii must be piddles, or values that can be interpreted by the pdl constructor');
518
519 croak('Radii must be greater than or equal to 1')
520 unless PDL::all($x_radius >= 1) and PDL::all($y_radius >= 1);
521
522 # Set the internal representation of the radii to the massaged values:
523 $self->{xRadius} = $x_radius;
524 $self->{yRadius} = $y_radius;
525 }
526  
527 # The collation code:
528 sub compute_collated_min_max_for {
529 my ($self, $axis_name, $pixel_extent) = @_;
530
531 # Get the list of properties for which we need to look for bad values:
532 my %properties
533 = $self->generate_properties(@PDL::Drawing::Prima::fill_ellipses_props);
534
535 # get the rest of the piddles, which are associated with plural keys
536 my @extras;
537 while(my ($k, $v) = each %properties) {
538 push @extras, $v if $k =~ /s$/;
539 }
540
541 # Get the data and radii:
542 my ($xs, $ys) = $self->dataset->get_data;
543 my ($to_check, $radii);
544 if ($axis_name eq 'x') {
545 $to_check = $xs;
546 $radii = $self->{xRadius};
547 push @extras, $ys, $self->{yRadius};
548 }
549 else {
550 $to_check = $ys;
551 $radii = $self->{yRadius};
552 push @extras, $xs, $self->{xRadius};
553 }
554
555 # Return the collated results:
556 return PDL::collate_min_max_wrt_many($to_check, $radii, $to_check, $radii
557 , $pixel_extent, @extras);
558 }
559  
560 sub draw {
561 my ($self, $canvas, $ratio) = @_;
562
563 # Assemble the various properties from the plot-type object and the dataset
564 my %properties = $self->generate_properties(@PDL::Drawing::Prima::fill_ellipses_props);
565
566 # Retrieve the data from the dataset:
567 my ($xs, $ys) = $self->dataset->get_data_as_pixels($ratio);
568  
569 # plot it:
570 $canvas->pdl_fill_ellipses($xs, $ys, 2*$self->{xRadius}, 2*$self->{yRadius}
571 , %properties);
572 }
573  
574 #####################################################
575 # PDL::Graphics::Prima::PlotType::Pair::Symbols #
576 #####################################################
577  
578 =item ppair::Symbols
579  
580 =for ref
581  
582 ppair::Symbols( [size => PDL], [filled => PDL::Byte],
583 [N_points => PDL::Byte], [orientation => PDL],
584 [skip => PDL::Byte], options )
585  
586 Lets you draw various geometric symbols, mostly based on regular polygons.
587 This function inspired the creation of L<PDL::Drawing::Prima/pdl_symbols>,
588 so you should acquaint yourself with that function's terminology if you
589 want to understand the meaning of the options here. There are also a number
590 of derived Symbol plot types, as discussed below.
591  
592 For each of your symbols, you can specify the size (radius), number of
593 points, orientation, skip, and whether or not you want the symbol filled.
594 These are the allowed arguments:
595  
596 =over
597  
598 =item size
599  
600 The symbols are drawn with a fixed size in pixels. This size is the radius
601 of a circle that would inscribe the symbol. The default size is 5 pixels.
602  
603 =item filled
604  
605 You can draw filled symbols or open symbols. Filled symbols do not have
606 a border. You can specify a per-symbol value of 0 or 1, or you can specify
607 a plotType-wide value of 0, 1, 'yes', or 'no'. The default setting is
608 unfilled. Note that the filling takes winding number into account, so for
609 example, a five-sided star (skip=2) will have a hollow center. This, perhaps,
610 should be changed. I'm still debating about that.
611  
612 =item N_points
613  
614 The number of points in your symbol. Values of zero and one are interpreted
615 as circles; values of 2 are interpreted as line segments; values of three or
616 more are interpreted as regular polygons with the specified number of
617 points. The number of points is an integer and must be less than 256. The
618 default value is 5.
619  
620 =item orientation
621  
622 The angle in degrees. An orientation of zero points to the right, and the
623 angle increases in a counterclockwise fashion. You can also use the following
624 descriptive (case insensitive) strings:
625  
626 up - 90 degrees
627 left - 180 degrees
628 down - 270 degrees
629 right - 0 degrees, or 360 degrees
630  
631 If the orientation is not specified, the polygon will be drawn 'right'.
632 This means that 4gons are drawn as diamonds, not squares, and triangels will
633 look tilted. (But see L</Triangles> and L</Squares>.)
634  
635 =item skip
636  
637 The default skip is 1 and leads to normal regular polygons, like a pentagon.
638 However, what if you want to draw a five-pointed star instead of a pentagon?
639 In that case, you would specify a skip of 2. This means I<draw a shape
640 connecting every B<other> point>. Higher values of skip are allowed, though
641 I am not sure how useful they would be.
642  
643 =back
644  
645 =cut
646  
647 package PDL::Graphics::Prima::PlotType::Pair::Symbols;
648 our @ISA = qw(PDL::Graphics::Prima::PlotType::Pair);
649  
650 use PDL::Core ':Internal';
651 use Carp 'croak';
652 use PDL;
653  
654 # Install the short name constructor:
655 sub ppair::Symbols {
656 PDL::Graphics::Prima::PlotType::Pair::Symbols->new(@_);
657 }
658  
659 sub initialize {
660 my $self = shift;
661 $self->SUPER::initialize(@_);
662
663 # if this is defined... use it
664 my $orientation = defined $self->{orientation} ? $self->{orientation}
665 : 'right';
666 my $filled = defined $self->{filled} ? $self->{filled}
667 : 0;
668 my $N_points = defined $self->{N_points} ? $self->{N_points}
669 : 5;
670 my $size = defined $self->{size} ? $self->{size}
671 : defined $self->{radius} ? $self->{radius}
672 : 5;
673 my $skip = defined $self->{skip} ? $self->{skip}
674 : 1;
675
676 # Replace descriptive strings with meaningful numerical values:
677 unless (ref $orientation) {
678 # if string looks like... use value...
679 $orientation = $orientation =~ /^up$/i ? 90
680 : $orientation =~ /^left$/i ? 180
681 : $orientation =~ /^down$/i ? 270
682 : $orientation =~ /^right$/i ? 0
683 : $orientation;
684 }
685 unless (ref $filled) {
686 # if string matches... use value...
687 $filled = $filled =~ /^yes$/i ? 1
688 : $filled =~ /^no$/i ? 0
689 : $filled;
690 }
691
692 # Make sure everything is piddles and croak if something goes wrong:
693 eval {
694 $orientation = topdl($orientation);
695 $filled = topdl($filled);
696 $N_points = topdl($N_points);
697 $size = topdl($size);
698 $skip = topdl($skip);
699 1;
700 } or croak('Symbls arguments must be piddles, or values that can be interpreted by the pdl constructor');
701
702 croak('Sizes must be greater than or equal to 1') unless PDL::all($size >= 1);
703 croak('N_points must be greater than or equal to 0 and less than 256')
704 unless PDL::all(($N_points >= 0) & ($N_points < 256));
705 croak('filled must be either 1 or zero')
706 unless PDL::all(($filled == 0) | ($filled == 1));
707 croak('skip must be greater than or equal to zero') unless PDL::all($skip >= 0);
708
709 # Set the internal representation of the parameters to the massaged values:
710 $self->{size} = $size;
711 $self->{orientation} = $orientation;
712 $self->{N_points} = $N_points->byte;
713 $self->{filled} = $filled->byte;
714 $self->{skip} = $skip->byte;
715 }
716  
717 # The collation code:
718 sub compute_collated_min_max_for {
719 my ($self, $axis_name, $pixel_extent) = @_;
720
721 # Get the list of properties for which we need to look for bad values:
722 my %properties
723 = $self->generate_properties(@PDL::Drawing::Prima::symbols_props);
724
725 # get the rest of the piddles, which are associated with plural keys
726 my @extras;
727 while(my ($k, $v) = each %properties) {
728 push @extras, $v if $k =~ /s$/;
729 }
730
731 my $size = $self->{size};
732 my $to_check;
733 my ($xs, $ys) = $self->dataset->get_data;
734
735 # working here - make this take the orientation of each polygon into account
736 # my ($min_points, $max_points);
737 if ($axis_name eq 'x') {
738 # # compute the min_points and max_points
739 $to_check = $xs;
740 push @extras, $ys;
741 }
742 else {
743 # # compute the min_points and max_points
744 $to_check = $ys;
745 push @extras, $xs;
746 }
747
748 # Return the collated results:
749 return PDL::collate_min_max_wrt_many($to_check, $size, $to_check, $size
750 , $pixel_extent, @extras);
751 }
752  
753 sub draw {
754 my ($self, $canvas, $ratio) = @_;
755
756 # Assemble the various properties from the plot-type object and the dataset
757 my %props = $self->generate_properties(@PDL::Drawing::Prima::symbols_props);
758
759 # Retrieve the data from the dataset:
760 my ($xs, $ys) = $self->dataset->get_data_as_pixels($ratio);
761 $canvas->pdl_symbols($xs, $ys, $self->{N_points}
762 , $self->{orientation}, $self->{filled}, $self->{size}
763 , $self->{skip}, %props);
764 }
765  
766 #############################################################
767 # PDL::Graphics::Prima::PlotType::Pair::Symbols Derivatives #
768 #############################################################
769  
770 =pod
771  
772 In addition, there are many nicely named derivatives of ppair::Symbols. These
773 give descriptive names to many common symbols and include:
774  
775 =over
776  
777 =item ppair::Sticks
778  
779 =for ref
780  
781 ppair::Sticks( [size => PDL], [orientation => PDL], options )
782  
783 C<ppair::Sticks> is a wrapper around the Symbols plotType that draws 2-point polygons,
784 that is, sticks. You can specify the orientation and the size; you can also specify
785 N_points and filled, but those will be ignored.
786  
787 =cut
788  
789 sub ppair::Sticks {
790 PDL::Graphics::Prima::PlotType::Pair::Symbols->new(@_, N_points => 2, filled => 'no');
791 }
792  
793 =item ppair::Triangles
794  
795 =for ref
796  
797 ppair::Triangles( [size => PDL], [filled => PDL::Byte],
798 [orientation => PDL], options )
799  
800 C<ppair::Triangles> is a wrapper around the Symbols plotType that draws 3-point regular
801 polygons. It takes the same options as Symbols, except that if you specify
802 N_points, it will be overridden by the value 3. Also, the default orientation
803 which you B<can> override, is 'up'.
804  
805 =cut
806  
807 sub ppair::Triangles {
808 PDL::Graphics::Prima::PlotType::Pair::Symbols->new(orientation => 'up', @_, N_points => 3);
809 }
810  
811 =item ppair::Squares
812  
813 =for ref
814  
815 ppair::Squares( [size => PDL], [filled => PDL::Byte], options )
816  
817 C<ppair::Squares> is a wrapper around Symbols that draws 4-point regular polygon with an
818 orientation that makes it look like a square (instead of a diamond). You can
819 specify vales for N_points and orientation, but they will be ignored.
820  
821 =cut
822  
823 sub ppair::Squares {
824 PDL::Graphics::Prima::PlotType::Pair::Symbols->new(@_, N_points => 4, orientation => 45);
825 }
826  
827 =item ppair::Diamonds
828  
829 =for ref
830  
831 ppair::Diamonds( [size => PDL], [filled => PDL::Byte], options )
832  
833 C<ppair::Diamonds> is just like Squares, but rotated by 45
834 degrees. Again, you can specify N_points and orientation, but those will be
835 ignored.
836  
837 =cut
838  
839 sub ppair::Diamonds {
840 PDL::Graphics::Prima::PlotType::Pair::Symbols->new(@_, N_points => 4, orientation => 0);
841 }
842  
843 =item ppair::Stars
844  
845 =for ref
846  
847 ppair::Stars( [size => PDL], [N_points => PDL::Byte],
848 [orientation => PDL], options )
849  
850 C<ppair::Stars> creates open or filled star shapes. These only look right when
851 you have five or more C<N_points>, though it will plot something with four
852 and fewer. The default orientation is 'up' but that can be overridden. The
853 C<skip> of two, however, cannot be overridden. You can also specify the fill
854 state and the orientation, in addition to all the other Drawable parameters,
855 of course.
856  
857 =cut
858  
859 sub ppair::Stars {
860 PDL::Graphics::Prima::PlotType::Pair::Symbols->new(orientation => 90, @_, skip => 2);
861 }
862  
863 =item ppair::Asterisks
864  
865 =for ref
866  
867 ppair::Asterisks( [size => PDL], [N_points => PDL::Byte],
868 [orientation => PDL], options )
869  
870 C<ppair::Asterisks> creates N-sided asterisks. It does this by forcing a skip
871 of zero that cannot be overridden. As with Stars, the default orientation is
872 'up' but that can be overridden. You can also specify the fill state, but
873 that will not be used.
874  
875 =cut
876  
877 sub ppair::Asterisks {
878 PDL::Graphics::Prima::PlotType::Pair::Symbols->new(orientation => 90, @_, skip => 0);
879 }
880  
881 =item ppair::Xs
882  
883 =for ref
884  
885 ppair::Xs( [size => PDL], options )
886  
887 C<ppair::Xs> creates C<x> shaped symbols. This sets all the Symbol arguments
888 except the size, so although you can specify them, they will be ignored.
889  
890 =cut
891  
892 sub ppair::Xs {
893 PDL::Graphics::Prima::PlotType::Pair::Symbols->new(@_, N_points => 4, orientation => 45, skip => 0);
894 }
895  
896 =item ppair::Crosses
897  
898 =for ref
899  
900 ppair::Crosses( [size => PDL], options )
901  
902 C<ppair::Crosses> creates cross-shaped symbols, i.e. a C<+> shape. As with Xs,
903 you are free to set the size, but all other Symbol options are set for you and
904 will be ignored if you specify them.
905  
906 =cut
907  
908 sub ppair::Crosses {
909 PDL::Graphics::Prima::PlotType::Pair::Symbols->new(@_, N_points => 4, orientation => 0, skip => 0);
910 }
911  
912 =back
913  
914 =cut
915  
916 ####################################################
917 # PDL::Graphics::Prima::PlotType::Pair::Slopes #
918 ####################################################
919 #
920 #=item ppair::Slopes
921 #
922 #This plot type visualizes derivatives, i.e. slopes.
923 #
924 #=cut
925  
926 #######################################################
927 # PDL::Graphics::Prima::PlotType::Pair::Histogram #
928 #######################################################
929  
930 =item ppair::Histogram
931  
932 =for ref
933  
934 ppair::Histogram( [binEdges => PDL], [baseline => SCALAR],
935 [topPadding => SCALAR], options )
936  
937 Draws a histogram. The bin-centers that are approximated from the x-values
938 and the bin heights are set as the data's y-values. Both positive and
939 negative y-values are allowed. The border of the histogram bars are drawn
940 using the applicable C<color> and the histograms are filled with the
941 applicable C<backColor>.
942  
943 Histogram computes the inter-point bin edges as the mid-point between each
944 (sequential) pair of x-values. For the first and last bins, the outer edge
945 is the same distance from the center as the corresponding inner edge. If all
946 of your bins have the same width, this will give you exactly what you mean.
947 If your bins do not have identical widths, the center of the bin is
948 guaranteed to fall somewhere within the bin boundaries, but it won't be in
949 the "center". For greater control of where the bin boundaries are placed,
950 you should specify the binEdges key:
951  
952 ppair::Histogram(binEdges => $bin_edges)
953  
954 Note that binEdges should have one more element compared with your y-data,
955 that is, if you have 20 heights, you'll need 21 binEdges. Unfortunately,
956 specifying bin edges in this way does not work very well with having a
957 function-based dataset.
958  
959 Options for this plotType include:
960  
961 =over
962  
963 =item baseline
964  
965 The histogram is plotted as a series of rectangles. The height of the bottom
966 of these rectangles is zero, but you can set a different heigh using this
967 key.
968  
969 =item binEdges
970  
971 Sets the location of the bin edges; useful if your histogram does not have
972 identical spacing.
973  
974 =item topPadding
975  
976 Histograms whose tallest column runs to the top of the graph are very
977 confusing. This plotType includes a little bit of padding to ensure that
978 the top of the highest histogram is plotted below the top axis when you use
979 autoscaling. The same logic is applied to negative columns if you have any.
980  
981 =back
982  
983 The histogram plotType works decently well, but it needs improvement. Don't
984 be surprised if this plotType changes in the near future. Potential areas
985 for improvement might be the inclusion of a Scaling property as well as
986 filled/unfilled specifications (as in Symbols).
987  
988 =cut
989  
990 package PDL::Graphics::Prima::PlotType::Pair::Histogram;
991 our @ISA = qw(PDL::Graphics::Prima::PlotType::Pair);
992  
993 use Carp 'croak';
994 use PDL;
995 use strict;
996 use warnings;
997  
998 # working here - does the background color make drawing a filled rectangle
999 # unnecessary?
1000  
1001 # Install the short name constructor:
1002 sub ppair::Histogram {
1003 PDL::Graphics::Prima::PlotType::Pair::Histogram->new(@_);
1004 }
1005  
1006 # The histogram initializer ensures that the top padding is set to a reasonable
1007 # value (defaults to 5 pixels):
1008 sub initialize {
1009 my $self = shift;
1010 $self->SUPER::initialize(@_);
1011
1012 # Default to an upper padding of of 10 pixels:
1013 $self->{topPadding} = 10 unless defined $self->{topPadding};
1014 croak("topPadding must be a nonnegative integer")
1015 unless $self->{topPadding} =~ /^\d+$/ and $self->{topPadding} >= 0;
1016
1017 # Make sure we have a default baseline:
1018 $self->{baseline} = 0 unless defined $self->{baseline};
1019 $self->{baseline} += 0;
1020 }
1021  
1022  
1023 # Returns user-supplied or computed bin-edge data.
1024 sub get_bin_edges {
1025 # Return the bin-edges if we have an internal copy of them:
1026 return $_[0]->{binEdges} if exists $_[0]->{binEdges};
1027
1028 my ($self) = @_;
1029
1030 # Compute linear bin edges if none are supplied:
1031 my $xs = $self->dataset->get_xs;
1032 my @dims = $xs->dims;
1033 @dims > 0 or @dims = (1);
1034 $dims[0]++;
1035 # The widths are based on the left and right values of x, unless
1036 # there is only one x-entry, in which case we have a degeneracy
1037 # problem
1038 my $edges;
1039 if ($dims[0] > 2) {
1040 my $widths = $xs(1:-1,) - $xs(0:-2,);
1041 $edges = zeroes(@dims);
1042 $edges(1:-2,) .= $xs(0:-2,) + $widths/2;
1043 $edges(0,) .= $xs(0,) - $widths(0,) / 2;
1044 $edges(-1,) .= $xs(-1,) + $widths(-1,) / 2;
1045 }
1046 elsif ($dims[0] == 2) {
1047 # Set the default width to half the x-value
1048 my $widths = $xs / 2;
1049 # If the x-value is zero, set the width to 1
1050 $widths->where($widths == 0) .= 1;
1051 $edges = xvals(@dims) * $widths + $xs(0,) - $widths/2;
1052 }
1053
1054 # note: empty piddles are silently ignored
1055
1056 # Store these bin edges if the underlying dataset is static:
1057 $self->{binEdges} = $edges unless ref($self->dataset) =~ /Func/;
1058
1059 return $edges;
1060
1061 # If the cached data is good, return it:
1062 # if (exists $dataset->properties->{cached_binEdges}
1063 # and $dataset->{cached_bin_scaling} eq $dataset->{scaling}
1064 # ) {
1065 # my $edges = $dataset->properties->{cached_binEdges};
1066 # return $edges
1067 # if $edges->nelem == $dataset->{N_points} + 1
1068 # and $edges->min == $widget->x->min
1069 # and $edges->max == $widget->x->max;
1070 # }
1071 #
1072 # # Otherwise, compute the bin edges, store them, and return them:
1073 # my $edges
1074 # = zeroes($dataset->{N_points} + 1)->xlinvals($widget->x->minmax);
1075 # $dataset->{cached_binEdges} = $edges;
1076 # $dataset->{cached_bin_scaling} = $dataset->{scaling};
1077 # return $edges;
1078 }
1079  
1080 # The collation code:
1081 sub compute_collated_min_max_for {
1082 my ($self, $axis_name, $pixel_extent) = @_;
1083
1084 # Get the list of properties for which we need to look for bad values:
1085 my %properties = $self->generate_properties(@PDL::Drawing::Prima::rectangles_props);
1086
1087 # Extract the line widths, against which we'll collate:
1088 my $lineWidths = $properties{lineWidths};
1089 $lineWidths = $self->widget->lineWidth unless defined $lineWidths;
1090 delete $properties{lineWidths};
1091
1092 # get the rest of the piddles, which are associated with plural keys
1093 my @prop_piddles;
1094 while(my ($k, $v) = each %properties) {
1095 push @prop_piddles, $v if $k =~ /s$/;
1096 }
1097
1098 my ($xs, $ys) = $self->dataset->get_data;
1099
1100 # Return "nothing" if the datasets are empty
1101 if ($xs->nelem == 0) {
1102 my $to_return = zeroes($pixel_extent + 1)->setvaltobad(0);
1103 return ($to_return, $to_return->copy);
1104 }
1105
1106 # For the y min/max, get the y-data, the padding, and the baseline:
1107 if ($axis_name eq 'y') {
1108 my $to_check = $ys->append(zeroes(1) + $self->{baseline});
1109 my $top_padding = $lineWidths;
1110 $top_padding += $self->{topPadding} if any $to_check > $self->{baseline};
1111 my $bottom_padding = $lineWidths;
1112 $bottom_padding += $self->{topPadding} if any $to_check < $self->{baseline};
1113
1114 return PDL::collate_min_max_wrt_many($to_check, $bottom_padding
1115 , $to_check, $top_padding, $pixel_extent
1116 , $xs->append(zeroes(1)), @prop_piddles);
1117 }
1118 # For the x min/max, get the bin edges and collate by line width:
1119 else {
1120 my $edges = $self->get_bin_edges;
1121
1122 # Handle degenerate edge case
1123 if ($edges->dim(0) == 2) {
1124 return PDL::collate_min_max_wrt_many($edges(0), $lineWidths
1125 , $edges(1), $lineWidths, $pixel_extent
1126 , $ys, @prop_piddles);
1127 }
1128
1129 return PDL::collate_min_max_wrt_many($edges(0:-2), $lineWidths
1130 , $edges(1:-1), $lineWidths, $pixel_extent
1131 , $ys, @prop_piddles);
1132 }
1133 }
1134  
1135  
1136 sub draw {
1137 my ($self, $canvas, $ratio) = @_;
1138 my $dataset = $self->dataset;
1139 my $widget = $self->widget;
1140
1141 # Get the edges and skip out if we have an empty case
1142 my $edges = $self->get_bin_edges($dataset, $widget);
1143 return unless defined $edges;
1144
1145 # convert everything to pixels
1146 my $pixel_edges = $widget->x->reals_to_pixels($edges, $ratio);
1147 my $pixel_bottom = $widget->y->reals_to_pixels($self->{baseline}, $ratio);
1148 my $ys = $widget->y->reals_to_pixels($dataset->get_ys, $ratio);
1149
1150 # For drawing the filled background, we need to temporarily isolate the
1151 # backGround color from the regular color.
1152 my %properties = $self->generate_properties(@PDL::Drawing::Prima::bars_props);
1153 delete $properties{color};
1154 delete $properties{colors};
1155 $properties{color} = $properties{backColor} if exists $properties{backColor};
1156 $properties{colors} = $properties{backColors} if exists $properties{backColors};
1157 # If we have a backColor, set our foreground color; otherwise skip
1158 if (exists $properties{color} or exists $properties{colors}) {
1159 $canvas->pdl_bars($pixel_edges(0:-2), $pixel_bottom
1160 , $pixel_edges(1:-1), $ys, %properties);
1161 }
1162
1163 # Assemble the various properties from the plot-type object and the
1164 # dataset, and plot the rectangles.
1165 %properties = $self->generate_properties(@PDL::Drawing::Prima::rectangles_props);
1166 $canvas->pdl_rectangles($pixel_edges(0:-2), $pixel_bottom
1167 , $pixel_edges(1:-1), $ys, %properties);
1168 }
1169  
1170 ###########################################################
1171 # PDL::Graphics::Prima::PlotType::Pair::BoxAndWhisker #
1172 ###########################################################
1173 # Plots vertical box-and-whisker at each data point
1174  
1175 package PDL::Graphics::Prima::PlotType::Pair::BoxAndWhisker;
1176 our @ISA = qw(PDL::Graphics::Prima::PlotType::Pair);
1177  
1178 #######################################################
1179 # PDL::Graphics::Prima::PlotType::Pair::ErrorBars #
1180 #######################################################
1181 # Adds error bars
1182  
1183 package PDL::Graphics::Prima::PlotType::Pair::ErrorBars;
1184 our @ISA = qw(PDL::Graphics::Prima::PlotType::Pair);
1185  
1186 # working here - ensure documentation consistency
1187  
1188 =item ppair::ErrorBars
1189  
1190 =for ref
1191  
1192 ppair::ErrorBars( [x_err => PDL], [y_err => PDL]
1193 [x_left_err => PDL], [x_right_err => PDL],
1194 [y_upper_err => PDL], [y_lower_err => PDL],
1195 [x_err_width => PDL], [y_err_width => PDL],
1196 [err_width => PDL], options );
1197  
1198 You create an error bars plotType objet with C<ppair::ErrorBars>:
1199  
1200 You must specify at least one sort of error bar to plot, though you can mix and
1201 match as you wish. Each error specification must be a piddle or something that
1202 can be converted to a piddle:
1203  
1204 x_err - symmetric x error bars
1205 y_err - symmetric y error bars
1206 x_left_err - left x error bars
1207 x_right_err - right x error bars
1208 y_upper_err - upper y error bars
1209 y_lower_err - lower y error bars
1210  
1211 Note that the more specific error bars will override the less specific ones,
1212 so if you provide C<x_err> and C<x_left_err>, the left error bars override the
1213 basic ones.
1214  
1215 You can also specify the width of the error bars in pixels:
1216  
1217 err_width - width of both error caps
1218 x_err_width - width of x-error caps
1219 y_err_width - width of y-error caps
1220  
1221 Again, the more specific widths override the less specific ones.
1222  
1223 =cut
1224  
1225 # Install the short name constructor:
1226 sub ppair::ErrorBars {
1227 PDL::Graphics::Prima::PlotType::Pair::ErrorBars->new(@_);
1228 }
1229  
1230 # The ErrorBars initializer figures out the x and y bar widths
1231 sub initialize {
1232 my $self = shift;
1233 $self->SUPER::initialize(@_);
1234
1235 # Set the x and y widths, with a default of 10:
1236 $self->{x_err_width} //= $self->{err_width} // 10;
1237 $self->{y_err_width} //= $self->{err_width} // 10;
1238
1239 # Set the various internal variables:
1240 my $bars = $self->{x_left_err} // $self->{x_err}; #/
1241 $self->{left_bars} = $bars->abs if defined $bars;
1242 $bars = $self->{x_right_err} // $self->{x_err}; #/
1243 $self->{right_bars} = $bars->abs if defined $bars;
1244 $bars = $self->{y_upper_err} // $self->{y_err}; #/
1245 $self->{upper_bars} = $bars->abs if defined $bars;
1246 $bars = $self->{y_lower_err} // $self->{y_err}; #/
1247 $self->{lower_bars} = $bars->abs if defined $bars;
1248 }
1249  
1250 sub y_bars_present {
1251 my $self = shift;
1252 return exists($self->{upper_bars}) || exists($self->{lower_bars});
1253 }
1254  
1255 sub x_bars_present {
1256 my $self = shift;
1257 return exists($self->{left_bars}) || exists($self->{right_bars});
1258 }
1259  
1260 # The collation code:
1261 sub compute_collated_min_max_for {
1262 my ($self, $axis_name, $pixel_extent) = @_;
1263
1264 # Get the list of properties for which we need to look for bad values:
1265 my %properties = $self->generate_properties(@PDL::Drawing::Prima::lines_props);
1266
1267 # Extract the line widths, which might be the index during the collation
1268 my $lineWidths = $properties{lineWidths};
1269 $lineWidths = $self->widget->lineWidth unless defined $lineWidths;
1270 delete $properties{lineWidths};
1271
1272 # get the rest of the piddles, which are associated with plural keys
1273 my @prop_piddles;
1274 while(my ($k, $v) = each %properties) {
1275 push @prop_piddles, $v if $k =~ /s$/;
1276 }
1277
1278 # This gets pretty complex. For example, consider the x-min. The
1279 # collation must combine the x data and their widths (the widths of the
1280 # error bars as well as the caps) along with x-minus-errors and the
1281 # linewidths.
1282
1283 my ($xs, $ys) = $self->dataset->get_data;
1284 my (@mins, @maxes);
1285
1286 # I'm going to hack through this. It could probably be cleaner, so
1287 # I'm marking it as working here:
1288 if ($axis_name eq 'x') {
1289 # Let's get started with left error bars
1290 if (exists($self->{left_bars})) {
1291 my ($min, $max) = PDL::collate_min_max_wrt_many(
1292 $xs - $self->{left_bars}, $lineWidths, $xs, 0
1293 , $pixel_extent, @prop_piddles
1294 , $self->{x_err_width}, $lineWidths, $ys);
1295 push @mins, $min;
1296 push @maxes, $max;
1297 }
1298 # Right error bars:
1299 if (exists $self->{left_bars}) {
1300 my ($min, $max) = PDL::collate_min_max_wrt_many(
1301 $xs, 0, $xs + $self->{right_bars}, $lineWidths
1302 , $pixel_extent, @prop_piddles
1303 , $self->{x_err_width}, $lineWidths, $ys);
1304 push @mins, $min;
1305 push @maxes, $max;
1306 }
1307 # Vertical error bars:
1308 if ($self->y_bars_present) {
1309 # Build the list of widths to be the greater of the lineWidths
1310 # and the y_err_width
1311 my $a = PDL::Core::topdl($lineWidths);
1312 my $b = PDL::Core::topdl($self->{y_err_width});
1313 ($b, $a) = ($a, $b) if $a->ndims < $b->ndims;
1314 my $width = $a->cat($b)->mv(-1,0)->maximum;
1315
1316 if (exists $self->{upper_bars}) {
1317 my ($min, $max) = PDL::collate_min_max_wrt_many(
1318 $xs, $width, $xs, $width
1319 , $pixel_extent, @prop_piddles
1320 , $self->{y_err_width}, $lineWidths, $ys
1321 , $self->{upper_bars});
1322 push @mins, $min;
1323 push @maxes, $max;
1324 }
1325 if (exists $self->{lower_bars}) {
1326 my ($min, $max) = PDL::collate_min_max_wrt_many(
1327 $xs, $width, $xs, $width
1328 , $pixel_extent, @prop_piddles
1329 , $self->{y_err_width}, $lineWidths, $ys
1330 , $self->{lower_bars});
1331 push @mins, $min;
1332 push @maxes, $max;
1333 }
1334 }
1335 }
1336 else {
1337 # Start with lower error bars
1338 if (exists($self->{lower_bars})) {
1339 my ($min, $max) = PDL::collate_min_max_wrt_many(
1340 $ys - $self->{lower_bars}, $lineWidths, $ys, 0
1341 , $pixel_extent, @prop_piddles
1342 , $self->{y_err_width}, $lineWidths, $xs);
1343 push @mins, $min;
1344 push @maxes, $max;
1345 }
1346 # Upper error bars:
1347 if (exists $self->{upper_bars}) {
1348 my ($min, $max) = PDL::collate_min_max_wrt_many(
1349 $ys, 0, $ys + $self->{upper_bars}, $lineWidths
1350 , $pixel_extent, @prop_piddles
1351 , $self->{y_err_width}, $lineWidths, $xs);
1352 push @mins, $min;
1353 push @maxes, $max;
1354 }
1355 # Vertical error bars:
1356 if ($self->x_bars_present) {
1357 # Build the list of widths to be the greater of the lineWidths
1358 # and the y_err_width
1359 my $a = PDL::Core::topdl($lineWidths);
1360 my $b = PDL::Core::topdl($self->{x_err_width});
1361 ($b, $a) = ($a, $b) if $a->ndims < $b->ndims;
1362 my $width = $a->cat($b)->mv(-1,0)->maximum;
1363
1364 if (exists $self->{left_bars}) {
1365 my ($min, $max) = PDL::collate_min_max_wrt_many(
1366 $ys, $width, $ys, $width
1367 , $pixel_extent, @prop_piddles
1368 , $self->{x_err_width}, $lineWidths, $xs
1369 , $self->{left_bars});
1370 push @mins, $min;
1371 push @maxes, $max;
1372 }
1373 if (exists $self->{right_bars}) {
1374 my ($min, $max) = PDL::collate_min_max_wrt_many(
1375 $ys, $width, $ys, $width
1376 , $pixel_extent, @prop_piddles
1377 , $self->{x_err_width}, $lineWidths, $xs
1378 , $self->{right_bars});
1379 push @mins, $min;
1380 push @maxes, $max;
1381 }
1382 }
1383 }
1384
1385 # combine all of them
1386 if (@mins > 1) {
1387 # combine with cat and return
1388 return PDL::cat(@mins), PDL::cat(@maxes);
1389 }
1390 elsif (@mins = 1) {
1391 return (@mins, @maxes);
1392 }
1393 else {
1394 # return arrays full of bad values
1395 my $to_return = zeroes($pixel_extent+1)->setvaltobad(0);
1396 return ($to_return, $to_return);
1397 }
1398 }
1399  
1400 sub draw {
1401 my ($self, $canvas, $ratio) = @_;
1402 my ($xs, $ys) = $self->dataset->get_data;
1403 my $widget = $self->widget;
1404
1405 # Assemble the various properties from the plot-type object and the dataset
1406 my %properties = $self->generate_properties(@PDL::Drawing::Prima::lines_props);
1407
1408 #---( left error bars )---#
1409 if (exists $self->{left_bars}) {
1410 my $left_xs = $xs - $self->{left_bars};
1411
1412 # Convert from points to pixels:
1413 $left_xs = $widget->x->reals_to_pixels($left_xs, $ratio);
1414 my $local_xs = $widget->x->reals_to_pixels($xs, $ratio);
1415 my $local_ys = $widget->y->reals_to_pixels($ys, $ratio);
1416  
1417 # Draw the line from the point to the edge:
1418 $canvas->pdl_lines($left_xs, $local_ys, $local_xs, $local_ys, %properties);
1419 # Draw the end caps:
1420 my $width = $self->{x_err_width}/2;
1421 $canvas->pdl_lines($left_xs, $local_ys + $width, $left_xs
1422 , $local_ys - $width, %properties);
1423 }
1424
1425 #---( right error bars )---#
1426 if (exists $self->{right_bars}) {
1427 my $right_xs = $xs + $self->{right_bars};
1428
1429 # Convert from points to pixels:
1430 $right_xs = $widget->x->reals_to_pixels($right_xs, $ratio);
1431 my $local_xs = $widget->x->reals_to_pixels($xs, $ratio);
1432 my $local_ys = $widget->y->reals_to_pixels($ys, $ratio);
1433  
1434 # Draw the line from the point to the edge:
1435 $canvas->pdl_lines($local_xs, $local_ys, $right_xs, $local_ys, %properties);
1436 # Draw the end caps:
1437 my $width = $self->{x_err_width} / 2;
1438 $canvas->pdl_lines($right_xs, $local_ys + $width, $right_xs
1439 , $local_ys - $width, %properties);
1440 }
1441
1442 #---( upper error bars )---#
1443 if (exists $self->{upper_bars}) {
1444 my $upper_ys = $ys + $self->{upper_bars};
1445
1446 # Convert from points to pixels:
1447 $upper_ys = $widget->y->reals_to_pixels($upper_ys, $ratio);
1448 my $local_xs = $widget->x->reals_to_pixels($xs, $ratio);
1449 my $local_ys = $widget->y->reals_to_pixels($ys, $ratio);
1450  
1451 # Draw the line from the point to the edge
1452 $canvas->pdl_lines($local_xs, $local_ys, $local_xs, $upper_ys, %properties);
1453 # Draw the caps:
1454 my $width = $self->{y_err_width} / 2;
1455 $canvas->pdl_lines($local_xs - $width, $upper_ys, $local_xs + $width
1456 , $upper_ys, %properties);
1457 }
1458
1459 #---( lower error bars )---#
1460 if (exists $self->{lower_bars}) {
1461 my $lower_ys = $ys - $self->{lower_bars};
1462
1463 # Convert from points to pixels:
1464 $lower_ys = $widget->y->reals_to_pixels($lower_ys, $ratio);
1465 my $local_xs = $widget->x->reals_to_pixels($xs, $ratio);
1466 my $local_ys = $widget->y->reals_to_pixels($ys, $ratio);
1467  
1468 # Draw the line from the point to the edge:
1469 $canvas->pdl_lines($local_xs, $local_ys, $local_xs, $lower_ys, %properties);
1470 # Draw the caps
1471 my $width = $self->{y_err_width} / 2;
1472 $canvas->pdl_lines($local_xs - $width, $lower_ys, $local_xs + $width
1473 , $lower_ys, %properties);
1474 }
1475 }
1476  
1477 ###################################################
1478 # PDL::Graphics::Prima::PlotType::Pair::Bands #
1479 ###################################################
1480 # Plots symmetric or unsymmetric error bands around the data
1481  
1482 package PDL::Graphics::Prima::PlotType::Pair::Bands;
1483 our @ISA = qw(PDL::Graphics::Prima::PlotType::Pair);
1484  
1485 ##################################################
1486 # PDL::Graphics::Prima::PlotType::Pair::Area #
1487 ##################################################
1488 # Plots shaded area, where one edge is the data
1489  
1490 package PDL::Graphics::Prima::PlotType::Pair::Area;
1491 our @ISA = qw(PDL::Graphics::Prima::PlotType::Pair);
1492  
1493  
1494 #############################################################################
1495 # Raster Role #
1496 #############################################################################
1497  
1498 # This provides a couple of functions that are used by two distinctly
1499 # different classes, namely basic images and matrix grids.
1500  
1501 package PDL::Graphics::Prima::PlotType::Role::Raster;
1502  
1503 # Collation function is really, really simple - just figure out the edges.
1504 # This requires that the consuming class provides a dataset that knows how
1505 # to report its edges.
1506 sub compute_collated_min_max_for {
1507 my ($self, $axis_name, $pixel_extent) = @_;
1508 # Get the list of properties for which we need to look for bad values:
1509 my %properties
1510 = $self->generate_properties(@PDL::Drawing::Prima::bars_props);
1511  
1512 # get the rest of the piddles, which are associated with plural keys
1513 my @prop_piddles;
1514 while(my ($k, $v) = each %properties) {
1515 push @prop_piddles, $v if $k =~ /s$/;
1516 }
1517
1518 my $to_check = $self->dataset->edges($axis_name);
1519 my ($left_check, $right_check, $left_extra, $right_extra);
1520 if ($axis_name eq 'x') {
1521 $left_check = $to_check(:-2);
1522 $right_check = $to_check(1:);
1523 $left_extra = $self->dataset->edges('y')->(1:)->dummy(0);
1524 $right_extra = $self->dataset->edges('y')->(:-2)->dummy(0);
1525 }
1526 else {
1527 $left_check = $to_check(:-2)->dummy(0);
1528 $right_check = $to_check(1:)->dummy(0);
1529 $left_extra = $self->dataset->edges('x')->(1:);
1530 $right_extra = $self->dataset->edges('x')->(:-2);
1531 }
1532
1533 # Fudging a little bith with $extra, this could probably be improved
1534 # working here
1535 return PDL::collate_min_max_wrt_many($left_check, 0, $right_check, 0
1536 , $pixel_extent, @prop_piddles, $left_extra, $right_extra);
1537 }
1538  
1539 # Drawing is fairly straight-forward. The consuming class must provide a
1540 # get_colored_data function.
1541 sub draw {
1542 my ($self, $canvas, $ratio) = @_;
1543 my $dataset = $self->dataset;
1544 my $widget = $self->widget;
1545
1546 # Convert the x and y edges to coordinate edges:
1547 my $xs = $widget->x->reals_to_pixels($dataset->edges('x'), $ratio);
1548 my $ys = $widget->y->reals_to_pixels($dataset->edges('y'), $ratio);
1549
1550 # Gather the properties that I will need to use in the plotting.
1551 my %properties = $self->generate_properties(@PDL::Drawing::Prima::bars_props);
1552
1553 # Set up the x- and y- dimension lists for proper threading:
1554 my $colors = $self->get_colored_data;
1555 $xs = $xs->dummy(1, $colors->dim(1));
1556 $ys = $ys->dummy(0, $colors->dim(0));
1557  
1558 # Now draw the bars for each rectangle:
1559 $canvas->pdl_bars($xs(:-2), $ys(0,:-2), $xs(1:), $ys(0,1:), %properties
1560 , colors => $colors);
1561 }
1562  
1563  
1564  
1565 ###############################################################################
1566 # Grid-based Plot Types #
1567 ###############################################################################
1568  
1569 =back
1570  
1571 =head2 Grid-based plot types
1572  
1573 Other plots focus on using color or grayscale to visualize data that is a
1574 function of two variables. If you need to visualize the elements of a matrix,
1575 you will use these plot types. If would like to
1576 visualize an image and have already computed the RGB, HSV, or similar values,
1577 you should use pimage::Basic instead.
1578  
1579 =over
1580  
1581 =cut
1582  
1583 package PDL::Graphics::Prima::PlotType::Grid;
1584 use base 'PDL::Graphics::Prima::PlotType';
1585  
1586 #################################################
1587 # PDL::Graphics::Prima::PlotType::Grid::Contour #
1588 #################################################
1589  
1590 #package PDL::Graphics::Prima::PlotType::Grid::Contour;
1591 #our @ISA = qw(PDL::Graphics::Prima::PlotType::Contour);
1592  
1593 # working here - contour plot visualization of gridded data
1594  
1595 ################################################
1596 # PDL::Graphics::Prima::PlotType::Grid::Matrix #
1597 ################################################
1598 # Plots a matrix with a specified palette
1599  
1600 package PDL::Graphics::Prima::PlotType::Grid::Matrix;
1601 our @ISA = qw(PDL::Graphics::Prima::PlotType::Grid);
1602  
1603 use Carp 'croak';
1604  
1605 =item pgrid::Matrix
1606  
1607 =for ref
1608  
1609 pgrid::Matrix( [palette => PDL::Graphics::Prima::Palette], options )
1610  
1611 This plot type lets you specify colors or values on a grid to visualize
1612 rasterized contour plots (as opposed to line contour plots).
1613 The default palette is a grayscale one but you can specify whichever
1614 palette you like. See L<PDL::Graphics::Prima::Palette>. If would like to
1615 visualize an image and have already computed the RGB, HSV, or similar values,
1616 you should use pimage::Basic instead.
1617  
1618 The x- and y-bounds of your Grid are taken from the dataset x- and y-bounds,
1619 so look into L<PDL::Graphics::Prima::DataSet> for details.
1620  
1621 working here - expand, give an example
1622  
1623 =cut
1624  
1625 # Install the short-name constructor:
1626 sub pgrid::Matrix {
1627 PDL::Graphics::Prima::PlotType::Grid::Matrix->new(@_);
1628 }
1629  
1630 use PDL::Graphics::Prima::Palette;
1631  
1632 # In the initialization, check that they supplied a color grid. I'd check the
1633 # x and y data, but I don't have access to that here:
1634 sub initialize {
1635 my $self = shift;
1636 $self->SUPER::initialize(@_);
1637
1638 # make sure we have a basic palette:
1639 unless (exists $self->{palette}) {
1640 $self->{palette} = pal::WhiteToBlack;
1641 }
1642 # XXX any reason we check for definedness? Any reason we don't croak if
1643 # the palette exists but is not defined? working here
1644 $self->{palette}->plotType($self) if defined $self->{palette};
1645 }
1646  
1647 # Collation and drawing are handled by the raster role, but require the
1648 # existence of the get_colored_data function:
1649 *compute_collated_min_max_for
1650 = \&PDL::Graphics::Prima::PlotType::Role::Raster::compute_collated_min_max_for;
1651 *draw = \&PDL::Graphics::Prima::PlotType::Role::Raster::draw;
1652  
1653 sub get_colored_data {
1654 my $self = shift;
1655 return $self->{palette}->apply($self->dataset->get_data);
1656 }
1657  
1658 ##############################################################################
1659 # Image-based Plot Types #
1660 ##############################################################################
1661  
1662 package PDL::Graphics::Prima::PlotType::Image;
1663 our @ISA = qw(PDL::Graphics::Prima::PlotType);
1664  
1665 =back
1666  
1667 =head2 Image-based Plot Types
1668  
1669 While Grid-based plots focus on imaging data with a specified palette,
1670 Image-based plots focus on plotting data that has already been converted to
1671 a color representation. At the moment, there is only one plot type for
1672 images (and there likely will remain only one plot type unless a stroke of
1673 brilliance hits me). As it is automatically used as the default plot type by
1674 L<ds::Image/PDL::Graphics::Prima::DataSet/ds::Image>, and as it does not
1675 have any configuration that cannot be specified in the data set, you
1676 probably can ignore this.
1677  
1678 =item pimage::Basic
1679  
1680 The most basic image plot type simply draws the imge with the palette
1681 provided by the plot type
1682  
1683 =for ref
1684  
1685 pimage::Basic()
1686  
1687 =cut
1688  
1689 package PDL::Graphics::Prima::PlotType::Image::Basic;
1690 our @ISA = qw(PDL::Graphics::Prima::PlotType::Image);
1691  
1692 use Carp 'croak';
1693  
1694 # short form constructor:
1695 sub pimage::Basic {
1696 PDL::Graphics::Prima::PlotType::Image::Basic->new(@_);
1697 }
1698  
1699 # no need for initialize because there is nothing special to handle!
1700 # sub initialize {
1701 # my $self = shift;
1702 # $self->SUPER::initialize(@_);
1703 #}
1704  
1705 # Collation and drawing are handled by the raster role, but require the
1706 # existence of the get_colored_data function:
1707 *compute_collated_min_max_for
1708 = \&PDL::Graphics::Prima::PlotType::Role::Raster::compute_collated_min_max_for;
1709 *draw = \&PDL::Graphics::Prima::PlotType::Role::Raster::draw;
1710  
1711 sub get_colored_data {
1712 return $_[0]->dataset->get_prima_color_data;
1713 }
1714  
1715  
1716 ###############################################################################
1717 # Annotation-based Plot Types #
1718 ###############################################################################
1719  
1720 =head2 Annotation Plot Types
1721  
1722 Annotation plot types have a number of distinct features compared with other
1723 plot types. They do not have any standard data or function arguments. They
1724 tend to provide features that are decorative or annotative. Many of them
1725 support relative positioning as well. However, none of these are requirements
1726 for annotation plot types and they are the general catch-all plot type class
1727 for plot types that do not have a sensibly related dataset.
1728  
1729 Since Annotation plot types do not presume any form of the data's structure,
1730 if you are considering creating a new plot type and cannot figure out which
1731 basic plot type to use, the Annotation base class may be the right fit.
1732  
1733 As a base class, C<PDL::Graphics::Prima::PlotType::Annotation> provides the
1734 following methods that may be useful for your derived classes:
1735  
1736 =over
1737  
1738 =cut
1739  
1740 package PDL::Graphics::Prima::PlotType::Annotation;
1741 our @ISA = qw(PDL::Graphics::Prima::PlotType);
1742 use Carp;
1743  
1744 =item parse_position
1745  
1746 This method standardizes and typo-checks position specifications. The
1747 specification can be either a string or an anonymous hash; the return value
1748 is an anonymous hash. If you pass in a malformed spec, the method croaks. You
1749 call it like any other method:
1750  
1751 $hash = $note_obj->parse_position($spec);
1752  
1753 A position specification is a powerful and flexible means for specifying a
1754 location on a plot widget as a combination of data values, pixel offsets,
1755 multiples of the current width of the letter C<M>, and a percentage of the
1756 current plot portion of the widget. I think best in terms of examples, so here
1757 are a couple that hopefully illustrate how this works.
1758  
1759 If passed as a y-specification, i.e. top or bottom specification, this will
1760 pick a location that is one M-width below the upper axis. If passed as an
1761 x-specification, this will pick a location that is one M-width to the left
1762 of the right axis.
1763  
1764 # input
1765 $spec_string = '100% - 1em';
1766 # output
1767 $spec_hash = {
1768 pct => 100, em => 1
1769 };
1770  
1771 Here's another one. As a y-specification, this will give a location that is
1772 five pixels below the y-value of 12. As an x-specification, this will give a
1773 location that is five pixels to the left of the x-value of 12.
1774  
1775 # input
1776 $spec_string = '12 - 5px';
1777 # output
1778 $spec_hash = {
1779 raw => 12, px => -5,
1780 };
1781  
1782 Allowed postfixes in the spec string are nothing for raw data values, C<%>
1783 for plot window percentages, C<em> for M-widths, and C<px> for pixel widths.
1784 The corresponding names in the output hash are C<raw>, C<pct>, C<em>, and
1785 C<px>, respectively. You can use normal floating-point number notation for
1786 the values. When you use a specification string, the values associated with
1787 each key in the returned hash will be Perl scalars.
1788  
1789 As I already mentioned, this method accepts either a string or a hash and
1790 most of what I have documented has focused on the string parsing. If
1791 passed a hash, it simply verifies that the keys in the hash are only the
1792 above four values. It does not verify the values asssociated with the hash.
1793 This lack of data verification is why I discribe it above as a method to
1794 "typo-check" a position specification. If you create a specification hash
1795 that includes C<pc> instead of C<px>, this will catch it for you.
1796  
1797 Why not verify? Your method that ultimately uses the results of the parsed
1798 position may be flexible enough to use complex data types, such as piddles
1799 or other objects, and I do not want to overly restrict the utility of this
1800 method. This can be used to great effect with L</pnote::Region>, for example,
1801 in which you can specify many region highlights with a single set of piddles.
1802 The drawing commands automatically thread over those piddle values. For this
1803 reason, C<parse_position> assumes that if you specified your position by
1804 hand with a hash rather than with a specification string, you know what
1805 you are doing.
1806  
1807 One final note: if the specification string includes weird or bad values, it
1808 returns a hash with the "bad" key set to true, i.e. C<{bad => 1}>, and nothing
1809 else. This is interpreted by C<compute_position> as a bad value. Strings that
1810 will trip bad value handling include "bad", "nan", and "inf". Presently, a
1811 warning is issued every time such a value is encountered; the issuance of the
1812 warning may become a configurable option some day.
1813  
1814 To translate the resulting hash into a pixel position on the plot widget,
1815 use C<compute_position>.
1816  
1817 =cut
1818  
1819 my %allowed_entries = map {$_ => 1} qw(em pct px raw bad);
1820 my $float_point_regex = qr/[-+]?([0-9]*\.?[0-9]+|[0-9]+\.[0-9]*)([eE][-+]?[0-9]+)?/;
1821 sub parse_position {
1822 my ($self, $spec) = @_;
1823
1824 # If they passed a pre-parsed hashref, use that
1825 if (ref($spec) eq 'HASH') {
1826 # Make sure the entries are valid
1827 for my $key (keys %$spec) {
1828 croak("Region edge-hash has invalid key $key")
1829 unless $allowed_entries{$key};
1830 }
1831 }
1832 else {
1833 # Strip spaces and convert to all lower-case
1834 $spec =~ s/\s+//g;
1835 $spec = lc $spec;
1836
1837 my %hash;
1838
1839 # Handle special/annoying values. Warnings for this need to be more
1840 # configurable.
1841 if ($spec =~ m/[+-]?(bad|nan|inf)/) {
1842 warn "Found $1 in position spec; ignoring position\n";
1843 return { bad => 1 };
1844 }
1845
1846 # Pull out the different parts, one at a time
1847 if ($spec =~ s/($float_point_regex)em//) {
1848 $hash{em} = $1;
1849 }
1850 if ($spec =~ s/($float_point_regex)\%//) {
1851 $hash{pct} = $1 / 100;
1852 }
1853 if ($spec =~ s/($float_point_regex)px//) {
1854 $hash{px} = $1;
1855 }
1856 if ($spec =~ /^($float_point_regex)$/) {
1857 $hash{raw} = $1;
1858 }
1859 elsif (length($spec) > 0) {
1860 croak("Unknown fragment in region edge spec: $spec");
1861 }
1862 $spec = \%hash;
1863 }
1864
1865 return $spec;
1866 }
1867  
1868 =item em_width
1869  
1870 This method takes the current axis and obtains the width of the letter C<M>
1871 in pixels. You call it like so:
1872  
1873 $em_width = $note_obj->em_width($y_axis);
1874  
1875 Note: you can obtain the x- or y-axis object calling the C<x> and C<y>
1876 methods, respectively, of the plot widget.
1877  
1878 =cut
1879  
1880 sub em_width {
1881 my ($self, $axis) = @_;
1882 my ($em_width) = $axis->em_dims;
1883 return $em_width;
1884 }
1885  
1886 =item compute_position
1887  
1888 This method expects a position hash, an axis, and a drawing ratio (which is
1889 always supplied as the last argument to C<draw>; if you're not sure what to
1890 do, use a value of 1) and computes a pixel offset for the position. The
1891 position hash must have a percentage or a raw data value or the method
1892 croaks. The returned value is a pixel position that corresponds to the
1893 desired location on the plot widget and which can be fed directly into
1894 Prima's drawing operations. If any of the values in the position hash are
1895 piddles, the result will be a piddle of positions that can be sent to the
1896 drawing operations provided by L<PDL::Drawing::Prima>.
1897  
1898 This value has special handling for bad values. If the bad key is set in the
1899 position hash, a piddle with a lone bad value is returned.
1900  
1901 This method expects a position hash of the form built (or verified) by
1902 C<parse_position>.
1903  
1904 =cut
1905  
1906 sub compute_position {
1907 my ($self, $position_hash, $axis, $ratio) = @_;
1908
1909 # Special-case weird value handling
1910 return pdl(1)->setvaltobad(1) if $position_hash->{bad};
1911
1912 # Start with the raw data, or undef
1913 my $rel_position;
1914 $rel_position = $axis->reals_to_relatives($position_hash->{raw})
1915 if defined $position_hash->{raw};
1916 # Next add the percent:
1917 $rel_position += $position_hash->{pct}
1918 if defined $position_hash->{pct};
1919 # If we don't have a relative position, croak
1920 croak("Position spec must have a raw or percentage spec")
1921 if not defined $rel_position;
1922
1923 # Convert the relative position to pixels
1924 my $position = $axis->relatives_to_pixels($rel_position, $ratio);
1925
1926 # Add any pixel offsets
1927 $position += $position_hash->{px} if defined $position_hash->{px};
1928 $position += $self->em_width($axis) * $position_hash->{em}
1929 if defined $position_hash->{em};
1930  
1931 return $position;
1932 }
1933  
1934 =back
1935  
1936 There are a number of annotation plot-types:
1937  
1938 =cut
1939  
1940  
1941 #####################################################
1942 # PDL::Graphics::Prima::PlotType::Annotation::Region #
1943 #####################################################
1944  
1945 =item pnote::Region
1946  
1947 =for ref
1948  
1949 pnote::Region( [left => position-spec],
1950 [right => position-spec],
1951 [bottom => position-spec],
1952 [top => position-spec],
1953 options )
1954  
1955 Draws a shaded region, or if any of your position specs
1956 include piddles it draws a set of shaded regions in one PDL-threaded drawing
1957 operation.
1958  
1959 This is useful if you want to highlight certain portions of your
1960 figure with a rectangular highlight (or is it a backlight?). Each Region
1961 annotation has a position specification for the left, bottom, right, and top
1962 edges. The defaults for the left and bottom are the specification string
1963 C<'0%'> and the defaults for the right and top are the specification string
1964 C<'100%'>.
1965  
1966 For more on position specifications, see the discussion of C<parse_position>
1967 under L</Annotation Plot Types>.
1968  
1969 =cut
1970  
1971 package PDL::Graphics::Prima::PlotType::Annotation::Region;
1972 our @ISA = qw(PDL::Graphics::Prima::PlotType::Annotation);
1973  
1974 use Carp;
1975 use PDL;
1976  
1977 # short-name constructor:
1978 sub pnote::Region {
1979 return PDL::Graphics::Prima::PlotType::Annotation::Region->new(@_);
1980 }
1981  
1982 sub initialize {
1983 my $self = shift;
1984  
1985 # Call the superclass initialization:
1986 $self->SUPER::initialize(@_);
1987
1988 # Set sane defaults for the different specs
1989 %$self = (
1990 left => '0%', bottom => '0%', right => '100%', top => '100%',
1991 %$self
1992 );
1993
1994 # Replace the specs with parsed versions
1995 for my $edge_name (qw(left bottom right top)) {
1996 $self->{$edge_name} = $self->parse_position($self->{$edge_name});
1997 }
1998 }
1999  
2000 # Collation needs to eventually account for raw values, but for now it simply
2001 # doesn't register; working here
2002 sub compute_collated_min_max_for {
2003 my ($self, $axis_name, $pixel_extent) = @_;
2004 return zeroes($pixel_extent+1)->setvaltobad(0),
2005 zeroes($pixel_extent+1)->setvaltobad(0);
2006 }
2007  
2008 sub draw {
2009 my ($self, $canvas, $ratio) = @_;
2010 # Assemble the various properties from the plot-type object and the dataset
2011 my @prop_list = @PDL::Drawing::Prima::bars_props;
2012 my %properties = $self->generate_properties(@prop_list);
2013  
2014 # Get the left, bottom, right, and top pixel positions
2015 my @pixel_positions = (
2016 $self->compute_position($self->{left}, $self->widget->x, $ratio),
2017 $self->compute_position($self->{bottom}, $self->widget->y, $ratio),
2018 $self->compute_position($self->{right}, $self->widget->x, $ratio),
2019 $self->compute_position($self->{top}, $self->widget->y, $ratio),
2020 );
2021
2022 $canvas->pdl_bars(@pixel_positions, %properties);
2023 }
2024  
2025 ###################################################
2026 # PDL::Graphics::Prima::PlotType::Annotation::Box #
2027 ###################################################
2028  
2029 =item pnote::Box
2030  
2031 =for ref
2032  
2033 pnote::Box( [left => position-spec],
2034 [right => position-spec],
2035 [bottom => position-spec],
2036 [top => position-spec],
2037 options )
2038  
2039 Draws an outlied box, or if any of your position specs
2040 include piddles it draws a set of outlined boxes in one PDL-threaded drawing
2041 operation.
2042  
2043 This is the outline equivalent of pnote::Region; see those docs for details.
2044  
2045 For more on position specifications, see the discussion of C<parse_position>
2046 under L</Annotation Plot Types>.
2047  
2048 =cut
2049  
2050 package PDL::Graphics::Prima::PlotType::Annotation::Box;
2051 our @ISA = qw(PDL::Graphics::Prima::PlotType::Annotation::Region);
2052  
2053 use Carp;
2054 use PDL;
2055  
2056 # short-name constructor:
2057 sub pnote::Box {
2058 return PDL::Graphics::Prima::PlotType::Annotation::Box->new(@_);
2059 }
2060  
2061 # Collation needs to eventually account for raw values, but for now it simply
2062 # doesn't register; working here
2063 sub compute_collated_min_max_for {
2064 my ($self, $axis_name, $pixel_extent) = @_;
2065 return zeroes($pixel_extent+1)->setvaltobad(0),
2066 zeroes($pixel_extent+1)->setvaltobad(0);
2067 }
2068  
2069 sub draw {
2070 my ($self, $canvas, $ratio) = @_;
2071 # Assemble the various properties from the plot-type object and the dataset
2072 my @prop_list = @PDL::Drawing::Prima::rectangles_props;
2073 my %properties = $self->generate_properties(@prop_list);
2074  
2075 # Get the left, bottom, right, and top pixel positions
2076 my @pixel_positions = (
2077 $self->compute_position($self->{left}, $self->widget->x, $ratio),
2078 $self->compute_position($self->{bottom}, $self->widget->y, $ratio),
2079 $self->compute_position($self->{right}, $self->widget->x, $ratio),
2080 $self->compute_position($self->{top}, $self->widget->y, $ratio),
2081 );
2082
2083 $canvas->pdl_rectangles(@pixel_positions, %properties);
2084 }
2085  
2086 #####################################################
2087 # PDL::Graphics::Prima::PlotType::Annotation::Line #
2088 #####################################################
2089  
2090 =item pnote::Line
2091  
2092 =for ref
2093  
2094 pnote::Line( [x1 => position-spec],
2095 [y1 => position-spec],
2096 [x2 => position-spec],
2097 [y2 => position-spec],
2098 options )
2099  
2100 Draws a line from (x1, y1) to (x2, y2). If any of the position specs involve
2101 piddles, it will draw a set of lines in one PDL-threaded drawing operation.
2102  
2103 The default value for x1 and y1 is C<'0%'> and the default value for x2 and y2
2104 is C<'100%'>.
2105  
2106 For more on position specifications, see the discussion of C<parse_position>
2107 under L</Annotation Plot Types>.
2108  
2109 =cut
2110  
2111 package PDL::Graphics::Prima::PlotType::Annotation::Line;
2112 our @ISA = qw(PDL::Graphics::Prima::PlotType::Annotation);
2113  
2114 use Carp;
2115 use PDL;
2116  
2117 # short-name constructor:
2118 sub pnote::Line {
2119 return PDL::Graphics::Prima::PlotType::Annotation::Line->new(@_);
2120 }
2121  
2122 sub initialize {
2123 my $self = shift;
2124  
2125 # Call the superclass initialization:
2126 $self->SUPER::initialize(@_);
2127
2128 # Set sane defaults for the different specs
2129 %$self = (
2130 x1 => '0%', y1 => '0%', x2 => '100%', y2 => '100%',
2131 %$self
2132 );
2133
2134 # Replace the specs with parsed versions
2135 for my $coord (qw(x1 y1 x2 y2)) {
2136 $self->{$coord} = $self->parse_position($self->{$coord});
2137 }
2138 }
2139  
2140 # Collation needs to eventually account for raw values, but for now it simply
2141 # doesn't register; working here
2142 sub compute_collated_min_max_for {
2143 my ($self, $axis_name, $pixel_extent) = @_;
2144 return zeroes($pixel_extent+1)->setvaltobad(0),
2145 zeroes($pixel_extent+1)->setvaltobad(0);
2146 }
2147  
2148 sub draw {
2149 my ($self, $canvas, $ratio) = @_;
2150 # Assemble the various properties from the plot-type object and the dataset
2151 my @prop_list = @PDL::Drawing::Prima::lines_props;
2152 my %properties = $self->generate_properties(@prop_list);
2153  
2154 # Get the left, bottom, right, and top pixel positions
2155 my @pixel_positions = (
2156 $self->compute_position($self->{x1}, $self->widget->x, $ratio),
2157 $self->compute_position($self->{y1}, $self->widget->y, $ratio),
2158 $self->compute_position($self->{x2}, $self->widget->x, $ratio),
2159 $self->compute_position($self->{y2}, $self->widget->y, $ratio),
2160 );
2161
2162 $canvas->pdl_lines(@pixel_positions, %properties);
2163 }
2164  
2165 ####################################################
2166 # PDL::Graphics::Prima::PlotType::Annotation::Text #
2167 ####################################################
2168  
2169 =item pnote::Text
2170  
2171 =for ref
2172  
2173 pnote::Text( text-string,
2174 [x => position-spec],
2175 [y => position-spec],
2176 [clipRect => clip-spec],
2177 options )
2178  
2179 Adds a text annotation to your plot. The x- and y-position specifications
2180 default to the string C<'50%'>, i.e. right in the middle of the plot. This
2181 may not be terribly useful, but hey, it's a default, right? The default
2182 C<clipRect> specification is the string C<'normal'>, which means that the
2183 drawing will be clipped like any other plot type to the "plot window", the
2184 region within the axes. You can also specify the string C<'canvas'>, which
2185 expands the clip region to the entire canvas, or pass a four-element array
2186 suitable for a call to the Prima C<clipRect> method. This added flexibility
2187 lets you to add notations anywhere on the figure, not just in the plotting
2188 region.
2189  
2190 For more on position specifications, see the discussion of C<parse_position>
2191 under L</Annotation Plot Types>.
2192  
2193 =cut
2194  
2195 package PDL::Graphics::Prima::PlotType::Annotation::Text;
2196 our @ISA = qw(PDL::Graphics::Prima::PlotType::Annotation);
2197  
2198 use Carp;
2199 use PDL;
2200  
2201 sub pnote::Text {
2202 croak('pnote::Text must be given a string of text and optional x/y key/value pairs')
2203 if @_ % 2 == 0;
2204 return PDL::Graphics::Prima::PlotType::Annotation::Text->new(text => @_);
2205 }
2206  
2207 sub initialize {
2208 my $self = shift;
2209
2210 # Call the superclass initialization:
2211 $self->SUPER::initialize(@_);
2212
2213 # Set sane defaults for the different specs
2214 %$self = (
2215 x => '50%', y => '50%', clipRect => 'normal',
2216 %$self
2217 );
2218
2219 # Replace the specs with parsed versions
2220 for my $edge_name (qw(x y)) {
2221 $self->{$edge_name} = $self->parse_position($self->{$edge_name});
2222 }
2223 }
2224  
2225 # Collation needs to eventually account for raw values, but for now it simply
2226 # doesn't register; working here
2227 sub compute_collated_min_max_for {
2228 my ($self, $axis_name, $pixel_extent) = @_;
2229 return zeroes($pixel_extent+1)->setvaltobad(0),
2230 zeroes($pixel_extent+1)->setvaltobad(0);
2231 }
2232  
2233 sub draw {
2234 my ($self, $canvas, $ratio) = @_;
2235
2236 # Parse the position and back out if it's bad
2237 my $x = $self->compute_position($self->{x}, $self->widget->x, $ratio);
2238 my $y = $self->compute_position($self->{y}, $self->widget->y, $ratio);
2239 return if PDL::Core::topdl($x)->isbad->all
2240 or PDL::Core::topdl($x)->isbad->all;
2241
2242 # Back up the clip rectangle
2243 my @clip_rect = $canvas->clipRect;
2244
2245 # Parse the clip rectangle
2246 my $clipRect = $self->{clipRect};
2247 if (ref($clipRect) and ref($clipRect) eq 'ARRAY' and @$clipRect == 4) {
2248 $canvas->clipRect(@$clipRect);
2249 }
2250 elsif (lc $clipRect eq 'canvas') {
2251 $canvas->clipRect(0, 0, $canvas->size);
2252 }
2253 elsif (lc $clipRect ne 'normal') {
2254 croak('Text Annotation clipRect must be "normal", "canvas", or a four-element array');
2255 }
2256
2257 # Set the properties for the text drawing operation and back up the old
2258 # properties
2259 my %properties = $self->generate_properties(qw(
2260 color backColor font rop textOpaque textOutBaseline
2261 ));
2262 my %backups = $canvas->get(keys %properties);
2263 if (exists $properties{font}) {
2264 $canvas->font->set(
2265 %{$properties{font}}
2266 );
2267 delete $properties{font};
2268 }
2269 $canvas->set(%properties);
2270
2271 # Draw the text
2272 $canvas->text_out($self->{text}, $x, $y);
2273
2274 # Restore the old properties and clip rectangle
2275 $canvas->set(%backups);
2276 $canvas->clipRect(@clip_rect);
2277 }
2278  
2279 ###############################################################################
2280 # Creating your own Plot Type #
2281 ###############################################################################
2282 # Also includes the base type
2283  
2284 package PDL::Graphics::Prima::PlotType;
2285  
2286 our $VERSION = 0.17; # update with update-version.pl
2287  
2288 use Carp 'croak';
2289  
2290 =back
2291  
2292 =head2 Creating new plot types
2293  
2294 If the supplied plot types do not match your needs, you can always make a new
2295 one: all of the code for all of these plot types is written in Perl, so it isn't
2296 too difficult. This section describes how to create custom plot types for your
2297 own needs.
2298  
2299 To write your own plot type, you must create a class that is derived from
2300 C<PDL::Graphics::Prima::PlotType>. (To make the discussion a bit more concrete,
2301 I am going to use the ficticious FooBars plotType, which I suppose would plot
2302 some fancy error bars.) Such a derived class would probably start out with these
2303 lines of code:
2304  
2305 package PDL::Graphics::Prima::PlotType::Pair::FooBars;
2306 use base 'PDL::Graphics::Prima::PlotType::Pair';
2307  
2308 You must then write a custom C<draw> function, and you can optionally overload
2309 the following functions: C<xmin>, C<xmax>, C<ymin>, C<ymax>, C<initialize>.
2310  
2311 You should also install a constructor under C<ppair::FooBars> that looks like
2312 this:
2313  
2314 sub ppair::FooBars {
2315 PDL::Graphics::Prima::PlotType::Pair::FooBars->new(@_);
2316 }
2317  
2318 That uses the inherited C<PDL::Graphics::Prima::PlotType::new> function, which
2319 will eventually call your class's C<initialize> function. If your initializer
2320 expects custom arguments, you should overload the C<initialize> function like
2321 so:
2322  
2323 # still in the PDL::Graphics::Prima::PlotType::Pair::FooBars package
2324 sub initialize {
2325 my $self = shift;
2326
2327 # You could pull items out of @args at this point if you
2328 # want. To call the superclass initialization do this:
2329 $self->SUPER::initialize(@_);
2330
2331 # Here's some custom args processing. If the user did
2332 # not specify a curviness, default to 4:
2333 $self->{curviness} ||= 4;
2334
2335 # Could also check that the supplied values make sense:
2336 croak('Curviness must be a positive integer')
2337 unless $self->{curviness} =~ /^\d+$/
2338 and $self->{curviness} > 0;
2339 }
2340  
2341 You could shove all of that construction functionality into C<ppair::FooBars>, but
2342 then other classes would not be able to derive functionality from your
2343 undoubtedly elegant class without resorting to rather inelegant code.
2344  
2345 Which brings me to writing plotTypes that are derived from other plotTypes.
2346 That is allowed, of course, in which case you can override whichever class
2347 functions you want. At that point, you are doing normal Perl OO programming,
2348 so it's as easy (and/or annoying) as that.
2349  
2350 =cut
2351  
2352 # The plotType new function. Do not override this. If you want to override how
2353 # the plotType is constructed, override the initialize function in your derived
2354 # class.
2355 sub new {
2356 my $class = shift;
2357 my $self = {};
2358 bless $self, $class;
2359 $self->initialize(@_);
2360 return $self;
2361 }
2362  
2363 # Standard initialization expects key/value pairs and simply stores them in
2364 # $self:
2365 sub initialize {
2366 my $self = shift;
2367 croak('Standard plotTypes arguments must be in key => value pairs')
2368 if @_ % 2 == 1;
2369 my %args = @_;
2370 foreach my $key (keys %args) {
2371 $self->{$key} = $args{$key};
2372 }
2373 }
2374  
2375 =head2 compute_collated_min_max_for
2376  
2377 This plotType function is called when the graph needs to determine automatic
2378 minima and maxima. It is hard to explain and will require some attention in
2379 the future to flesh out its documentation. My apologies for now.
2380  
2381 This function is called with three arguments and should always return
2382 two piddles. The return values should be of the sort described in
2383 L<PDL::Drawing::Prima::collate_min_max_wrt_many>. The three arguments are:
2384  
2385 =over
2386  
2387 =item plotType object (or class name)
2388  
2389 This is whatever you created with your constructor; if you're following the
2390 example above, that would be an instance of the plotType. This passes in
2391 whatever the dataset was given for the plotType.
2392  
2393 =item axis_name
2394  
2395 The axis for which we need to know the min and the max
2396  
2397 =item pixel_extent
2398  
2399 The width into which the
2400  
2401 =back
2402  
2403 If you cannot determine an extremum, or do not want to determine an extremum,
2404 you can return two piddles of size C<$pixel_extent> filled with bad values.
2405  
2406 =cut
2407  
2408 sub compute_collated_min_max_for {
2409 my ($self, $axis_name, $pixel_extent) = @_;
2410 # Get the list of properties for which we need to look for bad values:
2411 my %properties
2412 = $self->generate_properties(@PDL::Drawing::Prima::lines_props);
2413
2414 # Extract the line widths, against which we'll collate:
2415 my $lineWidths = $properties{lineWidths};
2416 $lineWidths = $self->widget->lineWidth unless defined $lineWidths;
2417 delete $properties{lineWidths};
2418
2419 # get the rest of the piddles, which are associated with plural keys
2420 my @prop_piddles;
2421 while(my ($k, $v) = each %properties) {
2422 push @prop_piddles, $v if $k =~ /s$/;
2423 }
2424
2425 # Get the data:
2426 my ($xs, $ys) = $self->dataset->get_data;
2427 my ($to_check, $extra) = ($xs, $ys);
2428 ($to_check, $extra) = ($ys, $xs) if $axis_name eq 'y';
2429
2430 # Collate:
2431 return PDL::collate_min_max_wrt_many($to_check, $lineWidths
2432 , $to_check, $lineWidths, $pixel_extent, $extra, @prop_piddles);
2433 }
2434  
2435 =head2 generate_properties
2436  
2437 This method accumulates all the properties from the plotType object together
2438 with those from the dataset into a single hash that you can submit to one of the
2439 L<PDL-based Prima drawing methods|PDL::Drawing::Prima/> or (if you are using a
2440 normal L<Prima::Drawable graphics primitive|Prima::Drawable/Graphic primitives methods>
2441 and expect that all of the properties will be singular) the set method discussed
2442 in L<Prima::Object|Prima::Object/>.
2443  
2444 I use this function both in the implementations of the C<draw> and
2445 C<collate_min_max_wrt_many> methods, and I have never encountered a reason to
2446 override it.
2447  
2448 =cut
2449  
2450 # This function exists to aggregate the list of properties that have been set
2451 # for the dataset in general (I want all plot types for this data to be red) and
2452 # for this particular plotType object (I want the error bars to have a lineWidth
2453 # of 3):
2454 sub generate_properties {
2455 my ($self, @prop_list) = @_;
2456
2457 # Collect singular and plural properties
2458 @prop_list = map {/((.*)s)$/ ? ($1, $2) : ($_) } @prop_list;
2459
2460 my %properties;
2461 my $dataset = $self->dataset;
2462
2463 # Add all of the specified properties to a local collection that eventually
2464 # gets passed to the low-level drawing routine:
2465 if (ref($self)) {
2466 for my $prop (@prop_list) {
2467 if (exists $self->{$prop}) {
2468 $properties{$prop} = $self->{$prop};
2469 }
2470 elsif (exists $dataset->{$prop}) {
2471 $properties{$prop} = $dataset->{$prop};
2472 }
2473 }
2474
2475 }
2476 else {
2477 for my $prop (@prop_list) {
2478 if (exists $dataset->{$prop}) {
2479 $properties{$prop} = $dataset->{$prop};
2480 }
2481 }
2482 }
2483
2484 return %properties;
2485 }
2486  
2487 =head2 widget
2488  
2489 Returns the widget that owns the dataType which, in turn, called this drawing
2490 operation.
2491  
2492 =head2 dataset
2493  
2494 Returns the dataSet that owns this plotType.
2495  
2496 =head2 get_data
2497  
2498 Shorthand: Returns the result of calling the dataset's get_data function.
2499  
2500 =cut
2501  
2502 sub widget {
2503 return $_[0]->dataset->widget;
2504 }
2505  
2506 # Weaken the reference to the dataset so that we don't have memory leaks
2507 use Scalar::Util;
2508 sub dataset {
2509 return $_[0]->{dataSet} if @_ == 1;
2510 my ($self, $dataSet) = @_;
2511 $self->{dataSet} = $dataSet;
2512 Scalar::Util::weaken($self->{dataSet});
2513 }
2514  
2515 # A function that gets the data, meant to be overloaded:
2516 sub get_data {
2517 return $_[0]->dataset->get_data;
2518 }
2519  
2520 =head2 draw
2521  
2522 Needs explanation and examples. This function will be called whenever the
2523 plot widget needs to redraw your plotType (window resizes, zooms, etc). It is
2524 a simple method call, and is called with the plotType object as the first
2525 argument, the canvas upon which to draw as the second argument (typically the
2526 widget, but sometimes not), and the canvas ratio if the canvas's size is not
2527 the same as the widget's size.
2528  
2529 Now, something that I I<always> forget to do is to convert the data values to
2530 pixel values. You do that with the widget's x- and y-axis objects with code like
2531  
2532 my $x_to_plot = $self->widget->x->reals_to_pixels($xs, $ratio)
2533  
2534 If it seems like your new plot type is not plotting anything, be sure that you
2535 have properly converted the points you are trying to plot.
2536  
2537 =cut
2538  
2539 #sub draw {
2540 # my $invocant = shift;
2541 # my $class = ref($invocant) ? ref($invocant) : $invocant;
2542 # croak("Plot type $class does not define its own drawing function. Please "
2543 # . 'report this bug to the author');
2544 #}
2545  
2546  
2547 ############################################
2548 # PDL::Graphics::Prima::PlotType::CallBack #
2549 ############################################
2550 # Calls user-supplied callbacks for all major functions
2551 # Provides a playground to try out new plot types
2552  
2553 package PDL::Graphics::Prima::PlotType::CallBack;
2554 our @ISA = qw(PDL::Graphics::Prima::PlotType);
2555  
2556 # working here - this isn't working the way it's supposed to, and I need to
2557 # update the documentation since I no longer have the min/max functions, but
2558 # I do need the collation function.
2559  
2560 =head1 CallBack
2561  
2562 This class lets you supply your own callback for drawing routines. In time,
2563 it may also allow you to supply your own callback for autoscaling, but that's
2564 not supported at the moment. This may seem overly high-level, but
2565 it's mostly here so that you can implement custom drawing routines, implement
2566 user-level tweaks to existing classes, and toy around with new plot types
2567 without having to write a full-blown plot class.
2568  
2569 =head2 New Drawing Techniques
2570  
2571 If you like the way that a class operates but want to use your own drawing
2572 routines, you can specify a base class and a drawing callback like so:
2573  
2574 my $smiley_plot_type = pt::CallBack(
2575 base_class => 'PDL::Graphics::Prima::PlotType::Pair::Blobs',
2576 draw => sub {
2577 my ($self, $canvas, $ratio) = @_;
2578
2579 # Retrieve the data from the dataset:
2580 my ($xs, $ys) = $self->dataset->get_data_as_pixels($ratio);
2581
2582 # Draw the smileys:
2583 $canvas->pdl_ellipses($xs, $ys, 20, 20); # face
2584 $canvas->pdl_fill_ellipses($xs - 5, $ys + 4, 2, 2); # left eye
2585 $canvas->pdl_fill_ellipses($xs + 5, $ys + 4, 2, 2); # right eye
2586 $canvas->pdl_arcs($xs, $ys, 10, 10, 200, 340); # smiling mouth
2587 },
2588 radius => 10, # be sure to coordinate with pdl_ellipses, above
2589 );
2590  
2591 This will use the Blobs methods for determining xmin, xmax, ymin, and ymax, but
2592 use this custom method for drawing smileys.
2593  
2594 =cut
2595  
2596  
2597 # Install the short name constructor:
2598 sub pt::CallBack {
2599 PDL::Graphics::Prima::PlotType::CallBack->new(@_);
2600 }
2601  
2602 # Set up the callback functions:
2603 sub initialize {
2604 my $self = shift;
2605  
2606 # Basic initialization:
2607 PDL::Graphics::Prima::PlotType::initialize($self, @_);
2608
2609 # Default the base class to the most basic one:
2610 croak("You must supply a base class") unless $self->{base_class};
2611 croak('Base class must be a valid PlotType')
2612 unless eval{$self->{base_class}->isa('PDL::Graphics::Prima::PlotType')};
2613
2614 # Call the superclass initialization:
2615 my $init = $self->{base_class}->can('initialize');
2616 &$init($self, @_);
2617
2618 # Make sure that we have a valid draw function:
2619 unless ($self->{base_class}->can('draw')) {
2620 croak('You must supply a draw function or a drawable base class to the CallBack plot class')
2621 unless exists $self->{draw} and ref ($self->{draw})
2622 and ref ($self->{draw}) eq 'CODE';
2623
2624 }
2625 }
2626  
2627 # Dynamic drawing based upon values of the draw key and/or the base class:
2628 sub draw {
2629 my ($self, $canvas, $ratio) = @_;
2630
2631 if (not exists $self->{draw}) {
2632 # Didn't supply a draw function, so call the base class's draw function:
2633 croak('CallBack plot type must supply a drawing function or '
2634 . 'a base class that can draw itself.')
2635 unless $self->{base_class}->can('draw');
2636
2637 # Masquerade as the base class:
2638 my $class = ref($self);
2639 bless $self, $self->{base_class};
2640 $self->draw($canvas, $ratio);
2641 bless $self, $class;
2642 return;
2643 }
2644
2645 if (ref($self->{draw}) and ref($self->{draw}) eq 'CODE') {
2646 # They supplied a code reference, so run it:
2647 my $func = $self->{draw};
2648 &$func($self, $canvas, $ratio);
2649 return;
2650 }
2651
2652 croak('You must supply a code reference for your drawing code.');
2653 }
2654  
2655 sub compute_collated_min_max_for {
2656 my ($self, @args) = @_;
2657 # Masquerade as the base class:
2658 my $class = ref($self);
2659 bless $self, $self->{base_class};
2660 my @to_return = $self->compute_collated_min_max_for(@args);
2661 bless $self, $class;
2662 return @to_return;
2663 }
2664  
2665 1;
2666  
2667 __END__