blib/lib/Graphics/HotMap.pm untested

filter: Statementstmt 0.0% 0 / 465 Branchbran 0.0% 0 / 104 Conditioncond 0.0% 0 / 110 MC/DCmcdc 0.0% 0 / 62 Subroutinesub 0.0% 0 / 49 Podpod 0.0% 0 / 38 totaltotal 0.0% 0 / 828 CC 53 SCAR 28.0
CC
53
Cov
0%
addLayer
42.0
addZone
42.0
addPoint
42.0
CRAP 16.4
1 #!/usr/bin/perl -w
2  
3 # Copyright (c) 2011 Mathieu Alorent
4 #
5 # This program is free software: you can redistribute it and/or modify
6 # it under the terms of the GNU General Public License as published by
7 # the Free Software Foundation, either version 3 of the License, or
8 # (at your option) any later version.
9 #
10 # This program is distributed in the hope that it will be useful,
11 # but WITHOUT ANY WARRANTY; without even the implied warranty of
12 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 # GNU General Public License for more details.
14 #
15 # You should have received a copy of the GNU General Public License
16 # along with this program. If not, see <http://www.gnu.org/licenses/>.
17  
18 package Graphics::HotMap;
19 use strict;
20  
21 =head1 NAME
22  
23 Graphics::HotMap -- generate thermographic images.
24  
25 =head1 SYNOPSIS
26  
27 =for example
28  
29 use Graphics::HotMap;
30  
31 # Create a new HotMap
32 my $hotMap = Graphics::HotMap->new(
33 minValue => 1,
34 maxValue => 50,
35 );
36  
37 # Define scale
38 $hotMap->scale(20);
39  
40 # Show legend
41 $hotMap->legend(1);
42  
43 # Show CrossMarks and values
44 $hotMap->crossMark(1,1);
45  
46 # Define a new size
47 $hotMap->mapSize({ sizeX => 15, sizeY => 15 });
48  
49 # Add time
50 $hotMap->addHorodatage(time, 15, 30);
51  
52 # Add layer
53 $hotMap->addLayer({ layerName => '10_back', visibility => 1, sliceColor => 1 });
54  
55 # Add a zone
56 $hotMap->addZone({
57 zoneName => 'AllMap',
58 layerName => '10_back',
59 coordonates => [0,0,14,14],
60 border => 1,
61 });
62 # And add some points
63 $hotMap->addPoint({ layerName => '10_back', x => 2, y => 2, value => 15 });
64 $hotMap->addPoint({ layerName => '10_back', x => 1, y => 6, value => 5 });
65 $hotMap->addPoint({ layerName => '10_back', x => 9, y => 13, value => 25 });
66 $hotMap->addLayer({ layerName => '20_inner' });
67  
68 # Add a zone
69 $hotMap->addZone({
70 zoneName => 'innerZone',
71 layerName => '20_inner',
72 coordonates => [4,0,9,6],
73 border => 1,
74 text => 'Inner Zone',
75 });
76  
77 # And some points
78 $hotMap->addPoint({ layerName => '20_inner', x => 5, y => 1, value => 1 });
79 $hotMap->addPoint({ layerName => '20_inner', x => 6, y => 5, value => 9 });
80  
81 # You can also prepare conf as a Hash, ...
82 my %other = (
83 layers => {
84 '30_anotherLayer' => {
85 visibility => 0,
86 sliceColors => 1,
87 },
88 '40_anotherLayer' => {
89 visibility => 0,
90 sliceColors => 0,
91 },
92 },
93 zones => {
94 anotherZone => {
95 layerName => '30_anotherLayer',
96 coordonates => [7,4,10,9],
97 border => 1,
98 text => 'other layer',
99 textSize => 8,
100 textColor => 'magenta',
101 },
102 zoneA => {
103 layerName => '40_anotherLayer',
104 coordonates => [0,10,1,12],
105 border => 1,
106 text => 'black',
107 textSize => 8,
108 textColor => 'white',
109 },
110 zoneB => {
111 layerName => '40_anotherLayer',
112 coordonates => [1,10,2,12],
113 border => 1,
114 text => 'blue',
115 textSize => 8,
116 textColor => 'white',
117 },
118 zoneC => {
119 layerName => '40_anotherLayer',
120 coordonates => [2,10,3,12],
121 border => 1,
122 text => 'green',
123 textSize => 8,
124 textColor => 'white',
125 },
126 zoneD => {
127 layerName => '40_anotherLayer',
128 coordonates => [3,10,4,12],
129 border => 1,
130 text => 'cyan',
131 textSize => 8,
132 textColor => 'white',
133 },
134 },
135 points => {
136 '30_anotherLayer' => [
137 [8,5,46],
138 [10,9,22],
139 ],
140 '10_back' => [
141 [13,1,50],
142 ],
143 '40_anotherLayer' => [
144 [0,10,1],
145 [1,10,2],
146 [2,10,3],
147 [3,10,4],
148 ],
149 },
150 );
151  
152 # ..., and import/add it
153 $hotMap->addConfs(\%other);
154  
155 # Run the interpolation and generate and image
156 $hotMap->genImage;
157  
158 # Save the image a a PNG file
159 $hotMap->genImagePng('MyTest.png');
160  
161 # print the text representation of the map
162 print $hotMap->toString('floor') if $hotMap->scale < 3;
163  
164 =head1 DESCRIPTION
165  
166 Generate thermographic images from a few know points. Others values are interpolated. Graphics::HotMap use PDL to work on matrix.
167 PDL can compute very very large matrix in a few seconds.
168  
169 See L<http://kumy.org/HotMap/HotMap.png>
170  
171 =head2 FUNCTIONS
172  
173 =over 4
174  
175 =cut
176  
177 use Data::Dumper;
178 use Image::Magick;
179 use Math::Gradient qw(multi_array_gradient);
180 use PDL;
181 use PDL::NiceSlice;
182 use PDL::IO::Pic;
183 use POSIX qw(strftime);
184 use File::Temp qw/ :POSIX /;
185 use File::Temp qw/ tempfile tempdir /;
186  
187 use constant {
188 PALETTE_SLICE => 35,
189 };
190  
191 our $VERSION = '0.0001';
192  
193 =item new(<HASH>)
194  
195 =for ref
196  
197 Construct and return a new HotMap Object;
198  
199 =for usage
200  
201 Graphics::HotMap->new(
202 outfileGif => <File path>, # file to write GIF
203 outfilePng => <File path>, # file to write PNG
204 legend => [0|1], # activate lengend
205 legendNbGrad => <number>, # Number a graduation
206 cross => <bool>, # activate crossing of known values
207 crossValues => <bool>, # activate values printing whith cross
208 minValue => <number>, # minimum value
209 maxValue => <number>, # maximum value
210 font => <path to font file>,
211 fontSize => <number>, # font size
212 scale => <number>, # scale values and coordonates
213 sizeX => <number>, # X size
214 sizeY => <number>, # Y size
215 );
216  
217 =for exemple
218  
219 my $hotMap = Graphics::HotMap->new(
220 sizeX => 10,
221 sizeY => 10,
222 minValue => 1,
223 maxvalue => 50,
224 );
225  
226  
227 =cut
228  
229 sub new {
230 my ($class, %params) = (@_);
231 my $self={};
232 $self->{_outfileGif} = $params{outfileGif} || undef;
233 $self->{_outfilePng} = $params{outfilePng} || undef;
234 $self->{_legend} = $params{legend} || 0;
235 $self->{_legendNbGrad} = $params{legendNbGrad} || 7;
236 $self->{_crossMark} = $params{cross} || 0;
237 $self->{_crossMarkTemp}= $params{crossTemp} || 0;
238 #$self->{_minValue} = $params{minValue} || 0;
239 #$self->{_maxValue} = $params{maxValue} || 70;
240 $self->{_font} = $params{font} || '/usr/share/fonts/truetype/freefont/FreeSans.ttf';
241 $self->{_fontSize} = $params{fontSize} || 15;
242 $self->{_text} = ();
243 $self->{_horodatage} = $params{horodatage} || [0, 0, 0];
244 $self->{_scale} = $params{echelle} || 1;
245 $self->{_verbose} = $params{verbose} || 0;
246 $self->{_mapSize}{x} = $params{sizeX} || 30;
247 $self->{_mapSize}{y} = $params{sizeY} || 20;
248 $self->{_knownPoints} = {};
249 $self->{_mapPoints} = PDL->zeroes(1);
250 bless $self, $class;
251 #$self->gradient(20, ([0,0,255],[0,255,255],[0,255,0],[255,255,0],[255,0,0]));
252 return $self;
253 }
254  
255 =item initKnownPoints()
256  
257 =for ref
258  
259 Reset all know points.
260  
261 =cut
262  
263 sub initKnownPoints {
264 my $self = shift;
265  
266 $self->{_knownPoints} = {};
267 }
268  
269 =item mapSize(<HASH>)
270  
271 =for ref
272  
273 Set or Return mapSize
274  
275 =for exemple
276  
277 $hotMap->mapSize({sizeX => 15, sizeY => 15}); # Set map size
278 @size = $hotMap->mapSize; # Return the actual map size
279  
280 =cut
281  
282 sub mapSize {
283 my $self = shift;
284 my ($dimentions) = @_;
285  
286 if (defined $dimentions) {
287 die ("mapSize: You must set sizeX and sizeY.",$/)
288 unless (defined $dimentions->{sizeX} && defined $dimentions->{sizeY});
289  
290 $self->{_mapSize}{x} = ($dimentions->{sizeX} ) * $self->{_scale};
291 $self->{_mapSize}{y} = ($dimentions->{sizeY} ) * $self->{_scale};
292  
293 $self->{_mapPoints} = PDL->zeroes($self->{_mapSize}{x}, $self->{_mapSize}{y});
294 $self->initKnownPoints;
295 } else {
296 return [$self->{_mapSize}{x}, $self->{_mapSize}{y}];
297 }
298 }
299  
300 =item scale(<SCALAR>)
301  
302 =for ref
303  
304 Set or Return current scale factor.
305  
306 =for exemple
307  
308 $hotMap->scale(2);
309 $scale = hotMap->scale;
310  
311 =cut
312  
313 sub scale {
314 my $self = shift;
315 my ($scaleFactor) = @_;
316  
317 if (defined $scaleFactor) {
318 die ("setScale: scaleFactor must be > 0. => '$scaleFactor'",$/)
319 unless $scaleFactor > 0;
320 $self->{_scale} = $scaleFactor;
321 } else {
322 return $self->{_scale};
323 }
324 }
325  
326 =for exemple
327 Internal function to scale point coordonates
328  
329 =cut
330  
331 sub _scalePoint {
332 my $self = shift;
333 my ($x, $y) = @_;
334  
335 return (
336 (0.5+$x) * $self->{_scale} -0.5,
337 (0.5+$y) * $self->{_scale} -0.5,
338 );
339 }
340  
341 =for exemple
342 Internal function to verify that point is inside matrix
343  
344 =cut
345  
346 sub _isPointInside {
347 my $self = shift;
348 my ($x, $y) = @_;
349  
350 return
351 0 <= $x && $x <= $self->{_mapSize}{x} &&
352 0 <= $y && $y <= $self->{_mapSize}{y};
353 }
354  
355 =item addLayer(<HASH>)
356  
357 =for ref
358  
359 Define a new Layer to store values.
360  
361 Layers are parsed by alphabetical order.
362  
363 * visibility (default: 1) : allow crossMarks to be displayed for this layer.
364  
365 * sliceColor (default: 1) : colors are looked up in the gradient. If set to 0, values between 0 to 16 are fixed colors (LUT).
366  
367 =for exemple
368  
369 $hotMap->addLayer({ layerName => 'Layer1' });
370 $hotMap->addLayer({ layerName => 'Layer2', visibility => 1, sliceColor => 1 });
371  
372 =cut
373  
374 sub addLayer {
375 my $self = shift;
376 my ($params) = @_;
377
378 my $layerName = $params->{layerName};
379 my $visibility = $params->{visibility};
380 my $sliceColors = $params->{sliceColors};
381 my $gradientName = $params->{gradientName};
382 my $maskIfNoValue= $params->{maskIfNoValue};
383  
384 $sliceColors = 1 unless defined $sliceColors;
385 $visibility = 1 unless defined $visibility;
386 $maskIfNoValue = 0 unless defined $maskIfNoValue;
387  
388 die ("addLayer: You must provide a layer name.",$/)
389 unless defined $layerName;
390  
391 die ("addLayer: Gradient must be defined: '$gradientName'.",$/)
392 unless (defined $gradientName && defined $self->{_gradient}{$gradientName});
393  
394 $self->{_layers}{$layerName}{sliceColors} = $sliceColors;
395 $self->{_layers}{$layerName}{visibility} = $visibility;
396 $self->{_layers}{$layerName}{gradientName} = $gradientName;
397 $self->{_layers}{$layerName}{maskIfNoValue}= $maskIfNoValue;
398 $self->{_knownPoints}{$layerName} = PDL->zeroes($self->{_mapSize}{x}, $self->{_mapSize}{y});
399 }
400  
401 =item addZone(<HASH>)
402  
403 =for ref
404  
405 Define a new zone to interpolate over a layer.
406  
407 =for exemple
408  
409 $hotMap->addZone({
410 zoneName => 'AllMap', # zone name
411 layerName => 'Layer1', # layer from which zone belongs
412 coordonates => [0,0,9,9], # coordonates [startX, startY, endX, endY]
413 border => 1, # border color (LUT) or undef for none
414 text => "your text", #
415 textSize => 10, #
416 textColor => 'red', #
417 noScale = 0, # if true, coordonates will not be auto-scaled
418 });
419  
420 =cut
421  
422 sub addZone {
423 my $self = shift;
424 my ($params) = @_;
425  
426 my $layerName = $params->{layerName};
427 my $zoneName = $params->{zoneName};
428 my $coordonates = $params->{coordonates};
429 my $border = $params->{border};
430 my $text = $params->{text};
431 my $textSize = $params->{textSize};
432 my $textColor = $params->{textColor};
433 my $noScale = $params->{noScale};
434  
435 if (!defined $noScale && !$noScale) {
436 ($coordonates->[0], $coordonates->[1]) = $self->_scalePoint($coordonates->[0], $coordonates->[1]);
437 ($coordonates->[2], $coordonates->[3]) = $self->_scalePoint($coordonates->[2], $coordonates->[3]);
438 }
439  
440 die ("addZone: You must provide a layer name.",$/)
441 unless defined $layerName;
442  
443 die ("addZone: You must provide a zone name.",$/)
444 unless defined $zoneName;
445  
446 die ("addZone: Zone must not be over mapSize limits. '$coordonates->[0],$coordonates->[1];$coordonates->[2],$coordonates->[3]'",$/)
447 unless (
448 $self->_isPointInside($coordonates->[0], $coordonates->[1]) &&
449 $self->_isPointInside($coordonates->[2], $coordonates->[3])
450 );
451  
452 $self->{_zones}{$layerName}{$zoneName}{coordonates} = $coordonates;
453 $self->{_zones}{$layerName}{$zoneName}{border} = $border;
454  
455 $self->addText ( {
456 x => $coordonates->[0] + ($coordonates->[2] - $coordonates->[0])/2,
457 y => $coordonates->[1] + ($coordonates->[3] - $coordonates->[1])/2,
458 text => $text,
459 size => $textSize,
460 align => 'center',
461 color => $textColor,
462 } )
463 if (defined $text);
464 }
465  
466 =item addPoint(<HASH>)
467  
468 =for ref
469  
470 Add a know point to a zone. Zone should first be declared with addZone.
471  
472 =for exemple
473  
474 $hotMap->addPoint({
475 layerName => 'AllMap',
476 x => 7,
477 y => 8,
478 value => 25,
479 noScale => 0,
480 });
481  
482 =cut
483  
484 sub addPoint {
485 my $self = shift;
486 my ($params) = @_;
487  
488 my $layerName = $params->{layerName};
489 my $x = $params->{x};
490 my $y = $params->{y};
491 my $value = $params->{value};
492 my $noScale = $params->{noScale};
493 my $gradientName = $self->{_layers}{$layerName}{gradientName};
494  
495 ($x, $y) = $self->_scalePoint($x, $y)
496 unless (defined $noScale && $noScale);
497  
498 if ( ! $value > 0) {
499 warn ("addPoint: Only values > 0 accepted. => '$value'",$/);
500 return;
501 }
502 #if ( ! $value <= ) {
503 # warn ("addPoint: Only values > 0 accepted. => '$value'",$/);
504 # return;
505 #}
506 die ("addPoint: Point should be inside ;) => '$x:$y' : '$self->{_mapSize}{x}:$self->{_mapSize}{y}' ($params->{x}, $params->{y}) $params->{layerName}",$/)
507 unless $self->_isPointInside($x, $y);
508 die ("addPoint: layer must exists. => '$layerName'",$/)
509 unless defined $self->{_knownPoints}{$layerName};
510 die ("addPoint: Value outside gradient Limits. Value => $value : Limits => ". $self->{_gradient}{$gradientName}{minValue} .' <=> '. $self->{_gradient}{$gradientName}{maxValue},$/)
511 unless ($self->{_gradient}{$gradientName}{minValue} <= $value && $value <= $self->{_gradient}{$gradientName}{maxValue});
512  
513 $self->{_knownPoints}{$layerName}->set($x, $y, $value);
514 }
515  
516 =item addHorodatage($timestamp, $x, $y)
517  
518 =for ref
519  
520 Timestamp on the image.
521  
522 =for exemple
523  
524 $hotMap->addHorodatage(time, 10, 10);
525 $hotMap->addHorodatage(1269122338, 10, 10);
526  
527 =cut
528  
529 sub addHorodatage {
530 my $self = shift;
531 my ($time, $x, $y) = @_;
532  
533 die ("You must set time and coordonates.",$/)
534 unless (defined $time && defined $x && defined $y);
535  
536 $self->{_horodatage} = [$time, $x, $y];
537 }
538  
539 =item addText(<HASH>)
540  
541 =for ref
542  
543 Add text on the image.
544  
545 =for exemple
546  
547 $hotMap->addText({
548 text => "your text",
549 x => $x,
550 y => $y,
551 font => <path to font file>
552 pointsize => 10,
553 fill => 'black',
554 align => '[left|center|right],
555 });
556  
557 =cut
558  
559 sub addText {
560 my $self = shift;
561 my ($params) = @_;
562  
563 push (@{$self->{_text}}, $params);
564  
565 }
566  
567 =item addConfs(<HASH>)
568  
569 =for ref
570  
571 Add Layers/Zones/Point from a hash config.
572  
573 =for exemple
574  
575 my %other = (
576 layers => {
577 '30_anotherLayer' => {
578 visibility => 0,
579 sliceColors => 1,
580 },
581 },
582 zones => {
583 anotherZone => {
584 layerName => '30_anotherLayer',
585 coordonates => [7,4,10,9],
586 border => 1,
587 text => 'other layer',
588 textSize => 8,
589 textColor => 'magenta',
590 },
591 },
592 points => {
593 '30_anotherLayer' => [
594 [8,5,46],
595 [10,9,22],
596 ],
597 },
598 );
599
600 $hotMap->addConfs(\%other);
601  
602 =cut
603  
604 sub addConfs {
605 my $self = shift;
606 my ($params) = @_;
607  
608 foreach my $layerName (keys %{$params->{layers}}) {
609 $self->addLayer({
610 layerName => $layerName,
611 visibility => $params->{layers}{$layerName}{visibility},
612 sliceColors => $params->{layers}{$layerName}{sliceColors},
613 gradientName => $params->{layers}{$layerName}{gradientName},
614 maskIfNoValue=> $params->{layers}{$layerName}{maskIfNoValue},
615 });
616 }
617  
618 foreach my $zoneName (keys %{$params->{zones}}) {
619 $self->addZone({
620 layerName => $params->{zones}{$zoneName}{layerName},
621 zoneName => $zoneName,
622 coordonates => $params->{zones}{$zoneName}{coordonates},
623 border => $params->{zones}{$zoneName}{border},
624 text => $params->{zones}{$zoneName}{text},
625 textSize => $params->{zones}{$zoneName}{textSize},
626 textColor => $params->{zones}{$zoneName}{textColor},
627 noScale => $params->{zones}{$zoneName}{noScale},
628 });
629 }
630  
631 foreach my $layerName (keys %{$params->{points}}) {
632 foreach my $point (@{$params->{points}{$layerName}}) {
633 $self->addPoint({
634 layerName => $layerName,
635 x => $point->[0],
636 y => $point->[1],
637 value => $point->[2],
638 noScale => $point->[3],
639 });
640 }
641 }
642 }
643  
644 =item getPoint()
645  
646 =for ref
647  
648 Return a point value at coordonate x/y.
649 Without a zone name, it returns a point from the interpolated table.
650 With zone name, it returns a point from that zone.
651  
652 =for exemple
653  
654 $hotMap->getPoint(6, 2, 'Zone1')
655 $hotMap->getPoint(6, 2)
656  
657 =cut
658  
659 sub getPoint {
660 my $self = shift;
661 my ($x, $y, $layerName) = @_;
662  
663 if (defined $layerName) {
664 die ("getPoint: layer must be defined. => '$layerName'",$/)
665 unless defined $self->{_knownPoints}{$layerName};
666  
667 return $self->{_knownPoints}{$layerName}->at($x,$y);
668 }
669  
670 return $self->{_mapPoints}->at($x,$y);
671 }
672  
673 =item fusionLayers()
674  
675 =for ref
676  
677 Fusion the second layer to the first one.
678  
679 =for exemple
680  
681 $hotMap->fusionLayers('AllMap', 'Zone1');
682  
683 =cut
684  
685 sub fusionLayers {
686 my $self = shift;
687 my ($dest, $orig) = @_;
688  
689 die ("fusionLayers: layers must be defined. => '$dest, $orig'",$/)
690 unless (defined $self->{_knownPoints}{$dest} && defined $self->{_knownPoints}{$orig});
691  
692 $self->{_knownPoints}{$dest}->inplace->or2($self->{_knownPoints}{$orig}, 0);
693 #$self->{_knownPoints}{$dest} += $self->{_knownPoints}{$orig};
694 }
695  
696 =item getLayer()
697  
698 =for ref
699  
700 Return all values from a layer.
701  
702 =for exemple
703  
704 my $piddleVal = $hotMap->getLayer('AllMap');
705  
706 =cut
707  
708 sub getLayer {
709 my $self = shift;
710 my ($layer) = @_;
711  
712 die ("getLayer: layer must be defined. => '$layer'",$/)
713 unless (defined $self->{_knownPoints}{$layer});
714  
715 return $self->{_knownPoints}{$layer};
716 }
717  
718 =item setLayer()
719  
720 =for ref
721  
722 Define all values from a layer.
723  
724 =for exemple
725  
726 $hotMap->setLayer('AllMap', $piddleVal);
727  
728 =cut
729  
730 sub setLayer {
731 my $self = shift;
732 my ($dest, $values) = @_;
733  
734 die ("setLayer: layers must be defined. => '$dest'",$/)
735 unless (defined $self->{_knownPoints}{$dest});
736  
737 $self->{_knownPoints}{$dest} += $values;
738 }
739  
740 =item toString()
741  
742 =for ref
743  
744 Convert the interpolated table to text.
745 The parameter 'floor' can be added to return rounded values.
746  
747 =for exemple
748  
749 print $hotMap->toString('floor');
750
751 [
752 [ 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1]
753 [ 1 14 14 14 14 13 13 13 13 13 14 14 14 15 1]
754 [ 1 14 15 14 13 13 13 13 13 13 14 14 15 15 1]
755 [ 1 13 14 13 13 12 12 13 13 14 14 15 15 15 1]
756 [ 1 9 10 11 11 12 12 13 13 14 15 15 16 16 1]
757 [ 1 6 7 8 10 11 12 13 14 15 15 16 16 17 1]
758 [ 1 5 5 7 9 11 12 13 14 15 16 17 17 17 1]
759 [ 1 5 6 7 9 11 13 14 16 17 17 18 18 18 1]
760 [ 1 6 7 8 10 12 14 16 17 18 19 19 19 19 1]
761 [ 1 8 8 10 11 14 16 18 19 20 21 21 20 20 1]
762 [ 1 9 10 11 13 16 18 20 21 22 22 22 21 21 1]
763 [ 1 11 12 13 15 17 20 22 23 23 23 23 22 22 1]
764 [ 1 12 13 15 17 19 21 23 24 24 24 24 23 22 1]
765 [ 1 13 15 16 18 20 22 23 24 25 24 24 23 22 1]
766 [ 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1]
767 ]
768  
769 =cut
770  
771 sub toString {
772 my $self = shift;
773 my $function = shift;
774  
775 my $tmpPiddle = $self->{_mapPoints};
776 #$tmpPiddle->where($tmpPiddle > PALETTE_SLICE) -= PALETTE_SLICE;
777  
778 if (defined $function) {
779 return scalar (floor($tmpPiddle)) if ($function eq 'floor');
780 die "toString: Unknown Function. => '$function'",$/;
781 }
782 return scalar ($tmpPiddle);
783 }
784  
785 =item legend()
786  
787 =for ref
788  
789 Set or Return legend status. When enabled, the legend gradient will be drawn on the image.
790  
791 =cut
792  
793 sub legend {
794 my $self = shift;
795 my ($value) = @_;
796  
797 if (defined $value) {
798 $self->{_legend} = 1;
799 } else {
800 return $self->{_legend};
801 }
802 }
803  
804 =item crossMark()
805  
806 =for ref
807  
808 Set or Return cross marks status. When enabled, a cross will be drawn on the image where points have been defined.
809  
810 =cut
811  
812 sub crossMark {
813 my $self = shift;
814 my ($mark, $value) = @_;
815  
816 if (defined $mark) {
817 $self->{_crossMark} = 1;
818 $self->{_crossMarkTemp} = 1 if defined $value;
819 } else {
820 return $self->{_crossMark};
821 }
822 }
823  
824 =for exemple
825 Internal function for base colors table
826  
827 =cut
828  
829 sub _genLut {
830 my $self = shift;
831 my ($lut) = @_;
832  
833 $lut = [
834 [255, 255, 255], # 0 white
835 [ 0, 0, 0], # 1 black
836 [ 0, 0, 255], # 2 blue
837 [ 0, 255, 0], # 3 green
838 [ 0, 255, 255], # 4 cyan
839 [255, 0, 0], # 5 red
840 [255, 0, 255], # 6 magenta
841 [255, 255, 0], # 7 yellow
842 [153, 204, 0], # 8 Green 1
843 [128, 128, 0], # 9 Green 2
844 [128, 0, 128], # 10 purple
845 [255, 255, 153], # 11 light yellow
846 [204, 153, 255], # 12 light purple
847 [ 0, 204, 255], # 13 cool blue
848 [228, 109, 10], # 14 orange
849 [255, 204, 153], # 15 peal
850 [246, 96, 134], # 16 rose1
851 [ 96, 118, 246], # 17 blue2
852 [152, 18, 13], # 18 red2
853 [153, 102, 204], # 19 violet2
854 [123, 160, 91], # 20 asperge
855 ]
856 unless defined $lut;
857  
858 for (@$lut..PALETTE_SLICE-1) {
859 push (@{$lut}, [100+$_, 100+$_, 100+$_]);
860 }
861  
862 return $lut;
863 }
864  
865 =for item gradient(<ARRAYREF>)
866  
867 Set the gradient.
868  
869 Parameter must be an array of RGB array.
870  
871 See Math::Gradient::multi_array_gradient()
872  
873 =cut
874  
875 sub gradient {
876 my $self = shift;
877 my ($params) = @_;
878  
879 my $nbColors = $params->{nbColors};
880 my $colorsPoints = $params->{colorsPoints};
881 my $gradientName = $params->{gradientName};
882 my $minValue = $params->{minValue};
883 my $maxValue = $params->{maxValue};
884 my $unit = $params->{unit};
885 my $visibility = $params->{visibility};
886  
887 $self->{_gradient}{$gradientName}{colorsPoints} = $colorsPoints;
888 $self->{_gradient}{$gradientName}{nbColors} = $nbColors;
889 $self->{_gradient}{$gradientName}{minValue} = $minValue;
890 $self->{_gradient}{$gradientName}{maxValue} = $maxValue;
891 $self->{_gradient}{$gradientName}{unit} = $unit;
892 $self->{_gradient}{$gradientName}{visibility} = $visibility;
893 }
894  
895 =for comment
896 Internal function for generation LUT
897  
898 =cut
899  
900 sub _genGradient {
901 my $self = shift;
902  
903 my $nextPaletteStart = PALETTE_SLICE;
904 my @gradients = ();
905  
906 foreach my $gradientName (sort keys %{$self->{_gradient}}) {
907 my $nbColors = 1+$self->{_gradient}{$gradientName}{nbColors};
908 my @grad = multi_array_gradient($nbColors, @{$self->{_gradient}{$gradientName}{colorsPoints}});
909 push (@gradients, @grad);
910 $self->{_gradient}{$gradientName}{start} = $nextPaletteStart;
911 $nextPaletteStart += $nbColors;
912 }
913  
914 my $lut = byte pdl((@{$self->_genLut}, @gradients));
915 $self->{_gradient}{colors} = PDL::cat ($lut);
916 }
917  
918 =for item getColor($level)
919 Return the lut color from the specified level
920  
921 =cut
922  
923 sub getColor {
924 my $self = shift;
925 my ($level) = @_;
926 my $lut = $self->{_gradient}{colors};
927  
928 return '#'.
929 sprintf("%02x",$lut->at(0,$level,0)).
930 sprintf("%02x",$lut->at(1,$level,0)).
931 sprintf("%02x",$lut->at(2,$level,0));
932 }
933  
934 =for comment
935 Internal function for writing text on the image
936  
937 =cut
938  
939 sub _printText {
940 my $self = shift;
941 my ($im, $textHash) = @_;
942  
943 my $text = $textHash->{text};
944 my $x = $textHash->{x};
945 my $y = $textHash->{y};
946 my $color = $textHash->{color} || 'black';
947 my $align = $textHash->{align} || 'left';
948 my $size = $textHash->{size} || $self->{_fontSize};
949 my $font = $textHash->{font} || $self->{_font};
950 my $rotate = $textHash->{rotate} || 0;
951  
952 $im->Annotate(
953 font=>$self->{_font},
954 pointsize=>$size,
955 fill=>$color,
956 text=>$text,
957 align=>$align,
958 x=>$x,
959 y=>$y,
960 rotate=>$rotate,
961 );
962 }
963  
964 =for comment
965 Internal function for generating legend bar on the image
966  
967 =cut
968  
969 sub _drawLegendBar {
970 my $self = shift;
971 my ($gradientName, $i, $im) = @_;
972 my $repere = 10;
973  
974 my $legendBar = Graphics::HotMap->new(
975 wall => 1,
976 );
977 $legendBar->{_gradient} = $self->{_gradient};
978 $legendBar->mapSize({
979 sizeX => 10,
980 sizeY => 500,
981 });
982
983 $legendBar->addLayer({ layerName => '_Legend'.$gradientName, visibility => 1, gradientName => $gradientName });
984  
985 my $nbGrad = $self->{_gradient}{$gradientName}{nbColors}; #$self->{_legendNbGrad}-1;
986 my $min = $self->{_gradient}{$gradientName}{minValue};
987 my $max = $self->{_gradient}{$gradientName}{maxValue};
988  
989 for (0..$nbGrad) {
990 my $x = $legendBar->{_mapSize}{x}-1;
991 my $y = $_/$nbGrad*($legendBar->{_mapSize}{y}-1);
992 my $valeur = $max-(int(($nbGrad-$_)/$nbGrad*($max-$min)));
993 my $unit = $legendBar->{_gradient}{$gradientName}{unit};
994 $legendBar->addPoint({
995 layerName => '_Legend'.$gradientName,
996 #x => $_/$nbGrad*($legendBar->{_mapSize}{x}-1),
997 #y => $legendBar->{_mapSize}{y}-1-$repere*$i,
998 x => $x,
999 y => $y,
1000 value => $valeur,
1001 noScale => 1,
1002 unit => $unit,
1003 });
1004 $legendBar->addText ( {
1005 x => $x+15,
1006 y => $y+10,
1007 text => int($valeur).$unit,
1008 size => 10,
1009 align => 'center'
1010 } ) if ($nbGrad < 11 || $_%5 == 0);
1011 }
1012  
1013 $legendBar->addZone({
1014 layerName =>'_Legend'.$gradientName,
1015 zoneName => '_Legend'.$gradientName,
1016 coordonates => [
1017 1,
1018 1,
1019 $legendBar->{_mapSize}{x}-1,
1020 $legendBar->{_mapSize}{y}-1,
1021 ],
1022 noScale => 1 });
1023 $legendBar->_genDegradZone('_Legend'.$gradientName, $legendBar->{_zones}{'_Legend'.$gradientName}{'_Legend'.$gradientName}, 1);
1024  
1025 my $imag = byte $legendBar->{_mapPoints};
1026 my $tmpName = new File::Temp( TEMPLATE => 'generated-XXXXX',
1027 DIR => '/tmp/',
1028 SUFFIX => '.png',
1029 OPEN => 0);
1030 #my $tmpName = tmpnam().'.png';
1031 my $cptLoop = 0;
1032 do {
1033 eval {$imag->wpic($tmpName, { LUT => $legendBar->{_gradient}{colors} }); };
1034 # $imag->wpic($tmpName, { LUT => $legendBar->{_gradient}{colors} });
1035 ++$cptLoop;
1036 } while ($@ && $cptLoop < 10);
1037  
1038 if ($cptLoop > 2) {
1039 print "ARgh ! Function: _saveImage ; nbErr for wpic:$cptLoop\n";
1040 exit;
1041 }
1042  
1043 # read the temporary File in PerlMagick
1044 my $status = $im->ReadImage($tmpName);
1045 warn $status if $status;
1046 #unlink $tmpName;
1047  
1048 # Flip the image
1049 $im->[$i+1]->Flip;
1050 $im->[$i+1]->Border(fill=>'black', width=>-1, height=>-1);
1051 $im->[$i+1]->Extent(
1052 background => 'white',
1053 geometry => ($legendBar->{_mapSize}{x}+35).'x'.($legendBar->{_mapSize}{y}+15),
1054 gravity => 'West',
1055 );
1056 $legendBar->_genText($im->[$i+1]);
1057 $im->[$i+1]->Extent(
1058 background => 'white',
1059 geometry => ($legendBar->{_mapSize}{x}+35).'x'.$self->{_mapSize}{y},
1060 gravity => 'Center',
1061 );
1062  
1063 $im->[$i+1]->Extent(
1064 background => 'white',
1065 geometry => ($legendBar->{_mapSize}{x}+35+20).'x'.$self->{_mapSize}{y},
1066 gravity => 'East',
1067 );
1068 $im->[$i+1]->Annotate(
1069 font=>$self->{_font},
1070 pointsize=>10,
1071 fill=>'black',
1072 text=>$gradientName,
1073 align=>'right',
1074 x=>10,
1075 y=>35,
1076 rotate=>270,
1077 );
1078 $self->{_im} = $im->Append(stack=>'false');
1079 }
1080  
1081 =for comment
1082 Internal function for generating legend on the image
1083  
1084 =cut
1085  
1086 sub _genLegende {
1087 my $self = shift;
1088 my ($im) = @_;
1089  
1090 my $i=0;
1091 #print "Printing Gradient Bars",$/;
1092 foreach my $gradientName (sort keys %{$self->{_gradient}}) {
1093 #print "* $gradientName",$/;
1094 next if $gradientName eq 'colors';
1095 next if defined $self->{_gradient}{$gradientName}{visibility} && !$self->{_gradient}{$gradientName}{visibility};
1096 $self->_drawLegendBar($gradientName, $i, $im);
1097 $i++;
1098 }
1099 }
1100  
1101 =for comment
1102 Internal function for generating one mark on the image
1103  
1104 =cut
1105  
1106 sub _drawMark {
1107 my $self = shift;
1108 my ($im, $x, $y, $valeur, $unit) = @_;
1109 my $red = '#FF0000';
1110 my $white = '#FFFFFF';
1111  
1112 my %cross = (
1113 -2 => { 0 => $red, },
1114 -1 => { 0 => $white, },
1115 0 => {-2 => $red,
1116 -1 => $white,
1117 0 => $white,
1118 1 => $white,
1119 2 => $red, },
1120 1 => { 0 => $white, },
1121 2 => { 0 => $red, },
1122 );
1123  
1124 foreach my $i (sort keys %cross) {
1125 foreach my $j (sort keys %cross) {
1126 for (0..2) {
1127 next unless defined $cross{$i}{$j};
1128 my $ix = $i * $_ + $x;
1129 my $jy = $j * $_ + $y;
1130 next unless (0 < $ix && $ix < $self->{_mapSize}{x}-1);
1131 next unless (0 < $jy && $jy < $self->{_mapSize}{y}-1);
1132 $im->Set("pixel[$ix,$jy]" => $cross{$i}{$j});
1133 }
1134 }
1135 }
1136  
1137 $self->addText ( {
1138 x => $x,
1139 y => $y,
1140 text => int($valeur).$unit,
1141 size => 10,
1142 align => 'center'
1143 } );
1144 }
1145  
1146 =for comment
1147 Internal function for generating all marks on the image
1148  
1149 =cut
1150  
1151 sub _genCrossMark {
1152 my $self = shift;
1153 my $im = shift;
1154  
1155 foreach my $layer (sort keys %{$self->{_knownPoints}}) {
1156 my ($d0,$d1) = whichND $self->{_knownPoints}{$layer};
1157 my $nbValues = nelem($d0);
1158 for (0..$nbValues-1) {
1159 next unless (
1160 defined $self->{_layers}{$layer}{visibility} &&
1161 $self->{_layers}{$layer}{visibility}
1162 );
1163 $self->_drawMark(
1164 $im,
1165 $d0(($_)),
1166 $d1(($_)),
1167 $self->{_knownPoints}{$layer}->at($d0(($_)),$d1(($_))),
1168 $self->{_gradient}{$self->{_layers}{$layer}{gradientName}}{unit}
1169 );
1170 }
1171 }
1172 }
1173  
1174 =for comment
1175 Internal function for writing timestamp on the image
1176  
1177 =cut
1178  
1179 sub _drawTime {
1180 my $self = shift;
1181 my $im = shift;
1182  
1183 my ($time, $x, $y) = @{$self->{_horodatage}};
1184 return unless $time;
1185 $self->addText ( {
1186 x => $x,
1187 y => $y,
1188 text => strftime ("%d-%m-%Y %H:%M:%S", localtime $time),
1189 } );
1190 }
1191  
1192 =for comment
1193 generate text on the image
1194  
1195 =cut
1196  
1197 sub _genText {
1198 my $self = shift;
1199 my ($im) = @_;
1200  
1201 foreach my $text (@{$self->{_text}}) {
1202 $self->_printText($im, $text);
1203 }
1204  
1205 }
1206  
1207 =for comment
1208 generate the image from the interpolated map.
1209  
1210 =cut
1211  
1212 sub _genPicture {
1213 my $self = shift;
1214 my $image = $self->{_im} = new Image::Magick();
1215  
1216 # write a temporary image of the piddle
1217 my $imag = byte $self->{_mapPoints};
1218 my $tmpName = tmpnam().'.png';
1219 #eval { $self->{_hotMap}->genImage };
1220 #print STDERR "error: _genTemperatureImage: $@" if $@;
1221 my $cptLoop = 0;
1222 do {
1223 eval {$imag->wpic($tmpName, { LUT => $self->{_gradient}{colors} }); };
1224 ++$cptLoop;
1225 } while ($@ && $cptLoop < 10);
1226  
1227 if ($cptLoop > 2) {
1228 print "ARgh ! Function: _genPicture; nbErr for wpic:$cptLoop\n";
1229 exit;
1230 }
1231  
1232 # read the temporary File in PerlMagick
1233 my $status = $image->ReadImage($tmpName);
1234 warn $status if $status;
1235 unlink $tmpName;
1236  
1237 # Flip the image
1238 my $im = $image;
1239 #my $im = $image->[0];
1240 $im->Flip;
1241  
1242 # Gen CrossMarks
1243 $self->_genCrossMark($im) if $self->{_crossMark};
1244 # Draw time on image
1245 $self->_drawTime($im) if $self->{_horodatage}[0];
1246 # Draw texts
1247 $self->_genText($im);
1248  
1249 # Gen legend in piddle
1250 $self->_genLegende($im) if $self->{_legend};
1251 }
1252  
1253 =for comment
1254 Really compute the interpolation from known points.
1255  
1256 =cut
1257  
1258 sub _pdlDegrad {
1259 my $self = shift;
1260 my ($input, $output, $sliceColors, $gradientName) = @_;
1261  
1262 my ($d0,$d1) = whichND $input;
1263 my $nbValues = nelem($d0);
1264 my $norm = pdl->zeroes($input->dims);
1265 $output .= 0;
1266  
1267 my $t0r2;
1268 my $t0r2inv;
1269  
1270 if ($nbValues > 1) {
1271 for (0..$nbValues-1) {
1272 my $indice = $_;
1273 $t0r2 = $input->rvals({ center=>[$d0($indice), $d1($indice)], squared=>1 } );
1274 $t0r2->where($t0r2==0) .= -1;
1275 $t0r2inv = 1/$t0r2;
1276 $norm += $t0r2inv;
1277 $output += $input($d0($indice), $d1($indice);-)*$t0r2inv;
1278 }
1279  
1280 $output->where($output < 0) .= 0;
1281 $output /= $norm;
1282 $output += $input;
1283 } elsif ($nbValues == 1) {
1284 $output->where($output==0) .= $input->at($d0->at(0),$d1->at(0));
1285 } else {
1286 # do not slice if there is no values
1287 return;
1288 }
1289  
1290 if (defined $sliceColors && $sliceColors) {
1291 my $minValue = $self->{_gradient}{$gradientName}{minValue};
1292 my $maxValue = $self->{_gradient}{$gradientName}{maxValue};
1293 my $ratio = $self->{_gradient}{$gradientName}{nbColors}/(1+$maxValue-$minValue);
1294 $output *= $ratio;
1295 $output += $self->{_gradient}{$gradientName}{start}-$minValue*$ratio;
1296  
1297 }
1298 }
1299  
1300 =for comment
1301 Fetch zones, get a slice from coordonates, then generate the interpolation.
1302 If border is defined, place the points too.
1303  
1304 =cut
1305  
1306 sub _genDegradZone {
1307 my $self = shift;
1308 my ($layerName, $zoneHash) = @_;
1309  
1310 my ($sX, $sY, $eX, $eY) = @{$zoneHash->{coordonates}};
1311  
1312 my $sliceColors = $self->{_layers}{$layerName}{sliceColors};
1313 my $gradientName= $self->{_layers}{$layerName}{gradientName};
1314  
1315 # define slices from zones
1316 my $mapPointsSlice = $self->{_mapPoints}->($sX:$eX,$sY:$eY);
1317 my $knownPointsSlice = $self->{_knownPoints}{$layerName}->($sX:$eX,$sY:$eY);
1318  
1319 # don't show invisible layers if no points inside
1320 return if ($self->{_layers}{$layerName}{maskIfNoValue} && !$knownPointsSlice->max);
1321  
1322 # generate gradient interpolation
1323 $self->_pdlDegrad($knownPointsSlice, $mapPointsSlice, $sliceColors, $gradientName);
1324  
1325 # draw walls
1326 if (defined $zoneHash->{border}) {
1327 $mapPointsSlice->(0) .= $zoneHash->{border};
1328 $mapPointsSlice->(-1) .= $zoneHash->{border};
1329 $mapPointsSlice->(:,0) .= $zoneHash->{border};
1330 $mapPointsSlice->(:,-1) .= $zoneHash->{border};
1331 }
1332  
1333 #$mapPointsSlice = byte($mapPointsSlice);
1334 }
1335  
1336 =for comment
1337 Fetch zone
1338  
1339 =cut
1340  
1341 sub _genDegrad {
1342 my $self = shift;
1343  
1344 $self->_genGradient;
1345  
1346 foreach my $layerName (sort keys %{$self->{_zones}}) {
1347 foreach my $zoneName (sort keys %{$self->{_zones}{$layerName}}) {
1348 $self->_genDegradZone($layerName, $self->{_zones}{$layerName}{$zoneName});
1349 }
1350 }
1351 }
1352  
1353 =item genImage()
1354  
1355 =for ref
1356  
1357 Calculate the interpolation of all Zones.
1358  
1359 =cut
1360  
1361 sub genImage {
1362 my $self = shift;
1363  
1364 $self->{_mapPoints} = PDL->zeroes($self->{_mapSize}{x}, $self->{_mapSize}{y});
1365 $self->_genDegrad;
1366 $self->_genPicture;
1367 }
1368  
1369 =for comment
1370  
1371 This function will write image to disk.
1372  
1373 =cut
1374  
1375 sub _saveImg {
1376 my $self = shift;
1377 my ($outfile, $im) = @_;
1378  
1379 print $im->Write(filename=>$outfile); #, compression=>'JPEG', type => 'Palette');
1380 }
1381  
1382 =item genImagePng()
1383  
1384 =for ref
1385  
1386 Write a PNG image from the interpolated table.
1387  
1388 =for exemple
1389  
1390 $hotMap->genImagePng('<path_to_png'>);
1391  
1392 =cut
1393  
1394 sub genImagePng {
1395 my $self = shift;
1396 my $fileName = shift || $self->{_outfilePng} || die "No output PNG specified";
1397 $self->_saveImg($fileName,$self->{_im});
1398 return {
1399 width => $self->{_im}->Get('width'),
1400 height => $self->{_im}->Get('height'),
1401 filesize => $self->{_im}->Get('filesize'),
1402 mime => $self->{_im}->Get('mime'),
1403 image => $self->{_im},
1404 };
1405 }
1406  
1407 =item genImageGif()
1408  
1409 =for ref
1410  
1411 Add a GIF image to the annimation from the interpolated table.
1412  
1413 =for exemple
1414  
1415 $hotMap->genImageGif('<path_to_gif'>);
1416  
1417 =cut
1418  
1419 sub genImageGif {
1420 my $self = shift;
1421 my $fileName = shift || $self->{_outfileGif} || die "No output GIF specified";
1422 my $image = shift;
1423 my $im = $self->{_im};
1424  
1425 unless (defined $image) {
1426 $image = new Image::Magick(size => "$self->{_mapSize}{x}x$self->{_mapSize}{y}");
1427 $image->Read($fileName);
1428 }
1429 $image->Set(magick=>'GIF', loop=> 100);
1430 $im->Set(magick=>'GIF', delay=>100);
1431 push (@$image, $im);
1432 $self->_saveImg($fileName, $image);
1433 return {
1434 width => $image->Get('width'),
1435 height => $image->Get('height'),
1436 filesize => $image->Get('filesize'),
1437 mime => $image->Get('mime'),
1438 image => $image,
1439 };
1440 }
1441  
1442 =back
1443  
1444 =head1 SEE ALSO
1445  
1446 PDL
1447  
1448 Math::Gradient
1449  
1450 =head1 AUTHOR
1451  
1452 Mathieu Alorent (cpan@kumy.net)
1453  
1454 =cut
1455  
1456 1;