PDL#

📦 stdpdl

PDL - the Perl Data Language: fast, vectorised, multidimensional arrays for scientific and bulk numeric work.

use PDL;
my $x = sequence(3, 2);                        # 3 columns, 2 rows: 0 .. 5
print +($x * 2 + 1)->flat, "\n";                # [1 3 5 7 9 11]
print $x->sumover, " ", $x->max, " ", $x->type, "\n";    # [3 12] 5 double
my $col = $x->slice("(1),:");                 # a view of column 1
$col .= -1;
print $x->flat, " ", $x->where($x > 3), "\n";            # [0 -1 2 3 -1 5] [5]
print float(1.5) + byte(2), " ", (float(1.5) + byte(2))->type, "\n";   # 3.5 float

An ndarray is a blessed scalar holding a dense, typed, multidimensional block of numbers. Operators and functions apply to the whole block at once - $x * 2 + 1 works on every element without a Perl loop - and slices such as $x->slice(...) are live views onto the parent’s data rather than copies, so writing through a view writes to the parent. Functions broadcast: an operation on one dimension runs over all the others, and operands of different shapes are matched dimension by dimension.

The element type is chosen per ndarray. The constructors named after each type - sbyte, byte, short, ushort, long, ulong, indx, longlong, ulonglong, float, double, ldouble, cfloat, cdouble, cldouble - both build an ndarray of that type and, called with no arguments, name the type itself.

use PDL loads and imports PDL::Core (constructors, dimensions, types), PDL::Ops (the operators), PDL::Primitive (products, selecting, searching, interpolation), PDL::Ufunc (reductions and sorting), PDL::Basic (sequences and coordinates), PDL::Slices (views and indexing), PDL::Bad (bad values), PDL::MatrixOps (linear algebra), PDL::Math (mathematical functions), and the IO modules: PDL::IO::Misc (columns of text, byte swapping), PDL::IO::FITS, PDL::IO::Pic (images, through PDL::IO::Pnm and PDL::ImageRGB) and PDL::IO::Storable. PDL::Lite and PDL::LiteF load fewer; PDL::FFT, PDL::Image2D, PDL::ImageND, PDL::Transform and PDL::Compression are loaded on their own.

This is PDL 2.106: its Perl is upstream’s, unchanged, and its compiled kernels are PDL’s own C, run by pperl’s engine. The XS that binds them is pperl’s. use PDL needs pperl built with PDL (the pdl feature).

As upstream, an operation on large ndarrays (by default from 1 Mi elements) is split across threads: set_autopthread_targ and set_autopthread_size in PDL::Core control it. The threads are pperl’s own pool, sized by --threads; --no-parallel keeps PDL on one thread.

Differences from upstream#

Where perl5 with PDL fails, pperl does better:

  • broadcast with a dimension the ndarray does not have croaks “Error in broadcastI:Invalid dim N (ndarray has M dims)” when first computed. Upstream reads outside the dimension array: memory before it for a negative dim (a garbage result), and for broadcast(99) it runs out of memory (t/81-xs-native/PDL/380-broadcast-methods.t).

Not there yet:

  • isnan (PDL::Bad) and casinh (PDL::Math), both new in PDL 2.105.

t/81-xs-native/PDL/838-open-differences.t holds one case for every difference from upstream, open or closed; a new one goes there first.

Modules#

  • PDL::Bad - Bad values: PDL’s marker for missing data, and the functions that find, make and replace them.

  • PDL::Basic - PDL’s basic constructors: counting sequences, coordinate values along a dimension, evenly spaced ranges, distances from a centre and histograms.

  • PDL::Complex

  • PDL::Compression - Rice compression of integer ndarrays, as FITS files use it.

  • PDL::Constants - basic compile time constants for PDL

  • PDL::Core - Build ndarrays, ask them about themselves, and convert between types.

  • PDL::Exporter - PDL export control

  • PDL::FFT - Fast Fourier transforms of PDL’s ndarrays, in place, in one or more dimensions.

  • PDL::IO

  • PDL::Image2D - Two-dimensional image processing: median filters, polygon filling, connected components, rotation and warping.

  • PDL::ImageND - Image processing in any number of dimensions: convolution, rebinning, interpolation, circular masks, contours and graph layout forces.

  • PDL::ImageRGB - Utility functions for RGB image data: palette quantisation, palette lookup, conversion to grey, and scaling to bytes.

  • PDL::Lite - PDL with methods only: the core modules loaded, four names imported.

  • PDL::LiteF - The core PDL modules, with their functions imported.

  • PDL::Math - PDL’s mathematical functions: trigonometric and hyperbolic, rounding, error and Bessel functions, log gamma, complex square roots, logarithms and inverses, and polynomials.

  • PDL::MatrixOps - Linear algebra on PDL’s ndarrays: determinants, inverses, LU, singular value and eigen decompositions, linear systems, triangular storage.

  • PDL::Ops - PDL’s operators: arithmetic, comparison, bitwise and the unary functions, element by element, as the functions behind Perl’s operators on ndarrays.

  • PDL::Options - simplifies option passing by hash in PerlDL

  • PDL::PP

  • PDL::Primitive - PDL’s primitives: products, selecting by a mask, clipping, searching sorted data, interpolation, set operations on vectors, statistics.

  • PDL::Slices - Take pieces of an ndarray, and rearrange the pieces you take.

  • PDL::Trans

  • PDL::Transform - Coordinate transformations as objects, and the resampling of images through them.

  • PDL::Types - define fundamental PDL Datatypes

  • PDL::Ufunc - Reductions of PDL’s ndarrays: sums, products, means, extrema, medians, percentiles, logical and bitwise folds, running sums and products, and sorting.

