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