Metadata-Version: 2.4
Name: openklic
Version: 0.1.0
Classifier: Development Status :: 4 - Beta
Classifier: Intended Audience :: Developers
Classifier: Intended Audience :: Science/Research
Classifier: Natural Language :: Dutch
Classifier: Natural Language :: English
Classifier: Operating System :: Microsoft :: Windows
Classifier: Operating System :: POSIX :: Linux
Classifier: Operating System :: MacOS
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3 :: Only
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Programming Language :: Python :: 3.14
Classifier: Programming Language :: Rust
Classifier: Topic :: Scientific/Engineering :: GIS
Classifier: Typing :: Typed
Summary: Reads a Kadaster KLIC levering (IMKL) into records as IMKL has them, fast and on your own machine.
Keywords: KLIC,IMKL,Kadaster,GML,WIBON,kabels en leidingen,GIS
Author: Ilya Gorbunov
License-Expression: MIT
Requires-Python: >=3.10
Description-Content-Type: text/markdown; charset=UTF-8; variant=GFM
Project-URL: Homepage, https://ilyagorb.github.io/openklic/
Project-URL: Issues, https://github.com/ilyagorb/openklic/issues
Project-URL: Repository, https://github.com/ilyagorb/openklic

# openklic

Reads a Kadaster **KLIC levering** (the zip you get after a graafmelding or oriëntatieverzoek)
into the records IMKL has, fast, on your own machine. Nothing is uploaded; nothing is fetched.

```python
import openklic

lev = openklic.read("Levering_99S0000001_1.zip")   # the zip, its unpacked folder, its bytes, or an open file
print(lev["report"]["imklVersion"], len(lev["features"]), "features")
```

It is the Python face of OpenKLIC's Rust engine, the same code that runs OpenKLIC's web page.
One wheel per platform serves every CPython from 3.10, ArcGIS Pro's 3.11 included.

## What you get

Every feature of the GML as IMKL has it, nothing renamed, joined or dropped:

```python
{"class": "Elektriciteitskabel", "id": "nl.imkl-KL1031.cable1",
 "properties": [
   {"name": "inNetwork", "href": "nl.imkl-KL1031.net1"},                              # a reference: a gml:id
   {"name": "link", "href": "nl.imkl-KL1031.ul1"},
   {"name": "currentStatus", "href": "http://inspire.ec.europa.eu/codelist/ConditionOfFacilityValue/functional"},
   {"name": "validFrom", "nil": "unknown"},                                            # xsi:nil, with its nilReason
   {"name": "nominalVoltage", "uom": "urn:ogc:def:uom:OGC::V", "text": "230"},         # text exactly as written
   {"name": "inspireId", "elements": [{"name": "Identifier", "elements": [...]}]}]}  # nested elements
```

Geometry is the one thing interpreted: GeoJSON-shaped, in the delivery's own RD New
coordinates (EPSG:28992, or 7415 with NAP heights), never reprojected:

```python
{"name": "centrelineGeometry",
 "geometry": {"type": "LineString", "coordinates": [[120010.0, 487010.0], [120020.5, 487015.25]], "epsg": 28992}}
```

The `report` says what the engine saw and what it did not keep: features per class, attributes
and elements not kept, geometries it could not read (`issues`, with the feature), references
to an id the levering does not hold (`unresolvedReferences`), ids held twice. A typical IMKL 2.0
levering has an empty report, but for `geometryRules`: the rules Kadaster checks netbeheerders'
geometry against, checked again, with how many geometries of which class break them (most
leveringen give no `srsDimension`, many EV areas run clockwise). Positions that cannot be what
the netbeheerder meant (outside the Netherlands, heights read as positions) are listed in
`doubtfulPositions`; they are kept as the levering gives them.

The full shape is typed in `openklic.types` (`Levering`, `Feature`, `Property`, `Shape`,
`Report`), so an editor completes it and a type checker checks it. It is a stable interface:
fields may be added, never renamed or removed without a new `format`.

## An example: every cable with its line and its owner

IMKL puts a cable's line on its `UtilityLink`s and its owner on the Belanghebbende of its
network. The engine leaves the joins to you, so that it never joins wrongly; they are short:

```python
import openklic

lev = openklic.read("Levering_99S0000001_1.zip")
by_id = openklic.index(lev)                                  # gml:id -> feature

def text(feature, *path):
    p = openklic.get(feature, *path)
    return p.get("text") if p else None

owner_of_net = {}                                            # Utiliteitsnet id -> netbeheerder
for bh in lev["features"]:
    if bh["class"] == "Belanghebbende":
        beheerder = by_id.get(openklic.get(bh, "netbeheerder")["href"])
        for net in openklic.get_all(bh, "utiliteitsnet"):
            owner_of_net[net["href"]] = text(beheerder, "organisatie", "Organisatie", "naam")

for cable in (f for f in lev["features"] if f["class"] == "Elektriciteitskabel"):
    lines = [by_id[l["href"]] for l in openklic.get_all(cable, "link") if l["href"] in by_id]
    shapes = [openklic.get(ul, "centrelineGeometry")["geometry"] for ul in lines]
    net = openklic.get(cable, "inNetwork")["href"]
    print(cable["id"], owner_of_net.get(net), [s["type"] for s in shapes])
```