Functions#

Contours and paths#

contour_segments#

($segs, $cnt) = contour_segments($c, $data, $points) - the line segments of the contour of $data at the level $c, in the coordinates $points gives each data point; $cnt is the index of the last segment end in $segs.

contour_polylines#

($pathendindex, $paths) = contour_polylines($c, $data, $points) - the contour of $data at the level $c as polylines: $paths holds the points and $pathendindex the index of each polyline’s last point, -1 after the last.

path_join#

($pathendindex, $paths) = path_join($edges, $nvertices, $directed) - the edges $edges (pairs of vertex numbers) joined into paths: $paths holds the vertices and $pathendindex the index of each path’s last vertex. $directed is true by default.

Graph layout#

combcoords#

combcoords($x, $y, $z) - the three coordinates packed into one float ndarray with a leading dimension of 3.

repulse#

repulse($coords, $boxsize, $dmult, $a, $b, $c, $d) - the repulsive force on each point of $coords from the points near it, for a spring-embedded graph layout. The points are sorted into boxes of side $boxsize, $dmult of them along each of three dimensions, and only points in neighbouring boxes interact. With s = 1 / (r + $d) for two points at distance r, each pushes the other along their difference vector, scaled by $c * sqrt(s) + $b * s + $a * s**2.

attract#

attract($coords, $from, $to, $strength, $m, $ms) - the attractive force on each point of $coords from the links $from to $to of the given $strength, for a spring-embedded graph layout.

First-dimension reductions#

sumover#

sumover($a) - the sum along the first dimension.

prodover#

prodover($a) - the product along the first dimension.

dprodover#

dprodover($a) - the product along the first dimension, computed in double precision.

dsumover#

dsumover($a) - the sum along the first dimension, computed in double precision.

average#

average($a) - the mean along the first dimension.

daverage#

daverage($a) - the mean along the first dimension, computed in double precision.

caverage#

caverage($a) - the mean along the first dimension as a complex value (cfloat for float input, cdouble otherwise); cavgover is the same function.

intover#

intover($a) - the integral along the first dimension, for a point spacing of one: scale the result by the real spacing.

magnover#

magnover($a) - the Euclidean length along the first dimension, sqrt(sumover($a ** 2)).

minimum#

minimum($a) - the smallest value along the first dimension.

minimum_ind#

minimum_ind($a) - the position of the smallest value along the first dimension.

maximum#

maximum($a) - the largest value along the first dimension.

maximum_ind#

maximum_ind($a) - the position of the largest value along the first dimension.

medover#

medover($a) - the median along the first dimension; for an even count, the mean of the two middle values.

oddmedover#

oddmedover($a) - the median along the first dimension; for an even count, the lower of the two middle values.

modeover#

modeover($data) - the most frequent value along the first dimension. Meant for integer types: floating-point values are demoted to integers first.

minmaximum#

minmaximum($x) - ($min, $max, $min_ind, $max_ind) along the first dimension, broadcasting over the rest.

pctover#

pctover($pdl, $percentile) - the given percentile along the first dimension, broadcasting over the others. $percentile is between 0.0 and 1.0; values outside are clipped to that range. Between data points the result is interpolated, by the variant Microsoft Excel uses and NIST recommends. Bad values are skipped.

oddpctover#

oddpctover($pdl, $percentile) - like pctover, but when the percentile falls between data points the result is the nearest data value rather than an interpolation.

Logical and bitwise reductions#

andover#

andover($a) - 1 where every value along the first dimension is true, else 0.

orover#

orover($a) - 1 where any value along the first dimension is true, else 0.

xorover#

xorover($a) - the logical exclusive or along the first dimension.

zcover#

zcover($a) - 1 where every value along the first dimension is zero, else 0.

bandover#

bandover($a) - the bitwise and along the first dimension (integer types).

borover#

borover($a) - the bitwise or along the first dimension (integer types).

bxorover#

bxorover($a) - the bitwise exclusive or along the first dimension (integer types).

