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

filter: Statementstmt 0.0% 0 / 88 Branchbran 0.0% 0 / 30 Conditioncond 0.0% 0 / 29 MC/DCmcdc n/a Subroutinesub 0.0% 0 / 20 Podpod 0.0% 0 / 13 totaltotal 0.0% 0 / 180 CC 16 SCAR 23.7
CC
16
Cov
0%
pal::HSVrange
30.0
plotType
20.0
new
12.0
CRAP 10.7
1 use strict;
2 use warnings;
3 use PDL::Drawing::Prima::Utils;
4  
5 =head1 NAME
6  
7 PDL::Graphics::Prima::Palette - a set of palettes for the Prima graph widget
8  
9 =head1 DESCRIPTION
10  
11 Suppose you want to use color to convey some meaningful value. For example,
12 you want the color to represent the topography of a landscape, darker is
13 lower, lighter is higher. In that case, you need a mapping from a height to
14 a color, i.e. from a scalar value to a color. This is what palettes provide.
15  
16 If all you need is basic palette, you can use one of the
17 L<palette builders provided below|/"Special Palettes">. That said, creating
18 custom color palettes, when you have some idea of what you're doing and a
19 simple means for doing so, is a lot of fun. This, for example, creates a
20 palette that runs from black to red. You could just use
21 L<pal::BlackToHSV|/pal::BlackToHSV>, but what's the fun in that?
22  
23 my $palette = PDL::Graphics::Prima::Palette->new(
24 apply => sub {
25 my $data = shift;
26 my ($min, $max) = $data->minmax;
27
28 # Build the rgb piddle
29 my $rgb = zeroes(3, $data->dims);
30 $rgb->slice("0") .= (($data->double - $min) / ($max - $min)) * 255;
31
32 # Convert to Prima colors
33 return $rgb->rgb_to_color;
34 }
35 );
36  
37 Applying the palette to some data simply calls the subref that your provided
38 earlier:
39  
40 my $colors = $palette->apply($some_data);
41  
42 Using this with a standard palette builder is pretty easy, too:
43  
44 my $colors = pal::Rainbow->apply($some_data);
45  
46 And, you can provide the palette to customize how
47 L<pgrid::Matrix|PDL::Graphics::Prima::PlotType/pgrid::Matrix>
48 colorizes its data:
49  
50 plot(
51 -data => ds::Grid( $matrix,
52 plotType => pgrid::Matrix(palette => $palette),
53 bounds => [0, 0, 1, 1],
54 )
55 );
56  
57 =for future
58 All Palette classes know how to make new copies of themselves... ?
59  
60 =cut
61  
62 # At this point, I am debating just how closely I want Palettes to interact
63 # with Axes. I know I want to provide both linear and logarithmic scaling
64 # options. I would like to provide for auto-scaling as well as a means for
65 # explicitly stating the min and max of the color scale. I want to provide a
66 # means for easy display of the palette, with tick marks and labels. Then
67 # again, I could simply have the Palette hold its own scaling and create a
68 # special widget to draw the Palette (and possibly another widget to draw
69 # legends, but now I'm getting ahead of myself)
70 #
71 # Let's start with the basics: the Palette knows how to scale data and
72 # convert scaled values to color values.
73  
74 package PDL::Graphics::Prima::Palette;
75 use Carp;
76  
77 our $VERSION = 0.17; # update with update-version.pl
78  
79 =head2 new
80  
81 Accepts key/value pairs. The only required key is the C<apply> key, which
82 should have a coderef that accepts a data piddle and performs the
83 data-to-color conversion, returning a piddle of Prima colors.
84  
85 =cut
86  
87 sub new {
88 my $class = shift;
89 croak("${class}::new expects arguments in key=>value pairs")
90 unless @_ % 2 == 0;
91
92 my $self = {@_};
93 croak("${class}::new requires that you supply an 'apply' key with a subroutine reference")
94 unless exists $self->{apply} and ref($self->{apply})
95 and ref($self->{apply}) eq 'CODE';
96
97 return bless $self, $class;
98 }
99  
100 =head2 apply
101  
102 Every palette knows how to apply itself to its data. The apply function
103 returns a piddle of Prima color values given a piddle of scalar values.
104  
105 =cut
106  
107 # A basic palette knows how to apply itself to a set of data. The basic
108 # palette invokes the subroutine reference supplied in the apply key:
109 sub apply {
110 my ($self, $data) = @_;
111 return $self->{apply}->($data);
112 }
113  
114 =head2 plotType
115  
116 Every Palette knows the specific data and plot type to which it belongs.
117 The first time that a Palette is used in a drawing operation, it will become
118 associated with that specific plotType object, which is in turn associated
119 with that specific dataSet and widget. Thereafter, you can retrieve the
120 plotType object using this accessor, but you cannot change it.
121 If you want to use the same Palette with a different plotType, you can
122 create a copy of your palette using the L</copy> method.
123  
124 =cut
125  
126 sub plotType {
127 my $self = shift;
128
129 # See if they're requesting the plotType, return it if we have one, and
130 # croak if we don't:
131 if (@_ == 0) {
132 return $self->{plotType} if exists $self->{plotType};
133 croak("Requested palette's plot type, but it does not have one");
134 }
135
136 # If they are setting the plotType, croak if it has already been set,
137 # since this is a write-once property
138 if (exists $self->{plotType}) {
139 croak("You can only set a palette's plot type once");
140 }
141
142 # Otherwise, they're setting the plotType. Set it and weaken the
143 # reference so we don't have a memory leak
144 $self->{plotType} = $_[0];
145 use Scalar::Util;
146 Scalar::Util::weaken($self->{plotType});
147 }
148  
149 =head2 copy
150  
151 You can make a copy of a Palette that is identical to your current pallete
152 except that it does not have an associated plotType. This way, if you put a
153 lot of effort into making a palette, you can easily reuse that palette with
154 minimal effort.
155  
156 Note that this mechanism does not perform a deep copy, and any nested data
157 structures will be copied by reference to the new palette object.
158  
159 =cut
160  
161 sub copy {
162 my $self = shift;
163 my $new_guy = { %$self };
164 delete $new_guy->{plotType};
165 return $new_guy;
166 }
167  
168 package PDL::Graphics::Prima::Palette::HSVrange;
169 our @ISA = qw(PDL::Graphics::Prima::Palette);
170 use Carp;
171  
172 sub new {
173 my $class = shift;
174 croak("${class}::new expects key=>value pairs")
175 unless @_ % 2 == 0;
176
177 # Default to a rainbow spectrum:
178 my $self = {
179 h_start => 0,
180 h_stop => 360,
181 s_start => 1,
182 s_stop => 1,
183 v_start => 1,
184 v_stop => 1,
185 gamma => 1,
186 @_
187 };
188 croak("${class}::new expects positive gamma values")
189 if $self->{gamma} <= 0;
190 return bless $self, $class;
191 }
192  
193 sub apply {
194 my ($self, $data) = @_;
195
196 # Get the data and scale it from zero to one, taking care to correctly
197 # handle collections of identical values:
198 my ($min, $max) = $data->minmax;
199 my $scaled_data = $min == $max ? $data->zeroes
200 : (($data->double - $min) / ($max - $min));
201 $scaled_data **= $self->{gamma};
202
203 # Compute the associated hue, saturation, and vaue:
204 my $h = $scaled_data * ($self->{h_stop} - $self->{h_start})
205 + $self->{h_start};
206 my $s = $scaled_data * ($self->{s_stop} - $self->{s_start})
207 + $self->{s_start};
208 my $v = $scaled_data * ($self->{v_stop} - $self->{v_start})
209 + $self->{v_start};
210
211 # changed $h->cat($s, $v) to PDL->pdl($h, $s, $v) because it's robust
212 # against empty piddles.
213 return PDL->pdl($h, $s, $v)->mv(-1,0)->hsv_to_rgb->rgb_to_color;
214 }
215  
216 =head1 Special Palettes
217  
218 This module provides many ready-made palettes with short-name constructors
219 in the C<pal> namespace.
220  
221 =over
222  
223 =item pal::Rainbow
224  
225 Runs from red->orange->yellow->green->blue->purple in ascending order.
226  
227 =cut
228  
229 sub pal::Rainbow {
230 return pal::RainbowSV(1, 1);
231 }
232  
233 =item pal::RainbowSV
234  
235 Runs from red->orange->yellow->green->blue->purple in ascending order. The two
236 arguments it accepts are the saturation and value, which it holds uniformly.
237 This makes it much easier to create palettes that can be easily seen against a
238 white background. For example, the yellow from this palette is much eaiser to
239 see against a white background than the yellow from pal::Rainbow:
240  
241 pal::RainbowSV(1, 0.8)
242  
243 =cut
244  
245 sub pal::RainbowSV {
246 croak("You must supply a saturation and a value") unless @_ == 2;
247 return pal::HSVrange([0, @_] => [300, @_]);
248 }
249  
250 =item pal::BlackToWhite
251  
252 Larger values are white, smaller values are black. The optional argument is
253 the gamma exponent correction value, which should be positive. Typically,
254 gamma exponents are near 0.5.
255  
256 =cut
257  
258 sub pal::BlackToWhite {
259 my $gamma = shift || 1/2.2;
260 return PDL::Graphics::Prima::Palette::HSVrange->new(
261 h_start => 0,
262 h_stop => 0,
263 s_start => 0,
264 s_stop => 0,
265 v_start => 0,
266 v_stop => 1,
267 gamma => $gamma,
268 );
269 }
270  
271 =item pal::WhiteToBlack
272  
273 Larger values are black, smaller values are white. The optional argument is
274 the gamma exponent correction value, which should be positive. Typically,
275 gamma exponents are near 0.5.
276  
277 =cut
278  
279 sub pal::WhiteToBlack {
280 my $gamma = shift || 1/2.2;
281 return PDL::Graphics::Prima::Palette::HSVrange->new(
282 h_start => 0,
283 h_stop => 0,
284 s_start => 0,
285 s_stop => 0,
286 v_start => 1,
287 v_stop => 0,
288 gamma => $gamma,
289 );
290 }
291  
292 =item pal::WhiteToHSV
293  
294 Smaller values are closer to white, larger values are closer to the color
295 indicated by the HSV values that you specify, which are supplied to the
296 function as three different scalars. The first three arguments are hue,
297 saturation, and value. The optional fourth value is a gamma correction
298 exponent.
299  
300 For example:
301  
302 my $white_to_red = pal::WhiteToHSV(0, 1, 1);
303 my $gamma_white_to_red = pal::WhiteToHSV(0, 1, 1, 0.8);
304  
305 =cut
306  
307 sub pal::WhiteToHSV {
308 my @gamma;
309 @gamma = (gamma => pop) if @_ == 4;
310 return PDL::Graphics::Prima::Palette::HSVrange->new(
311 h_start => 0,
312 s_start => 0,
313 v_start => 1,
314 h_stop => $_[0],
315 s_stop => $_[1],
316 v_stop => $_[2],
317 @gamma,
318 );
319 }
320  
321 =item pal::BlackToHSV
322  
323 Like WhiteToHSV, but smaller values are closer to black instead of white.
324  
325 =cut
326  
327 sub pal::BlackToHSV {
328 my @gamma;
329 @gamma = (gamma => pop) if @_ == 4;
330 return PDL::Graphics::Prima::Palette::HSVrange->new(
331 h_start => 0,
332 s_start => 0,
333 v_start => 0,
334 h_stop => $_[0],
335 s_stop => $_[1],
336 v_stop => $_[2],
337 @gamma,
338 );
339 }
340  
341 =item pal::HSVrange
342  
343 Maps data in ascending order from the start to the stop values in hue, saturation,
344 and value. You can specify the initial and final hue, saturation, and value
345 in one of two ways: (1) a pair of three-element arrayrefs/piddles with the
346 initial and final hsv values, or (3) a set of key/value pairs describing the initial
347 and final hue, saturation and value.
348  
349 For example, this creates a palette that runs from red (H=360) to blue
350 (H=240):
351  
352 my $blue_to_red = pal::HSVrange([360, 1, 1] => [240, 1, 1]);
353  
354 If you know the L<Prima name of your color|Prima::Const/cl>, you can use the
355 conversion functions provided by
356 L<PDL::Drawing::Prima::Utils|PDL::Drawing::Prima::Utils/> to build an HSV
357 range. This example produces a palette from blue to red:
358  
359 my $blue_hsv = pdl(cl::LightBlue)->color_to_rgb->rgb_to_hsv;
360 my $red_hsv = pdl(cl::LightRed)->color_to_rgb->rgb_to_hsv;
361 my $blue_to_red = pal::HSVrange($blue_hsv, $red_hsv);
362  
363 The final means for specifying a range in HSV space is to provide key/value
364 pairs that describe your initial and final points in HSV space. You can
365 also specify a non-unitary gamma correction exponent. For example,
366 to go from blue to red with a gamma of 0.8, you could say:
367  
368 my $blue_to_red = pal::HSVrange(
369 h_start => 240,
370 s_start => 1,
371 v_start => 1,
372 h_stop => 360,
373 s_stop => 1,
374 v_stop => 1,
375 gamma => 0.8,
376 );
377  
378 However, you do not need to provide all of these values. Any key that you do
379 not supply will use a default value:
380  
381 Key Default
382 -----------------
383 h_start 0
384 s_start 1
385 v_start 1
386 h_stop 360
387 s_stop 1
388 v_stop 1
389 gamma 1
390  
391 So the blue-to-red palette, without a gamma correction, could be specified
392 as:
393  
394 my $blue_to_red = pal::HSVrange(
395 h_start => 240, h_stop => 360,
396 );
397  
398 =cut
399  
400 use Scalar::Util qw(blessed);
401 sub pal::HSVrange {
402 croak("pal::HSVrange called with odd number of arguments")
403 if @_ % 2 == 1;
404
405 # replace piddles in either of the fist two args with arrayrefs
406 $_[0] = [$_[0]->dog] if blessed($_[0]) and $_[0]->isa('PDL');
407 $_[1] = [$_[1]->dog] if blessed($_[1]) and $_[1]->isa('PDL');
408
409 # Did they provide two array refs?
410 if (ref($_[0]) and ref($_[0]) eq ref([])) {
411 my $from = shift;
412 my $to = shift;
413
414 # Check that $to is also an array ref, and that the dims are correct
415 ref($to) and ref($to) eq ref([])
416 or croak('If the first argument to pal::HSVrange is an array ref'
417 . ' or piddle, the second should be an array ref or piddle, too');
418 @$from == 3 and @$to == 3
419 or croak('If called with to/from array refs or piddles, pal::HSVrange'
420 . ' expects three-elements in said array refs or piddles');
421 # Pad the argument list in preparation for the call to new
422 unshift @_,
423 h_start => $from->[0],
424 s_start => $from->[1],
425 v_start => $from->[2],
426 h_stop => $to->[0],
427 s_stop => $to->[1],
428 v_stop => $to->[2],
429 }
430
431 return PDL::Graphics::Prima::Palette::HSVrange->new(@_);
432 }
433  
434 ## Basic histogram equalization implementation, worth considering:
435 ## See http://www.generation5.org/content/2004/histogramEqualization.asp
436 #
437 ## Let's try histogram equalization on this
438 #my $xs = $m51->flat->qsort;
439 ## Find the bottom 10% and top 10% and clip by them
440 #$m51->flat .= $m51->flat->vsearch($xs);
441 #my $ys = $xs->xlinvals(0, 1);
442 #line_plot($xs, $ys);
443 #
444 ## Interesting clipping idea:
445 #my $min = $xs->at($xs->nelem/10);
446 #my $max = $xs->at($xs->nelem*0.9);
447 #$m51->clip($min, $max);
448  
449 1;
450  
451 =back
452  
453 =head1 AUTHOR
454  
455 David Mertens (dcmertens.perl@gmail.com)
456  
457 =head1 ADDITIONAL MODULES
458  
459 Here is the full list of modules in this distribution:
460  
461 =over
462  
463 =item L<PDL::Graphics::Prima|PDL::Graphics::Prima/>
464  
465 Defines the Plot widget for use in Prima applications
466  
467 =item L<PDL::Graphics::Prima::Axis|PDL::Graphics::Prima::Axis/>
468  
469 Specifies the behavior of axes (but not the scaling)
470  
471 =item L<PDL::Graphics::Prima::DataSet|PDL::Graphics::Prima::DataSet/>
472  
473 Specifies the behavior of DataSets
474  
475 =item L<PDL::Graphics::Prima::Limits|PDL::Graphics::Prima::Limits/>
476  
477 Defines the lm:: namespace
478  
479 =item L<PDL::Graphics::Prima::Palette|PDL::Graphics::Prima::Palette/>
480  
481 Specifies a collection of different color palettes
482  
483 =item L<PDL::Graphics::Prima::PlotType|PDL::Graphics::Prima::PlotType/>
484  
485 Defines the different ways to visualize your data
486  
487 =item L<PDL::Graphics::Prima::ReadLine|PDL::Graphics::Prima::ReadLine/>
488  
489 Encapsulates all interaction with the L<Term::ReadLine> family of
490 modules.
491  
492 =item L<PDL::Graphics::Prima::Scaling|PDL::Graphics::Prima::Scaling/>
493  
494 Specifies different kinds of scaling, including linear and logarithmic
495  
496 =item L<PDL::Graphics::Prima::Simple|PDL::Graphics::Prima::Simple/>
497  
498 Defines a number of useful functions for generating simple and not-so-simple
499 plots
500  
501 =back
502  
503 =head1 LICENSE AND COPYRIGHT
504  
505 Unless otherwise stated, all contributions in code and documentation are
506 copyright (c) their respective authors, all rights reserved.
507  
508 Portions of this module's code are copyright (c) 2011 The Board of
509 Trustees at the University of Illinois.
510  
511 Portions of this module's code are copyright (c) 2011-2013 Northwestern
512 University.
513  
514 Portions of this module's code are copyright (c) 2013-2014 Dickinson
515 College.
516  
517 This module's documentation is copyright (c) 2011-2014 David Mertens.
518  
519 This module is free software; you can redistribute it and/or
520 modify it under the same terms as Perl itself.
521  
522 =cut