1Core(3) User Contributed Perl Documentation Core(3)
2
3
4
6 PDL::Core - fundamental PDL functionality and
7 vectorization/broadcasting
8
10 Methods and functions for type conversions, PDL creation, type
11 conversion, broadcasting etc.
12
14 use PDL::Core; # Normal routines
15 use PDL::Core ':Internal'; # Hairy routines
16
18 PDL provides vectorized operations via a built-in engine.
19 Vectorization in PDL is called "broadcasting" (formerly, up to 2.074,
20 "threading"). The broadcasting engine implements simple rules for each
21 operation.
22
23 Each PDL object has a "shape" that is a generalized N-dimensional
24 rectangle defined by a "dim list" of sizes in an arbitrary set of
25 dimensions. A PDL with shape 2x3 has 6 elements and is said to be two-
26 dimensional, or may be referred to as a 2x3-PDL. The dimensions are
27 indexed numerically starting at 0, so a 2x3-PDL has a dimension 0 (or
28 "dim 0") with size 2 and a 1 dimension (or "dim 1") with size 3.
29
30 PDL generalizes *all* mathematical operations with the notion of
31 "active dims": each operator has zero or more active dims that are used
32 in carrying out the operation. Simple scalar operations like scalar
33 multiplication ('*') have 0 active dims. More complicated operators
34 can have more active dims. For example, matrix multiplication ('x')
35 has 2 active dims. Additional dims are automatically vectorized across
36 -- e.g. multiplying a 2x5-PDL with a 2x5-PDL requires 10 simple
37 multiplication operations, and yields a 2x5-PDL result.
38
39 Broadcasting rules
40 In any PDL expression, the active dims appropriate for each operator
41 are used starting at the 0 dim and working forward through the dim list
42 of each object. All additional dims after the active dims are
43 "broadcast dims". The broadcast dims do not have to agree exactly:
44 they are coerced to agree according to simple rules:
45
46 • Null PDLs match any dim list (see below).
47
48 • Dims with sizes other than 1 must all agree in size.
49
50 • Dims of size 1 are silently repeated as necessary except for
51 "[phys]" PDLs.
52
53 • Missing dims are expanded appropriately.
54
55 A size-1 dim for "[phys]" PDLs causes an exception if the dim is used
56 in another parameter and has a size greater than 1.
57
58 The "size 1" rule implements "generalized scalar" operation, by analogy
59 to scalar multiplication. The "missing dims" rule acknowledges the
60 ambiguity between a missing dim and a dim of size 1.
61
62 Null PDLs
63 PDLs on the left-hand side of assignment can have the special value
64 "Null". A null PDL has no dim list and no set size; its shape is
65 determined by the computed shape of the expression being assigned to
66 it. Null PDLs contain no values and can only be assigned to. When
67 assigned to (e.g. via the ".=" operator), they cease to be null PDLs.
68
69 To create a null PDL, use "PDL->null()".
70
71 Empty PDLs
72 PDLs can represent the empty set using "structured Empty" variables.
73 An empty PDL is not a null PDL.
74
75 Any dim of a PDL can be set explicitly to size 0. If so, the PDL
76 contains zero values (because the total number of values is the product
77 of all the sizes in the PDL's shape or dimlist).
78
79 Scalar PDLs are zero-dimensional and have no entries in the dim list,
80 so they cannot be empty. 1-D and higher PDLs can be empty. Empty PDLs
81 are useful for set operations, and are most commonly encountered in the
82 output from selection operators such as which and whichND. Not all
83 empty PDLs have the same broadcasting properties -- e.g. a 2x0-PDL
84 represents a collection of 2-vectors that happens to contain no
85 elements, while a simple 0-PDL represents a collection of scalar values
86 (that also happens to contain no elements).
87
88 Note that 0 dims are not adjustable via the broadcasting rules -- a dim
89 with size 0 can only match a corresponding dim of size 0 or 1.
90
91 Broadcast rules and assignments
92 Versions of PDL through 2.4.10 have some irregularity with broadcasting
93 and assignments. Currently the broadcasting engine performs a full
94 expansion of both sides of the computed assignment operator ".=" (which
95 assigns values to a pre-existing PDL). This leads to counter-intuitive
96 behavior in some cases:
97
98 • Empty PDLs and generalized scalars
99
100 Generalized scalars (PDLs with a dim of size 1) can match any size
101 in the corresponding dim, including 0. Thus,
102
103 $x = ones(2,0);
104 $y = sequence(2,1);
105 $c = $x * $y;
106 print $c;
107
108 prints "Empty[2,0]".
109
110 This behavior is counterintuitive but desirable, and will be
111 preserved in future versions of PDL.
112
114 These are important variables of global scope and are placed in the PDL
115 namespace.
116
117 $PDL::debug
118
119 When true, PDL debugging information is printed.
120
121 $PDL::verbose
122
123 When true, PDL functions provide chatty information.
124
125 $PDL::use_commas
126
127 Whether to insert commas when printing pdls
128
129 $PDL::floatformat, $PDL::doubleformat, $PDL::indxformat
130
131 The default print format for floats, doubles, and indx values,
132 respectively. The default default values are:
133
134 $PDL::floatformat = "%7g";
135 $PDL::doubleformat = "%10.8g";
136 $PDL::indxformat = "%12d";
137
138 $PDL::undefval
139
140 The value to use instead of "undef" when creating pdls. If is
141 "undef", 0 will be used.
142
143 $PDL::toolongtoprint
144
145 The maximal size pdls to print (defaults to 10000 elements)
146
148 barf
149 Standard error reporting routine for PDL.
150
151 barf() is the routine PDL modules should call to report errors. This is
152 because barf() will report the error as coming from the correct line in
153 the module user's script rather than in the PDL module.
154
155 For now, barf just calls Carp::confess()
156
157 Remember barf() is your friend. *Use* it!
158
159 At the perl level:
160
161 barf("User has too low an IQ!");
162
163 In C or XS code:
164
165 barf("You have made %d errors", count);
166
167 Note: this is one of the few functions ALWAYS exported by PDL::Core
168
169 pdl
170 PDL constructor - creates new ndarray from perl scalars/arrays,
171 ndarrays, and strings
172
173 $double_pdl = pdl(SCALAR|ARRAY REFERENCE|ARRAY|STRING); # default type
174 $type_pdl = pdl(PDL::Type,SCALAR|ARRAY REFERENCE|ARRAY|STRING);
175
176 $x = pdl [1..10]; # 1D array of doubles
177 $x = pdl ([1..10]); # 1D array
178 $x = pdl (1,2,3,4); # Ditto
179 $y = pdl [[1,2,3],[4,5,6]]; # 2D 3x2 array
180 $y = pdl "[[1,2,3],[4,5,6]]"; # Ditto (slower)
181 $y = pdl "[1 2 3; 4 5 6]"; # Ditto
182 $y = pdl q[1 2 3; 4 5 6]; # Ditto, using the q quote operator
183 $y = pdl "1 2 3; 4 5 6"; # Ditto, less obvious, but still works
184 $y = pdl 42 # 0-dimensional scalar
185 $c = pdl $x; # Make a new copy
186
187 $u = pdl ushort(), 42 # 0-dimensional ushort scalar
188 $y = pdl(byte(),[[1,2,3],[4,5,6]]); # 2D byte ndarray
189
190 $n = pdl indx(), [1..5]; # 1D array of indx values
191 $n = pdl indx, [1..5]; # ... can leave off parens
192 $n = indx( [1..5] ); # ... still the same!
193
194 $n = pdl cdouble, 2, 3; # native complex numbers, zero imaginary
195 use Math::Complex qw(cplx);
196 $n = pdl cdouble, 2, cplx(2, 1)); # explicit type
197 $n = pdl 2, cplx(2, 1); # default cdouble if Math::Complex obj
198
199 $x = pdl([[1,2,3],[4,5,6]]); # 2D
200 $x = pdl([1,2,3],[4,5,6]); # 2D
201
202 Note the last two are equivalent - a list is automatically converted to
203 a list reference for syntactic convenience. i.e. you can omit the outer
204 "[]"
205
206 You can mix and match arrays, array refs, and PDLs in your argument
207 list, and "pdl" will sort them out. You get back a PDL whose last
208 (slowest running) dim runs across the top level of the list you hand
209 in, and whose first (fastest running) dim runs across the deepest level
210 that you supply.
211
212 At the moment, you cannot mix and match those arguments with string
213 arguments, though we can't imagine a situation in which you would
214 really want to do that.
215
216 The string version of pdl also allows you to use the strings "bad",
217 "inf", and "nan", and it will insert the values that you mean (and set
218 the bad flag if you use "bad"). You can mix and match case, though you
219 shouldn't. Here are some examples:
220
221 $bad = pdl q[1 2 3 bad 5 6]; # Set fourth element to the bad value
222 $bad = pdl q[1 2 3 BAD 5 6]; # ditto
223 $bad = pdl q[1 2 inf bad 5]; # now third element is IEEE infinite value
224 $bad = pdl q[nan 2 inf -inf]; # first value is IEEE nan value
225
226 The default constructor uses IEEE double-precision floating point
227 numbers. You can use other types, but you will get a warning if you try
228 to use "nan" with integer types (it will be replaced with the "bad"
229 value) and you will get a fatal error if you try to use "inf".
230
231 Throwing a PDL into the mix has the same effect as throwing in a list
232 ref:
233
234 pdl(pdl(1,2),[3,4])
235
236 is the same as
237
238 pdl([1,2],[3,4]).
239
240 All of the dimensions in the list are "padded-out" with undefval to
241 meet the widest dim in the list, so (e.g.)
242
243 $x = pdl([[1,2,3],[2]])
244
245 gives you the same answer as
246
247 $x = pdl([[1,2,3],[2,undef,undef]]);
248
249 If your PDL module has bad values compiled into it (see PDL::Bad), you
250 can pass BAD values into the constructor within pre-existing PDLs. The
251 BAD values are automatically kept BAD and propagated correctly.
252
253 pdl() is a functional synonym for the 'new' constructor, e.g.:
254
255 $x = new PDL [1..10];
256
257 In order to control how undefs are handled in converting from perl
258 lists to PDLs, one can set the variable $PDL::undefval. For example:
259
260 $foo = [[1,2,undef],[undef,3,4]];
261 $PDL::undefval = -999;
262 $f = pdl $foo;
263 print $f
264 [
265 [ 1 2 -999]
266 [-999 3 4]
267 ]
268
269 $PDL::undefval defaults to zero.
270
271 As a final note, if you include an Empty PDL in the list of objects to
272 construct into a PDL, it is kept as a placeholder pane -- so if you
273 feed in (say) 7 objects, you get a size of 7 in the 0th dim of the
274 output PDL. The placeholder panes are completely padded out. But if
275 you feed in only a single Empty PDL, you get back the Empty PDL (no
276 padding).
277
278 empty
279 Returns an empty ndarray, with a single zero-length dimension. Only
280 available as a function, not a method.
281
282 $x = empty; # defaults to lowest type so it can always be promoted up
283 $x = empty(float);
284
285 null
286 Returns a 'null' ndarray. It is an error to pass one of these as an
287 input to a function.
288
289 $x = null;
290
291 null() has a special meaning to PDL::PP. It is used to flag a special
292 kind of empty ndarray, which can grow to appropriate dimensions to
293 store a result (as opposed to storing a result in an existing ndarray).
294
295 pdl> sumover sequence(10,10), $ans=null;p $ans
296 [45 145 245 345 445 545 645 745 845 945]
297
298 nullcreate
299 Returns a 'null' ndarray.
300
301 $x = PDL->nullcreate($arg)
302
303 This is an routine used by many of the broadcasting primitives (i.e.
304 sumover, minimum, etc.) to generate a null ndarray for the function's
305 output that will behave properly for derived (or subclassed) PDL
306 objects.
307
308 For the above usage: If $arg is a PDL, or a derived PDL, then
309 "$arg->null" is returned. If $arg is a scalar (i.e. a zero-dimensional
310 PDL) then "PDL->null" is returned.
311
312 PDL::Derived->nullcreate(10)
313 returns PDL::Derived->null.
314 PDL->nullcreate($pdlderived)
315 returns $pdlderived->null.
316
317 nelem
318 Return the number of elements in an ndarray
319
320 $n = nelem($ndarray); $n = $ndarray->nelem;
321
322 $mean = sum($data)/nelem($data);
323
324 dims
325 Return ndarray dimensions as a perl list
326
327 @dims = $ndarray->dims; @dims = dims($ndarray);
328
329 pdl> p @tmp = dims zeroes 10,3,22
330 10 3 22
331
332 See also "shape" which returns an ndarray instead.
333
334 shape
335 Return ndarray dimensions as an ndarray
336
337 $shape = $ndarray->shape; $shape = shape($ndarray);
338
339 pdl> p $shape = shape zeroes 10,3,22
340 [10 3 22]
341
342 See also "dims" which returns a perl list.
343
344 ndims
345 Returns the number of dimensions in an ndarray. Alias for getndims.
346
347 getndims
348 Returns the number of dimensions in an ndarray
349
350 $ndims = $ndarray->getndims;
351
352 pdl> p zeroes(10,3,22)->getndims
353 3
354
355 dim
356 Returns the size of the given dimension of an ndarray. Alias for
357 getdim.
358
359 getdim
360 Returns the size of the given dimension.
361
362 $dim0 = $ndarray->getdim(0);
363
364 pdl> p zeroes(10,3,22)->getdim(1)
365 3
366
367 Negative indices count from the end of the dims array. Indices beyond
368 the end will return a size of 1. This reflects the idea that any pdl is
369 equivalent to an infinitely dimensional array in which only a finite
370 number of dimensions have a size different from one. For example, in
371 that sense a 3D ndarray of shape [3,5,2] is equivalent to a
372 [3,5,2,1,1,1,1,1,....] ndarray. Accordingly,
373
374 print $x->getdim(10000);
375
376 will print 1 for most practically encountered ndarrays.
377
378 topdl
379 alternate ndarray constructor - ensures arg is an ndarray
380
381 $x = topdl(SCALAR|ARRAY REFERENCE|ARRAY);
382
383 The difference between pdl() and topdl() is that the latter will just
384 'fall through' if the argument is already an ndarray. It will return a
385 reference and NOT a new copy.
386
387 This is particularly useful if you are writing a function which is
388 doing some fiddling with internals and assumes an ndarray argument
389 (e.g. for method calls). Using topdl() will ensure nothing breaks if
390 passed with '2'.
391
392 Note that topdl() is not exported by default (see example below for
393 usage).
394
395 use PDL::Core ':Internal'; # use the internal routines of
396 # the Core module
397
398 $x = topdl 43; # $x is ndarray with value '43'
399 $y = topdl $ndarray; # fall through
400 $x = topdl (1,2,3,4); # Convert 1D array
401
402 get_datatype
403 Internal: Return the numeric value identifying the ndarray datatype
404
405 $x = $ndarray->get_datatype;
406
407 Mainly used for internal routines.
408
409 NOTE: get_datatype returns 'just a number' not any special type object,
410 unlike "type".
411
412 howbig
413 Returns the sizeof an ndarray datatype in bytes.
414
415 Note that howbig() is not exported by default (see example below for
416 usage).
417
418 use PDL::Core ':Internal'; # use the internal routines of
419 # the Core module
420
421 $size = howbig($ndarray->get_datatype);
422
423 Mainly used for internal routines.
424
425 NOTE: NOT a method! This is because get_datatype returns 'just a
426 number' not any special object.
427
428 pdl> p howbig(ushort([1..10])->get_datatype)
429 2
430
431 get_dataref
432 Return the internal data for an ndarray, as a perl SCALAR ref.
433
434 Most ndarrays hold their internal data in a packed perl string, to take
435 advantage of perl's memory management. This gives you direct access to
436 the string, which is handy when you need to manipulate the binary data
437 directly (e.g. for file I/O). If you modify the string, you'll need to
438 call "upd_data" afterward, to make sure that the ndarray points to the
439 new location of the underlying perl variable.
440
441 Calling "get_dataref" automatically physicalizes your ndarray (see
442 "make_physical"). You definitely don't want to do anything to the SV
443 to truncate or deallocate the string, unless you correspondingly call
444 "reshape" to make the PDL match its new data dimension.
445
446 You definitely don't want to use get_dataref unless you know what you
447 are doing (or are trying to find out): you can end up scrozzling memory
448 if you shrink or eliminate the string representation of the variable.
449 Here be dragons.
450
451 upd_data
452 Update the data pointer in an ndarray to match its perl SV.
453
454 This is useful if you've been monkeying with the packed string
455 representation of the PDL, which you probably shouldn't be doing
456 anyway. (see "get_dataref".)
457
458 broadcastids
459 Returns the ndarray broadcast IDs as a perl list
460
461 Note that broadcastids() is not exported by default (see example below
462 for usage).
463
464 use PDL::Core ':Internal'; # use the internal routines of
465 # the Core module
466
467 @ids = broadcastids $ndarray;
468
469 doflow
470 Turn on dataflow, forward only. This means any transformations (a.k.a.
471 PDL operations) applied to this ndarray afterwards will have forward
472 dataflow:
473
474 $x = sequence 3;
475 $x->doflow;
476 $y = $x + 1;
477 $x += 3;
478 print "$y\n"; # [4 5 6]
479
480 As of 2.064, the core API does not automatically sever transformations
481 that have forward dataflow into them:
482
483 # following from the above
484 $y->set(1, 9); # value now [4 9 6]
485 $x += 11;
486 print "$y\n"; # [15 16 17] - previously would have been [4 9 6]
487
488 If you want to sever such transformations, call "sever" on the child
489 ndarray (above, $y).
490
491 $x->doflow; doflow($x);
492
493 flows
494 Whether or not an ndarray is indulging in dataflow
495
496 something if $x->flows; $hmm = flows($x);
497
498 new
499 new ndarray constructor method
500
501 $x = PDL->new(SCALAR|ARRAY|ARRAY REF|STRING);
502
503 $x = PDL->new(42); # new from a Perl scalar
504 $x = new PDL 42; # ditto
505 $y = PDL->new(@list_of_vals); # new from Perl list
506 $y = new PDL @list_of_vals; # ditto
507 $z = PDL->new(\@list_of_vals); # new from Perl list reference
508 $w = PDL->new("[1 2 3]"); # new from Perl string, using
509 # Matlab constructor syntax
510
511 Constructs ndarray from perl numbers and lists and strings with
512 Matlab/Octave style constructor syntax.
513
514 The string input is fairly versatile though not performance optimized.
515 The goal is to make it easy to copy and paste code from PDL output and
516 to offer a familiar Matlab syntax for ndarray construction. As of May,
517 2010, it is a new feature, so feel free to report bugs or suggest new
518 features. See documentation for pdl for more examples of usage.
519
520 copy
521 Make a physical copy of an ndarray
522
523 $new = $old->copy;
524
525 Since "$new = $old" just makes a new reference, the "copy" method is
526 provided to allow real independent copies to be made.
527
528 hdr_copy
529 Return an explicit copy of the header of a PDL.
530
531 hdr_copy is just a wrapper for the internal routine _hdr_copy, which
532 takes the hash ref itself. That is the routine which is used to make
533 copies of the header during normal operations if the hdrcpy() flag of a
534 PDL is set.
535
536 General-purpose deep copies are expensive in perl, so some simple
537 optimization happens:
538
539 If the header is a tied array or a blessed hash ref with an associated
540 method called "copy", then that ->copy method is called. Otherwise,
541 all elements of the hash are explicitly copied. References are
542 recursively deep copied.
543
544 This routine seems to leak memory.
545
546 unwind
547 Return an ndarray which is the same as the argument except that all
548 broadcastids have been removed.
549
550 $y = $x->unwind;
551
552 make_physical
553 Make sure the data portion of an ndarray can be accessed from XS code.
554
555 $x->make_physical;
556 $x->call_my_xs_method;
557
558 Ensures that an ndarray gets its own allocated copy of data. This
559 obviously implies that there are certain ndarrays which do not have
560 their own data. These are so called virtual ndarrays that make use of
561 the vaffine optimisation (see PDL::Indexing). They do not have their
562 own copy of data but instead store only access information to some (or
563 all) of another ndarray's data.
564
565 Note: this function should not be used unless absolutely necessary
566 since otherwise memory requirements might be severely increased.
567 Instead of writing your own XS code with the need to call
568 "make_physical" you might want to consider using the PDL preprocessor
569 (see PDL::PP) which can be used to transparently access virtual
570 ndarrays without the need to physicalise them (though there are
571 exceptions).
572
573 dummy
574 Insert a 'dummy dimension' of given length (defaults to 1)
575
576 No relation to the 'Dungeon Dimensions' in Discworld!
577
578 Negative positions specify relative to last dimension, i.e. dummy(-1)
579 appends one dimension at end, dummy(-2) inserts a dummy dimension in
580 front of the last dim, etc.
581
582 If you specify a dimension position larger than the existing dimension
583 list of your PDL, the PDL gets automagically padded with extra dummy
584 dimensions so that you get the dim you asked for, in the slot you asked
585 for. This could cause you trouble if, for example, you ask for
586 $x->dummy(5000,1) because $x will get 5,000 dimensions, each of rank 1.
587
588 Because padding at the beginning of the dimension list moves existing
589 dimensions from slot to slot, it's considered unsafe, so automagic
590 padding doesn't work for large negative indices -- only for large
591 positive indices.
592
593 $y = $x->dummy($position[,$dimsize]);
594
595 pdl> p sequence(3)->dummy(0,3)
596 [
597 [0 0 0]
598 [1 1 1]
599 [2 2 2]
600 ]
601
602 pdl> p sequence(3)->dummy(3,2)
603 [
604 [
605 [0 1 2]
606 ]
607 [
608 [0 1 2]
609 ]
610 ]
611
612 pdl> p sequence(3)->dummy(-3,2)
613 Runtime error: PDL: For safety, <pos> < -(dims+1) forbidden in dummy. min=-2, pos=-3
614
615 dup
616 Duplicates an ndarray along a dimension
617
618 $x = sequence(3);
619 $y = $x->dup(0, 2); # doubles along first dimension
620 # $y now [0 1 2 0 1 2]
621
622 dupN
623 Duplicates an ndarray along several dimensions
624
625 $x = sequence(3,2);
626 $y = $x->dupN(2, 3); # doubles along first dimension, triples along second
627 # [
628 # [0 1 2 0 1 2]
629 # [3 4 5 3 4 5]
630 # [0 1 2 0 1 2]
631 # [3 4 5 3 4 5]
632 # ]
633
634 inflateN
635 Inflates an ndarray along several dimensions, useful for e.g. Kronecker
636 products
637
638 cf "dupN"
639
640 $x = sequence(3,2);
641 $y = $x->inflateN(2, 2); # doubles along first two dimensions
642 # [
643 # [0 0 1 1 2 2]
644 # [0 0 1 1 2 2]
645 # [3 3 4 4 5 5]
646 # [3 3 4 4 5 5]
647 # ]
648
649 clump
650 "clumps" several dimensions into one large dimension
651
652 If called with one argument $n clumps the first $n dimensions into one.
653 For example, if $x has dimensions "(5,3,4)" then after
654
655 $y = $x->clump(2); # Clump 2 first dimensions
656
657 the variable $y will have dimensions "(15,4)" and the element
658 "$y->at(7,3)" refers to the element "$x->at(1,2,3)".
659
660 Use clump(-1) to flatten an ndarray. The method flat is provided as a
661 convenient alias.
662
663 Clumping with a negative dimension in general leaves that many
664 dimensions behind -- e.g. clump(-2) clumps all of the first few
665 dimensions into a single one, leaving a 2-D ndarray.
666
667 If "clump" is called with an index list with more than one element it
668 is treated as a list of dimensions that should be clumped together into
669 one. The resulting clumped dim is placed at the position of the lowest
670 index in the list. This convention ensures that "clump" does the
671 expected thing in the usual cases. The following example demonstrates
672 typical usage:
673
674 $x = sequence 2,3,3,3,5; # 5D ndarray
675 $c = $x->clump(1..3); # clump all the dims 1 to 3 into one
676 print $c->info; # resulting 3D ndarray has clumped dim at pos 1
677 PDL: Double D [2,27,5]
678
679 broadcast_define
680 define functions that support broadcasting at the perl level
681
682 broadcast_define 'tline(a(n);b(n))', over {
683 line $_[0], $_[1]; # make line compliant with broadcasting
684 };
685
686 "broadcast_define" provides some support for broadcasting (see
687 PDL::Indexing) at the perl level. It allows you to do things for which
688 you normally would have resorted to PDL::PP (see PDL::PP); however, it
689 is most useful to wrap existing perl functions so that the new routine
690 supports PDL broadcasting.
691
692 "broadcast_define" is used to define new broadcasting aware functions.
693 Its first argument is a symbolic repesentation of the new function to
694 be defined. The string is composed of the name of the new function
695 followed by its signature (see PDL::Indexing and PDL::PP) in
696 parentheses. The second argument is a subroutine that will be called
697 with the slices of the actual runtime arguments as specified by its
698 signature. Correct dimension sizes and minimal number of dimensions for
699 all arguments will be checked (assuming the rules of PDL broadcasting,
700 see PDL::Indexing).
701
702 The actual work is done by the "signature" class which parses the
703 signature string, does runtime dimension checks and the routine
704 "broadcastover" that generates the loop over all appropriate slices of
705 pdl arguments and creates pdls as needed.
706
707 Similar to "pp_def" and its "OtherPars" option it is possible to define
708 the new function so that it accepts normal perl args as well as
709 ndarrays. You do this by using the "NOtherPars" parameter in the
710 signature. The number of "NOtherPars" specified will be passed
711 unaltered into the subroutine given as the second argument of
712 "broadcast_define". Let's illustrate this with an example:
713
714 PDL::broadcast_define 'triangles(inda();indb();indc()), NOtherPars => 2',
715 PDL::over {
716 ${$_[3]} .= $_[4].join(',',map {$_->at} @_[0..2]).",-1,\n";
717 };
718
719 This defines a function "triangles" that takes 3 ndarrays as input plus
720 2 arguments which are passed into the routine unaltered. This routine
721 is used to collect lists of indices into a perl scalar that is passed
722 by reference. Each line is preceded by a prefix passed as $_[4]. Here
723 is typical usage:
724
725 $txt = '';
726 triangles(pdl(1,2,3),pdl(1),pdl(0),\$txt," "x10);
727 print $txt;
728
729 resulting in the following output
730
731 1,1,0,-1,
732 2,1,0,-1,
733 3,1,0,-1,
734
735 which is used in PDL::Graphics::TriD::VRML to generate VRML output.
736
737 Currently, this is probably not much more than a POP (proof of
738 principle) but is hoped to be useful enough for some real life work.
739
740 Check PDL::PP for the format of the signature. Currently, the "[t]"
741 qualifier and all type qualifiers are ignored.
742
743 broadcast
744 Use explicit broadcasting over specified dimensions (see also
745 PDL::Indexing)
746
747 $y = $x->broadcast($dim,[$dim1,...])
748
749 $x = zeroes 3,4,5;
750 $y = $x->broadcast(2,0);
751
752 Same as "broadcast1", i.e. uses broadcast id 1.
753
754 broadcast1
755 Explicit broadcasting over specified dims using broadcast id 1.
756
757 $xx = $x->broadcast1(3,1)
758
759 Wibble
760
761 Convenience function interfacing to PDL::Slices::broadcastI.
762
763 broadcast2
764 Explicit broadcasting over specified dims using broadcast id 2.
765
766 $xx = $x->broadcast2(3,1)
767
768 Wibble
769
770 Convenience function interfacing to PDL::Slices::broadcastI.
771
772 broadcast3
773 Explicit broadcasting over specified dims using broadcast id 3.
774
775 $xx = $x->broadcast3(3,1)
776
777 Wibble
778
779 Convenience function interfacing to PDL::Slices::broadcastI.
780
781 sever
782 sever any links of this ndarray to parent ndarrays
783
784 In PDL it is possible for an ndarray to be just another view into
785 another ndarray's data. In that case we call this ndarray a virtual
786 ndarray and the original ndarray owning the data its parent. In other
787 languages these alternate views sometimes run by names such as alias or
788 smart reference.
789
790 Typical functions that return such ndarrays are "slice", "xchg",
791 "index", etc. Sometimes, however, you would like to separate the
792 virtual ndarray from its parent's data and just give it a life of its
793 own (so that manipulation of its data doesn't change the parent). This
794 is simply achieved by using "sever". For example,
795
796 $x = $pdl->index(pdl(0,3,7))->sever;
797 $x++; # important: $pdl is not modified!
798
799 In many (but not all) circumstances it acts therefore similar to copy.
800 However, in general performance is better with "sever" and secondly,
801 "sever" doesn't lead to futile copying when used on ndarrays that
802 already have their own data. On the other hand, if you really want to
803 make sure to work on a copy of an ndarray use copy.
804
805 $x = zeroes(20);
806 $x->sever; # NOOP since $x is already its own boss!
807
808 Again note: "sever" is not the same as copy! For example,
809
810 $x = zeroes(1); # $x does not have a parent, i.e. it is not a slice etc
811 $y = $x->sever; # $y is now pointing to the same ndarray as $x
812 $y++;
813 print $x;
814 [1]
815
816 but
817
818 $x = zeroes(1);
819 $y = $x->copy; # $y is now pointing to a new ndarray
820 $y++;
821 print $x;
822 [0]
823
824 info
825 Return formatted information about an ndarray.
826
827 $x->info($format_string);
828
829 print $x->info("Type: %T Dim: %-15D State: %S");
830
831 Returns a string with info about an ndarray. Takes an optional argument
832 to specify the format of information a la sprintf. Format specifiers
833 are in the form "%<width><letter>" where the width is optional and the
834 letter is one of
835
836 T Type
837
838 D Formatted Dimensions
839
840 F Dataflow status
841
842 S Some internal flags (P=physical,V=Vaffine,C=changed,B=may
843 contain bad data)
844
845 C Class of this ndarray, i.e. "ref $pdl"
846
847 A Address of the ndarray struct as a unique identifier
848
849 M Calculated memory consumption of this ndarray's data area
850
851 approx
852 test for approximately equal values (relaxed "==")
853
854 # ok if all corresponding values in
855 # ndarrays are within 1e-8 of each other
856 print "ok\n" if all approx $x, $y, 1e-8;
857
858 "approx" is a relaxed form of the "==" operator and often more
859 appropriate for floating point types ("float" and "double").
860
861 Usage:
862
863 $res = approx $x, $y [, $eps]
864
865 The optional parameter $eps is remembered across invocations and
866 initially set to 1e-6, e.g.
867
868 approx $x, $y; # last $eps used (1e-6 initially)
869 approx $x, $y, 1e-10; # 1e-10
870 approx $x, $y; # also 1e-10
871
872 mslice
873 Alias to "slice" in PDL::Slices.
874
875 nslice_if_pdl
876 If $self is a PDL, then calls "slice" with all but the last argument,
877 otherwise $self->($_[-1]) is called where $_[-1} is the original
878 argument string found during PDL::NiceSlice filtering.
879
880 DEVELOPER'S NOTE: this routine is found in Core.pm.PL but would be
881 better placed in Slices/slices.pd. It is likely to be moved there
882 and/or changed to "slice_if_pdl" for PDL 3.0.
883
884 $w = $x->nslice_if_pdl(...,'(args)');
885
886 inplace
887 Flag an ndarray so that the next operation is done 'in place'
888
889 somefunc($x->inplace); somefunc(inplace $x);
890
891 In most cases one likes to use the syntax "$y = f($x)", however in many
892 case the operation f() can be done correctly 'in place', i.e. without
893 making a new copy of the data for output. To make it easy to use this,
894 we write f() in such a way that it operates in-place, and use "inplace"
895 to hint that a new copy should be disabled. This also makes for clear
896 syntax.
897
898 Obviously this will not work for all functions, and if in doubt see the
899 function's documentation. However one can assume this is true for all
900 elemental functions (i.e. those which just operate array element by
901 array element like "log10").
902
903 pdl> $x = xvals zeroes 10;
904 pdl> log10(inplace $x)
905 pdl> p $x
906 [-inf 0 0.30103 0.47712125 0.60205999 0.69897 0.77815125 0.84509804 0.90308999 0.95424251]
907
908 is_inplace
909 Test the in-place flag on an ndarray
910
911 $out = ($in->is_inplace) ? $in : zeroes($in);
912 $in->set_inplace(0)
913
914 Provides access to the "inplace" hint flag, within the perl milieu.
915 That way functions you write can be inplace aware... If given an
916 argument the inplace flag will be set or unset depending on the value
917 at the same time. Can be used for shortcut tests that delete the
918 inplace flag while testing:
919
920 $out = ($in->is_inplace(0)) ? $in : zeroes($in); # test & unset!
921
922 set_inplace
923 Set the in-place flag on an ndarray
924
925 $out = ($in->is_inplace) ? $in : zeroes($in);
926 $in->set_inplace(0);
927
928 Provides access to the "inplace" hint flag, within the perl milieu.
929 Useful mainly for turning it OFF, as "inplace" turns it ON more
930 conveniently.
931
932 new_or_inplace
933 $w = new_or_inplace(shift());
934 $w = new_or_inplace(shift(),$preferred_type);
935
936 Return back either the argument pdl or a copy of it depending on
937 whether it be flagged in-place or no. Handy for building inplace-aware
938 functions.
939
940 If you specify a preferred type (must be one of the usual PDL type
941 strings, a list ref containing several of them, or a comma-separated
942 string containing several of them), then the copy is coerced into the
943 first preferred type listed if it is not already one of the preferred
944 types.
945
946 Note that if the inplace flag is set, no coercion happens even if you
947 specify a preferred type.
948
949 new_from_specification
950 Internal method: create ndarray by specification
951
952 This is the argument processing method called by "zeroes" and some
953 other functions which constructs ndarrays from argument lists of the
954 form:
955
956 [type], $nx, $ny, $nz,...
957
958 For $nx, $ny, etc. 0 and 1D ndarrays are allowed. Giving those has the
959 same effect as if saying "$arg->list", e.g.
960
961 1, pdl(5,2), 4
962
963 is equivalent to
964
965 1, 5, 2, 4
966
967 Note, however, that in all functions using "new_from_specification"
968 calling "func $ndarray" will probably not do what you want. So to play
969 safe use (e.g. with zeroes)
970
971 $pdl = zeroes $dimpdl->list;
972
973 Calling
974
975 $pdl = zeroes $dimpdl;
976
977 will rather be equivalent to
978
979 $pdl = zeroes $dimpdl->dims;
980
981 However,
982
983 $pdl = zeroes ushort, $dimpdl;
984
985 will again do what you intended since it is interpreted as if you had
986 said
987
988 $pdl = zeroes ushort, $dimpdl->list;
989
990 This is unfortunate and confusing but no good solution seems obvious
991 that would not break existing scripts.
992
993 isnull
994 Test whether an ndarray is null
995
996 croak("Input ndarray mustn't be null!")
997 if $input_ndarray->isnull;
998
999 This function returns 1 if the ndarray is null, zero if it is not. The
1000 purpose of null ndarrays is to "tell" any PDL::PP methods to allocate
1001 new memory for an output ndarray, but only when that PDL::PP method is
1002 called in full-arg form. Of course, there's no reason you couldn't
1003 commandeer the special value for your own purposes, for which this test
1004 function would prove most helpful. But in general, you shouldn't need
1005 to test for an ndarray's nullness.
1006
1007 See "Null PDLs" for more information.
1008
1009 isempty
1010 Test whether an ndarray is empty
1011
1012 print "The ndarray has zero dimension\n" if $pdl->isempty;
1013
1014 This function returns 1 if the ndarray has zero elements. This is
1015 useful in particular when using the indexing function which. In the
1016 case of no match to a specified criterion, the returned ndarray has
1017 zero dimension.
1018
1019 pdl> $w=sequence(10)
1020 pdl> $i=which($w < -1)
1021 pdl> print "I found no matches!\n" if ($i->isempty);
1022 I found no matches!
1023
1024 Note that having zero elements is rather different from the concept of
1025 being a null ndarray, see the PDL::FAQ and PDL::Indexing manpages for
1026 discussions of this.
1027
1028 zeroes
1029 construct a zero filled ndarray from dimension list or template
1030 ndarray. If called with no arguments, returns a zero-dimension ndarray
1031 (a scalar).
1032
1033 Various forms of usage,
1034
1035 (i) by specification or (ii) by template ndarray:
1036
1037 # usage type (i):
1038 $w = zeroes([type], $nx, $ny, $nz,...);
1039 $w = PDL->zeroes([type], $nx, $ny, $nz,...);
1040 $w = $pdl->zeroes([type], $nx, $ny, $nz,...); # all info about $pdl ignored
1041 # usage type (ii):
1042 $w = zeroes $y;
1043 $w = $y->zeroes
1044 zeroes inplace $w; # Equivalent to $w .= 0;
1045 $w->inplace->zeroes; # ""
1046
1047 pdl> $z = zeroes 4,3
1048 pdl> p $z
1049 [
1050 [0 0 0 0]
1051 [0 0 0 0]
1052 [0 0 0 0]
1053 ]
1054 pdl> $z = zeroes ushort, 3,2 # Create ushort array
1055 [ushort() etc. with no arg returns a PDL::Types token]
1056
1057 See also "new_from_specification" for details on using ndarrays in the
1058 dimensions list.
1059
1060 zeros
1061 construct a zero filled ndarray (see zeroes for usage)
1062
1063 ones
1064 construct a one filled ndarray. If called with no arguments, returns a
1065 zero-dimension ndarray (a scalar).
1066
1067 $w = ones([type], $nx, $ny, $nz,...);
1068 etc. (see 'zeroes')
1069
1070 see zeroes() and add one
1071
1072 See also "new_from_specification" for details on using ndarrays in the
1073 dimensions list.
1074
1075 nan
1076 construct a "NaN" filled ndarray. If called with no arguments, returns
1077 a zero-dimension ndarray (a scalar).
1078
1079 $w = nan([type], $nx, $ny, $nz,...);
1080 etc. (see 'zeroes')
1081
1082 see zeroes() and add NaN
1083
1084 See also "new_from_specification" for details on using ndarrays in the
1085 dimensions list.
1086
1087 inf
1088 construct an "Inf" filled ndarray. If called with no arguments,
1089 returns a zero-dimension ndarray (a scalar).
1090
1091 $w = inf([type], $nx, $ny, $nz,...);
1092 etc. (see 'zeroes')
1093
1094 see zeroes() and add Inf
1095
1096 See also "new_from_specification" for details on using ndarrays in the
1097 dimensions list.
1098
1099 i
1100 construct an ndarray filled with a native complex value equal to the
1101 imaginary number "i", the square root of -1. If called with no
1102 arguments, returns a zero-dimension ndarray (a scalar).
1103
1104 $w = i([type], $nx, $ny, $nz,...);
1105 etc. (see 'zeroes')
1106
1107 see zeroes() and add "i"
1108
1109 See also "new_from_specification" for details on using ndarrays in the
1110 dimensions list.
1111
1112 reshape
1113 Change the shape (i.e. dimensions) of an ndarray, preserving contents.
1114
1115 $x->reshape(NEWDIMS); reshape($x, NEWDIMS);
1116
1117 The data elements are preserved, obviously they will wrap differently
1118 and get truncated if the new array is shorter. If the new array is
1119 longer it will be zero-padded.
1120
1121 ***Potential incompatibility with earlier versions of PDL**** If the
1122 list of "NEWDIMS" is empty "reshape" will just drop all dimensions of
1123 size 1 (preserving the number of elements):
1124
1125 $w = sequence(3,4,5);
1126 $y = $w(1,3);
1127 $y->reshape();
1128 print $y->info;
1129 PDL: Double D [5]
1130
1131 Dimensions of size 1 will also be dropped if "reshape" is invoked with
1132 the argument -1:
1133
1134 $y = $w->reshape(-1);
1135
1136 As opposed to "reshape" without arguments, reshape(-1) preserves
1137 dataflow:
1138
1139 $w = ones(2,1,2);
1140 $y = $w(0)->reshape(-1);
1141 $y++;
1142 print $w;
1143 [
1144 [
1145 [2 1]
1146 ]
1147 [
1148 [2 1]
1149 ]
1150 ]
1151
1152 Important: ndarrays are changed inplace!
1153
1154 Note: If $x is connected to any other PDL (e.g. if it is a slice) then
1155 the connection is first severed.
1156
1157 pdl> $x = sequence(10)
1158 pdl> reshape $x,3,4; p $x
1159 [
1160 [0 1 2]
1161 [3 4 5]
1162 [6 7 8]
1163 [9 0 0]
1164 ]
1165 pdl> reshape $x,5; p $x
1166 [0 1 2 3 4]
1167
1168 squeeze
1169 eliminate all singleton dimensions (dims of size 1)
1170
1171 $y = $w(0,0)->squeeze;
1172
1173 Alias for reshape(-1). Removes all singleton dimensions and preserves
1174 dataflow. A more concise interface is provided by PDL::NiceSlice via
1175 modifiers:
1176
1177 use PDL::NiceSlice;
1178 $y = $w(0,0;-); # same as $w(0,0)->squeeze
1179
1180 flat
1181 flatten an ndarray (alias for "$pdl->clump(-1)")
1182
1183 $srt = $pdl->flat->qsort;
1184
1185 Useful method to make a 1D ndarray from an arbitrarily sized input
1186 ndarray. Data flows back and forth as usual with slicing routines.
1187 Falls through if argument already <= 1D.
1188
1189 convert
1190 Generic datatype conversion function
1191
1192 $y = convert($x, $newtype);
1193
1194 $newtype is a type number or PDL::Type object, for convenience they are
1195 returned by long() etc when called without arguments.
1196
1197 $y = convert $x, long;
1198 $y = convert $x, ushort;
1199
1200 Datatype_conversions
1201 sbyte|byte|short|ushort|long|ulong|indx|longlong|ulonglong|float|double|ldouble|cfloat|cdouble|cldouble
1202 (shorthands to convert datatypes)
1203
1204 $y = double $x; $y = ushort [1..10];
1205 # all of the above listed shorthands behave similarly
1206
1207 When called with an ndarray argument, they convert to the specific
1208 datatype.
1209
1210 When called with a numeric, list, listref, or string argument they
1211 construct a new ndarray. This is a convenience to avoid having to be
1212 long-winded and say "$x = long(pdl(42))"
1213
1214 Thus one can say:
1215
1216 $w = float(1,2,3,4); # 1D
1217 $w = float q[1 2 3; 4 5 6]; # 2D
1218 $w = float([1,2,3],[4,5,6]); # 2D
1219 $w = float([[1,2,3],[4,5,6]]); # 2D
1220
1221 Note the last three give identical results, and the last two are
1222 exactly equivalent - a list is automatically converted to a list
1223 reference for syntactic convenience. i.e. you can omit the outer "[]"
1224
1225 When called with no arguments, these functions return a special type
1226 token. This allows syntactical sugar like:
1227
1228 $x = ones byte, 1000,1000;
1229
1230 This example creates a large ndarray directly as byte datatype in order
1231 to save memory.
1232
1233 In order to control how undefs are handled in converting from perl
1234 lists to PDLs, one can set the variable $PDL::undefval; see the
1235 function pdl() for more details.
1236
1237 pdl> p $x=sqrt float [1..10]
1238 [1 1.41421 1.73205 2 2.23607 2.44949 2.64575 2.82843 3 3.16228]
1239 pdl> p byte $x
1240 [1 1 1 2 2 2 2 2 3 3]
1241
1242 byte
1243 Convert to byte datatype
1244
1245 short
1246 Convert to short datatype
1247
1248 ushort
1249 Convert to ushort datatype
1250
1251 long
1252 Convert to long datatype
1253
1254 indx
1255 Convert to indx datatype
1256
1257 longlong
1258 Convert to longlong datatype
1259
1260 float
1261 Convert to float datatype
1262
1263 double
1264 Convert to double datatype
1265
1266 cfloat
1267 Convert to complex float datatype
1268
1269 cdouble
1270 Convert to complex double datatype
1271
1272 type
1273 return the type of an ndarray as a blessed type object
1274
1275 A convenience function for use with the ndarray constructors, e.g.
1276
1277 $y = PDL->zeroes($x->type,$x->dims,3);
1278 die "must be float" unless $x->type == float;
1279
1280 See also the discussion of the "PDL::Type" class in PDL::Types. Note
1281 that the "PDL::Type" objects have overloaded comparison and stringify
1282 operators so that you can compare and print types:
1283
1284 $x = $x->float if $x->type < float;
1285 $t = $x->type; print "Type is $t\n";
1286
1287 list
1288 Convert ndarray to perl list
1289
1290 @tmp = list $x;
1291
1292 Obviously this is grossly inefficient for the large datasets PDL is
1293 designed to handle. This was provided as a get out while PDL matured.
1294 It should now be mostly superseded by superior constructs, such as
1295 PP/broadcasting. However it is still occasionally useful and is
1296 provided for backwards compatibility.
1297
1298 for (list $x) {
1299 # Do something on each value...
1300 }
1301
1302 list converts any bad values into the string 'BAD'.
1303
1304 unpdl
1305 Convert ndarray to nested Perl array references
1306
1307 $arrayref = unpdl $x;
1308
1309 This function returns a reference to a Perl list-of-lists structure
1310 equivalent to the input ndarray (within the limitation that while
1311 values of elements should be preserved, the detailed datatypes will not
1312 as perl itself basically has "number" data rather than byte, short,
1313 int... E.g., "sum($x - pdl( $x->unpdl ))" should equal 0.
1314
1315 Obviously this is grossly inefficient in memory and processing for the
1316 large datasets PDL is designed to handle. Sometimes, however, you
1317 really want to move your data back to Perl, and with proper
1318 dimensionality, unlike "list".
1319
1320 If you want to round-trip data including the use of "PDL::undefval",
1321 "unpdl" does not support this. However, it is suggested you would
1322 generate an index-set with "$pdl->whereND($pdl == $PDL::undefval)",
1323 then loop over the Perl data, setting those locations to "undef".
1324
1325 use JSON;
1326 my $json = encode_json unpdl $pdl;
1327
1328 unpdl converts any bad values into the string 'BAD'.
1329
1330 listindices
1331 Convert ndarray indices to perl list
1332
1333 @tmp = listindices $x;
1334
1335 @tmp now contains the values "0..nelem($x)".
1336
1337 Obviously this is grossly inefficient for the large datasets PDL is
1338 designed to handle. This was provided as a get out while PDL matured.
1339 It should now be mostly superseded by superior constructs, such as
1340 PP/broadcasting. However it is still occasionally useful and is provied
1341 for backwards compatibility.
1342
1343 for $i (listindices $x) {
1344 # Do something on each value...
1345 }
1346
1347 set
1348 Set a single value inside an ndarray
1349
1350 set $ndarray, @position, $value
1351
1352 @position is a coordinate list, of size equal to the number of
1353 dimensions in the ndarray. Occasionally useful, mainly provided for
1354 backwards compatibility as superseded by use of slice and assignment
1355 operator ".=".
1356
1357 pdl> $x = sequence 3,4
1358 pdl> set $x, 2,1,99
1359 pdl> p $x
1360 [
1361 [ 0 1 2]
1362 [ 3 4 99]
1363 [ 6 7 8]
1364 [ 9 10 11]
1365 ]
1366
1367 at
1368 Returns a single value inside an ndarray as perl scalar. If the
1369 ndarray is a native complex value (cdouble, cfloat), it will be a
1370 PDL::Complex::Overloads object.
1371
1372 $z = at($ndarray, @position); $z=$ndarray->at(@position);
1373
1374 @position is a coordinate list, of size equal to the number of
1375 dimensions in the ndarray. Occasionally useful in a general context,
1376 quite useful too inside PDL internals.
1377
1378 pdl> $x = sequence 3,4
1379 pdl> p $x->at(1,2)
1380 7
1381
1382 at converts any bad values into the string 'BAD'.
1383
1384 sclr
1385 return a single value from an ndarray as a scalar, ignoring whether it
1386 is bad.
1387
1388 $val = $x(10)->sclr;
1389 $val = sclr inner($x,$y);
1390
1391 The "sclr" method is useful to turn a single-element ndarray into a
1392 normal Perl scalar. Its main advantage over using "at" for this purpose
1393 is the fact that you do not need to worry if the ndarray is 0D, 1D or
1394 higher dimensional. Using "at" you have to supply the correct number
1395 of zeroes, e.g.
1396
1397 $x = sequence(10);
1398 $y = $x->slice('4');
1399 print $y->sclr; # no problem
1400 print $y->at(); # error: needs at least one zero
1401
1402 "sclr" is generally used when a Perl scalar is required instead of a
1403 one-element ndarray. As of 2.064, if the input is a multielement
1404 ndarray it will throw an exception.
1405
1406 cat
1407 concatenate ndarrays to N+1 dimensional ndarray
1408
1409 Takes a list of N ndarrays of same shape as argument, returns a single
1410 ndarray of dimension N+1.
1411
1412 pdl> $x = cat ones(3,3),zeroes(3,3),rvals(3,3); p $x
1413 [
1414 [
1415 [1 1 1]
1416 [1 1 1]
1417 [1 1 1]
1418 ]
1419 [
1420 [0 0 0]
1421 [0 0 0]
1422 [0 0 0]
1423 ]
1424 [
1425 [1 1 1]
1426 [1 0 1]
1427 [1 1 1]
1428 ]
1429 ]
1430
1431 The output ndarray is set bad if any input ndarrays have their bad flag
1432 set.
1433
1434 Similar functions include append, which appends only two ndarrays along
1435 their first dimension, and glue, which can append more than two
1436 ndarrays along an arbitrary dimension.
1437
1438 Also consider the generic constructor "pdl", which can handle ndarrays
1439 of different sizes (with zero-padding), and will return a ndarray of
1440 type 'double' by default, but may be considerably faster (up to 10x)
1441 than cat.
1442
1443 dog
1444 Opposite of 'cat' :). Split N dim ndarray to list of N-1 dim ndarrays
1445
1446 Takes a single N-dimensional ndarray and splits it into a list of N-1
1447 dimensional ndarrays. The breakup is done along the last dimension.
1448 Note the dataflowed connection is still preserved by default, e.g.:
1449
1450 pdl> $p = ones 3,3,3
1451 pdl> ($x,$y,$c) = dog $p
1452 pdl> $y++; p $p
1453 [
1454 [
1455 [1 1 1]
1456 [1 1 1]
1457 [1 1 1]
1458 ]
1459 [
1460 [2 2 2]
1461 [2 2 2]
1462 [2 2 2]
1463 ]
1464 [
1465 [1 1 1]
1466 [1 1 1]
1467 [1 1 1]
1468 ]
1469 ]
1470
1471 Break => 1 Break dataflow connection (new copy)
1472
1473 The output ndarrays are set bad if the original ndarray has its bad
1474 flag set.
1475
1476 gethdr
1477 Retrieve header information from an ndarray
1478
1479 $pdl=rfits('file.fits');
1480 $h=$pdl->gethdr;
1481 print "Number of pixels in the X-direction=$$h{NAXIS1}\n";
1482
1483 The "gethdr" function retrieves whatever header information is
1484 contained within an ndarray. The header can be set with "sethdr" and is
1485 always a hash reference or undef.
1486
1487 "gethdr" returns undef if the ndarray has not yet had a header defined;
1488 compare with "hdr" and "fhdr", which are guaranteed to return a defined
1489 value.
1490
1491 Note that gethdr() works by reference: you can modify the header in-
1492 place once it has been retrieved:
1493
1494 $x = rfits($filename);
1495 $xh = $x->gethdr();
1496 $xh->{FILENAME} = $filename;
1497
1498 It is also important to realise that in most cases the header is not
1499 automatically copied when you copy the ndarray. See "hdrcpy" to enable
1500 automatic header copying.
1501
1502 Here's another example: a wrapper around rcols that allows your ndarray
1503 to remember the file it was read from and the columns could be easily
1504 written (here assuming that no regexp is needed, extensions are left as
1505 an exercise for the reader)
1506
1507 sub ext_rcols {
1508 my ($file, @columns)=@_;
1509 my $header={};
1510 $$header{File}=$file;
1511 $$header{Columns}=\@columns;
1512
1513 @ndarrays=rcols $file, @columns;
1514 foreach (@ndarrays) { $_->sethdr($header); }
1515 return @ndarrays;
1516 }
1517
1518 hdr
1519 Retrieve or set header information from an ndarray
1520
1521 $pdl->hdr->{CDELT1} = 1;
1522
1523 The "hdr" function allows convenient access to the header of a ndarray.
1524 Unlike "gethdr" it is guaranteed to return a defined value, so you can
1525 use it in a hash dereference as in the example. If the header does not
1526 yet exist, it gets autogenerated as an empty hash.
1527
1528 Note that this is usually -- but not always -- What You Want. If you
1529 want to use a tied Astro::FITS::Header hash, for example, you should
1530 either construct it yourself and use "sethdr" to put it into the
1531 ndarray, or use "fhdr" instead. (Note that you should be able to write
1532 out the FITS file successfully regardless of whether your PDL has a
1533 tied FITS header object or a vanilla hash).
1534
1535 fhdr
1536 Retrieve or set FITS header information from an ndarray
1537
1538 $pdl->fhdr->{CDELT1} = 1;
1539
1540 The "fhdr" function allows convenient access to the header of a
1541 ndarray. Unlike "gethdr" it is guaranteed to return a defined value,
1542 so you can use it in a hash dereference as in the example. If the
1543 header does not yet exist, it gets autogenerated as a tied
1544 Astro::FITS::Header hash.
1545
1546 Astro::FITS::Header tied hashes are better at matching the behavior of
1547 FITS headers than are regular hashes. In particular, the hash keys are
1548 CAsE INsEnSItiVE, unlike normal hash keys. See Astro::FITS::Header for
1549 details.
1550
1551 If you do not have Astro::FITS::Header installed, you get back a normal
1552 hash instead of a tied object.
1553
1554 sethdr
1555 Set header information of an ndarray
1556
1557 $pdl = zeroes(100,100);
1558 $h = {NAXIS=>2, NAXIS1=>100, NAXIS=>100, COMMENT=>"Sample FITS-style header"};
1559 # add a FILENAME field to the header
1560 $$h{FILENAME} = 'file.fits';
1561 $pdl->sethdr( $h );
1562
1563 The "sethdr" function sets the header information for an ndarray. You
1564 must feed in a hash ref or undef, and the header field of the PDL is
1565 set to be a new ref to the same hash (or undefined).
1566
1567 The hash ref requirement is a speed bump put in place since the normal
1568 use of headers is to store fits header information and the like. Of
1569 course, if you want you can hang whatever ugly old data structure you
1570 want off of the header, but that makes life more complex.
1571
1572 Remember that the hash is not copied -- the header is made into a ref
1573 that points to the same underlying data. To get a real copy without
1574 making any assumptions about the underlying data structure, you can use
1575 one of the following:
1576
1577 use PDL::IO::Dumper;
1578 $pdl->sethdr( deep_copy($h) );
1579
1580 (which is slow but general), or
1581
1582 $pdl->sethdr( PDL::_hdr_copy($h) )
1583
1584 (which uses the built-in sleazy deep copier), or (if you know that all
1585 the elements happen to be scalars):
1586
1587 { my %a = %$h;
1588 $pdl->sethdr(\%a);
1589 }
1590
1591 which is considerably faster but just copies the top level.
1592
1593 The "sethdr" function must be given a hash reference or undef. For
1594 further information on the header, see "gethdr", "hdr", "fhdr" and
1595 "hdrcpy".
1596
1597 hdrcpy
1598 switch on/off/examine automatic header copying
1599
1600 print "hdrs will be copied" if $x->hdrcpy;
1601 $x->hdrcpy(1); # switch on automatic header copying
1602 $y = $x->sumover; # and $y will inherit $x's hdr
1603 $x->hdrcpy(0); # and now make $x non-infectious again
1604
1605 "hdrcpy" without an argument just returns the current setting of the
1606 flag. See also "hcpy" which returns its PDL argument (and so is useful
1607 in method-call pipelines).
1608
1609 Normally, the optional header of an ndarray is not copied automatically
1610 in pdl operations. Switching on the hdrcpy flag using the "hdrcpy"
1611 method will enable automatic hdr copying. Note that an actual deep copy
1612 gets made, which is rather processor-inefficient -- so avoid using
1613 header copying in tight loops!
1614
1615 Most PDLs have the "hdrcpy" flag cleared by default; however, some
1616 routines (notably rfits) set it by default where that makes more sense.
1617
1618 The "hdrcpy" flag is viral: if you set it for a PDL, then derived PDLs
1619 will get copies of the header and will also have their "hdrcpy" flags
1620 set. For example:
1621
1622 $x = xvals(50,50);
1623 $x->hdrcpy(1);
1624 $x->hdr->{FOO} = "bar";
1625 $y = $x++;
1626 $c = $y++;
1627 print $y->hdr->{FOO}, " - ", $c->hdr->{FOO}, "\n";
1628 $y->hdr->{FOO} = "baz";
1629 print $x->hdr->{FOO}, " - ", $y->hdr->{FOO}, " - ", $c->hdr->{FOO}, "\n";
1630
1631 will print:
1632
1633 bar - bar
1634 bar - baz - bar
1635
1636 Performing an operation in which more than one PDL has its hdrcpy flag
1637 causes the resulting PDL to take the header of the first PDL:
1638
1639 ($x,$y) = sequence(5,2)->dog;
1640 $x->hdrcpy(1); $y->hdrcpy(1);
1641 $x->hdr->{foo} = 'a';
1642 $y->hdr->{foo} = 'b';
1643 print (($x+$y)->hdr->{foo} , ($y+$x)->hdr->{foo});
1644
1645 will print:
1646
1647 a b
1648
1649 hcpy
1650 Switch on/off automatic header copying, with PDL pass-through
1651
1652 $x = rfits('foo.fits')->hcpy(0);
1653 $x = rfits('foo.fits')->hcpy(1);
1654
1655 "hcpy" sets or clears the hdrcpy flag of a PDL, and returns the PDL
1656 itself. That makes it convenient for inline use in expressions.
1657
1658 online_cpus
1659 Returns the number of available processors cores. Used to set the
1660 number of threads with "set_autopthread_targ" if
1661 $ENV{PDL_AUTOPTHREAD_TARG} is not set.
1662
1663 set_autopthread_targ
1664 Set the target number of processor threads (pthreads) for multi-
1665 threaded processing.
1666
1667 set_autopthread_targ($num_pthreads);
1668
1669 $num_pthreads is the target number of pthreads the auto-pthread process
1670 will try to achieve.
1671
1672 See PDL::ParallelCPU for an overview of the auto-pthread process.
1673
1674 # Example turning on auto-pthreading for a target of 2 pthreads and for functions involving
1675 # PDLs with greater than 1M elements
1676 set_autopthread_targ(2);
1677 set_autopthread_size(1);
1678
1679 # Execute a pdl function, processing will split into two pthreads
1680 $x = minimum($y);
1681
1682 # Get the actual number of pthreads that were run.
1683 $actual_pthread = get_autopthread_actual();
1684
1685 get_autopthread_targ
1686 Get the current target number of processor threads (pthreads) for
1687 multi-threaded processing.
1688
1689 $num_pthreads = get_autopthread_targ();
1690
1691 $num_pthreads is the target number of pthreads the auto-pthread process
1692 will try to achieve.
1693
1694 See PDL::ParallelCPU for an overview of the auto-pthread process.
1695
1696 get_autopthread_actual
1697 Get the actual number of pthreads executed for the last pdl processing
1698 function.
1699
1700 $autopthread_actual = get_autopthread_actual();
1701
1702 $autopthread_actual is the actual number of pthreads executed for the
1703 last pdl processing function.
1704
1705 See PDL::ParallelCPU for an overview of the auto-pthread process.
1706
1707 get_autopthread_dim
1708 Get the actual dimension on which pthreads were used for the last pdl
1709 processing function.
1710
1711 $autopthread_dim = get_autopthread_dim();
1712
1713 $autopthread_dim is the actual dimension on which pthreads were used
1714 for the last pdl processing function.
1715
1716 See PDL::ParallelCPU for an overview of the auto-pthread process.
1717
1718 set_autopthread_size
1719 Set the minimum size (in M-elements or 2^20 elements) of the largest
1720 PDL involved in a function where auto-pthreading will be performed. For
1721 small PDLs, it probably isn't worth starting multiple pthreads, so this
1722 function is used to define a minimum threshold where auto-pthreading
1723 won't be attempted.
1724
1725 set_autopthread_size($size);
1726
1727 $size is the mimumum size, in M-elements or 2^20 elements (approx 1e6
1728 elements) for the largest PDL involved in a function.
1729
1730 See PDL::ParallelCPU for an overview of the auto-pthread process.
1731
1732 # Example turning on auto-pthreading for a target of 2 pthreads and for functions involving
1733 # PDLs with greater than 1M elements
1734 set_autopthread_targ(2);
1735 set_autopthread_size(1);
1736
1737 # Execute a pdl function, processing will split into two pthreads as long as
1738 # one of the pdl-threaded dimensions is at least 2.
1739 $x = minimum($y);
1740
1741 # Get the actual number of pthreads that were run.
1742 $actual_pthread = get_autopthread_actual();
1743
1744 get_autopthread_size
1745 Get the current autopthread_size setting.
1746
1747 $autopthread_size = get_autopthread_size();
1748
1749 $autopthread_size is the mimumum size limit for auto_pthreading to
1750 occur, in M-elements or 2^20 elements (approx 1e6 elements) for the
1751 largest PDL involved in a function
1752
1753 See PDL::ParallelCPU for an overview of the auto-pthread process.
1754
1756 Copyright (C) Karl Glazebrook (kgb@aaoepp.aao.gov.au), Tuomas J. Lukka,
1757 (lukka@husc.harvard.edu) and Christian Soeller
1758 (c.soeller@auckland.ac.nz) 1997. Modified, Craig DeForest
1759 (deforest@boulder.swri.edu) 2002. All rights reserved. There is no
1760 warranty. You are allowed to redistribute this software / documentation
1761 under certain conditions. For details, see the file COPYING in the PDL
1762 distribution. If this file is separated from the PDL distribution, the
1763 copyright notice should be included in the file.
1764
1765
1766
1767perl v5.36.0 2023-01-20 Core(3)