firstnonzeroover#

firstnonzeroover($a) - the first non-zero value along the first dimension, or 0.

zcheck#

$pdl->zcheck - 1 if every value is zero, else 0.

and#

$pdl->and - 1 if every value is true, else 0.

or#

$pdl->or - 1 if any value is true, else 0.

xorall#

$pdl->xorall - the logical exclusive or of all the values.

band#

$pdl->band - the bitwise and of all the values.

bor#

$pdl->bor - the bitwise or of all the values.

bxor#

$pdl->bxor - the bitwise exclusive or of all the values.

Cumulative operations#

cumusumover#

cumusumover($a) - the running sum along the first dimension.

dcumusumover#

dcumusumover($a) - the running sum along the first dimension, in double precision.

cumuprodover#

cumuprodover($a) - the running product along the first dimension.

dcumuprodover#

dcumuprodover($a) - the running product along the first dimension, in double precision.

numdiff#

numdiff($x) - the differences of neighbouring values along the first dimension, the first value kept: the inverse of cumusumover. Works in place.

diffcentred#

diffcentred($a) - the centred difference along the first dimension, ($a[i+1] - $a[i-1]) / 2, wrapping around at the ends. partial($f, $dim) takes it along dimension $dim; with { dir => 'f' } or 'b' it takes the forward or backward difference instead.

diff2#

diff2($a) - the differences of neighbouring values along the first dimension, $a[i+1] - $a[i]: one element shorter than $a.

Sorting#

qsort#

qsort($a) - the values sorted along the first dimension, bad values last. Works in place.

qsorti#

qsorti($a) - the indices that sort the values along the first dimension.

qsortvec#

qsortvec($a) - a list of vectors sorted lexicographically: each vector runs along the first dimension, the list along the second. Works in place.

qsortveci#

qsortveci($a) - the indices that would sort a list of vectors lexicographically, as qsortvec does.

Whole-array reductions#

avg#

$pdl->avg - the mean of all the values, as a 0-dim ndarray.

sum#

$pdl->sum - the sum of all the values.

prod#

$pdl->prod - the product of all the values.

davg#

$pdl->davg - the mean of all the values, in double precision.

dsum#

$pdl->dsum - the sum of all the values, in double precision.

dprod#

$pdl->dprod - the product of all the values, in double precision.

min#

$pdl->min - the smallest of all the values.

max#

$pdl->max - the largest of all the values.

median#

$pdl->median - the median of all the values.

oddmedian#

$pdl->oddmedian - the median of all the values; for an even count, the lower middle value.

mode#

$pdl->mode - the most frequent of all the values.

pct#

pct($pdl, $p) - the given percentile of all the values of $pdl, whatever its dimensions, as a 0-dimensional PDL. Interpolated between data points, as pctover; bad values are skipped.

oddpct#

oddpct($pdl, $p) - like pct, but when the percentile falls between data points the result is the nearest data value.

Making values bad#

setinftobad#

$pdl->setinftobad - infinities made bad values; works in place.

setnonfinitetobad#

$pdl->setnonfinitetobad - infinities and NaNs made bad values; works in place.

setnantobad#

$pdl->setnantobad - NaNs made bad values; works in place.

setbadif#

setbadif($a, $mask) - $a with the elements bad where $mask is true.

copybad#

copybad($a, $mask) - $a with the elements bad where $mask is bad; works in place.

setvaltobad#

setvaltobad($pdl, $val) - elements equal to $val made bad; works in place.

Finding bad values#

isbad#

isbad($a) - 1 where the element is bad, 0 elsewhere.

isgood#

isgood($a) - 1 where the element is good, 0 elsewhere.

nbadover#

nbadover($a) - the number of bad elements along the first dimension.

ngoodover#

ngoodover($a) - the number of good elements along the first dimension.

Replacing bad values#

setbadtonan#

$pdl->setbadtonan - bad values made NaN; works in place.

locf#

locf($a) - each bad value replaced by the last good one before it.

setbadtoval#

setbadtoval($pdl, $val) - bad values replaced with $val; works in place.

badmask#

badmask($a, $b) - $a with each bad value replaced by $b’s; works in place.

Indexing#

index2d#

index2d($a, $inda, $indb) - the elements of the 2-D $a at the coordinate pairs ($inda, $indb), as a child linked both ways.

index1d#

index1d($a, $ind): the elements of $a along dim 0 at each of the indices in $ind, as a child linked both ways.

rangeb#

$source->rangeb($index, $size, $boundary) - the kernel under range: the elements, or with $size the rectangular blocks, of $source at the coordinates in $index (its first dimension runs over the dimensions of $source), as a child linked both ways. $boundary says what lies outside $source: forbid (the default), truncate, extend, periodic or mirror, one for all dimensions or one each. range is the same with optional arguments, and indexND is range without a size.

