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 = PDL->new([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 $y = PDL->new(@list_of_vals); # new from Perl list
505 $z = PDL->new(\@list_of_vals); # new from Perl list reference
506 $w = PDL->new("[1 2 3]"); # new from Perl string, using
507 # Matlab constructor syntax
508
509 Constructs ndarray from perl numbers and lists and strings with
510 Matlab/Octave style constructor syntax.
511
512 The string input is fairly versatile though not performance optimized.
513 The goal is to make it easy to copy and paste code from PDL output and
514 to offer a familiar Matlab syntax for ndarray construction. As of May,
515 2010, it is a new feature, so feel free to report bugs or suggest new
516 features. See documentation for pdl for more examples of usage.
517
518 copy
519 Make a physical copy of an ndarray
520
521 $new = $old->copy;
522
523 Since "$new = $old" just makes a new reference, the "copy" method is
524 provided to allow real independent copies to be made.
525
526 hdr_copy
527 Return an explicit copy of the header of a PDL.
528
529 hdr_copy is just a wrapper for the internal routine _hdr_copy, which
530 takes the hash ref itself. That is the routine which is used to make
531 copies of the header during normal operations if the hdrcpy() flag of a
532 PDL is set.
533
534 General-purpose deep copies are expensive in perl, so some simple
535 optimization happens:
536
537 If the header is a tied array or a blessed hash ref with an associated
538 method called "copy", then that ->copy method is called. Otherwise,
539 all elements of the hash are explicitly copied. References are
540 recursively deep copied.
541
542 This routine seems to leak memory.
543
544 unwind
545 Return an ndarray which is the same as the argument except that all
546 broadcastids have been removed.
547
548 $y = $x->unwind;
549
550 make_physical
551 Make sure the data portion of an ndarray can be accessed from XS code.
552
553 $x->make_physical;
554 $x->call_my_xs_method;
555
556 Ensures that an ndarray gets its own allocated copy of data. This
557 obviously implies that there are certain ndarrays which do not have
558 their own data. These are so called virtual ndarrays that make use of
559 the vaffine optimisation (see PDL::Indexing). They do not have their
560 own copy of data but instead store only access information to some (or
561 all) of another ndarray's data.
562
563 Note: this function should not be used unless absolutely necessary
564 since otherwise memory requirements might be severely increased.
565 Instead of writing your own XS code with the need to call
566 "make_physical" you might want to consider using the PDL preprocessor
567 (see PDL::PP) which can be used to transparently access virtual
568 ndarrays without the need to physicalise them (though there are
569 exceptions).
570
571 dummy
572 Insert a 'dummy dimension' of given length (defaults to 1)
573
574 No relation to the 'Dungeon Dimensions' in Discworld!
575
576 Negative positions specify relative to last dimension, i.e. dummy(-1)
577 appends one dimension at end, dummy(-2) inserts a dummy dimension in
578 front of the last dim, etc.
579
580 If you specify a dimension position larger than the existing dimension
581 list of your PDL, the PDL gets automagically padded with extra dummy
582 dimensions so that you get the dim you asked for, in the slot you asked
583 for. This could cause you trouble if, for example, you ask for
584 $x->dummy(5000,1) because $x will get 5,000 dimensions, each of rank 1.
585
586 Because padding at the beginning of the dimension list moves existing
587 dimensions from slot to slot, it's considered unsafe, so automagic
588 padding doesn't work for large negative indices -- only for large
589 positive indices.
590
591 $y = $x->dummy($position[,$dimsize]);
592
593 pdl> p sequence(3)->dummy(0,3)
594 [
595 [0 0 0]
596 [1 1 1]
597 [2 2 2]
598 ]
599
600 pdl> p sequence(3)->dummy(3,2)
601 [
602 [
603 [0 1 2]
604 ]
605 [
606 [0 1 2]
607 ]
608 ]
609
610 pdl> p sequence(3)->dummy(-3,2)
611 Runtime error: PDL: For safety, <pos> < -(dims+1) forbidden in dummy. min=-2, pos=-3
612
613 dup
614 Duplicates an ndarray along a dimension
615
616 $x = sequence(3);
617 $y = $x->dup(0, 2); # doubles along first dimension
618 # $y now [0 1 2 0 1 2]
619
620 dupN
621 Duplicates an ndarray along several dimensions
622
623 $x = sequence(3,2);
624 $y = $x->dupN(2, 3); # doubles along first dimension, triples along second
625 # [
626 # [0 1 2 0 1 2]
627 # [3 4 5 3 4 5]
628 # [0 1 2 0 1 2]
629 # [3 4 5 3 4 5]
630 # ]
631
632 inflateN
633 Inflates an ndarray along several dimensions, useful for e.g. Kronecker
634 products
635
636 cf "dupN"
637
638 $x = sequence(3,2);
639 $y = $x->inflateN(2, 2); # doubles along first two dimensions
640 # [
641 # [0 0 1 1 2 2]
642 # [0 0 1 1 2 2]
643 # [3 3 4 4 5 5]
644 # [3 3 4 4 5 5]
645 # ]
646
647 clump
648 "clumps" several dimensions into one large dimension
649
650 If called with one argument $n clumps the first $n dimensions into one.
651 For example, if $x has dimensions "(5,3,4)" then after
652
653 $y = $x->clump(2); # Clump 2 first dimensions
654
655 the variable $y will have dimensions "(15,4)" and the element
656 "$y->at(7,3)" refers to the element "$x->at(1,2,3)".
657
658 Use clump(-1) to flatten an ndarray. The method flat is provided as a
659 convenient alias.
660
661 Clumping with a negative dimension in general leaves that many
662 dimensions behind -- e.g. clump(-2) clumps all of the first few
663 dimensions into a single one, leaving a 2-D ndarray.
664
665 If "clump" is called with an index list with more than one element it
666 is treated as a list of dimensions that should be clumped together into
667 one. The resulting clumped dim is placed at the position of the lowest
668 index in the list. This convention ensures that "clump" does the
669 expected thing in the usual cases. The following example demonstrates
670 typical usage:
671
672 $x = sequence 2,3,3,3,5; # 5D ndarray
673 $c = $x->clump(1..3); # clump all the dims 1 to 3 into one
674 print $c->info; # resulting 3D ndarray has clumped dim at pos 1
675 PDL: Double D [2,27,5]
676
677 broadcast_define
678 define functions that support broadcasting at the perl level
679
680 broadcast_define 'tline(a(n);b(n))', over {
681 line $_[0], $_[1]; # make line compliant with broadcasting
682 };
683
684 "broadcast_define" provides some support for broadcasting (see
685 PDL::Indexing) at the perl level. It allows you to do things for which
686 you normally would have resorted to PDL::PP (see PDL::PP); however, it
687 is most useful to wrap existing perl functions so that the new routine
688 supports PDL broadcasting.
689
690 "broadcast_define" is used to define new broadcasting aware functions.
691 Its first argument is a symbolic repesentation of the new function to
692 be defined. The string is composed of the name of the new function
693 followed by its signature (see PDL::Indexing and PDL::PP) in
694 parentheses. The second argument is a subroutine that will be called
695 with the slices of the actual runtime arguments as specified by its
696 signature. Correct dimension sizes and minimal number of dimensions for
697 all arguments will be checked (assuming the rules of PDL broadcasting,
698 see PDL::Indexing).
699
700 The actual work is done by the "signature" class which parses the
701 signature string, does runtime dimension checks and the routine
702 "broadcastover" that generates the loop over all appropriate slices of
703 pdl arguments and creates pdls as needed.
704
705 Similar to "pp_def" and its "OtherPars" option it is possible to define
706 the new function so that it accepts normal perl args as well as
707 ndarrays. You do this by using the "NOtherPars" parameter in the
708 signature. The number of "NOtherPars" specified will be passed
709 unaltered into the subroutine given as the second argument of
710 "broadcast_define". Let's illustrate this with an example:
711
712 PDL::broadcast_define 'triangles(inda();indb();indc()), NOtherPars => 2',
713 PDL::over {
714 ${$_[3]} .= $_[4].join(',',map {$_->at} @_[0..2]).",-1,\n";
715 };
716
717 This defines a function "triangles" that takes 3 ndarrays as input plus
718 2 arguments which are passed into the routine unaltered. This routine
719 is used to collect lists of indices into a perl scalar that is passed
720 by reference. Each line is preceded by a prefix passed as $_[4]. Here
721 is typical usage:
722
723 $txt = '';
724 triangles(pdl(1,2,3),pdl(1),pdl(0),\$txt," "x10);
725 print $txt;
726
727 resulting in the following output
728
729 1,1,0,-1,
730 2,1,0,-1,
731 3,1,0,-1,
732
733 which is used in PDL::Graphics::TriD::VRML to generate VRML output.
734
735 Currently, this is probably not much more than a POP (proof of
736 principle) but is hoped to be useful enough for some real life work.
737
738 Check PDL::PP for the format of the signature. Currently, the "[t]"
739 qualifier and all type qualifiers are ignored.
740
741 broadcast
742 Use explicit broadcasting over specified dimensions (see also
743 PDL::Indexing)
744
745 $y = $x->broadcast($dim,[$dim1,...])
746
747 $x = zeroes 3,4,5;
748 $y = $x->broadcast(2,0);
749
750 Same as "broadcast1", i.e. uses broadcast id 1.
751
752 broadcast1
753 Explicit broadcasting over specified dims using broadcast id 1.
754
755 $xx = $x->broadcast1(3,1)
756
757 Wibble
758
759 Convenience function interfacing to PDL::Slices::broadcastI.
760
761 broadcast2
762 Explicit broadcasting over specified dims using broadcast id 2.
763
764 $xx = $x->broadcast2(3,1)
765
766 Wibble
767
768 Convenience function interfacing to PDL::Slices::broadcastI.
769
770 broadcast3
771 Explicit broadcasting over specified dims using broadcast id 3.
772
773 $xx = $x->broadcast3(3,1)
774
775 Wibble
776
777 Convenience function interfacing to PDL::Slices::broadcastI.
778
779 sever
780 sever any links of this ndarray to parent ndarrays
781
782 In PDL it is possible for an ndarray to be just another view into
783 another ndarray's data. In that case we call this ndarray a virtual
784 ndarray and the original ndarray owning the data its parent. In other
785 languages these alternate views sometimes run by names such as alias or
786 smart reference.
787
788 Typical functions that return such ndarrays are "slice", "xchg",
789 "index", etc. Sometimes, however, you would like to separate the
790 virtual ndarray from its parent's data and just give it a life of its
791 own (so that manipulation of its data doesn't change the parent). This
792 is simply achieved by using "sever". For example,
793
794 $x = $pdl->index(pdl(0,3,7))->sever;
795 $x++; # important: $pdl is not modified!
796
797 In many (but not all) circumstances it acts therefore similar to copy.
798 However, in general performance is better with "sever" and secondly,
799 "sever" doesn't lead to futile copying when used on ndarrays that
800 already have their own data. On the other hand, if you really want to
801 make sure to work on a copy of an ndarray use copy.
802
803 $x = zeroes(20);
804 $x->sever; # NOOP since $x is already its own boss!
805
806 Again note: "sever" is not the same as copy! For example,
807
808 $x = zeroes(1); # $x does not have a parent, i.e. it is not a slice etc
809 $y = $x->sever; # $y is now pointing to the same ndarray as $x
810 $y++;
811 print $x;
812 [1]
813
814 but
815
816 $x = zeroes(1);
817 $y = $x->copy; # $y is now pointing to a new ndarray
818 $y++;
819 print $x;
820 [0]
821
822 info
823 Return formatted information about an ndarray.
824
825 $x->info($format_string);
826
827 print $x->info("Type: %T Dim: %-15D State: %S");
828
829 Returns a string with info about an ndarray. Takes an optional argument
830 to specify the format of information a la sprintf. Format specifiers
831 are in the form "%<width><letter>" where the width is optional and the
832 letter is one of
833
834 T Type
835
836 D Formatted Dimensions
837
838 F Dataflow status
839
840 S Some internal flags (P=physical,V=Vaffine,C=changed,B=may
841 contain bad data)
842
843 C Class of this ndarray, i.e. "ref $pdl"
844
845 A Address of the ndarray struct as a unique identifier
846
847 M Calculated memory consumption of this ndarray's data area
848
849 approx
850 test for approximately equal values (relaxed "==")
851
852 # ok if all corresponding values in
853 # ndarrays are within 1e-8 of each other
854 print "ok\n" if all approx $x, $y, 1e-8;
855
856 "approx" is a relaxed form of the "==" operator and often more
857 appropriate for floating point types ("float" and "double").
858
859 Usage:
860
861 $res = approx $x, $y [, $eps]
862
863 The optional parameter $eps is remembered across invocations and
864 initially set to 1e-6, e.g.
865
866 approx $x, $y; # last $eps used (1e-6 initially)
867 approx $x, $y, 1e-10; # 1e-10
868 approx $x, $y; # also 1e-10
869
870 mslice
871 Alias to "slice" in PDL::Slices.
872
873 nslice_if_pdl
874 If $self is a PDL, then calls "slice" with all but the last argument,
875 otherwise $self->($_[-1]) is called where $_[-1} is the original
876 argument string found during PDL::NiceSlice filtering.
877
878 DEVELOPER'S NOTE: this routine is found in Core.pm.PL but would be
879 better placed in Slices/slices.pd. It is likely to be moved there
880 and/or changed to "slice_if_pdl" for PDL 3.0.
881
882 $w = $x->nslice_if_pdl(...,'(args)');
883
884 inplace
885 Flag an ndarray so that the next operation is done 'in place'
886
887 somefunc($x->inplace); somefunc(inplace $x);
888
889 In most cases one likes to use the syntax "$y = f($x)", however in many
890 case the operation f() can be done correctly 'in place', i.e. without
891 making a new copy of the data for output. To make it easy to use this,
892 we write f() in such a way that it operates in-place, and use "inplace"
893 to hint that a new copy should be disabled. This also makes for clear
894 syntax.
895
896 Obviously this will not work for all functions, and if in doubt see the
897 function's documentation. However one can assume this is true for all
898 elemental functions (i.e. those which just operate array element by
899 array element like "log10").
900
901 pdl> $x = xvals zeroes 10;
902 pdl> log10(inplace $x)
903 pdl> p $x
904 [-inf 0 0.30103 0.47712125 0.60205999 0.69897 0.77815125 0.84509804 0.90308999 0.95424251]
905
906 is_inplace
907 Test the in-place flag on an ndarray
908
909 $out = ($in->is_inplace) ? $in : zeroes($in);
910 $in->set_inplace(0)
911
912 Provides access to the "inplace" hint flag, within the perl milieu.
913 That way functions you write can be inplace aware... If given an
914 argument the inplace flag will be set or unset depending on the value
915 at the same time. Can be used for shortcut tests that delete the
916 inplace flag while testing:
917
918 $out = ($in->is_inplace(0)) ? $in : zeroes($in); # test & unset!
919
920 set_inplace
921 Set the in-place flag on an ndarray
922
923 $out = ($in->is_inplace) ? $in : zeroes($in);
924 $in->set_inplace(0);
925
926 Provides access to the "inplace" hint flag, within the perl milieu.
927 Useful mainly for turning it OFF, as "inplace" turns it ON more
928 conveniently.
929
930 new_or_inplace
931 $w = new_or_inplace(shift());
932 $w = new_or_inplace(shift(),$preferred_type);
933
934 Return back either the argument pdl or a copy of it depending on
935 whether it be flagged in-place or no. Handy for building inplace-aware
936 functions.
937
938 If you specify a preferred type (must be one of the usual PDL type
939 strings, a list ref containing several of them, or a comma-separated
940 string containing several of them), then the copy is coerced into the
941 first preferred type listed if it is not already one of the preferred
942 types.
943
944 Note that if the inplace flag is set, no coercion happens even if you
945 specify a preferred type.
946
947 new_from_specification
948 Internal method: create ndarray by specification
949
950 This is the argument processing method called by "zeroes" and some
951 other functions which constructs ndarrays from argument lists of the
952 form:
953
954 [type], $nx, $ny, $nz,...
955
956 For $nx, $ny, etc. 0 and 1D ndarrays are allowed. Giving those has the
957 same effect as if saying "$arg->list", e.g.
958
959 1, pdl(5,2), 4
960
961 is equivalent to
962
963 1, 5, 2, 4
964
965 Note, however, that in all functions using "new_from_specification"
966 calling "func $ndarray" will probably not do what you want. So to play
967 safe use (e.g. with zeroes)
968
969 $pdl = zeroes $dimpdl->list;
970
971 Calling
972
973 $pdl = zeroes $dimpdl;
974
975 will rather be equivalent to
976
977 $pdl = zeroes $dimpdl->dims;
978
979 However,
980
981 $pdl = zeroes ushort, $dimpdl;
982
983 will again do what you intended since it is interpreted as if you had
984 said
985
986 $pdl = zeroes ushort, $dimpdl->list;
987
988 This is unfortunate and confusing but no good solution seems obvious
989 that would not break existing scripts.
990
991 isnull
992 Test whether an ndarray is null
993
994 croak("Input ndarray mustn't be null!")
995 if $input_ndarray->isnull;
996
997 This function returns 1 if the ndarray is null, zero if it is not. The
998 purpose of null ndarrays is to "tell" any PDL::PP methods to allocate
999 new memory for an output ndarray, but only when that PDL::PP method is
1000 called in full-arg form. Of course, there's no reason you couldn't
1001 commandeer the special value for your own purposes, for which this test
1002 function would prove most helpful. But in general, you shouldn't need
1003 to test for an ndarray's nullness.
1004
1005 See "Null PDLs" for more information.
1006
1007 isempty
1008 Test whether an ndarray is empty
1009
1010 print "The ndarray has zero dimension\n" if $pdl->isempty;
1011
1012 This function returns 1 if the ndarray has zero elements. This is
1013 useful in particular when using the indexing function which. In the
1014 case of no match to a specified criterion, the returned ndarray has
1015 zero dimension.
1016
1017 pdl> $w=sequence(10)
1018 pdl> $i=which($w < -1)
1019 pdl> print "I found no matches!\n" if ($i->isempty);
1020 I found no matches!
1021
1022 Note that having zero elements is rather different from the concept of
1023 being a null ndarray, see the PDL::FAQ and PDL::Indexing manpages for
1024 discussions of this.
1025
1026 zeroes
1027 construct a zero filled ndarray from dimension list or template
1028 ndarray. If called with no arguments, returns a zero-dimension ndarray
1029 (a scalar).
1030
1031 Various forms of usage,
1032
1033 (i) by specification or (ii) by template ndarray:
1034
1035 # usage type (i):
1036 $w = zeroes([type], $nx, $ny, $nz,...);
1037 $w = PDL->zeroes([type], $nx, $ny, $nz,...);
1038 $w = $pdl->zeroes([type], $nx, $ny, $nz,...); # all info about $pdl ignored
1039 # usage type (ii):
1040 $w = zeroes $y;
1041 $w = $y->zeroes
1042 zeroes inplace $w; # Equivalent to $w .= 0;
1043 $w->inplace->zeroes; # ""
1044
1045 pdl> $z = zeroes 4,3
1046 pdl> p $z
1047 [
1048 [0 0 0 0]
1049 [0 0 0 0]
1050 [0 0 0 0]
1051 ]
1052 pdl> $z = zeroes ushort, 3,2 # Create ushort array
1053 [ushort() etc. with no arg returns a PDL::Types token]
1054
1055 See also "new_from_specification" for details on using ndarrays in the
1056 dimensions list.
1057
1058 zeros
1059 construct a zero filled ndarray (see zeroes for usage)
1060
1061 ones
1062 construct a one filled ndarray. If called with no arguments, returns a
1063 zero-dimension ndarray (a scalar).
1064
1065 $w = ones([type], $nx, $ny, $nz,...);
1066 etc. (see 'zeroes')
1067
1068 see zeroes() and add one
1069
1070 See also "new_from_specification" for details on using ndarrays in the
1071 dimensions list.
1072
1073 nan
1074 construct a "NaN" filled ndarray. If called with no arguments, returns
1075 a zero-dimension ndarray (a scalar).
1076
1077 $w = nan([type], $nx, $ny, $nz,...);
1078 etc. (see 'zeroes')
1079
1080 see zeroes() and add NaN
1081
1082 See also "new_from_specification" for details on using ndarrays in the
1083 dimensions list.
1084
1085 inf
1086 construct an "Inf" filled ndarray. If called with no arguments,
1087 returns a zero-dimension ndarray (a scalar).
1088
1089 $w = inf([type], $nx, $ny, $nz,...);
1090 etc. (see 'zeroes')
1091
1092 see zeroes() and add Inf
1093
1094 See also "new_from_specification" for details on using ndarrays in the
1095 dimensions list.
1096
1097 i
1098 construct an ndarray filled with a native complex value equal to the
1099 imaginary number "i", the square root of -1. If called with no
1100 arguments, returns a zero-dimension ndarray (a scalar).
1101
1102 $w = i([type], $nx, $ny, $nz,...);
1103 etc. (see 'zeroes')
1104
1105 see zeroes() and add "i"
1106
1107 See also "new_from_specification" for details on using ndarrays in the
1108 dimensions list.
1109
1110 reshape
1111 Change the shape (i.e. dimensions) of an ndarray, preserving contents.
1112
1113 $x->reshape(NEWDIMS); reshape($x, NEWDIMS);
1114
1115 The data elements are preserved, obviously they will wrap differently
1116 and get truncated if the new array is shorter. If the new array is
1117 longer it will be zero-padded.
1118
1119 ***Potential incompatibility with earlier versions of PDL**** If the
1120 list of "NEWDIMS" is empty "reshape" will just drop all dimensions of
1121 size 1 (preserving the number of elements):
1122
1123 $w = sequence(3,4,5);
1124 $y = $w(1,3);
1125 $y->reshape();
1126 print $y->info;
1127 PDL: Double D [5]
1128
1129 Dimensions of size 1 will also be dropped if "reshape" is invoked with
1130 the argument -1:
1131
1132 $y = $w->reshape(-1);
1133
1134 As opposed to "reshape" without arguments, reshape(-1) preserves
1135 dataflow:
1136
1137 $w = ones(2,1,2);
1138 $y = $w(0)->reshape(-1);
1139 $y++;
1140 print $w;
1141 [
1142 [
1143 [2 1]
1144 ]
1145 [
1146 [2 1]
1147 ]
1148 ]
1149
1150 Important: ndarrays are changed inplace!
1151
1152 Note: If $x is connected to any other PDL (e.g. if it is a slice) then
1153 the connection is first severed.
1154
1155 pdl> $x = sequence(10)
1156 pdl> reshape $x,3,4; p $x
1157 [
1158 [0 1 2]
1159 [3 4 5]
1160 [6 7 8]
1161 [9 0 0]
1162 ]
1163 pdl> reshape $x,5; p $x
1164 [0 1 2 3 4]
1165
1166 squeeze
1167 eliminate all singleton dimensions (dims of size 1)
1168
1169 $y = $w(0,0)->squeeze;
1170
1171 Alias for reshape(-1). Removes all singleton dimensions and preserves
1172 dataflow. A more concise interface is provided by PDL::NiceSlice via
1173 modifiers:
1174
1175 use PDL::NiceSlice;
1176 $y = $w(0,0;-); # same as $w(0,0)->squeeze
1177
1178 flat
1179 flatten an ndarray (alias for "$pdl->clump(-1)")
1180
1181 $srt = $pdl->flat->qsort;
1182
1183 Useful method to make a 1D ndarray from an arbitrarily sized input
1184 ndarray. Data flows back and forth as usual with slicing routines.
1185 Falls through if argument already <= 1D.
1186
1187 convert
1188 Generic datatype conversion function
1189
1190 $y = convert($x, $newtype);
1191
1192 $newtype is a type number or PDL::Type object, for convenience they are
1193 returned by long() etc when called without arguments.
1194
1195 $y = convert $x, long;
1196 $y = convert $x, ushort;
1197
1198 Datatype_conversions
1199 sbyte|byte|short|ushort|long|ulong|indx|longlong|ulonglong|float|double|ldouble|cfloat|cdouble|cldouble
1200 (shorthands to convert datatypes)
1201
1202 $y = double $x; $y = ushort [1..10];
1203 # all of the above listed shorthands behave similarly
1204
1205 When called with an ndarray argument, they convert to the specific
1206 datatype.
1207
1208 When called with a numeric, list, listref, or string argument they
1209 construct a new ndarray. This is a convenience to avoid having to be
1210 long-winded and say "$x = long(pdl(42))"
1211
1212 Thus one can say:
1213
1214 $w = float(1,2,3,4); # 1D
1215 $w = float q[1 2 3; 4 5 6]; # 2D
1216 $w = float([1,2,3],[4,5,6]); # 2D
1217 $w = float([[1,2,3],[4,5,6]]); # 2D
1218
1219 Note the last three give identical results, and the last two are
1220 exactly equivalent - a list is automatically converted to a list
1221 reference for syntactic convenience. i.e. you can omit the outer "[]"
1222
1223 When called with no arguments, these functions return a special type
1224 token. This allows syntactical sugar like:
1225
1226 $x = ones byte, 1000,1000;
1227
1228 This example creates a large ndarray directly as byte datatype in order
1229 to save memory.
1230
1231 In order to control how undefs are handled in converting from perl
1232 lists to PDLs, one can set the variable $PDL::undefval; see the
1233 function pdl() for more details.
1234
1235 pdl> p $x=sqrt float [1..10]
1236 [1 1.41421 1.73205 2 2.23607 2.44949 2.64575 2.82843 3 3.16228]
1237 pdl> p byte $x
1238 [1 1 1 2 2 2 2 2 3 3]
1239
1240 byte
1241 Convert to byte datatype
1242
1243 short
1244 Convert to short datatype
1245
1246 ushort
1247 Convert to ushort datatype
1248
1249 long
1250 Convert to long datatype
1251
1252 indx
1253 Convert to indx datatype
1254
1255 longlong
1256 Convert to longlong datatype
1257
1258 float
1259 Convert to float datatype
1260
1261 double
1262 Convert to double datatype
1263
1264 cfloat
1265 Convert to complex float datatype
1266
1267 cdouble
1268 Convert to complex double datatype
1269
1270 type
1271 return the type of an ndarray as a blessed type object
1272
1273 A convenience function for use with the ndarray constructors, e.g.
1274
1275 $y = PDL->zeroes($x->type,$x->dims,3);
1276 die "must be float" unless $x->type == float;
1277
1278 See also the discussion of the "PDL::Type" class in PDL::Types. Note
1279 that the "PDL::Type" objects have overloaded comparison and stringify
1280 operators so that you can compare and print types:
1281
1282 $x = $x->float if $x->type < float;
1283 $t = $x->type; print "Type is $t\n";
1284
1285 list
1286 Convert ndarray to perl list
1287
1288 @tmp = list $x;
1289
1290 Obviously this is grossly inefficient for the large datasets PDL is
1291 designed to handle. This was provided as a get out while PDL matured.
1292 It should now be mostly superseded by superior constructs, such as
1293 PP/broadcasting. However it is still occasionally useful and is
1294 provided for backwards compatibility.
1295
1296 for (list $x) {
1297 # Do something on each value...
1298 }
1299
1300 list converts any bad values into the string 'BAD'.
1301
1302 unpdl
1303 Convert ndarray to nested Perl array references
1304
1305 $arrayref = unpdl $x;
1306
1307 This function returns a reference to a Perl list-of-lists structure
1308 equivalent to the input ndarray (within the limitation that while
1309 values of elements should be preserved, the detailed datatypes will not
1310 as perl itself basically has "number" data rather than byte, short,
1311 int... E.g., "sum($x - pdl( $x->unpdl ))" should equal 0.
1312
1313 Obviously this is grossly inefficient in memory and processing for the
1314 large datasets PDL is designed to handle. Sometimes, however, you
1315 really want to move your data back to Perl, and with proper
1316 dimensionality, unlike "list".
1317
1318 If you want to round-trip data including the use of "PDL::undefval",
1319 "unpdl" does not support this. However, it is suggested you would
1320 generate an index-set with "$pdl->whereND($pdl == $PDL::undefval)",
1321 then loop over the Perl data, setting those locations to "undef".
1322
1323 use JSON;
1324 my $json = encode_json unpdl $pdl;
1325
1326 unpdl converts any bad values into the string 'BAD'.
1327
1328 listindices
1329 Convert ndarray indices to perl list
1330
1331 @tmp = listindices $x;
1332
1333 @tmp now contains the values "0..nelem($x)".
1334
1335 Obviously this is grossly inefficient for the large datasets PDL is
1336 designed to handle. This was provided as a get out while PDL matured.
1337 It should now be mostly superseded by superior constructs, such as
1338 PP/broadcasting. However it is still occasionally useful and is provied
1339 for backwards compatibility.
1340
1341 for $i (listindices $x) {
1342 # Do something on each value...
1343 }
1344
1345 set
1346 Set a single value inside an ndarray
1347
1348 set $ndarray, @position, $value
1349
1350 @position is a coordinate list, of size equal to the number of
1351 dimensions in the ndarray. Occasionally useful, mainly provided for
1352 backwards compatibility as superseded by use of slice and assignment
1353 operator ".=".
1354
1355 pdl> $x = sequence 3,4
1356 pdl> set $x, 2,1,99
1357 pdl> p $x
1358 [
1359 [ 0 1 2]
1360 [ 3 4 99]
1361 [ 6 7 8]
1362 [ 9 10 11]
1363 ]
1364
1365 at
1366 Returns a single value inside an ndarray as perl scalar. If the
1367 ndarray is a native complex value (cdouble, cfloat), it will be a
1368 PDL::Complex::Overloads object.
1369
1370 $z = at($ndarray, @position); $z=$ndarray->at(@position);
1371
1372 @position is a coordinate list, of size equal to the number of
1373 dimensions in the ndarray. Occasionally useful in a general context,
1374 quite useful too inside PDL internals.
1375
1376 pdl> $x = sequence 3,4
1377 pdl> p $x->at(1,2)
1378 7
1379
1380 at converts any bad values into the string 'BAD'.
1381
1382 sclr
1383 return a single value from an ndarray as a scalar, ignoring whether it
1384 is bad.
1385
1386 $val = $x(10)->sclr;
1387 $val = sclr inner($x,$y);
1388
1389 The "sclr" method is useful to turn a single-element ndarray into a
1390 normal Perl scalar. Its main advantage over using "at" for this purpose
1391 is the fact that you do not need to worry if the ndarray is 0D, 1D or
1392 higher dimensional. Using "at" you have to supply the correct number
1393 of zeroes, e.g.
1394
1395 $x = sequence(10);
1396 $y = $x->slice('4');
1397 print $y->sclr; # no problem
1398 print $y->at(); # error: needs at least one zero
1399
1400 "sclr" is generally used when a Perl scalar is required instead of a
1401 one-element ndarray. As of 2.064, if the input is a multielement
1402 ndarray it will throw an exception.
1403
1404 cat
1405 concatenate ndarrays to N+1 dimensional ndarray
1406
1407 Takes a list of N ndarrays of same shape as argument, returns a single
1408 ndarray of dimension N+1.
1409
1410 pdl> $x = cat ones(3,3),zeroes(3,3),rvals(3,3); p $x
1411 [
1412 [
1413 [1 1 1]
1414 [1 1 1]
1415 [1 1 1]
1416 ]
1417 [
1418 [0 0 0]
1419 [0 0 0]
1420 [0 0 0]
1421 ]
1422 [
1423 [1 1 1]
1424 [1 0 1]
1425 [1 1 1]
1426 ]
1427 ]
1428
1429 The output ndarray is set bad if any input ndarrays have their bad flag
1430 set.
1431
1432 Similar functions include append, which appends only two ndarrays along
1433 their first dimension, and glue, which can append more than two
1434 ndarrays along an arbitrary dimension.
1435
1436 Also consider the generic constructor "pdl", which can handle ndarrays
1437 of different sizes (with zero-padding), and will return a ndarray of
1438 type 'double' by default, but may be considerably faster (up to 10x)
1439 than cat.
1440
1441 dog
1442 Opposite of 'cat' :). Split N dim ndarray to list of N-1 dim ndarrays
1443
1444 Takes a single N-dimensional ndarray and splits it into a list of N-1
1445 dimensional ndarrays. The breakup is done along the last dimension.
1446 Note the dataflowed connection is still preserved by default, e.g.:
1447
1448 pdl> $p = ones 3,3,3
1449 pdl> ($x,$y,$c) = dog $p
1450 pdl> $y++; p $p
1451 [
1452 [
1453 [1 1 1]
1454 [1 1 1]
1455 [1 1 1]
1456 ]
1457 [
1458 [2 2 2]
1459 [2 2 2]
1460 [2 2 2]
1461 ]
1462 [
1463 [1 1 1]
1464 [1 1 1]
1465 [1 1 1]
1466 ]
1467 ]
1468
1469 Break => 1 Break dataflow connection (new copy)
1470
1471 The output ndarrays are set bad if the original ndarray has its bad
1472 flag set.
1473
1474 gethdr
1475 Retrieve header information from an ndarray
1476
1477 $pdl=rfits('file.fits');
1478 $h=$pdl->gethdr;
1479 print "Number of pixels in the X-direction=$$h{NAXIS1}\n";
1480
1481 The "gethdr" function retrieves whatever header information is
1482 contained within an ndarray. The header can be set with "sethdr" and is
1483 always a hash reference or undef.
1484
1485 "gethdr" returns undef if the ndarray has not yet had a header defined;
1486 compare with "hdr" and "fhdr", which are guaranteed to return a defined
1487 value.
1488
1489 Note that gethdr() works by reference: you can modify the header in-
1490 place once it has been retrieved:
1491
1492 $x = rfits($filename);
1493 $xh = $x->gethdr();
1494 $xh->{FILENAME} = $filename;
1495
1496 It is also important to realise that in most cases the header is not
1497 automatically copied when you copy the ndarray. See "hdrcpy" to enable
1498 automatic header copying.
1499
1500 Here's another example: a wrapper around rcols that allows your ndarray
1501 to remember the file it was read from and the columns could be easily
1502 written (here assuming that no regexp is needed, extensions are left as
1503 an exercise for the reader)
1504
1505 sub ext_rcols {
1506 my ($file, @columns)=@_;
1507 my $header={};
1508 $$header{File}=$file;
1509 $$header{Columns}=\@columns;
1510
1511 @ndarrays=rcols $file, @columns;
1512 foreach (@ndarrays) { $_->sethdr($header); }
1513 return @ndarrays;
1514 }
1515
1516 hdr
1517 Retrieve or set header information from an ndarray
1518
1519 $pdl->hdr->{CDELT1} = 1;
1520
1521 The "hdr" function allows convenient access to the header of a ndarray.
1522 Unlike "gethdr" it is guaranteed to return a defined value, so you can
1523 use it in a hash dereference as in the example. If the header does not
1524 yet exist, it gets autogenerated as an empty hash.
1525
1526 Note that this is usually -- but not always -- What You Want. If you
1527 want to use a tied Astro::FITS::Header hash, for example, you should
1528 either construct it yourself and use "sethdr" to put it into the
1529 ndarray, or use "fhdr" instead. (Note that you should be able to write
1530 out the FITS file successfully regardless of whether your PDL has a
1531 tied FITS header object or a vanilla hash).
1532
1533 fhdr
1534 Retrieve or set FITS header information from an ndarray
1535
1536 $pdl->fhdr->{CDELT1} = 1;
1537
1538 The "fhdr" function allows convenient access to the header of a
1539 ndarray. Unlike "gethdr" it is guaranteed to return a defined value,
1540 so you can use it in a hash dereference as in the example. If the
1541 header does not yet exist, it gets autogenerated as a tied
1542 Astro::FITS::Header hash.
1543
1544 Astro::FITS::Header tied hashes are better at matching the behavior of
1545 FITS headers than are regular hashes. In particular, the hash keys are
1546 CAsE INsEnSItiVE, unlike normal hash keys. See Astro::FITS::Header for
1547 details.
1548
1549 If you do not have Astro::FITS::Header installed, you get back a normal
1550 hash instead of a tied object.
1551
1552 sethdr
1553 Set header information of an ndarray
1554
1555 $pdl = zeroes(100,100);
1556 $h = {NAXIS=>2, NAXIS1=>100, NAXIS=>100, COMMENT=>"Sample FITS-style header"};
1557 # add a FILENAME field to the header
1558 $$h{FILENAME} = 'file.fits';
1559 $pdl->sethdr( $h );
1560
1561 The "sethdr" function sets the header information for an ndarray. You
1562 must feed in a hash ref or undef, and the header field of the PDL is
1563 set to be a new ref to the same hash (or undefined).
1564
1565 The hash ref requirement is a speed bump put in place since the normal
1566 use of headers is to store fits header information and the like. Of
1567 course, if you want you can hang whatever ugly old data structure you
1568 want off of the header, but that makes life more complex.
1569
1570 Remember that the hash is not copied -- the header is made into a ref
1571 that points to the same underlying data. To get a real copy without
1572 making any assumptions about the underlying data structure, you can use
1573 one of the following:
1574
1575 use PDL::IO::Dumper;
1576 $pdl->sethdr( deep_copy($h) );
1577
1578 (which is slow but general), or
1579
1580 $pdl->sethdr( PDL::_hdr_copy($h) )
1581
1582 (which uses the built-in sleazy deep copier), or (if you know that all
1583 the elements happen to be scalars):
1584
1585 { my %a = %$h;
1586 $pdl->sethdr(\%a);
1587 }
1588
1589 which is considerably faster but just copies the top level.
1590
1591 The "sethdr" function must be given a hash reference or undef. For
1592 further information on the header, see "gethdr", "hdr", "fhdr" and
1593 "hdrcpy".
1594
1595 hdrcpy
1596 switch on/off/examine automatic header copying
1597
1598 print "hdrs will be copied" if $x->hdrcpy;
1599 $x->hdrcpy(1); # switch on automatic header copying
1600 $y = $x->sumover; # and $y will inherit $x's hdr
1601 $x->hdrcpy(0); # and now make $x non-infectious again
1602
1603 "hdrcpy" without an argument just returns the current setting of the
1604 flag. See also "hcpy" which returns its PDL argument (and so is useful
1605 in method-call pipelines).
1606
1607 Normally, the optional header of an ndarray is not copied automatically
1608 in pdl operations. Switching on the hdrcpy flag using the "hdrcpy"
1609 method will enable automatic hdr copying. Note that an actual deep copy
1610 gets made, which is rather processor-inefficient -- so avoid using
1611 header copying in tight loops!
1612
1613 Most PDLs have the "hdrcpy" flag cleared by default; however, some
1614 routines (notably rfits) set it by default where that makes more sense.
1615
1616 The "hdrcpy" flag is viral: if you set it for a PDL, then derived PDLs
1617 will get copies of the header and will also have their "hdrcpy" flags
1618 set. For example:
1619
1620 $x = xvals(50,50);
1621 $x->hdrcpy(1);
1622 $x->hdr->{FOO} = "bar";
1623 $y = $x++;
1624 $c = $y++;
1625 print $y->hdr->{FOO}, " - ", $c->hdr->{FOO}, "\n";
1626 $y->hdr->{FOO} = "baz";
1627 print $x->hdr->{FOO}, " - ", $y->hdr->{FOO}, " - ", $c->hdr->{FOO}, "\n";
1628
1629 will print:
1630
1631 bar - bar
1632 bar - baz - bar
1633
1634 Performing an operation in which more than one PDL has its hdrcpy flag
1635 causes the resulting PDL to take the header of the first PDL:
1636
1637 ($x,$y) = sequence(5,2)->dog;
1638 $x->hdrcpy(1); $y->hdrcpy(1);
1639 $x->hdr->{foo} = 'a';
1640 $y->hdr->{foo} = 'b';
1641 print (($x+$y)->hdr->{foo} , ($y+$x)->hdr->{foo});
1642
1643 will print:
1644
1645 a b
1646
1647 hcpy
1648 Switch on/off automatic header copying, with PDL pass-through
1649
1650 $x = rfits('foo.fits')->hcpy(0);
1651 $x = rfits('foo.fits')->hcpy(1);
1652
1653 "hcpy" sets or clears the hdrcpy flag of a PDL, and returns the PDL
1654 itself. That makes it convenient for inline use in expressions.
1655
1656 online_cpus
1657 Returns the number of available processors cores. Used to set the
1658 number of threads with "set_autopthread_targ" if
1659 $ENV{PDL_AUTOPTHREAD_TARG} is not set.
1660
1661 set_autopthread_targ
1662 Set the target number of processor threads (pthreads) for multi-
1663 threaded processing.
1664
1665 set_autopthread_targ($num_pthreads);
1666
1667 $num_pthreads is the target number of pthreads the auto-pthread process
1668 will try to achieve.
1669
1670 See PDL::ParallelCPU for an overview of the auto-pthread process.
1671
1672 # Example turning on auto-pthreading for a target of 2 pthreads and for functions involving
1673 # PDLs with greater than 1M elements
1674 set_autopthread_targ(2);
1675 set_autopthread_size(1);
1676
1677 # Execute a pdl function, processing will split into two pthreads
1678 $x = minimum($y);
1679
1680 # Get the actual number of pthreads that were run.
1681 $actual_pthread = get_autopthread_actual();
1682
1683 get_autopthread_targ
1684 Get the current target number of processor threads (pthreads) for
1685 multi-threaded processing.
1686
1687 $num_pthreads = get_autopthread_targ();
1688
1689 $num_pthreads is the target number of pthreads the auto-pthread process
1690 will try to achieve.
1691
1692 See PDL::ParallelCPU for an overview of the auto-pthread process.
1693
1694 get_autopthread_actual
1695 Get the actual number of pthreads executed for the last pdl processing
1696 function.
1697
1698 $autopthread_actual = get_autopthread_actual();
1699
1700 $autopthread_actual is the actual number of pthreads executed for the
1701 last pdl processing function.
1702
1703 See PDL::ParallelCPU for an overview of the auto-pthread process.
1704
1705 get_autopthread_dim
1706 Get the actual dimension on which pthreads were used for the last pdl
1707 processing function.
1708
1709 $autopthread_dim = get_autopthread_dim();
1710
1711 $autopthread_dim is the actual dimension on which pthreads were used
1712 for the last pdl processing function.
1713
1714 See PDL::ParallelCPU for an overview of the auto-pthread process.
1715
1716 set_autopthread_size
1717 Set the minimum size (in M-elements or 2^20 elements) of the largest
1718 PDL involved in a function where auto-pthreading will be performed. For
1719 small PDLs, it probably isn't worth starting multiple pthreads, so this
1720 function is used to define a minimum threshold where auto-pthreading
1721 won't be attempted.
1722
1723 set_autopthread_size($size);
1724
1725 $size is the mimumum size, in M-elements or 2^20 elements (approx 1e6
1726 elements) for the largest PDL involved in a function.
1727
1728 See PDL::ParallelCPU for an overview of the auto-pthread process.
1729
1730 # Example turning on auto-pthreading for a target of 2 pthreads and for functions involving
1731 # PDLs with greater than 1M elements
1732 set_autopthread_targ(2);
1733 set_autopthread_size(1);
1734
1735 # Execute a pdl function, processing will split into two pthreads as long as
1736 # one of the pdl-threaded dimensions is at least 2.
1737 $x = minimum($y);
1738
1739 # Get the actual number of pthreads that were run.
1740 $actual_pthread = get_autopthread_actual();
1741
1742 get_autopthread_size
1743 Get the current autopthread_size setting.
1744
1745 $autopthread_size = get_autopthread_size();
1746
1747 $autopthread_size is the mimumum size limit for auto_pthreading to
1748 occur, in M-elements or 2^20 elements (approx 1e6 elements) for the
1749 largest PDL involved in a function
1750
1751 See PDL::ParallelCPU for an overview of the auto-pthread process.
1752
1754 Copyright (C) Karl Glazebrook (kgb@aaoepp.aao.gov.au), Tuomas J. Lukka,
1755 (lukka@husc.harvard.edu) and Christian Soeller
1756 (c.soeller@auckland.ac.nz) 1997. Modified, Craig DeForest
1757 (deforest@boulder.swri.edu) 2002. All rights reserved. There is no
1758 warranty. You are allowed to redistribute this software / documentation
1759 under certain conditions. For details, see the file COPYING in the PDL
1760 distribution. If this file is separated from the PDL distribution, the
1761 copyright notice should be included in the file.
1762
1763
1764
1765perl v5.38.0 2023-07-21 Core(3)