PDL::Core(3pm)
π PDL::Core β the whole vibe, part 1 π
okay bestie, welcome to PDL::Core(3pm) β that's the section-3pm manual page from the User Contributed Perl Documentation, and it's the beating heart of PDL. Sit down, grab a strawberry π, and let's get into it.
β¨ NAME β¨
PDL::Core β the fundamental PDL functionality plus vectorization/broadcasting. that's the whole thing, she's the main character π
πΈ DESCRIPTION πΈ
Methods and functions for type conversions, PDL creation, type conversion, broadcasting etc.
(yes, "type conversion" really does show up twice in there. we said what we said. π )
π¦ SYNOPSIS π¦
use PDL::Core; # Normal routines
use PDL::Core ':Internal'; # Hairy routines
so like, normal girlies do the first one, and the hairy-routine girlies do the second. both are valid.
π VECTORIZATION/BROADCASTING: METHOD AND NOMENCLATURE π
PDL gives you vectorized operations through a built-in engine. the name of the game is "broadcasting" β though fr fr, up until version 2.074 it was called "threading", so if you see old posts calling it that, you're not confused, the lore just changed. the broadcasting engine has simple rules for each operation.
Every PDL object has a "shape" β a generalized N-dimensional rectangle defined by a "dim list" of sizes in an arbitrary set of dimensions. a PDL with shape 2x3 has 6 elements, is two-dimensional, and might get called a "2x3-PDL". dimensions are indexed numerically starting at 0, so a 2x3-PDL has a dimension 0 (or "dim 0") with size 2, and a 1 dimension (or "dim 1") with size 3.
PDL generalizes all mathematical operations with the notion of "active dims": each operator has zero or more active dims that are used in carrying out the operation. simple scalar operations like scalar multiplication ('*') have 0 active dims. more complicated operators can have more active dims. for example, matrix multiplication ('x') has 2 active dims. additional dims are automatically vectorized across β e.g. multiplying a 2x5-PDL with a 2x5-PDL requires 10 simple multiplication operations, and yields a 2x5-PDL result. slay π«Ά
β¨ Broadcasting rules β¨
In any PDL expression, the active dims appropriate for each operator are used starting at the 0 dim and working forward through the dim list of each object. all additional dims after the active dims are "broadcast dims". broadcast dims do not have to agree exactly β they get coerced to agree according to these simple rules:
- Null PDLs match any dim list (see below). π
- Dims with sizes other than
1must all agree in size. - Dims of size
1are silently repeated as necessary β except for"[phys]"PDLs. - Missing dims are expanded appropriately.
A size-1 dim for "[phys]" PDLs causes an exception if the dim is used in another parameter and has a size greater than 1. β οΈ
The "size 1" rule implements "generalized scalar" operation, by analogy to scalar multiplication. the "missing dims" rule acknowledges the ambiguity between a missing dim and a dim of size 1.
π Null PDLs π
PDLs on the left-hand side of assignment can have the special value "Null". a null PDL has no dim list and no set size; its shape is determined by the computed shape of the expression being assigned to it. null PDLs contain no values and can only be assigned to. once you assign to one (e.g. via the .= operator), it stops being a null PDL. glow up moment β¨
To create a null PDL, use "PDL->null()".
π Empty PDLs π
PDLs can represent the empty set using "structured Empty" variables. and no β an empty PDL is not a null PDL, don't play them like that π
Any dim of a PDL can be set explicitly to size 0. if you do that, the PDL contains zero values β because the total number of values is the product of all the sizes in the PDL's shape or dimlist. math is math.
Scalar PDLs are zero-dimensional and have no entries in the dim list, so they cannot be empty. 1-D and higher PDLs can be empty. empty PDLs are useful for set operations, and are most commonly encountered in the output from selection operators such as which and whichND. not all empty PDLs have the same broadcasting properties β e.g. a 2x0-PDL represents a collection of 2-vectors that happens to contain no elements, while a simple 0-PDL represents a collection of scalar values (that also happens to contain no elements).
Heads up bestie:0dims are not adjustable via the broadcasting rules β a dim with size0can only match a corresponding dim of size0or1. that's the rule, periodt.
π Broadcast rules and assignments π
Versions of PDL through 2.4.10 have some irregularity with broadcasting and assignments. currently the broadcasting engine performs a full expansion of both sides of the computed assignment operator .= (which assigns values to a pre-existing PDL). this leads to counter-intuitive behavior in some cases:
- Empty PDLs and generalized scalars
Generalized scalars (PDLs with a dim of size 1) can match any size in the corresponding dim, including 0. Thus,
$x = ones(2,0);
$y = sequence(2,1);
$c = $x * $y;
print $c;
prints "Empty[2,0]".
This behavior is counterintuitive but desirable, and will be preserved in future versions of PDL.
π VARIABLES π
these are important variables of global scope, and they live in the PDL namespace.
$PDL::debugβ when true, PDL debugging information is printed.$PDL::verboseβ when true, PDL functions provide chatty information.$PDL::use_commasβ whether to insert commas when printing pdls.$PDL::floatformat,$PDL::doubleformat,$PDL::indxformatβ the default print format for floats, doubles, and indx values, respectively. the default default values are:
$PDL::floatformat = "%7g";
$PDL::doubleformat = "%10.8g";
$PDL::indxformat = "%12d";
$PDL::infoformatβ the default format for"info". the default value is:
$PDL::infoformat = "%C: %T %D";
$PDL::undefvalβ the value to use instead of"undef"when creating pdls. if it is"undef",0will be used.$PDL::toolongtoprintβ the maximal size pdls to print (defaults to10000elements).
π₯ FUNCTIONS π₯
π«Ά barf π«Ά
the standard error reporting routine for PDL.
barf() is the routine PDL modules should call to report errors. this is because barf() will report the error as coming from the correct line in the module user's script rather than in the PDL module. icon behavior honestly.
For now, barf just calls Carp::confess()
Remember barf() is your friend. Use it!
At the perl level:
barf("User has too low an IQ!");
In C or XS code:
barf("You have made %d errors", count);
Note: this is one of the few functions ALWAYS exported by PDL::Core. π
π§ pdl π§
PDL constructor β creates new ndarray from perl scalars/arrays, ndarrays, and strings.
$double_pdl = pdl(SCALAR|ARRAY REFERENCE|ARRAY|STRING); # default type
$type_pdl = pdl(PDL::Type,SCALAR|ARRAY REFERENCE|ARRAY|STRING);
$x = pdl [1..10]; # 1D array of doubles
$x = pdl ([1..10]); # 1D array
$x = pdl (1,2,3,4); # Ditto
$y = pdl [[1,2,3],[4,5,6]]; # 2D 3x2 array
$y = pdl "[[1,2,3],[4,5,6]]"; # Ditto (slower)
$y = pdl "[1 2 3; 4 5 6]"; # Ditto
$y = pdl q[1 2 3; 4 5 6]; # Ditto, using the q quote operator
$y = pdl "1 2 3; 4 5 6"; # Ditto, less obvious, but still works
$y = pdl 42 # 0-dimensional scalar
$c = pdl $x; # Make a new copy
$u = pdl ushort(), 42 # 0-dimensional ushort scalar
$y = pdl(byte(),[[1,2,3],[4,5,6]]); # 2D byte ndarray
$n = pdl indx(), [1..5]; # 1D array of indx values
$n = pdl indx, [1..5]; # ... can leave off parens
$n = indx( [1..5] ); # ... still the same!
$n = pdl cdouble, 2, 3; # native complex numbers, zero imaginary
use Math::Complex qw(cplx);
$n = pdl cdouble, 2, cplx(2, 1)); # explicit type
$n = pdl 2, cplx(2, 1); # default cdouble if Math::Complex obj
$x = pdl([[1,2,3],[4,5,6]]); # 2D
$x = pdl([1,2,3],[4,5,6]); # 2D
Note the last two are equivalent β a list is automatically converted to a list reference for syntactic convenience. i.e. you can omit the outer "[]". we love a shortcut π
You can mix and match arrays, array refs, and PDLs in your argument list, and "pdl" will sort them out. you get back a PDL whose last (slowest running) dim runs across the top level of the list you hand in, and whose first (fastest running) dim runs across the deepest level that you supply.
At the moment, you cannot mix and match those arguments with string arguments, though we can't imagine a situation in which you would really want to do that. π
The string version of pdl also allows you to use the strings "bad", "inf", and "nan", and it will insert the values that you mean (and set the bad flag if you use "bad"). you can mix and match case, though you shouldn't. here are some examples:
$bad = pdl q[1 2 3 bad 5 6]; # Set fourth element to the bad value
$bad = pdl q[1 2 3 BAD 5 6]; # ditto
$bad = pdl q[1 2 inf bad 5]; # now third element is IEEE infinite value
$bad = pdl q[nan 2 inf -inf]; # first value is IEEE nan value
The default constructor uses IEEE double-precision floating point numbers. you can use other types, but you will get a warning if you try to use "nan" with integer types (it will be replaced with the "bad" value) and you will get a fatal error if you try to use "inf". β οΈ no cap, be careful.
Throwing a PDL into the mix has the same effect as throwing in a list ref:
pdl(pdl(1,2),[3,4])
is the same as
pdl([1,2],[3,4]).
All of the dimensions in the list are "padded-out" with undefval to meet the widest dim in the list, so (e.g.)
$x = pdl([[1,2,3],[2]])
gives you the same answer as
$x = pdl([[1,2,3],[2,undef,undef]]);
If your PDL module has bad values compiled into it (see PDL::Bad), you can pass BAD values into the constructor within pre-existing PDLs. the BAD values are automatically kept BAD and propagated correctly. bestie behavior fr fr.
pdl() is a functional synonym for the 'new' constructor, e.g.:
$x = PDL->new([1..10]);
In order to control how undefs are handled in converting from perl lists to PDLs, one can set the variable $PDL::undefval. for example:
$foo = [[1,2,undef],[undef,3,4]];
$PDL::undefval = -999;
$f = pdl $foo;
print $f
[
[ 1 2 -999]
[-999 3 4]
]
$PDL::undefval defaults to zero.
As a final note, if you include an Empty PDL in the list of objects to construct into a PDL, it is kept as a placeholder pane β so if you feed in (say) 7 objects, you get a size of 7 in the 0th dim of the output PDL. the placeholder panes are completely padded out. but if you feed in only a single Empty PDL, you get back the Empty PDL (no padding). π
β empty β
Returns an empty ndarray, with a single zero-length dimension. only available as a function, not a method β she doesn't do methods.
$x = empty; # defaults to lowest type so it can always be promoted up
$x = empty(float);
π null π
Returns a 'null' ndarray. it is an error to pass one of these as an input to a function. π¨
$x = null;
okay that's part 1 bestie, we are SO back β more parts incoming πβ¨
So null() is not like other empties β PDL::PP gives it a whole special meaning π
It flags a super specific kind of empty ndarray that's allowed to grow to whatever dimensions it needs to hold a result (which is a totally different vibe from shoving a result into an ndarray that already exists).
pdl> sumover sequence(10,10), $ans=null;p $ans
[45 145 245 345 445 545 645 745 845 945]
π± nullcreate
Hands you back a 'null' ndarray. That's it, that's the job π«Ά
$x = PDL->nullcreate($arg)
It's the routine a whole bunch of the broadcasting primitives (think sumover, minimum, etc.) call to spin up a null ndarray for the function's output β one that'll actually behave right for derived (or subclassed) PDL objects. classy
For the usage up there: if $arg is a PDL, or a derived PDL, then $arg->null comes back at you. If $arg is a scalar (i.e. a zero-dimensional PDL) then you get PDL->null.
PDL::Derived->nullcreate(10)
returns PDL::Derived->null.
PDL->nullcreate($pdlderived)
returns $pdlderived->null.
π’ nelem
Returns how many elements are hanging out in an ndarray.
$n = nelem($ndarray); $n = $ndarray->nelem;
$mean = sum($data)/nelem($data);
π dims
Gives you the ndarray's dimensions as a perl list.
@dims = $ndarray->dims; @dims = dims($ndarray);
pdl> p @tmp = dims zeroes 10,3,22
10 3 22
Also peep "shape", which hands you back an ndarray instead. π
π§ dimincs
Returns the ndarray's "dimincs" as a perl list, and it reflects any vaffine transformations it happens to be a child of.
@dimincs = $ndarray->dimincs
pdl> p zeroes(10,3,22)->dimincs
1 10 30
pdl> p zeroes(10,3,22)->t->dimincs
10 1 30
π¦ shape
Returns the ndarray dimensions, but as an ndarray this time.
$shape = $ndarray->shape; $shape = shape($ndarray);
pdl> p $shape = shape zeroes 10,3,22
[10 3 22]
Also check "dims", which returns a perl list. two besties, two formats π
π ndims
Returns the number of dimensions in an ndarray. It's literally just an alias for getndims. same energy, different name.
π getndims
Returns the number of dimensions in an ndarray.
$ndims = $ndarray->getndims;
pdl> p zeroes(10,3,22)->getndims
3
π dim
Returns the size of the given dimension of an ndarray. Alias for getdim. (yes it's giving twin flames)
π getdim
Returns the size of the given dimension.
$dim0 = $ndarray->getdim(0);
pdl> p zeroes(10,3,22)->getdim(1)
3
Heads up bestie β negative indices count from the end of the dims array. And indices beyond the end just return a size of 1. Which makes total sense honestly, because it reflects the idea that any pdl is equivalent to an infinitely dimensional array where only a finite number of dimensions have a size that isn't one. So in that β¨senseβ¨, a 3D ndarray of shape [3,5,2] is equivalent to a [3,5,2,1,1,1,1,1,....] ndarray. So accordingly,
print $x->getdim(10000);
will print 1 for basically every ndarray you'll ever meet in practice. no cap π«
ποΈ topdl
The alternate ndarray constructor β it makes absolutely sure the arg is an ndarray.
$x = topdl(SCALAR|ARRAY REFERENCE|ARRAY);
The difference between pdl() and topdl() is that the latter will just fall through if the argument is already an ndarray. And it returns a reference, NOT a new copy. periodt.
This is lowkey extremely useful when you're writing a function that's fiddling with internals and just assumes it's got an ndarray argument (like for method calls, yk). Using topdl() means nothing breaks if somebody passes you a '2'. π
Btw topdl() is not exported by default β check the example below for how to actually use it.
use PDL::Core ':Internal'; # use the internal routines of
# the Core module
$x = topdl 43; # $x is ndarray with value '43'
$y = topdl $ndarray; # fall through
$x = topdl (1,2,3,4); # Convert 1D array
π« tocomplex
Returns a complex-typed ndarray β either as a total no-op or as a conversion, depends.
$cplx = $pdl->tocomplex;
Not exported. Added in 2.099. πΈ
βοΈ setdims
Sets the ndarray's dimension list. This is a very low-level routine that does not do any checks, so pls use with caution bestie π
$ndarray->setdims(\@dimlist);
π§ set_datatype
Sets the ndarray's data type to the given value (that's the integer identifier for the type, peep "enum" in PDL::Types). Also see "get_datatype". This is an internal function. It errors if the ndarray has child transforms, and it severs if it has a parent. messy but that's the deal π
π get_datatype
Internal: returns the numeric value that identifies the ndarray datatype.
$x = $ndarray->get_datatype;
Mainly used for internal routines.
NOTE: get_datatype returns 'just a number' β not any special type object, unlike "type". don't get it twisted.
π¦ howbig
Returns the sizeof an ndarray datatype in bytes.
Note that howbig() is not exported by default β example below, as always π«Ά
use PDL::Core ':Internal'; # use the internal routines of
# the Core module
$size = howbig($ndarray->get_datatype);
Mainly used for internal routines.
NOTE: this is NOT a method! And the reason is literally because get_datatype returns 'just a number', not any special object. mid but consistent.
pdl> p howbig(ushort([1..10])->get_datatype)
2
π update_data_from
Updates an ndarray's internal data from packed data.
$data = read_from_datasource();
$pdl->update_data_from($data);
Throws an exception if the argument is the wrong size for that ndarray. so like, don't test it π«
π₯ get_dataref
Returns the internal data for an ndarray, as a perl SCALAR ref.
If you're using this to manipulate the SV, then call "upd_data" β but as of 2.099 you're recommended to just use "update_data_from" instead to streamline the whole process. glow-up moment β¨
Most ndarrays keep their internal data in a packed perl string, all to take advantage of perl's memory management. This gives you direct access to that string, which is super handy when you need to manipulate the binary data directly (e.g. for file I/O). If you modify that string, you'll need to call "upd_data" afterward, so the ndarray properly points to the new location of the underlying perl variable.
Calling "get_dataref" automatically physicalizes your ndarray (see "make_physical"). You definitely don't want to do anything to the SV that truncates or deallocates the string, unless you correspondingly call "reshape" to make the PDL match its new data dimension.
You definitely don't want to use get_dataref unless you know what you're doing (or you're actively trying to find out): you can end up scrozzling memory if you shrink or eliminate the string representation of the variable.
Here be dragons. ππ genuinely, dragons.
π upd_data
Updates the data pointer in an ndarray to match its perl SV.
This is useful if you've been monkeying with the packed string representation of the PDL β which you probably shouldn't be doing anyway. (see "get_dataref".) no notes, just don't π«Ά
As of 2.099 you're recommended to just use "update_data_from" instead, to streamline the process.
π broadcastids
Returns the ndarray broadcast IDs as a perl list.
Note that broadcastids() is not exported by default β example time π
use PDL::Core ':Internal'; # use the internal routines of
# the Core module
@ids = broadcastids $ndarray;
π readonly
Makes an ndarray read-only, and returns the ndarray argument. Which means any future transformation (a.k.a. PDL operation) applied to this ndarray as an output will cause an exception:
$x = sequence(3)->readonly; # also works: $x = sequence(3); $x->readonly;
$y = $x + 1; # fine
$x .= 5; # error
$x += 5; # also error
Not exported.
$x->readonly;
π΅οΈ is_readonly
Tests whether an ndarray is read-only.
$bool = $x->is_readonly;
Not exported.
$x->is_readonly;
π flowing
Turns on dataflow β forward only, and only for the next operation (cf "inplace") β and returns the ndarray argument. Which means the next transformation (a.k.a. PDL operation) applied to this ndarray will have forward dataflow:
$x = sequence 3;
$y = $x->flowing + 1; # could instead do $x->flowing; $y = $x + 1
$x += 3; # this does not flow, but that would be an infinite loop anyway
print "$y\n"; # [4 5 6]
This replaced "doflow" as of 2.090. See PDL::Dataflow for more. β¨
$x->flowing; flowing($x);
π© fflows
Returns whether the ndarray's PDL_DATAFLOW_F flag is set.
π new
The new ndarray constructor method.
$x = PDL->new(SCALAR|ARRAY|ARRAY REF|STRING);
$x = PDL->new(42); # new from a Perl scalar
$y = PDL->new(@list_of_vals); # new from Perl list
$z = PDL->new(\@list_of_vals); # new from Perl list reference
$w = PDL->new("[1 2 3]"); # new from Perl string, using
# Matlab constructor syntax
Constructs an ndarray from perl numbers and lists and strings, using Matlab/Octave style constructor syntax. iconique π
The string input is pretty versatile, though it's not performance optimized. The whole goal is to make it easy to copy and paste code straight from PDL output, and to offer a familiar Matlab syntax for ndarray construction. As of May, 2010, it was a new feature, so feel free to report bugs or suggest new features. See the documentation for pdl for more examples of usage.
π copy
Makes a physical copy of an ndarray.
$new = $old->copy;
Since $new = $old just makes a new reference, the "copy" method exists to let you make real, independent copies. no shared custody here π
π hdr_copy
Returns an explicit copy of the header of a PDL.
hdr_copy is just a wrapper for the internal routine _hdr_copy, which takes the hash ref itself. That's the routine used to make copies of the header during normal operations whenever the hdrcpy() flag of a PDL is set.
General-purpose deep copies are expensive in perl, so some simple optimization happens:
If the header is a tied array, or a blessed hash ref with an associated method called "copy", then that ->copy method gets called. Otherwise, all elements of the hash are explicitly copied. References are recursively deep copied.
This routine seems to leak memory. π yeah. that's the note. sorry bestie.
π unwind
Returns an ndarray that's the same as the argument, except that all broadcastids have been removed.
$y = $x->unwind;
π§± make_physical
Makes sure the data portion of an ndarray can be accessed from XS code.
$x->make_physical;
$x->call_my_xs_method;
Ensures that an ndarray gets its own allocated copy of data. Which obviously implies that there are certain ndarrays out there that don't have their own data. These are the so-called virtual ndarrays that make use of the vaffine optimisation (see PDL::Indexing). They don't have their own copy of data at all β instead they just store access information to some (or all) of another ndarray's data. sneaky but legal π
Note: this function should not be used unless absolutely necessary, since otherwise memory requirements might be severely increased. Instead of writing your own XS code and needing to call"make_physical", you might want to consider using the PDL preprocessor (seePDL::PP) β which can transparently access virtual ndarrays without needing to physicalise them (though there are exceptions). iykyk π«Ά
make_physvaffine
The careful cousin of make_physical π
If an ndarray's parent isn't a vaffine transformation, it just quietly calls make_physical like nothing happened. But if it is a vaffine transformation, it goes and updates the vaffine transformation bookkeeping. Diligent. Organized. A whole accountant. π§Ύβ¨
make_physdims
Makes sure the ndarray's dims are up to date, parent's dimension changes included, and it calls redodims while it's at it. Basically the "did you check the group chat" of dimension maintenance. π«Ά
trans_parent
Returns a PDL::Trans object β that's the transformation (the PDL operation) that is the parent of this ndarray β or undef if there's no parent at all. Orphan arc. π
And bestie, these objects come with their own little methods, so let's go:
parentsβ Returns a list of ndarrays that are inputs to this trans.childrenβ Returns a list of ndarrays that are outputs to this trans (specified as[o],[oca],[io], or[t]inPars).addressβ The memory address of the struct.flagsβ List of strings of flags set for this trans.affineβ Whether the trans is affine.offsβ Affine-only: the offset into the parent's data.incsβ Affine-only: the dimincs for each of the child's dims.ind_sizesβ The size of each named dim.inc_sizesβ The size of the inc for each use of a named dim.vtableβ This trans's vtable.$vtable->nameβ The function name from this vtable.$vtable->flagsβ List of strings of flags set for this vtable.$vtable->par_namesβ List of 2 array-refs of strings of names of input pars, then output pars, for this vtable.
trans_children
Returns a list of PDL::Trans objects (peep trans_parent above π) representing each transformation that has this ndarray as an input. It has lore. It has fans. πΈ
address
Returns the memory address of the ndarray's struct. β¨
address_data
Returns the value of the ndarray struct's data member. π
set_donttouchdata
Sets the PDL_DONTTOUCHDATA flag and the nbytes to the given value. Super handy for memory-mapping functionality. The nbytes can be left out, and then only the flag gets set β minimal effort, still valid. π
nbytes
Returns the ndarray's nbytes.
seed
Returns the random seed being used by PDL's RNG. π² Not me checking the RNG's birth chart.
set_debugging
Sets whether PDL operations print lots of debugging info to standard output. Returns the old value, so you can put it back like the respectful little gremlin you are.
PDL::Core::set_debugging(1);
# ... these operations will have debugging info printed to stdout
PDL::Core::set_debugging(0); # turn it off again
dummy
Insert a 'dummy dimension' of given length (defaults to 1). π
No relation to the 'Dungeon Dimensions' in Discworld! (Sir Terry did not consult on this function. Probably.)
Negative positions specify relative to the last dimension, i.e. dummy(-1) appends one dimension at the end, dummy(-2) inserts a dummy dimension in front of the last dim, etc.
If you specify a dimension position larger than the existing dimension list of your PDL, the PDL gets automagically padded with extra dummy dimensions so you get the dim you asked for, in the slot you asked for. But like β this could cause you trouble. Specifically, if you ask for $x->dummy(5000,1), then $x will get 5,000 dimensions, each of rank 1. Five thousand. Not a typo. Bestie. π
Because padding at the beginning of the dimension list moves existing dimensions from slot to slot, it's considered unsafe, so automagic padding doesn't work for large negative indices β only for large positive indices.
$y = $x->dummy($position[,$dimsize]);
pdl> p sequence(3)->dummy(0,3)
[
[0 0 0]
[1 1 1]
[2 2 2]
]
pdl> p sequence(3)->dummy(3,2)
[
[
[0 1 2]
]
[
[0 1 2]
]
]
pdl> p sequence(3)->dummy(-3,2)
Runtime error: PDL: For safety, <pos> < -(dims+1) forbidden in dummy. min=-2, pos=-3
dup
Duplicates an ndarray along a dimension. Same energy, doubled. π¦
$x = sequence(3);
$y = $x->dup(0, 2); # doubles along first dimension
# $y now [0 1 2 0 1 2]
dupN
Duplicates an ndarray along several dimensions. Ambitious. Multi-hyphenate. β¨
$x = sequence(3,2);
$y = $x->dupN(2, 3); # doubles along first dimension, triples along second
# [
# [0 1 2 0 1 2]
# [3 4 5 3 4 5]
# [0 1 2 0 1 2]
# [3 4 5 3 4 5]
# [0 1 2 0 1 2]
# [3 4 5 3 4 5]
# ]
inflateN
Inflates an ndarray along several dimensions β super useful for e.g. Kronecker products. π
cf dupN (yes, they're siblings, and yes, the family resemblance is strong).
$x = sequence(3,2);
$y = $x->inflateN(2, 2); # doubles along first two dimensions
# [
# [0 0 1 1 2 2]
# [0 0 1 1 2 2]
# [3 3 4 4 5 5]
# [3 3 4 4 5 5]
# ]
clump
"Clumps" several dimensions into one large dimension. The vibes are: shove it all in one bag and shake. π
If called with one argument $n, it clumps the first $n dimensions into one. For example, if $x has dimensions (5,3,4) then after
$y = $x->clump(2); # Clump 2 first dimensions
the variable $y will have dimensions (15,4) and the element $y->at(7,3) refers to the element $x->at(1,2,3). Math checks out, it's giving efficient. π₯
Use clump(-1) to flatten an ndarray. The method flat is provided as a convenient alias.
Clumping with a negative dimension in general leaves that many dimensions behind β e.g. clump(-2) clumps all of the first few dimensions into a single one, leaving a 2-D ndarray.
If clump is called with an index list with more than one element, it's treated as a list of dimensions that should be clumped together into one. The resulting clumped dim is placed at the position of the lowest index in the list. This convention ensures clump does the expected thing in the usual cases. The following examples demonstrate usage:
zeroes(2,3,5,7)->clump(-1)->info # PDL: Double D [210]
zeroes(2,3,5,7)->clump(-2)->info # PDL: Double D [30,7]
zeroes(2,3,5,7)->clump(2)->info # PDL: Double D [6,5,7]
zeroes(2,3,5,7)->clump(3)->info # PDL: Double D [30,7]
zeroes(2,3,5,7)->clump(1,2)->info # PDL: Double D [2,15,7]
zeroes(2,3,5,7)->clump(1,3)->info # PDL: Double D [2,21,5]
Data flows back and forth as usual with slicing routines. π
broadcast_define
Define functions that support broadcasting at the perl level. β¨
broadcast_define 'tline(a(n);b(n))', over {
line $_[0], $_[1]; # make line compliant with broadcasting
};
broadcast_define provides some support for broadcasting (see PDL::Indexing) at the perl level. It lets you do things for which you normally would have resorted to PDL::PP (see PDL::PP); however, it's most useful to wrap existing perl functions so the new routine supports PDL broadcasting. π
broadcast_define is used to define new broadcasting aware functions. Its first argument is a symbolic representation of the new function to be defined. The string is composed of the name of the new function followed by its signature (see PDL::Indexing and PDL::PP) in parentheses. The second argument is a subroutine that will be called with the slices of the actual runtime arguments as specified by its signature. Correct dimension sizes and minimal number of dimensions for all arguments will be checked (assuming the rules of PDL broadcasting, see PDL::Indexing). No sneaky dimension crimes allowed. π¨
The actual work is done by the signature class, which parses the signature string, does runtime dimension checks, and the routine broadcastover, which generates the loop over all appropriate slices of pdl arguments and creates pdls as needed.
Similar to pp_def and its OtherPars option, it's possible to define the new function so that it accepts normal perl args as well as ndarrays. You do this by using the NOtherPars parameter in the signature. The number of NOtherPars specified will be passed unaltered into the subroutine given as the second argument of broadcast_define. Let's illustrate this with an example:
PDL::broadcast_define 'triangles(inda();indb();indc()), NOtherPars => 2',
PDL::over {
${$_[3]} .= $_[4].join(',',map {$_->at} @_[0..2]).",-1,\n";
};
This defines a function triangles that takes 3 ndarrays as input plus 2 arguments which are passed into the routine unaltered. This routine is used to collect lists of indices into a perl scalar that is passed by reference. Each line is preceded by a prefix passed as $_[4]. Here is typical usage:
$txt = '';
triangles(pdl(1,2,3),pdl(1),pdl(0),\$txt," "x10);
print $txt;
resulting in the following output
1,1,0,-1,
2,1,0,-1,
3,1,0,-1,
which is used in PDL::Graphics::TriD::VRML to generate VRML output. Slay, honestly. π
Currently, this is probably not much more than a POP (proof of principle) but is hoped to be useful enough for some real life work.
Check PDL::PP for the format of the signature. Currently, the [t] qualifier and all type qualifiers are ignored. π
broadcast
Use explicit broadcasting over specified dimensions (see also PDL::Indexing). π«
$y = $x->broadcast($dim,[$dim1,...])
$x = zeroes 3,4,5;
$y = $x->broadcast(2,0);
print $y->info; # PDL: Double D [4] T1 [5,3]
$pb = zeroes(3,3);
print $pb->broadcast(0,1)->info; # PDL: Double D [] T1 [3,3]
print $pb->broadcast(0)->info; # 'PDL: Double D [3] T1 [3]
print zeroes(4,7,2,8)->broadcast(2)->info; # PDL: Double D [4,7,8] T1 [2]
print zeroes(4,7,2,8)->broadcast(2,1)->info; # PDL: Double D [4,8] T1 [2,7]
print zeroes(4,7,2,8,5,6)->broadcast(2,4)->info; # PDL: Double D [4,7,8,6] T1 [2,5]
print zeroes(4,7,2,8,5,6)->broadcast1(2)->broadcast2(3)->info; # PDL: Double D [4,7,8,6] T1 [2] T2 [5]
Same as broadcast1, i.e. it uses broadcast id 1. To use broadcast id 2, use broadcast2, or broadcastI in PDL::Slices directly. π¦
broadcast1
Explicit broadcasting over specified dims using broadcast id 1.
$xx = $x->broadcast1(3,1)
Convenience function interfacing to PDL::Slices::broadcastI. π
broadcast2
Explicit broadcasting over specified dims using broadcast id 2.
$xx = $x->broadcast2(3,1)
Convenience function interfacing to PDL::Slices::broadcastI.
broadcast3
Explicit broadcasting over specified dims using broadcast id 3.
$xx = $x->broadcast3(3,1)
Convenience function interfacing to PDL::Slices::broadcastI.
sever
Sever any links of this ndarray to parent ndarrays. Cutting the cord. Setting boundaries. Therapy, but for memory. π
In PDL it's possible for an ndarray to be just another view into another ndarray's data. In that case we call this ndarray a virtual ndarray and the original ndarray owning the data its parent. In other languages these alternate views sometimes run by names such as alias or smart reference.
Typical functions that return such ndarrays are slice, xchg, index, etc. Sometimes, however, you'd like to separate the virtual ndarray from its parent's data and just give it a life of its own (so that manipulation of its data doesn't change the parent). This is simply achieved by using sever. For example,
$x = $pdl->index(pdl(0,3,7))->sever;
$x++; # important: $pdl is not modified!
β οΈ Note that# important:comment β genuinely important. If you skip thesever,$pdldoes get modified. Your parent's data is not your data, bestie. π¨π«Ά
In many (but not all) circumstances it acts therefore similar to copy. However, bestie, performance is generally better with sever, and also sever doesn't do that whole futile copying thing when it's used on ndarrays that already have their own data. On the other hand, if you really want to make sure you're working on a copy of an ndarray, use copy.
$x = zeroes(20);
$x->sever; # NOOP since $x is already its own boss!
Again note: sever is not the same as copy! For example,
$x = zeroes(1); # $x does not have a parent, i.e. it is not a slice etc
$y = $x->sever; # $y is now pointing to the same ndarray as $x
$y++;
print $x;
[1]
but
$x = zeroes(1);
$y = $x->copy; # $y is now pointing to a new ndarray
$y++;
print $x;
[0]
β¨ info β¨
Return formatted information about an ndarray. Like, a little report card for your ndarray, slay. π
$x->info($format_string);
print $x->info("Type: %T Dim: %-15D State: %S");
Returns a string with info about an ndarray. Takes an optional argument to specify the format of information a la sprintf. Format specifiers are in the form "%<width><letter>" where the width is optional and the letter is one of:
Tβ TypeDβ Formatted DimensionsFβ Dataflow statusSβ Some internal flags (P=physical,V=Vaffine,C=changed,B=may contain bad data)Cβ Class of this ndarray, i.e."ref $pdl"Aβ Address of the ndarray struct as a unique identifierMβ Calculated memory consumption of this ndarray's data area
The default format is "%C: %T %D". This can be modified by assigning to $PDL::infoformat.
π«Ά pdump π«Ά
Returns a close analogue of the output of "$pdl->dump" as a string. Like that C function, it will not cause any physicalisation of the ndarray. No cap, it just peeks without touching.
Not exported, and not inserted into the "PDL" namespace.
print PDL::Core::pdump($pdl);
π¦ pdump_trans π¦
Returns a string representation of a "PDL::Trans" object, a close analogue of part of the output of "$pdl->dump".
Not exported, and not inserted into the "PDL" namespace.
print PDL::Core::pdump_trans($pdl_trans);
πΈ pdumphash πΈ
Returns a hash-ref representing the information about a given object ("PDL::Trans" or ndarray) and all the objects of either type it is connected to. Includes similar information to that shown by "pdump" and "pdump_trans". It's giving the whole social network of your ndarray. π
Not exported, and not inserted into the "PDL" namespace.
$hashref = PDL::Core::pdumphash($pdl_trans); # or
$hashref = PDL::Core::pdumphash($pdl);
π pdumpgraph π
Given a hash-ref returned by "pdumphash", returns a Graph object representing the same information.
Not exported, and not inserted into the "PDL" namespace.
$g = PDL::Core::pdumphash($hashref);
β¨ pdumpgraphvizify β¨
Given a Graph object returned by "pdumpgraph", modifies it suitable for input to "from_graph" in GraphViz2, then returns it. See example for how to use. It's the glow-up your graph needed. π§
Not exported, and not inserted into the "PDL" namespace.
$g = PDL::Core::pdumpgraphvizify($g);
# full example:
$count = 1; $format = 'png'; sub output {
$g = PDL::Core::pdumpgraph(PDL::Core::pdumphash($_[0]));
require GraphViz2;
$gv = GraphViz2->from_graph(PDL::Core::pdumpgraphvizify($g));
$gv->run(format => $format, output_file => 'output'.$count++.".$format");
}
# keep changing ndarray, then calling this to show each state:
output($pdl);
# run the above script, then show the ndarray evolve over time, in a
# left-to-right montage using ImageMagick tools:
perl myscript.pl
montage output* -tile "$(echo output*|wc -w)"x1 -geometry '1x1<' final.png
display final.png
π approx π
test for approximately equal values (relaxed "=="). Because floating point is a liar sometimes, bestie.
# ok if all corresponding values in
# ndarrays are within 1e-8 of each other
print "ok\n" if all approx $x, $y, 1e-8;
"approx" is a relaxed form of the "==" operator and often more appropriate for floating point types ("float" "double" and "ldouble").
Usage:
$res = approx $x, $y [, $eps]
The optional parameter $eps is remembered across invocations and initially set to 1e-6, e.g.
approx $x, $y; # last $eps used (1e-6 initially)
approx $x, $y, 1e-10; # 1e-10
approx $x, $y; # also 1e-10
π mslice π
Alias to "slice" in PDL::Slices. Just a lil nickname, iykyk.
π nslice_if_pdl π
If $self is a PDL, then calls "slice" with all but the last argument, otherwise $self->($_[-1]) is called where $_[-1] is the original argument string found during PDL::NiceSlice filtering.
DEVELOPER'S NOTE: this routine is found in Core.pm but would be better placed in Slices/slices.pd. It is likely to be moved there and/or changed to "slice_if_pdl" for PDL 3.0.
$w = $x->nslice_if_pdl(...,'(args)');
π donttouch π
Returns whether the ndarray's "PDL_DONTTOUCHDATA" flag is set. Hands off, bestie.
β¨ allocated β¨
Returns whether the ndarray's "PDL_ALLOCATED" flag is set.
π¦ vaffine π¦
Returns whether the ndarray's "PDL_OPT_VAFFTRANSOK" flag is set.
πΈ anychgd πΈ
Returns whether the ndarray's "PDL_ANYCHANGED" flag is set.
π dimschgd π
Returns whether the ndarray's "PDL_PARENTDIMSCHANGED" flag is set.
π₯ inplace π₯
Flag an ndarray so that the next operation is done 'in place', returning the ndarray.
somefunc($x->inplace); somefunc(inplace $x);
In most cases one likes to use the syntax "$y = f($x)", however in many case the operation f() can be done correctly 'in place', i.e. without making a new copy of the data for output. To make it easy to use this, we write f() in such a way that it operates in-place, and use "inplace" to hint that a new copy should be disabled. This also makes for clear syntax.
Obviously this will not work for all functions, and if in doubt see the function's documentation. However one can assume this is true for all elemental functions (i.e. those which just operate array element by array element like "log10").
pdl> $x = xvals zeroes 10;
pdl> log10(inplace $x)
pdl> p $x
[-inf 0 0.30103 0.47712125 0.60205999 0.69897 0.77815125 0.84509804 0.90308999 0.95424251]
π«Ά is_inplace π«Ά
Sets whether an ndarray will operate "in-place" for the next operation if a (Boolean) value is given. Returns the old value.
$out = ($in->is_inplace) ? $in : zeroes($in);
$in->set_inplace(0)
Provides access to the "inplace" hint flag, within the perl milieu. That way functions you write can be inplace aware... If given an argument the inplace flag will be set or unset depending on the value at the same time. Can be used for shortcut tests that delete the inplace flag while testing:
$out = ($in->is_inplace(0)) ? $in : zeroes($in); # test & unset!
π set_inplace π
Set the in-place flag on an ndarray
$out = ($in->is_inplace) ? $in : zeroes($in);
$in->set_inplace(0);
Provides access to the "inplace" hint flag, within the perl milieu. Useful mainly for turning it OFF, as "inplace" turns it ON more conveniently.
π§ new_or_inplace π§
$w = new_or_inplace(shift());
$w = new_or_inplace(shift(),$preferred_type);
Return back either the argument pdl or a copy of it depending on whether it be flagged in-place or no. Handy for building inplace-aware functions.
If you specify a preferred type (must be one of the usual PDL type strings, a list ref containing several of them, or a comma-separated string containing several of them), then the copy is coerced into the first preferred type listed if it is not already one of the preferred types.
Note that if the inplace flag is set, no coercion happens even if you specify a preferred type.
π new_from_specification π
Internal method: create ndarray by specification
This is the argument processing method called by "zeroes" and some other functions which constructs ndarrays from argument lists of the form:
[type], $nx, $ny, $nz,...
For $nx, $ny, etc. 0 and 1D ndarrays are allowed. Giving those has the same effect as if saying "$arg->list", e.g.
1, pdl(5,2), 4
is equivalent to
1, 5, 2, 4
Note, however, that in all functions using "new_from_specification" calling "func $ndarray" will probably not do what you want. So to play safe use (e.g. with zeroes)
$pdl = zeroes $dimpdl->list;
Calling
$pdl = zeroes $dimpdl;
will rather be equivalent to
$pdl = zeroes $dimpdl->dims;
However,
$pdl = zeroes ushort, $dimpdl;
will again do what you intended since it is interpreted as if you had said
$pdl = zeroes ushort, $dimpdl->list;
This is unfortunate and confusing but no good solution seems obvious that would not break existing scripts. Awkward, but we move. π
π isnull π
Test whether an ndarray is null
croak("Input ndarray mustn't be null!")
if $input_ndarray->isnull;
This function returns 1 if the ndarray is null, zero if it is not. The purpose of null ndarrays is to "tell" any PDL::PP methods to allocate new memory for an output ndarray, but only when that PDL::PP method is called in full-arg form. Of course, there's no reason you couldn't commandeer the special value for your own purposes, for which this test function would prove most helpful. But in general, you shouldn't need to test for an ndarray's nullness.
See "Null PDLs" for more information.
πΈ isempty πΈ
Test whether an ndarray is empty
print "The ndarray has zero dimension\n" if $pdl->isempty;
This function returns 1 if the ndarray has zero elements. This is useful in particular when using the indexing function which. In the case of no match to a specified criterion, the returned ndarray has zero dimension.
pdl> $w=sequence(10)
pdl> $i=which($w < -1)
pdl> print "I found no matches!\n" if ($i->isempty);
I found no matches!
Note that having zero elements is rather different from the concept of being a null ndarray, see the PDL::FAQ and PDL::Indexing manpages for discussions of this.
π zeroes π
construct a zero filled ndarray from dimension list or template ndarray. If called with no arguments, returns a zero-dimension ndarray (a scalar). It's giving empty but make it organized. β¨
Various forms of usage,
(i) by specification or (ii) by template ndarray:
# usage type (i):
$w = zeroes([type], $nx, $ny, $nz,...);
$w = PDL->zeroes([type], $nx, $ny, $nz,...);
$w = $pdl->zeroes([type], $nx, $ny, $nz,...); # all info about $pdl ignored
# usage type (ii):
$w = zeroes $y;
$w = $y->zeroes
zeroes inplace $w; # Equivalent to $w .= 0;
$w->inplace->zeroes; # ""
pdl> $z = zeroes 4,3
pdl> p $z
[
[0 0 0 0]
[0 0 0 0]
[0 0 0 0]
]
pdl> $z = zeroes ushort, 3,2 # Create ushort array
[ushort() etc. with no arg returns a PDL::Types token]
See also "new_from_specification" for details on using ndarrays in the dimensions list.
π zeros π
construct a zero filled ndarray (see zeroes for usage). Yes it's the same thing, just shorter. Periodt. π
β¨ ones β¨
makes an ndarray absolutely PACKED with ones, no cap. call it with zero arguments and boom, you get a zero-dimension ndarray (a scalar, bestie).
$w = ones([type], $nx, $ny, $nz,...);
etc. (see 'zeroes')
it's literally zeroes() and then you add one. that's the whole vibe.
also go peep "new_from_specification" if you wanna know the tea about using ndarrays up in the dimensions list. π
πΈ nan πΈ
same energy but the ndarray is filled with "NaN". call with no args β zero-dimension ndarray (scalar) again.
$w = nan([type], $nx, $ny, $nz,...);
etc. (see 'zeroes')
take zeroes() and add NaN. slay.
"new_from_specification" has the deets on ndarrays in the dimensions list, iykyk.
π¦ inf π¦
constructs an ndarray full of "Inf". no arguments? zero-dimension ndarray (a scalar), naturally.
$w = inf([type], $nx, $ny, $nz,...);
etc. (see 'zeroes')
it's zeroes() plus Inf. gorgeous.
see "new_from_specification" for how ndarrays work inside the dimensions list. π«Ά
π i π
makes an ndarray filled with the native complex value equal to the imaginary number i, aka the square root of -1. call it empty and you get a zero-dimension ndarray (a scalar).
$w = i([type], $nx, $ny, $nz,...);
etc. (see 'zeroes')
basically zeroes() + i. it's giving imaginary math main character energy. β¨
"new_from_specification" explains using ndarrays in the dimensions list. π
π reshape π
changes the shape (a.k.a. the dimensions) of an ndarray while keeping the contents intact.
$x->reshape(NEWDIMS); reshape($x, NEWDIMS);
the data elements are preserved, obviously β they'll just wrap differently and get truncated if the new array is shorter. if the new array is longer, it's zero-padded. periodt.
***Potential incompatibility with earlier versions of PDL****β if the list of"NEWDIMS"is empty,"reshape"will just drop every dimension of size 1 (while preserving the number of elements):
$w = sequence(3,4,5);
$y = $w(1,3);
$y->reshape();
print $y->info;
PDL: Double D [5]
dimensions of size 1 also get dropped if "reshape" is invoked with the argument -1:
$y = $w->reshape(-1);
unlike "reshape" with no arguments, reshape(-1) preserves dataflow:
$w = ones(2,1,2);
$y = $w(0)->reshape(-1);
$y++;
print $w;
[
[
[2 1]
]
[
[2 1]
]
]
Important: ndarrays are changed inplace!!
Note: if $x is connected to any other PDL (like if it's a slice), then the connection is severed first. cut off. π
pdl> $x = sequence(10)
pdl> reshape $x,3,4; p $x
[
[0 1 2]
[3 4 5]
[6 7 8]
[9 0 0]
]
pdl> reshape $x,5; p $x
[0 1 2 3 4]
π§ squeeze π§
eliminates every singleton dimension (aka dims of size 1). so clean.
$y = $w(0,0)->squeeze;
it's an alias for reshape(-1). removes all the singleton dimensions and preserves dataflow. there's a more concise interface via PDL::NiceSlice modifiers:
use PDL::NiceSlice;
$y = $w(0,0;-); # same as $w(0,0)->squeeze
π flat π
flattens an ndarray (alias for "$pdl->clump(-1)").
$srt = $pdl->flat->qsort;
super useful method for making a 1D ndarray out of an arbitrarily sized input ndarray. data flows back and forth as usual with slicing routines. falls through if the argument is already == 1D. π
β convert β
the generic datatype conversion function. works on ndarrays AND normal numbers. if it's already that type, it returns your input as-is.
$y = convert($x, $newtype);
$y = $x->convert($newtype);
$x->inplace->convert($newtype);
$newtype is a type number or a PDL::Type object β for convenience those get returned by long() etc. when they're called without arguments. it can work in-place, though it will "sever" if it does.
$y = convert $x, long;
$y = $x->convert(ushort);
$x->inplace->convert(double);
π convert_flowing π
the generic datatype data-flowing conversion function.
$y = convert_flowing($x, $newtype);
$y = $x->convert_flowing($newtype);
$newtype is a type number or a PDL::Type object β again, for convenience they're returned by long() etc. when called with no arguments. this one ONLY works on ndarrays, not normal numbers. returns input if it's already that type. and it establishes two-way dataflow between the two ndarrays. it's giving connected. π«Ά
πΈ Datatype_conversions πΈ
sbyte|byte|short|ushort|long|ulong|indx|longlong|ulonglong|float|double|ldouble|cfloat|cdouble|cldouble (shorthands to convert datatypes)
$y = double $x; $y = ushort [1..10];
# all of the above listed shorthands behave similarly
when you hand them an ndarray argument, they convert it to that specific datatype.
when you give them a numeric, list, listref, or string argument, they construct a brand new ndarray. it's a convenience so you don't have to be long-winded and say "$x = long(pdl(42))". lifesaver fr.
so you can literally say:
$w = float(1,2,3,4); # 1D
$w = float q[1 2 3; 4 5 6]; # 2D
$w = float([1,2,3],[4,5,6]); # 2D
$w = float([[1,2,3],[4,5,6]]); # 2D
note the last three all give identical results, and the last two are exactly equivalent β a list is automatically converted to a list reference for syntactic convenience. i.e. you can omit the outer "[]". iconic.
when they're called with no arguments, these functions return a special type token. this allows syntactical sugar like:
$x = ones byte, 1000,1000;
this example creates a big ol' ndarray directly as byte datatype to save memory. so efficient. β¨
to control how undefs are handled when converting from perl lists to PDLs, you can set the variable $PDL::undefval; see the function pdl() for more deets.
pdl> p $x=sqrt float [1..10]
[1 1.41421 1.73205 2 2.23607 2.44949 2.64575 2.82843 3 3.16228]
pdl> p byte $x
[1 1 1 2 2 2 2 2 3 3]
byte
Convert to byte datatype π
short
Convert to short datatype
ushort
Convert to ushort datatype
long
Convert to long datatype
indx
Convert to indx datatype
longlong
Convert to longlong datatype
float
Convert to float datatype
double
Convert to double datatype
ldouble
Convert to long double datatype
cfloat
Convert to complex float datatype
cdouble
Convert to complex double datatype
cldouble
Convert to complex long double datatype
π type π
returns the type of an ndarray as a blessed type object.
a convenience function for use with the ndarray constructors, e.g.
$y = PDL->zeroes($x->type,$x->dims,3);
die "must be float" unless $x->type == float;
also peep the discussion of the "PDL::Type" class in PDL::Types. note that "PDL::Type" objects have overloaded comparison and stringify operators, so you can compare and print types like:
$x = $x->float if $x->type < float;
$t = $x->type; print "Type is $t\n";
π¦ string π¦
converts an ndarray to string, and you can optionally use a "sprintf" format. if you hand it such a format, it gets used. if you don't, then the formatting variables in "VARIABLES" provide a default β though heuristics are attempted to make a nice-looking output. π
print $x; # overloaded
print $x->string; # explicit method call
print $x->string("%5d"); # providing sprintf format
π list π
converts an ndarray to a perl list.
@tmp = list $x;
obviously this is grossly inefficient for the huge datasets PDL is designed to handle. it was provided as a get-out while PDL matured. it should now be mostly superseded by superior constructs, like PP/broadcasting. but it's still occasionally useful, so it's provided for backwards compatibility. classic.
for (list $x) {
# Do something on each value...
}
list converts any bad values into the string 'BAD'.
π unpdl π
converts an ndarray to nested Perl array references.
$arrayref = unpdl $x;
this function returns a reference to a Perl list-of-lists structure equivalent to the input ndarray (with the limitation that while the values of elements should be preserved, the detailed datatypes will NOT be, since perl itself basically has "number" data rather than byte, short, int... e.g., "sum($x - pdl( $x->unpdl ))" should equal 0).
obviously this is grossly inefficient in memory AND processing for the large datasets PDL is designed to handle. but sometimes you really, truly want to move your data back to Perl, with proper dimensionality, unlike "list".
if you want to round-trip data including the use of "PDL::undefval", "unpdl" does not support this. however, the suggestion is that you'd generate an index-set with "$pdl->whereND($pdl == $PDL::undefval)", then loop over the Perl data, setting those locations to "undef".
another round-trip caveat: a zero-dimensional ndarray (a scalar) will be returned as a single-element array-ref. this is conceptually incorrect, but it cannot now be changed due to backward compatibility. rip. π
use JSON;
my $json = encode_json unpdl $pdl;
unpdl converts any bad values into the string 'BAD'.
π listindices π
converts ndarray indices to a perl list.
@tmp = listindices $x;
@tmp now contains the values "0..nelem($x)-1".
obviously this is grossly inefficient for the large datasets PDL is designed to handle. provided as a get-out while PDL matured. it should now be mostly superseded by superior constructs like PP/broadcasting. still occasionally useful though, so it's provided for backwards compatibility.
for $i (listindices $x) {
# Do something on each value...
}
π set π
sets a single value inside an ndarray.
set $ndarray, @position, $value
@position is a coordinate list, of size equal to the number of dimensions in the ndarray. occasionally useful, mainly provided for backwards compatibility since it's been superseded by the use of slice and the assignment operator ".=". periodt.
pdl> $x = sequence 3,4
pdl> set $x, 2,1,99
pdl> p $x
[
[ 0 1 2]
[ 3 4 99]
[ 6 7 8]
[ 9 10 11]
]
β at β
returns a single value inside an ndarray as a perl scalar. if the ndarray is a native complex value (cdouble, cfloat), it will be a PDL::Complex::Overloads object. fancy.
$z = at($ndarray, @position); $z=$ndarray->at(@position);
@position is a coordinate list, of size equal to the number of dimensions in the ndarray. occasionally useful in a general context, and quite useful inside PDL internals.
pdl> $x = sequence 3,4
pdl> p $x->at(1,2)
7
at converts any bad values into the string 'BAD'.
π
sclr π
returns a single value from an ndarray as a scalar, ignoring whether it's bad.
$val = $x(10)->sclr;
$val = sclr inner($x,$y);
the "sclr" method is useful for turning a single-element ndarray into a normal Perl scalar. its main glow-up over using "at" for this is that you don't need to worry about whether the ndarray is 0D, 1D, or higher dimensional. with "at" you have to supply the correct number of zeroes, e.g.
$x = sequence(10);
$y = $x->slice('4');
print $y->sclr; # no problem
print $y->at(); # error: needs at least one zero
lowkey why sclr is the move. π«Ά
π sclr
sclr is what you reach for when you need a real live Perl scalar and not a one-element ndarray. Classic. But ok bestie, listen: as of 2.064, if you feed it a multielement ndarray, it will throw an exception. It is not here to babysit you. π
π± cat
cat β concatenate ndarrays to N+1 dimensional ndarray. It's giving very much "stack these up for me". π₯
You hand it a list of N ndarrays of same shape as the argument, and it hands you back a single ndarray of dimension N+1. Slay.
pdl> $x = cat ones(3,3),zeroes(3,3),rvals(3,3); p $x
[
[
[1 1 1]
[1 1 1]
[1 1 1]
]
[
[0 0 0]
[0 0 0]
[0 0 0]
]
[
[1 1 1]
[1 0 1]
[1 1 1]
]
]
The output ndarray is set bad if any input ndarrays have their bad flag set. So it's contagious, basically. π
Similar functions include append, which appends only two ndarrays along their first dimension, and glue, which can append more than two ndarrays along an arbitrary dimension.
Also consider the generic constructor pdl, which can handle ndarrays of different sizes (with zero-padding), and will return an ndarray of type 'double' by default, but may be considerably faster (up to 10x) than cat. π
πΆ dog
dog β the opposite of cat :). Split N dim ndarray to list of N-1 dim ndarrays. Yeah it's a reverse cat, we love a symmetrical queen. β¨
You give it a single N-dimensional ndarray and it splits it into a list of N-1 dimensional ndarrays. The breakup is done along the last dimension. And ngl, note the dataflowed connection is still preserved by default, like:
pdl> $p = ones 3,3,3
pdl> ($x,$y,$c) = dog $p
pdl> $y++; p $p
[
[
[1 1 1]
[1 1 1]
[1 1 1]
]
[
[2 2 2]
[2 2 2]
[2 2 2]
]
[
[1 1 1]
[1 1 1]
[1 1 1]
]
]
Break => 1β Break dataflow connection (new copy)
The output ndarrays are set bad if the original ndarray has its bad flag set.
π«Ά gethdr
Retrieve header information from an ndarray.
$pdl=rfits('file.fits');
$h=$pdl->gethdr;
print "Number of pixels in the X-direction=$$h{NAXIS1}\n";
The gethdr function retrieves whatever header information is contained within an ndarray. The header can be set with sethdr and is always a hash reference or undef.
gethdr returns undef if the ndarray has not yet had a header defined β compare with hdr and fhdr, which are guaranteed to return a defined value. No stress, no undef jumpscare. π§
Note that gethdr() works by reference: you can modify the header in-place once it has been retrieved:
$x = rfits($filename);
$xh = $x->gethdr();
$xh->{FILENAME} = $filename;
It is also important to realise that in most cases the header is not automatically copied when you copy the ndarray. See hdrcpy to enable automatic header copying. Yeah, it'll ghost your header. π
Here's another example: a wrapper around rcols that allows your ndarray to remember the file it was read from and the columns could be easily written (here assuming that no regexp is needed, extensions are left as an exercise for the reader)
sub ext_rcols {
my ($file, @columns)=@_;
my $header={};
$$header{File}=$file;
$$header{Columns}=\@columns;
@ndarrays=rcols $file, @columns;
foreach (@ndarrays) { $_->sethdr($header); }
return @ndarrays;
}
π hdr
Retrieve or set header information from an ndarray.
$pdl->hdr->{CDELT1} = 1;
The hdr function allows convenient access to the header of a ndarray. Unlike gethdr it is guaranteed to return a defined value, so you can use it in a hash dereference like in the example. If the header does not yet exist, it gets autogenerated as an empty hash. It literally makes one for you. Iconic. π
Note that this is usually β but not always β What You Want. If you want to use a tied Astro::FITS::Header hash, for example, you should either construct it yourself and use sethdr to put it into the ndarray, or use fhdr instead. (Note that you should be able to write out the FITS file successfully regardless of whether your PDL has a tied FITS header object or a vanilla hash).
πΈ fhdr
Retrieve or set FITS header information from an ndarray.
$pdl->fhdr->{CDELT1} = 1;
The fhdr function allows convenient access to the header of a ndarray. Unlike gethdr it is guaranteed to return a defined value, so you can use it in a hash dereference like in the example. If the header does not yet exist, it gets autogenerated as a tied Astro::FITS::Header hash.
Astro::FITS::Header tied hashes are better at matching the behavior of FITS headers than regular hashes. In particular, the hash keys are CAsE INsEnSItiVE, unlike normal hash keys. See Astro::FITS::Header for details.
If you do not have Astro::FITS::Header installed, you get back a normal hash instead of a tied object. F in the chat. π«Ά
π sethdr
Set header information of an ndarray.
$pdl = zeroes(100,100);
$h = {NAXIS=>2, NAXIS1=>100, NAXIS=>100, COMMENT=>"Sample FITS-style header"};
# add a FILENAME field to the header
$$h{FILENAME} = 'file.fits';
$pdl->sethdr( $h );
The sethdr function sets the header information for an ndarray. You must feed in a hash ref or undef, and the header field of the PDL is set to be a new ref to the same hash (or undefined).
The hash ref requirement is a speed bump put in place since the normal use of headers is to store fits header information and the like. Of course, if you want you can hang whatever ugly old data structure you want off of the header, but that makes life more complex. Live your truth bestie but it's not recommended. π
Remember that the hash is not copied β the header is made into a ref that points to the same underlying data. To get a real copy without making any assumptions about the underlying data structure, you can use one of the following:
use PDL::IO::Dumper;
$pdl->sethdr( deep_copy($h) );
(which is slow but general), or
$pdl->sethdr( PDL::_hdr_copy($h) )
(which uses the built-in sleazy deep copier), or (if you know that all the elements happen to be scalars):
{ my %a = %$h;
$pdl->sethdr(\%a);
}
which is considerably faster but just copies the top level. Pick your poison, queen. π
The sethdr function must be given a hash reference or undef. For further information on the header, see gethdr, hdr, fhdr and hdrcpy.
π¦ hdrcpy
Switch on/off/examine automatic header copying.
print "hdrs will be copied" if $x->hdrcpy;
$x->hdrcpy(1); # switch on automatic header copying
$y = $x->sumover; # and $y will inherit $x's hdr
$x->hdrcpy(0); # and now make $x non-infectious again
hdrcpy without an argument just returns the current setting of the flag. See also hcpy which returns its PDL argument (and so is useful in method-call pipelines).
Normally, the optional header of an ndarray is not copied automatically in pdl operations. Switching on the hdrcpy flag using the hdrcpy method will enable automatic hdr copying. Note that an actual deep copy gets made, which is rather processor-inefficient β so avoid using header copying in tight loops! You heard her. Don't do it. π
Most PDLs have the hdrcpy flag cleared by default; however, some routines (notably rfits) set it by default where that makes more sense.
The hdrcpy flag is viral: if you set it for a PDL, then derived PDLs will get copies of the header and will also have their hdrcpy flags set. For example:
$x = xvals(50,50);
$x->hdrcpy(1);
$x->hdr->{FOO} = "bar";
$y = $x++;
$c = $y++;
print $y->hdr->{FOO}, " - ", $c->hdr->{FOO}, "\n";
$y->hdr->{FOO} = "baz";
print $x->hdr->{FOO}, " - ", $y->hdr->{FOO}, " - ", $c->hdr->{FOO}, "\n";
will print:
bar - bar
bar - baz - bar
Performing an operation in which more than one PDL has its hdrcpy flag causes the resulting PDL to take the header of the first PDL:
($x,$y) = sequence(5,2)->dog;
$x->hdrcpy(1); $y->hdrcpy(1);
$x->hdr->{foo} = 'a';
$y->hdr->{foo} = 'b';
print (($x+$y)->hdr->{foo} , ($y+$x)->hdr->{foo});
will print:
a b
π hcpy
Switch on/off automatic header copying, with PDL pass-through.
$x = rfits('foo.fits')->hcpy(0);
$x = rfits('foo.fits')->hcpy(1);
hcpy sets or clears the hdrcpy flag of a PDL, and returns the PDL itself. That makes it convenient for inline use in expressions. Chainable queen. π
β online_cpus
Returns the number of available processors cores. Used to set the number of threads with set_autopthread_targ if $ENV{PDL_AUTOPTHREAD_TARG} is not set.
π₯ set_autopthread_targ
Set the target number of processor threads (pthreads) for multi-threaded processing.
set_autopthread_targ($num_pthreads);
$num_pthreads is the target number of pthreads the auto-pthread process will try to achieve.
See PDL::ParallelCPU for an overview of the auto-pthread process.
# Example turning on auto-pthreading for a target of 2 pthreads and for functions involving
# PDLs with greater than 1M elements
set_autopthread_targ(2);
set_autopthread_size(1);
# Execute a pdl function, processing will split into two pthreads
$x = minimum($y);
# Get the actual number of pthreads that were run.
$actual_pthread = get_autopthread_actual();
π§ get_autopthread_targ
Get the current target number of processor threads (pthreads) for multi-threaded processing.
$num_pthreads = get_autopthread_targ();
$num_pthreads is the target number of pthreads the auto-pthread process will try to achieve.
See PDL::ParallelCPU for an overview of the auto-pthread process.
π get_autopthread_actual
Get the actual number of pthreads executed for the last pdl processing function.
$autopthread_actual = get_autopthread_actual();
$autopthread_actual is the actual number of pthreads executed for the last pdl processing function.
See PDL::ParallelCPU for an overview of the auto-pthread process.
π get_autopthread_dim
Get the actual dimension on which pthreads were used for the last pdl processing function.
$autopthread_dim = get_autopthread_dim();
$autopthread_dim is the actual dimension on which pthreads were used for the last pdl processing function.
See PDL::ParallelCPU for an overview of the auto-pthread process.
π set_autopthread_size
Set the minimum size (in M-elements or 2^20 elements) of the largest PDL involved in a function where auto-pthreading will be performed. For small PDLs, it probably isn't worth starting multiple pthreads, so this function is used to define a minimum threshold where auto-pthreading won't be attempted.
set_autopthread_size($size);
$size is the mimumum size, in M-elements or 2^20 elements (approx 1e6 elements) for the largest PDL involved in a function.
See PDL::ParallelCPU for an overview of the auto-pthread process.
# Example turning on auto-pthreading for a target of 2 pthreads and for functions involving
# PDLs with greater than 1M elements
set_autopthread_targ(2);
set_autopthread_size(1);
# Execute a pdl function, processing will split into two pthreads as long as
# one of the pdl-threaded dimensions is at least 2.
$x = minimum($y);
# Get the actual number of pthreads that were run.
$actual_pthread = get_autopthread_actual();
π get_autopthread_size π
Bestie this one is literally just a peek behind the curtain β it hands you back whatever the current autopthread_size setting is π
$autopthread_size = get_autopthread_size();
So like, what even is $autopthread_size? It's the minimum size limit that has to be cleared before auto_pthreading will even bother happening β measured in M-elements, or 2^20 elements (that's roughly 1e6 elements, ngl) of the largest PDL that's involved in the function. No size, no threading. That's the vibe check π«Ά
If you wanna actually understand the whole auto-pthread saga, go read PDL::ParallelCPU for the full overview of how the auto-pthread process works β¨
π AUTHOR π
Copyright (C) Karl Glazebrook (kgb@aaoepp.aao.gov.au), Tuomas J. Lukka (lukka@husc.harvard.edu) and Christian Soeller (c.soeller@auckland.ac.nz) 1997. Modified, Craig DeForest (deforest@boulder.swri.edu) 2002. All rights reserved. There is no warranty β fr fr, none, don't come for them π You are allowed to redistribute this software / documentation under certain conditions, and the way to find out exactly which conditions is to look at the file COPYING in the PDL distribution π If this file ever gets separated from the PDL distribution, the copyright notice should be included in the file. Keep the whole thing together, it's giving family, periodt π
and that's the whole page, bestie!! πΈπ¦β¨
This little beauty is from perl v5.42.3, dated 2026-08-20, and it lives at PDL::Core(3pm) β go forth and vectorize responsibly πππ
π¦ where this page comes from
- ubuntu stonking: pdl 1:2.106-1build1 Β· Artistic-1.0-Perl OR GPL-1.0-or-later
- π girlified by deepseek-ai/DeepSeek-V4.1-Flash on : a language model's rewrite of the original, under its terms