Run-length encoding#

rlevec#

($counts, $rows) = rlevec($c) - run-length encode the rows of $c: how often each row repeats, and the rows that start each run.

rleseq#

($counts, $starts) = rleseq($c) - run-length encode $c as runs of consecutive values: the length of each run and the value it starts at.

Views#

rotate#

rotate($pdl, $shift)

make_physdims#

Force the ndarray’s dimensions to be worked out, and return it.

xchg#

$pdl->xchg($n1, $n2) - a view with dimensions $n1 and $n2 exchanged.

mv#

$pdl->mv($n1, $n2) - a view with dimension $n1 moved to position $n2, the others shifted.

lags#

$pdl->lags($nthdim, $step, $nlags) - a view of lagged copies of one dimension, one per lag.

splitdim#

$pdl->splitdim($nthdim, $nsp) - a view with dimension $nthdim split into two, the first of size $nsp.

unbroadcast#

$pdl->unbroadcast($atind) - a view with the broadcast dimensions moved back to position $atind.

broadcastI#

$pdl->broadcastI($id, [@dims]) - a view with @dims made broadcast dimensions of group $id.

Decompositions and solving#

svd#

($u, $s, $v) = svd($a) - singular value decomposition a = u * diag(s) * transpose(v); svd($a, 1) for the full decomposition.

simq#

($x, $ips) = simq($a, $b, $flag) - solve the linear system a x = b by LU decomposition; $a is replaced by its decomposition.

Triangular storage#

squaretotri#

Convert the lower triangle of a square matrix to triangular vector storage: squaretotri($a) or squaretotri($a, $b).

tritosquare#

Convert triangular vector storage to the lower triangle of a square matrix; the upper half of the output is left alone.

tricpy#

tricpy($A, $uplo = 0, $C): copy a triangular part of $A - uplo -1 strict upper, 0 upper, 1 lower, 2 strict lower.

Building matrices#

mstack#

Stack two matrices along dim 1: x(n,m) and y(n,p) give out(n,m+p).

augment#

Join two ndarrays along dim 0: x(n) and y(p) give out(n+p).

Complex numbers#

re#

$z->re - the real part of each complex element; assigning to it writes back into $z.

im#

$z->im - the imaginary part of each complex element; assigning to it writes back into $z.

carg#

carg($z) - the polar angle of each complex element, real.

conj#

conj($z) - the complex conjugate; $z->inplace->conj works.

czip#

czip($re, $im) - a complex ndarray from its real and imaginary parts.

Arithmetic#

plus#

plus($a, $b) - $a + $b, element by element.

minus#

minus($a, $b) - $a - $b.

mult#

mult($a, $b) - $a * $b.

divide#

divide($a, $b) - $a / $b.

power#

power($a, $b) - $a ** $b.

modulo#

modulo($a, $b) - $a % $b, with the sign of $b as Perl’s %.

atan2#

atan2($a, $b) - the angle of the point ($b, $a), element by element.

ipow#

ipow($a, $b) - $a to the integer power $b, by repeated multiplication.

pow#

pow($a, $b) - $a to the power $b, element by element, the result in the input type (pow(byte(2), 3) is a byte); $a->inplace->pow($b) works in place.

Comparison#

eq#

eq($a, $b) - $a == $b: 1 or 0 per element.

ne#

ne($a, $b) - $a != $b.

gt#

gt($a, $b) - $a > $b.

lt#

lt($a, $b) - $a < $b.

ge#

ge($a, $b) - $a >= $b.

le#

le($a, $b) - $a <= $b.

spaceship#

spaceship($a, $b) - $a <=> $b: -1, 0 or 1 per element.

in#

in($a, $b) - for each element of $a, whether it occurs in $b.

approx_artol#

approx_artol($got, $expected, $atol, $rtol) - 1 where $got is within $atol of $expected, or within $rtol relative to it, else 0 ($atol 1e-6 and $rtol 0 by default). Two NaNs, or two bad values, are approximately equal.

Bitwise#

and2#

and2($a, $b) - $a & $b, bitwise.

or2#

or2($a, $b) - $a | $b, bitwise.

xor#

xor($a, $b) - $a ^ $b, bitwise.

shiftleft#

shiftleft($a, $b) - $a << $b.

shiftright#

shiftright($a, $b) - $a >> $b.

bitnot#

bitnot($a) - bitwise negation.

Unary functions#

sqrt#

sqrt($a) - the element-wise square root.

abs2#

abs2($a) - the squared absolute value, real.

not#

not($a) - logical negation: 1 where $a is 0, else 0.

sin#

sin($a), element-wise.

cos#

cos($a), element-wise.

exp#

exp($a), element-wise.

log#

log($a), element-wise natural logarithm.

Assignment#

assgn#