A link that names no UtilityLink of the levering is listed in
`lev["report"]["unresolvedReferences"]`, so a missing line on a map can be explained.

## Files for QGIS, ArcGIS, CAD and GeoJSON

```python
openklic.geopackage("Levering_99S0000001_1.zip", "klic.gpkg")          # QGIS
openklic.arcgis(["a.zip", "b.zip", "c.zip"], "project_arcgis.zip")     # ArcGIS Pro
openklic.shapefile(zips, "klic_shapefile.zip")                         # shapefiles, styled for both
openklic.dxf(zips, "project.dxf")                                      # AutoCAD, BricsCAD
data = openklic.geojson(zips)                                          # bytes, without a path
```

Each takes one levering or a list of them and writes them into one file, in RD New as the
leveringen give it. The GeoPackage has a layer per IMKL class (a class with points and lines a
layer per kind, `Maatvoering_punt` and `Maatvoering_lijn`), each feature with the geometry a map
draws (a cable the lines of its UtilityLinks), its `levering`, thema, netbeheerder and status,
and every property as a column; the tables `netbeheerders` (per belang, whom to call),
`melding` (a row per levering), `utiliteitsnetten` (every net) and `documenten` (every letter,
precaution document and drawing, with whose it is, its net and its place in the levering; its
`pad` stays empty here, since only `documents(…, beside=…)` carries the files) come
with it, the layers and documents referring to their nets by foreign keys that QGIS discovers. QGIS draws it at once in the thema colours, with the
texts of annotations and dimensions. ArcGIS reads no style from a GeoPackage, so `arcgis` writes a
zip with the GeoPackage and a layer file (`.lyrx`) to drag into the map. The DXF is R2004, a layer
per thema and status, dashed by status; the GeoJSON names RD New in a `crs` member, as GDAL reads
it. Without a path each returns the file's bytes (for a web response, say).

`geopackage`, `arcgis`, `shapefile` and `dxf` take `style="clean"` (the default: the web page's look, lines in
their thema colour, a mantelbuis as a soft band, areas lightly filled) or `style="pmkl"`
(Kadaster's PMKL: a mantelbuis as two lines, EV areas hatched). On the command line, `--pmkl`.

## The documents' files

```python
openklic.documents(zips, "documenten.zip")                    # the files, organised
openklic.documents(zips, "klic.zip", beside="geopackage")     # the GeoPackage, a folder beside it
openklic.documents(zips, "klic.zip", beside="arcgis")         # the same for ArcGIS Pro
openklic.documents(zips, "los.zip", organised=False)          # where the levering has them
openklic.documents(zips, "apart.zip", apart=True)             # a folder per levering
```

The zip holds the netbeheerders' letters, precaution documents and drawings and the levering's
own files such as its overview PDF, each as the levering holds it. Organised, they lie per
netbeheerder, then `Eisen voorzorgsmaatregelen`, `Brieven en bijlagen` and a folder per net.
`LEESMIJ.txt` says how they are laid out and names what a levering refers to but does not hold.
Kadaster's `.kkv_` helpers and the XML are never in it. With `beside`, the GeoPackage's table
`documenten` says in `pad` where each file lies, seen from the GeoPackage. A levering may be given
as a zip, its bytes, or the folder it unpacked to. On the command line, `--documents-dir DIR`
writes `<name>_documenten.zip` (with `--together`, one zip of all).

## Errors

A levering that cannot be read at all raises `openklic.LeveringError`, a `ValueError` with a
stable `kind` to branch on (and word the message yourself): `zip`, `too_many_entries`,
`too_large_unpacked`, `suspicious_compression`, `no_delivery`, `too_large`, `not_utf8`, `xml`,
`io`. A hostile zip is refused before anything is unpacked; the limits can be tightened:

```python
try:
    lev = openklic.read(upload_bytes, max_unpacked_bytes=500 * 2**20)
except openklic.LeveringError as e:
    print(e.kind, e)
```

A file that is not well-formed XML is refused (`xml`) rather than read as far as it goes; a
single bad geometry is not: its feature is kept, and the issue is in the report.

## On a server

Reading and writing run with the interpreter released, so threads work side by side. A
file-like object (an upload stream) is read in binary mode. `openklic.read_json` gives the same
records as JSON text, for storing or forwarding without building Python objects.

## The command line

```text
python -m openklic Levering_99S0000001_1.zip          a summary: version, features, issues
python -m openklic --json Levering_99S0000001_1.zip   the records as JSON on stdout
python -m openklic --json-dir out/ leveringen/        one <name>.json per levering
python -m openklic --gpkg-dir out/ leveringen/        one <name>.gpkg per levering
python -m openklic --dxf-dir out/ --together leveringen/    all in one KLIC_<n>_leveringen.dxf
```

`--arcgis-dir`, `--shp-dir` and `--geojson-dir` work the same way.

## Speed

Over a corpus of 12 real leveringen (181 MB of GML, 146,019 features), on a laptop:
`openklic.read` hands over every record as Python objects in 1.8 seconds; the largest
levering (31 MB of GML) takes 0.36 s. `read_json` takes 1.5 s for the corpus. The objects are
built in Rust, which is faster than decoding JSON text in Python.

## Licence

MIT. Reading a levering does not change who may use it: a KLIC delivery is licensed to whoever
requested it.

