Module: PDL::Ops
Signature: (a(); [o]b())
elementwise absolut value
$b = abs $a; $a->inplace->abs; # modify $a inplace
It can be made to work inplace with the $a->inplace syntax. This function is used to overload the unary abs operator/function.
Signature: (a(); [o]b())
The usual trigonometric function.
Signature: (a(); [o]b())
The standard hyperbolic function.
Module: PDL::Primitive
Return true if all elements in piddle set
Useful in conditional expressions:
if (all $a>15) { print "all values are greater than 15\n" }
Generates a piddle with index values
$z = allaxisvals ($piddle);
allaxisvals produces an array with axis values along each dimension, adding an extra dimension at the start.
C
allaxisvals($piddle)->slice("($nth)")
will produce the same result
as axisvals($piddle,$nth) (although with extra work and not inplace).
It's useful when all the values will be required, as in the example
given of a generalized the rvals entry in the rvals
manpage.
Module: PDL::Primitive
Return the logical and of all elements in a piddle
$x = and($data);
Signature: (a(); b(); [o]c(); int swap)
binary and of two piddles
$c = and2 $a, $b, 0; # explicit call with trailing 0 $c = $a & $b; # overloaded call $a->inplace->and2($b,0); # modify $a inplace
It can be made to work inplace with the $a->inplace syntax. This function is used to overload the binary & operator. Note that when calling this function explicitly you need to supply a third argument that should generally be zero (see first example). This restriction is expected to go away in future releases.
Signature: (a(n); int+ [o]b())
Project via and to N-1 dimensions
This function reduces the dimensionality of a piddle by one by taking the and along the 1st dimension.
By using the xchg entry in the xchg
PDL::Slices manpage etc. it is possible to use
any dimension.
$a = andover($b);
$spectrum = andover $image->xchg(0,1)
Module: PDL::Primitive
Return true if any element in piddle set
Useful in conditional expressions:
if (any $a>15) { print "some values are greater than 15\n" }
Signature: (a(n); b(m); [o] c(mn))
append two piddles by concantening along their respective first dimensions
$a = ones(2,4,7); $b = sequence 5; $c = $a->append($b); # size of $c is now (7,4,7) (a jumbo-piddle ;)
append appends two piddles along their first dims. Rest of the dimensions must be compatible in the threading sense. Resulting size of first dim is sum of sizes of the two argument piddles' first dims.
Regex search PDL documentation database
apropos 'text'
perldl> apropos 'pic' rpic Read images in many formats with automatic format detection. rpiccan Test which image formats can be read/written wmpeg Write an image sequence ((x,y,n) piddle) as an MPEG animation. wpic Write images in many formats with automatic format selection. wpiccan Test which image formats can be read/written
To find all the manuals that come with PDL, try
apropos 'manual:'
and to get quick info about PDL modules say
apropos 'module:'
You get more detailed info about a PDL function/module/manual with the help function
Signature: (a(); [o]b())
The usual trigonometric function.
Signature: (a(); [o]b())
The standard hyperbolic function.
Signature: (a(); [o]b())
Plain numerical assignment. This is used to implement the ``.='' operator
Module: PDL::Core
Returns a single value inside a piddle as perl scalar.
$z = at($piddle, @position); $z=$piddle->at(@position);
@position is a coordinate list, of size equal to the number of dimensions in the piddle. Occasionally useful in a general context, quite useful too inside PDL internals.
perldl> $x = sequence 3,4 perldl> p $x->at(1,2) 7
Signature: (a(); [o]b())
The usual trigonometric function.
Signature: (a(); b(); [o]c(); int swap)
elementwise atan2 of two piddles
$c = $a->atan2($b,0); # explicit function call $c = atan2 $a, $b; # overloaded use $a->inplace->atan2($b,0); # modify $a inplace
It can be made to work inplace with the $a->inplace syntax. This function is used to overload the binary atan2 function. Note that when calling this function explicitly you need to supply a third argument that should generally be zero (see first example). This restriction is expected to go away in future releases.
Signature: (a(); [o]b())
The standard hyperbolic function.
Function to fetch one string value from a PDL::Char type PDL, given a position within the PDL. The input position of the string, not a character in the string. The length of the input string is the implied first dimension.
$char = PDL::Char->new( [['abc', 'def', 'ghi'], ['jkl', 'mno', 'pqr']] ); print $char->atstr(0,1); # Prints: # jkl
Signature: (coords(nc,np);
int from(nl);
int to(nl);
strength(nl);
[o]vecs(nc,np);;
double m;
double ms;
)
Attractive potential for molecule-like constructs.
attract is used to calculate
an attractive force for many
objects, of which some attract each other (in a way
like molecular bonds).
For use by the module the PDL::Graphics::TriD::MathGraph
PDL::Graphics::TriD::MathGraph manpage.
For definition of the potential, see the actual function.
$obj->attributes; PDL::Func->attributes;
Print out the flags for the attributes of a PDL::Func object.
Useful in case the documentation is just too opaque!
PDL::Func->attributes; Flags Attribute SGR x SGR y G err
Signature: (a(n); int+ [o]b())
Project via average to N-1 dimensions
This function reduces the dimensionality of a piddle by one by taking the average along the 1st dimension.
By using the xchg entry in the xchg
PDL::Slices manpage etc. it is possible to use
any dimension.
$a = average($b);
$spectrum = average $image->xchg(0,1)
Module: PDL::Primitive
Return the average of all elements in a piddle
$x = avg($data);
Fills a piddle with index values on Nth dimension
$z = axisvals ($piddle, $nth);
This is the routine, for which the xvals entry in the xvals
manpage, the yvals entry in the yvals
manpage etc
are mere shorthands. axisvals can be used to fill
along any dimension.
Note the 'from specification' style (see the zeroes entry in the zeroes
PDL::Core manpage) is
not available here, for obvious reasons.
Signature: ([o,nc]a(n))
Internal routine
axisvalues is the internal primitive that implements
the axisvals entry in the axisvals
PDL::Basic manpage
and alters its argument.
Signature: (a(); b(); [o]c())
Clears all infs and nans in $a to the corresponding value in $b
Return the bitwise and of all elements in a piddle
$x = band($data);
Signature: (a(n); int+ [o]b())
Project via bitwise and to N-1 dimensions
This function reduces the dimensionality of a piddle by one by taking the bitwise and along the 1st dimension.
By using the xchg entry in the xchg
PDL::Slices manpage etc. it is possible to use
any dimension.
$a = bandover($b);
$spectrum = bandover $image->xchg(0,1)
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.
It does this magic by unwinding the stack frames until it reaches a package NOT beginning with "PDL::". If you DO want it to report errors in some module PDL::Foo (e.g. when debugging PDL::Foo) then set the variable $PDL::Foo::Debugging=1.
Additionally if you set the variable $PDL::Debugging=1 you will get a COMPLETE stack trace back up to the top level package.
Finally barf() will try and report usage information from the PDL documentation database if the error message is of the form 'Usage: func'.
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
Signature: (a(); [o]b())
The standard Bessel Functions
Signature: (a(); [o]b())
The standard Bessel Functions
Signature: (a(); int n(); [o]b())
The standard Bessel Functions
Signature: (a(); [o]b())
The standard Bessel Functions
Signature: (a(); [o]b())
The standard Bessel Functions
Signature: (a(); int n(); [o]b())
The standard Bessel Functions
Signature: (I(n,m); O(q,p))
Bilineary maps the first piddle in the second. The interpolated values are actually added to the second piddle which is supposed to be larger than the first one.
Module: PDL::Graphics::PGPLOT
Plot vector as histogram (e.g. bin(hist($data)))
Usage: bin ( [$x,] $data )
Options recognised:
CENTRE - if true, the x values denote the centre of the bin
otherwise they give the lower-edge (in x) of the bin
CENTER - as CENTRE
The following standard options influence this command:
AXIS, BORDER, COLOUR, JUSTIFY, LINESTYLE, LINEWIDTH
Signature: (a(); [o]b())
unary bit negation
$b = ~ $a; $a->inplace->bitnot; # modify $a inplace
It can be made to work inplace with the $a->inplace syntax. This function is used to overload the unary ~ operator/function.
Module: PDL::Primitive
Return the bitwise or of all elements in a piddle
$x = bor($data);
Signature: (a(n); int+ [o]b())
Project via bitwise or to N-1 dimensions
This function reduces the dimensionality of a piddle by one by taking the bitwise or along the 1st dimension.
By using the xchg entry in the xchg
PDL::Slices manpage etc. it is possible to use
any dimension.
$a = borover($b);
$spectrum = borover $image->xchg(0,1)
Signature: (a(n,m))
browse a 2D array using terminal cursor keys
browse $data
This uses the CURSES library to allow one to scroll around a PDL array using the cursor keys.
Signature: (x(); )
Swaps pairs of bytes in argument x()
Signature: (x(); )
Swaps quads of bytes in argument x()
Signature: (x(); )
Swaps octets of bytes in argument x()
Default bindings for mousemotion with buttons 1 and 3
Convert to byte datatype -- see 'Datatype_conversions'
Scales a pdl into a specified data range (default 0
255)
$scale = $im->bytescl([$top])
By default $top=255, otherwise you have to give the desired top value as an argument to bytescl. Normally bytescl doesn't rescale data that fits already in the bounds 0..$top (it only does the type conversion if required). If you want to force it to rescale so that the max of the output is at $top and the min at 0 you give a negative $top value to indicate this.
Signature: (a(m=2); [o]c())
complex abs() (also known as modulus)
Signature: (a(m=2); [o]c())
complex squared abs() (also known squared modulus)
Signature: (a(m=2); [o]c(m=2))
Signature: (a(m=2); [o]c(m=2))
Call a function in an external library using Perl dynamic loading
callext('file.so', 'foofunc', $x, $y); # pass piddles to foofunc()
The file must be compiled with dynamic loading options (see callext_cc). See the module docs PDL::Callext for a description of the API.
Compile external C code for dynamic loading
Usage:
% perl -MPDL::CallExt -e callext_cc file.c -o file.so
This works portably because when Perl has built in knowledge of how to do dynamic loading on the system on which it was installed. See the module docs PDL::Callext for a description of the API.
Signature: (a(n); [o]c())
argument of a complex number.
$out_pdl_real = Carg($a_pdl_cplx);
Signature: (a(m=2); [o]c(m=2))
Signature: (a(m=2); [o]c(m=2))
Module: PDL::Core
concatentate piddles to N+1 dimensional piddle
Takes a list of N piddles of same shape as argument, returns a single piddle of dimension N+1
perldl> $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] ] ]
Signature: (a(m=2); [o]c(m=2))
Signature: (a(n))
Complex inplace conjugate.
Cbconj($a_pdl_cplx);
Signature: (a(n))
Complex inplace exponentation.
$out_pdl_cplx = Cexp($a_pdl_cplx);
Signature: (a(n); b(n))
Complex inplace multiplication.
Cbmul($a_pdl_cplx,$b_pdl_cplx);
Signature: (a(n); b())
Complex inplace multiplaction by real.
Cbscale($a_pdl_cplx,$b_pdl_real);
Signature: (a(m,n); [o]b(m,n))
Connected 8-component labeling of a binary image.
Connected 8-component labeling of 0,1 image -- i.e. find seperate segmented objects and fill object pixels with object number
$segmented = cc8compt( $image > $threshold );
Signature: (a(m=2); b(m=2); [o]c())
Complex comparison oeprator (spaceship). It orders by real first, then by imaginary.
Signature: (a(n); [o]c(n))
Complex conjugate.
$out_pdl_cplx = Cconj($a_pdl_cplx);
Signature: (a(m=2); [o]c(m=2))
cos (a) = 1/2 * (exp (a*i) + exp (-a*i))
Signature: (a(m=2); [o]c(m=2))
cosh (a) = (exp (a) + exp (-a)) / 2
Signature: (a(n); b(n); [o]c(n))
Complex division.
$out_pdl_cplx = Cdiv($a_pdl_cplx,$b_pdl_cplx);
Signature: (ar(); ai(); br(); bi(); [o]cr(); [o]ci())
Complex division
Signature: (a(); [o]b())
Round to integral values in floating-point format
Signature: (im(m,n); x(); y(); box(); [o]xcen(); [o]ycen())
Refine a list of object positions in 2D image by centroiding in a box
$box is the full-width of the box, i.e. the window is +/- $box/2.
Signature: (a(n); [o]c(n))
Complex exponentation.
$out_pdl_cplx = Cexp($a_pdl_cplx);
Signature: (x(n);f(n);d(n);int check();int [o]ismon(n);int [o]ierr())
Check the given piecewise cubic Hermite function for monotonicity.
The outout piddle $ismon indicates over which intervals the function is monotonic. Set check to 0 to skip checks on the input data.
For the data interval [x(i),x(i+1)], the values of ismon(i) can be:
If abs(ismon(i)) == 3, the derivative values are near the boundary of the monotonicity region. A small increase produces non-monotonicity, whereas a decrease produces strict monotonicity.
The above applies to i = 0 .. nelem($x)-1. The last element of $ismon indicates whether the entire function is monotonic over $x.
Error status returned by $ierr:
Signature: (x(n);f(n);d(n);int check();xe(ne);[o]fe(ne);[o]de(ne);int [o]ierr())
Interpolate function and derivative values.
Given a piecewise cubic Hermite function -- such as from
the chim entry in the chim
manpage -- evaluate the function ($fe) and
derivative ($de) at a set of points ($xe).
If function values alone are required, use the chfe entry in the chfe
manpage.
Set check to 0 to skip checks on the input data.
Error status returned by $ierr:
Signature: (x(n);f(n);d(n);int check();xe(ne);[o]fe(ne);int [o]ierr())
Interpolate function values.
Given a piecewise cubic Hermite function -- such as from
the chim entry in the chim
manpage -- evaluate the function ($fe) at
a set of points ($xe).
If derivative values are also required, use the chfd entry in the chfd
manpage.
Set check to 0 to skip checks on the input data.
Error status returned by $ierr:
Signature: (x(n);f(n);d(n);int check();a();b();[o]ans();int [o]ierr())
Integrate (x,f(x)) over arbitrary limits.
Evaluate the definite integral of a a piecewise
cubic Hermite function over an arbitrary interval,
given by [$a,$b].
See the chid entry in the chid
manpage if the integration limits are
data points.
Set check to 0 to skip checks on the input data.
The values of $a and $b do not have to lie within $x, although the resulting integral value will be highly suspect if they are not.
Error status returned by $ierr:
Signature: (int ic(two=2);vc(two=2);mflag();x(n);f(n);[o]d(n);wk(nwk);int [o]ierr())
Calculate the derivatives of (x,f(x)) using cubic Hermite interpolation.
Calculate the derivatives at the given points ($x,$f,
where $x is strictly increasing).
Control over the boundary conditions is given by the
$ic and $vc piddles, and the value of $mflag determines
the treatment of points where monotoncity switches
direction. A simpler, more restricted, interface is available
using the chim entry in the chim
manpage.
The first and second elements of $ic determine the boundary
conditions at the start and end of the data respectively.
If the value is 0, then the default condition, as used by
the chim entry in the chim
manpage, is adopted.
If greater than zero, no adjustment for monotonicity is made,
otherwise if less than zero the derivative will be adjusted.
The allowed magnitudes for ic(0) are:
The values for ic(1) are the same as above, except that the first-derivative value is stored in vc(1) for cases 1 and 2. The values of $vc need only be set if options 1 or 2 are chosen for $ic.
Set $mflag = 0 if interpolant is required to be monotonic in each interval, regardless of the data. This causes $d to be set to 0 at all switch points. Set $mflag to be non-zero to use a formula based on the 3-point difference formula at switch points. If $mflag > 0, then the interpolant at swich points is forced to not deviate from the data by more than $mflag*dfloc, where dfloc is the maximum of the change of $f on this interval and its two immediate neighbours. If $mflag < 0, no such control is to be imposed.
The piddle $wk is only needed for work space. However, I could not get it to work as a temporary variable, so you must supply it; it is a 1D piddle with 2*n elements.
Error status returned by $ierr:
Signature: (x(n);f(n);d(n);int check();int ia();int ib();[o]ans();int [o]ierr())
Integrate (x,f(x)) between data points.
Evaluate the definite integral of a a piecewise cubic Hermite function between x($ia) and x($ib).
See the chia entry in the chia
manpage for integration between arbitrary
limits.
Although using a fortran routine, the values of $ia and $ib are zero offset. Set check to 0 to skip checks on the input data.
Error status returned by $ierr:
Signature: (x(n);f(n);[o]d(n);int [o]ierr())
Calculate the derivatives of (x,f(x)) using cubic Hermite interpolation.
Calculate the derivatives at the given set of points ($x,$f,
where $x is strictly increasing).
The resulting set of points -- $x,$f,$d, referred to
as the cubic Hermite representation -- can then be used in
other functions, such as the chfe entry in the chfe
manpage, the chfd entry in the chfd
manpage,
and the chia entry in the chia
manpage.
The boundary conditions are compatible with monotonicity,
and if the data are only piecewise monotonic, the interpolant
will have an extremum at the switch points; for more control
over these issues use the chic entry in the chic
manpage.
Error status returned by $ierr:
Signature: (int ic(two=2);vc(two=2);x(n);f(n);[o]d(n);wk(nwk);int [o]ierr())
Calculate the derivatives of (x,f(x)) using cubic spline interpolation.
Calculate the derivatives, using cubic spline interpolation, at the given points ($x,$f), with the specified boundary conditions. Control over the boundary conditions is given by the $ic and $vc piddles. The resulting values -- $x,$f,$d - can be used in all the functions which expect a cubic Hermite function.
The first and second elements of $ic determine the boundary conditions at the start and end of the data respectively. The allowed values for ic(0) are:
The values for ic(1) are the same as above, except that the first-derivative value is stored in vc(1) for cases 1 and 2. The values of $vc need only be set if options 1 or 2 are chosen for $ic.
The piddle $wk is only needed for work space. However, I could not get it to work as a temporary variable, so you must supply it; it is a 1D piddle with 2*n elements.
Error status returned by $ierr:
Smooths an image by applying circular mean. Optionally takes the center to be used.
circ_mean($im);
circ_mean($im,{Center => [10,10]});
Calculates the circular mean of an n-dim image and returns the projection. Optionally takes the center to be used.
$cmean=circ_mean_p($im);
$cmean=circ_mean_p($im,{Center => [10,10]});
Clip a piddle by (optional) upper or lower bounds.
$b = $a->clip(0,3); $c = $a->clip(undef, $x);
Signature: (a(m=2); [o]c(m=2))
log (a) = log (cabs (a)) + i
carg (a)
Signature: (P(); C(); int n)
``clumps'' the first n dimensions into one large dimension
If, for example, $a has dimensions (5,3,4) then after
$b = $a->clump(2); # Clump 2 first dimensions
the variable $b will have dimensions (15,4) and the element $b->at(7,3) refers to the element $a->at(1,2,3).
Signature: (a(n); [o]c())
modulus of a complex piddle.
$out_pdl_real = Cmod($a_pdl_cplx);
Signature: (a(n); [o]c())
Returns squared modulus of a complex number.
$out_pdl_real = Cmod2($a_pdl_cplx);
Signature: (a(n); b(n); [o]c(n))
Complex multiplication
$out_pdl_cplx = Cmul($a_pdl_cplx,$b_pdl_cplx);
Signature: (ar(); ai(); br(); bi(); [o]cr(); [o]ci())
Complex multiplication
Signature: (x(); y(); z();
float [o]coords(tri=3);)
Combine three coordinates into a single piddle.
Combine x, y and z to a single piddle the first dimension of which is 3. This routine does dataflow automatically.
Display image as contour map
Usage: cont ( $image, [$contours, $transform, $misval], [$opt] )
Notes: $transform for image/cont etc. is used in the same way as the TR() array in the underlying PGPLOT FORTRAN routine but is, fortunately, zero-offset.
Options recognised:
CONTOURS - A piddle with the contour levels
FOLLOW - Follow the contour lines around (uses pgcont rather than
pgcons) If this is set >0 the chosen linestyle will be
ignored and solid line used for the positive contours
and dashed line for the negative contours.
LABELS - An array of strings with labels for each contour
LABELCOLOUR - The colour of labels if different from the draw colour
This will not interfere with the setting of draw colour
using the colour keyword.
MISSING - The value to ignore for contouring
NCONTOURS - The number of contours wanted for automatical creation,
overridden by CONTOURS
TRANSFORM - The pixel-to-world coordinate transform vector
The following standard options influence this command:
AXIS, BORDER, COLOUR, JUSTIFY, LINESTYLE, LINEWIDTH
$x=sequence(10,10);
$ncont = 4;
$labels= ['COLD', 'COLDER', 'FREEZING', 'NORWAY']
# This will give four blue contour lines labelled in red.
cont $x, {NCONT => $ncont, LABELS => $labels, LABELCOLOR => RED,
COLOR => BLUE}
This is the interface for the pp routine contour_segments_internal -- it takes 3 piddles as input
$c is a contour value (or a list of contour values)
$data is an [m,n] array of values at each point
$points is a list of [3,m,n] points, it should be a grid monotonically increasing with m and n.
contour_segments returns a reference to a Perl array of line segments associated with each value of $c. It does not (yet) handle missing data values.
Signature: (a(m,n); kern(p,q); [o]b(m,n); int opt)
2D convolution of an array with a kernel (smoothing)
For large kernels, using a FFT routine,
such as the fftconvolve entry in the PDL::FFT::fftconvolve()
PDL::FFT manpage,
will be quicker.
$new = conv2d $old, $kernel, {OPTIONS}
$smoothed = conv2d $image, ones(3,3), {Boundary => Reflect}
Boundary - controls what values are assumed for the image when kernel
crosses its edge:
=> Default - periodic boundary conditions
(i.e. wrap around axis)
=> Reflect - reflect at boundary
=> Truncate - truncate at boundary
Generic datatype conversion function
$y = convert($x, $newtype);
$y = convert $x, long $y = convert $x, ushort
$newtype is a type number, for convenience they are returned by long() etc when called without arguments.
Signature: ([o,nc]a(m); [o,nc]b(m))
Internal routine doing maths for convolution
Signature: (a(m); b(n); int adims(p); int bdims(q); [o]c(m))
N-dimensional convolution algorithm.
$new = convolve $a, $kernel
Convolve an array with a kernel, both of which are N-dimensional.
Note because of the algorithm used (writing N-dim routines is not easy on the brain!) the boundary conditions are a bit strange. They wrap, but up to the NEXT row/column/cube-slice/etc. If this is a problem consider using zero-padding or something.
Make a physical copy of a piddle
$new = $old->copy;
Since $new = $old just makes a new reference, the copy method is provided to allow real independent copies to be made.
Module: PDL::Ops
Signature: (a(); [o]b())
the cos function
$b = cos $a; $a->inplace->cos; # modify $a inplace
It can be made to work inplace with the $a->inplace syntax. This function is used to overload the unary cos operator/function.
Signature: (a(); [o]b())
The standard hyperbolic function.
Signature: (r(m=2); [o]p(m=2))
convert complex numbers in polar (mod,arg) form to rectangular form
Signature: (a(m=2); b(m=2); [o]c(m=2))
complex pow() (**-operator)
Signature: (a(m=2); [o]c(m=2))
compute the projection of a complex number to the riemann sphere
quantize and reduce colours in 8-bit images
($out, $lut) = cquant($image [,$ncols]);
This function does color reduction for <=8bit displays and accepts 8bit RGB and 8bit palette images. It does this through an interface to the ppm_quant routine from the pbmplus package that implements the median cut routine which intellegently selects the 'best' colors to represent your image on a <= 8bit display (based on the median cut algorithm). Optional args: $ncols sets the maximum nunmber of colours used for the output image (defaults to 256). There are images where a different color reduction scheme gives better results (it seems this is true for images containing large areas with very smoothly changing colours).
Returns a list containing the new palette image (type PDL_Byte) and the RGB colormap.
Signature: (r(m=2); float+ [o]p(m=2))
convert complex numbers in rectangular form to polar (mod,arg) form
Signature: (a(m=2); [o]c(m=2,n); int n => n)
Compute the n roots of a. n must be a positive integer. The result will always be a complex type!
Signature: (a(tri=3); b(tri); [o] c(tri))
Cross product of two 3D vectors
After
$c = crossp $a, $b
the inner product $c*$a and $c*$b will be zero, i.e. $c is orthogonal to $a and $b
Signature: (a(n); b(); [o]c(n))
Complex by real multiplation.
Cscale($a_pdl_cplx,$b_pdl_real);
Signature: (a(m=2); [o]c(m=2))
sin (a) = 1/(2*i) * (exp (a*i) - exp (-a*i))
Signature: (a(m=2); [o]c(m=2))
sinh (a) = (exp (a) - exp (-a)) / 2
Signature: (a(m=2); [o]c(m=2))
Load an image colour table.
Usage:
ctab ( $name, [$contrast, $brightness] ) # Builtin col table ctab ( $ctab, [$contrast, $brightness] ) # $ctab is Nx4 array ctab ( $levels, $red, $green, $blue, [$contrast, $brightness] ) ctab ( '', $contrast, $brightness ) # use last color table
Note: See the PDL::Graphics::LUT
PDL::Graphics::LUT manpage for access to a large
number of colour tables.
Signature: (a(m=2); [o]c(m=2))
Signature: (a(n); int+ [o]b(n))
Cumulative product
This function calculates the cumulative product along the 1st dimension.
By using the xchg entry in the xchg
PDL::Slices manpage etc. it is possible to use
any dimension.
The sum is started so that the first element in the cumulative product is the first element of the parameter.
$a = cumuprodover($b);
$spectrum = cumuprodover $image->xchg(0,1)
Signature: (a(n); int+ [o]b(n))
Cumulative sum
This function calculates the cumulative sum along the 1st dimension.
By using the xchg entry in the xchg
PDL::Slices manpage etc. it is possible to use
any dimension.
The sum is started so that the first element in the cumulative sum is the first element of the parameter.
$a = cumusumover($b);
$spectrum = cumusumover $image->xchg(0,1)
byte
short
ushort
long
float
double convert shorthands
$y = double $x; $y = ushort [1..10]; # all of byte|short|ushort|long|float|double behave similarly
When called with a piddle argument, they convert to the specific datatype.
When called with a numeric or list / listref argument they construct a new piddle. This is a convenience to avoid having to be long-winded and say $x = long(pdl(42))
Thus one can say:
$a = float(1,2,3,4); # 1D $a = float([1,2,3],[4,5,6]); # 2D $a = float([[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 []
When called with no arguments return a special type token. This allows syntactical sugar like:
$x = ones byte, 1000,1000;
This example creates a large piddle directly as byte datatype in order to save memory.
In order to control how undefs are handled in converting from perl lists to
PDLs, one can set the variable $PDL::undefval;
see the function the pdl entry in the pdl()
manpage for more details.
perldl> p $x=sqrt float [1..10] [1 1.41421 1.73205 2 2.23607 2.44949 2.64575 2.82843 3 3.16228] perldl> p byte $x [1 1 1 2 2 2 2 2 3 3]
Module: PDL::Graphics::PGPLOT
Open PGPLOT graphics device
Usage: dev $device, [$nx,$ny];
$device is a PGPLOT graphics device such as ``/xserve'' or ``/ps'', if omitted defaults to last used device (or value of env var PGPLOT_DEV if first time). $nx, $ny specify sub-panelling.
Returns the multidimensional diagonal over the specified dimensions.
$d = $x->diagonal(dim1, dim2,...)
perldl> $a = zeroes(3,3,3); perldl> ($b = $a->diagonal(0,1))++; perldl> p $a [ [ [1 0 0] [0 1 0] [0 0 1] ] [ [1 0 0] [0 1 0] [0 0 1] ] [ [1 0 0] [0 1 0] [0 0 1] ] ]
Signature: (P(); C(); SV *list)
Returns the multidimensional diagonal over the specified dimensions.
The diagonal is placed at the first (by number) dimension that is diagonalized. The other diagonalized dimensions are removed. So if $a has dimensions (5,3,5,4,6,5) then after
$b = $a->diagonal(0,2,5);
the piddle $b has dimensions (5,3,4,6) and $b->at(2,1,0,1) refers to $a->at(2,1,2,0,1,2).
NOTE: diagonal doesn't handle threadids correctly. XXX FIX
Dice rows/columns/planes out of a PDL using indexes for each dimension.
This function can be used to extract irregular subsets along many dimension of a PDL, e.g. only certain rows in an image, or planes in a cube. This can of course be done with the usual dimension tricks but this saves having to figure it out each time!
This method is similar in functionality to the the slice entry in the slice
manpage
method, but the slice entry in the slice
manpage requires that contiguous ranges or ranges
with constant offset be extracted. ( i.e. the slice entry in the slice
manpage requires
ranges of the form 1,2,3,4,5 or 2,4,6,8,10). Because of this
restriction, the slice entry in the slice
manpage is more memory efficient and slightly faster
than dice
$slice = $data->dice([0,2,6],[2,1,6]); # Dicing a 2-D array
The arguments to dice are arrays (or 1D PDLs) for each dimension in the PDL. These arrays are used as indexes to which rows/columns/cubes,etc to dice-out (or extract) from the $data PDL.
perldl> $a = sequence(10,4) perldl> p $a [ [ 0 1 2 3 4 5 6 7 8 9] [10 11 12 13 14 15 16 17 18 19] [20 21 22 23 24 25 26 27 28 29] [30 31 32 33 34 35 36 37 38 39] ] perldl> p $a->dice([1,2],[0,3]) # Select columns 1,2 and rows 0,3 [ [ 1 2] [31 32] ]
As this is an index function, any modifications to the slice change the parent.
Dice rows/columns/planes from a single PDL axis (dimension) using index along a specified axis
This function can be used to extract irregular subsets along any dimension, e.g. only certain rows in an image, or planes in a cube. This can of course be done with the usual dimension tricks but this saves having to figure it out each time!
$slice = $data->dice_axis($axis,$index);
perldl> $a = sequence(10,4) perldl> $idx = pdl(1,2) perldl> p $a->dice_axis(0,$idx) # Select columns [ [ 1 2] [11 12] [21 22] [31 32] ] perldl> $t = $a->dice_axis(1,$idx) # Select rows perldl> $t.=0 perldl> p $a [ [ 0 1 2 3 4 5 6 7 8 9] [ 0 0 0 0 0 0 0 0 0 0] [ 0 0 0 0 0 0 0 0 0 0] [30 31 32 33 34 35 36 37 38 39] ]
The trick to using this is that the index selects elements along the dimensions specified, so if you have a 2D image axis=0 will select certain X values -- i.e. extract columns
As this is an index function, any modifications to the slice change the parent.
Return piddle dimensions as a perl list
@dims = $piddle->dims; @dims = dims($piddle);
perldl> p @tmp = dims zeroes 10,3,22 10 3 22
Signature: (a(); b(); [o]c(); int swap)
divide two piddles
$c = divide $a, $b, 0; # explicit call with trailing 0 $c = $a / $b; # overloaded call $a->inplace->divide($b,0); # modify $a inplace
It can be made to work inplace with the $a->inplace syntax. This function is used to overload the binary / operator. Note that when calling this function explicitly you need to supply a third argument that should generally be zero (see first example). This restriction is expected to go away in future releases.
Turn on/off dataflow
$x->doflow; doflow($x);
Module: PDL::Core
Opposite of 'cat' :). Split N dim piddle to list of N-1 dim piddles
Takes a single N-dimensional piddle and splits it into a list of N-1 dimensional piddles. The breakup is done along the last dimension. Note the dataflown connection is still preserved by default, e.g.:
perldl> $p = ones 3,3,3 perldl> ($a,$b,$c) = dog $p perldl> $b++; 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)
Convert to double datatype -- see 'Datatype_conversions'
Insert a 'dummy dimension' of given length (defaults to 1)
No relation to the 'Dungeon Dimensions' in Discworld! Negative positions specify relative to last dimension, i.e. dummy(-1) appends one dimension at end, dummy(-2) inserts a dummy dimension in front of the last dim, etc.
$y = $x->dummy($position[,$dimsize]);
perldl> p sequence(3)->dummy(0,3) [ [0 0 0] [1 1 1] [2 2 2] ]
Signature: ([phys]a(m); [o,phys]ev(n,n); [o,phys]e(n))
Eigenvalues and -vectors of a symmetric square matrix. If passed an asymmetric matrix, the routine will warn and symmetrize it.
($e, $ev) = eigens($a);
Eigenvalues and eigenvectors of a real positive definite symmetric matrix.
($eigvals,$eigvecs) = eigsys($mat)
Note: this function should be extended to calculate only eigenvalues if called in scalar context!
Module: PDL::Graphics::PGPLOT
Define a plot window, and put graphics on 'hold'
Usage: env $xmin, $xmax, $ymin, $ymax, [$justify, $axis];
env $xmin, $xmax, $ymin, $ymax, [$options];
$xmin, $xmax, $ymin, $ymax are the plot boundaries. $justify is a boolean value (default is 0); if true the axes scales will be the same (see the justify entry elsewhere in this document). $axis describes how the axes should be drawn (see the axis entry elsewhere in this document) and defaults to 0.
If the second form is used, $justify and $axis can be set in the options hash, for example:
env 0, 100, 0, 50, {JUSTIFY => 1, AXIS => 'GRID', CHARSIZE => 0.7};
Module: PDL::Ops
Signature: (a(); b(); [o]c(); int swap)
binary equal to operation (==)
$c = eq $a, $b, 0; # explicit call with trailing 0 $c = $a == $b; # overloaded call $a->inplace->eq($b,0); # modify $a inplace
It can be made to work inplace with the $a->inplace syntax. This function is used to overload the binary == operator. Note that when calling this function explicitly you need to supply a third argument that should generally be zero (see first example). This restriction is expected to go away in future releases.
Module: PDL::Math
Signature: (a(); [o]b())
The error function
Signature: (a(); [o]b())
The complement of the error function
Signature: (a(); [o]b())
The inverse of the error function
Plot error bars (using pgerrb())
Usage:
errb ( $y, $yerrors, [$opt] ) errb ( $x, $y, $yerrors, [$opt] ) errb ( $x, $y, $xerrors, $yerrors, [$opt] ) errb ( $x, $y, $xloerr, $xhierr, $yloerr, $yhierr, [$opt])
Options recognised:
TERM - Length of terminals in multiples of the default length
SYMBOL - Plot the datapoints using the symbol value given, either
as name or number - see documentation for 'points'
The following standard options influence this command:
AXIS, BORDER, CHARSIZE, COLOUR, JUSTIFY, LINESTYLE, LINEWIDTH
$y = sequence(10)**2+random(10);
$sigma=0.5*sqrt($y);
errb $y, $sigma, {COLOUR => RED, SYMBOL => 18};
Module: PDL::Ops
Signature: (a(); [o]b())
the exponential function
$b = exp $a; $a->inplace->exp; # modify $a inplace
It can be made to work inplace with the $a->inplace syntax. This function is used to overload the unary exp operator/function.
Signature: ([o]r(n);azero();a(n);b(n);wsave(foo))
Signature: (r(n);[o]azero();[o]a(n);[o]b(n);wsave(foo))
Signature: (int n();[o]wsave(foo))
Subroutine ezffti initializes the work array wsave()
which is used in both the ezfftf entry in the ezfftf
manpage and
the ezfftb entry in the ezfftb
manpage.
The prime factorization
of n together with a tabulation of the trigonometric functions
are computed and stored in wsave().
Module: PDL::FFT
Signature: ([o,nc]real(n); [o,nc]imag(n))
Complex FFT of the ``real'' and ``imag'' arrays [inplace]
N-dimensional convolution
$kernel = kernctr($image,$smallk);
fftconvolve($image,$kernel);
fftconvolve works inplace, and returns an error array in kernel as an accuracy check -- all the values in it should be negligible.
The sizes of the image and the kernel must be the same.
the kernctr entry in the kernctr
manpage
centres a small kernel to emulate the behaviour of the direct
convolution routines.
The speed cross-over between using straight convolution
(the conv2d entry in the PDL::Image2D::conv2d()
PDL::Image2D manpage) and
these fft routines is for kernel sizes roughly 7x7.
N-dimensional FFT (inplace)
fftnd($real,$imag);
calculate the complex FFT of a real piddle (complex input, complex output)
$pdl_cplx = fftw $pdl_cplx;
ND convolution using complex ffts from the FFTW library
Assumes real input!
$conv = fftwconv $im, kernctr $k;
Signature: ([o]x(n))
Constructor -- a vector with Fibonacci's sequence
Fit 1D Gassian to data piddle
($cen, $pk, $fwhm2, $back, $err, $fit) = fitgauss1d($x, $data);
($cen, $pk, $fwhm2, $back, $err, $fit) = fitgauss1d($x, $data);
xval(n); data(n); [o]xcentre();[o]peak_ht(); [o]fwhm(); [o]background();int [o]err(); [o]datafit(n); [t]sig(n); [t]xtmp(n); [t]ytmp(n); [t]yytmp(n); [t]rtmp(n);
Fit's a 1D Gaussian robustly free parameters are the centre, peak height, FWHM. The background is NOT fit, because I find this is generally unreliable, rather a median is determined in the 'outer' 10% of pixels (i.e. those at the start/end of the data piddle). The initial estimate of the FWHM is the length of the piddle/3, so it might fail if the piddle is too long. (This is non-robust anyway). Most data does just fine and this is a good default gaussian fitter.
SEE ALSO: fitgauss1dr() for fitting radial gaussians
Fit 1D Gassian to radial data piddle
($pk, $fwhm2, $back, $err, $fit) = fitgauss1dr($r, $data);
($pk, $fwhm2, $back, $err, $fit) = fitgauss1dr($r, $data);
xval(n); data(n); [o]peak_ht(); [o]fwhm(); [o]background();int [o]err(); [o]datafit(n); [t]sig(n); [t]xtmp(n); [t]ytmp(n); [t]yytmp(n); [t]rtmp(n);
Fit's a 1D radial Gaussian robustly free parameters are the peak height, FWHM. Centre is assumed to be X=0 (i.e. start of piddle). The background is NOT fit, because I find this is generally unreliable, rather a median is determined in the 'outer' 10% of pixels (i.e. those at the end of the data piddle). The initial estimate of the FWHM is the length of the piddle/3, so it might fail if the piddle is too long. (This is non-robust anyway). Most data does just fine and this is a good default gaussian fitter.
SEE ALSO: fitgauss1d() to fit centre as well.
Fit 1D polynomials to data using min chi
2 (least squares)
Usage: ($yfit, [$coeffs]) = fitpoly1d [$xdata], $data, $order, [Options...]
Signature: (x(n); y(n); [o]yfit(n); [o]coeffs(order))
Uses a standard matrix inversion method to do a least
squares/min chi
2 polynomial fit to data. Order=2 is a linear
fit (two parameters).
Returns the fitted data and optionally the coefficients.
One can thread over extra dimensions to do multiple fits (except the order can not be threaded over -- i.e. it must be one fixed scalar number like ``4'').
The data is normalised internally to avoid overflows (using the mean of the abs value) which are common in large polynomial series but the returned fit, coeffs are in unnormalised units.
$yfit = fitpoly1d $data,2; # Least-squares line fit ($yfit, $coeffs) = fitpoly1d $x, $y, 4; # Fit a cubic
$fitimage = fitpoly1d $image,2 # Fit a quadratic to each row of an image
$myfit = fitpoly1d $line, 2, {Weights => $w}; # Weighted fit
Options:
Weights Weights to use in fit, e.g. 1/$sigma**2 (default=1)
Convert to float datatype -- see 'Datatype_conversions'
Signature: (a(); [o]b())
Round to integral values in floating-point format
Whether or not a piddle is indulging in dataflow
something if $x->flows; $hmm = flows($x);
Module: PDL::Ops
Signature: (a(); b(); [o]c(); int swap)
the binary >= (greater equal) operation
$c = ge $a, $b, 0; # explicit call with trailing 0 $c = $a >= $b; # overloaded call $a->inplace->ge($b,0); # modify $a inplace
It can be made to work inplace with the $a->inplace syntax. This function is used to overload the binary >= operator. Note that when calling this function explicitly you need to supply a third argument that should generally be zero (see first example). This restriction is expected to go away in future releases.
Signature: (a(n,n);int [o]ipvt(n);[o]rcond();[o]z(n))
Factor a matrix using Gaussian elimination and estimate the condition number of the matrix.
Signature: (a(n,n);int [o]ipvt(n);[o]det(two=2);[o]work(n);int job())
Compute the determinant and inverse of a matrix using the
factors computed by the geco entry in the geco
manpage or the gefa entry in the gefa
manpage.
Signature: (a(n,n);int [o]ipvt(n);int [o]info())
Factor a matrix using Gaussian elimination.
Signature: (a(lda,n);int ipvt(n);b(n);int job())
Solve the real system A*X=B or TRANS(A)*X=B using the
factors computed by the geco entry in the geco
manpage or the gefa entry in the gefa
manpage.
Module: PDL::Func
my $x = $obj->get( x ); my ( $x, $y ) = $obj->get( qw( x y ) );
Get attributes from a PDL::Func object.
Given a list of attribute names, return a list of their values; in scalar mode return a scalar value. If the supplied list contains an unknown attribute, get returns a value of undef for that attribute.
Internal: Return the numeric value identifying the piddle datatype
$x = $piddle->get_datatype;
Mainly used for internal routines.
NOTE: get_datatype returns 'just a number' not any special type object.
Returns the size of the given dimension.
$dim0 = $piddle->getdim(0);
perldl> p zeroes(10,3,22)->getdim(1) 3
Retrieve header information from a piddle
$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 a piddle. The header can be set with the sethdr entry in the sethdr
manpage and is always a
hash reference and has to be dereferenced for access to the value.
It is important to realise that you are free to insert whatever hash
reference you want in the header, so you can use it to record important
information about your piddle, and that it is not automatically copied
when you copy the piddle.
See the hdrcpy entry in the hdrcpy
manpage to enable automatic header copying.
For instance a wrapper around rcols that allows your piddle 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;
@piddles=rcols $file, @columns;
foreach (@piddles) { $_->sethdr($header); }
return @piddles;
}
Returns the number of dimensions in a piddle
$ndims = $piddle->getndims;
perldl> p zeroes(10,3,22)->getndims 3
GLinit is called internally by a Configure callback in Populate. This insures that the required Tk::Frame is initialized before the TriD::GL window that will go inside.
Grab a 3D image from the screen.
$pic = grabpic3d();
The returned piddle has dimensions (3,$x,$y) and is of type float (currently). XXX This should be altered later.
my $gi = $obj->gradient( $xi ); my ( $yi, $gi ) = $obj->gradient( $xi );
Returns the derivative and, optionally, the interpolated function for the Hermite scheme (PDL::Func).
Constructor which returns piddle of Gaussian random numbers
$a = grandom([type], $nx, $ny, $nz,...); $a = grandom $b;
etc (see the zeroes entry in the zeroes
PDL::Core manpage).
This is generated using the math library routine ndtri.
Mean = 0, Stddev = 1
Module: PDL::Ops
Signature: (a(); b(); [o]c(); int swap)
the binary > (greater than) operation
$c = gt $a, $b, 0; # explicit call with trailing 0 $c = $a > $b; # overloaded call $a->inplace->gt($b,0); # modify $a inplace
It can be made to work inplace with the $a->inplace syntax. This function is used to overload the binary > operator. Note that when calling this function explicitly you need to supply a third argument that should generally be zero (see first example). This restriction is expected to go away in future releases.
Signature: (a(); b(); [o] c())
clip $a by $b ($b is upper bound)
switch on/off/examine automatic header copying
print "hdrs will be copied" if $a->hdrcpy; $a->hdrcpy(1); # switch on hdr copying $b = $a->sumover; # and $b will inherit $a's hdr $a->hdrcpy(0); # and now make $a non-infectious again
Normally, the optional header of a piddle is not copied automatically in pdl operations. Switching on the hdrcpy flag using the hdrcpy method will enable automatic hdr copying. Note that copying is by reference for efficiency reasons. hdrcpy without an argument just returns the current setting of the flag.
print documentation about a PDL function or module or show a PDL manual
Usage: help 'func'
perldl> help 'PDL::Slices' # show the docs in the PDL::Slices module perldl> help 'PDL::Intro' # show the PDL::Intro manual perldl> help 'slice' # show docs on the 'slice' function
Plot image as 2d histogram (not very good IMHO...)
Usage: hi2d ( $image, [$x, $ioff, $bias], [$opt] )
Options recognised:
IOFFSET - The offset for each array slice. >0 slants to the right
<0 to the left.
BIAS - The bias to shift each array slice up by.
The following standard options influence this command:
AXIS, BORDER, JUSTIFY
Note that meddling with the ioffset and bias often will require you to
change the default plot range somewhat. It is also worth noting that if
you have TriD working you will probably be better off using
the mesh3d entry in the mesh3d
PDL::Graphics::TriD manpage or
a similar command -- see the PDL::Graphics::TriD manpage.
$r=sequence(100)/50-1.0;
$y=exp(-$r**2)*transpose(exp(-$r**2))
hi2d $y, {IOFF => 1.5, BIAS => 0.07};
Create histogram of a piddle
$hist = hist($data,[$min,$max,$step]); ($xvals,$hist) = hist($data,[$min,$max,$step]);
If requested, $xvals gives the computed bin centres
A nice idiom (with
the PDL::Graphics::PGPLOT
PDL::Graphics::PGPLOT manpage) is
bin hist $data; # Plot histogram
perldl> p $y [13 10 13 10 9 13 9 12 11 10 10 13 7 6 8 10 11 7 12 9 11 11 12 6 12 7] perldl> $h = hist $y,0,20,1; # hist with step 1, min 0 and 20 bins perldl> p $h [0 0 0 0 0 0 2 3 1 3 5 4 4 4 0 0 0 0 0 0]
Signature: (in(n); int+[o] hist(m); double step; double min; int msize => m)
Calculates a histogram for given stepsize and minimum.
$h = histogram($data, $step, $min, $numbins); $hist = zeroes $numbins; # Put histogram in existing piddle. histogram($data, $hist, $step, $min, $numbins);
The histogram will contain $numbins bins starting from $min, each $step wide. The value in each bin is the number of values in $data that lie within the bin limits.
Data below the lower limit is put in the first bin, and data above the upper limit is put in the last bin.
The output is reset in a different threadloop so that you can take a histogram of $a(10,12) into $b(15) and get the result you want.
Use the hist entry in the hist
PDL::Basic manpage instead for a high-level interface.
perldl> p histogram(pdl(1,1,2),1,0,3) [0 2 1]
Signature: (ina(n); inb(n); int+[o] hist(ma,mb); double stepa; double mina; int masize => ma;
double stepb; double minb; int mbsize => mb;)
Calculates a 2d histogram.
$h = histogram2d($datax, $datay,
$stepx, $minx, $nbinx, $stepy, $miny, $nbiny);
$hist = zeroes $nbinx, $nbiny; # Put histogram in existing piddle.
histogram2d($datax, $datay, $hist,
$stepx, $minx, $nbinx, $stepy, $miny, $nbiny);
The histogram will contain $nbinx x $nbiny bins, with the lower limits of the first one at ($minx, $miny), and with bin size ($stepx, $stepy). The value in each bin is the number of values in $datax and $datay that lie within the bin limits.
Data below the lower limit is put in the first bin, and data above the upper limit is put in the last bin.
perldl> p histogram2d(pdl(1,1,1,2,2),pdl(2,1,1,1,1),1,0,3,1,0,3) [ [0 0 0] [0 2 2] [0 1 0] ]
Returns the size of a piddle datatype in bytes.
$size = howbig($piddle->get_datatype);
Mainly used for internal routines.
NOTE: NOT a method! This is because get_datatype returns 'just a number' not any special object.
perldl> p howbig(ushort([1..10])->get_datatype) 2
Module: PDL::Complex
Signature: (r(); [o]c(m=2))
convert imaginary to complex, assuming a real part of zero
Signature: (P(); C())
A vaffine identity transformation (includes thread_id copying).
Mainly for internal use.
Signature: ([o,nc]real(n); [o,nc]imag(n))
Complex Inverse FFT of the ``real'' and ``imag'' arrays [inplace]
N-dimensional inverse FFT
ifftnd($real,$imag);
Complex inverse FFT (complex input, complex output).
$pdl_cplx = ifftw $pdl_cplx;
Module: PDL::Graphics::IIS
Displays an image on a IIS device (e.g. SAOimage/Ximtool)
iis $image, [ { MIN => $min, MAX => $max,
TITLE => 'pretty picture',
FRAME => 2 } ]
iis $image, [$min,$max]
(image(m,n),[\%options]) or (image(m,n),[min(),max()])
Displays image on a IIS device. If min() or max() are omitted they
are autoscaled. A good demonstration of PDL threading can be had
by giving iis() a data
cube
-- iis() will be repeatedly called
for each plane of the cube resulting in a poor man's movie!
If supplied, TITLE is used to label the frame, if no title is supplied, either the OBJECT value stored in the image header or a default string is used (the title is restricted to a maximum length of 32 characters).
To specify which frame to draw to, either use the package variable $iisframe, or the FRAME option.
Draws a circle on a IIS device (e.g. SAOimage/Ximtool)
(x(),y(),radius(),colour())
iiscirc $x, $y, [$radius, $colour]
Draws circles on the IIS device with specied points and colours. Because
this module uses
the PDL::PP
PDL::PP manpage threading you can supply lists of points via
1D arrays, etc.
An amusing PDL idiom is:
perldl> iiscirc iiscur
Note the colours are the same as IRAF, viz:
201 = cursor color (white) 202 = black 203 = white 204 = red 205 = green 206 = blue 207 = yellow 208 = cyan 209 = magenta 210 = coral 211 = maroon 212 = orange 213 = khaki 214 = orchid 215 = turquoise 216 = violet 217 = wheat
Return cursor position from an IIS device (e.g. SAOimage/Ximtool)
($x,$y) = iiscur($ch)
This function puts up an interactive cursor on the IIS device and returns the ($x,$y) position and the character typed ($ch) by the user.
Display an image (uses pgimag()/pggray() as appropriate)
Usage: imag ( $image, [$min, $max, $transform], [$opt] )
Notes: $transform for image/cont etc. is used in the same way as the TR() array in the underlying PGPLOT FORTRAN routine but is, fortunately, zero-offset.
There are several options related to scaling. By default, the image is scaled to fit the PGPLOT default viewport on the screen. Scaling, aspect ratio preservation, and 1:1 pixel mapping are available. (1:1 pixel mapping GREATLY increases the speed of pgimag, and is useful for, eg, movie display; but it's not recommended for final output as it's not device-independent.)
Options recognised:
ITF - the image transfer function applied to the pixel values. It
may be one of 'LINEAR', 'LOG', 'SQRT' (lower case is
acceptable). It defaults to 'LINEAR'.
MIN - Sets the minimum value to be used for calculation of the
display stretch
MAX - Sets the maximum value for the same
TRANSFORM - The transform 'matrix' as a 6x1 vector for display
PIX - Sets the image pixel aspect ratio. By default, imag
stretches the image pixels so that the final image aspect
ratio fits the viewport exactly. Setting PIX=>1 causes
the image aspect ratio to be preserved. (the image is
scaled to avoid cropping, unless you specify scaling
manually). Larger numbers yield "landscape mode" pixels.
PITCH - Sets the number of image pixels per screen unit, in the Y
direction. The X direction is determined by PIX, which
defaults to 1 if PITCH is specified and PIX is not. PITCH
causes UNIT to default to "inches" so that it's easy to say
100dpi by specifying {PITCH=>100}. Larger numbers yield
higher resolution (hence smaller appearing) images.
UNIT - Sets the screen unit used for scaling. Must be one of the
PGPLOT supported units (inch, mm, pixel, normalized). You
can refer to them by name or by number. Defaults to pixels
if not specified.
SCALE - Syntactic sugar for the reciprocal of PITCH. Makes the
UNIT default to "pixels" so you can say "{SCALE=>1}"
to see your image in device pixels. Larger SCALEs lead
to larger appearing images.
The following standard options influence this command:
AXIS, BORDER, JUSTIFY
To see an image with maximum size in the current window, but square
pixels, say:
imag $a,{PIX=>1}
An alternative approach is to try:
imag $a,{JUSTIFY=>1}
To see the same image, scaled 1:1 with device pixels, say:
imag $a,{SCALE=>1}
To see an image made on a device with 1:2 pixel aspect ratio, with
X pixels the same as original image pixels, say
imag $a,{PIX=>0.5,SCALE=>2}
To display an image at 100 dpi on any device, say:
imag $a,{PITCH=>100}
To display an image with 100 micron pixels, say:
imag $a,{PITCH=>10,UNIT=>'mm'}
Display an image with correct aspect ratio
Usage: imag1 ( $image, [$min, $max, $transform], [$opt] )
Notes: This is syntactic sugar for imag({PIX=>1}).
3D rendered image plot, defined by a variety of contexts
imag3d piddle(3,x,y), {OPTIONS}
imag3d [piddle,...], {OPTIONS}
Example:
perldl> imag3d [sqrt(rvals(zeroes(50,50))/2)], {{Lines=>0};
- Rendered image of surface
See module documentation for more information on contexts and options
2D TrueColor Image plot
imagrgb piddle(3,x,y), {OPTIONS}
imagrgb [piddle,...], {OPTIONS}
This would be used to plot an image, specifying red, green and blue values at each point. Note: contexts are very useful here as there are many ways one might want to do this.
e.g.
perldl> $a=sqrt(rvals(zeroes(50,50))/2) perldl> imagrgb [0.5*sin(8*$a)+0.5,0.5*cos(8*$a)+0.5,0.5*cos(4*$a)+0.5]
2D TrueColor Image plot as an object inside a 3D space
imagrdb3d piddle(3,x,y), {OPTIONS}
imagrdb3d [piddle,...], {OPTIONS}
The piddle gives the colors. The option allowed is Points, which should give 4 3D coordinates for the corners of the polygon, either as a piddle or as array ref. The default is [[0,0,0],[1,0,0],[1,1,0],[0,1,0]].
e.g.
perldl> imagrgb3d $colors, {Points => [[0,0,0],[1,0,0],[1,0,1],[0,0,1]]};
- plot on XZ plane instead of XY.
Signature: (a(); int ind(); [o] sum(m))
Threaded Index Add: Add a to the ind element of sum, i.e:
sum(ind) += a
Simple Example:
$a = 2; $ind = 3; $sum = zeroes(10); indadd($a,$ind, $sum); print $sum #Result: ( 2 added to element 3 of $sum) # [0 0 0 2 0 0 0 0 0 0]
Threaded Example:
$a = pdl( 1,2,3); $ind = pdl( 1,4,6); $sum = zeroes(10); indadd($a,$ind, $sum); print $sum."\n"; #Result: ( 1, 2, and 3 added to elements 1,4,6 $sum) # [0 1 0 0 2 0 3 0 0 0]
Signature: (a(n); int ind(); [oca] c())
These functions provide rudimentary index indirection.
$c = a(ind()); $c = a(ind1(),ind2());
It would be useful to have a more complete function for this at some point, or at least a perl wrapper, that allows
$c = $a->islice("1:2",$ind1,"3:4",$ind2");
with many dimensions.
This function is two-way, i.e. after
$c = $a->index(pdl[0,5,8]); $c .= pdl [0,2,4];
the changes in $c will flow back to $a.
Signature: (a(na,nb); int inda(); int indb(); [oca] c())
These functions provide rudimentary index indirection.
$c = a(ind()); $c = a(ind1(),ind2());
It would be useful to have a more complete function for this at some point, or at least a perl wrapper, that allows
$c = $a->islice("1:2",$ind1,"3:4",$ind2");
with many dimensions.
This function is two-way, i.e. after
$c = $a->index(pdl[0,5,8]); $c .= pdl [0,2,4];
the changes in $c will flow back to $a.
Complex inplace inverse FFT (complex input, complex output).
$pdl_cplx = infftw $pdl_cplx;
Return formatted information about a piddle.
$x->info($format_string);
print $x->info("Type: %T Dim: %-15D State: %S");
Returns a string with info about a piddle. 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
$obj = init PDL::Func( Interpolate => "Hermite", x => $x, y => $y );
$obj = init PDL::Func( { x => $x, y => $y } );
Create a PDL::Func object, which can interpolate, and possibly integrate and calculate gradients of a dataset.
If not specified, the value of Interpolate is taken to be
Linear, which means the interpolation is performed by
the interpolate entry in the PDL::Primitive::interpolate
PDL::Primitive manpage.
A value of Hermite uses piecewise cubic Hermite functions,
which also allows the integral and gradient of the data
to be estimated.
Signature: (a(n); b(n); [o]c(); )
Inner product over one dimension
c = sum_i a_i * b_i
Signature: (a(n); b(n,m); c(m); [o]d())
Inner product of two vectors and a matrix
d = sum_ij a(i) b(i,j) c(j)
Note that you should probably not thread over a and c since that would be very wasteful. Instead, you should use a temporary for b*c.
Signature: (a(n,m); b(n,m); [o]c())
Inner product over 2 dimensions.
Equivalent to
$c = inner($a->clump(2), $b->clump(2))
Signature: (a(j,n); b(n,m); c(m,k); [t]tmp(n,k); [o]d(j,k)))
Efficient Triple matrix product a*b*c
Efficiency comes from by using the temporary tmp. This operation only scales as
N**3 whereas threading using the inner2 entry in the inner2
manpage would scale as N**4.
The reason for having this routine is that you do not need to have the same thread-dimensions for tmp as for the other arguments, which in case of large numbers of matrices makes this much more memory-efficient.
It is hoped that things like this could be taken care of as a kind of closures at some point.
Signature: (a(n); b(n); c(n); [o]d(); )
Weighted (i.e. triple) inner product
d = sum_i a(i) b(i) c(i)
Flag a piddle so that the next operation is done 'in place'
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).
perldl> $x = xvals zeroes 10; perldl> log10(inplace $x) perldl> p $x [ -Inf 0 0.30103 0.47712125 0.60205999 0.69897 0.77815125 0.84509804 0.90308999 0.95424251]
Real inplace inverse FFT. Have a look at nrfftw to understand the format. USE ONLY an even first dimension size! (complex input, real output)
$pdl_real = infftw $pdl_cplx;
my $ans = $obj->integrate( index => pdl( 2, 5 ) ); my $ans = $obj->integrate( x => pdl( 2.3, 4.5 ) );
Integrate the function stored in the PDL::Func object, if the scheme is Hermite.
The integration can either be between points of the original x array (index), or arbitrary x values (x). For both cases, a two element piddle should be given, to specify the start and end points of the integration.
If the status method returns a value of
1, then
one or both of the integration limits did not
lie inside the x array. Caveat emptor with the
result in such a case.
Make an RGB image from a palette image and its lookup table.
$rgb = $palette_im->interlrgb($lut)
Input should be of an integer type and the lookup table (3,x,...). Will perform the lookup for any N-dimensional input pdl (i.e. 0D, 1D, 2D, ...). Uses the index command but will not dataflow by default. If you want it to dataflow the dataflow_forward flag must be set in the $lut piddle (you can do that by saying $lut->set_dataflow_f(1)).
Signature: (xi(); x(n); y(n); [o] yi())
routine for 1D linear interpolation
$yi = interpol($xi, $x, $y)
interpol uses the same search method as the interpolate entry in the interpolate
manpage,
hence $x must be strictly ordered (either increasing or decreasing).
The difference occurs in the handling of out-of-bounds values; here
an error message is printed.
Signature: (xi(); x(n); y(n); [o] yi(); int [o] err())
routine for 1D linear interpolation
( $yi, $err ) = interpolate($xi, $x, $y)
Given a set of points ($x,$y), use linear interpolation to find the values $yi at a set of points $xi.
interpolate uses a binary search to find the suspects, er..., interpolation indices and therefore abscissas (ie $x) have to be strictly ordered (increasing or decreasing). For interpolation at lots of closely spaced abscissas an approach that uses the last index found as a start for the next search can be faster (compare Numerical Recipes hunt routine). Feel free to implement that on top of the binary search if you like. For out of bounds values it just does a linear extrapolation and sets the corresponding element of $err to 1, which is otherwise 0.
See also the interpol entry in the interpol
manpage, which uses the same routine,
differing only in the handling of extrapolation -- an error message
is printed rather than returning an error piddle.
my $yi = $obj->interpolate( $xi );
Returns the interpolated function at a given set of points (PDL::Func).
A status value of
1, as returned by the status method,
means that some of the $xi points lay outside the
range of the data. The values for these points
were calculated by extrapolation (the details depend on the
scheme being used).
Signature: (a(n); int+ [o]b())
Project via integral to N-1 dimensions
This function reduces the dimensionality of a piddle by one by taking the integral along the 1st dimension.
By using the xchg entry in the xchg
PDL::Slices manpage etc. it is possible to use
any dimension.
$a = intover($b);
$spectrum = intover $image->xchg(0,1)
Notes:
For n > 3, these are all O(h^4) (like Simpson's rule), but are integrals between the end points assuming the pdl gives values just at these centres: for such `functions', sumover is correct to O(h), but is the natural (and correct) choice for binned data, of course.
Real inverse FFT. Have a look at rfftw to understand the format. USE ONLY an even n1! (complex input, real output)
$pdl_real = ifftw $pdl_cplx;
Determine endianness of machine -- returns 0 or 1 accordingly
Test whether a piddle is empty
print "The piddle has zero dimension\n" if $pdl->isempty;
This function returns 1 if the piddle 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 piddle has zero dimension.
perldl> $a=sequence(10) perldl> $i=which($a < -1) perldl> print "I found no matches!\n" if ($a->isempty);
Note that having zero elements is rather different from the concept
of being a null piddle, see the the PDL::FAQ
PDL::FAQ manpage and
the PDL::Indexing
PDL::Indexing manpage
manpages for discussions of this.
Return cursor position from a Karma application (e.g. kview/xray)
($x,$y) = kcur($ch, {App=>'karma-app',Coords=>"World|Pixel"})
This function connects to a Karma application and returns the ($x,$y) position and the character typed ($ch) by the user. By default world coordinates are returned.
print kcur {App=>"kview", Coords=>"World"}
`centre' a kernel (auxiliary routine to fftconvolve)
$kernel = kernctr($image,$smallk);
fftconvolve($image,$kernel);
kernctr centres a small kernel to emulate the behaviour of the direct convolution routines.
Module: PDL::Graphics::Karma
Sends piddle data array to an external Karma application for viewing
kim($pdl, [$karma-app, $lut])
Sends $pdl data to Karma application viewer. Remembers the last one used [default: kview].
Starts external Karma application koords
koords([OPTIONS])
perldl> kview (-num_col => 42) perldl> xray
Signature: (x(); y(); r(); ell(); PA(); fill(); int id(); char* karma_app; char* colour; int coordtype; int dotext)
Overlay graphics markers on a Karma application (e.g. kview)
koverlay $x, $y, {Options...}
Currently the only markers supported are ellipses. The default is a circle of radius 10 units,
$x = 10
xvals(10);
koverlay $x, sqrt($x), {Radius=>$x/3, Colour=>'green', App=>'kpolar'}
Radius - [piddle] specify radius of ellipses (major axis if ellipse). Default = 10 units.
Ellip - [piddle] specify ellipticity of ellipses. Default = 0 i.e. circle.
PA - [piddle] specify principle axis (degrees rotation anticlockwise
from the Y axis). Default.
ID - [piddle] Numeric integer id labels to apply.
Colour - [string] Colour name for overlay (e.g. 'red'). Default = 'blue'
App - [string] name of Karma app to send too
Fill - [piddle] whether outlines are filled (0 or 1). (Note filled,
ellipses are not yet available in Karma).
Coords - [string] "World" or "Pixel" - type of coordinates for x/y/r.
Note pixel implementation rounds to nearest pixel due
to Karma overlays not supporting proper IMAGE_PIXEL
coordinates.
Starts external Karma application kpvslice
kpvslice([OPTIONS])
perldl> kview (-num_col => 42) perldl> xray
Starts external Karma application krenzo
krenzo([OPTIONS])
perldl> kview (-num_col => 42) perldl> xray
krgb($lut, [$karma-app])
Sends RGB image to an external Karma application for viewing
Does not change current default viewer.
Starts external Karma application kshell
kshell([OPTIONS])
perldl> kview (-num_col => 42) perldl> xray
Starts external Karma application kslice_3d
kslice_3d([OPTIONS])
perldl> kview (-num_col => 42) perldl> xray
kstarted([$karma-app])
Tests if a Karma application is running.
It tries to connect to the karma application, returns 1 on success, 0 otherwise
Can be used to check if a karma application has already been started, e.g.
xray unless kstarted 'xray';
Starts external Karma application kview
kview([OPTIONS])
perldl> kview (-num_col => 42) perldl> xray
Signature: (P(); C(); int nthdim; int step; int n)
Returns a piddle of lags to parent.
I.e. if $a contains
[0,1,2,3,4,5,6,7]
then
$b = $a->lags(0,2,2);
is a (5,2) matrix
[2,3,4,5,6,7] [0,1,2,3,4,5]
This order of returned indices is kept because the function is called ``lags'' i.e. the nth lag is n steps behind the original.
alias for mesh3d
Signature: (a(); b(); [o] c())
clip $a by $b ($b is lower bound)
Module: PDL::Ops
Signature: (a(); b(); [o]c(); int swap)
the binary <= (less equal) operation
$c = le $a, $b, 0; # explicit call with trailing 0 $c = $a <= $b; # overloaded call $a->inplace->le($b,0); # modify $a inplace
It can be made to work inplace with the $a->inplace syntax. This function is used to overload the binary <= operator. Note that when calling this function explicitly you need to supply a third argument that should generally be zero (see first example). This restriction is expected to go away in future releases.
Signature: (a(); [o]b(); int[o]s())
log gamma function
This returns 2 piddles -- the first set gives the log(gamma) values, while the second set, of integer values, gives the sign of the gamma function. This is useful for determining factorials, amongst other things.
Plot vector as connected points
If the 'MISSING' option is specified, those points in the $y vector which are equal to the MISSING value are not plotted, but are skipped over. This allows one to quickly draw multiple lines with one call to line, for example to draw coastlines for maps.
Usage: line ( [$x,] $y, [$opt] )
The following standard options influence this command:
AXIS, BORDER, COLO(U)R, JUSTIFY, LINESTYLE, LINEWIDTH, MISSING
$x = sequence(10)/10.;
$y = sin($x)**2;
# Draw a red dot-dashed line
line $x, $y, {COLOR => 'RED', LINESTYLE=>3};
3D line plot, defined by a variety of contexts.
line3d piddle(3,x), {OPTIONS}
line3d [CONTEXT], {OPTIONS}
Example:
perldl> line3d [sqrt(rvals(zeroes(50,50))/2)] - Lines on surface perldl> line3d [$x,$y,$z] - Lines over X, Y, Z perldl> line3d $coords - Lines over the 3D coordinates in $coords.
Note: line plots differ from mesh plots in that lines only go in one direction. If this is unclear try both!
See module documentation for more information on contexts and options
Convert piddle to perl list
@tmp = list $x;
Obviously this is grossly inefficient for the large datasets PDL is designed to handle. This was provided as a get out while PDL matured. It should now be mostly superseded by superior constructs, such as PP/threading. However it is still occasionally useful and is provied for backwards compatibility.
for (list $x) {
# Do something on each value...
}
Convert piddle indices to perl list
@tmp = listindices $x;
@tmp now contains the values 0..nelem($x).
Obviously this is grossly inefficient for the large datasets PDL is designed to handle. This was provided as a get out while PDL matured. It should now be mostly superseded by superior constructs, such as PP/threading. However it is still occasionally useful and is provied for backwards compatibility.
for $i (listindices $x) {
# Do something on each value...
}
Levenberg-Marquardt fitting of a user supplied model function
($ym,$a,$covar,$iters) =
lmfit $x, $y, $sig, \&expfunc, $a, {Maxiter => 300, Eps => 1e-3};
Options:
Maxiter: maximum number of iterations before giving up
Eps: convergence citerium for fit; success when normalized change
in chisquare smaller than Eps
The user supplied sub routine reference should accept 4 arguments
As an example take this definition of a single exponential with 3 parameters (width, amplitude, offset):
sub expdec {
my ($x,$par,$ym,$dyda) = @_;
my ($a,$b,$c) = map {$par->slice("($_)")} (0..2);
my $arg = $x/$a;
my $ex = exp($arg);
$ym .= $b*$ex+$c;
my (@dy) = map {$dyda->slice(",($_)")} (0..2);
$dy[0] .= -$b*$ex*$arg/$a;
$dy[1] .= $ex;
$dy[2] .= 1;
}
Note usage of the .= operator for assignment
In scalar context returns a vector of the fitted dependent variable. In list context returns fitted y-values, vector of fitted parameters, an estimate of the covariance matrix (as an indicator of goodness of fit) and number of iterations performed.
Loads the wisdom from a file for better FFTW performance.
The wisdom is automatically saved when the program ends. It will be automagically called when the variable $PDL::FFT::wisdom is set to a file name. For example, the following is a useful idiom to have in your .perldlrc file:
$PDL::FFT::wisdom = "$ENV{HOME}/.fftwisdom"; # save fftw wisdom in this file
Explicit usage:
load_wisdom($fname);
Module: PDL::Ops
Signature: (a(); [o]b())
the natural logarithm
$b = log $a; $a->inplace->log; # modify $a inplace
It can be made to work inplace with the $a->inplace syntax. This function is used to overload the unary log operator/function.
Convert to long datatype -- see 'Datatype_conversions'
Module: PDL::Ops
Signature: (a(); b(); [o]c(); int swap)
the binary < (less than) operation
$c = lt $a, $b, 0; # explicit call with trailing 0 $c = $a < $b; # overloaded call $a->inplace->lt($b,0); # modify $a inplace
It can be made to work inplace with the $a->inplace syntax. This function is used to overload the binary < operator. Note that when calling this function explicitly you need to supply a third argument that should generally be zero (see first example). This restriction is expected to go away in future releases.
Load in the requested colour table and intensity ramp.
( $l, $r, $g, $b ) = lut_data( $table, [ $reverse, [ $ramp ] ] );
Returns the levels and r, g, b components of the colour table $table. If $reverse is 1 (defaults to 0 if not supplied), then the r, g, and b components are reversed before being returned. If not supplied, $ramp defaults to "ramp" (this is a linear intensity ramp).
The returned values are piddles containing values in the range 0 to 1 inclusive, and are floats.
Return, as a list, the names of the available colour tables.
@tables = lut_names();
Return, as a list, the names of the available intensity ramps.
@ramps = lut_names();
Make sure the data portion of a piddle can be accessed from XS code.
$a->make_physical; $a->call_my_xs_method;
Ensures that a piddle gets its own allocated copy of data. This obviously
implies that there are certain piddles which do not have their own data.
These are so called virtual piddles that make use of the vaffine
optimisation (see the PDL::Indexing
PDL::Indexing manpage).
They do not have their own copy of
data but instead store only access information to some (or all) of another
piddle's data.
Note: this function should not be used unless absolutely neccessary
since otherwise memory requirements might be severly increased. Instead
of writing your own XS code with the need to call make_physical you
might want to consider using the PDL preprocessor
(see the PDL::PP
PDL::PP manpage)
which can be used to transparently access virtual piddles without the
need to physicalise them (though there are exceptions).
Memory map a binary file with flexible format specification
($x,$y,...) = mapflex("filename" [, $hdr] [, $opts])
Memory map a raw format binary file (see the module docs also)
$pdl3 = mapfraw("fname2",{ReadOnly => 1});
The mapfraw command supports the following options (not all combinations make sense):
Memory map a text file (see the module docs also).
Note that this function maps the raw format so if you are using an operating system which does strange things to e.g. line delimiters upon reading a text file, you get the raw (binary) representation.
The file doesn't really need to be text but it is just mapped as one large binary chunk.
This function is just a convenience wrapper which firsts stats the file and sets the dimensions and datatype.
$pdl4 = maptextfraw("fname", {options}
The options other than Dims, Datatype of mapfraw are supported.
Inverse of a square matrix
($inv) = matinv($mat)
Signature: (a(x,y),b(y,z),[o]c(x,z))
Matrix multiplication
We peruse the inner product to define matrix multiplication via a threaded inner product
Module: PDL::Primitive
Return the maximum of all elements in a piddle
$x = max($data);
Signature: (a(m,n); [o]val(); int [o]x(); int[o]y())
Return value/position of maximum value in 2D image
Contributed by Tim Jeness
Signature: (a(n); [o]c())
Project via maximum to N-1 dimensions
This function reduces the dimensionality of a piddle by one by taking the maximum along the 1st dimension.
By using the xchg entry in the xchg
PDL::Slices manpage etc. it is possible to use
any dimension.
$a = maximum($b);
$spectrum = maximum $image->xchg(0,1)
Signature: (a(n); int[o]c())
Like maximum but returns the index rather than the value
Signature: (a(n); int[o]c(m))
Returns the index of m maximum elements
Find minimum and maximum and their indices for a given piddle;
perldl> $a=pdl [[-2,3,4],[1,0,3]] perldl> ($min, $max, $min_ind, $max_ind)=minmaximum($a) perldl> p $min, $max, $min_ind, $max_ind [-2 0] [4 3] [0 1] [2 2]
See also the minmax entry in the minmax
manpage, which clumps the piddle together.
Signature: (a(m,n); kern(p,q); [o]b(m,n); int opt)
2D median-convolution of an array with a kernel (smoothing)
Note: only points in the kernel >0 are included in the median, other points are weighted by the kernel value (medianing lots of zeroes is rather pointless)
$new = med2d $old, $kernel, {OPTIONS}
$smoothed = med2d $image, ones(3,3), {Boundary => Reflect}
Boundary - controls what values are assumed for the image when kernel
crosses its edge:
=> Default - periodic boundary conditions (i.e. wrap around axis)
=> Reflect - reflect at boundary
=> Truncate - truncate at boundary
Return the median of all elements in a piddle
$x = median($data);
Signature: (a(n); [o]b(); [t]tmp(n))
Project via median to N-1 dimensions
This function reduces the dimensionality of a piddle by one by taking the median along the 1st dimension.
By using the xchg entry in the xchg
PDL::Slices manpage etc. it is possible to use
any dimension.
$a = medover($b);
$spectrum = medover $image->xchg(0,1)
3D mesh plot, defined by a variety of contexts
mesh3d piddle(3,x,y), {OPTIONS}
mesh3d [piddle,...], {OPTIONS}
Example:
perldl> mesh3d [sqrt(rvals(zeroes(50,50))/2)]
- mesh of surface
Note: a mesh is defined by two sets of lines at right-angles (i.e. this is how is differs from line3d).
See module documentation for more information on contexts and options
Module: PDL::Primitive
Return the minimum of all elements in a piddle
$x = min($data);
Signature: (a(n); [o]c())
Project via minimum to N-1 dimensions
This function reduces the dimensionality of a piddle by one by taking the minimum along the 1st dimension.
By using the xchg entry in the xchg
PDL::Slices manpage etc. it is possible to use
any dimension.
$a = minimum($b);
$spectrum = minimum $image->xchg(0,1)
Signature: (a(n); int[o]c())
Like minimum but returns the index rather than the value
Signature: (a(n); int[o]c(m))
Returns the index of m minimum elements
Returns an array with minimum, maximum of a piddle.
($mn, $mx) = minmax($pdl);
Return $mn as minimum, $mx as maximum, $mn_ind as the index of minimum and $mx_ind as the index of the maximum.
perldl> $x = pdl [1,-2,3,5,0] perldl> ($min, $max) = minmax($x); perldl> p "$min $max\n"; -2 5
Signature: (a(n); [o]cmin(); [o] cmax(); int [o]cmin_ind(); int [o]cmax_ind())
info not available
Signature: (a(); b(); [o]c(); int swap)
subtract two piddles
$c = minus $a, $b, 0; # explicit call with trailing 0 $c = $a - $b; # overloaded call $a->inplace->minus($b,0); # modify $a inplace
It can be made to work inplace with the $a->inplace syntax. This function is used to overload the binary - operator. Note that when calling this function explicitly you need to supply a third argument that should generally be zero (see first example). This restriction is expected to go away in future releases.
Signature: (a(); b(); [o]c(); int swap)
elementwise modulo operation
$c = $a->modulo($b,0); # explicit function call $c = $a % $b; # overloaded use $a->inplace->modulo($b,0); # modify $a inplace
It can be made to work inplace with the $a->inplace syntax. This function is used to overload the binary op% function. Note that when calling this function explicitly you need to supply a third argument that should generally be zero (see first example). This restriction is expected to go away in future releases.
Convenience interface to the section on PDL::Slice/slice in the slice
manpage,
allowing easier inclusion of dimensions in perl code.
$a = $x->mslice(...);
# below is the same as $x->slice("5:7,:,3:4:2")
$a = $x->mslice([5,7],X,[3,4,2]);
Signature: (a(); b(); [o]c(); int swap)
multiply two piddles
$c = mult $a, $b, 0; # explicit call with trailing 0 $c = $a * $b; # overloaded call $a->inplace->mult($b,0); # modify $a inplace
It can be made to work inplace with the $a->inplace syntax. This function is used to overload the binary * operator. Note that when calling this function explicitly you need to supply a third argument that should generally be zero (see first example). This restriction is expected to go away in future releases.
Module: PDL::Slices
Signature: (P(); C(); int n1; int n2)
move a dimension to another position
The command
$b = $a->mv(4,1);
creates $b to be like $a except that the dimension 4 is moved to the place 1, so:
$b->at(1,2,3,4,5,6) == $a->at(1,5,2,3,4,6);
The other dimensions are moved accordingly. Negative dimension indices count from the end.
Signature: (a(); [o]b())
The value for which the area under the
Gaussian probability density function (integrated from
minus infinity) is equal to the argument (cf the erfi entry in the erfi
manpage)
Module: PDL::Ops
Signature: (a(); b(); [o]c(); int swap)
binary not equal to operation (!=)
$c = ne $a, $b, 0; # explicit call with trailing 0 $c = $a != $b; # overloaded call $a->inplace->ne($b,0); # modify $a inplace
It can be made to work inplace with the $a->inplace syntax. This function is used to overload the binary != operator. Note that when calling this function explicitly you need to supply a third argument that should generally be zero (see first example). This restriction is expected to go away in future releases.
Return the number of elements in a piddle
$n = nelem($piddle); $n = $piddle->nelem;
$mean = sum($data)/nelem($data);
Module: PDL::Char
Function to create a byte PDL from a string, list of strings, list of list of strings, etc.
# create a new PDL::Char from a perl array of strings $strpdl = PDL::Char->new( ['abc', 'def', 'ghij'] );
# Convert a PDL of type 'byte' to a PDL::Char $strpdl1 = PDL::Char->new (sequence (byte, 4, 5)+99);
$pdlchar3d = PDL::Char->new([['abc','def','ghi'],['jkl', 'mno', 'pqr']]);
Module: PDL::Core
new piddle constructor method
$x = PDL->new(SCALAR|ARRAY|ARRAY REF);
$x = PDL->new(42); $y = new PDL [1..10];
Constructs piddle from perl numbers and lists.
Internal method: create piddle by specification
This is the argument processing method called by the zeroes entry in the zeroes
manpage
and some other functions
which constructs piddles from argument listss of the form:
[type], $nx, $ny, $nz,...
Complex inplace FFT (complex input, complex output).
$pdl_cplx = nfftw $pdl_cplx;
N-dimensional interpolation routine
Signature: ninterpol(point(),data(n),[o]value())
$value = ninterpol($point, $data);
ninterpol uses interpol to find a linearly interpolated value in N dimensions, assuming the data is spread on a uniform grid. To use an arbitrary grid distribution, need to find the grid-space point from the indexing scheme, then call ninterpol -- this is far from trivial (and ill-defined in general).
Signature: (vec(n); [o] norm(n))
Normalises a vector to unit Euclidean length
Module: PDL::Ops
Signature: (a(); [o]b())
the elementwise not operation
$b = ! $a; $a->inplace->not; # modify $a inplace
It can be made to work inplace with the $a->inplace syntax. This function is used to overload the unary ! operator/function.
Real inplace FFT. If you want a transformation on a piddle
with dimensions [n1,n2,....] you MUST pass in a piddle
with dimensions [2
(n1/2+1),n2,...] (real input, complex output).
Use with care due to dimension restrictions mentioned below. For details check the html docs that come with the fftw library.
$pdl_cplx = nrfftw $pdl_real;
Returns a 'null' piddle.
$x = null;
null() has a special meaning to the section on in the PDL::PP
PDL::PP manpage. It is used to
flag a special kind of empty piddle, which can grow to
appropriate dimensions to store a result (as opposed to
storing a result in an existing piddle).
perldl> sumover sequence(10,10), $ans=null;p $ans [45 145 245 345 445 545 645 745 845 945]
Returns a 'null' piddle.
$x = PDL->nullcreate($arg)
This is an routine used by many of the threading primitives
(i.e. the sumover entry in the sumover
PDL::Primitive manpage,
the minimum entry in the minimum
PDL::Primitive manpage, etc.) to generate a null piddle for the
function's output that will behave properly for derived (or
subclassed) PDL objects.
For the above usage: If $arg is a PDL, or a derived PDL, then $arg->null is returned. If $arg is a scalar (i.e. a zero-dimensional PDL) then $PDL->null is returned.
PDL::Derived->nullcreate(10) returns PDL::Derived->null. PDL->nullcreate($pdlderived) returns $pdlderived->null.
Return the oddmedian of all elements in a piddle
$x = oddmedian($data);
Signature: (a(n); [o]b(); [t]tmp(n))
Project via oddmedian to N-1 dimensions
This function reduces the dimensionality of a piddle by one by taking the oddmedian along the 1st dimension.
By using the xchg entry in the xchg
PDL::Slices manpage etc. it is possible to use
any dimension.
$a = oddmedover($b);
$spectrum = oddmedover $image->xchg(0,1)
The median is sometimes not a good choice as if the array has an even number of elements it lies half-way between the two middle values -- thus it does not always correspond to a data value. The lower-odd median is just the lower of these two values and so it ALWAYS sits on an actual data value which is useful in some circumstances.
Converts a one dimensional index piddle to a set of ND coordinates
@coords=one2nd($a, $indices)
returns an array of piddles containing the ND indexes corresponding to
the one dimensional list indices. The indices are assumed to correspond
to array $a clumped using clump(-1). This routine is used in
the whichND entry in the whichND
manpage,
but is useful on its own occasionally.
perldl> $a=pdl [[[1,2],[-1,1]], [[0,-3],[3,2]]]; $c=$a->clump(-1) perldl> $maxind=maximum_ind($c); p $maxind; 6 perldl> print one2nd($a, maximum_ind($c)) 0 1 1 perldl> p $a->at(0,1,1) 3
construct a one filled piddle
$a = ones([type], $nx, $ny, $nz,...); etc. (see 'zeroes')
see zeroes() and add one
Signature: (P(); C(); int nth; int from; int step; int nsteps)
experimental function -- not for public use
$a = oneslice();
This is not for public use currently. See the source if you have to. This function can be used to accomplish run-time changing of transformations i.e. changing the size of some piddle at run-time.
However, the mechanism is not yet finalized and this is just a demonstration.
Module: PDL::Primitive
Return the logical or of all elements in a piddle
$x = or($data);
Module: PDL::Ops
Signature: (a(); b(); [o]c(); int swap)
binary or of two piddles
$c = or2 $a, $b, 0; # explicit call with trailing 0 $c = $a | $b; # overloaded call $a->inplace->or2($b,0); # modify $a inplace
It can be made to work inplace with the $a->inplace syntax. This function is used to overload the binary | operator. Note that when calling this function explicitly you need to supply a third argument that should generally be zero (see first example). This restriction is expected to go away in future releases.
Signature: (a(n); int+ [o]b())
Project via or to N-1 dimensions
This function reduces the dimensionality of a piddle by one by taking the or along the 1st dimension.
By using the xchg entry in the xchg
PDL::Slices manpage etc. it is possible to use
any dimension.
$a = orover($b);
$spectrum = orover $image->xchg(0,1)
Signature: (a(n); b(m); [o]c(n,m); )
outer product over one dimension
Naturally, it is possible to achieve the effects of outer product simply by threading over the ``*'' operator but this function is provided for convenience.
Signature: (a(m,n); int bad(m,n); [o]b(m,n))
patch bad pixels out of 2D images,
$patched = patch2d $data, $bad;
$bad is a 2D mask array where 1=bad pixel 0=good pixel. Pixels are replaced by the average of their non-bad neighbours.
Signature: (int l();c();[o]tc(bar);a(foo))
Convert the polfit coefficients to Taylor series form. c and a() must be of the same type.
Module: PDL::Core
piddle constructor -- creates new piddle from perl scalars/arrays
$a = pdl(SCALAR|ARRAY REFERENCE|ARRAY);
$a = pdl [1..10]; # 1D array $a = pdl ([1..10]); # 1D array $a = pdl (1,2,3,4); # Ditto $b = pdl [[1,2,3],[4,5,6]]; # 2D 3x2 array $b = pdl 42 # 0-dimensional scalar $c = pdl $a; # Make a new copy $a = pdl([1,2,3],[4,5,6]); # 2D $a = 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 []
pdl() is a functional synonym for the 'new' constructor, e.g.:
$x = new PDL [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.
Signature: (a(); b(); [o]c(); int swap)
add two piddles
$c = plus $a, $b, 0; # explicit call with trailing 0 $c = $a + $b; # overloaded call $a->inplace->plus($b,0); # modify $a inplace
It can be made to work inplace with the $a->inplace syntax. This function is used to overload the binary + operator. Note that when calling this function explicitly you need to supply a third argument that should generally be zero (see first example). This restriction is expected to go away in future releases.
Signature: (type(); byte+ [o] im(m,n); int ms => m; int ns => n;
int format; char* fd)
Read in an ascii pnm file.
Signature: (type(); byte+ [o] im(m,n); int ms => m; int ns => n;
int isbin; char* fd)
Read in a raw pnm file.
read a raw pnm file. The type argument is only there to determine the type of the operation when creating im or trigger the appropriate type conversion (maybe we want a byte+ here so that im follows strictly the type of type).
Signature: (a(m); int israw; int isbin; char *fd)
Write a line of pnm data.
This function is implemented this way so that threading works naturally.
Signature: (a(n,n);rcond();[o]z(n);int [o]info())
Factor a real symmetric positive definite matrix and estimate the condition number of the matrix.
Signature: (a(n,n);[o]det(two=2);int job())
Compute the determinant and inverse of a certain real
symmetric positive definite matrix using the factors
computed by the poco entry in the poco
manpage.
Plot vector as points
Usage: points ( [$x,] $y, [$symbol(s)], [$opt] )
Options recognised:
SYMBOL - Either a piddle with the same dimensions as $x, containing
the symbol associated to each point or a number specifying
the symbol to use for every point, or a name specifying the
symbol to use according to the following (recognised name in
capital letters):
0 - SQUARE 1 - DOT 2 - PLUS 3 - ASTERISK
4 - CIRCLE 5 - CROSS 7 - TRIANGLE 8 - EARTH
9 - SUN 11 - DIAMOND 12- STAR
PLOTLINE - If this is >0 a line will be drawn through the points.
The following standard options influence this command:
AXIS, BORDER, CHARSIZE, COLOUR, JUSTIFY, LINESTYLE, LINEWIDTH
$y = sequence(10)**2+random(10);
# Plot blue stars with a solid line through:
points $y, {PLOTLINE => 1, COLOUR => BLUE, SYMBOL => STAR};
3D points plot, defined by a variety of contexts
points3d piddle(3), {OPTIONS}
points3d [piddle,...], {OPTIONS}
Example:
perldl> points3d [sqrt(rvals(zeroes(50,50))/2)]; - points on surface
See module documentation for more information on contexts and options
Signature: (x(n);y(n);w(n);int maxdeg();int [o]ndeg();[o]eps();[o]r(n);int [o]ierr();[o]a(foo))
Fit discrete data in a least squares sense by polynomials in one variable. x(), y() and w() must be of the same type.
Draw a polygon
Usage: poly ( $x, $y )
Options recognised:
The following standard options influence this command:
AXIS, BORDER, COLOUR, FILLTYPE, HATCHING, JUSTIFY, LINESTYLE, LINEWIDTH
# Fill with hatching in two different colours
$x=sequence(10)/10;
# First fill with cyan hatching
poly $x, $x**2, {COLOR=>5, FILL=>3};
hold;
# Then do it over again with the hatching offset in phase:
poly $x, $x**2, {COLOR=>6, FILL=>3, HATCH=>{PHASE=>0.5}};
release;
Convenience wrapper routine around the pcoef slatec function. Separates supplied arguments and return values.
Convert the polyfit/polfit coefficients to Taylor series form.
$tc = polycoef($l, $c, $a);
Signature: (int [o,nc] im(m,n); float ps(two=2,np); int col())
fill the area inside the given polygon with a given colour
This function works inplace, i.e. modifies im.
return the (dataflown) area of an image within a polygon
# increment intensity in area bounded by $poly $im->polyfillv($pol)++; # legal in perl >= 5.6 # compute average intensity within area bounded by $poly $av = $im->polyfillv($poly)->avg;
Convenience wrapper routine about the polfit slatec function. Separates supplied arguments and return values.
Fit discrete data in a least squares sense by polynomials in one variable.
($ndeg, $r, $ierr, $a) = polyfit($x, $y, $w, $maxdeg, $eps);
eps is modified to contain the rms error of the fit.
Convenience wrapper routine around the pvalue slatec function. Separates supplied arguments and return values.
For multiple input x positions, a corresponding y position is calculated.
The derivatives PDL is one dimensional (of size nder) if a single x position is supplied, two dimensional if more than one x position is supplied.
Use the coefficients generated by polyfit (or polfit) to evaluate the polynomial fit of degree l, along with the first nder of its derivatives, at a specified point.
($yfit, $yp) = polyvalue($l, $nder, $x, $a);
Used for widget initialization by Tk, this function should never be called directly
Module: PDL::Math
Signature: (a(); b(); [o]c())
Synonym for `![]()
'
Signature: (a(); b(); [o]c(); int swap)
raise piddle $a to the power b
$c = $a->power($b,0); # explicit function call $c = $a ** $b; # overloaded use $a->inplace->power($b,0); # modify $a inplace
It can be made to work inplace with the $a->inplace syntax. This function is used to overload the binary op** function. Note that when calling this function explicitly you need to supply a third argument that should generally be zero (see first example). This restriction is expected to go away in future releases.
Signature: (a(n); int+ [o]b())
Project via product to N-1 dimensions
This function reduces the dimensionality of a piddle by one by taking the product along the 1st dimension.
By using the xchg entry in the xchg
PDL::Slices manpage etc. it is possible to use
any dimension.
$a = prodover($b);
$spectrum = prodover $image->xchg(0,1)
Routine to write a PDL to an NDF by copying the extension information from an existing NDF and writing DATA,VARIANCE, QUALITY and AXIS info from a PDL (if they exist).
Extensions, labels and history are propogated from the old NDF. No new extension information is written.
This command has been superseded by the wndf() entry in the wndf()
manpage.
Signature: (int l();x();[o]yfit();[o]yp(nder);a(foo))
Use the coefficients generated by polfit to evaluate the polynomial fit of degree l, along with the first nder of its derivatives, at a specified point. x and a must be of the same type.
Module: PDL::Dbg
Print info about a piddle (or all known piddles)
perldl> PDL->px
perldl> $b += $a->clump(2)->px('clumptest')->sumover
perldl> $a->px('%C (%A) Type: %T')
This function prints some information about piddles. It can be invoked
as a class method (e.g. PDL->px ) or as an instance method (e.g.
C
$pdl->px($arg)
). If
perldl> PDL->px('PDL::Mypack')
The default package is that of the caller.
The output of px will be determined by the default formatting string that is passed to the info method (unless you pass a string containing % to px when invoking as an instance method, see above). This default string is stored in $PDL::Dbg::Infostr and the default output format can be accordingly changed by setting this variable. If you do this you should also change the default title string that the class method branch prints at the top of the listing to match your new format string. The default title is stored in the variable $PDL::Dbg::Title.
For historical reasons vars is an alias for px.
Signature: (a(n); [o]b(n))
Quicksort a vector into ascending order.
print qsort random(10);
Signature: (a(n); int [o]indx(n))
Quicksort a vector and return index of elements in ascending order.
$ix = qsorti $a; print $a->index($ix); # Sorted list
Module: PDL::Complex
Signature: (r(); [o]c(m=2))
convert real to complex, assuming an imaginary part of zero
Constructor which returns piddle of random numbers
$a = random([type], $nx, $ny, $nz,...); $a = random $b;
etc (see the zeroes entry in the zeroes
PDL::Core manpage).
This is the uniform distribution between 0 and 1 (assumedly excluding 1 itself). The arguments are the same as zeroes (q.v.) -- i.e. one can specify dimensions, types or give a template.
Constructor which returns piddle of random numbers
$a = randsym([type], $nx, $ny, $nz,...); $a = randsym $b;
etc (see the zeroes entry in the zeroes
PDL::Core manpage).
This is the uniform distribution between 0 and 1 (excluding both 0 and
1, cf the random entry in the random
manpage). The arguments are the same as zeroes (q.v.) -- i.e. one can specify dimensions, types or give a template.
Simple function to slurp in ASCII numbers quite quickly, although error handling is marginal (to nonexistent).
$pdl->rasc("filename" [,$noElements]);
Where:
filename is the name of the ASCII file to read
$noElements is the optional number of elements in the file to read.
(If not present, all of the file will be read to fill up $pdl)
# (test.num is an ascii file with 20 numbers. One number per line.)
$in = PDL->null;
$num = 20;
$in->rasc('test.num',20);
$imm = zeroes(float,20,2);
$imm->rasc('test.num');
Read ASCII whitespaced cols from a file into piddles and perl arrays (also see the rgrep() entry elsewhere in this document).
There are two calling conventions -- the old version, where a pattern can be specified after the filename/handle, and the new version where options are given as as hash reference. This reference can be given as either the second or last argument.
The default behaviour is to ignore lines beginning with a # character and lines that only consist of whitespace. Options exist to only read from lines that match, or do not match, supplied patterns, and to set the types of the created piddles.
Can take file name or
HANDLE, and if no columns are specified,
all are assumed. For the allowed types, see
the section on Datatype_conversions in the PDL::Core manpage.
Options:
EXCLUDE or IGNORE -- ignore lines matching this pattern (default '/
#/').
INCLUDE or KEEP -- only use lines which match this pattern (default '').
LINES -- which line numbers to use. Line numbers start at 0 and the syntax is 'a:b:c' to use every c'th matching line between a and b (default '').
DEFTYPE -- default data type for stored data (if not specified, use the type stored in $PDL::IO::Misc::deftype, which starts off as double).
TYPES -- reference to an array of data types, one element for each column to be read in. Any missing columns use the DEFTYPE value (default []).
PERLCOLS -- an array of column numbers which are to be read into perl arrays rather than piddles. References to these arrays are returned after the requested piddles (default undef).
Usage:
($x,$y,...) = rcols( *HANDLE|"filename", { EXCLUDE => '/^!/' },
$col1, $col2, ... )
($x,$y,...) = rcols( *HANDLE|"filename", $col1, $col2, ...,
{ EXCLUDE => '/^!/' } )
($x,$y,...) = rcols( *HANDLE|"filename", "/foo/", $col1, $col2, ... )
e.g.,
$x = PDL->rcols 'file1'; ($x,$y) = rcols *STDOUT;
# read in lines containing the string foo, where the first
# example also ignores lines that with a # character.
($x,$y,$z) = rcols 'file2', 0,4,5, { INCLUDE => '/foo/' };
($x,$y,$z) = rcols 'file2', 0,4,5,
{ INCLUDE => '/foo/', EXCLUDE => '' };
# ignore the first 27 lines of the file, reading in as ushort's
($x,$y) = rcols 'file3', { LINES => '27:-1', DEFTYPE => ushort };
($x,$y) = rcols 'file3',
{ LINES => '27:', TYPES => [ ushort, ushort ] };
# read in the first column as a perl array and the next two as piddles
($x,$y,$name) = rcols 'file4', 1, 2, { PERLCOLS => [ 0 ] };
printf "Number of names read in = %d\n", 1 + $#$name;
Notes:
1. Quotes are required on patterns.
2. Columns are separated by whitespace by default, use $PDL::IO::Misc::colsep to specify an alternate separator.
3. For PDL-2.003, the meaning of the 'c' value in the LINES option has changed: it now only counts matching lines rather than all lines as in previous versions of PDL.
4. LINES => '
1:0:3' may not work as you expect, since lines are skipped
when read in, then the whole array reversed.
Signature: (coeffs(n); x(c=2,m); [o]out(c=2,m))
evaluate the polynomial with (real) coefficients coeffs at the (complex) position(s) x. coeffs[0] is the constant term.
Read list of files directly into a large data cube (for efficiency)
$cube = rcube \&reader_function, @files;
$cube = rcube \&rfits, glob("*.fits");
This IO function allows direct reading of files into a large data cube, Obviously one could use cat() but this is more memory efficient.
The reading function (e.g. rfits, readfraw) (passed as a reference) and files are the arguments.
The cube is created as the same X,Y dims and datatype as the first image specified. The Z dim is simply the number of images.
Read a FIGARO/NDF format file.
Requires non-PDL DSA module. Contact Frossie (frossie@jach.hawaii.edu) Usage:
([$xaxis],$data) = rdsa($file)
$a = rdsa 'file.sdf'
Not yet tested with PDL-1.9X versions
Read a binary file with flexible format specification
($x,$y,...) = readflex("filename" [, $hdr])
Read a raw format binary file
$pdl2 = readfraw("fname");
$pdl2 = PDL->readfraw("fname");
One-dimensional FFT of real function [inplace].
The real part of the transform ends up in the first half of the array and the imaginary part of the transform ends up in the second half of the array.
realfft($real);
Inverse of one-dimensional realfft routine [inplace].
realifft($real);
Signature: (a(m); [o]b(n); int ns => n)
N-dimensional rebinning algorithm
$new = rebin $a, $dim1, $dim2,..;. $new = rebin $a, $template; $new = rebin $a, $template, {Norm => 1};
Rebin an N-dimensional array to newly specified dimensions. Specifying `Norm' keeps the sum constant, otherwise the intensities are kept constant. If more template dimensions are given than for the input pdl, these dimensions are created; if less, the final dimensions are maintained as they were.
So if $a is a 10 x 10 pdl, then rebin($a,15) is a 15 x 10 pdl, while rebin($a,15,16,17) is a 15 x 16 x 17 pdl (where the values along the final dimension are all identical).
refresh() causes a display event to be put at the top of the TriD work que. This should be called at the end of each user defined TriD::Tk callback.
Re-orders the dimensions of a PDL based on the supplied list.
Similar to the the xchg entry in the xchg
manpage method, this method re-orders the dimensions
of a PDL. While the the xchg entry in the xchg
manpage method swaps the position of two dimensions,
the reorder method can change the positions of many dimensions at
once.
# Completely reverse the dimension order of a 6-Dim array. $reOrderedPDL = $pdl->reorder(5,4,3,2,1,0);
The argument to reorder is an array representing where the current dimensions should go in the new array. In the above usage, the argument to reorder (5,4,3,2,1,0) indicates that the old dimensions ($pdl's dims) should be re-arranged to make the new pdl ($reOrderPDL) according to the following:
Old Position New Position ------------ ------------ 5 0 4 1 3 2 2 3 1 4 0 5
Example:
perldl> $a = sequence(5,3,2); # Create a 3-d Array perldl> p $a [ [ [ 0 1 2 3 4] [ 5 6 7 8 9] [10 11 12 13 14] ] [ [15 16 17 18 19] [20 21 22 23 24] [25 26 27 28 29] ] ] perldl> p $a->reorder(2,1,0); # Reverse the order of the 3-D PDL [ [ [ 0 15] [ 5 20] [10 25] ] [ [ 1 16] [ 6 21] [11 26] ] [ [ 2 17] [ 7 22] [12 27] ] [ [ 3 18] [ 8 23] [13 28] ] [ [ 4 19] [ 9 24] [14 29] ] ]
The above is a simple example that could be duplicated by calling $a->xchg(0,2), but it demonstrates the basic functionality of reorder.
As this is an index function, any modifications to the result PDL will change the parent.
Signature: (coords(nc,np);
[o]vecs(nc,np);
int [t]links(np);;
double boxsize;
int dmult;
double a;
double b;
double c;
double d;
)
Repulsive potential for molecule-like constructs.
repulse uses a hash table of cubes to quickly calculate
a repulsive force that vanishes at infinity for many
objects. For use by the module the PDL::Graphics::TriD::MathGraph
PDL::Graphics::TriD::MathGraph manpage.
For definition of the potential, see the actual function.
Signature: (I(n,m); O(q,p))
The first piddle is rescaled to the dimensions of the second (expandind or meaning values as needed) and then added to it.
Change the shape (i.e. dimensions) of a piddle, preserving contents.
$x->reshape(NEWDIMS); reshape($x, NEWDIMS);
The data elements are preserved, obviously they will wrap differently and get truncated if the new array is shorter. If the new array is longer it will be zero-padded.
Note: an explicit copy is forced -- this is the only way (for now) of stopping a crash if $x is a slice.
perldl> $x = sequence(10) perldl> reshape $x,3,4; p $x [ [0 1 2] [3 4 5] [6 7 8] [9 0 0] ] perldl> reshape $x,5; p $x [0 1 2 3 4]
Real FFT. For an input piddle of dimensions [n1,n2,...] the output is [2,(n1/2)+1,n2,...] (real input, complex output).
$pdl_cplx = fftw $pdl_real;
ND convolution using real ffts from the FFTW library
$conv = rfftwconv $im, kernctr $k;
Simple piddle FITS reader.
$pdl = rfits('file.fits');
Suffix magic:
# Automatically uncompress via gunzip pipe
$pdl = rfits('file.fits.gz');
# Automatically uncompress via uncompress pipe
$pdl = rfits('file.fits.Z');
FITS Headers stored in piddle and can be retrived with $a->gethdr.
This header is a reference to a hash where the hash keys are the keywords in the FITS header. It is important to note that for strings, the surrounding quotes are kept to ensure that strings that look like numbers are kept as strings. This is also of importance if you create your own header information and you want the value to be printed out as a string.
Comments in headers are stored as $$h{COMMENT}{<Keyword>} where $h is the header retrieved with $a->gethdr. History entries in the header are stored as $$h{HISTORY}, which is an anonymous array for each HISTORY entry in the header.
Converts an RGB image to a grey scale using standard transform
$gr = $rgb->rgbtogr
Performs a conversion of an RGB input image (3,x,....) to a greyscale image (x,.....) using standard formula:
Grey = 0.301 R + 0.586 G + 0.113 B
Read columns into piddles using full regexp pattern matching.
Usage
($x,$y,...) = rgrep(sub, *HANDLE|"filename")
e.g.
($a,$b) = rgrep {/Foo (.*) Bar (.*) Mumble/} $file;
i.e. the vectors $a and $b get the progressive values of $1, $2 etc.
Signature: (a(); [o]b())
Round to integral values in floating-point format
Module: PDL::Slices
Signature: (int a(n); b(n); [o]c(m))
Run-length decode a vector
Given a vector $a of the numbers of instances of values $b, run-length decode to $c.
rld($a,$b,$c=null);
Module: PDL::Slices
Signature: (c(n); int [o]a(n); [o]b(n))
Run-length encode a vector
Given vector $c, generate a vector $a with the number of each element, and a vector $b of the unique values. Only the elements up to the first instance of `0' in $a should be considered.
rle($c,$a=null,$b=null);
Reads a piddle from a NDF format data file.
$pdl = rndf('file.sdf');
$pdl = rndf('file.sdf',1);
The '.sdf' suffix is optional. The optional second argument turns off automatic quality masking and returns a quality array as well.
Header information and NDF Extensions are stored in the piddle as a hash which can be retreived with the $pdl->gethdr command. Array extensions are stored in the header as follows:
$a - the base DATA_ARRAY
If $hdr = $a->gethdr;
then:
%{$hdr} contains all the FITS headers plus:
$$hdr{Error} contains the Error/Variance PDL
$$hdr{Quality} The quality byte array (if reqeusted)
@{$$hdr{Axis}} Is an array of piddles containing the information
for axis 0, 1, etc.
$$hdr{NDF_EXT} Contains all the NDF extensions
$$hdr{Hist} Contains the history information
$$hdr{NDF_EXT}{_TYPES} - Data types for non-PDL NDF extensions so that
wndf can reconstruct a NDF.
All extension information is stored in the header hash array. Extension structures are preserved in hashes, so that the PROJ_PARS component of the IRAS.ASTROMETRY extension is stored in $$hdr{NDF_EXT}{IRAS}{ASTROMETRY}{'PROJ_PARS'}. All array structures are stored as arrays in the Hdr: numeric arrays are stored as PDLs, logical and character arrays are stored as plain Perl arrays. FITS arrays are a special case and are expanded as scalars into the header.
Signature: (im(m,n); float angle(); bg(); int aa(); [o] om(p,q))
rotate an image by given angle
# rotate by 10.5 degrees with antialiasing, set missing values to 7 $rot = $im->rot2d(10.5,7,1);
This function rotates an image through an angle between
90 and + 90
degrees. Uses/doesn't use antialiasing depending on the aa flag.
Pixels outside the rotated image are set to bg.
Code modified from pnmrotate (Copyright Jef Poskanzer) with an algorithm based
on ``A Fast Algorithm for General Raster Rotation'' by Alan Paeth,
Graphics Interface '86, pp. 77
81.
Use the rotnewsz function to find out about the dimension of the newly created image
($newcols,$newrows) = rotnewsz $oldn, $oldm, $angle;
Signature: (x(n); int shift(); [oca]y(n))
Shift vector elements along with wrap. Flows data back&forth.
my $name = $obj->routine;
Returns the name of the last routine called by a PDL::Func object.
This is mainly useful for decoding the value stored in the err attribute.
Read images in many formats with automatic format detection.
$im = rpic $file;
$im = PDL->rpic 'PDL.jpg' if PDL->rpiccan('JPEG');
Options
FORMAT => 'JPEG' # explicitly read this format
XTRAFLAGS => '-nolut' # additional flags for converter
Reads image files in most of the formats supported by netpbm. You can explicitly specify a supported format by additionally passing a hash containing the FORMAT key as in
$im = rpic ($file, {FORMAT => 'GIF'});
This is especially useful if the particular format isn't identified by a magic number and doesn't have the 'typical' extension or you want to avoid the check of the magic number if your data comes in from a pipe. The function returns a pdl of the appropriate type upon completion. Option parsing uses the the PDL::Options manpage module and therefore supports minimal options matching.
You can also read directly into an existing pdl that has to have the right size(!). This can come in handy when you want to read a sequence of images into a datacube, e.g.
$stack = zeroes(byte,3,500,300,4);
rpic $stack->slice(':,:,:,(0)'),"PDL.jpg";
reads an rgb image (that had better be of size (500,300)) into the first plane of a 3D RGB datacube (=4D pdl datacube). You can also do transpose/inversion upon read that way.
Read a pnm (portable bitmap/pixmap, pbm/ppm) file into a piddle.
Reads a file in pnm format (ascii or raw) into a pdl (magic numbers P1-P6). Based on the input format it returns pdls with arrays of size (width,height) if binary or grey value data (pbm and pgm) or (3,width,height) if rgb data (ppm). This also means for a palette image that the distinction between an image and its lookup table is lost which can be a problem in cases (but can hardly be avoided when using netpbm/pbmplus). Datatype is dependent on the maximum grey/color-component value (for raw and binary formats always PDL_B). rpnm tries to read chopped files by zero padding the missing data (well it currently doesn't, it barfs; I'll probably fix it when it becomes a problem for me ;). You can also read directly into an existing pdl that has to have the right size(!). This can come in handy when you want to read a sequence of images into a datacube.
For details about the formats see appropriate manpages that come with the netpbm/pbmplus packages.
$im = rpnm $file;
$stack = zeroes(byte,3,500,300,4);
rpnm $stack->slice(':,:,:,(0)'),"PDL.ppm";
reads an rgb image (that had better be of size (500,300)) into the first plane of a 3D RGB datacube (=4D pdl datacube). You can also do inplace transpose/inversion that way.
Module: PDL::Slatec
Signature: (a(n,n);[o]w(n);int matz();[o]z(n,n);[t]fvone(n);[t]fvtwo(n);int [o]ierr())
This subroutine calls the recommended sequence of subroutines from the eigensystem subroutine package (EISPACK) to find the eigenvalues and eigenvectors (if desired) of a REAL SYMMETRIC matrix.
Fills a piddle with radial distance values from some centre.
$r = rvals $piddle,{OPTIONS};
$r = rvals [OPTIONAL TYPE],$nx,$ny,...{OPTIONS};
Options:
Centre => [$x,$y,$z...] # Specify centre Center => [$x,$y.$z...] # synonym.
perldl> print rvals long,7,7,{Centre=>[2,2]}
[
[2 2 2 2 2 3 4]
[2 1 1 1 2 3 4]
[2 1 0 1 2 3 4]
[2 1 1 1 2 3 4]
[2 2 2 2 2 3 4]
[3 3 3 3 3 4 5]
[4 4 4 4 4 5 5]
]
For a more general metric, one can define, e.g.,
sub distance {
my ($a,$centre,$f) = @_;
my ($r) = $a->allaxisvals-$centre;
$f->($r);
}
sub l1 { sumover(abs($_[0])); }
sub euclid { use PDL::Math 'pow'; pow(sumover(pow($_[0],2)),0.5); }
sub linfty { maximum(abs($_[0])); }
so now
distance($a, $centre, \&euclid);
will emulate rvals, while \&l1 and \&linfty will generate other well-known norms.
Starts the SAOimage external program
saoimage[(command line options)]
Starts up the SAOimage external program. Default FIFO devices are chosen so as to be compatible with other IIS module functions. If no suitable FIFOs are found it will offer to create them.
e.g.:
perldl> saoimage perldl> saoimage( -geometry => '800x800' )
my $scheme = $obj->scheme;
Return the type of interpolation of a PDL::Func object.
Returns either Linear or Hermite.
Create array filled with a sequence of values
$a = sequence($b); $a = sequence [OPTIONAL TYPE], @dims;
etc. see the zeroes entry in the zeroes
PDL::Core manpage.
perldl> p sequence(10) [0 1 2 3 4 5 6 7 8 9] perldl> p sequence(3,4) [ [ 0 1 2] [ 3 4 5] [ 6 7 8] [ 9 10 11] ]
Module: PDL::Func
my $nset = $obj->set( x = $newx, $y => $newy );
my $nset = $obj->set( { x = $newx, $y => $newy } );
Set attributes for a PDL::Func object.
The return value gives the number of the supplied attributes which were actually set.
Module: PDL::Core
Set a single value inside a piddle
set $piddle, @position, $value
@position is a coordinate list, of size equal to the
number of dimensions in the piddle. Occasionally useful,
mainly provided for backwards compatibility as superseded
by use of the slice entry in the slice
PDL::Slices manpage and assigment operator .=.
perldl> $x = sequence 3,4 perldl> set $x, 2,1,99 perldl> p $x [ [ 0 1 2] [ 3 4 99] [ 6 7 8] [ 9 10 11] ]
Set header information of a piddle
$pdl=rfits('file.fits');
$h=$pdl->gethdr;
# add a FILENAME field to the header
$$h{FILENAME} = 'file.fits';
$pdl->sethdr( $h );
The sethdr function sets the header information for a piddle.
Normally you would get the current header information with
the gethdr entry in the gethdr
manpage, add/change/remove fields, then apply those changes with
sethdr.
The sethdr function must be given a hash reference.
For further information on the header, see the gethdr entry in the gethdr
manpage and
the hdrcpy entry in the hdrcpy
manpage.
Function to set one string value in a character PDL. The input position is the position of the string, not a character in the string. The first dimension is assumed to be the length of the string.
The input string will be null-padded if the string is shorter than the first dimension of the PDL. It will be truncated if it is longer.
$char = PDL::Char->new( [['abc', 'def', 'ghi'], ['jkl', 'mno', 'pqr']] ); $char->setstr(0,1, 'foobar'); print $char; # 'string' bound to "", perl stringify function # Prints: # [ # ['abc' 'def' 'ghi'] # ['foo' 'mno' 'pqr'] # ] $char->setstr(2,1, 'f'); print $char; # 'string' bound to "", perl stringify function # Prints: # [ # ['abc' 'def' 'ghi'] # ['foo' 'mno' 'f'] -> note that this 'f' is stored "f\0\0" # ]
Signature: (a(); b(); [o]c(); int swap)
leftshift a$ by $b
$c = shiftleft $a, $b, 0; # explicit call with trailing 0 $c = $a << $b; # overloaded call $a->inplace->shiftleft($b,0); # modify $a inplace
It can be made to work inplace with the $a->inplace syntax. This function is used to overload the binary « operator. Note that when calling this function explicitly you need to supply a third argument that should generally be zero (see first example). This restriction is expected to go away in future releases.
Signature: (a(); b(); [o]c(); int swap)
leftshift a$ by $b
$c = shiftright $a, $b, 0; # explicit call with trailing 0 $c = $a >> $b; # overloaded call $a->inplace->shiftright($b,0); # modify $a inplace
It can be made to work inplace with the $a->inplace syntax. This function is used to overload the binary » operator. Note that when calling this function explicitly you need to supply a third argument that should generally be zero (see first example). This restriction is expected to go away in future releases.
Convert to short datatype -- see 'Datatype_conversions'
Module: PDL::Doc::Perldl
prints signature of PDL function
sig 'func'
The signature is the normal dimensionality of the functions arguments. Calling with different dimensions causes 'threading' -- see PDL::PP for more details.
perldl> sig 'outer'
Signature: outer(a(n); b(m); [o]c(n,m); )
Simplex optimization routine
($optimum,$ssize) = simplex($init,$initsize,$minsize,
$maxiter,
sub {evaluate_func_at($_[0])},
sub {display_simplex($_[0])}
);
See module PDL::Opt::Simplex for more information.
Signature: ([phys]a(n,n); [phys]b(n); [o,phys]x(n); int [o,phys]ips(n); int flag)
Solution of simultaneous linear equations, a x = b.
$a is an n x n matrix (i.e., a vector of length n*n), stored row-wise:
that is, a(i,j) = a[ij], where ij = i*n + j.
While this is the
transpose of the normal column-wise storage, this corresponds to
normal PDL usage. The contents of matrix a may be altered (but may be
required for subsequent calls with flag =
1).
$b, $x, $ips are vectors of length n.
Set flag=0 to solve. Set flag=-1 to do a new back substitution for different $b vector using the same a matrix previously reduced when flag=0 (the $ips vector generated in the previous solution is also required).
Module: PDL::Ops
Signature: (a(); [o]b())
the sin function
$b = sin $a; $a->inplace->sin; # modify $a inplace
It can be made to work inplace with the $a->inplace syntax. This function is used to overload the unary sin operator/function.
Signature: (a(); [o]b())
The standard hyperbolic function.
Signature: (P(); C(); char* str)
Returns a rectangular slice of the original piddle
$a->slice('1:3'); # return the second to fourth elements of $a
$a->slice('3:1'); # reverse the above
$a->slice('-2:1'); # return last-but-one to second elements of $a
The argument string is a comma-separated list of what to do
for each dimension. The current formats include
the following, where a, b and c are integers and can
take legal array index values (including
1 etc):
means the same as ``a'' by itself except that the resulting dimension of length one is deleted (so if $a has dims (3,4,5) then $a->slice(':,(2),:') has dimensions (3,5) whereas $a->slice(':,2,:') has dimensions (3,1,5)).
slices the range a to b inclusive out of the dimension.
An extension is planned for a later stage allowing
C
$a->slice('(=1),(=1
5:8),3:6(=1),4:6')
to express a multidimensional diagonal of $a.
Signature: (a(); b(); [o]c(); int swap)
binary <=> operation
$c = $a->spaceship($b,0); # explicit function call $c = $a <=> $b; # overloaded use $a->inplace->spaceship($b,0); # modify $a inplace
It can be made to work inplace with the $a->inplace syntax. This function is used to overload the binary op<=> function. Note that when calling this function explicitly you need to supply a third argument that should generally be zero (see first example). This restriction is expected to go away in future releases.
Signature: (P(); C(); int nthdim; int nsp)
Splits a dimension in the parent piddle (opposite of the clump entry in the clump
manpage)
After
$b = $a->splitdim(2,3);
the expression
$b->at(6,4,x,y,3,6) == $a->at(6,4,x+3*y)
is always true (x has to be less than 3).
Signature: (a(); [o]b())
elementwise square root
$b = sqrt $a; $a->inplace->sqrt; # modify $a inplace
It can be made to work inplace with the $a->inplace syntax. This function is used to overload the unary sqrt operator/function.
Signature: (a(n,n); b(m))
Convert a symmetric square matrix to triangular vector storage
Calculates useful statistics on a piddle
($mean,$rms,$median,$min,$max) = stats($piddle,[$weights]);
This utility calculates all the most useful quantities in one call.
Note: The RMS value that this function returns in the RMS deviation from the mean, also known as the population standard- deviation.
my $status = $obj->status;
Returns the status of a PDL::Func object.
This method provides a high-level indication of
the success of the last method called
(except for get which is ignored).
Returns 1 if everything is okay, 0 if
there has been a serious error,
and -1 if there
was a problem which was not serious.
In the latter case, C
$obj->get("err")
may
provide more information, depending on the
particular scheme in use.
Function to print a character PDL (created by 'char') in a pretty format.
$char = PDL::Char->new( [['abc', 'def', 'ghi'], ['jkl', 'mno', 'pqr']] ); print $char; # 'string' bound to "", perl stringify function # Prints: # [ # ['abc' 'def' 'ghi'] # ['jkl' 'mno' 'pqr'] # ]
# 'string' is overloaded to the "" operator, so: # print $char; # should have the same effect.
Module: PDL::Primitive
Return the sum of all elements in a piddle
$x = sum($data);
Signature: (a(n); int+ [o]b())
Project via sum to N-1 dimensions
This function reduces the dimensionality of a piddle by one by taking the sum along the 1st dimension.
By using the xchg entry in the xchg
PDL::Slices manpage etc. it is possible to use
any dimension.
$a = sumover($b);
$spectrum = sumover $image->xchg(0,1)
Module: PDL::Math
Signature: (a(n,m); [o]u(n,m); [o,phys]z(n); [o]v(n,n))
Singular value decomposition of array.
($u, $s, $v) = svd($a);
Signature: (x(n,p);[o]s(p);[o]e(p);[o]u(n,p);[o]v(p,p);[o]work(n);int job();int [o]info())
singular value decomposition of a matrix
Module: PDL::Math
Signature: (a(); [o]b())
The usual trigonometric function.
Signature: (a(); [o]b())
The standard hyperbolic function.
Use explicit threading over specified dimensions (see also the PDL::Indexing manpage)
$b = $a->thread($dim,[$dim1,...])
$a = zeroes 3,4,5; $b = $a->thread(2,0);
Same as the PDL::thread1 entry in the PDL::thread1
manpage, i.e. uses thread id 1.
Explicit threading over specified dims using thread id 1.
$xx = $x->thread1(3,1)
Wibble
Convenience function interfacing to
the threadI entry in the PDL::Slices::threadI
PDL::Slices manpage.
Explicit threading over specified dims using thread id 2.
$xx = $x->thread2(3,1)
Wibble
Convenience function interfacing to
the threadI entry in the PDL::Slices::threadI
PDL::Slices manpage.
Explicit threading over specified dims using thread id 3.
$xx = $x->thread3(3,1)
Wibble
Convenience function interfacing to
the threadI entry in the PDL::Slices::threadI
PDL::Slices manpage.
define functions that support threading at the perl level
thread_define 'tline(a(n);b(n))', over {
line $_[0], $_[1]; # make line compliant with threading
};
thread_define provides some support for threading (see the PDL::Indexing manpage) at the perl level. It allows you to do things for which you normally would have resorted to PDL::PP (see the PDL::PP manpage); however, it is most useful to wrap existing perl functions so that the new routine supports PDL threading.
thread_define is used to define new threading aware functions. Its first argument is a symbolic repesentation of the new function to be defined. The string is composed of the name of the new function followed by its signature (see the PDL::Indexing manpage and the PDL::PP manpage) 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 threading, see the PDL::Indexing manpage).
The actual work is done by the signature class which parses the signature string, does runtime dimension checks and the routine threadover that generates the loop over all appropriate slices of pdl arguments and creates pdls as needed.
Similar to pp_def and its OtherPars option it is possible to define the new function so that it accepts normal perl args as well as piddles. 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 thread_define. Let's illustrate this with an example:
PDL::thread_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 piddles 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
the PDL::Graphics::TriD::VRML
PDL::Graphics::TriD::VRML manpage
to generate VRML output.
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 the PDL::PP
PDL::PP manpage for the format of the signature. Currently, the
[t] qualifier and all type qualifiers are ignored.
Returns the piddle thread IDs as a perl list
@ids = threadids $piddle;
threaded version of Levenberg-Marquardt fitting routine mfit
tlmfit $x, $y, float(1)->dummy(0), $na, float(200), float(1e-4),
$ym=null, $afit=null, \&expdec;
Signature:
tlmfit(x(n);y(n);sig(n);a(m);iter();eps();[o] ym(n);[o] ao(m);
OtherPar => subref)
a threaded version of lmfit by using perl threading. Direct threading in lmfit seemed difficult since we have an if condition in the iteration. In principle that can be worked around by using where but .... Send a threaded lmfit version if you work it out!
Since we are using perl threading here speed is not really great but it is just convenient to have a threaded version for many applications (no explicit for-loops required, etc). Suffers from some of the current limitations of perl level threading.
alternate piddle constructor -- ensures arg is a piddle
$a = topdl(SCALAR|ARRAY REFERENCE|ARRAY);
The difference between the pdl entry in the pdl()
manpage and topdl() is that the
latter will just 'fall through' if the argument is
already a piddle. It will return a reference and NOT
a new copy.
This is particulary useful if you are writing a function which is doing some fiddling with internals and assumes a piddle argument (e.g. for method calls). Using topdl() will ensure nothing breaks if passed with '2'.
$a = topdl 43; # $a is piddle with value '43' $b = topdl $piddle; # fall through $a = topdl (1,2,3,4); # Convert 1D array
transpose rows and columns.
$b = transpose($a); $b = ~$a;
Also bound to the ~ unary operator.
perldl> $a = sequence(3,2) perldl> p $a [ [0 1 2] [3 4 5] ] perldl> p transpose( $a ) [ [0 3] [1 4] [2 5] ]
Wait for the user to rotate the image in 3D space.
Let the user rotate the image in 3D space, either for one step or until (s)he presses 'q', depending on the 'keeptwiddling3d' setting. If 'keeptwiddling3d' is not set the routine returns immediately and indicates that a 'q' event was received by returning 1. If the only events received were mouse events, returns 0.
return the type of a piddle as a blessed type object
A convenience function for use with the piddle constructors, e.g.
$b = PDL->zeroes($a->type,$a->dims,3);
Signature: (P(); C(); int atind)
All threaded dimensions are made real again.
See [TBD Doc] for details and examples.
Return a piddle which is the same as the argument except that all threadids have been removed.
$y = $x->unwind;
Prints usage information for a PDL function
Usage: usage 'func'
perldl> usage 'inner'
inner inner prodcuct over one dimension
(Module PDL::Primitive)
Signature: inner(a(n); b(n); [o]c(); )
Convert to ushort datatype -- see 'Datatype_conversions'
Returns array of column numbers requested
line $pdl->using(1,2);
Plot, as a line, column 1 of $pdl vs. column 2
perldl> $pdl = rcols("file");
perldl> line $pdl->using(1,2);
Alias for px
Display 2 images as a vector field
Usage: vect ( $a, $b, [$scale, $pos, $transform, $misval] )
Notes: $transform for image/cont etc. is used in the same way as the TR() array in the underlying PGPLOT FORTRAN routine but is, fortunately, zero-offset.
This routine will plot a vector field. $a is the horizontal component and $b the vertical component.
Options recognised:
SCALE - Set the scale factor for vector lengths.
POS - Set the position of vectors.
<0 - vector head at coordinate
>0 - vector base at coordinate
=0 - vector centered on the coordinate
TRANSFORM - The pixel-to-world coordinate transform vector
MISSING - Elements with this value are ignored.
The following standard options influence this command:
ARROW, ARROWSIZE, AXIS, BORDER, CHARSIZE, COLOUR, JUSTIFY, LINESTYLE, LINEWIDTH
$a=rvals(11,11,{Centre=>[5,5]});
$b=rvals(11,11,{Centre=>[0,0]});
vect $a, $b, {COLOR=>YELLOW, ARROWSIZE=>0.5, LINESTYLE=>dashed};
Signature: (vertices(n=3); char* space; char* fd)
info not available
Signature: (i(); x(n); int [o]ip())
routine for searching 1D values i.e. step-function interpolation.
$inds = vsearch($vals, $xs);
Returns for each value of $val the index of the least larger member of $xs (which need to be in increasing order). If the value is larger than any member of $xs, the index to the last element of $xs is returned.
This function is useful e.g. when you have a list of probabilities for events and want to generate indices to events:
$a = pdl(.01,.86,.93,1); # Barnsley IFS probabilities cumulatively $b = random 20; $c = vsearch($b, $a); # Now, $c will have the appropriate distr.
It is possible to use the the cumusumover entry in the cumusumover
manpage function to obtain
cumulative probabilities from absolute probabilities.
Write ASCII whitespaced cols into file from piddles efficiently.
If no columns are specified all are assumed.
Will optionally only process lines matching a pattern.
Can take file name or
HANDLE, and
if no file/filehandle is given defaults to STDOUT.
Options:
HEADER -- prints this string before the data. If the string is not terminated by a newline, one is added (default '').
Usage: wcols $piddle1, $piddle2,..., *HANDLE|"outfile", [\%options];
e.g.,
wcols $x, $y+2, 'foo.dat'; wcols $x, $y+2, *STDERR; wcols $x, $y+2, '|wc'; wcols $a,$b,$c; # Orthogonal version of 'print $a,$b,$c' :-)
wcols "%10.3f", $a,$b; # Formatted wcols "%10.3f %10.5g", $a,$b; # Individual column formatting
wcols $a,$b, { HEADER => "# a b" };
Note: columns are separated by whitespace by default, use $PDL::IO::Misc::colsep to specify an alternate separator.
Simple piddle FITS writer
wfits $pdl, 'filename.fits', [$BITPIX];
$pdl->wfits('foo.fits',-32);
Suffix magic:
# Automatically compress through pipe to gzip wfits $pdl, 'filename.fits.gz'; # Automatically compress through pipe to compress wfits $pdl, 'filename.fits.Z';
$BITPIX is optional and coerces the output format.
Returns indices to non-zero values or those values from another piddle.
$i = $x->where($x+5 > 0); # $i contains elements of $x
# where mask ($x+5 > 0) is 1
Note: $i is always 1-D, even if $x is >1-D. The first argument (the values) and the second argument (the mask) currently have to have the same initial dimensions (or horrible things happen).
It is also possible to use the same mask for several piddles with the same call:
($i,$j,$k) = where($x,$y,$z, $x+5>0);
There is also the following syntax, retained only for compatibility
with PDL versions < 1.99.
This use is deprecated, and will be removed
in the future. Use the which entry in the which
manpage instead.
$i = where($x > 0); # indices to $x, equivalent to 'which()'
Note: the mask has to be 1-D. See the documentation for the which entry in the which
manpage
Signature: (mask(n); int [o] inds(m))
Returns piddle of indices of non-zero values.
$i = which($mask);
returns a pdl with indices for all those elements that are nonzero in the mask. Note that mask really has to be 1-D (use clump(-1) if you need to work with ND-images)
If you want to return both the indices of non-zero values and the
complement, use the function the section on which_both in the which_both
manpage.
perldl> $x = sequence(10); p $x [0 1 2 3 4 5 6 7 8 9] perldl> $indx = which($x>6); p $indx [7 8 9]
Signature: (mask(n); int [o] inds(m); int [o]notinds(q))
Returns piddle of indices of non-zero values and their complement
($i, $c_i) = which_both($mask);
This works just as which, but the complement of $i will be in $c_i.
perldl> $x = sequence(10); p $x [0 1 2 3 4 5 6 7 8 9] perldl> ($small, $big) = which_both ($x >= 5); p "$small\n $big" [5 6 7 8 9] [0 1 2 3 4]
Returns the coordinates for non-zero values
@coords=whichND($mask);
returns an array of piddles containing the coordinates of the elements that are non-zero in $mask.
perldl> $a=sequence(10,10,3,4) perldl> ($x, $y, $z, $w)=whichND($a == 203); p $x, $y, $z, $w [3] [0] [2] [0] perldl> print $a->at(list(cat($x,$y,$z,$w))) 203
Signature: (in(n); float+ wt(n);float+[o] hist(m); double step; double min; int msize => m)
Calculates a histogram from weighted data for given stepsize and minimum.
$h = whistogram($data, $weights, $step, $min, $numbins); $hist = zeroes $numbins; # Put histogram in existing piddle. whistogram($data, $weights, $hist, $step, $min, $numbins);
The histogram will contain $numbins bins starting from $min, each $step wide. The value in each bin is the sum of the values in $weights that correspond to values in $data that lie within the bin limits.
Data below the lower limit is put in the first bin, and data above the upper limit is put in the last bin.
The output is reset in a different threadloop so that you can take a histogram of $a(10,12) into $b(15) and get the result you want.
perldl> p whistogram(pdl(1,1,2), pdl(0.1,0.1,0.5), 1, 0, 4) [0 0.2 0.5 0]
Signature: (ina(n); inb(n); float+ wt(n);float+[o] hist(ma,mb); double stepa; double mina; int masize => ma;
double stepb; double minb; int mbsize => mb;)
Calculates a 2d histogram from weighted data.
$h = whistogram2d($datax, $datay, $weights,
$stepx, $minx, $nbinx, $stepy, $miny, $nbiny);
$hist = zeroes $nbinx, $nbiny; # Put histogram in existing piddle.
whistogram2d($datax, $datay, $weights, $hist,
$stepx, $minx, $nbinx, $stepy, $miny, $nbiny);
The histogram will contain $nbinx x $nbiny bins, with the lower limits of the first one at ($minx, $miny), and with bin size ($stepx, $stepy). The value in each bin is the sum of the values in $weights that correspond to values in $datax and $datay that lie within the bin limits.
Data below the lower limit is put in the first bin, and data above the upper limit is put in the last bin.
perldl> p whistogram2d(pdl(1,1,1,2,2),pdl(2,1,1,1,1),pdl(0.1,0.2,0.3,0.4,0.5),1,0,3,1,0,3) [ [ 0 0 0] [ 0 0.5 0.9] [ 0 0.1 0] ]
Write an image sequence ((x,y,n) piddle) as an MPEG animation.
$anim->wmpeg("GreatAnimation.mpg");
Writes a stack of rgb images as an mpeg movie. Expects a 4-D pdl of type byte as input. First dim has to be 3 since it is interpreted as interlaced RGB. Some of the input data restrictions will have to be relaxed in the future but routine serves as a proof of principle at the moment. It uses the program mpeg_encode from the Berkeley multimedia package (see also text at the top of this package). Mpeg parameters written by this routines haven't been tweaked in any way yet (in other words, lots of room for improvement). For an example how to use the routine see appropriate test that comes with this package. Currently, wmpeg doesn't allow modification of the parameters written through its calling interface. This will change in the future as needed.
In the future it might be much nicer to implement a movie perl object that supplies methods for manipulating the image stack (insert, cut, append commands) and a final movie->make() call would invoke mpeg_encode on the picture stack (which will only be held on disk). This should get around the problem of having to hold a huge amount of data in memory to be passed into wmpeg (when you are, e.g. writing a large animation from PDL3D rendered fly-throughs). Having said that, the actual storage requirements might not be so big in the future any more if you could pass 'virtual' transform pdls into wmpeg that will only be actually calculated when accessed by the wpic routines, you know what I mean...
Writes a piddle to a NDF format file:
$pdl->wndf($file); wndf($pdl,$file);
wndf can be used for writing PDLs to NDF files. The '.sdf' suffix is optional. All the extensions created by rndf are supported by wndf. This means that error, axis and quality arrays will be written if they exist. Extensions are also reconstructed by using their name (ie FIGARO.TEST would be expanded as a FIGARO extension and a TEST component). Hdr keywords Label, Title and Units are treated as special cases and are written to the label, title and units fields of the NDF.
Header information is written to corresponding NDF extensions. NDF extensions can also be created in the {NDF} hash by using a key containing '.', ie {NDF}{'IRAS.DATA'} would write the information to an IRAS.DATA extension in the NDF. rndf stores this as $$hdr{NDF}{IRAS}{DATA} and the two systems are interchangeable.
rndf stores type information in {NDF}{'_TYPES'} and below so that wndf can reconstruct the data type of non-PDL extensions. If no entry exists in _TYPES, wndf chooses between characters, integer and double on a best guess basis. Any perl arrays are written as CHAR array extensions (on the assumption that numeric arrays will exist as PDLs).
Write images in many formats with automatic format selection.
Usage: wpic($pdl,$filename[,{ options... }])
wpic $pdl, $file;
$im->wpic('web.gif',{LUT => $lut});
for (@images) {
$_->wpic($name[0],{CONVERTER => 'ppmtogif'})
}
Write out an image file. Function will try to guess correct image format from the filename extension, e.g.
$pdl->wpic("image.gif")
will write a gif file. The data written out will be scaled to byte if input is of type float/double. Input data that is of a signed integer type and contains negative numbers will be rejected (assuming the user should have the desired conversion to an unsigned type already). A number of options can be specified (as a hash reference) to get more direct control of the image format that is being written. Valid options are (key => example_value):
CONVERTER => 'ppmtogif', # explicitly specify pbm converter FLAGS => '-interlaced -transparent 0', # flags for converter IFORM => 'PGM', # explicitly specify intermediate format XTRAFLAGS => '-imagename iris', # additional flags to defaultflags FORMAT => 'PCX', # explicitly specify output image format COLOR => 'bw', # specify color conversion LUT => $lut, # use color table information
Option parsing uses the the PDL::Options manpage module and therefore supports minimal options matching. A detailed explanation of supported options follows.
CONVERTER => 'ppmtogif',
FLAGS => '-interlaced -transparent 0',
IFORM => 'PGM',
XTRAFLAGS => '-imagename iris',
FORMAT => 'PCX',
COLOR => 'bw',
This is a palette image and the value of this key should be a pdl containg an RGB lookup table (3,x), e.g.
LUT => $lut,
Using the CONVERTER hint you can also build a pipe and perform several netpbm operations to get the special result you like. Using it this way the first converter/filecommand in the pipe should be specified with the CONVERTER hint and subsequent converters + flags in the FLAGS hint. This is because wpic tries to figure out the required format to be written by wpnm based on the first converter. Be careful when using the PBMBIN var as it will only be prepended to the converter. If more converters are in the FLAGS part specify the full path unless they are in your PATH anyway.
Example:
$im->wpic('test.ps',{CONVERTER => 'pgmtopbm',
FLAGS => "-dither8 | pnmtops" })
Some of the options may appear silly at the moment and probably are. The situation will hopefully improve as people use the code and the need for different/modified options becomes clear. The general idea is to make the function perl compliant: easy things should be easy, complicated tasks possible.
Write a pnm (portable bitmap/pixmap, pbm/ppm) file into a file.
Writes data in a pdl into pnm format (ascii or raw) (magic numbers P1-P6). The $format is required (normally produced by wpic) and routine just checks if data is compatible with that format. All conversions should already have been done. If possible, usage of wpic is preferred. Currently RAW format is chosen if compliant with range of input data. Explicit control of ASCII/RAW is possible through the optional $raw argument. If RAW is set to zero it will enforce ASCII mode. Enforcing RAW is somewhat meaningless as the routine will always try to write RAW format if the data range allows (but maybe it should reduce to a RAW supported type when RAW == 'RAW'?). For details about the formats consult appropriate manpages that come with the netpbm/pbmplus packages.
$im = wpnm $pdl, $file, $format[, $raw];
Write a binary file with flexible format specification
$hdr = writeflex($file, $pdl1, $pdl2,...)
Write a raw format binary file
writefraw($pdl,"fname");
Signature: (a(n); wt(n); avg(); [o]b(); int deg)
Weighted statistical moment of given degree
This calculates a weighted statistic over the vector a. The formula is
b() = (sum_i wt_i * (a_i ** degree - avg)) / (sum_i wt_i)
Signature: (P(); C(); int n1; int n2)
exchange two dimensions
Negative dimension indices count from the end.
The command
$b = $a->xchg(2,3);
creates $b to be like $a except that the dimensions 2 and 3 are exchanged with each other i.e.
$b->at(5,3,2,8) == $a->at(5,3,8,2)
Starts the Ximtool external program
ximtool[(command line options)]
Starts up the Ximtool external program. Default FIFO devices are chosen so as to be compatible with other IIS module functions. If no suitable FIFOs are found it will offer to create them.
e.g.
perldl> ximtool perldl> ximtool (-maxColors => 64)
X axis values between endpoints (see the xvals entry in the xvals
manpage).
$a = zeroes(100,100); $x = $a->xlinvals(0.5,1.5); $y = $a->ylinvals(-2,-1); # calculate Z for X between 0.5 and 1.5 and # Y between -2 and -1. $z = f($x,$y);
xlinvals, ylinvals and zlinvals return a piddle with the same shape as their first argument and linearly scaled values between the two other arguments along the given axis.
Module: PDL::Ops
Signature: (a(); b(); [o]c(); int swap)
binary exclusive or of two piddles
$c = xor $a, $b, 0; # explicit call with trailing 0 $c = $a ^ $b; # overloaded call $a->inplace->xor($b,0); # modify $a inplace
It can be made to work inplace with the $a->inplace syntax. This function is used to overload the binary ^ operator. Note that when calling this function explicitly you need to supply a third argument that should generally be zero (see first example). This restriction is expected to go away in future releases.
Starts external Karma application xray
xray([OPTIONS])
perldl> kview (-num_col => 42) perldl> xray
Fills a piddle with X index values
$x = xvals($somearray); $x = xvals([OPTIONAL TYPE],$nx,$ny,$nz...);
etc. see the zeroes entry in the zeroes
PDL::Core manpage.
perldl> print xvals zeroes(5,10) [ [0 1 2 3 4] [0 1 2 3 4] [0 1 2 3 4] [0 1 2 3 4] [0 1 2 3 4] [0 1 2 3 4] [0 1 2 3 4] [0 1 2 3 4] [0 1 2 3 4] [0 1 2 3 4] ]
Y axis values between endpoints (see the yvals entry in the yvals
manpage).
See the xlinvals entry in the xlinvals
manpage for more information.
Fills a piddle with Y index values
$x = yvals($somearray); yvals(inplace($somearray)); $x = yvals([OPTIONAL TYPE],$nx,$ny,$nz...);
etc. see the zeroes entry in the zeroes
PDL::Core manpage.
perldl> print yvals zeroes(5,10) [ [0 0 0 0 0] [1 1 1 1 1] [2 2 2 2 2] [3 3 3 3 3] [4 4 4 4 4] [5 5 5 5 5] [6 6 6 6 6] [7 7 7 7 7] [8 8 8 8 8] [9 9 9 9 9] ]
Return the check for zero of all elements in a piddle
$x = zcheck($data);
Signature: (a(n); int+ [o]b())
Project via != 0 to N-1 dimensions
This function reduces the dimensionality of a piddle by one by taking the != 0 along the 1st dimension.
By using the xchg entry in the xchg
PDL::Slices manpage etc. it is possible to use
any dimension.
$a = zcover($b);
$spectrum = zcover $image->xchg(0,1)
construct a zero filled piddle from dimension list or template piddle.
Various forms of usage,
(i) by specification or (ii) by template piddle:
# usage type (i): $a = zeroes([type], $nx, $ny, $nz,...); $a = PDL->zeroes([type], $nx, $ny, $nz,...); $a = $pdl->zeroes([type], $nx, $ny, $nz,...); # usage type (ii): $a = zeroes $b; $a = $b->zeroes zeroes inplace $a; # Equivalent to $a .= 0; $a->inplace->zeroes; # ""
perldl> $z = zeroes 4,3 perldl> p $z [ [0 0 0 0] [0 0 0 0] [0 0 0 0] ] perldl> $z = zeroes ushort, 3,2 # Create ushort array [ushort() etc. with no arg returns a PDL::Types token]
Z axis values between endpoints (see the zvals entry in the zvals
manpage).
See the xlinvals entry in the xlinvals
manpage for more information.
Fills a piddle with Z index values
$x = zvals($somearray); zvals(inplace($somearray)); $x = zvals([OPTIONAL TYPE],$nx,$ny,$nz...);
etc. see the zeroes entry in the zeroes
PDL::Core manpage.
perldl> print zvals zeroes(3,4,2) [ [ [0 0 0] [0 0 0] [0 0 0] [0 0 0] ] [ [1 1 1] [1 1 1] [1 1 1] [1 1 1] ] ]
lapeyre 2006-07-23