assgn($a, $b) - copies $a into $b, broadcasting, and returns $b when it was not given: the operation behind .=. Into a view the copy reaches the parent, as every write through a view does.

Miscellaneous#

hclip#

hclip($a, $b) - $a with every value above $b replaced by $b: $b is the upper bound. Works in place.

lclip#

lclip($a, $b) - $a with every value below $b replaced by $b: $b is the lower bound. Works in place.

axisvalues#

$pdl->inplace->axisvalues - each element set to its index along the first dimension; broadcasts over the rest.

indadd#

indadd($input, $ind, $sum) – broadcasting index-add.

broadcastids#

$pdl->broadcastids - where each broadcast group starts among the dimensions, in list context; how many ids there are, in scalar context.

flags#

$pdl->flags - the names of the state flags set on the ndarray, such as PDL_ALLOCATED or PDL_PARENTDIMSCHANGED. For debugging.

dump#

$pdl->dump - print the engine’s view of the ndarray to standard output: its state flags, dimensions, data and the transformations attached to it. For debugging; PDL::Core::pdump returns much the same as a string.

broadcastover_n#

PDL::broadcastover_n($code, $pdl1, ...) - call $code once per element of the ndarrays broadcast against each other. Each call gets the number of the outermost dimension that just changed, then the current element of each ndarray as a plain number.

broadcastover#

PDL::broadcastover($code, \@realdims, \@creating, $nothers, $pdl1, ..., @others) - call $code once per broadcast step, with a view of each ndarray that has the dimensions named in \@realdims, followed by the $nothers trailing arguments. An ndarray whose \@creating flag is set is created to fit; its dimensions follow the flags in \@creating. This is what broadcast_define builds its subs on.

Vectors#

eqvec#

eqvec($a, $b) - whether two vectors are equal.

enumvec#

enumvec($v) - number each vector by its position within its run of equal vectors.

enumvecg#

enumvecg($v) - number each vector by the group of equal vectors it belongs to.

vsearchvec#

vsearchvec($find, $which) - binary search of vectors in a sorted list of vectors.

vcos#

vcos($a, $b) - the cosine of the angle between each vector of $a (its rows along the second dimension) and the vector $b.

cmpvec#

cmpvec($a, $b) - lexicographic comparison of two vectors: -1, 0 or 1.

Searching#

vsearch_sample#

vsearch_sample($vals, $x) - where each value falls in the sorted $x, as vsearch with mode => 'sample'.

vsearch_insert_leftmost#

vsearch_insert_leftmost($vals, $x) - the leftmost insertion point of each value in the sorted $x.

vsearch_insert_rightmost#

vsearch_insert_rightmost($vals, $x) - the rightmost insertion point of each value in the sorted $x.

vsearch_match#

vsearch_match($vals, $x) - the index of each value in the sorted $x, or a negative insertion point where it is missing.

vsearch_bin_inclusive#

vsearch_bin_inclusive($vals, $x) - the bin of each value, bins closed at their lower edge.

vsearch_bin_exclusive#

vsearch_bin_exclusive($vals, $x) - the bin of each value, bins open at their lower edge.

Interpolation#

pchip_chim#

pchip_chim($x, $f) - derivatives for a monotone piecewise cubic Hermite interpolant.

pchip_chsp#

pchip_chsp($ic, $vc, $x, $f) - derivatives for a cubic spline interpolant.

pchip_chfd#

pchip_chfd($x, $f, $d, $xe) - the Hermite interpolant and its derivative at the points $xe.

pchip_chfe#

pchip_chfe($x, $f, $d, $xe) - the Hermite interpolant at the points $xe.

pchip_chia#

pchip_chia($x, $f, $d, $la, $lb) - the integral of the Hermite interpolant between two abscissae.

pchip_chid#

pchip_chid($x, $f, $d, $ia, $ib) - the integral of the Hermite interpolant between two data points.

pchip_chbs#

pchip_chbs($x, $f, $d, $knotyp) - the B-spline representation of the Hermite interpolant.

pchip_bvalu#

pchip_bvalu($t, $a, $ideriv, $x) - a B-spline or one of its derivatives at $x.

pchip_chic#

($d, $ierr) = pchip_chic($ic, $vc, $mflag, $x, $f) - the derivatives for a monotone piecewise cubic Hermite interpolant, with control over the end conditions (SLATEC PCHIC).

interpolate#

($yi, $err) = interpolate($xi, $x, $y) - linear interpolation of $y over $x at the positions $xi. $x must be monotonic. A position outside $x is extrapolated from the two nearest knots, and its $err is 1.

Products#

inner#

inner($a, $b) – inner (dot) product along the first dimension.

outer#

outer($a, $b) - the outer product: c(n,m) = a(n) * b(m).

norm#

norm($vec) - each vector along the first dimension scaled to unit length. Works in place.

inner2#

