itacart.geometry.count_internal_cells
- itacart.geometry.count_internal_cells(polygon, resolution, n_jobs=1)[source]
Count the cells a polygon covers, without naming any of them.
Fast path over
polyfill()withcontainment="center": the count is accumulated during descent, so nothing is materialised and the call runs at resolution 13 where the index could not be built.Since every cell carries the same area, the count times
itacart.resolutions.nominal_cell_area()gives a distortion-free area, which is the property the paper builds tokenization on.Why the centre and not strict containment. Counting only the cells wholly inside undercounts by the ring of cells the outline crosses, about
perimeter * side / 2in area terms. For a square kilometre at resolution 7 that is two per cent. Under the centre rule the cells the outline crosses are kept or dropped according to which side their centre falls, and the two errors cancel to first order. The origin counts the same way.A centre on the outline.
containsis false on the outline, so a centre lying exactly on it would be counted by no polygon: not by this one, and not by its neighbour across the edge. For a polygon drawn through cell centroids that is every vertex and every lattice point along every edge – a square of 1 000 by 1 000 resolution-13 cells counted 998 001, its interior – and which centres landed exactly on the line, rather than a unit in the last place to either side of it, depended on the C library that computed the projection. So the point tested is the centre moved one micrometre east and ten nanometres north on the sinusoidal plane. A centre on an edge then lies on one side of it, and of two polygons sharing the edge exactly one counts it: west and south edges count the centres on them, east and north edges do not. Counts add up across a shared edge. A centre farther from the outline than the shift, about a micrometre, never changes side; one nearer than that can, tie or not, which is the second case below, and it is what a polygon whose vertices are not cell centres sees of the shift. On one Linux machine, against the rule without it, that moved the count of one of 160 random polygons at resolutions 6 to 10, by one cell, and of 34 of 39 at resolution 13, where a cell is a centimetre wide, by at most six cells in counts of up to two billion.The vertices drawn on the lattice. The shift settles a centre on the outline only if the outline is where it was drawn. A polygon drawn through cell centroids reaches the plane through the projection, whose last bits differ between C libraries by a few nanometres, and the shift itself puts some centres that close to an edge: a centre the shift’s own size from an edge lands on it. So before anything is tested, a projected vertex within a micrometre, in each coordinate, of a point of the five-millimetre plane grid is moved onto that point, and one within a micrometre of a prime-meridian triangle’s centroid, a third of a side above the triangle’s base, onto that centroid.
polyfill()does the same undercenter. The grid holds every corner and every centre of an ordinary cell at every resolution, so a polygon drawn through the centroids or the corners of any resolution’s cells is read as drawn, with the same numbers on every machine: the move uses only division, rounding to a whole number, multiplication and addition. A corner or centroid this package returns in degrees projects back at most 7.5 nanometres from its point, as measured, against the micrometre allowed. Not moved: the centroid of a cell absorbing the domain border or of a polar cap, which the geometry engine computes from the cell’s ring, and any vertex not drawn on the lattice, which includes a lattice vertex written with too few decimals: eleven decimals of a degree left one 1.6 micrometres off its point near the antemeridian, while twelve, or a float written out in full, keep every one within reach. A polygon the move makes invalid is refused, as any invalid polygon is, and not repaired.What the rule decides otherwise than the exact count. The exact count is that of the lattice points a polygon keeps when each is moved an infinitesimal distance in the shift’s direction. With the vertices on the lattice and no edge densified, the count departs from it in two cases only, and in both it is the same on every machine, because every number it compares is computed with the operations above, and compared by the geometry engine’s robust predicates, which answer one input one way. Measured on one Linux machine with Python 3.13, Shapely 2.2 and GEOS 3.14:
An edge along the shift. The shift points 1:100 north of east on the plane, and a centre on an edge running that way stays on it after the shift; its side is settled by the rounding of the shifted point, not by the rule. At 22 degrees of latitude, in three quadrants, on edges carrying nine lattice points between their ends, the count departed from the exact one by up to ten cells for edges within 0.053 degrees of that direction, and by none from 0.06 degrees on.
A centre nearer an edge than the shift. A centre that is not on the outline but nearer to it than the shift’s component across the edge, at most a micrometre, changes side; one exactly that far lands on the edge and is a near tie, decided by the arithmetic. On a polygon drawn through cell centroids that takes an edge whose direction on the lattice has no short step: edges of 130 to 500 m with no common factor in their steps moved the count by up to four cells each, and edges up to 80 m by none. On any other polygon it is the whole of what the shift changes, as measured above.
What still depends on the machine. Two things, and both are points the move does not reach:
An edge this function densifies. The polygon arrives in longitude and latitude, and an edge at least as long as the densification threshold – 505.1 m at resolution 13, one kilometre at the others – is read as a geodesic and gains points that are not on the lattice; near them the decision is the platform’s again. A polygon whose edges are straight on the plane is counted as drawn only while every edge stays below the threshold, and with a margin, because the length is computed with the C library too. On a square of 20 km at resolution 13, with the C library’s results moved by a unit in the last place to stand for four other platforms, a vertex every 400 m kept the count exact on all four, and the corners alone let it move by one cell on three.
A vertex not on the lattice. A vertex the move does not reach is where the projection puts it, give or take the last bits, and a centre that lands within a few nanometres of an edge through it is decided by them. Nothing makes that systematic, as a tie does, but at resolution 13 nothing makes it rare either: on average a centre lies within a nanometre of an edge once in fifty kilometres of outline. Of 39 random polygons of 100 to 400 m at resolution 13, with their coordinates moved by a unit in the last place to stand for six other platforms, two moved by one cell, on one or two of the six. The centroids of the border-absorbing cells and the polar caps are vertices of this kind.
What the residual error is, and what it is not. The count is exact for every cell the outline does not cross, so the area it implies can only be wrong about the crossed ones:
abs(n * a - A) / A <= P * s / Afor perimeterP, cell sidesand areaA. That bound is arithmetic and holds for every parcel.Where inside the bound a given parcel lands is not predictable. Measured over 24 phases at each of seven parcel sizes, three estimators of the scaling exponent disagree outright: 0.61 from the RMS, -0.47 from the median, 0.00 from the ninetieth percentile. There is no power law to fit, because the residual depends on how that outline happens to sit against that lattice.
This matters for how the resolution is chosen. It is not chosen from the parcel: in cadastral work it follows from the mapping scale and the positional tolerance the applicable standard attaches to it, and it is fixed before any parcel is measured. The parcel’s size and perimeter then determine the residual, which is an outcome to be reported against the bound above, not a target to refine toward.
Every family is counted. The last lattice column of a row, the polar row and the two caps are not the sheared square the closed form counts, so their trees are walked – ring by ring inside the family, in closed form wherever a branch leaves it – and the prime-meridian column is counted by a walk of its own. None of those walks stops at
MAX_FILL_CELLS. That ceiling keeps a fill from naming more cells than can be materialised, and a count names none: stopping there would return the running total at the moment of passing it as though it were the count.How the descent is evaluated. Level by level, in arrays. Every node of a level is asked the questions
_count_node()asks – does the geometry meet the square, does it contain it – with one Shapely call per question for up to_COUNT_BATCHsquares, instead of one call per square. The squares are the same floating-point squares, built with the same arithmetic in the same order, and the predicates are the same prepared predicates, so the count is the one the recursive descent returns. That descent is kept as_count_internal_cells_recursive(), the reference the tests hold this one to. What changed is the cost. The recursive descent spent about 9 microseconds on each node, nearly all of it in the interpreter, and the batched one spends about a quarter of a microsecond on the same nodes: 320 973 of them under a square kilometre at resolution 11, counted in 2.8 s by release 1.1.0 and in 0.074 s here. Serially, the same square at resolution 13 went from 34 s to 0.74 s, and a one-degree box at resolution 9 from 43 s to 1.25 s, 46 and 34 times faster, with the same counts. Measured on one Linux machine with two cores, Python 3.12, Shapely 2.2 and GEOS 3.14.The gain is the ordinary cells’. The walks of the last lattice column, the polar row, the caps and the prime-meridian column still descend one node at a time, as in release 1.1.0, and cost what they cost there:
box(10.0, 89.983, 10.5, 89.9835), a patch of the polar row, took 34 s at resolution 11 in either release, on the same machine.A leaf at the target resolution is decided by its centre alone (
_count_leaves()says why that is the same answer), unless the lattice piece is not a valid geometry; then the leaf is decided the way_count_node()decides it.Workers.
n_jobsabove 1 spreads the descent over processes, not threads. In release 1.1.0 two threads made the count slower than one – 4.1 times, for the one-degree box at resolution 7 on the machine above – because every scalar Shapely call handed the interpreter lock to the other thread. The descent runs in this process until its frontier holds a few hundred nodes per worker; the frontier is then dealt out in interleaved chunks. A count too small to repay starting the workers (_PARALLEL_MIN_NODES) never leaves this process. On two workers the one-degree box at resolution 9 took 0.73 s against 1.25 s on one.The workers are started by
spawnon every system, Linux included: a process forked from a parent with another thread alive – a notebook kernel, a server – can deadlock. So a script whose count reaches the workers needs theif __name__ == "__main__":guard on every system. Without it each worker runs the script again as it starts, and the count fails withconcurrent.futures.process.BrokenProcessPool. A notebook needs no guard. The count does not depend onn_jobs.Provenance:
itacart_core/cell_filling.py(polygon_to_cells_count).- Parameters:
- Return type:
- Returns:
Number of cells whose centre lies inside the polygon, a centre on the outline counted on the side the shift sends it to (see A centre on the outline).
- Raises:
AntemeridianError – If the polygon crosses 180 degrees outside an extension zone.
DomainError – If a position lies outside the latitude domain.
GeometryError – If the polygon is not a valid geometry; it is refused, not repaired. And from resolution 11, if the polygon reaches the cell that holds a pole at resolution 10, whose children cannot be enumerated: a known limitation, stated in
itacart.hierarchy.