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