blib/lib/Math/Histo/PDL.pm untested

filter: Statementstmt 0.0% 0 / 328 Branchbran 0.0% 0 / 136 Conditioncond 0.0% 0 / 94 MC/DCmcdc n/a Subroutinesub 0.0% 0 / 28 Podpod 0.0% 0 / 19 totaltotal 0.0% 0 / 605 CC 69 SCAR 51.0
CC
69
Cov
0%
hist2d
506.0
hist1d
182.0
fill2d_pdl
132.0
CRAP 163.6
1 package Math::Histo::PDL;
2  
3 use strict;
4 use warnings;
5 use 5.010;
6  
7 our $VERSION = '0.4.0';
8  
9 use Math::Histo 0.4.0;
10 use Math::Histo::2D;
11 use PDL 2.000 ();
12 use Carp qw(croak);
13 use Exporter 'import';
14  
15 our @EXPORT_OK = qw(
16 hist1d
17 hist2d
18 fill_pdl
19 fill2d_pdl
20 to_pdl
21 to_pdl2d
22 pdl_to_histo
23 histo_to_pdl
24 counts_pdl
25 edges_pdl
26 centers_pdl
27 errors_pdl
28 matrix_pdl
29 x_edges_pdl
30 y_edges_pdl
31 x_centers_pdl
32 y_centers_pdl
33 );
34  
35 our %EXPORT_TAGS = (
36 all => \@EXPORT_OK,
37 );
38  
39 # Internal helper: extract packed byte buffer from a PDL object for zero-copy ingestion
40 sub _ensure_packed_double {
41 my ($pdl) = @_;
42 if (!eval { $pdl->isa('PDL') }) {
43 if (ref($pdl) eq 'ARRAY') {
44 $pdl = PDL::pdl(PDL::double(), $pdl);
45 } else {
46 croak "Math::Histo::PDL: input must be a PDL piddle or arrayref";
47 }
48 }
49 return ('', 0) if $pdl->isempty || $pdl->nelem == 0;
50  
51 my $d = ($pdl->type eq 'double') ? $pdl : $pdl->double;
52 $d = $d->flat unless $d->ndims == 1;
53 $d = $d->make_physical;
54 my $dataref = $d->get_dataref;
55 return ($$dataref, $d->nelem);
56 }
57  
58 # 1D Ingestion
59 sub fill_pdl {
60 my ($self, $data, $weights) = @_;
61 croak "Math::Histo::PDL: first argument must be a Math::Histo object"
62 unless eval { $self->isa('Math::Histo') };
63 croak "Math::Histo::PDL: data piddle is required" unless defined $data;
64  
65 my ($x_bytes, $n_x) = _ensure_packed_double($data);
66 return $self if $n_x == 0;
67  
68 if (defined $weights) {
69 my ($w_bytes, $n_w) = _ensure_packed_double($weights);
70 if ($n_w != $n_x) {
71 croak "Math::Histo::PDL::fill_pdl: weights length ($n_w) must match data length ($n_x)";
72 }
73 $self->fill_packed_f64($x_bytes, $w_bytes);
74 } else {
75 $self->fill_packed_f64($x_bytes);
76 }
77 return $self;
78 }
79  
80 # 2D Ingestion
81 sub fill2d_pdl {
82 my ($self, @args) = @_;
83 croak "Math::Histo::PDL: first argument must be a Math::Histo::2D object"
84 unless eval { $self->isa('Math::Histo::2D') };
85  
86 my ($x_pdl, $y_pdl, $weights);
87  
88 if (@args == 1 || (@args == 2 && eval { $args[0]->isa('PDL') } && $args[0]->ndims == 2)) {
89 # Single 2D coordinate matrix: (2, N) or (N, 2), plus optional weights
90 my $coords = $args[0];
91 $weights = $args[1] if @args == 2;
92  
93 if ($coords->dim(0) == 2) {
94 $x_pdl = $coords->slice('(0),:')->flat;
95 $y_pdl = $coords->slice('(1),:')->flat;
96 } elsif ($coords->dim(1) == 2) {
97 $x_pdl = $coords->slice(',(0)')->flat;
98 $y_pdl = $coords->slice(',(1)')->flat;
99 } else {
100 croak "Math::Histo::PDL::fill2d_pdl: coordinate matrix must have dimension 2 along axis 0 or 1 (got " . join('x', $coords->dims) . ")";
101 }
102 } elsif (@args == 2 || @args == 3) {
103 ($x_pdl, $y_pdl, $weights) = @args;
104 } else {
105 croak "Math::Histo::PDL::fill2d_pdl: invalid arguments (expected (\$h2d, \$x, \$y, [\$weights]) or (\$h2d, \$coords, [\$weights]))";
106 }
107  
108 my ($x_bytes, $n_x) = _ensure_packed_double($x_pdl);
109 my ($y_bytes, $n_y) = _ensure_packed_double($y_pdl);
110  
111 if ($n_x != $n_y) {
112 croak "Math::Histo::PDL::fill2d_pdl: X length ($n_x) and Y length ($n_y) must match";
113 }
114 return $self if $n_x == 0;
115  
116 if (defined $weights) {
117 my ($w_bytes, $n_w) = _ensure_packed_double($weights);
118 if ($n_w != $n_x) {
119 croak "Math::Histo::PDL::fill2d_pdl: weights length ($n_w) must match data length ($n_x)";
120 }
121 $self->fill_packed_f64($x_bytes, $y_bytes, $w_bytes);
122 } else {
123 $self->fill_packed_f64($x_bytes, $y_bytes);
124 }
125 return $self;
126 }
127  
128 # 1D Export to PDL
129 sub counts_pdl {
130 my ($self) = @_;
131 croak "Math::Histo::PDL: argument must be a Math::Histo object"
132 unless eval { $self->isa('Math::Histo') };
133 my $contents = $self->bin_contents;
134 my $packed = pack('d*', @$contents);
135 my $p = PDL->new_from_specification(PDL::double(), scalar(@$contents));
136 ${$p->get_dataref} = $packed;
137 $p->upd_data;
138 return $p;
139 }
140  
141 sub edges_pdl {
142 my ($self) = @_;
143 croak "Math::Histo::PDL: argument must be a Math::Histo object"
144 unless eval { $self->isa('Math::Histo') };
145 my $edges = $self->bin_edges;
146 my $packed = pack('d*', @$edges);
147 my $p = PDL->new_from_specification(PDL::double(), scalar(@$edges));
148 ${$p->get_dataref} = $packed;
149 $p->upd_data;
150 return $p;
151 }
152  
153 sub centers_pdl {
154 my ($self) = @_;
155 my $edges = edges_pdl($self);
156 return ($edges->slice('0:-2') + $edges->slice('1:-1')) / 2.0;
157 }
158  
159 sub errors_pdl {
160 my ($self) = @_;
161 croak "Math::Histo::PDL: argument must be a Math::Histo object"
162 unless eval { $self->isa('Math::Histo') };
163 my $n = $self->nbins;
164 my @errors = map { $self->bin_error($_) // 0.0 } 0 .. $n - 1;
165 my $packed = pack('d*', @errors);
166 my $p = PDL->new_from_specification(PDL::double(), $n);
167 ${$p->get_dataref} = $packed;
168 $p->upd_data;
169 return $p;
170 }
171  
172 sub to_pdl {
173 my ($self, %opts) = @_;
174 if (wantarray && !%opts) {
175 return (counts_pdl($self), edges_pdl($self), errors_pdl($self));
176 }
177 if ($opts{all}) {
178 return {
179 counts => counts_pdl($self),
180 edges => edges_pdl($self),
181 centers => centers_pdl($self),
182 errors => errors_pdl($self),
183 };
184 }
185 return counts_pdl($self);
186 }
187  
188 # 2D Export to PDL
189 sub matrix_pdl {
190 my ($self) = @_;
191 croak "Math::Histo::PDL: argument must be a Math::Histo::2D object"
192 unless eval { $self->isa('Math::Histo::2D') };
193 my $nx = $self->nx;
194 my $ny = $self->ny;
195 my $packed = '';
196 for my $iy (0 .. $ny - 1) {
197 for my $ix (0 .. $nx - 1) {
198 $packed .= pack('d', $self->bin_content($ix, $iy));
199 }
200 }
201 my $p = PDL->new_from_specification(PDL::double(), $nx, $ny);
202 ${$p->get_dataref} = $packed;
203 $p->upd_data;
204 return $p;
205 }
206  
207 sub x_edges_pdl {
208 my ($self) = @_;
209 croak "Math::Histo::PDL: argument must be a Math::Histo::2D object"
210 unless eval { $self->isa('Math::Histo::2D') };
211 my $nx = $self->nx;
212 my @edges;
213 for my $ix (0 .. $nx - 1) {
214 my ($x0, $x1) = $self->bin_bounds($ix, 0);
215 push @edges, $x0;
216 push @edges, $x1 if $ix == $nx - 1;
217 }
218 my $packed = pack('d*', @edges);
219 my $p = PDL->new_from_specification(PDL::double(), scalar(@edges));
220 ${$p->get_dataref} = $packed;
221 $p->upd_data;
222 return $p;
223 }
224  
225 sub y_edges_pdl {
226 my ($self) = @_;
227 croak "Math::Histo::PDL: argument must be a Math::Histo::2D object"
228 unless eval { $self->isa('Math::Histo::2D') };
229 my $ny = $self->ny;
230 my @edges;
231 for my $iy (0 .. $ny - 1) {
232 my (undef, undef, $y0, $y1) = $self->bin_bounds(0, $iy);
233 push @edges, $y0;
234 push @edges, $y1 if $iy == $ny - 1;
235 }
236 my $packed = pack('d*', @edges);
237 my $p = PDL->new_from_specification(PDL::double(), scalar(@edges));
238 ${$p->get_dataref} = $packed;
239 $p->upd_data;
240 return $p;
241 }
242  
243 sub x_centers_pdl {
244 my ($self) = @_;
245 my $edges = x_edges_pdl($self);
246 return ($edges->slice('0:-2') + $edges->slice('1:-1')) / 2.0;
247 }
248  
249 sub y_centers_pdl {
250 my ($self) = @_;
251 my $edges = y_edges_pdl($self);
252 return ($edges->slice('0:-2') + $edges->slice('1:-1')) / 2.0;
253 }
254  
255 sub errors2d_pdl {
256 my ($self) = @_;
257 croak "Math::Histo::PDL: argument must be a Math::Histo::2D object"
258 unless eval { $self->isa('Math::Histo::2D') };
259 my $nx = $self->nx;
260 my $ny = $self->ny;
261 my $packed = '';
262 for my $iy (0 .. $ny - 1) {
263 for my $ix (0 .. $nx - 1) {
264 $packed .= pack('d', $self->bin_error($ix, $iy) // 0.0);
265 }
266 }
267 my $p = PDL->new_from_specification(PDL::double(), $nx, $ny);
268 ${$p->get_dataref} = $packed;
269 $p->upd_data;
270 return $p;
271 }
272  
273 sub to_pdl2d {
274 my ($self, %opts) = @_;
275 if (wantarray && !%opts) {
276 return (matrix_pdl($self), x_edges_pdl($self), y_edges_pdl($self));
277 }
278 if ($opts{all}) {
279 return {
280 matrix => matrix_pdl($self),
281 x_edges => x_edges_pdl($self),
282 y_edges => y_edges_pdl($self),
283 x_centers => x_centers_pdl($self),
284 y_centers => y_centers_pdl($self),
285 errors => errors2d_pdl($self),
286 };
287 }
288 return matrix_pdl($self);
289 }
290  
291 # High-level functional builders
292 sub hist1d {
293 my ($data, %opts) = @_;
294 my $pdl = eval { $data->isa('PDL') } ? $data : PDL::pdl($data);
295 my $weights = delete $opts{weights};
296  
297 my $h;
298 if (exists $opts{edges}) {
299 my $edges = $opts{edges};
300 my @edges_arr = eval { $edges->isa('PDL') } ? $edges->list : @$edges;
301 delete $opts{edges};
302 $h = Math::Histo->new(edges => \@edges_arr, %opts);
303 } elsif (exists $opts{rule} || exists $opts{auto}) {
304 my $rule = delete $opts{rule} // delete $opts{auto};
305 my @samples = $pdl->list;
306 my ($nbins, $min, $max) = Math::Histo->estimate_bins(\@samples, $rule);
307 if ($min == $max) {
308 $min -= 0.5;
309 $max += 0.5;
310 } else {
311 my $margin = ($max - $min) * 1e-6;
312 $max += ($margin > 0 ? $margin : 1e-6);
313 }
314 $h = Math::Histo->new(bins => $nbins, min => $min, max => $max, %opts);
315 } else {
316 my $nbins = delete $opts{bins} // delete $opts{nbins} // 50;
317 my $min = delete $opts{min};
318 my $max = delete $opts{max};
319  
320 if (!defined $min || !defined $max) {
321 if ($pdl->nelem > 0) {
322 my ($pmin, $pmax) = $pdl->minmax;
323 $min //= $pmin;
324 if (!defined $max) {
325 if ($pmin == $pmax) {
326 $min -= 0.5;
327 $max = $pmax + 0.5;
328 } else {
329 my $margin = ($pmax - $pmin) * 1e-6;
330 $max = $pmax + ($margin > 0 ? $margin : 1e-6);
331 }
332 }
333 } else {
334 $min //= 0.0;
335 $max //= 1.0;
336 }
337 }
338 $h = Math::Histo->new(bins => $nbins, min => $min, max => $max, %opts);
339 }
340  
341 fill_pdl($h, $pdl, $weights) if $pdl->nelem > 0;
342 return $h;
343 }
344  
345 sub hist2d {
346 my (@args) = @_;
347 my ($x, $y, $coords, %opts);
348  
349 if (@args >= 1 && eval { $args[0]->isa('PDL') } && $args[0]->ndims == 2) {
350 $coords = shift @args;
351 %opts = @args;
352 if ($coords->dim(0) == 2) {
353 $x = $coords->slice('(0),:')->flat;
354 $y = $coords->slice('(1),:')->flat;
355 } elsif ($coords->dim(1) == 2) {
356 $x = $coords->slice(',(0)')->flat;
357 $y = $coords->slice(',(1)')->flat;
358 } else {
359 croak "Math::Histo::PDL::hist2d: coordinate matrix must have 2 columns or 2 rows (got " . join('x', $coords->dims) . ")";
360 }
361 } else {
362 $x = shift @args;
363 $y = shift @args;
364 %opts = @args;
365 $x = PDL::pdl($x) unless eval { $x->isa('PDL') };
366 $y = PDL::pdl($y) unless eval { $y->isa('PDL') };
367 }
368  
369 my $weights = delete $opts{weights};
370 my $h2d;
371  
372 if (exists $opts{xedges} && exists $opts{yedges}) {
373 my $xe = delete $opts{xedges};
374 my $ye = delete $opts{yedges};
375 my @x_arr = eval { $xe->isa('PDL') } ? $xe->list : @$xe;
376 my @y_arr = eval { $ye->isa('PDL') } ? $ye->list : @$ye;
377 $h2d = Math::Histo::2D->new(xedges => \@x_arr, yedges => \@y_arr, %opts);
378 } else {
379 my ($xbins, $ybins);
380 if (exists $opts{bins}) {
381 my $b = delete $opts{bins};
382 if (ref($b) eq 'ARRAY') {
383 ($xbins, $ybins) = @$b;
384 } else {
385 $xbins = $ybins = $b;
386 }
387 }
388 $xbins //= delete $opts{xbins} // 50;
389 $ybins //= delete $opts{ybins} // 50;
390  
391 my $xmin = delete $opts{xmin};
392 my $xmax = delete $opts{xmax};
393 my $ymin = delete $opts{ymin};
394 my $ymax = delete $opts{ymax};
395  
396 if (!defined $xmin || !defined $xmax) {
397 if ($x->nelem > 0) {
398 my ($min, $max) = $x->minmax;
399 $xmin //= $min;
400 if (!defined $xmax) {
401 if ($min == $max) {
402 $xmin -= 0.5;
403 $xmax = $max + 0.5;
404 } else {
405 my $margin = ($max - $min) * 1e-6;
406 $xmax = $max + ($margin > 0 ? $margin : 1e-6);
407 }
408 }
409 } else {
410 $xmin //= 0.0;
411 $xmax //= 1.0;
412 }
413 }
414  
415 if (!defined $ymin || !defined $ymax) {
416 if ($y->nelem > 0) {
417 my ($min, $max) = $y->minmax;
418 $ymin //= $min;
419 if (!defined $ymax) {
420 if ($min == $max) {
421 $ymin -= 0.5;
422 $ymax = $max + 0.5;
423 } else {
424 my $margin = ($max - $min) * 1e-6;
425 $ymax = $max + ($margin > 0 ? $margin : 1e-6);
426 }
427 }
428 } else {
429 $ymin //= 0.0;
430 $ymax //= 1.0;
431 }
432 }
433  
434 $h2d = Math::Histo::2D->new(
435 xbins => $xbins, xmin => $xmin, xmax => $xmax,
436 ybins => $ybins, ymin => $ymin, ymax => $ymax,
437 %opts
438 );
439 }
440  
441 if ($x->nelem > 0) {
442 fill2d_pdl($h2d, $x, $y, $weights);
443 }
444 return $h2d;
445 }
446  
447 sub pdl_to_histo {
448 my ($pdl, %opts) = @_;
449 if (eval { $pdl->isa('PDL') } && $pdl->ndims == 2 && ($pdl->dim(0) == 2 || $pdl->dim(1) == 2)) {
450 return hist2d($pdl, %opts);
451 }
452 return hist1d($pdl, %opts);
453 }
454  
455 sub histo_to_pdl {
456 my ($h, %opts) = @_;
457 if (eval { $h->isa('Math::Histo::2D') }) {
458 return to_pdl2d($h, %opts);
459 }
460 return to_pdl($h, %opts);
461 }
462  
463 # Inject OO extension methods into Math::Histo and Math::Histo::2D upon module load
464 {
465 no warnings 'redefine';
466 *Math::Histo::fill_pdl = \&fill_pdl;
467 *Math::Histo::to_pdl = \&to_pdl;
468 *Math::Histo::counts_pdl = \&counts_pdl;
469 *Math::Histo::edges_pdl = \&edges_pdl;
470 *Math::Histo::centers_pdl = \&centers_pdl;
471 *Math::Histo::errors_pdl = \&errors_pdl;
472  
473 *Math::Histo::2D::fill_pdl = \&fill2d_pdl;
474 *Math::Histo::2D::to_pdl = \&to_pdl2d;
475 *Math::Histo::2D::matrix_pdl = \&matrix_pdl;
476 *Math::Histo::2D::counts_pdl = \&matrix_pdl;
477 *Math::Histo::2D::x_edges_pdl = \&x_edges_pdl;
478 *Math::Histo::2D::y_edges_pdl = \&y_edges_pdl;
479 *Math::Histo::2D::x_centers_pdl = \&x_centers_pdl;
480 *Math::Histo::2D::y_centers_pdl = \&y_centers_pdl;
481 *Math::Histo::2D::errors_pdl = \&errors2d_pdl;
482 }
483  
484 1;
485  
486 __END__