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

filter: Statementstmt 0.0% 0 / 531 Branchbran 0.0% 0 / 148 Conditioncond 0.0% 0 / 54 MC/DCmcdc n/a Subroutinesub 0.0% 0 / 94 Podpod 0.0% 0 / 63 totaltotal 0.0% 0 / 890 CC 75 SCAR 30.0
CC
75
Cov
0%
init
156.0
CDF
30.0
guess_scaling_for
30.0
CRAP 20.1
1 use strict;
2 use warnings;
3 use PDL::Graphics::Prima::PlotType;
4 use PDL::Graphics::Prima::Palette;
5  
6 # Codifies the different kinds of dataset plotting that you can do, and defines
7 # the class for the tied dataset array.
8  
9 =head1 NAME
10  
11 PDL::Graphics::Prima::DataSet - the way we think about data
12  
13 =head1 SYNOPSIS
14  
15 -distribution => ds::Dist(
16 $data, plotType => ppair::Lines,
17 binning => bt::Linear,
18 ),
19 -lines => ds::Pair(
20 $x, $y, plotTypes => [ppair::Lines, ppair::Diamonds]
21 ),
22 -contour => ds::Grid(
23 $matrix,
24 # Specify your bounds in one of these three ways
25 bounds => [$left, $bottom, $right, $top],
26 y_edges => $ys, x_edges => $xs,
27 x_bounds => [$left, $right], y_bounds => [$bottom, $top],
28 # Unnecessary if you want the default palette
29 plotType => pgrid::Matrix(palette => $palette),
30 ),
31 -image => ds::Image(
32 $image, format => 'string',
33 ... ds::Grid bounder options ...
34 # Unnecessary at the moment
35 plotType => pimage::Basic,
36 ),
37 -function => ds::Func(
38 $func_ref, xmin => $left, xmax => $right, N_points => 200,
39 ),
40
41  
42 =head1 DESCRIPTION
43  
44 C<PDL::Graphics::Prima> fundamentally conceives of two different kinds of
45 data representations. There are pairwise representations, such as line plot
46 used to visualize a time series, and there are gridded representations,
47 such as raster images used to visualize heat maps (or images). Any data that
48 you want to represent must have some way to conceive of itself as either
49 pairwise or gridded.
50  
51 Of course, there are plenty of things we want to visualize that are not
52 pairwise data or grids. For example, what if we want to plot the
53 distribution of scores on an exam? In this case, we would probably use a
54 histogram. When you think about it, a histogram is just a pairwise
55 visual representation. In other words, to visualize a distribution, we have
56 to first map the distribution into a pairwise representation, and then
57 choose an appropriate way to visualize that representation, in this case a
58 histogram.
59  
60 So, we have two fundamental ways to represent data, but many possible
61 data sets. For pairwise representations, we have L<ds::Pair|/Pair>, the
62 basic pairwise DataSet. L<ds::Dist|/Dist> is a derived DataSet which
63 includes a binning specification that bins the distribution into bin centers
64 (x) and heights (y) to get a pairwise representation. L<ds::Func|/Func>
65 is another derived DataSet that generates evenly sampled data based on the
66 axis bounds and evaluates the supplied function at those points to get a
67 pairwise representation. L<ds::Image|/Image> provides a simple means for
68 visualizing images, and L<ds::Grid|/Grid> provides a means for mapping a
69 gridded collection of data into an image, using
70 L<palettes|PDL::Graphics::Prima::Palette/>.
71  
72 =head2 Base Class
73  
74 The Dataset base class provides a few methods that work for all datasets.
75 These include accessing the associated widget and drawing the data.
76  
77 =over
78  
79 =cut
80  
81 package PDL::Graphics::Prima::DataSet;
82 use Carp;
83 use Scalar::Util;
84  
85 our $VERSION = 0.17; # update with update-version.pl
86  
87 =item widget
88  
89 The widget associated with the dataset.
90  
91 =cut
92  
93 sub widget {
94 # Simply return the widget if it's a getter:
95 return $_[0]->{widget} if @_ == 1;
96
97 # It's a setter call, so set self's widget. Note the use of weaken to avoid
98 # circular references and memory leaks.
99 my ($self, $widget) = @_;
100 $self->{widget} = $widget;
101 Scalar::Util::weaken($self->{widget});
102 }
103  
104 =item draw
105  
106 Calls all of the drawing functions for each plotType of the dataSet. This also
107 applies all the global drawing options (like C<color>, for example) that were
108 supplied to the dataset.
109  
110 =cut
111  
112 # Calls all the drawing functions for the plotTypes for this dataset:
113 sub draw {
114 my ($dataset, $canvas, $ratio) = @_;
115 my $widget = $dataset->widget;
116
117 # Call each plot type's drawing function, in the order specified:
118 foreach my $plotType (@{$dataset->{plotTypes}}) {
119 $plotType->draw($canvas, $ratio);
120 }
121 }
122  
123 =item compute_collated_min_max_for
124  
125 This function is part of the collated min/max chain of function calls that
126 leads to reasonable autoscaling. The Plot widget asks each dataSet to determine
127 its collated min and max by calling this function, and this function simply
128 agregates the collated min and max results from each of its plotTypes.
129  
130 In general, you needn't worry about collated min and max calculations unless
131 you are trying to grapple with the autoscaling system or are creating a new
132 plotType.
133  
134 working here - link to more complete documentation of the collation and
135 autoscaling systems.
136  
137 =cut
138  
139 # working here - function based datasets with nonzero widths will get
140 # their x-bounds from the widget, then return wider bounds to accomodate
141 # the data for the full width. This means that either (1) successive
142 # resizing will lead to larger and larger bounds or (2) the plots of the
143 # function-data will be cropped. Of course, all of this is only a problem
144 # with auto-scaling. Otherwise it gives no trouble.
145  
146 sub compute_collated_min_max_for {
147 # Must get the collated min max for each plot type for this data:
148 my ($self, $axis_name, $pixel_extent) = @_;
149 my $widget = $self->{dataSets}->{widget};
150
151 # Add an initial collection of bad values to handle the special calse of
152 # no data sets.
153 my @min_collection = (PDL->zeroes($pixel_extent+1)->setvaltobad(0));
154 my @max_collection = (PDL->zeroes($pixel_extent+1)->setvaltobad(0));
155  
156 foreach my $plotType (@{$self->{plotTypes}}) {
157
158 # Accumulate all the collated results
159 my ($min, $max)
160 = $plotType->compute_collated_min_max_for($axis_name, $pixel_extent);
161 # The collated results are not required to be one dimensional.
162 # As such, I need to reduce them. I do this by moving the dimension
163 # with $pixel_extent entries to the back and then calling minimum
164 # until I have only one dimension remaining.
165 warn "Internal error: plot type $plotType returned an undefined min"
166 if not defined $min;
167 warn "Internal error: plot type $plotType returned an undefined max"
168 if not defined $max;
169 next if not defined $min or not defined $max;
170 $min = $min->squeeze->mv(0,-1);
171 $min = $min->minimum while($min->ndims > 1);
172 $max = $max->squeeze->mv(0,-1);
173 $max = $max->maximum while($max->ndims > 1);
174 push @min_collection, $min;
175 push @max_collection, $max;
176 }
177
178 # Merge all the data:
179 my $collated_min = PDL::cat(@min_collection)->mv(-1,0)->minimum;
180 my $collated_max = PDL::cat(@max_collection)->mv(-1,0)->maximum;
181
182 return ($collated_min, $collated_max);
183 }
184  
185 =item new
186  
187 This is the universal constructor that is called by the short-name constructors
188 introduced below. This handles the uniform packaging of plotTypes (for
189 example, allowing the user to say C<plotType => ppair::Diamonds> instead of
190 the more verbose C<plotTypes => [ppair::Diamonds]>). In general, you (the
191 user) will not need to invoke this constructor directly.
192  
193 =cut
194  
195 sub new {
196 # Short-name constructors are required to send us stuff that looks like
197 # this. In particular, they must pack their data into appropriately
198 # named keys among the %options
199 my ($class, %options) = @_;
200
201 my $self = \%options;
202 bless ($self, $class);
203
204 # Ensure that we have a plural plotTypes key, and no singular plotType key:
205 if (exists $self->{plotType}) {
206 my $type = $self->{plotType};
207 if (ref($type) eq 'ARRAY') {
208 $self->{plotTypes} = $type;
209 }
210 else {
211 $self->{plotTypes} = [$type];
212 }
213 delete $self->{plotType};
214 }
215
216 # Ensure that if they supplied a plotTypes, that it is an array reference,
217 # not a singulare plotType:
218 $self->{plotTypes} = [$self->{plotTypes}]
219 if (exists $self->{plotTypes} and ref($self->{plotTypes}) ne 'ARRAY');
220
221 # Initialize (and validate) the dataSet
222 $self->init;
223
224 # Make sure that the plotTypes know which dataSet they belong to:
225 for my $plotType (@{$self->{plotTypes}}) {
226 $plotType->dataset($self);
227 }
228
229 return $self;
230 }
231  
232  
233 =item check_plot_types
234  
235 Checks that the plotType(s) passed to the constructor or added at runtime are
236 built on the data type tha we expect. Derived classes must specify their
237 C<plotType_base_class> key before calling this function.
238  
239 =cut
240  
241 sub check_plot_types {
242 my ($self, @plotTypes) = @_;
243 my $expected_plot_class = $self->expected_plot_class;
244 foreach (@plotTypes) {
245 croak("Plottype should be of type $expected_plot_class, but it is of type "
246 . ref($_)) unless eval{$_->isa($expected_plot_class)}
247 or eval{$_->isa('PDL::Graphics::Prima::PlotType::CallBack')}
248 and eval{$_->{base_class}->isa($expected_plot_class)};
249 }
250 }
251  
252 =item init
253  
254 Called by new to initialize the dataset. This function is called on the new
255 dataset just before it is returned from C<new>.
256  
257 If you create a new dataSet, you should provide an C<init> function that
258 performs the following:
259  
260 =over
261  
262 =item supply a default plotType
263  
264 If the user supplied something to either the C<plotType> or C<plotTypes> keys,
265 then C<new> will be sure you have you will already have that something in
266 an array reference in C<< $self->{plotTypes} >>. However, if they did not supply
267 either key, you should supply a default. You should have something that looks
268 like this:
269  
270 $self->{plotTypes} = [pset::CDF] unless exists $self->{plotTypes};
271  
272 =item check the plot types
273  
274 After supplying a default plot type, you should check that the provided plot
275 types are derived from the acceptable base plot type class. You would do this
276 with code like this:
277  
278 $self->check_plot_types(@{self->{plotTypes}});
279  
280 =back
281  
282 This is your last step to validate or pre-calculate anything. For example, you
283 must provide functions to return your data, and you should probably make
284 guarantees about the kinds of data that such accessors return, such as the data
285 always being a piddle. If that is the case, then it might not be a bad idea to
286 say in your C<init> function something like this:
287  
288 $self->{data} = PDL::Core::topdl($self->{data});
289  
290 =cut
291  
292 sub init {
293 my $self = shift;
294 die "The class for $self does not define an init function!";
295 }
296  
297 =item change_data
298  
299 Sets the data to the given data by calling the derived class's C<_change_data>
300 method. Unlike C<_change_data>, this method also issues a C<ChangeData>
301 notification to the widget. This means that you should only use this method
302 once the dataset has been associated with a widget. Each class expects
303 different arguments, so you should look at the class's documentation for
304 details on what to send to the method.
305  
306 =cut
307  
308 # Sets the data and issues a notification
309 sub change_data {
310 my $self = shift;
311 $self->_change_data(@_);
312 $self->widget->notify('ChangeData', $self);
313 }
314  
315 =back
316  
317 =cut
318  
319 ###############################################################################
320 # Pair #
321 ###############################################################################
322  
323 package PDL::Graphics::Prima::DataSet::Pair;
324 use base 'PDL::Graphics::Prima::DataSet';
325 use Carp 'croak';
326  
327 =head2 Pair
328  
329 Pairwise datasets are collections of paired x/y data. A typical Pair dataset
330 is the sort of thing you would visualize with an x/y plot: a time series
331 such as the series of high temperatures for each day in a month or the x- and
332 y-coordinates of a bug walking across your desk. PDL::Graphics::Prima provides
333 many ways of visualizing Pair datasets, as discussed under
334 L<PDL::Graphics::Prima::PlotType/Pair>.
335  
336 The dimensions of pluralized properties (i.e. C<colors>) should
337 thread-match the dimensions of the data. An important exception to this is
338 C<ppair::Lines>, in which case you must specify how you want properties to thread.
339  
340 The default plot type is C<ppair::Diamonds>.
341  
342 =over
343  
344 =item ds::Pair - short-name constructor
345  
346 =for sig
347  
348 ds::Pair($x_data, $y_data, option => value, ...)
349  
350 The short-name constructor to create pairwise datasets. The x- and y-data
351 can be either piddles or array references (which will be converted to a
352 piddle during initialization).
353  
354 =cut
355  
356 sub ds::Pair {
357 croak('ds::Pair expects x- and y-data and then key => value pairs, but you'
358 . ' supplied an odd number of arguments') if @_ % 2 == 1;
359 my ($x_data, $y_data) = (shift, shift);
360 return PDL::Graphics::Prima::DataSet::Pair->new(@_
361 , x => $x_data, y => $y_data);
362 }
363  
364 =item expected_plot_class
365  
366 Pair datasets expect plot type objects that are derived from
367 C<PDL::Graphics::Prima::PlotType::Pair>.
368  
369 =cut
370  
371 sub expected_plot_class {'PDL::Graphics::Prima::PlotType::Pair'}
372  
373 # Standard initialization, and ensures that the data are piddles.
374 sub init {
375 my $self = shift;
376
377 # Supply a default plot type:
378 $self->{plotTypes} = [ppair::Diamonds(filled => 1)]
379 unless exists $self->{plotTypes};
380
381 # Check that the plotTypes are valid:
382 $self->check_plot_types(@{$self->{plotTypes}});
383
384 # Set the data
385 $self->_change_data($self->{x}, $self->{y});
386 }
387  
388 =item get_xs, get_ys, get_data
389  
390 Returns piddles with the x, y, or x-y data. The last function returns two
391 piddles in a list.
392  
393 =cut
394  
395 sub get_xs { $_[0]->{x} }
396 sub get_ys { $_[0]->{y} }
397 # This is really a convenience function that wraps the other two. However,
398 # it really wraps them, so that to override the behavior you simply need to
399 # override get_xs and get_ys.
400 sub get_data {
401 my $self = shift;
402 return ($self->get_xs, $self->get_ys);
403 }
404  
405 =item get_data_as_pixels
406  
407 Uses the reals_to_pixels functions for the x- and y- axes to convert the
408 values of the x- and y- data to actual pixel positions in the widget.
409  
410 =cut
411  
412 sub get_data_as_pixels {
413 my ($dataset, $ratio) = @_;
414 my $widget = $dataset->widget;
415
416 my ($xs, $ys) = $dataset->get_data;
417 return ($widget->x->reals_to_pixels($xs, $ratio), $widget->y->reals_to_pixels($ys, $ratio));
418 }
419  
420 =item change_data
421  
422 Changes the data to the piddles passed in. For example,
423  
424 $scatter_plot->dataSets->{'data'}->change_data($xs, $ys);
425  
426 =cut
427  
428 sub _change_data {
429 my ($self, $x, $y) = @_;
430
431 # Ensure the data are piddles:
432 eval {
433 $self->{x} = PDL::Core::topdl($x);
434 $self->{y} = PDL::Core::topdl($y);
435 1;
436 } or croak('For pairwise datasets, the x- and y-data must be piddles '
437 . 'or scalars that pdl() knows how to process');
438 }
439  
440 =back
441  
442 =cut
443  
444 ################################################################################
445 # Dist #
446 ################################################################################
447  
448 package PDL::Graphics::Prima::DataSet::Dist;
449 use base 'PDL::Graphics::Prima::DataSet::Pair';
450 use Carp;
451  
452  
453 #NOTE: I WOULD LIKE TO MAKE THE TRUNCATION BEHAVIOR MORE SPECIFIABLE WITH
454 #FLAGS SUCH AS trunc::LeftDrop | trunc::RightExtraBin. I WOULD ALSO LIKE TO
455 #INCLUDE norm::Integral, norm::ByWidth, norm::ByCount, OR MAYBE
456 #norm::ToOne, norm::ToN, norm::ByWidth, norm::NotByWidth, SOMETHING LIKE THAT.
457  
458 =head2 Distribution
459  
460 Distributions are unordered collections of sample data. The typical use case
461 of a distribution is that you have a population of things and you want to
462 analyze their agregate properties. For example, you might be interested in
463 the distribution of tree heights at your Christmas Tree Farm, or the
464 distribution of your students' (or your classmates') test scores from the
465 mid-term. Common ways for visualizing distributions are to plot their
466 cumulative distribution functions or their histogram, but those are actually
467 classic pairwise data visualization approaches. That means that what we really
468 need are means for converting unordered sets of data into pairwise data.
469 Distributions, therefore, let you specify the means by which your unordered
470 data should be transformed into pairwise data, and the pairwise plot types to
471 visualize the resulting transformed data. In an object oriented sense, the
472 Distribution class is derived from the Pairwise class because a distribution
473 B<is visualized> using pairwise plot types.
474  
475 Note that shape of pluralized properties (i.e. C<colors>) should
476 thread-match the shape of the data B<excluding> the data's first dimension.
477 That is, if I want to plot the cumulative distributions for three different
478 batches using three different line colors, my data would have shape (N, 3) and
479 my colors piddle would have shape (3).
480  
481 PDL::Graphics::Prima's notion of distributions is not yet finalized and is
482 open to suggestion. If you find yourself using distribution plots regularly,
483 you should give me feedback on what works and what doesn't. Thanks!
484  
485 =over
486  
487 =item ds::Dist - short-name constructor
488  
489 =for sig
490  
491 ds::Dist($data, option => value, ...)
492  
493 The short-name constructor to create distribtions. The data can be either a
494 piddle of values or an array reference of values (which will be converted to
495 a piddle during initialization).
496  
497 =cut
498  
499 package
500 bt;
501  
502 use Carp;
503  
504 =pod
505  
506 In addition to the standard keys, there is also the C<binning> key. The
507 C<binning> key expects either a standard binning approach using one of the
508 pre-defined forms, or a subroutine reference that performs the binning
509 in a customized fashion. The binning types are all functions that expect
510 key/value pairs that include C<min> and C<max> for the lower and upper
511 threshold of the binning, C<drop_extremes> to indicate if the data outside
512 the min/max range should be included in the first and last bins, and
513 C<normalize> to indicate if the binning should be normalized to 1, for some
514 appropriate definition of normalization. Other keys may also be allowed.
515  
516 If you want to write a customized binning function, it should accept the
517 two arguments, the C<data> to bin and the C<distribution> object. It should
518 return a pair of piddles representing the x and y coordinates to plot. In
519 addition, if the binning routine knows how to calculate properties for
520 specific plot types, it can specify the plot type and any properties that it
521 would provide for that plot type.
522  
523 For example, if you write a binning routine that knows how to calculate
524 the bin boundaries for the Histogram plot type, your return statement could
525 look like this:
526  
527 return ($x, $y, Histogram => { binEdges => $bounds } );
528  
529 If your binning routine uses the number of points in a Symbols plot type to
530 represent something, it could specify those:
531  
532 return ($x, $y, Symbols => { N_points => $n_points } );
533  
534 If you have a means for calculating the error on your bins, you could
535 include the error bar data:
536  
537 return ($x, $y, ErrorBars => { y_err => $count_err } );
538  
539 These properties will be applied to the relevant plot types just before
540 drawing and autoscaling operations, and any dataset operation that makes
541 use of your supplied function should examine the additional parameters and
542 act accordingly.
543  
544 The standard binning types include:
545  
546 =over
547  
548 =item bt::CDF
549  
550 Generates a cumulative distribution from the data. The default C<min> is the
551 data's minimum, the default C<max> is the data's maximum, the binning will not
552 C<drop_extremes> by default (i.e. C<< drop_extremes => 0 >>) and the binning
553 normalizes the data (i.e. C<< normalize => 1 >>). You can also specify if you
554 want an increasing or decreasing representation by specifying a boolean value
555 for the C<increasing> key (the default is increasing, i.e. true).
556  
557 In the context of the CDF, normalization refers to the curve runnning from
558 y = 0 to y = N - 1 (not normalized) or from y = 0 to y = 1 (normalized).
559 Bear in mind that this interacts with your choice to drop the extremes or not.
560  
561 In producing the CDF, bad values are simply skipped.
562  
563 =cut
564  
565 sub get_min_max {
566 my ($data, $min, $max) = @_;
567
568 # Calculate min and/or max from the data
569 if (not defined $min and not defined $max) {
570 ($min, $max) = $data->minmaximum;
571 }
572 elsif (not defined $min) {
573 $min = $data->minimum;
574 }
575 elsif (not defined $max) {
576 $max = $data->maximum;
577 }
578 # Ensure supplied args are piddles
579 $min = PDL::Core::topdl($min);
580 $max = PDL::Core::topdl($max);
581
582 # Return pdl-threadable results
583 return $min->dummy(0), $max->dummy(0);
584 }
585  
586 sub CDF {
587 croak('bt::CDF expects key/value pairs but you supplied an odd number of arguments')
588 if @_ % 2 == 1;
589 my %opts = (drop_extremes => 0, normalize => 1, increasing => 1, @_);
590
591 return sub {
592 my ($data, $set_obj) = @_;
593
594 my ($min, $max) = get_min_max($data, $opts{min}, $opts{max});
595
596 # The normalization term (also used in increasing/decreasing) depends
597 # on whether we drop the extreme values or not. The handling for the
598 # extreme values amounts to picking which of the x-values are bad and
599 # where they fall in their list so that they line up nicely with the
600 # result of the xvals function used to define the ys.
601 my ($norm, $xs);
602 if ($opts{drop_extremes}) {
603 $xs = $data->setbadif(($data < $min) | ($data > $max))->qsort;
604 $norm = ($xs->ngoodover - 1)->dummy(0);
605 }
606 else {
607 $norm = ($data->ngoodover - 1)->dummy(0);
608 $xs = $data->qsort->setbadif(($xs < $min) | ($xs > $max));
609 }
610 my $ys = $data->xvals;
611
612 # alter the ys if they are supposed to decrease
613 $ys = $norm - $ys if not $opts{increasing};
614
615 # Normalize, carefully
616 if ($opts{normalize}) {
617 $norm->where($norm == 0) .= 1;
618 $ys /= $norm;
619 }
620
621 return ($xs, $ys);
622 };
623 }
624  
625 =item bt::Linear
626  
627 Generates a histogram from the data with linear spacing. The default C<min> is the
628 data's minimum, the default C<max> is the data's maximum, the binning will
629 C<drop_extremes> by default (i.e. C<< drop_extremes => 1 >>) and the binning
630 normalizes the data (i.e. C<< normalize => 1 >>). You can also specify the
631 number of bins with C<nbins>. The default is 20. If you want empty bins to
632 be marked as bad, specify C<< mark_empty_as => 'bad' >>. The default is to
633 mark them as zero.
634  
635 In this case, normalization means that the "integral" of the histogram is
636 1, which means that the sum of the heights I<times the widths> is 1.
637  
638 =cut
639  
640 # Takes the data, bounds, min,
641 sub bin_by_data {
642 my ($data, $bounds, $min, $max, $drop_extremes) = @_;
643
644 # Find the bin indices to increment. If the bad value flag is set, vsearch
645 # gives us an annoying warning; however, the bad value itself is very likely
646 # to be outside the min and max, so we will temporarily turn it off for the
647 # vsearch and restore it when we're done.
648 my $orig_bad_flag = $data->badflag;
649 $data->badflag(0);
650 my $idx = vsearch($data, $bounds);
651 $data->badflag($orig_bad_flag);
652
653 # Safety guard so indadd doesn't choke
654 my $is_within_bounds = ($min <= $data) & ($data <= $max);
655 $idx->where(!$is_within_bounds) .= 1;
656 # The actual minimum value will have idx 0, all others will be offest
657 # by 1, so adjust:
658 $idx->where($idx > 0)--;
659
660 # Allocate the memory for the output piddle
661 my @dims = $bounds->dims;
662 $dims[0]--;
663 my $counts = zeroes(@dims);
664
665 # Tabulate the contributions
666 indadd($is_within_bounds, $idx, $counts);
667
668 # if we are not dropping the extremes, then we are dumping them into the
669 # first and last bins:
670 if (not $drop_extremes) {
671 $counts->slice('0') += sum($data < $min);
672 $counts->slice('-1') += sum($data > $max);
673 }
674
675 return $counts;
676 }
677  
678 use PDL::NiceSlice;
679 use PDL;
680 sub Linear {
681 croak('bt::Linear expects key/value pairs but you supplied an odd number of arguments')
682 if @_ % 2 == 1;
683 my %opts = (drop_extremes => 1, normalize => 1, nbins => 20,
684 mark_empty_as => 0, @_);
685
686 return sub {
687 my ($data, $set_obj) = @_;
688 local *__ANNON__ = 'bt::Linear';
689
690 # Get the appropriate min/max
691 my ($min, $max) = get_min_max($data, $opts{min}, $opts{max});
692
693 # Edge conditions: min is the same as max
694 my $pos_min_eq_max = ($min == $max) & ($min > 0);
695 $min->where($pos_min_eq_max) /= 2;
696 $max->where($pos_min_eq_max) *= 1.5;
697 my $neg_min_eq_max = ($min == $max) & ($min < 0);
698 $min->where($neg_min_eq_max) *= 1.5;
699 $max->where($neg_min_eq_max) /= 2;
700 my $min_max_eq_zero = ($min == 0) & ($max == 0);
701 $min->where($min_max_eq_zero) .= -1;
702 $max->where($min_max_eq_zero) .= 1;
703
704 # Build the bounds
705 my @dims = $data->dims;
706 $dims[0] = $opts{nbins} + 1;
707 my $bounds = zeroes(@dims)->xlinvals($min, $max);
708
709 # Accumulate the counts
710 my $hist = bin_by_data($data => $bounds, $min, $max, $opts{drop_extremes});
711
712 # Mark empties as bad, if requested
713 $hist = $hist->setvaltobad(0)
714 if $opts{mark_empty_as} eq 'bad' and any $hist == 0;
715
716 if ($opts{normalize}) {
717 # Normalize by count
718 $hist /= $hist->sumover;
719 # normalize by bin width (same for all bins)
720 $hist /= ($bounds(1) - $bounds(0));
721 }
722
723 # Return the bin centers and the heights, along with the histogram
724 # bin boundaries.
725 return (($bounds(1:-1) + $bounds(0:-2))/2, $hist,
726 Histogram => { binEdges => $bounds }
727 );
728 };
729 }
730 no PDL::NiceSlice;
731  
732 =item bt::Log
733  
734 Generates a histogram from the data with logarithmic spacing. The default
735 C<min> is the data's smallest positive value and the default max is the data's
736 maximum value. If none of the data is positive, the binning type croaks.
737 The binning will C<drop_extremes> by default (i.e. C<< drop_extremes => 1 >>)
738 and the binning normalizes the data (i.e. C<< normalize => 1 >>). You can also
739 specify the number of bins with C<nbins>. The default is 20. If you want empty bins to
740 be marked as bad, specify C<< mark_empty_as => 'bad' >>. The default is to
741 mark them as zero.
742  
743 As with linear binning, normalization means that the "integral" of the histogram is
744 1, which means that the sum of the heights I<times the widths> is 1.
745  
746 =item bt::StrictLog
747  
748 Identical to L<bt::Log|/bt::Log>, except that it croaks if it encounters
749 B<any> negative values. You can use this in place of L<bt::Log|/bt::Log> to
750 sanity check your data.
751  
752 =back
753  
754 =cut
755  
756 sub Log {
757 croak('bt::Log expects key/value pairs but you supplied an odd number of arguments')
758 if @_ % 2 == 1;
759 my %opts = (drop_extremes => 1, normalize => 1, nbins => 20,
760 mark_empty_as => 0, @_);
761
762 return sub {
763 my ($data, $set_obj) = @_;
764 local *__ANNON__ = 'bt::Log';
765
766 # Loose check condition: only croak if *everything* is negative
767 my ($min, $max) = get_min_max($data->setbadif($data <= 0), $opts{min}, $opts{max});
768 croak('data, or its truncation, seems to only contain negative values')
769 if any $max->isbad;
770
771 return logarithmic_binning($data, $set_obj, $min, $max, \%opts);
772 };
773 }
774  
775 sub StrictLog {
776 croak('bt::StrictLog expects key/value pairs but you supplied an odd number of arguments')
777 if @_ % 2 == 1;
778 my %opts = (drop_extremes => 1, normalize => 1, nbins => 20,
779 mark_empty_as => 0, @_);
780
781 return sub {
782 my ($data, $set_obj) = @_;
783 local *__ANNON__ = 'bt::StrictLog';
784
785 # Strict check condition: croak if *any* data is negative
786 my ($min, $max) = get_min_max($data, $opts{min}, $opts{max});
787 croak('data, or its truncation, seems to only contain negative values')
788 if any ($min < 0) or any $min->isbad;
789
790 return logarithmic_binning($data, $set_obj, $min, $max, \%opts);
791 };
792 }
793  
794 use PDL::NiceSlice;
795 sub logarithmic_binning {
796 # By the time this gets called, all cleaning of the min and max should
797 # have happened, and they should both contain only strictly positive
798 # values.
799 my ($data, $set_obj, $min, $max, $opts) = @_;
800
801 # Edge conditions: min is the same as max (Note that they will be
802 # strictly larger than zero since all negative values were removed
803 # before being sent to get_min_max). In that case, the special case
804 # of 1 must be handled with care, but otherwise it's pretty easy.
805 # Note that the values are chosen so that the bin centers, calculated
806 # below, work out correctly.
807 my $min_eq_max_eq_1 = ($min == $max) & ($max == 1);
808 $min->where($min_eq_max_eq_1) .= 0.5;
809 $max->where($min_eq_max_eq_1) .= 2;
810 my $min_eq_max_lt_1 = ($min == $max) & ($max < 1);
811 $min->where($min_eq_max_lt_1) **= 1.5;
812 $max->where($min_eq_max_lt_1) **= 0.5;
813 my $min_eq_max_gt_1 = ($min == $max) & ($max > 1);
814 $min->where($min_eq_max_gt_1) **= 0.5;
815 $max->where($min_eq_max_gt_1) **= 1.5;
816
817 # Build the bounds
818 my @dims = $data->dims;
819 $dims[0] = $opts->{nbins} + 1;
820 my $bounds = zeroes(@dims)->xlogvals($min, $max);
821
822 # Accumulate the counts
823 my $hist = bin_by_data($data => $bounds, $min, $max, $opts->{drop_extremes});
824
825 # Mark empties as bad, if requested
826 $hist = $hist->setvaltobad(0) if $opts->{mark_empty_as} eq 'bad';
827  
828 if ($opts->{normalize}) {
829 # Normalize by count
830 $hist /= $hist->sumover;
831 # normalize by bin width
832 $hist /= ($bounds(1:) - $bounds(:-2));
833 }
834
835 # Return the bin centers and the heights, along with the histogram
836 # bin boundaries.
837 return (sqrt($bounds(1:-1) * $bounds(0:-2)), $hist,
838 Histogram => { binEdges => $bounds }
839 );
840 }
841 no PDL::NiceSlice;
842  
843 =item bt::NormFit
844  
845 "Fits" the distribution between the specified min and max (defaults to the
846 data's min and max) to a normal distribution. This bin type does not pay
847 attention to the C<drop_extremes> key, but it cares about the C<normalize>
848 key. If unspecified (the default), the curve will be scaled so that the area
849 underneath it is the number of data points being fit. If normalized, the
850 curve will be scaled so that the area under the curve will be 1. You can
851 also specify the number of points to use in generating the curves by including
852 the C<N_points> key/value pair.
853  
854 I am pondering allowing the curve's min/max to take the current axis bounds
855 min/max if the axes are not autoscaling. Thoughts appreciated.
856  
857 =cut
858  
859 sub NormFit {
860 croak('bt::NormFit expects key/value pairs but you supplied an odd number of arguments')
861 if @_ % 2 == 1;
862 my %opts = (normalize => 1, nbins => 20, N_points => 200, @_);
863
864 return sub {
865 my ($data, $set_obj) = @_;
866 local *__ANNON__ = 'bt::NormFit';
867
868 my ($min, $max) = get_min_max($data, $opts{min}, $opts{max});
869 my $data_to_analyze = $data->setbadif(($data < $min) | ($data > $max));
870 my ($means, $stdevs) = $data_to_analyze->dummy(1, 1)->statsover;
871
872 my @dims = $data->dims;
873 $dims[0] = $opts{N_points};
874 my $xs = zeroes(@dims)->xlinvals($min, $max);
875 use PDL::Constants qw(PI);
876 my $ys = exp(-($xs - $means)**2 / 2 / $stdevs**2)
877 / sqrt(2 * PI) / $stdevs;
878 $ys *= $data_to_analyze->ngoodover->dummy(0)
879 if not $opts{normalize};
880
881 return ($xs, $ys);
882 };
883 }
884  
885 package PDL::Graphics::Prima::DataSet::Dist;
886 our @ISA = qw(PDL::Graphics::Prima::DataSet::Pair);
887  
888 sub ds::Dist {
889 croak('ds::Dist expects data and then key => value pairs, but you supplied'
890 . ' an even number of arguments') if @_ % 2 == 0;
891 my $data = shift;
892 return PDL::Graphics::Prima::DataSet::Dist->new(@_, data => $data);
893 }
894  
895 # Standard initialization, and ensures that the data is a piddle.
896 sub init {
897 my $self = shift;
898
899 # Supply a default plot type:
900 $self->{plotTypes} = [ppair::Histogram()] unless exists $self->{plotTypes};
901
902 # Check that the plotTypes are valid:
903 $self->check_plot_types(@{$self->{plotTypes}});
904
905 # Make sure we have a binning type
906 $self->{binning} = bt::Linear() unless exists $self->{binning};
907
908 # Set the data (without notifications)
909 $self->_change_data($self->{data});
910 }
911  
912 =item get_data, get_xs, get_ys
913  
914 Returns the binned data, just the x-values, or just the y-values. For all of
915 these, the binning function is applied to the current dataset. However, for
916 the x- or y-getters, the other piece of data is discarded.
917  
918 =cut
919  
920 sub get_data {
921 my $self = shift;
922 # Send the cached values if they exist
923 return ($self->{x}, $self->{y}) if exists $self->{x};
924 # Otherwise pull them from the binning function
925 my ($xs, $ys) = $self->{binning}->($self->{data}, $self);
926 return ($xs, $ys);
927 }
928  
929 sub get_xs {
930 my $self = shift;
931 return $self->{x} if exists $self->{x};
932 my ($xs) = $self->get_data;
933 return $xs;
934 }
935  
936 sub get_ys {
937 my $self = shift;
938 return $self->{y} if exists $self->{y};
939 my (undef, $ys) = $self->get_data;
940 return $ys;
941 }
942  
943 use Scalar::Util qw(blessed);
944  
945 # prep_plotTypes
946 # A function to be called on $self with a collection of
947 # plotType => {
948 # key => value,
949 # key => value,
950 # ....
951 # }
952 # to be set.
953 sub prep_plotTypes {
954 my ($self, %args) = @_;
955
956 # Run through all the plot types and apply any setters from the binning
957 for my $pt (@{$self->{plotTypes}}) {
958 my $type = blessed($pt);
959 if (exists $args{$type}) {
960 # We have some tweaks for this plot type. For now, just hack it
961 # by reaching into the plot type's internal storage. This needs
962 # to be done better. :-( working here
963 #$pt->set(%{$args{$type}});
964 while (my ($k, $v) = each %{$args{$type}}) {
965 $pt->{$k} = $v;
966 }
967 }
968 }
969 }
970  
971 sub draw {
972 my ($self, $canvas, $ratio) = @_;
973
974 # Calculate and cache the x/y values; apply the plot type modifications
975 my ($x, $y, %mods) = $self->{binning}->($self->{data}, $self);
976 $self->{x} = $x;
977 $self->{y} = $y;
978 $self->prep_plotTypes(%mods);
979
980 # Draw it!
981 $self->SUPER::draw($canvas, $ratio);
982
983 # Remove the cacehd x/y values
984 delete $self->{x};
985 delete $self->{y};
986 }
987  
988 sub compute_collated_min_max_for {
989 my ($self, $axis_name, $pixel_extent) = @_;
990
991 # Calculate and cache the x/y values; apply the plot type modifications
992 my ($x, $y, %mods) = $self->{binning}->($self->{data}, $self);
993 $self->{x} = $x;
994 $self->{y} = $y;
995 $self->prep_plotTypes(%mods);
996
997 # Call the parent method
998 my ($collated_min, $collated_max)
999 = $self->SUPER::compute_collated_min_max_for($axis_name, $pixel_extent);
1000
1001 # Remove the cacehd x/y values
1002 delete $self->{x};
1003 delete $self->{y};
1004
1005 # Return the collation results
1006 return ($collated_min, $collated_max);
1007 }
1008  
1009 =back
1010  
1011 =cut
1012  
1013 ################################################################################
1014 # Grid #
1015 ################################################################################
1016  
1017 package PDL::Graphics::Prima::DataSet::Grid;
1018 use base 'PDL::Graphics::Prima::DataSet';
1019 use Carp 'croak';
1020 use PDL;
1021  
1022 =head2 Grid
1023  
1024 Grids are collections of data that is regularly ordered in two dimensions. Put
1025 differently, it is a structure in which the data is described by two indices.
1026 The analogous mathematical structure is a matrix and the analogous visual is an
1027 image. PDL::Graphics::Prima provides a few ways to visualize grids, as
1028 discussed under L<PDL::Graphics::Prima::PlotType/Grids>. The default plot type
1029 is C<pgrid::Color>.
1030  
1031 This is the least well thought-out dataSet. As such, it may change in the
1032 future. All such changes will, hopefully, be backwards compatible.
1033  
1034 At the moment, there is only one way to visualize grid data: C<pseq::Matrix>.
1035 Although I can conceive of a contour plot, it has yet to be implemented. As
1036 such, it is hard to specify the dimension requirements for dataset-wide
1037 properties. There are a few dataset-wide properties discussed in the
1038 constructor, however, so see them for some examples.
1039  
1040 =over
1041  
1042 =item ds::Grid - short-name constructor
1043  
1044 =for sig
1045  
1046 ds::Grid($matrix, option => value, ...)
1047  
1048 The short-name constructor to create grids. The data should be a piddle of
1049 values or something which topdl can convert to a piddle (an array reference of
1050 array references).
1051  
1052 The current cross-plot-type options include the bounds settings. You can either
1053 specify a C<bounds> key or one key from each column:
1054  
1055 x_bounds y_bounds
1056 x_centers y_centers
1057 x_edges y_edges
1058  
1059 =over
1060  
1061 =item bounds
1062  
1063 The value associated with the C<bounds> key is a four-element anonymous array:
1064  
1065 bounds => [$left, $bottom, $right, $top]
1066  
1067 The values can either be scalars or piddles that indicate the corners of the
1068 grid plotting area. If the latter, it is possible to thread over the bounds by
1069 having the shape of (say) C<$left> thread-match the shape of your grid's data,
1070 excluding the first two dimensions. That is, if your C<$matrix> has
1071 a shape of (20, 30, 4, 5), the piddle for C<$left> can have shapes of (1), (4),
1072 (4, 1), (1, 5), or (4, 5).
1073  
1074 At the moment, if you specify bounds, linear spacing from the min to the max is
1075 used. In the future, a new key may be introduced to allow you to specify the
1076 spacing as something besides linear.
1077  
1078 =item x_bounds, y_bounds
1079  
1080 The values associated with C<x_bounds> and C<y_bounds> are anonymous arrays with
1081 two elements containing the same sorts of data as the C<bounds> array.
1082  
1083 =item x_centers, y_centers
1084  
1085 The value associated with C<x_centers> (or C<y_centers>) should be a piddle with
1086 increasing values of x (or y) that give the mid-points of the data. For example,
1087 if we have a matrix with shape (3, 4), C<x_centers> would have 3 elements and
1088 C<y_centers> would have 4 elements:
1089  
1090 -------------------
1091 y3 | d03 | d13 | d23 |
1092 -------------------
1093 y2 | d02 | d12 | d22 |
1094 -------------------
1095 y1 | d01 | d11 | d21 |
1096 -------------------
1097 y0 | d00 | d10 | d20 |
1098 -------------------
1099 x0 x1 x2
1100  
1101 Some plot types may require the edges. In that case, if there is more than one
1102 point, the plot guesses the scaling of the spacing between points (choosing
1103 between logarithmic or linear) and appropriate bounds for the given scaling are
1104 calculated using interpolation and extrapolation. The plot will croak if there
1105 is only one point (in which case interpolation is not possible). If the spacing
1106 for your grid is neither linear nor logarithmic, you should explicitly specify
1107 the edges, as discussed next.
1108  
1109 At the moment, the guess work assumes that all the scalings for a given Grid
1110 dataset are either linear or logarithmic, even though it's possible to mix
1111 the scaling using threading. (It's hard to do that by accident, so if that last
1112 bit seems confusing, then you probably don't need to worry about tripping on
1113 it.) Also, I would like for the plot to croak if the scaling does not appear to
1114 be either linear or logarithmic, but that is not yet implemented.
1115  
1116 =item x_edges, y_edges
1117  
1118 The value associated with C<x_edges> (or C<y_edges>) should be a piddle with
1119 increasing values of x (or y) that give the boundary edges of data. For example,
1120 if we have a matrix with shape (3, 4), C<x_edges> would have 3 + 1 = 4 elements
1121 and C<y_edges> would have 4 + 1 = 5 elements:
1122  
1123 y4 -------------------
1124 | d03 | d13 | d23 |
1125 y3 -------------------
1126 | d02 | d12 | d22 |
1127 y2 -------------------
1128 | d01 | d11 | d21 |
1129 y1 -------------------
1130 | d00 | d10 | d20 |
1131 y0 -------------------
1132 x0 x1 x2 x3
1133  
1134 Some plot types may require the data centers. In that case, if there are only
1135 two edges, a linear interpolation is used. If there are more than two points,
1136 the plot will try to guess the spacing, choosing between linear and logarithmic,
1137 and use the appropriate interpolation.
1138  
1139 The note above about regarding guess work for x_centers and y_centers applies
1140 here, also.
1141  
1142 =back
1143  
1144 =cut
1145  
1146 sub ds::Grid {
1147 croak('ds::Grid expects data and then key => value pairs, but you'
1148 . ' supplied an even number of arguments') if @_ % 2 == 0;
1149 my $data = shift;
1150 return PDL::Graphics::Prima::DataSet::Grid->new(@_, data => $data);
1151 }
1152  
1153 =item expected_plot_class
1154  
1155 Grids expect plot type objects that are derived from
1156 C<PDL::Graphics::Prima::PlotType::Grid>.
1157  
1158 =cut
1159  
1160 sub expected_plot_class {'PDL::Graphics::Prima::PlotType::Grid'}
1161 sub default_plot_type { pgrid::Matrix() }
1162  
1163 # Usual initialization, ensure that the data is a piddle, and ensure that we
1164 # have enough information for the bounds.
1165 sub init {
1166 my $self = shift;
1167
1168 # Supply a default plot type:
1169 $self->{plotTypes} = [$self->default_plot_type]
1170 unless exists $self->{plotTypes};
1171
1172 # Check that the plotTypes are valid:
1173 $self->check_plot_types(@{$self->{plotTypes}});
1174
1175 # Set the data and the bounders
1176 $self->_change_data($self->{data});
1177
1178 # Make sure that we have bounds, or some combination of x_bounds, y_centers,
1179 # etc
1180 my @bounders = grep {
1181 /([xy]_)?bounds/
1182 or /[xy]_(centers|edges)/
1183 } keys %$self;
1184
1185 # Nothing can be combined with 'bounds':
1186 croak("Cannot combine simple 'bounds' with more specific bounders")
1187 if @bounders > 1 and grep {$_ eq 'bounds'} @bounders;
1188
1189 # Handle simple bounds
1190 if (@bounders == 1) {
1191 croak("Must specify bounds or a combination of other bounders")
1192 unless $bounders[0] eq 'bounds';
1193
1194 $self->{x_bounds} = [$self->{bounds}->[0], $self->{bounds}->[2]];
1195 $self->{y_bounds} = [$self->{bounds}->[1], $self->{bounds}->[3]];
1196
1197 delete $self->{bounds};
1198 }
1199 else {
1200 # make sure they specified bounds pairs:
1201 croak('Must specify one x and one y bounder')
1202 unless 1 == grep {/^x/} @bounders and 1 == grep {/^y/} @bounders;
1203 }
1204  
1205 # Handle the x-bounds
1206 if (grep {/^x_edges$/} @bounders) {
1207 $self->compute_centers('x');
1208 }
1209 elsif (grep {/^x_centers$/} @bounders) {
1210 $self->compute_edges('x');
1211 }
1212 elsif (grep {/^(x_)?bounds$/} @bounders) {
1213 my $x_edges = zeroes($self->get_data->dim(0) + 1)
1214 ->xlinvals(@{$self->{x_bounds}});
1215 $self->edges('x', $x_edges);
1216 }
1217 # Handle the y-bounds
1218 if (grep {/^y_edges$/} @bounders) {
1219 $self->compute_centers('y');
1220 }
1221 elsif (grep {/^y_centers$/} @bounders) {
1222 $self->compute_edges('y');
1223 }
1224 elsif (grep {/^(y_)?bounds$/} @bounders) {
1225 my $y_edges = zeroes($self->get_data->dim(1) + 1)
1226 ->xlinvals(@{$self->{y_bounds}});
1227 $self->edges('y', $y_edges);
1228 }
1229 }
1230  
1231  
1232 # Getter and setter
1233 # Call like $x_edges = $dataset->edges('x');
1234 # or $dataset->edges(x => $new_edges);
1235 sub edges {
1236 my ($self, $axis) = (shift, shift);
1237
1238 # Called as a setter
1239 if (@_) {
1240 $self->{$axis . '_edges'} = PDL::Core::topdl($_[0]);
1241 $self->compute_centers($axis);
1242 return;
1243 }
1244
1245 # Called as a getter:
1246 return $self->{$axis . '_edges'};
1247 }
1248  
1249 # Getter and setter (see above for calling example)
1250 sub centers {
1251 my ($self, $axis) = (shift, shift);
1252
1253 # Called as a setter
1254 if (@_) {
1255 $self->{$axis . '_centers'} = PDL::Core::topdl($_[0]);
1256 $self->compute_edges($axis);
1257 return;
1258 }
1259
1260 # Called as a getter:
1261 return $self->{$axis . '_centers'};
1262 }
1263  
1264 use PDL::NiceSlice;
1265  
1266 sub compute_centers {
1267 my ($self, $axis) = @_;
1268 my $data = $self->{$axis . '_edges'};
1269
1270 my ($type, $spacing) = $self->guess_scaling_for($data);
1271 my $results;
1272 if ($type eq 'linear') {
1273 $results = $data(0:-2) + $spacing / 2;
1274 }
1275 elsif ($type eq 'log') {
1276 $results = $data(0:-2) * sqrt($spacing);
1277 }
1278 else {
1279 croak ("Unknown scaling type $type; I only know about linear and log scaling");
1280 }
1281
1282 $self->{$axis . '_centers'} = $results;
1283 }
1284  
1285 sub compute_edges {
1286 my ($self, $axis) = @_;
1287 my $data = $self->{$axis . '_centers'};
1288
1289 my ($type, $spacing) = $self->guess_scaling_for($data);
1290 my @dims = $data->dims;
1291 $dims[0]++;
1292 my $results = zeroes($data->type, @dims);
1293 if ($type eq 'linear') {
1294 $results(0:-2) .= $data - $spacing / 2;
1295 $results(-1) .= $data(-1) + $spacing / 2;
1296 }
1297 elsif ($type eq 'log') {
1298 $results(0:-2) .= $data / sqrt($spacing);
1299 $results(-1) .= $data(-1) * sqrt($spacing);
1300 }
1301 else {
1302 croak ("Unknown scaling type $type; I only know about linear and log scaling");
1303 }
1304
1305 $self->{$axis . '_edges'} = $results;
1306 }
1307  
1308 =item get_data
1309  
1310 Returns the piddle containing the data.
1311  
1312  
1313  
1314 =cut
1315  
1316 sub get_data { return $_[0]->{data} }
1317  
1318 =item change_data
1319  
1320 Changes the data to the piddle passed in. For example,
1321  
1322 $map_plot->dataSets->{'intensity'}->change_data($new_intensity);
1323  
1324 =cut
1325  
1326 sub _change_data {
1327 my ($self, $data) = @_;
1328
1329 # Ensure the data is a piddle:
1330 eval {
1331 $self->{data} = PDL::Core::topdl($data);
1332 1;
1333 } or croak('For Grid datasets, the data must be piddles '
1334 . 'or scalars that pdl() knows how to process');
1335 }
1336  
1337  
1338  
1339 =item guess_scaling_for
1340  
1341 Takes a piddle and tries to guess the scaling from the spacing. Returns a string
1342 indicating the scaling, either "linear" or "log", as well as the spacing term.
1343  
1344 working here - clarify that last bit with an example
1345  
1346 =cut
1347  
1348 # my $data = exists $self->{"$axis-edges"} ? $self->{"$axis-edges"}
1349 # : exists $self->{"$axis-centers"} ? $self->{"$axis-edges"}
1350 # : die "Huh?";
1351  
1352 sub guess_scaling_for {
1353 my ($self, $data) = @_;
1354
1355 Carp::confess("data is not defined") if not defined $data;
1356
1357 # One point is not allowed:
1358 croak("Cannot determine scaling with only one point!")
1359 if $data->dim(0) == 1;
1360
1361 # Assume linear if there are only two points of data:
1362 return ('linear', $data(1) - $data(0)) if $data->dim(0) == 2;
1363
1364 # Now we can really say something about linear vs logarithmic scaling:
1365 my $lin_spaces = $data(1:-1) - $data(0:-2);
1366 my $lin_space = $lin_spaces->average;
1367 my $lin_score = (($lin_spaces - $lin_space)**2)->sum / $lin_spaces->nelem;
1368
1369 my $log_spaces = $data(1:-1) / $data(0:-2);
1370 my $log_space = $log_spaces->average;
1371 my $log_score = (($log_spaces - $log_space)**2)->sum / $log_spaces->nelem;
1372
1373 return ('linear', $lin_space) if $lin_score < $log_score;
1374 return ('log', $log_space);
1375 }
1376  
1377 =back
1378  
1379 =cut
1380  
1381  
1382 #############################################################################
1383 # Image #
1384 #############################################################################
1385  
1386 package PDL::Graphics::Prima::DataSet::Image;
1387 use base 'PDL::Graphics::Prima::DataSet::Grid';
1388 use Carp 'croak';
1389  
1390 =head2 Image
1391  
1392 Images are like Grids (they are derived from Grids, actually) but they have
1393 a specified color format. Since they have a color format, this means that
1394 they need to hold information for different aspects of each color, so they
1395 typically have one more dimension than Grids. That is, where a grid might
1396 have dimensions M x N, an rgb or hsv image would have dimensions 3 x M x N.
1397  
1398 The default image format is rgb. Currently supported image formats are
1399 rgb (red-green-blue), hsv (hugh-saturation-value), and prima (Prima's internal
1400 color format, which is a packed form of rgb).
1401  
1402 As Images are derived from Grids, any method you can call on a Grid you can
1403 also call on an Image. Differences and details specific to Images include:
1404  
1405 =over
1406  
1407 =item ds::Image - short-name constructor
1408  
1409 =for sig
1410  
1411 ds::Image($image, option => value, ...)
1412  
1413 Creates an Image dataset. A particularly important key is the C<color_format>
1414 key, which indicates the format of the C<$image> piddle. When it comes to
1415 drawing the image, the data will be converted to a set of Prima colors,
1416 which means that the first dimension will be reduced away. Values associated
1417 with keys should be thread-compatible with the dimensions starting from the
1418 second dimension, so if your image has dims 3 x M x N, values associated
1419 with your various keys should be thread-compatible with an M x N piddle.
1420  
1421 Note that color formats are case insensitive. At the moment there is no way
1422 to add new color formats, but you should expect a color format API to come
1423 at some point in the not-distant future. It will very likely make use of
1424 L<PDL::Graphics::ColorSpace>, so if you want your own special color format
1425 to be used for Images, you should contribute to that project.
1426  
1427 =cut
1428  
1429 sub ds::Image {
1430 croak('ds::Image expects data and then key => value pairs, but you'
1431 . ' supplied an even number of arguments') if @_ % 2 == 0;
1432 my $data = shift;
1433 return PDL::Graphics::Prima::DataSet::Image->new(@_, data => $data);
1434 }
1435  
1436  
1437 # A color conversion lookup table. This converts any of the specified
1438 # formats into a Prima color piddle. At some point this needs to be
1439 # extracted into something more general.
1440 my %color_convert_func_for = (
1441 prima => sub { return $_[0]->mv(-1,0)->clump(2) },
1442 rgb => sub { return $_[0]->mv(-1,0)->rgb_to_color },
1443 hsv => sub { return $_[0]->mv(-1,0)->hsv_to_rgb->rgb_to_color },
1444 );
1445  
1446 sub expected_plot_class {'PDL::Graphics::Prima::PlotType::Image'}
1447 sub default_plot_type { pimage::Basic() }
1448  
1449 =item change_data
1450  
1451 Sets the image to the new image data. Expects a piddle with the new data
1452 and an optional format specification. If no specification is given, the
1453 current format is used.
1454  
1455 =cut
1456  
1457 sub _change_data {
1458 my ($self, $image, $format) = @_;
1459 $format = $self->{color_format} unless defined $format;
1460
1461 $format = lc $format;
1462 # Make sure a valid color format is given:
1463 croak("'$format' is not a known color format")
1464 unless exists $color_convert_func_for{$format};
1465 $self->{color_format} = $format;
1466
1467 # Ensure the data is a piddle:
1468 eval {
1469 $self->{data} = PDL::Core::topdl($image);
1470 1;
1471 } or croak('For Image datasets, the data must be piddles '
1472 . 'or scalars that pdl() knows how to process');
1473
1474 # Move the color dims to the back so Grid operations work without
1475 # modifiction. Note that PrimaColors is a special case that does not need
1476 # a first dimension in the way that the other formats do. To make it work
1477 # just like the other formats, add a dummy dimension of size 1 if no
1478 # first dimension exists.
1479 $self->{data} = $self->{data}->dummy(0)
1480 if $self->{color_format} and $self->{color_format} eq 'prima'
1481 and $self->{data}->dim(0) ne 1;
1482 $self->{data} = $self->{data}->mv(0,-1);
1483 }
1484  
1485 sub init {
1486 my $self = shift;
1487
1488 # Assume RGB if no color format is given:
1489 $self->{color_format} ||= 'rgb';
1490
1491 # Initialize the parent class:
1492 $self->SUPER::init;
1493 }
1494  
1495 # Converts the current data into a Prima color format.
1496 use PDL::Drawing::Prima::Utils;
1497 no PDL::NiceSlice;
1498 sub get_prima_color_data {
1499 my $self = shift;
1500 return $color_convert_func_for{$self->{color_format}}->($self->get_data);
1501 }
1502  
1503 ##############################################################################
1504 # Func #
1505 ##############################################################################
1506  
1507 =head2 Func
1508  
1509 PDL::Graphics::Prima provides a special pair dataset that takes a function
1510 reference instead of a set of data. The function should take a piddle of x-values
1511 as input and compute and return the y-values. You can specify the number of data
1512 points by supplying
1513  
1514 N_points => value
1515  
1516 in the list of key-value pairs that initialize the dataset. Most of the
1517 functionality is inherited from C<PDL::Graphics::Prima::DataSet::Pair>, but
1518 there are a few exceptions.
1519  
1520 =cut
1521  
1522 package PDL::Graphics::Prima::DataSet::Func;
1523 our @ISA = qw(PDL::Graphics::Prima::DataSet::Pair);
1524  
1525 use Carp 'croak';
1526  
1527 =over
1528  
1529 =item ds::Func - short-name constructor
1530  
1531 =for sig
1532  
1533 ds::Func($subroutine, option => value, ...)
1534  
1535 The short-name constructor to create function datasets. The subroutine must be
1536 a reference to a subroutine, or an anonymous sub. For example,
1537  
1538 =for example
1539  
1540 # Reference to a subroutine,
1541 # PDL's exponential function:
1542 ds::Func (\&PDL::exp)
1543
1544 # Using an anonymous subroutine:
1545 ds::Func ( sub {
1546 my $xs = shift;
1547 return $xs->exp;
1548 })
1549  
1550  
1551 =cut
1552  
1553 sub ds::Func {
1554 croak('ds::Func expects a function reference and then key => value pairs, but you'
1555 . ' supplied an even number of arguments') if @_ % 2 == 0;
1556 return PDL::Graphics::Prima::DataSet::Func->new(func => @_);
1557 }
1558  
1559 # Even less to do for this than for a normal dataset. Just verify the function,
1560 # store it in $self, and ensure we have a sensible value for N_points. Note
1561 # that there is no way to ensure that the supplied function takes a piddle;
1562 # we'll just have to take it on faith.
1563 sub init {
1564 my $self = shift;
1565
1566 # Supply a default plot type:
1567 $self->{plotTypes} = [ppair::Lines] unless exists $self->{plotTypes};
1568
1569 # Set the default number of data points (for evaluated data) to 200:
1570 $self->{N_points} ||= 200;
1571
1572 # Ensure that they provided *something* for the func key
1573 croak('You must supply a function under the "func" key')
1574 unless exists $self->{func};
1575
1576 # Set the function and number of points
1577 $self->_change_data($self->{func}, $self->{N_points});
1578 }
1579  
1580 =item change_data
1581  
1582 Sets the function and/or the number of points to evaluate. The basic usage
1583 looks like this:
1584  
1585 $plot->dataSets->{'curve'}->change_data(\&some_func, $N_points);
1586  
1587 Either of the arguments can be undefined if you want to change only the
1588 other. That means that you can change the function without changing the
1589 number of evaluation points like this:
1590  
1591 $plot->dataSets->{'curve'}->change_data(\&some_func);
1592  
1593 and you can change the number of evaluation points without changing the
1594 function like this:
1595  
1596 $plot->dataSets->{'curve'}->change_data(undef, $N_points);
1597  
1598 =cut
1599  
1600 sub _change_data {
1601 my ($self, $func_ref, $N_points) = @_;
1602
1603 if (defined $func_ref) {
1604 croak('Func datasets require a function reference, but what you '
1605 . 'supplied is not a function reference')
1606 unless ref($func_ref) and ref($func_ref) eq 'CODE';
1607
1608 $self->{func} = $func_ref;
1609 }
1610
1611 if (defined $N_points) {
1612 croak("N_points must be a positive number")
1613 unless $N_points =~ /^\d+$/ and $N_points > 0;
1614
1615 $self->{N_points} = $N_points;
1616 }
1617 }
1618  
1619 =item get_xs, get_ys
1620  
1621 These functions override the default Pair behavior by generating the x-data
1622 and using that to compute the y-data. The x-data is uniformly sampled
1623 according to the x-axis scaling.
1624  
1625 =cut
1626  
1627 sub get_xs {
1628 my ($self) = @_;
1629 my $x_axis = $self->widget->x;
1630
1631 # working here - implement caching as an option in $self, like this:
1632 #if ($self->{cacheData}) ...
1633 return $x_axis->{scaling}->sample_evenly($x_axis->minmax, $self->{N_points});
1634 }
1635 sub get_ys {
1636 my ($self) = @_;
1637 my $xs = $self->get_xs;
1638 return $self->{func}->($xs);
1639 }
1640  
1641 =item compute_collated_min_max_for
1642  
1643 This function is supposed to provide information for autoscaling. This is a
1644 sensible thing to do for the the y-values of functions, but it makes no
1645 situation with the x-values since these are taken from the x-axis min and
1646 max already.
1647  
1648 This could be smarter, methinks, so please give me your ideas if you have
1649 them. :-)
1650  
1651 =cut
1652  
1653 # Function-based datasets need to return a collection of bad values for x-axis
1654 # requirements.
1655 sub compute_collated_min_max_for {
1656 # Must get the collated min max for each plot type for this data:
1657 my ($self, $axis_name, $pixel_extent) = @_;
1658
1659 if ($axis_name eq 'x') {
1660 return (
1661 PDL->zeroes($pixel_extent+1)->setvaltobad(0),
1662 PDL->zeroes($pixel_extent+1)->setvaltobad(0),
1663 );
1664 }
1665
1666 # working here - this needs to be smarter, especially for the first round
1667 # when *nothing* is known about the axis limits.
1668
1669 my $widget = $self->{dataSets}->{widget};
1670
1671 my (@min_collection, @max_collection);
1672 foreach my $plotType (@{$self->{plotTypes}}) {
1673
1674 # Accumulate all the collated results
1675 my ($min, $max)
1676 = $plotType->compute_collated_min_max_for($axis_name, $pixel_extent);
1677 # The collated results are not required to be one dimensional.
1678 # As such, I need to reduce them. I do this by moving the dimension
1679 # with $pixel_extent entries to the back and then calling minimum
1680 # until I have only one dimension remaining.
1681 $min = $min->squeeze->mv(0,-1);
1682 $min = $min->minimum while($min->ndims > 1);
1683 $max = $max->squeeze->mv(0,-1);
1684 $max = $max->maximum while($max->ndims > 1);
1685 push @min_collection, $min;
1686 push @max_collection, $max;
1687 }
1688
1689 # Merge all the data:
1690 my $collated_min = PDL::cat(@min_collection)->mv(-1,0)->minimum;
1691 my $collated_max = PDL::cat(@max_collection)->mv(-1,0)->maximum;
1692
1693 return ($collated_min, $collated_max);
1694 }
1695  
1696 =back
1697  
1698 =cut
1699  
1700 =head2 Annotation
1701  
1702 PDL::Graphics::Prima provides a generic annotation dataset that is used for
1703 adding drawn or textual annotations to your plots.
1704  
1705 =cut
1706  
1707 ###############################################################################
1708 # Annotation #
1709 ###############################################################################
1710  
1711 package PDL::Graphics::Prima::DataSet::Annotation;
1712 our @ISA = qw(PDL::Graphics::Prima::DataSet);
1713  
1714 use Carp 'croak';
1715 use Scalar::Util qw(blessed);
1716  
1717 =over
1718  
1719 =item ds::Note - short-name constructor for annotations
1720  
1721 =for sig
1722  
1723 ds::Note(plotType, plotType, ..., drawing => option, drawing => option)
1724  
1725 The short-name constructor to create annotations. This expects a list of
1726 annotation plot types fullowed by a list of general drawing options, such as
1727 line width or color. For example,
1728  
1729 =for example
1730  
1731 ds::Note(
1732 pnote::Region(
1733 # args here
1734 ),
1735 pnote::Text('text',
1736 # args here
1737 ),
1738 ... more note objects ...
1739 # Dataset drawing options
1740 color => cl::LightRed,
1741 ...
1742 );
1743  
1744 Unlike other dataset short-form constructors, you do not need to specify the
1745 plotTypes key explicitly, though if you did it would do what you mean. That is,
1746 the previous example would give identical results as this:
1747  
1748 ds::Note(
1749 plotTypes => [
1750 pnote::Region(
1751 # args here
1752 ),
1753 pnote::Text('text',
1754 # args here
1755 ),
1756 ... more note objects ...
1757 ],
1758 # Dataset drawing options
1759 color => cl::LightRed,
1760 ...
1761 );
1762  
1763 The former is simply offered as a convenience for this more long-winded form.
1764  
1765 =cut
1766  
1767 sub ds::Note {
1768 # Pull all the note objects off the list
1769 my @notes;
1770 push (@notes, shift(@_))
1771 while (blessed($_[0]) and $_[0]->isa('PDL::Graphics::Prima::PlotType::Annotation'));
1772 croak("Non-note arguments must be key/value pairs") unless @_ % 2 == 0;
1773 return PDL::Graphics::Prima::DataSet::Annotation->new(plotTypes => \@notes, @_);
1774 }
1775  
1776 sub expected_plot_class {'PDL::Graphics::Prima::PlotType::Annotation'}
1777  
1778 sub init {
1779 my $self = shift;
1780
1781 # Check that the plotTypes are valid:
1782 $self->check_plot_types(@{$self->{plotTypes}});
1783 }
1784  
1785 sub change_data {
1786 carp("Annotations do not have data that can be changed; ignoring");
1787 }
1788  
1789 =back
1790  
1791 =cut
1792  
1793 #############################################################################
1794 # Dataset::Collection #
1795 #############################################################################
1796  
1797 =head1 DataSet::Collection
1798  
1799 The dataset collection is the thing that actually holds the datasets in the
1800 plot widget object. The Collection is a tied hash, so you access all of its
1801 data members as if they were hash elements. However, it does some
1802 double-checking for you behind the scenes to make sure that whenever you
1803 add a dataset to the Collection, that you added a real DataSet object and
1804 not some arbitrary thing.
1805  
1806 working here - this needs to be clarified
1807  
1808 =cut
1809  
1810 package PDL::Graphics::Prima::DataSet::Collection;
1811 # This package implements the tied array functionality needed for automatic
1812 # data validation for the array setting operations.
1813  
1814 use Tie::Hash;
1815 our @ISA = qw(Tie::StdHash);
1816  
1817 # Validate and convert the data, and set the graph's min/max values if they are
1818 # on auto mode.
1819 use Carp 'croak';
1820  
1821 sub TIEHASH {
1822 my ($class, $widget) = @_;
1823 my $self = {widget => $widget};
1824 return bless $self, $class;
1825 }
1826  
1827 # Override delete to prevent removing the widget key:
1828 sub DELETE {
1829 my ($this, $key) = @_;
1830 return if $key eq 'widget';
1831 $key =~ s/^-//; # strip any leading dash
1832 delete $this->{$key};
1833 $this->{widget}->notify('ChangeData');
1834 }
1835  
1836 # Clear the contents of the hash while preserving the widget:
1837 sub CLEAR {
1838 my ($this) = @_;
1839 %{$this} = (widget => $this->{widget});
1840 $this->{widget}->notify('ChangeData');
1841 }
1842  
1843 sub FETCH {
1844 my ($this, $key) = @_;
1845 $key =~ s/^-//; # strip any leading dash
1846 return $this->{$key};
1847 }
1848  
1849 sub STORE {
1850 my ($self, $name, $dataset) = @_;
1851 # Silently do nothing if they try to change the widget:
1852 return if $name eq 'widget';
1853
1854 # They must pass in a DataSet object:
1855 croak('You can only add dataSet objects to the collection of dataSets')
1856 unless eval {$dataset->isa('PDL::Graphics::Prima::DataSet')};
1857
1858 # strip any leading dash and store it
1859 $name =~ s/^-//;
1860 $self->{$name} = $dataset;
1861
1862 # Inform the dataset of its parent widget:
1863 $dataset->widget($self->{widget});
1864  
1865 # Call data initialization for all of the plot types:
1866 # working here - still do this? I think that histograms will want this,
1867 # maybe.
1868 # $dataset->initialize_plot_types;
1869
1870 # Recompute the auto min/max values:
1871 $self->{widget}->notify('ChangeData');
1872 }
1873  
1874  
1875  
1876  
1877 1;
1878  
1879 =head1 RESPONSIBILITIES
1880  
1881 The datasets and the dataset collection have a number of responsibilities, and
1882 a number of things for whch they are not responsible.
1883  
1884 The dataset container is responsible for:
1885  
1886 =over
1887  
1888 =item knowing the plot widget
1889  
1890 The container always maintains knowledge of the plot widget to which it belongs.
1891 Put a bit differently, a dataset container cannot belong to multiple plot
1892 widgets (at least, not at the moment).
1893  
1894 =item informing datasets of their container and plot widget
1895  
1896 When a dataset is added to a dataset collection, the collection is responsible
1897 for informing the dataset of the plot object and the dataset collection to which
1898 the dataset belongs.
1899  
1900 =back
1901  
1902 Datasets themselves are responsible for:
1903  
1904 =over
1905  
1906 =item knowing and managing the plotTypes
1907  
1908 The datasets are responsible for maintaining the list of plotTypes that are to
1909 be applied to their data.
1910  
1911 =item knowing per-dataset properties
1912  
1913 Drawing properties can be specified on a per-dataset scope. The dataset is
1914 responsible for maintaining a list of these properties and providing them to
1915 the plot types when they perform drawing operations.
1916  
1917 =item knowing the dataset container and the plot widget
1918  
1919 All datasets know the dataset container and the plot widget to which they belong.
1920 Although they could retrieve the widget through a method on the container, the
1921  
1922  
1923 =item informing plotTyes' plot widget
1924  
1925 The plot types all know the widget (and dataset) to which they belong, and it is
1926 the
1927  
1928 =item managing the drawing operations of plotTypes
1929  
1930 Although datasets themselves do not need to draw anything, they do call the
1931 drawing operations of the different plot types that they contain.
1932  
1933 =item knowing and supplying the data
1934  
1935 A key responsibility for the dataSets is holding the data that are drawn by the
1936 plot types. Althrough the plot types may hold specialized data, the dataset
1937 holds the actual data the underlies the plot types and provides a specific
1938 interface for the plot types to access that data.
1939  
1940 =back
1941  
1942 On the other hand, datasets are not responsible for knowing or doing any of the
1943 following:
1944  
1945 =over
1946  
1947 =item knowing axes
1948  
1949 The plot object is responsible for knowing the x- and y-axis objects. However,
1950 if the axis system is changed to allow for multiple x- and y-axes, then this
1951 burden will shift to the dataset as it will need to know which axis to use when
1952 performing data <-> pixel conversions.
1953  
1954 =back
1955  
1956 =head1 TODO
1957  
1958 Add optional bounds to function-based DataSets.
1959  
1960 Captitalization for plotType, etc.
1961  
1962 Use PDL documentation conventions for signatures, ref, etc.
1963  
1964 Additional datset, a two-tone grid. Imagine that you want to overlay the
1965 population density of a country and the average rainfall (at the granularity
1966 of counties, let's say). You could use the intensity of the red channel to
1967 indicate population and the intensity of blue to indicate rainfall. Highly
1968 populated areas with low rainfall would be bright red, while highly populated
1969 areas with high rainfall would be purple, and low populated areas with high
1970 rainfall would be blue. The color scale would be indicated
1971 with a square with a color gradient (rather than a horizontal or vertical bar
1972 with a color gradient, as in a normal ColorGrid). Anyway, this differs from
1973 a normal grid dataset because it would require two datasets, one for each
1974 tone.
1975  
1976 =head1 AUTHOR
1977  
1978 David Mertens (dcmertens.perl@gmail.com)
1979  
1980 =head1 ADDITIONAL MODULES
1981  
1982 Here is the full list of modules in this distribution:
1983  
1984 =over
1985  
1986 =item L<PDL::Graphics::Prima|PDL::Graphics::Prima/>
1987  
1988 Defines the Plot widget for use in Prima applications
1989  
1990 =item L<PDL::Graphics::Prima::Axis|PDL::Graphics::Prima::Axis/>
1991  
1992 Specifies the behavior of axes (but not the scaling)
1993  
1994 =item L<PDL::Graphics::Prima::DataSet|PDL::Graphics::Prima::DataSet/>
1995  
1996 Specifies the behavior of DataSets
1997  
1998 =item L<PDL::Graphics::Prima::Limits|PDL::Graphics::Prima::Limits/>
1999  
2000 Defines the lm:: namespace
2001  
2002 =item L<PDL::Graphics::Prima::Palette|PDL::Graphics::Prima::Palette/>
2003  
2004 Specifies a collection of different color palettes
2005  
2006 =item L<PDL::Graphics::Prima::PlotType|PDL::Graphics::Prima::PlotType/>
2007  
2008 Defines the different ways to visualize your data
2009  
2010 =item L<PDL::Graphics::Prima::ReadLine|PDL::Graphics::Prima::ReadLine/>
2011  
2012 Encapsulates all interaction with the L<Term::ReadLine> family of
2013 modules.
2014  
2015 =item L<PDL::Graphics::Prima::Scaling|PDL::Graphics::Prima::Scaling/>
2016  
2017 Specifies different kinds of scaling, including linear and logarithmic
2018  
2019 =item L<PDL::Graphics::Prima::Simple|PDL::Graphics::Prima::Simple/>
2020  
2021 Defines a number of useful functions for generating simple and not-so-simple
2022 plots
2023  
2024 =back
2025  
2026 =head1 LICENSE AND COPYRIGHT
2027  
2028 Unless otherwise stated, all contributions in code and documentation are
2029 copyright (c) their respective authors, all rights reserved.
2030  
2031 Portions of this module's code are copyright (c) 2011 The Board of
2032 Trustees at the University of Illinois.
2033  
2034 Portions of this module's code are copyright (c) 2011-2013 Northwestern
2035 University.
2036  
2037 Portions of this module's code are copyright (c) 2013-2014 Dickinson
2038 College.
2039  
2040 This module's documentation is copyright (c) 2011-2014 David Mertens.
2041  
2042 This module is free software; you can redistribute it and/or
2043 modify it under the same terms as Perl itself.
2044  
2045 =cut