inner2($a, $b, $c) - the inner product of a vector, a matrix and a vector: $a x $b x $c.

inner2d#

inner2d($a, $b) - the inner product over the first two dimensions: the sum of $a * $b over a 2-D slice.

inner2t#

inner2t($a, $b, $c) - the matrix product $a x $b x $c for matrices, through a temporary.

innerwt#

innerwt($a, $b, $c) - the weighted inner product: the sum of $a * $b * $c along the first dimension.

crossp#

crossp($a, $b) - the cross product of two 3-vectors; broadcasts over further dimensions.

Selecting#

whichover#

whichover($mask) - along the first dimension, the positions of the true elements first and -1 for the rest, broadcasting over the other dimensions. Works in place.

index#

index($a, $ind): the elements of $a along dim 0 at $ind, broadcasting over the rest, as a child linked both ways - a write into it reaches $a.

Complex functions#

csqrt#

csqrt($z) - the square root, taking real input as complex.

clog#

clog($z) - the natural logarithm, taking real input as complex.

cacos#

cacos($z) - the inverse cosine, taking real input as complex.

casin#

casin($z) - the inverse sine, taking real input as complex.

cacosh#

cacosh($z) - the inverse hyperbolic cosine, taking real input as complex.

catanh#

catanh($z) - the inverse hyperbolic tangent, taking real input as complex.

csqrt_up#

csqrt_up($z) - the square root with its imaginary part non-negative.

Classification#

isfinite#

isfinite($pdl) - 1 where the element is finite (and good), 0 elsewhere, as an int ndarray.

Trigonometric and hyperbolic#

asin#

asin($a) - the arc sine, in radians.

acos#

acos($a) - the arc cosine, in radians.

atan#

atan($a) - the arc tangent, in radians.

tan#

tan($a) - the tangent.

sinh#

sinh($a) - the hyperbolic sine.

cosh#

cosh($a) - the hyperbolic cosine.

tanh#

tanh($a) - the hyperbolic tangent.

asinh#

asinh($a) - the inverse hyperbolic sine.

acosh#

acosh($a) - the inverse hyperbolic cosine.

atanh#

atanh($a) - the inverse hyperbolic tangent.

Rounding#

ceil#

ceil($a) - rounded up to an integer value.

floor#

floor($a) - rounded down to an integer value.

rint#

rint($a) - rounded to the nearest integer value, halves to even (C99 rint).

Special functions#

erf#

erf($a) - the error function.

erfc#

erfc($a) - the complementary error function, 1 - erf($a).

erfi#

erfi($a) - the inverse of the error function.

ndtri#

ndtri($a) - the inverse of the standard normal distribution function: ndtri(0.975) is 1.96.

bessj0#

bessj0($a) - the Bessel function of the first kind, order 0.

bessj1#

bessj1($a) - the Bessel function of the first kind, order 1.

bessy0#

bessy0($a) - the Bessel function of the second kind, order 0.

bessy1#

bessy1($a) - the Bessel function of the second kind, order 1.

lgamma#

lgamma($a) - the log of the absolute value of the gamma function, and its sign: ($l, $s) = lgamma($a).

bessjn#

bessjn($a, $n) - the Bessel function of the first kind of integer order $n.

bessyn#

bessyn($a, $n) - the Bessel function of the second kind of integer order $n.

Constructors#

pdl#

$class->pdl(...): $class->new(...).

topdl#

Core.xs topdl(klass, arg1, ...): arg1 itself when it is an object; otherwise klass->new(...) of all the arguments - several of them, a plain scalar or an array ref.

null#

null() - create a null (typeless, dimensionless) PDL placeholder.

new#

PDL->new(...) - an ndarray from a number, a list of numbers, a (nested) array ref, a Matlab-style string ("[1 2; 3 4]"), a Math::Complex, or another ndarray (copied); a leading PDL::Type object sets the type.

initialize#

$class->initialize: a new null ndarray blessed into $class (a class name, or the class of a reference). new calls it on the class it was invoked on, so a subclass - or a subclass’s own initialize - decides what My->new(...) gives back.

zeroes#

Core.xs new_from_specification(invoc, ...), ALIAS: PDL::zeroes = 1.

Also available as PDL::new_from_specification.

set_sv_to_null_pdl#

Turn an existing scalar into a null ndarray.

new_around_datasv#

PDL->new_around_datasv($address, $offset) - an ndarray whose data is the string of the Perl scalar at $address (0 + \$scalar), from byte $offset (default 0) on. The scalar is kept alive, not copied. The result still needs its type and dimensions:

new_around_pointer#

PDL->new_around_pointer($pointer, $nbytes) - an ndarray whose data is the $nbytes bytes of memory at $pointer, which it neither copies nor frees. The result still needs its type and dimensions.

Elements and data#

get_dataref#

Return a reference to the scalar holding the ndarray’s raw bytes.

