blib/lib/PDL/Core.pm

filter: Statementstmt 86.2% 717 / 831 Branchbran 71.5% 392 / 548 Conditioncond 73.4% 108 / 147 MC/DCmcdc 47.8% 44 / 92 Subroutinesub 90.7% 98 / 108 Podpod 20.8% 15 / 72 totaltotal 76.4% 1374 / 1798 CC 662 SCAR 29.1
CC
662
Cov
80%
pdumpgraphvizify
110.0
pdumpgraphvizify
110.0
_deep_hdr_copy
80.0
CRAP 18.3
« blib/lib/PDL/Func.pm ↑ Summary lib/PDL/ImageND.pd »
1 package PDL::Core;
2  
3 # Core routines for PDL module
4  
5 71 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
6 71 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
7 71 ▶use PDL::Exporter;
Subroutine BEGIN: called CC=1 SCAR=0.0
8 71 ▶use DynaLoader;
Subroutine BEGIN: called CC=1 SCAR=0.0
9 71 our @ISA = qw( PDL::Exporter DynaLoader );
10 71 our $VERSION = '2.096'; # as of 2.097 it's back in lib/PDL.pm - EUMM XSMULTI extracts version from this as the XS_VERSION for the object, so no override it
11 71 bootstrap PDL::Core $VERSION;
12 71 ▶use PDL::Types ':All';
Subroutine BEGIN: called CC=1 SCAR=0.0
13 71 ▶use Config;
Subroutine BEGIN: called CC=1 SCAR=0.0
14 71 ▶use List::Util qw(max);
Subroutine BEGIN: called CC=1 SCAR=0.0
15 71 ▶use Scalar::Util 'blessed';
Subroutine BEGIN: called CC=1 SCAR=0.0
16  
17 # If quad (q/Q) is available for pack().
18 71 our $CAN_PACK_QUAD = !! eval { my $packed = pack "Q", 0; 1 };
19  
20 # If "D" is available for pack().
21 71 our $CAN_PACK_D = !! eval { my $packed = pack "D", 0; 1 };
22  
23 71 our @EXPORT = qw( piddle pdl null barf ); # Only stuff always exported!
24 71 my @convertfuncs = map $_->convertfunc, PDL::Types::types();
25 71 my @exports_internal = qw(howbig broadcastids topdl);
26 71 my @exports_normal = (@EXPORT,
27 @convertfuncs,
28 qw(nelem dims shape null
29 empty dup dupN inflateN
30 badflag
31 convert inplace zeroes zeros ones nan inf i list listindices unpdl
32 set at broadcast_define over reshape dog cat barf type
33 thread_define dummy mslice approx flat sclr squeeze
34 get_autopthread_targ set_autopthread_targ get_autopthread_actual
35 get_autopthread_dim get_autopthread_size set_autopthread_size) );
36 71 our @EXPORT_OK = (@exports_internal, @exports_normal);
37 71 our %EXPORT_TAGS = (
38 Func => [@exports_normal],
39 Internal => [@exports_internal] );
40  
41 71 our ($level, @dims, $sep, $sep2, $match);
42  
43 # Important variables (place in PDL namespace)
44 # (twice to eat "used only once" warning)
45  
46 71 $PDL::debug = # Debugging info
47 $PDL::debug = 0;
48 71 $PDL::verbose = # Functions provide chatty information
49 $PDL::verbose = 0;
50 71 $PDL::use_commas = 0; # Whether to insert commas when printing arrays
51 71 $PDL::floatformat = "%7g"; # Default print format for long numbers
52 71 $PDL::doubleformat = "%10.8g";
53 71 $PDL::indxformat = "%12d"; # Default print format for PDL_Indx values
54 71 $PDL::undefval = 0; # Value to use instead of undef when creating PDLs
55 71 $PDL::toolongtoprint = 10000; # maximum pdl size to stringify for printing
56 71 $PDL::infoformat = "%C: %T %D";
57  
58 ################ Exportable functions of the Core ######################
59  
60 71 *at_c = *at_bad_c; # back-compat alias
61 71 *thread_define = *broadcast_define;
62  
63 71 ▶our @pdl_ones :shared; # optimisation to provide a "one" of the right type to avoid converttype
Subroutine BEGIN: called CC=1 SCAR=0.0
64 71 for my $t (PDL::Types::types()) {
65 1065 my $conv = $t->convertfunc;
66 71 ▶ no strict 'refs';
Subroutine BEGIN: called CC=1 SCAR=0.0
67 1065 ▶ *$conv = *{"PDL::$conv"} = sub {
Subroutine __ANON__: called CC=3 SCAR=13.6
68 0 ▶ return $t unless @_;
Subroutine __ANON__: not called CC=3 SCAR=14.2
Branch: 2 branches
BranchTrueFalseTotal
unless @_ 11236 1123 12359
unless @_ 0 0 0
69 0 ▶ alltopdl('PDL', (@_>1 ? [@_] : shift), $t);
Branch: 2 branches
BranchTrueFalseTotal
@_ > 1 ? : 174 949 1123
@_ > 1 ? : 0 0 0
70 1065 };
71 1065 ▶ $pdl_ones[$t->enum] = $Config{useithreads} ? 1 : pdl($t, 1);
Branch: 1 branch
BranchTrueFalseTotal
$PDL::Core::Config{'useithreads'} ? : 0 1065 1065
72 }
73  
74 71 ▶BEGIN {
Subroutine BEGIN: called CC=2 SCAR=6.9
75 71 for (qw(
76 inflateN badflag dup dupN howbig unpdl nelem inplace dims
77 list broadcastids listindices null set at sclr shape
78 broadcast_define convert over dog cat mslice
79 type approx dummy isempty string
80 )) {
81 71 ▶ no strict 'refs'; *{$_} = \&{"PDL::$_"};
Subroutine BEGIN: called CC=1 SCAR=0.0
82 }
83 }
84  
85 =head1 NAME
86  
87 PDL::Core - fundamental PDL functionality and vectorization/broadcasting
88  
89 =head1 DESCRIPTION
90  
91 Methods and functions for type conversions, PDL creation,
92 type conversion, broadcasting etc.
93  
94 =head1 SYNOPSIS
95  
96 use PDL::Core; # Normal routines
97 use PDL::Core ':Internal'; # Hairy routines
98  
99 =head1 VECTORIZATION/BROADCASTING: METHOD AND NOMENCLATURE
100  
101 PDL provides vectorized operations via a built-in engine.
102 Vectorization in PDL is called "broadcasting" (formerly, up to 2.074, "threading").
103 The broadcasting engine implements simple rules for each operation.
104  
105 Each PDL object has a "shape" that is a generalized N-dimensional
106 rectangle defined by a "dim list" of sizes in an arbitrary
107 set of dimensions. A PDL with shape 2x3 has 6 elements and is
108 said to be two-dimensional, or may be referred to as a 2x3-PDL.
109 The dimensions are indexed numerically starting at 0, so a
110 2x3-PDL has a dimension 0 (or "dim 0") with size 2 and a 1 dimension
111 (or "dim 1") with size 3.
112  
113 PDL generalizes *all* mathematical operations with the notion of
114 "active dims": each operator has zero or more active dims that are
115 used in carrying out the operation. Simple scalar operations like
116 scalar multiplication ('*') have 0 active dims. More complicated
117 operators can have more active dims. For example, matrix
118 multiplication ('x') has 2 active dims. Additional dims are
119 automatically vectorized across -- e.g. multiplying a 2x5-PDL with a
120 2x5-PDL requires 10 simple multiplication operations, and yields a
121 2x5-PDL result.
122  
123 =head2 Broadcasting rules
124  
125 In any PDL expression, the active dims appropriate for each operator
126 are used starting at the 0 dim and working forward through the dim
127 list of each object. All additional dims after the active dims are
128 "broadcast dims". The broadcast dims do not have to agree exactly: they are
129 coerced to agree according to simple rules:
130  
131 =over 3
132  
133 =item * Null PDLs match any dim list (see below).
134  
135 =item * Dims with sizes other than 1 must all agree in size.
136  
137 =item * Dims of size 1 are silently repeated as necessary except for C<[phys]> PDLs.
138  
139 =item * Missing dims are expanded appropriately.
140  
141 =back
142  
143 A size-1 dim for C<[phys]> PDLs causes an exception if the dim is used
144 in another parameter and has a size greater than 1.
145  
146 The "size 1" rule implements "generalized scalar" operation, by
147 analogy to scalar multiplication. The "missing dims" rule
148 acknowledges the ambiguity between a missing dim and a dim of size 1.
149  
150 =head2 Null PDLs
151  
152 PDLs on the left-hand side of assignment can have the special value
153 "Null". A null PDL has no dim list and no set size; its shape is
154 determined by the computed shape of the expression being assigned to
155 it. Null PDLs contain no values and can only be assigned to. When
156 assigned to (e.g. via the C<.=> operator), they cease to be null PDLs.
157  
158 To create a null PDL, use C<PDL-E<gt>null()>.
159  
160 =head2 Empty PDLs
161  
162 PDLs can represent the empty set using "structured Empty" variables.
163 An empty PDL is not a null PDL.
164  
165 Any dim of a PDL can be set explicitly to size 0. If so, the PDL
166 contains zero values (because the total number of values is the
167 product of all the sizes in the PDL's shape or dimlist).
168  
169 Scalar PDLs are zero-dimensional and have no entries in the dim list,
170 so they cannot be empty. 1-D and higher PDLs can be empty. Empty
171 PDLs are useful for set operations, and are most commonly encountered
172 in the output from selection operators such as L<which|PDL::Primitive/which>
173 and L<whichND|PDL::Primitive/whichND>. Not all empty PDLs have the same
174 broadcasting properties -- e.g. a 2x0-PDL represents a collection of
175 2-vectors that happens to contain no elements, while a simple 0-PDL
176 represents a collection of scalar values (that also happens to contain
177 no elements).
178  
179 Note that 0 dims are not adjustable via the broadcasting rules -- a dim
180 with size 0 can only match a corresponding dim of size 0 or 1.
181  
182 =head2 Broadcast rules and assignments
183  
184 Versions of PDL through 2.4.10 have some irregularity with broadcasting and
185 assignments. Currently the broadcasting engine performs a full expansion of
186 both sides of the computed assignment operator C<.=> (which assigns values
187 to a pre-existing PDL). This leads to counter-intuitive behavior in
188 some cases:
189  
190 =over 3
191  
192 =item * Empty PDLs and generalized scalars
193  
194 Generalized scalars (PDLs with a dim of size 1) can match any size in the
195 corresponding dim, including 0. Thus,
196  
197 $x = ones(2,0);
198 $y = sequence(2,1);
199 $c = $x * $y;
200 print $c;
201  
202 prints C<Empty[2,0]>.
203  
204 This behavior is counterintuitive but desirable, and will be preserved
205 in future versions of PDL.
206  
207 =back
208  
209 =head1 VARIABLES
210  
211 These are important variables of B<global> scope and are placed
212 in the PDL namespace.
213  
214 =head3 C<$PDL::debug>
215  
216 =over 4
217  
218 When true, PDL debugging information is printed.
219  
220 =back
221  
222 =head3 C<$PDL::verbose>
223  
224 =over 4
225  
226 When true, PDL functions provide chatty information.
227  
228 =back
229  
230 =head3 C<$PDL::use_commas>
231  
232 =over 4
233  
234 Whether to insert commas when printing pdls
235  
236 =back
237  
238 =head3 C<$PDL::floatformat>, C<$PDL::doubleformat>, C<$PDL::indxformat>
239  
240 =over 4
241  
242 The default print format for floats, doubles, and indx values,
243 respectively. The default default values are:
244  
245 $PDL::floatformat = "%7g";
246 $PDL::doubleformat = "%10.8g";
247 $PDL::indxformat = "%12d";
248  
249 =back
250  
251 =head3 C<$PDL::infoformat>
252  
253 =over 4
254  
255 The default format for C<info>. The default value is:
256  
257 $PDL::infoformat = "%C: %T %D";
258  
259 =back
260  
261 =head3 C<$PDL::undefval>
262  
263 =over 4
264  
265 The value to use instead of C<undef> when creating pdls. If is
266 C<undef>, 0 will be used.
267  
268 =back
269  
270 =head3 C<$PDL::toolongtoprint>
271  
272 =over 4
273  
274 The maximal size pdls to print (defaults to 10000 elements)
275  
276 =back
277  
278 =head1 FUNCTIONS
279  
280  
281 =head2 barf
282  
283 =for ref
284  
285 Standard error reporting routine for PDL.
286  
287 C<barf()> is the routine PDL modules should call to report errors. This
288 is because C<barf()> will report the error as coming from the correct
289 line in the module user's script rather than in the PDL module.
290  
291 For now, barf just calls Carp::confess()
292  
293 Remember C<barf()> is your friend. *Use* it!
294  
295 =for example
296  
297 At the perl level:
298  
299 barf("User has too low an IQ!");
300  
301 In C or XS code:
302  
303 barf("You have made %d errors", count);
304  
305 Note: this is one of the few functions ALWAYS exported
306 by PDL::Core
307  
308 =cut
309  
310 71 ▶use Carp;
Subroutine BEGIN: called CC=1 SCAR=0.0
311 176 ▶sub barf { goto &Carp::confess }
Subroutine barf: called CC=1 SCAR=0.0
Pod documented
312 12 ▶sub cluck { goto &Carp::cluck }
Subroutine cluck: called CC=1 SCAR=0.0
Pod undocumented
313 71 *PDL::barf = \&barf;
314 71 *PDL::cluck = \&cluck;
315  
316 ########## Set Auto-PThread Based On Environment Vars ############
317 71 ▶$ENV{PDL_AUTOPTHREAD_TARG} //= online_cpus();
Condition66%2/3
$ENV{"PDL_AUTOPTHREAD_TARG"} //= online_cpus()
l!l&&r!l&&!r
1700
MC/DC0%0/2
$ENV{"PDL_AUTOPTHREAD_TARG"} //= online_cpus()
$ENV{"PDL_AUTOPTHREAD_TARG"} online_cpus()
Truth table66%2/3
A //= B
A= $ENV{"PDL_AUTOPTHREAD_TARG"}B= online_cpus()
ABresult
1X1
011
000
318 71 ▶PDL::set_autopthread_targ( $ENV{PDL_AUTOPTHREAD_TARG} ) if $ENV{PDL_AUTOPTHREAD_TARG} > 1;
Branch: 1 branch
BranchTrueFalseTotal
if $ENV{"PDL_AUTOPTHREAD_TARG"} > 1 70 1 71
319 71 ▶PDL::set_autopthread_size( $ENV{PDL_AUTOPTHREAD_SIZE} ) if( defined ( $ENV{PDL_AUTOPTHREAD_SIZE} ) );
Branch: 1 branch
BranchTrueFalseTotal
if defined $ENV{"PDL_AUTOPTHREAD_SIZE"} 0 71 71
320 ##################################################################
321  
322 =head2 pdl
323  
324 =for ref
325  
326 PDL constructor - creates new ndarray from perl scalars/arrays, ndarrays, and strings
327  
328 =for usage
329  
330 $double_pdl = pdl(SCALAR|ARRAY REFERENCE|ARRAY|STRING); # default type
331 $type_pdl = pdl(PDL::Type,SCALAR|ARRAY REFERENCE|ARRAY|STRING);
332  
333 =for example
334  
335 $x = pdl [1..10]; # 1D array of doubles
336 $x = pdl ([1..10]); # 1D array
337 $x = pdl (1,2,3,4); # Ditto
338 $y = pdl [[1,2,3],[4,5,6]]; # 2D 3x2 array
339 $y = pdl "[[1,2,3],[4,5,6]]"; # Ditto (slower)
340 $y = pdl "[1 2 3; 4 5 6]"; # Ditto
341 $y = pdl q[1 2 3; 4 5 6]; # Ditto, using the q quote operator
342 $y = pdl "1 2 3; 4 5 6"; # Ditto, less obvious, but still works
343 $y = pdl 42 # 0-dimensional scalar
344 $c = pdl $x; # Make a new copy
345  
346 $u = pdl ushort(), 42 # 0-dimensional ushort scalar
347 $y = pdl(byte(),[[1,2,3],[4,5,6]]); # 2D byte ndarray
348  
349 $n = pdl indx(), [1..5]; # 1D array of indx values
350 $n = pdl indx, [1..5]; # ... can leave off parens
351 $n = indx( [1..5] ); # ... still the same!
352  
353 $n = pdl cdouble, 2, 3; # native complex numbers, zero imaginary
354 use Math::Complex qw(cplx);
355 $n = pdl cdouble, 2, cplx(2, 1)); # explicit type
356 $n = pdl 2, cplx(2, 1); # default cdouble if Math::Complex obj
357  
358 $x = pdl([[1,2,3],[4,5,6]]); # 2D
359 $x = pdl([1,2,3],[4,5,6]); # 2D
360  
361 Note the last two are equivalent - a list is automatically
362 converted to a list reference for syntactic convenience. i.e. you
363 can omit the outer C<[]>
364  
365 You can mix and match arrays, array refs, and PDLs in your argument
366 list, and C<pdl> will sort them out. You get back a PDL whose last
367 (slowest running) dim runs across the top level of the list you hand
368 in, and whose first (fastest running) dim runs across the deepest
369 level that you supply.
370  
371 At the moment, you cannot mix and match those arguments with string
372 arguments, though we can't imagine a situation in which you would
373 really want to do that.
374  
375 The string version of pdl also allows you to use the strings C<bad>, C<inf>,
376 and C<nan>, and it will insert the values that you mean (and set the bad flag
377 if you use C<bad>). You can mix and match case, though you shouldn't. Here are
378 some examples:
379  
380 $bad = pdl q[1 2 3 bad 5 6]; # Set fourth element to the bad value
381 $bad = pdl q[1 2 3 BAD 5 6]; # ditto
382 $bad = pdl q[1 2 inf bad 5]; # now third element is IEEE infinite value
383 $bad = pdl q[nan 2 inf -inf]; # first value is IEEE nan value
384  
385 The default constructor uses IEEE double-precision floating point numbers. You
386 can use other types, but you will get a warning if you try to use C<nan> with
387 integer types (it will be replaced with the C<bad> value) and you will get a
388 fatal error if you try to use C<inf>.
389  
390 Throwing a PDL into the mix has the same effect as throwing in a list ref:
391  
392 pdl(pdl(1,2),[3,4])
393  
394 is the same as
395  
396 pdl([1,2],[3,4]).
397  
398 All of the dimensions in the list are "padded-out" with undefval to
399 meet the widest dim in the list, so (e.g.)
400  
401 $x = pdl([[1,2,3],[2]])
402  
403 gives you the same answer as
404  
405 $x = pdl([[1,2,3],[2,undef,undef]]);
406  
407 If your PDL module has bad values compiled into it (see L<PDL::Bad>),
408 you can pass BAD values into the constructor within pre-existing PDLs.
409 The BAD values are automatically kept BAD and propagated correctly.
410  
411 C<pdl()> is a functional synonym for the 'new' constructor,
412 e.g.:
413  
414 $x = PDL->new([1..10]);
415  
416 In order to control how undefs are handled in converting from perl lists to
417 PDLs, one can set the variable C<$PDL::undefval>.
418 For example:
419  
420 $foo = [[1,2,undef],[undef,3,4]];
421 $PDL::undefval = -999;
422 $f = pdl $foo;
423 print $f
424 [
425 [ 1 2 -999]
426 [-999 3 4]
427 ]
428  
429 C<$PDL::undefval> defaults to zero.
430  
431 As a final note, if you include an Empty PDL in the list of objects to
432 construct into a PDL, it is kept as a placeholder pane -- so if you feed
433 in (say) 7 objects, you get a size of 7 in the 0th dim of the output PDL.
434 The placeholder panes are completely padded out. But if you feed in only
435 a single Empty PDL, you get back the Empty PDL (no padding).
436  
437 =cut
438  
439 =head2 empty
440  
441 =for ref
442  
443 Returns an empty ndarray, with a single zero-length dimension.
444 Only available as a function, not a method.
445  
446 =for usage
447  
448 $x = empty; # defaults to lowest type so it can always be promoted up
449 $x = empty(float);
450  
451 =cut
452  
453 385 ▶sub empty {
Subroutine empty: called CC=2 SCAR=6.9
Pod documented
454 385 my ($type) = @_;
455 385 ▶ $type //= 0;
Condition100%2/2
$type //= 0
l!l
34639
MC/DC100%1/1
$type //= 0
$type
Truth table100%2/2
A
A= $type
Aresult
11
00
456 385 PDL->new_from_specification(PDL::Type->new($type), 0);
457 }
458  
459 =head2 null
460  
461 =for ref
462  
463 Returns a 'null' ndarray.
464 It is an error to pass one of these as an input to a function.
465  
466 =for usage
467  
468 $x = null;
469  
470 C<null()> has a special meaning to L<PDL::PP>. It is used to
471 flag a special kind of empty ndarray, which can grow to
472 appropriate dimensions to store a result (as opposed to
473 storing a result in an existing ndarray).
474  
475 =for example
476  
477 pdl> sumover sequence(10,10), $ans=null;p $ans
478 [45 145 245 345 445 545 645 745 845 945]
479  
480 =cut
481  
482 2877 ▶sub PDL::null{
Subroutine null: called CC=4 SCAR=13.9
Pod undocumented
483 2877 ▶ my $class = scalar(@_) ? shift : undef; # if this sub called with no
Branch: 1 branch
BranchTrueFalseTotal
scalar @_ ? : 2681 196 2877
484 # class ( i.e. like 'null()', instead
485 # of '$obj->null' or 'CLASS->null', setup
486  
487 2877 ▶ if( defined($class) ){
Branch: 1 branch
BranchTrueFalseTotal
if (defined $class) { } 2681 196 2877
488 2681 ▶ $class = ref($class) || $class; # get the class name
Condition66%2/3
ref $class || $class
l!l&&r!l&&!r
159810830
MC/DC0%0/2
ref $class || $class
ref $class $class
Truth table66%2/3
A || B
A= ref $classB= $class
ABresult
1X1
011
000
489 }
490 else{
491 196 $class = 'PDL'; # set class to the current package name if null called
492 # with no arguments
493 }
494  
495 2877 return $class->initialize();
496 }
497  
498 =head2 nullcreate
499  
500 =for ref
501  
502 Returns a 'null' ndarray.
503  
504 =for usage
505  
506 $x = PDL->nullcreate($arg)
507  
508 This is an routine used by many of the broadcasting primitives
509 (i.e. L<sumover|PDL::Ufunc/sumover>,
510 L<minimum|PDL::Ufunc/minimum>, etc.) to generate a null ndarray for the
511 function's output that will behave properly for derived (or
512 subclassed) PDL objects.
513  
514 For the above usage:
515 If C<$arg> is a PDL, or a derived PDL, then C<$arg-E<gt>null> is returned.
516 If C<$arg> is a scalar (i.e. a zero-dimensional PDL) then C<PDL-E<gt>null>
517 is returned.
518  
519 =for example
520  
521 PDL::Derived->nullcreate(10)
522 returns PDL::Derived->null.
523 PDL->nullcreate($pdlderived)
524 returns $pdlderived->null.
525  
526 =cut
527  
528 1603 ▶sub PDL::nullcreate{
Subroutine nullcreate: called CC=2 SCAR=6.9
Pod undocumented
529 1603 my ($type,$arg) = @_;
530 1603 ▶ return ref($arg) ? $arg->null : $type->null ;
Branch: 1 branch
BranchTrueFalseTotal
ref $arg ? : 224 1379 1603
531 }
532  
533 =head2 nelem
534  
535 =for ref
536  
537 Return the number of elements in an ndarray
538  
539 =for usage
540  
541 $n = nelem($ndarray); $n = $ndarray->nelem;
542  
543 =for example
544  
545 $mean = sum($data)/nelem($data);
546  
547 =head2 dims
548  
549 =for ref
550  
551 Return ndarray dimensions as a perl list
552  
553 =for usage
554  
555 @dims = $ndarray->dims; @dims = dims($ndarray);
556  
557 =for example
558  
559 pdl> p @tmp = dims zeroes 10,3,22
560 10 3 22
561  
562 See also L</shape> which returns an ndarray instead.
563  
564 =head2 dimincs
565  
566 =for ref
567  
568 Return ndarray C<dimincs> as a perl list, reflecting any
569 vaffine transformations of which this is a child.
570  
571 =for usage
572  
573 @dimincs = $ndarray->dimincs
574  
575 =for example
576  
577 pdl> p zeroes(10,3,22)->dimincs
578 1 10 30
579 pdl> p zeroes(10,3,22)->t->dimincs
580 10 1 30
581  
582 =head2 shape
583  
584 =for ref
585  
586 Return ndarray dimensions as an ndarray
587  
588 =for usage
589  
590 $shape = $ndarray->shape; $shape = shape($ndarray);
591  
592 =for example
593  
594 pdl> p $shape = shape zeroes 10,3,22
595 [10 3 22]
596  
597 See also L</dims> which returns a perl list.
598  
599 =head2 ndims
600  
601 =for ref
602  
603 Returns the number of dimensions in an ndarray. Alias
604 for L<getndims|PDL::Core/getndims>.
605  
606 =head2 getndims
607  
608 =for ref
609  
610 Returns the number of dimensions in an ndarray
611  
612 =for usage
613  
614 $ndims = $ndarray->getndims;
615  
616 =for example
617  
618 pdl> p zeroes(10,3,22)->getndims
619 3
620  
621 =head2 dim
622  
623 =for ref
624  
625 Returns the size of the given dimension of an ndarray. Alias
626 for L<getdim|PDL::Core/getdim>.
627  
628 =head2 getdim
629  
630 =for ref
631  
632 Returns the size of the given dimension.
633  
634 =for usage
635  
636 $dim0 = $ndarray->getdim(0);
637  
638 =for example
639  
640 pdl> p zeroes(10,3,22)->getdim(1)
641 3
642  
643 Negative indices count from the end of the dims array.
644 Indices beyond the end will return a size of 1. This
645 reflects the idea that any pdl is equivalent to an
646 infinitely dimensional array in which only a finite number of
647 dimensions have a size different from one. For example, in that sense a
648 3D ndarray of shape [3,5,2] is equivalent to a [3,5,2,1,1,1,1,1,....]
649 ndarray. Accordingly,
650  
651 print $x->getdim(10000);
652  
653 will print 1 for most practically encountered ndarrays.
654  
655 =head2 topdl
656  
657 =for ref
658  
659 alternate ndarray constructor - ensures arg is an ndarray
660  
661 =for usage
662  
663 $x = topdl(SCALAR|ARRAY REFERENCE|ARRAY);
664  
665 The difference between L<pdl()|/pdl> and C<topdl()> is that the
666 latter will just 'fall through' if the argument is
667 already an ndarray. It will return a reference and I<NOT>
668 a new copy.
669  
670 This is particularly useful if you are writing a function
671 which is doing some fiddling with internals and assumes
672 an ndarray argument (e.g. for method calls). Using C<topdl()>
673 will ensure nothing breaks if passed with '2'.
674  
675 Note that C<topdl()> is not exported by default (see example
676 below for usage).
677  
678 =for example
679  
680 use PDL::Core ':Internal'; # use the internal routines of
681 # the Core module
682  
683 $x = topdl 43; # $x is ndarray with value '43'
684 $y = topdl $ndarray; # fall through
685 $x = topdl (1,2,3,4); # Convert 1D array
686  
687 =head2 tocomplex
688  
689 =for ref
690  
691 Return a complex-typed ndarray, either as a no-op or a conversion.
692  
693 $cplx = $pdl->tocomplex;
694  
695 Not exported. Added in 2.099.
696  
697 =cut
698  
699 4 ▶sub PDL::tocomplex {
Subroutine tocomplex: called CC=2 SCAR=6.9
Pod undocumented
700 4 my $pdl = PDL->topdl(@_);
701 4 ▶ $pdl->type->real ? $pdl->r2C : $pdl;
Branch: 1 branch
BranchTrueFalseTotal
$pdl->type->real ? : 2 2 4
702 }
703  
704 =head2 setdims
705  
706 =for ref
707  
708 Sets the ndarray's dimension list. A very low-level routine which
709 does not do any checks, so use with caution.
710  
711 =for usage
712  
713 $ndarray->setdims(\@dimlist);
714  
715 =head2 set_datatype
716  
717 =for ref
718  
719 Sets the ndarray's data type to the given value (the integer identifier
720 for the type, see L<PDL::Types/enum>). See L</get_datatype>. Internal
721 function. Errors if ndarray has child transforms. Severs if has a parent.
722  
723 =head2 get_datatype
724  
725 =for ref
726  
727 Internal: Return the numeric value identifying the ndarray datatype
728  
729 =for usage
730  
731 $x = $ndarray->get_datatype;
732  
733 Mainly used for internal routines.
734  
735 NOTE: get_datatype returns 'just a number' not any special
736 type object, unlike L</type>.
737  
738 =head2 howbig
739  
740 =for ref
741  
742 Returns the sizeof an ndarray datatype in bytes.
743  
744 Note that C<howbig()> is not exported by default (see example
745 below for usage).
746  
747 =for usage
748  
749 use PDL::Core ':Internal'; # use the internal routines of
750 # the Core module
751  
752 $size = howbig($ndarray->get_datatype);
753  
754 Mainly used for internal routines.
755  
756 NOTE: NOT a method! This is because get_datatype returns
757 'just a number' not any special object.
758  
759 =for example
760  
761 pdl> p howbig(ushort([1..10])->get_datatype)
762 2
763  
764 =head2 update_data_from
765  
766 =for ref
767  
768 Update an ndarray's internal data for from packed data.
769  
770 $data = read_from_datasource();
771 $pdl->update_data_from($data);
772  
773 Throws an exception if the argument is the wrong size for that ndarray.
774  
775 =head2 get_dataref
776  
777 =for ref
778  
779 Return the internal data for an ndarray, as a perl SCALAR ref.
780  
781 If you are using this in order to manipulate the SV, then call
782 L</upd_data>, then as of 2.099 you are recommended instead to just
783 use L</update_data_from> to streamline the process.
784  
785 Most ndarrays hold their internal data in a packed perl string, to take
786 advantage of perl's memory management. This gives you direct access
787 to the string, which is handy when you need to manipulate the binary
788 data directly (e.g. for file I/O). If you modify the string, you'll
789 need to call L</upd_data> afterward, to make sure that the
790 ndarray points to the new location of the underlying perl variable.
791  
792 Calling C<get_dataref> automatically physicalizes your ndarray (see
793 L</make_physical>). You definitely
794 don't want to do anything to the SV to truncate or deallocate the
795 string, unless you correspondingly call L</reshape> to make the
796 PDL match its new data dimension.
797  
798 You definitely don't want to use get_dataref unless you know what you
799 are doing (or are trying to find out): you can end up scrozzling
800 memory if you shrink or eliminate the string representation of the
801 variable. Here be dragons.
802  
803 =head2 upd_data
804  
805 =for ref
806  
807 Update the data pointer in an ndarray to match its perl SV.
808  
809 This is useful if you've been monkeying with the packed string
810 representation of the PDL, which you probably shouldn't be doing
811 anyway. (see L</get_dataref>.)
812  
813 As of 2.099 you are recommended instead to just use
814 L</update_data_from> to streamline the process.
815  
816 =cut
817  
818 946 ▶sub topdl {PDL->topdl(@_)}
Subroutine topdl: called CC=1 SCAR=0.0
Pod documented
819  
820 ####################### Subclass as hashref #######################
821 { package # hide from PAUSE
822 PDL::Hash;
823 71 our @ISA = qw/PDL/;
824 50 ▶sub initialize {
Subroutine initialize: called CC=2 SCAR=7.1
825 50 my ($class) = @_;
826 50 ▶ bless { PDL => PDL->null }, ref $class || $class;
Condition66%2/3
ref $class || $class
l!l&&r!l&&!r
40100
MC/DC0%0/2
ref $class || $class
ref $class $class
Truth table66%2/3
A || B
A= ref $classB= $class
ABresult
1X1
011
000
827 }
828 }
829  
830 ####################### Overloaded operators #######################
831  
832 71 { package # hide from MetaCPAN
833 PDL;
834 71 ▶ use Carp;
Subroutine BEGIN: called CC=1 SCAR=0.0
835 306 ▶ sub overload_assign {$_[0]} # Don't deep copy, just copy reference
Subroutine overload_assign: called CC=1 SCAR=0.0
Pod undocumented
836 3496 ▶ sub overload_bool {
Subroutine overload_bool: called CC=5 SCAR=16.3
Pod undocumented
837 3496 ▶ return 0 if $_[0]->isnull;
Branch: 1 branch
BranchTrueFalseTotal
if $_[0]->isnull 0 3496 3496
838 3496 ▶ confess("multielement ndarray in conditional expression (see PDL::FAQ questions 6-10 and 6-11)")
Branch: 1 branch
BranchTrueFalseTotal
unless $_[0]->nelem == 1 4 3492 3496
839 unless $_[0]->nelem == 1;
840 3492 ▶ confess("bad value ndarray in conditional expression")
Branch: 1 branch
BranchTrueFalseTotal
if $_[0]->badflag and $_[0] . '' eq "BAD" 1 3491 3492
Condition66%2/3
$_[0]->badflag and $_[0] . '' eq "BAD"
!ll&&!rl&&r
27877050
MC/DC0%0/2
$_[0]->badflag and $_[0] . '' eq "BAD"
$_[0]->badflag $_[0] . '' eq "BAD"
Truth table66%2/3
A and B
A= $_[0]->badflagB= $_[0] . '' eq "BAD"
ABresult
0X0
100
111
841 if $_[0]->badflag and $_[0].'' eq 'BAD';
842 3491 $_[0]->flat->at(0);
843 }
844 use overload
845 71 ▶ '""' => \&PDL::Core::string,
Subroutine BEGIN: called CC=1 SCAR=0.0
846 "=" => \&overload_assign,
847 bool => \&overload_bool,
848 71 ;
849 }
850  
851 ##################### Data type/conversion stuff ########################
852  
853 71 ▶sub PDL::shape { # Return dimensions as a pdl
Subroutine shape: called CC=1 SCAR=0.0
Pod undocumented
854 57 indx([PDL->topdl(shift)->dims]);
855 }
856  
857 8206 ▶sub PDL::howbig {
Subroutine howbig: called CC=2 SCAR=6.9
Pod undocumented
858 8206 my $t = shift;
859 8206 ▶ if("PDL::Type" eq ref $t) {$t = $t->[0]}
Branch: 1 branch
BranchTrueFalseTotal
if ("PDL::Type" eq ref $t) 7689 517 8206
860 8206 PDL::howbig_c($t);
861 }
862  
863 =head2 broadcastids
864  
865 =for ref
866  
867 Returns the ndarray broadcast IDs as a perl list
868  
869 Note that C<broadcastids()> is not exported by default (see example
870 below for usage).
871  
872 =for usage
873  
874 use PDL::Core ':Internal'; # use the internal routines of
875 # the Core module
876  
877 @ids = broadcastids $ndarray;
878  
879 =cut
880  
881 ################# Creation/copying functions #######################
882  
883 0 ▶sub piddle {PDL->pdl(@_)}
Subroutine piddle: not called CC=1 SCAR=6.9
Pod undocumented
884 8830 ▶sub pdl {PDL->pdl(@_)}
Subroutine pdl: called CC=1 SCAR=0.0
Pod documented
885 9130 ▶sub PDL::pdl { shift->new(@_) }
Subroutine pdl: called CC=1 SCAR=0.0
Pod undocumented
886  
887 =head2 readonly
888  
889 =for ref
890  
891 Make an ndarray read-only, returning the ndarray argument.
892 This means any future transformation (a.k.a. PDL
893 operation) applied to this ndarray I<as an output> will cause an exception:
894  
895 $x = sequence(3)->readonly; # also works: $x = sequence(3); $x->readonly;
896 $y = $x + 1; # fine
897 $x .= 5; # error
898 $x += 5; # also error
899  
900 Not exported.
901  
902 =for usage
903  
904 $x->readonly;
905  
906 =head2 is_readonly
907  
908 =for ref
909  
910 Test whether an ndarray is read-only.
911  
912 $bool = $x->is_readonly;
913  
914 Not exported.
915  
916 =for usage
917  
918 $x->is_readonly;
919  
920 =head2 flowing
921  
922 =for ref
923  
924 Turn on dataflow, forward only, only for the next operation (cf
925 L</inplace>), returning the ndarray argument.
926 This means the next transformation (a.k.a. PDL
927 operation) applied to this ndarray will have forward dataflow:
928  
929 $x = sequence 3;
930 $y = $x->flowing + 1; # could instead do $x->flowing; $y = $x + 1
931 $x += 3; # this does not flow, but that would be an infinite loop anyway
932 print "$y\n"; # [4 5 6]
933  
934 This replaced C<doflow> as of 2.090. See L<PDL::Dataflow> for more.
935  
936 =for usage
937  
938 $x->flowing; flowing($x);
939  
940 =head2 fflows
941  
942 =for ref
943  
944 Returns whether the ndarray's C<PDL_DATAFLOW_F> flag is set.
945  
946 =head2 new
947  
948 =for ref
949  
950 new ndarray constructor method
951  
952 =for usage
953  
954 $x = PDL->new(SCALAR|ARRAY|ARRAY REF|STRING);
955  
956 =for example
957  
958 $x = PDL->new(42); # new from a Perl scalar
959 $y = PDL->new(@list_of_vals); # new from Perl list
960 $z = PDL->new(\@list_of_vals); # new from Perl list reference
961 $w = PDL->new("[1 2 3]"); # new from Perl string, using
962 # Matlab constructor syntax
963  
964 Constructs ndarray from perl numbers and lists
965 and strings with Matlab/Octave style constructor
966 syntax.
967  
968 The string input is fairly versatile though not
969 performance optimized. The goal is to make it
970 easy to copy and paste code from PDL output and
971 to offer a familiar Matlab syntax for ndarray
972 construction. As of May, 2010, it is a new
973 feature, so feel free to report bugs or suggest
974 new features. See documentation for L<pdl> for
975 more examples of usage.
976  
977  
978 =cut
979  
980 71 ▶use Scalar::Util; # for looks_like_number test
Subroutine BEGIN: called CC=1 SCAR=0.0
981 71 ▶use Carp 'carp'; # for carping (warnings in caller's context)
Subroutine BEGIN: called CC=1 SCAR=0.0
982  
983 # This is the code that handles string arguments. It has now got quite large,
984 # so here's the basic explanation. I want to allow expressions like 2, 1e3, +4,
985 # bad, nan, inf, and more. Checking this can get tricky. This croaks when it
986 # finds:
987 # 1) strings of e or E that are longer than 1 character long (like eeee)
988 # 2) non-supported characters or strings
989 # 3) expressions that are syntactically erroneous, like '1 2 3 ]', which has an
990 # extra bracket
991 # 4) use of inf when the data type does not support inf (i.e. the integers)
992  
993 71 my @types = PDL::Types::types;
994 71 my $STR_nan = PDL::_nan();
995 71 my $STR_i = PDL::_ci();
996 71 my $STR_inf = PDL::_inf();
997 71 my $STR_pi = 4 * atan2(1, 1);
998 71 my $STR_e = exp(1);
999 536 ▶sub PDL::Core::new_pdl_from_string {
Subroutine new_pdl_from_string: called CC=33 SCAR=36.3
Pod undocumented
1000 536 my ($new, $original_value, $this, $type) = @_;
1001 536 my $value = $original_value;
1002  
1003 # Check for input that would generate empty ndarrays as output:
1004 536 ▶ return zeroes($types[$type], 0) if $value eq '' or $value eq '[]';
Branch: 1 branch
BranchTrueFalseTotal
if $value eq "" or $value eq "[]" 2 534 536
Condition100%3/3
$value eq "" or $value eq "[]"
l!l&&r!l&&!r
11534
MC/DC100%2/2
$value eq "" or $value eq "[]"
$value eq "" $value eq "[]"
Truth table100%3/3
A or B
A= $value eq ""B= $value eq "[]"
ABresult
1X1
011
000
1005  
1006 # I check for invalid characters later, but arbitrary strings of e will
1007 # pass that check, so I'll check for that here, first.
1008 534 ▶ croak("PDL::Core::new_pdl_from_string: found 'e' as part of a larger word in $original_value")
Branch: 1 branch
BranchTrueFalseTotal
if $value =~ /e\p{IsAlpha}|\p{IsAlpha}e/ 10 524 534
1009 if $value =~ /e\p{IsAlpha}|\p{IsAlpha}e/;
1010  
1011 # Only a few characters are allowed in the expression, but we want to allow
1012 # expressions like 'inf' and 'bad'. As such, convert those values to internal
1013 # representations that will pass the invalid-character check. We'll replace
1014 # them with Perl-evalute-able strings in a little bit. Here, I represent
1015 # bad => EE
1016 # nan => ee
1017 # inf => Ee
1018 # pi => eE
1019 # i => EeE
1020 # --( Bad )--
1021 524 ▶ croak("PDL::Core::new_pdl_from_string: found 'bad' as part of a larger word in $original_value")
Branch: 1 branch
BranchTrueFalseTotal
if $value =~ /bad\B|\Bbad/ 4 520 524
1022 if $value =~ /bad\B|\Bbad/;
1023 520 my ($has_bad) = ($value =~ s/\bbad\b/EE/gi);
1024 # --( nan )--
1025 520 my $has_nan = 0;
1026 520 ▶ croak("PDL::Core::new_pdl_from_string: found 'nan' as part of a larger word in $original_value")
Branch: 1 branch
BranchTrueFalseTotal
if $value =~ /\Bnan|nan\B/ 0 520 520
1027 if $value =~ /\Bnan|nan\B/;
1028 520 ▶ $has_nan++ if ($value =~ s/\bnan\b/ee/gi);
Branch: 1 branch
BranchTrueFalseTotal
if $value =~ s/\bnan\b/ee/gi 13 507 520
1029 # Strawberry Perl compatibility:
1030 520 ▶ croak("PDL::Core::new_pdl_from_string: found '1.#IND' as part of a larger word in $original_value")
Branch: 1 branch
BranchTrueFalseTotal
if $value =~ /IND\B/i 0 520 520
1031 if $value =~ /IND\B/i;
1032 520 ▶ $has_nan++ if ($value =~ s/1\.\#IND/ee/gi);
Branch: 1 branch
BranchTrueFalseTotal
if $value =~ s/1\.\#IND/ee/gi 0 520 520
1033 # --( inf )--
1034 520 my $has_inf = 0;
1035 # Strawberry Perl compatibility:
1036 520 ▶ croak("PDL::Core::new_pdl_from_string: found '1.#INF' as part of a larger word in $original_value")
Branch: 1 branch
BranchTrueFalseTotal
if $value =~ /INF\B/i 2 518 520
1037 if $value =~ /INF\B/i;
1038 518 ▶ $has_inf++ if ($value =~ s/1\.\#INF/Ee/gi);
Branch: 1 branch
BranchTrueFalseTotal
if $value =~ s/1\.\#INF/Ee/gi 1 517 518
1039 # Other platforms:
1040 518 ▶ croak("PDL::Core::new_pdl_from_string: found 'inf' as part of a larger word in $original_value")
Branch: 1 branch
BranchTrueFalseTotal
if $value =~ /inf\B|\Binf/ 2 516 518
1041 if $value =~ /inf\B|\Binf/;
1042 516 ▶ $has_inf++ if ($value =~ s/\binf\b/Ee/gi);
Branch: 1 branch
BranchTrueFalseTotal
if $value =~ s/\binf\b/Ee/gi 7 509 516
1043 # --( pi )--
1044 516 ▶ croak("PDL::Core::new_pdl_from_string: found 'pi' as part of a larger word in $original_value")
Branch: 1 branch
BranchTrueFalseTotal
if $value =~ /pi\B|\Bpi/ 4 512 516
1045 if $value =~ /pi\B|\Bpi/;
1046 512 $value =~ s/\bpi\b/eE/gi;
1047 # --( i )--
1048 512 my $has_i = 0;
1049 512 ▶ croak("PDL::Core::new_pdl_from_string: found 'i' as part of a larger word ($1) in $original_value")
Branch: 1 branch
BranchTrueFalseTotal
if $value =~ /(i\B|[^\-+\d\s.\[]i)/ 0 512 512
1050 if $value =~ /(i\B|[^\-+\d\s.\[]i)/;
1051 512 ▶ $has_i++ if ($value =~ s/([\-+\d]*)i\b/${1}EeE/gi);
Branch: 1 branch
BranchTrueFalseTotal
if $value =~ s/([\-+\d]*)i\b/$1EeE/gi 71 441 512
1052 512 ▶ $type = $types[$type]->complexversion->enum if $has_i;
Branch: 1 branch
BranchTrueFalseTotal
if $has_i 71 441 512
1053  
1054 # Some data types do not support nan and inf, so check for and warn or croak,
1055 # as appropriate:
1056 512 ▶ if ($has_nan and not $types[$type]->usenan) {
Branch: 1 branch
BranchTrueFalseTotal
if ($has_nan and not $types[$type]->usenan) 0 512 512
Condition66%2/3
$has_nan and not $types[$type]->usenan
!ll&&!rl&&r
499130
MC/DC0%0/2
$has_nan and not $types[$type]->usenan
$has_nan not $types[$type]->usenan
Truth table66%2/3
A and not(B)
A= $has_nanB= not $types[$type]->usenan
ABresult
0X0
100
111
1057 0 carp("PDL::Core::new_pdl_from_string: no nan for type $types[$type]; converting to bad value");
1058 0 $value =~ s/ee/EE/g;
1059 0 $has_bad += $has_nan;
1060 0 $has_nan = 0;
1061 }
1062 512 ▶ croak("PDL::Core::new_pdl_from_string: type $types[$type] does not support inf")
Branch: 1 branch
BranchTrueFalseTotal
if $has_inf and not $types[$type]->usenan 0 512 512
Condition66%2/3
$has_inf and not $types[$type]->usenan
!ll&&!rl&&r
50480
MC/DC0%0/2
$has_inf and not $types[$type]->usenan
$has_inf not $types[$type]->usenan
Truth table66%2/3
A and not(B)
A= $has_infB= not $types[$type]->usenan
ABresult
0X0
100
111
1063 if ($has_inf and not $types[$type]->usenan);
1064  
1065 # Make the white-space uniform and see if any not-allowed characters are
1066 # present:
1067 512 $value =~ s/\s+/ /g;
1068 512 ▶ if (my ($disallowed) = ($value =~ /([^\[\]\+\-0-9;,.eE ]+)/)) {
Branch: 1 branch
BranchTrueFalseTotal
if (my($disallowed) = $value =~ /([^\[\]\+\-0-9;,.eE ]+)/) 4 508 512
1069 4 croak("PDL::Core::new_pdl_from_string: found disallowed character(s) '$disallowed' in '$original_value', value now: '$value'");
1070 }
1071  
1072 # Wrap the string in brackets [], so that the following works:
1073 # $x = PDL->new(q[1 2 3]);
1074 # We'll have to check for dimensions of size one after we've parsed
1075 # the string and built a PDL from the resulting array.
1076 508 $value = '[' . $value . ']';
1077  
1078 # Make sure that each closing bracket followed by an opening bracket
1079 # has a comma in between them:
1080 508 $value =~ s/\]\s*\[/],[/g;
1081  
1082 # Semicolons indicate 'start a new row' and require special handling:
1083 508 ▶ if ($value =~ /;/) {
Branch: 1 branch
BranchTrueFalseTotal
if ($value =~ /;/) 186 322 508
1084 186 $value =~ s/(\[[^\]]+;[^\]]+\])/[$1]/g;
1085 186 $value =~ s/;/],[/g;
1086 }
1087  
1088 # Remove ending decimal points and insert zeroes in front of starting
1089 # decimal points. This makes the white-space-to-comma replacement
1090 # in the next few lines much simpler.
1091 508 $value =~ s/(\d\.)(z|[^\d])/${1}0$2/g;
1092 508 $value =~ s/(\A|[^\d])\./${1}0./g;
1093  
1094 # Remove whitespace between signs and the numbers that follow them:
1095 508 $value =~ s/([+\-])\s+/$1/g;
1096  
1097 # Replace whitespace separators with commas:
1098 508 $value =~ s/([.\de])\s+(?=[+\-e\d])/$1,/gi;
1099  
1100 # Remove all other white space:
1101 508 $value =~ s/\s+//g;
1102  
1103 # Croak on operations with bad values. It might be nice to simply replace
1104 # these with bad values, but that is more difficult than I like, so I'm just
1105 # going to disallow that here:
1106 508 ▶ croak("PDL::Core::new_pdl_from_string: Operations with bad values are not supported")
Branch: 1 branch
BranchTrueFalseTotal
if $value =~ /EE[+\-]|[+\-]EE/ 0 508 508
1107 if($value =~ /EE[+\-]|[+\-]EE/);
1108  
1109 # Check for things that will evaluate as functions and croak if found
1110 508 ▶ if (my ($disallowed) = ($value =~ /((\D+|\A)[eE]\d+)/)) {
Branch: 1 branch
BranchTrueFalseTotal
if (my($disallowed) = $value =~ /((\D+|\A)[eE]\d+)/) 2 506 508
1111 2 croak("PDL::Core::new_pdl_from_string: syntax error, looks like an improper exponentiation: $disallowed\n"
1112 . "You originally gave me $original_value\n");
1113 }
1114  
1115 # Replace the place-holder strings with strings that will evaluate to their
1116 # correct numerical values
1117 506 ▶ my $bad = $has_bad ? $types[$type]->badvalue : undef;
Branch: 1 branch
BranchTrueFalseTotal
$has_bad ? : 106 400 506
1118 506 $value =~ s/\bEE\b/bad/g;
1119 506 $value =~ s/\bee\b/nan/g;
1120 506 ▶ $value =~ s/([-+]*)(\d*)EeE\b/$1 . (length($2) ? $2 : '1') . 'i'/ge
Branch: 2 branches
BranchTrueFalseTotal
if $has_i 71 435 506
length $2 ? : 95 59 154
1121 if $has_i;
1122 506 $value =~ s/\bEe\b/inf/g;
1123 506 $value =~ s/\beE\b/pi/g;
1124  
1125 506 my $val = eval {
1126 # Install the warnings handler:
1127 506 my $old_warn_handler = $SIG{__WARN__};
1128 0 ▶ local $SIG{__WARN__} = sub {
Subroutine __ANON__: not called CC=3 SCAR=24.8
1129 0 ▶ if ($_[0] =~ /(Argument ".*" isn't numeric)/) {
Branch: 2 branches
BranchTrueFalseTotal
if ($_[0] =~ /(Argument ".*" isn't numeric)/) { } 0 0 0
elsif ($old_warn_handler) { } 0 0 0
1130 # Send the error through die. This *always* gets caught, so keep
1131 # it simple.
1132 0 die "Incorrectly formatted input: $1\n";
1133 }
1134 elsif ($old_warn_handler) {
1135 0 $old_warn_handler->(@_);
1136 }
1137 else {
1138 0 warn @_;
1139 }
1140 506 };
1141  
1142 # Let's see if we can parse it as an array-of-arrays:
1143 506 local $_ = $value;
1144 506 PDL::Core::parse_basic_string($bad, $has_i);
1145 };
1146  
1147 506 ▶ if (ref $val ne 'ARRAY') {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $val ne "ARRAY") 4 502 506
1148 4 my @message = ("PDL::Core::new_pdl_from_string: string input='$original_value', string output='$value'" );
1149 4 ▶ push @message, $@ ||
Condition50%1/2
$@ || "Internal error: unexpected output type ->$val<- is not ARRAY ref"
l!l
40
MC/DC0%0/1
$@ || "Internal error: unexpected output type ->$val<- is not ARRAY ref"
$@
Truth table50%1/2
A
A= $@
Aresult
11
00
1150 "Internal error: unexpected output type ->$val<- is not ARRAY ref";
1151 4 croak join("\n ", @message);
1152 }
1153 502 my $to_return = PDL::Core::pdl_avref($val,$this,$type);
1154 502 ▶ if( $to_return->dim(-1) == 1 ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($to_return->dim(-1) == 1) 195 307 502
1155 195 ▶ if( $to_return->dims > 1 ) {
Branch: 2 branches
BranchTrueFalseTotal
if ($to_return->dims > 1) { } 154 41 195
elsif ($to_return->dims == 1) { } 41 0 41
1156 # remove potentially spurious last dimension
1157 154 $to_return = $to_return->mv(-1,1)->clump(2)->sever;
1158 } elsif( $to_return->dims == 1 ) {
1159 # fix scalar values
1160 41 $to_return->setdims([]);
1161 }
1162 }
1163 # Mark bad if appropriate
1164 502 $to_return->badflag($has_bad > 0);
1165 502 return $to_return;
1166 }
1167  
1168 71 my $NUM_RE = qr/(\d+(?:\.\d+)?(?:e[-+]?\d+)?)/i;
1169 1551 ▶sub PDL::Core::parse_basic_string {
Subroutine parse_basic_string: called CC=22 SCAR=30.9
Pod undocumented
1170 # Assumes $_ holds the string of interest, and modifies that value
1171 # in-place.
1172 71 ▶ use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
1173 # Takes a string with proper bracketing, etc, and returns an array-of-arrays
1174 # filled with numbers, suitable for use with pdl_avref. It uses recursive
1175 # descent to handle the nested nature of the data. The string should have
1176 # no whitespace and should be something that would evaluate into a Perl
1177 # array-of-arrays (except that strings like 'inf', etc, are allowed).
1178 1551 my ($bad, $has_i) = @_;
1179 # First character should be a bracket:
1180 1551 ▶ die "Internal error: input string -->$_<-- did not start with an opening bracket\n"
Branch: 1 branch
BranchTrueFalseTotal
unless s/^\[// 0 1551 1551
1181 unless s/^\[//;
1182 1551 my @to_return;
1183 # Loop until we run into our closing bracket:
1184 1551 my $sign = 1;
1185 1551 my $expects_number = 0;
1186 1551 ▶ SYMBOL: until (s/^\]//) {
Branch: 1 branch
BranchTrueFalseTotal
unless (s/^\]//) 5145 1547 6692
1187 # If we have a bracket, then go recursive:
1188 5630 ▶ if (/^\[/) {
Branch: 11 branches
BranchTrueFalseTotal
if (/^\[/) { } 1045 4585 5630
elsif (s/^\+//) { } 12 4573 4585
elsif (s/^\-//) { } 475 4098 4573
elsif (s/^bad//i) { } 169 3929 4098
elsif (s/^inf//i or s/1\.\#INF//i) { } 9 3920 3929
elsif (s/^nan//i or s/^1\.\#IND//i) { } 24 3896 3920
elsif (s/^pi//i) { } 3 3893 3896
elsif (s/^e//i) { } 13 3880 3893
elsif ($has_i and s/^${NUM_RE}i//i) { } 83 3797 3880
elsif ($has_i and s/^$NUM_RE([-+])${NUM_RE}i//i) { } 71 3726 3797
elsif (s/^$NUM_RE([^e])/$2/i) { } 3724 2 3726
1189 1045 ▶ die "Expected a number but found a bracket at ... ", substr ($_, 0, 10), "...\n"
Branch: 1 branch
BranchTrueFalseTotal
if $expects_number 0 1045 1045
1190 if $expects_number;
1191 1045 push @to_return, PDL::Core::parse_basic_string(@_);
1192 1045 next SYMBOL;
1193 }
1194 elsif (s/^\+//) {
1195 12 ▶ die "Expected number but found a plus sign at ... ", substr ($_, 0, 10), "...\n"
Branch: 1 branch
BranchTrueFalseTotal
if $expects_number 1 11 12
1196 if $expects_number;
1197 11 $expects_number = 1;
1198 11 redo SYMBOL;
1199 }
1200 elsif (s/^\-//) {
1201 475 ▶ die "Expected number but found a minus sign at ... ", substr ($_, 0, 10), "...\n"
Branch: 1 branch
BranchTrueFalseTotal
if $expects_number 1 474 475
1202 if $expects_number;
1203 474 $sign = -1;
1204 474 $expects_number = 1;
1205 474 redo SYMBOL;
1206 }
1207 elsif (s/^bad//i) {
1208 169 push @to_return, $bad;
1209 }
1210 ▶ elsif (s/^inf//i or s/1\.\#INF//i) {
Condition66%2/3
s/^inf//i or s/1\.\#INF//i
l!l&&r!l&&!r
903920
MC/DC50%1/2
s/^inf//i or s/1\.\#INF//i
s/^inf//i s/1\.\#INF//i
Truth table66%2/3
A or B
A= s/^inf//iB= s/1\.\#INF//i
ABresult
1X1
011
000
1211 9 push @to_return, $sign * $STR_inf;
1212 }
1213 ▶ elsif (s/^nan//i or s/^1\.\#IND//i) {
Condition66%2/3
s/^nan//i or s/^1\.\#IND//i
l!l&&r!l&&!r
2403896
MC/DC50%1/2
s/^nan//i or s/^1\.\#IND//i
s/^nan//i s/^1\.\#IND//i
Truth table66%2/3
A or B
A= s/^nan//iB= s/^1\.\#IND//i
ABresult
1X1
011
000
1214 24 push @to_return, $sign * $STR_nan;
1215 }
1216 elsif (s/^pi//i) {
1217 3 push @to_return, $sign * $STR_pi;
1218 }
1219 elsif (s/^e//i) {
1220 13 push @to_return, $sign * $STR_e;
1221 }
1222 ▶ elsif ($has_i and s/^${NUM_RE}i//i) {
Condition100%3/3
$has_i and s/^${NUM_RE}i//i
!ll&&!rl&&r
363016783
MC/DC100%2/2
$has_i and s/^${NUM_RE}i//i
$has_i s/^${NUM_RE}i//i
Truth table100%3/3
A and B
A= $has_iB= s/^${NUM_RE}i//i
ABresult
0X0
100
111
1223 83 my $val = $sign * $1 * $STR_i;
1224 83 push @to_return, $val;
1225 }
1226 ▶ elsif ($has_i and s/^$NUM_RE([-+])${NUM_RE}i//i) {
Condition100%3/3
$has_i and s/^$NUM_RE([-+])${NUM_RE}i//i
!ll&&!rl&&r
36309671
MC/DC100%2/2
$has_i and s/^$NUM_RE([-+])${NUM_RE}i//i
$has_i s/^$NUM_RE([-+])${NUM_RE}i//i
Truth table100%3/3
A and B
A= $has_iB= s/^$NUM_RE([-+])${NUM_RE}i//i
ABresult
0X0
100
111
1227 71 my $val = $sign * $1;
1228 71 ▶ my $imag = $3 * ($2 eq '-' ? -1 : 1) * $STR_i;
Branch: 1 branch
BranchTrueFalseTotal
$2 eq '-' ? : 23 48 71
1229 71 push @to_return, $val + $imag;
1230 }
1231 elsif (s/^$NUM_RE([^e])/$2/i) {
1232 # Note that improper numbers are handled by the warning signal
1233 # handler
1234 3724 push @to_return, $sign * ($1 + 0x0);
1235 }
1236 else {
1237 2 die "Incorrectly formatted input at:\n ", substr($_, 0, 10), "...\n";
1238 }
1239 }
1240 # Strip off any commas
1241 continue {
1242 5141 $sign = 1;
1243 5141 $expects_number = 0;
1244 5141 s/^,//;
1245 }
1246 1547 return \@to_return;
1247 }
1248  
1249 71 my $MAX_TYPE = $types[-1]->enum; # use lexical @types from above
1250 4546 ▶sub _establish_type {
Subroutine _establish_type: called CC=7 SCAR=19.7
1251 4546 my ($item, $sofar) = @_;
1252 4546 ▶ barf("Error: $sofar > max type value($MAX_TYPE)") if $sofar > $MAX_TYPE;
Branch: 1 branch
BranchTrueFalseTotal
if $sofar > $MAX_TYPE 0 4546 4546
1253 4546 ▶ return $sofar if $sofar == $MAX_TYPE;
Branch: 1 branch
BranchTrueFalseTotal
if $sofar == $MAX_TYPE 0 4546 4546
1254 4546 ▶ return $PDL_CD if UNIVERSAL::isa($item, 'Math::Complex');
Branch: 1 branch
BranchTrueFalseTotal
if UNIVERSAL::isa($item, "Math::Complex") 7 4539 4546
1255 4539 ▶ return max($item->type->enum, $sofar) if UNIVERSAL::isa($item, 'PDL');
Branch: 1 branch
BranchTrueFalseTotal
if UNIVERSAL::isa($item, "PDL") 278 4261 4539
1256 4261 ▶ return $PDL_D if ref($item) ne 'ARRAY';
Branch: 1 branch
BranchTrueFalseTotal
if ref $item ne "ARRAY" 1927 2334 4261
1257 # only need to check first item for an array of complex vals
1258 2334 ▶ return $MAX_TYPE if _establish_type($item->[0], $sofar) == $MAX_TYPE;
Branch: 1 branch
BranchTrueFalseTotal
if _establish_type($item->[0], $sofar) == $MAX_TYPE 0 2334 2334
1259 # only need to recurse for items that are refs
1260 # as $sofar will be $PDL_D at a minimum
1261 2334 max ($sofar, map _establish_type($_, $sofar), grep ref, @$item);
1262 }
1263  
1264 15904 ▶sub PDL::new {
Subroutine new: called CC=24 SCAR=33.7
Pod undocumented
1265 15904 ▶ return $_[0]->copy if ref($_[0]) and UNIVERSAL::isa($_[0], 'PDL');
Branch: 1 branch
BranchTrueFalseTotal
if ref $_[0] and UNIVERSAL::isa($_[0], "PDL") 3 15901 15904
Condition66%2/3
ref $_[0] and UNIVERSAL::isa($_[0], "PDL")
!ll&&!rl&&r
1590103
MC/DC50%1/2
ref $_[0] and UNIVERSAL::isa($_[0], "PDL")
ref $_[0] UNIVERSAL::isa($_[0], "PDL")
Truth table66%2/3
A and B
A= ref $_[0]B= UNIVERSAL::isa($_[0], "PDL")
ABresult
0X0
100
111
1266 15901 my $this = shift;
1267 15901 ▶ my $type = ref($_[0]) eq 'PDL::Type' ? shift->enum : undef;
Branch: 1 branch
BranchTrueFalseTotal
ref $_[0] eq 'PDL::Type' ? : 7708 8193 15901
1268 15901 ▶ my $value = (@_ > 1 ? [@_] : shift);
Branch: 1 branch
BranchTrueFalseTotal
@_ > 1 ? : 6510 9391 15901
1269 15901 ▶ unless(defined $value) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $value) 116 15785 15901
1270 116 ▶ if($PDL::debug) {
Branch: 1 branch
BranchTrueFalseTotal
if ($PDL::debug) 0 116 116
1271 0 print STDERR "Warning: PDL::new converted undef to \$PDL::undefval ($PDL::undefval)\n";
1272 }
1273 116 ▶ $value = ($PDL::undefval//0)+0
Condition100%2/2
$PDL::undefval // 0
l!l
1151
MC/DC100%1/1
$PDL::undefval // 0
$PDL::undefval
Truth table100%2/2
A
A= $PDL::undefval
Aresult
11
00
1274 }
1275 15901 ▶ $type //= ref($value) ? _establish_type($value, $PDL_D) : $PDL_D;
Branch: 1 branch
BranchTrueFalseTotal
ref $value ? : 1262 6931 8193
Condition66%2/3
$type //= ref $value ? _establish_type($value, $PDL::Core::PDL_D) : $PDL::Core::PDL_D
l!l&&r!l&&!r
770881930
MC/DC0%0/2
$type //= ref $value ? _establish_type($value, $PDL::Core::PDL_D) : $PDL::Core::PDL_D
$type ref $value ? _establish_type($value, $PDL::Core::PDL_D) : $PDL::Core::PDL_D
Truth table66%2/3
A //= B
A= $typeB= ref $value ? _establish_type($value, $PDL::Core::PDL_D) : $PDL::Core::PDL_D
ABresult
1X1
011
000
1276  
1277 15901 ▶ return pdl_avref($value,$this,$type) if ref($value) eq "ARRAY";
Branch: 1 branch
BranchTrueFalseTotal
if ref $value eq "ARRAY" 7296 8605 15901
1278 8605 my $new = $this->initialize;
1279 8605 $new->set_datatype($type);
1280  
1281 8605 ▶ if (ref(\$value) eq "SCALAR") {
Branch: 3 branches
BranchTrueFalseTotal
if (ref \$value eq 'SCALAR') { } 8452 153 8605
elsif (builtin::blessed($value) and UNIVERSAL::isa($value, 'Math::Complex')) { } 1 152 153
elsif (builtin::blessed($value)) { } 152 0 152
1282 # The string processing is extremely slow. Benchmarks indicated that it
1283 # takes 10x longer to process a scalar number compared with normal Perl
1284 # conversion of a string to a number. So, only use the string processing
1285 # if the input looks like a real string, i.e. it doesn't look like a plain
1286 # number. Note that for our purposes, looks_like_number incorrectly
1287 # handles the strings 'inf' and 'nan' on Windows machines. We want to send
1288 # those to the string processing, so this checks for them in a way that
1289 # short-circuits the looks_like_number check.
1290 8452 ▶ if (PDL::Core::is_scalar_SvPOK($value)
Branch: 3 branches
BranchTrueFalseTotal
if (is_scalar_SvPOK($value) and $value =~ /inf/i || $value =~ /nan/i || !&Scalar::Util::looks_like_number($value)) { } 536 7916 8452
elsif (not $PDL::Core::CAN_PACK_QUAD and $PDL::Core::pack[$new->get_datatype] =~ /^q\*$/i) { } 0 7916 7916
elsif (not $PDL::Core::CAN_PACK_D and $PDL::Core::pack[$new->get_datatype] =~ /^(D\*|\(DD\)\*)$/) { } 0 7916 7916
Condition100%9/9
is_scalar_SvPOK($value) and $value =~ /inf/i || $value =~ /nan/i || !&Scalar::Util::looks_like_number($value)
!ll&&!rl&&r
79106536
$value =~ /inf/i or $value =~ /nan/i or not &Scalar::Util::looks_like_number($value)
l!l&&r!l&&!r
245126
$value =~ /inf/i or $value =~ /nan/i
l!l&&r!l&&!r
1410518
MC/DC100%4/4
is_scalar_SvPOK($value) and $value =~ /inf/i || $value =~ /nan/i || !&Scalar::Util::looks_like_number($value)
is_scalar_SvPOK($value) $value =~ /inf/i $value =~ /nan/i not &Scalar::Util::looks_like_number($value)
Truth table100%5/5
A and B or C or not(D)
A= is_scalar_SvPOK($value)B= $value =~ /inf/iC= $value =~ /nan/iD= not &Scalar::Util::looks_like_number($value)
ABCDresult
0XXX0
10000
11XX1
101X1
10011
1291 and ($value =~ /inf/i or $value =~ /nan/i
1292 or !Scalar::Util::looks_like_number($value))) {
1293 # new was passed a string argument that doesn't look like a number
1294 # so we can process as a Matlab-style data entry format.
1295 536 return PDL::Core::new_pdl_from_string($new,$value,$this,$type);
1296 ▶ } elsif (! $CAN_PACK_QUAD && $pack[$new->get_datatype] =~ /^q\*$/i ) {
Condition33%1/3
not $PDL::Core::CAN_PACK_QUAD and $PDL::Core::pack[$new->get_datatype] =~ /^q\*$/i
!ll&&!rl&&r
791600
MC/DC0%0/2
not $PDL::Core::CAN_PACK_QUAD and $PDL::Core::pack[$new->get_datatype] =~ /^q\*$/i
not $PDL::Core::CAN_PACK_QUAD $PDL::Core::pack[$new->get_datatype] =~ /^q\*$/i
Truth table33%1/3
not(A) and B
A= not $PDL::Core::CAN_PACK_QUADB= $PDL::Core::pack[$new->get_datatype] =~ /^q\*$/i
ABresult
0X0
100
111
1297 # special case when running on a perl without 64bit int support
1298 # we have to avoid pack("q", ...) in this case
1299 # because it dies with error: "Invalid type 'q' in pack"
1300 0 $new->setdims([]);
1301 0 set_c($new, [0], $value);
1302 ▶ } elsif (! $CAN_PACK_D && $pack[$new->get_datatype] =~ /^(\QD*\E|\Q(DD)*\E)$/ ) {
Condition33%1/3
not $PDL::Core::CAN_PACK_D and $PDL::Core::pack[$new->get_datatype] =~ /^(D\*|\(DD\)\*)$/
!ll&&!rl&&r
791600
MC/DC0%0/2
not $PDL::Core::CAN_PACK_D and $PDL::Core::pack[$new->get_datatype] =~ /^(D\*|\(DD\)\*)$/
not $PDL::Core::CAN_PACK_D $PDL::Core::pack[$new->get_datatype] =~ /^(D\*|\(DD\)\*)$/
Truth table33%1/3
not(A) and B
A= not $PDL::Core::CAN_PACK_DB= $PDL::Core::pack[$new->get_datatype] =~ /^(D\*|\(DD\)\*)$/
ABresult
0X0
100
111
1303 # if "D" is not available for pack(),
1304 # it dies with error: "Invalid type 'D' in pack".
1305 0 $new->setdims([]);
1306 0 set_c($new, [0], $value);
1307 } else {
1308 7916 $new->setdims([]);
1309 7916 ▶ if ($value) {
Branch: 1 branch
BranchTrueFalseTotal
if ($value) { } 7469 447 7916
1310 7469 $new->update_data_from( pack $pack[$new->get_datatype], $value );
1311 } else { # do nothing if 0 - allocdata already memsets to 0
1312 447 $new->make_physical;
1313 }
1314 }
1315 }
1316 ▶ elsif (blessed($value) and UNIVERSAL::isa($value, 'Math::Complex')) {
Condition66%2/3
builtin::blessed($value) and UNIVERSAL::isa($value, "Math::Complex")
!ll&&!rl&&r
01521
MC/DC50%1/2
builtin::blessed($value) and UNIVERSAL::isa($value, "Math::Complex")
builtin::blessed($value) UNIVERSAL::isa($value, "Math::Complex")
Truth table66%2/3
A and B
A= builtin::blessed($value)B= UNIVERSAL::isa($value, "Math::Complex")
ABresult
0X0
100
111
1317 1 $new->setdims([]);
1318 1 set_c($new, [], $value);
1319 }
1320 elsif (blessed($value)) { # Object
1321 152 $new = $value->copy;
1322 }
1323 else {
1324 0 barf("Can not interpret argument $value of type ".ref($value) );
1325 }
1326 8069 $new;
1327 }
1328  
1329  
1330 =head2 copy
1331  
1332 =for ref
1333  
1334 Make a physical copy of an ndarray
1335  
1336 =for usage
1337  
1338 $new = $old->copy;
1339  
1340 Since C<$new = $old> just makes a new reference, the
1341 C<copy> method is provided to allow real independent
1342 copies to be made.
1343  
1344 =cut
1345  
1346 1019 ▶sub PDL::copy {
Subroutine copy: called CC=5 SCAR=16.1
Pod undocumented
1347 1019 my $value = shift;
1348 1019 ▶ barf("Argument is an ".ref($value)." not an object") unless blessed($value);
Branch: 1 branch
BranchTrueFalseTotal
unless builtin::blessed($value) 0 1019 1019
1349 1019 ▶ return $value->nullcreate if $value->isnull;
Branch: 1 branch
BranchTrueFalseTotal
if $value->isnull 1 1018 1019
1350 # broadcastI(-1,[]) is just an identity vafftrans with broadcastid copying ;)
1351 1018 my $is_inplace = $value->is_inplace;
1352 1018 ▶ $value->set_inplace(0) if $is_inplace;
Branch: 1 branch
BranchTrueFalseTotal
if $is_inplace 4 1014 1018
1353 1018 my $ret = $value->broadcastI(-1,[])->sever;
1354 1018 ▶ $value->set_inplace(1) if $is_inplace;
Branch: 1 branch
BranchTrueFalseTotal
if $is_inplace 4 1014 1018
1355 1018 $ret;
1356 }
1357  
1358 =head2 hdr_copy
1359  
1360 =for ref
1361  
1362 Return an explicit copy of the header of a PDL.
1363  
1364 hdr_copy is just a wrapper for the internal routine _hdr_copy, which
1365 takes the hash ref itself. That is the routine which is used to make
1366 copies of the header during normal operations if the hdrcpy() flag of
1367 a PDL is set.
1368  
1369 General-purpose deep copies are expensive in perl, so some simple
1370 optimization happens:
1371  
1372 If the header is a tied array or a blessed hash ref with an associated
1373 method called C<copy>, then that ->copy method is called. Otherwise, all
1374 elements of the hash are explicitly copied. References are recursively
1375 deep copied.
1376  
1377 This routine seems to leak memory.
1378  
1379 =cut
1380  
1381 9 ▶sub PDL::hdr_copy {
Subroutine hdr_copy: called CC=1 SCAR=0.0
Pod undocumented
1382 9 my $pdl = shift;
1383 9 my $hdr = $pdl->gethdr;
1384 9 return PDL::_hdr_copy($hdr);
1385 }
1386  
1387 # Same as hdr_copy but takes a hash ref instead of a PDL.
1388 4736 ▶sub PDL::_hdr_copy {
Subroutine _hdr_copy: called CC=14 SCAR=35.0
1389 4736 my $hdr = shift;
1390 4736 my $tobj;
1391  
1392 4736 ▶ print "called _hdr_copy\n" if($PDL::debug);
Branch: 1 branch
BranchTrueFalseTotal
if $PDL::debug 0 4736 4736
1393  
1394 4736 ▶ unless( (ref $hdr)=~m/HASH/ ) {
Branch: 1 branch
BranchTrueFalseTotal
unless (ref($hdr) =~ /HASH/) 0 4736 4736
1395 0 ▶ print"returning undef\n" if($PDL::debug);
Branch: 1 branch
BranchTrueFalseTotal
if $PDL::debug 0 0 0
1396 0 return undef ;
1397 }
1398  
1399 4736 ▶ if($tobj = tied %$hdr) { #
Branch: 2 branches
BranchTrueFalseTotal
if ($tobj = tied %$hdr) { } 4634 102 4736
elsif (UNIVERSAL::can($hdr, 'copy')) { } 0 102 102
1400 4634 ▶ print "tied..."if($PDL::debug);
Branch: 1 branch
BranchTrueFalseTotal
if $PDL::debug 0 4634 4634
1401 4634 ▶ if(UNIVERSAL::can($tobj,"copy")) {
Branch: 1 branch
BranchTrueFalseTotal
if (UNIVERSAL::can($tobj, "copy")) 0 4634 4634
1402 0 my %rhdr;
1403 0 tie(%rhdr, ref $tobj, $tobj->copy);
1404 0 ▶ print "returning\n" if($PDL::debug);
Branch: 1 branch
BranchTrueFalseTotal
if $PDL::debug 0 0 0
1405 0 return \%rhdr;
1406 }
1407  
1408 # Astro::FITS::Header is special for now -- no copy method yet
1409 # but it is recognized. Once it gets a copy method this will become
1410 # vestigial:
1411  
1412 4634 ▶ if(UNIVERSAL::isa($tobj,"Astro::FITS::Header")) {
Branch: 1 branch
BranchTrueFalseTotal
if (UNIVERSAL::isa($tobj, "Astro::FITS::Header")) 4634 0 4634
1413 4634 ▶ print "Astro::FITS::Header..." if($PDL::debug);
Branch: 1 branch
BranchTrueFalseTotal
if $PDL::debug 0 4634 4634
1414 4634 my @cards = $tobj->cards;
1415 4634 my %rhdr;
1416 4634 tie(%rhdr,"Astro::FITS::Header", new Astro::FITS::Header(Cards=>\@cards));
1417 4634 ▶ print "returning\n" if($PDL::debug);
Branch: 1 branch
BranchTrueFalseTotal
if $PDL::debug 0 4634 4634
1418 4634 return \%rhdr;
1419 }
1420 }
1421 elsif(UNIVERSAL::can($hdr,"copy")) {
1422 0 ▶ print "found a copy method\n" if($PDL::debug);
Branch: 1 branch
BranchTrueFalseTotal
if $PDL::debug 0 0 0
1423 0 return $hdr->copy;
1424 }
1425  
1426 # We got here if it's an unrecognized tie or if it's a vanilla hash.
1427 102 ▶ print "Making a hash copy..." if($PDL::debug);
Branch: 1 branch
BranchTrueFalseTotal
if $PDL::debug 0 102 102
1428  
1429 102 return PDL::_deep_hdr_copy($hdr);
1430  
1431 }
1432  
1433 #
1434 # Sleazy deep-copier that gets most cases
1435 # --CED 14-April-2003
1436 #
1437  
1438 102 ▶sub PDL::_deep_hdr_copy {
Subroutine _deep_hdr_copy: called CC=11 SCAR=43.8
1439 102 my $val = shift;
1440  
1441 102 ▶ if(ref $val eq 'HASH') {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $val eq "HASH") 102 0 102
1442 102 my %a;
1443 102 ▶ @a{keys %$val} = map ref($_) ? PDL::_deep_hdr_copy($_) : $_, values %$val;
Branch: 1 branch
BranchTrueFalseTotal
ref $_ ? : 0 1211 1211
1444 102 return \%a;
1445 }
1446  
1447 0 ▶ return [map ref($_) ? PDL::_deep_hdr_copy($_) : $_, @$val] if ref $val eq 'ARRAY';
Branch: 2 branches
BranchTrueFalseTotal
if ref $val eq "ARRAY" 0 0 0
ref $_ ? : 0 0 0
1448  
1449 0 ▶ if(ref $val eq 'SCALAR') {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $val eq "SCALAR") 0 0 0
1450 0 my $x = $$val;
1451 0 return \$x;
1452 }
1453  
1454 0 ▶ if(ref $val eq 'REF') {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $val eq "REF") 0 0 0
1455 0 my $x = PDL::_deep_hdr_copy($$val);
1456 0 return \$x;
1457 }
1458  
1459 # Special case for PDLs avoids potential nasty header recursion...
1460 0 ▶ if(UNIVERSAL::isa($val,'PDL')) {
Branch: 1 branch
BranchTrueFalseTotal
if (UNIVERSAL::isa($val, "PDL")) 0 0 0
1461 0 my $h;
1462 0 ▶ $val->hdrcpy(0) if($h = $val->hdrcpy); # assignment
Branch: 1 branch
BranchTrueFalseTotal
if $h = $val->hdrcpy 0 0 0
1463 0 my $out = $val->copy;
1464 0 ▶ $val->hdrcpy($h) if($h);
Branch: 1 branch
BranchTrueFalseTotal
if $h 0 0 0
1465 0 return $out;
1466 }
1467  
1468 0 ▶ if(UNIVERSAL::can($val,'copy')) {
Branch: 1 branch
BranchTrueFalseTotal
if (UNIVERSAL::can($val, "copy")) 0 0 0
1469 0 return $val->copy;
1470 }
1471  
1472 0 $val;
1473 }
1474  
1475  
1476 =head2 unwind
1477  
1478 =for ref
1479  
1480 Return an ndarray which is the same as the argument except
1481 that all broadcastids have been removed.
1482  
1483 =for usage
1484  
1485 $y = $x->unwind;
1486  
1487 =cut
1488  
1489 0 ▶sub PDL::unwind {
Subroutine unwind: not called CC=1 SCAR=6.9
Pod undocumented
1490 0 my $value = shift;
1491 0 my $foo = $value->null();
1492 0 $foo .= $value->unbroadcast();
1493 0 return $foo;
1494 }
1495  
1496 =head2 make_physical
1497  
1498 =for ref
1499  
1500 Make sure the data portion of an ndarray can be accessed from XS code.
1501  
1502 =for example
1503  
1504 $x->make_physical;
1505 $x->call_my_xs_method;
1506  
1507 Ensures that an ndarray gets its own allocated copy of data. This obviously
1508 implies that there are certain ndarrays which do not have their own data.
1509 These are so called I<virtual> ndarrays that make use of the I<vaffine>
1510 optimisation (see L<PDL::Indexing>).
1511 They do not have their own copy of
1512 data but instead store only access information to some (or all) of another
1513 ndarray's data.
1514  
1515 Note: this function should not be used unless absolutely necessary
1516 since otherwise memory requirements might be severely increased. Instead
1517 of writing your own XS code with the need to call C<make_physical> you
1518 might want to consider using the PDL preprocessor
1519 (see L<PDL::PP>)
1520 which can be used to transparently access virtual ndarrays without the
1521 need to physicalise them (though there are exceptions).
1522  
1523 =head2 make_physvaffine
1524  
1525 =for ref
1526  
1527 A more "careful" function than C<make_physical>. For ndarrays
1528 without a vaffine transformation as parent, it will just call
1529 C<make_physical>. Otherwise, it will update the vaffine transformation
1530 bookkeeping.
1531  
1532 =head2 make_physdims
1533  
1534 =for ref
1535  
1536 Ensures the ndarray's dimensions are up to date including changes in
1537 parent's dimensions, and calling C<redodims>.
1538  
1539 =head2 trans_parent
1540  
1541 =for ref
1542  
1543 Returns a PDL::Trans object representing the transformation (PDL
1544 operation) that is the "parent" of this ndarray, or C<undef> if none.
1545  
1546 Such objects have these methods:
1547  
1548 =over
1549  
1550 =item parents
1551  
1552 Returns a list of ndarrays that are inputs to this trans.
1553  
1554 =item children
1555  
1556 Returns a list of ndarrays that are outputs to this trans (specified as
1557 C<[o]>, C<[oca]>, C<[io]>, or C<[t]> in C<Pars>).
1558  
1559 =item address
1560  
1561 The memory address of the struct.
1562  
1563 =item flags
1564  
1565 List of strings of flags set for this trans.
1566  
1567 =item affine
1568  
1569 Whether the trans is affine.
1570  
1571 =item offs
1572  
1573 Affine-only: the offset into the parent's data.
1574  
1575 =item incs
1576  
1577 Affine-only: the dimincs for each of the child's dims.
1578  
1579 =item ind_sizes
1580  
1581 The size of each named dim.
1582  
1583 =item inc_sizes
1584  
1585 The size of the inc for each use of a named dim.
1586  
1587 =item vtable
1588  
1589 This trans's vtable.
1590  
1591 =item C<< $vtable->name >>
1592  
1593 The function name from this vtable.
1594  
1595 =item C<< $vtable->flags >>
1596  
1597 List of strings of flags set for this vtable.
1598  
1599 =item C<< $vtable->par_names >>
1600  
1601 List of 2 array-refs of strings of names of input pars, then output pars,
1602 for this vtable.
1603  
1604 =back
1605  
1606 =head2 trans_children
1607  
1608 =for ref
1609  
1610 Returns a list of PDL::Trans objects (see L</trans_parent>) representing
1611 each transformation that has this ndarray as an input.
1612  
1613 =head2 address
1614  
1615 =for ref
1616  
1617 Returns the memory address of the ndarray's C<struct>.
1618  
1619 =head2 address_data
1620  
1621 =for ref
1622  
1623 Returns the value of the ndarray C<struct>'s C<data> member.
1624  
1625 =head2 set_donttouchdata
1626  
1627 =for ref
1628  
1629 Sets the C<PDL_DONTTOUCHDATA> flag and the C<nbytes> to the given
1630 value. Useful in memory-mapping functionality.
1631 The C<nbytes> can be omitted, in which case only the flag is set.
1632  
1633 =head2 nbytes
1634  
1635 =for ref
1636  
1637 Returns the ndarray's C<nbytes>.
1638  
1639 =head2 seed
1640  
1641 =for ref
1642  
1643 Returns the random seed being used by PDL's RNG.
1644  
1645 =head2 set_debugging
1646  
1647 =for ref
1648  
1649 Sets whether PDL operations print lots of debugging info to standard
1650 output. Returns the old value.
1651  
1652 =for example
1653  
1654 PDL::Core::set_debugging(1);
1655 # ... these operations will have debugging info printed to stdout
1656 PDL::Core::set_debugging(0); # turn it off again
1657  
1658 =head2 dummy
1659  
1660 =for ref
1661  
1662 Insert a 'dummy dimension' of given length (defaults to 1)
1663  
1664 No relation to the 'Dungeon Dimensions' in Discworld!
1665  
1666 Negative positions specify relative to last dimension,
1667 i.e. C<dummy(-1)> appends one dimension at end,
1668 C<dummy(-2)> inserts a dummy dimension in front of the
1669 last dim, etc.
1670  
1671 If you specify a dimension position larger than the existing
1672 dimension list of your PDL, the PDL gets automagically padded with extra
1673 dummy dimensions so that you get the dim you asked for, in the slot you
1674 asked for. This could cause you trouble if, for example,
1675 you ask for $x->dummy(5000,1) because $x will get 5,000 dimensions,
1676 each of rank 1.
1677  
1678 Because padding at the beginning of the dimension list moves existing
1679 dimensions from slot to slot, it's considered unsafe, so automagic
1680 padding doesn't work for large negative indices -- only for large
1681 positive indices.
1682  
1683 =for usage
1684  
1685 $y = $x->dummy($position[,$dimsize]);
1686  
1687 =for example
1688  
1689 pdl> p sequence(3)->dummy(0,3)
1690 [
1691 [0 0 0]
1692 [1 1 1]
1693 [2 2 2]
1694 ]
1695  
1696 pdl> p sequence(3)->dummy(3,2)
1697 [
1698 [
1699 [0 1 2]
1700 ]
1701 [
1702 [0 1 2]
1703 ]
1704 ]
1705  
1706 pdl> p sequence(3)->dummy(-3,2)
1707 Runtime error: PDL: For safety, <pos> < -(dims+1) forbidden in dummy. min=-2, pos=-3
1708  
1709 =cut
1710  
1711 621 ▶sub PDL::dummy($$;$) :lvalue {
Subroutine dummy: called CC=7 SCAR=19.5
Pod undocumented
1712 621 my ($pdl,$dim,$size) = @_;
1713 621 ▶ barf("Missing position argument to dummy()") unless defined $dim; # required argument
Branch: 1 branch
BranchTrueFalseTotal
unless defined $dim 0 621 621
1714 621 ▶ $dim = $pdl->getndims+1+$dim if $dim < 0;
Branch: 1 branch
BranchTrueFalseTotal
if $dim < 0 54 567 621
1715 621 ▶ $size = defined($size) ? (1 * $size) : 1; # make $size a number (sf feature # 3479009)
Branch: 1 branch
BranchTrueFalseTotal
defined $size ? : 348 273 621
1716 621 ▶ barf("For safety, <pos> < -(dims+1) forbidden in dummy. min="
Branch: 1 branch
BranchTrueFalseTotal
if $dim < 0 0 621 621
1717 . -($pdl->getndims+1).", pos=". ($dim-1-$pdl->getndims) ) if($dim<0);
1718 # Avoid negative repeat count warning that came with 5.21 and later.
1719 621 my $dim_diff = $dim - $pdl->getndims;
1720 621 ▶ my($s) = ',' x ( $dim_diff > 0 ? $pdl->getndims : $dim );
Branch: 1 branch
BranchTrueFalseTotal
$dim_diff > 0 ? : 3 618 621
1721 621 ▶ $s .= '*1,' x ( $dim_diff > 0 ? $dim_diff : 0 );
Branch: 1 branch
BranchTrueFalseTotal
$dim_diff > 0 ? : 3 618 621
1722 621 $s .= "*$size";
1723 621 $pdl->slice($s);
1724 }
1725  
1726 =head2 dup
1727  
1728 =for ref
1729  
1730 Duplicates an ndarray along a dimension
1731  
1732 =for example
1733  
1734 $x = sequence(3);
1735 $y = $x->dup(0, 2); # doubles along first dimension
1736 # $y now [0 1 2 0 1 2]
1737  
1738 =cut
1739  
1740 1 ▶sub PDL::dup {
Subroutine dup: called CC=2 SCAR=7.1
Pod undocumented
1741 1 my ($this, $dim, $times) = @_;
1742 1 ▶ return $this->copy if $times == 1;
Branch: 1 branch
BranchTrueFalseTotal
if $times == 1 0 1 1
1743 1 $this->dummy($dim+1, $times)->clump($dim, $dim+1);
1744 }
1745  
1746 =head2 dupN
1747  
1748 =for ref
1749  
1750 Duplicates an ndarray along several dimensions
1751  
1752 =for example
1753  
1754 $x = sequence(3,2);
1755 $y = $x->dupN(2, 3); # doubles along first dimension, triples along second
1756 # [
1757 # [0 1 2 0 1 2]
1758 # [3 4 5 3 4 5]
1759 # [0 1 2 0 1 2]
1760 # [3 4 5 3 4 5]
1761 # [0 1 2 0 1 2]
1762 # [3 4 5 3 4 5]
1763 # ]
1764  
1765 =cut
1766  
1767 1 ▶sub PDL::dupN {
Subroutine dupN: called CC=3 SCAR=11.0
Pod undocumented
1768 1 my ($this, @times) = @_;
1769 1 ▶ return $this->copy if !grep $_ != 1, @times;
Branch: 1 branch
BranchTrueFalseTotal
unless grep(($_ != 1), @times) 0 1 1
1770 1 my $sl = join ',', map ":,*$_", @times; # insert right-size dummy after each real
1771 1 $this = $this->slice($sl);
1772 1 $this = $this->clump($_, $_+1) for 0..$#times;
1773 1 $this;
1774 }
1775  
1776 =head2 inflateN
1777  
1778 =for ref
1779  
1780 Inflates an ndarray along several dimensions, useful for e.g. Kronecker products
1781  
1782 cf L</dupN>
1783  
1784 =for example
1785  
1786 $x = sequence(3,2);
1787 $y = $x->inflateN(2, 2); # doubles along first two dimensions
1788 # [
1789 # [0 0 1 1 2 2]
1790 # [0 0 1 1 2 2]
1791 # [3 3 4 4 5 5]
1792 # [3 3 4 4 5 5]
1793 # ]
1794  
1795 =cut
1796  
1797 1 ▶sub PDL::inflateN {
Subroutine inflateN: called CC=3 SCAR=11.0
Pod undocumented
1798 1 my ($this, @times) = @_;
1799 1 ▶ return $this->copy if !grep $_ != 1, @times;
Branch: 1 branch
BranchTrueFalseTotal
unless grep(($_ != 1), @times) 0 1 1
1800 1 my $sl = join ',', map "*$_,:", @times;
1801 1 $this = $this->slice($sl);
1802 1 $this = $this->clump($_, $_+1) for 0..$#times;
1803 1 $this;
1804 }
1805  
1806 =head2 clump
1807  
1808 =for ref
1809  
1810 "clumps" several dimensions into one large dimension
1811  
1812 If called with one argument C<$n> clumps the first C<$n>
1813 dimensions into one. For example, if C<$x> has dimensions
1814 C<(5,3,4)> then after
1815  
1816 =for example
1817  
1818 $y = $x->clump(2); # Clump 2 first dimensions
1819  
1820 the variable C<$y> will have dimensions C<(15,4)>
1821 and the element C<$y-E<gt>at(7,3)> refers to the element
1822 C<$x-E<gt>at(1,2,3)>.
1823  
1824 Use C<clump(-1)> to flatten an ndarray. The method L<flat|PDL::Core/flat>
1825 is provided as a convenient alias.
1826  
1827 Clumping with a negative dimension in general leaves that many
1828 dimensions behind -- e.g. clump(-2) clumps all of the first few
1829 dimensions into a single one, leaving a 2-D ndarray.
1830  
1831 If C<clump> is called with an index list with more than one element
1832 it is treated as a list of dimensions that should be clumped together
1833 into one. The resulting
1834 clumped dim is placed at the position of the lowest index in the list.
1835 This convention ensures that C<clump> does the expected thing in
1836 the usual cases. The following examples demonstrate usage:
1837  
1838 zeroes(2,3,5,7)->clump(-1)->info # PDL: Double D [210]
1839 zeroes(2,3,5,7)->clump(-2)->info # PDL: Double D [30,7]
1840 zeroes(2,3,5,7)->clump(2)->info # PDL: Double D [6,5,7]
1841 zeroes(2,3,5,7)->clump(3)->info # PDL: Double D [30,7]
1842 zeroes(2,3,5,7)->clump(1,2)->info # PDL: Double D [2,15,7]
1843 zeroes(2,3,5,7)->clump(1,3)->info # PDL: Double D [2,21,5]
1844  
1845 Data flows back and forth as usual with slicing routines.
1846  
1847 =cut
1848  
1849 8453 ▶sub PDL::clump :lvalue {
Subroutine clump: called CC=8 SCAR=20.9
Pod undocumented
1850 8453 ▶ goto &PDL::_clump_int if @_ < 3;
Branch: 1 branch
BranchTrueFalseTotal
if @_ < 3 8418 35 8453
1851 35 my ($this,@dims) = @_;
1852 35 my $ndims = $this->getndims;
1853 35 my $targd = $ndims-1;
1854 35 my @dimmark = (0..$ndims-1);
1855 35 ▶ barf "too many dimensions" if @dims > $ndims;
Branch: 1 branch
BranchTrueFalseTotal
if @dims > $ndims 0 35 35
1856 35 for my $dim (@dims) {
1857 70 ▶ barf "dimension index $dim larger than greatest dimension"
Branch: 1 branch
BranchTrueFalseTotal
if $dim > $ndims - 1 0 70 70
1858 if $dim > $ndims-1 ;
1859 70 ▶ $targd = $dim if $targd > $dim;
Branch: 1 branch
BranchTrueFalseTotal
if $targd > $dim 35 35 70
1860 70 ▶ barf "duplicate dimension $dim" if $dimmark[$dim]++ > $dim;
Branch: 1 branch
BranchTrueFalseTotal
if $dimmark[$dim]++ > $dim 0 70 70
1861 }
1862 35 my $clumped = $this->broadcast(@dims)->unbroadcast(0)->clump(scalar @dims);
1863 35 ▶ $clumped = $clumped->mv(0,$targd) if $targd > 0;
Branch: 1 branch
BranchTrueFalseTotal
if $targd > 0 29 6 35
1864 35 return $clumped;
1865 }
1866  
1867 =head2 broadcast_define
1868  
1869 =for ref
1870  
1871 define functions that support broadcasting at the perl level
1872  
1873 =for example
1874  
1875 broadcast_define 'tline(a(n);b(n))', over {
1876 line $_[0], $_[1]; # make line compliant with broadcasting
1877 };
1878  
1879  
1880 C<broadcast_define> provides some support for broadcasting (see
1881 L<PDL::Indexing>) at the perl level. It allows you to do things for
1882 which you normally would have resorted to PDL::PP (see L<PDL::PP>);
1883 however, it is most useful to wrap existing perl functions so that the
1884 new routine supports PDL broadcasting.
1885  
1886 C<broadcast_define> is used to define new I<broadcasting aware>
1887 functions. Its first argument is a symbolic repesentation of the new
1888 function to be defined. The string is composed of the name of the new
1889 function followed by its signature (see L<PDL::Indexing> and L<PDL::PP>)
1890 in parentheses. The second argument is a subroutine that will be
1891 called with the slices of the actual runtime arguments as specified by
1892 its signature. Correct dimension sizes and minimal number of
1893 dimensions for all arguments will be checked (assuming the rules of
1894 PDL broadcasting, see L<PDL::Indexing>).
1895  
1896 The actual work is done by the C<signature> class which parses the signature
1897 string, does runtime dimension checks and the routine C<broadcastover> that
1898 generates the loop over all appropriate slices of pdl arguments and creates
1899 pdls as needed.
1900  
1901 Similar to C<pp_def> and its C<OtherPars> option it is possible to
1902 define the new function so that it accepts normal perl args as well as
1903 ndarrays. You do this by using the C<NOtherPars> parameter in the
1904 signature. The number of C<NOtherPars> specified will be passed
1905 unaltered into the subroutine given as the second argument of
1906 C<broadcast_define>. Let's illustrate this with an example:
1907  
1908 PDL::broadcast_define 'triangles(inda();indb();indc()), NOtherPars => 2',
1909 PDL::over {
1910 ${$_[3]} .= $_[4].join(',',map {$_->at} @_[0..2]).",-1,\n";
1911 };
1912  
1913 This defines a function C<triangles> that takes 3 ndarrays as input
1914 plus 2 arguments which are passed into the routine unaltered. This routine
1915 is used to collect lists of indices into a perl scalar that is passed by
1916 reference. Each line is preceded by a prefix passed as C<$_[4]>. Here is
1917 typical usage:
1918  
1919 $txt = '';
1920 triangles(pdl(1,2,3),pdl(1),pdl(0),\$txt," "x10);
1921 print $txt;
1922  
1923 resulting in the following output
1924  
1925 1,1,0,-1,
1926 2,1,0,-1,
1927 3,1,0,-1,
1928  
1929 which is used in
1930 L<PDL::Graphics::TriD::VRML>
1931 to generate VRML output.
1932  
1933 Currently, this is probably not much more than a POP (proof of principle)
1934 but is hoped to be useful enough for some real life work.
1935  
1936 Check L<PDL::PP> for the format of the signature. Currently, the
1937 C<[t]> qualifier and all type qualifiers are ignored.
1938  
1939 =cut
1940  
1941 6 ▶sub PDL::over (&) { $_[0] }
Subroutine over: called CC=1 SCAR=0.0
Pod undocumented
1942 6 ▶sub PDL::broadcast_define ($$) {
Subroutine broadcast_define: called CC=6 SCAR=18.0
Pod undocumented
1943 6 require PDL::PP::Signature;
1944 6 my ($str,$sub) = @_;
1945 6 my $others = 0;
1946 6 ▶ if ($str =~ s/[,]*\s*NOtherPars\s*=>\s*([0-9]+)\s*[,]*//) {$others = $1}
Branch: 1 branch
BranchTrueFalseTotal
if ($str =~ s/[,]*\s*NOtherPars\s*=>\s*([0-9]+)\s*[,]*//) 4 2 6
1947 6 ▶ barf "invalid string $str" unless $str =~ /\s*([^(]+)\((.+)\)\s*$/x;
Branch: 1 branch
BranchTrueFalseTotal
unless $str =~ /\s*([^(]+)\((.+)\)\s*$/x 0 6 6
1948 6 my ($name,$sigstr) = ($1,$2);
1949 6 ▶ print "defining '$name' with signature '$sigstr' and $others extra args\n"
Branch: 1 branch
BranchTrueFalseTotal
if $PDL::debug 0 6 6
1950 if $PDL::debug;
1951 6 my $sig = PDL::PP::Signature->new($sigstr);
1952 6 my $args = @{$sig->names}; # number of ndarray arguments
1953 6 ▶ barf "no ndarray args" if $args == 0;
Branch: 1 branch
BranchTrueFalseTotal
if $args == 0 0 6 6
1954 6 $args--;
1955 # TODO: $sig->dimcheck(@_) + proper creating generation
1956 6 my $package = caller;
1957 6 ▶ print "defining... $name\n" if $PDL::debug;
Branch: 1 branch
BranchTrueFalseTotal
if $PDL::debug 0 6 6
1958 71 ▶ no strict 'refs';
Subroutine BEGIN: called CC=1 SCAR=0.0
1959 6 ▶ *{"$package\::$name"} = sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
1960 12 @_[0..$args] = map PDL::Core::topdl($_), @_[0..$args];
1961 12 $sig->checkdims(@_);
1962 10 PDL::broadcastover($sub,$sig->realdims,$sig->creating,$others,@_);
1963 6 };
1964 }
1965  
1966 =head2 broadcast
1967  
1968 =for ref
1969  
1970 Use explicit broadcasting over specified dimensions (see also L<PDL::Indexing>)
1971  
1972 =for usage
1973  
1974 $y = $x->broadcast($dim,[$dim1,...])
1975  
1976 =for example
1977  
1978 $x = zeroes 3,4,5;
1979 $y = $x->broadcast(2,0);
1980 print $y->info; # PDL: Double D [4] T1 [5,3]
1981 $pb = zeroes(3,3);
1982 print $pb->broadcast(0,1)->info; # PDL: Double D [] T1 [3,3]
1983 print $pb->broadcast(0)->info; # 'PDL: Double D [3] T1 [3]
1984 print zeroes(4,7,2,8)->broadcast(2)->info; # PDL: Double D [4,7,8] T1 [2]
1985 print zeroes(4,7,2,8)->broadcast(2,1)->info; # PDL: Double D [4,8] T1 [2,7]
1986 print zeroes(4,7,2,8,5,6)->broadcast(2,4)->info; # PDL: Double D [4,7,8,6] T1 [2,5]
1987 print zeroes(4,7,2,8,5,6)->broadcast1(2)->broadcast2(3)->info; # PDL: Double D [4,7,8,6] T1 [2] T2 [5]
1988  
1989 Same as L</broadcast1>, i.e. uses broadcast id 1.
1990 To use broadcast id 2, use L</broadcast2>, or L<PDL::Slices/broadcastI>
1991 directly.
1992  
1993 =cut
1994  
1995 95 ▶sub PDL::broadcast :lvalue {
Subroutine broadcast: called CC=1 SCAR=0.0
Pod undocumented
1996 95 my $var = shift;
1997 95 $var->broadcastI(1,\@_);
1998 }
1999  
2000 =head2 broadcast1
2001  
2002 =for ref
2003  
2004 Explicit broadcasting over specified dims using broadcast id 1.
2005  
2006 =for usage
2007  
2008 $xx = $x->broadcast1(3,1)
2009  
2010 Convenience function interfacing to
2011 L<PDL::Slices::broadcastI|PDL::Slices/broadcastI>.
2012  
2013 =cut
2014  
2015 1 ▶sub PDL::broadcast1 {
Subroutine broadcast1: called CC=1 SCAR=0.0
Pod undocumented
2016 1 my $var = shift;
2017 1 $var->broadcastI(1,\@_);
2018 }
2019  
2020 =head2 broadcast2
2021  
2022 =for ref
2023  
2024 Explicit broadcasting over specified dims using broadcast id 2.
2025  
2026 =for usage
2027  
2028 $xx = $x->broadcast2(3,1)
2029  
2030 Convenience function interfacing to
2031 L<PDL::Slices::broadcastI|PDL::Slices/broadcastI>.
2032  
2033 =cut
2034  
2035 1 ▶sub PDL::broadcast2 {
Subroutine broadcast2: called CC=1 SCAR=0.0
Pod undocumented
2036 1 my $var = shift;
2037 1 $var->broadcastI(2,\@_);
2038 }
2039  
2040 =head2 broadcast3
2041  
2042 =for ref
2043  
2044 Explicit broadcasting over specified dims using broadcast id 3.
2045  
2046 =for usage
2047  
2048 $xx = $x->broadcast3(3,1)
2049  
2050 Convenience function interfacing to
2051 L<PDL::Slices::broadcastI|PDL::Slices/broadcastI>.
2052  
2053 =cut
2054  
2055 0 ▶sub PDL::broadcast3 {
Subroutine broadcast3: not called CC=1 SCAR=6.9
Pod undocumented
2056 0 my $var = shift;
2057 0 $var->broadcastI(3,\@_);
2058 }
2059  
2060 my %info = (
2061 D => {
2062 Name => 'Dimension',
2063 Sub => \&PDL::Core::dimstr,
2064 },
2065 T => {
2066 Name => 'Type',
2067 93 ▶ Sub => sub { return $_[0]->type->shortctype; },
Subroutine __ANON__: called CC=1 SCAR=0.0
2068 },
2069 S => {
2070 Name => 'State',
2071 37 ▶ Sub => sub { my $state = '';
Subroutine __ANON__: called CC=7 SCAR=21.2
2072 37 ▶ $state .= 'P' if $_[0]->allocated;
Branch: 1 branch
BranchTrueFalseTotal
if $_[0]->allocated 37 0 37
2073 37 ▶ $state .= 'V' if $_[0]->vaffine &&
Branch: 1 branch
BranchTrueFalseTotal
if $_[0]->vaffine and not $_[0]->allocated 0 37 37
Condition33%1/3
$_[0]->vaffine and not $_[0]->allocated
!ll&&!rl&&r
3700
MC/DC0%0/2
$_[0]->vaffine and not $_[0]->allocated
$_[0]->vaffine not $_[0]->allocated
Truth table33%1/3
A and not(B)
A= $_[0]->vaffineB= not $_[0]->allocated
ABresult
0X0
100
111
2074 !$_[0]->allocated; # apparently can be both?
2075 37 ▶ $state .= '-' if $state eq ''; # lazy eval
Branch: 1 branch
BranchTrueFalseTotal
if $state eq "" 0 37 37
2076 37 ▶ $state .= 'C' if $_[0]->anychgd;
Branch: 1 branch
BranchTrueFalseTotal
if $_[0]->anychgd 0 37 37
2077 37 ▶ $state .= 'B' if $_[0]->badflag;
Branch: 1 branch
BranchTrueFalseTotal
if $_[0]->badflag 2 35 37
2078 37 $state;
2079 },
2080 },
2081 M => {
2082 Name => 'Mem',
2083 6 ▶ Sub => sub { my ($size,$unit) = ($_[0]->allocated ?
Subroutine __ANON__: called CC=3 SCAR=13.3
Branch: 1 branch
BranchTrueFalseTotal
$_[0]->allocated ? : 6 0 6
2084 $_[0]->nelem*
2085 PDL::howbig($_[0]->get_datatype)/1024 : 0, 'KB');
2086 0 ▶ if ($size > 0.01*1024) { $size /= 1024;
Branch: 1 branch
BranchTrueFalseTotal
if ($size > "10.24") 0 6 6
2087 0 $unit = 'MB' };
2088 6 return sprintf "%6.2f%s",$size,$unit;
2089 },
2090 },
2091 C => {
2092 Name => 'Class',
2093 12 ▶ Sub => sub { ref $_[0] }
Subroutine __ANON__: called CC=1 SCAR=0.0
2094 },
2095 A => {
2096 Name => 'Address',
2097 71 ▶ Sub => sub { use Config;
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine __ANON__: not called CC=1 SCAR=1.2
2098 0 my $ivdformat = $Config{ivdformat};
2099 0 $ivdformat =~ s/"//g;
2100 0 sprintf "%$ivdformat", $_[0]->address }
2101 },
2102 71 );
2103  
2104 # print the dimension information about a pdl in some appropriate form
2105 48 ▶sub dimstr {
Subroutine dimstr: called CC=3 SCAR=11.0
Pod undocumented
2106 48 my $this = shift;
2107  
2108 48 my @dims = $this->dims;
2109 48 my @ids = $this->broadcastids;
2110 48 my ($nids,$i) = ($#ids,0);
2111 48 my $dstr = 'D ['. join(',',@dims[0..($ids[0]-1)]) .']';
2112 48 ▶ if ($nids > 0) {
Branch: 1 branch
BranchTrueFalseTotal
if ($nids > 0) 6 42 48
2113 6 for $i (1..$nids) {
2114 7 $dstr .= " T$i [". join(',',@dims[$ids[$i-1]..$ids[$i]-1]) .']';
2115 }
2116 }
2117 48 return $dstr;
2118 }
2119  
2120 =head2 sever
2121  
2122 =for ref
2123  
2124 sever any links of this ndarray to parent ndarrays
2125  
2126 In PDL it is possible for an ndarray to be just another
2127 view into another ndarray's data. In that case we call
2128 this ndarray a I<virtual ndarray> and the original ndarray owning
2129 the data its parent. In other languages these alternate views
2130 sometimes run by names such as I<alias> or I<smart reference>.
2131  
2132 Typical functions that return such ndarrays are C<slice>, C<xchg>,
2133 C<index>, etc. Sometimes, however, you would like to separate the
2134 I<virtual ndarray> from its parent's data and just give it a life of
2135 its own (so that manipulation of its data doesn't change the parent).
2136 This is simply achieved by using C<sever>. For example,
2137  
2138 =for example
2139  
2140 $x = $pdl->index(pdl(0,3,7))->sever;
2141 $x++; # important: $pdl is not modified!
2142  
2143 In many (but not all) circumstances it acts therefore similar to
2144 L<copy|PDL::Core/copy>.
2145 However, in general performance is better with C<sever> and secondly,
2146 C<sever> doesn't lead to futile copying when used on ndarrays that
2147 already have their own data. On the other hand, if you really want to make
2148 sure to work on a copy of an ndarray use L<copy|PDL::Core/copy>.
2149  
2150 $x = zeroes(20);
2151 $x->sever; # NOOP since $x is already its own boss!
2152  
2153 Again note: C<sever> I<is not> the same as L<copy|PDL::Core/copy>!
2154 For example,
2155  
2156 $x = zeroes(1); # $x does not have a parent, i.e. it is not a slice etc
2157 $y = $x->sever; # $y is now pointing to the same ndarray as $x
2158 $y++;
2159 print $x;
2160 [1]
2161  
2162 but
2163  
2164 $x = zeroes(1);
2165 $y = $x->copy; # $y is now pointing to a new ndarray
2166 $y++;
2167 print $x;
2168 [0]
2169  
2170  
2171 =head2 info
2172  
2173 =for ref
2174  
2175 Return formatted information about an ndarray.
2176  
2177 =for usage
2178  
2179 $x->info($format_string);
2180  
2181 =for example
2182  
2183 print $x->info("Type: %T Dim: %-15D State: %S");
2184  
2185 Returns a string with info about an ndarray. Takes an optional
2186 argument to specify the format of information a la sprintf.
2187 Format specifiers are in the form C<%E<lt>widthE<gt>E<lt>letterE<gt>>
2188 where the width is optional and the letter is one of
2189  
2190 =over 7
2191  
2192 =item T
2193  
2194 Type
2195  
2196 =item D
2197  
2198 Formatted Dimensions
2199  
2200 =item F
2201  
2202 Dataflow status
2203  
2204 =item S
2205  
2206 Some internal flags (P=physical,V=Vaffine,C=changed,B=may contain bad data)
2207  
2208 =item C
2209  
2210 Class of this ndarray, i.e. C<ref $pdl>
2211  
2212 =item A
2213  
2214 Address of the ndarray struct as a unique identifier
2215  
2216 =item M
2217  
2218 Calculated memory consumption of this ndarray's data area
2219  
2220 =back
2221  
2222 The default format is C<"%C: %T %D">.
2223 This can be modified by assigning to C<$PDL::infoformat>.
2224 =cut
2225  
2226 95 ▶sub PDL::info {
Subroutine info: called CC=6 SCAR=17.9
Pod undocumented
2227 95 my ($this,$str) = @_;
2228 95 ▶ $str = $PDL::infoformat unless defined $str;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $str 13 82 95
2229 95 ▶ return ref($this)."->null" if $this->isnull;
Branch: 1 branch
BranchTrueFalseTotal
if $this->isnull 1 94 95
2230 94 my @hash = split /(%[-,0-9]*[.]?[0-9]*\w)/, $str;
2231 94 my @args = ();
2232 94 my $nstr = '';
2233 94 for my $form (@hash) {
2234 423 ▶ if ($form =~ s/^%([-,0-9]*[.]?[0-9]*)(\w)$/%$1s/) {
Branch: 1 branch
BranchTrueFalseTotal
if ($form =~ s/^%([-,0-9]*[.]?[0-9]*)(\w)$/%$1s/) 196 227 423
2235 196 ▶ barf "unknown format specifier $2" unless defined $info{$2};
Branch: 1 branch
BranchTrueFalseTotal
unless defined $info{$2} 0 196 196
2236 196 push @args, &{$info{$2}->{Sub}}($this);
2237 }
2238 423 $nstr .= $form;
2239 }
2240 94 return sprintf $nstr, @args;
2241 }
2242  
2243 =head2 pdump
2244  
2245 =for ref
2246  
2247 Returns a close analogue of the output of C<< $pdl->dump >> as a
2248 string. Like that C function, it will not cause any physicalisation of
2249 the ndarray.
2250  
2251 Not exported, and not inserted into the C<PDL> namespace.
2252  
2253 =for example
2254  
2255 print PDL::Core::pdump($pdl);
2256  
2257 =cut
2258  
2259 2 ▶sub pdump {
Subroutine pdump: called CC=9 SCAR=22.9
Pod documented
2260 2 my ($pdl) = @_;
2261 2 my @dims = $pdl->dims_nophys;
2262 2 my $svaddr = $pdl->address_datasv;
2263 2 my @lines = (
2264 2 "State: ${\join '|', $pdl->flags}",
2265 "Dims: (@dims)",
2266 2 ▶ "BroadcastIds: (@{[$pdl->broadcastids_nophys]})",
Branch: 1 branch
BranchTrueFalseTotal
!$svaddr ? : 1 1 2
2267 !$svaddr ? () : sprintf("datasv: 0x%x, refcnt: %d", $svaddr, $pdl->datasv_refcount),
2268 sprintf("data: 0x%x, nbytes: %d, nvals: %d", $pdl->address_data, $pdl->nbytes, $pdl->nelem_nophys),
2269 );
2270 2 ▶ push @lines, sprintf "Vaffine: 0x%x (parent)", $pdl->vaffine_from if $pdl->has_vafftrans;
Branch: 1 branch
BranchTrueFalseTotal
if $pdl->has_vafftrans 0 2 2
2271 2 ▶ push @lines, !$pdl->badflag ? () : (
Branch: 2 branches
BranchTrueFalseTotal
!$pdl->badflag ? : 2 0 2
$pdl->has_badvalue ? : 0 0 0
2272 "Badvalue (".($pdl->has_badvalue ? 'bespoke' : 'orig')."): " . $pdl->badvalue
2273 );
2274 2 ▶ push @lines, !$pdl->allocated ? '(not allocated)' :
Branch: 1 branch
BranchTrueFalseTotal
!$pdl->allocated ? : 1 1 2
2275 1 "First values: (@{[$pdl->firstvals_nophys]})",
2276 ;
2277 2 ▶ if (my $trans = $pdl->trans_parent) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $trans = $pdl->trans_parent) 1 1 2
2278 1 push @lines, grep length, split "\n", pdump_trans($trans);
2279 }
2280 2 ▶ if (my @trans_children = $pdl->trans_children) {
Branch: 1 branch
BranchTrueFalseTotal
if (my(@trans_children) = $pdl->trans_children) 0 2 2
2281 0 push @lines, "CHILDREN:";
2282 0 push @lines, map " $_", grep length, split "\n", pdump_trans($_) for @trans_children;
2283 }
2284 2 join '', "PDUMPING 0x${\sprintf '%x', $pdl->address}, datatype: ${\$pdl->get_datatype}\n", map " $_\n", @lines;
2285 }
2286  
2287 =head2 pdump_trans
2288  
2289 =for ref
2290  
2291 Returns a string representation of a C<PDL::Trans> object, a close
2292 analogue of part of the output of C<< $pdl->dump >>.
2293  
2294 Not exported, and not inserted into the C<PDL> namespace.
2295  
2296 =for example
2297  
2298 print PDL::Core::pdump_trans($pdl_trans);
2299  
2300 =cut
2301  
2302 2 ▶sub pdump_trans {
Subroutine pdump_trans: called CC=3 SCAR=11.1
Pod documented
2303 2 my ($trans) = @_;
2304 2 my $vtable = $trans->vtable;
2305 2 my @lines = (
2306 2 "State: ${\join '|', $trans->flags}",
2307 2 "bvalflag: ${\$trans->bvalflag}",
2308 2 "vtable flags: ${\join '|', $vtable->flags}",
2309 );
2310 2 my @ins = $trans->parents;
2311 2 my @outs = $trans->children;
2312 2 ▶ push @lines,
Branch: 2 branches
BranchTrueFalseTotal
if $trans->affine 2 0 2
$outs[0]->dimschgd ? : 2 0 2
2313 "AFFINE, " . ($outs[0]->dimschgd
2314 ? "BUT DIMSCHANGED"
2315 0 : "o:".$trans->offs." i:(@{[$trans->incs]}) d:(@{[$outs[0]->dims_nophys]})")
2316 if $trans->affine;
2317 2 push @lines,
2318 2 "ind_sizes: (@{[$trans->ind_sizes]})",
2319 2 "inc_sizes: (@{[$trans->inc_sizes]})",
2320 2 "trans_children_indices: (@{[$trans->trans_children_indices]})",
2321 2 "INPUTS: (@{[map sprintf('0x%x', $_->address), @ins]}) OUTPUTS: (@{[map sprintf('0x%x', $_->address), @outs]})",
2322 ;
2323 2 join '', "PDUMPTRANS 0x${\sprintf '%x', $trans->address} (${\$vtable->name})\n", map " $_\n", @lines;
2324 }
2325  
2326 =head2 pdumphash
2327  
2328 =for ref
2329  
2330 Returns a hash-ref representing the information about a given object
2331 (C<PDL::Trans> or ndarray) and all the objects of either type it is
2332 connected to. Includes similar information to that shown by L</pdump>
2333 and L</pdump_trans>.
2334  
2335 Not exported, and not inserted into the C<PDL> namespace.
2336  
2337 =for example
2338  
2339 $hashref = PDL::Core::pdumphash($pdl_trans); # or
2340 $hashref = PDL::Core::pdumphash($pdl);
2341  
2342 =cut
2343  
2344 # only look at each obj once, mutates the hash
2345 12 ▶sub pdumphash {
Subroutine pdumphash: called CC=13 SCAR=26.5
Pod documented
2346 12 my ($obj, $sofar) = @_;
2347 12 ▶ confess "expected object but got '$obj'" if !ref $obj;
Branch: 1 branch
BranchTrueFalseTotal
unless ref $obj 0 12 12
2348 12 ▶ $sofar ||= {};
Condition66%2/3
$sofar ||= {}
l!l
930
MC/DC100%1/1
$sofar ||= {}
$sofar
Truth table100%2/2
A
A= $sofar
Aresult
11
00
2349 12 my $addr = sprintf '0x%x', $obj->address; # both ndarray and trans
2350 12 ▶ return $sofar if $sofar->{$addr};
Branch: 1 branch
BranchTrueFalseTotal
if $sofar->{$addr} 0 12 12
2351 12 ▶ if ($obj->isa('PDL::Trans')) {
Branch: 1 branch
BranchTrueFalseTotal
if ($obj->isa('PDL::Trans')) { } 4 8 12
2352 4 my $vtable = $obj->vtable;
2353 4 my @ins = $obj->parents;
2354 4 my @outs = $obj->children;
2355 4 ▶ $sofar->{$addr} = {
Branch: 1 branch
BranchTrueFalseTotal
!($obj->affine && !$outs[0]->dimschgd) ? : 4 0 4
Condition66%2/3
$obj->affine && !$outs[0]->dimschgd
!ll&&!rl&&r
220
MC/DC0%0/2
$obj->affine && !$outs[0]->dimschgd
$obj->affine !$outs[0]->dimschgd
Truth table66%2/3
A && not(B)
A= $obj->affineB= !$outs[0]->dimschgd
ABresult
0X0
100
111
2356 kind => 'trans',
2357 name => $vtable->name,
2358 flags => [$obj->flags],
2359 vtable_flags => [$vtable->flags],
2360 par_names => [$vtable->par_names],
2361 !($obj->affine && !$outs[0]->dimschgd) ? () : (
2362 0 affine => "o:".$obj->offs." i:(@{[$obj->incs]}) d:(@{[$outs[0]->dims_nophys]})"
2363 ),
2364 ins => [map sprintf('0x%x', $_->address), @ins],
2365 outs => [map sprintf('0x%x', $_->address), @outs],
2366 };
2367 4 ▶ for my $r (@ins, @outs) { pdumphash($r, $sofar) if !$sofar->{sprintf '0x%x', $r->address}; }
Branch: 1 branch
BranchTrueFalseTotal
unless $$sofar{sprintf "0x%x", $r->address} 6 3 9
2368 } else {
2369 8 my @ins = grep defined, $obj->trans_parent;
2370 8 my @outs = $obj->trans_children;
2371 8 ▶ $sofar->{$addr} = {
Branch: 2 branches
BranchTrueFalseTotal
!$obj->has_vafftrans ? : 8 0 8
!$obj->allocated ? : 4 4 8
2372 kind => 'ndarray',
2373 datatype => $obj->get_datatype,
2374 flags => [$obj->flags],
2375 !$obj->has_vafftrans ? () : (
2376 vaffine_from => sprintf("0x%x", $obj->vaffine_from),
2377 ),
2378 !$obj->allocated ? () : (
2379 data => sprintf("0x%x", $obj->address_data),
2380 nbytes => $obj->nbytes,
2381 nelem_nophys => $obj->nelem_nophys,
2382 firstvals => [$obj->firstvals_nophys],
2383 ),
2384 ins => [map sprintf('0x%x', $_->address), @ins],
2385 outs => [map sprintf('0x%x', $_->address), @outs],
2386 };
2387 8 ▶ for my $r (@ins, @outs) { pdumphash($r, $sofar) if !$sofar->{sprintf '0x%x', $r->address}; }
Branch: 1 branch
BranchTrueFalseTotal
unless $$sofar{sprintf "0x%x", $r->address} 3 6 9
2388 }
2389 12 $sofar;
2390 }
2391  
2392 =head2 pdumpgraph
2393  
2394 =for ref
2395  
2396 Given a hash-ref returned by L</pdumphash>, returns a L<Graph> object
2397 representing the same information.
2398  
2399 Not exported, and not inserted into the C<PDL> namespace.
2400  
2401 =for example
2402  
2403 $g = PDL::Core::pdumphash($hashref);
2404  
2405 =cut
2406  
2407 0 ▶sub pdumpgraph {
Subroutine pdumpgraph: not called CC=6 SCAR=37.4
Pod documented
2408 0 my ($hash) = @_;
2409 0 require Graph;
2410 0 my $g = Graph->new(multiedged=>1);
2411 0 for my $addr (keys %$hash) {
2412 0 $g->set_vertex_attributes($addr, my $props = $hash->{$addr});
2413 0 ▶ if ($props->{kind} eq 'trans') {
Branch: 1 branch
BranchTrueFalseTotal
if ($props->{"kind"} eq "trans") 0 0 0
2414 0 my ($ins, $outs) = @$props{qw(ins outs)};
2415 0 $g->add_edge_by_id($ins->[$_], $addr, $_) for 0..$#$ins;
2416 0 $g->add_edge_by_id($addr, $outs->[$_], $_) for 0..$#$outs;
2417 }
2418 0 ▶ if (my $from = $props->{vaffine_from}) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $from = $props->{"vaffine_from"}) 0 0 0
2419 0 $g->add_edge_by_id($addr, $from, 'vaffine_from');
2420 }
2421 }
2422 0 $g;
2423 }
2424  
2425 =head2 pdumpgraphvizify
2426  
2427 =for ref
2428  
2429 Given a L<Graph> object returned by L</pdumpgraph>, modifies it suitable
2430 for input to L<GraphViz2/from_graph>, then returns it. See example for
2431 how to use.
2432  
2433 Not exported, and not inserted into the C<PDL> namespace.
2434  
2435 =for example
2436  
2437 $g = PDL::Core::pdumpgraphvizify($g);
2438  
2439 # full example:
2440 $count = 1; $format = 'png'; sub output {
2441 $g = PDL::Core::pdumpgraph(PDL::Core::pdumphash($_[0]));
2442 require GraphViz2;
2443 $gv = GraphViz2->from_graph(PDL::Core::pdumpgraphvizify($g));
2444 $gv->run(format => $format, output_file => 'output'.$count++.".$format");
2445 }
2446 # keep changing ndarray, then calling this to show each state:
2447 output($pdl);
2448  
2449 # run the above script, then show the ndarray evolve over time, in a
2450 # left-to-right montage using ImageMagick tools:
2451 perl myscript.pl
2452 montage output* -tile "$(echo output*|wc -w)"x1 -geometry '1x1<' final.png
2453 display final.png
2454  
2455 =cut
2456  
2457 0 ▶sub pdumpgraphvizify {
Subroutine pdumpgraphvizify: not called CC=10 SCAR=47.0
Pod documented
2458 0 my ($g) = @_;
2459 0 for my $v ($g->vertices) {
2460 0 my $attrs = $g->get_vertex_attributes($v);
2461 0 my $kind = $attrs->{kind};
2462 0 ▶ if (my $from = $attrs->{vaffine_from}) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $from = $attrs->{"vaffine_from"}) 0 0 0
2463 0 $g->set_edge_attribute_by_id(
2464 $v, $from, 'vaffine_from',
2465 graphviz => { style => 'dashed', constraint => 'false' },
2466 );
2467 }
2468 0 my @blocks = join '', map "$_\\l", @{$attrs->{flags}};
2469 0 ▶ if ($kind eq 'trans') {
Branch: 1 branch
BranchTrueFalseTotal
if ($kind eq 'trans') { } 0 0 0
2470 0 my ($in_names, $out_names) = @{$attrs->{par_names}}[0,1];
2471 0 my ($ins, $outs) = @$attrs{qw(ins outs)};
2472 0 unshift @blocks, [map +{text=>$in_names->[$_],port=>"i$_"}, 0..$#$ins], $attrs->{name};
2473 $g->set_edge_attribute_by_id(
2474 $ins->[$_], $v, $_,
2475 graphviz => { headport => ["i$_","n"] },
2476 0 ) for 0..$#$ins;
2477 0 my @vflags = @{$attrs->{vtable_flags}};
2478 0 ▶ push @blocks, join '', map "$_\\l", @vflags ? @vflags : '(no vtable flags)';
Branch: 1 branch
BranchTrueFalseTotal
@vflags ? : 0 0 0
2479 0 my $affine = $attrs->{affine};
2480 0 ▶ push @blocks, $affine if $affine;
Branch: 1 branch
BranchTrueFalseTotal
if $affine 0 0 0
2481 0 push @blocks, [map +{text=>$out_names->[$_],port=>"o$_"}, 0..$#$outs];
2482 $g->set_edge_attribute_by_id(
2483 $v, $outs->[$_], $_,
2484 graphviz => { tailport => ["o$_","s"] },
2485 0 ) for 0..$#$outs;
2486 } else {
2487 0 my $firstvals = $attrs->{firstvals};
2488 0 ▶ $firstvals = ", (".($firstvals ? "@$firstvals" : 'not allocated').")";
Branch: 1 branch
BranchTrueFalseTotal
$firstvals ? : 0 0 0
2489 0 push @blocks, "datatype: $attrs->{datatype}$firstvals";
2490 }
2491 0 ▶ $g->set_vertex_attribute($v, graphviz => {
Branch: 1 branch
BranchTrueFalseTotal
$kind eq 'ndarray' ? : 0 0 0
2492 shape => 'record',
2493 color => $kind eq 'ndarray' ? 'blue' : 'red',
2494 label => [\@blocks],
2495 });
2496 }
2497 0 $g->set_graph_attribute(graphviz => {
2498 global => {directed => 1, combine_node_and_port => 0},
2499 graph => {concentrate => 'true', rankdir => 'TB'},
2500 });
2501 0 $g;
2502 }
2503  
2504 =head2 approx
2505  
2506 =for ref
2507  
2508 test for approximately equal values (relaxed C<==>)
2509  
2510 =for example
2511  
2512 # ok if all corresponding values in
2513 # ndarrays are within 1e-8 of each other
2514 print "ok\n" if all approx $x, $y, 1e-8;
2515  
2516 C<approx> is a relaxed form of the C<==> operator and
2517 often more appropriate for floating point types (C<float>
2518 C<double> and C<ldouble>).
2519  
2520 Usage:
2521  
2522 =for usage
2523  
2524 $res = approx $x, $y [, $eps]
2525  
2526 The optional parameter C<$eps> is remembered across invocations
2527 and initially set to 1e-6, e.g.
2528  
2529 approx $x, $y; # last $eps used (1e-6 initially)
2530 approx $x, $y, 1e-10; # 1e-10
2531 approx $x, $y; # also 1e-10
2532  
2533 =cut
2534  
2535 71 my $approx = 1e-6; # a reasonable init value
2536 19 ▶sub PDL::approx {
Subroutine approx: called CC=2 SCAR=6.9
Pod undocumented
2537 19 my ($x,$y,$eps) = @_;
2538 19 ▶ $eps = $approx unless defined $eps; # the default eps
Branch: 1 branch
BranchTrueFalseTotal
unless defined $eps 18 1 19
2539 19 $approx = $eps; # remember last eps
2540 19 PDL->topdl($x)->approx_artol($y, $eps);
2541 }
2542  
2543 =head2 mslice
2544  
2545 =for ref
2546  
2547 Alias to L<PDL::Slices/slice>.
2548  
2549 =cut
2550  
2551 71 *PDL::mslice = \&PDL::slice;
2552  
2553 =head2 nslice_if_pdl
2554  
2555 =for ref
2556  
2557 If C<$self> is a PDL, then calls C<slice> with all but the last
2558 argument, otherwise C<< $self->($_[-1]) >> is called where C<$_[-1]> is the
2559 original argument string found during PDL::NiceSlice filtering.
2560  
2561 DEVELOPER'S NOTE: this routine is found in Core.pm but would be
2562 better placed in Slices/slices.pd. It is likely to be moved there
2563 and/or changed to "slice_if_pdl" for PDL 3.0.
2564  
2565 =for usage
2566  
2567 $w = $x->nslice_if_pdl(...,'(args)');
2568  
2569 =cut
2570  
2571 1 ▶sub PDL::nslice_if_pdl :lvalue {
Subroutine nslice_if_pdl: called CC=2 SCAR=7.6
Pod undocumented
2572 1 my ($pdl) = shift;
2573 1 my ($orig_args) = pop;
2574  
2575 # warn "PDL::nslice_if_pdl called with (@_) args, originally ($orig_args)\n";
2576  
2577 1 ▶ if (ref($pdl) eq 'CODE') {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $pdl eq "CODE") 0 1 1
2578 # barf('PDL::nslice_if_pdl tried to process a sub ref, please use &$subref() syntax')
2579 0 @_ = eval $orig_args;
2580 0 goto &$pdl;
2581 }
2582  
2583 1 unshift @_, $pdl;
2584 1 goto &PDL::slice;
2585 }
2586  
2587 # Convert everything to PDL if not blessed
2588 1183 ▶sub alltopdl {
Subroutine alltopdl: called CC=5 SCAR=16.3
Pod undocumented
2589 1183 ▶ if (ref $_[2] eq 'PDL::Type') {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $_[2] eq "PDL::Type") 1123 60 1183
2590 1123 ▶ return convert($_[1], $_[2]) if blessed($_[1]);
Branch: 1 branch
BranchTrueFalseTotal
if builtin::blessed($_[1]) 398 725 1123
2591 725 ▶ return $_[0]->new($_[2], $_[1]) if $_[0] eq 'PDL';
Branch: 1 branch
BranchTrueFalseTotal
if $_[0] eq "PDL" 725 0 725
2592 }
2593 60 ▶ return $_[1] if blessed($_[1]); # Fall through
Branch: 1 branch
BranchTrueFalseTotal
if builtin::blessed($_[1]) 0 60 60
2594 60 return $_[0]->new($_[1]);
2595 }
2596  
2597 =head2 donttouch
2598  
2599 =for ref
2600  
2601 Returns whether the ndarray's C<PDL_DONTTOUCHDATA> flag is set.
2602  
2603 =head2 allocated
2604  
2605 =for ref
2606  
2607 Returns whether the ndarray's C<PDL_ALLOCATED> flag is set.
2608  
2609 =head2 vaffine
2610  
2611 =for ref
2612  
2613 Returns whether the ndarray's C<PDL_OPT_VAFFTRANSOK> flag is set.
2614  
2615 =head2 anychgd
2616  
2617 =for ref
2618  
2619 Returns whether the ndarray's C<PDL_ANYCHANGED> flag is set.
2620  
2621 =head2 dimschgd
2622  
2623 =for ref
2624  
2625 Returns whether the ndarray's C<PDL_PARENTDIMSCHANGED> flag is set.
2626  
2627 =head2 inplace
2628  
2629 =for ref
2630  
2631 Flag an ndarray so that the next operation is done 'in place', returning
2632 the ndarray.
2633  
2634 =for usage
2635  
2636 somefunc($x->inplace); somefunc(inplace $x);
2637  
2638 In most cases one likes to use the syntax C<$y = f($x)>, however
2639 in many case the operation C<f()> can be done correctly
2640 'in place', i.e. without making a new copy of the data for
2641 output. To make it easy to use this, we write C<f()> in such
2642 a way that it operates in-place, and use C<inplace> to hint
2643 that a new copy should be disabled. This also makes for
2644 clear syntax.
2645  
2646 Obviously this will not work for all functions, and if in
2647 doubt see the function's documentation. However one
2648 can assume this is
2649 true for all elemental functions (i.e. those which just
2650 operate array element by array element like C<log10>).
2651  
2652 =for example
2653  
2654 pdl> $x = xvals zeroes 10;
2655 pdl> log10(inplace $x)
2656 pdl> p $x
2657 [-inf 0 0.30103 0.47712125 0.60205999 0.69897 0.77815125 0.84509804 0.90308999 0.95424251]
2658  
2659 =head2 is_inplace
2660  
2661 =for ref
2662  
2663 Sets whether an ndarray will operate "in-place" for the next operation
2664 if a (Boolean) value is given. Returns the old value.
2665  
2666 =for usage
2667  
2668 $out = ($in->is_inplace) ? $in : zeroes($in);
2669 $in->set_inplace(0)
2670  
2671 Provides access to the L</inplace> hint flag, within the perl milieu.
2672 That way functions you write can be inplace aware... If given an
2673 argument the inplace flag will be set or unset depending on the value
2674 at the same time. Can be used for shortcut tests that delete the
2675 inplace flag while testing:
2676  
2677 $out = ($in->is_inplace(0)) ? $in : zeroes($in); # test & unset!
2678  
2679 =head2 set_inplace
2680  
2681 =for ref
2682  
2683 Set the in-place flag on an ndarray
2684  
2685 =for usage
2686  
2687 $out = ($in->is_inplace) ? $in : zeroes($in);
2688 $in->set_inplace(0);
2689  
2690 Provides access to the L</inplace> hint flag, within the perl milieu.
2691 Useful mainly for turning it OFF, as L</inplace> turns it ON more
2692 conveniently.
2693  
2694 =head2 new_or_inplace
2695  
2696 =for usage
2697  
2698 $w = new_or_inplace(shift());
2699 $w = new_or_inplace(shift(),$preferred_type);
2700  
2701 =for ref
2702  
2703 Return back either the argument pdl or a copy of it depending on whether
2704 it be flagged in-place or no. Handy for building inplace-aware functions.
2705  
2706 If you specify a preferred type (must be one of the usual PDL type strings,
2707 a list ref containing several of them, or a comma-separated string
2708 containing several of them),
2709 then the copy is coerced into the first preferred type listed if it is not
2710 already one of the preferred types.
2711  
2712 Note that if the inplace flag is set, no coercion happens even if you specify
2713 a preferred type.
2714  
2715 =cut
2716  
2717 544 ▶sub new_or_inplace {
Subroutine new_or_inplace: called CC=7 SCAR=19.5
Pod documented
2718 544 my $pdl = shift;
2719 544 ▶ if(blessed($pdl) && $pdl->is_inplace) {
Branch: 1 branch
BranchTrueFalseTotal
if (builtin::blessed($pdl) and $pdl->is_inplace) 43 501 544
Condition100%3/3
builtin::blessed($pdl) and $pdl->is_inplace
!ll&&!rl&&r
8641543
MC/DC100%2/2
builtin::blessed($pdl) and $pdl->is_inplace
builtin::blessed($pdl) $pdl->is_inplace
Truth table100%3/3
A and B
A= builtin::blessed($pdl)B= $pdl->is_inplace
ABresult
0X0
100
111
2720 43 $pdl->set_inplace(0);
2721 43 return $pdl;
2722 }
2723 501 my $preferred = shift;
2724 501 ▶ return blessed($pdl) ? $pdl->copy : null() if !defined $preferred;
Branch: 2 branches
BranchTrueFalseTotal
unless defined $preferred 500 1 501
builtin::blessed($pdl) ? : 414 86 500
2725 1 ▶ $preferred = [split ",",$preferred] if ref $preferred ne 'ARRAY';
Branch: 1 branch
BranchTrueFalseTotal
if ref $preferred ne "ARRAY" 1 0 1
2726 1 my $s = "".$pdl->type;
2727 1 ▶ return $pdl->copy if grep $_ eq $s, @$preferred; # the PDL is one of the preferred types.
Branch: 1 branch
BranchTrueFalseTotal
if grep(($_ eq $s), @$preferred) 0 1 1
2728 # No match - promote it to the first in the list.
2729 1 return $pdl->convert(PDL::Type->new($preferred->[0]));
2730 }
2731 71 *PDL::new_or_inplace = \&new_or_inplace;
2732  
2733 # Allow specifications like zeroes(10,10) or zeroes($x)
2734 # or zeroes(inplace $x) or zeroes(float,4,3)
2735  
2736 =head2 new_from_specification
2737  
2738 =for ref
2739  
2740 Internal method: create ndarray by specification
2741  
2742 This is the argument processing method called by L</zeroes>
2743 and some other functions
2744 which constructs ndarrays from argument lists of the form:
2745  
2746 [type], $nx, $ny, $nz,...
2747  
2748 For C<$nx>, C<$ny>, etc. 0 and 1D ndarrays are allowed.
2749 Giving those has the same effect as if saying C<$arg-E<gt>list>,
2750 e.g.
2751  
2752 1, pdl(5,2), 4
2753  
2754 is equivalent to
2755  
2756 1, 5, 2, 4
2757  
2758 Note, however, that in all functions using C<new_from_specification>
2759 calling C<func $ndarray> will probably not do what you want. So to play safe
2760 use (e.g. with zeroes)
2761  
2762 $pdl = zeroes $dimpdl->list;
2763  
2764 Calling
2765  
2766 $pdl = zeroes $dimpdl;
2767  
2768 will rather be equivalent to
2769  
2770 $pdl = zeroes $dimpdl->dims;
2771  
2772 However,
2773  
2774 $pdl = zeroes ushort, $dimpdl;
2775  
2776 will again do what you intended since it is interpreted
2777 as if you had said
2778  
2779 $pdl = zeroes ushort, $dimpdl->list;
2780  
2781 This is unfortunate and confusing but no good solution seems
2782 obvious that would not break existing scripts.
2783  
2784 =head2 isnull
2785  
2786 =for ref
2787  
2788 Test whether an ndarray is null
2789  
2790 =for usage
2791  
2792 croak("Input ndarray mustn't be null!")
2793 if $input_ndarray->isnull;
2794  
2795 This function returns 1 if the ndarray is null, zero if it is not. The purpose
2796 of null ndarrays is to "tell" any PDL::PP methods to allocate new memory for
2797 an output ndarray, but only when that PDL::PP method is called in full-arg
2798 form. Of course, there's no reason you couldn't commandeer the special value
2799 for your own purposes, for which this test function would prove most helpful.
2800 But in general, you shouldn't need to test for an ndarray's nullness.
2801  
2802 See L</Null PDLs> for more information.
2803  
2804 =head2 isempty
2805  
2806 =for ref
2807  
2808 Test whether an ndarray is empty
2809  
2810 =for usage
2811  
2812 print "The ndarray has zero dimension\n" if $pdl->isempty;
2813  
2814 This function returns 1 if the ndarray has zero elements. This is
2815 useful in particular when using the indexing function which. In the
2816 case of no match to a specified criterion, the returned ndarray has
2817 zero dimension.
2818  
2819 pdl> $w=sequence(10)
2820 pdl> $i=which($w < -1)
2821 pdl> print "I found no matches!\n" if ($i->isempty);
2822 I found no matches!
2823  
2824 Note that having zero elements is rather different from the concept
2825 of being a null ndarray, see the L<PDL::FAQ> and
2826 L<PDL::Indexing>
2827 manpages for discussions of this.
2828  
2829 =cut
2830  
2831 3876 ▶sub PDL::isempty {
Subroutine isempty: called CC=1 SCAR=0.0
Pod undocumented
2832 3876 my $pdl=shift;
2833 3876 return ($pdl->nelem == 0);
2834 }
2835  
2836 =head2 zeroes
2837  
2838 =for ref
2839  
2840 construct a zero filled ndarray from dimension list or template ndarray.
2841 If called with no arguments, returns a zero-dimension ndarray (a scalar).
2842  
2843 Various forms of usage,
2844  
2845 (i) by specification or (ii) by template ndarray:
2846  
2847 =for usage
2848  
2849 # usage type (i):
2850 $w = zeroes([type], $nx, $ny, $nz,...);
2851 $w = PDL->zeroes([type], $nx, $ny, $nz,...);
2852 $w = $pdl->zeroes([type], $nx, $ny, $nz,...); # all info about $pdl ignored
2853 # usage type (ii):
2854 $w = zeroes $y;
2855 $w = $y->zeroes
2856 zeroes inplace $w; # Equivalent to $w .= 0;
2857 $w->inplace->zeroes; # ""
2858  
2859 =for example
2860  
2861 pdl> $z = zeroes 4,3
2862 pdl> p $z
2863 [
2864 [0 0 0 0]
2865 [0 0 0 0]
2866 [0 0 0 0]
2867 ]
2868 pdl> $z = zeroes ushort, 3,2 # Create ushort array
2869 [ushort() etc. with no arg returns a PDL::Types token]
2870  
2871 See also L</new_from_specification>
2872 for details on using ndarrays in the dimensions list.
2873  
2874 =cut
2875  
2876 567 ▶sub zeroes { ref($_[0]) && ref($_[0]) ne 'PDL::Type' ? PDL::zeroes($_[0]) : PDL->zeroes(@_) }
Subroutine zeroes: called CC=3 SCAR=11.0
Pod documented
Branch: 1 branch
BranchTrueFalseTotal
ref $_[0] && ref $_[0] ne 'PDL::Type' ? : 12 555 567
Condition100%3/3
ref $_[0] and ref $_[0] ne "PDL::Type"
!ll&&!rl&&r
36519012
MC/DC100%2/2
ref $_[0] and ref $_[0] ne "PDL::Type"
ref $_[0] ref $_[0] ne "PDL::Type"
Truth table100%3/3
A and B
A= ref $_[0]B= ref $_[0] ne "PDL::Type"
ABresult
0X0
100
111
2877  
2878 # Create convenience aliases for zeroes
2879  
2880 =head2 zeros
2881  
2882 =for ref
2883  
2884 construct a zero filled ndarray (see zeroes for usage)
2885  
2886 =cut
2887  
2888 71 *zeros = \&zeroes;
2889 71 *PDL::zeros = \&PDL::zeroes;
2890  
2891 =head2 ones
2892  
2893 =for ref
2894  
2895 construct a one filled ndarray.
2896 If called with no arguments, returns a zero-dimension ndarray (a scalar).
2897  
2898 =for usage
2899  
2900 $w = ones([type], $nx, $ny, $nz,...);
2901 etc. (see 'zeroes')
2902  
2903 =for example
2904  
2905 see zeroes() and add one
2906  
2907 See also L</new_from_specification>
2908 for details on using ndarrays in the dimensions list.
2909  
2910 =cut
2911  
2912 1040 ▶sub _construct {
Subroutine _construct: called CC=4 SCAR=13.9
2913 1040 ▶ barf "No args given" if !@_;
Branch: 1 branch
BranchTrueFalseTotal
unless @_ 0 1040 1040
2914 1040 ▶ unshift @_, 'PDL' if !UNIVERSAL::can($_[0], 'new_from_specification');
Branch: 1 branch
BranchTrueFalseTotal
unless UNIVERSAL::can($_[0], "new_from_specification") 417 623 1040
2915 1040 ▶ @_>1 ? $_[0]->new_from_specification(@_[1..$#_]) : $_[0]->new_or_inplace;
Branch: 1 branch
BranchTrueFalseTotal
@_ > 1 ? : 671 369 1040
2916 }
2917 266 ▶sub ones { ref($_[0]) && ref($_[0]) ne 'PDL::Type' ? PDL::ones($_[0]) : PDL->ones(@_) }
Subroutine ones: called CC=3 SCAR=11.0
Pod documented
Branch: 1 branch
BranchTrueFalseTotal
ref $_[0] && ref $_[0] ne 'PDL::Type' ? : 59 207 266
Condition100%3/3
ref $_[0] and ref $_[0] ne "PDL::Type"
!ll&&!rl&&r
8512259
MC/DC100%2/2
ref $_[0] and ref $_[0] ne "PDL::Type"
ref $_[0] ref $_[0] ne "PDL::Type"
Truth table100%3/3
A and B
A= ref $_[0]B= ref $_[0] ne "PDL::Type"
ABresult
0X0
100
111
2918 371 ▶sub PDL::ones {
Subroutine ones: called CC=2 SCAR=7.6
Pod undocumented
2919 371 my $pdl = &_construct;
2920 371 ▶ $pdl .= ($pdl_ones[$pdl->get_datatype]//barf "Couldn't find 'one' for type ", $pdl->get_datatype);
Condition33%1/3
$PDL::Core::pdl_ones[$pdl->get_datatype] // barf("Couldn't find 'one' for type ", $pdl->get_datatype)
l!l&&r!l&&!r
37100
MC/DC0%0/2
$PDL::Core::pdl_ones[$pdl->get_datatype] // barf("Couldn't find 'one' for type ", $pdl->get_datatype)
$PDL::Core::pdl_ones[$pdl->get_datatype] barf("Couldn't find 'one' for type ", $pdl->get_datatype)
Truth table33%1/3
A // B
A= $PDL::Core::pdl_ones[$pdl->get_datatype]B= barf("Couldn't find 'one' for type ", $pdl->get_datatype)
ABresult
1X1
011
000
2921 371 return $pdl;
2922 }
2923  
2924 =head2 nan
2925  
2926 =for ref
2927  
2928 construct a C<NaN> filled ndarray.
2929 If called with no arguments, returns a zero-dimension ndarray (a scalar).
2930  
2931 =for usage
2932  
2933 $w = nan([type], $nx, $ny, $nz,...);
2934 etc. (see 'zeroes')
2935  
2936 =for example
2937  
2938 see zeroes() and add NaN
2939  
2940 See also L</new_from_specification>
2941 for details on using ndarrays in the dimensions list.
2942  
2943 =cut
2944  
2945 32 ▶sub nan { ref($_[0]) && ref($_[0]) ne 'PDL::Type' ? PDL::nan($_[0]) : PDL->nan(@_) }
Subroutine nan: called CC=3 SCAR=11.0
Pod documented
Branch: 1 branch
BranchTrueFalseTotal
ref $_[0] && ref $_[0] ne 'PDL::Type' ? : 1 31 32
Condition100%3/3
ref $_[0] and ref $_[0] ne "PDL::Type"
!ll&&!rl&&r
3011
MC/DC100%2/2
ref $_[0] and ref $_[0] ne "PDL::Type"
ref $_[0] ref $_[0] ne "PDL::Type"
Truth table100%3/3
A and B
A= ref $_[0]B= ref $_[0] ne "PDL::Type"
ABresult
0X0
100
111
2946 36 ▶sub PDL::nan {
Subroutine nan: called CC=1 SCAR=0.0
Pod undocumented
2947 36 my $pdl = &_construct;
2948 36 $pdl .= PDL::_nan();
2949 36 return $pdl;
2950 }
2951  
2952 =head2 inf
2953  
2954 =for ref
2955  
2956 construct an C<Inf> filled ndarray.
2957 If called with no arguments, returns a zero-dimension ndarray (a scalar).
2958  
2959 =for usage
2960  
2961 $w = inf([type], $nx, $ny, $nz,...);
2962 etc. (see 'zeroes')
2963  
2964 =for example
2965  
2966 see zeroes() and add Inf
2967  
2968 See also L</new_from_specification>
2969 for details on using ndarrays in the dimensions list.
2970  
2971 =cut
2972  
2973 17 ▶sub inf { ref($_[0]) && ref($_[0]) ne 'PDL::Type' ? PDL::inf($_[0]) : PDL->inf(@_) }
Subroutine inf: called CC=3 SCAR=11.0
Pod documented
Branch: 1 branch
BranchTrueFalseTotal
ref $_[0] && ref $_[0] ne 'PDL::Type' ? : 1 16 17
Condition100%3/3
ref $_[0] and ref $_[0] ne "PDL::Type"
!ll&&!rl&&r
1511
MC/DC100%2/2
ref $_[0] and ref $_[0] ne "PDL::Type"
ref $_[0] ref $_[0] ne "PDL::Type"
Truth table100%3/3
A and B
A= ref $_[0]B= ref $_[0] ne "PDL::Type"
ABresult
0X0
100
111
2974 21 ▶sub PDL::inf {
Subroutine inf: called CC=1 SCAR=0.0
Pod undocumented
2975 21 my $pdl = &_construct;
2976 21 $pdl .= PDL::_inf();
2977 21 return $pdl;
2978 }
2979  
2980 =head2 i
2981  
2982 =for ref
2983  
2984 construct an ndarray filled with a native complex value equal to the
2985 imaginary number "i", the square root of -1.
2986 If called with no arguments, returns a zero-dimension ndarray (a scalar).
2987  
2988 =for usage
2989  
2990 $w = i([type], $nx, $ny, $nz,...);
2991 etc. (see 'zeroes')
2992  
2993 =for example
2994  
2995 see zeroes() and add "i"
2996  
2997 See also L</new_from_specification>
2998 for details on using ndarrays in the dimensions list.
2999  
3000 =cut
3001  
3002 53 ▶sub i { ref($_[0]) && ref($_[0]) ne 'PDL::Type' ? PDL::i($_[0]) : PDL->i(@_) }
Subroutine i: called CC=3 SCAR=11.0
Pod documented
Branch: 1 branch
BranchTrueFalseTotal
ref $_[0] && ref $_[0] ne 'PDL::Type' ? : 1 52 53
Condition100%3/3
ref $_[0] and ref $_[0] ne "PDL::Type"
!ll&&!rl&&r
5111
MC/DC100%2/2
ref $_[0] and ref $_[0] ne "PDL::Type"
ref $_[0] ref $_[0] ne "PDL::Type"
Truth table100%3/3
A and B
A= ref $_[0]B= ref $_[0] ne "PDL::Type"
ABresult
0X0
100
111
3003 57 ▶sub PDL::i {
Subroutine i: called CC=7 SCAR=19.5
Pod undocumented
3004 57 my $class = shift;
3005 57 my @args = @_;
3006 57 ▶ if (@args) {
Branch: 1 branch
BranchTrueFalseTotal
if (@args) { } 7 50 57
3007 7 ▶ if (ref($args[0]) eq 'PDL::Type' and $args[0]->real) {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $args[0] eq 'PDL::Type' and $args[0]->real) { } 3 4 7
Condition66%2/3
ref $args[0] eq "PDL::Type" and $args[0]->real
!ll&&!rl&&r
403
MC/DC50%1/2
ref $args[0] eq "PDL::Type" and $args[0]->real
ref $args[0] eq "PDL::Type" $args[0]->real
Truth table66%2/3
A and B
A= ref $args[0] eq "PDL::Type"B= $args[0]->real
ABresult
0X0
100
111
3008 3 $args[0] = cdouble();
3009 } else {
3010 4 unshift @args, cdouble();
3011 }
3012 } else {
3013 50 ▶ $class = convert $class, cdouble() if ref $class and $class->type->real;
Branch: 1 branch
BranchTrueFalseTotal
if ref $class and $class->type->real 2 48 50
Condition66%2/3
ref $class and $class->type->real
!ll&&!rl&&r
4802
MC/DC50%1/2
ref $class and $class->type->real
ref $class $class->type->real
Truth table66%2/3
A and B
A= ref $classB= $class->type->real
ABresult
0X0
100
111
3014 }
3015 57 ▶ my $pdl = scalar(@args)? $class->new_from_specification(@args) : $class->new_or_inplace;
Branch: 1 branch
BranchTrueFalseTotal
scalar @args ? : 7 50 57
3016 57 $pdl .= PDL::_ci();
3017 57 return $pdl;
3018 }
3019  
3020 =head2 reshape
3021  
3022 =for ref
3023  
3024 Change the shape (i.e. dimensions) of an ndarray, preserving contents.
3025  
3026 =for usage
3027  
3028 $x->reshape(NEWDIMS); reshape($x, NEWDIMS);
3029  
3030 The data elements are preserved, obviously they will wrap
3031 differently and get truncated if the new array is shorter.
3032 If the new array is longer it will be zero-padded.
3033  
3034 ***Potential incompatibility with earlier versions of PDL****
3035 If the list of C<NEWDIMS> is empty C<reshape> will just drop
3036 all dimensions of size 1 (preserving the number of elements):
3037  
3038 $w = sequence(3,4,5);
3039 $y = $w(1,3);
3040 $y->reshape();
3041 print $y->info;
3042 PDL: Double D [5]
3043  
3044 Dimensions of size 1 will also be dropped if C<reshape> is
3045 invoked with the argument -1:
3046  
3047 $y = $w->reshape(-1);
3048  
3049 As opposed to C<reshape> without arguments, C<reshape(-1)>
3050 preserves dataflow:
3051  
3052 $w = ones(2,1,2);
3053 $y = $w(0)->reshape(-1);
3054 $y++;
3055 print $w;
3056 [
3057 [
3058 [2 1]
3059 ]
3060 [
3061 [2 1]
3062 ]
3063 ]
3064  
3065 Important: ndarrays are changed inplace!
3066  
3067 Note: If C<$x> is connected to any other PDL (e.g. if it is a slice)
3068 then the connection is first severed.
3069  
3070 =for example
3071  
3072 pdl> $x = sequence(10)
3073 pdl> reshape $x,3,4; p $x
3074 [
3075 [0 1 2]
3076 [3 4 5]
3077 [6 7 8]
3078 [9 0 0]
3079 ]
3080 pdl> reshape $x,5; p $x
3081 [0 1 2 3 4]
3082  
3083 =cut
3084  
3085 71 *reshape = \&PDL::reshape;
3086 161 ▶sub PDL::reshape :lvalue {
Subroutine reshape: called CC=10 SCAR=23.0
Pod undocumented
3087 161 my $pdl = topdl($_[0]);
3088 161 ▶ if (@_ == 2 && $_[1] == -1) { # a slicing reshape that drops 1-dims
Branch: 1 branch
BranchTrueFalseTotal
if (@_ == 2 and $_[1] == -1) 17 144 161
Condition100%3/3
@_ == 2 and $_[1] == -1
!ll&&!rl&&r
638117
MC/DC100%2/2
@_ == 2 and $_[1] == -1
@_ == 2 $_[1] == -1
Truth table100%3/3
A and B
A= @_ == 2B= $_[1] == -1
ABresult
0X0
100
111
3089 17 ▶ return $pdl->slice( map $_==1 ? [0,0,0] : [], $pdl->dims);
Branch: 1 branch
BranchTrueFalseTotal
$_ == 1 ? : 15 11 26
3090 }
3091 144 $pdl->sever;
3092 144 my $nelem = $pdl->nelem;
3093 barf "reshape: given non-scalar PDL as arg index $_"
3094 144 ▶ for grep UNIVERSAL::isa($_[$_], 'PDL') && $_[$_]->nelem != 1, 1..$#_;
Condition66%2/3
UNIVERSAL::isa($_[$_], 'PDL') && $_[$_]->nelem != 1
!ll&&!rl&&r
22110
MC/DC0%0/2
UNIVERSAL::isa($_[$_], 'PDL') && $_[$_]->nelem != 1
UNIVERSAL::isa($_[$_], 'PDL') $_[$_]->nelem != 1
Truth table66%2/3
A && B
A= UNIVERSAL::isa($_[$_], 'PDL')B= $_[$_]->nelem != 1
ABresult
0X0
100
111
3095 144 my @dims = grep defined, @_[1..$#_];
3096 144 ▶ for my $dim(@dims) { barf "reshape: invalid dim size '$dim'" if $dim < 0 }
Branch: 1 branch
BranchTrueFalseTotal
if $dim < 0 2 208 210
3097 142 ▶ @dims = grep($_ != 1, $pdl->dims) if @dims == 0; # get rid of dims of size 1
Branch: 1 branch
BranchTrueFalseTotal
if @dims == 0 2 140 142
3098 142 $pdl->setdims(\@dims);
3099 142 $pdl->make_physical;
3100 142 ▶ if ($pdl->nelem > $nelem) {
Branch: 1 branch
BranchTrueFalseTotal
if ($pdl->nelem > $nelem) 1 141 142
3101 1 my $tmp = $pdl->flat->slice("$nelem:-1");
3102 1 $tmp .= pdl($tmp->type, 0);
3103 }
3104 142 $_[0] = $pdl;
3105 142 return $pdl;
3106 }
3107  
3108 =head2 squeeze
3109  
3110 =for ref
3111  
3112 eliminate all singleton dimensions (dims of size 1)
3113  
3114 =for example
3115  
3116 $y = $w(0,0)->squeeze;
3117  
3118 Alias for C<reshape(-1)>. Removes all singleton dimensions
3119 and preserves dataflow. A more concise interface is
3120 provided by L<PDL::NiceSlice> via modifiers:
3121  
3122 use PDL::NiceSlice;
3123 $y = $w(0,0;-); # same as $w(0,0)->squeeze
3124  
3125 =cut
3126  
3127 71 *squeeze = \&PDL::squeeze;
3128 10 ▶sub PDL::squeeze { return $_[0]->reshape(-1) }
Subroutine squeeze: called CC=1 SCAR=0.0
Pod undocumented
3129  
3130 =head2 flat
3131  
3132 =for ref
3133  
3134 flatten an ndarray (alias for C<< $pdl->clump(-1) >>)
3135  
3136 =for example
3137  
3138 $srt = $pdl->flat->qsort;
3139  
3140 Useful method to make a 1D ndarray from an
3141 arbitrarily sized input ndarray. Data flows
3142 back and forth as usual with slicing routines.
3143 Falls through if argument already == 1D.
3144  
3145 =cut
3146  
3147 71 *flat = \&PDL::flat;
3148 10964 ▶sub PDL::flat :lvalue { # fall through if < 2D
Subroutine flat: called CC=2 SCAR=6.9
Pod undocumented
3149 10964 ▶ return my $dummy = $_[0]->getndims != 1 ? $_[0]->clump(-1) : $_[0];
Branch: 1 branch
BranchTrueFalseTotal
$_[0]->getndims != 1 ? : 8077 2887 10964
3150 }
3151  
3152 =head2 convert
3153  
3154 =for ref
3155  
3156 Generic datatype conversion function
3157  
3158 Works on ndarrays and normal numbers. Returns input if already that
3159 type.
3160  
3161 =for usage
3162  
3163 $y = convert($x, $newtype);
3164 $y = $x->convert($newtype);
3165 $x->inplace->convert($newtype);
3166  
3167 C<$newtype> is a type number or L<PDL::Type> object, for convenience they are
3168 returned by C<long()> etc when called without arguments.
3169 Can work in-place, though will C<sever> if so.
3170  
3171 =for example
3172  
3173 $y = convert $x, long;
3174 $y = $x->convert(ushort);
3175 $x->inplace->convert(double);
3176  
3177 =cut
3178  
3179 71 my $CONVERT_ERR = "Usage: \$y = convert(\$x, \$newtype)\n";
3180 676 ▶sub PDL::convert {
Subroutine convert: called CC=7 SCAR=19.5
Pod undocumented
3181 676 ▶ barf $CONVERT_ERR if @_ != 2;
Branch: 1 branch
BranchTrueFalseTotal
if @_ != 2 0 676 676
3182 676 my ($pdl,$type)= @_;
3183 676 $pdl = topdl($pdl); # Allow normal numbers
3184 676 ▶ barf "Tried to convert(null)" if $pdl->isnull;
Branch: 1 branch
BranchTrueFalseTotal
if $pdl->isnull 1 675 676
3185 675 ▶ $type = $type->enum if ref($type) eq 'PDL::Type';
Branch: 1 branch
BranchTrueFalseTotal
if ref $type eq "PDL::Type" 547 128 675
3186 675 ▶ barf $CONVERT_ERR unless Scalar::Util::looks_like_number($type);
Branch: 1 branch
BranchTrueFalseTotal
unless &Scalar::Util::looks_like_number($type) 0 675 675
3187 675 ▶ return $pdl if $pdl->get_datatype == $type;
Branch: 1 branch
BranchTrueFalseTotal
if $pdl->get_datatype == $type 292 383 675
3188 383 ▶ return $pdl->_convert_int($type)->sever if !$pdl->is_inplace;
Branch: 1 branch
BranchTrueFalseTotal
unless $pdl->is_inplace 376 7 383
3189 7 $pdl->set_inplace(0);
3190 7 $pdl->set_datatype($type);
3191 7 $pdl;
3192 }
3193  
3194 =head2 convert_flowing
3195  
3196 =for ref
3197  
3198 Generic datatype data-flowing conversion function
3199  
3200 =for usage
3201  
3202 $y = convert_flowing($x, $newtype);
3203 $y = $x->convert_flowing($newtype);
3204  
3205 C<$newtype> is a type number or L<PDL::Type> object, for convenience they are
3206 returned by C<long()> etc when called without arguments.
3207 Only works on ndarrays, not normal numbers. Returns input if already that
3208 type. Establishes two-way dataflow between the two ndarrays.
3209  
3210 =cut
3211  
3212 71 my $CONVERT_FLOW_ERR = "Usage: \$y = convert_flowing(\$pdl, \$newtype)\n";
3213 1 ▶sub PDL::convert_flowing {
Subroutine convert_flowing: called CC=8 SCAR=22.8
Pod undocumented
3214 1 ▶ barf $CONVERT_FLOW_ERR if @_ != 2;
Branch: 1 branch
BranchTrueFalseTotal
if @_ != 2 0 1 1
3215 1 my ($pdl,$type) = @_;
3216 1 ▶ barf $CONVERT_FLOW_ERR if !UNIVERSAL::isa($pdl, 'PDL');
Branch: 1 branch
BranchTrueFalseTotal
unless UNIVERSAL::isa($pdl, "PDL") 0 1 1
3217 1 ▶ barf "Tried to convert_flowing(null)" if $pdl->isnull;
Branch: 1 branch
BranchTrueFalseTotal
if $pdl->isnull 0 1 1
3218 1 ▶ barf "Cannot convert_flowing inplace" if $pdl->is_inplace;
Branch: 1 branch
BranchTrueFalseTotal
if $pdl->is_inplace 0 1 1
3219 1 ▶ $type = $type->enum if ref($type) eq 'PDL::Type';
Branch: 1 branch
BranchTrueFalseTotal
if ref $type eq "PDL::Type" 1 0 1
3220 1 ▶ barf $CONVERT_FLOW_ERR unless Scalar::Util::looks_like_number($type);
Branch: 1 branch
BranchTrueFalseTotal
unless &Scalar::Util::looks_like_number($type) 0 1 1
3221 1 ▶ return $pdl if $pdl->get_datatype == $type;
Branch: 1 branch
BranchTrueFalseTotal
if $pdl->get_datatype == $type 0 1 1
3222 1 $pdl->_convert_int($type);
3223 }
3224  
3225 =head2 Datatype_conversions
3226  
3227 =for ref
3228  
3229 sbyte|byte|short|ushort|long|ulong|indx|longlong|ulonglong|float|double|ldouble|cfloat|cdouble|cldouble (shorthands to convert datatypes)
3230  
3231 =for usage
3232  
3233 $y = double $x; $y = ushort [1..10];
3234 # all of the above listed shorthands behave similarly
3235  
3236 When called with an ndarray argument, they convert to the specific
3237 datatype.
3238  
3239 When called with a numeric, list, listref, or string argument they
3240 construct a new ndarray. This is a convenience to avoid having to be
3241 long-winded and say C<$x = long(pdl(42))>
3242  
3243 Thus one can say:
3244  
3245 $w = float(1,2,3,4); # 1D
3246 $w = float q[1 2 3; 4 5 6]; # 2D
3247 $w = float([1,2,3],[4,5,6]); # 2D
3248 $w = float([[1,2,3],[4,5,6]]); # 2D
3249  
3250 Note the last three give identical results, and the last two are exactly
3251 equivalent - a list is automatically converted to a list reference for
3252 syntactic convenience. i.e. you can omit the outer C<[]>
3253  
3254 When called with no arguments, these functions return a special type token.
3255 This allows syntactical sugar like:
3256  
3257 $x = ones byte, 1000,1000;
3258  
3259 This example creates a large ndarray directly as byte datatype in
3260 order to save memory.
3261  
3262 In order to control how undefs are handled in converting from perl lists to
3263 PDLs, one can set the variable C<$PDL::undefval>;
3264 see the function L<pdl()|/pdl> for more details.
3265  
3266 =for example
3267  
3268 pdl> p $x=sqrt float [1..10]
3269 [1 1.41421 1.73205 2 2.23607 2.44949 2.64575 2.82843 3 3.16228]
3270 pdl> p byte $x
3271 [1 1 1 2 2 2 2 2 3 3]
3272  
3273 =head2 byte
3274  
3275 Convert to byte datatype
3276  
3277 =head2 short
3278  
3279 Convert to short datatype
3280  
3281 =head2 ushort
3282  
3283 Convert to ushort datatype
3284  
3285 =head2 long
3286  
3287 Convert to long datatype
3288  
3289 =head2 indx
3290  
3291 Convert to indx datatype
3292  
3293 =head2 longlong
3294  
3295 Convert to longlong datatype
3296  
3297 =head2 float
3298  
3299 Convert to float datatype
3300  
3301 =head2 double
3302  
3303 Convert to double datatype
3304  
3305 =head2 ldouble
3306  
3307 Convert to long double datatype
3308  
3309 =head2 cfloat
3310  
3311 Convert to complex float datatype
3312  
3313 =head2 cdouble
3314  
3315 Convert to complex double datatype
3316  
3317 =head2 cldouble
3318  
3319 Convert to complex long double datatype
3320  
3321 =head2 type
3322  
3323 =for ref
3324  
3325 return the type of an ndarray as a blessed type object
3326  
3327 A convenience function for use with the ndarray constructors, e.g.
3328  
3329 =for example
3330  
3331 $y = PDL->zeroes($x->type,$x->dims,3);
3332 die "must be float" unless $x->type == float;
3333  
3334 See also the discussion of the C<PDL::Type> class in L<PDL::Types>.
3335 Note that the C<PDL::Type> objects have overloaded comparison and
3336 stringify operators so that you can compare and print types:
3337  
3338 $x = $x->float if $x->type < float;
3339 $t = $x->type; print "Type is $t\n";
3340  
3341 =cut
3342  
3343 13594 ▶sub PDL::type { return PDL::Type->new($_[0]->get_datatype); }
Subroutine type: called CC=1 SCAR=0.0
Pod undocumented
3344  
3345 ##################### Printing ####################
3346  
3347 =head2 string
3348  
3349 =for ref
3350  
3351 Convert ndarray to string, optionally using a C<sprintf> format. If such
3352 a format is provided, it is used. If not, then the formatting variables
3353 in L</VARIABLES> provide a default, though heuristics are attempted to
3354 make a nice-looking output.
3355  
3356 =for usage
3357  
3358 print $x; # overloaded
3359 print $x->string; # explicit method call
3360 print $x->string("%5d"); # providing sprintf format
3361  
3362 =cut
3363  
3364 71 $PDL::_STRINGIZING = 0;
3365  
3366 1559 ▶sub PDL::string {
Subroutine string: called CC=13 SCAR=26.1
Pod undocumented
3367 1559 my ($self,$format) = @_;
3368 1559 my $to_return = eval {
3369 1559 ▶ return "ALREADY_STRINGIZING_NO_LOOPS" if $PDL::_STRINGIZING;
Branch: 1 branch
BranchTrueFalseTotal
if $PDL::_STRINGIZING 373 1186 1559
3370 1186 local $PDL::_STRINGIZING = 1;
3371 1186 ▶ return "Null" if $self->isnull;
Branch: 1 branch
BranchTrueFalseTotal
if $self->isnull 10 1176 1186
3372 1176 ▶ return "Empty[".join("x",$self->dims)."]" if $self->isempty;
Branch: 1 branch
BranchTrueFalseTotal
if $self->isempty 7 1169 1176
3373 1169 ▶ return "TOO LONG TO PRINT" if $self->nelem > $PDL::toolongtoprint;
Branch: 1 branch
BranchTrueFalseTotal
if $self->nelem > $PDL::toolongtoprint 7 1162 1169
3374 1162 my $ndims = $self->getndims;
3375 1162 ▶ if ($ndims==0) {
Branch: 1 branch
BranchTrueFalseTotal
if ($ndims == 0) 737 425 1162
3376 737 ▶ return "BAD" if $self->badflag and $self->isbad;
Branch: 1 branch
BranchTrueFalseTotal
if $self->badflag and $self->isbad 13 724 737
Condition66%2/3
$self->badflag and $self->isbad
!ll&&!rl&&r
3643730
MC/DC0%0/2
$self->badflag and $self->isbad
$self->badflag $self->isbad
Truth table33%1/3
A and B
A= $self->badflagB= $self->isbad
ABresult
0X0
100
111
3377 724 my $x = $self->sclr;
3378 724 ▶ return $format ? sprintf($format, $x) : "$x";
Branch: 1 branch
BranchTrueFalseTotal
$format ? : 0 724 724
3379 }
3380 425 ▶ local $sep = $PDL::use_commas ? "," : " ";
Branch: 1 branch
BranchTrueFalseTotal
$PDL::use_commas ? : 0 425 425
3381 425 ▶ local $sep2 = $PDL::use_commas ? "," : "";
Branch: 1 branch
BranchTrueFalseTotal
$PDL::use_commas ? : 0 425 425
3382 425 ▶ return str1D($self,$format) if $ndims==1;
Branch: 1 branch
BranchTrueFalseTotal
if $ndims == 1 312 113 425
3383 113 return strND($self,$format,0);
3384 };
3385 1559 ▶ if ($@) {
Branch: 1 branch
BranchTrueFalseTotal
if ($@) 0 1559 1559
3386 # Remove reference to this line:
3387 0 $@ =~ s/\s*at .* line \d+\s*\.\n*/./;
3388 0 PDL::Core::barf("Stringizing problem: $@");
3389 }
3390 1559 return $to_return;
3391 }
3392  
3393 ############## Section/subsection functions ###################
3394  
3395 =head2 list
3396  
3397 =for ref
3398  
3399 Convert ndarray to perl list
3400  
3401 =for usage
3402  
3403 @tmp = list $x;
3404  
3405 Obviously this is grossly inefficient for the large datasets PDL is designed to
3406 handle. This was provided as a get out while PDL matured. It should now be mostly
3407 superseded by superior constructs, such as PP/broadcasting. However it is still
3408 occasionally useful and is provided for backwards compatibility.
3409  
3410 =for example
3411  
3412 for (list $x) {
3413 # Do something on each value...
3414 }
3415  
3416 =for bad
3417  
3418 list converts any bad values into the string 'BAD'.
3419  
3420 =cut
3421  
3422 # No broadcasting, just the ordinary dims.
3423 33 ▶sub PDL::list{ # pdl -> @list
Subroutine list: called CC=3 SCAR=11.3
Pod undocumented
3424 33 ▶ barf 'Usage: list($pdl)' if $#_!=0;
Branch: 1 branch
BranchTrueFalseTotal
if $#_ != 0 0 33 33
3425 33 my $pdl = PDL->topdl(shift);
3426 33 ▶ return () if nelem($pdl)==0;
Branch: 1 branch
BranchTrueFalseTotal
if nelem($pdl) == 0 0 33 33
3427 33 @{listref_c($pdl)};
3428 }
3429  
3430 =head2 unpdl
3431  
3432 =for ref
3433  
3434 Convert ndarray to nested Perl array references
3435  
3436 =for usage
3437  
3438 $arrayref = unpdl $x;
3439  
3440 This function returns a reference to a Perl list-of-lists structure
3441 equivalent to the input ndarray (within the limitation that while values
3442 of elements should be preserved, the detailed datatypes will not as
3443 perl itself basically has "number" data rather than byte, short, int...
3444 E.g., C<< sum($x - pdl( $x->unpdl )) >> should equal 0.
3445  
3446 Obviously this is grossly inefficient in memory and processing for the
3447 large datasets PDL is designed to handle. Sometimes, however, you really
3448 want to move your data back to Perl, and with proper dimensionality,
3449 unlike C<list>.
3450  
3451 If you want to round-trip data including the use of C<PDL::undefval>,
3452 C<unpdl> does not support this. However, it is suggested you would
3453 generate an index-set with C<< $pdl->whereND($pdl == $PDL::undefval)
3454 >>, then loop over the Perl data, setting those locations to C<undef>.
3455  
3456 Another round-trip caveat: a zero-dimensional ndarray (a scalar) will be
3457 returned as a single-element array-ref. This is conceptually incorrect,
3458 but cannot now be changed due to backward compatibility.
3459  
3460 =for example
3461  
3462 use JSON;
3463 my $json = encode_json unpdl $pdl;
3464  
3465 =for bad
3466  
3467 unpdl converts any bad values into the string 'BAD'.
3468  
3469 =cut
3470  
3471 =head2 listindices
3472  
3473 =for ref
3474  
3475 Convert ndarray indices to perl list
3476  
3477 =for usage
3478  
3479 @tmp = listindices $x;
3480  
3481 C<@tmp> now contains the values C<0..nelem($x)-1>.
3482  
3483 Obviously this is grossly inefficient for the large datasets PDL is designed to
3484 handle. This was provided as a get out while PDL matured. It should now be mostly
3485 superseded by superior constructs, such as PP/broadcasting. However it is still
3486 occasionally useful and is provied for backwards compatibility.
3487  
3488 =for example
3489  
3490 for $i (listindices $x) {
3491 # Do something on each value...
3492 }
3493  
3494 =cut
3495  
3496 0 ▶sub PDL::listindices{ # Return list of index values for 1D pdl
Subroutine listindices: not called CC=4 SCAR=30.0
Pod undocumented
3497 0 ▶ barf 'Usage: list($pdl)' if $#_!=0;
Branch: 1 branch
BranchTrueFalseTotal
if $#_ != 0 0 0 0
3498 0 my $pdl = shift;
3499 0 ▶ return () if nelem($pdl)==0;
Branch: 1 branch
BranchTrueFalseTotal
if nelem($pdl) == 0 0 0 0
3500 0 ▶ barf 'Not 1D' if scalar(dims($pdl)) != 1;
Branch: 1 branch
BranchTrueFalseTotal
if scalar dims($pdl) != 1 0 0 0
3501 0 return (0..nelem($pdl)-1);
3502 }
3503  
3504 =head2 set
3505  
3506 =for ref
3507  
3508 Set a single value inside an ndarray
3509  
3510 =for usage
3511  
3512 set $ndarray, @position, $value
3513  
3514 C<@position> is a coordinate list, of size equal to the
3515 number of dimensions in the ndarray. Occasionally useful,
3516 mainly provided for backwards compatibility as superseded
3517 by use of L<slice|PDL::Slices/slice> and assignment operator C<.=>.
3518  
3519 =for example
3520  
3521 pdl> $x = sequence 3,4
3522 pdl> set $x, 2,1,99
3523 pdl> p $x
3524 [
3525 [ 0 1 2]
3526 [ 3 4 99]
3527 [ 6 7 8]
3528 [ 9 10 11]
3529 ]
3530  
3531 =cut
3532  
3533 58 ▶sub PDL::set{ # Sets a particular single value
Subroutine set: called CC=2 SCAR=7.0
Pod undocumented
3534 58 ▶ barf 'Usage: set($pdl, $x, $y,.., $value)' if $#_<2;
Branch: 1 branch
BranchTrueFalseTotal
if $#_ < 2 0 58 58
3535 58 my $self = shift; my $value = pop @_;
3536 58 set_c ($self, [@_], $value);
3537 57 return $self;
3538 }
3539  
3540 =head2 at
3541  
3542 =for ref
3543  
3544 Returns a single value inside an ndarray as perl scalar.
3545 If the ndarray is a native complex value (cdouble, cfloat), it will
3546 be a L<PDL::Complex::Overloads> object.
3547  
3548 =for usage
3549  
3550 $z = at($ndarray, @position); $z=$ndarray->at(@position);
3551  
3552 C<@position> is a coordinate list, of size equal to the
3553 number of dimensions in the ndarray. Occasionally useful
3554 in a general context, quite useful too inside PDL internals.
3555  
3556 =for example
3557  
3558 pdl> $x = sequence 3,4
3559 pdl> p $x->at(1,2)
3560 7
3561  
3562 =for bad
3563  
3564 at converts any bad values into the string 'BAD'.
3565  
3566 =cut
3567  
3568 15555 ▶sub PDL::at { # Return value at ($x,$y,$z...)
Subroutine at: called CC=2 SCAR=7.1
Pod undocumented
3569 15555 ▶ barf 'Usage: at($pdl, $x, $y, ...)' if $#_<0;
Branch: 1 branch
BranchTrueFalseTotal
if $#_ < 0 0 15555 15555
3570 15555 my $self = shift;
3571 15555 at_bad_c ($self, [@_]);
3572 }
3573  
3574 =head2 sclr
3575  
3576 =for ref
3577  
3578 return a single value from an ndarray as a scalar, ignoring whether it is bad.
3579  
3580 =for example
3581  
3582 $val = $x(10)->sclr;
3583 $val = sclr inner($x,$y);
3584  
3585 The C<sclr> method is useful to turn a single-element ndarray into a normal Perl
3586 scalar. Its main advantage over using C<at> for this purpose is the fact
3587 that you do not need to worry if the ndarray is 0D, 1D or higher dimensional.
3588 Using C<at> you have to supply the correct number of zeroes, e.g.
3589  
3590 $x = sequence(10);
3591 $y = $x->slice('4');
3592 print $y->sclr; # no problem
3593 print $y->at(); # error: needs at least one zero
3594  
3595 C<sclr> is generally used when a Perl scalar is required instead
3596 of a one-element ndarray. As of 2.064, if the input is a multielement ndarray
3597 it will throw an exception.
3598  
3599 =head2 cat
3600  
3601 =for ref
3602  
3603 concatenate ndarrays to N+1 dimensional ndarray
3604  
3605 Takes a list of N ndarrays of same shape as argument,
3606 returns a single ndarray of dimension N+1.
3607  
3608 =for example
3609  
3610 pdl> $x = cat ones(3,3),zeroes(3,3),rvals(3,3); p $x
3611 [
3612 [
3613 [1 1 1]
3614 [1 1 1]
3615 [1 1 1]
3616 ]
3617 [
3618 [0 0 0]
3619 [0 0 0]
3620 [0 0 0]
3621 ]
3622 [
3623 [1 1 1]
3624 [1 0 1]
3625 [1 1 1]
3626 ]
3627 ]
3628  
3629 =for bad
3630  
3631 The output ndarray is set bad if any input ndarrays have their bad flag set.
3632  
3633 Similar functions include L<append|PDL::Primitive/append>, which
3634 appends only two ndarrays along their first dimension, and
3635 L<glue|PDL::Primitive/glue>, which can append more than two ndarrays
3636 along an arbitrary dimension.
3637  
3638 Also consider the generic constructor L</pdl>, which can handle
3639 ndarrays of different sizes (with zero-padding), and will return a
3640 ndarray of type 'double' by default, but may be considerably faster (up
3641 to 10x) than cat.
3642  
3643 =cut
3644  
3645 # takes a list of array-refs with dims, returns list of maximalised
3646 # broadcast-compatible dim lengths
3647 42 ▶sub dims_filled {
Subroutine dims_filled: called CC=7 SCAR=19.5
Pod undocumented
3648 42 my @resdims = @{shift()};
3649 42 ▶ while (@_) {
Branch: 1 branch
BranchTrueFalseTotal
if (@_) 53 39 92
3650 53 my @d = @{shift()};
3651 53 for my $j (0..$#d) {
3652 61 ▶ $resdims[$j] = $d[$j] if( !defined($resdims[$j]) or $resdims[$j]==1 );
Branch: 1 branch
BranchTrueFalseTotal
if not defined $resdims[$j] or $resdims[$j] == 1 1 60 61
Condition66%2/3
not defined $resdims[$j] or $resdims[$j] == 1
l!l&&r!l&&!r
1060
MC/DC50%1/2
not defined $resdims[$j] or $resdims[$j] == 1
not defined $resdims[$j] $resdims[$j] == 1
Truth table66%2/3
not(A) or B
A= not defined $resdims[$j]B= $resdims[$j] == 1
ABresult
1X1
011
000
3653 61 ▶ die "mismatched dims\n" if $d[$j] != 1 and $resdims[$j] != $d[$j];
Branch: 1 branch
BranchTrueFalseTotal
if $d[$j] != 1 and $resdims[$j] != $d[$j] 3 58 61
Condition66%2/3
$d[$j] != 1 and $resdims[$j] != $d[$j]
!ll&&!rl&&r
0583
MC/DC50%1/2
$d[$j] != 1 and $resdims[$j] != $d[$j]
$d[$j] != 1 $resdims[$j] != $d[$j]
Truth table66%2/3
A and B
A= $d[$j] != 1B= $resdims[$j] != $d[$j]
ABresult
0X0
100
111
3654 }
3655 }
3656 39 @resdims;
3657 }
3658  
3659 42 ▶sub PDL::cat {
Subroutine cat: called CC=25 SCAR=32.5
Pod undocumented
3660 42 ▶ barf("Called PDL::cat without any arguments") unless @_;
Branch: 1 branch
BranchTrueFalseTotal
unless @_ 0 42 42
3661 42 my (@yes_ndarray, @not_a_ndarray);
3662 42 ▶ push @{UNIVERSAL::isa($_[$_], 'PDL')?\@yes_ndarray:\@not_a_ndarray}, $_ for 0..$#_;
Branch: 1 branch
BranchTrueFalseTotal
UNIVERSAL::isa($_[$_], 'PDL') ? : 99 7 106
3663 42 ▶ barf("Called PDL::cat without any ndarray arguments") if !@yes_ndarray;
Branch: 1 branch
BranchTrueFalseTotal
unless @yes_ndarray 0 42 42
3664 42 my $old_err = $@;
3665 42 $@ = '';
3666 42 my @resdims = eval { dims_filled(map [$_->dims], @_[@yes_ndarray]) };
3667 42 ▶ if (!$@ and $yes_ndarray[0] == 0) {
Branch: 1 branch
BranchTrueFalseTotal
if (not $@ and $yes_ndarray[0] == 0) 37 5 42
Condition100%3/3
not $@ and $yes_ndarray[0] == 0
!ll&&!rl&&r
3237
MC/DC100%2/2
not $@ and $yes_ndarray[0] == 0
not $@ $yes_ndarray[0] == 0
Truth table100%3/3
not(A) and B
A= not $@B= $yes_ndarray[0] == 0
ABresult
0X0
100
111
3668 37 my $res;
3669 37 eval {
3670 37 $res = $_[0]->initialize;
3671 37 $res->set_datatype(max(map $_->get_datatype, @_));
3672  
3673 37 $res->setdims([@resdims,scalar(@_)]);
3674 37 my @dog = $res->dog;
3675 37 $dog[$_] .= $_[$_] for 0..$#_;
3676  
3677 # propagate any bad flags
3678 37 ▶ for (@_) { if ( $_->badflag() ) { $res->badflag(1); last; } }
Branch: 1 branch
BranchTrueFalseTotal
if ($_->badflag) 2 79 81
3679 };
3680 37 ▶ $@ = $old_err, return $res if !$@; # Restore the old error and return
Branch: 1 branch
BranchTrueFalseTotal
unless $@ 37 0 37
3681 }
3682  
3683 # If we've gotten here, then there's been an error, so check things
3684 # and barf out a meaningful message.
3685  
3686 5 my ($first_ndarray_argument, @mismatched_dims) = $yes_ndarray[0];
3687 5 ▶ if ($@ and $@ =~ /mismatched/) {
Branch: 1 branch
BranchTrueFalseTotal
if ($@ and $@ =~ /mismatched/) 3 2 5
Condition66%2/3
$@ and $@ =~ /mismatched/
!ll&&!rl&&r
203
MC/DC50%1/2
$@ and $@ =~ /mismatched/
$@ $@ =~ /mismatched/
Truth table66%2/3
A and B
A= $@B= $@ =~ /mismatched/
ABresult
0X0
100
111
3688 # Get the dimensions of the first actual ndarray in the argument list:
3689 3 my @dims = $_[$first_ndarray_argument]->dims;
3690 # Figure out all the ways that the caller screwed up:
3691 3 for my $i (@yes_ndarray) {
3692 10 my $arg = $_[$i];
3693 10 ▶ if (@dims != $arg->ndims) { # Check if different number of dimensions
Branch: 1 branch
BranchTrueFalseTotal
if (@dims != $arg->ndims) { } 3 7 10
3694 3 push @mismatched_dims, $i;
3695 } else { # Check if size of dimensions agree
3696 7 ▶ DIMENSION: for (my $j = 0; $j < @dims; $j++) {
Branch: 1 branch
BranchTrueFalseTotal
if ($j < @dims) 7 5 12
3697 7 ▶ next if $dims[$j] == $arg->dim($j);
Branch: 1 branch
BranchTrueFalseTotal
if $dims[$j] == $arg->dim($j) 5 2 7
3698 2 push @mismatched_dims, $i;
3699 2 last DIMENSION;
3700 }
3701 }
3702 10 $i++;
3703 }
3704 }
3705 # Handle the edge case that something else happened:
3706 5 ▶ barf "cat: unknown error from the internals:\n$@"
Branch: 1 branch
BranchTrueFalseTotal
if $@ and not $@ =~ /PDL::Ops::assgn|mismatched/ or not @not_a_ndarray || @mismatched_dims 0 5 5
Condition55%5/9
$@ and not $@ =~ /PDL::Ops::assgn|mismatched/ or not @not_a_ndarray || @mismatched_dims
l!l&&r!l&&!r
005
$@ and not $@ =~ /PDL::Ops::assgn|mismatched/
!ll&&!rl&&r
230
@not_a_ndarray || @mismatched_dims
l!l&&r!l&&!r
320
MC/DC0%0/4
$@ and not $@ =~ /PDL::Ops::assgn|mismatched/ or not @not_a_ndarray || @mismatched_dims
$@ not $@ =~ /PDL::Ops::assgn|mismatched/ @not_a_ndarray @mismatched_dims
Truth table42%3/7
A and not(B) or not(C || D)
A= $@B= not $@ =~ /PDL::Ops::assgn|mismatched/C= @not_a_ndarrayD= @mismatched_dims
ABCDresult
11XX1
0X001
10001
0X1X0
0X010
101X0
10010
3707 if ($@ and $@ !~ /PDL::Ops::assgn|mismatched/) or
3708 (!@not_a_ndarray and !@mismatched_dims);
3709  
3710 # Construct a message detailing the results
3711 5 my $message = "bad arguments passed to function PDL::cat\n";
3712 5 ▶ if (@mismatched_dims > 1) {
Branch: 2 branches
BranchTrueFalseTotal
if (@mismatched_dims > 1) { } 2 3 5
elsif (@mismatched_dims) { } 1 2 3
3713 # Many dimension mismatches
3714 2 $message .= "The dimensions of arguments "
3715 . join(', ', @mismatched_dims[0 .. $#mismatched_dims-1])
3716 . " and $mismatched_dims[-1] do not match the\n"
3717 . " dimensions of the first ndarray argument (argument $first_ndarray_argument).\n";
3718 } elsif (@mismatched_dims) {
3719 # One dimension mismatch
3720 1 $message .= "The dimensions of argument $mismatched_dims[0] do not match the\n"
3721 . " dimensions of the first ndarray argument (argument $first_ndarray_argument).\n";
3722 }
3723 5 ▶ if (@not_a_ndarray > 1) {
Branch: 2 branches
BranchTrueFalseTotal
if (@not_a_ndarray > 1) { } 2 3 5
elsif (@not_a_ndarray) { } 1 2 3
3724 # many non-ndarrays
3725 2 $message .= "Arguments " . join(', ', @not_a_ndarray[0 .. $#not_a_ndarray-1])
3726 . " and $not_a_ndarray[-1] are not ndarrays.\n";
3727 } elsif (@not_a_ndarray) {
3728 # one non-ndarray
3729 1 $message .= "Argument $not_a_ndarray[0] is not an ndarray.\n";
3730 }
3731 5 croak($message . "(Argument counting starts from zero.)");
3732 }
3733  
3734 =head2 dog
3735  
3736 =for ref
3737  
3738 Opposite of 'cat' :). Split N dim ndarray to list of N-1 dim ndarrays
3739  
3740 Takes a single N-dimensional ndarray and splits it into a list of N-1 dimensional
3741 ndarrays. The breakup is done along the last dimension.
3742 Note the dataflowed connection is still preserved by default,
3743 e.g.:
3744  
3745 =for example
3746  
3747 pdl> $p = ones 3,3,3
3748 pdl> ($x,$y,$c) = dog $p
3749 pdl> $y++; p $p
3750 [
3751 [
3752 [1 1 1]
3753 [1 1 1]
3754 [1 1 1]
3755 ]
3756 [
3757 [2 2 2]
3758 [2 2 2]
3759 [2 2 2]
3760 ]
3761 [
3762 [1 1 1]
3763 [1 1 1]
3764 [1 1 1]
3765 ]
3766 ]
3767  
3768 =for options
3769  
3770 Break => 1 Break dataflow connection (new copy)
3771  
3772 =for bad
3773  
3774 The output ndarrays are set bad if the original ndarray has its bad flag set.
3775  
3776 =cut
3777  
3778 ###################### Misc internal routines ####################
3779  
3780 # N-D array stringifier
3781  
3782 143 ▶sub strND {
Subroutine strND: called CC=4 SCAR=13.9
Pod undocumented
3783 143 my($self,$format,$level)=@_;
3784 # $self->make_physical();
3785 143 my @dims = $self->dims;
3786 # print "STRND, $#dims\n";
3787  
3788 143 ▶ if ($#dims==1) { # Return 2D string
Branch: 1 branch
BranchTrueFalseTotal
if ($#dims == 1) { } 136 7 143
3789 136 return str2D($self,$format,$level);
3790 }
3791 else { # Return list of (N-1)D strings
3792 7 my $secbas = join '',map {":,"} @dims[0..$#dims-1];
3793 7 my $ret="\n"." "x$level ."["; my $j;
3794 7 ▶ for ($j=0; $j<$dims[$#dims]; $j++) {
Branch: 1 branch
BranchTrueFalseTotal
if ($j < $dims[$#dims]) 30 7 37
3795 30 my $sec = $secbas . "($j)";
3796 # print "SLICE: $sec\n";
3797  
3798 30 $ret .= strND($self->slice($sec),$format, $level+1);
3799 30 chop $ret; $ret .= $sep2;
3800 }
3801 7 ▶ chop $ret if $PDL::use_commas;
Branch: 1 branch
BranchTrueFalseTotal
if $PDL::use_commas 0 7 7
3802 7 $ret .= "\n" ." "x$level ."]\n";
3803 7 return $ret;
3804 }
3805 }
3806  
3807  
3808 # String 1D array in nice format
3809  
3810 312 ▶sub str1D {
Subroutine str1D: called CC=5 SCAR=16.1
Pod undocumented
3811 312 my($self,$format)=@_;
3812 312 ▶ barf "Not 1D" if $self->getndims != 1;
Branch: 1 branch
BranchTrueFalseTotal
if $self->getndims != 1 0 312 312
3813 312 my $x = listref_c($self);
3814 312 my $badflag = $self->badflag;
3815 312 ▶ return "[".join($sep, map
Branch: 2 branches
BranchTrueFalseTotal
$badflag && $_ eq 'BAD' ? : 142 990 1132
$format ? : 18 972 990
Condition100%3/3
$badflag and $_ eq "BAD"
!ll&&!rl&&r
770220142
MC/DC100%2/2
$badflag and $_ eq "BAD"
$badflag $_ eq "BAD"
Truth table100%3/3
A and B
A= $badflagB= $_ eq "BAD"
ABresult
0X0
100
111
3816 $badflag && $_ eq "BAD" ? $_ :
3817 $format ? sprintf $format,$_ : $_,
3818 @$x)."]";
3819 }
3820  
3821 136 ▶sub str_list {
Subroutine str_list: called CC=15 SCAR=27.2
Pod undocumented
3822 136 my ($x, $row_len, $format, $dtype, $badflag) = @_;
3823 136 my ($len, $findmax) = (0, 1);
3824 136 ▶ if (!defined $format || $format eq "") {
Branch: 1 branch
BranchTrueFalseTotal
if (not defined $format or $format eq "") 136 0 136
Condition33%1/3
not defined $format or $format eq ""
l!l&&r!l&&!r
13600
MC/DC0%0/2
not defined $format or $format eq ""
not defined $format $format eq ""
Truth table33%1/3
not(A) or B
A= not defined $formatB= $format eq ""
ABresult
1X1
011
000
3825 # Format not given? - find max length of default
3826 136 $len = max map length($_), @$x;
3827 136 $format = "%".$len."s";
3828 136 ▶ if ($len>7) { # Too long? - perhaps try smaller format
Branch: 1 branch
BranchTrueFalseTotal
if ($len > 7) { } 13 123 136
3829 13 ▶ if ($dtype == $PDL_F) {
Branch: 3 branches
BranchTrueFalseTotal
if ($dtype == $PDL::Core::PDL_F) { } 0 13 13
elsif ($dtype == $PDL::Core::PDL_D) { } 9 4 13
elsif ($dtype == $PDL::Core::PDL_IND) { } 2 2 4
3830 0 $format = $PDL::floatformat;
3831 } elsif ($dtype == $PDL_D) {
3832 9 $format = $PDL::doubleformat;
3833 } elsif ($dtype == $PDL_IND) {
3834 2 $format = $PDL::indxformat;
3835 } else {
3836 # Stick with default
3837 2 $findmax = 0;
3838 }
3839 13 ▶ $len = max map $badflag && $_ eq "BAD" ? 3 : length(sprintf $format,$_), @$x; # we overrode, recalc
Branch: 1 branch
BranchTrueFalseTotal
$badflag && $_ eq 'BAD' ? : 2 104 106
Condition100%3/3
$badflag and $_ eq "BAD"
!ll&&!rl&&r
10042
MC/DC100%2/2
$badflag and $_ eq "BAD"
$badflag $_ eq "BAD"
Truth table100%3/3
A and B
A= $badflagB= $_ eq "BAD"
ABresult
0X0
100
111
3840 } else {
3841 # Default ok
3842 123 $findmax = 0;
3843 }
3844 }
3845 136 ▶ $len = $badflag ?
Branch: 3 branches
BranchTrueFalseTotal
if $findmax 11 125 136
$badflag ? : 1 10 11
$_ eq 'BAD' ? : 2 4 6
3846 max $len, map $_ eq "BAD" ? 3 : length(sprintf $format,$_), @$x :
3847 max $len, map length(sprintf $format,$_), @$x
3848 if $findmax; # Find max length of strings in final format
3849 136 my @ret;
3850 136 ▶ for (my $i=0; $i<=$#$x; $i+=$row_len) {
Branch: 1 branch
BranchTrueFalseTotal
if ($i <= $x->$#*) 619 136 755
3851 619 ▶ push @ret, "[".join($sep, map sprintf("%${len}s", $badflag && $_ eq "BAD" ? "BAD" : sprintf $format,$_), @$x[$i..$i+$row_len-1])."]";
Branch: 1 branch
BranchTrueFalseTotal
$badflag && $_ eq 'BAD' ? : 22 3775 3797
Condition100%3/3
$badflag and $_ eq "BAD"
!ll&&!rl&&r
36878822
MC/DC100%2/2
$badflag and $_ eq "BAD"
$badflag $_ eq "BAD"
Truth table100%3/3
A and B
A= $badflagB= $_ eq "BAD"
ABresult
0X0
100
111
3852 }
3853 136 return @ret;
3854 }
3855  
3856 # String 2D array in nice uniform format
3857  
3858 136 ▶sub str2D{
Subroutine str2D: called CC=2 SCAR=6.9
Pod undocumented
3859 136 my($self,$format,$level)=@_;
3860 136 my @dims = $self->dims();
3861 136 ▶ barf "Not 2D" if scalar(@dims)!=2;
Branch: 1 branch
BranchTrueFalseTotal
if scalar @dims != 2 0 136 136
3862 136 my $x = listref_c($self);
3863 136 my @lines = str_list($x, $dims[0], $format, $self->get_datatype, $self->badflag);
3864 136 my $ret = "\n" . " "x$level . "[\n";
3865 136 $ret .= join $sep2."\n", map " "x($level+1).$_, @lines;
3866 136 $ret .= "\n".(" "x$level)."]\n";
3867 136 return $ret;
3868 }
3869  
3870 ########## Docs for functions in Core.xs ##################
3871 # Pod docs for functions that are imported from Core.xs and are
3872 # not documented elsewhere. Currently this is not a complete
3873 # list. There are others.
3874  
3875 =head2 gethdr
3876  
3877 =for ref
3878  
3879 Retrieve header information from an ndarray
3880  
3881 =for example
3882  
3883 $pdl=rfits('file.fits');
3884 $h=$pdl->gethdr;
3885 print "Number of pixels in the X-direction=$$h{NAXIS1}\n";
3886  
3887 The C<gethdr> function retrieves whatever header information is contained
3888 within an ndarray. The header can be set with L</sethdr> and is always a
3889 hash reference or undef.
3890  
3891 C<gethdr> returns undef if the ndarray has not yet had a header
3892 defined; compare with C<hdr> and C<fhdr>, which are guaranteed to return a
3893 defined value.
3894  
3895 Note that gethdr() works by B<reference>: you can modify the header
3896 in-place once it has been retrieved:
3897  
3898 $x = rfits($filename);
3899 $xh = $x->gethdr();
3900 $xh->{FILENAME} = $filename;
3901  
3902 It is also important to realise that in most cases the header is not
3903 automatically copied when you copy the ndarray. See L</hdrcpy>
3904 to enable automatic header copying.
3905  
3906 Here's another example: a wrapper around rcols that allows your ndarray
3907 to remember the file it was read from and the columns could be easily
3908 written (here assuming that no regexp is needed, extensions are left
3909 as an exercise for the reader)
3910  
3911 sub ext_rcols {
3912 my ($file, @columns)=@_;
3913 my $header={};
3914 $$header{File}=$file;
3915 $$header{Columns}=\@columns;
3916  
3917 @ndarrays=rcols $file, @columns;
3918 foreach (@ndarrays) { $_->sethdr($header); }
3919 return @ndarrays;
3920 }
3921  
3922 =head2 hdr
3923  
3924 =for ref
3925  
3926 Retrieve or set header information from an ndarray
3927  
3928 =for example
3929  
3930 $pdl->hdr->{CDELT1} = 1;
3931  
3932 The C<hdr> function allows convenient access to the header of a
3933 ndarray. Unlike C<gethdr> it is guaranteed to return a defined value,
3934 so you can use it in a hash dereference as in the example. If the
3935 header does not yet exist, it gets autogenerated as an empty hash.
3936  
3937 Note that this is usually -- but not always -- What You Want. If you
3938 want to use a tied L<Astro::FITS::Header> hash,
3939 for example, you should either construct it yourself and use C<sethdr>
3940 to put it into the ndarray, or use L</fhdr> instead. (Note that
3941 you should be able to write out the FITS file successfully regardless
3942 of whether your PDL has a tied FITS header object or a vanilla hash).
3943  
3944 =head2 fhdr
3945  
3946 =for ref
3947  
3948 Retrieve or set FITS header information from an ndarray
3949  
3950 =for example
3951  
3952 $pdl->fhdr->{CDELT1} = 1;
3953  
3954 The C<fhdr> function allows convenient access to the header of a
3955 ndarray. Unlike C<gethdr> it is guaranteed to return a defined value,
3956 so you can use it in a hash dereference as in the example. If the
3957 header does not yet exist, it gets autogenerated as a tied
3958 L<Astro::FITS::Header> hash.
3959  
3960 Astro::FITS::Header tied hashes are better at matching the behavior of
3961 FITS headers than are regular hashes. In particular, the hash keys
3962 are CAsE INsEnSItiVE, unlike normal hash keys. See
3963 L<Astro::FITS::Header> for details.
3964  
3965 If you do not have Astro::FITS::Header installed, you get back a
3966 normal hash instead of a tied object.
3967  
3968 =head2 sethdr
3969  
3970 =for ref
3971  
3972 Set header information of an ndarray
3973  
3974 =for example
3975  
3976 $pdl = zeroes(100,100);
3977 $h = {NAXIS=>2, NAXIS1=>100, NAXIS=>100, COMMENT=>"Sample FITS-style header"};
3978 # add a FILENAME field to the header
3979 $$h{FILENAME} = 'file.fits';
3980 $pdl->sethdr( $h );
3981  
3982 The C<sethdr> function sets the header information for an ndarray.
3983 You must feed in a hash ref or undef, and the header field of the PDL is
3984 set to be a new ref to the same hash (or undefined).
3985  
3986 The hash ref requirement is a speed bump put in place since the normal
3987 use of headers is to store fits header information and the like. Of course,
3988 if you want you can hang whatever ugly old data structure you want off
3989 of the header, but that makes life more complex.
3990  
3991 Remember that the hash is not copied -- the header is made into a ref
3992 that points to the same underlying data. To get a real copy without
3993 making any assumptions about the underlying data structure, you
3994 can use one of the following:
3995  
3996 use PDL::IO::Dumper;
3997 $pdl->sethdr( deep_copy($h) );
3998  
3999 (which is slow but general), or
4000  
4001 $pdl->sethdr( PDL::_hdr_copy($h) )
4002  
4003 (which uses the built-in sleazy deep copier), or (if you know that all
4004 the elements happen to be scalars):
4005  
4006 { my %a = %$h;
4007 $pdl->sethdr(\%a);
4008 }
4009  
4010 which is considerably faster but just copies the top level.
4011  
4012 The C<sethdr> function must be given a hash reference or undef. For
4013 further information on the header, see L</gethdr>, L</hdr>,
4014 L</fhdr> and L</hdrcpy>.
4015  
4016 =head2 hdrcpy
4017  
4018 =for ref
4019  
4020 switch on/off/examine automatic header copying
4021  
4022 =for example
4023  
4024 print "hdrs will be copied" if $x->hdrcpy;
4025 $x->hdrcpy(1); # switch on automatic header copying
4026 $y = $x->sumover; # and $y will inherit $x's hdr
4027 $x->hdrcpy(0); # and now make $x non-infectious again
4028  
4029 C<hdrcpy> without an argument just returns the current setting of the
4030 flag. See also "hcpy" which returns its PDL argument (and so is useful
4031 in method-call pipelines).
4032  
4033 Normally, the optional header of an ndarray is not copied automatically
4034 in pdl operations. Switching on the hdrcpy flag using the C<hdrcpy>
4035 method will enable automatic hdr copying. Note that an actual deep
4036 copy gets made, which is rather processor-inefficient -- so avoid
4037 using header copying in tight loops!
4038  
4039 Most PDLs have the C<hdrcpy> flag cleared by default; however, some
4040 routines (notably L<rfits|PDL::IO::FITS/rfits()>) set it by default
4041 where that makes more sense.
4042  
4043 The C<hdrcpy> flag is viral: if you set it for a PDL, then derived
4044 PDLs will get copies of the header and will also have their C<hdrcpy>
4045 flags set. For example:
4046  
4047 $x = xvals(50,50);
4048 $x->hdrcpy(1);
4049 $x->hdr->{FOO} = "bar";
4050 $y = $x++;
4051 $c = $y++;
4052 print $y->hdr->{FOO}, " - ", $c->hdr->{FOO}, "\n";
4053 $y->hdr->{FOO} = "baz";
4054 print $x->hdr->{FOO}, " - ", $y->hdr->{FOO}, " - ", $c->hdr->{FOO}, "\n";
4055  
4056 will print:
4057  
4058 bar - bar
4059 bar - baz - bar
4060  
4061 Performing an operation in which more than one PDL has its hdrcpy flag
4062 causes the resulting PDL to take the header of the first PDL:
4063  
4064 ($x,$y) = sequence(5,2)->dog;
4065 $x->hdrcpy(1); $y->hdrcpy(1);
4066 $x->hdr->{foo} = 'a';
4067 $y->hdr->{foo} = 'b';
4068 print (($x+$y)->hdr->{foo} , ($y+$x)->hdr->{foo});
4069  
4070 will print:
4071  
4072 a b
4073  
4074 =head2 hcpy
4075  
4076 =for ref
4077  
4078 Switch on/off automatic header copying, with PDL pass-through
4079  
4080 =for example
4081  
4082 $x = rfits('foo.fits')->hcpy(0);
4083 $x = rfits('foo.fits')->hcpy(1);
4084  
4085 C<hcpy> sets or clears the hdrcpy flag of a PDL, and returns the PDL
4086 itself. That makes it convenient for inline use in expressions.
4087  
4088 =cut
4089  
4090 #
4091 # Sleazy hcpy saves me time typing
4092 #
4093 0 ▶sub PDL::hcpy {
Subroutine hcpy: not called CC=1 SCAR=6.9
Pod undocumented
4094 0 $_[0]->hdrcpy($_[1]);
4095 0 $_[0];
4096 }
4097  
4098 =head2 online_cpus
4099  
4100 =for ref
4101  
4102 Returns the number of available processors cores. Used to set the number
4103 of threads with L</set_autopthread_targ> if C<$ENV{PDL_AUTOPTHREAD_TARG}>
4104 is not set.
4105  
4106 =head2 set_autopthread_targ
4107  
4108 =for ref
4109  
4110 Set the target number of processor threads (pthreads) for multi-threaded processing.
4111  
4112 =for usage
4113  
4114 set_autopthread_targ($num_pthreads);
4115  
4116 C<$num_pthreads> is the target number of pthreads the auto-pthread process will try to achieve.
4117  
4118 See L<PDL::ParallelCPU> for an overview of the auto-pthread process.
4119  
4120 =for example
4121  
4122 # Example turning on auto-pthreading for a target of 2 pthreads and for functions involving
4123 # PDLs with greater than 1M elements
4124 set_autopthread_targ(2);
4125 set_autopthread_size(1);
4126  
4127 # Execute a pdl function, processing will split into two pthreads
4128 $x = minimum($y);
4129  
4130 # Get the actual number of pthreads that were run.
4131 $actual_pthread = get_autopthread_actual();
4132  
4133 =cut
4134  
4135 71 *set_autopthread_targ = \&PDL::set_autopthread_targ;
4136  
4137 =head2 get_autopthread_targ
4138  
4139 =for ref
4140  
4141 Get the current target number of processor threads (pthreads) for multi-threaded processing.
4142  
4143 =for usage
4144  
4145 $num_pthreads = get_autopthread_targ();
4146  
4147 C<$num_pthreads> is the target number of pthreads the auto-pthread process will try to achieve.
4148  
4149 See L<PDL::ParallelCPU> for an overview of the auto-pthread process.
4150  
4151 =cut
4152  
4153 71 *get_autopthread_targ = \&PDL::get_autopthread_targ;
4154  
4155 =head2 get_autopthread_actual
4156  
4157 =for ref
4158  
4159 Get the actual number of pthreads executed for the last pdl processing function.
4160  
4161 =for usage
4162  
4163 $autopthread_actual = get_autopthread_actual();
4164  
4165 C<$autopthread_actual> is the actual number of pthreads executed for the last pdl processing function.
4166  
4167 See L<PDL::ParallelCPU> for an overview of the auto-pthread process.
4168  
4169 =cut
4170  
4171 71 *get_autopthread_actual = \&PDL::get_autopthread_actual;
4172  
4173 =head2 get_autopthread_dim
4174  
4175 =for ref
4176  
4177 Get the actual dimension on which pthreads were used for the last
4178 pdl processing function.
4179  
4180 =for usage
4181  
4182 $autopthread_dim = get_autopthread_dim();
4183  
4184 C<$autopthread_dim> is the actual dimension on which pthreads were
4185 used for the last pdl processing function.
4186  
4187 See L<PDL::ParallelCPU> for an overview of the auto-pthread process.
4188  
4189 =cut
4190  
4191 71 *get_autopthread_dim = \&PDL::get_autopthread_dim;
4192  
4193 =head2 set_autopthread_size
4194  
4195 =for ref
4196  
4197 Set the minimum size (in M-elements or 2^20 elements) of the largest PDL involved in a function where auto-pthreading will
4198 be performed. For small PDLs, it probably isn't worth starting multiple pthreads, so this function
4199 is used to define a minimum threshold where auto-pthreading won't be attempted.
4200  
4201 =for usage
4202  
4203 set_autopthread_size($size);
4204  
4205 C<$size> is the mimumum size, in M-elements or 2^20 elements (approx 1e6 elements) for the largest PDL involved in a function.
4206  
4207 See L<PDL::ParallelCPU> for an overview of the auto-pthread process.
4208  
4209 =for example
4210  
4211 # Example turning on auto-pthreading for a target of 2 pthreads and for functions involving
4212 # PDLs with greater than 1M elements
4213 set_autopthread_targ(2);
4214 set_autopthread_size(1);
4215  
4216 # Execute a pdl function, processing will split into two pthreads as long as
4217 # one of the pdl-threaded dimensions is at least 2.
4218 $x = minimum($y);
4219  
4220 # Get the actual number of pthreads that were run.
4221 $actual_pthread = get_autopthread_actual();
4222  
4223 =cut
4224  
4225 71 *set_autopthread_size = \&PDL::set_autopthread_size;
4226  
4227 =head2 get_autopthread_size
4228  
4229 =for ref
4230  
4231 Get the current autopthread_size setting.
4232  
4233 =for usage
4234  
4235 $autopthread_size = get_autopthread_size();
4236  
4237 C<$autopthread_size> is the mimumum size limit for auto_pthreading to occur, in M-elements or 2^20 elements (approx 1e6 elements) for the largest PDL involved in a function
4238  
4239 See L<PDL::ParallelCPU> for an overview of the auto-pthread process.
4240  
4241 =cut
4242  
4243 71 *get_autopthread_size = \&PDL::get_autopthread_size;
4244  
4245 =head1 AUTHOR
4246  
4247 Copyright (C) Karl Glazebrook (kgb@aaoepp.aao.gov.au),
4248 Tuomas J. Lukka, (lukka@husc.harvard.edu) and Christian
4249 Soeller (c.soeller@auckland.ac.nz) 1997.
4250 Modified, Craig DeForest (deforest@boulder.swri.edu) 2002.
4251 All rights reserved. There is no warranty. You are allowed
4252 to redistribute this software / documentation under certain
4253 conditions. For details, see the file COPYING in the PDL
4254 distribution. If this file is separated from the PDL distribution,
4255 the copyright notice should be included in the file.
4256  
4257 =cut
4258  
4259 #
4260 # Easier to implement in perl than in XS...
4261 # -- CED
4262 #
4263  
4264 3 ▶sub PDL::fhdr {
Subroutine fhdr: called CC=3 SCAR=17.3
Pod undocumented
4265 3 my $pdl = shift;
4266  
4267 3 ▶ return $pdl->hdr
Branch: 1 branch
BranchTrueFalseTotal
if defined $pdl->gethdr or not defined $Astro::FITS::Header::VERSION 3 0 3
Condition33%1/3
defined $pdl->gethdr or not defined $Astro::FITS::Header::VERSION
l!l&&r!l&&!r
030
MC/DC0%0/2
defined $pdl->gethdr or not defined $Astro::FITS::Header::VERSION
defined $pdl->gethdr not defined $Astro::FITS::Header::VERSION
Truth table33%1/3
A or not(B)
A= defined $pdl->gethdrB= not defined $Astro::FITS::Header::VERSION
ABresult
1X1
011
000
4268 if( (defined $pdl->gethdr) ||
4269 !defined $Astro::FITS::Header::VERSION
4270 );
4271  
4272 # Avoid bug in 1.15 and earlier Astro::FITS::Header
4273 0 my @hdr = ("SIMPLE = T");
4274 0 my $hdr = Astro::FITS::Header->new(Cards=>\@hdr);
4275 0 tie my %hdr, "Astro::FITS::Header", $hdr;
4276 0 $pdl->sethdr(\%hdr);
4277 0 return \%hdr;
4278 }
4279  
4280 7 ▶sub _file_map_sv {
Subroutine _file_map_sv: called CC=5 SCAR=17.0
4281 7 require File::Map;
4282 7 my ($svref, $fh, $len, $shared, $writable) = @_;
4283 7 ▶ my $prot = File::Map::PROT_READ() | ($writable ? File::Map::PROT_WRITE() : 0);
Branch: 1 branch
BranchTrueFalseTotal
$writable ? : 7 0 7
4284 7 ▶ my $flags = ($shared ? File::Map::MAP_SHARED() : File::Map::MAP_PRIVATE());
Branch: 1 branch
BranchTrueFalseTotal
$shared ? : 7 0 7
4285 7 ▶ printf STDERR "_file_map_sv: calling sys_map(%s,%d,%d,%d,%s,%d)\n",
Branch: 1 branch
BranchTrueFalseTotal
if $PDL::debug 0 7 7
4286 $svref, $len, $prot, $flags, $fh, 0 if $PDL::debug;
4287 7 File::Map::sys_map($$svref, $len, $prot, $flags, $fh, 0);
4288 7 ▶ printf STDERR "_file_map_sv: length \$\$svref is %d.\n",
Branch: 1 branch
BranchTrueFalseTotal
if $PDL::debug 0 7 7
4289 length $$svref if $PDL::debug;
4290 }
4291  
4292 7 ▶sub _file_map_open {
Subroutine _file_map_open: called CC=8 SCAR=21.8
4293 7 require Fcntl;
4294 7 my ($name, $len, $shared, $writable, $creat, $perms, $trunc) = @_;
4295 7 ▶ my $mode = ($writable && $shared ? Fcntl::O_RDWR() : Fcntl::O_RDONLY());
Branch: 1 branch
BranchTrueFalseTotal
$writable && $shared ? : 7 0 7
Condition33%1/3
$writable and $shared
!ll&&!rl&&r
007
MC/DC0%0/2
$writable and $shared
$writable $shared
Truth table33%1/3
A and B
A= $writableB= $shared
ABresult
0X0
100
111
4296 7 ▶ $mode |= Fcntl::O_CREAT() if $creat;
Branch: 1 branch
BranchTrueFalseTotal
if $creat 2 5 7
4297 7 ▶ sysopen my $fh, $name, $mode, $perms
Branch: 1 branch
BranchTrueFalseTotal
sysopen my $fh, $name, $mode, $perms or die "Error opening file '${name}': $!\n" 7 0 7
4298 or die "Error opening file '$name': $!\n";
4299 7 binmode $fh;
4300 7 ▶ if ($trunc) {
Branch: 1 branch
BranchTrueFalseTotal
if ($trunc) 2 5 7
4301 2 ▶ truncate $fh,0 or die "truncate('$name',0) failed: $!";
Branch: 1 branch
BranchTrueFalseTotal
truncate $fh, 0 or die "truncate('${name}',0) failed: $!" 2 0 2
4302 2 ▶ truncate $fh,$len or die "truncate('$name',$len) failed: $!";
Branch: 1 branch
BranchTrueFalseTotal
truncate $fh, $len or die "truncate('${name}',$len) failed: $!" 2 0 2
4303 }
4304 7 $fh;
4305 }
4306  
4307 3 ▶sub PDL::set_data_by_file_map {
Subroutine set_data_by_file_map: called CC=2 SCAR=7.0
Pod undocumented
4308 3 my ($pdl,$name,$len,$shared,$writable,$creat,$perms,$trunc) = @_;
4309 3 my $fh = _file_map_open($name,$len,$shared,$writable,$creat,$perms,$trunc);
4310 3 ▶ return $_[0] = undef if !$len;
Branch: 1 branch
BranchTrueFalseTotal
unless $len 0 3 3
4311 3 _file_map_sv($pdl->get_dataref,$fh,$len,$shared,$writable);
4312 3 $pdl->upd_data(1);
4313 3 $pdl->set_donttouchdata($len);
4314 }
4315  
4316 71 1;
« blib/lib/PDL/Func.pm ↑ Summary lib/PDL/ImageND.pd »