If you are coding in Python and not using itertools you aren’t doing it right
Some neat coding tricks on the way to adding yet more options to weavingspace.
python
tiling
weavingspace
tutorial
stuff
Author
David O’Sullivan
Published
December 4, 2026
Code
%matplotlib inlineimport itertoolsimport geopandas as gpdimport matplotlib.pyplot as pltimport numpy as npimport shapely.geometry as geomimport shapely.affinity as affinefrom weavingspace import TileUnitletters ="abcdefghiklmnopqrstuvwxyz"
I’ve yet to start using AI to write code in earnest, although I will probably be making a start on that in the near future. The development of agentic coding has made me wonder about the value of posts like this that walk through how I’ve implemented some code to accomplish something geospatial, including code snippets, explanation, and related asides. Having said that, even if nobody else finds them useful, I find writing up an explanation of code I’ve written both a really useful way to lock in my understanding, and also helpful in the process of refining and cleaning things up. The posts also become useful additional documentation for the relevant
Given fair warning that this post is little more than a glorified note-to-self, please read on!
Some context
The weavingspace module, which I’ve written over the last couple of years enables you to make tiled maps of multivariate data.1 These are a novel way to map several variables associated with geographical areas in a single thematic map view. We have a paper coming out soon in Annals of the American Association of Geographers (co-authored with Luke Bergmann) which goes into more detail on the thinking behind the approach.
As things stand a big chunk of the Python code underpinning this work is in a single source file tiling_geometries.py which runs to many hundreds of lines and is used to setup an array of TileUnit objects of different kinds that store the repeating tile elements and translation vectors of the tiled patterns the mapping process makes use of. Lots of that code is a bit repetitive. When it comes to colourings of regular square tilings, the code looks (roughly) like this:
def _setup_square_colouring(unit):"""Set up colourings of a regular array of squares.""" s = unit.spacing / np.sqrt(unit.n)match unit.n: case ...: case ...:case5: squares = _get_square_colouring_squares([ (1,2), (0,1), (1,1), (2,1), (1,0)], s) _setup_vectors(unit, s, (1,2), (2,-1)) case ...:case _:return"That number of colours is not an option." unit.tiles = gpd.GeoDataFrame( data = {"tile_id": list(TILE_IDS)[:unit.n]}, crs = unit.crs, geometry = gpd.GeoSeries(squares))returnNone
The function _get_square_colouring_squares() makes square polygons with the indicated offsets, scaled by a factor s. The current code gives us this tiling:
Code
unit = TileUnit( tiling_type ="square-colouring", n =5).plot( r =2, r_alpha =0.8, show_vectors =True, show_ids =False, reg_prototile_edgecolour ="w", ).set_axis_off()
Figure 1: A 5-colouring of the square grid, as generated by the above code.
That might not seem too bad. A few lines of code for the 5-colouring, and it works fine. But there’s more to it than shown, with separate case statements for each of a range of requested numbers n of repeating elements in the pattern, each one individually hard-coded by hand. Although the code has been refined over time so that adding more options isn’t too difficult, it still requires sitting down with a notebook—preferably one with gridded pages—figuring out an arrangement of tiles, and (trickier) figuring out the translation vectors that enable that arrangement to tile the plane. And whatever arrangement of tiles I hard-code, you’re stuck with. There are, as we’ll see other possible arrangements of five squares than the one that I (in my wisdom) have hard-coded!
A more general solution would be nice. I’ve found one, and that’s what this post is about. Along the way, there are a few uses of itertools functions which I’ve become increasingly comfortable using lately, and some (I hope) interesting ideas about polyominoes.
Polyominoes
A polyomino is a configuration of squares arranged edge-to-edge to form a larger polygon and named as suchfollowing the usage domino. Triominos are composed of three squares, tetrominos of four, pentominoes of five, hexominoes of six, and so on.2
The number of polyominoes of any given size is one of those things mathematicians like to figure out. The numbers get big quickly. If we allow holes, and don’t consider reflected and rotated matching polyominoes the same, they get big really quickly. For example, according to the Online Encyclopedia of Integer Sequences, there are 22,964,779,660 possible 20-ominoes—almost 23 billion!3 Even if If we are a bit pickier and insist that the shapes have no holes, and consider rotated and reflected copies to be the same, then there are a mere 2 billion or so possibilities.4
Making a polyomino
So first things first, let’s make a polyomino. The function below does this using numpy’s where method and simple shapely unit squares.
The polyomino is formed from a union of the squares specified in the 2D array supplied as a pattern, where 0 values indicate a missing square, and any integer value indicates a square in the corresponding position. Normally, I would be nervous about the union_all() operation, but working with integer coordinates, I’m optimistic that no floating point gremlins will mess up the geometry.
The function returns both a polyomino and the squares from which it is formed. We’ll need these later, but it’s also helpful for simple visualization of the resulting shapes, like the five different pentominos below. Any of these (well… all but one of them) could form the basis for a repeating 5-colouring of squares.
Figure 2: Example polyominoes generated from the patterns supplied. One of these polyominoes is not like the others…
Figuring out if a polyomino tiles
Following close behind enumerating how many polyominoes of any given size exist, mathematicians are also interested in whether a given polyomino can tile the plane. In fact, more often than not, mathematicians are interested in the question can this shape (say a large rectangle) be tiled using this set of polyominoes?
One reason for this interest (beyond the puzzle of it) is that tiling can often be helpful in establishing seemingly complicated results. Can a checkerboard with two diagonally opposite corners be tiled by 2×1 dominoes? This is the mutilated chessboard problem. Perhaps it is obvious the answer is no. One way to see this quickly is that every domino must cover one dark and one light space. Since the two missing corners are both light, there are 32 dark squares, but only 30 light ones, and so no tiling is possible.
Code
board, spaces = get_polyomino([[1] *8for i inrange(8)])checkerboard = gpd.GeoDataFrame( geometry = gpd.GeoSeries(spaces), data = {"bw": [(r %2+ c %2) %2for r inrange(8) for c inrange(8)]})checkerboard_2 = checkerboard.iloc[1:63, :]fig = plt.figure(figsize = (5, 5))ax = fig.add_subplot(111)checkerboard_2.plot(ax = ax, column ="bw", cmap ="tab10")ax.set_axis_off()
Figure 3: A checkerboard with two corners missing.
More complicated combinatorial problems of various kinds can be simplified in similar ways. Polyomino tiling mathematics also finds application in the design of integrated circuits, and memory allocation and task parallelisation in computer science.
Here we are interested only in whether or not a given polyomino can tile the plane (without reflection or rotation, i.e., by translations only), not as an end in itself, but as a way to design arbitrary regular colourings of a grid. If we assign a different colour to each square in an n-omino, then a tiling of that n-omino will allows for n distinct positions in the grid pattern to be distinguished and used to symbolise map data.
Figuring out if a polyomino tiles is not difficult, and relies on a pleasingly different approach than a lot of the other machinery in weavingspace, which is heavily dependent on floating point and geometry operations. The idea is that we encode the polyomino as a sequence of directions around its boundary, which we call a boundary word. Since this is a geographical blog, label the directions N, S, E, and W. Then a unit square, going clockwise, would be NESW. A more convoluted example such as the cross pentomino is WNWNENESWSWS.
Code
cross = polyominoes[0]outline = geom.LineString(cross.exterior.coords)pts = [outline.interpolate(x, normalized =True) for x in [x /24for x inrange(1, 25, 2)]]ax = gpd.GeoSeries([cross]).plot(fc ="lightgrey")for p, s inzip(pts, "WNWNENESWSWS"): ax.annotate(s, (p.x, p.y), ha ="center", va ="center", fontsize =12)ax.set_axis_off()
Figure 4: Sequence of edge labels around the boundary of a polyominon, going clockwise.
The gist of the tileability checking idea is set out clearly by Andrew Winslow,5 who sadly then goes on to present a highly efficient algorithm in a ridiculously dense and completely impenetrable manner. Maybe you had to be there. The idea is to find a Beauquier-Nivat (BN) factorisation6 of the boundary word. A BN factorisation, breaks the sequence up into either 4 or 6 subsequences, ABA′B′ or ABCA′B′C′.7
By X′ I mean the inverse of X, which is most easily explained by an example. If X is WNEN then X′ would be SWSE, that is, the original sequence reversed both in order, and in direction, so WNEN → NENW (reversed) → SWSE (each step reversed).
The factorisation, if one can be found, is identifying paired subsections of the polyomino’s boundary, either two pairs of them, or three pairs of them. In the former case the polyomino will tile like a square; in the latter case like a hexagon. Again, consider the cross polyomino. We can factorise it like this: NWN|ENE|SWS|WSW. Since SWS is (NEN)′ and WSW is (ENE)′ this satisfies the criteria. It’s important to note here that to find this factorisation the boundary word has been cycled one position forward from the form given above. The boundary is a cycle, and so is the code: we can start anywhere along it, looping back to the start at the end, to find the factorisation. Illustrated, this looks this:
Code
corners =list(outline.coords)A = gpd.GeoSeries([geom.LineString(corners[1:5])])B = gpd.GeoSeries([geom.LineString(corners[4:8])])Ap = gpd.GeoSeries([geom.LineString(corners[7:11])])Bp = gpd.GeoSeries([geom.LineString(corners[10:] + corners[:2])])ax = gpd.GeoSeries([cross]).plot(fc ="lightgrey")A.plot(ax = ax, color ="r")B.plot(ax = ax, color ="b")Ap.plot(ax = ax, color ="r")Bp.plot(ax = ax, color ="b")for p, s inzip([pts[i] for i in (2, 5, 8, 11)], ("NWN", "ENE", "SES", "WSW")): ax.annotate(s, (p.x, p.y), ha ="center", va ="center", fontsize =12)ax.set_axis_off()
Figure 5: A BN-factorisation of the boundary of the cross polyomino. Matching factors are shown in matching colours.
The figure shows how matching segments of the polyomino boundary like this can establish its tileability. Clearly this is not a proof, but proof is for mathematicians.8
As I’ve noted, neither of the papers I’ve referenced help much with a clearly set out algorithm, or sample code. What follows is my solution, given these essential insights.
A working solution
What follows is not optimised. I don’t expect to be running this code on large polyominoes, nor on many of them at a time, so I’m not too concerned about that. If I could decipher the Winslow paper mentioned above, I would implement that, but what I’ve written seems fine for the problems at hand.
First up, we have build a boundary word for the polyomino:
Code
def get_boundary_word(poly): result = []for xy0, xy1 in itertools.pairwise(poly.exterior.coords): dxy = xy1[0] - xy0[0], xy1[1] - xy0[1] result.append(0if dxy[0] ==1else1if dxy[1] ==1else2if dxy[0] ==-1else3)return result
[2, 1, 2, 1, 0, 1, 0, 3, 0, 3, 2, 3]
In get_boundary_word() the direction encoding is E = 0, N = 1, S = 2, W = 3. Numbers are generally less fiddly to deal with than letters. Initially when I implemented this, I used complex numbers and did
but in debugging, it proved really difficult to deciphers lists of complex numbers, so I simplified to integers. Notable in this function is itertools.pairwise which makes it easy to step through a sequence by pairs. So
for a, b in itertools.pairwise([1, 2, 3, 4]):
...
will yield (1, 2), then (2, 3), then (3, 4). This is ideal for stepping through the coordinates of the polyomino exterior. pairwise is more or less equivalent to
for a, b in zip(my_list[:-1], my_list[1:]):
...
but a lot less fiddle. In this context, it’s convenient that shapely repeats the first coordinate of the polygon boundary at the end of the exterior.coords sequence.
So, just to confirm, we now have a boundary word:
Code
get_boundary_word(cross)
So we’ve got a boundary word. Next we need a list of all the possible factor partitioning patterns that might be applied to this word.
Code
def get_factor_lengths(n):return ([x[::-1] for x in itertools.product(*([range(1, n)] *2))ifsum(x) == n] + [x[::-1] for x in itertools.product(*([range(1, n-1)] *3))ifsum(x) == n])get_factor_lengths(4)
In get_factor_lengths() another itertools function, product comes in handy. Like pairwise this replaces a familiar looping pattern, so that
for pair in itertools.product(list1, list2):
...
is equivalent to
for x in list1:
for y in list2:
pair = (x, y)
...
product is quicker, and also more flexible, if we want all the combinations of more than two lists, we just add another list to the arguments of the function call. In get_factor_lengths I use this to collate all possible sets of subsequence lengths that we need to check for factorisations of the boundary word.
A couple of notes:
I think it makes sense to check factorisations that start with longer factors first, because those are more likely to defeat a candidate factorisation, hence the [::-1] inversion of the factor length lists, which by default are ordered based on the inputs to the product function call.
I include the four-factor solutions (i.e., the pairs, not triples) first, because any tileable polyomino should should admit a two translation vector option. That said, tiling is a slippery business, so I can easily believe that’s not always true, and that there is some rogue polyomino out there ready to trip me up. Even so, checking two translation vector cases first seems to make sense.
Checking a factorisation requires confirming that a factor and its corresponding factor in the other half of the boundary word are mutually inverse. That’s easy enough, and with the chosen encoding, the test is that the ‘letters’ in the two words differ by 2:
Code
def is_inverse(x, y):returnall(abs(a - b) ==2for a, b inzip(x, y[::-1]))is_inverse([0, 1, 2, 3], [1, 0, 3, 2])
True
Finally, some more helpers: one for partioning a list into sublists at a sequence of breaks (again using itertools.pairwise); another to ‘cycle’ a list by some offset—keeping in mind that the boundary word is cyclic, so we may need to step through it as such; and one to split an even length list at its midpoint. Here those all are:
Code
def get_sublists(L, breaks):return [L[i:j] for i, j in itertools.pairwise([0, *breaks])]def cycle_list(L, offset):return [*L[offset:], *L[:offset]]def get_list_halves(L):return get_sublists(L, [len(L) //2, len(L)])
And here they are in action:
Code
get_sublists([21, 22, 23, 24, 25], [2, 4, 5])
[[21, 22], [23, 24], [25]]
Code
cycle_list([1, 2, 3, 4], 2)
[3, 4, 1, 2]
Code
get_list_halves([1, 2, 3, 4, 5, 6])
[[1, 2, 3], [4, 5, 6]]
Putting (most of) it all together
I’ve pulled the code I’ve written apart a little here to make it easier to explain, which is my excuse for some ugliness in the return values of functions, specifically the is_polygon_tileable function below, which either returns None if the supplied polyomino is not tileable, or, if it is, returns some results that can be used to get the translation vectors.
Going through this function, first, we get the boundary word of the polygon, and the set of all possible factor length combinations to compare in each half of the boundary word. We only need the possible lengths associated with sequences half the length of the boundary, since we’re looking for ABCA′B′C′. For each set of factor lengths at the current offset position in the boundary word, we check if is_inverse is True for corresponding pairs of factors. As soon as we find a case where this is true for all factors, we return the current offset, lengths and breaks.
If we get to the end of all possible factor lengths, at all possible boundary word offsets, then the polyomino doesn’t tile and we return None.
Another useful itertools function appears here: accumulate which returns the cumulative sum of a series of values. This turns a series of factor lengths into a series of break points, as required by get_sublists(). It is rouhgly equivalent to the rather ugly
cumulative = [sum(L[:i]) for i in range(1, len(L) + 1)]
and has options that allow for it to apply some other function than summation as it iterates through the list.
Anyway, now we can check if the cross polyomino tiles:
Code
is_polyomino_tileable(cross)
(0, (3, 3), [3, 6])
Getting a result confirms that it does. Meanwhile, the ‘four’ shape, does not.
Code
is_polyomino_tileable(polyominoes[4]) isNone
True
To get a response here I’ve appended is None to the function call, otherwise, we would get None, which in Python would mean we’d see nothing.
Like I said, this code is not efficient. I am almost certain that failed checks early in the looping could rule out the need for other checks later, and there’s some cunning way to keep track of that. I expect that’s what Winslow’s impenetrable paper is about. I don’t mind the inefficiency for small problems, and as a wise man said, “premature optimisation is the root of all evil in programming.”9 Time will tell if I need to make the code quicker. Somewhat ironically, if I do, my first port of call might be this impenetrable algorithm.
Getting the translation vectors
Now we can check for tileability, but what we really want are the translation vectors.
This turned out to be the fiddliest bit to get right. Given the offset from the start of the boundary code when the factorisation was found, we know where on the perimeter of the polyomino to start, and the vectors we need are derived from the polyomino’s boundary points in positions corresponding to the breaks that formed the factorisation.
The wrinkle that tripped me up is that the break positions are at the end of the corresponding sequence of line segments in the first half of the boundary, but at the start of them in the second half, because in the second half, we are traversing the line segments in reverse. That means that rather than jumping forward half the length of the boundary word, we jump forward half and drop back by the length of the current segment, as stored in lengths.
This gives us matched locations on the boundary and the differences between them give us the vectors we are after.
In cases that don’t tile, where test_result is None, we return vectors that correspond to the width and height of the polyomino’s bounding box, which seems a reasonable fall back.
Tiling polyominoes
All this code is to be integrated into weavingspace where the tile shapes are bundled together with their translation vectors, and there is a bunch of pre-existing code for displaying and manipulating the results (and making maps). Without getting into the nitty gritty (click into the code cell if you must) it’s relatively simple to turn the results from the code above into a weavingspaceTileUnit object.
Code
def get_square_colouring_tile_unit(xys): unit = TileUnit() poly, squares = get_polyomino(xys) ids = [x for x in itertools.chain.from_iterable(xys) if x] vecs = get_translation_vectors(poly) unit.tiles = gpd.GeoDataFrame( geometry = gpd.GeoSeries(squares), data = {"tile_id": [letters[i-1] for i in ids]}) unit.tiles = unit.tiles.dissolve(by ="tile_id", as_index =False) bb = unit.tiles.geometry.total_bounds cxy = (bb[0] + bb[2]) /2, (bb[1] + bb[3]) /2 sf = unit.spacing / (len(squares) **0.5) unit.tiles.geometry = (unit.tiles.geometry .translate(-cxy[0], -cxy[1]) .scale(sf, sf, origin = (0, 0))) unit.setup_vectors(tuple(sf * x for x in vecs[0]),tuple(sf * x for x in vecs[1])) unit.prototile = unit.get_prototile_from_vectors() unit._setup_regularised_prototile(override =True)return unit
For this post, it’s handy to make a function to plot the resulting tilings, again using pre-existing weavingspace functionality.
Using this on the first four patterns from the start of this post, we get tiled polyominoes!
Code
tileable_patterns = [p for i, p inenumerate(patterns) if i !=2]fig, axes = plt.subplots(2, 2, figsize = (9, 12), height_ratios = (3, 5), width_ratios = (3, 3), layout ="constrained")for i, p inenumerate(patterns[:-1]): r, c = i //2, i %2 plot_polyomino_tiling(axes[r, c], p, fc ="lightgrey", ec ="k", lw =0.75)
Figure 6: The four patterns from the top whose polyominoes tile.
Figure 7: The non-tileable ‘four’ polyomino, repeated based on its bounding box.
Wait a minute, wasn’t this about colourings?!
Well, yes it was. If instead of supplying a simple binary pattern to get_square_colouring_tile_unit() we number the non-empty spaces in the pattern, then we get a colouring.
At the moment, because the code just yields the first factorisation it happens to come across, other possible ways to tile the polyomino are not offered. That’s a possible refinement for future work. Just to reinforce the point, the figure below, produced using Inkscape not code, shows the tiling the code did find, and another one it might have found (which happens to produce the same arrangement of colours as the cross tiling).
Figure 10: Two possible tilings with the same pentomino.
The get_square_colouring_tile_unit() function also ‘dissolves’ any matching values in the supplied pattern, so we can get up to all kinds of tricks.
Figure 11: You can make all kinds of patterns with this approach.
Looks like I’ve sort of reinvented ASCII art. More to the point, with this addition, weavingspace can support arbitrary colourings of the square lattice without the need to hard-code any more patterns.
Like the also experimental regular tilings in my previous post it’s not 100% clear anyone will find a use for the huge range of options opened up by this addition to weavingspace. Regardless, I had fun building it. Let a thousand flowers bloom. A graph paper notebook is still likely to come in handy.
Figure 13: One level of the classic triomino rep-tile pattern.
Postscript: on itertools
The code covered in this post makes use of the itertools functions accumulate, pairwise, product, and (quietly in the function for making a TileUnit) chain.chain_from_iterable and they all played a part. Any of them could have been replaced with not overly complicated bespoke loops, but the itertools seems a better way to go. The problem tackled here likely isn’t big enough for the performance advantages to manifest, but even without that benefit, it’s nice not to have to write inefficient reimplementations of such core functionality.
One thing to watch out for is that in general these functions don’t return actual lists until you unpack them, or convert them explicitly. So for example, if you do
Code
itertools.pairwise(range(5))
<itertools.pairwise at 0x114a3b3a0>
you get an iterator, not the list you might expect. If you need to access the contents, then list() will convert the iterator to an actual list:
Code
list(itertools.pairwise(range(5)))
[(0, 1), (1, 2), (2, 3), (3, 4)]
or perhaps more likely, you will iterate over the items
Code
for x, y in itertools.pairwise(range(5)):print(f"{x=}{y=}")
x=0 y=1
x=1 y=2
x=2 y=3
x=3 y=4
From time to time that leads to errors where the code, or, more accurately, the programmer, assumes they’re dealing with actual data, but is actually dealing with an iterator (or in other cases a generator). Like most things in code, you get used to that after a while. In short familiarising yourself with itertools is well worth the time. If nothing else, it will give you a better shot at understanding the code your AI assistant is writing.
Footnotes
This paper explains what that means in more detail.↩︎
At some point we run out of Greek and Latin and call them n-ominoes.↩︎
You can start to see how QR codes are such a compact way to store information…↩︎
2,269,506,062 to be precise. See A000104. This is a number more relevant to QR codes.↩︎
Winslow, A. 2015. An optimal algorithm for tiling the plane with a translated polyomino. In Algorithms and Computation, K Elbassioni, K Makino (eds.). Springer Berlin Heidelberg. doi: 10.1007/978-3-662-48971-0_1↩︎
Beauquier D and M Nivat. 1991. On translating one polyomino to tile the plane. Discrete & Computational Geometry6(4) 575–592. doi: 10.1007/BF02574705. This paper presents an overly elaborate algorithm for establishing tileability. Factorising the boundary word seems to me to be sufficient.↩︎
I am radically simplifying the notation here, because I am not planning to prove anything. If you are a fan of mathematical notation see the Winslow paper.↩︎
It was Donald Knuth who said it. The full quote is “We should forget about small efficiencies, say about 97% of the time: premature optimization is the root of all evil”, on page 268 in Knuth DE. 1974. Structured Programming with go to Statements. ACM Computing Surveys6(4) 261–301. doi:10.1145/356635.356640. This page explains why he said it.↩︎