upd_data#

Tell the ndarray that the scalar get_dataref returned was changed.

update_data_from#

Replace the ndarray’s contents with the bytes of a scalar.

at#

Return a single element of an ndarray as a plain Perl scalar.

set#

set($pdl, @indices, $value) - set the element at the given indices.

unpdl#

Return the ndarray as nested Perl arrayrefs, shape and all.

string#

string($pdl) - return the PDL’s string representation.

sclr#

sclr($pdl) - return the only element as a plain Perl scalar.

set_donttouchdata#

Declare that the ndarray’s storage belongs to someone else.

datasv_refcount#

Return how many references are held to the ndarray’s data scalar.

firstvals_nophys#

$pdl->firstvals_nophys - up to the first ten elements of the ndarray’s own data. Dies when it has none, as a view does.

Dimensions#

dims#

dims($pdl) - return the list of dimension sizes. Also aliased as shape().

getndims#

Return how many dimensions the ndarray has.

Also available as PDL::ndims.

nelem#

Return the total number of elements in the ndarray.

dim#

dim($pdl, $n) - return the size of dimension $n. A negative $n counts from the last dimension; one past the last dimension is 1.

Also available as PDL::getdim.

dimincs#

dimincs($pdl) - return the list of stride increments.

isnull#

isnull($pdl) - return 1 if the PDL is a null placeholder.

setdims#

Give an ndarray a new shape, in place.

nbytes#

nbytes($pdl) - return the number of bytes in the pdl’s data buffer.

nelem_nophys#

$pdl->nelem_nophys - the number of elements as currently recorded, without computing a pending view first.

dims_nophys#

$pdl->dims_nophys - the dimensions as currently recorded, without computing a pending view first. Always a list.

dimincs_nophys#

$pdl->dimincs_nophys - the step in elements along each dimension as currently recorded. Always a list.

broadcastids_nophys#

$pdl->broadcastids_nophys - the broadcast ids as currently recorded. Always a list.

getnbroadcastids#

$pdl->getnbroadcastids - how many broadcast ids the ndarray has.

getbroadcastid#

$pdl->getbroadcastid($n) - broadcast id number $n: the dimension where that broadcast group starts.

Parallel processing#

set_autopthread_targ#

set_autopthread_targ($n) - the number of threads an operation is split across, at most; 0 turns the splitting off. Returns $n.

get_autopthread_targ#

get_autopthread_targ() - the target set by set_autopthread_targ.

set_autopthread_size#

set_autopthread_size($n) - the size, in Mi elements of the largest ndarray, from which an operation is split across threads (default 1; PDL_AUTOPTHREAD_SIZE in the environment sets it when PDL loads). Returns $n.

get_autopthread_size#

get_autopthread_size() - the size set by set_autopthread_size.

get_autopthread_actual#

get_autopthread_actual() - how many threads the most recently set up operation was split across; 0 when it was not split.

get_autopthread_dim#

get_autopthread_dim() - the dimension the most recently set up operation was split along; -1 when it was not split.

add_threading_magic#

$pdl->add_threading_magic($dim, $nthreads) - have operations on this ndarray split dimension $dim across $nthreads threads, whatever the automatic setting would do.

remove_threading_magic#

$pdl->remove_threading_magic - undo add_threading_magic.

Dataflow and views#

inplace#

$pdl->inplace - mark the ndarray so that the next operation on it that can work in place writes its result into it; returns $pdl.

flowing#

Turn on dataflow, so ndarrays derived from this one track its changes.

sever#

Detach a view from its parent, keeping the values it has right now.

dog#

$pdl->dog - the ndarray as a list of views, one per element of its last dimension; $pdl->dog({Break => 1}) severs them from it.

readonly#

Mark the ndarray read-only and return it.

make_physical#

Give the ndarray data of its own - a view (slice, dice, …) gets its elements computed and stored - and return it.

has_vafftrans#

$pdl->has_vafftrans - 1 when the ndarray is a view that reads its data from another ndarray’s memory, 0 otherwise.

vaffine_from#

$pdl->vaffine_from - the address of the ndarray a view reads its data from. Dies when the ndarray is not such a view.

make_physvaffine#

$pdl->make_physvaffine - compute a view far enough that its elements can be read from its parent’s memory, without copying them. Returns the ndarray.

trans_parent#

$pdl->trans_parent - the transformation that produces this ndarray, a PDL::Trans object, or undef when it has none.

trans_children#

$pdl->trans_children - the transformations that read this ndarray, as PDL::Trans objects; in scalar context, how many there are.

bind#

$pdl->bind($code) - have $code called, without arguments, after the ndarray’s data changed. The calls are collected and made by the next PDL::dowhenidle().

dowhenidle#

PDL::dowhenidle() - call the subs bound with bind to ndarrays that changed since the last call.

