DEV Community

Kapil Singhal
Kapil Singhal

Posted on

Your Polygon Says 2.3 Hectares, the Approval Says 4: Checking Afforestation Plot Areas in Python

Every afforestation site I have worked with eventually produces the same argument. The approval says a plot is 4 hectares. The polygon someone drew says something else. Sometimes the polygon is right and the paperwork is old. More often the polygon is wrong in one of three boring ways: the area was computed in degrees, the boundary crosses itself, or two plots claim the same ground.

All three are easy to catch in code before the file goes into a site register, and very hard to explain once a reviewer finds them. This post is the check I run, in about 40 lines of Python with pyproj and shapely.

Why this matters for compensatory afforestation

Compensatory afforestation is planting done in return for forest land diverted to non-forest use, so the area is fixed by an approval rather than chosen by the planter. Every later number (saplings per hectare, survival, cost per hectare) is divided by that area. If the polygon is off by 40%, so is everything computed from it. The record-keeping side of this, including what CAMPA plantation records should hold, is in our note on the CAMPA plantation guidelines. Here I only deal with the geometry.

The test file

To keep this reproducible, I generate a small KML with three made-up plots near 21.25° N, 81.63° E:

  • CA-01: a 316 m × 316 m square, about 10 ha.
  • CA-02: a 200 m × 250 m plot that was drawn 16 m too far west, so it overlaps CA-01.
  • CA-03: a "rectangle" whose vertices were entered in the wrong order, so the ring crosses itself (a bow-tie).

Field teams produce all three of these, usually from a phone app or a hurried digitising session.

Mistake 1: area in square degrees

Shapely is a planar geometry library. Feed it longitude and latitude and polygon.area returns square degrees, which is not an area anyone can use. A degree of longitude is about 103.8 km at 21° N and about 111 km at the equator, so you cannot multiply your way out of it with one constant either.

The fix is to compute the area on the ellipsoid. pyproj.Geod.geometry_area_perimeter does that directly on a shapely geometry in lon/lat (pyproj Geod docs). It returns a signed area (the sign depends on ring orientation), so take the absolute value.

Mistake 2: a ring that crosses itself

A bow-tie polygon is invalid. Shapely will still give you a number for it, and that number is meaningless because the two lobes have opposite orientation and partly cancel. Check is_valid first and print the reason (is_valid_reason). make_valid will split a bow-tie into two triangles (make_valid), which is a correct geometry for the ring you drew, but probably not the plot you meant. Treat it as a flag for a field re-walk, not a fix.

Mistake 3: two plots claiming the same ground

Overlaps double-count planted area and, later, trees. A pairwise intersection over every plot is fine for a few hundred plots. For thousands, put them in an STRtree first.

The code

import xml.etree.ElementTree as ET
from itertools import combinations
from pyproj import Geod
from shapely.geometry import Polygon
from shapely.validation import explain_validity, make_valid

NS = {"k": "http://www.opengis.net/kml/2.2"}
geod = Geod(ellps="WGS84")

def read_kml(path):
    plots = {}
    for pm in ET.parse(path).getroot().iterfind(".//k:Placemark", NS):
        name = pm.findtext("k:name", namespaces=NS)
        text = pm.find(".//k:outerBoundaryIs//k:coordinates", NS).text
        coords = [tuple(map(float, c.split(",")[:2])) for c in text.split()]
        plots[name] = Polygon(coords)  # (lon, lat) order, as KML stores it
    return plots

def hectares(geom):
    area, _ = geod.geometry_area_perimeter(geom)
    return abs(area) / 10_000

plots = read_kml("plots.kml")
sanctioned = {"CA-01": 10.0, "CA-02": 5.0, "CA-03": 4.0}

for name, poly in plots.items():
    if not poly.is_valid:
        print(f"{name}: INVALID ({explain_validity(poly)})")
        poly = make_valid(poly)
        plots[name] = poly
    ha = hectares(poly)
    naive = poly.area  # square degrees: meaningless as an area
    gap = (ha - sanctioned[name]) / sanctioned[name] * 100
    print(f"{name}: {ha:.2f} ha geodesic | {naive:.6f} deg2 planar | {gap:+.1f}% vs sanctioned")

for (a, pa), (b, pb) in combinations(plots.items(), 2):
    inter = pa.intersection(pb)
    if not inter.is_empty and inter.area > 0:
        print(f"OVERLAP {a} x {b}: {hectares(inter):.2f} ha")
Enter fullscreen mode Exit fullscreen mode

KML stores coordinates as longitude, latitude, altitude (KML reference). Getting that order backwards is a fourth classic mistake; with these coordinates the plots would land near the Arctic, which at least fails loudly.

The output

CA-01: 10.00 ha geodesic | 0.000009 deg2 planar | +0.0% vs sanctioned
CA-02: 5.01 ha geodesic | 0.000004 deg2 planar | +0.2% vs sanctioned
CA-03: INVALID (Self-intersection[81.641 21.251])
CA-03: 2.30 ha geodesic | 0.000002 deg2 planar | -42.5% vs sanctioned
OVERLAP CA-01 x CA-02: 0.40 ha
Enter fullscreen mode Exit fullscreen mode

Three things to notice. The square-degree numbers are useless, as expected. CA-02 matches its approval on its own, yet 0.40 ha of it is also counted inside CA-01, so the site total is overstated even though every plot looks fine alone. CA-03 is the dangerous one: the boundary someone meant was roughly 4.6 ha, but the ring as drawn encloses 2.3 ha. Neither number should go into a register until someone walks the corners again.

What I do with the result

  • Block the record, do not auto-correct it. An invalid ring or an overlap goes back to the field team with the plot ID and the printed reason.
  • Set a tolerance and write it down. A few per cent difference from the approved area can come from GPS error at the corners. Agree the number before the first site, not after an argument.
  • Keep both numbers. Store the approved area and the computed geodesic area side by side, with the date and method of the computation. Divide survival and density by the approved area only when the two agree within tolerance.
  • Re-run on every edit. Boundaries get redrawn after a monsoon washes out a corner. The check is cheap; run it on every version.

This is the same discipline we apply in Aranyix, where plot boundaries, planting records and resurveys share one ID so that areas, counts and survival can be traced back to the same polygon. The geometry check is the foundation. Nothing downstream is worth more than the polygon it is divided by.

If you have plantation KML that breaks this script in a new way, I would like to see the failure.


Aranyix: https://aranyix.tech

Axentis Technologies: https://axentis.tech

Aranyix on LinkedIn: https://www.linkedin.com/showcase/aranyix/

Axentis Technologies on LinkedIn: https://www.linkedin.com/company/axentis-technologies

Kapil Singhal, Director, Axentis Technologies

Top comments (1)

Collapse
 
userxnom profile image
Abdullah Naseer •

Kapil, the line that earned the comment is "Block the record, do not auto-correct it" — make_valid splitting a bow-tie into two triangles is a correct geometry for the ring you drew, but probably not the plot you meant, and silently "fixing" it would bury the real error. That discipline — send it back to the field team with the plot ID and the printed reason — is the part most checklists skip.

The square-degrees trap is the one I would underline for anyone new to geospatial code: Shapely still gives you a number for a bow-tie, and it still gives you an area in square degrees — both look like answers, and neither is one. The 0.000009 deg² figure next to 10.00 ha makes that point better than any warning could.

One question on your tolerance rule: you say a few per cent difference from the approved area can come from GPS error at the corners, and to agree the number with the certifier. In practice, is that tolerance a fixed percentage, or does it scale with plot size — a few metres of GPS error is a bigger share of a 0.5 ha plot than of a 10 ha one?