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