PDL::Internals(3pm)
π PDL::Internals π
okay so this is PDL::Internals from the User Contributed Perl Documentation section (3pm), and bestie, it is a lot. it's the deep-lore doc. buckle up π«Ά
β¨ NAME β¨
PDL::Internals β literally a description of some aspects of the current internals π
β¨ SYNOPSIS β¨
# let PDL tell you what it's doing
use PDL;
PDL::Core::set_debugging(1);
$pa = sequence(6, 3, 2);
$pb = $pa->slice('1:3');
$pc = $pb->matmult($pb);
$pd = $pc->dsumover;
print "pb=$pb\npc=$pc\npd=$pd";
β¨ DESCRIPTION β¨
πΈ Intro πΈ
so this doc explains various aspects of the current implementation of PDL. if you just wanna, like, use PDL for something? you definitely do not need to read this. not even if you want to interface your C routines to PDL or make new PDL::PP functions β you do not need to read this man page either (though it may be informative ngl). this document is primarily for people who are into debugging or changing the internals of PDL.
to read this you need a good understanding of the C language, plus programming and data structures in general, plus some Perl understanding. and here's the whole vibe check: if you read through this document, understand all of it, can point out what any part of it refers to in the PDL core sources, and additionally still struggle to understand PDL::PP β you get awarded the title "PDL Guru". π periodt.
β οΈ Warning: if it seems like this document has got out of date, please inform the PDL porters email list (pdl-devel@lists.sourceforge.net). this may well happen. fr fr. π
π¦ ndarrays π¦
the pdl data object is generally an opaque scalar reference into a pdl structure in memory. alternatively, it may be a hash reference with the "PDL" field containing the scalar reference (this makes overloading ndarrays easy, see PDL::Objects). you can easily find out at the Perl level which type of ndarray you are dealing with. the example code below demonstrates how to do it:
# check if this is an ndarray
die "not an ndarray" unless UNIVERSAL::isa($pdl, 'PDL');
# is it a scalar ref or a hash ref?
if (UNIVERSAL::isa($pdl, "HASH")) {
die "not a valid PDL"
unless exists $pdl->{PDL} && UNIVERSAL::isa($pdl->{PDL},'PDL');
print "This is a hash reference,",
" the PDL field contains the scalar ref\n";
} else {
print "This is a scalar ref that points to address $$pdl in memory\n";
}
the scalar reference points to the numeric address of a C structure of type pdl which is defined in pdl.h. the mapping between the object at the Perl level and the C structure containing the actual data and structural [stuff] that makes up an ndarray is done by the PDL typemap. the functions used in the PDL typemap are defined pretty much at the top of the file pdlcore.h. so what does the structure look like:
struct pdl {
unsigned long magicno; /* Always stores PDL_MAGICNO as a sanity check */
/* This is first so most pointer accesses to wrong type are caught */
int state; /* What's in this pdl */
pdl_trans *trans_parent; /* Opaque pointer to internals of transformation from
parent */
pdl_vaffine *vafftrans;
void* sv; /* (optional) pointer back to original sv.
ALWAYS check for non-null before use.
We cannot inc refcnt on this one or we'd
never get destroyed */
void *datasv; /* Pointer to SV containing data. Refcnt inced */
void *data; /* Null: no data alloced for this one */
PDL_Indx nvals; /* How many values allocated */
int datatype;
PDL_Indx *dims; /* Array of data dimensions */
PDL_Indx *dimincs; /* Array of data default increments */
short ndims; /* Number of data dimensions */
unsigned char *broadcastids; /* Starting index of the broadcast index set n */
unsigned char nbroadcastids;
pdl_trans *def_trans_children[PDL_NCHILDREN];
PDL_Indx ntrans_children_allocated;
PDL_Indx first_trans_child_available;
struct pdl_trans *trans_children;
PDL_Indx def_dims[PDL_NDIMS]; /* Preallocated space for efficiency */
PDL_Indx def_dimincs[PDL_NDIMS]; /* Preallocated space for efficiency */
unsigned char def_broadcastids[PDL_NBROADCASTIDS];
struct pdl_magic *magic;
void *hdrsv; /* "header", settable from outside */
PDL_Value value; /* to store at least one value */
};
that is quite a structure for just storing some data in β so like, what is going on?? π
π Data storage π
we're gonna start with some of the simpler members. first of all, there are the members (as of 2.078)
void *datasv;
PDL_Value value; /* to store at least one value */
which are a pointer to a Perl SV structure (SV *), and a union value of all possible single PDL values. if the ndarray's whole data will fit in the value, the datasv will not be used except by get_dataref in PDL::Core for temporary use by Perl code. it will then be destroyed by the call to upd_data in PDL::Core method unless that is passed a true value to keep the datasv around (largely used by the memory-mapping implementation).
otherwise, the SV is expected to be representing a string, in which the data of the ndarray is stored in a tightly packed form. this pointer counts as a reference to the SV, so the reference count has been incremented when the SV * was placed here (this reference count business has to do with Perl's garbage collection mechanism β don't worry if this doesn't mean much to you, bestie). this pointer is allowed to have the value NULL which means that there is no actual Perl SV for this data, as alluded above. note the use of an SV* was purely for convenience, it allows easy transformation of packed data from files into ndarrays. other implementations are not excluded.
the actual pointer to data is stored in the member
void *data;
which contains a pointer to a memory area with space for
PDL_Indx nvals;
data items of the data type of this ndarray. PDL_Indx is either 'long' or 'long long' depending on whether your perl is 64bit or not.
the data type of the data is stored in the variable
int datatype;
the values for this member are given in the enum pdl_datatypes (see pdl.h). currently we have byte, short, unsigned short, long, index (either long or long long), long long, float and double (plus complex equivalents) types, see also PDL::Types.
π§ Dimensions π§
the number of dimensions in the ndarray is given by the member
int ndims;
which shows how many entries there are in the arrays
PDL_Indx *dims;
PDL_Indx *dimincs;
these arrays are intimately related: dims gives the sizes of the dimensions and dimincs is always calculated by the code
PDL_Indx inc = 1;
for(i=0; i<it->ndims; i++) {
it->dimincs[i] = inc; inc *= it->dims[i];
}
in the routine pdl_resize_defaultincs in pdlapi.c. what this means is that the dimincs can be used to calculate the offset by code like
PDL_Indx offs = 0;
for(i=0; i<it->ndims; i++) {
offs += it->dimincs[i] * index[i];
}
but this is not always the right thing to do, at least without checking for certain things first. π
π Default storage π
since the vast majority of ndarrays don't have more than 6 dimensions, it is more efficient to have default storage for the dimensions and dimincs inside the PDL struct.
PDL_Indx def_dims[PDL_NDIMS];
PDL_Indx def_dimincs[PDL_NDIMS];
the dims and dimincs may be set to point to the beginning of these arrays if ndims is smaller than or equal to the compile-time constant PDL_NDIMS. this is important to note when freeing an ndarray struct. the same applies for the broadcastids:
unsigned char def_broadcastids[PDL_NBROADCASTIDS];
π₯ Magic π₯
it is possible to attach magic to ndarrays, much like Perl's own magic mechanism. if the member pointer
struct pdl_magic *magic;
is nonzero, the PDL has some magic attached to it. the implementation of magic can be gleaned from the file pdlmagic.c in the distribution.
β State β
one of the first members of the structure is
int state;
the possible flags and their meanings are given in pdl.h. these are mainly used to implement the lazy evaluation mechanism and keep track of ndarrays in these operations.
πΈ Transformations and virtual affine transformations πΈ
as you should already know, ndarrays often carry information about where they come from. for example, the code
$y = $x->slice("2:5");
$y .= 1;
will alter $x. so $x and $y know that they are connected via a "slice"-transformation. this information is stored in the members
pdl_trans *trans_parent;
pdl_vaffine *vafftrans;
both $x (the parent) and $y (the child) store this information about the transformation in appropriate slots of the pdl structure.
pdl_trans and pdl_vaffine are structures that we will look at in more detail below.
π The Perl SVs π
when ndarrays are referred to through Perl SVs, we store an additional reference to it in the member
void* sv;
in order to be able to return a reference to the user when they want to inspect the transformation structure on the Perl side.
also, we store an opaque
void *hdrsv;
which is just for use by the user to hook up arbitrary data with this sv. this one is generally manipulated through sethdr and gethdr calls.
π Smart references and transformations: slicing and dicing π
smart references and most other fundamental functions operating on ndarrays are implemented via transformations (as mentioned above) which are represented by the type pdl_trans in PDL.
a transformation links input and output ndarrays and contains all the infrastructure that defines how:
- output ndarrays are obtained from input ndarrays;
- changes in smart-linked output ndarrays (e.g. the child of a sliced parent ndarray) are flowed back to the input ndarray in transformations where this is supported (the most often used example being
slicehere); - datatype and size of output ndarrays that need to be created are obtained.
okay so real talk π
β in general, when you run a PDL function over a whole group of ndarrays, what you get is a transformation of whatever type you asked for, and that transformation links all the input and output args together (at least the ones that are actually ndarrays). In flowing functions β the ones that do data flow between input and output args, like slice and index β that transformation links parent (input) and child (output) ndarrays permanently, like a situationship that refuses to end, until either the link gets explicitly broken by user request (sever at the Perl level) or all the parents and children have been destroyed. In those cases the transformation is lazy-evaluated, meaning it only actually runs when ndarray values are genuinely accessed.
In non-flowing functions, for example addition (+) and inner products (inner), the transformation is installed just like in flowing functions, but then it's immediately executed and destroyed (so the link between input and output args gets broken) before the function returns. Wham, bam, done. β¨
It should be noted β and this is the part that makes people go π β that the close link between input and output args of a flowing function (like slice) requires ndarray objects that are linked this way to be kept alive past the point where they've gone out of scope from Perl's point of view:
$x = zeroes(20);
$y = $x->slice('2:4');
undef $x; # last reference to $x is now destroyed
So even though $x should now be destroyed according to Perl's rules, the underlying pdl structure actually can only be freed once $y also goes out of scope (because it still internally references some of $x's data). This example is literally demonstrating that a dataflow paradigm between PDL objects necessitates a special destruction algorithm that takes the links between ndarrays into account and couples their lifespans together. That non-trivial algorithm is implemented in the function pdl_destroy in pdlapi.c. In fact, most of the code in pdlapi.c is concerned with making sure ndarrays (pdl *s) get created, updated and freed at the right times, depending on how they interact with other ndarrays via PDL transformations (remember, pdl_trans). π§
π Accessing children and parents of an ndarray π
When ndarrays get dynamically linked via transformations like we just described, the input ndarrays are called parents and the output ndarrays are called children.
A whole example of processing an ndarray's children is provided by the method badflag in PDL::Bad (before 2.079 it only operated on the children, though now it propagates to parents too).
Consider the following situation:
pdl> $x = rvals(7,7,{Centre=>[3,4]});
pdl> $y = $x->slice('2:4,3:5');
pdl> ? vars
PDL variables in package main::
Name Type Dimension Flow State Mem
----------------------------------------------------------------
$x Double D [7,7] P 0.38Kb
$y Double D [3,3] -C 0.00Kb
Now, if I suddenly decide that $x should be flagged as possibly containing bad values, using
pdl> $x->badflag(1)
then I want the state of $y β its child β to be changed as well (since it will either share or inherit some of $x's data and so be also bad), so that I get a B in the State field:
pdl> ? vars
PDL variables in package main::
Name Type Dimension Flow State Mem
----------------------------------------------------------------
$x Double D [7,7] PB 0.38Kb
$y Double D [3,3] -CB 0.00Kb
This bit of magic is performed by the propagate_badflag function, which is in pdlapi.c. Given an ndarray (pdl *it), the routine loops through each pdl_trans structure, where access to this structure is provided by the PDL_CHILDLOOP_THISCHILD macro. The children of the ndarray are stored in the pdls array, after the parents β hence the loop from i = ...nparents to i = ...npdls - 1. Once we have the pointer to the child ndarray, we can do whatever we want to it; here we change the value of the state variable, but the details are unimportant. What is important is that we call propagate_badflag on this ndarray, to make sure we loop through its children. This recursion makes sure we get to all the offspring of a particular ndarray.
Accessing parents is similar, with the for loop replaced by:
for( i = 0;
i < trans->vtable->nparents;
i++ ) {
/* do stuff with parent #i: trans->pdls[i] */
}
πΈ What's in a transformation (pdl_trans) πΈ
All transformations are implemented as structures:
struct pdl_trans {
int magicno; /* to detect memory overwrites */
short flags; /* state of the trans */
pdl_transvtable *vtable; /* the all important vtable */
int __datatype; /* the type of the transformation */
void *params; /* Opaque pointer to "compiled representation" of transformation */
pdl *pdls[]; /* The pdls involved in the transformation */
};
The params member is an opaque pointer, typically to a C struct that holds the "compiled representation" (generated by PDL::PP), and it's the way info like OtherPars etc get communicated from the invoking code to the redodims function β effectively a closure, in Perl/LISP terms. This is necessary because redodims gets called by a PDL-internal function, and therefore must have a fixed parameter list.
The transformation identifies all pdls involved in the trans:
pdl *pdls[];
This is a C99 "incomplete array type", and it works because it's at the end of the struct β PDL allocates the correct amount of memory based on the npdls member of the vtable. The trans records the state
short flags;
and the datatype
int __datatype;
of the trans (and all ndarrays must be converted to that datatype unless they're explicitly typed; PDL functions created with PDL::PP make sure these conversions happen as necessary). Most important of all is the pointer to the vtable (virtual table) that contains the actual functionality:
pdl_transvtable *vtable;
The vtable structure in turn looks something like (slightly simplified from pdl.h for clarity):
typedef struct pdl_transvtable {
int flags;
int nparents; /* number of parent pdls (input) */
int npdls; /* number of child pdls (output) */
char *per_pdl_flags; /* optimization flags */
pdl_error (*redodims)(pdl_trans *tr); /* figure out dims of children */
pdl_error (*readdata)(pdl_trans *tr); /* flow parents to children */
pdl_error (*writebackdata)(pdl_trans *tr); /* flow backwards */
pdl_error (*freetrans)(pdl_trans *tr, char);
int structsize;
char *name; /* the function's name */
} pdl_transvtable;
The transformation and vtable code is hardly ever written by hand β it's rather generated by PDL::PP from concise descriptions. Iconic behavior honestly. π
Certain types of transformations can be optimized very efficiently, which obviates the need for explicit readdata and writebackdata methods. Those transformations are called pdl_vaffine. Most dimension-manipulating functions (e.g., slice, xchg) belong to this class.
The basic trick is that parent and child of such a transformation work on the same (shared) block of data, which they just choose to interpret differently (by using different dims, dimincs and offs on the same data, compare the pdl structure above). So every operation on an ndarray that shares data with another one this way is automatically flowed from child to parent and back β like, after all, they are reading and writing the same block of memory. π«Ά
β οΈ Heads up bestie: this is currently not Perl thread safe β no big loss though, since the whole PDL core is not reentrant. π
β¨ Callback functions β¨
redodims
Works out the dimensions of ndarrays that need to be created, and gets called from within the API function that should be called to ensure an ndarray's dimensions are accessible (pdlapi.c):
pdl_error pdl_make_physdims(pdl *it)
readdata and writebackdata
These are responsible for the actual computations β child data from the parents, or parent data from the children, respectively (that's the dataflow aspect). readdata populates the children from the parents, and writebackdata implements updating the parent(s) from the child(ren) if dataflow is part of that transformation. The PDL core makes sure these get called as needed when ndarray data is accessed (lazy-evaluation, we love her). The general API function that makes sure an ndarray is up-to-date is
pdl_error pdl_make_physvaffine(pdl *it)
which should be called before accessing ndarray data from XS/C (go peek at Core.xs for some examples). π
freetrans
Frees dynamically allocated memory associated with the trans as needed. If redodims has previously been called, it will free any vaffine-associated memory. If the destroy parameter is true, it will also free any bespoke params-connected memory β this will not be the case if it's called before doing another redodims. Again, functions built with PDL::PP make sure that freeing via these callbacks happens at the right times. π
π¦ Signatures: broadcasting over elementary operations π¦
Most of that functionality of PDL broadcasting (automatic iteration of elementary operations over multi-dim ndarrays) is implemented in the file pdlbroadcast.c.
The PDL::PP generated functions (in particular the readdata and writebackdata callbacks) use this infrastructure to make sure that the fundamental operation implemented by the trans is performed in agreement with PDL's broadcasting semantics.
π Defining new PDL functions -- Glue code generation π
Please, see PDL::PP and examples in the PDL distribution. Implementation and syntax are currently far from perfect but it does a good job! fr fr π
π The Core struct π
As discussed in PDL::API, PDL uses a pointer to a structure to allow PDL modules access to its core routines. The definition of this structure (the Core struct) is in pdlcore.h (created by pdlcore.h in Basic/Core) and looks something like
/* Structure to hold pointers core PDL routines so as to be used by
* many modules
*/
struct Core {
I32 Version;
pdl* (*SvPDLV) ( SV* );
void (*SetSV_PDL) ( SV *sv, pdl *it );
pdl* (*pdlnew) ( );
pdl* (*tmp) ( );
pdl* (*create) (int type);
pdl_error (*destroy) (pdl *it);
...
}
typedef struct Core Core;
The first field of the structure (Version) is used to ensure consistency between modules at run time; the following code is placed in the BOOT section of the generated xs code:
if (PDL->Version != PDL_CORE_VERSION)
Perl_croak(aTHX_ "Foo needs to be recompiled against the newly installed PDL");
If you add a new field to the Core struct you should:
- hop on the pdl porters email list</> (
pdl-devel@lists.sourceforge.net) and pull the moves fromPDL::FAQ4.11. teamwork fr fr π - bump the value of the
"PDL_CORE_VERSION"C macro by 1 β that's the one used to populate theVersionfield, inpdlcore.h. little number, big responsibility π€ - drop some docs in (like, over in
PDL::API) if it's a "useful" function for external module writers β and also make sure the code is as well documented as the rest of PDL ;) yes that wink is in the original, we keep the wink π
π BUGS π
ngl, this description is far from perfect. it said it, not me if you need more deets or something is still giving unclear, please just ask on the pdl-devel mailing list (pdl-devel@lists.sourceforge.net). we don't bite, we just debug π«Ά
π AUTHOR π
Copyright(C) 1997 Tuomas J. Lukka (lukka@fas.harvard.edu), 2000 Doug Burke (djburke@cpan.org), 2002 Christian Soeller & Doug Burke, 2013 Chris Marshall. legends, all of them β¨π
okay bestie that's a wrap on PDL::Internals(3pm) π this one lived in perl v5.42.3, dated 2026-08-20, and honestly? it ate. go forth and internals responsibly π
πΈπ¦
π¦ where this page comes from
- ubuntu stonking: pdl 1:2.106-1build1 Β· Artistic-1.0-Perl OR GPL-1.0-or-later
- π girlified by deepseek-ai/DeepSeek-V4.1-Flash on : a language model's rewrite of the original, under its terms