Bad values#

badflag#

badflag($pdl, $flag?) - get or set the bad-value flag.

has_badvalue#

$pdl->has_badvalue - 1 when the ndarray has a bad value of its own instead of its type’s, 0 otherwise.

Types#

set_datatype#

Change the element type of an ndarray in place.

get_datatype#

get_datatype($pdl) - return the datatype as integer type code.

Headers#

sethdr#

$pdl->sethdr($hashref) - give the ndarray a header: any hash, such as the one rfits reads. sethdr(undef) removes it.

hdr#

$pdl->hdr - the header, a hash reference; an ndarray without one gets an empty header first.

gethdr#

$pdl->gethdr - the header, a hash reference, or undef when the ndarray has none.

hdrcpy#

Get or set whether the header travels with derived ndarrays.

Filtering#

box2d#

box2d($a, $wx, $wy, $edgezero) - each pixel replaced by the mean of the $wx by $wy box around it. The pixels nearer to the edge than half a box are set to 0 if $edgezero is true and copied otherwise.

patch2d#

patch2d($a, $bad) - $a with each pixel where $bad is true replaced by the mean of its good neighbours in the 3 by 3 box around it; a pixel with no good neighbour is kept.

patchbad2d#

patchbad2d($a) - $a with each bad value replaced by the mean of its good neighbours in the 3 by 3 box around it; one with no good neighbour stays bad.

Resampling#

bilin2d#

bilin2d($in, $out) - $in stretched to the size of $out by bilinear interpolation and added to $out, which must not be smaller.

rescale2d#

rescale2d($in, $out) - $in scaled to the size of $out, larger or smaller, each output pixel the area-weighted mean of the input it covers, and added to $out.

Other Functions#

rice_expand#

rice_expand($in, $len, $dim0, $blocksize?) - the rows rice_compress squeezed into $in, restored to $dim0 elements each.

cquant_c#

cquant_c($a, $b, $c, $psz) - the kernel under cquant: the palette image $b and the colour table $c (of $psz colours) for the RGB byte image $a.

wtstat#

wtstat($a, $wt, $avg, $deg) - the weighted moment of degree $deg of $a about $avg along the first dimension: the sum of $wt * ($a - $avg) ** $deg over the sum of $wt.

histogram#

histogram($data, $step, $min, $numbins) - the number of values of $data in each of $numbins bins of width $step starting at $min, along the first dimension. A value below the first bin counts in the first, one above the last in the last.

whistogram#

whistogram($data, $weight, $step, $min, $numbins) - as histogram, each value counting with its weight.

histogram2d#

histogram2d($a, $b, $stepa, $mina, $na, $stepb, $minb, $nb) - the two-dimensional histogram of the pairs ($a, $b).

whistogram2d#

whistogram2d($a, $b, $weight, $stepa, $mina, $na, $stepb, $minb, $nb) - as histogram2d, each pair counting with its weight.

t_spherical_inv#

t_spherical_inv($in, $origin, $angunit) - the kernel under the inverse of t_spherical: (longitude, latitude, radius) to Cartesian (x, y, z), the angles multiplied by $angunit (1 by default) to give radians. Works in place.

max2d_ind#

($val, $x, $y) = max2d_ind($img) - the largest value of an image and its position.

centroid2d#

($xcen, $ycen) = centroid2d($img, $x, $y, $box) - the centroid of the $box-wide square around ($x, $y).

ccNcompt#

ccNcompt($img, $con) - the connected components of an image, $con 4 or 8 for the neighbourhood, each numbered from 1.

rot2d#

rot2d($img, $angle, $bg, $aa) - a byte image turned by $angle degrees (-90 to 90), uncovered pixels set to $bg, antialiased when $aa is true.

pnminraw#

pnminraw($type, $im, $ms, $ns, $isbin, $fh) - read a raw PNM image of $ms by $ns pixels from $fh, bits ($isbin) or bytes, into $im.

pnminascii#

pnminascii($type, $im, $ms, $ns, $format, $fh) - read an ASCII PNM image of $ms by $ns pixels from $fh into $im.

pnmout#

pnmout($im, $israw, $isbin, $fh) - write the pixels of $im to $fh, raw or ASCII, as bits ($isbin) or bytes.

bswap2#

bswap2($x) - the bytes of each 2-byte element of $x reversed, in place.

bswap4#

bswap4($x) - the bytes of each 4-byte element reversed, in place.

bswap8#

bswap8($x) - the bytes of each 8-byte element reversed, in place.

bswap12#

bswap12($x) - the bytes of each 12-byte element reversed, in place.

bswap16#

bswap16($x) - the bytes of each 16-byte element reversed, in place.

bswap24#

bswap24($x) - the bytes of each 24-byte element reversed, in place.

bswap32#

bswap32($x) - the bytes of each 32-byte element reversed, in place.