PDL::B...casting(3pm)
β¨ PDL::Broadcasting β¨
ok so bestie, this is the manual page for PDL::Broadcasting, aka the tutorial for PDL's broadcasting feature (it's a 3pm page, if you're keeping track π). Sit down, grab a strawberry π, and let me tell you about the single most iconic thing PDL does.
π INTRODUCTION π
One of the most powerful features of PDL is broadcasting, which can produce very compact and very fast PDL code by avoiding multiple nested for loops that C and BASIC users may be familiar with. Like, the C girlies are out here writing nested loops and we're just... not. π
The trouble is that it can take some getting used to, and new users may not appreciate the benefits of broadcasting. It's giving "trust the process" energy fr fr.
Other vector based languages, such as MATLAB, use a subset of broadcasting techniques, but PDL shines by completely generalizing them for all sorts of vector-based applications. PDL went to the gym and did not skip a single day, no cap. π₯
π§ TERMINOLOGY: NDARRAY π§
MATLAB typically refers to vectors, matrices, and arrays. But here's the thing: Perl already has arrays, and the terms "vector" and "matrix" typically refer to one- and two-dimensional collections of data. Having no good term to describe their object, PDL developers coined the term "ndarray" to give a name to their data type. iconic naming behaviour honestly π
An ndarray consists of a series of numbers organized as an N-dimensional data set. ndarrays provide efficient storage and fast computation of large N-dimensional matrices. They are highly optimized for numerical work. π
π¦ THINKING IN TERMS OF BROADCASTING π¦
If you have used PDL for a little while already, you may have been using broadcasting without realising it. (Not me gaslighting you about your own code π). Start the PDL shell β type perldl on a terminal. Most examples in this tutorial use the PDL shell. Make sure that PDL::NiceSlice and PDL::AutoLoader are enabled. For example:
% perldl
perlDL shell v1.352
...
ReadLines, NiceSlice, MultiLines enabled
...
Note: AutoLoader not enabled ('use PDL::AutoLoader' recommended)
pdl>
In this example, NiceSlice was automatically enabled, but AutoLoader was not. To enable it, type use PDL::AutoLoader.
Let's start with a two-dimensional ndarray:
pdl> $x = sequence(11,9)
pdl> p $x
[
[ 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 40 41 42 43]
[44 45 46 47 48 49 50 51 52 53 54]
[55 56 57 58 59 60 61 62 63 64 65]
[66 67 68 69 70 71 72 73 74 75 76]
[77 78 79 80 81 82 83 84 85 86 87]
[88 89 90 91 92 93 94 95 96 97 98]
]
The info method gives you basic information about an ndarray:
pdl> p $x->info
PDL: Double D [11,9]
This tells us that $x is an 11 x 9 ndarray composed of double precision numbers. So if we wanted to add 3 to all elements in an "n x m" ndarray, a traditional language would use two nested for-loops:
# Pseudo-code. Traditional way to add 3 to an array.
for (i=0; i < n; i++) {
for (j=0; j < m; j++) {
a(i,j) = a(i,j) + 3
}
}
Note: Notice that indices start at 0, as in Perl, C and Java (and unlike MATLAB and IDL). Zero-indexing girlies rise up π
But with PDL, we can just write:
pdl> $y = $x + 3
pdl> p $y
[
[ 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 40 41 42 43 44 45 46]
[ 47 48 49 50 51 52 53 54 55 56 57]
[ 58 59 60 61 62 63 64 65 66 67 68]
[ 69 70 71 72 73 74 75 76 77 78 79]
[ 80 81 82 83 84 85 86 87 88 89 90]
[ 91 92 93 94 95 96 97 98 99 100 101]
]
This is the simplest example of broadcasting, and it is something that all numerical software tools do. The + 3 operation was automatically applied along two dimensions. slay. β¨
Now suppose you want to to subtract a line from every row in $x:
pdl> $line = sequence(11)
pdl> p $line
[0 1 2 3 4 5 6 7 8 9 10]
pdl> $c = $x - $line
pdl> p $c
[
[ 0 0 0 0 0 0 0 0 0 0 0]
[11 11 11 11 11 11 11 11 11 11 11]
[22 22 22 22 22 22 22 22 22 22 22]
[33 33 33 33 33 33 33 33 33 33 33]
[44 44 44 44 44 44 44 44 44 44 44]
[55 55 55 55 55 55 55 55 55 55 55]
[66 66 66 66 66 66 66 66 66 66 66]
[77 77 77 77 77 77 77 77 77 77 77]
[88 88 88 88 88 88 88 88 88 88 88]
]
Two things to note here:
- First, the value of
$xis still the same. Tryp $xto check. (it did not get touched, bestie is safe π) - Second, PDL automatically subtracted
$linefrom each row in$x. Why did it do that? Let's look at the dimensions of$x,$lineand$c:
pdl> p $line->info => PDL: Double D [11]
pdl> p $x->info => PDL: Double D [11,9]
pdl> p $c->info => PDL: Double D [11,9]
So, both $x and $line have the same number of elements in the 0th dimension! What PDL then did was broadcast over the higher dimensions in $x and repeated the same operation 9 times to all the rows on $x. This is PDL broadcasting in action. main character energy honestly π
What if you want to subtract $line from the first line in $x only? You can do that by specifying the line explicitly:
pdl> $x(:,0) -= $line
pdl> p $x
[
[ 0 0 0 0 0 0 0 0 0 0 0]
[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 40 41 42 43]
[44 45 46 47 48 49 50 51 52 53 54]
[55 56 57 58 59 60 61 62 63 64 65]
[66 67 68 69 70 71 72 73 74 75 76]
[77 78 79 80 81 82 83 84 85 86 87]
[88 89 90 91 92 93 94 95 96 97 98]
]
See PDL::Indexing and PDL::NiceSlice to learn more about specifying subsets from ndarrays. π
The true power of broadcasting comes when you realise that the ndarray can have any number of dimensions! Let's make a 4 dimensional ndarray:
pdl> $ndarray_4D = sequence(11,3,7,2)
pdl> $c = $ndarray_4D - $line
Now $c is an ndarray of the same dimension as $ndarray_4D.
pdl> p $ndarray_4D->info => PDL: Double D [11,3,7,2]
pdl> p $c->info => PDL: Double D [11,3,7,2]
This time PDL has broadcasted over three higher dimensions automatically, subtracting $line all the way. it ate and left no crumbs π₯
But, maybe you don't want to subtract from the rows (dimension 0), but from the columns (dimension 1). How do I subtract a column of numbers from each column in $x?
pdl> $cols = sequence(9)
pdl> p $x->info => PDL: Double D [11,9]
pdl> p $cols->info => PDL: Double D [9]
Naturally, we can't just type $x - $cols. The dimensions don't match:
pdl> p $x - $cols
PDL: PDL::Ops::minus(a,b,c): Parameter 'b'
PDL: Mismatched implicit broadcast dimension 0: should be 11, is 9
π the vibes are off. So how do we tell PDL that we want to subtract from dimension 1 instead?
π MANIPULATING DIMENSIONS π
There are many PDL functions that let you rearrange the dimensions of PDL arrays. They are mostly covered in PDL::Slices. The three most common ones are:
xchgmvreorder
π Method: xchg π
The xchg method "exchanges" two dimensions in an ndarray:
pdl> $x = sequence(6,7,8,9)
pdl> $x_xchg = $x->xchg(0,3)
pdl> p $x->info => PDL: Double D [6,7,8,9]
pdl> p $x_xchg->info => PDL: Double D [9,7,8,6]
| |
V V
(dim 0) (dim 3)
Notice that dimensions 0 and 3 were exchanged without affecting the other dimensions. Notice also that xchg does not alter $x. The original variable $x remains untouched. she's unbothered, moisturized, in her lane π§ββοΈ
π Method: mv π
The mv method "moves" one dimension, in an ndarray, shifting other dimensions as necessary.
pdl> $x = sequence(6,7,8,9) (dim 0)
pdl> $x_mv = $x->mv(0,3) |
pdl> V _____
pdl> p $x->info => PDL: Double D [6,7,8,9]
pdl> p $x_mv->info => PDL: Double D [7,8,9,6]
----- |
V
(dim 3)
Notice that when dimension 0 was moved to position 3, all the other dimensions had to be shifted as well. Notice also that mv does not alter $x. The original variable $x remains untouched. same girl, different position, we love to see it β¨
π Method: reorder π
The reorder method is a generalization of the xchg and mv methods. It "reorders" the dimensions in any way you specify:
pdl> $x = sequence(6,7,8,9)
pdl> $x_reorder = $x->reorder(3,0,2,1)
pdl>
pdl> p $x->info => PDL: Double D [6,7,8,9]
pdl> p $x_reorder->info => PDL: Double D [9,6,8,7]
| | | |
V V v V
dimensions: 0 1 2 3
Notice what happened. When we wrote reorder(3,0,2,1) we instructed PDL to:
- Put dimension 3 first.
- Put dimension 0 next.
- Put dimension 2 next.
- Put dimension 1 next.
When you use the reorder method, all the dimensions are shuffled. Notice that reorder does not alter $x. The original variable $x remains untouched. queen of not destroying your data π
β οΈ GOTCHA: LINKING VS ASSIGNMENT β οΈ
π Linking π
By default, ndarrays are linked together so that changes on one will go back and affect the original as well. it's giving clingy, but make it linear algebra π
pdl> $x = sequence(4,5)
pdl> $x_xchg = $x->xchg(1,0)
Here, $x_xchg is not a separate object. It is merely a different way of looking at $x. Any change in $x_xchg will appear in $x as well. (they're literally the same girl, just in a different fit π«Ά)
pdl> p $x
[
[ 0 1 2 3]
[ 4 5 6 7]
[ 8 9 10 11]
[12 13 14 15]
[16 17 18 19]
]
pdl> $x_xchg += 3
pdl> p $x
[
[ 3 4 5 6]
[ 7 8 9 10]
[11 12 13 14]
[15 16 17 18]
[19 20 21 22]
]
π Assignment π
Some times, linking is not the behaviour you want. If you want to make the ndarrays independent, use the copy method:
pdl> $x = sequence(4,5)
pdl> $x_xchg = $x->copy->xchg(1,0)
Now $x and $x_xchg are completely separate objects:
pdl> p $x
[
[ 0 1 2 3]
[ 4 5 6 7]
[ 8 9 10 11]
[12 13 14 15]
[16 17 18 19]
]
pdl> $x_xchg += 3
pdl> p $x
[
[ 0 1 2 3]
[ 4 5 6 7]
[ 8 9 10 11]
[12 13 14 15]
[16 17 18 19]
]
pdl> $x_xchg
[
[ 3 7 11 15 19]
[ 4 8 12 16 20]
[ 5 9 13 17 21]
[ 6 10 14 18 22]
]
see how $x didn't move at all? that's the copy. boundaries, bestie. we love them. π
β¨ PUTTING IT ALL TOGETHER β¨
okay bestie, time to actually solve the thing that started this whole yap session π«Ά
pdl> $x = sequence(11,9)
pdl> $cols = sequence(9)
pdl>
pdl> p $x->info => PDL: Double D [11,9]
pdl> p $cols->info => PDL: Double D [9]
so like. how do we tell PDL "hey, subtract $cols along dimension 1, not dimension 0"? π the simplest way is to use the xchg method and just let PDL linking do its thing β¨
pdl> p $x
[
[ 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 40 41 42 43]
[44 45 46 47 48 49 50 51 52 53 54]
[55 56 57 58 59 60 61 62 63 64 65]
[66 67 68 69 70 71 72 73 74 75 76]
[77 78 79 80 81 82 83 84 85 86 87]
[88 89 90 91 92 93 94 95 96 97 98]
]
pdl> $x->xchg(1,0) -= $cols
pdl> p $x
[
[ 0 1 2 3 4 5 6 7 8 9 10]
[10 11 12 13 14 15 16 17 18 19 20]
[20 21 22 23 24 25 26 27 28 29 30]
[30 31 32 33 34 35 36 37 38 39 40]
[40 41 42 43 44 45 46 47 48 49 50]
[50 51 52 53 54 55 56 57 58 59 60]
[60 61 62 63 64 65 66 67 68 69 70]
[70 71 72 73 74 75 76 77 78 79 80]
[80 81 82 83 84 85 86 87 88 89 90]
]
look at that glow-up ππ literally subtracted down the columns instead of across the rows. iconique.
General Strategy:
move the dimensions you wanna work on to the start of your ndarray's dimension list. then just let PDL broadcast over the higher dimensions. that's it. that's the whole trick. periodt π
π¦ EXAMPLE: CONWAY'S GAME OF LIFE π¦
okay enough theory, bestie, let's actually do something fun. we're writing Conway's Game of Life in PDL and watching it absolutely eat π₯
the Game of Life is a simulation that runs on a big two-dimensional grid. every cell in the grid is either alive or dead (represented by 1 or 0). the next generation of cells gets calculated with simple rules based on how many living cells are hanging out in its immediate neighbourhood:
- if an empty cell has exactly three neighbours, a living cell is generated.
- if a living cell has less than two neighbours, it dies of overfeeding.
- if a living cell has 4 or more neighbours, it dies from starvation.
only the first generation is picked by the programmer. after that the simulation just vibes entirely according to these rules πΈ to calculate the next generation you need to look at each cell in the 2D field (two loops), count the live cells next to that cell (two more loops) and then fill in the next generation grid.
π Classical implementation
here's the classic way to write this in Perl. we're only using PDL for addressing individual cells. very "doing it the hard way" energy ngl π
#!/usr/bin/perl -w
use PDL;
use PDL::NiceSlice;
# Make a board for the game of life.
my $nx = 20;
my $ny = 20;
# Current generation.
my $a1 = zeroes($nx, $ny);
# Next generation.
my $n = zeroes($nx, $ny);
# Put in a simple glider.
$a1(1:3,1:3) .= pdl ( [1,1,1],
[0,0,1],
[0,1,0] );
for (my $i = 0; $i < 100; $i++) {
$n = zeroes($nx, $ny);
$new_a = $a1->copy;
for ($x = 0; $x < $nx; $x++) {
for ($y = 0; $y < $ny; $y++) {
# For each cell, look at the surrounding neighbours.
for ($dx = -1; $dx <= 1; $dx++) {
for ($dy = -1; $dy <= 1; $dy++) {
$px = $x + $dx;
$py = $y + $dy;
# Wrap around at the edges.
if ($px < 0) {$px = $nx-1};
if ($py < 0) {$py = $ny-1};
if ($px >= $nx) {$px = 0};
if ($py >= $ny) {$py = 0};
$n($x,$y) .= $n($x,$y) + $a1($px,$py);
}
}
# Do not count the central cell itself.
$n($x,$y) -= $a1($x,$y);
# Work out if cell lives or dies:
# Dead cell lives if n = 3
# Live cell dies if n is not 2 or 3
if ($a1($x,$y) == 1) {
if ($n($x,$y) < 2) {$new_a($x,$y) .= 0};
if ($n($x,$y) > 3) {$new_a($x,$y) .= 0};
} else {
if ($n($x,$y) == 3) {$new_a($x,$y) .= 1}
}
}
}
print $a1;
$a1 = $new_a;
}
if you run this, you'll see a little glider crawl diagonally across the grid of zeroes π¦ on my machine it prints out a couple of generations per second. cute but slow, bestie. we can do so much better.
π¦ Broadcasting PDL implementation
and here's the broadcasted version in PDL. literally four lines of PDL code, and one of those is just printing out the latest generation πβ¨
#!/usr/bin/perl -w
use PDL;
use PDL::NiceSlice;
my $x = zeroes(20,20);
# Put in a simple glider.
$x(1:3,1:3) .= pdl ( [1,1,1],
[0,0,1],
[0,1,0] );
my $n;
for (my $i = 0; $i < 100; $i++) {
# Calculate the number of neighbours per cell.
$n = $x->range(ndcoords($x)-1,3,"periodic")->reorder(2,3,0,1);
$n = $n->sumover->sumover - $x;
# Calculate the next generation.
$x = ((($n == 2) + ($n == 3))* $x) + (($n==3) * !$x);
print $x;
}
the broadcasted PDL version is much faster:
Classical => 32.79 seconds.
Broadcasting => 0.41 seconds.
not the 32.79 seconds vs 0.41 seconds difference just casually ending the classical version's whole career ππ₯ ate and left no crumbs fr fr.
π Explanation
so like, how does the broadcasted version actually work? π
there are many PDL functions designed to help you carry out PDL broadcasting. in this example, the key functions are:
π Method: range
at the simplest level, the range method is just a different way to select a portion of an ndarray. instead of using the $x(2,3) notation, we use another ndarray. wild, i know.
pdl> $x = sequence(6,7)
pdl> p $x
[
[ 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 40 41]
]
pdl> p $x->range( pdl [1,2] )
13
pdl> p $x(1,2)
[
[13]
]
at this point, the range method looks very similar to a regular PDL slice. but bestie, range is more general than that π for example, you can select several components at once:
pdl> $index = pdl [ [1,2],[2,3],[3,4],[4,5] ]
pdl> p $x->range( $index )
[13 20 27 34]
additionally, range takes a second parameter which determines the size of the chunk to return:
pdl> $size = 3
pdl> p $x->range( pdl([1,2]) , $size )
[
[13 14 15]
[19 20 21]
[25 26 27]
]
we can use this to select one or more 3x3 boxes π
finally, range can take a third parameter called the boundary condition. it tells PDL what to do if the size box you request goes beyond the edge of the ndarray. we won't go over all the options. we'll just say that the option "periodic" means that the ndarray "wraps around". for example:
pdl> p $x
[
[ 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 40 41]
]
pdl> $size = 3
pdl> p $x->range( pdl([4,2]) , $size , "periodic" )
[
[16 17 12]
[22 23 18]
[28 29 24]
]
pdl> p $x->range( pdl([5,2]) , $size , "periodic" )
[
[17 12 13]
[23 18 19]
[29 24 25]
]
notice how the box wraps around the boundary of the ndarray π it's giving "the grid is a donut" and honestly? iconic.
πΈ Method: ndcoords
the ndcoords method is a convenience method that returns an enumerated list of coordinates suitable for use with the range method β¨
pdl> p $ndarray = sequence(3,3)
[
[0 1 2]
[3 4 5]
[6 7 8]
]
pdl> p ndcoords($ndarray)
[
[
[0 0]
[1 0]
[2 0]
]
[
[0 1]
[1 1]
[2 1]
]
[
[0 2]
[1 2]
[2 2]
]
]
ngl this can be a little hard to read π basically it's saying that the coordinates for every element in $ndarray is given by:
(0,0) (1,0) (2,0)
(1,0) (1,1) (2,1)
(2,0) (2,1) (2,2)
π§ Combining range and ndcoords
what really matters is that ndcoords is designed to work together with range β with no $size parameter, you get the same ndarray back. no cap.
pdl> p $ndarray
[
[0 1 2]
[3 4 5]
[6 7 8]
]
pdl> p $ndarray->range( ndcoords($ndarray) )
[
[0 1 2]
[3 4 5]
[6 7 8]
]
why would this be useful, you ask? π€ because now we can ask for a series of "boxes" for the entire ndarray. for example, 2x2 boxes:
pdl> p $ndarray->range( ndcoords($ndarray) , 2 , "periodic" )
the output of this function is difficult to read because the "boxes" along the last two dimension. we can make the result more readable by rearranging the dimensions:
pdl> p $ndarray->range( ndcoords($ndarray) , 2 , "periodic" )->reorder(2,3,0,1)
[
[
[
[0 1]
[3 4]
]
[
[1 2]
[4 5]
]
...
]
here you can see more clearly that
[0 1]
[3 4]
is the 2x2 box starting with the (0,0) element of $ndarray π
we're not done yet though! for the game of life, we want 3x3 boxes from $x:
pdl> p $x
[
[ 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 40 41]
]
pdl> p $x->range( ndcoords($x) , 3 , "periodic" )->reorder(2,3,0,1)
[
[
[
[ 0 1 2]
[ 6 7 8]
[12 13 14]
]
...
]
we can confirm that this is the 3x3 box starting with the (0,0) element of $x. but there's one problem: we actually want the 3x3 box to be centered on (0,0). that's not a problem though π
just subtract 1 from all the coordinates in ndcoords($x). remember that the "periodic" option takes care of making everything wrap around.
pdl> p $x->range( ndcoords($x) - 1 , 3 , "periodic" )->reorder(2,3,0,1)
[
[
[
[41 36 37]
[ 5 0 1]
[11 6 7]
]
[
[36 37 38]
[ 0 1 2]
[ 6 7 8]
]
...
]
now we see a 3x3 box with the (0,0) element in the centre of the box π― periodt.
β Method: sumover
the sumover method adds along only the first dimension. if we apply it twice, we will be adding all the elements of each 3x3 box β¨
pdl> $n = $x->range(ndcoords($x)-1,3,"periodic")->reorder(2,3,0,1)
pdl> p $n
[
[
[
[41 36 37]
[ 5 0 1]
[11 6 7]
]
[
[36 37 38]
[ 0 1 2]
[ 6 7 8]
]
...
pdl> p $n->sumover->sumover
[
[144 135 144 153 162 153]
[ 72 63 72 81 90 81]
[126 117 126 135 144 135]
[180 171 180 189 198 189]
[234 225 234 243 252 243]
[288 279 288 297 306 297]
[216 207 216 225 234 225]
]
grab a calculator bestie, fr β like, verify it yourself: 144 is literally the sum of every element in the first 3x3 box, and 135 is the sum of every element in the second 3x3 box. β¨
β¨ Counting neighbours β¨
we're SO close, i can feel it π«Ά
adding up everything in a 3x3 box isn't quite it tho. we do not want the center box counted, obviously. luckily that's a one-line fix, slay:
pdl> p $n->sumover->sumover - $x
[
[144 134 142 150 158 148]
[ 66 56 64 72 80 70]
[114 104 112 120 128 118]
[162 152 160 168 176 166]
[210 200 208 216 224 214]
[258 248 256 264 272 262]
[180 170 178 186 194 184]
]
and when you point that at Conway's Game of Life, it straight up tells you how many living neighbours every single cell has:
pdl> $x = zeroes(10,10)
pdl> $x(1:3,1:3) .= pdl ( [1,1,1],
..( > [0,0,1],
..( > [0,1,0] )
pdl> p $x
[
[0 0 0 0 0 0 0 0 0 0]
[0 1 1 1 0 0 0 0 0 0]
[0 0 0 1 0 0 0 0 0 0]
[0 0 1 0 0 0 0 0 0 0]
[0 0 0 0 0 0 0 0 0 0]
[0 0 0 0 0 0 0 0 0 0]
[0 0 0 0 0 0 0 0 0 0]
[0 0 0 0 0 0 0 0 0 0]
[0 0 0 0 0 0 0 0 0 0]
[0 0 0 0 0 0 0 0 0 0]
]
pdl> $n = $x->range(ndcoords($x)-1,3,"periodic")->reorder(2,3,0,1)
pdl> $n = $n->sumover->sumover - $x
pdl> p $n
[
[1 2 3 2 1 0 0 0 0 0]
[1 1 3 2 2 0 0 0 0 0]
[1 3 5 3 2 0 0 0 0 0]
[0 1 1 2 1 0 0 0 0 0]
[0 1 1 1 0 0 0 0 0 0]
[0 0 0 0 0 0 0 0 0 0]
[0 0 0 0 0 0 0 0 0 0]
[0 0 0 0 0 0 0 0 0 0]
[0 0 0 0 0 0 0 0 0 0]
[0 0 0 0 0 0 0 0 0 0]
]
so like, fun fact from that output: cell (0,0) has 1 living neighbour, and cell (2,2) has 5 living neighbours. iykyk π
β¨ Calculating the next generation β¨
okay so at this point $n holds the number of living neighbours for every cell. now we're just applying the rules of the game of life to get the next generation. no cap.
If an empty cell has exactly three neighbours, a living cell is generated.
get a list of cells with exactly three neighbours:
pdl> p ($n == 3)
[
[0 0 1 0 0 0 0 0 0 0]
[0 0 1 0 0 0 0 0 0 0]
[0 1 0 1 0 0 0 0 0 0]
[0 0 0 0 0 0 0 0 0 0]
[0 0 0 0 0 0 0 0 0 0]
[0 0 0 0 0 0 0 0 0 0]
[0 0 0 0 0 0 0 0 0 0]
[0 0 0 0 0 0 0 0 0 0]
[0 0 0 0 0 0 0 0 0 0]
[0 0 0 0 0 0 0 0 0 0]
]
then get a list of empty cells that have exactly three neighbours:
pdl> p ($n == 3) * !$x
If a living cell has less than 2 or more than 3 neighbours, it dies. π
get a list of cells with exactly 2 or 3 neighbours:
pdl> p (($n == 2) + ($n == 3))
[
[0 1 1 1 0 0 0 0 0 0]
[0 0 1 1 1 0 0 0 0 0]
[0 1 0 1 1 0 0 0 0 0]
[0 0 0 1 0 0 0 0 0 0]
[0 0 0 0 0 0 0 0 0 0]
[0 0 0 0 0 0 0 0 0 0]
[0 0 0 0 0 0 0 0 0 0]
[0 0 0 0 0 0 0 0 0 0]
[0 0 0 0 0 0 0 0 0 0]
[0 0 0 0 0 0 0 0 0 0]
]
then get a list of living cells that have exactly 2 or 3 neighbours:
pdl> p (($n == 2) + ($n == 3)) * $x
putting it ALL together, the next generation is:
pdl> $x = ((($n == 2) + ($n == 3)) * $x) + (($n == 3) * !$x)
pdl> p $x
[
[0 0 1 0 0 0 0 0 0 0]
[0 0 1 1 0 0 0 0 0 0]
[0 1 0 1 0 0 0 0 0 0]
[0 0 0 0 0 0 0 0 0 0]
[0 0 0 0 0 0 0 0 0 0]
[0 0 0 0 0 0 0 0 0 0]
[0 0 0 0 0 0 0 0 0 0]
[0 0 0 0 0 0 0 0 0 0]
[0 0 0 0 0 0 0 0 0 0]
[0 0 0 0 0 0 0 0 0 0]
]
ate, honestly. π
β¨ Bonus feature: Graphics! β¨
if you have PDL::Graphics::TriD installed, you can make a graphical version of the program by changing literally just three lines:
#!/usr/bin/perl
use PDL;
use PDL::NiceSlice;
use PDL::Graphics::TriD;
my $x = zeroes(20,20);
# Put in a simple glider.
$x(1:3,1:3) .= pdl ( [1,1,1],
[0,0,1],
[0,1,0] );
my $n;
for (my $i = 0; $i < 100; $i++) {
# Calculate the number of neighbours per cell.
$n = $x->range(ndcoords($x)-1,3,"periodic")->reorder(2,3,0,1);
$n = $n->sumover->sumover - $x;
# Calculate the next generation.
$x = ((($n == 2) + ($n == 3))* $x) + (($n==3) * !$x);
# Display.
nokeeptwiddling3d();
imagrgb [$x];
}
but honestly? if we really want to see something iconic, we should make a few more changes:
- Start with a random collection of 1's and 0's.
- Make the grid larger.
- Add a small timeout so we can see the game evolve better.
- Use a while loop so that the program can run as long as it needs to.
#!/usr/bin/perl
use PDL;
use PDL::NiceSlice;
use PDL::Graphics::TriD;
use Time::HiRes qw(usleep);
my $x = random(100,100);
$x = ($x < 0.5);
my $n;
while (1) {
# Calculate the number of neighbours per cell.
$n = $x->range(ndcoords($x)-1,3,"periodic")->reorder(2,3,0,1);
$n = $n->sumover->sumover - $x;
# Calculate the next generation.
$x = ((($n == 2) + ($n == 3))* $x) + (($n==3) * !$x);
# Display.
nokeeptwiddling3d();
imagrgb [$x];
# Sleep for 0.1 seconds.
usleep(100000);
}
main character energy, truly. π
β¨ CONCLUSION: GENERAL STRATEGY β¨
the general strategy is: move the dimensions you want to operate on to the start of your ndarray's dimension list. then let PDL broadcast over the higher dimensions. that's it. that's the whole vibe. π
broadcasting is a powerful tool that helps eliminate for-loops and can make your code more concise. hopefully this tutorial has shown why it is worth getting to grips with broadcasting in PDL. periodt.
β¨ COPYRIGHT β¨
Copyright 2010 Matthew Kenworthy (kenworthy@strw.leidenuniv.nl) and Daniel Carrera (dcarrera@gmail.com). You can distribute and/or modify this document under the same terms as the current Perl license.
See: http://dev.perl.org/licenses/
and that's a wrap bestie!! π this was PDL::B...casting(3pm) from the User Contributed Perl Documentation, shipped with perl v5.42.3 on 2026-08-20 β go forth and broadcast, you absolute legend π¦β¨π
π¦ 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