blib/lib/ICC/Support/Chart.pm untested

filter: Statementstmt 0.0% 0 / 4814 Branchbran 0.0% 0 / 1972 Conditioncond 0.0% 0 / 1467 MC/DCmcdc n/a Subroutinesub 0.0% 0 / 126 Podpod 0.0% 0 / 114 totaltotal 0.0% 0 / 8493 CC 987 SCAR 66.3
CC
987
Cov
0%
writeTIFF
4692.0
_readChartTIFF
2756.0
select_token
1980.0
CRAP 758.4
1 package ICC::Support::Chart;
2  
3 use strict;
4 use Carp;
5  
6 our $VERSION = 1.78;
7  
8 # revised 2018-09-11
9 #
10 # Copyright © 2004-2018 by William B. Birkett
11  
12 # add development directory
13 use lib 'lib';
14  
15 # inherit from Shared
16 use parent qw(ICC::Shared);
17  
18 # support modules
19 use Config;
20 use Encode;
21 use File::Glob;
22 use POSIX ();
23 use Time::Piece;
24 use XML::LibXML;
25  
26 # enable static variables
27 use feature 'state';
28  
29 # create new chart object
30 # parameters: ([hash])
31 # parameters: (ref_to_data_array, [hash])
32 # parameters: (path_to_file, [hash])
33 # parameters: (path_to_folder, [hash])
34 # returns: (ref_to_chart_object) -or- (ref_to_chart_object, error_string)
35 sub new {
36  
37 # get object class
38 my $class = shift();
39  
40 # local variables
41 my ($self, $hash, $array, $format, $offset, $path, $files, $result, $error);
42  
43 # create empty chart object
44 $self = [
45 {}, # object header
46 [[]], # chart data
47 [[]], # colorimetry data
48 [], # header lines
49 {}, # SAMPLE_ID hash
50 ];
51  
52 # get optional hash
53 $hash = pop() if (ref($_[-1]) eq 'HASH');
54  
55 # if there are additional parameters
56 if (@_) {
57
58 # if first parameter is an array or a Math::Matrix object
59 if (ref($_[0]) eq 'ARRAY' || UNIVERSAL::isa($_[0], 'Math::Matrix')) {
60
61 # copy array/matrix and optional format
62 add_cols($self, shift(), $hash->{'format'});
63
64 # if first parameter is a scalar
65 } elsif (! ref($_[0])) {
66
67 # get path
68 $path = shift();
69
70 # save path in object header
71 $self->[0]{'file_path'} = $path;
72
73 # get file list
74 $files = _files($path);
75
76 # no files
77 if (@{$files} == 0) {
78
79 # invalid path
80 carp($error = "no files in path: $path\n");
81
82 # one file
83 } elsif (@{$files} == 1) {
84
85 # read chart
86 ($result = _readChart($self, $files->[0], $hash)) && carp($error = "chart $files->[0] $result\n");
87
88 # add colorimetric metadata
89 _addColorMeta($self);
90
91 # multiple files
92 } else {
93
94 # if folder handling undefined or 'AVG'
95 if (! defined($hash->{'folder'}) || $hash->{'folder'} eq 'AVG') {
96
97 # read average chart
98 _readChartAvg($self, $files, $hash) || carp($error = "no valid charts in path: $path\n");
99
100 # if folder handling 'APPEND'
101 } elsif ($hash->{'folder'} eq 'APPEND') {
102
103 # read appended chart
104 _readChartAppend($self, $files, $hash) || carp($error = "no valid charts in path: $path\n");
105
106 } else {
107
108 # invalid folder handling
109 carp($error = "invalid folder handling: $hash->{'folder'}\n");
110
111 }
112
113 }
114
115 } else {
116
117 # invalid parameter(s)
118 carp($error = "invalid parameter(s)");
119
120 }
121
122 # make SAMPLE_ID hash
123 _makeSampleID($self);
124
125 # if hash defined
126 } elsif (defined($hash)) {
127
128 # make patch set
129 ($result = _makePatchSet($self, $hash)) && carp($error = "failed making patch set - $result\n");
130
131 }
132  
133 # add initial_size to object header
134 $self->[0]{'initial_size'} = [$#{$self->[1]}, $#{$self->[1][0]} + 1];
135  
136 # bless object
137 bless($self, $class);
138  
139 # return
140 return(wantarray() ? ($self, $error) : $self);
141  
142 }
143  
144 # get/set reference to header hash
145 # parameters: ([ref_to_new_hash])
146 # returns: (ref_to_hash)
147 sub header {
148  
149 # get object reference
150 my $self = shift();
151  
152 # if there are parameters
153 if (@_) {
154
155 # if one parameter, a hash reference
156 if (@_ == 1 && ref($_[0]) eq 'HASH') {
157
158 # set header to copy of hash
159 $self->[0] = {%{shift()}};
160
161 } else {
162
163 # error
164 croak('parameter must be a hash reference');
165
166 }
167
168 }
169  
170 # return reference
171 return($self->[0]);
172  
173 }
174  
175 # get/set reference to data array
176 # note: row 0 contains the DATA_FORMAT field names
177 # note: set updates the SAMPLE_ID hash and colorimetry array
178 # parameters: ([ref_to_new_array])
179 # returns: (ref_to_array)
180 sub array {
181  
182 # get object reference
183 my $self = shift();
184  
185 # if there are parameters
186 if (@_) {
187
188 # if one parameter, an array reference
189 if (@_ == 1 && ref($_[0]) eq 'ARRAY') {
190
191 # get array reference
192 my $array = shift();
193
194 # initialize data array
195 $self->[1] = [];
196
197 # if array is not empty
198 if (@{$array}) {
199
200 # for each row
201 for my $i (0 .. $#{$array}) {
202
203 # copy to object
204 $self->[1][$i] = [@{$array->[$i]}];
205
206 }
207
208 # make SAMPLE_ID hash
209 _makeSampleID($self);
210
211 # add colorimetric metadata
212 _addColorMeta($self);
213
214 }
215
216 } else {
217
218 # error
219 croak('parameter must be an array reference');
220
221 }
222
223 }
224  
225 # return reference
226 return($self->[1]);
227  
228 }
229  
230 # get data array size
231 # if flag is true, initial size is returned
232 # parameters: ([flag])
233 # returns: (number_rows)
234 # returns: (number_rows, number_columns)
235 sub size {
236  
237 # get parameters
238 my ($self, $flag) = @_;
239  
240 # if flag is true
241 if ($flag && defined($self->[0]{'initial_size'})) {
242
243 # return initial size, array or scalar
244 return(wantarray ? @{$self->[0]{'initial_size'}} : $self->[0]{'initial_size'}->[0]);
245
246 } else {
247
248 # return current size, array or scalar
249 return(wantarray ? ($#{$self->[1]}, $#{$self->[1][0]} + 1) : $#{$self->[1]});
250
251 }
252  
253 }
254  
255 # get data matrix size
256 # returns: (number_rows)
257 # returns: (number_rows, number_columns)
258 sub matrix_size {
259  
260 # get object reference
261 my $self = shift();
262  
263 # get row length
264 my $rows = _getRowLength($self) || $#{$self->[1]};
265  
266 # compute columns
267 my $cols = POSIX::ceil($#{$self->[1]}/$rows);
268  
269 # return array or scalar
270 wantarray ? return($rows, $cols) : return($rows);
271  
272 }
273  
274 # get row slice from SAMPLE_ID values
275 # id_keys is a list of scalars and/or array references
276 # row_slice is reference to an array of row indices
277 # note: returns undef if any key is missing
278 # parameters: (id_keys)
279 # returns: (row_slice)
280 sub rows {
281  
282 # get object reference
283 my $self = shift();
284  
285 # local variable
286 my (@keys, @rows);
287  
288 # flatten id key list
289 @keys = @{ICC::Shared::flatten(@_)};
290  
291 # get row list using SAMPLE_ID hash
292 @rows = @{$self->[4]}{@keys};
293  
294 # return row slice or undef if any rows are missing
295 return((grep {! defined()} @rows) ? undef : \@rows);
296  
297 }
298  
299 # get column slice from DATA_FORMAT keys
300 # format_keys is a list of scalars and/or array references
301 # column_slice is reference to an array of column indices
302 # note: tries to match ignoring context if exact match fails
303 # note: returns 'undef' if any column is missing
304 # parameters: (format_keys)
305 # returns: (column_slice)
306 sub cols {
307  
308 # get object reference
309 my $self = shift();
310  
311 # local variables
312 my (@keys, %fmt, @cols);
313  
314 # flatten format key list
315 @keys = @{ICC::Shared::flatten(@_)};
316  
317 # make lookup hash
318 %fmt = map {defined($self->[1][0][$_]) ? ($self->[1][0][$_], $_) : ()} (0 .. $#{$self->[1][0]});
319  
320 # lookup format keys in hash
321 @cols = @fmt{@keys};
322  
323 # if any columns undefined
324 if (grep {! defined()} @cols) {
325
326 # make lookup hash without context prefixes
327 %fmt = map {(defined($self->[1][0][$_]) && $self->[1][0][$_] =~ m/^(.*?)\|?([^\|\n]*)$/) ? ($2, $_) : ()} (0 .. $#{$self->[1][0]});
328
329 # lookup format keys in hash
330 @cols = @fmt{@keys};
331
332 }
333  
334 # return column slice or undef if any columns undefined
335 return((grep {! defined()} @cols) ? undef : \@cols);
336  
337 }
338  
339 # get DATA_FORMAT keys from column slice
340 # column_slice is a list of scalars and/or array references
341 # format_keys is an array reference
342 # parameters: ([column_slice])
343 # returns: (format_keys)
344 sub fmt_keys {
345  
346 # get object reference
347 my $self = shift();
348  
349 # if no parameter -or- column slice an empty array reference ([])
350 if (@_ == 0 || (@_ == 1 && ref($_[0]) eq 'ARRAY' && @{$_[0]} == 0)) {
351
352 # return all format keys
353 return([@{$self->[1][0]}]);
354
355 } else {
356
357 # return format keys slice
358 return([@{$self->[1][0]}[@{ICC::Shared::flatten(@_)}]]);
359
360 }
361  
362 }
363  
364 # get/set context
365 # 'undef' indicates no context (get or set)
366 # returned context may be a scalar or an array
367 # parameter: (column_slice) => returns: (context)
368 # parameters: (column_slice, context) => returns: (modified_keys)
369 sub context {
370  
371 # get object reference
372 my $self = shift();
373  
374 # local variables
375 my ($cols, $context, @cx);
376  
377 # return if no parameters supplied
378 return(undef) if (@_ == 0);
379  
380 # get column slice
381 $cols = ICC::Shared::flatten(shift());
382  
383 # use all columns if slice is empty
384 $cols = [0 .. $#{$self->[1][0]}] if (@{$cols} == 0);
385  
386 # if no context parameter
387 if (@_ == 0) {
388
389 # match contexts
390 @cx = map {$self->[1][0][$_] =~ m/^(.*)\|/ ? $1 : undef} @{$cols};
391
392 # return array if wanted
393 return(@cx) if (wantarray);
394
395 # warn if columns have different contexts
396 (@cx == grep {(! defined($cx[0]) && ! defined($_)) || ($cx[0] eq $_)} @cx) || warn('columns have different contexts');
397
398 # return context of first column
399 return($cx[0]);
400
401 } else {
402
403 # get context
404 $context = shift();
405
406 # for each column
407 for my $i (0 .. $#{$cols}) {
408
409 # if context is defined
410 if (defined($context)) {
411
412 # replace current context
413 $self->[1][0][$cols->[$i]] =~ s/^(?:.*\|)?(.*)$/$context\|$1/;
414
415 # if context is 'undef'
416 } else {
417
418 # remove current context
419 $self->[1][0][$cols->[$i]] =~ s/^.*\|//;
420
421 }
422
423 }
424
425 # return modified keys
426 return([@{$self->[1][0]}[@{$cols}]]);
427
428 }
429
430 }
431  
432 # test for a specified data class
433 # returns list of matched indices or count
434 # context parameter of '|' matches fields with no context
435 # parameters: (class, [context])
436 # returns: (list -or- count)
437 sub test {
438  
439 # get parameters
440 my ($self, $class, $context) = @_;
441  
442 # local variables
443 my (%regex, @fields);
444  
445 # hash of compiled regex
446 %regex = (
447 'RGB' => qr/^(?:(.*)\|)?RGB_[RGB]$/,
448 'CMYK' => qr/^(?:(.*)\|)?CMYK_[CMYK]$/,
449 'XYZ' => qr/^(?:(.*)\|)?XYZ_[XYZ]$/,
450 'XYY' => qr/^(?:(.*)\|)?XYY_(?:X|Y|CAPY)$/,
451 'LAB' => qr/^(?:(.*)\|)?LAB_[LAB]$/,
452 'LCH' => qr/^(?:(.*)\|)?LAB_[LCH]$/,
453 'NCLR' => qr/^(?:(.*)\|)?(?:[2-9A-F]CLR_[1-9A-F]|PC[2-9A-F]_[1-9A-F])$/,
454 'SPECTRAL' => qr/^(?:(.*)\|)?(?:nm|SPECTRAL_NM_|SPECTRAL_NM|SPECTRAL_|NM_|R_)\d{3}$/,
455 'SPOT' => qr/^(?:(.*)\|)?SPOT_\d+$/,
456 'DENSITY' => qr/^(?:(.*)\|)?D_(?:RED|GREEN|BLUE|VIS)$/,
457 'STDEVXYZ' => qr/^(?:(.*)\|)?STDEV_[XYZ]$/,
458 'STDEVLAB' => qr/^(?:(.*)\|)?STDEV_[LAB]$/,
459 'MEAN_DE' => qr/^(?:(.*)\|)?MEAN_DE$/,
460 'ID' => qr/^(?:(.*)\|)?(?:SAMPLE_ID|SampleID)$/,
461 'NAME' => qr/^(?:(.*)\|)?SAMPLE_NAME$/,
462 'DEVICE' => qr/^(?:(.*)\|)?(?:RGB_[RGB]|CMYK_[CMYK]|[2-9A-F]CLR_[1-9A-F]|PC[2-9A-F]_[1-9A-F])$/,
463 );
464  
465 # verify class
466 (! ref($class) && exists($regex{$class})) || croak('invalid data class');
467  
468 # if context is undefined
469 if (! defined($context)) {
470
471 # match format fields (ignoring context)
472 @fields = grep {$self->[1][0][$_] =~ /$regex{$class}/} (0 .. $#{$self->[1][0]});
473
474 # if context is '|'
475 } elsif ($context eq '|') {
476
477 # match format fields (no context)
478 @fields = grep {$self->[1][0][$_] =~ /$regex{$class}/ && ! defined($1)} (0 .. $#{$self->[1][0]});
479
480 } else {
481
482 # match format fields (matching context)
483 @fields = grep {$self->[1][0][$_] =~ /$regex{$class}/ && defined($1) && ($1 eq $context)} (0 .. $#{$self->[1][0]});
484
485 }
486  
487 # return (list -or- count)
488 return(wantarray() ? @fields : scalar(@fields));
489  
490 }
491  
492 # get/set keyword value(s)
493 # CGATS ASCII file header lines are stored as an array in the object header
494 # most lines contain a keyword followed by a value, which this methods gets/sets
495 # a keyword may be used more than once, so the value parameter is an array
496 # if the keyword doesn't exist, a new line is added when setting its value
497 # if the keyword is enclosed by angle brackets, existing lines are removed
498 # parameters: () => returns: (file_header_array_reference)
499 # parameters: (keyword) => returns: (value_array)
500 # parameters: (keyword, value_array) => returns: (original_value_array)
501 sub keyword {
502  
503 # get parameters
504 my ($self, $key, @values) = @_;
505  
506 # local variables
507 my ($del, @ix, @current);
508  
509 # if no keyword, return file header array reference
510 (defined($key)) || return($self->[3]);
511  
512 # set delete flag, stripping angle brackets (if any)
513 $del = ($key =~ s/^<(.*)>$/$1/);
514  
515 # get indices of existing keyword (if any)
516 @ix = grep {$self->[3][$_][0] eq $key} (0 .. $#{$self->[3]});
517  
518 # get current values array (if any)
519 @current = map {$self->[3][$_][1]} @ix;
520  
521 # if delete flag set
522 if ($del) {
523
524 # while indices
525 while (@ix) {
526
527 # delete array element
528 splice(@{$self->[3]}, pop(@ix), 1);
529
530 }
531
532 }
533  
534 # if there are supplied values
535 if (@values) {
536
537 # for each value
538 for (@values) {
539
540 # if not a number or already quoted
541 if (! m/^([\d.-]+|".*")$/) {
542
543 # remove any quotes
544 s/"//g;
545
546 # enclose in quotes
547 $_ = "\"$_\"";
548
549 }
550
551 }
552
553 # while indices and values
554 while (@ix && @values) {
555
556 # set keyword/value entry
557 $self->[3][shift(@ix)] = [$key, shift(@values)];
558
559 }
560
561 # for each remaining value (if any)
562 for (@values) {
563
564 # add keyword/value entry
565 push(@{$self->[3]}, [$key, $_]);
566
567 }
568
569 }
570  
571 # return current values array, or scalar
572 return(wantarray ? @current : $current[0]);
573  
574 }
575  
576 # get/set CREATED value
577 # adds CREATED keyword when setting, if none
578 # parameters: () # gets date/time from CREATED value
579 # parameters: (string) # sets/adds CREATED keyword/value
580 # parameters: (Time::Piece_object) # sets/adds CREATED keyword/value
581 # returns: (Time::Piece_object) # default is localtime
582 sub created {
583  
584 # get parameters
585 my ($self, $t) = @_;
586  
587 # local variables
588 my (@ix, $datetime);
589  
590 # get indices of existing CREATED lines (if any)
591 @ix = grep {$self->[3][$_][0] eq 'CREATED'} (0 .. $#{$self->[3]});
592  
593 # print warning if more than one CREATED line
594 print "warning: more than one CREATED keyword\n" if (@ix > 1);
595  
596 # if date/time parameter given
597 if (defined($t)) {
598
599 # make Time::Piece object if reference is a scalar
600 $t = _makeTimePiece($t) if (! ref($t));
601
602 # if not a Time::Piece object
603 if (ref($t) ne 'Time::Piece') {
604
605 # print warning
606 print "warning: invalid date/time parameter, using localtime instead\n";
607
608 # use local time
609 $t = localtime();
610
611 }
612
613 # make ISO 8601 datetime string from Time::Piece object
614 $datetime = sprintf("%s%+03d:00", $t->datetime, $t->tzoffset->hours);
615
616 # if CREATED lines
617 if (@ix) {
618
619 # replace value in first CREATED line
620 $self->[3][$ix[0]][1] = "\"$datetime\"";
621
622 } else {
623
624 # if keyword lines exist
625 if (@{$self->[3]}) {
626
627 # insert CREATED line (as second line)
628 splice(@{$self->[3]}, 1, 0, ['CREATED', "\"$datetime\""]);
629
630 } else {
631
632 # add CREATED line
633 $self->[3][0] = ['CREATED', "\"$datetime\""];
634
635 }
636
637 }
638
639 # no parameter
640 } else {
641
642 # if CREATED lines
643 if (@ix) {
644
645 # make Time::Piece object from first CREATED value
646 $t = _makeTimePiece($self->[3][$ix[0]][1]);
647
648 } else {
649
650 # print warning
651 print "warning: no CREATED keyword, returning localtime instead\n";
652
653 # use local time
654 $t = localtime();
655
656 }
657
658 }
659  
660 # return Time::Piece object
661 return($t);
662  
663 }
664  
665 # get/set data array slice
666 # row_slice and column_slice may be either a scalar or array reference
667 # replacement_data is reference to a 2-D array of replacement values
668 # replacement data dimensions must match size of row_slice and column_slice
669 # data_slice is reference to a 2-D array, selected by row_slice and column_slice
670 # parameters: ([row_slice, [column_slice, [replacement_data]]])
671 # return: (data_slice)
672 sub slice {
673  
674 # get parameters
675 my ($self, $rows, $cols, $data) = @_;
676  
677 # select all rows if row slice undefined
678 $rows = [] if (! defined($rows));
679  
680 # select all fields if column slice undefined
681 $cols = [] if (! defined($cols));
682  
683 # call get/set subroutine
684 _getset($self, 1, $rows, $cols, $data);
685  
686 }
687  
688 # get/set colorimetry array slice
689 # row_slice and column_slice may be either a scalar or array reference
690 # replacement_data is reference to a 2-D array of replacement values
691 # replacement data dimensions must match size of row_slice and column_slice
692 # data_slice is reference to a 2-D array, selected by row_slice and column_slice
693 # parameters: ([row_slice, [column_slice, [replacement_data]]])
694 # return: (data_slice)
695 sub colorimetry {
696  
697 # get parameters
698 my ($self, $rows, $cols, $data) = @_;
699  
700 # flatten row slice
701 $rows = defined($rows) ? ICC::Shared::flatten($rows) : [];
702  
703 # select all rows if row slice empty
704 $rows = [0 .. $#{$self->[2]}] if (@{$rows} == 0);
705  
706 # flatten column slice
707 $cols = defined($cols) ? ICC::Shared::flatten($cols) : [];
708  
709 # select all fields if column slice empty
710 $cols = [0 .. $#{$self->[1][0]}] if (@{$cols} == 0);
711  
712 # call get/set subroutine
713 _getset($self, 2, $rows, $cols, $data);
714  
715 }
716  
717 # get/set SAMPLE_ID data
718 # optional hash contains supplementary parameters
719 # row_slice and column_slice are 1-D array references
720 # data_slice is a Math::Matrix object (2-D array)
721 # replacement_data is a Math::Matrix object or 2-D array
722 # parameters: ([hash]) => returns: (column_slice)
723 # parameters: (row_slice, [hash]) => returns: (data_slice)
724 # parameters: (row_slice, replacement_data, [hash]) => returns: (column_slice)
725 sub id {
726  
727 # local variables
728 my ($hash, %fmt, $cols);
729  
730 # get optional hash
731 $hash = pop() if (ref($_[-1]) eq 'HASH');
732  
733 # get remaining parameters
734 my ($self, $rows, $data) = @_;
735  
736 # make lookup hash (context| -or- '||' => column)
737 %fmt = map {($self->[1][0][$_] =~ m/^(.*\|)?(?:SAMPLE_ID|SampleID|ID)$/) ? (defined($1) ? $1 : '||', $_) : ()} (0 .. $#{$self->[1][0]});
738  
739 # if context defined
740 if (defined($hash->{'context'})) {
741
742 # get id column with context
743 $cols = $fmt{"$hash->{'context'}|"};
744
745 } else {
746
747 # get id column without context
748 $cols = $fmt{'||'};
749
750 # if id column undefined
751 if (! defined($cols)) {
752
753 # make lookup hash ignoring context ('||' => column)
754 %fmt = map {($self->[1][0][$_] =~ m/^(?:.*\|)?(?:SAMPLE_ID|SampleID|ID)$/) ? ('||', $_) : ()} (0 .. $#{$self->[1][0]});
755
756 # get id column
757 $cols = $fmt{'||'};
758
759 }
760
761 }
762  
763 # call get/set subroutine
764 _getset($self, 1, $rows, $cols, $data);
765  
766 }
767  
768 # get/set SAMPLE_NAME data
769 # optional hash contains supplementary parameters
770 # row_slice and column_slice are 1-D array references
771 # data_slice is a Math::Matrix object (2-D array)
772 # replacement_data is a Math::Matrix object or 2-D array
773 # parameters: ([hash]) => returns: (column_slice)
774 # parameters: (row_slice, [hash]) => returns: (data_slice)
775 # parameters: (row_slice, replacement_data, [hash]) => returns: (column_slice)
776 sub name {
777  
778 # local variables
779 my ($hash, $cols);
780  
781 # get optional hash
782 $hash = pop() if (ref($_[-1]) eq 'HASH');
783  
784 # get remaining parameters
785 my ($self, $rows, $data) = @_;
786  
787 # get column slice, adding optional context prefix
788 $cols = cols($self, defined($hash->{'context'}) ? "$hash->{'context'}|SAMPLE_NAME" : 'SAMPLE_NAME');
789  
790 # call get/set subroutine
791 _getset($self, 1, $rows, $cols, $data);
792  
793 }
794  
795 # get/set RGB data
796 # optional hash contains supplementary parameters
797 # row_slice and column_slice are 1-D array references
798 # data_slice is a Math::Matrix object (2-D array)
799 # replacement_data is a Math::Matrix object or 2-D array
800 # parameters: ([hash]) => returns: (column_slice)
801 # parameters: (row_slice, [hash]) => returns: (data_slice)
802 # parameters: (row_slice, replacement_data, [hash]) => returns: (column_slice)
803 sub rgb {
804  
805 # local variables
806 my ($hash, $cols);
807  
808 # get optional hash
809 $hash = pop() if (ref($_[-1]) eq 'HASH');
810  
811 # get remaining parameters
812 my ($self, $rows, $data) = @_;
813  
814 # get column slice, adding optional context prefix
815 $cols = cols($self, map {defined($hash->{'context'}) ? "$hash->{'context'}|$_" : $_} qw(RGB_R RGB_G RGB_B));
816  
817 # call get/set subroutine
818 _getset($self, 1, $rows, $cols, $data);
819  
820 }
821  
822 # get/set CMYK data
823 # optional hash contains supplementary parameters
824 # row_slice and column_slice are 1-D array references
825 # data_slice is a Math::Matrix object (2-D array)
826 # replacement_data is a Math::Matrix object or 2-D array
827 # parameters: ([hash]) => returns: (column_slice)
828 # parameters: (row_slice, [hash]) => returns: (data_slice)
829 # parameters: (row_slice, replacement_data, [hash]) => returns: (column_slice)
830 sub cmyk {
831  
832 # local variables
833 my ($hash, $cols);
834  
835 # get optional hash
836 $hash = pop() if (ref($_[-1]) eq 'HASH');
837  
838 # get remaining parameters
839 my ($self, $rows, $data) = @_;
840  
841 # get column slice, adding optional context prefix
842 $cols = cols($self, map {defined($hash->{'context'}) ? "$hash->{'context'}|$_" : $_} qw(CMYK_C CMYK_M CMYK_Y CMYK_K));
843  
844 # call get/set subroutine
845 _getset($self, 1, $rows, $cols, $data);
846  
847 }
848  
849 # get/set 6CLR data
850 # optional hash contains supplementary parameters
851 # row_slice and column_slice are 1-D array references
852 # data_slice is a Math::Matrix object (2-D array)
853 # replacement_data is a Math::Matrix object or 2-D array
854 # parameters: ([hash]) => returns: (column_slice)
855 # parameters: (row_slice, [hash]) => returns: (data_slice)
856 # parameters: (row_slice, replacement_data, [hash]) => returns: (column_slice)
857 sub hex {
858  
859 # local variables
860 my ($hash, $cols);
861  
862 # get optional hash
863 $hash = pop() if (ref($_[-1]) eq 'HASH');
864  
865 # get remaining parameters
866 my ($self, $rows, $data) = @_;
867  
868 # get column slice, adding optional context prefix
869 $cols = cols($self, map {defined($hash->{'context'}) ? "$hash->{'context'}|6CLR_$_" : "6CLR_$_"} (1 .. 6)); # X-Rite notation
870 $cols = $cols // cols($self, map {defined($hash->{'context'}) ? "$hash->{'context'}|PC6_$_" : "PC6_$_"} (1 .. 6)); # Ekso notation
871  
872 # call get/set subroutine
873 _getset($self, 1, $rows, $cols, $data);
874  
875 }
876  
877 # get/set nCLR data
878 # optional hash contains supplementary parameters
879 # row_slice and column_slice are 1-D array references
880 # data_slice and replacement_data are 2-D array references
881 # parameters: ([hash]) => returns: (column_slice)
882 # parameters: (row_slice, [hash]) => returns: (data_slice)
883 # parameters: (row_slice, replacement_data, [hash]) => returns: (column_slice)
884 sub nCLR {
885  
886 # local variables
887 my ($hash, $context, %fmt, %fmt2, $chan, @cols);
888  
889 # get optional hash
890 $hash = pop() if (ref($_[-1]) eq 'HASH');
891  
892 # get remaining parameters
893 my ($self, $rows, $data) = @_;
894  
895 # get the context
896 $context = $hash->{'context'};
897  
898 # make lookup hash (key => column)
899 %fmt = map {($self->[1][0][$_] =~ m/^(?:.*\|)?([2-9A-F]CLR_[1-9A-F]|PC[2-9A-F]_[1-9A-F])$/) ? ($self->[1][0][$_], $_) : ()} (0 .. $#{$self->[1][0]});
900  
901 # make lookup hash (prefix -or- '||' => last key)
902 %fmt2 = map {($self->[1][0][$_] =~ m/^(.*\|)?([2-9A-F]CLR_[1-9A-F]|PC[2-9A-F]_[1-9A-F])$/) ? (defined($1) ? ($1, $2) : ('||', $2)) : ()} (0 .. $#{$self->[1][0]});
903  
904 # if context defined
905 if (defined($context)) {
906
907 # get the last key for this context
908 ($chan = $fmt2{"$context|"}) || return();
909
910 # remove the channel number
911 chop($chan);
912
913 # get column slice (selected from %fmt columns)
914 @cols = grep {$self->[1][0][$_] =~ m/^$context\|$chan[1-9A-F]$/} values(%fmt);
915
916 } else {
917
918 # if all keys have a context
919 if (! defined($chan = $fmt2{'||'})) {
920
921 # make lookup hash ignoring context (key => column)
922 %fmt = map {($self->[1][0][$_] =~ m/^(?:.*\|)?([2-9A-F]CLR_[1-9A-F]|PC[2-9A-F]_[1-9A-F])$/) ? ($1, $_) : ()} (0 .. $#{$self->[1][0]});
923
924 # make lookup hash ('||' => last key)
925 %fmt2 = map {($self->[1][0][$_] =~ m/^(?:.*\|)?([2-9A-F]CLR_[1-9A-F]|PC[2-9A-F]_[1-9A-F])$/) ? ('||', $1) : ()} (0 .. $#{$self->[1][0]});
926
927 # get last key for any context
928 ($chan = $fmt2{'||'}) || return();
929
930 # remove the channel number
931 chop($chan);
932
933 # get column slice (selected from %fmt columns)
934 @cols = grep {$self->[1][0][$_] =~ m/^(?:.*\|)?$chan[1-9A-F]$/} values(%fmt);
935
936 } else {
937
938 # remove the channel number
939 chop($chan);
940
941 # get column slice (selected from %fmt columns)
942 @cols = grep {$self->[1][0][$_] =~ m/^$chan[1-9A-F]$/} values(%fmt);
943
944 }
945
946 }
947  
948 # sort by color channel (1-9, A-F)
949 @cols = sort {substr($self->[1][0][$a], -1) cmp substr($self->[1][0][$b], -1)} @cols;
950  
951 # match last format key
952 $self->[1][0][$cols[-1]] =~ m/([2-9A-F])(?:CLR_|_)([1-9A-F])$/;
953  
954 # verify number of format keys
955 (CORE::hex($1) == @cols && CORE::hex($2) == @cols) || croak('wrong number of nCLR keys');
956  
957 # call get/set subroutine
958 _getset($self, 1, $rows, \@cols, $data);
959  
960 }
961  
962 # get/set device data
963 # device data is either RGB, CMYK or nCLR
964 # device values have range (0 - 1)
965 # optional hash contains supplementary parameters
966 # row_slice and column_slice are 1-D array references
967 # data_slice is a Math::Matrix object (2-D array)
968 # replacement_data is a Math::Matrix object or 2-D array
969 # parameters: ([hash]) => returns: (column_slice)
970 # parameters: (row_slice, [hash]) => returns: (data_slice)
971 # parameters: (row_slice, replacement_data, [hash]) => returns: (column_slice)
972 sub device {
973  
974 # local variables
975 my ($hash, $cols, $mult);
976  
977 # get optional hash
978 $hash = pop() if (ref($_[-1]) eq 'HASH');
979  
980 # get remaining parameters
981 my ($self, $rows, $data) = @_;
982  
983 # get column slice or return empty
984 $cols = rgb($self, $hash) || cmyk($self, $hash) || nCLR($self, $hash) || return();
985  
986 # set multiplier (255 if RGB, else 100)
987 $mult = ($self->[1][0][$cols->[0]] =~ m/RGB_R$/) ? 255 : 100;
988  
989 # call get/set subroutine
990 _getset($self, 1, $rows, $cols, $data, sub {map {defined($_) ? $_/$mult : $_} @_}, sub {map {defined($_) ? $_ * $mult : $_} @_});
991  
992 }
993  
994 # get/set CTV data
995 # optional hash contains supplementary parameters
996 # row_slice and column_slice are 1-D array references
997 # data_slice is a Math::Matrix object (2-D array)
998 # replacement_data is a Math::Matrix object or 2-D array
999 # parameters: ([hash]) => returns: (column_slice)
1000 # parameters: (row_slice, [hash]) => returns: (data_slice)
1001 # parameters: (row_slice, replacement_data, [hash]) => returns: (column_slice)
1002 sub ctv {
1003  
1004 # local variables
1005 my ($hash, $cols);
1006  
1007 # get optional hash
1008 $hash = pop() if (ref($_[-1]) eq 'HASH');
1009  
1010 # get remaining parameters
1011 my ($self, $rows, $data) = @_;
1012  
1013 # get column slice, adding optional context prefix
1014 $cols = cols($self, map {defined($hash->{'context'}) ? "$hash->{'context'}|$_" : $_} qw(CTV));
1015  
1016 # call get/set subroutine
1017 _getset($self, 1, $rows, $cols, $data);
1018  
1019 }
1020  
1021 # get/set L*a*b* data
1022 # optional hash contains supplementary parameters
1023 # row_slice and column_slice are 1-D array references
1024 # data_slice is a Math::Matrix object (2-D array)
1025 # replacement_data is a Math::Matrix object or 2-D array
1026 # parameters: ([hash]) => returns: (column_slice)
1027 # parameters: (row_slice, [hash]) => returns: (data_slice)
1028 # parameters: (row_slice, replacement_data, [hash]) => returns: (column_slice)
1029 sub lab {
1030  
1031 # local variables
1032 my ($hash, $cols);
1033  
1034 # get optional hash
1035 $hash = pop() if (ref($_[-1]) eq 'HASH');
1036  
1037 # get remaining parameters
1038 my ($self, $rows, $data) = @_;
1039  
1040 # get column slice, adding optional context prefix
1041 $cols = cols($self, map {defined($hash->{'context'}) ? "$hash->{'context'}|$_" : $_} qw(LAB_L LAB_A LAB_B));
1042  
1043 # call get/set subroutine
1044 _getset($self, 1, $rows, $cols, $data, _lab_encoding($self, $hash));
1045  
1046 }
1047  
1048 # get/set XYZ data
1049 # optional hash contains supplementary parameters
1050 # row_slice and column_slice are 1-D array references
1051 # data_slice is a Math::Matrix object (2-D array)
1052 # replacement_data is a Math::Matrix object or 2-D array
1053 # parameters: ([hash]) => returns: (column_slice)
1054 # parameters: (row_slice, [hash]) => returns: (data_slice)
1055 # parameters: (row_slice, replacement_data, [hash]) => returns: (column_slice)
1056 sub xyz {
1057  
1058 # local variables
1059 my ($hash, $cols);
1060  
1061 # get optional hash
1062 $hash = pop() if (ref($_[-1]) eq 'HASH');
1063  
1064 # get remaining parameters
1065 my ($self, $rows, $data) = @_;
1066  
1067 # get column slice, adding optional context prefix
1068 $cols = cols($self, map {defined($hash->{'context'}) ? "$hash->{'context'}|$_" : $_} qw(XYZ_X XYZ_Y XYZ_Z));
1069  
1070 # call get/set subroutine
1071 _getset($self, 1, $rows, $cols, $data, _xyz_encoding($self, $cols, $hash));
1072  
1073 }
1074  
1075 # get/set density data
1076 # optional hash contains supplementary parameters
1077 # row_slice and column_slice are 1-D array references
1078 # data_slice is a Math::Matrix object (2-D array)
1079 # replacement_data is a Math::Matrix object or 2-D array
1080 # parameters: ([hash]) => returns: (column_slice)
1081 # parameters: (row_slice, [hash]) => returns: (data_slice)
1082 # parameters: (row_slice, replacement_data, [hash]) => returns: (column_slice)
1083 sub density {
1084  
1085 # local variables
1086 my ($hash, $cols);
1087  
1088 # get optional hash
1089 $hash = pop() if (ref($_[-1]) eq 'HASH');
1090  
1091 # get remaining parameters
1092 my ($self, $rows, $data) = @_;
1093  
1094 # get column slice
1095 $cols = cols($self, map {defined($hash->{'context'}) ? "$hash->{'context'}|$_" : $_} qw(D_RED D_GREEN D_BLUE D_VIS));
1096  
1097 # call get/set subroutine
1098 _getset($self, 1, $rows, $cols, $data, _density_encoding($self, $hash));
1099  
1100 }
1101  
1102 # get/set reflectance/transmittance data
1103 # optional hash contains supplementary parameters
1104 # row_slice and column_slice are 1-D array references
1105 # data_slice is a Math::Matrix object (2-D array)
1106 # replacement_data is a Math::Matrix object or 2-D array
1107 # parameters: ([hash]) => returns: (column_slice)
1108 # parameters: (row_slice, [hash]) => returns: (data_slice)
1109 # parameters: (row_slice, replacement_data, [hash]) => returns: (column_slice)
1110 sub rgbv {
1111  
1112 # local variables
1113 my ($hash, $cols);
1114  
1115 # get optional hash
1116 $hash = pop() if (ref($_[-1]) eq 'HASH');
1117  
1118 # get remaining parameters
1119 my ($self, $rows, $data) = @_;
1120  
1121 # get column slice
1122 $cols = cols($self, map {defined($hash->{'context'}) ? "$hash->{'context'}|$_" : $_} qw(R_RED R_GREEN R_BLUE R_VIS));
1123  
1124 # call get/set subroutine
1125 _getset($self, 1, $rows, $cols, $data, _rgbv_encoding($self, $hash));
1126  
1127 }
1128  
1129 # get/set spectral data
1130 # optional hash contains supplementary parameters
1131 # row_slice and column_slice are 1-D array references
1132 # data_slice is a Math::Matrix object (2-D array)
1133 # replacement_data is a Math::Matrix object or 2-D array
1134 # parameters: ([hash]) => returns: (column_slice)
1135 # parameters: (row_slice, [hash]) => returns: (data_slice)
1136 # parameters: (row_slice, replacement_data, [hash]) => returns: (column_slice)
1137 sub spectral {
1138  
1139 # local variables
1140 my ($hash, $fields, $cols);
1141  
1142 # get optional hash
1143 $hash = pop() if (ref($_[-1]) eq 'HASH');
1144  
1145 # get remaining parameters
1146 my ($self, $rows, $data) = @_;
1147  
1148 # get spectral fields array
1149 $fields = _spectral($self, $hash->{'context'});
1150  
1151 # get column slice from spectral fields array
1152 $cols = defined($fields) ? [map {$_->[0]} @{$fields}] : undef;
1153  
1154 # call get/set subroutine
1155 _getset($self, 1, $rows, $cols, $data);
1156  
1157 }
1158  
1159 # get spectral wavelength array
1160 # array is sorted (low to high)
1161 # parameters: ([hash])
1162 # returns: (ref_to_wavelength_array)
1163 sub wavelength {
1164  
1165 # get parameters
1166 my ($self, $hash) = @_;
1167  
1168 # get spectral fields array or return empty
1169 my $fields = _spectral($self, $hash->{'context'}) || return();
1170  
1171 # return
1172 return([map {$_->[1]} @{$fields}]);
1173  
1174 }
1175  
1176 # get spectral wavelength range
1177 # structure is [start_nm, end_nm, increment]
1178 # parameters: ([hash])
1179 # returns: (range)
1180 sub nm {
1181  
1182 # get parameters
1183 my ($self, $hash) = @_;
1184
1185 # local variables
1186 my ($fields, $inc);
1187  
1188 # get spectral fields array or return empty
1189 $fields = _spectral($self, $hash->{'context'}) || return();
1190  
1191 # compute increment
1192 $inc = $fields->[1][1] - $fields->[0][1];
1193  
1194 # verify wavelength increment
1195 ($inc > 0 && abs($#{$fields} * $inc - $fields->[-1][1] + $fields->[0][1]) < 1E-12) || warn('inconsistent wavelength values');
1196  
1197 # return range
1198 return([$fields->[0][1], $fields->[-1][1], $inc]);
1199  
1200 }
1201  
1202 # get illuminant white point
1203 # parameters: ([hash])
1204 # returns: (XYZ_vector)
1205 sub iwtpt {
1206  
1207 # get parameters
1208 my ($self, $hash) = @_;
1209  
1210 # local variables
1211 my ($encode, $cols, $iwtpt, $get);
1212  
1213 # extract encoding hash
1214 $encode = {'encoding' => delete($hash->{'encoding'})};
1215  
1216 # get XYZ or L*a*b* column slice
1217 $cols = xyz($self, $hash) || lab($self, $hash) || croak('illuminant white point XYZ or L*a*b* column slice undefined');
1218  
1219 # get illuminant white point
1220 $iwtpt = _illumWP($self, $cols, $hash);
1221  
1222 # get code reference
1223 ($get) = _xyz_encoding($self, $cols, $encode);
1224  
1225 # return encoded XYZ vector
1226 return([&$get(@{$iwtpt})]);
1227  
1228 }
1229  
1230 # get media white point
1231 # parameters: ([hash])
1232 # returns: (XYZ_vector)
1233 sub wtpt {
1234  
1235 # get parameters
1236 my ($self, $hash) = @_;
1237  
1238 # local variables
1239 my ($encode, $cols, $get);
1240  
1241 # extract encoding hash
1242 $encode = {'encoding' => delete($hash->{'encoding'})};
1243  
1244 # get XYZ or L*a*b* column slice
1245 $cols = xyz($self, $hash) || lab($self, $hash) || croak('white point XYZ or L*a*b* column slice undefined');
1246  
1247 # if media white point undefined in colorimetry array
1248 if (! defined($self->[2][3][$cols->[0]])) {
1249
1250 # compute media white point or return undefined
1251 (_mediaWP($self, $cols, $hash)) || return();
1252
1253 }
1254  
1255 # get code reference
1256 ($get) = _xyz_encoding($self, $cols, $encode);
1257  
1258 # return encoded XYZ vector
1259 return([&$get(@{$self->[2][3]}[@{$cols}])]);
1260  
1261 }
1262  
1263 # get media black point
1264 # parameters: ([hash])
1265 # returns: (XYZ_vector)
1266 sub bkpt {
1267  
1268 # get parameters
1269 my ($self, $hash) = @_;
1270  
1271 # local variables
1272 my ($encode, $cols, $get);
1273  
1274 # extract encoding hash
1275 $encode = {'encoding' => delete($hash->{'encoding'})};
1276  
1277 # get XYZ or L*a*b* column slice
1278 $cols = xyz($self, $hash) || lab($self, $hash) || croak('black point XYZ or L*a*b* column slice undefined');
1279  
1280 # if media black point undefined in colorimetry array
1281 if (! defined($self->[2][4][$cols->[0]])) {
1282
1283 # compute media black point or return undefined
1284 (_mediaBP($self, $cols, $hash)) || return();
1285
1286 }
1287  
1288 # get code reference
1289 ($get) = _xyz_encoding($self, $cols, $encode);
1290  
1291 # return encoded XYZ vector
1292 return([&$get(@{$self->[2][4]}[@{$cols}])]);
1293  
1294 }
1295  
1296 # compute media OBA index
1297 # requires M1 and M2 measurements
1298 # requires device values -or- sample number
1299 # optional hash keys are 'sample', 'device', and 'context'
1300 # parameters: ([hash])
1301 # returns: (oba_index)
1302 # returns: (M1_XYZ_vector, M2_XYZ_vector)
1303 sub oba_index {
1304  
1305 # get parameters
1306 my ($self, $hash) = @_;
1307  
1308 # local variables
1309 my ($sample, $dev, $mwv, $wps, $wpdata, $context1, $context2, $m1, $m2, @xyz1, @xyz2, $nm, $color);
1310  
1311 # if 'sample' defined
1312 if (defined($hash->{'sample'})) {
1313
1314 # get sample from hash
1315 $sample = $hash->{'sample'};
1316
1317 # if valid sample number
1318 if (Scalar::Util::looks_like_number($sample) && $sample == int($sample) && $sample > 0 && $sample <= $#{$self->[1]}) {
1319
1320 # get sample data row
1321 $wpdata = $self->[1][$sample];
1322
1323 } else {
1324
1325 # warn
1326 warn('invalid sample number');
1327
1328 # return empty
1329 return();
1330
1331 }
1332
1333 } else {
1334
1335 # if device data (using 'device' context)
1336 if ($dev = device($self, {'context' => $hash->{'device'}})) {
1337
1338 # set media white device value (1 if RGB, 0 otherwise)
1339 $mwv = ($self->[1][0][$dev->[0]] =~ m/RGB_R$/) ? 255 : 0;
1340
1341 # find paper white samples
1342 $wps = find($self, sub {@_ == grep {$_ == $mwv} @_}, [], $dev);
1343
1344 # if samples found
1345 if (@{$wps}) {
1346
1347 # add average paper white sample row
1348 add_avg($self, $wps);
1349
1350 # get sample data row
1351 $wpdata = pop(@{$self->[1]});
1352
1353 } else {
1354
1355 # warn
1356 warn('no paper white samples');
1357
1358 # return empty
1359 return();
1360
1361 }
1362
1363 } else {
1364
1365 # warn
1366 warn('no sample value or device data');
1367
1368 # return empty
1369 return();
1370
1371 }
1372
1373 }
1374  
1375 # if 'context' defined
1376 if (defined($hash->{'context'})) {
1377
1378 # if context an array reference containing two scalars
1379 if (ref($hash->{'context'}) eq 'ARRAY' && ! ref($hash->{'context'}->[0]) && ! ref($hash->{'context'}->[1])) {
1380
1381 # get specified 'M1' context
1382 $context1 = $hash->{'context'}->[0];
1383
1384 # get specified 'M2' context
1385 $context2 = $hash->{'context'}->[1];
1386
1387 } else {
1388
1389 # warn
1390 warn('OBA context is an array reference containing M1 and M2 contexts');
1391
1392 # return empty
1393 return();
1394
1395 }
1396
1397 } else {
1398
1399 # use standard 'M1' context
1400 $context1 = 'M1_Measurement';
1401
1402 # use standard 'M2' context
1403 $context2 = 'M2_Measurement';
1404
1405 }
1406  
1407 # if M1 and M2 spectral data
1408 if (($m1 = spectral($self, {'context' => $context1})) && ($m2 = spectral($self, {'context' => $context2}))) {
1409
1410 # get spectral range
1411 $nm = nm($self, {'context' => $context1});
1412
1413 # if increment is 10 or 20 nm
1414 if ($nm->[2] == 10 || $nm->[2] == 20) {
1415
1416 # make ASTM color object
1417 $color = ICC::Support::Color->new({'illuminant' => 'D50', 'increment' => $nm->[2]});
1418
1419 } else {
1420
1421 # make CIE color object
1422 $color = ICC::Support::Color->new({'illuminant' => ['CIE', 'D50'], 'increment' => $nm->[2]});
1423
1424 }
1425
1426 # compute M1 and M2 XYZ values
1427 @xyz1 = $color->transform(@{$wpdata}[@{$m1}]);
1428 @xyz2 = $color->transform(@{$wpdata}[@{$m2}]);
1429
1430 # if M1 and M2 XYZ data
1431 } elsif (($m1 = xyz($self, {'context' => $context1})) && ($m2 = xyz($self, {'context' => $context2}))) {
1432
1433 # get M1 and M2 XYZ values (assumes D50 illumination)
1434 @xyz1 = @{$wpdata}[@{$m1}];
1435 @xyz2 = @{$wpdata}[@{$m2}];
1436
1437 # if M1 and M2 L*a*b* data
1438 } elsif (($m1 = lab($self, {'context' => $context1})) && ($m2 = lab($self, {'context' => $context2}))) {
1439
1440 # compute M1 and M2 XYZ values (D50 illumination)
1441 @xyz1 = ICC::Shared::_Lab2XYZ(@{$wpdata}[@{$m1}], ICC::Shared::D50);
1442 @xyz2 = ICC::Shared::_Lab2XYZ(@{$wpdata}[@{$m2}], ICC::Shared::D50);
1443
1444 } else {
1445
1446 # warn
1447 warn('M1 and M2 data required for OBA index');
1448
1449 # return empty
1450 return();
1451
1452 }
1453  
1454 # return array (XYZ media white points) or scalar (OBA index)
1455 return(wantarray ? (\@xyz1, \@xyz2) : ($xyz1[2] - $xyz2[2])/82.49);
1456  
1457 }
1458  
1459 # get chromatic adaptation transform (CAT) object
1460 # a CAT is optionally created when adding XYZ data
1461 # optional hash contains supplementary parameters
1462 # parameters: ([hash])
1463 # returns: (CAT_object)
1464 sub cat {
1465  
1466 # get parameters
1467 my ($self, $hash) = @_;
1468  
1469 # local variables
1470 my ($cols, $cat);
1471  
1472 # get column slice, adding optional context prefix
1473 $cols = cols($self, map {defined($hash->{'context'}) ? "$hash->{'context'}|$_" : $_} qw(XYZ_X XYZ_Y XYZ_Z));
1474  
1475 # return if slice undefined
1476 return() if (! defined($cols));
1477  
1478 # get CAT or illuminant
1479 $cat = $self->[2][2][$cols->[0]];
1480  
1481 # return CAT if defined
1482 return((defined($cat) && UNIVERSAL::isa($cat, 'ICC::Profile::matf')) ? $cat : ());
1483  
1484 }
1485  
1486 # get Color object
1487 # a Color object is created when adding XYZ data from spectral data
1488 # optional hash contains supplementary parameters
1489 # parameters: ([hash])
1490 # returns: (Color_object)
1491 sub color {
1492  
1493 # get parameters
1494 my ($self, $hash) = @_;
1495  
1496 # local variables
1497 my ($cols, $color);
1498  
1499 # get column slice, adding optional context prefix
1500 $cols = cols($self, map {defined($hash->{'context'}) ? "$hash->{'context'}|$_" : $_} qw(XYZ_X XYZ_Y XYZ_Z));
1501  
1502 # return if slice undefined
1503 return() if (! defined($cols));
1504  
1505 # get CAT or illuminant
1506 $color = $self->[2][1][$cols->[0]];
1507  
1508 # return CAT if defined
1509 return((defined($color) && UNIVERSAL::isa($color, 'ICC::Support::Color')) ? $color : ());
1510  
1511 }
1512  
1513 # append rows to data array
1514 # data matrix is the 2-D array of data values to be appended
1515 # column slice is a reference to an array of data matrix column indices
1516 # parameters: (data_matrix, [column_slice])
1517 # returns: (row_slice)
1518 sub add_rows {
1519  
1520 # get parameters
1521 my ($self, $matrix, $cols) = @_;
1522  
1523 # if object contains data
1524 if ($#{$self->[1]} || @{$self->[1][0]}) {
1525
1526 # set offset to upper index + 1
1527 my $offset = $#{$self->[1]} + 1;
1528
1529 # call 'splice_rows'
1530 splice_rows($self, $offset, 0, $matrix, $cols);
1531
1532 # return row slice
1533 return([$offset .. ($offset + $#{$matrix})]);
1534
1535 # new object
1536 } else {
1537
1538 # call 'splice_rows' (deleting first row)
1539 splice_rows($self, 0, 1, $matrix, $cols);
1540
1541 # return row slice
1542 return([0 .. $#{$matrix}]);
1543
1544 }
1545
1546 }
1547  
1548 # append columns to data array
1549 # data matrix is the 2-D array of data values to be appended
1550 # format is a reference to an array of DATA_FORMAT keywords
1551 # parameters: (data_matrix, [format])
1552 # returns: (column_slice)
1553 sub add_cols {
1554  
1555 # get parameters
1556 my ($self, $matrix, $format) = @_;
1557  
1558 # verify matrix a 2-D array or Math::Matrix object
1559 (ref($matrix) eq 'ARRAY' && ref($matrix->[0]) eq 'ARRAY') || (UNIVERSAL::isa($matrix, 'Math::Matrix')) || croak ('invalid matrix parameter');
1560  
1561 # if format supplied
1562 if (defined($format)) {
1563
1564 # verify format is 1-D array of scalars
1565 (ref($format) eq 'ARRAY' && @{$format} == grep {! ref()} @{$format}) || croak('invalid format parameter');
1566
1567 # verify format and matrix have same number of columns
1568 (@{$format} == @{$matrix->[0]}) || croak('format and matrix have different number of columns');
1569
1570 # add format to matrix
1571 $matrix = [$format, @{$matrix}];
1572
1573 }
1574
1575 # if object contains data
1576 if ($#{$self->[1]} || @{$self->[1][0]}) {
1577
1578 # warn if matrix and object have different number of rows
1579 (@{$matrix} == @{$self->[1]}) || carp('matrix and object have different number of rows');
1580
1581 # set offset to upper index + 1
1582 my $offset = $#{$self->[1][0]} + 1;
1583
1584 # call 'splice_cols'
1585 splice_cols($self, $offset, 0, $matrix);
1586
1587 # return column slice
1588 return([$offset .. ($offset + $#{$matrix->[0]})]);
1589
1590 # new object
1591 } else {
1592
1593 # call 'splice_rows' (deleting first row)
1594 splice_rows($self, 0, 1, $matrix);
1595
1596 # return column slice
1597 return([0 .. $#{$self->[1][0]}]);
1598
1599 }
1600
1601 }
1602  
1603 # add average sample
1604 # assumes device values (if any) are same for each sample
1605 # averages measurement values - spectral, XYZ, L*a*b* or density
1606 # L*a*b* values are converted to xyz for averaging, then back to L*a*b*
1607 # density values are converted to reflectance for averaging, then back to density
1608 # returns row slice of the appended average sample
1609 # parameters: (row_slice, [hash])
1610 # returns: (row_slice)
1611 sub add_avg {
1612  
1613 # get parameters
1614 my ($self, $rows, $hash) = @_;
1615  
1616 # local variables
1617 my ($c1, $c2, $c3, @id, @name);
1618  
1619 # flatten row slice
1620 $rows = ICC::Shared::flatten($rows);
1621  
1622 # resolve empty row slice
1623 $rows = [1 .. $#{$self->[1]}] if (@{$rows} == 0);
1624  
1625 # get averaging groups
1626 ($c1, $c2, $c3) = _avg_groups($self, $hash);
1627  
1628 # for each format field
1629 for my $i (0 .. $#{$self->[1][0]}) {
1630
1631 # add column if SAMPLE_ID field
1632 push(@id, $i) if ($self->[1][0][$i] =~ m/^(?:.*\|)?(?:SAMPLE_ID|SampleID)$/);
1633
1634 # add column if SAMPLE_NAME field
1635 push(@name, $i) if ($self->[1][0][$i] =~ m/^(?:.*\|)?SAMPLE_NAME$/);
1636
1637 }
1638  
1639 # return average sample
1640 return([_add_avg($self, $rows, $c1, $c2, $c3, \@id, \@name, $hash)]);
1641  
1642 }
1643  
1644 # add format keys
1645 # keys are appended to row 0 of the data array
1646 # note: format_keys is a list of scalars and/or array references
1647 # note: format_keys are saved as given, with or without context
1648 # parameters: (format_keys)
1649 # returns: (column_slice)
1650 sub add_fmt {
1651  
1652 # get parameters
1653 my $self = shift();
1654  
1655 # local variables
1656 my (@keys, $i, %fmt);
1657  
1658 # flatten format key list
1659 @keys = @{ICC::Shared::flatten(@_)};
1660  
1661 # get upper column index
1662 $i = $#{$self->[1][0]};
1663  
1664 # make format lookup hash of existing keys
1665 %fmt = map {$self->[1][0][$_], $_} (0 .. $#{$self->[1][0]});
1666  
1667 # warn if duplicate keys
1668 warn('adding duplicate format key(s)') if (grep {exists($fmt{$_})} @keys);
1669  
1670 # push format keys onto format row
1671 push(@{$self->[1][0]}, @keys);
1672  
1673 # return slice array reference
1674 return([$i + 1 .. $#{$self->[1][0]}]);
1675  
1676 }
1677  
1678 # append CTV data to data array
1679 # computed from L*a*b* data, XYZ data, or spectral data
1680 # if CTV data already exists, return those slices
1681 # adds L*a*b* data, and XYZ data if missing
1682 # parameters: ([hash])
1683 # returns: (column_slice)
1684 sub add_ctv {
1685  
1686 # get parameters
1687 my ($self, $hash) = @_;
1688  
1689 # local variables
1690 my ($context, $added, $cols, $Lab, $color);
1691 my ($iwtpt, $WPxyz, @wtpt, $dev, $mwv, $coef, @Ls);
1692 my ($den, $a, $b, $c, $d, $e, $f, $mat);
1693  
1694 # get base context
1695 $context = $hash->{'context'};
1696  
1697 # get added context
1698 $added = defined($hash->{'added'}) ? $hash->{'added'} : $context;
1699  
1700 # return column slice if CTV data already exists
1701 return($cols) if ($cols = _cols($self, map {defined($added) ? "$added|$_" : $_} qw(CTV)));
1702  
1703 # if L*a*b* exists, or is added
1704 if ($Lab = (_cols($self, map {defined($context) ? "$context|$_" : $_} qw(LAB_L LAB_A LAB_B)) || add_lab($self, $hash))) {
1705
1706 # get L*a*b* colorimetry hash
1707 $color = $self->[2][6][$Lab->[0]];
1708
1709 # for each possible colorimetry key
1710 for my $key (qw(illuminant observer increment bandpass cat)) {
1711
1712 # if key is specified
1713 if (defined($hash->{$key})) {
1714
1715 # if YAML strings differ
1716 if (YAML::Tiny::Dump($hash->{$key}) ne YAML::Tiny::Dump($color->{$key})) {
1717
1718 # print warning
1719 warn("$key parameter differs from source");
1720
1721 }
1722
1723 }
1724
1725 }
1726
1727 # if 'context' and 'added' keys are undefined, and L*a*b* source has context
1728 if (! defined($added) && $self->[1][0][$Lab->[0]] =~ m/^(.*)\|/) {
1729
1730 # set 'added' to L*a*b* context
1731 $added = $1;
1732
1733 }
1734
1735 # add CTV columns slice
1736 $cols = add_fmt($self, map {defined($added) ? "$added|$_" : $_} qw(CTV));
1737
1738 # get supplied illuminant white point
1739 $iwtpt = $hash->{'iwtpt'};
1740
1741 # if supplied illuminant white point is valid
1742 if (defined($iwtpt) && (3 == grep {defined() && ! ref() && $_ > 0} @{$iwtpt})) {
1743
1744 # use it
1745 $WPxyz = $iwtpt;
1746
1747 # if XYZ illuminant white point is valid
1748 } elsif (3 == grep {defined() && ! ref() && $_ > 0} @{$self->[2][2]}[@{$Lab}]) {
1749
1750 # use it
1751 $WPxyz = [@{$self->[2][2]}[@{$Lab}]];
1752
1753 } else {
1754
1755 # use D50
1756 $WPxyz = ICC::Shared::D50;
1757
1758 }
1759
1760 # if media white point undefined in colorimetry array
1761 if (! defined($self->[2][3][$Lab->[0]])) {
1762
1763 # compute media white point or return undefined
1764 (_mediaWP($self, $Lab, $hash)) || return();
1765
1766 }
1767
1768 # get media white point (Lx, Ly, Lz)
1769 @wtpt = ICC::Shared::_xyz2Lxyz($self->[2][3][$Lab->[0]]/$WPxyz->[0], $self->[2][3][$Lab->[1]]/$WPxyz->[1], $self->[2][3][$Lab->[2]]/$WPxyz->[2]);
1770
1771 # get device column slice
1772 $dev = device($self, {'context' => $hash->{'device'}});
1773
1774 # set media white device value (255 if RGB, 0 otherwise)
1775 $mwv = ($self->[1][0][$dev->[0]] =~ m/RGB_R$/) ? 255 : 0;
1776
1777 # set origin
1778 $self->[2][0][$cols->[0]] = $Lab;
1779
1780 # save media white CTV (0)
1781 $self->[2][3][$cols->[0]] = 0;
1782
1783 # save colorimetry hash
1784 @{$self->[2][6]}[$cols->[0]] = $color;
1785
1786 # get coefficient array
1787 $coef = defined($hash->{'coef'}) ? $hash->{'coef'} : [1, 1, 1, 0, 0, 0];
1788
1789 # compute denominator
1790 $den = $coef->[0]**2 + $coef->[1]**2 + $coef->[2]**2;
1791
1792 # compute matrix elements
1793 $a = ($coef->[0]**2 + $coef->[4]**2 + $coef->[5]**2)/$den;
1794 $b = ($coef->[1]**2 + $coef->[3]**2 + $coef->[5]**2)/$den;
1795 $c = ($coef->[2]**2 + $coef->[3]**2 + $coef->[4]**2)/$den;
1796 $d = -$coef->[5]**2/$den;
1797 $e = -$coef->[4]**2/$den;
1798 $f = -$coef->[3]**2/$den;
1799
1800 # make Mahalanobis matrix
1801 $mat = [
1802 [$a, $d, $e],
1803 [$d, $b, $f],
1804 [$e, $f, $c]
1805 ];
1806
1807 # bless the object
1808 bless($mat, 'Math::Matrix');
1809
1810 # for each sample
1811 for my $i (1 .. $#{$self->[1]}) {
1812
1813 # if all device channels are white
1814 if (@{$dev} == grep {$_ == $mwv} @{$self->[1][$i]}[@{$dev}]) {
1815
1816 # save CTV (0)
1817 $self->[1][$i][$cols->[0]] = 0;
1818
1819 } else {
1820
1821 # compute sample Lx, Ly, Lz values
1822 @Ls = ICC::Shared::_Lab2Lxyz(@{$self->[1][$i]}[@{$Lab}]);
1823
1824 # save CTV (computed as Mahalanobis distance)
1825 $self->[1][$i][$cols->[0]] = _mahal(\@wtpt, \@Ls, $mat);
1826
1827 }
1828
1829 }
1830
1831 } else {
1832
1833 # warn
1834 warn('spectral, XYZ or L*a*b* data is required');
1835
1836 # return empty
1837 return();
1838
1839 }
1840  
1841 # return column slice
1842 return($cols);
1843  
1844 }
1845  
1846 # append L*a*b* data to data array
1847 # computed from XYZ data or spectral data
1848 # if L*a*b* data already exists, returns that slice
1849 # adds XYZ data, if only spectral data exists
1850 # parameter: ([hash])
1851 # returns: (column_slice)
1852 sub add_lab {
1853  
1854 # get parameters
1855 my ($self, $hash) = @_;
1856  
1857 # local variables
1858 my ($context, $added, $cols, $xyz, $color, $iwtpt, $WPxyz);
1859  
1860 # get base context
1861 $context = $hash->{'context'};
1862  
1863 # get added context
1864 $added = defined($hash->{'added'}) ? $hash->{'added'} : $context;
1865  
1866 # return column slice if L*a*b* data already exists
1867 return($cols) if ($cols = _cols($self, map {defined($added) ? "$added|$_" : $_} qw(LAB_L LAB_A LAB_B)));
1868  
1869 # if XYZ data exists, or is added
1870 if ($xyz = (_cols($self, map {defined($context) ? "$context|$_" : $_} qw(XYZ_X XYZ_Y XYZ_Z)) || add_xyz($self, $hash))) {
1871
1872 # get XYZ colorimetry hash
1873 $color = $self->[2][6][$xyz->[0]];
1874
1875 # for each possible colorimetry key
1876 for my $key (qw(illuminant observer increment bandpass cat)) {
1877
1878 # if key is specified
1879 if (defined($hash->{$key})) {
1880
1881 # if YAML strings differ
1882 if (YAML::Tiny::Dump($hash->{$key}) ne YAML::Tiny::Dump($color->{$key})) {
1883
1884 # print warning
1885 warn("$key parameter differs from source");
1886
1887 }
1888
1889 }
1890
1891 }
1892
1893 # if 'context' and 'added' keys are undefined, and XYZ source has context
1894 if (! defined($added) && $self->[1][0][$xyz->[0]] =~ m/^(.*)\|/) {
1895
1896 # set 'added' to XYZ context
1897 $added = $1;
1898
1899 }
1900
1901 # add L*a*b* columns slice
1902 $cols = add_fmt($self, map {defined($added) ? "$added|$_" : $_} qw(LAB_L LAB_A LAB_B));
1903
1904 # get supplied illuminant white point
1905 $iwtpt = $hash->{'iwtpt'};
1906
1907 # if supplied illuminant white point is valid
1908 if (defined($iwtpt) && (3 == grep {defined() && ! ref() && $_ > 0} @{$iwtpt})) {
1909
1910 # use it
1911 $WPxyz = $iwtpt;
1912
1913 # if XYZ illuminant white point is valid
1914 } elsif (3 == grep {defined() && ! ref() && $_ > 0} @{$self->[2][2]}[@{$xyz}]) {
1915
1916 # use it
1917 $WPxyz = [@{$self->[2][2]}[@{$xyz}]];
1918
1919 } else {
1920
1921 # use D50
1922 $WPxyz = ICC::Shared::D50;
1923
1924 }
1925
1926 # set origin
1927 @{$self->[2][0]}[@{$cols}] = ($xyz) x 3;
1928
1929 # save illuminant white point
1930 @{$self->[2][2]}[@{$cols}] = @{$WPxyz};
1931
1932 # save colorimetry hash
1933 @{$self->[2][6]}[@{$cols}] = ($color) x 3;
1934
1935 # for each sample
1936 for my $s (1 .. $#{$self->[1]}) {
1937
1938 # compute L*a*b* values from XYZ values
1939 @{$self->[1][$s]}[@{$cols}] = ICC::Shared::_XYZ2Lab(@{$self->[1][$s]}[@{$xyz}], $WPxyz);
1940
1941 }
1942
1943 } else {
1944
1945 # warn
1946 warn('spectral or XYZ data is required');
1947
1948 # return empty
1949 return();
1950
1951 }
1952  
1953 # return column slice
1954 return($cols);
1955  
1956 }
1957  
1958 # append XYZ data to data array
1959 # computed from spectral data or L*a*b* data
1960 # if XYZ data already exists, returns that slice
1961 # default colorimetry is D50, 2 degree observer
1962 # parameters: ([hash])
1963 # returns: (column_slice)
1964 sub add_xyz {
1965  
1966 # get parameters
1967 my ($self, $hash) = @_;
1968  
1969 # local variables
1970 my ($oba, $spec1, $spec2, $context, $added);
1971 my ($spec, $color, $illum, $specv, $nm, $cols);
1972 my ($cat, $spectral, $xyz, $Lab, @WPlab, $WPxyz);
1973  
1974 # if 'oba' defined
1975 if (defined($hash->{'oba'})) {
1976
1977 # get oba factor
1978 $oba = $hash->{'oba'};
1979
1980 # if 'context' defined
1981 if (defined($hash->{'context'})) {
1982
1983 # if context an array reference containing two scalars
1984 if (ref($hash->{'context'}) eq 'ARRAY' && ! ref($hash->{'context'}->[0]) && ! ref($hash->{'context'}->[1])) {
1985
1986 # get specified 'M1' spectral slice
1987 $spec1 = spectral($self, {'context' => $hash->{'context'}->[0]});
1988
1989 # get specified 'M2' spectral slice
1990 $spec2 = spectral($self, {'context' => $hash->{'context'}->[1]});
1991
1992 # use specified 'M2' context
1993 $context = $hash->{'context'}->[1];
1994
1995 } else {
1996
1997 # warn
1998 warn('OBA context is an array reference containing M1 and M2 contexts');
1999
2000 # return empty
2001 return();
2002
2003 }
2004
2005 } else {
2006
2007 # get spectral slice using standard 'M1' context
2008 $spec1 = spectral($self, {'context' => 'M1_Measurement'});
2009
2010 # get spectral slice using standard 'M2' context
2011 $spec2 = spectral($self, {'context' => 'M2_Measurement'});
2012
2013 # use standard 'M2' context
2014 $context = 'M2_Measurement';
2015
2016 }
2017
2018 # verify spectral slices
2019 if (! $spec1 || ! $spec2 || $#{$spec1} != $#{$spec2}) {
2020
2021 # warn
2022 warn('M1 and M2 spectral data required for OBA effect');
2023
2024 # return empty
2025 return();
2026
2027 }
2028
2029 # get added context
2030 $added = defined($hash->{'added'}) ? $hash->{'added'} : 'OBA';
2031
2032 } else {
2033
2034 # get base context
2035 $context = $hash->{'context'};
2036
2037 # get added context
2038 $added = defined($hash->{'added'}) ? $hash->{'added'} : $context;
2039
2040 }
2041  
2042 # return column slice if XYZ data already exists
2043 return($cols) if ($cols = _cols($self, map {defined($added) ? "$added|$_" : $_} qw(XYZ_X XYZ_Y XYZ_Z)));
2044  
2045 # if spectral data exists
2046 if (test($self, 'SPECTRAL', $context)) {
2047
2048 # get spectral slice
2049 $spec = spectral($self, {'context' => $context});
2050
2051 # add chart wavelength range to hash
2052 $hash->{'range'} = nm($self, {'context' => $context});
2053
2054 # make empty 'Color.pm' object
2055 $color = ICC::Support::Color->new();
2056
2057 # if illuminant is defined, an array reference
2058 if (defined($hash->{'illuminant'}) && ref($hash->{'illuminant'}) eq 'ARRAY') {
2059
2060 # if illuminant is ['DATA'] (ProfileMaker convention)
2061 if (defined($hash->{'illuminant'}->[0]) && $hash->{'illuminant'}->[0] eq 'DATA') {
2062
2063 # verify chart object contains illuminant data
2064 (defined($self->[0]{'illuminant'}) && ref($self->[0]{'illuminant'}) eq 'ARRAY') || croak('no illuminant data');
2065
2066 # make new chart object from illuminant data
2067 $illum = ICC::Support::Chart->new($self->[0]{'illuminant'});
2068
2069 # get spectral values
2070 ($specv = $illum->spectral([1])->[0]) || croak('illuminant chart has no spectral data');
2071
2072 # get wavelength range
2073 $nm = $illum->nm();
2074
2075 # update 'illuminant' value in hash
2076 $hash->{'illuminant'} = [$nm, $specv];
2077
2078 }
2079
2080 # initialize object for CIE method
2081 ICC::Support::Color::_cie($color, $hash);
2082
2083 } else {
2084
2085 # initialize object for ASTM method
2086 ICC::Support::Color::_astm($color, $hash);
2087
2088 }
2089
2090 # if 'context' and 'added' keys are undefined, and spectral source has context
2091 if (! defined($added) && $self->[1][0][$spec->[0]] =~ m/^(.*)\|/) {
2092
2093 # set 'added' to spectral context
2094 $added = $1;
2095
2096 }
2097
2098 # add XYZ columns slice
2099 $cols = add_fmt($self, map {defined($added) ? "$added|$_" : $_} qw(XYZ_X XYZ_Y XYZ_Z));
2100
2101 # set origin
2102 @{$self->[2][0]}[@{$cols}] = ($spec) x 3;
2103
2104 # save reference to Color.pm object
2105 @{$self->[2][1]}[@{$cols}] = ($color) x 3;
2106
2107 # if chromatic adaptation transform (cat) is specified
2108 if (defined($hash->{'cat'})) {
2109
2110 # if cat is 'matf' object
2111 if (UNIVERSAL::isa($hash->{'cat'}, 'ICC::Profile::matf')) {
2112
2113 # use it
2114 $cat = $hash->{'cat'};
2115
2116 # if cat is 'bradford'
2117 } elsif ($hash->{'cat'} eq 'bradford') {
2118
2119 # make 'bradford' object
2120 $cat = ICC::Profile::matf->bradford($color->iwtpt());
2121
2122 # if cat is 'cat02'
2123 } elsif ($hash->{'cat'} eq 'cat02') {
2124
2125 # make 'cat02' object
2126 $cat = ICC::Profile::matf->cat02($color->iwtpt());
2127
2128 # if cat is 'quasi'
2129 } elsif ($hash->{'cat'} eq 'quasi') {
2130
2131 # make 'quasi' object
2132 $cat = ICC::Profile::matf->quasi($color->iwtpt());
2133
2134 } else {
2135
2136 # warn
2137 warn('invalid cat type');
2138
2139 }
2140
2141 }
2142
2143 # if cat defined
2144 if (defined($cat)) {
2145
2146 # save cat reference
2147 @{$self->[2][2]}[@{$cols}] = ($cat) x 3;
2148
2149 } else {
2150
2151 # save white point
2152 @{$self->[2][2]}[@{$cols}] = @{$color->iwtpt()};
2153
2154 }
2155
2156 # save colorimetry hash
2157 @{$self->[2][6]}[@{$cols}] = ({map {defined($hash->{$_}) ? ($_, $hash->{$_}) : ()} qw(illuminant observer bandpass method ibandpass imethod oba cat increment range encoding)}) x 3;
2158
2159 # for each sample
2160 for my $i (1 .. $#{$self->[1]}) {
2161
2162 # get spectral slice
2163 $spectral->[$i - 1] = [@{$self->[1][$i]}[@{$spec}]];
2164
2165 }
2166
2167 # transform to XYZ data (hash may contain 'encoding' key)
2168 $xyz = ICC::Support::Color::_trans2($color, $spectral, $hash);
2169
2170 # add OBA effect, if enabled
2171 _add_oba($self, $spec1, $spec2, $xyz, $oba, $hash) if $oba;
2172
2173 # for each sample
2174 for my $i (1 .. $#{$self->[1]}) {
2175
2176 # if cat defined
2177 if (defined($cat)) {
2178
2179 # set XYZ slice with cat
2180 @{$self->[1][$i]}[@{$cols}] = ICC::Profile::matf::_trans0($cat, @{$xyz->[$i - 1]});
2181
2182 } else {
2183
2184 # set XYZ slice
2185 @{$self->[1][$i]}[@{$cols}] = @{$xyz->[$i - 1]};
2186
2187 }
2188
2189 }
2190
2191 # if L*a*b* data exists
2192 } elsif (test($self, 'LAB', $context)) {
2193
2194 # warn if illuminant is specified
2195 (! defined($hash->{'illuminant'})) || warn('illuminant specified but no spectral data!');
2196
2197 # get L*a*b* slice
2198 $Lab = cols($self, map {defined($context) ? "$context|$_" : $_} qw(LAB_L LAB_A LAB_B));
2199
2200 # if 'context' and 'added' keys are undefined, and L*a*b* source has context
2201 if (! defined($added) && $self->[1][0][$Lab->[0]] =~ m/^(.*)\|/) {
2202
2203 # set 'added' to L*a*b* context
2204 $added = $1;
2205
2206 }
2207
2208 # get L*a*b* white point values
2209 @WPlab = @{$self->[2][2]}[@{$Lab}];
2210
2211 # use scalar values or D50
2212 $WPxyz = (3 == grep {defined() && ! ref() && $_ > 0} @WPlab) ? [@WPlab] : ICC::Shared::D50;
2213
2214 # add XYZ columns slice
2215 $cols = add_fmt($self, map {defined($added) ? "$added|$_" : $_} qw(XYZ_X XYZ_Y XYZ_Z));
2216
2217 # set origin
2218 @{$self->[2][0]}[@{$cols}] = ($Lab) x 3;
2219
2220 # save illuminant white point
2221 @{$self->[2][2]}[@{$cols}] = @{$WPxyz};
2222
2223 # for each sample
2224 for my $s (1 .. $#{$self->[1]}) {
2225
2226 # compute XYZ values from L*a*b* values
2227 @{$self->[1][$s]}[@{$cols}] = ICC::Shared::_Lab2XYZ(@{$self->[1][$s]}[@{$Lab}], $WPxyz);
2228
2229 }
2230
2231 } else {
2232
2233 # warn
2234 warn('spectral or L*a*b* data is required');
2235
2236 # return empty
2237 return();
2238
2239 }
2240  
2241 # return column slice
2242 return($cols);
2243  
2244 }
2245  
2246 # append ISO 5-3 density data to data array
2247 # computed from spectral data only
2248 # if density data already exists, return that slice
2249 # default status is 'T', encoding is 'density'
2250 # parameters: ([hash])
2251 # returns: (column_slice)
2252 sub add_density {
2253  
2254 # get parameters
2255 my ($self, $hash) = @_;
2256  
2257 # local variables
2258 my ($context, $added, $encode, $fp, $cols, $spec, $temp, $color, $spectral, $rgbv);
2259  
2260 # get base context
2261 $context = $hash->{'context'};
2262  
2263 # get added context
2264 $added = defined($hash->{'added'}) ? $hash->{'added'} : $context;
2265  
2266 # get encoding
2267 $encode = $hash->{'encoding'} // 'density';
2268  
2269 # if invalid encoding
2270 if ($encode ne 'density' && $encode ne 'linear') {
2271
2272 # warn
2273 warn('invalid density encoding, using \'density\'');
2274
2275 # set encoding
2276 $encode = 'density';
2277
2278 }
2279  
2280 # set format prefix
2281 $fp = $encode eq 'density' ? 'D' : 'R';
2282  
2283 # return column slice if density/reflectance data already exists
2284 return($cols) if ($cols = cols($self, map {defined($added) ? "$added|$fp$_" : "$fp$_"} qw(_RED _GREEN _BLUE _VIS)));
2285  
2286 # if spectral data
2287 if (test($self, 'SPECTRAL', $context)) {
2288
2289 # get spectral slice
2290 $spec = spectral($self, $hash);
2291
2292 # make copy of hash
2293 $temp = Storable::dclone($hash);
2294
2295 # add chart wavelength range to hash
2296 $temp->{'range'} = nm($self, $hash);
2297
2298 # make empty 'Color.pm' object
2299 $color = ICC::Support::Color->new();
2300
2301 # initialize object for ISO 5-3 method
2302 ICC::Support::Color::_iso($color, $temp);
2303
2304 # if 'context' and 'added' keys are undefined, and spectral source has context
2305 if (! defined($added) && $self->[1][0][$spec->[0]] =~ m/^(.*)\|/) {
2306
2307 # set 'added' to spectral context
2308 $added = $1;
2309
2310 }
2311
2312 # add density/reflectance columns slice
2313 $cols = add_fmt($self, map {defined($added) ? "$added|$fp$_" : "$fp$_"} qw(_RED _GREEN _BLUE _VIS));
2314
2315 # set origin
2316 @{$self->[2][0]}[@{$cols}] = ($spec) x 4;
2317
2318 # save reference to Color.pm object
2319 @{$self->[2][1]}[@{$cols}] = ($color) x 4;
2320
2321 # save colorimetry hash
2322 @{$self->[2][6]}[@{$cols}] = ({map {defined($temp->{$_}) ? ($_, $temp->{$_}) : ()} qw(status increment range encoding)}) x 4;
2323
2324 # for each sample
2325 for my $i (1 .. $#{$self->[1]}) {
2326
2327 # get spectral slice
2328 $spectral->[$i - 1] = [@{$self->[1][$i]}[@{$spec}]];
2329
2330 }
2331
2332 # set encoding
2333 $temp->{'encoding'} = $encode;
2334
2335 # transform to density/reflectance data (per encoding)
2336 $rgbv = ICC::Support::Color::_trans2($color, $spectral, $temp);
2337
2338 # for each sample
2339 for my $i (1 .. $#{$self->[1]}) {
2340
2341 # set data values
2342 @{$self->[1][$i]}[@{$cols}] = @{$rgbv->[$i - 1]};
2343
2344 }
2345
2346 } else {
2347
2348 # warn
2349 warn('spectral data is required');
2350
2351 # return empty
2352 return();
2353
2354 }
2355  
2356 # return column slice
2357 return($cols);
2358  
2359 }
2360  
2361 # add computed values to data array
2362 # processing is done by a user-defined function (udf)
2363 # data groups are defined by one or more column slice(s)
2364 # supported hash keys: 'element', 'sample', 'device', 'rows', 'start', 'added'
2365 # either an 'element' udf or a 'sample' udf are required, but not both
2366 # an 'element' udf computes a single value from single slice value(s)
2367 # a 'sample' udf computes all values at once from slice value array(s)
2368 # setting the 'device' flag converts RGB/CMYK/nCLR values to device values
2369 # the 'rows' parameter is the row slice computed, default is all rows
2370 # the 'start' parameter is the first column computed, default is to append
2371 # the 'added' parameter may be a scalar or an array reference
2372 # an 'added' scalar will be used as a context prefix
2373 # an 'added' array must be the same size as the columns added
2374 # parameters: (column_slice_0, column_slice_1, ... hash)
2375 # returns: (added_column_slice)
2376 sub add_udf {
2377  
2378 # local variables
2379 my ($self, $hash, @cs, $rows, $m, $n, @div, $udfe, $udfs);
2380 my (@p, @u, @s, $cx, $added);
2381  
2382 # get object reference
2383 $self = shift();
2384  
2385 # get parameter hash
2386 $hash = pop();
2387  
2388 # verify a hash reference
2389 (ref($hash) eq 'HASH') || croak('last parameter must be a hash reference');
2390  
2391 # verify number of slices
2392 (@cs = @_) || croak('one or more column slices are required');
2393  
2394 # get row slice, all rows by default
2395 $rows = defined($hash->{'rows'}) ? $hash->{'rows'} : [];
2396  
2397 # if row slice an empty array reference
2398 if (ref($rows) eq 'ARRAY' && @{$rows} == 0) {
2399
2400 # use all rows
2401 $rows = [1 .. $#{$self->[1]}];
2402
2403 } else {
2404
2405 # flatten row slice
2406 $rows = ICC::Shared::flatten($rows);
2407
2408 # verify row slice contents
2409 (@{$rows} == grep {Scalar::Util::looks_like_number($_) && int($_) == $_ && $_ > 0 && $_ <= $#{$self->[1]}} @{$rows}) || croak('invalid row slice');
2410
2411 }
2412  
2413 # get starting column, append by default
2414 $n = defined($hash->{'start'}) ? $hash->{'start'} : $#{$self->[1][0]} + 1;
2415  
2416 # if an array reference (slice), use the first value
2417 $n = $n->[0] if (ref($n) eq 'ARRAY');
2418  
2419 # verify starting column
2420 (Scalar::Util::looks_like_number($n) && int($n) eq $n && $n >= 0) || croak('invalid \'start\' parameter');
2421  
2422 # if 'device' flag
2423 if ($hash->{'device'}) {
2424
2425 # for each data format
2426 for my $i (0 .. $#{$self->[1][0]}) {
2427
2428 # set divisor to 255 for RGB data
2429 $div[$i] = 255 if ($self->[1][0][$i] =~ m/RGB_[RGB]$/);
2430
2431 # set divisor to 100 for CMYK data
2432 $div[$i] = 100 if ($self->[1][0][$i] =~ m/CMYK_[CMYK]$/);
2433
2434 # set divisor to 100 for nCLR data
2435 $div[$i] = 100 if ($self->[1][0][$i] =~ m/(?:[2-9A-F]CLR_[1-9A-F]|PC[2-9A-F]_[1-9A-F])$/);
2436 }
2437
2438 }
2439  
2440 # get udf CODE refs
2441 $udfe = $hash->{'element'};
2442 $udfs = $hash->{'sample'};
2443  
2444 # if both udfs defined
2445 if (defined($udfe) && defined($udfs)) {
2446
2447 # error
2448 croak('both \'element\' and \'sample\' udfs are defined');
2449
2450 # if 'element' udf defined
2451 } elsif (defined($udfe)) {
2452
2453 # verify udf is a code reference
2454 (ref($udfe) eq 'CODE') || croak('\'element\' udf is not a CODE reference');
2455
2456 # for each parameter
2457 for my $i (0 .. $#cs) {
2458
2459 # if an array reference
2460 if (ref($cs[$i]) eq 'ARRAY') {
2461
2462 # if first slice
2463 if (! defined($m)) {
2464
2465 # get upper index
2466 $m = $#{$cs[0]};
2467
2468 # compute added slice
2469 @s = ($n .. $n + $m);
2470
2471 } else {
2472
2473 # verify slice size
2474 ($#{$cs[$i]} == $m) || croak('column slices are different sizes');
2475
2476 }
2477
2478 # verify a valid column slice
2479 (ref($cs[$i]) eq 'ARRAY' || @{$cs[$i]} == grep {Scalar::Util::looks_like_number($_) && int($_) == $_ && $_ >= 0 && $_ <= $#{$self->[1][0]}} @{$cs[$i]}) || croak('invalid column slice');
2480
2481 # if a scalar
2482 } elsif (! ref($cs[$i])) {
2483
2484 # verify a valid column index
2485 (Scalar::Util::looks_like_number($cs[$i]) && int($cs[$i]) == $cs[$i] && $cs[$i] >= 0 && $cs[$i] <= $#{$self->[1][0]}) || croak('invalid column index');
2486
2487 } else {
2488
2489 # error
2490 croak('parameter must be a scalar or an array reference');
2491
2492 }
2493
2494 }
2495
2496 # verify at least one column slice parameter
2497 (defined($m)) || croak('at least one column slice is required');
2498
2499 # for each sample
2500 for my $i (@{$rows}) {
2501
2502 # for each column index
2503 for my $j (0 .. $m) {
2504
2505 # for each parameter
2506 for my $k (0 .. $#cs) {
2507
2508 # get column index (slice -or- scalar)
2509 $cx = (ref($cs[$k]) eq 'ARRAY') ? $cs[$k][$j] : $cs[$k];
2510
2511 # get parameter value
2512 $p[$k] = $self->[1][$i][$cx];
2513
2514 # adjust device values, if divisor defined
2515 $p[$k] /= $div[$cx] if defined($div[$cx]);
2516
2517 }
2518
2519 # call 'element' udf
2520 $self->[1][$i][$n + $j] = &$udfe(@p, $j);
2521
2522 }
2523
2524 }
2525
2526 # if 'sample' udf defined
2527 } elsif (defined($udfs)) {
2528
2529 # verify udf is a code reference
2530 (ref($udfs) eq 'CODE') || croak('\'sample\' udf is not a CODE reference');
2531
2532 # for each parameter
2533 for my $i (0 .. $#cs) {
2534
2535 # verify a valid column slice
2536 (ref($cs[$i]) eq 'ARRAY' || @{$cs[$i]} == grep {Scalar::Util::looks_like_number($_) && int($_) == $_ && $_ >= 0 && $_ <= $#{$self->[1][0]}} @{$cs[$i]}) || croak('invalid column slice');
2537
2538 }
2539
2540 # verify at least one parameter
2541 (@cs) || croak('at least one column slice is required');
2542
2543 # for each sample
2544 for my $i (@{$rows}) {
2545
2546 # for each column slice
2547 for my $j (0 .. $#cs) {
2548
2549 # for each slice element
2550 for my $k (0 .. $#{$cs[$j]}) {
2551
2552 # get column index
2553 $cx = $cs[$j][$k];
2554
2555 # get parameter value
2556 $p[$j][$k] = $self->[1][$i][$cx];
2557
2558 # adjust device values, if divisor defined
2559 $p[$j][$k] /= $div[$cx] if defined($div[$cx]);
2560
2561 }
2562
2563 }
2564
2565 # if first sample
2566 if (! defined($m)) {
2567
2568 # call 'sample' udf
2569 @u = &$udfs(@p);
2570
2571 # get upper index
2572 $m = $#u;
2573
2574 # compute added slice
2575 @s = ($n .. $n + $m);
2576
2577 # copy values to object
2578 @{$self->[1][$i]}[@s] = @u;
2579
2580 } else {
2581
2582 # call 'sample' udf
2583 @{$self->[1][$i]}[@s] = &$udfs(@p);
2584
2585 }
2586
2587 }
2588
2589 } else {
2590
2591 # error
2592 croak('no udf is defined');
2593
2594 }
2595  
2596 # get 'added' parameter, default is 'udf', could be undefined
2597 $added = exists($hash->{'added'}) ? $hash->{'added'} : 'udf';
2598  
2599 # if 'added' is undefined
2600 if (! defined($added)) {
2601
2602 # if 'element' udf -or- size of first column slice equals number of added columns
2603 if (defined($udfe) || @{$cs[0]} == @s) {
2604
2605 # add data format stripping context from first column slice
2606 @{$self->[1][0]}[@s] = map {m/^(?:.*\|)?(.*)$/; $1} @{$self->[1][0]}[@{$cs[0]}];
2607
2608 } else {
2609
2610 # add data format as 'colxxx'
2611 @{$self->[1][0]}[@s] = map {"col$_"} @s;
2612
2613 }
2614
2615 # if 'added' a scalar
2616 } elsif (! ref($added)) {
2617
2618 # if 'element' udf -or- size of first column slice equals number of added columns
2619 if (defined($udfe) || @{$cs[0]} == @s) {
2620
2621 # add data format using 'added' as context with first column slice format keys
2622 @{$self->[1][0]}[@s] = map {m/^(?:.*\|)?(.*)$/; "$added|$1"} @{$self->[1][0]}[@{$cs[0]}];
2623
2624 } else {
2625
2626 # add data format using 'added' as context to 'colxxx'
2627 @{$self->[1][0]}[@s] = map {"$added|col$_"} @s;
2628
2629 }
2630
2631 # if 'added' is an array ref and size equals number of added columns
2632 } elsif (ref($added) eq 'ARRAY' && @{$added} == @s) {
2633
2634 # add data format using 'added' as array
2635 @{$self->[1][0]}[@s] = @{$added};
2636
2637 } else {
2638
2639 # error
2640 croak('invalid \'added\' parameter');
2641
2642 }
2643  
2644 # return added column slice
2645 return([@s]);
2646  
2647 }
2648  
2649 # append date column to data array
2650 # adds same date/time to each sample
2651 # supported hash keys: 'date', 'format', 'added'
2652 # parameter: ([hash])
2653 # returns: (column_slice)
2654 sub add_date {
2655  
2656 # get parameters
2657 my ($self, $hash) = @_;
2658  
2659 # local variables
2660 my ($cols, $added, $date, $fmt, $str);
2661  
2662 # get added context
2663 $added = $hash->{'added'};
2664  
2665 # return column slice if date column already exists
2666 return($cols) if ($cols = _cols($self, defined($added) ? "$added|CREATED" : 'CREATED'));
2667  
2668 # add date column slice
2669 $cols = add_fmt($self, defined($added) ? "$added|CREATED" : 'CREATED');
2670  
2671 # if date supplied
2672 if (defined($date = $hash->{'date'})) {
2673
2674 # if date is a number
2675 if (Scalar::Util::looks_like_number($date)) {
2676
2677 # make Time::Piece object
2678 $date = localtime($date);
2679
2680 # if date not a Time::Piece object
2681 } elsif (ref($date) ne 'Time::Piece') {
2682
2683 # error
2684 croak('invalid date parameter');
2685 }
2686
2687 } else {
2688
2689 # use 'CREATED' value from chart
2690 $date = created($self);
2691
2692 }
2693  
2694 # compute the date/time string (same for each sample)
2695 $str = defined($fmt = $hash->{'format'}) ? $date->strftime($fmt) : $date->epoch();
2696  
2697 # for each row
2698 for my $i (1 .. $#{$self->[1]}) {
2699
2700 # set the date time string
2701 $self->[1][$i][$cols->[0]] = $str;
2702
2703 }
2704  
2705 # return column slice
2706 return($cols);
2707  
2708 }
2709  
2710 # splice rows into data array
2711 # offset and length are as used by Perl's 'splice' function
2712 # data matrix is the 2-D array of data values to be spliced
2713 # column slice is a reference to an array of data matrix column indices
2714 # parameters: ([offset, [length, [data_matrix, [column_slice]]]])
2715 # returns: (removed_data_matrix)
2716 sub splice_rows {
2717  
2718 # get parameters
2719 my ($self, $offset, $length, $matrix, $cols) = @_;
2720  
2721 # local variables
2722 my (@ix, @list, @s, $removed);
2723  
2724 # if offset supplied
2725 if (defined($offset)) {
2726
2727 # verify offset a scalar
2728 (! ref($offset) && (int($offset) == $offset)) || croak('invalid offset parameter');
2729
2730 }
2731  
2732 # if length supplied
2733 if (defined($length)) {
2734
2735 # verify length an integer scalar
2736 (! ref($length) && int($length) == $length) || croak('invalid length parameter');
2737
2738 }
2739  
2740 # if matrix supplied
2741 if (defined($matrix)) {
2742
2743 # verify matrix a 2-D array or Math::Matrix object
2744 (ref($matrix) eq 'ARRAY' && ref($matrix->[0]) eq 'ARRAY') || (UNIVERSAL::isa($matrix, 'Math::Matrix')) || croak ('invalid matrix parameter');
2745
2746 }
2747  
2748 # if column slice supplied
2749 if (defined($cols)) {
2750
2751 # verify column slice an array reference
2752 (ref($cols) eq 'ARRAY') || croak('invalid cols parameter');
2753
2754 # verify length, offset and matrix supplied
2755 (defined($length) && defined($offset) && defined($matrix)) || croak('cols requires length, offset and matrix');
2756
2757 # flatten column slice
2758 @ix = @{ICC::Shared::flatten($cols)};
2759
2760 # make splice list using column slice
2761 @list = map {@s[@ix] = @{$_}; [@s]} @{$matrix};
2762
2763 # splice the data
2764 $removed = [splice(@{$self->[1]}, $offset, $length, @list)];
2765
2766 } else {
2767
2768 # if matrix supplied
2769 if (defined($matrix)) {
2770
2771 # verify length, offset
2772 (defined($length) && defined($offset)) || croak('matrix requires length and offset');
2773
2774 # make splice list from full matrix
2775 @list = map {[@{$_}]} @{$matrix};
2776
2777 # splice the data
2778 $removed = [splice(@{$self->[1]}, $offset, $length, @list)];
2779
2780 } else {
2781
2782 # if length supplied
2783 if (defined($length)) {
2784
2785 # verify offset supplied
2786 (defined($offset)) || croak('length requires offset');
2787  
2788 # splice the data
2789 $removed = [splice(@{$self->[1]}, $offset, $length)];
2790
2791 } else {
2792
2793 # if offset supplied
2794 if (defined($offset)) {
2795
2796 # splice the data
2797 $removed = [splice(@{$self->[1]}, $offset)];
2798
2799 } else {
2800
2801 # get data array reference
2802 $removed = $self->[1];
2803
2804 # init data array
2805 $self->[1] = [[]];
2806
2807 # init colorimetry array
2808 $self->[2] = [[]];
2809
2810 }
2811
2812 }
2813
2814 }
2815
2816 }
2817  
2818 # update the SAMPLE_ID hash
2819 _makeSampleID($self);
2820  
2821 # return removed data
2822 return(bless($removed, 'Math::Matrix'));
2823  
2824 }
2825  
2826 # splice columns into data array
2827 # offset and length are as used by Perl's 'splice' function
2828 # data matrix is the 2-D array of data values to be spliced
2829 # row slice is a reference to an array of data matrix row indices
2830 # parameters: ([offset, [length, [data_matrix, [row_slice]]]])
2831 # returns: (removed_data_matrix)
2832 sub splice_cols {
2833  
2834 # get parameters
2835 my ($self, $offset, $length, $matrix, $rows) = @_;
2836  
2837 # local variables
2838 my (@ix, @s, @filler, $removed);
2839  
2840 # if offset supplied
2841 if (defined($offset)) {
2842
2843 # verify offset a scalar
2844 (! ref($offset) && (int($offset) == $offset)) || croak('invalid offset parameter');
2845
2846 }
2847  
2848 # if length supplied
2849 if (defined($length)) {
2850
2851 # verify length an integer scalar
2852 (! ref($length) && int($length) == $length) || croak('invalid length parameter');
2853
2854 }
2855  
2856 # if matrix supplied
2857 if (defined($matrix)) {
2858
2859 # verify matrix a 2-D array or Math::Matrix object
2860 (ref($matrix) eq 'ARRAY' && ref($matrix->[0]) eq 'ARRAY') || (UNIVERSAL::isa($matrix, 'Math::Matrix')) || croak ('invalid matrix parameter');
2861
2862 }
2863  
2864 # if row slice supplied
2865 if (defined($rows)) {
2866
2867 # verify row slice an array reference
2868 (ref($rows) eq 'ARRAY') || croak('invalid cols parameter');
2869
2870 # verify length, offset and matrix supplied
2871 (defined($length) && defined($offset) && defined($matrix)) || croak('rows requires length, offset and matrix');
2872
2873 # flatten row slice
2874 @ix = @{ICC::Shared::flatten($rows)};
2875
2876 # make list of matrix row refs
2877 @s[@ix] = @{$matrix};
2878
2879 # make filler data
2880 @filler = (undef) x @{$matrix->[0]};
2881
2882 # for each data row
2883 for my $i (0 .. $#{$self->[1]}) {
2884
2885 # if matrix data defined
2886 if (defined($s[$i])) {
2887
2888 # splice matrix data
2889 $removed->[$i] = [splice(@{$self->[1][$i]}, $offset, $length, @{$s[$i]})];
2890
2891 } else {
2892
2893 # splice filler data
2894 $removed->[$i] = [splice(@{$self->[1][$i]}, $offset, $length, @filler)];
2895
2896 }
2897
2898 }
2899
2900 # for each colorimetry row
2901 for my $i (0 .. $#{$self->[2]}) {
2902
2903 # splice filler data
2904 splice(@{$self->[2][$i]}, $offset, $length, @filler) if (defined($self->[2][$i][$offset]));
2905
2906 }
2907
2908 } else {
2909
2910 # if matrix supplied
2911 if (defined($matrix)) {
2912
2913 # verify length, offset
2914 (defined($length) && defined($offset)) || croak('matrix requires length and offset');
2915
2916 # make filler data
2917 @filler = (undef) x @{$matrix->[0]};
2918
2919 # for each data row
2920 for my $i (0 .. $#{$self->[1]}) {
2921
2922 # if matrix data defined
2923 if (defined($matrix->[$i])) {
2924
2925 # splice matrix data
2926 $removed->[$i] = [splice(@{$self->[1][$i]}, $offset, $length, @{$matrix->[$i]})];
2927
2928 } else {
2929
2930 # splice filler data
2931 $removed->[$i] = [splice(@{$self->[1][$i]}, $offset, $length, @filler)];
2932
2933 }
2934
2935 }
2936
2937 # for each colorimetry row
2938 for my $i (0 .. $#{$self->[2]}) {
2939
2940 # splice filler data
2941 splice(@{$self->[2][$i]}, $offset, $length, @filler) if (defined($self->[2][$i][$offset]));
2942
2943 }
2944
2945 } else {
2946
2947 # if length supplied
2948 if (defined($length)) {
2949
2950 # verify offset supplied
2951 (defined($offset)) || croak('length requires offset');
2952
2953 # for each data row
2954 for my $i (0 .. $#{$self->[1]}) {
2955
2956 # splice the data
2957 $removed->[$i] = [splice(@{$self->[1][$i]}, $offset, $length)];
2958
2959 }
2960
2961 # for each colorimetry row
2962 for my $i (0 .. $#{$self->[2]}) {
2963
2964 # splice filler data
2965 splice(@{$self->[2][$i]}, $offset, $length) if (defined($self->[2][$i][$offset]));
2966
2967 }
2968
2969 } else {
2970
2971 # if offset supplied
2972 if (defined($offset)) {
2973
2974 # for each data row
2975 for my $i (0 .. $#{$self->[1]}) {
2976
2977 # splice the data
2978 $removed->[$i] = [splice(@{$self->[1][$i]}, $offset)];
2979
2980 }
2981
2982 # for each colorimetry row
2983 for my $i (0 .. $#{$self->[2]}) {
2984
2985 # splice filler data
2986 splice(@{$self->[2][$i]}, $offset) if (defined($self->[2][$i][$offset]));
2987
2988 }
2989
2990 } else {
2991
2992 # get data array reference
2993 $removed = $self->[1];
2994
2995 # init data array
2996 $self->[1] = [[]];
2997
2998 # init colorimetry array
2999 $self->[2] = [[]];
3000
3001 }
3002
3003 }
3004
3005 }
3006
3007 }
3008  
3009 # initialize SAMPLE_ID hash if no SAMPLE_ID field
3010 $self->[4] = {} if (0 == test($self, 'ID'));
3011  
3012 # return removed data
3013 return(bless($removed, 'Math::Matrix'));
3014  
3015 }
3016  
3017 # remove rows from data array
3018 # parameters: (row_slice)
3019 # returns: (removed_data_matrix)
3020 sub remove_rows {
3021  
3022 # get parameters
3023 my ($self, $rows) = @_;
3024  
3025 # local variables
3026 my ($f, $up, @r, @s, $removed);
3027  
3028 # return empty matrix if row slice undefined
3029 return(bless([[]], 'Math::Matrix')) if (! defined($rows));
3030  
3031 # flatten row slice
3032 $f = ICC::Shared::flatten($rows);
3033  
3034 # if row slice is empty
3035 if (! defined($f->[0])) {
3036
3037 # remove all rows, except row 0 (DATA_FORMAT)
3038 $removed = [splice(@{$self->[1]}, 1)];
3039
3040 # clear SAMPLE_ID hash
3041 $self->[4] = {};
3042
3043 # return removed data
3044 return(bless($removed, 'Math::Matrix'));
3045
3046 }
3047  
3048 # get upper row index
3049 $up = $#{$self->[1]};
3050  
3051 # verify row slice
3052 (grep {$_ != int($_) || $_ < 1 || $_ > $up} @{$f}) && carp('row slice contains invalid index value(s)');
3053  
3054 # initialize slice (always keep row 0)
3055 @s = (0);
3056  
3057 # for each row
3058 for my $i (1 .. $up) {
3059
3060 # if index contained in row slice
3061 if (grep {$i == $_} @{$f}) {
3062
3063 # add to slice (remove)
3064 push(@r, $i);
3065
3066 } else {
3067
3068 # add to slice (keep)
3069 push(@s, $i)
3070
3071 }
3072
3073 }
3074  
3075 # if rows to remove
3076 if (@r) {
3077
3078 # set removed data (@r)
3079 $removed = [@{$self->[1]}[@r]];
3080
3081 # set kept data (@s)
3082 $self->[1] = [@{$self->[1]}[@s]];
3083
3084 # update the SAMPLE_ID hash
3085 _makeSampleID($self);
3086
3087 } else {
3088
3089 # set removed data (none)
3090 $removed = [[]];
3091
3092 }
3093  
3094 # return removed data
3095 return(bless($removed, 'Math::Matrix'));
3096  
3097 }
3098  
3099 # remove columns from data array
3100 # parameters: (column_slice)
3101 # returns: (removed_data_matrix)
3102 sub remove_cols {
3103  
3104 # get parameters
3105 my ($self, $cols) = @_;
3106  
3107 # local variables
3108 my ($f, $up, @r, @s, $removed, $kept, $color);
3109  
3110 # return empty matrix if column slice undefined
3111 return(bless([[]], 'Math::Matrix')) if (! defined($cols));
3112  
3113 # flatten column slice
3114 $f = ICC::Shared::flatten($cols);
3115  
3116 # if columns slice is empty
3117 if (! defined($f->[0])) {
3118
3119 # copy all rows
3120 $removed = [@{$self->[1]}];
3121
3122 # clear data array
3123 $self->[1] =[[]];
3124
3125 # clear colorimetry array
3126 $self->[2] = [[]];
3127
3128 # clear SAMPLE_ID hash
3129 $self->[4] = {};
3130
3131 # return removed data
3132 return(bless($removed, 'Math::Matrix'));
3133
3134 }
3135  
3136 # get upper column index
3137 $up = $#{$self->[1][0]};
3138  
3139 # verify column slice
3140 (grep {$_ != int($_) || $_ < 0 || $_ > $up} @{$f}) && carp('column slice contains invalid index value(s)');
3141  
3142 # for each column
3143 for my $i (0 .. $up) {
3144
3145 # if index contained in column slice
3146 if (grep {$i == $_} @{$f}) {
3147
3148 # add to slice (remove)
3149 push(@r, $i);
3150
3151 } else {
3152
3153 # add to slice (keep)
3154 push(@s, $i)
3155
3156 }
3157
3158 }
3159  
3160 # if columns to remove
3161 if (@r) {
3162
3163 # for each data row
3164 for my $i (0 .. $#{$self->[1]}) {
3165
3166 # set removed data (@r)
3167 $removed->[$i] = [@{$self->[1][$i]}[@r]];
3168
3169 # set kept data (@s)
3170 $kept->[$i] = [@{$self->[1][$i]}[@s]];
3171
3172 }
3173
3174 # update object data
3175 $self->[1] = $kept;
3176
3177 # for each colorimetry row
3178 for my $i (0 .. $#{$self->[2]}) {
3179
3180 # set kept colorimetry (@s)
3181 $color->[$i] = [@{$self->[2][$i]}[@s]];
3182
3183 }
3184
3185 # update colorimetry data
3186 $self->[2] = $color;
3187
3188 # initialize SAMPLE_ID hash if no SAMPLE_ID field
3189 $self->[4] = {} if (0 == test($self, 'ID'));
3190
3191 } else {
3192
3193 # set removed data (none)
3194 $removed = [[]];
3195
3196 }
3197  
3198 # return removed data
3199 return(bless($removed, 'Math::Matrix'));
3200  
3201 }
3202  
3203 # get sample selection based on 2-D location
3204 # indices are one-based, with origin at the upper left
3205 # row matrix slice may contain indices of undefined rows
3206 # entire chart is used when the row and column indices are omitted
3207 # chart row length is provided as a parameter, or obtained from the data
3208 # parameters: ([upper_row_index, lower_row_index, left_column_index, right_column_index], [chart_row_length])
3209 # returns: (row_matrix_slice)
3210 sub select_matrix {
3211  
3212 # get object reference
3213 my $self = shift();
3214  
3215 # local variables
3216 my ($sn, $cmax, @rows, @cols, $matrix);
3217 my ($row_length, $upper, $lower, $left, $right);
3218  
3219 # get number of samples
3220 $sn = $#{$self->[1]};
3221  
3222 # if 0 or 4 parameters
3223 if (@_ == 0 || @_ == 4) {
3224
3225 # get row length from data
3226 $row_length = _getRowLength($self);
3227
3228 # if 1 or 5 parameters
3229 } elsif (@_ == 1 || @_ == 5) {
3230
3231 # get row length
3232 $row_length = pop();
3233
3234 # verify row length
3235 (Scalar::Util::looks_like_number($row_length) && $row_length == int($row_length) && $row_length > 0) || croak('invalid chart row length');
3236
3237 } else {
3238
3239 # error
3240 croak('wrong number of parameters');
3241
3242 }
3243
3244 # if row and column parameters provided
3245 if (@_) {
3246
3247 # get row and column parameters
3248 ($upper, $lower, $left, $right) = @_;
3249
3250 # verify upper and lower indices
3251 (! ref($upper) && $upper == int($upper) && $upper > 0 && $upper <= $row_length) || warn('invalid upper row index');
3252 (! ref($lower) && $lower == int($lower) && $lower > 0 && $lower <= $row_length) || warn('invalid lower row index');
3253
3254 # get maximum column index
3255 $cmax = $sn % $row_length ? int($sn/$row_length) + 1 : int($sn/$row_length);
3256
3257 # verify left and right indices
3258 (! ref($left) && $left == int($left) && $left > 0 && $left <= $cmax) || warn('invalid left column index');
3259 (! ref($right) && $right == int($right) && $right > 0 && $right <= $cmax) || warn('invalid right column index');
3260
3261 # if upper index < lower index
3262 if ($upper < $lower) {
3263
3264 # make rows array
3265 @rows = ($upper .. $lower);
3266
3267 } else {
3268
3269 # make rows array
3270 @rows = reverse($lower .. $upper);
3271
3272 }
3273
3274 # if left index < right index
3275 if ($left < $right) {
3276
3277 # make columns array
3278 @cols = ($left .. $right);
3279
3280 } else {
3281
3282 # make columns array
3283 @cols = reverse($right .. $left);
3284
3285 }
3286
3287 # use entire chart
3288 } else {
3289
3290 # make rows array
3291 @rows = (1 .. $row_length);
3292
3293 # if chart is rectangular
3294 if ($sn % $row_length == 0) {
3295
3296 # make columns array
3297 @cols = (1 .. $sn/$row_length);
3298
3299 } else {
3300
3301 # warning
3302 warn('chart is not rectangular');
3303
3304 # make columns array
3305 @cols = (1 .. int($sn/$row_length) + 1);
3306
3307 }
3308
3309 }
3310  
3311 # for each row
3312 for my $i (0 .. $#rows) {
3313
3314 # for each column
3315 for my $j (0 .. $#cols) {
3316
3317 # set matrix element
3318 $matrix->[$j][$i] = ($cols[$j] - 1) * $row_length + $rows[$i];
3319
3320 }
3321
3322 }
3323  
3324 # return row matrix slice
3325 return(bless($matrix, 'Math::Matrix'));
3326  
3327 }
3328  
3329 # get sample selection using template
3330 # samples are matched by their device values
3331 # supported hash keys: 'dups', 'rows', 'context', 'template_context', 'sid_context', 'method', 'copy'
3332 # duplicate handling: 0 - sample average (default), 1 - FIFO, 2 - LIFO, 3 - first sample, 4 - last sample
3333 # parameters: (template_chart_object, [hash])
3334 # returns: (row_matrix_slice, [sid_matrix_slice])
3335 sub select_template {
3336  
3337 # get parameters
3338 my ($self, $template, $hash) = @_;
3339  
3340 # local variables
3341 my ($row_length, $dups, $copys, $copyt);
3342 my ($devcs, $devct, $devs, $devt);
3343 my ($sx, $c1, $c2, $c3, $n, @src, $cmp);
3344 my ($target, $low, $high, $interval, @m, $nomatch);
3345 my ($rows, $avg, $matrix, $devp, $sidt, $sid);
3346  
3347 # verify template is a chart object
3348 (UNIVERSAL::isa($template, 'ICC::Support::Chart')) || croak('template not an ICC::Support::Chart object');
3349  
3350 # get template row length
3351 $row_length = _getRowLength($template, $hash);
3352  
3353 # set duplicate handling
3354 $dups = defined($hash->{'dups'}) ? $hash->{'dups'} : 0;
3355  
3356 # if copy slice is defined
3357 if (defined($hash->{'copy'})) {
3358
3359 # flatten the copy slice
3360 $copys = ICC::Shared::flatten($hash->{'copy'});
3361
3362 # add copied fields to template
3363 $copyt = add_fmt($template, @{$self->[1][0]}[@{$copys}]);
3364
3365 }
3366  
3367 # verify parameters
3368 (! ref($row_length) && $row_length == int($row_length) && $row_length > 0) || croak('invalid chart_row_length parameter');
3369 ($dups == int($dups) && $dups >= 0 && $dups <= 4) || croak('invalid duplicate_handling parameter');
3370  
3371 # get object device column slice
3372 $devcs = device($self, $hash);
3373  
3374 # get template device column slice
3375 $devct = device($template, {'context' => $hash->{'template_context'}});
3376  
3377 # verify object and template column slices
3378 (defined($devcs)) || croak ('object device data missing');
3379 (defined($devct)) || croak ('template device data missing');
3380 ($#{$devcs} == $#{$devct}) || croak('object and template have different number of channels');
3381  
3382 # get object device values
3383 $devs = device($self, [], $hash);
3384  
3385 # get template device values
3386 $devt = device($template, [], {'context' => $hash->{'template_context'}});
3387  
3388 # get index of next object sample
3389 $sx = $#{$self->[1]} + 1;
3390  
3391 # get averaging groups if duplicates are averaged
3392 ($c1, $c2, $c3) = _avg_groups($self, $hash) if ($dups == 0);
3393  
3394 # get number of channels
3395 $n = @{$devcs};
3396  
3397 # initialize sample list
3398 @src = ();
3399  
3400 # for each sample
3401 for my $i (0 .. $#{$devs}) {
3402
3403 # if all device values defined
3404 if ($n == grep {defined()} @{$devs->[$i]}) {
3405
3406 # add sample to source list
3407 push(@src, [@{$devs->[$i]}, $i + 1]);
3408
3409 }
3410
3411 }
3412  
3413 # sort object device values
3414 @src = sort {
3415
3416 # for each channel
3417 for my $i (0 .. $#{$a}) {
3418
3419 # quit loop if device values are unequal
3420 last if ($cmp = $a->[$i] <=> $b->[$i])
3421
3422 # use last comparison for sort test
3423 } $cmp
3424
3425 } @src;
3426  
3427 # for each template sample
3428 for my $i (0 .. $#{$devt}) {
3429
3430 # initialize search indices
3431 $low = 0;
3432 $high = $#src;
3433
3434 # initialize no match flag
3435 $nomatch = 0;
3436
3437 # for each channel
3438 for my $j (0 .. $#{$devt->[0]}) {
3439
3440 # get the target value
3441 $target = $devt->[$i][$j];
3442
3443 # locate interval containing or bounding the target value
3444 $interval = _bin_search(\@src, $target, $j, $low, $high);
3445
3446 # find indices matching the target value
3447 @m = grep {$src[$_][$j] == $target} @{$interval};
3448
3449 # if no object values exactly match the target value
3450 if (@m == 0) {
3451
3452 # sort interval indices by distance to target value
3453 @m = sort {$a->[1] <=> $b->[1]} map {[$_, abs($src[$_][$j] - $target)]} @{$interval};
3454
3455 # if distance to closest object value > 0.00201
3456 if (abs($target - $src[$m[0][0]][$j]) > 0.00201) {
3457
3458 # print warning
3459 print "no match to template sample $i\n";
3460 print "device values: @{$devt->[$i]}\n";
3461
3462 # set no match flag
3463 $nomatch = 1;
3464
3465 # quit channel loop
3466 last;
3467
3468 }
3469
3470 # set target to closest object value
3471 $target = $src[$m[0][0]][$j];
3472
3473 # locate interval containing the target value
3474 $interval = _bin_search(\@src, $target, $j, $low, $high);
3475
3476 # find indices matching the target value
3477 @m = grep {$src[$_][$j] == $target} @{$interval};
3478
3479 }
3480
3481 # update interval
3482 $low = $m[0];
3483 $high = $m[-1];
3484
3485 }
3486
3487 # if no match found
3488 if ($nomatch) {
3489
3490 # locate nearest object sample(s) using linear search
3491 ($low, $high) = _lin_search(\@src, $devt->[$i]);
3492
3493 # print message
3494 print "closest match is object sample $src[$low][-1]\n";
3495 print "device values @{$src[$low]}[0 .. $#{$devt->[0]}]\n";
3496
3497 }
3498
3499 # single sample
3500 if ($low == $high) {
3501
3502 # set matrix element to first row matching object sample
3503 $matrix->[$i/$row_length][$i % $row_length] = $src[$low][-1];
3504
3505 # duplicate samples
3506 } else {
3507
3508 # duplicates are averaged
3509 if ($dups == 0) {
3510
3511 # for each appended avg sample
3512 for my $j ($sx .. $#{$self->[1]}) {
3513
3514 # set avg
3515 $avg = $j;
3516
3517 # get device values
3518 $devp = $self->device([$j]);
3519
3520 # for each channel
3521 for my $k (0 .. $#{$devp->[0]}) {
3522
3523 # clear avg if device values differ
3524 $avg = 0 if ($devp->[0][$k] != $devt->[$i][$k]);
3525
3526 }
3527
3528 # quit loop if device values match
3529 last if ($avg);
3530
3531 }
3532
3533 # if existing avg sample found
3534 if ($avg) {
3535
3536 # set matrix element to existing avg sample
3537 $matrix->[$i/$row_length][$i % $row_length] = $avg;
3538
3539 } else {
3540
3541 # make row slice of duplicate samples
3542 $rows = [map {$src[$_][-1]} ($low .. $high)];
3543
3544 # set matrix element to new avg sample
3545 $matrix->[$i/$row_length][$i % $row_length] = _add_avg($self, $rows, $c1, $c2, $c3);
3546
3547 }
3548
3549 # use FIFO sample
3550 } elsif ($dups == 1) {
3551
3552 # from low to high
3553 for my $j ($low .. $high) {
3554
3555 # if index > 0
3556 if ($src[$j][-1] > 0) {
3557
3558 # set matrix element to object sample index
3559 $matrix->[$i/$row_length][$i % $row_length] = $src[$j][-1];
3560
3561 # invert sample index to indicate it was used
3562 $src[$j][-1] = - $src[$j][-1];
3563
3564 # quit loop
3565 last;
3566
3567 }
3568
3569 }
3570
3571 # if matrix element undefined
3572 if (! defined($matrix->[$i/$row_length][$i % $row_length])) {
3573
3574 # print message
3575 print "FIFO stack empty for @{$devt->[$i]}\n";
3576 print "using last stack sample\n";
3577
3578 # set matrix element to last row matching object sample
3579 $matrix->[$i/$row_length][$i % $row_length] = - $src[$high][-1];
3580
3581 }
3582
3583 # use LIFO sample
3584 } elsif ($dups == 2) {
3585
3586 # from high to low
3587 for my $j (reverse($low .. $high)) {
3588
3589 # if index > 0
3590 if ($src[$j][-1] > 0) {
3591
3592 # set matrix element to object sample index
3593 $matrix->[$i/$row_length][$i % $row_length] = $src[$j][-1];
3594
3595 # invert sample index to indicate it was used
3596 $src[$j][-1] = - $src[$j][-1];
3597
3598 # quit loop
3599 last;
3600
3601 }
3602
3603 }
3604
3605 # if matrix element undefined
3606 if (! defined($matrix->[$i/$row_length][$i % $row_length])) {
3607
3608 # print message
3609 print "LIFO stack empty for @{$devt->[$i]}\n";
3610 print "using last stack sample\n";
3611
3612 # set matrix element to first row matching object sample
3613 $matrix->[$i/$row_length][$i % $row_length] = - $src[$low][-1];
3614
3615 }
3616
3617 # use first duplicate sample
3618 } elsif ($dups == 3) {
3619
3620 # set matrix element to first row matching object sample
3621 $matrix->[$i/$row_length][$i % $row_length] = $src[$low][-1];
3622
3623 # use last duplicate sample
3624 } elsif ($dups == 4) {
3625
3626 # set matrix element to last row matching object sample
3627 $matrix->[$i/$row_length][$i % $row_length] = $src[$high][-1];
3628
3629 } else {
3630
3631 # error
3632 croak('invalid duplicate handling');
3633
3634 }
3635
3636 }
3637
3638 # if 'copy' slice defined
3639 if (defined($copys)) {
3640
3641 # get the object row
3642 $n = $matrix->[$i/$row_length][$i % $row_length];
3643
3644 # copy selected values from object to template
3645 @{$template->[1][$i + 1]}[@{$copyt}] = @{$self->[1][$n]}[@{$copys}];
3646
3647 # if device values differ
3648 if ($nomatch) {
3649
3650 # copy device values from object to template
3651 @{$template->[1][$i + 1]}[@{$devct}] = @{$self->[1][$n]}[@{$devcs}];
3652
3653 }
3654
3655 }
3656
3657 }
3658  
3659 # if sid-matrix is wanted and template has sid values
3660 if (wantarray() && ($sidt = id($template, [], {'context' => $hash->{'sid_context'}}))) {
3661
3662 # for each template sample
3663 for my $i (0 .. $#{$sidt}) {
3664
3665 # set sid matrix element to sid slice value
3666 $sid->[$i/$row_length][$i % $row_length] = $sidt->[$i][0];
3667
3668 }
3669
3670 # return row matrix slice and sid matrix slice
3671 return(bless($matrix, 'Math::Matrix'), bless($sid, 'Math::Matrix'));
3672
3673 } else {
3674
3675 # return row matrix slice
3676 return(bless($matrix, 'Math::Matrix'));
3677
3678 }
3679  
3680 }
3681  
3682 # get sample selection using tokens
3683 # tokens are provided as a text string
3684 # supported hash keys: 'A2B', 'B2A', 'sort'
3685 # sample slice is sorted, duplicates are removed
3686 # context may be specified with parameter hash
3687 # parameters: (token_string, [hash])
3688 # returns: (sample_slice)
3689 sub select_token {
3690  
3691 # get parameters
3692 my ($self, $select, $hash) = @_;
3693  
3694 # local variables
3695 my ($n, $row_length, $sort, $sel, @nr, @samples, $token, @p);
3696 my ($mat, @dev, @cmy, @Lab, $A2B, $B2A, $pcs);
3697 my ($last, $code, $dev);
3698  
3699 # verify chart has device data
3700 ($n = test($self, 'DEVICE', $hash->{'context'})) || croak("device data is required for 'select_token' method");
3701  
3702 # get row length
3703 $row_length = _getRowLength($self);
3704  
3705 # get sort vector from hash
3706 $sort = $hash->{'sort'};
3707  
3708 # parse token string
3709 $sel = ICC::Shared::parse_tokens($select);
3710
3711 # if 'nr' token(s)
3712 if (@nr = grep {$sel->[$_] eq 'nr'} (0 .. $#{$sel})) {
3713
3714 # move first 'nr' token and parameter to beginning of array
3715 unshift(@{$sel}, splice(@{$sel}, $nr[0], 2));
3716
3717 # warn if more than one 'nr' token
3718 print "multiple 'nr' selection tokens\n" if (@nr > 1);
3719
3720 }
3721  
3722 # initialize sample slice
3723 @samples = ();
3724  
3725 # for each selection
3726 for (my $i = 0; $i <= $#{$sel}; $i++) {
3727
3728 # get the lowercase value of current token
3729 $token = lc($sel->[$i]);
3730
3731 # set parameter array
3732 @p = (ref($sel->[$i + 1]) eq 'ARRAY') ? @{$sel->[++$i]} : ();
3733
3734 # if 'all'
3735 if ($token eq 'all') {
3736
3737 # quit loop
3738 last;
3739
3740 # if 'sort'
3741 } elsif ($token eq 'sort') {
3742
3743 # if numeric parameters
3744 if (@p) {
3745
3746 # set the sort vector
3747 $sort = [@p];
3748
3749 } else {
3750
3751 # print warning
3752 print "selection token 'sort' requires numeric parameter(s)\n";
3753
3754 }
3755
3756 # if 'rows'
3757 } elsif ($token eq 'rows') {
3758
3759 # if numeric parameters
3760 if (@p) {
3761
3762 # for each row
3763 for my $i (0 .. $#p) {
3764
3765 # add row samples
3766 push(@samples, grep {($_ - 1) % $row_length == ($p[$i] - 1)} (1 .. size($self)));
3767
3768 }
3769
3770 } else {
3771
3772 # print warning
3773 print "selection token 'rows' requires numeric parameter(s)\n";
3774
3775 }
3776
3777 # if 'cols'
3778 } elsif ($token eq 'cols') {
3779
3780 # if numeric parameters
3781 if (@p) {
3782
3783 # for each column
3784 for my $i (0 .. $#p) {
3785
3786 # add column samples
3787 push(@samples, map {$row_length * ($p[$i] - 1) + $_} (1 .. $row_length));
3788
3789 }
3790
3791 } else {
3792
3793 # print warning
3794 print "selection token 'cols' requires numeric parameter(s)\n";
3795
3796 }
3797
3798 # if 'rect'
3799 } elsif ($token eq 'rect') {
3800
3801 # if 4 numeric parameters
3802 if (@p == 4) {
3803
3804 # get samples
3805 $mat = select_matrix($self, @p, $row_length);
3806
3807 # add column samples (flatten matrix)
3808 push(@samples, map {@{$_}} @{$mat});
3809
3810 } else {
3811
3812 # print warning
3813 print "selection token 'rect' requires 4 numeric parameters\n";
3814
3815 }
3816
3817 # if 'nr'
3818 } elsif ($token eq 'nr') {
3819
3820 # if numeric parameters
3821 if (@p) {
3822
3823 # set the number of rows
3824 $row_length = $p[0];
3825
3826 } else {
3827
3828 # print warning
3829 print "selection token 'nr' requires a numeric parameter\n";
3830
3831 }
3832
3833 # if 'iso'
3834 } elsif ($token eq 'iso') {
3835
3836 # if numeric parameters
3837 if (@p) {
3838
3839 # add isometric samples (C == M == Y, all other channels == 0) and c+m+y <= limit
3840 push(@samples, @{ramp($self, sub {@cmy = splice(@_, 0, 3); $cmy[0] == $cmy[1] && $cmy[1] == $cmy[2] && (0 == grep {$_} @_) && 300 * $cmy[0] <= $p[0]}, $hash)});
3841
3842 } else {
3843
3844 # print warning
3845 print "selection token 'iso' requires a numeric parameter\n";
3846
3847 }
3848
3849 # if 'c+m+y'
3850 } elsif ($token eq 'c+m+y') {
3851
3852 # if numeric parameters
3853 if (@p) {
3854
3855 # add samples with c+m+y <= limit
3856 push(@samples, @{ramp($self, sub {100 * ($_[0] + $_[1] + $_[2]) <= $p[0]}, $hash)});
3857
3858 } else {
3859
3860 # print warning
3861 print "selection token 'c+m+y' requires a numeric parameter\n";
3862
3863 }
3864
3865 # if 'tac'
3866 } elsif ($token eq 'tac') {
3867
3868 # if numeric parameters
3869 if (@p) {
3870
3871 # add samples with TAC <= limit
3872 push(@samples, @{ramp($self, sub {100 * List::Util::sum(@_) <= $p[0]}, $hash)});
3873
3874 } else {
3875
3876 # print warning
3877 print "selection token 'tac' requires a numeric parameter\n";
3878
3879 }
3880
3881 # if 'gray'
3882 } elsif ($token eq 'gray') {
3883
3884 # if the A2B tag is supplied in hash
3885 if (defined($A2B = $hash->{'A2B'})) {
3886
3887 # make PCS object (profile to L*a*b*, relative colorimetric)
3888 $pcs = ICC::Support::PCS->new([$A2B->pcs], [3]);
3889
3890 # if one parameter (C* limit)
3891 if (@p == 1) {
3892
3893 # add gray samples (cmy samples only)
3894 push(@samples, @{ramp($self, sub {@Lab = $pcs->transform($A2B->transform(@_)); sqrt($Lab[1]**2 + $Lab[2]**2) <= $p[0] && (0 == grep {$_} splice(@_, 3))}, $hash)});
3895
3896 # if two parameters (C* and L* limits)
3897 } elsif (@p) {
3898
3899 # add gray samples (cmy samples only)
3900 push(@samples, @{ramp($self, sub {@Lab = $pcs->transform($A2B->transform(@_)); sqrt($Lab[1]**2 + $Lab[2]**2) <= $p[0] && $Lab[0] >= $p[1] && (0 == grep {$_} splice(@_, 3))}, $hash)});
3901
3902 } else {
3903
3904 # print warning
3905 print "selection token 'gray' requires numeric parameter(s)\n";
3906
3907 }
3908
3909 } else {
3910
3911 # print warning
3912 print "selection token 'gray' requires A2B profile tag in hash\n";
3913
3914 }
3915
3916 # if 'rt'
3917 } elsif ($token eq 'rt') {
3918
3919 # if the A2B and B2A tags are supplied in hash
3920 if (defined($A2B = $hash->{'A2B'}) && defined($B2A = $hash->{'B2A'})) {
3921
3922 # if numeric parameters
3923 if (@p) {
3924
3925 # add samples with round-trip black change less than the limit
3926 push(@samples, @{ramp($self, sub {@dev = $B2A->transform($A2B->transform(@_)); 100 * abs($_[3] - $dev[3]) <= $p[0]}, $hash)});
3927
3928 } else {
3929
3930 # print warning
3931 print "selection token 'rt' requires a numeric parameter\n";
3932
3933 }
3934
3935 } else {
3936
3937 # print warning
3938 print "selection token 'rt' requires A2B and B2A profile tags in hash\n";
3939
3940 }
3941
3942 # if 'ink'
3943 } elsif ($token eq 'ink') {
3944
3945 # if numeric parameters
3946 if (@p) {
3947
3948 # for each parameter
3949 for my $i (0 .. $#p) {
3950
3951 # if parameter a valid ink channel
3952 if ($p[$i] == int($p[$i]) && $p[$i] > 0 && $p[$i] <= $n) {
3953
3954 # add inkx only samples
3955 push(@samples, @{ramp($self, sub {$_[$p[$i] - 1] = 0; 0 == grep {$_} @_}, $hash)});
3956
3957 } else {
3958
3959 # print warning
3960 print "selection token 'ink', channel $p[$i] is invalid\n";
3961
3962 }
3963
3964 }
3965
3966 } else {
3967
3968 # print warning
3969 print "selection token 'ink' requires numeric parameter(s)\n";
3970
3971 }
3972
3973 # if 'c'
3974 } elsif ($token eq 'c') {
3975
3976 # add cyan-only samples
3977 push(@samples, @{ramp($self, sub {$_[0] = 0; 0 == grep {$_} @_}, $hash)});
3978
3979 # if 'm'
3980 } elsif ($token eq 'm') {
3981
3982 # add magenta-only samples
3983 push(@samples, @{ramp($self, sub {$_[1] = 0; 0 == grep {$_} @_}, $hash)});
3984
3985 # if 'y'
3986 } elsif ($token eq 'y') {
3987
3988 # add yellow-only samples
3989 push(@samples, @{ramp($self, sub {$_[2] = 0; 0 == grep {$_} @_}, $hash)});
3990
3991 # if 'k'
3992 } elsif ($token eq 'k') {
3993
3994 # add black-only samples
3995 push(@samples, @{ramp($self, sub {$_[3] = 0; 0 == grep {$_} @_}, $hash)});
3996
3997 # if 'nok'
3998 } elsif ($token eq 'nok') {
3999
4000 # add no black samples
4001 push(@samples, @{ramp($self, sub {$_[3] == 0}, $hash)});
4002
4003 # if 'cmyk'
4004 } elsif ($token eq 'cmyk') {
4005
4006 # add cmyk ramps (number of non-zero CMYK channels <= 1, all extra channels == 0)
4007 push(@samples, @{ramp($self, sub {(1 >= grep {$_} splice(@_, 0, 4)) && (0 == grep {$_} @_)}, $hash)});
4008
4009 # if 'ramps'
4010 } elsif ($token eq 'ramps') {
4011
4012 # add device ramps (number of non-zero channels <= 1)
4013 push(@samples, @{ramp($self, sub {1 >= grep {$_} @_}, $hash)});
4014
4015 # if 'acro'
4016 } elsif ($token eq 'acro') {
4017
4018 # add achromatic samples (1 or more cmy channels == 0, all extra channels == 0)
4019 push(@samples, @{ramp($self, sub {(1 <= grep {$_ == 0} splice(@_, 0, 3)) && (0 == grep {$_} splice(@_, 1))}, $hash)});
4020
4021 # if 'gamut'
4022 } elsif ($token eq 'gamut') {
4023
4024 # add gamut samples (k == 0)
4025 push(@samples, @{ramp($self, sub {@cmy = splice(@_, 0, 3); $_[0] == 0 && 0 < grep {$_ == 0} @cmy}, $hash)});
4026
4027 # add gamut samples (k == 1)
4028 push(@samples, @{ramp($self, sub {@cmy = splice(@_, 0, 3); $_[0] == 1 && 0 < grep {$_ == 1} @cmy}, $hash)});
4029
4030 # add gamut samples (0 < k < 1)
4031 push(@samples, @{ramp($self, sub {@cmy = splice(@_, 0, 3); $_[0] > 0 && $_[0] < 1 && (0 < grep {$_ == 0} @cmy) && (0 < grep {$_ == 1} @cmy)}, $hash)});
4032
4033 } else {
4034
4035 # print warning
4036 printf "selection token '%s' not recognized\n", $token;
4037
4038 }
4039
4040 }
4041  
4042 # initialize
4043 $last = 0;
4044  
4045 # sort samples and remove duplicates
4046 @samples = grep {$last == $_ ? 0 : ($last = $_)} sort {$a <=> $b} grep {$_ >= 1 && $_ <= size($self)} @samples;
4047  
4048 # if sort vector provided (in hash or as a token)
4049 if ($sort) {
4050
4051 # verify sort parameter
4052 if (ICC::Shared::is_num_vector($sort) && @{$sort} == grep {$_ && $_ == int($_) && abs($_) <= $n} @{$sort}) {
4053
4054 # get device data
4055 $dev = device($self, \@samples);
4056
4057 # for each sample
4058 for my $i (0 .. $#{$dev}) {
4059
4060 # insert sample number
4061 unshift(@{$dev->[$i]}, $samples[$i] // $i + 1);
4062
4063 }
4064
4065 # make sort code fragment
4066 $code = '@{$dev} = sort {' . join(' || ', map {my $dir = m/-/; my $col = abs($_); $dir ? "\$b->[$col] <=> \$a->[$col]" : "\$a->[$col] <=> \$b->[$col]"} @{$sort}) . '} @{$dev}';
4067
4068 # evaluate code fragment
4069 eval($code);
4070
4071 # for each sample
4072 for my $i (0 .. $#{$dev}) {
4073
4074 # extract the sample number
4075 $samples[$i] = $dev->[$i][0];
4076
4077 }
4078
4079 } else {
4080
4081 # display warning
4082 carp("invalid sort parameter, sorting failed\n");
4083
4084 }
4085
4086 }
4087  
4088 # return
4089 return(\@samples);
4090  
4091 }
4092  
4093 # get sample selection
4094 # array of data values is supplied to code block
4095 # sample is included if code block returns 'true' value
4096 # default row_slice is all samples
4097 # default column_slice is all columns
4098 # parameters: (code_reference, row_slice, column_slice)
4099 # returns: (row_slice)
4100 sub find {
4101  
4102 # get parameters
4103 my ($self, $code, $rows, $cols) = @_;
4104  
4105 # verify code reference
4106 (ref($code) eq 'CODE') || croak('selection parameter must be a code reference');
4107  
4108 # if row slice undefined or empty
4109 if (! defined($rows) || (ref($rows) eq 'ARRAY' && @{$rows} == 0)) {
4110
4111 # use all rows
4112 $rows = [1 .. $#{$self->[1]}];
4113
4114 } else {
4115
4116 # flatten slice
4117 $rows = ICC::Shared::flatten($rows);
4118
4119 }
4120  
4121 # if column slice undefined or empty
4122 if (! defined($cols) || (ref($cols) eq 'ARRAY' && @{$cols} == 0)) {
4123
4124 # use all columns
4125 $cols = [0 .. $#{$self->[1][0]}];
4126
4127 } else {
4128
4129 # flatten slice
4130 $cols = ICC::Shared::flatten($cols);
4131
4132 }
4133  
4134 # return selection slice
4135 return([grep {&$code(@{$self->[1][$_]}[@{$cols}])} @{$rows}]);
4136  
4137 }
4138  
4139 # get sample selection based on device values
4140 # array of device values is supplied to code block
4141 # sample is included if code block returns 'true' value
4142 # default row_slice is all samples
4143 # context may be specified with parameter hash
4144 # parameters: (code_reference, [row_slice], [hash])
4145 # returns: (row_slice)
4146 sub ramp {
4147  
4148 # local variables
4149 my ($hash, $cols, $mult);
4150  
4151 # get optional hash
4152 $hash = pop() if (ref($_[-1]) eq 'HASH');
4153  
4154 # get remaining parameters
4155 my ($self, $code, $rows) = @_;
4156  
4157 # verify code reference
4158 (ref($code) eq 'CODE') || croak('selection parameter must be a code reference');
4159  
4160 # if row slice undefined or empty
4161 if (! defined($rows) || (ref($rows) eq 'ARRAY' && @{$rows} == 0)) {
4162
4163 # use all rows
4164 $rows = [1 .. $#{$self->[1]}];
4165
4166 } else {
4167
4168 # flatten slice
4169 $rows = ICC::Shared::flatten($rows);
4170
4171 }
4172  
4173 # get device column slice
4174 (defined($cols = device($self, $hash))) || croak('device values required');
4175  
4176 # set multiplier (255 if RGB, else 100)
4177 $mult = ($self->[1][0][$cols->[0]] =~ m/RGB_R$/) ? 255 : 100;
4178  
4179 # return selection slice
4180 return([grep {&$code(map {$_/$mult} @{$self->[1][$_]}[@{$cols}])} @{$rows}]);
4181  
4182 }
4183  
4184 # get sample selection based on L*a*b* values
4185 # array of L*a*b* values is supplied to code block
4186 # sample is included if code block returns 'true' value
4187 # default row_slice is all samples
4188 # context may be specified with parameter hash
4189 # parameters: (code_reference, [row_slice], [hash])
4190 # returns: (row_slice)
4191 sub range {
4192  
4193 # local variables
4194 my ($hash, $cols);
4195  
4196 # get optional hash
4197 $hash = pop() if (ref($_[-1]) eq 'HASH');
4198  
4199 # get remaining parameters
4200 my ($self, $code, $rows) = @_;
4201  
4202 # verify code reference
4203 (ref($code) eq 'CODE') || croak('selection parameter must be a code reference');
4204  
4205 # if row slice undefined or empty
4206 if (! defined($rows) || (ref($rows) eq 'ARRAY' && @{$rows} == 0)) {
4207
4208 # use all rows
4209 $rows = [1 .. $#{$self->[1]}];
4210
4211 } else {
4212
4213 # flatten slice
4214 $rows = ICC::Shared::flatten($rows);
4215
4216 }
4217  
4218 # get L*a*b* column slice
4219 (defined($cols = lab($self, $hash))) || croak('L*a*b* values required');
4220  
4221 # return selection slice
4222 return([grep {&$code(@{$self->[1][$_]}[@{$cols}])} @{$rows}]);
4223  
4224 }
4225  
4226 # generate randomized sample slice
4227 # parameter: ([row_slice])
4228 # returns: (row_slice)
4229 sub randomize {
4230  
4231 # get parameters
4232 my ($self, $rows) = @_;
4233  
4234 # if row slice defined
4235 if (defined($rows)) {
4236
4237 # if row slice an empty array reference
4238 if (ref($rows) eq 'ARRAY' && @{$rows} == 0) {
4239
4240 # use all rows
4241 $rows = [1 .. $#{$self->[1]}];
4242
4243 } else {
4244
4245 # flatten row slice
4246 $rows = ICC::Shared::flatten($rows);
4247
4248 # verify row slice contents
4249 (@{$rows} == grep {! ref() && $_ == int($_) && $_ >= 0} @{$rows}) || croak('invalid row slice');
4250
4251 }
4252
4253 # return row slice, randomized
4254 return([List::Util::shuffle(@{$rows})]);
4255
4256 } else {
4257
4258 # return all samples, randomized
4259 return([List::Util::shuffle(1 .. $#{$self->[1]})]);
4260
4261 }
4262  
4263 }
4264  
4265 # analyze chart device values
4266 # creates an array structure with an element for each device channel.
4267 # each element contains a hash, a keys array, and a ramp array.
4268 # hash keys are device values, and hash values are arrays of samples.
4269 # if row-slice is omitted, all samples are used.
4270 # if the dup_flag is false (default), a new sample is added
4271 # containing average measurement values, and the new sample
4272 # is substituted for the anonymous array of duplicates.
4273 # if the dup_flag is true, duplicate samples are included in
4274 # array of samples grouped within anonymous arrays.
4275 # dup_flag and/or device context are specified with parameter hash
4276 # parameters: ([row_slice], [hash])
4277 # returns: (ref_to_structure)
4278 sub analyze {
4279  
4280 # get object reference
4281 my $self = shift();
4282  
4283 # local variables
4284 my ($hash, $rows, $dup, $ramp, $dev, $c1, $c2, $c3, @id, @name, $mult);
4285 my (@d, %dev_hash, $key, $avg, $value, $struct);
4286  
4287 # get optional hash
4288 $hash = pop() if (ref($_[-1]) eq 'HASH');
4289  
4290 # get device column slice
4291 ($dev = device($self, $hash)) || croak('chart has no device values');
4292  
4293 # get row slice
4294 $rows = shift() if (ref($_[0]) eq 'ARRAY');
4295  
4296 # flatten row slice
4297 $rows = $rows ? ICC::Shared::flatten($rows) : [];
4298  
4299 # use all samples if slice is empty
4300 $rows = [1 .. $#{$self->[1]}] if (@{$rows} == 0);
4301  
4302 # get dup flag
4303 $dup = defined($hash->{'dups'}) ? $hash->{'dups'} : 0;
4304  
4305 # get ramp value
4306 $ramp = defined($hash->{'ramp'}) ? $hash->{'ramp'} : 0;
4307  
4308 # get averaging groups
4309 ($c1, $c2, $c3) = _avg_groups($self, $hash);
4310  
4311 # for each column
4312 for my $i (0 .. $#{$self->[1][0]}) {
4313
4314 # add column if SAMPLE_ID field
4315 push(@id, $i) if ($self->[1][0][$i] =~ m/^(?:.*\|)?(?:SAMPLE_ID|SampleID)$/);
4316
4317 # add column if SAMPLE_NAME field
4318 push(@name, $i) if ($self->[1][0][$i] =~ m/^(?:.*\|)?SAMPLE_NAME$/);
4319
4320 }
4321  
4322 # set device multiplier (255 for RGB values, otherwise 100)
4323 $mult = ($self->[1][0][$dev->[0]] =~ m/^(?:.*\|)?RGB_[RGB]$/) ? 255 : 100;
4324  
4325 # for each sample
4326 for my $i (0 .. $#{$rows}) {
4327
4328 # get device values
4329 @d = @{$self->[1][$rows->[$i]]}[@{$dev}];
4330
4331 # divide by multiplier (setting -0 to 0)
4332 @d = map {$_ == 0 ? 0 : $_/$mult} @d;
4333
4334 # make device value key
4335 $key = join(':', @d);
4336
4337 # if key exists
4338 if (exists($dev_hash{$key})) {
4339
4340 # add sample to existing hash entry
4341 push(@{$dev_hash{$key}}, $rows->[$i]);
4342
4343 } else {
4344
4345 # add device hash entry
4346 $dev_hash{$key} = [$rows->[$i]];
4347
4348 }
4349
4350 }
4351  
4352 # if dup flag is not set
4353 if (! $dup) {
4354
4355 # for each key
4356 for my $key (keys(%dev_hash)) {
4357
4358 # if duplicate samples
4359 if (@{$dev_hash{$key}} > 1) {
4360
4361 # if measurement data
4362 if (@{$c1} || @{$c2} || @{$c3}) {
4363
4364 # add average sample
4365 $avg = _add_avg($self, $dev_hash{$key}, $c1, $c2, $c3, \@id, \@name);
4366
4367 # update hash to average sample
4368 $dev_hash{$key} = [$avg];
4369
4370 } else {
4371
4372 # update hash to first sample
4373 $dev_hash{$key} = [$dev_hash{$key}[0]];
4374
4375 }
4376
4377 }
4378
4379 }
4380
4381 # update the SAMPLE_ID hash
4382 _makeSampleID($self);
4383
4384 }
4385  
4386 # make empty structure
4387 $struct = [map {[{}, [], []]} (0 .. $#{$dev})];
4388  
4389 # for each key
4390 for my $key (keys(%dev_hash)) {
4391
4392 # split key to device values
4393 @d = split(/:/, $key);
4394
4395 # get value
4396 $value = $dev_hash{$key};
4397
4398 # resolve single value to scalar
4399 $value = $value->[0] if (@{$value} == 1);
4400
4401 # for each device channel
4402 for my $i (0 .. $#d) {
4403
4404 # if key exists
4405 if (exists($struct->[$i][0]{$d[$i]})) {
4406
4407 # add sample to hash entry
4408 push(@{$struct->[$i][0]{$d[$i]}}, $value);
4409
4410 } else {
4411
4412 # add hash entry
4413 $struct->[$i][0]{$d[$i]} = [$value];
4414
4415 # add device value to keys array
4416 push(@{$struct->[$i][1]}, $d[$i]);
4417
4418 }
4419
4420 # if all other device values equal ramp value
4421 if (@d == grep {$_ == $i || $d[$_] == $ramp} (0 .. $#d)) {
4422
4423 # add sample to ramp array
4424 push(@{$struct->[$i][2]}, $value);
4425
4426 }
4427
4428 }
4429
4430 }
4431  
4432 # for each device channel
4433 for my $i (0 .. $#{$dev}) {
4434
4435 # sort keys array (decreasing frequency)
4436 $struct->[$i][1] = [sort {@{$struct->[$i][0]{$b}} <=> @{$struct->[$i][0]{$a}}} @{$struct->[$i][1]}];
4437
4438 # sort ramp array (increasing values)
4439 $struct->[$i][2] = [sort {$self->[1][(! ref($a) ? $a : $a->[0])][$dev->[$i]] <=> $self->[1][(! ref($b) ? $b : $b->[0])][$dev->[$i]]} @{$struct->[$i][2]}];
4440
4441 }
4442  
4443 # return
4444 return($struct);
4445  
4446 }
4447  
4448 # write chart to ISO 28178 (CGATS.17) ASCII file
4449 # optional slice parameters are either scalars, array references or 'Math::Matrix' objects
4450 # optional hash parameter keys: 'sid', 'append'
4451 # parameters: (path_to_file, [row_slice, [column_slice]], [hash])
4452 sub write {
4453  
4454 # local variables
4455 my ($hash, $row_length, $m, $n, $sid, $fh, $rs, @fields);
4456 my (%cspec, $keyword, $value, $source, $std_key, @s, $sidx, $append);
4457 my ($null, $undef);
4458  
4459 # get optional hash parameter
4460 $hash = pop() if (ref($_[-1]) eq 'HASH');
4461  
4462 # get remaining parameters
4463 my ($self, $path, $rows, $cols) = @_;
4464  
4465 # if row slice defined
4466 if (defined($rows)) {
4467
4468 # if row slice an empty array reference
4469 if (ref($rows) eq 'ARRAY' && @{$rows} == 0) {
4470
4471 # use all rows
4472 $rows = [1 .. $#{$self->[1]}];
4473
4474 } else {
4475
4476 # get row length if row slice is Math::Matrix object
4477 $row_length = @{$rows->[0]} if (UNIVERSAL::isa($rows, 'Math::Matrix'));
4478
4479 # flatten row slice
4480 $rows = ICC::Shared::flatten($rows);
4481
4482 }
4483
4484 } else {
4485
4486 # use all rows
4487 $rows = [1 .. $#{$self->[1]}];
4488
4489 }
4490  
4491 # get number of rows
4492 $m = @{$rows};
4493  
4494 # warn if invalid samples
4495 (@{$rows} == grep {$_ == int($_) && $_ != 0 && defined($self->[1][$_])} @{$rows})|| warn('row slice contains invalid samples');
4496  
4497 # if column slice defined
4498 if (defined($cols)) {
4499
4500 # if column slice an empty array reference
4501 if (ref($cols) eq 'ARRAY' && @{$cols} == 0) {
4502
4503 # use all columns
4504 $cols = [0 .. $#{$self->[1][0]}];
4505
4506 } else {
4507
4508 # flatten column slice
4509 $cols = ICC::Shared::flatten($cols);
4510
4511 }
4512
4513 } else {
4514
4515 # use all columns
4516 $cols = [0 .. $#{$self->[1][0]}];
4517
4518 }
4519  
4520 # get number of columns
4521 $n = @{$cols};
4522  
4523 # filter column slice
4524 @{$cols} = grep {$_ == int($_) && defined($self->[1][0][$_])} @{$cols};
4525  
4526 # warn if invalid fields
4527 ($n == @{$cols}) || warn('column slice contains invalid fields');
4528  
4529 # if 'sid' hash value defined
4530 if (defined($sid = $hash->{'sid'})) {
4531
4532 # if array reference or Math::Matrix object
4533 if (ref($sid) eq 'ARRAY' || UNIVERSAL::isa($sid, 'Math::Matrix')) {
4534
4535 # flatten 'sid' slice
4536 $sid = ICC::Shared::flatten($sid);
4537
4538 # warn row slice and sid slice are different sizes
4539 ($m == @{$sid}) || warn('row slice and sid slice are different sizes');
4540
4541 } elsif ($sid eq 'row') {
4542
4543 # use sequential row list
4544 $sid = [1 .. $m];
4545
4546 } else {
4547
4548 # error
4549 croak('invalid \'sid\' hash value');
4550
4551 }
4552
4553 }
4554  
4555 # filter path
4556 ICC::Shared::filterPath($path);
4557  
4558 # open the file
4559 open($fh, '>', $path) or croak("can't open $path: $!");
4560  
4561 # disable :crlf translation
4562 binmode($fh);
4563  
4564 # get the record separator
4565 $rs = $self->[0]{'write_rs'} || $self->[0]{'read_rs'} || "\n";
4566  
4567 # initialize color specification hash
4568 # so lines with 'FileInformation' source are printed
4569 %cspec = ('FileInformation' => 1);
4570  
4571 # add referenced sources to color specification hash
4572 for (@{$self->[2][5]}[@{$cols}]) {$cspec{$_}++ if defined()};
4573  
4574 # for each header line
4575 for (@{$self->[3]}) {
4576
4577 # get keyword, value and source
4578 ($keyword, $value, $source) = @{$_};
4579
4580 # if keyword defined and length > 0
4581 if (defined($keyword) && length($keyword)) {
4582
4583 # make uppercase
4584 $keyword = uc($keyword);
4585
4586 # skip certain keywords
4587 next if ($keyword =~ m/KEYWORD|NUMBER_OF_FIELDS|NUMBER_OF_SETS/);
4588 next if (defined($row_length) && $keyword =~ m/LGOROWLENGTH/);
4589
4590 # if no source or referenced source
4591 if (! defined($source) || $cspec{$source}) {
4592
4593 # if value defined and length > 0
4594 if (defined($value) && length($value)) {
4595
4596 # print keyword/value
4597 print $fh "$keyword\t$value$rs";
4598
4599 } else {
4600
4601 # print keyword only
4602 print $fh "$keyword$rs";
4603
4604 }
4605
4606 }
4607
4608 } else {
4609
4610 # print empty line
4611 print $fh "$rs";
4612
4613 }
4614
4615 }
4616  
4617 # get format fields
4618 @fields = @{$self->[1][0]}[@{$cols}];
4619  
4620 # remove any context, trim leading and trailing white space, and replace spaces with underscores
4621 for (@fields) {s/^.*\|//; s/^\s*(.*?)\s*$/$1/; s/ /_/g}
4622  
4623 # make standard format keyword regex (per ISO 28178 and common usage)
4624 $std_key = '^(?:' . join('|', qw(SAMPLE_ID SAMPLE_NO STRING RGB_[RGB] CMYK_[CMYK] [2-9A-F]CLR_[1-9A-F] PC\d+_\d+ SPOT_\d+
4625 (?:nm|SPECTRAL_NM_|SPECTRAL_NM|SPECTRAL_|NM_|R_)\d{3} D_(?:RED|GREEN|BLUE|VIS|MAJOR_FILTER) XYZ_[XYZ] XYY_(?:X|Y|CAPY)
4626 LAB_[LABCH] LAB_DE LAB_DE_94 LAB_DE_CMC LAB_DE_2000 MEAN_DE STDDEV_[XYZ] STDDEV_[LAB] CHI_SQD_PAR)) . ')$';
4627  
4628 # for each format field
4629 for (@fields) {
4630
4631 # if not a standard keyword
4632 if (! /$std_key/) {
4633
4634 # print KEYWORD
4635 printf $fh "KEYWORD\t%s$rs", $_;
4636
4637 }
4638
4639 }
4640  
4641 # if 'sid' slice defined
4642 if (defined($sid)) {
4643
4644 # if 'SAMPLE_ID' keyword(s)
4645 if (@s = grep {uc($fields[$_]) eq 'SAMPLE_ID'} (0 .. $#fields)) {
4646
4647 # save index of first match
4648 $sidx = $s[0];
4649
4650 } else {
4651
4652 # insert 'SAMPLE_ID' keyword
4653 unshift(@fields, 'SAMPLE_ID');
4654
4655 }
4656
4657 }
4658  
4659 # print LGOROWLENGTH (if $row_length defined)
4660 printf $fh "LGOROWLENGTH\t%d$rs", $row_length if (defined($row_length));
4661  
4662 # print NUMBER_OF_FIELDS
4663 printf $fh "NUMBER_OF_FIELDS\t%d$rs", scalar(@fields);
4664  
4665 # print BEGIN_DATA_FORMAT
4666 print $fh 'BEGIN_DATA_FORMAT', $rs;
4667  
4668 # print format string (if any)
4669 print $fh join("\t", @fields), $rs if (@fields);
4670  
4671 # print END_DATA_FORMAT
4672 print $fh 'END_DATA_FORMAT', $rs;
4673  
4674 # print NUMBER_OF_SETS
4675 printf $fh "NUMBER_OF_SETS\t%d$rs", scalar(@{$rows});
4676  
4677 # print BEGIN_DATA
4678 print $fh 'BEGIN_DATA', $rs;
4679  
4680 # get null replacement value
4681 $null = $hash->{'null'} // 'null';
4682  
4683 # get undef replacement value
4684 $undef = $hash->{'undef'} // 'undef';
4685  
4686 # for each row
4687 for my $i (0 .. $#{$rows}) {
4688
4689 # get data fields, replacing null and undefined values
4690 @fields = map {defined() ? length() ? $_ : $null : $undef} @{$self->[1][$rows->[$i]]}[@{$cols}];
4691
4692 # trim leading and trailing white space, and replace spaces with underscores
4693 for (@fields) {s/^\s*(.*?)\s*$/$1/; s/ /_/g};
4694
4695 # if 'sid' slice defined
4696 if (defined($sid)) {
4697
4698 # if 'sid' index defined
4699 if (defined($sidx)) {
4700
4701 # replace 'sid' value
4702 $fields[$sidx] = $sid->[$i];
4703
4704 } else {
4705
4706 # insert 'sid' value
4707 unshift(@fields, $sid->[$i]);
4708 }
4709
4710 }
4711
4712 # print the data record
4713 print $fh join("\t", @fields), $rs;
4714
4715 }
4716  
4717 # print END_DATA
4718 print $fh 'END_DATA', $rs;
4719  
4720 # if 'append' hash value defined
4721 if (defined($append = $hash->{'append'})) {
4722
4723 # replace line endings, if any
4724 $append =~ s/\n/$rs/g;
4725
4726 # print appended data
4727 print $fh $append;
4728
4729 }
4730  
4731 # close the file
4732 close($fh);
4733  
4734 }
4735  
4736 # write chart to CxF3 file
4737 # optional slice parameters are either scalars, array references or 'Math::Matrix' objects
4738 # optional hash parameter keys: 'cc:FileInformation'
4739 # parameters: (path_to_file, [row_slice, [column_slice]], [hash])
4740 sub writeCxF3 {
4741  
4742 # local variables
4743 my ($hash, $row_length, $n);
4744 my ($dom, $root, $ns, $nsURI);
4745 my ($datetime, $id, $ops, $objcol);
4746 my ($prefix, $nid, $obj, $xpath, $node);
4747 my (%lookup, @data, $sub, $spot);
4748  
4749 # get optional hash parameter
4750 $hash = pop() if (ref($_[-1]) eq 'HASH');
4751  
4752 # get remaining parameters
4753 my ($self, $path, $rows, $cols) = @_;
4754  
4755 # if row slice defined
4756 if (defined($rows)) {
4757
4758 # if row slice an empty array reference
4759 if (ref($rows) eq 'ARRAY' && @{$rows} == 0) {
4760
4761 # use all rows
4762 $rows = [1 .. $#{$self->[1]}];
4763
4764 } else {
4765
4766 # get row length if row slice is Math::Matrix object
4767 $row_length = @{$rows->[0]} if (UNIVERSAL::isa($rows, 'Math::Matrix'));
4768
4769 # flatten row slice
4770 $rows = ICC::Shared::flatten($rows);
4771
4772 }
4773
4774 } else {
4775
4776 # set array reference to all rows
4777 $rows = [1 .. $#{$self->[1]}];
4778
4779 }
4780  
4781 # get number of rows
4782 $n = @{$rows};
4783  
4784 # filter row slice
4785 @{$rows} = grep {$_ == int($_) && $_ != 0 && defined($self->[1][$_])} @{$rows};
4786  
4787 # warn if invalid samples
4788 ($n == @{$rows}) || warn('row slice contains invalid samples');
4789  
4790 # open CxF3 template
4791 eval {$dom = XML::LibXML->load_xml('location' => ICC::Shared::getICCPath('Templates/CxF3_template.xml'))} || croak('can\'t load CxF3 template');
4792  
4793 # get the root element
4794 $root = $dom->documentElement();
4795  
4796 # get the namespace prefix and URI
4797 $ns = $root->prefix();
4798 $nsURI = $root->namespaceURI();
4799  
4800 # make 'FileInformation' nodes
4801 $datetime = _makeCxF3fileinfo($self, $root, $ns, $nsURI, $hash);
4802  
4803 # make write operations array from column slice
4804 # array structure: [[[class, prefix, XPath, [sub_paths], [columns], {attributes}, sort_order], ...], ...]
4805 $ops = _makeCxF3writeops($self, $root, $ns, $cols);
4806  
4807 # make 'ColorSpecification' nodes
4808 _makeCxF3colorspec($self, $root, $ns, $nsURI, $ops);
4809  
4810 # get the 'ObjectCollection' node
4811 ($objcol) = $root->findnodes("$ns:Resources/$ns:ObjectCollection");
4812  
4813 # init object Id index
4814 $id = 1;
4815  
4816 # for each group of operations
4817 for my $i (0 .. $#{$ops}) {
4818
4819 # get prefix (ObjectType)
4820 $prefix = $ops->[$i][0][1];
4821
4822 # initialize name Id
4823 $nid = 0;
4824
4825 # for each row in slice
4826 for my $j (@{$rows}) {
4827
4828 # increment name Id
4829 $nid++;
4830
4831 # add 'Object' node
4832 $obj = $objcol->appendChild(XML::LibXML::Element->new("$ns:Object"));
4833 $obj->setAttribute('ObjectType', $prefix);
4834 $obj->setAttribute('Name', "$prefix$nid");
4835 $obj->setAttribute('Id', "c$id");
4836 $obj->setNamespace($nsURI, $ns);
4837
4838 # add 'CreationDate' node
4839 $node = $obj->appendChild(XML::LibXML::Element->new("$ns:CreationDate"));
4840 $node->appendText($datetime);
4841 $node->setNamespace($nsURI, $ns);
4842
4843 # init XPath node hash
4844 %lookup = ();
4845
4846 # for each operation in the group
4847 for my $k (0 .. $#{$ops->[$i]}) {
4848
4849 # set current node to Object
4850 $node = $obj;
4851
4852 # initialize XPath
4853 $xpath = undef;
4854
4855 # for each XPath segment
4856 for (split(/\//, $ops->[$i][$k][2])) {
4857
4858 # add segment to XPath
4859 $xpath = defined($xpath) ? "$xpath/$_" : $_;
4860
4861 # if segment exists
4862 if (exists($lookup{$xpath})) {
4863
4864 # use node
4865 $node = $lookup{$xpath};
4866
4867 } else {
4868
4869 # add node
4870 $node = $node->appendChild(XML::LibXML::Element->new($_));
4871 $node->setNamespace($nsURI, $ns);
4872
4873 # add hash entry (except Tag elements)
4874 $lookup{$xpath} = $node if ($_ ne "$ns:Tag");
4875
4876 }
4877
4878 }
4879
4880 # for each attribute key (if any)
4881 for (keys(%{$ops->[$i][$k][5]})) {
4882
4883 # set node attribute using either data element or hash value
4884 $node->setAttribute($_, (ref($ops->[$i][$k][5]{$_}) eq 'ARRAY') ? $self->[1][$j][$ops->[$i][$k][5]{$_}[0]] : $ops->[$i][$k][5]{$_});
4885
4886 }
4887
4888 # get data
4889 @data = @{$self->[1][$j]}[@{$ops->[$i][$k][4]}];
4890
4891 # warn on undefined data
4892 (@data == grep {defined()} @data) || warn("undefined data in sample $j when writing CxF3 file");
4893
4894 # if subpaths
4895 if (@{$ops->[$i][$k][3]}) {
4896
4897 # for each subpath
4898 for my $s (0 .. $#{$ops->[$i][$k][3]}) {
4899
4900 # add node
4901 # CxF3 schema requires integer values for RGB data
4902 $sub = $node->appendChild(XML::LibXML::Element->new($ops->[$i][$k][3][$s]));
4903 $sub->appendText($ops->[$i][$k][0] eq 'RGB' ? int($data[$s] + 0.5) : $data[$s]);
4904 $sub->setNamespace($nsURI, $ns);
4905
4906 }
4907
4908 # if NCLR class
4909 if ($ops->[$i][$k][0] eq 'NCLR') {
4910
4911 # for each spot color
4912 for my $s (4 .. $#data) {
4913
4914 # add SpotColor elements
4915 $spot = $node->appendChild(XML::LibXML::Element->new("$ns:SpotColor"));
4916 $spot->setNamespace($nsURI, $ns);
4917 $sub = $spot->appendChild(XML::LibXML::Element->new("$ns:Name"));
4918 $sub->appendText('Spot' . ($s + 1));
4919 $sub->setNamespace($nsURI, $ns);
4920 $sub = $spot->appendChild(XML::LibXML::Element->new("$ns:Percentage"));
4921 $sub->appendText($data[$s]);
4922 $sub->setNamespace($nsURI, $ns);
4923
4924 }
4925
4926 }
4927
4928 # no subpaths and one data value
4929 } elsif (@data == 1) {
4930
4931 # add data as text content
4932 $node->appendText($data[0]);
4933
4934 # no subpaths and multiple data values
4935 } elsif (@data > 1) {
4936
4937 # if DENSITY class
4938 if ($ops->[$i][$k][0] eq 'DENSITY') {
4939
4940 ##### to be done
4941
4942 } else {
4943
4944 # join data and add as text content
4945 $node->appendText(join(' ', @data));
4946
4947 }
4948
4949 }
4950
4951 }
4952
4953 # add Name attribute to TagCollection element
4954 $lookup{"$ns:TagCollection"}->setAttribute('Name', 'Location') if exists($lookup{"$ns:TagCollection"});
4955
4956 # if nothing was added to Object
4957 if ($node->isSameNode($obj)) {
4958
4959 # unbind the node
4960 $node->unbindNode();
4961
4962 } else {
4963
4964 # increment Object Id
4965 $id++;
4966
4967 }
4968
4969 }
4970
4971 }
4972  
4973 # validate the CxF3 document
4974 _validateCxF3($dom) if (defined($hash->{'validate'}) && $hash->{'validate'});
4975  
4976 # filter path
4977 ICC::Shared::filterPath($path);
4978  
4979 # write CxF3 file
4980 $dom->toFile($path, 1);
4981  
4982 }
4983  
4984 # write chart data array as delimited ASCII file (for Excel, R, MATLAB, etc.)
4985 # optional slice parameters are either scalars, array references or 'Math::Matrix' objects
4986 # optional hash parameter keys: 'header', 'sep', 'eol', and 'undef'
4987 # parameters: (path_to_file, [row_slice, [column_slice]], [hash])
4988 sub writeASCII {
4989  
4990 # local variables
4991 my ($hash, $row_length, $n, $fh);
4992 my ($fs, $rs, $undef, $hdr, @fields);
4993  
4994 # get optional hash parameter
4995 $hash = pop() if (ref($_[-1]) eq 'HASH');
4996  
4997 # get remaining parameters
4998 my ($self, $path, $rows, $cols) = @_;
4999  
5000 # if row slice defined
5001 if (defined($rows)) {
5002
5003 # if row slice an empty array reference
5004 if (ref($rows) eq 'ARRAY' && @{$rows} == 0) {
5005
5006 # use all rows
5007 $rows = [1 .. $#{$self->[1]}];
5008
5009 } else {
5010
5011 # get row length if row slice is Math::Matrix object
5012 $row_length = @{$rows->[0]} if (UNIVERSAL::isa($rows, 'Math::Matrix'));
5013
5014 # flatten row slice
5015 $rows = ICC::Shared::flatten($rows);
5016
5017 }
5018
5019 } else {
5020
5021 # use all rows
5022 $rows = [1 .. $#{$self->[1]}];
5023
5024 }
5025  
5026 # get number of rows
5027 $n = @{$rows};
5028  
5029 # filter row slice
5030 @{$rows} = grep {$_ == int($_) && $_ != 0 && defined($self->[1][$_])} @{$rows};
5031  
5032 # warn if invalid samples
5033 ($n == @{$rows}) || warn('row slice contains invalid samples');
5034  
5035 # if column slice defined
5036 if (defined($cols)) {
5037
5038 # if column slice an empty array reference
5039 if (ref($cols) eq 'ARRAY' && @{$cols} == 0) {
5040
5041 # use all columns
5042 $cols = [0 .. $#{$self->[1][0]}];
5043
5044 } else {
5045
5046 # flatten column slice
5047 $cols = ICC::Shared::flatten($cols);
5048
5049 }
5050
5051 } else {
5052
5053 # use all columns
5054 $cols = [0 .. $#{$self->[1][0]}];
5055
5056 }
5057  
5058 # get number of columns
5059 $n = @{$cols};
5060  
5061 # filter column slice
5062 @{$cols} = grep {$_ == int($_) && defined($self->[1][0][$_])} @{$cols};
5063  
5064 # warn if invalid fields
5065 ($n == @{$cols}) || warn('column slice contains invalid fields');
5066  
5067 # filter path
5068 ICC::Shared::filterPath($path);
5069  
5070 # open the file
5071 open($fh, '>', $path) or croak("can't open $path: $!");
5072  
5073 # disable :crlf translation
5074 binmode($fh);
5075  
5076 # get header mode
5077 $hdr = $hash->{'header'} || 1;
5078  
5079 # get the field separator
5080 $fs = $hash->{'sep'} || "\t";
5081  
5082 # get the record separator
5083 $rs = $hash->{'eol'} || "\n";
5084  
5085 # get the undefined string
5086 $undef = $hash->{'undef'} || '';
5087  
5088 # if header enabled
5089 if ($hdr) {
5090
5091 # if format fields, replacing undefined values
5092 if (@fields = map {defined() ? $_ : $undef} @{$self->[1][0]}[@{$cols}]) {
5093
5094 # if header mode 2, remove contexts
5095 if ($hdr == 2) {for (@fields) {s/^.*\|//}};
5096
5097 # trim leading and trailing white space, and replace spaces with underscores
5098 for (@fields) {s/^\s*(.*?)\s*$/$1/; s/ /_/g};
5099
5100 # print format record
5101 print $fh join($fs, @fields), $rs;
5102
5103 }
5104
5105 }
5106  
5107 # for each row
5108 for my $i (@{$rows}) {
5109
5110 # get data fields, replacing undefined values
5111 @fields = map {defined() ? $_ : $undef} @{$self->[1][$i]}[@{$cols}];
5112
5113 # trim leading and trailing white space, and replace spaces with underscores
5114 for (@fields) {s/^\s*(.*?)\s*$/$1/; s/ /_/g};
5115
5116 # print the data record
5117 print $fh join($fs, @fields), $rs;
5118
5119 }
5120  
5121 # close the file
5122 close($fh);
5123  
5124 }
5125  
5126 # write TIFF file
5127 # RGB, CMYK, and CIE L*a*b* color spaces supported
5128 # 8-bit, 16-bit or 32-bit, Intel or Motorola byte order supported
5129 # alpha and spot channels in RGB and CMYK files supported
5130 # supported hash keys: 'width', 'height', 'gap', 'left', 'right', 'rows', 'bits', 'dither', 'endian', 'xres', 'yres', 'unit'
5131 # parameters: (path_to_file, [row_slice, [column_slice]], [hash])
5132 sub writeTIFF {
5133  
5134 # local variables
5135 my ($hash, $trows, $tcols, $n, $fh);
5136 my ($base, $cs, %fields, @alpha, $pi, $rcols, $fmt, $mult, $mab, $samples);
5137 my ($width, $height, $gap, $left, $right, $bits, $xres, $yres, $unit);
5138 my ($le, $short, $long, $fp, $max, $minab, $maxab);
5139 my ($tags, $imagewidth, $bytecount, $stripsize);
5140 my ($ifd, $data, @cmyk, @spot);
5141  
5142 # get optional hash
5143 $hash = pop() if (ref($_[-1]) eq 'HASH');
5144  
5145 # get remaining parameters
5146 my ($self, $path, $rows, $cols) = @_;
5147  
5148 # if row slice defined
5149 if (defined($rows)) {
5150
5151 # if row slice an empty array reference
5152 if (ref($rows) eq 'ARRAY' && @{$rows} == 0) {
5153
5154 # use all rows
5155 $rows = [1 .. $#{$self->[1]}];
5156
5157 } else {
5158
5159 # get row length if row slice is Math::Matrix object
5160 $trows = @{$rows->[0]} if (UNIVERSAL::isa($rows, 'Math::Matrix'));
5161
5162 # flatten row slice
5163 $rows = ICC::Shared::flatten($rows);
5164
5165 }
5166
5167 } else {
5168
5169 # use all rows
5170 $rows = [1 .. $#{$self->[1]}];
5171
5172 }
5173  
5174 # get number of rows
5175 $n = @{$rows};
5176  
5177 # filter row slice
5178 @{$rows} = grep {$_ == int($_) && $_ != 0 && defined($self->[1][$_])} @{$rows};
5179  
5180 # warn if invalid samples
5181 ($n == @{$rows}) || warn('row slice contains invalid samples');
5182  
5183 # get target row length, if not defined by row matrix
5184 $trows = _getRowLength($self, $hash) if (! defined($trows));
5185  
5186 # limit to number of samples
5187 $trows = $trows > $n ? $n : $trows;
5188  
5189 # verify row length
5190 ($trows == int($trows) && $trows > 0) || croak('invalid row length, stopped');
5191  
5192 # compute target columns
5193 $tcols = int($n/$trows) + ($n % $trows ? 1 : 0);
5194  
5195 # if column slice defined
5196 if (defined($cols)) {
5197
5198 # if column slice an empty array reference
5199 if (ref($cols) eq 'ARRAY' && @{$cols} == 0) {
5200
5201 # use all columns
5202 $cols = [0 .. $#{$self->[1][0]}];
5203
5204 } else {
5205
5206 # flatten column slice
5207 $cols = ICC::Shared::flatten($cols);
5208
5209 }
5210
5211 } else {
5212
5213 # use all columns
5214 $cols = [0 .. $#{$self->[1][0]}];
5215
5216 }
5217  
5218 # get number of columns
5219 $n = @{$cols};
5220  
5221 # filter column slice
5222 @{$cols} = grep {$_ == int($_) && defined($self->[1][0][$_])} @{$cols};
5223  
5224 # warn if invalid fields
5225 ($n == @{$cols}) || warn('column slice contains invalid fields');
5226  
5227 # for each column in slice
5228 for (@{$self->[1][0]}[@{$cols}]) {
5229
5230 # if a supported color space
5231 if (m/^((?:.*\|)?(RGB|CMYK|[4-9A-F]CLR|LAB)_)/) {
5232
5233 # set base and color space
5234 $base = $1;
5235 $cs = $2;
5236
5237 # quit loop
5238 last();
5239
5240 }
5241
5242 }
5243  
5244 # verify color space
5245 (defined($cs)) || croak('column slice does not contain a supported color space, stopped');
5246  
5247 # get bits per sample and verify
5248 $bits = defined($hash->{'bits'}) ? $hash->{'bits'} : 16;
5249 ($bits == 8 || $bits == 16 || $bits == 32) || croak('invalid \'bits\' parameter, stopped');
5250  
5251 # set little-endian flag from system config
5252 $le = ($Config{'byteorder'} =~ m/1234/);
5253  
5254 # if endian parameter provided
5255 if (defined($hash->{'endian'})) {
5256  
5257 # if little-endian
5258 if ($hash->{'endian'} eq 'little') {
5259
5260 # set flag
5261 $le = 1;
5262
5263 # if big-endian
5264 } elsif ($hash->{'endian'} eq 'big') {
5265
5266 # clear flag
5267 $le = 0;
5268
5269 } else {
5270
5271 # warn
5272 warn('invalid \'endian\' parameter');
5273
5274 }
5275
5276 }
5277  
5278 # if little-endian
5279 if ($le) {
5280
5281 # set 'pack' formats
5282 $short = 'v';
5283 $long = 'V';
5284 $fp = 'f<';
5285
5286 } else {
5287
5288 # set 'pack' formats
5289 $short = 'n';
5290 $long = 'N';
5291 $fp = 'f>';
5292
5293 }
5294  
5295 # make lookup hash of column slice fields
5296 %fields = map {defined($self->[1][0][$_]) ? ($self->[1][0][$_], $_) : ()} @{$cols};
5297  
5298 # if color space is RGB
5299 if ($cs eq 'RGB') {
5300
5301 # set photometric interpretation
5302 $pi = 2;
5303
5304 # get alpha channels (if any)
5305 @alpha = map {defined($fields{"$base$_"}) ? $fields{"$base$_"} : ()} ('A', 'A0' .. 'A9');
5306
5307 # get refined column slice (including alpha channels)
5308 $rcols = [(map {$fields{"$base$_"}} qw(R G B)), @alpha];
5309
5310 # set pack format (8, 16 or 32 bits)
5311 $fmt = ($bits == 8) ? 'C*' : ($bits == 16) ? "$short*" : "$fp*";
5312
5313 # set multiplier (8, 16 or 32 bits)
5314 $mult = ($bits == 8) ? 1 : ($bits == 16) ? 257 : 1/255;
5315
5316 # if color space is CMYK (8 or 16 bits)
5317 } elsif ($cs eq 'CMYK' && $bits != 32) {
5318
5319 # set photometric interpretation
5320 $pi = 5;
5321
5322 # get refined column slice
5323 $rcols = [map {$fields{"$base$_"}} qw(C M Y K)];
5324
5325 # set pack format (8 or 16 bits)
5326 $fmt = ($bits == 8) ? 'C*' : "$short*";
5327
5328 # set multiplier (8 or 16 bits)
5329 $mult = ($bits == 8) ? 2.55 : 655.35;
5330
5331 # if color space is nCLR (8 or 16 bits)
5332 } elsif ($cs =~ m/^([4-9A-F])CLR$/ && $bits != 32) {
5333
5334 # set photometric interpretation
5335 $pi = 5;
5336
5337 # get refined column slice
5338 $rcols = [map {$fields{sprintf('%s%x', $base, $_)}} (1 .. CORE::hex($1))];
5339
5340 # set pack format (8 or 16 bits)
5341 $fmt = ($bits == 8) ? 'C*' : "$short*";
5342
5343 # set multiplier (8 or 16 bits)
5344 $mult = ($bits == 8) ? 2.55 : 655.35;
5345
5346 # if color space if L*a*b* (8 or 16 bits)
5347 } elsif ($cs eq 'LAB' && $bits != 32) {
5348
5349 # set photometric interpretation
5350 $pi = 8;
5351
5352 # get refined column slice
5353 $rcols = [map {$fields{"$base$_"}} qw(L A B)];
5354
5355 # set pack format (8 or 16 bits)
5356 $fmt = ($bits == 8) ? '(Ccc)*' : "$short*";
5357
5358 # set multipliers (8 or 16 bits)
5359 $mult = ($bits == 8) ? 2.55 : 655.35; # L*
5360 $mab = ($bits == 8) ? 1 : 256; # a* and b*
5361
5362 } else {
5363
5364 # error
5365 croak('invalid TIFF format');
5366
5367 }
5368  
5369 # verify all fields defined
5370 (@{$rcols} == grep {defined()} @{$rcols}) || croak('column slice has missing fields, stopped');
5371  
5372 # set number of samples
5373 $samples = @{$rcols};
5374  
5375 # get the sample patch width and verify
5376 $width = defined($hash->{'width'}) ? $hash->{'width'} : 1;
5377 ($width == int($width) && $width > 0) || croak('invalid \'width\' parameter, stopped');
5378  
5379 # get the sample patch height and verify
5380 $height = defined($hash->{'height'}) ? $hash->{'height'} : 1;
5381 ($height == int($height) && $height > 0) || croak('invalid \'height\' parameter, stopped');
5382  
5383 # get the sample patch gap and verify
5384 $gap = defined($hash->{'gap'}) ? $hash->{'gap'} : 0;
5385 ($gap == int($gap) && $gap >= 0) || croak('invalid \'gap\' parameter, stopped');
5386  
5387 # get the left edge width and verify
5388 $left = defined($hash->{'left'}) ? $hash->{'left'} : 0;
5389 ($left =~ m/^([0-9]+)(?:\.([0-9]+))?$/ && (! defined($2) || $1 >= $2)) || croak('invalid \'left\' parameter, stopped');
5390 $left = [$1, defined($2) ? $2 : 0];
5391  
5392 # get the right edge width and verify
5393 $right = defined($hash->{'right'}) ? $hash->{'right'} : 0;
5394 ($right =~ m/^([0-9]+)(?:\.([0-9]+))?$/ && (! defined($2) || $1 >= $2)) || croak('invalid \'right\' parameter, stopped');
5395 $right = [$1, defined($2) ? $2 : 0];
5396  
5397 # get the x-resolution and verify
5398 $xres = defined($hash->{'xres'}) ? $hash->{'xres'} : 72;
5399 ($xres > 0 && $xres <= 4E4) || croak('invalid \'xres\' parameter, stopped');
5400  
5401 # get the y-resolution and verify
5402 $yres = defined($hash->{'yres'}) ? $hash->{'yres'} : 72;
5403 ($yres > 0 && $yres <= 4E4) || croak('invalid \'yres\' parameter, stopped');
5404  
5405 # get the resolution unit and verify
5406 $unit = defined($hash->{'unit'}) ? $hash->{'unit'} : 2;
5407 ($unit == 1 || $unit == 2 || $unit == 3) || croak('invalid \'unit\' parameter, stopped');
5408  
5409 # compute image width
5410 $imagewidth = $tcols * $width + ($tcols - 1) * $gap + $left->[0] - $left->[1] + $right->[0] - $right->[1];
5411  
5412 # compute strip byte count
5413 $bytecount = $imagewidth * $height * $samples * $bits/8;
5414  
5415 # compute strip size (strips must begin on word boundary)
5416 $stripsize = $bytecount + $bytecount % 2;
5417  
5418 # set image tags [type, data]
5419 $tags->{'256'} = [3, $imagewidth]; # ImageWidth
5420 $tags->{'257'} = [3, $trows * $height]; # ImageLength
5421 $tags->{'258'} = [3, ($bits) x $samples]; # BitsPerSample
5422 $tags->{'259'} = [3, 1]; # Compression
5423 $tags->{'262'} = [3, $pi]; # PhotometricInterpretation
5424 $tags->{'273'} = [4, map {$_ * $stripsize + 8} (0 .. $trows - 1)]; # StripOffsets
5425 $tags->{'277'} = [3, $samples]; # SamplesPerPixel
5426 $tags->{'278'} = [3, $height]; # RowsPerStrip
5427 $tags->{'279'} = [4, ($bytecount) x $trows]; # StripByteCounts
5428 $tags->{'282'} = [5, $xres * 1E4, 1E4]; # XResolution
5429 $tags->{'283'} = [5, $yres * 1E4, 1E4]; # YResolution
5430 $tags->{'296'} = [3, $unit]; # ResolutionUnit
5431 $tags->{'339'} = [3, (3) x $samples] if ($bits == 32); # SampleFormat
5432  
5433 # filter path
5434 ICC::Shared::filterPath($path);
5435  
5436 # open the file
5437 open($fh, '>', $path) or croak("can't open $path: $!");
5438  
5439 # set binary mode
5440 binmode($fh);
5441  
5442 # write TIFF header
5443 print $fh pack("A2$short$long", $le ? 'II' : 'MM', 42, $ifd = $trows * $stripsize + 8);
5444  
5445 # set min/max values
5446 $max = ($bits == 8) ? 255 : ($bits == 16) ? 65535 : 1;
5447 $minab = ($bits == 8) ? -128 : -32768;
5448 $maxab = ($bits == 8) ? 127 : 32767;
5449  
5450 # for each strip
5451 for my $i (0 .. $trows - 1) {
5452
5453 # for each patch in strip
5454 for my $j (0 .. $tcols - 1) {
5455
5456 # if patch in row slice
5457 if (defined($rows->[$trows * $j + $i])) {
5458
5459 # if L*a*b* data
5460 if ($pi == 8) {
5461
5462 # get the data
5463 $data->[$j][0] = $mult * $self->[1][$rows->[$trows * $j + $i]][$rcols->[0]];
5464 $data->[$j][1] = $mab * $self->[1][$rows->[$trows * $j + $i]][$rcols->[1]];
5465 $data->[$j][2] = $mab * $self->[1][$rows->[$trows * $j + $i]][$rcols->[2]];
5466
5467 # limit the data
5468 $data->[$j][0] = $data->[$j][0] < 0 ? 0 : ($data->[$j][0] > $max ? $max : $data->[$j][0]);
5469 $data->[$j][1] = $data->[$j][1] < $minab ? $minab : ($data->[$j][1] > $maxab ? $maxab : $data->[$j][1]);
5470 $data->[$j][2] = $data->[$j][2] < $minab ? $minab : ($data->[$j][2] > $maxab ? $maxab : $data->[$j][2]);
5471
5472 # if CMYK + spot data
5473 } elsif ($pi == 5 && @{$rcols} > 4) {
5474
5475 # get CMYK values
5476 @cmyk = @{$self->[1][$rows->[$trows * $j + $i]]}[@{$rcols}[0 .. 3]];
5477
5478 # get spot values
5479 @spot = @{$self->[1][$rows->[$trows * $j + $i]]}[@{$rcols}[4 .. $#{$rcols}]];
5480
5481 # get the data (spot channels are inverted)
5482 $data->[$j] = [(map {$_ * $mult} @cmyk), (map {(100 - $_) * $mult} @spot)];
5483
5484 # limit the data
5485 @{$data->[$j]} = map {$_ < 0 ? 0 : ($_ > $max ? $max : $_)} @{$data->[$j]};
5486
5487 # RGB data
5488 } else {
5489
5490 # get the data
5491 $data->[$j] = [map {$_ * $mult} @{$self->[1][$rows->[$trows * $j + $i]]}[@{$rcols}]];
5492
5493 # limit the data (8 or 16 bits)
5494 @{$data->[$j]} = map {$_ < 0 ? 0 : ($_ > $max ? $max : $_)} @{$data->[$j]} if ($bits != 32);
5495
5496 }
5497
5498 # patch undefined
5499 } else {
5500
5501 # if L*a*b* data
5502 if ($pi == 8) {
5503
5504 # if last patch
5505 if ($i == ($trows - 1) && $j == ($tcols - 1)) {
5506
5507 # set gray value
5508 $data->[$j] = [$max * 0.7, 0, 0];
5509
5510 } else {
5511
5512 # set white value
5513 $data->[$j] = [$max, 0, 0];
5514
5515 }
5516
5517 # if CMYK + spot data
5518 } elsif ($pi == 5) {
5519
5520 # if last patch
5521 if ($i == ($trows - 1) && $j == ($tcols - 1)) {
5522
5523 # set gray value
5524 $data->[$j] = [0, 0, 0, $max * 0.4, ($max) x ($samples - 4)];
5525
5526 } else {
5527
5528 # set white value
5529 $data->[$j] = [0, 0, 0, 0, ($max) x ($samples - 4)];
5530
5531 }
5532
5533 # RGB data
5534 } else {
5535
5536 # if last patch
5537 if ($i == ($trows - 1) && $j == ($tcols - 1)) {
5538
5539 # set gray value
5540 $data->[$j] = [($max * 0.7) x $samples];
5541
5542 } else {
5543
5544 # set white value
5545 $data->[$j] = [($max) x $samples];
5546
5547 }
5548
5549 }
5550
5551 }
5552
5553 }
5554
5555 # write TIFF strip
5556 _writeTIFFstrip($fh, $tags, $width, $gap, $left, $right, $i, $data, $fmt, $hash->{'dither'});
5557
5558 }
5559  
5560 # write TIFF IFD
5561 _writeTIFFdir($fh, $ifd, $short, $long, $tags);
5562  
5563 # close file
5564 close($fh);
5565  
5566 }
5567  
5568 # write chart to Adobe Swatch Exchange (.ase) file
5569 # column slice must be CMYK, RGB or L*a*b*
5570 # color type: 0 - global, 1 - spot, 2 - normal (default)
5571 # parameters: (path_to_file, row_slice, column_slice, [color_type])
5572 sub writeASE {
5573  
5574 # get parameters
5575 my ($self, $path, $rows, $cols, $type) = @_;
5576  
5577 # local variables
5578 my ($n, @fmt, $cs, $le, $sn, $fh);
5579 my ($name, $slen, $blen);
5580 my ($cmyk, $rgb, $Lab, $val);
5581  
5582 # verify row_slice and column_slice are supplied
5583 (defined($rows) && defined($cols)) || croak('missing parameters');
5584  
5585 # if row slice an empty array reference
5586 if (ref($rows) eq 'ARRAY' && @{$rows} == 0) {
5587
5588 # use all rows
5589 $rows = [1 .. $#{$self->[1]}];
5590
5591 } else {
5592
5593 # flatten row slice
5594 $rows = ICC::Shared::flatten($rows);
5595
5596 }
5597  
5598 # get number of rows
5599 $n = @{$rows};
5600  
5601 # filter row slice
5602 @{$rows} = grep {$_ == int($_) && $_ != 0 && defined($self->[1][$_])} @{$rows};
5603  
5604 # warn if invalid samples
5605 ($n == @{$rows}) || warn('row slice contains invalid samples');
5606  
5607 # get format array
5608 @fmt = @{$self->[1][0]}[@{$cols}];
5609  
5610 # if column slice is CMYK
5611 if (4 == @fmt && 4 == grep {m/^(?:.*\|)?CMYK_[CMYK]$/} @fmt) {
5612
5613 # set color space
5614 $cs = 'CMYK';
5615
5616 # if column slice is RGB
5617 } elsif (3 == @fmt && 3 == grep {m/^(?:.*\|)?RGB_[RGB]$/} @fmt) {
5618
5619 # set color space
5620 $cs = 'RGB ';
5621
5622 # if column slice is L*a*b*
5623 } elsif (3 == @fmt && 3 == grep {m/^(?:.*\|)?LAB_[LAB]$/} @fmt) {
5624
5625 # set color space
5626 $cs = 'LAB ';
5627
5628 } else {
5629
5630 # error
5631 croak('invalid column slice');
5632
5633 }
5634  
5635 # if color type is undefined, set default (2 - normal)
5636 $type = 2 if (! defined($type));
5637  
5638 # verify color type
5639 ($type == int($type) && $type >= 0 && $type <= 2) || croak('invalid ASE color type');
5640  
5641 # get little-endian flag
5642 $le = ($Config{'byteorder'} =~ m/1234/);
5643  
5644 # get sample name slice (could be undefined)
5645 $sn = $self->name;
5646  
5647 # filter path
5648 ICC::Shared::filterPath($path);
5649  
5650 # open the file
5651 open($fh, '>', $path) or croak("can't open $path: $!");
5652  
5653 # set binary mode
5654 binmode($fh);
5655  
5656 # print header (file signature, version, number of blocks)
5657 print $fh pack('A4nnN', 'ASEF', 1, 0, scalar(@{$rows}));
5658  
5659 # for each sample
5660 for my $s (@{$rows}) {
5661
5662 # if color space is CMYK
5663 if ($cs eq 'CMYK') {
5664
5665 # get the CMYK values
5666 $cmyk = $self->slice([$s], $cols);
5667
5668 # if SAMPLE_NAME is defined
5669 if (defined($sn)) {
5670
5671 # get color name
5672 $name = $self->[1][$s][$sn->[0]];
5673
5674 # replace underscores with spaces
5675 $name =~ s/_/ /g;
5676
5677 } else {
5678
5679 # build color name from CMYK values
5680 $name = sprintf('C=%d M=%d Y=%d K=%d', @{$cmyk->[0]});
5681
5682 }
5683
5684 # compute string length
5685 $slen = length($name) + 1;
5686
5687 # compute block length
5688 $blen = 2 * $slen + 24;
5689
5690 # print block
5691 print $fh pack('nNn', 1, $blen, $slen);
5692 print $fh encode('UTF-16BE', $name . "\x00");
5693 print $fh pack('A4', 'CMYK');
5694
5695 # for each CMYK value
5696 for my $i (0 .. 3) {
5697
5698 # convert to floating point
5699 $val = pack('f', $cmyk->[0][$i]/100);
5700
5701 # reverse if little-endian system
5702 $val = reverse($val) if ($le);
5703
5704 # print value
5705 print $fh $val;
5706
5707 }
5708
5709 # print color type
5710 print $fh pack('n', $type);
5711
5712 # if color space is RGB
5713 } elsif ($cs eq 'RGB ') {
5714
5715 # get the RGB values
5716 $rgb = $self->slice([$s], $cols);
5717
5718 # if SAMPLE_NAME is defined
5719 if (defined($sn)) {
5720
5721 # get color name
5722 $name = $self->[1][$s][$sn->[0]];
5723
5724 # replace underscores with spaces
5725 $name =~ s/_/ /g;
5726
5727 } else {
5728
5729 # build color name from RGB values
5730 $name = sprintf('R=%d G=%d B=%d', @{$rgb->[0]});
5731
5732 }
5733
5734 # compute string length
5735 $slen = length($name) + 1;
5736
5737 # compute block length
5738 $blen = 2 * $slen + 20;
5739
5740 # print block
5741 print $fh pack('nNn', 1, $blen, $slen);
5742 print $fh encode('UTF-16BE', $name . "\x00");
5743 print $fh pack('A4', 'RGB ');
5744
5745 # for each RGB value
5746 for my $i (0 .. 2) {
5747
5748 # convert to floating point
5749 $val = pack('f', $rgb->[0][$i]/255);
5750
5751 # reverse if little-endian system
5752 $val = reverse($val) if ($le);
5753
5754 # print value
5755 print $fh $val;
5756
5757 }
5758
5759 # print color type
5760 print $fh pack('n', $type);
5761
5762 # if color space is L*a*b*
5763 } elsif ($cs eq 'LAB ') {
5764
5765 # get the L*a*b* values
5766 $Lab = $self->slice([$s], $cols);
5767
5768 # if SAMPLE_NAME is defined
5769 if (defined($sn)) {
5770
5771 # get color name
5772 $name = $self->[1][$s][$sn->[0]];
5773
5774 # replace underscores with spaces
5775 $name =~ s/_/ /g;
5776
5777 } else {
5778
5779 # build color name from L*a*b* values
5780 $name = sprintf('L=%d a=%d b=%d', @{$Lab->[0]});
5781
5782 }
5783
5784 # compute string length
5785 $slen = length($name) + 1;
5786
5787 # compute block length
5788 $blen = 2 * $slen + 20;
5789
5790 # print block
5791 print $fh pack('nNn', 1, $blen, $slen);
5792 print $fh encode('UTF-16BE', $name . "\x00");
5793 print $fh pack('A4', 'LAB ');
5794
5795 # modify L* value
5796 $Lab->[0][0] /= 100;
5797
5798 # for each L*a*b* value
5799 for my $i (0 .. 2) {
5800
5801 # convert to floating point
5802 $val = pack('f', $Lab->[0][$i]);
5803
5804 # reverse if little-endian system
5805 $val = reverse($val) if ($le);
5806
5807 # print value
5808 print $fh $val;
5809
5810 }
5811
5812 # print color type
5813 print $fh pack('n', $type);
5814
5815 }
5816
5817 }
5818  
5819 # close file
5820 close($fh);
5821  
5822 }
5823  
5824 # print object contents to string
5825 # format is an array structure
5826 # parameter: ([format])
5827 # returns: (string)
5828 sub sdump {
5829  
5830 # get parameters
5831 my ($self, $p) = @_;
5832  
5833 # local variables
5834 my ($s, $fmt);
5835  
5836 # resolve parameter to an array reference
5837 $p = defined($p) ? ref($p) eq 'ARRAY' ? $p : [$p] : [];
5838  
5839 # get format string
5840 $fmt = defined($p->[0]) && ! ref($p->[0]) ? $p->[0] : 'undef';
5841  
5842 # set string to object ID
5843 $s = sprintf("'%s' object, (0x%x)\n", ref($self), $self);
5844  
5845 # return
5846 return($s);
5847  
5848 }
5849  
5850 # get column slice from DATA_FORMAT keys
5851 # format_keys is a list of keys with optional context
5852 # column_slice is reference to an array of column indices
5853 # note: returns 'undef' if any column is missing
5854 # parameters: (format_keys)
5855 # returns: (column_slice)
5856 sub _cols {
5857  
5858 # get object reference
5859 my $self = shift();
5860  
5861 # local variables
5862 my (%fmt, @cols);
5863  
5864 # make lookup hash of DATA_FORMAT keys
5865 %fmt = map {defined($self->[1][0][$_]) ? ($self->[1][0][$_], $_) : ()} (0 .. $#{$self->[1][0]});
5866  
5867 # lookup format keys in hash
5868 @cols = @fmt{@_};
5869  
5870 # return column slice or undef if any columns undefined
5871 return((grep {! defined()} @cols) ? undef : \@cols);
5872  
5873 }
5874  
5875 # get spectral fields array
5876 # array contains column indices and wavelength
5877 # and is sorted by wavelength (low to high)
5878 # parameters: (object_reference, [context])
5879 # returns: (array_reference)
5880 sub _spectral {
5881  
5882 # get parameters
5883 my ($self, $context) = @_;
5884  
5885 # local variables
5886 my (%fmt, @fields);
5887  
5888 # make lookup hash (context|wavelength -or- wavelength => column)
5889 %fmt = map {($self->[1][0][$_] =~ m/^(.*\|)?(?:nm|SPECTRAL_NM_|SPECTRAL_NM|SPECTRAL_|NM_|R_)(\d{3})$/) ? (defined($1) ? "$1$2" : $2, $_) : ()} (0 .. $#{$self->[1][0]});
5890  
5891 # if context defined
5892 if (defined($context)) {
5893
5894 # make list of matching fields
5895 @fields = map {m/^$context\|(\d{3})$/ ? [$fmt{$_}, $1] : ()} keys(%fmt);
5896
5897 } else {
5898
5899 # make list of matching fields
5900 @fields = map {m/^(\d{3})$/ ? [$fmt{$_}, $1] : ()} keys(%fmt);
5901
5902 # if no matching fields
5903 if (@fields == 0) {
5904
5905 # make lookup hash (wavelength => column)
5906 %fmt = map {($self->[1][0][$_] =~ m/^(?:.*\|)?(?:nm|SPECTRAL_NM_|SPECTRAL_NM|SPECTRAL_|NM_|R_)(\d{3})$/) ? ($1, $_) : ()} (0 .. $#{$self->[1][0]});
5907
5908 # make list of fields
5909 @fields = map {[$fmt{$_}, $_]} keys(%fmt);
5910
5911 }
5912
5913 }
5914  
5915 # return undef if no match
5916 return() if (@fields == 0);
5917  
5918 # sort by wavelength
5919 @fields = sort {$a->[1] <=> $b->[1]} @fields;
5920  
5921 # return array reference
5922 return(\@fields);
5923  
5924 }
5925  
5926 # fix incorrectly scaled (X-Rite) data
5927 # checks spectral, XYZ and xyY data
5928 # parameters: (object_ref)
5929 sub _scale_check {
5930  
5931 # get object reference
5932 my $self = shift();
5933  
5934 # local variables
5935 my (@s, $pct, $cie);
5936  
5937 # get indices of suspect spectral values
5938 @s = grep {$self->[1][0][$_] =~ /^SPECTRAL_(NM)?\d{3}$/} (0 .. $#{$self->[1][0]});
5939  
5940 # if format found
5941 if (@s) {
5942
5943 # for each sample
5944 for my $i (1 .. $#{$self->[1]}) {
5945
5946 # if average value > 2 (must be %-values)
5947 if (List::Util::sum(@{$self->[1][$i]}[@s])/@s > 2) {
5948
5949 # set %-value flag
5950 $pct = 1;
5951
5952 last;
5953
5954 }
5955
5956 }
5957
5958 # if %-values
5959 if ($pct) {
5960
5961 # for each sample
5962 for my $i (1 .. $#{$self->[1]}) {
5963
5964 # for each spectral value
5965 for my $j (@s) {
5966
5967 # fix value
5968 $self->[1][$i][$j] /= 100;
5969
5970 }
5971
5972 }
5973
5974 }
5975
5976 }
5977  
5978 # get indices of XYZ or XYY values
5979 @s = grep {$self->[1][0][$_] =~ /^(XYZ_[XYZ]|XYY_CAPY)$/} (0 .. $#{$self->[1][0]});
5980  
5981 # if format found
5982 if (@s) {
5983
5984 # for each sample
5985 for my $i (1 .. $#{$self->[1]}) {
5986
5987 # if average value > 2 (must be CIE values)
5988 if (List::Util::sum(@{$self->[1][$i]}[@s])/@s > 2) {
5989
5990 # set CIE flag
5991 $cie = 1;
5992
5993 last;
5994
5995 }
5996
5997 }
5998
5999 # if not CIE values
6000 if (! $cie) {
6001
6002 # for each sample
6003 for my $i (1 .. $#{$self->[1]}) {
6004
6005 # for each value
6006 for my $j (@s) {
6007
6008 # fix value
6009 $self->[1][$i][$j] *= 100;
6010
6011 }
6012
6013 }
6014
6015 }
6016
6017 }
6018
6019 }
6020  
6021 # binary search
6022 # locates the interval containing or bounding the target value
6023 # returns an array of four index values, which indicate upper and lower transitions
6024 # parameters: (source_array, target_value, channel_index, low_index, high_index)
6025 # returns: (interval_index_array)
6026 sub _bin_search {
6027
6028 # get parameters
6029 my ($source, $target, $channel, $low, $high) = @_;
6030
6031 # local variables
6032 my ($k, $interval);
6033
6034 # copy low and high indices
6035 $interval->[0] = $low;
6036 $interval->[1] = $high;
6037
6038 # while interval is open
6039 while ($interval->[1] - $interval->[0] > 1) {
6040
6041 # compute the midpoint
6042 $k = int(($interval->[1] + $interval->[0])/2);
6043
6044 # if midpoint value >= target value
6045 if ($source->[$k][$channel] >= $target) {
6046
6047 # set higher index to midpoint
6048 $interval->[1] = $k;
6049
6050 } else {
6051
6052 # set lower index to midpoint
6053 $interval->[0] = $k;
6054
6055 }
6056
6057 }
6058
6059 # copy low and high indices
6060 $interval->[2] = $low;
6061 $interval->[3] = $high;
6062
6063 # while interval is open
6064 while ($interval->[3] - $interval->[2] > 1) {
6065
6066 # compute the midpoint
6067 $k = int(($interval->[3] + $interval->[2])/2);
6068
6069 # if midpoint value > target value
6070 if ($source->[$k][$channel] > $target) {
6071
6072 # set higher index to midpoint
6073 $interval->[3] = $k;
6074
6075 } else {
6076
6077 # set lower index to midpoint
6078 $interval->[2] = $k;
6079
6080 }
6081
6082 }
6083
6084 # return interval array
6085 return($interval);
6086
6087 }
6088  
6089 # linear search
6090 # locates the closest source sample based on Manhattan distance
6091 # parameters: (source_array, target_vector)
6092 # returns: (low_index, high_index)
6093 sub _lin_search {
6094
6095 # get parameters
6096 my ($source, $target) = @_;
6097
6098 # local variables
6099 my ($d0, $d1, $d2, $low, $high);
6100
6101 # set initial difference
6102 $d0 = @{$target};
6103
6104 # for each source sample
6105 for my $i (0 .. $#{$source}) {
6106
6107 # clear differences
6108 $d1 = $d2 = 0;
6109
6110 # for each channel
6111 for my $j (0 .. $#{$target}) {
6112
6113 # add difference to target sample
6114 $d1 += abs($source->[$i][$j] - $target->[$j]);
6115
6116 # add difference to previous sample
6117 $d2 += abs($source->[$i][$j] - $source->[$i - 1][$j]) if ($i > 0);
6118
6119 }
6120
6121 # if new difference less
6122 if ($d1 < $d0) {
6123
6124 # save index
6125 $low = $high = $i;
6126
6127 # update difference
6128 $d0 = $d1;
6129
6130 }
6131
6132 # if duplicate sample
6133 if ($d0 == $d1 && $d2 == 0) {
6134
6135 # save index
6136 $high = $i;
6137
6138 }
6139
6140 }
6141
6142 # return
6143 return($low, $high);
6144
6145 }
6146  
6147 # add average sample
6148 # assumes device values (if any) are same for each sample
6149 # averages measurements values - spectral, XYZ, L*a*b*, or density
6150 # L*a*b* values are converted to xyz for averaging, then back to L*a*b*
6151 # density values are converted to reflectance for averaging, then back to density
6152 # parameters: (object_reference, row_slice, linear_slice, L*a*b*_slice, density_slice, id_slice, name_slice, hash)
6153 # returns: (average_sample_index)
6154 sub _add_avg {
6155  
6156 # get parameters
6157 my ($self, $rows, $c1, $c2, $c3, $id, $name, $hash) = @_;
6158  
6159 # local variables
6160 my ($n, $next, @xyz, $sid, $sn);
6161  
6162 # get number of samples
6163 $n = @{$rows};
6164  
6165 # get index of next data row
6166 $next = $#{$self->[1]} + 1;
6167  
6168 # copy first sample
6169 $self->[1][$next] = [@{$self->[1][shift(@{$rows})]}];
6170  
6171 # for each group of L*a*b* columns
6172 for (my $j = 0; $j < @{$c2}; $j += 3) {
6173
6174 # convert to L*a*b* values to xyz
6175 @{$self->[1][$next]}[@{$c2}[$j .. $j + 2]] = ICC::Shared::_Lab2xyz(@{$self->[1][$next]}[@{$c2}[$j .. $j + 2]]);
6176
6177 }
6178
6179 # for each density column
6180 for my $j (@{$c3}) {
6181
6182 # convert to density to reflectance
6183 $self->[1][$next][$j] = POSIX::pow(10, -$self->[1][$next][$j]);
6184
6185 }
6186  
6187 # for remaining samples
6188 for my $i (@{$rows}) {
6189
6190 # for each linear column
6191 for my $j (@{$c1}) {
6192
6193 # add value
6194 $self->[1][$next][$j] += $self->[1][$i][$j];
6195
6196 }
6197
6198 # for each group of L*a*b* columns
6199 for (my $j = 0; $j < @{$c2}; $j += 3) {
6200
6201 # get xyz values
6202 @xyz = ICC::Shared::_Lab2xyz(@{$self->[1][$i]}[@{$c2}[$j .. $j + 2]]);
6203
6204 # add to self
6205 $self->[1][$next][$c2->[$j]] += $xyz[0];
6206 $self->[1][$next][$c2->[$j + 1]] += $xyz[1];
6207 $self->[1][$next][$c2->[$j + 2]] += $xyz[2];
6208
6209 }
6210
6211 # for each density column
6212 for my $j (@{$c3}) {
6213
6214 # add temp reflectance
6215 $self->[1][$next][$j] += POSIX::pow(10, -$self->[1][$i][$j]);
6216
6217 }
6218
6219 }
6220  
6221 # for each measurement column
6222 for my $j (@{$c1}, @{$c2}, @{$c3}) {
6223
6224 # divide by number of samples
6225 $self->[1][$next][$j] /= $n;
6226
6227 }
6228  
6229 # for each group of L*a*b* columns
6230 for (my $j = 0; $j < @{$c2}; $j += 3) {
6231
6232 # convert to xyz values to L*a*b*
6233 @{$self->[1][$next]}[@{$c2}[$j .. $j + 2]] = ICC::Shared::_xyz2Lab(@{$self->[1][$next]}[@{$c2}[$j .. $j + 2]]);
6234
6235 }
6236  
6237 # for each density column
6238 for my $j (@{$c3}) {
6239
6240 # convert to reflectance to density
6241 $self->[1][$next][$j] = -POSIX::log10($self->[1][$next][$j]);
6242
6243 }
6244  
6245 # get SAMPLE_ID value from hash
6246 $sid = $hash->{'id'};
6247  
6248 # for each SAMPLE_ID column
6249 for my $i (@{$id}) {
6250
6251 # if SAMPLE_ID defined
6252 if (defined($sid)) {
6253
6254 # set to hash value
6255 $self->[1][$next][$i] = $sid;
6256
6257 } else {
6258
6259 # set to row index
6260 $self->[1][$next][$i] = $next;
6261
6262 }
6263
6264 }
6265  
6266 # get SAMPLE_NAME value from hash
6267 $sn = $hash->{'name'};
6268  
6269 # for each SAMPLE_NAME column
6270 for my $i (@{$name}) {
6271
6272 # if SAMPLE_NAME defined
6273 if (defined($sn)) {
6274
6275 # set to hash value
6276 $self->[1][$next][$i] = $sn;
6277
6278 } else {
6279
6280 # append '_AVG' to existing value
6281 $self->[1][$next][$i] .= '_AVG';
6282
6283 }
6284
6285 }
6286  
6287 # return row
6288 return($next);
6289  
6290 }
6291  
6292 # get averaging groups
6293 # returns column slices for each averaging method
6294 # parameters: (object_reference, hash)
6295 # returns: (linear_slice, L*a*b*_slice, density_slice)
6296 sub _avg_groups {
6297  
6298 # get parameters
6299 my ($self, $hash) = @_;
6300  
6301 # local variables
6302 my (@c1, @c2, @c3, @cs);
6303  
6304 # for each format field
6305 for my $i (0 .. $#{$self->[1][0]}) {
6306
6307 # add column if XYZ or spectral field
6308 push(@c1, $i) if ($self->[1][0][$i] =~ m/^(?:.*\|)?(?:XYZ_[XYZ]|(?:nm|SPECTRAL_NM_|SPECTRAL_NM|SPECTRAL_|NM_|R_)\d{3})$/);
6309
6310 # add column if L*a*b* field
6311 push(@c2, $i) if ($self->[1][0][$i] =~ m/^(?:.*\|)?LAB_[LAB]$/);
6312
6313 # add column if density field
6314 push(@c3, $i) if ($self->[1][0][$i] =~ m/^(?:.*\|)?D_(?:RED|GREEN|BLUE|VIS)$/);
6315
6316 }
6317
6318 # linear averaging method (L*a*b* values are converted to xyz, density values are converted to reflectance)
6319 if (! defined($hash->{'method'}) || $hash->{'method'} eq 'LINEAR') {
6320
6321 # verify number of L*a*b* fields
6322 (@c2 % 3 == 0) || croak('wrong number of L*a*b* fields');
6323
6324 # for each group of L*a*b* columns
6325 for (my $j = 0; $j < @c2; $j += 3) {
6326
6327 # sort by field name
6328 @cs = sort {$self->[1][0][$a] cmp $self->[1][0][$b]} @c2[$j .. $j + 2];
6329
6330 # verify field consistency
6331 (join('', map {substr($_, -1, 1)} @{$self->[1][0]}[@cs]) eq 'ABL') || croak('L*a*b* field inconsistency');
6332
6333 # save columns in LAB order
6334 @c2[$j .. $j + 2] = @cs[2, 0, 1];
6335
6336 }
6337
6338 # if simple averaging method
6339 } elsif (defined($hash->{'method'}) && $hash->{'method'} eq 'SIMPLE') {
6340
6341 # copy L*a*b* and density columns to XYZ or spectral array
6342 push(@c1, @c2, @c3);
6343
6344 # clear L*a*b* and density arrays
6345 @c2 = ();
6346 @c3 = ();
6347
6348 } else {
6349
6350 # error
6351 croak('unsupported averaging method');
6352
6353 }
6354  
6355 # return slices
6356 return(\@c1, \@c2, \@c3);
6357  
6358 }
6359  
6360 # add OBA effect to XYZ array
6361 # parameters: (chart_object, M1_slice, M2_slice, XYZ_array, oba_factor, hash)
6362 sub _add_oba {
6363  
6364 # get parameters
6365 my ($self, $spec1, $spec2, $xyz, $oba, $hash) = @_;
6366  
6367 # local variables
6368 my ($color, $illum, @m1, @m2, $spectral, $xyzoba);
6369  
6370 # save illuminant
6371 $illum = $hash->{'illuminant'};
6372  
6373 # if illuminant an array reference
6374 if (defined($hash->{'illuminant'}) && ref($hash->{'illuminant'}) eq 'ARRAY') {
6375
6376 # set illuminant to CIE D50
6377 $hash->{'illuminant'} = ['CIE', 'D50'];
6378
6379 } else {
6380
6381 # set illuminant to ASTM D50
6382 $hash->{'illuminant'} = 'D50';
6383
6384 }
6385  
6386 # make 'Color.pm' object (D50 illuminant)
6387 $color = ICC::Support::Color->new($hash);
6388  
6389 # restore illuminant
6390 $hash->{'illuminant'} = $illum;
6391  
6392 # for each sample
6393 for my $i (1 .. $#{$self->[1]}) {
6394
6395 # get M1 spectral values
6396 @m1 = @{$self->[1][$i]}[@{$spec1}];
6397
6398 # get M2 spectral values
6399 @m2 = @{$self->[1][$i]}[@{$spec2}];
6400
6401 # compute (M1 - M2) spectral values
6402 $spectral->[$i - 1] = [map {$m1[$_] - $m2[$_]} (0 .. $#m1)];
6403
6404 }
6405  
6406 # transform (M1 - M2) spectral to D50 XYZ (hash may contain 'encoding' key)
6407 $xyzoba = ICC::Support::Color::_trans2($color, $spectral, $hash);
6408  
6409 # for each sample
6410 for my $i (0 .. $#{$xyz}) {
6411
6412 # for each XYZ
6413 for my $j (0 .. 2) {
6414
6415 # add scaled OBA effect
6416 $xyz->[$i][$j] += $xyzoba->[$i][$j] * $oba;
6417
6418 }
6419
6420 }
6421
6422 }
6423  
6424 # get/set data
6425 # common routine called by get/set methods
6426 # row_slice and column_slice may be either a scalar or array reference
6427 # an empty array reference indicates all samples or fields
6428 # replacement_data is reference to a 2-D array of replacement values
6429 # array dimensions must match size of row_slice and column_slice
6430 # data_slice is Math::Matrix object, defined by row_slice and column_slice
6431 # get_code_ref and set_code_ref transform the data when getting and setting
6432 # parameters: (object_ref, object_index, row_slice, column_slice, replacement_data, get_code_ref, set_code_ref)
6433 # if column_slice undefined, returns: ()
6434 # if row_slice undefined, returns: (column_slice)
6435 # if replacement_data undefined, returns: (data_slice)
6436 # otherwise, sets replacement data and returns: (column_slice)
6437 sub _getset {
6438  
6439 # get parameters
6440 my ($self, $ix, $rows, $cols, $data, $get, $set) = @_;
6441  
6442 # return empty if no column slice
6443 defined($cols) || return();
6444  
6445 # if column slice an empty array reference
6446 if (ref($cols) eq 'ARRAY' && @{$cols} == 0) {
6447
6448 # use all columns
6449 $cols = [0 .. $#{$self->[$ix][0]}];
6450
6451 } else {
6452
6453 # flatten column slice
6454 $cols = ICC::Shared::flatten($cols);
6455
6456 # verify column slice contents
6457 (@{$cols} == grep {! ref() && $_ == int($_) && $_ >= 0} @{$cols}) || croak('invalid column slice');
6458
6459 }
6460  
6461 # return columns slice if no row slice
6462 defined($rows) || return($cols);
6463  
6464 # if row slice an empty array reference
6465 if (ref($rows) eq 'ARRAY' && @{$rows} == 0) {
6466
6467 # use all rows
6468 $rows = [1 .. $#{$self->[$ix]}];
6469
6470 } else {
6471
6472 # flatten row slice
6473 $rows = ICC::Shared::flatten($rows);
6474
6475 # verify row slice contents
6476 (@{$rows} == grep {! ref() && $_ == int($_) && $_ >= 0} @{$rows}) || croak('invalid row slice');
6477
6478 }
6479  
6480 # no replacement data (get)
6481 if (! defined($data)) {
6482
6483 # verify 'get' code ref, or use identity function
6484 $get = (defined($get) && ref($get) eq 'CODE') ? $get : sub {@_};
6485
6486 # for each row
6487 for my $i (0 .. $#{$rows}) {
6488
6489 # get transformed data row
6490 @{$data->[$i]} = &$get(@{$self->[$ix][$rows->[$i]]}[@{$cols}]);
6491
6492 }
6493
6494 # return data slice as a Math::Matrix object
6495 return(bless($data, 'Math::Matrix'));
6496
6497 # with replacement data (set)
6498 } else {
6499
6500 # verify replacement data is 2-D array or Math::Matrix object
6501 ((ref($data) eq 'ARRAY' || UNIVERSAL::isa($data, 'Math::Matrix')) && ref($data->[0]) eq 'ARRAY') || croak('replacement data not a 2-D array reference');
6502
6503 # verify replacement data size
6504 ($#{$data} == $#{$rows} && $#{$data->[0]} == $#{$cols}) || croak('replacement data is wrong sized');
6505
6506 # verify 'set' code ref, or use identity function
6507 $set = (defined($set) && ref($set) eq 'CODE') ? $set : sub {@_};
6508
6509 # for each row
6510 for my $i (0 .. $#{$rows}) {
6511
6512 # set transformed data row
6513 @{$self->[$ix][$rows->[$i]]}[@{$cols}] = &$set(@{$data->[$i]});
6514
6515 }
6516
6517 # return column slice
6518 return($cols);
6519
6520 }
6521
6522 }
6523  
6524 # get accumulated sample values
6525 # sample dimensions are in pixels
6526 # used by _readChartTIFF to extract samples from a data stripe
6527 # parameters: (reference_to_data, sample_offset, sample_width, number_channels)
6528 # returns: (accumulated_sample_values)
6529 sub _getSample {
6530
6531 # get parameters
6532 my ($data, $so, $sx, $c) = @_;
6533
6534 # initialize sample values
6535 my @sv = (0) x $c;
6536
6537 # for each row
6538 for my $i (0 .. $#{$data}) {
6539
6540 # for each pixel
6541 for my $j (0 .. $sx - 1) {
6542
6543 # for each channel
6544 for my $k (0 .. $c - 1) {
6545
6546 # accumulate sample value
6547 $sv[$k] += $data->[$i][($so + $j) * $c + $k];
6548
6549 }
6550
6551 }
6552
6553 }
6554
6555 # return sample values
6556 return(@sv);
6557
6558 }
6559  
6560 # get row length
6561 # parameters: (object_reference, hash)
6562 # returns: (row_length)
6563 sub _getRowLength {
6564  
6565 # get parameters
6566 my ($self, $hash) = @_;
6567  
6568 # local variables
6569 my ($rows, $n, $square);
6570  
6571 # if 'rows' hash key is defined
6572 if (defined($hash->{'rows'})) {
6573
6574 # get row length value
6575 $rows = $hash->{'rows'};
6576
6577 # if valid row length
6578 if (Scalar::Util::looks_like_number($rows) && $rows > 0 && $rows == int($rows)) {
6579
6580 # return
6581 return($rows);
6582
6583 } else {
6584
6585 # warn
6586 warn('invalid \'rows\' parameter');
6587
6588 }
6589
6590 }
6591
6592 # if LGOROWLENGTH keyword
6593 if ($rows = keyword($self, 'LGOROWLENGTH')) {
6594
6595 # if valid row length
6596 if (Scalar::Util::looks_like_number($rows) && $rows > 0 && $rows == int($rows)) {
6597
6598 # return
6599 return($rows);
6600
6601 } else {
6602
6603 # warn
6604 warn('invalid \'LGOROWLENGTH\' value');
6605
6606 }
6607
6608 }
6609
6610 # if NUMBER_OF_STRIPS keyword
6611 if ($rows = keyword($self, 'NUMBER_OF_STRIPS')) {
6612
6613 # if valid row length
6614 if (Scalar::Util::looks_like_number($rows) && $rows > 0 && $rows == int($rows)) {
6615
6616 # return
6617 return($rows);
6618
6619 } else {
6620
6621 # warn
6622 warn('invalid \'NUMBER_OF_STRIPS\' value');
6623
6624 }
6625
6626 }
6627
6628 # if 'NumberPatchRows' key is defined
6629 if (defined($self->[0]{'xrp:CustomAttributes'}{'NumberPatchRows'})) {
6630
6631 # get row length value
6632 $rows = $self->[0]{'xrp:CustomAttributes'}{'NumberPatchRows'};
6633
6634 # if valid row length
6635 if (Scalar::Util::looks_like_number($rows) && $rows > 0 && $rows == int($rows)) {
6636
6637 # return
6638 return($rows);
6639
6640 } else {
6641
6642 # warn
6643 warn('invalid \'NumberPatchRows\' attribute');
6644
6645 }
6646
6647 }
6648  
6649 # get number of samples
6650 $n = $#{$self->[1]};
6651  
6652 # return if 0
6653 return(0) if ($n == 0);
6654  
6655 # return if 1 or 2
6656 return(1) if ($n < 3);
6657  
6658 # compute size of square chart
6659 $square = POSIX::ceil(sqrt($n));
6660  
6661 # return if chart is square
6662 return($square) if ($n == $square**2);
6663  
6664 # set row length one less than square chart
6665 $rows = $square - 1;
6666  
6667 # while modulus is non-zero, decrement row length
6668 while ($n % $rows) {$rows--}
6669  
6670 # return row length, choosing full rectangle if possible
6671 return($rows > $square/2 ? $rows : $square);
6672  
6673 }
6674  
6675 # get illuminant white point
6676 # returns XYZ vector from colorimetry array
6677 # returns D50 if CAT or undefined
6678 # parameter: (object_reference, column_slice, [hash])
6679 # returns: (XYZ_vector)
6680 sub _illumWP {
6681  
6682 # get parameters
6683 my ($self, $cols, $hash) = @_;
6684  
6685 # if XYZ values are valid
6686 if (3 == grep {defined() && ! ref() && $_ > 0} @{$self->[2][2]}[@{$cols}]) {
6687
6688 # return XYZ vector
6689 return([@{$self->[2][2]}[@{$cols}]]);
6690
6691 } else {
6692
6693 # return D50 vector
6694 return(ICC::Shared::D50);
6695
6696 }
6697  
6698 }
6699  
6700 # compute media white point
6701 # multiple samples are averaged
6702 # result also stored in colorimetry array
6703 # parameter: (object_reference, column_slice, [hash])
6704 # returns: (XYZ_vector)
6705 sub _mediaWP {
6706  
6707 # get parameters
6708 my ($self, $cols, $hash) = @_;
6709  
6710 # local variables
6711 my ($WPxyz, $dev, $mwv, $n, @XYZ, @XYZs);
6712  
6713 # if column slice is L*a*b*
6714 if ((3 == grep {$self->[1][0][$_] =~ m/LAB_[LAB]$/} @{$cols})) {
6715
6716 # get illuminant white point
6717 $WPxyz = defined($self->[2][2][$cols->[0]]) ? [@{$self->[2][2]}[@{$cols}]] : ICC::Shared::D50;
6718
6719 # if column slice is not XYZ
6720 } elsif ((3 != grep {$self->[1][0][$_] =~ m/XYZ_[XYZ]$/} @{$cols})) {
6721
6722 # warning
6723 warn('column slice not XYZ or L*a*b* data');
6724
6725 # return empty
6726 return();
6727
6728 }
6729  
6730 # if no device data (using 'device' context)
6731 if (! ($dev = device($self, {'context' => $hash->{'device'}}))) {
6732
6733 # warning
6734 warn('no device data');
6735
6736 # return empty
6737 return();
6738
6739 }
6740  
6741 # set media white device value (255 if RGB, 0 otherwise)
6742 $mwv = ($self->[1][0][$dev->[0]] =~ m/RGB_R$/) ? 255 : 0;
6743  
6744 # for each sample
6745 for my $i (1 .. $#{$self->[1]}) {
6746
6747 # if all device channels are white
6748 if (@{$dev} == grep {$_ == $mwv} @{$self->[1][$i]}[@{$dev}]) {
6749
6750 # if L*a*b* data
6751 if ($WPxyz) {
6752
6753 # convert L*a*b* values to XYZ
6754 @XYZs = ICC::Shared::_Lab2XYZ(@{$self->[1][$i]}[@{$cols}], $WPxyz);
6755
6756 # accumulate XYZ values
6757 $XYZ[0] += $XYZs[0];
6758 $XYZ[1] += $XYZs[1];
6759 $XYZ[2] += $XYZs[2];
6760
6761 # if XYZ data
6762 } else {
6763
6764 # accumulate XYZ values
6765 $XYZ[0] += $self->[1][$i][$cols->[0]];
6766 $XYZ[1] += $self->[1][$i][$cols->[1]];
6767 $XYZ[2] += $self->[1][$i][$cols->[2]];
6768
6769 }
6770
6771 # increment count
6772 $n++;
6773
6774 }
6775
6776 }
6777  
6778 # if media white sample(s)
6779 if ($n) {
6780
6781 # store average XYZ values in colorimetry array, and return XYZ vector
6782 return([@{$self->[2][3]}[@{$cols}] = map {$_/$n} @XYZ]);
6783
6784 } else {
6785
6786 # warning
6787 warn('no media white sample found');
6788
6789 # return empty
6790 return();
6791
6792 }
6793
6794 }
6795  
6796 # compute media black point
6797 # multiple samples are averaged
6798 # result also stored in colorimetry array
6799 # parameter: (object_reference, column_slice, [hash])
6800 # returns: (XYZ_vector)
6801 sub _mediaBP {
6802  
6803 # get parameters
6804 my ($self, $cols, $hash) = @_;
6805  
6806 # local variables
6807 my ($WPxyz, $dev, $mbv, $n, @XYZ, @XYZs);
6808  
6809 # if column slice is L*a*b*
6810 if ((3 == grep {$self->[1][0][$_] =~ m/LAB_[LAB]$/} @{$cols})) {
6811
6812 # get illuminant white point
6813 $WPxyz = defined($self->[2][2][$cols->[0]]) ? [@{$self->[2][2]}[@{$cols}]] : ICC::Shared::D50;
6814
6815 # if column slice is not XYZ
6816 } elsif ((3 != grep {$self->[1][0][$_] =~ m/XYZ_[XYZ]$/} @{$cols})) {
6817
6818 # warning
6819 warn('column slice not XYZ or L*a*b* data');
6820
6821 # return empty
6822 return();
6823
6824 }
6825  
6826 # if no device data (using 'device' context)
6827 if (! ($dev = device($self, {'context' => $hash->{'device'}}))) {
6828
6829 # warning
6830 warn('no device data');
6831
6832 # return empty
6833 return();
6834
6835 }
6836  
6837 # set media black device value (0 if RGB, 100 otherwise)
6838 $mbv = ($self->[1][0][$dev->[0]] =~ m/RGB_R$/) ? 1 : 100;
6839  
6840 # for each sample
6841 for my $i (1 .. $#{$self->[1]}) {
6842
6843 # if all device channels are black
6844 if (@{$dev} == grep {$_ == $mbv} @{$self->[1][$i]}[@{$dev}]) {
6845
6846 # increment count
6847 $n++;
6848
6849 # if L*a*b* data
6850 if ($WPxyz) {
6851
6852 # convert L*a*b* values to XYZ
6853 @XYZs = ICC::Shared::_Lab2XYZ(@{$self->[1][$i]}[@{$cols}], $WPxyz);
6854
6855 # accumulate XYZ values
6856 $XYZ[0] += $XYZs[0];
6857 $XYZ[1] += $XYZs[1];
6858 $XYZ[2] += $XYZs[2];
6859
6860 # if XYZ data
6861 } else {
6862
6863 # accumulate XYZ values
6864 $XYZ[0] += $self->[1][$i][$cols->[0]];
6865 $XYZ[1] += $self->[1][$i][$cols->[1]];
6866 $XYZ[2] += $self->[1][$i][$cols->[2]];
6867
6868 }
6869
6870 }
6871
6872 }
6873  
6874 # if media black sample(s)
6875 if ($n) {
6876
6877 # store average XYZ values in colorimetry array, and return XYZ vector
6878 return([@{$self->[2][4]}[@{$cols}] = map {$_/$n} @XYZ]);
6879
6880 } else {
6881
6882 # warning
6883 warn('no media black sample found');
6884
6885 # return empty
6886 return();
6887
6888 }
6889
6890 }
6891  
6892 # make SAMPLE_ID hash
6893 # if no SAMPLE_ID field, hash is initialized
6894 # parameter: (object_reference)
6895 sub _makeSampleID {
6896  
6897 # get object reference
6898 my $self = shift();
6899  
6900 # if SAMPLE_ID column(s) exist
6901 if (my @id = grep {$self->[1][0][$_] =~ m/^(?:.*\|)?(?:SAMPLE_ID|SampleID)$/} (0 .. $#{$self->[1][0]})) {
6902
6903 # make the SAMPLE_ID hash, omitting undefined ID values
6904 $self->[4] = {map {defined($self->[1][$_][$id[0]]) ? ($self->[1][$_][$id[0]], $_) : ()} (1 .. $#{$self->[1]})};
6905
6906 } else {
6907
6908 # initialize the hash
6909 $self->[4] = {};
6910
6911 }
6912  
6913 }
6914  
6915 # add colorimetry metadata
6916 # called when creating a new object
6917 # parameter: (object_reference)
6918 sub _addColorMeta {
6919  
6920 # get object reference
6921 my $self = shift();
6922  
6923 # local variables
6924 my (@cols, $hash, $illum, $spec, $nm, $str, $color, $WPxyz, @values);
6925  
6926 # if object contains colorimetric data
6927 if (@cols = grep {$self->[1][0][$_] =~ m/^(?:(.*)\|)?(?:LAB_[LAB]|XYZ_[XYZ]|STDEV_[LABXYZ]|MEAN_DE|STDEV_DE|CHI_SQD_PAR)$/} (0 .. $#{$self->[1][0]})) {
6928
6929 # set default hash values
6930 $hash = {'illuminant' => 'D50', 'observer' => '2'};
6931
6932 # if CxF3 'TristimulusSpec' node
6933 if (defined($self->[0]{'CxF3_dom'}) && 0) {
6934
6935 ##### to be implemented #####
6936
6937 # if 'WEIGHTING_FUNCTION' keyword(s)
6938 } elsif (@values = keyword($self, 'WEIGHTING_FUNCTION')) {
6939
6940 # join values into string
6941 $str = join(';', @values);
6942
6943 # match illuminant and save in hash
6944 $hash->{'illuminant'} = $1 if ($str =~ m/ILLUMINANT\s*,\s*(\w+)"/);
6945
6946 # match observer and save in hash
6947 $hash->{'observer'} = $1 if ($str =~ m/OBSERVER\s*,\s*(\d+).*"/);
6948
6949 }
6950
6951 # if non-standard illuminant
6952 if ($hash->{'illuminant'} ne 'D50' || $hash->{'observer'} ne '2') {
6953
6954 # make an empty 'Color.pm' object
6955 $color = ICC::Support::Color->new();
6956
6957 # if illuminant is an ARRAY reference
6958 if (ref($hash->{'illuminant'}) eq 'ARRAY') {
6959
6960 # initialize object for CIE method
6961 ICC::Support::Color::_cie($color, $hash);
6962
6963 } else {
6964
6965 # initialize object for ASTM method
6966 ICC::Support::Color::_astm($color, $hash);
6967
6968 }
6969
6970 # use computed white point
6971 $WPxyz = $color->iwtpt();
6972
6973 } else {
6974
6975 # use D50
6976 $WPxyz = ICC::Shared::D50;
6977
6978 }
6979
6980 # for each colorimetric field
6981 for my $i (@cols) {
6982
6983 # if field name ends in L or X
6984 if ($self->[1][0][$i] =~ m/[LX]$/) {
6985
6986 # save WP X-value
6987 $self->[2][2][$i] = $WPxyz->[0];
6988
6989 # if field name ends in A or Y
6990 } elsif ($self->[1][0][$i] =~ m/[AY]$/) {
6991
6992 # save WP Y-value
6993 $self->[2][2][$i] = $WPxyz->[1];
6994
6995 # if field name ends in B or Z
6996 } elsif ($self->[1][0][$i] =~ m/[BZ]$/) {
6997
6998 # save WP Z-value
6999 $self->[2][2][$i] = $WPxyz->[2];
7000
7001 }
7002
7003 }
7004
7005 }
7006
7007 }
7008  
7009 # read chart from list of data files
7010 # averages color measurement data (spectral, XYZ, L*a*b* or density)
7011 # files must have identical structure (rows and cols)
7012 # parameters: (object_reference, ref_to_file_list, hash)
7013 # returns: (number_of_files_averaged)
7014 sub _readChartAvg {
7015  
7016 # get parameters
7017 my ($self, $list, $hash) = @_;
7018  
7019 # local variables
7020 my ($n, $result, $c1, $c2, $c3, $keys, $temp, @xyz);
7021 my ($charts, $fstat, @ctx1, @ctx2, $add_hash);
7022  
7023 # initialize file count
7024 $n = 0;
7025  
7026 # if hash is defined
7027 if (defined($hash)) {
7028
7029 # for each hash key
7030 for (keys(%{$hash})) {
7031
7032 # if XYZ based stat requested
7033 if (m/^STDEV_XYZ$/) {
7034
7035 # if value is a scalar
7036 if (! ref($hash->{$_})) {
7037
7038 # save XYZ context
7039 push(@ctx1, $hash->{$_});
7040
7041 } elsif (ref($hash->{$_}) eq 'ARRAY') {
7042
7043 # save XYZ contexts
7044 push(@ctx1, @{$hash->{$_}});
7045
7046 }
7047
7048 # increment flag
7049 $fstat++;
7050
7051 # if L*a*b* based stat requested
7052 } elsif (m/^(MEAN_DE|STDEV_LAB|CHI_SQD_PAR)$/) {
7053
7054 # if value is a scalar
7055 if (! ref($hash->{$_})) {
7056
7057 # save L*a*b* context
7058 push(@ctx2, $hash->{$_});
7059
7060 } elsif (ref($hash->{$_}) eq 'ARRAY') {
7061
7062 # save L*a*b* contexts
7063 push(@ctx2, @{$hash->{$_}});
7064
7065 }
7066
7067 # increment flag
7068 $fstat++;
7069
7070 }
7071
7072 }
7073
7074 }
7075  
7076 # for each file
7077 for my $file (@{$list}) {
7078
7079 # if first file
7080 if ($n == 0) {
7081
7082 # if file read successfully
7083 if (! ($result = _readChart($self, $file, $hash))) {
7084
7085 # add colorimetric metadata
7086 _addColorMeta($self);
7087
7088 # make format key string
7089 $keys = join(':', map {defined() ? $_ : '-'} @{$self->[1][0]});
7090
7091 # for each XYZ context
7092 for my $ctx (@ctx1) {
7093
7094 # copy the hash
7095 $add_hash = Storable::dclone($hash);
7096
7097 # set the context (undef for no context)
7098 $add_hash->{'context'} = defined($ctx) && length($ctx) ? $ctx : undef;
7099
7100 # delete the 'added' context
7101 delete($add_hash->{'added'});
7102
7103 # add the XYZ values
7104 add_xyz($self, $add_hash);
7105
7106 }
7107
7108 # for each L*a*b* context
7109 for my $ctx (@ctx2) {
7110
7111 # copy the hash
7112 $add_hash = Storable::dclone($hash);
7113
7114 # set the context (undef for no context)
7115 $add_hash->{'context'} = defined($ctx) && length($ctx) ? $ctx : undef;
7116
7117 # delete the 'added' context
7118 delete($add_hash->{'added'});
7119
7120 # add the L*a*b* values
7121 add_lab($self, $add_hash);
7122
7123 }
7124
7125 # save copy of chart data, if needed for stats
7126 $charts->[0] = Storable::dclone($self->[1]) if ($fstat);
7127
7128 # get averaging groups
7129 ($c1, $c2, $c3) = _avg_groups($self, $hash);
7130
7131 # if there are L*a*b* or density groups
7132 if (@{$c2} || @{$c3}) {
7133
7134 # for each sample
7135 for my $i (1 .. $#{$self->[1]}) {
7136
7137 # for each group of L*a*b* columns
7138 for (my $j = 0; $j < @{$c2}; $j += 3) {
7139
7140 # convert to L*a*b* values to xyz
7141 @{$self->[1][$i]}[@{$c2}[$j .. $j + 2]] = ICC::Shared::_Lab2xyz(@{$self->[1][$i]}[@{$c2}[$j .. $j + 2]]);
7142
7143 }
7144
7145 # for each density column
7146 for my $j (@{$c3}) {
7147
7148 # convert to density to reflectance
7149 $self->[1][$i][$j] = POSIX::pow(10, -$self->[1][$i][$j]);
7150
7151 }
7152
7153 }
7154
7155 }
7156
7157 # increment file count
7158 $n++;
7159
7160 } else {
7161
7162 # print warning
7163 warn("chart $file $result, ignored\n");
7164
7165 }
7166
7167 } else {
7168
7169 # make temporary Chart object
7170 $temp = ICC::Support::Chart->new();
7171
7172 # if file read successfully
7173 if (! ($result = _readChart($temp, $file, $hash))) {
7174
7175 # if charts have same structure (rows and cols)
7176 if ($#{$self->[1]} == $#{$temp->[1]} && $keys eq join(':', map {defined() ? $_ : '-'} @{$temp->[1][0]})) {
7177
7178 # for each XYZ context
7179 for my $ctx (@ctx1) {
7180
7181 # copy the hash
7182 $add_hash = Storable::dclone($hash);
7183
7184 # set the context (undef for no context)
7185 $add_hash->{'context'} = defined($ctx) && length($ctx) ? $ctx : undef;
7186
7187 # delete the 'added' context
7188 delete($add_hash->{'added'});
7189
7190 # add the XYZ values
7191 add_xyz($temp, $add_hash);
7192
7193 }
7194
7195 # for each L*a*b* context
7196 for my $ctx (@ctx2) {
7197
7198 # copy the hash
7199 $add_hash = Storable::dclone($hash);
7200
7201 # set the context (undef for no context)
7202 $add_hash->{'context'} = defined($ctx) && length($ctx) ? $ctx : undef;
7203
7204 # delete the 'added' context
7205 delete($add_hash->{'added'});
7206
7207 # add the L*a*b* values
7208 add_lab($temp, $add_hash);
7209
7210 }
7211
7212 # save copy of chart data, if needed for stats
7213 $charts->[$n] = $temp->[1] if ($fstat);
7214
7215 # for each sample
7216 for my $i (1 .. $#{$self->[1]}) {
7217
7218 # for each linear column
7219 for my $j (@{$c1}) {
7220
7221 # add temp value
7222 $self->[1][$i][$j] += $temp->[1][$i][$j];
7223
7224 }
7225
7226 # for each group of L*a*b* columns
7227 for (my $j = 0; $j < @{$c2}; $j += 3) {
7228
7229 # get temp xyz values
7230 @xyz = ICC::Shared::_Lab2xyz(@{$temp->[1][$i]}[@{$c2}[$j .. $j + 2]]);
7231
7232 # add to self
7233 $self->[1][$i][$c2->[$j]] += $xyz[0];
7234 $self->[1][$i][$c2->[$j + 1]] += $xyz[1];
7235 $self->[1][$i][$c2->[$j + 2]] += $xyz[2];
7236
7237 }
7238
7239 # for each density column
7240 for my $j (@{$c3}) {
7241
7242 # add temp reflectance
7243 $self->[1][$i][$j] += POSIX::pow(10, -$temp->[1][$i][$j]);
7244
7245 }
7246
7247 }
7248
7249 # increment file count
7250 $n++;
7251
7252 } else {
7253
7254 # print warning
7255 warn("chart $file has different structure, ignored\n");
7256
7257 }
7258
7259 } else {
7260
7261 # print warning
7262 warn("chart $file $result, ignored\n");
7263
7264 }
7265
7266 }
7267
7268 }
7269  
7270 # if any files were read
7271 if ($n) {
7272
7273 # if there are measurement values
7274 if (@{$c1} || @{$c2} || @{$c3}) {
7275
7276 # for each sample
7277 for my $i (1 .. $#{$self->[1]}) {
7278
7279 # for each measurement column
7280 for my $j (@{$c1}, @{$c2}, @{$c3}) {
7281
7282 # divide by n
7283 $self->[1][$i][$j] /= $n;
7284
7285 }
7286
7287 # for each group of L*a*b* columns
7288 for (my $j = 0; $j < @{$c2}; $j += 3) {
7289
7290 # convert to xyz values to L*a*b*
7291 @{$self->[1][$i]}[@{$c2}[$j .. $j + 2]] = ICC::Shared::_xyz2Lab(@{$self->[1][$i]}[@{$c2}[$j .. $j + 2]]);
7292
7293 }
7294
7295 # for each density column
7296 for my $j (@{$c3}) {
7297
7298 # convert reflectance to density
7299 $self->[1][$i][$j] = -POSIX::log10($self->[1][$i][$j]);
7300
7301 }
7302
7303 }
7304
7305 }
7306
7307 # add ISO statistics, if requested
7308 _addStats($self, $charts, $hash) if ($fstat);
7309
7310 # print message
7311 print "$n files read in directory $self->[0]{'file_path'}\n\n";
7312
7313 # save number of files read
7314 $self->[0]{'files_read'} = $n;
7315
7316 }
7317  
7318 # return
7319 return($n);
7320  
7321 }
7322  
7323 # add ISO statistics
7324 # the object_reference contains the mean values
7325 # the individual charts are in the array_of_chart_objects
7326 # parameters: (object_reference, array_of_chart_objects, hash)
7327 sub _addStats {
7328  
7329 # get parameters
7330 my ($self, $charts, $hash) = @_;
7331  
7332 # local variables
7333 my (@ctx, $cols, $scols);
7334  
7335 # for each hash key
7336 for (keys(%{$hash})) {
7337
7338 # if value is a scalar
7339 if (! ref($hash->{$_})) {
7340
7341 # save context value
7342 @ctx = ($hash->{$_});
7343
7344 } elsif (ref($hash->{$_}) eq 'ARRAY') {
7345
7346 # save context values
7347 @ctx = @{$hash->{$_}};
7348
7349 }
7350
7351 # if 'STDEV_XYZ'
7352 if (m/^STDEV_XYZ$/) {
7353
7354 # for each context
7355 for my $context (@ctx) {
7356
7357 # resolve context value
7358 $context = defined($context) && length($context) ? $context : undef;
7359
7360 # if no STDEV_XYZ columns with context
7361 if (! test($self, 'STDEVXYZ', $context)) {
7362
7363 # get XYZ columns
7364 $cols = cols($self, map {defined($context) ? "$context|$_" : $_} qw(XYZ_X XYZ_Y XYZ_Z));
7365
7366 # add STDEV_XYZ columns
7367 $scols = add_fmt($self, map {defined($context) ? "$context|$_" : $_} qw(STDEV_X STDEV_Y STDEV_Z));
7368
7369 # for each XYZ
7370 for my $i (0 .. 2) {
7371
7372 # add STDEV_XYZ values
7373 _addStdDevCol($self, $charts, $cols->[$i], $scols->[$i]);
7374
7375 }
7376
7377 }
7378
7379 # set origin
7380 @{$self->[2][0]}[@{$scols}] = ($cols) x 3;
7381
7382 # save illuminant white point
7383 @{$self->[2][2]}[@{$scols}] = @{$self->[2][2]}[@{$cols}];
7384
7385 }
7386
7387 # if 'STDEV_LAB' or 'CHI_SQD_PAR'
7388 } elsif (m/^(STDEV_LAB|CHI_SQD_PAR)$/) {
7389
7390 # for each context
7391 for my $context (@ctx) {
7392
7393 # resolve context value
7394 $context = defined($context) && length($context) ? $context : undef;
7395
7396 # if no STDEV_LAB columns with context
7397 if (! test($self, 'STDEVLAB', $context)) {
7398
7399 # get L*a*b* columns
7400 $cols = cols($self, map {defined($context) ? "$context|$_" : $_} qw(LAB_L LAB_A LAB_B));
7401
7402 # add STDEV_LAB columns
7403 $scols = add_fmt($self, map {defined($context) ? "$context|$_" : $_} qw(STDEV_L STDEV_A STDEV_B));
7404
7405 # for each L*a*b*
7406 for my $i (0 .. 2) {
7407
7408 # add STDEV_LAB values
7409 _addStdDevCol($self, $charts, $cols->[$i], $scols->[$i]);
7410
7411 }
7412
7413 # set origin
7414 @{$self->[2][0]}[@{$scols}] = ($cols) x 3;
7415
7416 # save illuminant white point
7417 @{$self->[2][2]}[@{$scols}] = @{$self->[2][2]}[@{$cols}];
7418
7419 }
7420
7421 # if 'CHI_SQD_PAR'
7422 if ($1 eq 'CHI_SQD_PAR') {
7423
7424 # get STDEV_LAB columns
7425 $cols = cols($self, map {defined($context) ? "$context|$_" : $_} qw(STDEV_L STDEV_A STDEV_B));
7426
7427 # add CHI_SQD_PAR column
7428 $scols = add_fmt($self, map {defined($context) ? "$context|$_" : $_} qw(CHI_SQD_PAR));
7429
7430 # for each sample
7431 for my $i (1 .. $#{$self->[1]}) {
7432
7433 # set CHI_SQD_PAR value (average of L*a*b* standard deviations)
7434 $self->[1][$i][$scols->[0]] = List::Util::sum(@{$self->[1][$i]}[@{$cols}])/3;
7435
7436 }
7437
7438 # set origin
7439 $self->[2][0][$scols->[0]] = $cols;
7440
7441 }
7442
7443 }
7444
7445 # if 'MEAN_DE'
7446 } elsif (m/^MEAN_DE$/) {
7447
7448 # for each context
7449 for my $context (@ctx) {
7450
7451 # resolve context value
7452 $context = defined($context) && length($context) ? $context : undef;
7453
7454 # if no MEAN_DE columns with context
7455 if (! test($self, 'MEAN_DE', $context)) {
7456
7457 # get L*a*b* columns
7458 $cols = cols($self, map {defined($context) ? "$context|$_" : $_} qw(LAB_L LAB_A LAB_B));
7459
7460 # add MEAN_DE column
7461 $scols = add_fmt($self, map {defined($context) ? "$context|$_" : $_} qw(MEAN_DE));
7462
7463 # add MEAN_DE values
7464 _addMeanDECol($self, $charts, $cols, $scols->[0]);
7465
7466 # set origin
7467 $self->[2][0][$scols->[0]] = $cols;
7468
7469 }
7470
7471 }
7472
7473 }
7474
7475 }
7476
7477 }
7478  
7479 # add standard deviation column
7480 # the object_reference contains the mean values
7481 # the individual charts are in the array_of_chart_objects
7482 # parameters: (object_reference, array_of_chart_objects, mean_column, std_dev_column)
7483 sub _addStdDevCol {
7484  
7485 # get parameters
7486 my ($self, $charts, $m, $s) = @_;
7487  
7488 # local variables
7489 my ($n);
7490  
7491 # get number of charts
7492 $n = @{$charts};
7493  
7494 # for each sample
7495 for my $i (1 .. $#{$self->[1]}) {
7496
7497 # initialize value
7498 $self->[1][$i][$s] = 0;
7499
7500 # if number of charts > 0
7501 if ($n) {
7502
7503 # for each chart
7504 for my $j (0 .. $#{$charts}) {
7505
7506 # add squared difference
7507 $self->[1][$i][$s] += ($charts->[$j][$i][$m] - $self->[1][$i][$m])**2;
7508
7509 }
7510
7511 # complete calculation
7512 $self->[1][$i][$s] = sqrt($self->[1][$i][$s]/$n);
7513
7514 } else {
7515
7516 # error
7517 croak('can\'t compute standard deviation with zero samples');
7518
7519 }
7520
7521 }
7522
7523 }
7524  
7525 # add mean dEab column
7526 # the object_reference contains the mean values
7527 # the individual charts are in the array_of_chart_objects
7528 # parameters: (object_reference, array_of_chart_objects, mean_L*a*b*_columns, mean_dE_column)
7529 sub _addMeanDECol {
7530  
7531 # get parameters
7532 my ($self, $charts, $m, $s) = @_;
7533  
7534 # local variables
7535 my ($n, $dE);
7536  
7537 # get number of charts
7538 $n = @{$charts};
7539  
7540 # for each sample
7541 for my $i (1 .. $#{$self->[1]}) {
7542
7543 # initialize value
7544 $self->[1][$i][$s] = 0;
7545
7546 # if number of charts > 0
7547 if ($n) {
7548
7549 # for each chart
7550 for my $j (0 .. $#{$charts}) {
7551
7552 # initialize dE
7553 $dE = 0;
7554
7555 # for each L*a*b*
7556 for my $k (0 .. 2) {
7557
7558 # add squared difference
7559 $dE += ($self->[1][$i][$m->[$k]] - $charts->[$j][$i][$m->[$k]])**2;
7560
7561 }
7562
7563 # add dE for this chart
7564 $self->[1][$i][$s] += sqrt($dE);
7565
7566 }
7567
7568 # complete calculation
7569 $self->[1][$i][$s] /= $n;
7570
7571 } else {
7572
7573 # error
7574 croak('can\'t compute mean dE with zero samples');
7575
7576 }
7577
7578 }
7579
7580 }
7581  
7582 # read chart from list of data files
7583 # files must have identical structure (cols)
7584 # reads first chart, then appends other charts
7585 # parameters: (object_reference, ref_to_file_list, hash)
7586 # returns: (number_of_files_appended)
7587 sub _readChartAppend {
7588  
7589 # get parameters
7590 my ($self, $list, $hash) = @_;
7591  
7592 # local variables
7593 my ($n, $result, $keys, $temp);
7594  
7595 # initialize file counter
7596 $n = 0;
7597  
7598 # for each file
7599 for my $file (@{$list}) {
7600
7601 # if first file
7602 if ($n == 0) {
7603
7604 # if file read successfully
7605 if (! ($result = _readChart($self, $file, $hash))) {
7606
7607 # add colorimetric metadata
7608 _addColorMeta($self);
7609
7610 # make format key string
7611 $keys = join(':', map {defined() ? $_ : '-'} @{$self->[1][0]});
7612
7613 # increment counter
7614 $n++;
7615
7616 } else {
7617
7618 # print warning
7619 warn("chart $file $result, ignored\n");
7620
7621 }
7622
7623 } else {
7624
7625 # make temporary Chart object
7626 $temp = ICC::Support::Chart->new();
7627
7628 # if file read successfully
7629 if (! ($result = _readChart($temp, $file, $hash))) {
7630
7631 # if charts have same structure (cols)
7632 if ($keys eq join(':', map {defined() ? $_ : '-'} @{$temp->[1][0]})) {
7633
7634 # append temp samples
7635 push(@{$self->[1]}, @{$temp->[1]}[1 .. $#{$temp->[1]}]);
7636
7637 # increment counter
7638 $n++;
7639
7640 } else {
7641
7642 # print warning
7643 warn("chart $file has different structure, ignored\n");
7644
7645 }
7646
7647 } else {
7648
7649 # print warning
7650 warn("chart $file $result, ignored\n");
7651
7652 }
7653
7654 }
7655
7656 }
7657  
7658 # print message if any files were read
7659 print "$n files read in directory $self->[0]{'file_path'}\n\n" if ($n);
7660  
7661 # return
7662 return($n);
7663  
7664 }
7665  
7666 # read chart
7667 # parameters: (object_reference, path_to_file, hash)
7668 # returns: (result)
7669 sub _readChart {
7670  
7671 # get parameters
7672 my ($self, $path, $hash) = @_;
7673  
7674 # local variables
7675 my ($fh, $buf, $result);
7676  
7677 # open the file (read-only)
7678 open($fh, '<', $path) || return("$! when opening file");
7679  
7680 # set binary mode
7681 binmode($fh);
7682  
7683 # read start of file
7684 read($fh, $buf, 1024) || return("is zero length");
7685  
7686 # reset file pointer
7687 seek($fh, 0, 0);
7688  
7689 # if an ASE file
7690 if ($buf =~ m/^ASEF/) {
7691
7692 # save file type
7693 $self->[0]{'file_type'} = 'ASEF';
7694
7695 # read ASE file
7696 $result = _readChartASE($self, $fh, $hash);
7697
7698 # if a TIFF file
7699 } elsif ($buf =~ m/^(II\*\x00|MM\x00\*)/) {
7700
7701 # save file type
7702 $self->[0]{'file_type'} = 'TIFF';
7703
7704 # read TIFF file
7705 $result = _readChartTIFF($self, $fh, $hash);
7706
7707 # if an ICC profile
7708 } elsif (substr($buf, 36, 4) eq 'acsp') {
7709
7710 # save file type
7711 $self->[0]{'file_type'} = 'prof';
7712
7713 # read ICC file
7714 $result = _readChartICC($self, $fh, $hash);
7715
7716 # if an XML file
7717 } elsif ($buf =~ m/<\?xml/) {
7718
7719 # save file type
7720 $self->[0]{'file_type'} = 'CXFX';
7721
7722 # read CxF3 file
7723 $result = _readChartCxF3($self, $fh, $hash);
7724
7725 # if an SS3 file
7726 } elsif (substr($buf, 0, 4) eq "\x00\x20\x00\x00" || substr($buf, 0, 4) eq "\x00\x32\x00\x00") {
7727
7728 # save file type
7729 $self->[0]{'file_type'} = 'SS3';
7730
7731 # read SS3 file
7732 $result = _readChartSS3($self, $fh, $hash);
7733
7734 } else {
7735
7736 # check for CR-LF (DOS/Windows)
7737 if ($buf =~ m/\015\012/) {
7738
7739 # set record separator
7740 $self->[0]{'read_rs'} = "\015\012";
7741
7742 # check for LF (Unix/OSX)
7743 } elsif ($buf =~ m/\012/) {
7744
7745 # set record separator
7746 $self->[0]{'read_rs'} = "\012";
7747
7748 # check for CR (Mac)
7749 } elsif ($buf =~ m/\015/) {
7750
7751 # set record separator
7752 $self->[0]{'read_rs'} = "\015";
7753
7754 # not a text file
7755 } else {
7756
7757 # close the file
7758 close($fh);
7759
7760 # return
7761 return('unknown file type');
7762
7763 }
7764
7765 # save file type
7766 $self->[0]{'file_type'} = 'TEXT';
7767
7768 # read ASCII file
7769 $result = _readChartASCII($self, $fh, $hash);
7770
7771 }
7772  
7773 # close the file
7774 close($fh);
7775  
7776 # return
7777 return($result);
7778  
7779 }
7780  
7781 # read chart from ISO 28178 ASCII data file
7782 # parameters: (object_reference, file_handle, hash)
7783 # returns: (result)
7784 sub _readChartASCII {
7785  
7786 # get parameters
7787 my ($self, $fh, $hash) = @_;
7788  
7789 # local variables
7790 my ($state, $iflag, $eflag, $index);
7791 my (@fields, $illum, $append);
7792  
7793 # localize input record separator
7794 local $/ = $self->[0]{'read_rs'};
7795  
7796 # localize loop variable
7797 local $_;
7798  
7799 # initialize variables
7800 $self->[1] = [[]];
7801 $illum = [[]];
7802 $index = 1;
7803 $state = 0;
7804 $iflag = 0;
7805  
7806 # read the file, line by line
7807 while (<$fh>) {
7808
7809 # add appended text, as is
7810 $append .= $_ if ($state == 4);
7811
7812 # remove leading spaces/tabs and trailing whitespace
7813 s/^[ \t]*(.*?)[\s,]*$/$1/;
7814
7815 # if normal comment line (all comments are removed)
7816 if (s/#[\s]*(.*)// && $state == 0) {
7817
7818 # if remaining line blank
7819 if (length() == 0) {
7820
7821 # add comment to header array
7822 push(@{$self->[3]}, ['#', $1]);
7823
7824 } else {
7825
7826 # restore comment to header line
7827 # preserves time in ProfileMaker 'CREATED' lines
7828 $_ .= "# $1";
7829
7830 }
7831
7832 }
7833
7834 # skip blank lines
7835 next if (length() == 0);
7836
7837 # begin data format
7838 if (m/^BEGIN_DATA_FORMAT$/) {
7839
7840 # set state
7841 $state = 1;
7842
7843 # end data format
7844 } elsif (m/^END_DATA_FORMAT$/) {
7845
7846 # set state
7847 $state = 2;
7848
7849 # begin data
7850 } elsif (m/^BEGIN_DATA$/) {
7851
7852 # set state
7853 $state = 3;
7854
7855 # end data
7856 } elsif (m/^END_DATA$/) {
7857
7858 # set state
7859 $state = 4;
7860
7861 # begin ProfileMaker illuminant section
7862 } elsif (m/^BEGIN_DATA_EMISSION$/) {
7863
7864 # set illuminant flag
7865 $iflag = 1;
7866
7867 # reset index
7868 $index = 1;
7869
7870 # end ProfileMaker illuminant section
7871 } elsif (m/^END_DATA_EMISSION$/) {
7872
7873 # clear illuminant flag
7874 $iflag = 0;
7875
7876 # reset appended data
7877 $append = '';
7878
7879 # anything else
7880 } else {
7881
7882 # format
7883 if ($iflag == 0 && $state == 1) {
7884
7885 # change 'SampleID' to 'SAMPLE_ID'
7886 # non-standard notation used by ProfileMaker
7887 s/SampleID/SAMPLE_ID/;
7888
7889 # parse and save format keys
7890 push(@{$self->[1][0]}, split(/[\s,]+/));
7891
7892 # data
7893 } elsif ($iflag == 0 && $state == 3) {
7894
7895 # if Euro flag not defined
7896 if (! defined($eflag)) {
7897
7898 # split data
7899 @fields = split(/[\s,]+/);
7900
7901 # set flag for Euro decimal notation (e.g. 6,3 becomes 6.3)
7902 $eflag = m/,/ && @fields > (@{$self->[1][0]} || 0);
7903
7904 }
7905
7906 # fix Euro decimal notation (e.g. 6,3 becomes 6.3)
7907 s/(\d),(\d)/$1.$2/g if ($eflag);
7908
7909 # parse and save data
7910 $self->[1][$index++] = [split(/[\s,]+/)];
7911
7912 # illuminant format
7913 # may be different from data format
7914 } elsif ($iflag == 1 && $state == 1) {
7915
7916 # change 'SampleID' to 'SAMPLE_ID'
7917 # non-standard notation used by ProfileMaker
7918 s/SampleID/SAMPLE_ID/;
7919
7920 # parse and save illuminant format keys
7921 push(@{$illum->[0]}, split(/[\s,]+/));
7922
7923 # illuminant data
7924 } elsif ($iflag == 1 && $state == 3) {
7925
7926 # fix Euro decimal notation (e.g. 6,3 becomes 6.3)
7927 s/(\d),(\d)/$1.$2/g if ($eflag);
7928
7929 # parse and save illuminant data
7930 $illum->[$index++] = [split(/[\s,]+/)];
7931
7932 # header lines
7933 } elsif ($iflag == 0 && ($state == 0 || $state == 2)) {
7934
7935 # match keyword/value
7936 m/^([^\s,]*)[\s,]*(.*?)$/;
7937
7938 # add to header array
7939 push(@{$self->[3]}, [$1, $2]) if (length($1));
7940
7941 }
7942
7943 }
7944
7945 }
7946  
7947 # save illuminant data, if any
7948 $self->[0]{'illuminant'} = $illum if defined($illum->[1]);
7949  
7950 # save appended data, if any
7951 $self->[0]{'append'} = $append if (defined($append));
7952  
7953 # apply rotation/flip (special keywords)
7954 _rotateChartASCII($self);
7955  
7956 # check spectral data
7957 _scale_check($self);
7958  
7959 # return success flag
7960 return($state == 4 ? () : "ASCII read failed with state $state");
7961  
7962 }
7963  
7964 # apply rotation/flip to ASCII chart data
7965 # if LGOROWLENGTH and (DPLGROTATE or DPLGFLIP) keywords are present
7966 # parameter: (object_reference)
7967 sub _rotateChartASCII {
7968  
7969 # get object reference
7970 my $self = shift();
7971  
7972 # local variables
7973 my ($rot, $flip, $mat, $rows);
7974  
7975 # get the rotation and flip values
7976 $rot = keyword($self, 'DPLGROTATE');
7977 $flip = keyword($self, 'DPLGFLIP');
7978  
7979 # if LGOROWLENGTH and (DPLGROTATE or DPLGFLIP) keywords
7980 if (keyword($self, 'LGOROWLENGTH') && ($rot || $flip)) {
7981
7982 # get selection matrix
7983 $mat = select_matrix($self)->rotate($rot)->flip($flip);
7984
7985 # flatten matrix
7986 $rows = ICC::Shared::flatten($mat);
7987
7988 # prepend DATA_FORMAT row index (0)
7989 unshift(@{$rows}, 0);
7990
7991 # rearrange chart data
7992 $self->[1] = [@{$self->[1]}[@{$rows}]];
7993
7994 # update LGOROWLENGTH
7995 keyword($self, 'LGOROWLENGTH', scalar(@{$mat->[0]}));
7996
7997 }
7998
7999 }
8000  
8001 # read chart from Adobe Swatch Exchange (.ase) file
8002 # optional hash key: 'colorspace'
8003 # 'colorspace' values: 'CMYK', 'LAB ', 'RGB ' or 'Gray'
8004 # 'Gray' swatches are mapped to CMYK values
8005 # parameters: (object_reference, file_handle, hash)
8006 # returns: (result)
8007 sub _readChartASE {
8008  
8009 # get parameters
8010 my ($self, $fh, $hash) = @_;
8011  
8012 # local variables
8013 my ($cs, $le, $buf, @header, $sn);
8014 my ($mark, $type, $blen, $slen);
8015 my ($name, $space, $cmyk, $rgb, $Lab, $dev);
8016  
8017 # set colorspace selector
8018 $cs = $hash->{'colorspace'} if defined($hash->{'colorspace'});
8019  
8020 # get little-endian flag
8021 $le = ($Config{'byteorder'} =~ m/1234/);
8022  
8023 # read header (file signature, version, number of blocks)
8024 read($fh, $buf, 12);
8025  
8026 # unpack buffer
8027 @header = unpack('A4nnN', $buf);
8028  
8029 # verify file signature
8030 ($header[0] eq 'ASEF') || return('not a valid ASE file');
8031  
8032 # add SAMPLE_NAME field
8033 $sn = add_fmt($self, 'SAMPLE_NAME');
8034  
8035 # set file pointer
8036 $mark = 12;
8037  
8038 # for each block
8039 for my $s (1 .. $header[3]) {
8040
8041 # read block type, block length, and string length
8042 read($fh, $buf, 8);
8043
8044 # unpack buffer
8045 ($type, $blen, $slen) = unpack('nNn', $buf);
8046
8047 # if color entry type
8048 if ($type == 1) {
8049
8050 # read color name
8051 read($fh, $buf, 2 * $slen);
8052
8053 # decode color name
8054 $name = decode('UTF-16BE', $buf);
8055
8056 # trim trailing '0'
8057 $name =~ s/\x00$//;
8058
8059 # change spaces to underscores
8060 $name =~ s/\s/_/g;
8061
8062 # read color space
8063 read($fh, $space, 4);
8064
8065 # if colorspace is CMYK
8066 if (($space eq 'CMYK' && (! defined($cs)) || $cs eq 'CMYK')) {
8067
8068 # store color as SAMPLE_NAME
8069 $self->[1][$s][$sn->[0]] = $name;
8070
8071 # init device array
8072 $dev = [];
8073
8074 # for each CMYK value
8075 for my $i (0 .. 3) {
8076
8077 # read 32-bit floating point value
8078 read($fh, $buf, 4);
8079
8080 # reverse bytes if long-endian system
8081 $buf = reverse($buf) if ($le);
8082
8083 # unpack buffer
8084 $dev->[$i] = unpack('f', $buf);
8085
8086 }
8087
8088 # if CMYK slice undefined
8089 if (! defined($cmyk)) {
8090
8091 # add CMYK slice
8092 $cmyk = add_fmt($self, qw(CMYK_C CMYK_M CMYK_Y CMYK_K));
8093
8094 }
8095
8096 # store CMYK values
8097 @{$self->[1][$s]}[@{$cmyk}] = map {100 * $_} @{$dev};
8098
8099 # if colorspace is RGB
8100 } elsif (($space eq 'RGB ' && (! defined($cs)) || $cs eq 'RGB ')) {
8101
8102 # store color as SAMPLE_NAME
8103 $self->[1][$s][$sn->[0]] = $name;
8104
8105 # init device array
8106 $dev = [];
8107
8108 # for each RGB value
8109 for my $i (0 .. 2) {
8110
8111 # read 32-bit floating point value
8112 read($fh, $buf, 4);
8113
8114 # reverse bytes if long-endian system
8115 $buf = reverse($buf) if ($le);
8116
8117 # unpack buffer
8118 $dev->[$i] = unpack('f', $buf);
8119
8120 }
8121
8122 # if RGB slice undefined
8123 if (! defined($rgb)) {
8124
8125 # add RGB slice
8126 $rgb = add_fmt($self, qw(RGB_R RGB_G RGB_B));
8127
8128 }
8129
8130 # store RGB values
8131 @{$self->[1][$s]}[@{$rgb}] = map {255 * $_} @{$dev};
8132
8133 # if colorspace is L*a*b*
8134 } elsif (($space eq 'LAB ' && (! defined($cs)) || $cs eq 'LAB ')) {
8135
8136 # store color as SAMPLE_NAME
8137 $self->[1][$s][$sn->[0]] = $name;
8138
8139 # init device array
8140 $dev = [];
8141
8142 # for each L*a*b* value
8143 for my $i (0 .. 2) {
8144
8145 # read 32-bit floating point value
8146 read($fh, $buf, 4);
8147
8148 # reverse bytes if long-endian system
8149 $buf = reverse($buf) if ($le);
8150
8151 # unpack buffer
8152 $dev->[$i] = unpack('f', $buf);
8153
8154 }
8155
8156 # if L*a*b* slice undefined
8157 if (! defined($Lab)) {
8158
8159 # add L*a*b* fields
8160 $Lab = add_fmt($self, qw(LAB_L LAB_A LAB_B));
8161
8162 }
8163
8164 # store L*a*b* values
8165 @{$self->[1][$s]}[@{$Lab}] = (100 * $dev->[0], $dev->[1], $dev->[2]);
8166
8167 # if colorspace is Grayscale
8168 } elsif (($space eq 'Gray' && (! defined($cs)) || $cs eq 'Gray')) {
8169
8170 # store color as SAMPLE_NAME
8171 $self->[1][$s][$sn->[0]] = $name;
8172
8173 # read 32-bit floating point value
8174 read($fh, $buf, 4);
8175
8176 # reverse bytes if long-endian system
8177 $buf = reverse($buf) if ($le);
8178
8179 # unpack buffer
8180 $dev = [unpack('f', $buf)];
8181
8182 # if CMYK slice is undefined
8183 if (! defined($cmyk)) {
8184
8185 # add CMYK slice
8186 $cmyk = add_fmt($self, qw(CMYK_C CMYK_M CMYK_Y CMYK_K));
8187
8188 }
8189
8190 # store CMYK values
8191 @{$self->[1][$s]}[@{$cmyk}] = (0, 0, 0, 100 * (1 - $dev->[0]));
8192
8193 }
8194
8195 }
8196
8197 # set file pointer to next block
8198 $mark += $blen + 6;
8199
8200 # seek next block
8201 seek($fh, $mark, 0);
8202
8203 }
8204  
8205 # return
8206 return();
8207  
8208 }
8209  
8210 # read chart from ICC profile
8211 # some profiles have tags containing chart data
8212 # parameters: (object_reference, file_handle, hash)
8213 # returns: (result)
8214 sub _readChartICC {
8215  
8216 # get parameters
8217 my ($self, $fh, $hash) = @_;
8218  
8219 # local variables
8220 my (@header, @tagtab, %offset, %tags, $type, $class);
8221 my ($temp, $data, $text, $result);
8222  
8223 # load ICC::Profile modules, if not already included
8224 require ICC::Profile;
8225  
8226 # read the profile header
8227 ICC::Profile::_readICCheader($fh, \@header) || return('failed reading ICC profile header');
8228  
8229 # read the profile tag table
8230 ICC::Profile::_readICCtagtable($fh, \@tagtab) || return('failed reading ICC profile tag table');
8231  
8232 # for each tag
8233 for my $tag (@tagtab) {
8234
8235 # if tag contains measurement data
8236 if ($tag->[0] =~ m/^(?:CxF |DevD|CIED|DEVD|targ)$/) {
8237
8238 # if a duplicate tag
8239 if (exists($offset{$tag->[1]})) {
8240
8241 # use original tag
8242 $tags{$tag->[0]} = $offset{$tag->[1]};
8243
8244 } else {
8245
8246 # seek to start of tag
8247 seek($fh, $tag->[1], 0);
8248
8249 # read tag type signature
8250 read($fh, $type, 4);
8251
8252 # convert non-word characters to underscores
8253 $type =~ s|\W|_|g;
8254
8255 # form class specifier
8256 $class = 'ICC::Profile::' . $type;
8257
8258 # if 'class->new_fh' method exists
8259 if ($class->can('new_fh')) {
8260
8261 # create specific tag object
8262 $tags{$tag->[0]} = $class->new_fh($self, $fh, $tag);
8263
8264 } else {
8265
8266 # create generic tag object
8267 $tags{$tag->[0]} = ICC::Profile::Generic->new_fh($self, $fh, $tag);
8268
8269 }
8270
8271 # save tag in hash
8272 $offset{$tag->[1]} = $tags{$tag->[0]};
8273
8274 }
8275
8276 }
8277
8278 }
8279
8280 # if creator is i1Profiler and 'CxF ' tag exists
8281 if ($header[23] eq 'XRCM' && exists($tags{'CxF '})) {
8282
8283 # close file handle
8284 close($fh);
8285
8286 # open file handle to CxF3 string
8287 open($fh, '<', \$tags{'CxF '}->text());
8288
8289 # make chart from CxF3 string
8290 return(_readChartCxF3($self, $fh, $hash));
8291
8292 # if creator is ProfileMaker and 'DevD' / 'CIED' tags exist
8293 } elsif ($header[23] eq 'LOGO' && exists($tags{'DevD'}) && exists($tags{'CIED'})) {
8294
8295 # close file handle
8296 close($fh);
8297
8298 # open file handle to 'DevD' text string
8299 open($fh, '<', \$tags{'DevD'}->text());
8300
8301 # read chart from text
8302 ($result = _readChartASCII($self, $fh, $hash)) && return("failed reading ICC profile DEVD tag, $result");
8303
8304 # close file handle
8305 close($fh);
8306
8307 # make temporary chart object
8308 $temp = ICC::Support::Chart->new();
8309
8310 # open file handle to 'CIED' text string
8311 open($fh, '<', \$tags{'CIED'}->text());
8312
8313 # read chart from text
8314 ($result = _readChartASCII($temp, $fh, $hash)) && return("failed reading ICC profile CIED tag, $result");
8315
8316 # get data slice (all rows, spectral, XYZ and L*a*b* columns)
8317 $data = slice($temp, [0 .. $#{$temp->[1]}], [grep {$temp->[1][0][$_] =~ m/^(nm\d{3}|XYZ_(X|Y|Z)|LAB_(L|A|B))$/} (0 .. $#{$temp->[1][0]})]);
8318
8319 # append to chart
8320 add_cols($self, $data);
8321
8322 # for each keyword
8323 for my $key (@{$temp->[3]}) {
8324
8325 # if keyword not in main chart
8326 if (0 == grep {$key->[0] eq $_->[0]} @{$self->[3]}) {
8327
8328 # append keyword/value
8329 push(@{$self->[3]}, $key);
8330
8331 }
8332
8333 }
8334
8335 # return
8336 return();
8337
8338 # if creator is Monaco and 'DEVD' tag exists (some old profiles are identified by preferred CMM)
8339 } elsif (($header[23] eq 'MONS' || $header[1] eq 'mnco') && exists($tags{'DEVD'})) {
8340
8341 # read chart from Monaco 'DEVD' tag
8342 return(_readMonacoDEVD($self, $tags{'DEVD'}->data(), \@header));
8343
8344 # if 'targ' tag exists
8345 } elsif (exists($tags{'targ'})) {
8346
8347 # get 'targ' tag text string
8348 $text = $tags{'targ'}->text();
8349
8350 # if reference to ICC Characterization Data Registry
8351 if ($text =~ m/^ICCHDAT (.*)$/) {
8352
8353 # return
8354 return("profile derived from $1 characterization data, available at www.color.org");
8355
8356 } else {
8357
8358 # close file handle
8359 close($fh);
8360
8361 # open file handle to text string
8362 open($fh, '<', \$text);
8363
8364 # read chart from text
8365 return(_readChartASCII($self, $fh, $hash));
8366
8367 }
8368
8369 }
8370  
8371 # return
8372 return('failed reading ICC profile characterization data');
8373  
8374 }
8375  
8376 # read chart from Monaco 'DEVD' tag
8377 # parameters: (object_reference, tag_data, profile_header)
8378 # returns: (result)
8379 sub _readMonacoDEVD {
8380  
8381 # get parameters
8382 my ($self, $data, $header) = @_;
8383  
8384 # local variables
8385 my ($big, %cshash, $cs, $nc, $fix, $ix, $tag, $tac, $limit, $mult, $dev, $lab);
8386 my ($ns, $sec, @devfix, @nd, $nt, @devstep, @dev, @cmy, @sum, @temp, $m, @dat);
8387  
8388 # get big-endian flag (true if our system is big-endian)
8389 $big = ($Config{'byteorder'} =~ m/4321/);
8390  
8391 # colorspace hash (colorspace => number_channels)
8392 %cshash = ('RGB ' => 3, 'CMYK' => 4, '5CLR' => 5, '6CLR' => 6, '7CLR' => 7, '8CLR' => 8);
8393  
8394 # initialize fixed value array
8395 @devfix = ();
8396  
8397 # get colorspace from profile header
8398 $cs = $header->[4];
8399  
8400 # lookup number of channels
8401 $nc = $cshash{$cs};
8402  
8403 # set number of fixed channels
8404 $fix = $nc - 3;
8405  
8406 # set index to start of first tag
8407 $ix = 28;
8408  
8409 # set tag value
8410 $tag = pack('N', 0x002D);
8411  
8412 # find TAC tag
8413 do {$ix = index($data, $tag, $ix)} while ($ix >= 0 && $ix % 4 && $ix++);
8414  
8415 # verify tag found
8416 ($ix >= 0) || return('failed reading TAC from Monaco DEVD tag');
8417  
8418 # get TAC value
8419 $tac = 100 * unpack('d', $big ? substr($data, $ix + 4, 8) : reverse(substr($data, $ix + 4, 8)));
8420  
8421 # if RGB colorspace
8422 if ($cs eq 'RGB ') {
8423
8424 # add device fields
8425 $dev = add_fmt($self, qw(RGB_R RGB_G RGB_B));
8426
8427 # set device multiplier
8428 $mult = 255;
8429
8430 # if CMYK colorspace
8431 } elsif ($cs eq 'CMYK') {
8432
8433 # add device fields
8434 $dev = add_fmt($self, qw(CMYK_C CMYK_M CMYK_Y CMYK_K));
8435
8436 # set device multiplier
8437 $mult = 100;
8438
8439 } else {
8440
8441 # add device fields
8442 $dev = add_fmt($self, map {"$cs\_$_"} (1 .. $nc));
8443
8444 # set device multiplier
8445 $mult = 100;
8446
8447 }
8448  
8449 # add L*a*b* fields
8450 $lab = add_fmt($self, qw(LAB_L LAB_A LAB_B));
8451  
8452 # advance index
8453 $ix += 12;
8454  
8455 # set tag value
8456 $tag = pack('N', 0x0027);
8457  
8458 # find data group tag
8459 do {$ix = index($data, $tag, $ix)} while ($ix >= 0 && $ix % 4 && $ix++);
8460  
8461 # verify tag found
8462 ($ix >= 0) || return('failed reading data group from Monaco DEVD tag');
8463  
8464 # get number data sections in group
8465 $ns = unpack('N', substr($data, $ix + 4, 4));
8466  
8467 # advance index
8468 $ix += 8;
8469  
8470 # for data each section
8471 for my $s (0 .. $ns - 1) {
8472
8473 # verify tag 0x0028
8474 (substr($data, $ix, 4) eq pack('N', 0x0028)) || return(0);
8475
8476 # get section index
8477 $sec = unpack('N', substr($data, $ix + 4, 4));
8478
8479 # verify section index is correct
8480 ($sec == $s) || return('failed reading section index from Monaco DEVD tag');
8481
8482 # advance index
8483 $ix += 8;
8484
8485 # verify tag 0x002A (fixed device values)
8486 (substr($data, $ix, 4) eq pack('N', 0x002A)) || return('failed reading fixed device values from Monaco DEVD tag');
8487
8488 # if fixed device values (none for RGB)
8489 if ($fix) {
8490
8491 # get fixed device values (black plus any extra colors, e.g. orange or green)
8492 @devfix = unpack("d$fix", $big ? substr($data, $ix + 4, 8 * $fix) : reverse(substr($data, $ix + 4, 8 * $fix)));
8493
8494 # reverse array if little-endian
8495 @devfix = reverse(@devfix) if (! $big);
8496
8497 # apply multiplier
8498 @devfix = map {$_ * $mult} @devfix;
8499
8500 }
8501
8502 # advance index
8503 $ix += 8 * $fix + 4;
8504
8505 # verify tag 0x002B (step counts by color)
8506 (substr($data, $ix, 4) eq pack('N', 0x002B)) || return('failed reading step counts from Monaco DEVD tag');
8507
8508 # get device step counts
8509 @nd = unpack('N3', substr($data, $ix + 4, 12));
8510
8511 # get total number of steps
8512 $nt = $nd[0] + $nd[1] + $nd[2];
8513
8514 # advance index
8515 $ix += 16;
8516
8517 # verify tag 0x002C (step values by color)
8518 (substr($data, $ix, 4) eq pack('N', 0x002C)) || return('failed reading step values from Monaco DEVD tag');
8519
8520 # get step values
8521 @devstep = unpack("d$nt", $big ? substr($data, $ix + 4, 8 * $nt) : reverse(substr($data, $ix + 4, 8 * $nt)));
8522
8523 # reverse array if little-endian
8524 @devstep = reverse(@devstep) if (! $big);
8525
8526 # apply multiplier
8527 @devstep = map {$_ * $mult} @devstep;
8528
8529 # advance index
8530 $ix += 8 * $nt + 4;
8531
8532 # initialize arrays
8533 @dev = ();
8534 @sum = ();
8535 @temp = ();
8536
8537 # if RGB colorspace
8538 if ($cs eq 'RGB ') {
8539
8540 # for each blue step
8541 for my $i (0 .. $nd[2] - 1) {
8542
8543 # for each green step
8544 for my $j (0 .. $nd[1] - 1) {
8545
8546 # for each red step
8547 for my $k (0 .. $nd[0] - 1) {
8548
8549 # save RGB values
8550 push(@dev, $devstep[$k], $devstep[$j + $nd[0]], $devstep[$i + $nd[0] + $nd[1]]);
8551
8552 }
8553
8554 }
8555
8556 }
8557
8558 # if CMYK or NCLR colorspace
8559 } else {
8560
8561 # for each yellow step
8562 for my $i (0 .. $nd[2] - 1) {
8563
8564 # for each cyan step
8565 for my $j (0 .. $nd[0] - 1) {
8566
8567 # for each magenta step
8568 for my $k (0 .. $nd[1] - 1) {
8569
8570 # get CMY values
8571 @cmy = ($devstep[$j], $devstep[$k + $nd[0]], $devstep[$i + $nd[0] + $nd[1]]);
8572
8573 # save CMY values
8574 push(@temp, [@cmy]);
8575
8576 # save total ink value
8577 push(@sum, List::Util::sum(@cmy, @devfix));
8578
8579 }
8580
8581 }
8582
8583 }
8584
8585 # initialize actual ink limit
8586 $limit = $nc * 100;
8587
8588 # find actual ink limit (smallest value greater than TAC)
8589 for (@sum) {$limit = $_ if ($_ > $tac && $_ < $limit)};
8590
8591 # for each sample
8592 for my $i (0 .. $#sum) {
8593
8594 # get cmy values
8595 @cmy = @{$temp[$i]};
8596
8597 # if sample within ink limit, or a corner point
8598 if ($sum[$i] <= $limit || ((0 < grep {$_ == 0} @cmy) && (0 < grep {$_ == 100} @cmy))) {
8599
8600 # copy cmy values
8601 push(@dev, @cmy);
8602
8603 }
8604
8605 }
8606
8607 }
8608
8609 # verify tag 0x0032 (L*a*b* sample data)
8610 (substr($data, $ix, 4) eq pack('N', 0x0032)) || return('failed reading L*a*b* data from Monaco DEVD tag');
8611
8612 # get number of values
8613 $m = unpack('N', substr($data, $ix + 4, 4)) * 3;
8614
8615 # get L*a*b* color data
8616 @dat = unpack("d$m", $big ? substr($data, $ix + 8, 8 * $m) : reverse(substr($data, $ix + 8, 8 * $m)));
8617
8618 # reverse array if little-endian
8619 @dat = reverse(@dat) if (! $big);
8620
8621 # advance index
8622 $ix += 8 * $m + 8;
8623
8624 # verify @dev and @dat are same size
8625 (scalar(@dev) == scalar(@dat)) || return('failed comparing data counts of Monaco DEVD tag');
8626
8627 # for each sample (3 values per sample)
8628 for my $i (0 .. ($m/3 - 1)) {
8629
8630 # add sample data to object
8631 push (@{$self->[1]}, [@dev[($i * 3) .. ($i * 3 + 2)], @devfix, @dat[($i * 3) .. ($i * 3 + 2)]]);
8632
8633 }
8634
8635 # verify tag 0x0029 (end of section)
8636 (substr($data, $ix, 4) eq pack('N', 0x0029)) || return('failed reading section end from Monaco DEVD tag');
8637
8638 # advance index
8639 $ix += 4;
8640
8641 }
8642  
8643 # verify tag 0x0030 (end of data)
8644 (substr($data, $ix, 4) eq pack('N', 0x0030)) || return('failed reading data end from Monaco DEVD tag');
8645  
8646 # add 'CREATED' keyword/value from header date/time
8647 push(@{$self->[3]}, ['CREATED', sprintf('%.4d-%.2d-%.2dT%.2d:%.2d:%.2dZ', @{$header}[6 .. 11])]);
8648  
8649 # return
8650 return();
8651  
8652 }
8653  
8654 # read chart from SpectraShop (.ss3) file
8655 # parameters: (object_reference, file_handle, hash)
8656 sub _readChartSS3 {
8657  
8658 # get parameters
8659 my ($self, $fh, $hash) = @_;
8660  
8661 # local variables
8662 my (%fmt, $buf, @data, $notes);
8663 my ($meta, $measure, %tally, @keys, $value, $nm);
8664  
8665 # metadata format array (v32)
8666 $fmt{'32'} = [
8667 [qw(Identifier_1 SAMPLE_NAME P)],
8668 [qw(Identifier_2 SAMPLE_ID2 P)],
8669 [qw(Identifier_3 SAMPLE_ID3 P)],
8670 [qw(Material MATERIAL P)],
8671 [qw(Manufacturer MANUFACTURER P)],
8672 [qw(Model MODEL P)],
8673 [qw(Serial_Number SERIAL_NUMBER P)],
8674 [qw(Production_Date PROD_DATE P)],
8675 [qw(Surface SURFACE P)],
8676 [qw(Originator ORIGINATOR P)],
8677 [qw(Creation_Date CREATED P)],
8678 [qw(Comments NOTE P)],
8679 [qw(Instrument INSTRUMENTATION P)],
8680 [qw(Spectrum_Type SPECTRUM_TYPE n), [qw(Emissive-light Emissive-monitor Observer Reflective Transmissive)]],
8681 [qw(Filter MEASUREMENT_FILTER P)],
8682 [qw(Geometry MEASUREMENT_GEOMETRY P)],
8683 [qw(Aperture MEASUREMENT_APERTURE P)],
8684 [qw(Data_Reference DATA_REFERENCE P)],
8685 [qw(Illuminant MEASUREMENT_SOURCE P)],
8686 [qw(Backing SAMPLE_BACKING P)],
8687 [qw(Measurements NSAMPLES n)],
8688 [qw(Notes ACQUIRE_NOTE P)],
8689 ];
8690  
8691 # metadata format array (v50)
8692 $fmt{'50'} = [
8693 [qw(Identifier_1 SAMPLE_NAME P)],
8694 [qw(Identifier_2 SAMPLE_ID2 P)],
8695 [qw(Identifier_3 SAMPLE_ID3 P)],
8696 [qw(Material MATERIAL P)],
8697 [qw(Manufacturer MANUFACTURER P)],
8698 [qw(Model MODEL P)],
8699 [qw(Serial_Number SERIAL_NUMBER P)],
8700 [qw(Production_Date PROD_DATE P)],
8701 [qw(Surface SURFACE P)],
8702 [qw(Originator ORIGINATOR P)],
8703 [qw(Creation_Date CREATED P)],
8704 [qw(Comments NOTE P)],
8705 [qw(Instrument INSTRUMENTATION P)],
8706 [qw(Serial_Number INSTRUMENT_SERIAL_NUMBER P)],
8707 [qw(Spectrum_Type SPECTRUM_TYPE n), [qw(Emissive-light Emissive-monitor Observer Reflective Transmissive)]],
8708 [qw(Filter MEASUREMENT_FILTER P)],
8709 [qw(Geometry MEASUREMENT_GEOMETRY P)],
8710 [qw(Aperture MEASUREMENT_APERTURE P)],
8711 [qw(Data_Reference DATA_REFERENCE P)],
8712 [qw(Illuminant MEASUREMENT_SOURCE P)],
8713 [qw(Backing SAMPLE_BACKING P)],
8714 [qw(Measurements NSAMPLES n)],
8715 [qw(Notes ACQUIRE_NOTE P)],
8716 ];
8717  
8718 # read version, samples, Collection Notes length
8719 read($fh, $buf, 7);
8720  
8721 # unpack
8722 @data = unpack('nx2nC', $buf);
8723  
8724 # read Collection Notes string
8725 read($fh, $notes, $data[2]);
8726  
8727 # for each sample
8728 for my $i (0 .. ($data[1] - 1)) {
8729
8730 # for each metadata field
8731 for my $j (0 .. $#{$fmt{$data[0]}}) {
8732
8733 # if a Pascal string
8734 if ($fmt{$data[0]}[$j][2] eq 'P') {
8735
8736 # read string length
8737 read($fh, $buf, 1);
8738
8739 # read string
8740 read($fh, $meta->[$i][$j], unpack('C', $buf));
8741
8742 # if an unsigned short integer
8743 } elsif ($fmt{$data[0]}[$j][2] eq 'n') {
8744
8745 # read short integer
8746 read($fh, $buf, 2);
8747
8748 # unpack
8749 $meta->[$i][$j] = unpack('n', $buf);
8750
8751 }
8752
8753 }
8754
8755 # read wavelength parameters (start, end, increment, count)
8756 read($fh, $buf, 8);
8757
8758 # unpack (unsigned short integer)
8759 $measure->[$i][0] = [unpack('n4', $buf)];
8760
8761 # for each wavelength
8762 for my $j (1 .. $measure->[$i][0][3]) {
8763
8764 # read measurements (avg, low, high, std_dev)
8765 read($fh, $buf, 16);
8766
8767 # unpack (32-bit float, big endian)
8768 $measure->[$i][$j] = [unpack('(f4)>', $buf)];
8769
8770 }
8771
8772 }
8773  
8774 # add Collection Notes to header line array, if not null string
8775 push(@{$self->[3]}, ['FILE_DESCRIPTOR', "\"$notes\""]) if (length($notes));
8776  
8777 # for each metadata field
8778 for my $j (0 .. $#{$meta->[0]}) {
8779
8780 # init hash
8781 %tally = ();
8782
8783 # for each sample
8784 for my $i (0 .. $#{$meta}) {
8785
8786 # increment hash value
8787 $tally{$meta->[$i][$j]}++;
8788
8789 }
8790
8791 # get hash keys
8792 @keys = keys(%tally);
8793
8794 # if one hash key
8795 if (@keys == 1) {
8796
8797 # if not the null string
8798 if (length($keys[0])) {
8799
8800 # if value is string
8801 if ($fmt{$data[0]}[$j][2] eq 'P') {
8802
8803 # wrap in quotes
8804 $value = "\"$keys[0]\"";
8805
8806 } else {
8807
8808 # if value is an enumeration
8809 if (defined($fmt{$data[0]}[$j][3])) {
8810
8811 # look up enumerated value and wrap in quotes
8812 $value = "\"$fmt{$data[0]}[$j][3][$keys[0]]\"";
8813
8814 } else {
8815
8816 # use value as-is
8817 $value = $keys[0];
8818
8819 }
8820
8821 }
8822
8823 # add KEYWORD/VALUE to header line array
8824 push(@{$self->[3]}, [$fmt{$data[0]}[$j][1], $value]);
8825
8826 }
8827
8828 } else {
8829
8830 # add keyword to DATA_FORMAT array
8831 push(@{$self->[1][0]}, $fmt{$data[0]}[$j][1]);
8832
8833 # for each sample
8834 for my $i (0 .. $#{$meta}) {
8835
8836 # if value is an enumeration
8837 if (defined($fmt{$data[0]}[$j][3])) {
8838
8839 # look up enumerated value
8840 $value = $fmt{$data[0]}[$j][3][$meta->[$i][$j]];
8841
8842 } else {
8843
8844 # use value as-is
8845 $value = $meta->[$i][$j];
8846
8847 }
8848
8849 # add value to DATA array
8850 push(@{$self->[1][$i + 1]}, $meta->[$i][$j]);
8851
8852 }
8853
8854 }
8855
8856 }
8857  
8858 # for each wavelength parameter (start, end, increment, count)
8859 for my $j (0 .. 3) {
8860
8861 # init hash
8862 %tally = ();
8863
8864 # for each sample
8865 for my $i (0 .. $#{$measure}) {
8866
8867 # increment hash value
8868 $tally{$measure->[$i][0][$j]}++;
8869
8870 }
8871
8872 # get hash keys
8873 @keys = keys(%tally);
8874
8875 # verify all samples have same wavelength parameter value
8876 (@keys == 1) || return('samples have varied spectral range');
8877
8878 }
8879  
8880 # for each wavelength
8881 for my $j (0 .. ($#{$measure->[0]} - 1)) {
8882
8883 # compute wavelength from start and increment values
8884 $nm = $measure->[0][0][0] + $j * $measure->[0][0][2];
8885
8886 # add keyword to DATA_FORMAT array
8887 push(@{$self->[1][0]}, "nm$nm");
8888
8889 # for each sample
8890 for my $i (0 .. $#{$measure}) {
8891
8892 # add average measurement to DATA array
8893 push(@{$self->[1][$i + 1]}, $measure->[$i][$j + 1][0]);
8894
8895 }
8896
8897 }
8898  
8899 # return
8900 return();
8901  
8902 }
8903  
8904 # read data from TIFF file
8905 # RGB, CMYK, and CIE L*a*b* color spaces supported
8906 # 8-bit, 16-bit or 32-bit, Intel or Motorola byte order supported
8907 # alpha and spot channels in RGB and CMYK files supported
8908 # optional hash keys: 'rows', 'columns', 'crop', 'ratio', 'aperture', 'udf', 'format'
8909 # default 'rows' and 'columns' are taken from image size, default 'ratio' is 0.5
8910 # 'crop' is an array containing the left, right, upper and lower crop values in pixels
8911 # 'ratio' is a value between 0 and 1, sample is a single pixel when 'ratio' is 0
8912 # 'aperture' is in millimeters, and take precedence over 'ratio'
8913 # 'udf' is a code reference to a pixel processing function
8914 # 'format' is an array reference containing the format fields
8915 # parameters: (object_reference, file_handle, hash)
8916 # returns: (result)
8917 sub _readChartTIFF {
8918  
8919 # get parameters
8920 my ($self, $fh, $hash) = @_;
8921  
8922 # local variables
8923 my ($buf, $short, $long, $fp, @header, $tags);
8924 my ($cols, $rows, $bits, $pi, $samples);
8925 my ($context, $fmt, $upf, $udf, $dev, $div, $dab);
8926 my ($trows, $tcols, $crop, $roff, $coff);
8927 my ($res, $size, $frac, $ratio, $rxo, $cxo, $pixels, $width);
8928 my ($lower, $upper, $left, $right, $band, $pval, @data, @pix);
8929  
8930 # read the header
8931 read($fh, $buf, 8);
8932  
8933 # if big-endian (Motorola)
8934 if (substr($buf, 0, 2) eq 'MM') {
8935
8936 # set 'unpack' formats
8937 $short = 'n';
8938 $long = 'N';
8939 $fp = 'f>'; # might not be IEEE FP on some platforms
8940
8941 # if little-endian (Intel)
8942 } elsif (substr($buf, 0, 2) eq 'II'){
8943
8944 # set 'unpack' formats
8945 $short = 'v';
8946 $long = 'V';
8947 $fp = 'f<'; # might not be IEEE FP on some platforms
8948
8949 } else {
8950
8951 # error
8952 return('TIFF byte order incorrect');
8953
8954 }
8955  
8956 # unpack the header
8957 @header = unpack("A2 $short $long", $buf);
8958  
8959 # verify file signature
8960 ($header[1] == 42) || return('TIFF file signature incorrect');
8961  
8962 # read TIFF image file directory (IFD)
8963 $tags = _readTIFFdir($fh, $header[2], $short, $long);
8964  
8965 # verify compression (1 = uncompressed)
8966 ($tags->{'259'}[0] == 1) || return('TIFF compression unsupported');
8967  
8968 # verify orientation (1 = normal)
8969 (! exists($tags->{'274'}) || $tags->{'274'}[0] == 1) || warn('TIFF orientation rotated and/or flipped');
8970  
8971 # verify planar configuration (1 = chunky)
8972 (! exists($tags->{'284'}) || $tags->{'284'}[0] == 1) || return('TIFF planar configuration unsupported');
8973  
8974 # verify not tiled
8975 (! exists($tags->{'322'})) || return('TIFF tiled layout unsupported');
8976  
8977 # get TIFF columns (width)
8978 $cols = $tags->{'256'}[0];
8979  
8980 # get TIFF rows (length)
8981 $rows = $tags->{'257'}[0];
8982  
8983 # get TIFF bits per sample
8984 $bits = $tags->{'258'}[0];
8985  
8986 # verify bits per sample
8987 ($bits == 8 || $bits == 16 || $bits == 32) || return('TIFF bits per sample unsupported');
8988  
8989 # get the photometric interpretation
8990 $pi = $tags->{'262'}[0];
8991  
8992 # if 32-bits per sample
8993 if ($bits == 32) {
8994
8995 # verify 32-bit IEEE FP format, RGB image
8996 ($tags->{'339'}[0] == 3 && $pi == 2) || return('TIFF format unsupported');
8997
8998 }
8999  
9000 # get TIFF samples per pixel
9001 $samples = $tags->{'277'}[0];
9002  
9003 # verify bits per sample array
9004 ($samples == grep {$_ == $bits} @{$tags->{'258'}}) || return('TIFF image structure unsupported');
9005  
9006 # get context (if any)
9007 $context = $hash->{'context'};
9008  
9009 # get user defined function (if any)
9010 $udf = $hash->{'udf'};
9011  
9012 # verify UDF is a code reference
9013 (ref($udf) eq 'CODE') || return('UDF not a code reference') if (defined($udf));
9014  
9015 # set device value divisor
9016 $dev = ($bits == 8) ? 255 : 65535;
9017  
9018 # add fields for udf (if any)
9019 $fmt = add_fmt($self, map {defined($context) ? "$context|$_" : $_} @{$hash->{'format'}}) if defined($hash->{'format'});
9020  
9021 # if RGB file
9022 if ($pi == 2 && $samples < 13) {
9023
9024 # add RGB and ALPHA fields, if not already defined
9025 $fmt = add_fmt($self, map {defined($context) ? "$context|$_" : $_} (qw(RGB_R RGB_G RGB_B), map {"RGB_A$_"} (1 .. $samples - 3))) if (! defined($fmt));
9026
9027 # set unpack format (8, 16 or 32 bits)
9028 $upf = ($bits == 8) ? 'C*' : ($bits == 16) ? "$short*" : "$fp*";
9029
9030 # set divisor (8, 16 or 32 bits)
9031 $div = ($bits == 8) ? 1 : ($bits == 16) ? 257 : 1/255;
9032
9033 # if CMYK file
9034 } elsif ($pi == 5 && $samples == 4) {
9035
9036 # add CMYK fields, if not already defined
9037 $fmt = add_fmt($self, map {defined($context) ? "$context|$_" : $_} qw(CMYK_C CMYK_M CMYK_Y CMYK_K)) if (! defined($fmt));
9038
9039 # set unpack format (8 or 16 bits)
9040 $upf = ($bits == 8) ? 'C*' : "$short*";
9041
9042 # set divisor (8 or 16 bits)
9043 $div = ($bits == 8) ? 2.55 : 655.35;
9044
9045 # if nCLR file
9046 } elsif ($pi == 5 && $samples > 4 && $samples < 16) {
9047
9048 # add nCLR fields, if not already defined
9049 $fmt = add_fmt($self, map {defined($context) ? "$context|$_" : $_} map {sprintf('%xCLR_%x', $samples, $_)} (1 .. $samples)) if (! defined($fmt));
9050
9051 # set unpack format (8 or 16 bits)
9052 $upf = ($bits == 8) ? 'C*' : "$short*";
9053
9054 # set divisor (8 or 16 bits)
9055 $div = ($bits == 8) ? 2.55 : 655.35;
9056
9057 # if CIE L*a*b* file
9058 } elsif ($pi == 8 && $samples == 3) {
9059
9060 # add L*a*b* fields, if not already defined
9061 $fmt = add_fmt($self, map {defined($context) ? "$context|$_" : $_} qw(LAB_L LAB_A LAB_B)) if (! defined($fmt));
9062
9063 # set unpack format (8 or 16 bits)
9064 $upf = ($bits == 8) ? '(Ccc)*' : "$short*";
9065
9066 # set divisors (8 or 16 bits)
9067 $div = ($bits == 8) ? 2.55 : 655.35; # L*
9068 $dab = ($bits == 8) ? 1 : 256; # a* and b*
9069
9070 } else {
9071
9072 # return error
9073 return('TIFF color space unsupported');
9074
9075 }
9076  
9077 # get target rows (could be undefined)
9078 $trows = $hash->{'rows'};
9079  
9080 # get target columns (could be undefined)
9081 $tcols = $hash->{'columns'};
9082  
9083 # if 'crop' parameter is defined
9084 if (defined($hash->{'crop'})) {
9085
9086 # get crop parameter
9087 $crop = $hash->{'crop'};
9088
9089 # verify array reference
9090 (ref($crop) eq 'ARRAY') || return('TIFF crop parameter not an array reference');
9091
9092 # verify array contains four non-negative integers
9093 (4 == @{$crop} && 4 == grep {$_ == int($_) && $_ >= 0} @{$crop}) || return('TIFF crop parameter(s) invalid');
9094
9095 # adjust rows and columns
9096 $rows -= $crop->[2] + $crop->[3];
9097 $cols -= $crop->[0] + $crop->[1];
9098
9099 # verify cropped size
9100 ($rows > 0 && $cols > 0) || return('TIFF crop size too small');
9101
9102 # set offset values
9103 $roff = $crop->[2];
9104 $coff = $crop->[0];
9105
9106 } else {
9107
9108 # set offset values
9109 $roff = 0;
9110 $coff = 0;
9111
9112 }
9113  
9114 # if aperture is defined in hash
9115 if (defined($hash->{'aperture'})) {
9116
9117 # compute image resolution
9118 $res = $tags->{'283'}[0]/$tags->{'283'}[1];
9119
9120 # convert to lines/mm if resolution unit is inch
9121 $res /= 25.4 if ($tags->{'296'}[0] == 2);
9122
9123 # convert to lines/mm if resolution unit is cm
9124 $res /= 10 if ($tags->{'296'}[0] == 3);
9125
9126 # if target rows or target columns are defined
9127 if (defined($trows) || defined($tcols)) {
9128
9129 # use image rows if target rows undefined
9130 $trows = $rows if (! defined($trows));
9131
9132 # use image columns if target columns undefined
9133 $tcols = $cols if (! defined($tcols));
9134
9135 # compute aperture size (diameter in pixels)
9136 ($frac, $size) = POSIX::modf(sqrt(ICC::Shared::PI/4) * $res * $hash->{'aperture'});
9137
9138 # if fractional part < 0.25
9139 if ($frac < 0.25) {
9140
9141 # set row and column index offsets
9142 $rxo = $cxo = $size - 1;
9143
9144 # if fractional part < 0.75
9145 } elsif ($frac < 0.75) {
9146
9147 # set row index offset
9148 $rxo = $size - 1;
9149
9150 # set column index offset
9151 $cxo = $size;
9152
9153 } else {
9154
9155 # set row and column index offsets
9156 $rxo = $cxo = $size;
9157
9158 }
9159
9160 # verify aperture is within sample area
9161 ($rxo <= $rows/$trows && $cxo <= $cols/$tcols) || croak('TIFF aperture exceeds sample area')
9162
9163 } else {
9164
9165 # compute aperture area (in pixels)
9166 $size = ICC::Shared::PI * ($res * $hash->{'aperture'}/2)**2;
9167
9168 # compute the target rows
9169 $trows = int(sqrt($size * $rows/$cols) + 0.5);
9170
9171 # compute the target columns
9172 $tcols = int($size/$trows + 0.5);
9173
9174 # set row and column indices (single pixel sample)
9175 $rxo = $cxo = 0;
9176
9177 }
9178
9179 } else {
9180
9181 # use image rows if target rows undefined
9182 $trows = $rows if (! defined($trows));
9183
9184 # use image columns if target columns undefined
9185 $tcols = $cols if (! defined($tcols));
9186
9187 # get mask ratio (default 0.5)
9188 $ratio = defined($hash->{'ratio'}) ? $hash->{'ratio'} : 0.5;
9189
9190 # verify mask ratio
9191 ($ratio >= 0 && $ratio <= 1) || croak('TIFF mask ratio < 0 or > 1');
9192
9193 # compute row index offset
9194 $rxo = int($ratio * $rows/$trows - 0.5);
9195
9196 # compute column index offset
9197 $cxo = int($ratio * $cols/$tcols - 0.5);
9198
9199 }
9200  
9201 # warn if large target size
9202 ($trows * $tcols <= 10000) || warn('TIFF target size > 10000 samples');
9203  
9204 # compute number of pixels
9205 $pixels = ($rxo + 1) * ($cxo + 1);
9206  
9207 # compute row width (bytes)
9208 $width = $tags->{'256'}[0] * List::Util::sum(@{$tags->{'258'}})/8;
9209  
9210 # for each target row
9211 for my $i (0 .. $trows - 1) {
9212
9213 # compute sample lower row
9214 $lower = int(($i + 0.5) * $rows/$trows - $rxo/2) + $roff;
9215
9216 # compute sample upper row
9217 $upper = $lower + $rxo;
9218
9219 # get sample band data
9220 $band = _readTIFFband($fh, $tags, $lower, $upper, $width, $upf);
9221
9222 # for each target column
9223 for my $j (0 .. $tcols - 1) {
9224
9225 # compute sample left column
9226 $left = int(($j + 0.5) * $cols/$tcols - $cxo/2) + $coff;
9227
9228 # compute sample right column
9229 $right = $left + $cxo;
9230
9231 # initialize data
9232 @data = ();
9233
9234 # for each row (band)
9235 for my $m (0 .. $#{$band}) {
9236
9237 # for each column
9238 for my $n ($left .. $right) {
9239
9240 # get pixel value (all samples)
9241 @pix = @{$band->[$m]}[$n * $samples .. ($n + 1) * $samples - 1];
9242
9243 # if 16-bit L*a*b*
9244 if ($pi == 8 && $bits == 16) {
9245
9246 # adjust a* and b* if pixel value negative (signed 16-bit)
9247 $pix[1] += -65536 if ($pix[1] > 32767);
9248 $pix[2] += -65536 if ($pix[2] > 32767);
9249
9250 }
9251
9252 # if user defined function provided
9253 if (defined($udf)) {
9254
9255 # if L*a*b* file
9256 if ($pi == 8) {
9257
9258 # convert values
9259 $pix[0] /= $div;
9260 $pix[1] /= $dab;
9261 $pix[2] /= $dab;
9262
9263 } else {
9264
9265 # convert to device values
9266 @pix = map {$_/$dev} @pix;
9267
9268 # if a CMYK file
9269 if ($pi == 5) {
9270
9271 # for alpha/spot colors (if any)
9272 for my $s (4 .. $samples - 1) {
9273
9274 # invert device value
9275 $pix[$s] = 1 - $pix[$s];
9276
9277 }
9278
9279 }
9280
9281 }
9282
9283 # call user defined function
9284 @pix = &$udf(@pix);
9285
9286 }
9287
9288 # for each channel (may be different from TIFF samples)
9289 for my $s (0 .. $#pix) {
9290
9291 # accumulate pixel values
9292 $data[$s] += $pix[$s]
9293
9294 }
9295
9296 }
9297
9298 }
9299
9300 # if user defined function provided
9301 if (defined($udf)) {
9302
9303 # save data in object
9304 @{$self->[1][$j * $trows + $i + 1]}[@{$fmt}] = map {$_/$pixels} @data;
9305
9306 # if L*a*b* file
9307 } elsif ($pi == 8) {
9308
9309 # save data in object
9310 $self->[1][$j * $trows + $i + 1][$fmt->[0]] = $data[0]/($pixels * $div);
9311 $self->[1][$j * $trows + $i + 1][$fmt->[1]] = $data[1]/($pixels * $dab);
9312 $self->[1][$j * $trows + $i + 1][$fmt->[2]] = $data[2]/($pixels * $dab);
9313
9314 # all others
9315 } else {
9316
9317 # normalize data values
9318 @data = map {$_/($pixels * $div)} @data;
9319
9320 # if a CMYK file
9321 if ($pi == 5) {
9322
9323 # for alpha/spot colors (if any)
9324 for my $s (4 .. $samples - 1) {
9325
9326 # invert %-dot value
9327 $data[$s] = 100 - $data[$s];
9328
9329 }
9330
9331 }
9332
9333 # save data in object
9334 @{$self->[1][$j * $trows + $i + 1]}[@{$fmt}] = @data;
9335
9336 }
9337
9338 }
9339
9340 }
9341  
9342 # save the tag hash in object header
9343 $self->[0]{'TIFF_tag'} = $tags;
9344  
9345 # add LGOROWLENGTH keyword
9346 keyword($self, 'LGOROWLENGTH', $trows);
9347  
9348 # return
9349 return();
9350  
9351 }
9352  
9353 # read TIFF image file directory (IFD)
9354 # parameters: (file_handle, offset, short_format, long_format)
9355 # returns: (IFD_hash)
9356 sub _readTIFFdir {
9357  
9358 # get parameters
9359 my ($fh, $start, $short, $long) = @_;
9360  
9361 # local variables
9362 my (@ts, $buf, $id, $type, $count, $size, $mark, $offset, $num, $denom, $tags);
9363  
9364 # field type size (in bytes)
9365 @ts = (0, 1, 1, 2, 4, 8, 1, 1, 2, 4, 8, 4, 8, 4);
9366  
9367 # seek start of IFD
9368 seek($fh, $start, 0);
9369  
9370 # read number entries
9371 read($fh, $buf, 2);
9372  
9373 # read the directory
9374 for (1 .. unpack($short, $buf)) {
9375
9376 # read first part of IFD entry
9377 read($fh, $buf, 8);
9378
9379 # unpack first three fields (ID, type, count)
9380 ($id, $type, $count) = unpack("$short$short$long", $buf);
9381
9382 # read last part of IFD entry
9383 read($fh, $buf, 4);
9384
9385 # determine value/offset size (size * count) + (1 if ASCII string)
9386 $size = $ts[$type] * $count + (($type == 2) ? 1 : 0);
9387
9388 # if an offset
9389 if ($size > 4) {
9390
9391 # mark file location
9392 $mark = tell($fh);
9393
9394 # unpack offset
9395 $offset = unpack($long, $buf);
9396
9397 # seek values
9398 seek($fh, $offset, 0);
9399
9400 # if binary string
9401 if ($type == 1 || $type == 7) {
9402
9403 # read binary string
9404 read($fh, $buf, $count);
9405
9406 # unpack value
9407 $tags->{$id} = [unpack("a$count", $buf)];
9408
9409 # if ASCII string
9410 } elsif ($type == 2) {
9411
9412 # read ASCII string
9413 read($fh, $buf, $count);
9414
9415 # unpack null-terminated ASCII string
9416 $tags->{$id} = [unpack("Z$count", $buf)];
9417
9418 # if short values
9419 } elsif ($type == 3) {
9420
9421 # read values
9422 read($fh, $buf, 2 * $count);
9423
9424 # unpack values
9425 $tags->{$id} = [unpack("$short$count", $buf)];
9426
9427 # if long values
9428 } elsif ($type == 4) {
9429
9430 # read values
9431 read($fh, $buf, 4 * $count);
9432
9433 # unpack values
9434 $tags->{$id} = [unpack("$long$count", $buf)];
9435
9436 # if rational values
9437 } elsif ($type == 5) {
9438
9439 # double count (one rational value is two long values)
9440 $count *= 2;
9441
9442 # read values
9443 read($fh, $buf, 4 * $count);
9444
9445 # unpack values
9446 $tags->{$id} = [unpack("$long$count", $buf)];
9447
9448 }
9449
9450 # reset file pointer
9451 seek($fh, $mark, 0);
9452
9453 # if binary string
9454 } elsif ($type == 1 || $type == 7) {
9455
9456 # unpack binary string
9457 $tags->{$id} = [unpack("a$count", $buf)];
9458
9459 # if ASCII string
9460 } elsif ($type == 2) {
9461
9462 # unpack null-terminated ASCII string
9463 $tags->{$id} = [unpack("Z$count", $buf)];
9464
9465 # if short value(s)
9466 } elsif ($type == 3) {
9467
9468 # unpack value(s)
9469 $tags->{$id} = [unpack("$short$count", $buf)];
9470
9471 # if long value
9472 } elsif ($type == 4) {
9473
9474 # unpack value
9475 $tags->{$id} = [unpack($long, $buf)];
9476
9477 } else {
9478
9479 # save packed value
9480 $tags->{$id} = [$buf];
9481
9482 }
9483
9484 }
9485  
9486 # return
9487 return($tags);
9488  
9489 }
9490  
9491 # read TIFF image band
9492 # row zero is top of image
9493 # parameters: (file_handle, IFD_hash, lower_row, upper_row, row_width, unpack_format)
9494 # returns: (2D_array)
9495 sub _readTIFFband {
9496  
9497 # get parameters
9498 my ($fh, $tags, $lower, $upper, $width, $upf) = @_;
9499  
9500 # local variables
9501 my ($offset, $rows, $buf, $band);
9502  
9503 # get strip offset array
9504 $offset = $tags->{'273'};
9505  
9506 # get rows per strip
9507 $rows = $tags->{'278'}[0];
9508  
9509 # for each row
9510 for my $i ($lower .. $upper) {
9511
9512 # set file pointer
9513 seek($fh, $offset->[int($i/$rows)] + ($i % $rows) * $width, 0);
9514
9515 # read row data
9516 read($fh, $buf, $width);
9517
9518 # unpack data
9519 $band->[$i - $lower] = [unpack($upf, $buf)];
9520
9521 }
9522  
9523 # return
9524 return($band);
9525  
9526 }
9527  
9528 # write TIFF image file directory (IFD)
9529 # parameters: (file_handle, offset, short_format, long_format, IFD_hash)
9530 sub _writeTIFFdir {
9531  
9532 # get parameters
9533 my ($fh, $ifd, $short, $long, $tags) = @_;
9534  
9535 # local variables
9536 my (@ts, @sid, $mark, $type, $count, $size, $fmt);
9537  
9538 # field type size (in bytes)
9539 @ts = (0, 1, 1, 2, 4, 8, 1, 1, 2, 4, 8, 4, 8, 4);
9540  
9541 # make list of tag ids, sorted numerically
9542 @sid = sort {$a <=> $b} keys(%{$tags});
9543  
9544 # seek start of IFD
9545 seek($fh, $ifd, 0);
9546  
9547 # write number of tags
9548 print $fh pack($short, scalar(@sid));
9549  
9550 # set data pointer
9551 $mark = $ifd + 12 * @sid + 6;
9552  
9553 # for each tag
9554 for my $id (@sid) {
9555
9556 # get data type
9557 $type = $tags->{$id}[0];
9558
9559 # if a binary string
9560 if ($type == 1 || $type == 7) {
9561
9562 # set count to string length
9563 $count = length($tags->{$id}[1]);
9564
9565 # if an ASCII string
9566 } elsif ($type == 2) {
9567
9568 # set count to string length + 1
9569 $count = length($tags->{$id}[1]) + 1;
9570
9571 # if a rational value
9572 } elsif ($type == 5) {
9573
9574 # set count to number of values/2
9575 $count = $#{$tags->{$id}}/2;
9576
9577 } else {
9578
9579 # set count to number of values
9580 $count = $#{$tags->{$id}};
9581
9582 }
9583
9584 # if size of value/offset > 4
9585 if (($size = $count * $ts[$type]) > 4) {
9586
9587 # write directory entry with offset
9588 print $fh pack("$short$short$long$long", $id, $type, $count, $mark);
9589
9590 # increment data pointer
9591 $mark += $size;
9592
9593 # make a word boundary
9594 $mark += $mark % 2;
9595
9596 } else {
9597
9598 # if a binary string
9599 if ($type == 1 || $type == 7) {
9600
9601 # set pack format
9602 $fmt = 'a4';
9603
9604 # if an ASCII string
9605 } elsif ($type == 2) {
9606
9607 # set pack format
9608 $fmt = 'Z4';
9609
9610 # if a short value
9611 } elsif ($type == 3) {
9612
9613 # set pack format (one or two values)
9614 $fmt = $count == 1 ? $short . 'x2' : $short . '2';
9615
9616 # if a long value
9617 } elsif ($type == 4) {
9618
9619 # set pack format
9620 $fmt = $long;
9621
9622 } else {
9623
9624 # error
9625 croak('unsupported TIFF data type, stopped');
9626
9627 }
9628
9629 # write directory entry (12 bytes) with value(s)
9630 print $fh pack("$short$short$long$fmt", $id, $type, $count, @{$tags->{$id}}[1 .. $#{$tags->{$id}}]);
9631
9632 }
9633
9634 }
9635  
9636 # set data pointer
9637 $mark = $ifd + 12 * @sid + 6;
9638  
9639 # for each tag
9640 for my $id (@sid) {
9641
9642 # get data type
9643 $type = $tags->{$id}[0];
9644
9645 # if a binary string
9646 if ($type == 1 || $type == 7) {
9647
9648 # set count to string length
9649 $count = length($tags->{$id}[1]);
9650
9651 # if an ASCII string
9652 } elsif ($type == 2) {
9653
9654 # set count to string length + 1
9655 $count = length($tags->{$id}[1]) + 1;
9656
9657 # if a rational value
9658 } elsif ($type == 5) {
9659
9660 # set count to number of values/2
9661 $count = $#{$tags->{$id}}/2;
9662
9663 } else {
9664
9665 # set count to number of values
9666 $count = $#{$tags->{$id}};
9667
9668 }
9669
9670 # if size of value/offset > 4
9671 if (($size = $count * $ts[$type]) > 4) {
9672
9673 # if a binary string
9674 if ($type == 1 || $type == 7) {
9675
9676 # set pack format
9677 $fmt = "a$count";
9678
9679 # if an ASCII string
9680 } elsif ($type == 2) {
9681
9682 # set pack format
9683 $fmt = "Z$count";
9684
9685 # if a short value
9686 } elsif ($type == 3) {
9687
9688 # set pack format
9689 $fmt = "$short$count";
9690
9691 # if a long value
9692 } elsif ($type == 4) {
9693
9694 # set pack format
9695 $fmt = "$long$count";
9696
9697 # if a rational value
9698 } elsif ($type == 5) {
9699
9700 # set pack format
9701 $fmt = "$long$#{$tags->{$id}}";
9702
9703 } else {
9704
9705 # error
9706 croak('unsupported TIFF data type, stopped');
9707 }
9708
9709 # set file pointer
9710 seek($fh, $mark, 0);
9711
9712 # write the data value(s)
9713 print $fh pack($fmt, @{$tags->{$id}}[1 .. $#{$tags->{$id}}]);
9714
9715 # increment data pointer
9716 $mark += $size;
9717
9718 # make a word boundary
9719 $mark += $mark % 2;
9720
9721 }
9722
9723 }
9724
9725 }
9726  
9727 # write TIFF data strip
9728 # parameters: (file_handle, IFD_hash, patch_width, gap_width, left_edge_width, right_edge_width, strip_index, strip_data_array, pack_format, dither_value)
9729 sub _writeTIFFstrip {
9730  
9731 # get parameters
9732 my ($fh, $tags, $width, $gap, $left, $right, $sx, $data, $fmt, $dither) = @_;
9733  
9734 # local variables
9735 my ($pi, $samples, $bits, $max, $diff, $edge, $w, @spot, $rms, $gdata, @row, $strip);
9736  
9737 # get photometric interpretation
9738 $pi = $tags->{'262'}[1];
9739  
9740 # get number of samples (channels)
9741 $samples = $tags->{'277'}[1];
9742  
9743 # get bits per sample
9744 $bits = $tags->{'258'}[1];
9745  
9746 # max binary value (8, 16 or 32 bits)
9747 $max = ($bits == 8) ? 255 : ($bits == 16) ? 65535 : 1;
9748  
9749 # make list of spot channel indices
9750 @spot = (4 .. $tags->{'277'}[1] - 1);
9751  
9752 # for each patch
9753 for my $i (0 .. $#{$data}) {
9754
9755 # if RGB data
9756 if ($pi == 2) {
9757
9758 # compute white and black differences
9759 $diff->[$i][0] = sqrt(($max - $data->[$i][0])**2 + ($max - $data->[$i][1])**2 + ($max - $data->[$i][2])**2);
9760 $diff->[$i][1] = sqrt($data->[$i][0]**2 + $data->[$i][1]**2 + $data->[$i][2]**2);
9761
9762 # if CMYK data
9763 } elsif ($pi == 5) {
9764
9765 # compute rms value of CMY + spot channels (CMY weighted and spot channels inverted)
9766 $rms = sqrt(List::Util::sum(0.25 * $data->[$i][0]**2, 3 * $data->[$i][1]**2, 0.25 * $data->[$i][2]**2, (map {($max - $data->[$i][$_])**2} @spot))/(3 + @spot));
9767
9768 # compute white and black differences (black * color)
9769 $diff->[$i][0] = $max - ($max - $data->[$i][3]) * ($max - $rms)/$max;
9770 $diff->[$i][1] = ($max - $data->[$i][3]) * ($max - $rms)/$max;
9771
9772 # L*a*b* data
9773 } else {
9774
9775 # compute white and black differences (approx dEab)
9776 $diff->[$i][0] = sqrt(($max - $data->[$i][0])**2 + 6.55 * $data->[$i][1]**2 + 6.55 * $data->[$i][2]**2);
9777 $diff->[$i][1] = sqrt($data->[$i][0]**2 + 6.55 * $data->[$i][1]**2 + 6.55 * $data->[$i][2]**2);
9778
9779 }
9780
9781 # skip first patch
9782 if ($i > 0) {
9783
9784 # if RGB data
9785 if ($pi == 2) {
9786
9787 # if max white difference > max black difference
9788 if (($diff->[$i - 1][0] > $diff->[$i][0] ? $diff->[$i - 1][0] : $diff->[$i][0]) > ($diff->[$i - 1][1] > $diff->[$i][1] ? $diff->[$i - 1][1] : $diff->[$i][1])) {
9789
9790 # gap is white
9791 $gdata->[$i - 1] = [($max) x 3];
9792
9793 } else {
9794
9795 # gap is black
9796 $gdata->[$i - 1] = [0, 0, 0];
9797
9798 }
9799
9800 # if CMYK data
9801 } elsif ($pi == 5) {
9802
9803 # if max white difference > max black difference
9804 if (($diff->[$i - 1][0] > $diff->[$i][0] ? $diff->[$i - 1][0] : $diff->[$i][0]) > ($diff->[$i - 1][1] > $diff->[$i][1] ? $diff->[$i - 1][1] : $diff->[$i][1])) {
9805
9806 # gap is white
9807 $gdata->[$i - 1] = [0, 0, 0, 0, ($max) x ($samples - 4)];
9808
9809 } else {
9810
9811 # gap is black
9812 $gdata->[$i - 1] = [0, 0, 0, ($max) x ($samples - 3)];
9813
9814 }
9815
9816 # L*a*b* data
9817 } else {
9818
9819 # if max white difference > max black difference
9820 if (($diff->[$i - 1][0] > $diff->[$i][0] ? $diff->[$i - 1][0] : $diff->[$i][0]) > ($diff->[$i - 1][1] > $diff->[$i][1] ? $diff->[$i - 1][1] : $diff->[$i][1])) {
9821
9822 # gap is white
9823 $gdata->[$i - 1] = [$max, 0, 0];
9824
9825 } else {
9826
9827 # gap is black
9828 $gdata->[$i - 1] = [0, 0, 0];
9829
9830 }
9831
9832 }
9833
9834 }
9835
9836 }
9837  
9838 # compute edge pixel values (black)
9839 $edge = ($pi == 5) ? [0, 0, 0, ($max) x ($samples - 3)] : [0, 0, 0];
9840  
9841 # for each patch
9842 for my $i (0 .. $#{$data}) {
9843
9844 # if first patch
9845 if ($i == 0) {
9846
9847 # add left edge data
9848 push(@row, (@{$edge}) x $left->[0]);
9849
9850 # set patch width
9851 $w = $width - $left->[1];
9852
9853 # if last patch
9854 } elsif ($i == $#{$data}) {
9855
9856 # set patch width
9857 $w = $width - $right->[1];
9858
9859 # others
9860 } else {
9861
9862 # set patch width
9863 $w = $width;
9864
9865 }
9866
9867 # if dither enabled or 32-bits
9868 if (defined($dither) || $bits == 32) {
9869
9870 # add patch data
9871 push(@row, (@{$data->[$i]}) x $w);
9872
9873 } else {
9874
9875 # add patch data, adding/subtracting 0.5 to round to the nearest integer (by 'pack', below)
9876 push(@row, (map {$_ < 0 ? $_ - 0.5 : $_ + 0.5} @{$data->[$i]}) x $w);
9877
9878 }
9879
9880 # if last patch
9881 if ($i == $#{$data}) {
9882
9883 # add right edge data
9884 push(@row, (@{$edge}) x $right->[0]);
9885
9886 } else {
9887
9888 # add gap data
9889 push(@row, (@{$gdata->[$i]}) x $gap);
9890
9891 }
9892
9893 }
9894  
9895 # set file pointer to strip offset
9896 seek($fh, $tags->{'273'}[$sx + 1], 0);
9897
9898 # if dither enabled and 8-bit
9899 if (defined($dither) && $bits == 8) {
9900
9901 # for each strip row
9902 for my $i (0 .. $tags->{'278'}[1] - 1) {
9903
9904 # write packed data with dithering
9905 print $fh pack($fmt, map {$_ < 0 ? $_ - rand() : $_ + rand()} @row);
9906
9907 }
9908
9909 } else {
9910
9911 # for each strip row
9912 for my $i (0 .. $tags->{'278'}[1] - 1) {
9913
9914 # write packed data
9915 print $fh pack($fmt, @row);
9916
9917 }
9918
9919 }
9920
9921 }
9922  
9923 # read chart from CxF3 data file
9924 # parameters: (object_reference, file_handle, hash)
9925 # returns: (result)
9926 sub _readChartCxF3 {
9927  
9928 # get parameters
9929 my ($self, $fh, $hash) = @_;
9930  
9931 # local variables
9932 my ($dom, $root, $ns, $uri, %keys, @info, @obj, $ops_hash, $ops);
9933 my ($ix, $type, $name, $value, $node, @data, $xrp, @attr);
9934  
9935 # parse CxF3 document
9936 eval{$dom = XML::LibXML->load_xml('IO' => $fh)} || return('failed parsing CxF3 document');
9937  
9938 # validate the CxF3 document
9939 _validateCxF3($dom) if (defined($hash->{'validate'}) && $hash->{'validate'});
9940  
9941 # get root element
9942 $root = $dom->documentElement();
9943  
9944 # get the namespace prefix and URI
9945 $ns = $root->prefix();
9946 $uri = $root->namespaceURI();
9947  
9948 # verify CxF3 document or return
9949 ($uri eq 'http://colorexchangeformat.com/CxF3-core') || return('CxF3 document has wrong URI');
9950  
9951 # get cc:Object elements
9952 @obj = $root->findnodes("$ns:Resources/$ns:ObjectCollection/$ns:Object");
9953  
9954 # get cc:FileInformation elements (optional)
9955 @info = $root->findnodes("$ns:FileInformation/*");
9956  
9957 # save root element
9958 # this method only reads data from cc:Object nodes
9959 # all other CxF3 info is kept in the dom object
9960 # and accessed as needed by other methods
9961 $self->[0]{'CxF3_dom'} = $root;
9962  
9963 # save record separator in header
9964 # note: XML files might not have record separators
9965 # so we use Perl's input record separator instead
9966 $self->[0]{'read_rs'} = $/;
9967  
9968 # make CxF3 => ASCII mapping table (from ISO 17972-1, Annex A)
9969 %keys = ('Creator' => 'ORIGINATOR', 'Description' => 'FILE_DESCRIPTOR', 'CreationDate' => 'CREATED', 'Comment' => 'CXF3_COMMENT');
9970  
9971 # for each cc:FileInformation element
9972 for my $s (@info) {
9973
9974 # if cc:Tag node
9975 if ($s->nodeName() eq "$ns:Tag") {
9976
9977 # get name attribute
9978 $name = $s->getAttribute('Name');
9979
9980 # get value attribute
9981 $value = $s->getAttribute('Value');
9982
9983 } else {
9984
9985 # get node name
9986 $name = $s->nodeName();
9987
9988 # remove namespace prefix
9989 $name =~ s/^\w+://;
9990
9991 # lookup name in hash
9992 $name = defined($keys{$name}) ? $keys{$name} : $name;
9993
9994 # get node value
9995 $value = $s->textContent();
9996
9997 }
9998
9999 # add name/value to header array
10000 push(@{$self->[3]}, [$name, "\"$value\"", 'FileInformation']);
10001
10002 }
10003  
10004 # make the operations hash and add format fields
10005 $ops_hash = _makeCxF3readops($self, $root, $ns, \@obj, $hash);
10006  
10007 # initialize sample index
10008 $ix = 0;
10009  
10010 # for each cc:Object element
10011 for my $s (@obj) {
10012
10013 # get the ObjectType attribute
10014 $type = $s->getAttribute('ObjectType');
10015
10016 # get the Name attribute
10017 $name = $s->getAttribute('Name');
10018
10019 # if ObjectType is 'Target' or '...Measurement'
10020 if ($type =~ m/^Target$|Measurement$/) {
10021
10022 # match numeric part of Name attribute
10023 $name =~ m/(\d+)$/;
10024
10025 # set row index
10026 $ix = $1;
10027
10028 } else {
10029
10030 # increment row index
10031 $ix++;
10032
10033 }
10034
10035 # get operation list for this ObjectType
10036 $ops = $ops_hash->{$type};
10037
10038 # for each operation
10039 for my $i (0 .. $#{$ops}) {
10040
10041 # get main Xpath node
10042 ($node) = $s->findnodes($ops->[$i][1]);
10043
10044 # if subpaths
10045 if (@{$ops->[$i][2]}) {
10046
10047 # if data class is NCLR
10048 if ($ops->[$i][0] eq 'NCLR') {
10049
10050 # get the CMYK values
10051 @data = map {$node->findvalue($_)} @{$ops->[$i][2]};
10052
10053 # for each SpotColor
10054 for my $spotcolor ($node->findnodes("$ns:SpotColor")) {
10055
10056 # push SpotColor value
10057 push(@data, $spotcolor->findvalue("$ns:Percentage"));
10058
10059 }
10060
10061 # set chart data (CMYK + SPOT values)
10062 @{$self->[1][$ix]}[@{$ops->[$i][3]}] = @data;
10063
10064 } else {
10065
10066 # set chart data using subpaths
10067 @{$self->[1][$ix]}[@{$ops->[$i][3]}] = map {$node->findvalue($_)} @{$ops->[$i][2]};
10068
10069 }
10070
10071 # if no subpaths and one field
10072 } elsif (@{$ops->[$i][3]} == 1) {
10073
10074 # set chart data to text content
10075 $self->[1][$ix][$ops->[$i][3][0]] = $node->textContent();
10076
10077 # if no subpaths and multiple fields (e.g. spectral data)
10078 } elsif (@{$ops->[$i][3]} > 1) {
10079
10080 # set chart data splitting text content
10081 @{$self->[1][$ix]}[@{$ops->[$i][3]}] = split(/ /, $node->textContent());
10082
10083 }
10084
10085 }
10086
10087 }
10088  
10089 # read CxF3 ColorSpecification nodes
10090 _readCxF3colorspec($self, $root, $ns);
10091  
10092 # make XPathContext object for X-Rite Prism namespace
10093 $xrp = XML::LibXML::XPathContext->new($root);
10094 $xrp->registerNs('xrp', 'http://www.xrite.com/products/prism');
10095  
10096 # get the xrp:CustomAttributes node
10097 if (($node) = $xrp->findnodes("$ns:CustomResources/xrp:Prism/xrp:CustomAttributes")) {
10098
10099 # get the attribute list
10100 @attr = $node->attributes();
10101
10102 # add xrp:CustomAttributes hash
10103 $self->[0]{'xrp:CustomAttributes'} = {map {$_->nodeName, $_->getValue()} @attr};
10104
10105 }
10106  
10107 # return
10108 return();
10109  
10110 }
10111  
10112 # make CxF3 read operations hash
10113 # adds the format fields to object
10114 # parameters: (object_reference, CxF3_root, CxF3_prefix, CxF3_object_array_reference, hash)
10115 # returns: (hash_ref)
10116 sub _makeCxF3readops {
10117  
10118 # get parameters
10119 my ($self, $root, $ns, $obj, $hash) = @_;
10120  
10121 # local variables
10122 my (@attr, @tags, %keys, $table, $k, $m, $n, $t, $type, $entry, $ops_hash);
10123 my (@format, @nodes, $node, @data, $name, $colorspec, $start, $inc);
10124  
10125 # if cc:Object filter parameter provided
10126 if (defined($hash->{'cc:Object'}) && ref($hash->{'cc:Object'}) eq 'ARRAY') {
10127
10128 # for each entry
10129 for (@{$hash->{'cc:Object'}}) {
10130
10131 # match type/attribute
10132 m/^([^\s\/]*?)\/?([^\s\/]*)$/;
10133
10134 # save matched values
10135 $entry = [$1, $2];
10136
10137 # if a valid attribute (see CxF3_Core.xsd)
10138 if ($2 =~ m/^(?:|ObjectType|Name|Id|GUID|\*)$/) {
10139
10140 # push on array
10141 push(@attr, $entry);
10142
10143 } else {
10144
10145 # print warning
10146 warn('invalid cc:Object attribute');
10147
10148 }
10149
10150 }
10151
10152 }
10153  
10154 # if cc:Tag filter parameter provided
10155 if (defined($hash->{'cc:Tag'}) && ref($hash->{'cc:Tag'}) eq 'ARRAY') {
10156
10157 # for each entry
10158 for (@{$hash->{'cc:Tag'}}) {
10159
10160 # match type/key
10161 m/^([^\s\/]*?)\/?([^\s\/]*)$/;
10162
10163 # push on array
10164 push(@tags, [$1, $2]);
10165
10166 }
10167
10168 }
10169  
10170 # make hash for sort order of certain keys
10171 %keys = ('SampleID' => -2, 'SampleName' => -1, 'Id' => -2, 'Name' => -1);
10172  
10173 # table [data_class, CxF3_main_path, [CxF3_sub_paths], [CGATS/ASCII field names]]
10174 # some mappings have no sub-paths, which is indicated by an empty sub_path array
10175 # the 'NCLR', 'SPECTRAL' and 'DENSITY' data classes are special cases
10176 $table = [
10177 ['RGB', "$ns:DeviceColorValues/$ns:ColorRGB", ["$ns:R", "$ns:G", "$ns:B"], [qw(RGB_R RGB_G RGB_B)]],
10178 ['CMYK', "$ns:DeviceColorValues/$ns:ColorCMYK", ["$ns:Cyan", "$ns:Magenta", "$ns:Yellow", "$ns:Black"], [qw(CMYK_C CMYK_M CMYK_Y CMYK_K)]],
10179 ['NCLR', "$ns:DeviceColorValues/$ns:ColorCMYKPlusN", ["$ns:Cyan", "$ns:Magenta", "$ns:Yellow", "$ns:Black"], [qw(nCLR)]],
10180 ['SPECTRAL', "$ns:ColorValues/$ns:ReflectanceSpectrum", [], [qw(nm)]],
10181 ['DENSITY', "$ns:ColorValues/$ns:ColorDensity/$ns:Density", [], [qw(D_RED D_GREEN D_BLUE D_VIS)]],
10182 ['XYZ', "$ns:ColorValues/$ns:ColorCIEXYZ", ["$ns:X", "$ns:Y", "$ns:Z"], [qw(XYZ_X XYZ_Y XYZ_Z)]],
10183 ['XYY', "$ns:ColorValues/$ns:ColorCIExyY", ["$ns:x", "$ns:y", "$ns:Y"], [qw(XYY_X XYY_Y XYY_YCAP)]],
10184 ['LAB', "$ns:ColorValues/$ns:ColorCIELab", ["$ns:L", "$ns:A", "$ns:B"], [qw(LAB_L LAB_A LAB_B)]],
10185 ['LCH', "$ns:ColorValues/$ns:ColorCIELCh", ["$ns:L", "$ns:C", "$ns:H"], [qw(LAB_L LAB_C LAB_H)]],
10186 ['DE', "$ns:ColorDifferenceValues/$ns:DeltaCIELab/$ns:dE", [], [qw(LAB_DE)]],
10187 ['DE94', "$ns:ColorDifferenceValues/$ns:DeltaCIELab/$ns:dE94", [], [qw(LAB_DE94)]],
10188 ['DECMC', "$ns:ColorDifferenceValues/$ns:DeltaCIELab/$ns:dEcmc", [], [qw(LAB_CMC)]],
10189 ['DE2000', "$ns:ColorDifferenceValues/$ns:DeltaCIELab/$ns:dE2000", [], [qw(LAB_2000)]],
10190 ];
10191  
10192 # set next table index
10193 $m = $#{$table} + 1;
10194  
10195 # for each CxF3 'Object'
10196 for my $s (@{$obj}) {
10197
10198 # get the 'ObjectType' attribute
10199 $type = $s->getAttribute('ObjectType');
10200
10201 # if 'ObjectType' not in hash
10202 if (! defined($ops_hash->{$type})) {
10203
10204 # add 'ObjectType' to hash
10205 $ops_hash->{$type} = [];
10206
10207 # if 'Object' attributes are mapped
10208 if (@attr) {
10209
10210 # for each 'Object' attribute (GUID is optional)
10211 for my $t (qw(ObjectType Name Id GUID)) {
10212
10213 # if attribute exists and is mapped
10214 if ($s->exists("\@$t") && grep {($_->[0] eq $type || $_->[0] =~ m/^\*?$/) && ($_->[1] eq $t || $_->[1] =~ m/^\*?$/)} @attr) {
10215
10216 # get sort order
10217 $k = defined($keys{$t}) ? $keys{$t} : $m++;
10218
10219 # push table entry on hash array (note: attribute XPaths begin with @)
10220 push(@{$ops_hash->{$type}}, $entry = ["ATTR:$t", "\@$t", [], [$t], $type, $k]);
10221
10222 # push table entry on format array
10223 push(@format, $entry);
10224
10225 }
10226
10227 }
10228
10229 } else {
10230
10231 # if ObjectType not 'Target' or '...Measurement'
10232 if ($type !~ m/^Target$|Measurement$/) {
10233
10234 # push table entry on hash array (note: attribute XPaths begin with @)
10235 push(@{$ops_hash->{$type}}, $entry = ['NAME', '@Name', [], ['SAMPLE_NAME'], $type, -1]);
10236
10237 # push table entry on format array
10238 push(@format, $entry);
10239
10240 }
10241
10242 }
10243
10244 # for each table entry
10245 for my $i (0 .. $#{$table}) {
10246
10247 # get table entry
10248 $t = $table->[$i];
10249
10250 # if main XPath exists
10251 if ($s->exists($t->[1])) {
10252
10253 # get ColorSpecification attribute (if any)
10254 $colorspec = $s->findvalue("$t->[1]/\@ColorSpecification");
10255
10256 # push table entry on hash array
10257 push(@{$ops_hash->{$type}}, $entry = [@{$t}, $type, $i, $colorspec]);
10258
10259 # push table entry on format array
10260 push(@format, $entry);
10261
10262 # if an 'NCLR' entry
10263 if ($entry->[0] eq 'NCLR') {
10264
10265 # get cc:SpotColor nodes
10266 @nodes = $s->findnodes(".//$ns:SpotColor");
10267
10268 # get number of colors
10269 $n = @nodes + 4;
10270
10271 # add format fields
10272 $entry->[3] = [map {sprintf('%xCLR_%x', $n, $_)} (1 .. $n)];
10273
10274 # if a 'SPECTRAL' entry
10275 } elsif ($entry->[0] eq 'SPECTRAL') {
10276
10277 # get the ReflectanceSpectrum data
10278 @data = split(/ /, $s->findvalue($t->[1]));
10279
10280 # get the ColorSpecification node (linked by the ColorSpecification attribute)
10281 ($node) = $root->findnodes("$ns:Resources/$ns:ColorSpecificationCollection/$ns:ColorSpecification[\@Id='$colorspec']");
10282
10283 # get the StartWL attribute
10284 $start = $node->findvalue("$ns:MeasurementSpec/$ns:WavelengthRange/\@StartWL");
10285
10286 # get the Increment attribute
10287 $inc = $node->findvalue("$ns:MeasurementSpec/$ns:WavelengthRange/\@Increment");
10288
10289 # add format fields
10290 $entry->[3] = [map {'nm' . ($start + $_ * $inc)} (0 .. $#data)];
10291
10292 }
10293
10294 }
10295
10296 }
10297
10298 # if Tags are mapped
10299 if (@tags) {
10300
10301 # for each Tag
10302 for my $t ($s->findnodes("$ns:TagCollection/$ns:Tag")) {
10303
10304 # get Tag Name attribute
10305 $name = $t->getAttribute('Name');
10306
10307 # if this Tag is mapped
10308 if (grep {($_->[0] eq $type || $_->[0] =~ m/^\*?$/) && ($_->[1] eq $name || $_->[1] =~ m/^\*?$/)} @tags) {
10309
10310 # get sort order
10311 $k = defined($keys{$name}) ? $keys{$name} : $m++;
10312
10313 # push table entry on hash array (note: attribute XPaths begin with @)
10314 push(@{$ops_hash->{$type}}, $entry = ["TAG:$name", "$ns:TagCollection/$ns:Tag[\@Name = '$name']/\@Value", [], [$name], $type, $k]);
10315
10316 # push table entry on format array
10317 push(@format, $entry);
10318
10319 }
10320
10321 }
10322
10323 }
10324
10325 }
10326
10327 }
10328  
10329 # sort format array by table index
10330 @format = sort {$a->[5] <=> $b->[5]} @format;
10331
10332 # for each format entry
10333 for my $fmt (@format) {
10334
10335 # add format fields to data array and replace keys with column indices
10336 $fmt->[3] = add_fmt($self, map {"$fmt->[4]|$_"} @{$fmt->[3]});
10337
10338 # if entry has ColorSpecification
10339 if (defined($fmt->[6])) {
10340
10341 # add ColorSpecification attribute to colorimetry array
10342 for (@{$fmt->[3]}) {$self->[2][5][$_] = $fmt->[6]}
10343
10344 }
10345
10346 }
10347  
10348 # return
10349 return($ops_hash);
10350  
10351 }
10352  
10353 # read CxF3 ColorSpecification nodes
10354 # parameters: (object_reference, CxF3_root, CxF3_prefix)
10355 sub _readCxF3colorspec {
10356  
10357 # get parameters
10358 my ($self, $root, $ns) = @_;
10359  
10360 # local variables
10361 my (@keys, @cspec, $id, $node, $child, $value);
10362  
10363 # make CxF3 => ASCII mapping table (from ISO 17972-1, Annex A)
10364 @keys = (
10365 ["$ns:MeasurementSpec/$ns:GeometryChoice" => 'MEASUREMENT_GEOMETRY'],
10366 ["$ns:MeasurementSpec/$ns:Device/$ns:DeviceFilter" => 'FILTER'],
10367 ["$ns:MeasurementSpec/$ns:Device/$ns:DeviceIllumination" => 'MEASUREMENT_SOURCE'],
10368 ["$ns:MeasurementSpec/$ns:CalibrationStandard" => 'DEVCALSTD'],
10369 );
10370  
10371 # find the ColorSpecification nodes
10372 @cspec = $root->findnodes("$ns:Resources/$ns:ColorSpecificationCollection/$ns:ColorSpecification");
10373  
10374 # for each ColorSpecification node
10375 for my $s (@cspec) {
10376
10377 # get the Id attribute and skip if 'Unknown'
10378 next if (($id = $s->getAttribute('Id')) eq 'Unknown');
10379
10380 # for each entry in mapping table
10381 for my $i (0 .. $#keys) {
10382
10383 # if XPath is found
10384 if (($node) = $s->findnodes($keys[$i][0])) {
10385
10386 # get the first non-blank child node
10387 if (($child) = $node->nonBlankChildNodes()) {
10388
10389 # if child is an element node
10390 if ($child->nodeType() == 1) {
10391
10392 # serialize node
10393 $value = $node->toString(1);
10394
10395 # remove tabs and endlines
10396 $value =~ s/[\t\n]+//g;
10397
10398 # remove namespace prefix
10399 $value =~ s/([<\/])$ns:/$1/g;
10400
10401 # if child is a text node
10402 } elsif ($child->nodeType() == 3) {
10403
10404 # get the value
10405 $value = $node->textContent();
10406
10407 }
10408
10409 # save in header line array
10410 push(@{$self->[3]}, [$keys[$i][1], "\"$value\"", $id]);
10411
10412 }
10413
10414 }
10415
10416 }
10417
10418 }
10419
10420 }
10421  
10422 # make CxF3 FileInformation nodes
10423 # optional hash parameter contains 'cc:FileInformation' filter array
10424 # parameters: (object_reference, CxF3_root, CxF3_prefix, CxF3_namespace_URI, hash)
10425 # returns: (datetime)
10426 sub _makeCxF3fileinfo {
10427  
10428 # get parameters
10429 my ($self, $root, $ns, $nsURI, $hash) = @_;
10430  
10431 # local variables
10432 my (@filter, $t, $datetime, $info, %keys);
10433 my ($keyword, $value, $source, $node, $child);
10434  
10435 # get filter array (if any)
10436 @filter = @{ICC::Shared::flatten($hash->{'cc:FileInformation'})} if (defined($hash->{'cc:FileInformation'}));
10437  
10438 # make Time::Piece object
10439 $t = localtime();
10440  
10441 # get the 'FileInformation' node
10442 ($info) = $root->findnodes("$ns:FileInformation");
10443  
10444 # make ASCII => CxF3 mapping table (from ISO 17972-1, Annex A)
10445 %keys = ('ORIGINATOR' => "$ns:Creator", 'FILE_DESCRIPTOR' => "$ns:Description", 'CXF3_COMMENT' => "$ns:Comment");
10446  
10447 # for each file header line
10448 for (@{$self->[3]}) {
10449
10450 # get keyword, value and source
10451 ($keyword, $value, $source) = @{$_};
10452
10453 # strip quotes from value
10454 $value =~ s/^\"(.*)\"$/$1/;
10455
10456 # if keyword is 'CREATED'
10457 if ($keyword eq 'CREATED') {
10458
10459 # make Time::Piece object from 'CREATED' value
10460 $t = _makeTimePiece($value);
10461
10462 # if source is 'FileInformation' or keyword is in filter array
10463 } elsif ((defined($source) && $source eq 'FileInformation') || grep {$_ eq $keyword} @filter) {
10464
10465 # if keyword in mapping table
10466 if (exists($keys{$keyword})) {
10467
10468 # if XPath exists in FileInformation element
10469 if (($node) = $info->findnodes($keys{$keyword})) {
10470
10471 # if text content exists
10472 if ((($child) = $node->nonBlankChildNodes) && $child->nodeType == 3) {
10473
10474 # update text content
10475 $child->setData($value);
10476
10477 }
10478
10479 }
10480
10481 # must be a 'Tag' element
10482 } else {
10483
10484 # if XPath exists in FileInformation element
10485 if (($node) = $info->findnodes("$ns:Tag[\@Name='$keyword']")) {
10486
10487 # update the Value attribute
10488 $node->setAttribute('Value', $value);
10489
10490 } else {
10491
10492 # add new Tag element
10493 $node = $info->appendChild(XML::LibXML::Element->new('Tag'));
10494 $node->setAttribute('Name', $keyword);
10495 $node->setAttribute('Value', $value);
10496 $node->setNamespace($nsURI, $ns);
10497
10498 }
10499
10500 }
10501
10502 }
10503
10504 }
10505  
10506 # make ISO 8601 datetime string from Time::Piece object
10507 $datetime = sprintf("%s%+03d:00", $t->datetime, $t->tzoffset->hours);
10508  
10509 # get the 'CreationDate' node
10510 ($node) = $info->findnodes("$ns:CreationDate");
10511  
10512 # if text content exists
10513 if ((($child) = $node->nonBlankChildNodes) && $child->nodeType == 3) {
10514
10515 # update text content
10516 $child->setData($datetime);
10517
10518 }
10519  
10520 # return datetime
10521 return($datetime);
10522  
10523 }
10524  
10525 # make CxF3 write operations array
10526 # parameters: (object_reference, CxF3_root, CxF3_prefix, column_slice)
10527 # returns: (array_ref)
10528 sub _makeCxF3writeops {
10529  
10530 # get parameters
10531 my ($self, $root, $ns, $cols) = @_;
10532  
10533 # local variables
10534 my ($n, %keys, $table, $class, $prefix, $key, $ops, $groups, $sort);
10535  
10536 # if column slice defined
10537 if (defined($cols)) {
10538
10539 # if column slice an empty array reference
10540 if (ref($cols) eq 'ARRAY' && @{$cols} == 0) {
10541
10542 # use all columns
10543 $cols = [0 .. $#{$self->[1][0]}];
10544
10545 } else {
10546
10547 # flatten column slice
10548 $cols = ICC::Shared::flatten($cols);
10549
10550 }
10551
10552 } else {
10553
10554 # use all columns
10555 $cols = [0 .. $#{$self->[1][0]}];
10556
10557 }
10558  
10559 # get number of fields
10560 $n = @{$cols};
10561  
10562 # remove undefined keys
10563 @{$cols} = grep {defined($self->[1][0][$_])} @{$cols};
10564  
10565 # warn if undefined keys
10566 ($n == @{$cols}) || warn('undefined keys in column slice');
10567  
10568 # get number of fields
10569 $n = @{$cols};
10570  
10571 # remove duplicate keys
10572 @{$cols} = grep {! $keys{$self->[1][0][$_]}++} @{$cols};
10573  
10574 # warn if duplicate keys
10575 ($n == @{$cols}) || warn('duplicate keys in column slice');
10576  
10577 # table structure: [data_class, CxF3_main_path, [CxF3_sub_paths], regex, sort_order]
10578 # some mappings have no sub-paths, which is indicated by an empty sub_path array
10579 # sort_order array contains the last character(s) of the format keys, and is optional
10580 # the 'NCLR', 'SPECTRAL' and 'DENSITY' data classes are special cases
10581 $table = [
10582 ['RGB', "$ns:DeviceColorValues/$ns:ColorRGB", ["$ns:R", "$ns:G", "$ns:B"], qr/^(?:(.*)\|)?RGB_[RGB]$/, [qw(R G B)]],
10583 ['CMYK', "$ns:DeviceColorValues/$ns:ColorCMYK", ["$ns:Cyan", "$ns:Magenta", "$ns:Yellow", "$ns:Black"], qr/^(?:(.*)\|)?CMYK_[CMYK]$/, [qw(C M Y K)]],
10584 ['NCLR', "$ns:DeviceColorValues/$ns:ColorCMYKPlusN", ["$ns:Cyan", "$ns:Magenta", "$ns:Yellow", "$ns:Black"], qr/^(?:(.*)\|)?(?:[2-9A-F]CLR_[1-9A-F]|PC[2-9A-F]_[1-9A-F])$/],
10585 ['SPECTRAL', "$ns:ColorValues/$ns:ReflectanceSpectrum", [], qr/^(?:(.*)\|)?(?:nm|SPECTRAL_NM_|SPECTRAL_NM|SPECTRAL_|NM_|R_)\d{3}$/],
10586 ['DENSITY', "$ns:ColorValues/$ns:ColorDensity/$ns:Density", [], qr/^(?:(.*)\|)?D_(?:RED|GREEN|BLUE|VIS)$/, [qw(RED GREEN BLUE VIS)]],
10587 ['XYZ', "$ns:ColorValues/$ns:ColorCIEXYZ", ["$ns:X", "$ns:Y", "$ns:Z"], qr/^(?:(.*)\|)?XYZ_[XYZ]$/, [qw(X Y Z)]],
10588 ['XYY', "$ns:ColorValues/$ns:ColorCIExyY", ["$ns:x", "$ns:y", "$ns:Y"], qr/^(?:(.*)\|)?XYY_(?:X|Y|CAPY)$/, [qw(_X _Y _CAPY)]],
10589 ['LAB', "$ns:ColorValues/$ns:ColorCIELab", ["$ns:L", "$ns:A", "$ns:B"], qr/^(?:(.*)\|)?LAB_[LAB]$/, [qw(L A B)]],
10590 ['LCH', "$ns:ColorValues/$ns:ColorCIELCh", ["$ns:L", "$ns:C", "$ns:H"], qr/^(?:(.*)\|)?LAB_[LCH]$/, [qw(L C H)]],
10591 ['DE', "$ns:ColorDifferenceValues/$ns:DeltaCIELab/$ns:dE", [], qr/^(?:(.*)\|)?LAB_DE$/],
10592 ['DE94', "$ns:ColorDifferenceValues/$ns:DeltaCIELab/$ns:dE94", [], qr/^(?:(.*)\|)?LAB_DE94$/],
10593 ['DECMC', "$ns:ColorDifferenceValues/$ns:DeltaCIELab/$ns:dEcmc", [], qr/^(?:(.*)\|)?LAB_CMC$/],
10594 ['DE2000', "$ns:ColorDifferenceValues/$ns:DeltaCIELab/$ns:dE2000", [], qr/^(?:(.*)\|)?LAB_2000$/],
10595 ];
10596  
10597 # following section builds operations array from column slice
10598 #
10599 # sort keys alphabetically
10600 @{$cols} = sort {$self->[1][0][$a] cmp $self->[1][0][$b]} @{$cols};
10601  
10602 # for each field
10603 for my $i (@{$cols}) {
10604
10605 # if key matches current class and prefix (prefix could be undefined)
10606 if (defined($class) && $self->[1][0][$i] =~ /$table->[$class][3]/ && (defined($prefix) ? $prefix : "\n") eq (defined($1) ? $1 : "\n")) {
10607
10608 # add index to current operation
10609 push(@{$ops->[-1][4]}, $i);
10610
10611 } else {
10612
10613 # for each data class
10614 for my $j (0 .. $#{$table}) {
10615
10616 # if key matches class
10617 if ($self->[1][0][$i] =~ /$table->[$j][3]/) {
10618
10619 # save current prefix
10620 $prefix = $1;
10621
10622 # save current class
10623 $class = $j;
10624
10625 # add new operation
10626 push(@{$ops}, [$table->[$j][0], $prefix, $table->[$j][1], $table->[$j][2], [$i], {}, $j]);
10627
10628 # quit loop
10629 last;
10630
10631 # if no match found in table
10632 } elsif ($j == $#{$table}) {
10633
10634 # match prefix/key
10635 $self->[1][0][$i] =~ m/^(?:(.*)\|)?(.*)/;
10636
10637 # save matched values
10638 $prefix = $1;
10639 $key = $2;
10640
10641 # set current class
10642 $class = undef;
10643
10644 # if prefix defined, and not Target or ...Measurement, and key is SAMPLE_NAME
10645 if (defined($prefix) && $prefix !~ m/^Target$|Measurement$/ && $key =~ m/^SAMPLE_NAME$|^SampleName$/) {
10646
10647 # add special operation to set 'Object' 'Name' attribute to SAMPLE_NAME
10648 push(@{$ops}, ['TAG', $prefix, '', [], [], {'Name' => [$i]}, -1]);
10649
10650 } else {
10651
10652 # add Tag operation
10653 push(@{$ops}, ['TAG', $prefix, "$ns:TagCollection/$ns:Tag", [], [], {'Name' => $key, 'Value' => [$i]}, 100]);
10654
10655 }
10656
10657 }
10658
10659 }
10660
10661 }
10662
10663 }
10664  
10665 # following section sorts and verifies column slices, sets default prefixes and checks for multiple elements
10666 #
10667 # init loop variable
10668 %keys = ();
10669
10670 # for each array entry
10671 for my $t (@{$ops}) {
10672
10673 # if sort order is defined
10674 if (defined($table->[$t->[6]][4])) {
10675
10676 # arrange column indices in sort order
10677 @{$t->[4]} = map {my $end = $_; grep {$self->[1][0][$_] =~ m/$end$/} @{$t->[4]}} @{$table->[$t->[6]][4]};
10678
10679 }
10680
10681 # if class is SPECTRAL
10682 if ($t->[0] eq 'SPECTRAL') {
10683
10684 # verify spectral slice
10685 (@{$t->[4]} == @{_spectral($self, $t->[1])}) || warn("invalid column slice - SPECTRAL class");
10686
10687 # if class is DENSITY
10688 } elsif ($t->[0] eq 'DENSITY') {
10689
10690 # to be done
10691
10692 # if class is NCLR
10693 } elsif ($t->[0] eq 'NCLR') {
10694
10695 # match first key to get number of channels
10696 $self->[1][0][$t->[4][0]] =~ m/([2-9A-F])(?:CLR_|_)[1-9A-F]$/;
10697
10698 # verify nCLR slice
10699 (@{$t->[4]} == CORE::hex($1)) || warn("invalid column slice - NCLR class");
10700
10701 # all others
10702 } else {
10703
10704 # verify subpaths match column slice
10705 (@{$t->[4]} == @{$t->[3]} || (@{$t->[4]} == 1 && @{$t->[3]} == 0)) || warn("invalid column slice - $t->[0] class");
10706
10707 }
10708
10709 # if prefix undefined
10710 if (! defined($t->[1])) {
10711
10712 # if XPath contains 'ColorValues' or 'ColorDifferenceValues'
10713 if ($t->[2] =~ m/^$ns:(?:ColorValues|ColorDifferenceValues)\//) {
10714
10715 # set prefix to M0_Measurement
10716 $t->[1] = 'M0_Measurement';
10717
10718 # if XPath contains 'DeviceColorValues'
10719 } elsif ($t->[2] =~ m/^$ns:DeviceColorValues\//) {
10720
10721 # set prefix to Target
10722 $t->[1] = 'Target';
10723
10724 # all others
10725 } else {
10726
10727 # set prefix to '~~'
10728 $t->[1] = '~~';
10729
10730 }
10731
10732 }
10733
10734 # for 'ColorValues' or 'DeviceColorValues'
10735 if ($t->[2] =~ m/^$ns:(ColorValues|DeviceColorValues)\//) {
10736
10737 # warn on multiple elements (not allowed by i1Profiler)
10738 print "warning: multiple $1 elements in CxF3 $t->[1] object\n" if ($keys{"$1/$t->[1]"}++ == 1);
10739
10740 }
10741
10742 }
10743  
10744 # following section groups operations by prefix
10745 #
10746 # sort by prefix, then by table index
10747 @{$ops} = sort {($a->[1] cmp $b->[1]) or ($a->[6] <=> $b->[6])} @{$ops};
10748  
10749 # init loop variable
10750 $prefix = undef;
10751  
10752 # for each operation
10753 for my $t (@{$ops}) {
10754
10755 # if same prefix as last operation
10756 if (defined($prefix) && $prefix eq $t->[1]) {
10757
10758 # add operation to last group
10759 push(@{$groups->[-1]}, $t);
10760
10761 # if class is TAG and prefix is '~~'
10762 } elsif ($t->[0] eq 'TAG' && $t->[1] eq '~~') {
10763
10764 # for each group
10765 for my $g (@{$groups}) {
10766
10767 # add operation
10768 push(@{$g}, $t);
10769
10770 }
10771
10772 # set prefix
10773 $prefix = undef;
10774
10775 # others
10776 } else {
10777
10778 # add new group
10779 push(@{$groups}, [$t]);
10780
10781 # set prefix
10782 $prefix = $t->[1];
10783
10784 }
10785
10786 }
10787  
10788 # return
10789 return($groups);
10790  
10791 }
10792  
10793 # make CxF3 ColorSpecification nodes
10794 # parameters: (object_reference, CxF3_root, CxF3_prefix, CxF3_namespace_URI, operations_array)
10795 sub _makeCxF3colorspec {
10796  
10797 # get parameters
10798 my ($self, $root, $ns, $nsURI, $ops) = @_;
10799  
10800 # local variables
10801 my (@illum, @filter, $cscol, $template, $unknown);
10802 my (%table, %cspec, %hash, $keyword, $value, $source);
10803 my ($Id, $cs, @nodes, $node, $child, @wav);
10804 my ($parser, $frag, $std, $xpath);
10805  
10806 # illumination types
10807 @illum = qw(M0_Incandescent M1_Daylight M2_UVExcluded M3_Polarized);
10808  
10809 # filter types
10810 @filter = qw(Filter_None Filter_None Filter_UVExcluded Filter_None);
10811  
10812 # get the 'ColorSpecificationCollection' node
10813 ($cscol) = $root->findnodes("$ns:Resources/$ns:ColorSpecificationCollection");
10814  
10815 # get the 'ColorSpecification' node with Id = 'template'
10816 ($template) = $cscol->findnodes("$ns:ColorSpecification[\@Id='template']");
10817  
10818 # get the 'ColorSpecification' node with Id = 'Unknown'
10819 ($unknown) = $cscol->findnodes("$ns:ColorSpecification[\@Id='Unknown']");
10820  
10821 # make ASCII => CxF3 mapping table (from ISO 17972-1, Annex A)
10822 %table = (
10823 'MANUFACTURER' => "$ns:MeasurementSpec/$ns:Device/$ns:Manufacturer",
10824 'MODEL' => "$ns:MeasurementSpec/$ns:Device/$ns:Model",
10825 'SERIAL_NUMBER' => "$ns:MeasurementSpec/$ns:Device/$ns:SerialNumber",
10826 'MEASUREMENT_GEOMETRY' => "$ns:MeasurementSpec/$ns:GeometryChoice",
10827 'MEASUREMENT_SOURCE' => "$ns:MeasurementSpec/$ns:Device/$ns:DeviceIllumination",
10828 'FILTER' => "$ns:MeasurementSpec/$ns:Device/$ns:DeviceFilter",
10829 'POLARIZATION' => "$ns:MeasurementSpec/$ns:Device/$ns:DevicePolarization",
10830 'SAMPLE_BACKING' => "$ns:MeasurementSpec/$ns:Backing",
10831 'DEVCALSTD' => "$ns:MeasurementSpec/$ns:CalibrationStandard",
10832 );
10833  
10834 # for each group
10835 for my $group (@{$ops}) {
10836
10837 # for each operation
10838 for my $t (@{$group}) {
10839
10840 # if ColorValues (only ColorValues reference a ColorSpecification)
10841 if ($t->[2] =~ m/^$ns:ColorValues\//) {
10842
10843 # set Id to saved value, if defined, or add '_spec' to prefix
10844 # the ColorSpecification Id is saved in the Colorimetry array when reading a CxF3 file
10845 $Id = defined($self->[2][5][$t->[4][0]]) ? $self->[2][5][$t->[4][0]] : "$t->[1]\_spec";
10846
10847 # set attribute hash
10848 $t->[5]{'ColorSpecification'} = $Id;
10849
10850 # if 'ColorSpecification' undefined
10851 if (! $cspec{$Id}++) {
10852
10853 # initialize keyword hash
10854 %hash = ();
10855
10856 # add cloned 'ColorSpecification' element to 'ColorSpecificationCollection'
10857 $cs = $cscol->appendChild($template->cloneNode(1));
10858
10859 # set the Id
10860 $cs->setAttribute('Id', $Id);
10861
10862 # if spectral data
10863 # there are three types of spectral data, reflective, transmissive and emissive
10864 # spectral data has a WavelengthRange node which contains the starting wavelength and increment
10865 if ($t->[2] =~ m/(Reflectance|Transmittance|Emissive)Spectrum$/) {
10866
10867 # get the 'MeasurementType' node
10868 ($node) = $cs->findnodes("$ns:MeasurementSpec/$ns:MeasurementType");
10869
10870 # if text content exists
10871 if ((($child) = $node->nonBlankChildNodes) && $child->nodeType == 3) {
10872
10873 # update text content
10874 $child->setData("Spectrum_$1");
10875
10876 }
10877
10878 # for first two data columns
10879 for ($t->[4][0], $t->[4][1]) {
10880
10881 # match wavelength in format key
10882 $self->[1][0][$_] =~ m/(\d{3})$/;
10883
10884 # push to array
10885 push(@wav, $1);
10886
10887 }
10888
10889 # find the 'WavelengthRange' node
10890 ($node) = $cs->findnodes("$ns:MeasurementSpec/$ns:WavelengthRange");
10891
10892 # set the 'StartWL' attribute
10893 $node->setAttribute('StartWL', $wav[0]);
10894
10895 # set the 'Increment' attribute
10896 $node->setAttribute('Increment', $wav[1] - $wav[0]);
10897
10898 # set operation 'StartWL' attribute
10899 $t->[5]{'StartWL'} = $wav[0];
10900
10901 } else {
10902
10903 # find the 'WavelengthRange' node
10904 ($node) = $cs->findnodes("$ns:MeasurementSpec/$ns:WavelengthRange");
10905
10906 # unbind the node (used only with spectral data)
10907 $node->unbindNode();
10908
10909 }
10910
10911 # for each file header entry
10912 for (@{$self->[3]}) {
10913
10914 # get keyword, value and source
10915 ($keyword, $value, $source) = @{$_};
10916
10917 # strip quotes from value
10918 $value =~ s/^\"(.*)\"$/$1/;
10919
10920 # if source is ColorSpecification Id
10921 if (defined($source) && $source eq $Id) {
10922
10923 # add keyword to hash
10924 $hash{$keyword}++;
10925
10926 # if keyword in table
10927 if (exists($table{$keyword})) {
10928
10929 # if XPath does not exist in ColorSpecification element
10930 if (! (($node) = $cs->findnodes($table{$keyword}))) {
10931
10932 # set node
10933 $node = $cs;
10934
10935 # initialize XPath
10936 $xpath = undef;
10937
10938 # for each segment
10939 for (split(/\//, $table{$keyword})) {
10940
10941 # add segment to XPath
10942 $xpath = defined($xpath) ? "$xpath/$_" : $_;
10943
10944 # if XPath does not exist in ColorSpecification element
10945 if (! (($node) = $cs->findnodes($xpath))) {
10946
10947 # add element for XPath segment
10948 $node = $node->appendChild(XML::LibXML::Element->new($_));
10949 $node->setNamespace($nsURI, $ns);
10950
10951 }
10952
10953 }
10954
10955 }
10956
10957 # get the first non-blank child node
10958 ($child) = $node->nonBlankChildNodes();
10959
10960 # make a parser object
10961 $parser = XML::LibXML->new();
10962
10963 # if value is an XML balanced chunk
10964 if ($value =~ m/</ && eval{$frag = $parser->parse_balanced_chunk($value)}) {
10965
10966 # get all element nodes
10967 @nodes = $frag->findnodes('//*');
10968
10969 # replace existing node
10970 $node->replaceNode($frag);
10971
10972 # set namespace of each element
10973 for (@nodes) {$_->setNamespace($nsURI, $ns)};
10974
10975 # if no child node
10976 } elsif (! defined($child)) {
10977
10978 # set text content to value
10979 $node->appendText($value);
10980
10981 # if child node is text type
10982 } elsif ($child->nodeType == 3) {
10983
10984 # modify existing text content
10985 $child->setData($value);
10986
10987 }
10988
10989 }
10990
10991 }
10992
10993 }
10994
10995 # match illumination standard in prefix (M0, M1, M2, M3)
10996 $std = ($t->[1] =~ m/^M([0-3])/) ? $1 : 0;
10997
10998 # if 'MEASUREMENT_SOURCE' not a keyword
10999 if (! exists($hash{'MEASUREMENT_SOURCE'})) {
11000
11001 # find the 'DeviceIllumination' node
11002 ($node) = $cs->findnodes("$ns:MeasurementSpec/$ns:Device/$ns:DeviceIllumination");
11003
11004 # if text content exists
11005 if ((($child) = $node->nonBlankChildNodes) && $child->nodeType == 3) {
11006
11007 # update text content
11008 $child->setData($illum[$std]);
11009
11010 }
11011
11012 }
11013
11014 # if 'FILTER' not a keyword
11015 if (! exists($hash{'FILTER'})) {
11016
11017 # find the 'DeviceFilter' node
11018 ($node) = $cs->findnodes("$ns:MeasurementSpec/$ns:Device/$ns:DeviceFilter");
11019
11020 # if text content exists
11021 if ((($child) = $node->nonBlankChildNodes) && $child->nodeType == 3) {
11022
11023 # update text content
11024 $child->setData($filter[$std]);
11025
11026 }
11027
11028 }
11029
11030 # if 'POLARIZATION' not a keyword and M3 standard
11031 if (! exists($hash{'POLARIZATION'}) && $std == 3) {
11032
11033 # get the 'Device' node
11034 ($node) = $cs->findnodes("$ns:MeasurementSpec/$ns:Device");
11035
11036 # add 'Polarization' node
11037 $node = $node->appendChild(XML::LibXML::Element->new("$ns:Polarization"));
11038 $node->appendText(XML::LibXML::Boolean->True);
11039 $node->setNamespace($nsURI, $ns);
11040
11041 }
11042
11043 }
11044
11045 # if 'DeviceColorValues'
11046 } elsif ($t->[2] =~ m/^$ns:DeviceColorValues\//) {
11047
11048 # set attributes hash
11049 $t->[5]{'ColorSpecification'} = 'Unknown';
11050
11051 # increment 'ColorSpecification' hash
11052 $cspec{'Unknown'}++;
11053
11054 }
11055
11056 }
11057
11058 }
11059  
11060 # unbind 'template' node
11061 $template->unbindNode();
11062  
11063 # unbind 'Unknown' node, if not referenced
11064 $unknown->unbindNode() if (! $cspec{'Unknown'});
11065  
11066 }
11067  
11068 # validate CxF3 document
11069 # prints warning and error info
11070 # parameters: (document_reference)
11071 sub _validateCxF3 {
11072  
11073 # get document reference
11074 my $doc = shift();
11075  
11076 # load CxF3 schema
11077 state $xmlschema = XML::LibXML::Schema->new('location' => ICC::Shared::getICCPath('Templates/CxF3_Core.xsd'));
11078  
11079 # validate the document
11080 if (! defined(eval {$xmlschema->validate($doc)})) {
11081
11082 # print warning on failure
11083 print "warning: invalid CxF3 document\n$@\n";
11084
11085 }
11086
11087 }
11088  
11089 # make patch set
11090 # supported hash keys: 'colorspace', 'template', 'sort', 'limit'
11091 # parameters: (object_reference, hash)
11092 # returns: (result)
11093 sub _makePatchSet {
11094  
11095 # get parameters
11096 my ($self, $hash) = @_;
11097  
11098 # local variables
11099 my ($cs, $template, $sort, $tac, $n, $data, $eps);
11100 my (@fields, $loop, $limit, @inc, $init, $s, $code);
11101  
11102 # get the colorspace parameter
11103 (defined($cs = $hash->{'colorspace'})) || return('colorspace parameter missing');
11104  
11105 # get the template parameter
11106 (defined($template = $hash->{'template'})) || return('template parameter missing');
11107  
11108 # get the sort parameter (optional)
11109 $sort = $hash->{'sort'};
11110  
11111 # get the ink limit parameter (optional)
11112 $tac = $hash->{'limit'};
11113  
11114 # get number of elements in first group
11115 $n = @{$template->[0]};
11116  
11117 # for each group
11118 for my $i (0 .. $#{$template}) {
11119
11120 # verify number of elements
11121 ($n == @{$template->[$i]}) || return("wrong number of elements in template group $i");
11122
11123 # verify number of array references
11124 ($n == grep {ref() eq 'ARRAY'} @{$template->[$i]}) || return("non-array element(s) in template group $i");
11125
11126 # for each element
11127 for my $j (0 .. $#{$template->[$i]}) {
11128
11129 # verify element contains only numeric scalars
11130 (@{$template->[$i][$j]} > 0 && @{$template->[$i][$j]} == grep {! ref() && Scalar::Util::looks_like_number($_)} @{$template->[$i][$j]}) || return("non-numeric element in template group $i, $j");
11131
11132 }
11133
11134 }
11135  
11136 # if RGB colorspace
11137 if ($cs eq 'RGB') {
11138
11139 # verify number of channels
11140 ($n == 3) || return('wrong number of template elements for RGB colorspace');
11141
11142 # set fields
11143 @fields = qw(RGB_R RGB_G RGB_B);
11144
11145 # if CMYK colorspace
11146 } elsif ($cs eq 'CMYK') {
11147
11148 # verify number of channels
11149 ($n == 4) || return('wrong number of template elements for CMYK colorspace');
11150
11151 # set fields
11152 @fields = qw(CMYK_C CMYK_M CMYK_Y CMYK_K);
11153
11154 # if nCLR colorspace
11155 } elsif ($cs eq 'nCLR') {
11156
11157 # verify number of channels
11158 ($n > 0 && $n < 16) || return('wrong number of template elements for nCLR colorspace');
11159
11160 # set fields
11161 @fields = map {$n . "CLR_$_"} (1 .. $n);
11162
11163 # if L*a*b* colorspace
11164 } elsif ($cs eq 'Lab') {
11165
11166 # verify number of channels
11167 ($n == 3) || return('wrong number of template elements for L*a*b* colorspace');
11168
11169 # set fields
11170 @fields = qw(LAB_L LAB_A LAB_B);
11171
11172 } else {
11173
11174 # error
11175 return('invalid colorspace parameter');
11176
11177 }
11178  
11179 # make loop variable list
11180 $loop = join(', ', map {"\$i$_"} (0 .. $n - 1));
11181  
11182 # make initial code fragment
11183 $init = "\$data->[\$s++] = [$loop]";
11184  
11185 # initialize index
11186 $s = 0;
11187  
11188 # for each group
11189 for my $i (0 .. $#{$template}) {
11190
11191 # copy initial code fragment
11192 $code = $init;
11193
11194 # for each device channel (in reverse order)
11195 for my $j (reverse(0 .. $#{$template->[$i]})) {
11196
11197 # add loop code to fragment
11198 $code = "for my \$i$j (" . join(', ', @{$template->[$i][$j]}) . ") {$code}";
11199
11200 }
11201
11202 # evaluate code fragment
11203 eval($code);
11204
11205 }
11206  
11207 # if ink limit defined and color space is CMYK or nCLR
11208 if (defined($tac) && ($cs eq 'CMYK' || $cs eq 'nCLR')) {
11209
11210 # compute max comparison error
11211 $eps = 1E-12;
11212
11213 # verify ink limit is a number
11214 if (! ref($tac) && Scalar::Util::looks_like_number($tac)) {
11215
11216 # for each patch
11217 for (@{$data}) {
11218
11219 # add the total ink value
11220 push(@{$_}, List::Util::sum(@{$_}));
11221
11222 }
11223
11224 # make sort code fragment (sorts in ascending order by columns K ... total_ink_value)
11225 $code = '@{$data} = sort {' . join(' || ', map {"\$a->[$_] <=> \$b->[$_]"} (3 .. $n)) . '} @{$data}';
11226
11227 # sort data
11228 eval($code);
11229
11230 # for each patch
11231 for my $i (0 .. $#{$data}) {
11232
11233 # undefine limit if new group (different black or spot values)
11234 undef($limit) if (grep {$data->[$i][$_] != $data->[$i ? $i - 1 : 0][$_]} (3 .. $n - 1));
11235
11236 # select patch if limit undefined or total ink <= limit or a CMY corner point
11237 push(@inc, [@{$data->[$i]}[0 .. $n - 1]]) if (! defined($limit) || ($data->[$i][-1] - $limit <= $eps) || ((grep {$data->[$i][$_] == 0} (0 .. 2)) && (grep {$data->[$i][$_] == 100} (0 .. 2))));
11238
11239 # set limit if undefined and total ink > TAC
11240 $limit = $data->[$i][-1] if (! defined($limit) && $data->[$i][-1] - $tac > $eps);
11241
11242 }
11243
11244 # set data to selected patches
11245 $data = \@inc;
11246
11247 } else {
11248
11249 # display warning
11250 carp("invalid ink limit parameter, ink limiting failed\n");
11251
11252 }
11253
11254 }
11255  
11256 # if sort parameter defined
11257 if (defined($sort)) {
11258
11259 # verify sort parameter
11260 if (ICC::Shared::is_num_vector($sort) && @{$sort} == grep {$_ && $_ == int($_) && abs($_) <= @{$data->[0]}} @{$sort}) {
11261
11262 # make sort code fragment
11263 $code = '@{$data} = sort {' . join(' || ', map {my $dir = m/-/; my $col = abs($_) - 1; $dir ? "\$b->[$col] <=> \$a->[$col]" : "\$a->[$col] <=> \$b->[$col]"} @{$sort}) . '} @{$data}';
11264
11265 # evaluate code fragment
11266 eval($code);
11267
11268 } else {
11269
11270 # display warning
11271 carp("invalid sort parameter, sorting failed\n");
11272
11273 }
11274
11275 }
11276  
11277 # add format fields
11278 unshift(@{$data}, [@fields]);
11279  
11280 # set object reference
11281 $self->[1] = $data;
11282  
11283 # return
11284 return();
11285  
11286 }
11287  
11288 # make Time::Piece object from text string
11289 # parses most common date/time notations
11290 # no object returned if parsing fails
11291 # parameter: (string -or- value)
11292 # returns: (object)
11293 sub _makeTimePiece {
11294  
11295 # get parameter
11296 my $str = shift();
11297  
11298 # local variables
11299 my ($parse, $fmt, $hr, $sec, $month);
11300  
11301 # if a numeric value (Unix time)
11302 if (Scalar::Util::looks_like_number($str)) {
11303
11304 # return Time::Piece object from Unix time
11305 return(scalar(localtime($str)));
11306
11307 } else {
11308
11309 # if UTC offset matched (time string ends in '+/-hh:mm', '+/-hhmm', or '+/-hh')
11310 if ($str =~ s/(T[\d:]+)([+-]\d{2}):?(\d{2})?/$1/) {
11311
11312 # set UTC offset to matched value
11313 $parse = $2 . (defined($3) ? $3 : '00');
11314
11315 # set UTC format
11316 $fmt = '%z';
11317
11318 # if Zulu time (time string ends in 'Z')
11319 } elsif ($str =~ s/(T[\d:]+)Z/$1/) {
11320
11321 # set UTC offset to 0
11322 $parse = '+0000';
11323
11324 # set UTC format
11325 $fmt = '%z';
11326
11327 } else {
11328
11329 # initialize strings
11330 $parse = $fmt = '';
11331
11332 }
11333
11334 # if time matched (time string 'hh:mm' or 'hh:mm:ss', 'AM' or 'PM' optional)
11335 if ($str =~ s/(\d{1,2})(:\d{1,2})(:\d{1,2})?\s*(AM|PM)?//) {
11336
11337 # if 12 AM
11338 if (defined($4) && $4 eq 'AM' && $1 == 12) {
11339
11340 # set hour
11341 $hr = 0;
11342
11343 # if 1 PM - 11 PM
11344 } elsif (defined($4) && $4 eq 'PM' && $1 > 0 && $1 < 12) {
11345
11346 # set hour
11347 $hr = $1 + 12;
11348
11349 } else {
11350
11351 # set hour
11352 $hr = $1;
11353
11354 }
11355
11356 # set seconds
11357 $sec = defined($3) ? $3 : ':00';
11358
11359 # add time string
11360 $parse = "T$hr$2$sec$parse";
11361
11362 # add time format
11363 $fmt = "T%T$fmt";
11364
11365 }
11366
11367 # if three number date matched
11368 if ($str =~ m/(\d{1,4})[\/-](\d{1,2})[\/-](\d{1,4})/) {
11369
11370 # if first value > 99
11371 if ($1 > 99) {
11372
11373 # add date string
11374 $parse = "$1-$2-$3$parse";
11375
11376 # if last value > 99
11377 } elsif ($3 > 99) {
11378
11379 # add date string
11380 $parse = "$3-$1-$2$parse";
11381
11382 # last value is two digit year
11383 } else {
11384
11385 # add date string
11386 $parse = ($3 > 68 ? 1900 + $3 : 2000 + $3) . "-$1-$2$parse";
11387
11388 }
11389
11390 # add date format
11391 $fmt = "%Y-%m-%d$fmt";
11392
11393 # if text month matched
11394 } elsif (uc($str) =~ m/(JAN|FEB|MAR|APR|MAY|JUN|JUL|AUG|SEP|OCT|NOV|DEC)/) {
11395
11396 # save month
11397 $month = $1;
11398
11399 # if two numbers matched
11400 if ($str =~ m/(\d{1,4})[^\d]+(\d{1,4})/) {
11401
11402 # if first value > 99
11403 if ($1 > 99) {
11404
11405 # add date string
11406 $parse = "$1-$month-$2$parse";
11407
11408 # if last value > 99
11409 } elsif ($2 > 99) {
11410
11411 # add date string
11412 $parse = "$2-$month-$1$parse";
11413
11414 # last value is two digit year
11415 } else {
11416
11417 # add date string
11418 $parse = ($2 > 68 ? 1900 + $2 : 2000 + $2) . "/$month/$1$parse";
11419
11420 }
11421
11422 # if one number matched
11423 } elsif ($str =~ m/(\d{1,4})/) {
11424
11425 # if value > 99
11426 if ($1 > 99) {
11427
11428 # add date string
11429 $parse = "$1-$month-1$parse";
11430
11431 } else {
11432
11433 # add date string
11434 $parse = ($1 > 68 ? 1900 + $1 : 2000 + $1) . "/$month/1$parse";
11435
11436 }
11437
11438 }
11439
11440 # add date format
11441 $fmt = "%Y-%b-%d$fmt";
11442
11443 }
11444
11445 # return Time::Piece object, if string parsed successfully
11446 return(Time::Piece->strptime($parse, $fmt)) if (length($parse));
11447
11448 }
11449
11450 }
11451  
11452 # get file list
11453 # uses Perl 'bsd_glob' function
11454 # parameter: (path)
11455 # returns: (ref_to_file_list)
11456 sub _files {
11457  
11458 # get path
11459 my $path = shift();
11460  
11461 # replace '~~' with 'ICC' directory path
11462 $path =~ s/^~~(?{ICC::Shared::getICCPath})/$^R/;
11463  
11464 # get list of files and/or directories
11465 my @files = File::Glob::bsd_glob($path);
11466  
11467 # if list is just one directory
11468 if (@files == 1 && -d $files[0]) {
11469
11470 # get files in that directory
11471 @files = grep {-f} File::Glob::bsd_glob("$path/*");
11472
11473 } else {
11474
11475 # filter the files
11476 @files = grep {-f} @files;
11477
11478 }
11479  
11480 # return file list
11481 return(\@files);
11482  
11483 }
11484  
11485 # compute Mahalanobis distance
11486 # assumes parameters are valid
11487 # parameters: (vector1, vector2, inverse_covariance_matrix)
11488 # returns: (distance)
11489 sub _mahal {
11490  
11491 # get parameters
11492 my ($x, $y, $sinv) = @_;
11493  
11494 # local variables
11495 my ($d, $dT);
11496  
11497 # for each dimension
11498 for my $i (0 .. $#{$x}) {
11499
11500 # save difference
11501 $d->[0][$i] = $dT->[$i][0] = $x->[$i] - $y->[$i];
11502
11503 }
11504  
11505 # bless matrices
11506 bless($d, 'Math::Matrix');
11507 bless($dT, 'Math::Matrix');
11508  
11509 # return Mahalanobis distance
11510 return(sqrt(($d * $sinv * $dT)->[0][0]));
11511  
11512 }
11513  
11514 # get L*a*b* encoding code refs
11515 # parameter: (object_reference, hash)
11516 # returns: (get_code_ref, set_code_ref)
11517 sub _lab_encoding {
11518  
11519 # get object reference
11520 my ($self, $hash) = @_;
11521  
11522 # local variable
11523 my ($encode);
11524  
11525 # get encoding parameter from hash
11526 $encode = $hash->{'encoding'};
11527  
11528 # if encoding parameter undefined
11529 if (! defined($encode)) {
11530
11531 # return code refs (identity)
11532 return(sub {@_}, sub {@_});
11533
11534 # if encoding is 8/16-bit ICC CIELAB
11535 } elsif ($encode == 0) {
11536
11537 # return code refs
11538 return(sub {defined($_[0]) ? $_[0] / 100 : $_[0], defined($_[1]) ? ($_[1] + 128)/255 : $_[1], defined($_[2]) ? ($_[2] + 128)/255 : $_[2]},
11539 sub {defined($_[0]) ? $_[0] * 100 : $_[0], defined($_[1]) ? $_[1] * 255 - 128 : $_[1], defined($_[2]) ? $_[2] * 255 - 128 : $_[2]});
11540
11541 # if encoding is 16-bit ICC legacy L*a*b*
11542 } elsif ($encode == 1) {
11543
11544 # return code refs
11545 return(sub {defined($_[0]) ? $_[0] * 256/25700 : $_[0], defined($_[1]) ? ($_[1] + 128) * 256/65535 : $_[1], defined($_[2]) ? ($_[2] + 128) * 256/65535 : $_[2]},
11546 sub {defined($_[0]) ? $_[0] * 25700/256 : $_[0], defined($_[1]) ? $_[1] * 65535/256 - 128 : $_[1], defined($_[2]) ? $_[2] * 65535/256 - 128 : $_[2]});
11547
11548 # if encoding is 16-bit EFI/Monaco L*a*b*
11549 } elsif ($encode == 2) {
11550
11551 # return code refs
11552 return(sub {defined($_[0]) ? $_[0]/100 : $_[0], defined($_[1]) ? ($_[1] + 128) * 256/65535 : $_[1], defined($_[2]) ? ($_[2] + 128) * 256/65535 : $_[2]},
11553 sub {defined($_[0]) ? $_[0] * 100 : $_[0], defined($_[1]) ? $_[1] * 65535/256 - 128 : $_[1], defined($_[2]) ? $_[2] * 65535/256 - 128 : $_[2]});
11554
11555 # if encoding is L*a*b*
11556 } elsif ($encode == 3) {
11557
11558 # return code refs (identity)
11559 return(sub {@_}, sub {@_});
11560
11561 # if encoding is LxLyLz
11562 } elsif ($encode == 4) {
11563
11564 # return code refs
11565 return(sub {if (defined($_[0]) && defined($_[1]) && defined($_[2])) {$_[0] + 116 * $_[1]/500, $_[0], $_[0] - 116 * $_[2]/200} else {@_}},
11566 sub {if (defined($_[0]) && defined($_[1]) && defined($_[2])) {$_[1], 500 * ($_[0] - $_[1])/116, 200 * ($_[1] - $_[2])/116} else {@_}});
11567
11568 # if encoding is unit LxLyLz
11569 } elsif ($encode == 5) {
11570
11571 # return code refs
11572 return(sub {if (defined($_[0]) && defined($_[1]) && defined($_[2])) {map {$_/100} ($_[0] + 116 * $_[1]/500, $_[0], $_[0] - 116 * $_[2]/200)} else {@_}},
11573 sub {if (defined($_[0]) && defined($_[1]) && defined($_[2])) {map {$_ * 100} ($_[1], 500 * ($_[0] - $_[1])/116, 200 * ($_[1] - $_[2])/116)} else {@_}});
11574
11575 } else {
11576
11577 # error
11578 croak('invalid L*a*b* encoding');
11579
11580 }
11581  
11582 }
11583  
11584 # get XYZ encoding code refs
11585 # assumes there are XYZ columns
11586 # parameter: (object_reference, column_slice, [hash])
11587 # returns: (get_code_ref, set_code_ref)
11588 sub _xyz_encoding {
11589  
11590 # get object reference
11591 my ($self, $cols, $hash) = @_;
11592  
11593 # local variable
11594 my ($encode, $wtpt);
11595  
11596 # get encoding parameter from hash
11597 $encode = $hash->{'encoding'};
11598  
11599 # if encoding parameter undefined
11600 if (! defined($encode)) {
11601
11602 # return code refs (identity)
11603 return(sub {@_}, sub {@_});
11604
11605 # if encoding is L*
11606 } elsif ($encode eq 'L*' || $encode == 4) {
11607
11608 # get illuminant white point
11609 ($wtpt = _illumWP($self, $cols, $hash)) || croak('illuminant white point required for LxLyLz encoding');
11610
11611 # return code refs
11612 return(sub {defined($_[0]) ? ICC::Shared::x2L($_[0] / $wtpt->[0]) : $_[0], defined($_[1]) ? ICC::Shared::x2L($_[1] / $wtpt->[1]) : $_[1], defined($_[2]) ? ICC::Shared::x2L($_[2] / $wtpt->[2]) : $_[2]},
11613 sub {defined($_[0]) ? ICC::Shared::L2x($_[0]) * $wtpt->[0] : $_[0], defined($_[1]) ? ICC::Shared::L2x($_[1]) * $wtpt->[1] : $_[1], defined($_[2]) ? ICC::Shared::L2x($_[2]) * $wtpt->[2] : $_[2]});
11614
11615 # if encoding is 16-bit ICC XYZ
11616 } elsif ($encode == 7) {
11617
11618 # return code refs
11619 return(sub {map {defined() ? $_ / 199.9969482421875 : $_} @_}, sub {map {defined() ? $_ * 199.9969482421875 : $_} @_});
11620
11621 # if encoding is 32-bit ICC XYZNumber
11622 } elsif ($encode == 8) {
11623
11624 # return code refs
11625 return(sub {map {defined() ? $_ / 100 : $_} @_}, sub {map {defined() ? $_ * 100 : $_} @_});
11626
11627 # if encoding is xyz
11628 } elsif ($encode == 9) {
11629
11630 # get illuminant white point
11631 ($wtpt = _illumWP($self, $cols, $hash)) || croak('illuminant white point required for xyz encoding');
11632
11633 # return code refs
11634 return(sub {defined($_[0]) ? $_[0] / $wtpt->[0] : $_[0], defined($_[1]) ? $_[1] / $wtpt->[1] : $_[1], defined($_[2]) ? $_[2] / $wtpt->[2] : $_[2]},
11635 sub {defined($_[0]) ? $_[0] * $wtpt->[0] : $_[0], defined($_[1]) ? $_[1] * $wtpt->[1] : $_[1], defined($_[2]) ? $_[2] * $wtpt->[2] : $_[2]});
11636
11637 # if encoding is XYZ
11638 } elsif ($encode == 10) {
11639
11640 # return code refs (identity)
11641 return(sub {@_}, sub {@_});
11642
11643 # if encoding is media relative xyz
11644 } elsif ($encode == 11) {
11645
11646 # get media white point
11647 ($wtpt = _mediaWP($self, $cols, $hash)) || croak('media white point required for media relative xyz encoding');
11648
11649 # return code refs
11650 return(sub {defined($_[0]) ? $_[0] / $wtpt->[0] : $_[0], defined($_[1]) ? $_[1] / $wtpt->[1] : $_[1], defined($_[2]) ? $_[2] / $wtpt->[2] : $_[2]},
11651 sub {defined($_[0]) ? $_[0] * $wtpt->[0] : $_[0], defined($_[1]) ? $_[1] * $wtpt->[1] : $_[1], defined($_[2]) ? $_[2] * $wtpt->[2] : $_[2]});
11652
11653 } else {
11654
11655 # error
11656 croak('invalid XYZ encoding');
11657
11658 }
11659  
11660 }
11661  
11662 # get density encoding code refs
11663 # parameter: (object_reference, hash)
11664 # returns: (get_code_ref, set_code_ref)
11665 sub _density_encoding {
11666  
11667 # get object reference
11668 my ($self, $hash) = @_;
11669  
11670 # get encoding parameter from hash
11671 my $encode = $hash->{'encoding'};
11672  
11673 # if encoding parameter undefined or density
11674 if (! defined($encode) || $encode eq 'density') {
11675
11676 # return code refs (identity)
11677 return(sub {@_}, sub {@_});
11678
11679 # if encoding is linear (RGBV)
11680 } elsif ($encode eq 'linear') {
11681
11682 # return code refs
11683 return(sub {map {defined() ? 100 * POSIX::pow(10, -$_) : $_} @_}, sub {map {if (defined()) {if ($_ > 0) {-POSIX::log10($_/100)} else {warn("log of $_"); 99}} else {$_}} @_});
11684
11685 # if encoding is unit
11686 } elsif ($encode eq 'unit') {
11687
11688 # return code refs
11689 return(sub {map {defined() ? POSIX::pow(10, -$_) : $_} @_}, sub {map {if (defined()) {if ($_ > 0) {-POSIX::log10($_)} else {warn("log of $_"); 99}} else {$_}} @_});
11690
11691 # if encoding is L*
11692 } elsif ($encode eq 'L*') {
11693
11694 # return code refs
11695 return(sub {map {defined() ? ICC::Shared::x2L(POSIX::pow(10, -$_)) : $_} @_}, sub {map {if (defined()) {if ($_ > 0) {-POSIX::log10(ICC::Shared::L2x($_))} else {warn("log of $_"); 99}} else {$_}} @_});
11696
11697 } else {
11698
11699 # error
11700 croak('invalid density encoding');
11701
11702 }
11703  
11704 }
11705  
11706 # get rgbv encoding code refs
11707 # parameter: (object_reference, hash)
11708 # returns: (get_code_ref, set_code_ref)
11709 sub _rgbv_encoding {
11710  
11711 # get object reference
11712 my ($self, $hash) = @_;
11713  
11714 # get encoding parameter from hash
11715 my $encode = $hash->{'encoding'};
11716  
11717 # if encoding parameter undefined or linear
11718 if (! defined($encode) || $encode eq 'linear'|| $encode eq 'RGBV') {
11719
11720 # return code refs (identity)
11721 return(sub {@_}, sub {@_});
11722
11723 # if encoding is unit
11724 } elsif ($encode eq 'unit') {
11725
11726 # return code refs
11727 return(sub {map {$_/100} @_}, sub {map {$_ * 100} @_});
11728
11729 # if encoding is density
11730 } elsif ($encode eq 'density') {
11731
11732 # return code refs
11733 return(sub {map {if (defined()) {if ($_ > 0) {-POSIX::log10($_/100)} else {warn("log of $_"); 99}} else {$_}} @_}, sub {map {defined() ? 100 * POSIX::pow(10, -$_) : $_} @_});
11734
11735 # if encoding is L*
11736 } elsif ($encode eq 'L*') {
11737
11738 # return code refs
11739 return(sub {map {ICC::Shared::x2L($_/100)} @_}, sub {map {ICC::Shared::L2x($_) * 100} @_});
11740
11741 } else {
11742
11743 # error
11744 croak('invalid rgbv encoding');
11745
11746 }
11747  
11748 }
11749  
11750 #--------- additional Math::Matrix methods ---------
11751  
11752 package Math::Matrix;
11753  
11754 # rotate matrix
11755 # rotation: 0 = None, 1 = 90° CW, 2 = 180°, 3 = 90° CCW
11756 # note: rotation describes appearance in MeasureTool
11757 # parameter: (rotation)
11758 # returns: (rotated_matrix)
11759 sub rotate {
11760  
11761 # get parameters
11762 my ($self, $rot) = @_;
11763  
11764 # local variables
11765 my ($rows, $cols, $replace);
11766  
11767 # return if rotation undefined
11768 return($self) if (! defined($rot));
11769  
11770 # resolve rotation parameter
11771 $rot = int($rot) % 4;
11772  
11773 # get upper row index
11774 $rows = $#{$self};
11775  
11776 # get upper column index
11777 $cols = $#{$self->[0]};
11778  
11779 # if rotation = 0 (none)
11780 if ($rot == 0) {
11781
11782 # for each row
11783 for my $i (0 .. $rows) {
11784
11785 # for each column
11786 for my $j (0 .. $cols) {
11787
11788 # copy matrix element
11789 $replace->[$i][$j] = $self->[$i][$j];
11790
11791 }
11792
11793 }
11794
11795 # if rotation = 1 (90° CW)
11796 } elsif ($rot == 1) {
11797
11798 # for each row
11799 for my $i (0 .. $rows) {
11800
11801 # for each column
11802 for my $j (0 .. $cols) {
11803
11804 # copy matrix element
11805 $replace->[$j][$i] = $self->[$i][$cols - $j];
11806
11807 }
11808
11809 }
11810
11811 # if rotation = 2 (180°)
11812 } elsif ($rot == 2) {
11813
11814 # for each row
11815 for my $i (0 .. $rows) {
11816
11817 # for each column
11818 for my $j (0 .. $cols) {
11819
11820 # copy matrix element
11821 $replace->[$i][$j] = $self->[$rows - $i][$cols - $j];
11822
11823 }
11824
11825 }
11826
11827 # if rotation = 3 (90° CCW)
11828 } elsif ($rot == 3) {
11829
11830 # for each row
11831 for my $i (0 .. $rows) {
11832
11833 # for each column
11834 for my $j (0 .. $cols) {
11835
11836 # copy matrix element
11837 $replace->[$j][$i] = $self->[$rows - $i][$j];
11838
11839 }
11840
11841 }
11842
11843 }
11844  
11845 # return new object
11846 return(bless($replace, 'Math::Matrix'));
11847  
11848 }
11849  
11850 # flip matrix
11851 # flip: 0 = transpose, 1 = horizontal, 2 = cross transpose, 3 = vertical
11852 # note: flip describes appearance in MeasureTool
11853 # parameter: (flip)
11854 # returns: (flipped_matrix)
11855 sub flip {
11856  
11857 # get parameters
11858 my ($self, $flip) = @_;
11859  
11860 # local variables
11861 my ($rows, $cols, $replace);
11862  
11863 # return if flip undefined
11864 return($self) if (! defined($flip));
11865  
11866 # resolve flip parameter
11867 $flip = int($flip) % 4;
11868  
11869 # get upper row index
11870 $rows = $#{$self};
11871  
11872 # get upper column index
11873 $cols = $#{$self->[0]};
11874  
11875 # if flip = 0 (transpose)
11876 if ($flip == 0) {
11877
11878 # for each row
11879 for my $i (0 .. $rows) {
11880
11881 # for each column
11882 for my $j (0 .. $cols) {
11883
11884 # copy matrix element
11885 $replace->[$j][$i] = $self->[$i][$j];
11886
11887 }
11888
11889 }
11890
11891 # if flip = 1 (horizontal)
11892 } elsif ($flip == 1) {
11893
11894 # for each row
11895 for my $i (0 .. $rows) {
11896
11897 # for each column
11898 for my $j (0 .. $cols) {
11899
11900 # copy matrix element
11901 $replace->[$i][$j] = $self->[$rows - $i][$j];
11902
11903 }
11904
11905 }
11906
11907 # if flip = 2 (cross transpose)
11908 } elsif ($flip == 2) {
11909
11910 # for each row
11911 for my $i (0 .. $rows) {
11912
11913 # for each column
11914 for my $j (0 .. $cols) {
11915
11916 # copy matrix element
11917 $replace->[$j][$i] = $self->[$rows - $i][$cols - $j];
11918
11919 }
11920
11921 }
11922
11923 # if flip = 3 (vertical)
11924 } elsif ($flip == 3) {
11925
11926 # for each row
11927 for my $i (0 .. $rows) {
11928
11929 # for each column
11930 for my $j (0 .. $cols) {
11931
11932 # copy matrix element
11933 $replace->[$i][$j] = $self->[$i][$cols - $j];
11934
11935 }
11936
11937 }
11938
11939 }
11940  
11941 # return new object
11942 return(bless($replace, 'Math::Matrix'));
11943  
11944 }
11945  
11946 # randomize matrix
11947 # returns: (randomized_matrix)
11948 sub randomize {
11949  
11950 # get object reference
11951 my $self = shift();
11952  
11953 # local variables
11954 my (@ix, $rows, $cols, $replace);
11955  
11956 # flatten and randomize matrix
11957 @ix = List::Util::shuffle(@{ICC::Shared::flatten($self)});
11958  
11959 # get upper row index
11960 $rows = $#{$self};
11961  
11962 # get upper column index
11963 $cols = $#{$self->[0]};
11964  
11965 # for each row
11966 for my $i (0 .. $rows) {
11967
11968 # for each column
11969 for my $j (0 .. $cols) {
11970
11971 # set element
11972 $replace->[$i][$j] = $ix[$i * ($cols + 1) + $j];
11973
11974 }
11975
11976 }
11977  
11978 # return new object
11979 return(bless($replace, 'Math::Matrix'));
11980  
11981 }
11982  
11983 1;
11984